xref: /xv6-public/pipe.c (revision ea6e3709)
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 
49  oops:
50   if(p)
51     kfree((char*) p, PAGE);
52   if(*f0){
53     (*f0)->type = FD_NONE;
54     fileclose(*f0);
55   }
56   if(*f1){
57     (*f1)->type = FD_NONE;
58     fileclose(*f1);
59   }
60   return -1;
61 }
62 
63 void
64 pipe_close(struct pipe *p, int writable)
65 {
66   acquire(&p->lock);
67   if(writable){
68     p->writeopen = 0;
69     wakeup(&p->readp);
70   } else {
71     p->readopen = 0;
72     wakeup(&p->writep);
73   }
74   release(&p->lock);
75 
76   if(p->readopen == 0 && p->writeopen == 0)
77     kfree((char*) p, PAGE);
78 }
79 
80 //PAGEBREAK: 20
81 int
82 pipe_write(struct pipe *p, char *addr, int n)
83 {
84   int i;
85 
86   acquire(&p->lock);
87   for(i = 0; i < n; i++){
88     while(((p->writep + 1) % PIPESIZE) == p->readp){
89       if(p->readopen == 0 || cp->killed){
90         release(&p->lock);
91         return -1;
92       }
93       wakeup(&p->readp);
94       sleep(&p->writep, &p->lock);
95     }
96     p->data[p->writep] = addr[i];
97     p->writep = (p->writep + 1) % PIPESIZE;
98   }
99   wakeup(&p->readp);
100   release(&p->lock);
101   return i;
102 }
103 
104 int
105 pipe_read(struct pipe *p, char *addr, int n)
106 {
107   int i;
108 
109   acquire(&p->lock);
110   while(p->readp == p->writep){
111     if(p->writeopen == 0 || cp->killed){
112       release(&p->lock);
113       return 0;
114     }
115     sleep(&p->readp, &p->lock);
116   }
117   for(i = 0; i < n; i++){
118     if(p->readp == p->writep)
119       break;
120     addr[i] = p->data[p->readp];
121     p->readp = (p->readp + 1) % PIPESIZE;
122   }
123   wakeup(&p->writep);
124   release(&p->lock);
125   return i;
126 }
127