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