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