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