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