cache.c 43 KB

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