xref: /xv6-public/pipe.c (revision 3ce16470)
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 || (*f1 = filealloc()) == 0)
29     goto bad;
30   if((p = (struct pipe*)kalloc(PAGE)) == 0)
31     goto bad;
32   p->readopen = 1;
33   p->writeopen = 1;
34   p->writep = 0;
35   p->readp = 0;
36   initlock(&p->lock, "pipe");
37   (*f0)->type = FD_PIPE;
38   (*f0)->readable = 1;
39   (*f0)->writable = 0;
40   (*f0)->pipe = p;
41   (*f1)->type = FD_PIPE;
42   (*f1)->readable = 0;
43   (*f1)->writable = 1;
44   (*f1)->pipe = p;
45   return 0;
46 
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 pipe_close(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   release(&p->lock);
73 
74   if(p->readopen == 0 && p->writeopen == 0)
75     kfree((char*)p, PAGE);
76 }
77 
78 //PAGEBREAK: 20
79 int
80 pipe_write(struct pipe *p, char *addr, int n)
81 {
82   int i;
83 
84   acquire(&p->lock);
85   for(i = 0; i < n; i++){
86     while(((p->writep + 1) % PIPESIZE) == p->readp){
87       if(p->readopen == 0 || cp->killed){
88         release(&p->lock);
89         return -1;
90       }
91       wakeup(&p->readp);
92       sleep(&p->writep, &p->lock);
93     }
94     p->data[p->writep] = addr[i];
95     p->writep = (p->writep + 1) % PIPESIZE;
96   }
97   wakeup(&p->readp);
98   release(&p->lock);
99   return i;
100 }
101 
102 int
103 pipe_read(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];
119     p->readp = (p->readp + 1) % PIPESIZE;
120   }
121   wakeup(&p->writep);
122   release(&p->lock);
123   return i;
124 }
125