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