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