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