writeback.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  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. /* Rate limiting */
  18. static void __update_writeback_rate(struct cached_dev *dc)
  19. {
  20. struct cache_set *c = dc->disk.c;
  21. uint64_t cache_sectors = c->nbuckets * c->sb.bucket_size -
  22. bcache_flash_devs_sectors_dirty(c);
  23. uint64_t cache_dirty_target =
  24. div_u64(cache_sectors * dc->writeback_percent, 100);
  25. int64_t target = div64_u64(cache_dirty_target * bdev_sectors(dc->bdev),
  26. c->cached_dev_sectors);
  27. /*
  28. * PI controller:
  29. * Figures out the amount that should be written per second.
  30. *
  31. * First, the error (number of sectors that are dirty beyond our
  32. * target) is calculated. The error is accumulated (numerically
  33. * integrated).
  34. *
  35. * Then, the proportional value and integral value are scaled
  36. * based on configured values. These are stored as inverses to
  37. * avoid fixed point math and to make configuration easy-- e.g.
  38. * the default value of 40 for writeback_rate_p_term_inverse
  39. * attempts to write at a rate that would retire all the dirty
  40. * blocks in 40 seconds.
  41. *
  42. * The writeback_rate_i_inverse value of 10000 means that 1/10000th
  43. * of the error is accumulated in the integral term per second.
  44. * This acts as a slow, long-term average that is not subject to
  45. * variations in usage like the p term.
  46. */
  47. int64_t dirty = bcache_dev_sectors_dirty(&dc->disk);
  48. int64_t error = dirty - target;
  49. int64_t proportional_scaled =
  50. div_s64(error, dc->writeback_rate_p_term_inverse);
  51. int64_t integral_scaled;
  52. uint32_t new_rate;
  53. if ((error < 0 && dc->writeback_rate_integral > 0) ||
  54. (error > 0 && time_before64(local_clock(),
  55. dc->writeback_rate.next + NSEC_PER_MSEC))) {
  56. /*
  57. * Only decrease the integral term if it's more than
  58. * zero. Only increase the integral term if the device
  59. * is keeping up. (Don't wind up the integral
  60. * ineffectively in either case).
  61. *
  62. * It's necessary to scale this by
  63. * writeback_rate_update_seconds to keep the integral
  64. * term dimensioned properly.
  65. */
  66. dc->writeback_rate_integral += error *
  67. dc->writeback_rate_update_seconds;
  68. }
  69. integral_scaled = div_s64(dc->writeback_rate_integral,
  70. dc->writeback_rate_i_term_inverse);
  71. new_rate = clamp_t(int32_t, (proportional_scaled + integral_scaled),
  72. dc->writeback_rate_minimum, NSEC_PER_SEC);
  73. dc->writeback_rate_proportional = proportional_scaled;
  74. dc->writeback_rate_integral_scaled = integral_scaled;
  75. dc->writeback_rate_change = new_rate - dc->writeback_rate.rate;
  76. dc->writeback_rate.rate = new_rate;
  77. dc->writeback_rate_target = target;
  78. }
  79. static void update_writeback_rate(struct work_struct *work)
  80. {
  81. struct cached_dev *dc = container_of(to_delayed_work(work),
  82. struct cached_dev,
  83. writeback_rate_update);
  84. down_read(&dc->writeback_lock);
  85. if (atomic_read(&dc->has_dirty) &&
  86. dc->writeback_percent)
  87. __update_writeback_rate(dc);
  88. up_read(&dc->writeback_lock);
  89. schedule_delayed_work(&dc->writeback_rate_update,
  90. dc->writeback_rate_update_seconds * HZ);
  91. }
  92. static unsigned writeback_delay(struct cached_dev *dc, unsigned sectors)
  93. {
  94. if (test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags) ||
  95. !dc->writeback_percent)
  96. return 0;
  97. return bch_next_delay(&dc->writeback_rate, sectors);
  98. }
  99. struct dirty_io {
  100. struct closure cl;
  101. struct cached_dev *dc;
  102. uint16_t sequence;
  103. struct bio bio;
  104. };
  105. static void dirty_init(struct keybuf_key *w)
  106. {
  107. struct dirty_io *io = w->private;
  108. struct bio *bio = &io->bio;
  109. bio_init(bio, bio->bi_inline_vecs,
  110. DIV_ROUND_UP(KEY_SIZE(&w->key), PAGE_SECTORS));
  111. if (!io->dc->writeback_percent)
  112. bio_set_prio(bio, IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0));
  113. bio->bi_iter.bi_size = KEY_SIZE(&w->key) << 9;
  114. bio->bi_private = w;
  115. bch_bio_map(bio, NULL);
  116. }
  117. static void dirty_io_destructor(struct closure *cl)
  118. {
  119. struct dirty_io *io = container_of(cl, struct dirty_io, cl);
  120. kfree(io);
  121. }
  122. static void write_dirty_finish(struct closure *cl)
  123. {
  124. struct dirty_io *io = container_of(cl, struct dirty_io, cl);
  125. struct keybuf_key *w = io->bio.bi_private;
  126. struct cached_dev *dc = io->dc;
  127. bio_free_pages(&io->bio);
  128. /* This is kind of a dumb way of signalling errors. */
  129. if (KEY_DIRTY(&w->key)) {
  130. int ret;
  131. unsigned i;
  132. struct keylist keys;
  133. bch_keylist_init(&keys);
  134. bkey_copy(keys.top, &w->key);
  135. SET_KEY_DIRTY(keys.top, false);
  136. bch_keylist_push(&keys);
  137. for (i = 0; i < KEY_PTRS(&w->key); i++)
  138. atomic_inc(&PTR_BUCKET(dc->disk.c, &w->key, i)->pin);
  139. ret = bch_btree_insert(dc->disk.c, &keys, NULL, &w->key);
  140. if (ret)
  141. trace_bcache_writeback_collision(&w->key);
  142. atomic_long_inc(ret
  143. ? &dc->disk.c->writeback_keys_failed
  144. : &dc->disk.c->writeback_keys_done);
  145. }
  146. bch_keybuf_del(&dc->writeback_keys, w);
  147. up(&dc->in_flight);
  148. closure_return_with_destructor(cl, dirty_io_destructor);
  149. }
  150. static void dirty_endio(struct bio *bio)
  151. {
  152. struct keybuf_key *w = bio->bi_private;
  153. struct dirty_io *io = w->private;
  154. if (bio->bi_status)
  155. SET_KEY_DIRTY(&w->key, false);
  156. closure_put(&io->cl);
  157. }
  158. static void write_dirty(struct closure *cl)
  159. {
  160. struct dirty_io *io = container_of(cl, struct dirty_io, cl);
  161. struct keybuf_key *w = io->bio.bi_private;
  162. struct cached_dev *dc = io->dc;
  163. uint16_t next_sequence;
  164. if (atomic_read(&dc->writeback_sequence_next) != io->sequence) {
  165. /* Not our turn to write; wait for a write to complete */
  166. closure_wait(&dc->writeback_ordering_wait, cl);
  167. if (atomic_read(&dc->writeback_sequence_next) == io->sequence) {
  168. /*
  169. * Edge case-- it happened in indeterminate order
  170. * relative to when we were added to wait list..
  171. */
  172. closure_wake_up(&dc->writeback_ordering_wait);
  173. }
  174. continue_at(cl, write_dirty, io->dc->writeback_write_wq);
  175. return;
  176. }
  177. next_sequence = io->sequence + 1;
  178. /*
  179. * IO errors are signalled using the dirty bit on the key.
  180. * If we failed to read, we should not attempt to write to the
  181. * backing device. Instead, immediately go to write_dirty_finish
  182. * to clean up.
  183. */
  184. if (KEY_DIRTY(&w->key)) {
  185. dirty_init(w);
  186. bio_set_op_attrs(&io->bio, REQ_OP_WRITE, 0);
  187. io->bio.bi_iter.bi_sector = KEY_START(&w->key);
  188. bio_set_dev(&io->bio, io->dc->bdev);
  189. io->bio.bi_end_io = dirty_endio;
  190. closure_bio_submit(&io->bio, cl);
  191. }
  192. atomic_set(&dc->writeback_sequence_next, next_sequence);
  193. closure_wake_up(&dc->writeback_ordering_wait);
  194. continue_at(cl, write_dirty_finish, io->dc->writeback_write_wq);
  195. }
  196. static void read_dirty_endio(struct bio *bio)
  197. {
  198. struct keybuf_key *w = bio->bi_private;
  199. struct dirty_io *io = w->private;
  200. bch_count_io_errors(PTR_CACHE(io->dc->disk.c, &w->key, 0),
  201. bio->bi_status, "reading dirty data from cache");
  202. dirty_endio(bio);
  203. }
  204. static void read_dirty_submit(struct closure *cl)
  205. {
  206. struct dirty_io *io = container_of(cl, struct dirty_io, cl);
  207. closure_bio_submit(&io->bio, cl);
  208. continue_at(cl, write_dirty, io->dc->writeback_write_wq);
  209. }
  210. static void read_dirty(struct cached_dev *dc)
  211. {
  212. unsigned delay = 0;
  213. struct keybuf_key *next, *keys[MAX_WRITEBACKS_IN_PASS], *w;
  214. size_t size;
  215. int nk, i;
  216. struct dirty_io *io;
  217. struct closure cl;
  218. uint16_t sequence = 0;
  219. BUG_ON(!llist_empty(&dc->writeback_ordering_wait.list));
  220. atomic_set(&dc->writeback_sequence_next, sequence);
  221. closure_init_stack(&cl);
  222. /*
  223. * XXX: if we error, background writeback just spins. Should use some
  224. * mempools.
  225. */
  226. next = bch_keybuf_next(&dc->writeback_keys);
  227. while (!kthread_should_stop() && next) {
  228. size = 0;
  229. nk = 0;
  230. do {
  231. BUG_ON(ptr_stale(dc->disk.c, &next->key, 0));
  232. /*
  233. * Don't combine too many operations, even if they
  234. * are all small.
  235. */
  236. if (nk >= MAX_WRITEBACKS_IN_PASS)
  237. break;
  238. /*
  239. * If the current operation is very large, don't
  240. * further combine operations.
  241. */
  242. if (size >= MAX_WRITESIZE_IN_PASS)
  243. break;
  244. /*
  245. * Operations are only eligible to be combined
  246. * if they are contiguous.
  247. *
  248. * TODO: add a heuristic willing to fire a
  249. * certain amount of non-contiguous IO per pass,
  250. * so that we can benefit from backing device
  251. * command queueing.
  252. */
  253. if ((nk != 0) && bkey_cmp(&keys[nk-1]->key,
  254. &START_KEY(&next->key)))
  255. break;
  256. size += KEY_SIZE(&next->key);
  257. keys[nk++] = next;
  258. } while ((next = bch_keybuf_next(&dc->writeback_keys)));
  259. /* Now we have gathered a set of 1..5 keys to write back. */
  260. for (i = 0; i < nk; i++) {
  261. w = keys[i];
  262. io = kzalloc(sizeof(struct dirty_io) +
  263. sizeof(struct bio_vec) *
  264. DIV_ROUND_UP(KEY_SIZE(&w->key), PAGE_SECTORS),
  265. GFP_KERNEL);
  266. if (!io)
  267. goto err;
  268. w->private = io;
  269. io->dc = dc;
  270. io->sequence = sequence++;
  271. dirty_init(w);
  272. bio_set_op_attrs(&io->bio, REQ_OP_READ, 0);
  273. io->bio.bi_iter.bi_sector = PTR_OFFSET(&w->key, 0);
  274. bio_set_dev(&io->bio,
  275. PTR_CACHE(dc->disk.c, &w->key, 0)->bdev);
  276. io->bio.bi_end_io = read_dirty_endio;
  277. if (bch_bio_alloc_pages(&io->bio, GFP_KERNEL))
  278. goto err_free;
  279. trace_bcache_writeback(&w->key);
  280. down(&dc->in_flight);
  281. /* We've acquired a semaphore for the maximum
  282. * simultaneous number of writebacks; from here
  283. * everything happens asynchronously.
  284. */
  285. closure_call(&io->cl, read_dirty_submit, NULL, &cl);
  286. }
  287. delay = writeback_delay(dc, size);
  288. /* If the control system would wait for at least half a
  289. * second, and there's been no reqs hitting the backing disk
  290. * for awhile: use an alternate mode where we have at most
  291. * one contiguous set of writebacks in flight at a time. If
  292. * someone wants to do IO it will be quick, as it will only
  293. * have to contend with one operation in flight, and we'll
  294. * be round-tripping data to the backing disk as quickly as
  295. * it can accept it.
  296. */
  297. if (delay >= HZ / 2) {
  298. /* 3 means at least 1.5 seconds, up to 7.5 if we
  299. * have slowed way down.
  300. */
  301. if (atomic_inc_return(&dc->backing_idle) >= 3) {
  302. /* Wait for current I/Os to finish */
  303. closure_sync(&cl);
  304. /* And immediately launch a new set. */
  305. delay = 0;
  306. }
  307. }
  308. while (!kthread_should_stop() && delay) {
  309. schedule_timeout_interruptible(delay);
  310. delay = writeback_delay(dc, 0);
  311. }
  312. }
  313. if (0) {
  314. err_free:
  315. kfree(w->private);
  316. err:
  317. bch_keybuf_del(&dc->writeback_keys, w);
  318. }
  319. /*
  320. * Wait for outstanding writeback IOs to finish (and keybuf slots to be
  321. * freed) before refilling again
  322. */
  323. closure_sync(&cl);
  324. }
  325. /* Scan for dirty data */
  326. void bcache_dev_sectors_dirty_add(struct cache_set *c, unsigned inode,
  327. uint64_t offset, int nr_sectors)
  328. {
  329. struct bcache_device *d = c->devices[inode];
  330. unsigned stripe_offset, stripe, sectors_dirty;
  331. if (!d)
  332. return;
  333. stripe = offset_to_stripe(d, offset);
  334. stripe_offset = offset & (d->stripe_size - 1);
  335. while (nr_sectors) {
  336. int s = min_t(unsigned, abs(nr_sectors),
  337. d->stripe_size - stripe_offset);
  338. if (nr_sectors < 0)
  339. s = -s;
  340. if (stripe >= d->nr_stripes)
  341. return;
  342. sectors_dirty = atomic_add_return(s,
  343. d->stripe_sectors_dirty + stripe);
  344. if (sectors_dirty == d->stripe_size)
  345. set_bit(stripe, d->full_dirty_stripes);
  346. else
  347. clear_bit(stripe, d->full_dirty_stripes);
  348. nr_sectors -= s;
  349. stripe_offset = 0;
  350. stripe++;
  351. }
  352. }
  353. static bool dirty_pred(struct keybuf *buf, struct bkey *k)
  354. {
  355. struct cached_dev *dc = container_of(buf, struct cached_dev, writeback_keys);
  356. BUG_ON(KEY_INODE(k) != dc->disk.id);
  357. return KEY_DIRTY(k);
  358. }
  359. static void refill_full_stripes(struct cached_dev *dc)
  360. {
  361. struct keybuf *buf = &dc->writeback_keys;
  362. unsigned start_stripe, stripe, next_stripe;
  363. bool wrapped = false;
  364. stripe = offset_to_stripe(&dc->disk, KEY_OFFSET(&buf->last_scanned));
  365. if (stripe >= dc->disk.nr_stripes)
  366. stripe = 0;
  367. start_stripe = stripe;
  368. while (1) {
  369. stripe = find_next_bit(dc->disk.full_dirty_stripes,
  370. dc->disk.nr_stripes, stripe);
  371. if (stripe == dc->disk.nr_stripes)
  372. goto next;
  373. next_stripe = find_next_zero_bit(dc->disk.full_dirty_stripes,
  374. dc->disk.nr_stripes, stripe);
  375. buf->last_scanned = KEY(dc->disk.id,
  376. stripe * dc->disk.stripe_size, 0);
  377. bch_refill_keybuf(dc->disk.c, buf,
  378. &KEY(dc->disk.id,
  379. next_stripe * dc->disk.stripe_size, 0),
  380. dirty_pred);
  381. if (array_freelist_empty(&buf->freelist))
  382. return;
  383. stripe = next_stripe;
  384. next:
  385. if (wrapped && stripe > start_stripe)
  386. return;
  387. if (stripe == dc->disk.nr_stripes) {
  388. stripe = 0;
  389. wrapped = true;
  390. }
  391. }
  392. }
  393. /*
  394. * Returns true if we scanned the entire disk
  395. */
  396. static bool refill_dirty(struct cached_dev *dc)
  397. {
  398. struct keybuf *buf = &dc->writeback_keys;
  399. struct bkey start = KEY(dc->disk.id, 0, 0);
  400. struct bkey end = KEY(dc->disk.id, MAX_KEY_OFFSET, 0);
  401. struct bkey start_pos;
  402. /*
  403. * make sure keybuf pos is inside the range for this disk - at bringup
  404. * we might not be attached yet so this disk's inode nr isn't
  405. * initialized then
  406. */
  407. if (bkey_cmp(&buf->last_scanned, &start) < 0 ||
  408. bkey_cmp(&buf->last_scanned, &end) > 0)
  409. buf->last_scanned = start;
  410. if (dc->partial_stripes_expensive) {
  411. refill_full_stripes(dc);
  412. if (array_freelist_empty(&buf->freelist))
  413. return false;
  414. }
  415. start_pos = buf->last_scanned;
  416. bch_refill_keybuf(dc->disk.c, buf, &end, dirty_pred);
  417. if (bkey_cmp(&buf->last_scanned, &end) < 0)
  418. return false;
  419. /*
  420. * If we get to the end start scanning again from the beginning, and
  421. * only scan up to where we initially started scanning from:
  422. */
  423. buf->last_scanned = start;
  424. bch_refill_keybuf(dc->disk.c, buf, &start_pos, dirty_pred);
  425. return bkey_cmp(&buf->last_scanned, &start_pos) >= 0;
  426. }
  427. static int bch_writeback_thread(void *arg)
  428. {
  429. struct cached_dev *dc = arg;
  430. bool searched_full_index;
  431. bch_ratelimit_reset(&dc->writeback_rate);
  432. while (!kthread_should_stop()) {
  433. down_write(&dc->writeback_lock);
  434. if (!atomic_read(&dc->has_dirty) ||
  435. (!test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags) &&
  436. !dc->writeback_running)) {
  437. up_write(&dc->writeback_lock);
  438. set_current_state(TASK_INTERRUPTIBLE);
  439. if (kthread_should_stop())
  440. return 0;
  441. schedule();
  442. continue;
  443. }
  444. searched_full_index = refill_dirty(dc);
  445. if (searched_full_index &&
  446. RB_EMPTY_ROOT(&dc->writeback_keys.keys)) {
  447. atomic_set(&dc->has_dirty, 0);
  448. cached_dev_put(dc);
  449. SET_BDEV_STATE(&dc->sb, BDEV_STATE_CLEAN);
  450. bch_write_bdev_super(dc, NULL);
  451. }
  452. up_write(&dc->writeback_lock);
  453. read_dirty(dc);
  454. if (searched_full_index) {
  455. unsigned delay = dc->writeback_delay * HZ;
  456. while (delay &&
  457. !kthread_should_stop() &&
  458. !test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags))
  459. delay = schedule_timeout_interruptible(delay);
  460. bch_ratelimit_reset(&dc->writeback_rate);
  461. }
  462. }
  463. return 0;
  464. }
  465. /* Init */
  466. struct sectors_dirty_init {
  467. struct btree_op op;
  468. unsigned inode;
  469. };
  470. static int sectors_dirty_init_fn(struct btree_op *_op, struct btree *b,
  471. struct bkey *k)
  472. {
  473. struct sectors_dirty_init *op = container_of(_op,
  474. struct sectors_dirty_init, op);
  475. if (KEY_INODE(k) > op->inode)
  476. return MAP_DONE;
  477. if (KEY_DIRTY(k))
  478. bcache_dev_sectors_dirty_add(b->c, KEY_INODE(k),
  479. KEY_START(k), KEY_SIZE(k));
  480. return MAP_CONTINUE;
  481. }
  482. void bch_sectors_dirty_init(struct bcache_device *d)
  483. {
  484. struct sectors_dirty_init op;
  485. bch_btree_op_init(&op.op, -1);
  486. op.inode = d->id;
  487. bch_btree_map_keys(&op.op, d->c, &KEY(op.inode, 0, 0),
  488. sectors_dirty_init_fn, 0);
  489. }
  490. void bch_cached_dev_writeback_init(struct cached_dev *dc)
  491. {
  492. sema_init(&dc->in_flight, 64);
  493. init_rwsem(&dc->writeback_lock);
  494. bch_keybuf_init(&dc->writeback_keys);
  495. dc->writeback_metadata = true;
  496. dc->writeback_running = true;
  497. dc->writeback_percent = 10;
  498. dc->writeback_delay = 30;
  499. dc->writeback_rate.rate = 1024;
  500. dc->writeback_rate_minimum = 8;
  501. dc->writeback_rate_update_seconds = 5;
  502. dc->writeback_rate_p_term_inverse = 40;
  503. dc->writeback_rate_i_term_inverse = 10000;
  504. INIT_DELAYED_WORK(&dc->writeback_rate_update, update_writeback_rate);
  505. }
  506. int bch_cached_dev_writeback_start(struct cached_dev *dc)
  507. {
  508. dc->writeback_write_wq = alloc_workqueue("bcache_writeback_wq",
  509. WQ_MEM_RECLAIM, 0);
  510. if (!dc->writeback_write_wq)
  511. return -ENOMEM;
  512. dc->writeback_thread = kthread_create(bch_writeback_thread, dc,
  513. "bcache_writeback");
  514. if (IS_ERR(dc->writeback_thread))
  515. return PTR_ERR(dc->writeback_thread);
  516. schedule_delayed_work(&dc->writeback_rate_update,
  517. dc->writeback_rate_update_seconds * HZ);
  518. bch_writeback_queue(dc);
  519. return 0;
  520. }