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