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