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