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