xref: /freebsd/sys/kern/sys_pipe.c (revision 13ccadd4b00cd6944ff3e60bee50aa629a769016)
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/uio.h>
67 
68 #include <vm/vm.h>
69 #include <vm/vm_prot.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_ioctl __P((struct file *fp, u_long cmd, caddr_t data, struct proc *p));
98 
99 static struct fileops pipeops =
100     { pipe_read, pipe_write, pipe_ioctl, pipe_poll, pipe_close };
101 
102 /*
103  * Default pipe buffer size(s), this can be kind-of large now because pipe
104  * space is pageable.  The pipe code will try to maintain locality of
105  * reference for performance reasons, so small amounts of outstanding I/O
106  * will not wipe the cache.
107  */
108 #define MINPIPESIZE (PIPE_SIZE/3)
109 #define MAXPIPESIZE (2*PIPE_SIZE/3)
110 
111 /*
112  * Maximum amount of kva for pipes -- this is kind-of a soft limit, but
113  * is there so that on large systems, we don't exhaust it.
114  */
115 #define MAXPIPEKVA (8*1024*1024)
116 
117 /*
118  * Limit for direct transfers, we cannot, of course limit
119  * the amount of kva for pipes in general though.
120  */
121 #define LIMITPIPEKVA (16*1024*1024)
122 
123 /*
124  * Limit the number of "big" pipes
125  */
126 #define LIMITBIGPIPES	32
127 static int nbigpipe;
128 
129 static int amountpipekva;
130 
131 static void pipeclose __P((struct pipe *cpipe));
132 static void pipeinit __P((struct pipe *cpipe));
133 static __inline int pipelock __P((struct pipe *cpipe, int catch));
134 static __inline void pipeunlock __P((struct pipe *cpipe));
135 static __inline void pipeselwakeup __P((struct pipe *cpipe));
136 #ifndef PIPE_NODIRECT
137 static int pipe_build_write_buffer __P((struct pipe *wpipe, struct uio *uio));
138 static void pipe_destroy_write_buffer __P((struct pipe *wpipe));
139 static int pipe_direct_write __P((struct pipe *wpipe, struct uio *uio));
140 static void pipe_clone_write_buffer __P((struct pipe *wpipe));
141 #endif
142 static void pipespace __P((struct pipe *cpipe));
143 
144 static vm_zone_t pipe_zone;
145 
146 /*
147  * The pipe system call for the DTYPE_PIPE type of pipes
148  */
149 
150 /* ARGSUSED */
151 int
152 pipe(p, uap)
153 	struct proc *p;
154 	struct pipe_args /* {
155 		int	dummy;
156 	} */ *uap;
157 {
158 	register struct filedesc *fdp = p->p_fd;
159 	struct file *rf, *wf;
160 	struct pipe *rpipe, *wpipe;
161 	int fd, error;
162 
163 	if (pipe_zone == NULL)
164 		pipe_zone = zinit("PIPE", sizeof (struct pipe), 0, 0, 4);
165 
166 	rpipe = zalloc( pipe_zone);
167 	pipeinit(rpipe);
168 	rpipe->pipe_state |= PIPE_DIRECTOK;
169 	wpipe = zalloc( pipe_zone);
170 	pipeinit(wpipe);
171 	wpipe->pipe_state |= PIPE_DIRECTOK;
172 
173 	error = falloc(p, &rf, &fd);
174 	if (error)
175 		goto free2;
176 	p->p_retval[0] = fd;
177 	rf->f_flag = FREAD | FWRITE;
178 	rf->f_type = DTYPE_PIPE;
179 	rf->f_data = (caddr_t)rpipe;
180 	rf->f_ops = &pipeops;
181 	error = falloc(p, &wf, &fd);
182 	if (error)
183 		goto free3;
184 	wf->f_flag = FREAD | FWRITE;
185 	wf->f_type = DTYPE_PIPE;
186 	wf->f_data = (caddr_t)wpipe;
187 	wf->f_ops = &pipeops;
188 	p->p_retval[1] = fd;
189 
190 	rpipe->pipe_peer = wpipe;
191 	wpipe->pipe_peer = rpipe;
192 
193 	return (0);
194 free3:
195 	fdp->fd_ofiles[p->p_retval[0]] = 0;
196 	ffree(rf);
197 free2:
198 	(void)pipeclose(wpipe);
199 	(void)pipeclose(rpipe);
200 	return (error);
201 }
202 
203 /*
204  * Allocate kva for pipe circular buffer, the space is pageable
205  */
206 static void
207 pipespace(cpipe)
208 	struct pipe *cpipe;
209 {
210 	int npages, error;
211 
212 	npages = round_page(cpipe->pipe_buffer.size)/PAGE_SIZE;
213 	/*
214 	 * Create an object, I don't like the idea of paging to/from
215 	 * kernel_object.
216 	 * XXX -- minor change needed here for NetBSD/OpenBSD VM systems.
217 	 */
218 	cpipe->pipe_buffer.object = vm_object_allocate(OBJT_DEFAULT, npages);
219 	cpipe->pipe_buffer.buffer = (caddr_t) vm_map_min(kernel_map);
220 
221 	/*
222 	 * Insert the object into the kernel map, and allocate kva for it.
223 	 * The map entry is, by default, pageable.
224 	 * XXX -- minor change needed here for NetBSD/OpenBSD VM systems.
225 	 */
226 	error = vm_map_find(kernel_map, cpipe->pipe_buffer.object, 0,
227 		(vm_offset_t *) &cpipe->pipe_buffer.buffer,
228 		cpipe->pipe_buffer.size, 1,
229 		VM_PROT_ALL, VM_PROT_ALL, 0);
230 
231 	if (error != KERN_SUCCESS)
232 		panic("pipeinit: cannot allocate pipe -- out of kvm -- code = %d", error);
233 	amountpipekva += cpipe->pipe_buffer.size;
234 }
235 
236 /*
237  * initialize and allocate VM and memory for pipe
238  */
239 static void
240 pipeinit(cpipe)
241 	struct pipe *cpipe;
242 {
243 
244 	cpipe->pipe_buffer.in = 0;
245 	cpipe->pipe_buffer.out = 0;
246 	cpipe->pipe_buffer.cnt = 0;
247 	cpipe->pipe_buffer.size = PIPE_SIZE;
248 
249 	/* Buffer kva gets dynamically allocated */
250 	cpipe->pipe_buffer.buffer = NULL;
251 	/* cpipe->pipe_buffer.object = invalid */
252 
253 	cpipe->pipe_state = 0;
254 	cpipe->pipe_peer = NULL;
255 	cpipe->pipe_busy = 0;
256 	getnanotime(&cpipe->pipe_ctime);
257 	cpipe->pipe_atime = cpipe->pipe_ctime;
258 	cpipe->pipe_mtime = cpipe->pipe_ctime;
259 	bzero(&cpipe->pipe_sel, sizeof cpipe->pipe_sel);
260 
261 #ifndef PIPE_NODIRECT
262 	/*
263 	 * pipe data structure initializations to support direct pipe I/O
264 	 */
265 	cpipe->pipe_map.cnt = 0;
266 	cpipe->pipe_map.kva = 0;
267 	cpipe->pipe_map.pos = 0;
268 	cpipe->pipe_map.npages = 0;
269 	/* cpipe->pipe_map.ms[] = invalid */
270 #endif
271 }
272 
273 
274 /*
275  * lock a pipe for I/O, blocking other access
276  */
277 static __inline int
278 pipelock(cpipe, catch)
279 	struct pipe *cpipe;
280 	int catch;
281 {
282 	int error;
283 	while (cpipe->pipe_state & PIPE_LOCK) {
284 		cpipe->pipe_state |= PIPE_LWANT;
285 		if ((error = tsleep( cpipe,
286 			catch?(PRIBIO|PCATCH):PRIBIO, "pipelk", 0)) != 0) {
287 			return error;
288 		}
289 	}
290 	cpipe->pipe_state |= PIPE_LOCK;
291 	return 0;
292 }
293 
294 /*
295  * unlock a pipe I/O lock
296  */
297 static __inline void
298 pipeunlock(cpipe)
299 	struct pipe *cpipe;
300 {
301 	cpipe->pipe_state &= ~PIPE_LOCK;
302 	if (cpipe->pipe_state & PIPE_LWANT) {
303 		cpipe->pipe_state &= ~PIPE_LWANT;
304 		wakeup(cpipe);
305 	}
306 }
307 
308 static __inline void
309 pipeselwakeup(cpipe)
310 	struct pipe *cpipe;
311 {
312 	if (cpipe->pipe_state & PIPE_SEL) {
313 		cpipe->pipe_state &= ~PIPE_SEL;
314 		selwakeup(&cpipe->pipe_sel);
315 	}
316 	if ((cpipe->pipe_state & PIPE_ASYNC) && cpipe->pipe_sigio)
317 		pgsigio(cpipe->pipe_sigio, SIGIO, 0);
318 }
319 
320 /* ARGSUSED */
321 static int
322 pipe_read(fp, uio, cred, flags, p)
323 	struct file *fp;
324 	struct uio *uio;
325 	struct ucred *cred;
326 	struct proc *p;
327 	int flags;
328 {
329 
330 	struct pipe *rpipe = (struct pipe *) fp->f_data;
331 	int error;
332 	int nread = 0;
333 	u_int size;
334 
335 	++rpipe->pipe_busy;
336 	error = pipelock(rpipe, 1);
337 	if (error)
338 		goto unlocked_error;
339 
340 	while (uio->uio_resid) {
341 		/*
342 		 * normal pipe buffer receive
343 		 */
344 		if (rpipe->pipe_buffer.cnt > 0) {
345 			size = rpipe->pipe_buffer.size - rpipe->pipe_buffer.out;
346 			if (size > rpipe->pipe_buffer.cnt)
347 				size = rpipe->pipe_buffer.cnt;
348 			if (size > (u_int) uio->uio_resid)
349 				size = (u_int) uio->uio_resid;
350 
351 			error = uiomove(&rpipe->pipe_buffer.buffer[rpipe->pipe_buffer.out],
352 					size, uio);
353 			if (error) {
354 				break;
355 			}
356 			rpipe->pipe_buffer.out += size;
357 			if (rpipe->pipe_buffer.out >= rpipe->pipe_buffer.size)
358 				rpipe->pipe_buffer.out = 0;
359 
360 			rpipe->pipe_buffer.cnt -= size;
361 
362 			/*
363 			 * If there is no more to read in the pipe, reset
364 			 * its pointers to the beginning.  This improves
365 			 * cache hit stats.
366 			 */
367 			if (rpipe->pipe_buffer.cnt == 0) {
368 				rpipe->pipe_buffer.in = 0;
369 				rpipe->pipe_buffer.out = 0;
370 			}
371 			nread += size;
372 #ifndef PIPE_NODIRECT
373 		/*
374 		 * Direct copy, bypassing a kernel buffer.
375 		 */
376 		} else if ((size = rpipe->pipe_map.cnt) &&
377 			   (rpipe->pipe_state & PIPE_DIRECTW)) {
378 			caddr_t	va;
379 			if (size > (u_int) uio->uio_resid)
380 				size = (u_int) uio->uio_resid;
381 
382 			va = (caddr_t) rpipe->pipe_map.kva + rpipe->pipe_map.pos;
383 			error = uiomove(va, size, uio);
384 			if (error)
385 				break;
386 			nread += size;
387 			rpipe->pipe_map.pos += size;
388 			rpipe->pipe_map.cnt -= size;
389 			if (rpipe->pipe_map.cnt == 0) {
390 				rpipe->pipe_state &= ~PIPE_DIRECTW;
391 				wakeup(rpipe);
392 			}
393 #endif
394 		} else {
395 			/*
396 			 * detect EOF condition
397 			 */
398 			if (rpipe->pipe_state & PIPE_EOF) {
399 				/* XXX error = ? */
400 				break;
401 			}
402 
403 			/*
404 			 * If the "write-side" has been blocked, wake it up now.
405 			 */
406 			if (rpipe->pipe_state & PIPE_WANTW) {
407 				rpipe->pipe_state &= ~PIPE_WANTW;
408 				wakeup(rpipe);
409 			}
410 
411 			/*
412 			 * Break if some data was read.
413 			 */
414 			if (nread > 0)
415 				break;
416 
417 			/*
418 			 * Unlock the pipe buffer for our remaining processing.  We
419 			 * will either break out with an error or we will sleep and
420 			 * relock to loop.
421 			 */
422 			pipeunlock(rpipe);
423 
424 			/*
425 			 * Handle non-blocking mode operation or
426 			 * wait for more data.
427 			 */
428 			if (fp->f_flag & FNONBLOCK)
429 				error = EAGAIN;
430 			else {
431 				rpipe->pipe_state |= PIPE_WANTR;
432 				if ((error = tsleep(rpipe, PRIBIO|PCATCH, "piperd", 0)) == 0)
433 					error = pipelock(rpipe, 1);
434 			}
435 			if (error)
436 				goto unlocked_error;
437 		}
438 	}
439 	pipeunlock(rpipe);
440 
441 	if (error == 0)
442 		getnanotime(&rpipe->pipe_atime);
443 unlocked_error:
444 	--rpipe->pipe_busy;
445 
446 	/*
447 	 * PIPE_WANT processing only makes sense if pipe_busy is 0.
448 	 */
449 	if ((rpipe->pipe_busy == 0) && (rpipe->pipe_state & PIPE_WANT)) {
450 		rpipe->pipe_state &= ~(PIPE_WANT|PIPE_WANTW);
451 		wakeup(rpipe);
452 	} else if (rpipe->pipe_buffer.cnt < MINPIPESIZE) {
453 		/*
454 		 * Handle write blocking hysteresis.
455 		 */
456 		if (rpipe->pipe_state & PIPE_WANTW) {
457 			rpipe->pipe_state &= ~PIPE_WANTW;
458 			wakeup(rpipe);
459 		}
460 	}
461 
462 	if ((rpipe->pipe_buffer.size - rpipe->pipe_buffer.cnt) >= PIPE_BUF)
463 		pipeselwakeup(rpipe);
464 
465 	return error;
466 }
467 
468 #ifndef PIPE_NODIRECT
469 /*
470  * Map the sending processes' buffer into kernel space and wire it.
471  * This is similar to a physical write operation.
472  */
473 static int
474 pipe_build_write_buffer(wpipe, uio)
475 	struct pipe *wpipe;
476 	struct uio *uio;
477 {
478 	u_int size;
479 	int i;
480 	vm_offset_t addr, endaddr, paddr;
481 
482 	size = (u_int) uio->uio_iov->iov_len;
483 	if (size > wpipe->pipe_buffer.size)
484 		size = wpipe->pipe_buffer.size;
485 
486 	endaddr = round_page((vm_offset_t)uio->uio_iov->iov_base + size);
487 	for(i = 0, addr = trunc_page((vm_offset_t)uio->uio_iov->iov_base);
488 		addr < endaddr;
489 		addr += PAGE_SIZE, i+=1) {
490 
491 		vm_page_t m;
492 
493 		vm_fault_quick( (caddr_t) addr, VM_PROT_READ);
494 		paddr = pmap_kextract(addr);
495 		if (!paddr) {
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 		/* XXX perhaps they need to be contiguous to be atomic? */
804 		if ((space < uio->uio_resid) && (orig_resid <= PIPE_BUF))
805 			space = 0;
806 
807 		if (space > 0 && (wpipe->pipe_buffer.cnt < PIPE_SIZE)) {
808 			/*
809 			 * This set the maximum transfer as a segment of
810 			 * the buffer.
811 			 */
812 			int size = wpipe->pipe_buffer.size - wpipe->pipe_buffer.in;
813 			/*
814 			 * space is the size left in the buffer
815 			 */
816 			if (size > space)
817 				size = space;
818 			/*
819 			 * now limit it to the size of the uio transfer
820 			 */
821 			if (size > uio->uio_resid)
822 				size = uio->uio_resid;
823 			if ((error = pipelock(wpipe,1)) == 0) {
824 				/*
825 				 * It is possible for a direct write to
826 				 * slip in on us... handle it here...
827 				 */
828 				if (wpipe->pipe_state & PIPE_DIRECTW) {
829 					pipeunlock(wpipe);
830 					goto retrywrite;
831 				}
832 				error = uiomove( &wpipe->pipe_buffer.buffer[wpipe->pipe_buffer.in],
833 					size, uio);
834 				pipeunlock(wpipe);
835 			}
836 			if (error)
837 				break;
838 
839 			wpipe->pipe_buffer.in += size;
840 			if (wpipe->pipe_buffer.in >= wpipe->pipe_buffer.size)
841 				wpipe->pipe_buffer.in = 0;
842 
843 			wpipe->pipe_buffer.cnt += size;
844 		} else {
845 			/*
846 			 * If the "read-side" has been blocked, wake it up now.
847 			 */
848 			if (wpipe->pipe_state & PIPE_WANTR) {
849 				wpipe->pipe_state &= ~PIPE_WANTR;
850 				wakeup(wpipe);
851 			}
852 
853 			/*
854 			 * don't block on non-blocking I/O
855 			 */
856 			if (fp->f_flag & FNONBLOCK) {
857 				error = EAGAIN;
858 				break;
859 			}
860 
861 			/*
862 			 * We have no more space and have something to offer,
863 			 * wake up select/poll.
864 			 */
865 			pipeselwakeup(wpipe);
866 
867 			wpipe->pipe_state |= PIPE_WANTW;
868 			if ((error = tsleep(wpipe, (PRIBIO+1)|PCATCH, "pipewr", 0)) != 0) {
869 				break;
870 			}
871 			/*
872 			 * If read side wants to go away, we just issue a signal
873 			 * to ourselves.
874 			 */
875 			if (wpipe->pipe_state & PIPE_EOF) {
876 				error = EPIPE;
877 				break;
878 			}
879 		}
880 	}
881 
882 	--wpipe->pipe_busy;
883 	if ((wpipe->pipe_busy == 0) &&
884 		(wpipe->pipe_state & PIPE_WANT)) {
885 		wpipe->pipe_state &= ~(PIPE_WANT|PIPE_WANTR);
886 		wakeup(wpipe);
887 	} else if (wpipe->pipe_buffer.cnt > 0) {
888 		/*
889 		 * If we have put any characters in the buffer, we wake up
890 		 * the reader.
891 		 */
892 		if (wpipe->pipe_state & PIPE_WANTR) {
893 			wpipe->pipe_state &= ~PIPE_WANTR;
894 			wakeup(wpipe);
895 		}
896 	}
897 
898 	/*
899 	 * Don't return EPIPE if I/O was successful
900 	 */
901 	if ((wpipe->pipe_buffer.cnt == 0) &&
902 		(uio->uio_resid == 0) &&
903 		(error == EPIPE))
904 		error = 0;
905 
906 	if (error == 0)
907 		getnanotime(&wpipe->pipe_mtime);
908 
909 	/*
910 	 * We have something to offer,
911 	 * wake up select/poll.
912 	 */
913 	if (wpipe->pipe_buffer.cnt)
914 		pipeselwakeup(wpipe);
915 
916 	return error;
917 }
918 
919 /*
920  * we implement a very minimal set of ioctls for compatibility with sockets.
921  */
922 int
923 pipe_ioctl(fp, cmd, data, p)
924 	struct file *fp;
925 	u_long cmd;
926 	register caddr_t data;
927 	struct proc *p;
928 {
929 	register struct pipe *mpipe = (struct pipe *)fp->f_data;
930 
931 	switch (cmd) {
932 
933 	case FIONBIO:
934 		return (0);
935 
936 	case FIOASYNC:
937 		if (*(int *)data) {
938 			mpipe->pipe_state |= PIPE_ASYNC;
939 		} else {
940 			mpipe->pipe_state &= ~PIPE_ASYNC;
941 		}
942 		return (0);
943 
944 	case FIONREAD:
945 		if (mpipe->pipe_state & PIPE_DIRECTW)
946 			*(int *)data = mpipe->pipe_map.cnt;
947 		else
948 			*(int *)data = mpipe->pipe_buffer.cnt;
949 		return (0);
950 
951 	case FIOSETOWN:
952 		return (fsetown(*(int *)data, &mpipe->pipe_sigio));
953 
954 	case FIOGETOWN:
955 		*(int *)data = fgetown(mpipe->pipe_sigio);
956 		return (0);
957 
958 	/* This is deprecated, FIOSETOWN should be used instead. */
959 	case TIOCSPGRP:
960 		return (fsetown(-(*(int *)data), &mpipe->pipe_sigio));
961 
962 	/* This is deprecated, FIOGETOWN should be used instead. */
963 	case TIOCGPGRP:
964 		*(int *)data = -fgetown(mpipe->pipe_sigio);
965 		return (0);
966 
967 	}
968 	return (ENOTTY);
969 }
970 
971 int
972 pipe_poll(fp, events, cred, p)
973 	struct file *fp;
974 	int events;
975 	struct ucred *cred;
976 	struct proc *p;
977 {
978 	register struct pipe *rpipe = (struct pipe *)fp->f_data;
979 	struct pipe *wpipe;
980 	int revents = 0;
981 
982 	wpipe = rpipe->pipe_peer;
983 	if (events & (POLLIN | POLLRDNORM))
984 		if ((rpipe->pipe_state & PIPE_DIRECTW) ||
985 		    (rpipe->pipe_buffer.cnt > 0) ||
986 		    (rpipe->pipe_state & PIPE_EOF))
987 			revents |= events & (POLLIN | POLLRDNORM);
988 
989 	if (events & (POLLOUT | POLLWRNORM))
990 		if (wpipe == NULL || (wpipe->pipe_state & PIPE_EOF) ||
991 		    (((wpipe->pipe_state & PIPE_DIRECTW) == 0) &&
992 		     (wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt) >= PIPE_BUF))
993 			revents |= events & (POLLOUT | POLLWRNORM);
994 
995 	if ((rpipe->pipe_state & PIPE_EOF) ||
996 	    (wpipe == NULL) ||
997 	    (wpipe->pipe_state & PIPE_EOF))
998 		revents |= POLLHUP;
999 
1000 	if (revents == 0) {
1001 		if (events & (POLLIN | POLLRDNORM)) {
1002 			selrecord(p, &rpipe->pipe_sel);
1003 			rpipe->pipe_state |= PIPE_SEL;
1004 		}
1005 
1006 		if (events & (POLLOUT | POLLWRNORM)) {
1007 			selrecord(p, &wpipe->pipe_sel);
1008 			wpipe->pipe_state |= PIPE_SEL;
1009 		}
1010 	}
1011 
1012 	return (revents);
1013 }
1014 
1015 int
1016 pipe_stat(pipe, ub)
1017 	register struct pipe *pipe;
1018 	register struct stat *ub;
1019 {
1020 	bzero((caddr_t)ub, sizeof (*ub));
1021 	ub->st_mode = S_IFIFO;
1022 	ub->st_blksize = pipe->pipe_buffer.size;
1023 	ub->st_size = pipe->pipe_buffer.cnt;
1024 	ub->st_blocks = (ub->st_size + ub->st_blksize - 1) / ub->st_blksize;
1025 	ub->st_atimespec = pipe->pipe_atime;
1026 	ub->st_mtimespec = pipe->pipe_mtime;
1027 	ub->st_ctimespec = pipe->pipe_ctime;
1028 	/*
1029 	 * Left as 0: st_dev, st_ino, st_nlink, st_uid, st_gid, st_rdev,
1030 	 * st_flags, st_gen.
1031 	 * XXX (st_dev, st_ino) should be unique.
1032 	 */
1033 	return 0;
1034 }
1035 
1036 /* ARGSUSED */
1037 static int
1038 pipe_close(fp, p)
1039 	struct file *fp;
1040 	struct proc *p;
1041 {
1042 	struct pipe *cpipe = (struct pipe *)fp->f_data;
1043 
1044 	fp->f_ops = &badfileops;
1045 	fp->f_data = NULL;
1046 	funsetown(cpipe->pipe_sigio);
1047 	pipeclose(cpipe);
1048 	return 0;
1049 }
1050 
1051 /*
1052  * shutdown the pipe
1053  */
1054 static void
1055 pipeclose(cpipe)
1056 	struct pipe *cpipe;
1057 {
1058 	struct pipe *ppipe;
1059 	if (cpipe) {
1060 
1061 		pipeselwakeup(cpipe);
1062 
1063 		/*
1064 		 * If the other side is blocked, wake it up saying that
1065 		 * we want to close it down.
1066 		 */
1067 		while (cpipe->pipe_busy) {
1068 			wakeup(cpipe);
1069 			cpipe->pipe_state |= PIPE_WANT|PIPE_EOF;
1070 			tsleep(cpipe, PRIBIO, "pipecl", 0);
1071 		}
1072 
1073 		/*
1074 		 * Disconnect from peer
1075 		 */
1076 		if ((ppipe = cpipe->pipe_peer) != NULL) {
1077 			pipeselwakeup(ppipe);
1078 
1079 			ppipe->pipe_state |= PIPE_EOF;
1080 			wakeup(ppipe);
1081 			ppipe->pipe_peer = NULL;
1082 		}
1083 
1084 		/*
1085 		 * free resources
1086 		 */
1087 		if (cpipe->pipe_buffer.buffer) {
1088 			if (cpipe->pipe_buffer.size > PIPE_SIZE)
1089 				--nbigpipe;
1090 			amountpipekva -= cpipe->pipe_buffer.size;
1091 			kmem_free(kernel_map,
1092 				(vm_offset_t)cpipe->pipe_buffer.buffer,
1093 				cpipe->pipe_buffer.size);
1094 		}
1095 #ifndef PIPE_NODIRECT
1096 		if (cpipe->pipe_map.kva) {
1097 			amountpipekva -= cpipe->pipe_buffer.size + PAGE_SIZE;
1098 			kmem_free(kernel_map,
1099 				cpipe->pipe_map.kva,
1100 				cpipe->pipe_buffer.size + PAGE_SIZE);
1101 		}
1102 #endif
1103 		zfree(pipe_zone, cpipe);
1104 	}
1105 }
1106