sys_pipe.c revision 246907
177701Sbrian/*-
285964Sbrian * Copyright (c) 1996 John S. Dyson
377701Sbrian * Copyright (c) 2012 Giovanni Trematerra
477701Sbrian * All rights reserved.
577701Sbrian *
677701Sbrian * Redistribution and use in source and binary forms, with or without
777701Sbrian * modification, are permitted provided that the following conditions
877701Sbrian * are met:
977701Sbrian * 1. Redistributions of source code must retain the above copyright
1077701Sbrian *    notice immediately at the beginning of the file, without modification,
1177701Sbrian *    this list of conditions, and the following disclaimer.
1277701Sbrian * 2. Redistributions in binary form must reproduce the above copyright
1377701Sbrian *    notice, this list of conditions and the following disclaimer in the
1477701Sbrian *    documentation and/or other materials provided with the distribution.
1577701Sbrian * 3. Absolutely no warranty of function or purpose is made by the author
1677701Sbrian *    John S. Dyson.
1777701Sbrian * 4. Modifications may be freely made to this file if the above conditions
1877701Sbrian *    are met.
1977701Sbrian */
2077701Sbrian
2177701Sbrian/*
2277701Sbrian * This file contains a high-performance replacement for the socket-based
2377701Sbrian * pipes scheme originally used in FreeBSD/4.4Lite.  It does not support
2477701Sbrian * all features of sockets, but does do everything that pipes normally
2577701Sbrian * do.
2677701Sbrian */
2784195Sdillon
2884195Sdillon/*
2984195Sdillon * This code has two modes of operation, a small write mode and a large
3026026Sbrian * write mode.  The small write mode acts like conventional pipes with
3126026Sbrian * a kernel buffer.  If the buffer is less than PIPE_MINDIRECT, then the
3226026Sbrian * "normal" pipe buffering is done.  If the buffer is between PIPE_MINDIRECT
3326026Sbrian * and PIPE_SIZE in size, the sending process pins the underlying pages in
3426026Sbrian * memory, and the receiving process copies directly from these pinned pages
3526026Sbrian * in the sending process.
3626026Sbrian *
3726026Sbrian * If the sending process receives a signal, it is possible that it will
3826026Sbrian * go away, and certainly its address space can change, because control
3926026Sbrian * is returned back to the user-mode side.  In that case, the pipe code
4026026Sbrian * arranges to copy the buffer supplied by the user process, to a pageable
4126026Sbrian * kernel buffer, and the receiving process will grab the data from the
4226026Sbrian * pageable kernel buffer.  Since signals don't happen all that often,
4326026Sbrian * the copy operation is normally eliminated.
44131612Sdes *
45131612Sdes * The constant PIPE_MINDIRECT is chosen to make sure that buffering will
46131612Sdes * happen for small transfers so that the system will not spend all of
47131612Sdes * its time context switching.
4826026Sbrian *
4926026Sbrian * In order to limit the resource use of pipes, two sysctls exist:
5026026Sbrian *
5126026Sbrian * kern.ipc.maxpipekva - This is a hard limit on the amount of pageable
5299207Sbrian * address space available to us in pipe_map. This value is normally
5326026Sbrian * autotuned, but may also be loader tuned.
5426026Sbrian *
5526026Sbrian * kern.ipc.pipekva - This read-only sysctl tracks the current amount of
5626026Sbrian * memory in use by pipes.
5726026Sbrian *
5826026Sbrian * Based on how large pipekva is relative to maxpipekva, the following
5926026Sbrian * will happen:
6026026Sbrian *
6126026Sbrian * 0% - 50%:
6226026Sbrian *     New pipes are given 16K of memory backing, pipes may dynamically
6326026Sbrian *     grow to as large as 64K where needed.
6426026Sbrian * 50% - 75%:
6526026Sbrian *     New pipes are given 4K (or PAGE_SIZE) of memory backing,
6626026Sbrian *     existing pipes may NOT grow.
6726026Sbrian * 75% - 100%:
68127094Sdes *     New pipes are given 4K (or PAGE_SIZE) of memory backing,
69127094Sdes *     existing pipes will be shrunk down to 4K whenever possible.
70127094Sdes *
71127094Sdes * Resizing may be disabled by setting kern.ipc.piperesizeallowed=0.  If
72127094Sdes * that is set,  the only resize that will occur is the 0 -> SMALL_PIPE_SIZE
73127094Sdes * resize which MUST occur for reverse-direction pipes when they are
7499207Sbrian * first used.
75127094Sdes *
76127094Sdes * Additional information about the current state of pipes may be obtained
77127094Sdes * from kern.ipc.pipes, kern.ipc.pipefragretry, kern.ipc.pipeallocfail,
78127094Sdes * and kern.ipc.piperesizefail.
79127094Sdes *
80127094Sdes * Locking rules:  There are two locks present here:  A mutex, used via
8199207Sbrian * PIPE_LOCK, and a flag, used via pipelock().  All locking is done via
8226026Sbrian * the flag, as mutexes can not persist over uiomove.  The mutex
83127094Sdes * exists only to guard access to the flag, and is not in itself a
84127094Sdes * locking mechanism.  Also note that there is only a single mutex for
85127094Sdes * both directions of a pipe.
86127094Sdes *
8726026Sbrian * As pipelock() may have to sleep before it can acquire the flag, it
88127094Sdes * is important to reread all data after a call to pipelock(); everything
89127094Sdes * in the structure may have changed.
90127094Sdes */
91127094Sdes
92127094Sdes#include <sys/cdefs.h>
93127094Sdes__FBSDID("$FreeBSD: head/sys/kern/sys_pipe.c 246907 2013-02-17 11:48:16Z pjd $");
9426026Sbrian
9526026Sbrian#include <sys/param.h>
96127094Sdes#include <sys/systm.h>
97127094Sdes#include <sys/conf.h>
98127094Sdes#include <sys/fcntl.h>
99127094Sdes#include <sys/file.h>
10026026Sbrian#include <sys/filedesc.h>
101127094Sdes#include <sys/filio.h>
102127094Sdes#include <sys/kernel.h>
103127094Sdes#include <sys/lock.h>
104127094Sdes#include <sys/mutex.h>
105127094Sdes#include <sys/ttycom.h>
106127094Sdes#include <sys/stat.h>
107127094Sdes#include <sys/malloc.h>
10826026Sbrian#include <sys/poll.h>
109127094Sdes#include <sys/selinfo.h>
110127094Sdes#include <sys/signalvar.h>
111127094Sdes#include <sys/syscallsubr.h>
112127094Sdes#include <sys/sysctl.h>
113127094Sdes#include <sys/sysproto.h>
114127094Sdes#include <sys/pipe.h>
115127094Sdes#include <sys/proc.h>
116127094Sdes#include <sys/vnode.h>
117127094Sdes#include <sys/uio.h>
11826026Sbrian#include <sys/event.h>
119127094Sdes
120127094Sdes#include <security/mac/mac_framework.h>
121127094Sdes
122127094Sdes#include <vm/vm.h>
123127094Sdes#include <vm/vm_param.h>
124127094Sdes#include <vm/vm_object.h>
125127094Sdes#include <vm/vm_kern.h>
126127094Sdes#include <vm/vm_extern.h>
127127094Sdes#include <vm/pmap.h>
128127094Sdes#include <vm/vm_map.h>
129127094Sdes#include <vm/vm_page.h>
130127094Sdes#include <vm/uma.h>
131127094Sdes
132127094Sdes/* XXX */
133127094Sdesint	do_pipe(struct thread *td, int fildes[2], int flags);
134127094Sdes
135127094Sdes/*
136127094Sdes * Use this define if you want to disable *fancy* VM things.  Expect an
137127094Sdes * approx 30% decrease in transfer rate.  This could be useful for
138127094Sdes * NetBSD or OpenBSD.
139127094Sdes */
140127094Sdes/* #define PIPE_NODIRECT */
141127094Sdes
142127094Sdes#define PIPE_PEER(pipe)	\
14326026Sbrian	(((pipe)->pipe_state & PIPE_NAMED) ? (pipe) : ((pipe)->pipe_peer))
144127094Sdes
145127094Sdes/*
146127094Sdes * interfaces to the outside world
147127094Sdes */
148127094Sdesstatic fo_rdwr_t	pipe_read;
149127094Sdesstatic fo_rdwr_t	pipe_write;
150127094Sdesstatic fo_truncate_t	pipe_truncate;
151127094Sdesstatic fo_ioctl_t	pipe_ioctl;
152127094Sdesstatic fo_poll_t	pipe_poll;
153127094Sdesstatic fo_kqfilter_t	pipe_kqfilter;
154127094Sdesstatic fo_stat_t	pipe_stat;
15526026Sbrianstatic fo_close_t	pipe_close;
156127094Sdesstatic fo_chmod_t	pipe_chmod;
157127094Sdesstatic fo_chown_t	pipe_chown;
158127094Sdes
159127094Sdesstruct fileops pipeops = {
160127094Sdes	.fo_read = pipe_read,
161127094Sdes	.fo_write = pipe_write,
162127094Sdes	.fo_truncate = pipe_truncate,
163127094Sdes	.fo_ioctl = pipe_ioctl,
164127094Sdes	.fo_poll = pipe_poll,
165127094Sdes	.fo_kqfilter = pipe_kqfilter,
166127094Sdes	.fo_stat = pipe_stat,
16726026Sbrian	.fo_close = pipe_close,
168127094Sdes	.fo_chmod = pipe_chmod,
169127094Sdes	.fo_chown = pipe_chown,
170127094Sdes	.fo_flags = DFLAG_PASSABLE
171127094Sdes};
172127094Sdes
173127094Sdesstatic void	filt_pipedetach(struct knote *kn);
174127094Sdesstatic void	filt_pipedetach_notsup(struct knote *kn);
175127094Sdesstatic int	filt_pipenotsup(struct knote *kn, long hint);
176127094Sdesstatic int	filt_piperead(struct knote *kn, long hint);
177127094Sdesstatic int	filt_pipewrite(struct knote *kn, long hint);
178127094Sdes
17926026Sbrianstatic struct filterops pipe_nfiltops = {
180127094Sdes	.f_isfd = 1,
181127094Sdes	.f_detach = filt_pipedetach_notsup,
182127094Sdes	.f_event = filt_pipenotsup
183127094Sdes};
184127094Sdesstatic struct filterops pipe_rfiltops = {
185127094Sdes	.f_isfd = 1,
186127094Sdes	.f_detach = filt_pipedetach,
187127094Sdes	.f_event = filt_piperead
188127094Sdes};
189127094Sdesstatic struct filterops pipe_wfiltops = {
190127094Sdes	.f_isfd = 1,
19126026Sbrian	.f_detach = filt_pipedetach,
192127094Sdes	.f_event = filt_pipewrite
193127094Sdes};
194127094Sdes
195127094Sdes/*
196127094Sdes * Default pipe buffer size(s), this can be kind-of large now because pipe
197127094Sdes * space is pageable.  The pipe code will try to maintain locality of
198127094Sdes * reference for performance reasons, so small amounts of outstanding I/O
199127094Sdes * will not wipe the cache.
200127094Sdes */
201127094Sdes#define MINPIPESIZE (PIPE_SIZE/3)
202127094Sdes#define MAXPIPESIZE (2*PIPE_SIZE/3)
20326026Sbrian
204127094Sdesstatic long amountpipekva;
205127094Sdesstatic int pipefragretry;
206127094Sdesstatic int pipeallocfail;
207127094Sdesstatic int piperesizefail;
208127094Sdesstatic int piperesizeallowed = 1;
209127094Sdes
210127094SdesSYSCTL_LONG(_kern_ipc, OID_AUTO, maxpipekva, CTLFLAG_RDTUN,
211127094Sdes	   &maxpipekva, 0, "Pipe KVA limit");
212127094SdesSYSCTL_LONG(_kern_ipc, OID_AUTO, pipekva, CTLFLAG_RD,
213127094Sdes	   &amountpipekva, 0, "Pipe KVA usage");
214127094SdesSYSCTL_INT(_kern_ipc, OID_AUTO, pipefragretry, CTLFLAG_RD,
215127094Sdes	  &pipefragretry, 0, "Pipe allocation retries due to fragmentation");
216127094SdesSYSCTL_INT(_kern_ipc, OID_AUTO, pipeallocfail, CTLFLAG_RD,
217127094Sdes	  &pipeallocfail, 0, "Pipe allocation failures");
218127094SdesSYSCTL_INT(_kern_ipc, OID_AUTO, piperesizefail, CTLFLAG_RD,
219127094Sdes	  &piperesizefail, 0, "Pipe resize failures");
220127094SdesSYSCTL_INT(_kern_ipc, OID_AUTO, piperesizeallowed, CTLFLAG_RW,
221127094Sdes	  &piperesizeallowed, 0, "Pipe resizing allowed");
222127094Sdes
223127094Sdesstatic void pipeinit(void *dummy __unused);
224127094Sdesstatic void pipeclose(struct pipe *cpipe);
225127094Sdesstatic void pipe_free_kmem(struct pipe *cpipe);
226127094Sdesstatic int pipe_create(struct pipe *pipe, int backing);
227127094Sdesstatic int pipe_paircreate(struct thread *td, struct pipepair **p_pp);
228127094Sdesstatic __inline int pipelock(struct pipe *cpipe, int catch);
229127094Sdesstatic __inline void pipeunlock(struct pipe *cpipe);
230127094Sdes#ifndef PIPE_NODIRECT
231127094Sdesstatic int pipe_build_write_buffer(struct pipe *wpipe, struct uio *uio);
232127094Sdesstatic void pipe_destroy_write_buffer(struct pipe *wpipe);
233127094Sdesstatic int pipe_direct_write(struct pipe *wpipe, struct uio *uio);
234127094Sdesstatic void pipe_clone_write_buffer(struct pipe *wpipe);
235127094Sdes#endif
236127094Sdesstatic int pipespace(struct pipe *cpipe, int size);
237127094Sdesstatic int pipespace_new(struct pipe *cpipe, int size);
238127094Sdes
239127094Sdesstatic int	pipe_zone_ctor(void *mem, int size, void *arg, int flags);
240127094Sdesstatic int	pipe_zone_init(void *mem, int size, int flags);
241127094Sdesstatic void	pipe_zone_fini(void *mem, int size);
242127094Sdes
243127094Sdesstatic uma_zone_t pipe_zone;
244127094Sdesstatic struct unrhdr *pipeino_unr;
245127094Sdesstatic dev_t pipedev_ino;
246127094Sdes
247127094SdesSYSINIT(vfs, SI_SUB_VFS, SI_ORDER_ANY, pipeinit, NULL);
248127094Sdes
24926026Sbrianstatic void
250127094Sdespipeinit(void *dummy __unused)
251127094Sdes{
252127094Sdes
253127094Sdes	pipe_zone = uma_zcreate("pipe", sizeof(struct pipepair),
25499207Sbrian	    pipe_zone_ctor, NULL, pipe_zone_init, pipe_zone_fini,
25526026Sbrian	    UMA_ALIGN_PTR, 0);
256127094Sdes	KASSERT(pipe_zone != NULL, ("pipe_zone not initialized"));
257127094Sdes	pipeino_unr = new_unrhdr(1, INT32_MAX, NULL);
258127094Sdes	KASSERT(pipeino_unr != NULL, ("pipe fake inodes not initialized"));
25982050Sru	pipedev_ino = devfs_alloc_cdp_inode();
260127094Sdes	KASSERT(pipedev_ino > 0, ("pipe dev inode not initialized"));
261127094Sdes}
262127094Sdes
263127094Sdesstatic int
264127094Sdespipe_zone_ctor(void *mem, int size, void *arg, int flags)
26526026Sbrian{
266127094Sdes	struct pipepair *pp;
267127094Sdes	struct pipe *rpipe, *wpipe;
268127094Sdes
269127094Sdes	KASSERT(size == sizeof(*pp), ("pipe_zone_ctor: wrong size"));
270127094Sdes
271127094Sdes	pp = (struct pipepair *)mem;
272127094Sdes
273127094Sdes	/*
274127094Sdes	 * We zero both pipe endpoints to make sure all the kmem pointers
275127094Sdes	 * are NULL, flag fields are zero'd, etc.  We timestamp both
276127094Sdes	 * endpoints with the same time.
277127094Sdes	 */
278127094Sdes	rpipe = &pp->pp_rpipe;
279127094Sdes	bzero(rpipe, sizeof(*rpipe));
280127094Sdes	vfs_timestamp(&rpipe->pipe_ctime);
28136711Sbrian	rpipe->pipe_atime = rpipe->pipe_mtime = rpipe->pipe_ctime;
282127094Sdes
283127094Sdes	wpipe = &pp->pp_wpipe;
28436711Sbrian	bzero(wpipe, sizeof(*wpipe));
28532377Seivind	wpipe->pipe_ctime = rpipe->pipe_ctime;
286127094Sdes	wpipe->pipe_atime = wpipe->pipe_mtime = rpipe->pipe_ctime;
287127094Sdes
288127094Sdes	rpipe->pipe_peer = wpipe;
289127094Sdes	rpipe->pipe_pair = pp;
290127094Sdes	wpipe->pipe_peer = rpipe;
291127094Sdes	wpipe->pipe_pair = pp;
292127094Sdes
293127094Sdes	/*
294127094Sdes	 * Mark both endpoints as present; they will later get free'd
295127094Sdes	 * one at a time.  When both are free'd, then the whole pair
296127094Sdes	 * is released.
297127094Sdes	 */
298127094Sdes	rpipe->pipe_present = PIPE_ACTIVE;
299127094Sdes	wpipe->pipe_present = PIPE_ACTIVE;
300127094Sdes
301127094Sdes	/*
302127094Sdes	 * Eventually, the MAC Framework may initialize the label
303127094Sdes	 * in ctor or init, but for now we do it elswhere to avoid
304127094Sdes	 * blocking in ctor or init.
305127094Sdes	 */
306127094Sdes	pp->pp_label = NULL;
307127094Sdes
308127094Sdes	return (0);
309127094Sdes}
310127094Sdes
311127094Sdesstatic int
312127094Sdespipe_zone_init(void *mem, int size, int flags)
313127094Sdes{
314127094Sdes	struct pipepair *pp;
315127094Sdes
316127094Sdes	KASSERT(size == sizeof(*pp), ("pipe_zone_init: wrong size"));
317127094Sdes
318127094Sdes	pp = (struct pipepair *)mem;
319127094Sdes
320127094Sdes	mtx_init(&pp->pp_mtx, "pipe mutex", NULL, MTX_DEF | MTX_RECURSE);
321127094Sdes	return (0);
322127094Sdes}
323127094Sdes
324127094Sdesstatic void
325127094Sdespipe_zone_fini(void *mem, int size)
326127094Sdes{
327127094Sdes	struct pipepair *pp;
328127094Sdes
329127094Sdes	KASSERT(size == sizeof(*pp), ("pipe_zone_fini: wrong size"));
330127094Sdes
331127094Sdes	pp = (struct pipepair *)mem;
332127094Sdes
333127094Sdes	mtx_destroy(&pp->pp_mtx);
334127094Sdes}
335127094Sdes
336127094Sdesstatic int
337127094Sdespipe_paircreate(struct thread *td, struct pipepair **p_pp)
338127094Sdes{
339127094Sdes	struct pipepair *pp;
34026026Sbrian	struct pipe *rpipe, *wpipe;
34126026Sbrian	int error;
342127094Sdes
343127094Sdes	*p_pp = pp = uma_zalloc(pipe_zone, M_WAITOK);
34426026Sbrian#ifdef MAC
345127094Sdes	/*
346127094Sdes	 * The MAC label is shared between the connected endpoints.  As a
347127094Sdes	 * result mac_pipe_init() and mac_pipe_create() are called once
348127094Sdes	 * for the pair, and not on the endpoints.
34926026Sbrian	 */
350127094Sdes	mac_pipe_init(pp);
351127094Sdes	mac_pipe_create(td->td_ucred, pp);
352127094Sdes#endif
35399207Sbrian	rpipe = &pp->pp_rpipe;
354127094Sdes	wpipe = &pp->pp_wpipe;
355127094Sdes
356127094Sdes	knlist_init_mtx(&rpipe->pipe_sel.si_note, PIPE_MTX(rpipe));
357127094Sdes	knlist_init_mtx(&wpipe->pipe_sel.si_note, PIPE_MTX(wpipe));
358127094Sdes
359127094Sdes	/* Only the forward direction pipe is backed by default */
360127094Sdes	if ((error = pipe_create(rpipe, 1)) != 0 ||
36126026Sbrian	    (error = pipe_create(wpipe, 0)) != 0) {
362127094Sdes		pipeclose(rpipe);
363127094Sdes		pipeclose(wpipe);
364127094Sdes		return (error);
365127094Sdes	}
366127094Sdes
36726026Sbrian	rpipe->pipe_state |= PIPE_DIRECTOK;
36826026Sbrian	wpipe->pipe_state |= PIPE_DIRECTOK;
36926026Sbrian	return (0);
37026026Sbrian}
37126026Sbrian
37226026Sbrianint
37326026Sbrianpipe_named_ctor(struct pipe **ppipe, struct thread *td)
37426026Sbrian{
37526026Sbrian	struct pipepair *pp;
37626026Sbrian	int error;
37726026Sbrian
37826026Sbrian	error = pipe_paircreate(td, &pp);
37926026Sbrian	if (error != 0)
38026026Sbrian		return (error);
38126026Sbrian	pp->pp_rpipe.pipe_state |= PIPE_NAMED;
38226026Sbrian	*ppipe = &pp->pp_rpipe;
38326026Sbrian	return (0);
38426026Sbrian}
38526026Sbrian
38626026Sbrianvoid
387pipe_dtor(struct pipe *dpipe)
388{
389	ino_t ino;
390
391	ino = dpipe->pipe_ino;
392	funsetown(&dpipe->pipe_sigio);
393	pipeclose(dpipe);
394	if (dpipe->pipe_state & PIPE_NAMED) {
395		dpipe = dpipe->pipe_peer;
396		funsetown(&dpipe->pipe_sigio);
397		pipeclose(dpipe);
398	}
399	if (ino != 0 && ino != (ino_t)-1)
400		free_unr(pipeino_unr, ino);
401}
402
403/*
404 * The pipe system call for the DTYPE_PIPE type of pipes.  If we fail, let
405 * the zone pick up the pieces via pipeclose().
406 */
407int
408kern_pipe(struct thread *td, int fildes[2])
409{
410
411	return (do_pipe(td, fildes, 0));
412}
413
414int
415do_pipe(struct thread *td, int fildes[2], int flags)
416{
417	struct filedesc *fdp;
418	struct file *rf, *wf;
419	struct pipe *rpipe, *wpipe;
420	struct pipepair *pp;
421	int fd, fflags, error;
422
423	fdp = td->td_proc->p_fd;
424	error = pipe_paircreate(td, &pp);
425	if (error != 0)
426		return (error);
427	rpipe = &pp->pp_rpipe;
428	wpipe = &pp->pp_wpipe;
429	error = falloc(td, &rf, &fd, flags);
430	if (error) {
431		pipeclose(rpipe);
432		pipeclose(wpipe);
433		return (error);
434	}
435	/* An extra reference on `rf' has been held for us by falloc(). */
436	fildes[0] = fd;
437
438	fflags = FREAD | FWRITE;
439	if ((flags & O_NONBLOCK) != 0)
440		fflags |= FNONBLOCK;
441
442	/*
443	 * Warning: once we've gotten past allocation of the fd for the
444	 * read-side, we can only drop the read side via fdrop() in order
445	 * to avoid races against processes which manage to dup() the read
446	 * side while we are blocked trying to allocate the write side.
447	 */
448	finit(rf, fflags, DTYPE_PIPE, rpipe, &pipeops);
449	error = falloc(td, &wf, &fd, flags);
450	if (error) {
451		fdclose(fdp, rf, fildes[0], td);
452		fdrop(rf, td);
453		/* rpipe has been closed by fdrop(). */
454		pipeclose(wpipe);
455		return (error);
456	}
457	/* An extra reference on `wf' has been held for us by falloc(). */
458	finit(wf, fflags, DTYPE_PIPE, wpipe, &pipeops);
459	fdrop(wf, td);
460	fildes[1] = fd;
461	fdrop(rf, td);
462
463	return (0);
464}
465
466/* ARGSUSED */
467int
468sys_pipe(struct thread *td, struct pipe_args *uap)
469{
470	int error;
471	int fildes[2];
472
473	error = kern_pipe(td, fildes);
474	if (error)
475		return (error);
476
477	td->td_retval[0] = fildes[0];
478	td->td_retval[1] = fildes[1];
479
480	return (0);
481}
482
483/*
484 * Allocate kva for pipe circular buffer, the space is pageable
485 * This routine will 'realloc' the size of a pipe safely, if it fails
486 * it will retain the old buffer.
487 * If it fails it will return ENOMEM.
488 */
489static int
490pipespace_new(cpipe, size)
491	struct pipe *cpipe;
492	int size;
493{
494	caddr_t buffer;
495	int error, cnt, firstseg;
496	static int curfail = 0;
497	static struct timeval lastfail;
498
499	KASSERT(!mtx_owned(PIPE_MTX(cpipe)), ("pipespace: pipe mutex locked"));
500	KASSERT(!(cpipe->pipe_state & PIPE_DIRECTW),
501		("pipespace: resize of direct writes not allowed"));
502retry:
503	cnt = cpipe->pipe_buffer.cnt;
504	if (cnt > size)
505		size = cnt;
506
507	size = round_page(size);
508	buffer = (caddr_t) vm_map_min(pipe_map);
509
510	error = vm_map_find(pipe_map, NULL, 0,
511		(vm_offset_t *) &buffer, size, 1,
512		VM_PROT_ALL, VM_PROT_ALL, 0);
513	if (error != KERN_SUCCESS) {
514		if ((cpipe->pipe_buffer.buffer == NULL) &&
515			(size > SMALL_PIPE_SIZE)) {
516			size = SMALL_PIPE_SIZE;
517			pipefragretry++;
518			goto retry;
519		}
520		if (cpipe->pipe_buffer.buffer == NULL) {
521			pipeallocfail++;
522			if (ppsratecheck(&lastfail, &curfail, 1))
523				printf("kern.ipc.maxpipekva exceeded; see tuning(7)\n");
524		} else {
525			piperesizefail++;
526		}
527		return (ENOMEM);
528	}
529
530	/* copy data, then free old resources if we're resizing */
531	if (cnt > 0) {
532		if (cpipe->pipe_buffer.in <= cpipe->pipe_buffer.out) {
533			firstseg = cpipe->pipe_buffer.size - cpipe->pipe_buffer.out;
534			bcopy(&cpipe->pipe_buffer.buffer[cpipe->pipe_buffer.out],
535				buffer, firstseg);
536			if ((cnt - firstseg) > 0)
537				bcopy(cpipe->pipe_buffer.buffer, &buffer[firstseg],
538					cpipe->pipe_buffer.in);
539		} else {
540			bcopy(&cpipe->pipe_buffer.buffer[cpipe->pipe_buffer.out],
541				buffer, cnt);
542		}
543	}
544	pipe_free_kmem(cpipe);
545	cpipe->pipe_buffer.buffer = buffer;
546	cpipe->pipe_buffer.size = size;
547	cpipe->pipe_buffer.in = cnt;
548	cpipe->pipe_buffer.out = 0;
549	cpipe->pipe_buffer.cnt = cnt;
550	atomic_add_long(&amountpipekva, cpipe->pipe_buffer.size);
551	return (0);
552}
553
554/*
555 * Wrapper for pipespace_new() that performs locking assertions.
556 */
557static int
558pipespace(cpipe, size)
559	struct pipe *cpipe;
560	int size;
561{
562
563	KASSERT(cpipe->pipe_state & PIPE_LOCKFL,
564		("Unlocked pipe passed to pipespace"));
565	return (pipespace_new(cpipe, size));
566}
567
568/*
569 * lock a pipe for I/O, blocking other access
570 */
571static __inline int
572pipelock(cpipe, catch)
573	struct pipe *cpipe;
574	int catch;
575{
576	int error;
577
578	PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
579	while (cpipe->pipe_state & PIPE_LOCKFL) {
580		cpipe->pipe_state |= PIPE_LWANT;
581		error = msleep(cpipe, PIPE_MTX(cpipe),
582		    catch ? (PRIBIO | PCATCH) : PRIBIO,
583		    "pipelk", 0);
584		if (error != 0)
585			return (error);
586	}
587	cpipe->pipe_state |= PIPE_LOCKFL;
588	return (0);
589}
590
591/*
592 * unlock a pipe I/O lock
593 */
594static __inline void
595pipeunlock(cpipe)
596	struct pipe *cpipe;
597{
598
599	PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
600	KASSERT(cpipe->pipe_state & PIPE_LOCKFL,
601		("Unlocked pipe passed to pipeunlock"));
602	cpipe->pipe_state &= ~PIPE_LOCKFL;
603	if (cpipe->pipe_state & PIPE_LWANT) {
604		cpipe->pipe_state &= ~PIPE_LWANT;
605		wakeup(cpipe);
606	}
607}
608
609void
610pipeselwakeup(cpipe)
611	struct pipe *cpipe;
612{
613
614	PIPE_LOCK_ASSERT(cpipe, MA_OWNED);
615	if (cpipe->pipe_state & PIPE_SEL) {
616		selwakeuppri(&cpipe->pipe_sel, PSOCK);
617		if (!SEL_WAITING(&cpipe->pipe_sel))
618			cpipe->pipe_state &= ~PIPE_SEL;
619	}
620	if ((cpipe->pipe_state & PIPE_ASYNC) && cpipe->pipe_sigio)
621		pgsigio(&cpipe->pipe_sigio, SIGIO, 0);
622	KNOTE_LOCKED(&cpipe->pipe_sel.si_note, 0);
623}
624
625/*
626 * Initialize and allocate VM and memory for pipe.  The structure
627 * will start out zero'd from the ctor, so we just manage the kmem.
628 */
629static int
630pipe_create(pipe, backing)
631	struct pipe *pipe;
632	int backing;
633{
634	int error;
635
636	if (backing) {
637		if (amountpipekva > maxpipekva / 2)
638			error = pipespace_new(pipe, SMALL_PIPE_SIZE);
639		else
640			error = pipespace_new(pipe, PIPE_SIZE);
641	} else {
642		/* If we're not backing this pipe, no need to do anything. */
643		error = 0;
644	}
645	pipe->pipe_ino = -1;
646	return (error);
647}
648
649/* ARGSUSED */
650static int
651pipe_read(fp, uio, active_cred, flags, td)
652	struct file *fp;
653	struct uio *uio;
654	struct ucred *active_cred;
655	struct thread *td;
656	int flags;
657{
658	struct pipe *rpipe;
659	int error;
660	int nread = 0;
661	int size;
662
663	rpipe = fp->f_data;
664	PIPE_LOCK(rpipe);
665	++rpipe->pipe_busy;
666	error = pipelock(rpipe, 1);
667	if (error)
668		goto unlocked_error;
669
670#ifdef MAC
671	error = mac_pipe_check_read(active_cred, rpipe->pipe_pair);
672	if (error)
673		goto locked_error;
674#endif
675	if (amountpipekva > (3 * maxpipekva) / 4) {
676		if (!(rpipe->pipe_state & PIPE_DIRECTW) &&
677			(rpipe->pipe_buffer.size > SMALL_PIPE_SIZE) &&
678			(rpipe->pipe_buffer.cnt <= SMALL_PIPE_SIZE) &&
679			(piperesizeallowed == 1)) {
680			PIPE_UNLOCK(rpipe);
681			pipespace(rpipe, SMALL_PIPE_SIZE);
682			PIPE_LOCK(rpipe);
683		}
684	}
685
686	while (uio->uio_resid) {
687		/*
688		 * normal pipe buffer receive
689		 */
690		if (rpipe->pipe_buffer.cnt > 0) {
691			size = rpipe->pipe_buffer.size - rpipe->pipe_buffer.out;
692			if (size > rpipe->pipe_buffer.cnt)
693				size = rpipe->pipe_buffer.cnt;
694			if (size > uio->uio_resid)
695				size = uio->uio_resid;
696
697			PIPE_UNLOCK(rpipe);
698			error = uiomove(
699			    &rpipe->pipe_buffer.buffer[rpipe->pipe_buffer.out],
700			    size, uio);
701			PIPE_LOCK(rpipe);
702			if (error)
703				break;
704
705			rpipe->pipe_buffer.out += size;
706			if (rpipe->pipe_buffer.out >= rpipe->pipe_buffer.size)
707				rpipe->pipe_buffer.out = 0;
708
709			rpipe->pipe_buffer.cnt -= size;
710
711			/*
712			 * If there is no more to read in the pipe, reset
713			 * its pointers to the beginning.  This improves
714			 * cache hit stats.
715			 */
716			if (rpipe->pipe_buffer.cnt == 0) {
717				rpipe->pipe_buffer.in = 0;
718				rpipe->pipe_buffer.out = 0;
719			}
720			nread += size;
721#ifndef PIPE_NODIRECT
722		/*
723		 * Direct copy, bypassing a kernel buffer.
724		 */
725		} else if ((size = rpipe->pipe_map.cnt) &&
726			   (rpipe->pipe_state & PIPE_DIRECTW)) {
727			if (size > uio->uio_resid)
728				size = (u_int) uio->uio_resid;
729
730			PIPE_UNLOCK(rpipe);
731			error = uiomove_fromphys(rpipe->pipe_map.ms,
732			    rpipe->pipe_map.pos, size, uio);
733			PIPE_LOCK(rpipe);
734			if (error)
735				break;
736			nread += size;
737			rpipe->pipe_map.pos += size;
738			rpipe->pipe_map.cnt -= size;
739			if (rpipe->pipe_map.cnt == 0) {
740				rpipe->pipe_state &= ~(PIPE_DIRECTW|PIPE_WANTW);
741				wakeup(rpipe);
742			}
743#endif
744		} else {
745			/*
746			 * detect EOF condition
747			 * read returns 0 on EOF, no need to set error
748			 */
749			if (rpipe->pipe_state & PIPE_EOF)
750				break;
751
752			/*
753			 * If the "write-side" has been blocked, wake it up now.
754			 */
755			if (rpipe->pipe_state & PIPE_WANTW) {
756				rpipe->pipe_state &= ~PIPE_WANTW;
757				wakeup(rpipe);
758			}
759
760			/*
761			 * Break if some data was read.
762			 */
763			if (nread > 0)
764				break;
765
766			/*
767			 * Unlock the pipe buffer for our remaining processing.
768			 * We will either break out with an error or we will
769			 * sleep and relock to loop.
770			 */
771			pipeunlock(rpipe);
772
773			/*
774			 * Handle non-blocking mode operation or
775			 * wait for more data.
776			 */
777			if (fp->f_flag & FNONBLOCK) {
778				error = EAGAIN;
779			} else {
780				rpipe->pipe_state |= PIPE_WANTR;
781				if ((error = msleep(rpipe, PIPE_MTX(rpipe),
782				    PRIBIO | PCATCH,
783				    "piperd", 0)) == 0)
784					error = pipelock(rpipe, 1);
785			}
786			if (error)
787				goto unlocked_error;
788		}
789	}
790#ifdef MAC
791locked_error:
792#endif
793	pipeunlock(rpipe);
794
795	/* XXX: should probably do this before getting any locks. */
796	if (error == 0)
797		vfs_timestamp(&rpipe->pipe_atime);
798unlocked_error:
799	--rpipe->pipe_busy;
800
801	/*
802	 * PIPE_WANT processing only makes sense if pipe_busy is 0.
803	 */
804	if ((rpipe->pipe_busy == 0) && (rpipe->pipe_state & PIPE_WANT)) {
805		rpipe->pipe_state &= ~(PIPE_WANT|PIPE_WANTW);
806		wakeup(rpipe);
807	} else if (rpipe->pipe_buffer.cnt < MINPIPESIZE) {
808		/*
809		 * Handle write blocking hysteresis.
810		 */
811		if (rpipe->pipe_state & PIPE_WANTW) {
812			rpipe->pipe_state &= ~PIPE_WANTW;
813			wakeup(rpipe);
814		}
815	}
816
817	if ((rpipe->pipe_buffer.size - rpipe->pipe_buffer.cnt) >= PIPE_BUF)
818		pipeselwakeup(rpipe);
819
820	PIPE_UNLOCK(rpipe);
821	return (error);
822}
823
824#ifndef PIPE_NODIRECT
825/*
826 * Map the sending processes' buffer into kernel space and wire it.
827 * This is similar to a physical write operation.
828 */
829static int
830pipe_build_write_buffer(wpipe, uio)
831	struct pipe *wpipe;
832	struct uio *uio;
833{
834	u_int size;
835	int i;
836
837	PIPE_LOCK_ASSERT(wpipe, MA_NOTOWNED);
838	KASSERT(wpipe->pipe_state & PIPE_DIRECTW,
839		("Clone attempt on non-direct write pipe!"));
840
841	if (uio->uio_iov->iov_len > wpipe->pipe_buffer.size)
842                size = wpipe->pipe_buffer.size;
843	else
844                size = uio->uio_iov->iov_len;
845
846	if ((i = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
847	    (vm_offset_t)uio->uio_iov->iov_base, size, VM_PROT_READ,
848	    wpipe->pipe_map.ms, PIPENPAGES)) < 0)
849		return (EFAULT);
850
851/*
852 * set up the control block
853 */
854	wpipe->pipe_map.npages = i;
855	wpipe->pipe_map.pos =
856	    ((vm_offset_t) uio->uio_iov->iov_base) & PAGE_MASK;
857	wpipe->pipe_map.cnt = size;
858
859/*
860 * and update the uio data
861 */
862
863	uio->uio_iov->iov_len -= size;
864	uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + size;
865	if (uio->uio_iov->iov_len == 0)
866		uio->uio_iov++;
867	uio->uio_resid -= size;
868	uio->uio_offset += size;
869	return (0);
870}
871
872/*
873 * unmap and unwire the process buffer
874 */
875static void
876pipe_destroy_write_buffer(wpipe)
877	struct pipe *wpipe;
878{
879
880	PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
881	vm_page_unhold_pages(wpipe->pipe_map.ms, wpipe->pipe_map.npages);
882	wpipe->pipe_map.npages = 0;
883}
884
885/*
886 * In the case of a signal, the writing process might go away.  This
887 * code copies the data into the circular buffer so that the source
888 * pages can be freed without loss of data.
889 */
890static void
891pipe_clone_write_buffer(wpipe)
892	struct pipe *wpipe;
893{
894	struct uio uio;
895	struct iovec iov;
896	int size;
897	int pos;
898
899	PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
900	size = wpipe->pipe_map.cnt;
901	pos = wpipe->pipe_map.pos;
902
903	wpipe->pipe_buffer.in = size;
904	wpipe->pipe_buffer.out = 0;
905	wpipe->pipe_buffer.cnt = size;
906	wpipe->pipe_state &= ~PIPE_DIRECTW;
907
908	PIPE_UNLOCK(wpipe);
909	iov.iov_base = wpipe->pipe_buffer.buffer;
910	iov.iov_len = size;
911	uio.uio_iov = &iov;
912	uio.uio_iovcnt = 1;
913	uio.uio_offset = 0;
914	uio.uio_resid = size;
915	uio.uio_segflg = UIO_SYSSPACE;
916	uio.uio_rw = UIO_READ;
917	uio.uio_td = curthread;
918	uiomove_fromphys(wpipe->pipe_map.ms, pos, size, &uio);
919	PIPE_LOCK(wpipe);
920	pipe_destroy_write_buffer(wpipe);
921}
922
923/*
924 * This implements the pipe buffer write mechanism.  Note that only
925 * a direct write OR a normal pipe write can be pending at any given time.
926 * If there are any characters in the pipe buffer, the direct write will
927 * be deferred until the receiving process grabs all of the bytes from
928 * the pipe buffer.  Then the direct mapping write is set-up.
929 */
930static int
931pipe_direct_write(wpipe, uio)
932	struct pipe *wpipe;
933	struct uio *uio;
934{
935	int error;
936
937retry:
938	PIPE_LOCK_ASSERT(wpipe, MA_OWNED);
939	error = pipelock(wpipe, 1);
940	if (wpipe->pipe_state & PIPE_EOF)
941		error = EPIPE;
942	if (error) {
943		pipeunlock(wpipe);
944		goto error1;
945	}
946	while (wpipe->pipe_state & PIPE_DIRECTW) {
947		if (wpipe->pipe_state & PIPE_WANTR) {
948			wpipe->pipe_state &= ~PIPE_WANTR;
949			wakeup(wpipe);
950		}
951		pipeselwakeup(wpipe);
952		wpipe->pipe_state |= PIPE_WANTW;
953		pipeunlock(wpipe);
954		error = msleep(wpipe, PIPE_MTX(wpipe),
955		    PRIBIO | PCATCH, "pipdww", 0);
956		if (error)
957			goto error1;
958		else
959			goto retry;
960	}
961	wpipe->pipe_map.cnt = 0;	/* transfer not ready yet */
962	if (wpipe->pipe_buffer.cnt > 0) {
963		if (wpipe->pipe_state & PIPE_WANTR) {
964			wpipe->pipe_state &= ~PIPE_WANTR;
965			wakeup(wpipe);
966		}
967		pipeselwakeup(wpipe);
968		wpipe->pipe_state |= PIPE_WANTW;
969		pipeunlock(wpipe);
970		error = msleep(wpipe, PIPE_MTX(wpipe),
971		    PRIBIO | PCATCH, "pipdwc", 0);
972		if (error)
973			goto error1;
974		else
975			goto retry;
976	}
977
978	wpipe->pipe_state |= PIPE_DIRECTW;
979
980	PIPE_UNLOCK(wpipe);
981	error = pipe_build_write_buffer(wpipe, uio);
982	PIPE_LOCK(wpipe);
983	if (error) {
984		wpipe->pipe_state &= ~PIPE_DIRECTW;
985		pipeunlock(wpipe);
986		goto error1;
987	}
988
989	error = 0;
990	while (!error && (wpipe->pipe_state & PIPE_DIRECTW)) {
991		if (wpipe->pipe_state & PIPE_EOF) {
992			pipe_destroy_write_buffer(wpipe);
993			pipeselwakeup(wpipe);
994			pipeunlock(wpipe);
995			error = EPIPE;
996			goto error1;
997		}
998		if (wpipe->pipe_state & PIPE_WANTR) {
999			wpipe->pipe_state &= ~PIPE_WANTR;
1000			wakeup(wpipe);
1001		}
1002		pipeselwakeup(wpipe);
1003		wpipe->pipe_state |= PIPE_WANTW;
1004		pipeunlock(wpipe);
1005		error = msleep(wpipe, PIPE_MTX(wpipe), PRIBIO | PCATCH,
1006		    "pipdwt", 0);
1007		pipelock(wpipe, 0);
1008	}
1009
1010	if (wpipe->pipe_state & PIPE_EOF)
1011		error = EPIPE;
1012	if (wpipe->pipe_state & PIPE_DIRECTW) {
1013		/*
1014		 * this bit of trickery substitutes a kernel buffer for
1015		 * the process that might be going away.
1016		 */
1017		pipe_clone_write_buffer(wpipe);
1018	} else {
1019		pipe_destroy_write_buffer(wpipe);
1020	}
1021	pipeunlock(wpipe);
1022	return (error);
1023
1024error1:
1025	wakeup(wpipe);
1026	return (error);
1027}
1028#endif
1029
1030static int
1031pipe_write(fp, uio, active_cred, flags, td)
1032	struct file *fp;
1033	struct uio *uio;
1034	struct ucred *active_cred;
1035	struct thread *td;
1036	int flags;
1037{
1038	int error = 0;
1039	int desiredsize;
1040	ssize_t orig_resid;
1041	struct pipe *wpipe, *rpipe;
1042
1043	rpipe = fp->f_data;
1044	wpipe = PIPE_PEER(rpipe);
1045	PIPE_LOCK(rpipe);
1046	error = pipelock(wpipe, 1);
1047	if (error) {
1048		PIPE_UNLOCK(rpipe);
1049		return (error);
1050	}
1051	/*
1052	 * detect loss of pipe read side, issue SIGPIPE if lost.
1053	 */
1054	if (wpipe->pipe_present != PIPE_ACTIVE ||
1055	    (wpipe->pipe_state & PIPE_EOF)) {
1056		pipeunlock(wpipe);
1057		PIPE_UNLOCK(rpipe);
1058		return (EPIPE);
1059	}
1060#ifdef MAC
1061	error = mac_pipe_check_write(active_cred, wpipe->pipe_pair);
1062	if (error) {
1063		pipeunlock(wpipe);
1064		PIPE_UNLOCK(rpipe);
1065		return (error);
1066	}
1067#endif
1068	++wpipe->pipe_busy;
1069
1070	/* Choose a larger size if it's advantageous */
1071	desiredsize = max(SMALL_PIPE_SIZE, wpipe->pipe_buffer.size);
1072	while (desiredsize < wpipe->pipe_buffer.cnt + uio->uio_resid) {
1073		if (piperesizeallowed != 1)
1074			break;
1075		if (amountpipekva > maxpipekva / 2)
1076			break;
1077		if (desiredsize == BIG_PIPE_SIZE)
1078			break;
1079		desiredsize = desiredsize * 2;
1080	}
1081
1082	/* Choose a smaller size if we're in a OOM situation */
1083	if ((amountpipekva > (3 * maxpipekva) / 4) &&
1084		(wpipe->pipe_buffer.size > SMALL_PIPE_SIZE) &&
1085		(wpipe->pipe_buffer.cnt <= SMALL_PIPE_SIZE) &&
1086		(piperesizeallowed == 1))
1087		desiredsize = SMALL_PIPE_SIZE;
1088
1089	/* Resize if the above determined that a new size was necessary */
1090	if ((desiredsize != wpipe->pipe_buffer.size) &&
1091		((wpipe->pipe_state & PIPE_DIRECTW) == 0)) {
1092		PIPE_UNLOCK(wpipe);
1093		pipespace(wpipe, desiredsize);
1094		PIPE_LOCK(wpipe);
1095	}
1096	if (wpipe->pipe_buffer.size == 0) {
1097		/*
1098		 * This can only happen for reverse direction use of pipes
1099		 * in a complete OOM situation.
1100		 */
1101		error = ENOMEM;
1102		--wpipe->pipe_busy;
1103		pipeunlock(wpipe);
1104		PIPE_UNLOCK(wpipe);
1105		return (error);
1106	}
1107
1108	pipeunlock(wpipe);
1109
1110	orig_resid = uio->uio_resid;
1111
1112	while (uio->uio_resid) {
1113		int space;
1114
1115		pipelock(wpipe, 0);
1116		if (wpipe->pipe_state & PIPE_EOF) {
1117			pipeunlock(wpipe);
1118			error = EPIPE;
1119			break;
1120		}
1121#ifndef PIPE_NODIRECT
1122		/*
1123		 * If the transfer is large, we can gain performance if
1124		 * we do process-to-process copies directly.
1125		 * If the write is non-blocking, we don't use the
1126		 * direct write mechanism.
1127		 *
1128		 * The direct write mechanism will detect the reader going
1129		 * away on us.
1130		 */
1131		if (uio->uio_segflg == UIO_USERSPACE &&
1132		    uio->uio_iov->iov_len >= PIPE_MINDIRECT &&
1133		    wpipe->pipe_buffer.size >= PIPE_MINDIRECT &&
1134		    (fp->f_flag & FNONBLOCK) == 0) {
1135			pipeunlock(wpipe);
1136			error = pipe_direct_write(wpipe, uio);
1137			if (error)
1138				break;
1139			continue;
1140		}
1141#endif
1142
1143		/*
1144		 * Pipe buffered writes cannot be coincidental with
1145		 * direct writes.  We wait until the currently executing
1146		 * direct write is completed before we start filling the
1147		 * pipe buffer.  We break out if a signal occurs or the
1148		 * reader goes away.
1149		 */
1150		if (wpipe->pipe_state & PIPE_DIRECTW) {
1151			if (wpipe->pipe_state & PIPE_WANTR) {
1152				wpipe->pipe_state &= ~PIPE_WANTR;
1153				wakeup(wpipe);
1154			}
1155			pipeselwakeup(wpipe);
1156			wpipe->pipe_state |= PIPE_WANTW;
1157			pipeunlock(wpipe);
1158			error = msleep(wpipe, PIPE_MTX(rpipe), PRIBIO | PCATCH,
1159			    "pipbww", 0);
1160			if (error)
1161				break;
1162			else
1163				continue;
1164		}
1165
1166		space = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
1167
1168		/* Writes of size <= PIPE_BUF must be atomic. */
1169		if ((space < uio->uio_resid) && (orig_resid <= PIPE_BUF))
1170			space = 0;
1171
1172		if (space > 0) {
1173			int size;	/* Transfer size */
1174			int segsize;	/* first segment to transfer */
1175
1176			/*
1177			 * Transfer size is minimum of uio transfer
1178			 * and free space in pipe buffer.
1179			 */
1180			if (space > uio->uio_resid)
1181				size = uio->uio_resid;
1182			else
1183				size = space;
1184			/*
1185			 * First segment to transfer is minimum of
1186			 * transfer size and contiguous space in
1187			 * pipe buffer.  If first segment to transfer
1188			 * is less than the transfer size, we've got
1189			 * a wraparound in the buffer.
1190			 */
1191			segsize = wpipe->pipe_buffer.size -
1192				wpipe->pipe_buffer.in;
1193			if (segsize > size)
1194				segsize = size;
1195
1196			/* Transfer first segment */
1197
1198			PIPE_UNLOCK(rpipe);
1199			error = uiomove(&wpipe->pipe_buffer.buffer[wpipe->pipe_buffer.in],
1200					segsize, uio);
1201			PIPE_LOCK(rpipe);
1202
1203			if (error == 0 && segsize < size) {
1204				KASSERT(wpipe->pipe_buffer.in + segsize ==
1205					wpipe->pipe_buffer.size,
1206					("Pipe buffer wraparound disappeared"));
1207				/*
1208				 * Transfer remaining part now, to
1209				 * support atomic writes.  Wraparound
1210				 * happened.
1211				 */
1212
1213				PIPE_UNLOCK(rpipe);
1214				error = uiomove(
1215				    &wpipe->pipe_buffer.buffer[0],
1216				    size - segsize, uio);
1217				PIPE_LOCK(rpipe);
1218			}
1219			if (error == 0) {
1220				wpipe->pipe_buffer.in += size;
1221				if (wpipe->pipe_buffer.in >=
1222				    wpipe->pipe_buffer.size) {
1223					KASSERT(wpipe->pipe_buffer.in ==
1224						size - segsize +
1225						wpipe->pipe_buffer.size,
1226						("Expected wraparound bad"));
1227					wpipe->pipe_buffer.in = size - segsize;
1228				}
1229
1230				wpipe->pipe_buffer.cnt += size;
1231				KASSERT(wpipe->pipe_buffer.cnt <=
1232					wpipe->pipe_buffer.size,
1233					("Pipe buffer overflow"));
1234			}
1235			pipeunlock(wpipe);
1236			if (error != 0)
1237				break;
1238		} else {
1239			/*
1240			 * If the "read-side" has been blocked, wake it up now.
1241			 */
1242			if (wpipe->pipe_state & PIPE_WANTR) {
1243				wpipe->pipe_state &= ~PIPE_WANTR;
1244				wakeup(wpipe);
1245			}
1246
1247			/*
1248			 * don't block on non-blocking I/O
1249			 */
1250			if (fp->f_flag & FNONBLOCK) {
1251				error = EAGAIN;
1252				pipeunlock(wpipe);
1253				break;
1254			}
1255
1256			/*
1257			 * We have no more space and have something to offer,
1258			 * wake up select/poll.
1259			 */
1260			pipeselwakeup(wpipe);
1261
1262			wpipe->pipe_state |= PIPE_WANTW;
1263			pipeunlock(wpipe);
1264			error = msleep(wpipe, PIPE_MTX(rpipe),
1265			    PRIBIO | PCATCH, "pipewr", 0);
1266			if (error != 0)
1267				break;
1268		}
1269	}
1270
1271	pipelock(wpipe, 0);
1272	--wpipe->pipe_busy;
1273
1274	if ((wpipe->pipe_busy == 0) && (wpipe->pipe_state & PIPE_WANT)) {
1275		wpipe->pipe_state &= ~(PIPE_WANT | PIPE_WANTR);
1276		wakeup(wpipe);
1277	} else if (wpipe->pipe_buffer.cnt > 0) {
1278		/*
1279		 * If we have put any characters in the buffer, we wake up
1280		 * the reader.
1281		 */
1282		if (wpipe->pipe_state & PIPE_WANTR) {
1283			wpipe->pipe_state &= ~PIPE_WANTR;
1284			wakeup(wpipe);
1285		}
1286	}
1287
1288	/*
1289	 * Don't return EPIPE if I/O was successful
1290	 */
1291	if ((wpipe->pipe_buffer.cnt == 0) &&
1292	    (uio->uio_resid == 0) &&
1293	    (error == EPIPE)) {
1294		error = 0;
1295	}
1296
1297	if (error == 0)
1298		vfs_timestamp(&wpipe->pipe_mtime);
1299
1300	/*
1301	 * We have something to offer,
1302	 * wake up select/poll.
1303	 */
1304	if (wpipe->pipe_buffer.cnt)
1305		pipeselwakeup(wpipe);
1306
1307	pipeunlock(wpipe);
1308	PIPE_UNLOCK(rpipe);
1309	return (error);
1310}
1311
1312/* ARGSUSED */
1313static int
1314pipe_truncate(fp, length, active_cred, td)
1315	struct file *fp;
1316	off_t length;
1317	struct ucred *active_cred;
1318	struct thread *td;
1319{
1320
1321	/* For named pipes call the vnode operation. */
1322	if (fp->f_vnode != NULL)
1323		return (vnops.fo_truncate(fp, length, active_cred, td));
1324	return (EINVAL);
1325}
1326
1327/*
1328 * we implement a very minimal set of ioctls for compatibility with sockets.
1329 */
1330static int
1331pipe_ioctl(fp, cmd, data, active_cred, td)
1332	struct file *fp;
1333	u_long cmd;
1334	void *data;
1335	struct ucred *active_cred;
1336	struct thread *td;
1337{
1338	struct pipe *mpipe = fp->f_data;
1339	int error;
1340
1341	PIPE_LOCK(mpipe);
1342
1343#ifdef MAC
1344	error = mac_pipe_check_ioctl(active_cred, mpipe->pipe_pair, cmd, data);
1345	if (error) {
1346		PIPE_UNLOCK(mpipe);
1347		return (error);
1348	}
1349#endif
1350
1351	error = 0;
1352	switch (cmd) {
1353
1354	case FIONBIO:
1355		break;
1356
1357	case FIOASYNC:
1358		if (*(int *)data) {
1359			mpipe->pipe_state |= PIPE_ASYNC;
1360		} else {
1361			mpipe->pipe_state &= ~PIPE_ASYNC;
1362		}
1363		break;
1364
1365	case FIONREAD:
1366		if (!(fp->f_flag & FREAD)) {
1367			*(int *)data = 0;
1368			PIPE_UNLOCK(mpipe);
1369			return (0);
1370		}
1371		if (mpipe->pipe_state & PIPE_DIRECTW)
1372			*(int *)data = mpipe->pipe_map.cnt;
1373		else
1374			*(int *)data = mpipe->pipe_buffer.cnt;
1375		break;
1376
1377	case FIOSETOWN:
1378		PIPE_UNLOCK(mpipe);
1379		error = fsetown(*(int *)data, &mpipe->pipe_sigio);
1380		goto out_unlocked;
1381
1382	case FIOGETOWN:
1383		*(int *)data = fgetown(&mpipe->pipe_sigio);
1384		break;
1385
1386	/* This is deprecated, FIOSETOWN should be used instead. */
1387	case TIOCSPGRP:
1388		PIPE_UNLOCK(mpipe);
1389		error = fsetown(-(*(int *)data), &mpipe->pipe_sigio);
1390		goto out_unlocked;
1391
1392	/* This is deprecated, FIOGETOWN should be used instead. */
1393	case TIOCGPGRP:
1394		*(int *)data = -fgetown(&mpipe->pipe_sigio);
1395		break;
1396
1397	default:
1398		error = ENOTTY;
1399		break;
1400	}
1401	PIPE_UNLOCK(mpipe);
1402out_unlocked:
1403	return (error);
1404}
1405
1406static int
1407pipe_poll(fp, events, active_cred, td)
1408	struct file *fp;
1409	int events;
1410	struct ucred *active_cred;
1411	struct thread *td;
1412{
1413	struct pipe *rpipe;
1414	struct pipe *wpipe;
1415	int levents, revents;
1416#ifdef MAC
1417	int error;
1418#endif
1419
1420	revents = 0;
1421	rpipe = fp->f_data;
1422	wpipe = PIPE_PEER(rpipe);
1423	PIPE_LOCK(rpipe);
1424#ifdef MAC
1425	error = mac_pipe_check_poll(active_cred, rpipe->pipe_pair);
1426	if (error)
1427		goto locked_error;
1428#endif
1429	if (fp->f_flag & FREAD && events & (POLLIN | POLLRDNORM))
1430		if ((rpipe->pipe_state & PIPE_DIRECTW) ||
1431		    (rpipe->pipe_buffer.cnt > 0))
1432			revents |= events & (POLLIN | POLLRDNORM);
1433
1434	if (fp->f_flag & FWRITE && events & (POLLOUT | POLLWRNORM))
1435		if (wpipe->pipe_present != PIPE_ACTIVE ||
1436		    (wpipe->pipe_state & PIPE_EOF) ||
1437		    (((wpipe->pipe_state & PIPE_DIRECTW) == 0) &&
1438		     ((wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt) >= PIPE_BUF ||
1439			 wpipe->pipe_buffer.size == 0)))
1440			revents |= events & (POLLOUT | POLLWRNORM);
1441
1442	levents = events &
1443	    (POLLIN | POLLINIGNEOF | POLLPRI | POLLRDNORM | POLLRDBAND);
1444	if (rpipe->pipe_state & PIPE_NAMED && fp->f_flag & FREAD && levents &&
1445	    fp->f_seqcount == rpipe->pipe_wgen)
1446		events |= POLLINIGNEOF;
1447
1448	if ((events & POLLINIGNEOF) == 0) {
1449		if (rpipe->pipe_state & PIPE_EOF) {
1450			revents |= (events & (POLLIN | POLLRDNORM));
1451			if (wpipe->pipe_present != PIPE_ACTIVE ||
1452			    (wpipe->pipe_state & PIPE_EOF))
1453				revents |= POLLHUP;
1454		}
1455	}
1456
1457	if (revents == 0) {
1458		if (fp->f_flag & FREAD && events & (POLLIN | POLLRDNORM)) {
1459			selrecord(td, &rpipe->pipe_sel);
1460			if (SEL_WAITING(&rpipe->pipe_sel))
1461				rpipe->pipe_state |= PIPE_SEL;
1462		}
1463
1464		if (fp->f_flag & FWRITE && events & (POLLOUT | POLLWRNORM)) {
1465			selrecord(td, &wpipe->pipe_sel);
1466			if (SEL_WAITING(&wpipe->pipe_sel))
1467				wpipe->pipe_state |= PIPE_SEL;
1468		}
1469	}
1470#ifdef MAC
1471locked_error:
1472#endif
1473	PIPE_UNLOCK(rpipe);
1474
1475	return (revents);
1476}
1477
1478/*
1479 * We shouldn't need locks here as we're doing a read and this should
1480 * be a natural race.
1481 */
1482static int
1483pipe_stat(fp, ub, active_cred, td)
1484	struct file *fp;
1485	struct stat *ub;
1486	struct ucred *active_cred;
1487	struct thread *td;
1488{
1489	struct pipe *pipe;
1490	int new_unr;
1491#ifdef MAC
1492	int error;
1493#endif
1494
1495	pipe = fp->f_data;
1496	PIPE_LOCK(pipe);
1497#ifdef MAC
1498	error = mac_pipe_check_stat(active_cred, pipe->pipe_pair);
1499	if (error) {
1500		PIPE_UNLOCK(pipe);
1501		return (error);
1502	}
1503#endif
1504
1505	/* For named pipes ask the underlying filesystem. */
1506	if (pipe->pipe_state & PIPE_NAMED) {
1507		PIPE_UNLOCK(pipe);
1508		return (vnops.fo_stat(fp, ub, active_cred, td));
1509	}
1510
1511	/*
1512	 * Lazily allocate an inode number for the pipe.  Most pipe
1513	 * users do not call fstat(2) on the pipe, which means that
1514	 * postponing the inode allocation until it is must be
1515	 * returned to userland is useful.  If alloc_unr failed,
1516	 * assign st_ino zero instead of returning an error.
1517	 * Special pipe_ino values:
1518	 *  -1 - not yet initialized;
1519	 *  0  - alloc_unr failed, return 0 as st_ino forever.
1520	 */
1521	if (pipe->pipe_ino == (ino_t)-1) {
1522		new_unr = alloc_unr(pipeino_unr);
1523		if (new_unr != -1)
1524			pipe->pipe_ino = new_unr;
1525		else
1526			pipe->pipe_ino = 0;
1527	}
1528	PIPE_UNLOCK(pipe);
1529
1530	bzero(ub, sizeof(*ub));
1531	ub->st_mode = S_IFIFO;
1532	ub->st_blksize = PAGE_SIZE;
1533	if (pipe->pipe_state & PIPE_DIRECTW)
1534		ub->st_size = pipe->pipe_map.cnt;
1535	else
1536		ub->st_size = pipe->pipe_buffer.cnt;
1537	ub->st_blocks = (ub->st_size + ub->st_blksize - 1) / ub->st_blksize;
1538	ub->st_atim = pipe->pipe_atime;
1539	ub->st_mtim = pipe->pipe_mtime;
1540	ub->st_ctim = pipe->pipe_ctime;
1541	ub->st_uid = fp->f_cred->cr_uid;
1542	ub->st_gid = fp->f_cred->cr_gid;
1543	ub->st_dev = pipedev_ino;
1544	ub->st_ino = pipe->pipe_ino;
1545	/*
1546	 * Left as 0: st_nlink, st_rdev, st_flags, st_gen.
1547	 */
1548	return (0);
1549}
1550
1551/* ARGSUSED */
1552static int
1553pipe_close(fp, td)
1554	struct file *fp;
1555	struct thread *td;
1556{
1557
1558	if (fp->f_vnode != NULL)
1559		return vnops.fo_close(fp, td);
1560	fp->f_ops = &badfileops;
1561	pipe_dtor(fp->f_data);
1562	fp->f_data = NULL;
1563	return (0);
1564}
1565
1566static int
1567pipe_chmod(struct file *fp, mode_t mode, struct ucred *active_cred, struct thread *td)
1568{
1569	struct pipe *cpipe;
1570	int error;
1571
1572	cpipe = fp->f_data;
1573	if (cpipe->pipe_state & PIPE_NAMED)
1574		error = vn_chmod(fp, mode, active_cred, td);
1575	else
1576		error = invfo_chmod(fp, mode, active_cred, td);
1577	return (error);
1578}
1579
1580static int
1581pipe_chown(fp, uid, gid, active_cred, td)
1582	struct file *fp;
1583	uid_t uid;
1584	gid_t gid;
1585	struct ucred *active_cred;
1586	struct thread *td;
1587{
1588	struct pipe *cpipe;
1589	int error;
1590
1591	cpipe = fp->f_data;
1592	if (cpipe->pipe_state & PIPE_NAMED)
1593		error = vn_chown(fp, uid, gid, active_cred, td);
1594	else
1595		error = invfo_chown(fp, uid, gid, active_cred, td);
1596	return (error);
1597}
1598
1599static void
1600pipe_free_kmem(cpipe)
1601	struct pipe *cpipe;
1602{
1603
1604	KASSERT(!mtx_owned(PIPE_MTX(cpipe)),
1605	    ("pipe_free_kmem: pipe mutex locked"));
1606
1607	if (cpipe->pipe_buffer.buffer != NULL) {
1608		atomic_subtract_long(&amountpipekva, cpipe->pipe_buffer.size);
1609		vm_map_remove(pipe_map,
1610		    (vm_offset_t)cpipe->pipe_buffer.buffer,
1611		    (vm_offset_t)cpipe->pipe_buffer.buffer + cpipe->pipe_buffer.size);
1612		cpipe->pipe_buffer.buffer = NULL;
1613	}
1614#ifndef PIPE_NODIRECT
1615	{
1616		cpipe->pipe_map.cnt = 0;
1617		cpipe->pipe_map.pos = 0;
1618		cpipe->pipe_map.npages = 0;
1619	}
1620#endif
1621}
1622
1623/*
1624 * shutdown the pipe
1625 */
1626static void
1627pipeclose(cpipe)
1628	struct pipe *cpipe;
1629{
1630	struct pipepair *pp;
1631	struct pipe *ppipe;
1632
1633	KASSERT(cpipe != NULL, ("pipeclose: cpipe == NULL"));
1634
1635	PIPE_LOCK(cpipe);
1636	pipelock(cpipe, 0);
1637	pp = cpipe->pipe_pair;
1638
1639	pipeselwakeup(cpipe);
1640
1641	/*
1642	 * If the other side is blocked, wake it up saying that
1643	 * we want to close it down.
1644	 */
1645	cpipe->pipe_state |= PIPE_EOF;
1646	while (cpipe->pipe_busy) {
1647		wakeup(cpipe);
1648		cpipe->pipe_state |= PIPE_WANT;
1649		pipeunlock(cpipe);
1650		msleep(cpipe, PIPE_MTX(cpipe), PRIBIO, "pipecl", 0);
1651		pipelock(cpipe, 0);
1652	}
1653
1654
1655	/*
1656	 * Disconnect from peer, if any.
1657	 */
1658	ppipe = cpipe->pipe_peer;
1659	if (ppipe->pipe_present == PIPE_ACTIVE) {
1660		pipeselwakeup(ppipe);
1661
1662		ppipe->pipe_state |= PIPE_EOF;
1663		wakeup(ppipe);
1664		KNOTE_LOCKED(&ppipe->pipe_sel.si_note, 0);
1665	}
1666
1667	/*
1668	 * Mark this endpoint as free.  Release kmem resources.  We
1669	 * don't mark this endpoint as unused until we've finished
1670	 * doing that, or the pipe might disappear out from under
1671	 * us.
1672	 */
1673	PIPE_UNLOCK(cpipe);
1674	pipe_free_kmem(cpipe);
1675	PIPE_LOCK(cpipe);
1676	cpipe->pipe_present = PIPE_CLOSING;
1677	pipeunlock(cpipe);
1678
1679	/*
1680	 * knlist_clear() may sleep dropping the PIPE_MTX. Set the
1681	 * PIPE_FINALIZED, that allows other end to free the
1682	 * pipe_pair, only after the knotes are completely dismantled.
1683	 */
1684	knlist_clear(&cpipe->pipe_sel.si_note, 1);
1685	cpipe->pipe_present = PIPE_FINALIZED;
1686	seldrain(&cpipe->pipe_sel);
1687	knlist_destroy(&cpipe->pipe_sel.si_note);
1688
1689	/*
1690	 * If both endpoints are now closed, release the memory for the
1691	 * pipe pair.  If not, unlock.
1692	 */
1693	if (ppipe->pipe_present == PIPE_FINALIZED) {
1694		PIPE_UNLOCK(cpipe);
1695#ifdef MAC
1696		mac_pipe_destroy(pp);
1697#endif
1698		uma_zfree(pipe_zone, cpipe->pipe_pair);
1699	} else
1700		PIPE_UNLOCK(cpipe);
1701}
1702
1703/*ARGSUSED*/
1704static int
1705pipe_kqfilter(struct file *fp, struct knote *kn)
1706{
1707	struct pipe *cpipe;
1708
1709	/*
1710	 * If a filter is requested that is not supported by this file
1711	 * descriptor, don't return an error, but also don't ever generate an
1712	 * event.
1713	 */
1714	if ((kn->kn_filter == EVFILT_READ) && !(fp->f_flag & FREAD)) {
1715		kn->kn_fop = &pipe_nfiltops;
1716		return (0);
1717	}
1718	if ((kn->kn_filter == EVFILT_WRITE) && !(fp->f_flag & FWRITE)) {
1719		kn->kn_fop = &pipe_nfiltops;
1720		return (0);
1721	}
1722	cpipe = fp->f_data;
1723	PIPE_LOCK(cpipe);
1724	switch (kn->kn_filter) {
1725	case EVFILT_READ:
1726		kn->kn_fop = &pipe_rfiltops;
1727		break;
1728	case EVFILT_WRITE:
1729		kn->kn_fop = &pipe_wfiltops;
1730		if (cpipe->pipe_peer->pipe_present != PIPE_ACTIVE) {
1731			/* other end of pipe has been closed */
1732			PIPE_UNLOCK(cpipe);
1733			return (EPIPE);
1734		}
1735		cpipe = PIPE_PEER(cpipe);
1736		break;
1737	default:
1738		PIPE_UNLOCK(cpipe);
1739		return (EINVAL);
1740	}
1741
1742	kn->kn_hook = cpipe;
1743	knlist_add(&cpipe->pipe_sel.si_note, kn, 1);
1744	PIPE_UNLOCK(cpipe);
1745	return (0);
1746}
1747
1748static void
1749filt_pipedetach(struct knote *kn)
1750{
1751	struct pipe *cpipe = kn->kn_hook;
1752
1753	PIPE_LOCK(cpipe);
1754	knlist_remove(&cpipe->pipe_sel.si_note, kn, 1);
1755	PIPE_UNLOCK(cpipe);
1756}
1757
1758/*ARGSUSED*/
1759static int
1760filt_piperead(struct knote *kn, long hint)
1761{
1762	struct pipe *rpipe = kn->kn_hook;
1763	struct pipe *wpipe = rpipe->pipe_peer;
1764	int ret;
1765
1766	PIPE_LOCK(rpipe);
1767	kn->kn_data = rpipe->pipe_buffer.cnt;
1768	if ((kn->kn_data == 0) && (rpipe->pipe_state & PIPE_DIRECTW))
1769		kn->kn_data = rpipe->pipe_map.cnt;
1770
1771	if ((rpipe->pipe_state & PIPE_EOF) ||
1772	    wpipe->pipe_present != PIPE_ACTIVE ||
1773	    (wpipe->pipe_state & PIPE_EOF)) {
1774		kn->kn_flags |= EV_EOF;
1775		PIPE_UNLOCK(rpipe);
1776		return (1);
1777	}
1778	ret = kn->kn_data > 0;
1779	PIPE_UNLOCK(rpipe);
1780	return ret;
1781}
1782
1783/*ARGSUSED*/
1784static int
1785filt_pipewrite(struct knote *kn, long hint)
1786{
1787	struct pipe *wpipe;
1788
1789	wpipe = kn->kn_hook;
1790	PIPE_LOCK(wpipe);
1791	if (wpipe->pipe_present != PIPE_ACTIVE ||
1792	    (wpipe->pipe_state & PIPE_EOF)) {
1793		kn->kn_data = 0;
1794		kn->kn_flags |= EV_EOF;
1795		PIPE_UNLOCK(wpipe);
1796		return (1);
1797	}
1798	kn->kn_data = (wpipe->pipe_buffer.size > 0) ?
1799	    (wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt) : PIPE_BUF;
1800	if (wpipe->pipe_state & PIPE_DIRECTW)
1801		kn->kn_data = 0;
1802
1803	PIPE_UNLOCK(wpipe);
1804	return (kn->kn_data >= PIPE_BUF);
1805}
1806
1807static void
1808filt_pipedetach_notsup(struct knote *kn)
1809{
1810
1811}
1812
1813static int
1814filt_pipenotsup(struct knote *kn, long hint)
1815{
1816
1817	return (0);
1818}
1819