cache.c 43 KB

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