xref: /openbmc/linux/drivers/md/raid5-ppl.c (revision b4bc93bd76d4da32600795cd323c971f00a2e788)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Partial Parity Log for closing the RAID5 write hole
4  * Copyright (c) 2017, Intel Corporation.
5  */
6 
7 #include <linux/kernel.h>
8 #include <linux/blkdev.h>
9 #include <linux/slab.h>
10 #include <linux/crc32c.h>
11 #include <linux/async_tx.h>
12 #include <linux/raid/md_p.h>
13 #include "md.h"
14 #include "raid5.h"
15 #include "raid5-log.h"
16 
17 /*
18  * PPL consists of a 4KB header (struct ppl_header) and at least 128KB for
19  * partial parity data. The header contains an array of entries
20  * (struct ppl_header_entry) which describe the logged write requests.
21  * Partial parity for the entries comes after the header, written in the same
22  * sequence as the entries:
23  *
24  * Header
25  *   entry0
26  *   ...
27  *   entryN
28  * PP data
29  *   PP for entry0
30  *   ...
31  *   PP for entryN
32  *
33  * An entry describes one or more consecutive stripe_heads, up to a full
34  * stripe. The modifed raid data chunks form an m-by-n matrix, where m is the
35  * number of stripe_heads in the entry and n is the number of modified data
36  * disks. Every stripe_head in the entry must write to the same data disks.
37  * An example of a valid case described by a single entry (writes to the first
38  * stripe of a 4 disk array, 16k chunk size):
39  *
40  * sh->sector   dd0   dd1   dd2    ppl
41  *            +-----+-----+-----+
42  * 0          | --- | --- | --- | +----+
43  * 8          | -W- | -W- | --- | | pp |   data_sector = 8
44  * 16         | -W- | -W- | --- | | pp |   data_size = 3 * 2 * 4k
45  * 24         | -W- | -W- | --- | | pp |   pp_size = 3 * 4k
46  *            +-----+-----+-----+ +----+
47  *
48  * data_sector is the first raid sector of the modified data, data_size is the
49  * total size of modified data and pp_size is the size of partial parity for
50  * this entry. Entries for full stripe writes contain no partial parity
51  * (pp_size = 0), they only mark the stripes for which parity should be
52  * recalculated after an unclean shutdown. Every entry holds a checksum of its
53  * partial parity, the header also has a checksum of the header itself.
54  *
55  * A write request is always logged to the PPL instance stored on the parity
56  * disk of the corresponding stripe. For each member disk there is one ppl_log
57  * used to handle logging for this disk, independently from others. They are
58  * grouped in child_logs array in struct ppl_conf, which is assigned to
59  * r5conf->log_private.
60  *
61  * ppl_io_unit represents a full PPL write, header_page contains the ppl_header.
62  * PPL entries for logged stripes are added in ppl_log_stripe(). A stripe_head
63  * can be appended to the last entry if it meets the conditions for a valid
64  * entry described above, otherwise a new entry is added. Checksums of entries
65  * are calculated incrementally as stripes containing partial parity are being
66  * added. ppl_submit_iounit() calculates the checksum of the header and submits
67  * a bio containing the header page and partial parity pages (sh->ppl_page) for
68  * all stripes of the io_unit. When the PPL write completes, the stripes
69  * associated with the io_unit are released and raid5d starts writing their data
70  * and parity. When all stripes are written, the io_unit is freed and the next
71  * can be submitted.
72  *
73  * An io_unit is used to gather stripes until it is submitted or becomes full
74  * (if the maximum number of entries or size of PPL is reached). Another io_unit
75  * can't be submitted until the previous has completed (PPL and stripe
76  * data+parity is written). The log->io_list tracks all io_units of a log
77  * (for a single member disk). New io_units are added to the end of the list
78  * and the first io_unit is submitted, if it is not submitted already.
79  * The current io_unit accepting new stripes is always at the end of the list.
80  *
81  * If write-back cache is enabled for any of the disks in the array, its data
82  * must be flushed before next io_unit is submitted.
83  */
84 
85 #define PPL_SPACE_SIZE (128 * 1024)
86 
87 struct ppl_conf {
88 	struct mddev *mddev;
89 
90 	/* array of child logs, one for each raid disk */
91 	struct ppl_log *child_logs;
92 	int count;
93 
94 	int block_size;		/* the logical block size used for data_sector
95 				 * in ppl_header_entry */
96 	u32 signature;		/* raid array identifier */
97 	atomic64_t seq;		/* current log write sequence number */
98 
99 	struct kmem_cache *io_kc;
100 	mempool_t io_pool;
101 	struct bio_set bs;
102 	struct bio_set flush_bs;
103 
104 	/* used only for recovery */
105 	int recovered_entries;
106 	int mismatch_count;
107 
108 	/* stripes to retry if failed to allocate io_unit */
109 	struct list_head no_mem_stripes;
110 	spinlock_t no_mem_stripes_lock;
111 
112 	unsigned short write_hint;
113 };
114 
115 struct ppl_log {
116 	struct ppl_conf *ppl_conf;	/* shared between all log instances */
117 
118 	struct md_rdev *rdev;		/* array member disk associated with
119 					 * this log instance */
120 	struct mutex io_mutex;
121 	struct ppl_io_unit *current_io;	/* current io_unit accepting new data
122 					 * always at the end of io_list */
123 	spinlock_t io_list_lock;
124 	struct list_head io_list;	/* all io_units of this log */
125 
126 	sector_t next_io_sector;
127 	unsigned int entry_space;
128 	bool use_multippl;
129 	bool wb_cache_on;
130 	unsigned long disk_flush_bitmap;
131 };
132 
133 #define PPL_IO_INLINE_BVECS 32
134 
135 struct ppl_io_unit {
136 	struct ppl_log *log;
137 
138 	struct page *header_page;	/* for ppl_header */
139 
140 	unsigned int entries_count;	/* number of entries in ppl_header */
141 	unsigned int pp_size;		/* total size current of partial parity */
142 
143 	u64 seq;			/* sequence number of this log write */
144 	struct list_head log_sibling;	/* log->io_list */
145 
146 	struct list_head stripe_list;	/* stripes added to the io_unit */
147 	atomic_t pending_stripes;	/* how many stripes not written to raid */
148 	atomic_t pending_flushes;	/* how many disk flushes are in progress */
149 
150 	bool submitted;			/* true if write to log started */
151 
152 	/* inline bio and its biovec for submitting the iounit */
153 	struct bio bio;
154 	struct bio_vec biovec[PPL_IO_INLINE_BVECS];
155 };
156 
157 struct dma_async_tx_descriptor *
158 ops_run_partial_parity(struct stripe_head *sh, struct raid5_percpu *percpu,
159 		       struct dma_async_tx_descriptor *tx)
160 {
161 	int disks = sh->disks;
162 	struct page **srcs = percpu->scribble;
163 	int count = 0, pd_idx = sh->pd_idx, i;
164 	struct async_submit_ctl submit;
165 
166 	pr_debug("%s: stripe %llu\n", __func__, (unsigned long long)sh->sector);
167 
168 	/*
169 	 * Partial parity is the XOR of stripe data chunks that are not changed
170 	 * during the write request. Depending on available data
171 	 * (read-modify-write vs. reconstruct-write case) we calculate it
172 	 * differently.
173 	 */
174 	if (sh->reconstruct_state == reconstruct_state_prexor_drain_run) {
175 		/*
176 		 * rmw: xor old data and parity from updated disks
177 		 * This is calculated earlier by ops_run_prexor5() so just copy
178 		 * the parity dev page.
179 		 */
180 		srcs[count++] = sh->dev[pd_idx].page;
181 	} else if (sh->reconstruct_state == reconstruct_state_drain_run) {
182 		/* rcw: xor data from all not updated disks */
183 		for (i = disks; i--;) {
184 			struct r5dev *dev = &sh->dev[i];
185 			if (test_bit(R5_UPTODATE, &dev->flags))
186 				srcs[count++] = dev->page;
187 		}
188 	} else {
189 		return tx;
190 	}
191 
192 	init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST, tx,
193 			  NULL, sh, (void *) (srcs + sh->disks + 2));
194 
195 	if (count == 1)
196 		tx = async_memcpy(sh->ppl_page, srcs[0], 0, 0, PAGE_SIZE,
197 				  &submit);
198 	else
199 		tx = async_xor(sh->ppl_page, srcs, 0, count, PAGE_SIZE,
200 			       &submit);
201 
202 	return tx;
203 }
204 
205 static void *ppl_io_pool_alloc(gfp_t gfp_mask, void *pool_data)
206 {
207 	struct kmem_cache *kc = pool_data;
208 	struct ppl_io_unit *io;
209 
210 	io = kmem_cache_alloc(kc, gfp_mask);
211 	if (!io)
212 		return NULL;
213 
214 	io->header_page = alloc_page(gfp_mask);
215 	if (!io->header_page) {
216 		kmem_cache_free(kc, io);
217 		return NULL;
218 	}
219 
220 	return io;
221 }
222 
223 static void ppl_io_pool_free(void *element, void *pool_data)
224 {
225 	struct kmem_cache *kc = pool_data;
226 	struct ppl_io_unit *io = element;
227 
228 	__free_page(io->header_page);
229 	kmem_cache_free(kc, io);
230 }
231 
232 static struct ppl_io_unit *ppl_new_iounit(struct ppl_log *log,
233 					  struct stripe_head *sh)
234 {
235 	struct ppl_conf *ppl_conf = log->ppl_conf;
236 	struct ppl_io_unit *io;
237 	struct ppl_header *pplhdr;
238 	struct page *header_page;
239 
240 	io = mempool_alloc(&ppl_conf->io_pool, GFP_NOWAIT);
241 	if (!io)
242 		return NULL;
243 
244 	header_page = io->header_page;
245 	memset(io, 0, sizeof(*io));
246 	io->header_page = header_page;
247 
248 	io->log = log;
249 	INIT_LIST_HEAD(&io->log_sibling);
250 	INIT_LIST_HEAD(&io->stripe_list);
251 	atomic_set(&io->pending_stripes, 0);
252 	atomic_set(&io->pending_flushes, 0);
253 	bio_init(&io->bio, log->rdev->bdev, io->biovec, PPL_IO_INLINE_BVECS,
254 		 REQ_OP_WRITE | REQ_FUA);
255 
256 	pplhdr = page_address(io->header_page);
257 	clear_page(pplhdr);
258 	memset(pplhdr->reserved, 0xff, PPL_HDR_RESERVED);
259 	pplhdr->signature = cpu_to_le32(ppl_conf->signature);
260 
261 	io->seq = atomic64_add_return(1, &ppl_conf->seq);
262 	pplhdr->generation = cpu_to_le64(io->seq);
263 
264 	return io;
265 }
266 
267 static int ppl_log_stripe(struct ppl_log *log, struct stripe_head *sh)
268 {
269 	struct ppl_io_unit *io = log->current_io;
270 	struct ppl_header_entry *e = NULL;
271 	struct ppl_header *pplhdr;
272 	int i;
273 	sector_t data_sector = 0;
274 	int data_disks = 0;
275 	struct r5conf *conf = sh->raid_conf;
276 
277 	pr_debug("%s: stripe: %llu\n", __func__, (unsigned long long)sh->sector);
278 
279 	/* check if current io_unit is full */
280 	if (io && (io->pp_size == log->entry_space ||
281 		   io->entries_count == PPL_HDR_MAX_ENTRIES)) {
282 		pr_debug("%s: add io_unit blocked by seq: %llu\n",
283 			 __func__, io->seq);
284 		io = NULL;
285 	}
286 
287 	/* add a new unit if there is none or the current is full */
288 	if (!io) {
289 		io = ppl_new_iounit(log, sh);
290 		if (!io)
291 			return -ENOMEM;
292 		spin_lock_irq(&log->io_list_lock);
293 		list_add_tail(&io->log_sibling, &log->io_list);
294 		spin_unlock_irq(&log->io_list_lock);
295 
296 		log->current_io = io;
297 	}
298 
299 	for (i = 0; i < sh->disks; i++) {
300 		struct r5dev *dev = &sh->dev[i];
301 
302 		if (i != sh->pd_idx && test_bit(R5_Wantwrite, &dev->flags)) {
303 			if (!data_disks || dev->sector < data_sector)
304 				data_sector = dev->sector;
305 			data_disks++;
306 		}
307 	}
308 	BUG_ON(!data_disks);
309 
310 	pr_debug("%s: seq: %llu data_sector: %llu data_disks: %d\n", __func__,
311 		 io->seq, (unsigned long long)data_sector, data_disks);
312 
313 	pplhdr = page_address(io->header_page);
314 
315 	if (io->entries_count > 0) {
316 		struct ppl_header_entry *last =
317 				&pplhdr->entries[io->entries_count - 1];
318 		struct stripe_head *sh_last = list_last_entry(
319 				&io->stripe_list, struct stripe_head, log_list);
320 		u64 data_sector_last = le64_to_cpu(last->data_sector);
321 		u32 data_size_last = le32_to_cpu(last->data_size);
322 
323 		/*
324 		 * Check if we can append the stripe to the last entry. It must
325 		 * be just after the last logged stripe and write to the same
326 		 * disks. Use bit shift and logarithm to avoid 64-bit division.
327 		 */
328 		if ((sh->sector == sh_last->sector + RAID5_STRIPE_SECTORS(conf)) &&
329 		    (data_sector >> ilog2(conf->chunk_sectors) ==
330 		     data_sector_last >> ilog2(conf->chunk_sectors)) &&
331 		    ((data_sector - data_sector_last) * data_disks ==
332 		     data_size_last >> 9))
333 			e = last;
334 	}
335 
336 	if (!e) {
337 		e = &pplhdr->entries[io->entries_count++];
338 		e->data_sector = cpu_to_le64(data_sector);
339 		e->parity_disk = cpu_to_le32(sh->pd_idx);
340 		e->checksum = cpu_to_le32(~0);
341 	}
342 
343 	le32_add_cpu(&e->data_size, data_disks << PAGE_SHIFT);
344 
345 	/* don't write any PP if full stripe write */
346 	if (!test_bit(STRIPE_FULL_WRITE, &sh->state)) {
347 		le32_add_cpu(&e->pp_size, PAGE_SIZE);
348 		io->pp_size += PAGE_SIZE;
349 		e->checksum = cpu_to_le32(crc32c_le(le32_to_cpu(e->checksum),
350 						    page_address(sh->ppl_page),
351 						    PAGE_SIZE));
352 	}
353 
354 	list_add_tail(&sh->log_list, &io->stripe_list);
355 	atomic_inc(&io->pending_stripes);
356 	sh->ppl_io = io;
357 
358 	return 0;
359 }
360 
361 int ppl_write_stripe(struct r5conf *conf, struct stripe_head *sh)
362 {
363 	struct ppl_conf *ppl_conf = conf->log_private;
364 	struct ppl_io_unit *io = sh->ppl_io;
365 	struct ppl_log *log;
366 
367 	if (io || test_bit(STRIPE_SYNCING, &sh->state) || !sh->ppl_page ||
368 	    !test_bit(R5_Wantwrite, &sh->dev[sh->pd_idx].flags) ||
369 	    !test_bit(R5_Insync, &sh->dev[sh->pd_idx].flags)) {
370 		clear_bit(STRIPE_LOG_TRAPPED, &sh->state);
371 		return -EAGAIN;
372 	}
373 
374 	log = &ppl_conf->child_logs[sh->pd_idx];
375 
376 	mutex_lock(&log->io_mutex);
377 
378 	if (!log->rdev || test_bit(Faulty, &log->rdev->flags)) {
379 		mutex_unlock(&log->io_mutex);
380 		return -EAGAIN;
381 	}
382 
383 	set_bit(STRIPE_LOG_TRAPPED, &sh->state);
384 	clear_bit(STRIPE_DELAYED, &sh->state);
385 	atomic_inc(&sh->count);
386 
387 	if (ppl_log_stripe(log, sh)) {
388 		spin_lock_irq(&ppl_conf->no_mem_stripes_lock);
389 		list_add_tail(&sh->log_list, &ppl_conf->no_mem_stripes);
390 		spin_unlock_irq(&ppl_conf->no_mem_stripes_lock);
391 	}
392 
393 	mutex_unlock(&log->io_mutex);
394 
395 	return 0;
396 }
397 
398 static void ppl_log_endio(struct bio *bio)
399 {
400 	struct ppl_io_unit *io = bio->bi_private;
401 	struct ppl_log *log = io->log;
402 	struct ppl_conf *ppl_conf = log->ppl_conf;
403 	struct stripe_head *sh, *next;
404 
405 	pr_debug("%s: seq: %llu\n", __func__, io->seq);
406 
407 	if (bio->bi_status)
408 		md_error(ppl_conf->mddev, log->rdev);
409 
410 	list_for_each_entry_safe(sh, next, &io->stripe_list, log_list) {
411 		list_del_init(&sh->log_list);
412 
413 		set_bit(STRIPE_HANDLE, &sh->state);
414 		raid5_release_stripe(sh);
415 	}
416 }
417 
418 static void ppl_submit_iounit_bio(struct ppl_io_unit *io, struct bio *bio)
419 {
420 	pr_debug("%s: seq: %llu size: %u sector: %llu dev: %pg\n",
421 		 __func__, io->seq, bio->bi_iter.bi_size,
422 		 (unsigned long long)bio->bi_iter.bi_sector,
423 		 bio->bi_bdev);
424 
425 	submit_bio(bio);
426 }
427 
428 static void ppl_submit_iounit(struct ppl_io_unit *io)
429 {
430 	struct ppl_log *log = io->log;
431 	struct ppl_conf *ppl_conf = log->ppl_conf;
432 	struct ppl_header *pplhdr = page_address(io->header_page);
433 	struct bio *bio = &io->bio;
434 	struct stripe_head *sh;
435 	int i;
436 
437 	bio->bi_private = io;
438 
439 	if (!log->rdev || test_bit(Faulty, &log->rdev->flags)) {
440 		ppl_log_endio(bio);
441 		return;
442 	}
443 
444 	for (i = 0; i < io->entries_count; i++) {
445 		struct ppl_header_entry *e = &pplhdr->entries[i];
446 
447 		pr_debug("%s: seq: %llu entry: %d data_sector: %llu pp_size: %u data_size: %u\n",
448 			 __func__, io->seq, i, le64_to_cpu(e->data_sector),
449 			 le32_to_cpu(e->pp_size), le32_to_cpu(e->data_size));
450 
451 		e->data_sector = cpu_to_le64(le64_to_cpu(e->data_sector) >>
452 					     ilog2(ppl_conf->block_size >> 9));
453 		e->checksum = cpu_to_le32(~le32_to_cpu(e->checksum));
454 	}
455 
456 	pplhdr->entries_count = cpu_to_le32(io->entries_count);
457 	pplhdr->checksum = cpu_to_le32(~crc32c_le(~0, pplhdr, PPL_HEADER_SIZE));
458 
459 	/* Rewind the buffer if current PPL is larger then remaining space */
460 	if (log->use_multippl &&
461 	    log->rdev->ppl.sector + log->rdev->ppl.size - log->next_io_sector <
462 	    (PPL_HEADER_SIZE + io->pp_size) >> 9)
463 		log->next_io_sector = log->rdev->ppl.sector;
464 
465 
466 	bio->bi_end_io = ppl_log_endio;
467 	bio->bi_iter.bi_sector = log->next_io_sector;
468 	bio_add_page(bio, io->header_page, PAGE_SIZE, 0);
469 	bio->bi_write_hint = ppl_conf->write_hint;
470 
471 	pr_debug("%s: log->current_io_sector: %llu\n", __func__,
472 	    (unsigned long long)log->next_io_sector);
473 
474 	if (log->use_multippl)
475 		log->next_io_sector += (PPL_HEADER_SIZE + io->pp_size) >> 9;
476 
477 	WARN_ON(log->disk_flush_bitmap != 0);
478 
479 	list_for_each_entry(sh, &io->stripe_list, log_list) {
480 		for (i = 0; i < sh->disks; i++) {
481 			struct r5dev *dev = &sh->dev[i];
482 
483 			if ((ppl_conf->child_logs[i].wb_cache_on) &&
484 			    (test_bit(R5_Wantwrite, &dev->flags))) {
485 				set_bit(i, &log->disk_flush_bitmap);
486 			}
487 		}
488 
489 		/* entries for full stripe writes have no partial parity */
490 		if (test_bit(STRIPE_FULL_WRITE, &sh->state))
491 			continue;
492 
493 		if (!bio_add_page(bio, sh->ppl_page, PAGE_SIZE, 0)) {
494 			struct bio *prev = bio;
495 
496 			bio = bio_alloc_bioset(prev->bi_bdev, BIO_MAX_VECS,
497 					       prev->bi_opf, GFP_NOIO,
498 					       &ppl_conf->bs);
499 			bio->bi_write_hint = prev->bi_write_hint;
500 			bio->bi_iter.bi_sector = bio_end_sector(prev);
501 			bio_add_page(bio, sh->ppl_page, PAGE_SIZE, 0);
502 
503 			bio_chain(bio, prev);
504 			ppl_submit_iounit_bio(io, prev);
505 		}
506 	}
507 
508 	ppl_submit_iounit_bio(io, bio);
509 }
510 
511 static void ppl_submit_current_io(struct ppl_log *log)
512 {
513 	struct ppl_io_unit *io;
514 
515 	spin_lock_irq(&log->io_list_lock);
516 
517 	io = list_first_entry_or_null(&log->io_list, struct ppl_io_unit,
518 				      log_sibling);
519 	if (io && io->submitted)
520 		io = NULL;
521 
522 	spin_unlock_irq(&log->io_list_lock);
523 
524 	if (io) {
525 		io->submitted = true;
526 
527 		if (io == log->current_io)
528 			log->current_io = NULL;
529 
530 		ppl_submit_iounit(io);
531 	}
532 }
533 
534 void ppl_write_stripe_run(struct r5conf *conf)
535 {
536 	struct ppl_conf *ppl_conf = conf->log_private;
537 	struct ppl_log *log;
538 	int i;
539 
540 	for (i = 0; i < ppl_conf->count; i++) {
541 		log = &ppl_conf->child_logs[i];
542 
543 		mutex_lock(&log->io_mutex);
544 		ppl_submit_current_io(log);
545 		mutex_unlock(&log->io_mutex);
546 	}
547 }
548 
549 static void ppl_io_unit_finished(struct ppl_io_unit *io)
550 {
551 	struct ppl_log *log = io->log;
552 	struct ppl_conf *ppl_conf = log->ppl_conf;
553 	struct r5conf *conf = ppl_conf->mddev->private;
554 	unsigned long flags;
555 
556 	pr_debug("%s: seq: %llu\n", __func__, io->seq);
557 
558 	local_irq_save(flags);
559 
560 	spin_lock(&log->io_list_lock);
561 	list_del(&io->log_sibling);
562 	spin_unlock(&log->io_list_lock);
563 
564 	mempool_free(io, &ppl_conf->io_pool);
565 
566 	spin_lock(&ppl_conf->no_mem_stripes_lock);
567 	if (!list_empty(&ppl_conf->no_mem_stripes)) {
568 		struct stripe_head *sh;
569 
570 		sh = list_first_entry(&ppl_conf->no_mem_stripes,
571 				      struct stripe_head, log_list);
572 		list_del_init(&sh->log_list);
573 		set_bit(STRIPE_HANDLE, &sh->state);
574 		raid5_release_stripe(sh);
575 	}
576 	spin_unlock(&ppl_conf->no_mem_stripes_lock);
577 
578 	local_irq_restore(flags);
579 
580 	wake_up(&conf->wait_for_quiescent);
581 }
582 
583 static void ppl_flush_endio(struct bio *bio)
584 {
585 	struct ppl_io_unit *io = bio->bi_private;
586 	struct ppl_log *log = io->log;
587 	struct ppl_conf *ppl_conf = log->ppl_conf;
588 	struct r5conf *conf = ppl_conf->mddev->private;
589 
590 	pr_debug("%s: dev: %pg\n", __func__, bio->bi_bdev);
591 
592 	if (bio->bi_status) {
593 		struct md_rdev *rdev;
594 
595 		rcu_read_lock();
596 		rdev = md_find_rdev_rcu(conf->mddev, bio_dev(bio));
597 		if (rdev)
598 			md_error(rdev->mddev, rdev);
599 		rcu_read_unlock();
600 	}
601 
602 	bio_put(bio);
603 
604 	if (atomic_dec_and_test(&io->pending_flushes)) {
605 		ppl_io_unit_finished(io);
606 		md_wakeup_thread(conf->mddev->thread);
607 	}
608 }
609 
610 static void ppl_do_flush(struct ppl_io_unit *io)
611 {
612 	struct ppl_log *log = io->log;
613 	struct ppl_conf *ppl_conf = log->ppl_conf;
614 	struct r5conf *conf = ppl_conf->mddev->private;
615 	int raid_disks = conf->raid_disks;
616 	int flushed_disks = 0;
617 	int i;
618 
619 	atomic_set(&io->pending_flushes, raid_disks);
620 
621 	for_each_set_bit(i, &log->disk_flush_bitmap, raid_disks) {
622 		struct md_rdev *rdev;
623 		struct block_device *bdev = NULL;
624 
625 		rcu_read_lock();
626 		rdev = rcu_dereference(conf->disks[i].rdev);
627 		if (rdev && !test_bit(Faulty, &rdev->flags))
628 			bdev = rdev->bdev;
629 		rcu_read_unlock();
630 
631 		if (bdev) {
632 			struct bio *bio;
633 
634 			bio = bio_alloc_bioset(bdev, 0, GFP_NOIO,
635 					       REQ_OP_WRITE | REQ_PREFLUSH,
636 					       &ppl_conf->flush_bs);
637 			bio->bi_private = io;
638 			bio->bi_end_io = ppl_flush_endio;
639 
640 			pr_debug("%s: dev: %ps\n", __func__, bio->bi_bdev);
641 
642 			submit_bio(bio);
643 			flushed_disks++;
644 		}
645 	}
646 
647 	log->disk_flush_bitmap = 0;
648 
649 	for (i = flushed_disks ; i < raid_disks; i++) {
650 		if (atomic_dec_and_test(&io->pending_flushes))
651 			ppl_io_unit_finished(io);
652 	}
653 }
654 
655 static inline bool ppl_no_io_unit_submitted(struct r5conf *conf,
656 					    struct ppl_log *log)
657 {
658 	struct ppl_io_unit *io;
659 
660 	io = list_first_entry_or_null(&log->io_list, struct ppl_io_unit,
661 				      log_sibling);
662 
663 	return !io || !io->submitted;
664 }
665 
666 void ppl_quiesce(struct r5conf *conf, int quiesce)
667 {
668 	struct ppl_conf *ppl_conf = conf->log_private;
669 	int i;
670 
671 	if (quiesce) {
672 		for (i = 0; i < ppl_conf->count; i++) {
673 			struct ppl_log *log = &ppl_conf->child_logs[i];
674 
675 			spin_lock_irq(&log->io_list_lock);
676 			wait_event_lock_irq(conf->wait_for_quiescent,
677 					    ppl_no_io_unit_submitted(conf, log),
678 					    log->io_list_lock);
679 			spin_unlock_irq(&log->io_list_lock);
680 		}
681 	}
682 }
683 
684 int ppl_handle_flush_request(struct r5l_log *log, struct bio *bio)
685 {
686 	if (bio->bi_iter.bi_size == 0) {
687 		bio_endio(bio);
688 		return 0;
689 	}
690 	bio->bi_opf &= ~REQ_PREFLUSH;
691 	return -EAGAIN;
692 }
693 
694 void ppl_stripe_write_finished(struct stripe_head *sh)
695 {
696 	struct ppl_io_unit *io;
697 
698 	io = sh->ppl_io;
699 	sh->ppl_io = NULL;
700 
701 	if (io && atomic_dec_and_test(&io->pending_stripes)) {
702 		if (io->log->disk_flush_bitmap)
703 			ppl_do_flush(io);
704 		else
705 			ppl_io_unit_finished(io);
706 	}
707 }
708 
709 static void ppl_xor(int size, struct page *page1, struct page *page2)
710 {
711 	struct async_submit_ctl submit;
712 	struct dma_async_tx_descriptor *tx;
713 	struct page *xor_srcs[] = { page1, page2 };
714 
715 	init_async_submit(&submit, ASYNC_TX_ACK|ASYNC_TX_XOR_DROP_DST,
716 			  NULL, NULL, NULL, NULL);
717 	tx = async_xor(page1, xor_srcs, 0, 2, size, &submit);
718 
719 	async_tx_quiesce(&tx);
720 }
721 
722 /*
723  * PPL recovery strategy: xor partial parity and data from all modified data
724  * disks within a stripe and write the result as the new stripe parity. If all
725  * stripe data disks are modified (full stripe write), no partial parity is
726  * available, so just xor the data disks.
727  *
728  * Recovery of a PPL entry shall occur only if all modified data disks are
729  * available and read from all of them succeeds.
730  *
731  * A PPL entry applies to a stripe, partial parity size for an entry is at most
732  * the size of the chunk. Examples of possible cases for a single entry:
733  *
734  * case 0: single data disk write:
735  *   data0    data1    data2     ppl        parity
736  * +--------+--------+--------+           +--------------------+
737  * | ------ | ------ | ------ | +----+    | (no change)        |
738  * | ------ | -data- | ------ | | pp | -> | data1 ^ pp         |
739  * | ------ | -data- | ------ | | pp | -> | data1 ^ pp         |
740  * | ------ | ------ | ------ | +----+    | (no change)        |
741  * +--------+--------+--------+           +--------------------+
742  * pp_size = data_size
743  *
744  * case 1: more than one data disk write:
745  *   data0    data1    data2     ppl        parity
746  * +--------+--------+--------+           +--------------------+
747  * | ------ | ------ | ------ | +----+    | (no change)        |
748  * | -data- | -data- | ------ | | pp | -> | data0 ^ data1 ^ pp |
749  * | -data- | -data- | ------ | | pp | -> | data0 ^ data1 ^ pp |
750  * | ------ | ------ | ------ | +----+    | (no change)        |
751  * +--------+--------+--------+           +--------------------+
752  * pp_size = data_size / modified_data_disks
753  *
754  * case 2: write to all data disks (also full stripe write):
755  *   data0    data1    data2                parity
756  * +--------+--------+--------+           +--------------------+
757  * | ------ | ------ | ------ |           | (no change)        |
758  * | -data- | -data- | -data- | --------> | xor all data       |
759  * | ------ | ------ | ------ | --------> | (no change)        |
760  * | ------ | ------ | ------ |           | (no change)        |
761  * +--------+--------+--------+           +--------------------+
762  * pp_size = 0
763  *
764  * The following cases are possible only in other implementations. The recovery
765  * code can handle them, but they are not generated at runtime because they can
766  * be reduced to cases 0, 1 and 2:
767  *
768  * case 3:
769  *   data0    data1    data2     ppl        parity
770  * +--------+--------+--------+ +----+    +--------------------+
771  * | ------ | -data- | -data- | | pp |    | data1 ^ data2 ^ pp |
772  * | ------ | -data- | -data- | | pp | -> | data1 ^ data2 ^ pp |
773  * | -data- | -data- | -data- | | -- | -> | xor all data       |
774  * | -data- | -data- | ------ | | pp |    | data0 ^ data1 ^ pp |
775  * +--------+--------+--------+ +----+    +--------------------+
776  * pp_size = chunk_size
777  *
778  * case 4:
779  *   data0    data1    data2     ppl        parity
780  * +--------+--------+--------+ +----+    +--------------------+
781  * | ------ | -data- | ------ | | pp |    | data1 ^ pp         |
782  * | ------ | ------ | ------ | | -- | -> | (no change)        |
783  * | ------ | ------ | ------ | | -- | -> | (no change)        |
784  * | -data- | ------ | ------ | | pp |    | data0 ^ pp         |
785  * +--------+--------+--------+ +----+    +--------------------+
786  * pp_size = chunk_size
787  */
788 static int ppl_recover_entry(struct ppl_log *log, struct ppl_header_entry *e,
789 			     sector_t ppl_sector)
790 {
791 	struct ppl_conf *ppl_conf = log->ppl_conf;
792 	struct mddev *mddev = ppl_conf->mddev;
793 	struct r5conf *conf = mddev->private;
794 	int block_size = ppl_conf->block_size;
795 	struct page *page1;
796 	struct page *page2;
797 	sector_t r_sector_first;
798 	sector_t r_sector_last;
799 	int strip_sectors;
800 	int data_disks;
801 	int i;
802 	int ret = 0;
803 	char b[BDEVNAME_SIZE];
804 	unsigned int pp_size = le32_to_cpu(e->pp_size);
805 	unsigned int data_size = le32_to_cpu(e->data_size);
806 
807 	page1 = alloc_page(GFP_KERNEL);
808 	page2 = alloc_page(GFP_KERNEL);
809 
810 	if (!page1 || !page2) {
811 		ret = -ENOMEM;
812 		goto out;
813 	}
814 
815 	r_sector_first = le64_to_cpu(e->data_sector) * (block_size >> 9);
816 
817 	if ((pp_size >> 9) < conf->chunk_sectors) {
818 		if (pp_size > 0) {
819 			data_disks = data_size / pp_size;
820 			strip_sectors = pp_size >> 9;
821 		} else {
822 			data_disks = conf->raid_disks - conf->max_degraded;
823 			strip_sectors = (data_size >> 9) / data_disks;
824 		}
825 		r_sector_last = r_sector_first +
826 				(data_disks - 1) * conf->chunk_sectors +
827 				strip_sectors;
828 	} else {
829 		data_disks = conf->raid_disks - conf->max_degraded;
830 		strip_sectors = conf->chunk_sectors;
831 		r_sector_last = r_sector_first + (data_size >> 9);
832 	}
833 
834 	pr_debug("%s: array sector first: %llu last: %llu\n", __func__,
835 		 (unsigned long long)r_sector_first,
836 		 (unsigned long long)r_sector_last);
837 
838 	/* if start and end is 4k aligned, use a 4k block */
839 	if (block_size == 512 &&
840 	    (r_sector_first & (RAID5_STRIPE_SECTORS(conf) - 1)) == 0 &&
841 	    (r_sector_last & (RAID5_STRIPE_SECTORS(conf) - 1)) == 0)
842 		block_size = RAID5_STRIPE_SIZE(conf);
843 
844 	/* iterate through blocks in strip */
845 	for (i = 0; i < strip_sectors; i += (block_size >> 9)) {
846 		bool update_parity = false;
847 		sector_t parity_sector;
848 		struct md_rdev *parity_rdev;
849 		struct stripe_head sh;
850 		int disk;
851 		int indent = 0;
852 
853 		pr_debug("%s:%*s iter %d start\n", __func__, indent, "", i);
854 		indent += 2;
855 
856 		memset(page_address(page1), 0, PAGE_SIZE);
857 
858 		/* iterate through data member disks */
859 		for (disk = 0; disk < data_disks; disk++) {
860 			int dd_idx;
861 			struct md_rdev *rdev;
862 			sector_t sector;
863 			sector_t r_sector = r_sector_first + i +
864 					    (disk * conf->chunk_sectors);
865 
866 			pr_debug("%s:%*s data member disk %d start\n",
867 				 __func__, indent, "", disk);
868 			indent += 2;
869 
870 			if (r_sector >= r_sector_last) {
871 				pr_debug("%s:%*s array sector %llu doesn't need parity update\n",
872 					 __func__, indent, "",
873 					 (unsigned long long)r_sector);
874 				indent -= 2;
875 				continue;
876 			}
877 
878 			update_parity = true;
879 
880 			/* map raid sector to member disk */
881 			sector = raid5_compute_sector(conf, r_sector, 0,
882 						      &dd_idx, NULL);
883 			pr_debug("%s:%*s processing array sector %llu => data member disk %d, sector %llu\n",
884 				 __func__, indent, "",
885 				 (unsigned long long)r_sector, dd_idx,
886 				 (unsigned long long)sector);
887 
888 			rdev = conf->disks[dd_idx].rdev;
889 			if (!rdev || (!test_bit(In_sync, &rdev->flags) &&
890 				      sector >= rdev->recovery_offset)) {
891 				pr_debug("%s:%*s data member disk %d missing\n",
892 					 __func__, indent, "", dd_idx);
893 				update_parity = false;
894 				break;
895 			}
896 
897 			pr_debug("%s:%*s reading data member disk %s sector %llu\n",
898 				 __func__, indent, "", bdevname(rdev->bdev, b),
899 				 (unsigned long long)sector);
900 			if (!sync_page_io(rdev, sector, block_size, page2,
901 					REQ_OP_READ, 0, false)) {
902 				md_error(mddev, rdev);
903 				pr_debug("%s:%*s read failed!\n", __func__,
904 					 indent, "");
905 				ret = -EIO;
906 				goto out;
907 			}
908 
909 			ppl_xor(block_size, page1, page2);
910 
911 			indent -= 2;
912 		}
913 
914 		if (!update_parity)
915 			continue;
916 
917 		if (pp_size > 0) {
918 			pr_debug("%s:%*s reading pp disk sector %llu\n",
919 				 __func__, indent, "",
920 				 (unsigned long long)(ppl_sector + i));
921 			if (!sync_page_io(log->rdev,
922 					ppl_sector - log->rdev->data_offset + i,
923 					block_size, page2, REQ_OP_READ, 0,
924 					false)) {
925 				pr_debug("%s:%*s read failed!\n", __func__,
926 					 indent, "");
927 				md_error(mddev, log->rdev);
928 				ret = -EIO;
929 				goto out;
930 			}
931 
932 			ppl_xor(block_size, page1, page2);
933 		}
934 
935 		/* map raid sector to parity disk */
936 		parity_sector = raid5_compute_sector(conf, r_sector_first + i,
937 				0, &disk, &sh);
938 		BUG_ON(sh.pd_idx != le32_to_cpu(e->parity_disk));
939 		parity_rdev = conf->disks[sh.pd_idx].rdev;
940 
941 		BUG_ON(parity_rdev->bdev->bd_dev != log->rdev->bdev->bd_dev);
942 		pr_debug("%s:%*s write parity at sector %llu, disk %s\n",
943 			 __func__, indent, "",
944 			 (unsigned long long)parity_sector,
945 			 bdevname(parity_rdev->bdev, b));
946 		if (!sync_page_io(parity_rdev, parity_sector, block_size,
947 				page1, REQ_OP_WRITE, 0, false)) {
948 			pr_debug("%s:%*s parity write error!\n", __func__,
949 				 indent, "");
950 			md_error(mddev, parity_rdev);
951 			ret = -EIO;
952 			goto out;
953 		}
954 	}
955 out:
956 	if (page1)
957 		__free_page(page1);
958 	if (page2)
959 		__free_page(page2);
960 	return ret;
961 }
962 
963 static int ppl_recover(struct ppl_log *log, struct ppl_header *pplhdr,
964 		       sector_t offset)
965 {
966 	struct ppl_conf *ppl_conf = log->ppl_conf;
967 	struct md_rdev *rdev = log->rdev;
968 	struct mddev *mddev = rdev->mddev;
969 	sector_t ppl_sector = rdev->ppl.sector + offset +
970 			      (PPL_HEADER_SIZE >> 9);
971 	struct page *page;
972 	int i;
973 	int ret = 0;
974 
975 	page = alloc_page(GFP_KERNEL);
976 	if (!page)
977 		return -ENOMEM;
978 
979 	/* iterate through all PPL entries saved */
980 	for (i = 0; i < le32_to_cpu(pplhdr->entries_count); i++) {
981 		struct ppl_header_entry *e = &pplhdr->entries[i];
982 		u32 pp_size = le32_to_cpu(e->pp_size);
983 		sector_t sector = ppl_sector;
984 		int ppl_entry_sectors = pp_size >> 9;
985 		u32 crc, crc_stored;
986 
987 		pr_debug("%s: disk: %d entry: %d ppl_sector: %llu pp_size: %u\n",
988 			 __func__, rdev->raid_disk, i,
989 			 (unsigned long long)ppl_sector, pp_size);
990 
991 		crc = ~0;
992 		crc_stored = le32_to_cpu(e->checksum);
993 
994 		/* read parial parity for this entry and calculate its checksum */
995 		while (pp_size) {
996 			int s = pp_size > PAGE_SIZE ? PAGE_SIZE : pp_size;
997 
998 			if (!sync_page_io(rdev, sector - rdev->data_offset,
999 					s, page, REQ_OP_READ, 0, false)) {
1000 				md_error(mddev, rdev);
1001 				ret = -EIO;
1002 				goto out;
1003 			}
1004 
1005 			crc = crc32c_le(crc, page_address(page), s);
1006 
1007 			pp_size -= s;
1008 			sector += s >> 9;
1009 		}
1010 
1011 		crc = ~crc;
1012 
1013 		if (crc != crc_stored) {
1014 			/*
1015 			 * Don't recover this entry if the checksum does not
1016 			 * match, but keep going and try to recover other
1017 			 * entries.
1018 			 */
1019 			pr_debug("%s: ppl entry crc does not match: stored: 0x%x calculated: 0x%x\n",
1020 				 __func__, crc_stored, crc);
1021 			ppl_conf->mismatch_count++;
1022 		} else {
1023 			ret = ppl_recover_entry(log, e, ppl_sector);
1024 			if (ret)
1025 				goto out;
1026 			ppl_conf->recovered_entries++;
1027 		}
1028 
1029 		ppl_sector += ppl_entry_sectors;
1030 	}
1031 
1032 	/* flush the disk cache after recovery if necessary */
1033 	ret = blkdev_issue_flush(rdev->bdev);
1034 out:
1035 	__free_page(page);
1036 	return ret;
1037 }
1038 
1039 static int ppl_write_empty_header(struct ppl_log *log)
1040 {
1041 	struct page *page;
1042 	struct ppl_header *pplhdr;
1043 	struct md_rdev *rdev = log->rdev;
1044 	int ret = 0;
1045 
1046 	pr_debug("%s: disk: %d ppl_sector: %llu\n", __func__,
1047 		 rdev->raid_disk, (unsigned long long)rdev->ppl.sector);
1048 
1049 	page = alloc_page(GFP_NOIO | __GFP_ZERO);
1050 	if (!page)
1051 		return -ENOMEM;
1052 
1053 	pplhdr = page_address(page);
1054 	/* zero out PPL space to avoid collision with old PPLs */
1055 	blkdev_issue_zeroout(rdev->bdev, rdev->ppl.sector,
1056 			    log->rdev->ppl.size, GFP_NOIO, 0);
1057 	memset(pplhdr->reserved, 0xff, PPL_HDR_RESERVED);
1058 	pplhdr->signature = cpu_to_le32(log->ppl_conf->signature);
1059 	pplhdr->checksum = cpu_to_le32(~crc32c_le(~0, pplhdr, PAGE_SIZE));
1060 
1061 	if (!sync_page_io(rdev, rdev->ppl.sector - rdev->data_offset,
1062 			  PPL_HEADER_SIZE, page, REQ_OP_WRITE | REQ_SYNC |
1063 			  REQ_FUA, 0, false)) {
1064 		md_error(rdev->mddev, rdev);
1065 		ret = -EIO;
1066 	}
1067 
1068 	__free_page(page);
1069 	return ret;
1070 }
1071 
1072 static int ppl_load_distributed(struct ppl_log *log)
1073 {
1074 	struct ppl_conf *ppl_conf = log->ppl_conf;
1075 	struct md_rdev *rdev = log->rdev;
1076 	struct mddev *mddev = rdev->mddev;
1077 	struct page *page, *page2;
1078 	struct ppl_header *pplhdr = NULL, *prev_pplhdr = NULL;
1079 	u32 crc, crc_stored;
1080 	u32 signature;
1081 	int ret = 0, i;
1082 	sector_t pplhdr_offset = 0, prev_pplhdr_offset = 0;
1083 
1084 	pr_debug("%s: disk: %d\n", __func__, rdev->raid_disk);
1085 	/* read PPL headers, find the recent one */
1086 	page = alloc_page(GFP_KERNEL);
1087 	if (!page)
1088 		return -ENOMEM;
1089 
1090 	page2 = alloc_page(GFP_KERNEL);
1091 	if (!page2) {
1092 		__free_page(page);
1093 		return -ENOMEM;
1094 	}
1095 
1096 	/* searching ppl area for latest ppl */
1097 	while (pplhdr_offset < rdev->ppl.size - (PPL_HEADER_SIZE >> 9)) {
1098 		if (!sync_page_io(rdev,
1099 				  rdev->ppl.sector - rdev->data_offset +
1100 				  pplhdr_offset, PAGE_SIZE, page, REQ_OP_READ,
1101 				  0, false)) {
1102 			md_error(mddev, rdev);
1103 			ret = -EIO;
1104 			/* if not able to read - don't recover any PPL */
1105 			pplhdr = NULL;
1106 			break;
1107 		}
1108 		pplhdr = page_address(page);
1109 
1110 		/* check header validity */
1111 		crc_stored = le32_to_cpu(pplhdr->checksum);
1112 		pplhdr->checksum = 0;
1113 		crc = ~crc32c_le(~0, pplhdr, PAGE_SIZE);
1114 
1115 		if (crc_stored != crc) {
1116 			pr_debug("%s: ppl header crc does not match: stored: 0x%x calculated: 0x%x (offset: %llu)\n",
1117 				 __func__, crc_stored, crc,
1118 				 (unsigned long long)pplhdr_offset);
1119 			pplhdr = prev_pplhdr;
1120 			pplhdr_offset = prev_pplhdr_offset;
1121 			break;
1122 		}
1123 
1124 		signature = le32_to_cpu(pplhdr->signature);
1125 
1126 		if (mddev->external) {
1127 			/*
1128 			 * For external metadata the header signature is set and
1129 			 * validated in userspace.
1130 			 */
1131 			ppl_conf->signature = signature;
1132 		} else if (ppl_conf->signature != signature) {
1133 			pr_debug("%s: ppl header signature does not match: stored: 0x%x configured: 0x%x (offset: %llu)\n",
1134 				 __func__, signature, ppl_conf->signature,
1135 				 (unsigned long long)pplhdr_offset);
1136 			pplhdr = prev_pplhdr;
1137 			pplhdr_offset = prev_pplhdr_offset;
1138 			break;
1139 		}
1140 
1141 		if (prev_pplhdr && le64_to_cpu(prev_pplhdr->generation) >
1142 		    le64_to_cpu(pplhdr->generation)) {
1143 			/* previous was newest */
1144 			pplhdr = prev_pplhdr;
1145 			pplhdr_offset = prev_pplhdr_offset;
1146 			break;
1147 		}
1148 
1149 		prev_pplhdr_offset = pplhdr_offset;
1150 		prev_pplhdr = pplhdr;
1151 
1152 		swap(page, page2);
1153 
1154 		/* calculate next potential ppl offset */
1155 		for (i = 0; i < le32_to_cpu(pplhdr->entries_count); i++)
1156 			pplhdr_offset +=
1157 			    le32_to_cpu(pplhdr->entries[i].pp_size) >> 9;
1158 		pplhdr_offset += PPL_HEADER_SIZE >> 9;
1159 	}
1160 
1161 	/* no valid ppl found */
1162 	if (!pplhdr)
1163 		ppl_conf->mismatch_count++;
1164 	else
1165 		pr_debug("%s: latest PPL found at offset: %llu, with generation: %llu\n",
1166 		    __func__, (unsigned long long)pplhdr_offset,
1167 		    le64_to_cpu(pplhdr->generation));
1168 
1169 	/* attempt to recover from log if we are starting a dirty array */
1170 	if (pplhdr && !mddev->pers && mddev->recovery_cp != MaxSector)
1171 		ret = ppl_recover(log, pplhdr, pplhdr_offset);
1172 
1173 	/* write empty header if we are starting the array */
1174 	if (!ret && !mddev->pers)
1175 		ret = ppl_write_empty_header(log);
1176 
1177 	__free_page(page);
1178 	__free_page(page2);
1179 
1180 	pr_debug("%s: return: %d mismatch_count: %d recovered_entries: %d\n",
1181 		 __func__, ret, ppl_conf->mismatch_count,
1182 		 ppl_conf->recovered_entries);
1183 	return ret;
1184 }
1185 
1186 static int ppl_load(struct ppl_conf *ppl_conf)
1187 {
1188 	int ret = 0;
1189 	u32 signature = 0;
1190 	bool signature_set = false;
1191 	int i;
1192 
1193 	for (i = 0; i < ppl_conf->count; i++) {
1194 		struct ppl_log *log = &ppl_conf->child_logs[i];
1195 
1196 		/* skip missing drive */
1197 		if (!log->rdev)
1198 			continue;
1199 
1200 		ret = ppl_load_distributed(log);
1201 		if (ret)
1202 			break;
1203 
1204 		/*
1205 		 * For external metadata we can't check if the signature is
1206 		 * correct on a single drive, but we can check if it is the same
1207 		 * on all drives.
1208 		 */
1209 		if (ppl_conf->mddev->external) {
1210 			if (!signature_set) {
1211 				signature = ppl_conf->signature;
1212 				signature_set = true;
1213 			} else if (signature != ppl_conf->signature) {
1214 				pr_warn("md/raid:%s: PPL header signature does not match on all member drives\n",
1215 					mdname(ppl_conf->mddev));
1216 				ret = -EINVAL;
1217 				break;
1218 			}
1219 		}
1220 	}
1221 
1222 	pr_debug("%s: return: %d mismatch_count: %d recovered_entries: %d\n",
1223 		 __func__, ret, ppl_conf->mismatch_count,
1224 		 ppl_conf->recovered_entries);
1225 	return ret;
1226 }
1227 
1228 static void __ppl_exit_log(struct ppl_conf *ppl_conf)
1229 {
1230 	clear_bit(MD_HAS_PPL, &ppl_conf->mddev->flags);
1231 	clear_bit(MD_HAS_MULTIPLE_PPLS, &ppl_conf->mddev->flags);
1232 
1233 	kfree(ppl_conf->child_logs);
1234 
1235 	bioset_exit(&ppl_conf->bs);
1236 	bioset_exit(&ppl_conf->flush_bs);
1237 	mempool_exit(&ppl_conf->io_pool);
1238 	kmem_cache_destroy(ppl_conf->io_kc);
1239 
1240 	kfree(ppl_conf);
1241 }
1242 
1243 void ppl_exit_log(struct r5conf *conf)
1244 {
1245 	struct ppl_conf *ppl_conf = conf->log_private;
1246 
1247 	if (ppl_conf) {
1248 		__ppl_exit_log(ppl_conf);
1249 		conf->log_private = NULL;
1250 	}
1251 }
1252 
1253 static int ppl_validate_rdev(struct md_rdev *rdev)
1254 {
1255 	char b[BDEVNAME_SIZE];
1256 	int ppl_data_sectors;
1257 	int ppl_size_new;
1258 
1259 	/*
1260 	 * The configured PPL size must be enough to store
1261 	 * the header and (at the very least) partial parity
1262 	 * for one stripe. Round it down to ensure the data
1263 	 * space is cleanly divisible by stripe size.
1264 	 */
1265 	ppl_data_sectors = rdev->ppl.size - (PPL_HEADER_SIZE >> 9);
1266 
1267 	if (ppl_data_sectors > 0)
1268 		ppl_data_sectors = rounddown(ppl_data_sectors,
1269 				RAID5_STRIPE_SECTORS((struct r5conf *)rdev->mddev->private));
1270 
1271 	if (ppl_data_sectors <= 0) {
1272 		pr_warn("md/raid:%s: PPL space too small on %s\n",
1273 			mdname(rdev->mddev), bdevname(rdev->bdev, b));
1274 		return -ENOSPC;
1275 	}
1276 
1277 	ppl_size_new = ppl_data_sectors + (PPL_HEADER_SIZE >> 9);
1278 
1279 	if ((rdev->ppl.sector < rdev->data_offset &&
1280 	     rdev->ppl.sector + ppl_size_new > rdev->data_offset) ||
1281 	    (rdev->ppl.sector >= rdev->data_offset &&
1282 	     rdev->data_offset + rdev->sectors > rdev->ppl.sector)) {
1283 		pr_warn("md/raid:%s: PPL space overlaps with data on %s\n",
1284 			mdname(rdev->mddev), bdevname(rdev->bdev, b));
1285 		return -EINVAL;
1286 	}
1287 
1288 	if (!rdev->mddev->external &&
1289 	    ((rdev->ppl.offset > 0 && rdev->ppl.offset < (rdev->sb_size >> 9)) ||
1290 	     (rdev->ppl.offset <= 0 && rdev->ppl.offset + ppl_size_new > 0))) {
1291 		pr_warn("md/raid:%s: PPL space overlaps with superblock on %s\n",
1292 			mdname(rdev->mddev), bdevname(rdev->bdev, b));
1293 		return -EINVAL;
1294 	}
1295 
1296 	rdev->ppl.size = ppl_size_new;
1297 
1298 	return 0;
1299 }
1300 
1301 static void ppl_init_child_log(struct ppl_log *log, struct md_rdev *rdev)
1302 {
1303 	struct request_queue *q;
1304 
1305 	if ((rdev->ppl.size << 9) >= (PPL_SPACE_SIZE +
1306 				      PPL_HEADER_SIZE) * 2) {
1307 		log->use_multippl = true;
1308 		set_bit(MD_HAS_MULTIPLE_PPLS,
1309 			&log->ppl_conf->mddev->flags);
1310 		log->entry_space = PPL_SPACE_SIZE;
1311 	} else {
1312 		log->use_multippl = false;
1313 		log->entry_space = (log->rdev->ppl.size << 9) -
1314 				   PPL_HEADER_SIZE;
1315 	}
1316 	log->next_io_sector = rdev->ppl.sector;
1317 
1318 	q = bdev_get_queue(rdev->bdev);
1319 	if (test_bit(QUEUE_FLAG_WC, &q->queue_flags))
1320 		log->wb_cache_on = true;
1321 }
1322 
1323 int ppl_init_log(struct r5conf *conf)
1324 {
1325 	struct ppl_conf *ppl_conf;
1326 	struct mddev *mddev = conf->mddev;
1327 	int ret = 0;
1328 	int max_disks;
1329 	int i;
1330 
1331 	pr_debug("md/raid:%s: enabling distributed Partial Parity Log\n",
1332 		 mdname(conf->mddev));
1333 
1334 	if (PAGE_SIZE != 4096)
1335 		return -EINVAL;
1336 
1337 	if (mddev->level != 5) {
1338 		pr_warn("md/raid:%s PPL is not compatible with raid level %d\n",
1339 			mdname(mddev), mddev->level);
1340 		return -EINVAL;
1341 	}
1342 
1343 	if (mddev->bitmap_info.file || mddev->bitmap_info.offset) {
1344 		pr_warn("md/raid:%s PPL is not compatible with bitmap\n",
1345 			mdname(mddev));
1346 		return -EINVAL;
1347 	}
1348 
1349 	if (test_bit(MD_HAS_JOURNAL, &mddev->flags)) {
1350 		pr_warn("md/raid:%s PPL is not compatible with journal\n",
1351 			mdname(mddev));
1352 		return -EINVAL;
1353 	}
1354 
1355 	max_disks = sizeof_field(struct ppl_log, disk_flush_bitmap) *
1356 		BITS_PER_BYTE;
1357 	if (conf->raid_disks > max_disks) {
1358 		pr_warn("md/raid:%s PPL doesn't support over %d disks in the array\n",
1359 			mdname(mddev), max_disks);
1360 		return -EINVAL;
1361 	}
1362 
1363 	ppl_conf = kzalloc(sizeof(struct ppl_conf), GFP_KERNEL);
1364 	if (!ppl_conf)
1365 		return -ENOMEM;
1366 
1367 	ppl_conf->mddev = mddev;
1368 
1369 	ppl_conf->io_kc = KMEM_CACHE(ppl_io_unit, 0);
1370 	if (!ppl_conf->io_kc) {
1371 		ret = -ENOMEM;
1372 		goto err;
1373 	}
1374 
1375 	ret = mempool_init(&ppl_conf->io_pool, conf->raid_disks, ppl_io_pool_alloc,
1376 			   ppl_io_pool_free, ppl_conf->io_kc);
1377 	if (ret)
1378 		goto err;
1379 
1380 	ret = bioset_init(&ppl_conf->bs, conf->raid_disks, 0, BIOSET_NEED_BVECS);
1381 	if (ret)
1382 		goto err;
1383 
1384 	ret = bioset_init(&ppl_conf->flush_bs, conf->raid_disks, 0, 0);
1385 	if (ret)
1386 		goto err;
1387 
1388 	ppl_conf->count = conf->raid_disks;
1389 	ppl_conf->child_logs = kcalloc(ppl_conf->count, sizeof(struct ppl_log),
1390 				       GFP_KERNEL);
1391 	if (!ppl_conf->child_logs) {
1392 		ret = -ENOMEM;
1393 		goto err;
1394 	}
1395 
1396 	atomic64_set(&ppl_conf->seq, 0);
1397 	INIT_LIST_HEAD(&ppl_conf->no_mem_stripes);
1398 	spin_lock_init(&ppl_conf->no_mem_stripes_lock);
1399 	ppl_conf->write_hint = RWH_WRITE_LIFE_NOT_SET;
1400 
1401 	if (!mddev->external) {
1402 		ppl_conf->signature = ~crc32c_le(~0, mddev->uuid, sizeof(mddev->uuid));
1403 		ppl_conf->block_size = 512;
1404 	} else {
1405 		ppl_conf->block_size = queue_logical_block_size(mddev->queue);
1406 	}
1407 
1408 	for (i = 0; i < ppl_conf->count; i++) {
1409 		struct ppl_log *log = &ppl_conf->child_logs[i];
1410 		struct md_rdev *rdev = conf->disks[i].rdev;
1411 
1412 		mutex_init(&log->io_mutex);
1413 		spin_lock_init(&log->io_list_lock);
1414 		INIT_LIST_HEAD(&log->io_list);
1415 
1416 		log->ppl_conf = ppl_conf;
1417 		log->rdev = rdev;
1418 
1419 		if (rdev) {
1420 			ret = ppl_validate_rdev(rdev);
1421 			if (ret)
1422 				goto err;
1423 
1424 			ppl_init_child_log(log, rdev);
1425 		}
1426 	}
1427 
1428 	/* load and possibly recover the logs from the member disks */
1429 	ret = ppl_load(ppl_conf);
1430 
1431 	if (ret) {
1432 		goto err;
1433 	} else if (!mddev->pers && mddev->recovery_cp == 0 &&
1434 		   ppl_conf->recovered_entries > 0 &&
1435 		   ppl_conf->mismatch_count == 0) {
1436 		/*
1437 		 * If we are starting a dirty array and the recovery succeeds
1438 		 * without any issues, set the array as clean.
1439 		 */
1440 		mddev->recovery_cp = MaxSector;
1441 		set_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
1442 	} else if (mddev->pers && ppl_conf->mismatch_count > 0) {
1443 		/* no mismatch allowed when enabling PPL for a running array */
1444 		ret = -EINVAL;
1445 		goto err;
1446 	}
1447 
1448 	conf->log_private = ppl_conf;
1449 	set_bit(MD_HAS_PPL, &ppl_conf->mddev->flags);
1450 
1451 	return 0;
1452 err:
1453 	__ppl_exit_log(ppl_conf);
1454 	return ret;
1455 }
1456 
1457 int ppl_modify_log(struct r5conf *conf, struct md_rdev *rdev, bool add)
1458 {
1459 	struct ppl_conf *ppl_conf = conf->log_private;
1460 	struct ppl_log *log;
1461 	int ret = 0;
1462 	char b[BDEVNAME_SIZE];
1463 
1464 	if (!rdev)
1465 		return -EINVAL;
1466 
1467 	pr_debug("%s: disk: %d operation: %s dev: %s\n",
1468 		 __func__, rdev->raid_disk, add ? "add" : "remove",
1469 		 bdevname(rdev->bdev, b));
1470 
1471 	if (rdev->raid_disk < 0)
1472 		return 0;
1473 
1474 	if (rdev->raid_disk >= ppl_conf->count)
1475 		return -ENODEV;
1476 
1477 	log = &ppl_conf->child_logs[rdev->raid_disk];
1478 
1479 	mutex_lock(&log->io_mutex);
1480 	if (add) {
1481 		ret = ppl_validate_rdev(rdev);
1482 		if (!ret) {
1483 			log->rdev = rdev;
1484 			ret = ppl_write_empty_header(log);
1485 			ppl_init_child_log(log, rdev);
1486 		}
1487 	} else {
1488 		log->rdev = NULL;
1489 	}
1490 	mutex_unlock(&log->io_mutex);
1491 
1492 	return ret;
1493 }
1494 
1495 static ssize_t
1496 ppl_write_hint_show(struct mddev *mddev, char *buf)
1497 {
1498 	size_t ret = 0;
1499 	struct r5conf *conf;
1500 	struct ppl_conf *ppl_conf = NULL;
1501 
1502 	spin_lock(&mddev->lock);
1503 	conf = mddev->private;
1504 	if (conf && raid5_has_ppl(conf))
1505 		ppl_conf = conf->log_private;
1506 	ret = sprintf(buf, "%d\n", ppl_conf ? ppl_conf->write_hint : 0);
1507 	spin_unlock(&mddev->lock);
1508 
1509 	return ret;
1510 }
1511 
1512 static ssize_t
1513 ppl_write_hint_store(struct mddev *mddev, const char *page, size_t len)
1514 {
1515 	struct r5conf *conf;
1516 	struct ppl_conf *ppl_conf;
1517 	int err = 0;
1518 	unsigned short new;
1519 
1520 	if (len >= PAGE_SIZE)
1521 		return -EINVAL;
1522 	if (kstrtou16(page, 10, &new))
1523 		return -EINVAL;
1524 
1525 	err = mddev_lock(mddev);
1526 	if (err)
1527 		return err;
1528 
1529 	conf = mddev->private;
1530 	if (!conf) {
1531 		err = -ENODEV;
1532 	} else if (raid5_has_ppl(conf)) {
1533 		ppl_conf = conf->log_private;
1534 		if (!ppl_conf)
1535 			err = -EINVAL;
1536 		else
1537 			ppl_conf->write_hint = new;
1538 	} else {
1539 		err = -EINVAL;
1540 	}
1541 
1542 	mddev_unlock(mddev);
1543 
1544 	return err ?: len;
1545 }
1546 
1547 struct md_sysfs_entry
1548 ppl_write_hint = __ATTR(ppl_write_hint, S_IRUGO | S_IWUSR,
1549 			ppl_write_hint_show,
1550 			ppl_write_hint_store);
1551