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