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