The thread/proc pointer argument in the VFS subsystem originally existed
[dragonfly.git] / sys / kern / sys_pipe.c
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.33 2006/05/06 02:43:12 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/kernel.h>
56 #include <sys/proc.h>
57 #include <sys/fcntl.h>
58 #include <sys/file.h>
59 #include <sys/filedesc.h>
60 #include <sys/filio.h>
61 #include <sys/ttycom.h>
62 #include <sys/stat.h>
63 #include <sys/poll.h>
64 #include <sys/select.h>
65 #include <sys/signalvar.h>
66 #include <sys/sysproto.h>
67 #include <sys/pipe.h>
68 #include <sys/vnode.h>
69 #include <sys/uio.h>
70 #include <sys/event.h>
71 #include <sys/globaldata.h>
72 #include <sys/module.h>
73 #include <sys/malloc.h>
74 #include <sys/sysctl.h>
75 #include <sys/socket.h>
76
77 #include <vm/vm.h>
78 #include <vm/vm_param.h>
79 #include <sys/lock.h>
80 #include <vm/vm_object.h>
81 #include <vm/vm_kern.h>
82 #include <vm/vm_extern.h>
83 #include <vm/pmap.h>
84 #include <vm/vm_map.h>
85 #include <vm/vm_page.h>
86 #include <vm/vm_zone.h>
87
88 #include <sys/file2.h>
89
90 #include <machine/cpufunc.h>
91
92 /*
93  * interfaces to the outside world
94  */
95 static int pipe_read (struct file *fp, struct uio *uio, 
96                 struct ucred *cred, int flags);
97 static int pipe_write (struct file *fp, struct uio *uio, 
98                 struct ucred *cred, int flags);
99 static int pipe_close (struct file *fp);
100 static int pipe_shutdown (struct file *fp, int how);
101 static int pipe_poll (struct file *fp, int events, struct ucred *cred);
102 static int pipe_kqfilter (struct file *fp, struct knote *kn);
103 static int pipe_stat (struct file *fp, struct stat *sb, struct ucred *cred);
104 static int pipe_ioctl (struct file *fp, u_long cmd, caddr_t data, struct ucred *cred);
105
106 static struct fileops pipeops = {
107         NULL,   /* port */
108         NULL,   /* clone */
109         pipe_read, pipe_write, pipe_ioctl, pipe_poll, pipe_kqfilter,
110         pipe_stat, pipe_close, pipe_shutdown
111 };
112
113 static void     filt_pipedetach(struct knote *kn);
114 static int      filt_piperead(struct knote *kn, long hint);
115 static int      filt_pipewrite(struct knote *kn, long hint);
116
117 static struct filterops pipe_rfiltops =
118         { 1, NULL, filt_pipedetach, filt_piperead };
119 static struct filterops pipe_wfiltops =
120         { 1, NULL, filt_pipedetach, filt_pipewrite };
121
122 MALLOC_DEFINE(M_PIPE, "pipe", "pipe structures");
123
124 /*
125  * Default pipe buffer size(s), this can be kind-of large now because pipe
126  * space is pageable.  The pipe code will try to maintain locality of
127  * reference for performance reasons, so small amounts of outstanding I/O
128  * will not wipe the cache.
129  */
130 #define MINPIPESIZE (PIPE_SIZE/3)
131 #define MAXPIPESIZE (2*PIPE_SIZE/3)
132
133 /*
134  * Maximum amount of kva for pipes -- this is kind-of a soft limit, but
135  * is there so that on large systems, we don't exhaust it.
136  */
137 #define MAXPIPEKVA (8*1024*1024)
138
139 /*
140  * Limit for direct transfers, we cannot, of course limit
141  * the amount of kva for pipes in general though.
142  */
143 #define LIMITPIPEKVA (16*1024*1024)
144
145 /*
146  * Limit the number of "big" pipes
147  */
148 #define LIMITBIGPIPES   32
149 #define PIPEQ_MAX_CACHE 16      /* per-cpu pipe structure cache */
150
151 static int pipe_maxbig = LIMITBIGPIPES;
152 static int pipe_maxcache = PIPEQ_MAX_CACHE;
153 static int pipe_nbig;
154 static int pipe_bcache_alloc;
155 static int pipe_bkmem_alloc;
156 static int pipe_dwrite_enable = 1;      /* 0:copy, 1:kmem/sfbuf 2:force */
157 static int pipe_dwrite_sfbuf = 1;       /* 0:kmem_map 1:sfbufs 2:sfbufs_dmap */
158                                         /* 3:sfbuf_dmap w/ forced invlpg */
159
160 SYSCTL_NODE(_kern, OID_AUTO, pipe, CTLFLAG_RW, 0, "Pipe operation");
161 SYSCTL_INT(_kern_pipe, OID_AUTO, nbig,
162         CTLFLAG_RD, &pipe_nbig, 0, "numer of big pipes allocated");
163 SYSCTL_INT(_kern_pipe, OID_AUTO, maxcache,
164         CTLFLAG_RW, &pipe_maxcache, 0, "max pipes cached per-cpu");
165 SYSCTL_INT(_kern_pipe, OID_AUTO, maxbig,
166         CTLFLAG_RW, &pipe_maxbig, 0, "max number of big pipes");
167 SYSCTL_INT(_kern_pipe, OID_AUTO, dwrite_enable,
168         CTLFLAG_RW, &pipe_dwrite_enable, 0, "1:enable/2:force direct writes");
169 SYSCTL_INT(_kern_pipe, OID_AUTO, dwrite_sfbuf,
170         CTLFLAG_RW, &pipe_dwrite_sfbuf, 0,
171         "(if dwrite_enable) 0:kmem 1:sfbuf 2:sfbuf_dmap 3:sfbuf_dmap_forceinvlpg");
172 #if !defined(NO_PIPE_SYSCTL_STATS)
173 SYSCTL_INT(_kern_pipe, OID_AUTO, bcache_alloc,
174         CTLFLAG_RW, &pipe_bcache_alloc, 0, "pipe buffer from pcpu cache");
175 SYSCTL_INT(_kern_pipe, OID_AUTO, bkmem_alloc,
176         CTLFLAG_RW, &pipe_bkmem_alloc, 0, "pipe buffer from kmem");
177 #endif
178
179 static void pipeclose (struct pipe *cpipe);
180 static void pipe_free_kmem (struct pipe *cpipe);
181 static int pipe_create (struct pipe **cpipep);
182 static __inline int pipelock (struct pipe *cpipe, int catch);
183 static __inline void pipeunlock (struct pipe *cpipe);
184 static __inline void pipeselwakeup (struct pipe *cpipe);
185 #ifndef PIPE_NODIRECT
186 static int pipe_build_write_buffer (struct pipe *wpipe, struct uio *uio);
187 static int pipe_direct_write (struct pipe *wpipe, struct uio *uio);
188 static void pipe_clone_write_buffer (struct pipe *wpipe);
189 #endif
190 static int pipespace (struct pipe *cpipe, int size);
191
192 /*
193  * The pipe system call for the DTYPE_PIPE type of pipes
194  *
195  * pipe_ARgs(int dummy)
196  */
197
198 /* ARGSUSED */
199 int
200 pipe(struct pipe_args *uap)
201 {
202         struct thread *td = curthread;
203         struct proc *p = td->td_proc;
204         struct filedesc *fdp;
205         struct file *rf, *wf;
206         struct pipe *rpipe, *wpipe;
207         int fd1, fd2, error;
208
209         KKASSERT(p);
210         fdp = p->p_fd;
211
212         rpipe = wpipe = NULL;
213         if (pipe_create(&rpipe) || pipe_create(&wpipe)) {
214                 pipeclose(rpipe); 
215                 pipeclose(wpipe); 
216                 return (ENFILE);
217         }
218         
219         rpipe->pipe_state |= PIPE_DIRECTOK;
220         wpipe->pipe_state |= PIPE_DIRECTOK;
221
222         /*
223          * Select the direct-map features to use for this pipe.  Since the
224          * sysctl's can change on the fly we record the settings when the
225          * pipe is created.
226          *
227          * Generally speaking the system will default to what we consider
228          * to be the best-balanced and most stable option.  Right now this
229          * is SFBUF1.  Modes 2 and 3 are considered experiemental at the
230          * moment.
231          */
232         wpipe->pipe_feature = PIPE_COPY;
233         if (pipe_dwrite_enable) {
234                 switch(pipe_dwrite_sfbuf) {
235                 case 0:
236                         wpipe->pipe_feature = PIPE_KMEM;
237                         break;
238                 case 1:
239                         wpipe->pipe_feature = PIPE_SFBUF1;
240                         break;
241                 case 2:
242                 case 3:
243                         wpipe->pipe_feature = PIPE_SFBUF2;
244                         break;
245                 }
246         }
247         rpipe->pipe_feature = wpipe->pipe_feature;
248
249         error = falloc(p, &rf, &fd1);
250         if (error) {
251                 pipeclose(rpipe);
252                 pipeclose(wpipe);
253                 return (error);
254         }
255         uap->sysmsg_fds[0] = fd1;
256
257         /*
258          * Warning: once we've gotten past allocation of the fd for the
259          * read-side, we can only drop the read side via fdrop() in order
260          * to avoid races against processes which manage to dup() the read
261          * side while we are blocked trying to allocate the write side.
262          */
263         rf->f_type = DTYPE_PIPE;
264         rf->f_flag = FREAD | FWRITE;
265         rf->f_ops = &pipeops;
266         rf->f_data = rpipe;
267         error = falloc(p, &wf, &fd2);
268         if (error) {
269                 if (fdp->fd_files[fd1].fp == rf) {
270                         funsetfd(fdp, fd1);
271                         fdrop(rf, td);
272                 }
273                 fdrop(rf, td);
274                 /* rpipe has been closed by fdrop(). */
275                 pipeclose(wpipe);
276                 return (error);
277         }
278         wf->f_type = DTYPE_PIPE;
279         wf->f_flag = FREAD | FWRITE;
280         wf->f_ops = &pipeops;
281         wf->f_data = wpipe;
282         uap->sysmsg_fds[1] = fd2;
283
284         rpipe->pipe_peer = wpipe;
285         wpipe->pipe_peer = rpipe;
286         fdrop(rf, td);
287         fdrop(wf, td);
288
289         return (0);
290 }
291
292 /*
293  * Allocate kva for pipe circular buffer, the space is pageable
294  * This routine will 'realloc' the size of a pipe safely, if it fails
295  * it will retain the old buffer.
296  * If it fails it will return ENOMEM.
297  */
298 static int
299 pipespace(struct pipe *cpipe, int size)
300 {
301         struct vm_object *object;
302         caddr_t buffer;
303         int npages, error;
304
305         npages = round_page(size) / PAGE_SIZE;
306         object = cpipe->pipe_buffer.object;
307
308         /*
309          * [re]create the object if necessary and reserve space for it
310          * in the kernel_map.  The object and memory are pageable.  On
311          * success, free the old resources before assigning the new
312          * ones.
313          */
314         if (object == NULL || object->size != npages) {
315                 object = vm_object_allocate(OBJT_DEFAULT, npages);
316                 buffer = (caddr_t) vm_map_min(kernel_map);
317
318                 error = vm_map_find(kernel_map, object, 0,
319                         (vm_offset_t *) &buffer, size, 1,
320                         VM_PROT_ALL, VM_PROT_ALL, 0);
321
322                 if (error != KERN_SUCCESS) {
323                         vm_object_deallocate(object);
324                         return (ENOMEM);
325                 }
326                 pipe_free_kmem(cpipe);
327                 cpipe->pipe_buffer.object = object;
328                 cpipe->pipe_buffer.buffer = buffer;
329                 cpipe->pipe_buffer.size = size;
330                 ++pipe_bkmem_alloc;
331         } else {
332                 ++pipe_bcache_alloc;
333         }
334         cpipe->pipe_buffer.in = 0;
335         cpipe->pipe_buffer.out = 0;
336         cpipe->pipe_buffer.cnt = 0;
337         return (0);
338 }
339
340 /*
341  * Initialize and allocate VM and memory for pipe, pulling the pipe from
342  * our per-cpu cache if possible.  For now make sure it is sized for the
343  * smaller PIPE_SIZE default.
344  */
345 static int
346 pipe_create(cpipep)
347         struct pipe **cpipep;
348 {
349         globaldata_t gd = mycpu;
350         struct pipe *cpipe;
351         int error;
352
353         if ((cpipe = gd->gd_pipeq) != NULL) {
354                 gd->gd_pipeq = cpipe->pipe_peer;
355                 --gd->gd_pipeqcount;
356                 cpipe->pipe_peer = NULL;
357         } else {
358                 cpipe = malloc(sizeof(struct pipe), M_PIPE, M_WAITOK|M_ZERO);
359         }
360         *cpipep = cpipe;
361         if ((error = pipespace(cpipe, PIPE_SIZE)) != 0)
362                 return (error);
363         vfs_timestamp(&cpipe->pipe_ctime);
364         cpipe->pipe_atime = cpipe->pipe_ctime;
365         cpipe->pipe_mtime = cpipe->pipe_ctime;
366         return (0);
367 }
368
369
370 /*
371  * lock a pipe for I/O, blocking other access
372  */
373 static __inline int
374 pipelock(cpipe, catch)
375         struct pipe *cpipe;
376         int catch;
377 {
378         int error;
379
380         while (cpipe->pipe_state & PIPE_LOCK) {
381                 cpipe->pipe_state |= PIPE_LWANT;
382                 error = tsleep(cpipe, (catch ? PCATCH : 0), "pipelk", 0);
383                 if (error != 0) 
384                         return (error);
385         }
386         cpipe->pipe_state |= PIPE_LOCK;
387         return (0);
388 }
389
390 /*
391  * unlock a pipe I/O lock
392  */
393 static __inline void
394 pipeunlock(cpipe)
395         struct pipe *cpipe;
396 {
397
398         cpipe->pipe_state &= ~PIPE_LOCK;
399         if (cpipe->pipe_state & PIPE_LWANT) {
400                 cpipe->pipe_state &= ~PIPE_LWANT;
401                 wakeup(cpipe);
402         }
403 }
404
405 static __inline void
406 pipeselwakeup(cpipe)
407         struct pipe *cpipe;
408 {
409
410         if (cpipe->pipe_state & PIPE_SEL) {
411                 cpipe->pipe_state &= ~PIPE_SEL;
412                 selwakeup(&cpipe->pipe_sel);
413         }
414         if ((cpipe->pipe_state & PIPE_ASYNC) && cpipe->pipe_sigio)
415                 pgsigio(cpipe->pipe_sigio, SIGIO, 0);
416         KNOTE(&cpipe->pipe_sel.si_note, 0);
417 }
418
419 /* ARGSUSED */
420 static int
421 pipe_read(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
422 {
423         struct pipe *rpipe = (struct pipe *) fp->f_data;
424         int error;
425         int nread = 0;
426         u_int size;
427
428         ++rpipe->pipe_busy;
429         error = pipelock(rpipe, 1);
430         if (error)
431                 goto unlocked_error;
432
433         while (uio->uio_resid) {
434                 caddr_t va;
435
436                 if (rpipe->pipe_buffer.cnt > 0) {
437                         /*
438                          * normal pipe buffer receive
439                          */
440                         size = rpipe->pipe_buffer.size - rpipe->pipe_buffer.out;
441                         if (size > rpipe->pipe_buffer.cnt)
442                                 size = rpipe->pipe_buffer.cnt;
443                         if (size > (u_int) uio->uio_resid)
444                                 size = (u_int) uio->uio_resid;
445
446                         error = uiomove(&rpipe->pipe_buffer.buffer[rpipe->pipe_buffer.out],
447                                         size, uio);
448                         if (error)
449                                 break;
450
451                         rpipe->pipe_buffer.out += size;
452                         if (rpipe->pipe_buffer.out >= rpipe->pipe_buffer.size)
453                                 rpipe->pipe_buffer.out = 0;
454
455                         rpipe->pipe_buffer.cnt -= size;
456
457                         /*
458                          * If there is no more to read in the pipe, reset
459                          * its pointers to the beginning.  This improves
460                          * cache hit stats.
461                          */
462                         if (rpipe->pipe_buffer.cnt == 0) {
463                                 rpipe->pipe_buffer.in = 0;
464                                 rpipe->pipe_buffer.out = 0;
465                         }
466                         nread += size;
467 #ifndef PIPE_NODIRECT
468                 } else if (rpipe->pipe_kva &&
469                            rpipe->pipe_feature == PIPE_KMEM &&
470                            (rpipe->pipe_state & (PIPE_DIRECTW|PIPE_DIRECTIP)) 
471                                == PIPE_DIRECTW
472                 ) {
473                         /*
474                          * Direct copy using source-side kva mapping
475                          */
476                         size = rpipe->pipe_map.xio_bytes -
477                                 rpipe->pipe_buffer.out;
478                         if (size > (u_int)uio->uio_resid)
479                                 size = (u_int)uio->uio_resid;
480                         va = (caddr_t)rpipe->pipe_kva + 
481                                 xio_kvaoffset(&rpipe->pipe_map, rpipe->pipe_buffer.out);
482                         error = uiomove(va, size, uio);
483                         if (error)
484                                 break;
485                         nread += size;
486                         rpipe->pipe_buffer.out += size;
487                         if (rpipe->pipe_buffer.out == rpipe->pipe_map.xio_bytes) {
488                                 rpipe->pipe_state |= PIPE_DIRECTIP;
489                                 rpipe->pipe_state &= ~PIPE_DIRECTW;
490                                 /* reset out index for copy mode */
491                                 rpipe->pipe_buffer.out = 0;
492                                 wakeup(rpipe);
493                         }
494                 } else if (rpipe->pipe_buffer.out != rpipe->pipe_map.xio_bytes &&
495                            rpipe->pipe_kva &&
496                            rpipe->pipe_feature == PIPE_SFBUF2 &&
497                            (rpipe->pipe_state & (PIPE_DIRECTW|PIPE_DIRECTIP)) 
498                                == PIPE_DIRECTW
499                 ) {
500                         /*
501                          * Direct copy, bypassing a kernel buffer.  We cannot
502                          * mess with the direct-write buffer until
503                          * PIPE_DIRECTIP is cleared.  In order to prevent 
504                          * the pipe_write code from racing itself in
505                          * direct_write, we set DIRECTIP when we clear
506                          * DIRECTW after we have exhausted the buffer.
507                          */
508                         if (pipe_dwrite_sfbuf == 3)
509                                 rpipe->pipe_kvamask = 0;
510                         pmap_qenter2(rpipe->pipe_kva, rpipe->pipe_map.xio_pages,
511                                     rpipe->pipe_map.xio_npages,
512                                     &rpipe->pipe_kvamask);
513                         size = rpipe->pipe_map.xio_bytes - 
514                                 rpipe->pipe_buffer.out;
515                         if (size > (u_int)uio->uio_resid)
516                                 size = (u_int)uio->uio_resid;
517                         va = (caddr_t)rpipe->pipe_kva + xio_kvaoffset(&rpipe->pipe_map, rpipe->pipe_buffer.out);
518                         error = uiomove(va, size, uio);
519                         if (error)
520                                 break;
521                         nread += size;
522                         rpipe->pipe_buffer.out += size;
523                         if (rpipe->pipe_buffer.out == rpipe->pipe_map.xio_bytes) {
524                                 rpipe->pipe_state |= PIPE_DIRECTIP;
525                                 rpipe->pipe_state &= ~PIPE_DIRECTW;
526                                 /* reset out index for copy mode */
527                                 rpipe->pipe_buffer.out = 0;
528                                 wakeup(rpipe);
529                         }
530                 } else if (rpipe->pipe_buffer.out != rpipe->pipe_map.xio_bytes &&
531                            rpipe->pipe_feature == PIPE_SFBUF1 &&
532                            (rpipe->pipe_state & (PIPE_DIRECTW|PIPE_DIRECTIP)) 
533                                 == PIPE_DIRECTW
534                 ) {
535                         /*
536                          * Direct copy, bypassing a kernel buffer.  We cannot
537                          * mess with the direct-write buffer until
538                          * PIPE_DIRECTIP is cleared.  In order to prevent 
539                          * the pipe_write code from racing itself in
540                          * direct_write, we set DIRECTIP when we clear
541                          * DIRECTW after we have exhausted the buffer.
542                          */
543                         error = xio_uio_copy(&rpipe->pipe_map, rpipe->pipe_buffer.out, uio, &size);
544                         if (error)
545                                 break;
546                         nread += size;
547                         rpipe->pipe_buffer.out += size;
548                         if (rpipe->pipe_buffer.out == rpipe->pipe_map.xio_bytes) {
549                                 rpipe->pipe_state |= PIPE_DIRECTIP;
550                                 rpipe->pipe_state &= ~PIPE_DIRECTW;
551                                 /* reset out index for copy mode */
552                                 rpipe->pipe_buffer.out = 0;
553                                 wakeup(rpipe);
554                         }
555 #endif
556                 } else {
557                         /*
558                          * detect EOF condition
559                          * read returns 0 on EOF, no need to set error
560                          */
561                         if (rpipe->pipe_state & PIPE_EOF)
562                                 break;
563
564                         /*
565                          * If the "write-side" has been blocked, wake it up now.
566                          */
567                         if (rpipe->pipe_state & PIPE_WANTW) {
568                                 rpipe->pipe_state &= ~PIPE_WANTW;
569                                 wakeup(rpipe);
570                         }
571
572                         /*
573                          * Break if some data was read.
574                          */
575                         if (nread > 0)
576                                 break;
577
578                         /*
579                          * Unlock the pipe buffer for our remaining
580                          * processing.  We will either break out with an
581                          * error or we will sleep and relock to loop.
582                          */
583                         pipeunlock(rpipe);
584
585                         /*
586                          * Handle non-blocking mode operation or
587                          * wait for more data.
588                          */
589                         if (fp->f_flag & FNONBLOCK) {
590                                 error = EAGAIN;
591                         } else {
592                                 rpipe->pipe_state |= PIPE_WANTR;
593                                 if ((error = tsleep(rpipe, PCATCH|PNORESCHED,
594                                     "piperd", 0)) == 0) {
595                                         error = pipelock(rpipe, 1);
596                                 }
597                         }
598                         if (error)
599                                 goto unlocked_error;
600                 }
601         }
602         pipeunlock(rpipe);
603
604         if (error == 0)
605                 vfs_timestamp(&rpipe->pipe_atime);
606 unlocked_error:
607         --rpipe->pipe_busy;
608
609         /*
610          * PIPE_WANT processing only makes sense if pipe_busy is 0.
611          */
612         if ((rpipe->pipe_busy == 0) && (rpipe->pipe_state & PIPE_WANT)) {
613                 rpipe->pipe_state &= ~(PIPE_WANT|PIPE_WANTW);
614                 wakeup(rpipe);
615         } else if (rpipe->pipe_buffer.cnt < MINPIPESIZE) {
616                 /*
617                  * Handle write blocking hysteresis.
618                  */
619                 if (rpipe->pipe_state & PIPE_WANTW) {
620                         rpipe->pipe_state &= ~PIPE_WANTW;
621                         wakeup(rpipe);
622                 }
623         }
624
625         if ((rpipe->pipe_buffer.size - rpipe->pipe_buffer.cnt) >= PIPE_BUF)
626                 pipeselwakeup(rpipe);
627         return (error);
628 }
629
630 #ifndef PIPE_NODIRECT
631 /*
632  * Map the sending processes' buffer into kernel space and wire it.
633  * This is similar to a physical write operation.
634  */
635 static int
636 pipe_build_write_buffer(wpipe, uio)
637         struct pipe *wpipe;
638         struct uio *uio;
639 {
640         int error;
641         u_int size;
642
643         size = (u_int) uio->uio_iov->iov_len;
644         if (size > wpipe->pipe_buffer.size)
645                 size = wpipe->pipe_buffer.size;
646
647         if (uio->uio_segflg == UIO_SYSSPACE) {
648                 error = xio_init_kbuf(&wpipe->pipe_map, uio->uio_iov->iov_base, 
649                                         size);
650         } else {
651                 error = xio_init_ubuf(&wpipe->pipe_map, uio->uio_iov->iov_base, 
652                                         size, XIOF_READ);
653         }
654         wpipe->pipe_buffer.out = 0;
655         if (error)
656                 return(error);
657
658         /*
659          * Create a kernel map for KMEM and SFBUF2 copy modes.  SFBUF2 will
660          * map the pages on the target while KMEM maps the pages now.
661          */
662         switch(wpipe->pipe_feature) {
663         case PIPE_KMEM:
664         case PIPE_SFBUF2:
665                 if (wpipe->pipe_kva == NULL) {
666                         wpipe->pipe_kva = 
667                             kmem_alloc_nofault(kernel_map, XIO_INTERNAL_SIZE);
668                         wpipe->pipe_kvamask = 0;
669                 }
670                 if (wpipe->pipe_feature == PIPE_KMEM) {
671                         pmap_qenter(wpipe->pipe_kva, wpipe->pipe_map.xio_pages,
672                                     wpipe->pipe_map.xio_npages);
673                 }
674                 break;
675         default:
676                 break;
677         }
678
679         /*
680          * And update the uio data.  The XIO might have loaded fewer bytes
681          * then requested so reload 'size'.
682          */
683         size = wpipe->pipe_map.xio_bytes;
684         uio->uio_iov->iov_len -= size;
685         uio->uio_iov->iov_base += size;
686         if (uio->uio_iov->iov_len == 0)
687                 uio->uio_iov++;
688         uio->uio_resid -= size;
689         uio->uio_offset += size;
690         return (0);
691 }
692
693 /*
694  * In the case of a signal, the writing process might go away.  This
695  * code copies the data into the circular buffer so that the source
696  * pages can be freed without loss of data.
697  *
698  * Note that in direct mode pipe_buffer.out is used to track the
699  * XIO offset.  We are converting the direct mode into buffered mode
700  * which changes the meaning of pipe_buffer.out.
701  */
702 static void
703 pipe_clone_write_buffer(wpipe)
704         struct pipe *wpipe;
705 {
706         int size;
707         int offset;
708
709         offset = wpipe->pipe_buffer.out;
710         size = wpipe->pipe_map.xio_bytes - offset;
711
712         KKASSERT(size <= wpipe->pipe_buffer.size);
713
714         wpipe->pipe_buffer.in = size;
715         wpipe->pipe_buffer.out = 0;
716         wpipe->pipe_buffer.cnt = size;
717         wpipe->pipe_state &= ~(PIPE_DIRECTW | PIPE_DIRECTIP);
718
719         xio_copy_xtok(&wpipe->pipe_map, offset, wpipe->pipe_buffer.buffer, size);
720         xio_release(&wpipe->pipe_map);
721         if (wpipe->pipe_kva) {
722                 pmap_qremove(wpipe->pipe_kva, XIO_INTERNAL_PAGES);
723                 kmem_free(kernel_map, wpipe->pipe_kva, XIO_INTERNAL_SIZE);
724                 wpipe->pipe_kva = NULL;
725         }
726 }
727
728 /*
729  * This implements the pipe buffer write mechanism.  Note that only
730  * a direct write OR a normal pipe write can be pending at any given time.
731  * If there are any characters in the pipe buffer, the direct write will
732  * be deferred until the receiving process grabs all of the bytes from
733  * the pipe buffer.  Then the direct mapping write is set-up.
734  */
735 static int
736 pipe_direct_write(wpipe, uio)
737         struct pipe *wpipe;
738         struct uio *uio;
739 {
740         int error;
741
742 retry:
743         while (wpipe->pipe_state & (PIPE_DIRECTW|PIPE_DIRECTIP)) {
744                 if (wpipe->pipe_state & PIPE_WANTR) {
745                         wpipe->pipe_state &= ~PIPE_WANTR;
746                         wakeup(wpipe);
747                 }
748                 wpipe->pipe_state |= PIPE_WANTW;
749                 error = tsleep(wpipe, PCATCH, "pipdww", 0);
750                 if (error)
751                         goto error2;
752                 if (wpipe->pipe_state & PIPE_EOF) {
753                         error = EPIPE;
754                         goto error2;
755                 }
756         }
757         KKASSERT(wpipe->pipe_map.xio_bytes == 0);
758         if (wpipe->pipe_buffer.cnt > 0) {
759                 if (wpipe->pipe_state & PIPE_WANTR) {
760                         wpipe->pipe_state &= ~PIPE_WANTR;
761                         wakeup(wpipe);
762                 }
763                         
764                 wpipe->pipe_state |= PIPE_WANTW;
765                 error = tsleep(wpipe, PCATCH, "pipdwc", 0);
766                 if (error)
767                         goto error2;
768                 if (wpipe->pipe_state & PIPE_EOF) {
769                         error = EPIPE;
770                         goto error2;
771                 }
772                 goto retry;
773         }
774
775         /*
776          * Build our direct-write buffer
777          */
778         wpipe->pipe_state |= PIPE_DIRECTW | PIPE_DIRECTIP;
779         error = pipe_build_write_buffer(wpipe, uio);
780         if (error)
781                 goto error1;
782         wpipe->pipe_state &= ~PIPE_DIRECTIP;
783
784         /*
785          * Wait until the receiver has snarfed the data.  Since we are likely
786          * going to sleep we optimize the case and yield synchronously,
787          * possibly avoiding the tsleep().
788          */
789         error = 0;
790         while (!error && (wpipe->pipe_state & PIPE_DIRECTW)) {
791                 if (wpipe->pipe_state & PIPE_EOF) {
792                         pipelock(wpipe, 0);
793                         xio_release(&wpipe->pipe_map);
794                         if (wpipe->pipe_kva) {
795                                 pmap_qremove(wpipe->pipe_kva, XIO_INTERNAL_PAGES);
796                                 kmem_free(kernel_map, wpipe->pipe_kva, XIO_INTERNAL_SIZE);
797                                 wpipe->pipe_kva = NULL;
798                         }
799                         pipeunlock(wpipe);
800                         pipeselwakeup(wpipe);
801                         error = EPIPE;
802                         goto error1;
803                 }
804                 if (wpipe->pipe_state & PIPE_WANTR) {
805                         wpipe->pipe_state &= ~PIPE_WANTR;
806                         wakeup(wpipe);
807                 }
808                 pipeselwakeup(wpipe);
809                 error = tsleep(wpipe, PCATCH|PNORESCHED, "pipdwt", 0);
810         }
811         pipelock(wpipe,0);
812         if (wpipe->pipe_state & PIPE_DIRECTW) {
813                 /*
814                  * this bit of trickery substitutes a kernel buffer for
815                  * the process that might be going away.
816                  */
817                 pipe_clone_write_buffer(wpipe);
818                 KKASSERT((wpipe->pipe_state & PIPE_DIRECTIP) == 0);
819         } else {
820                 /*
821                  * note: The pipe_kva mapping is not qremove'd here.  For
822                  * legacy PIPE_KMEM mode this constitutes an improvement
823                  * over the original FreeBSD-4 algorithm.  For PIPE_SFBUF2
824                  * mode the kva mapping must not be removed to get the
825                  * caching benefit. 
826                  *
827                  * For testing purposes we will give the original algorithm
828                  * the benefit of the doubt 'what it could have been', and
829                  * keep the optimization.
830                  */
831                 KKASSERT(wpipe->pipe_state & PIPE_DIRECTIP);
832                 xio_release(&wpipe->pipe_map);
833                 wpipe->pipe_state &= ~PIPE_DIRECTIP;
834         }
835         pipeunlock(wpipe);
836         return (error);
837
838         /*
839          * Direct-write error, clear the direct write flags.
840          */
841 error1:
842         wpipe->pipe_state &= ~(PIPE_DIRECTW | PIPE_DIRECTIP);
843         /* fallthrough */
844
845         /*
846          * General error, wakeup the other side if it happens to be sleeping.
847          */
848 error2:
849         wakeup(wpipe);
850         return (error);
851 }
852 #endif
853         
854 static int
855 pipe_write(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
856 {
857         int error = 0;
858         int orig_resid;
859         struct pipe *wpipe, *rpipe;
860
861         rpipe = (struct pipe *) fp->f_data;
862         wpipe = rpipe->pipe_peer;
863
864         /*
865          * detect loss of pipe read side, issue SIGPIPE if lost.
866          */
867         if ((wpipe == NULL) || (wpipe->pipe_state & PIPE_EOF)) {
868                 return (EPIPE);
869         }
870         ++wpipe->pipe_busy;
871
872         /*
873          * If it is advantageous to resize the pipe buffer, do
874          * so.
875          */
876         if ((uio->uio_resid > PIPE_SIZE) &&
877                 (pipe_nbig < pipe_maxbig) &&
878                 (wpipe->pipe_state & (PIPE_DIRECTW|PIPE_DIRECTIP)) == 0 &&
879                 (wpipe->pipe_buffer.size <= PIPE_SIZE) &&
880                 (wpipe->pipe_buffer.cnt == 0)) {
881
882                 if ((error = pipelock(wpipe,1)) == 0) {
883                         if (pipespace(wpipe, BIG_PIPE_SIZE) == 0)
884                                 pipe_nbig++;
885                         pipeunlock(wpipe);
886                 }
887         }
888
889         /*
890          * If an early error occured unbusy and return, waking up any pending
891          * readers.
892          */
893         if (error) {
894                 --wpipe->pipe_busy;
895                 if ((wpipe->pipe_busy == 0) && 
896                     (wpipe->pipe_state & PIPE_WANT)) {
897                         wpipe->pipe_state &= ~(PIPE_WANT | PIPE_WANTR);
898                         wakeup(wpipe);
899                 }
900                 return(error);
901         }
902                 
903         KASSERT(wpipe->pipe_buffer.buffer != NULL, ("pipe buffer gone"));
904
905         orig_resid = uio->uio_resid;
906
907         while (uio->uio_resid) {
908                 int space;
909
910 #ifndef PIPE_NODIRECT
911                 /*
912                  * If the transfer is large, we can gain performance if
913                  * we do process-to-process copies directly.
914                  * If the write is non-blocking, we don't use the
915                  * direct write mechanism.
916                  *
917                  * The direct write mechanism will detect the reader going
918                  * away on us.
919                  */
920                 if ((uio->uio_iov->iov_len >= PIPE_MINDIRECT ||
921                     pipe_dwrite_enable > 1) &&
922                     (fp->f_flag & FNONBLOCK) == 0 &&
923                     pipe_dwrite_enable) {
924                         error = pipe_direct_write( wpipe, uio);
925                         if (error)
926                                 break;
927                         continue;
928                 }
929 #endif
930
931                 /*
932                  * Pipe buffered writes cannot be coincidental with
933                  * direct writes.  We wait until the currently executing
934                  * direct write is completed before we start filling the
935                  * pipe buffer.  We break out if a signal occurs or the
936                  * reader goes away.
937                  */
938         retrywrite:
939                 while (wpipe->pipe_state & (PIPE_DIRECTW|PIPE_DIRECTIP)) {
940                         if (wpipe->pipe_state & PIPE_WANTR) {
941                                 wpipe->pipe_state &= ~PIPE_WANTR;
942                                 wakeup(wpipe);
943                         }
944                         error = tsleep(wpipe, PCATCH, "pipbww", 0);
945                         if (wpipe->pipe_state & PIPE_EOF)
946                                 break;
947                         if (error)
948                                 break;
949                 }
950                 if (wpipe->pipe_state & PIPE_EOF) {
951                         error = EPIPE;
952                         break;
953                 }
954
955                 space = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
956
957                 /* Writes of size <= PIPE_BUF must be atomic. */
958                 if ((space < uio->uio_resid) && (orig_resid <= PIPE_BUF))
959                         space = 0;
960
961                 /* 
962                  * Write to fill, read size handles write hysteresis.  Also
963                  * additional restrictions can cause select-based non-blocking
964                  * writes to spin.
965                  */
966                 if (space > 0) {
967                         if ((error = pipelock(wpipe,1)) == 0) {
968                                 int size;       /* Transfer size */
969                                 int segsize;    /* first segment to transfer */
970
971                                 /*
972                                  * It is possible for a direct write to
973                                  * slip in on us... handle it here...
974                                  */
975                                 if (wpipe->pipe_state & (PIPE_DIRECTW|PIPE_DIRECTIP)) {
976                                         pipeunlock(wpipe);
977                                         goto retrywrite;
978                                 }
979                                 /* 
980                                  * If a process blocked in uiomove, our
981                                  * value for space might be bad.
982                                  *
983                                  * XXX will we be ok if the reader has gone
984                                  * away here?
985                                  */
986                                 if (space > wpipe->pipe_buffer.size - 
987                                     wpipe->pipe_buffer.cnt) {
988                                         pipeunlock(wpipe);
989                                         goto retrywrite;
990                                 }
991
992                                 /*
993                                  * Transfer size is minimum of uio transfer
994                                  * and free space in pipe buffer.
995                                  */
996                                 if (space > uio->uio_resid)
997                                         size = uio->uio_resid;
998                                 else
999                                         size = space;
1000                                 /*
1001                                  * First segment to transfer is minimum of 
1002                                  * transfer size and contiguous space in
1003                                  * pipe buffer.  If first segment to transfer
1004                                  * is less than the transfer size, we've got
1005                                  * a wraparound in the buffer.
1006                                  */
1007                                 segsize = wpipe->pipe_buffer.size - 
1008                                         wpipe->pipe_buffer.in;
1009                                 if (segsize > size)
1010                                         segsize = size;
1011                                 
1012                                 /* Transfer first segment */
1013
1014                                 error = uiomove(&wpipe->pipe_buffer.buffer[wpipe->pipe_buffer.in], 
1015                                                 segsize, uio);
1016                                 
1017                                 if (error == 0 && segsize < size) {
1018                                         /* 
1019                                          * Transfer remaining part now, to
1020                                          * support atomic writes.  Wraparound
1021                                          * happened.
1022                                          */
1023                                         if (wpipe->pipe_buffer.in + segsize != 
1024                                             wpipe->pipe_buffer.size)
1025                                                 panic("Expected pipe buffer wraparound disappeared");
1026                                                 
1027                                         error = uiomove(&wpipe->pipe_buffer.buffer[0],
1028                                                         size - segsize, uio);
1029                                 }
1030                                 if (error == 0) {
1031                                         wpipe->pipe_buffer.in += size;
1032                                         if (wpipe->pipe_buffer.in >=
1033                                             wpipe->pipe_buffer.size) {
1034                                                 if (wpipe->pipe_buffer.in != size - segsize + wpipe->pipe_buffer.size)
1035                                                         panic("Expected wraparound bad");
1036                                                 wpipe->pipe_buffer.in = size - segsize;
1037                                         }
1038                                 
1039                                         wpipe->pipe_buffer.cnt += size;
1040                                         if (wpipe->pipe_buffer.cnt > wpipe->pipe_buffer.size)
1041                                                 panic("Pipe buffer overflow");
1042                                 
1043                                 }
1044                                 pipeunlock(wpipe);
1045                         }
1046                         if (error)
1047                                 break;
1048
1049                 } else {
1050                         /*
1051                          * If the "read-side" has been blocked, wake it up now
1052                          * and yield to let it drain synchronously rather
1053                          * then block.
1054                          */
1055                         if (wpipe->pipe_state & PIPE_WANTR) {
1056                                 wpipe->pipe_state &= ~PIPE_WANTR;
1057                                 wakeup(wpipe);
1058                         }
1059
1060                         /*
1061                          * don't block on non-blocking I/O
1062                          */
1063                         if (fp->f_flag & FNONBLOCK) {
1064                                 error = EAGAIN;
1065                                 break;
1066                         }
1067
1068                         /*
1069                          * We have no more space and have something to offer,
1070                          * wake up select/poll.
1071                          */
1072                         pipeselwakeup(wpipe);
1073
1074                         wpipe->pipe_state |= PIPE_WANTW;
1075                         error = tsleep(wpipe, PCATCH|PNORESCHED, "pipewr", 0);
1076                         if (error != 0)
1077                                 break;
1078                         /*
1079                          * If read side wants to go away, we just issue a signal
1080                          * to ourselves.
1081                          */
1082                         if (wpipe->pipe_state & PIPE_EOF) {
1083                                 error = EPIPE;
1084                                 break;
1085                         }       
1086                 }
1087         }
1088
1089         --wpipe->pipe_busy;
1090
1091         if ((wpipe->pipe_busy == 0) && (wpipe->pipe_state & PIPE_WANT)) {
1092                 wpipe->pipe_state &= ~(PIPE_WANT | PIPE_WANTR);
1093                 wakeup(wpipe);
1094         } else if (wpipe->pipe_buffer.cnt > 0) {
1095                 /*
1096                  * If we have put any characters in the buffer, we wake up
1097                  * the reader.
1098                  */
1099                 if (wpipe->pipe_state & PIPE_WANTR) {
1100                         wpipe->pipe_state &= ~PIPE_WANTR;
1101                         wakeup(wpipe);
1102                 }
1103         }
1104
1105         /*
1106          * Don't return EPIPE if I/O was successful
1107          */
1108         if ((wpipe->pipe_buffer.cnt == 0) &&
1109             (uio->uio_resid == 0) &&
1110             (error == EPIPE)) {
1111                 error = 0;
1112         }
1113
1114         if (error == 0)
1115                 vfs_timestamp(&wpipe->pipe_mtime);
1116
1117         /*
1118          * We have something to offer,
1119          * wake up select/poll.
1120          */
1121         if (wpipe->pipe_buffer.cnt)
1122                 pipeselwakeup(wpipe);
1123
1124         return (error);
1125 }
1126
1127 /*
1128  * we implement a very minimal set of ioctls for compatibility with sockets.
1129  */
1130 int
1131 pipe_ioctl(struct file *fp, u_long cmd, caddr_t data, struct ucred *cred)
1132 {
1133         struct pipe *mpipe = (struct pipe *)fp->f_data;
1134
1135         switch (cmd) {
1136
1137         case FIONBIO:
1138                 return (0);
1139
1140         case FIOASYNC:
1141                 if (*(int *)data) {
1142                         mpipe->pipe_state |= PIPE_ASYNC;
1143                 } else {
1144                         mpipe->pipe_state &= ~PIPE_ASYNC;
1145                 }
1146                 return (0);
1147
1148         case FIONREAD:
1149                 if (mpipe->pipe_state & PIPE_DIRECTW) {
1150                         *(int *)data = mpipe->pipe_map.xio_bytes -
1151                                         mpipe->pipe_buffer.out;
1152                 } else {
1153                         *(int *)data = mpipe->pipe_buffer.cnt;
1154                 }
1155                 return (0);
1156
1157         case FIOSETOWN:
1158                 return (fsetown(*(int *)data, &mpipe->pipe_sigio));
1159
1160         case FIOGETOWN:
1161                 *(int *)data = fgetown(mpipe->pipe_sigio);
1162                 return (0);
1163
1164         /* This is deprecated, FIOSETOWN should be used instead. */
1165         case TIOCSPGRP:
1166                 return (fsetown(-(*(int *)data), &mpipe->pipe_sigio));
1167
1168         /* This is deprecated, FIOGETOWN should be used instead. */
1169         case TIOCGPGRP:
1170                 *(int *)data = -fgetown(mpipe->pipe_sigio);
1171                 return (0);
1172
1173         }
1174         return (ENOTTY);
1175 }
1176
1177 int
1178 pipe_poll(struct file *fp, int events, struct ucred *cred)
1179 {
1180         struct pipe *rpipe = (struct pipe *)fp->f_data;
1181         struct pipe *wpipe;
1182         int revents = 0;
1183
1184         wpipe = rpipe->pipe_peer;
1185         if (events & (POLLIN | POLLRDNORM))
1186                 if ((rpipe->pipe_state & PIPE_DIRECTW) ||
1187                     (rpipe->pipe_buffer.cnt > 0) ||
1188                     (rpipe->pipe_state & PIPE_EOF))
1189                         revents |= events & (POLLIN | POLLRDNORM);
1190
1191         if (events & (POLLOUT | POLLWRNORM))
1192                 if (wpipe == NULL || (wpipe->pipe_state & PIPE_EOF) ||
1193                     (((wpipe->pipe_state & PIPE_DIRECTW) == 0) &&
1194                      (wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt) >= PIPE_BUF))
1195                         revents |= events & (POLLOUT | POLLWRNORM);
1196
1197         if ((rpipe->pipe_state & PIPE_EOF) ||
1198             (wpipe == NULL) ||
1199             (wpipe->pipe_state & PIPE_EOF))
1200                 revents |= POLLHUP;
1201
1202         if (revents == 0) {
1203                 if (events & (POLLIN | POLLRDNORM)) {
1204                         selrecord(curthread, &rpipe->pipe_sel);
1205                         rpipe->pipe_state |= PIPE_SEL;
1206                 }
1207
1208                 if (events & (POLLOUT | POLLWRNORM)) {
1209                         selrecord(curthread, &wpipe->pipe_sel);
1210                         wpipe->pipe_state |= PIPE_SEL;
1211                 }
1212         }
1213
1214         return (revents);
1215 }
1216
1217 static int
1218 pipe_stat(struct file *fp, struct stat *ub, struct ucred *cred)
1219 {
1220         struct pipe *pipe = (struct pipe *)fp->f_data;
1221
1222         bzero((caddr_t)ub, sizeof(*ub));
1223         ub->st_mode = S_IFIFO;
1224         ub->st_blksize = pipe->pipe_buffer.size;
1225         ub->st_size = pipe->pipe_buffer.cnt;
1226         if (ub->st_size == 0 && (pipe->pipe_state & PIPE_DIRECTW)) {
1227                 ub->st_size = pipe->pipe_map.xio_bytes -
1228                                 pipe->pipe_buffer.out;
1229         }
1230         ub->st_blocks = (ub->st_size + ub->st_blksize - 1) / ub->st_blksize;
1231         ub->st_atimespec = pipe->pipe_atime;
1232         ub->st_mtimespec = pipe->pipe_mtime;
1233         ub->st_ctimespec = pipe->pipe_ctime;
1234         /*
1235          * Left as 0: st_dev, st_ino, st_nlink, st_uid, st_gid, st_rdev,
1236          * st_flags, st_gen.
1237          * XXX (st_dev, st_ino) should be unique.
1238          */
1239         return (0);
1240 }
1241
1242 /* ARGSUSED */
1243 static int
1244 pipe_close(struct file *fp)
1245 {
1246         struct pipe *cpipe = (struct pipe *)fp->f_data;
1247
1248         fp->f_ops = &badfileops;
1249         fp->f_data = NULL;
1250         funsetown(cpipe->pipe_sigio);
1251         pipeclose(cpipe);
1252         return (0);
1253 }
1254
1255 /*
1256  * Shutdown one or both directions of a full-duplex pipe.
1257  */
1258 /* ARGSUSED */
1259 static int
1260 pipe_shutdown(struct file *fp, int how)
1261 {
1262         struct pipe *rpipe = (struct pipe *)fp->f_data;
1263         struct pipe *wpipe;
1264         int error = EPIPE;
1265
1266         switch(how) {
1267         case SHUT_RDWR:
1268         case SHUT_RD:
1269                 if (rpipe) {
1270                         rpipe->pipe_state |= PIPE_EOF;
1271                         pipeselwakeup(rpipe);
1272                         if (rpipe->pipe_busy)
1273                                 wakeup(rpipe);
1274                         error = 0;
1275                 }
1276                 if (how == SHUT_RD)
1277                         break;
1278                 /* fall through */
1279         case SHUT_WR:
1280                 if (rpipe && (wpipe = rpipe->pipe_peer) != NULL) {
1281                         wpipe->pipe_state |= PIPE_EOF;
1282                         pipeselwakeup(wpipe);
1283                         if (wpipe->pipe_busy)
1284                                 wakeup(wpipe);
1285                         error = 0;
1286                 }
1287         }
1288         return (error);
1289 }
1290
1291 static void
1292 pipe_free_kmem(struct pipe *cpipe)
1293 {
1294         if (cpipe->pipe_buffer.buffer != NULL) {
1295                 if (cpipe->pipe_buffer.size > PIPE_SIZE)
1296                         --pipe_nbig;
1297                 kmem_free(kernel_map,
1298                         (vm_offset_t)cpipe->pipe_buffer.buffer,
1299                         cpipe->pipe_buffer.size);
1300                 cpipe->pipe_buffer.buffer = NULL;
1301                 cpipe->pipe_buffer.object = NULL;
1302         }
1303 #ifndef PIPE_NODIRECT
1304         KKASSERT(cpipe->pipe_map.xio_bytes == 0 &&
1305                 cpipe->pipe_map.xio_offset == 0 &&
1306                 cpipe->pipe_map.xio_npages == 0);
1307 #endif
1308 }
1309
1310 /*
1311  * shutdown the pipe
1312  */
1313 static void
1314 pipeclose(struct pipe *cpipe)
1315 {
1316         globaldata_t gd;
1317         struct pipe *ppipe;
1318
1319         if (cpipe == NULL)
1320                 return;
1321
1322         pipeselwakeup(cpipe);
1323
1324         /*
1325          * If the other side is blocked, wake it up saying that
1326          * we want to close it down.
1327          */
1328         while (cpipe->pipe_busy) {
1329                 wakeup(cpipe);
1330                 cpipe->pipe_state |= PIPE_WANT | PIPE_EOF;
1331                 tsleep(cpipe, 0, "pipecl", 0);
1332         }
1333
1334         /*
1335          * Disconnect from peer
1336          */
1337         if ((ppipe = cpipe->pipe_peer) != NULL) {
1338                 pipeselwakeup(ppipe);
1339
1340                 ppipe->pipe_state |= PIPE_EOF;
1341                 wakeup(ppipe);
1342                 KNOTE(&ppipe->pipe_sel.si_note, 0);
1343                 ppipe->pipe_peer = NULL;
1344         }
1345
1346         if (cpipe->pipe_kva) {
1347                 pmap_qremove(cpipe->pipe_kva, XIO_INTERNAL_PAGES);
1348                 kmem_free(kernel_map, cpipe->pipe_kva, XIO_INTERNAL_SIZE);
1349                 cpipe->pipe_kva = NULL;
1350         }
1351
1352         /*
1353          * free or cache resources
1354          */
1355         gd = mycpu;
1356         if (gd->gd_pipeqcount >= pipe_maxcache ||
1357             cpipe->pipe_buffer.size != PIPE_SIZE
1358         ) {
1359                 pipe_free_kmem(cpipe);
1360                 free(cpipe, M_PIPE);
1361         } else {
1362                 KKASSERT(cpipe->pipe_map.xio_npages == 0 &&
1363                         cpipe->pipe_map.xio_bytes == 0 &&
1364                         cpipe->pipe_map.xio_offset == 0);
1365                 cpipe->pipe_state = 0;
1366                 cpipe->pipe_busy = 0;
1367                 cpipe->pipe_peer = gd->gd_pipeq;
1368                 gd->gd_pipeq = cpipe;
1369                 ++gd->gd_pipeqcount;
1370         }
1371 }
1372
1373 /*ARGSUSED*/
1374 static int
1375 pipe_kqfilter(struct file *fp, struct knote *kn)
1376 {
1377         struct pipe *cpipe = (struct pipe *)kn->kn_fp->f_data;
1378
1379         switch (kn->kn_filter) {
1380         case EVFILT_READ:
1381                 kn->kn_fop = &pipe_rfiltops;
1382                 break;
1383         case EVFILT_WRITE:
1384                 kn->kn_fop = &pipe_wfiltops;
1385                 cpipe = cpipe->pipe_peer;
1386                 if (cpipe == NULL)
1387                         /* other end of pipe has been closed */
1388                         return (EPIPE);
1389                 break;
1390         default:
1391                 return (1);
1392         }
1393         kn->kn_hook = (caddr_t)cpipe;
1394
1395         SLIST_INSERT_HEAD(&cpipe->pipe_sel.si_note, kn, kn_selnext);
1396         return (0);
1397 }
1398
1399 static void
1400 filt_pipedetach(struct knote *kn)
1401 {
1402         struct pipe *cpipe = (struct pipe *)kn->kn_hook;
1403
1404         SLIST_REMOVE(&cpipe->pipe_sel.si_note, kn, knote, kn_selnext);
1405 }
1406
1407 /*ARGSUSED*/
1408 static int
1409 filt_piperead(struct knote *kn, long hint)
1410 {
1411         struct pipe *rpipe = (struct pipe *)kn->kn_fp->f_data;
1412         struct pipe *wpipe = rpipe->pipe_peer;
1413
1414         kn->kn_data = rpipe->pipe_buffer.cnt;
1415         if ((kn->kn_data == 0) && (rpipe->pipe_state & PIPE_DIRECTW)) {
1416                 kn->kn_data = rpipe->pipe_map.xio_bytes - 
1417                                 rpipe->pipe_buffer.out;
1418         }
1419
1420         if ((rpipe->pipe_state & PIPE_EOF) ||
1421             (wpipe == NULL) || (wpipe->pipe_state & PIPE_EOF)) {
1422                 kn->kn_flags |= EV_EOF; 
1423                 return (1);
1424         }
1425         return (kn->kn_data > 0);
1426 }
1427
1428 /*ARGSUSED*/
1429 static int
1430 filt_pipewrite(struct knote *kn, long hint)
1431 {
1432         struct pipe *rpipe = (struct pipe *)kn->kn_fp->f_data;
1433         struct pipe *wpipe = rpipe->pipe_peer;
1434
1435         if ((wpipe == NULL) || (wpipe->pipe_state & PIPE_EOF)) {
1436                 kn->kn_data = 0;
1437                 kn->kn_flags |= EV_EOF; 
1438                 return (1);
1439         }
1440         kn->kn_data = wpipe->pipe_buffer.size - wpipe->pipe_buffer.cnt;
1441         if (wpipe->pipe_state & PIPE_DIRECTW)
1442                 kn->kn_data = 0;
1443
1444         return (kn->kn_data >= PIPE_BUF);
1445 }