drm/radeon/kms/combios: fix dynamic allocation of PM clock modes
[pandora-kernel.git] / drivers / scsi / pmcraid.c
1 /*
2  * pmcraid.c -- driver for PMC Sierra MaxRAID controller adapters
3  *
4  * Written By: Anil Ravindranath<anil_ravindranath@pmc-sierra.com>
5  *             PMC-Sierra Inc
6  *
7  * Copyright (C) 2008, 2009 PMC Sierra Inc
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307,
22  * USA
23  *
24  */
25 #include <linux/fs.h>
26 #include <linux/init.h>
27 #include <linux/types.h>
28 #include <linux/errno.h>
29 #include <linux/kernel.h>
30 #include <linux/ioport.h>
31 #include <linux/delay.h>
32 #include <linux/pci.h>
33 #include <linux/wait.h>
34 #include <linux/spinlock.h>
35 #include <linux/sched.h>
36 #include <linux/interrupt.h>
37 #include <linux/blkdev.h>
38 #include <linux/firmware.h>
39 #include <linux/module.h>
40 #include <linux/moduleparam.h>
41 #include <linux/hdreg.h>
42 #include <linux/io.h>
43 #include <linux/slab.h>
44 #include <asm/irq.h>
45 #include <asm/processor.h>
46 #include <linux/libata.h>
47 #include <linux/mutex.h>
48 #include <scsi/scsi.h>
49 #include <scsi/scsi_host.h>
50 #include <scsi/scsi_device.h>
51 #include <scsi/scsi_tcq.h>
52 #include <scsi/scsi_eh.h>
53 #include <scsi/scsi_cmnd.h>
54 #include <scsi/scsicam.h>
55
56 #include "pmcraid.h"
57
58 /*
59  *   Module configuration parameters
60  */
61 static unsigned int pmcraid_debug_log;
62 static unsigned int pmcraid_disable_aen;
63 static unsigned int pmcraid_log_level = IOASC_LOG_LEVEL_MUST;
64 static unsigned int pmcraid_enable_msix;
65
66 /*
67  * Data structures to support multiple adapters by the LLD.
68  * pmcraid_adapter_count - count of configured adapters
69  */
70 static atomic_t pmcraid_adapter_count = ATOMIC_INIT(0);
71
72 /*
73  * Supporting user-level control interface through IOCTL commands.
74  * pmcraid_major - major number to use
75  * pmcraid_minor - minor number(s) to use
76  */
77 static unsigned int pmcraid_major;
78 static struct class *pmcraid_class;
79 DECLARE_BITMAP(pmcraid_minor, PMCRAID_MAX_ADAPTERS);
80
81 /*
82  * Module parameters
83  */
84 MODULE_AUTHOR("Anil Ravindranath<anil_ravindranath@pmc-sierra.com>");
85 MODULE_DESCRIPTION("PMC Sierra MaxRAID Controller Driver");
86 MODULE_LICENSE("GPL");
87 MODULE_VERSION(PMCRAID_DRIVER_VERSION);
88
89 module_param_named(log_level, pmcraid_log_level, uint, (S_IRUGO | S_IWUSR));
90 MODULE_PARM_DESC(log_level,
91                  "Enables firmware error code logging, default :1 high-severity"
92                  " errors, 2: all errors including high-severity errors,"
93                  " 0: disables logging");
94
95 module_param_named(debug, pmcraid_debug_log, uint, (S_IRUGO | S_IWUSR));
96 MODULE_PARM_DESC(debug,
97                  "Enable driver verbose message logging. Set 1 to enable."
98                  "(default: 0)");
99
100 module_param_named(disable_aen, pmcraid_disable_aen, uint, (S_IRUGO | S_IWUSR));
101 MODULE_PARM_DESC(disable_aen,
102                  "Disable driver aen notifications to apps. Set 1 to disable."
103                  "(default: 0)");
104
105 /* chip specific constants for PMC MaxRAID controllers (same for
106  * 0x5220 and 0x8010
107  */
108 static struct pmcraid_chip_details pmcraid_chip_cfg[] = {
109         {
110          .ioastatus = 0x0,
111          .ioarrin = 0x00040,
112          .mailbox = 0x7FC30,
113          .global_intr_mask = 0x00034,
114          .ioa_host_intr = 0x0009C,
115          .ioa_host_intr_clr = 0x000A0,
116          .ioa_host_msix_intr = 0x7FC40,
117          .ioa_host_mask = 0x7FC28,
118          .ioa_host_mask_clr = 0x7FC28,
119          .host_ioa_intr = 0x00020,
120          .host_ioa_intr_clr = 0x00020,
121          .transop_timeout = 300
122          }
123 };
124
125 /*
126  * PCI device ids supported by pmcraid driver
127  */
128 static struct pci_device_id pmcraid_pci_table[] __devinitdata = {
129         { PCI_DEVICE(PCI_VENDOR_ID_PMC, PCI_DEVICE_ID_PMC_MAXRAID),
130           0, 0, (kernel_ulong_t)&pmcraid_chip_cfg[0]
131         },
132         {}
133 };
134
135 MODULE_DEVICE_TABLE(pci, pmcraid_pci_table);
136
137
138
139 /**
140  * pmcraid_slave_alloc - Prepare for commands to a device
141  * @scsi_dev: scsi device struct
142  *
143  * This function is called by mid-layer prior to sending any command to the new
144  * device. Stores resource entry details of the device in scsi_device struct.
145  * Queuecommand uses the resource handle and other details to fill up IOARCB
146  * while sending commands to the device.
147  *
148  * Return value:
149  *        0 on success / -ENXIO if device does not exist
150  */
151 static int pmcraid_slave_alloc(struct scsi_device *scsi_dev)
152 {
153         struct pmcraid_resource_entry *temp, *res = NULL;
154         struct pmcraid_instance *pinstance;
155         u8 target, bus, lun;
156         unsigned long lock_flags;
157         int rc = -ENXIO;
158         u16 fw_version;
159
160         pinstance = shost_priv(scsi_dev->host);
161
162         fw_version = be16_to_cpu(pinstance->inq_data->fw_version);
163
164         /* Driver exposes VSET and GSCSI resources only; all other device types
165          * are not exposed. Resource list is synchronized using resource lock
166          * so any traversal or modifications to the list should be done inside
167          * this lock
168          */
169         spin_lock_irqsave(&pinstance->resource_lock, lock_flags);
170         list_for_each_entry(temp, &pinstance->used_res_q, queue) {
171
172                 /* do not expose VSETs with order-ids > MAX_VSET_TARGETS */
173                 if (RES_IS_VSET(temp->cfg_entry)) {
174                         if (fw_version <= PMCRAID_FW_VERSION_1)
175                                 target = temp->cfg_entry.unique_flags1;
176                         else
177                                 target = temp->cfg_entry.array_id & 0xFF;
178
179                         if (target > PMCRAID_MAX_VSET_TARGETS)
180                                 continue;
181                         bus = PMCRAID_VSET_BUS_ID;
182                         lun = 0;
183                 } else if (RES_IS_GSCSI(temp->cfg_entry)) {
184                         target = RES_TARGET(temp->cfg_entry.resource_address);
185                         bus = PMCRAID_PHYS_BUS_ID;
186                         lun = RES_LUN(temp->cfg_entry.resource_address);
187                 } else {
188                         continue;
189                 }
190
191                 if (bus == scsi_dev->channel &&
192                     target == scsi_dev->id &&
193                     lun == scsi_dev->lun) {
194                         res = temp;
195                         break;
196                 }
197         }
198
199         if (res) {
200                 res->scsi_dev = scsi_dev;
201                 scsi_dev->hostdata = res;
202                 res->change_detected = 0;
203                 atomic_set(&res->read_failures, 0);
204                 atomic_set(&res->write_failures, 0);
205                 rc = 0;
206         }
207         spin_unlock_irqrestore(&pinstance->resource_lock, lock_flags);
208         return rc;
209 }
210
211 /**
212  * pmcraid_slave_configure - Configures a SCSI device
213  * @scsi_dev: scsi device struct
214  *
215  * This function is executed by SCSI mid layer just after a device is first
216  * scanned (i.e. it has responded to an INQUIRY). For VSET resources, the
217  * timeout value (default 30s) will be over-written to a higher value (60s)
218  * and max_sectors value will be over-written to 512. It also sets queue depth
219  * to host->cmd_per_lun value
220  *
221  * Return value:
222  *        0 on success
223  */
224 static int pmcraid_slave_configure(struct scsi_device *scsi_dev)
225 {
226         struct pmcraid_resource_entry *res = scsi_dev->hostdata;
227
228         if (!res)
229                 return 0;
230
231         /* LLD exposes VSETs and Enclosure devices only */
232         if (RES_IS_GSCSI(res->cfg_entry) &&
233             scsi_dev->type != TYPE_ENCLOSURE)
234                 return -ENXIO;
235
236         pmcraid_info("configuring %x:%x:%x:%x\n",
237                      scsi_dev->host->unique_id,
238                      scsi_dev->channel,
239                      scsi_dev->id,
240                      scsi_dev->lun);
241
242         if (RES_IS_GSCSI(res->cfg_entry)) {
243                 scsi_dev->allow_restart = 1;
244         } else if (RES_IS_VSET(res->cfg_entry)) {
245                 scsi_dev->allow_restart = 1;
246                 blk_queue_rq_timeout(scsi_dev->request_queue,
247                                      PMCRAID_VSET_IO_TIMEOUT);
248                 blk_queue_max_hw_sectors(scsi_dev->request_queue,
249                                       PMCRAID_VSET_MAX_SECTORS);
250         }
251
252         if (scsi_dev->tagged_supported &&
253             (RES_IS_GSCSI(res->cfg_entry) || RES_IS_VSET(res->cfg_entry))) {
254                 scsi_activate_tcq(scsi_dev, scsi_dev->queue_depth);
255                 scsi_adjust_queue_depth(scsi_dev, MSG_SIMPLE_TAG,
256                                         scsi_dev->host->cmd_per_lun);
257         } else {
258                 scsi_adjust_queue_depth(scsi_dev, 0,
259                                         scsi_dev->host->cmd_per_lun);
260         }
261
262         return 0;
263 }
264
265 /**
266  * pmcraid_slave_destroy - Unconfigure a SCSI device before removing it
267  *
268  * @scsi_dev: scsi device struct
269  *
270  * This is called by mid-layer before removing a device. Pointer assignments
271  * done in pmcraid_slave_alloc will be reset to NULL here.
272  *
273  * Return value
274  *   none
275  */
276 static void pmcraid_slave_destroy(struct scsi_device *scsi_dev)
277 {
278         struct pmcraid_resource_entry *res;
279
280         res = (struct pmcraid_resource_entry *)scsi_dev->hostdata;
281
282         if (res)
283                 res->scsi_dev = NULL;
284
285         scsi_dev->hostdata = NULL;
286 }
287
288 /**
289  * pmcraid_change_queue_depth - Change the device's queue depth
290  * @scsi_dev: scsi device struct
291  * @depth: depth to set
292  * @reason: calling context
293  *
294  * Return value
295  *      actual depth set
296  */
297 static int pmcraid_change_queue_depth(struct scsi_device *scsi_dev, int depth,
298                                       int reason)
299 {
300         if (reason != SCSI_QDEPTH_DEFAULT)
301                 return -EOPNOTSUPP;
302
303         if (depth > PMCRAID_MAX_CMD_PER_LUN)
304                 depth = PMCRAID_MAX_CMD_PER_LUN;
305
306         scsi_adjust_queue_depth(scsi_dev, scsi_get_tag_type(scsi_dev), depth);
307
308         return scsi_dev->queue_depth;
309 }
310
311 /**
312  * pmcraid_change_queue_type - Change the device's queue type
313  * @scsi_dev: scsi device struct
314  * @tag: type of tags to use
315  *
316  * Return value:
317  *      actual queue type set
318  */
319 static int pmcraid_change_queue_type(struct scsi_device *scsi_dev, int tag)
320 {
321         struct pmcraid_resource_entry *res;
322
323         res = (struct pmcraid_resource_entry *)scsi_dev->hostdata;
324
325         if ((res) && scsi_dev->tagged_supported &&
326             (RES_IS_GSCSI(res->cfg_entry) || RES_IS_VSET(res->cfg_entry))) {
327                 scsi_set_tag_type(scsi_dev, tag);
328
329                 if (tag)
330                         scsi_activate_tcq(scsi_dev, scsi_dev->queue_depth);
331                 else
332                         scsi_deactivate_tcq(scsi_dev, scsi_dev->queue_depth);
333         } else
334                 tag = 0;
335
336         return tag;
337 }
338
339
340 /**
341  * pmcraid_init_cmdblk - initializes a command block
342  *
343  * @cmd: pointer to struct pmcraid_cmd to be initialized
344  * @index: if >=0 first time initialization; otherwise reinitialization
345  *
346  * Return Value
347  *       None
348  */
349 void pmcraid_init_cmdblk(struct pmcraid_cmd *cmd, int index)
350 {
351         struct pmcraid_ioarcb *ioarcb = &(cmd->ioa_cb->ioarcb);
352         dma_addr_t dma_addr = cmd->ioa_cb_bus_addr;
353
354         if (index >= 0) {
355                 /* first time initialization (called from  probe) */
356                 u32 ioasa_offset =
357                         offsetof(struct pmcraid_control_block, ioasa);
358
359                 cmd->index = index;
360                 ioarcb->response_handle = cpu_to_le32(index << 2);
361                 ioarcb->ioarcb_bus_addr = cpu_to_le64(dma_addr);
362                 ioarcb->ioasa_bus_addr = cpu_to_le64(dma_addr + ioasa_offset);
363                 ioarcb->ioasa_len = cpu_to_le16(sizeof(struct pmcraid_ioasa));
364         } else {
365                 /* re-initialization of various lengths, called once command is
366                  * processed by IOA
367                  */
368                 memset(&cmd->ioa_cb->ioarcb.cdb, 0, PMCRAID_MAX_CDB_LEN);
369                 ioarcb->hrrq_id = 0;
370                 ioarcb->request_flags0 = 0;
371                 ioarcb->request_flags1 = 0;
372                 ioarcb->cmd_timeout = 0;
373                 ioarcb->ioarcb_bus_addr &= (~0x1FULL);
374                 ioarcb->ioadl_bus_addr = 0;
375                 ioarcb->ioadl_length = 0;
376                 ioarcb->data_transfer_length = 0;
377                 ioarcb->add_cmd_param_length = 0;
378                 ioarcb->add_cmd_param_offset = 0;
379                 cmd->ioa_cb->ioasa.ioasc = 0;
380                 cmd->ioa_cb->ioasa.residual_data_length = 0;
381                 cmd->time_left = 0;
382         }
383
384         cmd->cmd_done = NULL;
385         cmd->scsi_cmd = NULL;
386         cmd->release = 0;
387         cmd->completion_req = 0;
388         cmd->sense_buffer = 0;
389         cmd->sense_buffer_dma = 0;
390         cmd->dma_handle = 0;
391         init_timer(&cmd->timer);
392 }
393
394 /**
395  * pmcraid_reinit_cmdblk - reinitialize a command block
396  *
397  * @cmd: pointer to struct pmcraid_cmd to be reinitialized
398  *
399  * Return Value
400  *       None
401  */
402 static void pmcraid_reinit_cmdblk(struct pmcraid_cmd *cmd)
403 {
404         pmcraid_init_cmdblk(cmd, -1);
405 }
406
407 /**
408  * pmcraid_get_free_cmd - get a free cmd block from command block pool
409  * @pinstance: adapter instance structure
410  *
411  * Return Value:
412  *      returns pointer to cmd block or NULL if no blocks are available
413  */
414 static struct pmcraid_cmd *pmcraid_get_free_cmd(
415         struct pmcraid_instance *pinstance
416 )
417 {
418         struct pmcraid_cmd *cmd = NULL;
419         unsigned long lock_flags;
420
421         /* free cmd block list is protected by free_pool_lock */
422         spin_lock_irqsave(&pinstance->free_pool_lock, lock_flags);
423
424         if (!list_empty(&pinstance->free_cmd_pool)) {
425                 cmd = list_entry(pinstance->free_cmd_pool.next,
426                                  struct pmcraid_cmd, free_list);
427                 list_del(&cmd->free_list);
428         }
429         spin_unlock_irqrestore(&pinstance->free_pool_lock, lock_flags);
430
431         /* Initialize the command block before giving it the caller */
432         if (cmd != NULL)
433                 pmcraid_reinit_cmdblk(cmd);
434         return cmd;
435 }
436
437 /**
438  * pmcraid_return_cmd - return a completed command block back into free pool
439  * @cmd: pointer to the command block
440  *
441  * Return Value:
442  *      nothing
443  */
444 void pmcraid_return_cmd(struct pmcraid_cmd *cmd)
445 {
446         struct pmcraid_instance *pinstance = cmd->drv_inst;
447         unsigned long lock_flags;
448
449         spin_lock_irqsave(&pinstance->free_pool_lock, lock_flags);
450         list_add_tail(&cmd->free_list, &pinstance->free_cmd_pool);
451         spin_unlock_irqrestore(&pinstance->free_pool_lock, lock_flags);
452 }
453
454 /**
455  * pmcraid_read_interrupts -  reads IOA interrupts
456  *
457  * @pinstance: pointer to adapter instance structure
458  *
459  * Return value
460  *       interrupts read from IOA
461  */
462 static u32 pmcraid_read_interrupts(struct pmcraid_instance *pinstance)
463 {
464         return (pinstance->interrupt_mode) ?
465                 ioread32(pinstance->int_regs.ioa_host_msix_interrupt_reg) :
466                 ioread32(pinstance->int_regs.ioa_host_interrupt_reg);
467 }
468
469 /**
470  * pmcraid_disable_interrupts - Masks and clears all specified interrupts
471  *
472  * @pinstance: pointer to per adapter instance structure
473  * @intrs: interrupts to disable
474  *
475  * Return Value
476  *       None
477  */
478 static void pmcraid_disable_interrupts(
479         struct pmcraid_instance *pinstance,
480         u32 intrs
481 )
482 {
483         u32 gmask = ioread32(pinstance->int_regs.global_interrupt_mask_reg);
484         u32 nmask = gmask | GLOBAL_INTERRUPT_MASK;
485
486         iowrite32(intrs, pinstance->int_regs.ioa_host_interrupt_clr_reg);
487         iowrite32(nmask, pinstance->int_regs.global_interrupt_mask_reg);
488         ioread32(pinstance->int_regs.global_interrupt_mask_reg);
489
490         if (!pinstance->interrupt_mode) {
491                 iowrite32(intrs,
492                         pinstance->int_regs.ioa_host_interrupt_mask_reg);
493                 ioread32(pinstance->int_regs.ioa_host_interrupt_mask_reg);
494         }
495 }
496
497 /**
498  * pmcraid_enable_interrupts - Enables specified interrupts
499  *
500  * @pinstance: pointer to per adapter instance structure
501  * @intr: interrupts to enable
502  *
503  * Return Value
504  *       None
505  */
506 static void pmcraid_enable_interrupts(
507         struct pmcraid_instance *pinstance,
508         u32 intrs
509 )
510 {
511         u32 gmask = ioread32(pinstance->int_regs.global_interrupt_mask_reg);
512         u32 nmask = gmask & (~GLOBAL_INTERRUPT_MASK);
513
514         iowrite32(nmask, pinstance->int_regs.global_interrupt_mask_reg);
515
516         if (!pinstance->interrupt_mode) {
517                 iowrite32(~intrs,
518                          pinstance->int_regs.ioa_host_interrupt_mask_reg);
519                 ioread32(pinstance->int_regs.ioa_host_interrupt_mask_reg);
520         }
521
522         pmcraid_info("enabled interrupts global mask = %x intr_mask = %x\n",
523                 ioread32(pinstance->int_regs.global_interrupt_mask_reg),
524                 ioread32(pinstance->int_regs.ioa_host_interrupt_mask_reg));
525 }
526
527 /**
528  * pmcraid_clr_trans_op - clear trans to op interrupt
529  *
530  * @pinstance: pointer to per adapter instance structure
531  *
532  * Return Value
533  *       None
534  */
535 static void pmcraid_clr_trans_op(
536         struct pmcraid_instance *pinstance
537 )
538 {
539         unsigned long lock_flags;
540
541         if (!pinstance->interrupt_mode) {
542                 iowrite32(INTRS_TRANSITION_TO_OPERATIONAL,
543                         pinstance->int_regs.ioa_host_interrupt_mask_reg);
544                 ioread32(pinstance->int_regs.ioa_host_interrupt_mask_reg);
545                 iowrite32(INTRS_TRANSITION_TO_OPERATIONAL,
546                         pinstance->int_regs.ioa_host_interrupt_clr_reg);
547                 ioread32(pinstance->int_regs.ioa_host_interrupt_clr_reg);
548         }
549
550         if (pinstance->reset_cmd != NULL) {
551                 del_timer(&pinstance->reset_cmd->timer);
552                 spin_lock_irqsave(
553                         pinstance->host->host_lock, lock_flags);
554                 pinstance->reset_cmd->cmd_done(pinstance->reset_cmd);
555                 spin_unlock_irqrestore(
556                         pinstance->host->host_lock, lock_flags);
557         }
558 }
559
560 /**
561  * pmcraid_reset_type - Determine the required reset type
562  * @pinstance: pointer to adapter instance structure
563  *
564  * IOA requires hard reset if any of the following conditions is true.
565  * 1. If HRRQ valid interrupt is not masked
566  * 2. IOA reset alert doorbell is set
567  * 3. If there are any error interrupts
568  */
569 static void pmcraid_reset_type(struct pmcraid_instance *pinstance)
570 {
571         u32 mask;
572         u32 intrs;
573         u32 alerts;
574
575         mask = ioread32(pinstance->int_regs.ioa_host_interrupt_mask_reg);
576         intrs = ioread32(pinstance->int_regs.ioa_host_interrupt_reg);
577         alerts = ioread32(pinstance->int_regs.host_ioa_interrupt_reg);
578
579         if ((mask & INTRS_HRRQ_VALID) == 0 ||
580             (alerts & DOORBELL_IOA_RESET_ALERT) ||
581             (intrs & PMCRAID_ERROR_INTERRUPTS)) {
582                 pmcraid_info("IOA requires hard reset\n");
583                 pinstance->ioa_hard_reset = 1;
584         }
585
586         /* If unit check is active, trigger the dump */
587         if (intrs & INTRS_IOA_UNIT_CHECK)
588                 pinstance->ioa_unit_check = 1;
589 }
590
591 /**
592  * pmcraid_bist_done - completion function for PCI BIST
593  * @cmd: pointer to reset command
594  * Return Value
595  *      none
596  */
597
598 static void pmcraid_ioa_reset(struct pmcraid_cmd *);
599
600 static void pmcraid_bist_done(struct pmcraid_cmd *cmd)
601 {
602         struct pmcraid_instance *pinstance = cmd->drv_inst;
603         unsigned long lock_flags;
604         int rc;
605         u16 pci_reg;
606
607         rc = pci_read_config_word(pinstance->pdev, PCI_COMMAND, &pci_reg);
608
609         /* If PCI config space can't be accessed wait for another two secs */
610         if ((rc != PCIBIOS_SUCCESSFUL || (!(pci_reg & PCI_COMMAND_MEMORY))) &&
611             cmd->time_left > 0) {
612                 pmcraid_info("BIST not complete, waiting another 2 secs\n");
613                 cmd->timer.expires = jiffies + cmd->time_left;
614                 cmd->time_left = 0;
615                 cmd->timer.data = (unsigned long)cmd;
616                 cmd->timer.function =
617                         (void (*)(unsigned long))pmcraid_bist_done;
618                 add_timer(&cmd->timer);
619         } else {
620                 cmd->time_left = 0;
621                 pmcraid_info("BIST is complete, proceeding with reset\n");
622                 spin_lock_irqsave(pinstance->host->host_lock, lock_flags);
623                 pmcraid_ioa_reset(cmd);
624                 spin_unlock_irqrestore(pinstance->host->host_lock, lock_flags);
625         }
626 }
627
628 /**
629  * pmcraid_start_bist - starts BIST
630  * @cmd: pointer to reset cmd
631  * Return Value
632  *   none
633  */
634 static void pmcraid_start_bist(struct pmcraid_cmd *cmd)
635 {
636         struct pmcraid_instance *pinstance = cmd->drv_inst;
637         u32 doorbells, intrs;
638
639         /* proceed with bist and wait for 2 seconds */
640         iowrite32(DOORBELL_IOA_START_BIST,
641                 pinstance->int_regs.host_ioa_interrupt_reg);
642         doorbells = ioread32(pinstance->int_regs.host_ioa_interrupt_reg);
643         intrs = ioread32(pinstance->int_regs.ioa_host_interrupt_reg);
644         pmcraid_info("doorbells after start bist: %x intrs: %x\n",
645                       doorbells, intrs);
646
647         cmd->time_left = msecs_to_jiffies(PMCRAID_BIST_TIMEOUT);
648         cmd->timer.data = (unsigned long)cmd;
649         cmd->timer.expires = jiffies + msecs_to_jiffies(PMCRAID_BIST_TIMEOUT);
650         cmd->timer.function = (void (*)(unsigned long))pmcraid_bist_done;
651         add_timer(&cmd->timer);
652 }
653
654 /**
655  * pmcraid_reset_alert_done - completion routine for reset_alert
656  * @cmd: pointer to command block used in reset sequence
657  * Return value
658  *  None
659  */
660 static void pmcraid_reset_alert_done(struct pmcraid_cmd *cmd)
661 {
662         struct pmcraid_instance *pinstance = cmd->drv_inst;
663         u32 status = ioread32(pinstance->ioa_status);
664         unsigned long lock_flags;
665
666         /* if the critical operation in progress bit is set or the wait times
667          * out, invoke reset engine to proceed with hard reset. If there is
668          * some more time to wait, restart the timer
669          */
670         if (((status & INTRS_CRITICAL_OP_IN_PROGRESS) == 0) ||
671             cmd->time_left <= 0) {
672                 pmcraid_info("critical op is reset proceeding with reset\n");
673                 spin_lock_irqsave(pinstance->host->host_lock, lock_flags);
674                 pmcraid_ioa_reset(cmd);
675                 spin_unlock_irqrestore(pinstance->host->host_lock, lock_flags);
676         } else {
677                 pmcraid_info("critical op is not yet reset waiting again\n");
678                 /* restart timer if some more time is available to wait */
679                 cmd->time_left -= PMCRAID_CHECK_FOR_RESET_TIMEOUT;
680                 cmd->timer.data = (unsigned long)cmd;
681                 cmd->timer.expires = jiffies + PMCRAID_CHECK_FOR_RESET_TIMEOUT;
682                 cmd->timer.function =
683                         (void (*)(unsigned long))pmcraid_reset_alert_done;
684                 add_timer(&cmd->timer);
685         }
686 }
687
688 /**
689  * pmcraid_reset_alert - alerts IOA for a possible reset
690  * @cmd : command block to be used for reset sequence.
691  *
692  * Return Value
693  *      returns 0 if pci config-space is accessible and RESET_DOORBELL is
694  *      successfully written to IOA. Returns non-zero in case pci_config_space
695  *      is not accessible
696  */
697 static void pmcraid_notify_ioastate(struct pmcraid_instance *, u32);
698 static void pmcraid_reset_alert(struct pmcraid_cmd *cmd)
699 {
700         struct pmcraid_instance *pinstance = cmd->drv_inst;
701         u32 doorbells;
702         int rc;
703         u16 pci_reg;
704
705         /* If we are able to access IOA PCI config space, alert IOA that we are
706          * going to reset it soon. This enables IOA to preserv persistent error
707          * data if any. In case memory space is not accessible, proceed with
708          * BIST or slot_reset
709          */
710         rc = pci_read_config_word(pinstance->pdev, PCI_COMMAND, &pci_reg);
711         if ((rc == PCIBIOS_SUCCESSFUL) && (pci_reg & PCI_COMMAND_MEMORY)) {
712
713                 /* wait for IOA permission i.e until CRITICAL_OPERATION bit is
714                  * reset IOA doesn't generate any interrupts when CRITICAL
715                  * OPERATION bit is reset. A timer is started to wait for this
716                  * bit to be reset.
717                  */
718                 cmd->time_left = PMCRAID_RESET_TIMEOUT;
719                 cmd->timer.data = (unsigned long)cmd;
720                 cmd->timer.expires = jiffies + PMCRAID_CHECK_FOR_RESET_TIMEOUT;
721                 cmd->timer.function =
722                         (void (*)(unsigned long))pmcraid_reset_alert_done;
723                 add_timer(&cmd->timer);
724
725                 iowrite32(DOORBELL_IOA_RESET_ALERT,
726                         pinstance->int_regs.host_ioa_interrupt_reg);
727                 doorbells =
728                         ioread32(pinstance->int_regs.host_ioa_interrupt_reg);
729                 pmcraid_info("doorbells after reset alert: %x\n", doorbells);
730         } else {
731                 pmcraid_info("PCI config is not accessible starting BIST\n");
732                 pinstance->ioa_state = IOA_STATE_IN_HARD_RESET;
733                 pmcraid_start_bist(cmd);
734         }
735 }
736
737 /**
738  * pmcraid_timeout_handler -  Timeout handler for internally generated ops
739  *
740  * @cmd : pointer to command structure, that got timedout
741  *
742  * This function blocks host requests and initiates an adapter reset.
743  *
744  * Return value:
745  *   None
746  */
747 static void pmcraid_timeout_handler(struct pmcraid_cmd *cmd)
748 {
749         struct pmcraid_instance *pinstance = cmd->drv_inst;
750         unsigned long lock_flags;
751
752         dev_info(&pinstance->pdev->dev,
753                 "Adapter being reset due to cmd(CDB[0] = %x) timeout\n",
754                 cmd->ioa_cb->ioarcb.cdb[0]);
755
756         /* Command timeouts result in hard reset sequence. The command that got
757          * timed out may be the one used as part of reset sequence. In this
758          * case restart reset sequence using the same command block even if
759          * reset is in progress. Otherwise fail this command and get a free
760          * command block to restart the reset sequence.
761          */
762         spin_lock_irqsave(pinstance->host->host_lock, lock_flags);
763         if (!pinstance->ioa_reset_in_progress) {
764                 pinstance->ioa_reset_attempts = 0;
765                 cmd = pmcraid_get_free_cmd(pinstance);
766
767                 /* If we are out of command blocks, just return here itself.
768                  * Some other command's timeout handler can do the reset job
769                  */
770                 if (cmd == NULL) {
771                         spin_unlock_irqrestore(pinstance->host->host_lock,
772                                                lock_flags);
773                         pmcraid_err("no free cmnd block for timeout handler\n");
774                         return;
775                 }
776
777                 pinstance->reset_cmd = cmd;
778                 pinstance->ioa_reset_in_progress = 1;
779         } else {
780                 pmcraid_info("reset is already in progress\n");
781
782                 if (pinstance->reset_cmd != cmd) {
783                         /* This command should have been given to IOA, this
784                          * command will be completed by fail_outstanding_cmds
785                          * anyway
786                          */
787                         pmcraid_err("cmd is pending but reset in progress\n");
788                 }
789
790                 /* If this command was being used as part of the reset
791                  * sequence, set cmd_done pointer to pmcraid_ioa_reset. This
792                  * causes fail_outstanding_commands not to return the command
793                  * block back to free pool
794                  */
795                 if (cmd == pinstance->reset_cmd)
796                         cmd->cmd_done = pmcraid_ioa_reset;
797         }
798
799         /* Notify apps of important IOA bringup/bringdown sequences */
800         if (pinstance->scn.ioa_state != PMC_DEVICE_EVENT_RESET_START &&
801             pinstance->scn.ioa_state != PMC_DEVICE_EVENT_SHUTDOWN_START)
802                 pmcraid_notify_ioastate(pinstance,
803                                         PMC_DEVICE_EVENT_RESET_START);
804
805         pinstance->ioa_state = IOA_STATE_IN_RESET_ALERT;
806         scsi_block_requests(pinstance->host);
807         pmcraid_reset_alert(cmd);
808         spin_unlock_irqrestore(pinstance->host->host_lock, lock_flags);
809 }
810
811 /**
812  * pmcraid_internal_done - completion routine for internally generated cmds
813  *
814  * @cmd: command that got response from IOA
815  *
816  * Return Value:
817  *       none
818  */
819 static void pmcraid_internal_done(struct pmcraid_cmd *cmd)
820 {
821         pmcraid_info("response internal cmd CDB[0] = %x ioasc = %x\n",
822                      cmd->ioa_cb->ioarcb.cdb[0],
823                      le32_to_cpu(cmd->ioa_cb->ioasa.ioasc));
824
825         /* Some of the internal commands are sent with callers blocking for the
826          * response. Same will be indicated as part of cmd->completion_req
827          * field. Response path needs to wake up any waiters waiting for cmd
828          * completion if this flag is set.
829          */
830         if (cmd->completion_req) {
831                 cmd->completion_req = 0;
832                 complete(&cmd->wait_for_completion);
833         }
834
835         /* most of the internal commands are completed by caller itself, so
836          * no need to return the command block back to free pool until we are
837          * required to do so (e.g once done with initialization).
838          */
839         if (cmd->release) {
840                 cmd->release = 0;
841                 pmcraid_return_cmd(cmd);
842         }
843 }
844
845 /**
846  * pmcraid_reinit_cfgtable_done - done function for cfg table reinitialization
847  *
848  * @cmd: command that got response from IOA
849  *
850  * This routine is called after driver re-reads configuration table due to a
851  * lost CCN. It returns the command block back to free pool and schedules
852  * worker thread to add/delete devices into the system.
853  *
854  * Return Value:
855  *       none
856  */
857 static void pmcraid_reinit_cfgtable_done(struct pmcraid_cmd *cmd)
858 {
859         pmcraid_info("response internal cmd CDB[0] = %x ioasc = %x\n",
860                      cmd->ioa_cb->ioarcb.cdb[0],
861                      le32_to_cpu(cmd->ioa_cb->ioasa.ioasc));
862
863         if (cmd->release) {
864                 cmd->release = 0;
865                 pmcraid_return_cmd(cmd);
866         }
867         pmcraid_info("scheduling worker for config table reinitialization\n");
868         schedule_work(&cmd->drv_inst->worker_q);
869 }
870
871 /**
872  * pmcraid_erp_done - Process completion of SCSI error response from device
873  * @cmd: pmcraid_command
874  *
875  * This function copies the sense buffer into the scsi_cmd struct and completes
876  * scsi_cmd by calling scsi_done function.
877  *
878  * Return value:
879  *  none
880  */
881 static void pmcraid_erp_done(struct pmcraid_cmd *cmd)
882 {
883         struct scsi_cmnd *scsi_cmd = cmd->scsi_cmd;
884         struct pmcraid_instance *pinstance = cmd->drv_inst;
885         u32 ioasc = le32_to_cpu(cmd->ioa_cb->ioasa.ioasc);
886
887         if (PMCRAID_IOASC_SENSE_KEY(ioasc) > 0) {
888                 scsi_cmd->result |= (DID_ERROR << 16);
889                 scmd_printk(KERN_INFO, scsi_cmd,
890                             "command CDB[0] = %x failed with IOASC: 0x%08X\n",
891                             cmd->ioa_cb->ioarcb.cdb[0], ioasc);
892         }
893
894         /* if we had allocated sense buffers for request sense, copy the sense
895          * release the buffers
896          */
897         if (cmd->sense_buffer != NULL) {
898                 memcpy(scsi_cmd->sense_buffer,
899                        cmd->sense_buffer,
900                        SCSI_SENSE_BUFFERSIZE);
901                 pci_free_consistent(pinstance->pdev,
902                                     SCSI_SENSE_BUFFERSIZE,
903                                     cmd->sense_buffer, cmd->sense_buffer_dma);
904                 cmd->sense_buffer = NULL;
905                 cmd->sense_buffer_dma = 0;
906         }
907
908         scsi_dma_unmap(scsi_cmd);
909         pmcraid_return_cmd(cmd);
910         scsi_cmd->scsi_done(scsi_cmd);
911 }
912
913 /**
914  * pmcraid_fire_command - sends an IOA command to adapter
915  *
916  * This function adds the given block into pending command list
917  * and returns without waiting
918  *
919  * @cmd : command to be sent to the device
920  *
921  * Return Value
922  *      None
923  */
924 static void _pmcraid_fire_command(struct pmcraid_cmd *cmd)
925 {
926         struct pmcraid_instance *pinstance = cmd->drv_inst;
927         unsigned long lock_flags;
928
929         /* Add this command block to pending cmd pool. We do this prior to
930          * writting IOARCB to ioarrin because IOA might complete the command
931          * by the time we are about to add it to the list. Response handler
932          * (isr/tasklet) looks for cmd block in the pending pending list.
933          */
934         spin_lock_irqsave(&pinstance->pending_pool_lock, lock_flags);
935         list_add_tail(&cmd->free_list, &pinstance->pending_cmd_pool);
936         spin_unlock_irqrestore(&pinstance->pending_pool_lock, lock_flags);
937         atomic_inc(&pinstance->outstanding_cmds);
938
939         /* driver writes lower 32-bit value of IOARCB address only */
940         mb();
941         iowrite32(le32_to_cpu(cmd->ioa_cb->ioarcb.ioarcb_bus_addr),
942                   pinstance->ioarrin);
943 }
944
945 /**
946  * pmcraid_send_cmd - fires a command to IOA
947  *
948  * This function also sets up timeout function, and command completion
949  * function
950  *
951  * @cmd: pointer to the command block to be fired to IOA
952  * @cmd_done: command completion function, called once IOA responds
953  * @timeout: timeout to wait for this command completion
954  * @timeout_func: timeout handler
955  *
956  * Return value
957  *   none
958  */
959 static void pmcraid_send_cmd(
960         struct pmcraid_cmd *cmd,
961         void (*cmd_done) (struct pmcraid_cmd *),
962         unsigned long timeout,
963         void (*timeout_func) (struct pmcraid_cmd *)
964 )
965 {
966         /* initialize done function */
967         cmd->cmd_done = cmd_done;
968
969         if (timeout_func) {
970                 /* setup timeout handler */
971                 cmd->timer.data = (unsigned long)cmd;
972                 cmd->timer.expires = jiffies + timeout;
973                 cmd->timer.function = (void (*)(unsigned long))timeout_func;
974                 add_timer(&cmd->timer);
975         }
976
977         /* fire the command to IOA */
978         _pmcraid_fire_command(cmd);
979 }
980
981 /**
982  * pmcraid_ioa_shutdown_done - completion function for IOA shutdown command
983  * @cmd: pointer to the command block used for sending IOA shutdown command
984  *
985  * Return value
986  *  None
987  */
988 static void pmcraid_ioa_shutdown_done(struct pmcraid_cmd *cmd)
989 {
990         struct pmcraid_instance *pinstance = cmd->drv_inst;
991         unsigned long lock_flags;
992
993         spin_lock_irqsave(pinstance->host->host_lock, lock_flags);
994         pmcraid_ioa_reset(cmd);
995         spin_unlock_irqrestore(pinstance->host->host_lock, lock_flags);
996 }
997
998 /**
999  * pmcraid_ioa_shutdown - sends SHUTDOWN command to ioa
1000  *
1001  * @cmd: pointer to the command block used as part of reset sequence
1002  *
1003  * Return Value
1004  *  None
1005  */
1006 static void pmcraid_ioa_shutdown(struct pmcraid_cmd *cmd)
1007 {
1008         pmcraid_info("response for Cancel CCN CDB[0] = %x ioasc = %x\n",
1009                      cmd->ioa_cb->ioarcb.cdb[0],
1010                      le32_to_cpu(cmd->ioa_cb->ioasa.ioasc));
1011
1012         /* Note that commands sent during reset require next command to be sent
1013          * to IOA. Hence reinit the done function as well as timeout function
1014          */
1015         pmcraid_reinit_cmdblk(cmd);
1016         cmd->ioa_cb->ioarcb.request_type = REQ_TYPE_IOACMD;
1017         cmd->ioa_cb->ioarcb.resource_handle =
1018                 cpu_to_le32(PMCRAID_IOA_RES_HANDLE);
1019         cmd->ioa_cb->ioarcb.cdb[0] = PMCRAID_IOA_SHUTDOWN;
1020         cmd->ioa_cb->ioarcb.cdb[1] = PMCRAID_SHUTDOWN_NORMAL;
1021
1022         /* fire shutdown command to hardware. */
1023         pmcraid_info("firing normal shutdown command (%d) to IOA\n",
1024                      le32_to_cpu(cmd->ioa_cb->ioarcb.response_handle));
1025
1026         pmcraid_notify_ioastate(cmd->drv_inst, PMC_DEVICE_EVENT_SHUTDOWN_START);
1027
1028         pmcraid_send_cmd(cmd, pmcraid_ioa_shutdown_done,
1029                          PMCRAID_SHUTDOWN_TIMEOUT,
1030                          pmcraid_timeout_handler);
1031 }
1032
1033 /**
1034  * pmcraid_get_fwversion_done - completion function for get_fwversion
1035  *
1036  * @cmd: pointer to command block used to send INQUIRY command
1037  *
1038  * Return Value
1039  *      none
1040  */
1041 static void pmcraid_querycfg(struct pmcraid_cmd *);
1042
1043 static void pmcraid_get_fwversion_done(struct pmcraid_cmd *cmd)
1044 {
1045         struct pmcraid_instance *pinstance = cmd->drv_inst;
1046         u32 ioasc = le32_to_cpu(cmd->ioa_cb->ioasa.ioasc);
1047         unsigned long lock_flags;
1048
1049         /* configuration table entry size depends on firmware version. If fw
1050          * version is not known, it is not possible to interpret IOA config
1051          * table
1052          */
1053         if (ioasc) {
1054                 pmcraid_err("IOA Inquiry failed with %x\n", ioasc);
1055                 spin_lock_irqsave(pinstance->host->host_lock, lock_flags);
1056                 pinstance->ioa_state = IOA_STATE_IN_RESET_ALERT;
1057                 pmcraid_reset_alert(cmd);
1058                 spin_unlock_irqrestore(pinstance->host->host_lock, lock_flags);
1059         } else  {
1060                 pmcraid_querycfg(cmd);
1061         }
1062 }
1063
1064 /**
1065  * pmcraid_get_fwversion - reads firmware version information
1066  *
1067  * @cmd: pointer to command block used to send INQUIRY command
1068  *
1069  * Return Value
1070  *      none
1071  */
1072 static void pmcraid_get_fwversion(struct pmcraid_cmd *cmd)
1073 {
1074         struct pmcraid_ioarcb *ioarcb = &cmd->ioa_cb->ioarcb;
1075         struct pmcraid_ioadl_desc *ioadl = ioarcb->add_data.u.ioadl;
1076         struct pmcraid_instance *pinstance = cmd->drv_inst;
1077         u16 data_size = sizeof(struct pmcraid_inquiry_data);
1078
1079         pmcraid_reinit_cmdblk(cmd);
1080         ioarcb->request_type = REQ_TYPE_SCSI;
1081         ioarcb->resource_handle = cpu_to_le32(PMCRAID_IOA_RES_HANDLE);
1082         ioarcb->cdb[0] = INQUIRY;
1083         ioarcb->cdb[1] = 1;
1084         ioarcb->cdb[2] = 0xD0;
1085         ioarcb->cdb[3] = (data_size >> 8) & 0xFF;
1086         ioarcb->cdb[4] = data_size & 0xFF;
1087
1088         /* Since entire inquiry data it can be part of IOARCB itself
1089          */
1090         ioarcb->ioadl_bus_addr = cpu_to_le64((cmd->ioa_cb_bus_addr) +
1091                                         offsetof(struct pmcraid_ioarcb,
1092                                                 add_data.u.ioadl[0]));
1093         ioarcb->ioadl_length = cpu_to_le32(sizeof(struct pmcraid_ioadl_desc));
1094         ioarcb->ioarcb_bus_addr &= ~(0x1FULL);
1095
1096         ioarcb->request_flags0 |= NO_LINK_DESCS;
1097         ioarcb->data_transfer_length = cpu_to_le32(data_size);
1098         ioadl = &(ioarcb->add_data.u.ioadl[0]);
1099         ioadl->flags = IOADL_FLAGS_LAST_DESC;
1100         ioadl->address = cpu_to_le64(pinstance->inq_data_baddr);
1101         ioadl->data_len = cpu_to_le32(data_size);
1102
1103         pmcraid_send_cmd(cmd, pmcraid_get_fwversion_done,
1104                          PMCRAID_INTERNAL_TIMEOUT, pmcraid_timeout_handler);
1105 }
1106
1107 /**
1108  * pmcraid_identify_hrrq - registers host rrq buffers with IOA
1109  * @cmd: pointer to command block to be used for identify hrrq
1110  *
1111  * Return Value
1112  *       none
1113  */
1114 static void pmcraid_identify_hrrq(struct pmcraid_cmd *cmd)
1115 {
1116         struct pmcraid_instance *pinstance = cmd->drv_inst;
1117         struct pmcraid_ioarcb *ioarcb = &cmd->ioa_cb->ioarcb;
1118         int index = cmd->hrrq_index;
1119         __be64 hrrq_addr = cpu_to_be64(pinstance->hrrq_start_bus_addr[index]);
1120         u32 hrrq_size = cpu_to_be32(sizeof(u32) * PMCRAID_MAX_CMD);
1121         void (*done_function)(struct pmcraid_cmd *);
1122
1123         pmcraid_reinit_cmdblk(cmd);
1124         cmd->hrrq_index = index + 1;
1125
1126         if (cmd->hrrq_index < pinstance->num_hrrq) {
1127                 done_function = pmcraid_identify_hrrq;
1128         } else {
1129                 cmd->hrrq_index = 0;
1130                 done_function = pmcraid_get_fwversion;
1131         }
1132
1133         /* Initialize ioarcb */
1134         ioarcb->request_type = REQ_TYPE_IOACMD;
1135         ioarcb->resource_handle = cpu_to_le32(PMCRAID_IOA_RES_HANDLE);
1136
1137         /* initialize the hrrq number where IOA will respond to this command */
1138         ioarcb->hrrq_id = index;
1139         ioarcb->cdb[0] = PMCRAID_IDENTIFY_HRRQ;
1140         ioarcb->cdb[1] = index;
1141
1142         /* IOA expects 64-bit pci address to be written in B.E format
1143          * (i.e cdb[2]=MSByte..cdb[9]=LSB.
1144          */
1145         pmcraid_info("HRRQ_IDENTIFY with hrrq:ioarcb:index => %llx:%llx:%x\n",
1146                      hrrq_addr, ioarcb->ioarcb_bus_addr, index);
1147
1148         memcpy(&(ioarcb->cdb[2]), &hrrq_addr, sizeof(hrrq_addr));
1149         memcpy(&(ioarcb->cdb[10]), &hrrq_size, sizeof(hrrq_size));
1150
1151         /* Subsequent commands require HRRQ identification to be successful.
1152          * Note that this gets called even during reset from SCSI mid-layer
1153          * or tasklet
1154          */
1155         pmcraid_send_cmd(cmd, done_function,
1156                          PMCRAID_INTERNAL_TIMEOUT,
1157                          pmcraid_timeout_handler);
1158 }
1159
1160 static void pmcraid_process_ccn(struct pmcraid_cmd *cmd);
1161 static void pmcraid_process_ldn(struct pmcraid_cmd *cmd);
1162
1163 /**
1164  * pmcraid_send_hcam_cmd - send an initialized command block(HCAM) to IOA
1165  *
1166  * @cmd: initialized command block pointer
1167  *
1168  * Return Value
1169  *   none
1170  */
1171 static void pmcraid_send_hcam_cmd(struct pmcraid_cmd *cmd)
1172 {
1173         if (cmd->ioa_cb->ioarcb.cdb[1] == PMCRAID_HCAM_CODE_CONFIG_CHANGE)
1174                 atomic_set(&(cmd->drv_inst->ccn.ignore), 0);
1175         else
1176                 atomic_set(&(cmd->drv_inst->ldn.ignore), 0);
1177
1178         pmcraid_send_cmd(cmd, cmd->cmd_done, 0, NULL);
1179 }
1180
1181 /**
1182  * pmcraid_init_hcam - send an initialized command block(HCAM) to IOA
1183  *
1184  * @pinstance: pointer to adapter instance structure
1185  * @type: HCAM type
1186  *
1187  * Return Value
1188  *   pointer to initialized pmcraid_cmd structure or NULL
1189  */
1190 static struct pmcraid_cmd *pmcraid_init_hcam
1191 (
1192         struct pmcraid_instance *pinstance,
1193         u8 type
1194 )
1195 {
1196         struct pmcraid_cmd *cmd;
1197         struct pmcraid_ioarcb *ioarcb;
1198         struct pmcraid_ioadl_desc *ioadl;
1199         struct pmcraid_hostrcb *hcam;
1200         void (*cmd_done) (struct pmcraid_cmd *);
1201         dma_addr_t dma;
1202         int rcb_size;
1203
1204         cmd = pmcraid_get_free_cmd(pinstance);
1205
1206         if (!cmd) {
1207                 pmcraid_err("no free command blocks for hcam\n");
1208                 return cmd;
1209         }
1210
1211         if (type == PMCRAID_HCAM_CODE_CONFIG_CHANGE) {
1212                 rcb_size = sizeof(struct pmcraid_hcam_ccn_ext);
1213                 cmd_done = pmcraid_process_ccn;
1214                 dma = pinstance->ccn.baddr + PMCRAID_AEN_HDR_SIZE;
1215                 hcam = &pinstance->ccn;
1216         } else {
1217                 rcb_size = sizeof(struct pmcraid_hcam_ldn);
1218                 cmd_done = pmcraid_process_ldn;
1219                 dma = pinstance->ldn.baddr + PMCRAID_AEN_HDR_SIZE;
1220                 hcam = &pinstance->ldn;
1221         }
1222
1223         /* initialize command pointer used for HCAM registration */
1224         hcam->cmd = cmd;
1225
1226         ioarcb = &cmd->ioa_cb->ioarcb;
1227         ioarcb->ioadl_bus_addr = cpu_to_le64((cmd->ioa_cb_bus_addr) +
1228                                         offsetof(struct pmcraid_ioarcb,
1229                                                 add_data.u.ioadl[0]));
1230         ioarcb->ioadl_length = cpu_to_le32(sizeof(struct pmcraid_ioadl_desc));
1231         ioadl = ioarcb->add_data.u.ioadl;
1232
1233         /* Initialize ioarcb */
1234         ioarcb->request_type = REQ_TYPE_HCAM;
1235         ioarcb->resource_handle = cpu_to_le32(PMCRAID_IOA_RES_HANDLE);
1236         ioarcb->cdb[0] = PMCRAID_HOST_CONTROLLED_ASYNC;
1237         ioarcb->cdb[1] = type;
1238         ioarcb->cdb[7] = (rcb_size >> 8) & 0xFF;
1239         ioarcb->cdb[8] = (rcb_size) & 0xFF;
1240
1241         ioarcb->data_transfer_length = cpu_to_le32(rcb_size);
1242
1243         ioadl[0].flags |= IOADL_FLAGS_READ_LAST;
1244         ioadl[0].data_len = cpu_to_le32(rcb_size);
1245         ioadl[0].address = cpu_to_le32(dma);
1246
1247         cmd->cmd_done = cmd_done;
1248         return cmd;
1249 }
1250
1251 /**
1252  * pmcraid_send_hcam - Send an HCAM to IOA
1253  * @pinstance: ioa config struct
1254  * @type: HCAM type
1255  *
1256  * This function will send a Host Controlled Async command to IOA.
1257  *
1258  * Return value:
1259  *      none
1260  */
1261 static void pmcraid_send_hcam(struct pmcraid_instance *pinstance, u8 type)
1262 {
1263         struct pmcraid_cmd *cmd = pmcraid_init_hcam(pinstance, type);
1264         pmcraid_send_hcam_cmd(cmd);
1265 }
1266
1267
1268 /**
1269  * pmcraid_prepare_cancel_cmd - prepares a command block to abort another
1270  *
1271  * @cmd: pointer to cmd that is used as cancelling command
1272  * @cmd_to_cancel: pointer to the command that needs to be cancelled
1273  */
1274 static void pmcraid_prepare_cancel_cmd(
1275         struct pmcraid_cmd *cmd,
1276         struct pmcraid_cmd *cmd_to_cancel
1277 )
1278 {
1279         struct pmcraid_ioarcb *ioarcb = &cmd->ioa_cb->ioarcb;
1280         __be64 ioarcb_addr = cmd_to_cancel->ioa_cb->ioarcb.ioarcb_bus_addr;
1281
1282         /* Get the resource handle to where the command to be aborted has been
1283          * sent.
1284          */
1285         ioarcb->resource_handle = cmd_to_cancel->ioa_cb->ioarcb.resource_handle;
1286         ioarcb->request_type = REQ_TYPE_IOACMD;
1287         memset(ioarcb->cdb, 0, PMCRAID_MAX_CDB_LEN);
1288         ioarcb->cdb[0] = PMCRAID_ABORT_CMD;
1289
1290         /* IOARCB address of the command to be cancelled is given in
1291          * cdb[2]..cdb[9] is Big-Endian format. Note that length bits in
1292          * IOARCB address are not masked.
1293          */
1294         ioarcb_addr = cpu_to_be64(ioarcb_addr);
1295         memcpy(&(ioarcb->cdb[2]), &ioarcb_addr, sizeof(ioarcb_addr));
1296 }
1297
1298 /**
1299  * pmcraid_cancel_hcam - sends ABORT task to abort a given HCAM
1300  *
1301  * @cmd: command to be used as cancelling command
1302  * @type: HCAM type
1303  * @cmd_done: op done function for the cancelling command
1304  */
1305 static void pmcraid_cancel_hcam(
1306         struct pmcraid_cmd *cmd,
1307         u8 type,
1308         void (*cmd_done) (struct pmcraid_cmd *)
1309 )
1310 {
1311         struct pmcraid_instance *pinstance;
1312         struct pmcraid_hostrcb  *hcam;
1313
1314         pinstance = cmd->drv_inst;
1315         hcam =  (type == PMCRAID_HCAM_CODE_LOG_DATA) ?
1316                 &pinstance->ldn : &pinstance->ccn;
1317
1318         /* prepare for cancelling previous hcam command. If the HCAM is
1319          * currently not pending with IOA, we would have hcam->cmd as non-null
1320          */
1321         if (hcam->cmd == NULL)
1322                 return;
1323
1324         pmcraid_prepare_cancel_cmd(cmd, hcam->cmd);
1325
1326         /* writing to IOARRIN must be protected by host_lock, as mid-layer
1327          * schedule queuecommand while we are doing this
1328          */
1329         pmcraid_send_cmd(cmd, cmd_done,
1330                          PMCRAID_INTERNAL_TIMEOUT,
1331                          pmcraid_timeout_handler);
1332 }
1333
1334 /**
1335  * pmcraid_cancel_ccn - cancel CCN HCAM already registered with IOA
1336  *
1337  * @cmd: command block to be used for cancelling the HCAM
1338  */
1339 static void pmcraid_cancel_ccn(struct pmcraid_cmd *cmd)
1340 {
1341         pmcraid_info("response for Cancel LDN CDB[0] = %x ioasc = %x\n",
1342                      cmd->ioa_cb->ioarcb.cdb[0],
1343                      le32_to_cpu(cmd->ioa_cb->ioasa.ioasc));
1344
1345         pmcraid_reinit_cmdblk(cmd);
1346
1347         pmcraid_cancel_hcam(cmd,
1348                             PMCRAID_HCAM_CODE_CONFIG_CHANGE,
1349                             pmcraid_ioa_shutdown);
1350 }
1351
1352 /**
1353  * pmcraid_cancel_ldn - cancel LDN HCAM already registered with IOA
1354  *
1355  * @cmd: command block to be used for cancelling the HCAM
1356  */
1357 static void pmcraid_cancel_ldn(struct pmcraid_cmd *cmd)
1358 {
1359         pmcraid_cancel_hcam(cmd,
1360                             PMCRAID_HCAM_CODE_LOG_DATA,
1361                             pmcraid_cancel_ccn);
1362 }
1363
1364 /**
1365  * pmcraid_expose_resource - check if the resource can be exposed to OS
1366  *
1367  * @fw_version: firmware version code
1368  * @cfgte: pointer to configuration table entry of the resource
1369  *
1370  * Return value:
1371  *      true if resource can be added to midlayer, false(0) otherwise
1372  */
1373 static int pmcraid_expose_resource(u16 fw_version,
1374                                    struct pmcraid_config_table_entry *cfgte)
1375 {
1376         int retval = 0;
1377
1378         if (cfgte->resource_type == RES_TYPE_VSET) {
1379                 if (fw_version <= PMCRAID_FW_VERSION_1)
1380                         retval = ((cfgte->unique_flags1 & 0x80) == 0);
1381                 else
1382                         retval = ((cfgte->unique_flags0 & 0x80) == 0 &&
1383                                   (cfgte->unique_flags1 & 0x80) == 0);
1384
1385         } else if (cfgte->resource_type == RES_TYPE_GSCSI)
1386                 retval = (RES_BUS(cfgte->resource_address) !=
1387                                 PMCRAID_VIRTUAL_ENCL_BUS_ID);
1388         return retval;
1389 }
1390
1391 /* attributes supported by pmcraid_event_family */
1392 enum {
1393         PMCRAID_AEN_ATTR_UNSPEC,
1394         PMCRAID_AEN_ATTR_EVENT,
1395         __PMCRAID_AEN_ATTR_MAX,
1396 };
1397 #define PMCRAID_AEN_ATTR_MAX (__PMCRAID_AEN_ATTR_MAX - 1)
1398
1399 /* commands supported by pmcraid_event_family */
1400 enum {
1401         PMCRAID_AEN_CMD_UNSPEC,
1402         PMCRAID_AEN_CMD_EVENT,
1403         __PMCRAID_AEN_CMD_MAX,
1404 };
1405 #define PMCRAID_AEN_CMD_MAX (__PMCRAID_AEN_CMD_MAX - 1)
1406
1407 static struct genl_family pmcraid_event_family = {
1408         .id = GENL_ID_GENERATE,
1409         .name = "pmcraid",
1410         .version = 1,
1411         .maxattr = PMCRAID_AEN_ATTR_MAX
1412 };
1413
1414 /**
1415  * pmcraid_netlink_init - registers pmcraid_event_family
1416  *
1417  * Return value:
1418  *      0 if the pmcraid_event_family is successfully registered
1419  *      with netlink generic, non-zero otherwise
1420  */
1421 static int pmcraid_netlink_init(void)
1422 {
1423         int result;
1424
1425         result = genl_register_family(&pmcraid_event_family);
1426
1427         if (result)
1428                 return result;
1429
1430         pmcraid_info("registered NETLINK GENERIC group: %d\n",
1431                      pmcraid_event_family.id);
1432
1433         return result;
1434 }
1435
1436 /**
1437  * pmcraid_netlink_release - unregisters pmcraid_event_family
1438  *
1439  * Return value:
1440  *      none
1441  */
1442 static void pmcraid_netlink_release(void)
1443 {
1444         genl_unregister_family(&pmcraid_event_family);
1445 }
1446
1447 /**
1448  * pmcraid_notify_aen - sends event msg to user space application
1449  * @pinstance: pointer to adapter instance structure
1450  * @type: HCAM type
1451  *
1452  * Return value:
1453  *      0 if success, error value in case of any failure.
1454  */
1455 static int pmcraid_notify_aen(
1456         struct pmcraid_instance *pinstance,
1457         struct pmcraid_aen_msg  *aen_msg,
1458         u32    data_size
1459 )
1460 {
1461         struct sk_buff *skb;
1462         void *msg_header;
1463         u32  total_size, nla_genl_hdr_total_size;
1464         int result;
1465
1466         aen_msg->hostno = (pinstance->host->unique_id << 16 |
1467                            MINOR(pinstance->cdev.dev));
1468         aen_msg->length = data_size;
1469
1470         data_size += sizeof(*aen_msg);
1471
1472         total_size = nla_total_size(data_size);
1473         /* Add GENL_HDR to total_size */
1474         nla_genl_hdr_total_size =
1475                 (total_size + (GENL_HDRLEN +
1476                 ((struct genl_family *)&pmcraid_event_family)->hdrsize)
1477                  + NLMSG_HDRLEN);
1478         skb = genlmsg_new(nla_genl_hdr_total_size, GFP_ATOMIC);
1479
1480
1481         if (!skb) {
1482                 pmcraid_err("Failed to allocate aen data SKB of size: %x\n",
1483                              total_size);
1484                 return -ENOMEM;
1485         }
1486
1487         /* add the genetlink message header */
1488         msg_header = genlmsg_put(skb, 0, 0,
1489                                  &pmcraid_event_family, 0,
1490                                  PMCRAID_AEN_CMD_EVENT);
1491         if (!msg_header) {
1492                 pmcraid_err("failed to copy command details\n");
1493                 nlmsg_free(skb);
1494                 return -ENOMEM;
1495         }
1496
1497         result = nla_put(skb, PMCRAID_AEN_ATTR_EVENT, data_size, aen_msg);
1498
1499         if (result) {
1500                 pmcraid_err("failed to copy AEN attribute data\n");
1501                 nlmsg_free(skb);
1502                 return -EINVAL;
1503         }
1504
1505         /* send genetlink multicast message to notify appplications */
1506         result = genlmsg_end(skb, msg_header);
1507
1508         if (result < 0) {
1509                 pmcraid_err("genlmsg_end failed\n");
1510                 nlmsg_free(skb);
1511                 return result;
1512         }
1513
1514         result =
1515                 genlmsg_multicast(skb, 0, pmcraid_event_family.id, GFP_ATOMIC);
1516
1517         /* If there are no listeners, genlmsg_multicast may return non-zero
1518          * value.
1519          */
1520         if (result)
1521                 pmcraid_info("error (%x) sending aen event message\n", result);
1522         return result;
1523 }
1524
1525 /**
1526  * pmcraid_notify_ccn - notifies about CCN event msg to user space
1527  * @pinstance: pointer adapter instance structure
1528  *
1529  * Return value:
1530  *      0 if success, error value in case of any failure
1531  */
1532 static int pmcraid_notify_ccn(struct pmcraid_instance *pinstance)
1533 {
1534         return pmcraid_notify_aen(pinstance,
1535                                 pinstance->ccn.msg,
1536                                 pinstance->ccn.hcam->data_len +
1537                                 sizeof(struct pmcraid_hcam_hdr));
1538 }
1539
1540 /**
1541  * pmcraid_notify_ldn - notifies about CCN event msg to user space
1542  * @pinstance: pointer adapter instance structure
1543  *
1544  * Return value:
1545  *      0 if success, error value in case of any failure
1546  */
1547 static int pmcraid_notify_ldn(struct pmcraid_instance *pinstance)
1548 {
1549         return pmcraid_notify_aen(pinstance,
1550                                 pinstance->ldn.msg,
1551                                 pinstance->ldn.hcam->data_len +
1552                                 sizeof(struct pmcraid_hcam_hdr));
1553 }
1554
1555 /**
1556  * pmcraid_notify_ioastate - sends IOA state event msg to user space
1557  * @pinstance: pointer adapter instance structure
1558  * @evt: controller state event to be sent
1559  *
1560  * Return value:
1561  *      0 if success, error value in case of any failure
1562  */
1563 static void pmcraid_notify_ioastate(struct pmcraid_instance *pinstance, u32 evt)
1564 {
1565         pinstance->scn.ioa_state = evt;
1566         pmcraid_notify_aen(pinstance,
1567                           &pinstance->scn.msg,
1568                           sizeof(u32));
1569 }
1570
1571 /**
1572  * pmcraid_handle_config_change - Handle a config change from the adapter
1573  * @pinstance: pointer to per adapter instance structure
1574  *
1575  * Return value:
1576  *  none
1577  */
1578
1579 static void pmcraid_handle_config_change(struct pmcraid_instance *pinstance)
1580 {
1581         struct pmcraid_config_table_entry *cfg_entry;
1582         struct pmcraid_hcam_ccn *ccn_hcam;
1583         struct pmcraid_cmd *cmd;
1584         struct pmcraid_cmd *cfgcmd;
1585         struct pmcraid_resource_entry *res = NULL;
1586         unsigned long lock_flags;
1587         unsigned long host_lock_flags;
1588         u32 new_entry = 1;
1589         u32 hidden_entry = 0;
1590         u16 fw_version;
1591         int rc;
1592
1593         ccn_hcam = (struct pmcraid_hcam_ccn *)pinstance->ccn.hcam;
1594         cfg_entry = &ccn_hcam->cfg_entry;
1595         fw_version = be16_to_cpu(pinstance->inq_data->fw_version);
1596
1597         pmcraid_info("CCN(%x): %x timestamp: %llx type: %x lost: %x flags: %x \
1598                  res: %x:%x:%x:%x\n",
1599                  pinstance->ccn.hcam->ilid,
1600                  pinstance->ccn.hcam->op_code,
1601                 ((pinstance->ccn.hcam->timestamp1) |
1602                 ((pinstance->ccn.hcam->timestamp2 & 0xffffffffLL) << 32)),
1603                  pinstance->ccn.hcam->notification_type,
1604                  pinstance->ccn.hcam->notification_lost,
1605                  pinstance->ccn.hcam->flags,
1606                  pinstance->host->unique_id,
1607                  RES_IS_VSET(*cfg_entry) ? PMCRAID_VSET_BUS_ID :
1608                  (RES_IS_GSCSI(*cfg_entry) ? PMCRAID_PHYS_BUS_ID :
1609                         RES_BUS(cfg_entry->resource_address)),
1610                  RES_IS_VSET(*cfg_entry) ?
1611                         (fw_version <= PMCRAID_FW_VERSION_1 ?
1612                                 cfg_entry->unique_flags1 :
1613                                         cfg_entry->array_id & 0xFF) :
1614                         RES_TARGET(cfg_entry->resource_address),
1615                  RES_LUN(cfg_entry->resource_address));
1616
1617
1618         /* If this HCAM indicates a lost notification, read the config table */
1619         if (pinstance->ccn.hcam->notification_lost) {
1620                 cfgcmd = pmcraid_get_free_cmd(pinstance);
1621                 if (cfgcmd) {
1622                         pmcraid_info("lost CCN, reading config table\b");
1623                         pinstance->reinit_cfg_table = 1;
1624                         pmcraid_querycfg(cfgcmd);
1625                 } else {
1626                         pmcraid_err("lost CCN, no free cmd for querycfg\n");
1627                 }
1628                 goto out_notify_apps;
1629         }
1630
1631         /* If this resource is not going to be added to mid-layer, just notify
1632          * applications and return. If this notification is about hiding a VSET
1633          * resource, check if it was exposed already.
1634          */
1635         if (pinstance->ccn.hcam->notification_type ==
1636             NOTIFICATION_TYPE_ENTRY_CHANGED &&
1637             cfg_entry->resource_type == RES_TYPE_VSET) {
1638
1639                 if (fw_version <= PMCRAID_FW_VERSION_1)
1640                         hidden_entry = (cfg_entry->unique_flags1 & 0x80) != 0;
1641                 else
1642                         hidden_entry = (cfg_entry->unique_flags1 & 0x80) != 0;
1643
1644         } else if (!pmcraid_expose_resource(fw_version, cfg_entry)) {
1645                 goto out_notify_apps;
1646         }
1647
1648         spin_lock_irqsave(&pinstance->resource_lock, lock_flags);
1649         list_for_each_entry(res, &pinstance->used_res_q, queue) {
1650                 rc = memcmp(&res->cfg_entry.resource_address,
1651                             &cfg_entry->resource_address,
1652                             sizeof(cfg_entry->resource_address));
1653                 if (!rc) {
1654                         new_entry = 0;
1655                         break;
1656                 }
1657         }
1658
1659         if (new_entry) {
1660
1661                 if (hidden_entry) {
1662                         spin_unlock_irqrestore(&pinstance->resource_lock,
1663                                                 lock_flags);
1664                         goto out_notify_apps;
1665                 }
1666
1667                 /* If there are more number of resources than what driver can
1668                  * manage, do not notify the applications about the CCN. Just
1669                  * ignore this notifications and re-register the same HCAM
1670                  */
1671                 if (list_empty(&pinstance->free_res_q)) {
1672                         spin_unlock_irqrestore(&pinstance->resource_lock,
1673                                                 lock_flags);
1674                         pmcraid_err("too many resources attached\n");
1675                         spin_lock_irqsave(pinstance->host->host_lock,
1676                                           host_lock_flags);
1677                         pmcraid_send_hcam(pinstance,
1678                                           PMCRAID_HCAM_CODE_CONFIG_CHANGE);
1679                         spin_unlock_irqrestore(pinstance->host->host_lock,
1680                                                host_lock_flags);
1681                         return;
1682                 }
1683
1684                 res = list_entry(pinstance->free_res_q.next,
1685                                  struct pmcraid_resource_entry, queue);
1686
1687                 list_del(&res->queue);
1688                 res->scsi_dev = NULL;
1689                 res->reset_progress = 0;
1690                 list_add_tail(&res->queue, &pinstance->used_res_q);
1691         }
1692
1693         memcpy(&res->cfg_entry, cfg_entry, pinstance->config_table_entry_size);
1694
1695         if (pinstance->ccn.hcam->notification_type ==
1696             NOTIFICATION_TYPE_ENTRY_DELETED || hidden_entry) {
1697                 if (res->scsi_dev) {
1698                         if (fw_version <= PMCRAID_FW_VERSION_1)
1699                                 res->cfg_entry.unique_flags1 &= 0x7F;
1700                         else
1701                                 res->cfg_entry.array_id &= 0xFF;
1702                         res->change_detected = RES_CHANGE_DEL;
1703                         res->cfg_entry.resource_handle =
1704                                 PMCRAID_INVALID_RES_HANDLE;
1705                         schedule_work(&pinstance->worker_q);
1706                 } else {
1707                         /* This may be one of the non-exposed resources */
1708                         list_move_tail(&res->queue, &pinstance->free_res_q);
1709                 }
1710         } else if (!res->scsi_dev) {
1711                 res->change_detected = RES_CHANGE_ADD;
1712                 schedule_work(&pinstance->worker_q);
1713         }
1714         spin_unlock_irqrestore(&pinstance->resource_lock, lock_flags);
1715
1716 out_notify_apps:
1717
1718         /* Notify configuration changes to registered applications.*/
1719         if (!pmcraid_disable_aen)
1720                 pmcraid_notify_ccn(pinstance);
1721
1722         cmd = pmcraid_init_hcam(pinstance, PMCRAID_HCAM_CODE_CONFIG_CHANGE);
1723         if (cmd)
1724                 pmcraid_send_hcam_cmd(cmd);
1725 }
1726
1727 /**
1728  * pmcraid_get_error_info - return error string for an ioasc
1729  * @ioasc: ioasc code
1730  * Return Value
1731  *       none
1732  */
1733 static struct pmcraid_ioasc_error *pmcraid_get_error_info(u32 ioasc)
1734 {
1735         int i;
1736         for (i = 0; i < ARRAY_SIZE(pmcraid_ioasc_error_table); i++) {
1737                 if (pmcraid_ioasc_error_table[i].ioasc_code == ioasc)
1738                         return &pmcraid_ioasc_error_table[i];
1739         }
1740         return NULL;
1741 }
1742
1743 /**
1744  * pmcraid_ioasc_logger - log IOASC information based user-settings
1745  * @ioasc: ioasc code
1746  * @cmd: pointer to command that resulted in 'ioasc'
1747  */
1748 void pmcraid_ioasc_logger(u32 ioasc, struct pmcraid_cmd *cmd)
1749 {
1750         struct pmcraid_ioasc_error *error_info = pmcraid_get_error_info(ioasc);
1751
1752         if (error_info == NULL ||
1753                 cmd->drv_inst->current_log_level < error_info->log_level)
1754                 return;
1755
1756         /* log the error string */
1757         pmcraid_err("cmd [%x] for resource %x failed with %x(%s)\n",
1758                 cmd->ioa_cb->ioarcb.cdb[0],
1759                 cmd->ioa_cb->ioarcb.resource_handle,
1760                 le32_to_cpu(ioasc), error_info->error_string);
1761 }
1762
1763 /**
1764  * pmcraid_handle_error_log - Handle a config change (error log) from the IOA
1765  *
1766  * @pinstance: pointer to per adapter instance structure
1767  *
1768  * Return value:
1769  *  none
1770  */
1771 static void pmcraid_handle_error_log(struct pmcraid_instance *pinstance)
1772 {
1773         struct pmcraid_hcam_ldn *hcam_ldn;
1774         u32 ioasc;
1775
1776         hcam_ldn = (struct pmcraid_hcam_ldn *)pinstance->ldn.hcam;
1777
1778         pmcraid_info
1779                 ("LDN(%x): %x type: %x lost: %x flags: %x overlay id: %x\n",
1780                  pinstance->ldn.hcam->ilid,
1781                  pinstance->ldn.hcam->op_code,
1782                  pinstance->ldn.hcam->notification_type,
1783                  pinstance->ldn.hcam->notification_lost,
1784                  pinstance->ldn.hcam->flags,
1785                  pinstance->ldn.hcam->overlay_id);
1786
1787         /* log only the errors, no need to log informational log entries */
1788         if (pinstance->ldn.hcam->notification_type !=
1789             NOTIFICATION_TYPE_ERROR_LOG)
1790                 return;
1791
1792         if (pinstance->ldn.hcam->notification_lost ==
1793             HOSTRCB_NOTIFICATIONS_LOST)
1794                 dev_info(&pinstance->pdev->dev, "Error notifications lost\n");
1795
1796         ioasc = le32_to_cpu(hcam_ldn->error_log.fd_ioasc);
1797
1798         if (ioasc == PMCRAID_IOASC_UA_BUS_WAS_RESET ||
1799                 ioasc == PMCRAID_IOASC_UA_BUS_WAS_RESET_BY_OTHER) {
1800                 dev_info(&pinstance->pdev->dev,
1801                         "UnitAttention due to IOA Bus Reset\n");
1802                 scsi_report_bus_reset(
1803                         pinstance->host,
1804                         RES_BUS(hcam_ldn->error_log.fd_ra));
1805         }
1806
1807         return;
1808 }
1809
1810 /**
1811  * pmcraid_process_ccn - Op done function for a CCN.
1812  * @cmd: pointer to command struct
1813  *
1814  * This function is the op done function for a configuration
1815  * change notification
1816  *
1817  * Return value:
1818  * none
1819  */
1820 static void pmcraid_process_ccn(struct pmcraid_cmd *cmd)
1821 {
1822         struct pmcraid_instance *pinstance = cmd->drv_inst;
1823         u32 ioasc = le32_to_cpu(cmd->ioa_cb->ioasa.ioasc);
1824         unsigned long lock_flags;
1825
1826         pinstance->ccn.cmd = NULL;
1827         pmcraid_return_cmd(cmd);
1828
1829         /* If driver initiated IOA reset happened while this hcam was pending
1830          * with IOA, or IOA bringdown sequence is in progress, no need to
1831          * re-register the hcam
1832          */
1833         if (ioasc == PMCRAID_IOASC_IOA_WAS_RESET ||
1834             atomic_read(&pinstance->ccn.ignore) == 1) {
1835                 return;
1836         } else if (ioasc) {
1837                 dev_info(&pinstance->pdev->dev,
1838                         "Host RCB (CCN) failed with IOASC: 0x%08X\n", ioasc);
1839                 spin_lock_irqsave(pinstance->host->host_lock, lock_flags);
1840                 pmcraid_send_hcam(pinstance, PMCRAID_HCAM_CODE_CONFIG_CHANGE);
1841                 spin_unlock_irqrestore(pinstance->host->host_lock, lock_flags);
1842         } else {
1843                 pmcraid_handle_config_change(pinstance);
1844         }
1845 }
1846
1847 /**
1848  * pmcraid_process_ldn - op done function for an LDN
1849  * @cmd: pointer to command block
1850  *
1851  * Return value
1852  *   none
1853  */
1854 static void pmcraid_initiate_reset(struct pmcraid_instance *);
1855 static void pmcraid_set_timestamp(struct pmcraid_cmd *cmd);
1856
1857 static void pmcraid_process_ldn(struct pmcraid_cmd *cmd)
1858 {
1859         struct pmcraid_instance *pinstance = cmd->drv_inst;
1860         struct pmcraid_hcam_ldn *ldn_hcam =
1861                         (struct pmcraid_hcam_ldn *)pinstance->ldn.hcam;
1862         u32 ioasc = le32_to_cpu(cmd->ioa_cb->ioasa.ioasc);
1863         u32 fd_ioasc = le32_to_cpu(ldn_hcam->error_log.fd_ioasc);
1864         unsigned long lock_flags;
1865
1866         /* return the command block back to freepool */
1867         pinstance->ldn.cmd = NULL;
1868         pmcraid_return_cmd(cmd);
1869
1870         /* If driver initiated IOA reset happened while this hcam was pending
1871          * with IOA, no need to re-register the hcam as reset engine will do it
1872          * once reset sequence is complete
1873          */
1874         if (ioasc == PMCRAID_IOASC_IOA_WAS_RESET ||
1875             atomic_read(&pinstance->ccn.ignore) == 1) {
1876                 return;
1877         } else if (!ioasc) {
1878                 pmcraid_handle_error_log(pinstance);
1879                 if (fd_ioasc == PMCRAID_IOASC_NR_IOA_RESET_REQUIRED) {
1880                         spin_lock_irqsave(pinstance->host->host_lock,
1881                                           lock_flags);
1882                         pmcraid_initiate_reset(pinstance);
1883                         spin_unlock_irqrestore(pinstance->host->host_lock,
1884                                                lock_flags);
1885                         return;
1886                 }
1887                 if (fd_ioasc == PMCRAID_IOASC_TIME_STAMP_OUT_OF_SYNC) {
1888                         pinstance->timestamp_error = 1;
1889                         pmcraid_set_timestamp(cmd);
1890                 }
1891         } else {
1892                 dev_info(&pinstance->pdev->dev,
1893                         "Host RCB(LDN) failed with IOASC: 0x%08X\n", ioasc);
1894         }
1895         /* send netlink message for HCAM notification if enabled */
1896         if (!pmcraid_disable_aen)
1897                 pmcraid_notify_ldn(pinstance);
1898
1899         cmd = pmcraid_init_hcam(pinstance, PMCRAID_HCAM_CODE_LOG_DATA);
1900         if (cmd)
1901                 pmcraid_send_hcam_cmd(cmd);
1902 }
1903
1904 /**
1905  * pmcraid_register_hcams - register HCAMs for CCN and LDN
1906  *
1907  * @pinstance: pointer per adapter instance structure
1908  *
1909  * Return Value
1910  *   none
1911  */
1912 static void pmcraid_register_hcams(struct pmcraid_instance *pinstance)
1913 {
1914         pmcraid_send_hcam(pinstance, PMCRAID_HCAM_CODE_CONFIG_CHANGE);
1915         pmcraid_send_hcam(pinstance, PMCRAID_HCAM_CODE_LOG_DATA);
1916 }
1917
1918 /**
1919  * pmcraid_unregister_hcams - cancel HCAMs registered already
1920  * @cmd: pointer to command used as part of reset sequence
1921  */
1922 static void pmcraid_unregister_hcams(struct pmcraid_cmd *cmd)
1923 {
1924         struct pmcraid_instance *pinstance = cmd->drv_inst;
1925
1926         /* During IOA bringdown, HCAM gets fired and tasklet proceeds with
1927          * handling hcam response though it is not necessary. In order to
1928          * prevent this, set 'ignore', so that bring-down sequence doesn't
1929          * re-send any more hcams
1930          */
1931         atomic_set(&pinstance->ccn.ignore, 1);
1932         atomic_set(&pinstance->ldn.ignore, 1);
1933
1934         /* If adapter reset was forced as part of runtime reset sequence,
1935          * start the reset sequence. Reset will be triggered even in case
1936          * IOA unit_check.
1937          */
1938         if ((pinstance->force_ioa_reset && !pinstance->ioa_bringdown) ||
1939              pinstance->ioa_unit_check) {
1940                 pinstance->force_ioa_reset = 0;
1941                 pinstance->ioa_unit_check = 0;
1942                 pinstance->ioa_state = IOA_STATE_IN_RESET_ALERT;
1943                 pmcraid_reset_alert(cmd);
1944                 return;
1945         }
1946
1947         /* Driver tries to cancel HCAMs by sending ABORT TASK for each HCAM
1948          * one after the other. So CCN cancellation will be triggered by
1949          * pmcraid_cancel_ldn itself.
1950          */
1951         pmcraid_cancel_ldn(cmd);
1952 }
1953
1954 /**
1955  * pmcraid_reset_enable_ioa - re-enable IOA after a hard reset
1956  * @pinstance: pointer to adapter instance structure
1957  * Return Value
1958  *  1 if TRANSITION_TO_OPERATIONAL is active, otherwise 0
1959  */
1960 static void pmcraid_reinit_buffers(struct pmcraid_instance *);
1961
1962 static int pmcraid_reset_enable_ioa(struct pmcraid_instance *pinstance)
1963 {
1964         u32 intrs;
1965
1966         pmcraid_reinit_buffers(pinstance);
1967         intrs = pmcraid_read_interrupts(pinstance);
1968
1969         pmcraid_enable_interrupts(pinstance, PMCRAID_PCI_INTERRUPTS);
1970
1971         if (intrs & INTRS_TRANSITION_TO_OPERATIONAL) {
1972                 if (!pinstance->interrupt_mode) {
1973                         iowrite32(INTRS_TRANSITION_TO_OPERATIONAL,
1974                                 pinstance->int_regs.
1975                                 ioa_host_interrupt_mask_reg);
1976                         iowrite32(INTRS_TRANSITION_TO_OPERATIONAL,
1977                                 pinstance->int_regs.ioa_host_interrupt_clr_reg);
1978                 }
1979                 return 1;
1980         } else {
1981                 return 0;
1982         }
1983 }
1984
1985 /**
1986  * pmcraid_soft_reset - performs a soft reset and makes IOA become ready
1987  * @cmd : pointer to reset command block
1988  *
1989  * Return Value
1990  *      none
1991  */
1992 static void pmcraid_soft_reset(struct pmcraid_cmd *cmd)
1993 {
1994         struct pmcraid_instance *pinstance = cmd->drv_inst;
1995         u32 int_reg;
1996         u32 doorbell;
1997
1998         /* There will be an interrupt when Transition to Operational bit is
1999          * set so tasklet would execute next reset task. The timeout handler
2000          * would re-initiate a reset
2001          */
2002         cmd->cmd_done = pmcraid_ioa_reset;
2003         cmd->timer.data = (unsigned long)cmd;
2004         cmd->timer.expires = jiffies +
2005                              msecs_to_jiffies(PMCRAID_TRANSOP_TIMEOUT);
2006         cmd->timer.function = (void (*)(unsigned long))pmcraid_timeout_handler;
2007
2008         if (!timer_pending(&cmd->timer))
2009                 add_timer(&cmd->timer);
2010
2011         /* Enable destructive diagnostics on IOA if it is not yet in
2012          * operational state
2013          */
2014         doorbell = DOORBELL_RUNTIME_RESET |
2015                    DOORBELL_ENABLE_DESTRUCTIVE_DIAGS;
2016
2017         /* Since we do RESET_ALERT and Start BIST we have to again write
2018          * MSIX Doorbell to indicate the interrupt mode
2019          */
2020         if (pinstance->interrupt_mode) {
2021                 iowrite32(DOORBELL_INTR_MODE_MSIX,
2022                           pinstance->int_regs.host_ioa_interrupt_reg);
2023                 ioread32(pinstance->int_regs.host_ioa_interrupt_reg);
2024         }
2025
2026         iowrite32(doorbell, pinstance->int_regs.host_ioa_interrupt_reg);
2027         ioread32(pinstance->int_regs.host_ioa_interrupt_reg),
2028         int_reg = ioread32(pinstance->int_regs.ioa_host_interrupt_reg);
2029
2030         pmcraid_info("Waiting for IOA to become operational %x:%x\n",
2031                      ioread32(pinstance->int_regs.host_ioa_interrupt_reg),
2032                      int_reg);
2033 }
2034
2035 /**
2036  * pmcraid_get_dump - retrieves IOA dump in case of Unit Check interrupt
2037  *
2038  * @pinstance: pointer to adapter instance structure
2039  *
2040  * Return Value
2041  *      none
2042  */
2043 static void pmcraid_get_dump(struct pmcraid_instance *pinstance)
2044 {
2045         pmcraid_info("%s is not yet implemented\n", __func__);
2046 }
2047
2048 /**
2049  * pmcraid_fail_outstanding_cmds - Fails all outstanding ops.
2050  * @pinstance: pointer to adapter instance structure
2051  *
2052  * This function fails all outstanding ops. If they are submitted to IOA
2053  * already, it sends cancel all messages if IOA is still accepting IOARCBs,
2054  * otherwise just completes the commands and returns the cmd blocks to free
2055  * pool.
2056  *
2057  * Return value:
2058  *       none
2059  */
2060 static void pmcraid_fail_outstanding_cmds(struct pmcraid_instance *pinstance)
2061 {
2062         struct pmcraid_cmd *cmd, *temp;
2063         unsigned long lock_flags;
2064
2065         /* pending command list is protected by pending_pool_lock. Its
2066          * traversal must be done as within this lock
2067          */
2068         spin_lock_irqsave(&pinstance->pending_pool_lock, lock_flags);
2069         list_for_each_entry_safe(cmd, temp, &pinstance->pending_cmd_pool,
2070                                  free_list) {
2071                 list_del(&cmd->free_list);
2072                 spin_unlock_irqrestore(&pinstance->pending_pool_lock,
2073                                         lock_flags);
2074                 cmd->ioa_cb->ioasa.ioasc =
2075                         cpu_to_le32(PMCRAID_IOASC_IOA_WAS_RESET);
2076                 cmd->ioa_cb->ioasa.ilid =
2077                         cpu_to_be32(PMCRAID_DRIVER_ILID);
2078
2079                 /* In case the command timer is still running */
2080                 del_timer(&cmd->timer);
2081
2082                 /* If this is an IO command, complete it by invoking scsi_done
2083                  * function. If this is one of the internal commands other
2084                  * than pmcraid_ioa_reset and HCAM commands invoke cmd_done to
2085                  * complete it
2086                  */
2087                 if (cmd->scsi_cmd) {
2088
2089                         struct scsi_cmnd *scsi_cmd = cmd->scsi_cmd;
2090                         __le32 resp = cmd->ioa_cb->ioarcb.response_handle;
2091
2092                         scsi_cmd->result |= DID_ERROR << 16;
2093
2094                         scsi_dma_unmap(scsi_cmd);
2095                         pmcraid_return_cmd(cmd);
2096
2097                         pmcraid_info("failing(%d) CDB[0] = %x result: %x\n",
2098                                      le32_to_cpu(resp) >> 2,
2099                                      cmd->ioa_cb->ioarcb.cdb[0],
2100                                      scsi_cmd->result);
2101                         scsi_cmd->scsi_done(scsi_cmd);
2102                 } else if (cmd->cmd_done == pmcraid_internal_done ||
2103                            cmd->cmd_done == pmcraid_erp_done) {
2104                         cmd->cmd_done(cmd);
2105                 } else if (cmd->cmd_done != pmcraid_ioa_reset &&
2106                            cmd->cmd_done != pmcraid_ioa_shutdown_done) {
2107                         pmcraid_return_cmd(cmd);
2108                 }
2109
2110                 atomic_dec(&pinstance->outstanding_cmds);
2111                 spin_lock_irqsave(&pinstance->pending_pool_lock, lock_flags);
2112         }
2113
2114         spin_unlock_irqrestore(&pinstance->pending_pool_lock, lock_flags);
2115 }
2116
2117 /**
2118  * pmcraid_ioa_reset - Implementation of IOA reset logic
2119  *
2120  * @cmd: pointer to the cmd block to be used for entire reset process
2121  *
2122  * This function executes most of the steps required for IOA reset. This gets
2123  * called by user threads (modprobe/insmod/rmmod) timer, tasklet and midlayer's
2124  * 'eh_' thread. Access to variables used for controlling the reset sequence is
2125  * synchronized using host lock. Various functions called during reset process
2126  * would make use of a single command block, pointer to which is also stored in
2127  * adapter instance structure.
2128  *
2129  * Return Value
2130  *       None
2131  */
2132 static void pmcraid_ioa_reset(struct pmcraid_cmd *cmd)
2133 {
2134         struct pmcraid_instance *pinstance = cmd->drv_inst;
2135         u8 reset_complete = 0;
2136
2137         pinstance->ioa_reset_in_progress = 1;
2138
2139         if (pinstance->reset_cmd != cmd) {
2140                 pmcraid_err("reset is called with different command block\n");
2141                 pinstance->reset_cmd = cmd;
2142         }
2143
2144         pmcraid_info("reset_engine: state = %d, command = %p\n",
2145                       pinstance->ioa_state, cmd);
2146
2147         switch (pinstance->ioa_state) {
2148
2149         case IOA_STATE_DEAD:
2150                 /* If IOA is offline, whatever may be the reset reason, just
2151                  * return. callers might be waiting on the reset wait_q, wake
2152                  * up them
2153                  */
2154                 pmcraid_err("IOA is offline no reset is possible\n");
2155                 reset_complete = 1;
2156                 break;
2157
2158         case IOA_STATE_IN_BRINGDOWN:
2159                 /* we enter here, once ioa shutdown command is processed by IOA
2160                  * Alert IOA for a possible reset. If reset alert fails, IOA
2161                  * goes through hard-reset
2162                  */
2163                 pmcraid_disable_interrupts(pinstance, ~0);
2164                 pinstance->ioa_state = IOA_STATE_IN_RESET_ALERT;
2165                 pmcraid_reset_alert(cmd);
2166                 break;
2167
2168         case IOA_STATE_UNKNOWN:
2169                 /* We may be called during probe or resume. Some pre-processing
2170                  * is required for prior to reset
2171                  */
2172                 scsi_block_requests(pinstance->host);
2173
2174                 /* If asked to reset while IOA was processing responses or
2175                  * there are any error responses then IOA may require
2176                  * hard-reset.
2177                  */
2178                 if (pinstance->ioa_hard_reset == 0) {
2179                         if (ioread32(pinstance->ioa_status) &
2180                             INTRS_TRANSITION_TO_OPERATIONAL) {
2181                                 pmcraid_info("sticky bit set, bring-up\n");
2182                                 pinstance->ioa_state = IOA_STATE_IN_BRINGUP;
2183                                 pmcraid_reinit_cmdblk(cmd);
2184                                 pmcraid_identify_hrrq(cmd);
2185                         } else {
2186                                 pinstance->ioa_state = IOA_STATE_IN_SOFT_RESET;
2187                                 pmcraid_soft_reset(cmd);
2188                         }
2189                 } else {
2190                         /* Alert IOA of a possible reset and wait for critical
2191                          * operation in progress bit to reset
2192                          */
2193                         pinstance->ioa_state = IOA_STATE_IN_RESET_ALERT;
2194                         pmcraid_reset_alert(cmd);
2195                 }
2196                 break;
2197
2198         case IOA_STATE_IN_RESET_ALERT:
2199                 /* If critical operation in progress bit is reset or wait gets
2200                  * timed out, reset proceeds with starting BIST on the IOA.
2201                  * pmcraid_ioa_hard_reset keeps a count of reset attempts. If
2202                  * they are 3 or more, reset engine marks IOA dead and returns
2203                  */
2204                 pinstance->ioa_state = IOA_STATE_IN_HARD_RESET;
2205                 pmcraid_start_bist(cmd);
2206                 break;
2207
2208         case IOA_STATE_IN_HARD_RESET:
2209                 pinstance->ioa_reset_attempts++;
2210
2211                 /* retry reset if we haven't reached maximum allowed limit */
2212                 if (pinstance->ioa_reset_attempts > PMCRAID_RESET_ATTEMPTS) {
2213                         pinstance->ioa_reset_attempts = 0;
2214                         pmcraid_err("IOA didn't respond marking it as dead\n");
2215                         pinstance->ioa_state = IOA_STATE_DEAD;
2216
2217                         if (pinstance->ioa_bringdown)
2218                                 pmcraid_notify_ioastate(pinstance,
2219                                         PMC_DEVICE_EVENT_SHUTDOWN_FAILED);
2220                         else
2221                                 pmcraid_notify_ioastate(pinstance,
2222                                                 PMC_DEVICE_EVENT_RESET_FAILED);
2223                         reset_complete = 1;
2224                         break;
2225                 }
2226
2227                 /* Once either bist or pci reset is done, restore PCI config
2228                  * space. If this fails, proceed with hard reset again
2229                  */
2230                 pci_restore_state(pinstance->pdev);
2231
2232                 /* fail all pending commands */
2233                 pmcraid_fail_outstanding_cmds(pinstance);
2234
2235                 /* check if unit check is active, if so extract dump */
2236                 if (pinstance->ioa_unit_check) {
2237                         pmcraid_info("unit check is active\n");
2238                         pinstance->ioa_unit_check = 0;
2239                         pmcraid_get_dump(pinstance);
2240                         pinstance->ioa_reset_attempts--;
2241                         pinstance->ioa_state = IOA_STATE_IN_RESET_ALERT;
2242                         pmcraid_reset_alert(cmd);
2243                         break;
2244                 }
2245
2246                 /* if the reset reason is to bring-down the ioa, we might be
2247                  * done with the reset restore pci_config_space and complete
2248                  * the reset
2249                  */
2250                 if (pinstance->ioa_bringdown) {
2251                         pmcraid_info("bringing down the adapter\n");
2252                         pinstance->ioa_shutdown_type = SHUTDOWN_NONE;
2253                         pinstance->ioa_bringdown = 0;
2254                         pinstance->ioa_state = IOA_STATE_UNKNOWN;
2255                         pmcraid_notify_ioastate(pinstance,
2256                                         PMC_DEVICE_EVENT_SHUTDOWN_SUCCESS);
2257                         reset_complete = 1;
2258                 } else {
2259                         /* bring-up IOA, so proceed with soft reset
2260                          * Reinitialize hrrq_buffers and their indices also
2261                          * enable interrupts after a pci_restore_state
2262                          */
2263                         if (pmcraid_reset_enable_ioa(pinstance)) {
2264                                 pinstance->ioa_state = IOA_STATE_IN_BRINGUP;
2265                                 pmcraid_info("bringing up the adapter\n");
2266                                 pmcraid_reinit_cmdblk(cmd);
2267                                 pmcraid_identify_hrrq(cmd);
2268                         } else {
2269                                 pinstance->ioa_state = IOA_STATE_IN_SOFT_RESET;
2270                                 pmcraid_soft_reset(cmd);
2271                         }
2272                 }
2273                 break;
2274
2275         case IOA_STATE_IN_SOFT_RESET:
2276                 /* TRANSITION TO OPERATIONAL is on so start initialization
2277                  * sequence
2278                  */
2279                 pmcraid_info("In softreset proceeding with bring-up\n");
2280                 pinstance->ioa_state = IOA_STATE_IN_BRINGUP;
2281
2282                 /* Initialization commands start with HRRQ identification. From
2283                  * now on tasklet completes most of the commands as IOA is up
2284                  * and intrs are enabled
2285                  */
2286                 pmcraid_identify_hrrq(cmd);
2287                 break;
2288
2289         case IOA_STATE_IN_BRINGUP:
2290                 /* we are done with bringing up of IOA, change the ioa_state to
2291                  * operational and wake up any waiters
2292                  */
2293                 pinstance->ioa_state = IOA_STATE_OPERATIONAL;
2294                 reset_complete = 1;
2295                 break;
2296
2297         case IOA_STATE_OPERATIONAL:
2298         default:
2299                 /* When IOA is operational and a reset is requested, check for
2300                  * the reset reason. If reset is to bring down IOA, unregister
2301                  * HCAMs and initiate shutdown; if adapter reset is forced then
2302                  * restart reset sequence again
2303                  */
2304                 if (pinstance->ioa_shutdown_type == SHUTDOWN_NONE &&
2305                     pinstance->force_ioa_reset == 0) {
2306                         pmcraid_notify_ioastate(pinstance,
2307                                                 PMC_DEVICE_EVENT_RESET_SUCCESS);
2308                         reset_complete = 1;
2309                 } else {
2310                         if (pinstance->ioa_shutdown_type != SHUTDOWN_NONE)
2311                                 pinstance->ioa_state = IOA_STATE_IN_BRINGDOWN;
2312                         pmcraid_reinit_cmdblk(cmd);
2313                         pmcraid_unregister_hcams(cmd);
2314                 }
2315                 break;
2316         }
2317
2318         /* reset will be completed if ioa_state is either DEAD or UNKNOWN or
2319          * OPERATIONAL. Reset all control variables used during reset, wake up
2320          * any waiting threads and let the SCSI mid-layer send commands. Note
2321          * that host_lock must be held before invoking scsi_report_bus_reset.
2322          */
2323         if (reset_complete) {
2324                 pinstance->ioa_reset_in_progress = 0;
2325                 pinstance->ioa_reset_attempts = 0;
2326                 pinstance->reset_cmd = NULL;
2327                 pinstance->ioa_shutdown_type = SHUTDOWN_NONE;
2328                 pinstance->ioa_bringdown = 0;
2329                 pmcraid_return_cmd(cmd);
2330
2331                 /* If target state is to bring up the adapter, proceed with
2332                  * hcam registration and resource exposure to mid-layer.
2333                  */
2334                 if (pinstance->ioa_state == IOA_STATE_OPERATIONAL)
2335                         pmcraid_register_hcams(pinstance);
2336
2337                 wake_up_all(&pinstance->reset_wait_q);
2338         }
2339
2340         return;
2341 }
2342
2343 /**
2344  * pmcraid_initiate_reset - initiates reset sequence. This is called from
2345  * ISR/tasklet during error interrupts including IOA unit check. If reset
2346  * is already in progress, it just returns, otherwise initiates IOA reset
2347  * to bring IOA up to operational state.
2348  *
2349  * @pinstance: pointer to adapter instance structure
2350  *
2351  * Return value
2352  *       none
2353  */
2354 static void pmcraid_initiate_reset(struct pmcraid_instance *pinstance)
2355 {
2356         struct pmcraid_cmd *cmd;
2357
2358         /* If the reset is already in progress, just return, otherwise start
2359          * reset sequence and return
2360          */
2361         if (!pinstance->ioa_reset_in_progress) {
2362                 scsi_block_requests(pinstance->host);
2363                 cmd = pmcraid_get_free_cmd(pinstance);
2364
2365                 if (cmd == NULL) {
2366                         pmcraid_err("no cmnd blocks for initiate_reset\n");
2367                         return;
2368                 }
2369
2370                 pinstance->ioa_shutdown_type = SHUTDOWN_NONE;
2371                 pinstance->reset_cmd = cmd;
2372                 pinstance->force_ioa_reset = 1;
2373                 pmcraid_notify_ioastate(pinstance,
2374                                         PMC_DEVICE_EVENT_RESET_START);
2375                 pmcraid_ioa_reset(cmd);
2376         }
2377 }
2378
2379 /**
2380  * pmcraid_reset_reload - utility routine for doing IOA reset either to bringup
2381  *                        or bringdown IOA
2382  * @pinstance: pointer adapter instance structure
2383  * @shutdown_type: shutdown type to be used NONE, NORMAL or ABRREV
2384  * @target_state: expected target state after reset
2385  *
2386  * Note: This command initiates reset and waits for its completion. Hence this
2387  * should not be called from isr/timer/tasklet functions (timeout handlers,
2388  * error response handlers and interrupt handlers).
2389  *
2390  * Return Value
2391  *       1 in case ioa_state is not target_state, 0 otherwise.
2392  */
2393 static int pmcraid_reset_reload(
2394         struct pmcraid_instance *pinstance,
2395         u8 shutdown_type,
2396         u8 target_state
2397 )
2398 {
2399         struct pmcraid_cmd *reset_cmd = NULL;
2400         unsigned long lock_flags;
2401         int reset = 1;
2402
2403         spin_lock_irqsave(pinstance->host->host_lock, lock_flags);
2404
2405         if (pinstance->ioa_reset_in_progress) {
2406                 pmcraid_info("reset_reload: reset is already in progress\n");
2407
2408                 spin_unlock_irqrestore(pinstance->host->host_lock, lock_flags);
2409
2410                 wait_event(pinstance->reset_wait_q,
2411                            !pinstance->ioa_reset_in_progress);
2412
2413                 spin_lock_irqsave(pinstance->host->host_lock, lock_flags);
2414
2415                 if (pinstance->ioa_state == IOA_STATE_DEAD) {
2416                         spin_unlock_irqrestore(pinstance->host->host_lock,
2417                                                lock_flags);
2418                         pmcraid_info("reset_reload: IOA is dead\n");
2419                         return reset;
2420                 } else if (pinstance->ioa_state == target_state) {
2421                         reset = 0;
2422                 }
2423         }
2424
2425         if (reset) {
2426                 pmcraid_info("reset_reload: proceeding with reset\n");
2427                 scsi_block_requests(pinstance->host);
2428                 reset_cmd = pmcraid_get_free_cmd(pinstance);
2429
2430                 if (reset_cmd == NULL) {
2431                         pmcraid_err("no free cmnd for reset_reload\n");
2432                         spin_unlock_irqrestore(pinstance->host->host_lock,
2433                                                lock_flags);
2434                         return reset;
2435                 }
2436
2437                 if (shutdown_type == SHUTDOWN_NORMAL)
2438                         pinstance->ioa_bringdown = 1;
2439
2440                 pinstance->ioa_shutdown_type = shutdown_type;
2441                 pinstance->reset_cmd = reset_cmd;
2442                 pinstance->force_ioa_reset = reset;
2443                 pmcraid_info("reset_reload: initiating reset\n");
2444                 pmcraid_ioa_reset(reset_cmd);
2445                 spin_unlock_irqrestore(pinstance->host->host_lock, lock_flags);
2446                 pmcraid_info("reset_reload: waiting for reset to complete\n");
2447                 wait_event(pinstance->reset_wait_q,
2448                            !pinstance->ioa_reset_in_progress);
2449
2450                 pmcraid_info("reset_reload: reset is complete !!\n");
2451                 scsi_unblock_requests(pinstance->host);
2452                 if (pinstance->ioa_state == target_state)
2453                         reset = 0;
2454         }
2455
2456         return reset;
2457 }
2458
2459 /**
2460  * pmcraid_reset_bringdown - wrapper over pmcraid_reset_reload to bringdown IOA
2461  *
2462  * @pinstance: pointer to adapter instance structure
2463  *
2464  * Return Value
2465  *       whatever is returned from pmcraid_reset_reload
2466  */
2467 static int pmcraid_reset_bringdown(struct pmcraid_instance *pinstance)
2468 {
2469         return pmcraid_reset_reload(pinstance,
2470                                     SHUTDOWN_NORMAL,
2471                                     IOA_STATE_UNKNOWN);
2472 }
2473
2474 /**
2475  * pmcraid_reset_bringup - wrapper over pmcraid_reset_reload to bring up IOA
2476  *
2477  * @pinstance: pointer to adapter instance structure
2478  *
2479  * Return Value
2480  *       whatever is returned from pmcraid_reset_reload
2481  */
2482 static int pmcraid_reset_bringup(struct pmcraid_instance *pinstance)
2483 {
2484         pmcraid_notify_ioastate(pinstance, PMC_DEVICE_EVENT_RESET_START);
2485
2486         return pmcraid_reset_reload(pinstance,
2487                                     SHUTDOWN_NONE,
2488                                     IOA_STATE_OPERATIONAL);
2489 }
2490
2491 /**
2492  * pmcraid_request_sense - Send request sense to a device
2493  * @cmd: pmcraid command struct
2494  *
2495  * This function sends a request sense to a device as a result of a check
2496  * condition. This method re-uses the same command block that failed earlier.
2497  */
2498 static void pmcraid_request_sense(struct pmcraid_cmd *cmd)
2499 {
2500         struct pmcraid_ioarcb *ioarcb = &cmd->ioa_cb->ioarcb;
2501         struct pmcraid_ioadl_desc *ioadl = ioarcb->add_data.u.ioadl;
2502
2503         /* allocate DMAable memory for sense buffers */
2504         cmd->sense_buffer = pci_alloc_consistent(cmd->drv_inst->pdev,
2505                                                  SCSI_SENSE_BUFFERSIZE,
2506                                                  &cmd->sense_buffer_dma);
2507
2508         if (cmd->sense_buffer == NULL) {
2509                 pmcraid_err
2510                         ("couldn't allocate sense buffer for request sense\n");
2511                 pmcraid_erp_done(cmd);
2512                 return;
2513         }
2514
2515         /* re-use the command block */
2516         memset(&cmd->ioa_cb->ioasa, 0, sizeof(struct pmcraid_ioasa));
2517         memset(ioarcb->cdb, 0, PMCRAID_MAX_CDB_LEN);
2518         ioarcb->request_flags0 = (SYNC_COMPLETE |
2519                                   NO_LINK_DESCS |
2520                                   INHIBIT_UL_CHECK);
2521         ioarcb->request_type = REQ_TYPE_SCSI;
2522         ioarcb->cdb[0] = REQUEST_SENSE;
2523         ioarcb->cdb[4] = SCSI_SENSE_BUFFERSIZE;
2524
2525         ioarcb->ioadl_bus_addr = cpu_to_le64((cmd->ioa_cb_bus_addr) +
2526                                         offsetof(struct pmcraid_ioarcb,
2527                                                 add_data.u.ioadl[0]));
2528         ioarcb->ioadl_length = cpu_to_le32(sizeof(struct pmcraid_ioadl_desc));
2529
2530         ioarcb->data_transfer_length = cpu_to_le32(SCSI_SENSE_BUFFERSIZE);
2531
2532         ioadl->address = cpu_to_le64(cmd->sense_buffer_dma);
2533         ioadl->data_len = cpu_to_le32(SCSI_SENSE_BUFFERSIZE);
2534         ioadl->flags = IOADL_FLAGS_LAST_DESC;
2535
2536         /* request sense might be called as part of error response processing
2537          * which runs in tasklets context. It is possible that mid-layer might
2538          * schedule queuecommand during this time, hence, writting to IOARRIN
2539          * must be protect by host_lock
2540          */
2541         pmcraid_send_cmd(cmd, pmcraid_erp_done,
2542                          PMCRAID_REQUEST_SENSE_TIMEOUT,
2543                          pmcraid_timeout_handler);
2544 }
2545
2546 /**
2547  * pmcraid_cancel_all - cancel all outstanding IOARCBs as part of error recovery
2548  * @cmd: command that failed
2549  * @sense: true if request_sense is required after cancel all
2550  *
2551  * This function sends a cancel all to a device to clear the queue.
2552  */
2553 static void pmcraid_cancel_all(struct pmcraid_cmd *cmd, u32 sense)
2554 {
2555         struct scsi_cmnd *scsi_cmd = cmd->scsi_cmd;
2556         struct pmcraid_ioarcb *ioarcb = &cmd->ioa_cb->ioarcb;
2557         struct pmcraid_resource_entry *res = scsi_cmd->device->hostdata;
2558         void (*cmd_done) (struct pmcraid_cmd *) = sense ? pmcraid_erp_done
2559                                                         : pmcraid_request_sense;
2560
2561         memset(ioarcb->cdb, 0, PMCRAID_MAX_CDB_LEN);
2562         ioarcb->request_flags0 = SYNC_OVERRIDE;
2563         ioarcb->request_type = REQ_TYPE_IOACMD;
2564         ioarcb->cdb[0] = PMCRAID_CANCEL_ALL_REQUESTS;
2565
2566         if (RES_IS_GSCSI(res->cfg_entry))
2567                 ioarcb->cdb[1] = PMCRAID_SYNC_COMPLETE_AFTER_CANCEL;
2568
2569         ioarcb->ioadl_bus_addr = 0;
2570         ioarcb->ioadl_length = 0;
2571         ioarcb->data_transfer_length = 0;
2572         ioarcb->ioarcb_bus_addr &= (~0x1FULL);
2573
2574         /* writing to IOARRIN must be protected by host_lock, as mid-layer
2575          * schedule queuecommand while we are doing this
2576          */
2577         pmcraid_send_cmd(cmd, cmd_done,
2578                          PMCRAID_REQUEST_SENSE_TIMEOUT,
2579                          pmcraid_timeout_handler);
2580 }
2581
2582 /**
2583  * pmcraid_frame_auto_sense: frame fixed format sense information
2584  *
2585  * @cmd: pointer to failing command block
2586  *
2587  * Return value
2588  *  none
2589  */
2590 static void pmcraid_frame_auto_sense(struct pmcraid_cmd *cmd)
2591 {
2592         u8 *sense_buf = cmd->scsi_cmd->sense_buffer;
2593         struct pmcraid_resource_entry *res = cmd->scsi_cmd->device->hostdata;
2594         struct pmcraid_ioasa *ioasa = &cmd->ioa_cb->ioasa;
2595         u32 ioasc = le32_to_cpu(ioasa->ioasc);
2596         u32 failing_lba = 0;
2597
2598         memset(sense_buf, 0, SCSI_SENSE_BUFFERSIZE);
2599         cmd->scsi_cmd->result = SAM_STAT_CHECK_CONDITION;
2600
2601         if (RES_IS_VSET(res->cfg_entry) &&
2602             ioasc == PMCRAID_IOASC_ME_READ_ERROR_NO_REALLOC &&
2603             ioasa->u.vset.failing_lba_hi != 0) {
2604
2605                 sense_buf[0] = 0x72;
2606                 sense_buf[1] = PMCRAID_IOASC_SENSE_KEY(ioasc);
2607                 sense_buf[2] = PMCRAID_IOASC_SENSE_CODE(ioasc);
2608                 sense_buf[3] = PMCRAID_IOASC_SENSE_QUAL(ioasc);
2609
2610                 sense_buf[7] = 12;
2611                 sense_buf[8] = 0;
2612                 sense_buf[9] = 0x0A;
2613                 sense_buf[10] = 0x80;
2614
2615                 failing_lba = le32_to_cpu(ioasa->u.vset.failing_lba_hi);
2616
2617                 sense_buf[12] = (failing_lba & 0xff000000) >> 24;
2618                 sense_buf[13] = (failing_lba & 0x00ff0000) >> 16;
2619                 sense_buf[14] = (failing_lba & 0x0000ff00) >> 8;
2620                 sense_buf[15] = failing_lba & 0x000000ff;
2621
2622                 failing_lba = le32_to_cpu(ioasa->u.vset.failing_lba_lo);
2623
2624                 sense_buf[16] = (failing_lba & 0xff000000) >> 24;
2625                 sense_buf[17] = (failing_lba & 0x00ff0000) >> 16;
2626                 sense_buf[18] = (failing_lba & 0x0000ff00) >> 8;
2627                 sense_buf[19] = failing_lba & 0x000000ff;
2628         } else {
2629                 sense_buf[0] = 0x70;
2630                 sense_buf[2] = PMCRAID_IOASC_SENSE_KEY(ioasc);
2631                 sense_buf[12] = PMCRAID_IOASC_SENSE_CODE(ioasc);
2632                 sense_buf[13] = PMCRAID_IOASC_SENSE_QUAL(ioasc);
2633
2634                 if (ioasc == PMCRAID_IOASC_ME_READ_ERROR_NO_REALLOC) {
2635                         if (RES_IS_VSET(res->cfg_entry))
2636                                 failing_lba =
2637                                         le32_to_cpu(ioasa->u.
2638                                                  vset.failing_lba_lo);
2639                         sense_buf[0] |= 0x80;
2640                         sense_buf[3] = (failing_lba >> 24) & 0xff;
2641                         sense_buf[4] = (failing_lba >> 16) & 0xff;
2642                         sense_buf[5] = (failing_lba >> 8) & 0xff;
2643                         sense_buf[6] = failing_lba & 0xff;
2644                 }
2645
2646                 sense_buf[7] = 6; /* additional length */
2647         }
2648 }
2649
2650 /**
2651  * pmcraid_error_handler - Error response handlers for a SCSI op
2652  * @cmd: pointer to pmcraid_cmd that has failed
2653  *
2654  * This function determines whether or not to initiate ERP on the affected
2655  * device. This is called from a tasklet, which doesn't hold any locks.
2656  *
2657  * Return value:
2658  *       0 it caller can complete the request, otherwise 1 where in error
2659  *       handler itself completes the request and returns the command block
2660  *       back to free-pool
2661  */
2662 static int pmcraid_error_handler(struct pmcraid_cmd *cmd)
2663 {
2664         struct scsi_cmnd *scsi_cmd = cmd->scsi_cmd;
2665         struct pmcraid_resource_entry *res = scsi_cmd->device->hostdata;
2666         struct pmcraid_instance *pinstance = cmd->drv_inst;
2667         struct pmcraid_ioasa *ioasa = &cmd->ioa_cb->ioasa;
2668         u32 ioasc = le32_to_cpu(ioasa->ioasc);
2669         u32 masked_ioasc = ioasc & PMCRAID_IOASC_SENSE_MASK;
2670         u32 sense_copied = 0;
2671
2672         if (!res) {
2673                 pmcraid_info("resource pointer is NULL\n");
2674                 return 0;
2675         }
2676
2677         /* If this was a SCSI read/write command keep count of errors */
2678         if (SCSI_CMD_TYPE(scsi_cmd->cmnd[0]) == SCSI_READ_CMD)
2679                 atomic_inc(&res->read_failures);
2680         else if (SCSI_CMD_TYPE(scsi_cmd->cmnd[0]) == SCSI_WRITE_CMD)
2681                 atomic_inc(&res->write_failures);
2682
2683         if (!RES_IS_GSCSI(res->cfg_entry) &&
2684                 masked_ioasc != PMCRAID_IOASC_HW_DEVICE_BUS_STATUS_ERROR) {
2685                 pmcraid_frame_auto_sense(cmd);
2686         }
2687
2688         /* Log IOASC/IOASA information based on user settings */
2689         pmcraid_ioasc_logger(ioasc, cmd);
2690
2691         switch (masked_ioasc) {
2692
2693         case PMCRAID_IOASC_AC_TERMINATED_BY_HOST:
2694                 scsi_cmd->result |= (DID_ABORT << 16);
2695                 break;
2696
2697         case PMCRAID_IOASC_IR_INVALID_RESOURCE_HANDLE:
2698         case PMCRAID_IOASC_HW_CANNOT_COMMUNICATE:
2699                 scsi_cmd->result |= (DID_NO_CONNECT << 16);
2700                 break;
2701
2702         case PMCRAID_IOASC_NR_SYNC_REQUIRED:
2703                 res->sync_reqd = 1;
2704                 scsi_cmd->result |= (DID_IMM_RETRY << 16);
2705                 break;
2706
2707         case PMCRAID_IOASC_ME_READ_ERROR_NO_REALLOC:
2708                 scsi_cmd->result |= (DID_PASSTHROUGH << 16);
2709                 break;
2710
2711         case PMCRAID_IOASC_UA_BUS_WAS_RESET:
2712         case PMCRAID_IOASC_UA_BUS_WAS_RESET_BY_OTHER:
2713                 if (!res->reset_progress)
2714                         scsi_report_bus_reset(pinstance->host,
2715                                               scsi_cmd->device->channel);
2716                 scsi_cmd->result |= (DID_ERROR << 16);
2717                 break;
2718
2719         case PMCRAID_IOASC_HW_DEVICE_BUS_STATUS_ERROR:
2720                 scsi_cmd->result |= PMCRAID_IOASC_SENSE_STATUS(ioasc);
2721                 res->sync_reqd = 1;
2722
2723                 /* if check_condition is not active return with error otherwise
2724                  * get/frame the sense buffer
2725                  */
2726                 if (PMCRAID_IOASC_SENSE_STATUS(ioasc) !=
2727                     SAM_STAT_CHECK_CONDITION &&
2728                     PMCRAID_IOASC_SENSE_STATUS(ioasc) != SAM_STAT_ACA_ACTIVE)
2729                         return 0;
2730
2731                 /* If we have auto sense data as part of IOASA pass it to
2732                  * mid-layer
2733                  */
2734                 if (ioasa->auto_sense_length != 0) {
2735                         short sense_len = ioasa->auto_sense_length;
2736                         int data_size = min_t(u16, le16_to_cpu(sense_len),
2737                                               SCSI_SENSE_BUFFERSIZE);
2738
2739                         memcpy(scsi_cmd->sense_buffer,
2740                                ioasa->sense_data,
2741                                data_size);
2742                         sense_copied = 1;
2743                 }
2744
2745                 if (RES_IS_GSCSI(res->cfg_entry))
2746                         pmcraid_cancel_all(cmd, sense_copied);
2747                 else if (sense_copied)
2748                         pmcraid_erp_done(cmd);
2749                 else
2750                         pmcraid_request_sense(cmd);
2751
2752                 return 1;
2753
2754         case PMCRAID_IOASC_NR_INIT_CMD_REQUIRED:
2755                 break;
2756
2757         default:
2758                 if (PMCRAID_IOASC_SENSE_KEY(ioasc) > RECOVERED_ERROR)
2759                         scsi_cmd->result |= (DID_ERROR << 16);
2760                 break;
2761         }
2762         return 0;
2763 }
2764
2765 /**
2766  * pmcraid_reset_device - device reset handler functions
2767  *
2768  * @scsi_cmd: scsi command struct
2769  * @modifier: reset modifier indicating the reset sequence to be performed
2770  *
2771  * This function issues a device reset to the affected device.
2772  * A LUN reset will be sent to the device first. If that does
2773  * not work, a target reset will be sent.
2774  *
2775  * Return value:
2776  *      SUCCESS / FAILED
2777  */
2778 static int pmcraid_reset_device(
2779         struct scsi_cmnd *scsi_cmd,
2780         unsigned long timeout,
2781         u8 modifier
2782 )
2783 {
2784         struct pmcraid_cmd *cmd;
2785         struct pmcraid_instance *pinstance;
2786         struct pmcraid_resource_entry *res;
2787         struct pmcraid_ioarcb *ioarcb;
2788         unsigned long lock_flags;
2789         u32 ioasc;
2790
2791         pinstance =
2792                 (struct pmcraid_instance *)scsi_cmd->device->host->hostdata;
2793         res = scsi_cmd->device->hostdata;
2794
2795         if (!res) {
2796                 sdev_printk(KERN_ERR, scsi_cmd->device,
2797                             "reset_device: NULL resource pointer\n");
2798                 return FAILED;
2799         }
2800
2801         /* If adapter is currently going through reset/reload, return failed.
2802          * This will force the mid-layer to call _eh_bus/host reset, which
2803          * will then go to sleep and wait for the reset to complete
2804          */
2805         spin_lock_irqsave(pinstance->host->host_lock, lock_flags);
2806         if (pinstance->ioa_reset_in_progress ||
2807             pinstance->ioa_state == IOA_STATE_DEAD) {
2808                 spin_unlock_irqrestore(pinstance->host->host_lock, lock_flags);
2809                 return FAILED;
2810         }
2811
2812         res->reset_progress = 1;
2813         pmcraid_info("Resetting %s resource with addr %x\n",
2814                      ((modifier & RESET_DEVICE_LUN) ? "LUN" :
2815                      ((modifier & RESET_DEVICE_TARGET) ? "TARGET" : "BUS")),
2816                      le32_to_cpu(res->cfg_entry.resource_address));
2817
2818         /* get a free cmd block */
2819         cmd = pmcraid_get_free_cmd(pinstance);
2820
2821         if (cmd == NULL) {
2822                 spin_unlock_irqrestore(pinstance->host->host_lock, lock_flags);
2823                 pmcraid_err("%s: no cmd blocks are available\n", __func__);
2824                 return FAILED;
2825         }
2826
2827         ioarcb = &cmd->ioa_cb->ioarcb;
2828         ioarcb->resource_handle = res->cfg_entry.resource_handle;
2829         ioarcb->request_type = REQ_TYPE_IOACMD;
2830         ioarcb->cdb[0] = PMCRAID_RESET_DEVICE;
2831
2832         /* Initialize reset modifier bits */
2833         if (modifier)
2834                 modifier = ENABLE_RESET_MODIFIER | modifier;
2835
2836         ioarcb->cdb[1] = modifier;
2837
2838         init_completion(&cmd->wait_for_completion);
2839         cmd->completion_req = 1;
2840
2841         pmcraid_info("cmd(CDB[0] = %x) for %x with index = %d\n",
2842                      cmd->ioa_cb->ioarcb.cdb[0],
2843                      le32_to_cpu(cmd->ioa_cb->ioarcb.resource_handle),
2844                      le32_to_cpu(cmd->ioa_cb->ioarcb.response_handle) >> 2);
2845
2846         pmcraid_send_cmd(cmd,
2847                          pmcraid_internal_done,
2848                          timeout,
2849                          pmcraid_timeout_handler);
2850
2851         spin_unlock_irqrestore(pinstance->host->host_lock, lock_flags);
2852
2853         /* RESET_DEVICE command completes after all pending IOARCBs are
2854          * completed. Once this command is completed, pmcraind_internal_done
2855          * will wake up the 'completion' queue.
2856          */
2857         wait_for_completion(&cmd->wait_for_completion);
2858
2859         /* complete the command here itself and return the command block
2860          * to free list
2861          */
2862         pmcraid_return_cmd(cmd);
2863         res->reset_progress = 0;
2864         ioasc = le32_to_cpu(cmd->ioa_cb->ioasa.ioasc);
2865
2866         /* set the return value based on the returned ioasc */
2867         return PMCRAID_IOASC_SENSE_KEY(ioasc) ? FAILED : SUCCESS;
2868 }
2869
2870 /**
2871  * _pmcraid_io_done - helper for pmcraid_io_done function
2872  *
2873  * @cmd: pointer to pmcraid command struct
2874  * @reslen: residual data length to be set in the ioasa
2875  * @ioasc: ioasc either returned by IOA or set by driver itself.
2876  *
2877  * This function is invoked by pmcraid_io_done to complete mid-layer
2878  * scsi ops.
2879  *
2880  * Return value:
2881  *        0 if caller is required to return it to free_pool. Returns 1 if
2882  *        caller need not worry about freeing command block as error handler
2883  *        will take care of that.
2884  */
2885
2886 static int _pmcraid_io_done(struct pmcraid_cmd *cmd, int reslen, int ioasc)
2887 {
2888         struct scsi_cmnd *scsi_cmd = cmd->scsi_cmd;
2889         int rc = 0;
2890
2891         scsi_set_resid(scsi_cmd, reslen);
2892
2893         pmcraid_info("response(%d) CDB[0] = %x ioasc:result: %x:%x\n",
2894                 le32_to_cpu(cmd->ioa_cb->ioarcb.response_handle) >> 2,
2895                 cmd->ioa_cb->ioarcb.cdb[0],
2896                 ioasc, scsi_cmd->result);
2897
2898         if (PMCRAID_IOASC_SENSE_KEY(ioasc) != 0)
2899                 rc = pmcraid_error_handler(cmd);
2900
2901         if (rc == 0) {
2902                 scsi_dma_unmap(scsi_cmd);
2903                 scsi_cmd->scsi_done(scsi_cmd);
2904         }
2905
2906         return rc;
2907 }
2908
2909 /**
2910  * pmcraid_io_done - SCSI completion function
2911  *
2912  * @cmd: pointer to pmcraid command struct
2913  *
2914  * This function is invoked by tasklet/mid-layer error handler to completing
2915  * the SCSI ops sent from mid-layer.
2916  *
2917  * Return value
2918  *        none
2919  */
2920
2921 static void pmcraid_io_done(struct pmcraid_cmd *cmd)
2922 {
2923         u32 ioasc = le32_to_cpu(cmd->ioa_cb->ioasa.ioasc);
2924         u32 reslen = le32_to_cpu(cmd->ioa_cb->ioasa.residual_data_length);
2925
2926         if (_pmcraid_io_done(cmd, reslen, ioasc) == 0)
2927                 pmcraid_return_cmd(cmd);
2928 }
2929
2930 /**
2931  * pmcraid_abort_cmd - Aborts a single IOARCB already submitted to IOA
2932  *
2933  * @cmd: command block of the command to be aborted
2934  *
2935  * Return Value:
2936  *       returns pointer to command structure used as cancelling cmd
2937  */
2938 static struct pmcraid_cmd *pmcraid_abort_cmd(struct pmcraid_cmd *cmd)
2939 {
2940         struct pmcraid_cmd *cancel_cmd;
2941         struct pmcraid_instance *pinstance;
2942         struct pmcraid_resource_entry *res;
2943
2944         pinstance = (struct pmcraid_instance *)cmd->drv_inst;
2945         res = cmd->scsi_cmd->device->hostdata;
2946
2947         cancel_cmd = pmcraid_get_free_cmd(pinstance);
2948
2949         if (cancel_cmd == NULL) {
2950                 pmcraid_err("%s: no cmd blocks are available\n", __func__);
2951                 return NULL;
2952         }
2953
2954         pmcraid_prepare_cancel_cmd(cancel_cmd, cmd);
2955
2956         pmcraid_info("aborting command CDB[0]= %x with index = %d\n",
2957                 cmd->ioa_cb->ioarcb.cdb[0],
2958                 cmd->ioa_cb->ioarcb.response_handle >> 2);
2959
2960         init_completion(&cancel_cmd->wait_for_completion);
2961         cancel_cmd->completion_req = 1;
2962
2963         pmcraid_info("command (%d) CDB[0] = %x for %x\n",
2964                 le32_to_cpu(cancel_cmd->ioa_cb->ioarcb.response_handle) >> 2,
2965                 cancel_cmd->ioa_cb->ioarcb.cdb[0],
2966                 le32_to_cpu(cancel_cmd->ioa_cb->ioarcb.resource_handle));
2967
2968         pmcraid_send_cmd(cancel_cmd,
2969                          pmcraid_internal_done,
2970                          PMCRAID_INTERNAL_TIMEOUT,
2971                          pmcraid_timeout_handler);
2972         return cancel_cmd;
2973 }
2974
2975 /**
2976  * pmcraid_abort_complete - Waits for ABORT TASK completion
2977  *
2978  * @cancel_cmd: command block use as cancelling command
2979  *
2980  * Return Value:
2981  *       returns SUCCESS if ABORT TASK has good completion
2982  *       otherwise FAILED
2983  */
2984 static int pmcraid_abort_complete(struct pmcraid_cmd *cancel_cmd)
2985 {
2986         struct pmcraid_resource_entry *res;
2987         u32 ioasc;
2988
2989         wait_for_completion(&cancel_cmd->wait_for_completion);
2990         res = cancel_cmd->res;
2991         cancel_cmd->res = NULL;
2992         ioasc = le32_to_cpu(cancel_cmd->ioa_cb->ioasa.ioasc);
2993
2994         /* If the abort task is not timed out we will get a Good completion
2995          * as sense_key, otherwise we may get one the following responses
2996          * due to subsequent bus reset or device reset. In case IOASC is
2997          * NR_SYNC_REQUIRED, set sync_reqd flag for the corresponding resource
2998          */
2999         if (ioasc == PMCRAID_IOASC_UA_BUS_WAS_RESET ||
3000             ioasc == PMCRAID_IOASC_NR_SYNC_REQUIRED) {
3001                 if (ioasc == PMCRAID_IOASC_NR_SYNC_REQUIRED)
3002                         res->sync_reqd = 1;
3003                 ioasc = 0;
3004         }
3005
3006         /* complete the command here itself */
3007         pmcraid_return_cmd(cancel_cmd);
3008         return PMCRAID_IOASC_SENSE_KEY(ioasc) ? FAILED : SUCCESS;
3009 }
3010
3011 /**
3012  * pmcraid_eh_abort_handler - entry point for aborting a single task on errors
3013  *
3014  * @scsi_cmd:   scsi command struct given by mid-layer. When this is called
3015  *              mid-layer ensures that no other commands are queued. This
3016  *              never gets called under interrupt, but a separate eh thread.
3017  *
3018  * Return value:
3019  *       SUCCESS / FAILED
3020  */
3021 static int pmcraid_eh_abort_handler(struct scsi_cmnd *scsi_cmd)
3022 {
3023         struct pmcraid_instance *pinstance;
3024         struct pmcraid_cmd *cmd;
3025         struct pmcraid_resource_entry *res;
3026         unsigned long host_lock_flags;
3027         unsigned long pending_lock_flags;
3028         struct pmcraid_cmd *cancel_cmd = NULL;
3029         int cmd_found = 0;
3030         int rc = FAILED;
3031
3032         pinstance =
3033                 (struct pmcraid_instance *)scsi_cmd->device->host->hostdata;
3034
3035         scmd_printk(KERN_INFO, scsi_cmd,
3036                     "I/O command timed out, aborting it.\n");
3037
3038         res = scsi_cmd->device->hostdata;
3039
3040         if (res == NULL)
3041                 return rc;
3042
3043         /* If we are currently going through reset/reload, return failed.
3044          * This will force the mid-layer to eventually call
3045          * pmcraid_eh_host_reset which will then go to sleep and wait for the
3046          * reset to complete
3047          */
3048         spin_lock_irqsave(pinstance->host->host_lock, host_lock_flags);
3049
3050         if (pinstance->ioa_reset_in_progress ||
3051             pinstance->ioa_state == IOA_STATE_DEAD) {
3052                 spin_unlock_irqrestore(pinstance->host->host_lock,
3053                                        host_lock_flags);
3054                 return rc;
3055         }
3056
3057         /* loop over pending cmd list to find cmd corresponding to this
3058          * scsi_cmd. Note that this command might not have been completed
3059          * already. locking: all pending commands are protected with
3060          * pending_pool_lock.
3061          */
3062         spin_lock_irqsave(&pinstance->pending_pool_lock, pending_lock_flags);
3063         list_for_each_entry(cmd, &pinstance->pending_cmd_pool, free_list) {
3064
3065                 if (cmd->scsi_cmd == scsi_cmd) {
3066                         cmd_found = 1;
3067                         break;
3068                 }
3069         }
3070
3071         spin_unlock_irqrestore(&pinstance->pending_pool_lock,
3072                                 pending_lock_flags);
3073
3074         /* If the command to be aborted was given to IOA and still pending with
3075          * it, send ABORT_TASK to abort this and wait for its completion
3076          */
3077         if (cmd_found)
3078                 cancel_cmd = pmcraid_abort_cmd(cmd);
3079
3080         spin_unlock_irqrestore(pinstance->host->host_lock,
3081                                host_lock_flags);
3082
3083         if (cancel_cmd) {
3084                 cancel_cmd->res = cmd->scsi_cmd->device->hostdata;
3085                 rc = pmcraid_abort_complete(cancel_cmd);
3086         }
3087
3088         return cmd_found ? rc : SUCCESS;
3089 }
3090
3091 /**
3092  * pmcraid_eh_xxxx_reset_handler - bus/target/device reset handler callbacks
3093  *
3094  * @scmd: pointer to scsi_cmd that was sent to the resource to be reset.
3095  *
3096  * All these routines invokve pmcraid_reset_device with appropriate parameters.
3097  * Since these are called from mid-layer EH thread, no other IO will be queued
3098  * to the resource being reset. However, control path (IOCTL) may be active so
3099  * it is necessary to synchronize IOARRIN writes which pmcraid_reset_device
3100  * takes care by locking/unlocking host_lock.
3101  *
3102  * Return value
3103  *      SUCCESS or FAILED
3104  */
3105 static int pmcraid_eh_device_reset_handler(struct scsi_cmnd *scmd)
3106 {
3107         scmd_printk(KERN_INFO, scmd,
3108                     "resetting device due to an I/O command timeout.\n");
3109         return pmcraid_reset_device(scmd,
3110                                     PMCRAID_INTERNAL_TIMEOUT,
3111                                     RESET_DEVICE_LUN);
3112 }
3113
3114 static int pmcraid_eh_bus_reset_handler(struct scsi_cmnd *scmd)
3115 {
3116         scmd_printk(KERN_INFO, scmd,
3117                     "Doing bus reset due to an I/O command timeout.\n");
3118         return pmcraid_reset_device(scmd,
3119                                     PMCRAID_RESET_BUS_TIMEOUT,
3120                                     RESET_DEVICE_BUS);
3121 }
3122
3123 static int pmcraid_eh_target_reset_handler(struct scsi_cmnd *scmd)
3124 {
3125         scmd_printk(KERN_INFO, scmd,
3126                     "Doing target reset due to an I/O command timeout.\n");
3127         return pmcraid_reset_device(scmd,
3128                                     PMCRAID_INTERNAL_TIMEOUT,
3129                                     RESET_DEVICE_TARGET);
3130 }
3131
3132 /**
3133  * pmcraid_eh_host_reset_handler - adapter reset handler callback
3134  *
3135  * @scmd: pointer to scsi_cmd that was sent to a resource of adapter
3136  *
3137  * Initiates adapter reset to bring it up to operational state
3138  *
3139  * Return value
3140  *      SUCCESS or FAILED
3141  */
3142 static int pmcraid_eh_host_reset_handler(struct scsi_cmnd *scmd)
3143 {
3144         unsigned long interval = 10000; /* 10 seconds interval */
3145         int waits = jiffies_to_msecs(PMCRAID_RESET_HOST_TIMEOUT) / interval;
3146         struct pmcraid_instance *pinstance =
3147                 (struct pmcraid_instance *)(scmd->device->host->hostdata);
3148
3149
3150         /* wait for an additional 150 seconds just in case firmware could come
3151          * up and if it could complete all the pending commands excluding the
3152          * two HCAM (CCN and LDN).
3153          */
3154         while (waits--) {
3155                 if (atomic_read(&pinstance->outstanding_cmds) <=
3156                     PMCRAID_MAX_HCAM_CMD)
3157                         return SUCCESS;
3158                 msleep(interval);
3159         }
3160
3161         dev_err(&pinstance->pdev->dev,
3162                 "Adapter being reset due to an I/O command timeout.\n");
3163         return pmcraid_reset_bringup(pinstance) == 0 ? SUCCESS : FAILED;
3164 }
3165
3166 /**
3167  * pmcraid_task_attributes - Translate SPI Q-Tags to task attributes
3168  * @scsi_cmd:   scsi command struct
3169  *
3170  * Return value
3171  *        number of tags or 0 if the task is not tagged
3172  */
3173 static u8 pmcraid_task_attributes(struct scsi_cmnd *scsi_cmd)
3174 {
3175         char tag[2];
3176         u8 rc = 0;
3177
3178         if (scsi_populate_tag_msg(scsi_cmd, tag)) {
3179                 switch (tag[0]) {
3180                 case MSG_SIMPLE_TAG:
3181                         rc = TASK_TAG_SIMPLE;
3182                         break;
3183                 case MSG_HEAD_TAG:
3184                         rc = TASK_TAG_QUEUE_HEAD;
3185                         break;
3186                 case MSG_ORDERED_TAG:
3187                         rc = TASK_TAG_ORDERED;
3188                         break;
3189                 };
3190         }
3191
3192         return rc;
3193 }
3194
3195
3196 /**
3197  * pmcraid_init_ioadls - initializes IOADL related fields in IOARCB
3198  * @cmd: pmcraid command struct
3199  * @sgcount: count of scatter-gather elements
3200  *
3201  * Return value
3202  *   returns pointer pmcraid_ioadl_desc, initialized to point to internal
3203  *   or external IOADLs
3204  */
3205 struct pmcraid_ioadl_desc *
3206 pmcraid_init_ioadls(struct pmcraid_cmd *cmd, int sgcount)
3207 {
3208         struct pmcraid_ioadl_desc *ioadl;
3209         struct pmcraid_ioarcb *ioarcb = &cmd->ioa_cb->ioarcb;
3210         int ioadl_count = 0;
3211
3212         if (ioarcb->add_cmd_param_length)
3213                 ioadl_count = DIV_ROUND_UP(ioarcb->add_cmd_param_length, 16);
3214         ioarcb->ioadl_length =
3215                 sizeof(struct pmcraid_ioadl_desc) * sgcount;
3216
3217         if ((sgcount + ioadl_count) > (ARRAY_SIZE(ioarcb->add_data.u.ioadl))) {
3218                 /* external ioadls start at offset 0x80 from control_block
3219                  * structure, re-using 24 out of 27 ioadls part of IOARCB.
3220                  * It is necessary to indicate to firmware that driver is
3221                  * using ioadls to be treated as external to IOARCB.
3222                  */
3223                 ioarcb->ioarcb_bus_addr &= ~(0x1FULL);
3224                 ioarcb->ioadl_bus_addr =
3225                         cpu_to_le64((cmd->ioa_cb_bus_addr) +
3226                                 offsetof(struct pmcraid_ioarcb,
3227                                         add_data.u.ioadl[3]));
3228                 ioadl = &ioarcb->add_data.u.ioadl[3];
3229         } else {
3230                 ioarcb->ioadl_bus_addr =
3231                         cpu_to_le64((cmd->ioa_cb_bus_addr) +
3232                                 offsetof(struct pmcraid_ioarcb,
3233                                         add_data.u.ioadl[ioadl_count]));
3234
3235                 ioadl = &ioarcb->add_data.u.ioadl[ioadl_count];
3236                 ioarcb->ioarcb_bus_addr |=
3237                                 DIV_ROUND_CLOSEST(sgcount + ioadl_count, 8);
3238         }
3239
3240         return ioadl;
3241 }
3242
3243 /**
3244  * pmcraid_build_ioadl - Build a scatter/gather list and map the buffer
3245  * @pinstance: pointer to adapter instance structure
3246  * @cmd: pmcraid command struct
3247  *
3248  * This function is invoked by queuecommand entry point while sending a command
3249  * to firmware. This builds ioadl descriptors and sets up ioarcb fields.
3250  *
3251  * Return value:
3252  *      0 on success or -1 on failure
3253  */
3254 static int pmcraid_build_ioadl(
3255         struct pmcraid_instance *pinstance,
3256         struct pmcraid_cmd *cmd
3257 )
3258 {
3259         int i, nseg;
3260         struct scatterlist *sglist;
3261
3262         struct scsi_cmnd *scsi_cmd = cmd->scsi_cmd;
3263         struct pmcraid_ioarcb *ioarcb = &(cmd->ioa_cb->ioarcb);
3264         struct pmcraid_ioadl_desc *ioadl = ioarcb->add_data.u.ioadl;
3265
3266         u32 length = scsi_bufflen(scsi_cmd);
3267
3268         if (!length)
3269                 return 0;
3270
3271         nseg = scsi_dma_map(scsi_cmd);
3272
3273         if (nseg < 0) {
3274                 scmd_printk(KERN_ERR, scsi_cmd, "scsi_map_dma failed!\n");
3275                 return -1;
3276         } else if (nseg > PMCRAID_MAX_IOADLS) {
3277                 scsi_dma_unmap(scsi_cmd);
3278                 scmd_printk(KERN_ERR, scsi_cmd,
3279                         "sg count is (%d) more than allowed!\n", nseg);
3280                 return -1;
3281         }
3282
3283         /* Initialize IOARCB data transfer length fields */
3284         if (scsi_cmd->sc_data_direction == DMA_TO_DEVICE)
3285                 ioarcb->request_flags0 |= TRANSFER_DIR_WRITE;
3286
3287         ioarcb->request_flags0 |= NO_LINK_DESCS;
3288         ioarcb->data_transfer_length = cpu_to_le32(length);
3289         ioadl = pmcraid_init_ioadls(cmd, nseg);
3290
3291         /* Initialize IOADL descriptor addresses */
3292         scsi_for_each_sg(scsi_cmd, sglist, nseg, i) {
3293                 ioadl[i].data_len = cpu_to_le32(sg_dma_len(sglist));
3294                 ioadl[i].address = cpu_to_le64(sg_dma_address(sglist));
3295                 ioadl[i].flags = 0;
3296         }
3297         /* setup last descriptor */
3298         ioadl[i - 1].flags = IOADL_FLAGS_LAST_DESC;
3299
3300         return 0;
3301 }
3302
3303 /**
3304  * pmcraid_free_sglist - Frees an allocated SG buffer list
3305  * @sglist: scatter/gather list pointer
3306  *
3307  * Free a DMA'able memory previously allocated with pmcraid_alloc_sglist
3308  *
3309  * Return value:
3310  *      none
3311  */
3312 static void pmcraid_free_sglist(struct pmcraid_sglist *sglist)
3313 {
3314         int i;
3315
3316         for (i = 0; i < sglist->num_sg; i++)
3317                 __free_pages(sg_page(&(sglist->scatterlist[i])),
3318                              sglist->order);
3319
3320         kfree(sglist);
3321 }
3322
3323 /**
3324  * pmcraid_alloc_sglist - Allocates memory for a SG list
3325  * @buflen: buffer length
3326  *
3327  * Allocates a DMA'able buffer in chunks and assembles a scatter/gather
3328  * list.
3329  *
3330  * Return value
3331  *      pointer to sglist / NULL on failure
3332  */
3333 static struct pmcraid_sglist *pmcraid_alloc_sglist(int buflen)
3334 {
3335         struct pmcraid_sglist *sglist;
3336         struct scatterlist *scatterlist;
3337         struct page *page;
3338         int num_elem, i, j;
3339         int sg_size;
3340         int order;
3341         int bsize_elem;
3342
3343         sg_size = buflen / (PMCRAID_MAX_IOADLS - 1);
3344         order = (sg_size > 0) ? get_order(sg_size) : 0;
3345         bsize_elem = PAGE_SIZE * (1 << order);
3346
3347         /* Determine the actual number of sg entries needed */
3348         if (buflen % bsize_elem)
3349                 num_elem = (buflen / bsize_elem) + 1;
3350         else
3351                 num_elem = buflen / bsize_elem;
3352
3353         /* Allocate a scatter/gather list for the DMA */
3354         sglist = kzalloc(sizeof(struct pmcraid_sglist) +
3355                          (sizeof(struct scatterlist) * (num_elem - 1)),
3356                          GFP_KERNEL);
3357
3358         if (sglist == NULL)
3359                 return NULL;
3360
3361         scatterlist = sglist->scatterlist;
3362         sg_init_table(scatterlist, num_elem);
3363         sglist->order = order;
3364         sglist->num_sg = num_elem;
3365         sg_size = buflen;
3366
3367         for (i = 0; i < num_elem; i++) {
3368                 page = alloc_pages(GFP_KERNEL|GFP_DMA|__GFP_ZERO, order);
3369                 if (!page) {
3370                         for (j = i - 1; j >= 0; j--)
3371                                 __free_pages(sg_page(&scatterlist[j]), order);
3372                         kfree(sglist);
3373                         return NULL;
3374                 }
3375
3376                 sg_set_page(&scatterlist[i], page,
3377                         sg_size < bsize_elem ? sg_size : bsize_elem, 0);
3378                 sg_size -= bsize_elem;
3379         }
3380
3381         return sglist;
3382 }
3383
3384 /**
3385  * pmcraid_copy_sglist - Copy user buffer to kernel buffer's SG list
3386  * @sglist: scatter/gather list pointer
3387  * @buffer: buffer pointer
3388  * @len: buffer length
3389  * @direction: data transfer direction
3390  *
3391  * Copy a user buffer into a buffer allocated by pmcraid_alloc_sglist
3392  *
3393  * Return value:
3394  * 0 on success / other on failure
3395  */
3396 static int pmcraid_copy_sglist(
3397         struct pmcraid_sglist *sglist,
3398         unsigned long buffer,
3399         u32 len,
3400         int direction
3401 )
3402 {
3403         struct scatterlist *scatterlist;
3404         void *kaddr;
3405         int bsize_elem;
3406         int i;
3407         int rc = 0;
3408
3409         /* Determine the actual number of bytes per element */
3410         bsize_elem = PAGE_SIZE * (1 << sglist->order);
3411
3412         scatterlist = sglist->scatterlist;
3413
3414         for (i = 0; i < (len / bsize_elem); i++, buffer += bsize_elem) {
3415                 struct page *page = sg_page(&scatterlist[i]);
3416
3417                 kaddr = kmap(page);
3418                 if (direction == DMA_TO_DEVICE)
3419                         rc = __copy_from_user(kaddr,
3420                                               (void *)buffer,
3421                                               bsize_elem);
3422                 else
3423                         rc = __copy_to_user((void *)buffer, kaddr, bsize_elem);
3424
3425                 kunmap(page);
3426
3427                 if (rc) {
3428                         pmcraid_err("failed to copy user data into sg list\n");
3429                         return -EFAULT;
3430                 }
3431
3432                 scatterlist[i].length = bsize_elem;
3433         }
3434
3435         if (len % bsize_elem) {
3436                 struct page *page = sg_page(&scatterlist[i]);
3437
3438                 kaddr = kmap(page);
3439
3440                 if (direction == DMA_TO_DEVICE)
3441                         rc = __copy_from_user(kaddr,
3442                                               (void *)buffer,
3443                                               len % bsize_elem);
3444                 else
3445                         rc = __copy_to_user((void *)buffer,
3446                                             kaddr,
3447                                             len % bsize_elem);
3448
3449                 kunmap(page);
3450
3451                 scatterlist[i].length = len % bsize_elem;
3452         }
3453
3454         if (rc) {
3455                 pmcraid_err("failed to copy user data into sg list\n");
3456                 rc = -EFAULT;
3457         }
3458
3459         return rc;
3460 }
3461
3462 /**
3463  * pmcraid_queuecommand - Queue a mid-layer request
3464  * @scsi_cmd: scsi command struct
3465  * @done: done function
3466  *
3467  * This function queues a request generated by the mid-layer. Midlayer calls
3468  * this routine within host->lock. Some of the functions called by queuecommand
3469  * would use cmd block queue locks (free_pool_lock and pending_pool_lock)
3470  *
3471  * Return value:
3472  *        0 on success
3473  *        SCSI_MLQUEUE_DEVICE_BUSY if device is busy
3474  *        SCSI_MLQUEUE_HOST_BUSY if host is busy
3475  */
3476 static int pmcraid_queuecommand_lck(
3477         struct scsi_cmnd *scsi_cmd,
3478         void (*done) (struct scsi_cmnd *)
3479 )
3480 {
3481         struct pmcraid_instance *pinstance;
3482         struct pmcraid_resource_entry *res;
3483         struct pmcraid_ioarcb *ioarcb;
3484         struct pmcraid_cmd *cmd;
3485         u32 fw_version;
3486         int rc = 0;
3487
3488         pinstance =
3489                 (struct pmcraid_instance *)scsi_cmd->device->host->hostdata;
3490         fw_version = be16_to_cpu(pinstance->inq_data->fw_version);
3491         scsi_cmd->scsi_done = done;
3492         res = scsi_cmd->device->hostdata;
3493         scsi_cmd->result = (DID_OK << 16);
3494
3495         /* if adapter is marked as dead, set result to DID_NO_CONNECT complete
3496          * the command
3497          */
3498         if (pinstance->ioa_state == IOA_STATE_DEAD) {
3499                 pmcraid_info("IOA is dead, but queuecommand is scheduled\n");
3500                 scsi_cmd->result = (DID_NO_CONNECT << 16);
3501                 scsi_cmd->scsi_done(scsi_cmd);
3502                 return 0;
3503         }
3504
3505         /* If IOA reset is in progress, can't queue the commands */
3506         if (pinstance->ioa_reset_in_progress)
3507                 return SCSI_MLQUEUE_HOST_BUSY;
3508
3509         /* Firmware doesn't support SYNCHRONIZE_CACHE command (0x35), complete
3510          * the command here itself with success return
3511          */
3512         if (scsi_cmd->cmnd[0] == SYNCHRONIZE_CACHE) {
3513                 pmcraid_info("SYNC_CACHE(0x35), completing in driver itself\n");
3514                 scsi_cmd->scsi_done(scsi_cmd);
3515                 return 0;
3516         }
3517
3518         /* initialize the command and IOARCB to be sent to IOA */
3519         cmd = pmcraid_get_free_cmd(pinstance);
3520
3521         if (cmd == NULL) {
3522                 pmcraid_err("free command block is not available\n");
3523                 return SCSI_MLQUEUE_HOST_BUSY;
3524         }
3525
3526         cmd->scsi_cmd = scsi_cmd;
3527         ioarcb = &(cmd->ioa_cb->ioarcb);
3528         memcpy(ioarcb->cdb, scsi_cmd->cmnd, scsi_cmd->cmd_len);
3529         ioarcb->resource_handle = res->cfg_entry.resource_handle;
3530         ioarcb->request_type = REQ_TYPE_SCSI;
3531
3532         /* set hrrq number where the IOA should respond to. Note that all cmds
3533          * generated internally uses hrrq_id 0, exception to this is the cmd
3534          * block of scsi_cmd which is re-used (e.g. cancel/abort), which uses
3535          * hrrq_id assigned here in queuecommand
3536          */
3537         ioarcb->hrrq_id = atomic_add_return(1, &(pinstance->last_message_id)) %
3538                           pinstance->num_hrrq;
3539         cmd->cmd_done = pmcraid_io_done;
3540
3541         if (RES_IS_GSCSI(res->cfg_entry) || RES_IS_VSET(res->cfg_entry)) {
3542                 if (scsi_cmd->underflow == 0)
3543                         ioarcb->request_flags0 |= INHIBIT_UL_CHECK;
3544
3545                 if (res->sync_reqd) {
3546                         ioarcb->request_flags0 |= SYNC_COMPLETE;
3547                         res->sync_reqd = 0;
3548                 }
3549
3550                 ioarcb->request_flags0 |= NO_LINK_DESCS;
3551                 ioarcb->request_flags1 |= pmcraid_task_attributes(scsi_cmd);
3552
3553                 if (RES_IS_GSCSI(res->cfg_entry))
3554                         ioarcb->request_flags1 |= DELAY_AFTER_RESET;
3555         }
3556
3557         rc = pmcraid_build_ioadl(pinstance, cmd);
3558
3559         pmcraid_info("command (%d) CDB[0] = %x for %x:%x:%x:%x\n",
3560                      le32_to_cpu(ioarcb->response_handle) >> 2,
3561                      scsi_cmd->cmnd[0], pinstance->host->unique_id,
3562                      RES_IS_VSET(res->cfg_entry) ? PMCRAID_VSET_BUS_ID :
3563                         PMCRAID_PHYS_BUS_ID,
3564                      RES_IS_VSET(res->cfg_entry) ?
3565                         (fw_version <= PMCRAID_FW_VERSION_1 ?
3566                                 res->cfg_entry.unique_flags1 :
3567                                         res->cfg_entry.array_id & 0xFF) :
3568                         RES_TARGET(res->cfg_entry.resource_address),
3569                      RES_LUN(res->cfg_entry.resource_address));
3570
3571         if (likely(rc == 0)) {
3572                 _pmcraid_fire_command(cmd);
3573         } else {
3574                 pmcraid_err("queuecommand could not build ioadl\n");
3575                 pmcraid_return_cmd(cmd);
3576                 rc = SCSI_MLQUEUE_HOST_BUSY;
3577         }
3578
3579         return rc;
3580 }
3581
3582 static DEF_SCSI_QCMD(pmcraid_queuecommand)
3583
3584 /**
3585  * pmcraid_open -char node "open" entry, allowed only users with admin access
3586  */
3587 static int pmcraid_chr_open(struct inode *inode, struct file *filep)
3588 {
3589         struct pmcraid_instance *pinstance;
3590
3591         if (!capable(CAP_SYS_ADMIN))
3592                 return -EACCES;
3593
3594         /* Populate adapter instance * pointer for use by ioctl */
3595         pinstance = container_of(inode->i_cdev, struct pmcraid_instance, cdev);
3596         filep->private_data = pinstance;
3597
3598         return 0;
3599 }
3600
3601 /**
3602  * pmcraid_release - char node "release" entry point
3603  */
3604 static int pmcraid_chr_release(struct inode *inode, struct file *filep)
3605 {
3606         struct pmcraid_instance *pinstance = filep->private_data;
3607
3608         filep->private_data = NULL;
3609         fasync_helper(-1, filep, 0, &pinstance->aen_queue);
3610
3611         return 0;
3612 }
3613
3614 /**
3615  * pmcraid_fasync - Async notifier registration from applications
3616  *
3617  * This function adds the calling process to a driver global queue. When an
3618  * event occurs, SIGIO will be sent to all processes in this queue.
3619  */
3620 static int pmcraid_chr_fasync(int fd, struct file *filep, int mode)
3621 {
3622         struct pmcraid_instance *pinstance;
3623         int rc;
3624
3625         pinstance = filep->private_data;
3626         mutex_lock(&pinstance->aen_queue_lock);
3627         rc = fasync_helper(fd, filep, mode, &pinstance->aen_queue);
3628         mutex_unlock(&pinstance->aen_queue_lock);
3629
3630         return rc;
3631 }
3632
3633
3634 /**
3635  * pmcraid_build_passthrough_ioadls - builds SG elements for passthrough
3636  * commands sent over IOCTL interface
3637  *
3638  * @cmd       : pointer to struct pmcraid_cmd
3639  * @buflen    : length of the request buffer
3640  * @direction : data transfer direction
3641  *
3642  * Return value
3643  *  0 on success, non-zero error code on failure
3644  */
3645 static int pmcraid_build_passthrough_ioadls(
3646         struct pmcraid_cmd *cmd,
3647         int buflen,
3648         int direction
3649 )
3650 {
3651         struct pmcraid_sglist *sglist = NULL;
3652         struct scatterlist *sg = NULL;
3653         struct pmcraid_ioarcb *ioarcb = &cmd->ioa_cb->ioarcb;
3654         struct pmcraid_ioadl_desc *ioadl;
3655         int i;
3656
3657         sglist = pmcraid_alloc_sglist(buflen);
3658
3659         if (!sglist) {
3660                 pmcraid_err("can't allocate memory for passthrough SGls\n");
3661                 return -ENOMEM;
3662         }
3663
3664         sglist->num_dma_sg = pci_map_sg(cmd->drv_inst->pdev,
3665                                         sglist->scatterlist,
3666                                         sglist->num_sg, direction);
3667
3668         if (!sglist->num_dma_sg || sglist->num_dma_sg > PMCRAID_MAX_IOADLS) {
3669                 dev_err(&cmd->drv_inst->pdev->dev,
3670                         "Failed to map passthrough buffer!\n");
3671                 pmcraid_free_sglist(sglist);
3672                 return -EIO;
3673         }
3674
3675         cmd->sglist = sglist;
3676         ioarcb->request_flags0 |= NO_LINK_DESCS;
3677
3678         ioadl = pmcraid_init_ioadls(cmd, sglist->num_dma_sg);
3679
3680         /* Initialize IOADL descriptor addresses */
3681         for_each_sg(sglist->scatterlist, sg, sglist->num_dma_sg, i) {
3682                 ioadl[i].data_len = cpu_to_le32(sg_dma_len(sg));
3683                 ioadl[i].address = cpu_to_le64(sg_dma_address(sg));
3684                 ioadl[i].flags = 0;
3685         }
3686
3687         /* setup the last descriptor */
3688         ioadl[i - 1].flags = IOADL_FLAGS_LAST_DESC;
3689
3690         return 0;
3691 }
3692
3693
3694 /**
3695  * pmcraid_release_passthrough_ioadls - release passthrough ioadls
3696  *
3697  * @cmd: pointer to struct pmcraid_cmd for which ioadls were allocated
3698  * @buflen: size of the request buffer
3699  * @direction: data transfer direction
3700  *
3701  * Return value
3702  *  0 on success, non-zero error code on failure
3703  */
3704 static void pmcraid_release_passthrough_ioadls(
3705         struct pmcraid_cmd *cmd,
3706         int buflen,
3707         int direction
3708 )
3709 {
3710         struct pmcraid_sglist *sglist = cmd->sglist;
3711
3712         if (buflen > 0) {
3713                 pci_unmap_sg(cmd->drv_inst->pdev,
3714                              sglist->scatterlist,
3715                              sglist->num_sg,
3716                              direction);
3717                 pmcraid_free_sglist(sglist);
3718                 cmd->sglist = NULL;
3719         }
3720 }
3721
3722 /**
3723  * pmcraid_ioctl_passthrough - handling passthrough IOCTL commands
3724  *
3725  * @pinstance: pointer to adapter instance structure
3726  * @cmd: ioctl code
3727  * @arg: pointer to pmcraid_passthrough_buffer user buffer
3728  *
3729  * Return value
3730  *  0 on success, non-zero error code on failure
3731  */
3732 static long pmcraid_ioctl_passthrough(
3733         struct pmcraid_instance *pinstance,
3734         unsigned int ioctl_cmd,
3735         unsigned int buflen,
3736         unsigned long arg
3737 )
3738 {
3739         struct pmcraid_passthrough_ioctl_buffer *buffer;
3740         struct pmcraid_ioarcb *ioarcb;
3741         struct pmcraid_cmd *cmd;
3742         struct pmcraid_cmd *cancel_cmd;
3743         unsigned long request_buffer;
3744         unsigned long request_offset;
3745         unsigned long lock_flags;
3746         void *ioasa;
3747         u32 ioasc;
3748         int request_size;
3749         int buffer_size;
3750         u8 access, direction;
3751         int rc = 0;
3752
3753         /* If IOA reset is in progress, wait 10 secs for reset to complete */
3754         if (pinstance->ioa_reset_in_progress) {
3755                 rc = wait_event_interruptible_timeout(
3756                                 pinstance->reset_wait_q,
3757                                 !pinstance->ioa_reset_in_progress,
3758                                 msecs_to_jiffies(10000));
3759
3760                 if (!rc)
3761                         return -ETIMEDOUT;
3762                 else if (rc < 0)
3763                         return -ERESTARTSYS;
3764         }
3765
3766         /* If adapter is not in operational state, return error */
3767         if (pinstance->ioa_state != IOA_STATE_OPERATIONAL) {
3768                 pmcraid_err("IOA is not operational\n");
3769                 return -ENOTTY;
3770         }
3771
3772         buffer_size = sizeof(struct pmcraid_passthrough_ioctl_buffer);
3773         buffer = kmalloc(buffer_size, GFP_KERNEL);
3774
3775         if (!buffer) {
3776                 pmcraid_err("no memory for passthrough buffer\n");
3777                 return -ENOMEM;
3778         }
3779
3780         request_offset =
3781             offsetof(struct pmcraid_passthrough_ioctl_buffer, request_buffer);
3782
3783         request_buffer = arg + request_offset;
3784
3785         rc = __copy_from_user(buffer,
3786                              (struct pmcraid_passthrough_ioctl_buffer *) arg,
3787                              sizeof(struct pmcraid_passthrough_ioctl_buffer));
3788
3789         ioasa =
3790         (void *)(arg +
3791                 offsetof(struct pmcraid_passthrough_ioctl_buffer, ioasa));
3792
3793         if (rc) {
3794                 pmcraid_err("ioctl: can't copy passthrough buffer\n");
3795                 rc = -EFAULT;
3796                 goto out_free_buffer;
3797         }
3798
3799         request_size = buffer->ioarcb.data_transfer_length;
3800
3801         if (buffer->ioarcb.request_flags0 & TRANSFER_DIR_WRITE) {
3802                 access = VERIFY_READ;
3803                 direction = DMA_TO_DEVICE;
3804         } else {
3805                 access = VERIFY_WRITE;
3806                 direction = DMA_FROM_DEVICE;
3807         }
3808
3809         if (request_size > 0) {
3810                 rc = access_ok(access, arg, request_offset + request_size);
3811
3812                 if (!rc) {
3813                         rc = -EFAULT;
3814                         goto out_free_buffer;
3815                 }
3816         } else if (request_size < 0) {
3817                 rc = -EINVAL;
3818                 goto out_free_buffer;
3819         }
3820
3821         /* check if we have any additional command parameters */
3822         if (buffer->ioarcb.add_cmd_param_length > PMCRAID_ADD_CMD_PARAM_LEN) {
3823                 rc = -EINVAL;
3824                 goto out_free_buffer;
3825         }
3826
3827         cmd = pmcraid_get_free_cmd(pinstance);
3828
3829         if (!cmd) {
3830                 pmcraid_err("free command block is not available\n");
3831                 rc = -ENOMEM;
3832                 goto out_free_buffer;
3833         }
3834
3835         cmd->scsi_cmd = NULL;
3836         ioarcb = &(cmd->ioa_cb->ioarcb);
3837
3838         /* Copy the user-provided IOARCB stuff field by field */
3839         ioarcb->resource_handle = buffer->ioarcb.resource_handle;
3840         ioarcb->data_transfer_length = buffer->ioarcb.data_transfer_length;
3841         ioarcb->cmd_timeout = buffer->ioarcb.cmd_timeout;
3842         ioarcb->request_type = buffer->ioarcb.request_type;
3843         ioarcb->request_flags0 = buffer->ioarcb.request_flags0;
3844         ioarcb->request_flags1 = buffer->ioarcb.request_flags1;
3845         memcpy(ioarcb->cdb, buffer->ioarcb.cdb, PMCRAID_MAX_CDB_LEN);
3846
3847         if (buffer->ioarcb.add_cmd_param_length) {
3848                 ioarcb->add_cmd_param_length =
3849                         buffer->ioarcb.add_cmd_param_length;
3850                 ioarcb->add_cmd_param_offset =
3851                         buffer->ioarcb.add_cmd_param_offset;
3852                 memcpy(ioarcb->add_data.u.add_cmd_params,
3853                         buffer->ioarcb.add_data.u.add_cmd_params,
3854                         buffer->ioarcb.add_cmd_param_length);
3855         }
3856
3857         /* set hrrq number where the IOA should respond to. Note that all cmds
3858          * generated internally uses hrrq_id 0, exception to this is the cmd
3859          * block of scsi_cmd which is re-used (e.g. cancel/abort), which uses
3860          * hrrq_id assigned here in queuecommand
3861          */
3862         ioarcb->hrrq_id = atomic_add_return(1, &(pinstance->last_message_id)) %
3863                           pinstance->num_hrrq;
3864
3865         if (request_size) {
3866                 rc = pmcraid_build_passthrough_ioadls(cmd,
3867                                                       request_size,
3868                                                       direction);
3869                 if (rc) {
3870                         pmcraid_err("couldn't build passthrough ioadls\n");
3871                         goto out_free_buffer;
3872                 }
3873         } else if (request_size < 0) {
3874                 rc = -EINVAL;
3875                 goto out_free_buffer;
3876         }
3877
3878         /* If data is being written into the device, copy the data from user
3879          * buffers
3880          */
3881         if (direction == DMA_TO_DEVICE && request_size > 0) {
3882                 rc = pmcraid_copy_sglist(cmd->sglist,
3883                                          request_buffer,
3884                                          request_size,
3885                                          direction);
3886                 if (rc) {
3887                         pmcraid_err("failed to copy user buffer\n");
3888                         goto out_free_sglist;
3889                 }
3890         }
3891
3892         /* passthrough ioctl is a blocking command so, put the user to sleep
3893          * until timeout. Note that a timeout value of 0 means, do timeout.
3894          */
3895         cmd->cmd_done = pmcraid_internal_done;
3896         init_completion(&cmd->wait_for_completion);
3897         cmd->completion_req = 1;
3898
3899         pmcraid_info("command(%d) (CDB[0] = %x) for %x\n",
3900                      le32_to_cpu(cmd->ioa_cb->ioarcb.response_handle) >> 2,
3901                      cmd->ioa_cb->ioarcb.cdb[0],
3902                      le32_to_cpu(cmd->ioa_cb->ioarcb.resource_handle));
3903
3904         spin_lock_irqsave(pinstance->host->host_lock, lock_flags);
3905         _pmcraid_fire_command(cmd);
3906         spin_unlock_irqrestore(pinstance->host->host_lock, lock_flags);
3907
3908         /* NOTE ! Remove the below line once abort_task is implemented
3909          * in firmware. This line disables ioctl command timeout handling logic
3910          * similar to IO command timeout handling, making ioctl commands to wait
3911          * until the command completion regardless of timeout value specified in
3912          * ioarcb
3913          */
3914         buffer->ioarcb.cmd_timeout = 0;
3915
3916         /* If command timeout is specified put caller to wait till that time,
3917          * otherwise it would be blocking wait. If command gets timed out, it
3918          * will be aborted.
3919          */
3920         if (buffer->ioarcb.cmd_timeout == 0) {
3921                 wait_for_completion(&cmd->wait_for_completion);
3922         } else if (!wait_for_completion_timeout(
3923                         &cmd->wait_for_completion,
3924                         msecs_to_jiffies(buffer->ioarcb.cmd_timeout * 1000))) {
3925
3926                 pmcraid_info("aborting cmd %d (CDB[0] = %x) due to timeout\n",
3927                         le32_to_cpu(cmd->ioa_cb->ioarcb.response_handle >> 2),
3928                         cmd->ioa_cb->ioarcb.cdb[0]);
3929
3930                 spin_lock_irqsave(pinstance->host->host_lock, lock_flags);
3931                 cancel_cmd = pmcraid_abort_cmd(cmd);
3932                 spin_unlock_irqrestore(pinstance->host->host_lock, lock_flags);
3933
3934                 if (cancel_cmd) {
3935                         wait_for_completion(&cancel_cmd->wait_for_completion);
3936                         ioasc = cancel_cmd->ioa_cb->ioasa.ioasc;
3937                         pmcraid_return_cmd(cancel_cmd);
3938
3939                         /* if abort task couldn't find the command i.e it got
3940                          * completed prior to aborting, return good completion.
3941                          * if command got aborted successfully or there was IOA
3942                          * reset due to abort task itself getting timedout then
3943                          * return -ETIMEDOUT
3944                          */
3945                         if (ioasc == PMCRAID_IOASC_IOA_WAS_RESET ||
3946                             PMCRAID_IOASC_SENSE_KEY(ioasc) == 0x00) {
3947                                 if (ioasc != PMCRAID_IOASC_GC_IOARCB_NOTFOUND)
3948                                         rc = -ETIMEDOUT;
3949                                 goto out_handle_response;
3950                         }
3951                 }
3952
3953                 /* no command block for abort task or abort task failed to abort
3954                  * the IOARCB, then wait for 150 more seconds and initiate reset
3955                  * sequence after timeout
3956                  */
3957                 if (!wait_for_completion_timeout(
3958                         &cmd->wait_for_completion,
3959                         msecs_to_jiffies(150 * 1000))) {
3960                         pmcraid_reset_bringup(cmd->drv_inst);
3961                         rc = -ETIMEDOUT;
3962                 }
3963         }
3964
3965 out_handle_response:
3966         /* copy entire IOASA buffer and return IOCTL success.
3967          * If copying IOASA to user-buffer fails, return
3968          * EFAULT
3969          */
3970         if (copy_to_user(ioasa, &cmd->ioa_cb->ioasa,
3971                 sizeof(struct pmcraid_ioasa))) {
3972                 pmcraid_err("failed to copy ioasa buffer to user\n");
3973                 rc = -EFAULT;
3974         }
3975
3976         /* If the data transfer was from device, copy the data onto user
3977          * buffers
3978          */
3979         else if (direction == DMA_FROM_DEVICE && request_size > 0) {
3980                 rc = pmcraid_copy_sglist(cmd->sglist,
3981                                          request_buffer,
3982                                          request_size,
3983                                          direction);
3984                 if (rc) {
3985                         pmcraid_err("failed to copy user buffer\n");
3986                         rc = -EFAULT;
3987                 }
3988         }
3989
3990 out_free_sglist:
3991         pmcraid_release_passthrough_ioadls(cmd, request_size, direction);
3992         pmcraid_return_cmd(cmd);
3993
3994 out_free_buffer:
3995         kfree(buffer);
3996
3997         return rc;
3998 }
3999
4000
4001
4002
4003 /**
4004  * pmcraid_ioctl_driver - ioctl handler for commands handled by driver itself
4005  *
4006  * @pinstance: pointer to adapter instance structure
4007  * @cmd: ioctl command passed in
4008  * @buflen: length of user_buffer
4009  * @user_buffer: user buffer pointer
4010  *
4011  * Return Value
4012  *   0 in case of success, otherwise appropriate error code
4013  */
4014 static long pmcraid_ioctl_driver(
4015         struct pmcraid_instance *pinstance,
4016         unsigned int cmd,
4017         unsigned int buflen,
4018         void __user *user_buffer
4019 )
4020 {
4021         int rc = -ENOSYS;
4022
4023         if (!access_ok(VERIFY_READ, user_buffer, _IOC_SIZE(cmd))) {
4024                 pmcraid_err("ioctl_driver: access fault in request buffer\n");
4025                 return -EFAULT;
4026         }
4027
4028         switch (cmd) {
4029         case PMCRAID_IOCTL_RESET_ADAPTER:
4030                 pmcraid_reset_bringup(pinstance);
4031                 rc = 0;
4032                 break;
4033
4034         default:
4035                 break;
4036         }
4037
4038         return rc;
4039 }
4040
4041 /**
4042  * pmcraid_check_ioctl_buffer - check for proper access to user buffer
4043  *
4044  * @cmd: ioctl command
4045  * @arg: user buffer
4046  * @hdr: pointer to kernel memory for pmcraid_ioctl_header
4047  *
4048  * Return Value
4049  *      negetive error code if there are access issues, otherwise zero.
4050  *      Upon success, returns ioctl header copied out of user buffer.
4051  */
4052
4053 static int pmcraid_check_ioctl_buffer(
4054         int cmd,
4055         void __user *arg,
4056         struct pmcraid_ioctl_header *hdr
4057 )
4058 {
4059         int rc = 0;
4060         int access = VERIFY_READ;
4061
4062         if (copy_from_user(hdr, arg, sizeof(struct pmcraid_ioctl_header))) {
4063                 pmcraid_err("couldn't copy ioctl header from user buffer\n");
4064                 return -EFAULT;
4065         }
4066
4067         /* check for valid driver signature */
4068         rc = memcmp(hdr->signature,
4069                     PMCRAID_IOCTL_SIGNATURE,
4070                     sizeof(hdr->signature));
4071         if (rc) {
4072                 pmcraid_err("signature verification failed\n");
4073                 return -EINVAL;
4074         }
4075
4076         /* check for appropriate buffer access */
4077         if ((_IOC_DIR(cmd) & _IOC_READ) == _IOC_READ)
4078                 access = VERIFY_WRITE;
4079
4080         rc = access_ok(access,
4081                        (arg + sizeof(struct pmcraid_ioctl_header)),
4082                        hdr->buffer_length);
4083         if (!rc) {
4084                 pmcraid_err("access failed for user buffer of size %d\n",
4085                              hdr->buffer_length);
4086                 return -EFAULT;
4087         }
4088
4089         return 0;
4090 }
4091
4092 /**
4093  *  pmcraid_ioctl - char node ioctl entry point
4094  */
4095 static long pmcraid_chr_ioctl(
4096         struct file *filep,
4097         unsigned int cmd,
4098         unsigned long arg
4099 )
4100 {
4101         struct pmcraid_instance *pinstance = NULL;
4102         struct pmcraid_ioctl_header *hdr = NULL;
4103         int retval = -ENOTTY;
4104
4105         hdr = kmalloc(sizeof(struct pmcraid_ioctl_header), GFP_KERNEL);
4106
4107         if (!hdr) {
4108                 pmcraid_err("faile to allocate memory for ioctl header\n");
4109                 return -ENOMEM;
4110         }
4111
4112         retval = pmcraid_check_ioctl_buffer(cmd, (void *)arg, hdr);
4113
4114         if (retval) {
4115                 pmcraid_info("chr_ioctl: header check failed\n");
4116                 kfree(hdr);
4117                 return retval;
4118         }
4119
4120         pinstance = filep->private_data;
4121
4122         if (!pinstance) {
4123                 pmcraid_info("adapter instance is not found\n");
4124                 kfree(hdr);
4125                 return -ENOTTY;
4126         }
4127
4128         switch (_IOC_TYPE(cmd)) {
4129
4130         case PMCRAID_PASSTHROUGH_IOCTL:
4131                 /* If ioctl code is to download microcode, we need to block
4132                  * mid-layer requests.
4133                  */
4134                 if (cmd == PMCRAID_IOCTL_DOWNLOAD_MICROCODE)
4135                         scsi_block_requests(pinstance->host);
4136
4137                 retval = pmcraid_ioctl_passthrough(pinstance,
4138                                                    cmd,
4139                                                    hdr->buffer_length,
4140                                                    arg);
4141
4142                 if (cmd == PMCRAID_IOCTL_DOWNLOAD_MICROCODE)
4143                         scsi_unblock_requests(pinstance->host);
4144                 break;
4145
4146         case PMCRAID_DRIVER_IOCTL:
4147                 arg += sizeof(struct pmcraid_ioctl_header);
4148                 retval = pmcraid_ioctl_driver(pinstance,
4149                                               cmd,
4150                                               hdr->buffer_length,
4151                                               (void __user *)arg);
4152                 break;
4153
4154         default:
4155                 retval = -ENOTTY;
4156                 break;
4157         }
4158
4159         kfree(hdr);
4160
4161         return retval;
4162 }
4163
4164 /**
4165  * File operations structure for management interface
4166  */
4167 static const struct file_operations pmcraid_fops = {
4168         .owner = THIS_MODULE,
4169         .open = pmcraid_chr_open,
4170         .release = pmcraid_chr_release,
4171         .fasync = pmcraid_chr_fasync,
4172         .unlocked_ioctl = pmcraid_chr_ioctl,
4173 #ifdef CONFIG_COMPAT
4174         .compat_ioctl = pmcraid_chr_ioctl,
4175 #endif
4176         .llseek = noop_llseek,
4177 };
4178
4179
4180
4181
4182 /**
4183  * pmcraid_show_log_level - Display adapter's error logging level
4184  * @dev: class device struct
4185  * @buf: buffer
4186  *
4187  * Return value:
4188  *  number of bytes printed to buffer
4189  */
4190 static ssize_t pmcraid_show_log_level(
4191         struct device *dev,
4192         struct device_attribute *attr,
4193         char *buf)
4194 {
4195         struct Scsi_Host *shost = class_to_shost(dev);
4196         struct pmcraid_instance *pinstance =
4197                 (struct pmcraid_instance *)shost->hostdata;
4198         return snprintf(buf, PAGE_SIZE, "%d\n", pinstance->current_log_level);
4199 }
4200
4201 /**
4202  * pmcraid_store_log_level - Change the adapter's error logging level
4203  * @dev: class device struct
4204  * @buf: buffer
4205  * @count: not used
4206  *
4207  * Return value:
4208  *  number of bytes printed to buffer
4209  */
4210 static ssize_t pmcraid_store_log_level(
4211         struct device *dev,
4212         struct device_attribute *attr,
4213         const char *buf,
4214         size_t count
4215 )
4216 {
4217         struct Scsi_Host *shost;
4218         struct pmcraid_instance *pinstance;
4219         unsigned long val;
4220
4221         if (strict_strtoul(buf, 10, &val))
4222                 return -EINVAL;
4223         /* log-level should be from 0 to 2 */
4224         if (val > 2)
4225                 return -EINVAL;
4226
4227         shost = class_to_shost(dev);
4228         pinstance = (struct pmcraid_instance *)shost->hostdata;
4229         pinstance->current_log_level = val;
4230
4231         return strlen(buf);
4232 }
4233
4234 static struct device_attribute pmcraid_log_level_attr = {
4235         .attr = {
4236                  .name = "log_level",
4237                  .mode = S_IRUGO | S_IWUSR,
4238                  },
4239         .show = pmcraid_show_log_level,
4240         .store = pmcraid_store_log_level,
4241 };
4242
4243 /**
4244  * pmcraid_show_drv_version - Display driver version
4245  * @dev: class device struct
4246  * @buf: buffer
4247  *
4248  * Return value:
4249  *  number of bytes printed to buffer
4250  */
4251 static ssize_t pmcraid_show_drv_version(
4252         struct device *dev,
4253         struct device_attribute *attr,
4254         char *buf
4255 )
4256 {
4257         return snprintf(buf, PAGE_SIZE, "version: %s\n",
4258                         PMCRAID_DRIVER_VERSION);
4259 }
4260
4261 static struct device_attribute pmcraid_driver_version_attr = {
4262         .attr = {
4263                  .name = "drv_version",
4264                  .mode = S_IRUGO,
4265                  },
4266         .show = pmcraid_show_drv_version,
4267 };
4268
4269 /**
4270  * pmcraid_show_io_adapter_id - Display driver assigned adapter id
4271  * @dev: class device struct
4272  * @buf: buffer
4273  *
4274  * Return value:
4275  *  number of bytes printed to buffer
4276  */
4277 static ssize_t pmcraid_show_adapter_id(
4278         struct device *dev,
4279         struct device_attribute *attr,
4280         char *buf
4281 )
4282 {
4283         struct Scsi_Host *shost = class_to_shost(dev);
4284         struct pmcraid_instance *pinstance =
4285                 (struct pmcraid_instance *)shost->hostdata;
4286         u32 adapter_id = (pinstance->pdev->bus->number << 8) |
4287                 pinstance->pdev->devfn;
4288         u32 aen_group = pmcraid_event_family.id;
4289
4290         return snprintf(buf, PAGE_SIZE,
4291                         "adapter id: %d\nminor: %d\naen group: %d\n",
4292                         adapter_id, MINOR(pinstance->cdev.dev), aen_group);
4293 }
4294
4295 static struct device_attribute pmcraid_adapter_id_attr = {
4296         .attr = {
4297                  .name = "adapter_id",
4298                  .mode = S_IRUGO | S_IWUSR,
4299                  },
4300         .show = pmcraid_show_adapter_id,
4301 };
4302
4303 static struct device_attribute *pmcraid_host_attrs[] = {
4304         &pmcraid_log_level_attr,
4305         &pmcraid_driver_version_attr,
4306         &pmcraid_adapter_id_attr,
4307         NULL,
4308 };
4309
4310
4311 /* host template structure for pmcraid driver */
4312 static struct scsi_host_template pmcraid_host_template = {
4313         .module = THIS_MODULE,
4314         .name = PMCRAID_DRIVER_NAME,
4315         .queuecommand = pmcraid_queuecommand,
4316         .eh_abort_handler = pmcraid_eh_abort_handler,
4317         .eh_bus_reset_handler = pmcraid_eh_bus_reset_handler,
4318         .eh_target_reset_handler = pmcraid_eh_target_reset_handler,
4319         .eh_device_reset_handler = pmcraid_eh_device_reset_handler,
4320         .eh_host_reset_handler = pmcraid_eh_host_reset_handler,
4321
4322         .slave_alloc = pmcraid_slave_alloc,
4323         .slave_configure = pmcraid_slave_configure,
4324         .slave_destroy = pmcraid_slave_destroy,
4325         .change_queue_depth = pmcraid_change_queue_depth,
4326         .change_queue_type  = pmcraid_change_queue_type,
4327         .can_queue = PMCRAID_MAX_IO_CMD,
4328         .this_id = -1,
4329         .sg_tablesize = PMCRAID_MAX_IOADLS,
4330         .max_sectors = PMCRAID_IOA_MAX_SECTORS,
4331         .cmd_per_lun = PMCRAID_MAX_CMD_PER_LUN,
4332         .use_clustering = ENABLE_CLUSTERING,
4333         .shost_attrs = pmcraid_host_attrs,
4334         .proc_name = PMCRAID_DRIVER_NAME
4335 };
4336
4337 /*
4338  * pmcraid_isr_msix - implements MSI-X interrupt handling routine
4339  * @irq: interrupt vector number
4340  * @dev_id: pointer hrrq_vector
4341  *
4342  * Return Value
4343  *       IRQ_HANDLED if interrupt is handled or IRQ_NONE if ignored
4344  */
4345
4346 static irqreturn_t pmcraid_isr_msix(int irq, void *dev_id)
4347 {
4348         struct pmcraid_isr_param *hrrq_vector;
4349         struct pmcraid_instance *pinstance;
4350         unsigned long lock_flags;
4351         u32 intrs_val;
4352         int hrrq_id;
4353
4354         hrrq_vector = (struct pmcraid_isr_param *)dev_id;
4355         hrrq_id = hrrq_vector->hrrq_id;
4356         pinstance = hrrq_vector->drv_inst;
4357
4358         if (!hrrq_id) {
4359                 /* Read the interrupt */
4360                 intrs_val = pmcraid_read_interrupts(pinstance);
4361                 if (intrs_val &&
4362                         ((ioread32(pinstance->int_regs.host_ioa_interrupt_reg)
4363                         & DOORBELL_INTR_MSIX_CLR) == 0)) {
4364                         /* Any error interrupts including unit_check,
4365                          * initiate IOA reset.In case of unit check indicate
4366                          * to reset_sequence that IOA unit checked and prepare
4367                          * for a dump during reset sequence
4368                          */
4369                         if (intrs_val & PMCRAID_ERROR_INTERRUPTS) {
4370                                 if (intrs_val & INTRS_IOA_UNIT_CHECK)
4371                                         pinstance->ioa_unit_check = 1;
4372
4373                                 pmcraid_err("ISR: error interrupts: %x \
4374                                         initiating reset\n", intrs_val);
4375                                 spin_lock_irqsave(pinstance->host->host_lock,
4376                                         lock_flags);
4377                                 pmcraid_initiate_reset(pinstance);
4378                                 spin_unlock_irqrestore(
4379                                         pinstance->host->host_lock,
4380                                         lock_flags);
4381                         }
4382                         /* If interrupt was as part of the ioa initialization,
4383                          * clear it. Delete the timer and wakeup the
4384                          * reset engine to proceed with reset sequence
4385                          */
4386                         if (intrs_val & INTRS_TRANSITION_TO_OPERATIONAL)
4387                                 pmcraid_clr_trans_op(pinstance);
4388
4389                         /* Clear the interrupt register by writing
4390                          * to host to ioa doorbell. Once done
4391                          * FW will clear the interrupt.
4392                          */
4393                         iowrite32(DOORBELL_INTR_MSIX_CLR,
4394                                 pinstance->int_regs.host_ioa_interrupt_reg);
4395                         ioread32(pinstance->int_regs.host_ioa_interrupt_reg);
4396
4397
4398                 }
4399         }
4400
4401         tasklet_schedule(&(pinstance->isr_tasklet[hrrq_id]));
4402
4403         return IRQ_HANDLED;
4404 }
4405
4406 /**
4407  * pmcraid_isr  - implements legacy interrupt handling routine
4408  *
4409  * @irq: interrupt vector number
4410  * @dev_id: pointer hrrq_vector
4411  *
4412  * Return Value
4413  *       IRQ_HANDLED if interrupt is handled or IRQ_NONE if ignored
4414  */
4415 static irqreturn_t pmcraid_isr(int irq, void *dev_id)
4416 {
4417         struct pmcraid_isr_param *hrrq_vector;
4418         struct pmcraid_instance *pinstance;
4419         u32 intrs;
4420         unsigned long lock_flags;
4421         int hrrq_id = 0;
4422
4423         /* In case of legacy interrupt mode where interrupts are shared across
4424          * isrs, it may be possible that the current interrupt is not from IOA
4425          */
4426         if (!dev_id) {
4427                 printk(KERN_INFO "%s(): NULL host pointer\n", __func__);
4428                 return IRQ_NONE;
4429         }
4430         hrrq_vector = (struct pmcraid_isr_param *)dev_id;
4431         pinstance = hrrq_vector->drv_inst;
4432
4433         intrs = pmcraid_read_interrupts(pinstance);
4434
4435         if (unlikely((intrs & PMCRAID_PCI_INTERRUPTS) == 0))
4436                 return IRQ_NONE;
4437
4438         /* Any error interrupts including unit_check, initiate IOA reset.
4439          * In case of unit check indicate to reset_sequence that IOA unit
4440          * checked and prepare for a dump during reset sequence
4441          */
4442         if (intrs & PMCRAID_ERROR_INTERRUPTS) {
4443
4444                 if (intrs & INTRS_IOA_UNIT_CHECK)
4445                         pinstance->ioa_unit_check = 1;
4446
4447                 iowrite32(intrs,
4448                           pinstance->int_regs.ioa_host_interrupt_clr_reg);
4449                 pmcraid_err("ISR: error interrupts: %x initiating reset\n",
4450                             intrs);
4451                 intrs = ioread32(
4452                                 pinstance->int_regs.ioa_host_interrupt_clr_reg);
4453                 spin_lock_irqsave(pinstance->host->host_lock, lock_flags);
4454                 pmcraid_initiate_reset(pinstance);
4455                 spin_unlock_irqrestore(pinstance->host->host_lock, lock_flags);
4456         } else {
4457                 /* If interrupt was as part of the ioa initialization,
4458                  * clear. Delete the timer and wakeup the
4459                  * reset engine to proceed with reset sequence
4460                  */
4461                 if (intrs & INTRS_TRANSITION_TO_OPERATIONAL) {
4462                         pmcraid_clr_trans_op(pinstance);
4463                 } else {
4464                         iowrite32(intrs,
4465                                 pinstance->int_regs.ioa_host_interrupt_clr_reg);
4466                         ioread32(
4467                                 pinstance->int_regs.ioa_host_interrupt_clr_reg);
4468
4469                         tasklet_schedule(
4470                                         &(pinstance->isr_tasklet[hrrq_id]));
4471                 }
4472         }
4473
4474         return IRQ_HANDLED;
4475 }
4476
4477
4478 /**
4479  * pmcraid_worker_function -  worker thread function
4480  *
4481  * @workp: pointer to struct work queue
4482  *
4483  * Return Value
4484  *       None
4485  */
4486
4487 static void pmcraid_worker_function(struct work_struct *workp)
4488 {
4489         struct pmcraid_instance *pinstance;
4490         struct pmcraid_resource_entry *res;
4491         struct pmcraid_resource_entry *temp;
4492         struct scsi_device *sdev;
4493         unsigned long lock_flags;
4494         unsigned long host_lock_flags;
4495         u16 fw_version;
4496         u8 bus, target, lun;
4497
4498         pinstance = container_of(workp, struct pmcraid_instance, worker_q);
4499         /* add resources only after host is added into system */
4500         if (!atomic_read(&pinstance->expose_resources))
4501                 return;
4502
4503         fw_version = be16_to_cpu(pinstance->inq_data->fw_version);
4504
4505         spin_lock_irqsave(&pinstance->resource_lock, lock_flags);
4506         list_for_each_entry_safe(res, temp, &pinstance->used_res_q, queue) {
4507
4508                 if (res->change_detected == RES_CHANGE_DEL && res->scsi_dev) {
4509                         sdev = res->scsi_dev;
4510
4511                         /* host_lock must be held before calling
4512                          * scsi_device_get
4513                          */
4514                         spin_lock_irqsave(pinstance->host->host_lock,
4515                                           host_lock_flags);
4516                         if (!scsi_device_get(sdev)) {
4517                                 spin_unlock_irqrestore(
4518                                                 pinstance->host->host_lock,
4519                                                 host_lock_flags);
4520                                 pmcraid_info("deleting %x from midlayer\n",
4521                                              res->cfg_entry.resource_address);
4522                                 list_move_tail(&res->queue,
4523                                                 &pinstance->free_res_q);
4524                                 spin_unlock_irqrestore(
4525                                         &pinstance->resource_lock,
4526                                         lock_flags);
4527                                 scsi_remove_device(sdev);
4528                                 scsi_device_put(sdev);
4529                                 spin_lock_irqsave(&pinstance->resource_lock,
4530                                                    lock_flags);
4531                                 res->change_detected = 0;
4532                         } else {
4533                                 spin_unlock_irqrestore(
4534                                                 pinstance->host->host_lock,
4535                                                 host_lock_flags);
4536                         }
4537                 }
4538         }
4539
4540         list_for_each_entry(res, &pinstance->used_res_q, queue) {
4541
4542                 if (res->change_detected == RES_CHANGE_ADD) {
4543
4544                         if (!pmcraid_expose_resource(fw_version,
4545                                                      &res->cfg_entry))
4546                                 continue;
4547
4548                         if (RES_IS_VSET(res->cfg_entry)) {
4549                                 bus = PMCRAID_VSET_BUS_ID;
4550                                 if (fw_version <= PMCRAID_FW_VERSION_1)
4551                                         target = res->cfg_entry.unique_flags1;
4552                                 else
4553                                         target = res->cfg_entry.array_id & 0xFF;
4554                                 lun = PMCRAID_VSET_LUN_ID;
4555                         } else {
4556                                 bus = PMCRAID_PHYS_BUS_ID;
4557                                 target =
4558                                      RES_TARGET(
4559                                         res->cfg_entry.resource_address);
4560                                 lun = RES_LUN(res->cfg_entry.resource_address);
4561                         }
4562
4563                         res->change_detected = 0;
4564                         spin_unlock_irqrestore(&pinstance->resource_lock,
4565                                                 lock_flags);
4566                         scsi_add_device(pinstance->host, bus, target, lun);
4567                         spin_lock_irqsave(&pinstance->resource_lock,
4568                                            lock_flags);
4569                 }
4570         }
4571
4572         spin_unlock_irqrestore(&pinstance->resource_lock, lock_flags);
4573 }
4574
4575 /**
4576  * pmcraid_tasklet_function - Tasklet function
4577  *
4578  * @instance: pointer to msix param structure
4579  *
4580  * Return Value
4581  *      None
4582  */
4583 static void pmcraid_tasklet_function(unsigned long instance)
4584 {
4585         struct pmcraid_isr_param *hrrq_vector;
4586         struct pmcraid_instance *pinstance;
4587         unsigned long hrrq_lock_flags;
4588         unsigned long pending_lock_flags;
4589         unsigned long host_lock_flags;
4590         spinlock_t *lockp; /* hrrq buffer lock */
4591         int id;
4592         __le32 resp;
4593
4594         hrrq_vector = (struct pmcraid_isr_param *)instance;
4595         pinstance = hrrq_vector->drv_inst;
4596         id = hrrq_vector->hrrq_id;
4597         lockp = &(pinstance->hrrq_lock[id]);
4598
4599         /* loop through each of the commands responded by IOA. Each HRRQ buf is
4600          * protected by its own lock. Traversals must be done within this lock
4601          * as there may be multiple tasklets running on multiple CPUs. Note
4602          * that the lock is held just for picking up the response handle and
4603          * manipulating hrrq_curr/toggle_bit values.
4604          */
4605         spin_lock_irqsave(lockp, hrrq_lock_flags);
4606
4607         resp = le32_to_cpu(*(pinstance->hrrq_curr[id]));
4608
4609         while ((resp & HRRQ_TOGGLE_BIT) ==
4610                 pinstance->host_toggle_bit[id]) {
4611
4612                 int cmd_index = resp >> 2;
4613                 struct pmcraid_cmd *cmd = NULL;
4614
4615                 if (pinstance->hrrq_curr[id] < pinstance->hrrq_end[id]) {
4616                         pinstance->hrrq_curr[id]++;
4617                 } else {
4618                         pinstance->hrrq_curr[id] = pinstance->hrrq_start[id];
4619                         pinstance->host_toggle_bit[id] ^= 1u;
4620                 }
4621
4622                 if (cmd_index >= PMCRAID_MAX_CMD) {
4623                         /* In case of invalid response handle, log message */
4624                         pmcraid_err("Invalid response handle %d\n", cmd_index);
4625                         resp = le32_to_cpu(*(pinstance->hrrq_curr[id]));
4626                         continue;
4627                 }
4628
4629                 cmd = pinstance->cmd_list[cmd_index];
4630                 spin_unlock_irqrestore(lockp, hrrq_lock_flags);
4631
4632                 spin_lock_irqsave(&pinstance->pending_pool_lock,
4633                                    pending_lock_flags);
4634                 list_del(&cmd->free_list);
4635                 spin_unlock_irqrestore(&pinstance->pending_pool_lock,
4636                                         pending_lock_flags);
4637                 del_timer(&cmd->timer);
4638                 atomic_dec(&pinstance->outstanding_cmds);
4639
4640                 if (cmd->cmd_done == pmcraid_ioa_reset) {
4641                         spin_lock_irqsave(pinstance->host->host_lock,
4642                                           host_lock_flags);
4643                         cmd->cmd_done(cmd);
4644                         spin_unlock_irqrestore(pinstance->host->host_lock,
4645                                                host_lock_flags);
4646                 } else if (cmd->cmd_done != NULL) {
4647                         cmd->cmd_done(cmd);
4648                 }
4649                 /* loop over until we are done with all responses */
4650                 spin_lock_irqsave(lockp, hrrq_lock_flags);
4651                 resp = le32_to_cpu(*(pinstance->hrrq_curr[id]));
4652         }
4653
4654         spin_unlock_irqrestore(lockp, hrrq_lock_flags);
4655 }
4656
4657 /**
4658  * pmcraid_unregister_interrupt_handler - de-register interrupts handlers
4659  * @pinstance: pointer to adapter instance structure
4660  *
4661  * This routine un-registers registered interrupt handler and
4662  * also frees irqs/vectors.
4663  *
4664  * Retun Value
4665  *      None
4666  */
4667 static
4668 void pmcraid_unregister_interrupt_handler(struct pmcraid_instance *pinstance)
4669 {
4670         int i;
4671
4672         for (i = 0; i < pinstance->num_hrrq; i++)
4673                 free_irq(pinstance->hrrq_vector[i].vector,
4674                          &(pinstance->hrrq_vector[i]));
4675
4676         if (pinstance->interrupt_mode) {
4677                 pci_disable_msix(pinstance->pdev);
4678                 pinstance->interrupt_mode = 0;
4679         }
4680 }
4681
4682 /**
4683  * pmcraid_register_interrupt_handler - registers interrupt handler
4684  * @pinstance: pointer to per-adapter instance structure
4685  *
4686  * Return Value
4687  *      0 on success, non-zero error code otherwise.
4688  */
4689 static int
4690 pmcraid_register_interrupt_handler(struct pmcraid_instance *pinstance)
4691 {
4692         int rc;
4693         struct pci_dev *pdev = pinstance->pdev;
4694
4695         if ((pmcraid_enable_msix) &&
4696                 (pci_find_capability(pdev, PCI_CAP_ID_MSIX))) {
4697                 int num_hrrq = PMCRAID_NUM_MSIX_VECTORS;
4698                 struct msix_entry entries[PMCRAID_NUM_MSIX_VECTORS];
4699                 int i;
4700                 for (i = 0; i < PMCRAID_NUM_MSIX_VECTORS; i++)
4701                         entries[i].entry = i;
4702
4703                 rc = pci_enable_msix(pdev, entries, num_hrrq);
4704                 if (rc < 0)
4705                         goto pmcraid_isr_legacy;
4706
4707                 /* Check how many MSIX vectors are allocated and register
4708                  * msi-x handlers for each of them giving appropriate buffer
4709                  */
4710                 if (rc > 0) {
4711                         num_hrrq = rc;
4712                         if (pci_enable_msix(pdev, entries, num_hrrq))
4713                                 goto pmcraid_isr_legacy;
4714                 }
4715
4716                 for (i = 0; i < num_hrrq; i++) {
4717                         pinstance->hrrq_vector[i].hrrq_id = i;
4718                         pinstance->hrrq_vector[i].drv_inst = pinstance;
4719                         pinstance->hrrq_vector[i].vector = entries[i].vector;
4720                         rc = request_irq(pinstance->hrrq_vector[i].vector,
4721                                         pmcraid_isr_msix, 0,
4722                                         PMCRAID_DRIVER_NAME,
4723                                         &(pinstance->hrrq_vector[i]));
4724
4725                         if (rc) {
4726                                 int j;
4727                                 for (j = 0; j < i; j++)
4728                                         free_irq(entries[j].vector,
4729                                                  &(pinstance->hrrq_vector[j]));
4730                                 pci_disable_msix(pdev);
4731                                 goto pmcraid_isr_legacy;
4732                         }
4733                 }
4734
4735                 pinstance->num_hrrq = num_hrrq;
4736                 pinstance->interrupt_mode = 1;
4737                 iowrite32(DOORBELL_INTR_MODE_MSIX,
4738                           pinstance->int_regs.host_ioa_interrupt_reg);
4739                 ioread32(pinstance->int_regs.host_ioa_interrupt_reg);
4740                 goto pmcraid_isr_out;
4741         }
4742
4743 pmcraid_isr_legacy:
4744         /* If MSI-X registration failed fallback to legacy mode, where
4745          * only one hrrq entry will be used
4746          */
4747         pinstance->hrrq_vector[0].hrrq_id = 0;
4748         pinstance->hrrq_vector[0].drv_inst = pinstance;
4749         pinstance->hrrq_vector[0].vector = pdev->irq;
4750         pinstance->num_hrrq = 1;
4751         rc = 0;
4752
4753         rc = request_irq(pdev->irq, pmcraid_isr, IRQF_SHARED,
4754                          PMCRAID_DRIVER_NAME, &pinstance->hrrq_vector[0]);
4755 pmcraid_isr_out:
4756         return rc;
4757 }
4758
4759 /**
4760  * pmcraid_release_cmd_blocks - release buufers allocated for command blocks
4761  * @pinstance: per adapter instance structure pointer
4762  * @max_index: number of buffer blocks to release
4763  *
4764  * Return Value
4765  *  None
4766  */
4767 static void
4768 pmcraid_release_cmd_blocks(struct pmcraid_instance *pinstance, int max_index)
4769 {
4770         int i;
4771         for (i = 0; i < max_index; i++) {
4772                 kmem_cache_free(pinstance->cmd_cachep, pinstance->cmd_list[i]);
4773                 pinstance->cmd_list[i] = NULL;
4774         }
4775         kmem_cache_destroy(pinstance->cmd_cachep);
4776         pinstance->cmd_cachep = NULL;
4777 }
4778
4779 /**
4780  * pmcraid_release_control_blocks - releases buffers alloced for control blocks
4781  * @pinstance: pointer to per adapter instance structure
4782  * @max_index: number of buffers (from 0 onwards) to release
4783  *
4784  * This function assumes that the command blocks for which control blocks are
4785  * linked are not released.
4786  *
4787  * Return Value
4788  *       None
4789  */
4790 static void
4791 pmcraid_release_control_blocks(
4792         struct pmcraid_instance *pinstance,
4793         int max_index
4794 )
4795 {
4796         int i;
4797
4798         if (pinstance->control_pool == NULL)
4799                 return;
4800
4801         for (i = 0; i < max_index; i++) {
4802                 pci_pool_free(pinstance->control_pool,
4803                               pinstance->cmd_list[i]->ioa_cb,
4804                               pinstance->cmd_list[i]->ioa_cb_bus_addr);
4805                 pinstance->cmd_list[i]->ioa_cb = NULL;
4806                 pinstance->cmd_list[i]->ioa_cb_bus_addr = 0;
4807         }
4808         pci_pool_destroy(pinstance->control_pool);
4809         pinstance->control_pool = NULL;
4810 }
4811
4812 /**
4813  * pmcraid_allocate_cmd_blocks - allocate memory for cmd block structures
4814  * @pinstance - pointer to per adapter instance structure
4815  *
4816  * Allocates memory for command blocks using kernel slab allocator.
4817  *
4818  * Return Value
4819  *      0 in case of success; -ENOMEM in case of failure
4820  */
4821 static int __devinit
4822 pmcraid_allocate_cmd_blocks(struct pmcraid_instance *pinstance)
4823 {
4824         int i;
4825
4826         sprintf(pinstance->cmd_pool_name, "pmcraid_cmd_pool_%d",
4827                 pinstance->host->unique_id);
4828
4829
4830         pinstance->cmd_cachep = kmem_cache_create(
4831                                         pinstance->cmd_pool_name,
4832                                         sizeof(struct pmcraid_cmd), 0,
4833                                         SLAB_HWCACHE_ALIGN, NULL);
4834         if (!pinstance->cmd_cachep)
4835                 return -ENOMEM;
4836
4837         for (i = 0; i < PMCRAID_MAX_CMD; i++) {
4838                 pinstance->cmd_list[i] =
4839                         kmem_cache_alloc(pinstance->cmd_cachep, GFP_KERNEL);
4840                 if (!pinstance->cmd_list[i]) {
4841                         pmcraid_release_cmd_blocks(pinstance, i);
4842                         return -ENOMEM;
4843                 }
4844         }
4845         return 0;
4846 }
4847
4848 /**
4849  * pmcraid_allocate_control_blocks - allocates memory control blocks
4850  * @pinstance : pointer to per adapter instance structure
4851  *
4852  * This function allocates PCI memory for DMAable buffers like IOARCB, IOADLs
4853  * and IOASAs. This is called after command blocks are already allocated.
4854  *
4855  * Return Value
4856  *  0 in case it can allocate all control blocks, otherwise -ENOMEM
4857  */
4858 static int __devinit
4859 pmcraid_allocate_control_blocks(struct pmcraid_instance *pinstance)
4860 {
4861         int i;
4862
4863         sprintf(pinstance->ctl_pool_name, "pmcraid_control_pool_%d",
4864                 pinstance->host->unique_id);
4865
4866         pinstance->control_pool =
4867                 pci_pool_create(pinstance->ctl_pool_name,
4868                                 pinstance->pdev,
4869                                 sizeof(struct pmcraid_control_block),
4870                                 PMCRAID_IOARCB_ALIGNMENT, 0);
4871
4872         if (!pinstance->control_pool)
4873                 return -ENOMEM;
4874
4875         for (i = 0; i < PMCRAID_MAX_CMD; i++) {
4876                 pinstance->cmd_list[i]->ioa_cb =
4877                         pci_pool_alloc(
4878                                 pinstance->control_pool,
4879                                 GFP_KERNEL,
4880                                 &(pinstance->cmd_list[i]->ioa_cb_bus_addr));
4881
4882                 if (!pinstance->cmd_list[i]->ioa_cb) {
4883                         pmcraid_release_control_blocks(pinstance, i);
4884                         return -ENOMEM;
4885                 }
4886                 memset(pinstance->cmd_list[i]->ioa_cb, 0,
4887                         sizeof(struct pmcraid_control_block));
4888         }
4889         return 0;
4890 }
4891
4892 /**
4893  * pmcraid_release_host_rrqs - release memory allocated for hrrq buffer(s)
4894  * @pinstance: pointer to per adapter instance structure
4895  * @maxindex: size of hrrq buffer pointer array
4896  *
4897  * Return Value
4898  *      None
4899  */
4900 static void
4901 pmcraid_release_host_rrqs(struct pmcraid_instance *pinstance, int maxindex)
4902 {
4903         int i;
4904         for (i = 0; i < maxindex; i++) {
4905
4906                 pci_free_consistent(pinstance->pdev,
4907                                     HRRQ_ENTRY_SIZE * PMCRAID_MAX_CMD,
4908                                     pinstance->hrrq_start[i],
4909                                     pinstance->hrrq_start_bus_addr[i]);
4910
4911                 /* reset pointers and toggle bit to zeros */
4912                 pinstance->hrrq_start[i] = NULL;
4913                 pinstance->hrrq_start_bus_addr[i] = 0;
4914                 pinstance->host_toggle_bit[i] = 0;
4915         }
4916 }
4917
4918 /**
4919  * pmcraid_allocate_host_rrqs - Allocate and initialize host RRQ buffers
4920  * @pinstance: pointer to per adapter instance structure
4921  *
4922  * Return value
4923  *      0 hrrq buffers are allocated, -ENOMEM otherwise.
4924  */
4925 static int __devinit
4926 pmcraid_allocate_host_rrqs(struct pmcraid_instance *pinstance)
4927 {
4928         int i, buffer_size;
4929
4930         buffer_size = HRRQ_ENTRY_SIZE * PMCRAID_MAX_CMD;
4931
4932         for (i = 0; i < pinstance->num_hrrq; i++) {
4933                 pinstance->hrrq_start[i] =
4934                         pci_alloc_consistent(
4935                                         pinstance->pdev,
4936                                         buffer_size,
4937                                         &(pinstance->hrrq_start_bus_addr[i]));
4938
4939                 if (pinstance->hrrq_start[i] == 0) {
4940                         pmcraid_err("pci_alloc failed for hrrq vector : %d\n",
4941                                     i);
4942                         pmcraid_release_host_rrqs(pinstance, i);
4943                         return -ENOMEM;
4944                 }
4945
4946                 memset(pinstance->hrrq_start[i], 0, buffer_size);
4947                 pinstance->hrrq_curr[i] = pinstance->hrrq_start[i];
4948                 pinstance->hrrq_end[i] =
4949                         pinstance->hrrq_start[i] + PMCRAID_MAX_CMD - 1;
4950                 pinstance->host_toggle_bit[i] = 1;
4951                 spin_lock_init(&pinstance->hrrq_lock[i]);
4952         }
4953         return 0;
4954 }
4955
4956 /**
4957  * pmcraid_release_hcams - release HCAM buffers
4958  *
4959  * @pinstance: pointer to per adapter instance structure
4960  *
4961  * Return value
4962  *  none
4963  */
4964 static void pmcraid_release_hcams(struct pmcraid_instance *pinstance)
4965 {
4966         if (pinstance->ccn.msg != NULL) {
4967                 pci_free_consistent(pinstance->pdev,
4968                                     PMCRAID_AEN_HDR_SIZE +
4969                                     sizeof(struct pmcraid_hcam_ccn_ext),
4970                                     pinstance->ccn.msg,
4971                                     pinstance->ccn.baddr);
4972
4973                 pinstance->ccn.msg = NULL;
4974                 pinstance->ccn.hcam = NULL;
4975                 pinstance->ccn.baddr = 0;
4976         }
4977
4978         if (pinstance->ldn.msg != NULL) {
4979                 pci_free_consistent(pinstance->pdev,
4980                                     PMCRAID_AEN_HDR_SIZE +
4981                                     sizeof(struct pmcraid_hcam_ldn),
4982                                     pinstance->ldn.msg,
4983                                     pinstance->ldn.baddr);
4984
4985                 pinstance->ldn.msg = NULL;
4986                 pinstance->ldn.hcam = NULL;
4987                 pinstance->ldn.baddr = 0;
4988         }
4989 }
4990
4991 /**
4992  * pmcraid_allocate_hcams - allocates HCAM buffers
4993  * @pinstance : pointer to per adapter instance structure
4994  *
4995  * Return Value:
4996  *   0 in case of successful allocation, non-zero otherwise
4997  */
4998 static int pmcraid_allocate_hcams(struct pmcraid_instance *pinstance)
4999 {
5000         pinstance->ccn.msg = pci_alloc_consistent(
5001                                         pinstance->pdev,
5002                                         PMCRAID_AEN_HDR_SIZE +
5003                                         sizeof(struct pmcraid_hcam_ccn_ext),
5004                                         &(pinstance->ccn.baddr));
5005
5006         pinstance->ldn.msg = pci_alloc_consistent(
5007                                         pinstance->pdev,
5008                                         PMCRAID_AEN_HDR_SIZE +
5009                                         sizeof(struct pmcraid_hcam_ldn),
5010                                         &(pinstance->ldn.baddr));
5011
5012         if (pinstance->ldn.msg == NULL || pinstance->ccn.msg == NULL) {
5013                 pmcraid_release_hcams(pinstance);
5014         } else {
5015                 pinstance->ccn.hcam =
5016                         (void *)pinstance->ccn.msg + PMCRAID_AEN_HDR_SIZE;
5017                 pinstance->ldn.hcam =
5018                         (void *)pinstance->ldn.msg + PMCRAID_AEN_HDR_SIZE;
5019
5020                 atomic_set(&pinstance->ccn.ignore, 0);
5021                 atomic_set(&pinstance->ldn.ignore, 0);
5022         }
5023
5024         return (pinstance->ldn.msg == NULL) ? -ENOMEM : 0;
5025 }
5026
5027 /**
5028  * pmcraid_release_config_buffers - release config.table buffers
5029  * @pinstance: pointer to per adapter instance structure
5030  *
5031  * Return Value
5032  *       none
5033  */
5034 static void pmcraid_release_config_buffers(struct pmcraid_instance *pinstance)
5035 {
5036         if (pinstance->cfg_table != NULL &&
5037             pinstance->cfg_table_bus_addr != 0) {
5038                 pci_free_consistent(pinstance->pdev,
5039                                     sizeof(struct pmcraid_config_table),
5040                                     pinstance->cfg_table,
5041                                     pinstance->cfg_table_bus_addr);
5042                 pinstance->cfg_table = NULL;
5043                 pinstance->cfg_table_bus_addr = 0;
5044         }
5045
5046         if (pinstance->res_entries != NULL) {
5047                 int i;
5048
5049                 for (i = 0; i < PMCRAID_MAX_RESOURCES; i++)
5050                         list_del(&pinstance->res_entries[i].queue);
5051                 kfree(pinstance->res_entries);
5052                 pinstance->res_entries = NULL;
5053         }
5054
5055         pmcraid_release_hcams(pinstance);
5056 }
5057
5058 /**
5059  * pmcraid_allocate_config_buffers - allocates DMAable memory for config table
5060  * @pinstance : pointer to per adapter instance structure
5061  *
5062  * Return Value
5063  *      0 for successful allocation, -ENOMEM for any failure
5064  */
5065 static int __devinit
5066 pmcraid_allocate_config_buffers(struct pmcraid_instance *pinstance)
5067 {
5068         int i;
5069
5070         pinstance->res_entries =
5071                         kzalloc(sizeof(struct pmcraid_resource_entry) *
5072                                 PMCRAID_MAX_RESOURCES, GFP_KERNEL);
5073
5074         if (NULL == pinstance->res_entries) {
5075                 pmcraid_err("failed to allocate memory for resource table\n");
5076                 return -ENOMEM;
5077         }
5078
5079         for (i = 0; i < PMCRAID_MAX_RESOURCES; i++)
5080                 list_add_tail(&pinstance->res_entries[i].queue,
5081                               &pinstance->free_res_q);
5082
5083         pinstance->cfg_table =
5084                 pci_alloc_consistent(pinstance->pdev,
5085                                      sizeof(struct pmcraid_config_table),
5086                                      &pinstance->cfg_table_bus_addr);
5087
5088         if (NULL == pinstance->cfg_table) {
5089                 pmcraid_err("couldn't alloc DMA memory for config table\n");
5090                 pmcraid_release_config_buffers(pinstance);
5091                 return -ENOMEM;
5092         }
5093
5094         if (pmcraid_allocate_hcams(pinstance)) {
5095                 pmcraid_err("could not alloc DMA memory for HCAMS\n");
5096                 pmcraid_release_config_buffers(pinstance);
5097                 return -ENOMEM;
5098         }
5099
5100         return 0;
5101 }
5102
5103 /**
5104  * pmcraid_init_tasklets - registers tasklets for response handling
5105  *
5106  * @pinstance: pointer adapter instance structure
5107  *
5108  * Return value
5109  *      none
5110  */
5111 static void pmcraid_init_tasklets(struct pmcraid_instance *pinstance)
5112 {
5113         int i;
5114         for (i = 0; i < pinstance->num_hrrq; i++)
5115                 tasklet_init(&pinstance->isr_tasklet[i],
5116                              pmcraid_tasklet_function,
5117                              (unsigned long)&pinstance->hrrq_vector[i]);
5118 }
5119
5120 /**
5121  * pmcraid_kill_tasklets - destroys tasklets registered for response handling
5122  *
5123  * @pinstance: pointer to adapter instance structure
5124  *
5125  * Return value
5126  *      none
5127  */
5128 static void pmcraid_kill_tasklets(struct pmcraid_instance *pinstance)
5129 {
5130         int i;
5131         for (i = 0; i < pinstance->num_hrrq; i++)
5132                 tasklet_kill(&pinstance->isr_tasklet[i]);
5133 }
5134
5135 /**
5136  * pmcraid_release_buffers - release per-adapter buffers allocated
5137  *
5138  * @pinstance: pointer to adapter soft state
5139  *
5140  * Return Value
5141  *      none
5142  */
5143 static void pmcraid_release_buffers(struct pmcraid_instance *pinstance)
5144 {
5145         pmcraid_release_config_buffers(pinstance);
5146         pmcraid_release_control_blocks(pinstance, PMCRAID_MAX_CMD);
5147         pmcraid_release_cmd_blocks(pinstance, PMCRAID_MAX_CMD);
5148         pmcraid_release_host_rrqs(pinstance, pinstance->num_hrrq);
5149
5150         if (pinstance->inq_data != NULL) {
5151                 pci_free_consistent(pinstance->pdev,
5152                                     sizeof(struct pmcraid_inquiry_data),
5153                                     pinstance->inq_data,
5154                                     pinstance->inq_data_baddr);
5155
5156                 pinstance->inq_data = NULL;
5157                 pinstance->inq_data_baddr = 0;
5158         }
5159
5160         if (pinstance->timestamp_data != NULL) {
5161                 pci_free_consistent(pinstance->pdev,
5162                                     sizeof(struct pmcraid_timestamp_data),
5163                                     pinstance->timestamp_data,
5164                                     pinstance->timestamp_data_baddr);
5165
5166                 pinstance->timestamp_data = NULL;
5167                 pinstance->timestamp_data_baddr = 0;
5168         }
5169 }
5170
5171 /**
5172  * pmcraid_init_buffers - allocates memory and initializes various structures
5173  * @pinstance: pointer to per adapter instance structure
5174  *
5175  * This routine pre-allocates memory based on the type of block as below:
5176  * cmdblocks(PMCRAID_MAX_CMD): kernel memory using kernel's slab_allocator,
5177  * IOARCBs(PMCRAID_MAX_CMD)  : DMAable memory, using pci pool allocator
5178  * config-table entries      : DMAable memory using pci_alloc_consistent
5179  * HostRRQs                  : DMAable memory, using pci_alloc_consistent
5180  *
5181  * Return Value
5182  *       0 in case all of the blocks are allocated, -ENOMEM otherwise.
5183  */
5184 static int __devinit pmcraid_init_buffers(struct pmcraid_instance *pinstance)
5185 {
5186         int i;
5187
5188         if (pmcraid_allocate_host_rrqs(pinstance)) {
5189                 pmcraid_err("couldn't allocate memory for %d host rrqs\n",
5190                              pinstance->num_hrrq);
5191                 return -ENOMEM;
5192         }
5193
5194         if (pmcraid_allocate_config_buffers(pinstance)) {
5195                 pmcraid_err("couldn't allocate memory for config buffers\n");
5196                 pmcraid_release_host_rrqs(pinstance, pinstance->num_hrrq);
5197                 return -ENOMEM;
5198         }
5199
5200         if (pmcraid_allocate_cmd_blocks(pinstance)) {
5201                 pmcraid_err("couldn't allocate memory for cmd blocks\n");
5202                 pmcraid_release_config_buffers(pinstance);
5203                 pmcraid_release_host_rrqs(pinstance, pinstance->num_hrrq);
5204                 return -ENOMEM;
5205         }
5206
5207         if (pmcraid_allocate_control_blocks(pinstance)) {
5208                 pmcraid_err("couldn't allocate memory control blocks\n");
5209                 pmcraid_release_config_buffers(pinstance);
5210                 pmcraid_release_cmd_blocks(pinstance, PMCRAID_MAX_CMD);
5211                 pmcraid_release_host_rrqs(pinstance, pinstance->num_hrrq);
5212                 return -ENOMEM;
5213         }
5214
5215         /* allocate DMAable memory for page D0 INQUIRY buffer */
5216         pinstance->inq_data = pci_alloc_consistent(
5217                                         pinstance->pdev,
5218                                         sizeof(struct pmcraid_inquiry_data),
5219                                         &pinstance->inq_data_baddr);
5220
5221         if (pinstance->inq_data == NULL) {
5222                 pmcraid_err("couldn't allocate DMA memory for INQUIRY\n");
5223                 pmcraid_release_buffers(pinstance);
5224                 return -ENOMEM;
5225         }
5226
5227         /* allocate DMAable memory for set timestamp data buffer */
5228         pinstance->timestamp_data = pci_alloc_consistent(
5229                                         pinstance->pdev,
5230                                         sizeof(struct pmcraid_timestamp_data),
5231                                         &pinstance->timestamp_data_baddr);
5232
5233         if (pinstance->timestamp_data == NULL) {
5234                 pmcraid_err("couldn't allocate DMA memory for \
5235                                 set time_stamp \n");
5236                 pmcraid_release_buffers(pinstance);
5237                 return -ENOMEM;
5238         }
5239
5240
5241         /* Initialize all the command blocks and add them to free pool. No
5242          * need to lock (free_pool_lock) as this is done in initialization
5243          * itself
5244          */
5245         for (i = 0; i < PMCRAID_MAX_CMD; i++) {
5246                 struct pmcraid_cmd *cmdp = pinstance->cmd_list[i];
5247                 pmcraid_init_cmdblk(cmdp, i);
5248                 cmdp->drv_inst = pinstance;
5249                 list_add_tail(&cmdp->free_list, &pinstance->free_cmd_pool);
5250         }
5251
5252         return 0;
5253 }
5254
5255 /**
5256  * pmcraid_reinit_buffers - resets various buffer pointers
5257  * @pinstance: pointer to adapter instance
5258  * Return value
5259  *      none
5260  */
5261 static void pmcraid_reinit_buffers(struct pmcraid_instance *pinstance)
5262 {
5263         int i;
5264         int buffer_size = HRRQ_ENTRY_SIZE * PMCRAID_MAX_CMD;
5265
5266         for (i = 0; i < pinstance->num_hrrq; i++) {
5267                 memset(pinstance->hrrq_start[i], 0, buffer_size);
5268                 pinstance->hrrq_curr[i] = pinstance->hrrq_start[i];
5269                 pinstance->hrrq_end[i] =
5270                         pinstance->hrrq_start[i] + PMCRAID_MAX_CMD - 1;
5271                 pinstance->host_toggle_bit[i] = 1;
5272         }
5273 }
5274
5275 /**
5276  * pmcraid_init_instance - initialize per instance data structure
5277  * @pdev: pointer to pci device structure
5278  * @host: pointer to Scsi_Host structure
5279  * @mapped_pci_addr: memory mapped IOA configuration registers
5280  *
5281  * Return Value
5282  *       0 on success, non-zero in case of any failure
5283  */
5284 static int __devinit pmcraid_init_instance(
5285         struct pci_dev *pdev,
5286         struct Scsi_Host *host,
5287         void __iomem *mapped_pci_addr
5288 )
5289 {
5290         struct pmcraid_instance *pinstance =
5291                 (struct pmcraid_instance *)host->hostdata;
5292
5293         pinstance->host = host;
5294         pinstance->pdev = pdev;
5295
5296         /* Initialize register addresses */
5297         pinstance->mapped_dma_addr = mapped_pci_addr;
5298
5299         /* Initialize chip-specific details */
5300         {
5301                 struct pmcraid_chip_details *chip_cfg = pinstance->chip_cfg;
5302                 struct pmcraid_interrupts *pint_regs = &pinstance->int_regs;
5303
5304                 pinstance->ioarrin = mapped_pci_addr + chip_cfg->ioarrin;
5305
5306                 pint_regs->ioa_host_interrupt_reg =
5307                         mapped_pci_addr + chip_cfg->ioa_host_intr;
5308                 pint_regs->ioa_host_interrupt_clr_reg =
5309                         mapped_pci_addr + chip_cfg->ioa_host_intr_clr;
5310                 pint_regs->ioa_host_msix_interrupt_reg =
5311                         mapped_pci_addr + chip_cfg->ioa_host_msix_intr;
5312                 pint_regs->host_ioa_interrupt_reg =
5313                         mapped_pci_addr + chip_cfg->host_ioa_intr;
5314                 pint_regs->host_ioa_interrupt_clr_reg =
5315                         mapped_pci_addr + chip_cfg->host_ioa_intr_clr;
5316
5317                 /* Current version of firmware exposes interrupt mask set
5318                  * and mask clr registers through memory mapped bar0.
5319                  */
5320                 pinstance->mailbox = mapped_pci_addr + chip_cfg->mailbox;
5321                 pinstance->ioa_status = mapped_pci_addr + chip_cfg->ioastatus;
5322                 pint_regs->ioa_host_interrupt_mask_reg =
5323                         mapped_pci_addr + chip_cfg->ioa_host_mask;
5324                 pint_regs->ioa_host_interrupt_mask_clr_reg =
5325                         mapped_pci_addr + chip_cfg->ioa_host_mask_clr;
5326                 pint_regs->global_interrupt_mask_reg =
5327                         mapped_pci_addr + chip_cfg->global_intr_mask;
5328         };
5329
5330         pinstance->ioa_reset_attempts = 0;
5331         init_waitqueue_head(&pinstance->reset_wait_q);
5332
5333         atomic_set(&pinstance->outstanding_cmds, 0);
5334         atomic_set(&pinstance->last_message_id, 0);
5335         atomic_set(&pinstance->expose_resources, 0);
5336
5337         INIT_LIST_HEAD(&pinstance->free_res_q);
5338         INIT_LIST_HEAD(&pinstance->used_res_q);
5339         INIT_LIST_HEAD(&pinstance->free_cmd_pool);
5340         INIT_LIST_HEAD(&pinstance->pending_cmd_pool);
5341
5342         spin_lock_init(&pinstance->free_pool_lock);
5343         spin_lock_init(&pinstance->pending_pool_lock);
5344         spin_lock_init(&pinstance->resource_lock);
5345         mutex_init(&pinstance->aen_queue_lock);
5346
5347         /* Work-queue (Shared) for deferred processing error handling */
5348         INIT_WORK(&pinstance->worker_q, pmcraid_worker_function);
5349
5350         /* Initialize the default log_level */
5351         pinstance->current_log_level = pmcraid_log_level;
5352
5353         /* Setup variables required for reset engine */
5354         pinstance->ioa_state = IOA_STATE_UNKNOWN;
5355         pinstance->reset_cmd = NULL;
5356         return 0;
5357 }
5358
5359 /**
5360  * pmcraid_shutdown - shutdown adapter controller.
5361  * @pdev: pci device struct
5362  *
5363  * Issues an adapter shutdown to the card waits for its completion
5364  *
5365  * Return value
5366  *        none
5367  */
5368 static void pmcraid_shutdown(struct pci_dev *pdev)
5369 {
5370         struct pmcraid_instance *pinstance = pci_get_drvdata(pdev);
5371         pmcraid_reset_bringdown(pinstance);
5372 }
5373
5374
5375 /**
5376  * pmcraid_get_minor - returns unused minor number from minor number bitmap
5377  */
5378 static unsigned short pmcraid_get_minor(void)
5379 {
5380         int minor;
5381
5382         minor = find_first_zero_bit(pmcraid_minor, sizeof(pmcraid_minor));
5383         __set_bit(minor, pmcraid_minor);
5384         return minor;
5385 }
5386
5387 /**
5388  * pmcraid_release_minor - releases given minor back to minor number bitmap
5389  */
5390 static void pmcraid_release_minor(unsigned short minor)
5391 {
5392         __clear_bit(minor, pmcraid_minor);
5393 }
5394
5395 /**
5396  * pmcraid_setup_chrdev - allocates a minor number and registers a char device
5397  *
5398  * @pinstance: pointer to adapter instance for which to register device
5399  *
5400  * Return value
5401  *      0 in case of success, otherwise non-zero
5402  */
5403 static int pmcraid_setup_chrdev(struct pmcraid_instance *pinstance)
5404 {
5405         int minor;
5406         int error;
5407
5408         minor = pmcraid_get_minor();
5409         cdev_init(&pinstance->cdev, &pmcraid_fops);
5410         pinstance->cdev.owner = THIS_MODULE;
5411
5412         error = cdev_add(&pinstance->cdev, MKDEV(pmcraid_major, minor), 1);
5413
5414         if (error)
5415                 pmcraid_release_minor(minor);
5416         else
5417                 device_create(pmcraid_class, NULL, MKDEV(pmcraid_major, minor),
5418                               NULL, "%s%u", PMCRAID_DEVFILE, minor);
5419         return error;
5420 }
5421
5422 /**
5423  * pmcraid_release_chrdev - unregisters per-adapter management interface
5424  *
5425  * @pinstance: pointer to adapter instance structure
5426  *
5427  * Return value
5428  *  none
5429  */
5430 static void pmcraid_release_chrdev(struct pmcraid_instance *pinstance)
5431 {
5432         pmcraid_release_minor(MINOR(pinstance->cdev.dev));
5433         device_destroy(pmcraid_class,
5434                        MKDEV(pmcraid_major, MINOR(pinstance->cdev.dev)));
5435         cdev_del(&pinstance->cdev);
5436 }
5437
5438 /**
5439  * pmcraid_remove - IOA hot plug remove entry point
5440  * @pdev: pci device struct
5441  *
5442  * Return value
5443  *        none
5444  */
5445 static void __devexit pmcraid_remove(struct pci_dev *pdev)
5446 {
5447         struct pmcraid_instance *pinstance = pci_get_drvdata(pdev);
5448
5449         /* remove the management interface (/dev file) for this device */
5450         pmcraid_release_chrdev(pinstance);
5451
5452         /* remove host template from scsi midlayer */
5453         scsi_remove_host(pinstance->host);
5454
5455         /* block requests from mid-layer */
5456         scsi_block_requests(pinstance->host);
5457
5458         /* initiate shutdown adapter */
5459         pmcraid_shutdown(pdev);
5460
5461         pmcraid_disable_interrupts(pinstance, ~0);
5462         flush_work_sync(&pinstance->worker_q);
5463
5464         pmcraid_kill_tasklets(pinstance);
5465         pmcraid_unregister_interrupt_handler(pinstance);
5466         pmcraid_release_buffers(pinstance);
5467         iounmap(pinstance->mapped_dma_addr);
5468         pci_release_regions(pdev);
5469         scsi_host_put(pinstance->host);
5470         pci_disable_device(pdev);
5471
5472         return;
5473 }
5474
5475 #ifdef CONFIG_PM
5476 /**
5477  * pmcraid_suspend - driver suspend entry point for power management
5478  * @pdev:   PCI device structure
5479  * @state:  PCI power state to suspend routine
5480  *
5481  * Return Value - 0 always
5482  */
5483 static int pmcraid_suspend(struct pci_dev *pdev, pm_message_t state)
5484 {
5485         struct pmcraid_instance *pinstance = pci_get_drvdata(pdev);
5486
5487         pmcraid_shutdown(pdev);
5488         pmcraid_disable_interrupts(pinstance, ~0);
5489         pmcraid_kill_tasklets(pinstance);
5490         pci_set_drvdata(pinstance->pdev, pinstance);
5491         pmcraid_unregister_interrupt_handler(pinstance);
5492         pci_save_state(pdev);
5493         pci_disable_device(pdev);
5494         pci_set_power_state(pdev, pci_choose_state(pdev, state));
5495
5496         return 0;
5497 }
5498
5499 /**
5500  * pmcraid_resume - driver resume entry point PCI power management
5501  * @pdev: PCI device structure
5502  *
5503  * Return Value - 0 in case of success. Error code in case of any failure
5504  */
5505 static int pmcraid_resume(struct pci_dev *pdev)
5506 {
5507         struct pmcraid_instance *pinstance = pci_get_drvdata(pdev);
5508         struct Scsi_Host *host = pinstance->host;
5509         int rc;
5510
5511         pci_set_power_state(pdev, PCI_D0);
5512         pci_enable_wake(pdev, PCI_D0, 0);
5513         pci_restore_state(pdev);
5514
5515         rc = pci_enable_device(pdev);
5516
5517         if (rc) {
5518                 dev_err(&pdev->dev, "resume: Enable device failed\n");
5519                 return rc;
5520         }
5521
5522         pci_set_master(pdev);
5523
5524         if ((sizeof(dma_addr_t) == 4) ||
5525              pci_set_dma_mask(pdev, DMA_BIT_MASK(64)))
5526                 rc = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
5527
5528         if (rc == 0)
5529                 rc = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
5530
5531         if (rc != 0) {
5532                 dev_err(&pdev->dev, "resume: Failed to set PCI DMA mask\n");
5533                 goto disable_device;
5534         }
5535
5536         pmcraid_disable_interrupts(pinstance, ~0);
5537         atomic_set(&pinstance->outstanding_cmds, 0);
5538         rc = pmcraid_register_interrupt_handler(pinstance);
5539
5540         if (rc) {
5541                 dev_err(&pdev->dev,
5542                         "resume: couldn't register interrupt handlers\n");
5543                 rc = -ENODEV;
5544                 goto release_host;
5545         }
5546
5547         pmcraid_init_tasklets(pinstance);
5548         pmcraid_enable_interrupts(pinstance, PMCRAID_PCI_INTERRUPTS);
5549
5550         /* Start with hard reset sequence which brings up IOA to operational
5551          * state as well as completes the reset sequence.
5552          */
5553         pinstance->ioa_hard_reset = 1;
5554
5555         /* Start IOA firmware initialization and bring card to Operational
5556          * state.
5557          */
5558         if (pmcraid_reset_bringup(pinstance)) {
5559                 dev_err(&pdev->dev, "couldn't initialize IOA\n");
5560                 rc = -ENODEV;
5561                 goto release_tasklets;
5562         }
5563
5564         return 0;
5565
5566 release_tasklets:
5567         pmcraid_disable_interrupts(pinstance, ~0);
5568         pmcraid_kill_tasklets(pinstance);
5569         pmcraid_unregister_interrupt_handler(pinstance);
5570
5571 release_host:
5572         scsi_host_put(host);
5573
5574 disable_device:
5575         pci_disable_device(pdev);
5576
5577         return rc;
5578 }
5579
5580 #else
5581
5582 #define pmcraid_suspend NULL
5583 #define pmcraid_resume  NULL
5584
5585 #endif /* CONFIG_PM */
5586
5587 /**
5588  * pmcraid_complete_ioa_reset - Called by either timer or tasklet during
5589  *                              completion of the ioa reset
5590  * @cmd: pointer to reset command block
5591  */
5592 static void pmcraid_complete_ioa_reset(struct pmcraid_cmd *cmd)
5593 {
5594         struct pmcraid_instance *pinstance = cmd->drv_inst;
5595         unsigned long flags;
5596
5597         spin_lock_irqsave(pinstance->host->host_lock, flags);
5598         pmcraid_ioa_reset(cmd);
5599         spin_unlock_irqrestore(pinstance->host->host_lock, flags);
5600         scsi_unblock_requests(pinstance->host);
5601         schedule_work(&pinstance->worker_q);
5602 }
5603
5604 /**
5605  * pmcraid_set_supported_devs - sends SET SUPPORTED DEVICES to IOAFP
5606  *
5607  * @cmd: pointer to pmcraid_cmd structure
5608  *
5609  * Return Value
5610  *  0 for success or non-zero for failure cases
5611  */
5612 static void pmcraid_set_supported_devs(struct pmcraid_cmd *cmd)
5613 {
5614         struct pmcraid_ioarcb *ioarcb = &cmd->ioa_cb->ioarcb;
5615         void (*cmd_done) (struct pmcraid_cmd *) = pmcraid_complete_ioa_reset;
5616
5617         pmcraid_reinit_cmdblk(cmd);
5618
5619         ioarcb->resource_handle = cpu_to_le32(PMCRAID_IOA_RES_HANDLE);
5620         ioarcb->request_type = REQ_TYPE_IOACMD;
5621         ioarcb->cdb[0] = PMCRAID_SET_SUPPORTED_DEVICES;
5622         ioarcb->cdb[1] = ALL_DEVICES_SUPPORTED;
5623
5624         /* If this was called as part of resource table reinitialization due to
5625          * lost CCN, it is enough to return the command block back to free pool
5626          * as part of set_supported_devs completion function.
5627          */
5628         if (cmd->drv_inst->reinit_cfg_table) {
5629                 cmd->drv_inst->reinit_cfg_table = 0;
5630                 cmd->release = 1;
5631                 cmd_done = pmcraid_reinit_cfgtable_done;
5632         }
5633
5634         /* we will be done with the reset sequence after set supported devices,
5635          * setup the done function to return the command block back to free
5636          * pool
5637          */
5638         pmcraid_send_cmd(cmd,
5639                          cmd_done,
5640                          PMCRAID_SET_SUP_DEV_TIMEOUT,
5641                          pmcraid_timeout_handler);
5642         return;
5643 }
5644
5645 /**
5646  * pmcraid_set_timestamp - set the timestamp to IOAFP
5647  *
5648  * @cmd: pointer to pmcraid_cmd structure
5649  *
5650  * Return Value
5651  *  0 for success or non-zero for failure cases
5652  */
5653 static void pmcraid_set_timestamp(struct pmcraid_cmd *cmd)
5654 {
5655         struct pmcraid_instance *pinstance = cmd->drv_inst;
5656         struct pmcraid_ioarcb *ioarcb = &cmd->ioa_cb->ioarcb;
5657         __be32 time_stamp_len = cpu_to_be32(PMCRAID_TIMESTAMP_LEN);
5658         struct pmcraid_ioadl_desc *ioadl = ioarcb->add_data.u.ioadl;
5659
5660         struct timeval tv;
5661         __le64 timestamp;
5662
5663         do_gettimeofday(&tv);
5664         timestamp = tv.tv_sec * 1000;
5665
5666         pinstance->timestamp_data->timestamp[0] = (__u8)(timestamp);
5667         pinstance->timestamp_data->timestamp[1] = (__u8)((timestamp) >> 8);
5668         pinstance->timestamp_data->timestamp[2] = (__u8)((timestamp) >> 16);
5669         pinstance->timestamp_data->timestamp[3] = (__u8)((timestamp) >> 24);
5670         pinstance->timestamp_data->timestamp[4] = (__u8)((timestamp) >> 32);
5671         pinstance->timestamp_data->timestamp[5] = (__u8)((timestamp)  >> 40);
5672
5673         pmcraid_reinit_cmdblk(cmd);
5674         ioarcb->request_type = REQ_TYPE_SCSI;
5675         ioarcb->resource_handle = cpu_to_le32(PMCRAID_IOA_RES_HANDLE);
5676         ioarcb->cdb[0] = PMCRAID_SCSI_SET_TIMESTAMP;
5677         ioarcb->cdb[1] = PMCRAID_SCSI_SERVICE_ACTION;
5678         memcpy(&(ioarcb->cdb[6]), &time_stamp_len, sizeof(time_stamp_len));
5679
5680         ioarcb->ioadl_bus_addr = cpu_to_le64((cmd->ioa_cb_bus_addr) +
5681                                         offsetof(struct pmcraid_ioarcb,
5682                                                 add_data.u.ioadl[0]));
5683         ioarcb->ioadl_length = cpu_to_le32(sizeof(struct pmcraid_ioadl_desc));
5684         ioarcb->ioarcb_bus_addr &= ~(0x1FULL);
5685
5686         ioarcb->request_flags0 |= NO_LINK_DESCS;
5687         ioarcb->request_flags0 |= TRANSFER_DIR_WRITE;
5688         ioarcb->data_transfer_length =
5689                 cpu_to_le32(sizeof(struct pmcraid_timestamp_data));
5690         ioadl = &(ioarcb->add_data.u.ioadl[0]);
5691         ioadl->flags = IOADL_FLAGS_LAST_DESC;
5692         ioadl->address = cpu_to_le64(pinstance->timestamp_data_baddr);
5693         ioadl->data_len = cpu_to_le32(sizeof(struct pmcraid_timestamp_data));
5694
5695         if (!pinstance->timestamp_error) {
5696                 pinstance->timestamp_error = 0;
5697                 pmcraid_send_cmd(cmd, pmcraid_set_supported_devs,
5698                          PMCRAID_INTERNAL_TIMEOUT, pmcraid_timeout_handler);
5699         } else {
5700                 pmcraid_send_cmd(cmd, pmcraid_return_cmd,
5701                          PMCRAID_INTERNAL_TIMEOUT, pmcraid_timeout_handler);
5702                 return;
5703         }
5704 }
5705
5706
5707 /**
5708  * pmcraid_init_res_table - Initialize the resource table
5709  * @cmd:  pointer to pmcraid command struct
5710  *
5711  * This function looks through the existing resource table, comparing
5712  * it with the config table. This function will take care of old/new
5713  * devices and schedule adding/removing them from the mid-layer
5714  * as appropriate.
5715  *
5716  * Return value
5717  *       None
5718  */
5719 static void pmcraid_init_res_table(struct pmcraid_cmd *cmd)
5720 {
5721         struct pmcraid_instance *pinstance = cmd->drv_inst;
5722         struct pmcraid_resource_entry *res, *temp;
5723         struct pmcraid_config_table_entry *cfgte;
5724         unsigned long lock_flags;
5725         int found, rc, i;
5726         u16 fw_version;
5727         LIST_HEAD(old_res);
5728
5729         if (pinstance->cfg_table->flags & MICROCODE_UPDATE_REQUIRED)
5730                 pmcraid_err("IOA requires microcode download\n");
5731
5732         fw_version = be16_to_cpu(pinstance->inq_data->fw_version);
5733
5734         /* resource list is protected by pinstance->resource_lock.
5735          * init_res_table can be called from probe (user-thread) or runtime
5736          * reset (timer/tasklet)
5737          */
5738         spin_lock_irqsave(&pinstance->resource_lock, lock_flags);
5739
5740         list_for_each_entry_safe(res, temp, &pinstance->used_res_q, queue)
5741                 list_move_tail(&res->queue, &old_res);
5742
5743         for (i = 0; i < pinstance->cfg_table->num_entries; i++) {
5744                 if (be16_to_cpu(pinstance->inq_data->fw_version) <=
5745                                                 PMCRAID_FW_VERSION_1)
5746                         cfgte = &pinstance->cfg_table->entries[i];
5747                 else
5748                         cfgte = (struct pmcraid_config_table_entry *)
5749                                         &pinstance->cfg_table->entries_ext[i];
5750
5751                 if (!pmcraid_expose_resource(fw_version, cfgte))
5752                         continue;
5753
5754                 found = 0;
5755
5756                 /* If this entry was already detected and initialized */
5757                 list_for_each_entry_safe(res, temp, &old_res, queue) {
5758
5759                         rc = memcmp(&res->cfg_entry.resource_address,
5760                                     &cfgte->resource_address,
5761                                     sizeof(cfgte->resource_address));
5762                         if (!rc) {
5763                                 list_move_tail(&res->queue,
5764                                                 &pinstance->used_res_q);
5765                                 found = 1;
5766                                 break;
5767                         }
5768                 }
5769
5770                 /* If this is new entry, initialize it and add it the queue */
5771                 if (!found) {
5772
5773                         if (list_empty(&pinstance->free_res_q)) {
5774                                 pmcraid_err("Too many devices attached\n");
5775                                 break;
5776                         }
5777
5778                         found = 1;
5779                         res = list_entry(pinstance->free_res_q.next,
5780                                          struct pmcraid_resource_entry, queue);
5781
5782                         res->scsi_dev = NULL;
5783                         res->change_detected = RES_CHANGE_ADD;
5784                         res->reset_progress = 0;
5785                         list_move_tail(&res->queue, &pinstance->used_res_q);
5786                 }
5787
5788                 /* copy new configuration table entry details into driver
5789                  * maintained resource entry
5790                  */
5791                 if (found) {
5792                         memcpy(&res->cfg_entry, cfgte,
5793                                         pinstance->config_table_entry_size);
5794                         pmcraid_info("New res type:%x, vset:%x, addr:%x:\n",
5795                                  res->cfg_entry.resource_type,
5796                                  (fw_version <= PMCRAID_FW_VERSION_1 ?
5797                                         res->cfg_entry.unique_flags1 :
5798                                                 res->cfg_entry.array_id & 0xFF),
5799                                  le32_to_cpu(res->cfg_entry.resource_address));
5800                 }
5801         }
5802
5803         /* Detect any deleted entries, mark them for deletion from mid-layer */
5804         list_for_each_entry_safe(res, temp, &old_res, queue) {
5805
5806                 if (res->scsi_dev) {
5807                         res->change_detected = RES_CHANGE_DEL;
5808                         res->cfg_entry.resource_handle =
5809                                 PMCRAID_INVALID_RES_HANDLE;
5810                         list_move_tail(&res->queue, &pinstance->used_res_q);
5811                 } else {
5812                         list_move_tail(&res->queue, &pinstance->free_res_q);
5813                 }
5814         }
5815
5816         /* release the resource list lock */
5817         spin_unlock_irqrestore(&pinstance->resource_lock, lock_flags);
5818         pmcraid_set_timestamp(cmd);
5819 }
5820
5821 /**
5822  * pmcraid_querycfg - Send a Query IOA Config to the adapter.
5823  * @cmd: pointer pmcraid_cmd struct
5824  *
5825  * This function sends a Query IOA Configuration command to the adapter to
5826  * retrieve the IOA configuration table.
5827  *
5828  * Return value:
5829  *      none
5830  */
5831 static void pmcraid_querycfg(struct pmcraid_cmd *cmd)
5832 {
5833         struct pmcraid_ioarcb *ioarcb = &cmd->ioa_cb->ioarcb;
5834         struct pmcraid_ioadl_desc *ioadl = ioarcb->add_data.u.ioadl;
5835         struct pmcraid_instance *pinstance = cmd->drv_inst;
5836         int cfg_table_size = cpu_to_be32(sizeof(struct pmcraid_config_table));
5837
5838         if (be16_to_cpu(pinstance->inq_data->fw_version) <=
5839                                         PMCRAID_FW_VERSION_1)
5840                 pinstance->config_table_entry_size =
5841                         sizeof(struct pmcraid_config_table_entry);
5842         else
5843                 pinstance->config_table_entry_size =
5844                         sizeof(struct pmcraid_config_table_entry_ext);
5845
5846         ioarcb->request_type = REQ_TYPE_IOACMD;
5847         ioarcb->resource_handle = cpu_to_le32(PMCRAID_IOA_RES_HANDLE);
5848
5849         ioarcb->cdb[0] = PMCRAID_QUERY_IOA_CONFIG;
5850
5851         /* firmware requires 4-byte length field, specified in B.E format */
5852         memcpy(&(ioarcb->cdb[10]), &cfg_table_size, sizeof(cfg_table_size));
5853
5854         /* Since entire config table can be described by single IOADL, it can
5855          * be part of IOARCB itself
5856          */
5857         ioarcb->ioadl_bus_addr = cpu_to_le64((cmd->ioa_cb_bus_addr) +
5858                                         offsetof(struct pmcraid_ioarcb,
5859                                                 add_data.u.ioadl[0]));
5860         ioarcb->ioadl_length = cpu_to_le32(sizeof(struct pmcraid_ioadl_desc));
5861         ioarcb->ioarcb_bus_addr &= ~(0x1FULL);
5862
5863         ioarcb->request_flags0 |= NO_LINK_DESCS;
5864         ioarcb->data_transfer_length =
5865                 cpu_to_le32(sizeof(struct pmcraid_config_table));
5866
5867         ioadl = &(ioarcb->add_data.u.ioadl[0]);
5868         ioadl->flags = IOADL_FLAGS_LAST_DESC;
5869         ioadl->address = cpu_to_le64(pinstance->cfg_table_bus_addr);
5870         ioadl->data_len = cpu_to_le32(sizeof(struct pmcraid_config_table));
5871
5872         pmcraid_send_cmd(cmd, pmcraid_init_res_table,
5873                          PMCRAID_INTERNAL_TIMEOUT, pmcraid_timeout_handler);
5874 }
5875
5876
5877 /**
5878  * pmcraid_probe - PCI probe entry pointer for PMC MaxRAID controller driver
5879  * @pdev: pointer to pci device structure
5880  * @dev_id: pointer to device ids structure
5881  *
5882  * Return Value
5883  *      returns 0 if the device is claimed and successfully configured.
5884  *      returns non-zero error code in case of any failure
5885  */
5886 static int __devinit pmcraid_probe(
5887         struct pci_dev *pdev,
5888         const struct pci_device_id *dev_id
5889 )
5890 {
5891         struct pmcraid_instance *pinstance;
5892         struct Scsi_Host *host;
5893         void __iomem *mapped_pci_addr;
5894         int rc = PCIBIOS_SUCCESSFUL;
5895
5896         if (atomic_read(&pmcraid_adapter_count) >= PMCRAID_MAX_ADAPTERS) {
5897                 pmcraid_err
5898                         ("maximum number(%d) of supported adapters reached\n",
5899                          atomic_read(&pmcraid_adapter_count));
5900                 return -ENOMEM;
5901         }
5902
5903         atomic_inc(&pmcraid_adapter_count);
5904         rc = pci_enable_device(pdev);
5905
5906         if (rc) {
5907                 dev_err(&pdev->dev, "Cannot enable adapter\n");
5908                 atomic_dec(&pmcraid_adapter_count);
5909                 return rc;
5910         }
5911
5912         dev_info(&pdev->dev,
5913                 "Found new IOA(%x:%x), Total IOA count: %d\n",
5914                  pdev->vendor, pdev->device,
5915                  atomic_read(&pmcraid_adapter_count));
5916
5917         rc = pci_request_regions(pdev, PMCRAID_DRIVER_NAME);
5918
5919         if (rc < 0) {
5920                 dev_err(&pdev->dev,
5921                         "Couldn't register memory range of registers\n");
5922                 goto out_disable_device;
5923         }
5924
5925         mapped_pci_addr = pci_iomap(pdev, 0, 0);
5926
5927         if (!mapped_pci_addr) {
5928                 dev_err(&pdev->dev, "Couldn't map PCI registers memory\n");
5929                 rc = -ENOMEM;
5930                 goto out_release_regions;
5931         }
5932
5933         pci_set_master(pdev);
5934
5935         /* Firmware requires the system bus address of IOARCB to be within
5936          * 32-bit addressable range though it has 64-bit IOARRIN register.
5937          * However, firmware supports 64-bit streaming DMA buffers, whereas
5938          * coherent buffers are to be 32-bit. Since pci_alloc_consistent always
5939          * returns memory within 4GB (if not, change this logic), coherent
5940          * buffers are within firmware acceptable address ranges.
5941          */
5942         if ((sizeof(dma_addr_t) == 4) ||
5943             pci_set_dma_mask(pdev, DMA_BIT_MASK(64)))
5944                 rc = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
5945
5946         /* firmware expects 32-bit DMA addresses for IOARRIN register; set 32
5947          * bit mask for pci_alloc_consistent to return addresses within 4GB
5948          */
5949         if (rc == 0)
5950                 rc = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
5951
5952         if (rc != 0) {
5953                 dev_err(&pdev->dev, "Failed to set PCI DMA mask\n");
5954                 goto cleanup_nomem;
5955         }
5956
5957         host = scsi_host_alloc(&pmcraid_host_template,
5958                                 sizeof(struct pmcraid_instance));
5959
5960         if (!host) {
5961                 dev_err(&pdev->dev, "scsi_host_alloc failed!\n");
5962                 rc = -ENOMEM;
5963                 goto cleanup_nomem;
5964         }
5965
5966         host->max_id = PMCRAID_MAX_NUM_TARGETS_PER_BUS;
5967         host->max_lun = PMCRAID_MAX_NUM_LUNS_PER_TARGET;
5968         host->unique_id = host->host_no;
5969         host->max_channel = PMCRAID_MAX_BUS_TO_SCAN;
5970         host->max_cmd_len = PMCRAID_MAX_CDB_LEN;
5971
5972         /* zero out entire instance structure */
5973         pinstance = (struct pmcraid_instance *)host->hostdata;
5974         memset(pinstance, 0, sizeof(*pinstance));
5975
5976         pinstance->chip_cfg =
5977                 (struct pmcraid_chip_details *)(dev_id->driver_data);
5978
5979         rc = pmcraid_init_instance(pdev, host, mapped_pci_addr);
5980
5981         if (rc < 0) {
5982                 dev_err(&pdev->dev, "failed to initialize adapter instance\n");
5983                 goto out_scsi_host_put;
5984         }
5985
5986         pci_set_drvdata(pdev, pinstance);
5987
5988         /* Save PCI config-space for use following the reset */
5989         rc = pci_save_state(pinstance->pdev);
5990
5991         if (rc != 0) {
5992                 dev_err(&pdev->dev, "Failed to save PCI config space\n");
5993                 goto out_scsi_host_put;
5994         }
5995
5996         pmcraid_disable_interrupts(pinstance, ~0);
5997
5998         rc = pmcraid_register_interrupt_handler(pinstance);
5999
6000         if (rc) {
6001                 dev_err(&pdev->dev, "couldn't register interrupt handler\n");
6002                 goto out_scsi_host_put;
6003         }
6004
6005         pmcraid_init_tasklets(pinstance);
6006
6007         /* allocate verious buffers used by LLD.*/
6008         rc = pmcraid_init_buffers(pinstance);
6009
6010         if (rc) {
6011                 pmcraid_err("couldn't allocate memory blocks\n");
6012                 goto out_unregister_isr;
6013         }
6014
6015         /* check the reset type required */
6016         pmcraid_reset_type(pinstance);
6017
6018         pmcraid_enable_interrupts(pinstance, PMCRAID_PCI_INTERRUPTS);
6019
6020         /* Start IOA firmware initialization and bring card to Operational
6021          * state.
6022          */
6023         pmcraid_info("starting IOA initialization sequence\n");
6024         if (pmcraid_reset_bringup(pinstance)) {
6025                 dev_err(&pdev->dev, "couldn't initialize IOA\n");
6026                 rc = 1;
6027                 goto out_release_bufs;
6028         }
6029
6030         /* Add adapter instance into mid-layer list */
6031         rc = scsi_add_host(pinstance->host, &pdev->dev);
6032         if (rc != 0) {
6033                 pmcraid_err("couldn't add host into mid-layer: %d\n", rc);
6034                 goto out_release_bufs;
6035         }
6036
6037         scsi_scan_host(pinstance->host);
6038
6039         rc = pmcraid_setup_chrdev(pinstance);
6040
6041         if (rc != 0) {
6042                 pmcraid_err("couldn't create mgmt interface, error: %x\n",
6043                              rc);
6044                 goto out_remove_host;
6045         }
6046
6047         /* Schedule worker thread to handle CCN and take care of adding and
6048          * removing devices to OS
6049          */
6050         atomic_set(&pinstance->expose_resources, 1);
6051         schedule_work(&pinstance->worker_q);
6052         return rc;
6053
6054 out_remove_host:
6055         scsi_remove_host(host);
6056
6057 out_release_bufs:
6058         pmcraid_release_buffers(pinstance);
6059
6060 out_unregister_isr:
6061         pmcraid_kill_tasklets(pinstance);
6062         pmcraid_unregister_interrupt_handler(pinstance);
6063
6064 out_scsi_host_put:
6065         scsi_host_put(host);
6066
6067 cleanup_nomem:
6068         iounmap(mapped_pci_addr);
6069
6070 out_release_regions:
6071         pci_release_regions(pdev);
6072
6073 out_disable_device:
6074         atomic_dec(&pmcraid_adapter_count);
6075         pci_set_drvdata(pdev, NULL);
6076         pci_disable_device(pdev);
6077         return -ENODEV;
6078 }
6079
6080 /*
6081  * PCI driver structure of pcmraid driver
6082  */
6083 static struct pci_driver pmcraid_driver = {
6084         .name = PMCRAID_DRIVER_NAME,
6085         .id_table = pmcraid_pci_table,
6086         .probe = pmcraid_probe,
6087         .remove = pmcraid_remove,
6088         .suspend = pmcraid_suspend,
6089         .resume = pmcraid_resume,
6090         .shutdown = pmcraid_shutdown
6091 };
6092
6093 /**
6094  * pmcraid_init - module load entry point
6095  */
6096 static int __init pmcraid_init(void)
6097 {
6098         dev_t dev;
6099         int error;
6100
6101         pmcraid_info("%s Device Driver version: %s\n",
6102                          PMCRAID_DRIVER_NAME, PMCRAID_DRIVER_VERSION);
6103
6104         error = alloc_chrdev_region(&dev, 0,
6105                                     PMCRAID_MAX_ADAPTERS,
6106                                     PMCRAID_DEVFILE);
6107
6108         if (error) {
6109                 pmcraid_err("failed to get a major number for adapters\n");
6110                 goto out_init;
6111         }
6112
6113         pmcraid_major = MAJOR(dev);
6114         pmcraid_class = class_create(THIS_MODULE, PMCRAID_DEVFILE);
6115
6116         if (IS_ERR(pmcraid_class)) {
6117                 error = PTR_ERR(pmcraid_class);
6118                 pmcraid_err("failed to register with with sysfs, error = %x\n",
6119                             error);
6120                 goto out_unreg_chrdev;
6121         }
6122
6123         error = pmcraid_netlink_init();
6124
6125         if (error)
6126                 goto out_unreg_chrdev;
6127
6128         error = pci_register_driver(&pmcraid_driver);
6129
6130         if (error == 0)
6131                 goto out_init;
6132
6133         pmcraid_err("failed to register pmcraid driver, error = %x\n",
6134                      error);
6135         class_destroy(pmcraid_class);
6136         pmcraid_netlink_release();
6137
6138 out_unreg_chrdev:
6139         unregister_chrdev_region(MKDEV(pmcraid_major, 0), PMCRAID_MAX_ADAPTERS);
6140
6141 out_init:
6142         return error;
6143 }
6144
6145 /**
6146  * pmcraid_exit - module unload entry point
6147  */
6148 static void __exit pmcraid_exit(void)
6149 {
6150         pmcraid_netlink_release();
6151         unregister_chrdev_region(MKDEV(pmcraid_major, 0),
6152                                  PMCRAID_MAX_ADAPTERS);
6153         pci_unregister_driver(&pmcraid_driver);
6154         class_destroy(pmcraid_class);
6155 }
6156
6157 module_init(pmcraid_init);
6158 module_exit(pmcraid_exit);