xref: /openbmc/linux/drivers/md/dm-writecache.c (revision cce8e04c)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2018 Red Hat. All rights reserved.
4  *
5  * This file is released under the GPL.
6  */
7 
8 #include <linux/device-mapper.h>
9 #include <linux/module.h>
10 #include <linux/init.h>
11 #include <linux/vmalloc.h>
12 #include <linux/kthread.h>
13 #include <linux/dm-io.h>
14 #include <linux/dm-kcopyd.h>
15 #include <linux/dax.h>
16 #include <linux/pfn_t.h>
17 #include <linux/libnvdimm.h>
18 
19 #define DM_MSG_PREFIX "writecache"
20 
21 #define HIGH_WATERMARK			50
22 #define LOW_WATERMARK			45
23 #define MAX_WRITEBACK_JOBS		0
24 #define ENDIO_LATENCY			16
25 #define WRITEBACK_LATENCY		64
26 #define AUTOCOMMIT_BLOCKS_SSD		65536
27 #define AUTOCOMMIT_BLOCKS_PMEM		64
28 #define AUTOCOMMIT_MSEC			1000
29 
30 #define BITMAP_GRANULARITY	65536
31 #if BITMAP_GRANULARITY < PAGE_SIZE
32 #undef BITMAP_GRANULARITY
33 #define BITMAP_GRANULARITY	PAGE_SIZE
34 #endif
35 
36 #if IS_ENABLED(CONFIG_ARCH_HAS_PMEM_API) && IS_ENABLED(CONFIG_DAX_DRIVER)
37 #define DM_WRITECACHE_HAS_PMEM
38 #endif
39 
40 #ifdef DM_WRITECACHE_HAS_PMEM
41 #define pmem_assign(dest, src)					\
42 do {								\
43 	typeof(dest) uniq = (src);				\
44 	memcpy_flushcache(&(dest), &uniq, sizeof(dest));	\
45 } while (0)
46 #else
47 #define pmem_assign(dest, src)	((dest) = (src))
48 #endif
49 
50 #if defined(__HAVE_ARCH_MEMCPY_MCSAFE) && defined(DM_WRITECACHE_HAS_PMEM)
51 #define DM_WRITECACHE_HANDLE_HARDWARE_ERRORS
52 #endif
53 
54 #define MEMORY_SUPERBLOCK_MAGIC		0x23489321
55 #define MEMORY_SUPERBLOCK_VERSION	1
56 
57 struct wc_memory_entry {
58 	__le64 original_sector;
59 	__le64 seq_count;
60 };
61 
62 struct wc_memory_superblock {
63 	union {
64 		struct {
65 			__le32 magic;
66 			__le32 version;
67 			__le32 block_size;
68 			__le32 pad;
69 			__le64 n_blocks;
70 			__le64 seq_count;
71 		};
72 		__le64 padding[8];
73 	};
74 	struct wc_memory_entry entries[0];
75 };
76 
77 struct wc_entry {
78 	struct rb_node rb_node;
79 	struct list_head lru;
80 	unsigned short wc_list_contiguous;
81 	bool write_in_progress
82 #if BITS_PER_LONG == 64
83 		:1
84 #endif
85 	;
86 	unsigned long index
87 #if BITS_PER_LONG == 64
88 		:47
89 #endif
90 	;
91 #ifdef DM_WRITECACHE_HANDLE_HARDWARE_ERRORS
92 	uint64_t original_sector;
93 	uint64_t seq_count;
94 #endif
95 };
96 
97 #ifdef DM_WRITECACHE_HAS_PMEM
98 #define WC_MODE_PMEM(wc)			((wc)->pmem_mode)
99 #define WC_MODE_FUA(wc)				((wc)->writeback_fua)
100 #else
101 #define WC_MODE_PMEM(wc)			false
102 #define WC_MODE_FUA(wc)				false
103 #endif
104 #define WC_MODE_SORT_FREELIST(wc)		(!WC_MODE_PMEM(wc))
105 
106 struct dm_writecache {
107 	struct mutex lock;
108 	struct list_head lru;
109 	union {
110 		struct list_head freelist;
111 		struct {
112 			struct rb_root freetree;
113 			struct wc_entry *current_free;
114 		};
115 	};
116 	struct rb_root tree;
117 
118 	size_t freelist_size;
119 	size_t writeback_size;
120 	size_t freelist_high_watermark;
121 	size_t freelist_low_watermark;
122 
123 	unsigned uncommitted_blocks;
124 	unsigned autocommit_blocks;
125 	unsigned max_writeback_jobs;
126 
127 	int error;
128 
129 	unsigned long autocommit_jiffies;
130 	struct timer_list autocommit_timer;
131 	struct wait_queue_head freelist_wait;
132 
133 	atomic_t bio_in_progress[2];
134 	struct wait_queue_head bio_in_progress_wait[2];
135 
136 	struct dm_target *ti;
137 	struct dm_dev *dev;
138 	struct dm_dev *ssd_dev;
139 	sector_t start_sector;
140 	void *memory_map;
141 	uint64_t memory_map_size;
142 	size_t metadata_sectors;
143 	size_t n_blocks;
144 	uint64_t seq_count;
145 	void *block_start;
146 	struct wc_entry *entries;
147 	unsigned block_size;
148 	unsigned char block_size_bits;
149 
150 	bool pmem_mode:1;
151 	bool writeback_fua:1;
152 
153 	bool overwrote_committed:1;
154 	bool memory_vmapped:1;
155 
156 	bool high_wm_percent_set:1;
157 	bool low_wm_percent_set:1;
158 	bool max_writeback_jobs_set:1;
159 	bool autocommit_blocks_set:1;
160 	bool autocommit_time_set:1;
161 	bool writeback_fua_set:1;
162 	bool flush_on_suspend:1;
163 
164 	unsigned writeback_all;
165 	struct workqueue_struct *writeback_wq;
166 	struct work_struct writeback_work;
167 	struct work_struct flush_work;
168 
169 	struct dm_io_client *dm_io;
170 
171 	raw_spinlock_t endio_list_lock;
172 	struct list_head endio_list;
173 	struct task_struct *endio_thread;
174 
175 	struct task_struct *flush_thread;
176 	struct bio_list flush_list;
177 
178 	struct dm_kcopyd_client *dm_kcopyd;
179 	unsigned long *dirty_bitmap;
180 	unsigned dirty_bitmap_size;
181 
182 	struct bio_set bio_set;
183 	mempool_t copy_pool;
184 };
185 
186 #define WB_LIST_INLINE		16
187 
188 struct writeback_struct {
189 	struct list_head endio_entry;
190 	struct dm_writecache *wc;
191 	struct wc_entry **wc_list;
192 	unsigned wc_list_n;
193 	unsigned page_offset;
194 	struct page *page;
195 	struct wc_entry *wc_list_inline[WB_LIST_INLINE];
196 	struct bio bio;
197 };
198 
199 struct copy_struct {
200 	struct list_head endio_entry;
201 	struct dm_writecache *wc;
202 	struct wc_entry *e;
203 	unsigned n_entries;
204 	int error;
205 };
206 
207 DECLARE_DM_KCOPYD_THROTTLE_WITH_MODULE_PARM(dm_writecache_throttle,
208 					    "A percentage of time allocated for data copying");
209 
210 static void wc_lock(struct dm_writecache *wc)
211 {
212 	mutex_lock(&wc->lock);
213 }
214 
215 static void wc_unlock(struct dm_writecache *wc)
216 {
217 	mutex_unlock(&wc->lock);
218 }
219 
220 #ifdef DM_WRITECACHE_HAS_PMEM
221 static int persistent_memory_claim(struct dm_writecache *wc)
222 {
223 	int r;
224 	loff_t s;
225 	long p, da;
226 	pfn_t pfn;
227 	int id;
228 	struct page **pages;
229 
230 	wc->memory_vmapped = false;
231 
232 	if (!wc->ssd_dev->dax_dev) {
233 		r = -EOPNOTSUPP;
234 		goto err1;
235 	}
236 	s = wc->memory_map_size;
237 	p = s >> PAGE_SHIFT;
238 	if (!p) {
239 		r = -EINVAL;
240 		goto err1;
241 	}
242 	if (p != s >> PAGE_SHIFT) {
243 		r = -EOVERFLOW;
244 		goto err1;
245 	}
246 
247 	id = dax_read_lock();
248 
249 	da = dax_direct_access(wc->ssd_dev->dax_dev, 0, p, &wc->memory_map, &pfn);
250 	if (da < 0) {
251 		wc->memory_map = NULL;
252 		r = da;
253 		goto err2;
254 	}
255 	if (!pfn_t_has_page(pfn)) {
256 		wc->memory_map = NULL;
257 		r = -EOPNOTSUPP;
258 		goto err2;
259 	}
260 	if (da != p) {
261 		long i;
262 		wc->memory_map = NULL;
263 		pages = kvmalloc_array(p, sizeof(struct page *), GFP_KERNEL);
264 		if (!pages) {
265 			r = -ENOMEM;
266 			goto err2;
267 		}
268 		i = 0;
269 		do {
270 			long daa;
271 			daa = dax_direct_access(wc->ssd_dev->dax_dev, i, p - i,
272 						NULL, &pfn);
273 			if (daa <= 0) {
274 				r = daa ? daa : -EINVAL;
275 				goto err3;
276 			}
277 			if (!pfn_t_has_page(pfn)) {
278 				r = -EOPNOTSUPP;
279 				goto err3;
280 			}
281 			while (daa-- && i < p) {
282 				pages[i++] = pfn_t_to_page(pfn);
283 				pfn.val++;
284 			}
285 		} while (i < p);
286 		wc->memory_map = vmap(pages, p, VM_MAP, PAGE_KERNEL);
287 		if (!wc->memory_map) {
288 			r = -ENOMEM;
289 			goto err3;
290 		}
291 		kvfree(pages);
292 		wc->memory_vmapped = true;
293 	}
294 
295 	dax_read_unlock(id);
296 
297 	wc->memory_map += (size_t)wc->start_sector << SECTOR_SHIFT;
298 	wc->memory_map_size -= (size_t)wc->start_sector << SECTOR_SHIFT;
299 
300 	return 0;
301 err3:
302 	kvfree(pages);
303 err2:
304 	dax_read_unlock(id);
305 err1:
306 	return r;
307 }
308 #else
309 static int persistent_memory_claim(struct dm_writecache *wc)
310 {
311 	BUG();
312 }
313 #endif
314 
315 static void persistent_memory_release(struct dm_writecache *wc)
316 {
317 	if (wc->memory_vmapped)
318 		vunmap(wc->memory_map - ((size_t)wc->start_sector << SECTOR_SHIFT));
319 }
320 
321 static struct page *persistent_memory_page(void *addr)
322 {
323 	if (is_vmalloc_addr(addr))
324 		return vmalloc_to_page(addr);
325 	else
326 		return virt_to_page(addr);
327 }
328 
329 static unsigned persistent_memory_page_offset(void *addr)
330 {
331 	return (unsigned long)addr & (PAGE_SIZE - 1);
332 }
333 
334 static void persistent_memory_flush_cache(void *ptr, size_t size)
335 {
336 	if (is_vmalloc_addr(ptr))
337 		flush_kernel_vmap_range(ptr, size);
338 }
339 
340 static void persistent_memory_invalidate_cache(void *ptr, size_t size)
341 {
342 	if (is_vmalloc_addr(ptr))
343 		invalidate_kernel_vmap_range(ptr, size);
344 }
345 
346 static struct wc_memory_superblock *sb(struct dm_writecache *wc)
347 {
348 	return wc->memory_map;
349 }
350 
351 static struct wc_memory_entry *memory_entry(struct dm_writecache *wc, struct wc_entry *e)
352 {
353 	return &sb(wc)->entries[e->index];
354 }
355 
356 static void *memory_data(struct dm_writecache *wc, struct wc_entry *e)
357 {
358 	return (char *)wc->block_start + (e->index << wc->block_size_bits);
359 }
360 
361 static sector_t cache_sector(struct dm_writecache *wc, struct wc_entry *e)
362 {
363 	return wc->start_sector + wc->metadata_sectors +
364 		((sector_t)e->index << (wc->block_size_bits - SECTOR_SHIFT));
365 }
366 
367 static uint64_t read_original_sector(struct dm_writecache *wc, struct wc_entry *e)
368 {
369 #ifdef DM_WRITECACHE_HANDLE_HARDWARE_ERRORS
370 	return e->original_sector;
371 #else
372 	return le64_to_cpu(memory_entry(wc, e)->original_sector);
373 #endif
374 }
375 
376 static uint64_t read_seq_count(struct dm_writecache *wc, struct wc_entry *e)
377 {
378 #ifdef DM_WRITECACHE_HANDLE_HARDWARE_ERRORS
379 	return e->seq_count;
380 #else
381 	return le64_to_cpu(memory_entry(wc, e)->seq_count);
382 #endif
383 }
384 
385 static void clear_seq_count(struct dm_writecache *wc, struct wc_entry *e)
386 {
387 #ifdef DM_WRITECACHE_HANDLE_HARDWARE_ERRORS
388 	e->seq_count = -1;
389 #endif
390 	pmem_assign(memory_entry(wc, e)->seq_count, cpu_to_le64(-1));
391 }
392 
393 static void write_original_sector_seq_count(struct dm_writecache *wc, struct wc_entry *e,
394 					    uint64_t original_sector, uint64_t seq_count)
395 {
396 	struct wc_memory_entry me;
397 #ifdef DM_WRITECACHE_HANDLE_HARDWARE_ERRORS
398 	e->original_sector = original_sector;
399 	e->seq_count = seq_count;
400 #endif
401 	me.original_sector = cpu_to_le64(original_sector);
402 	me.seq_count = cpu_to_le64(seq_count);
403 	pmem_assign(*memory_entry(wc, e), me);
404 }
405 
406 #define writecache_error(wc, err, msg, arg...)				\
407 do {									\
408 	if (!cmpxchg(&(wc)->error, 0, err))				\
409 		DMERR(msg, ##arg);					\
410 	wake_up(&(wc)->freelist_wait);					\
411 } while (0)
412 
413 #define writecache_has_error(wc)	(unlikely(READ_ONCE((wc)->error)))
414 
415 static void writecache_flush_all_metadata(struct dm_writecache *wc)
416 {
417 	if (!WC_MODE_PMEM(wc))
418 		memset(wc->dirty_bitmap, -1, wc->dirty_bitmap_size);
419 }
420 
421 static void writecache_flush_region(struct dm_writecache *wc, void *ptr, size_t size)
422 {
423 	if (!WC_MODE_PMEM(wc))
424 		__set_bit(((char *)ptr - (char *)wc->memory_map) / BITMAP_GRANULARITY,
425 			  wc->dirty_bitmap);
426 }
427 
428 static void writecache_disk_flush(struct dm_writecache *wc, struct dm_dev *dev);
429 
430 struct io_notify {
431 	struct dm_writecache *wc;
432 	struct completion c;
433 	atomic_t count;
434 };
435 
436 static void writecache_notify_io(unsigned long error, void *context)
437 {
438 	struct io_notify *endio = context;
439 
440 	if (unlikely(error != 0))
441 		writecache_error(endio->wc, -EIO, "error writing metadata");
442 	BUG_ON(atomic_read(&endio->count) <= 0);
443 	if (atomic_dec_and_test(&endio->count))
444 		complete(&endio->c);
445 }
446 
447 static void ssd_commit_flushed(struct dm_writecache *wc)
448 {
449 	struct dm_io_region region;
450 	struct dm_io_request req;
451 	struct io_notify endio = {
452 		wc,
453 		COMPLETION_INITIALIZER_ONSTACK(endio.c),
454 		ATOMIC_INIT(1),
455 	};
456 	unsigned bitmap_bits = wc->dirty_bitmap_size * 8;
457 	unsigned i = 0;
458 
459 	while (1) {
460 		unsigned j;
461 		i = find_next_bit(wc->dirty_bitmap, bitmap_bits, i);
462 		if (unlikely(i == bitmap_bits))
463 			break;
464 		j = find_next_zero_bit(wc->dirty_bitmap, bitmap_bits, i);
465 
466 		region.bdev = wc->ssd_dev->bdev;
467 		region.sector = (sector_t)i * (BITMAP_GRANULARITY >> SECTOR_SHIFT);
468 		region.count = (sector_t)(j - i) * (BITMAP_GRANULARITY >> SECTOR_SHIFT);
469 
470 		if (unlikely(region.sector >= wc->metadata_sectors))
471 			break;
472 		if (unlikely(region.sector + region.count > wc->metadata_sectors))
473 			region.count = wc->metadata_sectors - region.sector;
474 
475 		region.sector += wc->start_sector;
476 		atomic_inc(&endio.count);
477 		req.bi_op = REQ_OP_WRITE;
478 		req.bi_op_flags = REQ_SYNC;
479 		req.mem.type = DM_IO_VMA;
480 		req.mem.ptr.vma = (char *)wc->memory_map + (size_t)i * BITMAP_GRANULARITY;
481 		req.client = wc->dm_io;
482 		req.notify.fn = writecache_notify_io;
483 		req.notify.context = &endio;
484 
485 		/* writing via async dm-io (implied by notify.fn above) won't return an error */
486 	        (void) dm_io(&req, 1, &region, NULL);
487 		i = j;
488 	}
489 
490 	writecache_notify_io(0, &endio);
491 	wait_for_completion_io(&endio.c);
492 
493 	writecache_disk_flush(wc, wc->ssd_dev);
494 
495 	memset(wc->dirty_bitmap, 0, wc->dirty_bitmap_size);
496 }
497 
498 static void writecache_commit_flushed(struct dm_writecache *wc)
499 {
500 	if (WC_MODE_PMEM(wc))
501 		wmb();
502 	else
503 		ssd_commit_flushed(wc);
504 }
505 
506 static void writecache_disk_flush(struct dm_writecache *wc, struct dm_dev *dev)
507 {
508 	int r;
509 	struct dm_io_region region;
510 	struct dm_io_request req;
511 
512 	region.bdev = dev->bdev;
513 	region.sector = 0;
514 	region.count = 0;
515 	req.bi_op = REQ_OP_WRITE;
516 	req.bi_op_flags = REQ_PREFLUSH;
517 	req.mem.type = DM_IO_KMEM;
518 	req.mem.ptr.addr = NULL;
519 	req.client = wc->dm_io;
520 	req.notify.fn = NULL;
521 
522 	r = dm_io(&req, 1, &region, NULL);
523 	if (unlikely(r))
524 		writecache_error(wc, r, "error flushing metadata: %d", r);
525 }
526 
527 static void writecache_wait_for_ios(struct dm_writecache *wc, int direction)
528 {
529 	wait_event(wc->bio_in_progress_wait[direction],
530 		   !atomic_read(&wc->bio_in_progress[direction]));
531 }
532 
533 #define WFE_RETURN_FOLLOWING	1
534 #define WFE_LOWEST_SEQ		2
535 
536 static struct wc_entry *writecache_find_entry(struct dm_writecache *wc,
537 					      uint64_t block, int flags)
538 {
539 	struct wc_entry *e;
540 	struct rb_node *node = wc->tree.rb_node;
541 
542 	if (unlikely(!node))
543 		return NULL;
544 
545 	while (1) {
546 		e = container_of(node, struct wc_entry, rb_node);
547 		if (read_original_sector(wc, e) == block)
548 			break;
549 		node = (read_original_sector(wc, e) >= block ?
550 			e->rb_node.rb_left : e->rb_node.rb_right);
551 		if (unlikely(!node)) {
552 			if (!(flags & WFE_RETURN_FOLLOWING)) {
553 				return NULL;
554 			}
555 			if (read_original_sector(wc, e) >= block) {
556 				break;
557 			} else {
558 				node = rb_next(&e->rb_node);
559 				if (unlikely(!node)) {
560 					return NULL;
561 				}
562 				e = container_of(node, struct wc_entry, rb_node);
563 				break;
564 			}
565 		}
566 	}
567 
568 	while (1) {
569 		struct wc_entry *e2;
570 		if (flags & WFE_LOWEST_SEQ)
571 			node = rb_prev(&e->rb_node);
572 		else
573 			node = rb_next(&e->rb_node);
574 		if (!node)
575 			return e;
576 		e2 = container_of(node, struct wc_entry, rb_node);
577 		if (read_original_sector(wc, e2) != block)
578 			return e;
579 		e = e2;
580 	}
581 }
582 
583 static void writecache_insert_entry(struct dm_writecache *wc, struct wc_entry *ins)
584 {
585 	struct wc_entry *e;
586 	struct rb_node **node = &wc->tree.rb_node, *parent = NULL;
587 
588 	while (*node) {
589 		e = container_of(*node, struct wc_entry, rb_node);
590 		parent = &e->rb_node;
591 		if (read_original_sector(wc, e) > read_original_sector(wc, ins))
592 			node = &parent->rb_left;
593 		else
594 			node = &parent->rb_right;
595 	}
596 	rb_link_node(&ins->rb_node, parent, node);
597 	rb_insert_color(&ins->rb_node, &wc->tree);
598 	list_add(&ins->lru, &wc->lru);
599 }
600 
601 static void writecache_unlink(struct dm_writecache *wc, struct wc_entry *e)
602 {
603 	list_del(&e->lru);
604 	rb_erase(&e->rb_node, &wc->tree);
605 }
606 
607 static void writecache_add_to_freelist(struct dm_writecache *wc, struct wc_entry *e)
608 {
609 	if (WC_MODE_SORT_FREELIST(wc)) {
610 		struct rb_node **node = &wc->freetree.rb_node, *parent = NULL;
611 		if (unlikely(!*node))
612 			wc->current_free = e;
613 		while (*node) {
614 			parent = *node;
615 			if (&e->rb_node < *node)
616 				node = &parent->rb_left;
617 			else
618 				node = &parent->rb_right;
619 		}
620 		rb_link_node(&e->rb_node, parent, node);
621 		rb_insert_color(&e->rb_node, &wc->freetree);
622 	} else {
623 		list_add_tail(&e->lru, &wc->freelist);
624 	}
625 	wc->freelist_size++;
626 }
627 
628 static struct wc_entry *writecache_pop_from_freelist(struct dm_writecache *wc)
629 {
630 	struct wc_entry *e;
631 
632 	if (WC_MODE_SORT_FREELIST(wc)) {
633 		struct rb_node *next;
634 		if (unlikely(!wc->current_free))
635 			return NULL;
636 		e = wc->current_free;
637 		next = rb_next(&e->rb_node);
638 		rb_erase(&e->rb_node, &wc->freetree);
639 		if (unlikely(!next))
640 			next = rb_first(&wc->freetree);
641 		wc->current_free = next ? container_of(next, struct wc_entry, rb_node) : NULL;
642 	} else {
643 		if (unlikely(list_empty(&wc->freelist)))
644 			return NULL;
645 		e = container_of(wc->freelist.next, struct wc_entry, lru);
646 		list_del(&e->lru);
647 	}
648 	wc->freelist_size--;
649 	if (unlikely(wc->freelist_size + wc->writeback_size <= wc->freelist_high_watermark))
650 		queue_work(wc->writeback_wq, &wc->writeback_work);
651 
652 	return e;
653 }
654 
655 static void writecache_free_entry(struct dm_writecache *wc, struct wc_entry *e)
656 {
657 	writecache_unlink(wc, e);
658 	writecache_add_to_freelist(wc, e);
659 	clear_seq_count(wc, e);
660 	writecache_flush_region(wc, memory_entry(wc, e), sizeof(struct wc_memory_entry));
661 	if (unlikely(waitqueue_active(&wc->freelist_wait)))
662 		wake_up(&wc->freelist_wait);
663 }
664 
665 static void writecache_wait_on_freelist(struct dm_writecache *wc)
666 {
667 	DEFINE_WAIT(wait);
668 
669 	prepare_to_wait(&wc->freelist_wait, &wait, TASK_UNINTERRUPTIBLE);
670 	wc_unlock(wc);
671 	io_schedule();
672 	finish_wait(&wc->freelist_wait, &wait);
673 	wc_lock(wc);
674 }
675 
676 static void writecache_poison_lists(struct dm_writecache *wc)
677 {
678 	/*
679 	 * Catch incorrect access to these values while the device is suspended.
680 	 */
681 	memset(&wc->tree, -1, sizeof wc->tree);
682 	wc->lru.next = LIST_POISON1;
683 	wc->lru.prev = LIST_POISON2;
684 	wc->freelist.next = LIST_POISON1;
685 	wc->freelist.prev = LIST_POISON2;
686 }
687 
688 static void writecache_flush_entry(struct dm_writecache *wc, struct wc_entry *e)
689 {
690 	writecache_flush_region(wc, memory_entry(wc, e), sizeof(struct wc_memory_entry));
691 	if (WC_MODE_PMEM(wc))
692 		writecache_flush_region(wc, memory_data(wc, e), wc->block_size);
693 }
694 
695 static bool writecache_entry_is_committed(struct dm_writecache *wc, struct wc_entry *e)
696 {
697 	return read_seq_count(wc, e) < wc->seq_count;
698 }
699 
700 static void writecache_flush(struct dm_writecache *wc)
701 {
702 	struct wc_entry *e, *e2;
703 	bool need_flush_after_free;
704 
705 	wc->uncommitted_blocks = 0;
706 	del_timer(&wc->autocommit_timer);
707 
708 	if (list_empty(&wc->lru))
709 		return;
710 
711 	e = container_of(wc->lru.next, struct wc_entry, lru);
712 	if (writecache_entry_is_committed(wc, e)) {
713 		if (wc->overwrote_committed) {
714 			writecache_wait_for_ios(wc, WRITE);
715 			writecache_disk_flush(wc, wc->ssd_dev);
716 			wc->overwrote_committed = false;
717 		}
718 		return;
719 	}
720 	while (1) {
721 		writecache_flush_entry(wc, e);
722 		if (unlikely(e->lru.next == &wc->lru))
723 			break;
724 		e2 = container_of(e->lru.next, struct wc_entry, lru);
725 		if (writecache_entry_is_committed(wc, e2))
726 			break;
727 		e = e2;
728 		cond_resched();
729 	}
730 	writecache_commit_flushed(wc);
731 
732 	writecache_wait_for_ios(wc, WRITE);
733 
734 	wc->seq_count++;
735 	pmem_assign(sb(wc)->seq_count, cpu_to_le64(wc->seq_count));
736 	writecache_flush_region(wc, &sb(wc)->seq_count, sizeof sb(wc)->seq_count);
737 	writecache_commit_flushed(wc);
738 
739 	wc->overwrote_committed = false;
740 
741 	need_flush_after_free = false;
742 	while (1) {
743 		/* Free another committed entry with lower seq-count */
744 		struct rb_node *rb_node = rb_prev(&e->rb_node);
745 
746 		if (rb_node) {
747 			e2 = container_of(rb_node, struct wc_entry, rb_node);
748 			if (read_original_sector(wc, e2) == read_original_sector(wc, e) &&
749 			    likely(!e2->write_in_progress)) {
750 				writecache_free_entry(wc, e2);
751 				need_flush_after_free = true;
752 			}
753 		}
754 		if (unlikely(e->lru.prev == &wc->lru))
755 			break;
756 		e = container_of(e->lru.prev, struct wc_entry, lru);
757 		cond_resched();
758 	}
759 
760 	if (need_flush_after_free)
761 		writecache_commit_flushed(wc);
762 }
763 
764 static void writecache_flush_work(struct work_struct *work)
765 {
766 	struct dm_writecache *wc = container_of(work, struct dm_writecache, flush_work);
767 
768 	wc_lock(wc);
769 	writecache_flush(wc);
770 	wc_unlock(wc);
771 }
772 
773 static void writecache_autocommit_timer(struct timer_list *t)
774 {
775 	struct dm_writecache *wc = from_timer(wc, t, autocommit_timer);
776 	if (!writecache_has_error(wc))
777 		queue_work(wc->writeback_wq, &wc->flush_work);
778 }
779 
780 static void writecache_schedule_autocommit(struct dm_writecache *wc)
781 {
782 	if (!timer_pending(&wc->autocommit_timer))
783 		mod_timer(&wc->autocommit_timer, jiffies + wc->autocommit_jiffies);
784 }
785 
786 static void writecache_discard(struct dm_writecache *wc, sector_t start, sector_t end)
787 {
788 	struct wc_entry *e;
789 	bool discarded_something = false;
790 
791 	e = writecache_find_entry(wc, start, WFE_RETURN_FOLLOWING | WFE_LOWEST_SEQ);
792 	if (unlikely(!e))
793 		return;
794 
795 	while (read_original_sector(wc, e) < end) {
796 		struct rb_node *node = rb_next(&e->rb_node);
797 
798 		if (likely(!e->write_in_progress)) {
799 			if (!discarded_something) {
800 				writecache_wait_for_ios(wc, READ);
801 				writecache_wait_for_ios(wc, WRITE);
802 				discarded_something = true;
803 			}
804 			writecache_free_entry(wc, e);
805 		}
806 
807 		if (!node)
808 			break;
809 
810 		e = container_of(node, struct wc_entry, rb_node);
811 	}
812 
813 	if (discarded_something)
814 		writecache_commit_flushed(wc);
815 }
816 
817 static bool writecache_wait_for_writeback(struct dm_writecache *wc)
818 {
819 	if (wc->writeback_size) {
820 		writecache_wait_on_freelist(wc);
821 		return true;
822 	}
823 	return false;
824 }
825 
826 static void writecache_suspend(struct dm_target *ti)
827 {
828 	struct dm_writecache *wc = ti->private;
829 	bool flush_on_suspend;
830 
831 	del_timer_sync(&wc->autocommit_timer);
832 
833 	wc_lock(wc);
834 	writecache_flush(wc);
835 	flush_on_suspend = wc->flush_on_suspend;
836 	if (flush_on_suspend) {
837 		wc->flush_on_suspend = false;
838 		wc->writeback_all++;
839 		queue_work(wc->writeback_wq, &wc->writeback_work);
840 	}
841 	wc_unlock(wc);
842 
843 	flush_workqueue(wc->writeback_wq);
844 
845 	wc_lock(wc);
846 	if (flush_on_suspend)
847 		wc->writeback_all--;
848 	while (writecache_wait_for_writeback(wc));
849 
850 	if (WC_MODE_PMEM(wc))
851 		persistent_memory_flush_cache(wc->memory_map, wc->memory_map_size);
852 
853 	writecache_poison_lists(wc);
854 
855 	wc_unlock(wc);
856 }
857 
858 static int writecache_alloc_entries(struct dm_writecache *wc)
859 {
860 	size_t b;
861 
862 	if (wc->entries)
863 		return 0;
864 	wc->entries = vmalloc(array_size(sizeof(struct wc_entry), wc->n_blocks));
865 	if (!wc->entries)
866 		return -ENOMEM;
867 	for (b = 0; b < wc->n_blocks; b++) {
868 		struct wc_entry *e = &wc->entries[b];
869 		e->index = b;
870 		e->write_in_progress = false;
871 	}
872 
873 	return 0;
874 }
875 
876 static void writecache_resume(struct dm_target *ti)
877 {
878 	struct dm_writecache *wc = ti->private;
879 	size_t b;
880 	bool need_flush = false;
881 	__le64 sb_seq_count;
882 	int r;
883 
884 	wc_lock(wc);
885 
886 	if (WC_MODE_PMEM(wc))
887 		persistent_memory_invalidate_cache(wc->memory_map, wc->memory_map_size);
888 
889 	wc->tree = RB_ROOT;
890 	INIT_LIST_HEAD(&wc->lru);
891 	if (WC_MODE_SORT_FREELIST(wc)) {
892 		wc->freetree = RB_ROOT;
893 		wc->current_free = NULL;
894 	} else {
895 		INIT_LIST_HEAD(&wc->freelist);
896 	}
897 	wc->freelist_size = 0;
898 
899 	r = memcpy_mcsafe(&sb_seq_count, &sb(wc)->seq_count, sizeof(uint64_t));
900 	if (r) {
901 		writecache_error(wc, r, "hardware memory error when reading superblock: %d", r);
902 		sb_seq_count = cpu_to_le64(0);
903 	}
904 	wc->seq_count = le64_to_cpu(sb_seq_count);
905 
906 #ifdef DM_WRITECACHE_HANDLE_HARDWARE_ERRORS
907 	for (b = 0; b < wc->n_blocks; b++) {
908 		struct wc_entry *e = &wc->entries[b];
909 		struct wc_memory_entry wme;
910 		if (writecache_has_error(wc)) {
911 			e->original_sector = -1;
912 			e->seq_count = -1;
913 			continue;
914 		}
915 		r = memcpy_mcsafe(&wme, memory_entry(wc, e), sizeof(struct wc_memory_entry));
916 		if (r) {
917 			writecache_error(wc, r, "hardware memory error when reading metadata entry %lu: %d",
918 					 (unsigned long)b, r);
919 			e->original_sector = -1;
920 			e->seq_count = -1;
921 		} else {
922 			e->original_sector = le64_to_cpu(wme.original_sector);
923 			e->seq_count = le64_to_cpu(wme.seq_count);
924 		}
925 	}
926 #endif
927 	for (b = 0; b < wc->n_blocks; b++) {
928 		struct wc_entry *e = &wc->entries[b];
929 		if (!writecache_entry_is_committed(wc, e)) {
930 			if (read_seq_count(wc, e) != -1) {
931 erase_this:
932 				clear_seq_count(wc, e);
933 				need_flush = true;
934 			}
935 			writecache_add_to_freelist(wc, e);
936 		} else {
937 			struct wc_entry *old;
938 
939 			old = writecache_find_entry(wc, read_original_sector(wc, e), 0);
940 			if (!old) {
941 				writecache_insert_entry(wc, e);
942 			} else {
943 				if (read_seq_count(wc, old) == read_seq_count(wc, e)) {
944 					writecache_error(wc, -EINVAL,
945 						 "two identical entries, position %llu, sector %llu, sequence %llu",
946 						 (unsigned long long)b, (unsigned long long)read_original_sector(wc, e),
947 						 (unsigned long long)read_seq_count(wc, e));
948 				}
949 				if (read_seq_count(wc, old) > read_seq_count(wc, e)) {
950 					goto erase_this;
951 				} else {
952 					writecache_free_entry(wc, old);
953 					writecache_insert_entry(wc, e);
954 					need_flush = true;
955 				}
956 			}
957 		}
958 		cond_resched();
959 	}
960 
961 	if (need_flush) {
962 		writecache_flush_all_metadata(wc);
963 		writecache_commit_flushed(wc);
964 	}
965 
966 	wc_unlock(wc);
967 }
968 
969 static int process_flush_mesg(unsigned argc, char **argv, struct dm_writecache *wc)
970 {
971 	if (argc != 1)
972 		return -EINVAL;
973 
974 	wc_lock(wc);
975 	if (dm_suspended(wc->ti)) {
976 		wc_unlock(wc);
977 		return -EBUSY;
978 	}
979 	if (writecache_has_error(wc)) {
980 		wc_unlock(wc);
981 		return -EIO;
982 	}
983 
984 	writecache_flush(wc);
985 	wc->writeback_all++;
986 	queue_work(wc->writeback_wq, &wc->writeback_work);
987 	wc_unlock(wc);
988 
989 	flush_workqueue(wc->writeback_wq);
990 
991 	wc_lock(wc);
992 	wc->writeback_all--;
993 	if (writecache_has_error(wc)) {
994 		wc_unlock(wc);
995 		return -EIO;
996 	}
997 	wc_unlock(wc);
998 
999 	return 0;
1000 }
1001 
1002 static int process_flush_on_suspend_mesg(unsigned argc, char **argv, struct dm_writecache *wc)
1003 {
1004 	if (argc != 1)
1005 		return -EINVAL;
1006 
1007 	wc_lock(wc);
1008 	wc->flush_on_suspend = true;
1009 	wc_unlock(wc);
1010 
1011 	return 0;
1012 }
1013 
1014 static int writecache_message(struct dm_target *ti, unsigned argc, char **argv,
1015 			      char *result, unsigned maxlen)
1016 {
1017 	int r = -EINVAL;
1018 	struct dm_writecache *wc = ti->private;
1019 
1020 	if (!strcasecmp(argv[0], "flush"))
1021 		r = process_flush_mesg(argc, argv, wc);
1022 	else if (!strcasecmp(argv[0], "flush_on_suspend"))
1023 		r = process_flush_on_suspend_mesg(argc, argv, wc);
1024 	else
1025 		DMERR("unrecognised message received: %s", argv[0]);
1026 
1027 	return r;
1028 }
1029 
1030 static void bio_copy_block(struct dm_writecache *wc, struct bio *bio, void *data)
1031 {
1032 	void *buf;
1033 	unsigned long flags;
1034 	unsigned size;
1035 	int rw = bio_data_dir(bio);
1036 	unsigned remaining_size = wc->block_size;
1037 
1038 	do {
1039 		struct bio_vec bv = bio_iter_iovec(bio, bio->bi_iter);
1040 		buf = bvec_kmap_irq(&bv, &flags);
1041 		size = bv.bv_len;
1042 		if (unlikely(size > remaining_size))
1043 			size = remaining_size;
1044 
1045 		if (rw == READ) {
1046 			int r;
1047 			r = memcpy_mcsafe(buf, data, size);
1048 			flush_dcache_page(bio_page(bio));
1049 			if (unlikely(r)) {
1050 				writecache_error(wc, r, "hardware memory error when reading data: %d", r);
1051 				bio->bi_status = BLK_STS_IOERR;
1052 			}
1053 		} else {
1054 			flush_dcache_page(bio_page(bio));
1055 			memcpy_flushcache(data, buf, size);
1056 		}
1057 
1058 		bvec_kunmap_irq(buf, &flags);
1059 
1060 		data = (char *)data + size;
1061 		remaining_size -= size;
1062 		bio_advance(bio, size);
1063 	} while (unlikely(remaining_size));
1064 }
1065 
1066 static int writecache_flush_thread(void *data)
1067 {
1068 	struct dm_writecache *wc = data;
1069 
1070 	while (1) {
1071 		struct bio *bio;
1072 
1073 		wc_lock(wc);
1074 		bio = bio_list_pop(&wc->flush_list);
1075 		if (!bio) {
1076 			set_current_state(TASK_INTERRUPTIBLE);
1077 			wc_unlock(wc);
1078 
1079 			if (unlikely(kthread_should_stop())) {
1080 				set_current_state(TASK_RUNNING);
1081 				break;
1082 			}
1083 
1084 			schedule();
1085 			continue;
1086 		}
1087 
1088 		if (bio_op(bio) == REQ_OP_DISCARD) {
1089 			writecache_discard(wc, bio->bi_iter.bi_sector,
1090 					   bio_end_sector(bio));
1091 			wc_unlock(wc);
1092 			bio_set_dev(bio, wc->dev->bdev);
1093 			generic_make_request(bio);
1094 		} else {
1095 			writecache_flush(wc);
1096 			wc_unlock(wc);
1097 			if (writecache_has_error(wc))
1098 				bio->bi_status = BLK_STS_IOERR;
1099 			bio_endio(bio);
1100 		}
1101 	}
1102 
1103 	return 0;
1104 }
1105 
1106 static void writecache_offload_bio(struct dm_writecache *wc, struct bio *bio)
1107 {
1108 	if (bio_list_empty(&wc->flush_list))
1109 		wake_up_process(wc->flush_thread);
1110 	bio_list_add(&wc->flush_list, bio);
1111 }
1112 
1113 static int writecache_map(struct dm_target *ti, struct bio *bio)
1114 {
1115 	struct wc_entry *e;
1116 	struct dm_writecache *wc = ti->private;
1117 
1118 	bio->bi_private = NULL;
1119 
1120 	wc_lock(wc);
1121 
1122 	if (unlikely(bio->bi_opf & REQ_PREFLUSH)) {
1123 		if (writecache_has_error(wc))
1124 			goto unlock_error;
1125 		if (WC_MODE_PMEM(wc)) {
1126 			writecache_flush(wc);
1127 			if (writecache_has_error(wc))
1128 				goto unlock_error;
1129 			goto unlock_submit;
1130 		} else {
1131 			writecache_offload_bio(wc, bio);
1132 			goto unlock_return;
1133 		}
1134 	}
1135 
1136 	bio->bi_iter.bi_sector = dm_target_offset(ti, bio->bi_iter.bi_sector);
1137 
1138 	if (unlikely((((unsigned)bio->bi_iter.bi_sector | bio_sectors(bio)) &
1139 				(wc->block_size / 512 - 1)) != 0)) {
1140 		DMERR("I/O is not aligned, sector %llu, size %u, block size %u",
1141 		      (unsigned long long)bio->bi_iter.bi_sector,
1142 		      bio->bi_iter.bi_size, wc->block_size);
1143 		goto unlock_error;
1144 	}
1145 
1146 	if (unlikely(bio_op(bio) == REQ_OP_DISCARD)) {
1147 		if (writecache_has_error(wc))
1148 			goto unlock_error;
1149 		if (WC_MODE_PMEM(wc)) {
1150 			writecache_discard(wc, bio->bi_iter.bi_sector, bio_end_sector(bio));
1151 			goto unlock_remap_origin;
1152 		} else {
1153 			writecache_offload_bio(wc, bio);
1154 			goto unlock_return;
1155 		}
1156 	}
1157 
1158 	if (bio_data_dir(bio) == READ) {
1159 read_next_block:
1160 		e = writecache_find_entry(wc, bio->bi_iter.bi_sector, WFE_RETURN_FOLLOWING);
1161 		if (e && read_original_sector(wc, e) == bio->bi_iter.bi_sector) {
1162 			if (WC_MODE_PMEM(wc)) {
1163 				bio_copy_block(wc, bio, memory_data(wc, e));
1164 				if (bio->bi_iter.bi_size)
1165 					goto read_next_block;
1166 				goto unlock_submit;
1167 			} else {
1168 				dm_accept_partial_bio(bio, wc->block_size >> SECTOR_SHIFT);
1169 				bio_set_dev(bio, wc->ssd_dev->bdev);
1170 				bio->bi_iter.bi_sector = cache_sector(wc, e);
1171 				if (!writecache_entry_is_committed(wc, e))
1172 					writecache_wait_for_ios(wc, WRITE);
1173 				goto unlock_remap;
1174 			}
1175 		} else {
1176 			if (e) {
1177 				sector_t next_boundary =
1178 					read_original_sector(wc, e) - bio->bi_iter.bi_sector;
1179 				if (next_boundary < bio->bi_iter.bi_size >> SECTOR_SHIFT) {
1180 					dm_accept_partial_bio(bio, next_boundary);
1181 				}
1182 			}
1183 			goto unlock_remap_origin;
1184 		}
1185 	} else {
1186 		do {
1187 			if (writecache_has_error(wc))
1188 				goto unlock_error;
1189 			e = writecache_find_entry(wc, bio->bi_iter.bi_sector, 0);
1190 			if (e) {
1191 				if (!writecache_entry_is_committed(wc, e))
1192 					goto bio_copy;
1193 				if (!WC_MODE_PMEM(wc) && !e->write_in_progress) {
1194 					wc->overwrote_committed = true;
1195 					goto bio_copy;
1196 				}
1197 			}
1198 			e = writecache_pop_from_freelist(wc);
1199 			if (unlikely(!e)) {
1200 				writecache_wait_on_freelist(wc);
1201 				continue;
1202 			}
1203 			write_original_sector_seq_count(wc, e, bio->bi_iter.bi_sector, wc->seq_count);
1204 			writecache_insert_entry(wc, e);
1205 			wc->uncommitted_blocks++;
1206 bio_copy:
1207 			if (WC_MODE_PMEM(wc)) {
1208 				bio_copy_block(wc, bio, memory_data(wc, e));
1209 			} else {
1210 				dm_accept_partial_bio(bio, wc->block_size >> SECTOR_SHIFT);
1211 				bio_set_dev(bio, wc->ssd_dev->bdev);
1212 				bio->bi_iter.bi_sector = cache_sector(wc, e);
1213 				if (unlikely(wc->uncommitted_blocks >= wc->autocommit_blocks)) {
1214 					wc->uncommitted_blocks = 0;
1215 					queue_work(wc->writeback_wq, &wc->flush_work);
1216 				} else {
1217 					writecache_schedule_autocommit(wc);
1218 				}
1219 				goto unlock_remap;
1220 			}
1221 		} while (bio->bi_iter.bi_size);
1222 
1223 		if (unlikely(wc->uncommitted_blocks >= wc->autocommit_blocks))
1224 			writecache_flush(wc);
1225 		else
1226 			writecache_schedule_autocommit(wc);
1227 		goto unlock_submit;
1228 	}
1229 
1230 unlock_remap_origin:
1231 	bio_set_dev(bio, wc->dev->bdev);
1232 	wc_unlock(wc);
1233 	return DM_MAPIO_REMAPPED;
1234 
1235 unlock_remap:
1236 	/* make sure that writecache_end_io decrements bio_in_progress: */
1237 	bio->bi_private = (void *)1;
1238 	atomic_inc(&wc->bio_in_progress[bio_data_dir(bio)]);
1239 	wc_unlock(wc);
1240 	return DM_MAPIO_REMAPPED;
1241 
1242 unlock_submit:
1243 	wc_unlock(wc);
1244 	bio_endio(bio);
1245 	return DM_MAPIO_SUBMITTED;
1246 
1247 unlock_return:
1248 	wc_unlock(wc);
1249 	return DM_MAPIO_SUBMITTED;
1250 
1251 unlock_error:
1252 	wc_unlock(wc);
1253 	bio_io_error(bio);
1254 	return DM_MAPIO_SUBMITTED;
1255 }
1256 
1257 static int writecache_end_io(struct dm_target *ti, struct bio *bio, blk_status_t *status)
1258 {
1259 	struct dm_writecache *wc = ti->private;
1260 
1261 	if (bio->bi_private != NULL) {
1262 		int dir = bio_data_dir(bio);
1263 		if (atomic_dec_and_test(&wc->bio_in_progress[dir]))
1264 			if (unlikely(waitqueue_active(&wc->bio_in_progress_wait[dir])))
1265 				wake_up(&wc->bio_in_progress_wait[dir]);
1266 	}
1267 	return 0;
1268 }
1269 
1270 static int writecache_iterate_devices(struct dm_target *ti,
1271 				      iterate_devices_callout_fn fn, void *data)
1272 {
1273 	struct dm_writecache *wc = ti->private;
1274 
1275 	return fn(ti, wc->dev, 0, ti->len, data);
1276 }
1277 
1278 static void writecache_io_hints(struct dm_target *ti, struct queue_limits *limits)
1279 {
1280 	struct dm_writecache *wc = ti->private;
1281 
1282 	if (limits->logical_block_size < wc->block_size)
1283 		limits->logical_block_size = wc->block_size;
1284 
1285 	if (limits->physical_block_size < wc->block_size)
1286 		limits->physical_block_size = wc->block_size;
1287 
1288 	if (limits->io_min < wc->block_size)
1289 		limits->io_min = wc->block_size;
1290 }
1291 
1292 
1293 static void writecache_writeback_endio(struct bio *bio)
1294 {
1295 	struct writeback_struct *wb = container_of(bio, struct writeback_struct, bio);
1296 	struct dm_writecache *wc = wb->wc;
1297 	unsigned long flags;
1298 
1299 	raw_spin_lock_irqsave(&wc->endio_list_lock, flags);
1300 	if (unlikely(list_empty(&wc->endio_list)))
1301 		wake_up_process(wc->endio_thread);
1302 	list_add_tail(&wb->endio_entry, &wc->endio_list);
1303 	raw_spin_unlock_irqrestore(&wc->endio_list_lock, flags);
1304 }
1305 
1306 static void writecache_copy_endio(int read_err, unsigned long write_err, void *ptr)
1307 {
1308 	struct copy_struct *c = ptr;
1309 	struct dm_writecache *wc = c->wc;
1310 
1311 	c->error = likely(!(read_err | write_err)) ? 0 : -EIO;
1312 
1313 	raw_spin_lock_irq(&wc->endio_list_lock);
1314 	if (unlikely(list_empty(&wc->endio_list)))
1315 		wake_up_process(wc->endio_thread);
1316 	list_add_tail(&c->endio_entry, &wc->endio_list);
1317 	raw_spin_unlock_irq(&wc->endio_list_lock);
1318 }
1319 
1320 static void __writecache_endio_pmem(struct dm_writecache *wc, struct list_head *list)
1321 {
1322 	unsigned i;
1323 	struct writeback_struct *wb;
1324 	struct wc_entry *e;
1325 	unsigned long n_walked = 0;
1326 
1327 	do {
1328 		wb = list_entry(list->next, struct writeback_struct, endio_entry);
1329 		list_del(&wb->endio_entry);
1330 
1331 		if (unlikely(wb->bio.bi_status != BLK_STS_OK))
1332 			writecache_error(wc, blk_status_to_errno(wb->bio.bi_status),
1333 					"write error %d", wb->bio.bi_status);
1334 		i = 0;
1335 		do {
1336 			e = wb->wc_list[i];
1337 			BUG_ON(!e->write_in_progress);
1338 			e->write_in_progress = false;
1339 			INIT_LIST_HEAD(&e->lru);
1340 			if (!writecache_has_error(wc))
1341 				writecache_free_entry(wc, e);
1342 			BUG_ON(!wc->writeback_size);
1343 			wc->writeback_size--;
1344 			n_walked++;
1345 			if (unlikely(n_walked >= ENDIO_LATENCY)) {
1346 				writecache_commit_flushed(wc);
1347 				wc_unlock(wc);
1348 				wc_lock(wc);
1349 				n_walked = 0;
1350 			}
1351 		} while (++i < wb->wc_list_n);
1352 
1353 		if (wb->wc_list != wb->wc_list_inline)
1354 			kfree(wb->wc_list);
1355 		bio_put(&wb->bio);
1356 	} while (!list_empty(list));
1357 }
1358 
1359 static void __writecache_endio_ssd(struct dm_writecache *wc, struct list_head *list)
1360 {
1361 	struct copy_struct *c;
1362 	struct wc_entry *e;
1363 
1364 	do {
1365 		c = list_entry(list->next, struct copy_struct, endio_entry);
1366 		list_del(&c->endio_entry);
1367 
1368 		if (unlikely(c->error))
1369 			writecache_error(wc, c->error, "copy error");
1370 
1371 		e = c->e;
1372 		do {
1373 			BUG_ON(!e->write_in_progress);
1374 			e->write_in_progress = false;
1375 			INIT_LIST_HEAD(&e->lru);
1376 			if (!writecache_has_error(wc))
1377 				writecache_free_entry(wc, e);
1378 
1379 			BUG_ON(!wc->writeback_size);
1380 			wc->writeback_size--;
1381 			e++;
1382 		} while (--c->n_entries);
1383 		mempool_free(c, &wc->copy_pool);
1384 	} while (!list_empty(list));
1385 }
1386 
1387 static int writecache_endio_thread(void *data)
1388 {
1389 	struct dm_writecache *wc = data;
1390 
1391 	while (1) {
1392 		struct list_head list;
1393 
1394 		raw_spin_lock_irq(&wc->endio_list_lock);
1395 		if (!list_empty(&wc->endio_list))
1396 			goto pop_from_list;
1397 		set_current_state(TASK_INTERRUPTIBLE);
1398 		raw_spin_unlock_irq(&wc->endio_list_lock);
1399 
1400 		if (unlikely(kthread_should_stop())) {
1401 			set_current_state(TASK_RUNNING);
1402 			break;
1403 		}
1404 
1405 		schedule();
1406 
1407 		continue;
1408 
1409 pop_from_list:
1410 		list = wc->endio_list;
1411 		list.next->prev = list.prev->next = &list;
1412 		INIT_LIST_HEAD(&wc->endio_list);
1413 		raw_spin_unlock_irq(&wc->endio_list_lock);
1414 
1415 		if (!WC_MODE_FUA(wc))
1416 			writecache_disk_flush(wc, wc->dev);
1417 
1418 		wc_lock(wc);
1419 
1420 		if (WC_MODE_PMEM(wc)) {
1421 			__writecache_endio_pmem(wc, &list);
1422 		} else {
1423 			__writecache_endio_ssd(wc, &list);
1424 			writecache_wait_for_ios(wc, READ);
1425 		}
1426 
1427 		writecache_commit_flushed(wc);
1428 
1429 		wc_unlock(wc);
1430 	}
1431 
1432 	return 0;
1433 }
1434 
1435 static bool wc_add_block(struct writeback_struct *wb, struct wc_entry *e, gfp_t gfp)
1436 {
1437 	struct dm_writecache *wc = wb->wc;
1438 	unsigned block_size = wc->block_size;
1439 	void *address = memory_data(wc, e);
1440 
1441 	persistent_memory_flush_cache(address, block_size);
1442 	return bio_add_page(&wb->bio, persistent_memory_page(address),
1443 			    block_size, persistent_memory_page_offset(address)) != 0;
1444 }
1445 
1446 struct writeback_list {
1447 	struct list_head list;
1448 	size_t size;
1449 };
1450 
1451 static void __writeback_throttle(struct dm_writecache *wc, struct writeback_list *wbl)
1452 {
1453 	if (unlikely(wc->max_writeback_jobs)) {
1454 		if (READ_ONCE(wc->writeback_size) - wbl->size >= wc->max_writeback_jobs) {
1455 			wc_lock(wc);
1456 			while (wc->writeback_size - wbl->size >= wc->max_writeback_jobs)
1457 				writecache_wait_on_freelist(wc);
1458 			wc_unlock(wc);
1459 		}
1460 	}
1461 	cond_resched();
1462 }
1463 
1464 static void __writecache_writeback_pmem(struct dm_writecache *wc, struct writeback_list *wbl)
1465 {
1466 	struct wc_entry *e, *f;
1467 	struct bio *bio;
1468 	struct writeback_struct *wb;
1469 	unsigned max_pages;
1470 
1471 	while (wbl->size) {
1472 		wbl->size--;
1473 		e = container_of(wbl->list.prev, struct wc_entry, lru);
1474 		list_del(&e->lru);
1475 
1476 		max_pages = e->wc_list_contiguous;
1477 
1478 		bio = bio_alloc_bioset(GFP_NOIO, max_pages, &wc->bio_set);
1479 		wb = container_of(bio, struct writeback_struct, bio);
1480 		wb->wc = wc;
1481 		wb->bio.bi_end_io = writecache_writeback_endio;
1482 		bio_set_dev(&wb->bio, wc->dev->bdev);
1483 		wb->bio.bi_iter.bi_sector = read_original_sector(wc, e);
1484 		wb->page_offset = PAGE_SIZE;
1485 		if (max_pages <= WB_LIST_INLINE ||
1486 		    unlikely(!(wb->wc_list = kmalloc_array(max_pages, sizeof(struct wc_entry *),
1487 							   GFP_NOIO | __GFP_NORETRY |
1488 							   __GFP_NOMEMALLOC | __GFP_NOWARN)))) {
1489 			wb->wc_list = wb->wc_list_inline;
1490 			max_pages = WB_LIST_INLINE;
1491 		}
1492 
1493 		BUG_ON(!wc_add_block(wb, e, GFP_NOIO));
1494 
1495 		wb->wc_list[0] = e;
1496 		wb->wc_list_n = 1;
1497 
1498 		while (wbl->size && wb->wc_list_n < max_pages) {
1499 			f = container_of(wbl->list.prev, struct wc_entry, lru);
1500 			if (read_original_sector(wc, f) !=
1501 			    read_original_sector(wc, e) + (wc->block_size >> SECTOR_SHIFT))
1502 				break;
1503 			if (!wc_add_block(wb, f, GFP_NOWAIT | __GFP_NOWARN))
1504 				break;
1505 			wbl->size--;
1506 			list_del(&f->lru);
1507 			wb->wc_list[wb->wc_list_n++] = f;
1508 			e = f;
1509 		}
1510 		bio_set_op_attrs(&wb->bio, REQ_OP_WRITE, WC_MODE_FUA(wc) * REQ_FUA);
1511 		if (writecache_has_error(wc)) {
1512 			bio->bi_status = BLK_STS_IOERR;
1513 			bio_endio(&wb->bio);
1514 		} else {
1515 			submit_bio(&wb->bio);
1516 		}
1517 
1518 		__writeback_throttle(wc, wbl);
1519 	}
1520 }
1521 
1522 static void __writecache_writeback_ssd(struct dm_writecache *wc, struct writeback_list *wbl)
1523 {
1524 	struct wc_entry *e, *f;
1525 	struct dm_io_region from, to;
1526 	struct copy_struct *c;
1527 
1528 	while (wbl->size) {
1529 		unsigned n_sectors;
1530 
1531 		wbl->size--;
1532 		e = container_of(wbl->list.prev, struct wc_entry, lru);
1533 		list_del(&e->lru);
1534 
1535 		n_sectors = e->wc_list_contiguous << (wc->block_size_bits - SECTOR_SHIFT);
1536 
1537 		from.bdev = wc->ssd_dev->bdev;
1538 		from.sector = cache_sector(wc, e);
1539 		from.count = n_sectors;
1540 		to.bdev = wc->dev->bdev;
1541 		to.sector = read_original_sector(wc, e);
1542 		to.count = n_sectors;
1543 
1544 		c = mempool_alloc(&wc->copy_pool, GFP_NOIO);
1545 		c->wc = wc;
1546 		c->e = e;
1547 		c->n_entries = e->wc_list_contiguous;
1548 
1549 		while ((n_sectors -= wc->block_size >> SECTOR_SHIFT)) {
1550 			wbl->size--;
1551 			f = container_of(wbl->list.prev, struct wc_entry, lru);
1552 			BUG_ON(f != e + 1);
1553 			list_del(&f->lru);
1554 			e = f;
1555 		}
1556 
1557 		dm_kcopyd_copy(wc->dm_kcopyd, &from, 1, &to, 0, writecache_copy_endio, c);
1558 
1559 		__writeback_throttle(wc, wbl);
1560 	}
1561 }
1562 
1563 static void writecache_writeback(struct work_struct *work)
1564 {
1565 	struct dm_writecache *wc = container_of(work, struct dm_writecache, writeback_work);
1566 	struct blk_plug plug;
1567 	struct wc_entry *e, *f, *g;
1568 	struct rb_node *node, *next_node;
1569 	struct list_head skipped;
1570 	struct writeback_list wbl;
1571 	unsigned long n_walked;
1572 
1573 	wc_lock(wc);
1574 restart:
1575 	if (writecache_has_error(wc)) {
1576 		wc_unlock(wc);
1577 		return;
1578 	}
1579 
1580 	if (unlikely(wc->writeback_all)) {
1581 		if (writecache_wait_for_writeback(wc))
1582 			goto restart;
1583 	}
1584 
1585 	if (wc->overwrote_committed) {
1586 		writecache_wait_for_ios(wc, WRITE);
1587 	}
1588 
1589 	n_walked = 0;
1590 	INIT_LIST_HEAD(&skipped);
1591 	INIT_LIST_HEAD(&wbl.list);
1592 	wbl.size = 0;
1593 	while (!list_empty(&wc->lru) &&
1594 	       (wc->writeback_all ||
1595 		wc->freelist_size + wc->writeback_size <= wc->freelist_low_watermark)) {
1596 
1597 		n_walked++;
1598 		if (unlikely(n_walked > WRITEBACK_LATENCY) &&
1599 		    likely(!wc->writeback_all) && likely(!dm_suspended(wc->ti))) {
1600 			queue_work(wc->writeback_wq, &wc->writeback_work);
1601 			break;
1602 		}
1603 
1604 		e = container_of(wc->lru.prev, struct wc_entry, lru);
1605 		BUG_ON(e->write_in_progress);
1606 		if (unlikely(!writecache_entry_is_committed(wc, e))) {
1607 			writecache_flush(wc);
1608 		}
1609 		node = rb_prev(&e->rb_node);
1610 		if (node) {
1611 			f = container_of(node, struct wc_entry, rb_node);
1612 			if (unlikely(read_original_sector(wc, f) ==
1613 				     read_original_sector(wc, e))) {
1614 				BUG_ON(!f->write_in_progress);
1615 				list_del(&e->lru);
1616 				list_add(&e->lru, &skipped);
1617 				cond_resched();
1618 				continue;
1619 			}
1620 		}
1621 		wc->writeback_size++;
1622 		list_del(&e->lru);
1623 		list_add(&e->lru, &wbl.list);
1624 		wbl.size++;
1625 		e->write_in_progress = true;
1626 		e->wc_list_contiguous = 1;
1627 
1628 		f = e;
1629 
1630 		while (1) {
1631 			next_node = rb_next(&f->rb_node);
1632 			if (unlikely(!next_node))
1633 				break;
1634 			g = container_of(next_node, struct wc_entry, rb_node);
1635 			if (read_original_sector(wc, g) ==
1636 			    read_original_sector(wc, f)) {
1637 				f = g;
1638 				continue;
1639 			}
1640 			if (read_original_sector(wc, g) !=
1641 			    read_original_sector(wc, f) + (wc->block_size >> SECTOR_SHIFT))
1642 				break;
1643 			if (unlikely(g->write_in_progress))
1644 				break;
1645 			if (unlikely(!writecache_entry_is_committed(wc, g)))
1646 				break;
1647 
1648 			if (!WC_MODE_PMEM(wc)) {
1649 				if (g != f + 1)
1650 					break;
1651 			}
1652 
1653 			n_walked++;
1654 			//if (unlikely(n_walked > WRITEBACK_LATENCY) && likely(!wc->writeback_all))
1655 			//	break;
1656 
1657 			wc->writeback_size++;
1658 			list_del(&g->lru);
1659 			list_add(&g->lru, &wbl.list);
1660 			wbl.size++;
1661 			g->write_in_progress = true;
1662 			g->wc_list_contiguous = BIO_MAX_PAGES;
1663 			f = g;
1664 			e->wc_list_contiguous++;
1665 			if (unlikely(e->wc_list_contiguous == BIO_MAX_PAGES))
1666 				break;
1667 		}
1668 		cond_resched();
1669 	}
1670 
1671 	if (!list_empty(&skipped)) {
1672 		list_splice_tail(&skipped, &wc->lru);
1673 		/*
1674 		 * If we didn't do any progress, we must wait until some
1675 		 * writeback finishes to avoid burning CPU in a loop
1676 		 */
1677 		if (unlikely(!wbl.size))
1678 			writecache_wait_for_writeback(wc);
1679 	}
1680 
1681 	wc_unlock(wc);
1682 
1683 	blk_start_plug(&plug);
1684 
1685 	if (WC_MODE_PMEM(wc))
1686 		__writecache_writeback_pmem(wc, &wbl);
1687 	else
1688 		__writecache_writeback_ssd(wc, &wbl);
1689 
1690 	blk_finish_plug(&plug);
1691 
1692 	if (unlikely(wc->writeback_all)) {
1693 		wc_lock(wc);
1694 		while (writecache_wait_for_writeback(wc));
1695 		wc_unlock(wc);
1696 	}
1697 }
1698 
1699 static int calculate_memory_size(uint64_t device_size, unsigned block_size,
1700 				 size_t *n_blocks_p, size_t *n_metadata_blocks_p)
1701 {
1702 	uint64_t n_blocks, offset;
1703 	struct wc_entry e;
1704 
1705 	n_blocks = device_size;
1706 	do_div(n_blocks, block_size + sizeof(struct wc_memory_entry));
1707 
1708 	while (1) {
1709 		if (!n_blocks)
1710 			return -ENOSPC;
1711 		/* Verify the following entries[n_blocks] won't overflow */
1712 		if (n_blocks >= ((size_t)-sizeof(struct wc_memory_superblock) /
1713 				 sizeof(struct wc_memory_entry)))
1714 			return -EFBIG;
1715 		offset = offsetof(struct wc_memory_superblock, entries[n_blocks]);
1716 		offset = (offset + block_size - 1) & ~(uint64_t)(block_size - 1);
1717 		if (offset + n_blocks * block_size <= device_size)
1718 			break;
1719 		n_blocks--;
1720 	}
1721 
1722 	/* check if the bit field overflows */
1723 	e.index = n_blocks;
1724 	if (e.index != n_blocks)
1725 		return -EFBIG;
1726 
1727 	if (n_blocks_p)
1728 		*n_blocks_p = n_blocks;
1729 	if (n_metadata_blocks_p)
1730 		*n_metadata_blocks_p = offset >> __ffs(block_size);
1731 	return 0;
1732 }
1733 
1734 static int init_memory(struct dm_writecache *wc)
1735 {
1736 	size_t b;
1737 	int r;
1738 
1739 	r = calculate_memory_size(wc->memory_map_size, wc->block_size, &wc->n_blocks, NULL);
1740 	if (r)
1741 		return r;
1742 
1743 	r = writecache_alloc_entries(wc);
1744 	if (r)
1745 		return r;
1746 
1747 	for (b = 0; b < ARRAY_SIZE(sb(wc)->padding); b++)
1748 		pmem_assign(sb(wc)->padding[b], cpu_to_le64(0));
1749 	pmem_assign(sb(wc)->version, cpu_to_le32(MEMORY_SUPERBLOCK_VERSION));
1750 	pmem_assign(sb(wc)->block_size, cpu_to_le32(wc->block_size));
1751 	pmem_assign(sb(wc)->n_blocks, cpu_to_le64(wc->n_blocks));
1752 	pmem_assign(sb(wc)->seq_count, cpu_to_le64(0));
1753 
1754 	for (b = 0; b < wc->n_blocks; b++)
1755 		write_original_sector_seq_count(wc, &wc->entries[b], -1, -1);
1756 
1757 	writecache_flush_all_metadata(wc);
1758 	writecache_commit_flushed(wc);
1759 	pmem_assign(sb(wc)->magic, cpu_to_le32(MEMORY_SUPERBLOCK_MAGIC));
1760 	writecache_flush_region(wc, &sb(wc)->magic, sizeof sb(wc)->magic);
1761 	writecache_commit_flushed(wc);
1762 
1763 	return 0;
1764 }
1765 
1766 static void writecache_dtr(struct dm_target *ti)
1767 {
1768 	struct dm_writecache *wc = ti->private;
1769 
1770 	if (!wc)
1771 		return;
1772 
1773 	if (wc->endio_thread)
1774 		kthread_stop(wc->endio_thread);
1775 
1776 	if (wc->flush_thread)
1777 		kthread_stop(wc->flush_thread);
1778 
1779 	bioset_exit(&wc->bio_set);
1780 
1781 	mempool_exit(&wc->copy_pool);
1782 
1783 	if (wc->writeback_wq)
1784 		destroy_workqueue(wc->writeback_wq);
1785 
1786 	if (wc->dev)
1787 		dm_put_device(ti, wc->dev);
1788 
1789 	if (wc->ssd_dev)
1790 		dm_put_device(ti, wc->ssd_dev);
1791 
1792 	if (wc->entries)
1793 		vfree(wc->entries);
1794 
1795 	if (wc->memory_map) {
1796 		if (WC_MODE_PMEM(wc))
1797 			persistent_memory_release(wc);
1798 		else
1799 			vfree(wc->memory_map);
1800 	}
1801 
1802 	if (wc->dm_kcopyd)
1803 		dm_kcopyd_client_destroy(wc->dm_kcopyd);
1804 
1805 	if (wc->dm_io)
1806 		dm_io_client_destroy(wc->dm_io);
1807 
1808 	if (wc->dirty_bitmap)
1809 		vfree(wc->dirty_bitmap);
1810 
1811 	kfree(wc);
1812 }
1813 
1814 static int writecache_ctr(struct dm_target *ti, unsigned argc, char **argv)
1815 {
1816 	struct dm_writecache *wc;
1817 	struct dm_arg_set as;
1818 	const char *string;
1819 	unsigned opt_params;
1820 	size_t offset, data_size;
1821 	int i, r;
1822 	char dummy;
1823 	int high_wm_percent = HIGH_WATERMARK;
1824 	int low_wm_percent = LOW_WATERMARK;
1825 	uint64_t x;
1826 	struct wc_memory_superblock s;
1827 
1828 	static struct dm_arg _args[] = {
1829 		{0, 10, "Invalid number of feature args"},
1830 	};
1831 
1832 	as.argc = argc;
1833 	as.argv = argv;
1834 
1835 	wc = kzalloc(sizeof(struct dm_writecache), GFP_KERNEL);
1836 	if (!wc) {
1837 		ti->error = "Cannot allocate writecache structure";
1838 		r = -ENOMEM;
1839 		goto bad;
1840 	}
1841 	ti->private = wc;
1842 	wc->ti = ti;
1843 
1844 	mutex_init(&wc->lock);
1845 	writecache_poison_lists(wc);
1846 	init_waitqueue_head(&wc->freelist_wait);
1847 	timer_setup(&wc->autocommit_timer, writecache_autocommit_timer, 0);
1848 
1849 	for (i = 0; i < 2; i++) {
1850 		atomic_set(&wc->bio_in_progress[i], 0);
1851 		init_waitqueue_head(&wc->bio_in_progress_wait[i]);
1852 	}
1853 
1854 	wc->dm_io = dm_io_client_create();
1855 	if (IS_ERR(wc->dm_io)) {
1856 		r = PTR_ERR(wc->dm_io);
1857 		ti->error = "Unable to allocate dm-io client";
1858 		wc->dm_io = NULL;
1859 		goto bad;
1860 	}
1861 
1862 	wc->writeback_wq = alloc_workqueue("writecache-writeabck", WQ_MEM_RECLAIM, 1);
1863 	if (!wc->writeback_wq) {
1864 		r = -ENOMEM;
1865 		ti->error = "Could not allocate writeback workqueue";
1866 		goto bad;
1867 	}
1868 	INIT_WORK(&wc->writeback_work, writecache_writeback);
1869 	INIT_WORK(&wc->flush_work, writecache_flush_work);
1870 
1871 	raw_spin_lock_init(&wc->endio_list_lock);
1872 	INIT_LIST_HEAD(&wc->endio_list);
1873 	wc->endio_thread = kthread_create(writecache_endio_thread, wc, "writecache_endio");
1874 	if (IS_ERR(wc->endio_thread)) {
1875 		r = PTR_ERR(wc->endio_thread);
1876 		wc->endio_thread = NULL;
1877 		ti->error = "Couldn't spawn endio thread";
1878 		goto bad;
1879 	}
1880 	wake_up_process(wc->endio_thread);
1881 
1882 	/*
1883 	 * Parse the mode (pmem or ssd)
1884 	 */
1885 	string = dm_shift_arg(&as);
1886 	if (!string)
1887 		goto bad_arguments;
1888 
1889 	if (!strcasecmp(string, "s")) {
1890 		wc->pmem_mode = false;
1891 	} else if (!strcasecmp(string, "p")) {
1892 #ifdef DM_WRITECACHE_HAS_PMEM
1893 		wc->pmem_mode = true;
1894 		wc->writeback_fua = true;
1895 #else
1896 		/*
1897 		 * If the architecture doesn't support persistent memory or
1898 		 * the kernel doesn't support any DAX drivers, this driver can
1899 		 * only be used in SSD-only mode.
1900 		 */
1901 		r = -EOPNOTSUPP;
1902 		ti->error = "Persistent memory or DAX not supported on this system";
1903 		goto bad;
1904 #endif
1905 	} else {
1906 		goto bad_arguments;
1907 	}
1908 
1909 	if (WC_MODE_PMEM(wc)) {
1910 		r = bioset_init(&wc->bio_set, BIO_POOL_SIZE,
1911 				offsetof(struct writeback_struct, bio),
1912 				BIOSET_NEED_BVECS);
1913 		if (r) {
1914 			ti->error = "Could not allocate bio set";
1915 			goto bad;
1916 		}
1917 	} else {
1918 		r = mempool_init_kmalloc_pool(&wc->copy_pool, 1, sizeof(struct copy_struct));
1919 		if (r) {
1920 			ti->error = "Could not allocate mempool";
1921 			goto bad;
1922 		}
1923 	}
1924 
1925 	/*
1926 	 * Parse the origin data device
1927 	 */
1928 	string = dm_shift_arg(&as);
1929 	if (!string)
1930 		goto bad_arguments;
1931 	r = dm_get_device(ti, string, dm_table_get_mode(ti->table), &wc->dev);
1932 	if (r) {
1933 		ti->error = "Origin data device lookup failed";
1934 		goto bad;
1935 	}
1936 
1937 	/*
1938 	 * Parse cache data device (be it pmem or ssd)
1939 	 */
1940 	string = dm_shift_arg(&as);
1941 	if (!string)
1942 		goto bad_arguments;
1943 
1944 	r = dm_get_device(ti, string, dm_table_get_mode(ti->table), &wc->ssd_dev);
1945 	if (r) {
1946 		ti->error = "Cache data device lookup failed";
1947 		goto bad;
1948 	}
1949 	wc->memory_map_size = i_size_read(wc->ssd_dev->bdev->bd_inode);
1950 
1951 	/*
1952 	 * Parse the cache block size
1953 	 */
1954 	string = dm_shift_arg(&as);
1955 	if (!string)
1956 		goto bad_arguments;
1957 	if (sscanf(string, "%u%c", &wc->block_size, &dummy) != 1 ||
1958 	    wc->block_size < 512 || wc->block_size > PAGE_SIZE ||
1959 	    (wc->block_size & (wc->block_size - 1))) {
1960 		r = -EINVAL;
1961 		ti->error = "Invalid block size";
1962 		goto bad;
1963 	}
1964 	wc->block_size_bits = __ffs(wc->block_size);
1965 
1966 	wc->max_writeback_jobs = MAX_WRITEBACK_JOBS;
1967 	wc->autocommit_blocks = !WC_MODE_PMEM(wc) ? AUTOCOMMIT_BLOCKS_SSD : AUTOCOMMIT_BLOCKS_PMEM;
1968 	wc->autocommit_jiffies = msecs_to_jiffies(AUTOCOMMIT_MSEC);
1969 
1970 	/*
1971 	 * Parse optional arguments
1972 	 */
1973 	r = dm_read_arg_group(_args, &as, &opt_params, &ti->error);
1974 	if (r)
1975 		goto bad;
1976 
1977 	while (opt_params) {
1978 		string = dm_shift_arg(&as), opt_params--;
1979 		if (!strcasecmp(string, "start_sector") && opt_params >= 1) {
1980 			unsigned long long start_sector;
1981 			string = dm_shift_arg(&as), opt_params--;
1982 			if (sscanf(string, "%llu%c", &start_sector, &dummy) != 1)
1983 				goto invalid_optional;
1984 			wc->start_sector = start_sector;
1985 			if (wc->start_sector != start_sector ||
1986 			    wc->start_sector >= wc->memory_map_size >> SECTOR_SHIFT)
1987 				goto invalid_optional;
1988 		} else if (!strcasecmp(string, "high_watermark") && opt_params >= 1) {
1989 			string = dm_shift_arg(&as), opt_params--;
1990 			if (sscanf(string, "%d%c", &high_wm_percent, &dummy) != 1)
1991 				goto invalid_optional;
1992 			if (high_wm_percent < 0 || high_wm_percent > 100)
1993 				goto invalid_optional;
1994 			wc->high_wm_percent_set = true;
1995 		} else if (!strcasecmp(string, "low_watermark") && opt_params >= 1) {
1996 			string = dm_shift_arg(&as), opt_params--;
1997 			if (sscanf(string, "%d%c", &low_wm_percent, &dummy) != 1)
1998 				goto invalid_optional;
1999 			if (low_wm_percent < 0 || low_wm_percent > 100)
2000 				goto invalid_optional;
2001 			wc->low_wm_percent_set = true;
2002 		} else if (!strcasecmp(string, "writeback_jobs") && opt_params >= 1) {
2003 			string = dm_shift_arg(&as), opt_params--;
2004 			if (sscanf(string, "%u%c", &wc->max_writeback_jobs, &dummy) != 1)
2005 				goto invalid_optional;
2006 			wc->max_writeback_jobs_set = true;
2007 		} else if (!strcasecmp(string, "autocommit_blocks") && opt_params >= 1) {
2008 			string = dm_shift_arg(&as), opt_params--;
2009 			if (sscanf(string, "%u%c", &wc->autocommit_blocks, &dummy) != 1)
2010 				goto invalid_optional;
2011 			wc->autocommit_blocks_set = true;
2012 		} else if (!strcasecmp(string, "autocommit_time") && opt_params >= 1) {
2013 			unsigned autocommit_msecs;
2014 			string = dm_shift_arg(&as), opt_params--;
2015 			if (sscanf(string, "%u%c", &autocommit_msecs, &dummy) != 1)
2016 				goto invalid_optional;
2017 			if (autocommit_msecs > 3600000)
2018 				goto invalid_optional;
2019 			wc->autocommit_jiffies = msecs_to_jiffies(autocommit_msecs);
2020 			wc->autocommit_time_set = true;
2021 		} else if (!strcasecmp(string, "fua")) {
2022 			if (WC_MODE_PMEM(wc)) {
2023 				wc->writeback_fua = true;
2024 				wc->writeback_fua_set = true;
2025 			} else goto invalid_optional;
2026 		} else if (!strcasecmp(string, "nofua")) {
2027 			if (WC_MODE_PMEM(wc)) {
2028 				wc->writeback_fua = false;
2029 				wc->writeback_fua_set = true;
2030 			} else goto invalid_optional;
2031 		} else {
2032 invalid_optional:
2033 			r = -EINVAL;
2034 			ti->error = "Invalid optional argument";
2035 			goto bad;
2036 		}
2037 	}
2038 
2039 	if (high_wm_percent < low_wm_percent) {
2040 		r = -EINVAL;
2041 		ti->error = "High watermark must be greater than or equal to low watermark";
2042 		goto bad;
2043 	}
2044 
2045 	if (WC_MODE_PMEM(wc)) {
2046 		r = persistent_memory_claim(wc);
2047 		if (r) {
2048 			ti->error = "Unable to map persistent memory for cache";
2049 			goto bad;
2050 		}
2051 	} else {
2052 		struct dm_io_region region;
2053 		struct dm_io_request req;
2054 		size_t n_blocks, n_metadata_blocks;
2055 		uint64_t n_bitmap_bits;
2056 
2057 		wc->memory_map_size -= (uint64_t)wc->start_sector << SECTOR_SHIFT;
2058 
2059 		bio_list_init(&wc->flush_list);
2060 		wc->flush_thread = kthread_create(writecache_flush_thread, wc, "dm_writecache_flush");
2061 		if (IS_ERR(wc->flush_thread)) {
2062 			r = PTR_ERR(wc->flush_thread);
2063 			wc->flush_thread = NULL;
2064 			ti->error = "Couldn't spawn flush thread";
2065 			goto bad;
2066 		}
2067 		wake_up_process(wc->flush_thread);
2068 
2069 		r = calculate_memory_size(wc->memory_map_size, wc->block_size,
2070 					  &n_blocks, &n_metadata_blocks);
2071 		if (r) {
2072 			ti->error = "Invalid device size";
2073 			goto bad;
2074 		}
2075 
2076 		n_bitmap_bits = (((uint64_t)n_metadata_blocks << wc->block_size_bits) +
2077 				 BITMAP_GRANULARITY - 1) / BITMAP_GRANULARITY;
2078 		/* this is limitation of test_bit functions */
2079 		if (n_bitmap_bits > 1U << 31) {
2080 			r = -EFBIG;
2081 			ti->error = "Invalid device size";
2082 			goto bad;
2083 		}
2084 
2085 		wc->memory_map = vmalloc(n_metadata_blocks << wc->block_size_bits);
2086 		if (!wc->memory_map) {
2087 			r = -ENOMEM;
2088 			ti->error = "Unable to allocate memory for metadata";
2089 			goto bad;
2090 		}
2091 
2092 		wc->dm_kcopyd = dm_kcopyd_client_create(&dm_kcopyd_throttle);
2093 		if (IS_ERR(wc->dm_kcopyd)) {
2094 			r = PTR_ERR(wc->dm_kcopyd);
2095 			ti->error = "Unable to allocate dm-kcopyd client";
2096 			wc->dm_kcopyd = NULL;
2097 			goto bad;
2098 		}
2099 
2100 		wc->metadata_sectors = n_metadata_blocks << (wc->block_size_bits - SECTOR_SHIFT);
2101 		wc->dirty_bitmap_size = (n_bitmap_bits + BITS_PER_LONG - 1) /
2102 			BITS_PER_LONG * sizeof(unsigned long);
2103 		wc->dirty_bitmap = vzalloc(wc->dirty_bitmap_size);
2104 		if (!wc->dirty_bitmap) {
2105 			r = -ENOMEM;
2106 			ti->error = "Unable to allocate dirty bitmap";
2107 			goto bad;
2108 		}
2109 
2110 		region.bdev = wc->ssd_dev->bdev;
2111 		region.sector = wc->start_sector;
2112 		region.count = wc->metadata_sectors;
2113 		req.bi_op = REQ_OP_READ;
2114 		req.bi_op_flags = REQ_SYNC;
2115 		req.mem.type = DM_IO_VMA;
2116 		req.mem.ptr.vma = (char *)wc->memory_map;
2117 		req.client = wc->dm_io;
2118 		req.notify.fn = NULL;
2119 
2120 		r = dm_io(&req, 1, &region, NULL);
2121 		if (r) {
2122 			ti->error = "Unable to read metadata";
2123 			goto bad;
2124 		}
2125 	}
2126 
2127 	r = memcpy_mcsafe(&s, sb(wc), sizeof(struct wc_memory_superblock));
2128 	if (r) {
2129 		ti->error = "Hardware memory error when reading superblock";
2130 		goto bad;
2131 	}
2132 	if (!le32_to_cpu(s.magic) && !le32_to_cpu(s.version)) {
2133 		r = init_memory(wc);
2134 		if (r) {
2135 			ti->error = "Unable to initialize device";
2136 			goto bad;
2137 		}
2138 		r = memcpy_mcsafe(&s, sb(wc), sizeof(struct wc_memory_superblock));
2139 		if (r) {
2140 			ti->error = "Hardware memory error when reading superblock";
2141 			goto bad;
2142 		}
2143 	}
2144 
2145 	if (le32_to_cpu(s.magic) != MEMORY_SUPERBLOCK_MAGIC) {
2146 		ti->error = "Invalid magic in the superblock";
2147 		r = -EINVAL;
2148 		goto bad;
2149 	}
2150 
2151 	if (le32_to_cpu(s.version) != MEMORY_SUPERBLOCK_VERSION) {
2152 		ti->error = "Invalid version in the superblock";
2153 		r = -EINVAL;
2154 		goto bad;
2155 	}
2156 
2157 	if (le32_to_cpu(s.block_size) != wc->block_size) {
2158 		ti->error = "Block size does not match superblock";
2159 		r = -EINVAL;
2160 		goto bad;
2161 	}
2162 
2163 	wc->n_blocks = le64_to_cpu(s.n_blocks);
2164 
2165 	offset = wc->n_blocks * sizeof(struct wc_memory_entry);
2166 	if (offset / sizeof(struct wc_memory_entry) != le64_to_cpu(sb(wc)->n_blocks)) {
2167 overflow:
2168 		ti->error = "Overflow in size calculation";
2169 		r = -EINVAL;
2170 		goto bad;
2171 	}
2172 	offset += sizeof(struct wc_memory_superblock);
2173 	if (offset < sizeof(struct wc_memory_superblock))
2174 		goto overflow;
2175 	offset = (offset + wc->block_size - 1) & ~(size_t)(wc->block_size - 1);
2176 	data_size = wc->n_blocks * (size_t)wc->block_size;
2177 	if (!offset || (data_size / wc->block_size != wc->n_blocks) ||
2178 	    (offset + data_size < offset))
2179 		goto overflow;
2180 	if (offset + data_size > wc->memory_map_size) {
2181 		ti->error = "Memory area is too small";
2182 		r = -EINVAL;
2183 		goto bad;
2184 	}
2185 
2186 	wc->metadata_sectors = offset >> SECTOR_SHIFT;
2187 	wc->block_start = (char *)sb(wc) + offset;
2188 
2189 	x = (uint64_t)wc->n_blocks * (100 - high_wm_percent);
2190 	x += 50;
2191 	do_div(x, 100);
2192 	wc->freelist_high_watermark = x;
2193 	x = (uint64_t)wc->n_blocks * (100 - low_wm_percent);
2194 	x += 50;
2195 	do_div(x, 100);
2196 	wc->freelist_low_watermark = x;
2197 
2198 	r = writecache_alloc_entries(wc);
2199 	if (r) {
2200 		ti->error = "Cannot allocate memory";
2201 		goto bad;
2202 	}
2203 
2204 	ti->num_flush_bios = 1;
2205 	ti->flush_supported = true;
2206 	ti->num_discard_bios = 1;
2207 
2208 	if (WC_MODE_PMEM(wc))
2209 		persistent_memory_flush_cache(wc->memory_map, wc->memory_map_size);
2210 
2211 	return 0;
2212 
2213 bad_arguments:
2214 	r = -EINVAL;
2215 	ti->error = "Bad arguments";
2216 bad:
2217 	writecache_dtr(ti);
2218 	return r;
2219 }
2220 
2221 static void writecache_status(struct dm_target *ti, status_type_t type,
2222 			      unsigned status_flags, char *result, unsigned maxlen)
2223 {
2224 	struct dm_writecache *wc = ti->private;
2225 	unsigned extra_args;
2226 	unsigned sz = 0;
2227 	uint64_t x;
2228 
2229 	switch (type) {
2230 	case STATUSTYPE_INFO:
2231 		DMEMIT("%ld %llu %llu %llu", writecache_has_error(wc),
2232 		       (unsigned long long)wc->n_blocks, (unsigned long long)wc->freelist_size,
2233 		       (unsigned long long)wc->writeback_size);
2234 		break;
2235 	case STATUSTYPE_TABLE:
2236 		DMEMIT("%c %s %s %u ", WC_MODE_PMEM(wc) ? 'p' : 's',
2237 				wc->dev->name, wc->ssd_dev->name, wc->block_size);
2238 		extra_args = 0;
2239 		if (wc->start_sector)
2240 			extra_args += 2;
2241 		if (wc->high_wm_percent_set)
2242 			extra_args += 2;
2243 		if (wc->low_wm_percent_set)
2244 			extra_args += 2;
2245 		if (wc->max_writeback_jobs_set)
2246 			extra_args += 2;
2247 		if (wc->autocommit_blocks_set)
2248 			extra_args += 2;
2249 		if (wc->autocommit_time_set)
2250 			extra_args += 2;
2251 		if (wc->writeback_fua_set)
2252 			extra_args++;
2253 
2254 		DMEMIT("%u", extra_args);
2255 		if (wc->start_sector)
2256 			DMEMIT(" start_sector %llu", (unsigned long long)wc->start_sector);
2257 		if (wc->high_wm_percent_set) {
2258 			x = (uint64_t)wc->freelist_high_watermark * 100;
2259 			x += wc->n_blocks / 2;
2260 			do_div(x, (size_t)wc->n_blocks);
2261 			DMEMIT(" high_watermark %u", 100 - (unsigned)x);
2262 		}
2263 		if (wc->low_wm_percent_set) {
2264 			x = (uint64_t)wc->freelist_low_watermark * 100;
2265 			x += wc->n_blocks / 2;
2266 			do_div(x, (size_t)wc->n_blocks);
2267 			DMEMIT(" low_watermark %u", 100 - (unsigned)x);
2268 		}
2269 		if (wc->max_writeback_jobs_set)
2270 			DMEMIT(" writeback_jobs %u", wc->max_writeback_jobs);
2271 		if (wc->autocommit_blocks_set)
2272 			DMEMIT(" autocommit_blocks %u", wc->autocommit_blocks);
2273 		if (wc->autocommit_time_set)
2274 			DMEMIT(" autocommit_time %u", jiffies_to_msecs(wc->autocommit_jiffies));
2275 		if (wc->writeback_fua_set)
2276 			DMEMIT(" %sfua", wc->writeback_fua ? "" : "no");
2277 		break;
2278 	}
2279 }
2280 
2281 static struct target_type writecache_target = {
2282 	.name			= "writecache",
2283 	.version		= {1, 1, 1},
2284 	.module			= THIS_MODULE,
2285 	.ctr			= writecache_ctr,
2286 	.dtr			= writecache_dtr,
2287 	.status			= writecache_status,
2288 	.postsuspend		= writecache_suspend,
2289 	.resume			= writecache_resume,
2290 	.message		= writecache_message,
2291 	.map			= writecache_map,
2292 	.end_io			= writecache_end_io,
2293 	.iterate_devices	= writecache_iterate_devices,
2294 	.io_hints		= writecache_io_hints,
2295 };
2296 
2297 static int __init dm_writecache_init(void)
2298 {
2299 	int r;
2300 
2301 	r = dm_register_target(&writecache_target);
2302 	if (r < 0) {
2303 		DMERR("register failed %d", r);
2304 		return r;
2305 	}
2306 
2307 	return 0;
2308 }
2309 
2310 static void __exit dm_writecache_exit(void)
2311 {
2312 	dm_unregister_target(&writecache_target);
2313 }
2314 
2315 module_init(dm_writecache_init);
2316 module_exit(dm_writecache_exit);
2317 
2318 MODULE_DESCRIPTION(DM_NAME " writecache target");
2319 MODULE_AUTHOR("Mikulas Patocka <dm-devel@redhat.com>");
2320 MODULE_LICENSE("GPL");
2321