xref: /openbmc/linux/drivers/md/bcache/super.c (revision a702a692)
187418ef9SColy Li // SPDX-License-Identifier: GPL-2.0
2cafe5635SKent Overstreet /*
3cafe5635SKent Overstreet  * bcache setup/teardown code, and some metadata io - read a superblock and
4cafe5635SKent Overstreet  * figure out what to do with it.
5cafe5635SKent Overstreet  *
6cafe5635SKent Overstreet  * Copyright 2010, 2011 Kent Overstreet <kent.overstreet@gmail.com>
7cafe5635SKent Overstreet  * Copyright 2012 Google, Inc.
8cafe5635SKent Overstreet  */
9cafe5635SKent Overstreet 
10cafe5635SKent Overstreet #include "bcache.h"
11cafe5635SKent Overstreet #include "btree.h"
12cafe5635SKent Overstreet #include "debug.h"
1365d45231SKent Overstreet #include "extents.h"
14cafe5635SKent Overstreet #include "request.h"
15279afbadSKent Overstreet #include "writeback.h"
16cafe5635SKent Overstreet 
17c37511b8SKent Overstreet #include <linux/blkdev.h>
18cafe5635SKent Overstreet #include <linux/buffer_head.h>
19cafe5635SKent Overstreet #include <linux/debugfs.h>
20cafe5635SKent Overstreet #include <linux/genhd.h>
2128935ab5SKent Overstreet #include <linux/idr.h>
2279826c35SKent Overstreet #include <linux/kthread.h>
23cafe5635SKent Overstreet #include <linux/module.h>
24cafe5635SKent Overstreet #include <linux/random.h>
25cafe5635SKent Overstreet #include <linux/reboot.h>
26cafe5635SKent Overstreet #include <linux/sysfs.h>
27cafe5635SKent Overstreet 
289aaf5165SColy Li unsigned int bch_cutoff_writeback;
299aaf5165SColy Li unsigned int bch_cutoff_writeback_sync;
309aaf5165SColy Li 
31cafe5635SKent Overstreet static const char bcache_magic[] = {
32cafe5635SKent Overstreet 	0xc6, 0x85, 0x73, 0xf6, 0x4e, 0x1a, 0x45, 0xca,
33cafe5635SKent Overstreet 	0x82, 0x65, 0xf5, 0x7f, 0x48, 0xba, 0x6d, 0x81
34cafe5635SKent Overstreet };
35cafe5635SKent Overstreet 
36cafe5635SKent Overstreet static const char invalid_uuid[] = {
37cafe5635SKent Overstreet 	0xa0, 0x3e, 0xf8, 0xed, 0x3e, 0xe1, 0xb8, 0x78,
38cafe5635SKent Overstreet 	0xc8, 0x50, 0xfc, 0x5e, 0xcb, 0x16, 0xcd, 0x99
39cafe5635SKent Overstreet };
40cafe5635SKent Overstreet 
41cafe5635SKent Overstreet static struct kobject *bcache_kobj;
42cafe5635SKent Overstreet struct mutex bch_register_lock;
43a59ff6ccSColy Li bool bcache_is_reboot;
44cafe5635SKent Overstreet LIST_HEAD(bch_cache_sets);
45cafe5635SKent Overstreet static LIST_HEAD(uncached_devices);
46cafe5635SKent Overstreet 
4728935ab5SKent Overstreet static int bcache_major;
481dbe32adSColy Li static DEFINE_IDA(bcache_device_idx);
49cafe5635SKent Overstreet static wait_queue_head_t unregister_wait;
50cafe5635SKent Overstreet struct workqueue_struct *bcache_wq;
510f843e65SGuoju Fang struct workqueue_struct *bch_journal_wq;
52cafe5635SKent Overstreet 
53a59ff6ccSColy Li 
54cafe5635SKent Overstreet #define BTREE_MAX_PAGES		(256 * 1024 / PAGE_SIZE)
551dbe32adSColy Li /* limitation of partitions number on single bcache device */
561dbe32adSColy Li #define BCACHE_MINORS		128
571dbe32adSColy Li /* limitation of bcache devices number on single system */
581dbe32adSColy Li #define BCACHE_DEVICE_IDX_MAX	((1U << MINORBITS)/BCACHE_MINORS)
59cafe5635SKent Overstreet 
60cafe5635SKent Overstreet /* Superblock */
61cafe5635SKent Overstreet 
62cafe5635SKent Overstreet static const char *read_super(struct cache_sb *sb, struct block_device *bdev,
63cafe5635SKent Overstreet 			      struct page **res)
64cafe5635SKent Overstreet {
65cafe5635SKent Overstreet 	const char *err;
66a702a692SChristoph Hellwig 	struct cache_sb_disk *s;
67cafe5635SKent Overstreet 	struct buffer_head *bh = __bread(bdev, 1, SB_SIZE);
686f10f7d1SColy Li 	unsigned int i;
69cafe5635SKent Overstreet 
70cafe5635SKent Overstreet 	if (!bh)
71cafe5635SKent Overstreet 		return "IO error";
72cafe5635SKent Overstreet 
73a702a692SChristoph Hellwig 	s = (struct cache_sb_disk *)bh->b_data;
74cafe5635SKent Overstreet 
75cafe5635SKent Overstreet 	sb->offset		= le64_to_cpu(s->offset);
76cafe5635SKent Overstreet 	sb->version		= le64_to_cpu(s->version);
77cafe5635SKent Overstreet 
78cafe5635SKent Overstreet 	memcpy(sb->magic,	s->magic, 16);
79cafe5635SKent Overstreet 	memcpy(sb->uuid,	s->uuid, 16);
80cafe5635SKent Overstreet 	memcpy(sb->set_uuid,	s->set_uuid, 16);
81cafe5635SKent Overstreet 	memcpy(sb->label,	s->label, SB_LABEL_SIZE);
82cafe5635SKent Overstreet 
83cafe5635SKent Overstreet 	sb->flags		= le64_to_cpu(s->flags);
84cafe5635SKent Overstreet 	sb->seq			= le64_to_cpu(s->seq);
85cafe5635SKent Overstreet 	sb->last_mount		= le32_to_cpu(s->last_mount);
86cafe5635SKent Overstreet 	sb->first_bucket	= le16_to_cpu(s->first_bucket);
87cafe5635SKent Overstreet 	sb->keys		= le16_to_cpu(s->keys);
88cafe5635SKent Overstreet 
89cafe5635SKent Overstreet 	for (i = 0; i < SB_JOURNAL_BUCKETS; i++)
90cafe5635SKent Overstreet 		sb->d[i] = le64_to_cpu(s->d[i]);
91cafe5635SKent Overstreet 
92cafe5635SKent Overstreet 	pr_debug("read sb version %llu, flags %llu, seq %llu, journal size %u",
93cafe5635SKent Overstreet 		 sb->version, sb->flags, sb->seq, sb->keys);
94cafe5635SKent Overstreet 
95aaf8dbeaSColy Li 	err = "Not a bcache superblock (bad offset)";
96cafe5635SKent Overstreet 	if (sb->offset != SB_SECTOR)
97cafe5635SKent Overstreet 		goto err;
98cafe5635SKent Overstreet 
99aaf8dbeaSColy Li 	err = "Not a bcache superblock (bad magic)";
100cafe5635SKent Overstreet 	if (memcmp(sb->magic, bcache_magic, 16))
101cafe5635SKent Overstreet 		goto err;
102cafe5635SKent Overstreet 
103cafe5635SKent Overstreet 	err = "Too many journal buckets";
104cafe5635SKent Overstreet 	if (sb->keys > SB_JOURNAL_BUCKETS)
105cafe5635SKent Overstreet 		goto err;
106cafe5635SKent Overstreet 
107cafe5635SKent Overstreet 	err = "Bad checksum";
108cafe5635SKent Overstreet 	if (s->csum != csum_set(s))
109cafe5635SKent Overstreet 		goto err;
110cafe5635SKent Overstreet 
111cafe5635SKent Overstreet 	err = "Bad UUID";
112169ef1cfSKent Overstreet 	if (bch_is_zero(sb->uuid, 16))
113cafe5635SKent Overstreet 		goto err;
114cafe5635SKent Overstreet 
1158abb2a5dSKent Overstreet 	sb->block_size	= le16_to_cpu(s->block_size);
1168abb2a5dSKent Overstreet 
1178abb2a5dSKent Overstreet 	err = "Superblock block size smaller than device block size";
1188abb2a5dSKent Overstreet 	if (sb->block_size << 9 < bdev_logical_block_size(bdev))
1198abb2a5dSKent Overstreet 		goto err;
1208abb2a5dSKent Overstreet 
1212903381fSKent Overstreet 	switch (sb->version) {
1222903381fSKent Overstreet 	case BCACHE_SB_VERSION_BDEV:
1232903381fSKent Overstreet 		sb->data_offset	= BDEV_DATA_START_DEFAULT;
1242903381fSKent Overstreet 		break;
1252903381fSKent Overstreet 	case BCACHE_SB_VERSION_BDEV_WITH_OFFSET:
1262903381fSKent Overstreet 		sb->data_offset	= le64_to_cpu(s->data_offset);
1272903381fSKent Overstreet 
1282903381fSKent Overstreet 		err = "Bad data offset";
1292903381fSKent Overstreet 		if (sb->data_offset < BDEV_DATA_START_DEFAULT)
130cafe5635SKent Overstreet 			goto err;
131cafe5635SKent Overstreet 
1322903381fSKent Overstreet 		break;
1332903381fSKent Overstreet 	case BCACHE_SB_VERSION_CDEV:
1342903381fSKent Overstreet 	case BCACHE_SB_VERSION_CDEV_WITH_UUID:
1352903381fSKent Overstreet 		sb->nbuckets	= le64_to_cpu(s->nbuckets);
1362903381fSKent Overstreet 		sb->bucket_size	= le16_to_cpu(s->bucket_size);
1372903381fSKent Overstreet 
1382903381fSKent Overstreet 		sb->nr_in_set	= le16_to_cpu(s->nr_in_set);
1392903381fSKent Overstreet 		sb->nr_this_dev	= le16_to_cpu(s->nr_this_dev);
140cafe5635SKent Overstreet 
141cafe5635SKent Overstreet 		err = "Too many buckets";
142cafe5635SKent Overstreet 		if (sb->nbuckets > LONG_MAX)
143cafe5635SKent Overstreet 			goto err;
144cafe5635SKent Overstreet 
145cafe5635SKent Overstreet 		err = "Not enough buckets";
146cafe5635SKent Overstreet 		if (sb->nbuckets < 1 << 7)
147cafe5635SKent Overstreet 			goto err;
148cafe5635SKent Overstreet 
1492903381fSKent Overstreet 		err = "Bad block/bucket size";
1502903381fSKent Overstreet 		if (!is_power_of_2(sb->block_size) ||
1512903381fSKent Overstreet 		    sb->block_size > PAGE_SECTORS ||
1522903381fSKent Overstreet 		    !is_power_of_2(sb->bucket_size) ||
1532903381fSKent Overstreet 		    sb->bucket_size < PAGE_SECTORS)
1542903381fSKent Overstreet 			goto err;
1552903381fSKent Overstreet 
156cafe5635SKent Overstreet 		err = "Invalid superblock: device too small";
157b0d30981SColy Li 		if (get_capacity(bdev->bd_disk) <
158b0d30981SColy Li 		    sb->bucket_size * sb->nbuckets)
159cafe5635SKent Overstreet 			goto err;
160cafe5635SKent Overstreet 
161cafe5635SKent Overstreet 		err = "Bad UUID";
162169ef1cfSKent Overstreet 		if (bch_is_zero(sb->set_uuid, 16))
163cafe5635SKent Overstreet 			goto err;
164cafe5635SKent Overstreet 
165cafe5635SKent Overstreet 		err = "Bad cache device number in set";
166cafe5635SKent Overstreet 		if (!sb->nr_in_set ||
167cafe5635SKent Overstreet 		    sb->nr_in_set <= sb->nr_this_dev ||
168cafe5635SKent Overstreet 		    sb->nr_in_set > MAX_CACHES_PER_SET)
169cafe5635SKent Overstreet 			goto err;
170cafe5635SKent Overstreet 
171cafe5635SKent Overstreet 		err = "Journal buckets not sequential";
172cafe5635SKent Overstreet 		for (i = 0; i < sb->keys; i++)
173cafe5635SKent Overstreet 			if (sb->d[i] != sb->first_bucket + i)
174cafe5635SKent Overstreet 				goto err;
175cafe5635SKent Overstreet 
176cafe5635SKent Overstreet 		err = "Too many journal buckets";
177cafe5635SKent Overstreet 		if (sb->first_bucket + sb->keys > sb->nbuckets)
178cafe5635SKent Overstreet 			goto err;
179cafe5635SKent Overstreet 
180cafe5635SKent Overstreet 		err = "Invalid superblock: first bucket comes before end of super";
181cafe5635SKent Overstreet 		if (sb->first_bucket * sb->bucket_size < 16)
182cafe5635SKent Overstreet 			goto err;
1832903381fSKent Overstreet 
1842903381fSKent Overstreet 		break;
1852903381fSKent Overstreet 	default:
1862903381fSKent Overstreet 		err = "Unsupported superblock version";
1872903381fSKent Overstreet 		goto err;
1882903381fSKent Overstreet 	}
1892903381fSKent Overstreet 
19075cbb3f1SArnd Bergmann 	sb->last_mount = (u32)ktime_get_real_seconds();
191cafe5635SKent Overstreet 	err = NULL;
192cafe5635SKent Overstreet 
193cafe5635SKent Overstreet 	get_page(bh->b_page);
194cafe5635SKent Overstreet 	*res = bh->b_page;
195cafe5635SKent Overstreet err:
196cafe5635SKent Overstreet 	put_bh(bh);
197cafe5635SKent Overstreet 	return err;
198cafe5635SKent Overstreet }
199cafe5635SKent Overstreet 
2004246a0b6SChristoph Hellwig static void write_bdev_super_endio(struct bio *bio)
201cafe5635SKent Overstreet {
202cafe5635SKent Overstreet 	struct cached_dev *dc = bio->bi_private;
20308ec1e62SColy Li 
20408ec1e62SColy Li 	if (bio->bi_status)
20508ec1e62SColy Li 		bch_count_backing_io_errors(dc, bio);
206cafe5635SKent Overstreet 
207cb7a583eSKent Overstreet 	closure_put(&dc->sb_write);
208cafe5635SKent Overstreet }
209cafe5635SKent Overstreet 
210cafe5635SKent Overstreet static void __write_super(struct cache_sb *sb, struct bio *bio)
211cafe5635SKent Overstreet {
212a702a692SChristoph Hellwig 	struct cache_sb_disk *out = page_address(bio_first_page_all(bio));
2136f10f7d1SColy Li 	unsigned int i;
214cafe5635SKent Overstreet 
2154f024f37SKent Overstreet 	bio->bi_iter.bi_sector	= SB_SECTOR;
2164f024f37SKent Overstreet 	bio->bi_iter.bi_size	= SB_SIZE;
217ad0d9e76SMike Christie 	bio_set_op_attrs(bio, REQ_OP_WRITE, REQ_SYNC|REQ_META);
218169ef1cfSKent Overstreet 	bch_bio_map(bio, NULL);
219cafe5635SKent Overstreet 
220cafe5635SKent Overstreet 	out->offset		= cpu_to_le64(sb->offset);
221cafe5635SKent Overstreet 	out->version		= cpu_to_le64(sb->version);
222cafe5635SKent Overstreet 
223cafe5635SKent Overstreet 	memcpy(out->uuid,	sb->uuid, 16);
224cafe5635SKent Overstreet 	memcpy(out->set_uuid,	sb->set_uuid, 16);
225cafe5635SKent Overstreet 	memcpy(out->label,	sb->label, SB_LABEL_SIZE);
226cafe5635SKent Overstreet 
227cafe5635SKent Overstreet 	out->flags		= cpu_to_le64(sb->flags);
228cafe5635SKent Overstreet 	out->seq		= cpu_to_le64(sb->seq);
229cafe5635SKent Overstreet 
230cafe5635SKent Overstreet 	out->last_mount		= cpu_to_le32(sb->last_mount);
231cafe5635SKent Overstreet 	out->first_bucket	= cpu_to_le16(sb->first_bucket);
232cafe5635SKent Overstreet 	out->keys		= cpu_to_le16(sb->keys);
233cafe5635SKent Overstreet 
234cafe5635SKent Overstreet 	for (i = 0; i < sb->keys; i++)
235cafe5635SKent Overstreet 		out->d[i] = cpu_to_le64(sb->d[i]);
236cafe5635SKent Overstreet 
237cafe5635SKent Overstreet 	out->csum = csum_set(out);
238cafe5635SKent Overstreet 
239cafe5635SKent Overstreet 	pr_debug("ver %llu, flags %llu, seq %llu",
240cafe5635SKent Overstreet 		 sb->version, sb->flags, sb->seq);
241cafe5635SKent Overstreet 
2424e49ea4aSMike Christie 	submit_bio(bio);
243cafe5635SKent Overstreet }
244cafe5635SKent Overstreet 
245cb7a583eSKent Overstreet static void bch_write_bdev_super_unlock(struct closure *cl)
246cb7a583eSKent Overstreet {
247cb7a583eSKent Overstreet 	struct cached_dev *dc = container_of(cl, struct cached_dev, sb_write);
248cb7a583eSKent Overstreet 
249cb7a583eSKent Overstreet 	up(&dc->sb_write_mutex);
250cb7a583eSKent Overstreet }
251cb7a583eSKent Overstreet 
252cafe5635SKent Overstreet void bch_write_bdev_super(struct cached_dev *dc, struct closure *parent)
253cafe5635SKent Overstreet {
254cb7a583eSKent Overstreet 	struct closure *cl = &dc->sb_write;
255cafe5635SKent Overstreet 	struct bio *bio = &dc->sb_bio;
256cafe5635SKent Overstreet 
257cb7a583eSKent Overstreet 	down(&dc->sb_write_mutex);
258cb7a583eSKent Overstreet 	closure_init(cl, parent);
259cafe5635SKent Overstreet 
260cafe5635SKent Overstreet 	bio_reset(bio);
26174d46992SChristoph Hellwig 	bio_set_dev(bio, dc->bdev);
262cafe5635SKent Overstreet 	bio->bi_end_io	= write_bdev_super_endio;
263cafe5635SKent Overstreet 	bio->bi_private = dc;
264cafe5635SKent Overstreet 
265cafe5635SKent Overstreet 	closure_get(cl);
26627a40ab9SColy Li 	/* I/O request sent to backing device */
267cafe5635SKent Overstreet 	__write_super(&dc->sb, bio);
268cafe5635SKent Overstreet 
269cb7a583eSKent Overstreet 	closure_return_with_destructor(cl, bch_write_bdev_super_unlock);
270cafe5635SKent Overstreet }
271cafe5635SKent Overstreet 
2724246a0b6SChristoph Hellwig static void write_super_endio(struct bio *bio)
273cafe5635SKent Overstreet {
274cafe5635SKent Overstreet 	struct cache *ca = bio->bi_private;
275cafe5635SKent Overstreet 
2765138ac67SColy Li 	/* is_read = 0 */
2775138ac67SColy Li 	bch_count_io_errors(ca, bio->bi_status, 0,
2785138ac67SColy Li 			    "writing superblock");
279cb7a583eSKent Overstreet 	closure_put(&ca->set->sb_write);
280cb7a583eSKent Overstreet }
281cb7a583eSKent Overstreet 
282cb7a583eSKent Overstreet static void bcache_write_super_unlock(struct closure *cl)
283cb7a583eSKent Overstreet {
284cb7a583eSKent Overstreet 	struct cache_set *c = container_of(cl, struct cache_set, sb_write);
285cb7a583eSKent Overstreet 
286cb7a583eSKent Overstreet 	up(&c->sb_write_mutex);
287cafe5635SKent Overstreet }
288cafe5635SKent Overstreet 
289cafe5635SKent Overstreet void bcache_write_super(struct cache_set *c)
290cafe5635SKent Overstreet {
291cb7a583eSKent Overstreet 	struct closure *cl = &c->sb_write;
292cafe5635SKent Overstreet 	struct cache *ca;
2936f10f7d1SColy Li 	unsigned int i;
294cafe5635SKent Overstreet 
295cb7a583eSKent Overstreet 	down(&c->sb_write_mutex);
296cb7a583eSKent Overstreet 	closure_init(cl, &c->cl);
297cafe5635SKent Overstreet 
298cafe5635SKent Overstreet 	c->sb.seq++;
299cafe5635SKent Overstreet 
300cafe5635SKent Overstreet 	for_each_cache(ca, c, i) {
301cafe5635SKent Overstreet 		struct bio *bio = &ca->sb_bio;
302cafe5635SKent Overstreet 
3032903381fSKent Overstreet 		ca->sb.version		= BCACHE_SB_VERSION_CDEV_WITH_UUID;
304cafe5635SKent Overstreet 		ca->sb.seq		= c->sb.seq;
305cafe5635SKent Overstreet 		ca->sb.last_mount	= c->sb.last_mount;
306cafe5635SKent Overstreet 
307cafe5635SKent Overstreet 		SET_CACHE_SYNC(&ca->sb, CACHE_SYNC(&c->sb));
308cafe5635SKent Overstreet 
309cafe5635SKent Overstreet 		bio_reset(bio);
31074d46992SChristoph Hellwig 		bio_set_dev(bio, ca->bdev);
311cafe5635SKent Overstreet 		bio->bi_end_io	= write_super_endio;
312cafe5635SKent Overstreet 		bio->bi_private = ca;
313cafe5635SKent Overstreet 
314cafe5635SKent Overstreet 		closure_get(cl);
315cafe5635SKent Overstreet 		__write_super(&ca->sb, bio);
316cafe5635SKent Overstreet 	}
317cafe5635SKent Overstreet 
318cb7a583eSKent Overstreet 	closure_return_with_destructor(cl, bcache_write_super_unlock);
319cafe5635SKent Overstreet }
320cafe5635SKent Overstreet 
321cafe5635SKent Overstreet /* UUID io */
322cafe5635SKent Overstreet 
3234246a0b6SChristoph Hellwig static void uuid_endio(struct bio *bio)
324cafe5635SKent Overstreet {
325cafe5635SKent Overstreet 	struct closure *cl = bio->bi_private;
326cb7a583eSKent Overstreet 	struct cache_set *c = container_of(cl, struct cache_set, uuid_write);
327cafe5635SKent Overstreet 
3284e4cbee9SChristoph Hellwig 	cache_set_err_on(bio->bi_status, c, "accessing uuids");
329cafe5635SKent Overstreet 	bch_bbio_free(bio, c);
330cafe5635SKent Overstreet 	closure_put(cl);
331cafe5635SKent Overstreet }
332cafe5635SKent Overstreet 
333cb7a583eSKent Overstreet static void uuid_io_unlock(struct closure *cl)
334cb7a583eSKent Overstreet {
335cb7a583eSKent Overstreet 	struct cache_set *c = container_of(cl, struct cache_set, uuid_write);
336cb7a583eSKent Overstreet 
337cb7a583eSKent Overstreet 	up(&c->uuid_write_mutex);
338cb7a583eSKent Overstreet }
339cb7a583eSKent Overstreet 
340ad0d9e76SMike Christie static void uuid_io(struct cache_set *c, int op, unsigned long op_flags,
341cafe5635SKent Overstreet 		    struct bkey *k, struct closure *parent)
342cafe5635SKent Overstreet {
343cb7a583eSKent Overstreet 	struct closure *cl = &c->uuid_write;
344cafe5635SKent Overstreet 	struct uuid_entry *u;
3456f10f7d1SColy Li 	unsigned int i;
34685b1492eSKent Overstreet 	char buf[80];
347cafe5635SKent Overstreet 
348cafe5635SKent Overstreet 	BUG_ON(!parent);
349cb7a583eSKent Overstreet 	down(&c->uuid_write_mutex);
350cb7a583eSKent Overstreet 	closure_init(cl, parent);
351cafe5635SKent Overstreet 
352cafe5635SKent Overstreet 	for (i = 0; i < KEY_PTRS(k); i++) {
353cafe5635SKent Overstreet 		struct bio *bio = bch_bbio_alloc(c);
354cafe5635SKent Overstreet 
3551eff9d32SJens Axboe 		bio->bi_opf = REQ_SYNC | REQ_META | op_flags;
3564f024f37SKent Overstreet 		bio->bi_iter.bi_size = KEY_SIZE(k) << 9;
357cafe5635SKent Overstreet 
358cafe5635SKent Overstreet 		bio->bi_end_io	= uuid_endio;
359cafe5635SKent Overstreet 		bio->bi_private = cl;
360ad0d9e76SMike Christie 		bio_set_op_attrs(bio, op, REQ_SYNC|REQ_META|op_flags);
361169ef1cfSKent Overstreet 		bch_bio_map(bio, c->uuids);
362cafe5635SKent Overstreet 
363cafe5635SKent Overstreet 		bch_submit_bbio(bio, c, k, i);
364cafe5635SKent Overstreet 
365ad0d9e76SMike Christie 		if (op != REQ_OP_WRITE)
366cafe5635SKent Overstreet 			break;
367cafe5635SKent Overstreet 	}
368cafe5635SKent Overstreet 
369dc9d98d6SKent Overstreet 	bch_extent_to_text(buf, sizeof(buf), k);
370ad0d9e76SMike Christie 	pr_debug("%s UUIDs at %s", op == REQ_OP_WRITE ? "wrote" : "read", buf);
371cafe5635SKent Overstreet 
372cafe5635SKent Overstreet 	for (u = c->uuids; u < c->uuids + c->nr_uuids; u++)
373169ef1cfSKent Overstreet 		if (!bch_is_zero(u->uuid, 16))
374cafe5635SKent Overstreet 			pr_debug("Slot %zi: %pU: %s: 1st: %u last: %u inv: %u",
375cafe5635SKent Overstreet 				 u - c->uuids, u->uuid, u->label,
376cafe5635SKent Overstreet 				 u->first_reg, u->last_reg, u->invalidated);
377cafe5635SKent Overstreet 
378cb7a583eSKent Overstreet 	closure_return_with_destructor(cl, uuid_io_unlock);
379cafe5635SKent Overstreet }
380cafe5635SKent Overstreet 
381cafe5635SKent Overstreet static char *uuid_read(struct cache_set *c, struct jset *j, struct closure *cl)
382cafe5635SKent Overstreet {
383cafe5635SKent Overstreet 	struct bkey *k = &j->uuid_bucket;
384cafe5635SKent Overstreet 
38565d45231SKent Overstreet 	if (__bch_btree_ptr_invalid(c, k))
386cafe5635SKent Overstreet 		return "bad uuid pointer";
387cafe5635SKent Overstreet 
388cafe5635SKent Overstreet 	bkey_copy(&c->uuid_bucket, k);
38970fd7614SChristoph Hellwig 	uuid_io(c, REQ_OP_READ, 0, k, cl);
390cafe5635SKent Overstreet 
391cafe5635SKent Overstreet 	if (j->version < BCACHE_JSET_VERSION_UUIDv1) {
392cafe5635SKent Overstreet 		struct uuid_entry_v0	*u0 = (void *) c->uuids;
393cafe5635SKent Overstreet 		struct uuid_entry	*u1 = (void *) c->uuids;
394cafe5635SKent Overstreet 		int i;
395cafe5635SKent Overstreet 
396cafe5635SKent Overstreet 		closure_sync(cl);
397cafe5635SKent Overstreet 
398cafe5635SKent Overstreet 		/*
399cafe5635SKent Overstreet 		 * Since the new uuid entry is bigger than the old, we have to
400cafe5635SKent Overstreet 		 * convert starting at the highest memory address and work down
401cafe5635SKent Overstreet 		 * in order to do it in place
402cafe5635SKent Overstreet 		 */
403cafe5635SKent Overstreet 
404cafe5635SKent Overstreet 		for (i = c->nr_uuids - 1;
405cafe5635SKent Overstreet 		     i >= 0;
406cafe5635SKent Overstreet 		     --i) {
407cafe5635SKent Overstreet 			memcpy(u1[i].uuid,	u0[i].uuid, 16);
408cafe5635SKent Overstreet 			memcpy(u1[i].label,	u0[i].label, 32);
409cafe5635SKent Overstreet 
410cafe5635SKent Overstreet 			u1[i].first_reg		= u0[i].first_reg;
411cafe5635SKent Overstreet 			u1[i].last_reg		= u0[i].last_reg;
412cafe5635SKent Overstreet 			u1[i].invalidated	= u0[i].invalidated;
413cafe5635SKent Overstreet 
414cafe5635SKent Overstreet 			u1[i].flags	= 0;
415cafe5635SKent Overstreet 			u1[i].sectors	= 0;
416cafe5635SKent Overstreet 		}
417cafe5635SKent Overstreet 	}
418cafe5635SKent Overstreet 
419cafe5635SKent Overstreet 	return NULL;
420cafe5635SKent Overstreet }
421cafe5635SKent Overstreet 
422cafe5635SKent Overstreet static int __uuid_write(struct cache_set *c)
423cafe5635SKent Overstreet {
424cafe5635SKent Overstreet 	BKEY_PADDED(key) k;
425cafe5635SKent Overstreet 	struct closure cl;
4267a55948dSShenghui Wang 	struct cache *ca;
427cafe5635SKent Overstreet 
4281fae7cf0SColy Li 	closure_init_stack(&cl);
429cafe5635SKent Overstreet 	lockdep_assert_held(&bch_register_lock);
430cafe5635SKent Overstreet 
43178365411SKent Overstreet 	if (bch_bucket_alloc_set(c, RESERVE_BTREE, &k.key, 1, true))
432cafe5635SKent Overstreet 		return 1;
433cafe5635SKent Overstreet 
434cafe5635SKent Overstreet 	SET_KEY_SIZE(&k.key, c->sb.bucket_size);
435ad0d9e76SMike Christie 	uuid_io(c, REQ_OP_WRITE, 0, &k.key, &cl);
436cafe5635SKent Overstreet 	closure_sync(&cl);
437cafe5635SKent Overstreet 
4387a55948dSShenghui Wang 	/* Only one bucket used for uuid write */
4397a55948dSShenghui Wang 	ca = PTR_CACHE(c, &k.key, 0);
4407a55948dSShenghui Wang 	atomic_long_add(ca->sb.bucket_size, &ca->meta_sectors_written);
4417a55948dSShenghui Wang 
442cafe5635SKent Overstreet 	bkey_copy(&c->uuid_bucket, &k.key);
4433a3b6a4eSKent Overstreet 	bkey_put(c, &k.key);
444cafe5635SKent Overstreet 	return 0;
445cafe5635SKent Overstreet }
446cafe5635SKent Overstreet 
447cafe5635SKent Overstreet int bch_uuid_write(struct cache_set *c)
448cafe5635SKent Overstreet {
449cafe5635SKent Overstreet 	int ret = __uuid_write(c);
450cafe5635SKent Overstreet 
451cafe5635SKent Overstreet 	if (!ret)
452cafe5635SKent Overstreet 		bch_journal_meta(c, NULL);
453cafe5635SKent Overstreet 
454cafe5635SKent Overstreet 	return ret;
455cafe5635SKent Overstreet }
456cafe5635SKent Overstreet 
457cafe5635SKent Overstreet static struct uuid_entry *uuid_find(struct cache_set *c, const char *uuid)
458cafe5635SKent Overstreet {
459cafe5635SKent Overstreet 	struct uuid_entry *u;
460cafe5635SKent Overstreet 
461cafe5635SKent Overstreet 	for (u = c->uuids;
462cafe5635SKent Overstreet 	     u < c->uuids + c->nr_uuids; u++)
463cafe5635SKent Overstreet 		if (!memcmp(u->uuid, uuid, 16))
464cafe5635SKent Overstreet 			return u;
465cafe5635SKent Overstreet 
466cafe5635SKent Overstreet 	return NULL;
467cafe5635SKent Overstreet }
468cafe5635SKent Overstreet 
469cafe5635SKent Overstreet static struct uuid_entry *uuid_find_empty(struct cache_set *c)
470cafe5635SKent Overstreet {
471cafe5635SKent Overstreet 	static const char zero_uuid[16] = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
4721fae7cf0SColy Li 
473cafe5635SKent Overstreet 	return uuid_find(c, zero_uuid);
474cafe5635SKent Overstreet }
475cafe5635SKent Overstreet 
476cafe5635SKent Overstreet /*
477cafe5635SKent Overstreet  * Bucket priorities/gens:
478cafe5635SKent Overstreet  *
479cafe5635SKent Overstreet  * For each bucket, we store on disk its
480cafe5635SKent Overstreet  *   8 bit gen
481cafe5635SKent Overstreet  *  16 bit priority
482cafe5635SKent Overstreet  *
483cafe5635SKent Overstreet  * See alloc.c for an explanation of the gen. The priority is used to implement
484cafe5635SKent Overstreet  * lru (and in the future other) cache replacement policies; for most purposes
485cafe5635SKent Overstreet  * it's just an opaque integer.
486cafe5635SKent Overstreet  *
487cafe5635SKent Overstreet  * The gens and the priorities don't have a whole lot to do with each other, and
488cafe5635SKent Overstreet  * it's actually the gens that must be written out at specific times - it's no
489cafe5635SKent Overstreet  * big deal if the priorities don't get written, if we lose them we just reuse
490cafe5635SKent Overstreet  * buckets in suboptimal order.
491cafe5635SKent Overstreet  *
492cafe5635SKent Overstreet  * On disk they're stored in a packed array, and in as many buckets are required
493cafe5635SKent Overstreet  * to fit them all. The buckets we use to store them form a list; the journal
494cafe5635SKent Overstreet  * header points to the first bucket, the first bucket points to the second
495cafe5635SKent Overstreet  * bucket, et cetera.
496cafe5635SKent Overstreet  *
497cafe5635SKent Overstreet  * This code is used by the allocation code; periodically (whenever it runs out
498cafe5635SKent Overstreet  * of buckets to allocate from) the allocation code will invalidate some
499cafe5635SKent Overstreet  * buckets, but it can't use those buckets until their new gens are safely on
500cafe5635SKent Overstreet  * disk.
501cafe5635SKent Overstreet  */
502cafe5635SKent Overstreet 
5034246a0b6SChristoph Hellwig static void prio_endio(struct bio *bio)
504cafe5635SKent Overstreet {
505cafe5635SKent Overstreet 	struct cache *ca = bio->bi_private;
506cafe5635SKent Overstreet 
5074e4cbee9SChristoph Hellwig 	cache_set_err_on(bio->bi_status, ca->set, "accessing priorities");
508cafe5635SKent Overstreet 	bch_bbio_free(bio, ca->set);
509cafe5635SKent Overstreet 	closure_put(&ca->prio);
510cafe5635SKent Overstreet }
511cafe5635SKent Overstreet 
512ad0d9e76SMike Christie static void prio_io(struct cache *ca, uint64_t bucket, int op,
513ad0d9e76SMike Christie 		    unsigned long op_flags)
514cafe5635SKent Overstreet {
515cafe5635SKent Overstreet 	struct closure *cl = &ca->prio;
516cafe5635SKent Overstreet 	struct bio *bio = bch_bbio_alloc(ca->set);
517cafe5635SKent Overstreet 
518cafe5635SKent Overstreet 	closure_init_stack(cl);
519cafe5635SKent Overstreet 
5204f024f37SKent Overstreet 	bio->bi_iter.bi_sector	= bucket * ca->sb.bucket_size;
52174d46992SChristoph Hellwig 	bio_set_dev(bio, ca->bdev);
5224f024f37SKent Overstreet 	bio->bi_iter.bi_size	= bucket_bytes(ca);
523cafe5635SKent Overstreet 
524cafe5635SKent Overstreet 	bio->bi_end_io	= prio_endio;
525cafe5635SKent Overstreet 	bio->bi_private = ca;
526ad0d9e76SMike Christie 	bio_set_op_attrs(bio, op, REQ_SYNC|REQ_META|op_flags);
527169ef1cfSKent Overstreet 	bch_bio_map(bio, ca->disk_buckets);
528cafe5635SKent Overstreet 
529771f393eSColy Li 	closure_bio_submit(ca->set, bio, &ca->prio);
530cafe5635SKent Overstreet 	closure_sync(cl);
531cafe5635SKent Overstreet }
532cafe5635SKent Overstreet 
53384c529aeSAndrea Righi int bch_prio_write(struct cache *ca, bool wait)
534cafe5635SKent Overstreet {
535cafe5635SKent Overstreet 	int i;
536cafe5635SKent Overstreet 	struct bucket *b;
537cafe5635SKent Overstreet 	struct closure cl;
538cafe5635SKent Overstreet 
53984c529aeSAndrea Righi 	pr_debug("free_prio=%zu, free_none=%zu, free_inc=%zu",
54084c529aeSAndrea Righi 		 fifo_used(&ca->free[RESERVE_PRIO]),
54184c529aeSAndrea Righi 		 fifo_used(&ca->free[RESERVE_NONE]),
54284c529aeSAndrea Righi 		 fifo_used(&ca->free_inc));
54384c529aeSAndrea Righi 
54484c529aeSAndrea Righi 	/*
54584c529aeSAndrea Righi 	 * Pre-check if there are enough free buckets. In the non-blocking
54684c529aeSAndrea Righi 	 * scenario it's better to fail early rather than starting to allocate
54784c529aeSAndrea Righi 	 * buckets and do a cleanup later in case of failure.
54884c529aeSAndrea Righi 	 */
54984c529aeSAndrea Righi 	if (!wait) {
55084c529aeSAndrea Righi 		size_t avail = fifo_used(&ca->free[RESERVE_PRIO]) +
55184c529aeSAndrea Righi 			       fifo_used(&ca->free[RESERVE_NONE]);
55284c529aeSAndrea Righi 		if (prio_buckets(ca) > avail)
55384c529aeSAndrea Righi 			return -ENOMEM;
55484c529aeSAndrea Righi 	}
55584c529aeSAndrea Righi 
556cafe5635SKent Overstreet 	closure_init_stack(&cl);
557cafe5635SKent Overstreet 
558cafe5635SKent Overstreet 	lockdep_assert_held(&ca->set->bucket_lock);
559cafe5635SKent Overstreet 
560cafe5635SKent Overstreet 	ca->disk_buckets->seq++;
561cafe5635SKent Overstreet 
562cafe5635SKent Overstreet 	atomic_long_add(ca->sb.bucket_size * prio_buckets(ca),
563cafe5635SKent Overstreet 			&ca->meta_sectors_written);
564cafe5635SKent Overstreet 
565cafe5635SKent Overstreet 	for (i = prio_buckets(ca) - 1; i >= 0; --i) {
566cafe5635SKent Overstreet 		long bucket;
567cafe5635SKent Overstreet 		struct prio_set *p = ca->disk_buckets;
568b1a67b0fSKent Overstreet 		struct bucket_disk *d = p->data;
569b1a67b0fSKent Overstreet 		struct bucket_disk *end = d + prios_per_bucket(ca);
570cafe5635SKent Overstreet 
571cafe5635SKent Overstreet 		for (b = ca->buckets + i * prios_per_bucket(ca);
572cafe5635SKent Overstreet 		     b < ca->buckets + ca->sb.nbuckets && d < end;
573cafe5635SKent Overstreet 		     b++, d++) {
574cafe5635SKent Overstreet 			d->prio = cpu_to_le16(b->prio);
575cafe5635SKent Overstreet 			d->gen = b->gen;
576cafe5635SKent Overstreet 		}
577cafe5635SKent Overstreet 
578cafe5635SKent Overstreet 		p->next_bucket	= ca->prio_buckets[i + 1];
57981ab4190SKent Overstreet 		p->magic	= pset_magic(&ca->sb);
580169ef1cfSKent Overstreet 		p->csum		= bch_crc64(&p->magic, bucket_bytes(ca) - 8);
581cafe5635SKent Overstreet 
58284c529aeSAndrea Righi 		bucket = bch_bucket_alloc(ca, RESERVE_PRIO, wait);
583cafe5635SKent Overstreet 		BUG_ON(bucket == -1);
584cafe5635SKent Overstreet 
585cafe5635SKent Overstreet 		mutex_unlock(&ca->set->bucket_lock);
586ad0d9e76SMike Christie 		prio_io(ca, bucket, REQ_OP_WRITE, 0);
587cafe5635SKent Overstreet 		mutex_lock(&ca->set->bucket_lock);
588cafe5635SKent Overstreet 
589cafe5635SKent Overstreet 		ca->prio_buckets[i] = bucket;
590cafe5635SKent Overstreet 		atomic_dec_bug(&ca->buckets[bucket].pin);
591cafe5635SKent Overstreet 	}
592cafe5635SKent Overstreet 
593cafe5635SKent Overstreet 	mutex_unlock(&ca->set->bucket_lock);
594cafe5635SKent Overstreet 
595cafe5635SKent Overstreet 	bch_journal_meta(ca->set, &cl);
596cafe5635SKent Overstreet 	closure_sync(&cl);
597cafe5635SKent Overstreet 
598cafe5635SKent Overstreet 	mutex_lock(&ca->set->bucket_lock);
599cafe5635SKent Overstreet 
600cafe5635SKent Overstreet 	/*
601cafe5635SKent Overstreet 	 * Don't want the old priorities to get garbage collected until after we
602cafe5635SKent Overstreet 	 * finish writing the new ones, and they're journalled
603cafe5635SKent Overstreet 	 */
6042531d9eeSKent Overstreet 	for (i = 0; i < prio_buckets(ca); i++) {
6052531d9eeSKent Overstreet 		if (ca->prio_last_buckets[i])
6062531d9eeSKent Overstreet 			__bch_bucket_free(ca,
6072531d9eeSKent Overstreet 				&ca->buckets[ca->prio_last_buckets[i]]);
6082531d9eeSKent Overstreet 
609cafe5635SKent Overstreet 		ca->prio_last_buckets[i] = ca->prio_buckets[i];
610cafe5635SKent Overstreet 	}
61184c529aeSAndrea Righi 	return 0;
6122531d9eeSKent Overstreet }
613cafe5635SKent Overstreet 
614cafe5635SKent Overstreet static void prio_read(struct cache *ca, uint64_t bucket)
615cafe5635SKent Overstreet {
616cafe5635SKent Overstreet 	struct prio_set *p = ca->disk_buckets;
617cafe5635SKent Overstreet 	struct bucket_disk *d = p->data + prios_per_bucket(ca), *end = d;
618cafe5635SKent Overstreet 	struct bucket *b;
6196f10f7d1SColy Li 	unsigned int bucket_nr = 0;
620cafe5635SKent Overstreet 
621cafe5635SKent Overstreet 	for (b = ca->buckets;
622cafe5635SKent Overstreet 	     b < ca->buckets + ca->sb.nbuckets;
623cafe5635SKent Overstreet 	     b++, d++) {
624cafe5635SKent Overstreet 		if (d == end) {
625cafe5635SKent Overstreet 			ca->prio_buckets[bucket_nr] = bucket;
626cafe5635SKent Overstreet 			ca->prio_last_buckets[bucket_nr] = bucket;
627cafe5635SKent Overstreet 			bucket_nr++;
628cafe5635SKent Overstreet 
62970fd7614SChristoph Hellwig 			prio_io(ca, bucket, REQ_OP_READ, 0);
630cafe5635SKent Overstreet 
631b0d30981SColy Li 			if (p->csum !=
632b0d30981SColy Li 			    bch_crc64(&p->magic, bucket_bytes(ca) - 8))
633cafe5635SKent Overstreet 				pr_warn("bad csum reading priorities");
634cafe5635SKent Overstreet 
63581ab4190SKent Overstreet 			if (p->magic != pset_magic(&ca->sb))
636cafe5635SKent Overstreet 				pr_warn("bad magic reading priorities");
637cafe5635SKent Overstreet 
638cafe5635SKent Overstreet 			bucket = p->next_bucket;
639cafe5635SKent Overstreet 			d = p->data;
640cafe5635SKent Overstreet 		}
641cafe5635SKent Overstreet 
642cafe5635SKent Overstreet 		b->prio = le16_to_cpu(d->prio);
6433a2fd9d5SKent Overstreet 		b->gen = b->last_gc = d->gen;
644cafe5635SKent Overstreet 	}
645cafe5635SKent Overstreet }
646cafe5635SKent Overstreet 
647cafe5635SKent Overstreet /* Bcache device */
648cafe5635SKent Overstreet 
649cafe5635SKent Overstreet static int open_dev(struct block_device *b, fmode_t mode)
650cafe5635SKent Overstreet {
651cafe5635SKent Overstreet 	struct bcache_device *d = b->bd_disk->private_data;
6521fae7cf0SColy Li 
653c4d951ddSKent Overstreet 	if (test_bit(BCACHE_DEV_CLOSING, &d->flags))
654cafe5635SKent Overstreet 		return -ENXIO;
655cafe5635SKent Overstreet 
656cafe5635SKent Overstreet 	closure_get(&d->cl);
657cafe5635SKent Overstreet 	return 0;
658cafe5635SKent Overstreet }
659cafe5635SKent Overstreet 
660867e1162SEmil Goode static void release_dev(struct gendisk *b, fmode_t mode)
661cafe5635SKent Overstreet {
662cafe5635SKent Overstreet 	struct bcache_device *d = b->private_data;
6631fae7cf0SColy Li 
664cafe5635SKent Overstreet 	closure_put(&d->cl);
665cafe5635SKent Overstreet }
666cafe5635SKent Overstreet 
667cafe5635SKent Overstreet static int ioctl_dev(struct block_device *b, fmode_t mode,
668cafe5635SKent Overstreet 		     unsigned int cmd, unsigned long arg)
669cafe5635SKent Overstreet {
670cafe5635SKent Overstreet 	struct bcache_device *d = b->bd_disk->private_data;
6710f0709e6SColy Li 
672cafe5635SKent Overstreet 	return d->ioctl(d, mode, cmd, arg);
673cafe5635SKent Overstreet }
674cafe5635SKent Overstreet 
675cafe5635SKent Overstreet static const struct block_device_operations bcache_ops = {
676cafe5635SKent Overstreet 	.open		= open_dev,
677cafe5635SKent Overstreet 	.release	= release_dev,
678cafe5635SKent Overstreet 	.ioctl		= ioctl_dev,
679cafe5635SKent Overstreet 	.owner		= THIS_MODULE,
680cafe5635SKent Overstreet };
681cafe5635SKent Overstreet 
682cafe5635SKent Overstreet void bcache_device_stop(struct bcache_device *d)
683cafe5635SKent Overstreet {
684c4d951ddSKent Overstreet 	if (!test_and_set_bit(BCACHE_DEV_CLOSING, &d->flags))
68563d63b51SColy Li 		/*
68663d63b51SColy Li 		 * closure_fn set to
68763d63b51SColy Li 		 * - cached device: cached_dev_flush()
68863d63b51SColy Li 		 * - flash dev: flash_dev_flush()
68963d63b51SColy Li 		 */
690cafe5635SKent Overstreet 		closure_queue(&d->cl);
691cafe5635SKent Overstreet }
692cafe5635SKent Overstreet 
693ee668506SKent Overstreet static void bcache_device_unlink(struct bcache_device *d)
694ee668506SKent Overstreet {
695c4d951ddSKent Overstreet 	lockdep_assert_held(&bch_register_lock);
696c4d951ddSKent Overstreet 
697c4d951ddSKent Overstreet 	if (d->c && !test_and_set_bit(BCACHE_DEV_UNLINK_DONE, &d->flags)) {
6986f10f7d1SColy Li 		unsigned int i;
699ee668506SKent Overstreet 		struct cache *ca;
700ee668506SKent Overstreet 
701ee668506SKent Overstreet 		sysfs_remove_link(&d->c->kobj, d->name);
702ee668506SKent Overstreet 		sysfs_remove_link(&d->kobj, "cache");
703ee668506SKent Overstreet 
704ee668506SKent Overstreet 		for_each_cache(ca, d->c, i)
705ee668506SKent Overstreet 			bd_unlink_disk_holder(ca->bdev, d->disk);
706ee668506SKent Overstreet 	}
707c4d951ddSKent Overstreet }
708ee668506SKent Overstreet 
709ee668506SKent Overstreet static void bcache_device_link(struct bcache_device *d, struct cache_set *c,
710ee668506SKent Overstreet 			       const char *name)
711ee668506SKent Overstreet {
7126f10f7d1SColy Li 	unsigned int i;
713ee668506SKent Overstreet 	struct cache *ca;
7144b6efb4bSColy Li 	int ret;
715ee668506SKent Overstreet 
716ee668506SKent Overstreet 	for_each_cache(ca, d->c, i)
717ee668506SKent Overstreet 		bd_link_disk_holder(ca->bdev, d->disk);
718ee668506SKent Overstreet 
719ee668506SKent Overstreet 	snprintf(d->name, BCACHEDEVNAME_SIZE,
720ee668506SKent Overstreet 		 "%s%u", name, d->id);
721ee668506SKent Overstreet 
7224b6efb4bSColy Li 	ret = sysfs_create_link(&d->kobj, &c->kobj, "cache");
7234b6efb4bSColy Li 	if (ret < 0)
7244b6efb4bSColy Li 		pr_err("Couldn't create device -> cache set symlink");
7254b6efb4bSColy Li 
7264b6efb4bSColy Li 	ret = sysfs_create_link(&c->kobj, &d->kobj, d->name);
7274b6efb4bSColy Li 	if (ret < 0)
7284b6efb4bSColy Li 		pr_err("Couldn't create cache set -> device symlink");
729fecaee6fSZheng Liu 
730fecaee6fSZheng Liu 	clear_bit(BCACHE_DEV_UNLINK_DONE, &d->flags);
731ee668506SKent Overstreet }
732ee668506SKent Overstreet 
733cafe5635SKent Overstreet static void bcache_device_detach(struct bcache_device *d)
734cafe5635SKent Overstreet {
735cafe5635SKent Overstreet 	lockdep_assert_held(&bch_register_lock);
736cafe5635SKent Overstreet 
737ea8c5356SColy Li 	atomic_dec(&d->c->attached_dev_nr);
738ea8c5356SColy Li 
739c4d951ddSKent Overstreet 	if (test_bit(BCACHE_DEV_DETACHING, &d->flags)) {
740cafe5635SKent Overstreet 		struct uuid_entry *u = d->c->uuids + d->id;
741cafe5635SKent Overstreet 
742cafe5635SKent Overstreet 		SET_UUID_FLASH_ONLY(u, 0);
743cafe5635SKent Overstreet 		memcpy(u->uuid, invalid_uuid, 16);
74475cbb3f1SArnd Bergmann 		u->invalidated = cpu_to_le32((u32)ktime_get_real_seconds());
745cafe5635SKent Overstreet 		bch_uuid_write(d->c);
746cafe5635SKent Overstreet 	}
747cafe5635SKent Overstreet 
748ee668506SKent Overstreet 	bcache_device_unlink(d);
749ee668506SKent Overstreet 
750cafe5635SKent Overstreet 	d->c->devices[d->id] = NULL;
751cafe5635SKent Overstreet 	closure_put(&d->c->caching);
752cafe5635SKent Overstreet 	d->c = NULL;
753cafe5635SKent Overstreet }
754cafe5635SKent Overstreet 
755cafe5635SKent Overstreet static void bcache_device_attach(struct bcache_device *d, struct cache_set *c,
7566f10f7d1SColy Li 				 unsigned int id)
757cafe5635SKent Overstreet {
758cafe5635SKent Overstreet 	d->id = id;
759cafe5635SKent Overstreet 	d->c = c;
760cafe5635SKent Overstreet 	c->devices[id] = d;
761cafe5635SKent Overstreet 
7622831231dSColy Li 	if (id >= c->devices_max_used)
7632831231dSColy Li 		c->devices_max_used = id + 1;
7642831231dSColy Li 
765cafe5635SKent Overstreet 	closure_get(&c->caching);
766cafe5635SKent Overstreet }
767cafe5635SKent Overstreet 
7681dbe32adSColy Li static inline int first_minor_to_idx(int first_minor)
7691dbe32adSColy Li {
7701dbe32adSColy Li 	return (first_minor/BCACHE_MINORS);
7711dbe32adSColy Li }
7721dbe32adSColy Li 
7731dbe32adSColy Li static inline int idx_to_first_minor(int idx)
7741dbe32adSColy Li {
7751dbe32adSColy Li 	return (idx * BCACHE_MINORS);
7761dbe32adSColy Li }
7771dbe32adSColy Li 
778cafe5635SKent Overstreet static void bcache_device_free(struct bcache_device *d)
779cafe5635SKent Overstreet {
7802d886951SColy Li 	struct gendisk *disk = d->disk;
7812d886951SColy Li 
782cafe5635SKent Overstreet 	lockdep_assert_held(&bch_register_lock);
783cafe5635SKent Overstreet 
7842d886951SColy Li 	if (disk)
7852d886951SColy Li 		pr_info("%s stopped", disk->disk_name);
7862d886951SColy Li 	else
7872d886951SColy Li 		pr_err("bcache device (NULL gendisk) stopped");
788cafe5635SKent Overstreet 
789cafe5635SKent Overstreet 	if (d->c)
790cafe5635SKent Overstreet 		bcache_device_detach(d);
7912d886951SColy Li 
7922d886951SColy Li 	if (disk) {
7932d886951SColy Li 		if (disk->flags & GENHD_FL_UP)
7942d886951SColy Li 			del_gendisk(disk);
7952d886951SColy Li 
7962d886951SColy Li 		if (disk->queue)
7972d886951SColy Li 			blk_cleanup_queue(disk->queue);
7982d886951SColy Li 
7991dbe32adSColy Li 		ida_simple_remove(&bcache_device_idx,
8002d886951SColy Li 				  first_minor_to_idx(disk->first_minor));
8012d886951SColy Li 		put_disk(disk);
80228935ab5SKent Overstreet 	}
803cafe5635SKent Overstreet 
804d19936a2SKent Overstreet 	bioset_exit(&d->bio_split);
805958b4338SPekka Enberg 	kvfree(d->full_dirty_stripes);
806958b4338SPekka Enberg 	kvfree(d->stripe_sectors_dirty);
807cafe5635SKent Overstreet 
808cafe5635SKent Overstreet 	closure_debug_destroy(&d->cl);
809cafe5635SKent Overstreet }
810cafe5635SKent Overstreet 
8116f10f7d1SColy Li static int bcache_device_init(struct bcache_device *d, unsigned int block_size,
812279afbadSKent Overstreet 			      sector_t sectors)
813cafe5635SKent Overstreet {
814cafe5635SKent Overstreet 	struct request_queue *q;
8155f2b18ecSBart Van Assche 	const size_t max_stripes = min_t(size_t, INT_MAX,
8165f2b18ecSBart Van Assche 					 SIZE_MAX / sizeof(atomic_t));
817279afbadSKent Overstreet 	size_t n;
8181dbe32adSColy Li 	int idx;
819279afbadSKent Overstreet 
8202d679fc7SKent Overstreet 	if (!d->stripe_size)
8212d679fc7SKent Overstreet 		d->stripe_size = 1 << 31;
822279afbadSKent Overstreet 
8232d679fc7SKent Overstreet 	d->nr_stripes = DIV_ROUND_UP_ULL(sectors, d->stripe_size);
824279afbadSKent Overstreet 
8255f2b18ecSBart Van Assche 	if (!d->nr_stripes || d->nr_stripes > max_stripes) {
82690706094SEric Wheeler 		pr_err("nr_stripes too large or invalid: %u (start sector beyond end of disk?)",
8276f10f7d1SColy Li 			(unsigned int)d->nr_stripes);
828279afbadSKent Overstreet 		return -ENOMEM;
82948a915a8SKent Overstreet 	}
830279afbadSKent Overstreet 
831279afbadSKent Overstreet 	n = d->nr_stripes * sizeof(atomic_t);
832bc4e54f6SMichal Hocko 	d->stripe_sectors_dirty = kvzalloc(n, GFP_KERNEL);
833279afbadSKent Overstreet 	if (!d->stripe_sectors_dirty)
834279afbadSKent Overstreet 		return -ENOMEM;
835cafe5635SKent Overstreet 
83648a915a8SKent Overstreet 	n = BITS_TO_LONGS(d->nr_stripes) * sizeof(unsigned long);
837bc4e54f6SMichal Hocko 	d->full_dirty_stripes = kvzalloc(n, GFP_KERNEL);
83848a915a8SKent Overstreet 	if (!d->full_dirty_stripes)
83948a915a8SKent Overstreet 		return -ENOMEM;
84048a915a8SKent Overstreet 
8411dbe32adSColy Li 	idx = ida_simple_get(&bcache_device_idx, 0,
8421dbe32adSColy Li 				BCACHE_DEVICE_IDX_MAX, GFP_KERNEL);
8431dbe32adSColy Li 	if (idx < 0)
8441dbe32adSColy Li 		return idx;
845b8c0d911SEric Wheeler 
846d19936a2SKent Overstreet 	if (bioset_init(&d->bio_split, 4, offsetof(struct bbio, bio),
8479b4e9f5aSFlorian Schmaus 			BIOSET_NEED_BVECS|BIOSET_NEED_RESCUER))
8489b4e9f5aSFlorian Schmaus 		goto err;
8499b4e9f5aSFlorian Schmaus 
8509b4e9f5aSFlorian Schmaus 	d->disk = alloc_disk(BCACHE_MINORS);
8519b4e9f5aSFlorian Schmaus 	if (!d->disk)
8529b4e9f5aSFlorian Schmaus 		goto err;
853cafe5635SKent Overstreet 
854279afbadSKent Overstreet 	set_capacity(d->disk, sectors);
8551dbe32adSColy Li 	snprintf(d->disk->disk_name, DISK_NAME_LEN, "bcache%i", idx);
856cafe5635SKent Overstreet 
857cafe5635SKent Overstreet 	d->disk->major		= bcache_major;
8581dbe32adSColy Li 	d->disk->first_minor	= idx_to_first_minor(idx);
859cafe5635SKent Overstreet 	d->disk->fops		= &bcache_ops;
860cafe5635SKent Overstreet 	d->disk->private_data	= d;
861cafe5635SKent Overstreet 
86228935ab5SKent Overstreet 	q = blk_alloc_queue(GFP_KERNEL);
86328935ab5SKent Overstreet 	if (!q)
86428935ab5SKent Overstreet 		return -ENOMEM;
86528935ab5SKent Overstreet 
866cafe5635SKent Overstreet 	blk_queue_make_request(q, NULL);
867cafe5635SKent Overstreet 	d->disk->queue			= q;
868cafe5635SKent Overstreet 	q->queuedata			= d;
869dc3b17ccSJan Kara 	q->backing_dev_info->congested_data = d;
870cafe5635SKent Overstreet 	q->limits.max_hw_sectors	= UINT_MAX;
871cafe5635SKent Overstreet 	q->limits.max_sectors		= UINT_MAX;
872cafe5635SKent Overstreet 	q->limits.max_segment_size	= UINT_MAX;
873cafe5635SKent Overstreet 	q->limits.max_segments		= BIO_MAX_PAGES;
8742bb4cd5cSJens Axboe 	blk_queue_max_discard_sectors(q, UINT_MAX);
87590db6919SKent Overstreet 	q->limits.discard_granularity	= 512;
876cafe5635SKent Overstreet 	q->limits.io_min		= block_size;
877cafe5635SKent Overstreet 	q->limits.logical_block_size	= block_size;
878cafe5635SKent Overstreet 	q->limits.physical_block_size	= block_size;
87944e1ebe2SBart Van Assche 	blk_queue_flag_set(QUEUE_FLAG_NONROT, d->disk->queue);
88044e1ebe2SBart Van Assche 	blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, d->disk->queue);
88144e1ebe2SBart Van Assche 	blk_queue_flag_set(QUEUE_FLAG_DISCARD, d->disk->queue);
882cafe5635SKent Overstreet 
88384b4ff9eSJens Axboe 	blk_queue_write_cache(q, true, true);
88454d12f2bSKent Overstreet 
885cafe5635SKent Overstreet 	return 0;
8869b4e9f5aSFlorian Schmaus 
8879b4e9f5aSFlorian Schmaus err:
8889b4e9f5aSFlorian Schmaus 	ida_simple_remove(&bcache_device_idx, idx);
8899b4e9f5aSFlorian Schmaus 	return -ENOMEM;
8909b4e9f5aSFlorian Schmaus 
891cafe5635SKent Overstreet }
892cafe5635SKent Overstreet 
893cafe5635SKent Overstreet /* Cached device */
894cafe5635SKent Overstreet 
895cafe5635SKent Overstreet static void calc_cached_dev_sectors(struct cache_set *c)
896cafe5635SKent Overstreet {
897cafe5635SKent Overstreet 	uint64_t sectors = 0;
898cafe5635SKent Overstreet 	struct cached_dev *dc;
899cafe5635SKent Overstreet 
900cafe5635SKent Overstreet 	list_for_each_entry(dc, &c->cached_devs, list)
901cafe5635SKent Overstreet 		sectors += bdev_sectors(dc->bdev);
902cafe5635SKent Overstreet 
903cafe5635SKent Overstreet 	c->cached_dev_sectors = sectors;
904cafe5635SKent Overstreet }
905cafe5635SKent Overstreet 
9060f0709e6SColy Li #define BACKING_DEV_OFFLINE_TIMEOUT 5
9070f0709e6SColy Li static int cached_dev_status_update(void *arg)
9080f0709e6SColy Li {
9090f0709e6SColy Li 	struct cached_dev *dc = arg;
9100f0709e6SColy Li 	struct request_queue *q;
9110f0709e6SColy Li 
9120f0709e6SColy Li 	/*
9130f0709e6SColy Li 	 * If this delayed worker is stopping outside, directly quit here.
9140f0709e6SColy Li 	 * dc->io_disable might be set via sysfs interface, so check it
9150f0709e6SColy Li 	 * here too.
9160f0709e6SColy Li 	 */
9170f0709e6SColy Li 	while (!kthread_should_stop() && !dc->io_disable) {
9180f0709e6SColy Li 		q = bdev_get_queue(dc->bdev);
9190f0709e6SColy Li 		if (blk_queue_dying(q))
9200f0709e6SColy Li 			dc->offline_seconds++;
9210f0709e6SColy Li 		else
9220f0709e6SColy Li 			dc->offline_seconds = 0;
9230f0709e6SColy Li 
9240f0709e6SColy Li 		if (dc->offline_seconds >= BACKING_DEV_OFFLINE_TIMEOUT) {
9250f0709e6SColy Li 			pr_err("%s: device offline for %d seconds",
9260f0709e6SColy Li 			       dc->backing_dev_name,
9270f0709e6SColy Li 			       BACKING_DEV_OFFLINE_TIMEOUT);
9280f0709e6SColy Li 			pr_err("%s: disable I/O request due to backing "
9290f0709e6SColy Li 			       "device offline", dc->disk.name);
9300f0709e6SColy Li 			dc->io_disable = true;
9310f0709e6SColy Li 			/* let others know earlier that io_disable is true */
9320f0709e6SColy Li 			smp_mb();
9330f0709e6SColy Li 			bcache_device_stop(&dc->disk);
9340f0709e6SColy Li 			break;
9350f0709e6SColy Li 		}
9360f0709e6SColy Li 		schedule_timeout_interruptible(HZ);
9370f0709e6SColy Li 	}
9380f0709e6SColy Li 
9390f0709e6SColy Li 	wait_for_kthread_stop();
9400f0709e6SColy Li 	return 0;
9410f0709e6SColy Li }
9420f0709e6SColy Li 
9430f0709e6SColy Li 
9440b13efecSColy Li int bch_cached_dev_run(struct cached_dev *dc)
945cafe5635SKent Overstreet {
946cafe5635SKent Overstreet 	struct bcache_device *d = &dc->disk;
947792732d9SGeliang Tang 	char *buf = kmemdup_nul(dc->sb.label, SB_LABEL_SIZE, GFP_KERNEL);
948a25c32beSGabriel de Perthuis 	char *env[] = {
949a25c32beSGabriel de Perthuis 		"DRIVER=bcache",
950a25c32beSGabriel de Perthuis 		kasprintf(GFP_KERNEL, "CACHED_UUID=%pU", dc->sb.uuid),
951792732d9SGeliang Tang 		kasprintf(GFP_KERNEL, "CACHED_LABEL=%s", buf ? : ""),
952ab9e1400SGabriel de Perthuis 		NULL,
953a25c32beSGabriel de Perthuis 	};
954cafe5635SKent Overstreet 
955e0faa3d7SColy Li 	if (dc->io_disable) {
956e0faa3d7SColy Li 		pr_err("I/O disabled on cached dev %s",
957e0faa3d7SColy Li 		       dc->backing_dev_name);
9585d9e06d6SWei Yongjun 		kfree(env[1]);
9595d9e06d6SWei Yongjun 		kfree(env[2]);
9605d9e06d6SWei Yongjun 		kfree(buf);
9610b13efecSColy Li 		return -EIO;
962e0faa3d7SColy Li 	}
9630b13efecSColy Li 
9644d4d8573SAl Viro 	if (atomic_xchg(&dc->running, 1)) {
9654d4d8573SAl Viro 		kfree(env[1]);
9664d4d8573SAl Viro 		kfree(env[2]);
967792732d9SGeliang Tang 		kfree(buf);
968e0faa3d7SColy Li 		pr_info("cached dev %s is running already",
969e0faa3d7SColy Li 		       dc->backing_dev_name);
9700b13efecSColy Li 		return -EBUSY;
9714d4d8573SAl Viro 	}
972cafe5635SKent Overstreet 
973cafe5635SKent Overstreet 	if (!d->c &&
974cafe5635SKent Overstreet 	    BDEV_STATE(&dc->sb) != BDEV_STATE_NONE) {
975cafe5635SKent Overstreet 		struct closure cl;
9761fae7cf0SColy Li 
977cafe5635SKent Overstreet 		closure_init_stack(&cl);
978cafe5635SKent Overstreet 
979cafe5635SKent Overstreet 		SET_BDEV_STATE(&dc->sb, BDEV_STATE_STALE);
980cafe5635SKent Overstreet 		bch_write_bdev_super(dc, &cl);
981cafe5635SKent Overstreet 		closure_sync(&cl);
982cafe5635SKent Overstreet 	}
983cafe5635SKent Overstreet 
984cafe5635SKent Overstreet 	add_disk(d->disk);
985ee668506SKent Overstreet 	bd_link_disk_holder(dc->bdev, dc->disk.disk);
9863be11dbaSColy Li 	/*
9873be11dbaSColy Li 	 * won't show up in the uevent file, use udevadm monitor -e instead
9883be11dbaSColy Li 	 * only class / kset properties are persistent
9893be11dbaSColy Li 	 */
990cafe5635SKent Overstreet 	kobject_uevent_env(&disk_to_dev(d->disk)->kobj, KOBJ_CHANGE, env);
991a25c32beSGabriel de Perthuis 	kfree(env[1]);
992ab9e1400SGabriel de Perthuis 	kfree(env[2]);
993792732d9SGeliang Tang 	kfree(buf);
994a25c32beSGabriel de Perthuis 
995cafe5635SKent Overstreet 	if (sysfs_create_link(&d->kobj, &disk_to_dev(d->disk)->kobj, "dev") ||
9960b13efecSColy Li 	    sysfs_create_link(&disk_to_dev(d->disk)->kobj,
9970b13efecSColy Li 			      &d->kobj, "bcache")) {
998e0faa3d7SColy Li 		pr_err("Couldn't create bcache dev <-> disk sysfs symlinks");
9990b13efecSColy Li 		return -ENOMEM;
10000b13efecSColy Li 	}
10010f0709e6SColy Li 
10020f0709e6SColy Li 	dc->status_update_thread = kthread_run(cached_dev_status_update,
10030f0709e6SColy Li 					       dc, "bcache_status_update");
10040f0709e6SColy Li 	if (IS_ERR(dc->status_update_thread)) {
10050f0709e6SColy Li 		pr_warn("failed to create bcache_status_update kthread, "
10060f0709e6SColy Li 			"continue to run without monitoring backing "
10070f0709e6SColy Li 			"device status");
10080f0709e6SColy Li 	}
10090b13efecSColy Li 
10100b13efecSColy Li 	return 0;
1011cafe5635SKent Overstreet }
1012cafe5635SKent Overstreet 
10133fd47bfeSColy Li /*
10143fd47bfeSColy Li  * If BCACHE_DEV_RATE_DW_RUNNING is set, it means routine of the delayed
10153fd47bfeSColy Li  * work dc->writeback_rate_update is running. Wait until the routine
10163fd47bfeSColy Li  * quits (BCACHE_DEV_RATE_DW_RUNNING is clear), then continue to
10173fd47bfeSColy Li  * cancel it. If BCACHE_DEV_RATE_DW_RUNNING is not clear after time_out
10183fd47bfeSColy Li  * seconds, give up waiting here and continue to cancel it too.
10193fd47bfeSColy Li  */
10203fd47bfeSColy Li static void cancel_writeback_rate_update_dwork(struct cached_dev *dc)
10213fd47bfeSColy Li {
10223fd47bfeSColy Li 	int time_out = WRITEBACK_RATE_UPDATE_SECS_MAX * HZ;
10233fd47bfeSColy Li 
10243fd47bfeSColy Li 	do {
10253fd47bfeSColy Li 		if (!test_bit(BCACHE_DEV_RATE_DW_RUNNING,
10263fd47bfeSColy Li 			      &dc->disk.flags))
10273fd47bfeSColy Li 			break;
10283fd47bfeSColy Li 		time_out--;
10293fd47bfeSColy Li 		schedule_timeout_interruptible(1);
10303fd47bfeSColy Li 	} while (time_out > 0);
10313fd47bfeSColy Li 
10323fd47bfeSColy Li 	if (time_out == 0)
10333fd47bfeSColy Li 		pr_warn("give up waiting for dc->writeback_write_update to quit");
10343fd47bfeSColy Li 
10353fd47bfeSColy Li 	cancel_delayed_work_sync(&dc->writeback_rate_update);
10363fd47bfeSColy Li }
10373fd47bfeSColy Li 
1038cafe5635SKent Overstreet static void cached_dev_detach_finish(struct work_struct *w)
1039cafe5635SKent Overstreet {
1040cafe5635SKent Overstreet 	struct cached_dev *dc = container_of(w, struct cached_dev, detach);
1041cafe5635SKent Overstreet 	struct closure cl;
10421fae7cf0SColy Li 
1043cafe5635SKent Overstreet 	closure_init_stack(&cl);
1044cafe5635SKent Overstreet 
1045c4d951ddSKent Overstreet 	BUG_ON(!test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags));
10463b304d24SElena Reshetova 	BUG_ON(refcount_read(&dc->count));
1047cafe5635SKent Overstreet 
1048cafe5635SKent Overstreet 
10493fd47bfeSColy Li 	if (test_and_clear_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags))
10503fd47bfeSColy Li 		cancel_writeback_rate_update_dwork(dc);
10513fd47bfeSColy Li 
10528d29c442STang Junhui 	if (!IS_ERR_OR_NULL(dc->writeback_thread)) {
10538d29c442STang Junhui 		kthread_stop(dc->writeback_thread);
10548d29c442STang Junhui 		dc->writeback_thread = NULL;
10558d29c442STang Junhui 	}
10568d29c442STang Junhui 
1057cafe5635SKent Overstreet 	memset(&dc->sb.set_uuid, 0, 16);
1058cafe5635SKent Overstreet 	SET_BDEV_STATE(&dc->sb, BDEV_STATE_NONE);
1059cafe5635SKent Overstreet 
1060cafe5635SKent Overstreet 	bch_write_bdev_super(dc, &cl);
1061cafe5635SKent Overstreet 	closure_sync(&cl);
1062cafe5635SKent Overstreet 
106397ba3b81SColy Li 	mutex_lock(&bch_register_lock);
106497ba3b81SColy Li 
106546010141SShenghui Wang 	calc_cached_dev_sectors(dc->disk.c);
1066cafe5635SKent Overstreet 	bcache_device_detach(&dc->disk);
1067cafe5635SKent Overstreet 	list_move(&dc->list, &uncached_devices);
1068cafe5635SKent Overstreet 
1069c4d951ddSKent Overstreet 	clear_bit(BCACHE_DEV_DETACHING, &dc->disk.flags);
10705b1016e6SKent Overstreet 	clear_bit(BCACHE_DEV_UNLINK_DONE, &dc->disk.flags);
1071c4d951ddSKent Overstreet 
1072cafe5635SKent Overstreet 	mutex_unlock(&bch_register_lock);
1073cafe5635SKent Overstreet 
10746e916a7eSColy Li 	pr_info("Caching disabled for %s", dc->backing_dev_name);
1075cafe5635SKent Overstreet 
1076cafe5635SKent Overstreet 	/* Drop ref we took in cached_dev_detach() */
1077cafe5635SKent Overstreet 	closure_put(&dc->disk.cl);
1078cafe5635SKent Overstreet }
1079cafe5635SKent Overstreet 
1080cafe5635SKent Overstreet void bch_cached_dev_detach(struct cached_dev *dc)
1081cafe5635SKent Overstreet {
1082cafe5635SKent Overstreet 	lockdep_assert_held(&bch_register_lock);
1083cafe5635SKent Overstreet 
1084c4d951ddSKent Overstreet 	if (test_bit(BCACHE_DEV_CLOSING, &dc->disk.flags))
1085cafe5635SKent Overstreet 		return;
1086cafe5635SKent Overstreet 
1087c4d951ddSKent Overstreet 	if (test_and_set_bit(BCACHE_DEV_DETACHING, &dc->disk.flags))
1088cafe5635SKent Overstreet 		return;
1089cafe5635SKent Overstreet 
1090cafe5635SKent Overstreet 	/*
1091cafe5635SKent Overstreet 	 * Block the device from being closed and freed until we're finished
1092cafe5635SKent Overstreet 	 * detaching
1093cafe5635SKent Overstreet 	 */
1094cafe5635SKent Overstreet 	closure_get(&dc->disk.cl);
1095cafe5635SKent Overstreet 
1096cafe5635SKent Overstreet 	bch_writeback_queue(dc);
10973fd47bfeSColy Li 
1098cafe5635SKent Overstreet 	cached_dev_put(dc);
1099cafe5635SKent Overstreet }
1100cafe5635SKent Overstreet 
110173ac105bSTang Junhui int bch_cached_dev_attach(struct cached_dev *dc, struct cache_set *c,
110273ac105bSTang Junhui 			  uint8_t *set_uuid)
1103cafe5635SKent Overstreet {
110475cbb3f1SArnd Bergmann 	uint32_t rtime = cpu_to_le32((u32)ktime_get_real_seconds());
1105cafe5635SKent Overstreet 	struct uuid_entry *u;
110686755b7aSMichael Lyle 	struct cached_dev *exist_dc, *t;
11070b13efecSColy Li 	int ret = 0;
1108cafe5635SKent Overstreet 
110973ac105bSTang Junhui 	if ((set_uuid && memcmp(set_uuid, c->sb.set_uuid, 16)) ||
111073ac105bSTang Junhui 	    (!set_uuid && memcmp(dc->sb.set_uuid, c->sb.set_uuid, 16)))
1111cafe5635SKent Overstreet 		return -ENOENT;
1112cafe5635SKent Overstreet 
1113cafe5635SKent Overstreet 	if (dc->disk.c) {
11146e916a7eSColy Li 		pr_err("Can't attach %s: already attached",
11156e916a7eSColy Li 		       dc->backing_dev_name);
1116cafe5635SKent Overstreet 		return -EINVAL;
1117cafe5635SKent Overstreet 	}
1118cafe5635SKent Overstreet 
1119cafe5635SKent Overstreet 	if (test_bit(CACHE_SET_STOPPING, &c->flags)) {
11206e916a7eSColy Li 		pr_err("Can't attach %s: shutting down",
11216e916a7eSColy Li 		       dc->backing_dev_name);
1122cafe5635SKent Overstreet 		return -EINVAL;
1123cafe5635SKent Overstreet 	}
1124cafe5635SKent Overstreet 
1125cafe5635SKent Overstreet 	if (dc->sb.block_size < c->sb.block_size) {
1126cafe5635SKent Overstreet 		/* Will die */
1127b1a67b0fSKent Overstreet 		pr_err("Couldn't attach %s: block size less than set's block size",
11286e916a7eSColy Li 		       dc->backing_dev_name);
1129cafe5635SKent Overstreet 		return -EINVAL;
1130cafe5635SKent Overstreet 	}
1131cafe5635SKent Overstreet 
113286755b7aSMichael Lyle 	/* Check whether already attached */
113386755b7aSMichael Lyle 	list_for_each_entry_safe(exist_dc, t, &c->cached_devs, list) {
113486755b7aSMichael Lyle 		if (!memcmp(dc->sb.uuid, exist_dc->sb.uuid, 16)) {
113586755b7aSMichael Lyle 			pr_err("Tried to attach %s but duplicate UUID already attached",
11366e916a7eSColy Li 				dc->backing_dev_name);
113786755b7aSMichael Lyle 
113886755b7aSMichael Lyle 			return -EINVAL;
113986755b7aSMichael Lyle 		}
114086755b7aSMichael Lyle 	}
114186755b7aSMichael Lyle 
1142cafe5635SKent Overstreet 	u = uuid_find(c, dc->sb.uuid);
1143cafe5635SKent Overstreet 
1144cafe5635SKent Overstreet 	if (u &&
1145cafe5635SKent Overstreet 	    (BDEV_STATE(&dc->sb) == BDEV_STATE_STALE ||
1146cafe5635SKent Overstreet 	     BDEV_STATE(&dc->sb) == BDEV_STATE_NONE)) {
1147cafe5635SKent Overstreet 		memcpy(u->uuid, invalid_uuid, 16);
114875cbb3f1SArnd Bergmann 		u->invalidated = cpu_to_le32((u32)ktime_get_real_seconds());
1149cafe5635SKent Overstreet 		u = NULL;
1150cafe5635SKent Overstreet 	}
1151cafe5635SKent Overstreet 
1152cafe5635SKent Overstreet 	if (!u) {
1153cafe5635SKent Overstreet 		if (BDEV_STATE(&dc->sb) == BDEV_STATE_DIRTY) {
11546e916a7eSColy Li 			pr_err("Couldn't find uuid for %s in set",
11556e916a7eSColy Li 			       dc->backing_dev_name);
1156cafe5635SKent Overstreet 			return -ENOENT;
1157cafe5635SKent Overstreet 		}
1158cafe5635SKent Overstreet 
1159cafe5635SKent Overstreet 		u = uuid_find_empty(c);
1160cafe5635SKent Overstreet 		if (!u) {
11616e916a7eSColy Li 			pr_err("Not caching %s, no room for UUID",
11626e916a7eSColy Li 			       dc->backing_dev_name);
1163cafe5635SKent Overstreet 			return -EINVAL;
1164cafe5635SKent Overstreet 		}
1165cafe5635SKent Overstreet 	}
1166cafe5635SKent Overstreet 
11673be11dbaSColy Li 	/*
11683be11dbaSColy Li 	 * Deadlocks since we're called via sysfs...
11693be11dbaSColy Li 	 * sysfs_remove_file(&dc->kobj, &sysfs_attach);
1170cafe5635SKent Overstreet 	 */
1171cafe5635SKent Overstreet 
1172169ef1cfSKent Overstreet 	if (bch_is_zero(u->uuid, 16)) {
1173cafe5635SKent Overstreet 		struct closure cl;
11741fae7cf0SColy Li 
1175cafe5635SKent Overstreet 		closure_init_stack(&cl);
1176cafe5635SKent Overstreet 
1177cafe5635SKent Overstreet 		memcpy(u->uuid, dc->sb.uuid, 16);
1178cafe5635SKent Overstreet 		memcpy(u->label, dc->sb.label, SB_LABEL_SIZE);
1179cafe5635SKent Overstreet 		u->first_reg = u->last_reg = rtime;
1180cafe5635SKent Overstreet 		bch_uuid_write(c);
1181cafe5635SKent Overstreet 
1182cafe5635SKent Overstreet 		memcpy(dc->sb.set_uuid, c->sb.set_uuid, 16);
1183cafe5635SKent Overstreet 		SET_BDEV_STATE(&dc->sb, BDEV_STATE_CLEAN);
1184cafe5635SKent Overstreet 
1185cafe5635SKent Overstreet 		bch_write_bdev_super(dc, &cl);
1186cafe5635SKent Overstreet 		closure_sync(&cl);
1187cafe5635SKent Overstreet 	} else {
1188cafe5635SKent Overstreet 		u->last_reg = rtime;
1189cafe5635SKent Overstreet 		bch_uuid_write(c);
1190cafe5635SKent Overstreet 	}
1191cafe5635SKent Overstreet 
1192cafe5635SKent Overstreet 	bcache_device_attach(&dc->disk, c, u - c->uuids);
1193cafe5635SKent Overstreet 	list_move(&dc->list, &c->cached_devs);
1194cafe5635SKent Overstreet 	calc_cached_dev_sectors(c);
1195cafe5635SKent Overstreet 
1196cafe5635SKent Overstreet 	/*
1197cafe5635SKent Overstreet 	 * dc->c must be set before dc->count != 0 - paired with the mb in
1198cafe5635SKent Overstreet 	 * cached_dev_get()
1199cafe5635SKent Overstreet 	 */
1200eb2b3d03SColy Li 	smp_wmb();
12013b304d24SElena Reshetova 	refcount_set(&dc->count, 1);
1202cafe5635SKent Overstreet 
120307cc6ef8SEric Wheeler 	/* Block writeback thread, but spawn it */
120407cc6ef8SEric Wheeler 	down_write(&dc->writeback_lock);
120507cc6ef8SEric Wheeler 	if (bch_cached_dev_writeback_start(dc)) {
120607cc6ef8SEric Wheeler 		up_write(&dc->writeback_lock);
1207633bb2ceSColy Li 		pr_err("Couldn't start writeback facilities for %s",
1208633bb2ceSColy Li 		       dc->disk.disk->disk_name);
12099e5c3535SSlava Pestov 		return -ENOMEM;
121007cc6ef8SEric Wheeler 	}
12119e5c3535SSlava Pestov 
1212cafe5635SKent Overstreet 	if (BDEV_STATE(&dc->sb) == BDEV_STATE_DIRTY) {
1213cafe5635SKent Overstreet 		atomic_set(&dc->has_dirty, 1);
1214cafe5635SKent Overstreet 		bch_writeback_queue(dc);
1215cafe5635SKent Overstreet 	}
1216cafe5635SKent Overstreet 
12172e17a262STang Junhui 	bch_sectors_dirty_init(&dc->disk);
12182e17a262STang Junhui 
12190b13efecSColy Li 	ret = bch_cached_dev_run(dc);
12200b13efecSColy Li 	if (ret && (ret != -EBUSY)) {
12210b13efecSColy Li 		up_write(&dc->writeback_lock);
12225c2a634cSColy Li 		/*
12235c2a634cSColy Li 		 * bch_register_lock is held, bcache_device_stop() is not
12245c2a634cSColy Li 		 * able to be directly called. The kthread and kworker
12255c2a634cSColy Li 		 * created previously in bch_cached_dev_writeback_start()
12265c2a634cSColy Li 		 * have to be stopped manually here.
12275c2a634cSColy Li 		 */
12285c2a634cSColy Li 		kthread_stop(dc->writeback_thread);
12295c2a634cSColy Li 		cancel_writeback_rate_update_dwork(dc);
1230633bb2ceSColy Li 		pr_err("Couldn't run cached device %s",
1231633bb2ceSColy Li 		       dc->backing_dev_name);
12320b13efecSColy Li 		return ret;
12330b13efecSColy Li 	}
12340b13efecSColy Li 
1235ee668506SKent Overstreet 	bcache_device_link(&dc->disk, c, "bdev");
1236ea8c5356SColy Li 	atomic_inc(&c->attached_dev_nr);
1237cafe5635SKent Overstreet 
123807cc6ef8SEric Wheeler 	/* Allow the writeback thread to proceed */
123907cc6ef8SEric Wheeler 	up_write(&dc->writeback_lock);
124007cc6ef8SEric Wheeler 
1241cafe5635SKent Overstreet 	pr_info("Caching %s as %s on set %pU",
12426e916a7eSColy Li 		dc->backing_dev_name,
12436e916a7eSColy Li 		dc->disk.disk->disk_name,
1244cafe5635SKent Overstreet 		dc->disk.c->sb.set_uuid);
1245cafe5635SKent Overstreet 	return 0;
1246cafe5635SKent Overstreet }
1247cafe5635SKent Overstreet 
12482d17456eSColy Li /* when dc->disk.kobj released */
1249cafe5635SKent Overstreet void bch_cached_dev_release(struct kobject *kobj)
1250cafe5635SKent Overstreet {
1251cafe5635SKent Overstreet 	struct cached_dev *dc = container_of(kobj, struct cached_dev,
1252cafe5635SKent Overstreet 					     disk.kobj);
1253cafe5635SKent Overstreet 	kfree(dc);
1254cafe5635SKent Overstreet 	module_put(THIS_MODULE);
1255cafe5635SKent Overstreet }
1256cafe5635SKent Overstreet 
1257cafe5635SKent Overstreet static void cached_dev_free(struct closure *cl)
1258cafe5635SKent Overstreet {
1259cafe5635SKent Overstreet 	struct cached_dev *dc = container_of(cl, struct cached_dev, disk.cl);
1260cafe5635SKent Overstreet 
12613fd47bfeSColy Li 	if (test_and_clear_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags))
12623fd47bfeSColy Li 		cancel_writeback_rate_update_dwork(dc);
12633fd47bfeSColy Li 
1264a664d0f0SSlava Pestov 	if (!IS_ERR_OR_NULL(dc->writeback_thread))
12655e6926daSKent Overstreet 		kthread_stop(dc->writeback_thread);
12660f0709e6SColy Li 	if (!IS_ERR_OR_NULL(dc->status_update_thread))
12670f0709e6SColy Li 		kthread_stop(dc->status_update_thread);
1268cafe5635SKent Overstreet 
126980265d8dSColy Li 	mutex_lock(&bch_register_lock);
127080265d8dSColy Li 
1271f59fce84SKent Overstreet 	if (atomic_read(&dc->running))
1272ee668506SKent Overstreet 		bd_unlink_disk_holder(dc->bdev, dc->disk.disk);
1273cafe5635SKent Overstreet 	bcache_device_free(&dc->disk);
1274cafe5635SKent Overstreet 	list_del(&dc->list);
1275cafe5635SKent Overstreet 
1276cafe5635SKent Overstreet 	mutex_unlock(&bch_register_lock);
1277cafe5635SKent Overstreet 
1278e8547d42SLiang Chen 	if (dc->sb_bio.bi_inline_vecs[0].bv_page)
1279e8547d42SLiang Chen 		put_page(bio_first_page_all(&dc->sb_bio));
1280e8547d42SLiang Chen 
12810781c874SKent Overstreet 	if (!IS_ERR_OR_NULL(dc->bdev))
1282cafe5635SKent Overstreet 		blkdev_put(dc->bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
1283cafe5635SKent Overstreet 
1284cafe5635SKent Overstreet 	wake_up(&unregister_wait);
1285cafe5635SKent Overstreet 
1286cafe5635SKent Overstreet 	kobject_put(&dc->disk.kobj);
1287cafe5635SKent Overstreet }
1288cafe5635SKent Overstreet 
1289cafe5635SKent Overstreet static void cached_dev_flush(struct closure *cl)
1290cafe5635SKent Overstreet {
1291cafe5635SKent Overstreet 	struct cached_dev *dc = container_of(cl, struct cached_dev, disk.cl);
1292cafe5635SKent Overstreet 	struct bcache_device *d = &dc->disk;
1293cafe5635SKent Overstreet 
1294c9502ea4SKent Overstreet 	mutex_lock(&bch_register_lock);
1295c9502ea4SKent Overstreet 	bcache_device_unlink(d);
1296c9502ea4SKent Overstreet 	mutex_unlock(&bch_register_lock);
1297c9502ea4SKent Overstreet 
1298cafe5635SKent Overstreet 	bch_cache_accounting_destroy(&dc->accounting);
1299cafe5635SKent Overstreet 	kobject_del(&d->kobj);
1300cafe5635SKent Overstreet 
1301cafe5635SKent Overstreet 	continue_at(cl, cached_dev_free, system_wq);
1302cafe5635SKent Overstreet }
1303cafe5635SKent Overstreet 
13046f10f7d1SColy Li static int cached_dev_init(struct cached_dev *dc, unsigned int block_size)
1305cafe5635SKent Overstreet {
1306f59fce84SKent Overstreet 	int ret;
1307cafe5635SKent Overstreet 	struct io *io;
1308f59fce84SKent Overstreet 	struct request_queue *q = bdev_get_queue(dc->bdev);
1309cafe5635SKent Overstreet 
1310cafe5635SKent Overstreet 	__module_get(THIS_MODULE);
1311cafe5635SKent Overstreet 	INIT_LIST_HEAD(&dc->list);
1312f59fce84SKent Overstreet 	closure_init(&dc->disk.cl, NULL);
1313f59fce84SKent Overstreet 	set_closure_fn(&dc->disk.cl, cached_dev_flush, system_wq);
1314cafe5635SKent Overstreet 	kobject_init(&dc->disk.kobj, &bch_cached_dev_ktype);
1315cafe5635SKent Overstreet 	INIT_WORK(&dc->detach, cached_dev_detach_finish);
1316cb7a583eSKent Overstreet 	sema_init(&dc->sb_write_mutex, 1);
1317f59fce84SKent Overstreet 	INIT_LIST_HEAD(&dc->io_lru);
1318f59fce84SKent Overstreet 	spin_lock_init(&dc->io_lock);
1319f59fce84SKent Overstreet 	bch_cache_accounting_init(&dc->accounting, &dc->disk.cl);
1320cafe5635SKent Overstreet 
1321cafe5635SKent Overstreet 	dc->sequential_cutoff		= 4 << 20;
1322cafe5635SKent Overstreet 
1323cafe5635SKent Overstreet 	for (io = dc->io; io < dc->io + RECENT_IO; io++) {
1324cafe5635SKent Overstreet 		list_add(&io->lru, &dc->io_lru);
1325cafe5635SKent Overstreet 		hlist_add_head(&io->hash, dc->io_hash + RECENT_IO);
1326cafe5635SKent Overstreet 	}
1327cafe5635SKent Overstreet 
1328c78afc62SKent Overstreet 	dc->disk.stripe_size = q->limits.io_opt >> 9;
1329c78afc62SKent Overstreet 
1330c78afc62SKent Overstreet 	if (dc->disk.stripe_size)
1331c78afc62SKent Overstreet 		dc->partial_stripes_expensive =
1332c78afc62SKent Overstreet 			q->limits.raid_partial_stripes_expensive;
1333c78afc62SKent Overstreet 
1334279afbadSKent Overstreet 	ret = bcache_device_init(&dc->disk, block_size,
1335279afbadSKent Overstreet 			 dc->bdev->bd_part->nr_sects - dc->sb.data_offset);
1336f59fce84SKent Overstreet 	if (ret)
1337f59fce84SKent Overstreet 		return ret;
1338f59fce84SKent Overstreet 
1339dc3b17ccSJan Kara 	dc->disk.disk->queue->backing_dev_info->ra_pages =
1340dc3b17ccSJan Kara 		max(dc->disk.disk->queue->backing_dev_info->ra_pages,
1341dc3b17ccSJan Kara 		    q->backing_dev_info->ra_pages);
1342f59fce84SKent Overstreet 
1343c7b7bd07SColy Li 	atomic_set(&dc->io_errors, 0);
1344c7b7bd07SColy Li 	dc->io_disable = false;
1345c7b7bd07SColy Li 	dc->error_limit = DEFAULT_CACHED_DEV_ERROR_LIMIT;
13467e027ca4SColy Li 	/* default to auto */
13477e027ca4SColy Li 	dc->stop_when_cache_set_failed = BCH_CACHED_DEV_STOP_AUTO;
13487e027ca4SColy Li 
1349f59fce84SKent Overstreet 	bch_cached_dev_request_init(dc);
1350f59fce84SKent Overstreet 	bch_cached_dev_writeback_init(dc);
1351cafe5635SKent Overstreet 	return 0;
1352cafe5635SKent Overstreet }
1353cafe5635SKent Overstreet 
1354cafe5635SKent Overstreet /* Cached device - bcache superblock */
1355cafe5635SKent Overstreet 
135688c12d42SColy Li static int register_bdev(struct cache_sb *sb, struct page *sb_page,
1357cafe5635SKent Overstreet 				 struct block_device *bdev,
1358cafe5635SKent Overstreet 				 struct cached_dev *dc)
1359cafe5635SKent Overstreet {
1360cafe5635SKent Overstreet 	const char *err = "cannot allocate memory";
1361cafe5635SKent Overstreet 	struct cache_set *c;
13620b13efecSColy Li 	int ret = -ENOMEM;
1363cafe5635SKent Overstreet 
13646e916a7eSColy Li 	bdevname(bdev, dc->backing_dev_name);
1365cafe5635SKent Overstreet 	memcpy(&dc->sb, sb, sizeof(struct cache_sb));
1366cafe5635SKent Overstreet 	dc->bdev = bdev;
1367cafe5635SKent Overstreet 	dc->bdev->bd_holder = dc;
1368cafe5635SKent Overstreet 
13693a83f467SMing Lei 	bio_init(&dc->sb_bio, dc->sb_bio.bi_inline_vecs, 1);
1370263663cdSMing Lei 	bio_first_bvec_all(&dc->sb_bio)->bv_page = sb_page;
1371f59fce84SKent Overstreet 	get_page(sb_page);
1372cafe5635SKent Overstreet 
13736e916a7eSColy Li 
1374f59fce84SKent Overstreet 	if (cached_dev_init(dc, sb->block_size << 9))
1375f59fce84SKent Overstreet 		goto err;
1376cafe5635SKent Overstreet 
1377cafe5635SKent Overstreet 	err = "error creating kobject";
1378cafe5635SKent Overstreet 	if (kobject_add(&dc->disk.kobj, &part_to_dev(bdev->bd_part)->kobj,
1379cafe5635SKent Overstreet 			"bcache"))
1380cafe5635SKent Overstreet 		goto err;
1381cafe5635SKent Overstreet 	if (bch_cache_accounting_add_kobjs(&dc->accounting, &dc->disk.kobj))
1382cafe5635SKent Overstreet 		goto err;
1383cafe5635SKent Overstreet 
13846e916a7eSColy Li 	pr_info("registered backing device %s", dc->backing_dev_name);
1385f59fce84SKent Overstreet 
1386cafe5635SKent Overstreet 	list_add(&dc->list, &uncached_devices);
1387e57fd746SColy Li 	/* attach to a matched cache set if it exists */
1388cafe5635SKent Overstreet 	list_for_each_entry(c, &bch_cache_sets, list)
138973ac105bSTang Junhui 		bch_cached_dev_attach(dc, c, NULL);
1390cafe5635SKent Overstreet 
1391cafe5635SKent Overstreet 	if (BDEV_STATE(&dc->sb) == BDEV_STATE_NONE ||
13920b13efecSColy Li 	    BDEV_STATE(&dc->sb) == BDEV_STATE_STALE) {
13930b13efecSColy Li 		err = "failed to run cached device";
13940b13efecSColy Li 		ret = bch_cached_dev_run(dc);
13950b13efecSColy Li 		if (ret)
13960b13efecSColy Li 			goto err;
13970b13efecSColy Li 	}
1398cafe5635SKent Overstreet 
139988c12d42SColy Li 	return 0;
1400cafe5635SKent Overstreet err:
14016e916a7eSColy Li 	pr_notice("error %s: %s", dc->backing_dev_name, err);
1402f59fce84SKent Overstreet 	bcache_device_stop(&dc->disk);
14030b13efecSColy Li 	return ret;
1404cafe5635SKent Overstreet }
1405cafe5635SKent Overstreet 
1406cafe5635SKent Overstreet /* Flash only volumes */
1407cafe5635SKent Overstreet 
14082d17456eSColy Li /* When d->kobj released */
1409cafe5635SKent Overstreet void bch_flash_dev_release(struct kobject *kobj)
1410cafe5635SKent Overstreet {
1411cafe5635SKent Overstreet 	struct bcache_device *d = container_of(kobj, struct bcache_device,
1412cafe5635SKent Overstreet 					       kobj);
1413cafe5635SKent Overstreet 	kfree(d);
1414cafe5635SKent Overstreet }
1415cafe5635SKent Overstreet 
1416cafe5635SKent Overstreet static void flash_dev_free(struct closure *cl)
1417cafe5635SKent Overstreet {
1418cafe5635SKent Overstreet 	struct bcache_device *d = container_of(cl, struct bcache_device, cl);
14191fae7cf0SColy Li 
1420e5112201SSlava Pestov 	mutex_lock(&bch_register_lock);
142199a27d59STang Junhui 	atomic_long_sub(bcache_dev_sectors_dirty(d),
142299a27d59STang Junhui 			&d->c->flash_dev_dirty_sectors);
1423cafe5635SKent Overstreet 	bcache_device_free(d);
1424e5112201SSlava Pestov 	mutex_unlock(&bch_register_lock);
1425cafe5635SKent Overstreet 	kobject_put(&d->kobj);
1426cafe5635SKent Overstreet }
1427cafe5635SKent Overstreet 
1428cafe5635SKent Overstreet static void flash_dev_flush(struct closure *cl)
1429cafe5635SKent Overstreet {
1430cafe5635SKent Overstreet 	struct bcache_device *d = container_of(cl, struct bcache_device, cl);
1431cafe5635SKent Overstreet 
1432e5112201SSlava Pestov 	mutex_lock(&bch_register_lock);
1433ee668506SKent Overstreet 	bcache_device_unlink(d);
1434e5112201SSlava Pestov 	mutex_unlock(&bch_register_lock);
1435cafe5635SKent Overstreet 	kobject_del(&d->kobj);
1436cafe5635SKent Overstreet 	continue_at(cl, flash_dev_free, system_wq);
1437cafe5635SKent Overstreet }
1438cafe5635SKent Overstreet 
1439cafe5635SKent Overstreet static int flash_dev_run(struct cache_set *c, struct uuid_entry *u)
1440cafe5635SKent Overstreet {
1441cafe5635SKent Overstreet 	struct bcache_device *d = kzalloc(sizeof(struct bcache_device),
1442cafe5635SKent Overstreet 					  GFP_KERNEL);
1443cafe5635SKent Overstreet 	if (!d)
1444cafe5635SKent Overstreet 		return -ENOMEM;
1445cafe5635SKent Overstreet 
1446cafe5635SKent Overstreet 	closure_init(&d->cl, NULL);
1447cafe5635SKent Overstreet 	set_closure_fn(&d->cl, flash_dev_flush, system_wq);
1448cafe5635SKent Overstreet 
1449cafe5635SKent Overstreet 	kobject_init(&d->kobj, &bch_flash_dev_ktype);
1450cafe5635SKent Overstreet 
1451279afbadSKent Overstreet 	if (bcache_device_init(d, block_bytes(c), u->sectors))
1452cafe5635SKent Overstreet 		goto err;
1453cafe5635SKent Overstreet 
1454cafe5635SKent Overstreet 	bcache_device_attach(d, c, u - c->uuids);
1455175206cfSTang Junhui 	bch_sectors_dirty_init(d);
1456cafe5635SKent Overstreet 	bch_flash_dev_request_init(d);
1457cafe5635SKent Overstreet 	add_disk(d->disk);
1458cafe5635SKent Overstreet 
1459cafe5635SKent Overstreet 	if (kobject_add(&d->kobj, &disk_to_dev(d->disk)->kobj, "bcache"))
1460cafe5635SKent Overstreet 		goto err;
1461cafe5635SKent Overstreet 
1462cafe5635SKent Overstreet 	bcache_device_link(d, c, "volume");
1463cafe5635SKent Overstreet 
1464cafe5635SKent Overstreet 	return 0;
1465cafe5635SKent Overstreet err:
1466cafe5635SKent Overstreet 	kobject_put(&d->kobj);
1467cafe5635SKent Overstreet 	return -ENOMEM;
1468cafe5635SKent Overstreet }
1469cafe5635SKent Overstreet 
1470cafe5635SKent Overstreet static int flash_devs_run(struct cache_set *c)
1471cafe5635SKent Overstreet {
1472cafe5635SKent Overstreet 	int ret = 0;
1473cafe5635SKent Overstreet 	struct uuid_entry *u;
1474cafe5635SKent Overstreet 
1475cafe5635SKent Overstreet 	for (u = c->uuids;
147602aa8a8bSColy Li 	     u < c->uuids + c->nr_uuids && !ret;
1477cafe5635SKent Overstreet 	     u++)
1478cafe5635SKent Overstreet 		if (UUID_FLASH_ONLY(u))
1479cafe5635SKent Overstreet 			ret = flash_dev_run(c, u);
1480cafe5635SKent Overstreet 
1481cafe5635SKent Overstreet 	return ret;
1482cafe5635SKent Overstreet }
1483cafe5635SKent Overstreet 
1484cafe5635SKent Overstreet int bch_flash_dev_create(struct cache_set *c, uint64_t size)
1485cafe5635SKent Overstreet {
1486cafe5635SKent Overstreet 	struct uuid_entry *u;
1487cafe5635SKent Overstreet 
1488cafe5635SKent Overstreet 	if (test_bit(CACHE_SET_STOPPING, &c->flags))
1489cafe5635SKent Overstreet 		return -EINTR;
1490cafe5635SKent Overstreet 
1491bf0c55c9SSlava Pestov 	if (!test_bit(CACHE_SET_RUNNING, &c->flags))
1492bf0c55c9SSlava Pestov 		return -EPERM;
1493bf0c55c9SSlava Pestov 
1494cafe5635SKent Overstreet 	u = uuid_find_empty(c);
1495cafe5635SKent Overstreet 	if (!u) {
1496cafe5635SKent Overstreet 		pr_err("Can't create volume, no room for UUID");
1497cafe5635SKent Overstreet 		return -EINVAL;
1498cafe5635SKent Overstreet 	}
1499cafe5635SKent Overstreet 
1500cafe5635SKent Overstreet 	get_random_bytes(u->uuid, 16);
1501cafe5635SKent Overstreet 	memset(u->label, 0, 32);
150275cbb3f1SArnd Bergmann 	u->first_reg = u->last_reg = cpu_to_le32((u32)ktime_get_real_seconds());
1503cafe5635SKent Overstreet 
1504cafe5635SKent Overstreet 	SET_UUID_FLASH_ONLY(u, 1);
1505cafe5635SKent Overstreet 	u->sectors = size >> 9;
1506cafe5635SKent Overstreet 
1507cafe5635SKent Overstreet 	bch_uuid_write(c);
1508cafe5635SKent Overstreet 
1509cafe5635SKent Overstreet 	return flash_dev_run(c, u);
1510cafe5635SKent Overstreet }
1511cafe5635SKent Overstreet 
1512c7b7bd07SColy Li bool bch_cached_dev_error(struct cached_dev *dc)
1513c7b7bd07SColy Li {
1514c7b7bd07SColy Li 	if (!dc || test_bit(BCACHE_DEV_CLOSING, &dc->disk.flags))
1515c7b7bd07SColy Li 		return false;
1516c7b7bd07SColy Li 
1517c7b7bd07SColy Li 	dc->io_disable = true;
1518c7b7bd07SColy Li 	/* make others know io_disable is true earlier */
1519c7b7bd07SColy Li 	smp_mb();
1520c7b7bd07SColy Li 
1521c7b7bd07SColy Li 	pr_err("stop %s: too many IO errors on backing device %s\n",
15226e916a7eSColy Li 		dc->disk.disk->disk_name, dc->backing_dev_name);
1523c7b7bd07SColy Li 
1524c7b7bd07SColy Li 	bcache_device_stop(&dc->disk);
1525c7b7bd07SColy Li 	return true;
1526c7b7bd07SColy Li }
1527c7b7bd07SColy Li 
1528cafe5635SKent Overstreet /* Cache set */
1529cafe5635SKent Overstreet 
1530cafe5635SKent Overstreet __printf(2, 3)
1531cafe5635SKent Overstreet bool bch_cache_set_error(struct cache_set *c, const char *fmt, ...)
1532cafe5635SKent Overstreet {
1533cafe5635SKent Overstreet 	va_list args;
1534cafe5635SKent Overstreet 
153577c320ebSKent Overstreet 	if (c->on_error != ON_ERROR_PANIC &&
153677c320ebSKent Overstreet 	    test_bit(CACHE_SET_STOPPING, &c->flags))
1537cafe5635SKent Overstreet 		return false;
1538cafe5635SKent Overstreet 
1539771f393eSColy Li 	if (test_and_set_bit(CACHE_SET_IO_DISABLE, &c->flags))
154009a44ca2SColy Li 		pr_info("CACHE_SET_IO_DISABLE already set");
1541771f393eSColy Li 
15423be11dbaSColy Li 	/*
15433be11dbaSColy Li 	 * XXX: we can be called from atomic context
15443be11dbaSColy Li 	 * acquire_console_sem();
1545cafe5635SKent Overstreet 	 */
1546cafe5635SKent Overstreet 
15476ae63e35SColy Li 	pr_err("bcache: error on %pU: ", c->sb.set_uuid);
1548cafe5635SKent Overstreet 
1549cafe5635SKent Overstreet 	va_start(args, fmt);
1550cafe5635SKent Overstreet 	vprintk(fmt, args);
1551cafe5635SKent Overstreet 	va_end(args);
1552cafe5635SKent Overstreet 
15536ae63e35SColy Li 	pr_err(", disabling caching\n");
1554cafe5635SKent Overstreet 
155577c320ebSKent Overstreet 	if (c->on_error == ON_ERROR_PANIC)
155677c320ebSKent Overstreet 		panic("panic forced after error\n");
155777c320ebSKent Overstreet 
1558cafe5635SKent Overstreet 	bch_cache_set_unregister(c);
1559cafe5635SKent Overstreet 	return true;
1560cafe5635SKent Overstreet }
1561cafe5635SKent Overstreet 
15622d17456eSColy Li /* When c->kobj released */
1563cafe5635SKent Overstreet void bch_cache_set_release(struct kobject *kobj)
1564cafe5635SKent Overstreet {
1565cafe5635SKent Overstreet 	struct cache_set *c = container_of(kobj, struct cache_set, kobj);
15661fae7cf0SColy Li 
1567cafe5635SKent Overstreet 	kfree(c);
1568cafe5635SKent Overstreet 	module_put(THIS_MODULE);
1569cafe5635SKent Overstreet }
1570cafe5635SKent Overstreet 
1571cafe5635SKent Overstreet static void cache_set_free(struct closure *cl)
1572cafe5635SKent Overstreet {
1573cafe5635SKent Overstreet 	struct cache_set *c = container_of(cl, struct cache_set, cl);
1574cafe5635SKent Overstreet 	struct cache *ca;
15756f10f7d1SColy Li 	unsigned int i;
1576cafe5635SKent Overstreet 
1577cafe5635SKent Overstreet 	debugfs_remove(c->debug);
1578cafe5635SKent Overstreet 
1579cafe5635SKent Overstreet 	bch_open_buckets_free(c);
1580cafe5635SKent Overstreet 	bch_btree_cache_free(c);
1581cafe5635SKent Overstreet 	bch_journal_free(c);
1582cafe5635SKent Overstreet 
1583a4b732a2SLiang Chen 	mutex_lock(&bch_register_lock);
1584cafe5635SKent Overstreet 	for_each_cache(ca, c, i)
1585c9a78332SSlava Pestov 		if (ca) {
1586c9a78332SSlava Pestov 			ca->set = NULL;
1587c9a78332SSlava Pestov 			c->cache[ca->sb.nr_this_dev] = NULL;
1588cafe5635SKent Overstreet 			kobject_put(&ca->kobj);
1589c9a78332SSlava Pestov 		}
1590cafe5635SKent Overstreet 
159167539e85SKent Overstreet 	bch_bset_sort_state_free(&c->sort);
1592cafe5635SKent Overstreet 	free_pages((unsigned long) c->uuids, ilog2(bucket_pages(c)));
1593cafe5635SKent Overstreet 
1594da415a09SNicholas Swenson 	if (c->moving_gc_wq)
1595da415a09SNicholas Swenson 		destroy_workqueue(c->moving_gc_wq);
1596d19936a2SKent Overstreet 	bioset_exit(&c->bio_split);
1597d19936a2SKent Overstreet 	mempool_exit(&c->fill_iter);
1598d19936a2SKent Overstreet 	mempool_exit(&c->bio_meta);
1599d19936a2SKent Overstreet 	mempool_exit(&c->search);
1600cafe5635SKent Overstreet 	kfree(c->devices);
1601cafe5635SKent Overstreet 
1602cafe5635SKent Overstreet 	list_del(&c->list);
1603cafe5635SKent Overstreet 	mutex_unlock(&bch_register_lock);
1604cafe5635SKent Overstreet 
1605cafe5635SKent Overstreet 	pr_info("Cache set %pU unregistered", c->sb.set_uuid);
1606cafe5635SKent Overstreet 	wake_up(&unregister_wait);
1607cafe5635SKent Overstreet 
1608cafe5635SKent Overstreet 	closure_debug_destroy(&c->cl);
1609cafe5635SKent Overstreet 	kobject_put(&c->kobj);
1610cafe5635SKent Overstreet }
1611cafe5635SKent Overstreet 
1612cafe5635SKent Overstreet static void cache_set_flush(struct closure *cl)
1613cafe5635SKent Overstreet {
1614cafe5635SKent Overstreet 	struct cache_set *c = container_of(cl, struct cache_set, caching);
161579826c35SKent Overstreet 	struct cache *ca;
1616cafe5635SKent Overstreet 	struct btree *b;
16176f10f7d1SColy Li 	unsigned int i;
1618cafe5635SKent Overstreet 
1619cafe5635SKent Overstreet 	bch_cache_accounting_destroy(&c->accounting);
1620cafe5635SKent Overstreet 
1621cafe5635SKent Overstreet 	kobject_put(&c->internal);
1622cafe5635SKent Overstreet 	kobject_del(&c->kobj);
1623cafe5635SKent Overstreet 
1624b387e9b5SColy Li 	if (!IS_ERR_OR_NULL(c->gc_thread))
162572a44517SKent Overstreet 		kthread_stop(c->gc_thread);
162672a44517SKent Overstreet 
1627cafe5635SKent Overstreet 	if (!IS_ERR_OR_NULL(c->root))
1628cafe5635SKent Overstreet 		list_add(&c->root->list, &c->btree_cache);
1629cafe5635SKent Overstreet 
1630e6dcbd3eSColy Li 	/*
1631e6dcbd3eSColy Li 	 * Avoid flushing cached nodes if cache set is retiring
1632e6dcbd3eSColy Li 	 * due to too many I/O errors detected.
1633e6dcbd3eSColy Li 	 */
1634e6dcbd3eSColy Li 	if (!test_bit(CACHE_SET_IO_DISABLE, &c->flags))
16352a285686SKent Overstreet 		list_for_each_entry(b, &c->btree_cache, list) {
16362a285686SKent Overstreet 			mutex_lock(&b->write_lock);
1637cafe5635SKent Overstreet 			if (btree_node_dirty(b))
16382a285686SKent Overstreet 				__bch_btree_node_write(b, NULL);
16392a285686SKent Overstreet 			mutex_unlock(&b->write_lock);
16402a285686SKent Overstreet 		}
1641cafe5635SKent Overstreet 
164279826c35SKent Overstreet 	for_each_cache(ca, c, i)
164379826c35SKent Overstreet 		if (ca->alloc_thread)
164479826c35SKent Overstreet 			kthread_stop(ca->alloc_thread);
164579826c35SKent Overstreet 
16465b1016e6SKent Overstreet 	if (c->journal.cur) {
1647dabb4433SKent Overstreet 		cancel_delayed_work_sync(&c->journal.work);
1648dabb4433SKent Overstreet 		/* flush last journal entry if needed */
1649dabb4433SKent Overstreet 		c->journal.work.work.func(&c->journal.work.work);
16505b1016e6SKent Overstreet 	}
1651dabb4433SKent Overstreet 
1652cafe5635SKent Overstreet 	closure_return(cl);
1653cafe5635SKent Overstreet }
1654cafe5635SKent Overstreet 
16557e027ca4SColy Li /*
16567e027ca4SColy Li  * This function is only called when CACHE_SET_IO_DISABLE is set, which means
16577e027ca4SColy Li  * cache set is unregistering due to too many I/O errors. In this condition,
16587e027ca4SColy Li  * the bcache device might be stopped, it depends on stop_when_cache_set_failed
16597e027ca4SColy Li  * value and whether the broken cache has dirty data:
16607e027ca4SColy Li  *
16617e027ca4SColy Li  * dc->stop_when_cache_set_failed    dc->has_dirty   stop bcache device
16627e027ca4SColy Li  *  BCH_CACHED_STOP_AUTO               0               NO
16637e027ca4SColy Li  *  BCH_CACHED_STOP_AUTO               1               YES
16647e027ca4SColy Li  *  BCH_CACHED_DEV_STOP_ALWAYS         0               YES
16657e027ca4SColy Li  *  BCH_CACHED_DEV_STOP_ALWAYS         1               YES
16667e027ca4SColy Li  *
16677e027ca4SColy Li  * The expected behavior is, if stop_when_cache_set_failed is configured to
16687e027ca4SColy Li  * "auto" via sysfs interface, the bcache device will not be stopped if the
16697e027ca4SColy Li  * backing device is clean on the broken cache device.
16707e027ca4SColy Li  */
16717e027ca4SColy Li static void conditional_stop_bcache_device(struct cache_set *c,
16727e027ca4SColy Li 					   struct bcache_device *d,
16737e027ca4SColy Li 					   struct cached_dev *dc)
16747e027ca4SColy Li {
16757e027ca4SColy Li 	if (dc->stop_when_cache_set_failed == BCH_CACHED_DEV_STOP_ALWAYS) {
16767e027ca4SColy Li 		pr_warn("stop_when_cache_set_failed of %s is \"always\", stop it for failed cache set %pU.",
16777e027ca4SColy Li 			d->disk->disk_name, c->sb.set_uuid);
16787e027ca4SColy Li 		bcache_device_stop(d);
16797e027ca4SColy Li 	} else if (atomic_read(&dc->has_dirty)) {
16807e027ca4SColy Li 		/*
16817e027ca4SColy Li 		 * dc->stop_when_cache_set_failed == BCH_CACHED_STOP_AUTO
16827e027ca4SColy Li 		 * and dc->has_dirty == 1
16837e027ca4SColy Li 		 */
16847e027ca4SColy Li 		pr_warn("stop_when_cache_set_failed of %s is \"auto\" and cache is dirty, stop it to avoid potential data corruption.",
16857e027ca4SColy Li 			d->disk->disk_name);
16864fd8e138SColy Li 		/*
16874fd8e138SColy Li 		 * There might be a small time gap that cache set is
16884fd8e138SColy Li 		 * released but bcache device is not. Inside this time
16894fd8e138SColy Li 		 * gap, regular I/O requests will directly go into
16904fd8e138SColy Li 		 * backing device as no cache set attached to. This
16914fd8e138SColy Li 		 * behavior may also introduce potential inconsistence
16924fd8e138SColy Li 		 * data in writeback mode while cache is dirty.
16934fd8e138SColy Li 		 * Therefore before calling bcache_device_stop() due
16944fd8e138SColy Li 		 * to a broken cache device, dc->io_disable should be
16954fd8e138SColy Li 		 * explicitly set to true.
16964fd8e138SColy Li 		 */
16974fd8e138SColy Li 		dc->io_disable = true;
16984fd8e138SColy Li 		/* make others know io_disable is true earlier */
16994fd8e138SColy Li 		smp_mb();
17007e027ca4SColy Li 		bcache_device_stop(d);
17017e027ca4SColy Li 	} else {
17027e027ca4SColy Li 		/*
17037e027ca4SColy Li 		 * dc->stop_when_cache_set_failed == BCH_CACHED_STOP_AUTO
17047e027ca4SColy Li 		 * and dc->has_dirty == 0
17057e027ca4SColy Li 		 */
17067e027ca4SColy Li 		pr_warn("stop_when_cache_set_failed of %s is \"auto\" and cache is clean, keep it alive.",
17077e027ca4SColy Li 			d->disk->disk_name);
17087e027ca4SColy Li 	}
17097e027ca4SColy Li }
17107e027ca4SColy Li 
1711cafe5635SKent Overstreet static void __cache_set_unregister(struct closure *cl)
1712cafe5635SKent Overstreet {
1713cafe5635SKent Overstreet 	struct cache_set *c = container_of(cl, struct cache_set, caching);
17145caa52afSKent Overstreet 	struct cached_dev *dc;
17157e027ca4SColy Li 	struct bcache_device *d;
1716cafe5635SKent Overstreet 	size_t i;
1717cafe5635SKent Overstreet 
1718cafe5635SKent Overstreet 	mutex_lock(&bch_register_lock);
1719cafe5635SKent Overstreet 
17207e027ca4SColy Li 	for (i = 0; i < c->devices_max_used; i++) {
17217e027ca4SColy Li 		d = c->devices[i];
17227e027ca4SColy Li 		if (!d)
17237e027ca4SColy Li 			continue;
17247e027ca4SColy Li 
17255caa52afSKent Overstreet 		if (!UUID_FLASH_ONLY(&c->uuids[i]) &&
17265caa52afSKent Overstreet 		    test_bit(CACHE_SET_UNREGISTERING, &c->flags)) {
17277e027ca4SColy Li 			dc = container_of(d, struct cached_dev, disk);
17285caa52afSKent Overstreet 			bch_cached_dev_detach(dc);
17297e027ca4SColy Li 			if (test_bit(CACHE_SET_IO_DISABLE, &c->flags))
17307e027ca4SColy Li 				conditional_stop_bcache_device(c, d, dc);
17315caa52afSKent Overstreet 		} else {
17327e027ca4SColy Li 			bcache_device_stop(d);
17335caa52afSKent Overstreet 		}
17345caa52afSKent Overstreet 	}
1735cafe5635SKent Overstreet 
1736cafe5635SKent Overstreet 	mutex_unlock(&bch_register_lock);
1737cafe5635SKent Overstreet 
1738cafe5635SKent Overstreet 	continue_at(cl, cache_set_flush, system_wq);
1739cafe5635SKent Overstreet }
1740cafe5635SKent Overstreet 
1741cafe5635SKent Overstreet void bch_cache_set_stop(struct cache_set *c)
1742cafe5635SKent Overstreet {
1743cafe5635SKent Overstreet 	if (!test_and_set_bit(CACHE_SET_STOPPING, &c->flags))
174463d63b51SColy Li 		/* closure_fn set to __cache_set_unregister() */
1745cafe5635SKent Overstreet 		closure_queue(&c->caching);
1746cafe5635SKent Overstreet }
1747cafe5635SKent Overstreet 
1748cafe5635SKent Overstreet void bch_cache_set_unregister(struct cache_set *c)
1749cafe5635SKent Overstreet {
1750cafe5635SKent Overstreet 	set_bit(CACHE_SET_UNREGISTERING, &c->flags);
1751cafe5635SKent Overstreet 	bch_cache_set_stop(c);
1752cafe5635SKent Overstreet }
1753cafe5635SKent Overstreet 
1754cafe5635SKent Overstreet #define alloc_bucket_pages(gfp, c)			\
1755cafe5635SKent Overstreet 	((void *) __get_free_pages(__GFP_ZERO|gfp, ilog2(bucket_pages(c))))
1756cafe5635SKent Overstreet 
1757cafe5635SKent Overstreet struct cache_set *bch_cache_set_alloc(struct cache_sb *sb)
1758cafe5635SKent Overstreet {
1759cafe5635SKent Overstreet 	int iter_size;
1760cafe5635SKent Overstreet 	struct cache_set *c = kzalloc(sizeof(struct cache_set), GFP_KERNEL);
17611fae7cf0SColy Li 
1762cafe5635SKent Overstreet 	if (!c)
1763cafe5635SKent Overstreet 		return NULL;
1764cafe5635SKent Overstreet 
1765cafe5635SKent Overstreet 	__module_get(THIS_MODULE);
1766cafe5635SKent Overstreet 	closure_init(&c->cl, NULL);
1767cafe5635SKent Overstreet 	set_closure_fn(&c->cl, cache_set_free, system_wq);
1768cafe5635SKent Overstreet 
1769cafe5635SKent Overstreet 	closure_init(&c->caching, &c->cl);
1770cafe5635SKent Overstreet 	set_closure_fn(&c->caching, __cache_set_unregister, system_wq);
1771cafe5635SKent Overstreet 
1772cafe5635SKent Overstreet 	/* Maybe create continue_at_noreturn() and use it here? */
1773cafe5635SKent Overstreet 	closure_set_stopped(&c->cl);
1774cafe5635SKent Overstreet 	closure_put(&c->cl);
1775cafe5635SKent Overstreet 
1776cafe5635SKent Overstreet 	kobject_init(&c->kobj, &bch_cache_set_ktype);
1777cafe5635SKent Overstreet 	kobject_init(&c->internal, &bch_cache_set_internal_ktype);
1778cafe5635SKent Overstreet 
1779cafe5635SKent Overstreet 	bch_cache_accounting_init(&c->accounting, &c->cl);
1780cafe5635SKent Overstreet 
1781cafe5635SKent Overstreet 	memcpy(c->sb.set_uuid, sb->set_uuid, 16);
1782cafe5635SKent Overstreet 	c->sb.block_size	= sb->block_size;
1783cafe5635SKent Overstreet 	c->sb.bucket_size	= sb->bucket_size;
1784cafe5635SKent Overstreet 	c->sb.nr_in_set		= sb->nr_in_set;
1785cafe5635SKent Overstreet 	c->sb.last_mount	= sb->last_mount;
1786cafe5635SKent Overstreet 	c->bucket_bits		= ilog2(sb->bucket_size);
1787cafe5635SKent Overstreet 	c->block_bits		= ilog2(sb->block_size);
1788cafe5635SKent Overstreet 	c->nr_uuids		= bucket_bytes(c) / sizeof(struct uuid_entry);
17892831231dSColy Li 	c->devices_max_used	= 0;
1790ea8c5356SColy Li 	atomic_set(&c->attached_dev_nr, 0);
1791ee811287SKent Overstreet 	c->btree_pages		= bucket_pages(c);
1792cafe5635SKent Overstreet 	if (c->btree_pages > BTREE_MAX_PAGES)
1793cafe5635SKent Overstreet 		c->btree_pages = max_t(int, c->btree_pages / 4,
1794cafe5635SKent Overstreet 				       BTREE_MAX_PAGES);
1795cafe5635SKent Overstreet 
1796cb7a583eSKent Overstreet 	sema_init(&c->sb_write_mutex, 1);
1797e8e1d468SKent Overstreet 	mutex_init(&c->bucket_lock);
17980a63b66dSKent Overstreet 	init_waitqueue_head(&c->btree_cache_wait);
179934cf78bfSGuoju Fang 	spin_lock_init(&c->btree_cannibalize_lock);
180035fcd848SKent Overstreet 	init_waitqueue_head(&c->bucket_wait);
1801be628be0SKent Overstreet 	init_waitqueue_head(&c->gc_wait);
1802cb7a583eSKent Overstreet 	sema_init(&c->uuid_write_mutex, 1);
180365d22e91SKent Overstreet 
180465d22e91SKent Overstreet 	spin_lock_init(&c->btree_gc_time.lock);
180565d22e91SKent Overstreet 	spin_lock_init(&c->btree_split_time.lock);
180665d22e91SKent Overstreet 	spin_lock_init(&c->btree_read_time.lock);
1807e8e1d468SKent Overstreet 
1808cafe5635SKent Overstreet 	bch_moving_init_cache_set(c);
1809cafe5635SKent Overstreet 
1810cafe5635SKent Overstreet 	INIT_LIST_HEAD(&c->list);
1811cafe5635SKent Overstreet 	INIT_LIST_HEAD(&c->cached_devs);
1812cafe5635SKent Overstreet 	INIT_LIST_HEAD(&c->btree_cache);
1813cafe5635SKent Overstreet 	INIT_LIST_HEAD(&c->btree_cache_freeable);
1814cafe5635SKent Overstreet 	INIT_LIST_HEAD(&c->btree_cache_freed);
1815cafe5635SKent Overstreet 	INIT_LIST_HEAD(&c->data_buckets);
1816cafe5635SKent Overstreet 
1817cafe5635SKent Overstreet 	iter_size = (sb->bucket_size / sb->block_size + 1) *
1818cafe5635SKent Overstreet 		sizeof(struct btree_iter_set);
1819cafe5635SKent Overstreet 
18206396bb22SKees Cook 	if (!(c->devices = kcalloc(c->nr_uuids, sizeof(void *), GFP_KERNEL)) ||
1821d19936a2SKent Overstreet 	    mempool_init_slab_pool(&c->search, 32, bch_search_cache) ||
1822d19936a2SKent Overstreet 	    mempool_init_kmalloc_pool(&c->bio_meta, 2,
1823cafe5635SKent Overstreet 				sizeof(struct bbio) + sizeof(struct bio_vec) *
1824d19936a2SKent Overstreet 				bucket_pages(c)) ||
1825d19936a2SKent Overstreet 	    mempool_init_kmalloc_pool(&c->fill_iter, 1, iter_size) ||
1826d19936a2SKent Overstreet 	    bioset_init(&c->bio_split, 4, offsetof(struct bbio, bio),
1827d19936a2SKent Overstreet 			BIOSET_NEED_BVECS|BIOSET_NEED_RESCUER) ||
1828cafe5635SKent Overstreet 	    !(c->uuids = alloc_bucket_pages(GFP_KERNEL, c)) ||
182981baf90aSBhaktipriya Shridhar 	    !(c->moving_gc_wq = alloc_workqueue("bcache_gc",
183081baf90aSBhaktipriya Shridhar 						WQ_MEM_RECLAIM, 0)) ||
1831cafe5635SKent Overstreet 	    bch_journal_alloc(c) ||
1832cafe5635SKent Overstreet 	    bch_btree_cache_alloc(c) ||
183367539e85SKent Overstreet 	    bch_open_buckets_alloc(c) ||
183467539e85SKent Overstreet 	    bch_bset_sort_state_init(&c->sort, ilog2(c->btree_pages)))
1835cafe5635SKent Overstreet 		goto err;
1836cafe5635SKent Overstreet 
1837cafe5635SKent Overstreet 	c->congested_read_threshold_us	= 2000;
1838cafe5635SKent Overstreet 	c->congested_write_threshold_us	= 20000;
18397ba0d830SColy Li 	c->error_limit	= DEFAULT_IO_ERROR_LIMIT;
1840c5fcdedcSColy Li 	c->idle_max_writeback_rate_enabled = 1;
1841771f393eSColy Li 	WARN_ON(test_and_clear_bit(CACHE_SET_IO_DISABLE, &c->flags));
1842cafe5635SKent Overstreet 
1843cafe5635SKent Overstreet 	return c;
1844cafe5635SKent Overstreet err:
1845cafe5635SKent Overstreet 	bch_cache_set_unregister(c);
1846cafe5635SKent Overstreet 	return NULL;
1847cafe5635SKent Overstreet }
1848cafe5635SKent Overstreet 
1849ce3e4cfbSColy Li static int run_cache_set(struct cache_set *c)
1850cafe5635SKent Overstreet {
1851cafe5635SKent Overstreet 	const char *err = "cannot allocate memory";
1852cafe5635SKent Overstreet 	struct cached_dev *dc, *t;
1853cafe5635SKent Overstreet 	struct cache *ca;
1854c18536a7SKent Overstreet 	struct closure cl;
18556f10f7d1SColy Li 	unsigned int i;
185695f18c9dSShenghui Wang 	LIST_HEAD(journal);
185795f18c9dSShenghui Wang 	struct journal_replay *l;
1858cafe5635SKent Overstreet 
1859c18536a7SKent Overstreet 	closure_init_stack(&cl);
1860cafe5635SKent Overstreet 
1861cafe5635SKent Overstreet 	for_each_cache(ca, c, i)
1862cafe5635SKent Overstreet 		c->nbuckets += ca->sb.nbuckets;
1863be628be0SKent Overstreet 	set_gc_sectors(c);
1864cafe5635SKent Overstreet 
1865cafe5635SKent Overstreet 	if (CACHE_SYNC(&c->sb)) {
1866cafe5635SKent Overstreet 		struct bkey *k;
1867cafe5635SKent Overstreet 		struct jset *j;
1868cafe5635SKent Overstreet 
1869cafe5635SKent Overstreet 		err = "cannot allocate memory for journal";
1870c18536a7SKent Overstreet 		if (bch_journal_read(c, &journal))
1871cafe5635SKent Overstreet 			goto err;
1872cafe5635SKent Overstreet 
1873cafe5635SKent Overstreet 		pr_debug("btree_journal_read() done");
1874cafe5635SKent Overstreet 
1875cafe5635SKent Overstreet 		err = "no journal entries found";
1876cafe5635SKent Overstreet 		if (list_empty(&journal))
1877cafe5635SKent Overstreet 			goto err;
1878cafe5635SKent Overstreet 
1879cafe5635SKent Overstreet 		j = &list_entry(journal.prev, struct journal_replay, list)->j;
1880cafe5635SKent Overstreet 
1881cafe5635SKent Overstreet 		err = "IO error reading priorities";
1882cafe5635SKent Overstreet 		for_each_cache(ca, c, i)
1883cafe5635SKent Overstreet 			prio_read(ca, j->prio_bucket[ca->sb.nr_this_dev]);
1884cafe5635SKent Overstreet 
1885cafe5635SKent Overstreet 		/*
1886cafe5635SKent Overstreet 		 * If prio_read() fails it'll call cache_set_error and we'll
1887cafe5635SKent Overstreet 		 * tear everything down right away, but if we perhaps checked
1888cafe5635SKent Overstreet 		 * sooner we could avoid journal replay.
1889cafe5635SKent Overstreet 		 */
1890cafe5635SKent Overstreet 
1891cafe5635SKent Overstreet 		k = &j->btree_root;
1892cafe5635SKent Overstreet 
1893cafe5635SKent Overstreet 		err = "bad btree root";
189465d45231SKent Overstreet 		if (__bch_btree_ptr_invalid(c, k))
1895cafe5635SKent Overstreet 			goto err;
1896cafe5635SKent Overstreet 
1897cafe5635SKent Overstreet 		err = "error reading btree root";
1898b0d30981SColy Li 		c->root = bch_btree_node_get(c, NULL, k,
1899b0d30981SColy Li 					     j->btree_level,
1900b0d30981SColy Li 					     true, NULL);
1901cafe5635SKent Overstreet 		if (IS_ERR_OR_NULL(c->root))
1902cafe5635SKent Overstreet 			goto err;
1903cafe5635SKent Overstreet 
1904cafe5635SKent Overstreet 		list_del_init(&c->root->list);
1905cafe5635SKent Overstreet 		rw_unlock(true, c->root);
1906cafe5635SKent Overstreet 
1907c18536a7SKent Overstreet 		err = uuid_read(c, j, &cl);
1908cafe5635SKent Overstreet 		if (err)
1909cafe5635SKent Overstreet 			goto err;
1910cafe5635SKent Overstreet 
1911cafe5635SKent Overstreet 		err = "error in recovery";
1912c18536a7SKent Overstreet 		if (bch_btree_check(c))
1913cafe5635SKent Overstreet 			goto err;
1914cafe5635SKent Overstreet 
19151df3877fSColy Li 		/*
19161df3877fSColy Li 		 * bch_btree_check() may occupy too much system memory which
19171df3877fSColy Li 		 * has negative effects to user space application (e.g. data
19181df3877fSColy Li 		 * base) performance. Shrink the mca cache memory proactively
19191df3877fSColy Li 		 * here to avoid competing memory with user space workloads..
19201df3877fSColy Li 		 */
19211df3877fSColy Li 		if (!c->shrinker_disabled) {
19221df3877fSColy Li 			struct shrink_control sc;
19231df3877fSColy Li 
19241df3877fSColy Li 			sc.gfp_mask = GFP_KERNEL;
19251df3877fSColy Li 			sc.nr_to_scan = c->btree_cache_used * c->btree_pages;
19261df3877fSColy Li 			/* first run to clear b->accessed tag */
19271df3877fSColy Li 			c->shrink.scan_objects(&c->shrink, &sc);
19281df3877fSColy Li 			/* second run to reap non-accessed nodes */
19291df3877fSColy Li 			c->shrink.scan_objects(&c->shrink, &sc);
19301df3877fSColy Li 		}
19311df3877fSColy Li 
1932cafe5635SKent Overstreet 		bch_journal_mark(c, &journal);
19332531d9eeSKent Overstreet 		bch_initial_gc_finish(c);
1934cafe5635SKent Overstreet 		pr_debug("btree_check() done");
1935cafe5635SKent Overstreet 
1936cafe5635SKent Overstreet 		/*
1937cafe5635SKent Overstreet 		 * bcache_journal_next() can't happen sooner, or
1938cafe5635SKent Overstreet 		 * btree_gc_finish() will give spurious errors about last_gc >
1939cafe5635SKent Overstreet 		 * gc_gen - this is a hack but oh well.
1940cafe5635SKent Overstreet 		 */
1941cafe5635SKent Overstreet 		bch_journal_next(&c->journal);
1942cafe5635SKent Overstreet 
1943119ba0f8SKent Overstreet 		err = "error starting allocator thread";
1944cafe5635SKent Overstreet 		for_each_cache(ca, c, i)
1945119ba0f8SKent Overstreet 			if (bch_cache_allocator_start(ca))
1946119ba0f8SKent Overstreet 				goto err;
1947cafe5635SKent Overstreet 
1948cafe5635SKent Overstreet 		/*
1949cafe5635SKent Overstreet 		 * First place it's safe to allocate: btree_check() and
1950cafe5635SKent Overstreet 		 * btree_gc_finish() have to run before we have buckets to
1951cafe5635SKent Overstreet 		 * allocate, and bch_bucket_alloc_set() might cause a journal
1952cafe5635SKent Overstreet 		 * entry to be written so bcache_journal_next() has to be called
1953cafe5635SKent Overstreet 		 * first.
1954cafe5635SKent Overstreet 		 *
1955cafe5635SKent Overstreet 		 * If the uuids were in the old format we have to rewrite them
1956cafe5635SKent Overstreet 		 * before the next journal entry is written:
1957cafe5635SKent Overstreet 		 */
1958cafe5635SKent Overstreet 		if (j->version < BCACHE_JSET_VERSION_UUID)
1959cafe5635SKent Overstreet 			__uuid_write(c);
1960cafe5635SKent Overstreet 
1961ce3e4cfbSColy Li 		err = "bcache: replay journal failed";
1962ce3e4cfbSColy Li 		if (bch_journal_replay(c, &journal))
1963ce3e4cfbSColy Li 			goto err;
1964cafe5635SKent Overstreet 	} else {
1965cafe5635SKent Overstreet 		pr_notice("invalidating existing data");
1966cafe5635SKent Overstreet 
1967cafe5635SKent Overstreet 		for_each_cache(ca, c, i) {
19686f10f7d1SColy Li 			unsigned int j;
1969cafe5635SKent Overstreet 
1970cafe5635SKent Overstreet 			ca->sb.keys = clamp_t(int, ca->sb.nbuckets >> 7,
1971cafe5635SKent Overstreet 					      2, SB_JOURNAL_BUCKETS);
1972cafe5635SKent Overstreet 
1973cafe5635SKent Overstreet 			for (j = 0; j < ca->sb.keys; j++)
1974cafe5635SKent Overstreet 				ca->sb.d[j] = ca->sb.first_bucket + j;
1975cafe5635SKent Overstreet 		}
1976cafe5635SKent Overstreet 
19772531d9eeSKent Overstreet 		bch_initial_gc_finish(c);
1978cafe5635SKent Overstreet 
1979119ba0f8SKent Overstreet 		err = "error starting allocator thread";
1980cafe5635SKent Overstreet 		for_each_cache(ca, c, i)
1981119ba0f8SKent Overstreet 			if (bch_cache_allocator_start(ca))
1982119ba0f8SKent Overstreet 				goto err;
1983cafe5635SKent Overstreet 
1984cafe5635SKent Overstreet 		mutex_lock(&c->bucket_lock);
1985cafe5635SKent Overstreet 		for_each_cache(ca, c, i)
198684c529aeSAndrea Righi 			bch_prio_write(ca, true);
1987cafe5635SKent Overstreet 		mutex_unlock(&c->bucket_lock);
1988cafe5635SKent Overstreet 
1989cafe5635SKent Overstreet 		err = "cannot allocate new UUID bucket";
1990cafe5635SKent Overstreet 		if (__uuid_write(c))
199172a44517SKent Overstreet 			goto err;
1992cafe5635SKent Overstreet 
1993cafe5635SKent Overstreet 		err = "cannot allocate new btree root";
19942452cc89SSlava Pestov 		c->root = __bch_btree_node_alloc(c, NULL, 0, true, NULL);
1995cafe5635SKent Overstreet 		if (IS_ERR_OR_NULL(c->root))
199672a44517SKent Overstreet 			goto err;
1997cafe5635SKent Overstreet 
19982a285686SKent Overstreet 		mutex_lock(&c->root->write_lock);
1999cafe5635SKent Overstreet 		bkey_copy_key(&c->root->key, &MAX_KEY);
2000c18536a7SKent Overstreet 		bch_btree_node_write(c->root, &cl);
20012a285686SKent Overstreet 		mutex_unlock(&c->root->write_lock);
2002cafe5635SKent Overstreet 
2003cafe5635SKent Overstreet 		bch_btree_set_root(c->root);
2004cafe5635SKent Overstreet 		rw_unlock(true, c->root);
2005cafe5635SKent Overstreet 
2006cafe5635SKent Overstreet 		/*
2007cafe5635SKent Overstreet 		 * We don't want to write the first journal entry until
2008cafe5635SKent Overstreet 		 * everything is set up - fortunately journal entries won't be
2009cafe5635SKent Overstreet 		 * written until the SET_CACHE_SYNC() here:
2010cafe5635SKent Overstreet 		 */
2011cafe5635SKent Overstreet 		SET_CACHE_SYNC(&c->sb, true);
2012cafe5635SKent Overstreet 
2013cafe5635SKent Overstreet 		bch_journal_next(&c->journal);
2014c18536a7SKent Overstreet 		bch_journal_meta(c, &cl);
2015cafe5635SKent Overstreet 	}
2016cafe5635SKent Overstreet 
201772a44517SKent Overstreet 	err = "error starting gc thread";
201872a44517SKent Overstreet 	if (bch_gc_thread_start(c))
201972a44517SKent Overstreet 		goto err;
202072a44517SKent Overstreet 
2021c18536a7SKent Overstreet 	closure_sync(&cl);
202275cbb3f1SArnd Bergmann 	c->sb.last_mount = (u32)ktime_get_real_seconds();
2023cafe5635SKent Overstreet 	bcache_write_super(c);
2024cafe5635SKent Overstreet 
2025cafe5635SKent Overstreet 	list_for_each_entry_safe(dc, t, &uncached_devices, list)
202673ac105bSTang Junhui 		bch_cached_dev_attach(dc, c, NULL);
2027cafe5635SKent Overstreet 
2028cafe5635SKent Overstreet 	flash_devs_run(c);
2029cafe5635SKent Overstreet 
2030bf0c55c9SSlava Pestov 	set_bit(CACHE_SET_RUNNING, &c->flags);
2031ce3e4cfbSColy Li 	return 0;
2032cafe5635SKent Overstreet err:
203395f18c9dSShenghui Wang 	while (!list_empty(&journal)) {
203495f18c9dSShenghui Wang 		l = list_first_entry(&journal, struct journal_replay, list);
203595f18c9dSShenghui Wang 		list_del(&l->list);
203695f18c9dSShenghui Wang 		kfree(l);
203795f18c9dSShenghui Wang 	}
203895f18c9dSShenghui Wang 
2039c18536a7SKent Overstreet 	closure_sync(&cl);
204068a53c95SColy Li 
2041c8694948SKees Cook 	bch_cache_set_error(c, "%s", err);
2042ce3e4cfbSColy Li 
2043ce3e4cfbSColy Li 	return -EIO;
2044cafe5635SKent Overstreet }
2045cafe5635SKent Overstreet 
2046cafe5635SKent Overstreet static bool can_attach_cache(struct cache *ca, struct cache_set *c)
2047cafe5635SKent Overstreet {
2048cafe5635SKent Overstreet 	return ca->sb.block_size	== c->sb.block_size &&
20499eb8ebebSNicholas Swenson 		ca->sb.bucket_size	== c->sb.bucket_size &&
2050cafe5635SKent Overstreet 		ca->sb.nr_in_set	== c->sb.nr_in_set;
2051cafe5635SKent Overstreet }
2052cafe5635SKent Overstreet 
2053cafe5635SKent Overstreet static const char *register_cache_set(struct cache *ca)
2054cafe5635SKent Overstreet {
2055cafe5635SKent Overstreet 	char buf[12];
2056cafe5635SKent Overstreet 	const char *err = "cannot allocate memory";
2057cafe5635SKent Overstreet 	struct cache_set *c;
2058cafe5635SKent Overstreet 
2059cafe5635SKent Overstreet 	list_for_each_entry(c, &bch_cache_sets, list)
2060cafe5635SKent Overstreet 		if (!memcmp(c->sb.set_uuid, ca->sb.set_uuid, 16)) {
2061cafe5635SKent Overstreet 			if (c->cache[ca->sb.nr_this_dev])
2062cafe5635SKent Overstreet 				return "duplicate cache set member";
2063cafe5635SKent Overstreet 
2064cafe5635SKent Overstreet 			if (!can_attach_cache(ca, c))
2065cafe5635SKent Overstreet 				return "cache sb does not match set";
2066cafe5635SKent Overstreet 
2067cafe5635SKent Overstreet 			if (!CACHE_SYNC(&ca->sb))
2068cafe5635SKent Overstreet 				SET_CACHE_SYNC(&c->sb, false);
2069cafe5635SKent Overstreet 
2070cafe5635SKent Overstreet 			goto found;
2071cafe5635SKent Overstreet 		}
2072cafe5635SKent Overstreet 
2073cafe5635SKent Overstreet 	c = bch_cache_set_alloc(&ca->sb);
2074cafe5635SKent Overstreet 	if (!c)
2075cafe5635SKent Overstreet 		return err;
2076cafe5635SKent Overstreet 
2077cafe5635SKent Overstreet 	err = "error creating kobject";
2078cafe5635SKent Overstreet 	if (kobject_add(&c->kobj, bcache_kobj, "%pU", c->sb.set_uuid) ||
2079cafe5635SKent Overstreet 	    kobject_add(&c->internal, &c->kobj, "internal"))
2080cafe5635SKent Overstreet 		goto err;
2081cafe5635SKent Overstreet 
2082cafe5635SKent Overstreet 	if (bch_cache_accounting_add_kobjs(&c->accounting, &c->kobj))
2083cafe5635SKent Overstreet 		goto err;
2084cafe5635SKent Overstreet 
2085cafe5635SKent Overstreet 	bch_debug_init_cache_set(c);
2086cafe5635SKent Overstreet 
2087cafe5635SKent Overstreet 	list_add(&c->list, &bch_cache_sets);
2088cafe5635SKent Overstreet found:
2089cafe5635SKent Overstreet 	sprintf(buf, "cache%i", ca->sb.nr_this_dev);
2090cafe5635SKent Overstreet 	if (sysfs_create_link(&ca->kobj, &c->kobj, "set") ||
2091cafe5635SKent Overstreet 	    sysfs_create_link(&c->kobj, &ca->kobj, buf))
2092cafe5635SKent Overstreet 		goto err;
2093cafe5635SKent Overstreet 
2094cafe5635SKent Overstreet 	if (ca->sb.seq > c->sb.seq) {
2095cafe5635SKent Overstreet 		c->sb.version		= ca->sb.version;
2096cafe5635SKent Overstreet 		memcpy(c->sb.set_uuid, ca->sb.set_uuid, 16);
2097cafe5635SKent Overstreet 		c->sb.flags             = ca->sb.flags;
2098cafe5635SKent Overstreet 		c->sb.seq		= ca->sb.seq;
2099cafe5635SKent Overstreet 		pr_debug("set version = %llu", c->sb.version);
2100cafe5635SKent Overstreet 	}
2101cafe5635SKent Overstreet 
2102d83353b3SKent Overstreet 	kobject_get(&ca->kobj);
2103cafe5635SKent Overstreet 	ca->set = c;
2104cafe5635SKent Overstreet 	ca->set->cache[ca->sb.nr_this_dev] = ca;
2105cafe5635SKent Overstreet 	c->cache_by_alloc[c->caches_loaded++] = ca;
2106cafe5635SKent Overstreet 
2107ce3e4cfbSColy Li 	if (c->caches_loaded == c->sb.nr_in_set) {
2108ce3e4cfbSColy Li 		err = "failed to run cache set";
2109ce3e4cfbSColy Li 		if (run_cache_set(c) < 0)
2110ce3e4cfbSColy Li 			goto err;
2111ce3e4cfbSColy Li 	}
2112cafe5635SKent Overstreet 
2113cafe5635SKent Overstreet 	return NULL;
2114cafe5635SKent Overstreet err:
2115cafe5635SKent Overstreet 	bch_cache_set_unregister(c);
2116cafe5635SKent Overstreet 	return err;
2117cafe5635SKent Overstreet }
2118cafe5635SKent Overstreet 
2119cafe5635SKent Overstreet /* Cache device */
2120cafe5635SKent Overstreet 
21212d17456eSColy Li /* When ca->kobj released */
2122cafe5635SKent Overstreet void bch_cache_release(struct kobject *kobj)
2123cafe5635SKent Overstreet {
2124cafe5635SKent Overstreet 	struct cache *ca = container_of(kobj, struct cache, kobj);
21256f10f7d1SColy Li 	unsigned int i;
2126cafe5635SKent Overstreet 
2127c9a78332SSlava Pestov 	if (ca->set) {
2128c9a78332SSlava Pestov 		BUG_ON(ca->set->cache[ca->sb.nr_this_dev] != ca);
2129cafe5635SKent Overstreet 		ca->set->cache[ca->sb.nr_this_dev] = NULL;
2130c9a78332SSlava Pestov 	}
2131cafe5635SKent Overstreet 
2132cafe5635SKent Overstreet 	free_pages((unsigned long) ca->disk_buckets, ilog2(bucket_pages(ca)));
2133cafe5635SKent Overstreet 	kfree(ca->prio_buckets);
2134cafe5635SKent Overstreet 	vfree(ca->buckets);
2135cafe5635SKent Overstreet 
2136cafe5635SKent Overstreet 	free_heap(&ca->heap);
2137cafe5635SKent Overstreet 	free_fifo(&ca->free_inc);
213878365411SKent Overstreet 
213978365411SKent Overstreet 	for (i = 0; i < RESERVE_NR; i++)
214078365411SKent Overstreet 		free_fifo(&ca->free[i]);
2141cafe5635SKent Overstreet 
2142cafe5635SKent Overstreet 	if (ca->sb_bio.bi_inline_vecs[0].bv_page)
2143263663cdSMing Lei 		put_page(bio_first_page_all(&ca->sb_bio));
2144cafe5635SKent Overstreet 
21450781c874SKent Overstreet 	if (!IS_ERR_OR_NULL(ca->bdev))
2146cafe5635SKent Overstreet 		blkdev_put(ca->bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2147cafe5635SKent Overstreet 
2148cafe5635SKent Overstreet 	kfree(ca);
2149cafe5635SKent Overstreet 	module_put(THIS_MODULE);
2150cafe5635SKent Overstreet }
2151cafe5635SKent Overstreet 
2152c50d4d5dSYijing Wang static int cache_alloc(struct cache *ca)
2153cafe5635SKent Overstreet {
2154cafe5635SKent Overstreet 	size_t free;
2155682811b3STang Junhui 	size_t btree_buckets;
2156cafe5635SKent Overstreet 	struct bucket *b;
2157f6027bcaSDongbo Cao 	int ret = -ENOMEM;
2158f6027bcaSDongbo Cao 	const char *err = NULL;
2159cafe5635SKent Overstreet 
2160cafe5635SKent Overstreet 	__module_get(THIS_MODULE);
2161cafe5635SKent Overstreet 	kobject_init(&ca->kobj, &bch_cache_ktype);
2162cafe5635SKent Overstreet 
21633a83f467SMing Lei 	bio_init(&ca->journal.bio, ca->journal.bio.bi_inline_vecs, 8);
2164cafe5635SKent Overstreet 
2165682811b3STang Junhui 	/*
2166682811b3STang Junhui 	 * when ca->sb.njournal_buckets is not zero, journal exists,
2167682811b3STang Junhui 	 * and in bch_journal_replay(), tree node may split,
2168682811b3STang Junhui 	 * so bucket of RESERVE_BTREE type is needed,
2169682811b3STang Junhui 	 * the worst situation is all journal buckets are valid journal,
2170682811b3STang Junhui 	 * and all the keys need to replay,
2171682811b3STang Junhui 	 * so the number of  RESERVE_BTREE type buckets should be as much
2172682811b3STang Junhui 	 * as journal buckets
2173682811b3STang Junhui 	 */
2174682811b3STang Junhui 	btree_buckets = ca->sb.njournal_buckets ?: 8;
217578365411SKent Overstreet 	free = roundup_pow_of_two(ca->sb.nbuckets) >> 10;
21763a646fd7SDongbo Cao 	if (!free) {
21773a646fd7SDongbo Cao 		ret = -EPERM;
21783a646fd7SDongbo Cao 		err = "ca->sb.nbuckets is too small";
21793a646fd7SDongbo Cao 		goto err_free;
21803a646fd7SDongbo Cao 	}
2181cafe5635SKent Overstreet 
2182f6027bcaSDongbo Cao 	if (!init_fifo(&ca->free[RESERVE_BTREE], btree_buckets,
2183f6027bcaSDongbo Cao 						GFP_KERNEL)) {
2184f6027bcaSDongbo Cao 		err = "ca->free[RESERVE_BTREE] alloc failed";
2185f6027bcaSDongbo Cao 		goto err_btree_alloc;
2186f6027bcaSDongbo Cao 	}
2187f6027bcaSDongbo Cao 
2188f6027bcaSDongbo Cao 	if (!init_fifo_exact(&ca->free[RESERVE_PRIO], prio_buckets(ca),
2189f6027bcaSDongbo Cao 							GFP_KERNEL)) {
2190f6027bcaSDongbo Cao 		err = "ca->free[RESERVE_PRIO] alloc failed";
2191f6027bcaSDongbo Cao 		goto err_prio_alloc;
2192f6027bcaSDongbo Cao 	}
2193f6027bcaSDongbo Cao 
2194f6027bcaSDongbo Cao 	if (!init_fifo(&ca->free[RESERVE_MOVINGGC], free, GFP_KERNEL)) {
2195f6027bcaSDongbo Cao 		err = "ca->free[RESERVE_MOVINGGC] alloc failed";
2196f6027bcaSDongbo Cao 		goto err_movinggc_alloc;
2197f6027bcaSDongbo Cao 	}
2198f6027bcaSDongbo Cao 
2199f6027bcaSDongbo Cao 	if (!init_fifo(&ca->free[RESERVE_NONE], free, GFP_KERNEL)) {
2200f6027bcaSDongbo Cao 		err = "ca->free[RESERVE_NONE] alloc failed";
2201f6027bcaSDongbo Cao 		goto err_none_alloc;
2202f6027bcaSDongbo Cao 	}
2203f6027bcaSDongbo Cao 
2204f6027bcaSDongbo Cao 	if (!init_fifo(&ca->free_inc, free << 2, GFP_KERNEL)) {
2205f6027bcaSDongbo Cao 		err = "ca->free_inc alloc failed";
2206f6027bcaSDongbo Cao 		goto err_free_inc_alloc;
2207f6027bcaSDongbo Cao 	}
2208f6027bcaSDongbo Cao 
2209f6027bcaSDongbo Cao 	if (!init_heap(&ca->heap, free << 3, GFP_KERNEL)) {
2210f6027bcaSDongbo Cao 		err = "ca->heap alloc failed";
2211f6027bcaSDongbo Cao 		goto err_heap_alloc;
2212f6027bcaSDongbo Cao 	}
2213f6027bcaSDongbo Cao 
2214f6027bcaSDongbo Cao 	ca->buckets = vzalloc(array_size(sizeof(struct bucket),
2215f6027bcaSDongbo Cao 			      ca->sb.nbuckets));
2216f6027bcaSDongbo Cao 	if (!ca->buckets) {
2217f6027bcaSDongbo Cao 		err = "ca->buckets alloc failed";
2218f6027bcaSDongbo Cao 		goto err_buckets_alloc;
2219f6027bcaSDongbo Cao 	}
2220f6027bcaSDongbo Cao 
2221f6027bcaSDongbo Cao 	ca->prio_buckets = kzalloc(array3_size(sizeof(uint64_t),
22226396bb22SKees Cook 				   prio_buckets(ca), 2),
2223f6027bcaSDongbo Cao 				   GFP_KERNEL);
2224f6027bcaSDongbo Cao 	if (!ca->prio_buckets) {
2225f6027bcaSDongbo Cao 		err = "ca->prio_buckets alloc failed";
2226f6027bcaSDongbo Cao 		goto err_prio_buckets_alloc;
2227f6027bcaSDongbo Cao 	}
2228f6027bcaSDongbo Cao 
2229f6027bcaSDongbo Cao 	ca->disk_buckets = alloc_bucket_pages(GFP_KERNEL, ca);
2230f6027bcaSDongbo Cao 	if (!ca->disk_buckets) {
2231f6027bcaSDongbo Cao 		err = "ca->disk_buckets alloc failed";
2232f6027bcaSDongbo Cao 		goto err_disk_buckets_alloc;
2233f6027bcaSDongbo Cao 	}
2234cafe5635SKent Overstreet 
2235cafe5635SKent Overstreet 	ca->prio_last_buckets = ca->prio_buckets + prio_buckets(ca);
2236cafe5635SKent Overstreet 
2237cafe5635SKent Overstreet 	for_each_bucket(b, ca)
2238cafe5635SKent Overstreet 		atomic_set(&b->pin, 0);
2239cafe5635SKent Overstreet 	return 0;
2240f6027bcaSDongbo Cao 
2241f6027bcaSDongbo Cao err_disk_buckets_alloc:
2242f6027bcaSDongbo Cao 	kfree(ca->prio_buckets);
2243f6027bcaSDongbo Cao err_prio_buckets_alloc:
2244f6027bcaSDongbo Cao 	vfree(ca->buckets);
2245f6027bcaSDongbo Cao err_buckets_alloc:
2246f6027bcaSDongbo Cao 	free_heap(&ca->heap);
2247f6027bcaSDongbo Cao err_heap_alloc:
2248f6027bcaSDongbo Cao 	free_fifo(&ca->free_inc);
2249f6027bcaSDongbo Cao err_free_inc_alloc:
2250f6027bcaSDongbo Cao 	free_fifo(&ca->free[RESERVE_NONE]);
2251f6027bcaSDongbo Cao err_none_alloc:
2252f6027bcaSDongbo Cao 	free_fifo(&ca->free[RESERVE_MOVINGGC]);
2253f6027bcaSDongbo Cao err_movinggc_alloc:
2254f6027bcaSDongbo Cao 	free_fifo(&ca->free[RESERVE_PRIO]);
2255f6027bcaSDongbo Cao err_prio_alloc:
2256f6027bcaSDongbo Cao 	free_fifo(&ca->free[RESERVE_BTREE]);
2257f6027bcaSDongbo Cao err_btree_alloc:
22583a646fd7SDongbo Cao err_free:
2259f6027bcaSDongbo Cao 	module_put(THIS_MODULE);
2260f6027bcaSDongbo Cao 	if (err)
2261f6027bcaSDongbo Cao 		pr_notice("error %s: %s", ca->cache_dev_name, err);
2262f6027bcaSDongbo Cao 	return ret;
2263cafe5635SKent Overstreet }
2264cafe5635SKent Overstreet 
22659b299728SEric Wheeler static int register_cache(struct cache_sb *sb, struct page *sb_page,
2266cafe5635SKent Overstreet 				struct block_device *bdev, struct cache *ca)
2267cafe5635SKent Overstreet {
2268d9dc1702SEric Wheeler 	const char *err = NULL; /* must be set for any error case */
22699b299728SEric Wheeler 	int ret = 0;
2270cafe5635SKent Overstreet 
22716e916a7eSColy Li 	bdevname(bdev, ca->cache_dev_name);
2272f59fce84SKent Overstreet 	memcpy(&ca->sb, sb, sizeof(struct cache_sb));
2273cafe5635SKent Overstreet 	ca->bdev = bdev;
2274cafe5635SKent Overstreet 	ca->bdev->bd_holder = ca;
2275cafe5635SKent Overstreet 
22763a83f467SMing Lei 	bio_init(&ca->sb_bio, ca->sb_bio.bi_inline_vecs, 1);
2277263663cdSMing Lei 	bio_first_bvec_all(&ca->sb_bio)->bv_page = sb_page;
2278f59fce84SKent Overstreet 	get_page(sb_page);
2279f59fce84SKent Overstreet 
2280cc40daf9STang Junhui 	if (blk_queue_discard(bdev_get_queue(bdev)))
2281cafe5635SKent Overstreet 		ca->discard = CACHE_DISCARD(&ca->sb);
2282cafe5635SKent Overstreet 
2283c50d4d5dSYijing Wang 	ret = cache_alloc(ca);
2284d9dc1702SEric Wheeler 	if (ret != 0) {
2285bb6d355cSColy Li 		/*
2286bb6d355cSColy Li 		 * If we failed here, it means ca->kobj is not initialized yet,
2287bb6d355cSColy Li 		 * kobject_put() won't be called and there is no chance to
2288bb6d355cSColy Li 		 * call blkdev_put() to bdev in bch_cache_release(). So we
2289bb6d355cSColy Li 		 * explicitly call blkdev_put() here.
2290bb6d355cSColy Li 		 */
2291cc40daf9STang Junhui 		blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2292d9dc1702SEric Wheeler 		if (ret == -ENOMEM)
2293d9dc1702SEric Wheeler 			err = "cache_alloc(): -ENOMEM";
22943a646fd7SDongbo Cao 		else if (ret == -EPERM)
22953a646fd7SDongbo Cao 			err = "cache_alloc(): cache device is too small";
2296d9dc1702SEric Wheeler 		else
2297d9dc1702SEric Wheeler 			err = "cache_alloc(): unknown error";
2298f59fce84SKent Overstreet 		goto err;
2299d9dc1702SEric Wheeler 	}
2300f59fce84SKent Overstreet 
2301b0d30981SColy Li 	if (kobject_add(&ca->kobj,
2302b0d30981SColy Li 			&part_to_dev(bdev->bd_part)->kobj,
2303b0d30981SColy Li 			"bcache")) {
23049b299728SEric Wheeler 		err = "error calling kobject_add";
23059b299728SEric Wheeler 		ret = -ENOMEM;
23069b299728SEric Wheeler 		goto out;
23079b299728SEric Wheeler 	}
2308cafe5635SKent Overstreet 
23094fa03402SKent Overstreet 	mutex_lock(&bch_register_lock);
2310cafe5635SKent Overstreet 	err = register_cache_set(ca);
23114fa03402SKent Overstreet 	mutex_unlock(&bch_register_lock);
23124fa03402SKent Overstreet 
23139b299728SEric Wheeler 	if (err) {
23149b299728SEric Wheeler 		ret = -ENODEV;
23159b299728SEric Wheeler 		goto out;
23169b299728SEric Wheeler 	}
2317cafe5635SKent Overstreet 
23186e916a7eSColy Li 	pr_info("registered cache device %s", ca->cache_dev_name);
23199b299728SEric Wheeler 
2320d83353b3SKent Overstreet out:
2321d83353b3SKent Overstreet 	kobject_put(&ca->kobj);
23229b299728SEric Wheeler 
2323cafe5635SKent Overstreet err:
23249b299728SEric Wheeler 	if (err)
23256e916a7eSColy Li 		pr_notice("error %s: %s", ca->cache_dev_name, err);
23269b299728SEric Wheeler 
23279b299728SEric Wheeler 	return ret;
2328cafe5635SKent Overstreet }
2329cafe5635SKent Overstreet 
2330cafe5635SKent Overstreet /* Global interfaces/init */
2331cafe5635SKent Overstreet 
2332fc2d5988SColy Li static ssize_t register_bcache(struct kobject *k, struct kobj_attribute *attr,
2333fc2d5988SColy Li 			       const char *buffer, size_t size);
23340c277e21SColy Li static ssize_t bch_pending_bdevs_cleanup(struct kobject *k,
23350c277e21SColy Li 					 struct kobj_attribute *attr,
23360c277e21SColy Li 					 const char *buffer, size_t size);
2337cafe5635SKent Overstreet 
2338cafe5635SKent Overstreet kobj_attribute_write(register,		register_bcache);
2339cafe5635SKent Overstreet kobj_attribute_write(register_quiet,	register_bcache);
23400c277e21SColy Li kobj_attribute_write(pendings_cleanup,	bch_pending_bdevs_cleanup);
2341cafe5635SKent Overstreet 
2342b3cf37bfSColy Li static bool bch_is_open_backing(struct block_device *bdev)
2343b3cf37bfSColy Li {
2344a9dd53adSGabriel de Perthuis 	struct cache_set *c, *tc;
2345a9dd53adSGabriel de Perthuis 	struct cached_dev *dc, *t;
2346a9dd53adSGabriel de Perthuis 
2347a9dd53adSGabriel de Perthuis 	list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
2348a9dd53adSGabriel de Perthuis 		list_for_each_entry_safe(dc, t, &c->cached_devs, list)
2349a9dd53adSGabriel de Perthuis 			if (dc->bdev == bdev)
2350a9dd53adSGabriel de Perthuis 				return true;
2351a9dd53adSGabriel de Perthuis 	list_for_each_entry_safe(dc, t, &uncached_devices, list)
2352a9dd53adSGabriel de Perthuis 		if (dc->bdev == bdev)
2353a9dd53adSGabriel de Perthuis 			return true;
2354a9dd53adSGabriel de Perthuis 	return false;
2355a9dd53adSGabriel de Perthuis }
2356a9dd53adSGabriel de Perthuis 
2357b3cf37bfSColy Li static bool bch_is_open_cache(struct block_device *bdev)
2358b3cf37bfSColy Li {
2359a9dd53adSGabriel de Perthuis 	struct cache_set *c, *tc;
2360a9dd53adSGabriel de Perthuis 	struct cache *ca;
23616f10f7d1SColy Li 	unsigned int i;
2362a9dd53adSGabriel de Perthuis 
2363a9dd53adSGabriel de Perthuis 	list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
2364a9dd53adSGabriel de Perthuis 		for_each_cache(ca, c, i)
2365a9dd53adSGabriel de Perthuis 			if (ca->bdev == bdev)
2366a9dd53adSGabriel de Perthuis 				return true;
2367a9dd53adSGabriel de Perthuis 	return false;
2368a9dd53adSGabriel de Perthuis }
2369a9dd53adSGabriel de Perthuis 
2370b3cf37bfSColy Li static bool bch_is_open(struct block_device *bdev)
2371b3cf37bfSColy Li {
2372a9dd53adSGabriel de Perthuis 	return bch_is_open_cache(bdev) || bch_is_open_backing(bdev);
2373a9dd53adSGabriel de Perthuis }
2374a9dd53adSGabriel de Perthuis 
2375cafe5635SKent Overstreet static ssize_t register_bcache(struct kobject *k, struct kobj_attribute *attr,
2376cafe5635SKent Overstreet 			       const char *buffer, size_t size)
2377cafe5635SKent Overstreet {
237888c12d42SColy Li 	ssize_t ret = -EINVAL;
2379cafe5635SKent Overstreet 	const char *err = "cannot allocate memory";
2380cafe5635SKent Overstreet 	char *path = NULL;
2381cafe5635SKent Overstreet 	struct cache_sb *sb = NULL;
2382cafe5635SKent Overstreet 	struct block_device *bdev = NULL;
2383cafe5635SKent Overstreet 	struct page *sb_page = NULL;
2384cafe5635SKent Overstreet 
2385cafe5635SKent Overstreet 	if (!try_module_get(THIS_MODULE))
2386cafe5635SKent Overstreet 		return -EBUSY;
2387cafe5635SKent Overstreet 
2388a59ff6ccSColy Li 	/* For latest state of bcache_is_reboot */
2389a59ff6ccSColy Li 	smp_mb();
2390a59ff6ccSColy Li 	if (bcache_is_reboot)
2391a59ff6ccSColy Li 		return -EBUSY;
2392a59ff6ccSColy Li 
2393a56489d4SFlorian Schmaus 	path = kstrndup(buffer, size, GFP_KERNEL);
2394a56489d4SFlorian Schmaus 	if (!path)
2395a56489d4SFlorian Schmaus 		goto err;
2396a56489d4SFlorian Schmaus 
2397a56489d4SFlorian Schmaus 	sb = kmalloc(sizeof(struct cache_sb), GFP_KERNEL);
2398a56489d4SFlorian Schmaus 	if (!sb)
2399cafe5635SKent Overstreet 		goto err;
2400cafe5635SKent Overstreet 
2401cafe5635SKent Overstreet 	err = "failed to open device";
2402cafe5635SKent Overstreet 	bdev = blkdev_get_by_path(strim(path),
2403cafe5635SKent Overstreet 				  FMODE_READ|FMODE_WRITE|FMODE_EXCL,
2404cafe5635SKent Overstreet 				  sb);
2405f59fce84SKent Overstreet 	if (IS_ERR(bdev)) {
2406a9dd53adSGabriel de Perthuis 		if (bdev == ERR_PTR(-EBUSY)) {
2407a9dd53adSGabriel de Perthuis 			bdev = lookup_bdev(strim(path));
2408789d21dbSJianjian Huo 			mutex_lock(&bch_register_lock);
2409a9dd53adSGabriel de Perthuis 			if (!IS_ERR(bdev) && bch_is_open(bdev))
2410a9dd53adSGabriel de Perthuis 				err = "device already registered";
2411a9dd53adSGabriel de Perthuis 			else
2412cafe5635SKent Overstreet 				err = "device busy";
2413789d21dbSJianjian Huo 			mutex_unlock(&bch_register_lock);
24144b758df2SJan Kara 			if (!IS_ERR(bdev))
24154b758df2SJan Kara 				bdput(bdev);
2416d7076f21SGabriel de Perthuis 			if (attr == &ksysfs_register_quiet)
241788c12d42SColy Li 				goto quiet_out;
2418a9dd53adSGabriel de Perthuis 		}
2419cafe5635SKent Overstreet 		goto err;
2420f59fce84SKent Overstreet 	}
2421f59fce84SKent Overstreet 
2422f59fce84SKent Overstreet 	err = "failed to set blocksize";
2423f59fce84SKent Overstreet 	if (set_blocksize(bdev, 4096))
2424f59fce84SKent Overstreet 		goto err_close;
2425cafe5635SKent Overstreet 
2426cafe5635SKent Overstreet 	err = read_super(sb, bdev, &sb_page);
2427cafe5635SKent Overstreet 	if (err)
2428cafe5635SKent Overstreet 		goto err_close;
2429cafe5635SKent Overstreet 
2430cc40daf9STang Junhui 	err = "failed to register device";
24312903381fSKent Overstreet 	if (SB_IS_BDEV(sb)) {
2432cafe5635SKent Overstreet 		struct cached_dev *dc = kzalloc(sizeof(*dc), GFP_KERNEL);
24331fae7cf0SColy Li 
2434f59fce84SKent Overstreet 		if (!dc)
2435f59fce84SKent Overstreet 			goto err_close;
2436cafe5635SKent Overstreet 
24374fa03402SKent Overstreet 		mutex_lock(&bch_register_lock);
243888c12d42SColy Li 		ret = register_bdev(sb, sb_page, bdev, dc);
24394fa03402SKent Overstreet 		mutex_unlock(&bch_register_lock);
2440bb6d355cSColy Li 		/* blkdev_put() will be called in cached_dev_free() */
244188c12d42SColy Li 		if (ret < 0)
244288c12d42SColy Li 			goto err;
2443cafe5635SKent Overstreet 	} else {
2444cafe5635SKent Overstreet 		struct cache *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
24451fae7cf0SColy Li 
2446f59fce84SKent Overstreet 		if (!ca)
2447f59fce84SKent Overstreet 			goto err_close;
2448cafe5635SKent Overstreet 
2449bb6d355cSColy Li 		/* blkdev_put() will be called in bch_cache_release() */
24509b299728SEric Wheeler 		if (register_cache(sb, sb_page, bdev, ca) != 0)
2451cc40daf9STang Junhui 			goto err;
2452cafe5635SKent Overstreet 	}
245388c12d42SColy Li quiet_out:
245488c12d42SColy Li 	ret = size;
2455f59fce84SKent Overstreet out:
2456f59fce84SKent Overstreet 	if (sb_page)
2457cafe5635SKent Overstreet 		put_page(sb_page);
2458f59fce84SKent Overstreet 	kfree(sb);
2459f59fce84SKent Overstreet 	kfree(path);
2460f59fce84SKent Overstreet 	module_put(THIS_MODULE);
2461f59fce84SKent Overstreet 	return ret;
2462f59fce84SKent Overstreet 
2463cafe5635SKent Overstreet err_close:
2464cafe5635SKent Overstreet 	blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2465cafe5635SKent Overstreet err:
2466cc40daf9STang Junhui 	pr_info("error %s: %s", path, err);
2467f59fce84SKent Overstreet 	goto out;
2468cafe5635SKent Overstreet }
2469cafe5635SKent Overstreet 
24700c277e21SColy Li 
24710c277e21SColy Li struct pdev {
24720c277e21SColy Li 	struct list_head list;
24730c277e21SColy Li 	struct cached_dev *dc;
24740c277e21SColy Li };
24750c277e21SColy Li 
24760c277e21SColy Li static ssize_t bch_pending_bdevs_cleanup(struct kobject *k,
24770c277e21SColy Li 					 struct kobj_attribute *attr,
24780c277e21SColy Li 					 const char *buffer,
24790c277e21SColy Li 					 size_t size)
24800c277e21SColy Li {
24810c277e21SColy Li 	LIST_HEAD(pending_devs);
24820c277e21SColy Li 	ssize_t ret = size;
24830c277e21SColy Li 	struct cached_dev *dc, *tdc;
24840c277e21SColy Li 	struct pdev *pdev, *tpdev;
24850c277e21SColy Li 	struct cache_set *c, *tc;
24860c277e21SColy Li 
24870c277e21SColy Li 	mutex_lock(&bch_register_lock);
24880c277e21SColy Li 	list_for_each_entry_safe(dc, tdc, &uncached_devices, list) {
24890c277e21SColy Li 		pdev = kmalloc(sizeof(struct pdev), GFP_KERNEL);
24900c277e21SColy Li 		if (!pdev)
24910c277e21SColy Li 			break;
24920c277e21SColy Li 		pdev->dc = dc;
24930c277e21SColy Li 		list_add(&pdev->list, &pending_devs);
24940c277e21SColy Li 	}
24950c277e21SColy Li 
24960c277e21SColy Li 	list_for_each_entry_safe(pdev, tpdev, &pending_devs, list) {
24970c277e21SColy Li 		list_for_each_entry_safe(c, tc, &bch_cache_sets, list) {
24980c277e21SColy Li 			char *pdev_set_uuid = pdev->dc->sb.set_uuid;
24990c277e21SColy Li 			char *set_uuid = c->sb.uuid;
25000c277e21SColy Li 
25010c277e21SColy Li 			if (!memcmp(pdev_set_uuid, set_uuid, 16)) {
25020c277e21SColy Li 				list_del(&pdev->list);
25030c277e21SColy Li 				kfree(pdev);
25040c277e21SColy Li 				break;
25050c277e21SColy Li 			}
25060c277e21SColy Li 		}
25070c277e21SColy Li 	}
25080c277e21SColy Li 	mutex_unlock(&bch_register_lock);
25090c277e21SColy Li 
25100c277e21SColy Li 	list_for_each_entry_safe(pdev, tpdev, &pending_devs, list) {
25110c277e21SColy Li 		pr_info("delete pdev %p", pdev);
25120c277e21SColy Li 		list_del(&pdev->list);
25130c277e21SColy Li 		bcache_device_stop(&pdev->dc->disk);
25140c277e21SColy Li 		kfree(pdev);
25150c277e21SColy Li 	}
25160c277e21SColy Li 
25170c277e21SColy Li 	return ret;
25180c277e21SColy Li }
25190c277e21SColy Li 
2520cafe5635SKent Overstreet static int bcache_reboot(struct notifier_block *n, unsigned long code, void *x)
2521cafe5635SKent Overstreet {
2522a59ff6ccSColy Li 	if (bcache_is_reboot)
2523a59ff6ccSColy Li 		return NOTIFY_DONE;
2524a59ff6ccSColy Li 
2525cafe5635SKent Overstreet 	if (code == SYS_DOWN ||
2526cafe5635SKent Overstreet 	    code == SYS_HALT ||
2527cafe5635SKent Overstreet 	    code == SYS_POWER_OFF) {
2528cafe5635SKent Overstreet 		DEFINE_WAIT(wait);
2529cafe5635SKent Overstreet 		unsigned long start = jiffies;
2530cafe5635SKent Overstreet 		bool stopped = false;
2531cafe5635SKent Overstreet 
2532cafe5635SKent Overstreet 		struct cache_set *c, *tc;
2533cafe5635SKent Overstreet 		struct cached_dev *dc, *tdc;
2534cafe5635SKent Overstreet 
2535cafe5635SKent Overstreet 		mutex_lock(&bch_register_lock);
2536cafe5635SKent Overstreet 
2537a59ff6ccSColy Li 		if (bcache_is_reboot)
2538a59ff6ccSColy Li 			goto out;
2539a59ff6ccSColy Li 
2540a59ff6ccSColy Li 		/* New registration is rejected since now */
2541a59ff6ccSColy Li 		bcache_is_reboot = true;
2542a59ff6ccSColy Li 		/*
2543a59ff6ccSColy Li 		 * Make registering caller (if there is) on other CPU
2544a59ff6ccSColy Li 		 * core know bcache_is_reboot set to true earlier
2545a59ff6ccSColy Li 		 */
2546a59ff6ccSColy Li 		smp_mb();
2547a59ff6ccSColy Li 
2548cafe5635SKent Overstreet 		if (list_empty(&bch_cache_sets) &&
2549cafe5635SKent Overstreet 		    list_empty(&uncached_devices))
2550cafe5635SKent Overstreet 			goto out;
2551cafe5635SKent Overstreet 
2552a59ff6ccSColy Li 		mutex_unlock(&bch_register_lock);
2553a59ff6ccSColy Li 
2554cafe5635SKent Overstreet 		pr_info("Stopping all devices:");
2555cafe5635SKent Overstreet 
2556a59ff6ccSColy Li 		/*
2557a59ff6ccSColy Li 		 * The reason bch_register_lock is not held to call
2558a59ff6ccSColy Li 		 * bch_cache_set_stop() and bcache_device_stop() is to
2559a59ff6ccSColy Li 		 * avoid potential deadlock during reboot, because cache
2560a59ff6ccSColy Li 		 * set or bcache device stopping process will acqurie
2561a59ff6ccSColy Li 		 * bch_register_lock too.
2562a59ff6ccSColy Li 		 *
2563a59ff6ccSColy Li 		 * We are safe here because bcache_is_reboot sets to
2564a59ff6ccSColy Li 		 * true already, register_bcache() will reject new
2565a59ff6ccSColy Li 		 * registration now. bcache_is_reboot also makes sure
2566a59ff6ccSColy Li 		 * bcache_reboot() won't be re-entered on by other thread,
2567a59ff6ccSColy Li 		 * so there is no race in following list iteration by
2568a59ff6ccSColy Li 		 * list_for_each_entry_safe().
2569a59ff6ccSColy Li 		 */
2570cafe5635SKent Overstreet 		list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
2571cafe5635SKent Overstreet 			bch_cache_set_stop(c);
2572cafe5635SKent Overstreet 
2573cafe5635SKent Overstreet 		list_for_each_entry_safe(dc, tdc, &uncached_devices, list)
2574cafe5635SKent Overstreet 			bcache_device_stop(&dc->disk);
2575cafe5635SKent Overstreet 
2576eb8cbb6dSColy Li 
2577eb8cbb6dSColy Li 		/*
2578eb8cbb6dSColy Li 		 * Give an early chance for other kthreads and
2579eb8cbb6dSColy Li 		 * kworkers to stop themselves
2580eb8cbb6dSColy Li 		 */
2581eb8cbb6dSColy Li 		schedule();
2582eb8cbb6dSColy Li 
2583cafe5635SKent Overstreet 		/* What's a condition variable? */
2584cafe5635SKent Overstreet 		while (1) {
2585eb8cbb6dSColy Li 			long timeout = start + 10 * HZ - jiffies;
2586cafe5635SKent Overstreet 
2587eb8cbb6dSColy Li 			mutex_lock(&bch_register_lock);
2588cafe5635SKent Overstreet 			stopped = list_empty(&bch_cache_sets) &&
2589cafe5635SKent Overstreet 				list_empty(&uncached_devices);
2590cafe5635SKent Overstreet 
2591cafe5635SKent Overstreet 			if (timeout < 0 || stopped)
2592cafe5635SKent Overstreet 				break;
2593cafe5635SKent Overstreet 
2594cafe5635SKent Overstreet 			prepare_to_wait(&unregister_wait, &wait,
2595cafe5635SKent Overstreet 					TASK_UNINTERRUPTIBLE);
2596cafe5635SKent Overstreet 
2597cafe5635SKent Overstreet 			mutex_unlock(&bch_register_lock);
2598cafe5635SKent Overstreet 			schedule_timeout(timeout);
2599cafe5635SKent Overstreet 		}
2600cafe5635SKent Overstreet 
2601cafe5635SKent Overstreet 		finish_wait(&unregister_wait, &wait);
2602cafe5635SKent Overstreet 
2603cafe5635SKent Overstreet 		if (stopped)
2604cafe5635SKent Overstreet 			pr_info("All devices stopped");
2605cafe5635SKent Overstreet 		else
2606cafe5635SKent Overstreet 			pr_notice("Timeout waiting for devices to be closed");
2607cafe5635SKent Overstreet out:
2608cafe5635SKent Overstreet 		mutex_unlock(&bch_register_lock);
2609cafe5635SKent Overstreet 	}
2610cafe5635SKent Overstreet 
2611cafe5635SKent Overstreet 	return NOTIFY_DONE;
2612cafe5635SKent Overstreet }
2613cafe5635SKent Overstreet 
2614cafe5635SKent Overstreet static struct notifier_block reboot = {
2615cafe5635SKent Overstreet 	.notifier_call	= bcache_reboot,
2616cafe5635SKent Overstreet 	.priority	= INT_MAX, /* before any real devices */
2617cafe5635SKent Overstreet };
2618cafe5635SKent Overstreet 
2619cafe5635SKent Overstreet static void bcache_exit(void)
2620cafe5635SKent Overstreet {
2621cafe5635SKent Overstreet 	bch_debug_exit();
2622cafe5635SKent Overstreet 	bch_request_exit();
2623cafe5635SKent Overstreet 	if (bcache_kobj)
2624cafe5635SKent Overstreet 		kobject_put(bcache_kobj);
2625cafe5635SKent Overstreet 	if (bcache_wq)
2626cafe5635SKent Overstreet 		destroy_workqueue(bcache_wq);
26270f843e65SGuoju Fang 	if (bch_journal_wq)
26280f843e65SGuoju Fang 		destroy_workqueue(bch_journal_wq);
26290f843e65SGuoju Fang 
26305c41c8a7SKent Overstreet 	if (bcache_major)
2631cafe5635SKent Overstreet 		unregister_blkdev(bcache_major, "bcache");
2632cafe5635SKent Overstreet 	unregister_reboot_notifier(&reboot);
2633330a4db8SLiang Chen 	mutex_destroy(&bch_register_lock);
2634cafe5635SKent Overstreet }
2635cafe5635SKent Overstreet 
26369aaf5165SColy Li /* Check and fixup module parameters */
26379aaf5165SColy Li static void check_module_parameters(void)
26389aaf5165SColy Li {
26399aaf5165SColy Li 	if (bch_cutoff_writeback_sync == 0)
26409aaf5165SColy Li 		bch_cutoff_writeback_sync = CUTOFF_WRITEBACK_SYNC;
26419aaf5165SColy Li 	else if (bch_cutoff_writeback_sync > CUTOFF_WRITEBACK_SYNC_MAX) {
26429aaf5165SColy Li 		pr_warn("set bch_cutoff_writeback_sync (%u) to max value %u",
26439aaf5165SColy Li 			bch_cutoff_writeback_sync, CUTOFF_WRITEBACK_SYNC_MAX);
26449aaf5165SColy Li 		bch_cutoff_writeback_sync = CUTOFF_WRITEBACK_SYNC_MAX;
26459aaf5165SColy Li 	}
26469aaf5165SColy Li 
26479aaf5165SColy Li 	if (bch_cutoff_writeback == 0)
26489aaf5165SColy Li 		bch_cutoff_writeback = CUTOFF_WRITEBACK;
26499aaf5165SColy Li 	else if (bch_cutoff_writeback > CUTOFF_WRITEBACK_MAX) {
26509aaf5165SColy Li 		pr_warn("set bch_cutoff_writeback (%u) to max value %u",
26519aaf5165SColy Li 			bch_cutoff_writeback, CUTOFF_WRITEBACK_MAX);
26529aaf5165SColy Li 		bch_cutoff_writeback = CUTOFF_WRITEBACK_MAX;
26539aaf5165SColy Li 	}
26549aaf5165SColy Li 
26559aaf5165SColy Li 	if (bch_cutoff_writeback > bch_cutoff_writeback_sync) {
26569aaf5165SColy Li 		pr_warn("set bch_cutoff_writeback (%u) to %u",
26579aaf5165SColy Li 			bch_cutoff_writeback, bch_cutoff_writeback_sync);
26589aaf5165SColy Li 		bch_cutoff_writeback = bch_cutoff_writeback_sync;
26599aaf5165SColy Li 	}
26609aaf5165SColy Li }
26619aaf5165SColy Li 
2662cafe5635SKent Overstreet static int __init bcache_init(void)
2663cafe5635SKent Overstreet {
2664cafe5635SKent Overstreet 	static const struct attribute *files[] = {
2665cafe5635SKent Overstreet 		&ksysfs_register.attr,
2666cafe5635SKent Overstreet 		&ksysfs_register_quiet.attr,
26670c277e21SColy Li 		&ksysfs_pendings_cleanup.attr,
2668cafe5635SKent Overstreet 		NULL
2669cafe5635SKent Overstreet 	};
2670cafe5635SKent Overstreet 
26719aaf5165SColy Li 	check_module_parameters();
26729aaf5165SColy Li 
2673cafe5635SKent Overstreet 	mutex_init(&bch_register_lock);
2674cafe5635SKent Overstreet 	init_waitqueue_head(&unregister_wait);
2675cafe5635SKent Overstreet 	register_reboot_notifier(&reboot);
2676cafe5635SKent Overstreet 
2677cafe5635SKent Overstreet 	bcache_major = register_blkdev(0, "bcache");
26782ecf0cdbSZheng Liu 	if (bcache_major < 0) {
26792ecf0cdbSZheng Liu 		unregister_reboot_notifier(&reboot);
2680330a4db8SLiang Chen 		mutex_destroy(&bch_register_lock);
2681cafe5635SKent Overstreet 		return bcache_major;
26822ecf0cdbSZheng Liu 	}
2683cafe5635SKent Overstreet 
268416c1fdf4SFlorian Schmaus 	bcache_wq = alloc_workqueue("bcache", WQ_MEM_RECLAIM, 0);
268516c1fdf4SFlorian Schmaus 	if (!bcache_wq)
268616c1fdf4SFlorian Schmaus 		goto err;
268716c1fdf4SFlorian Schmaus 
26880f843e65SGuoju Fang 	bch_journal_wq = alloc_workqueue("bch_journal", WQ_MEM_RECLAIM, 0);
26890f843e65SGuoju Fang 	if (!bch_journal_wq)
26900f843e65SGuoju Fang 		goto err;
26910f843e65SGuoju Fang 
269216c1fdf4SFlorian Schmaus 	bcache_kobj = kobject_create_and_add("bcache", fs_kobj);
269316c1fdf4SFlorian Schmaus 	if (!bcache_kobj)
269416c1fdf4SFlorian Schmaus 		goto err;
269516c1fdf4SFlorian Schmaus 
269616c1fdf4SFlorian Schmaus 	if (bch_request_init() ||
2697330a4db8SLiang Chen 	    sysfs_create_files(bcache_kobj, files))
2698cafe5635SKent Overstreet 		goto err;
2699cafe5635SKent Overstreet 
270091bafdf0SDongbo Cao 	bch_debug_init();
270178ac2107SColy Li 	closure_debug_init();
270278ac2107SColy Li 
2703a59ff6ccSColy Li 	bcache_is_reboot = false;
2704a59ff6ccSColy Li 
2705cafe5635SKent Overstreet 	return 0;
2706cafe5635SKent Overstreet err:
2707cafe5635SKent Overstreet 	bcache_exit();
2708cafe5635SKent Overstreet 	return -ENOMEM;
2709cafe5635SKent Overstreet }
2710cafe5635SKent Overstreet 
27119aaf5165SColy Li /*
27129aaf5165SColy Li  * Module hooks
27139aaf5165SColy Li  */
2714cafe5635SKent Overstreet module_exit(bcache_exit);
2715cafe5635SKent Overstreet module_init(bcache_init);
2716009673d0SColy Li 
27179aaf5165SColy Li module_param(bch_cutoff_writeback, uint, 0);
27189aaf5165SColy Li MODULE_PARM_DESC(bch_cutoff_writeback, "threshold to cutoff writeback");
27199aaf5165SColy Li 
27209aaf5165SColy Li module_param(bch_cutoff_writeback_sync, uint, 0);
27219aaf5165SColy Li MODULE_PARM_DESC(bch_cutoff_writeback_sync, "hard threshold to cutoff writeback");
27229aaf5165SColy Li 
2723009673d0SColy Li MODULE_DESCRIPTION("Bcache: a Linux block layer cache");
2724009673d0SColy Li MODULE_AUTHOR("Kent Overstreet <kent.overstreet@gmail.com>");
2725009673d0SColy Li MODULE_LICENSE("GPL");
2726