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