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 release(&p->lock); 73 74 if(p->readopen == 0 && p->writeopen == 0) 75 kfree((char*)p, PAGE); 76 } 77 78 //PAGEBREAK: 30 79 int 80 pipewrite(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 == p->readp + PIPESIZE) { 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++ % PIPESIZE] = addr[i]; 95 } 96 wakeup(&p->readp); 97 release(&p->lock); 98 return i; 99 } 100 101 int 102 piperead(struct pipe *p, char *addr, int n) 103 { 104 int i; 105 106 acquire(&p->lock); 107 while(p->readp == p->writep && p->writeopen){ 108 if(cp->killed){ 109 release(&p->lock); 110 return -1; 111 } 112 sleep(&p->readp, &p->lock); 113 } 114 for(i = 0; i < n; i++){ 115 if(p->readp == p->writep) 116 break; 117 addr[i] = p->data[p->readp++ % PIPESIZE]; 118 } 119 wakeup(&p->writep); 120 release(&p->lock); 121 return i; 122 } 123