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