sys_pipe.c revision 76756
1/*
2 * Copyright (c) 1996 John S. Dyson
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice immediately at the beginning of the file, without modification,
10 *    this list of conditions, and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 * 3. Absolutely no warranty of function or purpose is made by the author
15 *    John S. Dyson.
16 * 4. Modifications may be freely made to this file if the above conditions
17 *    are met.
18 *
19 * $FreeBSD: head/sys/kern/sys_pipe.c 76756 2001-05-17 18:22:58Z alfred $
20 */
21
22/*
23 * This file contains a high-performance replacement for the socket-based
24 * pipes scheme originally used in FreeBSD/4.4Lite.  It does not support
25 * all features of sockets, but does do everything that pipes normally
26 * do.
27 */
28
29/*
30 * This code has two modes of operation, a small write mode and a large
31 * write mode.  The small write mode acts like conventional pipes with
32 * a kernel buffer.  If the buffer is less than PIPE_MINDIRECT, then the
33 * "normal" pipe buffering is done.  If the buffer is between PIPE_MINDIRECT
34 * and PIPE_SIZE in size, it is fully mapped and wired into the kernel, and
35 * the receiving process can copy it directly from the pages in the sending
36 * process.
37 *
38 * If the sending process receives a signal, it is possible that it will
39 * go away, and certainly its address space can change, because control
40 * is returned back to the user-mode side.  In that case, the pipe code
41 * arranges to copy the buffer supplied by the user process, to a pageable
42 * kernel buffer, and the receiving process will grab the data from the
43 * pageable kernel buffer.  Since signals don't happen all that often,
44 * the copy operation is normally eliminated.
45 *
46 * The constant PIPE_MINDIRECT is chosen to make sure that buffering will
47 * happen for small transfers so that the system will not spend all of
48 * its time context switching.  PIPE_SIZE is constrained by the
49 * amount of kernel virtual memory.
50 */
51
52#include <sys/param.h>
53#include <sys/systm.h>
54#include <sys/fcntl.h>
55#include <sys/file.h>
56#include <sys/filedesc.h>
57#include <sys/filio.h>
58#include <sys/lock.h>
59#include <sys/ttycom.h>
60#include <sys/stat.h>
61#include <sys/poll.h>
62#include <sys/selinfo.h>
63#include <sys/signalvar.h>
64#include <sys/sysproto.h>
65#include <sys/pipe.h>
66#include <sys/proc.h>
67#include <sys/vnode.h>
68#include <sys/uio.h>
69#include <sys/event.h>
70
71#include <vm/vm.h>
72#include <vm/vm_param.h>
73#include <vm/vm_object.h>
74#include <vm/vm_kern.h>
75#include <vm/vm_extern.h>
76#include <vm/pmap.h>
77#include <vm/vm_map.h>
78#include <vm/vm_page.h>
79#include <vm/vm_zone.h>
80
81/*
82 * Use this define if you want to disable *fancy* VM things.  Expect an
83 * approx 30% decrease in transfer rate.  This could be useful for
84 * NetBSD or OpenBSD.
85 */
86/* #define PIPE_NODIRECT */
87
88/*
89 * interfaces to the outside world
90 */
91static int pipe_read __P((struct file *fp, struct uio *uio,
92		struct ucred *cred, int flags, struct proc *p));
93static int pipe_write __P((struct file *fp, struct uio *uio,
94		struct ucred *cred, int flags, struct proc *p));
95static int pipe_close __P((struct file *fp, struct proc *p));
96static int pipe_poll __P((struct file *fp, int events, struct ucred *cred,
97		struct proc *p));
98static int pipe_kqfilter __P((struct file *fp, struct knote *kn));
99static int pipe_stat __P((struct file *fp, struct stat *sb, struct proc *p));
100static int pipe_ioctl __P((struct file *fp, u_long cmd, caddr_t data, struct proc *p));
101
102static struct fileops pipeops = {
103	pipe_read, pipe_write, pipe_ioctl, pipe_poll, pipe_kqfilter,
104	pipe_stat, pipe_close
105};
106
107static void	filt_pipedetach(struct knote *kn);
108static int	filt_piperead(struct knote *kn, long hint);
109static int	filt_pipewrite(struct knote *kn, long hint);
110
111static struct filterops pipe_rfiltops =
112	{ 1, NULL, filt_pipedetach, filt_piperead };
113static struct filterops pipe_wfiltops =
114	{ 1, NULL, filt_pipedetach, filt_pipewrite };
115
116
117/*
118 * Default pipe buffer size(s), this can be kind-of large now because pipe
119 * space is pageable.  The pipe code will try to maintain locality of
120 * reference for performance reasons, so small amounts of outstanding I/O
121 * will not wipe the cache.
122 */
123#define MINPIPESIZE (PIPE_SIZE/3)
124#define MAXPIPESIZE (2*PIPE_SIZE/3)
125
126/*
127 * Maximum amount of kva for pipes -- this is kind-of a soft limit, but
128 * is there so that on large systems, we don't exhaust it.
129 */
130#define MAXPIPEKVA (8*1024*1024)
131
132/*
133 * Limit for direct transfers, we cannot, of course limit
134 * the amount of kva for pipes in general though.
135 */
136#define LIMITPIPEKVA (16*1024*1024)
137
138/*
139 * Limit the number of "big" pipes
140 */
141#define LIMITBIGPIPES	32
142static int nbigpipe;
143
144static int amountpipekva;
145
146static void pipeclose __P((struct pipe *cpipe));
147static void pipe_free_kmem __P((struct pipe *cpipe));
148static int pipe_create __P((struct pipe **cpipep));
149static __inline int pipelock __P((struct pipe *cpipe, int catch));
150static __inline void pipeunlock __P((struct pipe *cpipe));
151static __inline void pipeselwakeup __P((struct pipe *cpipe));
152#ifndef PIPE_NODIRECT
153static int pipe_build_write_buffer __P((struct pipe *wpipe, struct uio *uio));
154static void pipe_destroy_write_buffer __P((struct pipe *wpipe));
155static int pipe_direct_write __P((struct pipe *wpipe, struct uio *uio));
156static void pipe_clone_write_buffer __P((struct pipe *wpipe));
157#endif
158static int pipespace __P((struct pipe *cpipe, int size));
159
160static vm_zone_t pipe_zone;
161
162/*
163 * The pipe system call for the DTYPE_PIPE type of pipes
164 */
165
166/* ARGSUSED */
167int
168pipe(p, uap)
169	struct proc *p;
170	struct pipe_args /* {
171		int	dummy;
172	} */ *uap;
173{
174	struct filedesc *fdp = p->p_fd;
175	struct file *rf, *wf;
176	struct pipe *rpipe, *wpipe;
177	int fd, error;
178
179	if (pipe_zone == NULL)
180		pipe_zone = zinit("PIPE", sizeof (struct pipe), 0, 0, 4);
181
182	rpipe = wpipe = NULL;
183	if (pipe_create(&rpipe) || pipe_create(&wpipe)) {
184		pipeclose(rpipe);
185		pipeclose(wpipe);
186		return (ENFILE);
187	}
188
189	rpipe->pipe_state |= PIPE_DIRECTOK;
190	wpipe->pipe_state |= PIPE_DIRECTOK;
191
192	error = falloc(p, &rf, &fd);
193	if (error) {
194		pipeclose(rpipe);
195		pipeclose(wpipe);
196		return (error);
197	}
198	fhold(rf);
199	p->p_retval[0] = fd;
200
201	/*
202	 * Warning: once we've gotten past allocation of the fd for the
203	 * read-side, we can only drop the read side via fdrop() in order
204	 * to avoid races against processes which manage to dup() the read
205	 * side while we are blocked trying to allocate the write side.
206	 */
207	rf->f_flag = FREAD | FWRITE;
208	rf->f_type = DTYPE_PIPE;
209	rf->f_data = (caddr_t)rpipe;
210	rf->f_ops = &pipeops;
211	error = falloc(p, &wf, &fd);
212	if (error) {
213		if (fdp->fd_ofiles[p->p_retval[0]] == rf) {
214			fdp->fd_ofiles[p->p_retval[0]] = NULL;
215			fdrop(rf, p);
216		}
217		fdrop(rf, p);
218		/* rpipe has been closed by fdrop(). */
219		pipeclose(wpipe);
220		return (error);
221	}
222	wf->f_flag = FREAD | FWRITE;
223	wf->f_type = DTYPE_PIPE;
224	wf->f_data = (caddr_t)wpipe;
225	wf->f_ops = &pipeops;
226	p->p_retval[1] = fd;
227
228	rpipe->pipe_peer = wpipe;
229	wpipe->pipe_peer = rpipe;
230	fdrop(rf, p);
231
232	return (0);
233}
234
235/*
236 * Allocate kva for pipe circular buffer, the space is pageable
237 * This routine will 'realloc' the size of a pipe safely, if it fails
238 * it will retain the old buffer.
239 * If it fails it will return ENOMEM.
240 */
241static int
242pipespace(cpipe, size)
243	struct pipe *cpipe;
244	int size;
245{
246	struct vm_object *object;
247	caddr_t buffer;
248	int npages, error;
249
250	npages = round_page(size)/PAGE_SIZE;
251	/*
252	 * Create an object, I don't like the idea of paging to/from
253	 * kernel_object.
254	 * XXX -- minor change needed here for NetBSD/OpenBSD VM systems.
255	 */
256	object = vm_object_allocate(OBJT_DEFAULT, npages);
257	buffer = (caddr_t) vm_map_min(kernel_map);
258
259	/*
260	 * Insert the object into the kernel map, and allocate kva for it.
261	 * The map entry is, by default, pageable.
262	 * XXX -- minor change needed here for NetBSD/OpenBSD VM systems.
263	 */
264	error = vm_map_find(kernel_map, object, 0,
265		(vm_offset_t *) &buffer, size, 1,
266		VM_PROT_ALL, VM_PROT_ALL, 0);
267
268	if (error != KERN_SUCCESS) {
269		vm_object_deallocate(object);
270		return (ENOMEM);
271	}
272
273	/* free old resources if we're resizing */
274	pipe_free_kmem(cpipe);
275	cpipe->pipe_buffer.object = object;
276	cpipe->pipe_buffer.buffer = buffer;
277	cpipe->pipe_buffer.size = size;
278	cpipe->pipe_buffer.in = 0;
279	cpipe->pipe_buffer.out = 0;
280	cpipe->pipe_buffer.cnt = 0;
281	amountpipekva += cpipe->pipe_buffer.size;
282	return (0);
283}
284
285/*
286 * initialize and allocate VM and memory for pipe
287 */
288static int
289pipe_create(cpipep)
290	struct pipe **cpipep;
291{
292	struct pipe *cpipe;
293	int error;
294
295	*cpipep = zalloc(pipe_zone);
296	if (*cpipep == NULL)
297		return (ENOMEM);
298
299	cpipe = *cpipep;
300
301	/* so pipespace()->pipe_free_kmem() doesn't follow junk pointer */
302	cpipe->pipe_buffer.object = NULL;
303#ifndef PIPE_NODIRECT
304	cpipe->pipe_map.kva = NULL;
305#endif
306	/*
307	 * protect so pipeclose() doesn't follow a junk pointer
308	 * if pipespace() fails.
309	 */
310	bzero(&cpipe->pipe_sel, sizeof(cpipe->pipe_sel));
311	cpipe->pipe_state = 0;
312	cpipe->pipe_peer = NULL;
313	cpipe->pipe_busy = 0;
314
315#ifndef PIPE_NODIRECT
316	/*
317	 * pipe data structure initializations to support direct pipe I/O
318	 */
319	cpipe->pipe_map.cnt = 0;
320	cpipe->pipe_map.kva = 0;
321	cpipe->pipe_map.pos = 0;
322	cpipe->pipe_map.npages = 0;
323	/* cpipe->pipe_map.ms[] = invalid */
324#endif
325
326	error = pipespace(cpipe, PIPE_SIZE);
327	if (error) {
328		return (error);
329	}
330
331	vfs_timestamp(&cpipe->pipe_ctime);
332	cpipe->pipe_atime = cpipe->pipe_ctime;
333	cpipe->pipe_mtime = cpipe->pipe_ctime;
334
335	return (0);
336}
337
338
339/*
340 * lock a pipe for I/O, blocking other access
341 */
342static __inline int
343pipelock(cpipe, catch)
344	struct pipe *cpipe;
345	int catch;
346{
347	int error;
348
349	while (cpipe->pipe_state & PIPE_LOCK) {
350		cpipe->pipe_state |= PIPE_LWANT;
351		if ((error = tsleep( cpipe,
352			catch?(PRIBIO|PCATCH):PRIBIO, "pipelk", 0)) != 0) {
353			return error;
354		}
355	}
356	cpipe->pipe_state |= PIPE_LOCK;
357	return 0;
358}
359
360/*
361 * unlock a pipe I/O lock
362 */
363static __inline void
364pipeunlock(cpipe)
365	struct pipe *cpipe;
366{
367
368	cpipe->pipe_state &= ~PIPE_LOCK;
369	if (cpipe->pipe_state & PIPE_LWANT) {
370		cpipe->pipe_state &= ~PIPE_LWANT;
371		wakeup(cpipe);
372	}
373}
374
375static __inline void
376pipeselwakeup(cpipe)
377	struct pipe *cpipe;
378{
379
380	if (cpipe->pipe_state & PIPE_SEL) {
381		cpipe->pipe_state &= ~PIPE_SEL;
382		selwakeup(&cpipe->pipe_sel);
383	}
384	if ((cpipe->pipe_state & PIPE_ASYNC) && cpipe->pipe_sigio)
385		pgsigio(cpipe->pipe_sigio, SIGIO, 0);
386	KNOTE(&cpipe->pipe_sel.si_note, 0);
387}
388
389/* ARGSUSED */
390static int
391pipe_read(fp, uio, cred, flags, p)
392	struct file *fp;
393	struct uio *uio;
394	struct ucred *cred;
395	struct proc *p;
396	int flags;
397{
398	struct pipe *rpipe = (struct pipe *) fp->f_data;
399	int error;
400	int nread = 0;
401	u_int size;
402
403	++rpipe->pipe_busy;
404	error = pipelock(rpipe, 1);
405	if (error)
406		goto unlocked_error;
407
408	while (uio->uio_resid) {
409		/*
410		 * normal pipe buffer receive
411		 */
412		if (rpipe->pipe_buffer.cnt > 0) {
413			size = rpipe->pipe_buffer.size - rpipe->pipe_buffer.out;
414			if (size > rpipe->pipe_buffer.cnt)
415				size = rpipe->pipe_buffer.cnt;
416			if (size > (u_int) uio->uio_resid)
417				size = (u_int) uio->uio_resid;
418
419			error = uiomove(&rpipe->pipe_buffer.buffer[rpipe->pipe_buffer.out],
420					size, uio);
421			if (error) {
422				break;
423			}
424			rpipe->pipe_buffer.out += size;
425			if (rpipe->pipe_buffer.out >= rpipe->pipe_buffer.size)
426				rpipe->pipe_buffer.out = 0;
427
428			rpipe->pipe_buffer.cnt -= size;
429
430			/*
431			 * If there is no more to read in the pipe, reset
432			 * its pointers to the beginning.  This improves
433			 * cache hit stats.
434			 */
435			if (rpipe->pipe_buffer.cnt == 0) {
436				rpipe->pipe_buffer.in = 0;
437				rpipe->pipe_buffer.out = 0;
438			}
439			nread += size;
440#ifndef PIPE_NODIRECT
441		/*
442		 * Direct copy, bypassing a kernel buffer.
443		 */
444		} else if ((size = rpipe->pipe_map.cnt) &&
445			   (rpipe->pipe_state & PIPE_DIRECTW)) {
446			caddr_t	va;
447			if (size > (u_int) uio->uio_resid)
448				size = (u_int) uio->uio_resid;
449
450			va = (caddr_t) rpipe->pipe_map.kva + rpipe->pipe_map.pos;
451			error = uiomove(va, size, uio);
452			if (error)
453				break;
454			nread += size;
455			rpipe->pipe_map.pos += size;
456			rpipe->pipe_map.cnt -= size;
457			if (rpipe->pipe_map.cnt == 0) {
458				rpipe->pipe_state &= ~PIPE_DIRECTW;
459				wakeup(rpipe);
460			}
461#endif
462		} else {
463			/*
464			 * detect EOF condition
465			 */
466			if (rpipe->pipe_state & PIPE_EOF) {
467				/* XXX error = ? */
468				break;
469			}
470
471			/*
472			 * If the "write-side" has been blocked, wake it up now.
473			 */
474			if (rpipe->pipe_state & PIPE_WANTW) {
475				rpipe->pipe_state &= ~PIPE_WANTW;
476				wakeup(rpipe);
477			}
478
479			/*
480			 * Break if some data was read.
481			 */
482			if (nread > 0)
483				break;
484
485			/*
486			 * Unlock the pipe buffer for our remaining processing.  We
487			 * will either break out with an error or we will sleep and
488			 * relock to loop.
489			 */
490			pipeunlock(rpipe);
491
492			/*
493			 * Handle non-blocking mode operation or
494			 * wait for more data.
495			 */
496			if (fp->f_flag & FNONBLOCK)
497				error = EAGAIN;
498			else {
499				rpipe->pipe_state |= PIPE_WANTR;
500				if ((error = tsleep(rpipe, PRIBIO|PCATCH, "piperd", 0)) == 0)
501					error = pipelock(rpipe, 1);
502			}
503			if (error)
504				goto unlocked_error;
505		}
506	}
507	pipeunlock(rpipe);
508
509	if (error == 0)
510		vfs_timestamp(&rpipe->pipe_atime);
511unlocked_error:
512	--rpipe->pipe_busy;
513
514	/*
515	 * PIPE_WANT processing only makes sense if pipe_busy is 0.
516	 */
517	if ((rpipe->pipe_busy == 0) && (rpipe->pipe_state & PIPE_WANT)) {
518		rpipe->pipe_state &= ~(PIPE_WANT|PIPE_WANTW);
519		wakeup(rpipe);
520	} else if (rpipe->pipe_buffer.cnt < MINPIPESIZE) {
521		/*
522		 * Handle write blocking hysteresis.
523		 */
524		if (rpipe->pipe_state & PIPE_WANTW) {
525			rpipe->pipe_state &= ~PIPE_WANTW;
526			wakeup(rpipe);
527		}
528	}
529
530	if ((rpipe->pipe_buffer.size - rpipe->pipe_buffer.cnt) >= PIPE_BUF)
531		pipeselwakeup(rpipe);
532
533	return error;
534}
535
536#ifndef PIPE_NODIRECT
537/*
538 * Map the sending processes' buffer into kernel space and wire it.
539 * This is similar to a physical write operation.
540 */
541static int
542pipe_build_write_buffer(wpipe, uio)
543	struct pipe *wpipe;
544	struct uio *uio;
545{
546	u_int size;
547	int i;
548	vm_offset_t addr, endaddr, paddr;
549
550	size = (u_int) uio->uio_iov->iov_len;
551	if (size > wpipe->pipe_buffer.size)
552		size = wpipe->pipe_buffer.size;
553
554	endaddr = round_page((vm_offset_t)uio->uio_iov->iov_base + size);
555	for(i = 0, addr = trunc_page((vm_offset_t)uio->uio_iov->iov_base);
556		addr < endaddr;
557		addr += PAGE_SIZE, i+=1) {
558
559		vm_page_t m;
560
561		if (vm_fault_quick((caddr_t)addr, VM_PROT_READ) < 0 ||
562		    (paddr = pmap_kextract(addr)) == 0) {
563			int j;
564			for(j=0;j<i;j++)
565				vm_page_unwire(wpipe->pipe_map.ms[j], 1);
566			return EFAULT;
567		}
568
569		m = PHYS_TO_VM_PAGE(paddr);
570		vm_page_wire(m);
571		wpipe->pipe_map.ms[i] = m;
572	}
573
574/*
575 * set up the control block
576 */
577	wpipe->pipe_map.npages = i;
578	wpipe->pipe_map.pos = ((vm_offset_t) uio->uio_iov->iov_base) & PAGE_MASK;
579	wpipe->pipe_map.cnt = size;
580
581/*
582 * and map the buffer
583 */
584	if (wpipe->pipe_map.kva == 0) {
585		/*
586		 * We need to allocate space for an extra page because the
587		 * address range might (will) span pages at times.
588		 */
589		wpipe->pipe_map.kva = kmem_alloc_pageable(kernel_map,
590			wpipe->pipe_buffer.size + PAGE_SIZE);
591		amountpipekva += wpipe->pipe_buffer.size + PAGE_SIZE;
592	}
593	pmap_qenter(wpipe->pipe_map.kva, wpipe->pipe_map.ms,
594		wpipe->pipe_map.npages);
595
596/*
597 * and update the uio data
598 */
599
600	uio->uio_iov->iov_len -= size;
601	uio->uio_iov->iov_base += size;
602	if (uio->uio_iov->iov_len == 0)
603		uio->uio_iov++;
604	uio->uio_resid -= size;
605	uio->uio_offset += size;
606	return 0;
607}
608
609/*
610 * unmap and unwire the process buffer
611 */
612static void
613pipe_destroy_write_buffer(wpipe)
614struct pipe *wpipe;
615{
616	int i;
617
618	if (wpipe->pipe_map.kva) {
619		pmap_qremove(wpipe->pipe_map.kva, wpipe->pipe_map.npages);
620
621		if (amountpipekva > MAXPIPEKVA) {
622			vm_offset_t kva = wpipe->pipe_map.kva;
623			wpipe->pipe_map.kva = 0;
624			kmem_free(kernel_map, kva,
625				wpipe->pipe_buffer.size + PAGE_SIZE);
626			amountpipekva -= wpipe->pipe_buffer.size + PAGE_SIZE;
627		}
628	}
629	for (i=0;i<wpipe->pipe_map.npages;i++)
630		vm_page_unwire(wpipe->pipe_map.ms[i], 1);
631}
632
633/*
634 * In the case of a signal, the writing process might go away.  This
635 * code copies the data into the circular buffer so that the source
636 * pages can be freed without loss of data.
637 */
638static void
639pipe_clone_write_buffer(wpipe)
640	struct pipe *wpipe;
641{
642	int size;
643	int pos;
644
645	size = wpipe->pipe_map.cnt;
646	pos = wpipe->pipe_map.pos;
647	bcopy((caddr_t) wpipe->pipe_map.kva+pos,
648			(caddr_t) wpipe->pipe_buffer.buffer,
649			size);
650
651	wpipe->pipe_buffer.in = size;
652	wpipe->pipe_buffer.out = 0;
653	wpipe->pipe_buffer.cnt = size;
654	wpipe->pipe_state &= ~PIPE_DIRECTW;
655
656	pipe_destroy_write_buffer(wpipe);
657}
658
659/*
660 * This implements the pipe buffer write mechanism.  Note that only
661 * a direct write OR a normal pipe write can be pending at any given time.
662 * If there are any characters in the pipe buffer, the direct write will
663 * be deferred until the receiving process grabs all of the bytes from
664 * the pipe buffer.  Then the direct mapping write is set-up.
665 */
666static int
667pipe_direct_write(wpipe, uio)
668	struct pipe *wpipe;
669	struct uio *uio;
670{
671	int error;
672
673retry:
674	while (wpipe->pipe_state & PIPE_DIRECTW) {
675		if ( wpipe->pipe_state & PIPE_WANTR) {
676			wpipe->pipe_state &= ~PIPE_WANTR;
677			wakeup(wpipe);
678		}
679		wpipe->pipe_state |= PIPE_WANTW;
680		error = tsleep(wpipe,
681				PRIBIO|PCATCH, "pipdww", 0);
682		if (error)
683			goto error1;
684		if (wpipe->pipe_state & PIPE_EOF) {
685			error = EPIPE;
686			goto error1;
687		}
688	}
689	wpipe->pipe_map.cnt = 0;	/* transfer not ready yet */
690	if (wpipe->pipe_buffer.cnt > 0) {
691		if ( wpipe->pipe_state & PIPE_WANTR) {
692			wpipe->pipe_state &= ~PIPE_WANTR;
693			wakeup(wpipe);
694		}
695
696		wpipe->pipe_state |= PIPE_WANTW;
697		error = tsleep(wpipe,
698				PRIBIO|PCATCH, "pipdwc", 0);
699		if (error)
700			goto error1;
701		if (wpipe->pipe_state & PIPE_EOF) {
702			error = EPIPE;
703			goto error1;
704		}
705		goto retry;
706	}
707
708	wpipe->pipe_state |= PIPE_DIRECTW;
709
710	error = pipe_build_write_buffer(wpipe, uio);
711	if (error) {
712		wpipe->pipe_state &= ~PIPE_DIRECTW;
713		goto error1;
714	}
715
716	error = 0;
717	while (!error && (wpipe->pipe_state & PIPE_DIRECTW)) {
718		if (wpipe->pipe_state & PIPE_EOF) {
719			pipelock(wpipe, 0);
720			pipe_destroy_write_buffer(wpipe);
721			pipeunlock(wpipe);
722			pipeselwakeup(wpipe);
723			error = EPIPE;
724			goto error1;
725		}
726		if (wpipe->pipe_state & PIPE_WANTR) {
727			wpipe->pipe_state &= ~PIPE_WANTR;
728			wakeup(wpipe);
729		}
730		pipeselwakeup(wpipe);
731		error = tsleep(wpipe, PRIBIO|PCATCH, "pipdwt", 0);
732	}
733
734	pipelock(wpipe,0);
735	if (wpipe->pipe_state & PIPE_DIRECTW) {
736		/*
737		 * this bit of trickery substitutes a kernel buffer for
738		 * the process that might be going away.
739		 */
740		pipe_clone_write_buffer(wpipe);
741	} else {
742		pipe_destroy_write_buffer(wpipe);
743	}
744	pipeunlock(wpipe);
745	return error;
746
747error1:
748	wakeup(wpipe);
749	return error;
750}
751#endif
752
753static int
754pipe_write(fp, uio, cred, flags, p)
755	struct file *fp;
756	struct uio *uio;
757	struct ucred *cred;
758	struct proc *p;
759	int flags;
760{
761	int error = 0;
762	int orig_resid;
763	struct pipe *wpipe, *rpipe;
764
765	rpipe = (struct pipe *) fp->f_data;
766	wpipe = rpipe->pipe_peer;
767
768	/*
769	 * detect loss of pipe read side, issue SIGPIPE if lost.
770	 */
771	if ((wpipe == NULL) || (wpipe->pipe_state & PIPE_EOF)) {
772		return EPIPE;
773	}
774
775	/*
776	 * If it is advantageous to resize the pipe buffer, do
777	 * so.
778	 */
779	if ((uio->uio_resid > PIPE_SIZE) &&
780		(nbigpipe < LIMITBIGPIPES) &&
781		(wpipe->pipe_state & PIPE_DIRECTW) == 0 &&
782		(wpipe->pipe_buffer.size <= PIPE_SIZE) &&
783		(wpipe->pipe_buffer.cnt == 0)) {
784
785		if ((error = pipelock(wpipe,1)) == 0) {
786			if (pipespace(wpipe, BIG_PIPE_SIZE) == 0)
787				nbigpipe++;
788			pipeunlock(wpipe);
789		} else {
790			return error;
791		}
792	}
793
794	KASSERT(wpipe->pipe_buffer.buffer != NULL, ("pipe buffer gone"));
795
796	++wpipe->pipe_busy;
797	orig_resid = uio->uio_resid;
798	while (uio->uio_resid) {
799		int space;
800#ifndef PIPE_NODIRECT
801		/*
802		 * If the transfer is large, we can gain performance if
803		 * we do process-to-process copies directly.
804		 * If the write is non-blocking, we don't use the
805		 * direct write mechanism.
806		 *
807		 * The direct write mechanism will detect the reader going
808		 * away on us.
809		 */
810		if ((uio->uio_iov->iov_len >= PIPE_MINDIRECT) &&
811		    (fp->f_flag & FNONBLOCK) == 0 &&
812			(wpipe->pipe_map.kva || (amountpipekva < LIMITPIPEKVA)) &&
813			(uio->uio_iov->iov_len >= PIPE_MINDIRECT)) {
814			error = pipe_direct_write( wpipe, uio);
815			if (error) {
816				break;
817			}
818			continue;
819		}
820#endif
821
822		/*
823		 * Pipe buffered writes cannot be coincidental with
824		 * direct writes.  We wait until the currently executing
825		 * direct write is completed before we start filling the
826		 * pipe buffer.  We break out if a signal occurs or the
827		 * reader goes away.
828		 */
829	retrywrite:
830		while (wpipe->pipe_state & PIPE_DIRECTW) {
831			if (wpipe->pipe_state & PIPE_WANTR) {
832				wpipe->pipe_state &= ~PIPE_WANTR;
833				wakeup(wpipe);
834			}
835			error = tsleep(wpipe, PRIBIO|PCATCH, "pipbww", 0);
836			if (wpipe->pipe_state & PIPE_EOF)
837				break;
838			if (error)
839				break;
840		}
841		if (wpipe->pipe_state & PIPE_EOF) {
842			error = EPIPE;
843			break;
844		}
845
846		space = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
847
848		/* Writes of size <= PIPE_BUF must be atomic. */
849		if ((space < uio->uio_resid) && (orig_resid <= PIPE_BUF))
850			space = 0;
851
852		if (space > 0 && (wpipe->pipe_buffer.cnt < PIPE_SIZE)) {
853			if ((error = pipelock(wpipe,1)) == 0) {
854				int size;	/* Transfer size */
855				int segsize;	/* first segment to transfer */
856				/*
857				 * It is possible for a direct write to
858				 * slip in on us... handle it here...
859				 */
860				if (wpipe->pipe_state & PIPE_DIRECTW) {
861					pipeunlock(wpipe);
862					goto retrywrite;
863				}
864				/*
865				 * If a process blocked in uiomove, our
866				 * value for space might be bad.
867				 *
868				 * XXX will we be ok if the reader has gone
869				 * away here?
870				 */
871				if (space > wpipe->pipe_buffer.size -
872				    wpipe->pipe_buffer.cnt) {
873					pipeunlock(wpipe);
874					goto retrywrite;
875				}
876
877				/*
878				 * Transfer size is minimum of uio transfer
879				 * and free space in pipe buffer.
880				 */
881				if (space > uio->uio_resid)
882					size = uio->uio_resid;
883				else
884					size = space;
885				/*
886				 * First segment to transfer is minimum of
887				 * transfer size and contiguous space in
888				 * pipe buffer.  If first segment to transfer
889				 * is less than the transfer size, we've got
890				 * a wraparound in the buffer.
891				 */
892				segsize = wpipe->pipe_buffer.size -
893					wpipe->pipe_buffer.in;
894				if (segsize > size)
895					segsize = size;
896
897				/* Transfer first segment */
898
899				error = uiomove(&wpipe->pipe_buffer.buffer[wpipe->pipe_buffer.in],
900						segsize, uio);
901
902				if (error == 0 && segsize < size) {
903					/*
904					 * Transfer remaining part now, to
905					 * support atomic writes.  Wraparound
906					 * happened.
907					 */
908					if (wpipe->pipe_buffer.in + segsize !=
909					    wpipe->pipe_buffer.size)
910						panic("Expected pipe buffer wraparound disappeared");
911
912					error = uiomove(&wpipe->pipe_buffer.buffer[0],
913							size - segsize, uio);
914				}
915				if (error == 0) {
916					wpipe->pipe_buffer.in += size;
917					if (wpipe->pipe_buffer.in >=
918					    wpipe->pipe_buffer.size) {
919						if (wpipe->pipe_buffer.in != size - segsize + wpipe->pipe_buffer.size)
920							panic("Expected wraparound bad");
921						wpipe->pipe_buffer.in = size - segsize;
922					}
923
924					wpipe->pipe_buffer.cnt += size;
925					if (wpipe->pipe_buffer.cnt > wpipe->pipe_buffer.size)
926						panic("Pipe buffer overflow");
927
928				}
929				pipeunlock(wpipe);
930			}
931			if (error)
932				break;
933
934		} else {
935			/*
936			 * If the "read-side" has been blocked, wake it up now.
937			 */
938			if (wpipe->pipe_state & PIPE_WANTR) {
939				wpipe->pipe_state &= ~PIPE_WANTR;
940				wakeup(wpipe);
941			}
942
943			/*
944			 * don't block on non-blocking I/O
945			 */
946			if (fp->f_flag & FNONBLOCK) {
947				error = EAGAIN;
948				break;
949			}
950
951			/*
952			 * We have no more space and have something to offer,
953			 * wake up select/poll.
954			 */
955			pipeselwakeup(wpipe);
956
957			wpipe->pipe_state |= PIPE_WANTW;
958			if ((error = tsleep(wpipe, (PRIBIO+1)|PCATCH, "pipewr", 0)) != 0) {
959				break;
960			}
961			/*
962			 * If read side wants to go away, we just issue a signal
963			 * to ourselves.
964			 */
965			if (wpipe->pipe_state & PIPE_EOF) {
966				error = EPIPE;
967				break;
968			}
969		}
970	}
971
972	--wpipe->pipe_busy;
973	if ((wpipe->pipe_busy == 0) &&
974		(wpipe->pipe_state & PIPE_WANT)) {
975		wpipe->pipe_state &= ~(PIPE_WANT|PIPE_WANTR);
976		wakeup(wpipe);
977	} else if (wpipe->pipe_buffer.cnt > 0) {
978		/*
979		 * If we have put any characters in the buffer, we wake up
980		 * the reader.
981		 */
982		if (wpipe->pipe_state & PIPE_WANTR) {
983			wpipe->pipe_state &= ~PIPE_WANTR;
984			wakeup(wpipe);
985		}
986	}
987
988	/*
989	 * Don't return EPIPE if I/O was successful
990	 */
991	if ((wpipe->pipe_buffer.cnt == 0) &&
992		(uio->uio_resid == 0) &&
993		(error == EPIPE))
994		error = 0;
995
996	if (error == 0)
997		vfs_timestamp(&wpipe->pipe_mtime);
998
999	/*
1000	 * We have something to offer,
1001	 * wake up select/poll.
1002	 */
1003	if (wpipe->pipe_buffer.cnt)
1004		pipeselwakeup(wpipe);
1005
1006	return error;
1007}
1008
1009/*
1010 * we implement a very minimal set of ioctls for compatibility with sockets.
1011 */
1012int
1013pipe_ioctl(fp, cmd, data, p)
1014	struct file *fp;
1015	u_long cmd;
1016	caddr_t data;
1017	struct proc *p;
1018{
1019	struct pipe *mpipe = (struct pipe *)fp->f_data;
1020
1021	switch (cmd) {
1022
1023	case FIONBIO:
1024		return (0);
1025
1026	case FIOASYNC:
1027		if (*(int *)data) {
1028			mpipe->pipe_state |= PIPE_ASYNC;
1029		} else {
1030			mpipe->pipe_state &= ~PIPE_ASYNC;
1031		}
1032		return (0);
1033
1034	case FIONREAD:
1035		if (mpipe->pipe_state & PIPE_DIRECTW)
1036			*(int *)data = mpipe->pipe_map.cnt;
1037		else
1038			*(int *)data = mpipe->pipe_buffer.cnt;
1039		return (0);
1040
1041	case FIOSETOWN:
1042		return (fsetown(*(int *)data, &mpipe->pipe_sigio));
1043
1044	case FIOGETOWN:
1045		*(int *)data = fgetown(mpipe->pipe_sigio);
1046		return (0);
1047
1048	/* This is deprecated, FIOSETOWN should be used instead. */
1049	case TIOCSPGRP:
1050		return (fsetown(-(*(int *)data), &mpipe->pipe_sigio));
1051
1052	/* This is deprecated, FIOGETOWN should be used instead. */
1053	case TIOCGPGRP:
1054		*(int *)data = -fgetown(mpipe->pipe_sigio);
1055		return (0);
1056
1057	}
1058	return (ENOTTY);
1059}
1060
1061int
1062pipe_poll(fp, events, cred, p)
1063	struct file *fp;
1064	int events;
1065	struct ucred *cred;
1066	struct proc *p;
1067{
1068	struct pipe *rpipe = (struct pipe *)fp->f_data;
1069	struct pipe *wpipe;
1070	int revents = 0;
1071
1072	wpipe = rpipe->pipe_peer;
1073	if (events & (POLLIN | POLLRDNORM))
1074		if ((rpipe->pipe_state & PIPE_DIRECTW) ||
1075		    (rpipe->pipe_buffer.cnt > 0) ||
1076		    (rpipe->pipe_state & PIPE_EOF))
1077			revents |= events & (POLLIN | POLLRDNORM);
1078
1079	if (events & (POLLOUT | POLLWRNORM))
1080		if (wpipe == NULL || (wpipe->pipe_state & PIPE_EOF) ||
1081		    (((wpipe->pipe_state & PIPE_DIRECTW) == 0) &&
1082		     (wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt) >= PIPE_BUF))
1083			revents |= events & (POLLOUT | POLLWRNORM);
1084
1085	if ((rpipe->pipe_state & PIPE_EOF) ||
1086	    (wpipe == NULL) ||
1087	    (wpipe->pipe_state & PIPE_EOF))
1088		revents |= POLLHUP;
1089
1090	if (revents == 0) {
1091		if (events & (POLLIN | POLLRDNORM)) {
1092			selrecord(p, &rpipe->pipe_sel);
1093			rpipe->pipe_state |= PIPE_SEL;
1094		}
1095
1096		if (events & (POLLOUT | POLLWRNORM)) {
1097			selrecord(p, &wpipe->pipe_sel);
1098			wpipe->pipe_state |= PIPE_SEL;
1099		}
1100	}
1101
1102	return (revents);
1103}
1104
1105static int
1106pipe_stat(fp, ub, p)
1107	struct file *fp;
1108	struct stat *ub;
1109	struct proc *p;
1110{
1111	struct pipe *pipe = (struct pipe *)fp->f_data;
1112
1113	bzero((caddr_t)ub, sizeof (*ub));
1114	ub->st_mode = S_IFIFO;
1115	ub->st_blksize = pipe->pipe_buffer.size;
1116	ub->st_size = pipe->pipe_buffer.cnt;
1117	ub->st_blocks = (ub->st_size + ub->st_blksize - 1) / ub->st_blksize;
1118	ub->st_atimespec = pipe->pipe_atime;
1119	ub->st_mtimespec = pipe->pipe_mtime;
1120	ub->st_ctimespec = pipe->pipe_ctime;
1121	ub->st_uid = fp->f_cred->cr_uid;
1122	ub->st_gid = fp->f_cred->cr_gid;
1123	/*
1124	 * Left as 0: st_dev, st_ino, st_nlink, st_rdev, st_flags, st_gen.
1125	 * XXX (st_dev, st_ino) should be unique.
1126	 */
1127	return 0;
1128}
1129
1130/* ARGSUSED */
1131static int
1132pipe_close(fp, p)
1133	struct file *fp;
1134	struct proc *p;
1135{
1136	struct pipe *cpipe = (struct pipe *)fp->f_data;
1137
1138	fp->f_ops = &badfileops;
1139	fp->f_data = NULL;
1140	funsetown(cpipe->pipe_sigio);
1141	pipeclose(cpipe);
1142	return 0;
1143}
1144
1145static void
1146pipe_free_kmem(cpipe)
1147	struct pipe *cpipe;
1148{
1149
1150	if (cpipe->pipe_buffer.buffer != NULL) {
1151		if (cpipe->pipe_buffer.size > PIPE_SIZE)
1152			--nbigpipe;
1153		amountpipekva -= cpipe->pipe_buffer.size;
1154		kmem_free(kernel_map,
1155			(vm_offset_t)cpipe->pipe_buffer.buffer,
1156			cpipe->pipe_buffer.size);
1157		cpipe->pipe_buffer.buffer = NULL;
1158	}
1159#ifndef PIPE_NODIRECT
1160	if (cpipe->pipe_map.kva != NULL) {
1161		amountpipekva -= cpipe->pipe_buffer.size + PAGE_SIZE;
1162		kmem_free(kernel_map,
1163			cpipe->pipe_map.kva,
1164			cpipe->pipe_buffer.size + PAGE_SIZE);
1165		cpipe->pipe_map.cnt = 0;
1166		cpipe->pipe_map.kva = 0;
1167		cpipe->pipe_map.pos = 0;
1168		cpipe->pipe_map.npages = 0;
1169	}
1170#endif
1171}
1172
1173/*
1174 * shutdown the pipe
1175 */
1176static void
1177pipeclose(cpipe)
1178	struct pipe *cpipe;
1179{
1180	struct pipe *ppipe;
1181
1182	if (cpipe) {
1183
1184		pipeselwakeup(cpipe);
1185
1186		/*
1187		 * If the other side is blocked, wake it up saying that
1188		 * we want to close it down.
1189		 */
1190		while (cpipe->pipe_busy) {
1191			wakeup(cpipe);
1192			cpipe->pipe_state |= PIPE_WANT|PIPE_EOF;
1193			tsleep(cpipe, PRIBIO, "pipecl", 0);
1194		}
1195
1196		/*
1197		 * Disconnect from peer
1198		 */
1199		if ((ppipe = cpipe->pipe_peer) != NULL) {
1200			pipeselwakeup(ppipe);
1201
1202			ppipe->pipe_state |= PIPE_EOF;
1203			wakeup(ppipe);
1204			ppipe->pipe_peer = NULL;
1205		}
1206
1207		/*
1208		 * free resources
1209		 */
1210		pipe_free_kmem(cpipe);
1211		zfree(pipe_zone, cpipe);
1212	}
1213}
1214
1215/*ARGSUSED*/
1216static int
1217pipe_kqfilter(struct file *fp, struct knote *kn)
1218{
1219	struct pipe *rpipe = (struct pipe *)kn->kn_fp->f_data;
1220
1221	switch (kn->kn_filter) {
1222	case EVFILT_READ:
1223		kn->kn_fop = &pipe_rfiltops;
1224		break;
1225	case EVFILT_WRITE:
1226		kn->kn_fop = &pipe_wfiltops;
1227		break;
1228	default:
1229		return (1);
1230	}
1231
1232	SLIST_INSERT_HEAD(&rpipe->pipe_sel.si_note, kn, kn_selnext);
1233	return (0);
1234}
1235
1236static void
1237filt_pipedetach(struct knote *kn)
1238{
1239	struct pipe *rpipe = (struct pipe *)kn->kn_fp->f_data;
1240
1241	SLIST_REMOVE(&rpipe->pipe_sel.si_note, kn, knote, kn_selnext);
1242}
1243
1244/*ARGSUSED*/
1245static int
1246filt_piperead(struct knote *kn, long hint)
1247{
1248	struct pipe *rpipe = (struct pipe *)kn->kn_fp->f_data;
1249	struct pipe *wpipe = rpipe->pipe_peer;
1250
1251	kn->kn_data = rpipe->pipe_buffer.cnt;
1252	if ((kn->kn_data == 0) && (rpipe->pipe_state & PIPE_DIRECTW))
1253		kn->kn_data = rpipe->pipe_map.cnt;
1254
1255	if ((rpipe->pipe_state & PIPE_EOF) ||
1256	    (wpipe == NULL) || (wpipe->pipe_state & PIPE_EOF)) {
1257		kn->kn_flags |= EV_EOF;
1258		return (1);
1259	}
1260	return (kn->kn_data > 0);
1261}
1262
1263/*ARGSUSED*/
1264static int
1265filt_pipewrite(struct knote *kn, long hint)
1266{
1267	struct pipe *rpipe = (struct pipe *)kn->kn_fp->f_data;
1268	struct pipe *wpipe = rpipe->pipe_peer;
1269
1270	if ((wpipe == NULL) || (wpipe->pipe_state & PIPE_EOF)) {
1271		kn->kn_data = 0;
1272		kn->kn_flags |= EV_EOF;
1273		return (1);
1274	}
1275	kn->kn_data = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
1276	if (wpipe->pipe_state & PIPE_DIRECTW)
1277		kn->kn_data = 0;
1278
1279	return (kn->kn_data >= PIPE_BUF);
1280}
1281