cache.c 44 KB

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