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