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