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