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