cache.c 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036
  1. #include "stdinc.h"
  2. #include "dat.h"
  3. #include "fns.h"
  4. #include "error.h"
  5. #include "9.h" /* for cacheFlush */
  6. typedef struct FreeList FreeList;
  7. typedef struct BAddr BAddr;
  8. enum {
  9. BadHeap = ~0,
  10. };
  11. /*
  12. * Store data to the memory cache in c->size blocks
  13. * with the block zero extended to fill it out. When writing to
  14. * Venti, the block will be zero truncated. The walker will also check
  15. * that the block fits within psize or dsize as the case may be.
  16. */
  17. struct Cache
  18. {
  19. VtLock *lk;
  20. int ref;
  21. int mode;
  22. Disk *disk;
  23. int size; /* block size */
  24. int ndmap; /* size of per-block dirty pointer map used in blockWrite */
  25. VtSession *z;
  26. u32int now; /* ticks for usage timestamps */
  27. Block **heads; /* hash table for finding address */
  28. int nheap; /* number of available victims */
  29. Block **heap; /* heap for locating victims */
  30. long nblocks; /* number of blocks allocated */
  31. Block *blocks; /* array of block descriptors */
  32. u8int *mem; /* memory for all block data & blists */
  33. BList *blfree;
  34. VtRendez *blrend;
  35. int ndirty; /* number of dirty blocks in the cache */
  36. int maxdirty; /* max number of dirty blocks */
  37. u32int vers;
  38. long hashSize;
  39. FreeList *fl;
  40. VtRendez *die; /* daemon threads should die when != nil */
  41. VtRendez *flush;
  42. VtRendez *flushwait;
  43. BAddr *baddr;
  44. int bw, br, be;
  45. int nflush;
  46. Periodic *sync;
  47. /* unlink daemon */
  48. BList *uhead;
  49. BList *utail;
  50. VtRendez *unlink;
  51. };
  52. struct BList {
  53. int part;
  54. u32int addr;
  55. uchar type;
  56. u32int tag;
  57. u32int epoch;
  58. u32int vers;
  59. /* for roll back */
  60. int index; /* -1 indicates not valid */
  61. union {
  62. uchar score[VtScoreSize];
  63. uchar entry[VtEntrySize];
  64. } old;
  65. BList *next;
  66. };
  67. struct BAddr {
  68. int part;
  69. u32int addr;
  70. u32int vers;
  71. };
  72. struct FreeList {
  73. VtLock *lk;
  74. u32int last; /* last block allocated */
  75. u32int end; /* end of data partition */
  76. };
  77. static FreeList *flAlloc(u32int end);
  78. static void flFree(FreeList *fl);
  79. static Block *cacheBumpBlock(Cache *c);
  80. static void heapDel(Block*);
  81. static void heapIns(Block*);
  82. static void cacheCheck(Cache*);
  83. static int readLabel(Cache*, Label*, u32int addr);
  84. static void unlinkThread(void *a);
  85. static void flushThread(void *a);
  86. static void flushBody(Cache *c);
  87. static void unlinkBody(Cache *c);
  88. static int cacheFlushBlock(Cache *c);
  89. static void cacheSync(void*);
  90. /*
  91. * Mapping from local block type to Venti type
  92. */
  93. int vtType[BtMax] = {
  94. VtDataType, /* BtData | 0 */
  95. VtPointerType0, /* BtData | 1 */
  96. VtPointerType1, /* BtData | 2 */
  97. VtPointerType2, /* BtData | 3 */
  98. VtPointerType3, /* BtData | 4 */
  99. VtPointerType4, /* BtData | 5 */
  100. VtPointerType5, /* BtData | 6 */
  101. VtPointerType6, /* BtData | 7 */
  102. VtDirType, /* BtDir | 0 */
  103. VtPointerType0, /* BtDir | 1 */
  104. VtPointerType1, /* BtDir | 2 */
  105. VtPointerType2, /* BtDir | 3 */
  106. VtPointerType3, /* BtDir | 4 */
  107. VtPointerType4, /* BtDir | 5 */
  108. VtPointerType5, /* BtDir | 6 */
  109. VtPointerType6, /* BtDir | 7 */
  110. };
  111. /*
  112. * Allocate the memory cache.
  113. */
  114. Cache *
  115. cacheAlloc(Disk *disk, VtSession *z, ulong nblocks, int mode)
  116. {
  117. int i;
  118. Cache *c;
  119. Block *b;
  120. BList *bl;
  121. u8int *p;
  122. int nbl;
  123. c = vtMemAllocZ(sizeof(Cache));
  124. /* reasonable number of BList elements */
  125. nbl = nblocks * 4;
  126. c->lk = vtLockAlloc();
  127. c->ref = 1;
  128. c->disk = disk;
  129. c->z = z;
  130. c->size = diskBlockSize(disk);
  131. bwatchSetBlockSize(c->size);
  132. /* round c->size up to be a nice multiple */
  133. c->size = (c->size + 127) & ~127;
  134. c->ndmap = (c->size/20 + 7) / 8;
  135. c->nblocks = nblocks;
  136. c->hashSize = nblocks;
  137. c->heads = vtMemAllocZ(c->hashSize*sizeof(Block*));
  138. c->heap = vtMemAllocZ(nblocks*sizeof(Block*));
  139. c->blocks = vtMemAllocZ(nblocks*sizeof(Block));
  140. c->mem = vtMemAllocZ(nblocks * (c->size + c->ndmap) + nbl * sizeof(BList));
  141. c->baddr = vtMemAllocZ(nblocks * sizeof(BAddr));
  142. c->mode = mode;
  143. c->vers++;
  144. p = c->mem;
  145. for(i = 0; i < nblocks; i++){
  146. b = &c->blocks[i];
  147. b->lk = vtLockAlloc();
  148. b->c = c;
  149. b->data = p;
  150. b->heap = i;
  151. b->ioready = vtRendezAlloc(b->lk);
  152. c->heap[i] = b;
  153. p += c->size;
  154. }
  155. c->nheap = nblocks;
  156. for(i = 0; i < nbl; i++){
  157. bl = (BList*)p;
  158. bl->next = c->blfree;
  159. c->blfree = bl;
  160. p += sizeof(BList);
  161. }
  162. /* separate loop to keep blocks and blists reasonably aligned */
  163. for(i = 0; i < nblocks; i++){
  164. b = &c->blocks[i];
  165. b->dmap = p;
  166. p += c->ndmap;
  167. }
  168. c->blrend = vtRendezAlloc(c->lk);
  169. c->maxdirty = nblocks*(DirtyPercentage*0.01);
  170. c->fl = flAlloc(diskSize(disk, PartData));
  171. c->unlink = vtRendezAlloc(c->lk);
  172. c->flush = vtRendezAlloc(c->lk);
  173. c->flushwait = vtRendezAlloc(c->lk);
  174. c->sync = periodicAlloc(cacheSync, c, 30*1000);
  175. if(mode == OReadWrite){
  176. c->ref += 2;
  177. vtThread(unlinkThread, c);
  178. vtThread(flushThread, c);
  179. }
  180. cacheCheck(c);
  181. return c;
  182. }
  183. /*
  184. * Free the whole memory cache, flushing all dirty blocks to the disk.
  185. */
  186. void
  187. cacheFree(Cache *c)
  188. {
  189. int i;
  190. /* kill off daemon threads */
  191. vtLock(c->lk);
  192. c->die = vtRendezAlloc(c->lk);
  193. periodicKill(c->sync);
  194. vtWakeup(c->flush);
  195. vtWakeup(c->unlink);
  196. while(c->ref > 1)
  197. vtSleep(c->die);
  198. /* flush everything out */
  199. do {
  200. unlinkBody(c);
  201. vtUnlock(c->lk);
  202. while(cacheFlushBlock(c))
  203. ;
  204. diskFlush(c->disk);
  205. vtLock(c->lk);
  206. } while(c->uhead || c->ndirty);
  207. vtUnlock(c->lk);
  208. cacheCheck(c);
  209. for(i = 0; i < c->nblocks; i++){
  210. assert(c->blocks[i].ref == 0);
  211. vtRendezFree(c->blocks[i].ioready);
  212. vtLockFree(c->blocks[i].lk);
  213. }
  214. flFree(c->fl);
  215. vtMemFree(c->baddr);
  216. vtMemFree(c->heads);
  217. vtMemFree(c->blocks);
  218. vtMemFree(c->mem);
  219. vtLockFree(c->lk);
  220. diskFree(c->disk);
  221. vtRendezFree(c->blrend);
  222. /* don't close vtSession */
  223. vtMemFree(c);
  224. }
  225. static void
  226. cacheDump(Cache *c)
  227. {
  228. int i;
  229. Block *b;
  230. for(i = 0; i < c->nblocks; i++){
  231. b = &c->blocks[i];
  232. fprint(2, "p=%d a=%ud %V t=%d ref=%d state=%s io=%s\n",
  233. b->part, b->addr, b->score, b->l.type, b->ref,
  234. bsStr(b->l.state), bioStr(b->iostate));
  235. }
  236. }
  237. static void
  238. cacheCheck(Cache *c)
  239. {
  240. u32int size, now;
  241. int i, k, refed;
  242. static uchar zero[VtScoreSize];
  243. Block *b;
  244. size = c->size;
  245. now = c->now;
  246. for(i = 0; i < c->nheap; i++){
  247. if(c->heap[i]->heap != i)
  248. vtFatal("mis-heaped at %d: %d", i, c->heap[i]->heap);
  249. if(i > 0 && c->heap[(i - 1) >> 1]->used - now > c->heap[i]->used - now)
  250. vtFatal("bad heap ordering");
  251. k = (i << 1) + 1;
  252. if(k < c->nheap && c->heap[i]->used - now > c->heap[k]->used - now)
  253. vtFatal("bad heap ordering");
  254. k++;
  255. if(k < c->nheap && c->heap[i]->used - now > c->heap[k]->used - now)
  256. vtFatal("bad heap ordering");
  257. }
  258. refed = 0;
  259. for(i = 0; i < c->nblocks; i++){
  260. b = &c->blocks[i];
  261. if(b->data != &c->mem[i * size])
  262. vtFatal("mis-blocked at %d", i);
  263. if(b->ref && b->heap == BadHeap){
  264. refed++;
  265. }
  266. }
  267. if(c->nheap + refed != c->nblocks){
  268. fprint(2, "cacheCheck: nheap %d refed %d nblocks %ld\n", c->nheap, refed, c->nblocks);
  269. cacheDump(c);
  270. }
  271. assert(c->nheap + refed == c->nblocks);
  272. refed = 0;
  273. for(i = 0; i < c->nblocks; i++){
  274. b = &c->blocks[i];
  275. if(b->ref){
  276. if(1)fprint(2, "p=%d a=%ud %V ref=%d %L\n", b->part, b->addr, b->score, b->ref, &b->l);
  277. refed++;
  278. }
  279. }
  280. if(refed > 0)fprint(2, "cacheCheck: in used %d\n", refed);
  281. }
  282. /*
  283. * locate the block with the oldest second to last use.
  284. * remove it from the heap, and fix up the heap.
  285. */
  286. /* called with c->lk held */
  287. static Block *
  288. cacheBumpBlock(Cache *c)
  289. {
  290. Block *b;
  291. /*
  292. * locate the block with the oldest second to last use.
  293. * remove it from the heap, and fix up the heap.
  294. */
  295. if(c->nheap == 0)
  296. vtFatal("cacheBumpBlock: no free blocks in cache");
  297. b = c->heap[0];
  298. heapDel(b);
  299. assert(b->heap == BadHeap);
  300. assert(b->ref == 0);
  301. assert(b->iostate == BioEmpty || b->iostate == BioLabel || b->iostate == BioClean);
  302. assert(b->prior == nil);
  303. assert(b->uhead == nil);
  304. /*
  305. * unchain the block from hash chain
  306. */
  307. if(b->prev){
  308. *(b->prev) = b->next;
  309. if(b->next)
  310. b->next->prev = b->prev;
  311. b->prev = nil;
  312. }
  313. if(0)fprint(2, "droping %d:%x:%V\n", b->part, b->addr, b->score);
  314. /* set block to a reasonable state */
  315. b->ref = 1;
  316. b->part = PartError;
  317. memset(&b->l, 0, sizeof(b->l));
  318. b->iostate = BioEmpty;
  319. return b;
  320. }
  321. /*
  322. * look for a particular version of the block in the memory cache.
  323. */
  324. static Block *
  325. _cacheLocalLookup(Cache *c, int part, u32int addr, u32int vers,
  326. int waitlock, int *lockfailure)
  327. {
  328. Block *b;
  329. ulong h;
  330. h = addr % c->hashSize;
  331. if(lockfailure)
  332. *lockfailure = 0;
  333. /*
  334. * look for the block in the cache
  335. */
  336. vtLock(c->lk);
  337. for(b = c->heads[h]; b != nil; b = b->next){
  338. if(b->part == part && b->addr == addr)
  339. break;
  340. }
  341. if(b == nil || b->vers != vers){
  342. vtUnlock(c->lk);
  343. return nil;
  344. }
  345. if(!waitlock && !vtCanLock(b->lk)){
  346. *lockfailure = 1;
  347. vtUnlock(c->lk);
  348. return nil;
  349. }
  350. heapDel(b);
  351. b->ref++;
  352. vtUnlock(c->lk);
  353. bwatchLock(b);
  354. if(waitlock)
  355. vtLock(b->lk);
  356. b->nlock = 1;
  357. for(;;){
  358. switch(b->iostate){
  359. default:
  360. abort();
  361. case BioEmpty:
  362. case BioLabel:
  363. case BioClean:
  364. case BioDirty:
  365. if(b->vers != vers){
  366. blockPut(b);
  367. return nil;
  368. }
  369. return b;
  370. case BioReading:
  371. case BioWriting:
  372. vtSleep(b->ioready);
  373. break;
  374. case BioVentiError:
  375. case BioReadError:
  376. blockSetIOState(b, BioEmpty);
  377. blockPut(b);
  378. vtSetError(EIO);
  379. return nil;
  380. }
  381. }
  382. /* NOT REACHED */
  383. }
  384. static Block*
  385. cacheLocalLookup(Cache *c, int part, u32int addr, u32int vers)
  386. {
  387. return _cacheLocalLookup(c, part, addr, vers, 1, 0);
  388. }
  389. /*
  390. * fetch a local (on-disk) block from the memory cache.
  391. * if it's not there, load it, bumping some other block.
  392. */
  393. Block *
  394. _cacheLocal(Cache *c, int part, u32int addr, int mode, u32int epoch)
  395. {
  396. Block *b;
  397. ulong h;
  398. assert(part != PartVenti);
  399. h = addr % c->hashSize;
  400. /*
  401. * look for the block in the cache
  402. */
  403. vtLock(c->lk);
  404. for(b = c->heads[h]; b != nil; b = b->next){
  405. if(b->part != part || b->addr != addr)
  406. continue;
  407. if(epoch && b->l.epoch != epoch){
  408. fprint(2, "_cacheLocal want epoch %ud got %ud\n", epoch, b->l.epoch);
  409. vtUnlock(c->lk);
  410. vtSetError(ELabelMismatch);
  411. return nil;
  412. }
  413. heapDel(b);
  414. b->ref++;
  415. break;
  416. }
  417. if(b == nil){
  418. b = cacheBumpBlock(c);
  419. b->part = part;
  420. b->addr = addr;
  421. localToGlobal(addr, b->score);
  422. /* chain onto correct hash */
  423. b->next = c->heads[h];
  424. c->heads[h] = b;
  425. if(b->next != nil)
  426. b->next->prev = &b->next;
  427. b->prev = &c->heads[h];
  428. }
  429. vtUnlock(c->lk);
  430. /*
  431. * BUG: what if the epoch changes right here?
  432. * In the worst case, we could end up in some weird
  433. * lock loop, because the block we want no longer exists,
  434. * and instead we're trying to lock a block we have no
  435. * business grabbing.
  436. *
  437. * For now, I'm not going to worry about it.
  438. */
  439. if(0)fprint(2, "cacheLocal: %d: %d %x\n", getpid(), b->part, b->addr);
  440. bwatchLock(b);
  441. vtLock(b->lk);
  442. b->nlock = 1;
  443. if(part == PartData && b->iostate == BioEmpty){
  444. if(!readLabel(c, &b->l, addr)){
  445. blockPut(b);
  446. return nil;
  447. }
  448. blockSetIOState(b, BioLabel);
  449. }
  450. if(epoch && b->l.epoch != epoch){
  451. blockPut(b);
  452. fprint(2, "_cacheLocal want epoch %ud got %ud\n", epoch, b->l.epoch);
  453. vtSetError(ELabelMismatch);
  454. return nil;
  455. }
  456. b->pc = getcallerpc(&c);
  457. for(;;){
  458. switch(b->iostate){
  459. default:
  460. abort();
  461. case BioEmpty:
  462. case BioLabel:
  463. if(mode == OOverWrite){
  464. blockSetIOState(b, BioClean);
  465. return b;
  466. }
  467. diskRead(c->disk, b);
  468. vtSleep(b->ioready);
  469. break;
  470. case BioClean:
  471. case BioDirty:
  472. return b;
  473. case BioReading:
  474. case BioWriting:
  475. vtSleep(b->ioready);
  476. break;
  477. case BioReadError:
  478. blockSetIOState(b, BioEmpty);
  479. blockPut(b);
  480. vtSetError(EIO);
  481. return nil;
  482. }
  483. }
  484. /* NOT REACHED */
  485. }
  486. Block *
  487. cacheLocal(Cache *c, int part, u32int addr, int mode)
  488. {
  489. return _cacheLocal(c, part, addr, mode, 0);
  490. }
  491. /*
  492. * fetch a local (on-disk) block from the memory cache.
  493. * if it's not there, load it, bumping some other block.
  494. * check tag and type.
  495. */
  496. Block *
  497. cacheLocalData(Cache *c, u32int addr, int type, u32int tag, int mode, u32int epoch)
  498. {
  499. Block *b;
  500. b = _cacheLocal(c, PartData, addr, mode, epoch);
  501. if(b == nil)
  502. return nil;
  503. if(b->l.type != type || b->l.tag != tag){
  504. fprint(2, "cacheLocalData: addr=%d type got %d exp %d: tag got %x exp %x\n",
  505. addr, b->l.type, type, b->l.tag, tag);
  506. abort();
  507. vtSetError(ELabelMismatch);
  508. blockPut(b);
  509. return nil;
  510. }
  511. b->pc = getcallerpc(&c);
  512. return b;
  513. }
  514. /*
  515. * fetch a global (Venti) block from the memory cache.
  516. * if it's not there, load it, bumping some other block.
  517. * check tag and type if it's really a local block in disguise.
  518. */
  519. Block *
  520. cacheGlobal(Cache *c, uchar score[VtScoreSize], int type, u32int tag, int mode)
  521. {
  522. int n;
  523. Block *b;
  524. ulong h;
  525. u32int addr;
  526. addr = globalToLocal(score);
  527. if(addr != NilBlock){
  528. b = cacheLocalData(c, addr, type, tag, mode, 0);
  529. if(b)
  530. b->pc = getcallerpc(&c);
  531. return b;
  532. }
  533. h = (u32int)(score[0]|(score[1]<<8)|(score[2]<<16)|(score[3]<<24)) % c->hashSize;
  534. /*
  535. * look for the block in the cache
  536. */
  537. vtLock(c->lk);
  538. for(b = c->heads[h]; b != nil; b = b->next){
  539. if(b->part != PartVenti || memcmp(b->score, score, VtScoreSize) != 0 || b->l.type != type)
  540. continue;
  541. heapDel(b);
  542. b->ref++;
  543. break;
  544. }
  545. if(b == nil){
  546. if(0)fprint(2, "cacheGlobal %V %d\n", score, type);
  547. b = cacheBumpBlock(c);
  548. b->part = PartVenti;
  549. b->addr = NilBlock;
  550. b->l.type = type;
  551. memmove(b->score, score, VtScoreSize);
  552. /* chain onto correct hash */
  553. b->next = c->heads[h];
  554. c->heads[h] = b;
  555. if(b->next != nil)
  556. b->next->prev = &b->next;
  557. b->prev = &c->heads[h];
  558. }
  559. vtUnlock(c->lk);
  560. bwatchLock(b);
  561. vtLock(b->lk);
  562. b->nlock = 1;
  563. b->pc = getcallerpc(&c);
  564. switch(b->iostate){
  565. default:
  566. abort();
  567. case BioEmpty:
  568. n = vtRead(c->z, score, vtType[type], b->data, c->size);
  569. if(n < 0 || !vtSha1Check(score, b->data, n)){
  570. blockSetIOState(b, BioVentiError);
  571. blockPut(b);
  572. return nil;
  573. }
  574. vtZeroExtend(vtType[type], b->data, n, c->size);
  575. blockSetIOState(b, BioClean);
  576. return b;
  577. case BioClean:
  578. return b;
  579. case BioVentiError:
  580. case BioReadError:
  581. blockPut(b);
  582. vtSetError(EIO);
  583. blockSetIOState(b, BioEmpty);
  584. return nil;
  585. }
  586. /* NOT REACHED */
  587. }
  588. /*
  589. * allocate a new on-disk block and load it into the memory cache.
  590. * BUG: if the disk is full, should we flush some of it to Venti?
  591. */
  592. static u32int lastAlloc;
  593. Block *
  594. cacheAllocBlock(Cache *c, int type, u32int tag, u32int epoch, u32int epochLow)
  595. {
  596. FreeList *fl;
  597. u32int addr;
  598. Block *b;
  599. int n, nwrap;
  600. Label lab;
  601. n = c->size / LabelSize;
  602. fl = c->fl;
  603. vtLock(fl->lk);
  604. fl->last = 0;
  605. addr = fl->last;
  606. b = cacheLocal(c, PartLabel, addr/n, OReadOnly);
  607. if(b == nil){
  608. fprint(2, "cacheAllocBlock: xxx %R\n");
  609. vtUnlock(fl->lk);
  610. return nil;
  611. }
  612. nwrap = 0;
  613. for(;;){
  614. if(++addr >= fl->end){
  615. addr = 0;
  616. fprint(2, "cacheAllocBlock wrap %d\n", fl->end);
  617. if(++nwrap >= 2){
  618. blockPut(b);
  619. fl->last = 0;
  620. vtSetError("disk is full");
  621. fprint(2, "cacheAllocBlock: xxx1 %R\n");
  622. vtUnlock(fl->lk);
  623. return nil;
  624. }
  625. }
  626. if(addr%n == 0){
  627. blockPut(b);
  628. b = cacheLocal(c, PartLabel, addr/n, OReadOnly);
  629. if(b == nil){
  630. fl->last = addr;
  631. fprint(2, "cacheAllocBlock: xxx2 %R\n");
  632. vtUnlock(fl->lk);
  633. return nil;
  634. }
  635. }
  636. if(!labelUnpack(&lab, b->data, addr%n))
  637. continue;
  638. if(lab.state == BsFree)
  639. goto Found;
  640. if((lab.state&BsClosed) && lab.epochClose <= epochLow)
  641. goto Found;
  642. }
  643. Found:
  644. blockPut(b);
  645. b = cacheLocal(c, PartData, addr, OOverWrite);
  646. if(b == nil){
  647. fprint(2, "cacheAllocBlock: xxx3 %R\n");
  648. return nil;
  649. }
  650. assert(b->iostate == BioLabel || b->iostate == BioClean);
  651. fl->last = addr;
  652. lab.type = type;
  653. lab.tag = tag;
  654. lab.state = BsAlloc;
  655. lab.epoch = epoch;
  656. lab.epochClose = ~(u32int)0;
  657. if(!blockSetLabel(b, &lab)){
  658. fprint(2, "cacheAllocBlock: xxx4 %R\n");
  659. blockPut(b);
  660. return nil;
  661. }
  662. vtZeroExtend(vtType[type], b->data, 0, c->size);
  663. if(0)diskWrite(c->disk, b);
  664. if(0)fprint(2, "fsAlloc %ud type=%d tag = %ux\n", addr, type, tag);
  665. lastAlloc = addr;
  666. vtUnlock(fl->lk);
  667. b->pc = getcallerpc(&c);
  668. return b;
  669. }
  670. static FreeList *
  671. flAlloc(u32int end)
  672. {
  673. FreeList *fl;
  674. fl = vtMemAllocZ(sizeof(*fl));
  675. fl->lk = vtLockAlloc();
  676. fl->last = end;
  677. fl->end = end;
  678. return fl;
  679. }
  680. static void
  681. flFree(FreeList *fl)
  682. {
  683. vtLockFree(fl->lk);
  684. vtMemFree(fl);
  685. }
  686. u32int
  687. cacheLocalSize(Cache *c, int part)
  688. {
  689. return diskSize(c->disk, part);
  690. }
  691. /*
  692. * Copy on write. Copied blocks have to be marked BaCopy.
  693. * See the big comment near blockRemoveLink.
  694. */
  695. Block*
  696. blockCopy(Block *b, u32int tag, u32int ehi, u32int elo)
  697. {
  698. Block *bb, *lb;
  699. Label l;
  700. assert((b->l.state&BsClosed)==0 && b->l.epoch < ehi);
  701. bb = cacheAllocBlock(b->c, b->l.type, tag, ehi, elo);
  702. if(bb == nil){
  703. blockPut(b);
  704. return nil;
  705. }
  706. /*
  707. * Change label on b to mark that we've copied it.
  708. * This has to come after cacheAllocBlock, since we
  709. * can't hold any labels blocks (lb) while we try to
  710. * fetch others (in cacheAllocBlock).
  711. */
  712. if(!(b->l.state&BsCopied) && b->part==PartData){
  713. l = b->l;
  714. l.state |= BsCopied;
  715. lb = _blockSetLabel(b, &l);
  716. if(lb == nil){
  717. /* can't set label => can't copy block */
  718. blockPut(b);
  719. l.type = BtMax;
  720. l.state = BsFree;
  721. l.epoch = 0;
  722. l.epochClose = 0;
  723. l.tag = 0;
  724. /* ignore error: block gets lost on error */
  725. blockSetLabel(bb, &l);
  726. blockPut(bb);
  727. return nil;
  728. }
  729. blockDependency(bb, lb, -1, nil, nil);
  730. blockPut(lb);
  731. }
  732. if(0){
  733. if(b->addr != NilBlock)
  734. fprint(2, "blockCopy %#ux/%ud => %#ux/%ud\n",
  735. b->addr, b->l.epoch, bb->addr, bb->l.epoch);
  736. else if(memcmp(b->score, vtZeroScore, VtScoreSize) != 0)
  737. fprint(2, "blockCopy %V => %#ux/%ud\n",
  738. b->score, bb->addr, bb->l.epoch);
  739. }
  740. memmove(bb->data, b->data, b->c->size);
  741. blockDirty(bb);
  742. blockPut(b);
  743. return bb;
  744. }
  745. /*
  746. * The thread that has locked b may refer to it by
  747. * multiple names. Nlock counts the number of
  748. * references the locking thread holds. It will call
  749. * blockPut once per reference.
  750. */
  751. void
  752. blockDupLock(Block *b)
  753. {
  754. assert(b->nlock > 0);
  755. b->nlock++;
  756. }
  757. /*
  758. * we're done with the block.
  759. * unlock it. can't use it after calling this.
  760. */
  761. void
  762. blockPut(Block* b)
  763. {
  764. Cache *c;
  765. if(b == nil)
  766. return;
  767. if(0)fprint(2, "blockPut: %d: %d %x %d %s\n", getpid(), b->part, b->addr, c->nheap, bioStr(b->iostate));
  768. if(b->iostate == BioDirty)
  769. bwatchDependency(b);
  770. if(--b->nlock > 0)
  771. return;
  772. /*
  773. * b->nlock should probably stay at zero while
  774. * the block is unlocked, but diskThread and vtSleep
  775. * conspire to assume that they can just vtLock(b->lk); blockPut(b),
  776. * so we have to keep b->nlock set to 1 even
  777. * when the block is unlocked.
  778. */
  779. assert(b->nlock == 0);
  780. b->nlock = 1;
  781. // b->pc = 0;
  782. bwatchUnlock(b);
  783. vtUnlock(b->lk);
  784. c = b->c;
  785. vtLock(c->lk);
  786. if(--b->ref > 0){
  787. vtUnlock(c->lk);
  788. return;
  789. }
  790. assert(b->ref == 0);
  791. switch(b->iostate){
  792. default:
  793. b->used = c->now++;
  794. heapIns(b);
  795. break;
  796. case BioEmpty:
  797. case BioLabel:
  798. if(c->nheap == 0)
  799. b->used = c->now++;
  800. else
  801. b->used = c->heap[0]->used;
  802. heapIns(b);
  803. break;
  804. case BioDirty:
  805. break;
  806. }
  807. vtUnlock(c->lk);
  808. }
  809. /*
  810. * we're deleting a block; delete all the blocks it points to
  811. * that are still active (i.e., not needed by snapshots).
  812. */
  813. static void
  814. blockCleanup(Block *b, u32int epoch)
  815. {
  816. Cache *c;
  817. Block *bb;
  818. int i, n;
  819. Label l;
  820. u32int a;
  821. int type;
  822. int mode;
  823. type = b->l.type;
  824. c = b->c;
  825. bwatchReset(b->score);
  826. blockSetIOState(b, BioClean);
  827. /* do not recursively free directories */
  828. if(type == BtData || type == BtDir)
  829. return;
  830. n = c->size / VtScoreSize;
  831. mode = OReadWrite;
  832. if(type-1 == BtData || type-1 == BtDir)
  833. mode = OOverWrite;
  834. for(i=0; i<n; i++){
  835. a = globalToLocal(b->data + i*VtScoreSize);
  836. if(a == NilBlock || !readLabel(c, &l, a))
  837. continue;
  838. if((l.state&BsClosed) || l.epoch != epoch)
  839. continue;
  840. bb = cacheLocalData(c, a, type-1, b->l.tag, mode, 0);
  841. if(bb == nil)
  842. continue;
  843. if((bb->l.state&BsClosed) || bb->l.epoch != epoch){
  844. fprint(2, "cleanupBlock: block %ud changed underfoot! expected %L got %L\n",
  845. a, &l, &bb->l);
  846. blockPut(bb);
  847. continue;
  848. }
  849. blockCleanup(bb, epoch);
  850. l.type = BtMax;
  851. l.epoch = epoch;
  852. l.epochClose = 0;
  853. l.state = BsFree;
  854. l.tag = 0;
  855. blockSetLabel(bb, &l);
  856. blockPut(bb);
  857. }
  858. }
  859. /*
  860. * We don't need the block at addr anymore for the active file system.
  861. * If we don't need it for the snapshots, remove it completely.
  862. * Epoch is the epoch during which we got rid of the block.
  863. * See blockRemoveLink for more.
  864. */
  865. static int
  866. unlinkBlock(Cache *c, u32int addr, int type, u32int tag, u32int epoch)
  867. {
  868. Block *b;
  869. Label l;
  870. if(addr == NilBlock)
  871. return 1;
  872. //fprint(2, "unlinkBlock %#ux\n", addr);
  873. b = cacheLocalData(c, addr, type, tag, OReadOnly, 0);
  874. if(b == nil)
  875. return 0;
  876. if(b->l.epoch > epoch){
  877. fprint(2, "unlinkBlock: strange epoch :%ud %ud\n", b->l.epoch, epoch);
  878. blockPut(b);
  879. return 0;
  880. }
  881. l = b->l;
  882. if((b->l.state&BsClosed)==0 && b->l.epoch==epoch){
  883. l.state = BsFree;
  884. l.type = BtMax;
  885. l.tag = 0;
  886. l.epoch = 0;
  887. l.epochClose = 0;
  888. blockCleanup(b, epoch);
  889. }else{
  890. l.state |= BsClosed;
  891. l.epochClose = epoch;
  892. }
  893. blockSetLabel(b, &l);
  894. blockPut(b);
  895. return 1;
  896. }
  897. /*
  898. * try to allocate a BList so we can record that b must
  899. * be written out before some other block.
  900. * if can't find a BList, write b out instead and return nil.
  901. */
  902. static BList *
  903. blistAlloc(Block *b)
  904. {
  905. Cache *c;
  906. BList *p;
  907. /*
  908. * It's possible that when we marked b dirty, there were
  909. * too many dirty blocks so we just wrote b there and then.
  910. * So b might not be dirty. If it's not, no need to worry
  911. * about recording the write constraint.
  912. *
  913. * BlockRemoveLink depends on the fact that if blistAlloc
  914. * returns non-nil, b really is dirty.
  915. */
  916. if(b->iostate != BioDirty){
  917. assert(b->iostate == BioClean);
  918. return nil;
  919. }
  920. /*
  921. * Easy: maybe there's a free list left.
  922. */
  923. c = b->c;
  924. vtLock(c->lk);
  925. if(c->blfree){
  926. HaveBlFree:
  927. p = c->blfree;
  928. c->blfree = p->next;
  929. vtUnlock(c->lk);
  930. return p;
  931. }
  932. vtUnlock(c->lk);
  933. /*
  934. * No free BLists. What are our options?
  935. */
  936. /* Block has no priors? Just write it. */
  937. if(b->prior == nil){
  938. diskWrite(c->disk, b);
  939. while(b->iostate != BioClean)
  940. vtSleep(b->ioready);
  941. return nil;
  942. }
  943. /*
  944. * Wake the flush thread, which will hopefully free up
  945. * some BLists for us. We used to flush a block from
  946. * our own prior list and reclaim that BList, but this is
  947. * a no-no: some of the blocks on our prior list may
  948. * be locked by our caller. Or maybe their label blocks
  949. * are locked by our caller. In any event, it's too hard
  950. * to make sure we can do I/O for ourselves. Instead,
  951. * we assume the flush thread will find something.
  952. * (The flush thread never blocks waiting for a block,
  953. * so it won't deadlock like we will.)
  954. */
  955. vtLock(c->lk);
  956. while(c->blfree == nil){
  957. vtWakeup(c->flush);
  958. vtSleep(c->blrend);
  959. }
  960. goto HaveBlFree;
  961. }
  962. void
  963. blistFree(Cache *c, BList *bl)
  964. {
  965. vtLock(c->lk);
  966. bl->next = c->blfree;
  967. c->blfree = bl;
  968. vtWakeup(c->blrend);
  969. vtUnlock(c->lk);
  970. }
  971. /*
  972. * Flush b or one of the blocks it depends on.
  973. */
  974. void
  975. blockFlush(Block *b)
  976. {
  977. int first, nlock;
  978. BList *p, **pp;
  979. Block *bb;
  980. Cache *c;
  981. //fprint(2, "blockFlush %p\n", b);
  982. c = b->c;
  983. first = 1;
  984. pp = &b->prior;
  985. for(p=*pp; p; p=*pp){
  986. bb = cacheLocalLookup(c, p->part, p->addr, p->vers);
  987. if(bb == nil){
  988. *pp = p->next;
  989. blistFree(c, p);
  990. continue;
  991. }
  992. if(!first)
  993. blockPut(b);
  994. first = 0;
  995. b = bb;
  996. pp = &b->prior;
  997. }
  998. /*
  999. * If b->nlock > 1, the block is aliased within
  1000. * a single thread. That thread is us, and it's
  1001. * the block that was passed in (rather than a prior).
  1002. * DiskWrite does some funny stuff with VtLock
  1003. * and blockPut that basically assumes b->nlock==1.
  1004. * We humor diskWrite by temporarily setting
  1005. * nlock to 1. This needs to be revisited. (TODO)
  1006. */
  1007. nlock = b->nlock;
  1008. if(nlock > 1){
  1009. assert(first);
  1010. b->nlock = 1;
  1011. }
  1012. diskWrite(c->disk, b);
  1013. while(b->iostate != BioClean)
  1014. vtSleep(b->ioready);
  1015. b->nlock = nlock;
  1016. if(!first)
  1017. blockPut(b);
  1018. }
  1019. /*
  1020. * Record that bb must be written out before b.
  1021. * If index is given, we're about to overwrite the score/e
  1022. * at that index in the block. Save the old value so we
  1023. * can write a safer ``old'' version of the block if pressed.
  1024. */
  1025. void
  1026. blockDependency(Block *b, Block *bb, int index, uchar *score, Entry *e)
  1027. {
  1028. BList *p;
  1029. if(bb->iostate == BioClean)
  1030. return;
  1031. /*
  1032. * Dependencies for blocks containing Entry structures
  1033. * or scores must always be explained. The problem with
  1034. * only explaining some of them is this. Suppose we have two
  1035. * dependencies for the same field, the first explained
  1036. * and the second not. We try to write the block when the first
  1037. * dependency is not written but the second is. We will roll back
  1038. * the first change even though the second trumps it.
  1039. */
  1040. if(index == -1 && bb->part == PartData)
  1041. assert(b->l.type == BtData);
  1042. assert(bb->iostate == BioDirty);
  1043. p = blistAlloc(bb);
  1044. if(p == nil)
  1045. return;
  1046. if(0)fprint(2, "%d:%x:%d depends on %d:%x:%d\n", b->part, b->addr, b->l.type, bb->part, bb->addr, bb->l.type);
  1047. p->part = bb->part;
  1048. p->addr = bb->addr;
  1049. p->type = bb->l.type;
  1050. p->vers = bb->vers;
  1051. p->index = index;
  1052. if(p->index >= 0){
  1053. /*
  1054. * This test would just be b->l.type==BtDir except
  1055. * we need to exclude the super block.
  1056. */
  1057. if(b->l.type == BtDir && b->part == PartData)
  1058. entryPack(e, p->old.entry, 0);
  1059. else
  1060. memmove(p->old.score, score, VtScoreSize);
  1061. }
  1062. p->next = b->prior;
  1063. b->prior = p;
  1064. }
  1065. /*
  1066. * Mark an in-memory block as dirty. If there are too many
  1067. * dirty blocks, start writing some out to disk. If there are way
  1068. * too many dirty blocks, write this one out too.
  1069. *
  1070. * Note that since we might call blockFlush, which walks
  1071. * the prior list, we can't call blockDirty while holding a lock
  1072. * on any of our priors. This can be tested by recompiling
  1073. * with flush always set to 1 below.
  1074. */
  1075. int
  1076. blockDirty(Block *b)
  1077. {
  1078. Cache *c;
  1079. int flush;
  1080. c = b->c;
  1081. assert(b->part != PartVenti);
  1082. if(b->iostate == BioDirty)
  1083. return 1;
  1084. assert(b->iostate == BioClean);
  1085. vtLock(c->lk);
  1086. b->iostate = BioDirty;
  1087. c->ndirty++;
  1088. if(c->ndirty > (c->maxdirty>>1))
  1089. vtWakeup(c->flush);
  1090. flush = c->ndirty > c->maxdirty;
  1091. vtUnlock(c->lk);
  1092. if(flush)
  1093. blockFlush(b);
  1094. return 1;
  1095. }
  1096. /*
  1097. * Block b once pointed at the block bb at addr/type/tag, but no longer does.
  1098. *
  1099. * The file system maintains the following invariants (i-iv checked by flchk):
  1100. *
  1101. * (i) b.e in [bb.e, bb.eClose)
  1102. * (ii) if b.e==bb.e, then no other b' in e points at bb.
  1103. * (iii) if !(b.state&Copied) and b.e==bb.e then no other b' points at bb.
  1104. * (iv) if b is active then no other active b' points at bb.
  1105. * (v) if b is a past life of b' then only one of b and b' is active (too hard to check)
  1106. *
  1107. * The file system initially satisfies these invariants, and we can verify that
  1108. * the various file system operations maintain them. See fossil.invariants.
  1109. *
  1110. * Condition (i) lets us reclaim blocks once the low epoch is greater
  1111. * than epochClose.
  1112. *
  1113. * If the condition in (iii) is satisfied, then this is the only pointer to bb,
  1114. * so bb can be reclaimed once b has been written to disk. blockRemoveLink
  1115. * checks !(b.state&Copied) as an optimization. UnlinkBlock and blockCleanup
  1116. * will check the conditions again for each block they consider.
  1117. */
  1118. int
  1119. blockRemoveLink(Block *b, u32int addr, int type, u32int tag)
  1120. {
  1121. BList *bl;
  1122. BList *p, **pp;
  1123. Cache *c;
  1124. c = b->c;
  1125. /* remove unlinked block from prior list */
  1126. pp = &b->prior;
  1127. for(p=*pp; p; p=*pp){
  1128. if(p->part != PartData || p->addr != addr){
  1129. pp = &p->next;
  1130. continue;
  1131. }
  1132. *pp = p->next;
  1133. blistFree(c, p);
  1134. }
  1135. /* if b has been copied, can't reclaim blocks it points at. */
  1136. if(b->l.state & BsCopied)
  1137. return 0;
  1138. bl = blistAlloc(b);
  1139. if(bl == nil)
  1140. return unlinkBlock(b->c, addr, type, tag, b->l.epoch);
  1141. /*
  1142. * Because bl != nil, we know b is dirty.
  1143. * (Linking b->uhead onto a clean block is
  1144. * counterproductive, since we only look at
  1145. * b->uhead when a block transitions from
  1146. * dirty to clean.)
  1147. */
  1148. assert(b->iostate == BioDirty);
  1149. bl->part = PartData;
  1150. bl->addr = addr;
  1151. bl->type = type;
  1152. bl->tag = tag;
  1153. bl->epoch = b->l.epoch;
  1154. if(b->uhead == nil)
  1155. b->uhead = bl;
  1156. else
  1157. b->utail->next = bl;
  1158. b->utail = bl;
  1159. bl->next = nil;
  1160. return 1;
  1161. }
  1162. /*
  1163. * set the label associated with a block.
  1164. */
  1165. Block*
  1166. _blockSetLabel(Block *b, Label *l)
  1167. {
  1168. int lpb;
  1169. Block *bb;
  1170. u32int a;
  1171. Cache *c;
  1172. c = b->c;
  1173. assert(b->part == PartData);
  1174. assert(b->iostate == BioLabel || b->iostate == BioClean || b->iostate == BioDirty);
  1175. lpb = c->size / LabelSize;
  1176. a = b->addr / lpb;
  1177. bb = cacheLocal(c, PartLabel, a, OReadWrite);
  1178. if(bb == nil){
  1179. blockPut(b);
  1180. return nil;
  1181. }
  1182. b->l = *l;
  1183. labelPack(l, bb->data, b->addr%lpb);
  1184. blockDirty(bb);
  1185. return bb;
  1186. }
  1187. int
  1188. blockSetLabel(Block *b, Label *l)
  1189. {
  1190. Block *lb;
  1191. Label oldl;
  1192. oldl = b->l;
  1193. lb = _blockSetLabel(b, l);
  1194. if(lb == nil)
  1195. return 0;
  1196. /*
  1197. * If we're allocating the block, make sure the label (bl)
  1198. * goes to disk before the data block (b) itself. This is to help
  1199. * the blocks that in turn depend on b.
  1200. *
  1201. * Suppose bx depends on (must be written out after) b.
  1202. * Once we write b we'll think it's safe to write bx.
  1203. * Bx can't get at b unless it has a valid label, though.
  1204. *
  1205. * Allocation is the only case in which having a current label
  1206. * is vital because:
  1207. *
  1208. * - l.type is set at allocation and never changes.
  1209. * - l.tag is set at allocation and never changes.
  1210. * - l.state is not checked when we load blocks.
  1211. * - the archiver cares deeply about l.state being
  1212. * BaActive vs. BaCopied, but that's handled
  1213. * by direct calls to _blockSetLabel.
  1214. */
  1215. if(oldl.state == BsFree)
  1216. blockDependency(b, lb, -1, nil, nil);
  1217. blockPut(lb);
  1218. return 1;
  1219. }
  1220. /*
  1221. * We've decided to write out b. Maybe b has some pointers to blocks
  1222. * that haven't yet been written to disk. If so, construct a slightly out-of-date
  1223. * copy of b that is safe to write out. (diskThread will make sure the block
  1224. * remains marked as dirty.)
  1225. */
  1226. uchar *
  1227. blockRollback(Block *b, uchar *buf)
  1228. {
  1229. u32int addr;
  1230. BList *p;
  1231. Super super;
  1232. /* easy case */
  1233. if(b->prior == nil)
  1234. return b->data;
  1235. memmove(buf, b->data, b->c->size);
  1236. for(p=b->prior; p; p=p->next){
  1237. /*
  1238. * we know p->index >= 0 because blockWrite has vetted this block for us.
  1239. */
  1240. assert(p->index >= 0);
  1241. assert(b->part == PartSuper || (b->part == PartData && b->l.type != BtData));
  1242. if(b->part == PartSuper){
  1243. assert(p->index == 0);
  1244. superUnpack(&super, buf);
  1245. addr = globalToLocal(p->old.score);
  1246. if(addr == NilBlock){
  1247. fprint(2, "rolling back super block: bad replacement addr %V\n", p->old.score);
  1248. abort();
  1249. }
  1250. super.active = addr;
  1251. superPack(&super, buf);
  1252. continue;
  1253. }
  1254. if(b->l.type == BtDir)
  1255. memmove(buf+p->index*VtEntrySize, p->old.entry, VtEntrySize);
  1256. else
  1257. memmove(buf+p->index*VtScoreSize, p->old.score, VtScoreSize);
  1258. }
  1259. return buf;
  1260. }
  1261. /*
  1262. * Try to write block b.
  1263. * If b depends on other blocks:
  1264. *
  1265. * If the block has been written out, remove the dependency.
  1266. * If we know how to write out an old version of b that doesn't
  1267. * depend on it, do that.
  1268. *
  1269. * Otherwise, bail.
  1270. */
  1271. int
  1272. blockWrite(Block *b)
  1273. {
  1274. uchar *dmap;
  1275. Cache *c;
  1276. BList *p, **pp;
  1277. Block *bb;
  1278. int lockfail;
  1279. c = b->c;
  1280. if(b->iostate != BioDirty)
  1281. return 1;
  1282. dmap = b->dmap;
  1283. memset(dmap, 0, c->ndmap);
  1284. pp = &b->prior;
  1285. for(p=*pp; p; p=*pp){
  1286. if(p->index >= 0){
  1287. /* more recent dependency has succeeded; this one can go */
  1288. if(dmap[p->index/8] & (1<<(p->index%8)))
  1289. goto ignblock;
  1290. }
  1291. lockfail = 0;
  1292. bb = _cacheLocalLookup(c, p->part, p->addr, p->vers, 0, &lockfail);
  1293. if(bb == nil){
  1294. if(lockfail)
  1295. return 0;
  1296. /* block not in cache => was written already */
  1297. dmap[p->index/8] |= 1<<(p->index%8);
  1298. goto ignblock;
  1299. }
  1300. /*
  1301. * same version of block is still in cache.
  1302. *
  1303. * the assertion is true because the block still has version p->vers,
  1304. * which means it hasn't been written out since we last saw it.
  1305. */
  1306. assert(bb->iostate == BioDirty);
  1307. blockPut(bb);
  1308. if(p->index < 0){
  1309. /*
  1310. * We don't know how to temporarily undo
  1311. * b's dependency on bb, so just don't write b yet.
  1312. */
  1313. if(0) fprint(2, "blockWrite skipping %d %x %d %d; need to write %d %x %d\n",
  1314. b->part, b->addr, b->vers, b->l.type, p->part, p->addr, bb->vers);
  1315. return 0;
  1316. }
  1317. /* keep walking down the list */
  1318. pp = &p->next;
  1319. continue;
  1320. ignblock:
  1321. *pp = p->next;
  1322. blistFree(c, p);
  1323. continue;
  1324. }
  1325. diskWrite(c->disk, b);
  1326. return 1;
  1327. }
  1328. /*
  1329. * Change the I/O state of block b.
  1330. * Just an assignment except for magic in
  1331. * switch statement (read comments there).
  1332. */
  1333. void
  1334. blockSetIOState(Block *b, int iostate)
  1335. {
  1336. int dowakeup;
  1337. Cache *c;
  1338. BList *p, *q;
  1339. if(0) fprint(2, "iostate part=%d addr=%x %s->%s\n", b->part, b->addr, bioStr(b->iostate), bioStr(iostate));
  1340. c = b->c;
  1341. dowakeup = 0;
  1342. switch(iostate){
  1343. default:
  1344. abort();
  1345. case BioEmpty:
  1346. assert(!b->uhead);
  1347. break;
  1348. case BioLabel:
  1349. assert(!b->uhead);
  1350. break;
  1351. case BioClean:
  1352. bwatchDependency(b);
  1353. /*
  1354. * If b->prior is set, it means a write just finished.
  1355. * The prior list isn't needed anymore.
  1356. */
  1357. for(p=b->prior; p; p=q){
  1358. q = p->next;
  1359. blistFree(c, p);
  1360. }
  1361. b->prior = nil;
  1362. /*
  1363. * Freeing a block or just finished a write.
  1364. * Move the blocks from the per-block unlink
  1365. * queue to the cache unlink queue.
  1366. */
  1367. if(b->iostate == BioDirty || b->iostate == BioWriting){
  1368. vtLock(c->lk);
  1369. c->ndirty--;
  1370. b->iostate = iostate; /* change here to keep in sync with ndirty */
  1371. b->vers = c->vers++;
  1372. if(b->uhead){
  1373. /* add unlink blocks to unlink queue */
  1374. if(c->uhead == nil){
  1375. c->uhead = b->uhead;
  1376. vtWakeup(c->unlink);
  1377. }else
  1378. c->utail->next = b->uhead;
  1379. c->utail = b->utail;
  1380. b->uhead = nil;
  1381. }
  1382. vtUnlock(c->lk);
  1383. }
  1384. assert(!b->uhead);
  1385. dowakeup = 1;
  1386. break;
  1387. case BioDirty:
  1388. /*
  1389. * Wrote out an old version of the block (see blockRollback).
  1390. * Bump a version count, leave it dirty.
  1391. */
  1392. if(b->iostate == BioWriting){
  1393. vtLock(c->lk);
  1394. b->vers = c->vers++;
  1395. vtUnlock(c->lk);
  1396. dowakeup = 1;
  1397. }
  1398. break;
  1399. case BioReading:
  1400. case BioWriting:
  1401. /*
  1402. * Adding block to disk queue. Bump reference count.
  1403. * diskThread decs the count later by calling blockPut.
  1404. * This is here because we need to lock c->lk to
  1405. * manipulate the ref count.
  1406. */
  1407. vtLock(c->lk);
  1408. b->ref++;
  1409. vtUnlock(c->lk);
  1410. break;
  1411. case BioReadError:
  1412. case BioVentiError:
  1413. /*
  1414. * Oops.
  1415. */
  1416. dowakeup = 1;
  1417. break;
  1418. }
  1419. b->iostate = iostate;
  1420. /*
  1421. * Now that the state has changed, we can wake the waiters.
  1422. */
  1423. if(dowakeup)
  1424. vtWakeupAll(b->ioready);
  1425. }
  1426. char*
  1427. bsStr(int state)
  1428. {
  1429. static char s[100];
  1430. if(state == BsFree)
  1431. return "Free";
  1432. if(state == BsBad)
  1433. return "Bad";
  1434. sprint(s, "%x", state);
  1435. if(!(state&BsAlloc))
  1436. strcat(s, ",Free"); /* should not happen */
  1437. if(state&BsCopied)
  1438. strcat(s, ",Copied");
  1439. if(state&BsVenti)
  1440. strcat(s, ",Venti");
  1441. if(state&BsClosed)
  1442. strcat(s, ",Closed");
  1443. return s;
  1444. }
  1445. char *
  1446. bioStr(int iostate)
  1447. {
  1448. switch(iostate){
  1449. default:
  1450. return "Unknown!!";
  1451. case BioEmpty:
  1452. return "Empty";
  1453. case BioLabel:
  1454. return "Label";
  1455. case BioClean:
  1456. return "Clean";
  1457. case BioDirty:
  1458. return "Dirty";
  1459. case BioReading:
  1460. return "Reading";
  1461. case BioWriting:
  1462. return "Writing";
  1463. case BioReadError:
  1464. return "ReadError";
  1465. case BioVentiError:
  1466. return "VentiError";
  1467. case BioMax:
  1468. return "Max";
  1469. }
  1470. }
  1471. static char *bttab[] = {
  1472. "BtData",
  1473. "BtData+1",
  1474. "BtData+2",
  1475. "BtData+3",
  1476. "BtData+4",
  1477. "BtData+5",
  1478. "BtData+6",
  1479. "BtData+7",
  1480. "BtDir",
  1481. "BtDir+1",
  1482. "BtDir+2",
  1483. "BtDir+3",
  1484. "BtDir+4",
  1485. "BtDir+5",
  1486. "BtDir+6",
  1487. "BtDir+7",
  1488. };
  1489. char*
  1490. btStr(int type)
  1491. {
  1492. if(type < nelem(bttab))
  1493. return bttab[type];
  1494. return "unknown";
  1495. }
  1496. int
  1497. labelFmt(Fmt *f)
  1498. {
  1499. Label *l;
  1500. l = va_arg(f->args, Label*);
  1501. return fmtprint(f, "%s,%s,e=%ud,%d,tag=%#ux",
  1502. btStr(l->type), bsStr(l->state), l->epoch, (int)l->epochClose, l->tag);
  1503. }
  1504. int
  1505. scoreFmt(Fmt *f)
  1506. {
  1507. uchar *v;
  1508. int i;
  1509. u32int addr;
  1510. v = va_arg(f->args, uchar*);
  1511. if(v == nil){
  1512. fmtprint(f, "*");
  1513. }else if((addr = globalToLocal(v)) != NilBlock)
  1514. fmtprint(f, "0x%.8ux", addr);
  1515. else{
  1516. for(i = 0; i < VtScoreSize; i++)
  1517. fmtprint(f, "%2.2ux", v[i]);
  1518. }
  1519. return 0;
  1520. }
  1521. static int
  1522. upHeap(int i, Block *b)
  1523. {
  1524. Block *bb;
  1525. u32int now;
  1526. int p;
  1527. Cache *c;
  1528. c = b->c;
  1529. now = c->now;
  1530. for(; i != 0; i = p){
  1531. p = (i - 1) >> 1;
  1532. bb = c->heap[p];
  1533. if(b->used - now >= bb->used - now)
  1534. break;
  1535. c->heap[i] = bb;
  1536. bb->heap = i;
  1537. }
  1538. c->heap[i] = b;
  1539. b->heap = i;
  1540. return i;
  1541. }
  1542. static int
  1543. downHeap(int i, Block *b)
  1544. {
  1545. Block *bb;
  1546. u32int now;
  1547. int k;
  1548. Cache *c;
  1549. c = b->c;
  1550. now = c->now;
  1551. for(; ; i = k){
  1552. k = (i << 1) + 1;
  1553. if(k >= c->nheap)
  1554. break;
  1555. if(k + 1 < c->nheap && c->heap[k]->used - now > c->heap[k + 1]->used - now)
  1556. k++;
  1557. bb = c->heap[k];
  1558. if(b->used - now <= bb->used - now)
  1559. break;
  1560. c->heap[i] = bb;
  1561. bb->heap = i;
  1562. }
  1563. c->heap[i] = b;
  1564. b->heap = i;
  1565. return i;
  1566. }
  1567. /*
  1568. * Delete a block from the heap.
  1569. * Called with c->lk held.
  1570. */
  1571. static void
  1572. heapDel(Block *b)
  1573. {
  1574. int i, si;
  1575. Cache *c;
  1576. c = b->c;
  1577. si = b->heap;
  1578. if(si == BadHeap)
  1579. return;
  1580. b->heap = BadHeap;
  1581. c->nheap--;
  1582. if(si == c->nheap)
  1583. return;
  1584. b = c->heap[c->nheap];
  1585. i = upHeap(si, b);
  1586. if(i == si)
  1587. downHeap(i, b);
  1588. }
  1589. /*
  1590. * Insert a block into the heap.
  1591. * Called with c->lk held.
  1592. */
  1593. static void
  1594. heapIns(Block *b)
  1595. {
  1596. assert(b->heap == BadHeap);
  1597. upHeap(b->c->nheap++, b);
  1598. }
  1599. /*
  1600. * Get just the label for a block.
  1601. */
  1602. static int
  1603. readLabel(Cache *c, Label *l, u32int addr)
  1604. {
  1605. int lpb;
  1606. Block *b;
  1607. u32int a;
  1608. lpb = c->size / LabelSize;
  1609. a = addr / lpb;
  1610. b = cacheLocal(c, PartLabel, a, OReadOnly);
  1611. if(b == nil){
  1612. blockPut(b);
  1613. return 0;
  1614. }
  1615. if(!labelUnpack(l, b->data, addr%lpb)){
  1616. blockPut(b);
  1617. return 0;
  1618. }
  1619. blockPut(b);
  1620. return 1;
  1621. }
  1622. /*
  1623. * Process unlink queue.
  1624. * Called with c->lk held.
  1625. */
  1626. static void
  1627. unlinkBody(Cache *c)
  1628. {
  1629. BList *p;
  1630. while(c->uhead != nil){
  1631. p = c->uhead;
  1632. c->uhead = p->next;
  1633. vtUnlock(c->lk);
  1634. if(!unlinkBlock(c, p->addr, p->type, p->tag, p->epoch))
  1635. fprint(2, "unlinkBlock failed: addr=%x type=%d tag = %ux: %r\n",
  1636. p->addr, p->type, p->tag);
  1637. vtLock(c->lk);
  1638. p->next = c->blfree;
  1639. c->blfree = p;
  1640. }
  1641. }
  1642. /*
  1643. * Occasionally unlink the blocks on the cache unlink queue.
  1644. */
  1645. static void
  1646. unlinkThread(void *a)
  1647. {
  1648. Cache *c = a;
  1649. vtThreadSetName("unlink");
  1650. vtLock(c->lk);
  1651. for(;;){
  1652. while(c->uhead == nil && c->die == nil)
  1653. vtSleep(c->unlink);
  1654. if(c->die != nil)
  1655. break;
  1656. unlinkBody(c);
  1657. }
  1658. c->ref--;
  1659. vtWakeup(c->die);
  1660. vtUnlock(c->lk);
  1661. }
  1662. static int
  1663. baddrCmp(void *a0, void *a1)
  1664. {
  1665. BAddr *b0, *b1;
  1666. b0 = a0;
  1667. b1 = a1;
  1668. if(b0->part < b1->part)
  1669. return -1;
  1670. if(b0->part > b1->part)
  1671. return 1;
  1672. if(b0->addr < b1->addr)
  1673. return -1;
  1674. if(b0->addr > b1->addr)
  1675. return 1;
  1676. return 0;
  1677. }
  1678. /*
  1679. * Scan the block list for dirty blocks; add them to the list c->baddr.
  1680. */
  1681. static void
  1682. flushFill(Cache *c)
  1683. {
  1684. int i, ndirty;
  1685. BAddr *p;
  1686. Block *b;
  1687. vtLock(c->lk);
  1688. // if(c->ndirty == 0){
  1689. // vtUnlock(c->lk);
  1690. // return;
  1691. // }
  1692. p = c->baddr;
  1693. ndirty = 0;
  1694. for(i=0; i<c->nblocks; i++){
  1695. b = c->blocks + i;
  1696. if(b->part == PartError)
  1697. continue;
  1698. if(b->iostate == BioDirty || b->iostate == BioWriting)
  1699. ndirty++;
  1700. if(b->iostate != BioDirty)
  1701. continue;
  1702. p->part = b->part;
  1703. p->addr = b->addr;
  1704. p->vers = b->vers;
  1705. p++;
  1706. }
  1707. if(ndirty != c->ndirty){
  1708. fprint(2, "ndirty mismatch expected %d found %d\n",
  1709. c->ndirty, ndirty);
  1710. c->ndirty = ndirty;
  1711. }
  1712. vtUnlock(c->lk);
  1713. c->bw = p - c->baddr;
  1714. qsort(c->baddr, c->bw, sizeof(BAddr), baddrCmp);
  1715. }
  1716. /*
  1717. * This is not thread safe, i.e. it can't be called from multiple threads.
  1718. *
  1719. * It's okay how we use it, because it only gets called in
  1720. * the flushThread. And cacheFree, but only after
  1721. * cacheFree has killed off the flushThread.
  1722. */
  1723. static int
  1724. cacheFlushBlock(Cache *c)
  1725. {
  1726. Block *b;
  1727. BAddr *p;
  1728. int lockfail, nfail;
  1729. nfail = 0;
  1730. for(;;){
  1731. if(c->br == c->be){
  1732. if(c->bw == 0 || c->bw == c->be)
  1733. flushFill(c);
  1734. c->br = 0;
  1735. c->be = c->bw;
  1736. c->bw = 0;
  1737. c->nflush = 0;
  1738. }
  1739. if(c->br == c->be)
  1740. return 0;
  1741. p = c->baddr + c->br;
  1742. c->br++;
  1743. b = _cacheLocalLookup(c, p->part, p->addr, p->vers, 0, &lockfail);
  1744. if(b && blockWrite(b)){
  1745. c->nflush++;
  1746. blockPut(b);
  1747. return 1;
  1748. }
  1749. if(b)
  1750. blockPut(b);
  1751. /*
  1752. * Why didn't we write the block?
  1753. */
  1754. /* Block already written out */
  1755. if(b == nil && !lockfail)
  1756. continue;
  1757. /* Failed to acquire lock; sleep if happens a lot. */
  1758. if(lockfail && ++nfail > 100)
  1759. sleep(500);
  1760. /* Requeue block. */
  1761. if(c->bw < c->be)
  1762. c->baddr[c->bw++] = *p;
  1763. }
  1764. return 0;
  1765. }
  1766. /*
  1767. * Occasionally flush dirty blocks from memory to the disk.
  1768. */
  1769. static void
  1770. flushThread(void *a)
  1771. {
  1772. Cache *c = a;
  1773. int i;
  1774. vtThreadSetName("flush");
  1775. vtLock(c->lk);
  1776. while(c->die == nil){
  1777. vtSleep(c->flush);
  1778. vtUnlock(c->lk);
  1779. for(i=0; i<FlushSize; i++)
  1780. if(!cacheFlushBlock(c))
  1781. break;
  1782. vtLock(c->lk);
  1783. vtWakeupAll(c->flushwait);
  1784. }
  1785. c->ref--;
  1786. vtWakeup(c->die);
  1787. vtUnlock(c->lk);
  1788. }
  1789. /*
  1790. * Keep flushing until everything is clean.
  1791. */
  1792. void
  1793. cacheFlush(Cache *c, int wait)
  1794. {
  1795. vtLock(c->lk);
  1796. if(wait){
  1797. while(c->ndirty){
  1798. consPrint("cacheFlush: %d dirty blocks\n", c->ndirty);
  1799. vtWakeup(c->flush);
  1800. vtSleep(c->flushwait);
  1801. }
  1802. consPrint("cacheFlush: done\n", c->ndirty);
  1803. }else
  1804. vtWakeup(c->flush);
  1805. vtUnlock(c->lk);
  1806. }
  1807. /*
  1808. * Kick the flushThread every 30 seconds.
  1809. */
  1810. static void
  1811. cacheSync(void *v)
  1812. {
  1813. Cache *c;
  1814. c = v;
  1815. cacheFlush(c, 0);
  1816. }