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