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