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