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