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