cache.c 42 KB

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