5529e7d28ae6bb73d2c86f831fd87f44e230bd01
[linux-2.6-microblaze.git] / include / linux / blk-mq.h
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef BLK_MQ_H
3 #define BLK_MQ_H
4
5 #include <linux/blkdev.h>
6 #include <linux/sbitmap.h>
7 #include <linux/lockdep.h>
8 #include <linux/scatterlist.h>
9 #include <linux/prefetch.h>
10 #include <linux/srcu.h>
11
12 struct blk_mq_tags;
13 struct blk_flush_queue;
14
15 #define BLKDEV_MIN_RQ   4
16 #define BLKDEV_DEFAULT_RQ       128
17
18 enum rq_end_io_ret {
19         RQ_END_IO_NONE,
20         RQ_END_IO_FREE,
21 };
22
23 typedef enum rq_end_io_ret (rq_end_io_fn)(struct request *, blk_status_t);
24
25 /*
26  * request flags */
27 typedef __u32 __bitwise req_flags_t;
28
29 /* drive already may have started this one */
30 #define RQF_STARTED             ((__force req_flags_t)(1 << 1))
31 /* may not be passed by ioscheduler */
32 #define RQF_SOFTBARRIER         ((__force req_flags_t)(1 << 3))
33 /* request for flush sequence */
34 #define RQF_FLUSH_SEQ           ((__force req_flags_t)(1 << 4))
35 /* merge of different types, fail separately */
36 #define RQF_MIXED_MERGE         ((__force req_flags_t)(1 << 5))
37 /* track inflight for MQ */
38 #define RQF_MQ_INFLIGHT         ((__force req_flags_t)(1 << 6))
39 /* don't call prep for this one */
40 #define RQF_DONTPREP            ((__force req_flags_t)(1 << 7))
41 /* vaguely specified driver internal error.  Ignored by the block layer */
42 #define RQF_FAILED              ((__force req_flags_t)(1 << 10))
43 /* don't warn about errors */
44 #define RQF_QUIET               ((__force req_flags_t)(1 << 11))
45 /* account into disk and partition IO statistics */
46 #define RQF_IO_STAT             ((__force req_flags_t)(1 << 13))
47 /* runtime pm request */
48 #define RQF_PM                  ((__force req_flags_t)(1 << 15))
49 /* on IO scheduler merge hash */
50 #define RQF_HASHED              ((__force req_flags_t)(1 << 16))
51 /* track IO completion time */
52 #define RQF_STATS               ((__force req_flags_t)(1 << 17))
53 /* Look at ->special_vec for the actual data payload instead of the
54    bio chain. */
55 #define RQF_SPECIAL_PAYLOAD     ((__force req_flags_t)(1 << 18))
56 /* The per-zone write lock is held for this request */
57 #define RQF_ZONE_WRITE_LOCKED   ((__force req_flags_t)(1 << 19))
58 /* ->timeout has been called, don't expire again */
59 #define RQF_TIMED_OUT           ((__force req_flags_t)(1 << 21))
60 /* queue has elevator attached */
61 #define RQF_ELV                 ((__force req_flags_t)(1 << 22))
62 #define RQF_RESV                        ((__force req_flags_t)(1 << 23))
63
64 /* flags that prevent us from merging requests: */
65 #define RQF_NOMERGE_FLAGS \
66         (RQF_STARTED | RQF_SOFTBARRIER | RQF_FLUSH_SEQ | RQF_SPECIAL_PAYLOAD)
67
68 enum mq_rq_state {
69         MQ_RQ_IDLE              = 0,
70         MQ_RQ_IN_FLIGHT         = 1,
71         MQ_RQ_COMPLETE          = 2,
72 };
73
74 /*
75  * Try to put the fields that are referenced together in the same cacheline.
76  *
77  * If you modify this structure, make sure to update blk_rq_init() and
78  * especially blk_mq_rq_ctx_init() to take care of the added fields.
79  */
80 struct request {
81         struct request_queue *q;
82         struct blk_mq_ctx *mq_ctx;
83         struct blk_mq_hw_ctx *mq_hctx;
84
85         blk_opf_t cmd_flags;            /* op and common flags */
86         req_flags_t rq_flags;
87
88         int tag;
89         int internal_tag;
90
91         unsigned int timeout;
92
93         /* the following two fields are internal, NEVER access directly */
94         unsigned int __data_len;        /* total data len */
95         sector_t __sector;              /* sector cursor */
96
97         struct bio *bio;
98         struct bio *biotail;
99
100         union {
101                 struct list_head queuelist;
102                 struct request *rq_next;
103         };
104
105         struct block_device *part;
106 #ifdef CONFIG_BLK_RQ_ALLOC_TIME
107         /* Time that the first bio started allocating this request. */
108         u64 alloc_time_ns;
109 #endif
110         /* Time that this request was allocated for this IO. */
111         u64 start_time_ns;
112         /* Time that I/O was submitted to the device. */
113         u64 io_start_time_ns;
114
115 #ifdef CONFIG_BLK_WBT
116         unsigned short wbt_flags;
117 #endif
118         /*
119          * rq sectors used for blk stats. It has the same value
120          * with blk_rq_sectors(rq), except that it never be zeroed
121          * by completion.
122          */
123         unsigned short stats_sectors;
124
125         /*
126          * Number of scatter-gather DMA addr+len pairs after
127          * physical address coalescing is performed.
128          */
129         unsigned short nr_phys_segments;
130
131 #ifdef CONFIG_BLK_DEV_INTEGRITY
132         unsigned short nr_integrity_segments;
133 #endif
134
135 #ifdef CONFIG_BLK_INLINE_ENCRYPTION
136         struct bio_crypt_ctx *crypt_ctx;
137         struct blk_crypto_keyslot *crypt_keyslot;
138 #endif
139
140         unsigned short ioprio;
141
142         enum mq_rq_state state;
143         atomic_t ref;
144
145         unsigned long deadline;
146
147         /*
148          * The hash is used inside the scheduler, and killed once the
149          * request reaches the dispatch list. The ipi_list is only used
150          * to queue the request for softirq completion, which is long
151          * after the request has been unhashed (and even removed from
152          * the dispatch list).
153          */
154         union {
155                 struct hlist_node hash; /* merge hash */
156                 struct llist_node ipi_list;
157         };
158
159         /*
160          * The rb_node is only used inside the io scheduler, requests
161          * are pruned when moved to the dispatch queue. So let the
162          * completion_data share space with the rb_node.
163          */
164         union {
165                 struct rb_node rb_node; /* sort/lookup */
166                 struct bio_vec special_vec;
167                 void *completion_data;
168         };
169
170
171         /*
172          * Three pointers are available for the IO schedulers, if they need
173          * more they have to dynamically allocate it.  Flush requests are
174          * never put on the IO scheduler. So let the flush fields share
175          * space with the elevator data.
176          */
177         union {
178                 struct {
179                         struct io_cq            *icq;
180                         void                    *priv[2];
181                 } elv;
182
183                 struct {
184                         unsigned int            seq;
185                         struct list_head        list;
186                         rq_end_io_fn            *saved_end_io;
187                 } flush;
188         };
189
190         union {
191                 struct __call_single_data csd;
192                 u64 fifo_time;
193         };
194
195         /*
196          * completion callback.
197          */
198         rq_end_io_fn *end_io;
199         void *end_io_data;
200 };
201
202 static inline enum req_op req_op(const struct request *req)
203 {
204         return req->cmd_flags & REQ_OP_MASK;
205 }
206
207 static inline bool blk_rq_is_passthrough(struct request *rq)
208 {
209         return blk_op_is_passthrough(req_op(rq));
210 }
211
212 static inline unsigned short req_get_ioprio(struct request *req)
213 {
214         return req->ioprio;
215 }
216
217 #define rq_data_dir(rq)         (op_is_write(req_op(rq)) ? WRITE : READ)
218
219 #define rq_dma_dir(rq) \
220         (op_is_write(req_op(rq)) ? DMA_TO_DEVICE : DMA_FROM_DEVICE)
221
222 #define rq_list_add(listptr, rq)        do {            \
223         (rq)->rq_next = *(listptr);                     \
224         *(listptr) = rq;                                \
225 } while (0)
226
227 #define rq_list_add_tail(lastpptr, rq)  do {            \
228         (rq)->rq_next = NULL;                           \
229         **(lastpptr) = rq;                              \
230         *(lastpptr) = &rq->rq_next;                     \
231 } while (0)
232
233 #define rq_list_pop(listptr)                            \
234 ({                                                      \
235         struct request *__req = NULL;                   \
236         if ((listptr) && *(listptr))    {               \
237                 __req = *(listptr);                     \
238                 *(listptr) = __req->rq_next;            \
239         }                                               \
240         __req;                                          \
241 })
242
243 #define rq_list_peek(listptr)                           \
244 ({                                                      \
245         struct request *__req = NULL;                   \
246         if ((listptr) && *(listptr))                    \
247                 __req = *(listptr);                     \
248         __req;                                          \
249 })
250
251 #define rq_list_for_each(listptr, pos)                  \
252         for (pos = rq_list_peek((listptr)); pos; pos = rq_list_next(pos))
253
254 #define rq_list_for_each_safe(listptr, pos, nxt)                        \
255         for (pos = rq_list_peek((listptr)), nxt = rq_list_next(pos);    \
256                 pos; pos = nxt, nxt = pos ? rq_list_next(pos) : NULL)
257
258 #define rq_list_next(rq)        (rq)->rq_next
259 #define rq_list_empty(list)     ((list) == (struct request *) NULL)
260
261 /**
262  * rq_list_move() - move a struct request from one list to another
263  * @src: The source list @rq is currently in
264  * @dst: The destination list that @rq will be appended to
265  * @rq: The request to move
266  * @prev: The request preceding @rq in @src (NULL if @rq is the head)
267  */
268 static inline void rq_list_move(struct request **src, struct request **dst,
269                                 struct request *rq, struct request *prev)
270 {
271         if (prev)
272                 prev->rq_next = rq->rq_next;
273         else
274                 *src = rq->rq_next;
275         rq_list_add(dst, rq);
276 }
277
278 /**
279  * enum blk_eh_timer_return - How the timeout handler should proceed
280  * @BLK_EH_DONE: The block driver completed the command or will complete it at
281  *      a later time.
282  * @BLK_EH_RESET_TIMER: Reset the request timer and continue waiting for the
283  *      request to complete.
284  */
285 enum blk_eh_timer_return {
286         BLK_EH_DONE,
287         BLK_EH_RESET_TIMER,
288 };
289
290 #define BLK_TAG_ALLOC_FIFO 0 /* allocate starting from 0 */
291 #define BLK_TAG_ALLOC_RR 1 /* allocate starting from last allocated tag */
292
293 /**
294  * struct blk_mq_hw_ctx - State for a hardware queue facing the hardware
295  * block device
296  */
297 struct blk_mq_hw_ctx {
298         struct {
299                 /** @lock: Protects the dispatch list. */
300                 spinlock_t              lock;
301                 /**
302                  * @dispatch: Used for requests that are ready to be
303                  * dispatched to the hardware but for some reason (e.g. lack of
304                  * resources) could not be sent to the hardware. As soon as the
305                  * driver can send new requests, requests at this list will
306                  * be sent first for a fairer dispatch.
307                  */
308                 struct list_head        dispatch;
309                  /**
310                   * @state: BLK_MQ_S_* flags. Defines the state of the hw
311                   * queue (active, scheduled to restart, stopped).
312                   */
313                 unsigned long           state;
314         } ____cacheline_aligned_in_smp;
315
316         /**
317          * @run_work: Used for scheduling a hardware queue run at a later time.
318          */
319         struct delayed_work     run_work;
320         /** @cpumask: Map of available CPUs where this hctx can run. */
321         cpumask_var_t           cpumask;
322         /**
323          * @next_cpu: Used by blk_mq_hctx_next_cpu() for round-robin CPU
324          * selection from @cpumask.
325          */
326         int                     next_cpu;
327         /**
328          * @next_cpu_batch: Counter of how many works left in the batch before
329          * changing to the next CPU.
330          */
331         int                     next_cpu_batch;
332
333         /** @flags: BLK_MQ_F_* flags. Defines the behaviour of the queue. */
334         unsigned long           flags;
335
336         /**
337          * @sched_data: Pointer owned by the IO scheduler attached to a request
338          * queue. It's up to the IO scheduler how to use this pointer.
339          */
340         void                    *sched_data;
341         /**
342          * @queue: Pointer to the request queue that owns this hardware context.
343          */
344         struct request_queue    *queue;
345         /** @fq: Queue of requests that need to perform a flush operation. */
346         struct blk_flush_queue  *fq;
347
348         /**
349          * @driver_data: Pointer to data owned by the block driver that created
350          * this hctx
351          */
352         void                    *driver_data;
353
354         /**
355          * @ctx_map: Bitmap for each software queue. If bit is on, there is a
356          * pending request in that software queue.
357          */
358         struct sbitmap          ctx_map;
359
360         /**
361          * @dispatch_from: Software queue to be used when no scheduler was
362          * selected.
363          */
364         struct blk_mq_ctx       *dispatch_from;
365         /**
366          * @dispatch_busy: Number used by blk_mq_update_dispatch_busy() to
367          * decide if the hw_queue is busy using Exponential Weighted Moving
368          * Average algorithm.
369          */
370         unsigned int            dispatch_busy;
371
372         /** @type: HCTX_TYPE_* flags. Type of hardware queue. */
373         unsigned short          type;
374         /** @nr_ctx: Number of software queues. */
375         unsigned short          nr_ctx;
376         /** @ctxs: Array of software queues. */
377         struct blk_mq_ctx       **ctxs;
378
379         /** @dispatch_wait_lock: Lock for dispatch_wait queue. */
380         spinlock_t              dispatch_wait_lock;
381         /**
382          * @dispatch_wait: Waitqueue to put requests when there is no tag
383          * available at the moment, to wait for another try in the future.
384          */
385         wait_queue_entry_t      dispatch_wait;
386
387         /**
388          * @wait_index: Index of next available dispatch_wait queue to insert
389          * requests.
390          */
391         atomic_t                wait_index;
392
393         /**
394          * @tags: Tags owned by the block driver. A tag at this set is only
395          * assigned when a request is dispatched from a hardware queue.
396          */
397         struct blk_mq_tags      *tags;
398         /**
399          * @sched_tags: Tags owned by I/O scheduler. If there is an I/O
400          * scheduler associated with a request queue, a tag is assigned when
401          * that request is allocated. Else, this member is not used.
402          */
403         struct blk_mq_tags      *sched_tags;
404
405         /** @queued: Number of queued requests. */
406         unsigned long           queued;
407         /** @run: Number of dispatched requests. */
408         unsigned long           run;
409
410         /** @numa_node: NUMA node the storage adapter has been connected to. */
411         unsigned int            numa_node;
412         /** @queue_num: Index of this hardware queue. */
413         unsigned int            queue_num;
414
415         /**
416          * @nr_active: Number of active requests. Only used when a tag set is
417          * shared across request queues.
418          */
419         atomic_t                nr_active;
420
421         /** @cpuhp_online: List to store request if CPU is going to die */
422         struct hlist_node       cpuhp_online;
423         /** @cpuhp_dead: List to store request if some CPU die. */
424         struct hlist_node       cpuhp_dead;
425         /** @kobj: Kernel object for sysfs. */
426         struct kobject          kobj;
427
428 #ifdef CONFIG_BLK_DEBUG_FS
429         /**
430          * @debugfs_dir: debugfs directory for this hardware queue. Named
431          * as cpu<cpu_number>.
432          */
433         struct dentry           *debugfs_dir;
434         /** @sched_debugfs_dir: debugfs directory for the scheduler. */
435         struct dentry           *sched_debugfs_dir;
436 #endif
437
438         /**
439          * @hctx_list: if this hctx is not in use, this is an entry in
440          * q->unused_hctx_list.
441          */
442         struct list_head        hctx_list;
443 };
444
445 /**
446  * struct blk_mq_queue_map - Map software queues to hardware queues
447  * @mq_map:       CPU ID to hardware queue index map. This is an array
448  *      with nr_cpu_ids elements. Each element has a value in the range
449  *      [@queue_offset, @queue_offset + @nr_queues).
450  * @nr_queues:    Number of hardware queues to map CPU IDs onto.
451  * @queue_offset: First hardware queue to map onto. Used by the PCIe NVMe
452  *      driver to map each hardware queue type (enum hctx_type) onto a distinct
453  *      set of hardware queues.
454  */
455 struct blk_mq_queue_map {
456         unsigned int *mq_map;
457         unsigned int nr_queues;
458         unsigned int queue_offset;
459 };
460
461 /**
462  * enum hctx_type - Type of hardware queue
463  * @HCTX_TYPE_DEFAULT:  All I/O not otherwise accounted for.
464  * @HCTX_TYPE_READ:     Just for READ I/O.
465  * @HCTX_TYPE_POLL:     Polled I/O of any kind.
466  * @HCTX_MAX_TYPES:     Number of types of hctx.
467  */
468 enum hctx_type {
469         HCTX_TYPE_DEFAULT,
470         HCTX_TYPE_READ,
471         HCTX_TYPE_POLL,
472
473         HCTX_MAX_TYPES,
474 };
475
476 /**
477  * struct blk_mq_tag_set - tag set that can be shared between request queues
478  * @ops:           Pointers to functions that implement block driver behavior.
479  * @map:           One or more ctx -> hctx mappings. One map exists for each
480  *                 hardware queue type (enum hctx_type) that the driver wishes
481  *                 to support. There are no restrictions on maps being of the
482  *                 same size, and it's perfectly legal to share maps between
483  *                 types.
484  * @nr_maps:       Number of elements in the @map array. A number in the range
485  *                 [1, HCTX_MAX_TYPES].
486  * @nr_hw_queues:  Number of hardware queues supported by the block driver that
487  *                 owns this data structure.
488  * @queue_depth:   Number of tags per hardware queue, reserved tags included.
489  * @reserved_tags: Number of tags to set aside for BLK_MQ_REQ_RESERVED tag
490  *                 allocations.
491  * @cmd_size:      Number of additional bytes to allocate per request. The block
492  *                 driver owns these additional bytes.
493  * @numa_node:     NUMA node the storage adapter has been connected to.
494  * @timeout:       Request processing timeout in jiffies.
495  * @flags:         Zero or more BLK_MQ_F_* flags.
496  * @driver_data:   Pointer to data owned by the block driver that created this
497  *                 tag set.
498  * @tags:          Tag sets. One tag set per hardware queue. Has @nr_hw_queues
499  *                 elements.
500  * @shared_tags:
501  *                 Shared set of tags. Has @nr_hw_queues elements. If set,
502  *                 shared by all @tags.
503  * @tag_list_lock: Serializes tag_list accesses.
504  * @tag_list:      List of the request queues that use this tag set. See also
505  *                 request_queue.tag_set_list.
506  * @srcu:          Use as lock when type of the request queue is blocking
507  *                 (BLK_MQ_F_BLOCKING).
508  */
509 struct blk_mq_tag_set {
510         const struct blk_mq_ops *ops;
511         struct blk_mq_queue_map map[HCTX_MAX_TYPES];
512         unsigned int            nr_maps;
513         unsigned int            nr_hw_queues;
514         unsigned int            queue_depth;
515         unsigned int            reserved_tags;
516         unsigned int            cmd_size;
517         int                     numa_node;
518         unsigned int            timeout;
519         unsigned int            flags;
520         void                    *driver_data;
521
522         struct blk_mq_tags      **tags;
523
524         struct blk_mq_tags      *shared_tags;
525
526         struct mutex            tag_list_lock;
527         struct list_head        tag_list;
528         struct srcu_struct      *srcu;
529 };
530
531 /**
532  * struct blk_mq_queue_data - Data about a request inserted in a queue
533  *
534  * @rq:   Request pointer.
535  * @last: If it is the last request in the queue.
536  */
537 struct blk_mq_queue_data {
538         struct request *rq;
539         bool last;
540 };
541
542 typedef bool (busy_tag_iter_fn)(struct request *, void *);
543
544 /**
545  * struct blk_mq_ops - Callback functions that implements block driver
546  * behaviour.
547  */
548 struct blk_mq_ops {
549         /**
550          * @queue_rq: Queue a new request from block IO.
551          */
552         blk_status_t (*queue_rq)(struct blk_mq_hw_ctx *,
553                                  const struct blk_mq_queue_data *);
554
555         /**
556          * @commit_rqs: If a driver uses bd->last to judge when to submit
557          * requests to hardware, it must define this function. In case of errors
558          * that make us stop issuing further requests, this hook serves the
559          * purpose of kicking the hardware (which the last request otherwise
560          * would have done).
561          */
562         void (*commit_rqs)(struct blk_mq_hw_ctx *);
563
564         /**
565          * @queue_rqs: Queue a list of new requests. Driver is guaranteed
566          * that each request belongs to the same queue. If the driver doesn't
567          * empty the @rqlist completely, then the rest will be queued
568          * individually by the block layer upon return.
569          */
570         void (*queue_rqs)(struct request **rqlist);
571
572         /**
573          * @get_budget: Reserve budget before queue request, once .queue_rq is
574          * run, it is driver's responsibility to release the
575          * reserved budget. Also we have to handle failure case
576          * of .get_budget for avoiding I/O deadlock.
577          */
578         int (*get_budget)(struct request_queue *);
579
580         /**
581          * @put_budget: Release the reserved budget.
582          */
583         void (*put_budget)(struct request_queue *, int);
584
585         /**
586          * @set_rq_budget_token: store rq's budget token
587          */
588         void (*set_rq_budget_token)(struct request *, int);
589         /**
590          * @get_rq_budget_token: retrieve rq's budget token
591          */
592         int (*get_rq_budget_token)(struct request *);
593
594         /**
595          * @timeout: Called on request timeout.
596          */
597         enum blk_eh_timer_return (*timeout)(struct request *);
598
599         /**
600          * @poll: Called to poll for completion of a specific tag.
601          */
602         int (*poll)(struct blk_mq_hw_ctx *, struct io_comp_batch *);
603
604         /**
605          * @complete: Mark the request as complete.
606          */
607         void (*complete)(struct request *);
608
609         /**
610          * @init_hctx: Called when the block layer side of a hardware queue has
611          * been set up, allowing the driver to allocate/init matching
612          * structures.
613          */
614         int (*init_hctx)(struct blk_mq_hw_ctx *, void *, unsigned int);
615         /**
616          * @exit_hctx: Ditto for exit/teardown.
617          */
618         void (*exit_hctx)(struct blk_mq_hw_ctx *, unsigned int);
619
620         /**
621          * @init_request: Called for every command allocated by the block layer
622          * to allow the driver to set up driver specific data.
623          *
624          * Tag greater than or equal to queue_depth is for setting up
625          * flush request.
626          */
627         int (*init_request)(struct blk_mq_tag_set *set, struct request *,
628                             unsigned int, unsigned int);
629         /**
630          * @exit_request: Ditto for exit/teardown.
631          */
632         void (*exit_request)(struct blk_mq_tag_set *set, struct request *,
633                              unsigned int);
634
635         /**
636          * @cleanup_rq: Called before freeing one request which isn't completed
637          * yet, and usually for freeing the driver private data.
638          */
639         void (*cleanup_rq)(struct request *);
640
641         /**
642          * @busy: If set, returns whether or not this queue currently is busy.
643          */
644         bool (*busy)(struct request_queue *);
645
646         /**
647          * @map_queues: This allows drivers specify their own queue mapping by
648          * overriding the setup-time function that builds the mq_map.
649          */
650         void (*map_queues)(struct blk_mq_tag_set *set);
651
652 #ifdef CONFIG_BLK_DEBUG_FS
653         /**
654          * @show_rq: Used by the debugfs implementation to show driver-specific
655          * information about a request.
656          */
657         void (*show_rq)(struct seq_file *m, struct request *rq);
658 #endif
659 };
660
661 enum {
662         BLK_MQ_F_SHOULD_MERGE   = 1 << 0,
663         BLK_MQ_F_TAG_QUEUE_SHARED = 1 << 1,
664         /*
665          * Set when this device requires underlying blk-mq device for
666          * completing IO:
667          */
668         BLK_MQ_F_STACKING       = 1 << 2,
669         BLK_MQ_F_TAG_HCTX_SHARED = 1 << 3,
670         BLK_MQ_F_BLOCKING       = 1 << 5,
671         /* Do not allow an I/O scheduler to be configured. */
672         BLK_MQ_F_NO_SCHED       = 1 << 6,
673         /*
674          * Select 'none' during queue registration in case of a single hwq
675          * or shared hwqs instead of 'mq-deadline'.
676          */
677         BLK_MQ_F_NO_SCHED_BY_DEFAULT    = 1 << 7,
678         BLK_MQ_F_ALLOC_POLICY_START_BIT = 8,
679         BLK_MQ_F_ALLOC_POLICY_BITS = 1,
680
681         BLK_MQ_S_STOPPED        = 0,
682         BLK_MQ_S_TAG_ACTIVE     = 1,
683         BLK_MQ_S_SCHED_RESTART  = 2,
684
685         /* hw queue is inactive after all its CPUs become offline */
686         BLK_MQ_S_INACTIVE       = 3,
687
688         BLK_MQ_MAX_DEPTH        = 10240,
689
690         BLK_MQ_CPU_WORK_BATCH   = 8,
691 };
692 #define BLK_MQ_FLAG_TO_ALLOC_POLICY(flags) \
693         ((flags >> BLK_MQ_F_ALLOC_POLICY_START_BIT) & \
694                 ((1 << BLK_MQ_F_ALLOC_POLICY_BITS) - 1))
695 #define BLK_ALLOC_POLICY_TO_MQ_FLAG(policy) \
696         ((policy & ((1 << BLK_MQ_F_ALLOC_POLICY_BITS) - 1)) \
697                 << BLK_MQ_F_ALLOC_POLICY_START_BIT)
698
699 #define BLK_MQ_NO_HCTX_IDX      (-1U)
700
701 struct gendisk *__blk_mq_alloc_disk(struct blk_mq_tag_set *set, void *queuedata,
702                 struct lock_class_key *lkclass);
703 #define blk_mq_alloc_disk(set, queuedata)                               \
704 ({                                                                      \
705         static struct lock_class_key __key;                             \
706                                                                         \
707         __blk_mq_alloc_disk(set, queuedata, &__key);                    \
708 })
709 struct gendisk *blk_mq_alloc_disk_for_queue(struct request_queue *q,
710                 struct lock_class_key *lkclass);
711 struct request_queue *blk_mq_init_queue(struct blk_mq_tag_set *);
712 int blk_mq_init_allocated_queue(struct blk_mq_tag_set *set,
713                 struct request_queue *q);
714 void blk_mq_destroy_queue(struct request_queue *);
715
716 int blk_mq_alloc_tag_set(struct blk_mq_tag_set *set);
717 int blk_mq_alloc_sq_tag_set(struct blk_mq_tag_set *set,
718                 const struct blk_mq_ops *ops, unsigned int queue_depth,
719                 unsigned int set_flags);
720 void blk_mq_free_tag_set(struct blk_mq_tag_set *set);
721
722 void blk_mq_free_request(struct request *rq);
723
724 bool blk_mq_queue_inflight(struct request_queue *q);
725
726 enum {
727         /* return when out of requests */
728         BLK_MQ_REQ_NOWAIT       = (__force blk_mq_req_flags_t)(1 << 0),
729         /* allocate from reserved pool */
730         BLK_MQ_REQ_RESERVED     = (__force blk_mq_req_flags_t)(1 << 1),
731         /* set RQF_PM */
732         BLK_MQ_REQ_PM           = (__force blk_mq_req_flags_t)(1 << 2),
733 };
734
735 struct request *blk_mq_alloc_request(struct request_queue *q, blk_opf_t opf,
736                 blk_mq_req_flags_t flags);
737 struct request *blk_mq_alloc_request_hctx(struct request_queue *q,
738                 blk_opf_t opf, blk_mq_req_flags_t flags,
739                 unsigned int hctx_idx);
740
741 /*
742  * Tag address space map.
743  */
744 struct blk_mq_tags {
745         unsigned int nr_tags;
746         unsigned int nr_reserved_tags;
747
748         atomic_t active_queues;
749
750         struct sbitmap_queue bitmap_tags;
751         struct sbitmap_queue breserved_tags;
752
753         struct request **rqs;
754         struct request **static_rqs;
755         struct list_head page_list;
756
757         /*
758          * used to clear request reference in rqs[] before freeing one
759          * request pool
760          */
761         spinlock_t lock;
762 };
763
764 static inline struct request *blk_mq_tag_to_rq(struct blk_mq_tags *tags,
765                                                unsigned int tag)
766 {
767         if (tag < tags->nr_tags) {
768                 prefetch(tags->rqs[tag]);
769                 return tags->rqs[tag];
770         }
771
772         return NULL;
773 }
774
775 enum {
776         BLK_MQ_UNIQUE_TAG_BITS = 16,
777         BLK_MQ_UNIQUE_TAG_MASK = (1 << BLK_MQ_UNIQUE_TAG_BITS) - 1,
778 };
779
780 u32 blk_mq_unique_tag(struct request *rq);
781
782 static inline u16 blk_mq_unique_tag_to_hwq(u32 unique_tag)
783 {
784         return unique_tag >> BLK_MQ_UNIQUE_TAG_BITS;
785 }
786
787 static inline u16 blk_mq_unique_tag_to_tag(u32 unique_tag)
788 {
789         return unique_tag & BLK_MQ_UNIQUE_TAG_MASK;
790 }
791
792 /**
793  * blk_mq_rq_state() - read the current MQ_RQ_* state of a request
794  * @rq: target request.
795  */
796 static inline enum mq_rq_state blk_mq_rq_state(struct request *rq)
797 {
798         return READ_ONCE(rq->state);
799 }
800
801 static inline int blk_mq_request_started(struct request *rq)
802 {
803         return blk_mq_rq_state(rq) != MQ_RQ_IDLE;
804 }
805
806 static inline int blk_mq_request_completed(struct request *rq)
807 {
808         return blk_mq_rq_state(rq) == MQ_RQ_COMPLETE;
809 }
810
811 /*
812  * 
813  * Set the state to complete when completing a request from inside ->queue_rq.
814  * This is used by drivers that want to ensure special complete actions that
815  * need access to the request are called on failure, e.g. by nvme for
816  * multipathing.
817  */
818 static inline void blk_mq_set_request_complete(struct request *rq)
819 {
820         WRITE_ONCE(rq->state, MQ_RQ_COMPLETE);
821 }
822
823 /*
824  * Complete the request directly instead of deferring it to softirq or
825  * completing it another CPU. Useful in preemptible instead of an interrupt.
826  */
827 static inline void blk_mq_complete_request_direct(struct request *rq,
828                    void (*complete)(struct request *rq))
829 {
830         WRITE_ONCE(rq->state, MQ_RQ_COMPLETE);
831         complete(rq);
832 }
833
834 void blk_mq_start_request(struct request *rq);
835 void blk_mq_end_request(struct request *rq, blk_status_t error);
836 void __blk_mq_end_request(struct request *rq, blk_status_t error);
837 void blk_mq_end_request_batch(struct io_comp_batch *ib);
838
839 /*
840  * Only need start/end time stamping if we have iostat or
841  * blk stats enabled, or using an IO scheduler.
842  */
843 static inline bool blk_mq_need_time_stamp(struct request *rq)
844 {
845         return (rq->rq_flags & (RQF_IO_STAT | RQF_STATS | RQF_ELV));
846 }
847
848 static inline bool blk_mq_is_reserved_rq(struct request *rq)
849 {
850         return rq->rq_flags & RQF_RESV;
851 }
852
853 /*
854  * Batched completions only work when there is no I/O error and no special
855  * ->end_io handler.
856  */
857 static inline bool blk_mq_add_to_batch(struct request *req,
858                                        struct io_comp_batch *iob, int ioerror,
859                                        void (*complete)(struct io_comp_batch *))
860 {
861         if (!iob || (req->rq_flags & RQF_ELV) || ioerror ||
862                         (req->end_io && !blk_rq_is_passthrough(req)))
863                 return false;
864
865         if (!iob->complete)
866                 iob->complete = complete;
867         else if (iob->complete != complete)
868                 return false;
869         iob->need_ts |= blk_mq_need_time_stamp(req);
870         rq_list_add(&iob->req_list, req);
871         return true;
872 }
873
874 void blk_mq_requeue_request(struct request *rq, bool kick_requeue_list);
875 void blk_mq_kick_requeue_list(struct request_queue *q);
876 void blk_mq_delay_kick_requeue_list(struct request_queue *q, unsigned long msecs);
877 void blk_mq_complete_request(struct request *rq);
878 bool blk_mq_complete_request_remote(struct request *rq);
879 void blk_mq_stop_hw_queue(struct blk_mq_hw_ctx *hctx);
880 void blk_mq_start_hw_queue(struct blk_mq_hw_ctx *hctx);
881 void blk_mq_stop_hw_queues(struct request_queue *q);
882 void blk_mq_start_hw_queues(struct request_queue *q);
883 void blk_mq_start_stopped_hw_queue(struct blk_mq_hw_ctx *hctx, bool async);
884 void blk_mq_start_stopped_hw_queues(struct request_queue *q, bool async);
885 void blk_mq_quiesce_queue(struct request_queue *q);
886 void blk_mq_wait_quiesce_done(struct blk_mq_tag_set *set);
887 void blk_mq_quiesce_tagset(struct blk_mq_tag_set *set);
888 void blk_mq_unquiesce_tagset(struct blk_mq_tag_set *set);
889 void blk_mq_unquiesce_queue(struct request_queue *q);
890 void blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx *hctx, unsigned long msecs);
891 void blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx, bool async);
892 void blk_mq_run_hw_queues(struct request_queue *q, bool async);
893 void blk_mq_delay_run_hw_queues(struct request_queue *q, unsigned long msecs);
894 void blk_mq_tagset_busy_iter(struct blk_mq_tag_set *tagset,
895                 busy_tag_iter_fn *fn, void *priv);
896 void blk_mq_tagset_wait_completed_request(struct blk_mq_tag_set *tagset);
897 void blk_mq_freeze_queue(struct request_queue *q);
898 void blk_mq_unfreeze_queue(struct request_queue *q);
899 void blk_freeze_queue_start(struct request_queue *q);
900 void blk_mq_freeze_queue_wait(struct request_queue *q);
901 int blk_mq_freeze_queue_wait_timeout(struct request_queue *q,
902                                      unsigned long timeout);
903
904 void blk_mq_map_queues(struct blk_mq_queue_map *qmap);
905 void blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set, int nr_hw_queues);
906
907 void blk_mq_quiesce_queue_nowait(struct request_queue *q);
908
909 unsigned int blk_mq_rq_cpu(struct request *rq);
910
911 bool __blk_should_fake_timeout(struct request_queue *q);
912 static inline bool blk_should_fake_timeout(struct request_queue *q)
913 {
914         if (IS_ENABLED(CONFIG_FAIL_IO_TIMEOUT) &&
915             test_bit(QUEUE_FLAG_FAIL_IO, &q->queue_flags))
916                 return __blk_should_fake_timeout(q);
917         return false;
918 }
919
920 /**
921  * blk_mq_rq_from_pdu - cast a PDU to a request
922  * @pdu: the PDU (Protocol Data Unit) to be casted
923  *
924  * Return: request
925  *
926  * Driver command data is immediately after the request. So subtract request
927  * size to get back to the original request.
928  */
929 static inline struct request *blk_mq_rq_from_pdu(void *pdu)
930 {
931         return pdu - sizeof(struct request);
932 }
933
934 /**
935  * blk_mq_rq_to_pdu - cast a request to a PDU
936  * @rq: the request to be casted
937  *
938  * Return: pointer to the PDU
939  *
940  * Driver command data is immediately after the request. So add request to get
941  * the PDU.
942  */
943 static inline void *blk_mq_rq_to_pdu(struct request *rq)
944 {
945         return rq + 1;
946 }
947
948 #define queue_for_each_hw_ctx(q, hctx, i)                               \
949         xa_for_each(&(q)->hctx_table, (i), (hctx))
950
951 #define hctx_for_each_ctx(hctx, ctx, i)                                 \
952         for ((i) = 0; (i) < (hctx)->nr_ctx &&                           \
953              ({ ctx = (hctx)->ctxs[(i)]; 1; }); (i)++)
954
955 static inline void blk_mq_cleanup_rq(struct request *rq)
956 {
957         if (rq->q->mq_ops->cleanup_rq)
958                 rq->q->mq_ops->cleanup_rq(rq);
959 }
960
961 static inline void blk_rq_bio_prep(struct request *rq, struct bio *bio,
962                 unsigned int nr_segs)
963 {
964         rq->nr_phys_segments = nr_segs;
965         rq->__data_len = bio->bi_iter.bi_size;
966         rq->bio = rq->biotail = bio;
967         rq->ioprio = bio_prio(bio);
968 }
969
970 void blk_mq_hctx_set_fq_lock_class(struct blk_mq_hw_ctx *hctx,
971                 struct lock_class_key *key);
972
973 static inline bool rq_is_sync(struct request *rq)
974 {
975         return op_is_sync(rq->cmd_flags);
976 }
977
978 void blk_rq_init(struct request_queue *q, struct request *rq);
979 int blk_rq_prep_clone(struct request *rq, struct request *rq_src,
980                 struct bio_set *bs, gfp_t gfp_mask,
981                 int (*bio_ctr)(struct bio *, struct bio *, void *), void *data);
982 void blk_rq_unprep_clone(struct request *rq);
983 blk_status_t blk_insert_cloned_request(struct request *rq);
984
985 struct rq_map_data {
986         struct page **pages;
987         unsigned long offset;
988         unsigned short page_order;
989         unsigned short nr_entries;
990         bool null_mapped;
991         bool from_user;
992 };
993
994 int blk_rq_map_user(struct request_queue *, struct request *,
995                 struct rq_map_data *, void __user *, unsigned long, gfp_t);
996 int blk_rq_map_user_io(struct request *, struct rq_map_data *,
997                 void __user *, unsigned long, gfp_t, bool, int, bool, int);
998 int blk_rq_map_user_iov(struct request_queue *, struct request *,
999                 struct rq_map_data *, const struct iov_iter *, gfp_t);
1000 int blk_rq_unmap_user(struct bio *);
1001 int blk_rq_map_kern(struct request_queue *, struct request *, void *,
1002                 unsigned int, gfp_t);
1003 int blk_rq_append_bio(struct request *rq, struct bio *bio);
1004 void blk_execute_rq_nowait(struct request *rq, bool at_head);
1005 blk_status_t blk_execute_rq(struct request *rq, bool at_head);
1006 bool blk_rq_is_poll(struct request *rq);
1007
1008 struct req_iterator {
1009         struct bvec_iter iter;
1010         struct bio *bio;
1011 };
1012
1013 #define __rq_for_each_bio(_bio, rq)     \
1014         if ((rq->bio))                  \
1015                 for (_bio = (rq)->bio; _bio; _bio = _bio->bi_next)
1016
1017 #define rq_for_each_segment(bvl, _rq, _iter)                    \
1018         __rq_for_each_bio(_iter.bio, _rq)                       \
1019                 bio_for_each_segment(bvl, _iter.bio, _iter.iter)
1020
1021 #define rq_for_each_bvec(bvl, _rq, _iter)                       \
1022         __rq_for_each_bio(_iter.bio, _rq)                       \
1023                 bio_for_each_bvec(bvl, _iter.bio, _iter.iter)
1024
1025 #define rq_iter_last(bvec, _iter)                               \
1026                 (_iter.bio->bi_next == NULL &&                  \
1027                  bio_iter_last(bvec, _iter.iter))
1028
1029 /*
1030  * blk_rq_pos()                 : the current sector
1031  * blk_rq_bytes()               : bytes left in the entire request
1032  * blk_rq_cur_bytes()           : bytes left in the current segment
1033  * blk_rq_sectors()             : sectors left in the entire request
1034  * blk_rq_cur_sectors()         : sectors left in the current segment
1035  * blk_rq_stats_sectors()       : sectors of the entire request used for stats
1036  */
1037 static inline sector_t blk_rq_pos(const struct request *rq)
1038 {
1039         return rq->__sector;
1040 }
1041
1042 static inline unsigned int blk_rq_bytes(const struct request *rq)
1043 {
1044         return rq->__data_len;
1045 }
1046
1047 static inline int blk_rq_cur_bytes(const struct request *rq)
1048 {
1049         if (!rq->bio)
1050                 return 0;
1051         if (!bio_has_data(rq->bio))     /* dataless requests such as discard */
1052                 return rq->bio->bi_iter.bi_size;
1053         return bio_iovec(rq->bio).bv_len;
1054 }
1055
1056 static inline unsigned int blk_rq_sectors(const struct request *rq)
1057 {
1058         return blk_rq_bytes(rq) >> SECTOR_SHIFT;
1059 }
1060
1061 static inline unsigned int blk_rq_cur_sectors(const struct request *rq)
1062 {
1063         return blk_rq_cur_bytes(rq) >> SECTOR_SHIFT;
1064 }
1065
1066 static inline unsigned int blk_rq_stats_sectors(const struct request *rq)
1067 {
1068         return rq->stats_sectors;
1069 }
1070
1071 /*
1072  * Some commands like WRITE SAME have a payload or data transfer size which
1073  * is different from the size of the request.  Any driver that supports such
1074  * commands using the RQF_SPECIAL_PAYLOAD flag needs to use this helper to
1075  * calculate the data transfer size.
1076  */
1077 static inline unsigned int blk_rq_payload_bytes(struct request *rq)
1078 {
1079         if (rq->rq_flags & RQF_SPECIAL_PAYLOAD)
1080                 return rq->special_vec.bv_len;
1081         return blk_rq_bytes(rq);
1082 }
1083
1084 /*
1085  * Return the first full biovec in the request.  The caller needs to check that
1086  * there are any bvecs before calling this helper.
1087  */
1088 static inline struct bio_vec req_bvec(struct request *rq)
1089 {
1090         if (rq->rq_flags & RQF_SPECIAL_PAYLOAD)
1091                 return rq->special_vec;
1092         return mp_bvec_iter_bvec(rq->bio->bi_io_vec, rq->bio->bi_iter);
1093 }
1094
1095 static inline unsigned int blk_rq_count_bios(struct request *rq)
1096 {
1097         unsigned int nr_bios = 0;
1098         struct bio *bio;
1099
1100         __rq_for_each_bio(bio, rq)
1101                 nr_bios++;
1102
1103         return nr_bios;
1104 }
1105
1106 void blk_steal_bios(struct bio_list *list, struct request *rq);
1107
1108 /*
1109  * Request completion related functions.
1110  *
1111  * blk_update_request() completes given number of bytes and updates
1112  * the request without completing it.
1113  */
1114 bool blk_update_request(struct request *rq, blk_status_t error,
1115                                unsigned int nr_bytes);
1116 void blk_abort_request(struct request *);
1117
1118 /*
1119  * Number of physical segments as sent to the device.
1120  *
1121  * Normally this is the number of discontiguous data segments sent by the
1122  * submitter.  But for data-less command like discard we might have no
1123  * actual data segments submitted, but the driver might have to add it's
1124  * own special payload.  In that case we still return 1 here so that this
1125  * special payload will be mapped.
1126  */
1127 static inline unsigned short blk_rq_nr_phys_segments(struct request *rq)
1128 {
1129         if (rq->rq_flags & RQF_SPECIAL_PAYLOAD)
1130                 return 1;
1131         return rq->nr_phys_segments;
1132 }
1133
1134 /*
1135  * Number of discard segments (or ranges) the driver needs to fill in.
1136  * Each discard bio merged into a request is counted as one segment.
1137  */
1138 static inline unsigned short blk_rq_nr_discard_segments(struct request *rq)
1139 {
1140         return max_t(unsigned short, rq->nr_phys_segments, 1);
1141 }
1142
1143 int __blk_rq_map_sg(struct request_queue *q, struct request *rq,
1144                 struct scatterlist *sglist, struct scatterlist **last_sg);
1145 static inline int blk_rq_map_sg(struct request_queue *q, struct request *rq,
1146                 struct scatterlist *sglist)
1147 {
1148         struct scatterlist *last_sg = NULL;
1149
1150         return __blk_rq_map_sg(q, rq, sglist, &last_sg);
1151 }
1152 void blk_dump_rq_flags(struct request *, char *);
1153
1154 #ifdef CONFIG_BLK_DEV_ZONED
1155 static inline unsigned int blk_rq_zone_no(struct request *rq)
1156 {
1157         return disk_zone_no(rq->q->disk, blk_rq_pos(rq));
1158 }
1159
1160 static inline unsigned int blk_rq_zone_is_seq(struct request *rq)
1161 {
1162         return disk_zone_is_seq(rq->q->disk, blk_rq_pos(rq));
1163 }
1164
1165 bool blk_req_needs_zone_write_lock(struct request *rq);
1166 bool blk_req_zone_write_trylock(struct request *rq);
1167 void __blk_req_zone_write_lock(struct request *rq);
1168 void __blk_req_zone_write_unlock(struct request *rq);
1169
1170 static inline void blk_req_zone_write_lock(struct request *rq)
1171 {
1172         if (blk_req_needs_zone_write_lock(rq))
1173                 __blk_req_zone_write_lock(rq);
1174 }
1175
1176 static inline void blk_req_zone_write_unlock(struct request *rq)
1177 {
1178         if (rq->rq_flags & RQF_ZONE_WRITE_LOCKED)
1179                 __blk_req_zone_write_unlock(rq);
1180 }
1181
1182 static inline bool blk_req_zone_is_write_locked(struct request *rq)
1183 {
1184         return rq->q->disk->seq_zones_wlock &&
1185                 test_bit(blk_rq_zone_no(rq), rq->q->disk->seq_zones_wlock);
1186 }
1187
1188 static inline bool blk_req_can_dispatch_to_zone(struct request *rq)
1189 {
1190         if (!blk_req_needs_zone_write_lock(rq))
1191                 return true;
1192         return !blk_req_zone_is_write_locked(rq);
1193 }
1194 #else /* CONFIG_BLK_DEV_ZONED */
1195 static inline bool blk_req_needs_zone_write_lock(struct request *rq)
1196 {
1197         return false;
1198 }
1199
1200 static inline void blk_req_zone_write_lock(struct request *rq)
1201 {
1202 }
1203
1204 static inline void blk_req_zone_write_unlock(struct request *rq)
1205 {
1206 }
1207 static inline bool blk_req_zone_is_write_locked(struct request *rq)
1208 {
1209         return false;
1210 }
1211
1212 static inline bool blk_req_can_dispatch_to_zone(struct request *rq)
1213 {
1214         return true;
1215 }
1216 #endif /* CONFIG_BLK_DEV_ZONED */
1217
1218 #endif /* BLK_MQ_H */