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