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