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