xref: /freebsd/sys/kern/sys_pipe.c (revision c678bc4f13a340ad88debe321afd0097db2590cb)
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/fcntl.h>
55 #include <sys/file.h>
56 #include <sys/filedesc.h>
57 #include <sys/filio.h>
58 #include <sys/lock.h>
59 #include <sys/mutex.h>
60 #include <sys/ttycom.h>
61 #include <sys/stat.h>
62 #include <sys/poll.h>
63 #include <sys/selinfo.h>
64 #include <sys/signalvar.h>
65 #include <sys/sysproto.h>
66 #include <sys/pipe.h>
67 #include <sys/proc.h>
68 #include <sys/vnode.h>
69 #include <sys/uio.h>
70 #include <sys/event.h>
71 
72 #include <vm/vm.h>
73 #include <vm/vm_param.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 	mtx_lock(&vm_mtx);
258 	object = vm_object_allocate(OBJT_DEFAULT, npages);
259 	buffer = (caddr_t) vm_map_min(kernel_map);
260 
261 	/*
262 	 * Insert the object into the kernel map, and allocate kva for it.
263 	 * The map entry is, by default, pageable.
264 	 * XXX -- minor change needed here for NetBSD/OpenBSD VM systems.
265 	 */
266 	error = vm_map_find(kernel_map, object, 0,
267 		(vm_offset_t *) &buffer, size, 1,
268 		VM_PROT_ALL, VM_PROT_ALL, 0);
269 
270 	if (error != KERN_SUCCESS) {
271 		vm_object_deallocate(object);
272 		mtx_unlock(&vm_mtx);
273 		return (ENOMEM);
274 	}
275 
276 	/* free old resources if we're resizing */
277 	pipe_free_kmem(cpipe);
278 	mtx_unlock(&vm_mtx);
279 	cpipe->pipe_buffer.object = object;
280 	cpipe->pipe_buffer.buffer = buffer;
281 	cpipe->pipe_buffer.size = size;
282 	cpipe->pipe_buffer.in = 0;
283 	cpipe->pipe_buffer.out = 0;
284 	cpipe->pipe_buffer.cnt = 0;
285 	amountpipekva += cpipe->pipe_buffer.size;
286 	return (0);
287 }
288 
289 /*
290  * initialize and allocate VM and memory for pipe
291  */
292 static int
293 pipe_create(cpipep)
294 	struct pipe **cpipep;
295 {
296 	struct pipe *cpipe;
297 	int error;
298 
299 	*cpipep = zalloc(pipe_zone);
300 	if (*cpipep == NULL)
301 		return (ENOMEM);
302 
303 	cpipe = *cpipep;
304 
305 	/* so pipespace()->pipe_free_kmem() doesn't follow junk pointer */
306 	cpipe->pipe_buffer.object = NULL;
307 #ifndef PIPE_NODIRECT
308 	cpipe->pipe_map.kva = NULL;
309 #endif
310 	/*
311 	 * protect so pipeclose() doesn't follow a junk pointer
312 	 * if pipespace() fails.
313 	 */
314 	bzero(&cpipe->pipe_sel, sizeof(cpipe->pipe_sel));
315 	cpipe->pipe_state = 0;
316 	cpipe->pipe_peer = NULL;
317 	cpipe->pipe_busy = 0;
318 
319 #ifndef PIPE_NODIRECT
320 	/*
321 	 * pipe data structure initializations to support direct pipe I/O
322 	 */
323 	cpipe->pipe_map.cnt = 0;
324 	cpipe->pipe_map.kva = 0;
325 	cpipe->pipe_map.pos = 0;
326 	cpipe->pipe_map.npages = 0;
327 	/* cpipe->pipe_map.ms[] = invalid */
328 #endif
329 
330 	error = pipespace(cpipe, PIPE_SIZE);
331 	if (error)
332 		return (error);
333 
334 	vfs_timestamp(&cpipe->pipe_ctime);
335 	cpipe->pipe_atime = cpipe->pipe_ctime;
336 	cpipe->pipe_mtime = cpipe->pipe_ctime;
337 
338 	return (0);
339 }
340 
341 
342 /*
343  * lock a pipe for I/O, blocking other access
344  */
345 static __inline int
346 pipelock(cpipe, catch)
347 	struct pipe *cpipe;
348 	int catch;
349 {
350 	int error;
351 
352 	while (cpipe->pipe_state & PIPE_LOCK) {
353 		cpipe->pipe_state |= PIPE_LWANT;
354 		error = tsleep(cpipe, catch ? (PRIBIO | PCATCH) : PRIBIO,
355 		    "pipelk", 0);
356 		if (error != 0)
357 			return (error);
358 	}
359 	cpipe->pipe_state |= PIPE_LOCK;
360 	return (0);
361 }
362 
363 /*
364  * unlock a pipe I/O lock
365  */
366 static __inline void
367 pipeunlock(cpipe)
368 	struct pipe *cpipe;
369 {
370 
371 	cpipe->pipe_state &= ~PIPE_LOCK;
372 	if (cpipe->pipe_state & PIPE_LWANT) {
373 		cpipe->pipe_state &= ~PIPE_LWANT;
374 		wakeup(cpipe);
375 	}
376 }
377 
378 static __inline void
379 pipeselwakeup(cpipe)
380 	struct pipe *cpipe;
381 {
382 
383 	if (cpipe->pipe_state & PIPE_SEL) {
384 		cpipe->pipe_state &= ~PIPE_SEL;
385 		selwakeup(&cpipe->pipe_sel);
386 	}
387 	if ((cpipe->pipe_state & PIPE_ASYNC) && cpipe->pipe_sigio)
388 		pgsigio(cpipe->pipe_sigio, SIGIO, 0);
389 	KNOTE(&cpipe->pipe_sel.si_note, 0);
390 }
391 
392 /* ARGSUSED */
393 static int
394 pipe_read(fp, uio, cred, flags, p)
395 	struct file *fp;
396 	struct uio *uio;
397 	struct ucred *cred;
398 	struct proc *p;
399 	int flags;
400 {
401 	struct pipe *rpipe = (struct pipe *) fp->f_data;
402 	int error;
403 	int nread = 0;
404 	u_int size;
405 
406 	++rpipe->pipe_busy;
407 	error = pipelock(rpipe, 1);
408 	if (error)
409 		goto unlocked_error;
410 
411 	while (uio->uio_resid) {
412 		/*
413 		 * normal pipe buffer receive
414 		 */
415 		if (rpipe->pipe_buffer.cnt > 0) {
416 			size = rpipe->pipe_buffer.size - rpipe->pipe_buffer.out;
417 			if (size > rpipe->pipe_buffer.cnt)
418 				size = rpipe->pipe_buffer.cnt;
419 			if (size > (u_int) uio->uio_resid)
420 				size = (u_int) uio->uio_resid;
421 
422 			error = uiomove(&rpipe->pipe_buffer.buffer[rpipe->pipe_buffer.out],
423 					size, uio);
424 			if (error)
425 				break;
426 
427 			rpipe->pipe_buffer.out += size;
428 			if (rpipe->pipe_buffer.out >= rpipe->pipe_buffer.size)
429 				rpipe->pipe_buffer.out = 0;
430 
431 			rpipe->pipe_buffer.cnt -= size;
432 
433 			/*
434 			 * If there is no more to read in the pipe, reset
435 			 * its pointers to the beginning.  This improves
436 			 * cache hit stats.
437 			 */
438 			if (rpipe->pipe_buffer.cnt == 0) {
439 				rpipe->pipe_buffer.in = 0;
440 				rpipe->pipe_buffer.out = 0;
441 			}
442 			nread += size;
443 #ifndef PIPE_NODIRECT
444 		/*
445 		 * Direct copy, bypassing a kernel buffer.
446 		 */
447 		} else if ((size = rpipe->pipe_map.cnt) &&
448 			   (rpipe->pipe_state & PIPE_DIRECTW)) {
449 			caddr_t	va;
450 			if (size > (u_int) uio->uio_resid)
451 				size = (u_int) uio->uio_resid;
452 
453 			va = (caddr_t) rpipe->pipe_map.kva +
454 			    rpipe->pipe_map.pos;
455 			error = uiomove(va, size, uio);
456 			if (error)
457 				break;
458 			nread += size;
459 			rpipe->pipe_map.pos += size;
460 			rpipe->pipe_map.cnt -= size;
461 			if (rpipe->pipe_map.cnt == 0) {
462 				rpipe->pipe_state &= ~PIPE_DIRECTW;
463 				wakeup(rpipe);
464 			}
465 #endif
466 		} else {
467 			/*
468 			 * detect EOF condition
469 			 * read returns 0 on EOF, no need to set error
470 			 */
471 			if (rpipe->pipe_state & PIPE_EOF)
472 				break;
473 
474 			/*
475 			 * If the "write-side" has been blocked, wake it up now.
476 			 */
477 			if (rpipe->pipe_state & PIPE_WANTW) {
478 				rpipe->pipe_state &= ~PIPE_WANTW;
479 				wakeup(rpipe);
480 			}
481 
482 			/*
483 			 * Break if some data was read.
484 			 */
485 			if (nread > 0)
486 				break;
487 
488 			/*
489 			 * Unlock the pipe buffer for our remaining processing.  We
490 			 * will either break out with an error or we will sleep and
491 			 * relock to loop.
492 			 */
493 			pipeunlock(rpipe);
494 
495 			/*
496 			 * Handle non-blocking mode operation or
497 			 * wait for more data.
498 			 */
499 			if (fp->f_flag & FNONBLOCK) {
500 				error = EAGAIN;
501 			} else {
502 				rpipe->pipe_state |= PIPE_WANTR;
503 				if ((error = tsleep(rpipe, PRIBIO | PCATCH,
504 				    "piperd", 0)) == 0)
505 					error = pipelock(rpipe, 1);
506 			}
507 			if (error)
508 				goto unlocked_error;
509 		}
510 	}
511 	pipeunlock(rpipe);
512 
513 	if (error == 0)
514 		vfs_timestamp(&rpipe->pipe_atime);
515 unlocked_error:
516 	--rpipe->pipe_busy;
517 
518 	/*
519 	 * PIPE_WANT processing only makes sense if pipe_busy is 0.
520 	 */
521 	if ((rpipe->pipe_busy == 0) && (rpipe->pipe_state & PIPE_WANT)) {
522 		rpipe->pipe_state &= ~(PIPE_WANT|PIPE_WANTW);
523 		wakeup(rpipe);
524 	} else if (rpipe->pipe_buffer.cnt < MINPIPESIZE) {
525 		/*
526 		 * Handle write blocking hysteresis.
527 		 */
528 		if (rpipe->pipe_state & PIPE_WANTW) {
529 			rpipe->pipe_state &= ~PIPE_WANTW;
530 			wakeup(rpipe);
531 		}
532 	}
533 
534 	if ((rpipe->pipe_buffer.size - rpipe->pipe_buffer.cnt) >= PIPE_BUF)
535 		pipeselwakeup(rpipe);
536 
537 	return (error);
538 }
539 
540 #ifndef PIPE_NODIRECT
541 /*
542  * Map the sending processes' buffer into kernel space and wire it.
543  * This is similar to a physical write operation.
544  */
545 static int
546 pipe_build_write_buffer(wpipe, uio)
547 	struct pipe *wpipe;
548 	struct uio *uio;
549 {
550 	u_int size;
551 	int i;
552 	vm_offset_t addr, endaddr, paddr;
553 
554 	size = (u_int) uio->uio_iov->iov_len;
555 	if (size > wpipe->pipe_buffer.size)
556 		size = wpipe->pipe_buffer.size;
557 
558 	endaddr = round_page((vm_offset_t)uio->uio_iov->iov_base + size);
559 	mtx_lock(&vm_mtx);
560 	addr = trunc_page((vm_offset_t)uio->uio_iov->iov_base);
561 	for (i = 0; addr < endaddr; addr += PAGE_SIZE, i++) {
562 		vm_page_t m;
563 
564 		if (vm_fault_quick((caddr_t)addr, VM_PROT_READ) < 0 ||
565 		    (paddr = pmap_kextract(addr)) == 0) {
566 			int j;
567 
568 			for (j = 0; j < i; j++)
569 				vm_page_unwire(wpipe->pipe_map.ms[j], 1);
570 			mtx_unlock(&vm_mtx);
571 			return (EFAULT);
572 		}
573 
574 		m = PHYS_TO_VM_PAGE(paddr);
575 		vm_page_wire(m);
576 		wpipe->pipe_map.ms[i] = m;
577 	}
578 
579 /*
580  * set up the control block
581  */
582 	wpipe->pipe_map.npages = i;
583 	wpipe->pipe_map.pos =
584 	    ((vm_offset_t) uio->uio_iov->iov_base) & PAGE_MASK;
585 	wpipe->pipe_map.cnt = size;
586 
587 /*
588  * and map the buffer
589  */
590 	if (wpipe->pipe_map.kva == 0) {
591 		/*
592 		 * We need to allocate space for an extra page because the
593 		 * address range might (will) span pages at times.
594 		 */
595 		wpipe->pipe_map.kva = kmem_alloc_pageable(kernel_map,
596 			wpipe->pipe_buffer.size + PAGE_SIZE);
597 		amountpipekva += wpipe->pipe_buffer.size + PAGE_SIZE;
598 	}
599 	pmap_qenter(wpipe->pipe_map.kva, wpipe->pipe_map.ms,
600 		wpipe->pipe_map.npages);
601 
602 	mtx_unlock(&vm_mtx);
603 /*
604  * and update the uio data
605  */
606 
607 	uio->uio_iov->iov_len -= size;
608 	uio->uio_iov->iov_base += size;
609 	if (uio->uio_iov->iov_len == 0)
610 		uio->uio_iov++;
611 	uio->uio_resid -= size;
612 	uio->uio_offset += size;
613 	return (0);
614 }
615 
616 /*
617  * unmap and unwire the process buffer
618  */
619 static void
620 pipe_destroy_write_buffer(wpipe)
621 	struct pipe *wpipe;
622 {
623 	int i;
624 
625 	mtx_lock(&vm_mtx);
626 	if (wpipe->pipe_map.kva) {
627 		pmap_qremove(wpipe->pipe_map.kva, wpipe->pipe_map.npages);
628 
629 		if (amountpipekva > MAXPIPEKVA) {
630 			vm_offset_t kva = wpipe->pipe_map.kva;
631 			wpipe->pipe_map.kva = 0;
632 			kmem_free(kernel_map, kva,
633 				wpipe->pipe_buffer.size + PAGE_SIZE);
634 			amountpipekva -= wpipe->pipe_buffer.size + PAGE_SIZE;
635 		}
636 	}
637 	for (i = 0; i < wpipe->pipe_map.npages; i++)
638 		vm_page_unwire(wpipe->pipe_map.ms[i], 1);
639 	mtx_unlock(&vm_mtx);
640 }
641 
642 /*
643  * In the case of a signal, the writing process might go away.  This
644  * code copies the data into the circular buffer so that the source
645  * pages can be freed without loss of data.
646  */
647 static void
648 pipe_clone_write_buffer(wpipe)
649 	struct pipe *wpipe;
650 {
651 	int size;
652 	int pos;
653 
654 	size = wpipe->pipe_map.cnt;
655 	pos = wpipe->pipe_map.pos;
656 	bcopy((caddr_t) wpipe->pipe_map.kva + pos,
657 	    (caddr_t) wpipe->pipe_buffer.buffer, size);
658 
659 	wpipe->pipe_buffer.in = size;
660 	wpipe->pipe_buffer.out = 0;
661 	wpipe->pipe_buffer.cnt = size;
662 	wpipe->pipe_state &= ~PIPE_DIRECTW;
663 
664 	pipe_destroy_write_buffer(wpipe);
665 }
666 
667 /*
668  * This implements the pipe buffer write mechanism.  Note that only
669  * a direct write OR a normal pipe write can be pending at any given time.
670  * If there are any characters in the pipe buffer, the direct write will
671  * be deferred until the receiving process grabs all of the bytes from
672  * the pipe buffer.  Then the direct mapping write is set-up.
673  */
674 static int
675 pipe_direct_write(wpipe, uio)
676 	struct pipe *wpipe;
677 	struct uio *uio;
678 {
679 	int error;
680 
681 retry:
682 	while (wpipe->pipe_state & PIPE_DIRECTW) {
683 		if (wpipe->pipe_state & PIPE_WANTR) {
684 			wpipe->pipe_state &= ~PIPE_WANTR;
685 			wakeup(wpipe);
686 		}
687 		wpipe->pipe_state |= PIPE_WANTW;
688 		error = tsleep(wpipe, PRIBIO | PCATCH, "pipdww", 0);
689 		if (error)
690 			goto error1;
691 		if (wpipe->pipe_state & PIPE_EOF) {
692 			error = EPIPE;
693 			goto error1;
694 		}
695 	}
696 	wpipe->pipe_map.cnt = 0;	/* transfer not ready yet */
697 	if (wpipe->pipe_buffer.cnt > 0) {
698 		if (wpipe->pipe_state & PIPE_WANTR) {
699 			wpipe->pipe_state &= ~PIPE_WANTR;
700 			wakeup(wpipe);
701 		}
702 
703 		wpipe->pipe_state |= PIPE_WANTW;
704 		error = tsleep(wpipe, PRIBIO | PCATCH, "pipdwc", 0);
705 		if (error)
706 			goto error1;
707 		if (wpipe->pipe_state & PIPE_EOF) {
708 			error = EPIPE;
709 			goto error1;
710 		}
711 		goto retry;
712 	}
713 
714 	wpipe->pipe_state |= PIPE_DIRECTW;
715 
716 	error = pipe_build_write_buffer(wpipe, uio);
717 	if (error) {
718 		wpipe->pipe_state &= ~PIPE_DIRECTW;
719 		goto error1;
720 	}
721 
722 	error = 0;
723 	while (!error && (wpipe->pipe_state & PIPE_DIRECTW)) {
724 		if (wpipe->pipe_state & PIPE_EOF) {
725 			pipelock(wpipe, 0);
726 			pipe_destroy_write_buffer(wpipe);
727 			pipeunlock(wpipe);
728 			pipeselwakeup(wpipe);
729 			error = EPIPE;
730 			goto error1;
731 		}
732 		if (wpipe->pipe_state & PIPE_WANTR) {
733 			wpipe->pipe_state &= ~PIPE_WANTR;
734 			wakeup(wpipe);
735 		}
736 		pipeselwakeup(wpipe);
737 		error = tsleep(wpipe, PRIBIO | PCATCH, "pipdwt", 0);
738 	}
739 
740 	pipelock(wpipe,0);
741 	if (wpipe->pipe_state & PIPE_DIRECTW) {
742 		/*
743 		 * this bit of trickery substitutes a kernel buffer for
744 		 * the process that might be going away.
745 		 */
746 		pipe_clone_write_buffer(wpipe);
747 	} else {
748 		pipe_destroy_write_buffer(wpipe);
749 	}
750 	pipeunlock(wpipe);
751 	return (error);
752 
753 error1:
754 	wakeup(wpipe);
755 	return (error);
756 }
757 #endif
758 
759 static int
760 pipe_write(fp, uio, cred, flags, p)
761 	struct file *fp;
762 	struct uio *uio;
763 	struct ucred *cred;
764 	struct proc *p;
765 	int flags;
766 {
767 	int error = 0;
768 	int orig_resid;
769 	struct pipe *wpipe, *rpipe;
770 
771 	rpipe = (struct pipe *) fp->f_data;
772 	wpipe = rpipe->pipe_peer;
773 
774 	/*
775 	 * detect loss of pipe read side, issue SIGPIPE if lost.
776 	 */
777 	if ((wpipe == NULL) || (wpipe->pipe_state & PIPE_EOF)) {
778 		return (EPIPE);
779 	}
780 
781 	/*
782 	 * If it is advantageous to resize the pipe buffer, do
783 	 * so.
784 	 */
785 	if ((uio->uio_resid > PIPE_SIZE) &&
786 		(nbigpipe < LIMITBIGPIPES) &&
787 		(wpipe->pipe_state & PIPE_DIRECTW) == 0 &&
788 		(wpipe->pipe_buffer.size <= PIPE_SIZE) &&
789 		(wpipe->pipe_buffer.cnt == 0)) {
790 
791 		if ((error = pipelock(wpipe,1)) == 0) {
792 			if (pipespace(wpipe, BIG_PIPE_SIZE) == 0)
793 				nbigpipe++;
794 			pipeunlock(wpipe);
795 		} else {
796 			return (error);
797 		}
798 	}
799 
800 	KASSERT(wpipe->pipe_buffer.buffer != NULL, ("pipe buffer gone"));
801 
802 	++wpipe->pipe_busy;
803 	orig_resid = uio->uio_resid;
804 	while (uio->uio_resid) {
805 		int space;
806 
807 #ifndef PIPE_NODIRECT
808 		/*
809 		 * If the transfer is large, we can gain performance if
810 		 * we do process-to-process copies directly.
811 		 * If the write is non-blocking, we don't use the
812 		 * direct write mechanism.
813 		 *
814 		 * The direct write mechanism will detect the reader going
815 		 * away on us.
816 		 */
817 		if ((uio->uio_iov->iov_len >= PIPE_MINDIRECT) &&
818 		    (fp->f_flag & FNONBLOCK) == 0 &&
819 			(wpipe->pipe_map.kva || (amountpipekva < LIMITPIPEKVA)) &&
820 			(uio->uio_iov->iov_len >= PIPE_MINDIRECT)) {
821 			error = pipe_direct_write( wpipe, uio);
822 			if (error)
823 				break;
824 			continue;
825 		}
826 #endif
827 
828 		/*
829 		 * Pipe buffered writes cannot be coincidental with
830 		 * direct writes.  We wait until the currently executing
831 		 * direct write is completed before we start filling the
832 		 * pipe buffer.  We break out if a signal occurs or the
833 		 * reader goes away.
834 		 */
835 	retrywrite:
836 		while (wpipe->pipe_state & PIPE_DIRECTW) {
837 			if (wpipe->pipe_state & PIPE_WANTR) {
838 				wpipe->pipe_state &= ~PIPE_WANTR;
839 				wakeup(wpipe);
840 			}
841 			error = tsleep(wpipe, PRIBIO | PCATCH, "pipbww", 0);
842 			if (wpipe->pipe_state & PIPE_EOF)
843 				break;
844 			if (error)
845 				break;
846 		}
847 		if (wpipe->pipe_state & PIPE_EOF) {
848 			error = EPIPE;
849 			break;
850 		}
851 
852 		space = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
853 
854 		/* Writes of size <= PIPE_BUF must be atomic. */
855 		if ((space < uio->uio_resid) && (orig_resid <= PIPE_BUF))
856 			space = 0;
857 
858 		if (space > 0 && (wpipe->pipe_buffer.cnt < PIPE_SIZE)) {
859 			if ((error = pipelock(wpipe,1)) == 0) {
860 				int size;	/* Transfer size */
861 				int segsize;	/* first segment to transfer */
862 
863 				/*
864 				 * It is possible for a direct write to
865 				 * slip in on us... handle it here...
866 				 */
867 				if (wpipe->pipe_state & PIPE_DIRECTW) {
868 					pipeunlock(wpipe);
869 					goto retrywrite;
870 				}
871 				/*
872 				 * If a process blocked in uiomove, our
873 				 * value for space might be bad.
874 				 *
875 				 * XXX will we be ok if the reader has gone
876 				 * away here?
877 				 */
878 				if (space > wpipe->pipe_buffer.size -
879 				    wpipe->pipe_buffer.cnt) {
880 					pipeunlock(wpipe);
881 					goto retrywrite;
882 				}
883 
884 				/*
885 				 * Transfer size is minimum of uio transfer
886 				 * and free space in pipe buffer.
887 				 */
888 				if (space > uio->uio_resid)
889 					size = uio->uio_resid;
890 				else
891 					size = space;
892 				/*
893 				 * First segment to transfer is minimum of
894 				 * transfer size and contiguous space in
895 				 * pipe buffer.  If first segment to transfer
896 				 * is less than the transfer size, we've got
897 				 * a wraparound in the buffer.
898 				 */
899 				segsize = wpipe->pipe_buffer.size -
900 					wpipe->pipe_buffer.in;
901 				if (segsize > size)
902 					segsize = size;
903 
904 				/* Transfer first segment */
905 
906 				error = uiomove(&wpipe->pipe_buffer.buffer[wpipe->pipe_buffer.in],
907 						segsize, uio);
908 
909 				if (error == 0 && segsize < size) {
910 					/*
911 					 * Transfer remaining part now, to
912 					 * support atomic writes.  Wraparound
913 					 * happened.
914 					 */
915 					if (wpipe->pipe_buffer.in + segsize !=
916 					    wpipe->pipe_buffer.size)
917 						panic("Expected pipe buffer wraparound disappeared");
918 
919 					error = uiomove(&wpipe->pipe_buffer.buffer[0],
920 							size - segsize, uio);
921 				}
922 				if (error == 0) {
923 					wpipe->pipe_buffer.in += size;
924 					if (wpipe->pipe_buffer.in >=
925 					    wpipe->pipe_buffer.size) {
926 						if (wpipe->pipe_buffer.in != size - segsize + wpipe->pipe_buffer.size)
927 							panic("Expected wraparound bad");
928 						wpipe->pipe_buffer.in = size - segsize;
929 					}
930 
931 					wpipe->pipe_buffer.cnt += size;
932 					if (wpipe->pipe_buffer.cnt > wpipe->pipe_buffer.size)
933 						panic("Pipe buffer overflow");
934 
935 				}
936 				pipeunlock(wpipe);
937 			}
938 			if (error)
939 				break;
940 
941 		} else {
942 			/*
943 			 * If the "read-side" has been blocked, wake it up now.
944 			 */
945 			if (wpipe->pipe_state & PIPE_WANTR) {
946 				wpipe->pipe_state &= ~PIPE_WANTR;
947 				wakeup(wpipe);
948 			}
949 
950 			/*
951 			 * don't block on non-blocking I/O
952 			 */
953 			if (fp->f_flag & FNONBLOCK) {
954 				error = EAGAIN;
955 				break;
956 			}
957 
958 			/*
959 			 * We have no more space and have something to offer,
960 			 * wake up select/poll.
961 			 */
962 			pipeselwakeup(wpipe);
963 
964 			wpipe->pipe_state |= PIPE_WANTW;
965 			error = tsleep(wpipe, PRIBIO | PCATCH, "pipewr", 0);
966 			if (error != 0)
967 				break;
968 			/*
969 			 * If read side wants to go away, we just issue a signal
970 			 * to ourselves.
971 			 */
972 			if (wpipe->pipe_state & PIPE_EOF) {
973 				error = EPIPE;
974 				break;
975 			}
976 		}
977 	}
978 
979 	--wpipe->pipe_busy;
980 	if ((wpipe->pipe_busy == 0) && (wpipe->pipe_state & PIPE_WANT)) {
981 		wpipe->pipe_state &= ~(PIPE_WANT | PIPE_WANTR);
982 		wakeup(wpipe);
983 	} else if (wpipe->pipe_buffer.cnt > 0) {
984 		/*
985 		 * If we have put any characters in the buffer, we wake up
986 		 * the reader.
987 		 */
988 		if (wpipe->pipe_state & PIPE_WANTR) {
989 			wpipe->pipe_state &= ~PIPE_WANTR;
990 			wakeup(wpipe);
991 		}
992 	}
993 
994 	/*
995 	 * Don't return EPIPE if I/O was successful
996 	 */
997 	if ((wpipe->pipe_buffer.cnt == 0) &&
998 		(uio->uio_resid == 0) &&
999 		(error == EPIPE))
1000 		error = 0;
1001 
1002 	if (error == 0)
1003 		vfs_timestamp(&wpipe->pipe_mtime);
1004 
1005 	/*
1006 	 * We have something to offer,
1007 	 * wake up select/poll.
1008 	 */
1009 	if (wpipe->pipe_buffer.cnt)
1010 		pipeselwakeup(wpipe);
1011 
1012 	return (error);
1013 }
1014 
1015 /*
1016  * we implement a very minimal set of ioctls for compatibility with sockets.
1017  */
1018 int
1019 pipe_ioctl(fp, cmd, data, p)
1020 	struct file *fp;
1021 	u_long cmd;
1022 	caddr_t data;
1023 	struct proc *p;
1024 {
1025 	struct pipe *mpipe = (struct pipe *)fp->f_data;
1026 
1027 	switch (cmd) {
1028 
1029 	case FIONBIO:
1030 		return (0);
1031 
1032 	case FIOASYNC:
1033 		if (*(int *)data) {
1034 			mpipe->pipe_state |= PIPE_ASYNC;
1035 		} else {
1036 			mpipe->pipe_state &= ~PIPE_ASYNC;
1037 		}
1038 		return (0);
1039 
1040 	case FIONREAD:
1041 		if (mpipe->pipe_state & PIPE_DIRECTW)
1042 			*(int *)data = mpipe->pipe_map.cnt;
1043 		else
1044 			*(int *)data = mpipe->pipe_buffer.cnt;
1045 		return (0);
1046 
1047 	case FIOSETOWN:
1048 		return (fsetown(*(int *)data, &mpipe->pipe_sigio));
1049 
1050 	case FIOGETOWN:
1051 		*(int *)data = fgetown(mpipe->pipe_sigio);
1052 		return (0);
1053 
1054 	/* This is deprecated, FIOSETOWN should be used instead. */
1055 	case TIOCSPGRP:
1056 		return (fsetown(-(*(int *)data), &mpipe->pipe_sigio));
1057 
1058 	/* This is deprecated, FIOGETOWN should be used instead. */
1059 	case TIOCGPGRP:
1060 		*(int *)data = -fgetown(mpipe->pipe_sigio);
1061 		return (0);
1062 
1063 	}
1064 	return (ENOTTY);
1065 }
1066 
1067 int
1068 pipe_poll(fp, events, cred, p)
1069 	struct file *fp;
1070 	int events;
1071 	struct ucred *cred;
1072 	struct proc *p;
1073 {
1074 	struct pipe *rpipe = (struct pipe *)fp->f_data;
1075 	struct pipe *wpipe;
1076 	int revents = 0;
1077 
1078 	wpipe = rpipe->pipe_peer;
1079 	if (events & (POLLIN | POLLRDNORM))
1080 		if ((rpipe->pipe_state & PIPE_DIRECTW) ||
1081 		    (rpipe->pipe_buffer.cnt > 0) ||
1082 		    (rpipe->pipe_state & PIPE_EOF))
1083 			revents |= events & (POLLIN | POLLRDNORM);
1084 
1085 	if (events & (POLLOUT | POLLWRNORM))
1086 		if (wpipe == NULL || (wpipe->pipe_state & PIPE_EOF) ||
1087 		    (((wpipe->pipe_state & PIPE_DIRECTW) == 0) &&
1088 		     (wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt) >= PIPE_BUF))
1089 			revents |= events & (POLLOUT | POLLWRNORM);
1090 
1091 	if ((rpipe->pipe_state & PIPE_EOF) ||
1092 	    (wpipe == NULL) ||
1093 	    (wpipe->pipe_state & PIPE_EOF))
1094 		revents |= POLLHUP;
1095 
1096 	if (revents == 0) {
1097 		if (events & (POLLIN | POLLRDNORM)) {
1098 			selrecord(p, &rpipe->pipe_sel);
1099 			rpipe->pipe_state |= PIPE_SEL;
1100 		}
1101 
1102 		if (events & (POLLOUT | POLLWRNORM)) {
1103 			selrecord(p, &wpipe->pipe_sel);
1104 			wpipe->pipe_state |= PIPE_SEL;
1105 		}
1106 	}
1107 
1108 	return (revents);
1109 }
1110 
1111 static int
1112 pipe_stat(fp, ub, p)
1113 	struct file *fp;
1114 	struct stat *ub;
1115 	struct proc *p;
1116 {
1117 	struct pipe *pipe = (struct pipe *)fp->f_data;
1118 
1119 	bzero((caddr_t)ub, sizeof(*ub));
1120 	ub->st_mode = S_IFIFO;
1121 	ub->st_blksize = pipe->pipe_buffer.size;
1122 	ub->st_size = pipe->pipe_buffer.cnt;
1123 	ub->st_blocks = (ub->st_size + ub->st_blksize - 1) / ub->st_blksize;
1124 	ub->st_atimespec = pipe->pipe_atime;
1125 	ub->st_mtimespec = pipe->pipe_mtime;
1126 	ub->st_ctimespec = pipe->pipe_ctime;
1127 	ub->st_uid = fp->f_cred->cr_uid;
1128 	ub->st_gid = fp->f_cred->cr_gid;
1129 	/*
1130 	 * Left as 0: st_dev, st_ino, st_nlink, st_rdev, st_flags, st_gen.
1131 	 * XXX (st_dev, st_ino) should be unique.
1132 	 */
1133 	return (0);
1134 }
1135 
1136 /* ARGSUSED */
1137 static int
1138 pipe_close(fp, p)
1139 	struct file *fp;
1140 	struct proc *p;
1141 {
1142 	struct pipe *cpipe = (struct pipe *)fp->f_data;
1143 
1144 	fp->f_ops = &badfileops;
1145 	fp->f_data = NULL;
1146 	funsetown(cpipe->pipe_sigio);
1147 	pipeclose(cpipe);
1148 	return (0);
1149 }
1150 
1151 static void
1152 pipe_free_kmem(cpipe)
1153 	struct pipe *cpipe;
1154 {
1155 
1156 	mtx_assert(&vm_mtx, MA_OWNED);
1157 	if (cpipe->pipe_buffer.buffer != NULL) {
1158 		if (cpipe->pipe_buffer.size > PIPE_SIZE)
1159 			--nbigpipe;
1160 		amountpipekva -= cpipe->pipe_buffer.size;
1161 		kmem_free(kernel_map,
1162 			(vm_offset_t)cpipe->pipe_buffer.buffer,
1163 			cpipe->pipe_buffer.size);
1164 		cpipe->pipe_buffer.buffer = NULL;
1165 	}
1166 #ifndef PIPE_NODIRECT
1167 	if (cpipe->pipe_map.kva != NULL) {
1168 		amountpipekva -= cpipe->pipe_buffer.size + PAGE_SIZE;
1169 		kmem_free(kernel_map,
1170 			cpipe->pipe_map.kva,
1171 			cpipe->pipe_buffer.size + PAGE_SIZE);
1172 		cpipe->pipe_map.cnt = 0;
1173 		cpipe->pipe_map.kva = 0;
1174 		cpipe->pipe_map.pos = 0;
1175 		cpipe->pipe_map.npages = 0;
1176 	}
1177 #endif
1178 }
1179 
1180 /*
1181  * shutdown the pipe
1182  */
1183 static void
1184 pipeclose(cpipe)
1185 	struct pipe *cpipe;
1186 {
1187 	struct pipe *ppipe;
1188 
1189 	if (cpipe) {
1190 
1191 		pipeselwakeup(cpipe);
1192 
1193 		/*
1194 		 * If the other side is blocked, wake it up saying that
1195 		 * we want to close it down.
1196 		 */
1197 		while (cpipe->pipe_busy) {
1198 			wakeup(cpipe);
1199 			cpipe->pipe_state |= PIPE_WANT | PIPE_EOF;
1200 			tsleep(cpipe, PRIBIO, "pipecl", 0);
1201 		}
1202 
1203 		/*
1204 		 * Disconnect from peer
1205 		 */
1206 		if ((ppipe = cpipe->pipe_peer) != NULL) {
1207 			pipeselwakeup(ppipe);
1208 
1209 			ppipe->pipe_state |= PIPE_EOF;
1210 			wakeup(ppipe);
1211 			ppipe->pipe_peer = NULL;
1212 		}
1213 		/*
1214 		 * free resources
1215 		 */
1216 		mtx_lock(&vm_mtx);
1217 		pipe_free_kmem(cpipe);
1218 		/* XXX: erm, doesn't zalloc already have its own locks and
1219 		 * not need the giant vm lock?
1220 		 */
1221 		zfree(pipe_zone, cpipe);
1222 		mtx_unlock(&vm_mtx);
1223 	}
1224 }
1225 
1226 /*ARGSUSED*/
1227 static int
1228 pipe_kqfilter(struct file *fp, struct knote *kn)
1229 {
1230 	struct pipe *rpipe = (struct pipe *)kn->kn_fp->f_data;
1231 
1232 	switch (kn->kn_filter) {
1233 	case EVFILT_READ:
1234 		kn->kn_fop = &pipe_rfiltops;
1235 		break;
1236 	case EVFILT_WRITE:
1237 		kn->kn_fop = &pipe_wfiltops;
1238 		break;
1239 	default:
1240 		return (1);
1241 	}
1242 
1243 	SLIST_INSERT_HEAD(&rpipe->pipe_sel.si_note, kn, kn_selnext);
1244 	return (0);
1245 }
1246 
1247 static void
1248 filt_pipedetach(struct knote *kn)
1249 {
1250 	struct pipe *rpipe = (struct pipe *)kn->kn_fp->f_data;
1251 
1252 	SLIST_REMOVE(&rpipe->pipe_sel.si_note, kn, knote, kn_selnext);
1253 }
1254 
1255 /*ARGSUSED*/
1256 static int
1257 filt_piperead(struct knote *kn, long hint)
1258 {
1259 	struct pipe *rpipe = (struct pipe *)kn->kn_fp->f_data;
1260 	struct pipe *wpipe = rpipe->pipe_peer;
1261 
1262 	kn->kn_data = rpipe->pipe_buffer.cnt;
1263 	if ((kn->kn_data == 0) && (rpipe->pipe_state & PIPE_DIRECTW))
1264 		kn->kn_data = rpipe->pipe_map.cnt;
1265 
1266 	if ((rpipe->pipe_state & PIPE_EOF) ||
1267 	    (wpipe == NULL) || (wpipe->pipe_state & PIPE_EOF)) {
1268 		kn->kn_flags |= EV_EOF;
1269 		return (1);
1270 	}
1271 	return (kn->kn_data > 0);
1272 }
1273 
1274 /*ARGSUSED*/
1275 static int
1276 filt_pipewrite(struct knote *kn, long hint)
1277 {
1278 	struct pipe *rpipe = (struct pipe *)kn->kn_fp->f_data;
1279 	struct pipe *wpipe = rpipe->pipe_peer;
1280 
1281 	if ((wpipe == NULL) || (wpipe->pipe_state & PIPE_EOF)) {
1282 		kn->kn_data = 0;
1283 		kn->kn_flags |= EV_EOF;
1284 		return (1);
1285 	}
1286 	kn->kn_data = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
1287 	if (wpipe->pipe_state & PIPE_DIRECTW)
1288 		kn->kn_data = 0;
1289 
1290 	return (kn->kn_data >= PIPE_BUF);
1291 }
1292