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