1139804Simp/*-
213675Sdyson * Copyright (c) 1996 John S. Dyson
313675Sdyson * All rights reserved.
413675Sdyson *
513675Sdyson * Redistribution and use in source and binary forms, with or without
613675Sdyson * modification, are permitted provided that the following conditions
713675Sdyson * are met:
813675Sdyson * 1. Redistributions of source code must retain the above copyright
913675Sdyson *    notice immediately at the beginning of the file, without modification,
1013675Sdyson *    this list of conditions, and the following disclaimer.
1113675Sdyson * 2. Redistributions in binary form must reproduce the above copyright
1213675Sdyson *    notice, this list of conditions and the following disclaimer in the
1313675Sdyson *    documentation and/or other materials provided with the distribution.
1413675Sdyson * 3. Absolutely no warranty of function or purpose is made by the author
1513675Sdyson *    John S. Dyson.
1614037Sdyson * 4. Modifications may be freely made to this file if the above conditions
1713675Sdyson *    are met.
1813675Sdyson */
1913675Sdyson
2013675Sdyson/*
2113675Sdyson * This file contains a high-performance replacement for the socket-based
2213675Sdyson * pipes scheme originally used in FreeBSD/4.4Lite.  It does not support
2313675Sdyson * all features of sockets, but does do everything that pipes normally
2413675Sdyson * do.
2513675Sdyson */
2613675Sdyson
2713907Sdyson/*
2813907Sdyson * This code has two modes of operation, a small write mode and a large
2913907Sdyson * write mode.  The small write mode acts like conventional pipes with
3013907Sdyson * a kernel buffer.  If the buffer is less than PIPE_MINDIRECT, then the
3113907Sdyson * "normal" pipe buffering is done.  If the buffer is between PIPE_MINDIRECT
32219801Salc * and PIPE_SIZE in size, the sending process pins the underlying pages in
33219801Salc * memory, and the receiving process copies directly from these pinned pages
34219801Salc * in the sending process.
3513907Sdyson *
3613907Sdyson * If the sending process receives a signal, it is possible that it will
3713913Sdyson * go away, and certainly its address space can change, because control
3813907Sdyson * is returned back to the user-mode side.  In that case, the pipe code
3913907Sdyson * arranges to copy the buffer supplied by the user process, to a pageable
4013907Sdyson * kernel buffer, and the receiving process will grab the data from the
4113907Sdyson * pageable kernel buffer.  Since signals don't happen all that often,
4213907Sdyson * the copy operation is normally eliminated.
4313907Sdyson *
4413907Sdyson * The constant PIPE_MINDIRECT is chosen to make sure that buffering will
4513907Sdyson * happen for small transfers so that the system will not spend all of
46118764Ssilby * its time context switching.
47117325Ssilby *
48118764Ssilby * In order to limit the resource use of pipes, two sysctls exist:
49117325Ssilby *
50118764Ssilby * kern.ipc.maxpipekva - This is a hard limit on the amount of pageable
51133790Ssilby * address space available to us in pipe_map. This value is normally
52133790Ssilby * autotuned, but may also be loader tuned.
53117325Ssilby *
54133790Ssilby * kern.ipc.pipekva - This read-only sysctl tracks the current amount of
55133790Ssilby * memory in use by pipes.
56117325Ssilby *
57133790Ssilby * Based on how large pipekva is relative to maxpipekva, the following
58133790Ssilby * will happen:
59117325Ssilby *
60133790Ssilby * 0% - 50%:
61133790Ssilby *     New pipes are given 16K of memory backing, pipes may dynamically
62133790Ssilby *     grow to as large as 64K where needed.
63133790Ssilby * 50% - 75%:
64133790Ssilby *     New pipes are given 4K (or PAGE_SIZE) of memory backing,
65133790Ssilby *     existing pipes may NOT grow.
66133790Ssilby * 75% - 100%:
67133790Ssilby *     New pipes are given 4K (or PAGE_SIZE) of memory backing,
68133790Ssilby *     existing pipes will be shrunk down to 4K whenever possible.
69133049Ssilby *
70133790Ssilby * Resizing may be disabled by setting kern.ipc.piperesizeallowed=0.  If
71133790Ssilby * that is set,  the only resize that will occur is the 0 -> SMALL_PIPE_SIZE
72133790Ssilby * resize which MUST occur for reverse-direction pipes when they are
73133790Ssilby * first used.
74133790Ssilby *
75133790Ssilby * Additional information about the current state of pipes may be obtained
76133790Ssilby * from kern.ipc.pipes, kern.ipc.pipefragretry, kern.ipc.pipeallocfail,
77133790Ssilby * and kern.ipc.piperesizefail.
78133790Ssilby *
79133049Ssilby * Locking rules:  There are two locks present here:  A mutex, used via
80133049Ssilby * PIPE_LOCK, and a flag, used via pipelock().  All locking is done via
81133049Ssilby * the flag, as mutexes can not persist over uiomove.  The mutex
82133049Ssilby * exists only to guard access to the flag, and is not in itself a
83133790Ssilby * locking mechanism.  Also note that there is only a single mutex for
84133790Ssilby * both directions of a pipe.
85133049Ssilby *
86133049Ssilby * As pipelock() may have to sleep before it can acquire the flag, it
87133049Ssilby * is important to reread all data after a call to pipelock(); everything
88133049Ssilby * in the structure may have changed.
8913907Sdyson */
9013907Sdyson
91116182Sobrien#include <sys/cdefs.h>
92116182Sobrien__FBSDID("$FreeBSD$");
93116182Sobrien
9413675Sdyson#include <sys/param.h>
9513675Sdyson#include <sys/systm.h>
96226578Skib#include <sys/conf.h>
9724131Sbde#include <sys/fcntl.h>
9813675Sdyson#include <sys/file.h>
9913675Sdyson#include <sys/filedesc.h>
10024206Sbde#include <sys/filio.h>
10191372Salfred#include <sys/kernel.h>
10276166Smarkm#include <sys/lock.h>
10376827Salfred#include <sys/mutex.h>
10424206Sbde#include <sys/ttycom.h>
10513675Sdyson#include <sys/stat.h>
10691968Salfred#include <sys/malloc.h>
10729356Speter#include <sys/poll.h>
10870834Swollman#include <sys/selinfo.h>
10913675Sdyson#include <sys/signalvar.h>
110184849Sed#include <sys/syscallsubr.h>
111117325Ssilby#include <sys/sysctl.h>
11213675Sdyson#include <sys/sysproto.h>
11313675Sdyson#include <sys/pipe.h>
11476166Smarkm#include <sys/proc.h>
11555112Sbde#include <sys/vnode.h>
11634924Sbde#include <sys/uio.h>
11759288Sjlemon#include <sys/event.h>
11813675Sdyson
119163606Srwatson#include <security/mac/mac_framework.h>
120163606Srwatson
12113675Sdyson#include <vm/vm.h>
12213675Sdyson#include <vm/vm_param.h>
12313675Sdyson#include <vm/vm_object.h>
12413675Sdyson#include <vm/vm_kern.h>
12513675Sdyson#include <vm/vm_extern.h>
12613675Sdyson#include <vm/pmap.h>
12713675Sdyson#include <vm/vm_map.h>
12813907Sdyson#include <vm/vm_page.h>
12992751Sjeff#include <vm/uma.h>
13013675Sdyson
131248532Sjkim/* XXX */
132248532Sjkimint	do_pipe(struct thread *td, int fildes[2], int flags);
133248532Sjkim
13414037Sdyson/*
13514037Sdyson * Use this define if you want to disable *fancy* VM things.  Expect an
13614037Sdyson * approx 30% decrease in transfer rate.  This could be useful for
13714037Sdyson * NetBSD or OpenBSD.
13814037Sdyson */
13914037Sdyson/* #define PIPE_NODIRECT */
14014037Sdyson
14114037Sdyson/*
14214037Sdyson * interfaces to the outside world
14314037Sdyson */
144108255Sphkstatic fo_rdwr_t	pipe_read;
145108255Sphkstatic fo_rdwr_t	pipe_write;
146175140Sjhbstatic fo_truncate_t	pipe_truncate;
147108255Sphkstatic fo_ioctl_t	pipe_ioctl;
148108255Sphkstatic fo_poll_t	pipe_poll;
149108255Sphkstatic fo_kqfilter_t	pipe_kqfilter;
150108255Sphkstatic fo_stat_t	pipe_stat;
151108255Sphkstatic fo_close_t	pipe_close;
15213675Sdyson
15372521Sjlemonstatic struct fileops pipeops = {
154116546Sphk	.fo_read = pipe_read,
155116546Sphk	.fo_write = pipe_write,
156175140Sjhb	.fo_truncate = pipe_truncate,
157116546Sphk	.fo_ioctl = pipe_ioctl,
158116546Sphk	.fo_poll = pipe_poll,
159116546Sphk	.fo_kqfilter = pipe_kqfilter,
160116546Sphk	.fo_stat = pipe_stat,
161116546Sphk	.fo_close = pipe_close,
162224914Skib	.fo_chmod = invfo_chmod,
163224914Skib	.fo_chown = invfo_chown,
164116546Sphk	.fo_flags = DFLAG_PASSABLE
16572521Sjlemon};
16613675Sdyson
16759288Sjlemonstatic void	filt_pipedetach(struct knote *kn);
16859288Sjlemonstatic int	filt_piperead(struct knote *kn, long hint);
16959288Sjlemonstatic int	filt_pipewrite(struct knote *kn, long hint);
17059288Sjlemon
171197134Srwatsonstatic struct filterops pipe_rfiltops = {
172197134Srwatson	.f_isfd = 1,
173197134Srwatson	.f_detach = filt_pipedetach,
174197134Srwatson	.f_event = filt_piperead
175197134Srwatson};
176197134Srwatsonstatic struct filterops pipe_wfiltops = {
177197134Srwatson	.f_isfd = 1,
178197134Srwatson	.f_detach = filt_pipedetach,
179197134Srwatson	.f_event = filt_pipewrite
180197134Srwatson};
18159288Sjlemon
18213675Sdyson/*
18313675Sdyson * Default pipe buffer size(s), this can be kind-of large now because pipe
18413675Sdyson * space is pageable.  The pipe code will try to maintain locality of
18513675Sdyson * reference for performance reasons, so small amounts of outstanding I/O
18613675Sdyson * will not wipe the cache.
18713675Sdyson */
18813907Sdyson#define MINPIPESIZE (PIPE_SIZE/3)
18913907Sdyson#define MAXPIPESIZE (2*PIPE_SIZE/3)
19013675Sdyson
191189649Sjhbstatic long amountpipekva;
192133790Ssilbystatic int pipefragretry;
193133790Ssilbystatic int pipeallocfail;
194133790Ssilbystatic int piperesizefail;
195133790Ssilbystatic int piperesizeallowed = 1;
19613907Sdyson
197189649SjhbSYSCTL_LONG(_kern_ipc, OID_AUTO, maxpipekva, CTLFLAG_RDTUN,
198117325Ssilby	   &maxpipekva, 0, "Pipe KVA limit");
199189649SjhbSYSCTL_LONG(_kern_ipc, OID_AUTO, pipekva, CTLFLAG_RD,
200117325Ssilby	   &amountpipekva, 0, "Pipe KVA usage");
201133790SsilbySYSCTL_INT(_kern_ipc, OID_AUTO, pipefragretry, CTLFLAG_RD,
202133790Ssilby	  &pipefragretry, 0, "Pipe allocation retries due to fragmentation");
203133790SsilbySYSCTL_INT(_kern_ipc, OID_AUTO, pipeallocfail, CTLFLAG_RD,
204133790Ssilby	  &pipeallocfail, 0, "Pipe allocation failures");
205133790SsilbySYSCTL_INT(_kern_ipc, OID_AUTO, piperesizefail, CTLFLAG_RD,
206133790Ssilby	  &piperesizefail, 0, "Pipe resize failures");
207133790SsilbySYSCTL_INT(_kern_ipc, OID_AUTO, piperesizeallowed, CTLFLAG_RW,
208133790Ssilby	  &piperesizeallowed, 0, "Pipe resizing allowed");
209117325Ssilby
21091413Salfredstatic void pipeinit(void *dummy __unused);
21191413Salfredstatic void pipeclose(struct pipe *cpipe);
21291413Salfredstatic void pipe_free_kmem(struct pipe *cpipe);
213133790Ssilbystatic int pipe_create(struct pipe *pipe, int backing);
21491413Salfredstatic __inline int pipelock(struct pipe *cpipe, int catch);
21591413Salfredstatic __inline void pipeunlock(struct pipe *cpipe);
21691413Salfredstatic __inline void pipeselwakeup(struct pipe *cpipe);
21714037Sdyson#ifndef PIPE_NODIRECT
21891413Salfredstatic int pipe_build_write_buffer(struct pipe *wpipe, struct uio *uio);
21991413Salfredstatic void pipe_destroy_write_buffer(struct pipe *wpipe);
22091413Salfredstatic int pipe_direct_write(struct pipe *wpipe, struct uio *uio);
22191413Salfredstatic void pipe_clone_write_buffer(struct pipe *wpipe);
22214037Sdyson#endif
22391413Salfredstatic int pipespace(struct pipe *cpipe, int size);
224132579Srwatsonstatic int pipespace_new(struct pipe *cpipe, int size);
22513675Sdyson
226132987Sgreenstatic int	pipe_zone_ctor(void *mem, int size, void *arg, int flags);
227132987Sgreenstatic int	pipe_zone_init(void *mem, int size, int flags);
228125293Srwatsonstatic void	pipe_zone_fini(void *mem, int size);
229125293Srwatson
23092751Sjeffstatic uma_zone_t pipe_zone;
231226578Skibstatic struct unrhdr *pipeino_unr;
232226578Skibstatic dev_t pipedev_ino;
23327899Sdyson
23491372SalfredSYSINIT(vfs, SI_SUB_VFS, SI_ORDER_ANY, pipeinit, NULL);
23591372Salfred
23691372Salfredstatic void
23791372Salfredpipeinit(void *dummy __unused)
23891372Salfred{
239118880Salc
240170022Srwatson	pipe_zone = uma_zcreate("pipe", sizeof(struct pipepair),
241170022Srwatson	    pipe_zone_ctor, NULL, pipe_zone_init, pipe_zone_fini,
242125293Srwatson	    UMA_ALIGN_PTR, 0);
243118880Salc	KASSERT(pipe_zone != NULL, ("pipe_zone not initialized"));
244226578Skib	pipeino_unr = new_unrhdr(1, INT32_MAX, NULL);
245226578Skib	KASSERT(pipeino_unr != NULL, ("pipe fake inodes not initialized"));
246226578Skib	pipedev_ino = devfs_alloc_cdp_inode();
247226578Skib	KASSERT(pipedev_ino > 0, ("pipe dev inode not initialized"));
24891372Salfred}
24991372Salfred
250132987Sgreenstatic int
251132987Sgreenpipe_zone_ctor(void *mem, int size, void *arg, int flags)
252125293Srwatson{
253125293Srwatson	struct pipepair *pp;
254125293Srwatson	struct pipe *rpipe, *wpipe;
255125293Srwatson
256125293Srwatson	KASSERT(size == sizeof(*pp), ("pipe_zone_ctor: wrong size"));
257125293Srwatson
258125293Srwatson	pp = (struct pipepair *)mem;
259125293Srwatson
260125293Srwatson	/*
261125293Srwatson	 * We zero both pipe endpoints to make sure all the kmem pointers
262125293Srwatson	 * are NULL, flag fields are zero'd, etc.  We timestamp both
263125293Srwatson	 * endpoints with the same time.
264125293Srwatson	 */
265125293Srwatson	rpipe = &pp->pp_rpipe;
266125293Srwatson	bzero(rpipe, sizeof(*rpipe));
267125293Srwatson	vfs_timestamp(&rpipe->pipe_ctime);
268125293Srwatson	rpipe->pipe_atime = rpipe->pipe_mtime = rpipe->pipe_ctime;
269125293Srwatson
270125293Srwatson	wpipe = &pp->pp_wpipe;
271125293Srwatson	bzero(wpipe, sizeof(*wpipe));
272125293Srwatson	wpipe->pipe_ctime = rpipe->pipe_ctime;
273125293Srwatson	wpipe->pipe_atime = wpipe->pipe_mtime = rpipe->pipe_ctime;
274125293Srwatson
275125293Srwatson	rpipe->pipe_peer = wpipe;
276125293Srwatson	rpipe->pipe_pair = pp;
277125293Srwatson	wpipe->pipe_peer = rpipe;
278125293Srwatson	wpipe->pipe_pair = pp;
279125293Srwatson
280125293Srwatson	/*
281125293Srwatson	 * Mark both endpoints as present; they will later get free'd
282125293Srwatson	 * one at a time.  When both are free'd, then the whole pair
283125293Srwatson	 * is released.
284125293Srwatson	 */
285179243Skib	rpipe->pipe_present = PIPE_ACTIVE;
286179243Skib	wpipe->pipe_present = PIPE_ACTIVE;
287125293Srwatson
288125293Srwatson	/*
289125293Srwatson	 * Eventually, the MAC Framework may initialize the label
290125293Srwatson	 * in ctor or init, but for now we do it elswhere to avoid
291125293Srwatson	 * blocking in ctor or init.
292125293Srwatson	 */
293125293Srwatson	pp->pp_label = NULL;
294125293Srwatson
295132987Sgreen	return (0);
296125293Srwatson}
297125293Srwatson
298132987Sgreenstatic int
299132987Sgreenpipe_zone_init(void *mem, int size, int flags)
300125293Srwatson{
301125293Srwatson	struct pipepair *pp;
302125293Srwatson
303125293Srwatson	KASSERT(size == sizeof(*pp), ("pipe_zone_init: wrong size"));
304125293Srwatson
305125293Srwatson	pp = (struct pipepair *)mem;
306125293Srwatson
307125293Srwatson	mtx_init(&pp->pp_mtx, "pipe mutex", NULL, MTX_DEF | MTX_RECURSE);
308132987Sgreen	return (0);
309125293Srwatson}
310125293Srwatson
311125293Srwatsonstatic void
312125293Srwatsonpipe_zone_fini(void *mem, int size)
313125293Srwatson{
314125293Srwatson	struct pipepair *pp;
315125293Srwatson
316125293Srwatson	KASSERT(size == sizeof(*pp), ("pipe_zone_fini: wrong size"));
317125293Srwatson
318125293Srwatson	pp = (struct pipepair *)mem;
319125293Srwatson
320125293Srwatson	mtx_destroy(&pp->pp_mtx);
321125293Srwatson}
322125293Srwatson
32313675Sdyson/*
324167232Srwatson * The pipe system call for the DTYPE_PIPE type of pipes.  If we fail, let
325167232Srwatson * the zone pick up the pieces via pipeclose().
32613675Sdyson */
32713675Sdysonint
328184849Sedkern_pipe(struct thread *td, int fildes[2])
32913675Sdyson{
330248532Sjkim
331248532Sjkim	return (do_pipe(td, fildes, 0));
332248532Sjkim}
333248532Sjkim
334248532Sjkimint
335248532Sjkimdo_pipe(struct thread *td, int fildes[2], int flags)
336248532Sjkim{
33783366Sjulian	struct filedesc *fdp = td->td_proc->p_fd;
33813675Sdyson	struct file *rf, *wf;
339125293Srwatson	struct pipepair *pp;
34013675Sdyson	struct pipe *rpipe, *wpipe;
341248532Sjkim	int fd, fflags, error;
34227899Sdyson
343125293Srwatson	pp = uma_zalloc(pipe_zone, M_WAITOK);
344125293Srwatson#ifdef MAC
345125293Srwatson	/*
346126249Srwatson	 * The MAC label is shared between the connected endpoints.  As a
347172930Srwatson	 * result mac_pipe_init() and mac_pipe_create() are called once
348126249Srwatson	 * for the pair, and not on the endpoints.
349125293Srwatson	 */
350172930Srwatson	mac_pipe_init(pp);
351172930Srwatson	mac_pipe_create(td->td_ucred, pp);
352125293Srwatson#endif
353125293Srwatson	rpipe = &pp->pp_rpipe;
354125293Srwatson	wpipe = &pp->pp_wpipe;
355125293Srwatson
356193951Skib	knlist_init_mtx(&rpipe->pipe_sel.si_note, PIPE_MTX(rpipe));
357193951Skib	knlist_init_mtx(&wpipe->pipe_sel.si_note, PIPE_MTX(wpipe));
358140369Ssilby
359133790Ssilby	/* Only the forward direction pipe is backed by default */
360155035Sglebius	if ((error = pipe_create(rpipe, 1)) != 0 ||
361155035Sglebius	    (error = pipe_create(wpipe, 0)) != 0) {
362124394Sdes		pipeclose(rpipe);
363124394Sdes		pipeclose(wpipe);
364155035Sglebius		return (error);
36576364Salfred	}
366124394Sdes
36713907Sdyson	rpipe->pipe_state |= PIPE_DIRECTOK;
36813907Sdyson	wpipe->pipe_state |= PIPE_DIRECTOK;
36913675Sdyson
370248532Sjkim	error = falloc(td, &rf, &fd, flags);
37170915Sdwmalone	if (error) {
37270915Sdwmalone		pipeclose(rpipe);
37370915Sdwmalone		pipeclose(wpipe);
37470915Sdwmalone		return (error);
37570915Sdwmalone	}
376121256Sdwmalone	/* An extra reference on `rf' has been held for us by falloc(). */
377184849Sed	fildes[0] = fd;
37870915Sdwmalone
379248532Sjkim	fflags = FREAD | FWRITE;
380248532Sjkim	if ((flags & O_NONBLOCK) != 0)
381248532Sjkim		fflags |= FNONBLOCK;
382248532Sjkim
38370803Sdwmalone	/*
38470803Sdwmalone	 * Warning: once we've gotten past allocation of the fd for the
38570803Sdwmalone	 * read-side, we can only drop the read side via fdrop() in order
38670803Sdwmalone	 * to avoid races against processes which manage to dup() the read
38770803Sdwmalone	 * side while we are blocked trying to allocate the write side.
38870803Sdwmalone	 */
389248532Sjkim	finit(rf, fflags, DTYPE_PIPE, rpipe, &pipeops);
390248532Sjkim	error = falloc(td, &wf, &fd, flags);
39170915Sdwmalone	if (error) {
392184849Sed		fdclose(fdp, rf, fildes[0], td);
39383366Sjulian		fdrop(rf, td);
39470915Sdwmalone		/* rpipe has been closed by fdrop(). */
39570915Sdwmalone		pipeclose(wpipe);
39670915Sdwmalone		return (error);
39770915Sdwmalone	}
398121256Sdwmalone	/* An extra reference on `wf' has been held for us by falloc(). */
399248532Sjkim	finit(wf, fflags, DTYPE_PIPE, wpipe, &pipeops);
400121256Sdwmalone	fdrop(wf, td);
401184849Sed	fildes[1] = fd;
40283366Sjulian	fdrop(rf, td);
40313675Sdyson
40413675Sdyson	return (0);
40513675Sdyson}
40613675Sdyson
407184849Sed/* ARGSUSED */
408184849Sedint
409225617Skmacysys_pipe(struct thread *td, struct pipe_args *uap)
410184849Sed{
411184849Sed	int error;
412184849Sed	int fildes[2];
413184849Sed
414184849Sed	error = kern_pipe(td, fildes);
415184849Sed	if (error)
416184849Sed		return (error);
417184849Sed
418184849Sed	td->td_retval[0] = fildes[0];
419184849Sed	td->td_retval[1] = fildes[1];
420184849Sed
421184849Sed	return (0);
422184849Sed}
423184849Sed
42413909Sdyson/*
42513909Sdyson * Allocate kva for pipe circular buffer, the space is pageable
42676364Salfred * This routine will 'realloc' the size of a pipe safely, if it fails
42776364Salfred * it will retain the old buffer.
42876364Salfred * If it fails it will return ENOMEM.
42913909Sdyson */
43076364Salfredstatic int
431132579Srwatsonpipespace_new(cpipe, size)
43213675Sdyson	struct pipe *cpipe;
43376364Salfred	int size;
43413675Sdyson{
43576364Salfred	caddr_t buffer;
436133790Ssilby	int error, cnt, firstseg;
437117325Ssilby	static int curfail = 0;
438117325Ssilby	static struct timeval lastfail;
43913675Sdyson
440125293Srwatson	KASSERT(!mtx_owned(PIPE_MTX(cpipe)), ("pipespace: pipe mutex locked"));
441133790Ssilby	KASSERT(!(cpipe->pipe_state & PIPE_DIRECTW),
442133790Ssilby		("pipespace: resize of direct writes not allowed"));
443133790Ssilbyretry:
444133790Ssilby	cnt = cpipe->pipe_buffer.cnt;
445133790Ssilby	if (cnt > size)
446133790Ssilby		size = cnt;
44779224Sdillon
448118764Ssilby	size = round_page(size);
449118764Ssilby	buffer = (caddr_t) vm_map_min(pipe_map);
45013675Sdyson
451122163Salc	error = vm_map_find(pipe_map, NULL, 0,
45276364Salfred		(vm_offset_t *) &buffer, size, 1,
45313688Sdyson		VM_PROT_ALL, VM_PROT_ALL, 0);
45476364Salfred	if (error != KERN_SUCCESS) {
455133790Ssilby		if ((cpipe->pipe_buffer.buffer == NULL) &&
456133790Ssilby			(size > SMALL_PIPE_SIZE)) {
457133790Ssilby			size = SMALL_PIPE_SIZE;
458133790Ssilby			pipefragretry++;
459133790Ssilby			goto retry;
460133790Ssilby		}
461133790Ssilby		if (cpipe->pipe_buffer.buffer == NULL) {
462133790Ssilby			pipeallocfail++;
463133790Ssilby			if (ppsratecheck(&lastfail, &curfail, 1))
464133790Ssilby				printf("kern.ipc.maxpipekva exceeded; see tuning(7)\n");
465133790Ssilby		} else {
466133790Ssilby			piperesizefail++;
467133790Ssilby		}
46876364Salfred		return (ENOMEM);
46976364Salfred	}
47076364Salfred
471133790Ssilby	/* copy data, then free old resources if we're resizing */
472133790Ssilby	if (cnt > 0) {
473133790Ssilby		if (cpipe->pipe_buffer.in <= cpipe->pipe_buffer.out) {
474133790Ssilby			firstseg = cpipe->pipe_buffer.size - cpipe->pipe_buffer.out;
475133790Ssilby			bcopy(&cpipe->pipe_buffer.buffer[cpipe->pipe_buffer.out],
476133790Ssilby				buffer, firstseg);
477133790Ssilby			if ((cnt - firstseg) > 0)
478133790Ssilby				bcopy(cpipe->pipe_buffer.buffer, &buffer[firstseg],
479133790Ssilby					cpipe->pipe_buffer.in);
480133790Ssilby		} else {
481133790Ssilby			bcopy(&cpipe->pipe_buffer.buffer[cpipe->pipe_buffer.out],
482133790Ssilby				buffer, cnt);
483133790Ssilby		}
484133790Ssilby	}
48576364Salfred	pipe_free_kmem(cpipe);
48676364Salfred	cpipe->pipe_buffer.buffer = buffer;
48776364Salfred	cpipe->pipe_buffer.size = size;
488133790Ssilby	cpipe->pipe_buffer.in = cnt;
48976364Salfred	cpipe->pipe_buffer.out = 0;
490133790Ssilby	cpipe->pipe_buffer.cnt = cnt;
491189649Sjhb	atomic_add_long(&amountpipekva, cpipe->pipe_buffer.size);
49276364Salfred	return (0);
49313907Sdyson}
49413688Sdyson
49513907Sdyson/*
496132579Srwatson * Wrapper for pipespace_new() that performs locking assertions.
497132579Srwatson */
498132579Srwatsonstatic int
499132579Srwatsonpipespace(cpipe, size)
500132579Srwatson	struct pipe *cpipe;
501132579Srwatson	int size;
502132579Srwatson{
503132579Srwatson
504133049Ssilby	KASSERT(cpipe->pipe_state & PIPE_LOCKFL,
505133049Ssilby		("Unlocked pipe passed to pipespace"));
506132579Srwatson	return (pipespace_new(cpipe, size));
507132579Srwatson}
508132579Srwatson
509132579Srwatson/*
51013675Sdyson * lock a pipe for I/O, blocking other access
51113675Sdyson */
51213675Sdysonstatic __inline int
51313907Sdysonpipelock(cpipe, catch)
51413675Sdyson	struct pipe *cpipe;
51513907Sdyson	int catch;
51613675Sdyson{
51713776Sdyson	int error;
51876364Salfred
51991362Salfred	PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
52091362Salfred	while (cpipe->pipe_state & PIPE_LOCKFL) {
52113675Sdyson		cpipe->pipe_state |= PIPE_LWANT;
52291362Salfred		error = msleep(cpipe, PIPE_MTX(cpipe),
52391362Salfred		    catch ? (PRIBIO | PCATCH) : PRIBIO,
52476760Salfred		    "pipelk", 0);
525124394Sdes		if (error != 0)
52676760Salfred			return (error);
52713675Sdyson	}
52891362Salfred	cpipe->pipe_state |= PIPE_LOCKFL;
52976760Salfred	return (0);
53013675Sdyson}
53113675Sdyson
53213675Sdyson/*
53313675Sdyson * unlock a pipe I/O lock
53413675Sdyson */
53513675Sdysonstatic __inline void
53613675Sdysonpipeunlock(cpipe)
53713675Sdyson	struct pipe *cpipe;
53813675Sdyson{
53976364Salfred
54091362Salfred	PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
541133049Ssilby	KASSERT(cpipe->pipe_state & PIPE_LOCKFL,
542133049Ssilby		("Unlocked pipe passed to pipeunlock"));
54391362Salfred	cpipe->pipe_state &= ~PIPE_LOCKFL;
54413675Sdyson	if (cpipe->pipe_state & PIPE_LWANT) {
54513675Sdyson		cpipe->pipe_state &= ~PIPE_LWANT;
54614177Sdyson		wakeup(cpipe);
54713675Sdyson	}
54813675Sdyson}
54913675Sdyson
55014037Sdysonstatic __inline void
55114037Sdysonpipeselwakeup(cpipe)
55214037Sdyson	struct pipe *cpipe;
55314037Sdyson{
55476364Salfred
555126252Srwatson	PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
55614037Sdyson	if (cpipe->pipe_state & PIPE_SEL) {
557122352Stanimura		selwakeuppri(&cpipe->pipe_sel, PSOCK);
558174647Sjeff		if (!SEL_WAITING(&cpipe->pipe_sel))
559174647Sjeff			cpipe->pipe_state &= ~PIPE_SEL;
56014037Sdyson	}
56141086Struckman	if ((cpipe->pipe_state & PIPE_ASYNC) && cpipe->pipe_sigio)
56295883Salfred		pgsigio(&cpipe->pipe_sigio, SIGIO, 0);
563133741Sjmg	KNOTE_LOCKED(&cpipe->pipe_sel.si_note, 0);
56414037Sdyson}
56514037Sdyson
566126131Sgreen/*
567126131Sgreen * Initialize and allocate VM and memory for pipe.  The structure
568126131Sgreen * will start out zero'd from the ctor, so we just manage the kmem.
569126131Sgreen */
570126131Sgreenstatic int
571133790Ssilbypipe_create(pipe, backing)
572126131Sgreen	struct pipe *pipe;
573133790Ssilby	int backing;
574126131Sgreen{
575126131Sgreen	int error;
576126131Sgreen
577133790Ssilby	if (backing) {
578133790Ssilby		if (amountpipekva > maxpipekva / 2)
579133790Ssilby			error = pipespace_new(pipe, SMALL_PIPE_SIZE);
580133790Ssilby		else
581133790Ssilby			error = pipespace_new(pipe, PIPE_SIZE);
582133790Ssilby	} else {
583133790Ssilby		/* If we're not backing this pipe, no need to do anything. */
584133790Ssilby		error = 0;
585133790Ssilby	}
586229248Skib	pipe->pipe_ino = -1;
587132579Srwatson	return (error);
588126131Sgreen}
589126131Sgreen
59013675Sdyson/* ARGSUSED */
59113675Sdysonstatic int
592101941Srwatsonpipe_read(fp, uio, active_cred, flags, td)
59313675Sdyson	struct file *fp;
59413675Sdyson	struct uio *uio;
595101941Srwatson	struct ucred *active_cred;
59683366Sjulian	struct thread *td;
59745311Sdt	int flags;
59813675Sdyson{
599109153Sdillon	struct pipe *rpipe = fp->f_data;
60047748Salc	int error;
60113675Sdyson	int nread = 0;
602233353Skib	int size;
60313675Sdyson
60491362Salfred	PIPE_LOCK(rpipe);
60513675Sdyson	++rpipe->pipe_busy;
60647748Salc	error = pipelock(rpipe, 1);
60747748Salc	if (error)
60847748Salc		goto unlocked_error;
60947748Salc
610101768Srwatson#ifdef MAC
611172930Srwatson	error = mac_pipe_check_read(active_cred, rpipe->pipe_pair);
612101768Srwatson	if (error)
613101768Srwatson		goto locked_error;
614101768Srwatson#endif
615133790Ssilby	if (amountpipekva > (3 * maxpipekva) / 4) {
616133790Ssilby		if (!(rpipe->pipe_state & PIPE_DIRECTW) &&
617133790Ssilby			(rpipe->pipe_buffer.size > SMALL_PIPE_SIZE) &&
618133790Ssilby			(rpipe->pipe_buffer.cnt <= SMALL_PIPE_SIZE) &&
619133790Ssilby			(piperesizeallowed == 1)) {
620133790Ssilby			PIPE_UNLOCK(rpipe);
621133790Ssilby			pipespace(rpipe, SMALL_PIPE_SIZE);
622133790Ssilby			PIPE_LOCK(rpipe);
623133790Ssilby		}
624133790Ssilby	}
625101768Srwatson
62613675Sdyson	while (uio->uio_resid) {
62713907Sdyson		/*
62813907Sdyson		 * normal pipe buffer receive
62913907Sdyson		 */
63013675Sdyson		if (rpipe->pipe_buffer.cnt > 0) {
63118863Sdyson			size = rpipe->pipe_buffer.size - rpipe->pipe_buffer.out;
63213675Sdyson			if (size > rpipe->pipe_buffer.cnt)
63313675Sdyson				size = rpipe->pipe_buffer.cnt;
634233353Skib			if (size > uio->uio_resid)
635233353Skib				size = uio->uio_resid;
63647748Salc
63791362Salfred			PIPE_UNLOCK(rpipe);
638116127Smux			error = uiomove(
639116127Smux			    &rpipe->pipe_buffer.buffer[rpipe->pipe_buffer.out],
640116127Smux			    size, uio);
64191362Salfred			PIPE_LOCK(rpipe);
64276760Salfred			if (error)
64313675Sdyson				break;
64476760Salfred
64513675Sdyson			rpipe->pipe_buffer.out += size;
64613675Sdyson			if (rpipe->pipe_buffer.out >= rpipe->pipe_buffer.size)
64713675Sdyson				rpipe->pipe_buffer.out = 0;
64813675Sdyson
64913675Sdyson			rpipe->pipe_buffer.cnt -= size;
65047748Salc
65147748Salc			/*
65247748Salc			 * If there is no more to read in the pipe, reset
65347748Salc			 * its pointers to the beginning.  This improves
65447748Salc			 * cache hit stats.
65547748Salc			 */
65647748Salc			if (rpipe->pipe_buffer.cnt == 0) {
65747748Salc				rpipe->pipe_buffer.in = 0;
65847748Salc				rpipe->pipe_buffer.out = 0;
65947748Salc			}
66013675Sdyson			nread += size;
66114037Sdyson#ifndef PIPE_NODIRECT
66213907Sdyson		/*
66313907Sdyson		 * Direct copy, bypassing a kernel buffer.
66413907Sdyson		 */
66513907Sdyson		} else if ((size = rpipe->pipe_map.cnt) &&
66647748Salc			   (rpipe->pipe_state & PIPE_DIRECTW)) {
667233353Skib			if (size > uio->uio_resid)
66818863Sdyson				size = (u_int) uio->uio_resid;
66947748Salc
67091362Salfred			PIPE_UNLOCK(rpipe);
671127501Salc			error = uiomove_fromphys(rpipe->pipe_map.ms,
672127501Salc			    rpipe->pipe_map.pos, size, uio);
67391362Salfred			PIPE_LOCK(rpipe);
67413907Sdyson			if (error)
67513907Sdyson				break;
67613907Sdyson			nread += size;
67713907Sdyson			rpipe->pipe_map.pos += size;
67813907Sdyson			rpipe->pipe_map.cnt -= size;
67913907Sdyson			if (rpipe->pipe_map.cnt == 0) {
68013907Sdyson				rpipe->pipe_state &= ~PIPE_DIRECTW;
68113907Sdyson				wakeup(rpipe);
68213907Sdyson			}
68314037Sdyson#endif
68413675Sdyson		} else {
68513675Sdyson			/*
68613675Sdyson			 * detect EOF condition
68776760Salfred			 * read returns 0 on EOF, no need to set error
68813675Sdyson			 */
68976760Salfred			if (rpipe->pipe_state & PIPE_EOF)
69013675Sdyson				break;
69143623Sdillon
69213675Sdyson			/*
69313675Sdyson			 * If the "write-side" has been blocked, wake it up now.
69413675Sdyson			 */
69513675Sdyson			if (rpipe->pipe_state & PIPE_WANTW) {
69613675Sdyson				rpipe->pipe_state &= ~PIPE_WANTW;
69713675Sdyson				wakeup(rpipe);
69813675Sdyson			}
69943623Sdillon
70043623Sdillon			/*
70147748Salc			 * Break if some data was read.
70243623Sdillon			 */
70347748Salc			if (nread > 0)
70413675Sdyson				break;
70516960Sdyson
70643623Sdillon			/*
707124394Sdes			 * Unlock the pipe buffer for our remaining processing.
708116127Smux			 * We will either break out with an error or we will
709116127Smux			 * sleep and relock to loop.
71043623Sdillon			 */
71147748Salc			pipeunlock(rpipe);
71243623Sdillon
71313675Sdyson			/*
71447748Salc			 * Handle non-blocking mode operation or
71547748Salc			 * wait for more data.
71613675Sdyson			 */
71776760Salfred			if (fp->f_flag & FNONBLOCK) {
71847748Salc				error = EAGAIN;
71976760Salfred			} else {
72047748Salc				rpipe->pipe_state |= PIPE_WANTR;
72191362Salfred				if ((error = msleep(rpipe, PIPE_MTX(rpipe),
72291362Salfred				    PRIBIO | PCATCH,
72377140Salfred				    "piperd", 0)) == 0)
72447748Salc					error = pipelock(rpipe, 1);
72513675Sdyson			}
72647748Salc			if (error)
72747748Salc				goto unlocked_error;
72813675Sdyson		}
72913675Sdyson	}
730101768Srwatson#ifdef MAC
731101768Srwatsonlocked_error:
732101768Srwatson#endif
73347748Salc	pipeunlock(rpipe);
73413675Sdyson
73591362Salfred	/* XXX: should probably do this before getting any locks. */
73624101Sbde	if (error == 0)
73755112Sbde		vfs_timestamp(&rpipe->pipe_atime);
73847748Salcunlocked_error:
73947748Salc	--rpipe->pipe_busy;
74013913Sdyson
74147748Salc	/*
74247748Salc	 * PIPE_WANT processing only makes sense if pipe_busy is 0.
74347748Salc	 */
74413675Sdyson	if ((rpipe->pipe_busy == 0) && (rpipe->pipe_state & PIPE_WANT)) {
74513675Sdyson		rpipe->pipe_state &= ~(PIPE_WANT|PIPE_WANTW);
74613675Sdyson		wakeup(rpipe);
74713675Sdyson	} else if (rpipe->pipe_buffer.cnt < MINPIPESIZE) {
74813675Sdyson		/*
74947748Salc		 * Handle write blocking hysteresis.
75013675Sdyson		 */
75113675Sdyson		if (rpipe->pipe_state & PIPE_WANTW) {
75213675Sdyson			rpipe->pipe_state &= ~PIPE_WANTW;
75313675Sdyson			wakeup(rpipe);
75413675Sdyson		}
75513675Sdyson	}
75614037Sdyson
75714802Sdyson	if ((rpipe->pipe_buffer.size - rpipe->pipe_buffer.cnt) >= PIPE_BUF)
75814037Sdyson		pipeselwakeup(rpipe);
75914037Sdyson
76091362Salfred	PIPE_UNLOCK(rpipe);
76176760Salfred	return (error);
76213675Sdyson}
76313675Sdyson
76414037Sdyson#ifndef PIPE_NODIRECT
76513907Sdyson/*
76613907Sdyson * Map the sending processes' buffer into kernel space and wire it.
76713907Sdyson * This is similar to a physical write operation.
76813907Sdyson */
76913675Sdysonstatic int
77013907Sdysonpipe_build_write_buffer(wpipe, uio)
77113907Sdyson	struct pipe *wpipe;
77213675Sdyson	struct uio *uio;
77313675Sdyson{
77418863Sdyson	u_int size;
775216511Salc	int i;
77613907Sdyson
77791412Salfred	PIPE_LOCK_ASSERT(wpipe, MA_NOTOWNED);
778133790Ssilby	KASSERT(wpipe->pipe_state & PIPE_DIRECTW,
779133790Ssilby		("Clone attempt on non-direct write pipe!"));
78079224Sdillon
781233353Skib	if (uio->uio_iov->iov_len > wpipe->pipe_buffer.size)
782233353Skib                size = wpipe->pipe_buffer.size;
783233353Skib	else
784233353Skib                size = uio->uio_iov->iov_len;
78513907Sdyson
786216699Salc	if ((i = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
787216699Salc	    (vm_offset_t)uio->uio_iov->iov_base, size, VM_PROT_READ,
788216699Salc	    wpipe->pipe_map.ms, PIPENPAGES)) < 0)
789193893Scperciva		return (EFAULT);
79013907Sdyson
79113907Sdyson/*
79213907Sdyson * set up the control block
79313907Sdyson */
79413907Sdyson	wpipe->pipe_map.npages = i;
79576760Salfred	wpipe->pipe_map.pos =
79676760Salfred	    ((vm_offset_t) uio->uio_iov->iov_base) & PAGE_MASK;
79713907Sdyson	wpipe->pipe_map.cnt = size;
79813907Sdyson
79913907Sdyson/*
80013907Sdyson * and update the uio data
80113907Sdyson */
80213907Sdyson
80313907Sdyson	uio->uio_iov->iov_len -= size;
804104908Smike	uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + size;
80513907Sdyson	if (uio->uio_iov->iov_len == 0)
80613907Sdyson		uio->uio_iov++;
80713907Sdyson	uio->uio_resid -= size;
80813907Sdyson	uio->uio_offset += size;
80976760Salfred	return (0);
81013907Sdyson}
81113907Sdyson
81213907Sdyson/*
81313907Sdyson * unmap and unwire the process buffer
81413907Sdyson */
81513907Sdysonstatic void
81613907Sdysonpipe_destroy_write_buffer(wpipe)
81776760Salfred	struct pipe *wpipe;
81813907Sdyson{
81976364Salfred
820127501Salc	PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
821216511Salc	vm_page_unhold_pages(wpipe->pipe_map.ms, wpipe->pipe_map.npages);
82291653Stanimura	wpipe->pipe_map.npages = 0;
82313907Sdyson}
82413907Sdyson
82513907Sdyson/*
82613907Sdyson * In the case of a signal, the writing process might go away.  This
82713907Sdyson * code copies the data into the circular buffer so that the source
82813907Sdyson * pages can be freed without loss of data.
82913907Sdyson */
83013907Sdysonstatic void
83113907Sdysonpipe_clone_write_buffer(wpipe)
83276364Salfred	struct pipe *wpipe;
83313907Sdyson{
834127501Salc	struct uio uio;
835127501Salc	struct iovec iov;
83613907Sdyson	int size;
83713907Sdyson	int pos;
83813907Sdyson
83991362Salfred	PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
84013907Sdyson	size = wpipe->pipe_map.cnt;
84113907Sdyson	pos = wpipe->pipe_map.pos;
84213907Sdyson
84313907Sdyson	wpipe->pipe_buffer.in = size;
84413907Sdyson	wpipe->pipe_buffer.out = 0;
84513907Sdyson	wpipe->pipe_buffer.cnt = size;
84613907Sdyson	wpipe->pipe_state &= ~PIPE_DIRECTW;
84713907Sdyson
848119811Salc	PIPE_UNLOCK(wpipe);
849127501Salc	iov.iov_base = wpipe->pipe_buffer.buffer;
850127501Salc	iov.iov_len = size;
851127501Salc	uio.uio_iov = &iov;
852127501Salc	uio.uio_iovcnt = 1;
853127501Salc	uio.uio_offset = 0;
854127501Salc	uio.uio_resid = size;
855127501Salc	uio.uio_segflg = UIO_SYSSPACE;
856127501Salc	uio.uio_rw = UIO_READ;
857127501Salc	uio.uio_td = curthread;
858127501Salc	uiomove_fromphys(wpipe->pipe_map.ms, pos, size, &uio);
859127501Salc	PIPE_LOCK(wpipe);
86013907Sdyson	pipe_destroy_write_buffer(wpipe);
86113907Sdyson}
86213907Sdyson
86313907Sdyson/*
86413907Sdyson * This implements the pipe buffer write mechanism.  Note that only
86513907Sdyson * a direct write OR a normal pipe write can be pending at any given time.
86613907Sdyson * If there are any characters in the pipe buffer, the direct write will
86713907Sdyson * be deferred until the receiving process grabs all of the bytes from
86813907Sdyson * the pipe buffer.  Then the direct mapping write is set-up.
86913907Sdyson */
87013907Sdysonstatic int
87113907Sdysonpipe_direct_write(wpipe, uio)
87213907Sdyson	struct pipe *wpipe;
87313907Sdyson	struct uio *uio;
87413907Sdyson{
87513907Sdyson	int error;
87676364Salfred
87713951Sdysonretry:
87891362Salfred	PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
879133049Ssilby	error = pipelock(wpipe, 1);
880133049Ssilby	if (wpipe->pipe_state & PIPE_EOF)
881133049Ssilby		error = EPIPE;
882133049Ssilby	if (error) {
883133049Ssilby		pipeunlock(wpipe);
884133049Ssilby		goto error1;
885133049Ssilby	}
88613907Sdyson	while (wpipe->pipe_state & PIPE_DIRECTW) {
88776760Salfred		if (wpipe->pipe_state & PIPE_WANTR) {
88813951Sdyson			wpipe->pipe_state &= ~PIPE_WANTR;
88913951Sdyson			wakeup(wpipe);
89013951Sdyson		}
891173750Sdumbbell		pipeselwakeup(wpipe);
89213992Sdyson		wpipe->pipe_state |= PIPE_WANTW;
893133049Ssilby		pipeunlock(wpipe);
89491362Salfred		error = msleep(wpipe, PIPE_MTX(wpipe),
89591362Salfred		    PRIBIO | PCATCH, "pipdww", 0);
89614802Sdyson		if (error)
89713907Sdyson			goto error1;
898133049Ssilby		else
899133049Ssilby			goto retry;
90013907Sdyson	}
90113907Sdyson	wpipe->pipe_map.cnt = 0;	/* transfer not ready yet */
90213951Sdyson	if (wpipe->pipe_buffer.cnt > 0) {
90376760Salfred		if (wpipe->pipe_state & PIPE_WANTR) {
90413951Sdyson			wpipe->pipe_state &= ~PIPE_WANTR;
90513951Sdyson			wakeup(wpipe);
90613951Sdyson		}
907173750Sdumbbell		pipeselwakeup(wpipe);
90813992Sdyson		wpipe->pipe_state |= PIPE_WANTW;
909133049Ssilby		pipeunlock(wpipe);
91091362Salfred		error = msleep(wpipe, PIPE_MTX(wpipe),
91191362Salfred		    PRIBIO | PCATCH, "pipdwc", 0);
91214802Sdyson		if (error)
91313907Sdyson			goto error1;
914133049Ssilby		else
915133049Ssilby			goto retry;
91613907Sdyson	}
91713907Sdyson
91813951Sdyson	wpipe->pipe_state |= PIPE_DIRECTW;
91913951Sdyson
920119872Salc	PIPE_UNLOCK(wpipe);
92113907Sdyson	error = pipe_build_write_buffer(wpipe, uio);
922119872Salc	PIPE_LOCK(wpipe);
92313907Sdyson	if (error) {
92413907Sdyson		wpipe->pipe_state &= ~PIPE_DIRECTW;
925133049Ssilby		pipeunlock(wpipe);
92613907Sdyson		goto error1;
92713907Sdyson	}
92813907Sdyson
92913907Sdyson	error = 0;
93013907Sdyson	while (!error && (wpipe->pipe_state & PIPE_DIRECTW)) {
93113907Sdyson		if (wpipe->pipe_state & PIPE_EOF) {
93213907Sdyson			pipe_destroy_write_buffer(wpipe);
933112981Shsu			pipeselwakeup(wpipe);
93413907Sdyson			pipeunlock(wpipe);
93514802Sdyson			error = EPIPE;
93614802Sdyson			goto error1;
93713907Sdyson		}
93813992Sdyson		if (wpipe->pipe_state & PIPE_WANTR) {
93913992Sdyson			wpipe->pipe_state &= ~PIPE_WANTR;
94013992Sdyson			wakeup(wpipe);
94113992Sdyson		}
94214037Sdyson		pipeselwakeup(wpipe);
943133049Ssilby		pipeunlock(wpipe);
94491362Salfred		error = msleep(wpipe, PIPE_MTX(wpipe), PRIBIO | PCATCH,
94591362Salfred		    "pipdwt", 0);
946133049Ssilby		pipelock(wpipe, 0);
94713907Sdyson	}
94813907Sdyson
949126131Sgreen	if (wpipe->pipe_state & PIPE_EOF)
950126131Sgreen		error = EPIPE;
95113907Sdyson	if (wpipe->pipe_state & PIPE_DIRECTW) {
95213907Sdyson		/*
95313907Sdyson		 * this bit of trickery substitutes a kernel buffer for
95413907Sdyson		 * the process that might be going away.
95513907Sdyson		 */
95613907Sdyson		pipe_clone_write_buffer(wpipe);
95713907Sdyson	} else {
95813907Sdyson		pipe_destroy_write_buffer(wpipe);
95913907Sdyson	}
96013907Sdyson	pipeunlock(wpipe);
96176760Salfred	return (error);
96213907Sdyson
96313907Sdysonerror1:
96413907Sdyson	wakeup(wpipe);
96576760Salfred	return (error);
96613907Sdyson}
96714037Sdyson#endif
968124394Sdes
96916960Sdysonstatic int
970101941Srwatsonpipe_write(fp, uio, active_cred, flags, td)
97116960Sdyson	struct file *fp;
97213907Sdyson	struct uio *uio;
973101941Srwatson	struct ucred *active_cred;
97483366Sjulian	struct thread *td;
97545311Sdt	int flags;
97613907Sdyson{
97713675Sdyson	int error = 0;
978233353Skib	int desiredsize;
979233353Skib	ssize_t orig_resid;
98016960Sdyson	struct pipe *wpipe, *rpipe;
98116960Sdyson
982109153Sdillon	rpipe = fp->f_data;
98316960Sdyson	wpipe = rpipe->pipe_peer;
98416960Sdyson
98591395Salfred	PIPE_LOCK(rpipe);
986133049Ssilby	error = pipelock(wpipe, 1);
987133049Ssilby	if (error) {
988133049Ssilby		PIPE_UNLOCK(rpipe);
989133049Ssilby		return (error);
990133049Ssilby	}
99113675Sdyson	/*
99213675Sdyson	 * detect loss of pipe read side, issue SIGPIPE if lost.
99313675Sdyson	 */
994179243Skib	if (wpipe->pipe_present != PIPE_ACTIVE ||
995179243Skib	    (wpipe->pipe_state & PIPE_EOF)) {
996133049Ssilby		pipeunlock(wpipe);
99791395Salfred		PIPE_UNLOCK(rpipe);
99876760Salfred		return (EPIPE);
99913675Sdyson	}
1000101768Srwatson#ifdef MAC
1001172930Srwatson	error = mac_pipe_check_write(active_cred, wpipe->pipe_pair);
1002101768Srwatson	if (error) {
1003133049Ssilby		pipeunlock(wpipe);
1004101768Srwatson		PIPE_UNLOCK(rpipe);
1005101768Srwatson		return (error);
1006101768Srwatson	}
1007101768Srwatson#endif
100877676Sdillon	++wpipe->pipe_busy;
100913675Sdyson
1010133790Ssilby	/* Choose a larger size if it's advantageous */
1011133790Ssilby	desiredsize = max(SMALL_PIPE_SIZE, wpipe->pipe_buffer.size);
1012133790Ssilby	while (desiredsize < wpipe->pipe_buffer.cnt + uio->uio_resid) {
1013133790Ssilby		if (piperesizeallowed != 1)
1014133790Ssilby			break;
1015133790Ssilby		if (amountpipekva > maxpipekva / 2)
1016133790Ssilby			break;
1017133790Ssilby		if (desiredsize == BIG_PIPE_SIZE)
1018133790Ssilby			break;
1019133790Ssilby		desiredsize = desiredsize * 2;
1020133790Ssilby	}
102117163Sdyson
1022133790Ssilby	/* Choose a smaller size if we're in a OOM situation */
1023133790Ssilby	if ((amountpipekva > (3 * maxpipekva) / 4) &&
1024133790Ssilby		(wpipe->pipe_buffer.size > SMALL_PIPE_SIZE) &&
1025133790Ssilby		(wpipe->pipe_buffer.cnt <= SMALL_PIPE_SIZE) &&
1026133790Ssilby		(piperesizeallowed == 1))
1027133790Ssilby		desiredsize = SMALL_PIPE_SIZE;
1028133790Ssilby
1029133790Ssilby	/* Resize if the above determined that a new size was necessary */
1030133790Ssilby	if ((desiredsize != wpipe->pipe_buffer.size) &&
1031133790Ssilby		((wpipe->pipe_state & PIPE_DIRECTW) == 0)) {
1032133049Ssilby		PIPE_UNLOCK(wpipe);
1033133790Ssilby		pipespace(wpipe, desiredsize);
1034133049Ssilby		PIPE_LOCK(wpipe);
103513907Sdyson	}
1036133790Ssilby	if (wpipe->pipe_buffer.size == 0) {
1037133790Ssilby		/*
1038133790Ssilby		 * This can only happen for reverse direction use of pipes
1039133790Ssilby		 * in a complete OOM situation.
1040133790Ssilby		 */
1041133790Ssilby		error = ENOMEM;
1042133790Ssilby		--wpipe->pipe_busy;
1043133790Ssilby		pipeunlock(wpipe);
1044133790Ssilby		PIPE_UNLOCK(wpipe);
1045133790Ssilby		return (error);
1046133790Ssilby	}
104777676Sdillon
1048133049Ssilby	pipeunlock(wpipe);
1049124394Sdes
105013913Sdyson	orig_resid = uio->uio_resid;
105177676Sdillon
105213675Sdyson	while (uio->uio_resid) {
105313907Sdyson		int space;
105476760Salfred
1055133049Ssilby		pipelock(wpipe, 0);
1056133049Ssilby		if (wpipe->pipe_state & PIPE_EOF) {
1057133049Ssilby			pipeunlock(wpipe);
1058133049Ssilby			error = EPIPE;
1059133049Ssilby			break;
1060133049Ssilby		}
106114037Sdyson#ifndef PIPE_NODIRECT
106213907Sdyson		/*
106313907Sdyson		 * If the transfer is large, we can gain performance if
106413907Sdyson		 * we do process-to-process copies directly.
106516416Sdyson		 * If the write is non-blocking, we don't use the
106616416Sdyson		 * direct write mechanism.
106758505Sdillon		 *
106858505Sdillon		 * The direct write mechanism will detect the reader going
106958505Sdillon		 * away on us.
107013907Sdyson		 */
1071165347Spjd		if (uio->uio_segflg == UIO_USERSPACE &&
1072165347Spjd		    uio->uio_iov->iov_len >= PIPE_MINDIRECT &&
1073165347Spjd		    wpipe->pipe_buffer.size >= PIPE_MINDIRECT &&
1074127501Salc		    (fp->f_flag & FNONBLOCK) == 0) {
1075133049Ssilby			pipeunlock(wpipe);
1076105009Salfred			error = pipe_direct_write(wpipe, uio);
107776760Salfred			if (error)
107813907Sdyson				break;
107913907Sdyson			continue;
108091362Salfred		}
108114037Sdyson#endif
108213907Sdyson
108313907Sdyson		/*
108413907Sdyson		 * Pipe buffered writes cannot be coincidental with
108513907Sdyson		 * direct writes.  We wait until the currently executing
108613907Sdyson		 * direct write is completed before we start filling the
108758505Sdillon		 * pipe buffer.  We break out if a signal occurs or the
108858505Sdillon		 * reader goes away.
108913907Sdyson		 */
1090133049Ssilby		if (wpipe->pipe_state & PIPE_DIRECTW) {
109113992Sdyson			if (wpipe->pipe_state & PIPE_WANTR) {
109213992Sdyson				wpipe->pipe_state &= ~PIPE_WANTR;
109313992Sdyson				wakeup(wpipe);
109413992Sdyson			}
1095173750Sdumbbell			pipeselwakeup(wpipe);
1096173750Sdumbbell			wpipe->pipe_state |= PIPE_WANTW;
1097133049Ssilby			pipeunlock(wpipe);
109891395Salfred			error = msleep(wpipe, PIPE_MTX(rpipe), PRIBIO | PCATCH,
109991362Salfred			    "pipbww", 0);
110013907Sdyson			if (error)
110113907Sdyson				break;
1102133049Ssilby			else
1103133049Ssilby				continue;
110413907Sdyson		}
110513907Sdyson
110613907Sdyson		space = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
110714644Sdyson
110814644Sdyson		/* Writes of size <= PIPE_BUF must be atomic. */
110913913Sdyson		if ((space < uio->uio_resid) && (orig_resid <= PIPE_BUF))
111013913Sdyson			space = 0;
111113907Sdyson
1112118230Spb		if (space > 0) {
1113133049Ssilby			int size;	/* Transfer size */
1114133049Ssilby			int segsize;	/* first segment to transfer */
111576760Salfred
1116133049Ssilby			/*
1117133049Ssilby			 * Transfer size is minimum of uio transfer
1118133049Ssilby			 * and free space in pipe buffer.
1119133049Ssilby			 */
1120133049Ssilby			if (space > uio->uio_resid)
1121133049Ssilby				size = uio->uio_resid;
1122133049Ssilby			else
1123133049Ssilby				size = space;
1124133049Ssilby			/*
1125133049Ssilby			 * First segment to transfer is minimum of
1126133049Ssilby			 * transfer size and contiguous space in
1127133049Ssilby			 * pipe buffer.  If first segment to transfer
1128133049Ssilby			 * is less than the transfer size, we've got
1129133049Ssilby			 * a wraparound in the buffer.
1130133049Ssilby			 */
1131133049Ssilby			segsize = wpipe->pipe_buffer.size -
1132133049Ssilby				wpipe->pipe_buffer.in;
1133133049Ssilby			if (segsize > size)
1134133049Ssilby				segsize = size;
113554534Stegge
1136133049Ssilby			/* Transfer first segment */
1137133049Ssilby
1138133049Ssilby			PIPE_UNLOCK(rpipe);
1139133049Ssilby			error = uiomove(&wpipe->pipe_buffer.buffer[wpipe->pipe_buffer.in],
1140133049Ssilby					segsize, uio);
1141133049Ssilby			PIPE_LOCK(rpipe);
1142133049Ssilby
1143133049Ssilby			if (error == 0 && segsize < size) {
1144133049Ssilby				KASSERT(wpipe->pipe_buffer.in + segsize ==
1145133049Ssilby					wpipe->pipe_buffer.size,
1146133049Ssilby					("Pipe buffer wraparound disappeared"));
114754534Stegge				/*
1148133049Ssilby				 * Transfer remaining part now, to
1149133049Ssilby				 * support atomic writes.  Wraparound
1150133049Ssilby				 * happened.
115154534Stegge				 */
1152124394Sdes
115391395Salfred				PIPE_UNLOCK(rpipe);
1154133049Ssilby				error = uiomove(
1155133049Ssilby				    &wpipe->pipe_buffer.buffer[0],
1156133049Ssilby				    size - segsize, uio);
115791395Salfred				PIPE_LOCK(rpipe);
1158133049Ssilby			}
1159133049Ssilby			if (error == 0) {
1160133049Ssilby				wpipe->pipe_buffer.in += size;
1161133049Ssilby				if (wpipe->pipe_buffer.in >=
1162133049Ssilby				    wpipe->pipe_buffer.size) {
1163133049Ssilby					KASSERT(wpipe->pipe_buffer.in ==
1164133049Ssilby						size - segsize +
1165133049Ssilby						wpipe->pipe_buffer.size,
1166133049Ssilby						("Expected wraparound bad"));
1167133049Ssilby					wpipe->pipe_buffer.in = size - segsize;
116854534Stegge				}
1169124394Sdes
1170133049Ssilby				wpipe->pipe_buffer.cnt += size;
1171133049Ssilby				KASSERT(wpipe->pipe_buffer.cnt <=
1172133049Ssilby					wpipe->pipe_buffer.size,
1173133049Ssilby					("Pipe buffer overflow"));
117413675Sdyson			}
1175133049Ssilby			pipeunlock(wpipe);
1176153484Sdelphij			if (error != 0)
1177153484Sdelphij				break;
117813675Sdyson		} else {
117913675Sdyson			/*
118013675Sdyson			 * If the "read-side" has been blocked, wake it up now.
118113675Sdyson			 */
118213675Sdyson			if (wpipe->pipe_state & PIPE_WANTR) {
118313675Sdyson				wpipe->pipe_state &= ~PIPE_WANTR;
118413675Sdyson				wakeup(wpipe);
118513675Sdyson			}
118614037Sdyson
118713675Sdyson			/*
118813675Sdyson			 * don't block on non-blocking I/O
118913675Sdyson			 */
119016960Sdyson			if (fp->f_flag & FNONBLOCK) {
119113907Sdyson				error = EAGAIN;
1192133049Ssilby				pipeunlock(wpipe);
119313675Sdyson				break;
119413675Sdyson			}
119513907Sdyson
119614037Sdyson			/*
119714037Sdyson			 * We have no more space and have something to offer,
119829356Speter			 * wake up select/poll.
119914037Sdyson			 */
120014037Sdyson			pipeselwakeup(wpipe);
120114037Sdyson
120213675Sdyson			wpipe->pipe_state |= PIPE_WANTW;
1203133049Ssilby			pipeunlock(wpipe);
120491395Salfred			error = msleep(wpipe, PIPE_MTX(rpipe),
120591362Salfred			    PRIBIO | PCATCH, "pipewr", 0);
120676760Salfred			if (error != 0)
120713675Sdyson				break;
120813675Sdyson		}
120913675Sdyson	}
121013675Sdyson
1211133049Ssilby	pipelock(wpipe, 0);
121214644Sdyson	--wpipe->pipe_busy;
121377676Sdillon
121476760Salfred	if ((wpipe->pipe_busy == 0) && (wpipe->pipe_state & PIPE_WANT)) {
121576760Salfred		wpipe->pipe_state &= ~(PIPE_WANT | PIPE_WANTR);
121613675Sdyson		wakeup(wpipe);
121713675Sdyson	} else if (wpipe->pipe_buffer.cnt > 0) {
121813675Sdyson		/*
121913675Sdyson		 * If we have put any characters in the buffer, we wake up
122013675Sdyson		 * the reader.
122113675Sdyson		 */
122213675Sdyson		if (wpipe->pipe_state & PIPE_WANTR) {
122313675Sdyson			wpipe->pipe_state &= ~PIPE_WANTR;
122413675Sdyson			wakeup(wpipe);
122513675Sdyson		}
122613675Sdyson	}
122713909Sdyson
122813909Sdyson	/*
122913909Sdyson	 * Don't return EPIPE if I/O was successful
123013909Sdyson	 */
123113907Sdyson	if ((wpipe->pipe_buffer.cnt == 0) &&
123277676Sdillon	    (uio->uio_resid == 0) &&
123377676Sdillon	    (error == EPIPE)) {
123413907Sdyson		error = 0;
123577676Sdillon	}
123613913Sdyson
123724101Sbde	if (error == 0)
123855112Sbde		vfs_timestamp(&wpipe->pipe_mtime);
123924101Sbde
124014037Sdyson	/*
124114037Sdyson	 * We have something to offer,
124229356Speter	 * wake up select/poll.
124314037Sdyson	 */
124414177Sdyson	if (wpipe->pipe_buffer.cnt)
124514037Sdyson		pipeselwakeup(wpipe);
124613907Sdyson
1247133049Ssilby	pipeunlock(wpipe);
124891395Salfred	PIPE_UNLOCK(rpipe);
124976760Salfred	return (error);
125013675Sdyson}
125113675Sdyson
1252175140Sjhb/* ARGSUSED */
1253175140Sjhbstatic int
1254175140Sjhbpipe_truncate(fp, length, active_cred, td)
1255175140Sjhb	struct file *fp;
1256175140Sjhb	off_t length;
1257175140Sjhb	struct ucred *active_cred;
1258175140Sjhb	struct thread *td;
1259175140Sjhb{
1260175140Sjhb
1261175140Sjhb	return (EINVAL);
1262175140Sjhb}
1263175140Sjhb
126413675Sdyson/*
126513675Sdyson * we implement a very minimal set of ioctls for compatibility with sockets.
126613675Sdyson */
1267104094Sphkstatic int
1268102003Srwatsonpipe_ioctl(fp, cmd, data, active_cred, td)
126913675Sdyson	struct file *fp;
127036735Sdfr	u_long cmd;
127199009Salfred	void *data;
1272102003Srwatson	struct ucred *active_cred;
127383366Sjulian	struct thread *td;
127413675Sdyson{
1275109153Sdillon	struct pipe *mpipe = fp->f_data;
1276101768Srwatson	int error;
127713675Sdyson
1278104269Srwatson	PIPE_LOCK(mpipe);
1279104269Srwatson
1280104269Srwatson#ifdef MAC
1281172930Srwatson	error = mac_pipe_check_ioctl(active_cred, mpipe->pipe_pair, cmd, data);
1282121970Srwatson	if (error) {
1283121970Srwatson		PIPE_UNLOCK(mpipe);
1284101768Srwatson		return (error);
1285121970Srwatson	}
1286101768Srwatson#endif
1287101768Srwatson
1288137752Sphk	error = 0;
128913675Sdyson	switch (cmd) {
129013675Sdyson
129113675Sdyson	case FIONBIO:
1292137752Sphk		break;
129313675Sdyson
129413675Sdyson	case FIOASYNC:
129513675Sdyson		if (*(int *)data) {
129613675Sdyson			mpipe->pipe_state |= PIPE_ASYNC;
129713675Sdyson		} else {
129813675Sdyson			mpipe->pipe_state &= ~PIPE_ASYNC;
129913675Sdyson		}
1300137752Sphk		break;
130113675Sdyson
130213675Sdyson	case FIONREAD:
130314037Sdyson		if (mpipe->pipe_state & PIPE_DIRECTW)
130414037Sdyson			*(int *)data = mpipe->pipe_map.cnt;
130514037Sdyson		else
130614037Sdyson			*(int *)data = mpipe->pipe_buffer.cnt;
1307137752Sphk		break;
130813675Sdyson
130941086Struckman	case FIOSETOWN:
1310138032Srwatson		PIPE_UNLOCK(mpipe);
1311137752Sphk		error = fsetown(*(int *)data, &mpipe->pipe_sigio);
1312138032Srwatson		goto out_unlocked;
131341086Struckman
131441086Struckman	case FIOGETOWN:
1315104393Struckman		*(int *)data = fgetown(&mpipe->pipe_sigio);
1316137752Sphk		break;
131713675Sdyson
131841086Struckman	/* This is deprecated, FIOSETOWN should be used instead. */
131941086Struckman	case TIOCSPGRP:
1320138032Srwatson		PIPE_UNLOCK(mpipe);
1321137752Sphk		error = fsetown(-(*(int *)data), &mpipe->pipe_sigio);
1322138032Srwatson		goto out_unlocked;
132341086Struckman
132441086Struckman	/* This is deprecated, FIOGETOWN should be used instead. */
132518863Sdyson	case TIOCGPGRP:
1326104393Struckman		*(int *)data = -fgetown(&mpipe->pipe_sigio);
1327137752Sphk		break;
132813675Sdyson
1329137752Sphk	default:
1330137752Sphk		error = ENOTTY;
1331137764Sphk		break;
133213675Sdyson	}
1333104269Srwatson	PIPE_UNLOCK(mpipe);
1334138032Srwatsonout_unlocked:
1335137752Sphk	return (error);
133613675Sdyson}
133713675Sdyson
1338104094Sphkstatic int
1339101983Srwatsonpipe_poll(fp, events, active_cred, td)
134013675Sdyson	struct file *fp;
134129356Speter	int events;
1342101983Srwatson	struct ucred *active_cred;
134383366Sjulian	struct thread *td;
134413675Sdyson{
1345109153Sdillon	struct pipe *rpipe = fp->f_data;
134613675Sdyson	struct pipe *wpipe;
134729356Speter	int revents = 0;
1348101768Srwatson#ifdef MAC
1349101768Srwatson	int error;
1350101768Srwatson#endif
135113675Sdyson
135213675Sdyson	wpipe = rpipe->pipe_peer;
135391362Salfred	PIPE_LOCK(rpipe);
1354101768Srwatson#ifdef MAC
1355172930Srwatson	error = mac_pipe_check_poll(active_cred, rpipe->pipe_pair);
1356101768Srwatson	if (error)
1357101768Srwatson		goto locked_error;
1358101768Srwatson#endif
135929356Speter	if (events & (POLLIN | POLLRDNORM))
136029356Speter		if ((rpipe->pipe_state & PIPE_DIRECTW) ||
1361195423Skib		    (rpipe->pipe_buffer.cnt > 0))
136229356Speter			revents |= events & (POLLIN | POLLRDNORM);
136313675Sdyson
136429356Speter	if (events & (POLLOUT | POLLWRNORM))
1365179243Skib		if (wpipe->pipe_present != PIPE_ACTIVE ||
1366179243Skib		    (wpipe->pipe_state & PIPE_EOF) ||
136743311Sdillon		    (((wpipe->pipe_state & PIPE_DIRECTW) == 0) &&
1368230955Sjilles		     ((wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt) >= PIPE_BUF ||
1369230955Sjilles			 wpipe->pipe_buffer.size == 0)))
137029356Speter			revents |= events & (POLLOUT | POLLWRNORM);
137113675Sdyson
1372195423Skib	if ((events & POLLINIGNEOF) == 0) {
1373195423Skib		if (rpipe->pipe_state & PIPE_EOF) {
1374195423Skib			revents |= (events & (POLLIN | POLLRDNORM));
1375195423Skib			if (wpipe->pipe_present != PIPE_ACTIVE ||
1376195423Skib			    (wpipe->pipe_state & PIPE_EOF))
1377195423Skib				revents |= POLLHUP;
1378195423Skib		}
1379195423Skib	}
138029356Speter
138129356Speter	if (revents == 0) {
138229356Speter		if (events & (POLLIN | POLLRDNORM)) {
138383805Sjhb			selrecord(td, &rpipe->pipe_sel);
1384174647Sjeff			if (SEL_WAITING(&rpipe->pipe_sel))
1385174647Sjeff				rpipe->pipe_state |= PIPE_SEL;
138613675Sdyson		}
138713675Sdyson
138829356Speter		if (events & (POLLOUT | POLLWRNORM)) {
138983805Sjhb			selrecord(td, &wpipe->pipe_sel);
1390174647Sjeff			if (SEL_WAITING(&wpipe->pipe_sel))
1391174647Sjeff				wpipe->pipe_state |= PIPE_SEL;
139213907Sdyson		}
139313675Sdyson	}
1394101768Srwatson#ifdef MAC
1395101768Srwatsonlocked_error:
1396101768Srwatson#endif
139791362Salfred	PIPE_UNLOCK(rpipe);
139829356Speter
139929356Speter	return (revents);
140013675Sdyson}
140113675Sdyson
140298989Salfred/*
140398989Salfred * We shouldn't need locks here as we're doing a read and this should
140498989Salfred * be a natural race.
140598989Salfred */
140652983Speterstatic int
1407101983Srwatsonpipe_stat(fp, ub, active_cred, td)
140852983Speter	struct file *fp;
140952983Speter	struct stat *ub;
1410101983Srwatson	struct ucred *active_cred;
141183366Sjulian	struct thread *td;
141213675Sdyson{
1413229248Skib	struct pipe *pipe;
1414229248Skib	int new_unr;
1415101768Srwatson#ifdef MAC
1416101768Srwatson	int error;
1417229248Skib#endif
141852983Speter
1419229248Skib	pipe = fp->f_data;
1420104269Srwatson	PIPE_LOCK(pipe);
1421229248Skib#ifdef MAC
1422172930Srwatson	error = mac_pipe_check_stat(active_cred, pipe->pipe_pair);
1423229248Skib	if (error) {
1424229248Skib		PIPE_UNLOCK(pipe);
1425101768Srwatson		return (error);
1426229248Skib	}
1427101768Srwatson#endif
1428229248Skib	/*
1429229248Skib	 * Lazily allocate an inode number for the pipe.  Most pipe
1430229248Skib	 * users do not call fstat(2) on the pipe, which means that
1431229248Skib	 * postponing the inode allocation until it is must be
1432229248Skib	 * returned to userland is useful.  If alloc_unr failed,
1433229248Skib	 * assign st_ino zero instead of returning an error.
1434229248Skib	 * Special pipe_ino values:
1435229248Skib	 *  -1 - not yet initialized;
1436229248Skib	 *  0  - alloc_unr failed, return 0 as st_ino forever.
1437229248Skib	 */
1438229248Skib	if (pipe->pipe_ino == (ino_t)-1) {
1439229248Skib		new_unr = alloc_unr(pipeino_unr);
1440229248Skib		if (new_unr != -1)
1441229248Skib			pipe->pipe_ino = new_unr;
1442229248Skib		else
1443229248Skib			pipe->pipe_ino = 0;
1444229248Skib	}
1445229248Skib	PIPE_UNLOCK(pipe);
1446229248Skib
1447100527Salfred	bzero(ub, sizeof(*ub));
144817124Sbde	ub->st_mode = S_IFIFO;
1449133790Ssilby	ub->st_blksize = PAGE_SIZE;
1450132436Ssilby	if (pipe->pipe_state & PIPE_DIRECTW)
1451132436Ssilby		ub->st_size = pipe->pipe_map.cnt;
1452132436Ssilby	else
1453132436Ssilby		ub->st_size = pipe->pipe_buffer.cnt;
145413675Sdyson	ub->st_blocks = (ub->st_size + ub->st_blksize - 1) / ub->st_blksize;
1455205792Sed	ub->st_atim = pipe->pipe_atime;
1456205792Sed	ub->st_mtim = pipe->pipe_mtime;
1457205792Sed	ub->st_ctim = pipe->pipe_ctime;
145860404Schris	ub->st_uid = fp->f_cred->cr_uid;
145960404Schris	ub->st_gid = fp->f_cred->cr_gid;
1460226578Skib	ub->st_dev = pipedev_ino;
1461226578Skib	ub->st_ino = pipe->pipe_ino;
146217124Sbde	/*
1463226578Skib	 * Left as 0: st_nlink, st_rdev, st_flags, st_gen.
146417124Sbde	 */
146576760Salfred	return (0);
146613675Sdyson}
146713675Sdyson
146813675Sdyson/* ARGSUSED */
146913675Sdysonstatic int
147083366Sjulianpipe_close(fp, td)
147113675Sdyson	struct file *fp;
147283366Sjulian	struct thread *td;
147313675Sdyson{
1474109153Sdillon	struct pipe *cpipe = fp->f_data;
147516322Sgpalmer
147649413Sgreen	fp->f_ops = &badfileops;
1477109153Sdillon	fp->f_data = NULL;
147896122Salfred	funsetown(&cpipe->pipe_sigio);
147913675Sdyson	pipeclose(cpipe);
148076760Salfred	return (0);
148113675Sdyson}
148213675Sdyson
148376364Salfredstatic void
148476364Salfredpipe_free_kmem(cpipe)
148576364Salfred	struct pipe *cpipe;
148676364Salfred{
148791412Salfred
1488125293Srwatson	KASSERT(!mtx_owned(PIPE_MTX(cpipe)),
1489125293Srwatson	    ("pipe_free_kmem: pipe mutex locked"));
149076364Salfred
149176364Salfred	if (cpipe->pipe_buffer.buffer != NULL) {
1492189649Sjhb		atomic_subtract_long(&amountpipekva, cpipe->pipe_buffer.size);
1493118764Ssilby		vm_map_remove(pipe_map,
1494118764Ssilby		    (vm_offset_t)cpipe->pipe_buffer.buffer,
1495118764Ssilby		    (vm_offset_t)cpipe->pipe_buffer.buffer + cpipe->pipe_buffer.size);
149676364Salfred		cpipe->pipe_buffer.buffer = NULL;
149776364Salfred	}
149876364Salfred#ifndef PIPE_NODIRECT
1499127501Salc	{
150076364Salfred		cpipe->pipe_map.cnt = 0;
150176364Salfred		cpipe->pipe_map.pos = 0;
150276364Salfred		cpipe->pipe_map.npages = 0;
150376364Salfred	}
150476364Salfred#endif
150576364Salfred}
150676364Salfred
150713675Sdyson/*
150813675Sdyson * shutdown the pipe
150913675Sdyson */
151013675Sdysonstatic void
151113675Sdysonpipeclose(cpipe)
151213675Sdyson	struct pipe *cpipe;
151313675Sdyson{
1514125293Srwatson	struct pipepair *pp;
151513907Sdyson	struct pipe *ppipe;
1516226578Skib	ino_t ino;
151776364Salfred
1518125293Srwatson	KASSERT(cpipe != NULL, ("pipeclose: cpipe == NULL"));
151991968Salfred
1520125293Srwatson	PIPE_LOCK(cpipe);
1521133049Ssilby	pipelock(cpipe, 0);
1522125293Srwatson	pp = cpipe->pipe_pair;
152391968Salfred
152491968Salfred	pipeselwakeup(cpipe);
152513907Sdyson
152691968Salfred	/*
152791968Salfred	 * If the other side is blocked, wake it up saying that
152891968Salfred	 * we want to close it down.
152991968Salfred	 */
1530126131Sgreen	cpipe->pipe_state |= PIPE_EOF;
153191968Salfred	while (cpipe->pipe_busy) {
153291968Salfred		wakeup(cpipe);
1533126131Sgreen		cpipe->pipe_state |= PIPE_WANT;
1534133049Ssilby		pipeunlock(cpipe);
153591968Salfred		msleep(cpipe, PIPE_MTX(cpipe), PRIBIO, "pipecl", 0);
1536133049Ssilby		pipelock(cpipe, 0);
153791968Salfred	}
153813675Sdyson
1539101768Srwatson
154091968Salfred	/*
1541125293Srwatson	 * Disconnect from peer, if any.
154291968Salfred	 */
1543125293Srwatson	ppipe = cpipe->pipe_peer;
1544179243Skib	if (ppipe->pipe_present == PIPE_ACTIVE) {
154591968Salfred		pipeselwakeup(ppipe);
154613907Sdyson
154791968Salfred		ppipe->pipe_state |= PIPE_EOF;
154891968Salfred		wakeup(ppipe);
1549133741Sjmg		KNOTE_LOCKED(&ppipe->pipe_sel.si_note, 0);
155091968Salfred	}
1551125293Srwatson
155291968Salfred	/*
1553125293Srwatson	 * Mark this endpoint as free.  Release kmem resources.  We
1554125293Srwatson	 * don't mark this endpoint as unused until we've finished
1555125293Srwatson	 * doing that, or the pipe might disappear out from under
1556125293Srwatson	 * us.
155791968Salfred	 */
1558125293Srwatson	PIPE_UNLOCK(cpipe);
1559125293Srwatson	pipe_free_kmem(cpipe);
1560125293Srwatson	PIPE_LOCK(cpipe);
1561179243Skib	cpipe->pipe_present = PIPE_CLOSING;
1562126131Sgreen	pipeunlock(cpipe);
1563179243Skib
1564179243Skib	/*
1565179243Skib	 * knlist_clear() may sleep dropping the PIPE_MTX. Set the
1566179243Skib	 * PIPE_FINALIZED, that allows other end to free the
1567179243Skib	 * pipe_pair, only after the knotes are completely dismantled.
1568179243Skib	 */
1569133741Sjmg	knlist_clear(&cpipe->pipe_sel.si_note, 1);
1570179243Skib	cpipe->pipe_present = PIPE_FINALIZED;
1571225177Sattilio	seldrain(&cpipe->pipe_sel);
1572133741Sjmg	knlist_destroy(&cpipe->pipe_sel.si_note);
1573125293Srwatson
1574125293Srwatson	/*
1575226578Skib	 * Postpone the destroy of the fake inode number allocated for
1576226578Skib	 * our end, until pipe mtx is unlocked.
1577226578Skib	 */
1578226578Skib	ino = cpipe->pipe_ino;
1579226578Skib
1580226578Skib	/*
1581125293Srwatson	 * If both endpoints are now closed, release the memory for the
1582125293Srwatson	 * pipe pair.  If not, unlock.
1583125293Srwatson	 */
1584179243Skib	if (ppipe->pipe_present == PIPE_FINALIZED) {
158591968Salfred		PIPE_UNLOCK(cpipe);
1586125293Srwatson#ifdef MAC
1587172930Srwatson		mac_pipe_destroy(pp);
1588125293Srwatson#endif
1589125293Srwatson		uma_zfree(pipe_zone, cpipe->pipe_pair);
1590125293Srwatson	} else
1591125293Srwatson		PIPE_UNLOCK(cpipe);
1592226578Skib
1593229016Skib	if (ino != 0 && ino != (ino_t)-1)
1594229016Skib		free_unr(pipeino_unr, ino);
159513675Sdyson}
159659288Sjlemon
159772521Sjlemon/*ARGSUSED*/
159859288Sjlemonstatic int
159972521Sjlemonpipe_kqfilter(struct file *fp, struct knote *kn)
160059288Sjlemon{
160189306Salfred	struct pipe *cpipe;
160259288Sjlemon
1603109153Sdillon	cpipe = kn->kn_fp->f_data;
1604126131Sgreen	PIPE_LOCK(cpipe);
160572521Sjlemon	switch (kn->kn_filter) {
160672521Sjlemon	case EVFILT_READ:
160772521Sjlemon		kn->kn_fop = &pipe_rfiltops;
160872521Sjlemon		break;
160972521Sjlemon	case EVFILT_WRITE:
161072521Sjlemon		kn->kn_fop = &pipe_wfiltops;
1611179243Skib		if (cpipe->pipe_peer->pipe_present != PIPE_ACTIVE) {
1612101382Sdes			/* other end of pipe has been closed */
1613126131Sgreen			PIPE_UNLOCK(cpipe);
1614118929Sjmg			return (EPIPE);
1615126131Sgreen		}
1616126131Sgreen		cpipe = cpipe->pipe_peer;
161772521Sjlemon		break;
161872521Sjlemon	default:
1619126131Sgreen		PIPE_UNLOCK(cpipe);
1620133741Sjmg		return (EINVAL);
162172521Sjlemon	}
162278292Sjlemon
1623133741Sjmg	knlist_add(&cpipe->pipe_sel.si_note, kn, 1);
162491372Salfred	PIPE_UNLOCK(cpipe);
162559288Sjlemon	return (0);
162659288Sjlemon}
162759288Sjlemon
162859288Sjlemonstatic void
162959288Sjlemonfilt_pipedetach(struct knote *kn)
163059288Sjlemon{
1631121018Sjmg	struct pipe *cpipe = (struct pipe *)kn->kn_fp->f_data;
163259288Sjlemon
1633126131Sgreen	PIPE_LOCK(cpipe);
1634179242Skib	if (kn->kn_filter == EVFILT_WRITE)
1635121018Sjmg		cpipe = cpipe->pipe_peer;
1636133741Sjmg	knlist_remove(&cpipe->pipe_sel.si_note, kn, 1);
163791372Salfred	PIPE_UNLOCK(cpipe);
163859288Sjlemon}
163959288Sjlemon
164059288Sjlemon/*ARGSUSED*/
164159288Sjlemonstatic int
164259288Sjlemonfilt_piperead(struct knote *kn, long hint)
164359288Sjlemon{
1644109153Sdillon	struct pipe *rpipe = kn->kn_fp->f_data;
164559288Sjlemon	struct pipe *wpipe = rpipe->pipe_peer;
1646133741Sjmg	int ret;
164759288Sjlemon
164891372Salfred	PIPE_LOCK(rpipe);
164959288Sjlemon	kn->kn_data = rpipe->pipe_buffer.cnt;
165059288Sjlemon	if ((kn->kn_data == 0) && (rpipe->pipe_state & PIPE_DIRECTW))
165159288Sjlemon		kn->kn_data = rpipe->pipe_map.cnt;
165259288Sjlemon
165359288Sjlemon	if ((rpipe->pipe_state & PIPE_EOF) ||
1654179243Skib	    wpipe->pipe_present != PIPE_ACTIVE ||
1655179243Skib	    (wpipe->pipe_state & PIPE_EOF)) {
165691372Salfred		kn->kn_flags |= EV_EOF;
165791372Salfred		PIPE_UNLOCK(rpipe);
165859288Sjlemon		return (1);
165959288Sjlemon	}
1660133741Sjmg	ret = kn->kn_data > 0;
166191372Salfred	PIPE_UNLOCK(rpipe);
1662133741Sjmg	return ret;
166359288Sjlemon}
166459288Sjlemon
166559288Sjlemon/*ARGSUSED*/
166659288Sjlemonstatic int
166759288Sjlemonfilt_pipewrite(struct knote *kn, long hint)
166859288Sjlemon{
1669109153Sdillon	struct pipe *rpipe = kn->kn_fp->f_data;
167059288Sjlemon	struct pipe *wpipe = rpipe->pipe_peer;
167159288Sjlemon
167291372Salfred	PIPE_LOCK(rpipe);
1673179243Skib	if (wpipe->pipe_present != PIPE_ACTIVE ||
1674179243Skib	    (wpipe->pipe_state & PIPE_EOF)) {
167559288Sjlemon		kn->kn_data = 0;
1676124394Sdes		kn->kn_flags |= EV_EOF;
167791372Salfred		PIPE_UNLOCK(rpipe);
167859288Sjlemon		return (1);
167959288Sjlemon	}
1680230955Sjilles	kn->kn_data = (wpipe->pipe_buffer.size > 0) ?
1681230955Sjilles	    (wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt) : PIPE_BUF;
168265855Sjlemon	if (wpipe->pipe_state & PIPE_DIRECTW)
168359288Sjlemon		kn->kn_data = 0;
168459288Sjlemon
168591372Salfred	PIPE_UNLOCK(rpipe);
168659288Sjlemon	return (kn->kn_data >= PIPE_BUF);
168759288Sjlemon}
1688