scsi: move scsi_dispatch_cmd to scsi_lib.c
[firefly-linux-kernel-4.4.55.git] / drivers / scsi / scsi.c
1 /*
2  *  scsi.c Copyright (C) 1992 Drew Eckhardt
3  *         Copyright (C) 1993, 1994, 1995, 1999 Eric Youngdale
4  *         Copyright (C) 2002, 2003 Christoph Hellwig
5  *
6  *  generic mid-level SCSI driver
7  *      Initial versions: Drew Eckhardt
8  *      Subsequent revisions: Eric Youngdale
9  *
10  *  <drew@colorado.edu>
11  *
12  *  Bug correction thanks go to :
13  *      Rik Faith <faith@cs.unc.edu>
14  *      Tommy Thorn <tthorn>
15  *      Thomas Wuensche <tw@fgb1.fgb.mw.tu-muenchen.de>
16  *
17  *  Modified by Eric Youngdale eric@andante.org or ericy@gnu.ai.mit.edu to
18  *  add scatter-gather, multiple outstanding request, and other
19  *  enhancements.
20  *
21  *  Native multichannel, wide scsi, /proc/scsi and hot plugging
22  *  support added by Michael Neuffer <mike@i-connect.net>
23  *
24  *  Added request_module("scsi_hostadapter") for kerneld:
25  *  (Put an "alias scsi_hostadapter your_hostadapter" in /etc/modprobe.conf)
26  *  Bjorn Ekwall  <bj0rn@blox.se>
27  *  (changed to kmod)
28  *
29  *  Major improvements to the timeout, abort, and reset processing,
30  *  as well as performance modifications for large queue depths by
31  *  Leonard N. Zubkoff <lnz@dandelion.com>
32  *
33  *  Converted cli() code to spinlocks, Ingo Molnar
34  *
35  *  Jiffies wrap fixes (host->resetting), 3 Dec 1998 Andrea Arcangeli
36  *
37  *  out_of_space hacks, D. Gilbert (dpg) 990608
38  */
39
40 #include <linux/module.h>
41 #include <linux/moduleparam.h>
42 #include <linux/kernel.h>
43 #include <linux/timer.h>
44 #include <linux/string.h>
45 #include <linux/slab.h>
46 #include <linux/blkdev.h>
47 #include <linux/delay.h>
48 #include <linux/init.h>
49 #include <linux/completion.h>
50 #include <linux/unistd.h>
51 #include <linux/spinlock.h>
52 #include <linux/kmod.h>
53 #include <linux/interrupt.h>
54 #include <linux/notifier.h>
55 #include <linux/cpu.h>
56 #include <linux/mutex.h>
57 #include <linux/async.h>
58 #include <asm/unaligned.h>
59
60 #include <scsi/scsi.h>
61 #include <scsi/scsi_cmnd.h>
62 #include <scsi/scsi_dbg.h>
63 #include <scsi/scsi_device.h>
64 #include <scsi/scsi_driver.h>
65 #include <scsi/scsi_eh.h>
66 #include <scsi/scsi_host.h>
67 #include <scsi/scsi_tcq.h>
68
69 #include "scsi_priv.h"
70 #include "scsi_logging.h"
71
72 #define CREATE_TRACE_POINTS
73 #include <trace/events/scsi.h>
74
75 /*
76  * Definitions and constants.
77  */
78
79 /*
80  * Note - the initial logging level can be set here to log events at boot time.
81  * After the system is up, you may enable logging via the /proc interface.
82  */
83 unsigned int scsi_logging_level;
84 #if defined(CONFIG_SCSI_LOGGING)
85 EXPORT_SYMBOL(scsi_logging_level);
86 #endif
87
88 /* sd, scsi core and power management need to coordinate flushing async actions */
89 ASYNC_DOMAIN(scsi_sd_probe_domain);
90 EXPORT_SYMBOL(scsi_sd_probe_domain);
91
92 /*
93  * Separate domain (from scsi_sd_probe_domain) to maximize the benefit of
94  * asynchronous system resume operations.  It is marked 'exclusive' to avoid
95  * being included in the async_synchronize_full() that is invoked by
96  * dpm_resume()
97  */
98 ASYNC_DOMAIN_EXCLUSIVE(scsi_sd_pm_domain);
99 EXPORT_SYMBOL(scsi_sd_pm_domain);
100
101 /* NB: These are exposed through /proc/scsi/scsi and form part of the ABI.
102  * You may not alter any existing entry (although adding new ones is
103  * encouraged once assigned by ANSI/INCITS T10
104  */
105 static const char *const scsi_device_types[] = {
106         "Direct-Access    ",
107         "Sequential-Access",
108         "Printer          ",
109         "Processor        ",
110         "WORM             ",
111         "CD-ROM           ",
112         "Scanner          ",
113         "Optical Device   ",
114         "Medium Changer   ",
115         "Communications   ",
116         "ASC IT8          ",
117         "ASC IT8          ",
118         "RAID             ",
119         "Enclosure        ",
120         "Direct-Access-RBC",
121         "Optical card     ",
122         "Bridge controller",
123         "Object storage   ",
124         "Automation/Drive ",
125         "Security Manager ",
126         "Direct-Access-ZBC",
127 };
128
129 /**
130  * scsi_device_type - Return 17 char string indicating device type.
131  * @type: type number to look up
132  */
133
134 const char * scsi_device_type(unsigned type)
135 {
136         if (type == 0x1e)
137                 return "Well-known LUN   ";
138         if (type == 0x1f)
139                 return "No Device        ";
140         if (type >= ARRAY_SIZE(scsi_device_types))
141                 return "Unknown          ";
142         return scsi_device_types[type];
143 }
144
145 EXPORT_SYMBOL(scsi_device_type);
146
147 struct scsi_host_cmd_pool {
148         struct kmem_cache       *cmd_slab;
149         struct kmem_cache       *sense_slab;
150         unsigned int            users;
151         char                    *cmd_name;
152         char                    *sense_name;
153         unsigned int            slab_flags;
154         gfp_t                   gfp_mask;
155 };
156
157 static struct scsi_host_cmd_pool scsi_cmd_pool = {
158         .cmd_name       = "scsi_cmd_cache",
159         .sense_name     = "scsi_sense_cache",
160         .slab_flags     = SLAB_HWCACHE_ALIGN,
161 };
162
163 static struct scsi_host_cmd_pool scsi_cmd_dma_pool = {
164         .cmd_name       = "scsi_cmd_cache(DMA)",
165         .sense_name     = "scsi_sense_cache(DMA)",
166         .slab_flags     = SLAB_HWCACHE_ALIGN|SLAB_CACHE_DMA,
167         .gfp_mask       = __GFP_DMA,
168 };
169
170 static DEFINE_MUTEX(host_cmd_pool_mutex);
171
172 /**
173  * scsi_host_free_command - internal function to release a command
174  * @shost:      host to free the command for
175  * @cmd:        command to release
176  *
177  * the command must previously have been allocated by
178  * scsi_host_alloc_command.
179  */
180 static void
181 scsi_host_free_command(struct Scsi_Host *shost, struct scsi_cmnd *cmd)
182 {
183         struct scsi_host_cmd_pool *pool = shost->cmd_pool;
184
185         if (cmd->prot_sdb)
186                 kmem_cache_free(scsi_sdb_cache, cmd->prot_sdb);
187         kmem_cache_free(pool->sense_slab, cmd->sense_buffer);
188         kmem_cache_free(pool->cmd_slab, cmd);
189 }
190
191 /**
192  * scsi_host_alloc_command - internal function to allocate command
193  * @shost:      SCSI host whose pool to allocate from
194  * @gfp_mask:   mask for the allocation
195  *
196  * Returns a fully allocated command with sense buffer and protection
197  * data buffer (where applicable) or NULL on failure
198  */
199 static struct scsi_cmnd *
200 scsi_host_alloc_command(struct Scsi_Host *shost, gfp_t gfp_mask)
201 {
202         struct scsi_host_cmd_pool *pool = shost->cmd_pool;
203         struct scsi_cmnd *cmd;
204
205         cmd = kmem_cache_zalloc(pool->cmd_slab, gfp_mask | pool->gfp_mask);
206         if (!cmd)
207                 goto fail;
208
209         cmd->sense_buffer = kmem_cache_alloc(pool->sense_slab,
210                                              gfp_mask | pool->gfp_mask);
211         if (!cmd->sense_buffer)
212                 goto fail_free_cmd;
213
214         if (scsi_host_get_prot(shost) >= SHOST_DIX_TYPE0_PROTECTION) {
215                 cmd->prot_sdb = kmem_cache_zalloc(scsi_sdb_cache, gfp_mask);
216                 if (!cmd->prot_sdb)
217                         goto fail_free_sense;
218         }
219
220         return cmd;
221
222 fail_free_sense:
223         kmem_cache_free(pool->sense_slab, cmd->sense_buffer);
224 fail_free_cmd:
225         kmem_cache_free(pool->cmd_slab, cmd);
226 fail:
227         return NULL;
228 }
229
230 /**
231  * __scsi_get_command - Allocate a struct scsi_cmnd
232  * @shost: host to transmit command
233  * @gfp_mask: allocation mask
234  *
235  * Description: allocate a struct scsi_cmd from host's slab, recycling from the
236  *              host's free_list if necessary.
237  */
238 static struct scsi_cmnd *
239 __scsi_get_command(struct Scsi_Host *shost, gfp_t gfp_mask)
240 {
241         struct scsi_cmnd *cmd = scsi_host_alloc_command(shost, gfp_mask);
242
243         if (unlikely(!cmd)) {
244                 unsigned long flags;
245
246                 spin_lock_irqsave(&shost->free_list_lock, flags);
247                 if (likely(!list_empty(&shost->free_list))) {
248                         cmd = list_entry(shost->free_list.next,
249                                          struct scsi_cmnd, list);
250                         list_del_init(&cmd->list);
251                 }
252                 spin_unlock_irqrestore(&shost->free_list_lock, flags);
253
254                 if (cmd) {
255                         void *buf, *prot;
256
257                         buf = cmd->sense_buffer;
258                         prot = cmd->prot_sdb;
259
260                         memset(cmd, 0, sizeof(*cmd));
261
262                         cmd->sense_buffer = buf;
263                         cmd->prot_sdb = prot;
264                 }
265         }
266
267         return cmd;
268 }
269
270 /**
271  * scsi_get_command - Allocate and setup a scsi command block
272  * @dev: parent scsi device
273  * @gfp_mask: allocator flags
274  *
275  * Returns:     The allocated scsi command structure.
276  */
277 struct scsi_cmnd *scsi_get_command(struct scsi_device *dev, gfp_t gfp_mask)
278 {
279         struct scsi_cmnd *cmd = __scsi_get_command(dev->host, gfp_mask);
280         unsigned long flags;
281
282         if (unlikely(cmd == NULL))
283                 return NULL;
284
285         cmd->device = dev;
286         INIT_LIST_HEAD(&cmd->list);
287         INIT_DELAYED_WORK(&cmd->abort_work, scmd_eh_abort_handler);
288         spin_lock_irqsave(&dev->list_lock, flags);
289         list_add_tail(&cmd->list, &dev->cmd_list);
290         spin_unlock_irqrestore(&dev->list_lock, flags);
291         cmd->jiffies_at_alloc = jiffies;
292         return cmd;
293 }
294
295 /**
296  * __scsi_put_command - Free a struct scsi_cmnd
297  * @shost: dev->host
298  * @cmd: Command to free
299  */
300 static void __scsi_put_command(struct Scsi_Host *shost, struct scsi_cmnd *cmd)
301 {
302         unsigned long flags;
303
304         if (unlikely(list_empty(&shost->free_list))) {
305                 spin_lock_irqsave(&shost->free_list_lock, flags);
306                 if (list_empty(&shost->free_list)) {
307                         list_add(&cmd->list, &shost->free_list);
308                         cmd = NULL;
309                 }
310                 spin_unlock_irqrestore(&shost->free_list_lock, flags);
311         }
312
313         if (likely(cmd != NULL))
314                 scsi_host_free_command(shost, cmd);
315 }
316
317 /**
318  * scsi_put_command - Free a scsi command block
319  * @cmd: command block to free
320  *
321  * Returns:     Nothing.
322  *
323  * Notes:       The command must not belong to any lists.
324  */
325 void scsi_put_command(struct scsi_cmnd *cmd)
326 {
327         unsigned long flags;
328
329         /* serious error if the command hasn't come from a device list */
330         spin_lock_irqsave(&cmd->device->list_lock, flags);
331         BUG_ON(list_empty(&cmd->list));
332         list_del_init(&cmd->list);
333         spin_unlock_irqrestore(&cmd->device->list_lock, flags);
334
335         BUG_ON(delayed_work_pending(&cmd->abort_work));
336
337         __scsi_put_command(cmd->device->host, cmd);
338 }
339
340 static struct scsi_host_cmd_pool *
341 scsi_find_host_cmd_pool(struct Scsi_Host *shost)
342 {
343         if (shost->hostt->cmd_size)
344                 return shost->hostt->cmd_pool;
345         if (shost->unchecked_isa_dma)
346                 return &scsi_cmd_dma_pool;
347         return &scsi_cmd_pool;
348 }
349
350 static void
351 scsi_free_host_cmd_pool(struct scsi_host_cmd_pool *pool)
352 {
353         kfree(pool->sense_name);
354         kfree(pool->cmd_name);
355         kfree(pool);
356 }
357
358 static struct scsi_host_cmd_pool *
359 scsi_alloc_host_cmd_pool(struct Scsi_Host *shost)
360 {
361         struct scsi_host_template *hostt = shost->hostt;
362         struct scsi_host_cmd_pool *pool;
363
364         pool = kzalloc(sizeof(*pool), GFP_KERNEL);
365         if (!pool)
366                 return NULL;
367
368         pool->cmd_name = kasprintf(GFP_KERNEL, "%s_cmd", hostt->proc_name);
369         pool->sense_name = kasprintf(GFP_KERNEL, "%s_sense", hostt->proc_name);
370         if (!pool->cmd_name || !pool->sense_name) {
371                 scsi_free_host_cmd_pool(pool);
372                 return NULL;
373         }
374
375         pool->slab_flags = SLAB_HWCACHE_ALIGN;
376         if (shost->unchecked_isa_dma) {
377                 pool->slab_flags |= SLAB_CACHE_DMA;
378                 pool->gfp_mask = __GFP_DMA;
379         }
380
381         if (hostt->cmd_size)
382                 hostt->cmd_pool = pool;
383
384         return pool;
385 }
386
387 static struct scsi_host_cmd_pool *
388 scsi_get_host_cmd_pool(struct Scsi_Host *shost)
389 {
390         struct scsi_host_template *hostt = shost->hostt;
391         struct scsi_host_cmd_pool *retval = NULL, *pool;
392         size_t cmd_size = sizeof(struct scsi_cmnd) + hostt->cmd_size;
393
394         /*
395          * Select a command slab for this host and create it if not
396          * yet existent.
397          */
398         mutex_lock(&host_cmd_pool_mutex);
399         pool = scsi_find_host_cmd_pool(shost);
400         if (!pool) {
401                 pool = scsi_alloc_host_cmd_pool(shost);
402                 if (!pool)
403                         goto out;
404         }
405
406         if (!pool->users) {
407                 pool->cmd_slab = kmem_cache_create(pool->cmd_name, cmd_size, 0,
408                                                    pool->slab_flags, NULL);
409                 if (!pool->cmd_slab)
410                         goto out_free_pool;
411
412                 pool->sense_slab = kmem_cache_create(pool->sense_name,
413                                                      SCSI_SENSE_BUFFERSIZE, 0,
414                                                      pool->slab_flags, NULL);
415                 if (!pool->sense_slab)
416                         goto out_free_slab;
417         }
418
419         pool->users++;
420         retval = pool;
421 out:
422         mutex_unlock(&host_cmd_pool_mutex);
423         return retval;
424
425 out_free_slab:
426         kmem_cache_destroy(pool->cmd_slab);
427 out_free_pool:
428         if (hostt->cmd_size) {
429                 scsi_free_host_cmd_pool(pool);
430                 hostt->cmd_pool = NULL;
431         }
432         goto out;
433 }
434
435 static void scsi_put_host_cmd_pool(struct Scsi_Host *shost)
436 {
437         struct scsi_host_template *hostt = shost->hostt;
438         struct scsi_host_cmd_pool *pool;
439
440         mutex_lock(&host_cmd_pool_mutex);
441         pool = scsi_find_host_cmd_pool(shost);
442
443         /*
444          * This may happen if a driver has a mismatched get and put
445          * of the command pool; the driver should be implicated in
446          * the stack trace
447          */
448         BUG_ON(pool->users == 0);
449
450         if (!--pool->users) {
451                 kmem_cache_destroy(pool->cmd_slab);
452                 kmem_cache_destroy(pool->sense_slab);
453                 if (hostt->cmd_size) {
454                         scsi_free_host_cmd_pool(pool);
455                         hostt->cmd_pool = NULL;
456                 }
457         }
458         mutex_unlock(&host_cmd_pool_mutex);
459 }
460
461 /**
462  * scsi_setup_command_freelist - Setup the command freelist for a scsi host.
463  * @shost: host to allocate the freelist for.
464  *
465  * Description: The command freelist protects against system-wide out of memory
466  * deadlock by preallocating one SCSI command structure for each host, so the
467  * system can always write to a swap file on a device associated with that host.
468  *
469  * Returns:     Nothing.
470  */
471 int scsi_setup_command_freelist(struct Scsi_Host *shost)
472 {
473         const gfp_t gfp_mask = shost->unchecked_isa_dma ? GFP_DMA : GFP_KERNEL;
474         struct scsi_cmnd *cmd;
475
476         spin_lock_init(&shost->free_list_lock);
477         INIT_LIST_HEAD(&shost->free_list);
478
479         shost->cmd_pool = scsi_get_host_cmd_pool(shost);
480         if (!shost->cmd_pool)
481                 return -ENOMEM;
482
483         /*
484          * Get one backup command for this host.
485          */
486         cmd = scsi_host_alloc_command(shost, gfp_mask);
487         if (!cmd) {
488                 scsi_put_host_cmd_pool(shost);
489                 shost->cmd_pool = NULL;
490                 return -ENOMEM;
491         }
492         list_add(&cmd->list, &shost->free_list);
493         return 0;
494 }
495
496 /**
497  * scsi_destroy_command_freelist - Release the command freelist for a scsi host.
498  * @shost: host whose freelist is going to be destroyed
499  */
500 void scsi_destroy_command_freelist(struct Scsi_Host *shost)
501 {
502         /*
503          * If cmd_pool is NULL the free list was not initialized, so
504          * do not attempt to release resources.
505          */
506         if (!shost->cmd_pool)
507                 return;
508
509         while (!list_empty(&shost->free_list)) {
510                 struct scsi_cmnd *cmd;
511
512                 cmd = list_entry(shost->free_list.next, struct scsi_cmnd, list);
513                 list_del_init(&cmd->list);
514                 scsi_host_free_command(shost, cmd);
515         }
516         shost->cmd_pool = NULL;
517         scsi_put_host_cmd_pool(shost);
518 }
519
520 #ifdef CONFIG_SCSI_LOGGING
521 void scsi_log_send(struct scsi_cmnd *cmd)
522 {
523         unsigned int level;
524
525         /*
526          * If ML QUEUE log level is greater than or equal to:
527          *
528          * 1: nothing (match completion)
529          *
530          * 2: log opcode + command of all commands + cmd address
531          *
532          * 3: same as 2
533          *
534          * 4: same as 3 plus dump extra junk
535          */
536         if (unlikely(scsi_logging_level)) {
537                 level = SCSI_LOG_LEVEL(SCSI_LOG_MLQUEUE_SHIFT,
538                                        SCSI_LOG_MLQUEUE_BITS);
539                 if (level > 1) {
540                         scmd_printk(KERN_INFO, cmd,
541                                     "Send: scmd 0x%p\n", cmd);
542                         scsi_print_command(cmd);
543                         if (level > 3) {
544                                 printk(KERN_INFO "buffer = 0x%p, bufflen = %d,"
545                                        " queuecommand 0x%p\n",
546                                         scsi_sglist(cmd), scsi_bufflen(cmd),
547                                         cmd->device->host->hostt->queuecommand);
548
549                         }
550                 }
551         }
552 }
553
554 void scsi_log_completion(struct scsi_cmnd *cmd, int disposition)
555 {
556         unsigned int level;
557
558         /*
559          * If ML COMPLETE log level is greater than or equal to:
560          *
561          * 1: log disposition, result, opcode + command, and conditionally
562          * sense data for failures or non SUCCESS dispositions.
563          *
564          * 2: same as 1 but for all command completions.
565          *
566          * 3: same as 2
567          *
568          * 4: same as 3 plus dump extra junk
569          */
570         if (unlikely(scsi_logging_level)) {
571                 level = SCSI_LOG_LEVEL(SCSI_LOG_MLCOMPLETE_SHIFT,
572                                        SCSI_LOG_MLCOMPLETE_BITS);
573                 if (((level > 0) && (cmd->result || disposition != SUCCESS)) ||
574                     (level > 1)) {
575                         scsi_print_result(cmd, "Done: ", disposition);
576                         scsi_print_command(cmd);
577                         if (status_byte(cmd->result) & CHECK_CONDITION)
578                                 scsi_print_sense(cmd);
579                         if (level > 3)
580                                 scmd_printk(KERN_INFO, cmd,
581                                             "scsi host busy %d failed %d\n",
582                                             atomic_read(&cmd->device->host->host_busy),
583                                             cmd->device->host->host_failed);
584                 }
585         }
586 }
587 #endif
588
589 /**
590  * scsi_cmd_get_serial - Assign a serial number to a command
591  * @host: the scsi host
592  * @cmd: command to assign serial number to
593  *
594  * Description: a serial number identifies a request for error recovery
595  * and debugging purposes.  Protected by the Host_Lock of host.
596  */
597 void scsi_cmd_get_serial(struct Scsi_Host *host, struct scsi_cmnd *cmd)
598 {
599         cmd->serial_number = host->cmd_serial_number++;
600         if (cmd->serial_number == 0) 
601                 cmd->serial_number = host->cmd_serial_number++;
602 }
603 EXPORT_SYMBOL(scsi_cmd_get_serial);
604
605 /**
606  * scsi_finish_command - cleanup and pass command back to upper layer
607  * @cmd: the command
608  *
609  * Description: Pass command off to upper layer for finishing of I/O
610  *              request, waking processes that are waiting on results,
611  *              etc.
612  */
613 void scsi_finish_command(struct scsi_cmnd *cmd)
614 {
615         struct scsi_device *sdev = cmd->device;
616         struct scsi_target *starget = scsi_target(sdev);
617         struct Scsi_Host *shost = sdev->host;
618         struct scsi_driver *drv;
619         unsigned int good_bytes;
620
621         scsi_device_unbusy(sdev);
622
623         /*
624          * Clear the flags that say that the device/target/host is no longer
625          * capable of accepting new commands.
626          */
627         if (atomic_read(&shost->host_blocked))
628                 atomic_set(&shost->host_blocked, 0);
629         if (atomic_read(&starget->target_blocked))
630                 atomic_set(&starget->target_blocked, 0);
631         if (atomic_read(&sdev->device_blocked))
632                 atomic_set(&sdev->device_blocked, 0);
633
634         /*
635          * If we have valid sense information, then some kind of recovery
636          * must have taken place.  Make a note of this.
637          */
638         if (SCSI_SENSE_VALID(cmd))
639                 cmd->result |= (DRIVER_SENSE << 24);
640
641         SCSI_LOG_MLCOMPLETE(4, sdev_printk(KERN_INFO, sdev,
642                                 "Notifying upper driver of completion "
643                                 "(result %x)\n", cmd->result));
644
645         good_bytes = scsi_bufflen(cmd);
646         if (cmd->request->cmd_type != REQ_TYPE_BLOCK_PC) {
647                 int old_good_bytes = good_bytes;
648                 drv = scsi_cmd_to_driver(cmd);
649                 if (drv->done)
650                         good_bytes = drv->done(cmd);
651                 /*
652                  * USB may not give sense identifying bad sector and
653                  * simply return a residue instead, so subtract off the
654                  * residue if drv->done() error processing indicates no
655                  * change to the completion length.
656                  */
657                 if (good_bytes == old_good_bytes)
658                         good_bytes -= scsi_get_resid(cmd);
659         }
660         scsi_io_completion(cmd, good_bytes);
661 }
662
663 /**
664  * scsi_adjust_queue_depth - Let low level drivers change a device's queue depth
665  * @sdev: SCSI Device in question
666  * @tags: Number of tags allowed if tagged queueing enabled,
667  *        or number of commands the low level driver can
668  *        queue up in non-tagged mode (as per cmd_per_lun).
669  *
670  * Returns:     Nothing
671  *
672  * Lock Status: None held on entry
673  *
674  * Notes:       Low level drivers may call this at any time and we will do
675  *              the right thing depending on whether or not the device is
676  *              currently active and whether or not it even has the
677  *              command blocks built yet.
678  */
679 void scsi_adjust_queue_depth(struct scsi_device *sdev, int tags)
680 {
681         unsigned long flags;
682
683         /*
684          * refuse to set tagged depth to an unworkable size
685          */
686         if (tags <= 0)
687                 return;
688
689         spin_lock_irqsave(sdev->request_queue->queue_lock, flags);
690
691         /*
692          * Check to see if the queue is managed by the block layer.
693          * If it is, and we fail to adjust the depth, exit.
694          *
695          * Do not resize the tag map if it is a host wide share bqt,
696          * because the size should be the hosts's can_queue. If there
697          * is more IO than the LLD's can_queue (so there are not enuogh
698          * tags) request_fn's host queue ready check will handle it.
699          */
700         if (!shost_use_blk_mq(sdev->host) && !sdev->host->bqt) {
701                 if (blk_queue_tagged(sdev->request_queue) &&
702                     blk_queue_resize_tags(sdev->request_queue, tags) != 0)
703                         goto out;
704         }
705
706         sdev->queue_depth = tags;
707  out:
708         spin_unlock_irqrestore(sdev->request_queue->queue_lock, flags);
709 }
710 EXPORT_SYMBOL(scsi_adjust_queue_depth);
711
712 /**
713  * scsi_track_queue_full - track QUEUE_FULL events to adjust queue depth
714  * @sdev: SCSI Device in question
715  * @depth: Current number of outstanding SCSI commands on this device,
716  *         not counting the one returned as QUEUE_FULL.
717  *
718  * Description: This function will track successive QUEUE_FULL events on a
719  *              specific SCSI device to determine if and when there is a
720  *              need to adjust the queue depth on the device.
721  *
722  * Returns:     0 - No change needed, >0 - Adjust queue depth to this new depth,
723  *              -1 - Drop back to untagged operation using host->cmd_per_lun
724  *                      as the untagged command depth
725  *
726  * Lock Status: None held on entry
727  *
728  * Notes:       Low level drivers may call this at any time and we will do
729  *              "The Right Thing."  We are interrupt context safe.
730  */
731 int scsi_track_queue_full(struct scsi_device *sdev, int depth)
732 {
733
734         /*
735          * Don't let QUEUE_FULLs on the same
736          * jiffies count, they could all be from
737          * same event.
738          */
739         if ((jiffies >> 4) == (sdev->last_queue_full_time >> 4))
740                 return 0;
741
742         sdev->last_queue_full_time = jiffies;
743         if (sdev->last_queue_full_depth != depth) {
744                 sdev->last_queue_full_count = 1;
745                 sdev->last_queue_full_depth = depth;
746         } else {
747                 sdev->last_queue_full_count++;
748         }
749
750         if (sdev->last_queue_full_count <= 10)
751                 return 0;
752         if (sdev->last_queue_full_depth < 8) {
753                 /* Drop back to untagged */
754                 scsi_set_tag_type(sdev, 0);
755                 scsi_adjust_queue_depth(sdev, sdev->host->cmd_per_lun);
756                 return -1;
757         }
758
759         scsi_adjust_queue_depth(sdev, depth);
760         return depth;
761 }
762 EXPORT_SYMBOL(scsi_track_queue_full);
763
764 /**
765  * scsi_change_queue_type() - Change a device's queue type
766  * @sdev:     The SCSI device whose queue depth is to change
767  * @tag_type: Identifier for queue type
768  */
769 int scsi_change_queue_type(struct scsi_device *sdev, int tag_type)
770 {
771         if (!sdev->tagged_supported)
772                 return 0;
773
774         scsi_set_tag_type(sdev, tag_type);
775         return tag_type;
776
777 }
778 EXPORT_SYMBOL(scsi_change_queue_type);
779
780 /**
781  * scsi_vpd_inquiry - Request a device provide us with a VPD page
782  * @sdev: The device to ask
783  * @buffer: Where to put the result
784  * @page: Which Vital Product Data to return
785  * @len: The length of the buffer
786  *
787  * This is an internal helper function.  You probably want to use
788  * scsi_get_vpd_page instead.
789  *
790  * Returns size of the vpd page on success or a negative error number.
791  */
792 static int scsi_vpd_inquiry(struct scsi_device *sdev, unsigned char *buffer,
793                                                         u8 page, unsigned len)
794 {
795         int result;
796         unsigned char cmd[16];
797
798         if (len < 4)
799                 return -EINVAL;
800
801         cmd[0] = INQUIRY;
802         cmd[1] = 1;             /* EVPD */
803         cmd[2] = page;
804         cmd[3] = len >> 8;
805         cmd[4] = len & 0xff;
806         cmd[5] = 0;             /* Control byte */
807
808         /*
809          * I'm not convinced we need to try quite this hard to get VPD, but
810          * all the existing users tried this hard.
811          */
812         result = scsi_execute_req(sdev, cmd, DMA_FROM_DEVICE, buffer,
813                                   len, NULL, 30 * HZ, 3, NULL);
814         if (result)
815                 return -EIO;
816
817         /* Sanity check that we got the page back that we asked for */
818         if (buffer[1] != page)
819                 return -EIO;
820
821         return get_unaligned_be16(&buffer[2]) + 4;
822 }
823
824 /**
825  * scsi_get_vpd_page - Get Vital Product Data from a SCSI device
826  * @sdev: The device to ask
827  * @page: Which Vital Product Data to return
828  * @buf: where to store the VPD
829  * @buf_len: number of bytes in the VPD buffer area
830  *
831  * SCSI devices may optionally supply Vital Product Data.  Each 'page'
832  * of VPD is defined in the appropriate SCSI document (eg SPC, SBC).
833  * If the device supports this VPD page, this routine returns a pointer
834  * to a buffer containing the data from that page.  The caller is
835  * responsible for calling kfree() on this pointer when it is no longer
836  * needed.  If we cannot retrieve the VPD page this routine returns %NULL.
837  */
838 int scsi_get_vpd_page(struct scsi_device *sdev, u8 page, unsigned char *buf,
839                       int buf_len)
840 {
841         int i, result;
842
843         if (sdev->skip_vpd_pages)
844                 goto fail;
845
846         /* Ask for all the pages supported by this device */
847         result = scsi_vpd_inquiry(sdev, buf, 0, buf_len);
848         if (result < 4)
849                 goto fail;
850
851         /* If the user actually wanted this page, we can skip the rest */
852         if (page == 0)
853                 return 0;
854
855         for (i = 4; i < min(result, buf_len); i++)
856                 if (buf[i] == page)
857                         goto found;
858
859         if (i < result && i >= buf_len)
860                 /* ran off the end of the buffer, give us benefit of doubt */
861                 goto found;
862         /* The device claims it doesn't support the requested page */
863         goto fail;
864
865  found:
866         result = scsi_vpd_inquiry(sdev, buf, page, buf_len);
867         if (result < 0)
868                 goto fail;
869
870         return 0;
871
872  fail:
873         return -EINVAL;
874 }
875 EXPORT_SYMBOL_GPL(scsi_get_vpd_page);
876
877 /**
878  * scsi_attach_vpd - Attach Vital Product Data to a SCSI device structure
879  * @sdev: The device to ask
880  *
881  * Attach the 'Device Identification' VPD page (0x83) and the
882  * 'Unit Serial Number' VPD page (0x80) to a SCSI device
883  * structure. This information can be used to identify the device
884  * uniquely.
885  */
886 void scsi_attach_vpd(struct scsi_device *sdev)
887 {
888         int result, i;
889         int vpd_len = SCSI_VPD_PG_LEN;
890         int pg80_supported = 0;
891         int pg83_supported = 0;
892         unsigned char *vpd_buf;
893
894         if (sdev->skip_vpd_pages)
895                 return;
896 retry_pg0:
897         vpd_buf = kmalloc(vpd_len, GFP_KERNEL);
898         if (!vpd_buf)
899                 return;
900
901         /* Ask for all the pages supported by this device */
902         result = scsi_vpd_inquiry(sdev, vpd_buf, 0, vpd_len);
903         if (result < 0) {
904                 kfree(vpd_buf);
905                 return;
906         }
907         if (result > vpd_len) {
908                 vpd_len = result;
909                 kfree(vpd_buf);
910                 goto retry_pg0;
911         }
912
913         for (i = 4; i < result; i++) {
914                 if (vpd_buf[i] == 0x80)
915                         pg80_supported = 1;
916                 if (vpd_buf[i] == 0x83)
917                         pg83_supported = 1;
918         }
919         kfree(vpd_buf);
920         vpd_len = SCSI_VPD_PG_LEN;
921
922         if (pg80_supported) {
923 retry_pg80:
924                 vpd_buf = kmalloc(vpd_len, GFP_KERNEL);
925                 if (!vpd_buf)
926                         return;
927
928                 result = scsi_vpd_inquiry(sdev, vpd_buf, 0x80, vpd_len);
929                 if (result < 0) {
930                         kfree(vpd_buf);
931                         return;
932                 }
933                 if (result > vpd_len) {
934                         vpd_len = result;
935                         kfree(vpd_buf);
936                         goto retry_pg80;
937                 }
938                 sdev->vpd_pg80_len = result;
939                 sdev->vpd_pg80 = vpd_buf;
940                 vpd_len = SCSI_VPD_PG_LEN;
941         }
942
943         if (pg83_supported) {
944 retry_pg83:
945                 vpd_buf = kmalloc(vpd_len, GFP_KERNEL);
946                 if (!vpd_buf)
947                         return;
948
949                 result = scsi_vpd_inquiry(sdev, vpd_buf, 0x83, vpd_len);
950                 if (result < 0) {
951                         kfree(vpd_buf);
952                         return;
953                 }
954                 if (result > vpd_len) {
955                         vpd_len = result;
956                         kfree(vpd_buf);
957                         goto retry_pg83;
958                 }
959                 sdev->vpd_pg83_len = result;
960                 sdev->vpd_pg83 = vpd_buf;
961         }
962 }
963
964 /**
965  * scsi_report_opcode - Find out if a given command opcode is supported
966  * @sdev:       scsi device to query
967  * @buffer:     scratch buffer (must be at least 20 bytes long)
968  * @len:        length of buffer
969  * @opcode:     opcode for command to look up
970  *
971  * Uses the REPORT SUPPORTED OPERATION CODES to look up the given
972  * opcode. Returns -EINVAL if RSOC fails, 0 if the command opcode is
973  * unsupported and 1 if the device claims to support the command.
974  */
975 int scsi_report_opcode(struct scsi_device *sdev, unsigned char *buffer,
976                        unsigned int len, unsigned char opcode)
977 {
978         unsigned char cmd[16];
979         struct scsi_sense_hdr sshdr;
980         int result;
981
982         if (sdev->no_report_opcodes || sdev->scsi_level < SCSI_SPC_3)
983                 return -EINVAL;
984
985         memset(cmd, 0, 16);
986         cmd[0] = MAINTENANCE_IN;
987         cmd[1] = MI_REPORT_SUPPORTED_OPERATION_CODES;
988         cmd[2] = 1;             /* One command format */
989         cmd[3] = opcode;
990         put_unaligned_be32(len, &cmd[6]);
991         memset(buffer, 0, len);
992
993         result = scsi_execute_req(sdev, cmd, DMA_FROM_DEVICE, buffer, len,
994                                   &sshdr, 30 * HZ, 3, NULL);
995
996         if (result && scsi_sense_valid(&sshdr) &&
997             sshdr.sense_key == ILLEGAL_REQUEST &&
998             (sshdr.asc == 0x20 || sshdr.asc == 0x24) && sshdr.ascq == 0x00)
999                 return -EINVAL;
1000
1001         if ((buffer[1] & 3) == 3) /* Command supported */
1002                 return 1;
1003
1004         return 0;
1005 }
1006 EXPORT_SYMBOL(scsi_report_opcode);
1007
1008 /**
1009  * scsi_device_get  -  get an additional reference to a scsi_device
1010  * @sdev:       device to get a reference to
1011  *
1012  * Description: Gets a reference to the scsi_device and increments the use count
1013  * of the underlying LLDD module.  You must hold host_lock of the
1014  * parent Scsi_Host or already have a reference when calling this.
1015  */
1016 int scsi_device_get(struct scsi_device *sdev)
1017 {
1018         if (sdev->sdev_state == SDEV_DEL)
1019                 return -ENXIO;
1020         if (!get_device(&sdev->sdev_gendev))
1021                 return -ENXIO;
1022         /* We can fail this if we're doing SCSI operations
1023          * from module exit (like cache flush) */
1024         try_module_get(sdev->host->hostt->module);
1025
1026         return 0;
1027 }
1028 EXPORT_SYMBOL(scsi_device_get);
1029
1030 /**
1031  * scsi_device_put  -  release a reference to a scsi_device
1032  * @sdev:       device to release a reference on.
1033  *
1034  * Description: Release a reference to the scsi_device and decrements the use
1035  * count of the underlying LLDD module.  The device is freed once the last
1036  * user vanishes.
1037  */
1038 void scsi_device_put(struct scsi_device *sdev)
1039 {
1040 #ifdef CONFIG_MODULE_UNLOAD
1041         struct module *module = sdev->host->hostt->module;
1042
1043         /* The module refcount will be zero if scsi_device_get()
1044          * was called from a module removal routine */
1045         if (module && module_refcount(module) != 0)
1046                 module_put(module);
1047 #endif
1048         put_device(&sdev->sdev_gendev);
1049 }
1050 EXPORT_SYMBOL(scsi_device_put);
1051
1052 /* helper for shost_for_each_device, see that for documentation */
1053 struct scsi_device *__scsi_iterate_devices(struct Scsi_Host *shost,
1054                                            struct scsi_device *prev)
1055 {
1056         struct list_head *list = (prev ? &prev->siblings : &shost->__devices);
1057         struct scsi_device *next = NULL;
1058         unsigned long flags;
1059
1060         spin_lock_irqsave(shost->host_lock, flags);
1061         while (list->next != &shost->__devices) {
1062                 next = list_entry(list->next, struct scsi_device, siblings);
1063                 /* skip devices that we can't get a reference to */
1064                 if (!scsi_device_get(next))
1065                         break;
1066                 next = NULL;
1067                 list = list->next;
1068         }
1069         spin_unlock_irqrestore(shost->host_lock, flags);
1070
1071         if (prev)
1072                 scsi_device_put(prev);
1073         return next;
1074 }
1075 EXPORT_SYMBOL(__scsi_iterate_devices);
1076
1077 /**
1078  * starget_for_each_device  -  helper to walk all devices of a target
1079  * @starget:    target whose devices we want to iterate over.
1080  * @data:       Opaque passed to each function call.
1081  * @fn:         Function to call on each device
1082  *
1083  * This traverses over each device of @starget.  The devices have
1084  * a reference that must be released by scsi_host_put when breaking
1085  * out of the loop.
1086  */
1087 void starget_for_each_device(struct scsi_target *starget, void *data,
1088                      void (*fn)(struct scsi_device *, void *))
1089 {
1090         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
1091         struct scsi_device *sdev;
1092
1093         shost_for_each_device(sdev, shost) {
1094                 if ((sdev->channel == starget->channel) &&
1095                     (sdev->id == starget->id))
1096                         fn(sdev, data);
1097         }
1098 }
1099 EXPORT_SYMBOL(starget_for_each_device);
1100
1101 /**
1102  * __starget_for_each_device - helper to walk all devices of a target (UNLOCKED)
1103  * @starget:    target whose devices we want to iterate over.
1104  * @data:       parameter for callback @fn()
1105  * @fn:         callback function that is invoked for each device
1106  *
1107  * This traverses over each device of @starget.  It does _not_
1108  * take a reference on the scsi_device, so the whole loop must be
1109  * protected by shost->host_lock.
1110  *
1111  * Note:  The only reason why drivers would want to use this is because
1112  * they need to access the device list in irq context.  Otherwise you
1113  * really want to use starget_for_each_device instead.
1114  **/
1115 void __starget_for_each_device(struct scsi_target *starget, void *data,
1116                                void (*fn)(struct scsi_device *, void *))
1117 {
1118         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
1119         struct scsi_device *sdev;
1120
1121         __shost_for_each_device(sdev, shost) {
1122                 if ((sdev->channel == starget->channel) &&
1123                     (sdev->id == starget->id))
1124                         fn(sdev, data);
1125         }
1126 }
1127 EXPORT_SYMBOL(__starget_for_each_device);
1128
1129 /**
1130  * __scsi_device_lookup_by_target - find a device given the target (UNLOCKED)
1131  * @starget:    SCSI target pointer
1132  * @lun:        SCSI Logical Unit Number
1133  *
1134  * Description: Looks up the scsi_device with the specified @lun for a given
1135  * @starget.  The returned scsi_device does not have an additional
1136  * reference.  You must hold the host's host_lock over this call and
1137  * any access to the returned scsi_device. A scsi_device in state
1138  * SDEV_DEL is skipped.
1139  *
1140  * Note:  The only reason why drivers should use this is because
1141  * they need to access the device list in irq context.  Otherwise you
1142  * really want to use scsi_device_lookup_by_target instead.
1143  **/
1144 struct scsi_device *__scsi_device_lookup_by_target(struct scsi_target *starget,
1145                                                    u64 lun)
1146 {
1147         struct scsi_device *sdev;
1148
1149         list_for_each_entry(sdev, &starget->devices, same_target_siblings) {
1150                 if (sdev->sdev_state == SDEV_DEL)
1151                         continue;
1152                 if (sdev->lun ==lun)
1153                         return sdev;
1154         }
1155
1156         return NULL;
1157 }
1158 EXPORT_SYMBOL(__scsi_device_lookup_by_target);
1159
1160 /**
1161  * scsi_device_lookup_by_target - find a device given the target
1162  * @starget:    SCSI target pointer
1163  * @lun:        SCSI Logical Unit Number
1164  *
1165  * Description: Looks up the scsi_device with the specified @lun for a given
1166  * @starget.  The returned scsi_device has an additional reference that
1167  * needs to be released with scsi_device_put once you're done with it.
1168  **/
1169 struct scsi_device *scsi_device_lookup_by_target(struct scsi_target *starget,
1170                                                  u64 lun)
1171 {
1172         struct scsi_device *sdev;
1173         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
1174         unsigned long flags;
1175
1176         spin_lock_irqsave(shost->host_lock, flags);
1177         sdev = __scsi_device_lookup_by_target(starget, lun);
1178         if (sdev && scsi_device_get(sdev))
1179                 sdev = NULL;
1180         spin_unlock_irqrestore(shost->host_lock, flags);
1181
1182         return sdev;
1183 }
1184 EXPORT_SYMBOL(scsi_device_lookup_by_target);
1185
1186 /**
1187  * __scsi_device_lookup - find a device given the host (UNLOCKED)
1188  * @shost:      SCSI host pointer
1189  * @channel:    SCSI channel (zero if only one channel)
1190  * @id:         SCSI target number (physical unit number)
1191  * @lun:        SCSI Logical Unit Number
1192  *
1193  * Description: Looks up the scsi_device with the specified @channel, @id, @lun
1194  * for a given host. The returned scsi_device does not have an additional
1195  * reference.  You must hold the host's host_lock over this call and any access
1196  * to the returned scsi_device.
1197  *
1198  * Note:  The only reason why drivers would want to use this is because
1199  * they need to access the device list in irq context.  Otherwise you
1200  * really want to use scsi_device_lookup instead.
1201  **/
1202 struct scsi_device *__scsi_device_lookup(struct Scsi_Host *shost,
1203                 uint channel, uint id, u64 lun)
1204 {
1205         struct scsi_device *sdev;
1206
1207         list_for_each_entry(sdev, &shost->__devices, siblings) {
1208                 if (sdev->channel == channel && sdev->id == id &&
1209                                 sdev->lun ==lun)
1210                         return sdev;
1211         }
1212
1213         return NULL;
1214 }
1215 EXPORT_SYMBOL(__scsi_device_lookup);
1216
1217 /**
1218  * scsi_device_lookup - find a device given the host
1219  * @shost:      SCSI host pointer
1220  * @channel:    SCSI channel (zero if only one channel)
1221  * @id:         SCSI target number (physical unit number)
1222  * @lun:        SCSI Logical Unit Number
1223  *
1224  * Description: Looks up the scsi_device with the specified @channel, @id, @lun
1225  * for a given host.  The returned scsi_device has an additional reference that
1226  * needs to be released with scsi_device_put once you're done with it.
1227  **/
1228 struct scsi_device *scsi_device_lookup(struct Scsi_Host *shost,
1229                 uint channel, uint id, u64 lun)
1230 {
1231         struct scsi_device *sdev;
1232         unsigned long flags;
1233
1234         spin_lock_irqsave(shost->host_lock, flags);
1235         sdev = __scsi_device_lookup(shost, channel, id, lun);
1236         if (sdev && scsi_device_get(sdev))
1237                 sdev = NULL;
1238         spin_unlock_irqrestore(shost->host_lock, flags);
1239
1240         return sdev;
1241 }
1242 EXPORT_SYMBOL(scsi_device_lookup);
1243
1244 MODULE_DESCRIPTION("SCSI core");
1245 MODULE_LICENSE("GPL");
1246
1247 module_param(scsi_logging_level, int, S_IRUGO|S_IWUSR);
1248 MODULE_PARM_DESC(scsi_logging_level, "a bit mask of logging levels");
1249
1250 #ifdef CONFIG_SCSI_MQ_DEFAULT
1251 bool scsi_use_blk_mq = true;
1252 #else
1253 bool scsi_use_blk_mq = false;
1254 #endif
1255 module_param_named(use_blk_mq, scsi_use_blk_mq, bool, S_IWUSR | S_IRUGO);
1256
1257 static int __init init_scsi(void)
1258 {
1259         int error;
1260
1261         error = scsi_init_queue();
1262         if (error)
1263                 return error;
1264         error = scsi_init_procfs();
1265         if (error)
1266                 goto cleanup_queue;
1267         error = scsi_init_devinfo();
1268         if (error)
1269                 goto cleanup_procfs;
1270         error = scsi_init_hosts();
1271         if (error)
1272                 goto cleanup_devlist;
1273         error = scsi_init_sysctl();
1274         if (error)
1275                 goto cleanup_hosts;
1276         error = scsi_sysfs_register();
1277         if (error)
1278                 goto cleanup_sysctl;
1279
1280         scsi_netlink_init();
1281
1282         printk(KERN_NOTICE "SCSI subsystem initialized\n");
1283         return 0;
1284
1285 cleanup_sysctl:
1286         scsi_exit_sysctl();
1287 cleanup_hosts:
1288         scsi_exit_hosts();
1289 cleanup_devlist:
1290         scsi_exit_devinfo();
1291 cleanup_procfs:
1292         scsi_exit_procfs();
1293 cleanup_queue:
1294         scsi_exit_queue();
1295         printk(KERN_ERR "SCSI subsystem failed to initialize, error = %d\n",
1296                -error);
1297         return error;
1298 }
1299
1300 static void __exit exit_scsi(void)
1301 {
1302         scsi_netlink_exit();
1303         scsi_sysfs_unregister();
1304         scsi_exit_sysctl();
1305         scsi_exit_hosts();
1306         scsi_exit_devinfo();
1307         scsi_exit_procfs();
1308         scsi_exit_queue();
1309         async_unregister_domain(&scsi_sd_probe_domain);
1310 }
1311
1312 subsys_initcall(init_scsi);
1313 module_exit(exit_scsi);