bcache.h 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  1. #ifndef _BCACHE_H
  2. #define _BCACHE_H
  3. /*
  4. * SOME HIGH LEVEL CODE DOCUMENTATION:
  5. *
  6. * Bcache mostly works with cache sets, cache devices, and backing devices.
  7. *
  8. * Support for multiple cache devices hasn't quite been finished off yet, but
  9. * it's about 95% plumbed through. A cache set and its cache devices is sort of
  10. * like a md raid array and its component devices. Most of the code doesn't care
  11. * about individual cache devices, the main abstraction is the cache set.
  12. *
  13. * Multiple cache devices is intended to give us the ability to mirror dirty
  14. * cached data and metadata, without mirroring clean cached data.
  15. *
  16. * Backing devices are different, in that they have a lifetime independent of a
  17. * cache set. When you register a newly formatted backing device it'll come up
  18. * in passthrough mode, and then you can attach and detach a backing device from
  19. * a cache set at runtime - while it's mounted and in use. Detaching implicitly
  20. * invalidates any cached data for that backing device.
  21. *
  22. * A cache set can have multiple (many) backing devices attached to it.
  23. *
  24. * There's also flash only volumes - this is the reason for the distinction
  25. * between struct cached_dev and struct bcache_device. A flash only volume
  26. * works much like a bcache device that has a backing device, except the
  27. * "cached" data is always dirty. The end result is that we get thin
  28. * provisioning with very little additional code.
  29. *
  30. * Flash only volumes work but they're not production ready because the moving
  31. * garbage collector needs more work. More on that later.
  32. *
  33. * BUCKETS/ALLOCATION:
  34. *
  35. * Bcache is primarily designed for caching, which means that in normal
  36. * operation all of our available space will be allocated. Thus, we need an
  37. * efficient way of deleting things from the cache so we can write new things to
  38. * it.
  39. *
  40. * To do this, we first divide the cache device up into buckets. A bucket is the
  41. * unit of allocation; they're typically around 1 mb - anywhere from 128k to 2M+
  42. * works efficiently.
  43. *
  44. * Each bucket has a 16 bit priority, and an 8 bit generation associated with
  45. * it. The gens and priorities for all the buckets are stored contiguously and
  46. * packed on disk (in a linked list of buckets - aside from the superblock, all
  47. * of bcache's metadata is stored in buckets).
  48. *
  49. * The priority is used to implement an LRU. We reset a bucket's priority when
  50. * we allocate it or on cache it, and every so often we decrement the priority
  51. * of each bucket. It could be used to implement something more sophisticated,
  52. * if anyone ever gets around to it.
  53. *
  54. * The generation is used for invalidating buckets. Each pointer also has an 8
  55. * bit generation embedded in it; for a pointer to be considered valid, its gen
  56. * must match the gen of the bucket it points into. Thus, to reuse a bucket all
  57. * we have to do is increment its gen (and write its new gen to disk; we batch
  58. * this up).
  59. *
  60. * Bcache is entirely COW - we never write twice to a bucket, even buckets that
  61. * contain metadata (including btree nodes).
  62. *
  63. * THE BTREE:
  64. *
  65. * Bcache is in large part design around the btree.
  66. *
  67. * At a high level, the btree is just an index of key -> ptr tuples.
  68. *
  69. * Keys represent extents, and thus have a size field. Keys also have a variable
  70. * number of pointers attached to them (potentially zero, which is handy for
  71. * invalidating the cache).
  72. *
  73. * The key itself is an inode:offset pair. The inode number corresponds to a
  74. * backing device or a flash only volume. The offset is the ending offset of the
  75. * extent within the inode - not the starting offset; this makes lookups
  76. * slightly more convenient.
  77. *
  78. * Pointers contain the cache device id, the offset on that device, and an 8 bit
  79. * generation number. More on the gen later.
  80. *
  81. * Index lookups are not fully abstracted - cache lookups in particular are
  82. * still somewhat mixed in with the btree code, but things are headed in that
  83. * direction.
  84. *
  85. * Updates are fairly well abstracted, though. There are two different ways of
  86. * updating the btree; insert and replace.
  87. *
  88. * BTREE_INSERT will just take a list of keys and insert them into the btree -
  89. * overwriting (possibly only partially) any extents they overlap with. This is
  90. * used to update the index after a write.
  91. *
  92. * BTREE_REPLACE is really cmpxchg(); it inserts a key into the btree iff it is
  93. * overwriting a key that matches another given key. This is used for inserting
  94. * data into the cache after a cache miss, and for background writeback, and for
  95. * the moving garbage collector.
  96. *
  97. * There is no "delete" operation; deleting things from the index is
  98. * accomplished by either by invalidating pointers (by incrementing a bucket's
  99. * gen) or by inserting a key with 0 pointers - which will overwrite anything
  100. * previously present at that location in the index.
  101. *
  102. * This means that there are always stale/invalid keys in the btree. They're
  103. * filtered out by the code that iterates through a btree node, and removed when
  104. * a btree node is rewritten.
  105. *
  106. * BTREE NODES:
  107. *
  108. * Our unit of allocation is a bucket, and we we can't arbitrarily allocate and
  109. * free smaller than a bucket - so, that's how big our btree nodes are.
  110. *
  111. * (If buckets are really big we'll only use part of the bucket for a btree node
  112. * - no less than 1/4th - but a bucket still contains no more than a single
  113. * btree node. I'd actually like to change this, but for now we rely on the
  114. * bucket's gen for deleting btree nodes when we rewrite/split a node.)
  115. *
  116. * Anyways, btree nodes are big - big enough to be inefficient with a textbook
  117. * btree implementation.
  118. *
  119. * The way this is solved is that btree nodes are internally log structured; we
  120. * can append new keys to an existing btree node without rewriting it. This
  121. * means each set of keys we write is sorted, but the node is not.
  122. *
  123. * We maintain this log structure in memory - keeping 1Mb of keys sorted would
  124. * be expensive, and we have to distinguish between the keys we have written and
  125. * the keys we haven't. So to do a lookup in a btree node, we have to search
  126. * each sorted set. But we do merge written sets together lazily, so the cost of
  127. * these extra searches is quite low (normally most of the keys in a btree node
  128. * will be in one big set, and then there'll be one or two sets that are much
  129. * smaller).
  130. *
  131. * This log structure makes bcache's btree more of a hybrid between a
  132. * conventional btree and a compacting data structure, with some of the
  133. * advantages of both.
  134. *
  135. * GARBAGE COLLECTION:
  136. *
  137. * We can't just invalidate any bucket - it might contain dirty data or
  138. * metadata. If it once contained dirty data, other writes might overwrite it
  139. * later, leaving no valid pointers into that bucket in the index.
  140. *
  141. * Thus, the primary purpose of garbage collection is to find buckets to reuse.
  142. * It also counts how much valid data it each bucket currently contains, so that
  143. * allocation can reuse buckets sooner when they've been mostly overwritten.
  144. *
  145. * It also does some things that are really internal to the btree
  146. * implementation. If a btree node contains pointers that are stale by more than
  147. * some threshold, it rewrites the btree node to avoid the bucket's generation
  148. * wrapping around. It also merges adjacent btree nodes if they're empty enough.
  149. *
  150. * THE JOURNAL:
  151. *
  152. * Bcache's journal is not necessary for consistency; we always strictly
  153. * order metadata writes so that the btree and everything else is consistent on
  154. * disk in the event of an unclean shutdown, and in fact bcache had writeback
  155. * caching (with recovery from unclean shutdown) before journalling was
  156. * implemented.
  157. *
  158. * Rather, the journal is purely a performance optimization; we can't complete a
  159. * write until we've updated the index on disk, otherwise the cache would be
  160. * inconsistent in the event of an unclean shutdown. This means that without the
  161. * journal, on random write workloads we constantly have to update all the leaf
  162. * nodes in the btree, and those writes will be mostly empty (appending at most
  163. * a few keys each) - highly inefficient in terms of amount of metadata writes,
  164. * and it puts more strain on the various btree resorting/compacting code.
  165. *
  166. * The journal is just a log of keys we've inserted; on startup we just reinsert
  167. * all the keys in the open journal entries. That means that when we're updating
  168. * a node in the btree, we can wait until a 4k block of keys fills up before
  169. * writing them out.
  170. *
  171. * For simplicity, we only journal updates to leaf nodes; updates to parent
  172. * nodes are rare enough (since our leaf nodes are huge) that it wasn't worth
  173. * the complexity to deal with journalling them (in particular, journal replay)
  174. * - updates to non leaf nodes just happen synchronously (see btree_split()).
  175. */
  176. #define pr_fmt(fmt) "bcache: %s() " fmt "\n", __func__
  177. #include <linux/bcache.h>
  178. #include <linux/bio.h>
  179. #include <linux/kobject.h>
  180. #include <linux/list.h>
  181. #include <linux/mutex.h>
  182. #include <linux/rbtree.h>
  183. #include <linux/rwsem.h>
  184. #include <linux/types.h>
  185. #include <linux/workqueue.h>
  186. #include "util.h"
  187. #include "closure.h"
  188. struct bucket {
  189. atomic_t pin;
  190. uint16_t prio;
  191. uint8_t gen;
  192. uint8_t disk_gen;
  193. uint8_t last_gc; /* Most out of date gen in the btree */
  194. uint8_t gc_gen;
  195. uint16_t gc_mark;
  196. };
  197. /*
  198. * I'd use bitfields for these, but I don't trust the compiler not to screw me
  199. * as multiple threads touch struct bucket without locking
  200. */
  201. BITMASK(GC_MARK, struct bucket, gc_mark, 0, 2);
  202. #define GC_MARK_RECLAIMABLE 0
  203. #define GC_MARK_DIRTY 1
  204. #define GC_MARK_METADATA 2
  205. BITMASK(GC_SECTORS_USED, struct bucket, gc_mark, 2, 14);
  206. #include "journal.h"
  207. #include "stats.h"
  208. struct search;
  209. struct btree;
  210. struct keybuf;
  211. struct keybuf_key {
  212. struct rb_node node;
  213. BKEY_PADDED(key);
  214. void *private;
  215. };
  216. struct keybuf {
  217. struct bkey last_scanned;
  218. spinlock_t lock;
  219. /*
  220. * Beginning and end of range in rb tree - so that we can skip taking
  221. * lock and checking the rb tree when we need to check for overlapping
  222. * keys.
  223. */
  224. struct bkey start;
  225. struct bkey end;
  226. struct rb_root keys;
  227. #define KEYBUF_NR 100
  228. DECLARE_ARRAY_ALLOCATOR(struct keybuf_key, freelist, KEYBUF_NR);
  229. };
  230. struct bio_split_pool {
  231. struct bio_set *bio_split;
  232. mempool_t *bio_split_hook;
  233. };
  234. struct bio_split_hook {
  235. struct closure cl;
  236. struct bio_split_pool *p;
  237. struct bio *bio;
  238. bio_end_io_t *bi_end_io;
  239. void *bi_private;
  240. };
  241. struct bcache_device {
  242. struct closure cl;
  243. struct kobject kobj;
  244. struct cache_set *c;
  245. unsigned id;
  246. #define BCACHEDEVNAME_SIZE 12
  247. char name[BCACHEDEVNAME_SIZE];
  248. struct gendisk *disk;
  249. /* If nonzero, we're closing */
  250. atomic_t closing;
  251. /* If nonzero, we're detaching/unregistering from cache set */
  252. atomic_t detaching;
  253. int flush_done;
  254. uint64_t nr_stripes;
  255. unsigned stripe_size;
  256. atomic_t *stripe_sectors_dirty;
  257. unsigned long sectors_dirty_last;
  258. long sectors_dirty_derivative;
  259. mempool_t *unaligned_bvec;
  260. struct bio_set *bio_split;
  261. unsigned data_csum:1;
  262. int (*cache_miss)(struct btree *, struct search *,
  263. struct bio *, unsigned);
  264. int (*ioctl) (struct bcache_device *, fmode_t, unsigned, unsigned long);
  265. struct bio_split_pool bio_split_hook;
  266. };
  267. struct io {
  268. /* Used to track sequential IO so it can be skipped */
  269. struct hlist_node hash;
  270. struct list_head lru;
  271. unsigned long jiffies;
  272. unsigned sequential;
  273. sector_t last;
  274. };
  275. struct cached_dev {
  276. struct list_head list;
  277. struct bcache_device disk;
  278. struct block_device *bdev;
  279. struct cache_sb sb;
  280. struct bio sb_bio;
  281. struct bio_vec sb_bv[1];
  282. struct closure_with_waitlist sb_write;
  283. /* Refcount on the cache set. Always nonzero when we're caching. */
  284. atomic_t count;
  285. struct work_struct detach;
  286. /*
  287. * Device might not be running if it's dirty and the cache set hasn't
  288. * showed up yet.
  289. */
  290. atomic_t running;
  291. /*
  292. * Writes take a shared lock from start to finish; scanning for dirty
  293. * data to refill the rb tree requires an exclusive lock.
  294. */
  295. struct rw_semaphore writeback_lock;
  296. /*
  297. * Nonzero, and writeback has a refcount (d->count), iff there is dirty
  298. * data in the cache. Protected by writeback_lock; must have an
  299. * shared lock to set and exclusive lock to clear.
  300. */
  301. atomic_t has_dirty;
  302. struct bch_ratelimit writeback_rate;
  303. struct delayed_work writeback_rate_update;
  304. /*
  305. * Internal to the writeback code, so read_dirty() can keep track of
  306. * where it's at.
  307. */
  308. sector_t last_read;
  309. /* Limit number of writeback bios in flight */
  310. struct semaphore in_flight;
  311. struct task_struct *writeback_thread;
  312. struct keybuf writeback_keys;
  313. /* For tracking sequential IO */
  314. #define RECENT_IO_BITS 7
  315. #define RECENT_IO (1 << RECENT_IO_BITS)
  316. struct io io[RECENT_IO];
  317. struct hlist_head io_hash[RECENT_IO + 1];
  318. struct list_head io_lru;
  319. spinlock_t io_lock;
  320. struct cache_accounting accounting;
  321. /* The rest of this all shows up in sysfs */
  322. unsigned sequential_cutoff;
  323. unsigned readahead;
  324. unsigned sequential_merge:1;
  325. unsigned verify:1;
  326. unsigned partial_stripes_expensive:1;
  327. unsigned writeback_metadata:1;
  328. unsigned writeback_running:1;
  329. unsigned char writeback_percent;
  330. unsigned writeback_delay;
  331. int writeback_rate_change;
  332. int64_t writeback_rate_derivative;
  333. uint64_t writeback_rate_target;
  334. unsigned writeback_rate_update_seconds;
  335. unsigned writeback_rate_d_term;
  336. unsigned writeback_rate_p_term_inverse;
  337. unsigned writeback_rate_d_smooth;
  338. };
  339. enum alloc_watermarks {
  340. WATERMARK_PRIO,
  341. WATERMARK_METADATA,
  342. WATERMARK_MOVINGGC,
  343. WATERMARK_NONE,
  344. WATERMARK_MAX
  345. };
  346. struct cache {
  347. struct cache_set *set;
  348. struct cache_sb sb;
  349. struct bio sb_bio;
  350. struct bio_vec sb_bv[1];
  351. struct kobject kobj;
  352. struct block_device *bdev;
  353. unsigned watermark[WATERMARK_MAX];
  354. struct task_struct *alloc_thread;
  355. struct closure prio;
  356. struct prio_set *disk_buckets;
  357. /*
  358. * When allocating new buckets, prio_write() gets first dibs - since we
  359. * may not be allocate at all without writing priorities and gens.
  360. * prio_buckets[] contains the last buckets we wrote priorities to (so
  361. * gc can mark them as metadata), prio_next[] contains the buckets
  362. * allocated for the next prio write.
  363. */
  364. uint64_t *prio_buckets;
  365. uint64_t *prio_last_buckets;
  366. /*
  367. * free: Buckets that are ready to be used
  368. *
  369. * free_inc: Incoming buckets - these are buckets that currently have
  370. * cached data in them, and we can't reuse them until after we write
  371. * their new gen to disk. After prio_write() finishes writing the new
  372. * gens/prios, they'll be moved to the free list (and possibly discarded
  373. * in the process)
  374. *
  375. * unused: GC found nothing pointing into these buckets (possibly
  376. * because all the data they contained was overwritten), so we only
  377. * need to discard them before they can be moved to the free list.
  378. */
  379. DECLARE_FIFO(long, free);
  380. DECLARE_FIFO(long, free_inc);
  381. DECLARE_FIFO(long, unused);
  382. size_t fifo_last_bucket;
  383. /* Allocation stuff: */
  384. struct bucket *buckets;
  385. DECLARE_HEAP(struct bucket *, heap);
  386. /*
  387. * max(gen - disk_gen) for all buckets. When it gets too big we have to
  388. * call prio_write() to keep gens from wrapping.
  389. */
  390. uint8_t need_save_prio;
  391. unsigned gc_move_threshold;
  392. /*
  393. * If nonzero, we know we aren't going to find any buckets to invalidate
  394. * until a gc finishes - otherwise we could pointlessly burn a ton of
  395. * cpu
  396. */
  397. unsigned invalidate_needs_gc:1;
  398. bool discard; /* Get rid of? */
  399. struct journal_device journal;
  400. /* The rest of this all shows up in sysfs */
  401. #define IO_ERROR_SHIFT 20
  402. atomic_t io_errors;
  403. atomic_t io_count;
  404. atomic_long_t meta_sectors_written;
  405. atomic_long_t btree_sectors_written;
  406. atomic_long_t sectors_written;
  407. struct bio_split_pool bio_split_hook;
  408. };
  409. struct gc_stat {
  410. size_t nodes;
  411. size_t key_bytes;
  412. size_t nkeys;
  413. uint64_t data; /* sectors */
  414. unsigned in_use; /* percent */
  415. };
  416. /*
  417. * Flag bits, for how the cache set is shutting down, and what phase it's at:
  418. *
  419. * CACHE_SET_UNREGISTERING means we're not just shutting down, we're detaching
  420. * all the backing devices first (their cached data gets invalidated, and they
  421. * won't automatically reattach).
  422. *
  423. * CACHE_SET_STOPPING always gets set first when we're closing down a cache set;
  424. * we'll continue to run normally for awhile with CACHE_SET_STOPPING set (i.e.
  425. * flushing dirty data).
  426. */
  427. #define CACHE_SET_UNREGISTERING 0
  428. #define CACHE_SET_STOPPING 1
  429. struct cache_set {
  430. struct closure cl;
  431. struct list_head list;
  432. struct kobject kobj;
  433. struct kobject internal;
  434. struct dentry *debug;
  435. struct cache_accounting accounting;
  436. unsigned long flags;
  437. struct cache_sb sb;
  438. struct cache *cache[MAX_CACHES_PER_SET];
  439. struct cache *cache_by_alloc[MAX_CACHES_PER_SET];
  440. int caches_loaded;
  441. struct bcache_device **devices;
  442. struct list_head cached_devs;
  443. uint64_t cached_dev_sectors;
  444. struct closure caching;
  445. struct closure_with_waitlist sb_write;
  446. mempool_t *search;
  447. mempool_t *bio_meta;
  448. struct bio_set *bio_split;
  449. /* For the btree cache */
  450. struct shrinker shrink;
  451. /* For the btree cache and anything allocation related */
  452. struct mutex bucket_lock;
  453. /* log2(bucket_size), in sectors */
  454. unsigned short bucket_bits;
  455. /* log2(block_size), in sectors */
  456. unsigned short block_bits;
  457. /*
  458. * Default number of pages for a new btree node - may be less than a
  459. * full bucket
  460. */
  461. unsigned btree_pages;
  462. /*
  463. * Lists of struct btrees; lru is the list for structs that have memory
  464. * allocated for actual btree node, freed is for structs that do not.
  465. *
  466. * We never free a struct btree, except on shutdown - we just put it on
  467. * the btree_cache_freed list and reuse it later. This simplifies the
  468. * code, and it doesn't cost us much memory as the memory usage is
  469. * dominated by buffers that hold the actual btree node data and those
  470. * can be freed - and the number of struct btrees allocated is
  471. * effectively bounded.
  472. *
  473. * btree_cache_freeable effectively is a small cache - we use it because
  474. * high order page allocations can be rather expensive, and it's quite
  475. * common to delete and allocate btree nodes in quick succession. It
  476. * should never grow past ~2-3 nodes in practice.
  477. */
  478. struct list_head btree_cache;
  479. struct list_head btree_cache_freeable;
  480. struct list_head btree_cache_freed;
  481. /* Number of elements in btree_cache + btree_cache_freeable lists */
  482. unsigned bucket_cache_used;
  483. /*
  484. * If we need to allocate memory for a new btree node and that
  485. * allocation fails, we can cannibalize another node in the btree cache
  486. * to satisfy the allocation. However, only one thread can be doing this
  487. * at a time, for obvious reasons - try_harder and try_wait are
  488. * basically a lock for this that we can wait on asynchronously. The
  489. * btree_root() macro releases the lock when it returns.
  490. */
  491. struct task_struct *try_harder;
  492. wait_queue_head_t try_wait;
  493. uint64_t try_harder_start;
  494. /*
  495. * When we free a btree node, we increment the gen of the bucket the
  496. * node is in - but we can't rewrite the prios and gens until we
  497. * finished whatever it is we were doing, otherwise after a crash the
  498. * btree node would be freed but for say a split, we might not have the
  499. * pointers to the new nodes inserted into the btree yet.
  500. *
  501. * This is a refcount that blocks prio_write() until the new keys are
  502. * written.
  503. */
  504. atomic_t prio_blocked;
  505. wait_queue_head_t bucket_wait;
  506. /*
  507. * For any bio we don't skip we subtract the number of sectors from
  508. * rescale; when it hits 0 we rescale all the bucket priorities.
  509. */
  510. atomic_t rescale;
  511. /*
  512. * When we invalidate buckets, we use both the priority and the amount
  513. * of good data to determine which buckets to reuse first - to weight
  514. * those together consistently we keep track of the smallest nonzero
  515. * priority of any bucket.
  516. */
  517. uint16_t min_prio;
  518. /*
  519. * max(gen - gc_gen) for all buckets. When it gets too big we have to gc
  520. * to keep gens from wrapping around.
  521. */
  522. uint8_t need_gc;
  523. struct gc_stat gc_stats;
  524. size_t nbuckets;
  525. struct task_struct *gc_thread;
  526. /* Where in the btree gc currently is */
  527. struct bkey gc_done;
  528. /*
  529. * The allocation code needs gc_mark in struct bucket to be correct, but
  530. * it's not while a gc is in progress. Protected by bucket_lock.
  531. */
  532. int gc_mark_valid;
  533. /* Counts how many sectors bio_insert has added to the cache */
  534. atomic_t sectors_to_gc;
  535. wait_queue_head_t moving_gc_wait;
  536. struct keybuf moving_gc_keys;
  537. /* Number of moving GC bios in flight */
  538. struct semaphore moving_in_flight;
  539. struct btree *root;
  540. #ifdef CONFIG_BCACHE_DEBUG
  541. struct btree *verify_data;
  542. struct mutex verify_lock;
  543. #endif
  544. unsigned nr_uuids;
  545. struct uuid_entry *uuids;
  546. BKEY_PADDED(uuid_bucket);
  547. struct closure_with_waitlist uuid_write;
  548. /*
  549. * A btree node on disk could have too many bsets for an iterator to fit
  550. * on the stack - have to dynamically allocate them
  551. */
  552. mempool_t *fill_iter;
  553. /*
  554. * btree_sort() is a merge sort and requires temporary space - single
  555. * element mempool
  556. */
  557. struct mutex sort_lock;
  558. struct bset *sort;
  559. unsigned sort_crit_factor;
  560. /* List of buckets we're currently writing data to */
  561. struct list_head data_buckets;
  562. spinlock_t data_bucket_lock;
  563. struct journal journal;
  564. #define CONGESTED_MAX 1024
  565. unsigned congested_last_us;
  566. atomic_t congested;
  567. /* The rest of this all shows up in sysfs */
  568. unsigned congested_read_threshold_us;
  569. unsigned congested_write_threshold_us;
  570. spinlock_t sort_time_lock;
  571. struct time_stats sort_time;
  572. struct time_stats btree_gc_time;
  573. struct time_stats btree_split_time;
  574. spinlock_t btree_read_time_lock;
  575. struct time_stats btree_read_time;
  576. struct time_stats try_harder_time;
  577. atomic_long_t cache_read_races;
  578. atomic_long_t writeback_keys_done;
  579. atomic_long_t writeback_keys_failed;
  580. enum {
  581. ON_ERROR_UNREGISTER,
  582. ON_ERROR_PANIC,
  583. } on_error;
  584. unsigned error_limit;
  585. unsigned error_decay;
  586. unsigned short journal_delay_ms;
  587. unsigned verify:1;
  588. unsigned key_merging_disabled:1;
  589. unsigned expensive_debug_checks:1;
  590. unsigned gc_always_rewrite:1;
  591. unsigned shrinker_disabled:1;
  592. unsigned copy_gc_enabled:1;
  593. #define BUCKET_HASH_BITS 12
  594. struct hlist_head bucket_hash[1 << BUCKET_HASH_BITS];
  595. };
  596. struct bbio {
  597. unsigned submit_time_us;
  598. union {
  599. struct bkey key;
  600. uint64_t _pad[3];
  601. /*
  602. * We only need pad = 3 here because we only ever carry around a
  603. * single pointer - i.e. the pointer we're doing io to/from.
  604. */
  605. };
  606. struct bio bio;
  607. };
  608. static inline unsigned local_clock_us(void)
  609. {
  610. return local_clock() >> 10;
  611. }
  612. #define BTREE_PRIO USHRT_MAX
  613. #define INITIAL_PRIO 32768
  614. #define btree_bytes(c) ((c)->btree_pages * PAGE_SIZE)
  615. #define btree_blocks(b) \
  616. ((unsigned) (KEY_SIZE(&b->key) >> (b)->c->block_bits))
  617. #define btree_default_blocks(c) \
  618. ((unsigned) ((PAGE_SECTORS * (c)->btree_pages) >> (c)->block_bits))
  619. #define bucket_pages(c) ((c)->sb.bucket_size / PAGE_SECTORS)
  620. #define bucket_bytes(c) ((c)->sb.bucket_size << 9)
  621. #define block_bytes(c) ((c)->sb.block_size << 9)
  622. #define __set_bytes(i, k) (sizeof(*(i)) + (k) * sizeof(uint64_t))
  623. #define set_bytes(i) __set_bytes(i, i->keys)
  624. #define __set_blocks(i, k, c) DIV_ROUND_UP(__set_bytes(i, k), block_bytes(c))
  625. #define set_blocks(i, c) __set_blocks(i, (i)->keys, c)
  626. #define node(i, j) ((struct bkey *) ((i)->d + (j)))
  627. #define end(i) node(i, (i)->keys)
  628. #define index(i, b) \
  629. ((size_t) (((void *) i - (void *) (b)->sets[0].data) / \
  630. block_bytes(b->c)))
  631. #define btree_data_space(b) (PAGE_SIZE << (b)->page_order)
  632. #define prios_per_bucket(c) \
  633. ((bucket_bytes(c) - sizeof(struct prio_set)) / \
  634. sizeof(struct bucket_disk))
  635. #define prio_buckets(c) \
  636. DIV_ROUND_UP((size_t) (c)->sb.nbuckets, prios_per_bucket(c))
  637. static inline size_t sector_to_bucket(struct cache_set *c, sector_t s)
  638. {
  639. return s >> c->bucket_bits;
  640. }
  641. static inline sector_t bucket_to_sector(struct cache_set *c, size_t b)
  642. {
  643. return ((sector_t) b) << c->bucket_bits;
  644. }
  645. static inline sector_t bucket_remainder(struct cache_set *c, sector_t s)
  646. {
  647. return s & (c->sb.bucket_size - 1);
  648. }
  649. static inline struct cache *PTR_CACHE(struct cache_set *c,
  650. const struct bkey *k,
  651. unsigned ptr)
  652. {
  653. return c->cache[PTR_DEV(k, ptr)];
  654. }
  655. static inline size_t PTR_BUCKET_NR(struct cache_set *c,
  656. const struct bkey *k,
  657. unsigned ptr)
  658. {
  659. return sector_to_bucket(c, PTR_OFFSET(k, ptr));
  660. }
  661. static inline struct bucket *PTR_BUCKET(struct cache_set *c,
  662. const struct bkey *k,
  663. unsigned ptr)
  664. {
  665. return PTR_CACHE(c, k, ptr)->buckets + PTR_BUCKET_NR(c, k, ptr);
  666. }
  667. /* Btree key macros */
  668. static inline void bkey_init(struct bkey *k)
  669. {
  670. *k = ZERO_KEY;
  671. }
  672. /*
  673. * This is used for various on disk data structures - cache_sb, prio_set, bset,
  674. * jset: The checksum is _always_ the first 8 bytes of these structs
  675. */
  676. #define csum_set(i) \
  677. bch_crc64(((void *) (i)) + sizeof(uint64_t), \
  678. ((void *) end(i)) - (((void *) (i)) + sizeof(uint64_t)))
  679. /* Error handling macros */
  680. #define btree_bug(b, ...) \
  681. do { \
  682. if (bch_cache_set_error((b)->c, __VA_ARGS__)) \
  683. dump_stack(); \
  684. } while (0)
  685. #define cache_bug(c, ...) \
  686. do { \
  687. if (bch_cache_set_error(c, __VA_ARGS__)) \
  688. dump_stack(); \
  689. } while (0)
  690. #define btree_bug_on(cond, b, ...) \
  691. do { \
  692. if (cond) \
  693. btree_bug(b, __VA_ARGS__); \
  694. } while (0)
  695. #define cache_bug_on(cond, c, ...) \
  696. do { \
  697. if (cond) \
  698. cache_bug(c, __VA_ARGS__); \
  699. } while (0)
  700. #define cache_set_err_on(cond, c, ...) \
  701. do { \
  702. if (cond) \
  703. bch_cache_set_error(c, __VA_ARGS__); \
  704. } while (0)
  705. /* Looping macros */
  706. #define for_each_cache(ca, cs, iter) \
  707. for (iter = 0; ca = cs->cache[iter], iter < (cs)->sb.nr_in_set; iter++)
  708. #define for_each_bucket(b, ca) \
  709. for (b = (ca)->buckets + (ca)->sb.first_bucket; \
  710. b < (ca)->buckets + (ca)->sb.nbuckets; b++)
  711. static inline void cached_dev_put(struct cached_dev *dc)
  712. {
  713. if (atomic_dec_and_test(&dc->count))
  714. schedule_work(&dc->detach);
  715. }
  716. static inline bool cached_dev_get(struct cached_dev *dc)
  717. {
  718. if (!atomic_inc_not_zero(&dc->count))
  719. return false;
  720. /* Paired with the mb in cached_dev_attach */
  721. smp_mb__after_atomic_inc();
  722. return true;
  723. }
  724. /*
  725. * bucket_gc_gen() returns the difference between the bucket's current gen and
  726. * the oldest gen of any pointer into that bucket in the btree (last_gc).
  727. *
  728. * bucket_disk_gen() returns the difference between the current gen and the gen
  729. * on disk; they're both used to make sure gens don't wrap around.
  730. */
  731. static inline uint8_t bucket_gc_gen(struct bucket *b)
  732. {
  733. return b->gen - b->last_gc;
  734. }
  735. static inline uint8_t bucket_disk_gen(struct bucket *b)
  736. {
  737. return b->gen - b->disk_gen;
  738. }
  739. #define BUCKET_GC_GEN_MAX 96U
  740. #define BUCKET_DISK_GEN_MAX 64U
  741. #define kobj_attribute_write(n, fn) \
  742. static struct kobj_attribute ksysfs_##n = __ATTR(n, S_IWUSR, NULL, fn)
  743. #define kobj_attribute_rw(n, show, store) \
  744. static struct kobj_attribute ksysfs_##n = \
  745. __ATTR(n, S_IWUSR|S_IRUSR, show, store)
  746. static inline void wake_up_allocators(struct cache_set *c)
  747. {
  748. struct cache *ca;
  749. unsigned i;
  750. for_each_cache(ca, c, i)
  751. wake_up_process(ca->alloc_thread);
  752. }
  753. /* Forward declarations */
  754. void bch_count_io_errors(struct cache *, int, const char *);
  755. void bch_bbio_count_io_errors(struct cache_set *, struct bio *,
  756. int, const char *);
  757. void bch_bbio_endio(struct cache_set *, struct bio *, int, const char *);
  758. void bch_bbio_free(struct bio *, struct cache_set *);
  759. struct bio *bch_bbio_alloc(struct cache_set *);
  760. struct bio *bch_bio_split(struct bio *, int, gfp_t, struct bio_set *);
  761. void bch_generic_make_request(struct bio *, struct bio_split_pool *);
  762. void __bch_submit_bbio(struct bio *, struct cache_set *);
  763. void bch_submit_bbio(struct bio *, struct cache_set *, struct bkey *, unsigned);
  764. uint8_t bch_inc_gen(struct cache *, struct bucket *);
  765. void bch_rescale_priorities(struct cache_set *, int);
  766. bool bch_bucket_add_unused(struct cache *, struct bucket *);
  767. long bch_bucket_alloc(struct cache *, unsigned, bool);
  768. void bch_bucket_free(struct cache_set *, struct bkey *);
  769. int __bch_bucket_alloc_set(struct cache_set *, unsigned,
  770. struct bkey *, int, bool);
  771. int bch_bucket_alloc_set(struct cache_set *, unsigned,
  772. struct bkey *, int, bool);
  773. bool bch_alloc_sectors(struct cache_set *, struct bkey *, unsigned,
  774. unsigned, unsigned, bool);
  775. __printf(2, 3)
  776. bool bch_cache_set_error(struct cache_set *, const char *, ...);
  777. void bch_prio_write(struct cache *);
  778. void bch_write_bdev_super(struct cached_dev *, struct closure *);
  779. extern struct workqueue_struct *bcache_wq;
  780. extern const char * const bch_cache_modes[];
  781. extern struct mutex bch_register_lock;
  782. extern struct list_head bch_cache_sets;
  783. extern struct kobj_type bch_cached_dev_ktype;
  784. extern struct kobj_type bch_flash_dev_ktype;
  785. extern struct kobj_type bch_cache_set_ktype;
  786. extern struct kobj_type bch_cache_set_internal_ktype;
  787. extern struct kobj_type bch_cache_ktype;
  788. void bch_cached_dev_release(struct kobject *);
  789. void bch_flash_dev_release(struct kobject *);
  790. void bch_cache_set_release(struct kobject *);
  791. void bch_cache_release(struct kobject *);
  792. int bch_uuid_write(struct cache_set *);
  793. void bcache_write_super(struct cache_set *);
  794. int bch_flash_dev_create(struct cache_set *c, uint64_t size);
  795. int bch_cached_dev_attach(struct cached_dev *, struct cache_set *);
  796. void bch_cached_dev_detach(struct cached_dev *);
  797. void bch_cached_dev_run(struct cached_dev *);
  798. void bcache_device_stop(struct bcache_device *);
  799. void bch_cache_set_unregister(struct cache_set *);
  800. void bch_cache_set_stop(struct cache_set *);
  801. struct cache_set *bch_cache_set_alloc(struct cache_sb *);
  802. void bch_btree_cache_free(struct cache_set *);
  803. int bch_btree_cache_alloc(struct cache_set *);
  804. void bch_moving_init_cache_set(struct cache_set *);
  805. int bch_open_buckets_alloc(struct cache_set *);
  806. void bch_open_buckets_free(struct cache_set *);
  807. int bch_cache_allocator_start(struct cache *ca);
  808. int bch_cache_allocator_init(struct cache *ca);
  809. void bch_debug_exit(void);
  810. int bch_debug_init(struct kobject *);
  811. void bch_request_exit(void);
  812. int bch_request_init(void);
  813. void bch_btree_exit(void);
  814. int bch_btree_init(void);
  815. #endif /* _BCACHE_H */