xref: /xv6-public/pipe.c (revision 3bbbaca1)
1 #include "types.h"
2 #include "param.h"
3 #include "x86.h"
4 #include "mmu.h"
5 #include "proc.h"
6 #include "defs.h"
7 #include "file.h"
8 #include "spinlock.h"
9 
10 #define PIPESIZE 512
11 
12 struct pipe {
13   int readopen;   // read fd is still open
14   int writeopen;  // write fd is still open
15   int writep;     // next index to write
16   int readp;      // next index to read
17   struct spinlock lock;
18   char data[PIPESIZE];
19 };
20 
21 int
22 pipe_alloc(struct file **f0, struct file **f1)
23 {
24   struct pipe *p;
25 
26   p = 0;
27   *f0 = *f1 = 0;
28   if((*f0 = filealloc()) == 0)
29     goto oops;
30   if((*f1 = filealloc()) == 0)
31     goto oops;
32   if((p = (struct pipe*) kalloc(PAGE)) == 0)
33     goto oops;
34   p->readopen = 1;
35   p->writeopen = 1;
36   p->writep = 0;
37   p->readp = 0;
38   initlock(&p->lock, "pipe");
39   (*f0)->type = FD_PIPE;
40   (*f0)->readable = 1;
41   (*f0)->writable = 0;
42   (*f0)->pipe = p;
43   (*f1)->type = FD_PIPE;
44   (*f1)->readable = 0;
45   (*f1)->writable = 1;
46   (*f1)->pipe = p;
47   return 0;
48  oops:
49   if(p)
50     kfree((char*) p, PAGE);
51   if(*f0){
52     (*f0)->type = FD_NONE;
53     fileclose(*f0);
54   }
55   if(*f1){
56     (*f1)->type = FD_NONE;
57     fileclose(*f1);
58   }
59   return -1;
60 }
61 
62 void
63 pipe_close(struct pipe *p, int writable)
64 {
65   acquire(&p->lock);
66 
67   if(writable){
68     p->writeopen = 0;
69     wakeup(&p->readp);
70   } else {
71     p->readopen = 0;
72     wakeup(&p->writep);
73   }
74 
75   release(&p->lock);
76 
77   if(p->readopen == 0 && p->writeopen == 0)
78     kfree((char*) p, PAGE);
79 }
80 
81 int
82 pipe_write(struct pipe *p, char *addr, int n)
83 {
84   int i;
85 
86   acquire(&p->lock);
87 
88   for(i = 0; i < n; i++){
89     while(((p->writep + 1) % PIPESIZE) == p->readp){
90       if(p->readopen == 0 || curproc[cpu()]->killed){
91         release(&p->lock);
92         return -1;
93       }
94       wakeup(&p->readp);
95       sleep(&p->writep, &p->lock);
96     }
97     p->data[p->writep] = addr[i];
98     p->writep = (p->writep + 1) % PIPESIZE;
99   }
100 
101   release(&p->lock);
102   wakeup(&p->readp);
103   return i;
104 }
105 
106 int
107 pipe_read(struct pipe *p, char *addr, int n)
108 {
109   int i;
110 
111   acquire(&p->lock);
112 
113   while(p->readp == p->writep){
114     if(p->writeopen == 0 || curproc[cpu()]->killed){
115       release(&p->lock);
116       return 0;
117     }
118     sleep(&p->readp, &p->lock);
119   }
120 
121   for(i = 0; i < n; i++){
122     if(p->readp == p->writep)
123       break;
124     addr[i] = p->data[p->readp];
125     p->readp = (p->readp + 1) % PIPESIZE;
126   }
127 
128   release(&p->lock);
129   wakeup(&p->writep);
130   return i;
131 }
132