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