source: rtems-libbsd/freebsd/sys/kern/sys_generic.c @ 3c967ca

55-freebsd-126-freebsd-12
Last change on this file since 3c967ca was 3c967ca, checked in by Sebastian Huber <sebastian.huber@…>, on 06/08/17 at 11:15:12

Use <sys/lock.h> provided by Newlib

  • Property mode set to 100644
File size: 45.4 KB
Line 
1#include <machine/rtems-bsd-kernel-space.h>
2
3/*-
4 * Copyright (c) 1982, 1986, 1989, 1993
5 *      The Regents of the University of California.  All rights reserved.
6 * (c) UNIX System Laboratories, Inc.
7 * All or some portions of this file are derived from material licensed
8 * to the University of California by American Telephone and Telegraph
9 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10 * the permission of UNIX System Laboratories, Inc.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 *    notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 *    notice, this list of conditions and the following disclaimer in the
19 *    documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 *    may be used to endorse or promote products derived from this software
22 *    without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 *
36 *      @(#)sys_generic.c       8.5 (Berkeley) 1/21/94
37 */
38
39#include <sys/cdefs.h>
40__FBSDID("$FreeBSD$");
41
42#include <rtems/bsd/local/opt_capsicum.h>
43#include <rtems/bsd/local/opt_compat.h>
44#include <rtems/bsd/local/opt_ktrace.h>
45
46#include <sys/param.h>
47#include <sys/systm.h>
48#include <sys/sysproto.h>
49#include <sys/capsicum.h>
50#include <sys/filedesc.h>
51#include <sys/filio.h>
52#include <sys/fcntl.h>
53#include <sys/file.h>
54#include <sys/lock.h>
55#include <sys/proc.h>
56#include <sys/signalvar.h>
57#include <sys/socketvar.h>
58#include <sys/uio.h>
59#include <sys/kernel.h>
60#include <sys/ktr.h>
61#include <sys/limits.h>
62#include <sys/malloc.h>
63#include <sys/poll.h>
64#include <sys/resourcevar.h>
65#include <sys/selinfo.h>
66#include <sys/sleepqueue.h>
67#include <sys/syscallsubr.h>
68#include <sys/sysctl.h>
69#include <sys/sysent.h>
70#include <sys/vnode.h>
71#include <sys/bio.h>
72#include <sys/buf.h>
73#include <sys/condvar.h>
74#ifdef KTRACE
75#include <sys/ktrace.h>
76#endif
77
78#include <security/audit/audit.h>
79#ifdef __rtems__
80#include <machine/rtems-bsd-syscall-api.h>
81#endif /* __rtems__ */
82
83/*
84 * The following macro defines how many bytes will be allocated from
85 * the stack instead of memory allocated when passing the IOCTL data
86 * structures from userspace and to the kernel. Some IOCTLs having
87 * small data structures are used very frequently and this small
88 * buffer on the stack gives a significant speedup improvement for
89 * those requests. The value of this define should be greater or equal
90 * to 64 bytes and should also be power of two. The data structure is
91 * currently hard-aligned to a 8-byte boundary on the stack. This
92 * should currently be sufficient for all supported platforms.
93 */
94#define SYS_IOCTL_SMALL_SIZE    128     /* bytes */
95#define SYS_IOCTL_SMALL_ALIGN   8       /* bytes */
96
97#ifndef __rtems__
98#ifdef __LP64__
99static int iosize_max_clamp = 0;
100SYSCTL_INT(_debug, OID_AUTO, iosize_max_clamp, CTLFLAG_RW,
101    &iosize_max_clamp, 0, "Clamp max i/o size to INT_MAX");
102static int devfs_iosize_max_clamp = 1;
103SYSCTL_INT(_debug, OID_AUTO, devfs_iosize_max_clamp, CTLFLAG_RW,
104    &devfs_iosize_max_clamp, 0, "Clamp max i/o size to INT_MAX for devices");
105#endif
106
107/*
108 * Assert that the return value of read(2) and write(2) syscalls fits
109 * into a register.  If not, an architecture will need to provide the
110 * usermode wrappers to reconstruct the result.
111 */
112CTASSERT(sizeof(register_t) >= sizeof(size_t));
113
114static MALLOC_DEFINE(M_IOCTLOPS, "ioctlops", "ioctl data buffer");
115#endif /* __rtems__ */
116static MALLOC_DEFINE(M_SELECT, "select", "select() buffer");
117#ifndef __rtems__
118MALLOC_DEFINE(M_IOV, "iov", "large iov's");
119#endif /* __rtems__ */
120
121static int      pollout(struct thread *, struct pollfd *, struct pollfd *,
122                    u_int);
123static int      pollscan(struct thread *, struct pollfd *, u_int);
124static int      pollrescan(struct thread *);
125static int      selscan(struct thread *, fd_mask **, fd_mask **, int);
126static int      selrescan(struct thread *, fd_mask **, fd_mask **);
127static void     selfdalloc(struct thread *, void *);
128static void     selfdfree(struct seltd *, struct selfd *);
129#ifndef __rtems__
130static int      dofileread(struct thread *, int, struct file *, struct uio *,
131                    off_t, int);
132static int      dofilewrite(struct thread *, int, struct file *, struct uio *,
133                    off_t, int);
134#endif /* __rtems__ */
135static void     doselwakeup(struct selinfo *, int);
136static void     seltdinit(struct thread *);
137static int      seltdwait(struct thread *, sbintime_t, sbintime_t);
138static void     seltdclear(struct thread *);
139
140/*
141 * One seltd per-thread allocated on demand as needed.
142 *
143 *      t - protected by st_mtx
144 *      k - Only accessed by curthread or read-only
145 */
146struct seltd {
147        STAILQ_HEAD(, selfd)    st_selq;        /* (k) List of selfds. */
148        struct selfd            *st_free1;      /* (k) free fd for read set. */
149        struct selfd            *st_free2;      /* (k) free fd for write set. */
150        struct mtx              st_mtx;         /* Protects struct seltd */
151        struct cv               st_wait;        /* (t) Wait channel. */
152        int                     st_flags;       /* (t) SELTD_ flags. */
153};
154
155#define SELTD_PENDING   0x0001                  /* We have pending events. */
156#define SELTD_RESCAN    0x0002                  /* Doing a rescan. */
157
158/*
159 * One selfd allocated per-thread per-file-descriptor.
160 *      f - protected by sf_mtx
161 */
162struct selfd {
163        STAILQ_ENTRY(selfd)     sf_link;        /* (k) fds owned by this td. */
164        TAILQ_ENTRY(selfd)      sf_threads;     /* (f) fds on this selinfo. */
165        struct selinfo          *sf_si;         /* (f) selinfo when linked. */
166        struct mtx              *sf_mtx;        /* Pointer to selinfo mtx. */
167        struct seltd            *sf_td;         /* (k) owning seltd. */
168        void                    *sf_cookie;     /* (k) fd or pollfd. */
169        u_int                   sf_refs;
170};
171
172static uma_zone_t selfd_zone;
173static struct mtx_pool *mtxpool_select;
174
175#ifndef __rtems__
176#ifdef __LP64__
177size_t
178devfs_iosize_max(void)
179{
180
181        return (devfs_iosize_max_clamp || SV_CURPROC_FLAG(SV_ILP32) ?
182            INT_MAX : SSIZE_MAX);
183}
184
185size_t
186iosize_max(void)
187{
188
189        return (iosize_max_clamp || SV_CURPROC_FLAG(SV_ILP32) ?
190            INT_MAX : SSIZE_MAX);
191}
192#endif
193
194#ifndef _SYS_SYSPROTO_H_
195struct read_args {
196        int     fd;
197        void    *buf;
198        size_t  nbyte;
199};
200#endif
201int
202sys_read(td, uap)
203        struct thread *td;
204        struct read_args *uap;
205{
206        struct uio auio;
207        struct iovec aiov;
208        int error;
209
210        if (uap->nbyte > IOSIZE_MAX)
211                return (EINVAL);
212        aiov.iov_base = uap->buf;
213        aiov.iov_len = uap->nbyte;
214        auio.uio_iov = &aiov;
215        auio.uio_iovcnt = 1;
216        auio.uio_resid = uap->nbyte;
217        auio.uio_segflg = UIO_USERSPACE;
218        error = kern_readv(td, uap->fd, &auio);
219        return(error);
220}
221
222/*
223 * Positioned read system call
224 */
225#ifndef _SYS_SYSPROTO_H_
226struct pread_args {
227        int     fd;
228        void    *buf;
229        size_t  nbyte;
230        int     pad;
231        off_t   offset;
232};
233#endif
234int
235sys_pread(struct thread *td, struct pread_args *uap)
236{
237
238        return (kern_pread(td, uap->fd, uap->buf, uap->nbyte, uap->offset));
239}
240
241int
242kern_pread(struct thread *td, int fd, void *buf, size_t nbyte, off_t offset)
243{
244        struct uio auio;
245        struct iovec aiov;
246        int error;
247
248        if (nbyte > IOSIZE_MAX)
249                return (EINVAL);
250        aiov.iov_base = buf;
251        aiov.iov_len = nbyte;
252        auio.uio_iov = &aiov;
253        auio.uio_iovcnt = 1;
254        auio.uio_resid = nbyte;
255        auio.uio_segflg = UIO_USERSPACE;
256        error = kern_preadv(td, fd, &auio, offset);
257        return (error);
258}
259
260#if defined(COMPAT_FREEBSD6)
261int
262freebsd6_pread(struct thread *td, struct freebsd6_pread_args *uap)
263{
264
265        return (kern_pread(td, uap->fd, uap->buf, uap->nbyte, uap->offset));
266}
267#endif
268
269/*
270 * Scatter read system call.
271 */
272#ifndef _SYS_SYSPROTO_H_
273struct readv_args {
274        int     fd;
275        struct  iovec *iovp;
276        u_int   iovcnt;
277};
278#endif
279int
280sys_readv(struct thread *td, struct readv_args *uap)
281{
282        struct uio *auio;
283        int error;
284
285        error = copyinuio(uap->iovp, uap->iovcnt, &auio);
286        if (error)
287                return (error);
288        error = kern_readv(td, uap->fd, auio);
289        free(auio, M_IOV);
290        return (error);
291}
292
293int
294kern_readv(struct thread *td, int fd, struct uio *auio)
295{
296        struct file *fp;
297        cap_rights_t rights;
298        int error;
299
300        error = fget_read(td, fd, cap_rights_init(&rights, CAP_READ), &fp);
301        if (error)
302                return (error);
303        error = dofileread(td, fd, fp, auio, (off_t)-1, 0);
304        fdrop(fp, td);
305        return (error);
306}
307
308/*
309 * Scatter positioned read system call.
310 */
311#ifndef _SYS_SYSPROTO_H_
312struct preadv_args {
313        int     fd;
314        struct  iovec *iovp;
315        u_int   iovcnt;
316        off_t   offset;
317};
318#endif
319int
320sys_preadv(struct thread *td, struct preadv_args *uap)
321{
322        struct uio *auio;
323        int error;
324
325        error = copyinuio(uap->iovp, uap->iovcnt, &auio);
326        if (error)
327                return (error);
328        error = kern_preadv(td, uap->fd, auio, uap->offset);
329        free(auio, M_IOV);
330        return (error);
331}
332
333int
334kern_preadv(td, fd, auio, offset)
335        struct thread *td;
336        int fd;
337        struct uio *auio;
338        off_t offset;
339{
340        struct file *fp;
341        cap_rights_t rights;
342        int error;
343
344        error = fget_read(td, fd, cap_rights_init(&rights, CAP_PREAD), &fp);
345        if (error)
346                return (error);
347        if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
348                error = ESPIPE;
349        else if (offset < 0 &&
350            (fp->f_vnode == NULL || fp->f_vnode->v_type != VCHR))
351                error = EINVAL;
352        else
353                error = dofileread(td, fd, fp, auio, offset, FOF_OFFSET);
354        fdrop(fp, td);
355        return (error);
356}
357
358/*
359 * Common code for readv and preadv that reads data in
360 * from a file using the passed in uio, offset, and flags.
361 */
362static int
363dofileread(td, fd, fp, auio, offset, flags)
364        struct thread *td;
365        int fd;
366        struct file *fp;
367        struct uio *auio;
368        off_t offset;
369        int flags;
370{
371        ssize_t cnt;
372        int error;
373#ifdef KTRACE
374        struct uio *ktruio = NULL;
375#endif
376
377        AUDIT_ARG_FD(fd);
378
379        /* Finish zero length reads right here */
380        if (auio->uio_resid == 0) {
381                td->td_retval[0] = 0;
382                return(0);
383        }
384        auio->uio_rw = UIO_READ;
385        auio->uio_offset = offset;
386        auio->uio_td = td;
387#ifdef KTRACE
388        if (KTRPOINT(td, KTR_GENIO))
389                ktruio = cloneuio(auio);
390#endif
391        cnt = auio->uio_resid;
392        if ((error = fo_read(fp, auio, td->td_ucred, flags, td))) {
393                if (auio->uio_resid != cnt && (error == ERESTART ||
394                    error == EINTR || error == EWOULDBLOCK))
395                        error = 0;
396        }
397        cnt -= auio->uio_resid;
398#ifdef KTRACE
399        if (ktruio != NULL) {
400                ktruio->uio_resid = cnt;
401                ktrgenio(fd, UIO_READ, ktruio, error);
402        }
403#endif
404        td->td_retval[0] = cnt;
405        return (error);
406}
407
408#ifndef _SYS_SYSPROTO_H_
409struct write_args {
410        int     fd;
411        const void *buf;
412        size_t  nbyte;
413};
414#endif
415int
416sys_write(td, uap)
417        struct thread *td;
418        struct write_args *uap;
419{
420        struct uio auio;
421        struct iovec aiov;
422        int error;
423
424        if (uap->nbyte > IOSIZE_MAX)
425                return (EINVAL);
426        aiov.iov_base = (void *)(uintptr_t)uap->buf;
427        aiov.iov_len = uap->nbyte;
428        auio.uio_iov = &aiov;
429        auio.uio_iovcnt = 1;
430        auio.uio_resid = uap->nbyte;
431        auio.uio_segflg = UIO_USERSPACE;
432        error = kern_writev(td, uap->fd, &auio);
433        return(error);
434}
435
436/*
437 * Positioned write system call.
438 */
439#ifndef _SYS_SYSPROTO_H_
440struct pwrite_args {
441        int     fd;
442        const void *buf;
443        size_t  nbyte;
444        int     pad;
445        off_t   offset;
446};
447#endif
448int
449sys_pwrite(struct thread *td, struct pwrite_args *uap)
450{
451
452        return (kern_pwrite(td, uap->fd, uap->buf, uap->nbyte, uap->offset));
453}
454
455int
456kern_pwrite(struct thread *td, int fd, const void *buf, size_t nbyte,
457    off_t offset)
458{
459        struct uio auio;
460        struct iovec aiov;
461        int error;
462
463        if (nbyte > IOSIZE_MAX)
464                return (EINVAL);
465        aiov.iov_base = (void *)(uintptr_t)buf;
466        aiov.iov_len = nbyte;
467        auio.uio_iov = &aiov;
468        auio.uio_iovcnt = 1;
469        auio.uio_resid = nbyte;
470        auio.uio_segflg = UIO_USERSPACE;
471        error = kern_pwritev(td, fd, &auio, offset);
472        return(error);
473}
474
475#if defined(COMPAT_FREEBSD6)
476int
477freebsd6_pwrite(struct thread *td, struct freebsd6_pwrite_args *uap)
478{
479
480        return (kern_pwrite(td, uap->fd, uap->buf, uap->nbyte, uap->offset));
481}
482#endif
483
484/*
485 * Gather write system call.
486 */
487#ifndef _SYS_SYSPROTO_H_
488struct writev_args {
489        int     fd;
490        struct  iovec *iovp;
491        u_int   iovcnt;
492};
493#endif
494int
495sys_writev(struct thread *td, struct writev_args *uap)
496{
497        struct uio *auio;
498        int error;
499
500        error = copyinuio(uap->iovp, uap->iovcnt, &auio);
501        if (error)
502                return (error);
503        error = kern_writev(td, uap->fd, auio);
504        free(auio, M_IOV);
505        return (error);
506}
507
508int
509kern_writev(struct thread *td, int fd, struct uio *auio)
510{
511        struct file *fp;
512        cap_rights_t rights;
513        int error;
514
515        error = fget_write(td, fd, cap_rights_init(&rights, CAP_WRITE), &fp);
516        if (error)
517                return (error);
518        error = dofilewrite(td, fd, fp, auio, (off_t)-1, 0);
519        fdrop(fp, td);
520        return (error);
521}
522
523/*
524 * Gather positioned write system call.
525 */
526#ifndef _SYS_SYSPROTO_H_
527struct pwritev_args {
528        int     fd;
529        struct  iovec *iovp;
530        u_int   iovcnt;
531        off_t   offset;
532};
533#endif
534int
535sys_pwritev(struct thread *td, struct pwritev_args *uap)
536{
537        struct uio *auio;
538        int error;
539
540        error = copyinuio(uap->iovp, uap->iovcnt, &auio);
541        if (error)
542                return (error);
543        error = kern_pwritev(td, uap->fd, auio, uap->offset);
544        free(auio, M_IOV);
545        return (error);
546}
547
548int
549kern_pwritev(td, fd, auio, offset)
550        struct thread *td;
551        struct uio *auio;
552        int fd;
553        off_t offset;
554{
555        struct file *fp;
556        cap_rights_t rights;
557        int error;
558
559        error = fget_write(td, fd, cap_rights_init(&rights, CAP_PWRITE), &fp);
560        if (error)
561                return (error);
562        if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
563                error = ESPIPE;
564        else if (offset < 0 &&
565            (fp->f_vnode == NULL || fp->f_vnode->v_type != VCHR))
566                error = EINVAL;
567        else
568                error = dofilewrite(td, fd, fp, auio, offset, FOF_OFFSET);
569        fdrop(fp, td);
570        return (error);
571}
572
573/*
574 * Common code for writev and pwritev that writes data to
575 * a file using the passed in uio, offset, and flags.
576 */
577static int
578dofilewrite(td, fd, fp, auio, offset, flags)
579        struct thread *td;
580        int fd;
581        struct file *fp;
582        struct uio *auio;
583        off_t offset;
584        int flags;
585{
586        ssize_t cnt;
587        int error;
588#ifdef KTRACE
589        struct uio *ktruio = NULL;
590#endif
591
592        AUDIT_ARG_FD(fd);
593        auio->uio_rw = UIO_WRITE;
594        auio->uio_td = td;
595        auio->uio_offset = offset;
596#ifdef KTRACE
597        if (KTRPOINT(td, KTR_GENIO))
598                ktruio = cloneuio(auio);
599#endif
600        cnt = auio->uio_resid;
601        if (fp->f_type == DTYPE_VNODE &&
602            (fp->f_vnread_flags & FDEVFS_VNODE) == 0)
603                bwillwrite();
604        if ((error = fo_write(fp, auio, td->td_ucred, flags, td))) {
605                if (auio->uio_resid != cnt && (error == ERESTART ||
606                    error == EINTR || error == EWOULDBLOCK))
607                        error = 0;
608                /* Socket layer is responsible for issuing SIGPIPE. */
609                if (fp->f_type != DTYPE_SOCKET && error == EPIPE) {
610                        PROC_LOCK(td->td_proc);
611                        tdsignal(td, SIGPIPE);
612                        PROC_UNLOCK(td->td_proc);
613                }
614        }
615        cnt -= auio->uio_resid;
616#ifdef KTRACE
617        if (ktruio != NULL) {
618                ktruio->uio_resid = cnt;
619                ktrgenio(fd, UIO_WRITE, ktruio, error);
620        }
621#endif
622        td->td_retval[0] = cnt;
623        return (error);
624}
625
626/*
627 * Truncate a file given a file descriptor.
628 *
629 * Can't use fget_write() here, since must return EINVAL and not EBADF if the
630 * descriptor isn't writable.
631 */
632int
633kern_ftruncate(td, fd, length)
634        struct thread *td;
635        int fd;
636        off_t length;
637{
638        struct file *fp;
639        cap_rights_t rights;
640        int error;
641
642        AUDIT_ARG_FD(fd);
643        if (length < 0)
644                return (EINVAL);
645        error = fget(td, fd, cap_rights_init(&rights, CAP_FTRUNCATE), &fp);
646        if (error)
647                return (error);
648        AUDIT_ARG_FILE(td->td_proc, fp);
649        if (!(fp->f_flag & FWRITE)) {
650                fdrop(fp, td);
651                return (EINVAL);
652        }
653        error = fo_truncate(fp, length, td->td_ucred, td);
654        fdrop(fp, td);
655        return (error);
656}
657
658#ifndef _SYS_SYSPROTO_H_
659struct ftruncate_args {
660        int     fd;
661        int     pad;
662        off_t   length;
663};
664#endif
665int
666sys_ftruncate(td, uap)
667        struct thread *td;
668        struct ftruncate_args *uap;
669{
670
671        return (kern_ftruncate(td, uap->fd, uap->length));
672}
673
674#if defined(COMPAT_43)
675#ifndef _SYS_SYSPROTO_H_
676struct oftruncate_args {
677        int     fd;
678        long    length;
679};
680#endif
681int
682oftruncate(td, uap)
683        struct thread *td;
684        struct oftruncate_args *uap;
685{
686
687        return (kern_ftruncate(td, uap->fd, uap->length));
688}
689#endif /* COMPAT_43 */
690
691#ifndef _SYS_SYSPROTO_H_
692struct ioctl_args {
693        int     fd;
694        u_long  com;
695        caddr_t data;
696};
697#endif
698/* ARGSUSED */
699int
700sys_ioctl(struct thread *td, struct ioctl_args *uap)
701{
702        u_char smalldata[SYS_IOCTL_SMALL_SIZE] __aligned(SYS_IOCTL_SMALL_ALIGN);
703        u_long com;
704        int arg, error;
705        u_int size;
706        caddr_t data;
707
708        if (uap->com > 0xffffffff) {
709                printf(
710                    "WARNING pid %d (%s): ioctl sign-extension ioctl %lx\n",
711                    td->td_proc->p_pid, td->td_name, uap->com);
712                uap->com &= 0xffffffff;
713        }
714        com = uap->com;
715
716        /*
717         * Interpret high order word to find amount of data to be
718         * copied to/from the user's address space.
719         */
720        size = IOCPARM_LEN(com);
721        if ((size > IOCPARM_MAX) ||
722            ((com & (IOC_VOID  | IOC_IN | IOC_OUT)) == 0) ||
723#if defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
724            ((com & IOC_OUT) && size == 0) ||
725#else
726            ((com & (IOC_IN | IOC_OUT)) && size == 0) ||
727#endif
728            ((com & IOC_VOID) && size > 0 && size != sizeof(int)))
729                return (ENOTTY);
730
731        if (size > 0) {
732                if (com & IOC_VOID) {
733                        /* Integer argument. */
734                        arg = (intptr_t)uap->data;
735                        data = (void *)&arg;
736                        size = 0;
737                } else {
738                        if (size > SYS_IOCTL_SMALL_SIZE)
739                                data = malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
740                        else
741                                data = smalldata;
742                }
743        } else
744                data = (void *)&uap->data;
745        if (com & IOC_IN) {
746                error = copyin(uap->data, data, (u_int)size);
747                if (error != 0)
748                        goto out;
749        } else if (com & IOC_OUT) {
750                /*
751                 * Zero the buffer so the user always
752                 * gets back something deterministic.
753                 */
754                bzero(data, size);
755        }
756
757        error = kern_ioctl(td, uap->fd, com, data);
758
759        if (error == 0 && (com & IOC_OUT))
760                error = copyout(data, uap->data, (u_int)size);
761
762out:
763        if (size > SYS_IOCTL_SMALL_SIZE)
764                free(data, M_IOCTLOPS);
765        return (error);
766}
767
768int
769kern_ioctl(struct thread *td, int fd, u_long com, caddr_t data)
770{
771        struct file *fp;
772        struct filedesc *fdp;
773#ifndef CAPABILITIES
774        cap_rights_t rights;
775#endif
776        int error, tmp, locked;
777
778        AUDIT_ARG_FD(fd);
779        AUDIT_ARG_CMD(com);
780
781        fdp = td->td_proc->p_fd;
782
783        switch (com) {
784        case FIONCLEX:
785        case FIOCLEX:
786                FILEDESC_XLOCK(fdp);
787                locked = LA_XLOCKED;
788                break;
789        default:
790#ifdef CAPABILITIES
791                FILEDESC_SLOCK(fdp);
792                locked = LA_SLOCKED;
793#else
794                locked = LA_UNLOCKED;
795#endif
796                break;
797        }
798
799#ifdef CAPABILITIES
800        if ((fp = fget_locked(fdp, fd)) == NULL) {
801                error = EBADF;
802                goto out;
803        }
804        if ((error = cap_ioctl_check(fdp, fd, com)) != 0) {
805                fp = NULL;      /* fhold() was not called yet */
806                goto out;
807        }
808        fhold(fp);
809        if (locked == LA_SLOCKED) {
810                FILEDESC_SUNLOCK(fdp);
811                locked = LA_UNLOCKED;
812        }
813#else
814        error = fget(td, fd, cap_rights_init(&rights, CAP_IOCTL), &fp);
815        if (error != 0) {
816                fp = NULL;
817                goto out;
818        }
819#endif
820        if ((fp->f_flag & (FREAD | FWRITE)) == 0) {
821                error = EBADF;
822                goto out;
823        }
824
825        switch (com) {
826        case FIONCLEX:
827                fdp->fd_ofiles[fd].fde_flags &= ~UF_EXCLOSE;
828                goto out;
829        case FIOCLEX:
830                fdp->fd_ofiles[fd].fde_flags |= UF_EXCLOSE;
831                goto out;
832        case FIONBIO:
833                if ((tmp = *(int *)data))
834                        atomic_set_int(&fp->f_flag, FNONBLOCK);
835                else
836                        atomic_clear_int(&fp->f_flag, FNONBLOCK);
837                data = (void *)&tmp;
838                break;
839        case FIOASYNC:
840                if ((tmp = *(int *)data))
841                        atomic_set_int(&fp->f_flag, FASYNC);
842                else
843                        atomic_clear_int(&fp->f_flag, FASYNC);
844                data = (void *)&tmp;
845                break;
846        }
847
848        error = fo_ioctl(fp, com, data, td->td_ucred, td);
849out:
850        switch (locked) {
851        case LA_XLOCKED:
852                FILEDESC_XUNLOCK(fdp);
853                break;
854#ifdef CAPABILITIES
855        case LA_SLOCKED:
856                FILEDESC_SUNLOCK(fdp);
857                break;
858#endif
859        default:
860                FILEDESC_UNLOCK_ASSERT(fdp);
861                break;
862        }
863        if (fp != NULL)
864                fdrop(fp, td);
865        return (error);
866}
867#endif /* __rtems__ */
868
869int
870poll_no_poll(int events)
871{
872        /*
873         * Return true for read/write.  If the user asked for something
874         * special, return POLLNVAL, so that clients have a way of
875         * determining reliably whether or not the extended
876         * functionality is present without hard-coding knowledge
877         * of specific filesystem implementations.
878         */
879        if (events & ~POLLSTANDARD)
880                return (POLLNVAL);
881
882        return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
883}
884
885#ifndef __rtems__
886int
887sys_pselect(struct thread *td, struct pselect_args *uap)
888{
889        struct timespec ts;
890        struct timeval tv, *tvp;
891        sigset_t set, *uset;
892        int error;
893
894        if (uap->ts != NULL) {
895                error = copyin(uap->ts, &ts, sizeof(ts));
896                if (error != 0)
897                    return (error);
898                TIMESPEC_TO_TIMEVAL(&tv, &ts);
899                tvp = &tv;
900        } else
901                tvp = NULL;
902        if (uap->sm != NULL) {
903                error = copyin(uap->sm, &set, sizeof(set));
904                if (error != 0)
905                        return (error);
906                uset = &set;
907        } else
908                uset = NULL;
909        return (kern_pselect(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
910            uset, NFDBITS));
911}
912
913int
914kern_pselect(struct thread *td, int nd, fd_set *in, fd_set *ou, fd_set *ex,
915    struct timeval *tvp, sigset_t *uset, int abi_nfdbits)
916{
917        int error;
918
919        if (uset != NULL) {
920                error = kern_sigprocmask(td, SIG_SETMASK, uset,
921                    &td->td_oldsigmask, 0);
922                if (error != 0)
923                        return (error);
924                td->td_pflags |= TDP_OLDMASK;
925                /*
926                 * Make sure that ast() is called on return to
927                 * usermode and TDP_OLDMASK is cleared, restoring old
928                 * sigmask.
929                 */
930                thread_lock(td);
931                td->td_flags |= TDF_ASTPENDING;
932                thread_unlock(td);
933        }
934        error = kern_select(td, nd, in, ou, ex, tvp, abi_nfdbits);
935        return (error);
936}
937
938#ifndef _SYS_SYSPROTO_H_
939struct select_args {
940        int     nd;
941        fd_set  *in, *ou, *ex;
942        struct  timeval *tv;
943};
944#endif
945int
946sys_select(struct thread *td, struct select_args *uap)
947{
948        struct timeval tv, *tvp;
949        int error;
950
951        if (uap->tv != NULL) {
952                error = copyin(uap->tv, &tv, sizeof(tv));
953                if (error)
954                        return (error);
955                tvp = &tv;
956        } else
957                tvp = NULL;
958
959        return (kern_select(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
960            NFDBITS));
961}
962#endif /* __rtems__ */
963
964/*
965 * In the unlikely case when user specified n greater then the last
966 * open file descriptor, check that no bits are set after the last
967 * valid fd.  We must return EBADF if any is set.
968 *
969 * There are applications that rely on the behaviour.
970 *
971 * nd is fd_lastfile + 1.
972 */
973static int
974select_check_badfd(fd_set *fd_in, int nd, int ndu, int abi_nfdbits)
975{
976        char *addr, *oaddr;
977        int b, i, res;
978        uint8_t bits;
979
980        if (nd >= ndu || fd_in == NULL)
981                return (0);
982
983        oaddr = NULL;
984        bits = 0; /* silence gcc */
985        for (i = nd; i < ndu; i++) {
986                b = i / NBBY;
987#if BYTE_ORDER == LITTLE_ENDIAN
988                addr = (char *)fd_in + b;
989#else
990                addr = (char *)fd_in;
991                if (abi_nfdbits == NFDBITS) {
992                        addr += rounddown(b, sizeof(fd_mask)) +
993                            sizeof(fd_mask) - 1 - b % sizeof(fd_mask);
994                } else {
995                        addr += rounddown(b, sizeof(uint32_t)) +
996                            sizeof(uint32_t) - 1 - b % sizeof(uint32_t);
997                }
998#endif
999                if (addr != oaddr) {
1000                        res = fubyte(addr);
1001                        if (res == -1)
1002                                return (EFAULT);
1003                        oaddr = addr;
1004                        bits = res;
1005                }
1006                if ((bits & (1 << (i % NBBY))) != 0)
1007                        return (EBADF);
1008        }
1009        return (0);
1010}
1011
1012int
1013kern_select(struct thread *td, int nd, fd_set *fd_in, fd_set *fd_ou,
1014    fd_set *fd_ex, struct timeval *tvp, int abi_nfdbits)
1015{
1016        struct filedesc *fdp;
1017        /*
1018         * The magic 2048 here is chosen to be just enough for FD_SETSIZE
1019         * infds with the new FD_SETSIZE of 1024, and more than enough for
1020         * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
1021         * of 256.
1022         */
1023        fd_mask s_selbits[howmany(2048, NFDBITS)];
1024        fd_mask *ibits[3], *obits[3], *selbits, *sbp;
1025        struct timeval rtv;
1026        sbintime_t asbt, precision, rsbt;
1027        u_int nbufbytes, ncpbytes, ncpubytes, nfdbits;
1028        int error, lf, ndu;
1029
1030        if (nd < 0)
1031                return (EINVAL);
1032#ifndef __rtems__
1033        fdp = td->td_proc->p_fd;
1034#endif /* __rtems__ */
1035        ndu = nd;
1036#ifndef __rtems__
1037        lf = fdp->fd_lastfile;
1038#else /* __rtems__ */
1039        (void) fdp;
1040        lf = rtems_libio_number_iops;
1041#endif /* __rtems__ */
1042        if (nd > lf + 1)
1043                nd = lf + 1;
1044
1045        error = select_check_badfd(fd_in, nd, ndu, abi_nfdbits);
1046        if (error != 0)
1047                return (error);
1048        error = select_check_badfd(fd_ou, nd, ndu, abi_nfdbits);
1049        if (error != 0)
1050                return (error);
1051        error = select_check_badfd(fd_ex, nd, ndu, abi_nfdbits);
1052        if (error != 0)
1053                return (error);
1054
1055        /*
1056         * Allocate just enough bits for the non-null fd_sets.  Use the
1057         * preallocated auto buffer if possible.
1058         */
1059        nfdbits = roundup(nd, NFDBITS);
1060        ncpbytes = nfdbits / NBBY;
1061        ncpubytes = roundup(nd, abi_nfdbits) / NBBY;
1062        nbufbytes = 0;
1063        if (fd_in != NULL)
1064                nbufbytes += 2 * ncpbytes;
1065        if (fd_ou != NULL)
1066                nbufbytes += 2 * ncpbytes;
1067        if (fd_ex != NULL)
1068                nbufbytes += 2 * ncpbytes;
1069        if (nbufbytes <= sizeof s_selbits)
1070                selbits = &s_selbits[0];
1071        else
1072                selbits = malloc(nbufbytes, M_SELECT, M_WAITOK);
1073
1074        /*
1075         * Assign pointers into the bit buffers and fetch the input bits.
1076         * Put the output buffers together so that they can be bzeroed
1077         * together.
1078         */
1079        sbp = selbits;
1080#define getbits(name, x) \
1081        do {                                                            \
1082                if (name == NULL) {                                     \
1083                        ibits[x] = NULL;                                \
1084                        obits[x] = NULL;                                \
1085                } else {                                                \
1086                        ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp;   \
1087                        obits[x] = sbp;                                 \
1088                        sbp += ncpbytes / sizeof *sbp;                  \
1089                        error = copyin(name, ibits[x], ncpubytes);      \
1090                        if (error != 0)                                 \
1091                                goto done;                              \
1092                        bzero((char *)ibits[x] + ncpubytes,             \
1093                            ncpbytes - ncpubytes);                      \
1094                }                                                       \
1095        } while (0)
1096        getbits(fd_in, 0);
1097        getbits(fd_ou, 1);
1098        getbits(fd_ex, 2);
1099#undef  getbits
1100
1101#if BYTE_ORDER == BIG_ENDIAN && defined(__LP64__)
1102        /*
1103         * XXX: swizzle_fdset assumes that if abi_nfdbits != NFDBITS,
1104         * we are running under 32-bit emulation. This should be more
1105         * generic.
1106         */
1107#define swizzle_fdset(bits)                                             \
1108        if (abi_nfdbits != NFDBITS && bits != NULL) {                   \
1109                int i;                                                  \
1110                for (i = 0; i < ncpbytes / sizeof *sbp; i++)            \
1111                        bits[i] = (bits[i] >> 32) | (bits[i] << 32);    \
1112        }
1113#else
1114#define swizzle_fdset(bits)
1115#endif
1116
1117        /* Make sure the bit order makes it through an ABI transition */
1118        swizzle_fdset(ibits[0]);
1119        swizzle_fdset(ibits[1]);
1120        swizzle_fdset(ibits[2]);
1121       
1122        if (nbufbytes != 0)
1123                bzero(selbits, nbufbytes / 2);
1124
1125        precision = 0;
1126        if (tvp != NULL) {
1127                rtv = *tvp;
1128                if (rtv.tv_sec < 0 || rtv.tv_usec < 0 ||
1129                    rtv.tv_usec >= 1000000) {
1130                        error = EINVAL;
1131                        goto done;
1132                }
1133                if (!timevalisset(&rtv))
1134                        asbt = 0;
1135                else if (rtv.tv_sec <= INT32_MAX) {
1136                        rsbt = tvtosbt(rtv);
1137                        precision = rsbt;
1138                        precision >>= tc_precexp;
1139                        if (TIMESEL(&asbt, rsbt))
1140                                asbt += tc_tick_sbt;
1141                        if (asbt <= SBT_MAX - rsbt)
1142                                asbt += rsbt;
1143                        else
1144                                asbt = -1;
1145                } else
1146                        asbt = -1;
1147        } else
1148                asbt = -1;
1149        seltdinit(td);
1150        /* Iterate until the timeout expires or descriptors become ready. */
1151        for (;;) {
1152                error = selscan(td, ibits, obits, nd);
1153                if (error || td->td_retval[0] != 0)
1154                        break;
1155                error = seltdwait(td, asbt, precision);
1156                if (error)
1157                        break;
1158                error = selrescan(td, ibits, obits);
1159                if (error || td->td_retval[0] != 0)
1160                        break;
1161        }
1162        seltdclear(td);
1163
1164done:
1165        /* select is not restarted after signals... */
1166        if (error == ERESTART)
1167                error = EINTR;
1168        if (error == EWOULDBLOCK)
1169                error = 0;
1170
1171        /* swizzle bit order back, if necessary */
1172        swizzle_fdset(obits[0]);
1173        swizzle_fdset(obits[1]);
1174        swizzle_fdset(obits[2]);
1175#undef swizzle_fdset
1176
1177#define putbits(name, x) \
1178        if (name && (error2 = copyout(obits[x], name, ncpubytes))) \
1179                error = error2;
1180        if (error == 0) {
1181                int error2;
1182
1183                putbits(fd_in, 0);
1184                putbits(fd_ou, 1);
1185                putbits(fd_ex, 2);
1186#undef putbits
1187        }
1188        if (selbits != &s_selbits[0])
1189                free(selbits, M_SELECT);
1190
1191        return (error);
1192}
1193#ifdef __rtems__
1194int
1195select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds,
1196    struct timeval *timeout)
1197{
1198        struct thread *td = rtems_bsd_get_curthread_or_null();
1199        int error;
1200
1201        if (td != NULL) {
1202                error = kern_select(td, nfds, readfds, writefds, errorfds,
1203                    timeout, NFDBITS);
1204        } else {
1205                error = ENOMEM;
1206        }
1207
1208        if (error == 0) {
1209                return td->td_retval[0];
1210        } else {
1211                rtems_set_errno_and_return_minus_one(error);
1212        }
1213}
1214#endif /* __rtems__ */
1215
1216/*
1217 * Convert a select bit set to poll flags.
1218 *
1219 * The backend always returns POLLHUP/POLLERR if appropriate and we
1220 * return this as a set bit in any set.
1221 */
1222static int select_flags[3] = {
1223    POLLRDNORM | POLLHUP | POLLERR,
1224    POLLWRNORM | POLLHUP | POLLERR,
1225    POLLRDBAND | POLLERR
1226};
1227
1228/*
1229 * Compute the fo_poll flags required for a fd given by the index and
1230 * bit position in the fd_mask array.
1231 */
1232static __inline int
1233selflags(fd_mask **ibits, int idx, fd_mask bit)
1234{
1235        int flags;
1236        int msk;
1237
1238        flags = 0;
1239        for (msk = 0; msk < 3; msk++) {
1240                if (ibits[msk] == NULL)
1241                        continue;
1242                if ((ibits[msk][idx] & bit) == 0)
1243                        continue;
1244                flags |= select_flags[msk];
1245        }
1246        return (flags);
1247}
1248
1249/*
1250 * Set the appropriate output bits given a mask of fired events and the
1251 * input bits originally requested.
1252 */
1253static __inline int
1254selsetbits(fd_mask **ibits, fd_mask **obits, int idx, fd_mask bit, int events)
1255{
1256        int msk;
1257        int n;
1258
1259        n = 0;
1260        for (msk = 0; msk < 3; msk++) {
1261                if ((events & select_flags[msk]) == 0)
1262                        continue;
1263                if (ibits[msk] == NULL)
1264                        continue;
1265                if ((ibits[msk][idx] & bit) == 0)
1266                        continue;
1267                /*
1268                 * XXX Check for a duplicate set.  This can occur because a
1269                 * socket calls selrecord() twice for each poll() call
1270                 * resulting in two selfds per real fd.  selrescan() will
1271                 * call selsetbits twice as a result.
1272                 */
1273                if ((obits[msk][idx] & bit) != 0)
1274                        continue;
1275                obits[msk][idx] |= bit;
1276                n++;
1277        }
1278
1279        return (n);
1280}
1281
1282static __inline int
1283getselfd_cap(struct filedesc *fdp, int fd, struct file **fpp)
1284{
1285        cap_rights_t rights;
1286
1287        cap_rights_init(&rights, CAP_EVENT);
1288
1289        return (fget_unlocked(fdp, fd, &rights, fpp, NULL));
1290}
1291
1292/*
1293 * Traverse the list of fds attached to this thread's seltd and check for
1294 * completion.
1295 */
1296static int
1297selrescan(struct thread *td, fd_mask **ibits, fd_mask **obits)
1298{
1299        struct filedesc *fdp;
1300        struct selinfo *si;
1301        struct seltd *stp;
1302        struct selfd *sfp;
1303        struct selfd *sfn;
1304        struct file *fp;
1305        fd_mask bit;
1306        int fd, ev, n, idx;
1307        int error;
1308
1309#ifndef __rtems__
1310        fdp = td->td_proc->p_fd;
1311#else /* __rtems__ */
1312        fdp = NULL;
1313#endif /* __rtems__ */
1314        stp = td->td_sel;
1315        n = 0;
1316        STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1317                fd = (int)(uintptr_t)sfp->sf_cookie;
1318                si = sfp->sf_si;
1319                selfdfree(stp, sfp);
1320                /* If the selinfo wasn't cleared the event didn't fire. */
1321                if (si != NULL)
1322                        continue;
1323                error = getselfd_cap(fdp, fd, &fp);
1324                if (error)
1325                        return (error);
1326                idx = fd / NFDBITS;
1327                bit = (fd_mask)1 << (fd % NFDBITS);
1328                ev = fo_poll(fp, selflags(ibits, idx, bit), td->td_ucred, td);
1329                fdrop(fp, td);
1330                if (ev != 0)
1331                        n += selsetbits(ibits, obits, idx, bit, ev);
1332        }
1333        stp->st_flags = 0;
1334        td->td_retval[0] = n;
1335        return (0);
1336}
1337
1338/*
1339 * Perform the initial filedescriptor scan and register ourselves with
1340 * each selinfo.
1341 */
1342static int
1343selscan(td, ibits, obits, nfd)
1344        struct thread *td;
1345        fd_mask **ibits, **obits;
1346        int nfd;
1347{
1348        struct filedesc *fdp;
1349        struct file *fp;
1350        fd_mask bit;
1351        int ev, flags, end, fd;
1352        int n, idx;
1353        int error;
1354
1355#ifndef __rtems__
1356        fdp = td->td_proc->p_fd;
1357#else /* __rtems__ */
1358        fdp = NULL;
1359#endif /* __rtems__ */
1360        n = 0;
1361        for (idx = 0, fd = 0; fd < nfd; idx++) {
1362                end = imin(fd + NFDBITS, nfd);
1363                for (bit = 1; fd < end; bit <<= 1, fd++) {
1364                        /* Compute the list of events we're interested in. */
1365                        flags = selflags(ibits, idx, bit);
1366                        if (flags == 0)
1367                                continue;
1368                        error = getselfd_cap(fdp, fd, &fp);
1369                        if (error)
1370                                return (error);
1371                        selfdalloc(td, (void *)(uintptr_t)fd);
1372                        ev = fo_poll(fp, flags, td->td_ucred, td);
1373                        fdrop(fp, td);
1374                        if (ev != 0)
1375                                n += selsetbits(ibits, obits, idx, bit, ev);
1376                }
1377        }
1378
1379        td->td_retval[0] = n;
1380        return (0);
1381}
1382
1383#ifdef __rtems__
1384static int kern_poll(struct thread *td, struct pollfd *fds, u_int nfds,
1385    struct timespec *tsp, sigset_t *uset);
1386
1387static
1388#endif /* __rtems__ */
1389int
1390sys_poll(struct thread *td, struct poll_args *uap)
1391{
1392        struct timespec ts, *tsp;
1393
1394        if (uap->timeout != INFTIM) {
1395                if (uap->timeout < 0)
1396                        return (EINVAL);
1397                ts.tv_sec = uap->timeout / 1000;
1398                ts.tv_nsec = (uap->timeout % 1000) * 1000000;
1399                tsp = &ts;
1400        } else
1401                tsp = NULL;
1402
1403        return (kern_poll(td, uap->fds, uap->nfds, tsp, NULL));
1404}
1405
1406int
1407kern_poll(struct thread *td, struct pollfd *fds, u_int nfds,
1408    struct timespec *tsp, sigset_t *uset)
1409{
1410        struct pollfd *bits;
1411        struct pollfd smallbits[32];
1412        sbintime_t sbt, precision, tmp;
1413        time_t over;
1414        struct timespec ts;
1415        int error;
1416        size_t ni;
1417
1418        precision = 0;
1419        if (tsp != NULL) {
1420                if (tsp->tv_sec < 0)
1421                        return (EINVAL);
1422                if (tsp->tv_nsec < 0 || tsp->tv_nsec >= 1000000000)
1423                        return (EINVAL);
1424                if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
1425                        sbt = 0;
1426                else {
1427                        ts = *tsp;
1428                        if (ts.tv_sec > INT32_MAX / 2) {
1429                                over = ts.tv_sec - INT32_MAX / 2;
1430                                ts.tv_sec -= over;
1431                        } else
1432                                over = 0;
1433                        tmp = tstosbt(ts);
1434                        precision = tmp;
1435                        precision >>= tc_precexp;
1436                        if (TIMESEL(&sbt, tmp))
1437                                sbt += tc_tick_sbt;
1438                        sbt += tmp;
1439                }
1440        } else
1441                sbt = -1;
1442
1443#ifndef __rtems__
1444        if (nfds > maxfilesperproc && nfds > FD_SETSIZE)
1445#else /* __rtems__ */
1446        if (nfds > rtems_libio_number_iops)
1447#endif /* __rtems__ */
1448                return (EINVAL);
1449        ni = nfds * sizeof(struct pollfd);
1450        if (ni > sizeof(smallbits))
1451                bits = malloc(ni, M_TEMP, M_WAITOK);
1452        else
1453                bits = smallbits;
1454        error = copyin(fds, bits, ni);
1455        if (error)
1456                goto done;
1457
1458#ifndef __rtems__
1459        if (uset != NULL) {
1460                error = kern_sigprocmask(td, SIG_SETMASK, uset,
1461                    &td->td_oldsigmask, 0);
1462                if (error)
1463                        goto done;
1464                td->td_pflags |= TDP_OLDMASK;
1465                /*
1466                 * Make sure that ast() is called on return to
1467                 * usermode and TDP_OLDMASK is cleared, restoring old
1468                 * sigmask.
1469                 */
1470                thread_lock(td);
1471                td->td_flags |= TDF_ASTPENDING;
1472                thread_unlock(td);
1473        }
1474#endif /* __rtems__ */
1475
1476        seltdinit(td);
1477        /* Iterate until the timeout expires or descriptors become ready. */
1478        for (;;) {
1479                error = pollscan(td, bits, nfds);
1480                if (error || td->td_retval[0] != 0)
1481                        break;
1482                error = seltdwait(td, sbt, precision);
1483                if (error)
1484                        break;
1485                error = pollrescan(td);
1486                if (error || td->td_retval[0] != 0)
1487                        break;
1488        }
1489        seltdclear(td);
1490
1491done:
1492        /* poll is not restarted after signals... */
1493        if (error == ERESTART)
1494                error = EINTR;
1495        if (error == EWOULDBLOCK)
1496                error = 0;
1497        if (error == 0) {
1498                error = pollout(td, bits, fds, nfds);
1499                if (error)
1500                        goto out;
1501        }
1502out:
1503        if (ni > sizeof(smallbits))
1504                free(bits, M_TEMP);
1505        return (error);
1506}
1507#ifdef __rtems__
1508int
1509poll(struct pollfd fds[], nfds_t nfds, int timeout)
1510{
1511        struct thread *td = rtems_bsd_get_curthread_or_null();
1512        struct poll_args ua = {
1513                .fds = &fds[0],
1514                .nfds = nfds,
1515                .timeout = timeout
1516        };
1517        int error;
1518
1519        if (td != NULL) {
1520                error = sys_poll(td, &ua);
1521        } else {
1522                error = ENOMEM;
1523        }
1524
1525        if (error == 0) {
1526                return td->td_retval[0];
1527        } else {
1528                rtems_set_errno_and_return_minus_one(error);
1529        }
1530}
1531#endif /* __rtems__ */
1532
1533#ifndef __rtems__
1534int
1535sys_ppoll(struct thread *td, struct ppoll_args *uap)
1536{
1537        struct timespec ts, *tsp;
1538        sigset_t set, *ssp;
1539        int error;
1540
1541        if (uap->ts != NULL) {
1542                error = copyin(uap->ts, &ts, sizeof(ts));
1543                if (error)
1544                        return (error);
1545                tsp = &ts;
1546        } else
1547                tsp = NULL;
1548        if (uap->set != NULL) {
1549                error = copyin(uap->set, &set, sizeof(set));
1550                if (error)
1551                        return (error);
1552                ssp = &set;
1553        } else
1554                ssp = NULL;
1555        /*
1556         * fds is still a pointer to user space. kern_poll() will
1557         * take care of copyin that array to the kernel space.
1558         */
1559
1560        return (kern_poll(td, uap->fds, uap->nfds, tsp, ssp));
1561}
1562#endif /* __rtems__ */
1563
1564static int
1565pollrescan(struct thread *td)
1566{
1567        struct seltd *stp;
1568        struct selfd *sfp;
1569        struct selfd *sfn;
1570        struct selinfo *si;
1571        struct filedesc *fdp;
1572        struct file *fp;
1573        struct pollfd *fd;
1574#ifdef CAPABILITIES
1575        cap_rights_t rights;
1576#endif
1577        int n;
1578
1579        n = 0;
1580#ifndef __rtems__
1581        fdp = td->td_proc->p_fd;
1582#else /* __rtems__ */
1583        fdp = NULL;
1584#endif /* __rtems__ */
1585        stp = td->td_sel;
1586        FILEDESC_SLOCK(fdp);
1587        STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1588                fd = (struct pollfd *)sfp->sf_cookie;
1589                si = sfp->sf_si;
1590                selfdfree(stp, sfp);
1591                /* If the selinfo wasn't cleared the event didn't fire. */
1592                if (si != NULL)
1593                        continue;
1594#ifndef __rtems__
1595                fp = fdp->fd_ofiles[fd->fd].fde_file;
1596#else /* __rtems__ */
1597                fget_unlocked(fdp, fd->fd, NULL, &fp, NULL);
1598#endif /* __rtems__ */
1599#ifdef CAPABILITIES
1600                if (fp == NULL ||
1601                    cap_check(cap_rights(fdp, fd->fd),
1602                    cap_rights_init(&rights, CAP_EVENT)) != 0)
1603#else
1604                if (fp == NULL)
1605#endif
1606                {
1607                        fd->revents = POLLNVAL;
1608                        n++;
1609                        continue;
1610                }
1611
1612                /*
1613                 * Note: backend also returns POLLHUP and
1614                 * POLLERR if appropriate.
1615                 */
1616                fd->revents = fo_poll(fp, fd->events, td->td_ucred, td);
1617                if (fd->revents != 0)
1618                        n++;
1619        }
1620        FILEDESC_SUNLOCK(fdp);
1621        stp->st_flags = 0;
1622        td->td_retval[0] = n;
1623        return (0);
1624}
1625
1626
1627static int
1628pollout(td, fds, ufds, nfd)
1629        struct thread *td;
1630        struct pollfd *fds;
1631        struct pollfd *ufds;
1632        u_int nfd;
1633{
1634        int error = 0;
1635        u_int i = 0;
1636        u_int n = 0;
1637
1638        for (i = 0; i < nfd; i++) {
1639                error = copyout(&fds->revents, &ufds->revents,
1640                    sizeof(ufds->revents));
1641                if (error)
1642                        return (error);
1643                if (fds->revents != 0)
1644                        n++;
1645                fds++;
1646                ufds++;
1647        }
1648        td->td_retval[0] = n;
1649        return (0);
1650}
1651
1652static int
1653pollscan(td, fds, nfd)
1654        struct thread *td;
1655        struct pollfd *fds;
1656        u_int nfd;
1657{
1658#ifndef __rtems__
1659        struct filedesc *fdp = td->td_proc->p_fd;
1660#else /* __rtems__ */
1661        struct filedesc *fdp = NULL;
1662#endif /* __rtems__ */
1663        struct file *fp;
1664#ifdef CAPABILITIES
1665        cap_rights_t rights;
1666#endif
1667        int i, n = 0;
1668
1669        FILEDESC_SLOCK(fdp);
1670        for (i = 0; i < nfd; i++, fds++) {
1671#ifndef __rtems__
1672                if (fds->fd > fdp->fd_lastfile) {
1673#else /* __rtems__ */
1674                if (fds->fd >= rtems_libio_number_iops) {
1675#endif /* __rtems__ */
1676                        fds->revents = POLLNVAL;
1677                        n++;
1678                } else if (fds->fd < 0) {
1679                        fds->revents = 0;
1680                } else {
1681#ifndef __rtems__
1682                        fp = fdp->fd_ofiles[fds->fd].fde_file;
1683#else /* __rtems__ */
1684                        fget_unlocked(fdp, fds->fd, NULL, &fp, NULL);
1685#endif /* __rtems__ */
1686#ifdef CAPABILITIES
1687                        if (fp == NULL ||
1688                            cap_check(cap_rights(fdp, fds->fd),
1689                            cap_rights_init(&rights, CAP_EVENT)) != 0)
1690#else
1691                        if (fp == NULL)
1692#endif
1693                        {
1694                                fds->revents = POLLNVAL;
1695                                n++;
1696                        } else {
1697                                /*
1698                                 * Note: backend also returns POLLHUP and
1699                                 * POLLERR if appropriate.
1700                                 */
1701                                selfdalloc(td, fds);
1702                                fds->revents = fo_poll(fp, fds->events,
1703                                    td->td_ucred, td);
1704                                /*
1705                                 * POSIX requires POLLOUT to be never
1706                                 * set simultaneously with POLLHUP.
1707                                 */
1708                                if ((fds->revents & POLLHUP) != 0)
1709                                        fds->revents &= ~POLLOUT;
1710
1711                                if (fds->revents != 0)
1712                                        n++;
1713                        }
1714                }
1715        }
1716        FILEDESC_SUNLOCK(fdp);
1717        td->td_retval[0] = n;
1718        return (0);
1719}
1720
1721#ifndef __rtems__
1722/*
1723 * XXX This was created specifically to support netncp and netsmb.  This
1724 * allows the caller to specify a socket to wait for events on.  It returns
1725 * 0 if any events matched and an error otherwise.  There is no way to
1726 * determine which events fired.
1727 */
1728int
1729selsocket(struct socket *so, int events, struct timeval *tvp, struct thread *td)
1730{
1731        struct timeval rtv;
1732        sbintime_t asbt, precision, rsbt;
1733        int error;
1734
1735        precision = 0;  /* stupid gcc! */
1736        if (tvp != NULL) {
1737                rtv = *tvp;
1738                if (rtv.tv_sec < 0 || rtv.tv_usec < 0 ||
1739                    rtv.tv_usec >= 1000000)
1740                        return (EINVAL);
1741                if (!timevalisset(&rtv))
1742                        asbt = 0;
1743                else if (rtv.tv_sec <= INT32_MAX) {
1744                        rsbt = tvtosbt(rtv);
1745                        precision = rsbt;
1746                        precision >>= tc_precexp;
1747                        if (TIMESEL(&asbt, rsbt))
1748                                asbt += tc_tick_sbt;
1749                        if (asbt <= SBT_MAX - rsbt)
1750                                asbt += rsbt;
1751                        else
1752                                asbt = -1;
1753                } else
1754                        asbt = -1;
1755        } else
1756                asbt = -1;
1757        seltdinit(td);
1758        /*
1759         * Iterate until the timeout expires or the socket becomes ready.
1760         */
1761        for (;;) {
1762                selfdalloc(td, NULL);
1763                error = sopoll(so, events, NULL, td);
1764                /* error here is actually the ready events. */
1765                if (error)
1766                        return (0);
1767                error = seltdwait(td, asbt, precision);
1768                if (error)
1769                        break;
1770        }
1771        seltdclear(td);
1772        /* XXX Duplicates ncp/smb behavior. */
1773        if (error == ERESTART)
1774                error = 0;
1775        return (error);
1776}
1777#endif /* __rtems__ */
1778
1779/*
1780 * Preallocate two selfds associated with 'cookie'.  Some fo_poll routines
1781 * have two select sets, one for read and another for write.
1782 */
1783static void
1784selfdalloc(struct thread *td, void *cookie)
1785{
1786        struct seltd *stp;
1787
1788        stp = td->td_sel;
1789        if (stp->st_free1 == NULL)
1790                stp->st_free1 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1791        stp->st_free1->sf_td = stp;
1792        stp->st_free1->sf_cookie = cookie;
1793        if (stp->st_free2 == NULL)
1794                stp->st_free2 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1795        stp->st_free2->sf_td = stp;
1796        stp->st_free2->sf_cookie = cookie;
1797}
1798
1799static void
1800selfdfree(struct seltd *stp, struct selfd *sfp)
1801{
1802        STAILQ_REMOVE(&stp->st_selq, sfp, selfd, sf_link);
1803        if (sfp->sf_si != NULL) {
1804                mtx_lock(sfp->sf_mtx);
1805                if (sfp->sf_si != NULL) {
1806                        TAILQ_REMOVE(&sfp->sf_si->si_tdlist, sfp, sf_threads);
1807                        refcount_release(&sfp->sf_refs);
1808                }
1809                mtx_unlock(sfp->sf_mtx);
1810        }
1811        if (refcount_release(&sfp->sf_refs))
1812                uma_zfree(selfd_zone, sfp);
1813}
1814
1815/* Drain the waiters tied to all the selfd belonging the specified selinfo. */
1816void
1817seldrain(sip)
1818        struct selinfo *sip;
1819{
1820
1821        /*
1822         * This feature is already provided by doselwakeup(), thus it is
1823         * enough to go for it.
1824         * Eventually, the context, should take care to avoid races
1825         * between thread calling select()/poll() and file descriptor
1826         * detaching, but, again, the races are just the same as
1827         * selwakeup().
1828         */
1829        doselwakeup(sip, -1);
1830}
1831
1832/*
1833 * Record a select request.
1834 */
1835void
1836selrecord(selector, sip)
1837        struct thread *selector;
1838        struct selinfo *sip;
1839{
1840        struct selfd *sfp;
1841        struct seltd *stp;
1842        struct mtx *mtxp;
1843
1844        stp = selector->td_sel;
1845        /*
1846         * Don't record when doing a rescan.
1847         */
1848        if (stp->st_flags & SELTD_RESCAN)
1849                return;
1850        /*
1851         * Grab one of the preallocated descriptors.
1852         */
1853        sfp = NULL;
1854        if ((sfp = stp->st_free1) != NULL)
1855                stp->st_free1 = NULL;
1856        else if ((sfp = stp->st_free2) != NULL)
1857                stp->st_free2 = NULL;
1858        else
1859                panic("selrecord: No free selfd on selq");
1860        mtxp = sip->si_mtx;
1861        if (mtxp == NULL)
1862                mtxp = mtx_pool_find(mtxpool_select, sip);
1863        /*
1864         * Initialize the sfp and queue it in the thread.
1865         */
1866        sfp->sf_si = sip;
1867        sfp->sf_mtx = mtxp;
1868        refcount_init(&sfp->sf_refs, 2);
1869        STAILQ_INSERT_TAIL(&stp->st_selq, sfp, sf_link);
1870        /*
1871         * Now that we've locked the sip, check for initialization.
1872         */
1873        mtx_lock(mtxp);
1874        if (sip->si_mtx == NULL) {
1875                sip->si_mtx = mtxp;
1876                TAILQ_INIT(&sip->si_tdlist);
1877        }
1878        /*
1879         * Add this thread to the list of selfds listening on this selinfo.
1880         */
1881        TAILQ_INSERT_TAIL(&sip->si_tdlist, sfp, sf_threads);
1882        mtx_unlock(sip->si_mtx);
1883}
1884
1885/* Wake up a selecting thread. */
1886void
1887selwakeup(sip)
1888        struct selinfo *sip;
1889{
1890        doselwakeup(sip, -1);
1891}
1892
1893/* Wake up a selecting thread, and set its priority. */
1894void
1895selwakeuppri(sip, pri)
1896        struct selinfo *sip;
1897        int pri;
1898{
1899        doselwakeup(sip, pri);
1900}
1901
1902/*
1903 * Do a wakeup when a selectable event occurs.
1904 */
1905static void
1906doselwakeup(sip, pri)
1907        struct selinfo *sip;
1908        int pri;
1909{
1910        struct selfd *sfp;
1911        struct selfd *sfn;
1912        struct seltd *stp;
1913
1914        /* If it's not initialized there can't be any waiters. */
1915        if (sip->si_mtx == NULL)
1916                return;
1917        /*
1918         * Locking the selinfo locks all selfds associated with it.
1919         */
1920        mtx_lock(sip->si_mtx);
1921        TAILQ_FOREACH_SAFE(sfp, &sip->si_tdlist, sf_threads, sfn) {
1922                /*
1923                 * Once we remove this sfp from the list and clear the
1924                 * sf_si seltdclear will know to ignore this si.
1925                 */
1926                TAILQ_REMOVE(&sip->si_tdlist, sfp, sf_threads);
1927                sfp->sf_si = NULL;
1928                stp = sfp->sf_td;
1929                mtx_lock(&stp->st_mtx);
1930                stp->st_flags |= SELTD_PENDING;
1931                cv_broadcastpri(&stp->st_wait, pri);
1932                mtx_unlock(&stp->st_mtx);
1933                if (refcount_release(&sfp->sf_refs))
1934                        uma_zfree(selfd_zone, sfp);
1935        }
1936        mtx_unlock(sip->si_mtx);
1937}
1938
1939static void
1940seltdinit(struct thread *td)
1941{
1942        struct seltd *stp;
1943
1944        if ((stp = td->td_sel) != NULL)
1945                goto out;
1946        td->td_sel = stp = malloc(sizeof(*stp), M_SELECT, M_WAITOK|M_ZERO);
1947        mtx_init(&stp->st_mtx, "sellck", NULL, MTX_DEF);
1948        cv_init(&stp->st_wait, "select");
1949out:
1950        stp->st_flags = 0;
1951        STAILQ_INIT(&stp->st_selq);
1952}
1953
1954static int
1955seltdwait(struct thread *td, sbintime_t sbt, sbintime_t precision)
1956{
1957        struct seltd *stp;
1958        int error;
1959
1960        stp = td->td_sel;
1961        /*
1962         * An event of interest may occur while we do not hold the seltd
1963         * locked so check the pending flag before we sleep.
1964         */
1965        mtx_lock(&stp->st_mtx);
1966        /*
1967         * Any further calls to selrecord will be a rescan.
1968         */
1969        stp->st_flags |= SELTD_RESCAN;
1970        if (stp->st_flags & SELTD_PENDING) {
1971                mtx_unlock(&stp->st_mtx);
1972                return (0);
1973        }
1974        if (sbt == 0)
1975                error = EWOULDBLOCK;
1976        else if (sbt != -1)
1977                error = cv_timedwait_sig_sbt(&stp->st_wait, &stp->st_mtx,
1978                    sbt, precision, C_ABSOLUTE);
1979        else
1980                error = cv_wait_sig(&stp->st_wait, &stp->st_mtx);
1981        mtx_unlock(&stp->st_mtx);
1982
1983        return (error);
1984}
1985
1986void
1987seltdfini(struct thread *td)
1988{
1989        struct seltd *stp;
1990
1991        stp = td->td_sel;
1992        if (stp == NULL)
1993                return;
1994        if (stp->st_free1)
1995                uma_zfree(selfd_zone, stp->st_free1);
1996        if (stp->st_free2)
1997                uma_zfree(selfd_zone, stp->st_free2);
1998        td->td_sel = NULL;
1999        free(stp, M_SELECT);
2000}
2001
2002/*
2003 * Remove the references to the thread from all of the objects we were
2004 * polling.
2005 */
2006static void
2007seltdclear(struct thread *td)
2008{
2009        struct seltd *stp;
2010        struct selfd *sfp;
2011        struct selfd *sfn;
2012
2013        stp = td->td_sel;
2014        STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn)
2015                selfdfree(stp, sfp);
2016        stp->st_flags = 0;
2017}
2018
2019static void selectinit(void *);
2020SYSINIT(select, SI_SUB_SYSCALLS, SI_ORDER_ANY, selectinit, NULL);
2021static void
2022selectinit(void *dummy __unused)
2023{
2024
2025        selfd_zone = uma_zcreate("selfd", sizeof(struct selfd), NULL, NULL,
2026            NULL, NULL, UMA_ALIGN_PTR, 0);
2027        mtxpool_select = mtx_pool_create("select mtxpool", 128, MTX_DEF);
2028}
2029
2030#ifndef __rtems__
2031/*
2032 * Set up a syscall return value that follows the convention specified for
2033 * posix_* functions.
2034 */
2035int
2036kern_posix_error(struct thread *td, int error)
2037{
2038
2039        if (error <= 0)
2040                return (error);
2041        td->td_errno = error;
2042        td->td_pflags |= TDP_NERRNO;
2043        td->td_retval[0] = error;
2044        return (0);
2045}
2046#endif /* __rtems__ */
2047#ifdef __rtems__
2048#include <machine/rtems-bsd-thread.h>
2049
2050#undef ticks
2051
2052#include <rtems/score/objectimpl.h>
2053#include <rtems/score/threadimpl.h>
2054
2055#include <rtems/bsd/util.h>
2056
2057static void
2058force_select_timeout(Thread_Control *thread)
2059{
2060        struct thread *td = rtems_bsd_get_thread(thread);
2061
2062        if (td != NULL) {
2063                struct seltd *stp = td->td_sel;
2064
2065                cv_broadcastpri(&stp->st_wait, 0);
2066        }
2067}
2068
2069rtems_status_code rtems_bsd_force_select_timeout(rtems_id task_id)
2070{
2071        Thread_Control *thread;
2072        ISR_lock_Context lock_context;
2073
2074        thread = _Thread_Get(task_id, &lock_context);
2075        if (thread == NULL) {
2076#if defined(RTEMS_MULTIPROCESSING)
2077                if (_Thread_MP_Is_remote(id)) {
2078                        return (RTEMS_ILLEGAL_ON_REMOTE_OBJECT);
2079                }
2080#endif
2081
2082                return (RTEMS_INVALID_ID);
2083        }
2084
2085        _ISR_lock_ISR_enable(&lock_context);
2086        force_select_timeout(thread);
2087        return (RTEMS_SUCCESSFUL);
2088}
2089#endif /* __rtems__ */
Note: See TracBrowser for help on using the repository browser.