sys_pipe.c revision 220245
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, the sending process pins the underlying pages in
33 * memory, and the receiving process copies directly from these pinned pages
34 * in the sending 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 220245 2011-04-01 13:28:34Z kib $");
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, 0);
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, 0);
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	u_int size;
751	int i;
752
753	PIPE_LOCK_ASSERT(wpipe, MA_NOTOWNED);
754	KASSERT(wpipe->pipe_state & PIPE_DIRECTW,
755		("Clone attempt on non-direct write pipe!"));
756
757	size = (u_int) uio->uio_iov->iov_len;
758	if (size > wpipe->pipe_buffer.size)
759		size = wpipe->pipe_buffer.size;
760
761	if ((i = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
762	    (vm_offset_t)uio->uio_iov->iov_base, size, VM_PROT_READ,
763	    wpipe->pipe_map.ms, PIPENPAGES)) < 0)
764		return (EFAULT);
765
766/*
767 * set up the control block
768 */
769	wpipe->pipe_map.npages = i;
770	wpipe->pipe_map.pos =
771	    ((vm_offset_t) uio->uio_iov->iov_base) & PAGE_MASK;
772	wpipe->pipe_map.cnt = size;
773
774/*
775 * and update the uio data
776 */
777
778	uio->uio_iov->iov_len -= size;
779	uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + size;
780	if (uio->uio_iov->iov_len == 0)
781		uio->uio_iov++;
782	uio->uio_resid -= size;
783	uio->uio_offset += size;
784	return (0);
785}
786
787/*
788 * unmap and unwire the process buffer
789 */
790static void
791pipe_destroy_write_buffer(wpipe)
792	struct pipe *wpipe;
793{
794
795	PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
796	vm_page_unhold_pages(wpipe->pipe_map.ms, wpipe->pipe_map.npages);
797	wpipe->pipe_map.npages = 0;
798}
799
800/*
801 * In the case of a signal, the writing process might go away.  This
802 * code copies the data into the circular buffer so that the source
803 * pages can be freed without loss of data.
804 */
805static void
806pipe_clone_write_buffer(wpipe)
807	struct pipe *wpipe;
808{
809	struct uio uio;
810	struct iovec iov;
811	int size;
812	int pos;
813
814	PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
815	size = wpipe->pipe_map.cnt;
816	pos = wpipe->pipe_map.pos;
817
818	wpipe->pipe_buffer.in = size;
819	wpipe->pipe_buffer.out = 0;
820	wpipe->pipe_buffer.cnt = size;
821	wpipe->pipe_state &= ~PIPE_DIRECTW;
822
823	PIPE_UNLOCK(wpipe);
824	iov.iov_base = wpipe->pipe_buffer.buffer;
825	iov.iov_len = size;
826	uio.uio_iov = &iov;
827	uio.uio_iovcnt = 1;
828	uio.uio_offset = 0;
829	uio.uio_resid = size;
830	uio.uio_segflg = UIO_SYSSPACE;
831	uio.uio_rw = UIO_READ;
832	uio.uio_td = curthread;
833	uiomove_fromphys(wpipe->pipe_map.ms, pos, size, &uio);
834	PIPE_LOCK(wpipe);
835	pipe_destroy_write_buffer(wpipe);
836}
837
838/*
839 * This implements the pipe buffer write mechanism.  Note that only
840 * a direct write OR a normal pipe write can be pending at any given time.
841 * If there are any characters in the pipe buffer, the direct write will
842 * be deferred until the receiving process grabs all of the bytes from
843 * the pipe buffer.  Then the direct mapping write is set-up.
844 */
845static int
846pipe_direct_write(wpipe, uio)
847	struct pipe *wpipe;
848	struct uio *uio;
849{
850	int error;
851
852retry:
853	PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
854	error = pipelock(wpipe, 1);
855	if (wpipe->pipe_state & PIPE_EOF)
856		error = EPIPE;
857	if (error) {
858		pipeunlock(wpipe);
859		goto error1;
860	}
861	while (wpipe->pipe_state & PIPE_DIRECTW) {
862		if (wpipe->pipe_state & PIPE_WANTR) {
863			wpipe->pipe_state &= ~PIPE_WANTR;
864			wakeup(wpipe);
865		}
866		pipeselwakeup(wpipe);
867		wpipe->pipe_state |= PIPE_WANTW;
868		pipeunlock(wpipe);
869		error = msleep(wpipe, PIPE_MTX(wpipe),
870		    PRIBIO | PCATCH, "pipdww", 0);
871		if (error)
872			goto error1;
873		else
874			goto retry;
875	}
876	wpipe->pipe_map.cnt = 0;	/* transfer not ready yet */
877	if (wpipe->pipe_buffer.cnt > 0) {
878		if (wpipe->pipe_state & PIPE_WANTR) {
879			wpipe->pipe_state &= ~PIPE_WANTR;
880			wakeup(wpipe);
881		}
882		pipeselwakeup(wpipe);
883		wpipe->pipe_state |= PIPE_WANTW;
884		pipeunlock(wpipe);
885		error = msleep(wpipe, PIPE_MTX(wpipe),
886		    PRIBIO | PCATCH, "pipdwc", 0);
887		if (error)
888			goto error1;
889		else
890			goto retry;
891	}
892
893	wpipe->pipe_state |= PIPE_DIRECTW;
894
895	PIPE_UNLOCK(wpipe);
896	error = pipe_build_write_buffer(wpipe, uio);
897	PIPE_LOCK(wpipe);
898	if (error) {
899		wpipe->pipe_state &= ~PIPE_DIRECTW;
900		pipeunlock(wpipe);
901		goto error1;
902	}
903
904	error = 0;
905	while (!error && (wpipe->pipe_state & PIPE_DIRECTW)) {
906		if (wpipe->pipe_state & PIPE_EOF) {
907			pipe_destroy_write_buffer(wpipe);
908			pipeselwakeup(wpipe);
909			pipeunlock(wpipe);
910			error = EPIPE;
911			goto error1;
912		}
913		if (wpipe->pipe_state & PIPE_WANTR) {
914			wpipe->pipe_state &= ~PIPE_WANTR;
915			wakeup(wpipe);
916		}
917		pipeselwakeup(wpipe);
918		pipeunlock(wpipe);
919		error = msleep(wpipe, PIPE_MTX(wpipe), PRIBIO | PCATCH,
920		    "pipdwt", 0);
921		pipelock(wpipe, 0);
922	}
923
924	if (wpipe->pipe_state & PIPE_EOF)
925		error = EPIPE;
926	if (wpipe->pipe_state & PIPE_DIRECTW) {
927		/*
928		 * this bit of trickery substitutes a kernel buffer for
929		 * the process that might be going away.
930		 */
931		pipe_clone_write_buffer(wpipe);
932	} else {
933		pipe_destroy_write_buffer(wpipe);
934	}
935	pipeunlock(wpipe);
936	return (error);
937
938error1:
939	wakeup(wpipe);
940	return (error);
941}
942#endif
943
944static int
945pipe_write(fp, uio, active_cred, flags, td)
946	struct file *fp;
947	struct uio *uio;
948	struct ucred *active_cred;
949	struct thread *td;
950	int flags;
951{
952	int error = 0;
953	int desiredsize, orig_resid;
954	struct pipe *wpipe, *rpipe;
955
956	rpipe = fp->f_data;
957	wpipe = rpipe->pipe_peer;
958
959	PIPE_LOCK(rpipe);
960	error = pipelock(wpipe, 1);
961	if (error) {
962		PIPE_UNLOCK(rpipe);
963		return (error);
964	}
965	/*
966	 * detect loss of pipe read side, issue SIGPIPE if lost.
967	 */
968	if (wpipe->pipe_present != PIPE_ACTIVE ||
969	    (wpipe->pipe_state & PIPE_EOF)) {
970		pipeunlock(wpipe);
971		PIPE_UNLOCK(rpipe);
972		return (EPIPE);
973	}
974#ifdef MAC
975	error = mac_pipe_check_write(active_cred, wpipe->pipe_pair);
976	if (error) {
977		pipeunlock(wpipe);
978		PIPE_UNLOCK(rpipe);
979		return (error);
980	}
981#endif
982	++wpipe->pipe_busy;
983
984	/* Choose a larger size if it's advantageous */
985	desiredsize = max(SMALL_PIPE_SIZE, wpipe->pipe_buffer.size);
986	while (desiredsize < wpipe->pipe_buffer.cnt + uio->uio_resid) {
987		if (piperesizeallowed != 1)
988			break;
989		if (amountpipekva > maxpipekva / 2)
990			break;
991		if (desiredsize == BIG_PIPE_SIZE)
992			break;
993		desiredsize = desiredsize * 2;
994	}
995
996	/* Choose a smaller size if we're in a OOM situation */
997	if ((amountpipekva > (3 * maxpipekva) / 4) &&
998		(wpipe->pipe_buffer.size > SMALL_PIPE_SIZE) &&
999		(wpipe->pipe_buffer.cnt <= SMALL_PIPE_SIZE) &&
1000		(piperesizeallowed == 1))
1001		desiredsize = SMALL_PIPE_SIZE;
1002
1003	/* Resize if the above determined that a new size was necessary */
1004	if ((desiredsize != wpipe->pipe_buffer.size) &&
1005		((wpipe->pipe_state & PIPE_DIRECTW) == 0)) {
1006		PIPE_UNLOCK(wpipe);
1007		pipespace(wpipe, desiredsize);
1008		PIPE_LOCK(wpipe);
1009	}
1010	if (wpipe->pipe_buffer.size == 0) {
1011		/*
1012		 * This can only happen for reverse direction use of pipes
1013		 * in a complete OOM situation.
1014		 */
1015		error = ENOMEM;
1016		--wpipe->pipe_busy;
1017		pipeunlock(wpipe);
1018		PIPE_UNLOCK(wpipe);
1019		return (error);
1020	}
1021
1022	pipeunlock(wpipe);
1023
1024	orig_resid = uio->uio_resid;
1025
1026	while (uio->uio_resid) {
1027		int space;
1028
1029		pipelock(wpipe, 0);
1030		if (wpipe->pipe_state & PIPE_EOF) {
1031			pipeunlock(wpipe);
1032			error = EPIPE;
1033			break;
1034		}
1035#ifndef PIPE_NODIRECT
1036		/*
1037		 * If the transfer is large, we can gain performance if
1038		 * we do process-to-process copies directly.
1039		 * If the write is non-blocking, we don't use the
1040		 * direct write mechanism.
1041		 *
1042		 * The direct write mechanism will detect the reader going
1043		 * away on us.
1044		 */
1045		if (uio->uio_segflg == UIO_USERSPACE &&
1046		    uio->uio_iov->iov_len >= PIPE_MINDIRECT &&
1047		    wpipe->pipe_buffer.size >= PIPE_MINDIRECT &&
1048		    (fp->f_flag & FNONBLOCK) == 0) {
1049			pipeunlock(wpipe);
1050			error = pipe_direct_write(wpipe, uio);
1051			if (error)
1052				break;
1053			continue;
1054		}
1055#endif
1056
1057		/*
1058		 * Pipe buffered writes cannot be coincidental with
1059		 * direct writes.  We wait until the currently executing
1060		 * direct write is completed before we start filling the
1061		 * pipe buffer.  We break out if a signal occurs or the
1062		 * reader goes away.
1063		 */
1064		if (wpipe->pipe_state & PIPE_DIRECTW) {
1065			if (wpipe->pipe_state & PIPE_WANTR) {
1066				wpipe->pipe_state &= ~PIPE_WANTR;
1067				wakeup(wpipe);
1068			}
1069			pipeselwakeup(wpipe);
1070			wpipe->pipe_state |= PIPE_WANTW;
1071			pipeunlock(wpipe);
1072			error = msleep(wpipe, PIPE_MTX(rpipe), PRIBIO | PCATCH,
1073			    "pipbww", 0);
1074			if (error)
1075				break;
1076			else
1077				continue;
1078		}
1079
1080		space = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
1081
1082		/* Writes of size <= PIPE_BUF must be atomic. */
1083		if ((space < uio->uio_resid) && (orig_resid <= PIPE_BUF))
1084			space = 0;
1085
1086		if (space > 0) {
1087			int size;	/* Transfer size */
1088			int segsize;	/* first segment to transfer */
1089
1090			/*
1091			 * Transfer size is minimum of uio transfer
1092			 * and free space in pipe buffer.
1093			 */
1094			if (space > uio->uio_resid)
1095				size = uio->uio_resid;
1096			else
1097				size = space;
1098			/*
1099			 * First segment to transfer is minimum of
1100			 * transfer size and contiguous space in
1101			 * pipe buffer.  If first segment to transfer
1102			 * is less than the transfer size, we've got
1103			 * a wraparound in the buffer.
1104			 */
1105			segsize = wpipe->pipe_buffer.size -
1106				wpipe->pipe_buffer.in;
1107			if (segsize > size)
1108				segsize = size;
1109
1110			/* Transfer first segment */
1111
1112			PIPE_UNLOCK(rpipe);
1113			error = uiomove(&wpipe->pipe_buffer.buffer[wpipe->pipe_buffer.in],
1114					segsize, uio);
1115			PIPE_LOCK(rpipe);
1116
1117			if (error == 0 && segsize < size) {
1118				KASSERT(wpipe->pipe_buffer.in + segsize ==
1119					wpipe->pipe_buffer.size,
1120					("Pipe buffer wraparound disappeared"));
1121				/*
1122				 * Transfer remaining part now, to
1123				 * support atomic writes.  Wraparound
1124				 * happened.
1125				 */
1126
1127				PIPE_UNLOCK(rpipe);
1128				error = uiomove(
1129				    &wpipe->pipe_buffer.buffer[0],
1130				    size - segsize, uio);
1131				PIPE_LOCK(rpipe);
1132			}
1133			if (error == 0) {
1134				wpipe->pipe_buffer.in += size;
1135				if (wpipe->pipe_buffer.in >=
1136				    wpipe->pipe_buffer.size) {
1137					KASSERT(wpipe->pipe_buffer.in ==
1138						size - segsize +
1139						wpipe->pipe_buffer.size,
1140						("Expected wraparound bad"));
1141					wpipe->pipe_buffer.in = size - segsize;
1142				}
1143
1144				wpipe->pipe_buffer.cnt += size;
1145				KASSERT(wpipe->pipe_buffer.cnt <=
1146					wpipe->pipe_buffer.size,
1147					("Pipe buffer overflow"));
1148			}
1149			pipeunlock(wpipe);
1150			if (error != 0)
1151				break;
1152		} else {
1153			/*
1154			 * If the "read-side" has been blocked, wake it up now.
1155			 */
1156			if (wpipe->pipe_state & PIPE_WANTR) {
1157				wpipe->pipe_state &= ~PIPE_WANTR;
1158				wakeup(wpipe);
1159			}
1160
1161			/*
1162			 * don't block on non-blocking I/O
1163			 */
1164			if (fp->f_flag & FNONBLOCK) {
1165				error = EAGAIN;
1166				pipeunlock(wpipe);
1167				break;
1168			}
1169
1170			/*
1171			 * We have no more space and have something to offer,
1172			 * wake up select/poll.
1173			 */
1174			pipeselwakeup(wpipe);
1175
1176			wpipe->pipe_state |= PIPE_WANTW;
1177			pipeunlock(wpipe);
1178			error = msleep(wpipe, PIPE_MTX(rpipe),
1179			    PRIBIO | PCATCH, "pipewr", 0);
1180			if (error != 0)
1181				break;
1182		}
1183	}
1184
1185	pipelock(wpipe, 0);
1186	--wpipe->pipe_busy;
1187
1188	if ((wpipe->pipe_busy == 0) && (wpipe->pipe_state & PIPE_WANT)) {
1189		wpipe->pipe_state &= ~(PIPE_WANT | PIPE_WANTR);
1190		wakeup(wpipe);
1191	} else if (wpipe->pipe_buffer.cnt > 0) {
1192		/*
1193		 * If we have put any characters in the buffer, we wake up
1194		 * the reader.
1195		 */
1196		if (wpipe->pipe_state & PIPE_WANTR) {
1197			wpipe->pipe_state &= ~PIPE_WANTR;
1198			wakeup(wpipe);
1199		}
1200	}
1201
1202	/*
1203	 * Don't return EPIPE if I/O was successful
1204	 */
1205	if ((wpipe->pipe_buffer.cnt == 0) &&
1206	    (uio->uio_resid == 0) &&
1207	    (error == EPIPE)) {
1208		error = 0;
1209	}
1210
1211	if (error == 0)
1212		vfs_timestamp(&wpipe->pipe_mtime);
1213
1214	/*
1215	 * We have something to offer,
1216	 * wake up select/poll.
1217	 */
1218	if (wpipe->pipe_buffer.cnt)
1219		pipeselwakeup(wpipe);
1220
1221	pipeunlock(wpipe);
1222	PIPE_UNLOCK(rpipe);
1223	return (error);
1224}
1225
1226/* ARGSUSED */
1227static int
1228pipe_truncate(fp, length, active_cred, td)
1229	struct file *fp;
1230	off_t length;
1231	struct ucred *active_cred;
1232	struct thread *td;
1233{
1234
1235	return (EINVAL);
1236}
1237
1238/*
1239 * we implement a very minimal set of ioctls for compatibility with sockets.
1240 */
1241static int
1242pipe_ioctl(fp, cmd, data, active_cred, td)
1243	struct file *fp;
1244	u_long cmd;
1245	void *data;
1246	struct ucred *active_cred;
1247	struct thread *td;
1248{
1249	struct pipe *mpipe = fp->f_data;
1250	int error;
1251
1252	PIPE_LOCK(mpipe);
1253
1254#ifdef MAC
1255	error = mac_pipe_check_ioctl(active_cred, mpipe->pipe_pair, cmd, data);
1256	if (error) {
1257		PIPE_UNLOCK(mpipe);
1258		return (error);
1259	}
1260#endif
1261
1262	error = 0;
1263	switch (cmd) {
1264
1265	case FIONBIO:
1266		break;
1267
1268	case FIOASYNC:
1269		if (*(int *)data) {
1270			mpipe->pipe_state |= PIPE_ASYNC;
1271		} else {
1272			mpipe->pipe_state &= ~PIPE_ASYNC;
1273		}
1274		break;
1275
1276	case FIONREAD:
1277		if (mpipe->pipe_state & PIPE_DIRECTW)
1278			*(int *)data = mpipe->pipe_map.cnt;
1279		else
1280			*(int *)data = mpipe->pipe_buffer.cnt;
1281		break;
1282
1283	case FIOSETOWN:
1284		PIPE_UNLOCK(mpipe);
1285		error = fsetown(*(int *)data, &mpipe->pipe_sigio);
1286		goto out_unlocked;
1287
1288	case FIOGETOWN:
1289		*(int *)data = fgetown(&mpipe->pipe_sigio);
1290		break;
1291
1292	/* This is deprecated, FIOSETOWN should be used instead. */
1293	case TIOCSPGRP:
1294		PIPE_UNLOCK(mpipe);
1295		error = fsetown(-(*(int *)data), &mpipe->pipe_sigio);
1296		goto out_unlocked;
1297
1298	/* This is deprecated, FIOGETOWN should be used instead. */
1299	case TIOCGPGRP:
1300		*(int *)data = -fgetown(&mpipe->pipe_sigio);
1301		break;
1302
1303	default:
1304		error = ENOTTY;
1305		break;
1306	}
1307	PIPE_UNLOCK(mpipe);
1308out_unlocked:
1309	return (error);
1310}
1311
1312static int
1313pipe_poll(fp, events, active_cred, td)
1314	struct file *fp;
1315	int events;
1316	struct ucred *active_cred;
1317	struct thread *td;
1318{
1319	struct pipe *rpipe = fp->f_data;
1320	struct pipe *wpipe;
1321	int revents = 0;
1322#ifdef MAC
1323	int error;
1324#endif
1325
1326	wpipe = rpipe->pipe_peer;
1327	PIPE_LOCK(rpipe);
1328#ifdef MAC
1329	error = mac_pipe_check_poll(active_cred, rpipe->pipe_pair);
1330	if (error)
1331		goto locked_error;
1332#endif
1333	if (events & (POLLIN | POLLRDNORM))
1334		if ((rpipe->pipe_state & PIPE_DIRECTW) ||
1335		    (rpipe->pipe_buffer.cnt > 0))
1336			revents |= events & (POLLIN | POLLRDNORM);
1337
1338	if (events & (POLLOUT | POLLWRNORM))
1339		if (wpipe->pipe_present != PIPE_ACTIVE ||
1340		    (wpipe->pipe_state & PIPE_EOF) ||
1341		    (((wpipe->pipe_state & PIPE_DIRECTW) == 0) &&
1342		     (wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt) >= PIPE_BUF))
1343			revents |= events & (POLLOUT | POLLWRNORM);
1344
1345	if ((events & POLLINIGNEOF) == 0) {
1346		if (rpipe->pipe_state & PIPE_EOF) {
1347			revents |= (events & (POLLIN | POLLRDNORM));
1348			if (wpipe->pipe_present != PIPE_ACTIVE ||
1349			    (wpipe->pipe_state & PIPE_EOF))
1350				revents |= POLLHUP;
1351		}
1352	}
1353
1354	if (revents == 0) {
1355		if (events & (POLLIN | POLLRDNORM)) {
1356			selrecord(td, &rpipe->pipe_sel);
1357			if (SEL_WAITING(&rpipe->pipe_sel))
1358				rpipe->pipe_state |= PIPE_SEL;
1359		}
1360
1361		if (events & (POLLOUT | POLLWRNORM)) {
1362			selrecord(td, &wpipe->pipe_sel);
1363			if (SEL_WAITING(&wpipe->pipe_sel))
1364				wpipe->pipe_state |= PIPE_SEL;
1365		}
1366	}
1367#ifdef MAC
1368locked_error:
1369#endif
1370	PIPE_UNLOCK(rpipe);
1371
1372	return (revents);
1373}
1374
1375/*
1376 * We shouldn't need locks here as we're doing a read and this should
1377 * be a natural race.
1378 */
1379static int
1380pipe_stat(fp, ub, active_cred, td)
1381	struct file *fp;
1382	struct stat *ub;
1383	struct ucred *active_cred;
1384	struct thread *td;
1385{
1386	struct pipe *pipe = fp->f_data;
1387#ifdef MAC
1388	int error;
1389
1390	PIPE_LOCK(pipe);
1391	error = mac_pipe_check_stat(active_cred, pipe->pipe_pair);
1392	PIPE_UNLOCK(pipe);
1393	if (error)
1394		return (error);
1395#endif
1396	bzero(ub, sizeof(*ub));
1397	ub->st_mode = S_IFIFO;
1398	ub->st_blksize = PAGE_SIZE;
1399	if (pipe->pipe_state & PIPE_DIRECTW)
1400		ub->st_size = pipe->pipe_map.cnt;
1401	else
1402		ub->st_size = pipe->pipe_buffer.cnt;
1403	ub->st_blocks = (ub->st_size + ub->st_blksize - 1) / ub->st_blksize;
1404	ub->st_atim = pipe->pipe_atime;
1405	ub->st_mtim = pipe->pipe_mtime;
1406	ub->st_ctim = pipe->pipe_ctime;
1407	ub->st_uid = fp->f_cred->cr_uid;
1408	ub->st_gid = fp->f_cred->cr_gid;
1409	/*
1410	 * Left as 0: st_dev, st_ino, st_nlink, st_rdev, st_flags, st_gen.
1411	 * XXX (st_dev, st_ino) should be unique.
1412	 */
1413	return (0);
1414}
1415
1416/* ARGSUSED */
1417static int
1418pipe_close(fp, td)
1419	struct file *fp;
1420	struct thread *td;
1421{
1422	struct pipe *cpipe = fp->f_data;
1423
1424	fp->f_ops = &badfileops;
1425	fp->f_data = NULL;
1426	funsetown(&cpipe->pipe_sigio);
1427	pipeclose(cpipe);
1428	return (0);
1429}
1430
1431static void
1432pipe_free_kmem(cpipe)
1433	struct pipe *cpipe;
1434{
1435
1436	KASSERT(!mtx_owned(PIPE_MTX(cpipe)),
1437	    ("pipe_free_kmem: pipe mutex locked"));
1438
1439	if (cpipe->pipe_buffer.buffer != NULL) {
1440		atomic_subtract_long(&amountpipekva, cpipe->pipe_buffer.size);
1441		vm_map_remove(pipe_map,
1442		    (vm_offset_t)cpipe->pipe_buffer.buffer,
1443		    (vm_offset_t)cpipe->pipe_buffer.buffer + cpipe->pipe_buffer.size);
1444		cpipe->pipe_buffer.buffer = NULL;
1445	}
1446#ifndef PIPE_NODIRECT
1447	{
1448		cpipe->pipe_map.cnt = 0;
1449		cpipe->pipe_map.pos = 0;
1450		cpipe->pipe_map.npages = 0;
1451	}
1452#endif
1453}
1454
1455/*
1456 * shutdown the pipe
1457 */
1458static void
1459pipeclose(cpipe)
1460	struct pipe *cpipe;
1461{
1462	struct pipepair *pp;
1463	struct pipe *ppipe;
1464
1465	KASSERT(cpipe != NULL, ("pipeclose: cpipe == NULL"));
1466
1467	PIPE_LOCK(cpipe);
1468	pipelock(cpipe, 0);
1469	pp = cpipe->pipe_pair;
1470
1471	pipeselwakeup(cpipe);
1472
1473	/*
1474	 * If the other side is blocked, wake it up saying that
1475	 * we want to close it down.
1476	 */
1477	cpipe->pipe_state |= PIPE_EOF;
1478	while (cpipe->pipe_busy) {
1479		wakeup(cpipe);
1480		cpipe->pipe_state |= PIPE_WANT;
1481		pipeunlock(cpipe);
1482		msleep(cpipe, PIPE_MTX(cpipe), PRIBIO, "pipecl", 0);
1483		pipelock(cpipe, 0);
1484	}
1485
1486
1487	/*
1488	 * Disconnect from peer, if any.
1489	 */
1490	ppipe = cpipe->pipe_peer;
1491	if (ppipe->pipe_present == PIPE_ACTIVE) {
1492		pipeselwakeup(ppipe);
1493
1494		ppipe->pipe_state |= PIPE_EOF;
1495		wakeup(ppipe);
1496		KNOTE_LOCKED(&ppipe->pipe_sel.si_note, 0);
1497	}
1498
1499	/*
1500	 * Mark this endpoint as free.  Release kmem resources.  We
1501	 * don't mark this endpoint as unused until we've finished
1502	 * doing that, or the pipe might disappear out from under
1503	 * us.
1504	 */
1505	PIPE_UNLOCK(cpipe);
1506	pipe_free_kmem(cpipe);
1507	PIPE_LOCK(cpipe);
1508	cpipe->pipe_present = PIPE_CLOSING;
1509	pipeunlock(cpipe);
1510
1511	/*
1512	 * knlist_clear() may sleep dropping the PIPE_MTX. Set the
1513	 * PIPE_FINALIZED, that allows other end to free the
1514	 * pipe_pair, only after the knotes are completely dismantled.
1515	 */
1516	knlist_clear(&cpipe->pipe_sel.si_note, 1);
1517	cpipe->pipe_present = PIPE_FINALIZED;
1518	knlist_destroy(&cpipe->pipe_sel.si_note);
1519
1520	/*
1521	 * If both endpoints are now closed, release the memory for the
1522	 * pipe pair.  If not, unlock.
1523	 */
1524	if (ppipe->pipe_present == PIPE_FINALIZED) {
1525		PIPE_UNLOCK(cpipe);
1526#ifdef MAC
1527		mac_pipe_destroy(pp);
1528#endif
1529		uma_zfree(pipe_zone, cpipe->pipe_pair);
1530	} else
1531		PIPE_UNLOCK(cpipe);
1532}
1533
1534/*ARGSUSED*/
1535static int
1536pipe_kqfilter(struct file *fp, struct knote *kn)
1537{
1538	struct pipe *cpipe;
1539
1540	cpipe = kn->kn_fp->f_data;
1541	PIPE_LOCK(cpipe);
1542	switch (kn->kn_filter) {
1543	case EVFILT_READ:
1544		kn->kn_fop = &pipe_rfiltops;
1545		break;
1546	case EVFILT_WRITE:
1547		kn->kn_fop = &pipe_wfiltops;
1548		if (cpipe->pipe_peer->pipe_present != PIPE_ACTIVE) {
1549			/* other end of pipe has been closed */
1550			PIPE_UNLOCK(cpipe);
1551			return (EPIPE);
1552		}
1553		cpipe = cpipe->pipe_peer;
1554		break;
1555	default:
1556		PIPE_UNLOCK(cpipe);
1557		return (EINVAL);
1558	}
1559
1560	knlist_add(&cpipe->pipe_sel.si_note, kn, 1);
1561	PIPE_UNLOCK(cpipe);
1562	return (0);
1563}
1564
1565static void
1566filt_pipedetach(struct knote *kn)
1567{
1568	struct pipe *cpipe = (struct pipe *)kn->kn_fp->f_data;
1569
1570	PIPE_LOCK(cpipe);
1571	if (kn->kn_filter == EVFILT_WRITE)
1572		cpipe = cpipe->pipe_peer;
1573	knlist_remove(&cpipe->pipe_sel.si_note, kn, 1);
1574	PIPE_UNLOCK(cpipe);
1575}
1576
1577/*ARGSUSED*/
1578static int
1579filt_piperead(struct knote *kn, long hint)
1580{
1581	struct pipe *rpipe = kn->kn_fp->f_data;
1582	struct pipe *wpipe = rpipe->pipe_peer;
1583	int ret;
1584
1585	PIPE_LOCK(rpipe);
1586	kn->kn_data = rpipe->pipe_buffer.cnt;
1587	if ((kn->kn_data == 0) && (rpipe->pipe_state & PIPE_DIRECTW))
1588		kn->kn_data = rpipe->pipe_map.cnt;
1589
1590	if ((rpipe->pipe_state & PIPE_EOF) ||
1591	    wpipe->pipe_present != PIPE_ACTIVE ||
1592	    (wpipe->pipe_state & PIPE_EOF)) {
1593		kn->kn_flags |= EV_EOF;
1594		PIPE_UNLOCK(rpipe);
1595		return (1);
1596	}
1597	ret = kn->kn_data > 0;
1598	PIPE_UNLOCK(rpipe);
1599	return ret;
1600}
1601
1602/*ARGSUSED*/
1603static int
1604filt_pipewrite(struct knote *kn, long hint)
1605{
1606	struct pipe *rpipe = kn->kn_fp->f_data;
1607	struct pipe *wpipe = rpipe->pipe_peer;
1608
1609	PIPE_LOCK(rpipe);
1610	if (wpipe->pipe_present != PIPE_ACTIVE ||
1611	    (wpipe->pipe_state & PIPE_EOF)) {
1612		kn->kn_data = 0;
1613		kn->kn_flags |= EV_EOF;
1614		PIPE_UNLOCK(rpipe);
1615		return (1);
1616	}
1617	kn->kn_data = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
1618	if (wpipe->pipe_state & PIPE_DIRECTW)
1619		kn->kn_data = 0;
1620
1621	PIPE_UNLOCK(rpipe);
1622	return (kn->kn_data >= PIPE_BUF);
1623}
1624