95ce53106765a68fe037e67c7b45af1705678ed2
[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.50 2008/09/09 04:06:13 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 #include <sys/param.h>
30 #include <sys/systm.h>
31 #include <sys/kernel.h>
32 #include <sys/proc.h>
33 #include <sys/fcntl.h>
34 #include <sys/file.h>
35 #include <sys/filedesc.h>
36 #include <sys/filio.h>
37 #include <sys/ttycom.h>
38 #include <sys/stat.h>
39 #include <sys/poll.h>
40 #include <sys/select.h>
41 #include <sys/signalvar.h>
42 #include <sys/sysproto.h>
43 #include <sys/pipe.h>
44 #include <sys/vnode.h>
45 #include <sys/uio.h>
46 #include <sys/event.h>
47 #include <sys/globaldata.h>
48 #include <sys/module.h>
49 #include <sys/malloc.h>
50 #include <sys/sysctl.h>
51 #include <sys/socket.h>
52
53 #include <vm/vm.h>
54 #include <vm/vm_param.h>
55 #include <sys/lock.h>
56 #include <vm/vm_object.h>
57 #include <vm/vm_kern.h>
58 #include <vm/vm_extern.h>
59 #include <vm/pmap.h>
60 #include <vm/vm_map.h>
61 #include <vm/vm_page.h>
62 #include <vm/vm_zone.h>
63
64 #include <sys/file2.h>
65
66 #include <machine/cpufunc.h>
67
68 /*
69  * interfaces to the outside world
70  */
71 static int pipe_read (struct file *fp, struct uio *uio, 
72                 struct ucred *cred, int flags);
73 static int pipe_write (struct file *fp, struct uio *uio, 
74                 struct ucred *cred, int flags);
75 static int pipe_close (struct file *fp);
76 static int pipe_shutdown (struct file *fp, int how);
77 static int pipe_poll (struct file *fp, int events, struct ucred *cred);
78 static int pipe_kqfilter (struct file *fp, struct knote *kn);
79 static int pipe_stat (struct file *fp, struct stat *sb, struct ucred *cred);
80 static int pipe_ioctl (struct file *fp, u_long cmd, caddr_t data, struct ucred *cred);
81
82 static struct fileops pipeops = {
83         .fo_read = pipe_read, 
84         .fo_write = pipe_write,
85         .fo_ioctl = pipe_ioctl,
86         .fo_poll = pipe_poll,
87         .fo_kqfilter = pipe_kqfilter,
88         .fo_stat = pipe_stat,
89         .fo_close = pipe_close,
90         .fo_shutdown = pipe_shutdown
91 };
92
93 static void     filt_pipedetach(struct knote *kn);
94 static int      filt_piperead(struct knote *kn, long hint);
95 static int      filt_pipewrite(struct knote *kn, long hint);
96
97 static struct filterops pipe_rfiltops =
98         { 1, NULL, filt_pipedetach, filt_piperead };
99 static struct filterops pipe_wfiltops =
100         { 1, NULL, filt_pipedetach, filt_pipewrite };
101
102 MALLOC_DEFINE(M_PIPE, "pipe", "pipe structures");
103
104 /*
105  * Default pipe buffer size(s), this can be kind-of large now because pipe
106  * space is pageable.  The pipe code will try to maintain locality of
107  * reference for performance reasons, so small amounts of outstanding I/O
108  * will not wipe the cache.
109  */
110 #define MINPIPESIZE (PIPE_SIZE/3)
111 #define MAXPIPESIZE (2*PIPE_SIZE/3)
112
113 /*
114  * Limit the number of "big" pipes
115  */
116 #define LIMITBIGPIPES   64
117 #define PIPEQ_MAX_CACHE 16      /* per-cpu pipe structure cache */
118
119 static int pipe_maxbig = LIMITBIGPIPES;
120 static int pipe_maxcache = PIPEQ_MAX_CACHE;
121 static int pipe_bigcount;
122 static int pipe_nbig;
123 static int pipe_bcache_alloc;
124 static int pipe_bkmem_alloc;
125
126 SYSCTL_NODE(_kern, OID_AUTO, pipe, CTLFLAG_RW, 0, "Pipe operation");
127 SYSCTL_INT(_kern_pipe, OID_AUTO, nbig,
128         CTLFLAG_RD, &pipe_nbig, 0, "numer of big pipes allocated");
129 SYSCTL_INT(_kern_pipe, OID_AUTO, bigcount,
130         CTLFLAG_RW, &pipe_bigcount, 0, "number of times pipe expanded");
131 SYSCTL_INT(_kern_pipe, OID_AUTO, maxcache,
132         CTLFLAG_RW, &pipe_maxcache, 0, "max pipes cached per-cpu");
133 SYSCTL_INT(_kern_pipe, OID_AUTO, maxbig,
134         CTLFLAG_RW, &pipe_maxbig, 0, "max number of big pipes");
135 #ifdef SMP
136 static int pipe_mpsafe = 0;
137 SYSCTL_INT(_kern_pipe, OID_AUTO, mpsafe,
138         CTLFLAG_RW, &pipe_mpsafe, 0, "");
139 #endif
140 #if !defined(NO_PIPE_SYSCTL_STATS)
141 SYSCTL_INT(_kern_pipe, OID_AUTO, bcache_alloc,
142         CTLFLAG_RW, &pipe_bcache_alloc, 0, "pipe buffer from pcpu cache");
143 SYSCTL_INT(_kern_pipe, OID_AUTO, bkmem_alloc,
144         CTLFLAG_RW, &pipe_bkmem_alloc, 0, "pipe buffer from kmem");
145 #endif
146
147 static void pipeclose (struct pipe *cpipe);
148 static void pipe_free_kmem (struct pipe *cpipe);
149 static int pipe_create (struct pipe **cpipep);
150 static __inline void pipeselwakeup (struct pipe *cpipe);
151 static int pipespace (struct pipe *cpipe, int size);
152
153 static __inline void
154 pipeselwakeup(struct pipe *cpipe)
155 {
156         if (cpipe->pipe_state & PIPE_SEL) {
157                 get_mplock();
158                 cpipe->pipe_state &= ~PIPE_SEL;
159                 selwakeup(&cpipe->pipe_sel);
160                 rel_mplock();
161         }
162         if ((cpipe->pipe_state & PIPE_ASYNC) && cpipe->pipe_sigio) {
163                 get_mplock();
164                 pgsigio(cpipe->pipe_sigio, SIGIO, 0);
165                 rel_mplock();
166         }
167         if (SLIST_FIRST(&cpipe->pipe_sel.si_note)) {
168                 get_mplock();
169                 KNOTE(&cpipe->pipe_sel.si_note, 0);
170                 rel_mplock();
171         }
172 }
173
174 /*
175  * These routines are called before and after a UIO.  The UIO
176  * may block, causing our held tokens to be lost temporarily.
177  *
178  * We use these routines to serialize reads against other reads
179  * and writes against other writes.
180  *
181  * The read token is held on entry so *ipp does not race.
182  */
183 static __inline int
184 pipe_start_uio(struct pipe *cpipe, u_int *ipp)
185 {
186         int error;
187
188         while (*ipp) {
189                 *ipp = -1;
190                 error = tsleep(ipp, PCATCH, "pipexx", 0);
191                 if (error)
192                         return (error);
193         }
194         *ipp = 1;
195         return (0);
196 }
197
198 static __inline void
199 pipe_end_uio(struct pipe *cpipe, u_int *ipp)
200 {
201         if (*ipp < 0) {
202                 *ipp = 0;
203                 wakeup(ipp);
204         } else {
205                 *ipp = 0;
206         }
207 }
208
209 static __inline void
210 pipe_get_mplock(int *save)
211 {
212 #ifdef SMP
213         if (pipe_mpsafe == 0) {
214                 get_mplock();
215                 *save = 1;
216         } else
217 #endif
218         {
219                 *save = 0;
220         }
221 }
222
223 static __inline void
224 pipe_rel_mplock(int *save)
225 {
226 #ifdef SMP
227         if (*save)
228                 rel_mplock();
229 #endif
230 }
231
232
233 /*
234  * The pipe system call for the DTYPE_PIPE type of pipes
235  *
236  * pipe_ARgs(int dummy)
237  */
238
239 /* ARGSUSED */
240 int
241 sys_pipe(struct pipe_args *uap)
242 {
243         struct thread *td = curthread;
244         struct proc *p = td->td_proc;
245         struct file *rf, *wf;
246         struct pipe *rpipe, *wpipe;
247         int fd1, fd2, error;
248
249         KKASSERT(p);
250
251         rpipe = wpipe = NULL;
252         if (pipe_create(&rpipe) || pipe_create(&wpipe)) {
253                 pipeclose(rpipe); 
254                 pipeclose(wpipe); 
255                 return (ENFILE);
256         }
257         
258         error = falloc(p, &rf, &fd1);
259         if (error) {
260                 pipeclose(rpipe);
261                 pipeclose(wpipe);
262                 return (error);
263         }
264         uap->sysmsg_fds[0] = fd1;
265
266         /*
267          * Warning: once we've gotten past allocation of the fd for the
268          * read-side, we can only drop the read side via fdrop() in order
269          * to avoid races against processes which manage to dup() the read
270          * side while we are blocked trying to allocate the write side.
271          */
272         rf->f_type = DTYPE_PIPE;
273         rf->f_flag = FREAD | FWRITE;
274         rf->f_ops = &pipeops;
275         rf->f_data = rpipe;
276         error = falloc(p, &wf, &fd2);
277         if (error) {
278                 fsetfd(p, NULL, fd1);
279                 fdrop(rf);
280                 /* rpipe has been closed by fdrop(). */
281                 pipeclose(wpipe);
282                 return (error);
283         }
284         wf->f_type = DTYPE_PIPE;
285         wf->f_flag = FREAD | FWRITE;
286         wf->f_ops = &pipeops;
287         wf->f_data = wpipe;
288         uap->sysmsg_fds[1] = fd2;
289
290         rpipe->pipe_slock = kmalloc(sizeof(struct lock),
291                                     M_PIPE, M_WAITOK|M_ZERO);
292         wpipe->pipe_slock = rpipe->pipe_slock;
293         rpipe->pipe_peer = wpipe;
294         wpipe->pipe_peer = rpipe;
295         lockinit(rpipe->pipe_slock, "pipecl", 0, 0);
296
297         /*
298          * Once activated the peer relationship remains valid until
299          * both sides are closed.
300          */
301         fsetfd(p, rf, fd1);
302         fsetfd(p, wf, fd2);
303         fdrop(rf);
304         fdrop(wf);
305
306         return (0);
307 }
308
309 /*
310  * Allocate kva for pipe circular buffer, the space is pageable
311  * This routine will 'realloc' the size of a pipe safely, if it fails
312  * it will retain the old buffer.
313  * If it fails it will return ENOMEM.
314  */
315 static int
316 pipespace(struct pipe *cpipe, int size)
317 {
318         struct vm_object *object;
319         caddr_t buffer;
320         int npages, error;
321
322         npages = round_page(size) / PAGE_SIZE;
323         object = cpipe->pipe_buffer.object;
324
325         /*
326          * [re]create the object if necessary and reserve space for it
327          * in the kernel_map.  The object and memory are pageable.  On
328          * success, free the old resources before assigning the new
329          * ones.
330          */
331         if (object == NULL || object->size != npages) {
332                 get_mplock();
333                 object = vm_object_allocate(OBJT_DEFAULT, npages);
334                 buffer = (caddr_t)vm_map_min(&kernel_map);
335
336                 error = vm_map_find(&kernel_map, object, 0,
337                                     (vm_offset_t *)&buffer, size,
338                                     1,
339                                     VM_MAPTYPE_NORMAL,
340                                     VM_PROT_ALL, VM_PROT_ALL,
341                                     0);
342
343                 if (error != KERN_SUCCESS) {
344                         vm_object_deallocate(object);
345                         rel_mplock();
346                         return (ENOMEM);
347                 }
348                 pipe_free_kmem(cpipe);
349                 rel_mplock();
350                 cpipe->pipe_buffer.object = object;
351                 cpipe->pipe_buffer.buffer = buffer;
352                 cpipe->pipe_buffer.size = size;
353                 ++pipe_bkmem_alloc;
354         } else {
355                 ++pipe_bcache_alloc;
356         }
357         cpipe->pipe_buffer.rindex = 0;
358         cpipe->pipe_buffer.windex = 0;
359         return (0);
360 }
361
362 /*
363  * Initialize and allocate VM and memory for pipe, pulling the pipe from
364  * our per-cpu cache if possible.  For now make sure it is sized for the
365  * smaller PIPE_SIZE default.
366  */
367 static int
368 pipe_create(struct pipe **cpipep)
369 {
370         globaldata_t gd = mycpu;
371         struct pipe *cpipe;
372         int error;
373
374         if ((cpipe = gd->gd_pipeq) != NULL) {
375                 gd->gd_pipeq = cpipe->pipe_peer;
376                 --gd->gd_pipeqcount;
377                 cpipe->pipe_peer = NULL;
378                 cpipe->pipe_wantwcnt = 0;
379         } else {
380                 cpipe = kmalloc(sizeof(struct pipe), M_PIPE, M_WAITOK|M_ZERO);
381         }
382         *cpipep = cpipe;
383         if ((error = pipespace(cpipe, PIPE_SIZE)) != 0)
384                 return (error);
385         vfs_timestamp(&cpipe->pipe_ctime);
386         cpipe->pipe_atime = cpipe->pipe_ctime;
387         cpipe->pipe_mtime = cpipe->pipe_ctime;
388         lwkt_token_init(&cpipe->pipe_rlock);
389         lwkt_token_init(&cpipe->pipe_wlock);
390         return (0);
391 }
392
393 /*
394  * MPALMOSTSAFE (acquires mplock)
395  */
396 static int
397 pipe_read(struct file *fp, struct uio *uio, struct ucred *cred, int fflags)
398 {
399         struct pipe *rpipe;
400         int error;
401         int nread = 0;
402         int nbio;
403         u_int size;     /* total bytes available */
404         u_int nsize;    /* total bytes to read */
405         u_int rindex;   /* contiguous bytes available */
406         int notify_writer;
407         lwkt_tokref rlock;
408         lwkt_tokref wlock;
409         int mpsave;
410
411         /*
412          * Degenerate case
413          */
414         if (uio->uio_resid == 0)
415                 return(0);
416
417         /*
418          * Setup locks, calculate nbio
419          */
420         pipe_get_mplock(&mpsave);
421         rpipe = (struct pipe *)fp->f_data;
422         lwkt_gettoken(&rlock, &rpipe->pipe_rlock);
423
424         if (fflags & O_FBLOCKING)
425                 nbio = 0;
426         else if (fflags & O_FNONBLOCKING)
427                 nbio = 1;
428         else if (fp->f_flag & O_NONBLOCK)
429                 nbio = 1;
430         else
431                 nbio = 0;
432
433         /*
434          * Reads are serialized.  Note howeverthat pipe_buffer.buffer and
435          * pipe_buffer.size can change out from under us when the number
436          * of bytes in the buffer are zero due to the write-side doing a
437          * pipespace().
438          */
439         error = pipe_start_uio(rpipe, &rpipe->pipe_rip);
440         if (error) {
441                 pipe_rel_mplock(&mpsave);
442                 lwkt_reltoken(&rlock);
443                 return (error);
444         }
445         notify_writer = 0;
446         while (uio->uio_resid) {
447                 size = rpipe->pipe_buffer.windex - rpipe->pipe_buffer.rindex;
448                 cpu_lfence();
449                 if (size) {
450                         rindex = rpipe->pipe_buffer.rindex &
451                                  (rpipe->pipe_buffer.size - 1);
452                         nsize = size;
453                         if (nsize > rpipe->pipe_buffer.size - rindex)
454                                 nsize = rpipe->pipe_buffer.size - rindex;
455                         if (nsize > (u_int)uio->uio_resid)
456                                 nsize = (u_int)uio->uio_resid;
457
458                         error = uiomove(&rpipe->pipe_buffer.buffer[rindex],
459                                         nsize, uio);
460                         if (error)
461                                 break;
462                         cpu_mfence();
463                         rpipe->pipe_buffer.rindex += nsize;
464                         nread += nsize;
465
466                         /*
467                          * If the FIFO has not been drained past the half-way
468                          * mark then just continue and do not try to notify
469                          * the writer yet.
470                          */
471                         if (size - nsize >= (rpipe->pipe_buffer.size >> 1)) {
472                                 notify_writer = 0;
473                                 continue;
474                         }
475
476                         /*
477                          * If the FIFO has been drained past the half-way
478                          * mark we have to check the writer at some point,
479                          * but for now continue if the writer is not yet
480                          * blocked.
481                          */
482                         notify_writer = 1;
483                         if ((rpipe->pipe_state & PIPE_WANTW) == 0)
484                                 continue;
485                 }
486
487                 /*
488                  * If the "write-side" was blocked we wake it up.  This code
489                  * is reached either when the buffer is completely emptied
490                  * or if it becomes more then half-empty.
491                  *
492                  * Pipe_state can only be modified if both the rlock and
493                  * wlock are held.
494                  */
495                 if (rpipe->pipe_state & PIPE_WANTW) {
496                         lwkt_gettoken(&wlock, &rpipe->pipe_wlock);
497                         if (rpipe->pipe_state & PIPE_WANTW) {
498                                 notify_writer = 0;
499                                 rpipe->pipe_state &= ~PIPE_WANTW;
500                                 lwkt_reltoken(&wlock);
501                                 wakeup(rpipe);
502                         } else {
503                                 lwkt_reltoken(&wlock);
504                         }
505                 }
506
507                 /*
508                  * Pick up our copy loop again if the writer sent data to
509                  * us.
510                  */
511                 size = rpipe->pipe_buffer.windex - rpipe->pipe_buffer.rindex;
512                 if (size)
513                         continue;
514
515                 /*
516                  * Detect EOF condition, do not set error.
517                  */
518                 if (rpipe->pipe_state & PIPE_REOF)
519                         break;
520
521 #ifdef SMP
522                 /*
523                  * Gravy train if SMP box.  This saves a ton of IPIs and
524                  * allows two cpus to operate in lockstep.
525                  *
526                  * XXX check pipe_wip also?
527                  */
528                 DELAY(1);
529                 size = rpipe->pipe_buffer.windex - rpipe->pipe_buffer.rindex;
530                 if (size)
531                         continue;
532 #endif
533
534                 /*
535                  * Break if some data was read, or if this was a non-blocking
536                  * read.
537                  */
538                 if (nread > 0)
539                         break;
540
541                 if (nbio) {
542                         error = EAGAIN;
543                         break;
544                 }
545
546                 /*
547                  * Last chance, interlock with WANTR.
548                  */
549                 lwkt_gettoken(&wlock, &rpipe->pipe_wlock);
550                 size = rpipe->pipe_buffer.windex - rpipe->pipe_buffer.rindex;
551                 if (size) {
552                         lwkt_reltoken(&wlock);
553                         continue;
554                 }
555
556                 /*
557                  * If there is no more to read in the pipe, reset its
558                  * pointers to the beginning.  This improves cache hit
559                  * stats.
560                  *
561                  * We need both locks to modify both pointers, and there
562                  * must also not be a write in progress or the uiomove()
563                  * in the write might block and temporarily release
564                  * its wlock, then reacquire and update windex.  We are
565                  * only serialized against reads, not writes.
566                  *
567                  * XXX should we even bother resetting the indices?  It
568                  *     might actually be more cache efficient not to.
569                  */
570                 if (rpipe->pipe_buffer.rindex == rpipe->pipe_buffer.windex &&
571                     rpipe->pipe_wip == 0) {
572                         rpipe->pipe_buffer.rindex = 0;
573                         rpipe->pipe_buffer.windex = 0;
574                 }
575
576                 /*
577                  * Wait for more data.
578                  *
579                  * Pipe_state can only be set if both the rlock and wlock
580                  * are held.
581                  */
582                 rpipe->pipe_state |= PIPE_WANTR;
583                 tsleep_interlock(rpipe);
584                 lwkt_reltoken(&wlock);
585                 error = tsleep(rpipe, PCATCH, "piperd", 0);
586                 if (error)
587                         break;
588         }
589         pipe_end_uio(rpipe, &rpipe->pipe_rip);
590
591         /*
592          * Uptime last access time
593          */
594         if (error == 0 && nread)
595                 vfs_timestamp(&rpipe->pipe_atime);
596
597         /*
598          * If we drained the FIFO more then half way then handle
599          * write blocking hysteresis.
600          *
601          * Note that PIPE_WANTW cannot be set by the writer without
602          * it holding both rlock and wlock, so we can test it
603          * while holding just rlock.
604          */
605         if (notify_writer) {
606                 if (rpipe->pipe_state & PIPE_WANTW) {
607                         lwkt_gettoken(&wlock, &rpipe->pipe_wlock);
608                         if (rpipe->pipe_state & PIPE_WANTW) {
609                                 rpipe->pipe_state &= ~PIPE_WANTW;
610                                 lwkt_reltoken(&wlock);
611                                 wakeup(rpipe);
612                         } else {
613                                 lwkt_reltoken(&wlock);
614                         }
615                 }
616         }
617         size = rpipe->pipe_buffer.windex - rpipe->pipe_buffer.rindex;
618         lwkt_reltoken(&rlock);
619
620         /*
621          * If enough space is available in buffer then wakeup sel writers?
622          */
623         if ((rpipe->pipe_buffer.size - size) >= PIPE_BUF)
624                 pipeselwakeup(rpipe);
625         pipe_rel_mplock(&mpsave);
626         return (error);
627 }
628
629 /*
630  * MPALMOSTSAFE - acquires mplock
631  */
632 static int
633 pipe_write(struct file *fp, struct uio *uio, struct ucred *cred, int fflags)
634 {
635         int error;
636         int orig_resid;
637         int nbio;
638         struct pipe *wpipe, *rpipe;
639         lwkt_tokref rlock;
640         lwkt_tokref wlock;
641         u_int windex;
642         u_int space;
643         u_int wcount;
644         int mpsave;
645
646         pipe_get_mplock(&mpsave);
647
648         /*
649          * Writes go to the peer.  The peer will always exist.
650          */
651         rpipe = (struct pipe *) fp->f_data;
652         wpipe = rpipe->pipe_peer;
653         lwkt_gettoken(&wlock, &wpipe->pipe_wlock);
654         if (wpipe->pipe_state & PIPE_WEOF) {
655                 pipe_rel_mplock(&mpsave);
656                 lwkt_reltoken(&wlock);
657                 return (EPIPE);
658         }
659
660         /*
661          * Degenerate case (EPIPE takes prec)
662          */
663         if (uio->uio_resid == 0) {
664                 pipe_rel_mplock(&mpsave);
665                 lwkt_reltoken(&wlock);
666                 return(0);
667         }
668
669         /*
670          * Writes are serialized (start_uio must be called with wlock)
671          */
672         error = pipe_start_uio(wpipe, &wpipe->pipe_wip);
673         if (error) {
674                 pipe_rel_mplock(&mpsave);
675                 lwkt_reltoken(&wlock);
676                 return (error);
677         }
678
679         if (fflags & O_FBLOCKING)
680                 nbio = 0;
681         else if (fflags & O_FNONBLOCKING)
682                 nbio = 1;
683         else if (fp->f_flag & O_NONBLOCK)
684                 nbio = 1;
685         else
686                 nbio = 0;
687
688         /*
689          * If it is advantageous to resize the pipe buffer, do
690          * so.  We are write-serialized so we can block safely.
691          */
692         if ((wpipe->pipe_buffer.size <= PIPE_SIZE) &&
693             (pipe_nbig < pipe_maxbig) &&
694             wpipe->pipe_wantwcnt > 4 &&
695             (wpipe->pipe_buffer.rindex == wpipe->pipe_buffer.windex)) {
696                 /* 
697                  * Recheck after lock.
698                  */
699                 lwkt_gettoken(&rlock, &wpipe->pipe_rlock);
700                 if ((wpipe->pipe_buffer.size <= PIPE_SIZE) &&
701                     (pipe_nbig < pipe_maxbig) &&
702                     (wpipe->pipe_buffer.rindex == wpipe->pipe_buffer.windex)) {
703                         if (pipespace(wpipe, BIG_PIPE_SIZE) == 0) {
704                                 ++pipe_bigcount;
705                                 pipe_nbig++;
706                         }
707                 }
708                 lwkt_reltoken(&rlock);
709         }
710
711         orig_resid = uio->uio_resid;
712         wcount = 0;
713
714         while (uio->uio_resid) {
715                 if (wpipe->pipe_state & PIPE_WEOF) {
716                         error = EPIPE;
717                         break;
718                 }
719
720                 windex = wpipe->pipe_buffer.windex &
721                          (wpipe->pipe_buffer.size - 1);
722                 space = wpipe->pipe_buffer.size -
723                         (wpipe->pipe_buffer.windex - wpipe->pipe_buffer.rindex);
724                 cpu_lfence();
725
726                 /* Writes of size <= PIPE_BUF must be atomic. */
727                 if ((space < uio->uio_resid) && (orig_resid <= PIPE_BUF))
728                         space = 0;
729
730                 /* 
731                  * Write to fill, read size handles write hysteresis.  Also
732                  * additional restrictions can cause select-based non-blocking
733                  * writes to spin.
734                  */
735                 if (space > 0) {
736                         u_int segsize;
737
738                         /*
739                          * Transfer size is minimum of uio transfer
740                          * and free space in pipe buffer.
741                          *
742                          * Limit each uiocopy to no more then PIPE_SIZE
743                          * so we can keep the gravy train going on a
744                          * SMP box.  This doubles the performance for
745                          * write sizes > 16K.  Otherwise large writes
746                          * wind up doing an inefficient synchronous
747                          * ping-pong.
748                          */
749                         if (space > (u_int)uio->uio_resid)
750                                 space = (u_int)uio->uio_resid;
751                         if (space > PIPE_SIZE)
752                                 space = PIPE_SIZE;
753
754                         /*
755                          * First segment to transfer is minimum of
756                          * transfer size and contiguous space in
757                          * pipe buffer.  If first segment to transfer
758                          * is less than the transfer size, we've got
759                          * a wraparound in the buffer.
760                          */
761                         segsize = wpipe->pipe_buffer.size - windex;
762                         if (segsize > space)
763                                 segsize = space;
764
765                         /*
766                          * If this is the first loop and the reader is
767                          * blocked, do a preemptive wakeup of the reader.
768                          *
769                          * This works for both SMP and UP.  On SMP the IPI
770                          * latency plus the wlock interlock on the reader
771                          * side is the fastest way to get the reader going.
772                          * (The scheduler will hard loop on lock tokens).
773                          *
774                          * NOTE: We can't clear WANTR here without acquiring
775                          * the rlock, which we don't want to do here!
776                          */
777                         if (wpipe->pipe_state & PIPE_WANTR)
778                                 wakeup(wpipe);
779
780                         /*
781                          * Transfer first segment
782                          */
783                         error = uiomove(&wpipe->pipe_buffer.buffer[windex],
784                                         segsize, uio);
785                         cpu_mfence();
786                         wpipe->pipe_buffer.windex += segsize;
787
788                         if (error == 0 && segsize < space) {
789                                 /*
790                                  * Transfer remaining part now, to
791                                  * support atomic writes.  Wraparound
792                                  * happened.
793                                  */
794                                 segsize = space - segsize;
795                                 error = uiomove(&wpipe->pipe_buffer.buffer[0],
796                                                 segsize, uio);
797                                 cpu_mfence();
798                                 wpipe->pipe_buffer.windex += segsize;
799                         }
800                         if (error)
801                                 break;
802                         wcount += space;
803                         continue;
804                 }
805
806                 /*
807                  * We need both the rlock and the wlock to interlock against
808                  * the EOF, WANTW, and size checks, and to modify pipe_state.
809                  *
810                  * These are token locks so we do not have to worry about
811                  * deadlocks.
812                  */
813                 lwkt_gettoken(&rlock, &wpipe->pipe_rlock);
814
815                 /*
816                  * If the "read-side" has been blocked, wake it up now
817                  * and yield to let it drain synchronously rather
818                  * then block.
819                  */
820                 if (wpipe->pipe_state & PIPE_WANTR) {
821                         wpipe->pipe_state &= ~PIPE_WANTR;
822                         wakeup(wpipe);
823                 }
824
825                 /*
826                  * don't block on non-blocking I/O
827                  */
828                 if (nbio) {
829                         lwkt_reltoken(&rlock);
830                         error = EAGAIN;
831                         break;
832                 }
833
834                 /*
835                  * re-test whether we have to block in the writer after
836                  * acquiring both locks, in case the reader opened up
837                  * some space.
838                  */
839                 space = wpipe->pipe_buffer.size -
840                         (wpipe->pipe_buffer.windex - wpipe->pipe_buffer.rindex);
841                 cpu_lfence();
842                 if ((space < uio->uio_resid) && (orig_resid <= PIPE_BUF))
843                         space = 0;
844
845                 /*
846                  * We have no more space and have something to offer,
847                  * wake up select/poll.
848                  */
849                 if (space == 0) {
850                         pipeselwakeup(wpipe);
851                         ++wpipe->pipe_wantwcnt;
852                         wpipe->pipe_state |= PIPE_WANTW;
853                         error = tsleep(wpipe, PCATCH, "pipewr", 0);
854                 }
855                 lwkt_reltoken(&rlock);
856
857                 /*
858                  * Break out if we errored or the read side wants us to go
859                  * away.
860                  */
861                 if (error)
862                         break;
863                 if (wpipe->pipe_state & PIPE_WEOF) {
864                         error = EPIPE;
865                         break;
866                 }
867         }
868         pipe_end_uio(wpipe, &wpipe->pipe_wip);
869
870         /*
871          * If we have put any characters in the buffer, we wake up
872          * the reader.
873          *
874          * Both rlock and wlock are required to be able to modify pipe_state.
875          */
876         if (wpipe->pipe_buffer.windex != wpipe->pipe_buffer.rindex) {
877                 if (wpipe->pipe_state & PIPE_WANTR) {
878                         lwkt_gettoken(&rlock, &wpipe->pipe_rlock);
879                         if (wpipe->pipe_state & PIPE_WANTR) {
880                                 wpipe->pipe_state &= ~PIPE_WANTR;
881                                 lwkt_reltoken(&rlock);
882                                 wakeup(wpipe);
883                         } else {
884                                 lwkt_reltoken(&rlock);
885                         }
886                 }
887         }
888
889         /*
890          * Don't return EPIPE if I/O was successful
891          */
892         if ((wpipe->pipe_buffer.rindex == wpipe->pipe_buffer.windex) &&
893             (uio->uio_resid == 0) &&
894             (error == EPIPE)) {
895                 error = 0;
896         }
897
898         if (error == 0)
899                 vfs_timestamp(&wpipe->pipe_mtime);
900
901         /*
902          * We have something to offer,
903          * wake up select/poll.
904          */
905         space = wpipe->pipe_buffer.windex - wpipe->pipe_buffer.rindex;
906         lwkt_reltoken(&wlock);
907         if (space)
908                 pipeselwakeup(wpipe);
909         pipe_rel_mplock(&mpsave);
910         return (error);
911 }
912
913 /*
914  * MPALMOSTSAFE - acquires mplock
915  *
916  * we implement a very minimal set of ioctls for compatibility with sockets.
917  */
918 int
919 pipe_ioctl(struct file *fp, u_long cmd, caddr_t data, struct ucred *cred)
920 {
921         struct pipe *mpipe;
922         int error;
923
924         get_mplock();
925         mpipe = (struct pipe *)fp->f_data;
926
927         switch (cmd) {
928         case FIOASYNC:
929                 if (*(int *)data) {
930                         mpipe->pipe_state |= PIPE_ASYNC;
931                 } else {
932                         mpipe->pipe_state &= ~PIPE_ASYNC;
933                 }
934                 error = 0;
935                 break;
936         case FIONREAD:
937                 *(int *)data = mpipe->pipe_buffer.windex -
938                                 mpipe->pipe_buffer.rindex;
939                 error = 0;
940                 break;
941         case FIOSETOWN:
942                 error = fsetown(*(int *)data, &mpipe->pipe_sigio);
943                 break;
944         case FIOGETOWN:
945                 *(int *)data = fgetown(mpipe->pipe_sigio);
946                 error = 0;
947                 break;
948         case TIOCSPGRP:
949                 /* This is deprecated, FIOSETOWN should be used instead. */
950                 error = fsetown(-(*(int *)data), &mpipe->pipe_sigio);
951                 break;
952
953         case TIOCGPGRP:
954                 /* This is deprecated, FIOGETOWN should be used instead. */
955                 *(int *)data = -fgetown(mpipe->pipe_sigio);
956                 error = 0;
957                 break;
958         default:
959                 error = ENOTTY;
960                 break;
961         }
962         rel_mplock();
963         return (error);
964 }
965
966 /*
967  * MPALMOSTSAFE - acquires mplock
968  */
969 int
970 pipe_poll(struct file *fp, int events, struct ucred *cred)
971 {
972         struct pipe *rpipe;
973         struct pipe *wpipe;
974         int revents = 0;
975         u_int space;
976         int mpsave;
977
978         pipe_get_mplock(&mpsave);
979         rpipe = (struct pipe *)fp->f_data;
980         wpipe = rpipe->pipe_peer;
981         if (events & (POLLIN | POLLRDNORM)) {
982                 if ((rpipe->pipe_buffer.windex != rpipe->pipe_buffer.rindex) ||
983                     (rpipe->pipe_state & PIPE_REOF)) {
984                         revents |= events & (POLLIN | POLLRDNORM);
985                 }
986         }
987
988         if (events & (POLLOUT | POLLWRNORM)) {
989                 if (wpipe == NULL || (wpipe->pipe_state & PIPE_WEOF)) {
990                         revents |= events & (POLLOUT | POLLWRNORM);
991                 } else {
992                         space = wpipe->pipe_buffer.windex -
993                                 wpipe->pipe_buffer.rindex;
994                         space = wpipe->pipe_buffer.size - space;
995                         if (space >= PIPE_BUF)
996                                 revents |= events & (POLLOUT | POLLWRNORM);
997                 }
998         }
999
1000         if ((rpipe->pipe_state & PIPE_REOF) ||
1001             (wpipe == NULL) ||
1002             (wpipe->pipe_state & PIPE_WEOF))
1003                 revents |= POLLHUP;
1004
1005         if (revents == 0) {
1006                 if (events & (POLLIN | POLLRDNORM)) {
1007                         selrecord(curthread, &rpipe->pipe_sel);
1008                         rpipe->pipe_state |= PIPE_SEL;
1009                 }
1010
1011                 if (events & (POLLOUT | POLLWRNORM)) {
1012                         selrecord(curthread, &wpipe->pipe_sel);
1013                         wpipe->pipe_state |= PIPE_SEL;
1014                 }
1015         }
1016         pipe_rel_mplock(&mpsave);
1017         return (revents);
1018 }
1019
1020 /*
1021  * MPALMOSTSAFE - acquires mplock
1022  */
1023 static int
1024 pipe_stat(struct file *fp, struct stat *ub, struct ucred *cred)
1025 {
1026         struct pipe *pipe;
1027         int mpsave;
1028
1029         pipe_get_mplock(&mpsave);
1030         pipe = (struct pipe *)fp->f_data;
1031
1032         bzero((caddr_t)ub, sizeof(*ub));
1033         ub->st_mode = S_IFIFO;
1034         ub->st_blksize = pipe->pipe_buffer.size;
1035         ub->st_size = pipe->pipe_buffer.windex - pipe->pipe_buffer.rindex;
1036         ub->st_blocks = (ub->st_size + ub->st_blksize - 1) / ub->st_blksize;
1037         ub->st_atimespec = pipe->pipe_atime;
1038         ub->st_mtimespec = pipe->pipe_mtime;
1039         ub->st_ctimespec = pipe->pipe_ctime;
1040         /*
1041          * Left as 0: st_dev, st_ino, st_nlink, st_uid, st_gid, st_rdev,
1042          * st_flags, st_gen.
1043          * XXX (st_dev, st_ino) should be unique.
1044          */
1045         pipe_rel_mplock(&mpsave);
1046         return (0);
1047 }
1048
1049 /*
1050  * MPALMOSTSAFE - acquires mplock
1051  */
1052 static int
1053 pipe_close(struct file *fp)
1054 {
1055         struct pipe *cpipe;
1056
1057         get_mplock();
1058         cpipe = (struct pipe *)fp->f_data;
1059         fp->f_ops = &badfileops;
1060         fp->f_data = NULL;
1061         funsetown(cpipe->pipe_sigio);
1062         pipeclose(cpipe);
1063         rel_mplock();
1064         return (0);
1065 }
1066
1067 /*
1068  * Shutdown one or both directions of a full-duplex pipe.
1069  *
1070  * MPALMOSTSAFE - acquires mplock
1071  */
1072 static int
1073 pipe_shutdown(struct file *fp, int how)
1074 {
1075         struct pipe *rpipe;
1076         struct pipe *wpipe;
1077         int error = EPIPE;
1078         lwkt_tokref rpipe_rlock;
1079         lwkt_tokref rpipe_wlock;
1080         lwkt_tokref wpipe_rlock;
1081         lwkt_tokref wpipe_wlock;
1082         int mpsave;
1083
1084         pipe_get_mplock(&mpsave);
1085         rpipe = (struct pipe *)fp->f_data;
1086         wpipe = rpipe->pipe_peer;
1087
1088         /*
1089          * We modify pipe_state on both pipes, which means we need
1090          * all four tokens!
1091          */
1092         lwkt_gettoken(&rpipe_rlock, &rpipe->pipe_rlock);
1093         lwkt_gettoken(&rpipe_wlock, &rpipe->pipe_wlock);
1094         lwkt_gettoken(&wpipe_rlock, &wpipe->pipe_rlock);
1095         lwkt_gettoken(&wpipe_wlock, &wpipe->pipe_wlock);
1096
1097         switch(how) {
1098         case SHUT_RDWR:
1099         case SHUT_RD:
1100                 rpipe->pipe_state |= PIPE_REOF;
1101                 wpipe->pipe_state |= PIPE_WEOF;
1102                 if (rpipe->pipe_state & PIPE_WANTR) {
1103                         rpipe->pipe_state &= ~PIPE_WANTR;
1104                         wakeup(rpipe);
1105                 }
1106                 if (wpipe->pipe_state & PIPE_WANTW) {
1107                         wpipe->pipe_state &= ~PIPE_WANTW;
1108                         wakeup(wpipe);
1109                 }
1110                 pipeselwakeup(rpipe);
1111                 error = 0;
1112                 if (how == SHUT_RD)
1113                         break;
1114                 /* fall through */
1115         case SHUT_WR:
1116                 wpipe->pipe_state |= PIPE_WEOF;
1117                 rpipe->pipe_state |= PIPE_REOF;
1118                 if (wpipe->pipe_state & PIPE_WANTW) {
1119                         wpipe->pipe_state &= ~PIPE_WANTW;
1120                         wakeup(wpipe);
1121                 }
1122                 if (rpipe->pipe_state & PIPE_WANTR) {
1123                         rpipe->pipe_state &= ~PIPE_WANTR;
1124                         wakeup(rpipe);
1125                 }
1126                 pipeselwakeup(wpipe);
1127                 error = 0;
1128                 break;
1129         }
1130
1131         lwkt_reltoken(&rpipe_rlock);
1132         lwkt_reltoken(&rpipe_wlock);
1133         lwkt_reltoken(&wpipe_rlock);
1134         lwkt_reltoken(&wpipe_wlock);
1135
1136         pipe_rel_mplock(&mpsave);
1137         return (error);
1138 }
1139
1140 static void
1141 pipe_free_kmem(struct pipe *cpipe)
1142 {
1143         if (cpipe->pipe_buffer.buffer != NULL) {
1144                 if (cpipe->pipe_buffer.size > PIPE_SIZE)
1145                         --pipe_nbig;
1146                 kmem_free(&kernel_map,
1147                         (vm_offset_t)cpipe->pipe_buffer.buffer,
1148                         cpipe->pipe_buffer.size);
1149                 cpipe->pipe_buffer.buffer = NULL;
1150                 cpipe->pipe_buffer.object = NULL;
1151         }
1152 }
1153
1154 /*
1155  * Close the pipe.  The slock must be held to interlock against simultanious
1156  * closes.  The rlock and wlock must be held to adjust the pipe_state.
1157  */
1158 static void
1159 pipeclose(struct pipe *cpipe)
1160 {
1161         globaldata_t gd;
1162         struct pipe *ppipe;
1163         lwkt_tokref cpipe_rlock;
1164         lwkt_tokref cpipe_wlock;
1165         lwkt_tokref ppipe_rlock;
1166         lwkt_tokref ppipe_wlock;
1167
1168         if (cpipe == NULL)
1169                 return;
1170
1171         /*
1172          * The slock may not have been allocated yet (close during
1173          * initialization)
1174          *
1175          * We need both the read and write tokens to modify pipe_state.
1176          */
1177         if (cpipe->pipe_slock)
1178                 lockmgr(cpipe->pipe_slock, LK_EXCLUSIVE);
1179         lwkt_gettoken(&cpipe_rlock, &cpipe->pipe_rlock);
1180         lwkt_gettoken(&cpipe_wlock, &cpipe->pipe_wlock);
1181
1182         /*
1183          * Set our state, wakeup anyone waiting in select, and
1184          * wakeup anyone blocked on our pipe.
1185          */
1186         cpipe->pipe_state |= PIPE_CLOSED | PIPE_REOF | PIPE_WEOF;
1187         pipeselwakeup(cpipe);
1188         if (cpipe->pipe_state & (PIPE_WANTR | PIPE_WANTW)) {
1189                 cpipe->pipe_state &= ~(PIPE_WANTR | PIPE_WANTW);
1190                 wakeup(cpipe);
1191         }
1192
1193         /*
1194          * Disconnect from peer
1195          */
1196         if ((ppipe = cpipe->pipe_peer) != NULL) {
1197                 lwkt_gettoken(&ppipe_rlock, &ppipe->pipe_rlock);
1198                 lwkt_gettoken(&ppipe_wlock, &ppipe->pipe_wlock);
1199                 ppipe->pipe_state |= PIPE_REOF;
1200                 pipeselwakeup(ppipe);
1201                 if (ppipe->pipe_state & (PIPE_WANTR | PIPE_WANTW)) {
1202                         ppipe->pipe_state &= ~(PIPE_WANTR | PIPE_WANTW);
1203                         wakeup(ppipe);
1204                 }
1205                 if (SLIST_FIRST(&ppipe->pipe_sel.si_note)) {
1206                         get_mplock();
1207                         KNOTE(&ppipe->pipe_sel.si_note, 0);
1208                         rel_mplock();
1209                 }
1210                 lwkt_reltoken(&ppipe_rlock);
1211                 lwkt_reltoken(&ppipe_wlock);
1212         }
1213
1214         /*
1215          * If the peer is also closed we can free resources for both
1216          * sides, otherwise we leave our side intact to deal with any
1217          * races (since we only have the slock).
1218          */
1219         if (ppipe && (ppipe->pipe_state & PIPE_CLOSED)) {
1220                 cpipe->pipe_peer = NULL;
1221                 ppipe->pipe_peer = NULL;
1222                 ppipe->pipe_slock = NULL;       /* we will free the slock */
1223                 pipeclose(ppipe);
1224                 ppipe = NULL;
1225         }
1226
1227         lwkt_reltoken(&cpipe_rlock);
1228         lwkt_reltoken(&cpipe_wlock);
1229         if (cpipe->pipe_slock)
1230                 lockmgr(cpipe->pipe_slock, LK_RELEASE);
1231
1232         /*
1233          * If we disassociated from our peer we can free resources
1234          */
1235         if (ppipe == NULL) {
1236                 gd = mycpu;
1237                 if (cpipe->pipe_slock) {
1238                         kfree(cpipe->pipe_slock, M_PIPE);
1239                         cpipe->pipe_slock = NULL;
1240                 }
1241                 if (gd->gd_pipeqcount >= pipe_maxcache ||
1242                     cpipe->pipe_buffer.size != PIPE_SIZE
1243                 ) {
1244                         pipe_free_kmem(cpipe);
1245                         kfree(cpipe, M_PIPE);
1246                 } else {
1247                         cpipe->pipe_state = 0;
1248                         cpipe->pipe_peer = gd->gd_pipeq;
1249                         gd->gd_pipeq = cpipe;
1250                         ++gd->gd_pipeqcount;
1251                 }
1252         }
1253 }
1254
1255 /*
1256  * MPALMOSTSAFE - acquires mplock
1257  */
1258 static int
1259 pipe_kqfilter(struct file *fp, struct knote *kn)
1260 {
1261         struct pipe *cpipe;
1262
1263         get_mplock();
1264         cpipe = (struct pipe *)kn->kn_fp->f_data;
1265
1266         switch (kn->kn_filter) {
1267         case EVFILT_READ:
1268                 kn->kn_fop = &pipe_rfiltops;
1269                 break;
1270         case EVFILT_WRITE:
1271                 kn->kn_fop = &pipe_wfiltops;
1272                 cpipe = cpipe->pipe_peer;
1273                 if (cpipe == NULL) {
1274                         /* other end of pipe has been closed */
1275                         rel_mplock();
1276                         return (EPIPE);
1277                 }
1278                 break;
1279         default:
1280                 return (1);
1281         }
1282         kn->kn_hook = (caddr_t)cpipe;
1283
1284         SLIST_INSERT_HEAD(&cpipe->pipe_sel.si_note, kn, kn_selnext);
1285         rel_mplock();
1286         return (0);
1287 }
1288
1289 static void
1290 filt_pipedetach(struct knote *kn)
1291 {
1292         struct pipe *cpipe = (struct pipe *)kn->kn_hook;
1293
1294         SLIST_REMOVE(&cpipe->pipe_sel.si_note, kn, knote, kn_selnext);
1295 }
1296
1297 /*ARGSUSED*/
1298 static int
1299 filt_piperead(struct knote *kn, long hint)
1300 {
1301         struct pipe *rpipe = (struct pipe *)kn->kn_fp->f_data;
1302
1303         kn->kn_data = rpipe->pipe_buffer.windex - rpipe->pipe_buffer.rindex;
1304
1305         /* XXX RACE */
1306         if (rpipe->pipe_state & PIPE_REOF) {
1307                 kn->kn_flags |= EV_EOF; 
1308                 return (1);
1309         }
1310         return (kn->kn_data > 0);
1311 }
1312
1313 /*ARGSUSED*/
1314 static int
1315 filt_pipewrite(struct knote *kn, long hint)
1316 {
1317         struct pipe *rpipe = (struct pipe *)kn->kn_fp->f_data;
1318         struct pipe *wpipe = rpipe->pipe_peer;
1319         u_int32_t space;
1320
1321         /* XXX RACE */
1322         if ((wpipe == NULL) || (wpipe->pipe_state & PIPE_WEOF)) {
1323                 kn->kn_data = 0;
1324                 kn->kn_flags |= EV_EOF; 
1325                 return (1);
1326         }
1327         space = wpipe->pipe_buffer.windex -
1328                 wpipe->pipe_buffer.rindex;
1329         space = wpipe->pipe_buffer.size - space;
1330         kn->kn_data = space;
1331         return (kn->kn_data >= PIPE_BUF);
1332 }