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