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