[Bcache v15 00/16]
Subsystems (15)
v15 cover [Bcache v15 00/16]
bcache: a cache for arbitrary block devices using an SSD.
Short overview:
Bcache does both writethrough and writeback caching. It presents itself as a new block device, a bit like say md. You can cache an arbitrary number of block devices with a single cache device, and attach and detach things at runtime - it's quite flexible.
It's very fast. It uses a b+ tree for the index, along with a journal to coalesce index updates, and a bunch of other cool tricks like auxiliary binary search trees with software floating point keys for searching within btree nodes.
CURRENT STATUS:
Bcache is solid, production ready code. I think there's still a bug or two related to bcache + dm, but nothing I've been able to reproduce. I'm running it on this machine in writeback mode for awhile now - subjectively, it's just as good as running on an SSD. It's been running on various servers in production, I have no clue how many.
This patch series is based on my block_stuff branch, available atgit://evilpiepirate.org/~kent/linux-bcache.org
http://evilpiepirate.org/git/linux-bcache.git/log/?h=block_stuff
and that branch is in turn based on v3.5.
CHANGES SINCE v14:
Almost 500 lines of new code documentation, most of it high level design docs. Start at the top of bcache.h - most of the header files now start with some high level documentation, and alloc.c since it doesn't have its own header.
Suggestions on what else to document would be most welcome. I think the high level design documentation is in pretty good shape (except perhaps for non btree metadata stuff), but I've started on function level documentation. So, if there's a function and you can't figure out wtf it does, please let me know.
Incorporated Joe Perches' feedback.
CHANGES SINCE v13:
I lost the cover letter I was writing just as I was about to send out v14, and in a fit of frustration sent it out with just the shortlog. Anyways, v14 had all a ton of review feedback incorporated; if there's anything anyone pointed out that hasn't been fixed or responded to I probably missed it.
Incorporated feedback from Tejun, Vivek, and Joe Perches'. Though it's quite possible I missed some bits.
I also refactored a lot of the trickiest code; the refcounting and flow control in request.c (around request_write) in particular is massively improved, and I changed the way bio splits are refcounted, which is now much more consistent. The btree in memory cache code was also significantly improved.
I rebased onto my patches for the generic block layer that make generic_make_request() take arbitrary sized bios, which cleaned up a lot of bcache code and let me delete like 400 lines of code from bcache.
Merged in the moving garbage collector. It needs more work (needs generational garbage collection, rate limiting) but it does currently work. It's for flash only volumes, and ultimately for making bcache a full blown FTL.
TODO/KNOWN ISSUES (Incomplete):
* More documentation
* My patch for adding human readable units to vsnprintf() isn't going to work because of gcc printf typechecking. Probably going to end up reverting that. The current code works fine, gcc just complains a lot.
* I need to get better at responding to emails.
Kent Overstreet (16):
Revert "rw_semaphore: remove up/down_read_non_owner" Fix ratelimit macro to compile in c99 mode Export get_random_int()
Export blk_fill_rwbs()
Export __lockdep_no_validate__
Add human-readable units modifier to vsnprintf() Closures
bcache: Generic utility code
bcache: Documentation, and changes to generic code
bcache: Superblock/initialization/sysfs code
bcache: Core btree code
bcache: Bset code (lookups within a btree node)
bcache: Journalling
bcache: Request, io and allocation code
bcache: Writeback, copying garbage collection
bcache: Debug and tracing code
Documentation/ABI/testing/sysfs-block-bcache | 156 ++ Documentation/bcache.txt | 255 +++ drivers/char/random.c | 1 + drivers/md/Kconfig | 2 + drivers/md/Makefile | 1 + drivers/md/bcache/Kconfig | 41 + drivers/md/bcache/Makefile | 14 + drivers/md/bcache/alloc.c | 615 +++++++ drivers/md/bcache/bcache.h | 1142 ++++++++++++ drivers/md/bcache/bset.c | 1165 ++++++++++++ drivers/md/bcache/bset.h | 372 ++++ drivers/md/bcache/btree.c | 2508 ++++++++++++++++++++++++++ drivers/md/bcache/btree.h | 423 +++++ drivers/md/bcache/debug.c | 576 ++++++ drivers/md/bcache/debug.h | 54 + drivers/md/bcache/io.c | 136 ++ drivers/md/bcache/journal.c | 703 ++++++++ drivers/md/bcache/journal.h | 159 ++ drivers/md/bcache/movinggc.c | 245 +++ drivers/md/bcache/request.c | 1366 ++++++++++++++ drivers/md/bcache/request.h | 61 + drivers/md/bcache/stats.c | 245 +++ drivers/md/bcache/stats.h | 58 + drivers/md/bcache/super.c | 1992 ++++++++++++++++++++ drivers/md/bcache/sysfs.c | 812 +++++++++ drivers/md/bcache/sysfs.h | 91 + drivers/md/bcache/trace.c | 26 + drivers/md/bcache/util.c | 392 ++++ drivers/md/bcache/util.h | 606 +++++++ drivers/md/bcache/writeback.c | 405 +++++ include/linux/cgroup_subsys.h | 6 + include/linux/closure.h | 88 +- include/linux/ratelimit.h | 2 +- include/linux/rwsem.h | 10 + include/linux/sched.h | 4 + include/trace/events/bcache.h | 271 +++ kernel/fork.c | 4 + kernel/lockdep.c | 1 + kernel/rwsem.c | 16 + kernel/trace/blktrace.c | 1 + lib/closure.c | 26 +- lib/vsprintf.c | 24 +- 42 files changed, 15022 insertions(+), 53 deletions(-) create mode 100644 Documentation/ABI/testing/sysfs-block-bcache create mode 100644 Documentation/bcache.txt create mode 100644 drivers/md/bcache/Kconfig create mode 100644 drivers/md/bcache/Makefile create mode 100644 drivers/md/bcache/alloc.c create mode 100644 drivers/md/bcache/bcache.h create mode 100644 drivers/md/bcache/bset.c create mode 100644 drivers/md/bcache/bset.h create mode 100644 drivers/md/bcache/btree.c create mode 100644 drivers/md/bcache/btree.h create mode 100644 drivers/md/bcache/debug.c create mode 100644 drivers/md/bcache/debug.h create mode 100644 drivers/md/bcache/io.c create mode 100644 drivers/md/bcache/journal.c create mode 100644 drivers/md/bcache/journal.h create mode 100644 drivers/md/bcache/movinggc.c create mode 100644 drivers/md/bcache/request.c create mode 100644 drivers/md/bcache/request.h create mode 100644 drivers/md/bcache/stats.c create mode 100644 drivers/md/bcache/stats.h create mode 100644 drivers/md/bcache/super.c create mode 100644 drivers/md/bcache/sysfs.c create mode 100644 drivers/md/bcache/sysfs.h create mode 100644 drivers/md/bcache/trace.c create mode 100644 drivers/md/bcache/util.c create mode 100644 drivers/md/bcache/util.h create mode 100644 drivers/md/bcache/writeback.c create mode 100644 include/trace/events/bcache.h
Signature · 1 line
1.7.7.3
PATCH v15 1/16 Revert "rw_semaphore: remove up/down_read_non_owner"
This reverts commit 11b80f459adaf91a712f95e7734a17655a36bf30.
--- include/linux/rwsem.h | 10 ++++++++++ kernel/rwsem.c | 16 ++++++++++++++++ 2 files changed, 26 insertions(+), 0 deletions(-)
include/linux/rwsem.h +10 -0
@@ -125,9 +125,19 @@ extern void downgrade_write(struct rw_semaphore *sem);*/ extern void down_read_nested (struct rw_semaphore *sem,int subclass);extern void down_write_nested (struct rw_semaphore *sem,int subclass); +/* +* Take/release a lock when not the owner will release it. +* +* [ This API should be avoided as much as possible - the +* proper abstraction for this case is completions. ] +*/ +extern void down_read_non_owner (struct rw_semaphore *sem); +extern void up_read_non_owner (struct rw_semaphore *sem);#else # define down_read_nested (sem, subclass) down_read(sem)# define down_write_nested (sem, subclass) down_write(sem) +# define down_read_non_owner (sem) down_read(sem) +# define up_read_non_owner (sem) up_read(sem)#endif #endif /* _LINUX_RWSEM_H */
kernel/rwsem.c +16 -0
@@ -116,6 +116,15 @@ void down_read_nested(struct rw_semaphore *sem, int subclass)EXPORT_SYMBOL (down_read_nested); +void down_read_non_owner (struct rw_semaphore *sem) +{ +might_sleep (); + +__down_read (sem); +} + +EXPORT_SYMBOL (down_read_non_owner); +void down_write_nested (struct rw_semaphore *sem,int subclass) {might_sleep ();
@@ -126,6 +135,13 @@ void down_write_nested(struct rw_semaphore *sem, int subclass)EXPORT_SYMBOL (down_write_nested); +void up_read_non_owner (struct rw_semaphore *sem) +{ +__up_read (sem); +} + +EXPORT_SYMBOL (up_read_non_owner); +#endif
Signature · 1 line
1.7.7.3
PATCH v15 2/16 Fix ratelimit macro to compile in c99 mode
In reply to Kent Overstreet--- include/linux/ratelimit.h | 2 +- 1 files changed, 1 insertions(+), 1 deletions(-)
include/linux/ratelimit.h +1 -1
@@ -20,7 +20,7 @@ struct ratelimit_state {#define DEFINE_RATELIMIT_STATE (name, interval_init, burst_init) \ \ struct ratelimit_state name = { \ - .lock = __RAW_SPIN_LOCK_UNLOCKED(name.lock), \ + .lock = __RAW_SPIN_LOCK_INITIALIZER(name.lock),\ .interval = interval_init, \ .burst = burst_init, \ }
Signature · 1 line
1.7.7.3
PATCH v15 3/16 Export get_random_int()
In reply to Kent Overstreet--- drivers/char/random.c | 1 + 1 files changed, 1 insertions(+), 0 deletions(-)
drivers/char/random.c +1 -0
@@ -1362,6 +1362,7 @@ unsigned int get_random_int(void)return ret; } +EXPORT_SYMBOL (get_random_int);/* * randomize_range() returns a start address such that
Signature · 1 line
1.7.7.3
PATCH v15 4/16 Export blk_fill_rwbs()
In reply to Kent OverstreetExported so it can be used by bcache's tracepoints
--- kernel/trace/blktrace.c | 1 + 1 files changed, 1 insertions(+), 0 deletions(-)
kernel/trace/blktrace.c +1 -0
@@ -1806,6 +1806,7 @@ void blk_fill_rwbs(char *rwbs, u32 rw, int bytes) rwbs[i] = '\0'; } +EXPORT_SYMBOL_GPL (blk_fill_rwbs);#endif /* CONFIG_EVENT_TRACING */
Signature · 1 line
1.7.7.3
PATCH v15 5/16 Export __lockdep_no_validate__
In reply to Kent OverstreetBcache's garbage collection needs a way around lockdep; this might not be the best way but it'll do for the moment.
--- kernel/lockdep.c | 1 + 1 files changed, 1 insertions(+), 0 deletions(-)
kernel/lockdep.c +1 -0
@@ -2997,6 +2997,7 @@ void lockdep_init_map(struct lockdep_map *lock, const char *name,EXPORT_SYMBOL_GPL (lockdep_init_map);struct lock_class_key __lockdep_no_validate__; +EXPORT_SYMBOL_GPL (__lockdep_no_validate__);/* * This gets called for every mutex_lock*()/spin_lock*() operation.
Signature · 1 line
1.7.7.3
PATCH v15 6/16 Add human-readable units modifier to vsnprintf()
In reply to Kent Overstreet--- lib/vsprintf.c | 24 +++++++++++++++++++++++- 1 files changed, 23 insertions(+), 1 deletions(-)
lib/vsprintf.c +23 -1
@@ -338,6 +338,7 @@ int num_to_str(char *buf, int size, unsigned long long num)#define LEFT 16/* left justified */ #define SMALL 32/* use lowercase in hex (must be 32 == 0x20) */ #define SPECIAL 64/* prefix hex with "0x", octal with "0" */ +#define HUNITS 128/* Human readable units, i.e. k/M/G/T */ enum format_type {FORMAT_TYPE_NONE ,/* Just a string part */
@@ -377,6 +378,7 @@ char *number(char *buf, char *end, unsigned long long num, {/* we are called with base 8, 10 or 16, only, thus don't need "G..." */ static const char digits[16 ] ="0123456789ABCDEF" ;/* "GHIJKLMNOPQRSTUVWXYZ"; */ +static const char units[] ="?kMGTPEZY" ;char tmp[66 ];char sign;
@@ -431,7 +433,26 @@ char *number(char *buf, char *end, unsigned long long num, num >>= shift; }while (num); }else {/* base 10 */ - i =put_dec (tmp, num) - tmp; +if (spec.flags &HUNITS ) { +int u, rem =0 ; + +for (u =0 ; num >=1024 ; u++) { + rem = num & ~(~0 <<10 ); + num >>=10 ; + } + +if (u) { + tmp[i++] = units[u]; + +if (num <100 ) { + rem /=100 ; + i =put_dec (tmp + i, rem) - tmp; + tmp[i++] ='.' ; + } + } + } + + i =put_dec (tmp + i, num) - tmp; }/* printing 100 using %2d gives "100", not "00" */
@@ -1127,6 +1148,7 @@ int format_decode(const char *fmt, struct printf_spec *spec)case ' ' : spec->flags |=SPACE ;break ;case '#' : spec->flags |=SPECIAL ;break ;case '0' : spec->flags |=ZEROPAD ;break ; +case 'h' : spec->flags |=HUNITS ;break ;default : found = false; }
Signature · 1 line
1.7.7.3
PATCH v15 7/16 Closures
In reply to Kent OverstreetClosures are asynchronous refcounty things based on workqueues, used extensively in bcache.
--- include/linux/closure.h | 88 ++++++++++++++++++++++++++--------------------- lib/closure.c | 26 +++++++------ 2 files changed, 63 insertions(+), 51 deletions(-)
include/linux/closure.h +49 -39
@@ -160,7 +160,7 @@* enough: * struct closure_with_timer; * -* This gives you access to closure_sleep(). It takes a refcount for a specified +* This gives you access to closure_delay(). It takes a refcount for a specified * number of jiffies - you could then call closure_sync() (for a slightly * convoluted version of msleep()) or continue_at() - which gives you the same * effect as using a delayed work item, except you can reuse the work_struct
@@ -187,22 +187,6 @@ enum closure_type { MAX_CLOSURE_TYPE = 3, }; -enum closure_state_bits { -CLOSURE_REMAINING_END =20 , -CLOSURE_BLOCKING_GUARD =20 , -CLOSURE_BLOCKING_BIT =21 , -CLOSURE_WAITING_GUARD =22 , -CLOSURE_WAITING_BIT =23 , -CLOSURE_SLEEPING_GUARD =24 , -CLOSURE_SLEEPING_BIT =25 , -CLOSURE_TIMER_GUARD =26 , -CLOSURE_TIMER_BIT =27 , -CLOSURE_RUNNING_GUARD =28 , -CLOSURE_RUNNING_BIT =29 , -CLOSURE_STACK_GUARD =30 , -CLOSURE_STACK_BIT =31 , -}; -enum closure_state {/* * CLOSURE_BLOCKING: Causes closure_wait_event() to block, instead of
@@ -234,23 +218,21 @@ enum closure_state {* closure with this flag set */ -CLOSURE_BLOCKING = (1 <<CLOSURE_BLOCKING_BIT ), -CLOSURE_WAITING = (1 <<CLOSURE_WAITING_BIT ), -CLOSURE_SLEEPING = (1 <<CLOSURE_SLEEPING_BIT ), -CLOSURE_TIMER = (1 <<CLOSURE_TIMER_BIT ), -CLOSURE_RUNNING = (1 <<CLOSURE_RUNNING_BIT ), - CLOSURE_STACK = (1 << CLOSURE_STACK_BIT), +CLOSURE_BITS_START = (1 <<19 ), +CLOSURE_DESTRUCTOR = (1 <<19 ), +CLOSURE_BLOCKING = (1 <<21 ), +CLOSURE_WAITING = (1 <<23 ), +CLOSURE_SLEEPING = (1 <<25 ), +CLOSURE_TIMER = (1 <<27 ), +CLOSURE_RUNNING = (1 <<29 ), + CLOSURE_STACK = (1 << 31), };#define CLOSURE_GUARD_MASK \ - ((1 << CLOSURE_BLOCKING_GUARD)| \ - (1 << CLOSURE_WAITING_GUARD)| \ - (1 << CLOSURE_SLEEPING_GUARD)| \ - (1 << CLOSURE_TIMER_GUARD)| \ - (1 << CLOSURE_RUNNING_GUARD)| \ - (1 << CLOSURE_STACK_GUARD)) - -#define CLOSURE_REMAINING_MASK ((1 << CLOSURE_REMAINING_END) - 1) + ((CLOSURE_DESTRUCTOR|CLOSURE_BLOCKING|CLOSURE_WAITING| \ + CLOSURE_SLEEPING|CLOSURE_TIMER|CLOSURE_RUNNING|CLOSURE_STACK) << 1) + +#define CLOSURE_REMAINING_MASK (CLOSURE_BITS_START - 1)#define CLOSURE_REMAINING_INITIALIZER (1|CLOSURE_RUNNING) struct closure {
@@ -324,7 +306,7 @@ void __closure_lock(struct closure *cl, struct closure *parent, struct closure_waitlist *wait_list);void do_closure_timer_init (struct closure *cl); -bool __closure_sleep (struct closure *cl,unsigned long delay, +bool __closure_delay (struct closure *cl,unsigned long delay,struct timer_list *timer);void __closure_flush (struct closure *cl,struct timer_list *timer);void __closure_flush_sync (struct closure *cl,struct timer_list *timer);
@@ -478,7 +460,7 @@ do { \__closure_lock (__to_internal_closure (cl), parent, &(cl)->wait)/** -* closure_sleep() - asynchronous sleep +* closure_delay() - delay some number of jiffies * @cl: the closure that will sleep * @delay: the delay in jiffies *
@@ -486,8 +468,8 @@ do { \* be used to have a function run after a delay with continue_at(), or * closure_sync() may be used for a convoluted version of msleep(). */ -#define closure_sleep (cl, delay) \ - __closure_sleep(__to_internal_closure(cl), delay, &(cl)->timer) +#define closure_delay (cl, delay) \ + __closure_delay(__to_internal_closure(cl), delay, &(cl)->timer)#define closure_flush (cl) \ __closure_flush(__to_internal_closure(cl), &(cl)->timer)
@@ -638,21 +620,49 @@ static inline void closure_wake_up(struct closure_waitlist *list)static inline void set_closure_fn (struct closure *cl,closure_fn *fn,struct workqueue_struct *wq) { +BUG_ON (object_is_on_stack (cl)); +closure_set_ip (cl); cl->fn = fn; cl->wq = wq;/* between atomic_dec() in closure_put() */ smp_mb__before_atomic_dec (); } -#define continue_at (_cl, _fn, _wq, ...) \ +#define continue_at (_cl, _fn, _wq) \ do { \ - BUG_ON(!(_cl) || object_is_on_stack(_cl)); \ - closure_set_ip(_cl); \ set_closure_fn(_cl, _fn, _wq); \ closure_sub(_cl, CLOSURE_RUNNING + 1); \ - return __VA_ARGS__; \ + return; \ } while (0)#define closure_return (_cl) continue_at((_cl), NULL, NULL) +#define continue_at_nobarrier (_cl, _fn, _wq) \ +do { \ + set_closure_fn(_cl, _fn, _wq); \ + closure_queue(cl); \ + return; \ +} while (0) + +#define closure_return_with_destructor (_cl, _destructor) \ +do { \ + set_closure_fn(_cl, _destructor, NULL); \ + closure_sub(_cl, CLOSURE_RUNNING - CLOSURE_DESTRUCTOR + 1); \ + return; \ +} while (0) + +static inline void closure_call (closure_fn fn,struct closure *cl, +struct closure *parent) +{ +closure_init (cl, parent); +fn (cl); +} + +static inline void closure_trylock_call (closure_fn fn,struct closure *cl, +struct closure *parent) +{ +if (closure_trylock (cl, parent)) +fn (cl); +} +#endif /* _LINUX_CLOSURE_H */
lib/closure.c +14 -12
@@ -44,20 +44,19 @@ static struct timer_list *closure_timer(struct closure *cl) } } -static void closure_put_after_sub (struct closure *cl,int r) +static inline void closure_put_after_sub (struct closure *cl,int flags) { -int rem = r &CLOSURE_REMAINING_MASK ; +int r = flags &CLOSURE_REMAINING_MASK ; -BUG_ON (r &CLOSURE_GUARD_MASK ); -/* CLOSURE_BLOCK is the only flag that's allowed when r hits 0 */ -BUG_ON (!rem && (r & ~CLOSURE_BLOCKING )); +BUG_ON (flags &CLOSURE_GUARD_MASK ); +BUG_ON (!r && (flags & ~(CLOSURE_DESTRUCTOR |CLOSURE_BLOCKING )));/* Must deliver precisely one wakeup */ -if (rem ==1 && (r &CLOSURE_SLEEPING )) +if (r ==1 && (flags &CLOSURE_SLEEPING ))wake_up_process (cl->task); -if (!rem) { -if (cl->fn) { +if (!r) { +if (cl->fn && !(flags &CLOSURE_DESTRUCTOR )) {/* CLOSURE_BLOCKING might be set - clear it */ atomic_set (&cl->remaining,CLOSURE_REMAINING_INITIALIZER );
@@ -73,6 +72,9 @@ static void closure_put_after_sub(struct closure *cl, int r)if (wait)closure_wake_up (wait); +if (cl->fn) + cl->fn (cl); +if (parent)closure_put (parent); }
@@ -205,7 +207,7 @@ void __closure_lock(struct closure *cl, struct closure *parent, }EXPORT_SYMBOL_GPL (__closure_lock); -static void closure_sleep_timer_fn (unsigned long data) +static void closure_delay_timer_fn (unsigned long data) {struct closure *cl = (struct closure *) data;closure_sub (cl,CLOSURE_TIMER +1 );
@@ -217,11 +219,11 @@ void do_closure_timer_init(struct closure *cl)init_timer (timer); timer->data = (unsigned long ) cl; - timer->function = closure_sleep_timer_fn; + timer->function = closure_delay_timer_fn; }EXPORT_SYMBOL_GPL (do_closure_timer_init); -bool __closure_sleep (struct closure *cl,unsigned long delay, +bool __closure_delay (struct closure *cl,unsigned long delay,struct timer_list *timer) {if (atomic_read (&cl->remaining) &CLOSURE_TIMER )
@@ -235,7 +237,7 @@ bool __closure_sleep(struct closure *cl, unsigned long delay,add_timer (timer);return true; } -EXPORT_SYMBOL_GPL (__closure_sleep); +EXPORT_SYMBOL_GPL (__closure_delay);void __closure_flush (struct closure *cl,struct timer_list *timer) {
Signature · 1 line
1.7.7.3
Re: [Bcache v15 07/16] Closures
I screwed up this patch - here's the correct one:
commit f2f374ca1fedf912dab186f2e2ccd1fd82486acc
Author: Kent Overstreet <[email protected]> Date: Fri Jan 13 16:14:05 2012 -0800
Closures
Asynchronous refcounty thingies; they embed a refcount and a work struct. Extensive documentation follows in include/linux/closure.h
include/linux/closure.h new file +668 -0
@@ -0,0 +1,668 @@ +#ifndef _LINUX_CLOSURE_H +#define _LINUX_CLOSURE_H + +#include <linux/llist.h> +#include <linux/sched.h> +#include <linux/workqueue.h> + +/* +* Closure is perhaps the most overused and abused term in computer science, but +* since I've been unable to come up with anything better you're stuck with it +* again. +* +* What are closures? +* +* They embed a refcount. The basic idea is they count "things that are in +* progress" - in flight bios, some other thread that's doing something else - +* anything you might want to wait on. +* +* The refcount may be manipulated with closure_get() and closure_put(). +* closure_put() is where many of the interesting things happen, when it causes +* the refcount to go to 0. +* +* Closures can be used to wait on things both synchronously and asynchronously, +* and synchronous and asynchronous use can be mixed without restriction. To +* wait synchronously, use closure_sync() - you will sleep until your closure's +* refcount hits 1. +* +* To wait asynchronously, use +* continue_at(cl, next_function, workqueue); +* +* passing it, as you might expect, the function to run when nothing is pending +* and the workqueue to run that function out of. +* +* continue_at() also, critically, is a macro that returns the calling function. +* There's good reason for this. +* +* To use safely closures asynchronously, they must always have a refcount while +* they are running owned by the thread that is running them. Otherwise, suppose +* you submit some bios and wish to have a function run when they all complete: +* +* foo_endio(struct bio *bio, int error) +* { +* closure_put(cl); +* } +* +* closure_init(cl); +* +* do_stuff(); +* closure_get(cl); +* bio1->bi_endio = foo_endio; +* bio_submit(bio1); +* +* do_more_stuff(); +* closure_get(cl); +* bio2->bi_endio = foo_endio; +* bio_submit(bio2); +* +* continue_at(cl, complete_some_read, system_wq); +* +* If closure's refcount started at 0, complete_some_read() could run before the +* second bio was submitted - which is almost always not what you want! More +* importantly, it wouldn't be possible to say whether the original thread or +* complete_some_read()'s thread owned the closure - and whatever state it was +* associated with! +* +* So, closure_init() initializes a closure's refcount to 1 - and when a +* closure_fn is run, the refcount will be reset to 1 first. +* +* Then, the rule is - if you got the refcount with closure_get(), release it +* with closure_put() (i.e, in a bio->bi_endio function). If you have a refcount +* on a closure because you called closure_init() or you were run out of a +* closure - _always_ use continue_at(). Doing so consistently will help +* eliminate an entire class of particularly pernicious races. +* +* For a closure to wait on an arbitrary event, we need to introduce waitlists: +* +* struct closure_waitlist list; +* closure_wait_event(list, cl, condition); +* closure_wake_up(wait_list); +* +* These work analagously to wait_event() and wake_up() - except that instead of +* operating on the current thread (for wait_event()) and lists of threads, they +* operate on an explicit closure and lists of closures. +* +* Because it's a closure we can now wait either synchronously or +* asynchronously. closure_wait_event() returns the current value of the +* condition, and if it returned false continue_at() or closure_sync() can be +* used to wait for it to become true. +* +* It's useful for waiting on things when you can't sleep in the context in +* which you must check the condition (perhaps a spinlock held, or you might be +* beneath generic_make_request() - in which case you can't sleep on IO). +* +* closure_wait_event() will wait either synchronously or asynchronously, +* depending on whether the closure is in blocking mode or not. You can pick a +* mode explicitly with closure_wait_event_sync() and +* closure_wait_event_async(), which do just what you might expect. +* +* Lastly, you might have a wait list dedicated to a specific event, and have no +* need for specifying the condition - you just want to wait until someone runs +* closure_wake_up() on the appropriate wait list. In that case, just use +* closure_wait(). It will return either true or false, depending on whether the +* closure was already on a wait list or not - a closure can only be on one wait +* list at a time. +* +* Parents: +* +* closure_init() takes two arguments - it takes the closure to initialize, and +* a (possibly null) parent. +* +* If parent is non null, the new closure will have a refcount for its lifetime; +* a closure is considered to be "finished" when its refcount hits 0 and the +* function to run is null. Hence +* +* continue_at(cl, NULL, NULL); +* +* returns up the (spaghetti) stack of closures, precisely like normal return +* returns up the C stack. continue_at() with non null fn is better thought of +* as doing a tail call. +* +* All this implies that a closure should typically be embedded in a particular +* struct (which its refcount will normally control the lifetime of), and that +* struct can very much be thought of as a stack frame. +* +* Locking: +* +* Closures are based on work items but they can be thought of as more like +* threads - in that like threads and unlike work items they have a well +* defined lifetime; they are created (with closure_init()) and eventually +* complete after a continue_at(cl, NULL, NULL). +* +* Suppose you've got some larger structure with a closure embedded in it that's +* used for periodically doing garbage collection. You only want one garbage +* collection happening at a time, so the natural thing to do is protect it with +* a lock. However, it's difficult to use a lock protecting a closure correctly +* because the unlock should come after the last continue_to() (additionally, if +* you're using the closure asynchronously a mutex won't work since a mutex has +* to be unlocked by the same process that locked it). +* +* So to make it less error prone and more efficient, we also have the ability +* to use closures as locks: +* +* closure_init_unlocked(); +* closure_trylock(); +* +* That's all we need for trylock() - the last closure_put() implicitly unlocks +* it for you. But for closure_lock(), we also need a wait list: +* +* struct closure_with_waitlist frobnicator_cl; +* +* closure_init_unlocked(&frobnicator_cl); +* closure_lock(&frobnicator_cl); +* +* A closure_with_waitlist embeds a closure and a wait list - much like struct +* delayed_work embeds a work item and a timer_list. The important thing is, use +* it exactly like you would a regular closure and closure_put() will magically +* handle everything for you. +* +* We've got closures that embed timers, too. They're called, appropriately +* enough: +* struct closure_with_timer; +* +* This gives you access to closure_delay(). It takes a refcount for a specified +* number of jiffies - you could then call closure_sync() (for a slightly +* convoluted version of msleep()) or continue_at() - which gives you the same +* effect as using a delayed work item, except you can reuse the work_struct +* already embedded in struct closure. +* +* Lastly, there's struct closure_with_waitlist_and_timer. It does what you +* probably expect, if you happen to need the features of both. (You don't +* really want to know how all this is implemented, but if I've done my job +* right you shouldn't have to care). +*/ + +struct closure ; +typedef void (closure_fn ) (struct closure *); + +struct closure_waitlist { +struct llist_head list; +}; + +enum closure_type { + TYPE_closure =0 , + TYPE_closure_with_waitlist =1 , + TYPE_closure_with_timer =2 , + TYPE_closure_with_waitlist_and_timer =3 , +MAX_CLOSURE_TYPE =3 , +}; + +enum closure_state { +/* +* CLOSURE_BLOCKING: Causes closure_wait_event() to block, instead of +* waiting asynchronously +* +* CLOSURE_WAITING: Set iff the closure is on a waitlist. Must be set by +* the thread that owns the closure, and cleared by the thread that's +* waking up the closure. +* +* CLOSURE_SLEEPING: Must be set before a thread uses a closure to sleep +* - indicates that cl->task is valid and closure_put() may wake it up. +* Only set or cleared by the thread that owns the closure. +* +* CLOSURE_TIMER: Analagous to CLOSURE_WAITING, indicates that a closure +* has an outstanding timer. Must be set by the thread that owns the +* closure, and cleared by the timer function when the timer goes off. +* +* The rest are for debugging and don't affect behaviour: +* +* CLOSURE_RUNNING: Set when a closure is running (i.e. by +* closure_init() and when closure_put() runs then next function), and +* must be cleared before remaining hits 0. Primarily to help guard +* against incorrect usage and accidentally transferring references. +* continue_at() and closure_return() clear it for you, if you're doing +* something unusual you can use closure_set_dead() which also helps +* annotate where references are being transferred. +* +* CLOSURE_STACK: Sanity check - remaining should never hit 0 on a +* closure with this flag set +*/ + +CLOSURE_BITS_START = (1 <<19 ), +CLOSURE_DESTRUCTOR = (1 <<19 ), +CLOSURE_BLOCKING = (1 <<21 ), +CLOSURE_WAITING = (1 <<23 ), +CLOSURE_SLEEPING = (1 <<25 ), +CLOSURE_TIMER = (1 <<27 ), +CLOSURE_RUNNING = (1 <<29 ), +CLOSURE_STACK = (1 <<31 ), +}; + +#define CLOSURE_GUARD_MASK \ + ((CLOSURE_DESTRUCTOR|CLOSURE_BLOCKING|CLOSURE_WAITING| \ + CLOSURE_SLEEPING|CLOSURE_TIMER|CLOSURE_RUNNING|CLOSURE_STACK) << 1) + +#define CLOSURE_REMAINING_MASK (CLOSURE_BITS_START - 1) +#define CLOSURE_REMAINING_INITIALIZER (1|CLOSURE_RUNNING) + +struct closure { +union { +struct { +struct workqueue_struct *wq; +struct task_struct *task; +struct llist_node list; +closure_fn *fn; + }; +struct work_struct work; + }; + +struct closure *parent; + +atomic_t remaining; + +enum closure_type type; + +#ifdef CONFIG_DEBUG_CLOSURES +#define CLOSURE_MAGIC_DEAD 0xc054dead +#define CLOSURE_MAGIC_ALIVE 0xc054a11e + +unsigned magic; +struct list_head all; +unsigned long ip; +unsigned long waiting_on; +#endif +}; + +struct closure_with_waitlist { +struct closure cl; +struct closure_waitlist wait; +}; + +struct closure_with_timer { +struct closure cl; +struct timer_list timer; +}; + +struct closure_with_waitlist_and_timer { +struct closure cl; +struct closure_waitlist wait; +struct timer_list timer; +}; + +extern unsigned invalid_closure_type (void ); + +#define __CLOSURE_TYPE (cl, _t) \ + __builtin_types_compatible_p(typeof(cl), struct _t) \ + ? TYPE_ ## _t : \ + +#define __closure_type (cl) \ +( \ + __CLOSURE_TYPE(cl, closure) \ + __CLOSURE_TYPE(cl, closure_with_waitlist) \ + __CLOSURE_TYPE(cl, closure_with_timer) \ + __CLOSURE_TYPE(cl, closure_with_waitlist_and_timer) \ + invalid_closure_type() \ +) + +void closure_sub (struct closure *cl,int v); +void closure_put (struct closure *cl); +void closure_queue (struct closure *cl); +void __closure_wake_up (struct closure_waitlist *list); +bool closure_wait (struct closure_waitlist *list,struct closure *cl); +void closure_sync (struct closure *cl); + +bool closure_trylock (struct closure *cl,struct closure *parent); +void __closure_lock (struct closure *cl,struct closure *parent, +struct closure_waitlist *wait_list); + +void do_closure_timer_init (struct closure *cl); +bool __closure_delay (struct closure *cl,unsigned long delay, +struct timer_list *timer); +void __closure_flush (struct closure *cl,struct timer_list *timer); +void __closure_flush_sync (struct closure *cl,struct timer_list *timer); + +#ifdef CONFIG_DEBUG_CLOSURES + +void closure_debug_create (struct closure *cl); +void closure_debug_destroy (struct closure *cl); + +#else + +static inline void closure_debug_create (struct closure *cl) {} +static inline void closure_debug_destroy (struct closure *cl) {} + +#endif + +static inline void closure_set_ip (struct closure *cl) +{ +#ifdef CONFIG_DEBUG_CLOSURES + cl->ip = _THIS_IP_; +#endif +} + +static inline void closure_set_ret_ip (struct closure *cl) +{ +#ifdef CONFIG_DEBUG_CLOSURES + cl->ip = _RET_IP_; +#endif +} + +static inline void closure_get (struct closure *cl) +{ +#ifdef CONFIG_DEBUG_CLOSURES +BUG_ON ((atomic_inc_return (&cl->remaining) & +CLOSURE_REMAINING_MASK ) <=1 ); +#else +atomic_inc (&cl->remaining); +#endif +} + +static inline void closure_set_stopped (struct closure *cl) +{ +atomic_sub (CLOSURE_RUNNING , &cl->remaining); +} + +static inline bool closure_is_stopped (struct closure *cl) +{ +return !(atomic_read (&cl->remaining) &CLOSURE_RUNNING ); +} + +static inline bool closure_is_unlocked (struct closure *cl) +{ +return atomic_read (&cl->remaining) ==-1 ; +} + +static inline void do_closure_init (struct closure *cl,struct closure *parent, +bool running) +{ +switch (cl->type) { +case TYPE_closure_with_timer: +case TYPE_closure_with_waitlist_and_timer: +do_closure_timer_init (cl); +default : +break ; + } + + cl->parent = parent; +if (parent) +closure_get (parent); + +if (running) { +closure_debug_create (cl); +atomic_set (&cl->remaining,CLOSURE_REMAINING_INITIALIZER ); + }else +atomic_set (&cl->remaining,-1 ); + +closure_set_ip (cl); +} + +/* +* Hack to get at the embedded closure if there is one, by doing an unsafe cast: +* the result of __closure_type() is thrown away, it's used merely for type +* checking. +*/ +#define __to_internal_closure (cl) \ +({ \ + BUILD_BUG_ON(__closure_type(*cl) > MAX_CLOSURE_TYPE); \ + (struct closure *) cl; \ +}) + +#define closure_init_type (cl, parent, running) \ +do { \ + struct closure *_cl = __to_internal_closure(cl); \ + _cl->type = __closure_type(*(cl)); \ + do_closure_init(_cl, parent, running); \ +} while (0) + +/** +* __closure_init() - Initialize a closure, skipping the memset() +* +* May be used instead of closure_init() when memory has already been zeroed. +*/ +#define __closure_init (cl, parent) \ + closure_init_type(cl, parent, true) + +/** +* closure_init() - Initialize a closure, setting the refcount to 1 +* @cl: closure to initialize +* @parent: parent of the new closure. cl will take a refcount on it for its +* lifetime; may be NULL. +*/ +#define closure_init (cl, parent) \ +do { \ + memset((cl), 0, sizeof(*(cl))); \ + __closure_init(cl, parent); \ +} while (0) + +static inline void closure_init_stack (struct closure *cl) +{ +memset (cl,0 ,sizeof (struct closure )); +atomic_set (&cl->remaining,CLOSURE_REMAINING_INITIALIZER | +CLOSURE_BLOCKING |CLOSURE_STACK ); +} + +/** +* closure_init_unlocked() - Initialize a closure but leave it unlocked. +* @cl: closure to initialize +* +* For when the closure will be used as a lock. The closure may not be used +* until after a closure_lock() or closure_trylock(). +*/ +#define closure_init_unlocked (cl) \ +do { \ + memset((cl), 0, sizeof(*(cl))); \ + closure_init_type(cl, NULL, false); \ +} while (0) + +/** +* closure_lock() - lock and initialize a closure. +* @cl: the closure to lock +* @parent: the new parent for this closure +* +* The closure must be of one of the types that has a waitlist (otherwise we +* wouldn't be able to sleep on contention). +* +* @parent has exactly the same meaning as in closure_init(); if non null, the +* closure will take a reference on @parent which will be released when it is +* unlocked. +*/ +#define closure_lock (cl, parent) \ + __closure_lock(__to_internal_closure(cl), parent, &(cl)->wait) + +/** +* closure_delay() - delay some number of jiffies +* @cl: the closure that will sleep +* @delay: the delay in jiffies +* +* Takes a refcount on @cl which will be released after @delay jiffies; this may +* be used to have a function run after a delay with continue_at(), or +* closure_sync() may be used for a convoluted version of msleep(). +*/ +#define closure_delay (cl, delay) \ + __closure_delay(__to_internal_closure(cl), delay, &(cl)->timer) + +#define closure_flush (cl) \ + __closure_flush(__to_internal_closure(cl), &(cl)->timer) + +#define closure_flush_sync (cl) \ + __closure_flush_sync(__to_internal_closure(cl), &(cl)->timer) + +static inline void __closure_end_sleep (struct closure *cl) +{ +__set_current_state (TASK_RUNNING ); + +if (atomic_read (&cl->remaining) &CLOSURE_SLEEPING ) +atomic_sub (CLOSURE_SLEEPING , &cl->remaining); +} + +static inline void __closure_start_sleep (struct closure *cl) +{ +closure_set_ip (cl); + cl->task = current; +set_current_state (TASK_UNINTERRUPTIBLE ); + +if (!(atomic_read (&cl->remaining) &CLOSURE_SLEEPING )) +atomic_add (CLOSURE_SLEEPING , &cl->remaining); +} + +/** +* closure_blocking() - returns true if the closure is in blocking mode. +* +* If a closure is in blocking mode, closure_wait_event() will sleep until the +* condition is true instead of waiting asynchronously. +*/ +static inline bool closure_blocking (struct closure *cl) +{ +return atomic_read (&cl->remaining) &CLOSURE_BLOCKING ; +} + +/** +* set_closure_blocking() - put a closure in blocking mode. +* +* If a closure is in blocking mode, closure_wait_event() will sleep until the +* condition is true instead of waiting asynchronously. +* +* Not thread safe - can only be called by the thread running the closure. +*/ +static inline void set_closure_blocking (struct closure *cl) +{ +if (!closure_blocking (cl)) +atomic_add (CLOSURE_BLOCKING , &cl->remaining); +} + +/* +* Not thread safe - can only be called by the thread running the closure. +*/ +static inline void clear_closure_blocking (struct closure *cl) +{ +if (closure_blocking (cl)) +atomic_sub (CLOSURE_BLOCKING , &cl->remaining); +} + +/** +* closure_wake_up() - wake up all closures on a wait list. +*/ +static inline void closure_wake_up (struct closure_waitlist *list) +{ +smp_mb (); +__closure_wake_up (list); +} + +/* +* Wait on an event, synchronously or asynchronously - analogous to wait_event() +* but for closures. +* +* The loop is oddly structured so as to avoid a race; we must check the +* condition again after we've added ourself to the waitlist. We know if we were +* already on the waitlist because closure_wait() returns false; thus, we only +* schedule or break if closure_wait() returns false. If it returns true, we +* just loop again - rechecking the condition. +* +* The __closure_wake_up() is necessary because we may race with the event +* becoming true; i.e. we see event false -> wait -> recheck condition, but the +* thread that made the event true may have called closure_wake_up() before we +* added ourself to the wait list. +* +* We have to call closure_sync() at the end instead of just +* __closure_end_sleep() because a different thread might've called +* closure_wake_up() before us and gotten preempted before they dropped the +* refcount on our closure. If this was a stack allocated closure, that would be +* bad. +*/ +#define __closure_wait_event (list, cl, condition, _block) \ +({ \ + bool block = _block; \ + typeof(condition) ret; \ + \ + while (1) { \ + ret = (condition); \ + if (ret) { \ + __closure_wake_up(list); \ + if (block) \ + closure_sync(cl); \ + \ + break; \ + } \ + \ + if (block) \ + __closure_start_sleep(cl); \ + \ + if (!closure_wait(list, cl)) { \ + if (!block) \ + break; \ + \ + schedule(); \ + } \ + } \ + \ + ret; \ +}) + +/** +* closure_wait_event() - wait on a condition, synchronously or asynchronously. +* @list: the wait list to wait on +* @cl: the closure that is doing the waiting +* @condition: a C expression for the event to wait for +* +* If the closure is in blocking mode, sleeps until the @condition evaluates to +* true - exactly like wait_event(). +* +* If the closure is not in blocking mode, waits asynchronously; if the +* condition is currently false the @cl is put onto @list and returns. @list +* owns a refcount on @cl; closure_sync() or continue_at() may be used later to +* wait for another thread to wake up @list, which drops the refcount on @cl. +* +* Returns the value of @condition; @cl will be on @list iff @condition was +* false. +* +* closure_wake_up(@list) must be called after changing any variable that could +* cause @condition to become true. +*/ +#define closure_wait_event (list, cl, condition) \ + __closure_wait_event(list, cl, condition, closure_blocking(cl)) + +#define closure_wait_event_async (list, cl, condition) \ + __closure_wait_event(list, cl, condition, false) + +#define closure_wait_event_sync (list, cl, condition) \ + __closure_wait_event(list, cl, condition, true) + +static inline void set_closure_fn (struct closure *cl,closure_fn *fn, +struct workqueue_struct *wq) +{ +BUG_ON (object_is_on_stack (cl)); +closure_set_ip (cl); + cl->fn = fn; + cl->wq = wq; +/* between atomic_dec() in closure_put() */ +smp_mb__before_atomic_dec (); +} + +#define continue_at (_cl, _fn, _wq) \ +do { \ + set_closure_fn(_cl, _fn, _wq); \ + closure_sub(_cl, CLOSURE_RUNNING + 1); \ + return; \ +} while (0) + +#define closure_return (_cl) continue_at((_cl), NULL, NULL) + +#define continue_at_nobarrier (_cl, _fn, _wq) \ +do { \ + set_closure_fn(_cl, _fn, _wq); \ + closure_queue(cl); \ + return; \ +} while (0) + +#define closure_return_with_destructor (_cl, _destructor) \ +do { \ + set_closure_fn(_cl, _destructor, NULL); \ + closure_sub(_cl, CLOSURE_RUNNING - CLOSURE_DESTRUCTOR + 1); \ + return; \ +} while (0) + +static inline void closure_call (closure_fn fn,struct closure *cl, +struct closure *parent) +{ +closure_init (cl, parent); +fn (cl); +} + +static inline void closure_trylock_call (closure_fn fn,struct closure *cl, +struct closure *parent) +{ +if (closure_trylock (cl, parent)) +fn (cl); +} + +#endif /* _LINUX_CLOSURE_H */
lib/Kconfig.debug +8 -0
@@ -411,6 +411,14 @@ config DEBUG_OBJECTS_ENABLE_DEFAULT help Debug objects boot parameter default value +config DEBUG_CLOSURES + bool "Debug closures" + select DEBUG_FS + ---help--- + Keeps all active closures in a linked list and provides a debugfs + interface to list them, which makes it possible to see asynchronous + operations that get stuck. + config DEBUG_SLAB bool "Debug slab memory allocations" depends on DEBUG_KERNEL && SLAB && !KMEMCHECK
lib/Makefile +1 -1
@@ -22,7 +22,7 @@ lib-y += kobject.o klist.o obj-y += bcd.o div64.o sort.o parser.o halfmd4.o debug_locks.o random32.o \ bust_spinlocks.o hexdump.o kasprintf.o bitmap.o scatterlist.o \ string_helpers.o gcd.o lcm.o list_sort.o uuid.o flex_array.o \ - bsearch.o find_last_bit.o find_next_bit.o llist.o + bsearch.o find_last_bit.o find_next_bit.o llist.o closure.o obj-y += kstrtox.o obj-$(CONFIG_TEST_KSTRTOX) += test-kstrtox.o
lib/closure.c new file +346 -0
346 lines not on this page · raw message
Re: [Bcache v15 07/16] Closures
Out of curiosity, have you seen Featherstitch[1]?. Valerie Aurora did a really nice article[2] about it for LWN a ways back.
[1] http://featherstitch.cs.ucla.edu/
[2] https://lwn.net/Articles/354861/
Re: [Bcache v15 07/16] Closures
Quoted 2 lines · Alex Elsayed
Out of curiosity, have you seen Featherstitch[1]?. Valerie Aurora did a really nice article[2] about it for LWN a ways back.
I don't think I had. Not sure if any of it is applicable, but interesting stuff :)
Quoted 9 lines
[1] http://featherstitch.cs.ucla.edu/
[2] https://lwn.net/Articles/354861/--
To unsubscribe from this list: send the line "unsubscribe linux-bcache" in the body of a message to [email protected]
More majordomo info at http://vger.kernel.org/majordomo-info.html
PATCH v15 8/16 bcache: Generic utility code
In reply to Kent OverstreetMuch of this code should be moved out of drivers/block/bcache, but it was originally written for bcache.
--- drivers/md/bcache/util.c | 392 ++++++++++++++++++++++++++++++ drivers/md/bcache/util.h | 606 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 998 insertions(+), 0 deletions(-) create mode 100644 drivers/md/bcache/util.c create mode 100644 drivers/md/bcache/util.h
drivers/md/bcache/util.c new file +392 -0
@@ -0,0 +1,392 @@ +#include <linux/bio.h> +#include <linux/blkdev.h> +#include <linux/ctype.h> +#include <linux/debugfs.h> +#include <linux/module.h> +#include <linux/seq_file.h> +#include <linux/types.h> + +#include "util.h" + +#define simple_strtoint (c, end, base) simple_strtol(c, end, base) +#define simple_strtouint (c, end, base) simple_strtoul(c, end, base) + +#define STRTO_H (name, type) \ +int name ## _h(const char *cp, type *res) \ +{ \ + int u = 0; \ + char *e; \ + type i = simple_ ## name(cp, &e, 10); \ + \ + switch (tolower(*e)) { \ + default: \ + return -EINVAL; \ + case 'y': \ + case 'z': \ + u++; \ + case 'e': \ + u++; \ + case 'p': \ + u++; \ + case 't': \ + u++; \ + case 'g': \ + u++; \ + case 'm': \ + u++; \ + case 'k': \ + u++; \ + if (e++ == cp) \ + return -EINVAL; \ + case '\n': \ + case '\0': \ + if (*e == '\n') \ + e++; \ + } \ + \ + if (*e) \ + return -EINVAL; \ + \ + while (u--) { \ + if ((type) ~0 > 0 && \ + (type) ~0 / 1024 <= i) \ + return -EINVAL; \ + if ((i > 0 && ANYSINT_MAX(type) / 1024 < i) || \ + (i < 0 && -ANYSINT_MAX(type) / 1024 > i)) \ + return -EINVAL; \ + i *= 1024; \ + } \ + \ + *res = i; \ + return 0; \ +} \ +EXPORT_SYMBOL_GPL(name ## _h); + +STRTO_H(strtoint, int) +STRTO_H(strtouint, unsigned int) +STRTO_H(strtoll, long long) +STRTO_H(strtoull, unsigned long long) + +ssize_t snprint_string_list (char *buf,size_t size,const char *const list[], +size_t selected) +{ +char *out = buf; +size_t i; + +for (i =0 ; list[i]; i++) + out +=snprintf (out, buf + size - out, + i == selected ?"[%s] " :"%s " , list[i]); + + out[-1 ] ='\n' ; +return out - buf; +} +EXPORT_SYMBOL_GPL (snprint_string_list); + +ssize_t read_string_list (const char *buf,const char *const list[]) +{ +size_t i; +char *s, *d =kstrndup (buf,PAGE_SIZE -1 ,GFP_KERNEL ); +if (!d) +return -ENOMEM ; + + s =strim (d); + +for (i =0 ; list[i]; i++) +if (!strcmp (list[i], s)) +break ; + +kfree (d); + +if (!list[i]) +return -EINVAL ; + +return i; +} +EXPORT_SYMBOL_GPL (read_string_list); + +bool is_zero (const char *p,size_t n) +{ +size_t i; + +for (i =0 ; i < n; i++) +if (p[i]) +return false; +return true; +} +EXPORT_SYMBOL_GPL (is_zero); + +int parse_uuid (const char *s,char *uuid) +{ +size_t i, j, x; +memset (uuid,0 ,16 ); + +for (i =0 , j =0 ; + i <strspn (s,"-0123456789:ABCDEFabcdef" ) && j <32 ; + i++) { + x = s[i] |32 ; + +switch (x) { + case '0'...'9': + x -='0' ; +break ; + case 'a'...'f': + x -='a' -10 ; +break ; +default : +continue ; + } + +if (!(j &1 )) + x <<=4 ; + uuid[j++ >>1 ] |= x; + } +return i; +} +EXPORT_SYMBOL_GPL (parse_uuid); + +void time_stats_update (struct time_stats *stats,uint64_t start_time) +{ +uint64_t now =local_clock (); +uint64_t duration =time_after64 (now, start_time) + ? now - start_time :0 ; +uint64_t last =time_after64 (now, stats->last) + ? now - stats->last :0 ; + + stats->max_duration =max (stats->max_duration, duration); + +if (stats->last) { +ewma_add (stats->average_duration, duration,8 ,8 ); + +if (stats->average_frequency) +ewma_add (stats->average_frequency, last,8 ,8 ); +else + stats->average_frequency = last <<8 ; + }else { + stats->average_duration = duration <<8 ; + } + + stats->last = now ?:1 ; +} +EXPORT_SYMBOL_GPL (time_stats_update); + +unsigned next_delay (struct ratelimit *d,uint64_t done) +{ +uint64_t now =local_clock (); + + d->next +=div_u64 (done, d->rate); + +return time_after64 (d->next, now) + ?div_u64 (d->next - now,NSEC_PER_SEC /HZ ) + :0 ; +} +EXPORT_SYMBOL_GPL (next_delay); + +#ifdef CONFIG_BCACHE_LATENCY_DEBUG +unsigned latency_warn_ms; +#endif + +#ifdef CONFIG_BCACHE_EDEBUG + +static void check_bio (struct bio *bio) +{ +unsigned i, size =0 ; +struct bio_vec *bv; +struct request_queue *q =bdev_get_queue (bio->bi_bdev); + +BUG_ON (!bio->bi_vcnt); +BUG_ON (!bio->bi_size); + +bio_for_each_segment (bv, bio, i) + size += bv->bv_len; + +BUG_ON (size != bio->bi_size); +BUG_ON (size >queue_max_sectors (q) <<9 ); + +blk_recount_segments (q, bio); +BUG_ON (bio->bi_phys_segments >queue_max_segments (q)); +} + +#else /* EDEBUG */ + +#define check_bio (bio) do {} while (0) + +#endif + +void bio_map (struct bio *bio,void *base) +{ +size_t size = bio->bi_size; +struct bio_vec *bv = bio->bi_io_vec; + +BUG_ON (!bio->bi_size); +BUG_ON (bio->bi_vcnt); + + bv->bv_offset = base ? ((unsigned long ) base) %PAGE_SIZE :0 ; + goto start; + +for (; size; bio->bi_vcnt++, bv++) { + bv->bv_offset =0 ; +start: bv->bv_len =min_t (size_t,PAGE_SIZE - bv->bv_offset, + size); +if (base) { + bv->bv_page =is_vmalloc_addr (base) + ?vmalloc_to_page (base) + :virt_to_page (base); + + base += bv->bv_len; + } + + size -= bv->bv_len; + } +} +EXPORT_SYMBOL_GPL (bio_map); + +int bio_alloc_pages (struct bio *bio,gfp_t gfp) +{ +int i; +struct bio_vec *bv; + +bio_for_each_segment (bv, bio, i) { + bv->bv_page =alloc_page (gfp); +if (!bv->bv_page) { +while (bv-- != bio->bi_io_vec + bio->bi_idx) +__free_page (bv->bv_page); +return -ENOMEM ; + } + } + +return 0 ; +} +EXPORT_SYMBOL_GPL (bio_alloc_pages); + +/* +* Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group (Any +* use permitted, subject to terms of PostgreSQL license; see.) + +* If we have a 64-bit integer type, then a 64-bit CRC looks just like the +* usual sort of implementation. (See Ross Williams' excellent introduction +* A PAINLESS GUIDE TO CRC ERROR DETECTION ALGORITHMS, available from +* ftp://ftp.rocksoft.com/papers/crc_v3.txt or several other net sites.) +* If we have no working 64-bit type, then fake it with two 32-bit registers. +* +* The present implementation is a normal (not "reflected", in Williams' +* terms) 64-bit CRC, using initial all-ones register contents and a final +* bit inversion. The chosen polynomial is borrowed from the DLT1 spec +* (ECMA-182, available from http://www.ecma.ch/ecma1/STAND/ECMA-182.HTM): +* +* x^64 + x^62 + x^57 + x^55 + x^54 + x^53 + x^52 + x^47 + x^46 + x^45 + +* x^40 + x^39 + x^38 + x^37 + x^35 + x^33 + x^32 + x^31 + x^29 + x^27 + +* x^24 + x^23 + x^22 + x^21 + x^19 + x^17 + x^13 + x^12 + x^10 + x^9 + +* x^7 + x^4 + x + 1 +*/ + +static const uint64_t crc_table[256 ] = { +0x0000000000000000 ,0x42F0E1EBA9EA3693 ,0x85E1C3D753D46D26 , +0xC711223CFA3E5BB5 ,0x493366450E42ECDF ,0x0BC387AEA7A8DA4C , +0xCCD2A5925D9681F9 ,0x8E224479F47CB76A ,0x9266CC8A1C85D9BE , +0xD0962D61B56FEF2D ,0x17870F5D4F51B498 ,0x5577EEB6E6BB820B , +0xDB55AACF12C73561 ,0x99A54B24BB2D03F2 ,0x5EB4691841135847 , +0x1C4488F3E8F96ED4 ,0x663D78FF90E185EF ,0x24CD9914390BB37C , +0xE3DCBB28C335E8C9 ,0xA12C5AC36ADFDE5A ,0x2F0E1EBA9EA36930 , +0x6DFEFF5137495FA3 ,0xAAEFDD6DCD770416 ,0xE81F3C86649D3285 , +0xF45BB4758C645C51 ,0xB6AB559E258E6AC2 ,0x71BA77A2DFB03177 , +0x334A9649765A07E4 ,0xBD68D2308226B08E ,0xFF9833DB2BCC861D , +0x388911E7D1F2DDA8 ,0x7A79F00C7818EB3B ,0xCC7AF1FF21C30BDE , +0x8E8A101488293D4D ,0x499B3228721766F8 ,0x0B6BD3C3DBFD506B , +0x854997BA2F81E701 ,0xC7B97651866BD192 ,0x00A8546D7C558A27 , +0x4258B586D5BFBCB4 ,0x5E1C3D753D46D260 ,0x1CECDC9E94ACE4F3 , +0xDBFDFEA26E92BF46 ,0x990D1F49C77889D5 ,0x172F5B3033043EBF , +0x55DFBADB9AEE082C ,0x92CE98E760D05399 ,0xD03E790CC93A650A , +0xAA478900B1228E31 ,0xE8B768EB18C8B8A2 ,0x2FA64AD7E2F6E317 , +0x6D56AB3C4B1CD584 ,0xE374EF45BF6062EE ,0xA1840EAE168A547D , +0x66952C92ECB40FC8 ,0x2465CD79455E395B ,0x3821458AADA7578F , +0x7AD1A461044D611C ,0xBDC0865DFE733AA9 ,0xFF3067B657990C3A , +0x711223CFA3E5BB50 ,0x33E2C2240A0F8DC3 ,0xF4F3E018F031D676 , +0xB60301F359DBE0E5 ,0xDA050215EA6C212F ,0x98F5E3FE438617BC , +0x5FE4C1C2B9B84C09 ,0x1D14202910527A9A ,0x93366450E42ECDF0 , +0xD1C685BB4DC4FB63 ,0x16D7A787B7FAA0D6 ,0x5427466C1E109645 , +0x4863CE9FF6E9F891 ,0x0A932F745F03CE02 ,0xCD820D48A53D95B7 , +0x8F72ECA30CD7A324 ,0x0150A8DAF8AB144E ,0x43A04931514122DD , +0x84B16B0DAB7F7968 ,0xC6418AE602954FFB ,0xBC387AEA7A8DA4C0 , +0xFEC89B01D3679253 ,0x39D9B93D2959C9E6 ,0x7B2958D680B3FF75 , +0xF50B1CAF74CF481F ,0xB7FBFD44DD257E8C ,0x70EADF78271B2539 , +0x321A3E938EF113AA ,0x2E5EB66066087D7E ,0x6CAE578BCFE24BED , +0xABBF75B735DC1058 ,0xE94F945C9C3626CB ,0x676DD025684A91A1 , +0x259D31CEC1A0A732 ,0xE28C13F23B9EFC87 ,0xA07CF2199274CA14 , +0x167FF3EACBAF2AF1 ,0x548F120162451C62 ,0x939E303D987B47D7 , +0xD16ED1D631917144 ,0x5F4C95AFC5EDC62E ,0x1DBC74446C07F0BD , +0xDAAD56789639AB08 ,0x985DB7933FD39D9B ,0x84193F60D72AF34F , +0xC6E9DE8B7EC0C5DC ,0x01F8FCB784FE9E69 ,0x43081D5C2D14A8FA , +0xCD2A5925D9681F90 ,0x8FDAB8CE70822903 ,0x48CB9AF28ABC72B6 , +0x0A3B7B1923564425 ,0x70428B155B4EAF1E ,0x32B26AFEF2A4998D , +0xF5A348C2089AC238 ,0xB753A929A170F4AB ,0x3971ED50550C43C1 , +0x7B810CBBFCE67552 ,0xBC902E8706D82EE7 ,0xFE60CF6CAF321874 , +0xE224479F47CB76A0 ,0xA0D4A674EE214033 ,0x67C58448141F1B86 , +0x253565A3BDF52D15 ,0xAB1721DA49899A7F ,0xE9E7C031E063ACEC , +0x2EF6E20D1A5DF759 ,0x6C0603E6B3B7C1CA ,0xF6FAE5C07D3274CD , +0xB40A042BD4D8425E ,0x731B26172EE619EB ,0x31EBC7FC870C2F78 , +0xBFC9838573709812 ,0xFD39626EDA9AAE81 ,0x3A28405220A4F534 , +0x78D8A1B9894EC3A7 ,0x649C294A61B7AD73 ,0x266CC8A1C85D9BE0 , +0xE17DEA9D3263C055 ,0xA38D0B769B89F6C6 ,0x2DAF4F0F6FF541AC , +0x6F5FAEE4C61F773F ,0xA84E8CD83C212C8A ,0xEABE6D3395CB1A19 , +0x90C79D3FEDD3F122 ,0xD2377CD44439C7B1 ,0x15265EE8BE079C04 , +0x57D6BF0317EDAA97 ,0xD9F4FB7AE3911DFD ,0x9B041A914A7B2B6E , +0x5C1538ADB04570DB ,0x1EE5D94619AF4648 ,0x02A151B5F156289C , +0x4051B05E58BC1E0F ,0x87409262A28245BA ,0xC5B073890B687329 , +0x4B9237F0FF14C443 ,0x0962D61B56FEF2D0 ,0xCE73F427ACC0A965 , +0x8C8315CC052A9FF6 ,0x3A80143F5CF17F13 ,0x7870F5D4F51B4980 , +0xBF61D7E80F251235 ,0xFD913603A6CF24A6 ,0x73B3727A52B393CC , +0x31439391FB59A55F ,0xF652B1AD0167FEEA ,0xB4A25046A88DC879 , +0xA8E6D8B54074A6AD ,0xEA16395EE99E903E ,0x2D071B6213A0CB8B , +0x6FF7FA89BA4AFD18 ,0xE1D5BEF04E364A72 ,0xA3255F1BE7DC7CE1 , +0x64347D271DE22754 ,0x26C49CCCB40811C7 ,0x5CBD6CC0CC10FAFC , +0x1E4D8D2B65FACC6F ,0xD95CAF179FC497DA ,0x9BAC4EFC362EA149 , +0x158E0A85C2521623 ,0x577EEB6E6BB820B0 ,0x906FC95291867B05 , +0xD29F28B9386C4D96 ,0xCEDBA04AD0952342 ,0x8C2B41A1797F15D1 , +0x4B3A639D83414E64 ,0x09CA82762AAB78F7 ,0x87E8C60FDED7CF9D , +0xC51827E4773DF90E ,0x020905D88D03A2BB ,0x40F9E43324E99428 , +0x2CFFE7D5975E55E2 ,0x6E0F063E3EB46371 ,0xA91E2402C48A38C4 , +0xEBEEC5E96D600E57 ,0x65CC8190991CB93D ,0x273C607B30F68FAE , +0xE02D4247CAC8D41B ,0xA2DDA3AC6322E288 ,0xBE992B5F8BDB8C5C , +0xFC69CAB42231BACF ,0x3B78E888D80FE17A ,0x7988096371E5D7E9 , +0xF7AA4D1A85996083 ,0xB55AACF12C735610 ,0x724B8ECDD64D0DA5 , +0x30BB6F267FA73B36 ,0x4AC29F2A07BFD00D ,0x08327EC1AE55E69E , +0xCF235CFD546BBD2B ,0x8DD3BD16FD818BB8 ,0x03F1F96F09FD3CD2 , +0x41011884A0170A41 ,0x86103AB85A2951F4 ,0xC4E0DB53F3C36767 , +0xD8A453A01B3A09B3 ,0x9A54B24BB2D03F20 ,0x5D45907748EE6495 , +0x1FB5719CE1045206 ,0x919735E51578E56C ,0xD367D40EBC92D3FF , +0x1476F63246AC884A ,0x568617D9EF46BED9 ,0xE085162AB69D5E3C , +0xA275F7C11F7768AF ,0x6564D5FDE549331A ,0x279434164CA30589 , +0xA9B6706FB8DFB2E3 ,0xEB46918411358470 ,0x2C57B3B8EB0BDFC5 , +0x6EA7525342E1E956 ,0x72E3DAA0AA188782 ,0x30133B4B03F2B111 , +0xF7021977F9CCEAA4 ,0xB5F2F89C5026DC37 ,0x3BD0BCE5A45A6B5D , +0x79205D0E0DB05DCE ,0xBE317F32F78E067B ,0xFCC19ED95E6430E8 , +0x86B86ED5267CDBD3 ,0xC4488F3E8F96ED40 ,0x0359AD0275A8B6F5 , +0x41A94CE9DC428066 ,0xCF8B0890283E370C ,0x8D7BE97B81D4019F , +0x4A6ACB477BEA5A2A ,0x089A2AACD2006CB9 ,0x14DEA25F3AF9026D , +0x562E43B4931334FE ,0x913F6188692D6F4B ,0xD3CF8063C0C759D8 , +0x5DEDC41A34BBEEB2 ,0x1F1D25F19D51D821 ,0xD80C07CD676F8394 , +0x9AFCE626CE85B507 +}; + +uint64_t crc64_update (uint64_t crc,const void *_data,size_t len) +{ +const unsigned char *data = _data; + +while (len--) { +int i = ((int ) (crc >>56 ) ^ *data++) &0xFF ; + crc = crc_table[i] ^ (crc <<8 ); + } + +return crc; +} +EXPORT_SYMBOL (crc64_update); + +uint64_t crc64 (const void *data,size_t len) +{ +uint64_t crc =0xffffffffffffffff ; + + crc =crc64_update (crc, data, len); + +return crc ^0xffffffffffffffff ; +} +EXPORT_SYMBOL (crc64);
drivers/md/bcache/util.h new file +606 -0
606 lines not on this page · raw message
Signature · 1 line
1.7.7.3
PATCH v15 9/16 bcache: Documentation, and changes to generic code
In reply to Kent Overstreet--- Documentation/ABI/testing/sysfs-block-bcache | 156 ++++++++++++++++ Documentation/bcache.txt | 255 ++++++++++++++++++++++++++ drivers/md/Kconfig | 2 + drivers/md/Makefile | 1 + drivers/md/bcache/Kconfig | 41 ++++ drivers/md/bcache/Makefile | 14 ++ include/linux/cgroup_subsys.h | 6 + include/linux/sched.h | 4 + kernel/fork.c | 4 + 9 files changed, 483 insertions(+), 0 deletions(-) create mode 100644 Documentation/ABI/testing/sysfs-block-bcache create mode 100644 Documentation/bcache.txt create mode 100644 drivers/md/bcache/Kconfig create mode 100644 drivers/md/bcache/Makefile
Documentation/ABI/testing/sysfs-block-bcache new file +156 -0
@@ -0,0 +1,156 @@ +What: /sys/block/<disk>/bcache/unregister +Date: November 2010 +Contact: Kent Overstreet <[email protected]> +Description: + A write to this file causes the backing device or cache to be + unregistered. If a backing device had dirty data in the cache, + writeback mode is automatically disabled and all dirty data is + flushed before the device is unregistered. Caches unregister + all associated backing devices before unregistering themselves. + +What: /sys/block/<disk>/bcache/clear_stats +Date: November 2010 +Contact: Kent Overstreet <[email protected]> +Description: + Writing to this file resets all the statistics for the device. + +What: /sys/block/<disk>/bcache/cache +Date: November 2010 +Contact: Kent Overstreet <[email protected]> +Description: + For a backing device that has cache, a symlink to + the bcache/ dir of that cache. + +What: /sys/block/<disk>/bcache/cache_hits +Date: November 2010 +Contact: Kent Overstreet <[email protected]> +Description: + For backing devices: integer number of full cache hits, + counted per bio. A partial cache hit counts as a miss. + +What: /sys/block/<disk>/bcache/cache_misses +Date: November 2010 +Contact: Kent Overstreet <[email protected]> +Description: + For backing devices: integer number of cache misses. + +What: /sys/block/<disk>/bcache/cache_hit_ratio +Date: November 2010 +Contact: Kent Overstreet <[email protected]> +Description: + For backing devices: cache hits as a percentage. + +What: /sys/block/<disk>/bcache/sequential_cutoff +Date: November 2010 +Contact: Kent Overstreet <[email protected]> +Description: + For backing devices: Threshold past which sequential IO will + skip the cache. Read and written as bytes in human readable + units (i.e. echo 10M > sequntial_cutoff). + +What: /sys/block/<disk>/bcache/bypassed +Date: November 2010 +Contact: Kent Overstreet <[email protected]> +Description: + Sum of all reads and writes that have bypassed the cache (due + to the sequential cutoff). Expressed as bytes in human + readable units. + +What: /sys/block/<disk>/bcache/writeback +Date: November 2010 +Contact: Kent Overstreet <[email protected]> +Description: + For backing devices: When on, writeback caching is enabled and + writes will be buffered in the cache. When off, caching is in + writethrough mode; reads and writes will be added to the + cache but no write buffering will take place. + +What: /sys/block/<disk>/bcache/writeback_running +Date: November 2010 +Contact: Kent Overstreet <[email protected]> +Description: + For backing devices: when off, dirty data will not be written + from the cache to the backing device. The cache will still be + used to buffer writes until it is mostly full, at which point + writes transparently revert to writethrough mode. Intended only + for benchmarking/testing. + +What: /sys/block/<disk>/bcache/writeback_delay +Date: November 2010 +Contact: Kent Overstreet <[email protected]> +Description: + For backing devices: In writeback mode, when dirty data is + written to the cache and the cache held no dirty data for that + backing device, writeback from cache to backing device starts + after this delay, expressed as an integer number of seconds. + +What: /sys/block/<disk>/bcache/writeback_percent +Date: November 2010 +Contact: Kent Overstreet <[email protected]> +Description: + For backing devices: If nonzero, writeback from cache to + backing device only takes place when more than this percentage + of the cache is used, allowing more write coalescing to take + place and reducing total number of writes sent to the backing + device. Integer between 0 and 40. + +What: /sys/block/<disk>/bcache/synchronous +Date: November 2010 +Contact: Kent Overstreet <[email protected]> +Description: + For a cache, a boolean that allows synchronous mode to be + switched on and off. In synchronous mode all writes are ordered + such that the cache can reliably recover from unclean shutdown; + if disabled bcache will not generally wait for writes to + complete but if the cache is not shut down cleanly all data + will be discarded from the cache. Should not be turned off with + writeback caching enabled. + +What: /sys/block/<disk>/bcache/discard +Date: November 2010 +Contact: Kent Overstreet <[email protected]> +Description: + For a cache, a boolean allowing discard/TRIM to be turned off + or back on if the device supports it. + +What: /sys/block/<disk>/bcache/bucket_size +Date: November 2010 +Contact: Kent Overstreet <[email protected]> +Description: + For a cache, bucket size in human readable units, as set at + cache creation time; should match the erase block size of the + SSD for optimal performance. + +What: /sys/block/<disk>/bcache/nbuckets +Date: November 2010 +Contact: Kent Overstreet <[email protected]> +Description: + For a cache, the number of usable buckets. + +What: /sys/block/<disk>/bcache/tree_depth +Date: November 2010 +Contact: Kent Overstreet <[email protected]> +Description: + For a cache, height of the btree excluding leaf nodes (i.e. a + one node tree will have a depth of 0). + +What: /sys/block/<disk>/bcache/btree_cache_size +Date: November 2010 +Contact: Kent Overstreet <[email protected]> +Description: + Number of btree buckets/nodes that are currently cached in + memory; cache dynamically grows and shrinks in response to + memory pressure from the rest of the system. + +What: /sys/block/<disk>/bcache/written +Date: November 2010 +Contact: Kent Overstreet <[email protected]> +Description: + For a cache, total amount of data in human readable units + written to the cache, excluding all metadata. + +What: /sys/block/<disk>/bcache/btree_written +Date: November 2010 +Contact: Kent Overstreet <[email protected]> +Description: + For a cache, sum of all btree writes in human readable units.
Documentation/bcache.txt new file +255 -0
255 lines not on this page · raw message
drivers/md/Kconfig +2 -0
@@ -185,6 +185,8 @@ config MD_FAULTY In unsure, say N. +source "drivers/md/bcache/Kconfig" + config BLK_DEV_DM tristate "Device mapper support" ---help---
drivers/md/Makefile +1 -0
@@ -26,6 +26,7 @@ obj-$(CONFIG_MD_RAID10) += raid10.o obj-$(CONFIG_MD_RAID456) += raid456.o obj-$(CONFIG_MD_MULTIPATH) += multipath.o obj-$(CONFIG_MD_FAULTY) += faulty.o +obj-$(CONFIG_BCACHE) += bcache/ obj-$(CONFIG_BLK_DEV_MD) += md-mod.o obj-$(CONFIG_BLK_DEV_DM) += dm-mod.o obj-$(CONFIG_DM_BUFIO) += dm-bufio.o
drivers/md/bcache/Kconfig new file +41 -0
41 lines not on this page · raw message
drivers/md/bcache/Makefile new file +14 -0
@@ -0,0 +1,14 @@ + +obj-$(CONFIG_BCACHE) += bcache.o + +bcache-y := alloc.o btree.o bset.o io.o journal.o\ + writeback.o movinggc.o request.o super.o debug.o util.o trace.o stats.o + +CFLAGS_alloc.o += -std=gnu99 +CFLAGS_btree.o += -std=gnu99 +CFLAGS_bset.o += -std=gnu99 +CFLAGS_journal.o += -std=gnu99 +CFLAGS_movinggc.o += -std=gnu99 +CFLAGS_request.o += -std=gnu99 -Iblock +CFLAGS_super.o += -std=gnu99 +CFLAGS_debug.o += -std=gnu99
include/linux/cgroup_subsys.h +6 -0
@@ -72,3 +72,9 @@ SUBSYS(net_prio)#endif /* */ + +#ifdef CONFIG_CGROUP_BCACHE +SUBSYS(bcache) +#endif + +/* */
include/linux/sched.h +4 -0
@@ -1583,6 +1583,10 @@ struct task_struct {struct uprobe_task *utask;int uprobe_srcu_id;#endif +#if defined(CONFIG_BCACHE ) || defined(CONFIG_BCACHE_MODULE ) +unsigned int sequential_io; +unsigned int sequential_io_avg; +#endif };/* Future-safe accessor for struct task_struct's cpus_allowed. */
kernel/fork.c +4 -0
@@ -1314,6 +1314,10 @@ static struct task_struct *copy_process(unsigned long clone_flags, p->memcg_batch.do_batch =0 ; p->memcg_batch.memcg =NULL ;#endif +#ifdef CONFIG_BCACHE + p->sequential_io =0 ; + p->sequential_io_avg =0 ; +#endif /* Perform scheduler related setup. Assign this task to a CPU. */ sched_fork (p);
Signature · 1 line
1.7.7.3
PATCH v15 10/16 bcache: Superblock/initialization/sysfs code
In reply to Kent Overstreet--- drivers/md/bcache/stats.c | 245 ++++++ drivers/md/bcache/stats.h | 58 ++ drivers/md/bcache/super.c | 1992 +++++++++++++++++++++++++++++++++++++++++++++ drivers/md/bcache/sysfs.c | 812 ++++++++++++++++++ drivers/md/bcache/sysfs.h | 91 ++ 5 files changed, 3198 insertions(+), 0 deletions(-) create mode 100644 drivers/md/bcache/stats.c create mode 100644 drivers/md/bcache/stats.h create mode 100644 drivers/md/bcache/super.c create mode 100644 drivers/md/bcache/sysfs.c create mode 100644 drivers/md/bcache/sysfs.h
drivers/md/bcache/stats.c new file +245 -0
@@ -0,0 +1,245 @@ +#include "bcache.h" +#include "stats.h" +#include "btree.h" +#include "request.h" +#include "sysfs.h" + +/* We keep absolute totals of various statistics, and addionally a set of three +* rolling averages. +* +* Every so often, a timer goes off and rescales the rolling averages. +* accounting_rescale[] is how many times the timer has to go off before we +* rescale each set of numbers; that gets us half lives of 5 minutes, one hour, +* and one day. +* +* accounting_delay is how often the timer goes off - 22 times in 5 minutes, +* and accounting_weight is what we use to rescale: +* +* pow(31 / 32, 22) ~= 1/2 +* +* So that we don't have to increment each set of numbers every time we (say) +* get a cache hit, we increment a single atomic_t in acc->collector, and when +* the rescale function runs it resets the atomic counter to 0 and adds its +* old value to each of the exported numbers. +* +* To reduce rounding error, the numbers in struct cache_stats are all +* stored left shifted by 16, and scaled back in the sysfs show() function. +*/ + +static const unsigned DAY_RESCALE =288 ; +static const unsigned HOUR_RESCALE =12 ; +static const unsigned FIVE_MINUTE_RESCALE =1 ; +static const unsigned accounting_delay = (HZ *300 ) /22 ; +static const unsigned accounting_weight =32 ; + +/* sysfs reading/writing */ + +read_attribute (cache_hits); +read_attribute (cache_misses); +read_attribute (cache_bypass_hits); +read_attribute (cache_bypass_misses); +read_attribute (cache_hit_ratio); +read_attribute (cache_readaheads); +read_attribute (cache_miss_collisions); +read_attribute (bypassed); + +static struct attribute *accounting_files[] = { + &sysfs_cache_hits, + &sysfs_cache_misses, + &sysfs_cache_bypass_hits, + &sysfs_cache_bypass_misses, + &sysfs_cache_hit_ratio, + &sysfs_cache_readaheads, + &sysfs_cache_miss_collisions, + &sysfs_bypassed, +NULL +}; + +static ssize_t cache_stats_show (struct kobject *kobj, +struct attribute *attr, +char *buf) { +struct cache_stats *s = + container_of(kobj, struct cache_stats, kobj); +#define var (stat) (s->stat >> 16) +var_print (cache_hits); +var_print (cache_misses); +var_print (cache_bypass_hits); +var_print (cache_bypass_misses); + +sysfs_print (cache_hit_ratio, +DIV_SAFE (var (cache_hits) *100 , +var (cache_hits) +var (cache_misses))); + +var_print (cache_readaheads); +var_print (cache_miss_collisions); +sysfs_printf (bypassed,"%hli" ,var (sectors_bypassed) <<9 ); +#undef var +return 0 ; +} + +/* kobjects */ + +static void unregister_fake (struct kobject *k) +{ +} + +static const struct sysfs_ops accounting_ops = { + .show = cache_stats_show, + .store =NULL +}; +static struct kobj_type accounting_obj = { + .release = unregister_fake, + .sysfs_ops = &accounting_ops, + .default_attrs = accounting_files +}; + +static void scale_accounting (unsigned long data); + +void bch_cache_accounting_init (struct cache_accounting *acc,struct closure *parent) +{ +kobject_init (&acc->total.kobj, &accounting_obj); +kobject_init (&acc->five_minute.kobj, &accounting_obj); +kobject_init (&acc->hour.kobj, &accounting_obj); +kobject_init (&acc->day.kobj, &accounting_obj); + +closure_init (&acc->cl, parent); +init_timer (&acc->timer); + acc->timer.expires = jiffies + accounting_delay; + acc->timer.data = (unsigned long ) acc; + acc->timer.function = scale_accounting; +add_timer (&acc->timer); +} + +int bch_cache_accounting_add_kobjs (struct cache_accounting *acc, +struct kobject *parent) +{ +int ret =kobject_add (&acc->total.kobj, parent, +"stats_total" ); + ret = ret ?:kobject_add (&acc->five_minute.kobj, parent, +"stats_five_minute" ); + ret = ret ?:kobject_add (&acc->hour.kobj, parent, +"stats_hour" ); + ret = ret ?:kobject_add (&acc->day.kobj, parent, +"stats_day" ); +return ret; +} + +void bch_cache_accounting_clear (struct cache_accounting *acc) +{ +memset (&acc->total.cache_hits, +0 , +sizeof (unsigned long ) *7 ); +} + +void bch_cache_accounting_destroy (struct cache_accounting *acc) +{ +kobject_put (&acc->total.kobj); +kobject_put (&acc->five_minute.kobj); +kobject_put (&acc->hour.kobj); +kobject_put (&acc->day.kobj); + +atomic_set (&acc->closing,1 ); +if (del_timer_sync (&acc->timer)) +closure_return (&acc->cl); +} + +/* EWMA scaling */ + +static void scale_stat (unsigned long *stat) +{ + *stat =ewma_add (*stat,0 , accounting_weight,0 ); +} + +static void scale_stats (struct cache_stats *stats,unsigned long rescale_at) +{ +if (++stats->rescale == rescale_at) { + stats->rescale =0 ; +scale_stat (&stats->cache_hits); +scale_stat (&stats->cache_misses); +scale_stat (&stats->cache_bypass_hits); +scale_stat (&stats->cache_bypass_misses); +scale_stat (&stats->cache_readaheads); +scale_stat (&stats->cache_miss_collisions); +scale_stat (&stats->sectors_bypassed); + } +} + +static void scale_accounting (unsigned long data) +{ +struct cache_accounting *acc = (struct cache_accounting *) data; + +#define move_stat (name) do { \ + unsigned long t = atomic_xchg(&acc->collector.name, 0); \ + t <<= 16; \ + acc->five_minute.name += t; \ + acc->hour.name += t; \ + acc->day.name += t; \ + acc->total.name += t; \ +} while (0) + +move_stat (cache_hits); +move_stat (cache_misses); +move_stat (cache_bypass_hits); +move_stat (cache_bypass_misses); +move_stat (cache_readaheads); +move_stat (cache_miss_collisions); +move_stat (sectors_bypassed); + +scale_stats (&acc->total,0 ); +scale_stats (&acc->day,DAY_RESCALE ); +scale_stats (&acc->hour,HOUR_RESCALE ); +scale_stats (&acc->five_minute,FIVE_MINUTE_RESCALE ); + + acc->timer.expires += accounting_delay; + +if (!atomic_read (&acc->closing)) +add_timer (&acc->timer); +else +closure_return (&acc->cl); +} + +static void mark_cache_stats (struct cache_stat_collector *stats, +bool hit,bool bypass) +{ +if (!bypass) +if (hit) +atomic_inc (&stats->cache_hits); +else +atomic_inc (&stats->cache_misses); +else +if (hit) +atomic_inc (&stats->cache_bypass_hits); +else +atomic_inc (&stats->cache_bypass_misses); +} + +void bch_mark_cache_accounting (struct search *s,bool hit,bool bypass) +{ + struct cached_dev *dc = container_of(s->d, struct cached_dev, disk); +mark_cache_stats (&dc->accounting.collector, hit, bypass); +mark_cache_stats (&s->op.c->accounting.collector, hit, bypass); +#ifdef CONFIG_CGROUP_BCACHE +mark_cache_stats (&(bch_bio_to_cgroup (s->orig_bio)->stats), hit, bypass); +#endif +} + +void bch_mark_cache_readahead (struct search *s) +{ + struct cached_dev *dc = container_of(s->d, struct cached_dev, disk); +atomic_inc (&dc->accounting.collector.cache_readaheads); +atomic_inc (&s->op.c->accounting.collector.cache_readaheads); +} + +void bch_mark_cache_miss_collision (struct search *s) +{ + struct cached_dev *dc = container_of(s->d, struct cached_dev, disk); +atomic_inc (&dc->accounting.collector.cache_miss_collisions); +atomic_inc (&s->op.c->accounting.collector.cache_miss_collisions); +} + +void bch_mark_sectors_bypassed (struct search *s,int sectors) +{ + struct cached_dev *dc = container_of(s->d, struct cached_dev, disk); +atomic_add (sectors, &dc->accounting.collector.sectors_bypassed); +atomic_add (sectors, &s->op.c->accounting.collector.sectors_bypassed); +}
drivers/md/bcache/stats.h new file +58 -0
58 lines not on this page · raw message
drivers/md/bcache/super.c new file +1992 -0
1,992 lines not on this page · raw message
drivers/md/bcache/sysfs.c new file +812 -0
705 lines not on this page · raw message
drivers/md/bcache/sysfs.h new file +91 -0
91 lines not on this page · raw message
The rest of this diff is not shown. View the raw message.
Signature · 1 line
1.7.7.3
Part of the diff is not shown here. View the raw message.
PATCH v15 11/16 bcache: Core btree code
In reply to Kent Overstreet--- drivers/md/bcache/bcache.h | 1142 ++++++++++++++++++++ drivers/md/bcache/btree.c | 2508 ++++++++++++++++++++++++++++++++++++++++++++ drivers/md/bcache/btree.h | 423 ++++++++ 3 files changed, 4073 insertions(+), 0 deletions(-) create mode 100644 drivers/md/bcache/bcache.h create mode 100644 drivers/md/bcache/btree.c create mode 100644 drivers/md/bcache/btree.h
drivers/md/bcache/bcache.h new file +1142 -0
@@ -0,0 +1,1142 @@ +#ifndef _BCACHE_H +#define _BCACHE_H + +/* +* SOME HIGH LEVEL CODE DOCUMENTATION: +* +* Bcache mostly works with cache sets, cache devices, and backing devices. +* +* Support for multiple cache devices hasn't quite been finished off yet, but +* it's about 95% plumbed through. A cache set and its cache devices is sort of +* like a md raid array and its component devices. Most of the code doesn't care +* about individual cache devices, the main abstraction is the cache set. +* +* Multiple cache devices is intended to give us the ability to mirror dirty +* cached data and metadata, without mirroring clean cached data. +* +* Backing devices are different, in that they have a lifetime independent of a +* cache set. When you register a newly formatted backing device it'll come up +* in passthrough mode, and then you can attach and detach a backing device from +* a cache set at runtime - while it's mounted and in use. Detaching implicitly +* invalidates any cached data for that backing device. +* +* A cache set can have multiple (many) backing devices attached to it. +* +* There's also flash only volumes - this is the reason for the distinction +* between struct cached_dev and struct bcache_device. A flash only volume +* works much like a bcache device that has a backing device, except the +* "cached" data is always dirty. The end result is that we get thin +* provisioning with very little additional code. +* +* Flash only volumes work but they're not production ready because the moving +* garbage collector needs more work. More on that later. +* +* BUCKETS/ALLOCATION: +* +* Bcache is primarily designed for caching, which means that in normal +* operation all of our available space will be allocated. Thus, we need an +* efficient way of deleting things from the cache so we can write new things to +* it. +* +* To do this, we first divide the cache device up into buckets. A bucket is the +* unit of allocation; they're typically around 1 mb - anywhere from 128k to 2M+ +* works efficiently. +* +* Each bucket has a 16 bit priority, and an 8 bit generation associated with +* it. The gens and priorities for all the buckets are stored contiguously and +* packed on disk (in a linked list of buckets - aside from the superblock, all +* of bcache's metadata is stored in buckets). +* +* The priority is used to implement an LRU. We reset a bucket's priority when +* we allocate it or on cache it, and every so often we decrement the priority +* of each bucket. It could be used to implement something more sophisticated, +* if anyone ever gets around to it. +* +* The generation is used for invalidating buckets. Each pointer also has an 8 +* bit generation embedded in it; for a pointer to be considered valid, its gen +* must match the gen of the bucket it points into. Thus, to reuse a bucket all +* we have to do is increment its gen (and write its new gen to disk; we batch +* this up). +* +* Bcache is entirely COW - we never write twice to a bucket, even buckets that +* contain metadata (including btree nodes). +* +* THE BTREE: +* +* Bcache is in large part design around the btree. +* +* At a high level, the btree is just an index of key -> ptr tuples. +* +* Keys represent extents, and thus have a size field. Keys also have a variable +* number of pointers attached to them (potentially zero, which is handy for +* invalidating the cache). +* +* The key itself is an inode:offset pair. The inode number corresponds to a +* backing device or a flash only volume. The offset is the ending offset of the +* extent within the inode - not the starting offset; this makes lookups +* slightly more convenient. +* +* Pointers contain the cache device id, the offset on that device, and an 8 bit +* generation number. More on the gen later. +* +* Index lookups are not fully abstracted - cache lookups in particular are +* still somewhat mixed in with the btree code, but things are headed in that +* direction. +* +* Updates are fairly well abstracted, though. There are two different ways of +* updating the btree; insert and replace. +* +* BTREE_INSERT will just take a list of keys and insert them into the btree - +* overwriting (possibly only partially) any extents they overlap with. This is +* used to update the index after a write. +* +* BTREE_REPLACE is really cmpxchg(); it inserts a key into the btree iff it is +* overwriting a key that matches another given key. This is used for inserting +* data into the cache after a cache miss, and for background writeback, and for +* the moving garbage collector. +* +* There is no "delete" operation; deleting things from the index is +* accomplished by either by invalidating pointers (by incrementing a bucket's +* gen) or by inserting a key with 0 pointers - which will overwrite anything +* previously present at that location in the index. +* +* This means that there are always stale/invalid keys in the btree. They're +* filtered out by the code that iterates through a btree node, and removed when +* a btree node is rewritten. +* +* BTREE NODES: +* +* Our unit of allocation is a bucket, and we we can't arbitrarily allocate and +* free smaller than a bucket - so, that's how big our btree nodes are. +* +* (If buckets are really big we'll only use part of the bucket for a btree node +* - no less than 1/4th - but a bucket still contains no more than a single +* btree node. I'd actually like to change this, but for now we rely on the +* bucket's gen for deleting btree nodes when we rewrite/split a node.) +* +* Anyways, btree nodes are big - big enough to be inefficient with a textbook +* btree implementation. +* +* The way this is solved is that btree nodes are internally log structured; we +* can append new keys to an existing btree node without rewriting it. This +* means each set of keys we write is sorted, but the node is not. +* +* We maintain this log structure in memory - keeping 1Mb of keys sorted would +* be expensive, and we have to distinguish between the keys we have written and +* the keys we haven't. So to do a lookup in a btree node, we have to search +* each sorted set. But we do merge written sets together lazily, so the cost of +* these extra searches is quite low (normally most of the keys in a btree node +* will be in one big set, and then there'll be one or two sets that are much +* smaller). +* +* This log structure makes bcache's btree more of a hybrid between a +* conventional btree and a compacting data structure, with some of the +* advantages of both. +* +* GARBAGE COLLECTION: +* +* We can't just invalidate any bucket - it might contain dirty data or +* metadata. If it once contained dirty data, other writes might overwrite it +* later, leaving no valid pointers into that bucket in the index. +* +* Thus, the primary purpose of garbage collection is to find buckets to reuse. +* It also counts how much valid data it each bucket currently contains, so that +* allocation can reuse buckets sooner when they've been mostly overwritten. +* +* It also does some things that are really internal to the btree +* implementation. If a btree node contains pointers that are stale by more than +* some threshold, it rewrites the btree node to avoid the bucket's generation +* wrapping around. It also merges adjacent btree nodes if they're empty enough. +* +* THE JOURNAL: +* +* Bcache's journal is not necessary for consistency; we always strictly +* order metadata writes so that the btree and everything else is consistent on +* disk in the event of an unclean shutdown, and in fact bcache had writeback +* caching (with recovery from unclean shutdown) before journalling was +* implemented. +* +* Rather, the journal is purely a performance optimization; we can't complete a +* write until we've updated the index on disk, otherwise the cache would be +* inconsistent in the event of an unclean shutdown. This means that without the +* journal, on random write workloads we constantly have to update all the leaf +* nodes in the btree, and those writes will be mostly empty (appending at most +* a few keys each) - highly inefficient in terms of amount of metadata writes, +* and it puts more strain on the various btree resorting/compacting code. +* +* The journal is just a log of keys we've inserted; on startup we just reinsert +* all the keys in the open journal entries. That means that when we're updating +* a node in the btree, we can wait until a 4k block of keys fills up before +* writing them out. +* +* For simplicity, we only journal updates to leaf nodes; updates to parent +* nodes are rare enough (since our leaf nodes are huge) that it wasn't worth +* the complexity to deal with journalling them (in particular, journal replay) +* - updates to non leaf nodes just happen synchronously (see btree_split()). +*/ + +#define pr_fmt (fmt) "bcache: %s() " fmt "\n", __func__ + +#include <linux/bio.h> +#include <linux/blktrace_api.h> +#include <linux/closure.h> +#include <linux/kobject.h> +#include <linux/list.h> +#include <linux/mutex.h> +#include <linux/rbtree.h> +#include <linux/rwsem.h> +#include <linux/types.h> +#include <linux/workqueue.h> + +#include "util.h" + +struct bucket { +atomic_t pin; +uint16_t prio; +uint8_t gen; +uint8_t disk_gen; +uint8_t last_gc;/* Most out of date gen in the btree */ +uint8_t gc_gen; +uint16_t gc_mark; +}; + +/* +* I'd use bitfields for these, but I don't trust the compiler not to screw me +* as multiple threads touch struct bucket without locking +*/ + +BITMASK(GC_MARK, struct bucket, gc_mark, 0, 2); +#define GC_MARK_RECLAIMABLE 0 +#define GC_MARK_DIRTY 1 +#define GC_MARK_BTREE 2 +BITMASK(GC_SECTORS_USED, struct bucket, gc_mark, 2, 14); + +struct bkey { +uint64_t high; +uint64_t low; +uint64_t ptr[]; +}; + +/* Enough for a key with 6 pointers */ +#define BKEY_PAD 8 + +#define BKEY_PADDED (key) \ + union { struct bkey key; uint64_t key ## _pad[BKEY_PAD]; } + +/* Version 1: Backing device +* Version 2: Seed pointer into btree node checksum +* Version 3: New UUID format +*/ +#define BCACHE_SB_VERSION 3 + +#define SB_SECTOR 8 +#define SB_SIZE 4096 +#define SB_LABEL_SIZE 32 +#define SB_JOURNAL_BUCKETS 256 +/* SB_JOURNAL_BUCKETS must be divisible by BITS_PER_LONG */ +#define MAX_CACHES_PER_SET 8 + +#define BDEV_DATA_START 16/* sectors */ + +struct cache_sb { +uint64_t csum; +uint64_t offset;/* sector where this sb was written */ +uint64_t version; +#define CACHE_BACKING_DEV 1 + +uint8_t magic[16 ]; + +uint8_t uuid[16 ]; +union { +uint8_t set_uuid[16 ]; +uint64_t set_magic; + }; +uint8_t label[SB_LABEL_SIZE ]; + +uint64_t flags; +uint64_t seq; +uint64_t pad[8 ]; + +uint64_t nbuckets;/* device size */ +uint16_t block_size;/* sectors */ +uint16_t bucket_size;/* sectors */ + +uint16_t nr_in_set; +uint16_t nr_this_dev; + +uint32_t last_mount;/* time_t */ + +uint16_t first_bucket; +union { +uint16_t njournal_buckets; +uint16_t keys; + }; +uint64_t d[SB_JOURNAL_BUCKETS ];/* journal buckets */ +}; + +BITMASK(CACHE_SYNC, struct cache_sb, flags, 0, 1); +BITMASK(CACHE_DISCARD, struct cache_sb, flags, 1, 1); +BITMASK(CACHE_REPLACEMENT, struct cache_sb, flags, 2, 3); +#define CACHE_REPLACEMENT_LRU 0U +#define CACHE_REPLACEMENT_FIFO 1U +#define CACHE_REPLACEMENT_RANDOM 2U + +BITMASK(BDEV_CACHE_MODE, struct cache_sb, flags, 0, 4); +#define CACHE_MODE_WRITETHROUGH 0U +#define CACHE_MODE_WRITEBACK 1U +#define CACHE_MODE_WRITEAROUND 2U +#define CACHE_MODE_NONE 3U +BITMASK(BDEV_STATE, struct cache_sb, flags, 61, 2); +#define BDEV_STATE_NONE 0U +#define BDEV_STATE_CLEAN 1U +#define BDEV_STATE_DIRTY 2U +#define BDEV_STATE_STALE 3U + +/* Version 1: Seed pointer into btree node checksum +*/ +#define BCACHE_BSET_VERSION 1 + +/* +* This is the on disk format for btree nodes - a btree node on disk is a list +* of these; within each set the keys are sorted +*/ +struct bset { +uint64_t csum; +uint64_t magic; +uint64_t seq; +uint32_t version; +uint32_t keys; + +union { +struct bkey start[0 ]; +uint64_t d[0 ]; + }; +}; + +/* +* On disk format for priorities and gens - see super.c near prio_write() for +* more. +*/ +struct prio_set { +uint64_t csum; +uint64_t magic; +uint64_t seq; +uint32_t version; +uint32_t pad; + +uint64_t next_bucket; + +struct bucket_disk { +uint16_t prio; +uint8_t gen; + } __attribute((packed)) data[]; +}; + +#include "journal.h" +#include "stats.h" +struct search ; +struct btree ; +struct keybuf ; + +struct keybuf_key { +struct rb_node node; +BKEY_PADDED (key); +void *private; +}; + +typedef bool (keybuf_pred_fn )(struct keybuf *,struct bkey *); + +struct keybuf { +keybuf_pred_fn *key_predicate; + +struct bkey last_scanned; +spinlock_t lock; + +/* +* Beginning and end of range in rb tree - so that we can skip taking +* lock and checking the rb tree when we need to check for overlapping +* keys. +*/ +struct bkey start; +struct bkey end; + +struct rb_root keys; + +#define KEYBUF_NR 100 + DECLARE_ARRAY_ALLOCATOR(struct keybuf_key, freelist, KEYBUF_NR); +}; + +struct bcache_device { +struct closure cl; + +struct kobject kobj; + +struct cache_set *c; +unsigned id; +#define BCACHEDEVNAME_SIZE 12 +char name[BCACHEDEVNAME_SIZE ]; + +struct gendisk *disk; + +/* If nonzero, we're closing */ +atomic_t closing; + +/* If nonzero, we're detaching/unregistering from cache set */ +atomic_t detaching; + +atomic_long_t sectors_dirty; +unsigned long sectors_dirty_gc; +unsigned long sectors_dirty_last; +long sectors_dirty_derivative; + +mempool_t *unaligned_bvec; +struct bio_set *bio_split; + +unsigned data_csum:1 ; + +int (*cache_miss)(struct btree *,struct search *,struct bio *,unsigned ); +int (*ioctl) (struct bcache_device *,fmode_t ,unsigned ,unsigned long ); +}; + +struct io { +/* Used to track sequential IO so it can be skipped */ +struct hlist_node hash; +struct list_head lru; + +unsigned long jiffies; +unsigned sequential; +sector_t last; +}; + +struct cached_dev { +struct list_head list; +struct bcache_device disk; +struct block_device *bdev; + +struct cache_sb sb; +struct bio sb_bio; +struct bio_vec sb_bv[1 ]; +struct closure_with_waitlist sb_write; + +/* Refcount on the cache set. Always nonzero when we're caching. */ +atomic_t count; +struct work_struct detach; + +/* +* Device might not be running if it's dirty and the cache set hasn't +* showed up yet. +*/ +atomic_t running; + +/* +* Writes take a shared lock from start to finish; scanning for dirty +* data to refill the rb tree requires an exclusive lock. +*/ +struct rw_semaphore writeback_lock; + +/* +* Nonzero, and writeback has a refcount (d->count), iff there is dirty +* data in the cache. Protected by writeback_lock; must have an +* shared lock to set and exclusive lock to clear. +*/ +atomic_t has_dirty; + +struct ratelimit writeback_rate; +struct delayed_work writeback_rate_update; + +/* +* Internal to the writeback code, so read_dirty() can keep track of +* where it's at. +*/ +sector_t last_read; + +/* Number of writeback bios in flight */ +atomic_t in_flight; +struct closure_with_timer writeback; +struct closure_waitlist writeback_wait; + +struct keybuf writeback_keys; + +/* For tracking sequential IO */ +#define RECENT_IO_BITS 7 +#define RECENT_IO (1 << RECENT_IO_BITS) +struct io io[RECENT_IO ]; +struct hlist_head io_hash[RECENT_IO +1 ]; +struct list_head io_lru; +spinlock_t io_lock; + +struct cache_accounting accounting; + +/* The rest of this all shows up in sysfs */ +unsigned sequential_cutoff; +unsigned readahead; + +unsigned sequential_merge:1 ; +unsigned verify:1 ; + +unsigned writeback_metadata:1 ; +unsigned writeback_running:1 ; +unsigned char writeback_percent; +unsigned writeback_delay; + +int writeback_rate_change; +int64_t writeback_rate_derivative; +uint64_t writeback_rate_target; + +unsigned writeback_rate_update_seconds; +unsigned writeback_rate_d_term; +unsigned writeback_rate_p_term_inverse; +unsigned writeback_rate_d_smooth; +}; + +struct cache { +struct cache_set *set; +struct cache_sb sb; +struct bio sb_bio; +struct bio_vec sb_bv[1 ]; + +struct kobject kobj; +struct block_device *bdev; + +struct closure prio; +struct prio_set *disk_buckets; + +/* +* When allocating new buckets, prio_write() gets first dibs - since we +* may not be allocate at all without writing priorities and gens. +* prio_buckets[] contains the last buckets we wrote priorities to (so +* gc can mark them as metadata), prio_next[] contains the buckets +* allocated for the next prio write. +*/ +uint64_t *prio_buckets; +uint64_t *prio_next; +unsigned prio_write; +unsigned prio_alloc; + +/* > 0: buckets in free_inc have been marked as free +* = 0: buckets in free_inc can't be used until priorities are written +* < 0: priority write in progress +*/ +atomic_t prio_written; + +/* +* free: Buckets that are ready to be used +* +* free_inc: Incoming buckets - these are buckets that currently have +* cached data in them, and we can't reuse them until after we write +* their new gen to disk. After prio_write() finishes writing the new +* gens/prios, they'll be moved to the free list (and possibly discarded +* in the process) +* +* unused: GC found nothing pointing into these buckets (possibly +* because all the data they contained was overwritten), so we only +* need to discard them before they can be moved to the free list. +*/ + DECLARE_FIFO(long, free); + DECLARE_FIFO(long, free_inc); + DECLARE_FIFO(long, unused); + +size_t fifo_last_bucket; + +/* Allocation stuff: */ +struct bucket *buckets; + + DECLARE_HEAP(struct bucket *, heap); + +/* +* max(gen - disk_gen) for all buckets. When it gets too big we have to +* call prio_write() to keep gens from wrapping. +*/ +uint8_t need_save_prio; +unsigned gc_move_threshold; + +/* +* If nonzero, we know we aren't going to find any buckets to invalidate +* until a gc finishes - otherwise we could pointlessly burn a ton of +* cpu +*/ +unsigned invalidate_needs_gc:1 ; + +bool discard;/* Get rid of? */ + +/* +* We preallocate structs for issuing discards to buckets, and keep them +* on this list when they're not in use; do_discard() issues discards +* whenever there's work to do and is called by free_some_buckets() and +* when a discard finishes. +*/ +struct list_head discards; +struct page *discard_page; + +struct journal_device journal; + +/* The rest of this all shows up in sysfs */ +#define IO_ERROR_SHIFT 20 +atomic_t io_errors; +atomic_t io_count; + +atomic_long_t meta_sectors_written; +atomic_long_t btree_sectors_written; +atomic_long_t sectors_written; +}; + +struct gc_stat { +size_t nodes; +size_t key_bytes; + +size_t nkeys; +uint64_t data;/* sectors */ +uint64_t dirty;/* sectors */ +unsigned in_use;/* percent */ +}; + +struct cache_set { +struct closure cl; + +struct list_head list; +struct kobject kobj; +struct kobject internal; +struct dentry *debug; +struct cache_accounting accounting; + +/* +* If nonzero, we're trying to detach from all the devices we're +* caching; otherwise we're merely closing +*/ +atomic_t unregistering; +atomic_t closing; + +struct cache_sb sb; + +struct cache *cache[MAX_CACHES_PER_SET ]; +struct cache *cache_by_alloc[MAX_CACHES_PER_SET ]; +int caches_loaded; + +struct bcache_device **devices; +struct list_head cached_devs; +uint64_t cached_dev_sectors; +struct closure caching; + +struct closure_with_waitlist sb_write; + +mempool_t *search; +mempool_t *bio_meta; +struct bio_set *bio_split; + +/* For the btree cache */ +struct shrinker shrink; + +/* For the btree cache and anything allocation related */ +struct mutex bucket_lock; + +/* log2(bucket_size), in sectors */ +unsigned short bucket_bits; + +/* log2(block_size), in sectors */ +unsigned short block_bits; + +/* +* Default number of pages for a new btree node - may be less than a +* full bucket +*/ +unsigned btree_pages; + +/* +* Lists of struct btrees; lru is the list for structs that have memory +* allocated for actual btree node, freed is for structs that do not. +* +* We never free a struct btree, except on shutdown - we just put it on +* the btree_cache_freed list and reuse it later. This simplifies the +* code, and it doesn't cost us much memory as the memory usage is +* dominated by buffers that hold the actual btree node data and those +* can be freed - and the number of struct btrees allocated is +* effectively bounded. +* +* btree_cache_freeable effectively is a small cache - we use it because +* high order page allocations can be rather expensive, and it's quite +* common to delete and allocate btree nodes in quick succession. It +* should never grow past ~2-3 nodes in practice. +*/ +struct list_head btree_cache; +struct list_head btree_cache_freeable; +struct list_head btree_cache_freed; + +/* Number of elements in btree_cache + btree_cache_freeable lists */ +unsigned bucket_cache_used; + +/* +* If we need to allocate memory for a new btree node and that +* allocation fails, we can cannibalize another node in the btree cache +* to satisfy the allocation. However, only one thread can be doing this +* at a time, for obvious reasons - try_harder and try_wait are +* basically a lock for this that we can wait on asynchronously. The +* btree_root() macro releases the lock when it returns. +*/ +struct closure *try_harder; +struct closure_waitlist try_wait; +uint64_t try_harder_start; + +/* +* When we free a btree node, we increment the gen of the bucket the +* node is in - but we can't rewrite the prios and gens until we +* finished whatever it is we were doing, otherwise after a crash the +* btree node would be freed but for say a split, we might not have the +* pointers to the new nodes inserted into the btree yet. +* +* This is a refcount that blocks prio_write() until the new keys are +* written. +*/ +atomic_t prio_blocked; +struct closure_waitlist bucket_wait; + +/* +* For any bio we don't skip we subtract the number of sectors from +* rescale; when it hits 0 we rescale all the bucket priorities. +*/ +atomic_t rescale; +/* +* When we invalidate buckets, we use both the priority and the amount +* of good data to determine which buckets to reuse first - to weight +* those together consistently we keep track of the smallest nonzero +* priority of any bucket. +*/ +uint16_t min_prio; + +/* +* max(gen - gc_gen) for all buckets. When it gets too big we have to gc +* to keep gens from wrapping around. +*/ +uint8_t need_gc; +struct gc_stat gc_stats; +size_t nbuckets; + +struct closure_with_waitlist gc; +/* Where in the btree gc currently is */ +struct bkey gc_done; + +/* +* The allocation code needs gc_mark in struct bucket to be correct, but +* it's not while a gc is in progress. Protected by bucket_lock. +*/ +int gc_mark_valid; + +/* Counts how many sectors bio_insert has added to the cache */ +atomic_t sectors_to_gc; + +struct closure moving_gc; +struct closure_waitlist moving_gc_wait; +struct keybuf moving_gc_keys; +/* Number of moving GC bios in flight */ +atomic_t in_flight; + +struct btree *root; + +#ifdef CONFIG_BCACHE_DEBUG +struct btree *verify_data; +struct mutex verify_lock; +#endif + +unsigned nr_uuids; +struct uuid_entry *uuids; +BKEY_PADDED (uuid_bucket); +struct closure_with_waitlist uuid_write; + +/* +* A btree node on disk could have too many bsets for an iterator to fit +* on the stack - this is a single element mempool for btree_read_work() +*/ +struct mutex fill_lock; +struct btree_iter *fill_iter; + +/* +* btree_sort() is a merge sort and requires temporary space - single +* element mempool +*/ +struct mutex sort_lock; +struct bset *sort; + +/* List of buckets we're currently writing data to */ +struct list_head data_buckets; +spinlock_t data_bucket_lock; + +struct journal journal; + +#define CONGESTED_MAX 1024 +unsigned congested_last_us; +atomic_t congested; + +/* The rest of this all shows up in sysfs */ +unsigned congested_read_threshold_us; +unsigned congested_write_threshold_us; + +spinlock_t sort_time_lock; +struct time_stats sort_time; +struct time_stats btree_gc_time; +struct time_stats btree_split_time; +spinlock_t btree_read_time_lock; +struct time_stats btree_read_time; +struct time_stats try_harder_time; + +atomic_long_t cache_read_races; +atomic_long_t writeback_keys_done; +atomic_long_t writeback_keys_failed; +unsigned error_limit; +unsigned error_decay; +unsigned short journal_delay_ms; +unsigned verify:1 ; +unsigned key_merging_disabled:1 ; +unsigned gc_always_rewrite:1 ; +unsigned shrinker_disabled:1 ; +unsigned copy_gc_enabled:1 ; + +#define BUCKET_HASH_BITS 12 +struct hlist_head bucket_hash[1 <<BUCKET_HASH_BITS ]; +}; + +static inline bool key_merging_disabled (struct cache_set *c) +{ +#ifdef CONFIG_BCACHE_DEBUG +return c->key_merging_disabled; +#else +return 0 ; +#endif +} + +struct bbio { +unsigned submit_time_us; +union { +struct bkey key; +uint64_t _pad[3 ]; +/* +* We only need pad = 3 here because we only ever carry around a +* single pointer - i.e. the pointer we're doing io to/from. +*/ + }; +struct bio bio; +}; + +static inline unsigned local_clock_us (void ) +{ +return local_clock () >>10 ; +} + +#define MAX_BSETS 4 + +#define BTREE_PRIO USHRT_MAX +#define INITIAL_PRIO 32768 + +#define btree_bytes (c) ((c)->btree_pages * PAGE_SIZE) +#define btree_blocks (b) \ + ((unsigned) (KEY_SIZE(&b->key) >> (b)->c->block_bits)) + +#define btree_default_blocks (c) \ + ((unsigned) ((PAGE_SECTORS * (c)->btree_pages) >> (c)->block_bits)) + +#define bucket_pages (c) ((c)->sb.bucket_size / PAGE_SECTORS) +#define bucket_bytes (c) ((c)->sb.bucket_size << 9) +#define block_bytes (c) ((c)->sb.block_size << 9) + +#define __set_bytes (i, k) (sizeof(*(i)) + (k) * sizeof(uint64_t)) +#define set_bytes (i) __set_bytes(i, i->keys) + +#define __set_blocks (i, k, c) DIV_ROUND_UP(__set_bytes(i, k), block_bytes(c)) +#define set_blocks (i, c) __set_blocks(i, (i)->keys, c) + +#define node (i, j) ((struct bkey *) ((i)->d + (j))) +#define end (i) node(i, (i)->keys) + +#define index (i, b) \ + ((size_t) (((void *) i - (void *) (b)->sets[0].data) / \ + block_bytes(b->c))) + +#define btree_data_space (b) (PAGE_SIZE << (b)->page_order) + +#define prios_per_bucket (c) \ + ((bucket_bytes(c) - sizeof(struct prio_set)) / \ + sizeof(struct bucket_disk)) +#define prio_buckets (c) \ + DIV_ROUND_UP((size_t) (c)->sb.nbuckets, prios_per_bucket(c)) + +#define JSET_MAGIC 0x245235c1a3625032ULL +#define PSET_MAGIC 0x6750e15f87337f91ULL +#define BSET_MAGIC 0x90135c78b99e07f5ULL + +#define jset_magic (c) ((c)->sb.set_magic ^ JSET_MAGIC) +#define pset_magic (c) ((c)->sb.set_magic ^ PSET_MAGIC) +#define bset_magic (c) ((c)->sb.set_magic ^ BSET_MAGIC) + +/* Bkey fields: all units are in sectors */ + +#define KEY_FIELD (name, field, offset, size) \ + BITMASK(name, struct bkey, field, offset, size) + +#define PTR_FIELD (name, offset, size) \ + static inline uint64_t name(const struct bkey *k, unsigned i) \ + { return (k->ptr[i] >> offset) & ~(((uint64_t) ~0) << size); } \ + \ + static inline void SET_##name(struct bkey *k, unsigned i, uint64_t v)\ + { \ + k->ptr[i] &= ~(~((uint64_t) ~0 << size) << offset); \ + k->ptr[i] |= v << offset; \ + } + +KEY_FIELD(KEY_PTRS, high, 60, 3) +KEY_FIELD(HEADER_SIZE, high, 58, 2) +KEY_FIELD(KEY_CSUM, high, 56, 2) +KEY_FIELD(KEY_PINNED, high, 55, 1) +KEY_FIELD(KEY_DIRTY, high, 36, 1) + +KEY_FIELD(KEY_SIZE, high, 20, 16) +KEY_FIELD (KEY_INODE , high,0 ,20 ) + +/* Next time I change the on disk format, KEY_OFFSET() won't be 64 bits */ + +static inline uint64_t KEY_OFFSET (const struct bkey *k) +{ +return k->low; +} + +static inline void SET_KEY_OFFSET (struct bkey *k,uint64_t v) +{ + k->low = v; +} + +PTR_FIELD(PTR_DEV, 51, 12) +PTR_FIELD(PTR_OFFSET, 8, 43) +PTR_FIELD(PTR_GEN, 0, 8) + +#define PTR_CHECK_DEV ((1 << 12) - 1) + +#define PTR (gen, offset, dev) \ + ((((uint64_t) dev) << 51) | ((uint64_t) offset) << 8 | gen) + +static inline size_t sector_to_bucket (struct cache_set *c,sector_t s) +{ +return s >> c->bucket_bits; +} + +static inline sector_t bucket_to_sector (struct cache_set *c,size_t b) +{ +return ((sector_t ) b) << c->bucket_bits; +} + +static inline sector_t bucket_remainder (struct cache_set *c,sector_t s) +{ +return s & (c->sb.bucket_size -1 ); +} + +static inline struct cache *PTR_CACHE (struct cache_set *c, +const struct bkey *k, +unsigned ptr) +{ +return c->cache[PTR_DEV (k, ptr)]; +} + +static inline size_t PTR_BUCKET_NR (struct cache_set *c, +const struct bkey *k, +unsigned ptr) +{ +return sector_to_bucket (c,PTR_OFFSET (k, ptr)); +} + +static inline struct bucket *PTR_BUCKET (struct cache_set *c, +const struct bkey *k, +unsigned ptr) +{ +return PTR_CACHE (c, k, ptr)->buckets +PTR_BUCKET_NR (c, k, ptr); +} + +/* Btree key macros */ + +/* +* The high bit being set is a relic from when we used it to do binary +* searches - it told you where a key started. It's not used anymore, +* and can probably be safely dropped. +*/ +#define KEY (dev, sector, len) (struct bkey) \ +{ \ + .high = (1ULL << 63) | ((uint64_t) (len) << 20) | (dev), \ + .low = (sector) \ +} + +static inline void bkey_init (struct bkey *k) +{ + *k =KEY (0 ,0 ,0 ); +} + +#define KEY_START (k) (KEY_OFFSET(k) - KEY_SIZE(k)) +#define START_KEY (k) KEY(KEY_INODE(k), KEY_START(k), 0) +#define MAX_KEY KEY(~(~0 << 20), ((uint64_t) ~0) >> 1, 0) +#define ZERO_KEY KEY(0, 0, 0) + +/* +* This is used for various on disk data structures - cache_sb, prio_set, bset, +* jset: The checksum is _always_ the first 8 bytes of these structs +*/ +#define csum_set (i) \ + crc64(((void *) (i)) + sizeof(uint64_t), \ + ((void *) end(i)) - (((void *) (i)) + sizeof(uint64_t))) + +/* Error handling macros */ + +#define btree_bug (b, ...) \ +do { \ + if (bch_cache_set_error((b)->c, __VA_ARGS__)) \ + dump_stack(); \ +} while (0) + +#define cache_bug (c, ...) \ +do { \ + if (bch_cache_set_error(c, __VA_ARGS__)) \ + dump_stack(); \ +} while (0) + +#define btree_bug_on (cond, b, ...) \ +do { \ + if (cond) \ + btree_bug(b, __VA_ARGS__); \ +} while (0) + +#define cache_bug_on (cond, c, ...) \ +do { \ + if (cond) \ + cache_bug(c, __VA_ARGS__); \ +} while (0) + +#define cache_set_err_on (cond, c, ...) \ +do { \ + if (cond) \ + bch_cache_set_error(c, __VA_ARGS__); \ +} while (0) + +/* Looping macros */ + +#define for_each_cache (ca, cs) \ + for (int _i = 0; ca = cs->cache[_i], _i < (cs)->sb.nr_in_set; _i++) + +#define for_each_bucket (b, ca) \ + for (b = (ca)->buckets + (ca)->sb.first_bucket; \ + b < (ca)->buckets + (ca)->sb.nbuckets; b++) + +static inline void __bkey_put (struct cache_set *c,struct bkey *k) +{ +unsigned i; + +for (i =0 ; i <KEY_PTRS (k); i++) +atomic_dec_bug (&PTR_BUCKET (c, k, i)->pin); +} + +/* Blktrace macros */ + +#define blktrace_msg (c, fmt, ...) \ +do { \ + struct request_queue *q = bdev_get_queue(c->bdev); \ + if (q) \ + blk_add_trace_msg(q, fmt, ##__VA_ARGS__); \ +} while (0) + +#define blktrace_msg_all (s, fmt, ...) \ +do { \ + struct cache *_c; \ + for_each_cache(_c, (s)) \ + blktrace_msg(_c, fmt, ##__VA_ARGS__); \ +} while (0) + +#define err_printk (...) printk(KERN_ERR "bcache: " __VA_ARGS__) + +static inline void cached_dev_put (struct cached_dev *dc) +{ +if (atomic_dec_and_test (&dc->count)) +schedule_work (&dc->detach); +} + +static inline bool cached_dev_get (struct cached_dev *dc) +{ +if (!atomic_inc_not_zero (&dc->count)) +return false; + +/* Paired with the mb in cached_dev_attach */ +smp_mb__after_atomic_inc (); +return true; +} + +/* +* bucket_gc_gen() returns the difference between the bucket's current gen and +* the oldest gen of any pointer into that bucket in the btree (last_gc). +* +* bucket_disk_gen() returns the difference between the current gen and the gen +* on disk; they're both used to make sure gens don't wrap around. +*/ + +static inline uint8_t bucket_gc_gen (struct bucket *b) +{ +return b->gen - b->last_gc; +} + +static inline uint8_t bucket_disk_gen (struct bucket *b) +{ +return b->gen - b->disk_gen; +} + +#define BUCKET_GC_GEN_MAX 96U +#define BUCKET_DISK_GEN_MAX 64U + +#define kobj_attribute_write (n, fn) \ + static struct kobj_attribute ksysfs_##n = __ATTR(n, S_IWUSR, NULL, fn) + +#define kobj_attribute_rw (n, show, store) \ + static struct kobj_attribute ksysfs_##n = \ + __ATTR(n, S_IWUSR|S_IRUSR, show, store) + +/* Forward declarations */ + +void bch_writeback_queue (struct cached_dev *); +void bch_writeback_add (struct cached_dev *,unsigned ); + +void bch_count_io_errors (struct cache *,int ,const char *); +void bch_bbio_count_io_errors (struct cache_set *,struct bio *,int ,const char *); +void bch_bbio_endio (struct cache_set *,struct bio *,int ,const char *); +void bch_bbio_free (struct bio *,struct cache_set *); +struct bio *bch_bbio_alloc (struct cache_set *); + +void __bch_submit_bbio (struct bio *,struct cache_set *); +void bch_submit_bbio (struct bio *,struct cache_set *,struct bkey *,unsigned ); + +uint8_t bch_inc_gen (struct cache *,struct bucket *); +void bch_rescale_priorities (struct cache_set *,int ); +bool bch_bucket_add_unused (struct cache *,struct bucket *); +bool bch_can_save_prios (struct cache *); +void bch_free_some_buckets (struct cache *); +void bch_bucket_free (struct cache_set *,struct bkey *); +int __bch_bucket_alloc_set (struct cache_set *,int ,uint16_t , +struct bkey *,int ,struct closure *); +int bch_bucket_alloc_set (struct cache_set *,int ,uint16_t , +struct bkey *,int ,struct closure *); + +__printf(2, 3) +bool bch_cache_set_error (struct cache_set *,const char *, ...); + +void bch_prio_write (struct cache *); +void bch_write_bdev_super (struct cached_dev *,struct closure *); + +extern struct workqueue_struct *bcache_wq, *bch_gc_wq; +extern const char *const bch_cache_modes[]; + +struct cache_set *bch_cache_set_alloc (struct cache_sb *); +void bch_free_discards (struct cache *); +int bch_alloc_discards (struct cache *); +void bch_btree_cache_free (struct cache_set *); +int bch_btree_cache_alloc (struct cache_set *); +void bch_writeback_init_cached_dev (struct cached_dev *); +void bch_moving_init_cache_set (struct cache_set *); + +void bch_debug_exit (void ); +int bch_debug_init (struct kobject *); +void bch_writeback_exit (void ); +int bch_writeback_init (void ); +void bch_request_exit (void ); +int bch_request_init (void ); +void bch_btree_exit (void ); +int bch_btree_init (void ); + +#endif /* _BCACHE_H */
drivers/md/bcache/btree.c new file +2508 -0
1,858 lines not on this page · raw message
drivers/md/bcache/btree.h new file +423 -0
423 lines not on this page · raw message
The rest of this diff is not shown. View the raw message.
Signature · 1 line
1.7.7.3
Part of the diff is not shown here. View the raw message.
PATCH v15 12/16 bcache: Bset code (lookups within a btree node)
In reply to Kent Overstreet--- drivers/md/bcache/bset.c | 1165 ++++++++++++++++++++++++++++++++++++++++++++++ drivers/md/bcache/bset.h | 372 +++++++++++++++ 2 files changed, 1537 insertions(+), 0 deletions(-) create mode 100644 drivers/md/bcache/bset.c create mode 100644 drivers/md/bcache/bset.h
drivers/md/bcache/bset.c new file +1165 -0
@@ -0,0 +1,1165 @@ + +#include "bcache.h" +#include "btree.h" +#include "debug.h" + +#include <linux/random.h> + +/* Keylists */ + +void bch_keylist_copy (struct keylist *dest,struct keylist *src) +{ + *dest = *src; + +if (src->list == src->d) { +size_t n = (uint64_t *) src->top - src->d; + dest->top = (struct bkey *) &dest->d[n]; + dest->list = dest->d; + } +} + +int bch_keylist_realloc (struct keylist *l,int nptrs,struct cache_set *c) +{ +unsigned oldsize = (uint64_t *) l->top - l->list; +unsigned newsize = oldsize +2 + nptrs; +uint64_t *new; + +/* The journalling code doesn't handle the case where the keys to insert +* is bigger than an empty write: If we just return -ENOMEM here, +* bio_insert() and bio_invalidate() will insert the keys created so far +* and finish the rest when the keylist is empty. +*/ +if (newsize *sizeof (uint64_t ) >block_bytes (c) -sizeof (struct jset )) +return -ENOMEM ; + + newsize =roundup_pow_of_two (newsize); + +if (newsize <=KEYLIST_INLINE || +roundup_pow_of_two (oldsize) == newsize) +return 0 ; + + new =krealloc (l->list == l->d ?NULL : l->list, +sizeof (uint64_t ) * newsize,GFP_NOIO ); + +if (!new) +return -ENOMEM ; + +if (l->list == l->d) +memcpy (new, l->list,sizeof (uint64_t ) *KEYLIST_INLINE ); + + l->list = new; + l->top = (struct bkey *) (&l->list[oldsize]); + +return 0 ; +} + +struct bkey *bch_keylist_pop (struct keylist *l) +{ +struct bkey *k = l->bottom; + +if (k == l->top) +return NULL ; + +while (bkey_next (k) != l->top) + k =bkey_next (k); + +return l->top = k; +} + +/* Pointer validation */ + +bool __bch_ptr_invalid (struct cache_set *c,int level,const struct bkey *k) +{ +if (level && (!KEY_PTRS (k) || !KEY_SIZE (k) ||KEY_DIRTY (k))) + goto bad; + +if (!level &&KEY_SIZE (k) >KEY_OFFSET (k)) + goto bad; + +if (!KEY_SIZE (k)) +return true; + +for (unsigned i =0 ; i <KEY_PTRS (k); i++) +if (ptr_available (c, k, i)) { +struct cache *ca =PTR_CACHE (c, k, i); +size_t bucket =PTR_BUCKET_NR (c, k, i); +size_t r =bucket_remainder (c,PTR_OFFSET (k, i)); + +if (KEY_SIZE (k) + r > c->sb.bucket_size || + bucket < ca->sb.first_bucket || + bucket >= ca->sb.nbuckets) + goto bad; + } + +return false; +bad: +cache_bug (c,"spotted bad key %s: %s" ,pkey (k),bch_ptr_status (c, k)); +return true; +} + +bool bch_ptr_bad (struct btree *b,const struct bkey *k) +{ +struct bucket *g; +unsigned i, stale; + +if (!bkey_cmp (k, &ZERO_KEY ) || + !KEY_PTRS (k) || +bch_ptr_invalid (b, k)) +return true; + +if (KEY_PTRS (k) &&PTR_DEV (k,0 ) ==PTR_CHECK_DEV ) +return true; + +for (i =0 ; i <KEY_PTRS (k); i++) +if (ptr_available (b->c, k, i)) { + g =PTR_BUCKET (b->c, k, i); + stale =ptr_stale (b->c, k, i); + +btree_bug_on (stale >96 , b, +"key too stale: %i, need_gc %u" , + stale, b->c->need_gc); + +btree_bug_on (stale &&KEY_DIRTY (k) &&KEY_SIZE (k), + b,"stale dirty pointer" ); + +if (stale) +return true; + +#ifdef CONFIG_BCACHE_EDEBUG +if (!mutex_trylock (&b->c->bucket_lock)) +continue ; + +if (b->level) { +if (KEY_DIRTY (k) || + g->prio !=BTREE_PRIO || + (b->c->gc_mark_valid && +GC_MARK (g) !=GC_MARK_BTREE )) + goto bug; + + }else { +if (g->prio ==BTREE_PRIO ) + goto bug; + +if (KEY_DIRTY (k) && + b->c->gc_mark_valid && +GC_MARK (g) !=GC_MARK_DIRTY ) + goto bug; + } +mutex_unlock (&b->c->bucket_lock); +#endif + } + +return false; +#ifdef CONFIG_BCACHE_EDEBUG +bug: +mutex_unlock (&b->c->bucket_lock); +btree_bug (b,"inconsistent pointer %s: bucket %li pin %i " +"prio %i gen %i last_gc %i mark %llu gc_gen %i" ,pkey (k), +PTR_BUCKET_NR (b->c, k, i),atomic_read (&g->pin), + g->prio, g->gen, g->last_gc,GC_MARK (g), g->gc_gen); +return true; +#endif +} + +/* Key/pointer manipulation */ + +void bch_bkey_copy_single_ptr (struct bkey *dest,const struct bkey *src,unsigned i) +{ +BUG_ON (i >KEY_PTRS (src)); + +/* Only copy the header, key, and one pointer. */ +memcpy (dest, src,2 *sizeof (uint64_t )); + dest->ptr[0 ] = src->ptr[i]; +SET_KEY_PTRS (dest,1 ); +/* We didn't copy the checksum so clear that bit. */ +SET_KEY_CSUM (dest,0 ); +} + +bool __bch_cut_front (const struct bkey *where,struct bkey *k) +{ +unsigned len =0 ; + +if (bkey_cmp (where, &START_KEY (k)) <=0 ) +return false; + +if (bkey_cmp (where, k) <0 ) + len =KEY_OFFSET (k) -KEY_OFFSET (where); +else +bkey_copy_key (k, where); + +for (unsigned i =0 ; i <KEY_PTRS (k); i++) +SET_PTR_OFFSET (k, i,PTR_OFFSET (k, i) +KEY_SIZE (k) - len); + +BUG_ON (len >KEY_SIZE (k)); +SET_KEY_SIZE (k, len); +return true; +} + +bool __bch_cut_back (const struct bkey *where,struct bkey *k) +{ +unsigned len =0 ; + +if (bkey_cmp (where, k) >=0 ) +return false; + +BUG_ON (KEY_INODE (where) !=KEY_INODE (k)); + +if (bkey_cmp (where, &START_KEY (k)) >0 ) + len =KEY_OFFSET (where) -KEY_START (k); + +bkey_copy_key (k, where); + +BUG_ON (len >KEY_SIZE (k)); +SET_KEY_SIZE (k, len); +return true; +} + +static uint64_t merge_chksums (struct bkey *l,struct bkey *r) +{ +return (l->ptr[KEY_PTRS (l)] + r->ptr[KEY_PTRS (r)]) & + ~((uint64_t )1 <<63 ); +} + +/* Tries to merge l and r: l should be lower than r +* Returns true if we were able to merge. If we did merge, l will be the merged +* key, r will be untouched. +*/ +bool bch_bkey_try_merge (struct btree *b,struct bkey *l,struct bkey *r) +{ +if (key_merging_disabled (b->c)) +return false; + +if (KEY_PTRS (l) !=KEY_PTRS (r) || +KEY_DIRTY (l) !=KEY_DIRTY (r) || +bkey_cmp (l, &START_KEY (r))) +return false; + +for (unsigned j =0 ; j <KEY_PTRS (l); j++) +if (l->ptr[j] +PTR (0 ,KEY_SIZE (l),0 ) != r->ptr[j] || +PTR_BUCKET_NR (b->c, l, j) !=PTR_BUCKET_NR (b->c, r, j)) +return false; + +/* Keys with no pointers aren't restricted to one bucket and could +* overflow KEY_SIZE +*/ +if (KEY_SIZE (l) +KEY_SIZE (r) >USHRT_MAX ) { +SET_KEY_OFFSET (l,KEY_OFFSET (l) +USHRT_MAX -KEY_SIZE (l)); +SET_KEY_SIZE (l,USHRT_MAX ); + +bch_cut_front (l, r); +return false; + } + +if (KEY_CSUM (l)) { +if (KEY_CSUM (r)) + l->ptr[KEY_PTRS (l)] =merge_chksums (l, r); +else +SET_KEY_CSUM (l,0 ); + } + +SET_KEY_OFFSET (l,KEY_OFFSET (l) +KEY_SIZE (r)); +SET_KEY_SIZE (l,KEY_SIZE (l) +KEY_SIZE (r)); + +return true; +} + +/* Binary tree stuff for auxiliary search trees */ + +static unsigned inorder_next (unsigned j,unsigned size) +{ +if (j *2 +1 < size) { + j = j *2 +1 ; + +while (j *2 < size) + j *=2 ; + }else + j >>=ffz (j) +1 ; + +return j; +} + +static unsigned inorder_prev (unsigned j,unsigned size) +{ +if (j *2 < size) { + j = j *2 ; + +while (j *2 +1 < size) + j = j *2 +1 ; + }else + j >>=ffs (j); + +return j; +} + +/* I have no idea why this code works... and I'm the one who wrote it +* +* However, I do know what it does: +* Given a binary tree constructed in an array (i.e. how you normally implement +* a heap), it converts a node in the tree - referenced by array index - to the +* index it would have if you did an inorder traversal. +* +* Also tested for every j, size up to size somewhere around 6 million. +* +* The binary tree starts at array index 1, not 0 +* extra is a function of size: +* extra = (size - rounddown_pow_of_two(size - 1)) << 1; +*/ +static unsigned __to_inorder (unsigned j,unsigned size,unsigned extra) +{ +unsigned b =fls (j); +unsigned shift =fls (size -1 ) - b; + + j ^=1U << (b -1 ); + j <<=1 ; + j |=1 ; + j <<= shift; + +if (j > extra) + j -= (j - extra) >>1 ; + +return j; +} + +static unsigned to_inorder (unsigned j,struct bset_tree *t) +{ +return __to_inorder (j, t->size, t->extra); +} + +static unsigned __inorder_to_tree (unsigned j,unsigned size,unsigned extra) +{ +unsigned shift; + +if (j > extra) + j += j - extra; + + shift =ffs (j); + + j >>= shift; + j |=roundup_pow_of_two (size) >> shift; + +return j; +} + +static unsigned inorder_to_tree (unsigned j,struct bset_tree *t) +{ +return __inorder_to_tree (j, t->size, t->extra); +} + +#if 0 +void inorder_test (void ) +{ +unsigned long done =0 ; +ktime_t start =ktime_get (); + +for (unsigned size =2 ; + size <65536000 ; + size++) { +unsigned extra = (size -rounddown_pow_of_two (size -1 )) <<1 ; +unsigned i =1 , j =rounddown_pow_of_two (size -1 ); + +if (!(size %4096 )) +printk (KERN_NOTICE "loop %u, %llu per us\n" , size, + done /ktime_us_delta (ktime_get (), start)); + +while (1 ) { +if (__inorder_to_tree (i, size, extra) != j) +panic ("size %10u j %10u i %10u" , size, j, i); + +if (__to_inorder (j, size, extra) != i) +panic ("size %10u j %10u i %10u" , size, j, i); + +if (j ==rounddown_pow_of_two (size) -1 ) +break ; + +BUG_ON (inorder_prev (inorder_next (j, size), size) != j); + + j =inorder_next (j, size); + i++; + } + + done += size -1 ; + } +} +#endif + +/* +* Cacheline/offset <-> bkey pointer arithmatic: +* +* t->tree is a binary search tree in an array; each node corresponds to a key +* in one cacheline in t->set (BSET_CACHELINE bytes). +* +* This means we don't have to store the full index of the key that a node in +* the binary tree points to; to_inorder() gives us the cacheline, and then +* bkey_float->m gives us the offset within that cacheline, in units of 8 bytes. +* +* cacheline_to_bkey() and friends abstract out all the pointer arithmatic to +* make this work. +* +* To construct the bfloat for an arbitrary key we need to know what the key +* immediately preceding it is: we have to check if the two keys differ in the +* bits we're going to store in bkey_float->mantissa. t->prev[j] stores the size +* of the previous key so we can walk backwards to it from t->tree[j]'s key. +*/ + +static struct bkey *cacheline_to_bkey (struct bset_tree *t,unsigned cacheline, +unsigned offset) +{ +return ((void *) t->data) + cacheline *BSET_CACHELINE + offset *8 ; +} + +static unsigned bkey_to_cacheline (struct bset_tree *t,struct bkey *k) +{ +return ((void *) k - (void *) t->data) /BSET_CACHELINE ; +} + +static unsigned bkey_to_cacheline_offset (struct bkey *k) +{ +return ((size_t ) k & (BSET_CACHELINE -1 )) /sizeof (uint64_t ); +} + +static struct bkey *tree_to_bkey (struct bset_tree *t,unsigned j) +{ +return cacheline_to_bkey (t,to_inorder (j, t), t->tree[j].m); +} + +static struct bkey *tree_to_prev_bkey (struct bset_tree *t,unsigned j) +{ +return (void *) (((uint64_t *)tree_to_bkey (t, j)) - t->prev[j]); +} + +/* +* For the write set - the one we're currently inserting keys into - we don't +* maintain a full search tree, we just keep a simple lookup table in t->prev. +*/ +static struct bkey *table_to_bkey (struct bset_tree *t,unsigned cacheline) +{ +return cacheline_to_bkey (t, cacheline, t->prev[cacheline]); +} + +static inline uint64_t shrd128 (uint64_t high,uint64_t low,uint8_t shift) +{ +#ifdef CONFIG_X86_64 + asm("shrd %[shift],%[high],%[low]" + : [low]"+Rm" (low) + : [high]"R" (high), + [shift]"ci" (shift) + :"cc" ); +#else + low >>= shift; + low |= (high <<1 ) << (63U - shift); +#endif +return low; +} + +static inline unsigned bfloat_mantissa (const struct bkey *k, +struct bkey_float *f) +{ +const uint64_t *p = &k->low - (f->exponent >>6 ); +return shrd128 (p[-1 ], p[0 ], f->exponent &63 ) &BKEY_MANTISSA_MASK ; +} + +static void make_bfloat (struct bset_tree *t,unsigned j) +{ +struct bkey_float *f = &t->tree[j]; +struct bkey *m =tree_to_bkey (t, j); +struct bkey *p =tree_to_prev_bkey (t, j); + +struct bkey *l =is_power_of_2 (j) + ? t->data->start + :tree_to_prev_bkey (t, j >>ffs (j)); + +struct bkey *r =is_power_of_2 (j +1 ) + ?node (t->data, t->data->keys -bkey_u64s (&t->end)) + :tree_to_bkey (t, j >> (ffz (j) +1 )); + +BUG_ON (m < l || m > r); +BUG_ON (bkey_next (p) != m); + +if (KEY_INODE (l) !=KEY_INODE (r)) + f->exponent =fls64 (KEY_INODE (r) ^KEY_INODE (l)) +64 ; +else + f->exponent =fls64 (r->low ^ l->low); + + f->exponent =max_t (int, f->exponent -BKEY_MANTISSA_BITS ,0 ); + +/* +* Setting f->exponent = 127 flags this node as failed, and causes the +* lookup code to fall back to comparing against the original key. +*/ + +if (bfloat_mantissa (m, f) !=bfloat_mantissa (p, f)) + f->mantissa =bfloat_mantissa (m, f) -1 ; +else + f->exponent =127 ; +} + +static void bset_alloc_tree (struct btree *b,struct bset_tree *t) +{ +if (t != b->sets) { +unsigned j =roundup (t[-1 ].size, +64 /sizeof (struct bkey_float )); + + t->tree = t[-1 ].tree + j; + t->prev = t[-1 ].prev + j; + } + +while (t < b->sets +MAX_BSETS ) + t++->size =0 ; +} + +static void bset_build_unwritten_tree (struct btree *b) +{ +struct bset_tree *t = b->sets + b->nsets; + +bset_alloc_tree (b, t); + +if (t->tree != b->sets->tree +bset_tree_space (b)) { + t->prev[0 ] =bkey_to_cacheline_offset (t->data->start); + t->size =1 ; + } +} + +static void bset_build_written_tree (struct btree *b) +{ +struct bset_tree *t = b->sets + b->nsets; +struct bkey *k = t->data->start; +unsigned j, cacheline =1 ; + +bset_alloc_tree (b, t); + + t->size =min_t (unsigned, +bkey_to_cacheline (t,end (t->data)), + b->sets->tree +bset_tree_space (b) - t->tree); + +if (t->size <2 ) { + t->size =0 ; +return ; + } + + t->extra = (t->size -rounddown_pow_of_two (t->size -1 )) <<1 ; + +/* First we figure out where the first key in each cacheline is */ +for (j =inorder_next (0 , t->size); + j; + j =inorder_next (j, t->size)) { +while (bkey_to_cacheline (t, k) != cacheline) + k =bkey_next (k); + + t->prev[j] =bkey_u64s (k); + k =bkey_next (k); + cacheline++; + t->tree[j].m =bkey_to_cacheline_offset (k); + } + +while (bkey_next (k) !=end (t->data)) + k =bkey_next (k); + + t->end = *k; + +/* Then we build the tree */ +for (j =inorder_next (0 , t->size); + j; + j =inorder_next (j, t->size)) +make_bfloat (t, j); +} + +void bch_bset_fix_invalidated_key (struct btree *b,struct bkey *k) +{ +struct bset_tree *t; +unsigned inorder, j =1 ; + +for (t = b->sets; t <= &b->sets[b->nsets]; t++) +if (k <end (t->data)) + goto found_set; + +BUG (); +found_set: +if (!t->size || !bset_written (b, t)) +return ; + + inorder =bkey_to_cacheline (t, k); + +if (k == t->data->start) + goto fix_left; + +if (bkey_next (k) ==end (t->data)) { + t->end = *k; + goto fix_right; + } + + j =inorder_to_tree (inorder, t); + +if (j && + j < t->size && + k ==tree_to_bkey (t, j)) +fix_left:do { +make_bfloat (t, j); + j = j *2 ; + }while (j < t->size); + + j =inorder_to_tree (inorder +1 , t); + +if (j && + j < t->size && + k ==tree_to_prev_bkey (t, j)) +fix_right:do { +make_bfloat (t, j); + j = j *2 +1 ; + }while (j < t->size); +} + +void bch_bset_fix_lookup_table (struct btree *b,struct bkey *k) +{ +struct bset_tree *t = &b->sets[b->nsets]; +unsigned shift =bkey_u64s (k); +unsigned j =bkey_to_cacheline (t, k); + +/* We're getting called from btree_split() or btree_gc, just bail out */ +if (!t->size) +return ; + +/* k is the key we just inserted; we need to find the entry in the +* lookup table for the first key that is strictly greater than k: +* it's either k's cacheline or the next one +*/ +if (j < t->size && +table_to_bkey (t, j) <= k) + j++; + +/* Adjust all the lookup table entries, and find a new key for any that +* have gotten too big +*/ +for (; j < t->size; j++) { + t->prev[j] += shift; + +if (t->prev[j] >7 ) { + k =table_to_bkey (t, j -1 ); + +while (k <cacheline_to_bkey (t, j,0 )) + k =bkey_next (k); + + t->prev[j] =bkey_to_cacheline_offset (k); + } + } + +if (t->size == b->sets->tree +bset_tree_space (b) - t->tree) +return ; + +/* Possibly add a new entry to the end of the lookup table */ + +for (k =table_to_bkey (t, t->size -1 ); + k !=end (t->data); + k =bkey_next (k)) +if (t->size ==bkey_to_cacheline (t, k)) { + t->prev[t->size] =bkey_to_cacheline_offset (k); + t->size++; + } +} + +void bch_bset_init_next (struct btree *b) +{ +struct bset *i =write_block (b); + +if (i != b->sets[0 ].data) { + b->sets[++b->nsets].data = i; + i->seq = b->sets[0 ].data->seq; + }else +get_random_bytes (&i->seq,sizeof (uint64_t )); + + i->magic =bset_magic (b->c); + i->version =0 ; + i->keys =0 ; + +bset_build_unwritten_tree (b); +} + +struct bset_search_iter { +struct bkey *l, *r; +}; + +static struct bset_search_iter bset_search_write_set (struct btree *b, +struct bset_tree *t, +const struct bkey *search) +{ +unsigned li =0 , ri = t->size; + +BUG_ON (!b->nsets && + t->size <bkey_to_cacheline (t,end (t->data))); + +while (li +1 != ri) { +unsigned m = (li + ri) >>1 ; + +if (bkey_cmp (table_to_bkey (t, m), search) >0 ) + ri = m; +else + li = m; + } + +return (struct bset_search_iter ) { +table_to_bkey (t, li), + ri < t->size ?table_to_bkey (t, ri) :end (t->data) + }; +} + +static struct bset_search_iter bset_search_tree (struct btree *b, +struct bset_tree *t, +const struct bkey *search) +{ +struct bkey *l, *r; +struct bkey_float *f; +unsigned inorder, j, n =1 ; + +do { +unsigned p = n <<4 ; + p &= ((int ) (p - t->size)) >>31 ; + +prefetch (&t->tree[p]); + + j = n; + f = &t->tree[j]; + +/* +* n = (f->mantissa > bfloat_mantissa()) +* ? j * 2 +* : j * 2 + 1; +* +* We need to subtract 1 from f->mantissa for the sign bit trick +* to work - that's done in make_bfloat() +*/ +if (likely (f->exponent !=127 )) + n = j *2 + (((unsigned ) + (f->mantissa - +bfloat_mantissa (search, f))) >>31 ); +else + n = (bkey_cmp (tree_to_bkey (t, j), search) >0 ) + ? j *2 + : j *2 +1 ; + }while (n < t->size); + + inorder =to_inorder (j, t); + +/* +* n would have been the node we recursed to - the low bit tells us if +* we recursed left or recursed right. +*/ +if (n &1 ) { + l =cacheline_to_bkey (t, inorder, f->m); + +if (++inorder != t->size) { + f = &t->tree[inorder_next (j, t->size)]; + r =cacheline_to_bkey (t, inorder, f->m); + }else + r =end (t->data); + }else { + r =cacheline_to_bkey (t, inorder, f->m); + +if (--inorder) { + f = &t->tree[inorder_prev (j, t->size)]; + l =cacheline_to_bkey (t, inorder, f->m); + }else + l = t->data->start; + } + +return (struct bset_search_iter ) {l, r}; +} + +struct bkey *__bch_bset_search (struct btree *b,struct bset_tree *t, +const struct bkey *search) +{ +struct bset_search_iter i; + +/* +* First, we search for a cacheline, then lastly we do a linear search +* within that cacheline. +* +* To search for the cacheline, there's three different possibilities: +* * The set is too small to have a search tree, so we just do a linear +* search over the whole set. +* * The set is the one we're currently inserting into; keeping a full +* auxiliary search tree up to date would be too expensive, so we +* use a much simpler lookup table to do a binary search - +* bset_search_write_set(). +* * Or we use the auxiliary search tree we constructed earlier - +* bset_search_tree() +*/ + +if (unlikely (!t->size)) { + i.l = t->data->start; + i.r =end (t->data); + }else if (bset_written (b, t)) { +/* +* Each node in the auxiliary search tree covers a certain range +* of bits, and keys above and below the set it covers might +* differ outside those bits - so we have to special case the +* start and end - handle that here: +*/ + +if (unlikely (bkey_cmp (search, &t->end) >=0 )) +return end (t->data); + +if (unlikely (bkey_cmp (search, t->data->start) <0 )) +return t->data->start; + + i =bset_search_tree (b, t, search); + }else + i =bset_search_write_set (b, t, search); + +#ifdef CONFIG_BCACHE_EDEBUG +BUG_ON (bset_written (b, t) && + i.l != t->data->start && +bkey_cmp (tree_to_prev_bkey (t, +inorder_to_tree (bkey_to_cacheline (t, i.l), t)), + search) >0 ); + +BUG_ON (i.r !=end (t->data) && +bkey_cmp (i.r, search) <=0 ); +#endif + +while (likely (i.l != i.r) && +bkey_cmp (i.l, search) <=0 ) + i.l =bkey_next (i.l); + +return i.l; +} + +/* Btree iterator */ + +static inline bool btree_iter_cmp (struct btree_iter_set l, +struct btree_iter_set r) +{ +int64_t c =bkey_cmp (&START_KEY (l.k), &START_KEY (r.k)); + +return c ? c >0 : l.k < r.k; +} + +static inline bool btree_iter_end (struct btree_iter *iter) +{ +return !iter->used; +} + +void bch_btree_iter_push (struct btree_iter *iter,struct bkey *k,struct bkey *end) +{ +if (k != end) +BUG_ON (!heap_add (iter, + ((struct btree_iter_set ) { k, end }), + btree_iter_cmp)); +} + +struct bkey *__bch_btree_iter_init (struct btree *b,struct btree_iter *iter, +struct bkey *search,struct bset_tree *start) +{ +struct bkey *ret =NULL ; + iter->size =ARRAY_SIZE (iter->data); + iter->used =0 ; + +for (; start <= &b->sets[b->nsets]; start++) { + ret =bch_bset_search (b, start, search); +bch_btree_iter_push (iter, ret,end (start->data)); + } + +return ret; +} + +struct bkey *bch_btree_iter_next (struct btree_iter *iter) +{ +struct btree_iter_set unused; +struct bkey *ret =NULL ; + +if (!btree_iter_end (iter)) { + ret = iter->data->k; + iter->data->k =bkey_next (iter->data->k); + +if (iter->data->k > iter->data->end) { +__WARN (); + iter->data->k = iter->data->end; + } + +if (iter->data->k == iter->data->end) +heap_pop (iter, unused, btree_iter_cmp); +else +heap_sift (iter,0 , btree_iter_cmp); + } + +return ret; +} + +struct bkey *bch_next_recurse_key (struct btree *b,struct bkey *search) +{ +struct bkey *ret; +struct btree_iter iter; +bch_btree_iter_init (b, &iter, search); + +do + ret =bch_btree_iter_next (&iter); +while (ret &&bch_ptr_bad (b, ret)); + +return ret; +} + +/* Mergesort */ + +static void btree_sort_fixup (struct btree_iter *iter) +{ +while (iter->used >1 ) { +struct btree_iter_set *top = iter->data, *i = top +1 ; +struct bkey *k; + +if (iter->used >2 && +btree_iter_cmp (i[0 ], i[1 ])) + i++; + +for (k = i->k; + k != i->end &&bkey_cmp (top->k, &START_KEY (k)) >0 ; + k =bkey_next (k)) +if (top->k > i->k) +__bch_cut_front (top->k, k); +else if (KEY_SIZE (k)) +bch_cut_back (&START_KEY (k), top->k); + +if (top->k < i->k || k == i->k) +break ; + +heap_sift (iter, i - top, btree_iter_cmp); + } +} + +static void btree_mergesort (struct btree *b,struct bset *out, +struct btree_iter *iter, +bool fixup,bool remove_stale) +{ +struct bkey *k, *last =NULL ; +bool (*bad)(struct btree *,const struct bkey *) = remove_stale + ? bch_ptr_bad + : bch_ptr_invalid; + +while (!btree_iter_end (iter)) { +if (fixup && !b->level) +btree_sort_fixup (iter); + + k =bch_btree_iter_next (iter); +if (bad (b, k)) +continue ; + +if (!last) { + last = out->start; +bkey_copy (last, k); + }else if (b->level || + !bch_bkey_try_merge (b, last, k)) { + last =bkey_next (last); +bkey_copy (last, k); + } + } + + out->keys = last ? (uint64_t *)bkey_next (last) - out->d :0 ; + +pr_debug ("sorted %i keys" , out->keys); +bch_check_key_order (b, out); +} + +static void __btree_sort (struct btree *b,struct btree_iter *iter, +unsigned start,unsigned order,bool fixup) +{ +uint64_t start_time; +bool remove_stale = !b->written; +struct bset *out = (void *)__get_free_pages (__GFP_NOWARN|GFP_NOIO , + order); +if (!out) { +mutex_lock (&b->c->sort_lock); + out = b->c->sort; + order =ilog2 (bucket_pages (b->c)); + } + + start_time =local_clock (); + +btree_mergesort (b, out, iter, fixup, remove_stale); + b->nsets = start; + +if (!fixup && !start && b->written) +bch_btree_verify (b, out); + +if (!start && order == b->page_order) { +/* +* Our temporary buffer is the same size as the btree node's +* buffer, we can just swap buffers instead of doing a big +* memcpy() +*/ + + out->magic =bset_magic (b->c); + out->seq = b->sets[0 ].data->seq; + out->version = b->sets[0 ].data->version; +swap (out, b->sets[0 ].data); + +if (b->c->sort == b->sets[0 ].data) + b->c->sort = out; + }else { + b->sets[start].data->keys = out->keys; +memcpy (b->sets[start].data->start, out->start, + (void *)end (out) - (void *) out->start); + } + +if (out == b->c->sort) +mutex_unlock (&b->c->sort_lock); +else +free_pages ((unsigned long ) out, order); + +if (b->written) +bset_build_written_tree (b); + +if (!start) { +spin_lock (&b->c->sort_time_lock); +time_stats_update (&b->c->sort_time, start_time); +spin_unlock (&b->c->sort_time_lock); + } +} + +void bch_btree_sort_partial (struct btree *b,unsigned start) +{ +size_t oldsize =0 , order = b->page_order, keys =0 ; +struct btree_iter iter; +__bch_btree_iter_init (b, &iter,NULL , &b->sets[start]); + +BUG_ON (b->sets[b->nsets].data ==write_block (b) && + (b->sets[b->nsets].size || b->nsets)); + +if (b->written) + oldsize =bch_count_data (b); + +if (start) { +struct bset *i; +for_each_sorted_set_start (b, i, start) + keys += i->keys; + + order =roundup_pow_of_two (__set_bytes (i, keys)) /PAGE_SIZE ; +if (order) + order =ilog2 (order); + } + +__btree_sort (b, &iter, start, order, false); + +EBUG_ON (b->written &&bch_count_data (b) != oldsize); +} + +void bch_btree_sort_and_fix_extents (struct btree *b,struct btree_iter *iter) +{ +BUG_ON (!b->written); +__btree_sort (b, iter,0 , b->page_order, true); +} + +void bch_btree_sort_into (struct btree *b,struct btree *new) +{ +uint64_t start_time =local_clock (); + +struct btree_iter iter; +bch_btree_iter_init (b, &iter,NULL ); + +btree_mergesort (b, new->sets->data, &iter, false, true); + +spin_lock (&b->c->sort_time_lock); +time_stats_update (&b->c->sort_time, start_time); +spin_unlock (&b->c->sort_time_lock); + +bkey_copy_key (&new->key, &b->key); + new->sets->size =0 ; +} + +void bch_btree_sort_lazy (struct btree *b) +{ +if (b->nsets) { +struct bset *i; +unsigned keys =0 , total; + +for_each_sorted_set (b, i) + keys += i->keys; + total = keys; + +for (unsigned j =0 ; j < b->nsets; j++) { +if (keys *2 < total || + keys <1000 ) { +bch_btree_sort_partial (b, j); +return ; + } + + keys -= b->sets[j].data->keys; + } + +/* Must sort if b->nsets == 3 or we'll overflow */ +if (b->nsets >= (MAX_BSETS -1 ) - b->level) { +bch_btree_sort (b); +return ; + } + } + +bset_build_written_tree (b); +} + +/* Sysfs stuff */ + +struct bset_stats { +size_t nodes; +size_t sets_written, sets_unwritten; +size_t bytes_written, bytes_unwritten; +size_t floats, failed; +}; + +static int bch_btree_bset_stats (struct btree *b,struct btree_op *op, +struct bset_stats *stats) +{ +struct bkey *k; + + stats->nodes++; + +for (int i =0 ; i <= b->nsets; i++) { +struct bset_tree *t = &b->sets[i]; +size_t bytes = t->data->keys *sizeof (uint64_t ); + +if (bset_written (b, t)) { + stats->sets_written++; + stats->bytes_written += bytes; + + stats->floats += t->size -1 ; + +for (size_t j =1 ; j < t->size; j++) +if (t->tree[j].exponent ==127 ) + stats->failed++; + }else { + stats->sets_unwritten++; + stats->bytes_unwritten += bytes; + } + } + +if (b->level) +for_each_key_filter (b, k, bch_ptr_bad) { +int ret =btree (bset_stats, k, b, op, stats); +if (ret) +return ret; + } + +return 0 ; +} + +int bch_bset_print_stats (struct cache_set *c,char *buf) +{ +struct btree_op op; +struct bset_stats t; +int ret; + +bch_btree_op_init_stack (&op); +memset (&t,0 ,sizeof (struct bset_stats )); + + ret =btree_root (bset_stats, c, &op, &t); +if (ret) +return ret; + +return snprintf (buf,PAGE_SIZE , +"btree nodes: %zu\n" +"written sets: %zu\n" +"unwritten sets: %zu\n" +"written key bytes: %zu\n" +"unwritten key bytes: %zu\n" +"floats: %zu\n" +"failed: %zu\n" , + t.nodes, + t.sets_written, t.sets_unwritten, + t.bytes_written, t.bytes_unwritten, + t.floats, t.failed); +}
drivers/md/bcache/bset.h new file +372 -0
372 lines not on this page · raw message
Signature · 1 line
1.7.7.3
PATCH v15 13/16 bcache: Journalling
In reply to Kent Overstreet--- drivers/md/bcache/journal.c | 703 +++++++++++++++++++++++++++++++++++++++++++ drivers/md/bcache/journal.h | 159 ++++++++++ 2 files changed, 862 insertions(+), 0 deletions(-) create mode 100644 drivers/md/bcache/journal.c create mode 100644 drivers/md/bcache/journal.h
drivers/md/bcache/journal.c new file +703 -0
@@ -0,0 +1,703 @@ + +#include "bcache.h" +#include "btree.h" +#include "debug.h" +#include "request.h" + +/* +* Journal replay/recovery: +* +* This code is all driven from run_cache_set(); we first read the journal +* entries, do some other stuff, then we mark all the keys in the journal +* entries (same as garbage collection would), then we replay them - reinserting +* them into the cache in precisely the same order as they appear in the +* journal. +* +* We only journal keys that go in leaf nodes, which simplifies things quite a +* bit. +*/ + +static void journal_read_endio (struct bio *bio,int error) +{ +struct closure *cl = bio->bi_private; +closure_put (cl); +} + +static int journal_read_bucket (struct cache *ca,struct list_head *list, +struct btree_op *op,unsigned bucket_index) +{ +struct journal_device *ja = &ca->journal; +struct bio *bio = &ja->bio; + +struct journal_replay *i; +struct jset *j, *data = ca->set->journal.w[0 ].data; +unsigned len, left, offset =0 ; +int ret =0 ; +sector_t bucket =bucket_to_sector (ca->set, ca->sb.d[bucket_index]); + +pr_debug ("reading %llu" , (uint64_t ) bucket); + +while (offset < ca->sb.bucket_size) { +reread: left = ca->sb.bucket_size - offset; + len =min_t (unsigned, left,PAGE_SECTORS *8 ); + +bio_reset (bio); + bio->bi_sector = bucket + offset; + bio->bi_bdev = ca->bdev; + bio->bi_rw =READ ; + bio->bi_size = len <<9 ; + + bio->bi_end_io = journal_read_endio; + bio->bi_private = &op->cl; +bio_map (bio, data); + +closure_bio_submit (bio, &op->cl); +closure_sync (&op->cl); + +/* This function could be simpler now since we no longer write +* journal entries that overlap bucket boundaries; this means +* the start of a bucket will always have a valid journal entry +* if it has any journal entries at all. +*/ + + j = data; +while (len) { +struct list_head *where; +size_t blocks, bytes =set_bytes (j); + +if (j->magic !=jset_magic (ca->set)) +return ret; + +if (bytes > left <<9 ) +return ret; + +if (bytes > len <<9 ) + goto reread; + +if (j->csum !=csum_set (j)) +return ret; + + blocks =set_blocks (j, ca->set); + +while (!list_empty (list)) { + i =list_first_entry (list, + struct journal_replay, list); +if (i->j.seq >= j->last_seq) +break ; +list_del (&i->list); +kfree (i); + } + +list_for_each_entry_reverse (i, list, list) { +if (j->seq == i->j.seq) + goto next_set; + +if (j->seq < i->j.last_seq) + goto next_set; + +if (j->seq > i->j.seq) { + where = &i->list; + goto add; + } + } + + where = list; +add: + i =kmalloc (offsetof(struct journal_replay , j) + + bytes,GFP_KERNEL ); +if (!i) +return -ENOMEM ; +memcpy (&i->j, j, bytes); +list_add (&i->list, where); + ret =1 ; + + ja->seq[bucket_index] = j->seq; +next_set: + offset += blocks * ca->sb.block_size; + len -= blocks * ca->sb.block_size; + j = ((void *) j) + blocks *block_bytes (ca); + } + } + +return ret; +} + +int bch_journal_read (struct cache_set *c,struct list_head *list, +struct btree_op *op) +{ +#define read_bucket (b) \ + ({ \ + int ret = journal_read_bucket(ca, list, op, b); \ + __set_bit(b, bitmap); \ + if (ret < 0) \ + return ret; \ + ret; \ + }) + +struct cache *ca; + +for_each_cache (ca, c) { +struct journal_device *ja = &ca->journal; +unsigned long bitmap[SB_JOURNAL_BUCKETS /BITS_PER_LONG ]; +unsigned l, r, m; +uint64_t seq; + +bitmap_zero (bitmap,SB_JOURNAL_BUCKETS ); +pr_debug ("%u journal buckets" , ca->sb.njournal_buckets); + +/* Read journal buckets ordered by golden ratio hash to quickly +* find a sequence of buckets with valid journal entries +*/ +for (unsigned i =0 ; i < ca->sb.njournal_buckets; i++) { + l = (i *2654435769U ) % ca->sb.njournal_buckets; + +if (test_bit (l, bitmap)) +break ; + +if (read_bucket (l)) + goto bsearch; + } + +/* If that fails, check all the buckets we haven't checked +* already +*/ +pr_debug ("falling back to linear search" ); + +for (l =0 ; l < ca->sb.njournal_buckets; l++) { +if (test_bit (l, bitmap)) +continue ; + +if (read_bucket (l)) + goto bsearch; + } +bsearch: +/* Binary search */ + m = r =find_next_bit (bitmap, ca->sb.njournal_buckets, l +1 ); +pr_debug ("starting binary search, l %u r %u" , l, r); + +while (l +1 < r) { + m = (l + r) >>1 ; + +if (read_bucket (m)) + l = m; +else + r = m; + } + +/* Read buckets in reverse order until we stop finding more +* journal entries +*/ +pr_debug ("finishing up" ); + l = m; + +while (1 ) { +if (!l--) + l = ca->sb.njournal_buckets -1 ; + +if (l == m) +break ; + +if (test_bit (l, bitmap)) +continue ; + +if (!read_bucket (l)) +break ; + } + + seq =0 ; + +for (unsigned i =0 ; i < ca->sb.njournal_buckets; i++) +if (ja->seq[i] > seq) { + seq = ja->seq[i]; + ja->cur = ja->last = i; + + } + } + + c->journal.seq =list_entry (list->prev, + struct journal_replay, + list)->j.seq; + +return 0 ; +#undef read_bucket +} + +void bch_journal_mark (struct cache_set *c,struct list_head *list) +{ +atomic_t p = {0 }; +struct journal_replay *i; +struct journal *j = &c->journal; +uint64_t last = j->seq; + +/* +* journal.pin should never fill up - we never write a journal +* entry when it would fill up. But if for some reason it does, we +* iterate over the list in reverse order so that we can just skip that +* refcount instead of bugging. +*/ + +list_for_each_entry_reverse (i, list, list) { +BUG_ON (last < i->j.seq); + i->pin =NULL ; + +while (last-- != i->j.seq) +if (fifo_free (&j->pin) >1 ) { +fifo_push_front (&j->pin, p); +atomic_set (&fifo_front (&j->pin),0 ); + } + +if (fifo_free (&j->pin) >1 ) { +fifo_push_front (&j->pin, p); + i->pin = &fifo_front (&j->pin); +atomic_set (i->pin,1 ); + } + +for (struct bkey *k = i->j.start; + k <end (&i->j); + k =bkey_next (k)) { +for (unsigned j =0 ; j <KEY_PTRS (k); j++) { +struct bucket *g =PTR_BUCKET (c, k, j); +atomic_inc (&g->pin); + +if (g->prio ==BTREE_PRIO && + !ptr_stale (c, k, j)) + g->prio =INITIAL_PRIO ; + } + +__bch_btree_mark_key (c,0 , k); + } + } +} + +int bch_journal_replay (struct cache_set *s,struct list_head *list, +struct btree_op *op) +{ +int ret =0 , keys =0 , entries =0 ; +struct journal_replay *i = + list_entry(list->prev, struct journal_replay, list); + +uint64_t start = i->j.last_seq, end = i->j.seq, n = start; + +list_for_each_entry (i, list, list) { +BUG_ON (i->pin &&atomic_read (i->pin) !=1 ); + +if (n != i->j.seq) +err_printk ("journal entries %llu-%llu " +"missing! (replaying %llu-%llu)\n" , + n, i->j.seq -1 , start, end); + +for (struct bkey *k = i->j.start; + k <end (&i->j); + k =bkey_next (k)) { +pr_debug ("%s" ,pkey (k)); +bkey_copy (op->keys.top, k); +bch_keylist_push (&op->keys); + + op->journal = i->pin; +atomic_inc (op->journal); + + ret =bch_btree_insert (op, s); +if (ret) + goto err; + +BUG_ON (!bch_keylist_empty (&op->keys)); + keys++; + } + +if (i->pin) +atomic_dec (i->pin); + n = i->j.seq +1 ; + entries++; + } + +printk (KERN_INFO "bcache: journal replay done, %i keys in %i " +"entries, seq %llu-%llu\n" , keys, entries, start, end); + +while (!list_empty (list)) { + i = list_first_entry(list, struct journal_replay, list); +list_del (&i->list); +kfree (i); + } +err: +closure_sync (&op->cl); +return ret; +} + +/* Journalling */ + +static void btree_flush_write (struct cache_set *c) +{ +/* +* Try to find the btree node with that references the oldest journal +* entry, best is our current candidate and is locked if non NULL: +*/ +struct btree *b, *best =NULL ; +struct hlist_node *cursor; + +for_each_cached_btree (b, cursor, c) { +if (!down_write_trylock (&b->lock)) +continue ; + +if (!btree_node_dirty (b) || + !btree_current_write (b)->journal) { +rw_unlock (true, b); +continue ; + } + +if (!best) + best = b; +else if (journal_pin_cmp (c, +btree_current_write (best), +btree_current_write (b))) { +rw_unlock (true, best); + best = b; + }else +rw_unlock (true, b); + } + +if (best) + goto out; + +/* We can't find the best btree node, just pick the first */ +list_for_each_entry (b, &c->btree_cache, list) +if (!b->level &&btree_node_dirty (b)) { + best = b; +rw_lock (true, best, best->level); + goto found; + } + +out: +if (!best) +return ; +found: +if (btree_node_dirty (best)) +bch_btree_write (best, true,NULL ); +rw_unlock (true, best); +} + +#define last_seq (j) ((j)->seq - fifo_used(&(j)->pin) + 1) + +static void journal_reclaim (struct cache_set *c) +{ +struct bkey *k = &c->journal.key; +struct cache *ca; +uint64_t last_seq; +unsigned n =0 ; +atomic_t p; + +while (!atomic_read (&fifo_front (&c->journal.pin))) +fifo_pop (&c->journal.pin, p); + + last_seq =last_seq (&c->journal); + +for_each_cache (ca, c) { +struct journal_device *ja = &ca->journal; + +while (ja->last != ja->cur && + ja->seq[ja->last] < last_seq) +if (++ja->last == ca->sb.njournal_buckets) + ja->last =0 ; + } + +if (c->journal.blocks_free) +return ; + +/* +* Now we allocate: +* XXX: Sort by free journal space +*/ + +for_each_cache (ca, c) { +struct journal_device *ja = &ca->journal; +unsigned next = (ja->cur +1 ) % ca->sb.njournal_buckets; + +if (next == ja->last) +continue ; + + ja->cur = next; + k->ptr[n++] =PTR (0 , +bucket_to_sector (c, ca->sb.d[ja->cur]), + ca->sb.nr_this_dev); + } + +bkey_init (k); +SET_KEY_PTRS (k, n); + +if (n) + c->journal.blocks_free = c->sb.bucket_size >> c->block_bits; + +if (!journal_full (&c->journal)) +__closure_wake_up (&c->journal.wait); +} + +void bch_journal_next (struct journal *j) +{ +atomic_t p = {1 }; + + j->cur = (j->cur == j->w) + ? &j->w[1 ] + : &j->w[0 ]; + +/* +* The fifo_push() needs to happen at the same time as j->seq is +* incremented for last_seq() to be calculated correctly +*/ +BUG_ON (!fifo_push (&j->pin, p)); +atomic_set (&fifo_back (&j->pin),1 ); + + j->cur->data->seq = ++j->seq; + j->cur->need_write = false; + j->cur->data->keys =0 ; + +if (fifo_full (&j->pin)) +pr_debug ("journal_pin full (%zu)" ,fifo_used (&j->pin)); +} + +static void journal_write_endio (struct bio *bio,int error) +{ +struct journal_write *w = bio->bi_private; + +cache_set_err_on (error, w->c,"journal io error" ); +closure_put (&w->c->journal.io.cl); +} + +static void journal_write (struct closure *); + +static void journal_write_done (struct closure *cl) +{ + struct journal *j = container_of(cl, struct journal, io.cl); + struct cache_set *c = container_of(j, struct cache_set, journal); + +struct journal_write *w = (j->cur == j->w) + ? &j->w[1 ] + : &j->w[0 ]; + +__closure_wake_up (&w->wait); + +if (c->journal_delay_ms) +closure_delay (&j->io,msecs_to_jiffies (c->journal_delay_ms)); + +continue_at (cl, journal_write, system_wq); +} + +static void journal_write_unlocked (struct closure *cl) +{ + struct cache_set *c = container_of(cl, struct cache_set, journal.io.cl); +struct cache *ca; +struct journal_write *w = c->journal.cur; +struct bkey *k = &c->journal.key; +unsigned sectors =set_blocks (w->data, c) * c->sb.block_size; + +struct bio *bio; +struct bio_list list; +bio_list_init (&list); + +if (!w->need_write) { +/* +* XXX: have to unlock closure before we unlock journal lock, +* else we race with bch_journal(). But this way we race +* against cache set unregister. Doh. +*/ +set_closure_fn (cl,NULL ,NULL ); +closure_sub (cl,CLOSURE_RUNNING +1 ); +spin_unlock (&c->journal.lock); +return ; + }else if (journal_full (&c->journal)) { +journal_reclaim (c); +spin_unlock (&c->journal.lock); + +btree_flush_write (c); +continue_at (cl, journal_write, system_wq); + } + + c->journal.blocks_free -=set_blocks (w->data, c); + + w->data->btree_level = c->root->level; + +bkey_copy (&w->data->btree_root, &c->root->key); +bkey_copy (&w->data->uuid_bucket, &c->uuid_bucket); + +for_each_cache (ca, c) + w->data->prio_bucket[ca->sb.nr_this_dev] = ca->prio_buckets[0 ]; + + w->data->magic =jset_magic (c); + w->data->version =BCACHE_JSET_VERSION ; + w->data->last_seq =last_seq (&c->journal); + w->data->csum =csum_set (w->data); + +for (unsigned i =0 ; i <KEY_PTRS (k); i++) { + ca =PTR_CACHE (c, k, i); + bio = &ca->journal.bio; + +atomic_long_add (sectors, &ca->meta_sectors_written); + +bio_reset (bio); + bio->bi_sector =PTR_OFFSET (k, i); + bio->bi_bdev = ca->bdev; + bio->bi_rw =REQ_WRITE |REQ_SYNC |REQ_META |REQ_FLUSH ; + bio->bi_size = sectors <<9 ; + + bio->bi_end_io = journal_write_endio; + bio->bi_private = w; +bio_map (bio, w->data); + +trace_bcache_journal_write (bio); +bio_list_add (&list, bio); + +SET_PTR_OFFSET (k, i,PTR_OFFSET (k, i) + sectors); + + ca->journal.seq[ca->journal.cur] = w->data->seq; + } + +atomic_dec_bug (&fifo_back (&c->journal.pin)); +bch_journal_next (&c->journal); +journal_reclaim (c); + +spin_unlock (&c->journal.lock); + +while ((bio =bio_list_pop (&list))) +closure_bio_submit (bio, cl); + +continue_at (cl, journal_write_done,NULL ); +} + +static void journal_write (struct closure *cl) +{ + struct cache_set *c = container_of(cl, struct cache_set, journal.io.cl); + +spin_lock (&c->journal.lock); +journal_write_unlocked (cl); +} + +static void __journal_try_write (struct cache_set *c,bool noflush) +{ +struct closure *cl = &c->journal.io.cl; + +if (!closure_trylock (cl, &c->cl)) +spin_unlock (&c->journal.lock); +else if (noflush &&journal_full (&c->journal)) { +spin_unlock (&c->journal.lock); +continue_at (cl, journal_write, system_wq); + }else +journal_write_unlocked (cl); +} + +#define journal_try_write (c) __journal_try_write(c, false) + +void bch_journal_meta (struct cache_set *c,struct closure *cl) +{ +struct journal_write *w; + +if (CACHE_SYNC (&c->sb)) { +spin_lock (&c->journal.lock); + + w = c->journal.cur; + w->need_write = true; + +if (cl) +BUG_ON (!closure_wait (&w->wait, cl)); + +__journal_try_write (c, true); + } +} + +/* +* Entry point to the journalling code - bio_insert() and btree_invalidate() +* pass bch_journal() a list of keys to be journalled, and then +* bch_journal() hands those same keys off to btree_insert_async() +*/ + +void bch_journal (struct closure *cl) +{ + struct btree_op *op = container_of(cl, struct btree_op, cl); +struct cache_set *c = op->c; +struct journal_write *w; +size_t b, n = ((uint64_t *) op->keys.top) - op->keys.list; + +if (op->type !=BTREE_INSERT || + !CACHE_SYNC (&c->sb)) + goto out; + +/* +* If we're looping because we errored, might already be waiting on +* another journal write: +*/ +while (atomic_read (&cl->parent->remaining) &CLOSURE_WAITING ) +closure_sync (cl->parent); + +spin_lock (&c->journal.lock); + +if (journal_full (&c->journal)) { +/* XXX: tracepoint */ +closure_wait (&c->journal.wait, cl); + +journal_reclaim (c); +spin_unlock (&c->journal.lock); + +btree_flush_write (c); +continue_at (cl, bch_journal, bcache_wq); + } + + w = c->journal.cur; + w->need_write = true; + b =__set_blocks (w->data, w->data->keys + n, c); + +if (b * c->sb.block_size >PAGE_SECTORS <<JSET_BITS || + b > c->journal.blocks_free) { +/* XXX: If we were inserting so many keys that they won't fit in +* an _empty_ journal write, we'll deadlock. For now, handle +* this in bch_keylist_realloc() - but something to think about. +*/ +BUG_ON (!w->data->keys); + +/* XXX: tracepoint */ +BUG_ON (!closure_wait (&w->wait, cl)); + +closure_flush (&c->journal.io); + +journal_try_write (c); +continue_at (cl, bch_journal, bcache_wq); + } + +memcpy (end (w->data), op->keys.list, n *sizeof (uint64_t )); + w->data->keys += n; + + op->journal = &fifo_back (&c->journal.pin); +atomic_inc (op->journal); + +if (op->flush_journal) { +closure_flush (&c->journal.io); +closure_wait (&w->wait, cl->parent); + } + +journal_try_write (c); +out: +bch_btree_insert_async (cl); +} + +void bch_journal_free (struct cache_set *c) +{ +free_pages ((unsigned long ) c->journal.w[1 ].data,JSET_BITS ); +free_pages ((unsigned long ) c->journal.w[0 ].data,JSET_BITS ); +free_fifo (&c->journal.pin); +} + +int bch_journal_alloc (struct cache_set *c) +{ +struct journal *j = &c->journal; + +closure_init_unlocked (&j->io); +spin_lock_init (&j->lock); + + c->journal_delay_ms =100 ; + + j->w[0 ].c = c; + j->w[1 ].c = c; + +if (!(init_fifo (&j->pin,JOURNAL_PIN ,GFP_KERNEL )) || + !(j->w[0 ].data = (void *)__get_free_pages (GFP_KERNEL ,JSET_BITS )) || + !(j->w[1 ].data = (void *)__get_free_pages (GFP_KERNEL ,JSET_BITS ))) +return -ENOMEM ; + +return 0 ; +}
drivers/md/bcache/journal.h new file +159 -0
159 lines not on this page · raw message
Signature · 1 line
1.7.7.3
PATCH v15 14/16 bcache: Request, io and allocation code
In reply to Kent Overstreet--- drivers/md/bcache/alloc.c | 615 +++++++++++++++++++ drivers/md/bcache/io.c | 136 +++++ drivers/md/bcache/request.c | 1366 +++++++++++++++++++++++++++++++++++++++++++ drivers/md/bcache/request.h | 61 ++ 4 files changed, 2178 insertions(+), 0 deletions(-) create mode 100644 drivers/md/bcache/alloc.c create mode 100644 drivers/md/bcache/io.c create mode 100644 drivers/md/bcache/request.c create mode 100644 drivers/md/bcache/request.h
drivers/md/bcache/alloc.c new file +615 -0
@@ -0,0 +1,615 @@ + +#include "bcache.h" +#include "btree.h" + +#include <linux/random.h> + +/* +* Allocation in bcache is done in terms of buckets: +* +* Each bucket has associated an 8 bit gen; this gen corresponds to the gen in +* btree pointers - they must match for the pointer to be considered valid. +* +* Thus (assuming a bucket has no dirty data or metadata in it) we can reuse a +* bucket simply by incrementing its gen. +* +* The gens (along with the priorities; it's really the gens are important but +* the code is named as if it's the priorities) are written in an arbitrary list +* of buckets on disk, with a pointer to them in the journal header. +* +* When we invalidate a bucket, we have to write its new gen to disk and wait +* for that write to complete before we use it - otherwise after a crash we +* could have pointers that appeared to be good but pointed to data that had +* been overwritten. +* +* Since the gens and priorities are all stored contiguously on disk, we can +* batch this up: We fill up the free_inc list with freshly invalidated buckets, +* call prio_write() - and when prio_write() eventually finishes it toggles +* c->prio_written and the buckets in free_inc are now ready to be used. When +* the free_inc list empties, we toggle c->prio_written and the cycle repeats. +* +* free_inc isn't the only freelist - if it was, we'd often to sleep while +* priorities and gens were being written before we could allocate. c->free is a +* smaller freelist, and buckets on that list are always ready to be used. +* +* If we've got discards enabled, that happens when a bucket moves from the +* free_inc list to the free list. +* +* There is another freelist, because sometimes we have buckets that we know +* have nothing pointing into them - these we can reuse without waiting for +* priorities to be rewritten. These come from freed btree nodes and buckets +* that garbage collection discovered no longer had valid keys pointing into +* them (because they were overwritten). That's the unused list - buckets on the +* unused list move to the free list, optionally being discarded in the process. +* +* It's also important to ensure that gens don't wrap around - with respect to +* either the oldest gen in the btree or the gen on disk. This is quite +* difficult to do in practice, but we explicitly guard against it anyways - if +* a bucket is in danger of wrapping around we simply skip invalidating it that +* time around, and we garbage collect or rewrite the priorities sooner than we +* would have otherwise. +* +* bch_bucket_alloc() allocates a single bucket from a specific cache. +* +* bch_bucket_alloc_set() allocates one or more buckets from different caches +* out of a cache set. +* +* free_some_buckets() drives all the processes described above. It's called +* from bch_bucket_alloc() and a few other places that need to make sure free +* buckets are ready. +* +* invalidate_buckets_(lru|fifo)() find buckets that are available to be +* invalidated, and then invalidate them and stick them on the free_inc list - +* in either lru or fifo order. +*/ + +#define MAX_IN_FLIGHT_DISCARDS 8 + +static void do_discard (struct cache *); + +/* Bucket heap / gen */ + +uint8_t bch_inc_gen (struct cache *ca,struct bucket *b) +{ +uint8_t ret = ++b->gen; + + ca->set->need_gc =max (ca->set->need_gc,bucket_gc_gen (b)); +WARN_ON_ONCE (ca->set->need_gc >BUCKET_GC_GEN_MAX ); + +if (CACHE_SYNC (&ca->set->sb)) { + ca->need_save_prio =max (ca->need_save_prio,bucket_disk_gen (b)); +WARN_ON_ONCE (ca->need_save_prio >BUCKET_DISK_GEN_MAX ); + } + +return ret; +} + +void bch_rescale_priorities (struct cache_set *c,int sectors) +{ +struct cache *ca; +struct bucket *b; +unsigned next = c->nbuckets * c->sb.bucket_size /1024 ; +int r; + +atomic_sub (sectors, &c->rescale); + +do { + r =atomic_read (&c->rescale); + +if (r >=0 ) +return ; + }while (atomic_cmpxchg (&c->rescale, r, r + next) != r); + +mutex_lock (&c->bucket_lock); + + c->min_prio =USHRT_MAX ; + +for_each_cache (ca, c) +for_each_bucket (b, ca) +if (b->prio && + b->prio !=BTREE_PRIO && + !atomic_read (&b->pin)) { + b->prio--; + c->min_prio =min (c->min_prio, b->prio); + } + +mutex_unlock (&c->bucket_lock); +} + +static long pop_freed (struct cache *ca) +{ +long r; + +if ((!CACHE_SYNC (&ca->set->sb) || + !atomic_read (&ca->set->prio_blocked)) && +fifo_pop (&ca->unused, r)) +return r; + +if ((!CACHE_SYNC (&ca->set->sb) || +atomic_read (&ca->prio_written) >0 ) && +fifo_pop (&ca->free_inc, r)) +return r; + +return -1 ; +} + +/* Discard/TRIM */ + +struct discard { +struct list_head list; +struct work_struct work; +struct cache *ca; +long bucket; + +struct bio bio; +struct bio_vec bv; +}; + +static void discard_finish (struct work_struct *w) +{ + struct discard *d = container_of(w, struct discard, work); +struct cache *ca = d->ca; +char buf[BDEVNAME_SIZE ]; +bool run = false; + +if (!test_bit (BIO_UPTODATE , &d->bio.bi_flags)) { +printk (KERN_NOTICE "bcache: discard error on %s, disabling\n" , +bdevname (ca->bdev, buf)); + d->ca->discard =0 ; + } + +mutex_lock (&ca->set->bucket_lock); +if (fifo_empty (&ca->free) || +fifo_used (&ca->free) ==8 ) + run = true; + +fifo_push (&ca->free, d->bucket); + +list_add (&d->list, &ca->discards); + +do_discard (ca); +mutex_unlock (&ca->set->bucket_lock); + +if (run) +closure_wake_up (&ca->set->bucket_wait); + +closure_put (&ca->set->cl); +} + +static void discard_endio (struct bio *bio,int error) +{ + struct discard *d = container_of(bio, struct discard, bio); + +PREPARE_WORK (&d->work, discard_finish); +schedule_work (&d->work); +} + +static void discard_work (struct work_struct *w) +{ + struct discard *d = container_of(w, struct discard, work); +submit_bio (0 , &d->bio); +} + +static void do_discard (struct cache *ca) +{ +struct request_queue *q =bdev_get_queue (ca->bdev); +int s = q->limits.logical_block_size; + +lockdep_assert_held (&ca->set->bucket_lock); + +while (ca->discard && + !atomic_read (&ca->set->closing) && + !list_empty (&ca->discards) && +fifo_free (&ca->free) >=MAX_IN_FLIGHT_DISCARDS ) { +struct discard *d =list_first_entry (&ca->discards, + struct discard, list); + + d->bucket =pop_freed (ca); +if (d->bucket ==-1 ) +break ; + +list_del (&d->list); +closure_get (&ca->set->cl); + +bio_init (&d->bio); +memset (&d->bv,0 ,sizeof (struct bio_vec )); +bio_set_prio (&d->bio,IOPRIO_PRIO_VALUE (IOPRIO_CLASS_IDLE ,0 )); + + d->bio.bi_sector =bucket_to_sector (ca->set, d->bucket); + d->bio.bi_bdev = ca->bdev; + d->bio.bi_rw =REQ_WRITE |REQ_DISCARD ; + d->bio.bi_max_vecs =1 ; + d->bio.bi_io_vec = d->bio.bi_inline_vecs; + d->bio.bi_end_io = discard_endio; + +if (bio_add_pc_page (q, &d->bio, ca->discard_page, s,0 ) < s) { +printk (KERN_DEBUG "bcache: bio_add_pc_page failed\n" ); + ca->discard =0 ; +fifo_push (&ca->free, d->bucket); +list_add (&d->list, &ca->discards); +break ; + } + + d->bio.bi_size =bucket_bytes (ca); + +schedule_work (&d->work); + } +} + +void bch_free_discards (struct cache *ca) +{ +struct discard *d; + +while (!list_empty (&ca->discards)) { + d = list_first_entry(&ca->discards, struct discard, list); +cancel_work_sync (&d->work); +list_del (&d->list); +kfree (d); + } +} + +int bch_alloc_discards (struct cache *ca) +{ +for (int i =0 ; i <MAX_IN_FLIGHT_DISCARDS ; i++) { +struct discard *d =kzalloc (sizeof (*d),GFP_KERNEL ); +if (!d) +return -ENOMEM ; + + d->ca = ca; +INIT_WORK (&d->work, discard_work); +list_add (&d->list, &ca->discards); + } + +return 0 ; +} + +/* Allocation */ + +static inline bool can_inc_bucket_gen (struct bucket *b) +{ +return bucket_gc_gen (b) <BUCKET_GC_GEN_MAX && +bucket_disk_gen (b) <BUCKET_DISK_GEN_MAX ; +} + +bool bch_bucket_add_unused (struct cache *ca,struct bucket *b) +{ +BUG_ON (GC_MARK (b) ||GC_SECTORS_USED (b)); + +if (ca->prio_alloc ==prio_buckets (ca) && +CACHE_REPLACEMENT (&ca->sb) ==CACHE_REPLACEMENT_FIFO ) +return false; + + b->prio =0 ; + +if (can_inc_bucket_gen (b) && +fifo_push (&ca->unused, b - ca->buckets)) { +atomic_inc (&b->pin); +return true; + } + +return false; +} + +static bool can_invalidate_bucket (struct cache *ca,struct bucket *b) +{ +return GC_MARK (b) ==GC_MARK_RECLAIMABLE && + !atomic_read (&b->pin) && +can_inc_bucket_gen (b); +} + +static void invalidate_one_bucket (struct cache *ca,struct bucket *b) +{ +bch_inc_gen (ca, b); + b->prio =INITIAL_PRIO ; +atomic_inc (&b->pin); +fifo_push (&ca->free_inc, b - ca->buckets); +} + +static void invalidate_buckets_lru (struct cache *ca) +{ +unsigned bucket_prio (struct bucket *b) + { +return ((unsigned ) (b->prio - ca->set->min_prio)) * +GC_SECTORS_USED (b); + } + +bool bucket_max_cmp (struct bucket *l,struct bucket *r) + { +return bucket_prio (l) <bucket_prio (r); + } + +bool bucket_min_cmp (struct bucket *l,struct bucket *r) + { +return bucket_prio (l) >bucket_prio (r); + } + +struct bucket *b; + + ca->heap.used =0 ; + +for_each_bucket (b, ca) { +if (!can_invalidate_bucket (ca, b)) +continue ; + +if (!GC_SECTORS_USED (b)) { +if (!bch_bucket_add_unused (ca, b)) +return ; + }else { +if (!heap_full (&ca->heap)) +heap_add (&ca->heap, b, bucket_max_cmp); +else if (bucket_max_cmp (b,heap_peek (&ca->heap))) { + ca->heap.data[0 ] = b; +heap_sift (&ca->heap,0 , bucket_max_cmp); + } + } + } + +if (ca->heap.used *2 < ca->heap.size) +bch_queue_gc (ca->set); + +for (ssize_t i = ca->heap.used /2 -1 ; i >=0 ; --i) +heap_sift (&ca->heap, i, bucket_min_cmp); + +while (!fifo_full (&ca->free_inc)) { +if (!heap_pop (&ca->heap, b, bucket_min_cmp)) { +/* We don't want to be calling invalidate_buckets() +* multiple times when it can't do anything +*/ + ca->invalidate_needs_gc =1 ; +bch_queue_gc (ca->set); +return ; + } + +invalidate_one_bucket (ca, b); + } +} + +static void invalidate_buckets_fifo (struct cache *ca) +{ +struct bucket *b; +size_t checked =0 ; + +while (!fifo_full (&ca->free_inc)) { +if (ca->fifo_last_bucket < ca->sb.first_bucket || + ca->fifo_last_bucket >= ca->sb.nbuckets) + ca->fifo_last_bucket = ca->sb.first_bucket; + + b = ca->buckets + ca->fifo_last_bucket++; + +if (can_invalidate_bucket (ca, b)) +invalidate_one_bucket (ca, b); + +if (++checked >= ca->sb.nbuckets) { + ca->invalidate_needs_gc =1 ; +bch_queue_gc (ca->set); +return ; + } + } +} + +static void invalidate_buckets_random (struct cache *ca) +{ +struct bucket *b; +size_t checked =0 ; + +while (!fifo_full (&ca->free_inc)) { +size_t n; +get_random_bytes (&n,sizeof (n)); + + n %= (size_t ) (ca->sb.nbuckets - ca->sb.first_bucket); + n += ca->sb.first_bucket; + + b = ca->buckets + n; + +if (can_invalidate_bucket (ca, b)) +invalidate_one_bucket (ca, b); + +if (++checked >= ca->sb.nbuckets /2 ) { + ca->invalidate_needs_gc =1 ; +bch_queue_gc (ca->set); +return ; + } + } +} + +static void invalidate_buckets (struct cache *ca) +{ +/* free_some_buckets() may just need to write priorities to keep gens +* from wrapping around +*/ +if (!ca->set->gc_mark_valid || + ca->invalidate_needs_gc) +return ; + +switch (CACHE_REPLACEMENT (&ca->sb)) { +case CACHE_REPLACEMENT_LRU : +invalidate_buckets_lru (ca); +break ; +case CACHE_REPLACEMENT_FIFO : +invalidate_buckets_fifo (ca); +break ; +case CACHE_REPLACEMENT_RANDOM : +invalidate_buckets_random (ca); +break ; + } +} + +bool bch_can_save_prios (struct cache *ca) +{ +return ((ca->need_save_prio >64 || + (ca->set->gc_mark_valid && + !ca->invalidate_needs_gc)) && + !atomic_read (&ca->prio_written) && + !atomic_read (&ca->set->prio_blocked)); +} + +void bch_free_some_buckets (struct cache *ca) +{ +long r; +lockdep_assert_held (&ca->set->bucket_lock); + +/* +* XXX: do_discard(), prio_write() take refcounts on the cache set. How +* do we know that refcount is nonzero? +*/ + +if (ca->discard) +do_discard (ca); +else +while (!fifo_full (&ca->free) && + (r =pop_freed (ca)) !=-1 ) +fifo_push (&ca->free, r); + +while (ca->prio_alloc !=prio_buckets (ca) && +fifo_pop (&ca->free, r)) { +struct bucket *b = ca->buckets + r; + ca->prio_next[ca->prio_alloc++] = r; + +SET_GC_MARK (b,GC_MARK_BTREE ); +atomic_dec_bug (&b->pin); + } + +if (!CACHE_SYNC (&ca->set->sb)) { +if (fifo_empty (&ca->free_inc)) +invalidate_buckets (ca); +return ; + } + +/* XXX: tracepoint for when c->need_save_prio > 64 */ + +if (ca->need_save_prio <=64 && +fifo_used (&ca->unused) > ca->unused.size /2 ) +return ; + +if (atomic_read (&ca->prio_written) >0 && + (fifo_empty (&ca->free_inc) || + ca->need_save_prio >64 )) +atomic_set (&ca->prio_written,0 ); + +if (!bch_can_save_prios (ca)) +return ; + +invalidate_buckets (ca); + +if (!fifo_empty (&ca->free_inc) || + ca->need_save_prio >64 ) +bch_prio_write (ca); +} + +static long bch_bucket_alloc (struct cache *ca,int mark, +uint16_t write_prio,struct closure *cl) +{ +long r =-1 ; +unsigned watermark; + +if (mark ==GC_MARK_BTREE ) + watermark =0 ; +else if (write_prio) + watermark =8 ; +else + watermark = ca->free.size /2 ; + +again: +bch_free_some_buckets (ca); + +if (fifo_used (&ca->free) > watermark && +fifo_pop (&ca->free, r)) { +struct bucket *b = ca->buckets + r; +#ifdef CONFIG_BCACHE_EDEBUG +long i; +for (unsigned j =0 ; j <prio_buckets (ca); j++) +BUG_ON (ca->prio_buckets[j] == (uint64_t ) r); +for (unsigned j =0 ; j < ca->prio_alloc; j++) +BUG_ON (ca->prio_next[j] == (uint64_t ) r); + +fifo_for_each (i, &ca->free) +BUG_ON (i == r); +fifo_for_each (i, &ca->free_inc) +BUG_ON (i == r); +fifo_for_each (i, &ca->unused) +BUG_ON (i == r); +#endif +BUG_ON (atomic_read (&b->pin) !=1 ); + +SET_GC_MARK (b, mark); +SET_GC_SECTORS_USED (b, ca->sb.bucket_size); + b->prio = (mark ==GC_MARK_BTREE ) + ?BTREE_PRIO :INITIAL_PRIO ; + +return r; + } + +pr_debug ("no free buckets, prio_written %i, blocked %i, " +"free %zu, free_inc %zu, unused %zu" , +atomic_read (&ca->prio_written), +atomic_read (&ca->set->prio_blocked),fifo_used (&ca->free), +fifo_used (&ca->free_inc),fifo_used (&ca->unused)); + +if (cl) { +if (closure_blocking (cl)) +mutex_unlock (&ca->set->bucket_lock); + +closure_wait_event (&ca->set->bucket_wait, cl, +atomic_read (&ca->prio_written) >0 || +bch_can_save_prios (ca)); + +if (closure_blocking (cl)) { +mutex_lock (&ca->set->bucket_lock); + goto again; + } + } + +return -1 ; +} + +void bch_bucket_free (struct cache_set *c,struct bkey *k) +{ +for (unsigned i =0 ; i <KEY_PTRS (k); i++) { +struct bucket *b =PTR_BUCKET (c, k, i); + +SET_GC_MARK (b,0 ); +SET_GC_SECTORS_USED (b,0 ); +bch_bucket_add_unused (PTR_CACHE (c, k, i), b); + } +} + +int __bch_bucket_alloc_set (struct cache_set *c,int mark,uint16_t write_prio, +struct bkey *k,int n,struct closure *cl) +{ +lockdep_assert_held (&c->bucket_lock); +BUG_ON (!n || n > c->caches_loaded || n >8 ); + +bkey_init (k); + +/* sort by free space/prio of oldest data in caches */ + +for (int i =0 ; i < n; i++) { +struct cache *ca = c->cache_by_alloc[i]; +long b =bch_bucket_alloc (ca, mark, write_prio, cl); + +if (b ==-1 ) + goto err; + + k->ptr[i] =PTR (ca->buckets[b].gen, +bucket_to_sector (c, b), + ca->sb.nr_this_dev); + +SET_KEY_PTRS (k, i +1 ); + } + +return 0 ; +err: +bch_bucket_free (c, k); +__bkey_put (c, k); +return -1 ; +} + +int bch_bucket_alloc_set (struct cache_set *c,int mark,uint16_t write_prio, +struct bkey *k,int n,struct closure *cl) +{ +int ret; +mutex_lock (&c->bucket_lock); + ret =__bch_bucket_alloc_set (c, mark, write_prio, k, n, cl); +mutex_unlock (&c->bucket_lock); +return ret; +}
drivers/md/bcache/io.c new file +136 -0
136 lines not on this page · raw message
drivers/md/bcache/request.c new file +1366 -0
1,366 lines not on this page · raw message
drivers/md/bcache/request.h new file +61 -0
61 lines not on this page · raw message
Signature · 1 line
1.7.7.3
PATCH v15 15/16 bcache: Writeback, copying garbage collection
In reply to Kent Overstreet--- drivers/md/bcache/movinggc.c | 245 +++++++++++++++++++++++++ drivers/md/bcache/writeback.c | 405 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 650 insertions(+), 0 deletions(-) create mode 100644 drivers/md/bcache/movinggc.c create mode 100644 drivers/md/bcache/writeback.c
drivers/md/bcache/movinggc.c new file +245 -0
@@ -0,0 +1,245 @@ +#include "bcache.h" +#include "btree.h" +#include "debug.h" +#include "request.h" + +struct moving_io { +struct keybuf_key *w; +struct search s; +struct bbio bio; +}; + +static bool moving_pred (struct keybuf *buf,struct bkey *k) +{ + struct cache_set *c = container_of(buf, struct cache_set, + moving_gc_keys); + +for (unsigned i =0 ; i <KEY_PTRS (k); i++) { +struct cache *ca =PTR_CACHE (c, k, i); +struct bucket *g =PTR_BUCKET (c, k, i); + +if (GC_SECTORS_USED (g) < ca->gc_move_threshold) +return true; + } + +return false; +} + +/* Moving GC - IO loop */ + +static void moving_io_destructor (struct closure *cl) +{ + struct moving_io *io = container_of(cl, struct moving_io, s.cl); +kfree (io); +} + +static void write_moving_finish (struct closure *cl) +{ + struct moving_io *io = container_of(cl, struct moving_io, s.cl); +struct bio *bio = &io->bio.bio; +struct bio_vec *bv =bio_iovec_idx (bio, bio->bi_vcnt); + +while (bv-- != bio->bi_io_vec) +__free_page (bv->bv_page); + +pr_debug ("%s %s" , io->s.op.insert_collision + ?"collision moving" :"moved" , +pkey (&io->w->key)); + +bch_keybuf_del (&io->s.op.c->moving_gc_keys, io->w); + +atomic_dec_bug (&io->s.op.c->in_flight); +closure_wake_up (&io->s.op.c->moving_gc_wait); + +closure_return_with_destructor (cl, moving_io_destructor); +} + +static void read_moving_endio (struct bio *bio,int error) +{ +struct moving_io *io =container_of (bio->bi_private, + struct moving_io, s.cl); + +if (error) + io->s.error = error; + +bch_bbio_endio (io->s.op.c, bio, error,"reading data to move" ); +} + +static void moving_init (struct moving_io *io) +{ +struct bio *bio = &io->bio.bio; + +bio_init (bio); +bio_get (bio); +bio_set_prio (bio,IOPRIO_PRIO_VALUE (IOPRIO_CLASS_IDLE ,0 )); + + bio->bi_size =KEY_SIZE (&io->w->key) <<9 ; + bio->bi_max_vecs =DIV_ROUND_UP (KEY_SIZE (&io->w->key),PAGE_SECTORS ); + bio->bi_private = &io->s.cl; + bio->bi_io_vec = bio->bi_inline_vecs; +bio_map (bio,NULL ); +} + +static void write_moving (struct closure *cl) +{ + struct search *s = container_of(cl, struct search, cl); + struct moving_io *io = container_of(s, struct moving_io, s); + +if (!s->error) { +trace_bcache_write_moving (&io->bio.bio); + +moving_init (io); + + io->bio.bio.bi_sector =KEY_START (&io->w->key); + s->op.lock =-1 ; + s->op.write_prio =1 ; + s->op.cache_bio = &io->bio.bio; + + s->writeback =KEY_DIRTY (&io->w->key); + s->op.csum =KEY_CSUM (&io->w->key); + + s->op.type =BTREE_REPLACE ; +bkey_copy (&s->op.replace, &io->w->key); + +closure_init (&s->op.cl, cl); +bch_insert_data (&s->op.cl); + } + +continue_at (cl, write_moving_finish,NULL ); +} + +static void read_moving_submit (struct closure *cl) +{ + struct search *s = container_of(cl, struct search, cl); + struct moving_io *io = container_of(s, struct moving_io, s); +struct bio *bio = &io->bio.bio; + +trace_bcache_read_moving (bio); +bch_submit_bbio (bio, s->op.c, &io->w->key,0 ); + +continue_at (cl, write_moving, bch_gc_wq); +} + +static void read_moving (struct closure *cl) +{ + struct cache_set *c = container_of(cl, struct cache_set, moving_gc); +struct keybuf_key *w; +struct moving_io *io; +struct bio *bio; + +/* XXX: if we error, background writeback could stall indefinitely */ + +while (!atomic_read (&c->closing)) { + w =bch_keybuf_next_rescan (c, &c->moving_gc_keys, &MAX_KEY ); +if (!w) +break ; + + io =kzalloc (sizeof (struct moving_io ) +sizeof (struct bio_vec ) + *DIV_ROUND_UP (KEY_SIZE (&w->key),PAGE_SECTORS ), +GFP_KERNEL ); +if (!io) + goto err; + + w->private = io; + io->w = w; + io->s.op.inode =KEY_INODE (&w->key); + io->s.op.c = c; + +moving_init (io); + bio = &io->bio.bio; + + bio->bi_rw =READ ; + bio->bi_end_io = read_moving_endio; + +if (bio_alloc_pages (bio,GFP_KERNEL )) + goto err; + +pr_debug ("%s" ,pkey (&w->key)); + +closure_call (read_moving_submit, &io->s.cl, &c->gc.cl); + +if (atomic_inc_return (&c->in_flight) >=64 ) { +closure_wait_event (&c->moving_gc_wait, cl, +atomic_read (&c->in_flight) <64 ); +continue_at (cl, read_moving, bch_gc_wq); + } + } + +if (0 ) { +err:if (!IS_ERR_OR_NULL (w->private)) +kfree (w->private); + +bch_keybuf_del (&c->moving_gc_keys, w); + } + +closure_return (cl); +} + +void bch_moving_gc (struct closure *cl) +{ + struct cache_set *c = container_of(cl, struct cache_set, gc.cl); +struct cache *ca; +struct bucket *b; + +bool bucket_cmp (struct bucket *l,struct bucket *r) + { +return GC_SECTORS_USED (l) <GC_SECTORS_USED (r); + } + +unsigned top (struct cache *ca) + { +return GC_SECTORS_USED (heap_peek (&ca->heap)); + } + +if (!c->copy_gc_enabled) +closure_return (cl); + +mutex_lock (&c->bucket_lock); + +for_each_cache (ca, c) { +unsigned sectors_to_move =0 ; +unsigned reserve_sectors = ca->sb.bucket_size * +min (fifo_used (&ca->free), ca->free.size /2 ); + + ca->heap.used =0 ; + +for_each_bucket (b, ca) { +if (!GC_SECTORS_USED (b)) +continue ; + +if (!heap_full (&ca->heap)) { + sectors_to_move +=GC_SECTORS_USED (b); +heap_add (&ca->heap, b, bucket_cmp); + }else if (bucket_cmp (b,heap_peek (&ca->heap))) { + sectors_to_move -=top (ca); + sectors_to_move +=GC_SECTORS_USED (b); + + ca->heap.data[0 ] = b; +heap_sift (&ca->heap,0 , bucket_cmp); + } + } + +while (sectors_to_move > reserve_sectors) { +heap_pop (&ca->heap, b, bucket_cmp); + sectors_to_move -=GC_SECTORS_USED (b); + } + + ca->gc_move_threshold =top (ca); + +pr_debug ("threshold %u" , ca->gc_move_threshold); + } + +mutex_unlock (&c->bucket_lock); + + c->moving_gc_keys.last_scanned =ZERO_KEY ; + +closure_init (&c->moving_gc, cl); +read_moving (&c->moving_gc); + +closure_return (cl); +} + +void bch_moving_init_cache_set (struct cache_set *c) +{ +bch_keybuf_init (&c->moving_gc_keys, moving_pred); +}
drivers/md/bcache/writeback.c new file +405 -0
405 lines not on this page · raw message
Signature · 1 line
1.7.7.3
PATCH v15 16/16 bcache: Debug and tracing code
In reply to Kent Overstreet--- drivers/md/bcache/debug.c | 576 +++++++++++++++++++++++++++++++++++++++++ drivers/md/bcache/debug.h | 54 ++++ drivers/md/bcache/trace.c | 26 ++ include/trace/events/bcache.h | 271 +++++++++++++++++++ 4 files changed, 927 insertions(+), 0 deletions(-) create mode 100644 drivers/md/bcache/debug.c create mode 100644 drivers/md/bcache/debug.h create mode 100644 drivers/md/bcache/trace.c create mode 100644 include/trace/events/bcache.h
drivers/md/bcache/debug.c new file +576 -0
@@ -0,0 +1,576 @@ + +#include "bcache.h" +#include "btree.h" +#include "debug.h" +#include "request.h" + +#include <linux/console.h> +#include <linux/debugfs.h> +#include <linux/module.h> +#include <linux/random.h> +#include <linux/seq_file.h> + +static struct dentry *debug; + +/* Various debug code */ + +const char *bch_ptr_status (struct cache_set *c,const struct bkey *k) +{ +for (unsigned i =0 ; i <KEY_PTRS (k); i++) +if (ptr_available (c, k, i)) { +struct cache *ca =PTR_CACHE (c, k, i); +size_t bucket =PTR_BUCKET_NR (c, k, i); +size_t r =bucket_remainder (c,PTR_OFFSET (k, i)); + +if (KEY_SIZE (k) + r > c->sb.bucket_size) +return "bad, length too big" ; +if (bucket < ca->sb.first_bucket) +return "bad, short offset" ; +if (bucket >= ca->sb.nbuckets) +return "bad, offset past end of device" ; +if (ptr_stale (c, k, i)) +return "stale" ; + } + +if (!bkey_cmp (k, &ZERO_KEY )) +return "bad, null key" ; +if (!KEY_PTRS (k)) +return "bad, no pointers" ; +if (!KEY_SIZE (k)) +return "zeroed key" ; +return "" ; +} + +struct keyprint_hack bch_pkey (const struct bkey *k) +{ +unsigned i =0 ; +struct keyprint_hack r; +char *out = r.s, *end = r.s +KEYHACK_SIZE ; + +#define p (...) (out += scnprintf(out, end - out, __VA_ARGS__)) + +p ("%llu:%llu len %llu -> [" ,KEY_INODE (k),KEY_OFFSET (k),KEY_SIZE (k)); + +if (KEY_PTRS (k)) +while (1 ) { +p ("%llu:%llu gen %llu" , +PTR_DEV (k, i),PTR_OFFSET (k, i),PTR_GEN (k, i)); + +if (++i ==KEY_PTRS (k)) +break ; + +p (", " ); + } + +p ("]" ); + +if (KEY_DIRTY (k)) +p (" dirty" ); +if (KEY_CSUM (k)) +p (" cs%llu %llx" ,KEY_CSUM (k), k->ptr[1 ]); +#undef p +return r; +} + +struct keyprint_hack bch_pbtree (const struct btree *b) +{ +struct keyprint_hack r; + +snprintf (r.s,40 ,"%li level %i/%i" ,PTR_BUCKET_NR (b->c, &b->key,0 ), + b->level, b->c->root ? b->c->root->level :-1 ); +return r; +} + +#if defined(CONFIG_BCACHE_DEBUG ) || defined(CONFIG_BCACHE_EDEBUG ) + +static bool skipped_backwards (struct btree *b,struct bkey *k) +{ +return bkey_cmp (k, (!b->level) + ? &START_KEY (bkey_next (k)) + :bkey_next (k)) >0 ; +} + +static void dump_bset (struct btree *b,struct bset *i) +{ +for (struct bkey *k = i->start; k <end (i); k =bkey_next (k)) { +printk (KERN_ERR "block %zu key %zi/%u: %s" ,index (i, b), + (uint64_t *) k - i->d, i->keys,pkey (k)); + +for (unsigned j =0 ; j <KEY_PTRS (k); j++) { +size_t n =PTR_BUCKET_NR (b->c, k, j); +printk (" bucket %zu" , n); + +if (n >= b->c->sb.first_bucket && n < b->c->sb.nbuckets) +printk (" prio %i" , +PTR_BUCKET (b->c, k, j)->prio); + } + +printk (" %s\n" ,bch_ptr_status (b->c, k)); + +if (bkey_next (k) <end (i) && +skipped_backwards (b, k)) +printk (KERN_ERR "Key skipped backwards\n" ); + } +} + +#endif + +#ifdef CONFIG_BCACHE_DEBUG + +void bch_btree_verify (struct btree *b,struct bset *new) +{ +struct btree *v = b->c->verify_data; +struct closure cl; +closure_init_stack (&cl); + +if (!b->c->verify) +return ; + +closure_wait_event (&b->io.wait, &cl, +atomic_read (&b->io.cl.remaining) ==-1 ); + +mutex_lock (&b->c->verify_lock); + +bkey_copy (&v->key, &b->key); + v->written =0 ; + v->level = b->level; + +bch_btree_read (v); +closure_wait_event (&v->io.wait, &cl, +atomic_read (&b->io.cl.remaining) ==-1 ); + +if (new->keys != v->sets[0 ].data->keys || +memcmp (new->start, + v->sets[0 ].data->start, + (void *)end (new) - (void *) new->start)) { +struct bset *i; +unsigned j; + +console_lock (); + +printk (KERN_ERR "*** original memory node:\n" ); +for_each_sorted_set (b, i) +dump_bset (b, i); + +printk (KERN_ERR "*** sorted memory node:\n" ); +dump_bset (b, new); + +printk (KERN_ERR "*** on disk node:\n" ); +dump_bset (v, v->sets[0 ].data); + +for (j =0 ; j < new->keys; j++) +if (new->d[j] != v->sets[0 ].data->d[j]) +break ; + +console_unlock (); +panic ("verify failed at %u\n" , j); + } + +mutex_unlock (&b->c->verify_lock); +} + +static void data_verify_endio (struct bio *bio,int error) +{ +struct closure *cl = bio->bi_private; +closure_put (cl); +} + +void bch_data_verify (struct search *s) +{ +char name[BDEVNAME_SIZE ]; + struct cached_dev *dc = container_of(s->d, struct cached_dev, disk); +struct closure *cl = &s->cl; +struct bio *check; +struct bio_vec *bv; +int i; + +if (!s->unaligned_bvec) +bio_for_each_segment (bv, s->orig_bio, i) + bv->bv_offset =0 , bv->bv_len =PAGE_SIZE ; + + check =bio_clone (s->orig_bio,GFP_NOIO ); +if (!check) +return ; + +if (bio_alloc_pages (check,GFP_NOIO )) + goto out_put; + + check->bi_rw =READ_SYNC ; + check->bi_private = cl; + check->bi_end_io = data_verify_endio; + +closure_bio_submit (check, cl); +closure_sync (cl); + +bio_for_each_segment (bv, s->orig_bio, i) { +void *p1 =kmap (bv->bv_page); +void *p2 =kmap (check->bi_io_vec[i].bv_page); + +if (memcmp (p1 + bv->bv_offset, + p2 + bv->bv_offset, + bv->bv_len)) +printk (KERN_ERR "bcache (%s): verify failed" +" at sector %llu\n" , +bdevname (dc->bdev, name), + (uint64_t ) s->orig_bio->bi_sector); + +kunmap (bv->bv_page); +kunmap (check->bi_io_vec[i].bv_page); + } + +__bio_for_each_segment (bv, check, i,0 ) +__free_page (bv->bv_page); +out_put: +bio_put (check); +} + +#endif + +#ifdef CONFIG_BCACHE_EDEBUG + +unsigned bch_count_data (struct btree *b) +{ +unsigned ret =0 ; +struct bkey *k; + +if (!b->level) +for_each_key (b, k) + ret +=KEY_SIZE (k); +return ret; +} + +static void vdump_bucket_and_panic (struct btree *b,const char *fmt, +va_list args) +{ +struct bset *i; + +console_lock (); + +for_each_sorted_set (b, i) +dump_bset (b, i); + +vprintk (fmt, args); + +console_unlock (); + +panic ("at %s\n" ,pbtree (b)); +} + +void bch_check_key_order_msg (struct btree *b,struct bset *i, +const char *fmt, ...) +{ +if (!i->keys) +return ; + +for (struct bkey *k = i->start;bkey_next (k) <end (i); k =bkey_next (k)) +if (skipped_backwards (b, k)) { +va_list args; +va_start (args, fmt); + +vdump_bucket_and_panic (b, fmt, args); +va_end (args); + } +} + +void bch_check_keys (struct btree *b,const char *fmt, ...) +{ +va_list args; +struct bkey *k, *p; +struct btree_iter iter; + +if (b->level) +return ; + +bch_btree_iter_init (b, &iter,NULL ); + +do + p =bch_btree_iter_next (&iter); +while (p &&bch_ptr_invalid (b, p)); + +while ((k =bch_btree_iter_next (&iter))) { +if (bkey_cmp (&START_KEY (p), &START_KEY (k)) >0 ) { +printk (KERN_ERR "Keys out of order:\n" ); + goto bug; + } + +if (bch_ptr_invalid (b, k)) +continue ; + +if (bkey_cmp (p, &START_KEY (k)) >0 ) { +printk (KERN_ERR "Overlapping keys:\n" ); + goto bug; + } + p = k; + } +return ; +bug: +va_start (args, fmt); +vdump_bucket_and_panic (b, fmt, args); +va_end (args); +} + +#endif + +#ifdef CONFIG_DEBUG_FS + +/* XXX: cache set refcounting */ + +struct dump_iterator { +char buf[PAGE_SIZE ]; +size_t bytes; +struct cache_set *c; +struct keybuf keys; +}; + +static bool dump_pred (struct keybuf *buf,struct bkey *k) +{ +return true; +} + +static ssize_t bch_dump_read (struct file *file,char __user *buf, +size_t size,loff_t *ppos) +{ +struct dump_iterator *i = file->private_data; +ssize_t ret =0 ; + +while (size) { +struct keybuf_key *w; +unsigned bytes =min (i->bytes, size); + +int err =copy_to_user (buf, i->buf, bytes); +if (err) +return err; + + ret += bytes; + buf += bytes; + size -= bytes; + i->bytes -= bytes; +memmove (i->buf, i->buf + bytes, i->bytes); + +if (i->bytes) +break ; + + w =bch_keybuf_next_rescan (i->c, &i->keys, &MAX_KEY ); +if (!w) +break ; + + i->bytes =snprintf (i->buf,PAGE_SIZE ,"%s\n" ,pkey (&w->key)); +bch_keybuf_del (&i->keys, w); + } + +return ret; +} + +static int bch_dump_open (struct inode *inode,struct file *file) +{ +struct cache_set *c = inode->i_private; +struct dump_iterator *i; + + i =kzalloc (sizeof (struct dump_iterator ),GFP_KERNEL ); +if (!i) +return -ENOMEM ; + + file->private_data = i; + i->c = c; +bch_keybuf_init (&i->keys, dump_pred); + i->keys.last_scanned =KEY (0 ,0 ,0 ); + +return 0 ; +} + +static int bch_dump_release (struct inode *inode,struct file *file) +{ +kfree (file->private_data); +return 0 ; +} + +static const struct file_operations cache_set_debug_ops = { + .owner =THIS_MODULE , + .open = bch_dump_open, + .read = bch_dump_read, + .release = bch_dump_release +}; + +void bch_debug_init_cache_set (struct cache_set *c) +{ +if (!IS_ERR_OR_NULL (debug)) { +char name[50 ]; +snprintf (name,50 ,"bcache-%pU" , c->sb.set_uuid); + + c->debug =debugfs_create_file (name,0400 , debug, c, + &cache_set_debug_ops); + } +} + +#endif + +#ifdef CONFIG_BCACHE_DEBUG +static ssize_t btree_fuzz (struct kobject *k,struct kobj_attribute *a, +const char *buffer,size_t size) +{ +void dump (struct btree *b) + { +for (struct bset *i = b->sets[0 ].data; +index (i, b) <btree_blocks (b) && + i->seq == b->sets[0 ].data->seq; + i = ((void *) i) +set_blocks (i, b->c) *block_bytes (b->c)) +dump_bset (b, i); + } + +struct cache_sb *sb; +struct cache_set *c; +struct btree *all[3 ], *b, *fill, *orig; + +struct btree_op op; +bch_btree_op_init_stack (&op); + + sb =kzalloc (sizeof (struct cache_sb ),GFP_KERNEL ); +if (!sb) +return -ENOMEM ; + + sb->bucket_size =128 ; + sb->block_size =4 ; + + c =bch_cache_set_alloc (sb); +if (!c) +return -ENOMEM ; + +for (int i =0 ; i <3 ; i++) { +BUG_ON (list_empty (&c->btree_cache)); + all[i] = list_first_entry(&c->btree_cache, struct btree, list); +list_del_init (&all[i]->list); + + all[i]->key =KEY (0 ,0 , c->sb.bucket_size); +bkey_copy_key (&all[i]->key, &MAX_KEY ); + } + + b = all[0 ]; + fill = all[1 ]; + orig = all[2 ]; + +while (1 ) { +for (int i =0 ; i <3 ; i++) + all[i]->written = all[i]->nsets =0 ; + +bch_bset_init_next (b); + +while (1 ) { +struct bset *i =write_block (b); +struct bkey *k = op.keys.top; +unsigned rand; + +bkey_init (k); + rand =get_random_int (); + + op.type = rand &1 + ?BTREE_INSERT + :BTREE_REPLACE ; + rand >>=1 ; + +SET_KEY_SIZE (k,bucket_remainder (c, rand)); + rand >>= c->bucket_bits; + rand &=1024 *512 -1 ; + rand += c->sb.bucket_size; +SET_KEY_OFFSET (k, rand); +#if 0 +SET_KEY_PTRS (k,1 ); +#endif +bch_keylist_push (&op.keys); +bch_btree_insert_keys (b, &op); + +if (should_split (b) || +set_blocks (i, b->c) != +__set_blocks (i, i->keys +15 , b->c)) { + i->csum =csum_set (i); + +memcpy (write_block (fill), + i,set_bytes (i)); + + b->written +=set_blocks (i, b->c); + fill->written = b->written; +if (b->written ==btree_blocks (b)) +break ; + +bch_btree_sort_lazy (b); +bch_bset_init_next (b); + } + } + +memcpy (orig->sets[0 ].data, + fill->sets[0 ].data, +btree_bytes (c)); + +bch_btree_sort (b); + fill->written =0 ; +bch_btree_read_done (&fill->io.cl); + +if (b->sets[0 ].data->keys != fill->sets[0 ].data->keys || +memcmp (b->sets[0 ].data->start, + fill->sets[0 ].data->start, + b->sets[0 ].data->keys *sizeof (uint64_t ))) { +struct bset *i = b->sets[0 ].data; + +for (struct bkey *k = i->start, + *j = fill->sets[0 ].data->start; + k <end (i); + k =bkey_next (k), j =bkey_next (j)) +if (bkey_cmp (k, j) || +KEY_SIZE (k) !=KEY_SIZE (j)) +printk (KERN_ERR "key %zi differs: %s " +"!= %s\n" , (uint64_t *) k - i->d, +pkey (k),pkey (j)); + +for (int i =0 ; i <3 ; i++) { +printk (KERN_ERR "**** Set %i ****\n" , i); +dump (all[i]); + } +panic ("\n" ); + } + +printk (KERN_DEBUG "bcache: fuzz complete: %i keys\n" , + b->sets[0 ].data->keys); + } +} + +kobj_attribute_write (fuzz, btree_fuzz); +#endif + +#ifdef CONFIG_BCACHE_LATENCY_DEBUG +static ssize_t show (struct kobject *k,struct kobj_attribute *attr,char *buf) +{ +return snprintf (buf,PAGE_SIZE ,"%i\n" , latency_warn_ms); +} + +static ssize_t store (struct kobject *k,struct kobj_attribute *attr, +const char *buffer,size_t size) +{ +return strtoul_safe (buffer, latency_warn_ms) ?: (ssize_t ) size; +} + +kobj_attribute_rw (latency_warn_ms, show, store); +#endif + +void bch_debug_exit (void ) +{ +if (!IS_ERR_OR_NULL (debug)) +debugfs_remove_recursive (debug); +} + +int __init bch_debug_init (struct kobject *kobj) +{ +int ret =0 ; +#ifdef CONFIG_BCACHE_DEBUG + ret =sysfs_create_file (kobj, &ksysfs_fuzz.attr); +if (ret) +return ret; +#endif + +#ifdef CONFIG_BCACHE_LATENCY_DEBUG + ret =sysfs_create_file (kobj, &ksysfs_latency_warn_ms.attr); +if (ret) +return ret; +#endif + + debug =debugfs_create_dir ("bcache" ,NULL ); +return ret; +}
drivers/md/bcache/debug.h new file +54 -0
54 lines not on this page · raw message
drivers/md/bcache/trace.c new file +26 -0
@@ -0,0 +1,26 @@ +#include "bcache.h" +#include "btree.h" +#include "request.h" + +#include <linux/module.h> + +#define CREATE_TRACE_POINTS +#include <trace/events/bcache.h> + +EXPORT_TRACEPOINT_SYMBOL_GPL (bcache_request_start); +EXPORT_TRACEPOINT_SYMBOL_GPL (bcache_request_end); +EXPORT_TRACEPOINT_SYMBOL_GPL (bcache_passthrough); +EXPORT_TRACEPOINT_SYMBOL_GPL (bcache_cache_hit); +EXPORT_TRACEPOINT_SYMBOL_GPL (bcache_cache_miss); +EXPORT_TRACEPOINT_SYMBOL_GPL (bcache_read_retry); +EXPORT_TRACEPOINT_SYMBOL_GPL (bcache_writethrough); +EXPORT_TRACEPOINT_SYMBOL_GPL (bcache_writeback); +EXPORT_TRACEPOINT_SYMBOL_GPL (bcache_write_skip); +EXPORT_TRACEPOINT_SYMBOL_GPL (bcache_btree_read); +EXPORT_TRACEPOINT_SYMBOL_GPL (bcache_btree_write); +EXPORT_TRACEPOINT_SYMBOL_GPL (bcache_write_dirty); +EXPORT_TRACEPOINT_SYMBOL_GPL (bcache_read_dirty); +EXPORT_TRACEPOINT_SYMBOL_GPL (bcache_journal_write); +EXPORT_TRACEPOINT_SYMBOL_GPL (bcache_cache_insert); +EXPORT_TRACEPOINT_SYMBOL_GPL (bcache_gc_start); +EXPORT_TRACEPOINT_SYMBOL_GPL (bcache_gc_end);
include/trace/events/bcache.h new file +271 -0
271 lines not on this page · raw message
Signature · 1 line
1.7.7.3