• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * bcache setup/teardown code, and some metadata io - read a superblock and
3  * figure out what to do with it.
4  *
5  * Copyright 2010, 2011 Kent Overstreet <kent.overstreet@gmail.com>
6  * Copyright 2012 Google, Inc.
7  */
8 
9 #include "bcache.h"
10 #include "btree.h"
11 #include "debug.h"
12 #include "request.h"
13 
14 #include <linux/buffer_head.h>
15 #include <linux/debugfs.h>
16 #include <linux/genhd.h>
17 #include <linux/module.h>
18 #include <linux/random.h>
19 #include <linux/reboot.h>
20 #include <linux/sysfs.h>
21 
22 MODULE_LICENSE("GPL");
23 MODULE_AUTHOR("Kent Overstreet <kent.overstreet@gmail.com>");
24 
25 static const char bcache_magic[] = {
26 	0xc6, 0x85, 0x73, 0xf6, 0x4e, 0x1a, 0x45, 0xca,
27 	0x82, 0x65, 0xf5, 0x7f, 0x48, 0xba, 0x6d, 0x81
28 };
29 
30 static const char invalid_uuid[] = {
31 	0xa0, 0x3e, 0xf8, 0xed, 0x3e, 0xe1, 0xb8, 0x78,
32 	0xc8, 0x50, 0xfc, 0x5e, 0xcb, 0x16, 0xcd, 0x99
33 };
34 
35 /* Default is -1; we skip past it for struct cached_dev's cache mode */
36 const char * const bch_cache_modes[] = {
37 	"default",
38 	"writethrough",
39 	"writeback",
40 	"writearound",
41 	"none",
42 	NULL
43 };
44 
45 struct uuid_entry_v0 {
46 	uint8_t		uuid[16];
47 	uint8_t		label[32];
48 	uint32_t	first_reg;
49 	uint32_t	last_reg;
50 	uint32_t	invalidated;
51 	uint32_t	pad;
52 };
53 
54 static struct kobject *bcache_kobj;
55 struct mutex bch_register_lock;
56 LIST_HEAD(bch_cache_sets);
57 static LIST_HEAD(uncached_devices);
58 
59 static int bcache_major, bcache_minor;
60 static wait_queue_head_t unregister_wait;
61 struct workqueue_struct *bcache_wq;
62 
63 #define BTREE_MAX_PAGES		(256 * 1024 / PAGE_SIZE)
64 
bio_split_pool_free(struct bio_split_pool * p)65 static void bio_split_pool_free(struct bio_split_pool *p)
66 {
67 	if (p->bio_split_hook)
68 		mempool_destroy(p->bio_split_hook);
69 
70 	if (p->bio_split)
71 		bioset_free(p->bio_split);
72 }
73 
bio_split_pool_init(struct bio_split_pool * p)74 static int bio_split_pool_init(struct bio_split_pool *p)
75 {
76 	p->bio_split = bioset_create(4, 0);
77 	if (!p->bio_split)
78 		return -ENOMEM;
79 
80 	p->bio_split_hook = mempool_create_kmalloc_pool(4,
81 				sizeof(struct bio_split_hook));
82 	if (!p->bio_split_hook)
83 		return -ENOMEM;
84 
85 	return 0;
86 }
87 
88 /* Superblock */
89 
read_super(struct cache_sb * sb,struct block_device * bdev,struct page ** res)90 static const char *read_super(struct cache_sb *sb, struct block_device *bdev,
91 			      struct page **res)
92 {
93 	const char *err;
94 	struct cache_sb *s;
95 	struct buffer_head *bh = __bread(bdev, 1, SB_SIZE);
96 	unsigned i;
97 
98 	if (!bh)
99 		return "IO error";
100 
101 	s = (struct cache_sb *) bh->b_data;
102 
103 	sb->offset		= le64_to_cpu(s->offset);
104 	sb->version		= le64_to_cpu(s->version);
105 
106 	memcpy(sb->magic,	s->magic, 16);
107 	memcpy(sb->uuid,	s->uuid, 16);
108 	memcpy(sb->set_uuid,	s->set_uuid, 16);
109 	memcpy(sb->label,	s->label, SB_LABEL_SIZE);
110 
111 	sb->flags		= le64_to_cpu(s->flags);
112 	sb->seq			= le64_to_cpu(s->seq);
113 	sb->last_mount		= le32_to_cpu(s->last_mount);
114 	sb->first_bucket	= le16_to_cpu(s->first_bucket);
115 	sb->keys		= le16_to_cpu(s->keys);
116 
117 	for (i = 0; i < SB_JOURNAL_BUCKETS; i++)
118 		sb->d[i] = le64_to_cpu(s->d[i]);
119 
120 	pr_debug("read sb version %llu, flags %llu, seq %llu, journal size %u",
121 		 sb->version, sb->flags, sb->seq, sb->keys);
122 
123 	err = "Not a bcache superblock";
124 	if (sb->offset != SB_SECTOR)
125 		goto err;
126 
127 	if (memcmp(sb->magic, bcache_magic, 16))
128 		goto err;
129 
130 	err = "Too many journal buckets";
131 	if (sb->keys > SB_JOURNAL_BUCKETS)
132 		goto err;
133 
134 	err = "Bad checksum";
135 	if (s->csum != csum_set(s))
136 		goto err;
137 
138 	err = "Bad UUID";
139 	if (bch_is_zero(sb->uuid, 16))
140 		goto err;
141 
142 	sb->block_size	= le16_to_cpu(s->block_size);
143 
144 	err = "Superblock block size smaller than device block size";
145 	if (sb->block_size << 9 < bdev_logical_block_size(bdev))
146 		goto err;
147 
148 	switch (sb->version) {
149 	case BCACHE_SB_VERSION_BDEV:
150 		sb->data_offset	= BDEV_DATA_START_DEFAULT;
151 		break;
152 	case BCACHE_SB_VERSION_BDEV_WITH_OFFSET:
153 		sb->data_offset	= le64_to_cpu(s->data_offset);
154 
155 		err = "Bad data offset";
156 		if (sb->data_offset < BDEV_DATA_START_DEFAULT)
157 			goto err;
158 
159 		break;
160 	case BCACHE_SB_VERSION_CDEV:
161 	case BCACHE_SB_VERSION_CDEV_WITH_UUID:
162 		sb->nbuckets	= le64_to_cpu(s->nbuckets);
163 		sb->block_size	= le16_to_cpu(s->block_size);
164 		sb->bucket_size	= le16_to_cpu(s->bucket_size);
165 
166 		sb->nr_in_set	= le16_to_cpu(s->nr_in_set);
167 		sb->nr_this_dev	= le16_to_cpu(s->nr_this_dev);
168 
169 		err = "Too many buckets";
170 		if (sb->nbuckets > LONG_MAX)
171 			goto err;
172 
173 		err = "Not enough buckets";
174 		if (sb->nbuckets < 1 << 7)
175 			goto err;
176 
177 		err = "Bad block/bucket size";
178 		if (!is_power_of_2(sb->block_size) ||
179 		    sb->block_size > PAGE_SECTORS ||
180 		    !is_power_of_2(sb->bucket_size) ||
181 		    sb->bucket_size < PAGE_SECTORS)
182 			goto err;
183 
184 		err = "Invalid superblock: device too small";
185 		if (get_capacity(bdev->bd_disk) < sb->bucket_size * sb->nbuckets)
186 			goto err;
187 
188 		err = "Bad UUID";
189 		if (bch_is_zero(sb->set_uuid, 16))
190 			goto err;
191 
192 		err = "Bad cache device number in set";
193 		if (!sb->nr_in_set ||
194 		    sb->nr_in_set <= sb->nr_this_dev ||
195 		    sb->nr_in_set > MAX_CACHES_PER_SET)
196 			goto err;
197 
198 		err = "Journal buckets not sequential";
199 		for (i = 0; i < sb->keys; i++)
200 			if (sb->d[i] != sb->first_bucket + i)
201 				goto err;
202 
203 		err = "Too many journal buckets";
204 		if (sb->first_bucket + sb->keys > sb->nbuckets)
205 			goto err;
206 
207 		err = "Invalid superblock: first bucket comes before end of super";
208 		if (sb->first_bucket * sb->bucket_size < 16)
209 			goto err;
210 
211 		break;
212 	default:
213 		err = "Unsupported superblock version";
214 		goto err;
215 	}
216 
217 	sb->last_mount = get_seconds();
218 	err = NULL;
219 
220 	get_page(bh->b_page);
221 	*res = bh->b_page;
222 err:
223 	put_bh(bh);
224 	return err;
225 }
226 
write_bdev_super_endio(struct bio * bio,int error)227 static void write_bdev_super_endio(struct bio *bio, int error)
228 {
229 	struct cached_dev *dc = bio->bi_private;
230 	/* XXX: error checking */
231 
232 	closure_put(&dc->sb_write.cl);
233 }
234 
__write_super(struct cache_sb * sb,struct bio * bio)235 static void __write_super(struct cache_sb *sb, struct bio *bio)
236 {
237 	struct cache_sb *out = page_address(bio->bi_io_vec[0].bv_page);
238 	unsigned i;
239 
240 	bio->bi_sector	= SB_SECTOR;
241 	bio->bi_rw	= REQ_SYNC|REQ_META;
242 	bio->bi_size	= SB_SIZE;
243 	bch_bio_map(bio, NULL);
244 
245 	out->offset		= cpu_to_le64(sb->offset);
246 	out->version		= cpu_to_le64(sb->version);
247 
248 	memcpy(out->uuid,	sb->uuid, 16);
249 	memcpy(out->set_uuid,	sb->set_uuid, 16);
250 	memcpy(out->label,	sb->label, SB_LABEL_SIZE);
251 
252 	out->flags		= cpu_to_le64(sb->flags);
253 	out->seq		= cpu_to_le64(sb->seq);
254 
255 	out->last_mount		= cpu_to_le32(sb->last_mount);
256 	out->first_bucket	= cpu_to_le16(sb->first_bucket);
257 	out->keys		= cpu_to_le16(sb->keys);
258 
259 	for (i = 0; i < sb->keys; i++)
260 		out->d[i] = cpu_to_le64(sb->d[i]);
261 
262 	out->csum = csum_set(out);
263 
264 	pr_debug("ver %llu, flags %llu, seq %llu",
265 		 sb->version, sb->flags, sb->seq);
266 
267 	submit_bio(REQ_WRITE, bio);
268 }
269 
bch_write_bdev_super(struct cached_dev * dc,struct closure * parent)270 void bch_write_bdev_super(struct cached_dev *dc, struct closure *parent)
271 {
272 	struct closure *cl = &dc->sb_write.cl;
273 	struct bio *bio = &dc->sb_bio;
274 
275 	closure_lock(&dc->sb_write, parent);
276 
277 	bio_reset(bio);
278 	bio->bi_bdev	= dc->bdev;
279 	bio->bi_end_io	= write_bdev_super_endio;
280 	bio->bi_private = dc;
281 
282 	closure_get(cl);
283 	__write_super(&dc->sb, bio);
284 
285 	closure_return(cl);
286 }
287 
write_super_endio(struct bio * bio,int error)288 static void write_super_endio(struct bio *bio, int error)
289 {
290 	struct cache *ca = bio->bi_private;
291 
292 	bch_count_io_errors(ca, error, "writing superblock");
293 	closure_put(&ca->set->sb_write.cl);
294 }
295 
bcache_write_super(struct cache_set * c)296 void bcache_write_super(struct cache_set *c)
297 {
298 	struct closure *cl = &c->sb_write.cl;
299 	struct cache *ca;
300 	unsigned i;
301 
302 	closure_lock(&c->sb_write, &c->cl);
303 
304 	c->sb.seq++;
305 
306 	for_each_cache(ca, c, i) {
307 		struct bio *bio = &ca->sb_bio;
308 
309 		ca->sb.version		= BCACHE_SB_VERSION_CDEV_WITH_UUID;
310 		ca->sb.seq		= c->sb.seq;
311 		ca->sb.last_mount	= c->sb.last_mount;
312 
313 		SET_CACHE_SYNC(&ca->sb, CACHE_SYNC(&c->sb));
314 
315 		bio_reset(bio);
316 		bio->bi_bdev	= ca->bdev;
317 		bio->bi_end_io	= write_super_endio;
318 		bio->bi_private = ca;
319 
320 		closure_get(cl);
321 		__write_super(&ca->sb, bio);
322 	}
323 
324 	closure_return(cl);
325 }
326 
327 /* UUID io */
328 
uuid_endio(struct bio * bio,int error)329 static void uuid_endio(struct bio *bio, int error)
330 {
331 	struct closure *cl = bio->bi_private;
332 	struct cache_set *c = container_of(cl, struct cache_set, uuid_write.cl);
333 
334 	cache_set_err_on(error, c, "accessing uuids");
335 	bch_bbio_free(bio, c);
336 	closure_put(cl);
337 }
338 
uuid_io(struct cache_set * c,unsigned long rw,struct bkey * k,struct closure * parent)339 static void uuid_io(struct cache_set *c, unsigned long rw,
340 		    struct bkey *k, struct closure *parent)
341 {
342 	struct closure *cl = &c->uuid_write.cl;
343 	struct uuid_entry *u;
344 	unsigned i;
345 
346 	BUG_ON(!parent);
347 	closure_lock(&c->uuid_write, parent);
348 
349 	for (i = 0; i < KEY_PTRS(k); i++) {
350 		struct bio *bio = bch_bbio_alloc(c);
351 
352 		bio->bi_rw	= REQ_SYNC|REQ_META|rw;
353 		bio->bi_size	= KEY_SIZE(k) << 9;
354 
355 		bio->bi_end_io	= uuid_endio;
356 		bio->bi_private = cl;
357 		bch_bio_map(bio, c->uuids);
358 
359 		bch_submit_bbio(bio, c, k, i);
360 
361 		if (!(rw & WRITE))
362 			break;
363 	}
364 
365 	pr_debug("%s UUIDs at %s", rw & REQ_WRITE ? "wrote" : "read",
366 		 pkey(&c->uuid_bucket));
367 
368 	for (u = c->uuids; u < c->uuids + c->nr_uuids; u++)
369 		if (!bch_is_zero(u->uuid, 16))
370 			pr_debug("Slot %zi: %pU: %s: 1st: %u last: %u inv: %u",
371 				 u - c->uuids, u->uuid, u->label,
372 				 u->first_reg, u->last_reg, u->invalidated);
373 
374 	closure_return(cl);
375 }
376 
uuid_read(struct cache_set * c,struct jset * j,struct closure * cl)377 static char *uuid_read(struct cache_set *c, struct jset *j, struct closure *cl)
378 {
379 	struct bkey *k = &j->uuid_bucket;
380 
381 	if (__bch_ptr_invalid(c, 1, k))
382 		return "bad uuid pointer";
383 
384 	bkey_copy(&c->uuid_bucket, k);
385 	uuid_io(c, READ_SYNC, k, cl);
386 
387 	if (j->version < BCACHE_JSET_VERSION_UUIDv1) {
388 		struct uuid_entry_v0	*u0 = (void *) c->uuids;
389 		struct uuid_entry	*u1 = (void *) c->uuids;
390 		int i;
391 
392 		closure_sync(cl);
393 
394 		/*
395 		 * Since the new uuid entry is bigger than the old, we have to
396 		 * convert starting at the highest memory address and work down
397 		 * in order to do it in place
398 		 */
399 
400 		for (i = c->nr_uuids - 1;
401 		     i >= 0;
402 		     --i) {
403 			memcpy(u1[i].uuid,	u0[i].uuid, 16);
404 			memcpy(u1[i].label,	u0[i].label, 32);
405 
406 			u1[i].first_reg		= u0[i].first_reg;
407 			u1[i].last_reg		= u0[i].last_reg;
408 			u1[i].invalidated	= u0[i].invalidated;
409 
410 			u1[i].flags	= 0;
411 			u1[i].sectors	= 0;
412 		}
413 	}
414 
415 	return NULL;
416 }
417 
__uuid_write(struct cache_set * c)418 static int __uuid_write(struct cache_set *c)
419 {
420 	BKEY_PADDED(key) k;
421 	struct closure cl;
422 	closure_init_stack(&cl);
423 
424 	lockdep_assert_held(&bch_register_lock);
425 
426 	if (bch_bucket_alloc_set(c, WATERMARK_METADATA, &k.key, 1, &cl))
427 		return 1;
428 
429 	SET_KEY_SIZE(&k.key, c->sb.bucket_size);
430 	uuid_io(c, REQ_WRITE, &k.key, &cl);
431 	closure_sync(&cl);
432 
433 	bkey_copy(&c->uuid_bucket, &k.key);
434 	__bkey_put(c, &k.key);
435 	return 0;
436 }
437 
bch_uuid_write(struct cache_set * c)438 int bch_uuid_write(struct cache_set *c)
439 {
440 	int ret = __uuid_write(c);
441 
442 	if (!ret)
443 		bch_journal_meta(c, NULL);
444 
445 	return ret;
446 }
447 
uuid_find(struct cache_set * c,const char * uuid)448 static struct uuid_entry *uuid_find(struct cache_set *c, const char *uuid)
449 {
450 	struct uuid_entry *u;
451 
452 	for (u = c->uuids;
453 	     u < c->uuids + c->nr_uuids; u++)
454 		if (!memcmp(u->uuid, uuid, 16))
455 			return u;
456 
457 	return NULL;
458 }
459 
uuid_find_empty(struct cache_set * c)460 static struct uuid_entry *uuid_find_empty(struct cache_set *c)
461 {
462 	static const char zero_uuid[16] = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
463 	return uuid_find(c, zero_uuid);
464 }
465 
466 /*
467  * Bucket priorities/gens:
468  *
469  * For each bucket, we store on disk its
470    * 8 bit gen
471    * 16 bit priority
472  *
473  * See alloc.c for an explanation of the gen. The priority is used to implement
474  * lru (and in the future other) cache replacement policies; for most purposes
475  * it's just an opaque integer.
476  *
477  * The gens and the priorities don't have a whole lot to do with each other, and
478  * it's actually the gens that must be written out at specific times - it's no
479  * big deal if the priorities don't get written, if we lose them we just reuse
480  * buckets in suboptimal order.
481  *
482  * On disk they're stored in a packed array, and in as many buckets are required
483  * to fit them all. The buckets we use to store them form a list; the journal
484  * header points to the first bucket, the first bucket points to the second
485  * bucket, et cetera.
486  *
487  * This code is used by the allocation code; periodically (whenever it runs out
488  * of buckets to allocate from) the allocation code will invalidate some
489  * buckets, but it can't use those buckets until their new gens are safely on
490  * disk.
491  */
492 
prio_endio(struct bio * bio,int error)493 static void prio_endio(struct bio *bio, int error)
494 {
495 	struct cache *ca = bio->bi_private;
496 
497 	cache_set_err_on(error, ca->set, "accessing priorities");
498 	bch_bbio_free(bio, ca->set);
499 	closure_put(&ca->prio);
500 }
501 
prio_io(struct cache * ca,uint64_t bucket,unsigned long rw)502 static void prio_io(struct cache *ca, uint64_t bucket, unsigned long rw)
503 {
504 	struct closure *cl = &ca->prio;
505 	struct bio *bio = bch_bbio_alloc(ca->set);
506 
507 	closure_init_stack(cl);
508 
509 	bio->bi_sector	= bucket * ca->sb.bucket_size;
510 	bio->bi_bdev	= ca->bdev;
511 	bio->bi_rw	= REQ_SYNC|REQ_META|rw;
512 	bio->bi_size	= bucket_bytes(ca);
513 
514 	bio->bi_end_io	= prio_endio;
515 	bio->bi_private = ca;
516 	bch_bio_map(bio, ca->disk_buckets);
517 
518 	closure_bio_submit(bio, &ca->prio, ca);
519 	closure_sync(cl);
520 }
521 
522 #define buckets_free(c)	"free %zu, free_inc %zu, unused %zu",		\
523 	fifo_used(&c->free), fifo_used(&c->free_inc), fifo_used(&c->unused)
524 
bch_prio_write(struct cache * ca)525 void bch_prio_write(struct cache *ca)
526 {
527 	int i;
528 	struct bucket *b;
529 	struct closure cl;
530 
531 	closure_init_stack(&cl);
532 
533 	lockdep_assert_held(&ca->set->bucket_lock);
534 
535 	for (b = ca->buckets;
536 	     b < ca->buckets + ca->sb.nbuckets; b++)
537 		b->disk_gen = b->gen;
538 
539 	ca->disk_buckets->seq++;
540 
541 	atomic_long_add(ca->sb.bucket_size * prio_buckets(ca),
542 			&ca->meta_sectors_written);
543 
544 	pr_debug("free %zu, free_inc %zu, unused %zu", fifo_used(&ca->free),
545 		 fifo_used(&ca->free_inc), fifo_used(&ca->unused));
546 	blktrace_msg(ca, "Starting priorities: " buckets_free(ca));
547 
548 	for (i = prio_buckets(ca) - 1; i >= 0; --i) {
549 		long bucket;
550 		struct prio_set *p = ca->disk_buckets;
551 		struct bucket_disk *d = p->data;
552 		struct bucket_disk *end = d + prios_per_bucket(ca);
553 
554 		for (b = ca->buckets + i * prios_per_bucket(ca);
555 		     b < ca->buckets + ca->sb.nbuckets && d < end;
556 		     b++, d++) {
557 			d->prio = cpu_to_le16(b->prio);
558 			d->gen = b->gen;
559 		}
560 
561 		p->next_bucket	= ca->prio_buckets[i + 1];
562 		p->magic	= pset_magic(ca);
563 		p->csum		= bch_crc64(&p->magic, bucket_bytes(ca) - 8);
564 
565 		bucket = bch_bucket_alloc(ca, WATERMARK_PRIO, &cl);
566 		BUG_ON(bucket == -1);
567 
568 		mutex_unlock(&ca->set->bucket_lock);
569 		prio_io(ca, bucket, REQ_WRITE);
570 		mutex_lock(&ca->set->bucket_lock);
571 
572 		ca->prio_buckets[i] = bucket;
573 		atomic_dec_bug(&ca->buckets[bucket].pin);
574 	}
575 
576 	mutex_unlock(&ca->set->bucket_lock);
577 
578 	bch_journal_meta(ca->set, &cl);
579 	closure_sync(&cl);
580 
581 	mutex_lock(&ca->set->bucket_lock);
582 
583 	ca->need_save_prio = 0;
584 
585 	/*
586 	 * Don't want the old priorities to get garbage collected until after we
587 	 * finish writing the new ones, and they're journalled
588 	 */
589 	for (i = 0; i < prio_buckets(ca); i++)
590 		ca->prio_last_buckets[i] = ca->prio_buckets[i];
591 }
592 
prio_read(struct cache * ca,uint64_t bucket)593 static void prio_read(struct cache *ca, uint64_t bucket)
594 {
595 	struct prio_set *p = ca->disk_buckets;
596 	struct bucket_disk *d = p->data + prios_per_bucket(ca), *end = d;
597 	struct bucket *b;
598 	unsigned bucket_nr = 0;
599 
600 	for (b = ca->buckets;
601 	     b < ca->buckets + ca->sb.nbuckets;
602 	     b++, d++) {
603 		if (d == end) {
604 			ca->prio_buckets[bucket_nr] = bucket;
605 			ca->prio_last_buckets[bucket_nr] = bucket;
606 			bucket_nr++;
607 
608 			prio_io(ca, bucket, READ_SYNC);
609 
610 			if (p->csum != bch_crc64(&p->magic, bucket_bytes(ca) - 8))
611 				pr_warn("bad csum reading priorities");
612 
613 			if (p->magic != pset_magic(ca))
614 				pr_warn("bad magic reading priorities");
615 
616 			bucket = p->next_bucket;
617 			d = p->data;
618 		}
619 
620 		b->prio = le16_to_cpu(d->prio);
621 		b->gen = b->disk_gen = b->last_gc = b->gc_gen = d->gen;
622 	}
623 }
624 
625 /* Bcache device */
626 
open_dev(struct block_device * b,fmode_t mode)627 static int open_dev(struct block_device *b, fmode_t mode)
628 {
629 	struct bcache_device *d = b->bd_disk->private_data;
630 	if (atomic_read(&d->closing))
631 		return -ENXIO;
632 
633 	closure_get(&d->cl);
634 	return 0;
635 }
636 
release_dev(struct gendisk * b,fmode_t mode)637 static void release_dev(struct gendisk *b, fmode_t mode)
638 {
639 	struct bcache_device *d = b->private_data;
640 	closure_put(&d->cl);
641 }
642 
ioctl_dev(struct block_device * b,fmode_t mode,unsigned int cmd,unsigned long arg)643 static int ioctl_dev(struct block_device *b, fmode_t mode,
644 		     unsigned int cmd, unsigned long arg)
645 {
646 	struct bcache_device *d = b->bd_disk->private_data;
647 	return d->ioctl(d, mode, cmd, arg);
648 }
649 
650 static const struct block_device_operations bcache_ops = {
651 	.open		= open_dev,
652 	.release	= release_dev,
653 	.ioctl		= ioctl_dev,
654 	.owner		= THIS_MODULE,
655 };
656 
bcache_device_stop(struct bcache_device * d)657 void bcache_device_stop(struct bcache_device *d)
658 {
659 	if (!atomic_xchg(&d->closing, 1))
660 		closure_queue(&d->cl);
661 }
662 
bcache_device_unlink(struct bcache_device * d)663 static void bcache_device_unlink(struct bcache_device *d)
664 {
665 	unsigned i;
666 	struct cache *ca;
667 
668 	sysfs_remove_link(&d->c->kobj, d->name);
669 	sysfs_remove_link(&d->kobj, "cache");
670 
671 	for_each_cache(ca, d->c, i)
672 		bd_unlink_disk_holder(ca->bdev, d->disk);
673 }
674 
bcache_device_link(struct bcache_device * d,struct cache_set * c,const char * name)675 static void bcache_device_link(struct bcache_device *d, struct cache_set *c,
676 			       const char *name)
677 {
678 	unsigned i;
679 	struct cache *ca;
680 
681 	for_each_cache(ca, d->c, i)
682 		bd_link_disk_holder(ca->bdev, d->disk);
683 
684 	snprintf(d->name, BCACHEDEVNAME_SIZE,
685 		 "%s%u", name, d->id);
686 
687 	WARN(sysfs_create_link(&d->kobj, &c->kobj, "cache") ||
688 	     sysfs_create_link(&c->kobj, &d->kobj, d->name),
689 	     "Couldn't create device <-> cache set symlinks");
690 }
691 
bcache_device_detach(struct bcache_device * d)692 static void bcache_device_detach(struct bcache_device *d)
693 {
694 	lockdep_assert_held(&bch_register_lock);
695 
696 	if (atomic_read(&d->detaching)) {
697 		struct uuid_entry *u = d->c->uuids + d->id;
698 
699 		SET_UUID_FLASH_ONLY(u, 0);
700 		memcpy(u->uuid, invalid_uuid, 16);
701 		u->invalidated = cpu_to_le32(get_seconds());
702 		bch_uuid_write(d->c);
703 
704 		atomic_set(&d->detaching, 0);
705 	}
706 
707 	bcache_device_unlink(d);
708 
709 	d->c->devices[d->id] = NULL;
710 	closure_put(&d->c->caching);
711 	d->c = NULL;
712 }
713 
bcache_device_attach(struct bcache_device * d,struct cache_set * c,unsigned id)714 static void bcache_device_attach(struct bcache_device *d, struct cache_set *c,
715 				 unsigned id)
716 {
717 	BUG_ON(test_bit(CACHE_SET_STOPPING, &c->flags));
718 
719 	d->id = id;
720 	d->c = c;
721 	c->devices[id] = d;
722 
723 	closure_get(&c->caching);
724 }
725 
bcache_device_free(struct bcache_device * d)726 static void bcache_device_free(struct bcache_device *d)
727 {
728 	lockdep_assert_held(&bch_register_lock);
729 
730 	pr_info("%s stopped", d->disk->disk_name);
731 
732 	if (d->c)
733 		bcache_device_detach(d);
734 	if (d->disk && d->disk->flags & GENHD_FL_UP)
735 		del_gendisk(d->disk);
736 	if (d->disk && d->disk->queue)
737 		blk_cleanup_queue(d->disk->queue);
738 	if (d->disk)
739 		put_disk(d->disk);
740 
741 	bio_split_pool_free(&d->bio_split_hook);
742 	if (d->unaligned_bvec)
743 		mempool_destroy(d->unaligned_bvec);
744 	if (d->bio_split)
745 		bioset_free(d->bio_split);
746 
747 	closure_debug_destroy(&d->cl);
748 }
749 
bcache_device_init(struct bcache_device * d,unsigned block_size)750 static int bcache_device_init(struct bcache_device *d, unsigned block_size)
751 {
752 	struct request_queue *q;
753 
754 	if (!(d->bio_split = bioset_create(4, offsetof(struct bbio, bio))) ||
755 	    !(d->unaligned_bvec = mempool_create_kmalloc_pool(1,
756 				sizeof(struct bio_vec) * BIO_MAX_PAGES)) ||
757 	    bio_split_pool_init(&d->bio_split_hook) ||
758 	    !(d->disk = alloc_disk(1)) ||
759 	    !(q = blk_alloc_queue(GFP_KERNEL)))
760 		return -ENOMEM;
761 
762 	snprintf(d->disk->disk_name, DISK_NAME_LEN, "bcache%i", bcache_minor);
763 
764 	d->disk->major		= bcache_major;
765 	d->disk->first_minor	= bcache_minor++;
766 	d->disk->fops		= &bcache_ops;
767 	d->disk->private_data	= d;
768 
769 	blk_queue_make_request(q, NULL);
770 	d->disk->queue			= q;
771 	q->queuedata			= d;
772 	q->backing_dev_info.congested_data = d;
773 	q->limits.max_hw_sectors	= UINT_MAX;
774 	q->limits.max_sectors		= UINT_MAX;
775 	q->limits.max_segment_size	= UINT_MAX;
776 	q->limits.max_segments		= BIO_MAX_PAGES;
777 	q->limits.max_discard_sectors	= UINT_MAX;
778 	q->limits.io_min		= block_size;
779 	q->limits.logical_block_size	= block_size;
780 	q->limits.physical_block_size	= block_size;
781 	set_bit(QUEUE_FLAG_NONROT,	&d->disk->queue->queue_flags);
782 	clear_bit(QUEUE_FLAG_ADD_RANDOM, &d->disk->queue->queue_flags);
783 	set_bit(QUEUE_FLAG_DISCARD,	&d->disk->queue->queue_flags);
784 
785 	return 0;
786 }
787 
788 /* Cached device */
789 
calc_cached_dev_sectors(struct cache_set * c)790 static void calc_cached_dev_sectors(struct cache_set *c)
791 {
792 	uint64_t sectors = 0;
793 	struct cached_dev *dc;
794 
795 	list_for_each_entry(dc, &c->cached_devs, list)
796 		sectors += bdev_sectors(dc->bdev);
797 
798 	c->cached_dev_sectors = sectors;
799 }
800 
bch_cached_dev_run(struct cached_dev * dc)801 void bch_cached_dev_run(struct cached_dev *dc)
802 {
803 	struct bcache_device *d = &dc->disk;
804 
805 	if (atomic_xchg(&dc->running, 1))
806 		return;
807 
808 	if (!d->c &&
809 	    BDEV_STATE(&dc->sb) != BDEV_STATE_NONE) {
810 		struct closure cl;
811 		closure_init_stack(&cl);
812 
813 		SET_BDEV_STATE(&dc->sb, BDEV_STATE_STALE);
814 		bch_write_bdev_super(dc, &cl);
815 		closure_sync(&cl);
816 	}
817 
818 	add_disk(d->disk);
819 	bd_link_disk_holder(dc->bdev, dc->disk.disk);
820 #if 0
821 	char *env[] = { "SYMLINK=label" , NULL };
822 	kobject_uevent_env(&disk_to_dev(d->disk)->kobj, KOBJ_CHANGE, env);
823 #endif
824 	if (sysfs_create_link(&d->kobj, &disk_to_dev(d->disk)->kobj, "dev") ||
825 	    sysfs_create_link(&disk_to_dev(d->disk)->kobj, &d->kobj, "bcache"))
826 		pr_debug("error creating sysfs link");
827 }
828 
cached_dev_detach_finish(struct work_struct * w)829 static void cached_dev_detach_finish(struct work_struct *w)
830 {
831 	struct cached_dev *dc = container_of(w, struct cached_dev, detach);
832 	char buf[BDEVNAME_SIZE];
833 	struct closure cl;
834 	closure_init_stack(&cl);
835 
836 	BUG_ON(!atomic_read(&dc->disk.detaching));
837 	BUG_ON(atomic_read(&dc->count));
838 
839 	mutex_lock(&bch_register_lock);
840 
841 	memset(&dc->sb.set_uuid, 0, 16);
842 	SET_BDEV_STATE(&dc->sb, BDEV_STATE_NONE);
843 
844 	bch_write_bdev_super(dc, &cl);
845 	closure_sync(&cl);
846 
847 	bcache_device_detach(&dc->disk);
848 	list_move(&dc->list, &uncached_devices);
849 
850 	mutex_unlock(&bch_register_lock);
851 
852 	pr_info("Caching disabled for %s", bdevname(dc->bdev, buf));
853 
854 	/* Drop ref we took in cached_dev_detach() */
855 	closure_put(&dc->disk.cl);
856 }
857 
bch_cached_dev_detach(struct cached_dev * dc)858 void bch_cached_dev_detach(struct cached_dev *dc)
859 {
860 	lockdep_assert_held(&bch_register_lock);
861 
862 	if (atomic_read(&dc->disk.closing))
863 		return;
864 
865 	if (atomic_xchg(&dc->disk.detaching, 1))
866 		return;
867 
868 	/*
869 	 * Block the device from being closed and freed until we're finished
870 	 * detaching
871 	 */
872 	closure_get(&dc->disk.cl);
873 
874 	bch_writeback_queue(dc);
875 	cached_dev_put(dc);
876 }
877 
bch_cached_dev_attach(struct cached_dev * dc,struct cache_set * c)878 int bch_cached_dev_attach(struct cached_dev *dc, struct cache_set *c)
879 {
880 	uint32_t rtime = cpu_to_le32(get_seconds());
881 	struct uuid_entry *u;
882 	char buf[BDEVNAME_SIZE];
883 
884 	bdevname(dc->bdev, buf);
885 
886 	if (memcmp(dc->sb.set_uuid, c->sb.set_uuid, 16))
887 		return -ENOENT;
888 
889 	if (dc->disk.c) {
890 		pr_err("Can't attach %s: already attached", buf);
891 		return -EINVAL;
892 	}
893 
894 	if (test_bit(CACHE_SET_STOPPING, &c->flags)) {
895 		pr_err("Can't attach %s: shutting down", buf);
896 		return -EINVAL;
897 	}
898 
899 	if (dc->sb.block_size < c->sb.block_size) {
900 		/* Will die */
901 		pr_err("Couldn't attach %s: block size less than set's block size",
902 		       buf);
903 		return -EINVAL;
904 	}
905 
906 	u = uuid_find(c, dc->sb.uuid);
907 
908 	if (u &&
909 	    (BDEV_STATE(&dc->sb) == BDEV_STATE_STALE ||
910 	     BDEV_STATE(&dc->sb) == BDEV_STATE_NONE)) {
911 		memcpy(u->uuid, invalid_uuid, 16);
912 		u->invalidated = cpu_to_le32(get_seconds());
913 		u = NULL;
914 	}
915 
916 	if (!u) {
917 		if (BDEV_STATE(&dc->sb) == BDEV_STATE_DIRTY) {
918 			pr_err("Couldn't find uuid for %s in set", buf);
919 			return -ENOENT;
920 		}
921 
922 		u = uuid_find_empty(c);
923 		if (!u) {
924 			pr_err("Not caching %s, no room for UUID", buf);
925 			return -EINVAL;
926 		}
927 	}
928 
929 	/* Deadlocks since we're called via sysfs...
930 	sysfs_remove_file(&dc->kobj, &sysfs_attach);
931 	 */
932 
933 	if (bch_is_zero(u->uuid, 16)) {
934 		struct closure cl;
935 		closure_init_stack(&cl);
936 
937 		memcpy(u->uuid, dc->sb.uuid, 16);
938 		memcpy(u->label, dc->sb.label, SB_LABEL_SIZE);
939 		u->first_reg = u->last_reg = rtime;
940 		bch_uuid_write(c);
941 
942 		memcpy(dc->sb.set_uuid, c->sb.set_uuid, 16);
943 		SET_BDEV_STATE(&dc->sb, BDEV_STATE_CLEAN);
944 
945 		bch_write_bdev_super(dc, &cl);
946 		closure_sync(&cl);
947 	} else {
948 		u->last_reg = rtime;
949 		bch_uuid_write(c);
950 	}
951 
952 	bcache_device_attach(&dc->disk, c, u - c->uuids);
953 	list_move(&dc->list, &c->cached_devs);
954 	calc_cached_dev_sectors(c);
955 
956 	smp_wmb();
957 	/*
958 	 * dc->c must be set before dc->count != 0 - paired with the mb in
959 	 * cached_dev_get()
960 	 */
961 	atomic_set(&dc->count, 1);
962 
963 	if (BDEV_STATE(&dc->sb) == BDEV_STATE_DIRTY) {
964 		atomic_set(&dc->has_dirty, 1);
965 		atomic_inc(&dc->count);
966 		bch_writeback_queue(dc);
967 	}
968 
969 	bch_cached_dev_run(dc);
970 	bcache_device_link(&dc->disk, c, "bdev");
971 
972 	pr_info("Caching %s as %s on set %pU",
973 		bdevname(dc->bdev, buf), dc->disk.disk->disk_name,
974 		dc->disk.c->sb.set_uuid);
975 	return 0;
976 }
977 
bch_cached_dev_release(struct kobject * kobj)978 void bch_cached_dev_release(struct kobject *kobj)
979 {
980 	struct cached_dev *dc = container_of(kobj, struct cached_dev,
981 					     disk.kobj);
982 	kfree(dc);
983 	module_put(THIS_MODULE);
984 }
985 
cached_dev_free(struct closure * cl)986 static void cached_dev_free(struct closure *cl)
987 {
988 	struct cached_dev *dc = container_of(cl, struct cached_dev, disk.cl);
989 
990 	cancel_delayed_work_sync(&dc->writeback_rate_update);
991 
992 	mutex_lock(&bch_register_lock);
993 
994 	if (atomic_read(&dc->running))
995 		bd_unlink_disk_holder(dc->bdev, dc->disk.disk);
996 	bcache_device_free(&dc->disk);
997 	list_del(&dc->list);
998 
999 	mutex_unlock(&bch_register_lock);
1000 
1001 	if (!IS_ERR_OR_NULL(dc->bdev)) {
1002 		if (dc->bdev->bd_disk)
1003 			blk_sync_queue(bdev_get_queue(dc->bdev));
1004 
1005 		blkdev_put(dc->bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
1006 	}
1007 
1008 	wake_up(&unregister_wait);
1009 
1010 	kobject_put(&dc->disk.kobj);
1011 }
1012 
cached_dev_flush(struct closure * cl)1013 static void cached_dev_flush(struct closure *cl)
1014 {
1015 	struct cached_dev *dc = container_of(cl, struct cached_dev, disk.cl);
1016 	struct bcache_device *d = &dc->disk;
1017 
1018 	bch_cache_accounting_destroy(&dc->accounting);
1019 	kobject_del(&d->kobj);
1020 
1021 	continue_at(cl, cached_dev_free, system_wq);
1022 }
1023 
cached_dev_init(struct cached_dev * dc,unsigned block_size)1024 static int cached_dev_init(struct cached_dev *dc, unsigned block_size)
1025 {
1026 	int ret;
1027 	struct io *io;
1028 	struct request_queue *q = bdev_get_queue(dc->bdev);
1029 
1030 	__module_get(THIS_MODULE);
1031 	INIT_LIST_HEAD(&dc->list);
1032 	closure_init(&dc->disk.cl, NULL);
1033 	set_closure_fn(&dc->disk.cl, cached_dev_flush, system_wq);
1034 	kobject_init(&dc->disk.kobj, &bch_cached_dev_ktype);
1035 	INIT_WORK(&dc->detach, cached_dev_detach_finish);
1036 	closure_init_unlocked(&dc->sb_write);
1037 	INIT_LIST_HEAD(&dc->io_lru);
1038 	spin_lock_init(&dc->io_lock);
1039 	bch_cache_accounting_init(&dc->accounting, &dc->disk.cl);
1040 
1041 	dc->sequential_merge		= true;
1042 	dc->sequential_cutoff		= 4 << 20;
1043 
1044 	for (io = dc->io; io < dc->io + RECENT_IO; io++) {
1045 		list_add(&io->lru, &dc->io_lru);
1046 		hlist_add_head(&io->hash, dc->io_hash + RECENT_IO);
1047 	}
1048 
1049 	ret = bcache_device_init(&dc->disk, block_size);
1050 	if (ret)
1051 		return ret;
1052 
1053 	set_capacity(dc->disk.disk,
1054 		     dc->bdev->bd_part->nr_sects - dc->sb.data_offset);
1055 
1056 	dc->disk.disk->queue->backing_dev_info.ra_pages =
1057 		max(dc->disk.disk->queue->backing_dev_info.ra_pages,
1058 		    q->backing_dev_info.ra_pages);
1059 
1060 	bch_cached_dev_request_init(dc);
1061 	bch_cached_dev_writeback_init(dc);
1062 	return 0;
1063 }
1064 
1065 /* Cached device - bcache superblock */
1066 
register_bdev(struct cache_sb * sb,struct page * sb_page,struct block_device * bdev,struct cached_dev * dc)1067 static void register_bdev(struct cache_sb *sb, struct page *sb_page,
1068 				 struct block_device *bdev,
1069 				 struct cached_dev *dc)
1070 {
1071 	char name[BDEVNAME_SIZE];
1072 	const char *err = "cannot allocate memory";
1073 	struct cache_set *c;
1074 
1075 	memcpy(&dc->sb, sb, sizeof(struct cache_sb));
1076 	dc->bdev = bdev;
1077 	dc->bdev->bd_holder = dc;
1078 
1079 	bio_init(&dc->sb_bio);
1080 	dc->sb_bio.bi_max_vecs	= 1;
1081 	dc->sb_bio.bi_io_vec	= dc->sb_bio.bi_inline_vecs;
1082 	dc->sb_bio.bi_io_vec[0].bv_page = sb_page;
1083 	get_page(sb_page);
1084 
1085 	if (cached_dev_init(dc, sb->block_size << 9))
1086 		goto err;
1087 
1088 	err = "error creating kobject";
1089 	if (kobject_add(&dc->disk.kobj, &part_to_dev(bdev->bd_part)->kobj,
1090 			"bcache"))
1091 		goto err;
1092 	if (bch_cache_accounting_add_kobjs(&dc->accounting, &dc->disk.kobj))
1093 		goto err;
1094 
1095 	pr_info("registered backing device %s", bdevname(bdev, name));
1096 
1097 	list_add(&dc->list, &uncached_devices);
1098 	list_for_each_entry(c, &bch_cache_sets, list)
1099 		bch_cached_dev_attach(dc, c);
1100 
1101 	if (BDEV_STATE(&dc->sb) == BDEV_STATE_NONE ||
1102 	    BDEV_STATE(&dc->sb) == BDEV_STATE_STALE)
1103 		bch_cached_dev_run(dc);
1104 
1105 	return;
1106 err:
1107 	pr_notice("error opening %s: %s", bdevname(bdev, name), err);
1108 	bcache_device_stop(&dc->disk);
1109 }
1110 
1111 /* Flash only volumes */
1112 
bch_flash_dev_release(struct kobject * kobj)1113 void bch_flash_dev_release(struct kobject *kobj)
1114 {
1115 	struct bcache_device *d = container_of(kobj, struct bcache_device,
1116 					       kobj);
1117 	kfree(d);
1118 }
1119 
flash_dev_free(struct closure * cl)1120 static void flash_dev_free(struct closure *cl)
1121 {
1122 	struct bcache_device *d = container_of(cl, struct bcache_device, cl);
1123 	bcache_device_free(d);
1124 	kobject_put(&d->kobj);
1125 }
1126 
flash_dev_flush(struct closure * cl)1127 static void flash_dev_flush(struct closure *cl)
1128 {
1129 	struct bcache_device *d = container_of(cl, struct bcache_device, cl);
1130 
1131 	bcache_device_unlink(d);
1132 	kobject_del(&d->kobj);
1133 	continue_at(cl, flash_dev_free, system_wq);
1134 }
1135 
flash_dev_run(struct cache_set * c,struct uuid_entry * u)1136 static int flash_dev_run(struct cache_set *c, struct uuid_entry *u)
1137 {
1138 	struct bcache_device *d = kzalloc(sizeof(struct bcache_device),
1139 					  GFP_KERNEL);
1140 	if (!d)
1141 		return -ENOMEM;
1142 
1143 	closure_init(&d->cl, NULL);
1144 	set_closure_fn(&d->cl, flash_dev_flush, system_wq);
1145 
1146 	kobject_init(&d->kobj, &bch_flash_dev_ktype);
1147 
1148 	if (bcache_device_init(d, block_bytes(c)))
1149 		goto err;
1150 
1151 	bcache_device_attach(d, c, u - c->uuids);
1152 	set_capacity(d->disk, u->sectors);
1153 	bch_flash_dev_request_init(d);
1154 	add_disk(d->disk);
1155 
1156 	if (kobject_add(&d->kobj, &disk_to_dev(d->disk)->kobj, "bcache"))
1157 		goto err;
1158 
1159 	bcache_device_link(d, c, "volume");
1160 
1161 	return 0;
1162 err:
1163 	kobject_put(&d->kobj);
1164 	return -ENOMEM;
1165 }
1166 
flash_devs_run(struct cache_set * c)1167 static int flash_devs_run(struct cache_set *c)
1168 {
1169 	int ret = 0;
1170 	struct uuid_entry *u;
1171 
1172 	for (u = c->uuids;
1173 	     u < c->uuids + c->nr_uuids && !ret;
1174 	     u++)
1175 		if (UUID_FLASH_ONLY(u))
1176 			ret = flash_dev_run(c, u);
1177 
1178 	return ret;
1179 }
1180 
bch_flash_dev_create(struct cache_set * c,uint64_t size)1181 int bch_flash_dev_create(struct cache_set *c, uint64_t size)
1182 {
1183 	struct uuid_entry *u;
1184 
1185 	if (test_bit(CACHE_SET_STOPPING, &c->flags))
1186 		return -EINTR;
1187 
1188 	u = uuid_find_empty(c);
1189 	if (!u) {
1190 		pr_err("Can't create volume, no room for UUID");
1191 		return -EINVAL;
1192 	}
1193 
1194 	get_random_bytes(u->uuid, 16);
1195 	memset(u->label, 0, 32);
1196 	u->first_reg = u->last_reg = cpu_to_le32(get_seconds());
1197 
1198 	SET_UUID_FLASH_ONLY(u, 1);
1199 	u->sectors = size >> 9;
1200 
1201 	bch_uuid_write(c);
1202 
1203 	return flash_dev_run(c, u);
1204 }
1205 
1206 /* Cache set */
1207 
1208 __printf(2, 3)
bch_cache_set_error(struct cache_set * c,const char * fmt,...)1209 bool bch_cache_set_error(struct cache_set *c, const char *fmt, ...)
1210 {
1211 	va_list args;
1212 
1213 	if (test_bit(CACHE_SET_STOPPING, &c->flags))
1214 		return false;
1215 
1216 	/* XXX: we can be called from atomic context
1217 	acquire_console_sem();
1218 	*/
1219 
1220 	printk(KERN_ERR "bcache: error on %pU: ", c->sb.set_uuid);
1221 
1222 	va_start(args, fmt);
1223 	vprintk(fmt, args);
1224 	va_end(args);
1225 
1226 	printk(", disabling caching\n");
1227 
1228 	bch_cache_set_unregister(c);
1229 	return true;
1230 }
1231 
bch_cache_set_release(struct kobject * kobj)1232 void bch_cache_set_release(struct kobject *kobj)
1233 {
1234 	struct cache_set *c = container_of(kobj, struct cache_set, kobj);
1235 	kfree(c);
1236 	module_put(THIS_MODULE);
1237 }
1238 
cache_set_free(struct closure * cl)1239 static void cache_set_free(struct closure *cl)
1240 {
1241 	struct cache_set *c = container_of(cl, struct cache_set, cl);
1242 	struct cache *ca;
1243 	unsigned i;
1244 
1245 	if (!IS_ERR_OR_NULL(c->debug))
1246 		debugfs_remove(c->debug);
1247 
1248 	bch_open_buckets_free(c);
1249 	bch_btree_cache_free(c);
1250 	bch_journal_free(c);
1251 
1252 	for_each_cache(ca, c, i)
1253 		if (ca)
1254 			kobject_put(&ca->kobj);
1255 
1256 	free_pages((unsigned long) c->uuids, ilog2(bucket_pages(c)));
1257 	free_pages((unsigned long) c->sort, ilog2(bucket_pages(c)));
1258 
1259 	kfree(c->fill_iter);
1260 	if (c->bio_split)
1261 		bioset_free(c->bio_split);
1262 	if (c->bio_meta)
1263 		mempool_destroy(c->bio_meta);
1264 	if (c->search)
1265 		mempool_destroy(c->search);
1266 	kfree(c->devices);
1267 
1268 	mutex_lock(&bch_register_lock);
1269 	list_del(&c->list);
1270 	mutex_unlock(&bch_register_lock);
1271 
1272 	pr_info("Cache set %pU unregistered", c->sb.set_uuid);
1273 	wake_up(&unregister_wait);
1274 
1275 	closure_debug_destroy(&c->cl);
1276 	kobject_put(&c->kobj);
1277 }
1278 
cache_set_flush(struct closure * cl)1279 static void cache_set_flush(struct closure *cl)
1280 {
1281 	struct cache_set *c = container_of(cl, struct cache_set, caching);
1282 	struct btree *b;
1283 
1284 	/* Shut down allocator threads */
1285 	set_bit(CACHE_SET_STOPPING_2, &c->flags);
1286 	wake_up(&c->alloc_wait);
1287 
1288 	bch_cache_accounting_destroy(&c->accounting);
1289 
1290 	kobject_put(&c->internal);
1291 	kobject_del(&c->kobj);
1292 
1293 	if (!IS_ERR_OR_NULL(c->root))
1294 		list_add(&c->root->list, &c->btree_cache);
1295 
1296 	/* Should skip this if we're unregistering because of an error */
1297 	list_for_each_entry(b, &c->btree_cache, list)
1298 		if (btree_node_dirty(b))
1299 			bch_btree_write(b, true, NULL);
1300 
1301 	closure_return(cl);
1302 }
1303 
__cache_set_unregister(struct closure * cl)1304 static void __cache_set_unregister(struct closure *cl)
1305 {
1306 	struct cache_set *c = container_of(cl, struct cache_set, caching);
1307 	struct cached_dev *dc, *t;
1308 	size_t i;
1309 
1310 	mutex_lock(&bch_register_lock);
1311 
1312 	if (test_bit(CACHE_SET_UNREGISTERING, &c->flags))
1313 		list_for_each_entry_safe(dc, t, &c->cached_devs, list)
1314 			bch_cached_dev_detach(dc);
1315 
1316 	for (i = 0; i < c->nr_uuids; i++)
1317 		if (c->devices[i] && UUID_FLASH_ONLY(&c->uuids[i]))
1318 			bcache_device_stop(c->devices[i]);
1319 
1320 	mutex_unlock(&bch_register_lock);
1321 
1322 	continue_at(cl, cache_set_flush, system_wq);
1323 }
1324 
bch_cache_set_stop(struct cache_set * c)1325 void bch_cache_set_stop(struct cache_set *c)
1326 {
1327 	if (!test_and_set_bit(CACHE_SET_STOPPING, &c->flags))
1328 		closure_queue(&c->caching);
1329 }
1330 
bch_cache_set_unregister(struct cache_set * c)1331 void bch_cache_set_unregister(struct cache_set *c)
1332 {
1333 	set_bit(CACHE_SET_UNREGISTERING, &c->flags);
1334 	bch_cache_set_stop(c);
1335 }
1336 
1337 #define alloc_bucket_pages(gfp, c)			\
1338 	((void *) __get_free_pages(__GFP_ZERO|gfp, ilog2(bucket_pages(c))))
1339 
bch_cache_set_alloc(struct cache_sb * sb)1340 struct cache_set *bch_cache_set_alloc(struct cache_sb *sb)
1341 {
1342 	int iter_size;
1343 	struct cache_set *c = kzalloc(sizeof(struct cache_set), GFP_KERNEL);
1344 	if (!c)
1345 		return NULL;
1346 
1347 	__module_get(THIS_MODULE);
1348 	closure_init(&c->cl, NULL);
1349 	set_closure_fn(&c->cl, cache_set_free, system_wq);
1350 
1351 	closure_init(&c->caching, &c->cl);
1352 	set_closure_fn(&c->caching, __cache_set_unregister, system_wq);
1353 
1354 	/* Maybe create continue_at_noreturn() and use it here? */
1355 	closure_set_stopped(&c->cl);
1356 	closure_put(&c->cl);
1357 
1358 	kobject_init(&c->kobj, &bch_cache_set_ktype);
1359 	kobject_init(&c->internal, &bch_cache_set_internal_ktype);
1360 
1361 	bch_cache_accounting_init(&c->accounting, &c->cl);
1362 
1363 	memcpy(c->sb.set_uuid, sb->set_uuid, 16);
1364 	c->sb.block_size	= sb->block_size;
1365 	c->sb.bucket_size	= sb->bucket_size;
1366 	c->sb.nr_in_set		= sb->nr_in_set;
1367 	c->sb.last_mount	= sb->last_mount;
1368 	c->bucket_bits		= ilog2(sb->bucket_size);
1369 	c->block_bits		= ilog2(sb->block_size);
1370 	c->nr_uuids		= bucket_bytes(c) / sizeof(struct uuid_entry);
1371 
1372 	c->btree_pages		= c->sb.bucket_size / PAGE_SECTORS;
1373 	if (c->btree_pages > BTREE_MAX_PAGES)
1374 		c->btree_pages = max_t(int, c->btree_pages / 4,
1375 				       BTREE_MAX_PAGES);
1376 
1377 	init_waitqueue_head(&c->alloc_wait);
1378 	mutex_init(&c->bucket_lock);
1379 	mutex_init(&c->fill_lock);
1380 	mutex_init(&c->sort_lock);
1381 	spin_lock_init(&c->sort_time_lock);
1382 	closure_init_unlocked(&c->sb_write);
1383 	closure_init_unlocked(&c->uuid_write);
1384 	spin_lock_init(&c->btree_read_time_lock);
1385 	bch_moving_init_cache_set(c);
1386 
1387 	INIT_LIST_HEAD(&c->list);
1388 	INIT_LIST_HEAD(&c->cached_devs);
1389 	INIT_LIST_HEAD(&c->btree_cache);
1390 	INIT_LIST_HEAD(&c->btree_cache_freeable);
1391 	INIT_LIST_HEAD(&c->btree_cache_freed);
1392 	INIT_LIST_HEAD(&c->data_buckets);
1393 
1394 	c->search = mempool_create_slab_pool(32, bch_search_cache);
1395 	if (!c->search)
1396 		goto err;
1397 
1398 	iter_size = (sb->bucket_size / sb->block_size + 1) *
1399 		sizeof(struct btree_iter_set);
1400 
1401 	if (!(c->devices = kzalloc(c->nr_uuids * sizeof(void *), GFP_KERNEL)) ||
1402 	    !(c->bio_meta = mempool_create_kmalloc_pool(2,
1403 				sizeof(struct bbio) + sizeof(struct bio_vec) *
1404 				bucket_pages(c))) ||
1405 	    !(c->bio_split = bioset_create(4, offsetof(struct bbio, bio))) ||
1406 	    !(c->fill_iter = kmalloc(iter_size, GFP_KERNEL)) ||
1407 	    !(c->sort = alloc_bucket_pages(GFP_KERNEL, c)) ||
1408 	    !(c->uuids = alloc_bucket_pages(GFP_KERNEL, c)) ||
1409 	    bch_journal_alloc(c) ||
1410 	    bch_btree_cache_alloc(c) ||
1411 	    bch_open_buckets_alloc(c))
1412 		goto err;
1413 
1414 	c->fill_iter->size = sb->bucket_size / sb->block_size;
1415 
1416 	c->congested_read_threshold_us	= 2000;
1417 	c->congested_write_threshold_us	= 20000;
1418 	c->error_limit	= 8 << IO_ERROR_SHIFT;
1419 
1420 	return c;
1421 err:
1422 	bch_cache_set_unregister(c);
1423 	return NULL;
1424 }
1425 
run_cache_set(struct cache_set * c)1426 static void run_cache_set(struct cache_set *c)
1427 {
1428 	const char *err = "cannot allocate memory";
1429 	struct cached_dev *dc, *t;
1430 	struct cache *ca;
1431 	unsigned i;
1432 
1433 	struct btree_op op;
1434 	bch_btree_op_init_stack(&op);
1435 	op.lock = SHRT_MAX;
1436 
1437 	for_each_cache(ca, c, i)
1438 		c->nbuckets += ca->sb.nbuckets;
1439 
1440 	if (CACHE_SYNC(&c->sb)) {
1441 		LIST_HEAD(journal);
1442 		struct bkey *k;
1443 		struct jset *j;
1444 
1445 		err = "cannot allocate memory for journal";
1446 		if (bch_journal_read(c, &journal, &op))
1447 			goto err;
1448 
1449 		pr_debug("btree_journal_read() done");
1450 
1451 		err = "no journal entries found";
1452 		if (list_empty(&journal))
1453 			goto err;
1454 
1455 		j = &list_entry(journal.prev, struct journal_replay, list)->j;
1456 
1457 		err = "IO error reading priorities";
1458 		for_each_cache(ca, c, i)
1459 			prio_read(ca, j->prio_bucket[ca->sb.nr_this_dev]);
1460 
1461 		/*
1462 		 * If prio_read() fails it'll call cache_set_error and we'll
1463 		 * tear everything down right away, but if we perhaps checked
1464 		 * sooner we could avoid journal replay.
1465 		 */
1466 
1467 		k = &j->btree_root;
1468 
1469 		err = "bad btree root";
1470 		if (__bch_ptr_invalid(c, j->btree_level + 1, k))
1471 			goto err;
1472 
1473 		err = "error reading btree root";
1474 		c->root = bch_btree_node_get(c, k, j->btree_level, &op);
1475 		if (IS_ERR_OR_NULL(c->root))
1476 			goto err;
1477 
1478 		list_del_init(&c->root->list);
1479 		rw_unlock(true, c->root);
1480 
1481 		err = uuid_read(c, j, &op.cl);
1482 		if (err)
1483 			goto err;
1484 
1485 		err = "error in recovery";
1486 		if (bch_btree_check(c, &op))
1487 			goto err;
1488 
1489 		bch_journal_mark(c, &journal);
1490 		bch_btree_gc_finish(c);
1491 		pr_debug("btree_check() done");
1492 
1493 		/*
1494 		 * bcache_journal_next() can't happen sooner, or
1495 		 * btree_gc_finish() will give spurious errors about last_gc >
1496 		 * gc_gen - this is a hack but oh well.
1497 		 */
1498 		bch_journal_next(&c->journal);
1499 
1500 		for_each_cache(ca, c, i)
1501 			closure_call(&ca->alloc, bch_allocator_thread,
1502 				     system_wq, &c->cl);
1503 
1504 		/*
1505 		 * First place it's safe to allocate: btree_check() and
1506 		 * btree_gc_finish() have to run before we have buckets to
1507 		 * allocate, and bch_bucket_alloc_set() might cause a journal
1508 		 * entry to be written so bcache_journal_next() has to be called
1509 		 * first.
1510 		 *
1511 		 * If the uuids were in the old format we have to rewrite them
1512 		 * before the next journal entry is written:
1513 		 */
1514 		if (j->version < BCACHE_JSET_VERSION_UUID)
1515 			__uuid_write(c);
1516 
1517 		bch_journal_replay(c, &journal, &op);
1518 	} else {
1519 		pr_notice("invalidating existing data");
1520 		/* Don't want invalidate_buckets() to queue a gc yet */
1521 		closure_lock(&c->gc, NULL);
1522 
1523 		for_each_cache(ca, c, i) {
1524 			unsigned j;
1525 
1526 			ca->sb.keys = clamp_t(int, ca->sb.nbuckets >> 7,
1527 					      2, SB_JOURNAL_BUCKETS);
1528 
1529 			for (j = 0; j < ca->sb.keys; j++)
1530 				ca->sb.d[j] = ca->sb.first_bucket + j;
1531 		}
1532 
1533 		bch_btree_gc_finish(c);
1534 
1535 		for_each_cache(ca, c, i)
1536 			closure_call(&ca->alloc, bch_allocator_thread,
1537 				     ca->alloc_workqueue, &c->cl);
1538 
1539 		mutex_lock(&c->bucket_lock);
1540 		for_each_cache(ca, c, i)
1541 			bch_prio_write(ca);
1542 		mutex_unlock(&c->bucket_lock);
1543 
1544 		wake_up(&c->alloc_wait);
1545 
1546 		err = "cannot allocate new UUID bucket";
1547 		if (__uuid_write(c))
1548 			goto err_unlock_gc;
1549 
1550 		err = "cannot allocate new btree root";
1551 		c->root = bch_btree_node_alloc(c, 0, &op.cl);
1552 		if (IS_ERR_OR_NULL(c->root))
1553 			goto err_unlock_gc;
1554 
1555 		bkey_copy_key(&c->root->key, &MAX_KEY);
1556 		bch_btree_write(c->root, true, &op);
1557 
1558 		bch_btree_set_root(c->root);
1559 		rw_unlock(true, c->root);
1560 
1561 		/*
1562 		 * We don't want to write the first journal entry until
1563 		 * everything is set up - fortunately journal entries won't be
1564 		 * written until the SET_CACHE_SYNC() here:
1565 		 */
1566 		SET_CACHE_SYNC(&c->sb, true);
1567 
1568 		bch_journal_next(&c->journal);
1569 		bch_journal_meta(c, &op.cl);
1570 
1571 		/* Unlock */
1572 		closure_set_stopped(&c->gc.cl);
1573 		closure_put(&c->gc.cl);
1574 	}
1575 
1576 	closure_sync(&op.cl);
1577 	c->sb.last_mount = get_seconds();
1578 	bcache_write_super(c);
1579 
1580 	list_for_each_entry_safe(dc, t, &uncached_devices, list)
1581 		bch_cached_dev_attach(dc, c);
1582 
1583 	flash_devs_run(c);
1584 
1585 	return;
1586 err_unlock_gc:
1587 	closure_set_stopped(&c->gc.cl);
1588 	closure_put(&c->gc.cl);
1589 err:
1590 	closure_sync(&op.cl);
1591 	/* XXX: test this, it's broken */
1592 	bch_cache_set_error(c, err);
1593 }
1594 
can_attach_cache(struct cache * ca,struct cache_set * c)1595 static bool can_attach_cache(struct cache *ca, struct cache_set *c)
1596 {
1597 	return ca->sb.block_size	== c->sb.block_size &&
1598 		ca->sb.bucket_size	== c->sb.block_size &&
1599 		ca->sb.nr_in_set	== c->sb.nr_in_set;
1600 }
1601 
register_cache_set(struct cache * ca)1602 static const char *register_cache_set(struct cache *ca)
1603 {
1604 	char buf[12];
1605 	const char *err = "cannot allocate memory";
1606 	struct cache_set *c;
1607 
1608 	list_for_each_entry(c, &bch_cache_sets, list)
1609 		if (!memcmp(c->sb.set_uuid, ca->sb.set_uuid, 16)) {
1610 			if (c->cache[ca->sb.nr_this_dev])
1611 				return "duplicate cache set member";
1612 
1613 			if (!can_attach_cache(ca, c))
1614 				return "cache sb does not match set";
1615 
1616 			if (!CACHE_SYNC(&ca->sb))
1617 				SET_CACHE_SYNC(&c->sb, false);
1618 
1619 			goto found;
1620 		}
1621 
1622 	c = bch_cache_set_alloc(&ca->sb);
1623 	if (!c)
1624 		return err;
1625 
1626 	err = "error creating kobject";
1627 	if (kobject_add(&c->kobj, bcache_kobj, "%pU", c->sb.set_uuid) ||
1628 	    kobject_add(&c->internal, &c->kobj, "internal"))
1629 		goto err;
1630 
1631 	if (bch_cache_accounting_add_kobjs(&c->accounting, &c->kobj))
1632 		goto err;
1633 
1634 	bch_debug_init_cache_set(c);
1635 
1636 	list_add(&c->list, &bch_cache_sets);
1637 found:
1638 	sprintf(buf, "cache%i", ca->sb.nr_this_dev);
1639 	if (sysfs_create_link(&ca->kobj, &c->kobj, "set") ||
1640 	    sysfs_create_link(&c->kobj, &ca->kobj, buf))
1641 		goto err;
1642 
1643 	if (ca->sb.seq > c->sb.seq) {
1644 		c->sb.version		= ca->sb.version;
1645 		memcpy(c->sb.set_uuid, ca->sb.set_uuid, 16);
1646 		c->sb.flags             = ca->sb.flags;
1647 		c->sb.seq		= ca->sb.seq;
1648 		pr_debug("set version = %llu", c->sb.version);
1649 	}
1650 
1651 	ca->set = c;
1652 	ca->set->cache[ca->sb.nr_this_dev] = ca;
1653 	c->cache_by_alloc[c->caches_loaded++] = ca;
1654 
1655 	if (c->caches_loaded == c->sb.nr_in_set)
1656 		run_cache_set(c);
1657 
1658 	return NULL;
1659 err:
1660 	bch_cache_set_unregister(c);
1661 	return err;
1662 }
1663 
1664 /* Cache device */
1665 
bch_cache_release(struct kobject * kobj)1666 void bch_cache_release(struct kobject *kobj)
1667 {
1668 	struct cache *ca = container_of(kobj, struct cache, kobj);
1669 
1670 	if (ca->set)
1671 		ca->set->cache[ca->sb.nr_this_dev] = NULL;
1672 
1673 	bch_cache_allocator_exit(ca);
1674 
1675 	bio_split_pool_free(&ca->bio_split_hook);
1676 
1677 	if (ca->alloc_workqueue)
1678 		destroy_workqueue(ca->alloc_workqueue);
1679 
1680 	free_pages((unsigned long) ca->disk_buckets, ilog2(bucket_pages(ca)));
1681 	kfree(ca->prio_buckets);
1682 	vfree(ca->buckets);
1683 
1684 	free_heap(&ca->heap);
1685 	free_fifo(&ca->unused);
1686 	free_fifo(&ca->free_inc);
1687 	free_fifo(&ca->free);
1688 
1689 	if (ca->sb_bio.bi_inline_vecs[0].bv_page)
1690 		put_page(ca->sb_bio.bi_io_vec[0].bv_page);
1691 
1692 	if (!IS_ERR_OR_NULL(ca->bdev)) {
1693 		blk_sync_queue(bdev_get_queue(ca->bdev));
1694 		blkdev_put(ca->bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
1695 	}
1696 
1697 	kfree(ca);
1698 	module_put(THIS_MODULE);
1699 }
1700 
cache_alloc(struct cache_sb * sb,struct cache * ca)1701 static int cache_alloc(struct cache_sb *sb, struct cache *ca)
1702 {
1703 	size_t free;
1704 	struct bucket *b;
1705 
1706 	__module_get(THIS_MODULE);
1707 	kobject_init(&ca->kobj, &bch_cache_ktype);
1708 
1709 	INIT_LIST_HEAD(&ca->discards);
1710 
1711 	bio_init(&ca->journal.bio);
1712 	ca->journal.bio.bi_max_vecs = 8;
1713 	ca->journal.bio.bi_io_vec = ca->journal.bio.bi_inline_vecs;
1714 
1715 	free = roundup_pow_of_two(ca->sb.nbuckets) >> 9;
1716 	free = max_t(size_t, free, (prio_buckets(ca) + 8) * 2);
1717 
1718 	if (!init_fifo(&ca->free,	free, GFP_KERNEL) ||
1719 	    !init_fifo(&ca->free_inc,	free << 2, GFP_KERNEL) ||
1720 	    !init_fifo(&ca->unused,	free << 2, GFP_KERNEL) ||
1721 	    !init_heap(&ca->heap,	free << 3, GFP_KERNEL) ||
1722 	    !(ca->buckets	= vzalloc(sizeof(struct bucket) *
1723 					  ca->sb.nbuckets)) ||
1724 	    !(ca->prio_buckets	= kzalloc(sizeof(uint64_t) * prio_buckets(ca) *
1725 					  2, GFP_KERNEL)) ||
1726 	    !(ca->disk_buckets	= alloc_bucket_pages(GFP_KERNEL, ca)) ||
1727 	    !(ca->alloc_workqueue = alloc_workqueue("bch_allocator", 0, 1)) ||
1728 	    bio_split_pool_init(&ca->bio_split_hook))
1729 		return -ENOMEM;
1730 
1731 	ca->prio_last_buckets = ca->prio_buckets + prio_buckets(ca);
1732 
1733 	for_each_bucket(b, ca)
1734 		atomic_set(&b->pin, 0);
1735 
1736 	if (bch_cache_allocator_init(ca))
1737 		goto err;
1738 
1739 	return 0;
1740 err:
1741 	kobject_put(&ca->kobj);
1742 	return -ENOMEM;
1743 }
1744 
register_cache(struct cache_sb * sb,struct page * sb_page,struct block_device * bdev,struct cache * ca)1745 static void register_cache(struct cache_sb *sb, struct page *sb_page,
1746 				  struct block_device *bdev, struct cache *ca)
1747 {
1748 	char name[BDEVNAME_SIZE];
1749 	const char *err = "cannot allocate memory";
1750 
1751 	memcpy(&ca->sb, sb, sizeof(struct cache_sb));
1752 	ca->bdev = bdev;
1753 	ca->bdev->bd_holder = ca;
1754 
1755 	bio_init(&ca->sb_bio);
1756 	ca->sb_bio.bi_max_vecs	= 1;
1757 	ca->sb_bio.bi_io_vec	= ca->sb_bio.bi_inline_vecs;
1758 	ca->sb_bio.bi_io_vec[0].bv_page = sb_page;
1759 	get_page(sb_page);
1760 
1761 	if (blk_queue_discard(bdev_get_queue(ca->bdev)))
1762 		ca->discard = CACHE_DISCARD(&ca->sb);
1763 
1764 	if (cache_alloc(sb, ca) != 0)
1765 		goto err;
1766 
1767 	err = "error creating kobject";
1768 	if (kobject_add(&ca->kobj, &part_to_dev(bdev->bd_part)->kobj, "bcache"))
1769 		goto err;
1770 
1771 	err = register_cache_set(ca);
1772 	if (err)
1773 		goto err;
1774 
1775 	pr_info("registered cache device %s", bdevname(bdev, name));
1776 	return;
1777 err:
1778 	pr_notice("error opening %s: %s", bdevname(bdev, name), err);
1779 	kobject_put(&ca->kobj);
1780 }
1781 
1782 /* Global interfaces/init */
1783 
1784 static ssize_t register_bcache(struct kobject *, struct kobj_attribute *,
1785 			       const char *, size_t);
1786 
1787 kobj_attribute_write(register,		register_bcache);
1788 kobj_attribute_write(register_quiet,	register_bcache);
1789 
register_bcache(struct kobject * k,struct kobj_attribute * attr,const char * buffer,size_t size)1790 static ssize_t register_bcache(struct kobject *k, struct kobj_attribute *attr,
1791 			       const char *buffer, size_t size)
1792 {
1793 	ssize_t ret = size;
1794 	const char *err = "cannot allocate memory";
1795 	char *path = NULL;
1796 	struct cache_sb *sb = NULL;
1797 	struct block_device *bdev = NULL;
1798 	struct page *sb_page = NULL;
1799 
1800 	if (!try_module_get(THIS_MODULE))
1801 		return -EBUSY;
1802 
1803 	mutex_lock(&bch_register_lock);
1804 
1805 	if (!(path = kstrndup(buffer, size, GFP_KERNEL)) ||
1806 	    !(sb = kmalloc(sizeof(struct cache_sb), GFP_KERNEL)))
1807 		goto err;
1808 
1809 	err = "failed to open device";
1810 	bdev = blkdev_get_by_path(strim(path),
1811 				  FMODE_READ|FMODE_WRITE|FMODE_EXCL,
1812 				  sb);
1813 	if (IS_ERR(bdev)) {
1814 		if (bdev == ERR_PTR(-EBUSY))
1815 			err = "device busy";
1816 		goto err;
1817 	}
1818 
1819 	err = "failed to set blocksize";
1820 	if (set_blocksize(bdev, 4096))
1821 		goto err_close;
1822 
1823 	err = read_super(sb, bdev, &sb_page);
1824 	if (err)
1825 		goto err_close;
1826 
1827 	if (SB_IS_BDEV(sb)) {
1828 		struct cached_dev *dc = kzalloc(sizeof(*dc), GFP_KERNEL);
1829 		if (!dc)
1830 			goto err_close;
1831 
1832 		register_bdev(sb, sb_page, bdev, dc);
1833 	} else {
1834 		struct cache *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
1835 		if (!ca)
1836 			goto err_close;
1837 
1838 		register_cache(sb, sb_page, bdev, ca);
1839 	}
1840 out:
1841 	if (sb_page)
1842 		put_page(sb_page);
1843 	kfree(sb);
1844 	kfree(path);
1845 	mutex_unlock(&bch_register_lock);
1846 	module_put(THIS_MODULE);
1847 	return ret;
1848 
1849 err_close:
1850 	blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
1851 err:
1852 	if (attr != &ksysfs_register_quiet)
1853 		pr_info("error opening %s: %s", path, err);
1854 	ret = -EINVAL;
1855 	goto out;
1856 }
1857 
bcache_reboot(struct notifier_block * n,unsigned long code,void * x)1858 static int bcache_reboot(struct notifier_block *n, unsigned long code, void *x)
1859 {
1860 	if (code == SYS_DOWN ||
1861 	    code == SYS_HALT ||
1862 	    code == SYS_POWER_OFF) {
1863 		DEFINE_WAIT(wait);
1864 		unsigned long start = jiffies;
1865 		bool stopped = false;
1866 
1867 		struct cache_set *c, *tc;
1868 		struct cached_dev *dc, *tdc;
1869 
1870 		mutex_lock(&bch_register_lock);
1871 
1872 		if (list_empty(&bch_cache_sets) &&
1873 		    list_empty(&uncached_devices))
1874 			goto out;
1875 
1876 		pr_info("Stopping all devices:");
1877 
1878 		list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
1879 			bch_cache_set_stop(c);
1880 
1881 		list_for_each_entry_safe(dc, tdc, &uncached_devices, list)
1882 			bcache_device_stop(&dc->disk);
1883 
1884 		/* What's a condition variable? */
1885 		while (1) {
1886 			long timeout = start + 2 * HZ - jiffies;
1887 
1888 			stopped = list_empty(&bch_cache_sets) &&
1889 				list_empty(&uncached_devices);
1890 
1891 			if (timeout < 0 || stopped)
1892 				break;
1893 
1894 			prepare_to_wait(&unregister_wait, &wait,
1895 					TASK_UNINTERRUPTIBLE);
1896 
1897 			mutex_unlock(&bch_register_lock);
1898 			schedule_timeout(timeout);
1899 			mutex_lock(&bch_register_lock);
1900 		}
1901 
1902 		finish_wait(&unregister_wait, &wait);
1903 
1904 		if (stopped)
1905 			pr_info("All devices stopped");
1906 		else
1907 			pr_notice("Timeout waiting for devices to be closed");
1908 out:
1909 		mutex_unlock(&bch_register_lock);
1910 	}
1911 
1912 	return NOTIFY_DONE;
1913 }
1914 
1915 static struct notifier_block reboot = {
1916 	.notifier_call	= bcache_reboot,
1917 	.priority	= INT_MAX, /* before any real devices */
1918 };
1919 
bcache_exit(void)1920 static void bcache_exit(void)
1921 {
1922 	bch_debug_exit();
1923 	bch_writeback_exit();
1924 	bch_request_exit();
1925 	bch_btree_exit();
1926 	if (bcache_kobj)
1927 		kobject_put(bcache_kobj);
1928 	if (bcache_wq)
1929 		destroy_workqueue(bcache_wq);
1930 	unregister_blkdev(bcache_major, "bcache");
1931 	unregister_reboot_notifier(&reboot);
1932 }
1933 
bcache_init(void)1934 static int __init bcache_init(void)
1935 {
1936 	static const struct attribute *files[] = {
1937 		&ksysfs_register.attr,
1938 		&ksysfs_register_quiet.attr,
1939 		NULL
1940 	};
1941 
1942 	mutex_init(&bch_register_lock);
1943 	init_waitqueue_head(&unregister_wait);
1944 	register_reboot_notifier(&reboot);
1945 	closure_debug_init();
1946 
1947 	bcache_major = register_blkdev(0, "bcache");
1948 	if (bcache_major < 0)
1949 		return bcache_major;
1950 
1951 	if (!(bcache_wq = create_workqueue("bcache")) ||
1952 	    !(bcache_kobj = kobject_create_and_add("bcache", fs_kobj)) ||
1953 	    sysfs_create_files(bcache_kobj, files) ||
1954 	    bch_btree_init() ||
1955 	    bch_request_init() ||
1956 	    bch_writeback_init() ||
1957 	    bch_debug_init(bcache_kobj))
1958 		goto err;
1959 
1960 	return 0;
1961 err:
1962 	bcache_exit();
1963 	return -ENOMEM;
1964 }
1965 
1966 module_exit(bcache_exit);
1967 module_init(bcache_init);
1968