bcache.h 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  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. * The allocation code needs gc_mark in struct bucket to be correct, but
  552. * it's not while a gc is in progress. Protected by bucket_lock.
  553. */
  554. int gc_mark_valid;
  555. /* Counts how many sectors bio_insert has added to the cache */
  556. atomic_t sectors_to_gc;
  557. wait_queue_head_t gc_wait;
  558. struct keybuf moving_gc_keys;
  559. /* Number of moving GC bios in flight */
  560. struct semaphore moving_in_flight;
  561. struct workqueue_struct *moving_gc_wq;
  562. struct btree *root;
  563. #ifdef CONFIG_BCACHE_DEBUG
  564. struct btree *verify_data;
  565. struct bset *verify_ondisk;
  566. struct mutex verify_lock;
  567. #endif
  568. unsigned int nr_uuids;
  569. struct uuid_entry *uuids;
  570. BKEY_PADDED(uuid_bucket);
  571. struct closure uuid_write;
  572. struct semaphore uuid_write_mutex;
  573. /*
  574. * A btree node on disk could have too many bsets for an iterator to fit
  575. * on the stack - have to dynamically allocate them
  576. */
  577. mempool_t fill_iter;
  578. struct bset_sort_state sort;
  579. /* List of buckets we're currently writing data to */
  580. struct list_head data_buckets;
  581. spinlock_t data_bucket_lock;
  582. struct journal journal;
  583. #define CONGESTED_MAX 1024
  584. unsigned int congested_last_us;
  585. atomic_t congested;
  586. /* The rest of this all shows up in sysfs */
  587. unsigned int congested_read_threshold_us;
  588. unsigned int congested_write_threshold_us;
  589. struct time_stats btree_gc_time;
  590. struct time_stats btree_split_time;
  591. struct time_stats btree_read_time;
  592. atomic_long_t cache_read_races;
  593. atomic_long_t writeback_keys_done;
  594. atomic_long_t writeback_keys_failed;
  595. atomic_long_t reclaim;
  596. atomic_long_t flush_write;
  597. atomic_long_t retry_flush_write;
  598. enum {
  599. ON_ERROR_UNREGISTER,
  600. ON_ERROR_PANIC,
  601. } on_error;
  602. #define DEFAULT_IO_ERROR_LIMIT 8
  603. unsigned int error_limit;
  604. unsigned int error_decay;
  605. unsigned short journal_delay_ms;
  606. bool expensive_debug_checks;
  607. unsigned int verify:1;
  608. unsigned int key_merging_disabled:1;
  609. unsigned int gc_always_rewrite:1;
  610. unsigned int shrinker_disabled:1;
  611. unsigned int copy_gc_enabled:1;
  612. #define BUCKET_HASH_BITS 12
  613. struct hlist_head bucket_hash[1 << BUCKET_HASH_BITS];
  614. };
  615. struct bbio {
  616. unsigned int submit_time_us;
  617. union {
  618. struct bkey key;
  619. uint64_t _pad[3];
  620. /*
  621. * We only need pad = 3 here because we only ever carry around a
  622. * single pointer - i.e. the pointer we're doing io to/from.
  623. */
  624. };
  625. struct bio bio;
  626. };
  627. #define BTREE_PRIO USHRT_MAX
  628. #define INITIAL_PRIO 32768U
  629. #define btree_bytes(c) ((c)->btree_pages * PAGE_SIZE)
  630. #define btree_blocks(b) \
  631. ((unsigned int) (KEY_SIZE(&b->key) >> (b)->c->block_bits))
  632. #define btree_default_blocks(c) \
  633. ((unsigned int) ((PAGE_SECTORS * (c)->btree_pages) >> (c)->block_bits))
  634. #define bucket_pages(c) ((c)->sb.bucket_size / PAGE_SECTORS)
  635. #define bucket_bytes(c) ((c)->sb.bucket_size << 9)
  636. #define block_bytes(c) ((c)->sb.block_size << 9)
  637. #define prios_per_bucket(c) \
  638. ((bucket_bytes(c) - sizeof(struct prio_set)) / \
  639. sizeof(struct bucket_disk))
  640. #define prio_buckets(c) \
  641. DIV_ROUND_UP((size_t) (c)->sb.nbuckets, prios_per_bucket(c))
  642. static inline size_t sector_to_bucket(struct cache_set *c, sector_t s)
  643. {
  644. return s >> c->bucket_bits;
  645. }
  646. static inline sector_t bucket_to_sector(struct cache_set *c, size_t b)
  647. {
  648. return ((sector_t) b) << c->bucket_bits;
  649. }
  650. static inline sector_t bucket_remainder(struct cache_set *c, sector_t s)
  651. {
  652. return s & (c->sb.bucket_size - 1);
  653. }
  654. static inline struct cache *PTR_CACHE(struct cache_set *c,
  655. const struct bkey *k,
  656. unsigned int ptr)
  657. {
  658. return c->cache[PTR_DEV(k, ptr)];
  659. }
  660. static inline size_t PTR_BUCKET_NR(struct cache_set *c,
  661. const struct bkey *k,
  662. unsigned int ptr)
  663. {
  664. return sector_to_bucket(c, PTR_OFFSET(k, ptr));
  665. }
  666. static inline struct bucket *PTR_BUCKET(struct cache_set *c,
  667. const struct bkey *k,
  668. unsigned int ptr)
  669. {
  670. return PTR_CACHE(c, k, ptr)->buckets + PTR_BUCKET_NR(c, k, ptr);
  671. }
  672. static inline uint8_t gen_after(uint8_t a, uint8_t b)
  673. {
  674. uint8_t r = a - b;
  675. return r > 128U ? 0 : r;
  676. }
  677. static inline uint8_t ptr_stale(struct cache_set *c, const struct bkey *k,
  678. unsigned int i)
  679. {
  680. return gen_after(PTR_BUCKET(c, k, i)->gen, PTR_GEN(k, i));
  681. }
  682. static inline bool ptr_available(struct cache_set *c, const struct bkey *k,
  683. unsigned int i)
  684. {
  685. return (PTR_DEV(k, i) < MAX_CACHES_PER_SET) && PTR_CACHE(c, k, i);
  686. }
  687. /* Btree key macros */
  688. /*
  689. * This is used for various on disk data structures - cache_sb, prio_set, bset,
  690. * jset: The checksum is _always_ the first 8 bytes of these structs
  691. */
  692. #define csum_set(i) \
  693. bch_crc64(((void *) (i)) + sizeof(uint64_t), \
  694. ((void *) bset_bkey_last(i)) - \
  695. (((void *) (i)) + sizeof(uint64_t)))
  696. /* Error handling macros */
  697. #define btree_bug(b, ...) \
  698. do { \
  699. if (bch_cache_set_error((b)->c, __VA_ARGS__)) \
  700. dump_stack(); \
  701. } while (0)
  702. #define cache_bug(c, ...) \
  703. do { \
  704. if (bch_cache_set_error(c, __VA_ARGS__)) \
  705. dump_stack(); \
  706. } while (0)
  707. #define btree_bug_on(cond, b, ...) \
  708. do { \
  709. if (cond) \
  710. btree_bug(b, __VA_ARGS__); \
  711. } while (0)
  712. #define cache_bug_on(cond, c, ...) \
  713. do { \
  714. if (cond) \
  715. cache_bug(c, __VA_ARGS__); \
  716. } while (0)
  717. #define cache_set_err_on(cond, c, ...) \
  718. do { \
  719. if (cond) \
  720. bch_cache_set_error(c, __VA_ARGS__); \
  721. } while (0)
  722. /* Looping macros */
  723. #define for_each_cache(ca, cs, iter) \
  724. for (iter = 0; ca = cs->cache[iter], iter < (cs)->sb.nr_in_set; iter++)
  725. #define for_each_bucket(b, ca) \
  726. for (b = (ca)->buckets + (ca)->sb.first_bucket; \
  727. b < (ca)->buckets + (ca)->sb.nbuckets; b++)
  728. static inline void cached_dev_put(struct cached_dev *dc)
  729. {
  730. if (refcount_dec_and_test(&dc->count))
  731. schedule_work(&dc->detach);
  732. }
  733. static inline bool cached_dev_get(struct cached_dev *dc)
  734. {
  735. if (!refcount_inc_not_zero(&dc->count))
  736. return false;
  737. /* Paired with the mb in cached_dev_attach */
  738. smp_mb__after_atomic();
  739. return true;
  740. }
  741. /*
  742. * bucket_gc_gen() returns the difference between the bucket's current gen and
  743. * the oldest gen of any pointer into that bucket in the btree (last_gc).
  744. */
  745. static inline uint8_t bucket_gc_gen(struct bucket *b)
  746. {
  747. return b->gen - b->last_gc;
  748. }
  749. #define BUCKET_GC_GEN_MAX 96U
  750. #define kobj_attribute_write(n, fn) \
  751. static struct kobj_attribute ksysfs_##n = __ATTR(n, 0200, NULL, fn)
  752. #define kobj_attribute_rw(n, show, store) \
  753. static struct kobj_attribute ksysfs_##n = \
  754. __ATTR(n, 0600, show, store)
  755. static inline void wake_up_allocators(struct cache_set *c)
  756. {
  757. struct cache *ca;
  758. unsigned int i;
  759. for_each_cache(ca, c, i)
  760. wake_up_process(ca->alloc_thread);
  761. }
  762. static inline void closure_bio_submit(struct cache_set *c,
  763. struct bio *bio,
  764. struct closure *cl)
  765. {
  766. closure_get(cl);
  767. if (unlikely(test_bit(CACHE_SET_IO_DISABLE, &c->flags))) {
  768. bio->bi_status = BLK_STS_IOERR;
  769. bio_endio(bio);
  770. return;
  771. }
  772. generic_make_request(bio);
  773. }
  774. /*
  775. * Prevent the kthread exits directly, and make sure when kthread_stop()
  776. * is called to stop a kthread, it is still alive. If a kthread might be
  777. * stopped by CACHE_SET_IO_DISABLE bit set, wait_for_kthread_stop() is
  778. * necessary before the kthread returns.
  779. */
  780. static inline void wait_for_kthread_stop(void)
  781. {
  782. while (!kthread_should_stop()) {
  783. set_current_state(TASK_INTERRUPTIBLE);
  784. schedule();
  785. }
  786. }
  787. /* Forward declarations */
  788. void bch_count_backing_io_errors(struct cached_dev *dc, struct bio *bio);
  789. void bch_count_io_errors(struct cache *ca, blk_status_t error,
  790. int is_read, const char *m);
  791. void bch_bbio_count_io_errors(struct cache_set *c, struct bio *bio,
  792. blk_status_t error, const char *m);
  793. void bch_bbio_endio(struct cache_set *c, struct bio *bio,
  794. blk_status_t error, const char *m);
  795. void bch_bbio_free(struct bio *bio, struct cache_set *c);
  796. struct bio *bch_bbio_alloc(struct cache_set *c);
  797. void __bch_submit_bbio(struct bio *bio, struct cache_set *c);
  798. void bch_submit_bbio(struct bio *bio, struct cache_set *c,
  799. struct bkey *k, unsigned int ptr);
  800. uint8_t bch_inc_gen(struct cache *ca, struct bucket *b);
  801. void bch_rescale_priorities(struct cache_set *c, int sectors);
  802. bool bch_can_invalidate_bucket(struct cache *ca, struct bucket *b);
  803. void __bch_invalidate_one_bucket(struct cache *ca, struct bucket *b);
  804. void __bch_bucket_free(struct cache *ca, struct bucket *b);
  805. void bch_bucket_free(struct cache_set *c, struct bkey *k);
  806. long bch_bucket_alloc(struct cache *ca, unsigned int reserve, bool wait);
  807. int __bch_bucket_alloc_set(struct cache_set *c, unsigned int reserve,
  808. struct bkey *k, int n, bool wait);
  809. int bch_bucket_alloc_set(struct cache_set *c, unsigned int reserve,
  810. struct bkey *k, int n, bool wait);
  811. bool bch_alloc_sectors(struct cache_set *c, struct bkey *k,
  812. unsigned int sectors, unsigned int write_point,
  813. unsigned int write_prio, bool wait);
  814. bool bch_cached_dev_error(struct cached_dev *dc);
  815. __printf(2, 3)
  816. bool bch_cache_set_error(struct cache_set *c, const char *fmt, ...);
  817. int bch_prio_write(struct cache *ca, bool wait);
  818. void bch_write_bdev_super(struct cached_dev *dc, struct closure *parent);
  819. extern struct workqueue_struct *bcache_wq;
  820. extern struct workqueue_struct *bch_journal_wq;
  821. extern struct mutex bch_register_lock;
  822. extern struct list_head bch_cache_sets;
  823. extern struct kobj_type bch_cached_dev_ktype;
  824. extern struct kobj_type bch_flash_dev_ktype;
  825. extern struct kobj_type bch_cache_set_ktype;
  826. extern struct kobj_type bch_cache_set_internal_ktype;
  827. extern struct kobj_type bch_cache_ktype;
  828. void bch_cached_dev_release(struct kobject *kobj);
  829. void bch_flash_dev_release(struct kobject *kobj);
  830. void bch_cache_set_release(struct kobject *kobj);
  831. void bch_cache_release(struct kobject *kobj);
  832. int bch_uuid_write(struct cache_set *c);
  833. void bcache_write_super(struct cache_set *c);
  834. int bch_flash_dev_create(struct cache_set *c, uint64_t size);
  835. int bch_cached_dev_attach(struct cached_dev *dc, struct cache_set *c,
  836. uint8_t *set_uuid);
  837. void bch_cached_dev_detach(struct cached_dev *dc);
  838. void bch_cached_dev_run(struct cached_dev *dc);
  839. void bcache_device_stop(struct bcache_device *d);
  840. void bch_cache_set_unregister(struct cache_set *c);
  841. void bch_cache_set_stop(struct cache_set *c);
  842. struct cache_set *bch_cache_set_alloc(struct cache_sb *sb);
  843. void bch_btree_cache_free(struct cache_set *c);
  844. int bch_btree_cache_alloc(struct cache_set *c);
  845. void bch_moving_init_cache_set(struct cache_set *c);
  846. int bch_open_buckets_alloc(struct cache_set *c);
  847. void bch_open_buckets_free(struct cache_set *c);
  848. int bch_cache_allocator_start(struct cache *ca);
  849. void bch_debug_exit(void);
  850. void bch_debug_init(struct kobject *kobj);
  851. void bch_request_exit(void);
  852. int bch_request_init(void);
  853. #endif /* _BCACHE_H */