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