]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/sys_pipe.c
Re-apply reverted parts of r236935 by pjd with some changes.
[FreeBSD/FreeBSD.git] / sys / kern / sys_pipe.c
1 /*-
2  * Copyright (c) 1996 John S. Dyson
3  * Copyright (c) 2012 Giovanni Trematerra
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice immediately at the beginning of the file, without modification,
11  *    this list of conditions, and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Absolutely no warranty of function or purpose is made by the author
16  *    John S. Dyson.
17  * 4. Modifications may be freely made to this file if the above conditions
18  *    are met.
19  */
20
21 /*
22  * This file contains a high-performance replacement for the socket-based
23  * pipes scheme originally used in FreeBSD/4.4Lite.  It does not support
24  * all features of sockets, but does do everything that pipes normally
25  * do.
26  */
27
28 /*
29  * This code has two modes of operation, a small write mode and a large
30  * write mode.  The small write mode acts like conventional pipes with
31  * a kernel buffer.  If the buffer is less than PIPE_MINDIRECT, then the
32  * "normal" pipe buffering is done.  If the buffer is between PIPE_MINDIRECT
33  * and PIPE_SIZE in size, the sending process pins the underlying pages in
34  * memory, and the receiving process copies directly from these pinned pages
35  * in the sending process.
36  *
37  * If the sending process receives a signal, it is possible that it will
38  * go away, and certainly its address space can change, because control
39  * is returned back to the user-mode side.  In that case, the pipe code
40  * arranges to copy the buffer supplied by the user process, to a pageable
41  * kernel buffer, and the receiving process will grab the data from the
42  * pageable kernel buffer.  Since signals don't happen all that often,
43  * the copy operation is normally eliminated.
44  *
45  * The constant PIPE_MINDIRECT is chosen to make sure that buffering will
46  * happen for small transfers so that the system will not spend all of
47  * its time context switching.
48  *
49  * In order to limit the resource use of pipes, two sysctls exist:
50  *
51  * kern.ipc.maxpipekva - This is a hard limit on the amount of pageable
52  * address space available to us in pipe_map. This value is normally
53  * autotuned, but may also be loader tuned.
54  *
55  * kern.ipc.pipekva - This read-only sysctl tracks the current amount of
56  * memory in use by pipes.
57  *
58  * Based on how large pipekva is relative to maxpipekva, the following
59  * will happen:
60  *
61  * 0% - 50%:
62  *     New pipes are given 16K of memory backing, pipes may dynamically
63  *     grow to as large as 64K where needed.
64  * 50% - 75%:
65  *     New pipes are given 4K (or PAGE_SIZE) of memory backing,
66  *     existing pipes may NOT grow.
67  * 75% - 100%:
68  *     New pipes are given 4K (or PAGE_SIZE) of memory backing,
69  *     existing pipes will be shrunk down to 4K whenever possible.
70  *
71  * Resizing may be disabled by setting kern.ipc.piperesizeallowed=0.  If
72  * that is set,  the only resize that will occur is the 0 -> SMALL_PIPE_SIZE
73  * resize which MUST occur for reverse-direction pipes when they are
74  * first used.
75  *
76  * Additional information about the current state of pipes may be obtained
77  * from kern.ipc.pipes, kern.ipc.pipefragretry, kern.ipc.pipeallocfail,
78  * and kern.ipc.piperesizefail.
79  *
80  * Locking rules:  There are two locks present here:  A mutex, used via
81  * PIPE_LOCK, and a flag, used via pipelock().  All locking is done via
82  * the flag, as mutexes can not persist over uiomove.  The mutex
83  * exists only to guard access to the flag, and is not in itself a
84  * locking mechanism.  Also note that there is only a single mutex for
85  * both directions of a pipe.
86  *
87  * As pipelock() may have to sleep before it can acquire the flag, it
88  * is important to reread all data after a call to pipelock(); everything
89  * in the structure may have changed.
90  */
91
92 #include <sys/cdefs.h>
93 __FBSDID("$FreeBSD$");
94
95 #include <sys/param.h>
96 #include <sys/systm.h>
97 #include <sys/conf.h>
98 #include <sys/fcntl.h>
99 #include <sys/file.h>
100 #include <sys/filedesc.h>
101 #include <sys/filio.h>
102 #include <sys/kernel.h>
103 #include <sys/lock.h>
104 #include <sys/mutex.h>
105 #include <sys/ttycom.h>
106 #include <sys/stat.h>
107 #include <sys/malloc.h>
108 #include <sys/poll.h>
109 #include <sys/selinfo.h>
110 #include <sys/signalvar.h>
111 #include <sys/syscallsubr.h>
112 #include <sys/sysctl.h>
113 #include <sys/sysproto.h>
114 #include <sys/pipe.h>
115 #include <sys/proc.h>
116 #include <sys/vnode.h>
117 #include <sys/uio.h>
118 #include <sys/event.h>
119
120 #include <security/mac/mac_framework.h>
121
122 #include <vm/vm.h>
123 #include <vm/vm_param.h>
124 #include <vm/vm_object.h>
125 #include <vm/vm_kern.h>
126 #include <vm/vm_extern.h>
127 #include <vm/pmap.h>
128 #include <vm/vm_map.h>
129 #include <vm/vm_page.h>
130 #include <vm/uma.h>
131
132 /* XXX */
133 int     do_pipe(struct thread *td, int fildes[2], int flags);
134
135 /*
136  * Use this define if you want to disable *fancy* VM things.  Expect an
137  * approx 30% decrease in transfer rate.  This could be useful for
138  * NetBSD or OpenBSD.
139  */
140 /* #define PIPE_NODIRECT */
141
142 #define PIPE_PEER(pipe) \
143         (((pipe)->pipe_state & PIPE_NAMED) ? (pipe) : ((pipe)->pipe_peer))
144
145 /*
146  * interfaces to the outside world
147  */
148 static fo_rdwr_t        pipe_read;
149 static fo_rdwr_t        pipe_write;
150 static fo_truncate_t    pipe_truncate;
151 static fo_ioctl_t       pipe_ioctl;
152 static fo_poll_t        pipe_poll;
153 static fo_kqfilter_t    pipe_kqfilter;
154 static fo_stat_t        pipe_stat;
155 static fo_close_t       pipe_close;
156 static fo_chmod_t       pipe_chmod;
157 static fo_chown_t       pipe_chown;
158
159 struct fileops pipeops = {
160         .fo_read = pipe_read,
161         .fo_write = pipe_write,
162         .fo_truncate = pipe_truncate,
163         .fo_ioctl = pipe_ioctl,
164         .fo_poll = pipe_poll,
165         .fo_kqfilter = pipe_kqfilter,
166         .fo_stat = pipe_stat,
167         .fo_close = pipe_close,
168         .fo_chmod = pipe_chmod,
169         .fo_chown = pipe_chown,
170         .fo_flags = DFLAG_PASSABLE
171 };
172
173 static void     filt_pipedetach(struct knote *kn);
174 static void     filt_pipedetach_notsup(struct knote *kn);
175 static int      filt_pipenotsup(struct knote *kn, long hint);
176 static int      filt_piperead(struct knote *kn, long hint);
177 static int      filt_pipewrite(struct knote *kn, long hint);
178
179 static struct filterops pipe_nfiltops = {
180         .f_isfd = 1,
181         .f_detach = filt_pipedetach_notsup,
182         .f_event = filt_pipenotsup
183 };
184 static struct filterops pipe_rfiltops = {
185         .f_isfd = 1,
186         .f_detach = filt_pipedetach,
187         .f_event = filt_piperead
188 };
189 static struct filterops pipe_wfiltops = {
190         .f_isfd = 1,
191         .f_detach = filt_pipedetach,
192         .f_event = filt_pipewrite
193 };
194
195 /*
196  * Default pipe buffer size(s), this can be kind-of large now because pipe
197  * space is pageable.  The pipe code will try to maintain locality of
198  * reference for performance reasons, so small amounts of outstanding I/O
199  * will not wipe the cache.
200  */
201 #define MINPIPESIZE (PIPE_SIZE/3)
202 #define MAXPIPESIZE (2*PIPE_SIZE/3)
203
204 static long amountpipekva;
205 static int pipefragretry;
206 static int pipeallocfail;
207 static int piperesizefail;
208 static int piperesizeallowed = 1;
209
210 SYSCTL_LONG(_kern_ipc, OID_AUTO, maxpipekva, CTLFLAG_RDTUN,
211            &maxpipekva, 0, "Pipe KVA limit");
212 SYSCTL_LONG(_kern_ipc, OID_AUTO, pipekva, CTLFLAG_RD,
213            &amountpipekva, 0, "Pipe KVA usage");
214 SYSCTL_INT(_kern_ipc, OID_AUTO, pipefragretry, CTLFLAG_RD,
215           &pipefragretry, 0, "Pipe allocation retries due to fragmentation");
216 SYSCTL_INT(_kern_ipc, OID_AUTO, pipeallocfail, CTLFLAG_RD,
217           &pipeallocfail, 0, "Pipe allocation failures");
218 SYSCTL_INT(_kern_ipc, OID_AUTO, piperesizefail, CTLFLAG_RD,
219           &piperesizefail, 0, "Pipe resize failures");
220 SYSCTL_INT(_kern_ipc, OID_AUTO, piperesizeallowed, CTLFLAG_RW,
221           &piperesizeallowed, 0, "Pipe resizing allowed");
222
223 static void pipeinit(void *dummy __unused);
224 static void pipeclose(struct pipe *cpipe);
225 static void pipe_free_kmem(struct pipe *cpipe);
226 static int pipe_create(struct pipe *pipe, int backing);
227 static int pipe_paircreate(struct thread *td, struct pipepair **p_pp);
228 static __inline int pipelock(struct pipe *cpipe, int catch);
229 static __inline void pipeunlock(struct pipe *cpipe);
230 static __inline void pipeselwakeup(struct pipe *cpipe);
231 #ifndef PIPE_NODIRECT
232 static int pipe_build_write_buffer(struct pipe *wpipe, struct uio *uio);
233 static void pipe_destroy_write_buffer(struct pipe *wpipe);
234 static int pipe_direct_write(struct pipe *wpipe, struct uio *uio);
235 static void pipe_clone_write_buffer(struct pipe *wpipe);
236 #endif
237 static int pipespace(struct pipe *cpipe, int size);
238 static int pipespace_new(struct pipe *cpipe, int size);
239
240 static int      pipe_zone_ctor(void *mem, int size, void *arg, int flags);
241 static int      pipe_zone_init(void *mem, int size, int flags);
242 static void     pipe_zone_fini(void *mem, int size);
243
244 static uma_zone_t pipe_zone;
245 static struct unrhdr *pipeino_unr;
246 static dev_t pipedev_ino;
247
248 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_ANY, pipeinit, NULL);
249
250 static void
251 pipeinit(void *dummy __unused)
252 {
253
254         pipe_zone = uma_zcreate("pipe", sizeof(struct pipepair),
255             pipe_zone_ctor, NULL, pipe_zone_init, pipe_zone_fini,
256             UMA_ALIGN_PTR, 0);
257         KASSERT(pipe_zone != NULL, ("pipe_zone not initialized"));
258         pipeino_unr = new_unrhdr(1, INT32_MAX, NULL);
259         KASSERT(pipeino_unr != NULL, ("pipe fake inodes not initialized"));
260         pipedev_ino = devfs_alloc_cdp_inode();
261         KASSERT(pipedev_ino > 0, ("pipe dev inode not initialized"));
262 }
263
264 static int
265 pipe_zone_ctor(void *mem, int size, void *arg, int flags)
266 {
267         struct pipepair *pp;
268         struct pipe *rpipe, *wpipe;
269
270         KASSERT(size == sizeof(*pp), ("pipe_zone_ctor: wrong size"));
271
272         pp = (struct pipepair *)mem;
273
274         /*
275          * We zero both pipe endpoints to make sure all the kmem pointers
276          * are NULL, flag fields are zero'd, etc.  We timestamp both
277          * endpoints with the same time.
278          */
279         rpipe = &pp->pp_rpipe;
280         bzero(rpipe, sizeof(*rpipe));
281         vfs_timestamp(&rpipe->pipe_ctime);
282         rpipe->pipe_atime = rpipe->pipe_mtime = rpipe->pipe_ctime;
283
284         wpipe = &pp->pp_wpipe;
285         bzero(wpipe, sizeof(*wpipe));
286         wpipe->pipe_ctime = rpipe->pipe_ctime;
287         wpipe->pipe_atime = wpipe->pipe_mtime = rpipe->pipe_ctime;
288
289         rpipe->pipe_peer = wpipe;
290         rpipe->pipe_pair = pp;
291         wpipe->pipe_peer = rpipe;
292         wpipe->pipe_pair = pp;
293
294         /*
295          * Mark both endpoints as present; they will later get free'd
296          * one at a time.  When both are free'd, then the whole pair
297          * is released.
298          */
299         rpipe->pipe_present = PIPE_ACTIVE;
300         wpipe->pipe_present = PIPE_ACTIVE;
301
302         /*
303          * Eventually, the MAC Framework may initialize the label
304          * in ctor or init, but for now we do it elswhere to avoid
305          * blocking in ctor or init.
306          */
307         pp->pp_label = NULL;
308
309         return (0);
310 }
311
312 static int
313 pipe_zone_init(void *mem, int size, int flags)
314 {
315         struct pipepair *pp;
316
317         KASSERT(size == sizeof(*pp), ("pipe_zone_init: wrong size"));
318
319         pp = (struct pipepair *)mem;
320
321         mtx_init(&pp->pp_mtx, "pipe mutex", NULL, MTX_DEF | MTX_RECURSE);
322         return (0);
323 }
324
325 static void
326 pipe_zone_fini(void *mem, int size)
327 {
328         struct pipepair *pp;
329
330         KASSERT(size == sizeof(*pp), ("pipe_zone_fini: wrong size"));
331
332         pp = (struct pipepair *)mem;
333
334         mtx_destroy(&pp->pp_mtx);
335 }
336
337 static int
338 pipe_paircreate(struct thread *td, struct pipepair **p_pp)
339 {
340         struct pipepair *pp;
341         struct pipe *rpipe, *wpipe;
342         int error;
343
344         *p_pp = pp = uma_zalloc(pipe_zone, M_WAITOK);
345 #ifdef MAC
346         /*
347          * The MAC label is shared between the connected endpoints.  As a
348          * result mac_pipe_init() and mac_pipe_create() are called once
349          * for the pair, and not on the endpoints.
350          */
351         mac_pipe_init(pp);
352         mac_pipe_create(td->td_ucred, pp);
353 #endif
354         rpipe = &pp->pp_rpipe;
355         wpipe = &pp->pp_wpipe;
356
357         knlist_init_mtx(&rpipe->pipe_sel.si_note, PIPE_MTX(rpipe));
358         knlist_init_mtx(&wpipe->pipe_sel.si_note, PIPE_MTX(wpipe));
359
360         /* Only the forward direction pipe is backed by default */
361         if ((error = pipe_create(rpipe, 1)) != 0 ||
362             (error = pipe_create(wpipe, 0)) != 0) {
363                 pipeclose(rpipe);
364                 pipeclose(wpipe);
365                 return (error);
366         }
367
368         rpipe->pipe_state |= PIPE_DIRECTOK;
369         wpipe->pipe_state |= PIPE_DIRECTOK;
370         return (0);
371 }
372
373 int
374 pipe_named_ctor(struct pipe **ppipe, struct thread *td)
375 {
376         struct pipepair *pp;
377         int error;
378
379         error = pipe_paircreate(td, &pp);
380         if (error != 0)
381                 return (error);
382         pp->pp_rpipe.pipe_state |= PIPE_NAMED;
383         *ppipe = &pp->pp_rpipe;
384         return (0);
385 }
386
387 void
388 pipe_dtor(struct pipe *dpipe)
389 {
390         ino_t ino;
391
392         ino = dpipe->pipe_ino;
393         funsetown(&dpipe->pipe_sigio);
394         pipeclose(dpipe);
395         if (dpipe->pipe_state & PIPE_NAMED) {
396                 dpipe = dpipe->pipe_peer;
397                 funsetown(&dpipe->pipe_sigio);
398                 pipeclose(dpipe);
399         }
400         if (ino != 0 && ino != (ino_t)-1)
401                 free_unr(pipeino_unr, ino);
402 }
403
404 /*
405  * The pipe system call for the DTYPE_PIPE type of pipes.  If we fail, let
406  * the zone pick up the pieces via pipeclose().
407  */
408 int
409 kern_pipe(struct thread *td, int fildes[2])
410 {
411
412         return (do_pipe(td, fildes, 0));
413 }
414
415 int
416 do_pipe(struct thread *td, int fildes[2], int flags)
417 {
418         struct filedesc *fdp; 
419         struct file *rf, *wf;
420         struct pipe *rpipe, *wpipe;
421         struct pipepair *pp;
422         int fd, fflags, error;
423
424         fdp = td->td_proc->p_fd;
425         error = pipe_paircreate(td, &pp);
426         if (error != 0)
427                 return (error);
428         rpipe = &pp->pp_rpipe;
429         wpipe = &pp->pp_wpipe;
430         error = falloc(td, &rf, &fd, flags);
431         if (error) {
432                 pipeclose(rpipe);
433                 pipeclose(wpipe);
434                 return (error);
435         }
436         /* An extra reference on `rf' has been held for us by falloc(). */
437         fildes[0] = fd;
438
439         fflags = FREAD | FWRITE;
440         if ((flags & O_NONBLOCK) != 0)
441                 fflags |= FNONBLOCK;
442
443         /*
444          * Warning: once we've gotten past allocation of the fd for the
445          * read-side, we can only drop the read side via fdrop() in order
446          * to avoid races against processes which manage to dup() the read
447          * side while we are blocked trying to allocate the write side.
448          */
449         finit(rf, fflags, DTYPE_PIPE, rpipe, &pipeops);
450         error = falloc(td, &wf, &fd, flags);
451         if (error) {
452                 fdclose(fdp, rf, fildes[0], td);
453                 fdrop(rf, td);
454                 /* rpipe has been closed by fdrop(). */
455                 pipeclose(wpipe);
456                 return (error);
457         }
458         /* An extra reference on `wf' has been held for us by falloc(). */
459         finit(wf, fflags, DTYPE_PIPE, wpipe, &pipeops);
460         fdrop(wf, td);
461         fildes[1] = fd;
462         fdrop(rf, td);
463
464         return (0);
465 }
466
467 /* ARGSUSED */
468 int
469 sys_pipe(struct thread *td, struct pipe_args *uap)
470 {
471         int error;
472         int fildes[2];
473
474         error = kern_pipe(td, fildes);
475         if (error)
476                 return (error);
477         
478         td->td_retval[0] = fildes[0];
479         td->td_retval[1] = fildes[1];
480
481         return (0);
482 }
483
484 /*
485  * Allocate kva for pipe circular buffer, the space is pageable
486  * This routine will 'realloc' the size of a pipe safely, if it fails
487  * it will retain the old buffer.
488  * If it fails it will return ENOMEM.
489  */
490 static int
491 pipespace_new(cpipe, size)
492         struct pipe *cpipe;
493         int size;
494 {
495         caddr_t buffer;
496         int error, cnt, firstseg;
497         static int curfail = 0;
498         static struct timeval lastfail;
499
500         KASSERT(!mtx_owned(PIPE_MTX(cpipe)), ("pipespace: pipe mutex locked"));
501         KASSERT(!(cpipe->pipe_state & PIPE_DIRECTW),
502                 ("pipespace: resize of direct writes not allowed"));
503 retry:
504         cnt = cpipe->pipe_buffer.cnt;
505         if (cnt > size)
506                 size = cnt;
507
508         size = round_page(size);
509         buffer = (caddr_t) vm_map_min(pipe_map);
510
511         error = vm_map_find(pipe_map, NULL, 0,
512                 (vm_offset_t *) &buffer, size, 1,
513                 VM_PROT_ALL, VM_PROT_ALL, 0);
514         if (error != KERN_SUCCESS) {
515                 if ((cpipe->pipe_buffer.buffer == NULL) &&
516                         (size > SMALL_PIPE_SIZE)) {
517                         size = SMALL_PIPE_SIZE;
518                         pipefragretry++;
519                         goto retry;
520                 }
521                 if (cpipe->pipe_buffer.buffer == NULL) {
522                         pipeallocfail++;
523                         if (ppsratecheck(&lastfail, &curfail, 1))
524                                 printf("kern.ipc.maxpipekva exceeded; see tuning(7)\n");
525                 } else {
526                         piperesizefail++;
527                 }
528                 return (ENOMEM);
529         }
530
531         /* copy data, then free old resources if we're resizing */
532         if (cnt > 0) {
533                 if (cpipe->pipe_buffer.in <= cpipe->pipe_buffer.out) {
534                         firstseg = cpipe->pipe_buffer.size - cpipe->pipe_buffer.out;
535                         bcopy(&cpipe->pipe_buffer.buffer[cpipe->pipe_buffer.out],
536                                 buffer, firstseg);
537                         if ((cnt - firstseg) > 0)
538                                 bcopy(cpipe->pipe_buffer.buffer, &buffer[firstseg],
539                                         cpipe->pipe_buffer.in);
540                 } else {
541                         bcopy(&cpipe->pipe_buffer.buffer[cpipe->pipe_buffer.out],
542                                 buffer, cnt);
543                 }
544         }
545         pipe_free_kmem(cpipe);
546         cpipe->pipe_buffer.buffer = buffer;
547         cpipe->pipe_buffer.size = size;
548         cpipe->pipe_buffer.in = cnt;
549         cpipe->pipe_buffer.out = 0;
550         cpipe->pipe_buffer.cnt = cnt;
551         atomic_add_long(&amountpipekva, cpipe->pipe_buffer.size);
552         return (0);
553 }
554
555 /*
556  * Wrapper for pipespace_new() that performs locking assertions.
557  */
558 static int
559 pipespace(cpipe, size)
560         struct pipe *cpipe;
561         int size;
562 {
563
564         KASSERT(cpipe->pipe_state & PIPE_LOCKFL,
565                 ("Unlocked pipe passed to pipespace"));
566         return (pipespace_new(cpipe, size));
567 }
568
569 /*
570  * lock a pipe for I/O, blocking other access
571  */
572 static __inline int
573 pipelock(cpipe, catch)
574         struct pipe *cpipe;
575         int catch;
576 {
577         int error;
578
579         PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
580         while (cpipe->pipe_state & PIPE_LOCKFL) {
581                 cpipe->pipe_state |= PIPE_LWANT;
582                 error = msleep(cpipe, PIPE_MTX(cpipe),
583                     catch ? (PRIBIO | PCATCH) : PRIBIO,
584                     "pipelk", 0);
585                 if (error != 0)
586                         return (error);
587         }
588         cpipe->pipe_state |= PIPE_LOCKFL;
589         return (0);
590 }
591
592 /*
593  * unlock a pipe I/O lock
594  */
595 static __inline void
596 pipeunlock(cpipe)
597         struct pipe *cpipe;
598 {
599
600         PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
601         KASSERT(cpipe->pipe_state & PIPE_LOCKFL,
602                 ("Unlocked pipe passed to pipeunlock"));
603         cpipe->pipe_state &= ~PIPE_LOCKFL;
604         if (cpipe->pipe_state & PIPE_LWANT) {
605                 cpipe->pipe_state &= ~PIPE_LWANT;
606                 wakeup(cpipe);
607         }
608 }
609
610 static __inline void
611 pipeselwakeup(cpipe)
612         struct pipe *cpipe;
613 {
614
615         PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
616         if (cpipe->pipe_state & PIPE_SEL) {
617                 selwakeuppri(&cpipe->pipe_sel, PSOCK);
618                 if (!SEL_WAITING(&cpipe->pipe_sel))
619                         cpipe->pipe_state &= ~PIPE_SEL;
620         }
621         if ((cpipe->pipe_state & PIPE_ASYNC) && cpipe->pipe_sigio)
622                 pgsigio(&cpipe->pipe_sigio, SIGIO, 0);
623         KNOTE_LOCKED(&cpipe->pipe_sel.si_note, 0);
624 }
625
626 /*
627  * Initialize and allocate VM and memory for pipe.  The structure
628  * will start out zero'd from the ctor, so we just manage the kmem.
629  */
630 static int
631 pipe_create(pipe, backing)
632         struct pipe *pipe;
633         int backing;
634 {
635         int error;
636
637         if (backing) {
638                 if (amountpipekva > maxpipekva / 2)
639                         error = pipespace_new(pipe, SMALL_PIPE_SIZE);
640                 else
641                         error = pipespace_new(pipe, PIPE_SIZE);
642         } else {
643                 /* If we're not backing this pipe, no need to do anything. */
644                 error = 0;
645         }
646         pipe->pipe_ino = -1;
647         return (error);
648 }
649
650 /* ARGSUSED */
651 static int
652 pipe_read(fp, uio, active_cred, flags, td)
653         struct file *fp;
654         struct uio *uio;
655         struct ucred *active_cred;
656         struct thread *td;
657         int flags;
658 {
659         struct pipe *rpipe;
660         int error;
661         int nread = 0;
662         int size;
663
664         rpipe = fp->f_data;
665         PIPE_LOCK(rpipe);
666         ++rpipe->pipe_busy;
667         error = pipelock(rpipe, 1);
668         if (error)
669                 goto unlocked_error;
670
671 #ifdef MAC
672         error = mac_pipe_check_read(active_cred, rpipe->pipe_pair);
673         if (error)
674                 goto locked_error;
675 #endif
676         if (amountpipekva > (3 * maxpipekva) / 4) {
677                 if (!(rpipe->pipe_state & PIPE_DIRECTW) &&
678                         (rpipe->pipe_buffer.size > SMALL_PIPE_SIZE) &&
679                         (rpipe->pipe_buffer.cnt <= SMALL_PIPE_SIZE) &&
680                         (piperesizeallowed == 1)) {
681                         PIPE_UNLOCK(rpipe);
682                         pipespace(rpipe, SMALL_PIPE_SIZE);
683                         PIPE_LOCK(rpipe);
684                 }
685         }
686
687         while (uio->uio_resid) {
688                 /*
689                  * normal pipe buffer receive
690                  */
691                 if (rpipe->pipe_buffer.cnt > 0) {
692                         size = rpipe->pipe_buffer.size - rpipe->pipe_buffer.out;
693                         if (size > rpipe->pipe_buffer.cnt)
694                                 size = rpipe->pipe_buffer.cnt;
695                         if (size > uio->uio_resid)
696                                 size = uio->uio_resid;
697
698                         PIPE_UNLOCK(rpipe);
699                         error = uiomove(
700                             &rpipe->pipe_buffer.buffer[rpipe->pipe_buffer.out],
701                             size, uio);
702                         PIPE_LOCK(rpipe);
703                         if (error)
704                                 break;
705
706                         rpipe->pipe_buffer.out += size;
707                         if (rpipe->pipe_buffer.out >= rpipe->pipe_buffer.size)
708                                 rpipe->pipe_buffer.out = 0;
709
710                         rpipe->pipe_buffer.cnt -= size;
711
712                         /*
713                          * If there is no more to read in the pipe, reset
714                          * its pointers to the beginning.  This improves
715                          * cache hit stats.
716                          */
717                         if (rpipe->pipe_buffer.cnt == 0) {
718                                 rpipe->pipe_buffer.in = 0;
719                                 rpipe->pipe_buffer.out = 0;
720                         }
721                         nread += size;
722 #ifndef PIPE_NODIRECT
723                 /*
724                  * Direct copy, bypassing a kernel buffer.
725                  */
726                 } else if ((size = rpipe->pipe_map.cnt) &&
727                            (rpipe->pipe_state & PIPE_DIRECTW)) {
728                         if (size > uio->uio_resid)
729                                 size = (u_int) uio->uio_resid;
730
731                         PIPE_UNLOCK(rpipe);
732                         error = uiomove_fromphys(rpipe->pipe_map.ms,
733                             rpipe->pipe_map.pos, size, uio);
734                         PIPE_LOCK(rpipe);
735                         if (error)
736                                 break;
737                         nread += size;
738                         rpipe->pipe_map.pos += size;
739                         rpipe->pipe_map.cnt -= size;
740                         if (rpipe->pipe_map.cnt == 0) {
741                                 rpipe->pipe_state &= ~PIPE_DIRECTW;
742                                 wakeup(rpipe);
743                         }
744 #endif
745                 } else {
746                         /*
747                          * detect EOF condition
748                          * read returns 0 on EOF, no need to set error
749                          */
750                         if (rpipe->pipe_state & PIPE_EOF)
751                                 break;
752
753                         /*
754                          * If the "write-side" has been blocked, wake it up now.
755                          */
756                         if (rpipe->pipe_state & PIPE_WANTW) {
757                                 rpipe->pipe_state &= ~PIPE_WANTW;
758                                 wakeup(rpipe);
759                         }
760
761                         /*
762                          * Break if some data was read.
763                          */
764                         if (nread > 0)
765                                 break;
766
767                         /*
768                          * Unlock the pipe buffer for our remaining processing.
769                          * We will either break out with an error or we will
770                          * sleep and relock to loop.
771                          */
772                         pipeunlock(rpipe);
773
774                         /*
775                          * Handle non-blocking mode operation or
776                          * wait for more data.
777                          */
778                         if (fp->f_flag & FNONBLOCK) {
779                                 error = EAGAIN;
780                         } else {
781                                 rpipe->pipe_state |= PIPE_WANTR;
782                                 if ((error = msleep(rpipe, PIPE_MTX(rpipe),
783                                     PRIBIO | PCATCH,
784                                     "piperd", 0)) == 0)
785                                         error = pipelock(rpipe, 1);
786                         }
787                         if (error)
788                                 goto unlocked_error;
789                 }
790         }
791 #ifdef MAC
792 locked_error:
793 #endif
794         pipeunlock(rpipe);
795
796         /* XXX: should probably do this before getting any locks. */
797         if (error == 0)
798                 vfs_timestamp(&rpipe->pipe_atime);
799 unlocked_error:
800         --rpipe->pipe_busy;
801
802         /*
803          * PIPE_WANT processing only makes sense if pipe_busy is 0.
804          */
805         if ((rpipe->pipe_busy == 0) && (rpipe->pipe_state & PIPE_WANT)) {
806                 rpipe->pipe_state &= ~(PIPE_WANT|PIPE_WANTW);
807                 wakeup(rpipe);
808         } else if (rpipe->pipe_buffer.cnt < MINPIPESIZE) {
809                 /*
810                  * Handle write blocking hysteresis.
811                  */
812                 if (rpipe->pipe_state & PIPE_WANTW) {
813                         rpipe->pipe_state &= ~PIPE_WANTW;
814                         wakeup(rpipe);
815                 }
816         }
817
818         if ((rpipe->pipe_buffer.size - rpipe->pipe_buffer.cnt) >= PIPE_BUF)
819                 pipeselwakeup(rpipe);
820
821         PIPE_UNLOCK(rpipe);
822         return (error);
823 }
824
825 #ifndef PIPE_NODIRECT
826 /*
827  * Map the sending processes' buffer into kernel space and wire it.
828  * This is similar to a physical write operation.
829  */
830 static int
831 pipe_build_write_buffer(wpipe, uio)
832         struct pipe *wpipe;
833         struct uio *uio;
834 {
835         u_int size;
836         int i;
837
838         PIPE_LOCK_ASSERT(wpipe, MA_NOTOWNED);
839         KASSERT(wpipe->pipe_state & PIPE_DIRECTW,
840                 ("Clone attempt on non-direct write pipe!"));
841
842         if (uio->uio_iov->iov_len > wpipe->pipe_buffer.size)
843                 size = wpipe->pipe_buffer.size;
844         else
845                 size = uio->uio_iov->iov_len;
846
847         if ((i = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
848             (vm_offset_t)uio->uio_iov->iov_base, size, VM_PROT_READ,
849             wpipe->pipe_map.ms, PIPENPAGES)) < 0)
850                 return (EFAULT);
851
852 /*
853  * set up the control block
854  */
855         wpipe->pipe_map.npages = i;
856         wpipe->pipe_map.pos =
857             ((vm_offset_t) uio->uio_iov->iov_base) & PAGE_MASK;
858         wpipe->pipe_map.cnt = size;
859
860 /*
861  * and update the uio data
862  */
863
864         uio->uio_iov->iov_len -= size;
865         uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + size;
866         if (uio->uio_iov->iov_len == 0)
867                 uio->uio_iov++;
868         uio->uio_resid -= size;
869         uio->uio_offset += size;
870         return (0);
871 }
872
873 /*
874  * unmap and unwire the process buffer
875  */
876 static void
877 pipe_destroy_write_buffer(wpipe)
878         struct pipe *wpipe;
879 {
880
881         PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
882         vm_page_unhold_pages(wpipe->pipe_map.ms, wpipe->pipe_map.npages);
883         wpipe->pipe_map.npages = 0;
884 }
885
886 /*
887  * In the case of a signal, the writing process might go away.  This
888  * code copies the data into the circular buffer so that the source
889  * pages can be freed without loss of data.
890  */
891 static void
892 pipe_clone_write_buffer(wpipe)
893         struct pipe *wpipe;
894 {
895         struct uio uio;
896         struct iovec iov;
897         int size;
898         int pos;
899
900         PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
901         size = wpipe->pipe_map.cnt;
902         pos = wpipe->pipe_map.pos;
903
904         wpipe->pipe_buffer.in = size;
905         wpipe->pipe_buffer.out = 0;
906         wpipe->pipe_buffer.cnt = size;
907         wpipe->pipe_state &= ~PIPE_DIRECTW;
908
909         PIPE_UNLOCK(wpipe);
910         iov.iov_base = wpipe->pipe_buffer.buffer;
911         iov.iov_len = size;
912         uio.uio_iov = &iov;
913         uio.uio_iovcnt = 1;
914         uio.uio_offset = 0;
915         uio.uio_resid = size;
916         uio.uio_segflg = UIO_SYSSPACE;
917         uio.uio_rw = UIO_READ;
918         uio.uio_td = curthread;
919         uiomove_fromphys(wpipe->pipe_map.ms, pos, size, &uio);
920         PIPE_LOCK(wpipe);
921         pipe_destroy_write_buffer(wpipe);
922 }
923
924 /*
925  * This implements the pipe buffer write mechanism.  Note that only
926  * a direct write OR a normal pipe write can be pending at any given time.
927  * If there are any characters in the pipe buffer, the direct write will
928  * be deferred until the receiving process grabs all of the bytes from
929  * the pipe buffer.  Then the direct mapping write is set-up.
930  */
931 static int
932 pipe_direct_write(wpipe, uio)
933         struct pipe *wpipe;
934         struct uio *uio;
935 {
936         int error;
937
938 retry:
939         PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
940         error = pipelock(wpipe, 1);
941         if (wpipe->pipe_state & PIPE_EOF)
942                 error = EPIPE;
943         if (error) {
944                 pipeunlock(wpipe);
945                 goto error1;
946         }
947         while (wpipe->pipe_state & PIPE_DIRECTW) {
948                 if (wpipe->pipe_state & PIPE_WANTR) {
949                         wpipe->pipe_state &= ~PIPE_WANTR;
950                         wakeup(wpipe);
951                 }
952                 pipeselwakeup(wpipe);
953                 wpipe->pipe_state |= PIPE_WANTW;
954                 pipeunlock(wpipe);
955                 error = msleep(wpipe, PIPE_MTX(wpipe),
956                     PRIBIO | PCATCH, "pipdww", 0);
957                 if (error)
958                         goto error1;
959                 else
960                         goto retry;
961         }
962         wpipe->pipe_map.cnt = 0;        /* transfer not ready yet */
963         if (wpipe->pipe_buffer.cnt > 0) {
964                 if (wpipe->pipe_state & PIPE_WANTR) {
965                         wpipe->pipe_state &= ~PIPE_WANTR;
966                         wakeup(wpipe);
967                 }
968                 pipeselwakeup(wpipe);
969                 wpipe->pipe_state |= PIPE_WANTW;
970                 pipeunlock(wpipe);
971                 error = msleep(wpipe, PIPE_MTX(wpipe),
972                     PRIBIO | PCATCH, "pipdwc", 0);
973                 if (error)
974                         goto error1;
975                 else
976                         goto retry;
977         }
978
979         wpipe->pipe_state |= PIPE_DIRECTW;
980
981         PIPE_UNLOCK(wpipe);
982         error = pipe_build_write_buffer(wpipe, uio);
983         PIPE_LOCK(wpipe);
984         if (error) {
985                 wpipe->pipe_state &= ~PIPE_DIRECTW;
986                 pipeunlock(wpipe);
987                 goto error1;
988         }
989
990         error = 0;
991         while (!error && (wpipe->pipe_state & PIPE_DIRECTW)) {
992                 if (wpipe->pipe_state & PIPE_EOF) {
993                         pipe_destroy_write_buffer(wpipe);
994                         pipeselwakeup(wpipe);
995                         pipeunlock(wpipe);
996                         error = EPIPE;
997                         goto error1;
998                 }
999                 if (wpipe->pipe_state & PIPE_WANTR) {
1000                         wpipe->pipe_state &= ~PIPE_WANTR;
1001                         wakeup(wpipe);
1002                 }
1003                 pipeselwakeup(wpipe);
1004                 pipeunlock(wpipe);
1005                 error = msleep(wpipe, PIPE_MTX(wpipe), PRIBIO | PCATCH,
1006                     "pipdwt", 0);
1007                 pipelock(wpipe, 0);
1008         }
1009
1010         if (wpipe->pipe_state & PIPE_EOF)
1011                 error = EPIPE;
1012         if (wpipe->pipe_state & PIPE_DIRECTW) {
1013                 /*
1014                  * this bit of trickery substitutes a kernel buffer for
1015                  * the process that might be going away.
1016                  */
1017                 pipe_clone_write_buffer(wpipe);
1018         } else {
1019                 pipe_destroy_write_buffer(wpipe);
1020         }
1021         pipeunlock(wpipe);
1022         return (error);
1023
1024 error1:
1025         wakeup(wpipe);
1026         return (error);
1027 }
1028 #endif
1029
1030 static int
1031 pipe_write(fp, uio, active_cred, flags, td)
1032         struct file *fp;
1033         struct uio *uio;
1034         struct ucred *active_cred;
1035         struct thread *td;
1036         int flags;
1037 {
1038         int error = 0;
1039         int desiredsize;
1040         ssize_t orig_resid;
1041         struct pipe *wpipe, *rpipe;
1042
1043         rpipe = fp->f_data;
1044         wpipe = PIPE_PEER(rpipe);
1045         PIPE_LOCK(rpipe);
1046         error = pipelock(wpipe, 1);
1047         if (error) {
1048                 PIPE_UNLOCK(rpipe);
1049                 return (error);
1050         }
1051         /*
1052          * detect loss of pipe read side, issue SIGPIPE if lost.
1053          */
1054         if (wpipe->pipe_present != PIPE_ACTIVE ||
1055             (wpipe->pipe_state & PIPE_EOF)) {
1056                 pipeunlock(wpipe);
1057                 PIPE_UNLOCK(rpipe);
1058                 return (EPIPE);
1059         }
1060 #ifdef MAC
1061         error = mac_pipe_check_write(active_cred, wpipe->pipe_pair);
1062         if (error) {
1063                 pipeunlock(wpipe);
1064                 PIPE_UNLOCK(rpipe);
1065                 return (error);
1066         }
1067 #endif
1068         ++wpipe->pipe_busy;
1069
1070         /* Choose a larger size if it's advantageous */
1071         desiredsize = max(SMALL_PIPE_SIZE, wpipe->pipe_buffer.size);
1072         while (desiredsize < wpipe->pipe_buffer.cnt + uio->uio_resid) {
1073                 if (piperesizeallowed != 1)
1074                         break;
1075                 if (amountpipekva > maxpipekva / 2)
1076                         break;
1077                 if (desiredsize == BIG_PIPE_SIZE)
1078                         break;
1079                 desiredsize = desiredsize * 2;
1080         }
1081
1082         /* Choose a smaller size if we're in a OOM situation */
1083         if ((amountpipekva > (3 * maxpipekva) / 4) &&
1084                 (wpipe->pipe_buffer.size > SMALL_PIPE_SIZE) &&
1085                 (wpipe->pipe_buffer.cnt <= SMALL_PIPE_SIZE) &&
1086                 (piperesizeallowed == 1))
1087                 desiredsize = SMALL_PIPE_SIZE;
1088
1089         /* Resize if the above determined that a new size was necessary */
1090         if ((desiredsize != wpipe->pipe_buffer.size) &&
1091                 ((wpipe->pipe_state & PIPE_DIRECTW) == 0)) {
1092                 PIPE_UNLOCK(wpipe);
1093                 pipespace(wpipe, desiredsize);
1094                 PIPE_LOCK(wpipe);
1095         }
1096         if (wpipe->pipe_buffer.size == 0) {
1097                 /*
1098                  * This can only happen for reverse direction use of pipes
1099                  * in a complete OOM situation.
1100                  */
1101                 error = ENOMEM;
1102                 --wpipe->pipe_busy;
1103                 pipeunlock(wpipe);
1104                 PIPE_UNLOCK(wpipe);
1105                 return (error);
1106         }
1107
1108         pipeunlock(wpipe);
1109
1110         orig_resid = uio->uio_resid;
1111
1112         while (uio->uio_resid) {
1113                 int space;
1114
1115                 pipelock(wpipe, 0);
1116                 if (wpipe->pipe_state & PIPE_EOF) {
1117                         pipeunlock(wpipe);
1118                         error = EPIPE;
1119                         break;
1120                 }
1121 #ifndef PIPE_NODIRECT
1122                 /*
1123                  * If the transfer is large, we can gain performance if
1124                  * we do process-to-process copies directly.
1125                  * If the write is non-blocking, we don't use the
1126                  * direct write mechanism.
1127                  *
1128                  * The direct write mechanism will detect the reader going
1129                  * away on us.
1130                  */
1131                 if (uio->uio_segflg == UIO_USERSPACE &&
1132                     uio->uio_iov->iov_len >= PIPE_MINDIRECT &&
1133                     wpipe->pipe_buffer.size >= PIPE_MINDIRECT &&
1134                     (fp->f_flag & FNONBLOCK) == 0) {
1135                         pipeunlock(wpipe);
1136                         error = pipe_direct_write(wpipe, uio);
1137                         if (error)
1138                                 break;
1139                         continue;
1140                 }
1141 #endif
1142
1143                 /*
1144                  * Pipe buffered writes cannot be coincidental with
1145                  * direct writes.  We wait until the currently executing
1146                  * direct write is completed before we start filling the
1147                  * pipe buffer.  We break out if a signal occurs or the
1148                  * reader goes away.
1149                  */
1150                 if (wpipe->pipe_state & PIPE_DIRECTW) {
1151                         if (wpipe->pipe_state & PIPE_WANTR) {
1152                                 wpipe->pipe_state &= ~PIPE_WANTR;
1153                                 wakeup(wpipe);
1154                         }
1155                         pipeselwakeup(wpipe);
1156                         wpipe->pipe_state |= PIPE_WANTW;
1157                         pipeunlock(wpipe);
1158                         error = msleep(wpipe, PIPE_MTX(rpipe), PRIBIO | PCATCH,
1159                             "pipbww", 0);
1160                         if (error)
1161                                 break;
1162                         else
1163                                 continue;
1164                 }
1165
1166                 space = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
1167
1168                 /* Writes of size <= PIPE_BUF must be atomic. */
1169                 if ((space < uio->uio_resid) && (orig_resid <= PIPE_BUF))
1170                         space = 0;
1171
1172                 if (space > 0) {
1173                         int size;       /* Transfer size */
1174                         int segsize;    /* first segment to transfer */
1175
1176                         /*
1177                          * Transfer size is minimum of uio transfer
1178                          * and free space in pipe buffer.
1179                          */
1180                         if (space > uio->uio_resid)
1181                                 size = uio->uio_resid;
1182                         else
1183                                 size = space;
1184                         /*
1185                          * First segment to transfer is minimum of
1186                          * transfer size and contiguous space in
1187                          * pipe buffer.  If first segment to transfer
1188                          * is less than the transfer size, we've got
1189                          * a wraparound in the buffer.
1190                          */
1191                         segsize = wpipe->pipe_buffer.size -
1192                                 wpipe->pipe_buffer.in;
1193                         if (segsize > size)
1194                                 segsize = size;
1195
1196                         /* Transfer first segment */
1197
1198                         PIPE_UNLOCK(rpipe);
1199                         error = uiomove(&wpipe->pipe_buffer.buffer[wpipe->pipe_buffer.in],
1200                                         segsize, uio);
1201                         PIPE_LOCK(rpipe);
1202
1203                         if (error == 0 && segsize < size) {
1204                                 KASSERT(wpipe->pipe_buffer.in + segsize ==
1205                                         wpipe->pipe_buffer.size,
1206                                         ("Pipe buffer wraparound disappeared"));
1207                                 /*
1208                                  * Transfer remaining part now, to
1209                                  * support atomic writes.  Wraparound
1210                                  * happened.
1211                                  */
1212
1213                                 PIPE_UNLOCK(rpipe);
1214                                 error = uiomove(
1215                                     &wpipe->pipe_buffer.buffer[0],
1216                                     size - segsize, uio);
1217                                 PIPE_LOCK(rpipe);
1218                         }
1219                         if (error == 0) {
1220                                 wpipe->pipe_buffer.in += size;
1221                                 if (wpipe->pipe_buffer.in >=
1222                                     wpipe->pipe_buffer.size) {
1223                                         KASSERT(wpipe->pipe_buffer.in ==
1224                                                 size - segsize +
1225                                                 wpipe->pipe_buffer.size,
1226                                                 ("Expected wraparound bad"));
1227                                         wpipe->pipe_buffer.in = size - segsize;
1228                                 }
1229
1230                                 wpipe->pipe_buffer.cnt += size;
1231                                 KASSERT(wpipe->pipe_buffer.cnt <=
1232                                         wpipe->pipe_buffer.size,
1233                                         ("Pipe buffer overflow"));
1234                         }
1235                         pipeunlock(wpipe);
1236                         if (error != 0)
1237                                 break;
1238                 } else {
1239                         /*
1240                          * If the "read-side" has been blocked, wake it up now.
1241                          */
1242                         if (wpipe->pipe_state & PIPE_WANTR) {
1243                                 wpipe->pipe_state &= ~PIPE_WANTR;
1244                                 wakeup(wpipe);
1245                         }
1246
1247                         /*
1248                          * don't block on non-blocking I/O
1249                          */
1250                         if (fp->f_flag & FNONBLOCK) {
1251                                 error = EAGAIN;
1252                                 pipeunlock(wpipe);
1253                                 break;
1254                         }
1255
1256                         /*
1257                          * We have no more space and have something to offer,
1258                          * wake up select/poll.
1259                          */
1260                         pipeselwakeup(wpipe);
1261
1262                         wpipe->pipe_state |= PIPE_WANTW;
1263                         pipeunlock(wpipe);
1264                         error = msleep(wpipe, PIPE_MTX(rpipe),
1265                             PRIBIO | PCATCH, "pipewr", 0);
1266                         if (error != 0)
1267                                 break;
1268                 }
1269         }
1270
1271         pipelock(wpipe, 0);
1272         --wpipe->pipe_busy;
1273
1274         if ((wpipe->pipe_busy == 0) && (wpipe->pipe_state & PIPE_WANT)) {
1275                 wpipe->pipe_state &= ~(PIPE_WANT | PIPE_WANTR);
1276                 wakeup(wpipe);
1277         } else if (wpipe->pipe_buffer.cnt > 0) {
1278                 /*
1279                  * If we have put any characters in the buffer, we wake up
1280                  * the reader.
1281                  */
1282                 if (wpipe->pipe_state & PIPE_WANTR) {
1283                         wpipe->pipe_state &= ~PIPE_WANTR;
1284                         wakeup(wpipe);
1285                 }
1286         }
1287
1288         /*
1289          * Don't return EPIPE if I/O was successful
1290          */
1291         if ((wpipe->pipe_buffer.cnt == 0) &&
1292             (uio->uio_resid == 0) &&
1293             (error == EPIPE)) {
1294                 error = 0;
1295         }
1296
1297         if (error == 0)
1298                 vfs_timestamp(&wpipe->pipe_mtime);
1299
1300         /*
1301          * We have something to offer,
1302          * wake up select/poll.
1303          */
1304         if (wpipe->pipe_buffer.cnt)
1305                 pipeselwakeup(wpipe);
1306
1307         pipeunlock(wpipe);
1308         PIPE_UNLOCK(rpipe);
1309         return (error);
1310 }
1311
1312 /* ARGSUSED */
1313 static int
1314 pipe_truncate(fp, length, active_cred, td)
1315         struct file *fp;
1316         off_t length;
1317         struct ucred *active_cred;
1318         struct thread *td;
1319 {
1320
1321         /* For named pipes call the vnode operation. */
1322         if (fp->f_vnode != NULL)
1323                 return (vnops.fo_truncate(fp, length, active_cred, td));
1324         return (EINVAL);
1325 }
1326
1327 /*
1328  * we implement a very minimal set of ioctls for compatibility with sockets.
1329  */
1330 static int
1331 pipe_ioctl(fp, cmd, data, active_cred, td)
1332         struct file *fp;
1333         u_long cmd;
1334         void *data;
1335         struct ucred *active_cred;
1336         struct thread *td;
1337 {
1338         struct pipe *mpipe = fp->f_data;
1339         int error;
1340
1341         PIPE_LOCK(mpipe);
1342
1343 #ifdef MAC
1344         error = mac_pipe_check_ioctl(active_cred, mpipe->pipe_pair, cmd, data);
1345         if (error) {
1346                 PIPE_UNLOCK(mpipe);
1347                 return (error);
1348         }
1349 #endif
1350
1351         error = 0;
1352         switch (cmd) {
1353
1354         case FIONBIO:
1355                 break;
1356
1357         case FIOASYNC:
1358                 if (*(int *)data) {
1359                         mpipe->pipe_state |= PIPE_ASYNC;
1360                 } else {
1361                         mpipe->pipe_state &= ~PIPE_ASYNC;
1362                 }
1363                 break;
1364
1365         case FIONREAD:
1366                 if (!(fp->f_flag & FREAD)) {
1367                         *(int *)data = 0;
1368                         PIPE_UNLOCK(mpipe);
1369                         return (0);
1370                 }
1371                 if (mpipe->pipe_state & PIPE_DIRECTW)
1372                         *(int *)data = mpipe->pipe_map.cnt;
1373                 else
1374                         *(int *)data = mpipe->pipe_buffer.cnt;
1375                 break;
1376
1377         case FIOSETOWN:
1378                 PIPE_UNLOCK(mpipe);
1379                 error = fsetown(*(int *)data, &mpipe->pipe_sigio);
1380                 goto out_unlocked;
1381
1382         case FIOGETOWN:
1383                 *(int *)data = fgetown(&mpipe->pipe_sigio);
1384                 break;
1385
1386         /* This is deprecated, FIOSETOWN should be used instead. */
1387         case TIOCSPGRP:
1388                 PIPE_UNLOCK(mpipe);
1389                 error = fsetown(-(*(int *)data), &mpipe->pipe_sigio);
1390                 goto out_unlocked;
1391
1392         /* This is deprecated, FIOGETOWN should be used instead. */
1393         case TIOCGPGRP:
1394                 *(int *)data = -fgetown(&mpipe->pipe_sigio);
1395                 break;
1396
1397         default:
1398                 error = ENOTTY;
1399                 break;
1400         }
1401         PIPE_UNLOCK(mpipe);
1402 out_unlocked:
1403         return (error);
1404 }
1405
1406 static int
1407 pipe_poll(fp, events, active_cred, td)
1408         struct file *fp;
1409         int events;
1410         struct ucred *active_cred;
1411         struct thread *td;
1412 {
1413         struct pipe *rpipe;
1414         struct pipe *wpipe;
1415         int levents, revents;
1416 #ifdef MAC
1417         int error;
1418 #endif
1419
1420         revents = 0;
1421         rpipe = fp->f_data;
1422         wpipe = PIPE_PEER(rpipe);
1423         PIPE_LOCK(rpipe);
1424 #ifdef MAC
1425         error = mac_pipe_check_poll(active_cred, rpipe->pipe_pair);
1426         if (error)
1427                 goto locked_error;
1428 #endif
1429         if (fp->f_flag & FREAD && events & (POLLIN | POLLRDNORM))
1430                 if ((rpipe->pipe_state & PIPE_DIRECTW) ||
1431                     (rpipe->pipe_buffer.cnt > 0))
1432                         revents |= events & (POLLIN | POLLRDNORM);
1433
1434         if (fp->f_flag & FWRITE && events & (POLLOUT | POLLWRNORM))
1435                 if (wpipe->pipe_present != PIPE_ACTIVE ||
1436                     (wpipe->pipe_state & PIPE_EOF) ||
1437                     (((wpipe->pipe_state & PIPE_DIRECTW) == 0) &&
1438                      ((wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt) >= PIPE_BUF ||
1439                          wpipe->pipe_buffer.size == 0)))
1440                         revents |= events & (POLLOUT | POLLWRNORM);
1441
1442         levents = events &
1443             (POLLIN | POLLINIGNEOF | POLLPRI | POLLRDNORM | POLLRDBAND);
1444         if (rpipe->pipe_state & PIPE_NAMED && fp->f_flag & FREAD && levents &&
1445             rpipe->pipe_state & PIPE_SAMEWGEN)
1446                 events |= POLLINIGNEOF;
1447
1448         if ((events & POLLINIGNEOF) == 0) {
1449                 if (rpipe->pipe_state & PIPE_EOF) {
1450                         revents |= (events & (POLLIN | POLLRDNORM));
1451                         if (wpipe->pipe_present != PIPE_ACTIVE ||
1452                             (wpipe->pipe_state & PIPE_EOF))
1453                                 revents |= POLLHUP;
1454                 }
1455         }
1456
1457         if (revents == 0) {
1458                 if (fp->f_flag & FREAD && events & (POLLIN | POLLRDNORM)) {
1459                         selrecord(td, &rpipe->pipe_sel);
1460                         if (SEL_WAITING(&rpipe->pipe_sel))
1461                                 rpipe->pipe_state |= PIPE_SEL;
1462                 }
1463
1464                 if (fp->f_flag & FWRITE && events & (POLLOUT | POLLWRNORM)) {
1465                         selrecord(td, &wpipe->pipe_sel);
1466                         if (SEL_WAITING(&wpipe->pipe_sel))
1467                                 wpipe->pipe_state |= PIPE_SEL;
1468                 }
1469         }
1470 #ifdef MAC
1471 locked_error:
1472 #endif
1473         PIPE_UNLOCK(rpipe);
1474
1475         return (revents);
1476 }
1477
1478 /*
1479  * We shouldn't need locks here as we're doing a read and this should
1480  * be a natural race.
1481  */
1482 static int
1483 pipe_stat(fp, ub, active_cred, td)
1484         struct file *fp;
1485         struct stat *ub;
1486         struct ucred *active_cred;
1487         struct thread *td;
1488 {
1489         struct pipe *pipe;
1490         int new_unr;
1491 #ifdef MAC
1492         int error;
1493 #endif
1494
1495         pipe = fp->f_data;
1496         PIPE_LOCK(pipe);
1497 #ifdef MAC
1498         error = mac_pipe_check_stat(active_cred, pipe->pipe_pair);
1499         if (error) {
1500                 PIPE_UNLOCK(pipe);
1501                 return (error);
1502         }
1503 #endif
1504
1505         /* For named pipes ask the underlying filesystem. */
1506         if (pipe->pipe_state & PIPE_NAMED) {
1507                 PIPE_UNLOCK(pipe);
1508                 return (vnops.fo_stat(fp, ub, active_cred, td));
1509         }
1510
1511         /*
1512          * Lazily allocate an inode number for the pipe.  Most pipe
1513          * users do not call fstat(2) on the pipe, which means that
1514          * postponing the inode allocation until it is must be
1515          * returned to userland is useful.  If alloc_unr failed,
1516          * assign st_ino zero instead of returning an error.
1517          * Special pipe_ino values:
1518          *  -1 - not yet initialized;
1519          *  0  - alloc_unr failed, return 0 as st_ino forever.
1520          */
1521         if (pipe->pipe_ino == (ino_t)-1) {
1522                 new_unr = alloc_unr(pipeino_unr);
1523                 if (new_unr != -1)
1524                         pipe->pipe_ino = new_unr;
1525                 else
1526                         pipe->pipe_ino = 0;
1527         }
1528         PIPE_UNLOCK(pipe);
1529
1530         bzero(ub, sizeof(*ub));
1531         ub->st_mode = S_IFIFO;
1532         ub->st_blksize = PAGE_SIZE;
1533         if (pipe->pipe_state & PIPE_DIRECTW)
1534                 ub->st_size = pipe->pipe_map.cnt;
1535         else
1536                 ub->st_size = pipe->pipe_buffer.cnt;
1537         ub->st_blocks = (ub->st_size + ub->st_blksize - 1) / ub->st_blksize;
1538         ub->st_atim = pipe->pipe_atime;
1539         ub->st_mtim = pipe->pipe_mtime;
1540         ub->st_ctim = pipe->pipe_ctime;
1541         ub->st_uid = fp->f_cred->cr_uid;
1542         ub->st_gid = fp->f_cred->cr_gid;
1543         ub->st_dev = pipedev_ino;
1544         ub->st_ino = pipe->pipe_ino;
1545         /*
1546          * Left as 0: st_nlink, st_rdev, st_flags, st_gen.
1547          */
1548         return (0);
1549 }
1550
1551 /* ARGSUSED */
1552 static int
1553 pipe_close(fp, td)
1554         struct file *fp;
1555         struct thread *td;
1556 {
1557
1558         if (fp->f_vnode != NULL) 
1559                 return vnops.fo_close(fp, td);
1560         fp->f_ops = &badfileops;
1561         pipe_dtor(fp->f_data);
1562         fp->f_data = NULL;
1563         return (0);
1564 }
1565
1566 static int
1567 pipe_chmod(struct file *fp, mode_t mode, struct ucred *active_cred, struct thread *td)
1568 {
1569         struct pipe *cpipe;
1570         int error;
1571
1572         cpipe = fp->f_data;
1573         if (cpipe->pipe_state & PIPE_NAMED)
1574                 error = vn_chmod(fp, mode, active_cred, td);
1575         else
1576                 error = invfo_chmod(fp, mode, active_cred, td);
1577         return (error);
1578 }
1579
1580 static int
1581 pipe_chown(fp, uid, gid, active_cred, td)
1582         struct file *fp;
1583         uid_t uid;
1584         gid_t gid;
1585         struct ucred *active_cred;
1586         struct thread *td;
1587 {
1588         struct pipe *cpipe;
1589         int error;
1590
1591         cpipe = fp->f_data;
1592         if (cpipe->pipe_state & PIPE_NAMED)
1593                 error = vn_chown(fp, uid, gid, active_cred, td);
1594         else
1595                 error = invfo_chown(fp, uid, gid, active_cred, td);
1596         return (error);
1597 }
1598
1599 static void
1600 pipe_free_kmem(cpipe)
1601         struct pipe *cpipe;
1602 {
1603
1604         KASSERT(!mtx_owned(PIPE_MTX(cpipe)),
1605             ("pipe_free_kmem: pipe mutex locked"));
1606
1607         if (cpipe->pipe_buffer.buffer != NULL) {
1608                 atomic_subtract_long(&amountpipekva, cpipe->pipe_buffer.size);
1609                 vm_map_remove(pipe_map,
1610                     (vm_offset_t)cpipe->pipe_buffer.buffer,
1611                     (vm_offset_t)cpipe->pipe_buffer.buffer + cpipe->pipe_buffer.size);
1612                 cpipe->pipe_buffer.buffer = NULL;
1613         }
1614 #ifndef PIPE_NODIRECT
1615         {
1616                 cpipe->pipe_map.cnt = 0;
1617                 cpipe->pipe_map.pos = 0;
1618                 cpipe->pipe_map.npages = 0;
1619         }
1620 #endif
1621 }
1622
1623 /*
1624  * shutdown the pipe
1625  */
1626 static void
1627 pipeclose(cpipe)
1628         struct pipe *cpipe;
1629 {
1630         struct pipepair *pp;
1631         struct pipe *ppipe;
1632
1633         KASSERT(cpipe != NULL, ("pipeclose: cpipe == NULL"));
1634
1635         PIPE_LOCK(cpipe);
1636         pipelock(cpipe, 0);
1637         pp = cpipe->pipe_pair;
1638
1639         pipeselwakeup(cpipe);
1640
1641         /*
1642          * If the other side is blocked, wake it up saying that
1643          * we want to close it down.
1644          */
1645         cpipe->pipe_state |= PIPE_EOF;
1646         while (cpipe->pipe_busy) {
1647                 wakeup(cpipe);
1648                 cpipe->pipe_state |= PIPE_WANT;
1649                 pipeunlock(cpipe);
1650                 msleep(cpipe, PIPE_MTX(cpipe), PRIBIO, "pipecl", 0);
1651                 pipelock(cpipe, 0);
1652         }
1653
1654
1655         /*
1656          * Disconnect from peer, if any.
1657          */
1658         ppipe = cpipe->pipe_peer;
1659         if (ppipe->pipe_present == PIPE_ACTIVE) {
1660                 pipeselwakeup(ppipe);
1661
1662                 ppipe->pipe_state |= PIPE_EOF;
1663                 wakeup(ppipe);
1664                 KNOTE_LOCKED(&ppipe->pipe_sel.si_note, 0);
1665         }
1666
1667         /*
1668          * Mark this endpoint as free.  Release kmem resources.  We
1669          * don't mark this endpoint as unused until we've finished
1670          * doing that, or the pipe might disappear out from under
1671          * us.
1672          */
1673         PIPE_UNLOCK(cpipe);
1674         pipe_free_kmem(cpipe);
1675         PIPE_LOCK(cpipe);
1676         cpipe->pipe_present = PIPE_CLOSING;
1677         pipeunlock(cpipe);
1678
1679         /*
1680          * knlist_clear() may sleep dropping the PIPE_MTX. Set the
1681          * PIPE_FINALIZED, that allows other end to free the
1682          * pipe_pair, only after the knotes are completely dismantled.
1683          */
1684         knlist_clear(&cpipe->pipe_sel.si_note, 1);
1685         cpipe->pipe_present = PIPE_FINALIZED;
1686         seldrain(&cpipe->pipe_sel);
1687         knlist_destroy(&cpipe->pipe_sel.si_note);
1688
1689         /*
1690          * If both endpoints are now closed, release the memory for the
1691          * pipe pair.  If not, unlock.
1692          */
1693         if (ppipe->pipe_present == PIPE_FINALIZED) {
1694                 PIPE_UNLOCK(cpipe);
1695 #ifdef MAC
1696                 mac_pipe_destroy(pp);
1697 #endif
1698                 uma_zfree(pipe_zone, cpipe->pipe_pair);
1699         } else
1700                 PIPE_UNLOCK(cpipe);
1701 }
1702
1703 /*ARGSUSED*/
1704 static int
1705 pipe_kqfilter(struct file *fp, struct knote *kn)
1706 {
1707         struct pipe *cpipe;
1708
1709         /*
1710          * If a filter is requested that is not supported by this file
1711          * descriptor, don't return an error, but also don't ever generate an
1712          * event.
1713          */
1714         if ((kn->kn_filter == EVFILT_READ) && !(fp->f_flag & FREAD)) {
1715                 kn->kn_fop = &pipe_nfiltops;
1716                 return (0);
1717         }
1718         if ((kn->kn_filter == EVFILT_WRITE) && !(fp->f_flag & FWRITE)) {
1719                 kn->kn_fop = &pipe_nfiltops;
1720                 return (0);
1721         }
1722         cpipe = fp->f_data;
1723         PIPE_LOCK(cpipe);
1724         switch (kn->kn_filter) {
1725         case EVFILT_READ:
1726                 kn->kn_fop = &pipe_rfiltops;
1727                 break;
1728         case EVFILT_WRITE:
1729                 kn->kn_fop = &pipe_wfiltops;
1730                 if (cpipe->pipe_peer->pipe_present != PIPE_ACTIVE) {
1731                         /* other end of pipe has been closed */
1732                         PIPE_UNLOCK(cpipe);
1733                         return (EPIPE);
1734                 }
1735                 cpipe = PIPE_PEER(cpipe);
1736                 break;
1737         default:
1738                 PIPE_UNLOCK(cpipe);
1739                 return (EINVAL);
1740         }
1741
1742         kn->kn_hook = cpipe; 
1743         knlist_add(&cpipe->pipe_sel.si_note, kn, 1);
1744         PIPE_UNLOCK(cpipe);
1745         return (0);
1746 }
1747
1748 static void
1749 filt_pipedetach(struct knote *kn)
1750 {
1751         struct pipe *cpipe = kn->kn_hook;
1752
1753         PIPE_LOCK(cpipe);
1754         knlist_remove(&cpipe->pipe_sel.si_note, kn, 1);
1755         PIPE_UNLOCK(cpipe);
1756 }
1757
1758 /*ARGSUSED*/
1759 static int
1760 filt_piperead(struct knote *kn, long hint)
1761 {
1762         struct pipe *rpipe = kn->kn_hook;
1763         struct pipe *wpipe = rpipe->pipe_peer;
1764         int ret;
1765
1766         PIPE_LOCK(rpipe);
1767         kn->kn_data = rpipe->pipe_buffer.cnt;
1768         if ((kn->kn_data == 0) && (rpipe->pipe_state & PIPE_DIRECTW))
1769                 kn->kn_data = rpipe->pipe_map.cnt;
1770
1771         if ((rpipe->pipe_state & PIPE_EOF) ||
1772             wpipe->pipe_present != PIPE_ACTIVE ||
1773             (wpipe->pipe_state & PIPE_EOF)) {
1774                 kn->kn_flags |= EV_EOF;
1775                 PIPE_UNLOCK(rpipe);
1776                 return (1);
1777         }
1778         ret = kn->kn_data > 0;
1779         PIPE_UNLOCK(rpipe);
1780         return ret;
1781 }
1782
1783 /*ARGSUSED*/
1784 static int
1785 filt_pipewrite(struct knote *kn, long hint)
1786 {
1787         struct pipe *wpipe;
1788    
1789         wpipe = kn->kn_hook;
1790         PIPE_LOCK(wpipe);
1791         if (wpipe->pipe_present != PIPE_ACTIVE ||
1792             (wpipe->pipe_state & PIPE_EOF)) {
1793                 kn->kn_data = 0;
1794                 kn->kn_flags |= EV_EOF;
1795                 PIPE_UNLOCK(wpipe);
1796                 return (1);
1797         }
1798         kn->kn_data = (wpipe->pipe_buffer.size > 0) ?
1799             (wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt) : PIPE_BUF;
1800         if (wpipe->pipe_state & PIPE_DIRECTW)
1801                 kn->kn_data = 0;
1802
1803         PIPE_UNLOCK(wpipe);
1804         return (kn->kn_data >= PIPE_BUF);
1805 }
1806
1807 static void
1808 filt_pipedetach_notsup(struct knote *kn)
1809 {
1810
1811 }
1812
1813 static int
1814 filt_pipenotsup(struct knote *kn, long hint)
1815 {
1816
1817         return (0);
1818 }