Merge git://git.kernel.org/pub/scm/linux/kernel/git/sfrench/cifs-2.6
[pandora-kernel.git] / drivers / scsi / megaraid / megaraid_mbox.c
1 /*
2  *
3  *                      Linux MegaRAID device driver
4  *
5  * Copyright (c) 2003-2004  LSI Logic Corporation.
6  *
7  *         This program is free software; you can redistribute it and/or
8  *         modify it under the terms of the GNU General Public License
9  *         as published by the Free Software Foundation; either version
10  *         2 of the License, or (at your option) any later version.
11  *
12  * FILE         : megaraid_mbox.c
13  * Version      : v2.20.5.1 (Nov 16 2006)
14  *
15  * Authors:
16  *      Atul Mukker             <Atul.Mukker@lsi.com>
17  *      Sreenivas Bagalkote     <Sreenivas.Bagalkote@lsi.com>
18  *      Manoj Jose              <Manoj.Jose@lsi.com>
19  *      Seokmann Ju
20  *
21  * List of supported controllers
22  *
23  * OEM  Product Name                    VID     DID     SSVID   SSID
24  * ---  ------------                    ---     ---     ----    ----
25  * Dell PERC3/QC                        101E    1960    1028    0471
26  * Dell PERC3/DC                        101E    1960    1028    0493
27  * Dell PERC3/SC                        101E    1960    1028    0475
28  * Dell PERC3/Di                        1028    1960    1028    0123
29  * Dell PERC4/SC                        1000    1960    1028    0520
30  * Dell PERC4/DC                        1000    1960    1028    0518
31  * Dell PERC4/QC                        1000    0407    1028    0531
32  * Dell PERC4/Di                        1028    000F    1028    014A
33  * Dell PERC 4e/Si                      1028    0013    1028    016c
34  * Dell PERC 4e/Di                      1028    0013    1028    016d
35  * Dell PERC 4e/Di                      1028    0013    1028    016e
36  * Dell PERC 4e/Di                      1028    0013    1028    016f
37  * Dell PERC 4e/Di                      1028    0013    1028    0170
38  * Dell PERC 4e/DC                      1000    0408    1028    0002
39  * Dell PERC 4e/SC                      1000    0408    1028    0001
40  *
41  *
42  * LSI MegaRAID SCSI 320-0              1000    1960    1000    A520
43  * LSI MegaRAID SCSI 320-1              1000    1960    1000    0520
44  * LSI MegaRAID SCSI 320-2              1000    1960    1000    0518
45  * LSI MegaRAID SCSI 320-0X             1000    0407    1000    0530
46  * LSI MegaRAID SCSI 320-2X             1000    0407    1000    0532
47  * LSI MegaRAID SCSI 320-4X             1000    0407    1000    0531
48  * LSI MegaRAID SCSI 320-1E             1000    0408    1000    0001
49  * LSI MegaRAID SCSI 320-2E             1000    0408    1000    0002
50  * LSI MegaRAID SATA 150-4              1000    1960    1000    4523
51  * LSI MegaRAID SATA 150-6              1000    1960    1000    0523
52  * LSI MegaRAID SATA 300-4X             1000    0409    1000    3004
53  * LSI MegaRAID SATA 300-8X             1000    0409    1000    3008
54  *
55  * INTEL RAID Controller SRCU42X        1000    0407    8086    0532
56  * INTEL RAID Controller SRCS16         1000    1960    8086    0523
57  * INTEL RAID Controller SRCU42E        1000    0408    8086    0002
58  * INTEL RAID Controller SRCZCRX        1000    0407    8086    0530
59  * INTEL RAID Controller SRCS28X        1000    0409    8086    3008
60  * INTEL RAID Controller SROMBU42E      1000    0408    8086    3431
61  * INTEL RAID Controller SROMBU42E      1000    0408    8086    3499
62  * INTEL RAID Controller SRCU51L        1000    1960    8086    0520
63  *
64  * FSC  MegaRAID PCI Express ROMB       1000    0408    1734    1065
65  *
66  * ACER MegaRAID ROMB-2E                1000    0408    1025    004D
67  *
68  * NEC  MegaRAID PCI Express ROMB       1000    0408    1033    8287
69  *
70  * For history of changes, see Documentation/ChangeLog.megaraid
71  */
72
73 #include "megaraid_mbox.h"
74
75 static int megaraid_init(void);
76 static void megaraid_exit(void);
77
78 static int megaraid_probe_one(struct pci_dev*, const struct pci_device_id *);
79 static void megaraid_detach_one(struct pci_dev *);
80 static void megaraid_mbox_shutdown(struct pci_dev *);
81
82 static int megaraid_io_attach(adapter_t *);
83 static void megaraid_io_detach(adapter_t *);
84
85 static int megaraid_init_mbox(adapter_t *);
86 static void megaraid_fini_mbox(adapter_t *);
87
88 static int megaraid_alloc_cmd_packets(adapter_t *);
89 static void megaraid_free_cmd_packets(adapter_t *);
90
91 static int megaraid_mbox_setup_dma_pools(adapter_t *);
92 static void megaraid_mbox_teardown_dma_pools(adapter_t *);
93
94 static int megaraid_sysfs_alloc_resources(adapter_t *);
95 static void megaraid_sysfs_free_resources(adapter_t *);
96
97 static int megaraid_abort_handler(struct scsi_cmnd *);
98 static int megaraid_reset_handler(struct scsi_cmnd *);
99
100 static int mbox_post_sync_cmd(adapter_t *, uint8_t []);
101 static int mbox_post_sync_cmd_fast(adapter_t *, uint8_t []);
102 static int megaraid_busywait_mbox(mraid_device_t *);
103 static int megaraid_mbox_product_info(adapter_t *);
104 static int megaraid_mbox_extended_cdb(adapter_t *);
105 static int megaraid_mbox_support_ha(adapter_t *, uint16_t *);
106 static int megaraid_mbox_support_random_del(adapter_t *);
107 static int megaraid_mbox_get_max_sg(adapter_t *);
108 static void megaraid_mbox_enum_raid_scsi(adapter_t *);
109 static void megaraid_mbox_flush_cache(adapter_t *);
110 static int megaraid_mbox_fire_sync_cmd(adapter_t *);
111
112 static void megaraid_mbox_display_scb(adapter_t *, scb_t *);
113 static void megaraid_mbox_setup_device_map(adapter_t *);
114
115 static int megaraid_queue_command(struct scsi_cmnd *,
116                 void (*)(struct scsi_cmnd *));
117 static scb_t *megaraid_mbox_build_cmd(adapter_t *, struct scsi_cmnd *, int *);
118 static void megaraid_mbox_runpendq(adapter_t *, scb_t *);
119 static void megaraid_mbox_prepare_pthru(adapter_t *, scb_t *,
120                 struct scsi_cmnd *);
121 static void megaraid_mbox_prepare_epthru(adapter_t *, scb_t *,
122                 struct scsi_cmnd *);
123
124 static irqreturn_t megaraid_isr(int, void *);
125
126 static void megaraid_mbox_dpc(unsigned long);
127
128 static ssize_t megaraid_sysfs_show_app_hndl(struct class_device *, char *);
129 static ssize_t megaraid_sysfs_show_ldnum(struct device *, struct device_attribute *attr, char *);
130
131 static int megaraid_cmm_register(adapter_t *);
132 static int megaraid_cmm_unregister(adapter_t *);
133 static int megaraid_mbox_mm_handler(unsigned long, uioc_t *, uint32_t);
134 static int megaraid_mbox_mm_command(adapter_t *, uioc_t *);
135 static void megaraid_mbox_mm_done(adapter_t *, scb_t *);
136 static int gather_hbainfo(adapter_t *, mraid_hba_info_t *);
137 static int wait_till_fw_empty(adapter_t *);
138
139
140
141 MODULE_AUTHOR("megaraidlinux@lsi.com");
142 MODULE_DESCRIPTION("LSI Logic MegaRAID Mailbox Driver");
143 MODULE_LICENSE("GPL");
144 MODULE_VERSION(MEGARAID_VERSION);
145
146 /*
147  * ### modules parameters for driver ###
148  */
149
150 /*
151  * Set to enable driver to expose unconfigured disk to kernel
152  */
153 static int megaraid_expose_unconf_disks = 0;
154 module_param_named(unconf_disks, megaraid_expose_unconf_disks, int, 0);
155 MODULE_PARM_DESC(unconf_disks,
156         "Set to expose unconfigured disks to kernel (default=0)");
157
158 /*
159  * driver wait time if the adapter's mailbox is busy
160  */
161 static unsigned int max_mbox_busy_wait = MBOX_BUSY_WAIT;
162 module_param_named(busy_wait, max_mbox_busy_wait, int, 0);
163 MODULE_PARM_DESC(busy_wait,
164         "Max wait for mailbox in microseconds if busy (default=10)");
165
166 /*
167  * number of sectors per IO command
168  */
169 static unsigned int megaraid_max_sectors = MBOX_MAX_SECTORS;
170 module_param_named(max_sectors, megaraid_max_sectors, int, 0);
171 MODULE_PARM_DESC(max_sectors,
172         "Maximum number of sectors per IO command (default=128)");
173
174 /*
175  * number of commands per logical unit
176  */
177 static unsigned int megaraid_cmd_per_lun = MBOX_DEF_CMD_PER_LUN;
178 module_param_named(cmd_per_lun, megaraid_cmd_per_lun, int, 0);
179 MODULE_PARM_DESC(cmd_per_lun,
180         "Maximum number of commands per logical unit (default=64)");
181
182
183 /*
184  * Fast driver load option, skip scanning for physical devices during load.
185  * This would result in non-disk devices being skipped during driver load
186  * time. These can be later added though, using /proc/scsi/scsi
187  */
188 static unsigned int megaraid_fast_load = 0;
189 module_param_named(fast_load, megaraid_fast_load, int, 0);
190 MODULE_PARM_DESC(fast_load,
191         "Faster loading of the driver, skips physical devices! (default=0)");
192
193
194 /*
195  * mraid_debug level - threshold for amount of information to be displayed by
196  * the driver. This level can be changed through modules parameters, ioctl or
197  * sysfs/proc interface. By default, print the announcement messages only.
198  */
199 int mraid_debug_level = CL_ANN;
200 module_param_named(debug_level, mraid_debug_level, int, 0);
201 MODULE_PARM_DESC(debug_level, "Debug level for driver (default=0)");
202
203 /*
204  * ### global data ###
205  */
206 static uint8_t megaraid_mbox_version[8] =
207         { 0x02, 0x20, 0x04, 0x06, 3, 7, 20, 5 };
208
209
210 /*
211  * PCI table for all supported controllers.
212  */
213 static struct pci_device_id pci_id_table_g[] =  {
214         {
215                 PCI_VENDOR_ID_DELL,
216                 PCI_DEVICE_ID_PERC4_DI_DISCOVERY,
217                 PCI_VENDOR_ID_DELL,
218                 PCI_SUBSYS_ID_PERC4_DI_DISCOVERY,
219         },
220         {
221                 PCI_VENDOR_ID_LSI_LOGIC,
222                 PCI_DEVICE_ID_PERC4_SC,
223                 PCI_VENDOR_ID_DELL,
224                 PCI_SUBSYS_ID_PERC4_SC,
225         },
226         {
227                 PCI_VENDOR_ID_LSI_LOGIC,
228                 PCI_DEVICE_ID_PERC4_DC,
229                 PCI_VENDOR_ID_DELL,
230                 PCI_SUBSYS_ID_PERC4_DC,
231         },
232         {
233                 PCI_VENDOR_ID_LSI_LOGIC,
234                 PCI_DEVICE_ID_VERDE,
235                 PCI_ANY_ID,
236                 PCI_ANY_ID,
237         },
238         {
239                 PCI_VENDOR_ID_DELL,
240                 PCI_DEVICE_ID_PERC4_DI_EVERGLADES,
241                 PCI_VENDOR_ID_DELL,
242                 PCI_SUBSYS_ID_PERC4_DI_EVERGLADES,
243         },
244         {
245                 PCI_VENDOR_ID_DELL,
246                 PCI_DEVICE_ID_PERC4E_SI_BIGBEND,
247                 PCI_VENDOR_ID_DELL,
248                 PCI_SUBSYS_ID_PERC4E_SI_BIGBEND,
249         },
250         {
251                 PCI_VENDOR_ID_DELL,
252                 PCI_DEVICE_ID_PERC4E_DI_KOBUK,
253                 PCI_VENDOR_ID_DELL,
254                 PCI_SUBSYS_ID_PERC4E_DI_KOBUK,
255         },
256         {
257                 PCI_VENDOR_ID_DELL,
258                 PCI_DEVICE_ID_PERC4E_DI_CORVETTE,
259                 PCI_VENDOR_ID_DELL,
260                 PCI_SUBSYS_ID_PERC4E_DI_CORVETTE,
261         },
262         {
263                 PCI_VENDOR_ID_DELL,
264                 PCI_DEVICE_ID_PERC4E_DI_EXPEDITION,
265                 PCI_VENDOR_ID_DELL,
266                 PCI_SUBSYS_ID_PERC4E_DI_EXPEDITION,
267         },
268         {
269                 PCI_VENDOR_ID_DELL,
270                 PCI_DEVICE_ID_PERC4E_DI_GUADALUPE,
271                 PCI_VENDOR_ID_DELL,
272                 PCI_SUBSYS_ID_PERC4E_DI_GUADALUPE,
273         },
274         {
275                 PCI_VENDOR_ID_LSI_LOGIC,
276                 PCI_DEVICE_ID_DOBSON,
277                 PCI_ANY_ID,
278                 PCI_ANY_ID,
279         },
280         {
281                 PCI_VENDOR_ID_AMI,
282                 PCI_DEVICE_ID_AMI_MEGARAID3,
283                 PCI_ANY_ID,
284                 PCI_ANY_ID,
285         },
286         {
287                 PCI_VENDOR_ID_LSI_LOGIC,
288                 PCI_DEVICE_ID_AMI_MEGARAID3,
289                 PCI_ANY_ID,
290                 PCI_ANY_ID,
291         },
292         {
293                 PCI_VENDOR_ID_LSI_LOGIC,
294                 PCI_DEVICE_ID_LINDSAY,
295                 PCI_ANY_ID,
296                 PCI_ANY_ID,
297         },
298         {0}     /* Terminating entry */
299 };
300 MODULE_DEVICE_TABLE(pci, pci_id_table_g);
301
302
303 static struct pci_driver megaraid_pci_driver = {
304         .name           = "megaraid",
305         .id_table       = pci_id_table_g,
306         .probe          = megaraid_probe_one,
307         .remove         = __devexit_p(megaraid_detach_one),
308         .shutdown       = megaraid_mbox_shutdown,
309 };
310
311
312
313 // definitions for the device attributes for exporting logical drive number
314 // for a scsi address (Host, Channel, Id, Lun)
315
316 CLASS_DEVICE_ATTR(megaraid_mbox_app_hndl, S_IRUSR, megaraid_sysfs_show_app_hndl,
317                 NULL);
318
319 // Host template initializer for megaraid mbox sysfs device attributes
320 static struct class_device_attribute *megaraid_shost_attrs[] = {
321         &class_device_attr_megaraid_mbox_app_hndl,
322         NULL,
323 };
324
325
326 DEVICE_ATTR(megaraid_mbox_ld, S_IRUSR, megaraid_sysfs_show_ldnum, NULL);
327
328 // Host template initializer for megaraid mbox sysfs device attributes
329 static struct device_attribute *megaraid_sdev_attrs[] = {
330         &dev_attr_megaraid_mbox_ld,
331         NULL,
332 };
333
334 /**
335  * megaraid_change_queue_depth - Change the device's queue depth
336  * @sdev:       scsi device struct
337  * @qdepth:     depth to set
338  *
339  * Return value:
340  *      actual depth set
341  */
342 static int megaraid_change_queue_depth(struct scsi_device *sdev, int qdepth)
343 {
344         if (qdepth > MBOX_MAX_SCSI_CMDS)
345                 qdepth = MBOX_MAX_SCSI_CMDS;
346         scsi_adjust_queue_depth(sdev, 0, qdepth);
347         return sdev->queue_depth;
348 }
349
350 /*
351  * Scsi host template for megaraid unified driver
352  */
353 static struct scsi_host_template megaraid_template_g = {
354         .module                         = THIS_MODULE,
355         .name                           = "LSI Logic MegaRAID driver",
356         .proc_name                      = "megaraid",
357         .queuecommand                   = megaraid_queue_command,
358         .eh_abort_handler               = megaraid_abort_handler,
359         .eh_device_reset_handler        = megaraid_reset_handler,
360         .eh_bus_reset_handler           = megaraid_reset_handler,
361         .eh_host_reset_handler          = megaraid_reset_handler,
362         .change_queue_depth             = megaraid_change_queue_depth,
363         .use_clustering                 = ENABLE_CLUSTERING,
364         .use_sg_chaining                = ENABLE_SG_CHAINING,
365         .sdev_attrs                     = megaraid_sdev_attrs,
366         .shost_attrs                    = megaraid_shost_attrs,
367 };
368
369
370 /**
371  * megaraid_init - module load hook
372  *
373  * We register ourselves as hotplug enabled module and let PCI subsystem
374  * discover our adapters.
375  */
376 static int __init
377 megaraid_init(void)
378 {
379         int     rval;
380
381         // Announce the driver version
382         con_log(CL_ANN, (KERN_INFO "megaraid: %s %s\n", MEGARAID_VERSION,
383                 MEGARAID_EXT_VERSION));
384
385         // check validity of module parameters
386         if (megaraid_cmd_per_lun > MBOX_MAX_SCSI_CMDS) {
387
388                 con_log(CL_ANN, (KERN_WARNING
389                         "megaraid mailbox: max commands per lun reset to %d\n",
390                         MBOX_MAX_SCSI_CMDS));
391
392                 megaraid_cmd_per_lun = MBOX_MAX_SCSI_CMDS;
393         }
394
395
396         // register as a PCI hot-plug driver module
397         rval = pci_register_driver(&megaraid_pci_driver);
398         if (rval < 0) {
399                 con_log(CL_ANN, (KERN_WARNING
400                         "megaraid: could not register hotplug support.\n"));
401         }
402
403         return rval;
404 }
405
406
407 /**
408  * megaraid_exit - driver unload entry point
409  *
410  * We simply unwrap the megaraid_init routine here.
411  */
412 static void __exit
413 megaraid_exit(void)
414 {
415         con_log(CL_DLEVEL1, (KERN_NOTICE "megaraid: unloading framework\n"));
416
417         // unregister as PCI hotplug driver
418         pci_unregister_driver(&megaraid_pci_driver);
419
420         return;
421 }
422
423
424 /**
425  * megaraid_probe_one - PCI hotplug entry point
426  * @pdev        : handle to this controller's PCI configuration space
427  * @id          : pci device id of the class of controllers
428  *
429  * This routine should be called whenever a new adapter is detected by the
430  * PCI hotplug susbsystem.
431  */
432 static int __devinit
433 megaraid_probe_one(struct pci_dev *pdev, const struct pci_device_id *id)
434 {
435         adapter_t       *adapter;
436
437
438         // detected a new controller
439         con_log(CL_ANN, (KERN_INFO
440                 "megaraid: probe new device %#4.04x:%#4.04x:%#4.04x:%#4.04x: ",
441                 pdev->vendor, pdev->device, pdev->subsystem_vendor,
442                 pdev->subsystem_device));
443
444         con_log(CL_ANN, ("bus %d:slot %d:func %d\n", pdev->bus->number,
445                 PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn)));
446
447         if (pci_enable_device(pdev)) {
448                 con_log(CL_ANN, (KERN_WARNING
449                                 "megaraid: pci_enable_device failed\n"));
450
451                 return -ENODEV;
452         }
453
454         // Enable bus-mastering on this controller
455         pci_set_master(pdev);
456
457         // Allocate the per driver initialization structure
458         adapter = kzalloc(sizeof(adapter_t), GFP_KERNEL);
459
460         if (adapter == NULL) {
461                 con_log(CL_ANN, (KERN_WARNING
462                 "megaraid: out of memory, %s %d.\n", __FUNCTION__, __LINE__));
463
464                 goto out_probe_one;
465         }
466
467
468         // set up PCI related soft state and other pre-known parameters
469         adapter->unique_id      = pdev->bus->number << 8 | pdev->devfn;
470         adapter->irq            = pdev->irq;
471         adapter->pdev           = pdev;
472
473         atomic_set(&adapter->being_detached, 0);
474
475         // Setup the default DMA mask. This would be changed later on
476         // depending on hardware capabilities
477         if (pci_set_dma_mask(adapter->pdev, DMA_32BIT_MASK) != 0) {
478
479                 con_log(CL_ANN, (KERN_WARNING
480                         "megaraid: pci_set_dma_mask failed:%d\n", __LINE__));
481
482                 goto out_free_adapter;
483         }
484
485
486         // Initialize the synchronization lock for kernel and LLD
487         spin_lock_init(&adapter->lock);
488
489         // Initialize the command queues: the list of free SCBs and the list
490         // of pending SCBs.
491         INIT_LIST_HEAD(&adapter->kscb_pool);
492         spin_lock_init(SCSI_FREE_LIST_LOCK(adapter));
493
494         INIT_LIST_HEAD(&adapter->pend_list);
495         spin_lock_init(PENDING_LIST_LOCK(adapter));
496
497         INIT_LIST_HEAD(&adapter->completed_list);
498         spin_lock_init(COMPLETED_LIST_LOCK(adapter));
499
500
501         // Start the mailbox based controller
502         if (megaraid_init_mbox(adapter) != 0) {
503                 con_log(CL_ANN, (KERN_WARNING
504                         "megaraid: maibox adapter did not initialize\n"));
505
506                 goto out_free_adapter;
507         }
508
509         // Register with LSI Common Management Module
510         if (megaraid_cmm_register(adapter) != 0) {
511
512                 con_log(CL_ANN, (KERN_WARNING
513                 "megaraid: could not register with management module\n"));
514
515                 goto out_fini_mbox;
516         }
517
518         // setup adapter handle in PCI soft state
519         pci_set_drvdata(pdev, adapter);
520
521         // attach with scsi mid-layer
522         if (megaraid_io_attach(adapter) != 0) {
523
524                 con_log(CL_ANN, (KERN_WARNING "megaraid: io attach failed\n"));
525
526                 goto out_cmm_unreg;
527         }
528
529         return 0;
530
531 out_cmm_unreg:
532         pci_set_drvdata(pdev, NULL);
533         megaraid_cmm_unregister(adapter);
534 out_fini_mbox:
535         megaraid_fini_mbox(adapter);
536 out_free_adapter:
537         kfree(adapter);
538 out_probe_one:
539         pci_disable_device(pdev);
540
541         return -ENODEV;
542 }
543
544
545 /**
546  * megaraid_detach_one - release framework resources and call LLD release routine
547  * @pdev        : handle for our PCI cofiguration space
548  *
549  * This routine is called during driver unload. We free all the allocated
550  * resources and call the corresponding LLD so that it can also release all
551  * its resources.
552  *
553  * This routine is also called from the PCI hotplug system.
554  */
555 static void
556 megaraid_detach_one(struct pci_dev *pdev)
557 {
558         adapter_t               *adapter;
559         struct Scsi_Host        *host;
560
561
562         // Start a rollback on this adapter
563         adapter = pci_get_drvdata(pdev);
564
565         if (!adapter) {
566                 con_log(CL_ANN, (KERN_CRIT
567                 "megaraid: Invalid detach on %#4.04x:%#4.04x:%#4.04x:%#4.04x\n",
568                         pdev->vendor, pdev->device, pdev->subsystem_vendor,
569                         pdev->subsystem_device));
570
571                 return;
572         }
573         else {
574                 con_log(CL_ANN, (KERN_NOTICE
575                 "megaraid: detaching device %#4.04x:%#4.04x:%#4.04x:%#4.04x\n",
576                         pdev->vendor, pdev->device, pdev->subsystem_vendor,
577                         pdev->subsystem_device));
578         }
579
580
581         host = adapter->host;
582
583         // do not allow any more requests from the management module for this
584         // adapter.
585         // FIXME: How do we account for the request which might still be
586         // pending with us?
587         atomic_set(&adapter->being_detached, 1);
588
589         // detach from the IO sub-system
590         megaraid_io_detach(adapter);
591
592         // reset the device state in the PCI structure. We check this
593         // condition when we enter here. If the device state is NULL,
594         // that would mean the device has already been removed
595         pci_set_drvdata(pdev, NULL);
596
597         // Unregister from common management module
598         //
599         // FIXME: this must return success or failure for conditions if there
600         // is a command pending with LLD or not.
601         megaraid_cmm_unregister(adapter);
602
603         // finalize the mailbox based controller and release all resources
604         megaraid_fini_mbox(adapter);
605
606         kfree(adapter);
607
608         scsi_host_put(host);
609
610         pci_disable_device(pdev);
611
612         return;
613 }
614
615
616 /**
617  * megaraid_mbox_shutdown - PCI shutdown for megaraid HBA
618  * @pdev                : generic driver model device
619  *
620  * Shutdown notification, perform flush cache.
621  */
622 static void
623 megaraid_mbox_shutdown(struct pci_dev *pdev)
624 {
625         adapter_t               *adapter = pci_get_drvdata(pdev);
626         static int              counter;
627
628         if (!adapter) {
629                 con_log(CL_ANN, (KERN_WARNING
630                         "megaraid: null device in shutdown\n"));
631                 return;
632         }
633
634         // flush caches now
635         con_log(CL_ANN, (KERN_INFO "megaraid: flushing adapter %d...",
636                 counter++));
637
638         megaraid_mbox_flush_cache(adapter);
639
640         con_log(CL_ANN, ("done\n"));
641 }
642
643
644 /**
645  * megaraid_io_attach - attach a device with the IO subsystem
646  * @adapter             : controller's soft state
647  *
648  * Attach this device with the IO subsystem.
649  */
650 static int
651 megaraid_io_attach(adapter_t *adapter)
652 {
653         struct Scsi_Host        *host;
654
655         // Initialize SCSI Host structure
656         host = scsi_host_alloc(&megaraid_template_g, 8);
657         if (!host) {
658                 con_log(CL_ANN, (KERN_WARNING
659                         "megaraid mbox: scsi_register failed\n"));
660
661                 return -1;
662         }
663
664         SCSIHOST2ADAP(host)     = (caddr_t)adapter;
665         adapter->host           = host;
666
667         host->irq               = adapter->irq;
668         host->unique_id         = adapter->unique_id;
669         host->can_queue         = adapter->max_cmds;
670         host->this_id           = adapter->init_id;
671         host->sg_tablesize      = adapter->sglen;
672         host->max_sectors       = adapter->max_sectors;
673         host->cmd_per_lun       = adapter->cmd_per_lun;
674         host->max_channel       = adapter->max_channel;
675         host->max_id            = adapter->max_target;
676         host->max_lun           = adapter->max_lun;
677
678
679         // notify mid-layer about the new controller
680         if (scsi_add_host(host, &adapter->pdev->dev)) {
681
682                 con_log(CL_ANN, (KERN_WARNING
683                         "megaraid mbox: scsi_add_host failed\n"));
684
685                 scsi_host_put(host);
686
687                 return -1;
688         }
689
690         scsi_scan_host(host);
691
692         return 0;
693 }
694
695
696 /**
697  * megaraid_io_detach - detach a device from the IO subsystem
698  * @adapter             : controller's soft state
699  *
700  * Detach this device from the IO subsystem.
701  */
702 static void
703 megaraid_io_detach(adapter_t *adapter)
704 {
705         struct Scsi_Host        *host;
706
707         con_log(CL_DLEVEL1, (KERN_INFO "megaraid: io detach\n"));
708
709         host = adapter->host;
710
711         scsi_remove_host(host);
712
713         return;
714 }
715
716
717 /*
718  * START: Mailbox Low Level Driver
719  *
720  * This is section specific to the single mailbox based controllers
721  */
722
723 /**
724  * megaraid_init_mbox - initialize controller
725  * @adapter             : our soft state
726  *
727  * - Allocate 16-byte aligned mailbox memory for firmware handshake
728  * - Allocate controller's memory resources
729  * - Find out all initialization data
730  * - Allocate memory required for all the commands
731  * - Use internal library of FW routines, build up complete soft state
732  */
733 static int __devinit
734 megaraid_init_mbox(adapter_t *adapter)
735 {
736         struct pci_dev          *pdev;
737         mraid_device_t          *raid_dev;
738         int                     i;
739         uint32_t                magic64;
740
741
742         adapter->ito    = MBOX_TIMEOUT;
743         pdev            = adapter->pdev;
744
745         /*
746          * Allocate and initialize the init data structure for mailbox
747          * controllers
748          */
749         raid_dev = kzalloc(sizeof(mraid_device_t), GFP_KERNEL);
750         if (raid_dev == NULL) return -1;
751
752
753         /*
754          * Attach the adapter soft state to raid device soft state
755          */
756         adapter->raid_device    = (caddr_t)raid_dev;
757         raid_dev->fast_load     = megaraid_fast_load;
758
759
760         // our baseport
761         raid_dev->baseport = pci_resource_start(pdev, 0);
762
763         if (pci_request_regions(pdev, "MegaRAID: LSI Logic Corporation") != 0) {
764
765                 con_log(CL_ANN, (KERN_WARNING
766                                 "megaraid: mem region busy\n"));
767
768                 goto out_free_raid_dev;
769         }
770
771         raid_dev->baseaddr = ioremap_nocache(raid_dev->baseport, 128);
772
773         if (!raid_dev->baseaddr) {
774
775                 con_log(CL_ANN, (KERN_WARNING
776                         "megaraid: could not map hba memory\n") );
777
778                 goto out_release_regions;
779         }
780
781         /* initialize the mutual exclusion lock for the mailbox */
782         spin_lock_init(&raid_dev->mailbox_lock);
783
784         /* allocate memory required for commands */
785         if (megaraid_alloc_cmd_packets(adapter) != 0)
786                 goto out_iounmap;
787
788         /*
789          * Issue SYNC cmd to flush the pending cmds in the adapter
790          * and initialize its internal state
791          */
792
793         if (megaraid_mbox_fire_sync_cmd(adapter))
794                 con_log(CL_ANN, ("megaraid: sync cmd failed\n"));
795
796         /*
797          * Setup the rest of the soft state using the library of
798          * FW routines
799          */
800
801         /* request IRQ and register the interrupt service routine */
802         if (request_irq(adapter->irq, megaraid_isr, IRQF_SHARED, "megaraid",
803                 adapter)) {
804
805                 con_log(CL_ANN, (KERN_WARNING
806                         "megaraid: Couldn't register IRQ %d!\n", adapter->irq));
807                 goto out_alloc_cmds;
808
809         }
810
811         // Product info
812         if (megaraid_mbox_product_info(adapter) != 0)
813                 goto out_free_irq;
814
815         // Do we support extended CDBs
816         adapter->max_cdb_sz = 10;
817         if (megaraid_mbox_extended_cdb(adapter) == 0) {
818                 adapter->max_cdb_sz = 16;
819         }
820
821         /*
822          * Do we support cluster environment, if we do, what is the initiator
823          * id.
824          * NOTE: In a non-cluster aware firmware environment, the LLD should
825          * return 7 as initiator id.
826          */
827         adapter->ha             = 0;
828         adapter->init_id        = -1;
829         if (megaraid_mbox_support_ha(adapter, &adapter->init_id) == 0) {
830                 adapter->ha = 1;
831         }
832
833         /*
834          * Prepare the device ids array to have the mapping between the kernel
835          * device address and megaraid device address.
836          * We export the physical devices on their actual addresses. The
837          * logical drives are exported on a virtual SCSI channel
838          */
839         megaraid_mbox_setup_device_map(adapter);
840
841         // If the firmware supports random deletion, update the device id map
842         if (megaraid_mbox_support_random_del(adapter)) {
843
844                 // Change the logical drives numbers in device_ids array one
845                 // slot in device_ids is reserved for target id, that's why
846                 // "<=" below
847                 for (i = 0; i <= MAX_LOGICAL_DRIVES_40LD; i++) {
848                         adapter->device_ids[adapter->max_channel][i] += 0x80;
849                 }
850                 adapter->device_ids[adapter->max_channel][adapter->init_id] =
851                         0xFF;
852
853                 raid_dev->random_del_supported = 1;
854         }
855
856         /*
857          * find out the maximum number of scatter-gather elements supported by
858          * this firmware
859          */
860         adapter->sglen = megaraid_mbox_get_max_sg(adapter);
861
862         // enumerate RAID and SCSI channels so that all devices on SCSI
863         // channels can later be exported, including disk devices
864         megaraid_mbox_enum_raid_scsi(adapter);
865
866         /*
867          * Other parameters required by upper layer
868          *
869          * maximum number of sectors per IO command
870          */
871         adapter->max_sectors = megaraid_max_sectors;
872
873         /*
874          * number of queued commands per LUN.
875          */
876         adapter->cmd_per_lun = megaraid_cmd_per_lun;
877
878         /*
879          * Allocate resources required to issue FW calls, when sysfs is
880          * accessed
881          */
882         if (megaraid_sysfs_alloc_resources(adapter) != 0)
883                 goto out_free_irq;
884
885         // Set the DMA mask to 64-bit. All supported controllers as capable of
886         // DMA in this range
887         pci_read_config_dword(adapter->pdev, PCI_CONF_AMISIG64, &magic64);
888
889         if (((magic64 == HBA_SIGNATURE_64_BIT) &&
890                 ((adapter->pdev->subsystem_device !=
891                 PCI_SUBSYS_ID_MEGARAID_SATA_150_6) &&
892                 (adapter->pdev->subsystem_device !=
893                 PCI_SUBSYS_ID_MEGARAID_SATA_150_4))) ||
894                 (adapter->pdev->vendor == PCI_VENDOR_ID_LSI_LOGIC &&
895                 adapter->pdev->device == PCI_DEVICE_ID_VERDE) ||
896                 (adapter->pdev->vendor == PCI_VENDOR_ID_LSI_LOGIC &&
897                 adapter->pdev->device == PCI_DEVICE_ID_DOBSON) ||
898                 (adapter->pdev->vendor == PCI_VENDOR_ID_LSI_LOGIC &&
899                 adapter->pdev->device == PCI_DEVICE_ID_LINDSAY) ||
900                 (adapter->pdev->vendor == PCI_VENDOR_ID_DELL &&
901                 adapter->pdev->device == PCI_DEVICE_ID_PERC4_DI_EVERGLADES) ||
902                 (adapter->pdev->vendor == PCI_VENDOR_ID_DELL &&
903                 adapter->pdev->device == PCI_DEVICE_ID_PERC4E_DI_KOBUK)) {
904                 if (pci_set_dma_mask(adapter->pdev, DMA_64BIT_MASK)) {
905                         con_log(CL_ANN, (KERN_WARNING
906                                 "megaraid: DMA mask for 64-bit failed\n"));
907
908                         if (pci_set_dma_mask (adapter->pdev, DMA_32BIT_MASK)) {
909                                 con_log(CL_ANN, (KERN_WARNING
910                                         "megaraid: 32-bit DMA mask failed\n"));
911                                 goto out_free_sysfs_res;
912                         }
913                 }
914         }
915
916         // setup tasklet for DPC
917         tasklet_init(&adapter->dpc_h, megaraid_mbox_dpc,
918                         (unsigned long)adapter);
919
920         con_log(CL_DLEVEL1, (KERN_INFO
921                 "megaraid mbox hba successfully initialized\n"));
922
923         return 0;
924
925 out_free_sysfs_res:
926         megaraid_sysfs_free_resources(adapter);
927 out_free_irq:
928         free_irq(adapter->irq, adapter);
929 out_alloc_cmds:
930         megaraid_free_cmd_packets(adapter);
931 out_iounmap:
932         iounmap(raid_dev->baseaddr);
933 out_release_regions:
934         pci_release_regions(pdev);
935 out_free_raid_dev:
936         kfree(raid_dev);
937
938         return -1;
939 }
940
941
942 /**
943  * megaraid_fini_mbox - undo controller initialization
944  * @adapter             : our soft state
945  */
946 static void
947 megaraid_fini_mbox(adapter_t *adapter)
948 {
949         mraid_device_t *raid_dev = ADAP2RAIDDEV(adapter);
950
951         // flush all caches
952         megaraid_mbox_flush_cache(adapter);
953
954         tasklet_kill(&adapter->dpc_h);
955
956         megaraid_sysfs_free_resources(adapter);
957
958         megaraid_free_cmd_packets(adapter);
959
960         free_irq(adapter->irq, adapter);
961
962         iounmap(raid_dev->baseaddr);
963
964         pci_release_regions(adapter->pdev);
965
966         kfree(raid_dev);
967
968         return;
969 }
970
971
972 /**
973  * megaraid_alloc_cmd_packets - allocate shared mailbox
974  * @adapter             : soft state of the raid controller
975  *
976  * Allocate and align the shared mailbox. This maibox is used to issue
977  * all the commands. For IO based controllers, the mailbox is also regsitered
978  * with the FW. Allocate memory for all commands as well.
979  * This is our big allocator.
980  */
981 static int
982 megaraid_alloc_cmd_packets(adapter_t *adapter)
983 {
984         mraid_device_t          *raid_dev = ADAP2RAIDDEV(adapter);
985         struct pci_dev          *pdev;
986         unsigned long           align;
987         scb_t                   *scb;
988         mbox_ccb_t              *ccb;
989         struct mraid_pci_blk    *epthru_pci_blk;
990         struct mraid_pci_blk    *sg_pci_blk;
991         struct mraid_pci_blk    *mbox_pci_blk;
992         int                     i;
993
994         pdev = adapter->pdev;
995
996         /*
997          * Setup the mailbox
998          * Allocate the common 16-byte aligned memory for the handshake
999          * mailbox.
1000          */
1001         raid_dev->una_mbox64 = pci_alloc_consistent(adapter->pdev,
1002                         sizeof(mbox64_t), &raid_dev->una_mbox64_dma);
1003
1004         if (!raid_dev->una_mbox64) {
1005                 con_log(CL_ANN, (KERN_WARNING
1006                         "megaraid: out of memory, %s %d\n", __FUNCTION__,
1007                         __LINE__));
1008                 return -1;
1009         }
1010         memset(raid_dev->una_mbox64, 0, sizeof(mbox64_t));
1011
1012         /*
1013          * Align the mailbox at 16-byte boundary
1014          */
1015         raid_dev->mbox  = &raid_dev->una_mbox64->mbox32;
1016
1017         raid_dev->mbox  = (mbox_t *)((((unsigned long)raid_dev->mbox) + 15) &
1018                                 (~0UL ^ 0xFUL));
1019
1020         raid_dev->mbox64 = (mbox64_t *)(((unsigned long)raid_dev->mbox) - 8);
1021
1022         align = ((void *)raid_dev->mbox -
1023                         ((void *)&raid_dev->una_mbox64->mbox32));
1024
1025         raid_dev->mbox_dma = (unsigned long)raid_dev->una_mbox64_dma + 8 +
1026                         align;
1027
1028         // Allocate memory for commands issued internally
1029         adapter->ibuf = pci_alloc_consistent(pdev, MBOX_IBUF_SIZE,
1030                                 &adapter->ibuf_dma_h);
1031         if (!adapter->ibuf) {
1032
1033                 con_log(CL_ANN, (KERN_WARNING
1034                         "megaraid: out of memory, %s %d\n", __FUNCTION__,
1035                         __LINE__));
1036
1037                 goto out_free_common_mbox;
1038         }
1039         memset(adapter->ibuf, 0, MBOX_IBUF_SIZE);
1040
1041         // Allocate memory for our SCSI Command Blocks and their associated
1042         // memory
1043
1044         /*
1045          * Allocate memory for the base list of scb. Later allocate memory for
1046          * CCBs and embedded components of each CCB and point the pointers in
1047          * scb to the allocated components
1048          * NOTE: The code to allocate SCB will be duplicated in all the LLD
1049          * since the calling routine does not yet know the number of available
1050          * commands.
1051          */
1052         adapter->kscb_list = kcalloc(MBOX_MAX_SCSI_CMDS, sizeof(scb_t), GFP_KERNEL);
1053
1054         if (adapter->kscb_list == NULL) {
1055                 con_log(CL_ANN, (KERN_WARNING
1056                         "megaraid: out of memory, %s %d\n", __FUNCTION__,
1057                         __LINE__));
1058                 goto out_free_ibuf;
1059         }
1060
1061         // memory allocation for our command packets
1062         if (megaraid_mbox_setup_dma_pools(adapter) != 0) {
1063                 con_log(CL_ANN, (KERN_WARNING
1064                         "megaraid: out of memory, %s %d\n", __FUNCTION__,
1065                         __LINE__));
1066                 goto out_free_scb_list;
1067         }
1068
1069         // Adjust the scb pointers and link in the free pool
1070         epthru_pci_blk  = raid_dev->epthru_pool;
1071         sg_pci_blk      = raid_dev->sg_pool;
1072         mbox_pci_blk    = raid_dev->mbox_pool;
1073
1074         for (i = 0; i < MBOX_MAX_SCSI_CMDS; i++) {
1075                 scb                     = adapter->kscb_list + i;
1076                 ccb                     = raid_dev->ccb_list + i;
1077
1078                 ccb->mbox       = (mbox_t *)(mbox_pci_blk[i].vaddr + 16);
1079                 ccb->raw_mbox   = (uint8_t *)ccb->mbox;
1080                 ccb->mbox64     = (mbox64_t *)(mbox_pci_blk[i].vaddr + 8);
1081                 ccb->mbox_dma_h = (unsigned long)mbox_pci_blk[i].dma_addr + 16;
1082
1083                 // make sure the mailbox is aligned properly
1084                 if (ccb->mbox_dma_h & 0x0F) {
1085                         con_log(CL_ANN, (KERN_CRIT
1086                                 "megaraid mbox: not aligned on 16-bytes\n"));
1087
1088                         goto out_teardown_dma_pools;
1089                 }
1090
1091                 ccb->epthru             = (mraid_epassthru_t *)
1092                                                 epthru_pci_blk[i].vaddr;
1093                 ccb->epthru_dma_h       = epthru_pci_blk[i].dma_addr;
1094                 ccb->pthru              = (mraid_passthru_t *)ccb->epthru;
1095                 ccb->pthru_dma_h        = ccb->epthru_dma_h;
1096
1097
1098                 ccb->sgl64              = (mbox_sgl64 *)sg_pci_blk[i].vaddr;
1099                 ccb->sgl_dma_h          = sg_pci_blk[i].dma_addr;
1100                 ccb->sgl32              = (mbox_sgl32 *)ccb->sgl64;
1101
1102                 scb->ccb                = (caddr_t)ccb;
1103                 scb->gp                 = 0;
1104
1105                 scb->sno                = i;    // command index
1106
1107                 scb->scp                = NULL;
1108                 scb->state              = SCB_FREE;
1109                 scb->dma_direction      = PCI_DMA_NONE;
1110                 scb->dma_type           = MRAID_DMA_NONE;
1111                 scb->dev_channel        = -1;
1112                 scb->dev_target         = -1;
1113
1114                 // put scb in the free pool
1115                 list_add_tail(&scb->list, &adapter->kscb_pool);
1116         }
1117
1118         return 0;
1119
1120 out_teardown_dma_pools:
1121         megaraid_mbox_teardown_dma_pools(adapter);
1122 out_free_scb_list:
1123         kfree(adapter->kscb_list);
1124 out_free_ibuf:
1125         pci_free_consistent(pdev, MBOX_IBUF_SIZE, (void *)adapter->ibuf,
1126                 adapter->ibuf_dma_h);
1127 out_free_common_mbox:
1128         pci_free_consistent(adapter->pdev, sizeof(mbox64_t),
1129                 (caddr_t)raid_dev->una_mbox64, raid_dev->una_mbox64_dma);
1130
1131         return -1;
1132 }
1133
1134
1135 /**
1136  * megaraid_free_cmd_packets - free memory
1137  * @adapter             : soft state of the raid controller
1138  *
1139  * Release memory resources allocated for commands.
1140  */
1141 static void
1142 megaraid_free_cmd_packets(adapter_t *adapter)
1143 {
1144         mraid_device_t *raid_dev = ADAP2RAIDDEV(adapter);
1145
1146         megaraid_mbox_teardown_dma_pools(adapter);
1147
1148         kfree(adapter->kscb_list);
1149
1150         pci_free_consistent(adapter->pdev, MBOX_IBUF_SIZE,
1151                 (void *)adapter->ibuf, adapter->ibuf_dma_h);
1152
1153         pci_free_consistent(adapter->pdev, sizeof(mbox64_t),
1154                 (caddr_t)raid_dev->una_mbox64, raid_dev->una_mbox64_dma);
1155         return;
1156 }
1157
1158
1159 /**
1160  * megaraid_mbox_setup_dma_pools - setup dma pool for command packets
1161  * @adapter             : HBA soft state
1162  *
1163  * Setup the dma pools for mailbox, passthru and extended passthru structures,
1164  * and scatter-gather lists.
1165  */
1166 static int
1167 megaraid_mbox_setup_dma_pools(adapter_t *adapter)
1168 {
1169         mraid_device_t          *raid_dev = ADAP2RAIDDEV(adapter);
1170         struct mraid_pci_blk    *epthru_pci_blk;
1171         struct mraid_pci_blk    *sg_pci_blk;
1172         struct mraid_pci_blk    *mbox_pci_blk;
1173         int                     i;
1174
1175
1176
1177         // Allocate memory for 16-bytes aligned mailboxes
1178         raid_dev->mbox_pool_handle = pci_pool_create("megaraid mbox pool",
1179                                                 adapter->pdev,
1180                                                 sizeof(mbox64_t) + 16,
1181                                                 16, 0);
1182
1183         if (raid_dev->mbox_pool_handle == NULL) {
1184                 goto fail_setup_dma_pool;
1185         }
1186
1187         mbox_pci_blk = raid_dev->mbox_pool;
1188         for (i = 0; i < MBOX_MAX_SCSI_CMDS; i++) {
1189                 mbox_pci_blk[i].vaddr = pci_pool_alloc(
1190                                                 raid_dev->mbox_pool_handle,
1191                                                 GFP_KERNEL,
1192                                                 &mbox_pci_blk[i].dma_addr);
1193                 if (!mbox_pci_blk[i].vaddr) {
1194                         goto fail_setup_dma_pool;
1195                 }
1196         }
1197
1198         /*
1199          * Allocate memory for each embedded passthru strucuture pointer
1200          * Request for a 128 bytes aligned structure for each passthru command
1201          * structure
1202          * Since passthru and extended passthru commands are exclusive, they
1203          * share common memory pool. Passthru structures piggyback on memory
1204          * allocted to extended passthru since passthru is smaller of the two
1205          */
1206         raid_dev->epthru_pool_handle = pci_pool_create("megaraid mbox pthru",
1207                         adapter->pdev, sizeof(mraid_epassthru_t), 128, 0);
1208
1209         if (raid_dev->epthru_pool_handle == NULL) {
1210                 goto fail_setup_dma_pool;
1211         }
1212
1213         epthru_pci_blk = raid_dev->epthru_pool;
1214         for (i = 0; i < MBOX_MAX_SCSI_CMDS; i++) {
1215                 epthru_pci_blk[i].vaddr = pci_pool_alloc(
1216                                                 raid_dev->epthru_pool_handle,
1217                                                 GFP_KERNEL,
1218                                                 &epthru_pci_blk[i].dma_addr);
1219                 if (!epthru_pci_blk[i].vaddr) {
1220                         goto fail_setup_dma_pool;
1221                 }
1222         }
1223
1224
1225         // Allocate memory for each scatter-gather list. Request for 512 bytes
1226         // alignment for each sg list
1227         raid_dev->sg_pool_handle = pci_pool_create("megaraid mbox sg",
1228                                         adapter->pdev,
1229                                         sizeof(mbox_sgl64) * MBOX_MAX_SG_SIZE,
1230                                         512, 0);
1231
1232         if (raid_dev->sg_pool_handle == NULL) {
1233                 goto fail_setup_dma_pool;
1234         }
1235
1236         sg_pci_blk = raid_dev->sg_pool;
1237         for (i = 0; i < MBOX_MAX_SCSI_CMDS; i++) {
1238                 sg_pci_blk[i].vaddr = pci_pool_alloc(
1239                                                 raid_dev->sg_pool_handle,
1240                                                 GFP_KERNEL,
1241                                                 &sg_pci_blk[i].dma_addr);
1242                 if (!sg_pci_blk[i].vaddr) {
1243                         goto fail_setup_dma_pool;
1244                 }
1245         }
1246
1247         return 0;
1248
1249 fail_setup_dma_pool:
1250         megaraid_mbox_teardown_dma_pools(adapter);
1251         return -1;
1252 }
1253
1254
1255 /**
1256  * megaraid_mbox_teardown_dma_pools - teardown dma pools for command packets
1257  * @adapter             : HBA soft state
1258  *
1259  * Teardown the dma pool for mailbox, passthru and extended passthru
1260  * structures, and scatter-gather lists.
1261  */
1262 static void
1263 megaraid_mbox_teardown_dma_pools(adapter_t *adapter)
1264 {
1265         mraid_device_t          *raid_dev = ADAP2RAIDDEV(adapter);
1266         struct mraid_pci_blk    *epthru_pci_blk;
1267         struct mraid_pci_blk    *sg_pci_blk;
1268         struct mraid_pci_blk    *mbox_pci_blk;
1269         int                     i;
1270
1271
1272         sg_pci_blk = raid_dev->sg_pool;
1273         for (i = 0; i < MBOX_MAX_SCSI_CMDS && sg_pci_blk[i].vaddr; i++) {
1274                 pci_pool_free(raid_dev->sg_pool_handle, sg_pci_blk[i].vaddr,
1275                         sg_pci_blk[i].dma_addr);
1276         }
1277         if (raid_dev->sg_pool_handle)
1278                 pci_pool_destroy(raid_dev->sg_pool_handle);
1279
1280
1281         epthru_pci_blk = raid_dev->epthru_pool;
1282         for (i = 0; i < MBOX_MAX_SCSI_CMDS && epthru_pci_blk[i].vaddr; i++) {
1283                 pci_pool_free(raid_dev->epthru_pool_handle,
1284                         epthru_pci_blk[i].vaddr, epthru_pci_blk[i].dma_addr);
1285         }
1286         if (raid_dev->epthru_pool_handle)
1287                 pci_pool_destroy(raid_dev->epthru_pool_handle);
1288
1289
1290         mbox_pci_blk = raid_dev->mbox_pool;
1291         for (i = 0; i < MBOX_MAX_SCSI_CMDS && mbox_pci_blk[i].vaddr; i++) {
1292                 pci_pool_free(raid_dev->mbox_pool_handle,
1293                         mbox_pci_blk[i].vaddr, mbox_pci_blk[i].dma_addr);
1294         }
1295         if (raid_dev->mbox_pool_handle)
1296                 pci_pool_destroy(raid_dev->mbox_pool_handle);
1297
1298         return;
1299 }
1300
1301
1302 /**
1303  * megaraid_alloc_scb - detach and return a scb from the free list
1304  * @adapter     : controller's soft state
1305  * @scp         : pointer to the scsi command to be executed
1306  *
1307  * Return the scb from the head of the free list. %NULL if there are none
1308  * available.
1309  */
1310 static scb_t *
1311 megaraid_alloc_scb(adapter_t *adapter, struct scsi_cmnd *scp)
1312 {
1313         struct list_head        *head = &adapter->kscb_pool;
1314         scb_t                   *scb = NULL;
1315         unsigned long           flags;
1316
1317         // detach scb from free pool
1318         spin_lock_irqsave(SCSI_FREE_LIST_LOCK(adapter), flags);
1319
1320         if (list_empty(head)) {
1321                 spin_unlock_irqrestore(SCSI_FREE_LIST_LOCK(adapter), flags);
1322                 return NULL;
1323         }
1324
1325         scb = list_entry(head->next, scb_t, list);
1326         list_del_init(&scb->list);
1327
1328         spin_unlock_irqrestore(SCSI_FREE_LIST_LOCK(adapter), flags);
1329
1330         scb->state      = SCB_ACTIVE;
1331         scb->scp        = scp;
1332         scb->dma_type   = MRAID_DMA_NONE;
1333
1334         return scb;
1335 }
1336
1337
1338 /**
1339  * megaraid_dealloc_scb - return the scb to the free pool
1340  * @adapter     : controller's soft state
1341  * @scb         : scb to be freed
1342  *
1343  * Return the scb back to the free list of scbs. The caller must 'flush' the
1344  * SCB before calling us. E.g., performing pci_unamp and/or pci_sync etc.
1345  * NOTE NOTE: Make sure the scb is not on any list before calling this
1346  * routine.
1347  */
1348 static inline void
1349 megaraid_dealloc_scb(adapter_t *adapter, scb_t *scb)
1350 {
1351         unsigned long           flags;
1352
1353         // put scb in the free pool
1354         scb->state      = SCB_FREE;
1355         scb->scp        = NULL;
1356         spin_lock_irqsave(SCSI_FREE_LIST_LOCK(adapter), flags);
1357
1358         list_add(&scb->list, &adapter->kscb_pool);
1359
1360         spin_unlock_irqrestore(SCSI_FREE_LIST_LOCK(adapter), flags);
1361
1362         return;
1363 }
1364
1365
1366 /**
1367  * megaraid_mbox_mksgl - make the scatter-gather list
1368  * @adapter     : controller's soft state
1369  * @scb         : scsi control block
1370  *
1371  * Prepare the scatter-gather list.
1372  */
1373 static int
1374 megaraid_mbox_mksgl(adapter_t *adapter, scb_t *scb)
1375 {
1376         struct scatterlist      *sgl;
1377         mbox_ccb_t              *ccb;
1378         struct scsi_cmnd        *scp;
1379         int                     sgcnt;
1380         int                     i;
1381
1382
1383         scp     = scb->scp;
1384         ccb     = (mbox_ccb_t *)scb->ccb;
1385
1386         sgcnt = scsi_dma_map(scp);
1387         BUG_ON(sgcnt < 0 || sgcnt > adapter->sglen);
1388
1389         // no mapping required if no data to be transferred
1390         if (!sgcnt)
1391                 return 0;
1392
1393         scb->dma_type = MRAID_DMA_WSG;
1394
1395         scsi_for_each_sg(scp, sgl, sgcnt, i) {
1396                 ccb->sgl64[i].address   = sg_dma_address(sgl);
1397                 ccb->sgl64[i].length    = sg_dma_len(sgl);
1398         }
1399
1400         // Return count of SG nodes
1401         return sgcnt;
1402 }
1403
1404
1405 /**
1406  * mbox_post_cmd - issue a mailbox command
1407  * @adapter     : controller's soft state
1408  * @scb         : command to be issued
1409  *
1410  * Post the command to the controller if mailbox is available.
1411  */
1412 static int
1413 mbox_post_cmd(adapter_t *adapter, scb_t *scb)
1414 {
1415         mraid_device_t  *raid_dev = ADAP2RAIDDEV(adapter);
1416         mbox64_t        *mbox64;
1417         mbox_t          *mbox;
1418         mbox_ccb_t      *ccb;
1419         unsigned long   flags;
1420         unsigned int    i = 0;
1421
1422
1423         ccb     = (mbox_ccb_t *)scb->ccb;
1424         mbox    = raid_dev->mbox;
1425         mbox64  = raid_dev->mbox64;
1426
1427         /*
1428          * Check for busy mailbox. If it is, return failure - the caller
1429          * should retry later.
1430          */
1431         spin_lock_irqsave(MAILBOX_LOCK(raid_dev), flags);
1432
1433         if (unlikely(mbox->busy)) {
1434                 do {
1435                         udelay(1);
1436                         i++;
1437                         rmb();
1438                 } while(mbox->busy && (i < max_mbox_busy_wait));
1439
1440                 if (mbox->busy) {
1441
1442                         spin_unlock_irqrestore(MAILBOX_LOCK(raid_dev), flags);
1443
1444                         return -1;
1445                 }
1446         }
1447
1448
1449         // Copy this command's mailbox data into "adapter's" mailbox
1450         memcpy((caddr_t)mbox64, (caddr_t)ccb->mbox64, 22);
1451         mbox->cmdid = scb->sno;
1452
1453         adapter->outstanding_cmds++;
1454
1455         if (scb->dma_direction == PCI_DMA_TODEVICE)
1456                 pci_dma_sync_sg_for_device(adapter->pdev,
1457                                            scsi_sglist(scb->scp),
1458                                            scsi_sg_count(scb->scp),
1459                                            PCI_DMA_TODEVICE);
1460
1461         mbox->busy      = 1;    // Set busy
1462         mbox->poll      = 0;
1463         mbox->ack       = 0;
1464         wmb();
1465
1466         WRINDOOR(raid_dev, raid_dev->mbox_dma | 0x1);
1467
1468         spin_unlock_irqrestore(MAILBOX_LOCK(raid_dev), flags);
1469
1470         return 0;
1471 }
1472
1473
1474 /**
1475  * megaraid_queue_command - generic queue entry point for all LLDs
1476  * @scp         : pointer to the scsi command to be executed
1477  * @done        : callback routine to be called after the cmd has be completed
1478  *
1479  * Queue entry point for mailbox based controllers.
1480  */
1481 static int
1482 megaraid_queue_command(struct scsi_cmnd *scp, void (*done)(struct scsi_cmnd *))
1483 {
1484         adapter_t       *adapter;
1485         scb_t           *scb;
1486         int             if_busy;
1487
1488         adapter         = SCP2ADAPTER(scp);
1489         scp->scsi_done  = done;
1490         scp->result     = 0;
1491
1492         /*
1493          * Allocate and build a SCB request
1494          * if_busy flag will be set if megaraid_mbox_build_cmd() command could
1495          * not allocate scb. We will return non-zero status in that case.
1496          * NOTE: scb can be null even though certain commands completed
1497          * successfully, e.g., MODE_SENSE and TEST_UNIT_READY, it would
1498          * return 0 in that case, and we would do the callback right away.
1499          */
1500         if_busy = 0;
1501         scb = megaraid_mbox_build_cmd(adapter, scp, &if_busy);
1502         if (!scb) {     // command already completed
1503                 done(scp);
1504                 return 0;
1505         }
1506
1507         megaraid_mbox_runpendq(adapter, scb);
1508         return if_busy;
1509 }
1510
1511 /**
1512  * megaraid_mbox_build_cmd - transform the mid-layer scsi commands
1513  * @adapter     : controller's soft state
1514  * @scp         : mid-layer scsi command pointer
1515  * @busy        : set if request could not be completed because of lack of
1516  *              resources
1517  *
1518  * Transform the mid-layer scsi command to megaraid firmware lingua.
1519  * Convert the command issued by mid-layer to format understood by megaraid
1520  * firmware. We also complete certain commands without sending them to firmware.
1521  */
1522 static scb_t *
1523 megaraid_mbox_build_cmd(adapter_t *adapter, struct scsi_cmnd *scp, int *busy)
1524 {
1525         mraid_device_t          *rdev = ADAP2RAIDDEV(adapter);
1526         int                     channel;
1527         int                     target;
1528         int                     islogical;
1529         mbox_ccb_t              *ccb;
1530         mraid_passthru_t        *pthru;
1531         mbox64_t                *mbox64;
1532         mbox_t                  *mbox;
1533         scb_t                   *scb;
1534         char                    skip[] = "skipping";
1535         char                    scan[] = "scanning";
1536         char                    *ss;
1537
1538
1539         /*
1540          * Get the appropriate device map for the device this command is
1541          * intended for
1542          */
1543         MRAID_GET_DEVICE_MAP(adapter, scp, channel, target, islogical);
1544
1545         /*
1546          * Logical drive commands
1547          */
1548         if (islogical) {
1549                 switch (scp->cmnd[0]) {
1550                 case TEST_UNIT_READY:
1551                         /*
1552                          * Do we support clustering and is the support enabled
1553                          * If no, return success always
1554                          */
1555                         if (!adapter->ha) {
1556                                 scp->result = (DID_OK << 16);
1557                                 return NULL;
1558                         }
1559
1560                         if (!(scb = megaraid_alloc_scb(adapter, scp))) {
1561                                 scp->result = (DID_ERROR << 16);
1562                                 *busy = 1;
1563                                 return NULL;
1564                         }
1565
1566                         scb->dma_direction      = scp->sc_data_direction;
1567                         scb->dev_channel        = 0xFF;
1568                         scb->dev_target         = target;
1569                         ccb                     = (mbox_ccb_t *)scb->ccb;
1570
1571                         /*
1572                          * The command id will be provided by the command
1573                          * issuance routine
1574                          */
1575                         ccb->raw_mbox[0]        = CLUSTER_CMD;
1576                         ccb->raw_mbox[2]        = RESERVATION_STATUS;
1577                         ccb->raw_mbox[3]        = target;
1578
1579                         return scb;
1580
1581                 case MODE_SENSE:
1582                 {
1583                         struct scatterlist      *sgl;
1584                         caddr_t                 vaddr;
1585
1586                         sgl = scsi_sglist(scp);
1587                         if (sg_page(sgl)) {
1588                                 vaddr = (caddr_t) sg_virt(&sgl[0]);
1589
1590                                 memset(vaddr, 0, scp->cmnd[4]);
1591                         }
1592                         else {
1593                                 con_log(CL_ANN, (KERN_WARNING
1594                                                  "megaraid mailbox: invalid sg:%d\n",
1595                                                  __LINE__));
1596                         }
1597                 }
1598                 scp->result = (DID_OK << 16);
1599                 return NULL;
1600
1601                 case INQUIRY:
1602                         /*
1603                          * Display the channel scan for logical drives
1604                          * Do not display scan for a channel if already done.
1605                          */
1606                         if (!(rdev->last_disp & (1L << SCP2CHANNEL(scp)))) {
1607
1608                                 con_log(CL_ANN, (KERN_INFO
1609                                         "scsi[%d]: scanning scsi channel %d",
1610                                         adapter->host->host_no,
1611                                         SCP2CHANNEL(scp)));
1612
1613                                 con_log(CL_ANN, (
1614                                         " [virtual] for logical drives\n"));
1615
1616                                 rdev->last_disp |= (1L << SCP2CHANNEL(scp));
1617                         }
1618
1619                         if (scp->cmnd[1] & MEGA_SCSI_INQ_EVPD) {
1620                                 scp->sense_buffer[0] = 0x70;
1621                                 scp->sense_buffer[2] = ILLEGAL_REQUEST;
1622                                 scp->sense_buffer[12] = MEGA_INVALID_FIELD_IN_CDB;
1623                                 scp->result = CHECK_CONDITION << 1;
1624                                 return NULL;
1625                         }
1626
1627                         /* Fall through */
1628
1629                 case READ_CAPACITY:
1630                         /*
1631                          * Do not allow LUN > 0 for logical drives and
1632                          * requests for more than 40 logical drives
1633                          */
1634                         if (SCP2LUN(scp)) {
1635                                 scp->result = (DID_BAD_TARGET << 16);
1636                                 return NULL;
1637                         }
1638                         if ((target % 0x80) >= MAX_LOGICAL_DRIVES_40LD) {
1639                                 scp->result = (DID_BAD_TARGET << 16);
1640                                 return NULL;
1641                         }
1642
1643
1644                         /* Allocate a SCB and initialize passthru */
1645                         if (!(scb = megaraid_alloc_scb(adapter, scp))) {
1646                                 scp->result = (DID_ERROR << 16);
1647                                 *busy = 1;
1648                                 return NULL;
1649                         }
1650
1651                         ccb                     = (mbox_ccb_t *)scb->ccb;
1652                         scb->dev_channel        = 0xFF;
1653                         scb->dev_target         = target;
1654                         pthru                   = ccb->pthru;
1655                         mbox                    = ccb->mbox;
1656                         mbox64                  = ccb->mbox64;
1657
1658                         pthru->timeout          = 0;
1659                         pthru->ars              = 1;
1660                         pthru->reqsenselen      = 14;
1661                         pthru->islogical        = 1;
1662                         pthru->logdrv           = target;
1663                         pthru->cdblen           = scp->cmd_len;
1664                         memcpy(pthru->cdb, scp->cmnd, scp->cmd_len);
1665
1666                         mbox->cmd               = MBOXCMD_PASSTHRU64;
1667                         scb->dma_direction      = scp->sc_data_direction;
1668
1669                         pthru->dataxferlen      = scsi_bufflen(scp);
1670                         pthru->dataxferaddr     = ccb->sgl_dma_h;
1671                         pthru->numsge           = megaraid_mbox_mksgl(adapter,
1672                                                         scb);
1673
1674                         mbox->xferaddr          = 0xFFFFFFFF;
1675                         mbox64->xferaddr_lo     = (uint32_t )ccb->pthru_dma_h;
1676                         mbox64->xferaddr_hi     = 0;
1677
1678                         return scb;
1679
1680                 case READ_6:
1681                 case WRITE_6:
1682                 case READ_10:
1683                 case WRITE_10:
1684                 case READ_12:
1685                 case WRITE_12:
1686
1687                         /*
1688                          * Allocate a SCB and initialize mailbox
1689                          */
1690                         if (!(scb = megaraid_alloc_scb(adapter, scp))) {
1691                                 scp->result = (DID_ERROR << 16);
1692                                 *busy = 1;
1693                                 return NULL;
1694                         }
1695                         ccb                     = (mbox_ccb_t *)scb->ccb;
1696                         scb->dev_channel        = 0xFF;
1697                         scb->dev_target         = target;
1698                         mbox                    = ccb->mbox;
1699                         mbox64                  = ccb->mbox64;
1700                         mbox->logdrv            = target;
1701
1702                         /*
1703                          * A little HACK: 2nd bit is zero for all scsi read
1704                          * commands and is set for all scsi write commands
1705                          */
1706                         mbox->cmd = (scp->cmnd[0] & 0x02) ?  MBOXCMD_LWRITE64:
1707                                         MBOXCMD_LREAD64 ;
1708
1709                         /*
1710                          * 6-byte READ(0x08) or WRITE(0x0A) cdb
1711                          */
1712                         if (scp->cmd_len == 6) {
1713                                 mbox->numsectors = (uint32_t)scp->cmnd[4];
1714                                 mbox->lba =
1715                                         ((uint32_t)scp->cmnd[1] << 16)  |
1716                                         ((uint32_t)scp->cmnd[2] << 8)   |
1717                                         (uint32_t)scp->cmnd[3];
1718
1719                                 mbox->lba &= 0x1FFFFF;
1720                         }
1721
1722                         /*
1723                          * 10-byte READ(0x28) or WRITE(0x2A) cdb
1724                          */
1725                         else if (scp->cmd_len == 10) {
1726                                 mbox->numsectors =
1727                                         (uint32_t)scp->cmnd[8] |
1728                                         ((uint32_t)scp->cmnd[7] << 8);
1729                                 mbox->lba =
1730                                         ((uint32_t)scp->cmnd[2] << 24) |
1731                                         ((uint32_t)scp->cmnd[3] << 16) |
1732                                         ((uint32_t)scp->cmnd[4] << 8) |
1733                                         (uint32_t)scp->cmnd[5];
1734                         }
1735
1736                         /*
1737                          * 12-byte READ(0xA8) or WRITE(0xAA) cdb
1738                          */
1739                         else if (scp->cmd_len == 12) {
1740                                 mbox->lba =
1741                                         ((uint32_t)scp->cmnd[2] << 24) |
1742                                         ((uint32_t)scp->cmnd[3] << 16) |
1743                                         ((uint32_t)scp->cmnd[4] << 8) |
1744                                         (uint32_t)scp->cmnd[5];
1745
1746                                 mbox->numsectors =
1747                                         ((uint32_t)scp->cmnd[6] << 24) |
1748                                         ((uint32_t)scp->cmnd[7] << 16) |
1749                                         ((uint32_t)scp->cmnd[8] << 8) |
1750                                         (uint32_t)scp->cmnd[9];
1751                         }
1752                         else {
1753                                 con_log(CL_ANN, (KERN_WARNING
1754                                         "megaraid: unsupported CDB length\n"));
1755
1756                                 megaraid_dealloc_scb(adapter, scb);
1757
1758                                 scp->result = (DID_ERROR << 16);
1759                                 return NULL;
1760                         }
1761
1762                         scb->dma_direction = scp->sc_data_direction;
1763
1764                         // Calculate Scatter-Gather info
1765                         mbox64->xferaddr_lo     = (uint32_t )ccb->sgl_dma_h;
1766                         mbox->numsge            = megaraid_mbox_mksgl(adapter,
1767                                                         scb);
1768                         mbox->xferaddr          = 0xFFFFFFFF;
1769                         mbox64->xferaddr_hi     = 0;
1770
1771                         return scb;
1772
1773                 case RESERVE:
1774                 case RELEASE:
1775                         /*
1776                          * Do we support clustering and is the support enabled
1777                          */
1778                         if (!adapter->ha) {
1779                                 scp->result = (DID_BAD_TARGET << 16);
1780                                 return NULL;
1781                         }
1782
1783                         /*
1784                          * Allocate a SCB and initialize mailbox
1785                          */
1786                         if (!(scb = megaraid_alloc_scb(adapter, scp))) {
1787                                 scp->result = (DID_ERROR << 16);
1788                                 *busy = 1;
1789                                 return NULL;
1790                         }
1791
1792                         ccb                     = (mbox_ccb_t *)scb->ccb;
1793                         scb->dev_channel        = 0xFF;
1794                         scb->dev_target         = target;
1795                         ccb->raw_mbox[0]        = CLUSTER_CMD;
1796                         ccb->raw_mbox[2]        =  (scp->cmnd[0] == RESERVE) ?
1797                                                 RESERVE_LD : RELEASE_LD;
1798
1799                         ccb->raw_mbox[3]        = target;
1800                         scb->dma_direction      = scp->sc_data_direction;
1801
1802                         return scb;
1803
1804                 default:
1805                         scp->result = (DID_BAD_TARGET << 16);
1806                         return NULL;
1807                 }
1808         }
1809         else { // Passthru device commands
1810
1811                 // Do not allow access to target id > 15 or LUN > 7
1812                 if (target > 15 || SCP2LUN(scp) > 7) {
1813                         scp->result = (DID_BAD_TARGET << 16);
1814                         return NULL;
1815                 }
1816
1817                 // if fast load option was set and scan for last device is
1818                 // over, reset the fast_load flag so that during a possible
1819                 // next scan, devices can be made available
1820                 if (rdev->fast_load && (target == 15) &&
1821                         (SCP2CHANNEL(scp) == adapter->max_channel -1)) {
1822
1823                         con_log(CL_ANN, (KERN_INFO
1824                         "megaraid[%d]: physical device scan re-enabled\n",
1825                                 adapter->host->host_no));
1826                         rdev->fast_load = 0;
1827                 }
1828
1829                 /*
1830                  * Display the channel scan for physical devices
1831                  */
1832                 if (!(rdev->last_disp & (1L << SCP2CHANNEL(scp)))) {
1833
1834                         ss = rdev->fast_load ? skip : scan;
1835
1836                         con_log(CL_ANN, (KERN_INFO
1837                                 "scsi[%d]: %s scsi channel %d [Phy %d]",
1838                                 adapter->host->host_no, ss, SCP2CHANNEL(scp),
1839                                 channel));
1840
1841                         con_log(CL_ANN, (
1842                                 " for non-raid devices\n"));
1843
1844                         rdev->last_disp |= (1L << SCP2CHANNEL(scp));
1845                 }
1846
1847                 // disable channel sweep if fast load option given
1848                 if (rdev->fast_load) {
1849                         scp->result = (DID_BAD_TARGET << 16);
1850                         return NULL;
1851                 }
1852
1853                 // Allocate a SCB and initialize passthru
1854                 if (!(scb = megaraid_alloc_scb(adapter, scp))) {
1855                         scp->result = (DID_ERROR << 16);
1856                         *busy = 1;
1857                         return NULL;
1858                 }
1859
1860                 ccb                     = (mbox_ccb_t *)scb->ccb;
1861                 scb->dev_channel        = channel;
1862                 scb->dev_target         = target;
1863                 scb->dma_direction      = scp->sc_data_direction;
1864                 mbox                    = ccb->mbox;
1865                 mbox64                  = ccb->mbox64;
1866
1867                 // Does this firmware support extended CDBs
1868                 if (adapter->max_cdb_sz == 16) {
1869                         mbox->cmd               = MBOXCMD_EXTPTHRU;
1870
1871                         megaraid_mbox_prepare_epthru(adapter, scb, scp);
1872
1873                         mbox64->xferaddr_lo     = (uint32_t)ccb->epthru_dma_h;
1874                         mbox64->xferaddr_hi     = 0;
1875                         mbox->xferaddr          = 0xFFFFFFFF;
1876                 }
1877                 else {
1878                         mbox->cmd = MBOXCMD_PASSTHRU64;
1879
1880                         megaraid_mbox_prepare_pthru(adapter, scb, scp);
1881
1882                         mbox64->xferaddr_lo     = (uint32_t)ccb->pthru_dma_h;
1883                         mbox64->xferaddr_hi     = 0;
1884                         mbox->xferaddr          = 0xFFFFFFFF;
1885                 }
1886                 return scb;
1887         }
1888
1889         // NOT REACHED
1890 }
1891
1892
1893 /**
1894  * megaraid_mbox_runpendq - execute commands queued in the pending queue
1895  * @adapter     : controller's soft state
1896  * @scb_q       : SCB to be queued in the pending list
1897  *
1898  * Scan the pending list for commands which are not yet issued and try to
1899  * post to the controller. The SCB can be a null pointer, which would indicate
1900  * no SCB to be queue, just try to execute the ones in the pending list.
1901  *
1902  * NOTE: We do not actually traverse the pending list. The SCBs are plucked
1903  * out from the head of the pending list. If it is successfully issued, the
1904  * next SCB is at the head now.
1905  */
1906 static void
1907 megaraid_mbox_runpendq(adapter_t *adapter, scb_t *scb_q)
1908 {
1909         scb_t                   *scb;
1910         unsigned long           flags;
1911
1912         spin_lock_irqsave(PENDING_LIST_LOCK(adapter), flags);
1913
1914         if (scb_q) {
1915                 scb_q->state = SCB_PENDQ;
1916                 list_add_tail(&scb_q->list, &adapter->pend_list);
1917         }
1918
1919         // if the adapter in not in quiescent mode, post the commands to FW
1920         if (adapter->quiescent) {
1921                 spin_unlock_irqrestore(PENDING_LIST_LOCK(adapter), flags);
1922                 return;
1923         }
1924
1925         while (!list_empty(&adapter->pend_list)) {
1926
1927                 assert_spin_locked(PENDING_LIST_LOCK(adapter));
1928
1929                 scb = list_entry(adapter->pend_list.next, scb_t, list);
1930
1931                 // remove the scb from the pending list and try to
1932                 // issue. If we are unable to issue it, put back in
1933                 // the pending list and return
1934
1935                 list_del_init(&scb->list);
1936
1937                 spin_unlock_irqrestore(PENDING_LIST_LOCK(adapter), flags);
1938
1939                 // if mailbox was busy, return SCB back to pending
1940                 // list. Make sure to add at the head, since that's
1941                 // where it would have been removed from
1942
1943                 scb->state = SCB_ISSUED;
1944
1945                 if (mbox_post_cmd(adapter, scb) != 0) {
1946
1947                         spin_lock_irqsave(PENDING_LIST_LOCK(adapter), flags);
1948
1949                         scb->state = SCB_PENDQ;
1950
1951                         list_add(&scb->list, &adapter->pend_list);
1952
1953                         spin_unlock_irqrestore(PENDING_LIST_LOCK(adapter),
1954                                 flags);
1955
1956                         return;
1957                 }
1958
1959                 spin_lock_irqsave(PENDING_LIST_LOCK(adapter), flags);
1960         }
1961
1962         spin_unlock_irqrestore(PENDING_LIST_LOCK(adapter), flags);
1963
1964
1965         return;
1966 }
1967
1968
1969 /**
1970  * megaraid_mbox_prepare_pthru - prepare a command for physical devices
1971  * @adapter     : pointer to controller's soft state
1972  * @scb         : scsi control block
1973  * @scp         : scsi command from the mid-layer
1974  *
1975  * Prepare a command for the scsi physical devices.
1976  */
1977 static void
1978 megaraid_mbox_prepare_pthru(adapter_t *adapter, scb_t *scb,
1979                 struct scsi_cmnd *scp)
1980 {
1981         mbox_ccb_t              *ccb;
1982         mraid_passthru_t        *pthru;
1983         uint8_t                 channel;
1984         uint8_t                 target;
1985
1986         ccb     = (mbox_ccb_t *)scb->ccb;
1987         pthru   = ccb->pthru;
1988         channel = scb->dev_channel;
1989         target  = scb->dev_target;
1990
1991         // 0=6sec, 1=60sec, 2=10min, 3=3hrs, 4=NO timeout
1992         pthru->timeout          = 4;    
1993         pthru->ars              = 1;
1994         pthru->islogical        = 0;
1995         pthru->channel          = 0;
1996         pthru->target           = (channel << 4) | target;
1997         pthru->logdrv           = SCP2LUN(scp);
1998         pthru->reqsenselen      = 14;
1999         pthru->cdblen           = scp->cmd_len;
2000
2001         memcpy(pthru->cdb, scp->cmnd, scp->cmd_len);
2002
2003         if (scsi_bufflen(scp)) {
2004                 pthru->dataxferlen      = scsi_bufflen(scp);
2005                 pthru->dataxferaddr     = ccb->sgl_dma_h;
2006                 pthru->numsge           = megaraid_mbox_mksgl(adapter, scb);
2007         }
2008         else {
2009                 pthru->dataxferaddr     = 0;
2010                 pthru->dataxferlen      = 0;
2011                 pthru->numsge           = 0;
2012         }
2013         return;
2014 }
2015
2016
2017 /**
2018  * megaraid_mbox_prepare_epthru - prepare a command for physical devices
2019  * @adapter     : pointer to controller's soft state
2020  * @scb         : scsi control block
2021  * @scp         : scsi command from the mid-layer
2022  *
2023  * Prepare a command for the scsi physical devices. This rountine prepares
2024  * commands for devices which can take extended CDBs (>10 bytes).
2025  */
2026 static void
2027 megaraid_mbox_prepare_epthru(adapter_t *adapter, scb_t *scb,
2028                 struct scsi_cmnd *scp)
2029 {
2030         mbox_ccb_t              *ccb;
2031         mraid_epassthru_t       *epthru;
2032         uint8_t                 channel;
2033         uint8_t                 target;
2034
2035         ccb     = (mbox_ccb_t *)scb->ccb;
2036         epthru  = ccb->epthru;
2037         channel = scb->dev_channel;
2038         target  = scb->dev_target;
2039
2040         // 0=6sec, 1=60sec, 2=10min, 3=3hrs, 4=NO timeout
2041         epthru->timeout         = 4;    
2042         epthru->ars             = 1;
2043         epthru->islogical       = 0;
2044         epthru->channel         = 0;
2045         epthru->target          = (channel << 4) | target;
2046         epthru->logdrv          = SCP2LUN(scp);
2047         epthru->reqsenselen     = 14;
2048         epthru->cdblen          = scp->cmd_len;
2049
2050         memcpy(epthru->cdb, scp->cmnd, scp->cmd_len);
2051
2052         if (scsi_bufflen(scp)) {
2053                 epthru->dataxferlen     = scsi_bufflen(scp);
2054                 epthru->dataxferaddr    = ccb->sgl_dma_h;
2055                 epthru->numsge          = megaraid_mbox_mksgl(adapter, scb);
2056         }
2057         else {
2058                 epthru->dataxferaddr    = 0;
2059                 epthru->dataxferlen     = 0;
2060                 epthru->numsge          = 0;
2061         }
2062         return;
2063 }
2064
2065
2066 /**
2067  * megaraid_ack_sequence - interrupt ack sequence for memory mapped HBAs
2068  * @adapter     : controller's soft state
2069  *
2070  * Interrupt acknowledgement sequence for memory mapped HBAs. Find out the
2071  * completed command and put them on the completed list for later processing.
2072  *
2073  * Returns:     1 if the interrupt is valid, 0 otherwise
2074  */
2075 static int
2076 megaraid_ack_sequence(adapter_t *adapter)
2077 {
2078         mraid_device_t          *raid_dev = ADAP2RAIDDEV(adapter);
2079         mbox_t                  *mbox;
2080         scb_t                   *scb;
2081         uint8_t                 nstatus;
2082         uint8_t                 completed[MBOX_MAX_FIRMWARE_STATUS];
2083         struct list_head        clist;
2084         int                     handled;
2085         uint32_t                dword;
2086         unsigned long           flags;
2087         int                     i, j;
2088
2089
2090         mbox    = raid_dev->mbox;
2091
2092         // move the SCBs from the firmware completed array to our local list
2093         INIT_LIST_HEAD(&clist);
2094
2095         // loop till F/W has more commands for us to complete
2096         handled = 0;
2097         spin_lock_irqsave(MAILBOX_LOCK(raid_dev), flags);
2098         do {
2099                 /*
2100                  * Check if a valid interrupt is pending. If found, force the
2101                  * interrupt line low.
2102                  */
2103                 dword = RDOUTDOOR(raid_dev);
2104                 if (dword != 0x10001234) break;
2105
2106                 handled = 1;
2107
2108                 WROUTDOOR(raid_dev, 0x10001234);
2109
2110                 nstatus = 0;
2111                 // wait for valid numstatus to post
2112                 for (i = 0; i < 0xFFFFF; i++) {
2113                         if (mbox->numstatus != 0xFF) {
2114                                 nstatus = mbox->numstatus;
2115                                 break;
2116                         }
2117                         rmb();
2118                 }
2119                 mbox->numstatus = 0xFF;
2120
2121                 adapter->outstanding_cmds -= nstatus;
2122
2123                 for (i = 0; i < nstatus; i++) {
2124
2125                         // wait for valid command index to post
2126                         for (j = 0; j < 0xFFFFF; j++) {
2127                                 if (mbox->completed[i] != 0xFF) break;
2128                                 rmb();
2129                         }
2130                         completed[i]            = mbox->completed[i];
2131                         mbox->completed[i]      = 0xFF;
2132
2133                         if (completed[i] == 0xFF) {
2134                                 con_log(CL_ANN, (KERN_CRIT
2135                                 "megaraid: command posting timed out\n"));
2136
2137                                 BUG();
2138                                 continue;
2139                         }
2140
2141                         // Get SCB associated with this command id
2142                         if (completed[i] >= MBOX_MAX_SCSI_CMDS) {
2143                                 // a cmm command
2144                                 scb = adapter->uscb_list + (completed[i] -
2145                                                 MBOX_MAX_SCSI_CMDS);
2146                         }
2147                         else {
2148                                 // an os command
2149                                 scb = adapter->kscb_list + completed[i];
2150                         }
2151
2152                         scb->status = mbox->status;
2153                         list_add_tail(&scb->list, &clist);
2154                 }
2155
2156                 // Acknowledge interrupt
2157                 WRINDOOR(raid_dev, 0x02);
2158
2159         } while(1);
2160
2161         spin_unlock_irqrestore(MAILBOX_LOCK(raid_dev), flags);
2162
2163
2164         // put the completed commands in the completed list. DPC would
2165         // complete these commands later
2166         spin_lock_irqsave(COMPLETED_LIST_LOCK(adapter), flags);
2167
2168         list_splice(&clist, &adapter->completed_list);
2169
2170         spin_unlock_irqrestore(COMPLETED_LIST_LOCK(adapter), flags);
2171
2172
2173         // schedule the DPC if there is some work for it
2174         if (handled)
2175                 tasklet_schedule(&adapter->dpc_h);
2176
2177         return handled;
2178 }
2179
2180
2181 /**
2182  * megaraid_isr - isr for memory based mailbox based controllers
2183  * @irq         : irq
2184  * @devp        : pointer to our soft state
2185  *
2186  * Interrupt service routine for memory-mapped mailbox controllers.
2187  */
2188 static irqreturn_t
2189 megaraid_isr(int irq, void *devp)
2190 {
2191         adapter_t       *adapter = devp;
2192         int             handled;
2193
2194         handled = megaraid_ack_sequence(adapter);
2195
2196         /* Loop through any pending requests */
2197         if (!adapter->quiescent) {
2198                 megaraid_mbox_runpendq(adapter, NULL);
2199         }
2200
2201         return IRQ_RETVAL(handled);
2202 }
2203
2204
2205 /**
2206  * megaraid_mbox_sync_scb - sync kernel buffers
2207  * @adapter     : controller's soft state
2208  * @scb         : pointer to the resource packet
2209  *
2210  * DMA sync if required.
2211  */
2212 static void
2213 megaraid_mbox_sync_scb(adapter_t *adapter, scb_t *scb)
2214 {
2215         mbox_ccb_t      *ccb;
2216
2217         ccb     = (mbox_ccb_t *)scb->ccb;
2218
2219         if (scb->dma_direction == PCI_DMA_FROMDEVICE)
2220                 pci_dma_sync_sg_for_cpu(adapter->pdev,
2221                                         scsi_sglist(scb->scp),
2222                                         scsi_sg_count(scb->scp),
2223                                         PCI_DMA_FROMDEVICE);
2224
2225         scsi_dma_unmap(scb->scp);
2226         return;
2227 }
2228
2229
2230 /**
2231  * megaraid_mbox_dpc - the tasklet to complete the commands from completed list
2232  * @devp        : pointer to HBA soft state
2233  *
2234  * Pick up the commands from the completed list and send back to the owners.
2235  * This is a reentrant function and does not assume any locks are held while
2236  * it is being called.
2237  */
2238 static void
2239 megaraid_mbox_dpc(unsigned long devp)
2240 {
2241         adapter_t               *adapter = (adapter_t *)devp;
2242         mraid_device_t          *raid_dev;
2243         struct list_head        clist;
2244         struct scatterlist      *sgl;
2245         scb_t                   *scb;
2246         scb_t                   *tmp;
2247         struct scsi_cmnd        *scp;
2248         mraid_passthru_t        *pthru;
2249         mraid_epassthru_t       *epthru;
2250         mbox_ccb_t              *ccb;
2251         int                     islogical;
2252         int                     pdev_index;
2253         int                     pdev_state;
2254         mbox_t                  *mbox;
2255         unsigned long           flags;
2256         uint8_t                 c;
2257         int                     status;
2258         uioc_t                  *kioc;
2259
2260
2261         if (!adapter) return;
2262
2263         raid_dev = ADAP2RAIDDEV(adapter);
2264
2265         // move the SCBs from the completed list to our local list
2266         INIT_LIST_HEAD(&clist);
2267
2268         spin_lock_irqsave(COMPLETED_LIST_LOCK(adapter), flags);
2269
2270         list_splice_init(&adapter->completed_list, &clist);
2271
2272         spin_unlock_irqrestore(COMPLETED_LIST_LOCK(adapter), flags);
2273
2274
2275         list_for_each_entry_safe(scb, tmp, &clist, list) {
2276
2277                 status          = scb->status;
2278                 scp             = scb->scp;
2279                 ccb             = (mbox_ccb_t *)scb->ccb;
2280                 pthru           = ccb->pthru;
2281                 epthru          = ccb->epthru;
2282                 mbox            = ccb->mbox;
2283
2284                 // Make sure f/w has completed a valid command
2285                 if (scb->state != SCB_ISSUED) {
2286                         con_log(CL_ANN, (KERN_CRIT
2287                         "megaraid critical err: invalid command %d:%d:%p\n",
2288                                 scb->sno, scb->state, scp));
2289                         BUG();
2290                         continue;       // Must never happen!
2291                 }
2292
2293                 // check for the management command and complete it right away
2294                 if (scb->sno >= MBOX_MAX_SCSI_CMDS) {
2295                         scb->state      = SCB_FREE;
2296                         scb->status     = status;
2297
2298                         // remove from local clist
2299                         list_del_init(&scb->list);
2300
2301                         kioc                    = (uioc_t *)scb->gp;
2302                         kioc->status            = 0;
2303
2304                         megaraid_mbox_mm_done(adapter, scb);
2305
2306                         continue;
2307                 }
2308
2309                 // Was an abort issued for this command earlier
2310                 if (scb->state & SCB_ABORT) {
2311                         con_log(CL_ANN, (KERN_NOTICE
2312                         "megaraid: aborted cmd %lx[%x] completed\n",
2313                                 scp->serial_number, scb->sno));
2314                 }
2315
2316                 /*
2317                  * If the inquiry came of a disk drive which is not part of
2318                  * any RAID array, expose it to the kernel. For this to be
2319                  * enabled, user must set the "megaraid_expose_unconf_disks"
2320                  * flag to 1 by specifying it on module parameter list.
2321                  * This would enable data migration off drives from other
2322                  * configurations.
2323                  */
2324                 islogical = MRAID_IS_LOGICAL(adapter, scp);
2325                 if (scp->cmnd[0] == INQUIRY && status == 0 && islogical == 0
2326                                 && IS_RAID_CH(raid_dev, scb->dev_channel)) {
2327
2328                         sgl = scsi_sglist(scp);
2329                         if (sg_page(sgl)) {
2330                                 c = *(unsigned char *) sg_virt(&sgl[0]);
2331                         } else {
2332                                 con_log(CL_ANN, (KERN_WARNING
2333                                                  "megaraid mailbox: invalid sg:%d\n",
2334                                                  __LINE__));
2335                                 c = 0;
2336                         }
2337
2338                         if ((c & 0x1F ) == TYPE_DISK) {
2339                                 pdev_index = (scb->dev_channel * 16) +
2340                                         scb->dev_target;
2341                                 pdev_state =
2342                                         raid_dev->pdrv_state[pdev_index] & 0x0F;
2343
2344                                 if (pdev_state == PDRV_ONLINE           ||
2345                                         pdev_state == PDRV_FAILED       ||
2346                                         pdev_state == PDRV_RBLD         ||
2347                                         pdev_state == PDRV_HOTSPARE     ||
2348                                         megaraid_expose_unconf_disks == 0) {
2349
2350                                         status = 0xF0;
2351                                 }
2352                         }
2353                 }
2354
2355                 // Convert MegaRAID status to Linux error code
2356                 switch (status) {
2357
2358                 case 0x00:
2359
2360                         scp->result = (DID_OK << 16);
2361                         break;
2362
2363                 case 0x02:
2364
2365                         /* set sense_buffer and result fields */
2366                         if (mbox->cmd == MBOXCMD_PASSTHRU ||
2367                                 mbox->cmd == MBOXCMD_PASSTHRU64) {
2368
2369                                 memcpy(scp->sense_buffer, pthru->reqsensearea,
2370                                                 14);
2371
2372                                 scp->result = DRIVER_SENSE << 24 |
2373                                         DID_OK << 16 | CHECK_CONDITION << 1;
2374                         }
2375                         else {
2376                                 if (mbox->cmd == MBOXCMD_EXTPTHRU) {
2377
2378                                         memcpy(scp->sense_buffer,
2379                                                 epthru->reqsensearea, 14);
2380
2381                                         scp->result = DRIVER_SENSE << 24 |
2382                                                 DID_OK << 16 |
2383                                                 CHECK_CONDITION << 1;
2384                                 } else {
2385                                         scp->sense_buffer[0] = 0x70;
2386                                         scp->sense_buffer[2] = ABORTED_COMMAND;
2387                                         scp->result = CHECK_CONDITION << 1;
2388                                 }
2389                         }
2390                         break;
2391
2392                 case 0x08:
2393
2394                         scp->result = DID_BUS_BUSY << 16 | status;
2395                         break;
2396
2397                 default:
2398
2399                         /*
2400                          * If TEST_UNIT_READY fails, we know RESERVATION_STATUS
2401                          * failed
2402                          */
2403                         if (scp->cmnd[0] == TEST_UNIT_READY) {
2404                                 scp->result = DID_ERROR << 16 |
2405                                         RESERVATION_CONFLICT << 1;
2406                         }
2407                         else
2408                         /*
2409                          * Error code returned is 1 if Reserve or Release
2410                          * failed or the input parameter is invalid
2411                          */
2412                         if (status == 1 && (scp->cmnd[0] == RESERVE ||
2413                                          scp->cmnd[0] == RELEASE)) {
2414
2415                                 scp->result = DID_ERROR << 16 |
2416                                         RESERVATION_CONFLICT << 1;
2417                         }
2418                         else {
2419                                 scp->result = DID_BAD_TARGET << 16 | status;
2420                         }
2421                 }
2422
2423                 // print a debug message for all failed commands
2424                 if (status) {
2425                         megaraid_mbox_display_scb(adapter, scb);
2426                 }
2427
2428                 // Free our internal resources and call the mid-layer callback
2429                 // routine
2430                 megaraid_mbox_sync_scb(adapter, scb);
2431
2432                 // remove from local clist
2433                 list_del_init(&scb->list);
2434
2435                 // put back in free list
2436                 megaraid_dealloc_scb(adapter, scb);
2437
2438                 // send the scsi packet back to kernel
2439                 scp->scsi_done(scp);
2440         }
2441
2442         return;
2443 }
2444
2445
2446 /**
2447  * megaraid_abort_handler - abort the scsi command
2448  * @scp         : command to be aborted
2449  *
2450  * Abort a previous SCSI request. Only commands on the pending list can be
2451  * aborted. All the commands issued to the F/W must complete.
2452  **/
2453 static int
2454 megaraid_abort_handler(struct scsi_cmnd *scp)
2455 {
2456         adapter_t               *adapter;
2457         mraid_device_t          *raid_dev;
2458         scb_t                   *scb;
2459         scb_t                   *tmp;
2460         int                     found;
2461         unsigned long           flags;
2462         int                     i;
2463
2464
2465         adapter         = SCP2ADAPTER(scp);
2466         raid_dev        = ADAP2RAIDDEV(adapter);
2467
2468         con_log(CL_ANN, (KERN_WARNING
2469                 "megaraid: aborting-%ld cmd=%x <c=%d t=%d l=%d>\n",
2470                 scp->serial_number, scp->cmnd[0], SCP2CHANNEL(scp),
2471                 SCP2TARGET(scp), SCP2LUN(scp)));
2472
2473         // If FW has stopped responding, simply return failure
2474         if (raid_dev->hw_error) {
2475                 con_log(CL_ANN, (KERN_NOTICE
2476                         "megaraid: hw error, not aborting\n"));
2477                 return FAILED;
2478         }
2479
2480         // There might a race here, where the command was completed by the
2481         // firmware and now it is on the completed list. Before we could
2482         // complete the command to the kernel in dpc, the abort came.
2483         // Find out if this is the case to avoid the race.
2484         scb = NULL;
2485         spin_lock_irqsave(COMPLETED_LIST_LOCK(adapter), flags);
2486         list_for_each_entry_safe(scb, tmp, &adapter->completed_list, list) {
2487
2488                 if (scb->scp == scp) {  // Found command
2489
2490                         list_del_init(&scb->list);      // from completed list
2491
2492                         con_log(CL_ANN, (KERN_WARNING
2493                         "megaraid: %ld:%d[%d:%d], abort from completed list\n",
2494                                 scp->serial_number, scb->sno,
2495                                 scb->dev_channel, scb->dev_target));
2496
2497                         scp->result = (DID_ABORT << 16);
2498                         scp->scsi_done(scp);
2499
2500                         megaraid_dealloc_scb(adapter, scb);
2501
2502                         spin_unlock_irqrestore(COMPLETED_LIST_LOCK(adapter),
2503                                 flags);
2504
2505                         return SUCCESS;
2506                 }
2507         }
2508         spin_unlock_irqrestore(COMPLETED_LIST_LOCK(adapter), flags);
2509
2510
2511         // Find out if this command is still on the pending list. If it is and
2512         // was never issued, abort and return success. If the command is owned
2513         // by the firmware, we must wait for it to complete by the FW.
2514         spin_lock_irqsave(PENDING_LIST_LOCK(adapter), flags);
2515         list_for_each_entry_safe(scb, tmp, &adapter->pend_list, list) {
2516
2517                 if (scb->scp == scp) {  // Found command
2518
2519                         list_del_init(&scb->list);      // from pending list
2520
2521                         ASSERT(!(scb->state & SCB_ISSUED));
2522
2523                         con_log(CL_ANN, (KERN_WARNING
2524                                 "megaraid abort: %ld[%d:%d], driver owner\n",
2525                                 scp->serial_number, scb->dev_channel,
2526                                 scb->dev_target));
2527
2528                         scp->result = (DID_ABORT << 16);
2529                         scp->scsi_done(scp);
2530
2531                         megaraid_dealloc_scb(adapter, scb);
2532
2533                         spin_unlock_irqrestore(PENDING_LIST_LOCK(adapter),
2534                                 flags);
2535
2536                         return SUCCESS;
2537                 }
2538         }
2539         spin_unlock_irqrestore(PENDING_LIST_LOCK(adapter), flags);
2540
2541
2542         // Check do we even own this command, in which case this would be
2543         // owned by the firmware. The only way to locate the FW scb is to
2544         // traverse through the list of all SCB, since driver does not
2545         // maintain these SCBs on any list
2546         found = 0;
2547         spin_lock_irq(&adapter->lock);
2548         for (i = 0; i < MBOX_MAX_SCSI_CMDS; i++) {
2549                 scb = adapter->kscb_list + i;
2550
2551                 if (scb->scp == scp) {
2552
2553                         found = 1;
2554
2555                         if (!(scb->state & SCB_ISSUED)) {
2556                                 con_log(CL_ANN, (KERN_WARNING
2557                                 "megaraid abort: %ld%d[%d:%d], invalid state\n",
2558                                 scp->serial_number, scb->sno, scb->dev_channel,
2559                                 scb->dev_target));
2560                                 BUG();
2561                         }
2562                         else {
2563                                 con_log(CL_ANN, (KERN_WARNING
2564                                 "megaraid abort: %ld:%d[%d:%d], fw owner\n",
2565                                 scp->serial_number, scb->sno, scb->dev_channel,
2566                                 scb->dev_target));
2567                         }
2568                 }
2569         }
2570         spin_unlock_irq(&adapter->lock);
2571
2572         if (!found) {
2573                 con_log(CL_ANN, (KERN_WARNING
2574                         "megaraid abort: scsi cmd:%ld, do now own\n",
2575                         scp->serial_number));
2576
2577                 // FIXME: Should there be a callback for this command?
2578                 return SUCCESS;
2579         }
2580
2581         // We cannot actually abort a command owned by firmware, return
2582         // failure and wait for reset. In host reset handler, we will find out
2583         // if the HBA is still live
2584         return FAILED;
2585 }
2586
2587 /**
2588  * megaraid_reset_handler - device reset hadler for mailbox based driver
2589  * @scp         : reference command
2590  *
2591  * Reset handler for the mailbox based controller. First try to find out if
2592  * the FW is still live, in which case the outstanding commands counter mut go
2593  * down to 0. If that happens, also issue the reservation reset command to
2594  * relinquish (possible) reservations on the logical drives connected to this
2595  * host.
2596  **/
2597 static int
2598 megaraid_reset_handler(struct scsi_cmnd *scp)
2599 {
2600         adapter_t       *adapter;
2601         scb_t           *scb;
2602         scb_t           *tmp;
2603         mraid_device_t  *raid_dev;
2604         unsigned long   flags;
2605         uint8_t         raw_mbox[sizeof(mbox_t)];
2606         int             rval;
2607         int             recovery_window;
2608         int             recovering;
2609         int             i;
2610         uioc_t          *kioc;
2611
2612         adapter         = SCP2ADAPTER(scp);
2613         raid_dev        = ADAP2RAIDDEV(adapter);
2614
2615         // return failure if adapter is not responding
2616         if (raid_dev->hw_error) {
2617                 con_log(CL_ANN, (KERN_NOTICE
2618                         "megaraid: hw error, cannot reset\n"));
2619                 return FAILED;
2620         }
2621
2622
2623         // Under exceptional conditions, FW can take up to 3 minutes to
2624         // complete command processing. Wait for additional 2 minutes for the
2625         // pending commands counter to go down to 0. If it doesn't, let the
2626         // controller be marked offline
2627         // Also, reset all the commands currently owned by the driver
2628         spin_lock_irqsave(PENDING_LIST_LOCK(adapter), flags);
2629         list_for_each_entry_safe(scb, tmp, &adapter->pend_list, list) {
2630                 list_del_init(&scb->list);      // from pending list
2631
2632                 if (scb->sno >= MBOX_MAX_SCSI_CMDS) {
2633                         con_log(CL_ANN, (KERN_WARNING
2634                         "megaraid: IOCTL packet with %d[%d:%d] being reset\n",
2635                         scb->sno, scb->dev_channel, scb->dev_target));
2636
2637                         scb->status = -1;
2638
2639                         kioc                    = (uioc_t *)scb->gp;
2640                         kioc->status            = -EFAULT;
2641
2642                         megaraid_mbox_mm_done(adapter, scb);
2643                 } else {
2644                         if (scb->scp == scp) {  // Found command
2645                                 con_log(CL_ANN, (KERN_WARNING
2646                                         "megaraid: %ld:%d[%d:%d], reset from pending list\n",
2647                                         scp->serial_number, scb->sno,
2648                                         scb->dev_channel, scb->dev_target));
2649                         } else {
2650                                 con_log(CL_ANN, (KERN_WARNING
2651                                 "megaraid: IO packet with %d[%d:%d] being reset\n",
2652                                 scb->sno, scb->dev_channel, scb->dev_target));
2653                         }
2654
2655                         scb->scp->result = (DID_RESET << 16);
2656                         scb->scp->scsi_done(scb->scp);
2657
2658                         megaraid_dealloc_scb(adapter, scb);
2659                 }
2660         }
2661         spin_unlock_irqrestore(PENDING_LIST_LOCK(adapter), flags);
2662
2663         if (adapter->outstanding_cmds) {
2664                 con_log(CL_ANN, (KERN_NOTICE
2665                         "megaraid: %d outstanding commands. Max wait %d sec\n",
2666                         adapter->outstanding_cmds,
2667                         (MBOX_RESET_WAIT + MBOX_RESET_EXT_WAIT)));
2668         }
2669
2670         recovery_window = MBOX_RESET_WAIT + MBOX_RESET_EXT_WAIT;
2671
2672         recovering = adapter->outstanding_cmds;
2673
2674         for (i = 0; i < recovery_window; i++) {
2675
2676                 megaraid_ack_sequence(adapter);
2677
2678                 // print a message once every 5 seconds only
2679                 if (!(i % 5)) {
2680                         con_log(CL_ANN, (
2681                         "megaraid mbox: Wait for %d commands to complete:%d\n",
2682                                 adapter->outstanding_cmds,
2683                                 (MBOX_RESET_WAIT + MBOX_RESET_EXT_WAIT) - i));
2684                 }
2685
2686                 // bailout if no recovery happended in reset time
2687                 if (adapter->outstanding_cmds == 0) {
2688                         break;
2689                 }
2690
2691                 msleep(1000);
2692         }
2693
2694         spin_lock(&adapter->lock);
2695
2696         // If still outstanding commands, bail out
2697         if (adapter->outstanding_cmds) {
2698                 con_log(CL_ANN, (KERN_WARNING
2699                         "megaraid mbox: critical hardware error!\n"));
2700
2701                 raid_dev->hw_error = 1;
2702
2703                 rval = FAILED;
2704                 goto out;
2705         }
2706         else {
2707                 con_log(CL_ANN, (KERN_NOTICE
2708                 "megaraid mbox: reset sequence completed sucessfully\n"));
2709         }
2710
2711
2712         // If the controller supports clustering, reset reservations
2713         if (!adapter->ha) {
2714                 rval = SUCCESS;
2715                 goto out;
2716         }
2717
2718         // clear reservations if any
2719         raw_mbox[0] = CLUSTER_CMD;
2720         raw_mbox[2] = RESET_RESERVATIONS;
2721
2722         rval = SUCCESS;
2723         if (mbox_post_sync_cmd_fast(adapter, raw_mbox) == 0) {
2724                 con_log(CL_ANN,
2725                         (KERN_INFO "megaraid: reservation reset\n"));
2726         }
2727         else {
2728                 rval = FAILED;
2729                 con_log(CL_ANN, (KERN_WARNING
2730                                 "megaraid: reservation reset failed\n"));
2731         }
2732
2733  out:
2734         spin_unlock_irq(&adapter->lock);
2735         return rval;
2736 }
2737
2738 /*
2739  * START: internal commands library
2740  *
2741  * This section of the driver has the common routine used by the driver and
2742  * also has all the FW routines
2743  */
2744
2745 /**
2746  * mbox_post_sync_cmd() - blocking command to the mailbox based controllers
2747  * @adapter     : controller's soft state
2748  * @raw_mbox    : the mailbox
2749  *
2750  * Issue a scb in synchronous and non-interrupt mode for mailbox based
2751  * controllers.
2752  */
2753 static int
2754 mbox_post_sync_cmd(adapter_t *adapter, uint8_t raw_mbox[])
2755 {
2756         mraid_device_t  *raid_dev = ADAP2RAIDDEV(adapter);
2757         mbox64_t        *mbox64;
2758         mbox_t          *mbox;
2759         uint8_t         status;
2760         int             i;
2761
2762
2763         mbox64  = raid_dev->mbox64;
2764         mbox    = raid_dev->mbox;
2765
2766         /*
2767          * Wait until mailbox is free
2768          */
2769         if (megaraid_busywait_mbox(raid_dev) != 0)
2770                 goto blocked_mailbox;
2771
2772         /*
2773          * Copy mailbox data into host structure
2774          */
2775         memcpy((caddr_t)mbox, (caddr_t)raw_mbox, 16);
2776         mbox->cmdid             = 0xFE;
2777         mbox->busy              = 1;
2778         mbox->poll              = 0;
2779         mbox->ack               = 0;
2780         mbox->numstatus         = 0xFF;
2781         mbox->status            = 0xFF;
2782
2783         wmb();
2784         WRINDOOR(raid_dev, raid_dev->mbox_dma | 0x1);
2785
2786         // wait for maximum 1 second for status to post. If the status is not
2787         // available within 1 second, assume FW is initializing and wait
2788         // for an extended amount of time
2789         if (mbox->numstatus == 0xFF) {  // status not yet available
2790                 udelay(25);
2791
2792                 for (i = 0; mbox->numstatus == 0xFF && i < 1000; i++) {
2793                         rmb();
2794                         msleep(1);
2795                 }
2796
2797
2798                 if (i == 1000) {
2799                         con_log(CL_ANN, (KERN_NOTICE
2800                                 "megaraid mailbox: wait for FW to boot      "));
2801
2802                         for (i = 0; (mbox->numstatus == 0xFF) &&
2803                                         (i < MBOX_RESET_WAIT); i++) {
2804                                 rmb();
2805                                 con_log(CL_ANN, ("\b\b\b\b\b[%03d]",
2806                                                         MBOX_RESET_WAIT - i));
2807                                 msleep(1000);
2808                         }
2809
2810                         if (i == MBOX_RESET_WAIT) {
2811
2812                                 con_log(CL_ANN, (
2813                                 "\nmegaraid mailbox: status not available\n"));
2814
2815                                 return -1;
2816                         }
2817                         con_log(CL_ANN, ("\b\b\b\b\b[ok] \n"));
2818                 }
2819         }
2820
2821         // wait for maximum 1 second for poll semaphore
2822         if (mbox->poll != 0x77) {
2823                 udelay(25);
2824
2825                 for (i = 0; (mbox->poll != 0x77) && (i < 1000); i++) {
2826                         rmb();
2827                         msleep(1);
2828                 }
2829
2830                 if (i == 1000) {
2831                         con_log(CL_ANN, (KERN_WARNING
2832                         "megaraid mailbox: could not get poll semaphore\n"));
2833                         return -1;
2834                 }
2835         }
2836
2837         WRINDOOR(raid_dev, raid_dev->mbox_dma | 0x2);
2838         wmb();
2839
2840         // wait for maximum 1 second for acknowledgement
2841         if (RDINDOOR(raid_dev) & 0x2) {
2842                 udelay(25);
2843
2844                 for (i = 0; (RDINDOOR(raid_dev) & 0x2) && (i < 1000); i++) {
2845                         rmb();
2846                         msleep(1);
2847                 }
2848
2849                 if (i == 1000) {
2850                         con_log(CL_ANN, (KERN_WARNING
2851                                 "megaraid mailbox: could not acknowledge\n"));
2852                         return -1;
2853                 }
2854         }
2855         mbox->poll      = 0;
2856         mbox->ack       = 0x77;
2857
2858         status = mbox->status;
2859
2860         // invalidate the completed command id array. After command
2861         // completion, firmware would write the valid id.
2862         mbox->numstatus = 0xFF;
2863         mbox->status    = 0xFF;
2864         for (i = 0; i < MBOX_MAX_FIRMWARE_STATUS; i++) {
2865                 mbox->completed[i] = 0xFF;
2866         }
2867
2868         return status;
2869
2870 blocked_mailbox:
2871
2872         con_log(CL_ANN, (KERN_WARNING "megaraid: blocked mailbox\n") );
2873         return -1;
2874 }
2875
2876
2877 /**
2878  * mbox_post_sync_cmd_fast - blocking command to the mailbox based controllers
2879  * @adapter     : controller's soft state
2880  * @raw_mbox    : the mailbox
2881  *
2882  * Issue a scb in synchronous and non-interrupt mode for mailbox based
2883  * controllers. This is a faster version of the synchronous command and
2884  * therefore can be called in interrupt-context as well.
2885  */
2886 static int
2887 mbox_post_sync_cmd_fast(adapter_t *adapter, uint8_t raw_mbox[])
2888 {
2889         mraid_device_t  *raid_dev = ADAP2RAIDDEV(adapter);
2890         mbox_t          *mbox;
2891         long            i;
2892
2893
2894         mbox    = raid_dev->mbox;
2895
2896         // return immediately if the mailbox is busy
2897         if (mbox->busy) return -1;
2898
2899         // Copy mailbox data into host structure
2900         memcpy((caddr_t)mbox, (caddr_t)raw_mbox, 14);
2901         mbox->cmdid             = 0xFE;
2902         mbox->busy              = 1;
2903         mbox->poll              = 0;
2904         mbox->ack               = 0;
2905         mbox->numstatus         = 0xFF;
2906         mbox->status            = 0xFF;
2907
2908         wmb();
2909         WRINDOOR(raid_dev, raid_dev->mbox_dma | 0x1);
2910
2911         for (i = 0; i < MBOX_SYNC_WAIT_CNT; i++) {
2912                 if (mbox->numstatus != 0xFF) break;
2913                 rmb();
2914                 udelay(MBOX_SYNC_DELAY_200);
2915         }
2916
2917         if (i == MBOX_SYNC_WAIT_CNT) {
2918                 // We may need to re-calibrate the counter
2919                 con_log(CL_ANN, (KERN_CRIT
2920                         "megaraid: fast sync command timed out\n"));
2921         }
2922
2923         WRINDOOR(raid_dev, raid_dev->mbox_dma | 0x2);
2924         wmb();
2925
2926         return mbox->status;
2927 }
2928
2929
2930 /**
2931  * megaraid_busywait_mbox() - Wait until the controller's mailbox is available
2932  * @raid_dev    : RAID device (HBA) soft state
2933  *
2934  * Wait until the controller's mailbox is available to accept more commands.
2935  * Wait for at most 1 second.
2936  */
2937 static int
2938 megaraid_busywait_mbox(mraid_device_t *raid_dev)
2939 {
2940         mbox_t  *mbox = raid_dev->mbox;
2941         int     i = 0;
2942
2943         if (mbox->busy) {
2944                 udelay(25);
2945                 for (i = 0; mbox->busy && i < 1000; i++)
2946                         msleep(1);
2947         }
2948
2949         if (i < 1000) return 0;
2950         else return -1;
2951 }
2952
2953
2954 /**
2955  * megaraid_mbox_product_info - some static information about the controller
2956  * @adapter     : our soft state
2957  *
2958  * Issue commands to the controller to grab some parameters required by our
2959  * caller.
2960  */
2961 static int
2962 megaraid_mbox_product_info(adapter_t *adapter)
2963 {
2964         mraid_device_t          *raid_dev = ADAP2RAIDDEV(adapter);
2965         mbox_t                  *mbox;
2966         uint8_t                 raw_mbox[sizeof(mbox_t)];
2967         mraid_pinfo_t           *pinfo;
2968         dma_addr_t              pinfo_dma_h;
2969         mraid_inquiry3_t        *mraid_inq3;
2970         int                     i;
2971
2972
2973         memset((caddr_t)raw_mbox, 0, sizeof(raw_mbox));
2974         mbox = (mbox_t *)raw_mbox;
2975
2976         /*
2977          * Issue an ENQUIRY3 command to find out certain adapter parameters,
2978          * e.g., max channels, max commands etc.
2979          */
2980         pinfo = pci_alloc_consistent(adapter->pdev, sizeof(mraid_pinfo_t),
2981                         &pinfo_dma_h);
2982
2983         if (pinfo == NULL) {
2984                 con_log(CL_ANN, (KERN_WARNING
2985                         "megaraid: out of memory, %s %d\n", __FUNCTION__,
2986                         __LINE__));
2987
2988                 return -1;
2989         }
2990         memset(pinfo, 0, sizeof(mraid_pinfo_t));
2991
2992         mbox->xferaddr = (uint32_t)adapter->ibuf_dma_h;
2993         memset((void *)adapter->ibuf, 0, MBOX_IBUF_SIZE);
2994
2995         raw_mbox[0] = FC_NEW_CONFIG;
2996         raw_mbox[2] = NC_SUBOP_ENQUIRY3;
2997         raw_mbox[3] = ENQ3_GET_SOLICITED_FULL;
2998
2999         // Issue the command
3000         if (mbox_post_sync_cmd(adapter, raw_mbox) != 0) {
3001
3002                 con_log(CL_ANN, (KERN_WARNING "megaraid: Inquiry3 failed\n"));
3003
3004                 pci_free_consistent(adapter->pdev, sizeof(mraid_pinfo_t),
3005                         pinfo, pinfo_dma_h);
3006
3007                 return -1;
3008         }
3009
3010         /*
3011          * Collect information about state of each physical drive
3012          * attached to the controller. We will expose all the disks
3013          * which are not part of RAID
3014          */
3015         mraid_inq3 = (mraid_inquiry3_t *)adapter->ibuf;
3016         for (i = 0; i < MBOX_MAX_PHYSICAL_DRIVES; i++) {
3017                 raid_dev->pdrv_state[i] = mraid_inq3->pdrv_state[i];
3018         }
3019
3020         /*
3021          * Get product info for information like number of channels,
3022          * maximum commands supported.
3023          */
3024         memset((caddr_t)raw_mbox, 0, sizeof(raw_mbox));
3025         mbox->xferaddr = (uint32_t)pinfo_dma_h;
3026
3027         raw_mbox[0] = FC_NEW_CONFIG;
3028         raw_mbox[2] = NC_SUBOP_PRODUCT_INFO;
3029
3030         if (mbox_post_sync_cmd(adapter, raw_mbox) != 0) {
3031
3032                 con_log(CL_ANN, (KERN_WARNING
3033                         "megaraid: product info failed\n"));
3034
3035                 pci_free_consistent(adapter->pdev, sizeof(mraid_pinfo_t),
3036                         pinfo, pinfo_dma_h);
3037
3038                 return -1;
3039         }
3040
3041         /*
3042          * Setup some parameters for host, as required by our caller
3043          */
3044         adapter->max_channel = pinfo->nchannels;
3045
3046         /*
3047          * we will export all the logical drives on a single channel.
3048          * Add 1 since inquires do not come for inititor ID
3049          */
3050         adapter->max_target     = MAX_LOGICAL_DRIVES_40LD + 1;
3051         adapter->max_lun        = 8;    // up to 8 LUNs for non-disk devices
3052
3053         /*
3054          * These are the maximum outstanding commands for the scsi-layer
3055          */
3056         adapter->max_cmds       = MBOX_MAX_SCSI_CMDS;
3057
3058         memset(adapter->fw_version, 0, VERSION_SIZE);
3059         memset(adapter->bios_version, 0, VERSION_SIZE);
3060
3061         memcpy(adapter->fw_version, pinfo->fw_version, 4);
3062         adapter->fw_version[4] = 0;
3063
3064         memcpy(adapter->bios_version, pinfo->bios_version, 4);
3065         adapter->bios_version[4] = 0;
3066
3067         con_log(CL_ANN, (KERN_NOTICE
3068                 "megaraid: fw version:[%s] bios version:[%s]\n",
3069                 adapter->fw_version, adapter->bios_version));
3070
3071         pci_free_consistent(adapter->pdev, sizeof(mraid_pinfo_t), pinfo,
3072                         pinfo_dma_h);
3073
3074         return 0;
3075 }
3076
3077
3078
3079 /**
3080  * megaraid_mbox_extended_cdb - check for support for extended CDBs
3081  * @adapter     : soft state for the controller
3082  *
3083  * This routine check whether the controller in question supports extended
3084  * ( > 10 bytes ) CDBs.
3085  */
3086 static int
3087 megaraid_mbox_extended_cdb(adapter_t *adapter)
3088 {
3089         mbox_t          *mbox;
3090         uint8_t         raw_mbox[sizeof(mbox_t)];
3091         int             rval;
3092
3093         mbox = (mbox_t *)raw_mbox;
3094
3095         memset((caddr_t)raw_mbox, 0, sizeof(raw_mbox));
3096         mbox->xferaddr  = (uint32_t)adapter->ibuf_dma_h;
3097
3098         memset((void *)adapter->ibuf, 0, MBOX_IBUF_SIZE);
3099
3100         raw_mbox[0] = MAIN_MISC_OPCODE;
3101         raw_mbox[2] = SUPPORT_EXT_CDB;
3102
3103         /*
3104          * Issue the command
3105          */
3106         rval = 0;
3107         if (mbox_post_sync_cmd(adapter, raw_mbox) != 0) {
3108                 rval = -1;
3109         }
3110
3111         return rval;
3112 }
3113
3114
3115 /**
3116  * megaraid_mbox_support_ha - Do we support clustering
3117  * @adapter     : soft state for the controller
3118  * @init_id     : ID of the initiator
3119  *
3120  * Determine if the firmware supports clustering and the ID of the initiator.
3121  */
3122 static int
3123 megaraid_mbox_support_ha(adapter_t *adapter, uint16_t *init_id)
3124 {
3125         mbox_t          *mbox;
3126         uint8_t         raw_mbox[sizeof(mbox_t)];
3127         int             rval;
3128
3129
3130         mbox = (mbox_t *)raw_mbox;
3131
3132         memset((caddr_t)raw_mbox, 0, sizeof(raw_mbox));
3133
3134         mbox->xferaddr = (uint32_t)adapter->ibuf_dma_h;
3135
3136         memset((void *)adapter->ibuf, 0, MBOX_IBUF_SIZE);
3137
3138         raw_mbox[0] = GET_TARGET_ID;
3139
3140         // Issue the command
3141         *init_id = 7;
3142         rval =  -1;
3143         if (mbox_post_sync_cmd(adapter, raw_mbox) == 0) {
3144
3145                 *init_id = *(uint8_t *)adapter->ibuf;
3146
3147                 con_log(CL_ANN, (KERN_INFO
3148                         "megaraid: cluster firmware, initiator ID: %d\n",
3149                         *init_id));
3150
3151                 rval =  0;
3152         }
3153
3154         return rval;
3155 }
3156
3157
3158 /**
3159  * megaraid_mbox_support_random_del - Do we support random deletion
3160  * @adapter     : soft state for the controller
3161  *
3162  * Determine if the firmware supports random deletion.
3163  * Return:      1 is operation supported, 0 otherwise
3164  */
3165 static int
3166 megaraid_mbox_support_random_del(adapter_t *adapter)
3167 {
3168         mbox_t          *mbox;
3169         uint8_t         raw_mbox[sizeof(mbox_t)];
3170         int             rval;
3171
3172
3173         mbox = (mbox_t *)raw_mbox;
3174
3175         memset((caddr_t)raw_mbox, 0, sizeof(mbox_t));
3176
3177         raw_mbox[0] = FC_DEL_LOGDRV;
3178         raw_mbox[2] = OP_SUP_DEL_LOGDRV;
3179
3180         // Issue the command
3181         rval = 0;
3182         if (mbox_post_sync_cmd(adapter, raw_mbox) == 0) {
3183
3184                 con_log(CL_DLEVEL1, ("megaraid: supports random deletion\n"));
3185
3186                 rval =  1;
3187         }
3188
3189         return rval;
3190 }
3191
3192
3193 /**
3194  * megaraid_mbox_get_max_sg - maximum sg elements supported by the firmware
3195  * @adapter     : soft state for the controller
3196  *
3197  * Find out the maximum number of scatter-gather elements supported by the
3198  * firmware.
3199  */
3200 static int
3201 megaraid_mbox_get_max_sg(adapter_t *adapter)
3202 {
3203         mbox_t          *mbox;
3204         uint8_t         raw_mbox[sizeof(mbox_t)];
3205         int             nsg;
3206
3207
3208         mbox = (mbox_t *)raw_mbox;
3209
3210         memset((caddr_t)raw_mbox, 0, sizeof(mbox_t));
3211
3212         mbox->xferaddr = (uint32_t)adapter->ibuf_dma_h;
3213
3214         memset((void *)adapter->ibuf, 0, MBOX_IBUF_SIZE);
3215
3216         raw_mbox[0] = MAIN_MISC_OPCODE;
3217         raw_mbox[2] = GET_MAX_SG_SUPPORT;
3218
3219         // Issue the command
3220         if (mbox_post_sync_cmd(adapter, raw_mbox) == 0) {
3221                 nsg =  *(uint8_t *)adapter->ibuf;
3222         }
3223         else {
3224                 nsg =  MBOX_DEFAULT_SG_SIZE;
3225         }
3226
3227         if (nsg > MBOX_MAX_SG_SIZE) nsg = MBOX_MAX_SG_SIZE;
3228
3229         return nsg;
3230 }
3231
3232
3233 /**
3234  * megaraid_mbox_enum_raid_scsi - enumerate the RAID and SCSI channels
3235  * @adapter     : soft state for the controller
3236  *
3237  * Enumerate the RAID and SCSI channels for ROMB platforms so that channels
3238  * can be exported as regular SCSI channels.
3239  */
3240 static void
3241 megaraid_mbox_enum_raid_scsi(adapter_t *adapter)
3242 {
3243         mraid_device_t  *raid_dev = ADAP2RAIDDEV(adapter);
3244         mbox_t          *mbox;
3245         uint8_t         raw_mbox[sizeof(mbox_t)];
3246
3247
3248         mbox = (mbox_t *)raw_mbox;
3249
3250         memset((caddr_t)raw_mbox, 0, sizeof(mbox_t));
3251
3252         mbox->xferaddr = (uint32_t)adapter->ibuf_dma_h;
3253
3254         memset((void *)adapter->ibuf, 0, MBOX_IBUF_SIZE);
3255
3256         raw_mbox[0] = CHNL_CLASS;
3257         raw_mbox[2] = GET_CHNL_CLASS;
3258
3259         // Issue the command. If the command fails, all channels are RAID
3260         // channels
3261         raid_dev->channel_class = 0xFF;
3262         if (mbox_post_sync_cmd(adapter, raw_mbox) == 0) {
3263                 raid_dev->channel_class =  *(uint8_t *)adapter->ibuf;
3264         }
3265
3266         return;
3267 }
3268
3269
3270 /**
3271  * megaraid_mbox_flush_cache - flush adapter and disks cache
3272  * @adapter             : soft state for the controller
3273  *
3274  * Flush adapter cache followed by disks cache.
3275  */
3276 static void
3277 megaraid_mbox_flush_cache(adapter_t *adapter)
3278 {
3279         mbox_t  *mbox;
3280         uint8_t raw_mbox[sizeof(mbox_t)];
3281
3282
3283         mbox = (mbox_t *)raw_mbox;
3284
3285         memset((caddr_t)raw_mbox, 0, sizeof(mbox_t));
3286
3287         raw_mbox[0] = FLUSH_ADAPTER;
3288
3289         if (mbox_post_sync_cmd(adapter, raw_mbox) != 0) {
3290                 con_log(CL_ANN, ("megaraid: flush adapter failed\n"));
3291         }
3292
3293         raw_mbox[0] = FLUSH_SYSTEM;
3294
3295         if (mbox_post_sync_cmd(adapter, raw_mbox) != 0) {
3296                 con_log(CL_ANN, ("megaraid: flush disks cache failed\n"));
3297         }
3298
3299         return;
3300 }
3301
3302
3303 /**
3304  * megaraid_mbox_fire_sync_cmd - fire the sync cmd
3305  * @adapter             : soft state for the controller
3306  *
3307  * Clears the pending cmds in FW and reinits its RAID structs.
3308  */
3309 static int
3310 megaraid_mbox_fire_sync_cmd(adapter_t *adapter)
3311 {
3312         mbox_t  *mbox;
3313         uint8_t raw_mbox[sizeof(mbox_t)];
3314         mraid_device_t  *raid_dev = ADAP2RAIDDEV(adapter);
3315         mbox64_t *mbox64;
3316         int     status = 0;
3317         int i;
3318         uint32_t dword;
3319
3320         mbox = (mbox_t *)raw_mbox;
3321
3322         memset((caddr_t)raw_mbox, 0, sizeof(mbox_t));
3323
3324         raw_mbox[0] = 0xFF;
3325
3326         mbox64  = raid_dev->mbox64;
3327         mbox    = raid_dev->mbox;
3328
3329         /* Wait until mailbox is free */
3330         if (megaraid_busywait_mbox(raid_dev) != 0) {
3331                 status = 1;
3332                 goto blocked_mailbox;
3333         }
3334
3335         /* Copy mailbox data into host structure */
3336         memcpy((caddr_t)mbox, (caddr_t)raw_mbox, 16);
3337         mbox->cmdid             = 0xFE;
3338         mbox->busy              = 1;
3339         mbox->poll              = 0;
3340         mbox->ack               = 0;
3341         mbox->numstatus         = 0;
3342         mbox->status            = 0;
3343
3344         wmb();
3345         WRINDOOR(raid_dev, raid_dev->mbox_dma | 0x1);
3346
3347         /* Wait for maximum 1 min for status to post.
3348          * If the Firmware SUPPORTS the ABOVE COMMAND,
3349          * mbox->cmd will be set to 0
3350          * else
3351          * the firmware will reject the command with
3352          * mbox->numstatus set to 1
3353          */
3354
3355         i = 0;
3356         status = 0;
3357         while (!mbox->numstatus && mbox->cmd == 0xFF) {
3358                 rmb();
3359                 msleep(1);
3360                 i++;
3361                 if (i > 1000 * 60) {
3362                         status = 1;
3363                         break;
3364                 }
3365         }
3366         if (mbox->numstatus == 1)
3367                 status = 1; /*cmd not supported*/
3368
3369         /* Check for interrupt line */
3370         dword = RDOUTDOOR(raid_dev);
3371         WROUTDOOR(raid_dev, dword);
3372         WRINDOOR(raid_dev,2);
3373
3374         return status;
3375
3376 blocked_mailbox:
3377         con_log(CL_ANN, (KERN_WARNING "megaraid: blocked mailbox\n"));
3378         return status;
3379 }
3380
3381 /**
3382  * megaraid_mbox_display_scb - display SCB information, mostly debug purposes
3383  * @adapter             : controller's soft state
3384  * @scb                 : SCB to be displayed
3385  * @level               : debug level for console print
3386  *
3387  * Diplay information about the given SCB iff the current debug level is
3388  * verbose.
3389  */
3390 static void
3391 megaraid_mbox_display_scb(adapter_t *adapter, scb_t *scb)
3392 {
3393         mbox_ccb_t              *ccb;
3394         struct scsi_cmnd        *scp;
3395         mbox_t                  *mbox;
3396         int                     level;
3397         int                     i;
3398
3399
3400         ccb     = (mbox_ccb_t *)scb->ccb;
3401         scp     = scb->scp;
3402         mbox    = ccb->mbox;
3403
3404         level = CL_DLEVEL3;
3405
3406         con_log(level, (KERN_NOTICE
3407                 "megaraid mailbox: status:%#x cmd:%#x id:%#x ", scb->status,
3408                 mbox->cmd, scb->sno));
3409
3410         con_log(level, ("sec:%#x lba:%#x addr:%#x ld:%d sg:%d\n",
3411                 mbox->numsectors, mbox->lba, mbox->xferaddr, mbox->logdrv,
3412                 mbox->numsge));
3413
3414         if (!scp) return;
3415
3416         con_log(level, (KERN_NOTICE "scsi cmnd: "));
3417
3418         for (i = 0; i < scp->cmd_len; i++) {
3419                 con_log(level, ("%#2.02x ", scp->cmnd[i]));
3420         }
3421
3422         con_log(level, ("\n"));
3423
3424         return;
3425 }
3426
3427
3428 /**
3429  * megaraid_mbox_setup_device_map - manage device ids
3430  * @adapter     : Driver's soft state
3431  *
3432  * Manange the device ids to have an appropraite mapping between the kernel
3433  * scsi addresses and megaraid scsi and logical drive addresses. We export
3434  * scsi devices on their actual addresses, whereas the logical drives are
3435  * exported on a virtual scsi channel.
3436  */
3437 static void
3438 megaraid_mbox_setup_device_map(adapter_t *adapter)
3439 {
3440         uint8_t         c;
3441         uint8_t         t;
3442
3443         /*
3444          * First fill the values on the logical drive channel
3445          */
3446         for (t = 0; t < LSI_MAX_LOGICAL_DRIVES_64LD; t++)
3447                 adapter->device_ids[adapter->max_channel][t] =
3448                         (t < adapter->init_id) ?  t : t - 1;
3449
3450         adapter->device_ids[adapter->max_channel][adapter->init_id] = 0xFF;
3451
3452         /*
3453          * Fill the values on the physical devices channels
3454          */
3455         for (c = 0; c < adapter->max_channel; c++)
3456                 for (t = 0; t < LSI_MAX_LOGICAL_DRIVES_64LD; t++)
3457                         adapter->device_ids[c][t] = (c << 8) | t;
3458 }
3459
3460
3461 /*
3462  * END: internal commands library
3463  */
3464
3465 /*
3466  * START: Interface for the common management module
3467  *
3468  * This is the module, which interfaces with the common mangement module to
3469  * provide support for ioctl and sysfs
3470  */
3471
3472 /**
3473  * megaraid_cmm_register - register with the mangement module
3474  * @adapter             : HBA soft state
3475  *
3476  * Register with the management module, which allows applications to issue
3477  * ioctl calls to the drivers. This interface is used by the management module
3478  * to setup sysfs support as well.
3479  */
3480 static int
3481 megaraid_cmm_register(adapter_t *adapter)
3482 {
3483         mraid_device_t  *raid_dev = ADAP2RAIDDEV(adapter);
3484         mraid_mmadp_t   adp;
3485         scb_t           *scb;
3486         mbox_ccb_t      *ccb;
3487         int             rval;
3488         int             i;
3489
3490         // Allocate memory for the base list of scb for management module.
3491         adapter->uscb_list = kcalloc(MBOX_MAX_USER_CMDS, sizeof(scb_t), GFP_KERNEL);
3492
3493         if (adapter->uscb_list == NULL) {
3494                 con_log(CL_ANN, (KERN_WARNING
3495                         "megaraid: out of memory, %s %d\n", __FUNCTION__,
3496                         __LINE__));
3497                 return -1;
3498         }
3499
3500
3501         // Initialize the synchronization parameters for resources for
3502         // commands for management module
3503         INIT_LIST_HEAD(&adapter->uscb_pool);
3504
3505         spin_lock_init(USER_FREE_LIST_LOCK(adapter));
3506
3507
3508
3509         // link all the packets. Note, CCB for commands, coming from the
3510         // commom management module, mailbox physical address are already
3511         // setup by it. We just need placeholder for that in our local command
3512         // control blocks
3513         for (i = 0; i < MBOX_MAX_USER_CMDS; i++) {
3514
3515                 scb                     = adapter->uscb_list + i;
3516                 ccb                     = raid_dev->uccb_list + i;
3517
3518                 scb->ccb                = (caddr_t)ccb;
3519                 ccb->mbox64             = raid_dev->umbox64 + i;
3520                 ccb->mbox               = &ccb->mbox64->mbox32;
3521                 ccb->raw_mbox           = (uint8_t *)ccb->mbox;
3522
3523                 scb->gp                 = 0;
3524
3525                 // COMMAND ID 0 - (MBOX_MAX_SCSI_CMDS-1) ARE RESERVED FOR
3526                 // COMMANDS COMING FROM IO SUBSYSTEM (MID-LAYER)
3527                 scb->sno                = i + MBOX_MAX_SCSI_CMDS;
3528
3529                 scb->scp                = NULL;
3530                 scb->state              = SCB_FREE;
3531                 scb->dma_direction      = PCI_DMA_NONE;
3532                 scb->dma_type           = MRAID_DMA_NONE;
3533                 scb->dev_channel        = -1;
3534                 scb->dev_target         = -1;
3535
3536                 // put scb in the free pool
3537                 list_add_tail(&scb->list, &adapter->uscb_pool);
3538         }
3539
3540         adp.unique_id           = adapter->unique_id;
3541         adp.drvr_type           = DRVRTYPE_MBOX;
3542         adp.drvr_data           = (unsigned long)adapter;
3543         adp.pdev                = adapter->pdev;
3544         adp.issue_uioc          = megaraid_mbox_mm_handler;
3545         adp.timeout             = MBOX_RESET_WAIT + MBOX_RESET_EXT_WAIT;
3546         adp.max_kioc            = MBOX_MAX_USER_CMDS;
3547
3548         if ((rval = mraid_mm_register_adp(&adp)) != 0) {
3549
3550                 con_log(CL_ANN, (KERN_WARNING
3551                         "megaraid mbox: did not register with CMM\n"));
3552
3553                 kfree(adapter->uscb_list);
3554         }
3555
3556         return rval;
3557 }
3558
3559
3560 /**
3561  * megaraid_cmm_unregister - un-register with the mangement module
3562  * @adapter             : HBA soft state
3563  *
3564  * Un-register with the management module.
3565  * FIXME: mgmt module must return failure for unregister if it has pending
3566  * commands in LLD.
3567  */
3568 static int
3569 megaraid_cmm_unregister(adapter_t *adapter)
3570 {
3571         kfree(adapter->uscb_list);
3572         mraid_mm_unregister_adp(adapter->unique_id);
3573         return 0;
3574 }
3575
3576
3577 /**
3578  * megaraid_mbox_mm_handler - interface for CMM to issue commands to LLD
3579  * @drvr_data           : LLD specific data
3580  * @kioc                : CMM interface packet
3581  * @action              : command action
3582  *
3583  * This routine is invoked whenever the Common Mangement Module (CMM) has a
3584  * command for us. The 'action' parameter specifies if this is a new command
3585  * or otherwise.
3586  */
3587 static int
3588 megaraid_mbox_mm_handler(unsigned long drvr_data, uioc_t *kioc, uint32_t action)
3589 {
3590         adapter_t *adapter;
3591
3592         if (action != IOCTL_ISSUE) {
3593                 con_log(CL_ANN, (KERN_WARNING
3594                         "megaraid: unsupported management action:%#2x\n",
3595                         action));
3596                 return (-ENOTSUPP);
3597         }
3598
3599         adapter = (adapter_t *)drvr_data;
3600
3601         // make sure this adapter is not being detached right now.
3602         if (atomic_read(&adapter->being_detached)) {
3603                 con_log(CL_ANN, (KERN_WARNING
3604                         "megaraid: reject management request, detaching\n"));
3605                 return (-ENODEV);
3606         }
3607
3608         switch (kioc->opcode) {
3609
3610         case GET_ADAP_INFO:
3611
3612                 kioc->status =  gather_hbainfo(adapter, (mraid_hba_info_t *)
3613                                         (unsigned long)kioc->buf_vaddr);
3614
3615                 kioc->done(kioc);
3616
3617                 return kioc->status;
3618
3619         case MBOX_CMD:
3620
3621                 return megaraid_mbox_mm_command(adapter, kioc);
3622
3623         default:
3624                 kioc->status = (-EINVAL);
3625                 kioc->done(kioc);
3626                 return (-EINVAL);
3627         }
3628
3629         return 0;       // not reached
3630 }
3631
3632 /**
3633  * megaraid_mbox_mm_command - issues commands routed through CMM
3634  * @adapter             : HBA soft state
3635  * @kioc                : management command packet
3636  *
3637  * Issues commands, which are routed through the management module.
3638  */
3639 static int
3640 megaraid_mbox_mm_command(adapter_t *adapter, uioc_t *kioc)
3641 {
3642         struct list_head        *head = &adapter->uscb_pool;
3643         mbox64_t                *mbox64;
3644         uint8_t                 *raw_mbox;
3645         scb_t                   *scb;
3646         mbox_ccb_t              *ccb;
3647         unsigned long           flags;
3648
3649         // detach one scb from free pool
3650         spin_lock_irqsave(USER_FREE_LIST_LOCK(adapter), flags);
3651
3652         if (list_empty(head)) { // should never happen because of CMM
3653
3654                 con_log(CL_ANN, (KERN_WARNING
3655                         "megaraid mbox: bug in cmm handler, lost resources\n"));
3656
3657                 spin_unlock_irqrestore(USER_FREE_LIST_LOCK(adapter), flags);
3658
3659                 return (-EINVAL);
3660         }
3661
3662         scb = list_entry(head->next, scb_t, list);
3663         list_del_init(&scb->list);
3664
3665         spin_unlock_irqrestore(USER_FREE_LIST_LOCK(adapter), flags);
3666
3667         scb->state              = SCB_ACTIVE;
3668         scb->dma_type           = MRAID_DMA_NONE;
3669         scb->dma_direction      = PCI_DMA_NONE;
3670
3671         ccb             = (mbox_ccb_t *)scb->ccb;
3672         mbox64          = (mbox64_t *)(unsigned long)kioc->cmdbuf;
3673         raw_mbox        = (uint8_t *)&mbox64->mbox32;
3674
3675         memcpy(ccb->mbox64, mbox64, sizeof(mbox64_t));
3676
3677         scb->gp         = (unsigned long)kioc;
3678
3679         /*
3680          * If it is a logdrv random delete operation, we have to wait till
3681          * there are no outstanding cmds at the fw and then issue it directly
3682          */
3683         if (raw_mbox[0] == FC_DEL_LOGDRV && raw_mbox[2] == OP_DEL_LOGDRV) {
3684
3685                 if (wait_till_fw_empty(adapter)) {
3686                         con_log(CL_ANN, (KERN_NOTICE
3687                                 "megaraid mbox: LD delete, timed out\n"));
3688
3689                         kioc->status = -ETIME;
3690
3691                         scb->status = -1;
3692
3693                         megaraid_mbox_mm_done(adapter, scb);
3694
3695                         return (-ETIME);
3696                 }
3697
3698                 INIT_LIST_HEAD(&scb->list);
3699
3700                 scb->state = SCB_ISSUED;
3701                 if (mbox_post_cmd(adapter, scb) != 0) {
3702
3703                         con_log(CL_ANN, (KERN_NOTICE
3704                                 "megaraid mbox: LD delete, mailbox busy\n"));
3705
3706                         kioc->status = -EBUSY;
3707
3708                         scb->status = -1;
3709
3710                         megaraid_mbox_mm_done(adapter, scb);
3711
3712                         return (-EBUSY);
3713                 }
3714
3715                 return 0;
3716         }
3717
3718         // put the command on the pending list and execute
3719         megaraid_mbox_runpendq(adapter, scb);
3720
3721         return 0;
3722 }
3723
3724
3725 static int
3726 wait_till_fw_empty(adapter_t *adapter)
3727 {
3728         unsigned long   flags = 0;
3729         int             i;
3730
3731
3732         /*
3733          * Set the quiescent flag to stop issuing cmds to FW.
3734          */
3735         spin_lock_irqsave(&adapter->lock, flags);
3736         adapter->quiescent++;
3737         spin_unlock_irqrestore(&adapter->lock, flags);
3738
3739         /*
3740          * Wait till there are no more cmds outstanding at FW. Try for at most
3741          * 60 seconds
3742          */
3743         for (i = 0; i < 60 && adapter->outstanding_cmds; i++) {
3744                 con_log(CL_DLEVEL1, (KERN_INFO
3745                         "megaraid: FW has %d pending commands\n",
3746                         adapter->outstanding_cmds));
3747
3748                 msleep(1000);
3749         }
3750
3751         return adapter->outstanding_cmds;
3752 }
3753
3754
3755 /**
3756  * megaraid_mbox_mm_done - callback for CMM commands
3757  * @adapter     : HBA soft state
3758  * @scb         : completed command
3759  *
3760  * Callback routine for internal commands originated from the management
3761  * module.
3762  */
3763 static void
3764 megaraid_mbox_mm_done(adapter_t *adapter, scb_t *scb)
3765 {
3766         uioc_t                  *kioc;
3767         mbox64_t                *mbox64;
3768         uint8_t                 *raw_mbox;
3769         unsigned long           flags;
3770
3771         kioc                    = (uioc_t *)scb->gp;
3772         mbox64                  = (mbox64_t *)(unsigned long)kioc->cmdbuf;
3773         mbox64->mbox32.status   = scb->status;
3774         raw_mbox                = (uint8_t *)&mbox64->mbox32;
3775
3776
3777         // put scb in the free pool
3778         scb->state      = SCB_FREE;
3779         scb->scp        = NULL;
3780
3781         spin_lock_irqsave(USER_FREE_LIST_LOCK(adapter), flags);
3782
3783         list_add(&scb->list, &adapter->uscb_pool);
3784
3785         spin_unlock_irqrestore(USER_FREE_LIST_LOCK(adapter), flags);
3786
3787         // if a delete logical drive operation succeeded, restart the
3788         // controller
3789         if (raw_mbox[0] == FC_DEL_LOGDRV && raw_mbox[2] == OP_DEL_LOGDRV) {
3790
3791                 adapter->quiescent--;
3792
3793                 megaraid_mbox_runpendq(adapter, NULL);
3794         }
3795
3796         kioc->done(kioc);
3797
3798         return;
3799 }
3800
3801
3802 /**
3803  * gather_hbainfo - HBA characteristics for the applications
3804  * @adapter             : HBA soft state
3805  * @hinfo               : pointer to the caller's host info strucuture
3806  */
3807 static int
3808 gather_hbainfo(adapter_t *adapter, mraid_hba_info_t *hinfo)
3809 {
3810         uint8_t dmajor;
3811
3812         dmajor                  = megaraid_mbox_version[0];
3813
3814         hinfo->pci_vendor_id    = adapter->pdev->vendor;
3815         hinfo->pci_device_id    = adapter->pdev->device;
3816         hinfo->subsys_vendor_id = adapter->pdev->subsystem_vendor;
3817         hinfo->subsys_device_id = adapter->pdev->subsystem_device;
3818
3819         hinfo->pci_bus          = adapter->pdev->bus->number;
3820         hinfo->pci_dev_fn       = adapter->pdev->devfn;
3821         hinfo->pci_slot         = PCI_SLOT(adapter->pdev->devfn);
3822         hinfo->irq              = adapter->host->irq;
3823         hinfo->baseport         = ADAP2RAIDDEV(adapter)->baseport;
3824
3825         hinfo->unique_id        = (hinfo->pci_bus << 8) | adapter->pdev->devfn;
3826         hinfo->host_no          = adapter->host->host_no;
3827
3828         return 0;
3829 }
3830
3831 /*
3832  * END: Interface for the common management module
3833  */
3834
3835
3836
3837 /**
3838  * megaraid_sysfs_alloc_resources - allocate sysfs related resources
3839  * @adapter     : controller's soft state
3840  *
3841  * Allocate packets required to issue FW calls whenever the sysfs attributes
3842  * are read. These attributes would require up-to-date information from the
3843  * FW. Also set up resources for mutual exclusion to share these resources and
3844  * the wait queue.
3845  *
3846  * Return 0 on success.
3847  * Return -ERROR_CODE on failure.
3848  */
3849 static int
3850 megaraid_sysfs_alloc_resources(adapter_t *adapter)
3851 {
3852         mraid_device_t  *raid_dev = ADAP2RAIDDEV(adapter);
3853         int             rval = 0;
3854
3855         raid_dev->sysfs_uioc = kmalloc(sizeof(uioc_t), GFP_KERNEL);
3856
3857         raid_dev->sysfs_mbox64 = kmalloc(sizeof(mbox64_t), GFP_KERNEL);
3858
3859         raid_dev->sysfs_buffer = pci_alloc_consistent(adapter->pdev,
3860                         PAGE_SIZE, &raid_dev->sysfs_buffer_dma);
3861
3862         if (!raid_dev->sysfs_uioc || !raid_dev->sysfs_mbox64 ||
3863                 !raid_dev->sysfs_buffer) {
3864
3865                 con_log(CL_ANN, (KERN_WARNING
3866                         "megaraid: out of memory, %s %d\n", __FUNCTION__,
3867                         __LINE__));
3868
3869                 rval = -ENOMEM;
3870
3871                 megaraid_sysfs_free_resources(adapter);
3872         }
3873
3874         mutex_init(&raid_dev->sysfs_mtx);
3875
3876         init_waitqueue_head(&raid_dev->sysfs_wait_q);
3877
3878         return rval;
3879 }
3880
3881
3882 /**
3883  * megaraid_sysfs_free_resources - free sysfs related resources
3884  * @adapter     : controller's soft state
3885  *
3886  * Free packets allocated for sysfs FW commands
3887  */
3888 static void
3889 megaraid_sysfs_free_resources(adapter_t *adapter)
3890 {
3891         mraid_device_t  *raid_dev = ADAP2RAIDDEV(adapter);
3892
3893         kfree(raid_dev->sysfs_uioc);
3894         kfree(raid_dev->sysfs_mbox64);
3895
3896         if (raid_dev->sysfs_buffer) {
3897                 pci_free_consistent(adapter->pdev, PAGE_SIZE,
3898                         raid_dev->sysfs_buffer, raid_dev->sysfs_buffer_dma);
3899         }
3900 }
3901
3902
3903 /**
3904  * megaraid_sysfs_get_ldmap_done - callback for get ldmap
3905  * @uioc        : completed packet
3906  *
3907  * Callback routine called in the ISR/tasklet context for get ldmap call
3908  */
3909 static void
3910 megaraid_sysfs_get_ldmap_done(uioc_t *uioc)
3911 {
3912         adapter_t       *adapter = (adapter_t *)uioc->buf_vaddr;
3913         mraid_device_t  *raid_dev = ADAP2RAIDDEV(adapter);
3914
3915         uioc->status = 0;
3916
3917         wake_up(&raid_dev->sysfs_wait_q);
3918 }
3919
3920
3921 /**
3922  * megaraid_sysfs_get_ldmap_timeout - timeout handling for get ldmap
3923  * @data        : timed out packet
3924  *
3925  * Timeout routine to recover and return to application, in case the adapter
3926  * has stopped responding. A timeout of 60 seconds for this command seems like
3927  * a good value.
3928  */
3929 static void
3930 megaraid_sysfs_get_ldmap_timeout(unsigned long data)
3931 {
3932         uioc_t          *uioc = (uioc_t *)data;
3933         adapter_t       *adapter = (adapter_t *)uioc->buf_vaddr;
3934         mraid_device_t  *raid_dev = ADAP2RAIDDEV(adapter);
3935
3936         uioc->status = -ETIME;
3937
3938         wake_up(&raid_dev->sysfs_wait_q);
3939 }
3940
3941
3942 /**
3943  * megaraid_sysfs_get_ldmap - get update logical drive map
3944  * @adapter     : controller's soft state
3945  *
3946  * This routine will be called whenever user reads the logical drive
3947  * attributes, go get the current logical drive mapping table from the
3948  * firmware. We use the managment API's to issue commands to the controller.
3949  *
3950  * NOTE: The commands issuance functionality is not generalized and
3951  * implemented in context of "get ld map" command only. If required, the
3952  * command issuance logical can be trivially pulled out and implemented as a
3953  * standalone libary. For now, this should suffice since there is no other
3954  * user of this interface.
3955  *
3956  * Return 0 on success.
3957  * Return -1 on failure.
3958  */
3959 static int
3960 megaraid_sysfs_get_ldmap(adapter_t *adapter)
3961 {
3962         mraid_device_t          *raid_dev = ADAP2RAIDDEV(adapter);
3963         uioc_t                  *uioc;
3964         mbox64_t                *mbox64;
3965         mbox_t                  *mbox;
3966         char                    *raw_mbox;
3967         struct timer_list       sysfs_timer;
3968         struct timer_list       *timerp;
3969         caddr_t                 ldmap;
3970         int                     rval = 0;
3971
3972         /*
3973          * Allow only one read at a time to go through the sysfs attributes
3974          */
3975         mutex_lock(&raid_dev->sysfs_mtx);
3976
3977         uioc    = raid_dev->sysfs_uioc;
3978         mbox64  = raid_dev->sysfs_mbox64;
3979         ldmap   = raid_dev->sysfs_buffer;
3980
3981         memset(uioc, 0, sizeof(uioc_t));
3982         memset(mbox64, 0, sizeof(mbox64_t));
3983         memset(ldmap, 0, sizeof(raid_dev->curr_ldmap));
3984
3985         mbox            = &mbox64->mbox32;
3986         raw_mbox        = (char *)mbox;
3987         uioc->cmdbuf    = (uint64_t)(unsigned long)mbox64;
3988         uioc->buf_vaddr = (caddr_t)adapter;
3989         uioc->status    = -ENODATA;
3990         uioc->done      = megaraid_sysfs_get_ldmap_done;
3991
3992         /*
3993          * Prepare the mailbox packet to get the current logical drive mapping
3994          * table
3995          */
3996         mbox->xferaddr = (uint32_t)raid_dev->sysfs_buffer_dma;
3997
3998         raw_mbox[0] = FC_DEL_LOGDRV;
3999         raw_mbox[2] = OP_GET_LDID_MAP;
4000
4001         /*
4002          * Setup a timer to recover from a non-responding controller
4003          */
4004         timerp  = &sysfs_timer;
4005         init_timer(timerp);
4006
4007         timerp->function        = megaraid_sysfs_get_ldmap_timeout;
4008         timerp->data            = (unsigned long)uioc;
4009         timerp->expires         = jiffies + 60 * HZ;
4010
4011         add_timer(timerp);
4012
4013         /*
4014          * Send the command to the firmware
4015          */
4016         rval = megaraid_mbox_mm_command(adapter, uioc);
4017
4018         if (rval == 0) {        // command successfully issued
4019                 wait_event(raid_dev->sysfs_wait_q, (uioc->status != -ENODATA));
4020
4021                 /*
4022                  * Check if the command timed out
4023                  */
4024                 if (uioc->status == -ETIME) {
4025                         con_log(CL_ANN, (KERN_NOTICE
4026                                 "megaraid: sysfs get ld map timed out\n"));
4027
4028                         rval = -ETIME;
4029                 }
4030                 else {
4031                         rval = mbox->status;
4032                 }
4033
4034                 if (rval == 0) {
4035                         memcpy(raid_dev->curr_ldmap, ldmap,
4036                                 sizeof(raid_dev->curr_ldmap));
4037                 }
4038                 else {
4039                         con_log(CL_ANN, (KERN_NOTICE
4040                                 "megaraid: get ld map failed with %x\n", rval));
4041                 }
4042         }
4043         else {
4044                 con_log(CL_ANN, (KERN_NOTICE
4045                         "megaraid: could not issue ldmap command:%x\n", rval));
4046         }
4047
4048
4049         del_timer_sync(timerp);
4050
4051         mutex_unlock(&raid_dev->sysfs_mtx);
4052
4053         return rval;
4054 }
4055
4056
4057 /**
4058  * megaraid_sysfs_show_app_hndl - display application handle for this adapter
4059  * @cdev        : class device object representation for the host
4060  * @buf         : buffer to send data to
4061  *
4062  * Display the handle used by the applications while executing management
4063  * tasks on the adapter. We invoke a management module API to get the adapter
4064  * handle, since we do not interface with applications directly.
4065  */
4066 static ssize_t
4067 megaraid_sysfs_show_app_hndl(struct class_device *cdev, char *buf)
4068 {
4069         struct Scsi_Host *shost = class_to_shost(cdev);
4070         adapter_t       *adapter = (adapter_t *)SCSIHOST2ADAP(shost);
4071         uint32_t        app_hndl;
4072
4073         app_hndl = mraid_mm_adapter_app_handle(adapter->unique_id);
4074
4075         return snprintf(buf, 8, "%u\n", app_hndl);
4076 }
4077
4078
4079 /**
4080  * megaraid_sysfs_show_ldnum - display the logical drive number for this device
4081  * @dev         : device object representation for the scsi device
4082  * @attr        : device attribute to show
4083  * @buf         : buffer to send data to
4084  *
4085  * Display the logical drive number for the device in question, if it a valid
4086  * logical drive. For physical devices, "-1" is returned.
4087  *
4088  * The logical drive number is displayed in following format:
4089  *
4090  * <SCSI ID> <LD NUM> <LD STICKY ID> <APP ADAPTER HANDLE>
4091  *
4092  *   <int>     <int>       <int>            <int>
4093  */
4094 static ssize_t
4095 megaraid_sysfs_show_ldnum(struct device *dev, struct device_attribute *attr, char *buf)
4096 {
4097         struct scsi_device *sdev = to_scsi_device(dev);
4098         adapter_t       *adapter = (adapter_t *)SCSIHOST2ADAP(sdev->host);
4099         mraid_device_t  *raid_dev = ADAP2RAIDDEV(adapter);
4100         int             scsi_id = -1;
4101         int             logical_drv = -1;
4102         int             ldid_map = -1;
4103         uint32_t        app_hndl = 0;
4104         int             mapped_sdev_id;
4105         int             rval;
4106         int             i;
4107
4108         if (raid_dev->random_del_supported &&
4109                         MRAID_IS_LOGICAL_SDEV(adapter, sdev)) {
4110
4111                 rval = megaraid_sysfs_get_ldmap(adapter);
4112                 if (rval == 0) {
4113
4114                         for (i = 0; i < MAX_LOGICAL_DRIVES_40LD; i++) {
4115
4116                                 mapped_sdev_id = sdev->id;
4117
4118                                 if (sdev->id > adapter->init_id) {
4119                                         mapped_sdev_id -= 1;
4120                                 }
4121
4122                                 if (raid_dev->curr_ldmap[i] == mapped_sdev_id) {
4123
4124                                         scsi_id = sdev->id;
4125
4126                                         logical_drv = i;
4127
4128                                         ldid_map = raid_dev->curr_ldmap[i];
4129
4130                                         app_hndl = mraid_mm_adapter_app_handle(
4131                                                         adapter->unique_id);
4132
4133                                         break;
4134                                 }
4135                         }
4136                 }
4137                 else {
4138                         con_log(CL_ANN, (KERN_NOTICE
4139                                 "megaraid: sysfs get ld map failed: %x\n",
4140                                 rval));
4141                 }
4142         }
4143
4144         return snprintf(buf, 36, "%d %d %d %d\n", scsi_id, logical_drv,
4145                         ldid_map, app_hndl);
4146 }
4147
4148
4149 /*
4150  * END: Mailbox Low Level Driver
4151  */
4152 module_init(megaraid_init);
4153 module_exit(megaraid_exit);
4154
4155 /* vim: set ts=8 sw=8 tw=78 ai si: */