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