bcache.h 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048
  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 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, __func__
  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/refcount.h>
  185. #include <linux/types.h>
  186. #include <linux/workqueue.h>
  187. #include <linux/kthread.h>
  188. #include "bcache_ondisk.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 cache_sb_disk *sb_disk;
  279. struct bio sb_bio;
  280. struct bio_vec sb_bv[1];
  281. struct closure sb_write;
  282. struct semaphore sb_write_mutex;
  283. /* Refcount on the cache set. Always nonzero when we're caching. */
  284. refcount_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. #define BCH_CACHE_READA_ALL 0
  303. #define BCH_CACHE_READA_META_ONLY 1
  304. unsigned int cache_readahead_policy;
  305. struct bch_ratelimit writeback_rate;
  306. struct delayed_work writeback_rate_update;
  307. /* Limit number of writeback bios in flight */
  308. struct semaphore in_flight;
  309. struct task_struct *writeback_thread;
  310. struct workqueue_struct *writeback_write_wq;
  311. struct keybuf writeback_keys;
  312. struct task_struct *status_update_thread;
  313. /*
  314. * Order the write-half of writeback operations strongly in dispatch
  315. * order. (Maintain LBA order; don't allow reads completing out of
  316. * order to re-order the writes...)
  317. */
  318. struct closure_waitlist writeback_ordering_wait;
  319. atomic_t writeback_sequence_next;
  320. /* For tracking sequential IO */
  321. #define RECENT_IO_BITS 7
  322. #define RECENT_IO (1 << RECENT_IO_BITS)
  323. struct io io[RECENT_IO];
  324. struct hlist_head io_hash[RECENT_IO + 1];
  325. struct list_head io_lru;
  326. spinlock_t io_lock;
  327. struct cache_accounting accounting;
  328. /* The rest of this all shows up in sysfs */
  329. unsigned int sequential_cutoff;
  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 int writeback_consider_fragment:1;
  337. unsigned char writeback_percent;
  338. unsigned int writeback_delay;
  339. uint64_t writeback_rate_target;
  340. int64_t writeback_rate_proportional;
  341. int64_t writeback_rate_integral;
  342. int64_t writeback_rate_integral_scaled;
  343. int32_t writeback_rate_change;
  344. unsigned int writeback_rate_update_seconds;
  345. unsigned int writeback_rate_i_term_inverse;
  346. unsigned int writeback_rate_p_term_inverse;
  347. unsigned int writeback_rate_fp_term_low;
  348. unsigned int writeback_rate_fp_term_mid;
  349. unsigned int writeback_rate_fp_term_high;
  350. unsigned int writeback_rate_minimum;
  351. enum stop_on_failure stop_when_cache_set_failed;
  352. #define DEFAULT_CACHED_DEV_ERROR_LIMIT 64
  353. atomic_t io_errors;
  354. unsigned int error_limit;
  355. unsigned int offline_seconds;
  356. /*
  357. * Retry to update writeback_rate if contention happens for
  358. * down_read(dc->writeback_lock) in update_writeback_rate()
  359. */
  360. #define BCH_WBRATE_UPDATE_MAX_SKIPS 15
  361. unsigned int rate_update_retry;
  362. };
  363. enum alloc_reserve {
  364. RESERVE_BTREE,
  365. RESERVE_PRIO,
  366. RESERVE_MOVINGGC,
  367. RESERVE_NONE,
  368. RESERVE_NR,
  369. };
  370. struct cache {
  371. struct cache_set *set;
  372. struct cache_sb sb;
  373. struct cache_sb_disk *sb_disk;
  374. struct bio sb_bio;
  375. struct bio_vec sb_bv[1];
  376. struct kobject kobj;
  377. struct block_device *bdev;
  378. struct task_struct *alloc_thread;
  379. struct closure prio;
  380. struct prio_set *disk_buckets;
  381. /*
  382. * When allocating new buckets, prio_write() gets first dibs - since we
  383. * may not be allocate at all without writing priorities and gens.
  384. * prio_last_buckets[] contains the last buckets we wrote priorities to
  385. * (so gc can mark them as metadata), prio_buckets[] contains the
  386. * buckets allocated for the next prio write.
  387. */
  388. uint64_t *prio_buckets;
  389. uint64_t *prio_last_buckets;
  390. /*
  391. * free: Buckets that are ready to be used
  392. *
  393. * free_inc: Incoming buckets - these are buckets that currently have
  394. * cached data in them, and we can't reuse them until after we write
  395. * their new gen to disk. After prio_write() finishes writing the new
  396. * gens/prios, they'll be moved to the free list (and possibly discarded
  397. * in the process)
  398. */
  399. DECLARE_FIFO(long, free)[RESERVE_NR];
  400. DECLARE_FIFO(long, free_inc);
  401. size_t fifo_last_bucket;
  402. /* Allocation stuff: */
  403. struct bucket *buckets;
  404. DECLARE_HEAP(struct bucket *, heap);
  405. /*
  406. * If nonzero, we know we aren't going to find any buckets to invalidate
  407. * until a gc finishes - otherwise we could pointlessly burn a ton of
  408. * cpu
  409. */
  410. unsigned int invalidate_needs_gc;
  411. bool discard; /* Get rid of? */
  412. struct journal_device journal;
  413. /* The rest of this all shows up in sysfs */
  414. #define IO_ERROR_SHIFT 20
  415. atomic_t io_errors;
  416. atomic_t io_count;
  417. atomic_long_t meta_sectors_written;
  418. atomic_long_t btree_sectors_written;
  419. atomic_long_t sectors_written;
  420. };
  421. struct gc_stat {
  422. size_t nodes;
  423. size_t nodes_pre;
  424. size_t key_bytes;
  425. size_t nkeys;
  426. uint64_t data; /* sectors */
  427. unsigned int in_use; /* percent */
  428. };
  429. /*
  430. * Flag bits, for how the cache set is shutting down, and what phase it's at:
  431. *
  432. * CACHE_SET_UNREGISTERING means we're not just shutting down, we're detaching
  433. * all the backing devices first (their cached data gets invalidated, and they
  434. * won't automatically reattach).
  435. *
  436. * CACHE_SET_STOPPING always gets set first when we're closing down a cache set;
  437. * we'll continue to run normally for awhile with CACHE_SET_STOPPING set (i.e.
  438. * flushing dirty data).
  439. *
  440. * CACHE_SET_RUNNING means all cache devices have been registered and journal
  441. * replay is complete.
  442. *
  443. * CACHE_SET_IO_DISABLE is set when bcache is stopping the whold cache set, all
  444. * external and internal I/O should be denied when this flag is set.
  445. *
  446. */
  447. #define CACHE_SET_UNREGISTERING 0
  448. #define CACHE_SET_STOPPING 1
  449. #define CACHE_SET_RUNNING 2
  450. #define CACHE_SET_IO_DISABLE 3
  451. struct cache_set {
  452. struct closure cl;
  453. struct list_head list;
  454. struct kobject kobj;
  455. struct kobject internal;
  456. struct dentry *debug;
  457. struct cache_accounting accounting;
  458. unsigned long flags;
  459. atomic_t idle_counter;
  460. atomic_t at_max_writeback_rate;
  461. struct cache *cache;
  462. struct bcache_device **devices;
  463. unsigned int devices_max_used;
  464. atomic_t attached_dev_nr;
  465. struct list_head cached_devs;
  466. uint64_t cached_dev_sectors;
  467. atomic_long_t flash_dev_dirty_sectors;
  468. struct closure caching;
  469. struct closure sb_write;
  470. struct semaphore sb_write_mutex;
  471. mempool_t search;
  472. mempool_t bio_meta;
  473. struct bio_set bio_split;
  474. /* For the btree cache */
  475. struct shrinker shrink;
  476. /* For the btree cache and anything allocation related */
  477. struct mutex bucket_lock;
  478. /* log2(bucket_size), in sectors */
  479. unsigned short bucket_bits;
  480. /* log2(block_size), in sectors */
  481. unsigned short block_bits;
  482. /*
  483. * Default number of pages for a new btree node - may be less than a
  484. * full bucket
  485. */
  486. unsigned int btree_pages;
  487. /*
  488. * Lists of struct btrees; lru is the list for structs that have memory
  489. * allocated for actual btree node, freed is for structs that do not.
  490. *
  491. * We never free a struct btree, except on shutdown - we just put it on
  492. * the btree_cache_freed list and reuse it later. This simplifies the
  493. * code, and it doesn't cost us much memory as the memory usage is
  494. * dominated by buffers that hold the actual btree node data and those
  495. * can be freed - and the number of struct btrees allocated is
  496. * effectively bounded.
  497. *
  498. * btree_cache_freeable effectively is a small cache - we use it because
  499. * high order page allocations can be rather expensive, and it's quite
  500. * common to delete and allocate btree nodes in quick succession. It
  501. * should never grow past ~2-3 nodes in practice.
  502. */
  503. struct list_head btree_cache;
  504. struct list_head btree_cache_freeable;
  505. struct list_head btree_cache_freed;
  506. /* Number of elements in btree_cache + btree_cache_freeable lists */
  507. unsigned int btree_cache_used;
  508. /*
  509. * If we need to allocate memory for a new btree node and that
  510. * allocation fails, we can cannibalize another node in the btree cache
  511. * to satisfy the allocation - lock to guarantee only one thread does
  512. * this at a time:
  513. */
  514. wait_queue_head_t btree_cache_wait;
  515. struct task_struct *btree_cache_alloc_lock;
  516. spinlock_t btree_cannibalize_lock;
  517. /*
  518. * When we free a btree node, we increment the gen of the bucket the
  519. * node is in - but we can't rewrite the prios and gens until we
  520. * finished whatever it is we were doing, otherwise after a crash the
  521. * btree node would be freed but for say a split, we might not have the
  522. * pointers to the new nodes inserted into the btree yet.
  523. *
  524. * This is a refcount that blocks prio_write() until the new keys are
  525. * written.
  526. */
  527. atomic_t prio_blocked;
  528. wait_queue_head_t bucket_wait;
  529. /*
  530. * For any bio we don't skip we subtract the number of sectors from
  531. * rescale; when it hits 0 we rescale all the bucket priorities.
  532. */
  533. atomic_t rescale;
  534. /*
  535. * used for GC, identify if any front side I/Os is inflight
  536. */
  537. atomic_t search_inflight;
  538. /*
  539. * When we invalidate buckets, we use both the priority and the amount
  540. * of good data to determine which buckets to reuse first - to weight
  541. * those together consistently we keep track of the smallest nonzero
  542. * priority of any bucket.
  543. */
  544. uint16_t min_prio;
  545. /*
  546. * max(gen - last_gc) for all buckets. When it gets too big we have to
  547. * gc to keep gens from wrapping around.
  548. */
  549. uint8_t need_gc;
  550. struct gc_stat gc_stats;
  551. size_t nbuckets;
  552. size_t avail_nbuckets;
  553. struct task_struct *gc_thread;
  554. /* Where in the btree gc currently is */
  555. struct bkey gc_done;
  556. /*
  557. * For automatical garbage collection after writeback completed, this
  558. * varialbe is used as bit fields,
  559. * - 0000 0001b (BCH_ENABLE_AUTO_GC): enable gc after writeback
  560. * - 0000 0010b (BCH_DO_AUTO_GC): do gc after writeback
  561. * This is an optimization for following write request after writeback
  562. * finished, but read hit rate dropped due to clean data on cache is
  563. * discarded. Unless user explicitly sets it via sysfs, it won't be
  564. * enabled.
  565. */
  566. #define BCH_ENABLE_AUTO_GC 1
  567. #define BCH_DO_AUTO_GC 2
  568. uint8_t gc_after_writeback;
  569. /*
  570. * The allocation code needs gc_mark in struct bucket to be correct, but
  571. * it's not while a gc is in progress. Protected by bucket_lock.
  572. */
  573. int gc_mark_valid;
  574. /* Counts how many sectors bio_insert has added to the cache */
  575. atomic_t sectors_to_gc;
  576. wait_queue_head_t gc_wait;
  577. struct keybuf moving_gc_keys;
  578. /* Number of moving GC bios in flight */
  579. struct semaphore moving_in_flight;
  580. struct workqueue_struct *moving_gc_wq;
  581. struct btree *root;
  582. #ifdef CONFIG_BCACHE_DEBUG
  583. struct btree *verify_data;
  584. struct bset *verify_ondisk;
  585. struct mutex verify_lock;
  586. #endif
  587. uint8_t set_uuid[16];
  588. unsigned int nr_uuids;
  589. struct uuid_entry *uuids;
  590. BKEY_PADDED(uuid_bucket);
  591. struct closure uuid_write;
  592. struct semaphore uuid_write_mutex;
  593. /*
  594. * A btree node on disk could have too many bsets for an iterator to fit
  595. * on the stack - have to dynamically allocate them.
  596. * bch_cache_set_alloc() will make sure the pool can allocate iterators
  597. * equipped with enough room that can host
  598. * (sb.bucket_size / sb.block_size)
  599. * btree_iter_sets, which is more than static MAX_BSETS.
  600. */
  601. mempool_t fill_iter;
  602. struct bset_sort_state sort;
  603. /* List of buckets we're currently writing data to */
  604. struct list_head data_buckets;
  605. spinlock_t data_bucket_lock;
  606. struct journal journal;
  607. #define CONGESTED_MAX 1024
  608. unsigned int congested_last_us;
  609. atomic_t congested;
  610. /* The rest of this all shows up in sysfs */
  611. unsigned int congested_read_threshold_us;
  612. unsigned int congested_write_threshold_us;
  613. struct time_stats btree_gc_time;
  614. struct time_stats btree_split_time;
  615. struct time_stats btree_read_time;
  616. atomic_long_t cache_read_races;
  617. atomic_long_t writeback_keys_done;
  618. atomic_long_t writeback_keys_failed;
  619. atomic_long_t reclaim;
  620. atomic_long_t reclaimed_journal_buckets;
  621. atomic_long_t flush_write;
  622. enum {
  623. ON_ERROR_UNREGISTER,
  624. ON_ERROR_PANIC,
  625. } on_error;
  626. #define DEFAULT_IO_ERROR_LIMIT 8
  627. unsigned int error_limit;
  628. unsigned int error_decay;
  629. unsigned short journal_delay_ms;
  630. bool expensive_debug_checks;
  631. unsigned int verify:1;
  632. unsigned int key_merging_disabled:1;
  633. unsigned int gc_always_rewrite:1;
  634. unsigned int shrinker_disabled:1;
  635. unsigned int copy_gc_enabled:1;
  636. unsigned int idle_max_writeback_rate_enabled:1;
  637. #define BUCKET_HASH_BITS 12
  638. struct hlist_head bucket_hash[1 << BUCKET_HASH_BITS];
  639. };
  640. struct bbio {
  641. unsigned int submit_time_us;
  642. union {
  643. struct bkey key;
  644. uint64_t _pad[3];
  645. /*
  646. * We only need pad = 3 here because we only ever carry around a
  647. * single pointer - i.e. the pointer we're doing io to/from.
  648. */
  649. };
  650. struct bio bio;
  651. };
  652. #define BTREE_PRIO USHRT_MAX
  653. #define INITIAL_PRIO 32768U
  654. #define btree_bytes(c) ((c)->btree_pages * PAGE_SIZE)
  655. #define btree_blocks(b) \
  656. ((unsigned int) (KEY_SIZE(&b->key) >> (b)->c->block_bits))
  657. #define btree_default_blocks(c) \
  658. ((unsigned int) ((PAGE_SECTORS * (c)->btree_pages) >> (c)->block_bits))
  659. #define bucket_bytes(ca) ((ca)->sb.bucket_size << 9)
  660. #define block_bytes(ca) ((ca)->sb.block_size << 9)
  661. static inline unsigned int meta_bucket_pages(struct cache_sb *sb)
  662. {
  663. unsigned int n, max_pages;
  664. max_pages = min_t(unsigned int,
  665. __rounddown_pow_of_two(USHRT_MAX) / PAGE_SECTORS,
  666. MAX_ORDER_NR_PAGES);
  667. n = sb->bucket_size / PAGE_SECTORS;
  668. if (n > max_pages)
  669. n = max_pages;
  670. return n;
  671. }
  672. static inline unsigned int meta_bucket_bytes(struct cache_sb *sb)
  673. {
  674. return meta_bucket_pages(sb) << PAGE_SHIFT;
  675. }
  676. #define prios_per_bucket(ca) \
  677. ((meta_bucket_bytes(&(ca)->sb) - sizeof(struct prio_set)) / \
  678. sizeof(struct bucket_disk))
  679. #define prio_buckets(ca) \
  680. DIV_ROUND_UP((size_t) (ca)->sb.nbuckets, prios_per_bucket(ca))
  681. static inline size_t sector_to_bucket(struct cache_set *c, sector_t s)
  682. {
  683. return s >> c->bucket_bits;
  684. }
  685. static inline sector_t bucket_to_sector(struct cache_set *c, size_t b)
  686. {
  687. return ((sector_t) b) << c->bucket_bits;
  688. }
  689. static inline sector_t bucket_remainder(struct cache_set *c, sector_t s)
  690. {
  691. return s & (c->cache->sb.bucket_size - 1);
  692. }
  693. static inline size_t PTR_BUCKET_NR(struct cache_set *c,
  694. const struct bkey *k,
  695. unsigned int ptr)
  696. {
  697. return sector_to_bucket(c, PTR_OFFSET(k, ptr));
  698. }
  699. static inline struct bucket *PTR_BUCKET(struct cache_set *c,
  700. const struct bkey *k,
  701. unsigned int ptr)
  702. {
  703. return c->cache->buckets + PTR_BUCKET_NR(c, k, ptr);
  704. }
  705. static inline uint8_t gen_after(uint8_t a, uint8_t b)
  706. {
  707. uint8_t r = a - b;
  708. return r > 128U ? 0 : r;
  709. }
  710. static inline uint8_t ptr_stale(struct cache_set *c, const struct bkey *k,
  711. unsigned int i)
  712. {
  713. return gen_after(PTR_BUCKET(c, k, i)->gen, PTR_GEN(k, i));
  714. }
  715. static inline bool ptr_available(struct cache_set *c, const struct bkey *k,
  716. unsigned int i)
  717. {
  718. return (PTR_DEV(k, i) < MAX_CACHES_PER_SET) && c->cache;
  719. }
  720. /* Btree key macros */
  721. /*
  722. * This is used for various on disk data structures - cache_sb, prio_set, bset,
  723. * jset: The checksum is _always_ the first 8 bytes of these structs
  724. */
  725. #define csum_set(i) \
  726. bch_crc64(((void *) (i)) + sizeof(uint64_t), \
  727. ((void *) bset_bkey_last(i)) - \
  728. (((void *) (i)) + sizeof(uint64_t)))
  729. /* Error handling macros */
  730. #define btree_bug(b, ...) \
  731. do { \
  732. if (bch_cache_set_error((b)->c, __VA_ARGS__)) \
  733. dump_stack(); \
  734. } while (0)
  735. #define cache_bug(c, ...) \
  736. do { \
  737. if (bch_cache_set_error(c, __VA_ARGS__)) \
  738. dump_stack(); \
  739. } while (0)
  740. #define btree_bug_on(cond, b, ...) \
  741. do { \
  742. if (cond) \
  743. btree_bug(b, __VA_ARGS__); \
  744. } while (0)
  745. #define cache_bug_on(cond, c, ...) \
  746. do { \
  747. if (cond) \
  748. cache_bug(c, __VA_ARGS__); \
  749. } while (0)
  750. #define cache_set_err_on(cond, c, ...) \
  751. do { \
  752. if (cond) \
  753. bch_cache_set_error(c, __VA_ARGS__); \
  754. } while (0)
  755. /* Looping macros */
  756. #define for_each_bucket(b, ca) \
  757. for (b = (ca)->buckets + (ca)->sb.first_bucket; \
  758. b < (ca)->buckets + (ca)->sb.nbuckets; b++)
  759. static inline void cached_dev_put(struct cached_dev *dc)
  760. {
  761. if (refcount_dec_and_test(&dc->count))
  762. schedule_work(&dc->detach);
  763. }
  764. static inline bool cached_dev_get(struct cached_dev *dc)
  765. {
  766. if (!refcount_inc_not_zero(&dc->count))
  767. return false;
  768. /* Paired with the mb in cached_dev_attach */
  769. smp_mb__after_atomic();
  770. return true;
  771. }
  772. /*
  773. * bucket_gc_gen() returns the difference between the bucket's current gen and
  774. * the oldest gen of any pointer into that bucket in the btree (last_gc).
  775. */
  776. static inline uint8_t bucket_gc_gen(struct bucket *b)
  777. {
  778. return b->gen - b->last_gc;
  779. }
  780. #define BUCKET_GC_GEN_MAX 96U
  781. #define kobj_attribute_write(n, fn) \
  782. static struct kobj_attribute ksysfs_##n = __ATTR(n, 0200, NULL, fn)
  783. #define kobj_attribute_rw(n, show, store) \
  784. static struct kobj_attribute ksysfs_##n = \
  785. __ATTR(n, 0600, show, store)
  786. static inline void wake_up_allocators(struct cache_set *c)
  787. {
  788. struct cache *ca = c->cache;
  789. wake_up_process(ca->alloc_thread);
  790. }
  791. static inline void closure_bio_submit(struct cache_set *c,
  792. struct bio *bio,
  793. struct closure *cl)
  794. {
  795. closure_get(cl);
  796. if (unlikely(test_bit(CACHE_SET_IO_DISABLE, &c->flags))) {
  797. bio->bi_status = BLK_STS_IOERR;
  798. bio_endio(bio);
  799. return;
  800. }
  801. submit_bio_noacct(bio);
  802. }
  803. /*
  804. * Prevent the kthread exits directly, and make sure when kthread_stop()
  805. * is called to stop a kthread, it is still alive. If a kthread might be
  806. * stopped by CACHE_SET_IO_DISABLE bit set, wait_for_kthread_stop() is
  807. * necessary before the kthread returns.
  808. */
  809. static inline void wait_for_kthread_stop(void)
  810. {
  811. while (!kthread_should_stop()) {
  812. set_current_state(TASK_INTERRUPTIBLE);
  813. schedule();
  814. }
  815. }
  816. /* Forward declarations */
  817. void bch_count_backing_io_errors(struct cached_dev *dc, struct bio *bio);
  818. void bch_count_io_errors(struct cache *ca, blk_status_t error,
  819. int is_read, const char *m);
  820. void bch_bbio_count_io_errors(struct cache_set *c, struct bio *bio,
  821. blk_status_t error, const char *m);
  822. void bch_bbio_endio(struct cache_set *c, struct bio *bio,
  823. blk_status_t error, const char *m);
  824. void bch_bbio_free(struct bio *bio, struct cache_set *c);
  825. struct bio *bch_bbio_alloc(struct cache_set *c);
  826. void __bch_submit_bbio(struct bio *bio, struct cache_set *c);
  827. void bch_submit_bbio(struct bio *bio, struct cache_set *c,
  828. struct bkey *k, unsigned int ptr);
  829. uint8_t bch_inc_gen(struct cache *ca, struct bucket *b);
  830. void bch_rescale_priorities(struct cache_set *c, int sectors);
  831. bool bch_can_invalidate_bucket(struct cache *ca, struct bucket *b);
  832. void __bch_invalidate_one_bucket(struct cache *ca, struct bucket *b);
  833. void __bch_bucket_free(struct cache *ca, struct bucket *b);
  834. void bch_bucket_free(struct cache_set *c, struct bkey *k);
  835. long bch_bucket_alloc(struct cache *ca, unsigned int reserve, bool wait);
  836. int __bch_bucket_alloc_set(struct cache_set *c, unsigned int reserve,
  837. struct bkey *k, bool wait);
  838. int bch_bucket_alloc_set(struct cache_set *c, unsigned int reserve,
  839. struct bkey *k, bool wait);
  840. bool bch_alloc_sectors(struct cache_set *c, struct bkey *k,
  841. unsigned int sectors, unsigned int write_point,
  842. unsigned int write_prio, bool wait);
  843. bool bch_cached_dev_error(struct cached_dev *dc);
  844. __printf(2, 3)
  845. bool bch_cache_set_error(struct cache_set *c, const char *fmt, ...);
  846. int bch_prio_write(struct cache *ca, bool wait);
  847. void bch_write_bdev_super(struct cached_dev *dc, struct closure *parent);
  848. extern struct workqueue_struct *bcache_wq;
  849. extern struct workqueue_struct *bch_journal_wq;
  850. extern struct workqueue_struct *bch_flush_wq;
  851. extern struct mutex bch_register_lock;
  852. extern struct list_head bch_cache_sets;
  853. extern struct kobj_type bch_cached_dev_ktype;
  854. extern struct kobj_type bch_flash_dev_ktype;
  855. extern struct kobj_type bch_cache_set_ktype;
  856. extern struct kobj_type bch_cache_set_internal_ktype;
  857. extern struct kobj_type bch_cache_ktype;
  858. void bch_cached_dev_release(struct kobject *kobj);
  859. void bch_flash_dev_release(struct kobject *kobj);
  860. void bch_cache_set_release(struct kobject *kobj);
  861. void bch_cache_release(struct kobject *kobj);
  862. int bch_uuid_write(struct cache_set *c);
  863. void bcache_write_super(struct cache_set *c);
  864. int bch_flash_dev_create(struct cache_set *c, uint64_t size);
  865. int bch_cached_dev_attach(struct cached_dev *dc, struct cache_set *c,
  866. uint8_t *set_uuid);
  867. void bch_cached_dev_detach(struct cached_dev *dc);
  868. int bch_cached_dev_run(struct cached_dev *dc);
  869. void bcache_device_stop(struct bcache_device *d);
  870. void bch_cache_set_unregister(struct cache_set *c);
  871. void bch_cache_set_stop(struct cache_set *c);
  872. struct cache_set *bch_cache_set_alloc(struct cache_sb *sb);
  873. void bch_btree_cache_free(struct cache_set *c);
  874. int bch_btree_cache_alloc(struct cache_set *c);
  875. void bch_moving_init_cache_set(struct cache_set *c);
  876. int bch_open_buckets_alloc(struct cache_set *c);
  877. void bch_open_buckets_free(struct cache_set *c);
  878. int bch_cache_allocator_start(struct cache *ca);
  879. void bch_debug_exit(void);
  880. void bch_debug_init(void);
  881. void bch_request_exit(void);
  882. int bch_request_init(void);
  883. void bch_btree_exit(void);
  884. int bch_btree_init(void);
  885. #endif /* _BCACHE_H */