bcache.h 32 KB

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