6 #include "9.h" /* for cacheFlush */
8 typedef struct FreeList FreeList;
9 typedef struct BAddr BAddr;
16 * Store data to the memory cache in c->size blocks
17 * with the block zero extended to fill it out. When writing to
18 * Venti, the block will be zero truncated. The walker will also check
19 * that the block fits within psize or dsize as the case may be.
29 int size; /* block size */
30 int ndmap; /* size of per-block dirty pointer map used in blockWrite */
32 u32int now; /* ticks for usage timestamps */
33 Block **heads; /* hash table for finding address */
34 int nheap; /* number of available victims */
35 Block **heap; /* heap for locating victims */
36 long nblocks; /* number of blocks allocated */
37 Block *blocks; /* array of block descriptors */
38 u8int *mem; /* memory for all block data & blists */
43 int ndirty; /* number of dirty blocks in the cache */
44 int maxdirty; /* max number of dirty blocks */
51 Rendez die; /* daemon threads should die when QLock != nil */
80 int recurse; /* for block unlink */
83 int index; /* -1 indicates not valid */
85 uchar score[VtScoreSize];
86 uchar entry[VtEntrySize];
99 u32int last; /* last block allocated */
100 u32int end; /* end of data partition */
101 u32int nused; /* number of used blocks */
102 u32int epochLow; /* low epoch when last updated nused */
105 static FreeList *flAlloc(u32int end);
106 static void flFree(FreeList *fl);
108 static Block *cacheBumpBlock(Cache *c);
109 static void heapDel(Block*);
110 static void heapIns(Block*);
111 static void cacheCheck(Cache*);
112 static void unlinkThread(void *a);
113 static void flushThread(void *a);
114 static void unlinkBody(Cache *c);
115 static int cacheFlushBlock(Cache *c);
116 static void cacheSync(void*);
117 static BList *blistAlloc(Block*);
118 static void blistFree(Cache*, BList*);
119 static void doRemoveLink(Cache*, BList*);
122 * Mapping from local block type to Venti type
124 int vtType[BtMax] = {
125 VtDataType, /* BtData | 0 */
126 VtDataType+1, /* BtData | 1 */
127 VtDataType+2, /* BtData | 2 */
128 VtDataType+3, /* BtData | 3 */
129 VtDataType+4, /* BtData | 4 */
130 VtDataType+5, /* BtData | 5 */
131 VtDataType+6, /* BtData | 6 */
132 VtDataType+7, /* BtData | 7 */
133 VtDirType, /* BtDir | 0 */
134 VtDirType+1, /* BtDir | 1 */
135 VtDirType+2, /* BtDir | 2 */
136 VtDirType+3, /* BtDir | 3 */
137 VtDirType+4, /* BtDir | 4 */
138 VtDirType+5, /* BtDir | 5 */
139 VtDirType+6, /* BtDir | 6 */
140 VtDirType+7, /* BtDir | 7 */
144 * Allocate the memory cache.
147 cacheAlloc(Disk *disk, VtConn *z, ulong nblocks, int mode)
156 c = vtmallocz(sizeof(Cache));
158 /* reasonable number of BList elements */
164 c->size = diskBlockSize(disk);
165 bwatchSetBlockSize(c->size);
166 /* round c->size up to be a nice multiple */
167 c->size = (c->size + 127) & ~127;
168 c->ndmap = (c->size/20 + 7) / 8;
169 c->nblocks = nblocks;
170 c->hashSize = nblocks;
171 c->heads = vtmallocz(c->hashSize*sizeof(Block*));
172 c->heap = vtmallocz(nblocks*sizeof(Block*));
173 c->blocks = vtmallocz(nblocks*sizeof(Block));
174 c->mem = vtmallocz(nblocks * (c->size + c->ndmap) + nbl * sizeof(BList));
175 c->baddr = vtmallocz(nblocks * sizeof(BAddr));
179 for(i = 0; i < nblocks; i++){
184 b->ioready.l = &b->lk;
189 for(i = 0; i < nbl; i++){
191 bl->next = c->blfree;
195 /* separate loop to keep blocks and blists reasonably aligned */
196 for(i = 0; i < nblocks; i++){
202 c->blrend.l = &c->lk;
204 c->maxdirty = nblocks*(DirtyPercentage*0.01);
206 c->fl = flAlloc(diskSize(disk, PartData));
208 c->unlink.l = &c->lk;
210 c->flushwait.l = &c->lk;
211 c->heapwait.l = &c->lk;
212 c->sync = periodicAlloc(cacheSync, c, 30*1000);
214 if(mode == OReadWrite){
216 proccreate(unlinkThread, c, STACK);
217 proccreate(flushThread, c, STACK);
225 * Free the whole memory cache, flushing all dirty blocks to the disk.
232 /* kill off daemon threads */
235 periodicKill(c->sync);
241 /* flush everything out */
245 while(cacheFlushBlock(c))
249 } while(c->uhead || c->ndirty);
254 for(i = 0; i < c->nblocks; i++){
255 assert(c->blocks[i].ref == 0);
263 /* don't close vtSession */
273 for(i = 0; i < c->nblocks; i++){
275 fprint(2, "%d. p=%d a=%ud %V t=%d ref=%d state=%s io=%s pc=%#p\n",
276 i, b->part, b->addr, b->score, b->l.type, b->ref,
277 bsStr(b->l.state), bioStr(b->iostate), b->pc);
291 for(i = 0; i < c->nheap; i++){
292 if(c->heap[i]->heap != i)
293 sysfatal("mis-heaped at %d: %d", i, c->heap[i]->heap);
294 if(i > 0 && c->heap[(i - 1) >> 1]->used - now > c->heap[i]->used - now)
295 sysfatal("bad heap ordering");
297 if(k < c->nheap && c->heap[i]->used - now > c->heap[k]->used - now)
298 sysfatal("bad heap ordering");
300 if(k < c->nheap && c->heap[i]->used - now > c->heap[k]->used - now)
301 sysfatal("bad heap ordering");
305 for(i = 0; i < c->nblocks; i++){
307 if(b->data != &c->mem[i * size])
308 sysfatal("mis-blocked at %d", i);
309 if(b->ref && b->heap == BadHeap){
313 if(c->nheap + refed != c->nblocks){
314 fprint(2, "%s: cacheCheck: nheap %d refed %d nblocks %ld\n", argv0, c->nheap, refed, c->nblocks);
317 assert(c->nheap + refed == c->nblocks);
319 for(i = 0; i < c->nblocks; i++){
322 if(1)fprint(2, "%s: p=%d a=%ud %V ref=%d %L\n", argv0, b->part, b->addr, b->score, b->ref, &b->l);
326 if(refed > 0)fprint(2, "%s: cacheCheck: in used %d\n", argv0, refed);
331 * locate the block with the oldest second to last use.
332 * remove it from the heap, and fix up the heap.
334 /* called with c->lk held */
336 cacheBumpBlock(Cache *c)
342 * locate the block with the oldest second to last use.
343 * remove it from the heap, and fix up the heap.
347 while(c->nheap == 0){
349 rsleep(&c->heapwait);
352 fprint(2, "%s: entire cache is busy, %d dirty "
353 "-- waking flush thread\n",
358 fprint(2, "%s: cache is okay again, %d dirty\n",
365 assert(b->heap == BadHeap);
367 assert(b->iostate != BioDirty && b->iostate != BioReading && b->iostate != BioWriting);
368 assert(b->prior == nil);
369 assert(b->uhead == nil);
372 * unchain the block from hash chain
375 *(b->prev) = b->next;
377 b->next->prev = b->prev;
382 if(0)fprint(2, "%s: dropping %d:%x:%V\n", argv0, b->part, b->addr, b->score);
383 /* set block to a reasonable state */
386 memset(&b->l, 0, sizeof(b->l));
387 b->iostate = BioEmpty;
393 * look for a particular version of the block in the memory cache.
396 _cacheLocalLookup(Cache *c, int part, u32int addr, u32int vers,
397 int waitlock, int *lockfailure)
402 h = addr % c->hashSize;
408 * look for the block in the cache
411 for(b = c->heads[h]; b != nil; b = b->next){
412 if(b->part == part && b->addr == addr)
415 if(b == nil || b->vers != vers){
419 if(!waitlock && !canqlock(&b->lk)){
452 werrstr("venti i/o error block 0x%.8ux", addr);
456 werrstr("error reading block 0x%.8ux", addr);
465 * fetch a local (on-disk) block from the memory cache.
466 * if it's not there, load it, bumping some other block.
469 _cacheLocal(Cache *c, int part, u32int addr, int mode, u32int epoch)
474 assert(part != PartVenti);
476 h = addr % c->hashSize;
479 * look for the block in the cache
482 for(b = c->heads[h]; b != nil; b = b->next){
483 if(b->part != part || b->addr != addr)
485 if(epoch && b->l.epoch != epoch){
486 fprint(2, "%s: _cacheLocal want epoch %ud got %ud\n", argv0, epoch, b->l.epoch);
488 werrstr(ELabelMismatch);
497 b = cacheBumpBlock(c);
501 localToGlobal(addr, b->score);
503 /* chain onto correct hash */
504 b->next = c->heads[h];
507 b->next->prev = &b->next;
508 b->prev = &c->heads[h];
514 * BUG: what if the epoch changes right here?
515 * In the worst case, we could end up in some weird
516 * lock loop, because the block we want no longer exists,
517 * and instead we're trying to lock a block we have no
520 * For now, I'm not going to worry about it.
523 if(0)fprint(2, "%s: cacheLocal: %d: %d %x\n", argv0, getpid(), b->part, b->addr);
528 if(part == PartData && b->iostate == BioEmpty){
529 if(!readLabel(c, &b->l, addr)){
533 blockSetIOState(b, BioLabel);
535 if(epoch && b->l.epoch != epoch){
537 fprint(2, "%s: _cacheLocal want epoch %ud got %ud\n", argv0, epoch, b->l.epoch);
538 werrstr(ELabelMismatch);
542 b->pc = getcallerpc(&c);
548 if(mode == OOverWrite)
550 * leave iostate as BioLabel because data
556 diskRead(c->disk, b);
567 blockSetIOState(b, BioEmpty);
569 werrstr("error reading block 0x%.8ux", addr);
577 cacheLocal(Cache *c, int part, u32int addr, int mode)
579 return _cacheLocal(c, part, addr, mode, 0);
583 * fetch a local (on-disk) block from the memory cache.
584 * if it's not there, load it, bumping some other block.
585 * check tag and type.
588 cacheLocalData(Cache *c, u32int addr, int type, u32int tag, int mode, u32int epoch)
592 b = _cacheLocal(c, PartData, addr, mode, epoch);
595 if(b->l.type != type || b->l.tag != tag){
596 fprint(2, "%s: cacheLocalData: addr=%d type got %d exp %d: tag got %ux exp %ux\n",
597 argv0, addr, b->l.type, type, b->l.tag, tag);
598 werrstr(ELabelMismatch);
602 b->pc = getcallerpc(&c);
607 * fetch a global (Venti) block from the memory cache.
608 * if it's not there, load it, bumping some other block.
609 * check tag and type if it's really a local block in disguise.
612 cacheGlobal(Cache *c, uchar score[VtScoreSize], int type, u32int tag, int mode)
619 addr = globalToLocal(score);
620 if(addr != NilBlock){
621 b = cacheLocalData(c, addr, type, tag, mode, 0);
623 b->pc = getcallerpc(&c);
627 h = (u32int)(score[0]|(score[1]<<8)|(score[2]<<16)|(score[3]<<24)) % c->hashSize;
630 * look for the block in the cache
633 for(b = c->heads[h]; b != nil; b = b->next){
634 if(b->part != PartVenti || memcmp(b->score, score, VtScoreSize) != 0 || b->l.type != type)
642 if(0)fprint(2, "%s: cacheGlobal %V %d\n", argv0, score, type);
644 b = cacheBumpBlock(c);
649 memmove(b->score, score, VtScoreSize);
651 /* chain onto correct hash */
652 b->next = c->heads[h];
655 b->next->prev = &b->next;
656 b->prev = &c->heads[h];
663 b->pc = getcallerpc(&c);
669 n = vtread(c->z, score, vtType[type], b->data, c->size);
670 if(n < 0 || vtsha1check(score, b->data, n) < 0){
671 blockSetIOState(b, BioVentiError);
674 "venti error reading block %V or wrong score: %r",
678 vtzeroextend(vtType[type], b->data, n, c->size);
679 blockSetIOState(b, BioClean);
685 werrstr("venti i/o error or wrong score, block %V", score);
689 werrstr("error reading block %V", b->score);
696 * allocate a new on-disk block and load it into the memory cache.
697 * BUG: if the disk is full, should we flush some of it to Venti?
699 static u32int lastAlloc;
702 cacheAllocBlock(Cache *c, int type, u32int tag, u32int epoch, u32int epochLow)
710 n = c->size / LabelSize;
715 b = cacheLocal(c, PartLabel, addr/n, OReadOnly);
717 fprint(2, "%s: cacheAllocBlock: xxx %r\n", argv0);
723 if(++addr >= fl->end){
727 werrstr("disk is full");
729 * try to avoid a continuous spew of console
733 fprint(2, "%s: cacheAllocBlock: xxx1 %r\n",
742 b = cacheLocal(c, PartLabel, addr/n, OReadOnly);
745 fprint(2, "%s: cacheAllocBlock: xxx2 %r\n", argv0);
750 if(!labelUnpack(&lab, b->data, addr%n))
752 if(lab.state == BsFree)
754 if(lab.state&BsClosed)
755 if(lab.epochClose <= epochLow || lab.epoch==lab.epochClose)
760 b = cacheLocal(c, PartData, addr, OOverWrite);
762 fprint(2, "%s: cacheAllocBlock: xxx3 %r\n", argv0);
765 assert(b->iostate == BioLabel || b->iostate == BioClean);
771 lab.epochClose = ~(u32int)0;
772 if(!blockSetLabel(b, &lab, 1)){
773 fprint(2, "%s: cacheAllocBlock: xxx4 %r\n", argv0);
777 vtzeroextend(vtType[type], b->data, 0, c->size);
778 if(0)diskWrite(c->disk, b);
780 if(0)fprint(2, "%s: fsAlloc %ud type=%d tag = %ux\n", argv0, addr, type, tag);
784 b->pc = getcallerpc(&c);
795 cacheCountUsed(Cache *c, u32int epochLow, u32int *used, u32int *total, u32int *bsize)
804 n = c->size / LabelSize;
807 if(fl->epochLow == epochLow){
815 for(addr=0; addr<fl->end; addr++){
818 b = cacheLocal(c, PartLabel, addr/n, OReadOnly);
820 fprint(2, "%s: flCountUsed: loading %ux: %r\n",
825 if(!labelUnpack(&lab, b->data, addr%n))
827 if(lab.state == BsFree)
829 if(lab.state&BsClosed)
830 if(lab.epochClose <= epochLow || lab.epoch==lab.epochClose)
837 fl->epochLow = epochLow;
850 fl = vtmallocz(sizeof(*fl));
863 cacheLocalSize(Cache *c, int part)
865 return diskSize(c->disk, part);
869 * The thread that has locked b may refer to it by
870 * multiple names. Nlock counts the number of
871 * references the locking thread holds. It will call
872 * blockPut once per reference.
875 blockDupLock(Block *b)
877 assert(b->nlock > 0);
882 * we're done with the block.
883 * unlock it. can't use it after calling this.
893 if(0)fprint(2, "%s: blockPut: %d: %d %x %d %s\n", argv0, getpid(), b->part, b->addr, c->nheap, bioStr(b->iostate));
895 if(b->iostate == BioDirty)
902 * b->nlock should probably stay at zero while
903 * the block is unlocked, but diskThread and rsleep
904 * conspire to assume that they can just qlock(&b->lk); blockPut(b),
905 * so we have to keep b->nlock set to 1 even
906 * when the block is unlocked.
908 assert(b->nlock == 0);
933 b->used = c->heap[0]->used;
943 * set the label associated with a block.
946 _blockSetLabel(Block *b, Label *l)
955 assert(b->part == PartData);
956 assert(b->iostate == BioLabel || b->iostate == BioClean || b->iostate == BioDirty);
957 lpb = c->size / LabelSize;
959 bb = cacheLocal(c, PartLabel, a, OReadWrite);
965 labelPack(l, bb->data, b->addr%lpb);
971 blockSetLabel(Block *b, Label *l, int allocating)
975 lb = _blockSetLabel(b, l);
980 * If we're allocating the block, make sure the label (bl)
981 * goes to disk before the data block (b) itself. This is to help
982 * the blocks that in turn depend on b.
984 * Suppose bx depends on (must be written out after) b.
985 * Once we write b we'll think it's safe to write bx.
986 * Bx can't get at b unless it has a valid label, though.
988 * Allocation is the only case in which having a current label
991 * - l.type is set at allocation and never changes.
992 * - l.tag is set at allocation and never changes.
993 * - l.state is not checked when we load blocks.
994 * - the archiver cares deeply about l.state being
995 * BaActive vs. BaCopied, but that's handled
996 * by direct calls to _blockSetLabel.
1000 blockDependency(b, lb, -1, nil, nil);
1006 * Record that bb must be written out before b.
1007 * If index is given, we're about to overwrite the score/e
1008 * at that index in the block. Save the old value so we
1009 * can write a safer ``old'' version of the block if pressed.
1012 blockDependency(Block *b, Block *bb, int index, uchar *score, Entry *e)
1016 if(bb->iostate == BioClean)
1020 * Dependencies for blocks containing Entry structures
1021 * or scores must always be explained. The problem with
1022 * only explaining some of them is this. Suppose we have two
1023 * dependencies for the same field, the first explained
1024 * and the second not. We try to write the block when the first
1025 * dependency is not written but the second is. We will roll back
1026 * the first change even though the second trumps it.
1028 if(index == -1 && bb->part == PartData)
1029 assert(b->l.type == BtData);
1031 if(bb->iostate != BioDirty){
1032 fprint(2, "%s: %d:%x:%d iostate is %d in blockDependency\n",
1033 argv0, bb->part, bb->addr, bb->l.type, bb->iostate);
1041 assert(bb->iostate == BioDirty);
1042 if(0)fprint(2, "%s: %d:%x:%d depends on %d:%x:%d\n", argv0, b->part, b->addr, b->l.type, bb->part, bb->addr, bb->l.type);
1046 p->type = bb->l.type;
1051 * This test would just be b->l.type==BtDir except
1052 * we need to exclude the super block.
1054 if(b->l.type == BtDir && b->part == PartData)
1055 entryPack(e, p->old.entry, 0);
1057 memmove(p->old.score, score, VtScoreSize);
1064 * Mark an in-memory block as dirty. If there are too many
1065 * dirty blocks, start writing some out to disk.
1067 * If there were way too many dirty blocks, we used to
1068 * try to do some flushing ourselves, but it's just too dangerous --
1069 * it implies that the callers cannot have any of our priors locked,
1070 * but this is hard to avoid in some cases.
1073 blockDirty(Block *b)
1079 assert(b->part != PartVenti);
1081 if(b->iostate == BioDirty)
1083 assert(b->iostate == BioClean || b->iostate == BioLabel);
1086 b->iostate = BioDirty;
1088 if(c->ndirty > (c->maxdirty>>1))
1096 * We've decided to write out b. Maybe b has some pointers to blocks
1097 * that haven't yet been written to disk. If so, construct a slightly out-of-date
1098 * copy of b that is safe to write out. (diskThread will make sure the block
1099 * remains marked as dirty.)
1102 blockRollback(Block *b, uchar *buf)
1112 memmove(buf, b->data, b->c->size);
1113 for(p=b->prior; p; p=p->next){
1115 * we know p->index >= 0 because blockWrite has vetted this block for us.
1117 assert(p->index >= 0);
1118 assert(b->part == PartSuper || (b->part == PartData && b->l.type != BtData));
1119 if(b->part == PartSuper){
1120 assert(p->index == 0);
1121 superUnpack(&super, buf);
1122 addr = globalToLocal(p->old.score);
1123 if(addr == NilBlock){
1124 fprint(2, "%s: rolling back super block: "
1125 "bad replacement addr %V\n",
1126 argv0, p->old.score);
1129 super.active = addr;
1130 superPack(&super, buf);
1133 if(b->l.type == BtDir)
1134 memmove(buf+p->index*VtEntrySize, p->old.entry, VtEntrySize);
1136 memmove(buf+p->index*VtScoreSize, p->old.score, VtScoreSize);
1142 * Try to write block b.
1143 * If b depends on other blocks:
1145 * If the block has been written out, remove the dependency.
1146 * If the dependency is replaced by a more recent dependency,
1148 * If we know how to write out an old version of b that doesn't
1149 * depend on it, do that.
1154 blockWrite(Block *b, int waitlock)
1164 if(b->iostate != BioDirty)
1168 memset(dmap, 0, c->ndmap);
1170 for(p=*pp; p; p=*pp){
1172 /* more recent dependency has succeeded; this one can go */
1173 if(dmap[p->index/8] & (1<<(p->index%8)))
1178 bb = _cacheLocalLookup(c, p->part, p->addr, p->vers, waitlock,
1183 /* block not in cache => was written already */
1184 dmap[p->index/8] |= 1<<(p->index%8);
1189 * same version of block is still in cache.
1191 * the assertion is true because the block still has version p->vers,
1192 * which means it hasn't been written out since we last saw it.
1194 if(bb->iostate != BioDirty){
1195 fprint(2, "%s: %d:%x:%d iostate is %d in blockWrite\n",
1196 argv0, bb->part, bb->addr, bb->l.type, bb->iostate);
1197 /* probably BioWriting if it happens? */
1198 if(bb->iostate == BioClean)
1206 * We don't know how to temporarily undo
1207 * b's dependency on bb, so just don't write b yet.
1209 if(0) fprint(2, "%s: blockWrite skipping %d %x %d %d; need to write %d %x %d\n",
1210 argv0, b->part, b->addr, b->vers, b->l.type, p->part, p->addr, bb->vers);
1213 /* keep walking down the list */
1224 * DiskWrite must never be called with a double-locked block.
1225 * This call to diskWrite is okay because blockWrite is only called
1226 * from the cache flush thread, which never double-locks a block.
1228 diskWrite(c->disk, b);
1233 * Change the I/O state of block b.
1234 * Just an assignment except for magic in
1235 * switch statement (read comments there).
1238 blockSetIOState(Block *b, int iostate)
1244 if(0) fprint(2, "%s: iostate part=%d addr=%x %s->%s\n", argv0, b->part, b->addr, bioStr(b->iostate), bioStr(iostate));
1259 bwatchDependency(b);
1261 * If b->prior is set, it means a write just finished.
1262 * The prior list isn't needed anymore.
1264 for(p=b->prior; p; p=q){
1270 * Freeing a block or just finished a write.
1271 * Move the blocks from the per-block unlink
1272 * queue to the cache unlink queue.
1274 if(b->iostate == BioDirty || b->iostate == BioWriting){
1277 b->iostate = iostate; /* change here to keep in sync with ndirty */
1278 b->vers = c->vers++;
1280 /* add unlink blocks to unlink queue */
1281 if(c->uhead == nil){
1282 c->uhead = b->uhead;
1283 rwakeup(&c->unlink);
1285 c->utail->next = b->uhead;
1286 c->utail = b->utail;
1296 * Wrote out an old version of the block (see blockRollback).
1297 * Bump a version count, leave it dirty.
1299 if(b->iostate == BioWriting){
1301 b->vers = c->vers++;
1309 * Adding block to disk queue. Bump reference count.
1310 * diskThread decs the count later by calling blockPut.
1311 * This is here because we need to lock c->lk to
1312 * manipulate the ref count.
1326 b->iostate = iostate;
1328 * Now that the state has changed, we can wake the waiters.
1331 rwakeupall(&b->ioready);
1335 * The active file system is a tree of blocks.
1336 * When we add snapshots to the mix, the entire file system
1337 * becomes a dag and thus requires a bit more care.
1339 * The life of the file system is divided into epochs. A snapshot
1340 * ends one epoch and begins the next. Each file system block
1341 * is marked with the epoch in which it was created (b.epoch).
1342 * When the block is unlinked from the file system (closed), it is marked
1343 * with the epoch in which it was removed (b.epochClose).
1344 * Once we have discarded or archived all snapshots up to
1345 * b.epochClose, we can reclaim the block.
1347 * If a block was created in a past epoch but is not yet closed,
1348 * it is treated as copy-on-write. Of course, in order to insert the
1349 * new pointer into the tree, the parent must be made writable,
1350 * and so on up the tree. The recursion stops because the root
1351 * block is always writable.
1353 * If blocks are never closed, they will never be reused, and
1354 * we will run out of disk space. But marking a block as closed
1355 * requires some care about dependencies and write orderings.
1357 * (1) If a block p points at a copy-on-write block b and we
1358 * copy b to create bb, then p must be written out after bb and
1359 * lbb (bb's label block).
1361 * (2) We have to mark b as closed, but only after we switch
1362 * the pointer, so lb must be written out after p. In fact, we
1363 * can't even update the in-memory copy, or the cache might
1364 * mistakenly give out b for reuse before p gets written.
1366 * CacheAllocBlock's call to blockSetLabel records a "bb after lbb" dependency.
1367 * The caller is expected to record a "p after bb" dependency
1368 * to finish (1), and also expected to call blockRemoveLink
1369 * to arrange for (2) to happen once p is written.
1371 * Until (2) happens, some pieces of the code (e.g., the archiver)
1372 * still need to know whether a block has been copied, so we
1373 * set the BsCopied bit in the label and force that to disk *before*
1374 * the copy gets written out.
1377 blockCopy(Block *b, u32int tag, u32int ehi, u32int elo)
1382 if((b->l.state&BsClosed) || b->l.epoch >= ehi)
1383 fprint(2, "%s: blockCopy %#ux %L but fs is [%ud,%ud]\n",
1384 argv0, b->addr, &b->l, elo, ehi);
1386 bb = cacheAllocBlock(b->c, b->l.type, tag, ehi, elo);
1393 * Update label so we know the block has been copied.
1394 * (It will be marked closed once it has been unlinked from
1395 * the tree.) This must follow cacheAllocBlock since we
1396 * can't be holding onto lb when we call cacheAllocBlock.
1398 if((b->l.state&BsCopied)==0)
1399 if(b->part == PartData){ /* not the superblock */
1401 l.state |= BsCopied;
1402 lb = _blockSetLabel(b, &l);
1404 /* can't set label => can't copy block */
1411 blockSetLabel(bb, &l, 0);
1415 blockDependency(bb, lb, -1, nil, nil);
1419 memmove(bb->data, b->data, b->c->size);
1426 * Block b once pointed at the block bb at addr/type/tag, but no longer does.
1427 * If recurse is set, we are unlinking all of bb's children as well.
1429 * We can't reclaim bb (or its kids) until the block b gets written to disk. We add
1430 * the relevant information to b's list of unlinked blocks. Once b is written,
1431 * the list will be queued for processing.
1433 * If b depends on bb, it doesn't anymore, so we remove bb from the prior list.
1436 blockRemoveLink(Block *b, u32int addr, int type, u32int tag, int recurse)
1440 /* remove bb from prior list */
1441 for(pp=&b->prior; (p=*pp)!=nil; ){
1442 if(p->part == PartData && p->addr == addr){
1454 assert(b->part == PartSuper);
1455 bl.epoch = b->l.epoch;
1457 bl.recurse = recurse;
1459 if(b->part == PartSuper && b->iostate == BioClean)
1465 * b has already been written to disk.
1467 doRemoveLink(b->c, &bl);
1471 /* Uhead is only processed when the block goes from Dirty -> Clean */
1472 assert(b->iostate == BioDirty);
1483 * Process removal of a single block and perhaps its children.
1486 doRemoveLink(Cache *c, BList *p)
1494 recurse = (p->recurse && p->type != BtData && p->type != BtDir);
1497 * We're not really going to overwrite b, but if we're not
1498 * going to look at its contents, there is no point in reading
1499 * them from the disk.
1501 b = cacheLocalData(c, p->addr, p->type, p->tag, recurse ? OReadOnly : OOverWrite, 0);
1506 * When we're unlinking from the superblock, close with the next epoch.
1509 p->epoch = b->l.epoch+1;
1512 if(b->l.epoch > p->epoch){
1513 fprint(2, "%s: doRemoveLink: strange epoch %ud > %ud\n",
1514 argv0, b->l.epoch, p->epoch);
1520 n = c->size / VtScoreSize;
1522 a = globalToLocal(b->data + i*VtScoreSize);
1523 if(a == NilBlock || !readLabel(c, &l, a))
1525 if(l.state&BsClosed)
1528 * If stack space becomes an issue...
1539 bl.epoch = p->epoch;
1542 /* give up the block lock - share with others */
1544 doRemoveLink(c, &bl);
1545 b = cacheLocalData(c, p->addr, p->type, p->tag, OReadOnly, 0);
1547 fprint(2, "%s: warning: lost block in doRemoveLink\n",
1555 l.state |= BsClosed;
1556 l.epochClose = p->epoch;
1557 if(l.epochClose == l.epoch){
1559 if(l.epoch == c->fl->epochLow)
1561 blockSetLabel(b, &l, 0);
1562 qunlock(&c->fl->lk);
1564 blockSetLabel(b, &l, 0);
1569 * Allocate a BList so that we can record a dependency
1570 * or queue a removal related to block b.
1571 * If we can't find a BList, we write out b and return nil.
1574 blistAlloc(Block *b)
1579 if(b->iostate != BioDirty){
1581 * should not happen anymore -
1582 * blockDirty used to flush but no longer does.
1584 assert(b->iostate == BioClean);
1585 fprint(2, "%s: blistAlloc: called on clean block\n", argv0);
1591 if(c->blfree == nil){
1593 * No free BLists. What are our options?
1596 /* Block has no priors? Just write it. */
1597 if(b->prior == nil){
1599 diskWriteAndWait(c->disk, b);
1604 * Wake the flush thread, which will hopefully free up
1605 * some BLists for us. We used to flush a block from
1606 * our own prior list and reclaim that BList, but this is
1607 * a no-no: some of the blocks on our prior list may
1608 * be locked by our caller. Or maybe their label blocks
1609 * are locked by our caller. In any event, it's too hard
1610 * to make sure we can do I/O for ourselves. Instead,
1611 * we assume the flush thread will find something.
1612 * (The flush thread never blocks waiting for a block,
1613 * so it can't deadlock like we can.)
1615 while(c->blfree == nil){
1618 if(c->blfree == nil)
1619 fprint(2, "%s: flushing for blists\n", argv0);
1624 c->blfree = p->next;
1630 blistFree(Cache *c, BList *bl)
1633 bl->next = c->blfree;
1635 rwakeup(&c->blrend);
1649 sprint(s, "%x", state);
1650 if(!(state&BsAlloc))
1651 strcat(s, ",Free"); /* should not happen */
1653 strcat(s, ",Copied");
1655 strcat(s, ",Venti");
1657 strcat(s, ",Closed");
1682 return "VentiError";
1688 static char *bttab[] = {
1710 if(type < nelem(bttab))
1720 l = va_arg(f->args, Label*);
1721 return fmtprint(f, "%s,%s,e=%ud,%d,tag=%#ux",
1722 btStr(l->type), bsStr(l->state), l->epoch, (int)l->epochClose, l->tag);
1732 v = va_arg(f->args, uchar*);
1735 }else if((addr = globalToLocal(v)) != NilBlock)
1736 fmtprint(f, "0x%.8ux", addr);
1738 for(i = 0; i < VtScoreSize; i++)
1739 fmtprint(f, "%2.2ux", v[i]);
1746 upHeap(int i, Block *b)
1755 for(; i != 0; i = p){
1758 if(b->used - now >= bb->used - now)
1770 downHeap(int i, Block *b)
1783 if(k + 1 < c->nheap && c->heap[k]->used - now > c->heap[k + 1]->used - now)
1786 if(b->used - now <= bb->used - now)
1797 * Delete a block from the heap.
1798 * Called with c->lk held.
1815 b = c->heap[c->nheap];
1822 * Insert a block into the heap.
1823 * Called with c->lk held.
1828 assert(b->heap == BadHeap);
1829 upHeap(b->c->nheap++, b);
1830 rwakeup(&b->c->heapwait);
1834 * Get just the label for a block.
1837 readLabel(Cache *c, Label *l, u32int addr)
1843 lpb = c->size / LabelSize;
1845 b = cacheLocal(c, PartLabel, a, OReadOnly);
1851 if(!labelUnpack(l, b->data, addr%lpb)){
1860 * Process unlink queue.
1861 * Called with c->lk held.
1864 unlinkBody(Cache *c)
1868 while(c->uhead != nil){
1874 p->next = c->blfree;
1880 * Occasionally unlink the blocks on the cache unlink queue.
1883 unlinkThread(void *a)
1887 threadsetname("unlink");
1891 while(c->uhead == nil && c->die.l == nil)
1903 baddrCmp(const void *a0, const void *a1)
1909 if(b0->part < b1->part)
1911 if(b0->part > b1->part)
1913 if(b0->addr < b1->addr)
1915 if(b0->addr > b1->addr)
1921 * Scan the block list for dirty blocks; add them to the list c->baddr.
1938 for(i=0; i<c->nblocks; i++){
1940 if(b->part == PartError)
1942 if(b->iostate == BioDirty || b->iostate == BioWriting)
1944 if(b->iostate != BioDirty)
1951 if(ndirty != c->ndirty){
1952 fprint(2, "%s: ndirty mismatch expected %d found %d\n",
1953 argv0, c->ndirty, ndirty);
1958 c->bw = p - c->baddr;
1959 qsort(c->baddr, c->bw, sizeof(BAddr), baddrCmp);
1963 * This is not thread safe, i.e. it can't be called from multiple threads.
1965 * It's okay how we use it, because it only gets called in
1966 * the flushThread. And cacheFree, but only after
1967 * cacheFree has killed off the flushThread.
1970 cacheFlushBlock(Cache *c)
1974 int lockfail, nfail;
1979 if(c->bw == 0 || c->bw == c->be)
1989 p = c->baddr + c->br;
1991 b = _cacheLocalLookup(c, p->part, p->addr, p->vers, Nowaitlock,
1994 if(b && blockWrite(b, Nowaitlock)){
2003 * Why didn't we write the block?
2006 /* Block already written out */
2007 if(b == nil && !lockfail)
2010 /* Failed to acquire lock; sleep if happens a lot. */
2011 if(lockfail && ++nfail > 100){
2015 /* Requeue block. */
2017 c->baddr[c->bw++] = *p;
2022 * Occasionally flush dirty blocks from memory to the disk.
2025 flushThread(void *a)
2030 threadsetname("flush");
2032 while(c->die.l == nil){
2035 for(i=0; i<FlushSize; i++)
2036 if(!cacheFlushBlock(c)){
2038 * If i==0, could be someone is waking us repeatedly
2039 * to flush the cache but there's no work to do.
2043 // fprint(2, "%s: flushthread found "
2044 // "nothing to flush - %d dirty\n",
2045 // argv0, c->ndirty);
2050 if(i==0 && c->ndirty){
2052 * All the blocks are being written right now -- there's nothing to do.
2053 * We might be spinning with cacheFlush though -- he'll just keep
2054 * kicking us until c->ndirty goes down. Probably we should sleep
2055 * on something that the diskThread can kick, but for now we'll
2056 * just pause for a little while waiting for disks to finish.
2061 rwakeupall(&c->flushwait);
2072 cacheFlush(Cache *c, int wait)
2077 // consPrint("cacheFlush: %d dirty blocks, uhead %p\n",
2078 // c->ndirty, c->uhead);
2080 rsleep(&c->flushwait);
2082 // consPrint("cacheFlush: done (uhead %p)\n", c->ndirty, c->uhead);
2089 * Kick the flushThread every 30 seconds.