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