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