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