dm rq: simplify dm_old_stop_queue()
[cascardo/linux.git] / drivers / md / dm-rq.c
1 /*
2  * Copyright (C) 2016 Red Hat, Inc. All rights reserved.
3  *
4  * This file is released under the GPL.
5  */
6
7 #include "dm-core.h"
8 #include "dm-rq.h"
9
10 #include <linux/elevator.h> /* for rq_end_sector() */
11 #include <linux/blk-mq.h>
12
13 #define DM_MSG_PREFIX "core-rq"
14
15 #define DM_MQ_NR_HW_QUEUES 1
16 #define DM_MQ_QUEUE_DEPTH 2048
17 static unsigned dm_mq_nr_hw_queues = DM_MQ_NR_HW_QUEUES;
18 static unsigned dm_mq_queue_depth = DM_MQ_QUEUE_DEPTH;
19
20 /*
21  * Request-based DM's mempools' reserved IOs set by the user.
22  */
23 #define RESERVED_REQUEST_BASED_IOS      256
24 static unsigned reserved_rq_based_ios = RESERVED_REQUEST_BASED_IOS;
25
26 #ifdef CONFIG_DM_MQ_DEFAULT
27 static bool use_blk_mq = true;
28 #else
29 static bool use_blk_mq = false;
30 #endif
31
32 bool dm_use_blk_mq_default(void)
33 {
34         return use_blk_mq;
35 }
36
37 bool dm_use_blk_mq(struct mapped_device *md)
38 {
39         return md->use_blk_mq;
40 }
41 EXPORT_SYMBOL_GPL(dm_use_blk_mq);
42
43 unsigned dm_get_reserved_rq_based_ios(void)
44 {
45         return __dm_get_module_param(&reserved_rq_based_ios,
46                                      RESERVED_REQUEST_BASED_IOS, DM_RESERVED_MAX_IOS);
47 }
48 EXPORT_SYMBOL_GPL(dm_get_reserved_rq_based_ios);
49
50 static unsigned dm_get_blk_mq_nr_hw_queues(void)
51 {
52         return __dm_get_module_param(&dm_mq_nr_hw_queues, 1, 32);
53 }
54
55 static unsigned dm_get_blk_mq_queue_depth(void)
56 {
57         return __dm_get_module_param(&dm_mq_queue_depth,
58                                      DM_MQ_QUEUE_DEPTH, BLK_MQ_MAX_DEPTH);
59 }
60
61 int dm_request_based(struct mapped_device *md)
62 {
63         return blk_queue_stackable(md->queue);
64 }
65
66 static void dm_old_start_queue(struct request_queue *q)
67 {
68         unsigned long flags;
69
70         spin_lock_irqsave(q->queue_lock, flags);
71         if (blk_queue_stopped(q))
72                 blk_start_queue(q);
73         spin_unlock_irqrestore(q->queue_lock, flags);
74 }
75
76 static void dm_mq_start_queue(struct request_queue *q)
77 {
78         unsigned long flags;
79
80         spin_lock_irqsave(q->queue_lock, flags);
81         queue_flag_clear(QUEUE_FLAG_STOPPED, q);
82         spin_unlock_irqrestore(q->queue_lock, flags);
83
84         blk_mq_start_stopped_hw_queues(q, true);
85         blk_mq_kick_requeue_list(q);
86 }
87
88 void dm_start_queue(struct request_queue *q)
89 {
90         if (!q->mq_ops)
91                 dm_old_start_queue(q);
92         else
93                 dm_mq_start_queue(q);
94 }
95
96 static void dm_old_stop_queue(struct request_queue *q)
97 {
98         unsigned long flags;
99
100         spin_lock_irqsave(q->queue_lock, flags);
101         if (!blk_queue_stopped(q))
102                 blk_stop_queue(q);
103         spin_unlock_irqrestore(q->queue_lock, flags);
104 }
105
106 static void dm_mq_stop_queue(struct request_queue *q)
107 {
108         unsigned long flags;
109
110         spin_lock_irqsave(q->queue_lock, flags);
111         if (blk_queue_stopped(q)) {
112                 spin_unlock_irqrestore(q->queue_lock, flags);
113                 return;
114         }
115
116         queue_flag_set(QUEUE_FLAG_STOPPED, q);
117         spin_unlock_irqrestore(q->queue_lock, flags);
118
119         /* Avoid that requeuing could restart the queue. */
120         blk_mq_cancel_requeue_work(q);
121         blk_mq_stop_hw_queues(q);
122 }
123
124 void dm_stop_queue(struct request_queue *q)
125 {
126         if (!q->mq_ops)
127                 dm_old_stop_queue(q);
128         else
129                 dm_mq_stop_queue(q);
130 }
131
132 static struct dm_rq_target_io *alloc_old_rq_tio(struct mapped_device *md,
133                                                 gfp_t gfp_mask)
134 {
135         return mempool_alloc(md->io_pool, gfp_mask);
136 }
137
138 static void free_old_rq_tio(struct dm_rq_target_io *tio)
139 {
140         mempool_free(tio, tio->md->io_pool);
141 }
142
143 static struct request *alloc_old_clone_request(struct mapped_device *md,
144                                                gfp_t gfp_mask)
145 {
146         return mempool_alloc(md->rq_pool, gfp_mask);
147 }
148
149 static void free_old_clone_request(struct mapped_device *md, struct request *rq)
150 {
151         mempool_free(rq, md->rq_pool);
152 }
153
154 /*
155  * Partial completion handling for request-based dm
156  */
157 static void end_clone_bio(struct bio *clone)
158 {
159         struct dm_rq_clone_bio_info *info =
160                 container_of(clone, struct dm_rq_clone_bio_info, clone);
161         struct dm_rq_target_io *tio = info->tio;
162         struct bio *bio = info->orig;
163         unsigned int nr_bytes = info->orig->bi_iter.bi_size;
164         int error = clone->bi_error;
165
166         bio_put(clone);
167
168         if (tio->error)
169                 /*
170                  * An error has already been detected on the request.
171                  * Once error occurred, just let clone->end_io() handle
172                  * the remainder.
173                  */
174                 return;
175         else if (error) {
176                 /*
177                  * Don't notice the error to the upper layer yet.
178                  * The error handling decision is made by the target driver,
179                  * when the request is completed.
180                  */
181                 tio->error = error;
182                 return;
183         }
184
185         /*
186          * I/O for the bio successfully completed.
187          * Notice the data completion to the upper layer.
188          */
189
190         /*
191          * bios are processed from the head of the list.
192          * So the completing bio should always be rq->bio.
193          * If it's not, something wrong is happening.
194          */
195         if (tio->orig->bio != bio)
196                 DMERR("bio completion is going in the middle of the request");
197
198         /*
199          * Update the original request.
200          * Do not use blk_end_request() here, because it may complete
201          * the original request before the clone, and break the ordering.
202          */
203         blk_update_request(tio->orig, 0, nr_bytes);
204 }
205
206 static struct dm_rq_target_io *tio_from_request(struct request *rq)
207 {
208         return (rq->q->mq_ops ? blk_mq_rq_to_pdu(rq) : rq->special);
209 }
210
211 static void rq_end_stats(struct mapped_device *md, struct request *orig)
212 {
213         if (unlikely(dm_stats_used(&md->stats))) {
214                 struct dm_rq_target_io *tio = tio_from_request(orig);
215                 tio->duration_jiffies = jiffies - tio->duration_jiffies;
216                 dm_stats_account_io(&md->stats, rq_data_dir(orig),
217                                     blk_rq_pos(orig), tio->n_sectors, true,
218                                     tio->duration_jiffies, &tio->stats_aux);
219         }
220 }
221
222 /*
223  * Don't touch any member of the md after calling this function because
224  * the md may be freed in dm_put() at the end of this function.
225  * Or do dm_get() before calling this function and dm_put() later.
226  */
227 static void rq_completed(struct mapped_device *md, int rw, bool run_queue)
228 {
229         atomic_dec(&md->pending[rw]);
230
231         /* nudge anyone waiting on suspend queue */
232         if (!md_in_flight(md))
233                 wake_up(&md->wait);
234
235         /*
236          * Run this off this callpath, as drivers could invoke end_io while
237          * inside their request_fn (and holding the queue lock). Calling
238          * back into ->request_fn() could deadlock attempting to grab the
239          * queue lock again.
240          */
241         if (!md->queue->mq_ops && run_queue)
242                 blk_run_queue_async(md->queue);
243
244         /*
245          * dm_put() must be at the end of this function. See the comment above
246          */
247         dm_put(md);
248 }
249
250 static void free_rq_clone(struct request *clone)
251 {
252         struct dm_rq_target_io *tio = clone->end_io_data;
253         struct mapped_device *md = tio->md;
254
255         blk_rq_unprep_clone(clone);
256
257         /*
258          * It is possible for a clone_old_rq() allocated clone to
259          * get passed in -- it may not yet have a request_queue.
260          * This is known to occur if the error target replaces
261          * a multipath target that has a request_fn queue stacked
262          * on blk-mq queue(s).
263          */
264         if (clone->q && clone->q->mq_ops)
265                 /* stacked on blk-mq queue(s) */
266                 tio->ti->type->release_clone_rq(clone);
267         else if (!md->queue->mq_ops)
268                 /* request_fn queue stacked on request_fn queue(s) */
269                 free_old_clone_request(md, clone);
270
271         if (!md->queue->mq_ops)
272                 free_old_rq_tio(tio);
273 }
274
275 /*
276  * Complete the clone and the original request.
277  * Must be called without clone's queue lock held,
278  * see end_clone_request() for more details.
279  */
280 static void dm_end_request(struct request *clone, int error)
281 {
282         int rw = rq_data_dir(clone);
283         struct dm_rq_target_io *tio = clone->end_io_data;
284         struct mapped_device *md = tio->md;
285         struct request *rq = tio->orig;
286
287         if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
288                 rq->errors = clone->errors;
289                 rq->resid_len = clone->resid_len;
290
291                 if (rq->sense)
292                         /*
293                          * We are using the sense buffer of the original
294                          * request.
295                          * So setting the length of the sense data is enough.
296                          */
297                         rq->sense_len = clone->sense_len;
298         }
299
300         free_rq_clone(clone);
301         rq_end_stats(md, rq);
302         if (!rq->q->mq_ops)
303                 blk_end_request_all(rq, error);
304         else
305                 blk_mq_end_request(rq, error);
306         rq_completed(md, rw, true);
307 }
308
309 static void dm_unprep_request(struct request *rq)
310 {
311         struct dm_rq_target_io *tio = tio_from_request(rq);
312         struct request *clone = tio->clone;
313
314         if (!rq->q->mq_ops) {
315                 rq->special = NULL;
316                 rq->cmd_flags &= ~REQ_DONTPREP;
317         }
318
319         if (clone)
320                 free_rq_clone(clone);
321         else if (!tio->md->queue->mq_ops)
322                 free_old_rq_tio(tio);
323 }
324
325 /*
326  * Requeue the original request of a clone.
327  */
328 static void dm_old_requeue_request(struct request *rq)
329 {
330         struct request_queue *q = rq->q;
331         unsigned long flags;
332
333         spin_lock_irqsave(q->queue_lock, flags);
334         blk_requeue_request(q, rq);
335         blk_run_queue_async(q);
336         spin_unlock_irqrestore(q->queue_lock, flags);
337 }
338
339 static void dm_mq_requeue_request(struct request *rq)
340 {
341         struct request_queue *q = rq->q;
342         unsigned long flags;
343
344         blk_mq_requeue_request(rq);
345         spin_lock_irqsave(q->queue_lock, flags);
346         if (!blk_queue_stopped(q))
347                 blk_mq_kick_requeue_list(q);
348         spin_unlock_irqrestore(q->queue_lock, flags);
349 }
350
351 static void dm_requeue_original_request(struct mapped_device *md,
352                                         struct request *rq)
353 {
354         int rw = rq_data_dir(rq);
355
356         rq_end_stats(md, rq);
357         dm_unprep_request(rq);
358
359         if (!rq->q->mq_ops)
360                 dm_old_requeue_request(rq);
361         else
362                 dm_mq_requeue_request(rq);
363
364         rq_completed(md, rw, false);
365 }
366
367 static void dm_done(struct request *clone, int error, bool mapped)
368 {
369         int r = error;
370         struct dm_rq_target_io *tio = clone->end_io_data;
371         dm_request_endio_fn rq_end_io = NULL;
372
373         if (tio->ti) {
374                 rq_end_io = tio->ti->type->rq_end_io;
375
376                 if (mapped && rq_end_io)
377                         r = rq_end_io(tio->ti, clone, error, &tio->info);
378         }
379
380         if (unlikely(r == -EREMOTEIO && (req_op(clone) == REQ_OP_WRITE_SAME) &&
381                      !clone->q->limits.max_write_same_sectors))
382                 disable_write_same(tio->md);
383
384         if (r <= 0)
385                 /* The target wants to complete the I/O */
386                 dm_end_request(clone, r);
387         else if (r == DM_ENDIO_INCOMPLETE)
388                 /* The target will handle the I/O */
389                 return;
390         else if (r == DM_ENDIO_REQUEUE)
391                 /* The target wants to requeue the I/O */
392                 dm_requeue_original_request(tio->md, tio->orig);
393         else {
394                 DMWARN("unimplemented target endio return value: %d", r);
395                 BUG();
396         }
397 }
398
399 /*
400  * Request completion handler for request-based dm
401  */
402 static void dm_softirq_done(struct request *rq)
403 {
404         bool mapped = true;
405         struct dm_rq_target_io *tio = tio_from_request(rq);
406         struct request *clone = tio->clone;
407         int rw;
408
409         if (!clone) {
410                 rq_end_stats(tio->md, rq);
411                 rw = rq_data_dir(rq);
412                 if (!rq->q->mq_ops) {
413                         blk_end_request_all(rq, tio->error);
414                         rq_completed(tio->md, rw, false);
415                         free_old_rq_tio(tio);
416                 } else {
417                         blk_mq_end_request(rq, tio->error);
418                         rq_completed(tio->md, rw, false);
419                 }
420                 return;
421         }
422
423         if (rq->cmd_flags & REQ_FAILED)
424                 mapped = false;
425
426         dm_done(clone, tio->error, mapped);
427 }
428
429 /*
430  * Complete the clone and the original request with the error status
431  * through softirq context.
432  */
433 static void dm_complete_request(struct request *rq, int error)
434 {
435         struct dm_rq_target_io *tio = tio_from_request(rq);
436
437         tio->error = error;
438         if (!rq->q->mq_ops)
439                 blk_complete_request(rq);
440         else
441                 blk_mq_complete_request(rq, error);
442 }
443
444 /*
445  * Complete the not-mapped clone and the original request with the error status
446  * through softirq context.
447  * Target's rq_end_io() function isn't called.
448  * This may be used when the target's map_rq() or clone_and_map_rq() functions fail.
449  */
450 static void dm_kill_unmapped_request(struct request *rq, int error)
451 {
452         rq->cmd_flags |= REQ_FAILED;
453         dm_complete_request(rq, error);
454 }
455
456 /*
457  * Called with the clone's queue lock held (in the case of .request_fn)
458  */
459 static void end_clone_request(struct request *clone, int error)
460 {
461         struct dm_rq_target_io *tio = clone->end_io_data;
462
463         if (!clone->q->mq_ops) {
464                 /*
465                  * For just cleaning up the information of the queue in which
466                  * the clone was dispatched.
467                  * The clone is *NOT* freed actually here because it is alloced
468                  * from dm own mempool (REQ_ALLOCED isn't set).
469                  */
470                 __blk_put_request(clone->q, clone);
471         }
472
473         /*
474          * Actual request completion is done in a softirq context which doesn't
475          * hold the clone's queue lock.  Otherwise, deadlock could occur because:
476          *     - another request may be submitted by the upper level driver
477          *       of the stacking during the completion
478          *     - the submission which requires queue lock may be done
479          *       against this clone's queue
480          */
481         dm_complete_request(tio->orig, error);
482 }
483
484 static void dm_dispatch_clone_request(struct request *clone, struct request *rq)
485 {
486         int r;
487
488         if (blk_queue_io_stat(clone->q))
489                 clone->cmd_flags |= REQ_IO_STAT;
490
491         clone->start_time = jiffies;
492         r = blk_insert_cloned_request(clone->q, clone);
493         if (r)
494                 /* must complete clone in terms of original request */
495                 dm_complete_request(rq, r);
496 }
497
498 static int dm_rq_bio_constructor(struct bio *bio, struct bio *bio_orig,
499                                  void *data)
500 {
501         struct dm_rq_target_io *tio = data;
502         struct dm_rq_clone_bio_info *info =
503                 container_of(bio, struct dm_rq_clone_bio_info, clone);
504
505         info->orig = bio_orig;
506         info->tio = tio;
507         bio->bi_end_io = end_clone_bio;
508
509         return 0;
510 }
511
512 static int setup_clone(struct request *clone, struct request *rq,
513                        struct dm_rq_target_io *tio, gfp_t gfp_mask)
514 {
515         int r;
516
517         r = blk_rq_prep_clone(clone, rq, tio->md->bs, gfp_mask,
518                               dm_rq_bio_constructor, tio);
519         if (r)
520                 return r;
521
522         clone->cmd = rq->cmd;
523         clone->cmd_len = rq->cmd_len;
524         clone->sense = rq->sense;
525         clone->end_io = end_clone_request;
526         clone->end_io_data = tio;
527
528         tio->clone = clone;
529
530         return 0;
531 }
532
533 static struct request *clone_old_rq(struct request *rq, struct mapped_device *md,
534                                     struct dm_rq_target_io *tio, gfp_t gfp_mask)
535 {
536         /*
537          * Create clone for use with .request_fn request_queue
538          */
539         struct request *clone;
540
541         clone = alloc_old_clone_request(md, gfp_mask);
542         if (!clone)
543                 return NULL;
544
545         blk_rq_init(NULL, clone);
546         if (setup_clone(clone, rq, tio, gfp_mask)) {
547                 /* -ENOMEM */
548                 free_old_clone_request(md, clone);
549                 return NULL;
550         }
551
552         return clone;
553 }
554
555 static void map_tio_request(struct kthread_work *work);
556
557 static void init_tio(struct dm_rq_target_io *tio, struct request *rq,
558                      struct mapped_device *md)
559 {
560         tio->md = md;
561         tio->ti = NULL;
562         tio->clone = NULL;
563         tio->orig = rq;
564         tio->error = 0;
565         /*
566          * Avoid initializing info for blk-mq; it passes
567          * target-specific data through info.ptr
568          * (see: dm_mq_init_request)
569          */
570         if (!md->init_tio_pdu)
571                 memset(&tio->info, 0, sizeof(tio->info));
572         if (md->kworker_task)
573                 init_kthread_work(&tio->work, map_tio_request);
574 }
575
576 static struct dm_rq_target_io *dm_old_prep_tio(struct request *rq,
577                                                struct mapped_device *md,
578                                                gfp_t gfp_mask)
579 {
580         struct dm_rq_target_io *tio;
581         int srcu_idx;
582         struct dm_table *table;
583
584         tio = alloc_old_rq_tio(md, gfp_mask);
585         if (!tio)
586                 return NULL;
587
588         init_tio(tio, rq, md);
589
590         table = dm_get_live_table(md, &srcu_idx);
591         /*
592          * Must clone a request if this .request_fn DM device
593          * is stacked on .request_fn device(s).
594          */
595         if (!dm_table_all_blk_mq_devices(table)) {
596                 if (!clone_old_rq(rq, md, tio, gfp_mask)) {
597                         dm_put_live_table(md, srcu_idx);
598                         free_old_rq_tio(tio);
599                         return NULL;
600                 }
601         }
602         dm_put_live_table(md, srcu_idx);
603
604         return tio;
605 }
606
607 /*
608  * Called with the queue lock held.
609  */
610 static int dm_old_prep_fn(struct request_queue *q, struct request *rq)
611 {
612         struct mapped_device *md = q->queuedata;
613         struct dm_rq_target_io *tio;
614
615         if (unlikely(rq->special)) {
616                 DMWARN("Already has something in rq->special.");
617                 return BLKPREP_KILL;
618         }
619
620         tio = dm_old_prep_tio(rq, md, GFP_ATOMIC);
621         if (!tio)
622                 return BLKPREP_DEFER;
623
624         rq->special = tio;
625         rq->cmd_flags |= REQ_DONTPREP;
626
627         return BLKPREP_OK;
628 }
629
630 /*
631  * Returns:
632  * 0                : the request has been processed
633  * DM_MAPIO_REQUEUE : the original request needs to be requeued
634  * < 0              : the request was completed due to failure
635  */
636 static int map_request(struct dm_rq_target_io *tio, struct request *rq,
637                        struct mapped_device *md)
638 {
639         int r;
640         struct dm_target *ti = tio->ti;
641         struct request *clone = NULL;
642
643         if (tio->clone) {
644                 clone = tio->clone;
645                 r = ti->type->map_rq(ti, clone, &tio->info);
646         } else {
647                 r = ti->type->clone_and_map_rq(ti, rq, &tio->info, &clone);
648                 if (r < 0) {
649                         /* The target wants to complete the I/O */
650                         dm_kill_unmapped_request(rq, r);
651                         return r;
652                 }
653                 if (r != DM_MAPIO_REMAPPED)
654                         return r;
655                 if (setup_clone(clone, rq, tio, GFP_ATOMIC)) {
656                         /* -ENOMEM */
657                         ti->type->release_clone_rq(clone);
658                         return DM_MAPIO_REQUEUE;
659                 }
660         }
661
662         switch (r) {
663         case DM_MAPIO_SUBMITTED:
664                 /* The target has taken the I/O to submit by itself later */
665                 break;
666         case DM_MAPIO_REMAPPED:
667                 /* The target has remapped the I/O so dispatch it */
668                 trace_block_rq_remap(clone->q, clone, disk_devt(dm_disk(md)),
669                                      blk_rq_pos(rq));
670                 dm_dispatch_clone_request(clone, rq);
671                 break;
672         case DM_MAPIO_REQUEUE:
673                 /* The target wants to requeue the I/O */
674                 dm_requeue_original_request(md, tio->orig);
675                 break;
676         default:
677                 if (r > 0) {
678                         DMWARN("unimplemented target map return value: %d", r);
679                         BUG();
680                 }
681
682                 /* The target wants to complete the I/O */
683                 dm_kill_unmapped_request(rq, r);
684                 return r;
685         }
686
687         return 0;
688 }
689
690 static void dm_start_request(struct mapped_device *md, struct request *orig)
691 {
692         if (!orig->q->mq_ops)
693                 blk_start_request(orig);
694         else
695                 blk_mq_start_request(orig);
696         atomic_inc(&md->pending[rq_data_dir(orig)]);
697
698         if (md->seq_rq_merge_deadline_usecs) {
699                 md->last_rq_pos = rq_end_sector(orig);
700                 md->last_rq_rw = rq_data_dir(orig);
701                 md->last_rq_start_time = ktime_get();
702         }
703
704         if (unlikely(dm_stats_used(&md->stats))) {
705                 struct dm_rq_target_io *tio = tio_from_request(orig);
706                 tio->duration_jiffies = jiffies;
707                 tio->n_sectors = blk_rq_sectors(orig);
708                 dm_stats_account_io(&md->stats, rq_data_dir(orig),
709                                     blk_rq_pos(orig), tio->n_sectors, false, 0,
710                                     &tio->stats_aux);
711         }
712
713         /*
714          * Hold the md reference here for the in-flight I/O.
715          * We can't rely on the reference count by device opener,
716          * because the device may be closed during the request completion
717          * when all bios are completed.
718          * See the comment in rq_completed() too.
719          */
720         dm_get(md);
721 }
722
723 static void map_tio_request(struct kthread_work *work)
724 {
725         struct dm_rq_target_io *tio = container_of(work, struct dm_rq_target_io, work);
726         struct request *rq = tio->orig;
727         struct mapped_device *md = tio->md;
728
729         if (map_request(tio, rq, md) == DM_MAPIO_REQUEUE)
730                 dm_requeue_original_request(md, rq);
731 }
732
733 ssize_t dm_attr_rq_based_seq_io_merge_deadline_show(struct mapped_device *md, char *buf)
734 {
735         return sprintf(buf, "%u\n", md->seq_rq_merge_deadline_usecs);
736 }
737
738 #define MAX_SEQ_RQ_MERGE_DEADLINE_USECS 100000
739
740 ssize_t dm_attr_rq_based_seq_io_merge_deadline_store(struct mapped_device *md,
741                                                      const char *buf, size_t count)
742 {
743         unsigned deadline;
744
745         if (dm_get_md_type(md) != DM_TYPE_REQUEST_BASED)
746                 return count;
747
748         if (kstrtouint(buf, 10, &deadline))
749                 return -EINVAL;
750
751         if (deadline > MAX_SEQ_RQ_MERGE_DEADLINE_USECS)
752                 deadline = MAX_SEQ_RQ_MERGE_DEADLINE_USECS;
753
754         md->seq_rq_merge_deadline_usecs = deadline;
755
756         return count;
757 }
758
759 static bool dm_old_request_peeked_before_merge_deadline(struct mapped_device *md)
760 {
761         ktime_t kt_deadline;
762
763         if (!md->seq_rq_merge_deadline_usecs)
764                 return false;
765
766         kt_deadline = ns_to_ktime((u64)md->seq_rq_merge_deadline_usecs * NSEC_PER_USEC);
767         kt_deadline = ktime_add_safe(md->last_rq_start_time, kt_deadline);
768
769         return !ktime_after(ktime_get(), kt_deadline);
770 }
771
772 /*
773  * q->request_fn for old request-based dm.
774  * Called with the queue lock held.
775  */
776 static void dm_old_request_fn(struct request_queue *q)
777 {
778         struct mapped_device *md = q->queuedata;
779         struct dm_target *ti = md->immutable_target;
780         struct request *rq;
781         struct dm_rq_target_io *tio;
782         sector_t pos = 0;
783
784         if (unlikely(!ti)) {
785                 int srcu_idx;
786                 struct dm_table *map = dm_get_live_table(md, &srcu_idx);
787
788                 ti = dm_table_find_target(map, pos);
789                 dm_put_live_table(md, srcu_idx);
790         }
791
792         /*
793          * For suspend, check blk_queue_stopped() and increment
794          * ->pending within a single queue_lock not to increment the
795          * number of in-flight I/Os after the queue is stopped in
796          * dm_suspend().
797          */
798         while (!blk_queue_stopped(q)) {
799                 rq = blk_peek_request(q);
800                 if (!rq)
801                         return;
802
803                 /* always use block 0 to find the target for flushes for now */
804                 pos = 0;
805                 if (req_op(rq) != REQ_OP_FLUSH)
806                         pos = blk_rq_pos(rq);
807
808                 if ((dm_old_request_peeked_before_merge_deadline(md) &&
809                      md_in_flight(md) && rq->bio && rq->bio->bi_vcnt == 1 &&
810                      md->last_rq_pos == pos && md->last_rq_rw == rq_data_dir(rq)) ||
811                     (ti->type->busy && ti->type->busy(ti))) {
812                         blk_delay_queue(q, 10);
813                         return;
814                 }
815
816                 dm_start_request(md, rq);
817
818                 tio = tio_from_request(rq);
819                 /* Establish tio->ti before queuing work (map_tio_request) */
820                 tio->ti = ti;
821                 queue_kthread_work(&md->kworker, &tio->work);
822                 BUG_ON(!irqs_disabled());
823         }
824 }
825
826 /*
827  * Fully initialize a .request_fn request-based queue.
828  */
829 int dm_old_init_request_queue(struct mapped_device *md)
830 {
831         /* Fully initialize the queue */
832         if (!blk_init_allocated_queue(md->queue, dm_old_request_fn, NULL))
833                 return -EINVAL;
834
835         /* disable dm_old_request_fn's merge heuristic by default */
836         md->seq_rq_merge_deadline_usecs = 0;
837
838         dm_init_normal_md_queue(md);
839         blk_queue_softirq_done(md->queue, dm_softirq_done);
840         blk_queue_prep_rq(md->queue, dm_old_prep_fn);
841
842         /* Initialize the request-based DM worker thread */
843         init_kthread_worker(&md->kworker);
844         md->kworker_task = kthread_run(kthread_worker_fn, &md->kworker,
845                                        "kdmwork-%s", dm_device_name(md));
846         if (IS_ERR(md->kworker_task))
847                 return PTR_ERR(md->kworker_task);
848
849         elv_register_queue(md->queue);
850
851         return 0;
852 }
853
854 static int dm_mq_init_request(void *data, struct request *rq,
855                        unsigned int hctx_idx, unsigned int request_idx,
856                        unsigned int numa_node)
857 {
858         struct mapped_device *md = data;
859         struct dm_rq_target_io *tio = blk_mq_rq_to_pdu(rq);
860
861         /*
862          * Must initialize md member of tio, otherwise it won't
863          * be available in dm_mq_queue_rq.
864          */
865         tio->md = md;
866
867         if (md->init_tio_pdu) {
868                 /* target-specific per-io data is immediately after the tio */
869                 tio->info.ptr = tio + 1;
870         }
871
872         return 0;
873 }
874
875 static int dm_mq_queue_rq(struct blk_mq_hw_ctx *hctx,
876                           const struct blk_mq_queue_data *bd)
877 {
878         struct request *rq = bd->rq;
879         struct dm_rq_target_io *tio = blk_mq_rq_to_pdu(rq);
880         struct mapped_device *md = tio->md;
881         struct dm_target *ti = md->immutable_target;
882
883         if (unlikely(!ti)) {
884                 int srcu_idx;
885                 struct dm_table *map = dm_get_live_table(md, &srcu_idx);
886
887                 ti = dm_table_find_target(map, 0);
888                 dm_put_live_table(md, srcu_idx);
889         }
890
891         /*
892          * On suspend dm_stop_queue() handles stopping the blk-mq
893          * request_queue BUT: even though the hw_queues are marked
894          * BLK_MQ_S_STOPPED at that point there is still a race that
895          * is allowing block/blk-mq.c to call ->queue_rq against a
896          * hctx that it really shouldn't.  The following check guards
897          * against this rarity (albeit _not_ race-free).
898          */
899         if (unlikely(test_bit(BLK_MQ_S_STOPPED, &hctx->state)))
900                 return BLK_MQ_RQ_QUEUE_BUSY;
901
902         if (ti->type->busy && ti->type->busy(ti))
903                 return BLK_MQ_RQ_QUEUE_BUSY;
904
905         dm_start_request(md, rq);
906
907         /* Init tio using md established in .init_request */
908         init_tio(tio, rq, md);
909
910         /*
911          * Establish tio->ti before calling map_request().
912          */
913         tio->ti = ti;
914
915         /* Direct call is fine since .queue_rq allows allocations */
916         if (map_request(tio, rq, md) == DM_MAPIO_REQUEUE) {
917                 /* Undo dm_start_request() before requeuing */
918                 rq_end_stats(md, rq);
919                 rq_completed(md, rq_data_dir(rq), false);
920                 return BLK_MQ_RQ_QUEUE_BUSY;
921         }
922
923         return BLK_MQ_RQ_QUEUE_OK;
924 }
925
926 static struct blk_mq_ops dm_mq_ops = {
927         .queue_rq = dm_mq_queue_rq,
928         .map_queue = blk_mq_map_queue,
929         .complete = dm_softirq_done,
930         .init_request = dm_mq_init_request,
931 };
932
933 int dm_mq_init_request_queue(struct mapped_device *md, struct dm_table *t)
934 {
935         struct request_queue *q;
936         struct dm_target *immutable_tgt;
937         int err;
938
939         if (!dm_table_all_blk_mq_devices(t)) {
940                 DMERR("request-based dm-mq may only be stacked on blk-mq device(s)");
941                 return -EINVAL;
942         }
943
944         md->tag_set = kzalloc_node(sizeof(struct blk_mq_tag_set), GFP_KERNEL, md->numa_node_id);
945         if (!md->tag_set)
946                 return -ENOMEM;
947
948         md->tag_set->ops = &dm_mq_ops;
949         md->tag_set->queue_depth = dm_get_blk_mq_queue_depth();
950         md->tag_set->numa_node = md->numa_node_id;
951         md->tag_set->flags = BLK_MQ_F_SHOULD_MERGE | BLK_MQ_F_SG_MERGE;
952         md->tag_set->nr_hw_queues = dm_get_blk_mq_nr_hw_queues();
953         md->tag_set->driver_data = md;
954
955         md->tag_set->cmd_size = sizeof(struct dm_rq_target_io);
956         immutable_tgt = dm_table_get_immutable_target(t);
957         if (immutable_tgt && immutable_tgt->per_io_data_size) {
958                 /* any target-specific per-io data is immediately after the tio */
959                 md->tag_set->cmd_size += immutable_tgt->per_io_data_size;
960                 md->init_tio_pdu = true;
961         }
962
963         err = blk_mq_alloc_tag_set(md->tag_set);
964         if (err)
965                 goto out_kfree_tag_set;
966
967         q = blk_mq_init_allocated_queue(md->tag_set, md->queue);
968         if (IS_ERR(q)) {
969                 err = PTR_ERR(q);
970                 goto out_tag_set;
971         }
972         dm_init_md_queue(md);
973
974         /* backfill 'mq' sysfs registration normally done in blk_register_queue */
975         blk_mq_register_disk(md->disk);
976
977         return 0;
978
979 out_tag_set:
980         blk_mq_free_tag_set(md->tag_set);
981 out_kfree_tag_set:
982         kfree(md->tag_set);
983
984         return err;
985 }
986
987 void dm_mq_cleanup_mapped_device(struct mapped_device *md)
988 {
989         if (md->tag_set) {
990                 blk_mq_free_tag_set(md->tag_set);
991                 kfree(md->tag_set);
992         }
993 }
994
995 module_param(reserved_rq_based_ios, uint, S_IRUGO | S_IWUSR);
996 MODULE_PARM_DESC(reserved_rq_based_ios, "Reserved IOs in request-based mempools");
997
998 module_param(use_blk_mq, bool, S_IRUGO | S_IWUSR);
999 MODULE_PARM_DESC(use_blk_mq, "Use block multiqueue for request-based DM devices");
1000
1001 module_param(dm_mq_nr_hw_queues, uint, S_IRUGO | S_IWUSR);
1002 MODULE_PARM_DESC(dm_mq_nr_hw_queues, "Number of hardware queues for request-based dm-mq devices");
1003
1004 module_param(dm_mq_queue_depth, uint, S_IRUGO | S_IWUSR);
1005 MODULE_PARM_DESC(dm_mq_queue_depth, "Queue depth for request-based dm-mq devices");