cache.c 42 KB

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