xref: /linux/block/blk-merge.c (revision 4b99990cdf9560e8a071640baf19f312e6ae02f4)
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/part_stat.h>
11 #include <linux/blk-cgroup.h>
12 
13 #include <trace/events/block.h>
14 
15 #include "blk.h"
16 #include "blk-mq-sched.h"
17 #include "blk-rq-qos.h"
18 #include "blk-throttle.h"
19 
20 static inline void bio_get_first_bvec(struct bio *bio, struct bio_vec *bv)
21 {
22 	*bv = mp_bvec_iter_bvec(bio->bi_io_vec, bio->bi_iter);
23 }
24 
25 static inline void bio_get_last_bvec(struct bio *bio, struct bio_vec *bv)
26 {
27 	struct bvec_iter iter = bio->bi_iter;
28 	int idx;
29 
30 	bio_get_first_bvec(bio, bv);
31 	if (bv->bv_len == bio->bi_iter.bi_size)
32 		return;		/* this bio only has a single bvec */
33 
34 	bio_advance_iter(bio, &iter, iter.bi_size);
35 
36 	if (!iter.bi_bvec_done)
37 		idx = iter.bi_idx - 1;
38 	else	/* in the middle of bvec */
39 		idx = iter.bi_idx;
40 
41 	*bv = bio->bi_io_vec[idx];
42 
43 	/*
44 	 * iter.bi_bvec_done records actual length of the last bvec
45 	 * if this bio ends in the middle of one io vector
46 	 */
47 	if (iter.bi_bvec_done)
48 		bv->bv_len = iter.bi_bvec_done;
49 }
50 
51 static inline bool bio_will_gap(struct request_queue *q,
52 		struct request *prev_rq, struct bio *prev, struct bio *next)
53 {
54 	struct bio_vec pb, nb;
55 
56 	if (!bio_has_data(prev) || !queue_virt_boundary(q))
57 		return false;
58 
59 	/*
60 	 * Don't merge if the 1st bio starts with non-zero offset, otherwise it
61 	 * is quite difficult to respect the sg gap limit.  We work hard to
62 	 * merge a huge number of small single bios in case of mkfs.
63 	 */
64 	if (prev_rq)
65 		bio_get_first_bvec(prev_rq->bio, &pb);
66 	else
67 		bio_get_first_bvec(prev, &pb);
68 	if (pb.bv_offset & queue_virt_boundary(q))
69 		return true;
70 
71 	/*
72 	 * We don't need to worry about the situation that the merged segment
73 	 * ends in unaligned virt boundary:
74 	 *
75 	 * - if 'pb' ends aligned, the merged segment ends aligned
76 	 * - if 'pb' ends unaligned, the next bio must include
77 	 *   one single bvec of 'nb', otherwise the 'nb' can't
78 	 *   merge with 'pb'
79 	 */
80 	bio_get_last_bvec(prev, &pb);
81 	bio_get_first_bvec(next, &nb);
82 	if (biovec_phys_mergeable(q, &pb, &nb))
83 		return false;
84 	return __bvec_gap_to_prev(&q->limits, &pb, nb.bv_offset);
85 }
86 
87 static inline bool req_gap_back_merge(struct request *req, struct bio *bio)
88 {
89 	return bio_will_gap(req->q, req, req->biotail, bio);
90 }
91 
92 static inline bool req_gap_front_merge(struct request *req, struct bio *bio)
93 {
94 	return bio_will_gap(req->q, NULL, bio, req->bio);
95 }
96 
97 /*
98  * The maximum size that a bio can fit has to be aligned down to the
99  * logical block size, which is the minimum accepted unit by hardware.
100  */
101 static unsigned int bio_allowed_max_sectors(const struct queue_limits *lim)
102 {
103 	return round_down(BIO_MAX_SIZE, lim->logical_block_size) >>
104 			SECTOR_SHIFT;
105 }
106 
107 /*
108  * bio_submit_split_bioset - Submit a bio, splitting it at a designated sector
109  * @bio:		the original bio to be submitted and split
110  * @split_sectors:	the sector count at which to split
111  * @bs:			the bio set used for allocating the new split bio
112  *
113  * The original bio is modified to contain the remaining sectors and submitted.
114  * The caller is responsible for submitting the returned bio.
115  *
116  * If succeed, the newly allocated bio representing the initial part will be
117  * returned, on failure NULL will be returned and original bio will fail.
118  */
119 struct bio *bio_submit_split_bioset(struct bio *bio, unsigned int split_sectors,
120 				    struct bio_set *bs)
121 {
122 	struct bio *split = bio_split(bio, split_sectors, GFP_NOIO, bs);
123 
124 	if (IS_ERR(split)) {
125 		bio_endio_status(bio, errno_to_blk_status(PTR_ERR(split)));
126 		return NULL;
127 	}
128 
129 	bio_chain(split, bio);
130 	trace_block_split(split, bio->bi_iter.bi_sector);
131 	WARN_ON_ONCE(bio_zone_write_plugging(bio));
132 
133 	if (should_fail_bio(bio))
134 		bio_io_error(bio);
135 	else if (!blk_throtl_bio(bio))
136 		submit_bio_noacct_nocheck(bio, true);
137 
138 	return split;
139 }
140 EXPORT_SYMBOL_GPL(bio_submit_split_bioset);
141 
142 static struct bio *bio_submit_split(struct bio *bio, int split_sectors)
143 {
144 	if (unlikely(split_sectors < 0)) {
145 		bio_endio_status(bio, errno_to_blk_status(split_sectors));
146 		return NULL;
147 	}
148 
149 	if (split_sectors) {
150 		bio = bio_submit_split_bioset(bio, split_sectors,
151 				&bio->bi_bdev->bd_disk->bio_split);
152 		if (bio)
153 			bio->bi_opf |= REQ_NOMERGE;
154 	}
155 
156 	return bio;
157 }
158 
159 static struct bio *__bio_split_discard(struct bio *bio,
160 		const struct queue_limits *lim, unsigned *nsegs,
161 		unsigned int max_sectors)
162 {
163 	unsigned int max_discard_sectors, granularity;
164 	sector_t tmp;
165 	unsigned split_sectors;
166 
167 	*nsegs = 1;
168 
169 	granularity = max(lim->discard_granularity >> 9, 1U);
170 
171 	max_discard_sectors = min(max_sectors, bio_allowed_max_sectors(lim));
172 	max_discard_sectors -= max_discard_sectors % granularity;
173 	if (unlikely(!max_discard_sectors))
174 		return bio;
175 
176 	if (bio_sectors(bio) <= max_discard_sectors)
177 		return bio;
178 
179 	split_sectors = max_discard_sectors;
180 
181 	/*
182 	 * If the next starting sector would be misaligned, stop the discard at
183 	 * the previous aligned sector.
184 	 */
185 	tmp = bio->bi_iter.bi_sector + split_sectors -
186 		((lim->discard_alignment >> 9) % granularity);
187 	tmp = sector_div(tmp, granularity);
188 
189 	if (split_sectors > tmp)
190 		split_sectors -= tmp;
191 
192 	return bio_submit_split(bio, split_sectors);
193 }
194 
195 struct bio *bio_split_discard(struct bio *bio, const struct queue_limits *lim,
196 		unsigned *nsegs)
197 {
198 	unsigned int max_sectors;
199 
200 	if (bio_op(bio) == REQ_OP_SECURE_ERASE)
201 		max_sectors = lim->max_secure_erase_sectors;
202 	else
203 		max_sectors = lim->max_discard_sectors;
204 
205 	return __bio_split_discard(bio, lim, nsegs, max_sectors);
206 }
207 
208 static inline unsigned int blk_boundary_sectors(const struct queue_limits *lim,
209 						bool is_atomic)
210 {
211 	/*
212 	 * chunk_sectors must be a multiple of atomic_write_boundary_sectors if
213 	 * both non-zero.
214 	 */
215 	if (is_atomic && lim->atomic_write_boundary_sectors)
216 		return lim->atomic_write_boundary_sectors;
217 
218 	return lim->chunk_sectors;
219 }
220 
221 /*
222  * Return the maximum number of sectors from the start of a bio that may be
223  * submitted as a single request to a block device. If enough sectors remain,
224  * align the end to the physical block size. Otherwise align the end to the
225  * logical block size. This approach minimizes the number of non-aligned
226  * requests that are submitted to a block device if the start of a bio is not
227  * aligned to a physical block boundary.
228  */
229 static inline unsigned get_max_io_size(struct bio *bio,
230 				       const struct queue_limits *lim)
231 {
232 	unsigned pbs = lim->physical_block_size >> SECTOR_SHIFT;
233 	unsigned lbs = lim->logical_block_size >> SECTOR_SHIFT;
234 	bool is_atomic = bio->bi_opf & REQ_ATOMIC;
235 	unsigned boundary_sectors = blk_boundary_sectors(lim, is_atomic);
236 	unsigned max_sectors, start, end;
237 
238 	/*
239 	 * We ignore lim->max_sectors for atomic writes because it may less
240 	 * than the actual bio size, which we cannot tolerate.
241 	 */
242 	if (bio_op(bio) == REQ_OP_WRITE_ZEROES)
243 		max_sectors = lim->max_write_zeroes_sectors;
244 	else if (is_atomic)
245 		max_sectors = lim->atomic_write_max_sectors;
246 	else
247 		max_sectors = lim->max_sectors;
248 
249 	if (boundary_sectors) {
250 		max_sectors = min(max_sectors,
251 			blk_boundary_sectors_left(bio->bi_iter.bi_sector,
252 					      boundary_sectors));
253 	}
254 
255 	start = bio->bi_iter.bi_sector & (pbs - 1);
256 	end = (start + max_sectors) & ~(pbs - 1);
257 	if (end > start)
258 		return end - start;
259 	return max_sectors & ~(lbs - 1);
260 }
261 
262 /**
263  * bvec_split_segs - verify whether or not a bvec should be split in the middle
264  * @lim:      [in] queue limits to split based on
265  * @bv:       [in] bvec to examine
266  * @nsegs:    [in,out] Number of segments in the bio being built. Incremented
267  *            by the number of segments from @bv that may be appended to that
268  *            bio without exceeding @max_segs
269  * @bytes:    [in,out] Number of bytes in the bio being built. Incremented
270  *            by the number of bytes from @bv that may be appended to that
271  *            bio without exceeding @max_bytes
272  * @max_segs: [in] upper bound for *@nsegs
273  * @max_bytes: [in] upper bound for *@bytes
274  *
275  * When splitting a bio, it can happen that a bvec is encountered that is too
276  * big to fit in a single segment and hence that it has to be split in the
277  * middle. This function verifies whether or not that should happen. The value
278  * %true is returned if and only if appending the entire @bv to a bio with
279  * *@nsegs segments and *@sectors sectors would make that bio unacceptable for
280  * the block driver.
281  */
282 static bool bvec_split_segs(const struct queue_limits *lim,
283 		const struct bio_vec *bv, unsigned *nsegs, unsigned *bytes,
284 		unsigned max_segs, unsigned max_bytes)
285 {
286 	unsigned max_len = max_bytes - *bytes;
287 	unsigned len = min(bv->bv_len, max_len);
288 	unsigned total_len = 0;
289 	unsigned seg_size = 0;
290 
291 	while (len && *nsegs < max_segs) {
292 		seg_size = get_max_segment_size(lim, bvec_phys(bv) + total_len, len);
293 
294 		(*nsegs)++;
295 		total_len += seg_size;
296 		len -= seg_size;
297 
298 		if ((bv->bv_offset + total_len) & lim->virt_boundary_mask)
299 			break;
300 	}
301 
302 	*bytes += total_len;
303 
304 	/* tell the caller to split the bvec if it is too big to fit */
305 	return len > 0 || bv->bv_len > max_len;
306 }
307 
308 static unsigned int bio_split_alignment(struct bio *bio,
309 		const struct queue_limits *lim)
310 {
311 	if (op_is_write(bio_op(bio)) && lim->zone_write_granularity)
312 		return lim->zone_write_granularity;
313 	return lim->logical_block_size;
314 }
315 
316 static inline unsigned int bvec_seg_gap(struct bio_vec *bvprv,
317 					struct bio_vec *bv)
318 {
319 	return bv->bv_offset | (bvprv->bv_offset + bvprv->bv_len);
320 }
321 
322 /**
323  * bio_split_io_at - check if and where to split a bio
324  * @bio:  [in] bio to be split
325  * @lim:  [in] queue limits to split based on
326  * @segs: [out] number of segments in the bio with the first half of the sectors
327  * @max_bytes: [in] maximum number of bytes per bio
328  * @len_align_mask: [in] length alignment mask for each vector
329  *
330  * Find out if @bio needs to be split to fit the queue limits in @lim and a
331  * maximum size of @max_bytes.  Returns a negative error number if @bio can't be
332  * split, 0 if the bio doesn't have to be split, or a positive sector offset if
333  * @bio needs to be split.
334  */
335 int bio_split_io_at(struct bio *bio, const struct queue_limits *lim,
336 		unsigned *segs, unsigned max_bytes, unsigned len_align_mask)
337 {
338 	struct bio_crypt_ctx *bc = bio_crypt_ctx(bio);
339 	struct bio_vec bv, bvprv, *bvprvp = NULL;
340 	unsigned nsegs = 0, bytes = 0, gaps = 0;
341 	struct bvec_iter iter;
342 	unsigned start_align_mask = lim->dma_alignment;
343 
344 	if (bc) {
345 		start_align_mask |= (bc->bc_key->crypto_cfg.data_unit_size - 1);
346 		len_align_mask |= (bc->bc_key->crypto_cfg.data_unit_size - 1);
347 	}
348 
349 	bio_for_each_bvec(bv, bio, iter) {
350 		if (bv.bv_offset & start_align_mask ||
351 		    bv.bv_len & len_align_mask)
352 			return -EINVAL;
353 
354 		/*
355 		 * If the queue doesn't support SG gaps and adding this
356 		 * offset would create a gap, disallow it.
357 		 */
358 		if (bvprvp) {
359 			if (bvec_gap_to_prev(lim, bvprvp, bv.bv_offset))
360 				goto split;
361 			gaps |= bvec_seg_gap(bvprvp, &bv);
362 		}
363 
364 		if (nsegs < lim->max_segments &&
365 		    bytes + bv.bv_len <= max_bytes &&
366 		    bv.bv_offset + bv.bv_len <= lim->max_fast_segment_size) {
367 			nsegs++;
368 			bytes += bv.bv_len;
369 		} else {
370 			if (bvec_split_segs(lim, &bv, &nsegs, &bytes,
371 					lim->max_segments, max_bytes))
372 				goto split;
373 		}
374 
375 		bvprv = bv;
376 		bvprvp = &bvprv;
377 	}
378 
379 	*segs = nsegs;
380 	bio->bi_bvec_gap_bit = ffs(gaps);
381 	return 0;
382 split:
383 	if (bio->bi_opf & REQ_ATOMIC)
384 		return -EINVAL;
385 
386 	/*
387 	 * We can't sanely support splitting for a REQ_NOWAIT bio. End it
388 	 * with EAGAIN if splitting is required and return an error pointer.
389 	 */
390 	if (bio->bi_opf & REQ_NOWAIT)
391 		return -EAGAIN;
392 
393 	*segs = nsegs;
394 
395 	/*
396 	 * Individual bvecs might not be logical block aligned. Round down the
397 	 * split size so that each bio is properly block size aligned, even if
398 	 * we do not use the full hardware limits.
399 	 *
400 	 * It is possible to submit a bio that can't be split into a valid io:
401 	 * there may either be too many discontiguous vectors for the max
402 	 * segments limit, or contain virtual boundary gaps without having a
403 	 * valid block sized split. A zero byte result means one of those
404 	 * conditions occured.
405 	 */
406 	bytes = ALIGN_DOWN(bytes, bio_split_alignment(bio, lim));
407 	if (!bytes)
408 		return -EINVAL;
409 
410 	/*
411 	 * Bio splitting may cause subtle trouble such as hang when doing sync
412 	 * iopoll in direct IO routine. Given performance gain of iopoll for
413 	 * big IO can be trival, disable iopoll when split needed.
414 	 */
415 	bio_clear_polled(bio);
416 	bio->bi_bvec_gap_bit = ffs(gaps);
417 	return bytes >> SECTOR_SHIFT;
418 }
419 EXPORT_SYMBOL_GPL(bio_split_io_at);
420 
421 struct bio *bio_split_rw(struct bio *bio, const struct queue_limits *lim,
422 		unsigned *nr_segs)
423 {
424 	return bio_submit_split(bio,
425 		bio_split_rw_at(bio, lim, nr_segs,
426 			get_max_io_size(bio, lim) << SECTOR_SHIFT));
427 }
428 
429 /*
430  * REQ_OP_ZONE_APPEND bios must never be split by the block layer.
431  *
432  * But we want the nr_segs calculation provided by bio_split_rw_at, and having
433  * a good sanity check that the submitter built the bio correctly is nice to
434  * have as well.
435  */
436 struct bio *bio_split_zone_append(struct bio *bio,
437 		const struct queue_limits *lim, unsigned *nr_segs)
438 {
439 	int split_sectors;
440 
441 	split_sectors = bio_split_rw_at(bio, lim, nr_segs,
442 			lim->max_zone_append_sectors << SECTOR_SHIFT);
443 	if (WARN_ON_ONCE(split_sectors > 0))
444 		split_sectors = -EINVAL;
445 	return bio_submit_split(bio, split_sectors);
446 }
447 
448 struct bio *bio_split_write_zeroes(struct bio *bio,
449 		const struct queue_limits *lim, unsigned *nsegs)
450 {
451 	unsigned int max_sectors = get_max_io_size(bio, lim);
452 
453 	*nsegs = 0;
454 
455 	/*
456 	 * An unset limit should normally not happen, as bio submission is keyed
457 	 * off having a non-zero limit.  But SCSI can clear the limit in the
458 	 * I/O completion handler, and we can race and see this.  Splitting to a
459 	 * zero limit obviously doesn't make sense, so band-aid it here.
460 	 */
461 	if (!max_sectors)
462 		return bio;
463 	if (bio_sectors(bio) <= max_sectors)
464 		return bio;
465 	return bio_submit_split(bio, max_sectors);
466 }
467 
468 /**
469  * bio_split_to_limits - split a bio to fit the queue limits
470  * @bio:     bio to be split
471  *
472  * Check if @bio needs splitting based on the queue limits of @bio->bi_bdev, and
473  * if so split off a bio fitting the limits from the beginning of @bio and
474  * return it.  @bio is shortened to the remainder and re-submitted.
475  *
476  * The split bio is allocated from @q->bio_split, which is provided by the
477  * block layer.
478  */
479 struct bio *bio_split_to_limits(struct bio *bio)
480 {
481 	unsigned int nr_segs;
482 
483 	return __bio_split_to_limits(bio, bdev_limits(bio->bi_bdev), &nr_segs);
484 }
485 EXPORT_SYMBOL(bio_split_to_limits);
486 
487 unsigned int blk_recalc_rq_segments(struct request *rq)
488 {
489 	unsigned int nr_phys_segs = 0;
490 	unsigned int bytes = 0;
491 	struct req_iterator iter;
492 	struct bio_vec bv;
493 
494 	if (!rq->bio)
495 		return 0;
496 
497 	switch (bio_op(rq->bio)) {
498 	case REQ_OP_DISCARD:
499 	case REQ_OP_SECURE_ERASE:
500 		if (queue_max_discard_segments(rq->q) > 1) {
501 			struct bio *bio = rq->bio;
502 
503 			for_each_bio(bio)
504 				nr_phys_segs++;
505 			return nr_phys_segs;
506 		}
507 		return 1;
508 	case REQ_OP_WRITE_ZEROES:
509 		return 0;
510 	default:
511 		break;
512 	}
513 
514 	rq_for_each_bvec(bv, rq, iter)
515 		bvec_split_segs(&rq->q->limits, &bv, &nr_phys_segs, &bytes,
516 				UINT_MAX, BIO_MAX_SIZE);
517 	return nr_phys_segs;
518 }
519 
520 static inline unsigned int blk_rq_get_max_sectors(struct request *rq,
521 						  sector_t offset)
522 {
523 	struct request_queue *q = rq->q;
524 	struct queue_limits *lim = &q->limits;
525 	unsigned int max_sectors, boundary_sectors;
526 	bool is_atomic = rq->cmd_flags & REQ_ATOMIC;
527 
528 	if (blk_rq_is_passthrough(rq))
529 		return q->limits.max_hw_sectors;
530 
531 	boundary_sectors = blk_boundary_sectors(lim, is_atomic);
532 	max_sectors = blk_queue_get_max_sectors(rq);
533 
534 	if (!boundary_sectors ||
535 	    req_op(rq) == REQ_OP_DISCARD ||
536 	    req_op(rq) == REQ_OP_SECURE_ERASE)
537 		return max_sectors;
538 	return min(max_sectors,
539 		   blk_boundary_sectors_left(offset, boundary_sectors));
540 }
541 
542 static inline int ll_new_hw_segment(struct request *req, struct bio *bio,
543 		unsigned int nr_phys_segs)
544 {
545 	if (!blk_cgroup_mergeable(req, bio))
546 		goto no_merge;
547 
548 	if (unlikely(!blk_integrity_merge_bio(req->q, req, bio)))
549 		goto no_merge;
550 
551 	/* discard request merge won't add new segment */
552 	if (req_op(req) == REQ_OP_DISCARD)
553 		return 1;
554 
555 	if (req->nr_phys_segments + nr_phys_segs > blk_rq_get_max_segments(req))
556 		goto no_merge;
557 
558 	/*
559 	 * This will form the start of a new hw segment.  Bump both
560 	 * counters.
561 	 */
562 	req->nr_phys_segments += nr_phys_segs;
563 	if (bio_integrity(bio))
564 		req->nr_integrity_segments += blk_rq_count_integrity_sg(req->q,
565 									bio);
566 	return 1;
567 
568 no_merge:
569 	req_set_nomerge(req->q, req);
570 	return 0;
571 }
572 
573 int ll_back_merge_fn(struct request *req, struct bio *bio, unsigned int nr_segs)
574 {
575 	if (req_gap_back_merge(req, bio))
576 		return 0;
577 	if (blk_integrity_rq(req) &&
578 	    integrity_req_gap_back_merge(req, bio))
579 		return 0;
580 	if (!bio_crypt_ctx_back_mergeable(req, bio))
581 		return 0;
582 	if (blk_rq_sectors(req) + bio_sectors(bio) >
583 	    blk_rq_get_max_sectors(req, blk_rq_pos(req))) {
584 		req_set_nomerge(req->q, req);
585 		return 0;
586 	}
587 
588 	return ll_new_hw_segment(req, bio, nr_segs);
589 }
590 
591 static int ll_front_merge_fn(struct request *req, struct bio *bio,
592 		unsigned int nr_segs)
593 {
594 	if (req_gap_front_merge(req, bio))
595 		return 0;
596 	if (blk_integrity_rq(req) &&
597 	    integrity_req_gap_front_merge(req, bio))
598 		return 0;
599 	if (!bio_crypt_ctx_front_mergeable(req, bio))
600 		return 0;
601 	if (blk_rq_sectors(req) + bio_sectors(bio) >
602 	    blk_rq_get_max_sectors(req, bio->bi_iter.bi_sector)) {
603 		req_set_nomerge(req->q, req);
604 		return 0;
605 	}
606 
607 	return ll_new_hw_segment(req, bio, nr_segs);
608 }
609 
610 static bool req_attempt_discard_merge(struct request_queue *q, struct request *req,
611 		struct request *next)
612 {
613 	unsigned short segments = blk_rq_nr_discard_segments(req);
614 
615 	if (segments >= queue_max_discard_segments(q))
616 		goto no_merge;
617 	if (blk_rq_sectors(req) + bio_sectors(next->bio) >
618 	    blk_rq_get_max_sectors(req, blk_rq_pos(req)))
619 		goto no_merge;
620 
621 	req->nr_phys_segments = segments + blk_rq_nr_discard_segments(next);
622 	return true;
623 no_merge:
624 	req_set_nomerge(q, req);
625 	return false;
626 }
627 
628 static int ll_merge_requests_fn(struct request_queue *q, struct request *req,
629 				struct request *next)
630 {
631 	int total_phys_segments;
632 
633 	if (req_gap_back_merge(req, next->bio))
634 		return 0;
635 
636 	/*
637 	 * Will it become too large?
638 	 */
639 	if ((blk_rq_sectors(req) + blk_rq_sectors(next)) >
640 	    blk_rq_get_max_sectors(req, blk_rq_pos(req)))
641 		return 0;
642 
643 	total_phys_segments = req->nr_phys_segments + next->nr_phys_segments;
644 	if (total_phys_segments > blk_rq_get_max_segments(req))
645 		return 0;
646 
647 	if (!blk_cgroup_mergeable(req, next->bio))
648 		return 0;
649 
650 	if (unlikely(!blk_integrity_merge_rq(q, req, next)))
651 		return 0;
652 
653 	if (!bio_crypt_ctx_merge_rq(req, next))
654 		return 0;
655 
656 	/* Merge is OK... */
657 	req->nr_phys_segments = total_phys_segments;
658 	req->nr_integrity_segments += next->nr_integrity_segments;
659 	return 1;
660 }
661 
662 /**
663  * blk_rq_set_mixed_merge - mark a request as mixed merge
664  * @rq: request to mark as mixed merge
665  *
666  * Description:
667  *     @rq is about to be mixed merged.  Make sure the attributes
668  *     which can be mixed are set in each bio and mark @rq as mixed
669  *     merged.
670  */
671 static void blk_rq_set_mixed_merge(struct request *rq)
672 {
673 	blk_opf_t ff = rq->cmd_flags & REQ_FAILFAST_MASK;
674 	struct bio *bio;
675 
676 	if (rq->rq_flags & RQF_MIXED_MERGE)
677 		return;
678 
679 	/*
680 	 * @rq will no longer represent mixable attributes for all the
681 	 * contained bios.  It will just track those of the first one.
682 	 * Distributes the attributs to each bio.
683 	 */
684 	for (bio = rq->bio; bio; bio = bio->bi_next) {
685 		WARN_ON_ONCE((bio->bi_opf & REQ_FAILFAST_MASK) &&
686 			     (bio->bi_opf & REQ_FAILFAST_MASK) != ff);
687 		bio->bi_opf |= ff;
688 	}
689 	rq->rq_flags |= RQF_MIXED_MERGE;
690 }
691 
692 static inline blk_opf_t bio_failfast(const struct bio *bio)
693 {
694 	if (bio->bi_opf & REQ_RAHEAD)
695 		return REQ_FAILFAST_MASK;
696 
697 	return bio->bi_opf & REQ_FAILFAST_MASK;
698 }
699 
700 /*
701  * After we are marked as MIXED_MERGE, any new RA bio has to be updated
702  * as failfast, and request's failfast has to be updated in case of
703  * front merge.
704  */
705 static inline void blk_update_mixed_merge(struct request *req,
706 		struct bio *bio, bool front_merge)
707 {
708 	if (req->rq_flags & RQF_MIXED_MERGE) {
709 		if (bio->bi_opf & REQ_RAHEAD)
710 			bio->bi_opf |= REQ_FAILFAST_MASK;
711 
712 		if (front_merge) {
713 			req->cmd_flags &= ~REQ_FAILFAST_MASK;
714 			req->cmd_flags |= bio->bi_opf & REQ_FAILFAST_MASK;
715 		}
716 	}
717 }
718 
719 static void blk_account_io_merge_request(struct request *req)
720 {
721 	if (req->rq_flags & RQF_IO_STAT) {
722 		part_stat_lock();
723 		part_stat_inc(req->part, merges[op_stat_group(req_op(req))]);
724 		bdev_dec_in_flight(req->part, req_op(req));
725 		part_stat_unlock();
726 	}
727 }
728 
729 static enum elv_merge blk_try_req_merge(struct request *req,
730 					struct request *next)
731 {
732 	if (blk_discard_mergable(req))
733 		return ELEVATOR_DISCARD_MERGE;
734 	else if (blk_rq_pos(req) + blk_rq_sectors(req) == blk_rq_pos(next))
735 		return ELEVATOR_BACK_MERGE;
736 
737 	return ELEVATOR_NO_MERGE;
738 }
739 
740 static bool blk_atomic_write_mergeable_rq_bio(struct request *rq,
741 					      struct bio *bio)
742 {
743 	return (rq->cmd_flags & REQ_ATOMIC) == (bio->bi_opf & REQ_ATOMIC);
744 }
745 
746 static bool blk_atomic_write_mergeable_rqs(struct request *rq,
747 					   struct request *next)
748 {
749 	return (rq->cmd_flags & REQ_ATOMIC) == (next->cmd_flags & REQ_ATOMIC);
750 }
751 
752 u8 bio_seg_gap(struct request_queue *q, struct bio *prev, struct bio *next,
753 	       u8 gaps_bit)
754 {
755 	struct bio_vec pb, nb;
756 
757 	if (!bio_has_data(prev))
758 		return 0;
759 
760 	gaps_bit = min_not_zero(gaps_bit, prev->bi_bvec_gap_bit);
761 	gaps_bit = min_not_zero(gaps_bit, next->bi_bvec_gap_bit);
762 
763 	bio_get_last_bvec(prev, &pb);
764 	bio_get_first_bvec(next, &nb);
765 	if (!biovec_phys_mergeable(q, &pb, &nb))
766 		gaps_bit = min_not_zero(gaps_bit, ffs(bvec_seg_gap(&pb, &nb)));
767 	return gaps_bit;
768 }
769 
770 /*
771  * For non-mq, this has to be called with the request spinlock acquired.
772  * For mq with scheduling, the appropriate queue wide lock should be held.
773  */
774 static struct request *attempt_merge(struct request_queue *q,
775 				     struct request *req, struct request *next)
776 {
777 	if (!rq_mergeable(req) || !rq_mergeable(next))
778 		return NULL;
779 
780 	if (req_op(req) != req_op(next))
781 		return NULL;
782 
783 	if (req->bio->bi_write_hint != next->bio->bi_write_hint)
784 		return NULL;
785 	if (req->bio->bi_write_stream != next->bio->bi_write_stream)
786 		return NULL;
787 	if (req->bio->bi_ioprio != next->bio->bi_ioprio)
788 		return NULL;
789 	if (!blk_atomic_write_mergeable_rqs(req, next))
790 		return NULL;
791 
792 	/*
793 	 * If we are allowed to merge, then append bio list
794 	 * from next to rq and release next. merge_requests_fn
795 	 * will have updated segment counts, update sector
796 	 * counts here. Handle DISCARDs separately, as they
797 	 * have separate settings.
798 	 */
799 
800 	switch (blk_try_req_merge(req, next)) {
801 	case ELEVATOR_DISCARD_MERGE:
802 		if (!req_attempt_discard_merge(q, req, next))
803 			return NULL;
804 		break;
805 	case ELEVATOR_BACK_MERGE:
806 		if (!ll_merge_requests_fn(q, req, next))
807 			return NULL;
808 		break;
809 	default:
810 		return NULL;
811 	}
812 
813 	/*
814 	 * If failfast settings disagree or any of the two is already
815 	 * a mixed merge, mark both as mixed before proceeding.  This
816 	 * makes sure that all involved bios have mixable attributes
817 	 * set properly.
818 	 */
819 	if (((req->rq_flags | next->rq_flags) & RQF_MIXED_MERGE) ||
820 	    (req->cmd_flags & REQ_FAILFAST_MASK) !=
821 	    (next->cmd_flags & REQ_FAILFAST_MASK)) {
822 		blk_rq_set_mixed_merge(req);
823 		blk_rq_set_mixed_merge(next);
824 	}
825 
826 	/*
827 	 * At this point we have either done a back merge or front merge. We
828 	 * need the smaller start_time_ns of the merged requests to be the
829 	 * current request for accounting purposes.
830 	 */
831 	if (next->start_time_ns < req->start_time_ns)
832 		req->start_time_ns = next->start_time_ns;
833 
834 	req->phys_gap_bit = bio_seg_gap(req->q, req->biotail, next->bio,
835 					min_not_zero(next->phys_gap_bit,
836 						     req->phys_gap_bit));
837 	req->biotail->bi_next = next->bio;
838 	req->biotail = next->biotail;
839 
840 	req->__data_len += blk_rq_bytes(next);
841 
842 	if (!blk_discard_mergable(req))
843 		elv_merge_requests(q, req, next);
844 
845 	blk_crypto_rq_put_keyslot(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 	if (!blk_cgroup_mergeable(rq, bio))
904 		return false;
905 	if (unlikely(!blk_integrity_merge_bio(rq->q, rq, bio)))
906 		return false;
907 	if (!bio_crypt_rq_ctx_compatible(rq, bio))
908 		return false;
909 	if (rq->bio->bi_write_hint != bio->bi_write_hint)
910 		return false;
911 	if (rq->bio->bi_write_stream != bio->bi_write_stream)
912 		return false;
913 	if (rq->bio->bi_ioprio != bio->bi_ioprio)
914 		return false;
915 	if (unlikely(!blk_atomic_write_mergeable_rq_bio(rq, bio)))
916 		return false;
917 
918 	return true;
919 }
920 
921 enum elv_merge blk_try_merge(struct request *rq, struct bio *bio)
922 {
923 	if (blk_discard_mergable(rq))
924 		return ELEVATOR_DISCARD_MERGE;
925 	else if (blk_rq_pos(rq) + blk_rq_sectors(rq) == bio->bi_iter.bi_sector)
926 		return ELEVATOR_BACK_MERGE;
927 	else if (blk_rq_pos(rq) - bio_sectors(bio) == bio->bi_iter.bi_sector)
928 		return ELEVATOR_FRONT_MERGE;
929 	return ELEVATOR_NO_MERGE;
930 }
931 
932 static void blk_account_io_merge_bio(struct request *req)
933 {
934 	if (req->rq_flags & RQF_IO_STAT) {
935 		part_stat_lock();
936 		part_stat_inc(req->part, merges[op_stat_group(req_op(req))]);
937 		part_stat_unlock();
938 	}
939 }
940 
941 enum bio_merge_status bio_attempt_back_merge(struct request *req,
942 		struct bio *bio, unsigned int nr_segs)
943 {
944 	const blk_opf_t ff = bio_failfast(bio);
945 
946 	if (!ll_back_merge_fn(req, bio, nr_segs))
947 		return BIO_MERGE_FAILED;
948 
949 	trace_block_bio_backmerge(bio);
950 	rq_qos_merge(req->q, req, bio);
951 
952 	if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
953 		blk_rq_set_mixed_merge(req);
954 
955 	blk_update_mixed_merge(req, bio, false);
956 
957 	if (req->rq_flags & RQF_ZONE_WRITE_PLUGGING)
958 		blk_zone_write_plug_bio_merged(bio);
959 
960 	req->phys_gap_bit = bio_seg_gap(req->q, req->biotail, bio,
961 					req->phys_gap_bit);
962 	req->biotail->bi_next = bio;
963 	req->biotail = bio;
964 	req->__data_len += bio->bi_iter.bi_size;
965 
966 	bio_crypt_free_ctx(bio);
967 
968 	blk_account_io_merge_bio(req);
969 	return BIO_MERGE_OK;
970 }
971 
972 static enum bio_merge_status bio_attempt_front_merge(struct request *req,
973 		struct bio *bio, unsigned int nr_segs)
974 {
975 	const blk_opf_t ff = bio_failfast(bio);
976 
977 	/*
978 	 * A front merge for writes to sequential zones of a zoned block device
979 	 * can happen only if the user submitted writes out of order. Do not
980 	 * merge such write to let it fail.
981 	 */
982 	if (req->rq_flags & RQF_ZONE_WRITE_PLUGGING)
983 		return BIO_MERGE_FAILED;
984 
985 	if (!ll_front_merge_fn(req, bio, nr_segs))
986 		return BIO_MERGE_FAILED;
987 
988 	trace_block_bio_frontmerge(bio);
989 	rq_qos_merge(req->q, req, bio);
990 
991 	if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
992 		blk_rq_set_mixed_merge(req);
993 
994 	blk_update_mixed_merge(req, bio, true);
995 
996 	req->phys_gap_bit = bio_seg_gap(req->q, bio, req->bio,
997 					req->phys_gap_bit);
998 	bio->bi_next = req->bio;
999 	req->bio = bio;
1000 
1001 	req->__sector = bio->bi_iter.bi_sector;
1002 	req->__data_len += bio->bi_iter.bi_size;
1003 
1004 	bio_crypt_do_front_merge(req, bio);
1005 
1006 	blk_account_io_merge_bio(req);
1007 	return BIO_MERGE_OK;
1008 }
1009 
1010 static enum bio_merge_status bio_attempt_discard_merge(struct request_queue *q,
1011 		struct request *req, struct bio *bio)
1012 {
1013 	unsigned short segments = blk_rq_nr_discard_segments(req);
1014 
1015 	if (segments >= queue_max_discard_segments(q))
1016 		goto no_merge;
1017 	if (blk_rq_sectors(req) + bio_sectors(bio) >
1018 	    blk_rq_get_max_sectors(req, blk_rq_pos(req)))
1019 		goto no_merge;
1020 
1021 	rq_qos_merge(q, req, bio);
1022 
1023 	req->biotail->bi_next = bio;
1024 	req->biotail = bio;
1025 	req->__data_len += bio->bi_iter.bi_size;
1026 	req->nr_phys_segments = segments + 1;
1027 
1028 	blk_account_io_merge_bio(req);
1029 	return BIO_MERGE_OK;
1030 no_merge:
1031 	req_set_nomerge(q, req);
1032 	return BIO_MERGE_FAILED;
1033 }
1034 
1035 static enum bio_merge_status blk_attempt_bio_merge(struct request_queue *q,
1036 						   struct request *rq,
1037 						   struct bio *bio,
1038 						   unsigned int nr_segs,
1039 						   bool sched_allow_merge)
1040 {
1041 	if (!blk_rq_merge_ok(rq, bio))
1042 		return BIO_MERGE_NONE;
1043 
1044 	switch (blk_try_merge(rq, bio)) {
1045 	case ELEVATOR_BACK_MERGE:
1046 		if (!sched_allow_merge || blk_mq_sched_allow_merge(q, rq, bio))
1047 			return bio_attempt_back_merge(rq, bio, nr_segs);
1048 		break;
1049 	case ELEVATOR_FRONT_MERGE:
1050 		if (!sched_allow_merge || blk_mq_sched_allow_merge(q, rq, bio))
1051 			return bio_attempt_front_merge(rq, bio, nr_segs);
1052 		break;
1053 	case ELEVATOR_DISCARD_MERGE:
1054 		return bio_attempt_discard_merge(q, rq, bio);
1055 	default:
1056 		return BIO_MERGE_NONE;
1057 	}
1058 
1059 	return BIO_MERGE_FAILED;
1060 }
1061 
1062 /**
1063  * blk_attempt_plug_merge - try to merge with %current's plugged list
1064  * @q: request_queue new bio is being queued at
1065  * @bio: new bio being queued
1066  * @nr_segs: number of segments in @bio
1067  * from the passed in @q already in the plug list
1068  *
1069  * Determine whether @bio being queued on @q can be merged with the previous
1070  * request on %current's plugged list.  Returns %true if merge was successful,
1071  * otherwise %false.
1072  *
1073  * Plugging coalesces IOs from the same issuer for the same purpose without
1074  * going through @q->queue_lock.  As such it's more of an issuing mechanism
1075  * than scheduling, and the request, while may have elvpriv data, is not
1076  * added on the elevator at this point.  In addition, we don't have
1077  * reliable access to the elevator outside queue lock.  Only check basic
1078  * merging parameters without querying the elevator.
1079  *
1080  * Caller must ensure !blk_queue_nomerges(q) beforehand.
1081  */
1082 bool blk_attempt_plug_merge(struct request_queue *q, struct bio *bio,
1083 		unsigned int nr_segs)
1084 {
1085 	struct blk_plug *plug = current->plug;
1086 	struct request *rq;
1087 
1088 	if (!plug || rq_list_empty(&plug->mq_list))
1089 		return false;
1090 
1091 	rq = plug->mq_list.tail;
1092 	if (rq->q == q)
1093 		return blk_attempt_bio_merge(q, rq, bio, nr_segs, false) ==
1094 			BIO_MERGE_OK;
1095 	else if (!plug->multiple_queues)
1096 		return false;
1097 
1098 	rq_list_for_each(&plug->mq_list, rq) {
1099 		if (rq->q != q)
1100 			continue;
1101 		if (blk_attempt_bio_merge(q, rq, bio, nr_segs, false) ==
1102 		    BIO_MERGE_OK)
1103 			return true;
1104 		break;
1105 	}
1106 	return false;
1107 }
1108 
1109 /*
1110  * Iterate list of requests and see if we can merge this bio with any
1111  * of them.
1112  */
1113 bool blk_bio_list_merge(struct request_queue *q, struct list_head *list,
1114 			struct bio *bio, unsigned int nr_segs)
1115 {
1116 	struct request *rq;
1117 	int checked = 8;
1118 
1119 	list_for_each_entry_reverse(rq, list, queuelist) {
1120 		if (!checked--)
1121 			break;
1122 
1123 		switch (blk_attempt_bio_merge(q, rq, bio, nr_segs, true)) {
1124 		case BIO_MERGE_NONE:
1125 			continue;
1126 		case BIO_MERGE_OK:
1127 			return true;
1128 		case BIO_MERGE_FAILED:
1129 			return false;
1130 		}
1131 
1132 	}
1133 
1134 	return false;
1135 }
1136 EXPORT_SYMBOL_GPL(blk_bio_list_merge);
1137 
1138 bool blk_mq_sched_try_merge(struct request_queue *q, struct bio *bio,
1139 		unsigned int nr_segs, struct request **merged_request)
1140 {
1141 	struct request *rq;
1142 
1143 	switch (elv_merge(q, &rq, bio)) {
1144 	case ELEVATOR_BACK_MERGE:
1145 		if (!blk_mq_sched_allow_merge(q, rq, bio))
1146 			return false;
1147 		if (bio_attempt_back_merge(rq, bio, nr_segs) != BIO_MERGE_OK)
1148 			return false;
1149 		*merged_request = attempt_back_merge(q, rq);
1150 		if (!*merged_request)
1151 			elv_merged_request(q, rq, ELEVATOR_BACK_MERGE);
1152 		return true;
1153 	case ELEVATOR_FRONT_MERGE:
1154 		if (!blk_mq_sched_allow_merge(q, rq, bio))
1155 			return false;
1156 		if (bio_attempt_front_merge(rq, bio, nr_segs) != BIO_MERGE_OK)
1157 			return false;
1158 		*merged_request = attempt_front_merge(q, rq);
1159 		if (!*merged_request)
1160 			elv_merged_request(q, rq, ELEVATOR_FRONT_MERGE);
1161 		return true;
1162 	case ELEVATOR_DISCARD_MERGE:
1163 		return bio_attempt_discard_merge(q, rq, bio) == BIO_MERGE_OK;
1164 	default:
1165 		return false;
1166 	}
1167 }
1168 EXPORT_SYMBOL_GPL(blk_mq_sched_try_merge);
1169