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