writeback.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * background writeback - scan btree for dirty data and write it to the backing
  4. * device
  5. *
  6. * Copyright 2010, 2011 Kent Overstreet <kent.overstreet@gmail.com>
  7. * Copyright 2012 Google, Inc.
  8. */
  9. #include "bcache.h"
  10. #include "btree.h"
  11. #include "debug.h"
  12. #include "writeback.h"
  13. #include <linux/delay.h>
  14. #include <linux/kthread.h>
  15. #include <linux/sched/clock.h>
  16. #include <trace/events/bcache.h>
  17. static void update_gc_after_writeback(struct cache_set *c)
  18. {
  19. if (c->gc_after_writeback != (BCH_ENABLE_AUTO_GC) ||
  20. c->gc_stats.in_use < BCH_AUTO_GC_DIRTY_THRESHOLD)
  21. return;
  22. c->gc_after_writeback |= BCH_DO_AUTO_GC;
  23. }
  24. /* Rate limiting */
  25. static uint64_t __calc_target_rate(struct cached_dev *dc)
  26. {
  27. struct cache_set *c = dc->disk.c;
  28. /*
  29. * This is the size of the cache, minus the amount used for
  30. * flash-only devices
  31. */
  32. uint64_t cache_sectors = c->nbuckets * c->sb.bucket_size -
  33. atomic_long_read(&c->flash_dev_dirty_sectors);
  34. /*
  35. * Unfortunately there is no control of global dirty data. If the
  36. * user states that they want 10% dirty data in the cache, and has,
  37. * e.g., 5 backing volumes of equal size, we try and ensure each
  38. * backing volume uses about 2% of the cache for dirty data.
  39. */
  40. uint32_t bdev_share =
  41. div64_u64(bdev_sectors(dc->bdev) << WRITEBACK_SHARE_SHIFT,
  42. c->cached_dev_sectors);
  43. uint64_t cache_dirty_target =
  44. div_u64(cache_sectors * dc->writeback_percent, 100);
  45. /* Ensure each backing dev gets at least one dirty share */
  46. if (bdev_share < 1)
  47. bdev_share = 1;
  48. return (cache_dirty_target * bdev_share) >> WRITEBACK_SHARE_SHIFT;
  49. }
  50. static void __update_writeback_rate(struct cached_dev *dc)
  51. {
  52. /*
  53. * PI controller:
  54. * Figures out the amount that should be written per second.
  55. *
  56. * First, the error (number of sectors that are dirty beyond our
  57. * target) is calculated. The error is accumulated (numerically
  58. * integrated).
  59. *
  60. * Then, the proportional value and integral value are scaled
  61. * based on configured values. These are stored as inverses to
  62. * avoid fixed point math and to make configuration easy-- e.g.
  63. * the default value of 40 for writeback_rate_p_term_inverse
  64. * attempts to write at a rate that would retire all the dirty
  65. * blocks in 40 seconds.
  66. *
  67. * The writeback_rate_i_inverse value of 10000 means that 1/10000th
  68. * of the error is accumulated in the integral term per second.
  69. * This acts as a slow, long-term average that is not subject to
  70. * variations in usage like the p term.
  71. */
  72. int64_t target = __calc_target_rate(dc);
  73. int64_t dirty = bcache_dev_sectors_dirty(&dc->disk);
  74. int64_t error = dirty - target;
  75. int64_t proportional_scaled =
  76. div_s64(error, dc->writeback_rate_p_term_inverse);
  77. int64_t integral_scaled;
  78. uint32_t new_rate;
  79. if ((error < 0 && dc->writeback_rate_integral > 0) ||
  80. (error > 0 && time_before64(local_clock(),
  81. dc->writeback_rate.next + NSEC_PER_MSEC))) {
  82. /*
  83. * Only decrease the integral term if it's more than
  84. * zero. Only increase the integral term if the device
  85. * is keeping up. (Don't wind up the integral
  86. * ineffectively in either case).
  87. *
  88. * It's necessary to scale this by
  89. * writeback_rate_update_seconds to keep the integral
  90. * term dimensioned properly.
  91. */
  92. dc->writeback_rate_integral += error *
  93. dc->writeback_rate_update_seconds;
  94. }
  95. integral_scaled = div_s64(dc->writeback_rate_integral,
  96. dc->writeback_rate_i_term_inverse);
  97. new_rate = clamp_t(int32_t, (proportional_scaled + integral_scaled),
  98. dc->writeback_rate_minimum, NSEC_PER_SEC);
  99. dc->writeback_rate_proportional = proportional_scaled;
  100. dc->writeback_rate_integral_scaled = integral_scaled;
  101. dc->writeback_rate_change = new_rate -
  102. atomic_long_read(&dc->writeback_rate.rate);
  103. atomic_long_set(&dc->writeback_rate.rate, new_rate);
  104. dc->writeback_rate_target = target;
  105. }
  106. static bool set_at_max_writeback_rate(struct cache_set *c,
  107. struct cached_dev *dc)
  108. {
  109. /* Don't set max writeback rate if gc is running */
  110. if (!c->gc_mark_valid)
  111. return false;
  112. /*
  113. * Idle_counter is increased everytime when update_writeback_rate() is
  114. * called. If all backing devices attached to the same cache set have
  115. * identical dc->writeback_rate_update_seconds values, it is about 6
  116. * rounds of update_writeback_rate() on each backing device before
  117. * c->at_max_writeback_rate is set to 1, and then max wrteback rate set
  118. * to each dc->writeback_rate.rate.
  119. * In order to avoid extra locking cost for counting exact dirty cached
  120. * devices number, c->attached_dev_nr is used to calculate the idle
  121. * throushold. It might be bigger if not all cached device are in write-
  122. * back mode, but it still works well with limited extra rounds of
  123. * update_writeback_rate().
  124. */
  125. if (atomic_inc_return(&c->idle_counter) <
  126. atomic_read(&c->attached_dev_nr) * 6)
  127. return false;
  128. if (atomic_read(&c->at_max_writeback_rate) != 1)
  129. atomic_set(&c->at_max_writeback_rate, 1);
  130. atomic_long_set(&dc->writeback_rate.rate, INT_MAX);
  131. /* keep writeback_rate_target as existing value */
  132. dc->writeback_rate_proportional = 0;
  133. dc->writeback_rate_integral_scaled = 0;
  134. dc->writeback_rate_change = 0;
  135. /*
  136. * Check c->idle_counter and c->at_max_writeback_rate agagain in case
  137. * new I/O arrives during before set_at_max_writeback_rate() returns.
  138. * Then the writeback rate is set to 1, and its new value should be
  139. * decided via __update_writeback_rate().
  140. */
  141. if ((atomic_read(&c->idle_counter) <
  142. atomic_read(&c->attached_dev_nr) * 6) ||
  143. !atomic_read(&c->at_max_writeback_rate))
  144. return false;
  145. return true;
  146. }
  147. static void update_writeback_rate(struct work_struct *work)
  148. {
  149. struct cached_dev *dc = container_of(to_delayed_work(work),
  150. struct cached_dev,
  151. writeback_rate_update);
  152. struct cache_set *c = dc->disk.c;
  153. /*
  154. * should check BCACHE_DEV_RATE_DW_RUNNING before calling
  155. * cancel_delayed_work_sync().
  156. */
  157. set_bit(BCACHE_DEV_RATE_DW_RUNNING, &dc->disk.flags);
  158. /* paired with where BCACHE_DEV_RATE_DW_RUNNING is tested */
  159. smp_mb();
  160. /*
  161. * CACHE_SET_IO_DISABLE might be set via sysfs interface,
  162. * check it here too.
  163. */
  164. if (!test_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags) ||
  165. test_bit(CACHE_SET_IO_DISABLE, &c->flags)) {
  166. clear_bit(BCACHE_DEV_RATE_DW_RUNNING, &dc->disk.flags);
  167. /* paired with where BCACHE_DEV_RATE_DW_RUNNING is tested */
  168. smp_mb();
  169. return;
  170. }
  171. if (atomic_read(&dc->has_dirty) && dc->writeback_percent) {
  172. /*
  173. * If the whole cache set is idle, set_at_max_writeback_rate()
  174. * will set writeback rate to a max number. Then it is
  175. * unncessary to update writeback rate for an idle cache set
  176. * in maximum writeback rate number(s).
  177. */
  178. if (!set_at_max_writeback_rate(c, dc)) {
  179. down_read(&dc->writeback_lock);
  180. __update_writeback_rate(dc);
  181. update_gc_after_writeback(c);
  182. up_read(&dc->writeback_lock);
  183. }
  184. }
  185. /*
  186. * CACHE_SET_IO_DISABLE might be set via sysfs interface,
  187. * check it here too.
  188. */
  189. if (test_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags) &&
  190. !test_bit(CACHE_SET_IO_DISABLE, &c->flags)) {
  191. schedule_delayed_work(&dc->writeback_rate_update,
  192. dc->writeback_rate_update_seconds * HZ);
  193. }
  194. /*
  195. * should check BCACHE_DEV_RATE_DW_RUNNING before calling
  196. * cancel_delayed_work_sync().
  197. */
  198. clear_bit(BCACHE_DEV_RATE_DW_RUNNING, &dc->disk.flags);
  199. /* paired with where BCACHE_DEV_RATE_DW_RUNNING is tested */
  200. smp_mb();
  201. }
  202. static unsigned int writeback_delay(struct cached_dev *dc,
  203. unsigned int sectors)
  204. {
  205. if (test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags) ||
  206. !dc->writeback_percent)
  207. return 0;
  208. return bch_next_delay(&dc->writeback_rate, sectors);
  209. }
  210. struct dirty_io {
  211. struct closure cl;
  212. struct cached_dev *dc;
  213. uint16_t sequence;
  214. struct bio bio;
  215. };
  216. static void dirty_init(struct keybuf_key *w)
  217. {
  218. struct dirty_io *io = w->private;
  219. struct bio *bio = &io->bio;
  220. bio_init(bio, bio->bi_inline_vecs,
  221. DIV_ROUND_UP(KEY_SIZE(&w->key), PAGE_SECTORS));
  222. if (!io->dc->writeback_percent)
  223. bio_set_prio(bio, IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0));
  224. bio->bi_iter.bi_size = KEY_SIZE(&w->key) << 9;
  225. bio->bi_private = w;
  226. bch_bio_map(bio, NULL);
  227. }
  228. static void dirty_io_destructor(struct closure *cl)
  229. {
  230. struct dirty_io *io = container_of(cl, struct dirty_io, cl);
  231. kfree(io);
  232. }
  233. static void write_dirty_finish(struct closure *cl)
  234. {
  235. struct dirty_io *io = container_of(cl, struct dirty_io, cl);
  236. struct keybuf_key *w = io->bio.bi_private;
  237. struct cached_dev *dc = io->dc;
  238. bio_free_pages(&io->bio);
  239. /* This is kind of a dumb way of signalling errors. */
  240. if (KEY_DIRTY(&w->key)) {
  241. int ret;
  242. unsigned int i;
  243. struct keylist keys;
  244. bch_keylist_init(&keys);
  245. bkey_copy(keys.top, &w->key);
  246. SET_KEY_DIRTY(keys.top, false);
  247. bch_keylist_push(&keys);
  248. for (i = 0; i < KEY_PTRS(&w->key); i++)
  249. atomic_inc(&PTR_BUCKET(dc->disk.c, &w->key, i)->pin);
  250. ret = bch_btree_insert(dc->disk.c, &keys, NULL, &w->key);
  251. if (ret)
  252. trace_bcache_writeback_collision(&w->key);
  253. atomic_long_inc(ret
  254. ? &dc->disk.c->writeback_keys_failed
  255. : &dc->disk.c->writeback_keys_done);
  256. }
  257. bch_keybuf_del(&dc->writeback_keys, w);
  258. up(&dc->in_flight);
  259. closure_return_with_destructor(cl, dirty_io_destructor);
  260. }
  261. static void dirty_endio(struct bio *bio)
  262. {
  263. struct keybuf_key *w = bio->bi_private;
  264. struct dirty_io *io = w->private;
  265. if (bio->bi_status) {
  266. SET_KEY_DIRTY(&w->key, false);
  267. bch_count_backing_io_errors(io->dc, bio);
  268. }
  269. closure_put(&io->cl);
  270. }
  271. static void write_dirty(struct closure *cl)
  272. {
  273. struct dirty_io *io = container_of(cl, struct dirty_io, cl);
  274. struct keybuf_key *w = io->bio.bi_private;
  275. struct cached_dev *dc = io->dc;
  276. uint16_t next_sequence;
  277. if (atomic_read(&dc->writeback_sequence_next) != io->sequence) {
  278. /* Not our turn to write; wait for a write to complete */
  279. closure_wait(&dc->writeback_ordering_wait, cl);
  280. if (atomic_read(&dc->writeback_sequence_next) == io->sequence) {
  281. /*
  282. * Edge case-- it happened in indeterminate order
  283. * relative to when we were added to wait list..
  284. */
  285. closure_wake_up(&dc->writeback_ordering_wait);
  286. }
  287. continue_at(cl, write_dirty, io->dc->writeback_write_wq);
  288. return;
  289. }
  290. next_sequence = io->sequence + 1;
  291. /*
  292. * IO errors are signalled using the dirty bit on the key.
  293. * If we failed to read, we should not attempt to write to the
  294. * backing device. Instead, immediately go to write_dirty_finish
  295. * to clean up.
  296. */
  297. if (KEY_DIRTY(&w->key)) {
  298. dirty_init(w);
  299. bio_set_op_attrs(&io->bio, REQ_OP_WRITE, 0);
  300. io->bio.bi_iter.bi_sector = KEY_START(&w->key);
  301. bio_set_dev(&io->bio, io->dc->bdev);
  302. io->bio.bi_end_io = dirty_endio;
  303. /* I/O request sent to backing device */
  304. closure_bio_submit(io->dc->disk.c, &io->bio, cl);
  305. }
  306. atomic_set(&dc->writeback_sequence_next, next_sequence);
  307. closure_wake_up(&dc->writeback_ordering_wait);
  308. continue_at(cl, write_dirty_finish, io->dc->writeback_write_wq);
  309. }
  310. static void read_dirty_endio(struct bio *bio)
  311. {
  312. struct keybuf_key *w = bio->bi_private;
  313. struct dirty_io *io = w->private;
  314. /* is_read = 1 */
  315. bch_count_io_errors(PTR_CACHE(io->dc->disk.c, &w->key, 0),
  316. bio->bi_status, 1,
  317. "reading dirty data from cache");
  318. dirty_endio(bio);
  319. }
  320. static void read_dirty_submit(struct closure *cl)
  321. {
  322. struct dirty_io *io = container_of(cl, struct dirty_io, cl);
  323. closure_bio_submit(io->dc->disk.c, &io->bio, cl);
  324. continue_at(cl, write_dirty, io->dc->writeback_write_wq);
  325. }
  326. static void read_dirty(struct cached_dev *dc)
  327. {
  328. unsigned int delay = 0;
  329. struct keybuf_key *next, *keys[MAX_WRITEBACKS_IN_PASS], *w;
  330. size_t size;
  331. int nk, i;
  332. struct dirty_io *io;
  333. struct closure cl;
  334. uint16_t sequence = 0;
  335. BUG_ON(!llist_empty(&dc->writeback_ordering_wait.list));
  336. atomic_set(&dc->writeback_sequence_next, sequence);
  337. closure_init_stack(&cl);
  338. /*
  339. * XXX: if we error, background writeback just spins. Should use some
  340. * mempools.
  341. */
  342. next = bch_keybuf_next(&dc->writeback_keys);
  343. while (!kthread_should_stop() &&
  344. !test_bit(CACHE_SET_IO_DISABLE, &dc->disk.c->flags) &&
  345. next) {
  346. size = 0;
  347. nk = 0;
  348. do {
  349. BUG_ON(ptr_stale(dc->disk.c, &next->key, 0));
  350. /*
  351. * Don't combine too many operations, even if they
  352. * are all small.
  353. */
  354. if (nk >= MAX_WRITEBACKS_IN_PASS)
  355. break;
  356. /*
  357. * If the current operation is very large, don't
  358. * further combine operations.
  359. */
  360. if (size >= MAX_WRITESIZE_IN_PASS)
  361. break;
  362. /*
  363. * Operations are only eligible to be combined
  364. * if they are contiguous.
  365. *
  366. * TODO: add a heuristic willing to fire a
  367. * certain amount of non-contiguous IO per pass,
  368. * so that we can benefit from backing device
  369. * command queueing.
  370. */
  371. if ((nk != 0) && bkey_cmp(&keys[nk-1]->key,
  372. &START_KEY(&next->key)))
  373. break;
  374. size += KEY_SIZE(&next->key);
  375. keys[nk++] = next;
  376. } while ((next = bch_keybuf_next(&dc->writeback_keys)));
  377. /* Now we have gathered a set of 1..5 keys to write back. */
  378. for (i = 0; i < nk; i++) {
  379. w = keys[i];
  380. io = kzalloc(sizeof(struct dirty_io) +
  381. sizeof(struct bio_vec) *
  382. DIV_ROUND_UP(KEY_SIZE(&w->key),
  383. PAGE_SECTORS),
  384. GFP_KERNEL);
  385. if (!io)
  386. goto err;
  387. w->private = io;
  388. io->dc = dc;
  389. io->sequence = sequence++;
  390. dirty_init(w);
  391. bio_set_op_attrs(&io->bio, REQ_OP_READ, 0);
  392. io->bio.bi_iter.bi_sector = PTR_OFFSET(&w->key, 0);
  393. bio_set_dev(&io->bio,
  394. PTR_CACHE(dc->disk.c, &w->key, 0)->bdev);
  395. io->bio.bi_end_io = read_dirty_endio;
  396. if (bch_bio_alloc_pages(&io->bio, GFP_KERNEL))
  397. goto err_free;
  398. trace_bcache_writeback(&w->key);
  399. down(&dc->in_flight);
  400. /*
  401. * We've acquired a semaphore for the maximum
  402. * simultaneous number of writebacks; from here
  403. * everything happens asynchronously.
  404. */
  405. closure_call(&io->cl, read_dirty_submit, NULL, &cl);
  406. }
  407. delay = writeback_delay(dc, size);
  408. while (!kthread_should_stop() &&
  409. !test_bit(CACHE_SET_IO_DISABLE, &dc->disk.c->flags) &&
  410. delay) {
  411. schedule_timeout_interruptible(delay);
  412. delay = writeback_delay(dc, 0);
  413. }
  414. }
  415. if (0) {
  416. err_free:
  417. kfree(w->private);
  418. err:
  419. bch_keybuf_del(&dc->writeback_keys, w);
  420. }
  421. /*
  422. * Wait for outstanding writeback IOs to finish (and keybuf slots to be
  423. * freed) before refilling again
  424. */
  425. closure_sync(&cl);
  426. }
  427. /* Scan for dirty data */
  428. void bcache_dev_sectors_dirty_add(struct cache_set *c, unsigned int inode,
  429. uint64_t offset, int nr_sectors)
  430. {
  431. struct bcache_device *d = c->devices[inode];
  432. unsigned int stripe_offset, sectors_dirty;
  433. int stripe;
  434. if (!d)
  435. return;
  436. stripe = offset_to_stripe(d, offset);
  437. if (stripe < 0)
  438. return;
  439. if (UUID_FLASH_ONLY(&c->uuids[inode]))
  440. atomic_long_add(nr_sectors, &c->flash_dev_dirty_sectors);
  441. stripe_offset = offset & (d->stripe_size - 1);
  442. while (nr_sectors) {
  443. int s = min_t(unsigned int, abs(nr_sectors),
  444. d->stripe_size - stripe_offset);
  445. if (nr_sectors < 0)
  446. s = -s;
  447. if (stripe >= d->nr_stripes)
  448. return;
  449. sectors_dirty = atomic_add_return(s,
  450. d->stripe_sectors_dirty + stripe);
  451. if (sectors_dirty == d->stripe_size)
  452. set_bit(stripe, d->full_dirty_stripes);
  453. else
  454. clear_bit(stripe, d->full_dirty_stripes);
  455. nr_sectors -= s;
  456. stripe_offset = 0;
  457. stripe++;
  458. }
  459. }
  460. static bool dirty_pred(struct keybuf *buf, struct bkey *k)
  461. {
  462. struct cached_dev *dc = container_of(buf,
  463. struct cached_dev,
  464. writeback_keys);
  465. BUG_ON(KEY_INODE(k) != dc->disk.id);
  466. return KEY_DIRTY(k);
  467. }
  468. static void refill_full_stripes(struct cached_dev *dc)
  469. {
  470. struct keybuf *buf = &dc->writeback_keys;
  471. unsigned int start_stripe, next_stripe;
  472. int stripe;
  473. bool wrapped = false;
  474. stripe = offset_to_stripe(&dc->disk, KEY_OFFSET(&buf->last_scanned));
  475. if (stripe < 0)
  476. stripe = 0;
  477. start_stripe = stripe;
  478. while (1) {
  479. stripe = find_next_bit(dc->disk.full_dirty_stripes,
  480. dc->disk.nr_stripes, stripe);
  481. if (stripe == dc->disk.nr_stripes)
  482. goto next;
  483. next_stripe = find_next_zero_bit(dc->disk.full_dirty_stripes,
  484. dc->disk.nr_stripes, stripe);
  485. buf->last_scanned = KEY(dc->disk.id,
  486. stripe * dc->disk.stripe_size, 0);
  487. bch_refill_keybuf(dc->disk.c, buf,
  488. &KEY(dc->disk.id,
  489. next_stripe * dc->disk.stripe_size, 0),
  490. dirty_pred);
  491. if (array_freelist_empty(&buf->freelist))
  492. return;
  493. stripe = next_stripe;
  494. next:
  495. if (wrapped && stripe > start_stripe)
  496. return;
  497. if (stripe == dc->disk.nr_stripes) {
  498. stripe = 0;
  499. wrapped = true;
  500. }
  501. }
  502. }
  503. /*
  504. * Returns true if we scanned the entire disk
  505. */
  506. static bool refill_dirty(struct cached_dev *dc)
  507. {
  508. struct keybuf *buf = &dc->writeback_keys;
  509. struct bkey start = KEY(dc->disk.id, 0, 0);
  510. struct bkey end = KEY(dc->disk.id, MAX_KEY_OFFSET, 0);
  511. struct bkey start_pos;
  512. /*
  513. * make sure keybuf pos is inside the range for this disk - at bringup
  514. * we might not be attached yet so this disk's inode nr isn't
  515. * initialized then
  516. */
  517. if (bkey_cmp(&buf->last_scanned, &start) < 0 ||
  518. bkey_cmp(&buf->last_scanned, &end) > 0)
  519. buf->last_scanned = start;
  520. if (dc->partial_stripes_expensive) {
  521. refill_full_stripes(dc);
  522. if (array_freelist_empty(&buf->freelist))
  523. return false;
  524. }
  525. start_pos = buf->last_scanned;
  526. bch_refill_keybuf(dc->disk.c, buf, &end, dirty_pred);
  527. if (bkey_cmp(&buf->last_scanned, &end) < 0)
  528. return false;
  529. /*
  530. * If we get to the end start scanning again from the beginning, and
  531. * only scan up to where we initially started scanning from:
  532. */
  533. buf->last_scanned = start;
  534. bch_refill_keybuf(dc->disk.c, buf, &start_pos, dirty_pred);
  535. return bkey_cmp(&buf->last_scanned, &start_pos) >= 0;
  536. }
  537. static int bch_writeback_thread(void *arg)
  538. {
  539. struct cached_dev *dc = arg;
  540. struct cache_set *c = dc->disk.c;
  541. bool searched_full_index;
  542. bch_ratelimit_reset(&dc->writeback_rate);
  543. while (!kthread_should_stop() &&
  544. !test_bit(CACHE_SET_IO_DISABLE, &c->flags)) {
  545. down_write(&dc->writeback_lock);
  546. set_current_state(TASK_INTERRUPTIBLE);
  547. /*
  548. * If the bache device is detaching, skip here and continue
  549. * to perform writeback. Otherwise, if no dirty data on cache,
  550. * or there is dirty data on cache but writeback is disabled,
  551. * the writeback thread should sleep here and wait for others
  552. * to wake up it.
  553. */
  554. if (!test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags) &&
  555. (!atomic_read(&dc->has_dirty) || !dc->writeback_running)) {
  556. up_write(&dc->writeback_lock);
  557. if (kthread_should_stop() ||
  558. test_bit(CACHE_SET_IO_DISABLE, &c->flags)) {
  559. set_current_state(TASK_RUNNING);
  560. break;
  561. }
  562. schedule();
  563. continue;
  564. }
  565. set_current_state(TASK_RUNNING);
  566. searched_full_index = refill_dirty(dc);
  567. if (searched_full_index &&
  568. RB_EMPTY_ROOT(&dc->writeback_keys.keys)) {
  569. atomic_set(&dc->has_dirty, 0);
  570. SET_BDEV_STATE(&dc->sb, BDEV_STATE_CLEAN);
  571. bch_write_bdev_super(dc, NULL);
  572. /*
  573. * If bcache device is detaching via sysfs interface,
  574. * writeback thread should stop after there is no dirty
  575. * data on cache. BCACHE_DEV_DETACHING flag is set in
  576. * bch_cached_dev_detach().
  577. */
  578. if (test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags)) {
  579. up_write(&dc->writeback_lock);
  580. break;
  581. }
  582. /*
  583. * When dirty data rate is high (e.g. 50%+), there might
  584. * be heavy buckets fragmentation after writeback
  585. * finished, which hurts following write performance.
  586. * If users really care about write performance they
  587. * may set BCH_ENABLE_AUTO_GC via sysfs, then when
  588. * BCH_DO_AUTO_GC is set, garbage collection thread
  589. * will be wake up here. After moving gc, the shrunk
  590. * btree and discarded free buckets SSD space may be
  591. * helpful for following write requests.
  592. */
  593. if (c->gc_after_writeback ==
  594. (BCH_ENABLE_AUTO_GC|BCH_DO_AUTO_GC)) {
  595. c->gc_after_writeback &= ~BCH_DO_AUTO_GC;
  596. force_wake_up_gc(c);
  597. }
  598. }
  599. up_write(&dc->writeback_lock);
  600. read_dirty(dc);
  601. if (searched_full_index) {
  602. unsigned int delay = dc->writeback_delay * HZ;
  603. while (delay &&
  604. !kthread_should_stop() &&
  605. !test_bit(CACHE_SET_IO_DISABLE, &c->flags) &&
  606. !test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags))
  607. delay = schedule_timeout_interruptible(delay);
  608. bch_ratelimit_reset(&dc->writeback_rate);
  609. }
  610. }
  611. if (dc->writeback_write_wq) {
  612. flush_workqueue(dc->writeback_write_wq);
  613. destroy_workqueue(dc->writeback_write_wq);
  614. }
  615. cached_dev_put(dc);
  616. wait_for_kthread_stop();
  617. return 0;
  618. }
  619. /* Init */
  620. #define INIT_KEYS_EACH_TIME 500000
  621. #define INIT_KEYS_SLEEP_MS 100
  622. struct sectors_dirty_init {
  623. struct btree_op op;
  624. unsigned int inode;
  625. size_t count;
  626. struct bkey start;
  627. };
  628. static int sectors_dirty_init_fn(struct btree_op *_op, struct btree *b,
  629. struct bkey *k)
  630. {
  631. struct sectors_dirty_init *op = container_of(_op,
  632. struct sectors_dirty_init, op);
  633. if (KEY_INODE(k) > op->inode)
  634. return MAP_DONE;
  635. if (KEY_DIRTY(k))
  636. bcache_dev_sectors_dirty_add(b->c, KEY_INODE(k),
  637. KEY_START(k), KEY_SIZE(k));
  638. op->count++;
  639. if (atomic_read(&b->c->search_inflight) &&
  640. !(op->count % INIT_KEYS_EACH_TIME)) {
  641. bkey_copy_key(&op->start, k);
  642. return -EAGAIN;
  643. }
  644. return MAP_CONTINUE;
  645. }
  646. void bch_sectors_dirty_init(struct bcache_device *d)
  647. {
  648. struct sectors_dirty_init op;
  649. int ret;
  650. bch_btree_op_init(&op.op, -1);
  651. op.inode = d->id;
  652. op.count = 0;
  653. op.start = KEY(op.inode, 0, 0);
  654. do {
  655. ret = bch_btree_map_keys(&op.op, d->c, &op.start,
  656. sectors_dirty_init_fn, 0);
  657. if (ret == -EAGAIN)
  658. schedule_timeout_interruptible(
  659. msecs_to_jiffies(INIT_KEYS_SLEEP_MS));
  660. else if (ret < 0) {
  661. pr_warn("sectors dirty init failed, ret=%d!", ret);
  662. break;
  663. }
  664. } while (ret == -EAGAIN);
  665. }
  666. void bch_cached_dev_writeback_init(struct cached_dev *dc)
  667. {
  668. sema_init(&dc->in_flight, 64);
  669. init_rwsem(&dc->writeback_lock);
  670. bch_keybuf_init(&dc->writeback_keys);
  671. dc->writeback_metadata = true;
  672. dc->writeback_running = false;
  673. dc->writeback_percent = 10;
  674. dc->writeback_delay = 30;
  675. atomic_long_set(&dc->writeback_rate.rate, 1024);
  676. dc->writeback_rate_minimum = 8;
  677. dc->writeback_rate_update_seconds = WRITEBACK_RATE_UPDATE_SECS_DEFAULT;
  678. dc->writeback_rate_p_term_inverse = 40;
  679. dc->writeback_rate_i_term_inverse = 10000;
  680. WARN_ON(test_and_clear_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags));
  681. INIT_DELAYED_WORK(&dc->writeback_rate_update, update_writeback_rate);
  682. }
  683. int bch_cached_dev_writeback_start(struct cached_dev *dc)
  684. {
  685. dc->writeback_write_wq = alloc_workqueue("bcache_writeback_wq",
  686. WQ_MEM_RECLAIM, 0);
  687. if (!dc->writeback_write_wq)
  688. return -ENOMEM;
  689. cached_dev_get(dc);
  690. dc->writeback_thread = kthread_create(bch_writeback_thread, dc,
  691. "bcache_writeback");
  692. if (IS_ERR(dc->writeback_thread)) {
  693. cached_dev_put(dc);
  694. destroy_workqueue(dc->writeback_write_wq);
  695. return PTR_ERR(dc->writeback_thread);
  696. }
  697. dc->writeback_running = true;
  698. WARN_ON(test_and_set_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags));
  699. schedule_delayed_work(&dc->writeback_rate_update,
  700. dc->writeback_rate_update_seconds * HZ);
  701. bch_writeback_queue(dc);
  702. return 0;
  703. }