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