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