GNU Linux-libre 5.10.215-gnu1
[releases.git] / drivers / scsi / scsi_lib.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 1999 Eric Youngdale
4  * Copyright (C) 2014 Christoph Hellwig
5  *
6  *  SCSI queueing library.
7  *      Initial versions: Eric Youngdale (eric@andante.org).
8  *                        Based upon conversations with large numbers
9  *                        of people at Linux Expo.
10  */
11
12 #include <linux/bio.h>
13 #include <linux/bitops.h>
14 #include <linux/blkdev.h>
15 #include <linux/completion.h>
16 #include <linux/kernel.h>
17 #include <linux/export.h>
18 #include <linux/init.h>
19 #include <linux/pci.h>
20 #include <linux/delay.h>
21 #include <linux/hardirq.h>
22 #include <linux/scatterlist.h>
23 #include <linux/blk-mq.h>
24 #include <linux/ratelimit.h>
25 #include <asm/unaligned.h>
26
27 #include <scsi/scsi.h>
28 #include <scsi/scsi_cmnd.h>
29 #include <scsi/scsi_dbg.h>
30 #include <scsi/scsi_device.h>
31 #include <scsi/scsi_driver.h>
32 #include <scsi/scsi_eh.h>
33 #include <scsi/scsi_host.h>
34 #include <scsi/scsi_transport.h> /* __scsi_init_queue() */
35 #include <scsi/scsi_dh.h>
36
37 #include <trace/events/scsi.h>
38
39 #include "scsi_debugfs.h"
40 #include "scsi_priv.h"
41 #include "scsi_logging.h"
42
43 /*
44  * Size of integrity metadata is usually small, 1 inline sg should
45  * cover normal cases.
46  */
47 #ifdef CONFIG_ARCH_NO_SG_CHAIN
48 #define  SCSI_INLINE_PROT_SG_CNT  0
49 #define  SCSI_INLINE_SG_CNT  0
50 #else
51 #define  SCSI_INLINE_PROT_SG_CNT  1
52 #define  SCSI_INLINE_SG_CNT  2
53 #endif
54
55 static struct kmem_cache *scsi_sense_cache;
56 static struct kmem_cache *scsi_sense_isadma_cache;
57 static DEFINE_MUTEX(scsi_sense_cache_mutex);
58
59 static void scsi_mq_uninit_cmd(struct scsi_cmnd *cmd);
60
61 static inline struct kmem_cache *
62 scsi_select_sense_cache(bool unchecked_isa_dma)
63 {
64         return unchecked_isa_dma ? scsi_sense_isadma_cache : scsi_sense_cache;
65 }
66
67 static void scsi_free_sense_buffer(bool unchecked_isa_dma,
68                                    unsigned char *sense_buffer)
69 {
70         kmem_cache_free(scsi_select_sense_cache(unchecked_isa_dma),
71                         sense_buffer);
72 }
73
74 static unsigned char *scsi_alloc_sense_buffer(bool unchecked_isa_dma,
75         gfp_t gfp_mask, int numa_node)
76 {
77         return kmem_cache_alloc_node(scsi_select_sense_cache(unchecked_isa_dma),
78                                      gfp_mask, numa_node);
79 }
80
81 int scsi_init_sense_cache(struct Scsi_Host *shost)
82 {
83         struct kmem_cache *cache;
84         int ret = 0;
85
86         mutex_lock(&scsi_sense_cache_mutex);
87         cache = scsi_select_sense_cache(shost->unchecked_isa_dma);
88         if (cache)
89                 goto exit;
90
91         if (shost->unchecked_isa_dma) {
92                 scsi_sense_isadma_cache =
93                         kmem_cache_create("scsi_sense_cache(DMA)",
94                                 SCSI_SENSE_BUFFERSIZE, 0,
95                                 SLAB_HWCACHE_ALIGN | SLAB_CACHE_DMA, NULL);
96                 if (!scsi_sense_isadma_cache)
97                         ret = -ENOMEM;
98         } else {
99                 scsi_sense_cache =
100                         kmem_cache_create_usercopy("scsi_sense_cache",
101                                 SCSI_SENSE_BUFFERSIZE, 0, SLAB_HWCACHE_ALIGN,
102                                 0, SCSI_SENSE_BUFFERSIZE, NULL);
103                 if (!scsi_sense_cache)
104                         ret = -ENOMEM;
105         }
106  exit:
107         mutex_unlock(&scsi_sense_cache_mutex);
108         return ret;
109 }
110
111 /*
112  * When to reinvoke queueing after a resource shortage. It's 3 msecs to
113  * not change behaviour from the previous unplug mechanism, experimentation
114  * may prove this needs changing.
115  */
116 #define SCSI_QUEUE_DELAY        3
117
118 static void
119 scsi_set_blocked(struct scsi_cmnd *cmd, int reason)
120 {
121         struct Scsi_Host *host = cmd->device->host;
122         struct scsi_device *device = cmd->device;
123         struct scsi_target *starget = scsi_target(device);
124
125         /*
126          * Set the appropriate busy bit for the device/host.
127          *
128          * If the host/device isn't busy, assume that something actually
129          * completed, and that we should be able to queue a command now.
130          *
131          * Note that the prior mid-layer assumption that any host could
132          * always queue at least one command is now broken.  The mid-layer
133          * will implement a user specifiable stall (see
134          * scsi_host.max_host_blocked and scsi_device.max_device_blocked)
135          * if a command is requeued with no other commands outstanding
136          * either for the device or for the host.
137          */
138         switch (reason) {
139         case SCSI_MLQUEUE_HOST_BUSY:
140                 atomic_set(&host->host_blocked, host->max_host_blocked);
141                 break;
142         case SCSI_MLQUEUE_DEVICE_BUSY:
143         case SCSI_MLQUEUE_EH_RETRY:
144                 atomic_set(&device->device_blocked,
145                            device->max_device_blocked);
146                 break;
147         case SCSI_MLQUEUE_TARGET_BUSY:
148                 atomic_set(&starget->target_blocked,
149                            starget->max_target_blocked);
150                 break;
151         }
152 }
153
154 static void scsi_mq_requeue_cmd(struct scsi_cmnd *cmd)
155 {
156         if (cmd->request->rq_flags & RQF_DONTPREP) {
157                 cmd->request->rq_flags &= ~RQF_DONTPREP;
158                 scsi_mq_uninit_cmd(cmd);
159         } else {
160                 WARN_ON_ONCE(true);
161         }
162         blk_mq_requeue_request(cmd->request, true);
163 }
164
165 /**
166  * __scsi_queue_insert - private queue insertion
167  * @cmd: The SCSI command being requeued
168  * @reason:  The reason for the requeue
169  * @unbusy: Whether the queue should be unbusied
170  *
171  * This is a private queue insertion.  The public interface
172  * scsi_queue_insert() always assumes the queue should be unbusied
173  * because it's always called before the completion.  This function is
174  * for a requeue after completion, which should only occur in this
175  * file.
176  */
177 static void __scsi_queue_insert(struct scsi_cmnd *cmd, int reason, bool unbusy)
178 {
179         struct scsi_device *device = cmd->device;
180
181         SCSI_LOG_MLQUEUE(1, scmd_printk(KERN_INFO, cmd,
182                 "Inserting command %p into mlqueue\n", cmd));
183
184         scsi_set_blocked(cmd, reason);
185
186         /*
187          * Decrement the counters, since these commands are no longer
188          * active on the host/device.
189          */
190         if (unbusy)
191                 scsi_device_unbusy(device, cmd);
192
193         /*
194          * Requeue this command.  It will go before all other commands
195          * that are already in the queue. Schedule requeue work under
196          * lock such that the kblockd_schedule_work() call happens
197          * before blk_cleanup_queue() finishes.
198          */
199         cmd->result = 0;
200
201         blk_mq_requeue_request(cmd->request, true);
202 }
203
204 /**
205  * scsi_queue_insert - Reinsert a command in the queue.
206  * @cmd:    command that we are adding to queue.
207  * @reason: why we are inserting command to queue.
208  *
209  * We do this for one of two cases. Either the host is busy and it cannot accept
210  * any more commands for the time being, or the device returned QUEUE_FULL and
211  * can accept no more commands.
212  *
213  * Context: This could be called either from an interrupt context or a normal
214  * process context.
215  */
216 void scsi_queue_insert(struct scsi_cmnd *cmd, int reason)
217 {
218         __scsi_queue_insert(cmd, reason, true);
219 }
220
221
222 /**
223  * __scsi_execute - insert request and wait for the result
224  * @sdev:       scsi device
225  * @cmd:        scsi command
226  * @data_direction: data direction
227  * @buffer:     data buffer
228  * @bufflen:    len of buffer
229  * @sense:      optional sense buffer
230  * @sshdr:      optional decoded sense header
231  * @timeout:    request timeout in seconds
232  * @retries:    number of times to retry request
233  * @flags:      flags for ->cmd_flags
234  * @rq_flags:   flags for ->rq_flags
235  * @resid:      optional residual length
236  *
237  * Returns the scsi_cmnd result field if a command was executed, or a negative
238  * Linux error code if we didn't get that far.
239  */
240 int __scsi_execute(struct scsi_device *sdev, const unsigned char *cmd,
241                  int data_direction, void *buffer, unsigned bufflen,
242                  unsigned char *sense, struct scsi_sense_hdr *sshdr,
243                  int timeout, int retries, u64 flags, req_flags_t rq_flags,
244                  int *resid)
245 {
246         struct request *req;
247         struct scsi_request *rq;
248         int ret = DRIVER_ERROR << 24;
249
250         req = blk_get_request(sdev->request_queue,
251                         data_direction == DMA_TO_DEVICE ?
252                         REQ_OP_SCSI_OUT : REQ_OP_SCSI_IN,
253                         rq_flags & RQF_PM ? BLK_MQ_REQ_PM : 0);
254         if (IS_ERR(req))
255                 return ret;
256         rq = scsi_req(req);
257
258         if (bufflen &&  blk_rq_map_kern(sdev->request_queue, req,
259                                         buffer, bufflen, GFP_NOIO))
260                 goto out;
261
262         rq->cmd_len = COMMAND_SIZE(cmd[0]);
263         memcpy(rq->cmd, cmd, rq->cmd_len);
264         rq->retries = retries;
265         req->timeout = timeout;
266         req->cmd_flags |= flags;
267         req->rq_flags |= rq_flags | RQF_QUIET;
268
269         /*
270          * head injection *required* here otherwise quiesce won't work
271          */
272         blk_execute_rq(req->q, NULL, req, 1);
273
274         /*
275          * Some devices (USB mass-storage in particular) may transfer
276          * garbage data together with a residue indicating that the data
277          * is invalid.  Prevent the garbage from being misinterpreted
278          * and prevent security leaks by zeroing out the excess data.
279          */
280         if (unlikely(rq->resid_len > 0 && rq->resid_len <= bufflen))
281                 memset(buffer + (bufflen - rq->resid_len), 0, rq->resid_len);
282
283         if (resid)
284                 *resid = rq->resid_len;
285         if (sense && rq->sense_len)
286                 memcpy(sense, rq->sense, SCSI_SENSE_BUFFERSIZE);
287         if (sshdr)
288                 scsi_normalize_sense(rq->sense, rq->sense_len, sshdr);
289         ret = rq->result;
290  out:
291         blk_put_request(req);
292
293         return ret;
294 }
295 EXPORT_SYMBOL(__scsi_execute);
296
297 /*
298  * Wake up the error handler if necessary. Avoid as follows that the error
299  * handler is not woken up if host in-flight requests number ==
300  * shost->host_failed: use call_rcu() in scsi_eh_scmd_add() in combination
301  * with an RCU read lock in this function to ensure that this function in
302  * its entirety either finishes before scsi_eh_scmd_add() increases the
303  * host_failed counter or that it notices the shost state change made by
304  * scsi_eh_scmd_add().
305  */
306 static void scsi_dec_host_busy(struct Scsi_Host *shost, struct scsi_cmnd *cmd)
307 {
308         unsigned long flags;
309
310         rcu_read_lock();
311         __clear_bit(SCMD_STATE_INFLIGHT, &cmd->state);
312         if (unlikely(scsi_host_in_recovery(shost))) {
313                 unsigned int busy = scsi_host_busy(shost);
314
315                 spin_lock_irqsave(shost->host_lock, flags);
316                 if (shost->host_failed || shost->host_eh_scheduled)
317                         scsi_eh_wakeup(shost, busy);
318                 spin_unlock_irqrestore(shost->host_lock, flags);
319         }
320         rcu_read_unlock();
321 }
322
323 void scsi_device_unbusy(struct scsi_device *sdev, struct scsi_cmnd *cmd)
324 {
325         struct Scsi_Host *shost = sdev->host;
326         struct scsi_target *starget = scsi_target(sdev);
327
328         scsi_dec_host_busy(shost, cmd);
329
330         if (starget->can_queue > 0)
331                 atomic_dec(&starget->target_busy);
332
333         atomic_dec(&sdev->device_busy);
334 }
335
336 static void scsi_kick_queue(struct request_queue *q)
337 {
338         blk_mq_run_hw_queues(q, false);
339 }
340
341 /*
342  * Called for single_lun devices on IO completion. Clear starget_sdev_user,
343  * and call blk_run_queue for all the scsi_devices on the target -
344  * including current_sdev first.
345  *
346  * Called with *no* scsi locks held.
347  */
348 static void scsi_single_lun_run(struct scsi_device *current_sdev)
349 {
350         struct Scsi_Host *shost = current_sdev->host;
351         struct scsi_device *sdev, *tmp;
352         struct scsi_target *starget = scsi_target(current_sdev);
353         unsigned long flags;
354
355         spin_lock_irqsave(shost->host_lock, flags);
356         starget->starget_sdev_user = NULL;
357         spin_unlock_irqrestore(shost->host_lock, flags);
358
359         /*
360          * Call blk_run_queue for all LUNs on the target, starting with
361          * current_sdev. We race with others (to set starget_sdev_user),
362          * but in most cases, we will be first. Ideally, each LU on the
363          * target would get some limited time or requests on the target.
364          */
365         scsi_kick_queue(current_sdev->request_queue);
366
367         spin_lock_irqsave(shost->host_lock, flags);
368         if (starget->starget_sdev_user)
369                 goto out;
370         list_for_each_entry_safe(sdev, tmp, &starget->devices,
371                         same_target_siblings) {
372                 if (sdev == current_sdev)
373                         continue;
374                 if (scsi_device_get(sdev))
375                         continue;
376
377                 spin_unlock_irqrestore(shost->host_lock, flags);
378                 scsi_kick_queue(sdev->request_queue);
379                 spin_lock_irqsave(shost->host_lock, flags);
380
381                 scsi_device_put(sdev);
382         }
383  out:
384         spin_unlock_irqrestore(shost->host_lock, flags);
385 }
386
387 static inline bool scsi_device_is_busy(struct scsi_device *sdev)
388 {
389         if (atomic_read(&sdev->device_busy) >= sdev->queue_depth)
390                 return true;
391         if (atomic_read(&sdev->device_blocked) > 0)
392                 return true;
393         return false;
394 }
395
396 static inline bool scsi_target_is_busy(struct scsi_target *starget)
397 {
398         if (starget->can_queue > 0) {
399                 if (atomic_read(&starget->target_busy) >= starget->can_queue)
400                         return true;
401                 if (atomic_read(&starget->target_blocked) > 0)
402                         return true;
403         }
404         return false;
405 }
406
407 static inline bool scsi_host_is_busy(struct Scsi_Host *shost)
408 {
409         if (atomic_read(&shost->host_blocked) > 0)
410                 return true;
411         if (shost->host_self_blocked)
412                 return true;
413         return false;
414 }
415
416 static void scsi_starved_list_run(struct Scsi_Host *shost)
417 {
418         LIST_HEAD(starved_list);
419         struct scsi_device *sdev;
420         unsigned long flags;
421
422         spin_lock_irqsave(shost->host_lock, flags);
423         list_splice_init(&shost->starved_list, &starved_list);
424
425         while (!list_empty(&starved_list)) {
426                 struct request_queue *slq;
427
428                 /*
429                  * As long as shost is accepting commands and we have
430                  * starved queues, call blk_run_queue. scsi_request_fn
431                  * drops the queue_lock and can add us back to the
432                  * starved_list.
433                  *
434                  * host_lock protects the starved_list and starved_entry.
435                  * scsi_request_fn must get the host_lock before checking
436                  * or modifying starved_list or starved_entry.
437                  */
438                 if (scsi_host_is_busy(shost))
439                         break;
440
441                 sdev = list_entry(starved_list.next,
442                                   struct scsi_device, starved_entry);
443                 list_del_init(&sdev->starved_entry);
444                 if (scsi_target_is_busy(scsi_target(sdev))) {
445                         list_move_tail(&sdev->starved_entry,
446                                        &shost->starved_list);
447                         continue;
448                 }
449
450                 /*
451                  * Once we drop the host lock, a racing scsi_remove_device()
452                  * call may remove the sdev from the starved list and destroy
453                  * it and the queue.  Mitigate by taking a reference to the
454                  * queue and never touching the sdev again after we drop the
455                  * host lock.  Note: if __scsi_remove_device() invokes
456                  * blk_cleanup_queue() before the queue is run from this
457                  * function then blk_run_queue() will return immediately since
458                  * blk_cleanup_queue() marks the queue with QUEUE_FLAG_DYING.
459                  */
460                 slq = sdev->request_queue;
461                 if (!blk_get_queue(slq))
462                         continue;
463                 spin_unlock_irqrestore(shost->host_lock, flags);
464
465                 scsi_kick_queue(slq);
466                 blk_put_queue(slq);
467
468                 spin_lock_irqsave(shost->host_lock, flags);
469         }
470         /* put any unprocessed entries back */
471         list_splice(&starved_list, &shost->starved_list);
472         spin_unlock_irqrestore(shost->host_lock, flags);
473 }
474
475 /**
476  * scsi_run_queue - Select a proper request queue to serve next.
477  * @q:  last request's queue
478  *
479  * The previous command was completely finished, start a new one if possible.
480  */
481 static void scsi_run_queue(struct request_queue *q)
482 {
483         struct scsi_device *sdev = q->queuedata;
484
485         if (scsi_target(sdev)->single_lun)
486                 scsi_single_lun_run(sdev);
487         if (!list_empty(&sdev->host->starved_list))
488                 scsi_starved_list_run(sdev->host);
489
490         blk_mq_run_hw_queues(q, false);
491 }
492
493 void scsi_requeue_run_queue(struct work_struct *work)
494 {
495         struct scsi_device *sdev;
496         struct request_queue *q;
497
498         sdev = container_of(work, struct scsi_device, requeue_work);
499         q = sdev->request_queue;
500         scsi_run_queue(q);
501 }
502
503 void scsi_run_host_queues(struct Scsi_Host *shost)
504 {
505         struct scsi_device *sdev;
506
507         shost_for_each_device(sdev, shost)
508                 scsi_run_queue(sdev->request_queue);
509 }
510
511 static void scsi_uninit_cmd(struct scsi_cmnd *cmd)
512 {
513         if (!blk_rq_is_passthrough(cmd->request)) {
514                 struct scsi_driver *drv = scsi_cmd_to_driver(cmd);
515
516                 if (drv->uninit_command)
517                         drv->uninit_command(cmd);
518         }
519 }
520
521 void scsi_free_sgtables(struct scsi_cmnd *cmd)
522 {
523         if (cmd->sdb.table.nents)
524                 sg_free_table_chained(&cmd->sdb.table,
525                                 SCSI_INLINE_SG_CNT);
526         if (scsi_prot_sg_count(cmd))
527                 sg_free_table_chained(&cmd->prot_sdb->table,
528                                 SCSI_INLINE_PROT_SG_CNT);
529 }
530 EXPORT_SYMBOL_GPL(scsi_free_sgtables);
531
532 static void scsi_mq_uninit_cmd(struct scsi_cmnd *cmd)
533 {
534         scsi_free_sgtables(cmd);
535         scsi_uninit_cmd(cmd);
536 }
537
538 static void scsi_run_queue_async(struct scsi_device *sdev)
539 {
540         if (scsi_target(sdev)->single_lun ||
541             !list_empty(&sdev->host->starved_list)) {
542                 kblockd_schedule_work(&sdev->requeue_work);
543         } else {
544                 /*
545                  * smp_mb() present in sbitmap_queue_clear() or implied in
546                  * .end_io is for ordering writing .device_busy in
547                  * scsi_device_unbusy() and reading sdev->restarts.
548                  */
549                 int old = atomic_read(&sdev->restarts);
550
551                 /*
552                  * ->restarts has to be kept as non-zero if new budget
553                  *  contention occurs.
554                  *
555                  *  No need to run queue when either another re-run
556                  *  queue wins in updating ->restarts or a new budget
557                  *  contention occurs.
558                  */
559                 if (old && atomic_cmpxchg(&sdev->restarts, old, 0) == old)
560                         blk_mq_run_hw_queues(sdev->request_queue, true);
561         }
562 }
563
564 /* Returns false when no more bytes to process, true if there are more */
565 static bool scsi_end_request(struct request *req, blk_status_t error,
566                 unsigned int bytes)
567 {
568         struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
569         struct scsi_device *sdev = cmd->device;
570         struct request_queue *q = sdev->request_queue;
571
572         if (blk_update_request(req, error, bytes))
573                 return true;
574
575         if (blk_queue_add_random(q))
576                 add_disk_randomness(req->rq_disk);
577
578         if (!blk_rq_is_scsi(req)) {
579                 WARN_ON_ONCE(!(cmd->flags & SCMD_INITIALIZED));
580                 cmd->flags &= ~SCMD_INITIALIZED;
581         }
582
583         /*
584          * Calling rcu_barrier() is not necessary here because the
585          * SCSI error handler guarantees that the function called by
586          * call_rcu() has been called before scsi_end_request() is
587          * called.
588          */
589         destroy_rcu_head(&cmd->rcu);
590
591         /*
592          * In the MQ case the command gets freed by __blk_mq_end_request,
593          * so we have to do all cleanup that depends on it earlier.
594          *
595          * We also can't kick the queues from irq context, so we
596          * will have to defer it to a workqueue.
597          */
598         scsi_mq_uninit_cmd(cmd);
599
600         /*
601          * queue is still alive, so grab the ref for preventing it
602          * from being cleaned up during running queue.
603          */
604         percpu_ref_get(&q->q_usage_counter);
605
606         __blk_mq_end_request(req, error);
607
608         scsi_run_queue_async(sdev);
609
610         percpu_ref_put(&q->q_usage_counter);
611         return false;
612 }
613
614 /**
615  * scsi_result_to_blk_status - translate a SCSI result code into blk_status_t
616  * @cmd:        SCSI command
617  * @result:     scsi error code
618  *
619  * Translate a SCSI result code into a blk_status_t value. May reset the host
620  * byte of @cmd->result.
621  */
622 static blk_status_t scsi_result_to_blk_status(struct scsi_cmnd *cmd, int result)
623 {
624         switch (host_byte(result)) {
625         case DID_OK:
626                 /*
627                  * Also check the other bytes than the status byte in result
628                  * to handle the case when a SCSI LLD sets result to
629                  * DRIVER_SENSE << 24 without setting SAM_STAT_CHECK_CONDITION.
630                  */
631                 if (scsi_status_is_good(result) && (result & ~0xff) == 0)
632                         return BLK_STS_OK;
633                 return BLK_STS_IOERR;
634         case DID_TRANSPORT_FAILFAST:
635                 return BLK_STS_TRANSPORT;
636         case DID_TARGET_FAILURE:
637                 set_host_byte(cmd, DID_OK);
638                 return BLK_STS_TARGET;
639         case DID_NEXUS_FAILURE:
640                 set_host_byte(cmd, DID_OK);
641                 return BLK_STS_NEXUS;
642         case DID_ALLOC_FAILURE:
643                 set_host_byte(cmd, DID_OK);
644                 return BLK_STS_NOSPC;
645         case DID_MEDIUM_ERROR:
646                 set_host_byte(cmd, DID_OK);
647                 return BLK_STS_MEDIUM;
648         default:
649                 return BLK_STS_IOERR;
650         }
651 }
652
653 /* Helper for scsi_io_completion() when "reprep" action required. */
654 static void scsi_io_completion_reprep(struct scsi_cmnd *cmd,
655                                       struct request_queue *q)
656 {
657         /* A new command will be prepared and issued. */
658         scsi_mq_requeue_cmd(cmd);
659 }
660
661 static bool scsi_cmd_runtime_exceeced(struct scsi_cmnd *cmd)
662 {
663         struct request *req = cmd->request;
664         unsigned long wait_for;
665
666         if (cmd->allowed == SCSI_CMD_RETRIES_NO_LIMIT)
667                 return false;
668
669         wait_for = (cmd->allowed + 1) * req->timeout;
670         if (time_before(cmd->jiffies_at_alloc + wait_for, jiffies)) {
671                 scmd_printk(KERN_ERR, cmd, "timing out command, waited %lus\n",
672                             wait_for/HZ);
673                 return true;
674         }
675         return false;
676 }
677
678 /* Helper for scsi_io_completion() when special action required. */
679 static void scsi_io_completion_action(struct scsi_cmnd *cmd, int result)
680 {
681         struct request_queue *q = cmd->device->request_queue;
682         struct request *req = cmd->request;
683         int level = 0;
684         enum {ACTION_FAIL, ACTION_REPREP, ACTION_RETRY,
685               ACTION_DELAYED_RETRY} action;
686         struct scsi_sense_hdr sshdr;
687         bool sense_valid;
688         bool sense_current = true;      /* false implies "deferred sense" */
689         blk_status_t blk_stat;
690
691         sense_valid = scsi_command_normalize_sense(cmd, &sshdr);
692         if (sense_valid)
693                 sense_current = !scsi_sense_is_deferred(&sshdr);
694
695         blk_stat = scsi_result_to_blk_status(cmd, result);
696
697         if (host_byte(result) == DID_RESET) {
698                 /* Third party bus reset or reset for error recovery
699                  * reasons.  Just retry the command and see what
700                  * happens.
701                  */
702                 action = ACTION_RETRY;
703         } else if (sense_valid && sense_current) {
704                 switch (sshdr.sense_key) {
705                 case UNIT_ATTENTION:
706                         if (cmd->device->removable) {
707                                 /* Detected disc change.  Set a bit
708                                  * and quietly refuse further access.
709                                  */
710                                 cmd->device->changed = 1;
711                                 action = ACTION_FAIL;
712                         } else {
713                                 /* Must have been a power glitch, or a
714                                  * bus reset.  Could not have been a
715                                  * media change, so we just retry the
716                                  * command and see what happens.
717                                  */
718                                 action = ACTION_RETRY;
719                         }
720                         break;
721                 case ILLEGAL_REQUEST:
722                         /* If we had an ILLEGAL REQUEST returned, then
723                          * we may have performed an unsupported
724                          * command.  The only thing this should be
725                          * would be a ten byte read where only a six
726                          * byte read was supported.  Also, on a system
727                          * where READ CAPACITY failed, we may have
728                          * read past the end of the disk.
729                          */
730                         if ((cmd->device->use_10_for_rw &&
731                             sshdr.asc == 0x20 && sshdr.ascq == 0x00) &&
732                             (cmd->cmnd[0] == READ_10 ||
733                              cmd->cmnd[0] == WRITE_10)) {
734                                 /* This will issue a new 6-byte command. */
735                                 cmd->device->use_10_for_rw = 0;
736                                 action = ACTION_REPREP;
737                         } else if (sshdr.asc == 0x10) /* DIX */ {
738                                 action = ACTION_FAIL;
739                                 blk_stat = BLK_STS_PROTECTION;
740                         /* INVALID COMMAND OPCODE or INVALID FIELD IN CDB */
741                         } else if (sshdr.asc == 0x20 || sshdr.asc == 0x24) {
742                                 action = ACTION_FAIL;
743                                 blk_stat = BLK_STS_TARGET;
744                         } else
745                                 action = ACTION_FAIL;
746                         break;
747                 case ABORTED_COMMAND:
748                         action = ACTION_FAIL;
749                         if (sshdr.asc == 0x10) /* DIF */
750                                 blk_stat = BLK_STS_PROTECTION;
751                         break;
752                 case NOT_READY:
753                         /* If the device is in the process of becoming
754                          * ready, or has a temporary blockage, retry.
755                          */
756                         if (sshdr.asc == 0x04) {
757                                 switch (sshdr.ascq) {
758                                 case 0x01: /* becoming ready */
759                                 case 0x04: /* format in progress */
760                                 case 0x05: /* rebuild in progress */
761                                 case 0x06: /* recalculation in progress */
762                                 case 0x07: /* operation in progress */
763                                 case 0x08: /* Long write in progress */
764                                 case 0x09: /* self test in progress */
765                                 case 0x11: /* notify (enable spinup) required */
766                                 case 0x14: /* space allocation in progress */
767                                 case 0x1a: /* start stop unit in progress */
768                                 case 0x1b: /* sanitize in progress */
769                                 case 0x1d: /* configuration in progress */
770                                 case 0x24: /* depopulation in progress */
771                                         action = ACTION_DELAYED_RETRY;
772                                         break;
773                                 default:
774                                         action = ACTION_FAIL;
775                                         break;
776                                 }
777                         } else
778                                 action = ACTION_FAIL;
779                         break;
780                 case VOLUME_OVERFLOW:
781                         /* See SSC3rXX or current. */
782                         action = ACTION_FAIL;
783                         break;
784                 case DATA_PROTECT:
785                         action = ACTION_FAIL;
786                         if ((sshdr.asc == 0x0C && sshdr.ascq == 0x12) ||
787                             (sshdr.asc == 0x55 &&
788                              (sshdr.ascq == 0x0E || sshdr.ascq == 0x0F))) {
789                                 /* Insufficient zone resources */
790                                 blk_stat = BLK_STS_ZONE_OPEN_RESOURCE;
791                         }
792                         break;
793                 default:
794                         action = ACTION_FAIL;
795                         break;
796                 }
797         } else
798                 action = ACTION_FAIL;
799
800         if (action != ACTION_FAIL && scsi_cmd_runtime_exceeced(cmd))
801                 action = ACTION_FAIL;
802
803         switch (action) {
804         case ACTION_FAIL:
805                 /* Give up and fail the remainder of the request */
806                 if (!(req->rq_flags & RQF_QUIET)) {
807                         static DEFINE_RATELIMIT_STATE(_rs,
808                                         DEFAULT_RATELIMIT_INTERVAL,
809                                         DEFAULT_RATELIMIT_BURST);
810
811                         if (unlikely(scsi_logging_level))
812                                 level =
813                                      SCSI_LOG_LEVEL(SCSI_LOG_MLCOMPLETE_SHIFT,
814                                                     SCSI_LOG_MLCOMPLETE_BITS);
815
816                         /*
817                          * if logging is enabled the failure will be printed
818                          * in scsi_log_completion(), so avoid duplicate messages
819                          */
820                         if (!level && __ratelimit(&_rs)) {
821                                 scsi_print_result(cmd, NULL, FAILED);
822                                 if (driver_byte(result) == DRIVER_SENSE)
823                                         scsi_print_sense(cmd);
824                                 scsi_print_command(cmd);
825                         }
826                 }
827                 if (!scsi_end_request(req, blk_stat, blk_rq_err_bytes(req)))
828                         return;
829                 fallthrough;
830         case ACTION_REPREP:
831                 scsi_io_completion_reprep(cmd, q);
832                 break;
833         case ACTION_RETRY:
834                 /* Retry the same command immediately */
835                 __scsi_queue_insert(cmd, SCSI_MLQUEUE_EH_RETRY, false);
836                 break;
837         case ACTION_DELAYED_RETRY:
838                 /* Retry the same command after a delay */
839                 __scsi_queue_insert(cmd, SCSI_MLQUEUE_DEVICE_BUSY, false);
840                 break;
841         }
842 }
843
844 /*
845  * Helper for scsi_io_completion() when cmd->result is non-zero. Returns a
846  * new result that may suppress further error checking. Also modifies
847  * *blk_statp in some cases.
848  */
849 static int scsi_io_completion_nz_result(struct scsi_cmnd *cmd, int result,
850                                         blk_status_t *blk_statp)
851 {
852         bool sense_valid;
853         bool sense_current = true;      /* false implies "deferred sense" */
854         struct request *req = cmd->request;
855         struct scsi_sense_hdr sshdr;
856
857         sense_valid = scsi_command_normalize_sense(cmd, &sshdr);
858         if (sense_valid)
859                 sense_current = !scsi_sense_is_deferred(&sshdr);
860
861         if (blk_rq_is_passthrough(req)) {
862                 if (sense_valid) {
863                         /*
864                          * SG_IO wants current and deferred errors
865                          */
866                         scsi_req(req)->sense_len =
867                                 min(8 + cmd->sense_buffer[7],
868                                     SCSI_SENSE_BUFFERSIZE);
869                 }
870                 if (sense_current)
871                         *blk_statp = scsi_result_to_blk_status(cmd, result);
872         } else if (blk_rq_bytes(req) == 0 && sense_current) {
873                 /*
874                  * Flush commands do not transfers any data, and thus cannot use
875                  * good_bytes != blk_rq_bytes(req) as the signal for an error.
876                  * This sets *blk_statp explicitly for the problem case.
877                  */
878                 *blk_statp = scsi_result_to_blk_status(cmd, result);
879         }
880         /*
881          * Recovered errors need reporting, but they're always treated as
882          * success, so fiddle the result code here.  For passthrough requests
883          * we already took a copy of the original into sreq->result which
884          * is what gets returned to the user
885          */
886         if (sense_valid && (sshdr.sense_key == RECOVERED_ERROR)) {
887                 bool do_print = true;
888                 /*
889                  * if ATA PASS-THROUGH INFORMATION AVAILABLE [0x0, 0x1d]
890                  * skip print since caller wants ATA registers. Only occurs
891                  * on SCSI ATA PASS_THROUGH commands when CK_COND=1
892                  */
893                 if ((sshdr.asc == 0x0) && (sshdr.ascq == 0x1d))
894                         do_print = false;
895                 else if (req->rq_flags & RQF_QUIET)
896                         do_print = false;
897                 if (do_print)
898                         scsi_print_sense(cmd);
899                 result = 0;
900                 /* for passthrough, *blk_statp may be set */
901                 *blk_statp = BLK_STS_OK;
902         }
903         /*
904          * Another corner case: the SCSI status byte is non-zero but 'good'.
905          * Example: PRE-FETCH command returns SAM_STAT_CONDITION_MET when
906          * it is able to fit nominated LBs in its cache (and SAM_STAT_GOOD
907          * if it can't fit). Treat SAM_STAT_CONDITION_MET and the related
908          * intermediate statuses (both obsolete in SAM-4) as good.
909          */
910         if (status_byte(result) && scsi_status_is_good(result)) {
911                 result = 0;
912                 *blk_statp = BLK_STS_OK;
913         }
914         return result;
915 }
916
917 /**
918  * scsi_io_completion - Completion processing for SCSI commands.
919  * @cmd:        command that is finished.
920  * @good_bytes: number of processed bytes.
921  *
922  * We will finish off the specified number of sectors. If we are done, the
923  * command block will be released and the queue function will be goosed. If we
924  * are not done then we have to figure out what to do next:
925  *
926  *   a) We can call scsi_io_completion_reprep().  The request will be
927  *      unprepared and put back on the queue.  Then a new command will
928  *      be created for it.  This should be used if we made forward
929  *      progress, or if we want to switch from READ(10) to READ(6) for
930  *      example.
931  *
932  *   b) We can call scsi_io_completion_action().  The request will be
933  *      put back on the queue and retried using the same command as
934  *      before, possibly after a delay.
935  *
936  *   c) We can call scsi_end_request() with blk_stat other than
937  *      BLK_STS_OK, to fail the remainder of the request.
938  */
939 void scsi_io_completion(struct scsi_cmnd *cmd, unsigned int good_bytes)
940 {
941         int result = cmd->result;
942         struct request_queue *q = cmd->device->request_queue;
943         struct request *req = cmd->request;
944         blk_status_t blk_stat = BLK_STS_OK;
945
946         if (unlikely(result))   /* a nz result may or may not be an error */
947                 result = scsi_io_completion_nz_result(cmd, result, &blk_stat);
948
949         if (unlikely(blk_rq_is_passthrough(req))) {
950                 /*
951                  * scsi_result_to_blk_status may have reset the host_byte
952                  */
953                 scsi_req(req)->result = cmd->result;
954         }
955
956         /*
957          * Next deal with any sectors which we were able to correctly
958          * handle.
959          */
960         SCSI_LOG_HLCOMPLETE(1, scmd_printk(KERN_INFO, cmd,
961                 "%u sectors total, %d bytes done.\n",
962                 blk_rq_sectors(req), good_bytes));
963
964         /*
965          * Failed, zero length commands always need to drop down
966          * to retry code. Fast path should return in this block.
967          */
968         if (likely(blk_rq_bytes(req) > 0 || blk_stat == BLK_STS_OK)) {
969                 if (likely(!scsi_end_request(req, blk_stat, good_bytes)))
970                         return; /* no bytes remaining */
971         }
972
973         /* Kill remainder if no retries. */
974         if (unlikely(blk_stat && scsi_noretry_cmd(cmd))) {
975                 if (scsi_end_request(req, blk_stat, blk_rq_bytes(req)))
976                         WARN_ONCE(true,
977                             "Bytes remaining after failed, no-retry command");
978                 return;
979         }
980
981         /*
982          * If there had been no error, but we have leftover bytes in the
983          * requeues just queue the command up again.
984          */
985         if (likely(result == 0))
986                 scsi_io_completion_reprep(cmd, q);
987         else
988                 scsi_io_completion_action(cmd, result);
989 }
990
991 static inline bool scsi_cmd_needs_dma_drain(struct scsi_device *sdev,
992                 struct request *rq)
993 {
994         return sdev->dma_drain_len && blk_rq_is_passthrough(rq) &&
995                !op_is_write(req_op(rq)) &&
996                sdev->host->hostt->dma_need_drain(rq);
997 }
998
999 /**
1000  * scsi_alloc_sgtables - allocate S/G tables for a command
1001  * @cmd:  command descriptor we wish to initialize
1002  *
1003  * Returns:
1004  * * BLK_STS_OK       - on success
1005  * * BLK_STS_RESOURCE - if the failure is retryable
1006  * * BLK_STS_IOERR    - if the failure is fatal
1007  */
1008 blk_status_t scsi_alloc_sgtables(struct scsi_cmnd *cmd)
1009 {
1010         struct scsi_device *sdev = cmd->device;
1011         struct request *rq = cmd->request;
1012         unsigned short nr_segs = blk_rq_nr_phys_segments(rq);
1013         struct scatterlist *last_sg = NULL;
1014         blk_status_t ret;
1015         bool need_drain = scsi_cmd_needs_dma_drain(sdev, rq);
1016         int count;
1017
1018         if (WARN_ON_ONCE(!nr_segs))
1019                 return BLK_STS_IOERR;
1020
1021         /*
1022          * Make sure there is space for the drain.  The driver must adjust
1023          * max_hw_segments to be prepared for this.
1024          */
1025         if (need_drain)
1026                 nr_segs++;
1027
1028         /*
1029          * If sg table allocation fails, requeue request later.
1030          */
1031         if (unlikely(sg_alloc_table_chained(&cmd->sdb.table, nr_segs,
1032                         cmd->sdb.table.sgl, SCSI_INLINE_SG_CNT)))
1033                 return BLK_STS_RESOURCE;
1034
1035         /*
1036          * Next, walk the list, and fill in the addresses and sizes of
1037          * each segment.
1038          */
1039         count = __blk_rq_map_sg(rq->q, rq, cmd->sdb.table.sgl, &last_sg);
1040
1041         if (blk_rq_bytes(rq) & rq->q->dma_pad_mask) {
1042                 unsigned int pad_len =
1043                         (rq->q->dma_pad_mask & ~blk_rq_bytes(rq)) + 1;
1044
1045                 last_sg->length += pad_len;
1046                 cmd->extra_len += pad_len;
1047         }
1048
1049         if (need_drain) {
1050                 sg_unmark_end(last_sg);
1051                 last_sg = sg_next(last_sg);
1052                 sg_set_buf(last_sg, sdev->dma_drain_buf, sdev->dma_drain_len);
1053                 sg_mark_end(last_sg);
1054
1055                 cmd->extra_len += sdev->dma_drain_len;
1056                 count++;
1057         }
1058
1059         BUG_ON(count > cmd->sdb.table.nents);
1060         cmd->sdb.table.nents = count;
1061         cmd->sdb.length = blk_rq_payload_bytes(rq);
1062
1063         if (blk_integrity_rq(rq)) {
1064                 struct scsi_data_buffer *prot_sdb = cmd->prot_sdb;
1065                 int ivecs;
1066
1067                 if (WARN_ON_ONCE(!prot_sdb)) {
1068                         /*
1069                          * This can happen if someone (e.g. multipath)
1070                          * queues a command to a device on an adapter
1071                          * that does not support DIX.
1072                          */
1073                         ret = BLK_STS_IOERR;
1074                         goto out_free_sgtables;
1075                 }
1076
1077                 ivecs = blk_rq_count_integrity_sg(rq->q, rq->bio);
1078
1079                 if (sg_alloc_table_chained(&prot_sdb->table, ivecs,
1080                                 prot_sdb->table.sgl,
1081                                 SCSI_INLINE_PROT_SG_CNT)) {
1082                         ret = BLK_STS_RESOURCE;
1083                         goto out_free_sgtables;
1084                 }
1085
1086                 count = blk_rq_map_integrity_sg(rq->q, rq->bio,
1087                                                 prot_sdb->table.sgl);
1088                 BUG_ON(count > ivecs);
1089                 BUG_ON(count > queue_max_integrity_segments(rq->q));
1090
1091                 cmd->prot_sdb = prot_sdb;
1092                 cmd->prot_sdb->table.nents = count;
1093         }
1094
1095         return BLK_STS_OK;
1096 out_free_sgtables:
1097         scsi_free_sgtables(cmd);
1098         return ret;
1099 }
1100 EXPORT_SYMBOL(scsi_alloc_sgtables);
1101
1102 /**
1103  * scsi_initialize_rq - initialize struct scsi_cmnd partially
1104  * @rq: Request associated with the SCSI command to be initialized.
1105  *
1106  * This function initializes the members of struct scsi_cmnd that must be
1107  * initialized before request processing starts and that won't be
1108  * reinitialized if a SCSI command is requeued.
1109  *
1110  * Called from inside blk_get_request() for pass-through requests and from
1111  * inside scsi_init_command() for filesystem requests.
1112  */
1113 static void scsi_initialize_rq(struct request *rq)
1114 {
1115         struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
1116
1117         scsi_req_init(&cmd->req);
1118         init_rcu_head(&cmd->rcu);
1119         cmd->jiffies_at_alloc = jiffies;
1120         cmd->retries = 0;
1121 }
1122
1123 /*
1124  * Only called when the request isn't completed by SCSI, and not freed by
1125  * SCSI
1126  */
1127 static void scsi_cleanup_rq(struct request *rq)
1128 {
1129         if (rq->rq_flags & RQF_DONTPREP) {
1130                 scsi_mq_uninit_cmd(blk_mq_rq_to_pdu(rq));
1131                 rq->rq_flags &= ~RQF_DONTPREP;
1132         }
1133 }
1134
1135 /* Called before a request is prepared. See also scsi_mq_prep_fn(). */
1136 void scsi_init_command(struct scsi_device *dev, struct scsi_cmnd *cmd)
1137 {
1138         void *buf = cmd->sense_buffer;
1139         void *prot = cmd->prot_sdb;
1140         struct request *rq = blk_mq_rq_from_pdu(cmd);
1141         unsigned int flags = cmd->flags & SCMD_PRESERVED_FLAGS;
1142         unsigned long jiffies_at_alloc;
1143         int retries, to_clear;
1144         bool in_flight;
1145
1146         if (!blk_rq_is_scsi(rq) && !(flags & SCMD_INITIALIZED)) {
1147                 flags |= SCMD_INITIALIZED;
1148                 scsi_initialize_rq(rq);
1149         }
1150
1151         jiffies_at_alloc = cmd->jiffies_at_alloc;
1152         retries = cmd->retries;
1153         in_flight = test_bit(SCMD_STATE_INFLIGHT, &cmd->state);
1154         /*
1155          * Zero out the cmd, except for the embedded scsi_request. Only clear
1156          * the driver-private command data if the LLD does not supply a
1157          * function to initialize that data.
1158          */
1159         to_clear = sizeof(*cmd) - sizeof(cmd->req);
1160         if (!dev->host->hostt->init_cmd_priv)
1161                 to_clear += dev->host->hostt->cmd_size;
1162         memset((char *)cmd + sizeof(cmd->req), 0, to_clear);
1163
1164         cmd->device = dev;
1165         cmd->sense_buffer = buf;
1166         cmd->prot_sdb = prot;
1167         cmd->flags = flags;
1168         INIT_DELAYED_WORK(&cmd->abort_work, scmd_eh_abort_handler);
1169         cmd->jiffies_at_alloc = jiffies_at_alloc;
1170         cmd->retries = retries;
1171         if (in_flight)
1172                 __set_bit(SCMD_STATE_INFLIGHT, &cmd->state);
1173
1174 }
1175
1176 static blk_status_t scsi_setup_scsi_cmnd(struct scsi_device *sdev,
1177                 struct request *req)
1178 {
1179         struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
1180
1181         /*
1182          * Passthrough requests may transfer data, in which case they must
1183          * a bio attached to them.  Or they might contain a SCSI command
1184          * that does not transfer data, in which case they may optionally
1185          * submit a request without an attached bio.
1186          */
1187         if (req->bio) {
1188                 blk_status_t ret = scsi_alloc_sgtables(cmd);
1189                 if (unlikely(ret != BLK_STS_OK))
1190                         return ret;
1191         } else {
1192                 BUG_ON(blk_rq_bytes(req));
1193
1194                 memset(&cmd->sdb, 0, sizeof(cmd->sdb));
1195         }
1196
1197         cmd->cmd_len = scsi_req(req)->cmd_len;
1198         cmd->cmnd = scsi_req(req)->cmd;
1199         cmd->transfersize = blk_rq_bytes(req);
1200         cmd->allowed = scsi_req(req)->retries;
1201         return BLK_STS_OK;
1202 }
1203
1204 static blk_status_t
1205 scsi_device_state_check(struct scsi_device *sdev, struct request *req)
1206 {
1207         switch (sdev->sdev_state) {
1208         case SDEV_CREATED:
1209                 return BLK_STS_OK;
1210         case SDEV_OFFLINE:
1211         case SDEV_TRANSPORT_OFFLINE:
1212                 /*
1213                  * If the device is offline we refuse to process any
1214                  * commands.  The device must be brought online
1215                  * before trying any recovery commands.
1216                  */
1217                 if (!sdev->offline_already) {
1218                         sdev->offline_already = true;
1219                         sdev_printk(KERN_ERR, sdev,
1220                                     "rejecting I/O to offline device\n");
1221                 }
1222                 return BLK_STS_IOERR;
1223         case SDEV_DEL:
1224                 /*
1225                  * If the device is fully deleted, we refuse to
1226                  * process any commands as well.
1227                  */
1228                 sdev_printk(KERN_ERR, sdev,
1229                             "rejecting I/O to dead device\n");
1230                 return BLK_STS_IOERR;
1231         case SDEV_BLOCK:
1232         case SDEV_CREATED_BLOCK:
1233                 return BLK_STS_RESOURCE;
1234         case SDEV_QUIESCE:
1235                 /*
1236                  * If the device is blocked we only accept power management
1237                  * commands.
1238                  */
1239                 if (req && WARN_ON_ONCE(!(req->rq_flags & RQF_PM)))
1240                         return BLK_STS_RESOURCE;
1241                 return BLK_STS_OK;
1242         default:
1243                 /*
1244                  * For any other not fully online state we only allow
1245                  * power management commands.
1246                  */
1247                 if (req && !(req->rq_flags & RQF_PM))
1248                         return BLK_STS_IOERR;
1249                 return BLK_STS_OK;
1250         }
1251 }
1252
1253 /*
1254  * scsi_dev_queue_ready: if we can send requests to sdev, return 1 else
1255  * return 0.
1256  *
1257  * Called with the queue_lock held.
1258  */
1259 static inline int scsi_dev_queue_ready(struct request_queue *q,
1260                                   struct scsi_device *sdev)
1261 {
1262         unsigned int busy;
1263
1264         busy = atomic_inc_return(&sdev->device_busy) - 1;
1265         if (atomic_read(&sdev->device_blocked)) {
1266                 if (busy)
1267                         goto out_dec;
1268
1269                 /*
1270                  * unblock after device_blocked iterates to zero
1271                  */
1272                 if (atomic_dec_return(&sdev->device_blocked) > 0)
1273                         goto out_dec;
1274                 SCSI_LOG_MLQUEUE(3, sdev_printk(KERN_INFO, sdev,
1275                                    "unblocking device at zero depth\n"));
1276         }
1277
1278         if (busy >= sdev->queue_depth)
1279                 goto out_dec;
1280
1281         return 1;
1282 out_dec:
1283         atomic_dec(&sdev->device_busy);
1284         return 0;
1285 }
1286
1287 /*
1288  * scsi_target_queue_ready: checks if there we can send commands to target
1289  * @sdev: scsi device on starget to check.
1290  */
1291 static inline int scsi_target_queue_ready(struct Scsi_Host *shost,
1292                                            struct scsi_device *sdev)
1293 {
1294         struct scsi_target *starget = scsi_target(sdev);
1295         unsigned int busy;
1296
1297         if (starget->single_lun) {
1298                 spin_lock_irq(shost->host_lock);
1299                 if (starget->starget_sdev_user &&
1300                     starget->starget_sdev_user != sdev) {
1301                         spin_unlock_irq(shost->host_lock);
1302                         return 0;
1303                 }
1304                 starget->starget_sdev_user = sdev;
1305                 spin_unlock_irq(shost->host_lock);
1306         }
1307
1308         if (starget->can_queue <= 0)
1309                 return 1;
1310
1311         busy = atomic_inc_return(&starget->target_busy) - 1;
1312         if (atomic_read(&starget->target_blocked) > 0) {
1313                 if (busy)
1314                         goto starved;
1315
1316                 /*
1317                  * unblock after target_blocked iterates to zero
1318                  */
1319                 if (atomic_dec_return(&starget->target_blocked) > 0)
1320                         goto out_dec;
1321
1322                 SCSI_LOG_MLQUEUE(3, starget_printk(KERN_INFO, starget,
1323                                  "unblocking target at zero depth\n"));
1324         }
1325
1326         if (busy >= starget->can_queue)
1327                 goto starved;
1328
1329         return 1;
1330
1331 starved:
1332         spin_lock_irq(shost->host_lock);
1333         list_move_tail(&sdev->starved_entry, &shost->starved_list);
1334         spin_unlock_irq(shost->host_lock);
1335 out_dec:
1336         if (starget->can_queue > 0)
1337                 atomic_dec(&starget->target_busy);
1338         return 0;
1339 }
1340
1341 /*
1342  * scsi_host_queue_ready: if we can send requests to shost, return 1 else
1343  * return 0. We must end up running the queue again whenever 0 is
1344  * returned, else IO can hang.
1345  */
1346 static inline int scsi_host_queue_ready(struct request_queue *q,
1347                                    struct Scsi_Host *shost,
1348                                    struct scsi_device *sdev,
1349                                    struct scsi_cmnd *cmd)
1350 {
1351         if (scsi_host_in_recovery(shost))
1352                 return 0;
1353
1354         if (atomic_read(&shost->host_blocked) > 0) {
1355                 if (scsi_host_busy(shost) > 0)
1356                         goto starved;
1357
1358                 /*
1359                  * unblock after host_blocked iterates to zero
1360                  */
1361                 if (atomic_dec_return(&shost->host_blocked) > 0)
1362                         goto out_dec;
1363
1364                 SCSI_LOG_MLQUEUE(3,
1365                         shost_printk(KERN_INFO, shost,
1366                                      "unblocking host at zero depth\n"));
1367         }
1368
1369         if (shost->host_self_blocked)
1370                 goto starved;
1371
1372         /* We're OK to process the command, so we can't be starved */
1373         if (!list_empty(&sdev->starved_entry)) {
1374                 spin_lock_irq(shost->host_lock);
1375                 if (!list_empty(&sdev->starved_entry))
1376                         list_del_init(&sdev->starved_entry);
1377                 spin_unlock_irq(shost->host_lock);
1378         }
1379
1380         __set_bit(SCMD_STATE_INFLIGHT, &cmd->state);
1381
1382         return 1;
1383
1384 starved:
1385         spin_lock_irq(shost->host_lock);
1386         if (list_empty(&sdev->starved_entry))
1387                 list_add_tail(&sdev->starved_entry, &shost->starved_list);
1388         spin_unlock_irq(shost->host_lock);
1389 out_dec:
1390         scsi_dec_host_busy(shost, cmd);
1391         return 0;
1392 }
1393
1394 /*
1395  * Busy state exporting function for request stacking drivers.
1396  *
1397  * For efficiency, no lock is taken to check the busy state of
1398  * shost/starget/sdev, since the returned value is not guaranteed and
1399  * may be changed after request stacking drivers call the function,
1400  * regardless of taking lock or not.
1401  *
1402  * When scsi can't dispatch I/Os anymore and needs to kill I/Os scsi
1403  * needs to return 'not busy'. Otherwise, request stacking drivers
1404  * may hold requests forever.
1405  */
1406 static bool scsi_mq_lld_busy(struct request_queue *q)
1407 {
1408         struct scsi_device *sdev = q->queuedata;
1409         struct Scsi_Host *shost;
1410
1411         if (blk_queue_dying(q))
1412                 return false;
1413
1414         shost = sdev->host;
1415
1416         /*
1417          * Ignore host/starget busy state.
1418          * Since block layer does not have a concept of fairness across
1419          * multiple queues, congestion of host/starget needs to be handled
1420          * in SCSI layer.
1421          */
1422         if (scsi_host_in_recovery(shost) || scsi_device_is_busy(sdev))
1423                 return true;
1424
1425         return false;
1426 }
1427
1428 static void scsi_softirq_done(struct request *rq)
1429 {
1430         struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
1431         enum scsi_disposition disposition;
1432
1433         INIT_LIST_HEAD(&cmd->eh_entry);
1434
1435         atomic_inc(&cmd->device->iodone_cnt);
1436         if (cmd->result)
1437                 atomic_inc(&cmd->device->ioerr_cnt);
1438
1439         disposition = scsi_decide_disposition(cmd);
1440         if (disposition != SUCCESS && scsi_cmd_runtime_exceeced(cmd))
1441                 disposition = SUCCESS;
1442
1443         scsi_log_completion(cmd, disposition);
1444
1445         switch (disposition) {
1446         case SUCCESS:
1447                 scsi_finish_command(cmd);
1448                 break;
1449         case NEEDS_RETRY:
1450                 scsi_queue_insert(cmd, SCSI_MLQUEUE_EH_RETRY);
1451                 break;
1452         case ADD_TO_MLQUEUE:
1453                 scsi_queue_insert(cmd, SCSI_MLQUEUE_DEVICE_BUSY);
1454                 break;
1455         default:
1456                 scsi_eh_scmd_add(cmd);
1457                 break;
1458         }
1459 }
1460
1461 /**
1462  * scsi_dispatch_command - Dispatch a command to the low-level driver.
1463  * @cmd: command block we are dispatching.
1464  *
1465  * Return: nonzero return request was rejected and device's queue needs to be
1466  * plugged.
1467  */
1468 static int scsi_dispatch_cmd(struct scsi_cmnd *cmd)
1469 {
1470         struct Scsi_Host *host = cmd->device->host;
1471         int rtn = 0;
1472
1473         atomic_inc(&cmd->device->iorequest_cnt);
1474
1475         /* check if the device is still usable */
1476         if (unlikely(cmd->device->sdev_state == SDEV_DEL)) {
1477                 /* in SDEV_DEL we error all commands. DID_NO_CONNECT
1478                  * returns an immediate error upwards, and signals
1479                  * that the device is no longer present */
1480                 cmd->result = DID_NO_CONNECT << 16;
1481                 goto done;
1482         }
1483
1484         /* Check to see if the scsi lld made this device blocked. */
1485         if (unlikely(scsi_device_blocked(cmd->device))) {
1486                 /*
1487                  * in blocked state, the command is just put back on
1488                  * the device queue.  The suspend state has already
1489                  * blocked the queue so future requests should not
1490                  * occur until the device transitions out of the
1491                  * suspend state.
1492                  */
1493                 SCSI_LOG_MLQUEUE(3, scmd_printk(KERN_INFO, cmd,
1494                         "queuecommand : device blocked\n"));
1495                 atomic_dec(&cmd->device->iorequest_cnt);
1496                 return SCSI_MLQUEUE_DEVICE_BUSY;
1497         }
1498
1499         /* Store the LUN value in cmnd, if needed. */
1500         if (cmd->device->lun_in_cdb)
1501                 cmd->cmnd[1] = (cmd->cmnd[1] & 0x1f) |
1502                                (cmd->device->lun << 5 & 0xe0);
1503
1504         scsi_log_send(cmd);
1505
1506         /*
1507          * Before we queue this command, check if the command
1508          * length exceeds what the host adapter can handle.
1509          */
1510         if (cmd->cmd_len > cmd->device->host->max_cmd_len) {
1511                 SCSI_LOG_MLQUEUE(3, scmd_printk(KERN_INFO, cmd,
1512                                "queuecommand : command too long. "
1513                                "cdb_size=%d host->max_cmd_len=%d\n",
1514                                cmd->cmd_len, cmd->device->host->max_cmd_len));
1515                 cmd->result = (DID_ABORT << 16);
1516                 goto done;
1517         }
1518
1519         if (unlikely(host->shost_state == SHOST_DEL)) {
1520                 cmd->result = (DID_NO_CONNECT << 16);
1521                 goto done;
1522
1523         }
1524
1525         trace_scsi_dispatch_cmd_start(cmd);
1526         rtn = host->hostt->queuecommand(host, cmd);
1527         if (rtn) {
1528                 atomic_dec(&cmd->device->iorequest_cnt);
1529                 trace_scsi_dispatch_cmd_error(cmd, rtn);
1530                 if (rtn != SCSI_MLQUEUE_DEVICE_BUSY &&
1531                     rtn != SCSI_MLQUEUE_TARGET_BUSY)
1532                         rtn = SCSI_MLQUEUE_HOST_BUSY;
1533
1534                 SCSI_LOG_MLQUEUE(3, scmd_printk(KERN_INFO, cmd,
1535                         "queuecommand : request rejected\n"));
1536         }
1537
1538         return rtn;
1539  done:
1540         cmd->scsi_done(cmd);
1541         return 0;
1542 }
1543
1544 /* Size in bytes of the sg-list stored in the scsi-mq command-private data. */
1545 static unsigned int scsi_mq_inline_sgl_size(struct Scsi_Host *shost)
1546 {
1547         return min_t(unsigned int, shost->sg_tablesize, SCSI_INLINE_SG_CNT) *
1548                 sizeof(struct scatterlist);
1549 }
1550
1551 static blk_status_t scsi_prepare_cmd(struct request *req)
1552 {
1553         struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
1554         struct scsi_device *sdev = req->q->queuedata;
1555         struct Scsi_Host *shost = sdev->host;
1556         struct scatterlist *sg;
1557
1558         scsi_init_command(sdev, cmd);
1559
1560         cmd->request = req;
1561         cmd->tag = req->tag;
1562         cmd->prot_op = SCSI_PROT_NORMAL;
1563         if (blk_rq_bytes(req))
1564                 cmd->sc_data_direction = rq_dma_dir(req);
1565         else
1566                 cmd->sc_data_direction = DMA_NONE;
1567
1568         sg = (void *)cmd + sizeof(struct scsi_cmnd) + shost->hostt->cmd_size;
1569         cmd->sdb.table.sgl = sg;
1570
1571         if (scsi_host_get_prot(shost)) {
1572                 memset(cmd->prot_sdb, 0, sizeof(struct scsi_data_buffer));
1573
1574                 cmd->prot_sdb->table.sgl =
1575                         (struct scatterlist *)(cmd->prot_sdb + 1);
1576         }
1577
1578         /*
1579          * Special handling for passthrough commands, which don't go to the ULP
1580          * at all:
1581          */
1582         if (blk_rq_is_scsi(req))
1583                 return scsi_setup_scsi_cmnd(sdev, req);
1584
1585         if (sdev->handler && sdev->handler->prep_fn) {
1586                 blk_status_t ret = sdev->handler->prep_fn(sdev, req);
1587
1588                 if (ret != BLK_STS_OK)
1589                         return ret;
1590         }
1591
1592         cmd->cmnd = scsi_req(req)->cmd = scsi_req(req)->__cmd;
1593         memset(cmd->cmnd, 0, BLK_MAX_CDB);
1594         return scsi_cmd_to_driver(cmd)->init_command(cmd);
1595 }
1596
1597 static void scsi_mq_done(struct scsi_cmnd *cmd)
1598 {
1599         if (unlikely(blk_should_fake_timeout(cmd->request->q)))
1600                 return;
1601         if (unlikely(test_and_set_bit(SCMD_STATE_COMPLETE, &cmd->state)))
1602                 return;
1603         trace_scsi_dispatch_cmd_done(cmd);
1604         blk_mq_complete_request(cmd->request);
1605 }
1606
1607 static void scsi_mq_put_budget(struct request_queue *q)
1608 {
1609         struct scsi_device *sdev = q->queuedata;
1610
1611         atomic_dec(&sdev->device_busy);
1612 }
1613
1614 static bool scsi_mq_get_budget(struct request_queue *q)
1615 {
1616         struct scsi_device *sdev = q->queuedata;
1617
1618         if (scsi_dev_queue_ready(q, sdev))
1619                 return true;
1620
1621         atomic_inc(&sdev->restarts);
1622
1623         /*
1624          * Orders atomic_inc(&sdev->restarts) and atomic_read(&sdev->device_busy).
1625          * .restarts must be incremented before .device_busy is read because the
1626          * code in scsi_run_queue_async() depends on the order of these operations.
1627          */
1628         smp_mb__after_atomic();
1629
1630         /*
1631          * If all in-flight requests originated from this LUN are completed
1632          * before reading .device_busy, sdev->device_busy will be observed as
1633          * zero, then blk_mq_delay_run_hw_queues() will dispatch this request
1634          * soon. Otherwise, completion of one of these requests will observe
1635          * the .restarts flag, and the request queue will be run for handling
1636          * this request, see scsi_end_request().
1637          */
1638         if (unlikely(atomic_read(&sdev->device_busy) == 0 &&
1639                                 !scsi_device_blocked(sdev)))
1640                 blk_mq_delay_run_hw_queues(sdev->request_queue, SCSI_QUEUE_DELAY);
1641         return false;
1642 }
1643
1644 static blk_status_t scsi_queue_rq(struct blk_mq_hw_ctx *hctx,
1645                          const struct blk_mq_queue_data *bd)
1646 {
1647         struct request *req = bd->rq;
1648         struct request_queue *q = req->q;
1649         struct scsi_device *sdev = q->queuedata;
1650         struct Scsi_Host *shost = sdev->host;
1651         struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
1652         blk_status_t ret;
1653         int reason;
1654
1655         /*
1656          * If the device is not in running state we will reject some or all
1657          * commands.
1658          */
1659         if (unlikely(sdev->sdev_state != SDEV_RUNNING)) {
1660                 ret = scsi_device_state_check(sdev, req);
1661                 if (ret != BLK_STS_OK)
1662                         goto out_put_budget;
1663         }
1664
1665         ret = BLK_STS_RESOURCE;
1666         if (!scsi_target_queue_ready(shost, sdev))
1667                 goto out_put_budget;
1668         if (!scsi_host_queue_ready(q, shost, sdev, cmd))
1669                 goto out_dec_target_busy;
1670
1671         if (!(req->rq_flags & RQF_DONTPREP)) {
1672                 ret = scsi_prepare_cmd(req);
1673                 if (ret != BLK_STS_OK)
1674                         goto out_dec_host_busy;
1675                 req->rq_flags |= RQF_DONTPREP;
1676         } else {
1677                 clear_bit(SCMD_STATE_COMPLETE, &cmd->state);
1678         }
1679
1680         cmd->flags &= SCMD_PRESERVED_FLAGS;
1681         if (sdev->simple_tags)
1682                 cmd->flags |= SCMD_TAGGED;
1683         if (bd->last)
1684                 cmd->flags |= SCMD_LAST;
1685
1686         scsi_set_resid(cmd, 0);
1687         memset(cmd->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE);
1688         cmd->scsi_done = scsi_mq_done;
1689
1690         blk_mq_start_request(req);
1691         reason = scsi_dispatch_cmd(cmd);
1692         if (reason) {
1693                 scsi_set_blocked(cmd, reason);
1694                 ret = BLK_STS_RESOURCE;
1695                 goto out_dec_host_busy;
1696         }
1697
1698         return BLK_STS_OK;
1699
1700 out_dec_host_busy:
1701         scsi_dec_host_busy(shost, cmd);
1702 out_dec_target_busy:
1703         if (scsi_target(sdev)->can_queue > 0)
1704                 atomic_dec(&scsi_target(sdev)->target_busy);
1705 out_put_budget:
1706         scsi_mq_put_budget(q);
1707         switch (ret) {
1708         case BLK_STS_OK:
1709                 break;
1710         case BLK_STS_RESOURCE:
1711         case BLK_STS_ZONE_RESOURCE:
1712                 if (scsi_device_blocked(sdev))
1713                         ret = BLK_STS_DEV_RESOURCE;
1714                 break;
1715         default:
1716                 if (unlikely(!scsi_device_online(sdev)))
1717                         scsi_req(req)->result = DID_NO_CONNECT << 16;
1718                 else
1719                         scsi_req(req)->result = DID_ERROR << 16;
1720                 /*
1721                  * Make sure to release all allocated resources when
1722                  * we hit an error, as we will never see this command
1723                  * again.
1724                  */
1725                 if (req->rq_flags & RQF_DONTPREP)
1726                         scsi_mq_uninit_cmd(cmd);
1727                 scsi_run_queue_async(sdev);
1728                 break;
1729         }
1730         return ret;
1731 }
1732
1733 static enum blk_eh_timer_return scsi_timeout(struct request *req,
1734                 bool reserved)
1735 {
1736         if (reserved)
1737                 return BLK_EH_RESET_TIMER;
1738         return scsi_times_out(req);
1739 }
1740
1741 static int scsi_mq_init_request(struct blk_mq_tag_set *set, struct request *rq,
1742                                 unsigned int hctx_idx, unsigned int numa_node)
1743 {
1744         struct Scsi_Host *shost = set->driver_data;
1745         const bool unchecked_isa_dma = shost->unchecked_isa_dma;
1746         struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
1747         struct scatterlist *sg;
1748         int ret = 0;
1749
1750         if (unchecked_isa_dma)
1751                 cmd->flags |= SCMD_UNCHECKED_ISA_DMA;
1752         cmd->sense_buffer = scsi_alloc_sense_buffer(unchecked_isa_dma,
1753                                                     GFP_KERNEL, numa_node);
1754         if (!cmd->sense_buffer)
1755                 return -ENOMEM;
1756         cmd->req.sense = cmd->sense_buffer;
1757
1758         if (scsi_host_get_prot(shost)) {
1759                 sg = (void *)cmd + sizeof(struct scsi_cmnd) +
1760                         shost->hostt->cmd_size;
1761                 cmd->prot_sdb = (void *)sg + scsi_mq_inline_sgl_size(shost);
1762         }
1763
1764         if (shost->hostt->init_cmd_priv) {
1765                 ret = shost->hostt->init_cmd_priv(shost, cmd);
1766                 if (ret < 0)
1767                         scsi_free_sense_buffer(unchecked_isa_dma,
1768                                                cmd->sense_buffer);
1769         }
1770
1771         return ret;
1772 }
1773
1774 static void scsi_mq_exit_request(struct blk_mq_tag_set *set, struct request *rq,
1775                                  unsigned int hctx_idx)
1776 {
1777         struct Scsi_Host *shost = set->driver_data;
1778         struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
1779
1780         if (shost->hostt->exit_cmd_priv)
1781                 shost->hostt->exit_cmd_priv(shost, cmd);
1782         scsi_free_sense_buffer(cmd->flags & SCMD_UNCHECKED_ISA_DMA,
1783                                cmd->sense_buffer);
1784 }
1785
1786 static int scsi_map_queues(struct blk_mq_tag_set *set)
1787 {
1788         struct Scsi_Host *shost = container_of(set, struct Scsi_Host, tag_set);
1789
1790         if (shost->hostt->map_queues)
1791                 return shost->hostt->map_queues(shost);
1792         return blk_mq_map_queues(&set->map[HCTX_TYPE_DEFAULT]);
1793 }
1794
1795 void __scsi_init_queue(struct Scsi_Host *shost, struct request_queue *q)
1796 {
1797         struct device *dev = shost->dma_dev;
1798
1799         /*
1800          * this limit is imposed by hardware restrictions
1801          */
1802         blk_queue_max_segments(q, min_t(unsigned short, shost->sg_tablesize,
1803                                         SG_MAX_SEGMENTS));
1804
1805         if (scsi_host_prot_dma(shost)) {
1806                 shost->sg_prot_tablesize =
1807                         min_not_zero(shost->sg_prot_tablesize,
1808                                      (unsigned short)SCSI_MAX_PROT_SG_SEGMENTS);
1809                 BUG_ON(shost->sg_prot_tablesize < shost->sg_tablesize);
1810                 blk_queue_max_integrity_segments(q, shost->sg_prot_tablesize);
1811         }
1812
1813         if (dev->dma_mask) {
1814                 shost->max_sectors = min_t(unsigned int, shost->max_sectors,
1815                                 dma_max_mapping_size(dev) >> SECTOR_SHIFT);
1816         }
1817         blk_queue_max_hw_sectors(q, shost->max_sectors);
1818         if (shost->unchecked_isa_dma)
1819                 blk_queue_bounce_limit(q, BLK_BOUNCE_ISA);
1820         blk_queue_segment_boundary(q, shost->dma_boundary);
1821         dma_set_seg_boundary(dev, shost->dma_boundary);
1822
1823         blk_queue_max_segment_size(q, shost->max_segment_size);
1824         blk_queue_virt_boundary(q, shost->virt_boundary_mask);
1825         dma_set_max_seg_size(dev, queue_max_segment_size(q));
1826
1827         /*
1828          * Set a reasonable default alignment:  The larger of 32-byte (dword),
1829          * which is a common minimum for HBAs, and the minimum DMA alignment,
1830          * which is set by the platform.
1831          *
1832          * Devices that require a bigger alignment can increase it later.
1833          */
1834         blk_queue_dma_alignment(q, max(4, dma_get_cache_alignment()) - 1);
1835 }
1836 EXPORT_SYMBOL_GPL(__scsi_init_queue);
1837
1838 static const struct blk_mq_ops scsi_mq_ops_no_commit = {
1839         .get_budget     = scsi_mq_get_budget,
1840         .put_budget     = scsi_mq_put_budget,
1841         .queue_rq       = scsi_queue_rq,
1842         .complete       = scsi_softirq_done,
1843         .timeout        = scsi_timeout,
1844 #ifdef CONFIG_BLK_DEBUG_FS
1845         .show_rq        = scsi_show_rq,
1846 #endif
1847         .init_request   = scsi_mq_init_request,
1848         .exit_request   = scsi_mq_exit_request,
1849         .initialize_rq_fn = scsi_initialize_rq,
1850         .cleanup_rq     = scsi_cleanup_rq,
1851         .busy           = scsi_mq_lld_busy,
1852         .map_queues     = scsi_map_queues,
1853 };
1854
1855
1856 static void scsi_commit_rqs(struct blk_mq_hw_ctx *hctx)
1857 {
1858         struct request_queue *q = hctx->queue;
1859         struct scsi_device *sdev = q->queuedata;
1860         struct Scsi_Host *shost = sdev->host;
1861
1862         shost->hostt->commit_rqs(shost, hctx->queue_num);
1863 }
1864
1865 static const struct blk_mq_ops scsi_mq_ops = {
1866         .get_budget     = scsi_mq_get_budget,
1867         .put_budget     = scsi_mq_put_budget,
1868         .queue_rq       = scsi_queue_rq,
1869         .commit_rqs     = scsi_commit_rqs,
1870         .complete       = scsi_softirq_done,
1871         .timeout        = scsi_timeout,
1872 #ifdef CONFIG_BLK_DEBUG_FS
1873         .show_rq        = scsi_show_rq,
1874 #endif
1875         .init_request   = scsi_mq_init_request,
1876         .exit_request   = scsi_mq_exit_request,
1877         .initialize_rq_fn = scsi_initialize_rq,
1878         .cleanup_rq     = scsi_cleanup_rq,
1879         .busy           = scsi_mq_lld_busy,
1880         .map_queues     = scsi_map_queues,
1881 };
1882
1883 struct request_queue *scsi_mq_alloc_queue(struct scsi_device *sdev)
1884 {
1885         sdev->request_queue = blk_mq_init_queue(&sdev->host->tag_set);
1886         if (IS_ERR(sdev->request_queue))
1887                 return NULL;
1888
1889         sdev->request_queue->queuedata = sdev;
1890         __scsi_init_queue(sdev->host, sdev->request_queue);
1891         blk_queue_flag_set(QUEUE_FLAG_SCSI_PASSTHROUGH, sdev->request_queue);
1892         return sdev->request_queue;
1893 }
1894
1895 int scsi_mq_setup_tags(struct Scsi_Host *shost)
1896 {
1897         unsigned int cmd_size, sgl_size;
1898         struct blk_mq_tag_set *tag_set = &shost->tag_set;
1899
1900         sgl_size = max_t(unsigned int, sizeof(struct scatterlist),
1901                                 scsi_mq_inline_sgl_size(shost));
1902         cmd_size = sizeof(struct scsi_cmnd) + shost->hostt->cmd_size + sgl_size;
1903         if (scsi_host_get_prot(shost))
1904                 cmd_size += sizeof(struct scsi_data_buffer) +
1905                         sizeof(struct scatterlist) * SCSI_INLINE_PROT_SG_CNT;
1906
1907         memset(tag_set, 0, sizeof(*tag_set));
1908         if (shost->hostt->commit_rqs)
1909                 tag_set->ops = &scsi_mq_ops;
1910         else
1911                 tag_set->ops = &scsi_mq_ops_no_commit;
1912         tag_set->nr_hw_queues = shost->nr_hw_queues ? : 1;
1913         tag_set->queue_depth = shost->can_queue;
1914         tag_set->cmd_size = cmd_size;
1915         tag_set->numa_node = NUMA_NO_NODE;
1916         tag_set->flags = BLK_MQ_F_SHOULD_MERGE;
1917         tag_set->flags |=
1918                 BLK_ALLOC_POLICY_TO_MQ_FLAG(shost->hostt->tag_alloc_policy);
1919         tag_set->driver_data = shost;
1920         if (shost->host_tagset)
1921                 tag_set->flags |= BLK_MQ_F_TAG_HCTX_SHARED;
1922
1923         return blk_mq_alloc_tag_set(tag_set);
1924 }
1925
1926 void scsi_mq_destroy_tags(struct Scsi_Host *shost)
1927 {
1928         blk_mq_free_tag_set(&shost->tag_set);
1929 }
1930
1931 /**
1932  * scsi_device_from_queue - return sdev associated with a request_queue
1933  * @q: The request queue to return the sdev from
1934  *
1935  * Return the sdev associated with a request queue or NULL if the
1936  * request_queue does not reference a SCSI device.
1937  */
1938 struct scsi_device *scsi_device_from_queue(struct request_queue *q)
1939 {
1940         struct scsi_device *sdev = NULL;
1941
1942         if (q->mq_ops == &scsi_mq_ops_no_commit ||
1943             q->mq_ops == &scsi_mq_ops)
1944                 sdev = q->queuedata;
1945         if (!sdev || !get_device(&sdev->sdev_gendev))
1946                 sdev = NULL;
1947
1948         return sdev;
1949 }
1950
1951 /**
1952  * scsi_block_requests - Utility function used by low-level drivers to prevent
1953  * further commands from being queued to the device.
1954  * @shost:  host in question
1955  *
1956  * There is no timer nor any other means by which the requests get unblocked
1957  * other than the low-level driver calling scsi_unblock_requests().
1958  */
1959 void scsi_block_requests(struct Scsi_Host *shost)
1960 {
1961         shost->host_self_blocked = 1;
1962 }
1963 EXPORT_SYMBOL(scsi_block_requests);
1964
1965 /**
1966  * scsi_unblock_requests - Utility function used by low-level drivers to allow
1967  * further commands to be queued to the device.
1968  * @shost:  host in question
1969  *
1970  * There is no timer nor any other means by which the requests get unblocked
1971  * other than the low-level driver calling scsi_unblock_requests(). This is done
1972  * as an API function so that changes to the internals of the scsi mid-layer
1973  * won't require wholesale changes to drivers that use this feature.
1974  */
1975 void scsi_unblock_requests(struct Scsi_Host *shost)
1976 {
1977         shost->host_self_blocked = 0;
1978         scsi_run_host_queues(shost);
1979 }
1980 EXPORT_SYMBOL(scsi_unblock_requests);
1981
1982 void scsi_exit_queue(void)
1983 {
1984         kmem_cache_destroy(scsi_sense_cache);
1985         kmem_cache_destroy(scsi_sense_isadma_cache);
1986 }
1987
1988 /**
1989  *      scsi_mode_select - issue a mode select
1990  *      @sdev:  SCSI device to be queried
1991  *      @pf:    Page format bit (1 == standard, 0 == vendor specific)
1992  *      @sp:    Save page bit (0 == don't save, 1 == save)
1993  *      @modepage: mode page being requested
1994  *      @buffer: request buffer (may not be smaller than eight bytes)
1995  *      @len:   length of request buffer.
1996  *      @timeout: command timeout
1997  *      @retries: number of retries before failing
1998  *      @data: returns a structure abstracting the mode header data
1999  *      @sshdr: place to put sense data (or NULL if no sense to be collected).
2000  *              must be SCSI_SENSE_BUFFERSIZE big.
2001  *
2002  *      Returns zero if successful; negative error number or scsi
2003  *      status on error
2004  *
2005  */
2006 int
2007 scsi_mode_select(struct scsi_device *sdev, int pf, int sp, int modepage,
2008                  unsigned char *buffer, int len, int timeout, int retries,
2009                  struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr)
2010 {
2011         unsigned char cmd[10];
2012         unsigned char *real_buffer;
2013         int ret;
2014
2015         memset(cmd, 0, sizeof(cmd));
2016         cmd[1] = (pf ? 0x10 : 0) | (sp ? 0x01 : 0);
2017
2018         if (sdev->use_10_for_ms) {
2019                 if (len > 65535)
2020                         return -EINVAL;
2021                 real_buffer = kmalloc(8 + len, GFP_KERNEL);
2022                 if (!real_buffer)
2023                         return -ENOMEM;
2024                 memcpy(real_buffer + 8, buffer, len);
2025                 len += 8;
2026                 real_buffer[0] = 0;
2027                 real_buffer[1] = 0;
2028                 real_buffer[2] = data->medium_type;
2029                 real_buffer[3] = data->device_specific;
2030                 real_buffer[4] = data->longlba ? 0x01 : 0;
2031                 real_buffer[5] = 0;
2032                 real_buffer[6] = data->block_descriptor_length >> 8;
2033                 real_buffer[7] = data->block_descriptor_length;
2034
2035                 cmd[0] = MODE_SELECT_10;
2036                 cmd[7] = len >> 8;
2037                 cmd[8] = len;
2038         } else {
2039                 if (len > 255 || data->block_descriptor_length > 255 ||
2040                     data->longlba)
2041                         return -EINVAL;
2042
2043                 real_buffer = kmalloc(4 + len, GFP_KERNEL);
2044                 if (!real_buffer)
2045                         return -ENOMEM;
2046                 memcpy(real_buffer + 4, buffer, len);
2047                 len += 4;
2048                 real_buffer[0] = 0;
2049                 real_buffer[1] = data->medium_type;
2050                 real_buffer[2] = data->device_specific;
2051                 real_buffer[3] = data->block_descriptor_length;
2052
2053                 cmd[0] = MODE_SELECT;
2054                 cmd[4] = len;
2055         }
2056
2057         ret = scsi_execute_req(sdev, cmd, DMA_TO_DEVICE, real_buffer, len,
2058                                sshdr, timeout, retries, NULL);
2059         kfree(real_buffer);
2060         return ret;
2061 }
2062 EXPORT_SYMBOL_GPL(scsi_mode_select);
2063
2064 /**
2065  *      scsi_mode_sense - issue a mode sense, falling back from 10 to six bytes if necessary.
2066  *      @sdev:  SCSI device to be queried
2067  *      @dbd:   set if mode sense will allow block descriptors to be returned
2068  *      @modepage: mode page being requested
2069  *      @buffer: request buffer (may not be smaller than eight bytes)
2070  *      @len:   length of request buffer.
2071  *      @timeout: command timeout
2072  *      @retries: number of retries before failing
2073  *      @data: returns a structure abstracting the mode header data
2074  *      @sshdr: place to put sense data (or NULL if no sense to be collected).
2075  *              must be SCSI_SENSE_BUFFERSIZE big.
2076  *
2077  *      Returns zero if successful, or a negative error number on failure
2078  */
2079 int
2080 scsi_mode_sense(struct scsi_device *sdev, int dbd, int modepage,
2081                   unsigned char *buffer, int len, int timeout, int retries,
2082                   struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr)
2083 {
2084         unsigned char cmd[12];
2085         int use_10_for_ms;
2086         int header_length;
2087         int result, retry_count = retries;
2088         struct scsi_sense_hdr my_sshdr;
2089
2090         memset(data, 0, sizeof(*data));
2091         memset(&cmd[0], 0, 12);
2092
2093         dbd = sdev->set_dbd_for_ms ? 8 : dbd;
2094         cmd[1] = dbd & 0x18;    /* allows DBD and LLBA bits */
2095         cmd[2] = modepage;
2096
2097         /* caller might not be interested in sense, but we need it */
2098         if (!sshdr)
2099                 sshdr = &my_sshdr;
2100
2101  retry:
2102         use_10_for_ms = sdev->use_10_for_ms;
2103
2104         if (use_10_for_ms) {
2105                 if (len < 8)
2106                         len = 8;
2107
2108                 cmd[0] = MODE_SENSE_10;
2109                 cmd[8] = len;
2110                 header_length = 8;
2111         } else {
2112                 if (len < 4)
2113                         len = 4;
2114
2115                 cmd[0] = MODE_SENSE;
2116                 cmd[4] = len;
2117                 header_length = 4;
2118         }
2119
2120         memset(buffer, 0, len);
2121
2122         result = scsi_execute_req(sdev, cmd, DMA_FROM_DEVICE, buffer, len,
2123                                   sshdr, timeout, retries, NULL);
2124         if (result < 0)
2125                 return result;
2126
2127         /* This code looks awful: what it's doing is making sure an
2128          * ILLEGAL REQUEST sense return identifies the actual command
2129          * byte as the problem.  MODE_SENSE commands can return
2130          * ILLEGAL REQUEST if the code page isn't supported */
2131
2132         if (use_10_for_ms && !scsi_status_is_good(result) &&
2133             driver_byte(result) == DRIVER_SENSE) {
2134                 if (scsi_sense_valid(sshdr)) {
2135                         if ((sshdr->sense_key == ILLEGAL_REQUEST) &&
2136                             (sshdr->asc == 0x20) && (sshdr->ascq == 0)) {
2137                                 /*
2138                                  * Invalid command operation code
2139                                  */
2140                                 sdev->use_10_for_ms = 0;
2141                                 goto retry;
2142                         }
2143                 }
2144         }
2145
2146         if (scsi_status_is_good(result)) {
2147                 if (unlikely(buffer[0] == 0x86 && buffer[1] == 0x0b &&
2148                              (modepage == 6 || modepage == 8))) {
2149                         /* Initio breakage? */
2150                         header_length = 0;
2151                         data->length = 13;
2152                         data->medium_type = 0;
2153                         data->device_specific = 0;
2154                         data->longlba = 0;
2155                         data->block_descriptor_length = 0;
2156                 } else if (use_10_for_ms) {
2157                         data->length = buffer[0]*256 + buffer[1] + 2;
2158                         data->medium_type = buffer[2];
2159                         data->device_specific = buffer[3];
2160                         data->longlba = buffer[4] & 0x01;
2161                         data->block_descriptor_length = buffer[6]*256
2162                                 + buffer[7];
2163                 } else {
2164                         data->length = buffer[0] + 1;
2165                         data->medium_type = buffer[1];
2166                         data->device_specific = buffer[2];
2167                         data->block_descriptor_length = buffer[3];
2168                 }
2169                 data->header_length = header_length;
2170                 result = 0;
2171         } else if ((status_byte(result) == CHECK_CONDITION) &&
2172                    scsi_sense_valid(sshdr) &&
2173                    sshdr->sense_key == UNIT_ATTENTION && retry_count) {
2174                 retry_count--;
2175                 goto retry;
2176         }
2177         if (result > 0)
2178                 result = -EIO;
2179         return result;
2180 }
2181 EXPORT_SYMBOL(scsi_mode_sense);
2182
2183 /**
2184  *      scsi_test_unit_ready - test if unit is ready
2185  *      @sdev:  scsi device to change the state of.
2186  *      @timeout: command timeout
2187  *      @retries: number of retries before failing
2188  *      @sshdr: outpout pointer for decoded sense information.
2189  *
2190  *      Returns zero if unsuccessful or an error if TUR failed.  For
2191  *      removable media, UNIT_ATTENTION sets ->changed flag.
2192  **/
2193 int
2194 scsi_test_unit_ready(struct scsi_device *sdev, int timeout, int retries,
2195                      struct scsi_sense_hdr *sshdr)
2196 {
2197         char cmd[] = {
2198                 TEST_UNIT_READY, 0, 0, 0, 0, 0,
2199         };
2200         int result;
2201
2202         /* try to eat the UNIT_ATTENTION if there are enough retries */
2203         do {
2204                 result = scsi_execute_req(sdev, cmd, DMA_NONE, NULL, 0, sshdr,
2205                                           timeout, 1, NULL);
2206                 if (sdev->removable && scsi_sense_valid(sshdr) &&
2207                     sshdr->sense_key == UNIT_ATTENTION)
2208                         sdev->changed = 1;
2209         } while (scsi_sense_valid(sshdr) &&
2210                  sshdr->sense_key == UNIT_ATTENTION && --retries);
2211
2212         return result;
2213 }
2214 EXPORT_SYMBOL(scsi_test_unit_ready);
2215
2216 /**
2217  *      scsi_device_set_state - Take the given device through the device state model.
2218  *      @sdev:  scsi device to change the state of.
2219  *      @state: state to change to.
2220  *
2221  *      Returns zero if successful or an error if the requested
2222  *      transition is illegal.
2223  */
2224 int
2225 scsi_device_set_state(struct scsi_device *sdev, enum scsi_device_state state)
2226 {
2227         enum scsi_device_state oldstate = sdev->sdev_state;
2228
2229         if (state == oldstate)
2230                 return 0;
2231
2232         switch (state) {
2233         case SDEV_CREATED:
2234                 switch (oldstate) {
2235                 case SDEV_CREATED_BLOCK:
2236                         break;
2237                 default:
2238                         goto illegal;
2239                 }
2240                 break;
2241
2242         case SDEV_RUNNING:
2243                 switch (oldstate) {
2244                 case SDEV_CREATED:
2245                 case SDEV_OFFLINE:
2246                 case SDEV_TRANSPORT_OFFLINE:
2247                 case SDEV_QUIESCE:
2248                 case SDEV_BLOCK:
2249                         break;
2250                 default:
2251                         goto illegal;
2252                 }
2253                 break;
2254
2255         case SDEV_QUIESCE:
2256                 switch (oldstate) {
2257                 case SDEV_RUNNING:
2258                 case SDEV_OFFLINE:
2259                 case SDEV_TRANSPORT_OFFLINE:
2260                         break;
2261                 default:
2262                         goto illegal;
2263                 }
2264                 break;
2265
2266         case SDEV_OFFLINE:
2267         case SDEV_TRANSPORT_OFFLINE:
2268                 switch (oldstate) {
2269                 case SDEV_CREATED:
2270                 case SDEV_RUNNING:
2271                 case SDEV_QUIESCE:
2272                 case SDEV_BLOCK:
2273                         break;
2274                 default:
2275                         goto illegal;
2276                 }
2277                 break;
2278
2279         case SDEV_BLOCK:
2280                 switch (oldstate) {
2281                 case SDEV_RUNNING:
2282                 case SDEV_CREATED_BLOCK:
2283                 case SDEV_QUIESCE:
2284                 case SDEV_OFFLINE:
2285                         break;
2286                 default:
2287                         goto illegal;
2288                 }
2289                 break;
2290
2291         case SDEV_CREATED_BLOCK:
2292                 switch (oldstate) {
2293                 case SDEV_CREATED:
2294                         break;
2295                 default:
2296                         goto illegal;
2297                 }
2298                 break;
2299
2300         case SDEV_CANCEL:
2301                 switch (oldstate) {
2302                 case SDEV_CREATED:
2303                 case SDEV_RUNNING:
2304                 case SDEV_QUIESCE:
2305                 case SDEV_OFFLINE:
2306                 case SDEV_TRANSPORT_OFFLINE:
2307                         break;
2308                 default:
2309                         goto illegal;
2310                 }
2311                 break;
2312
2313         case SDEV_DEL:
2314                 switch (oldstate) {
2315                 case SDEV_CREATED:
2316                 case SDEV_RUNNING:
2317                 case SDEV_OFFLINE:
2318                 case SDEV_TRANSPORT_OFFLINE:
2319                 case SDEV_CANCEL:
2320                 case SDEV_BLOCK:
2321                 case SDEV_CREATED_BLOCK:
2322                         break;
2323                 default:
2324                         goto illegal;
2325                 }
2326                 break;
2327
2328         }
2329         sdev->offline_already = false;
2330         sdev->sdev_state = state;
2331         return 0;
2332
2333  illegal:
2334         SCSI_LOG_ERROR_RECOVERY(1,
2335                                 sdev_printk(KERN_ERR, sdev,
2336                                             "Illegal state transition %s->%s",
2337                                             scsi_device_state_name(oldstate),
2338                                             scsi_device_state_name(state))
2339                                 );
2340         return -EINVAL;
2341 }
2342 EXPORT_SYMBOL(scsi_device_set_state);
2343
2344 /**
2345  *      sdev_evt_emit - emit a single SCSI device uevent
2346  *      @sdev: associated SCSI device
2347  *      @evt: event to emit
2348  *
2349  *      Send a single uevent (scsi_event) to the associated scsi_device.
2350  */
2351 static void scsi_evt_emit(struct scsi_device *sdev, struct scsi_event *evt)
2352 {
2353         int idx = 0;
2354         char *envp[3];
2355
2356         switch (evt->evt_type) {
2357         case SDEV_EVT_MEDIA_CHANGE:
2358                 envp[idx++] = "SDEV_MEDIA_CHANGE=1";
2359                 break;
2360         case SDEV_EVT_INQUIRY_CHANGE_REPORTED:
2361                 scsi_rescan_device(&sdev->sdev_gendev);
2362                 envp[idx++] = "SDEV_UA=INQUIRY_DATA_HAS_CHANGED";
2363                 break;
2364         case SDEV_EVT_CAPACITY_CHANGE_REPORTED:
2365                 envp[idx++] = "SDEV_UA=CAPACITY_DATA_HAS_CHANGED";
2366                 break;
2367         case SDEV_EVT_SOFT_THRESHOLD_REACHED_REPORTED:
2368                envp[idx++] = "SDEV_UA=THIN_PROVISIONING_SOFT_THRESHOLD_REACHED";
2369                 break;
2370         case SDEV_EVT_MODE_PARAMETER_CHANGE_REPORTED:
2371                 envp[idx++] = "SDEV_UA=MODE_PARAMETERS_CHANGED";
2372                 break;
2373         case SDEV_EVT_LUN_CHANGE_REPORTED:
2374                 envp[idx++] = "SDEV_UA=REPORTED_LUNS_DATA_HAS_CHANGED";
2375                 break;
2376         case SDEV_EVT_ALUA_STATE_CHANGE_REPORTED:
2377                 envp[idx++] = "SDEV_UA=ASYMMETRIC_ACCESS_STATE_CHANGED";
2378                 break;
2379         case SDEV_EVT_POWER_ON_RESET_OCCURRED:
2380                 envp[idx++] = "SDEV_UA=POWER_ON_RESET_OCCURRED";
2381                 break;
2382         default:
2383                 /* do nothing */
2384                 break;
2385         }
2386
2387         envp[idx++] = NULL;
2388
2389         kobject_uevent_env(&sdev->sdev_gendev.kobj, KOBJ_CHANGE, envp);
2390 }
2391
2392 /**
2393  *      sdev_evt_thread - send a uevent for each scsi event
2394  *      @work: work struct for scsi_device
2395  *
2396  *      Dispatch queued events to their associated scsi_device kobjects
2397  *      as uevents.
2398  */
2399 void scsi_evt_thread(struct work_struct *work)
2400 {
2401         struct scsi_device *sdev;
2402         enum scsi_device_event evt_type;
2403         LIST_HEAD(event_list);
2404
2405         sdev = container_of(work, struct scsi_device, event_work);
2406
2407         for (evt_type = SDEV_EVT_FIRST; evt_type <= SDEV_EVT_LAST; evt_type++)
2408                 if (test_and_clear_bit(evt_type, sdev->pending_events))
2409                         sdev_evt_send_simple(sdev, evt_type, GFP_KERNEL);
2410
2411         while (1) {
2412                 struct scsi_event *evt;
2413                 struct list_head *this, *tmp;
2414                 unsigned long flags;
2415
2416                 spin_lock_irqsave(&sdev->list_lock, flags);
2417                 list_splice_init(&sdev->event_list, &event_list);
2418                 spin_unlock_irqrestore(&sdev->list_lock, flags);
2419
2420                 if (list_empty(&event_list))
2421                         break;
2422
2423                 list_for_each_safe(this, tmp, &event_list) {
2424                         evt = list_entry(this, struct scsi_event, node);
2425                         list_del(&evt->node);
2426                         scsi_evt_emit(sdev, evt);
2427                         kfree(evt);
2428                 }
2429         }
2430 }
2431
2432 /**
2433  *      sdev_evt_send - send asserted event to uevent thread
2434  *      @sdev: scsi_device event occurred on
2435  *      @evt: event to send
2436  *
2437  *      Assert scsi device event asynchronously.
2438  */
2439 void sdev_evt_send(struct scsi_device *sdev, struct scsi_event *evt)
2440 {
2441         unsigned long flags;
2442
2443 #if 0
2444         /* FIXME: currently this check eliminates all media change events
2445          * for polled devices.  Need to update to discriminate between AN
2446          * and polled events */
2447         if (!test_bit(evt->evt_type, sdev->supported_events)) {
2448                 kfree(evt);
2449                 return;
2450         }
2451 #endif
2452
2453         spin_lock_irqsave(&sdev->list_lock, flags);
2454         list_add_tail(&evt->node, &sdev->event_list);
2455         schedule_work(&sdev->event_work);
2456         spin_unlock_irqrestore(&sdev->list_lock, flags);
2457 }
2458 EXPORT_SYMBOL_GPL(sdev_evt_send);
2459
2460 /**
2461  *      sdev_evt_alloc - allocate a new scsi event
2462  *      @evt_type: type of event to allocate
2463  *      @gfpflags: GFP flags for allocation
2464  *
2465  *      Allocates and returns a new scsi_event.
2466  */
2467 struct scsi_event *sdev_evt_alloc(enum scsi_device_event evt_type,
2468                                   gfp_t gfpflags)
2469 {
2470         struct scsi_event *evt = kzalloc(sizeof(struct scsi_event), gfpflags);
2471         if (!evt)
2472                 return NULL;
2473
2474         evt->evt_type = evt_type;
2475         INIT_LIST_HEAD(&evt->node);
2476
2477         /* evt_type-specific initialization, if any */
2478         switch (evt_type) {
2479         case SDEV_EVT_MEDIA_CHANGE:
2480         case SDEV_EVT_INQUIRY_CHANGE_REPORTED:
2481         case SDEV_EVT_CAPACITY_CHANGE_REPORTED:
2482         case SDEV_EVT_SOFT_THRESHOLD_REACHED_REPORTED:
2483         case SDEV_EVT_MODE_PARAMETER_CHANGE_REPORTED:
2484         case SDEV_EVT_LUN_CHANGE_REPORTED:
2485         case SDEV_EVT_ALUA_STATE_CHANGE_REPORTED:
2486         case SDEV_EVT_POWER_ON_RESET_OCCURRED:
2487         default:
2488                 /* do nothing */
2489                 break;
2490         }
2491
2492         return evt;
2493 }
2494 EXPORT_SYMBOL_GPL(sdev_evt_alloc);
2495
2496 /**
2497  *      sdev_evt_send_simple - send asserted event to uevent thread
2498  *      @sdev: scsi_device event occurred on
2499  *      @evt_type: type of event to send
2500  *      @gfpflags: GFP flags for allocation
2501  *
2502  *      Assert scsi device event asynchronously, given an event type.
2503  */
2504 void sdev_evt_send_simple(struct scsi_device *sdev,
2505                           enum scsi_device_event evt_type, gfp_t gfpflags)
2506 {
2507         struct scsi_event *evt = sdev_evt_alloc(evt_type, gfpflags);
2508         if (!evt) {
2509                 sdev_printk(KERN_ERR, sdev, "event %d eaten due to OOM\n",
2510                             evt_type);
2511                 return;
2512         }
2513
2514         sdev_evt_send(sdev, evt);
2515 }
2516 EXPORT_SYMBOL_GPL(sdev_evt_send_simple);
2517
2518 /**
2519  *      scsi_device_quiesce - Block all commands except power management.
2520  *      @sdev:  scsi device to quiesce.
2521  *
2522  *      This works by trying to transition to the SDEV_QUIESCE state
2523  *      (which must be a legal transition).  When the device is in this
2524  *      state, only power management requests will be accepted, all others will
2525  *      be deferred.
2526  *
2527  *      Must be called with user context, may sleep.
2528  *
2529  *      Returns zero if unsuccessful or an error if not.
2530  */
2531 int
2532 scsi_device_quiesce(struct scsi_device *sdev)
2533 {
2534         struct request_queue *q = sdev->request_queue;
2535         int err;
2536
2537         /*
2538          * It is allowed to call scsi_device_quiesce() multiple times from
2539          * the same context but concurrent scsi_device_quiesce() calls are
2540          * not allowed.
2541          */
2542         WARN_ON_ONCE(sdev->quiesced_by && sdev->quiesced_by != current);
2543
2544         if (sdev->quiesced_by == current)
2545                 return 0;
2546
2547         blk_set_pm_only(q);
2548
2549         blk_mq_freeze_queue(q);
2550         /*
2551          * Ensure that the effect of blk_set_pm_only() will be visible
2552          * for percpu_ref_tryget() callers that occur after the queue
2553          * unfreeze even if the queue was already frozen before this function
2554          * was called. See also https://lwn.net/Articles/573497/.
2555          */
2556         synchronize_rcu();
2557         blk_mq_unfreeze_queue(q);
2558
2559         mutex_lock(&sdev->state_mutex);
2560         err = scsi_device_set_state(sdev, SDEV_QUIESCE);
2561         if (err == 0)
2562                 sdev->quiesced_by = current;
2563         else
2564                 blk_clear_pm_only(q);
2565         mutex_unlock(&sdev->state_mutex);
2566
2567         return err;
2568 }
2569 EXPORT_SYMBOL(scsi_device_quiesce);
2570
2571 /**
2572  *      scsi_device_resume - Restart user issued commands to a quiesced device.
2573  *      @sdev:  scsi device to resume.
2574  *
2575  *      Moves the device from quiesced back to running and restarts the
2576  *      queues.
2577  *
2578  *      Must be called with user context, may sleep.
2579  */
2580 void scsi_device_resume(struct scsi_device *sdev)
2581 {
2582         /* check if the device state was mutated prior to resume, and if
2583          * so assume the state is being managed elsewhere (for example
2584          * device deleted during suspend)
2585          */
2586         mutex_lock(&sdev->state_mutex);
2587         if (sdev->sdev_state == SDEV_QUIESCE)
2588                 scsi_device_set_state(sdev, SDEV_RUNNING);
2589         if (sdev->quiesced_by) {
2590                 sdev->quiesced_by = NULL;
2591                 blk_clear_pm_only(sdev->request_queue);
2592         }
2593         mutex_unlock(&sdev->state_mutex);
2594 }
2595 EXPORT_SYMBOL(scsi_device_resume);
2596
2597 static void
2598 device_quiesce_fn(struct scsi_device *sdev, void *data)
2599 {
2600         scsi_device_quiesce(sdev);
2601 }
2602
2603 void
2604 scsi_target_quiesce(struct scsi_target *starget)
2605 {
2606         starget_for_each_device(starget, NULL, device_quiesce_fn);
2607 }
2608 EXPORT_SYMBOL(scsi_target_quiesce);
2609
2610 static void
2611 device_resume_fn(struct scsi_device *sdev, void *data)
2612 {
2613         scsi_device_resume(sdev);
2614 }
2615
2616 void
2617 scsi_target_resume(struct scsi_target *starget)
2618 {
2619         starget_for_each_device(starget, NULL, device_resume_fn);
2620 }
2621 EXPORT_SYMBOL(scsi_target_resume);
2622
2623 /**
2624  * scsi_internal_device_block_nowait - try to transition to the SDEV_BLOCK state
2625  * @sdev: device to block
2626  *
2627  * Pause SCSI command processing on the specified device. Does not sleep.
2628  *
2629  * Returns zero if successful or a negative error code upon failure.
2630  *
2631  * Notes:
2632  * This routine transitions the device to the SDEV_BLOCK state (which must be
2633  * a legal transition). When the device is in this state, command processing
2634  * is paused until the device leaves the SDEV_BLOCK state. See also
2635  * scsi_internal_device_unblock_nowait().
2636  */
2637 int scsi_internal_device_block_nowait(struct scsi_device *sdev)
2638 {
2639         struct request_queue *q = sdev->request_queue;
2640         int err = 0;
2641
2642         err = scsi_device_set_state(sdev, SDEV_BLOCK);
2643         if (err) {
2644                 err = scsi_device_set_state(sdev, SDEV_CREATED_BLOCK);
2645
2646                 if (err)
2647                         return err;
2648         }
2649
2650         /*
2651          * The device has transitioned to SDEV_BLOCK.  Stop the
2652          * block layer from calling the midlayer with this device's
2653          * request queue.
2654          */
2655         blk_mq_quiesce_queue_nowait(q);
2656         return 0;
2657 }
2658 EXPORT_SYMBOL_GPL(scsi_internal_device_block_nowait);
2659
2660 /**
2661  * scsi_internal_device_block - try to transition to the SDEV_BLOCK state
2662  * @sdev: device to block
2663  *
2664  * Pause SCSI command processing on the specified device and wait until all
2665  * ongoing scsi_request_fn() / scsi_queue_rq() calls have finished. May sleep.
2666  *
2667  * Returns zero if successful or a negative error code upon failure.
2668  *
2669  * Note:
2670  * This routine transitions the device to the SDEV_BLOCK state (which must be
2671  * a legal transition). When the device is in this state, command processing
2672  * is paused until the device leaves the SDEV_BLOCK state. See also
2673  * scsi_internal_device_unblock().
2674  */
2675 static int scsi_internal_device_block(struct scsi_device *sdev)
2676 {
2677         struct request_queue *q = sdev->request_queue;
2678         int err;
2679
2680         mutex_lock(&sdev->state_mutex);
2681         err = scsi_internal_device_block_nowait(sdev);
2682         if (err == 0)
2683                 blk_mq_quiesce_queue(q);
2684         mutex_unlock(&sdev->state_mutex);
2685
2686         return err;
2687 }
2688
2689 void scsi_start_queue(struct scsi_device *sdev)
2690 {
2691         struct request_queue *q = sdev->request_queue;
2692
2693         blk_mq_unquiesce_queue(q);
2694 }
2695
2696 /**
2697  * scsi_internal_device_unblock_nowait - resume a device after a block request
2698  * @sdev:       device to resume
2699  * @new_state:  state to set the device to after unblocking
2700  *
2701  * Restart the device queue for a previously suspended SCSI device. Does not
2702  * sleep.
2703  *
2704  * Returns zero if successful or a negative error code upon failure.
2705  *
2706  * Notes:
2707  * This routine transitions the device to the SDEV_RUNNING state or to one of
2708  * the offline states (which must be a legal transition) allowing the midlayer
2709  * to goose the queue for this device.
2710  */
2711 int scsi_internal_device_unblock_nowait(struct scsi_device *sdev,
2712                                         enum scsi_device_state new_state)
2713 {
2714         switch (new_state) {
2715         case SDEV_RUNNING:
2716         case SDEV_TRANSPORT_OFFLINE:
2717                 break;
2718         default:
2719                 return -EINVAL;
2720         }
2721
2722         /*
2723          * Try to transition the scsi device to SDEV_RUNNING or one of the
2724          * offlined states and goose the device queue if successful.
2725          */
2726         switch (sdev->sdev_state) {
2727         case SDEV_BLOCK:
2728         case SDEV_TRANSPORT_OFFLINE:
2729                 sdev->sdev_state = new_state;
2730                 break;
2731         case SDEV_CREATED_BLOCK:
2732                 if (new_state == SDEV_TRANSPORT_OFFLINE ||
2733                     new_state == SDEV_OFFLINE)
2734                         sdev->sdev_state = new_state;
2735                 else
2736                         sdev->sdev_state = SDEV_CREATED;
2737                 break;
2738         case SDEV_CANCEL:
2739         case SDEV_OFFLINE:
2740                 break;
2741         default:
2742                 return -EINVAL;
2743         }
2744         scsi_start_queue(sdev);
2745
2746         return 0;
2747 }
2748 EXPORT_SYMBOL_GPL(scsi_internal_device_unblock_nowait);
2749
2750 /**
2751  * scsi_internal_device_unblock - resume a device after a block request
2752  * @sdev:       device to resume
2753  * @new_state:  state to set the device to after unblocking
2754  *
2755  * Restart the device queue for a previously suspended SCSI device. May sleep.
2756  *
2757  * Returns zero if successful or a negative error code upon failure.
2758  *
2759  * Notes:
2760  * This routine transitions the device to the SDEV_RUNNING state or to one of
2761  * the offline states (which must be a legal transition) allowing the midlayer
2762  * to goose the queue for this device.
2763  */
2764 static int scsi_internal_device_unblock(struct scsi_device *sdev,
2765                                         enum scsi_device_state new_state)
2766 {
2767         int ret;
2768
2769         mutex_lock(&sdev->state_mutex);
2770         ret = scsi_internal_device_unblock_nowait(sdev, new_state);
2771         mutex_unlock(&sdev->state_mutex);
2772
2773         return ret;
2774 }
2775
2776 static void
2777 device_block(struct scsi_device *sdev, void *data)
2778 {
2779         int ret;
2780
2781         ret = scsi_internal_device_block(sdev);
2782
2783         WARN_ONCE(ret, "scsi_internal_device_block(%s) failed: ret = %d\n",
2784                   dev_name(&sdev->sdev_gendev), ret);
2785 }
2786
2787 static int
2788 target_block(struct device *dev, void *data)
2789 {
2790         if (scsi_is_target_device(dev))
2791                 starget_for_each_device(to_scsi_target(dev), NULL,
2792                                         device_block);
2793         return 0;
2794 }
2795
2796 void
2797 scsi_target_block(struct device *dev)
2798 {
2799         if (scsi_is_target_device(dev))
2800                 starget_for_each_device(to_scsi_target(dev), NULL,
2801                                         device_block);
2802         else
2803                 device_for_each_child(dev, NULL, target_block);
2804 }
2805 EXPORT_SYMBOL_GPL(scsi_target_block);
2806
2807 static void
2808 device_unblock(struct scsi_device *sdev, void *data)
2809 {
2810         scsi_internal_device_unblock(sdev, *(enum scsi_device_state *)data);
2811 }
2812
2813 static int
2814 target_unblock(struct device *dev, void *data)
2815 {
2816         if (scsi_is_target_device(dev))
2817                 starget_for_each_device(to_scsi_target(dev), data,
2818                                         device_unblock);
2819         return 0;
2820 }
2821
2822 void
2823 scsi_target_unblock(struct device *dev, enum scsi_device_state new_state)
2824 {
2825         if (scsi_is_target_device(dev))
2826                 starget_for_each_device(to_scsi_target(dev), &new_state,
2827                                         device_unblock);
2828         else
2829                 device_for_each_child(dev, &new_state, target_unblock);
2830 }
2831 EXPORT_SYMBOL_GPL(scsi_target_unblock);
2832
2833 int
2834 scsi_host_block(struct Scsi_Host *shost)
2835 {
2836         struct scsi_device *sdev;
2837         int ret = 0;
2838
2839         /*
2840          * Call scsi_internal_device_block_nowait so we can avoid
2841          * calling synchronize_rcu() for each LUN.
2842          */
2843         shost_for_each_device(sdev, shost) {
2844                 mutex_lock(&sdev->state_mutex);
2845                 ret = scsi_internal_device_block_nowait(sdev);
2846                 mutex_unlock(&sdev->state_mutex);
2847                 if (ret) {
2848                         scsi_device_put(sdev);
2849                         break;
2850                 }
2851         }
2852
2853         /*
2854          * SCSI never enables blk-mq's BLK_MQ_F_BLOCKING flag so
2855          * calling synchronize_rcu() once is enough.
2856          */
2857         WARN_ON_ONCE(shost->tag_set.flags & BLK_MQ_F_BLOCKING);
2858
2859         if (!ret)
2860                 synchronize_rcu();
2861
2862         return ret;
2863 }
2864 EXPORT_SYMBOL_GPL(scsi_host_block);
2865
2866 int
2867 scsi_host_unblock(struct Scsi_Host *shost, int new_state)
2868 {
2869         struct scsi_device *sdev;
2870         int ret = 0;
2871
2872         shost_for_each_device(sdev, shost) {
2873                 ret = scsi_internal_device_unblock(sdev, new_state);
2874                 if (ret) {
2875                         scsi_device_put(sdev);
2876                         break;
2877                 }
2878         }
2879         return ret;
2880 }
2881 EXPORT_SYMBOL_GPL(scsi_host_unblock);
2882
2883 /**
2884  * scsi_kmap_atomic_sg - find and atomically map an sg-elemnt
2885  * @sgl:        scatter-gather list
2886  * @sg_count:   number of segments in sg
2887  * @offset:     offset in bytes into sg, on return offset into the mapped area
2888  * @len:        bytes to map, on return number of bytes mapped
2889  *
2890  * Returns virtual address of the start of the mapped page
2891  */
2892 void *scsi_kmap_atomic_sg(struct scatterlist *sgl, int sg_count,
2893                           size_t *offset, size_t *len)
2894 {
2895         int i;
2896         size_t sg_len = 0, len_complete = 0;
2897         struct scatterlist *sg;
2898         struct page *page;
2899
2900         WARN_ON(!irqs_disabled());
2901
2902         for_each_sg(sgl, sg, sg_count, i) {
2903                 len_complete = sg_len; /* Complete sg-entries */
2904                 sg_len += sg->length;
2905                 if (sg_len > *offset)
2906                         break;
2907         }
2908
2909         if (unlikely(i == sg_count)) {
2910                 printk(KERN_ERR "%s: Bytes in sg: %zu, requested offset %zu, "
2911                         "elements %d\n",
2912                        __func__, sg_len, *offset, sg_count);
2913                 WARN_ON(1);
2914                 return NULL;
2915         }
2916
2917         /* Offset starting from the beginning of first page in this sg-entry */
2918         *offset = *offset - len_complete + sg->offset;
2919
2920         /* Assumption: contiguous pages can be accessed as "page + i" */
2921         page = nth_page(sg_page(sg), (*offset >> PAGE_SHIFT));
2922         *offset &= ~PAGE_MASK;
2923
2924         /* Bytes in this sg-entry from *offset to the end of the page */
2925         sg_len = PAGE_SIZE - *offset;
2926         if (*len > sg_len)
2927                 *len = sg_len;
2928
2929         return kmap_atomic(page);
2930 }
2931 EXPORT_SYMBOL(scsi_kmap_atomic_sg);
2932
2933 /**
2934  * scsi_kunmap_atomic_sg - atomically unmap a virtual address, previously mapped with scsi_kmap_atomic_sg
2935  * @virt:       virtual address to be unmapped
2936  */
2937 void scsi_kunmap_atomic_sg(void *virt)
2938 {
2939         kunmap_atomic(virt);
2940 }
2941 EXPORT_SYMBOL(scsi_kunmap_atomic_sg);
2942
2943 void sdev_disable_disk_events(struct scsi_device *sdev)
2944 {
2945         atomic_inc(&sdev->disk_events_disable_depth);
2946 }
2947 EXPORT_SYMBOL(sdev_disable_disk_events);
2948
2949 void sdev_enable_disk_events(struct scsi_device *sdev)
2950 {
2951         if (WARN_ON_ONCE(atomic_read(&sdev->disk_events_disable_depth) <= 0))
2952                 return;
2953         atomic_dec(&sdev->disk_events_disable_depth);
2954 }
2955 EXPORT_SYMBOL(sdev_enable_disk_events);
2956
2957 static unsigned char designator_prio(const unsigned char *d)
2958 {
2959         if (d[1] & 0x30)
2960                 /* not associated with LUN */
2961                 return 0;
2962
2963         if (d[3] == 0)
2964                 /* invalid length */
2965                 return 0;
2966
2967         /*
2968          * Order of preference for lun descriptor:
2969          * - SCSI name string
2970          * - NAA IEEE Registered Extended
2971          * - EUI-64 based 16-byte
2972          * - EUI-64 based 12-byte
2973          * - NAA IEEE Registered
2974          * - NAA IEEE Extended
2975          * - EUI-64 based 8-byte
2976          * - SCSI name string (truncated)
2977          * - T10 Vendor ID
2978          * as longer descriptors reduce the likelyhood
2979          * of identification clashes.
2980          */
2981
2982         switch (d[1] & 0xf) {
2983         case 8:
2984                 /* SCSI name string, variable-length UTF-8 */
2985                 return 9;
2986         case 3:
2987                 switch (d[4] >> 4) {
2988                 case 6:
2989                         /* NAA registered extended */
2990                         return 8;
2991                 case 5:
2992                         /* NAA registered */
2993                         return 5;
2994                 case 4:
2995                         /* NAA extended */
2996                         return 4;
2997                 case 3:
2998                         /* NAA locally assigned */
2999                         return 1;
3000                 default:
3001                         break;
3002                 }
3003                 break;
3004         case 2:
3005                 switch (d[3]) {
3006                 case 16:
3007                         /* EUI64-based, 16 byte */
3008                         return 7;
3009                 case 12:
3010                         /* EUI64-based, 12 byte */
3011                         return 6;
3012                 case 8:
3013                         /* EUI64-based, 8 byte */
3014                         return 3;
3015                 default:
3016                         break;
3017                 }
3018                 break;
3019         case 1:
3020                 /* T10 vendor ID */
3021                 return 1;
3022         default:
3023                 break;
3024         }
3025
3026         return 0;
3027 }
3028
3029 /**
3030  * scsi_vpd_lun_id - return a unique device identification
3031  * @sdev: SCSI device
3032  * @id:   buffer for the identification
3033  * @id_len:  length of the buffer
3034  *
3035  * Copies a unique device identification into @id based
3036  * on the information in the VPD page 0x83 of the device.
3037  * The string will be formatted as a SCSI name string.
3038  *
3039  * Returns the length of the identification or error on failure.
3040  * If the identifier is longer than the supplied buffer the actual
3041  * identifier length is returned and the buffer is not zero-padded.
3042  */
3043 int scsi_vpd_lun_id(struct scsi_device *sdev, char *id, size_t id_len)
3044 {
3045         u8 cur_id_prio = 0;
3046         u8 cur_id_size = 0;
3047         const unsigned char *d, *cur_id_str;
3048         const struct scsi_vpd *vpd_pg83;
3049         int id_size = -EINVAL;
3050
3051         rcu_read_lock();
3052         vpd_pg83 = rcu_dereference(sdev->vpd_pg83);
3053         if (!vpd_pg83) {
3054                 rcu_read_unlock();
3055                 return -ENXIO;
3056         }
3057
3058         /* The id string must be at least 20 bytes + terminating NULL byte */
3059         if (id_len < 21) {
3060                 rcu_read_unlock();
3061                 return -EINVAL;
3062         }
3063
3064         memset(id, 0, id_len);
3065         d = vpd_pg83->data + 4;
3066         while (d < vpd_pg83->data + vpd_pg83->len) {
3067                 u8 prio = designator_prio(d);
3068
3069                 if (prio == 0 || cur_id_prio > prio)
3070                         goto next_desig;
3071
3072                 switch (d[1] & 0xf) {
3073                 case 0x1:
3074                         /* T10 Vendor ID */
3075                         if (cur_id_size > d[3])
3076                                 break;
3077                         cur_id_prio = prio;
3078                         cur_id_size = d[3];
3079                         if (cur_id_size + 4 > id_len)
3080                                 cur_id_size = id_len - 4;
3081                         cur_id_str = d + 4;
3082                         id_size = snprintf(id, id_len, "t10.%*pE",
3083                                            cur_id_size, cur_id_str);
3084                         break;
3085                 case 0x2:
3086                         /* EUI-64 */
3087                         cur_id_prio = prio;
3088                         cur_id_size = d[3];
3089                         cur_id_str = d + 4;
3090                         switch (cur_id_size) {
3091                         case 8:
3092                                 id_size = snprintf(id, id_len,
3093                                                    "eui.%8phN",
3094                                                    cur_id_str);
3095                                 break;
3096                         case 12:
3097                                 id_size = snprintf(id, id_len,
3098                                                    "eui.%12phN",
3099                                                    cur_id_str);
3100                                 break;
3101                         case 16:
3102                                 id_size = snprintf(id, id_len,
3103                                                    "eui.%16phN",
3104                                                    cur_id_str);
3105                                 break;
3106                         default:
3107                                 break;
3108                         }
3109                         break;
3110                 case 0x3:
3111                         /* NAA */
3112                         cur_id_prio = prio;
3113                         cur_id_size = d[3];
3114                         cur_id_str = d + 4;
3115                         switch (cur_id_size) {
3116                         case 8:
3117                                 id_size = snprintf(id, id_len,
3118                                                    "naa.%8phN",
3119                                                    cur_id_str);
3120                                 break;
3121                         case 16:
3122                                 id_size = snprintf(id, id_len,
3123                                                    "naa.%16phN",
3124                                                    cur_id_str);
3125                                 break;
3126                         default:
3127                                 break;
3128                         }
3129                         break;
3130                 case 0x8:
3131                         /* SCSI name string */
3132                         if (cur_id_size > d[3])
3133                                 break;
3134                         /* Prefer others for truncated descriptor */
3135                         if (d[3] > id_len) {
3136                                 prio = 2;
3137                                 if (cur_id_prio > prio)
3138                                         break;
3139                         }
3140                         cur_id_prio = prio;
3141                         cur_id_size = id_size = d[3];
3142                         cur_id_str = d + 4;
3143                         if (cur_id_size >= id_len)
3144                                 cur_id_size = id_len - 1;
3145                         memcpy(id, cur_id_str, cur_id_size);
3146                         break;
3147                 default:
3148                         break;
3149                 }
3150 next_desig:
3151                 d += d[3] + 4;
3152         }
3153         rcu_read_unlock();
3154
3155         return id_size;
3156 }
3157 EXPORT_SYMBOL(scsi_vpd_lun_id);
3158
3159 /*
3160  * scsi_vpd_tpg_id - return a target port group identifier
3161  * @sdev: SCSI device
3162  *
3163  * Returns the Target Port Group identifier from the information
3164  * froom VPD page 0x83 of the device.
3165  *
3166  * Returns the identifier or error on failure.
3167  */
3168 int scsi_vpd_tpg_id(struct scsi_device *sdev, int *rel_id)
3169 {
3170         const unsigned char *d;
3171         const struct scsi_vpd *vpd_pg83;
3172         int group_id = -EAGAIN, rel_port = -1;
3173
3174         rcu_read_lock();
3175         vpd_pg83 = rcu_dereference(sdev->vpd_pg83);
3176         if (!vpd_pg83) {
3177                 rcu_read_unlock();
3178                 return -ENXIO;
3179         }
3180
3181         d = vpd_pg83->data + 4;
3182         while (d < vpd_pg83->data + vpd_pg83->len) {
3183                 switch (d[1] & 0xf) {
3184                 case 0x4:
3185                         /* Relative target port */
3186                         rel_port = get_unaligned_be16(&d[6]);
3187                         break;
3188                 case 0x5:
3189                         /* Target port group */
3190                         group_id = get_unaligned_be16(&d[6]);
3191                         break;
3192                 default:
3193                         break;
3194                 }
3195                 d += d[3] + 4;
3196         }
3197         rcu_read_unlock();
3198
3199         if (group_id >= 0 && rel_id && rel_port != -1)
3200                 *rel_id = rel_port;
3201
3202         return group_id;
3203 }
3204 EXPORT_SYMBOL(scsi_vpd_tpg_id);