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