VServer 1.9.2 (patch-2.6.8.1-vs1.9.2.diff)
[linux-2.6.git] / drivers / scsi / qla2xxx / qla_os.c
1 /*
2  *                  QLOGIC LINUX SOFTWARE
3  *
4  * QLogic ISP2x00 device driver for Linux 2.6.x
5  * Copyright (C) 2003-2004 QLogic Corporation
6  * (www.qlogic.com)
7  *
8  * This program is free software; you can redistribute it and/or modify it
9  * under the terms of the GNU General Public License as published by the
10  * Free Software Foundation; either version 2, or (at your option) any
11  * later version.
12  *
13  * This program is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * General Public License for more details.
17  *
18  */
19 #include "qla_def.h"
20
21 #include <linux/moduleparam.h>
22 #include <linux/vmalloc.h>
23 #include <linux/smp_lock.h>
24
25 #include <scsi/scsi_tcq.h>
26 #include <scsi/scsicam.h>
27 #include <scsi/scsi_transport.h>
28 #include <scsi/scsi_transport_fc.h>
29
30 /*
31  * Driver version
32  */
33 char qla2x00_version_str[40];
34
35 /*
36  * SRB allocation cache
37  */
38 char srb_cachep_name[16];
39 kmem_cache_t *srb_cachep;
40
41 /*
42  * Stats for all adpaters.
43  */
44 struct _qla2x00stats qla2x00_stats;
45
46 /*
47  * Ioctl related information.
48  */
49 int num_hosts;
50 int apiHBAInstance;
51
52 /*
53  * Module parameter information and variables
54  */
55 int ql2xmaxqdepth;
56 module_param(ql2xmaxqdepth, int, S_IRUGO|S_IWUSR);
57 MODULE_PARM_DESC(ql2xmaxqdepth,
58                 "Maximum queue depth to report for target devices.");
59
60 int ql2xlogintimeout = 20;
61 module_param(ql2xlogintimeout, int, S_IRUGO|S_IRUSR);
62 MODULE_PARM_DESC(ql2xlogintimeout,
63                 "Login timeout value in seconds.");
64
65 int qlport_down_retry;
66 module_param(qlport_down_retry, int, S_IRUGO|S_IRUSR);
67 MODULE_PARM_DESC(qlport_down_retry,
68                 "Maximum number of command retries to a port that returns"
69                 "a PORT-DOWN status.");
70
71 int ql2xretrycount = 20;
72 module_param(ql2xretrycount, int, S_IRUGO|S_IWUSR);
73 MODULE_PARM_DESC(ql2xretrycount,
74                 "Maximum number of mid-layer retries allowed for a command.  "
75                 "Default value is 20, ");
76
77 int displayConfig;
78 module_param(displayConfig, int, S_IRUGO|S_IWUSR);
79 MODULE_PARM_DESC(displayConfig,
80                 "If 1 then display the configuration used in /etc/modprobe.conf.");
81
82 int ql2xplogiabsentdevice;
83 module_param(ql2xplogiabsentdevice, int, S_IRUGO|S_IWUSR);
84 MODULE_PARM_DESC(ql2xplogiabsentdevice,
85                 "Option to enable PLOGI to devices that are not present after "
86                 "a Fabric scan.  This is needed for several broken switches."
87                 "Default is 0 - no PLOGI. 1 - perfom PLOGI.");
88
89 int ql2xenablezio = 0;
90 module_param(ql2xenablezio, int, S_IRUGO|S_IRUSR);
91 MODULE_PARM_DESC(ql2xenablezio,
92                 "Option to enable ZIO:If 1 then enable it otherwise" 
93                 " use the default set in the NVRAM."
94                 " Default is 0 : disabled");
95
96 int ql2xintrdelaytimer = 10;
97 module_param(ql2xintrdelaytimer, int, S_IRUGO|S_IRUSR);
98 MODULE_PARM_DESC(ql2xintrdelaytimer,
99                 "ZIO: Waiting time for Firmware before it generates an "
100                 "interrupt to the host to notify completion of request.");
101
102 int ConfigRequired;
103 module_param(ConfigRequired, int, S_IRUGO|S_IRUSR);
104 MODULE_PARM_DESC(ConfigRequired,
105                 "If 1, then only configured devices passed in through the"
106                 "ql2xopts parameter will be presented to the OS");
107
108 int Bind = BIND_BY_PORT_NAME;
109 module_param(Bind, int, S_IRUGO|S_IRUSR);
110 MODULE_PARM_DESC(Bind,
111                 "Target persistent binding method: "
112                 "0 by Portname (default); 1 by PortID; 2 by Nodename. ");
113
114 int ql2xsuspendcount = SUSPEND_COUNT;
115 module_param(ql2xsuspendcount, int, S_IRUGO|S_IWUSR);
116 MODULE_PARM_DESC(ql2xsuspendcount,
117                 "Number of 6-second suspend iterations to perform while a "
118                 "target returns a <NOT READY> status.  Default is 10 "
119                 "iterations.");
120
121 int ql2xdoinitscan = 1;
122 module_param(ql2xdoinitscan, int, S_IRUGO|S_IWUSR);
123 MODULE_PARM_DESC(ql2xdoinitscan,
124                 "Signal mid-layer to perform scan after driver load: 0 -- no "
125                 "signal sent to mid-layer.");
126
127 int ql2xloginretrycount = 0;
128 module_param(ql2xloginretrycount, int, S_IRUGO|S_IRUSR);
129 MODULE_PARM_DESC(ql2xloginretrycount,
130                 "Specify an alternate value for the NVRAM login retry count.");
131
132 /*
133  * Proc structures and functions
134  */
135 struct info_str {
136         char    *buffer;
137         int     length;
138         off_t   offset;
139         int     pos;
140 };
141
142 static void copy_mem_info(struct info_str *, char *, int);
143 static int copy_info(struct info_str *, char *, ...);
144
145 static void qla2x00_free_device(scsi_qla_host_t *);
146
147 static void qla2x00_config_dma_addressing(scsi_qla_host_t *ha);
148
149 /*
150  * SCSI host template entry points 
151  */
152 static int qla2xxx_slave_configure(struct scsi_device * device);
153 static int qla2xxx_eh_abort(struct scsi_cmnd *);
154 static int qla2xxx_eh_device_reset(struct scsi_cmnd *);
155 static int qla2xxx_eh_bus_reset(struct scsi_cmnd *);
156 static int qla2xxx_eh_host_reset(struct scsi_cmnd *);
157 static int qla2x00_loop_reset(scsi_qla_host_t *ha);
158 static int qla2x00_device_reset(scsi_qla_host_t *, fc_port_t *);
159
160 static int qla2x00_proc_info(struct Scsi_Host *, char *, char **,
161     off_t, int, int);
162
163 static struct scsi_host_template qla2x00_driver_template = {
164         .module                 = THIS_MODULE,
165         .name                   = "qla2xxx",
166         .proc_name              = "qla2xxx",
167         .proc_info              = qla2x00_proc_info,
168         .queuecommand           = qla2x00_queuecommand,
169
170         .eh_abort_handler       = qla2xxx_eh_abort,
171         .eh_device_reset_handler = qla2xxx_eh_device_reset,
172         .eh_bus_reset_handler   = qla2xxx_eh_bus_reset,
173         .eh_host_reset_handler  = qla2xxx_eh_host_reset,
174
175         .slave_configure        = qla2xxx_slave_configure,
176
177         .this_id                = -1,
178         .cmd_per_lun            = 3,
179         .use_clustering         = ENABLE_CLUSTERING,
180         .sg_tablesize           = SG_ALL,
181
182         /*
183          * The RISC allows for each command to transfer (2^32-1) bytes of data,
184          * which equates to 0x800000 sectors.
185          */
186         .max_sectors            = 0xFFFF,
187 };
188
189 static struct scsi_transport_template *qla2xxx_transport_template = NULL;
190
191 static void qla2x00_display_fc_names(scsi_qla_host_t *);
192
193 /* TODO Convert to inlines
194  *
195  * Timer routines
196  */
197 #define WATCH_INTERVAL          1       /* number of seconds */
198
199 static void qla2x00_timer(scsi_qla_host_t *);
200
201 static __inline__ void qla2x00_start_timer(scsi_qla_host_t *,
202     void *, unsigned long);
203 static __inline__ void qla2x00_restart_timer(scsi_qla_host_t *, unsigned long);
204 static __inline__ void qla2x00_stop_timer(scsi_qla_host_t *);
205
206 static inline void
207 qla2x00_start_timer(scsi_qla_host_t *ha, void *func, unsigned long interval)
208 {
209         init_timer(&ha->timer);
210         ha->timer.expires = jiffies + interval * HZ;
211         ha->timer.data = (unsigned long)ha;
212         ha->timer.function = (void (*)(unsigned long))func;
213         add_timer(&ha->timer);
214         ha->timer_active = 1;
215 }
216
217 static inline void
218 qla2x00_restart_timer(scsi_qla_host_t *ha, unsigned long interval)
219 {
220         mod_timer(&ha->timer, jiffies + interval * HZ);
221 }
222
223 static __inline__ void
224 qla2x00_stop_timer(scsi_qla_host_t *ha)
225 {
226         del_timer_sync(&ha->timer);
227         ha->timer_active = 0;
228 }
229
230 void qla2x00_cmd_timeout(srb_t *);
231
232 static __inline__ void qla2x00_callback(scsi_qla_host_t *, struct scsi_cmnd *);
233 static __inline__ void sp_put(struct scsi_qla_host * ha, srb_t *sp);
234 static __inline__ void sp_get(struct scsi_qla_host * ha, srb_t *sp);
235 static __inline__ void
236 qla2x00_delete_from_done_queue(scsi_qla_host_t *, srb_t *); 
237
238 /**************************************************************************
239 * sp_put
240 *
241 * Description:
242 *   Decrement reference count and call the callback if we're the last
243 *   owner of the specified sp. Will get the host_lock before calling
244 *   the callback.
245 *
246 * Input:
247 *   ha - pointer to the scsi_qla_host_t where the callback is to occur.
248 *   sp - pointer to srb_t structure to use.
249 *
250 * Returns:
251 *
252 **************************************************************************/
253 static inline void
254 sp_put(struct scsi_qla_host * ha, srb_t *sp)
255 {
256         if (atomic_read(&sp->ref_count) == 0) {
257                 qla_printk(KERN_INFO, ha,
258                         "%s(): **** SP->ref_count not zero\n",
259                         __func__);
260                 DEBUG2(BUG();)
261
262                 return;
263         }
264
265         if (!atomic_dec_and_test(&sp->ref_count)) {
266                 return;
267         }
268
269         qla2x00_callback(ha, sp->cmd);
270 }
271
272 /**************************************************************************
273 * sp_get
274 *
275 * Description:
276 *   Increment reference count of the specified sp.
277 *
278 * Input:
279 *   sp - pointer to srb_t structure to use.
280 *
281 * Returns:
282 *
283 **************************************************************************/
284 static inline void
285 sp_get(struct scsi_qla_host * ha, srb_t *sp)
286 {
287         atomic_inc(&sp->ref_count);
288
289         if (atomic_read(&sp->ref_count) > 2) {
290                 qla_printk(KERN_INFO, ha,
291                         "%s(): **** SP->ref_count greater than two\n",
292                         __func__);
293                 DEBUG2(BUG();)
294
295                 return;
296         }
297 }
298
299 /*
300 * qla2x00_callback
301 *      Returns the completed SCSI command to LINUX.
302 *
303 * Input:
304 *       ha -- Host adapter structure
305 *       cmd -- SCSI mid-level command structure.
306 * Returns:
307 *      None
308 * Note:From failover point of view we always get the sp
309 *      from vis_ha pool in queuecommand.So when we put it 
310 *      back to the pool it has to be the vis_ha.         
311 *      So rely on struct scsi_cmnd to get the vis_ha and not on sp.                     
312 */
313 static inline void
314 qla2x00_callback(scsi_qla_host_t *ha, struct scsi_cmnd *cmd)
315 {
316         srb_t *sp = (srb_t *) CMD_SP(cmd);
317         scsi_qla_host_t *vis_ha;
318         os_lun_t *lq;
319         int got_sense;
320         unsigned long   cpu_flags = 0;
321
322         cmd->host_scribble = (unsigned char *) NULL;
323         vis_ha = (scsi_qla_host_t *) cmd->device->host->hostdata;
324
325         if (sp == NULL) {
326                 qla_printk(KERN_INFO, ha,
327                         "%s(): **** CMD derives a NULL SP\n",
328                         __func__);
329                 DEBUG2(BUG();)
330                 return;
331         }
332
333         /*
334          * If command status is not DID_BUS_BUSY then go ahead and freed sp.
335          */
336         /*
337          * Cancel command timeout
338          */
339         qla2x00_delete_timer_from_cmd(sp);
340
341         /*
342          * Put SP back in the free queue
343          */
344         sp->cmd   = NULL;
345         CMD_SP(cmd) = NULL;
346         lq = sp->lun_queue;
347         got_sense = (sp->flags & SRB_GOT_SENSE)? 1: 0;
348         add_to_free_queue(vis_ha, sp);
349
350         if (host_byte(cmd->result) == DID_OK) {
351                 /* device ok */
352                 ha->total_bytes += cmd->bufflen;
353                 if (!got_sense) {
354                         /* If lun was suspended then clear retry count */
355                         spin_lock_irqsave(&lq->q_lock, cpu_flags);
356                         if (!test_bit(LUN_EXEC_DELAYED, &lq->q_flag))
357                                 lq->q_state = LUN_STATE_READY;
358                         spin_unlock_irqrestore(&lq->q_lock, cpu_flags);
359                 }
360         } else if (host_byte(cmd->result) == DID_ERROR) {
361                 /* device error */
362                 ha->total_dev_errs++;
363         }
364
365         /* Call the mid-level driver interrupt handler */
366         (*(cmd)->scsi_done)(cmd);
367 }
368
369 static inline void 
370 qla2x00_delete_from_done_queue(scsi_qla_host_t *dest_ha, srb_t *sp) 
371 {
372         /* remove command from done list */
373         list_del_init(&sp->list);
374         dest_ha->done_q_cnt--;
375         sp->state = SRB_NO_QUEUE_STATE;
376
377         if (sp->flags & SRB_DMA_VALID) {
378                 sp->flags &= ~SRB_DMA_VALID;
379
380                 /* Release memory used for this I/O */
381                 if (sp->cmd->use_sg) {
382                         pci_unmap_sg(dest_ha->pdev, sp->cmd->request_buffer,
383                             sp->cmd->use_sg, sp->cmd->sc_data_direction);
384                 } else if (sp->cmd->request_bufflen) {
385                         pci_unmap_page(dest_ha->pdev, sp->dma_handle,
386                             sp->cmd->request_bufflen,
387                             sp->cmd->sc_data_direction);
388                 }
389         }
390 }
391
392 static int qla2x00_do_dpc(void *data);
393
394 static void qla2x00_rst_aen(scsi_qla_host_t *);
395
396 static uint8_t qla2x00_mem_alloc(scsi_qla_host_t *);
397 static void qla2x00_mem_free(scsi_qla_host_t *ha);
398 int qla2x00_allocate_sp_pool( scsi_qla_host_t *ha);
399 void qla2x00_free_sp_pool(scsi_qla_host_t *ha);
400
401 static ssize_t qla2x00_sysfs_read_fw_dump(struct kobject *, char *, loff_t,
402     size_t);
403 static ssize_t qla2x00_sysfs_write_fw_dump(struct kobject *, char *, loff_t,
404     size_t);
405 static struct bin_attribute sysfs_fw_dump_attr = {
406         .attr = {
407                 .name = "fw_dump",
408                 .mode = S_IRUSR | S_IWUSR,
409                 .owner = THIS_MODULE,
410         },
411         .size = 0,
412         .read = qla2x00_sysfs_read_fw_dump,
413         .write = qla2x00_sysfs_write_fw_dump,
414 };
415 static ssize_t qla2x00_sysfs_read_nvram(struct kobject *, char *, loff_t,
416     size_t);
417 static ssize_t qla2x00_sysfs_write_nvram(struct kobject *, char *, loff_t,
418     size_t);
419 static struct bin_attribute sysfs_nvram_attr = {
420         .attr = {
421                 .name = "nvram",
422                 .mode = S_IRUSR | S_IWUSR,
423                 .owner = THIS_MODULE,
424         },
425         .size = sizeof(nvram_t),
426         .read = qla2x00_sysfs_read_nvram,
427         .write = qla2x00_sysfs_write_nvram,
428 };
429
430
431 int
432 qla2x00_set_info(char *buffer, int length, struct Scsi_Host *shost)
433 {
434         return (-ENOSYS);  /* Currently this is a no-op */
435 }
436
437 /* -------------------------------------------------------------------------- */
438
439
440 /* SysFS attributes. */
441 static ssize_t qla2x00_sysfs_read_fw_dump(struct kobject *kobj, char *buf,
442     loff_t off, size_t count)
443 {
444         struct scsi_qla_host *ha = to_qla_host(dev_to_shost(container_of(kobj,
445             struct device, kobj)));
446
447         if (ha->fw_dump_reading == 0)
448                 return 0;
449         if (off > ha->fw_dump_buffer_len)
450                 return 0;
451         if (off + count > ha->fw_dump_buffer_len)
452                 count = ha->fw_dump_buffer_len - off;
453
454         memcpy(buf, &ha->fw_dump_buffer[off], count);
455
456         return (count);
457 }
458
459 static ssize_t qla2x00_sysfs_write_fw_dump(struct kobject *kobj, char *buf,
460     loff_t off, size_t count)
461 {
462         struct scsi_qla_host *ha = to_qla_host(dev_to_shost(container_of(kobj,
463             struct device, kobj)));
464         int reading;
465         uint32_t dump_size;
466
467         if (off != 0)
468                 return (0);
469
470         reading = simple_strtol(buf, NULL, 10);
471         switch (reading) {
472         case 0:
473                 if (ha->fw_dump_reading == 1) {
474                         qla_printk(KERN_INFO, ha,
475                             "Firmware dump cleared on (%ld).\n",
476                             ha->host_no);
477
478                         vfree(ha->fw_dump_buffer);
479                         free_pages((unsigned long)ha->fw_dump,
480                             ha->fw_dump_order);
481
482                         ha->fw_dump_reading = 0;
483                         ha->fw_dump_buffer = NULL;
484                         ha->fw_dump = NULL;
485                 }
486                 break;
487         case 1:
488                 if (ha->fw_dump != NULL && !ha->fw_dump_reading) {
489                         ha->fw_dump_reading = 1;
490
491                         dump_size = FW_DUMP_SIZE_1M;
492                         if (ha->fw_memory_size < 0x20000) 
493                                 dump_size = FW_DUMP_SIZE_128K;
494                         else if (ha->fw_memory_size < 0x80000) 
495                                 dump_size = FW_DUMP_SIZE_512K;
496                         ha->fw_dump_buffer = (char *)vmalloc(dump_size);
497                         if (ha->fw_dump_buffer == NULL) {
498                                 qla_printk(KERN_WARNING, ha,
499                                     "Unable to allocate memory for firmware "
500                                     "dump buffer (%d).\n", dump_size);
501
502                                 ha->fw_dump_reading = 0;
503                                 return (count);
504                         }
505                         qla_printk(KERN_INFO, ha,
506                             "Firmware dump ready for read on (%ld).\n",
507                             ha->host_no);
508                         memset(ha->fw_dump_buffer, 0, dump_size);
509                         if (IS_QLA2100(ha) || IS_QLA2200(ha))
510                                 qla2100_ascii_fw_dump(ha);
511                         else
512                                 qla2300_ascii_fw_dump(ha);
513                         ha->fw_dump_buffer_len = strlen(ha->fw_dump_buffer);
514                 }
515                 break;
516         }
517         return (count);
518 }
519
520 static ssize_t qla2x00_sysfs_read_nvram(struct kobject *kobj, char *buf,
521     loff_t off, size_t count)
522 {
523         struct scsi_qla_host *ha = to_qla_host(dev_to_shost(container_of(kobj,
524             struct device, kobj)));
525         uint16_t        *witer;
526         unsigned long   flags;
527         uint16_t        cnt;
528
529         if (!capable(CAP_SYS_ADMIN) || off != 0 || count != sizeof(nvram_t))
530                 return 0;
531
532         /* Read NVRAM. */
533         spin_lock_irqsave(&ha->hardware_lock, flags);
534         qla2x00_lock_nvram_access(ha);
535         witer = (uint16_t *)buf;
536         for (cnt = 0; cnt < count / 2; cnt++) {
537                 *witer = cpu_to_le16(qla2x00_get_nvram_word(ha,
538                     cnt+ha->nvram_base));
539                 witer++;
540         }
541         qla2x00_unlock_nvram_access(ha);
542         spin_unlock_irqrestore(&ha->hardware_lock, flags);
543
544         return (count);
545 }
546
547 static ssize_t qla2x00_sysfs_write_nvram(struct kobject *kobj, char *buf,
548     loff_t off, size_t count)
549 {
550         struct scsi_qla_host *ha = to_qla_host(dev_to_shost(container_of(kobj,
551             struct device, kobj)));
552         uint8_t         *iter;
553         uint16_t        *witer;
554         unsigned long   flags;
555         uint16_t        cnt;
556         uint8_t         chksum;
557
558         if (!capable(CAP_SYS_ADMIN) || off != 0 || count != sizeof(nvram_t))
559                 return 0;
560
561         /* Checksum NVRAM. */
562         iter = (uint8_t *)buf;
563         chksum = 0;
564         for (cnt = 0; cnt < count - 1; cnt++)
565                 chksum += *iter++;
566         chksum = ~chksum + 1;
567         *iter = chksum;
568
569         /* Write NVRAM. */
570         spin_lock_irqsave(&ha->hardware_lock, flags);
571         qla2x00_lock_nvram_access(ha);
572         witer = (uint16_t *)buf;
573         for (cnt = 0; cnt < count / 2; cnt++) {
574                 qla2x00_write_nvram_word(ha, cnt+ha->nvram_base,
575                     cpu_to_le16(*witer));
576                 witer++;
577         }
578         qla2x00_unlock_nvram_access(ha);
579         spin_unlock_irqrestore(&ha->hardware_lock, flags);
580
581         return (count);
582 }
583
584 /* -------------------------------------------------------------------------- */
585 char *
586 qla2x00_get_pci_info_str(struct scsi_qla_host *ha, char *str)
587 {
588         static char *pci_bus_modes[] = {
589                 "33", "66", "100", "133",
590         };
591         uint16_t pci_bus;
592
593         strcpy(str, "PCI");
594         pci_bus = (ha->pci_attr & (BIT_9 | BIT_10)) >> 9;
595         if (pci_bus) {
596                 strcat(str, "-X (");
597                 strcat(str, pci_bus_modes[pci_bus]);
598         } else {
599                 pci_bus = (ha->pci_attr & BIT_8) >> 8;
600                 strcat(str, " (");
601                 strcat(str, pci_bus_modes[pci_bus]);
602         }
603         strcat(str, " MHz)");
604
605         return (str);
606 }
607
608 char *
609 qla2x00_get_fw_version_str(struct scsi_qla_host *ha, char *str)
610 {
611         char un_str[10];
612         
613         sprintf(str, "%d.%02d.%02d ", ha->fw_major_version,
614             ha->fw_minor_version,
615             ha->fw_subminor_version);
616
617         if (ha->fw_attributes & BIT_9) {
618                 strcat(str, "FLX");
619                 return (str);
620         }
621
622         switch (ha->fw_attributes & 0xFF) {
623         case 0x7:
624                 strcat(str, "EF");
625                 break;
626         case 0x17:
627                 strcat(str, "TP");
628                 break;
629         case 0x37:
630                 strcat(str, "IP");
631                 break;
632         case 0x77:
633                 strcat(str, "VI");
634                 break;
635         default:
636                 sprintf(un_str, "(%x)", ha->fw_attributes);
637                 strcat(str, un_str);
638                 break;
639         }
640         if (ha->fw_attributes & 0x100)
641                 strcat(str, "X");
642
643         return (str);
644 }
645
646 /**************************************************************************
647 * qla2x00_queuecommand
648 *
649 * Description:
650 *     Queue a command to the controller.
651 *
652 * Input:
653 *     cmd - pointer to Scsi cmd structure
654 *     fn - pointer to Scsi done function
655 *
656 * Returns:
657 *   0 - Always
658 *
659 * Note:
660 * The mid-level driver tries to ensures that queuecommand never gets invoked
661 * concurrently with itself or the interrupt handler (although the
662 * interrupt handler may call this routine as part of request-completion
663 * handling).
664 **************************************************************************/
665 int
666 qla2x00_queuecommand(struct scsi_cmnd *cmd, void (*fn)(struct scsi_cmnd *))
667 {
668         fc_port_t       *fcport;
669         os_lun_t        *lq;
670         os_tgt_t        *tq;
671         scsi_qla_host_t *ha, *ha2;
672         srb_t           *sp;
673         struct Scsi_Host *host;
674         unsigned int    b, t, l;
675         unsigned long   handle;
676         int             was_empty;
677
678
679         host = cmd->device->host;
680         ha = (scsi_qla_host_t *) host->hostdata;
681         was_empty = 1;
682
683         cmd->scsi_done = fn;
684
685         spin_unlock_irq(ha->host->host_lock);
686
687         /*
688          * Allocate a command packet from the "sp" pool.  If we cant get back
689          * one then let scsi layer come back later.
690          */
691         if ((sp = qla2x00_get_new_sp(ha)) == NULL) {
692                 qla_printk(KERN_WARNING, ha,
693                     "Couldn't allocate memory for sp - retried.\n");
694
695                 spin_lock_irq(ha->host->host_lock);
696
697                 return (1);
698         }
699
700         sp->cmd = cmd;
701         CMD_SP(cmd) = (void *)sp;
702
703         sp->flags = 0;
704         if (CMD_RESID_LEN(cmd) & SRB_IOCTL) {
705                 /* Need to set sp->flags */
706                 sp->flags |= SRB_IOCTL;
707                 CMD_RESID_LEN(cmd) = 0; /* Clear it since no more use. */
708         }
709
710         sp->fo_retry_cnt = 0;
711         sp->err_id = 0;
712
713         /* Generate LU queue on bus, target, LUN */
714         b = cmd->device->channel;
715         t = cmd->device->id;
716         l = cmd->device->lun;
717
718         /*
719          * Start Command Timer. Typically it will be 2 seconds less than what
720          * is requested by the Host such that we can return the IO before
721          * aborts are called.
722          */
723         if ((cmd->timeout_per_command / HZ) > QLA_CMD_TIMER_DELTA)
724                 qla2x00_add_timer_to_cmd(sp,
725                     (cmd->timeout_per_command / HZ) - QLA_CMD_TIMER_DELTA);
726         else
727                 qla2x00_add_timer_to_cmd(sp, cmd->timeout_per_command / HZ);
728
729         if (l >= ha->max_luns) {
730                 cmd->result = DID_NO_CONNECT << 16;
731                 sp->err_id = SRB_ERR_PORT;
732
733                 spin_lock_irq(ha->host->host_lock);
734
735                 sp_put(ha, sp);
736
737                 return (0);
738         }
739
740         if ((tq = (os_tgt_t *) TGT_Q(ha, t)) != NULL &&
741             (lq = (os_lun_t *) LUN_Q(ha, t, l)) != NULL) {
742                 fcport = lq->fclun->fcport;
743                 ha2 = fcport->ha;
744         } else {
745                 lq = NULL;
746                 fcport = NULL;
747                 ha2 = ha;
748         }
749
750         /* Set an invalid handle until we issue the command to ISP */
751         /* then we will set the real handle value.                 */
752         handle = INVALID_HANDLE;
753         cmd->host_scribble = (unsigned char *)handle;
754
755         /* Bookkeeping information */
756         sp->r_start = jiffies;       /* time the request was recieved */
757         sp->u_start = 0;
758
759         /* Setup device queue pointers. */
760         sp->tgt_queue = tq;
761         sp->lun_queue = lq;
762
763         /*
764          * NOTE : q is NULL
765          *
766          * 1. When device is added from persistent binding but has not been
767          *    discovered yet.The state of loopid == PORT_AVAIL.
768          * 2. When device is never found on the bus.(loopid == UNUSED)
769          *
770          * IF Device Queue is not created, or device is not in a valid state
771          * and link down error reporting is enabled, reject IO.
772          */
773         if (fcport == NULL) {
774                 DEBUG3(printk("scsi(%ld:%2d:%2d): port unavailable\n",
775                     ha->host_no,t,l));
776
777                 cmd->result = DID_NO_CONNECT << 16;
778                 sp->err_id = SRB_ERR_PORT;
779
780                 spin_lock_irq(ha->host->host_lock);
781
782                 sp_put(ha, sp);
783
784                 return (0);
785         }
786
787         /* Only modify the allowed count if the target is a *non* tape device */
788         if ((fcport->flags & FCF_TAPE_PRESENT) == 0) {
789                 sp->flags &= ~SRB_TAPE;
790                 if (cmd->allowed < ql2xretrycount) {
791                         cmd->allowed = ql2xretrycount;
792                 }
793         } else
794                 sp->flags |= SRB_TAPE;
795
796
797         DEBUG5(printk("scsi(%ld:%2d:%2d): (queuecmd) queue sp = %p, "
798             "flags=0x%x fo retry=%d, pid=%ld\n",
799             ha->host_no, t, l, sp, sp->flags, sp->fo_retry_cnt,
800             cmd->serial_number));
801         DEBUG5(qla2x00_print_scsi_cmd(cmd));
802
803         sp->fclun = lq->fclun;
804         sp->ha = ha2;
805
806         if (cmd->sc_data_direction == DMA_BIDIRECTIONAL &&
807             cmd->request_bufflen != 0) {
808
809                 DEBUG2(printk(KERN_WARNING
810                     "scsi(%ld): Incorrect data direction - transfer "
811                     "length=%d, direction=%d, pid=%ld, opcode=%x\n",
812                     ha->host_no, cmd->request_bufflen, cmd->sc_data_direction,
813                     cmd->serial_number, cmd->cmnd[0]));
814         }
815
816         /* Final pre-check :
817          *
818          *      Either PORT_DOWN_TIMER OR LINK_DOWN_TIMER Expired.
819          */
820         if (atomic_read(&fcport->state) == FCS_DEVICE_DEAD ||
821             atomic_read(&ha2->loop_state) == LOOP_DEAD) {
822                 /*
823                  * Add the command to the done-queue for later failover
824                  * processing.
825                  */
826                 cmd->result = DID_NO_CONNECT << 16;
827                 if (atomic_read(&ha2->loop_state) == LOOP_DOWN) 
828                         sp->err_id = SRB_ERR_LOOP;
829                 else
830                         sp->err_id = SRB_ERR_PORT;
831
832                 add_to_done_queue(ha, sp);
833                 qla2x00_done(ha);
834
835                 spin_lock_irq(ha->host->host_lock);
836                 return (0);
837         }
838         if (tq && test_bit(TQF_SUSPENDED, &tq->flags) &&
839             (sp->flags & SRB_TAPE) == 0) {
840                 /* If target suspended put incoming I/O in retry_q. */
841                 qla2x00_extend_timeout(sp->cmd, 10);
842                 add_to_scsi_retry_queue(ha, sp);
843         } else
844                 was_empty = add_to_pending_queue(ha, sp);
845
846         if ((IS_QLA2100(ha) || IS_QLA2200(ha)) && ha->flags.online) {
847                 unsigned long flags;
848                 device_reg_t *reg;
849                 reg = ha->iobase;
850                 
851                 if (ha->response_ring_ptr->signature != RESPONSE_PROCESSED) {
852                         spin_lock_irqsave(&ha->hardware_lock, flags);   
853                         qla2x00_process_response_queue(ha);
854                         spin_unlock_irqrestore(&ha->hardware_lock, flags);
855                 }
856         }
857
858         /* We submit to the hardware if:
859          *
860          *      1) we're on the cpu the irq's arrive on or
861          *      2) there are very few io's outstanding.
862          *
863          * In all other cases we'll let an irq pick up our IO and submit it
864          * to the controller to improve affinity.
865          */
866         if (smp_processor_id() == ha->last_irq_cpu || was_empty)
867                 qla2x00_next(ha);
868
869         spin_lock_irq(ha->host->host_lock);
870
871         return (0);
872 }
873
874 /*
875  * qla2x00_eh_wait_on_command
876  *    Waits for the command to be returned by the Firmware for some
877  *    max time.
878  *
879  * Input:
880  *    ha = actual ha whose done queue will contain the command
881  *            returned by firmware.
882  *    cmd = Scsi Command to wait on.
883  *    flag = Abort/Reset(Bus or Device Reset)
884  *
885  * Return:
886  *    Not Found : 0
887  *    Found : 1
888  */
889 static int
890 qla2x00_eh_wait_on_command(scsi_qla_host_t *ha, struct scsi_cmnd *cmd)
891 {
892 #define ABORT_POLLING_PERIOD    HZ
893 #define ABORT_WAIT_TIME         ((10 * HZ) / (ABORT_POLLING_PERIOD))
894
895         int             found = 0;
896         int             done = 0;
897         srb_t           *rp = NULL;
898         struct list_head *list, *temp;
899         u_long          max_wait_time = ABORT_WAIT_TIME;
900
901         do {
902                 /* Check on done queue */
903                 spin_lock(&ha->list_lock);
904                 list_for_each_safe(list, temp, &ha->done_queue) {
905                         rp = list_entry(list, srb_t, list);
906
907                         /*
908                          * Found command. Just exit and wait for the cmd sent
909                          * to OS.
910                         */
911                         if (cmd == rp->cmd) {
912                                 found++;
913                                 DEBUG3(printk("%s: found in done queue.\n",
914                                     __func__);)
915                                 break;
916                         }
917                 }
918                 spin_unlock(&ha->list_lock);
919
920                 /* Complete the cmd right away. */
921                 if (found) { 
922                         qla2x00_delete_from_done_queue(ha, rp);
923                         sp_put(ha, rp);
924                         done++;
925                         break;
926                 }
927
928                 spin_unlock_irq(ha->host->host_lock);
929
930                 set_current_state(TASK_UNINTERRUPTIBLE);
931                 schedule_timeout(ABORT_POLLING_PERIOD);
932
933                 spin_lock_irq(ha->host->host_lock);
934
935         } while ((max_wait_time--));
936
937         if (done)
938                 DEBUG2(printk(KERN_INFO "%s: found cmd=%p.\n", __func__, cmd));
939
940         return (done);
941 }
942
943 /*
944  * qla2x00_wait_for_hba_online
945  *    Wait till the HBA is online after going through 
946  *    <= MAX_RETRIES_OF_ISP_ABORT  or
947  *    finally HBA is disabled ie marked offline
948  *
949  * Input:
950  *     ha - pointer to host adapter structure
951  * 
952  * Note:    
953  *    Does context switching-Release SPIN_LOCK
954  *    (if any) before calling this routine.
955  *
956  * Return:
957  *    Success (Adapter is online) : 0
958  *    Failed  (Adapter is offline/disabled) : 1
959  */
960 int 
961 qla2x00_wait_for_hba_online(scsi_qla_host_t *ha)
962 {
963         int      return_status;
964         unsigned long wait_online;
965
966         wait_online = jiffies + (MAX_LOOP_TIMEOUT * HZ); 
967         while (((test_bit(ISP_ABORT_NEEDED, &ha->dpc_flags)) ||
968             test_bit(ABORT_ISP_ACTIVE, &ha->dpc_flags) ||
969             test_bit(ISP_ABORT_RETRY, &ha->dpc_flags) ||
970             ha->dpc_active) && time_before(jiffies, wait_online)) {
971
972                 set_current_state(TASK_UNINTERRUPTIBLE);
973                 schedule_timeout(HZ);
974         }
975         if (ha->flags.online) 
976                 return_status = QLA_SUCCESS; 
977         else
978                 return_status = QLA_FUNCTION_FAILED;
979
980         DEBUG2(printk("%s return_status=%d\n",__func__,return_status));
981
982         return (return_status);
983 }
984
985 /*
986  * qla2x00_wait_for_loop_ready
987  *    Wait for MAX_LOOP_TIMEOUT(5 min) value for loop
988  *    to be in LOOP_READY state.         
989  * Input:
990  *     ha - pointer to host adapter structure
991  * 
992  * Note:    
993  *    Does context switching-Release SPIN_LOCK
994  *    (if any) before calling this routine.
995  *    
996  *
997  * Return:
998  *    Success (LOOP_READY) : 0
999  *    Failed  (LOOP_NOT_READY) : 1
1000  */
1001 static inline int 
1002 qla2x00_wait_for_loop_ready(scsi_qla_host_t *ha)
1003 {
1004         int      return_status = QLA_SUCCESS;
1005         unsigned long loop_timeout ;
1006
1007         /* wait for 5 min at the max for loop to be ready */
1008         loop_timeout = jiffies + (MAX_LOOP_TIMEOUT * HZ); 
1009
1010         while ((!atomic_read(&ha->loop_down_timer) &&
1011             atomic_read(&ha->loop_state) == LOOP_DOWN) ||
1012             test_bit(CFG_ACTIVE, &ha->cfg_flags) ||
1013             atomic_read(&ha->loop_state) != LOOP_READY) {
1014                 set_current_state(TASK_UNINTERRUPTIBLE);
1015                 schedule_timeout(HZ);
1016                 if (time_after_eq(jiffies, loop_timeout)) {
1017                         return_status = QLA_FUNCTION_FAILED;
1018                         break;
1019                 }
1020         }
1021         return (return_status); 
1022 }
1023
1024 /**************************************************************************
1025 * qla2xxx_eh_abort
1026 *
1027 * Description:
1028 *    The abort function will abort the specified command.
1029 *
1030 * Input:
1031 *    cmd = Linux SCSI command packet to be aborted.
1032 *
1033 * Returns:
1034 *    Either SUCCESS or FAILED.
1035 *
1036 * Note:
1037 **************************************************************************/
1038 int
1039 qla2xxx_eh_abort(struct scsi_cmnd *cmd)
1040 {
1041         int             i;
1042         int             return_status = FAILED;
1043         os_lun_t        *q;
1044         scsi_qla_host_t *ha;
1045         scsi_qla_host_t *vis_ha;
1046         srb_t           *sp;
1047         srb_t           *rp;
1048         struct list_head *list, *temp;
1049         struct Scsi_Host *host;
1050         uint8_t         found = 0;
1051         unsigned int    b, t, l;
1052
1053         /* Get the SCSI request ptr */
1054         sp = (srb_t *) CMD_SP(cmd);
1055
1056         /*
1057          * If sp is NULL, command is already returned.
1058          * sp is NULLED just before we call back scsi_done
1059          *
1060          */
1061         if ((sp == NULL)) {
1062                 /* no action - we don't have command */
1063                 qla_printk(KERN_INFO, to_qla_host(cmd->device->host),
1064                     "qla2xxx_eh_abort: cmd already done sp=%p\n", sp);
1065                 DEBUG(printk("qla2xxx_eh_abort: cmd already done sp=%p\n", sp);)
1066                 return SUCCESS;
1067         }
1068         if (sp) {
1069                 DEBUG(printk("qla2xxx_eh_abort: refcount %i \n",
1070                     atomic_read(&sp->ref_count));)
1071         }
1072
1073         vis_ha = (scsi_qla_host_t *) cmd->device->host->hostdata;
1074         ha = (scsi_qla_host_t *)cmd->device->host->hostdata;
1075
1076         host = ha->host;
1077
1078         /* Generate LU queue on bus, target, LUN */
1079         b = cmd->device->channel;
1080         t = cmd->device->id;
1081         l = cmd->device->lun;
1082         q = GET_LU_Q(vis_ha, t, l);
1083
1084         qla_printk(KERN_INFO, ha, 
1085             "%s scsi(%ld:%d:%d:%d): cmd_timeout_in_sec=0x%x.\n", __func__,
1086             ha->host_no, (int)b, (int)t, (int)l,
1087             cmd->timeout_per_command / HZ);
1088
1089         /*
1090          * if no LUN queue then something is very wrong!!!
1091          */
1092         if (q == NULL) {
1093                 qla_printk(KERN_WARNING, ha,
1094                         "qla2x00: (%x:%x:%x) No LUN queue.\n", b, t, l);
1095
1096                 /* no action - we don't have command */
1097                 return FAILED;
1098         }
1099
1100         DEBUG2(printk("scsi(%ld): ABORTing cmd=%p sp=%p jiffies = 0x%lx, "
1101             "timeout=%x, dpc_flags=%lx, vis_ha->dpc_flags=%lx q->flag=%lx\n",
1102             ha->host_no, cmd, sp, jiffies, cmd->timeout_per_command / HZ,
1103             ha->dpc_flags, vis_ha->dpc_flags, q->q_flag));
1104         DEBUG2(qla2x00_print_scsi_cmd(cmd));
1105
1106         spin_unlock_irq(ha->host->host_lock);
1107         if (qla2x00_wait_for_hba_online(ha) != QLA_SUCCESS) {
1108                 DEBUG2(printk("%s failed:board disabled\n", __func__);)
1109                 spin_lock_irq(ha->host->host_lock);
1110                 return FAILED;
1111         }
1112         spin_lock_irq(ha->host->host_lock);
1113
1114         /* Search done queue */
1115         spin_lock(&ha->list_lock);
1116         list_for_each_safe(list, temp, &ha->done_queue) {
1117                 rp = list_entry(list, srb_t, list);
1118
1119                 if (cmd != rp->cmd)
1120                         continue;
1121
1122                 /*
1123                  * Found command.Remove it from done list.
1124                  * And proceed to post completion to scsi mid layer.
1125                  */
1126                 return_status = SUCCESS;
1127                 found++;
1128                 qla2x00_delete_from_done_queue(ha, sp);
1129
1130                 break;
1131         } /* list_for_each_safe() */
1132         spin_unlock(&ha->list_lock);
1133
1134         /*
1135          * Return immediately if the aborted command was already in the done
1136          * queue
1137          */
1138         if (found) {
1139                 qla_printk(KERN_INFO, ha,
1140                     "qla2xxx_eh_abort: Returning completed command=%p sp=%p\n",
1141                     cmd, sp);
1142                 sp_put(ha, sp);
1143                 return (return_status);
1144         }
1145         
1146
1147         /*
1148          * See if this command is in the retry queue
1149          */
1150         DEBUG3(printk("qla2xxx_eh_abort: searching sp %p in retry "
1151                     "queue.\n", sp);)
1152
1153         spin_lock(&ha->list_lock);
1154         list_for_each_safe(list, temp, &ha->retry_queue) {
1155                 rp = list_entry(list, srb_t, list);
1156
1157                 if (cmd != rp->cmd)
1158                         continue;
1159
1160
1161                 DEBUG2(printk("qla2xxx_eh_abort: found "
1162                     "in retry queue. SP=%p\n", sp);)
1163
1164                 __del_from_retry_queue(ha, rp);
1165                 cmd->result = DID_ABORT << 16;
1166                 __add_to_done_queue(ha, rp);
1167
1168                 return_status = SUCCESS;
1169                 found++;
1170
1171                 break;
1172
1173         } 
1174         spin_unlock(&ha->list_lock);
1175
1176
1177         /*
1178          * Our SP pointer points at the command we want to remove from the
1179          * pending queue providing we haven't already sent it to the adapter.
1180          */
1181         if (!found) {
1182                 DEBUG3(printk("qla2xxx_eh_abort: searching sp %p "
1183                     "in pending queue.\n", sp);)
1184
1185                 spin_lock(&vis_ha->list_lock);
1186                 list_for_each_safe(list, temp, &vis_ha->pending_queue) {
1187                         rp = list_entry(list, srb_t, list);
1188
1189                         if (rp->cmd != cmd)
1190                                 continue;
1191
1192                         /* Remove srb from LUN queue. */
1193                         rp->flags |=  SRB_ABORTED;
1194
1195                         DEBUG2(printk("qla2xxx_eh_abort: Cmd in pending queue."
1196                             " serial_number %ld.\n",
1197                             sp->cmd->serial_number);)
1198
1199                         __del_from_pending_queue(vis_ha, rp);
1200                         cmd->result = DID_ABORT << 16;
1201
1202                         __add_to_done_queue(vis_ha, rp);
1203
1204                         return_status = SUCCESS;
1205
1206                         found++;
1207                         break;
1208                 } /* list_for_each_safe() */
1209                 spin_unlock(&vis_ha->list_lock);
1210         } /*End of if !found */
1211
1212         if (!found) {  /* find the command in our active list */
1213                 DEBUG3(printk("qla2xxx_eh_abort: searching sp %p "
1214                     "in outstanding queue.\n", sp);)
1215
1216                 spin_lock(&ha->hardware_lock);
1217                 for (i = 1; i < MAX_OUTSTANDING_COMMANDS; i++) {
1218                         sp = ha->outstanding_cmds[i];
1219
1220                         if (sp == NULL)
1221                                 continue;
1222
1223                         if (sp->cmd != cmd)
1224                                 continue;
1225
1226                         DEBUG2(printk("qla2xxx_eh_abort(%ld): aborting sp %p "
1227                             "from RISC. pid=%ld sp->state=%x q->q_flag=%lx\n",
1228                             ha->host_no, sp, sp->cmd->serial_number,
1229                             sp->state, q->q_flag);)
1230                         DEBUG(qla2x00_print_scsi_cmd(cmd);)
1231
1232                         /* Get a reference to the sp and drop the lock.*/
1233                         sp_get(ha, sp);
1234
1235                         spin_unlock(&ha->hardware_lock);
1236                         spin_unlock_irq(ha->host->host_lock);
1237
1238                         if (qla2x00_abort_command(ha, sp)) {
1239                                 DEBUG2(printk("qla2xxx_eh_abort: abort_command "
1240                                     "mbx failed.\n");)
1241                                 return_status = FAILED;
1242                         } else {
1243                                 DEBUG3(printk("qla2xxx_eh_abort: abort_command "
1244                                     " mbx success.\n");)
1245                                 return_status = SUCCESS;
1246                         }
1247
1248                         sp_put(ha,sp);
1249
1250                         spin_lock_irq(ha->host->host_lock);
1251                         spin_lock(&ha->hardware_lock);
1252
1253                         /*
1254                          * Regardless of mailbox command status, go check on
1255                          * done queue just in case the sp is already done.
1256                          */
1257                         break;
1258
1259                 }/*End of for loop */
1260                 spin_unlock(&ha->hardware_lock);
1261
1262         } /*End of if !found */
1263
1264         /* Waiting for our command in done_queue to be returned to OS.*/
1265         if (qla2x00_eh_wait_on_command(ha, cmd) != 0) {
1266                 DEBUG2(printk("qla2xxx_eh_abort: cmd returned back to OS.\n");)
1267                 return_status = SUCCESS;
1268         }
1269
1270         if (return_status == FAILED) {
1271                 qla_printk(KERN_INFO, ha, 
1272                         "qla2xxx_eh_abort Exiting: status=Failed\n");
1273                 return FAILED;
1274         }
1275
1276         DEBUG2(printk("qla2xxx_eh_abort: Exiting. return_status=0x%x.\n",
1277             return_status));
1278
1279         return return_status;
1280 }
1281
1282 /**************************************************************************
1283 * qla2x00_eh_wait_for_pending_target_commands
1284 *
1285 * Description:
1286 *    Waits for all the commands to come back from the specified target.
1287 *
1288 * Input:
1289 *    ha - pointer to scsi_qla_host structure.
1290 *    t  - target        
1291 * Returns:
1292 *    Either SUCCESS or FAILED.
1293 *
1294 * Note:
1295 **************************************************************************/
1296 int
1297 qla2x00_eh_wait_for_pending_target_commands(scsi_qla_host_t *ha, unsigned int t)
1298 {
1299         int     cnt;
1300         int     status;
1301         srb_t           *sp;
1302         struct scsi_cmnd *cmd;
1303
1304         status = 0;
1305
1306         /*
1307          * Waiting for all commands for the designated target in the active
1308          * array
1309          */
1310         for (cnt = 1; cnt < MAX_OUTSTANDING_COMMANDS; cnt++) {
1311                 spin_lock(&ha->hardware_lock);
1312                 sp = ha->outstanding_cmds[cnt];
1313                 if (sp) {
1314                         cmd = sp->cmd;
1315                         spin_unlock(&ha->hardware_lock);
1316                         if (cmd->device->id == t) {
1317                                 if (!qla2x00_eh_wait_on_command(ha, cmd)) {
1318                                         status = 1;
1319                                         break;
1320                                 }
1321                         }
1322                 }
1323                 else {
1324                         spin_unlock(&ha->hardware_lock);
1325                 }
1326         }
1327         return (status);
1328 }
1329
1330
1331 /**************************************************************************
1332 * qla2xxx_eh_device_reset
1333 *
1334 * Description:
1335 *    The device reset function will reset the target and abort any
1336 *    executing commands.
1337 *
1338 *    NOTE: The use of SP is undefined within this context.  Do *NOT*
1339 *          attempt to use this value, even if you determine it is 
1340 *          non-null.
1341 *
1342 * Input:
1343 *    cmd = Linux SCSI command packet of the command that cause the
1344 *          bus device reset.
1345 *
1346 * Returns:
1347 *    SUCCESS/FAILURE (defined as macro in scsi.h).
1348 *
1349 **************************************************************************/
1350 int
1351 qla2xxx_eh_device_reset(struct scsi_cmnd *cmd)
1352 {
1353         int             return_status;
1354         unsigned int    b, t, l;
1355         scsi_qla_host_t *ha;
1356         os_tgt_t        *tq;
1357         os_lun_t        *lq;
1358         fc_port_t       *fcport_to_reset;
1359         srb_t           *rp;
1360         struct list_head *list, *temp;
1361
1362         return_status = FAILED;
1363         if (cmd == NULL) {
1364                 printk(KERN_INFO
1365                     "%s(): **** SCSI mid-layer passing in NULL cmd\n",
1366                     __func__);
1367
1368                 return (return_status);
1369         }
1370
1371         b = cmd->device->channel;
1372         t = cmd->device->id;
1373         l = cmd->device->lun;
1374         ha = (scsi_qla_host_t *)cmd->device->host->hostdata;
1375
1376         tq = TGT_Q(ha, t);
1377         if (tq == NULL) {
1378                 qla_printk(KERN_INFO, ha,
1379                     "%s(): **** CMD derives a NULL TGT_Q\n", __func__);
1380
1381                 return (return_status);
1382         }
1383         lq = (os_lun_t *)LUN_Q(ha, t, l);
1384         if (lq == NULL) {
1385                 printk(KERN_INFO
1386                     "%s(): **** CMD derives a NULL LUN_Q\n", __func__);
1387
1388                 return (return_status);
1389         }
1390         fcport_to_reset = lq->fclun->fcport;
1391
1392         /* If we are coming in from the back-door, stall I/O until complete. */
1393         if (!cmd->device->host->eh_active)
1394                 set_bit(TQF_SUSPENDED, &tq->flags);
1395
1396         qla_printk(KERN_INFO, ha,
1397             "scsi(%ld:%d:%d:%d): DEVICE RESET ISSUED.\n", ha->host_no, b, t, l);
1398
1399         DEBUG2(printk(KERN_INFO
1400             "scsi(%ld): DEVICE_RESET cmd=%p jiffies = 0x%lx, timeout=%x, "
1401             "dpc_flags=%lx, status=%x allowed=%d cmd.state=%x\n",
1402             ha->host_no, cmd, jiffies, cmd->timeout_per_command / HZ,
1403             ha->dpc_flags, cmd->result, cmd->allowed, cmd->state));
1404
1405         /* Clear commands from the retry queue. */
1406         spin_lock(&ha->list_lock);
1407         list_for_each_safe(list, temp, &ha->retry_queue) {
1408                 rp = list_entry(list, srb_t, list);
1409  
1410                 if (t != rp->cmd->device->id) 
1411                         continue;
1412  
1413                 DEBUG2(printk(KERN_INFO
1414                     "qla2xxx_eh_reset: found in retry queue. SP=%p\n", rp));
1415  
1416                 __del_from_retry_queue(ha, rp);
1417                 rp->cmd->result = DID_RESET << 16;
1418                 __add_to_done_queue(ha, rp);
1419         }
1420         spin_unlock(&ha->list_lock);
1421
1422         spin_unlock_irq(ha->host->host_lock);
1423
1424         if (qla2x00_wait_for_hba_online(ha) != QLA_SUCCESS) {
1425                 DEBUG2(printk(KERN_INFO
1426                     "%s failed:board disabled\n",__func__));
1427
1428                 spin_lock_irq(ha->host->host_lock);
1429                 goto eh_dev_reset_done;
1430         }
1431
1432         if (qla2x00_wait_for_loop_ready(ha) == QLA_SUCCESS) {
1433                 if (qla2x00_device_reset(ha, fcport_to_reset) == 0) {
1434                         return_status = SUCCESS;
1435                 }
1436
1437 #if defined(LOGOUT_AFTER_DEVICE_RESET)
1438                 if (return_status == SUCCESS) {
1439                         if (fcport_to_reset->flags & FC_FABRIC_DEVICE) {
1440                                 qla2x00_fabric_logout(ha,
1441                                     fcport_to_reset->loop_id);
1442                                 qla2x00_mark_device_lost(ha, fcport_to_reset);
1443                         }
1444                 }
1445 #endif
1446         } else {
1447                 DEBUG2(printk(KERN_INFO
1448                     "%s failed: loop not ready\n",__func__);)
1449         }
1450
1451         spin_lock_irq(ha->host->host_lock);
1452
1453         if (return_status == FAILED) {
1454                 DEBUG3(printk("%s(%ld): device reset failed\n",
1455                     __func__, ha->host_no));
1456                 qla_printk(KERN_INFO, ha, "%s: device reset failed\n",
1457                     __func__);
1458
1459                 goto eh_dev_reset_done;
1460         }
1461
1462         /*
1463          * If we are coming down the EH path, wait for all commands to
1464          * complete for the device.
1465          */
1466         if (cmd->device->host->eh_active) {
1467                 if (qla2x00_eh_wait_for_pending_target_commands(ha, t))
1468                         return_status = FAILED;
1469
1470                 if (return_status == FAILED) {
1471                         DEBUG3(printk("%s(%ld): failed while waiting for "
1472                             "commands\n", __func__, ha->host_no));
1473                         qla_printk(KERN_INFO, ha,
1474                             "%s: failed while waiting for commands\n",
1475                             __func__); 
1476
1477                         goto eh_dev_reset_done;
1478                 }
1479         }
1480
1481         qla_printk(KERN_INFO, ha,
1482             "scsi(%ld:%d:%d:%d): DEVICE RESET SUCCEEDED.\n",
1483             ha->host_no, b, t, l);
1484
1485 eh_dev_reset_done:
1486
1487         if (!cmd->device->host->eh_active)
1488                 clear_bit(TQF_SUSPENDED, &tq->flags);
1489
1490         return (return_status);
1491 }
1492
1493 /**************************************************************************
1494 * qla2x00_eh_wait_for_pending_commands
1495 *
1496 * Description:
1497 *    Waits for all the commands to come back from the specified host.
1498 *
1499 * Input:
1500 *    ha - pointer to scsi_qla_host structure.
1501 *
1502 * Returns:
1503 *    1 : SUCCESS
1504 *    0 : FAILED
1505 *
1506 * Note:
1507 **************************************************************************/
1508 int
1509 qla2x00_eh_wait_for_pending_commands(scsi_qla_host_t *ha)
1510 {
1511         int     cnt;
1512         int     status;
1513         srb_t           *sp;
1514         struct scsi_cmnd *cmd;
1515
1516         status = 1;
1517
1518         /*
1519          * Waiting for all commands for the designated target in the active
1520          * array
1521          */
1522         for (cnt = 1; cnt < MAX_OUTSTANDING_COMMANDS; cnt++) {
1523                 spin_lock(&ha->hardware_lock);
1524                 sp = ha->outstanding_cmds[cnt];
1525                 if (sp) {
1526                         cmd = sp->cmd;
1527                         spin_unlock(&ha->hardware_lock);
1528                         status = qla2x00_eh_wait_on_command(ha, cmd);
1529                         if (status == 0)
1530                                 break;
1531                 }
1532                 else {
1533                         spin_unlock(&ha->hardware_lock);
1534                 }
1535         }
1536         return (status);
1537 }
1538
1539
1540 /**************************************************************************
1541 * qla2xxx_eh_bus_reset
1542 *
1543 * Description:
1544 *    The bus reset function will reset the bus and abort any executing
1545 *    commands.
1546 *
1547 * Input:
1548 *    cmd = Linux SCSI command packet of the command that cause the
1549 *          bus reset.
1550 *
1551 * Returns:
1552 *    SUCCESS/FAILURE (defined as macro in scsi.h).
1553 *
1554 **************************************************************************/
1555 int
1556 qla2xxx_eh_bus_reset(struct scsi_cmnd *cmd)
1557 {
1558         scsi_qla_host_t *ha;
1559         srb_t *sp;
1560         int rval = FAILED;
1561
1562         ha = (scsi_qla_host_t *) cmd->device->host->hostdata;
1563         sp = (srb_t *) CMD_SP(cmd);
1564
1565         qla_printk(KERN_INFO, ha,
1566             "scsi(%ld:%d:%d:%d): LOOP RESET ISSUED.\n", ha->host_no,
1567             cmd->device->channel, cmd->device->id, cmd->device->lun);
1568
1569         spin_unlock_irq(ha->host->host_lock);
1570
1571         if (qla2x00_wait_for_hba_online(ha) != QLA_SUCCESS) {
1572                 DEBUG2(printk("%s failed:board disabled\n",__func__));
1573                 spin_lock_irq(ha->host->host_lock);
1574                 return FAILED;
1575         }
1576
1577         if (qla2x00_wait_for_loop_ready(ha) == QLA_SUCCESS) {
1578                 if (qla2x00_loop_reset(ha) == QLA_SUCCESS) 
1579                         rval = SUCCESS;
1580         }
1581
1582         spin_lock_irq(ha->host->host_lock);
1583         if (rval == FAILED)
1584                 goto out;
1585
1586         /*
1587          * Blocking Call. It goes to sleep waiting for cmd to get to done q
1588          *
1589          * XXX(hch): really?  We're under host_lock here..
1590          */
1591         /* Waiting for our command in done_queue to be returned to OS.*/
1592         if (!qla2x00_eh_wait_for_pending_commands(ha))
1593                 rval = FAILED;
1594
1595  out:
1596         qla_printk(KERN_INFO, ha, "%s: reset %s\n", __func__,
1597                         (rval == FAILED) ? "failed" : "succeded");
1598
1599         return rval;
1600 }
1601
1602 /**************************************************************************
1603 * qla2xxx_eh_host_reset
1604 *
1605 * Description:
1606 *    The reset function will reset the Adapter.
1607 *
1608 * Input:
1609 *      cmd = Linux SCSI command packet of the command that cause the
1610 *            adapter reset.
1611 *
1612 * Returns:
1613 *      Either SUCCESS or FAILED.
1614 *
1615 * Note:
1616 **************************************************************************/
1617 int
1618 qla2xxx_eh_host_reset(struct scsi_cmnd *cmd)
1619 {
1620         scsi_qla_host_t *ha = (scsi_qla_host_t *)cmd->device->host->hostdata;
1621         int             rval = SUCCESS;
1622
1623         /* Display which one we're actually resetting for debug. */
1624         DEBUG(printk("qla2xxx_eh_host_reset:Resetting scsi(%ld).\n",
1625             ha->host_no));
1626
1627         /*
1628          *  Now issue reset.
1629          */
1630         qla_printk(KERN_INFO, ha,
1631             "scsi(%ld:%d:%d:%d): ADAPTER RESET issued.\n", ha->host_no,
1632             cmd->device->channel, cmd->device->id, cmd->device->lun);
1633
1634         spin_unlock_irq(ha->host->host_lock);
1635
1636         if (qla2x00_wait_for_hba_online(ha) != QLA_SUCCESS)
1637                 goto board_disabled;
1638
1639         /*
1640          * Fixme-may be dpc thread is active and processing
1641          * loop_resync,so wait a while for it to 
1642          * be completed and then issue big hammer.Otherwise
1643          * it may cause I/O failure as big hammer marks the
1644          * devices as lost kicking of the port_down_timer
1645          * while dpc is stuck for the mailbox to complete.
1646          */
1647         /* Blocking call-Does context switching if loop is Not Ready */
1648         qla2x00_wait_for_loop_ready(ha);
1649         set_bit(ABORT_ISP_ACTIVE, &ha->dpc_flags);
1650         if (qla2x00_abort_isp(ha)) {
1651                 clear_bit(ABORT_ISP_ACTIVE, &ha->dpc_flags);
1652                 /* failed. schedule dpc to try */
1653                 set_bit(ISP_ABORT_NEEDED, &ha->dpc_flags);
1654
1655                 if (qla2x00_wait_for_hba_online(ha) != QLA_SUCCESS)
1656                         goto board_disabled;
1657         } 
1658
1659         clear_bit(ABORT_ISP_ACTIVE, &ha->dpc_flags);
1660
1661         spin_lock_irq(ha->host->host_lock);
1662         if (rval == FAILED)
1663                 goto out;
1664
1665         /* Waiting for our command in done_queue to be returned to OS.*/
1666         if (qla2x00_eh_wait_for_pending_commands(ha))
1667                 rval = FAILED;
1668
1669  out:
1670         qla_printk(KERN_INFO, ha, "%s: reset %s\n", __func__,
1671                         (rval == FAILED) ? "failed" : "succeded");
1672
1673         return rval;
1674
1675  board_disabled:
1676         spin_lock_irq(ha->host->host_lock);
1677
1678         qla_printk(KERN_INFO, ha, "%s: failed:board disabled\n", __func__);
1679         return FAILED;
1680 }
1681
1682
1683 /*
1684 * qla2x00_loop_reset
1685 *      Issue loop reset.
1686 *
1687 * Input:
1688 *      ha = adapter block pointer.
1689 *
1690 * Returns:
1691 *      0 = success
1692 */
1693 static int
1694 qla2x00_loop_reset(scsi_qla_host_t *ha)
1695 {
1696         int status = QLA_SUCCESS;
1697         uint16_t t;
1698         os_tgt_t        *tq;
1699
1700         if (ha->flags.enable_lip_reset) {
1701                 status = qla2x00_lip_reset(ha);
1702         }
1703
1704         if (status == QLA_SUCCESS && ha->flags.enable_target_reset) {
1705                 for (t = 0; t < MAX_FIBRE_DEVICES; t++) {
1706                         if ((tq = TGT_Q(ha, t)) == NULL)
1707                                 continue;
1708
1709                         if (tq->fcport == NULL)
1710                                 continue;
1711
1712                         status = qla2x00_target_reset(ha, 0, t);
1713                         if (status != QLA_SUCCESS) {
1714                                 break;
1715                         }
1716                 }
1717         }
1718
1719         if (status == QLA_SUCCESS &&
1720                 ((!ha->flags.enable_target_reset && 
1721                   !ha->flags.enable_lip_reset) ||
1722                 ha->flags.enable_lip_full_login)) {
1723
1724                 status = qla2x00_full_login_lip(ha);
1725         }
1726
1727         /* Issue marker command only when we are going to start the I/O */
1728         ha->marker_needed = 1;
1729
1730         if (status) {
1731                 /* Empty */
1732                 DEBUG2_3(printk("%s(%ld): **** FAILED ****\n",
1733                                 __func__,
1734                                 ha->host_no);)
1735         } else {
1736                 /* Empty */
1737                 DEBUG3(printk("%s(%ld): exiting normally.\n",
1738                                 __func__,
1739                                 ha->host_no);)
1740         }
1741
1742         return(status);
1743 }
1744
1745 /*
1746  * qla2x00_device_reset
1747  *      Issue bus device reset message to the target.
1748  *
1749  * Input:
1750  *      ha = adapter block pointer.
1751  *      t = SCSI ID.
1752  *      TARGET_QUEUE_LOCK must be released.
1753  *      ADAPTER_STATE_LOCK must be released.
1754  *
1755  * Context:
1756  *      Kernel context.
1757  */
1758 static int
1759 qla2x00_device_reset(scsi_qla_host_t *ha, fc_port_t *reset_fcport)
1760 {
1761         /* Abort Target command will clear Reservation */
1762         return qla2x00_abort_target(reset_fcport);
1763 }
1764
1765 /**************************************************************************
1766 * qla2xxx_slave_configure
1767 *
1768 * Description:
1769 **************************************************************************/
1770 int
1771 qla2xxx_slave_configure(struct scsi_device *sdev)
1772 {
1773         scsi_qla_host_t *ha = to_qla_host(sdev->host);
1774         int queue_depth;
1775
1776         if (IS_QLA2100(ha) || IS_QLA2200(ha))
1777                 queue_depth = 16;
1778         else
1779                 queue_depth = 32;
1780
1781         if (sdev->tagged_supported) {
1782                 if (ql2xmaxqdepth != 0 && ql2xmaxqdepth <= 0xffffU)
1783                         queue_depth = ql2xmaxqdepth;
1784
1785                 ql2xmaxqdepth = queue_depth;
1786
1787                 scsi_adjust_queue_depth(sdev, MSG_ORDERED_TAG, queue_depth);
1788
1789                 qla_printk(KERN_INFO, ha,
1790                     "scsi(%d:%d:%d:%d): Enabled tagged queuing, queue "
1791                     "depth %d.\n",
1792                     sdev->host->host_no, sdev->channel, sdev->id, sdev->lun,
1793                     sdev->queue_depth);
1794         } else {
1795                  scsi_adjust_queue_depth(sdev, 0 /* TCQ off */,
1796                      sdev->host->hostt->cmd_per_lun /* 3 */);
1797         }
1798
1799         return (0);
1800 }
1801
1802 /**
1803  * qla2x00_config_dma_addressing() - Configure OS DMA addressing method.
1804  * @ha: HA context
1805  *
1806  * At exit, the @ha's flags.enable_64bit_addressing set to indicated
1807  * supported addressing method.
1808  */
1809 static void
1810 qla2x00_config_dma_addressing(scsi_qla_host_t *ha)
1811 {
1812         /* Assume 32bit DMA address */
1813         ha->flags.enable_64bit_addressing = 0;
1814         ha->calc_request_entries = qla2x00_calc_iocbs_32;
1815         ha->build_scsi_iocbs = qla2x00_build_scsi_iocbs_32;
1816
1817         /*
1818          * Given the two variants pci_set_dma_mask(), allow the compiler to
1819          * assist in setting the proper dma mask.
1820          */
1821         if (sizeof(dma_addr_t) > 4) {
1822                 /* Update our PCI device dma_mask for full 64 bits */
1823                 if (pci_set_dma_mask(ha->pdev, 0xffffffffffffffffULL) == 0) {
1824                         ha->flags.enable_64bit_addressing = 1;
1825                         ha->calc_request_entries = qla2x00_calc_iocbs_64;
1826                         ha->build_scsi_iocbs = qla2x00_build_scsi_iocbs_64;
1827
1828                         if (pci_set_consistent_dma_mask(ha->pdev,
1829                             0xffffffffffffffffULL)) {
1830                                 qla_printk(KERN_DEBUG, ha, 
1831                                     "Failed to set 64 bit PCI consistent mask; "
1832                                     "using 32 bit.\n");
1833                                 pci_set_consistent_dma_mask(ha->pdev,
1834                                     0xffffffffULL);
1835                         }
1836                 } else {
1837                         qla_printk(KERN_DEBUG, ha,
1838                             "Failed to set 64 bit PCI DMA mask, falling back "
1839                             "to 32 bit MASK.\n");
1840                         pci_set_dma_mask(ha->pdev, 0xffffffff);
1841                 }
1842         } else {
1843                 pci_set_dma_mask(ha->pdev, 0xffffffff);
1844         }
1845 }
1846
1847 static int
1848 qla2x00_iospace_config(scsi_qla_host_t *ha)
1849 {
1850         unsigned long   pio, pio_len, pio_flags;
1851         unsigned long   mmio, mmio_len, mmio_flags;
1852
1853         /* We only need PIO for Flash operations on ISP2312 v2 chips. */
1854         pio = pci_resource_start(ha->pdev, 0);
1855         pio_len = pci_resource_len(ha->pdev, 0);
1856         pio_flags = pci_resource_flags(ha->pdev, 0);
1857         if (pio_flags & IORESOURCE_IO) {
1858                 if (pio_len < MIN_IOBASE_LEN) {
1859                         qla_printk(KERN_WARNING, ha,
1860                             "Invalid PCI I/O region size (%s)...\n",
1861                             ha->pdev->slot_name);
1862                         pio = 0;
1863                 }
1864         } else {
1865                 qla_printk(KERN_WARNING, ha,
1866                     "region #0 not a PIO resource (%s)...\n",
1867                     ha->pdev->slot_name);
1868                 pio = 0;
1869         }
1870
1871         /* Use MMIO operations for all accesses. */
1872         mmio = pci_resource_start(ha->pdev, 1);
1873         mmio_len = pci_resource_len(ha->pdev, 1);
1874         mmio_flags = pci_resource_flags(ha->pdev, 1);
1875
1876         if (!(mmio_flags & IORESOURCE_MEM)) {
1877                 qla_printk(KERN_ERR, ha,
1878                     "region #0 not an MMIO resource (%s), aborting\n",
1879                     ha->pdev->slot_name);
1880                 goto iospace_error_exit;
1881         }
1882         if (mmio_len < MIN_IOBASE_LEN) {
1883                 qla_printk(KERN_ERR, ha,
1884                     "Invalid PCI mem region size (%s), aborting\n",
1885                     ha->pdev->slot_name);
1886                 goto iospace_error_exit;
1887         }
1888
1889         if (pci_request_regions(ha->pdev, ha->brd_info->drv_name)) {
1890                 qla_printk(KERN_WARNING, ha,
1891                     "Failed to reserve PIO/MMIO regions (%s)\n", 
1892                     ha->pdev->slot_name);
1893
1894                 goto iospace_error_exit;
1895         }
1896
1897         ha->pio_address = pio;
1898         ha->pio_length = pio_len;
1899         ha->mmio_address = ioremap(mmio, MIN_IOBASE_LEN);
1900         if (!ha->mmio_address) {
1901                 qla_printk(KERN_ERR, ha,
1902                     "cannot remap MMIO (%s), aborting\n", ha->pdev->slot_name);
1903
1904                 goto iospace_error_exit;
1905         }
1906         ha->mmio_length = mmio_len;
1907         ha->iobase = (device_reg_t *) ha->mmio_address;
1908
1909         return (0);
1910
1911 iospace_error_exit:
1912         return (-ENOMEM);
1913 }
1914
1915 /*
1916  * PCI driver interface
1917  */
1918 int qla2x00_probe_one(struct pci_dev *pdev, struct qla_board_info *brd_info)
1919 {
1920         int     ret;
1921         device_reg_t *reg;
1922         struct Scsi_Host *host;
1923         scsi_qla_host_t *ha;
1924         unsigned long   flags = 0;
1925         unsigned long   wait_switch = 0;
1926         char pci_info[20];
1927         char fw_str[30];
1928
1929         if (pci_enable_device(pdev))
1930                 return -1;
1931
1932         host = scsi_host_alloc(&qla2x00_driver_template,
1933             sizeof(scsi_qla_host_t));
1934         if (host == NULL) {
1935                 printk(KERN_WARNING
1936                     "qla2xxx: Couldn't allocate host from scsi layer!\n");
1937                 return -1;
1938         }
1939
1940         /* Clear our data area */
1941         ha = (scsi_qla_host_t *)host->hostdata;
1942         memset(ha, 0, sizeof(scsi_qla_host_t));
1943
1944         ha->pdev = pdev;
1945         ha->host = host;
1946         ha->host_no = host->host_no;
1947         ha->brd_info = brd_info;
1948         sprintf(ha->host_str, "%s_%ld", ha->brd_info->drv_name, ha->host_no);
1949
1950         /* Configure PCI I/O space */
1951         ret = qla2x00_iospace_config(ha);
1952         if (ret != 0) {
1953                 goto probe_failed;
1954         }
1955
1956         /* Sanitize the information from PCI BIOS. */
1957         host->irq = pdev->irq;
1958
1959         qla_printk(KERN_INFO, ha,
1960             "Found an %s, irq %d, iobase 0x%p\n", ha->brd_info->isp_name,
1961             host->irq, ha->iobase);
1962
1963         spin_lock_init(&ha->hardware_lock);
1964
1965         /* 4.23 Initialize /proc/scsi/qla2x00 counters */
1966         ha->actthreads = 0;
1967         ha->qthreads   = 0;
1968         ha->total_isr_cnt = 0;
1969         ha->total_isp_aborts = 0;
1970         ha->total_lip_cnt = 0;
1971         ha->total_dev_errs = 0;
1972         ha->total_ios = 0;
1973         ha->total_bytes = 0;
1974
1975         ha->prev_topology = 0;
1976         ha->ports = MAX_BUSES;
1977
1978         if (IS_QLA2100(ha)) {
1979                 ha->max_targets = MAX_TARGETS_2100;
1980                 ha->mbx_count = MAILBOX_REGISTER_COUNT_2100;
1981                 ha->request_q_length = REQUEST_ENTRY_CNT_2100;
1982                 ha->response_q_length = RESPONSE_ENTRY_CNT_2100;
1983                 ha->last_loop_id = SNS_LAST_LOOP_ID_2100;
1984                 host->sg_tablesize = 32;
1985         } else if (IS_QLA2200(ha)) {
1986                 ha->max_targets = MAX_TARGETS_2200;
1987                 ha->mbx_count = MAILBOX_REGISTER_COUNT;
1988                 ha->request_q_length = REQUEST_ENTRY_CNT_2200;
1989                 ha->response_q_length = RESPONSE_ENTRY_CNT_2100;
1990                 ha->last_loop_id = SNS_LAST_LOOP_ID_2100;
1991         } else /*if (IS_QLA2300(ha))*/ {
1992                 ha->max_targets = MAX_TARGETS_2200;
1993                 ha->mbx_count = MAILBOX_REGISTER_COUNT;
1994                 ha->request_q_length = REQUEST_ENTRY_CNT_2200;
1995                 ha->response_q_length = RESPONSE_ENTRY_CNT_2300;
1996                 ha->last_loop_id = SNS_LAST_LOOP_ID_2300;
1997         }
1998         host->can_queue = ha->request_q_length + 128;
1999
2000         /* load the F/W, read paramaters, and init the H/W */
2001         ha->instance = num_hosts;
2002
2003         init_MUTEX(&ha->mbx_cmd_sem);
2004         init_MUTEX_LOCKED(&ha->mbx_intr_sem);
2005
2006         INIT_LIST_HEAD(&ha->list);
2007         INIT_LIST_HEAD(&ha->fcports);
2008         INIT_LIST_HEAD(&ha->rscn_fcports);
2009         INIT_LIST_HEAD(&ha->done_queue);
2010         INIT_LIST_HEAD(&ha->retry_queue);
2011         INIT_LIST_HEAD(&ha->scsi_retry_queue);
2012         INIT_LIST_HEAD(&ha->pending_queue);
2013
2014         /*
2015          * These locks are used to prevent more than one CPU
2016          * from modifying the queue at the same time. The
2017          * higher level "host_lock" will reduce most
2018          * contention for these locks.
2019          */
2020         spin_lock_init(&ha->mbx_reg_lock);
2021         spin_lock_init(&ha->list_lock);
2022
2023         ha->dpc_pid = -1;
2024         init_completion(&ha->dpc_inited);
2025         init_completion(&ha->dpc_exited);
2026
2027         qla2x00_config_dma_addressing(ha);
2028         if (qla2x00_mem_alloc(ha)) {
2029                 qla_printk(KERN_WARNING, ha,
2030                     "[ERROR] Failed to allocate memory for adapter\n");
2031
2032                 goto probe_failed;
2033         }
2034
2035         if (qla2x00_initialize_adapter(ha) &&
2036             !(ha->device_flags & DFLG_NO_CABLE)) {
2037
2038                 qla_printk(KERN_WARNING, ha,
2039                     "Failed to initialize adapter\n");
2040
2041                 DEBUG2(printk("scsi(%ld): Failed to initialize adapter - "
2042                     "Adapter flags %x.\n",
2043                     ha->host_no, ha->device_flags));
2044
2045                 goto probe_failed;
2046         }
2047
2048         /*
2049          * Startup the kernel thread for this host adapter
2050          */
2051         ha->dpc_should_die = 0;
2052         ha->dpc_pid = kernel_thread(qla2x00_do_dpc, ha, 0);
2053         if (ha->dpc_pid < 0) {
2054                 qla_printk(KERN_WARNING, ha,
2055                     "Unable to start DPC thread!\n");
2056
2057                 goto probe_failed;
2058         }
2059         wait_for_completion(&ha->dpc_inited);
2060
2061         host->this_id = 255;
2062         host->cmd_per_lun = 3;
2063         host->max_cmd_len = MAX_CMDSZ;
2064         host->max_channel = ha->ports - 1;
2065         host->max_lun = ha->max_luns;
2066         BUG_ON(qla2xxx_transport_template == NULL);
2067         host->transportt = qla2xxx_transport_template;
2068         host->unique_id = ha->instance;
2069         host->max_id = ha->max_targets;
2070
2071         if (request_irq(host->irq, qla2x00_intr_handler, SA_INTERRUPT|SA_SHIRQ,
2072             ha->brd_info->drv_name, ha)) {
2073                 qla_printk(KERN_WARNING, ha,
2074                     "Failed to reserve interrupt %d already in use.\n",
2075                     host->irq);
2076                 goto probe_failed;
2077         }
2078
2079         /* Initialized the timer */
2080         qla2x00_start_timer(ha, qla2x00_timer, WATCH_INTERVAL);
2081
2082         DEBUG2(printk("DEBUG: detect hba %ld at address = %p\n",
2083             ha->host_no, ha));
2084
2085         reg = ha->iobase;
2086
2087         /* Disable ISP interrupts. */
2088         qla2x00_disable_intrs(ha);
2089
2090         /* Ensure mailbox registers are free. */
2091         spin_lock_irqsave(&ha->hardware_lock, flags);
2092         WRT_REG_WORD(&reg->semaphore, 0);
2093         WRT_REG_WORD(&reg->hccr, HCCR_CLR_RISC_INT);
2094         WRT_REG_WORD(&reg->hccr, HCCR_CLR_HOST_INT);
2095
2096         /* Enable proper parity */
2097         if (!IS_QLA2100(ha) && !IS_QLA2200(ha)) {
2098                 if (IS_QLA2300(ha))
2099                         /* SRAM parity */
2100                         WRT_REG_WORD(&reg->hccr, (HCCR_ENABLE_PARITY + 0x1));
2101                 else
2102                         /* SRAM, Instruction RAM and GP RAM parity */
2103                         WRT_REG_WORD(&reg->hccr, (HCCR_ENABLE_PARITY + 0x7));
2104         }
2105         spin_unlock_irqrestore(&ha->hardware_lock, flags);
2106
2107         /* Enable chip interrupts. */
2108         qla2x00_enable_intrs(ha);
2109
2110         /* v2.19.5b6 */
2111         /*
2112          * Wait around max loop_reset_delay secs for the devices to come
2113          * on-line. We don't want Linux scanning before we are ready.
2114          *
2115          */
2116         for (wait_switch = jiffies + (ha->loop_reset_delay * HZ);
2117             time_before(jiffies,wait_switch) &&
2118              !(ha->device_flags & (DFLG_NO_CABLE | DFLG_FABRIC_DEVICES))
2119              && (ha->device_flags & SWITCH_FOUND) ;) {
2120
2121                 qla2x00_check_fabric_devices(ha);
2122
2123                 set_current_state(TASK_UNINTERRUPTIBLE);
2124                 schedule_timeout(HZ/100);
2125         }
2126
2127         pci_set_drvdata(pdev, ha);
2128         ha->flags.init_done = 1;
2129         num_hosts++;
2130
2131         /* List the target we have found */
2132         if (displayConfig) {
2133                 qla2x00_display_fc_names(ha);
2134         }
2135
2136         if (scsi_add_host(host, &pdev->dev))
2137                 goto probe_failed;
2138
2139         sysfs_create_bin_file(&host->shost_gendev.kobj, &sysfs_fw_dump_attr);
2140         sysfs_create_bin_file(&host->shost_gendev.kobj, &sysfs_nvram_attr);
2141
2142         qla_printk(KERN_INFO, ha, "\n"
2143             " QLogic Fibre Channel HBA Driver: %s\n"
2144             "  QLogic %s - %s\n"
2145             "  %s: %s @ %s hdma%c, host#=%ld, fw=%s\n", qla2x00_version_str,
2146             ha->model_number, ha->model_desc ? ha->model_desc: "",
2147             ha->brd_info->isp_name, qla2x00_get_pci_info_str(ha, pci_info),
2148             pci_name(ha->pdev), ha->flags.enable_64bit_addressing ? '+': '-',
2149             ha->host_no, qla2x00_get_fw_version_str(ha, fw_str));
2150
2151         if (ql2xdoinitscan)
2152                 scsi_scan_host(host);
2153
2154         return 0;
2155
2156 probe_failed:
2157         qla2x00_free_device(ha);
2158
2159         scsi_host_put(host);
2160
2161         return -1;
2162 }
2163 EXPORT_SYMBOL_GPL(qla2x00_probe_one);
2164
2165 void qla2x00_remove_one(struct pci_dev *pdev)
2166 {
2167         scsi_qla_host_t *ha;
2168
2169         ha = pci_get_drvdata(pdev);
2170
2171         sysfs_remove_bin_file(&ha->host->shost_gendev.kobj,
2172             &sysfs_fw_dump_attr);
2173         sysfs_remove_bin_file(&ha->host->shost_gendev.kobj, &sysfs_nvram_attr);
2174
2175         scsi_remove_host(ha->host);
2176
2177         qla2x00_free_device(ha);
2178
2179         scsi_host_put(ha->host);
2180
2181         pci_set_drvdata(pdev, NULL);
2182 }
2183 EXPORT_SYMBOL_GPL(qla2x00_remove_one);
2184
2185 static void
2186 qla2x00_free_device(scsi_qla_host_t *ha)
2187 {
2188         int ret;
2189
2190         /* Abort any outstanding IO descriptors. */
2191         if (!IS_QLA2100(ha) && !IS_QLA2200(ha))
2192                 qla2x00_cancel_io_descriptors(ha);
2193
2194         /* turn-off interrupts on the card */
2195         if (ha->interrupts_on)
2196                 qla2x00_disable_intrs(ha);
2197
2198         /* Disable timer */
2199         if (ha->timer_active)
2200                 qla2x00_stop_timer(ha);
2201
2202         /* Kill the kernel thread for this host */
2203         if (ha->dpc_pid >= 0) {
2204                 ha->dpc_should_die = 1;
2205                 wmb();
2206                 ret = kill_proc(ha->dpc_pid, SIGHUP, 1);
2207                 if (ret) {
2208                         qla_printk(KERN_ERR, ha,
2209                             "Unable to signal DPC thread -- (%d)\n", ret);
2210
2211                         /* TODO: SOMETHING MORE??? */
2212                 } else {
2213                         wait_for_completion(&ha->dpc_exited);
2214                 }
2215         }
2216
2217         qla2x00_mem_free(ha);
2218
2219
2220         ha->flags.online = 0;
2221
2222         /* Detach interrupts */
2223         if (ha->pdev->irq)
2224                 free_irq(ha->pdev->irq, ha);
2225
2226         /* release io space registers  */
2227         pci_release_regions(ha->pdev);
2228
2229 #if MEMORY_MAPPED_IO
2230         if (ha->mmio_address)
2231                 iounmap(ha->mmio_address);
2232 #endif
2233 }
2234
2235
2236 /*
2237  * The following support functions are adopted to handle
2238  * the re-entrant qla2x00_proc_info correctly.
2239  */
2240 static void
2241 copy_mem_info(struct info_str *info, char *data, int len)
2242 {
2243         if (info->pos + len > info->offset + info->length)
2244                 len = info->offset + info->length - info->pos;
2245
2246         if (info->pos + len < info->offset) {
2247                 info->pos += len;
2248                 return;
2249         }
2250  
2251         if (info->pos < info->offset) {
2252                 off_t partial;
2253  
2254                 partial = info->offset - info->pos;
2255                 data += partial;
2256                 info->pos += partial;
2257                 len  -= partial;
2258         }
2259  
2260         if (len > 0) {
2261                 memcpy(info->buffer, data, len);
2262                 info->pos += len;
2263                 info->buffer += len;
2264         }
2265 }
2266
2267 static int
2268 copy_info(struct info_str *info, char *fmt, ...)
2269 {
2270         va_list args;
2271         char buf[256];
2272         int len;
2273  
2274         va_start(args, fmt);
2275         len = vsprintf(buf, fmt, args);
2276         va_end(args);
2277  
2278         copy_mem_info(info, buf, len);
2279
2280         return (len);
2281 }
2282
2283 /*************************************************************************
2284 * qla2x00_proc_info
2285 *
2286 * Description:
2287 *   Return information to handle /proc support for the driver.
2288 *
2289 * inout : decides the direction of the dataflow and the meaning of the
2290 *         variables
2291 * buffer: If inout==0 data is being written to it else read from it
2292 *         (ptr to a page buffer)
2293 * *start: If inout==0 start of the valid data in the buffer
2294 * offset: If inout==0 starting offset from the beginning of all
2295 *         possible data to return.
2296 * length: If inout==0 max number of bytes to be written into the buffer
2297 *         else number of bytes in "buffer"
2298 * Returns:
2299 *         < 0:  error. errno value.
2300 *         >= 0: sizeof data returned.
2301 *************************************************************************/
2302 int
2303 qla2x00_proc_info(struct Scsi_Host *shost, char *buffer,
2304     char **start, off_t offset, int length, int inout)
2305 {
2306         struct info_str info;
2307         int             retval = -EINVAL;
2308         os_lun_t        *up;
2309         os_tgt_t        *tq;
2310         unsigned int    t, l;
2311         uint32_t        tmp_sn;
2312         uint32_t        *flags;
2313         uint8_t         *loop_state;
2314         scsi_qla_host_t *ha;
2315         char fw_info[30];
2316  
2317         DEBUG3(printk(KERN_INFO
2318             "Entering proc_info buff_in=%p, offset=0x%lx, length=0x%x\n",
2319             buffer, offset, length);)
2320
2321         ha = (scsi_qla_host_t *) shost->hostdata;
2322
2323         if (inout) {
2324                 /* Has data been written to the file? */
2325                 DEBUG3(printk(
2326                     "%s: has data been written to the file. \n",
2327                     __func__);)
2328
2329                 return (qla2x00_set_info(buffer, length, shost));
2330         }
2331
2332         if (start) {
2333                 *start = buffer;
2334         }
2335
2336         info.buffer = buffer;
2337         info.length = length;
2338         info.offset = offset;
2339         info.pos    = 0;
2340
2341         /* start building the print buffer */
2342         copy_info(&info,
2343             "QLogic PCI to Fibre Channel Host Adapter for %s:\n"
2344             "        Firmware version %s, ",
2345             ha->model_number, qla2x00_get_fw_version_str(ha, fw_info));
2346
2347         copy_info(&info, "Driver version %s\n", qla2x00_version_str);
2348
2349         copy_info(&info, "Entry address = %p\n", qla2x00_set_info);
2350
2351         tmp_sn = ((ha->serial0 & 0x1f) << 16) | (ha->serial2 << 8) | 
2352             ha->serial1;
2353         copy_info(&info, "ISP: %s, Serial# %c%05d\n",
2354             ha->brd_info->isp_name, ('A' + tmp_sn/100000), (tmp_sn%100000));
2355
2356         copy_info(&info,
2357             "Request Queue = 0x%llx, Response Queue = 0x%llx\n",
2358                 (unsigned long long)ha->request_dma,
2359                 (unsigned long long)ha->response_dma);
2360
2361         copy_info(&info,
2362             "Request Queue count = %d, Response Queue count = %d\n",
2363             ha->request_q_length, ha->response_q_length);
2364
2365         copy_info(&info,
2366             "Total number of active commands = %ld\n",
2367             ha->actthreads);
2368
2369         copy_info(&info,
2370             "Total number of interrupts = %ld\n",
2371             (long)ha->total_isr_cnt);
2372
2373         copy_info(&info,
2374             "    Device queue depth = 0x%x\n",
2375             (ql2xmaxqdepth == 0) ? 16 : ql2xmaxqdepth);
2376
2377         copy_info(&info,
2378             "Number of free request entries = %d\n", ha->req_q_cnt);
2379
2380         copy_info(&info,
2381             "Number of mailbox timeouts = %ld\n", ha->total_mbx_timeout);
2382
2383         copy_info(&info,
2384             "Number of ISP aborts = %ld\n", ha->total_isp_aborts);
2385
2386         copy_info(&info,
2387             "Number of loop resyncs = %ld\n", ha->total_loop_resync);
2388
2389         copy_info(&info,
2390             "Number of retries for empty slots = %ld\n",
2391             qla2x00_stats.outarray_full);
2392
2393         copy_info(&info,
2394             "Number of reqs in pending_q= %ld, retry_q= %d, "
2395             "done_q= %ld, scsi_retry_q= %d\n",
2396             ha->qthreads, ha->retry_q_cnt,
2397             ha->done_q_cnt, ha->scsi_retry_q_cnt);
2398
2399
2400         flags = (uint32_t *) &ha->flags;
2401
2402         if (atomic_read(&ha->loop_state) == LOOP_DOWN) {
2403                 loop_state = "DOWN";
2404         } else if (atomic_read(&ha->loop_state) == LOOP_UP) {
2405                 loop_state = "UP";
2406         } else if (atomic_read(&ha->loop_state) == LOOP_READY) {
2407                 loop_state = "READY";
2408         } else if (atomic_read(&ha->loop_state) == LOOP_TIMEOUT) {
2409                 loop_state = "TIMEOUT";
2410         } else if (atomic_read(&ha->loop_state) == LOOP_UPDATE) {
2411                 loop_state = "UPDATE";
2412         } else {
2413                 loop_state = "UNKNOWN";
2414         }
2415
2416         copy_info(&info, 
2417             "Host adapter:loop state = <%s>, flags = 0x%lx\n",
2418             loop_state , *flags);
2419
2420         copy_info(&info, "Dpc flags = 0x%lx\n", ha->dpc_flags);
2421
2422         copy_info(&info, "MBX flags = 0x%x\n", ha->mbx_flags);
2423
2424         copy_info(&info, "Link down Timeout = %3.3d\n",
2425             ha->link_down_timeout);
2426
2427         copy_info(&info, "Port down retry = %3.3d\n",
2428             ha->port_down_retry_count);
2429
2430         copy_info(&info, "Login retry count = %3.3d\n",
2431             ha->login_retry_count);
2432
2433         copy_info(&info,
2434             "Commands retried with dropped frame(s) = %d\n",
2435             ha->dropped_frame_error_cnt);
2436
2437         copy_info(&info,
2438             "Product ID = %04x %04x %04x %04x\n", ha->product_id[0],
2439             ha->product_id[1], ha->product_id[2], ha->product_id[3]);
2440
2441         copy_info(&info, "\n");
2442
2443         /* 2.25 node/port display to proc */
2444         /* Display the node name for adapter */
2445         copy_info(&info, "\nSCSI Device Information:\n");
2446         copy_info(&info,
2447             "scsi-qla%d-adapter-node="
2448             "%02x%02x%02x%02x%02x%02x%02x%02x;\n",
2449             (int)ha->instance,
2450             ha->init_cb->node_name[0],
2451             ha->init_cb->node_name[1],
2452             ha->init_cb->node_name[2],
2453             ha->init_cb->node_name[3],
2454             ha->init_cb->node_name[4],
2455             ha->init_cb->node_name[5],
2456             ha->init_cb->node_name[6],
2457             ha->init_cb->node_name[7]);
2458
2459         /* display the port name for adapter */
2460         copy_info(&info,
2461             "scsi-qla%d-adapter-port="
2462             "%02x%02x%02x%02x%02x%02x%02x%02x;\n",
2463             (int)ha->instance,
2464             ha->init_cb->port_name[0],
2465             ha->init_cb->port_name[1],
2466             ha->init_cb->port_name[2],
2467             ha->init_cb->port_name[3],
2468             ha->init_cb->port_name[4],
2469             ha->init_cb->port_name[5],
2470             ha->init_cb->port_name[6],
2471             ha->init_cb->port_name[7]);
2472
2473         /* Print out device port names */
2474         for (t = 0; t < MAX_FIBRE_DEVICES; t++) {
2475                 if ((tq = TGT_Q(ha, t)) == NULL)
2476                         continue;
2477
2478                 copy_info(&info,
2479                     "scsi-qla%d-target-%d="
2480                     "%02x%02x%02x%02x%02x%02x%02x%02x;\n",
2481                     (int)ha->instance, t,
2482                     tq->port_name[0], tq->port_name[1],
2483                     tq->port_name[2], tq->port_name[3],
2484                     tq->port_name[4], tq->port_name[5],
2485                     tq->port_name[6], tq->port_name[7]);
2486         }
2487
2488         copy_info(&info, "\nSCSI LUN Information:\n");
2489         copy_info(&info,
2490             "(Id:Lun)  * - indicates lun is not registered with the OS.\n");
2491
2492         /* scan for all equipment stats */
2493         for (t = 0; t < MAX_FIBRE_DEVICES; t++) {
2494                 /* scan all luns */
2495                 for (l = 0; l < ha->max_luns; l++) {
2496                         up = (os_lun_t *) GET_LU_Q(ha, t, l);
2497
2498                         if (up == NULL) {
2499                                 continue;
2500                         }
2501                         if (up->fclun == NULL) {
2502                                 continue;
2503                         }
2504
2505                         copy_info(&info,
2506                             "(%2d:%2d): Total reqs %ld,",
2507                             t,l,up->io_cnt);
2508
2509                         copy_info(&info,
2510                             " Pending reqs %ld,",
2511                             up->out_cnt);
2512
2513                         if (up->io_cnt < 4) {
2514                                 copy_info(&info,
2515                                     " flags 0x%x*,",
2516                                     (int)up->q_flag);
2517                         } else {
2518                                 copy_info(&info,
2519                                     " flags 0x%x,",
2520                                     (int)up->q_flag);
2521                         }
2522
2523                         copy_info(&info, 
2524                             " %ld:%d:%02x %02x",
2525                             up->fclun->fcport->ha->instance,
2526                             up->fclun->fcport->cur_path,
2527                             up->fclun->fcport->loop_id,
2528                             up->fclun->device_type);
2529
2530                         copy_info(&info, "\n");
2531
2532                         if (info.pos >= info.offset + info.length) {
2533                                 /* No need to continue */
2534                                 goto profile_stop;
2535                         }
2536                 }
2537
2538                 if (info.pos >= info.offset + info.length) {
2539                         /* No need to continue */
2540                         break;
2541                 }
2542         }
2543
2544 profile_stop:
2545
2546         retval = info.pos > info.offset ? info.pos - info.offset : 0;
2547
2548         DEBUG3(printk(KERN_INFO 
2549             "Exiting proc_info: info.pos=%d, offset=0x%lx, "
2550             "length=0x%x\n", info.pos, offset, length);)
2551
2552         return (retval);
2553 }
2554
2555 /*
2556 * qla2x00_display_fc_names
2557 *      This routine will the node names of the different devices found
2558 *      after port inquiry.
2559 *
2560 * Input:
2561 *      cmd = SCSI command structure
2562 *
2563 * Returns:
2564 *      None.
2565 */
2566 static void
2567 qla2x00_display_fc_names(scsi_qla_host_t *ha) 
2568 {
2569         uint16_t        tgt;
2570         os_tgt_t        *tq;
2571
2572         /* Display the node name for adapter */
2573         qla_printk(KERN_INFO, ha,
2574             "scsi-qla%d-adapter-node=%02x%02x%02x%02x%02x%02x%02x%02x\\;\n",
2575             (int)ha->instance,
2576             ha->init_cb->node_name[0],
2577             ha->init_cb->node_name[1],
2578             ha->init_cb->node_name[2],
2579             ha->init_cb->node_name[3],
2580             ha->init_cb->node_name[4],
2581             ha->init_cb->node_name[5],
2582             ha->init_cb->node_name[6],
2583             ha->init_cb->node_name[7]);
2584
2585         /* display the port name for adapter */
2586         qla_printk(KERN_INFO, ha,
2587             "scsi-qla%d-adapter-port=%02x%02x%02x%02x%02x%02x%02x%02x\\;\n",
2588             (int)ha->instance,
2589             ha->init_cb->port_name[0],
2590             ha->init_cb->port_name[1],
2591             ha->init_cb->port_name[2],
2592             ha->init_cb->port_name[3],
2593             ha->init_cb->port_name[4],
2594             ha->init_cb->port_name[5],
2595             ha->init_cb->port_name[6],
2596             ha->init_cb->port_name[7]);
2597
2598         /* Print out device port names */
2599         for (tgt = 0; tgt < MAX_TARGETS; tgt++) {
2600                 if ((tq = ha->otgt[tgt]) == NULL)
2601                         continue;
2602
2603                 if (tq->fcport == NULL)
2604                         continue;
2605
2606                 switch (ha->binding_type) {
2607                         case BIND_BY_PORT_NAME:
2608                                 qla_printk(KERN_INFO, ha,
2609                                     "scsi-qla%d-tgt-%d-di-0-port="
2610                                     "%02x%02x%02x%02x%02x%02x%02x%02x\\;\n",
2611                                     (int)ha->instance, 
2612                                     tgt,
2613                                     tq->port_name[0], 
2614                                     tq->port_name[1],
2615                                     tq->port_name[2], 
2616                                     tq->port_name[3],
2617                                     tq->port_name[4], 
2618                                     tq->port_name[5],
2619                                     tq->port_name[6], 
2620                                     tq->port_name[7]);
2621
2622                                 break;
2623
2624                         case BIND_BY_PORT_ID:
2625                                 qla_printk(KERN_INFO, ha,
2626                                     "scsi-qla%d-tgt-%d-di-0-pid="
2627                                     "%02x%02x%02x\\;\n",
2628                                     (int)ha->instance,
2629                                     tgt,
2630                                     tq->d_id.b.domain,
2631                                     tq->d_id.b.area,
2632                                     tq->d_id.b.al_pa);
2633                                 break;
2634                 }
2635
2636 #if VSA
2637                 qla_printk(KERN_INFO, ha,
2638                     "scsi-qla%d-target-%d-vsa=01;\n", (int)ha->instance, tgt);
2639 #endif
2640         }
2641 }
2642
2643 /*
2644  *  qla2x00_suspend_lun
2645  *      Suspend lun and start port down timer
2646  *
2647  * Input:
2648  *      ha = visable adapter block pointer.
2649  *  lq = lun queue
2650  *  cp = Scsi command pointer 
2651  *  time = time in seconds
2652  *  count = number of times to let time expire
2653  *  delay_lun = non-zero, if lun should be delayed rather than suspended
2654  *
2655  * Return:
2656  *     QLA_SUCCESS  -- suspended lun 
2657  *     QLA_FUNCTION_FAILED  -- Didn't suspend lun
2658  *
2659  * Context:
2660  *      Interrupt context.
2661  */
2662 int
2663 __qla2x00_suspend_lun(scsi_qla_host_t *ha,
2664                 os_lun_t *lq, int time, int count, int delay_lun)
2665 {
2666         int     rval;
2667         srb_t *sp;
2668         struct list_head *list, *temp;
2669         unsigned long flags;
2670
2671         rval = QLA_SUCCESS;
2672
2673         /* if the lun_q is already suspended then don't do it again */
2674         if (lq->q_state == LUN_STATE_READY ||lq->q_state == LUN_STATE_RUN) {
2675
2676                 spin_lock_irqsave(&lq->q_lock, flags);
2677                 if (lq->q_state == LUN_STATE_READY) {
2678                         lq->q_max = count;
2679                         lq->q_count = 0;
2680                 }
2681                 /* Set the suspend time usually 6 secs */
2682                 atomic_set(&lq->q_timer, time);
2683
2684                 /* now suspend the lun */
2685                 lq->q_state = LUN_STATE_WAIT;
2686
2687                 if (delay_lun) {
2688                         set_bit(LUN_EXEC_DELAYED, &lq->q_flag);
2689                         DEBUG(printk(KERN_INFO
2690                             "scsi(%ld): Delay lun execution for %d secs, "
2691                             "count=%d, max count=%d, state=%d\n",
2692                             ha->host_no,
2693                             time,
2694                             lq->q_count, lq->q_max, lq->q_state));
2695                 } else {
2696                         DEBUG(printk(KERN_INFO
2697                             "scsi(%ld): Suspend lun for %d secs, count=%d, "
2698                             "max count=%d, state=%d\n",
2699                             ha->host_no,
2700                             time,
2701                             lq->q_count, lq->q_max, lq->q_state));
2702                 }
2703                 spin_unlock_irqrestore(&lq->q_lock, flags);
2704
2705                 /*
2706                  * Remove all pending commands from request queue and  put them
2707                  * in the scsi_retry queue.
2708                  */
2709                 spin_lock_irqsave(&ha->list_lock, flags);
2710                 list_for_each_safe(list, temp, &ha->pending_queue) {
2711                         sp = list_entry(list, srb_t, list);
2712                         if (sp->lun_queue != lq)
2713                                 continue;
2714
2715                         __del_from_pending_queue(ha, sp);
2716
2717                         if (sp->cmd->allowed < count)
2718                                 sp->cmd->allowed = count;
2719                         __add_to_scsi_retry_queue(ha, sp);
2720
2721                 } /* list_for_each_safe */
2722                 spin_unlock_irqrestore(&ha->list_lock, flags);
2723                 rval = QLA_SUCCESS;
2724         } else {
2725                 rval = QLA_FUNCTION_FAILED;
2726         }
2727
2728         return (rval);
2729 }
2730
2731 /*
2732  * qla2x00_mark_device_lost Updates fcport state when device goes offline.
2733  *
2734  * Input: ha = adapter block pointer.  fcport = port structure pointer.
2735  *
2736  * Return: None.
2737  *
2738  * Context:
2739  */
2740 void qla2x00_mark_device_lost(scsi_qla_host_t *ha, fc_port_t *fcport,
2741     int do_login)
2742 {
2743         /* 
2744          * We may need to retry the login, so don't change the state of the
2745          * port but do the retries.
2746          */
2747         if (atomic_read(&fcport->state) != FCS_DEVICE_DEAD)
2748                 atomic_set(&fcport->state, FCS_DEVICE_LOST);
2749
2750         if (!do_login)
2751                 return;
2752
2753         if (fcport->login_retry == 0) {
2754                 fcport->login_retry = ha->login_retry_count;
2755                 set_bit(RELOGIN_NEEDED, &ha->dpc_flags);
2756
2757                 DEBUG(printk("scsi(%ld): Port login retry: "
2758                     "%02x%02x%02x%02x%02x%02x%02x%02x, "
2759                     "id = 0x%04x retry cnt=%d\n",
2760                     ha->host_no,
2761                     fcport->port_name[0],
2762                     fcport->port_name[1],
2763                     fcport->port_name[2],
2764                     fcport->port_name[3],
2765                     fcport->port_name[4],
2766                     fcport->port_name[5],
2767                     fcport->port_name[6],
2768                     fcport->port_name[7],
2769                     fcport->loop_id,
2770                     fcport->login_retry));
2771         }
2772 }
2773
2774 /*
2775  * qla2x00_mark_all_devices_lost
2776  *      Updates fcport state when device goes offline.
2777  *
2778  * Input:
2779  *      ha = adapter block pointer.
2780  *      fcport = port structure pointer.
2781  *
2782  * Return:
2783  *      None.
2784  *
2785  * Context:
2786  */
2787 void
2788 qla2x00_mark_all_devices_lost(scsi_qla_host_t *ha) 
2789 {
2790         fc_port_t *fcport;
2791
2792         list_for_each_entry(fcport, &ha->fcports, list) {
2793                 if (fcport->port_type != FCT_TARGET)
2794                         continue;
2795
2796                 /*
2797                  * No point in marking the device as lost, if the device is
2798                  * already DEAD.
2799                  */
2800                 if (atomic_read(&fcport->state) == FCS_DEVICE_DEAD)
2801                         continue;
2802
2803                 atomic_set(&fcport->state, FCS_DEVICE_LOST);
2804         }
2805 }
2806
2807 /*
2808 * qla2x00_mem_alloc
2809 *      Allocates adapter memory.
2810 *
2811 * Returns:
2812 *      0  = success.
2813 *      1  = failure.
2814 */
2815 static uint8_t
2816 qla2x00_mem_alloc(scsi_qla_host_t *ha)
2817 {
2818         uint8_t   status = 1;
2819         int     retry= 10;
2820
2821         do {
2822                 /*
2823                  * This will loop only once if everything goes well, else some
2824                  * number of retries will be performed to get around a kernel
2825                  * bug where available mem is not allocated until after a
2826                  * little delay and a retry.
2827                  */
2828                 ha->request_ring = pci_alloc_consistent(ha->pdev,
2829                     ((ha->request_q_length + 1) * (sizeof(request_t))),
2830                     &ha->request_dma);
2831                 if (ha->request_ring == NULL) {
2832                         qla_printk(KERN_WARNING, ha,
2833                             "Memory Allocation failed - request_ring\n");
2834
2835                         qla2x00_mem_free(ha);
2836                         set_current_state(TASK_UNINTERRUPTIBLE);
2837                         schedule_timeout(HZ/10);
2838
2839                         continue;
2840                 }
2841
2842                 ha->response_ring = pci_alloc_consistent(ha->pdev,
2843                     ((ha->response_q_length + 1) * (sizeof(response_t))),
2844                     &ha->response_dma);
2845                 if (ha->response_ring == NULL) {
2846                         qla_printk(KERN_WARNING, ha,
2847                             "Memory Allocation failed - response_ring\n");
2848
2849                         qla2x00_mem_free(ha);
2850                         set_current_state(TASK_UNINTERRUPTIBLE);
2851                         schedule_timeout(HZ/10);
2852
2853                         continue;
2854                 }
2855
2856                 /* get consistent memory allocated for init control block */
2857                 ha->init_cb = pci_alloc_consistent(ha->pdev,
2858                     sizeof(init_cb_t), &ha->init_cb_dma);
2859                 if (ha->init_cb == NULL) {
2860                         qla_printk(KERN_WARNING, ha,
2861                             "Memory Allocation failed - init_cb\n");
2862
2863                         qla2x00_mem_free(ha);
2864                         set_current_state(TASK_UNINTERRUPTIBLE);
2865                         schedule_timeout(HZ/10);
2866
2867                         continue;
2868                 }
2869                 memset(ha->init_cb, 0, sizeof(init_cb_t));
2870
2871                 /* Allocate ioctl related memory. */
2872                 if (qla2x00_alloc_ioctl_mem(ha)) {
2873                         qla_printk(KERN_WARNING, ha,
2874                             "Memory Allocation failed - ioctl_mem\n");
2875
2876                         qla2x00_mem_free(ha);
2877                         set_current_state(TASK_UNINTERRUPTIBLE);
2878                         schedule_timeout(HZ/10);
2879
2880                         continue;
2881                 }
2882
2883                 if (qla2x00_allocate_sp_pool(ha)) {
2884                         qla_printk(KERN_WARNING, ha,
2885                             "Memory Allocation failed - "
2886                             "qla2x00_allocate_sp_pool()\n");
2887
2888                         qla2x00_mem_free(ha);
2889                         set_current_state(TASK_UNINTERRUPTIBLE);
2890                         schedule_timeout(HZ/10);
2891
2892                         continue;
2893                 }
2894
2895                 /* Allocate memory for SNS commands */
2896                 if (IS_QLA2100(ha) || IS_QLA2200(ha)) {
2897                         /* Get consistent memory allocated for SNS commands */
2898                         ha->sns_cmd = pci_alloc_consistent(ha->pdev,
2899                             sizeof(struct sns_cmd_pkt), &ha->sns_cmd_dma);
2900                         if (ha->sns_cmd == NULL) {
2901                                 /* error */
2902                                 qla_printk(KERN_WARNING, ha,
2903                                     "Memory Allocation failed - sns_cmd\n");
2904
2905                                 qla2x00_mem_free(ha);
2906                                 set_current_state(TASK_UNINTERRUPTIBLE);
2907                                 schedule_timeout(HZ/10);
2908
2909                                 continue;
2910                         }
2911                         memset(ha->sns_cmd, 0, sizeof(struct sns_cmd_pkt));
2912                 } else {
2913                         /* Get consistent memory allocated for MS IOCB */
2914                         ha->ms_iocb = pci_alloc_consistent(ha->pdev,
2915                             sizeof(ms_iocb_entry_t), &ha->ms_iocb_dma);
2916                         if (ha->ms_iocb == NULL) {
2917                                 /* error */
2918                                 qla_printk(KERN_WARNING, ha,
2919                                     "Memory Allocation failed - ms_iocb\n");
2920
2921                                 qla2x00_mem_free(ha);
2922                                 set_current_state(TASK_UNINTERRUPTIBLE);
2923                                 schedule_timeout(HZ/10);
2924
2925                                 continue;
2926                         }
2927                         memset(ha->ms_iocb, 0, sizeof(ms_iocb_entry_t));
2928
2929                         /*
2930                          * Get consistent memory allocated for CT SNS
2931                          * commands
2932                          */
2933                         ha->ct_sns = pci_alloc_consistent(ha->pdev,
2934                             sizeof(struct ct_sns_pkt), &ha->ct_sns_dma);
2935                         if (ha->ct_sns == NULL) {
2936                                 /* error */
2937                                 qla_printk(KERN_WARNING, ha,
2938                                     "Memory Allocation failed - ct_sns\n");
2939
2940                                 qla2x00_mem_free(ha);
2941                                 set_current_state(TASK_UNINTERRUPTIBLE);
2942                                 schedule_timeout(HZ/10);
2943
2944                                 continue;
2945                         }
2946                         memset(ha->ct_sns, 0, sizeof(struct ct_sns_pkt));
2947                 }
2948
2949                 /* Get consistent memory allocated for Get Port Database cmd */
2950                 ha->iodesc_pd = pci_alloc_consistent(ha->pdev,
2951                     PORT_DATABASE_SIZE, &ha->iodesc_pd_dma);
2952                 if (ha->iodesc_pd == NULL) {
2953                         /* error */
2954                         qla_printk(KERN_WARNING, ha,
2955                             "Memory Allocation failed - iodesc_pd\n");
2956
2957                         qla2x00_mem_free(ha);
2958                         set_current_state(TASK_UNINTERRUPTIBLE);
2959                         schedule_timeout(HZ/10);
2960
2961                         continue;
2962                 }
2963                 memset(ha->iodesc_pd, 0, PORT_DATABASE_SIZE);
2964
2965                 /* Done all allocations without any error. */
2966                 status = 0;
2967
2968         } while (retry-- && status != 0);
2969
2970         if (status) {
2971                 printk(KERN_WARNING
2972                         "%s(): **** FAILED ****\n", __func__);
2973         }
2974
2975         return(status);
2976 }
2977
2978 /*
2979 * qla2x00_mem_free
2980 *      Frees all adapter allocated memory.
2981 *
2982 * Input:
2983 *      ha = adapter block pointer.
2984 */
2985 static void
2986 qla2x00_mem_free(scsi_qla_host_t *ha)
2987 {
2988         uint32_t        t;
2989         struct list_head        *fcpl, *fcptemp;
2990         fc_port_t       *fcport;
2991         struct list_head        *fcll, *fcltemp;
2992         fc_lun_t        *fclun;
2993         unsigned long   wtime;/* max wait time if mbx cmd is busy. */
2994
2995         if (ha == NULL) {
2996                 /* error */
2997                 DEBUG2(printk("%s(): ERROR invalid ha pointer.\n", __func__));
2998                 return;
2999         }
3000
3001         /* Free the target queues */
3002         for (t = 0; t < MAX_TARGETS; t++) {
3003                 qla2x00_tgt_free(ha, t);
3004         }
3005
3006         /* Make sure all other threads are stopped. */
3007         wtime = 60 * HZ;
3008         while (ha->dpc_wait && wtime) {
3009                 set_current_state(TASK_INTERRUPTIBLE);
3010                 wtime = schedule_timeout(wtime);
3011         }
3012
3013         /* free ioctl memory */
3014         qla2x00_free_ioctl_mem(ha);
3015
3016         /* free sp pool */
3017         qla2x00_free_sp_pool(ha);
3018
3019         if (ha->iodesc_pd) {
3020                 pci_free_consistent(ha->pdev, PORT_DATABASE_SIZE,
3021                     ha->iodesc_pd, ha->iodesc_pd_dma);
3022         }
3023
3024         if (ha->sns_cmd) {
3025                 pci_free_consistent(ha->pdev,
3026                     sizeof(struct sns_cmd_pkt), ha->sns_cmd, ha->sns_cmd_dma);
3027         }
3028
3029         if (ha->ct_sns) {
3030                 pci_free_consistent(ha->pdev,
3031                     sizeof(struct ct_sns_pkt), ha->ct_sns, ha->ct_sns_dma);
3032         }
3033         if (ha->ms_iocb) {
3034                 pci_free_consistent(ha->pdev,
3035                     sizeof(ms_iocb_entry_t), ha->ms_iocb, ha->ms_iocb_dma);
3036         }
3037
3038         if (ha->init_cb) {
3039                 pci_free_consistent(ha->pdev,
3040                     sizeof(init_cb_t), ha->init_cb, ha->init_cb_dma);
3041         }
3042
3043         if (ha->request_ring) {
3044                 pci_free_consistent(ha->pdev,
3045                     ((ha->request_q_length + 1) * (sizeof(request_t))),
3046                     ha->request_ring, ha->request_dma);
3047         }
3048
3049         if (ha->response_ring) {
3050                 pci_free_consistent(ha->pdev,
3051                     ((ha->response_q_length + 1) * (sizeof(response_t))),
3052                     ha->response_ring, ha->response_dma);
3053         }
3054
3055         ha->iodesc_pd = NULL;
3056         ha->iodesc_pd_dma = 0;
3057         ha->ct_sns = NULL;
3058         ha->ms_iocb = NULL;
3059
3060         ha->init_cb = NULL;
3061         ha->request_ring = NULL;
3062         ha->request_dma = 0;
3063         ha->response_ring = NULL;
3064         ha->response_dma = 0;
3065
3066         list_for_each_safe(fcpl, fcptemp, &ha->fcports) {
3067                 fcport = list_entry(fcpl, fc_port_t, list);
3068
3069                 /* fc luns */
3070                 list_for_each_safe(fcll, fcltemp, &fcport->fcluns) {
3071                         fclun = list_entry(fcll, fc_lun_t, list);
3072
3073                         list_del_init(&fclun->list);
3074                         kfree(fclun);
3075                 }
3076
3077                 /* fc ports */
3078                 list_del_init(&fcport->list);
3079                 kfree(fcport);
3080         }
3081         INIT_LIST_HEAD(&ha->fcports);
3082
3083         if (ha->fw_dump) {
3084                 free_pages((unsigned long)ha->fw_dump, ha->fw_dump_order);
3085                 ha->fw_dump = NULL;
3086         }
3087
3088         if (ha->fw_dump_buffer) {
3089                 vfree(ha->fw_dump_buffer);
3090                 ha->fw_dump_reading = 0;
3091                 ha->fw_dump_buffer = NULL;
3092         }
3093 }
3094
3095 /*
3096  * qla2x00_allocate_sp_pool
3097  *       This routine is called during initialization to allocate
3098  *       memory for local srb_t.
3099  *
3100  * Input:
3101  *       ha   = adapter block pointer.
3102  *
3103  * Context:
3104  *      Kernel context.
3105  * 
3106  * Note: Sets the ref_count for non Null sp to one.
3107  */
3108 int
3109 qla2x00_allocate_sp_pool(scsi_qla_host_t *ha) 
3110 {
3111         int      rval;
3112
3113         rval = QLA_SUCCESS;
3114         ha->srb_mempool = mempool_create(SRB_MIN_REQ, mempool_alloc_slab,
3115             mempool_free_slab, srb_cachep);
3116         if (ha->srb_mempool == NULL) {
3117                 qla_printk(KERN_INFO, ha, "Unable to allocate SRB mempool.\n");
3118                 rval = QLA_FUNCTION_FAILED;
3119         }
3120         return (rval);
3121 }
3122
3123 /*
3124  *  This routine frees all adapter allocated memory.
3125  *  
3126  */
3127 void
3128 qla2x00_free_sp_pool( scsi_qla_host_t *ha) 
3129 {
3130         if (ha->srb_mempool) {
3131                 mempool_destroy(ha->srb_mempool);
3132                 ha->srb_mempool = NULL;
3133         }
3134 }
3135
3136 /**************************************************************************
3137 * qla2x00_do_dpc
3138 *   This kernel thread is a task that is schedule by the interrupt handler
3139 *   to perform the background processing for interrupts.
3140 *
3141 * Notes:
3142 * This task always run in the context of a kernel thread.  It
3143 * is kick-off by the driver's detect code and starts up
3144 * up one per adapter. It immediately goes to sleep and waits for
3145 * some fibre event.  When either the interrupt handler or
3146 * the timer routine detects a event it will one of the task
3147 * bits then wake us up.
3148 **************************************************************************/
3149 static int
3150 qla2x00_do_dpc(void *data)
3151 {
3152         DECLARE_MUTEX_LOCKED(sem);
3153         scsi_qla_host_t *ha;
3154         fc_port_t       *fcport;
3155         os_lun_t        *q;
3156         srb_t           *sp;
3157         uint8_t         status;
3158         unsigned long   flags = 0;
3159         struct list_head *list, *templist;
3160         int     dead_cnt, online_cnt;
3161         int     retry_cmds = 0;
3162         uint16_t        next_loopid;
3163         int t;
3164         os_tgt_t *tq;
3165
3166         ha = (scsi_qla_host_t *)data;
3167
3168         lock_kernel();
3169
3170         daemonize("%s_dpc", ha->host_str);
3171         allow_signal(SIGHUP);
3172
3173         ha->dpc_wait = &sem;
3174
3175         set_user_nice(current, -20);
3176
3177         unlock_kernel();
3178
3179         complete(&ha->dpc_inited);
3180
3181         while (1) {
3182                 DEBUG3(printk("qla2x00: DPC handler sleeping\n"));
3183
3184                 if (down_interruptible(&sem))
3185                         break;
3186
3187                 if (ha->dpc_should_die)
3188                         break;
3189
3190                 if (!list_empty(&ha->done_queue))
3191                         qla2x00_done(ha);
3192
3193                 DEBUG3(printk("qla2x00: DPC handler waking up\n"));
3194
3195                 /* Initialization not yet finished. Don't do anything yet. */
3196                 if (!ha->flags.init_done || ha->dpc_active)
3197                         continue;
3198
3199                 DEBUG3(printk("scsi(%ld): DPC handler\n", ha->host_no));
3200
3201                 ha->dpc_active = 1;
3202
3203                 /* Process commands in retry queue */
3204                 if (test_and_clear_bit(PORT_RESTART_NEEDED, &ha->dpc_flags)) {
3205                         DEBUG(printk("scsi(%ld): DPC checking retry_q. "
3206                             "total=%d\n",
3207                             ha->host_no, ha->retry_q_cnt));
3208
3209                         spin_lock_irqsave(&ha->list_lock, flags);
3210                         dead_cnt = online_cnt = 0;
3211                         list_for_each_safe(list, templist, &ha->retry_queue) {
3212                                 sp = list_entry(list, srb_t, list);
3213                                 q = sp->lun_queue;
3214                                 DEBUG3(printk("scsi(%ld): pid=%ld sp=%p, "
3215                                     "spflags=0x%x, q_flag= 0x%lx\n",
3216                                     ha->host_no, sp->cmd->serial_number, sp,
3217                                     sp->flags, q->q_flag));
3218
3219                                 if (q == NULL)
3220                                         continue;
3221                                 fcport = q->fclun->fcport;
3222
3223                                 if (atomic_read(&fcport->state) ==
3224                                     FCS_DEVICE_DEAD ||
3225                                     atomic_read(&fcport->ha->loop_state) == LOOP_DEAD) {
3226
3227                                         __del_from_retry_queue(ha, sp);
3228                                         sp->cmd->result = DID_NO_CONNECT << 16;
3229                                         if (atomic_read(&fcport->ha->loop_state) ==
3230                                             LOOP_DOWN) 
3231                                                 sp->err_id = SRB_ERR_LOOP;
3232                                         else
3233                                                 sp->err_id = SRB_ERR_PORT;
3234                                         sp->cmd->host_scribble =
3235                                             (unsigned char *) NULL;
3236                                         __add_to_done_queue(ha, sp);
3237                                         dead_cnt++;
3238                                 } else if (atomic_read(&fcport->state) !=
3239                                     FCS_DEVICE_LOST) {
3240
3241                                         __del_from_retry_queue(ha, sp);
3242                                         sp->cmd->result = DID_BUS_BUSY << 16;
3243                                         sp->cmd->host_scribble =
3244                                             (unsigned char *) NULL;
3245                                         __add_to_done_queue(ha, sp);
3246                                         online_cnt++;
3247                                 }
3248                         } /* list_for_each_safe() */
3249                         spin_unlock_irqrestore(&ha->list_lock, flags);
3250
3251                         DEBUG(printk("scsi(%ld): done processing retry queue "
3252                             "- dead=%d, online=%d\n ",
3253                             ha->host_no, dead_cnt, online_cnt));
3254                 }
3255
3256                 /* Process commands in scsi retry queue */
3257                 if (test_and_clear_bit(SCSI_RESTART_NEEDED, &ha->dpc_flags)) {
3258                         /*
3259                          * Any requests we want to delay for some period is put
3260                          * in the scsi retry queue with a delay added. The
3261                          * timer will schedule a "scsi_restart_needed" every 
3262                          * second as long as there are requests in the scsi
3263                          * queue. 
3264                          */
3265                         DEBUG(printk("scsi(%ld): DPC checking scsi "
3266                             "retry_q.total=%d\n",
3267                             ha->host_no, ha->scsi_retry_q_cnt));
3268
3269                         online_cnt = 0;
3270                         spin_lock_irqsave(&ha->list_lock, flags);
3271                         list_for_each_safe(list, templist,
3272                             &ha->scsi_retry_queue) {
3273
3274                                 sp = list_entry(list, srb_t, list);
3275                                 q = sp->lun_queue;
3276                                 tq = sp->tgt_queue;
3277
3278                                 DEBUG3(printk("scsi(%ld): scsi_retry_q: "
3279                                     "pid=%ld sp=%p, spflags=0x%x, "
3280                                     "q_flag= 0x%lx,q_state=%d\n",
3281                                     ha->host_no, sp->cmd->serial_number,
3282                                     sp, sp->flags, q->q_flag, q->q_state));
3283
3284                                 /* Was this lun suspended */
3285                                 if (q->q_state != LUN_STATE_WAIT) {
3286                                         online_cnt++;
3287                                         __del_from_scsi_retry_queue(ha, sp);
3288
3289                                         if (test_bit(TQF_RETRY_CMDS,
3290                                             &tq->flags)) {
3291                                                 qla2x00_extend_timeout(sp->cmd,
3292                                                     (sp->cmd->timeout_per_command / HZ) - QLA_CMD_TIMER_DELTA);
3293                                                 __add_to_pending_queue(ha, sp);
3294                                                 retry_cmds++;
3295                                         } else
3296                                                 __add_to_retry_queue(ha, sp);
3297                                 }
3298
3299                                 /* Was this command suspended for N secs */
3300                                 if (sp->delay != 0) {
3301                                         sp->delay--;
3302                                         if (sp->delay == 0) {
3303                                                 online_cnt++;
3304                                                 __del_from_scsi_retry_queue(
3305                                                     ha, sp);
3306                                                 __add_to_retry_queue(ha,sp);
3307                                         }
3308                                 }
3309                         }
3310                         spin_unlock_irqrestore(&ha->list_lock, flags);
3311
3312                         /* Clear all Target Unsuspended bits */
3313                         for (t = 0; t < ha->max_targets; t++) {
3314                                 if ((tq = ha->otgt[t]) == NULL)
3315                                         continue;
3316
3317                                 if (test_bit(TQF_RETRY_CMDS, &tq->flags))
3318                                         clear_bit(TQF_RETRY_CMDS, &tq->flags);
3319                         }
3320                         if (retry_cmds)
3321                                 qla2x00_next(ha);
3322
3323                         DEBUG(if (online_cnt > 0))
3324                         DEBUG(printk("scsi(%ld): dpc() found scsi reqs to "
3325                             "restart= %d\n",
3326                             ha->host_no, online_cnt));
3327                 }
3328
3329                 if (ha->flags.mbox_busy) {
3330                         if (!list_empty(&ha->done_queue))
3331                                 qla2x00_done(ha);
3332
3333                         ha->dpc_active = 0;
3334                         continue;
3335                 }
3336
3337                 if (test_and_clear_bit(ISP_ABORT_NEEDED, &ha->dpc_flags)) {
3338
3339                         DEBUG(printk("scsi(%ld): dpc: sched "
3340                             "qla2x00_abort_isp ha = %p\n",
3341                             ha->host_no, ha));
3342                         if (!(test_and_set_bit(ABORT_ISP_ACTIVE,
3343                             &ha->dpc_flags))) {
3344
3345                                 if (qla2x00_abort_isp(ha)) {
3346                                         /* failed. retry later */
3347                                         set_bit(ISP_ABORT_NEEDED,
3348                                             &ha->dpc_flags);
3349                                 }
3350                                 clear_bit(ABORT_ISP_ACTIVE, &ha->dpc_flags);
3351                         }
3352                         DEBUG(printk("scsi(%ld): dpc: qla2x00_abort_isp end\n",
3353                             ha->host_no));
3354                 }
3355
3356                 if (test_and_clear_bit(RESET_MARKER_NEEDED, &ha->dpc_flags) &&
3357                     (!(test_and_set_bit(RESET_ACTIVE, &ha->dpc_flags)))) {
3358
3359                         DEBUG(printk("scsi(%ld): qla2x00_reset_marker()\n",
3360                             ha->host_no));
3361
3362                         qla2x00_rst_aen(ha);
3363                         clear_bit(RESET_ACTIVE, &ha->dpc_flags);
3364                 }
3365
3366                 /* Retry each device up to login retry count */
3367                 if ((test_and_clear_bit(RELOGIN_NEEDED, &ha->dpc_flags)) &&
3368                     !test_bit(LOOP_RESYNC_NEEDED, &ha->dpc_flags) &&
3369                     atomic_read(&ha->loop_state) != LOOP_DOWN) {
3370
3371                         DEBUG(printk("scsi(%ld): qla2x00_port_login()\n",
3372                             ha->host_no));
3373
3374                         next_loopid = 0;
3375                         list_for_each_entry(fcport, &ha->fcports, list) {
3376                                 if (fcport->port_type != FCT_TARGET)
3377                                         continue;
3378
3379                                 /*
3380                                  * If the port is not ONLINE then try to login
3381                                  * to it if we haven't run out of retries.
3382                                  */
3383                                 if (atomic_read(&fcport->state) != FCS_ONLINE &&
3384                                     fcport->login_retry) {
3385
3386                                         fcport->login_retry--;
3387                                         if (fcport->flags & FCF_FABRIC_DEVICE) {
3388                                                 if (fcport->flags &
3389                                                     FCF_TAPE_PRESENT)
3390                                                         qla2x00_fabric_logout(
3391                                                             ha,
3392                                                             fcport->loop_id);
3393                                                 status = qla2x00_fabric_login(
3394                                                     ha, fcport, &next_loopid);
3395                                         } else
3396                                                 status =
3397                                                     qla2x00_local_device_login(
3398                                                         ha, fcport->loop_id);
3399
3400                                         if (status == QLA_SUCCESS) {
3401                                                 fcport->old_loop_id = fcport->loop_id;
3402
3403                                                 DEBUG(printk("scsi(%ld): port login OK: logged in ID 0x%x\n",
3404                                                     ha->host_no, fcport->loop_id));
3405                                                 
3406                                                 fcport->port_login_retry_count =
3407                                                     ha->port_down_retry_count * PORT_RETRY_TIME;
3408                                                 atomic_set(&fcport->state, FCS_ONLINE);
3409                                                 atomic_set(&fcport->port_down_timer,
3410                                                     ha->port_down_retry_count * PORT_RETRY_TIME);
3411
3412                                                 fcport->login_retry = 0;
3413                                         } else if (status == 1) {
3414                                                 set_bit(RELOGIN_NEEDED, &ha->dpc_flags);
3415                                                 /* retry the login again */
3416                                                 DEBUG(printk("scsi(%ld): Retrying %d login again loop_id 0x%x\n",
3417                                                     ha->host_no,
3418                                                     fcport->login_retry, fcport->loop_id));
3419                                         } else {
3420                                                 fcport->login_retry = 0;
3421                                         }
3422                                 }
3423                                 if (test_bit(LOOP_RESYNC_NEEDED, &ha->dpc_flags))
3424                                         break;
3425                         }
3426                         DEBUG(printk("scsi(%ld): qla2x00_port_login - end\n",
3427                             ha->host_no));
3428                 }
3429
3430                 if ((test_bit(LOGIN_RETRY_NEEDED, &ha->dpc_flags)) &&
3431                     atomic_read(&ha->loop_state) != LOOP_DOWN) {
3432
3433                         clear_bit(LOGIN_RETRY_NEEDED, &ha->dpc_flags);
3434                         DEBUG(printk("scsi(%ld): qla2x00_login_retry()\n",
3435                             ha->host_no));
3436                                 
3437                         set_bit(LOOP_RESYNC_NEEDED, &ha->dpc_flags);
3438
3439                         DEBUG(printk("scsi(%ld): qla2x00_login_retry - end\n",
3440                             ha->host_no));
3441                 }
3442
3443                 if (test_and_clear_bit(LOOP_RESYNC_NEEDED, &ha->dpc_flags)) {
3444
3445                         DEBUG(printk("scsi(%ld): qla2x00_loop_resync()\n",
3446                             ha->host_no));
3447
3448                         if (!(test_and_set_bit(LOOP_RESYNC_ACTIVE,
3449                             &ha->dpc_flags))) {
3450
3451                                 qla2x00_loop_resync(ha);
3452
3453                                 clear_bit(LOOP_RESYNC_ACTIVE, &ha->dpc_flags);
3454                         }
3455
3456                         DEBUG(printk("scsi(%ld): qla2x00_loop_resync - end\n",
3457                             ha->host_no));
3458                 }
3459
3460
3461                 if (test_bit(RESTART_QUEUES_NEEDED, &ha->dpc_flags)) {
3462                         DEBUG(printk("scsi(%ld): qla2x00_restart_queues()\n",
3463                             ha->host_no));
3464
3465                         qla2x00_restart_queues(ha, 0);
3466
3467                         DEBUG(printk("scsi(%ld): qla2x00_restart_queues - end\n",
3468                             ha->host_no));
3469                 }
3470
3471                 if (test_bit(ABORT_QUEUES_NEEDED, &ha->dpc_flags)) {
3472
3473                         DEBUG(printk("scsi(%ld): qla2x00_abort_queues()\n",
3474                             ha->host_no));
3475                                 
3476                         qla2x00_abort_queues(ha, 0);
3477
3478                         DEBUG(printk("scsi(%ld): qla2x00_abort_queues - end\n",
3479                             ha->host_no));
3480                 }
3481
3482                 if (test_and_clear_bit(FCPORT_RESCAN_NEEDED, &ha->dpc_flags)) {
3483
3484                         DEBUG(printk("scsi(%ld): Rescan flagged fcports...\n",
3485                             ha->host_no));
3486
3487                         qla2x00_rescan_fcports(ha);
3488
3489                         DEBUG(printk("scsi(%ld): Rescan flagged fcports..."
3490                             "end.\n",
3491                             ha->host_no));
3492                 }
3493
3494
3495                 if (!ha->interrupts_on)
3496                         qla2x00_enable_intrs(ha);
3497
3498                 if (!list_empty(&ha->done_queue))
3499                         qla2x00_done(ha);
3500
3501                 ha->dpc_active = 0;
3502         } /* End of while(1) */
3503
3504         DEBUG(printk("scsi(%ld): DPC handler exiting\n", ha->host_no));
3505
3506         /*
3507          * Make sure that nobody tries to wake us up again.
3508          */
3509         ha->dpc_wait = NULL;
3510         ha->dpc_active = 0;
3511
3512         complete_and_exit(&ha->dpc_exited, 0);
3513 }
3514
3515 /*
3516  *  qla2x00_abort_queues
3517  *      Abort all commands on queues on device
3518  *
3519  * Input:
3520  *      ha = adapter block pointer.
3521  *
3522  * Context:
3523  *      Interrupt context.
3524  */
3525 void
3526 qla2x00_abort_queues(scsi_qla_host_t *ha, uint8_t doneqflg) 
3527 {
3528
3529         srb_t       *sp;
3530         struct list_head *list, *temp;
3531         unsigned long flags;
3532
3533         clear_bit(ABORT_QUEUES_NEEDED, &ha->dpc_flags);
3534
3535         /* Return all commands device queues. */
3536         spin_lock_irqsave(&ha->list_lock,flags);
3537         list_for_each_safe(list, temp, &ha->pending_queue) {
3538                 sp = list_entry(list, srb_t, list);
3539
3540                 if (sp->flags & SRB_ABORTED)
3541                         continue;
3542
3543                 /* Remove srb from LUN queue. */
3544                 __del_from_pending_queue(ha, sp);
3545
3546                 /* Set ending status. */
3547                 sp->cmd->result = DID_BUS_BUSY << 16;
3548
3549                 __add_to_done_queue(ha, sp);
3550         }
3551         spin_unlock_irqrestore(&ha->list_lock, flags);
3552 }
3553
3554 /*
3555 *  qla2x00_rst_aen
3556 *      Processes asynchronous reset.
3557 *
3558 * Input:
3559 *      ha  = adapter block pointer.
3560 */
3561 static void
3562 qla2x00_rst_aen(scsi_qla_host_t *ha) 
3563 {
3564         if (ha->flags.online && !ha->flags.reset_active &&
3565             !atomic_read(&ha->loop_down_timer) &&
3566             !(test_bit(ABORT_ISP_ACTIVE, &ha->dpc_flags))) {
3567                 do {
3568                         clear_bit(RESET_MARKER_NEEDED, &ha->dpc_flags);
3569
3570                         /*
3571                          * Issue marker command only when we are going to start
3572                          * the I/O.
3573                          */
3574                         ha->marker_needed = 1;
3575                 } while (!atomic_read(&ha->loop_down_timer) &&
3576                     (test_bit(RESET_MARKER_NEEDED, &ha->dpc_flags)));
3577         }
3578 }
3579
3580
3581 /*
3582  * This routine will allocate SP from the free queue
3583  * input:
3584  *        scsi_qla_host_t *
3585  * output:
3586  *        srb_t * or NULL
3587  */
3588 srb_t *
3589 qla2x00_get_new_sp(scsi_qla_host_t *ha)
3590 {
3591         srb_t *sp;
3592
3593         sp = mempool_alloc(ha->srb_mempool, GFP_KERNEL);
3594         if (sp)
3595                 atomic_set(&sp->ref_count, 1);
3596         return (sp);
3597 }
3598
3599 /**************************************************************************
3600 *   qla2x00_timer
3601 *
3602 * Description:
3603 *   One second timer
3604 *
3605 * Context: Interrupt
3606 ***************************************************************************/
3607 static void
3608 qla2x00_timer(scsi_qla_host_t *ha)
3609 {
3610         int             t,l;
3611         unsigned long   cpu_flags = 0;
3612         fc_port_t       *fcport;
3613         os_lun_t *lq;
3614         os_tgt_t *tq;
3615         int             start_dpc = 0;
3616         int             index;
3617         srb_t           *sp;
3618
3619         /*
3620          * We try and restart any request in the retry queue every second.
3621          */
3622         if (!list_empty(&ha->retry_queue)) {
3623                 set_bit(PORT_RESTART_NEEDED, &ha->dpc_flags);
3624                 start_dpc++;
3625         }
3626
3627         /*
3628          * We try and restart any request in the scsi_retry queue every second.
3629          */
3630         if (!list_empty(&ha->scsi_retry_queue)) {
3631                 set_bit(SCSI_RESTART_NEEDED, &ha->dpc_flags);
3632                 start_dpc++;
3633         }
3634
3635         /*
3636          * Ports - Port down timer.
3637          *
3638          * Whenever, a port is in the LOST state we start decrementing its port
3639          * down timer every second until it reaches zero. Once  it reaches zero
3640          * the port it marked DEAD. 
3641          */
3642         t = 0;
3643         list_for_each_entry(fcport, &ha->fcports, list) {
3644                 if (fcport->port_type != FCT_TARGET)
3645                         continue;
3646
3647                 if (atomic_read(&fcport->state) == FCS_DEVICE_LOST) {
3648
3649                         if (atomic_read(&fcport->port_down_timer) == 0)
3650                                 continue;
3651
3652                         if (atomic_dec_and_test(&fcport->port_down_timer) != 0) 
3653                                 atomic_set(&fcport->state, FCS_DEVICE_DEAD);
3654                         
3655                         DEBUG(printk("scsi(%ld): fcport-%d - port retry count: "
3656                             "%d remainning\n",
3657                             ha->host_no,
3658                             t, atomic_read(&fcport->port_down_timer)));
3659                 }
3660                 t++;
3661         } /* End of for fcport  */
3662
3663         /*
3664          * LUNS - lun suspend timer.
3665          *
3666          * Whenever, a lun is suspended the timer starts decrementing its
3667          * suspend timer every second until it reaches zero. Once  it reaches
3668          * zero the lun retry count is decremented. 
3669          */
3670
3671         /*
3672          * FIXME(dg) - Need to convert this linear search of luns into a search
3673          * of a list of suspended luns.
3674          */
3675         for (t = 0; t < ha->max_targets; t++) {
3676                 if ((tq = ha->otgt[t]) == NULL)
3677                         continue;
3678
3679                 for (l = 0; l < ha->max_luns; l++) {
3680                         if ((lq = (os_lun_t *) tq->olun[l]) == NULL)
3681                                 continue;
3682
3683                         spin_lock_irqsave(&lq->q_lock, cpu_flags);
3684                         if (lq->q_state == LUN_STATE_WAIT &&
3685                                 atomic_read(&lq->q_timer) != 0) {
3686
3687                                 if (atomic_dec_and_test(&lq->q_timer) != 0) {
3688                                         /*
3689                                          * A delay should immediately
3690                                          * transition to a READY state
3691                                          */
3692                                         if (test_and_clear_bit(LUN_EXEC_DELAYED,
3693                                             &lq->q_flag)) {
3694                                                 lq->q_state = LUN_STATE_READY;
3695                                         }
3696                                         else {
3697                                                 lq->q_count++;
3698                                                 if (lq->q_count == lq->q_max)
3699                                                         lq->q_state =
3700                                                             LUN_STATE_TIMEOUT;
3701                                                 else
3702                                                         lq->q_state =
3703                                                             LUN_STATE_RUN;
3704                                         }
3705                                 }
3706                                 DEBUG3(printk("scsi(%ld): lun%d - timer %d, "
3707                                     "count=%d, max=%d, state=%d\n",
3708                                     ha->host_no,
3709                                     l,
3710                                     atomic_read(&lq->q_timer),
3711                                     lq->q_count, lq->q_max, lq->q_state));
3712                         }
3713                         spin_unlock_irqrestore(&lq->q_lock, cpu_flags);
3714                 } /* End of for luns  */
3715         } /* End of for targets  */
3716
3717         /* Loop down handler. */
3718         if (atomic_read(&ha->loop_down_timer) > 0 &&
3719             !(test_bit(ABORT_ISP_ACTIVE, &ha->dpc_flags)) && ha->flags.online) {
3720
3721                 if (atomic_read(&ha->loop_down_timer) ==
3722                     ha->loop_down_abort_time) {
3723
3724                         DEBUG(printk("scsi(%ld): Loop Down - aborting the "
3725                             "queues before time expire\n",
3726                             ha->host_no));
3727
3728                         if (!IS_QLA2100(ha) && ha->link_down_timeout)
3729                                 atomic_set(&ha->loop_state, LOOP_DEAD); 
3730
3731                         /* Schedule an ISP abort to return any tape commands. */
3732                         spin_lock_irqsave(&ha->hardware_lock, cpu_flags);
3733                         for (index = 1; index < MAX_OUTSTANDING_COMMANDS;
3734                             index++) {
3735                                 sp = ha->outstanding_cmds[index];
3736                                 if (!sp)
3737                                         continue;
3738                                 if (!(sp->fclun->fcport->flags &
3739                                     FCF_TAPE_PRESENT))
3740                                         continue;
3741
3742                                 set_bit(ISP_ABORT_NEEDED, &ha->dpc_flags);
3743                                 break;
3744                         }
3745                         spin_unlock_irqrestore(&ha->hardware_lock, cpu_flags);
3746
3747                         set_bit(ABORT_QUEUES_NEEDED, &ha->dpc_flags);
3748                         start_dpc++;
3749                 }
3750
3751                 /* if the loop has been down for 4 minutes, reinit adapter */
3752                 if (atomic_dec_and_test(&ha->loop_down_timer) != 0) {
3753                         DEBUG(printk("scsi(%ld): Loop down exceed 4 mins - "
3754                             "restarting queues.\n",
3755                             ha->host_no));
3756
3757                         set_bit(RESTART_QUEUES_NEEDED, &ha->dpc_flags);
3758                         start_dpc++;
3759
3760                         if (!(ha->device_flags & DFLG_NO_CABLE)) {
3761                                 DEBUG(printk("scsi(%ld): Loop down - "
3762                                     "aborting ISP.\n",
3763                                     ha->host_no));
3764                                 qla_printk(KERN_WARNING, ha,
3765                                     "Loop down - aborting ISP.\n");
3766
3767                                 set_bit(ISP_ABORT_NEEDED, &ha->dpc_flags);
3768                         }
3769                 }
3770                 DEBUG3(printk("scsi(%ld): Loop Down - seconds remainning %d\n",
3771                     ha->host_no,
3772                     atomic_read(&ha->loop_down_timer)));
3773         }
3774
3775         /*
3776          * Done Q Handler -- dgFIXME This handler will kick off doneq if we
3777          * haven't process it in 2 seconds.
3778          */
3779         if (!list_empty(&ha->done_queue))
3780                 qla2x00_done(ha);
3781
3782
3783         /* Schedule the DPC routine if needed */
3784         if ((test_bit(ISP_ABORT_NEEDED, &ha->dpc_flags) ||
3785             test_bit(LOOP_RESYNC_NEEDED, &ha->dpc_flags) ||
3786             start_dpc ||
3787             test_bit(LOGIN_RETRY_NEEDED, &ha->dpc_flags) ||
3788             test_bit(RELOGIN_NEEDED, &ha->dpc_flags)) &&
3789             ha->dpc_wait && !ha->dpc_active) {
3790
3791                 up(ha->dpc_wait);
3792         }
3793
3794         qla2x00_restart_timer(ha, WATCH_INTERVAL);
3795 }
3796
3797 /*
3798  * qla2x00_extend_timeout
3799  *      This routine will extend the timeout to the specified value.
3800  *
3801  * Input:
3802  *      cmd = SCSI command structure
3803  *
3804  * Returns:
3805  *      None.
3806  */
3807 void 
3808 qla2x00_extend_timeout(struct scsi_cmnd *cmd, int timeout) 
3809 {
3810         srb_t *sp = (srb_t *) CMD_SP(cmd);
3811         u_long our_jiffies = (timeout * HZ) + jiffies;
3812
3813         sp->ext_history= 0; 
3814         sp->e_start = jiffies;
3815         if (cmd->eh_timeout.function) {
3816                 mod_timer(&cmd->eh_timeout,our_jiffies);
3817                 sp->ext_history |= 1;
3818         }
3819         if (sp->timer.function != NULL) {
3820                 /* 
3821                  * Our internal timer should timeout before the midlayer has a
3822                  * chance begin the abort process
3823                  */
3824                 mod_timer(&sp->timer,our_jiffies - (QLA_CMD_TIMER_DELTA * HZ));
3825
3826                 sp->ext_history |= 2;
3827         }
3828 }
3829
3830 /**************************************************************************
3831 *   qla2x00_cmd_timeout
3832 *
3833 * Description:
3834 *       Handles the command if it times out in any state.
3835 *
3836 * Input:
3837 *     sp - pointer to validate
3838 *
3839 * Returns:
3840 * None.
3841 * Note:Need to add the support for if( sp->state == SRB_FAILOVER_STATE).
3842 **************************************************************************/
3843 void
3844 qla2x00_cmd_timeout(srb_t *sp)
3845 {
3846         int t, l;
3847         int processed;
3848         scsi_qla_host_t *vis_ha, *dest_ha;
3849         struct scsi_cmnd *cmd;
3850         unsigned long flags, cpu_flags;
3851         fc_port_t *fcport;
3852
3853         cmd = sp->cmd;
3854         vis_ha = (scsi_qla_host_t *)cmd->device->host->hostdata;
3855
3856         DEBUG3(printk("cmd_timeout: Entering sp->state = %x\n", sp->state));
3857
3858         t = cmd->device->id;
3859         l = cmd->device->lun;
3860         fcport = sp->fclun->fcport;
3861         dest_ha = sp->ha;
3862
3863         /*
3864          * If IO is found either in retry Queue 
3865          *    OR in Lun Queue
3866          * Return this IO back to host
3867          */
3868         spin_lock_irqsave(&vis_ha->list_lock, flags);
3869         processed = 0;
3870         if (sp->state == SRB_PENDING_STATE) {
3871                 __del_from_pending_queue(vis_ha, sp);
3872                 DEBUG2(printk("scsi(%ld): Found in Pending queue pid %ld, "
3873                     "State = %x., fcport state=%d jiffies=%lx\n",
3874                     vis_ha->host_no, cmd->serial_number, sp->state,
3875                     atomic_read(&fcport->state), jiffies));
3876
3877                 /*
3878                  * If FC_DEVICE is marked as dead return the cmd with
3879                  * DID_NO_CONNECT status.  Otherwise set the host_byte to
3880                  * DID_BUS_BUSY to let the OS  retry this cmd.
3881                  */
3882                 if (atomic_read(&fcport->state) == FCS_DEVICE_DEAD ||
3883                     atomic_read(&fcport->ha->loop_state) == LOOP_DEAD) {
3884                         cmd->result = DID_NO_CONNECT << 16;
3885                         if (atomic_read(&fcport->ha->loop_state) == LOOP_DOWN) 
3886                                 sp->err_id = SRB_ERR_LOOP;
3887                         else
3888                                 sp->err_id = SRB_ERR_PORT;
3889                 } else {
3890                         cmd->result = DID_BUS_BUSY << 16;
3891                 }
3892                 __add_to_done_queue(vis_ha, sp);
3893                 processed++;
3894         } 
3895         spin_unlock_irqrestore(&vis_ha->list_lock, flags);
3896
3897         if (processed) {
3898                 qla2x00_done(vis_ha);
3899                 return;
3900         }
3901
3902         spin_lock_irqsave(&dest_ha->list_lock, flags);
3903         if ((sp->state == SRB_RETRY_STATE) ||
3904             (sp->state == SRB_SCSI_RETRY_STATE)) {
3905
3906                 DEBUG2(printk("scsi(%ld): Found in (Scsi) Retry queue or "
3907                     "failover Q pid %ld, State = %x., fcport state=%d "
3908                     "jiffies=%lx retried=%d\n",
3909                     dest_ha->host_no, cmd->serial_number, sp->state,
3910                     atomic_read(&fcport->state), jiffies, cmd->retries));
3911
3912                 if ((sp->state == SRB_RETRY_STATE)) {
3913                         __del_from_retry_queue(dest_ha, sp);
3914                 } else if ((sp->state == SRB_SCSI_RETRY_STATE)) {
3915                         __del_from_scsi_retry_queue(dest_ha, sp);
3916                 } 
3917
3918                 /*
3919                  * If FC_DEVICE is marked as dead return the cmd with
3920                  * DID_NO_CONNECT status.  Otherwise set the host_byte to
3921                  * DID_BUS_BUSY to let the OS  retry this cmd.
3922                  */
3923                 if ((atomic_read(&fcport->state) == FCS_DEVICE_DEAD) ||
3924                     atomic_read(&dest_ha->loop_state) == LOOP_DEAD) {
3925                         qla2x00_extend_timeout(cmd, EXTEND_CMD_TIMEOUT);
3926                         cmd->result = DID_NO_CONNECT << 16;
3927                         if (atomic_read(&dest_ha->loop_state) == LOOP_DOWN) 
3928                                 sp->err_id = SRB_ERR_LOOP;
3929                         else
3930                                 sp->err_id = SRB_ERR_PORT;
3931                 } else {
3932                         cmd->result = DID_BUS_BUSY << 16;
3933                 }
3934
3935                 __add_to_done_queue(dest_ha, sp);
3936                 processed++;
3937         } 
3938         spin_unlock_irqrestore(&dest_ha->list_lock, flags);
3939
3940         if (processed) {
3941                 qla2x00_done(dest_ha);
3942
3943                  return;
3944         }
3945
3946         spin_lock_irqsave(&dest_ha->list_lock, cpu_flags);
3947         if (sp->state == SRB_DONE_STATE) {
3948                 /* IO in done_q  -- leave it */
3949                 DEBUG(printk("scsi(%ld): Found in Done queue pid %ld sp=%p.\n",
3950                     dest_ha->host_no, cmd->serial_number, sp));
3951         } else if (sp->state == SRB_SUSPENDED_STATE) {
3952                 DEBUG(printk("scsi(%ld): Found SP %p in suspended state  "
3953                     "- pid %ld:\n",
3954                     dest_ha->host_no, sp, cmd->serial_number));
3955                 DEBUG(qla2x00_dump_buffer((uint8_t *)sp, sizeof(srb_t));)
3956         } else if (sp->state == SRB_ACTIVE_STATE) {
3957                 /*
3958                  * IO is with ISP find the command in our active list.
3959                  */
3960                 spin_unlock_irqrestore(&dest_ha->list_lock, cpu_flags);
3961                 spin_lock_irqsave(&dest_ha->hardware_lock, flags);
3962                 if (sp == dest_ha->outstanding_cmds[
3963                     (unsigned long)sp->cmd->host_scribble]) {
3964
3965                         DEBUG(printk("cmd_timeout: Found in ISP \n"));
3966
3967                         if (sp->flags & SRB_TAPE) {
3968                                 /*
3969                                  * We cannot allow the midlayer error handler
3970                                  * to wakeup and begin the abort process.
3971                                  * Extend the timer so that the firmware can
3972                                  * properly return the IOCB.
3973                                  */
3974                                 DEBUG(printk("cmd_timeout: Extending timeout "
3975                                     "of FCP2 tape command!\n"));
3976                                 qla2x00_extend_timeout(sp->cmd,
3977                                     EXTEND_CMD_TIMEOUT);
3978                         }
3979                         sp->state = SRB_ACTIVE_TIMEOUT_STATE;
3980                         spin_unlock_irqrestore(&dest_ha->hardware_lock, flags);
3981                 } else {
3982                         spin_unlock_irqrestore(&dest_ha->hardware_lock, flags);
3983                         printk(KERN_INFO 
3984                                 "qla_cmd_timeout: State indicates it is with "
3985                                 "ISP, But not in active array\n");
3986                 }
3987                 spin_lock_irqsave(&dest_ha->list_lock, cpu_flags);
3988         } else if (sp->state == SRB_ACTIVE_TIMEOUT_STATE) {
3989                 DEBUG(printk("qla2100%ld: Found in Active timeout state"
3990                                 "pid %ld, State = %x., \n",
3991                                 dest_ha->host_no,
3992                                 sp->cmd->serial_number, sp->state);)
3993         } else {
3994                 /* EMPTY */
3995                 DEBUG2(printk("cmd_timeout%ld: LOST command state = "
3996                                 "0x%x, sp=%p\n",
3997                                 vis_ha->host_no, sp->state,sp);)
3998
3999                 qla_printk(KERN_INFO, vis_ha,
4000                         "cmd_timeout: LOST command state = 0x%x\n", sp->state);
4001         }
4002         spin_unlock_irqrestore(&dest_ha->list_lock, cpu_flags);
4003
4004         DEBUG3(printk("cmd_timeout: Leaving\n");)
4005 }
4006
4007 /**************************************************************************
4008 * qla2x00_done
4009 *      Process completed commands.
4010 *
4011 * Input:
4012 *      old_ha           = adapter block pointer.
4013 *
4014 **************************************************************************/
4015 void
4016 qla2x00_done(scsi_qla_host_t *old_ha)
4017 {
4018         os_lun_t        *lq;
4019         struct scsi_cmnd *cmd;
4020         unsigned long   flags = 0;
4021         scsi_qla_host_t *ha;
4022         scsi_qla_host_t *vis_ha;
4023         int     send_marker_once = 0;
4024         srb_t           *sp, *sptemp;
4025         LIST_HEAD(local_sp_list);
4026
4027         /*
4028          * Get into local queue such that we do not wind up calling done queue
4029          * tasklet for the same IOs from DPC or any other place.
4030          */
4031         spin_lock_irqsave(&old_ha->list_lock, flags);
4032         list_splice_init(&old_ha->done_queue, &local_sp_list);
4033         spin_unlock_irqrestore(&old_ha->list_lock, flags);
4034
4035         /*
4036          * All done commands are in the local queue, now do the call back.
4037          */
4038         list_for_each_entry_safe(sp, sptemp, &local_sp_list, list) {
4039                 old_ha->done_q_cnt--;
4040                 sp->state = SRB_NO_QUEUE_STATE;
4041
4042                 /* remove command from local list */
4043                 list_del_init(&sp->list);
4044
4045                 cmd = sp->cmd;
4046                 if (cmd == NULL)
4047                         continue;
4048
4049                 vis_ha = (scsi_qla_host_t *)cmd->device->host->hostdata;
4050                 lq = sp->lun_queue;
4051                 ha = sp->ha;
4052
4053                 if (sp->flags & SRB_DMA_VALID) {
4054                         sp->flags &= ~SRB_DMA_VALID;
4055
4056                         /* Release memory used for this I/O */
4057                         if (cmd->use_sg) {
4058                                 pci_unmap_sg(ha->pdev, cmd->request_buffer,
4059                                     cmd->use_sg, cmd->sc_data_direction);
4060                         } else if (cmd->request_bufflen) {
4061                                 pci_unmap_page(ha->pdev, sp->dma_handle,
4062                                     cmd->request_bufflen,
4063                                     cmd->sc_data_direction);
4064                         }
4065                 }
4066
4067
4068                 switch (host_byte(cmd->result)) {
4069                         case DID_OK:
4070                         case DID_ERROR:
4071                                 break;
4072
4073                         case DID_RESET:
4074                                 /*
4075                                  * Set marker needed, so we don't have to
4076                                  * send multiple markers
4077                                  */
4078                                 if (!send_marker_once) {
4079                                         ha->marker_needed = 1;
4080                                         send_marker_once++;
4081                                 }
4082
4083                                 /*
4084                                  * WORKAROUND
4085                                  *
4086                                  * A backdoor device-reset requires different
4087                                  * error handling.  This code differentiates
4088                                  * between normal error handling and the
4089                                  * backdoor method.
4090                                  *
4091                                  */
4092                                 if (ha->host->eh_active != EH_ACTIVE)
4093                                         cmd->result = DID_BUS_BUSY << 16;
4094                                 break;
4095
4096
4097                         case DID_ABORT:
4098                                 sp->flags &= ~SRB_ABORT_PENDING;
4099                                 sp->flags |= SRB_ABORTED;
4100
4101                                 if (sp->flags & SRB_TIMEOUT)
4102                                         cmd->result = DID_TIME_OUT << 16;
4103
4104                                 break;
4105
4106                         default:
4107                                 DEBUG2(printk("scsi(%ld:%d:%d) %s: did_error "
4108                                     "= %d, comp-scsi= 0x%x-0x%x.\n",
4109                                     vis_ha->host_no,
4110                                     cmd->device->id, cmd->device->lun,
4111                                     __func__,
4112                                     host_byte(cmd->result),
4113                                     CMD_COMPL_STATUS(cmd),
4114                                     CMD_SCSI_STATUS(cmd)));
4115                                 break;
4116                 }
4117
4118                 /*
4119                  * Call the mid-level driver interrupt handler -- via sp_put()
4120                  */
4121                 sp_put(ha, sp);
4122         } /* end of while */
4123 }
4124
4125 /*
4126  * qla2x00_process_response_queue_in_zio_mode
4127  *      Process response queue completion as fast as possible
4128  *      to achieve Zero Interrupt Opertions-ZIO
4129  *
4130  * Input:
4131  *      ha = adapter block pointer.
4132  *
4133  * Context:
4134  *      Kernel context.
4135  */
4136 static inline void
4137 qla2x00_process_response_queue_in_zio_mode(scsi_qla_host_t *ha)
4138 {
4139         unsigned long flags;
4140
4141         /* Check for unprocessed commands in response queue. */
4142         if (!ha->flags.process_response_queue)
4143                 return;
4144         if (!ha->flags.online)
4145                 return;
4146         if (ha->response_ring_ptr->signature == RESPONSE_PROCESSED)
4147                 return;
4148         
4149         spin_lock_irqsave(&ha->hardware_lock,flags);
4150         qla2x00_process_response_queue(ha);
4151         spin_unlock_irqrestore(&ha->hardware_lock, flags);
4152 }
4153
4154 /*
4155  * qla2x00_next
4156  *      Retrieve and process next job in the LUN queue.
4157  *
4158  * Input:
4159  *      tq = SCSI target queue pointer.
4160  *      lq = SCSI LUN queue pointer.
4161  *      TGT_LOCK must be already obtained.
4162  *
4163  * Output:
4164  *      Releases TGT_LOCK upon exit.
4165  *
4166  * Context:
4167  *      Kernel/Interrupt context.
4168  * 
4169  * Note: This routine will always try to start I/O from visible HBA.
4170  */
4171 void
4172 qla2x00_next(scsi_qla_host_t *vis_ha) 
4173 {
4174         int             rval;
4175         unsigned long   flags;
4176         scsi_qla_host_t *dest_ha;
4177         fc_port_t       *fcport;
4178         srb_t           *sp, *sptemp;
4179         LIST_HEAD(local_sp_list);
4180
4181         dest_ha = NULL;
4182
4183         spin_lock_irqsave(&vis_ha->list_lock, flags);
4184         list_splice_init(&vis_ha->pending_queue, &local_sp_list);
4185         vis_ha->qthreads = 0;
4186         spin_unlock_irqrestore(&vis_ha->list_lock, flags);
4187
4188         list_for_each_entry_safe(sp, sptemp, &local_sp_list, list) {
4189                 list_del_init(&sp->list);
4190                 sp->state = SRB_NO_QUEUE_STATE;
4191
4192                 fcport = sp->fclun->fcport;
4193                 dest_ha = fcport->ha;
4194
4195                 /* If device is dead then send request back to OS */
4196                 if (atomic_read(&fcport->state) == FCS_DEVICE_DEAD) {
4197                         sp->cmd->result = DID_NO_CONNECT << 16;
4198                         if (atomic_read(&dest_ha->loop_state) == LOOP_DOWN) 
4199                                 sp->err_id = SRB_ERR_LOOP;
4200                         else
4201                                 sp->err_id = SRB_ERR_PORT;
4202
4203                         DEBUG3(printk("scsi(%ld): loop/port is down - pid=%ld, "
4204                             "sp=%p err_id=%d loopid=0x%x queued to dest HBA "
4205                             "scsi%ld.\n", dest_ha->host_no,
4206                             sp->cmd->serial_number, sp, sp->err_id,
4207                             fcport->loop_id, dest_ha->host_no));
4208                         /* 
4209                          * Initiate a failover - done routine will initiate.
4210                          */
4211                         add_to_done_queue(vis_ha, sp);
4212
4213                         continue;
4214                 }
4215
4216                 /*
4217                  * SCSI Kluge: Whenever, we need to wait for an event such as
4218                  * loop down (i.e. loop_down_timer ) or port down (i.e.  LUN
4219                  * request qeueue is suspended) then we will recycle new
4220                  * commands back to the SCSI layer.  We do this because this is
4221                  * normally a temporary condition and we don't want the
4222                  * mid-level scsi.c driver to get upset and start aborting
4223                  * commands.  The timeout value is extracted from the command
4224                  * minus 1-second and put on a retry queue (watchdog). Once the
4225                  * command timeout it is returned to the mid-level with a BUSY
4226                  * status, so the mid-level will retry it. This process
4227                  * continues until the LOOP DOWN time expires or the condition
4228                  * goes away.
4229                  */
4230                 if (!(sp->flags & (SRB_IOCTL | SRB_TAPE)) &&
4231                     (atomic_read(&fcport->state) != FCS_ONLINE ||
4232                         test_bit(ABORT_ISP_ACTIVE, &dest_ha->dpc_flags) ||
4233                         atomic_read(&dest_ha->loop_state) != LOOP_READY)) {
4234
4235                         DEBUG3(printk("scsi(%ld): port=(0x%x) retry_q(%d) "
4236                             "loop state = %d, loop counter = 0x%x dpc flags "
4237                             "= 0x%lx\n",
4238                             dest_ha->host_no,
4239                             fcport->loop_id,
4240                             atomic_read(&fcport->state),
4241                             atomic_read(&dest_ha->loop_state),
4242                             atomic_read(&dest_ha->loop_down_timer),
4243                             dest_ha->dpc_flags));
4244
4245                         qla2x00_extend_timeout(sp->cmd, EXTEND_CMD_TIMEOUT);
4246                         add_to_retry_queue(vis_ha, sp);
4247
4248                         continue;
4249                 } 
4250
4251                 /*
4252                  * If this request's lun is suspended then put the request on
4253                  * the  scsi_retry queue. 
4254                  */
4255                 if (!(sp->flags & (SRB_IOCTL | SRB_TAPE)) &&
4256                     sp->lun_queue->q_state == LUN_STATE_WAIT) {
4257                         DEBUG3(printk("scsi(%ld): lun wait state - pid=%ld, "
4258                             "opcode=%d, allowed=%d, retries=%d\n",
4259                             dest_ha->host_no,
4260                             sp->cmd->serial_number,
4261                             sp->cmd->cmnd[0],
4262                             sp->cmd->allowed,
4263                             sp->cmd->retries));
4264                                 
4265                         add_to_scsi_retry_queue(vis_ha, sp);
4266
4267                         continue;
4268                 }
4269
4270                 sp->lun_queue->io_cnt++;
4271
4272                 rval = qla2x00_start_scsi(sp);
4273                 if (rval != QLA_SUCCESS) {
4274                         /* Place request back on top of device queue */
4275                         /* add to the top of queue */
4276                         add_to_pending_queue_head(vis_ha, sp);
4277
4278                         sp->lun_queue->io_cnt--;
4279                 }
4280         }
4281
4282         if (!IS_QLA2100(vis_ha) && !IS_QLA2200(vis_ha)) {
4283                 /* Process response_queue if ZIO support is enabled*/ 
4284                 qla2x00_process_response_queue_in_zio_mode(vis_ha);
4285
4286         }
4287 }
4288
4289
4290 /**************************************************************************
4291 *   qla2x00_check_tgt_status
4292 *
4293 * Description:
4294 *     Checks to see if the target or loop is down.
4295 *
4296 * Input:
4297 *     cmd - pointer to Scsi cmd structure
4298 *
4299 * Returns:
4300 *   1 - if target is present
4301 *   0 - if target is not present
4302 *
4303 **************************************************************************/
4304 int
4305 qla2x00_check_tgt_status(scsi_qla_host_t *ha, struct scsi_cmnd *cmd)
4306 {
4307         os_lun_t        *lq;
4308         unsigned int    b, t, l;
4309         fc_port_t       *fcport;
4310
4311         /* Generate LU queue on bus, target, LUN */
4312         b = cmd->device->channel;
4313         t = cmd->device->id;
4314         l = cmd->device->lun;
4315
4316         if ((lq = GET_LU_Q(ha,t,l)) == NULL) {
4317                 return (QLA_FUNCTION_FAILED);
4318         }
4319
4320         fcport = lq->fclun->fcport;
4321
4322         if (TGT_Q(ha, t) == NULL ||
4323             l >= ha->max_luns ||
4324             atomic_read(&fcport->state) == FCS_DEVICE_DEAD ||
4325             atomic_read(&ha->loop_state) == LOOP_DEAD ||
4326             (!atomic_read(&ha->loop_down_timer) &&
4327                 atomic_read(&ha->loop_state) == LOOP_DOWN) ||
4328             test_bit(ABORT_ISP_ACTIVE, &ha->dpc_flags) ||
4329             test_bit(ISP_ABORT_NEEDED, &ha->dpc_flags) ||
4330             atomic_read(&ha->loop_state) != LOOP_READY) {
4331
4332                 DEBUG(printk(KERN_INFO
4333                     "scsi(%ld:%2d:%2d:%2d): %s connection is down\n",
4334                     ha->host_no,
4335                     b, t, l,
4336                     __func__));
4337
4338                 cmd->result = DID_NO_CONNECT << 16;
4339                 return (QLA_FUNCTION_FAILED);
4340         }
4341         return (QLA_SUCCESS);
4342 }
4343
4344 /**************************************************************************
4345 *   qla2x00_check_port_status
4346 *
4347 * Description:
4348 *     Checks to see if the port or loop is down.
4349 *
4350 * Input:
4351 *     fcport - pointer to fc_port_t structure.
4352 *
4353 * Returns:
4354 *   1 - if port is present
4355 *   0 - if port is not present
4356 *
4357 **************************************************************************/
4358 int
4359 qla2x00_check_port_status(scsi_qla_host_t *ha, fc_port_t *fcport)
4360 {
4361         if (fcport == NULL) {
4362                 return (QLA_FUNCTION_FAILED);
4363         }
4364
4365         if (atomic_read(&fcport->state) == FCS_DEVICE_DEAD ||
4366             atomic_read(&ha->loop_state) == LOOP_DEAD) {
4367                 return (QLA_FUNCTION_FAILED);
4368         }
4369
4370         if ((atomic_read(&fcport->state) != FCS_ONLINE) || 
4371             (!atomic_read(&ha->loop_down_timer) &&
4372                 atomic_read(&ha->loop_state) == LOOP_DOWN) ||
4373             (test_bit(ABORT_ISP_ACTIVE, &ha->dpc_flags)) ||
4374             test_bit(CFG_ACTIVE, &ha->cfg_flags) ||
4375             test_bit(ISP_ABORT_NEEDED, &ha->dpc_flags) ||
4376             atomic_read(&ha->loop_state) != LOOP_READY) {
4377
4378                 DEBUG(printk(KERN_INFO
4379                     "scsi(%ld): Connection is down. fcport=%p.\n",
4380                     ha->host_no, fcport));
4381
4382                 return (QLA_BUSY);
4383         }
4384
4385         return (QLA_SUCCESS);
4386 }
4387
4388 /* XXX(hch): crude hack to emulate a down_timeout() */
4389 int
4390 qla2x00_down_timeout(struct semaphore *sema, unsigned long timeout)
4391 {
4392         const unsigned int step = HZ/10;
4393
4394         do {
4395                 if (!down_trylock(sema))
4396                         return 0;
4397                 set_current_state(TASK_INTERRUPTIBLE);
4398                 if (schedule_timeout(step))
4399                         break;
4400         } while ((timeout -= step) > 0);
4401
4402         return -ETIMEDOUT;
4403 }
4404
4405 static void
4406 qla2xxx_get_port_id(struct scsi_device *sdev)
4407 {
4408         scsi_qla_host_t *ha = to_qla_host(sdev->host);
4409         struct fc_port *fc;
4410
4411         list_for_each_entry(fc, &ha->fcports, list) {
4412                 if (fc->os_target_id == sdev->id) {
4413                         fc_port_id(sdev) = fc->d_id.b.domain << 16 |
4414                                 fc->d_id.b.area << 8 | 
4415                                 fc->d_id.b.al_pa;
4416                         return;
4417                 }
4418         }
4419         fc_port_id(sdev) = -1;
4420 }
4421
4422 static void
4423 qla2xxx_get_port_name(struct scsi_device *sdev)
4424 {
4425         scsi_qla_host_t *ha = to_qla_host(sdev->host);
4426         struct fc_port *fc;
4427
4428         list_for_each_entry(fc, &ha->fcports, list) {
4429                 if (fc->os_target_id == sdev->id) {
4430                         fc_port_name(sdev) =
4431                                 __be64_to_cpu(*(uint64_t *)fc->port_name);
4432                         return;
4433                 }
4434         }
4435         fc_port_name(sdev) = -1;
4436 }
4437
4438 static void
4439 qla2xxx_get_node_name(struct scsi_device *sdev)
4440 {
4441         scsi_qla_host_t *ha = to_qla_host(sdev->host);
4442         struct fc_port *fc;
4443
4444         list_for_each_entry(fc, &ha->fcports, list) {
4445                 if (fc->os_target_id == sdev->id) {
4446                         fc_node_name(sdev) =
4447                                 __be64_to_cpu(*(uint64_t *)fc->node_name);
4448                         return;
4449                 }
4450         }
4451         fc_node_name(sdev) = -1;
4452 }
4453
4454 static struct fc_function_template qla2xxx_transport_functions = {
4455         .get_port_id = qla2xxx_get_port_id,
4456         .show_port_id = 1,
4457         .get_port_name = qla2xxx_get_port_name,
4458         .show_port_name = 1,
4459         .get_node_name = qla2xxx_get_node_name,
4460         .show_node_name = 1,
4461 };
4462
4463 /**
4464  * qla2x00_module_init - Module initialization.
4465  **/
4466 static int __init
4467 qla2x00_module_init(void)
4468 {
4469         /* Allocate cache for SRBs. */
4470         sprintf(srb_cachep_name, "qla2xxx_srbs");
4471         srb_cachep = kmem_cache_create(srb_cachep_name, sizeof(srb_t), 0,
4472             SLAB_HWCACHE_ALIGN, NULL, NULL);
4473         if (srb_cachep == NULL) {
4474                 printk(KERN_ERR
4475                     "qla2xxx: Unable to allocate SRB cache...Failing load!\n");
4476                 return -ENOMEM;
4477         }
4478
4479         /* Derive version string. */
4480         strcpy(qla2x00_version_str, QLA2XXX_VERSION);
4481 #if DEBUG_QLA2100
4482         strcat(qla2x00_version_str, "-debug");
4483 #endif
4484
4485         qla2xxx_transport_template = fc_attach_transport(&qla2xxx_transport_functions);
4486         if (!qla2xxx_transport_template)
4487                 return -ENODEV;
4488
4489         printk(KERN_INFO
4490             "QLogic Fibre Channel HBA Driver (%p)\n", qla2x00_set_info);
4491
4492         return 0;
4493 }
4494
4495 /**
4496  * qla2x00_module_exit - Module cleanup.
4497  **/
4498 static void __exit
4499 qla2x00_module_exit(void)
4500 {
4501         /* Free SRBs cache. */
4502         if (srb_cachep != NULL) {
4503                 if (kmem_cache_destroy(srb_cachep) != 0) {
4504                         printk(KERN_ERR
4505                             "qla2xxx: Unable to free SRB cache...Memory pools "
4506                             "still active?\n");
4507                 }
4508                 srb_cachep = NULL;
4509         }
4510
4511         fc_release_transport(qla2xxx_transport_template);
4512 }
4513
4514 module_init(qla2x00_module_init);
4515 module_exit(qla2x00_module_exit);
4516
4517 MODULE_AUTHOR("QLogic Corporation");
4518 MODULE_DESCRIPTION("QLogic Fibre Channel HBA Driver");
4519 MODULE_LICENSE("GPL");