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