1============================ 2A block layer cache (bcache) 3============================ 4 5Say you've got a big slow raid 6, and an ssd or three. Wouldn't it be 6nice if you could use them as cache... Hence bcache. 7 8The bcache wiki can be found at: 9 https://bcache.evilpiepirate.org 10 11This is the git repository of bcache-tools: 12 https://git.kernel.org/pub/scm/linux/kernel/git/colyli/bcache-tools.git/ 13 14The latest bcache kernel code can be found from mainline Linux kernel: 15 https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/ 16 17It's designed around the performance characteristics of SSDs - it only allocates 18in erase block sized buckets, and it uses a hybrid btree/log to track cached 19extents (which can be anywhere from a single sector to the bucket size). It's 20designed to avoid random writes at all costs. 21 22Both writethrough and writeback caching are supported. Writeback defaults to 23off, but can be switched on and off arbitrarily at runtime. Bcache goes to 24great lengths to protect your data - it reliably handles unclean shutdown. (It 25doesn't even have a notion of a clean shutdown; bcache simply doesn't return 26writes as completed until they're on stable storage). 27 28Writeback caching can use most of the cache for buffering writes - writing 29dirty data to the backing device is always done sequentially, scanning from the 30start to the end of the index. 31 32Since random IO is what SSDs excel at, there generally won't be much benefit 33to caching large sequential IO. Bcache detects sequential IO and skips it; 34it also keeps a rolling average of the IO sizes per task, and as long as the 35average is above the cutoff it will skip all IO from that task - instead of 36caching the first 512k after every seek. Backups and large file copies should 37thus entirely bypass the cache. 38 39In the event of a data IO error on the flash it will try to recover by reading 40from disk or invalidating cache entries. For unrecoverable errors (meta data 41or dirty data), caching is automatically disabled; if dirty data was present 42in the cache it first disables writeback caching and waits for all dirty data 43to be flushed. 44 45Getting started: 46You'll need bcache util from the bcache-tools repository. Both the cache device 47and backing device must be formatted before use:: 48 49 bcache make -B /dev/sdb 50 bcache make -C /dev/sdc 51 52`bcache make` has the ability to format multiple devices at the same time - if 53you format your backing devices and cache device at the same time, you won't 54have to manually attach:: 55 56 bcache make -B /dev/sda /dev/sdb -C /dev/sdc 57 58If your bcache-tools is not updated to latest version and does not have the 59unified `bcache` utility, you may use the legacy `make-bcache` utility to format 60bcache device with same -B and -C parameters. 61 62bcache-tools now ships udev rules, and bcache devices are known to the kernel 63immediately. Without udev, you can manually register devices like this:: 64 65 echo /dev/sdb > /sys/fs/bcache/register 66 echo /dev/sdc > /sys/fs/bcache/register 67 68Registering the backing device makes the bcache device show up in /dev; you can 69now format it and use it as normal. But the first time using a new bcache 70device, it'll be running in passthrough mode until you attach it to a cache. 71If you are thinking about using bcache later, it is recommended to setup all your 72slow devices as bcache backing devices without a cache, and you can choose to add 73a caching device later. 74See 'ATTACHING' section below. 75 76The devices show up as:: 77 78 /dev/bcache<N> 79 80As well as (with udev):: 81 82 /dev/bcache/by-uuid/<uuid> 83 /dev/bcache/by-label/<label> 84 85To get started:: 86 87 mkfs.ext4 /dev/bcache0 88 mount /dev/bcache0 /mnt 89 90You can control bcache devices through sysfs at /sys/block/bcache<N>/bcache . 91You can also control them through /sys/fs//bcache/<cset-uuid>/ . 92 93Cache devices are managed as sets; multiple caches per set isn't supported yet 94but will allow for mirroring of metadata and dirty data in the future. Your new 95cache set shows up as /sys/fs/bcache/<UUID> 96 97Attaching 98--------- 99 100After your cache device and backing device are registered, the backing device 101must be attached to your cache set to enable caching. Attaching a backing 102device to a cache set is done thusly, with the UUID of the cache set in 103/sys/fs/bcache:: 104 105 echo <CSET-UUID> > /sys/block/bcache0/bcache/attach 106 107This only has to be done once. The next time you reboot, just reregister all 108your bcache devices. If a backing device has data in a cache somewhere, the 109/dev/bcache<N> device won't be created until the cache shows up - particularly 110important if you have writeback caching turned on. 111 112If you're booting up and your cache device is gone and never coming back, you 113can force run the backing device:: 114 115 echo 1 > /sys/block/sdb/bcache/running 116 117(You need to use /sys/block/sdb (or whatever your backing device is called), not 118/sys/block/bcache0, because bcache0 doesn't exist yet. If you're using a 119partition, the bcache directory would be at /sys/block/sdb/sdb2/bcache) 120 121The backing device will still use that cache set if it shows up in the future, 122but all the cached data will be invalidated. If there was dirty data in the 123cache, don't expect the filesystem to be recoverable - you will have massive 124filesystem corruption, though ext4's fsck does work miracles. 125 126Error Handling 127-------------- 128 129Bcache tries to transparently handle IO errors to/from the cache device without 130affecting normal operation; if it sees too many errors (the threshold is 131configurable, and defaults to 0) it shuts down the cache device and switches all 132the backing devices to passthrough mode. 133 134 - For reads from the cache, if they error we just retry the read from the 135 backing device. 136 137 - For writethrough writes, if the write to the cache errors we just switch to 138 invalidating the data at that lba in the cache (i.e. the same thing we do for 139 a write that bypasses the cache) 140 141 - For writeback writes, we currently pass that error back up to the 142 filesystem/userspace. This could be improved - we could retry it as a write 143 that skips the cache so we don't have to error the write. 144 145 - When we detach, we first try to flush any dirty data (if we were running in 146 writeback mode). It currently doesn't do anything intelligent if it fails to 147 read some of the dirty data, though. 148 149 150Howto/cookbook 151-------------- 152 153A) Starting a bcache with a missing caching device 154 155If registering the backing device doesn't help, it's already there, you just need 156to force it to run without the cache:: 157 158 host:~# echo /dev/sdb1 > /sys/fs/bcache/register 159 [ 119.844831] bcache: register_bcache() error opening /dev/sdb1: device already registered 160 161Next, you try to register your caching device if it's present. However 162if it's absent, or registration fails for some reason, you can still 163start your bcache without its cache, like so:: 164 165 host:/sys/block/sdb/sdb1/bcache# echo 1 > running 166 167Note that this may cause data loss if you were running in writeback mode. 168 169 170B) Bcache does not find its cache:: 171 172 host:/sys/block/md5/bcache# echo 0226553a-37cf-41d5-b3ce-8b1e944543a8 > attach 173 [ 1933.455082] bcache: bch_cached_dev_attach() Couldn't find uuid for md5 in set 174 [ 1933.478179] bcache: __cached_dev_store() Can't attach 0226553a-37cf-41d5-b3ce-8b1e944543a8 175 [ 1933.478179] : cache set not found 176 177In this case, the caching device was simply not registered at boot 178or disappeared and came back, and needs to be (re-)registered:: 179 180 host:/sys/block/md5/bcache# echo /dev/sdh2 > /sys/fs/bcache/register 181 182 183C) Corrupt bcache crashes the kernel at device registration time: 184 185This should never happen. If it does happen, then you have found a bug! 186Please report it to the bcache development list: linux-bcache@vger.kernel.org 187 188Be sure to provide as much information that you can including kernel dmesg 189output if available so that we may assist. 190 191 192D) Recovering data without bcache: 193 194If bcache is not available in the kernel, a filesystem on the backing 195device is still available at an 8KiB offset. So either via a loopdev 196of the backing device created with --offset 8K, or any value defined by 197--data-offset when you originally formatted bcache with `bcache make`. 198 199For example:: 200 201 losetup -o 8192 /dev/loop0 /dev/your_bcache_backing_dev 202 203This should present your unmodified backing device data in /dev/loop0 204 205If your cache is in writethrough mode, then you can safely discard the 206cache device without losing data. 207 208 209E) Wiping a cache device 210 211:: 212 213 host:~# wipefs -a /dev/sdh2 214 16 bytes were erased at offset 0x1018 (bcache) 215 they were: c6 85 73 f6 4e 1a 45 ca 82 65 f5 7f 48 ba 6d 81 216 217After you boot back with bcache enabled, you recreate the cache and attach it:: 218 219 host:~# bcache make -C /dev/sdh2 220 UUID: 7be7e175-8f4c-4f99-94b2-9c904d227045 221 Set UUID: 5bc072a8-ab17-446d-9744-e247949913c1 222 version: 0 223 nbuckets: 106874 224 block_size: 1 225 bucket_size: 1024 226 nr_in_set: 1 227 nr_this_dev: 0 228 first_bucket: 1 229 [ 650.511912] bcache: run_cache_set() invalidating existing data 230 [ 650.549228] bcache: register_cache() registered cache device sdh2 231 232start backing device with missing cache:: 233 234 host:/sys/block/md5/bcache# echo 1 > running 235 236attach new cache:: 237 238 host:/sys/block/md5/bcache# echo 5bc072a8-ab17-446d-9744-e247949913c1 > attach 239 [ 865.276616] bcache: bch_cached_dev_attach() Caching md5 as bcache0 on set 5bc072a8-ab17-446d-9744-e247949913c1 240 241 242F) Remove or replace a caching device:: 243 244 host:/sys/block/sda/sda7/bcache# echo 1 > detach 245 [ 695.872542] bcache: cached_dev_detach_finish() Caching disabled for sda7 246 247 host:~# wipefs -a /dev/nvme0n1p4 248 wipefs: error: /dev/nvme0n1p4: probing initialization failed: Device or resource busy 249 Ooops, it's disabled, but not unregistered, so it's still protected 250 251We need to go and unregister it:: 252 253 host:/sys/fs/bcache/b7ba27a1-2398-4649-8ae3-0959f57ba128# ls -l cache0 254 lrwxrwxrwx 1 root root 0 Feb 25 18:33 cache0 -> ../../../devices/pci0000:00/0000:00:1d.0/0000:70:00.0/nvme/nvme0/nvme0n1/nvme0n1p4/bcache/ 255 host:/sys/fs/bcache/b7ba27a1-2398-4649-8ae3-0959f57ba128# echo 1 > stop 256 kernel: [ 917.041908] bcache: cache_set_free() Cache set b7ba27a1-2398-4649-8ae3-0959f57ba128 unregistered 257 258Now we can wipe it:: 259 260 host:~# wipefs -a /dev/nvme0n1p4 261 /dev/nvme0n1p4: 16 bytes were erased at offset 0x00001018 (bcache): c6 85 73 f6 4e 1a 45 ca 82 65 f5 7f 48 ba 6d 81 262 263 264G) dm-crypt and bcache 265 266First setup bcache unencrypted and then install dmcrypt on top of 267/dev/bcache<N> This will work faster than if you dmcrypt both the backing 268and caching devices and then install bcache on top. [benchmarks?] 269 270 271H) Stop/free a registered bcache to wipe and/or recreate it 272 273Suppose that you need to free up all bcache references so that you can 274fdisk run and re-register a changed partition table, which won't work 275if there are any active backing or caching devices left on it: 276 2771) Is it present in /dev/bcache* ? (there are times where it won't be) 278 279 If so, it's easy:: 280 281 host:/sys/block/bcache0/bcache# echo 1 > stop 282 2832) But if your backing device is gone, this won't work:: 284 285 host:/sys/block/bcache0# cd bcache 286 bash: cd: bcache: No such file or directory 287 288 In this case, you may have to unregister the dmcrypt block device that 289 references this bcache to free it up:: 290 291 host:~# dmsetup remove oldds1 292 bcache: bcache_device_free() bcache0 stopped 293 bcache: cache_set_free() Cache set 5bc072a8-ab17-446d-9744-e247949913c1 unregistered 294 295 This causes the backing bcache to be removed from /sys/fs/bcache and 296 then it can be reused. This would be true of any block device stacking 297 where bcache is a lower device. 298 2993) In other cases, you can also look in /sys/fs/bcache/:: 300 301 host:/sys/fs/bcache# ls -l */{cache?,bdev?} 302 lrwxrwxrwx 1 root root 0 Mar 5 09:39 0226553a-37cf-41d5-b3ce-8b1e944543a8/bdev1 -> ../../../devices/virtual/block/dm-1/bcache/ 303 lrwxrwxrwx 1 root root 0 Mar 5 09:39 0226553a-37cf-41d5-b3ce-8b1e944543a8/cache0 -> ../../../devices/virtual/block/dm-4/bcache/ 304 lrwxrwxrwx 1 root root 0 Mar 5 09:39 5bc072a8-ab17-446d-9744-e247949913c1/cache0 -> ../../../devices/pci0000:00/0000:00:01.0/0000:01:00.0/ata10/host9/target9:0:0/9:0:0:0/block/sdl/sdl2/bcache/ 305 306 The device names will show which UUID is relevant, cd in that directory 307 and stop the cache:: 308 309 host:/sys/fs/bcache/5bc072a8-ab17-446d-9744-e247949913c1# echo 1 > stop 310 311 This will free up bcache references and let you reuse the partition for 312 other purposes. 313 314 315 316Troubleshooting performance 317--------------------------- 318 319Bcache has a bunch of config options and tunables. The defaults are intended to 320be reasonable for typical desktop and server workloads, but they're not what you 321want for getting the best possible numbers when benchmarking. 322 323 - Backing device alignment 324 325 The default metadata size in bcache is 8k. If your backing device is 326 RAID based, then be sure to align this by a multiple of your stride 327 width using `bcache make --data-offset`. If you intend to expand your 328 disk array in the future, then multiply a series of primes by your 329 raid stripe size to get the disk multiples that you would like. 330 331 For example: If you have a 64k stripe size, then the following offset 332 would provide alignment for many common RAID5 data spindle counts:: 333 334 64k * 2*2*2*3*3*5*7 bytes = 161280k 335 336 That space is wasted, but for only 157.5MB you can grow your RAID 5 337 volume to the following data-spindle counts without re-aligning:: 338 339 3,4,5,6,7,8,9,10,12,14,15,18,20,21 ... 340 341 - Bad write performance 342 343 If write performance is not what you expected, you probably wanted to be 344 running in writeback mode, which isn't the default (not due to a lack of 345 maturity, but simply because in writeback mode you'll lose data if something 346 happens to your SSD):: 347 348 # echo writeback > /sys/block/bcache0/bcache/cache_mode 349 350 - Bad performance, or traffic not going to the SSD that you'd expect 351 352 By default, bcache doesn't cache everything. It tries to skip sequential IO - 353 because you really want to be caching the random IO, and if you copy a 10 354 gigabyte file you probably don't want that pushing 10 gigabytes of randomly 355 accessed data out of your cache. 356 357 But if you want to benchmark reads from cache, and you start out with fio 358 writing an 8 gigabyte test file - so you want to disable that:: 359 360 # echo 0 > /sys/block/bcache0/bcache/sequential_cutoff 361 362 To set it back to the default (4 mb), do:: 363 364 # echo 4M > /sys/block/bcache0/bcache/sequential_cutoff 365 366 - Traffic's still going to the spindle/still getting cache misses 367 368 In the real world, SSDs don't always keep up with disks - particularly with 369 slower SSDs, many disks being cached by one SSD, or mostly sequential IO. So 370 you want to avoid being bottlenecked by the SSD and having it slow everything 371 down. 372 373 To avoid that bcache tracks latency to the cache device, and gradually 374 throttles traffic if the latency exceeds a threshold (it does this by 375 cranking down the sequential bypass). 376 377 You can disable this if you need to by setting the thresholds to 0:: 378 379 # echo 0 > /sys/fs/bcache/<cache set>/congested_read_threshold_us 380 # echo 0 > /sys/fs/bcache/<cache set>/congested_write_threshold_us 381 382 The default is 2000 us (2 milliseconds) for reads, and 20000 for writes. 383 384 - Still getting cache misses, of the same data 385 386 One last issue that sometimes trips people up is actually an old bug, due to 387 the way cache coherency is handled for cache misses. If a btree node is full, 388 a cache miss won't be able to insert a key for the new data and the data 389 won't be written to the cache. 390 391 In practice this isn't an issue because as soon as a write comes along it'll 392 cause the btree node to be split, and you need almost no write traffic for 393 this to not show up enough to be noticeable (especially since bcache's btree 394 nodes are huge and index large regions of the device). But when you're 395 benchmarking, if you're trying to warm the cache by reading a bunch of data 396 and there's no other traffic - that can be a problem. 397 398 Solution: warm the cache by doing writes, or use the testing branch (there's 399 a fix for the issue there). 400 401 402Sysfs - backing device 403---------------------- 404 405Available at /sys/block/<bdev>/bcache, /sys/block/bcache*/bcache and 406(if attached) /sys/fs/bcache/<cset-uuid>/bdev* 407 408attach 409 Echo the UUID of a cache set to this file to enable caching. 410 411cache_mode 412 Can be one of either writethrough, writeback, writearound or none. 413 414clear_stats 415 Writing to this file resets the running total stats (not the day/hour/5 minute 416 decaying versions). 417 418detach 419 Write to this file to detach from a cache set. If there is dirty data in the 420 cache, it will be flushed first. 421 422dirty_data 423 Amount of dirty data for this backing device in the cache. Continuously 424 updated unlike the cache set's version, but may be slightly off. 425 426label 427 Name of underlying device. 428 429readahead 430 Size of readahead that should be performed. Defaults to 0. If set to e.g. 431 1M, it will round cache miss reads up to that size, but without overlapping 432 existing cache entries. 433 434running 435 1 if bcache is running (i.e. whether the /dev/bcache device exists, whether 436 it's in passthrough mode or caching). 437 438sequential_cutoff 439 A sequential IO will bypass the cache once it passes this threshold; the 440 most recent 128 IOs are tracked so sequential IO can be detected even when 441 it isn't all done at once. 442 443sequential_merge 444 If non zero, bcache keeps a list of the last 128 requests submitted to compare 445 against all new requests to determine which new requests are sequential 446 continuations of previous requests for the purpose of determining sequential 447 cutoff. This is necessary if the sequential cutoff value is greater than the 448 maximum acceptable sequential size for any single request. 449 450state 451 The backing device can be in one of four different states: 452 453 no cache: Has never been attached to a cache set. 454 455 clean: Part of a cache set, and there is no cached dirty data. 456 457 dirty: Part of a cache set, and there is cached dirty data. 458 459 inconsistent: The backing device was forcibly run by the user when there was 460 dirty data cached but the cache set was unavailable; whatever data was on the 461 backing device has likely been corrupted. 462 463stop 464 Write to this file to shut down the bcache device and close the backing 465 device. 466 467writeback_delay 468 When dirty data is written to the cache and it previously did not contain 469 any, waits some number of seconds before initiating writeback. Defaults to 470 30. 471 472writeback_percent 473 If nonzero, bcache tries to keep around this percentage of the cache dirty by 474 throttling background writeback and using a PD controller to smoothly adjust 475 the rate. 476 477writeback_rate 478 Rate in sectors per second - if writeback_percent is nonzero, background 479 writeback is throttled to this rate. Continuously adjusted by bcache but may 480 also be set by the user. 481 482writeback_running 483 If off, writeback of dirty data will not take place at all. Dirty data will 484 still be added to the cache until it is mostly full; only meant for 485 benchmarking. Defaults to on. 486 487Sysfs - backing device stats 488~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 489 490There are directories with these numbers for a running total, as well as 491versions that decay over the past day, hour and 5 minutes; they're also 492aggregated in the cache set directory as well. 493 494bypassed 495 Amount of IO (both reads and writes) that has bypassed the cache 496 497cache_hits, cache_misses, cache_hit_ratio 498 Hits and misses are counted per individual IO as bcache sees them; a 499 partial hit is counted as a miss. 500 501cache_bypass_hits, cache_bypass_misses 502 Hits and misses for IO that is intended to skip the cache are still counted, 503 but broken out here. 504 505cache_miss_collisions 506 Counts instances where data was going to be inserted into the cache from a 507 cache miss, but raced with a write and data was already present (usually 0 508 since the synchronization for cache misses was rewritten) 509 510Sysfs - cache set 511~~~~~~~~~~~~~~~~~ 512 513Available at /sys/fs/bcache/<cset-uuid> 514 515average_key_size 516 Average data per key in the btree. 517 518bdev<0..n> 519 Symlink to each of the attached backing devices. 520 521block_size 522 Block size of the cache devices. 523 524btree_cache_size 525 Amount of memory currently used by the btree cache 526 527bucket_size 528 Size of buckets 529 530cache<0..n> 531 Symlink to each of the cache devices comprising this cache set. 532 533cache_available_percent 534 Percentage of cache device which doesn't contain dirty data, and could 535 potentially be used for writeback. This doesn't mean this space isn't used 536 for clean cached data; the unused statistic (in priority_stats) is typically 537 much lower. 538 539clear_stats 540 Clears the statistics associated with this cache 541 542dirty_data 543 Amount of dirty data is in the cache (updated when garbage collection runs). 544 545flash_vol_create 546 Echoing a size to this file (in human readable units, k/M/G) creates a thinly 547 provisioned volume backed by the cache set. 548 549io_error_halflife, io_error_limit 550 These determines how many errors we accept before disabling the cache. 551 Each error is decayed by the half life (in # ios). If the decaying count 552 reaches io_error_limit dirty data is written out and the cache is disabled. 553 554journal_delay_ms 555 Journal writes will delay for up to this many milliseconds, unless a cache 556 flush happens sooner. Defaults to 100. 557 558root_usage_percent 559 Percentage of the root btree node in use. If this gets too high the node 560 will split, increasing the tree depth. 561 562stop 563 Write to this file to shut down the cache set - waits until all attached 564 backing devices have been shut down. 565 566tree_depth 567 Depth of the btree (A single node btree has depth 0). 568 569unregister 570 Detaches all backing devices and closes the cache devices; if dirty data is 571 present it will disable writeback caching and wait for it to be flushed. 572 573Sysfs - cache set internal 574~~~~~~~~~~~~~~~~~~~~~~~~~~ 575 576This directory also exposes timings for a number of internal operations, with 577separate files for average duration, average frequency, last occurrence and max 578duration: garbage collection, btree read, btree node sorts and btree splits. 579 580active_journal_entries 581 Number of journal entries that are newer than the index. 582 583btree_nodes 584 Total nodes in the btree. 585 586btree_used_percent 587 Average fraction of btree in use. 588 589bset_tree_stats 590 Statistics about the auxiliary search trees 591 592btree_cache_max_chain 593 Longest chain in the btree node cache's hash table 594 595cache_read_races 596 Counts instances where while data was being read from the cache, the bucket 597 was reused and invalidated - i.e. where the pointer was stale after the read 598 completed. When this occurs the data is reread from the backing device. 599 600trigger_gc 601 Writing to this file forces garbage collection to run. 602 603Sysfs - Cache device 604~~~~~~~~~~~~~~~~~~~~ 605 606Available at /sys/block/<cdev>/bcache 607 608block_size 609 Minimum granularity of writes - should match hardware sector size. 610 611btree_written 612 Sum of all btree writes, in (kilo/mega/giga) bytes 613 614bucket_size 615 Size of buckets 616 617cache_replacement_policy 618 One of either lru, fifo or random. 619 620freelist_percent 621 Size of the freelist as a percentage of nbuckets. Can be written to to 622 increase the number of buckets kept on the freelist, which lets you 623 artificially reduce the size of the cache at runtime. Mostly for testing 624 purposes (i.e. testing how different size caches affect your hit rate). 625 626io_errors 627 Number of errors that have occurred, decayed by io_error_halflife. 628 629metadata_written 630 Sum of all non data writes (btree writes and all other metadata). 631 632nbuckets 633 Total buckets in this cache 634 635priority_stats 636 Statistics about how recently data in the cache has been accessed. 637 This can reveal your working set size. Unused is the percentage of 638 the cache that doesn't contain any data. Metadata is bcache's 639 metadata overhead. Average is the average priority of cache buckets. 640 Next is a list of quantiles with the priority threshold of each. 641 642written 643 Sum of all data that has been written to the cache; comparison with 644 btree_written gives the amount of write inflation in bcache. 645