cache.c 43 KB

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