bcache.h 32 KB

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