xref: /openbmc/linux/block/blk-merge.c (revision 2aa7745b)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Functions related to segment and merge handling
4  */
5 #include <linux/kernel.h>
6 #include <linux/module.h>
7 #include <linux/bio.h>
8 #include <linux/blkdev.h>
9 #include <linux/blk-integrity.h>
10 #include <linux/scatterlist.h>
11 
12 #include <trace/events/block.h>
13 
14 #include "blk.h"
15 #include "blk-mq-sched.h"
16 #include "blk-rq-qos.h"
17 #include "blk-throttle.h"
18 
19 static inline void bio_get_first_bvec(struct bio *bio, struct bio_vec *bv)
20 {
21 	*bv = mp_bvec_iter_bvec(bio->bi_io_vec, bio->bi_iter);
22 }
23 
24 static inline void bio_get_last_bvec(struct bio *bio, struct bio_vec *bv)
25 {
26 	struct bvec_iter iter = bio->bi_iter;
27 	int idx;
28 
29 	bio_get_first_bvec(bio, bv);
30 	if (bv->bv_len == bio->bi_iter.bi_size)
31 		return;		/* this bio only has a single bvec */
32 
33 	bio_advance_iter(bio, &iter, iter.bi_size);
34 
35 	if (!iter.bi_bvec_done)
36 		idx = iter.bi_idx - 1;
37 	else	/* in the middle of bvec */
38 		idx = iter.bi_idx;
39 
40 	*bv = bio->bi_io_vec[idx];
41 
42 	/*
43 	 * iter.bi_bvec_done records actual length of the last bvec
44 	 * if this bio ends in the middle of one io vector
45 	 */
46 	if (iter.bi_bvec_done)
47 		bv->bv_len = iter.bi_bvec_done;
48 }
49 
50 static inline bool bio_will_gap(struct request_queue *q,
51 		struct request *prev_rq, struct bio *prev, struct bio *next)
52 {
53 	struct bio_vec pb, nb;
54 
55 	if (!bio_has_data(prev) || !queue_virt_boundary(q))
56 		return false;
57 
58 	/*
59 	 * Don't merge if the 1st bio starts with non-zero offset, otherwise it
60 	 * is quite difficult to respect the sg gap limit.  We work hard to
61 	 * merge a huge number of small single bios in case of mkfs.
62 	 */
63 	if (prev_rq)
64 		bio_get_first_bvec(prev_rq->bio, &pb);
65 	else
66 		bio_get_first_bvec(prev, &pb);
67 	if (pb.bv_offset & queue_virt_boundary(q))
68 		return true;
69 
70 	/*
71 	 * We don't need to worry about the situation that the merged segment
72 	 * ends in unaligned virt boundary:
73 	 *
74 	 * - if 'pb' ends aligned, the merged segment ends aligned
75 	 * - if 'pb' ends unaligned, the next bio must include
76 	 *   one single bvec of 'nb', otherwise the 'nb' can't
77 	 *   merge with 'pb'
78 	 */
79 	bio_get_last_bvec(prev, &pb);
80 	bio_get_first_bvec(next, &nb);
81 	if (biovec_phys_mergeable(q, &pb, &nb))
82 		return false;
83 	return __bvec_gap_to_prev(q, &pb, nb.bv_offset);
84 }
85 
86 static inline bool req_gap_back_merge(struct request *req, struct bio *bio)
87 {
88 	return bio_will_gap(req->q, req, req->biotail, bio);
89 }
90 
91 static inline bool req_gap_front_merge(struct request *req, struct bio *bio)
92 {
93 	return bio_will_gap(req->q, NULL, bio, req->bio);
94 }
95 
96 static struct bio *blk_bio_discard_split(struct request_queue *q,
97 					 struct bio *bio,
98 					 struct bio_set *bs,
99 					 unsigned *nsegs)
100 {
101 	unsigned int max_discard_sectors, granularity;
102 	int alignment;
103 	sector_t tmp;
104 	unsigned split_sectors;
105 
106 	*nsegs = 1;
107 
108 	/* Zero-sector (unknown) and one-sector granularities are the same.  */
109 	granularity = max(q->limits.discard_granularity >> 9, 1U);
110 
111 	max_discard_sectors = min(q->limits.max_discard_sectors,
112 			bio_allowed_max_sectors(q));
113 	max_discard_sectors -= max_discard_sectors % granularity;
114 
115 	if (unlikely(!max_discard_sectors)) {
116 		/* XXX: warn */
117 		return NULL;
118 	}
119 
120 	if (bio_sectors(bio) <= max_discard_sectors)
121 		return NULL;
122 
123 	split_sectors = max_discard_sectors;
124 
125 	/*
126 	 * If the next starting sector would be misaligned, stop the discard at
127 	 * the previous aligned sector.
128 	 */
129 	alignment = (q->limits.discard_alignment >> 9) % granularity;
130 
131 	tmp = bio->bi_iter.bi_sector + split_sectors - alignment;
132 	tmp = sector_div(tmp, granularity);
133 
134 	if (split_sectors > tmp)
135 		split_sectors -= tmp;
136 
137 	return bio_split(bio, split_sectors, GFP_NOIO, bs);
138 }
139 
140 static struct bio *blk_bio_write_zeroes_split(struct request_queue *q,
141 		struct bio *bio, struct bio_set *bs, unsigned *nsegs)
142 {
143 	*nsegs = 0;
144 
145 	if (!q->limits.max_write_zeroes_sectors)
146 		return NULL;
147 
148 	if (bio_sectors(bio) <= q->limits.max_write_zeroes_sectors)
149 		return NULL;
150 
151 	return bio_split(bio, q->limits.max_write_zeroes_sectors, GFP_NOIO, bs);
152 }
153 
154 static struct bio *blk_bio_write_same_split(struct request_queue *q,
155 					    struct bio *bio,
156 					    struct bio_set *bs,
157 					    unsigned *nsegs)
158 {
159 	*nsegs = 1;
160 
161 	if (!q->limits.max_write_same_sectors)
162 		return NULL;
163 
164 	if (bio_sectors(bio) <= q->limits.max_write_same_sectors)
165 		return NULL;
166 
167 	return bio_split(bio, q->limits.max_write_same_sectors, GFP_NOIO, bs);
168 }
169 
170 /*
171  * Return the maximum number of sectors from the start of a bio that may be
172  * submitted as a single request to a block device. If enough sectors remain,
173  * align the end to the physical block size. Otherwise align the end to the
174  * logical block size. This approach minimizes the number of non-aligned
175  * requests that are submitted to a block device if the start of a bio is not
176  * aligned to a physical block boundary.
177  */
178 static inline unsigned get_max_io_size(struct request_queue *q,
179 				       struct bio *bio)
180 {
181 	unsigned sectors = blk_max_size_offset(q, bio->bi_iter.bi_sector, 0);
182 	unsigned max_sectors = sectors;
183 	unsigned pbs = queue_physical_block_size(q) >> SECTOR_SHIFT;
184 	unsigned lbs = queue_logical_block_size(q) >> SECTOR_SHIFT;
185 	unsigned start_offset = bio->bi_iter.bi_sector & (pbs - 1);
186 
187 	max_sectors += start_offset;
188 	max_sectors &= ~(pbs - 1);
189 	if (max_sectors > start_offset)
190 		return max_sectors - start_offset;
191 
192 	return sectors & ~(lbs - 1);
193 }
194 
195 static inline unsigned get_max_segment_size(const struct request_queue *q,
196 					    struct page *start_page,
197 					    unsigned long offset)
198 {
199 	unsigned long mask = queue_segment_boundary(q);
200 
201 	offset = mask & (page_to_phys(start_page) + offset);
202 
203 	/*
204 	 * overflow may be triggered in case of zero page physical address
205 	 * on 32bit arch, use queue's max segment size when that happens.
206 	 */
207 	return min_not_zero(mask - offset + 1,
208 			(unsigned long)queue_max_segment_size(q));
209 }
210 
211 /**
212  * bvec_split_segs - verify whether or not a bvec should be split in the middle
213  * @q:        [in] request queue associated with the bio associated with @bv
214  * @bv:       [in] bvec to examine
215  * @nsegs:    [in,out] Number of segments in the bio being built. Incremented
216  *            by the number of segments from @bv that may be appended to that
217  *            bio without exceeding @max_segs
218  * @sectors:  [in,out] Number of sectors in the bio being built. Incremented
219  *            by the number of sectors from @bv that may be appended to that
220  *            bio without exceeding @max_sectors
221  * @max_segs: [in] upper bound for *@nsegs
222  * @max_sectors: [in] upper bound for *@sectors
223  *
224  * When splitting a bio, it can happen that a bvec is encountered that is too
225  * big to fit in a single segment and hence that it has to be split in the
226  * middle. This function verifies whether or not that should happen. The value
227  * %true is returned if and only if appending the entire @bv to a bio with
228  * *@nsegs segments and *@sectors sectors would make that bio unacceptable for
229  * the block driver.
230  */
231 static bool bvec_split_segs(const struct request_queue *q,
232 			    const struct bio_vec *bv, unsigned *nsegs,
233 			    unsigned *sectors, unsigned max_segs,
234 			    unsigned max_sectors)
235 {
236 	unsigned max_len = (min(max_sectors, UINT_MAX >> 9) - *sectors) << 9;
237 	unsigned len = min(bv->bv_len, max_len);
238 	unsigned total_len = 0;
239 	unsigned seg_size = 0;
240 
241 	while (len && *nsegs < max_segs) {
242 		seg_size = get_max_segment_size(q, bv->bv_page,
243 						bv->bv_offset + total_len);
244 		seg_size = min(seg_size, len);
245 
246 		(*nsegs)++;
247 		total_len += seg_size;
248 		len -= seg_size;
249 
250 		if ((bv->bv_offset + total_len) & queue_virt_boundary(q))
251 			break;
252 	}
253 
254 	*sectors += total_len >> 9;
255 
256 	/* tell the caller to split the bvec if it is too big to fit */
257 	return len > 0 || bv->bv_len > max_len;
258 }
259 
260 /**
261  * blk_bio_segment_split - split a bio in two bios
262  * @q:    [in] request queue pointer
263  * @bio:  [in] bio to be split
264  * @bs:	  [in] bio set to allocate the clone from
265  * @segs: [out] number of segments in the bio with the first half of the sectors
266  *
267  * Clone @bio, update the bi_iter of the clone to represent the first sectors
268  * of @bio and update @bio->bi_iter to represent the remaining sectors. The
269  * following is guaranteed for the cloned bio:
270  * - That it has at most get_max_io_size(@q, @bio) sectors.
271  * - That it has at most queue_max_segments(@q) segments.
272  *
273  * Except for discard requests the cloned bio will point at the bi_io_vec of
274  * the original bio. It is the responsibility of the caller to ensure that the
275  * original bio is not freed before the cloned bio. The caller is also
276  * responsible for ensuring that @bs is only destroyed after processing of the
277  * split bio has finished.
278  */
279 static struct bio *blk_bio_segment_split(struct request_queue *q,
280 					 struct bio *bio,
281 					 struct bio_set *bs,
282 					 unsigned *segs)
283 {
284 	struct bio_vec bv, bvprv, *bvprvp = NULL;
285 	struct bvec_iter iter;
286 	unsigned nsegs = 0, sectors = 0;
287 	const unsigned max_sectors = get_max_io_size(q, bio);
288 	const unsigned max_segs = queue_max_segments(q);
289 
290 	bio_for_each_bvec(bv, bio, iter) {
291 		/*
292 		 * If the queue doesn't support SG gaps and adding this
293 		 * offset would create a gap, disallow it.
294 		 */
295 		if (bvprvp && bvec_gap_to_prev(q, bvprvp, bv.bv_offset))
296 			goto split;
297 
298 		if (nsegs < max_segs &&
299 		    sectors + (bv.bv_len >> 9) <= max_sectors &&
300 		    bv.bv_offset + bv.bv_len <= PAGE_SIZE) {
301 			nsegs++;
302 			sectors += bv.bv_len >> 9;
303 		} else if (bvec_split_segs(q, &bv, &nsegs, &sectors, max_segs,
304 					 max_sectors)) {
305 			goto split;
306 		}
307 
308 		bvprv = bv;
309 		bvprvp = &bvprv;
310 	}
311 
312 	*segs = nsegs;
313 	return NULL;
314 split:
315 	*segs = nsegs;
316 
317 	/*
318 	 * Bio splitting may cause subtle trouble such as hang when doing sync
319 	 * iopoll in direct IO routine. Given performance gain of iopoll for
320 	 * big IO can be trival, disable iopoll when split needed.
321 	 */
322 	bio_clear_polled(bio);
323 	return bio_split(bio, sectors, GFP_NOIO, bs);
324 }
325 
326 /**
327  * __blk_queue_split - split a bio and submit the second half
328  * @q:       [in] request_queue new bio is being queued at
329  * @bio:     [in, out] bio to be split
330  * @nr_segs: [out] number of segments in the first bio
331  *
332  * Split a bio into two bios, chain the two bios, submit the second half and
333  * store a pointer to the first half in *@bio. If the second bio is still too
334  * big it will be split by a recursive call to this function. Since this
335  * function may allocate a new bio from q->bio_split, it is the responsibility
336  * of the caller to ensure that q->bio_split is only released after processing
337  * of the split bio has finished.
338  */
339 void __blk_queue_split(struct request_queue *q, struct bio **bio,
340 		       unsigned int *nr_segs)
341 {
342 	struct bio *split = NULL;
343 
344 	switch (bio_op(*bio)) {
345 	case REQ_OP_DISCARD:
346 	case REQ_OP_SECURE_ERASE:
347 		split = blk_bio_discard_split(q, *bio, &q->bio_split, nr_segs);
348 		break;
349 	case REQ_OP_WRITE_ZEROES:
350 		split = blk_bio_write_zeroes_split(q, *bio, &q->bio_split,
351 				nr_segs);
352 		break;
353 	case REQ_OP_WRITE_SAME:
354 		split = blk_bio_write_same_split(q, *bio, &q->bio_split,
355 				nr_segs);
356 		break;
357 	default:
358 		split = blk_bio_segment_split(q, *bio, &q->bio_split, nr_segs);
359 		break;
360 	}
361 
362 	if (split) {
363 		/* there isn't chance to merge the splitted bio */
364 		split->bi_opf |= REQ_NOMERGE;
365 
366 		bio_chain(split, *bio);
367 		trace_block_split(split, (*bio)->bi_iter.bi_sector);
368 		submit_bio_noacct(*bio);
369 		*bio = split;
370 
371 		blk_throtl_charge_bio_split(*bio);
372 	}
373 }
374 
375 /**
376  * blk_queue_split - split a bio and submit the second half
377  * @bio: [in, out] bio to be split
378  *
379  * Split a bio into two bios, chains the two bios, submit the second half and
380  * store a pointer to the first half in *@bio. Since this function may allocate
381  * a new bio from q->bio_split, it is the responsibility of the caller to ensure
382  * that q->bio_split is only released after processing of the split bio has
383  * finished.
384  */
385 void blk_queue_split(struct bio **bio)
386 {
387 	struct request_queue *q = bdev_get_queue((*bio)->bi_bdev);
388 	unsigned int nr_segs;
389 
390 	if (blk_may_split(q, *bio))
391 		__blk_queue_split(q, bio, &nr_segs);
392 }
393 EXPORT_SYMBOL(blk_queue_split);
394 
395 unsigned int blk_recalc_rq_segments(struct request *rq)
396 {
397 	unsigned int nr_phys_segs = 0;
398 	unsigned int nr_sectors = 0;
399 	struct req_iterator iter;
400 	struct bio_vec bv;
401 
402 	if (!rq->bio)
403 		return 0;
404 
405 	switch (bio_op(rq->bio)) {
406 	case REQ_OP_DISCARD:
407 	case REQ_OP_SECURE_ERASE:
408 		if (queue_max_discard_segments(rq->q) > 1) {
409 			struct bio *bio = rq->bio;
410 
411 			for_each_bio(bio)
412 				nr_phys_segs++;
413 			return nr_phys_segs;
414 		}
415 		return 1;
416 	case REQ_OP_WRITE_ZEROES:
417 		return 0;
418 	case REQ_OP_WRITE_SAME:
419 		return 1;
420 	}
421 
422 	rq_for_each_bvec(bv, rq, iter)
423 		bvec_split_segs(rq->q, &bv, &nr_phys_segs, &nr_sectors,
424 				UINT_MAX, UINT_MAX);
425 	return nr_phys_segs;
426 }
427 
428 static inline struct scatterlist *blk_next_sg(struct scatterlist **sg,
429 		struct scatterlist *sglist)
430 {
431 	if (!*sg)
432 		return sglist;
433 
434 	/*
435 	 * If the driver previously mapped a shorter list, we could see a
436 	 * termination bit prematurely unless it fully inits the sg table
437 	 * on each mapping. We KNOW that there must be more entries here
438 	 * or the driver would be buggy, so force clear the termination bit
439 	 * to avoid doing a full sg_init_table() in drivers for each command.
440 	 */
441 	sg_unmark_end(*sg);
442 	return sg_next(*sg);
443 }
444 
445 static unsigned blk_bvec_map_sg(struct request_queue *q,
446 		struct bio_vec *bvec, struct scatterlist *sglist,
447 		struct scatterlist **sg)
448 {
449 	unsigned nbytes = bvec->bv_len;
450 	unsigned nsegs = 0, total = 0;
451 
452 	while (nbytes > 0) {
453 		unsigned offset = bvec->bv_offset + total;
454 		unsigned len = min(get_max_segment_size(q, bvec->bv_page,
455 					offset), nbytes);
456 		struct page *page = bvec->bv_page;
457 
458 		/*
459 		 * Unfortunately a fair number of drivers barf on scatterlists
460 		 * that have an offset larger than PAGE_SIZE, despite other
461 		 * subsystems dealing with that invariant just fine.  For now
462 		 * stick to the legacy format where we never present those from
463 		 * the block layer, but the code below should be removed once
464 		 * these offenders (mostly MMC/SD drivers) are fixed.
465 		 */
466 		page += (offset >> PAGE_SHIFT);
467 		offset &= ~PAGE_MASK;
468 
469 		*sg = blk_next_sg(sg, sglist);
470 		sg_set_page(*sg, page, len, offset);
471 
472 		total += len;
473 		nbytes -= len;
474 		nsegs++;
475 	}
476 
477 	return nsegs;
478 }
479 
480 static inline int __blk_bvec_map_sg(struct bio_vec bv,
481 		struct scatterlist *sglist, struct scatterlist **sg)
482 {
483 	*sg = blk_next_sg(sg, sglist);
484 	sg_set_page(*sg, bv.bv_page, bv.bv_len, bv.bv_offset);
485 	return 1;
486 }
487 
488 /* only try to merge bvecs into one sg if they are from two bios */
489 static inline bool
490 __blk_segment_map_sg_merge(struct request_queue *q, struct bio_vec *bvec,
491 			   struct bio_vec *bvprv, struct scatterlist **sg)
492 {
493 
494 	int nbytes = bvec->bv_len;
495 
496 	if (!*sg)
497 		return false;
498 
499 	if ((*sg)->length + nbytes > queue_max_segment_size(q))
500 		return false;
501 
502 	if (!biovec_phys_mergeable(q, bvprv, bvec))
503 		return false;
504 
505 	(*sg)->length += nbytes;
506 
507 	return true;
508 }
509 
510 static int __blk_bios_map_sg(struct request_queue *q, struct bio *bio,
511 			     struct scatterlist *sglist,
512 			     struct scatterlist **sg)
513 {
514 	struct bio_vec bvec, bvprv = { NULL };
515 	struct bvec_iter iter;
516 	int nsegs = 0;
517 	bool new_bio = false;
518 
519 	for_each_bio(bio) {
520 		bio_for_each_bvec(bvec, bio, iter) {
521 			/*
522 			 * Only try to merge bvecs from two bios given we
523 			 * have done bio internal merge when adding pages
524 			 * to bio
525 			 */
526 			if (new_bio &&
527 			    __blk_segment_map_sg_merge(q, &bvec, &bvprv, sg))
528 				goto next_bvec;
529 
530 			if (bvec.bv_offset + bvec.bv_len <= PAGE_SIZE)
531 				nsegs += __blk_bvec_map_sg(bvec, sglist, sg);
532 			else
533 				nsegs += blk_bvec_map_sg(q, &bvec, sglist, sg);
534  next_bvec:
535 			new_bio = false;
536 		}
537 		if (likely(bio->bi_iter.bi_size)) {
538 			bvprv = bvec;
539 			new_bio = true;
540 		}
541 	}
542 
543 	return nsegs;
544 }
545 
546 /*
547  * map a request to scatterlist, return number of sg entries setup. Caller
548  * must make sure sg can hold rq->nr_phys_segments entries
549  */
550 int __blk_rq_map_sg(struct request_queue *q, struct request *rq,
551 		struct scatterlist *sglist, struct scatterlist **last_sg)
552 {
553 	int nsegs = 0;
554 
555 	if (rq->rq_flags & RQF_SPECIAL_PAYLOAD)
556 		nsegs = __blk_bvec_map_sg(rq->special_vec, sglist, last_sg);
557 	else if (rq->bio && bio_op(rq->bio) == REQ_OP_WRITE_SAME)
558 		nsegs = __blk_bvec_map_sg(bio_iovec(rq->bio), sglist, last_sg);
559 	else if (rq->bio)
560 		nsegs = __blk_bios_map_sg(q, rq->bio, sglist, last_sg);
561 
562 	if (*last_sg)
563 		sg_mark_end(*last_sg);
564 
565 	/*
566 	 * Something must have been wrong if the figured number of
567 	 * segment is bigger than number of req's physical segments
568 	 */
569 	WARN_ON(nsegs > blk_rq_nr_phys_segments(rq));
570 
571 	return nsegs;
572 }
573 EXPORT_SYMBOL(__blk_rq_map_sg);
574 
575 static inline unsigned int blk_rq_get_max_segments(struct request *rq)
576 {
577 	if (req_op(rq) == REQ_OP_DISCARD)
578 		return queue_max_discard_segments(rq->q);
579 	return queue_max_segments(rq->q);
580 }
581 
582 static inline unsigned int blk_rq_get_max_sectors(struct request *rq,
583 						  sector_t offset)
584 {
585 	struct request_queue *q = rq->q;
586 
587 	if (blk_rq_is_passthrough(rq))
588 		return q->limits.max_hw_sectors;
589 
590 	if (!q->limits.chunk_sectors ||
591 	    req_op(rq) == REQ_OP_DISCARD ||
592 	    req_op(rq) == REQ_OP_SECURE_ERASE)
593 		return blk_queue_get_max_sectors(q, req_op(rq));
594 
595 	return min(blk_max_size_offset(q, offset, 0),
596 			blk_queue_get_max_sectors(q, req_op(rq)));
597 }
598 
599 static inline int ll_new_hw_segment(struct request *req, struct bio *bio,
600 		unsigned int nr_phys_segs)
601 {
602 	if (blk_integrity_merge_bio(req->q, req, bio) == false)
603 		goto no_merge;
604 
605 	/* discard request merge won't add new segment */
606 	if (req_op(req) == REQ_OP_DISCARD)
607 		return 1;
608 
609 	if (req->nr_phys_segments + nr_phys_segs > blk_rq_get_max_segments(req))
610 		goto no_merge;
611 
612 	/*
613 	 * This will form the start of a new hw segment.  Bump both
614 	 * counters.
615 	 */
616 	req->nr_phys_segments += nr_phys_segs;
617 	return 1;
618 
619 no_merge:
620 	req_set_nomerge(req->q, req);
621 	return 0;
622 }
623 
624 int ll_back_merge_fn(struct request *req, struct bio *bio, unsigned int nr_segs)
625 {
626 	if (req_gap_back_merge(req, bio))
627 		return 0;
628 	if (blk_integrity_rq(req) &&
629 	    integrity_req_gap_back_merge(req, bio))
630 		return 0;
631 	if (!bio_crypt_ctx_back_mergeable(req, bio))
632 		return 0;
633 	if (blk_rq_sectors(req) + bio_sectors(bio) >
634 	    blk_rq_get_max_sectors(req, blk_rq_pos(req))) {
635 		req_set_nomerge(req->q, req);
636 		return 0;
637 	}
638 
639 	return ll_new_hw_segment(req, bio, nr_segs);
640 }
641 
642 static int ll_front_merge_fn(struct request *req, struct bio *bio,
643 		unsigned int nr_segs)
644 {
645 	if (req_gap_front_merge(req, bio))
646 		return 0;
647 	if (blk_integrity_rq(req) &&
648 	    integrity_req_gap_front_merge(req, bio))
649 		return 0;
650 	if (!bio_crypt_ctx_front_mergeable(req, bio))
651 		return 0;
652 	if (blk_rq_sectors(req) + bio_sectors(bio) >
653 	    blk_rq_get_max_sectors(req, bio->bi_iter.bi_sector)) {
654 		req_set_nomerge(req->q, req);
655 		return 0;
656 	}
657 
658 	return ll_new_hw_segment(req, bio, nr_segs);
659 }
660 
661 static bool req_attempt_discard_merge(struct request_queue *q, struct request *req,
662 		struct request *next)
663 {
664 	unsigned short segments = blk_rq_nr_discard_segments(req);
665 
666 	if (segments >= queue_max_discard_segments(q))
667 		goto no_merge;
668 	if (blk_rq_sectors(req) + bio_sectors(next->bio) >
669 	    blk_rq_get_max_sectors(req, blk_rq_pos(req)))
670 		goto no_merge;
671 
672 	req->nr_phys_segments = segments + blk_rq_nr_discard_segments(next);
673 	return true;
674 no_merge:
675 	req_set_nomerge(q, req);
676 	return false;
677 }
678 
679 static int ll_merge_requests_fn(struct request_queue *q, struct request *req,
680 				struct request *next)
681 {
682 	int total_phys_segments;
683 
684 	if (req_gap_back_merge(req, next->bio))
685 		return 0;
686 
687 	/*
688 	 * Will it become too large?
689 	 */
690 	if ((blk_rq_sectors(req) + blk_rq_sectors(next)) >
691 	    blk_rq_get_max_sectors(req, blk_rq_pos(req)))
692 		return 0;
693 
694 	total_phys_segments = req->nr_phys_segments + next->nr_phys_segments;
695 	if (total_phys_segments > blk_rq_get_max_segments(req))
696 		return 0;
697 
698 	if (blk_integrity_merge_rq(q, req, next) == false)
699 		return 0;
700 
701 	if (!bio_crypt_ctx_merge_rq(req, next))
702 		return 0;
703 
704 	/* Merge is OK... */
705 	req->nr_phys_segments = total_phys_segments;
706 	return 1;
707 }
708 
709 /**
710  * blk_rq_set_mixed_merge - mark a request as mixed merge
711  * @rq: request to mark as mixed merge
712  *
713  * Description:
714  *     @rq is about to be mixed merged.  Make sure the attributes
715  *     which can be mixed are set in each bio and mark @rq as mixed
716  *     merged.
717  */
718 void blk_rq_set_mixed_merge(struct request *rq)
719 {
720 	unsigned int ff = rq->cmd_flags & REQ_FAILFAST_MASK;
721 	struct bio *bio;
722 
723 	if (rq->rq_flags & RQF_MIXED_MERGE)
724 		return;
725 
726 	/*
727 	 * @rq will no longer represent mixable attributes for all the
728 	 * contained bios.  It will just track those of the first one.
729 	 * Distributes the attributs to each bio.
730 	 */
731 	for (bio = rq->bio; bio; bio = bio->bi_next) {
732 		WARN_ON_ONCE((bio->bi_opf & REQ_FAILFAST_MASK) &&
733 			     (bio->bi_opf & REQ_FAILFAST_MASK) != ff);
734 		bio->bi_opf |= ff;
735 	}
736 	rq->rq_flags |= RQF_MIXED_MERGE;
737 }
738 
739 static void blk_account_io_merge_request(struct request *req)
740 {
741 	if (blk_do_io_stat(req)) {
742 		part_stat_lock();
743 		part_stat_inc(req->part, merges[op_stat_group(req_op(req))]);
744 		part_stat_unlock();
745 	}
746 }
747 
748 static enum elv_merge blk_try_req_merge(struct request *req,
749 					struct request *next)
750 {
751 	if (blk_discard_mergable(req))
752 		return ELEVATOR_DISCARD_MERGE;
753 	else if (blk_rq_pos(req) + blk_rq_sectors(req) == blk_rq_pos(next))
754 		return ELEVATOR_BACK_MERGE;
755 
756 	return ELEVATOR_NO_MERGE;
757 }
758 
759 static inline bool blk_write_same_mergeable(struct bio *a, struct bio *b)
760 {
761 	if (bio_page(a) == bio_page(b) && bio_offset(a) == bio_offset(b))
762 		return true;
763 	return false;
764 }
765 
766 /*
767  * For non-mq, this has to be called with the request spinlock acquired.
768  * For mq with scheduling, the appropriate queue wide lock should be held.
769  */
770 static struct request *attempt_merge(struct request_queue *q,
771 				     struct request *req, struct request *next)
772 {
773 	if (!rq_mergeable(req) || !rq_mergeable(next))
774 		return NULL;
775 
776 	if (req_op(req) != req_op(next))
777 		return NULL;
778 
779 	if (rq_data_dir(req) != rq_data_dir(next)
780 	    || req->rq_disk != next->rq_disk)
781 		return NULL;
782 
783 	if (req_op(req) == REQ_OP_WRITE_SAME &&
784 	    !blk_write_same_mergeable(req->bio, next->bio))
785 		return NULL;
786 
787 	/*
788 	 * Don't allow merge of different write hints, or for a hint with
789 	 * non-hint IO.
790 	 */
791 	if (req->write_hint != next->write_hint)
792 		return NULL;
793 
794 	if (req->ioprio != next->ioprio)
795 		return NULL;
796 
797 	/*
798 	 * If we are allowed to merge, then append bio list
799 	 * from next to rq and release next. merge_requests_fn
800 	 * will have updated segment counts, update sector
801 	 * counts here. Handle DISCARDs separately, as they
802 	 * have separate settings.
803 	 */
804 
805 	switch (blk_try_req_merge(req, next)) {
806 	case ELEVATOR_DISCARD_MERGE:
807 		if (!req_attempt_discard_merge(q, req, next))
808 			return NULL;
809 		break;
810 	case ELEVATOR_BACK_MERGE:
811 		if (!ll_merge_requests_fn(q, req, next))
812 			return NULL;
813 		break;
814 	default:
815 		return NULL;
816 	}
817 
818 	/*
819 	 * If failfast settings disagree or any of the two is already
820 	 * a mixed merge, mark both as mixed before proceeding.  This
821 	 * makes sure that all involved bios have mixable attributes
822 	 * set properly.
823 	 */
824 	if (((req->rq_flags | next->rq_flags) & RQF_MIXED_MERGE) ||
825 	    (req->cmd_flags & REQ_FAILFAST_MASK) !=
826 	    (next->cmd_flags & REQ_FAILFAST_MASK)) {
827 		blk_rq_set_mixed_merge(req);
828 		blk_rq_set_mixed_merge(next);
829 	}
830 
831 	/*
832 	 * At this point we have either done a back merge or front merge. We
833 	 * need the smaller start_time_ns of the merged requests to be the
834 	 * current request for accounting purposes.
835 	 */
836 	if (next->start_time_ns < req->start_time_ns)
837 		req->start_time_ns = next->start_time_ns;
838 
839 	req->biotail->bi_next = next->bio;
840 	req->biotail = next->biotail;
841 
842 	req->__data_len += blk_rq_bytes(next);
843 
844 	if (!blk_discard_mergable(req))
845 		elv_merge_requests(q, req, next);
846 
847 	/*
848 	 * 'next' is going away, so update stats accordingly
849 	 */
850 	blk_account_io_merge_request(next);
851 
852 	trace_block_rq_merge(next);
853 
854 	/*
855 	 * ownership of bio passed from next to req, return 'next' for
856 	 * the caller to free
857 	 */
858 	next->bio = NULL;
859 	return next;
860 }
861 
862 static struct request *attempt_back_merge(struct request_queue *q,
863 		struct request *rq)
864 {
865 	struct request *next = elv_latter_request(q, rq);
866 
867 	if (next)
868 		return attempt_merge(q, rq, next);
869 
870 	return NULL;
871 }
872 
873 static struct request *attempt_front_merge(struct request_queue *q,
874 		struct request *rq)
875 {
876 	struct request *prev = elv_former_request(q, rq);
877 
878 	if (prev)
879 		return attempt_merge(q, prev, rq);
880 
881 	return NULL;
882 }
883 
884 /*
885  * Try to merge 'next' into 'rq'. Return true if the merge happened, false
886  * otherwise. The caller is responsible for freeing 'next' if the merge
887  * happened.
888  */
889 bool blk_attempt_req_merge(struct request_queue *q, struct request *rq,
890 			   struct request *next)
891 {
892 	return attempt_merge(q, rq, next);
893 }
894 
895 bool blk_rq_merge_ok(struct request *rq, struct bio *bio)
896 {
897 	if (!rq_mergeable(rq) || !bio_mergeable(bio))
898 		return false;
899 
900 	if (req_op(rq) != bio_op(bio))
901 		return false;
902 
903 	/* different data direction or already started, don't merge */
904 	if (bio_data_dir(bio) != rq_data_dir(rq))
905 		return false;
906 
907 	/* must be same device */
908 	if (rq->rq_disk != bio->bi_bdev->bd_disk)
909 		return false;
910 
911 	/* only merge integrity protected bio into ditto rq */
912 	if (blk_integrity_merge_bio(rq->q, rq, bio) == false)
913 		return false;
914 
915 	/* Only merge if the crypt contexts are compatible */
916 	if (!bio_crypt_rq_ctx_compatible(rq, bio))
917 		return false;
918 
919 	/* must be using the same buffer */
920 	if (req_op(rq) == REQ_OP_WRITE_SAME &&
921 	    !blk_write_same_mergeable(rq->bio, bio))
922 		return false;
923 
924 	/*
925 	 * Don't allow merge of different write hints, or for a hint with
926 	 * non-hint IO.
927 	 */
928 	if (rq->write_hint != bio->bi_write_hint)
929 		return false;
930 
931 	if (rq->ioprio != bio_prio(bio))
932 		return false;
933 
934 	return true;
935 }
936 
937 enum elv_merge blk_try_merge(struct request *rq, struct bio *bio)
938 {
939 	if (blk_discard_mergable(rq))
940 		return ELEVATOR_DISCARD_MERGE;
941 	else if (blk_rq_pos(rq) + blk_rq_sectors(rq) == bio->bi_iter.bi_sector)
942 		return ELEVATOR_BACK_MERGE;
943 	else if (blk_rq_pos(rq) - bio_sectors(bio) == bio->bi_iter.bi_sector)
944 		return ELEVATOR_FRONT_MERGE;
945 	return ELEVATOR_NO_MERGE;
946 }
947 
948 static void blk_account_io_merge_bio(struct request *req)
949 {
950 	if (!blk_do_io_stat(req))
951 		return;
952 
953 	part_stat_lock();
954 	part_stat_inc(req->part, merges[op_stat_group(req_op(req))]);
955 	part_stat_unlock();
956 }
957 
958 enum bio_merge_status {
959 	BIO_MERGE_OK,
960 	BIO_MERGE_NONE,
961 	BIO_MERGE_FAILED,
962 };
963 
964 static enum bio_merge_status bio_attempt_back_merge(struct request *req,
965 		struct bio *bio, unsigned int nr_segs)
966 {
967 	const int ff = bio->bi_opf & REQ_FAILFAST_MASK;
968 
969 	if (!ll_back_merge_fn(req, bio, nr_segs))
970 		return BIO_MERGE_FAILED;
971 
972 	trace_block_bio_backmerge(bio);
973 	rq_qos_merge(req->q, req, bio);
974 
975 	if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
976 		blk_rq_set_mixed_merge(req);
977 
978 	req->biotail->bi_next = bio;
979 	req->biotail = bio;
980 	req->__data_len += bio->bi_iter.bi_size;
981 
982 	bio_crypt_free_ctx(bio);
983 
984 	blk_account_io_merge_bio(req);
985 	return BIO_MERGE_OK;
986 }
987 
988 static enum bio_merge_status bio_attempt_front_merge(struct request *req,
989 		struct bio *bio, unsigned int nr_segs)
990 {
991 	const int ff = bio->bi_opf & REQ_FAILFAST_MASK;
992 
993 	if (!ll_front_merge_fn(req, bio, nr_segs))
994 		return BIO_MERGE_FAILED;
995 
996 	trace_block_bio_frontmerge(bio);
997 	rq_qos_merge(req->q, req, bio);
998 
999 	if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
1000 		blk_rq_set_mixed_merge(req);
1001 
1002 	bio->bi_next = req->bio;
1003 	req->bio = bio;
1004 
1005 	req->__sector = bio->bi_iter.bi_sector;
1006 	req->__data_len += bio->bi_iter.bi_size;
1007 
1008 	bio_crypt_do_front_merge(req, bio);
1009 
1010 	blk_account_io_merge_bio(req);
1011 	return BIO_MERGE_OK;
1012 }
1013 
1014 static enum bio_merge_status bio_attempt_discard_merge(struct request_queue *q,
1015 		struct request *req, struct bio *bio)
1016 {
1017 	unsigned short segments = blk_rq_nr_discard_segments(req);
1018 
1019 	if (segments >= queue_max_discard_segments(q))
1020 		goto no_merge;
1021 	if (blk_rq_sectors(req) + bio_sectors(bio) >
1022 	    blk_rq_get_max_sectors(req, blk_rq_pos(req)))
1023 		goto no_merge;
1024 
1025 	rq_qos_merge(q, req, bio);
1026 
1027 	req->biotail->bi_next = bio;
1028 	req->biotail = bio;
1029 	req->__data_len += bio->bi_iter.bi_size;
1030 	req->nr_phys_segments = segments + 1;
1031 
1032 	blk_account_io_merge_bio(req);
1033 	return BIO_MERGE_OK;
1034 no_merge:
1035 	req_set_nomerge(q, req);
1036 	return BIO_MERGE_FAILED;
1037 }
1038 
1039 static enum bio_merge_status blk_attempt_bio_merge(struct request_queue *q,
1040 						   struct request *rq,
1041 						   struct bio *bio,
1042 						   unsigned int nr_segs,
1043 						   bool sched_allow_merge)
1044 {
1045 	if (!blk_rq_merge_ok(rq, bio))
1046 		return BIO_MERGE_NONE;
1047 
1048 	switch (blk_try_merge(rq, bio)) {
1049 	case ELEVATOR_BACK_MERGE:
1050 		if (!sched_allow_merge || blk_mq_sched_allow_merge(q, rq, bio))
1051 			return bio_attempt_back_merge(rq, bio, nr_segs);
1052 		break;
1053 	case ELEVATOR_FRONT_MERGE:
1054 		if (!sched_allow_merge || blk_mq_sched_allow_merge(q, rq, bio))
1055 			return bio_attempt_front_merge(rq, bio, nr_segs);
1056 		break;
1057 	case ELEVATOR_DISCARD_MERGE:
1058 		return bio_attempt_discard_merge(q, rq, bio);
1059 	default:
1060 		return BIO_MERGE_NONE;
1061 	}
1062 
1063 	return BIO_MERGE_FAILED;
1064 }
1065 
1066 /**
1067  * blk_attempt_plug_merge - try to merge with %current's plugged list
1068  * @q: request_queue new bio is being queued at
1069  * @bio: new bio being queued
1070  * @nr_segs: number of segments in @bio
1071  * from the passed in @q already in the plug list
1072  *
1073  * Determine whether @bio being queued on @q can be merged with the previous
1074  * request on %current's plugged list.  Returns %true if merge was successful,
1075  * otherwise %false.
1076  *
1077  * Plugging coalesces IOs from the same issuer for the same purpose without
1078  * going through @q->queue_lock.  As such it's more of an issuing mechanism
1079  * than scheduling, and the request, while may have elvpriv data, is not
1080  * added on the elevator at this point.  In addition, we don't have
1081  * reliable access to the elevator outside queue lock.  Only check basic
1082  * merging parameters without querying the elevator.
1083  *
1084  * Caller must ensure !blk_queue_nomerges(q) beforehand.
1085  */
1086 bool blk_attempt_plug_merge(struct request_queue *q, struct bio *bio,
1087 		unsigned int nr_segs)
1088 {
1089 	struct blk_plug *plug;
1090 	struct request *rq;
1091 
1092 	plug = blk_mq_plug(q, bio);
1093 	if (!plug || rq_list_empty(plug->mq_list))
1094 		return false;
1095 
1096 	/* check the previously added entry for a quick merge attempt */
1097 	rq = rq_list_peek(&plug->mq_list);
1098 	if (rq->q == q) {
1099 		if (blk_attempt_bio_merge(q, rq, bio, nr_segs, false) ==
1100 				BIO_MERGE_OK)
1101 			return true;
1102 	}
1103 	return false;
1104 }
1105 
1106 /*
1107  * Iterate list of requests and see if we can merge this bio with any
1108  * of them.
1109  */
1110 bool blk_bio_list_merge(struct request_queue *q, struct list_head *list,
1111 			struct bio *bio, unsigned int nr_segs)
1112 {
1113 	struct request *rq;
1114 	int checked = 8;
1115 
1116 	list_for_each_entry_reverse(rq, list, queuelist) {
1117 		if (!checked--)
1118 			break;
1119 
1120 		switch (blk_attempt_bio_merge(q, rq, bio, nr_segs, true)) {
1121 		case BIO_MERGE_NONE:
1122 			continue;
1123 		case BIO_MERGE_OK:
1124 			return true;
1125 		case BIO_MERGE_FAILED:
1126 			return false;
1127 		}
1128 
1129 	}
1130 
1131 	return false;
1132 }
1133 EXPORT_SYMBOL_GPL(blk_bio_list_merge);
1134 
1135 bool blk_mq_sched_try_merge(struct request_queue *q, struct bio *bio,
1136 		unsigned int nr_segs, struct request **merged_request)
1137 {
1138 	struct request *rq;
1139 
1140 	switch (elv_merge(q, &rq, bio)) {
1141 	case ELEVATOR_BACK_MERGE:
1142 		if (!blk_mq_sched_allow_merge(q, rq, bio))
1143 			return false;
1144 		if (bio_attempt_back_merge(rq, bio, nr_segs) != BIO_MERGE_OK)
1145 			return false;
1146 		*merged_request = attempt_back_merge(q, rq);
1147 		if (!*merged_request)
1148 			elv_merged_request(q, rq, ELEVATOR_BACK_MERGE);
1149 		return true;
1150 	case ELEVATOR_FRONT_MERGE:
1151 		if (!blk_mq_sched_allow_merge(q, rq, bio))
1152 			return false;
1153 		if (bio_attempt_front_merge(rq, bio, nr_segs) != BIO_MERGE_OK)
1154 			return false;
1155 		*merged_request = attempt_front_merge(q, rq);
1156 		if (!*merged_request)
1157 			elv_merged_request(q, rq, ELEVATOR_FRONT_MERGE);
1158 		return true;
1159 	case ELEVATOR_DISCARD_MERGE:
1160 		return bio_attempt_discard_merge(q, rq, bio) == BIO_MERGE_OK;
1161 	default:
1162 		return false;
1163 	}
1164 }
1165 EXPORT_SYMBOL_GPL(blk_mq_sched_try_merge);
1166