cache.c 43 KB

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