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