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