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