[SCSI] libiscsi: fix shutdown
[safe/jmp/linux-2.6] / drivers / scsi / qla4xxx / ql4_os.c
1 /*
2  * QLogic iSCSI HBA Driver
3  * Copyright (c)  2003-2006 QLogic Corporation
4  *
5  * See LICENSE.qla4xxx for copyright and licensing details.
6  */
7 #include <linux/moduleparam.h>
8
9 #include <scsi/scsi_tcq.h>
10 #include <scsi/scsicam.h>
11
12 #include "ql4_def.h"
13 #include "ql4_version.h"
14 #include "ql4_glbl.h"
15 #include "ql4_dbg.h"
16 #include "ql4_inline.h"
17
18 /*
19  * Driver version
20  */
21 static char qla4xxx_version_str[40];
22
23 /*
24  * SRB allocation cache
25  */
26 static struct kmem_cache *srb_cachep;
27
28 /*
29  * Module parameter information and variables
30  */
31 int ql4xdiscoverywait = 60;
32 module_param(ql4xdiscoverywait, int, S_IRUGO | S_IRUSR);
33 MODULE_PARM_DESC(ql4xdiscoverywait, "Discovery wait time");
34 int ql4xdontresethba = 0;
35 module_param(ql4xdontresethba, int, S_IRUGO | S_IRUSR);
36 MODULE_PARM_DESC(ql4xdontresethba,
37                  "Dont reset the HBA when the driver gets 0x8002 AEN "
38                  " default it will reset hba :0"
39                  " set to 1 to avoid resetting HBA");
40
41 int ql4xextended_error_logging = 0; /* 0 = off, 1 = log errors */
42 module_param(ql4xextended_error_logging, int, S_IRUGO | S_IRUSR);
43 MODULE_PARM_DESC(ql4xextended_error_logging,
44                  "Option to enable extended error logging, "
45                  "Default is 0 - no logging, 1 - debug logging");
46
47 int ql4_mod_unload = 0;
48
49 /*
50  * SCSI host template entry points
51  */
52 static void qla4xxx_config_dma_addressing(struct scsi_qla_host *ha);
53
54 /*
55  * iSCSI template entry points
56  */
57 static int qla4xxx_tgt_dscvr(struct Scsi_Host *shost,
58                              enum iscsi_tgt_dscvr type, uint32_t enable,
59                              struct sockaddr *dst_addr);
60 static int qla4xxx_conn_get_param(struct iscsi_cls_conn *conn,
61                                   enum iscsi_param param, char *buf);
62 static int qla4xxx_sess_get_param(struct iscsi_cls_session *sess,
63                                   enum iscsi_param param, char *buf);
64 static int qla4xxx_host_get_param(struct Scsi_Host *shost,
65                                   enum iscsi_host_param param, char *buf);
66 static void qla4xxx_conn_stop(struct iscsi_cls_conn *conn, int flag);
67 static int qla4xxx_conn_start(struct iscsi_cls_conn *conn);
68 static void qla4xxx_recovery_timedout(struct iscsi_cls_session *session);
69
70 /*
71  * SCSI host template entry points
72  */
73 static int qla4xxx_queuecommand(struct scsi_cmnd *cmd,
74                                 void (*done) (struct scsi_cmnd *));
75 static int qla4xxx_eh_device_reset(struct scsi_cmnd *cmd);
76 static int qla4xxx_eh_host_reset(struct scsi_cmnd *cmd);
77 static int qla4xxx_slave_alloc(struct scsi_device *device);
78 static int qla4xxx_slave_configure(struct scsi_device *device);
79 static void qla4xxx_slave_destroy(struct scsi_device *sdev);
80
81 static struct scsi_host_template qla4xxx_driver_template = {
82         .module                 = THIS_MODULE,
83         .name                   = DRIVER_NAME,
84         .proc_name              = DRIVER_NAME,
85         .queuecommand           = qla4xxx_queuecommand,
86
87         .eh_device_reset_handler = qla4xxx_eh_device_reset,
88         .eh_host_reset_handler  = qla4xxx_eh_host_reset,
89
90         .slave_configure        = qla4xxx_slave_configure,
91         .slave_alloc            = qla4xxx_slave_alloc,
92         .slave_destroy          = qla4xxx_slave_destroy,
93
94         .this_id                = -1,
95         .cmd_per_lun            = 3,
96         .use_clustering         = ENABLE_CLUSTERING,
97         .use_sg_chaining        = ENABLE_SG_CHAINING,
98         .sg_tablesize           = SG_ALL,
99
100         .max_sectors            = 0xFFFF,
101 };
102
103 static struct iscsi_transport qla4xxx_iscsi_transport = {
104         .owner                  = THIS_MODULE,
105         .name                   = DRIVER_NAME,
106         .caps                   = CAP_FW_DB | CAP_SENDTARGETS_OFFLOAD |
107                                   CAP_DATA_PATH_OFFLOAD,
108         .param_mask             = ISCSI_CONN_PORT | ISCSI_CONN_ADDRESS |
109                                   ISCSI_TARGET_NAME | ISCSI_TPGT,
110         .host_param_mask        = ISCSI_HOST_HWADDRESS |
111                                   ISCSI_HOST_IPADDRESS |
112                                   ISCSI_HOST_INITIATOR_NAME,
113         .sessiondata_size       = sizeof(struct ddb_entry),
114         .host_template          = &qla4xxx_driver_template,
115
116         .tgt_dscvr              = qla4xxx_tgt_dscvr,
117         .get_conn_param         = qla4xxx_conn_get_param,
118         .get_session_param      = qla4xxx_sess_get_param,
119         .get_host_param         = qla4xxx_host_get_param,
120         .start_conn             = qla4xxx_conn_start,
121         .stop_conn              = qla4xxx_conn_stop,
122         .session_recovery_timedout = qla4xxx_recovery_timedout,
123 };
124
125 static struct scsi_transport_template *qla4xxx_scsi_transport;
126
127 static void qla4xxx_recovery_timedout(struct iscsi_cls_session *session)
128 {
129         struct ddb_entry *ddb_entry = session->dd_data;
130         struct scsi_qla_host *ha = ddb_entry->ha;
131
132         DEBUG2(printk("scsi%ld: %s: index [%d] port down retry count of (%d) "
133                       "secs exhausted, marking device DEAD.\n", ha->host_no,
134                       __func__, ddb_entry->fw_ddb_index,
135                       ha->port_down_retry_count));
136
137         atomic_set(&ddb_entry->state, DDB_STATE_DEAD);
138
139         DEBUG2(printk("scsi%ld: %s: scheduling dpc routine - dpc flags = "
140                       "0x%lx\n", ha->host_no, __func__, ha->dpc_flags));
141         queue_work(ha->dpc_thread, &ha->dpc_work);
142 }
143
144 static int qla4xxx_conn_start(struct iscsi_cls_conn *conn)
145 {
146         struct iscsi_cls_session *session;
147         struct ddb_entry *ddb_entry;
148
149         session = iscsi_dev_to_session(conn->dev.parent);
150         ddb_entry = session->dd_data;
151
152         DEBUG2(printk("scsi%ld: %s: index [%d] starting conn\n",
153                       ddb_entry->ha->host_no, __func__,
154                       ddb_entry->fw_ddb_index));
155         iscsi_unblock_session(session);
156         return 0;
157 }
158
159 static void qla4xxx_conn_stop(struct iscsi_cls_conn *conn, int flag)
160 {
161         struct iscsi_cls_session *session;
162         struct ddb_entry *ddb_entry;
163
164         session = iscsi_dev_to_session(conn->dev.parent);
165         ddb_entry = session->dd_data;
166
167         DEBUG2(printk("scsi%ld: %s: index [%d] stopping conn\n",
168                       ddb_entry->ha->host_no, __func__,
169                       ddb_entry->fw_ddb_index));
170         if (flag == STOP_CONN_RECOVER)
171                 iscsi_block_session(session);
172         else
173                 printk(KERN_ERR "iscsi: invalid stop flag %d\n", flag);
174 }
175
176 static ssize_t format_addr(char *buf, const unsigned char *addr, int len)
177 {
178         int i;
179         char *cp = buf;
180
181         for (i = 0; i < len; i++)
182                 cp += sprintf(cp, "%02x%c", addr[i],
183                               i == (len - 1) ? '\n' : ':');
184         return cp - buf;
185 }
186
187
188 static int qla4xxx_host_get_param(struct Scsi_Host *shost,
189                                   enum iscsi_host_param param, char *buf)
190 {
191         struct scsi_qla_host *ha = to_qla_host(shost);
192         int len;
193
194         switch (param) {
195         case ISCSI_HOST_PARAM_HWADDRESS:
196                 len = format_addr(buf, ha->my_mac, MAC_ADDR_LEN);
197                 break;
198         case ISCSI_HOST_PARAM_IPADDRESS:
199                 len = sprintf(buf, "%d.%d.%d.%d\n", ha->ip_address[0],
200                               ha->ip_address[1], ha->ip_address[2],
201                               ha->ip_address[3]);
202                 break;
203         case ISCSI_HOST_PARAM_INITIATOR_NAME:
204                 len = sprintf(buf, "%s\n", ha->name_string);
205                 break;
206         default:
207                 return -ENOSYS;
208         }
209
210         return len;
211 }
212
213 static int qla4xxx_sess_get_param(struct iscsi_cls_session *sess,
214                                   enum iscsi_param param, char *buf)
215 {
216         struct ddb_entry *ddb_entry = sess->dd_data;
217         int len;
218
219         switch (param) {
220         case ISCSI_PARAM_TARGET_NAME:
221                 len = snprintf(buf, PAGE_SIZE - 1, "%s\n",
222                                ddb_entry->iscsi_name);
223                 break;
224         case ISCSI_PARAM_TPGT:
225                 len = sprintf(buf, "%u\n", ddb_entry->tpgt);
226                 break;
227         default:
228                 return -ENOSYS;
229         }
230
231         return len;
232 }
233
234 static int qla4xxx_conn_get_param(struct iscsi_cls_conn *conn,
235                                   enum iscsi_param param, char *buf)
236 {
237         struct iscsi_cls_session *session;
238         struct ddb_entry *ddb_entry;
239         int len;
240
241         session = iscsi_dev_to_session(conn->dev.parent);
242         ddb_entry = session->dd_data;
243
244         switch (param) {
245         case ISCSI_PARAM_CONN_PORT:
246                 len = sprintf(buf, "%hu\n", ddb_entry->port);
247                 break;
248         case ISCSI_PARAM_CONN_ADDRESS:
249                 /* TODO: what are the ipv6 bits */
250                 len = sprintf(buf, "%u.%u.%u.%u\n",
251                               NIPQUAD(ddb_entry->ip_addr));
252                 break;
253         default:
254                 return -ENOSYS;
255         }
256
257         return len;
258 }
259
260 static int qla4xxx_tgt_dscvr(struct Scsi_Host *shost,
261                              enum iscsi_tgt_dscvr type, uint32_t enable,
262                              struct sockaddr *dst_addr)
263 {
264         struct scsi_qla_host *ha;
265         struct sockaddr_in *addr;
266         struct sockaddr_in6 *addr6;
267         int ret = 0;
268
269         ha = (struct scsi_qla_host *) shost->hostdata;
270
271         switch (type) {
272         case ISCSI_TGT_DSCVR_SEND_TARGETS:
273                 if (dst_addr->sa_family == AF_INET) {
274                         addr = (struct sockaddr_in *)dst_addr;
275                         if (qla4xxx_send_tgts(ha, (char *)&addr->sin_addr,
276                                               addr->sin_port) != QLA_SUCCESS)
277                                 ret = -EIO;
278                 } else if (dst_addr->sa_family == AF_INET6) {
279                         /*
280                          * TODO: fix qla4xxx_send_tgts
281                          */
282                         addr6 = (struct sockaddr_in6 *)dst_addr;
283                         if (qla4xxx_send_tgts(ha, (char *)&addr6->sin6_addr,
284                                               addr6->sin6_port) != QLA_SUCCESS)
285                                 ret = -EIO;
286                 } else
287                         ret = -ENOSYS;
288                 break;
289         default:
290                 ret = -ENOSYS;
291         }
292         return ret;
293 }
294
295 void qla4xxx_destroy_sess(struct ddb_entry *ddb_entry)
296 {
297         if (!ddb_entry->sess)
298                 return;
299
300         if (ddb_entry->conn) {
301                 atomic_set(&ddb_entry->state, DDB_STATE_DEAD);
302                 iscsi_remove_session(ddb_entry->sess);
303         }
304         iscsi_free_session(ddb_entry->sess);
305 }
306
307 int qla4xxx_add_sess(struct ddb_entry *ddb_entry)
308 {
309         int err;
310
311         ddb_entry->sess->recovery_tmo = ddb_entry->ha->port_down_retry_count;
312         err = iscsi_add_session(ddb_entry->sess, ddb_entry->fw_ddb_index);
313         if (err) {
314                 DEBUG2(printk(KERN_ERR "Could not add session.\n"));
315                 return err;
316         }
317
318         ddb_entry->conn = iscsi_create_conn(ddb_entry->sess, 0);
319         if (!ddb_entry->conn) {
320                 iscsi_remove_session(ddb_entry->sess);
321                 DEBUG2(printk(KERN_ERR "Could not add connection.\n"));
322                 return -ENOMEM;
323         }
324         return 0;
325 }
326
327 struct ddb_entry *qla4xxx_alloc_sess(struct scsi_qla_host *ha)
328 {
329         struct ddb_entry *ddb_entry;
330         struct iscsi_cls_session *sess;
331
332         sess = iscsi_alloc_session(ha->host, &qla4xxx_iscsi_transport);
333         if (!sess)
334                 return NULL;
335
336         ddb_entry = sess->dd_data;
337         memset(ddb_entry, 0, sizeof(*ddb_entry));
338         ddb_entry->ha = ha;
339         ddb_entry->sess = sess;
340         return ddb_entry;
341 }
342
343 /*
344  * Timer routines
345  */
346
347 static void qla4xxx_start_timer(struct scsi_qla_host *ha, void *func,
348                                 unsigned long interval)
349 {
350         DEBUG(printk("scsi: %s: Starting timer thread for adapter %d\n",
351                      __func__, ha->host->host_no));
352         init_timer(&ha->timer);
353         ha->timer.expires = jiffies + interval * HZ;
354         ha->timer.data = (unsigned long)ha;
355         ha->timer.function = (void (*)(unsigned long))func;
356         add_timer(&ha->timer);
357         ha->timer_active = 1;
358 }
359
360 static void qla4xxx_stop_timer(struct scsi_qla_host *ha)
361 {
362         del_timer_sync(&ha->timer);
363         ha->timer_active = 0;
364 }
365
366 /***
367  * qla4xxx_mark_device_missing - mark a device as missing.
368  * @ha: Pointer to host adapter structure.
369  * @ddb_entry: Pointer to device database entry
370  *
371  * This routine marks a device missing and resets the relogin retry count.
372  **/
373 void qla4xxx_mark_device_missing(struct scsi_qla_host *ha,
374                                  struct ddb_entry *ddb_entry)
375 {
376         atomic_set(&ddb_entry->state, DDB_STATE_MISSING);
377         DEBUG3(printk("scsi%d:%d:%d: index [%d] marked MISSING\n",
378                       ha->host_no, ddb_entry->bus, ddb_entry->target,
379                       ddb_entry->fw_ddb_index));
380         iscsi_conn_error(ddb_entry->conn, ISCSI_ERR_CONN_FAILED);
381 }
382
383 static struct srb* qla4xxx_get_new_srb(struct scsi_qla_host *ha,
384                                        struct ddb_entry *ddb_entry,
385                                        struct scsi_cmnd *cmd,
386                                        void (*done)(struct scsi_cmnd *))
387 {
388         struct srb *srb;
389
390         srb = mempool_alloc(ha->srb_mempool, GFP_ATOMIC);
391         if (!srb)
392                 return srb;
393
394         atomic_set(&srb->ref_count, 1);
395         srb->ha = ha;
396         srb->ddb = ddb_entry;
397         srb->cmd = cmd;
398         srb->flags = 0;
399         cmd->SCp.ptr = (void *)srb;
400         cmd->scsi_done = done;
401
402         return srb;
403 }
404
405 static void qla4xxx_srb_free_dma(struct scsi_qla_host *ha, struct srb *srb)
406 {
407         struct scsi_cmnd *cmd = srb->cmd;
408
409         if (srb->flags & SRB_DMA_VALID) {
410                 scsi_dma_unmap(cmd);
411                 srb->flags &= ~SRB_DMA_VALID;
412         }
413         cmd->SCp.ptr = NULL;
414 }
415
416 void qla4xxx_srb_compl(struct scsi_qla_host *ha, struct srb *srb)
417 {
418         struct scsi_cmnd *cmd = srb->cmd;
419
420         qla4xxx_srb_free_dma(ha, srb);
421
422         mempool_free(srb, ha->srb_mempool);
423
424         cmd->scsi_done(cmd);
425 }
426
427 /**
428  * qla4xxx_queuecommand - scsi layer issues scsi command to driver.
429  * @cmd: Pointer to Linux's SCSI command structure
430  * @done_fn: Function that the driver calls to notify the SCSI mid-layer
431  *      that the command has been processed.
432  *
433  * Remarks:
434  * This routine is invoked by Linux to send a SCSI command to the driver.
435  * The mid-level driver tries to ensure that queuecommand never gets
436  * invoked concurrently with itself or the interrupt handler (although
437  * the interrupt handler may call this routine as part of request-
438  * completion handling).   Unfortunely, it sometimes calls the scheduler
439  * in interrupt context which is a big NO! NO!.
440  **/
441 static int qla4xxx_queuecommand(struct scsi_cmnd *cmd,
442                                 void (*done)(struct scsi_cmnd *))
443 {
444         struct scsi_qla_host *ha = to_qla_host(cmd->device->host);
445         struct ddb_entry *ddb_entry = cmd->device->hostdata;
446         struct srb *srb;
447         int rval;
448
449         if (atomic_read(&ddb_entry->state) != DDB_STATE_ONLINE) {
450                 if (atomic_read(&ddb_entry->state) == DDB_STATE_DEAD) {
451                         cmd->result = DID_NO_CONNECT << 16;
452                         goto qc_fail_command;
453                 }
454                 goto qc_host_busy;
455         }
456
457         if (test_bit(DPC_RESET_HA_INTR, &ha->dpc_flags))
458                 goto qc_host_busy;
459
460         spin_unlock_irq(ha->host->host_lock);
461
462         srb = qla4xxx_get_new_srb(ha, ddb_entry, cmd, done);
463         if (!srb)
464                 goto qc_host_busy_lock;
465
466         rval = qla4xxx_send_command_to_isp(ha, srb);
467         if (rval != QLA_SUCCESS)
468                 goto qc_host_busy_free_sp;
469
470         spin_lock_irq(ha->host->host_lock);
471         return 0;
472
473 qc_host_busy_free_sp:
474         qla4xxx_srb_free_dma(ha, srb);
475         mempool_free(srb, ha->srb_mempool);
476
477 qc_host_busy_lock:
478         spin_lock_irq(ha->host->host_lock);
479
480 qc_host_busy:
481         return SCSI_MLQUEUE_HOST_BUSY;
482
483 qc_fail_command:
484         done(cmd);
485
486         return 0;
487 }
488
489 /**
490  * qla4xxx_mem_free - frees memory allocated to adapter
491  * @ha: Pointer to host adapter structure.
492  *
493  * Frees memory previously allocated by qla4xxx_mem_alloc
494  **/
495 static void qla4xxx_mem_free(struct scsi_qla_host *ha)
496 {
497         if (ha->queues)
498                 dma_free_coherent(&ha->pdev->dev, ha->queues_len, ha->queues,
499                                   ha->queues_dma);
500
501         ha->queues_len = 0;
502         ha->queues = NULL;
503         ha->queues_dma = 0;
504         ha->request_ring = NULL;
505         ha->request_dma = 0;
506         ha->response_ring = NULL;
507         ha->response_dma = 0;
508         ha->shadow_regs = NULL;
509         ha->shadow_regs_dma = 0;
510
511         /* Free srb pool. */
512         if (ha->srb_mempool)
513                 mempool_destroy(ha->srb_mempool);
514
515         ha->srb_mempool = NULL;
516
517         /* release io space registers  */
518         if (ha->reg)
519                 iounmap(ha->reg);
520         pci_release_regions(ha->pdev);
521 }
522
523 /**
524  * qla4xxx_mem_alloc - allocates memory for use by adapter.
525  * @ha: Pointer to host adapter structure
526  *
527  * Allocates DMA memory for request and response queues. Also allocates memory
528  * for srbs.
529  **/
530 static int qla4xxx_mem_alloc(struct scsi_qla_host *ha)
531 {
532         unsigned long align;
533
534         /* Allocate contiguous block of DMA memory for queues. */
535         ha->queues_len = ((REQUEST_QUEUE_DEPTH * QUEUE_SIZE) +
536                           (RESPONSE_QUEUE_DEPTH * QUEUE_SIZE) +
537                           sizeof(struct shadow_regs) +
538                           MEM_ALIGN_VALUE +
539                           (PAGE_SIZE - 1)) & ~(PAGE_SIZE - 1);
540         ha->queues = dma_alloc_coherent(&ha->pdev->dev, ha->queues_len,
541                                         &ha->queues_dma, GFP_KERNEL);
542         if (ha->queues == NULL) {
543                 dev_warn(&ha->pdev->dev,
544                         "Memory Allocation failed - queues.\n");
545
546                 goto mem_alloc_error_exit;
547         }
548         memset(ha->queues, 0, ha->queues_len);
549
550         /*
551          * As per RISC alignment requirements -- the bus-address must be a
552          * multiple of the request-ring size (in bytes).
553          */
554         align = 0;
555         if ((unsigned long)ha->queues_dma & (MEM_ALIGN_VALUE - 1))
556                 align = MEM_ALIGN_VALUE - ((unsigned long)ha->queues_dma &
557                                            (MEM_ALIGN_VALUE - 1));
558
559         /* Update request and response queue pointers. */
560         ha->request_dma = ha->queues_dma + align;
561         ha->request_ring = (struct queue_entry *) (ha->queues + align);
562         ha->response_dma = ha->queues_dma + align +
563                 (REQUEST_QUEUE_DEPTH * QUEUE_SIZE);
564         ha->response_ring = (struct queue_entry *) (ha->queues + align +
565                                                     (REQUEST_QUEUE_DEPTH *
566                                                      QUEUE_SIZE));
567         ha->shadow_regs_dma = ha->queues_dma + align +
568                 (REQUEST_QUEUE_DEPTH * QUEUE_SIZE) +
569                 (RESPONSE_QUEUE_DEPTH * QUEUE_SIZE);
570         ha->shadow_regs = (struct shadow_regs *) (ha->queues + align +
571                                                   (REQUEST_QUEUE_DEPTH *
572                                                    QUEUE_SIZE) +
573                                                   (RESPONSE_QUEUE_DEPTH *
574                                                    QUEUE_SIZE));
575
576         /* Allocate memory for srb pool. */
577         ha->srb_mempool = mempool_create(SRB_MIN_REQ, mempool_alloc_slab,
578                                          mempool_free_slab, srb_cachep);
579         if (ha->srb_mempool == NULL) {
580                 dev_warn(&ha->pdev->dev,
581                         "Memory Allocation failed - SRB Pool.\n");
582
583                 goto mem_alloc_error_exit;
584         }
585
586         return QLA_SUCCESS;
587
588 mem_alloc_error_exit:
589         qla4xxx_mem_free(ha);
590         return QLA_ERROR;
591 }
592
593 /**
594  * qla4xxx_timer - checks every second for work to do.
595  * @ha: Pointer to host adapter structure.
596  **/
597 static void qla4xxx_timer(struct scsi_qla_host *ha)
598 {
599         struct ddb_entry *ddb_entry, *dtemp;
600         int start_dpc = 0;
601
602         /* Search for relogin's to time-out and port down retry. */
603         list_for_each_entry_safe(ddb_entry, dtemp, &ha->ddb_list, list) {
604                 /* Count down time between sending relogins */
605                 if (adapter_up(ha) &&
606                     !test_bit(DF_RELOGIN, &ddb_entry->flags) &&
607                     atomic_read(&ddb_entry->state) != DDB_STATE_ONLINE) {
608                         if (atomic_read(&ddb_entry->retry_relogin_timer) !=
609                             INVALID_ENTRY) {
610                                 if (atomic_read(&ddb_entry->retry_relogin_timer)
611                                                 == 0) {
612                                         atomic_set(&ddb_entry->
613                                                 retry_relogin_timer,
614                                                 INVALID_ENTRY);
615                                         set_bit(DPC_RELOGIN_DEVICE,
616                                                 &ha->dpc_flags);
617                                         set_bit(DF_RELOGIN, &ddb_entry->flags);
618                                         DEBUG2(printk("scsi%ld: %s: index [%d]"
619                                                       " login device\n",
620                                                       ha->host_no, __func__,
621                                                       ddb_entry->fw_ddb_index));
622                                 } else
623                                         atomic_dec(&ddb_entry->
624                                                         retry_relogin_timer);
625                         }
626                 }
627
628                 /* Wait for relogin to timeout */
629                 if (atomic_read(&ddb_entry->relogin_timer) &&
630                     (atomic_dec_and_test(&ddb_entry->relogin_timer) != 0)) {
631                         /*
632                          * If the relogin times out and the device is
633                          * still NOT ONLINE then try and relogin again.
634                          */
635                         if (atomic_read(&ddb_entry->state) !=
636                             DDB_STATE_ONLINE &&
637                             ddb_entry->fw_ddb_device_state ==
638                             DDB_DS_SESSION_FAILED) {
639                                 /* Reset retry relogin timer */
640                                 atomic_inc(&ddb_entry->relogin_retry_count);
641                                 DEBUG2(printk("scsi%ld: index[%d] relogin"
642                                               " timed out-retrying"
643                                               " relogin (%d)\n",
644                                               ha->host_no,
645                                               ddb_entry->fw_ddb_index,
646                                               atomic_read(&ddb_entry->
647                                                           relogin_retry_count))
648                                         );
649                                 start_dpc++;
650                                 DEBUG(printk("scsi%ld:%d:%d: index [%d] "
651                                              "initate relogin after"
652                                              " %d seconds\n",
653                                              ha->host_no, ddb_entry->bus,
654                                              ddb_entry->target,
655                                              ddb_entry->fw_ddb_index,
656                                              ddb_entry->default_time2wait + 4)
657                                         );
658
659                                 atomic_set(&ddb_entry->retry_relogin_timer,
660                                            ddb_entry->default_time2wait + 4);
661                         }
662                 }
663         }
664
665         /* Check for heartbeat interval. */
666         if (ha->firmware_options & FWOPT_HEARTBEAT_ENABLE &&
667             ha->heartbeat_interval != 0) {
668                 ha->seconds_since_last_heartbeat++;
669                 if (ha->seconds_since_last_heartbeat >
670                     ha->heartbeat_interval + 2)
671                         set_bit(DPC_RESET_HA, &ha->dpc_flags);
672         }
673
674
675         /* Wakeup the dpc routine for this adapter, if needed. */
676         if ((start_dpc ||
677              test_bit(DPC_RESET_HA, &ha->dpc_flags) ||
678              test_bit(DPC_RETRY_RESET_HA, &ha->dpc_flags) ||
679              test_bit(DPC_RELOGIN_DEVICE, &ha->dpc_flags) ||
680              test_bit(DPC_RESET_HA_DESTROY_DDB_LIST, &ha->dpc_flags) ||
681              test_bit(DPC_RESET_HA_INTR, &ha->dpc_flags) ||
682              test_bit(DPC_GET_DHCP_IP_ADDR, &ha->dpc_flags) ||
683              test_bit(DPC_AEN, &ha->dpc_flags)) &&
684              ha->dpc_thread) {
685                 DEBUG2(printk("scsi%ld: %s: scheduling dpc routine"
686                               " - dpc flags = 0x%lx\n",
687                               ha->host_no, __func__, ha->dpc_flags));
688                 queue_work(ha->dpc_thread, &ha->dpc_work);
689         }
690
691         /* Reschedule timer thread to call us back in one second */
692         mod_timer(&ha->timer, jiffies + HZ);
693
694         DEBUG2(ha->seconds_since_last_intr++);
695 }
696
697 /**
698  * qla4xxx_cmd_wait - waits for all outstanding commands to complete
699  * @ha: Pointer to host adapter structure.
700  *
701  * This routine stalls the driver until all outstanding commands are returned.
702  * Caller must release the Hardware Lock prior to calling this routine.
703  **/
704 static int qla4xxx_cmd_wait(struct scsi_qla_host *ha)
705 {
706         uint32_t index = 0;
707         int stat = QLA_SUCCESS;
708         unsigned long flags;
709         struct scsi_cmnd *cmd;
710         int wait_cnt = WAIT_CMD_TOV;    /*
711                                          * Initialized for 30 seconds as we
712                                          * expect all commands to retuned
713                                          * ASAP.
714                                          */
715
716         while (wait_cnt) {
717                 spin_lock_irqsave(&ha->hardware_lock, flags);
718                 /* Find a command that hasn't completed. */
719                 for (index = 0; index < ha->host->can_queue; index++) {
720                         cmd = scsi_host_find_tag(ha->host, index);
721                         if (cmd != NULL)
722                                 break;
723                 }
724                 spin_unlock_irqrestore(&ha->hardware_lock, flags);
725
726                 /* If No Commands are pending, wait is complete */
727                 if (index == ha->host->can_queue) {
728                         break;
729                 }
730
731                 /* If we timed out on waiting for commands to come back
732                  * return ERROR.
733                  */
734                 wait_cnt--;
735                 if (wait_cnt == 0)
736                         stat = QLA_ERROR;
737                 else {
738                         msleep(1000);
739                 }
740         }                       /* End of While (wait_cnt) */
741
742         return stat;
743 }
744
745 void qla4xxx_hw_reset(struct scsi_qla_host *ha)
746 {
747         uint32_t ctrl_status;
748         unsigned long flags = 0;
749
750         DEBUG2(printk(KERN_ERR "scsi%ld: %s\n", ha->host_no, __func__));
751
752         spin_lock_irqsave(&ha->hardware_lock, flags);
753
754         /*
755          * If the SCSI Reset Interrupt bit is set, clear it.
756          * Otherwise, the Soft Reset won't work.
757          */
758         ctrl_status = readw(&ha->reg->ctrl_status);
759         if ((ctrl_status & CSR_SCSI_RESET_INTR) != 0)
760                 writel(set_rmask(CSR_SCSI_RESET_INTR), &ha->reg->ctrl_status);
761
762         /* Issue Soft Reset */
763         writel(set_rmask(CSR_SOFT_RESET), &ha->reg->ctrl_status);
764         readl(&ha->reg->ctrl_status);
765
766         spin_unlock_irqrestore(&ha->hardware_lock, flags);
767 }
768
769 /**
770  * qla4xxx_soft_reset - performs soft reset.
771  * @ha: Pointer to host adapter structure.
772  **/
773 int qla4xxx_soft_reset(struct scsi_qla_host *ha)
774 {
775         uint32_t max_wait_time;
776         unsigned long flags = 0;
777         int status = QLA_ERROR;
778         uint32_t ctrl_status;
779
780         qla4xxx_hw_reset(ha);
781
782         /* Wait until the Network Reset Intr bit is cleared */
783         max_wait_time = RESET_INTR_TOV;
784         do {
785                 spin_lock_irqsave(&ha->hardware_lock, flags);
786                 ctrl_status = readw(&ha->reg->ctrl_status);
787                 spin_unlock_irqrestore(&ha->hardware_lock, flags);
788
789                 if ((ctrl_status & CSR_NET_RESET_INTR) == 0)
790                         break;
791
792                 msleep(1000);
793         } while ((--max_wait_time));
794
795         if ((ctrl_status & CSR_NET_RESET_INTR) != 0) {
796                 DEBUG2(printk(KERN_WARNING
797                               "scsi%ld: Network Reset Intr not cleared by "
798                               "Network function, clearing it now!\n",
799                               ha->host_no));
800                 spin_lock_irqsave(&ha->hardware_lock, flags);
801                 writel(set_rmask(CSR_NET_RESET_INTR), &ha->reg->ctrl_status);
802                 readl(&ha->reg->ctrl_status);
803                 spin_unlock_irqrestore(&ha->hardware_lock, flags);
804         }
805
806         /* Wait until the firmware tells us the Soft Reset is done */
807         max_wait_time = SOFT_RESET_TOV;
808         do {
809                 spin_lock_irqsave(&ha->hardware_lock, flags);
810                 ctrl_status = readw(&ha->reg->ctrl_status);
811                 spin_unlock_irqrestore(&ha->hardware_lock, flags);
812
813                 if ((ctrl_status & CSR_SOFT_RESET) == 0) {
814                         status = QLA_SUCCESS;
815                         break;
816                 }
817
818                 msleep(1000);
819         } while ((--max_wait_time));
820
821         /*
822          * Also, make sure that the SCSI Reset Interrupt bit has been cleared
823          * after the soft reset has taken place.
824          */
825         spin_lock_irqsave(&ha->hardware_lock, flags);
826         ctrl_status = readw(&ha->reg->ctrl_status);
827         if ((ctrl_status & CSR_SCSI_RESET_INTR) != 0) {
828                 writel(set_rmask(CSR_SCSI_RESET_INTR), &ha->reg->ctrl_status);
829                 readl(&ha->reg->ctrl_status);
830         }
831         spin_unlock_irqrestore(&ha->hardware_lock, flags);
832
833         /* If soft reset fails then most probably the bios on other
834          * function is also enabled.
835          * Since the initialization is sequential the other fn
836          * wont be able to acknowledge the soft reset.
837          * Issue a force soft reset to workaround this scenario.
838          */
839         if (max_wait_time == 0) {
840                 /* Issue Force Soft Reset */
841                 spin_lock_irqsave(&ha->hardware_lock, flags);
842                 writel(set_rmask(CSR_FORCE_SOFT_RESET), &ha->reg->ctrl_status);
843                 readl(&ha->reg->ctrl_status);
844                 spin_unlock_irqrestore(&ha->hardware_lock, flags);
845                 /* Wait until the firmware tells us the Soft Reset is done */
846                 max_wait_time = SOFT_RESET_TOV;
847                 do {
848                         spin_lock_irqsave(&ha->hardware_lock, flags);
849                         ctrl_status = readw(&ha->reg->ctrl_status);
850                         spin_unlock_irqrestore(&ha->hardware_lock, flags);
851
852                         if ((ctrl_status & CSR_FORCE_SOFT_RESET) == 0) {
853                                 status = QLA_SUCCESS;
854                                 break;
855                         }
856
857                         msleep(1000);
858                 } while ((--max_wait_time));
859         }
860
861         return status;
862 }
863
864 /**
865  * qla4xxx_flush_active_srbs - returns all outstanding i/o requests to O.S.
866  * @ha: Pointer to host adapter structure.
867  *
868  * This routine is called just prior to a HARD RESET to return all
869  * outstanding commands back to the Operating System.
870  * Caller should make sure that the following locks are released
871  * before this calling routine: Hardware lock, and io_request_lock.
872  **/
873 static void qla4xxx_flush_active_srbs(struct scsi_qla_host *ha)
874 {
875         struct srb *srb;
876         int i;
877         unsigned long flags;
878
879         spin_lock_irqsave(&ha->hardware_lock, flags);
880         for (i = 0; i < ha->host->can_queue; i++) {
881                 srb = qla4xxx_del_from_active_array(ha, i);
882                 if (srb != NULL) {
883                         srb->cmd->result = DID_RESET << 16;
884                         qla4xxx_srb_compl(ha, srb);
885                 }
886         }
887         spin_unlock_irqrestore(&ha->hardware_lock, flags);
888
889 }
890
891 /**
892  * qla4xxx_recover_adapter - recovers adapter after a fatal error
893  * @ha: Pointer to host adapter structure.
894  * @renew_ddb_list: Indicates what to do with the adapter's ddb list
895  *      after adapter recovery has completed.
896  *      0=preserve ddb list, 1=destroy and rebuild ddb list
897  **/
898 static int qla4xxx_recover_adapter(struct scsi_qla_host *ha,
899                                 uint8_t renew_ddb_list)
900 {
901         int status;
902
903         /* Stall incoming I/O until we are done */
904         clear_bit(AF_ONLINE, &ha->flags);
905         DEBUG2(printk("scsi%ld: %s calling qla4xxx_cmd_wait\n", ha->host_no,
906                       __func__));
907
908         /* Wait for outstanding commands to complete.
909          * Stalls the driver for max 30 secs
910          */
911         status = qla4xxx_cmd_wait(ha);
912
913         qla4xxx_disable_intrs(ha);
914
915         /* Flush any pending ddb changed AENs */
916         qla4xxx_process_aen(ha, FLUSH_DDB_CHANGED_AENS);
917
918         /* Reset the firmware.  If successful, function
919          * returns with ISP interrupts enabled.
920          */
921         if (status == QLA_SUCCESS) {
922                 DEBUG2(printk("scsi%ld: %s - Performing soft reset..\n",
923                               ha->host_no, __func__));
924                 qla4xxx_flush_active_srbs(ha);
925                 if (ql4xxx_lock_drvr_wait(ha) == QLA_SUCCESS)
926                         status = qla4xxx_soft_reset(ha);
927                 else
928                         status = QLA_ERROR;
929         }
930
931         /* Flush any pending ddb changed AENs */
932         qla4xxx_process_aen(ha, FLUSH_DDB_CHANGED_AENS);
933
934         /* Re-initialize firmware. If successful, function returns
935          * with ISP interrupts enabled */
936         if (status == QLA_SUCCESS) {
937                 DEBUG2(printk("scsi%ld: %s - Initializing adapter..\n",
938                               ha->host_no, __func__));
939
940                 /* If successful, AF_ONLINE flag set in
941                  * qla4xxx_initialize_adapter */
942                 status = qla4xxx_initialize_adapter(ha, renew_ddb_list);
943         }
944
945         /* Failed adapter initialization?
946          * Retry reset_ha only if invoked via DPC (DPC_RESET_HA) */
947         if ((test_bit(AF_ONLINE, &ha->flags) == 0) &&
948             (test_bit(DPC_RESET_HA, &ha->dpc_flags))) {
949                 /* Adapter initialization failed, see if we can retry
950                  * resetting the ha */
951                 if (!test_bit(DPC_RETRY_RESET_HA, &ha->dpc_flags)) {
952                         ha->retry_reset_ha_cnt = MAX_RESET_HA_RETRIES;
953                         DEBUG2(printk("scsi%ld: recover adapter - retrying "
954                                       "(%d) more times\n", ha->host_no,
955                                       ha->retry_reset_ha_cnt));
956                         set_bit(DPC_RETRY_RESET_HA, &ha->dpc_flags);
957                         status = QLA_ERROR;
958                 } else {
959                         if (ha->retry_reset_ha_cnt > 0) {
960                                 /* Schedule another Reset HA--DPC will retry */
961                                 ha->retry_reset_ha_cnt--;
962                                 DEBUG2(printk("scsi%ld: recover adapter - "
963                                               "retry remaining %d\n",
964                                               ha->host_no,
965                                               ha->retry_reset_ha_cnt));
966                                 status = QLA_ERROR;
967                         }
968
969                         if (ha->retry_reset_ha_cnt == 0) {
970                                 /* Recover adapter retries have been exhausted.
971                                  * Adapter DEAD */
972                                 DEBUG2(printk("scsi%ld: recover adapter "
973                                               "failed - board disabled\n",
974                                               ha->host_no));
975                                 qla4xxx_flush_active_srbs(ha);
976                                 clear_bit(DPC_RETRY_RESET_HA, &ha->dpc_flags);
977                                 clear_bit(DPC_RESET_HA, &ha->dpc_flags);
978                                 clear_bit(DPC_RESET_HA_DESTROY_DDB_LIST,
979                                           &ha->dpc_flags);
980                                 status = QLA_ERROR;
981                         }
982                 }
983         } else {
984                 clear_bit(DPC_RESET_HA, &ha->dpc_flags);
985                 clear_bit(DPC_RESET_HA_DESTROY_DDB_LIST, &ha->dpc_flags);
986                 clear_bit(DPC_RETRY_RESET_HA, &ha->dpc_flags);
987         }
988
989         ha->adapter_error_count++;
990
991         if (status == QLA_SUCCESS)
992                 qla4xxx_enable_intrs(ha);
993
994         DEBUG2(printk("scsi%ld: recover adapter .. DONE\n", ha->host_no));
995         return status;
996 }
997
998 /**
999  * qla4xxx_do_dpc - dpc routine
1000  * @data: in our case pointer to adapter structure
1001  *
1002  * This routine is a task that is schedule by the interrupt handler
1003  * to perform the background processing for interrupts.  We put it
1004  * on a task queue that is consumed whenever the scheduler runs; that's
1005  * so you can do anything (i.e. put the process to sleep etc).  In fact,
1006  * the mid-level tries to sleep when it reaches the driver threshold
1007  * "host->can_queue". This can cause a panic if we were in our interrupt code.
1008  **/
1009 static void qla4xxx_do_dpc(struct work_struct *work)
1010 {
1011         struct scsi_qla_host *ha =
1012                 container_of(work, struct scsi_qla_host, dpc_work);
1013         struct ddb_entry *ddb_entry, *dtemp;
1014         int status = QLA_ERROR;
1015
1016         DEBUG2(printk("scsi%ld: %s: DPC handler waking up."
1017                 "flags = 0x%08lx, dpc_flags = 0x%08lx ctrl_stat = 0x%08x\n",
1018                 ha->host_no, __func__, ha->flags, ha->dpc_flags,
1019                 readw(&ha->reg->ctrl_status)));
1020
1021         /* Initialization not yet finished. Don't do anything yet. */
1022         if (!test_bit(AF_INIT_DONE, &ha->flags))
1023                 return;
1024
1025         if (adapter_up(ha) ||
1026             test_bit(DPC_RESET_HA, &ha->dpc_flags) ||
1027             test_bit(DPC_RESET_HA_INTR, &ha->dpc_flags) ||
1028             test_bit(DPC_RESET_HA_DESTROY_DDB_LIST, &ha->dpc_flags)) {
1029                 if (test_bit(DPC_RESET_HA_DESTROY_DDB_LIST, &ha->dpc_flags) ||
1030                         test_bit(DPC_RESET_HA, &ha->dpc_flags))
1031                         qla4xxx_recover_adapter(ha, PRESERVE_DDB_LIST);
1032
1033                 if (test_bit(DPC_RESET_HA_INTR, &ha->dpc_flags)) {
1034                         uint8_t wait_time = RESET_INTR_TOV;
1035
1036                         while ((readw(&ha->reg->ctrl_status) &
1037                                 (CSR_SOFT_RESET | CSR_FORCE_SOFT_RESET)) != 0) {
1038                                 if (--wait_time == 0)
1039                                         break;
1040                                 msleep(1000);
1041                         }
1042                         if (wait_time == 0)
1043                                 DEBUG2(printk("scsi%ld: %s: SR|FSR "
1044                                               "bit not cleared-- resetting\n",
1045                                               ha->host_no, __func__));
1046                         qla4xxx_flush_active_srbs(ha);
1047                         if (ql4xxx_lock_drvr_wait(ha) == QLA_SUCCESS) {
1048                                 qla4xxx_process_aen(ha, FLUSH_DDB_CHANGED_AENS);
1049                                 status = qla4xxx_initialize_adapter(ha,
1050                                                 PRESERVE_DDB_LIST);
1051                         }
1052                         clear_bit(DPC_RESET_HA_INTR, &ha->dpc_flags);
1053                         if (status == QLA_SUCCESS)
1054                                 qla4xxx_enable_intrs(ha);
1055                 }
1056         }
1057
1058         /* ---- process AEN? --- */
1059         if (test_and_clear_bit(DPC_AEN, &ha->dpc_flags))
1060                 qla4xxx_process_aen(ha, PROCESS_ALL_AENS);
1061
1062         /* ---- Get DHCP IP Address? --- */
1063         if (test_and_clear_bit(DPC_GET_DHCP_IP_ADDR, &ha->dpc_flags))
1064                 qla4xxx_get_dhcp_ip_address(ha);
1065
1066         /* ---- relogin device? --- */
1067         if (adapter_up(ha) &&
1068             test_and_clear_bit(DPC_RELOGIN_DEVICE, &ha->dpc_flags)) {
1069                 list_for_each_entry_safe(ddb_entry, dtemp,
1070                                          &ha->ddb_list, list) {
1071                         if (test_and_clear_bit(DF_RELOGIN, &ddb_entry->flags) &&
1072                             atomic_read(&ddb_entry->state) != DDB_STATE_ONLINE)
1073                                 qla4xxx_relogin_device(ha, ddb_entry);
1074
1075                         /*
1076                          * If mbx cmd times out there is no point
1077                          * in continuing further.
1078                          * With large no of targets this can hang
1079                          * the system.
1080                          */
1081                         if (test_bit(DPC_RESET_HA, &ha->dpc_flags)) {
1082                                 printk(KERN_WARNING "scsi%ld: %s: "
1083                                        "need to reset hba\n",
1084                                        ha->host_no, __func__);
1085                                 break;
1086                         }
1087                 }
1088         }
1089 }
1090
1091 /**
1092  * qla4xxx_free_adapter - release the adapter
1093  * @ha: pointer to adapter structure
1094  **/
1095 static void qla4xxx_free_adapter(struct scsi_qla_host *ha)
1096 {
1097
1098         if (test_bit(AF_INTERRUPTS_ON, &ha->flags)) {
1099                 /* Turn-off interrupts on the card. */
1100                 qla4xxx_disable_intrs(ha);
1101         }
1102
1103         /* Kill the kernel thread for this host */
1104         if (ha->dpc_thread)
1105                 destroy_workqueue(ha->dpc_thread);
1106
1107         /* Issue Soft Reset to put firmware in unknown state */
1108         if (ql4xxx_lock_drvr_wait(ha) == QLA_SUCCESS)
1109                 qla4xxx_hw_reset(ha);
1110
1111         /* Remove timer thread, if present */
1112         if (ha->timer_active)
1113                 qla4xxx_stop_timer(ha);
1114
1115         /* Detach interrupts */
1116         if (test_and_clear_bit(AF_IRQ_ATTACHED, &ha->flags))
1117                 free_irq(ha->pdev->irq, ha);
1118
1119         /* free extra memory */
1120         qla4xxx_mem_free(ha);
1121
1122         pci_disable_device(ha->pdev);
1123
1124 }
1125
1126 /***
1127  * qla4xxx_iospace_config - maps registers
1128  * @ha: pointer to adapter structure
1129  *
1130  * This routines maps HBA's registers from the pci address space
1131  * into the kernel virtual address space for memory mapped i/o.
1132  **/
1133 static int qla4xxx_iospace_config(struct scsi_qla_host *ha)
1134 {
1135         unsigned long pio, pio_len, pio_flags;
1136         unsigned long mmio, mmio_len, mmio_flags;
1137
1138         pio = pci_resource_start(ha->pdev, 0);
1139         pio_len = pci_resource_len(ha->pdev, 0);
1140         pio_flags = pci_resource_flags(ha->pdev, 0);
1141         if (pio_flags & IORESOURCE_IO) {
1142                 if (pio_len < MIN_IOBASE_LEN) {
1143                         dev_warn(&ha->pdev->dev,
1144                                 "Invalid PCI I/O region size\n");
1145                         pio = 0;
1146                 }
1147         } else {
1148                 dev_warn(&ha->pdev->dev, "region #0 not a PIO resource\n");
1149                 pio = 0;
1150         }
1151
1152         /* Use MMIO operations for all accesses. */
1153         mmio = pci_resource_start(ha->pdev, 1);
1154         mmio_len = pci_resource_len(ha->pdev, 1);
1155         mmio_flags = pci_resource_flags(ha->pdev, 1);
1156
1157         if (!(mmio_flags & IORESOURCE_MEM)) {
1158                 dev_err(&ha->pdev->dev,
1159                         "region #0 not an MMIO resource, aborting\n");
1160
1161                 goto iospace_error_exit;
1162         }
1163         if (mmio_len < MIN_IOBASE_LEN) {
1164                 dev_err(&ha->pdev->dev,
1165                         "Invalid PCI mem region size, aborting\n");
1166                 goto iospace_error_exit;
1167         }
1168
1169         if (pci_request_regions(ha->pdev, DRIVER_NAME)) {
1170                 dev_warn(&ha->pdev->dev,
1171                         "Failed to reserve PIO/MMIO regions\n");
1172
1173                 goto iospace_error_exit;
1174         }
1175
1176         ha->pio_address = pio;
1177         ha->pio_length = pio_len;
1178         ha->reg = ioremap(mmio, MIN_IOBASE_LEN);
1179         if (!ha->reg) {
1180                 dev_err(&ha->pdev->dev,
1181                         "cannot remap MMIO, aborting\n");
1182
1183                 goto iospace_error_exit;
1184         }
1185
1186         return 0;
1187
1188 iospace_error_exit:
1189         return -ENOMEM;
1190 }
1191
1192 /**
1193  * qla4xxx_probe_adapter - callback function to probe HBA
1194  * @pdev: pointer to pci_dev structure
1195  * @pci_device_id: pointer to pci_device entry
1196  *
1197  * This routine will probe for Qlogic 4xxx iSCSI host adapters.
1198  * It returns zero if successful. It also initializes all data necessary for
1199  * the driver.
1200  **/
1201 static int __devinit qla4xxx_probe_adapter(struct pci_dev *pdev,
1202                                            const struct pci_device_id *ent)
1203 {
1204         int ret = -ENODEV, status;
1205         struct Scsi_Host *host;
1206         struct scsi_qla_host *ha;
1207         struct ddb_entry *ddb_entry, *ddbtemp;
1208         uint8_t init_retry_count = 0;
1209         char buf[34];
1210
1211         if (pci_enable_device(pdev))
1212                 return -1;
1213
1214         host = scsi_host_alloc(&qla4xxx_driver_template, sizeof(*ha));
1215         if (host == NULL) {
1216                 printk(KERN_WARNING
1217                        "qla4xxx: Couldn't allocate host from scsi layer!\n");
1218                 goto probe_disable_device;
1219         }
1220
1221         /* Clear our data area */
1222         ha = (struct scsi_qla_host *) host->hostdata;
1223         memset(ha, 0, sizeof(*ha));
1224
1225         /* Save the information from PCI BIOS.  */
1226         ha->pdev = pdev;
1227         ha->host = host;
1228         ha->host_no = host->host_no;
1229
1230         /* Configure PCI I/O space. */
1231         ret = qla4xxx_iospace_config(ha);
1232         if (ret)
1233                 goto probe_failed;
1234
1235         dev_info(&ha->pdev->dev, "Found an ISP%04x, irq %d, iobase 0x%p\n",
1236                    pdev->device, pdev->irq, ha->reg);
1237
1238         qla4xxx_config_dma_addressing(ha);
1239
1240         /* Initialize lists and spinlocks. */
1241         INIT_LIST_HEAD(&ha->ddb_list);
1242         INIT_LIST_HEAD(&ha->free_srb_q);
1243
1244         mutex_init(&ha->mbox_sem);
1245
1246         spin_lock_init(&ha->hardware_lock);
1247
1248         /* Allocate dma buffers */
1249         if (qla4xxx_mem_alloc(ha)) {
1250                 dev_warn(&ha->pdev->dev,
1251                            "[ERROR] Failed to allocate memory for adapter\n");
1252
1253                 ret = -ENOMEM;
1254                 goto probe_failed;
1255         }
1256
1257         /*
1258          * Initialize the Host adapter request/response queues and
1259          * firmware
1260          * NOTE: interrupts enabled upon successful completion
1261          */
1262         status = qla4xxx_initialize_adapter(ha, REBUILD_DDB_LIST);
1263         while (status == QLA_ERROR && init_retry_count++ < MAX_INIT_RETRIES) {
1264                 DEBUG2(printk("scsi: %s: retrying adapter initialization "
1265                               "(%d)\n", __func__, init_retry_count));
1266                 qla4xxx_soft_reset(ha);
1267                 status = qla4xxx_initialize_adapter(ha, REBUILD_DDB_LIST);
1268         }
1269         if (status == QLA_ERROR) {
1270                 dev_warn(&ha->pdev->dev, "Failed to initialize adapter\n");
1271
1272                 ret = -ENODEV;
1273                 goto probe_failed;
1274         }
1275
1276         host->cmd_per_lun = 3;
1277         host->max_channel = 0;
1278         host->max_lun = MAX_LUNS - 1;
1279         host->max_id = MAX_TARGETS;
1280         host->max_cmd_len = IOCB_MAX_CDB_LEN;
1281         host->can_queue = MAX_SRBS ;
1282         host->transportt = qla4xxx_scsi_transport;
1283
1284         ret = scsi_init_shared_tag_map(host, MAX_SRBS);
1285         if (ret) {
1286                 dev_warn(&ha->pdev->dev, "scsi_init_shared_tag_map failed\n");
1287                 goto probe_failed;
1288         }
1289
1290         /* Startup the kernel thread for this host adapter. */
1291         DEBUG2(printk("scsi: %s: Starting kernel thread for "
1292                       "qla4xxx_dpc\n", __func__));
1293         sprintf(buf, "qla4xxx_%lu_dpc", ha->host_no);
1294         ha->dpc_thread = create_singlethread_workqueue(buf);
1295         if (!ha->dpc_thread) {
1296                 dev_warn(&ha->pdev->dev, "Unable to start DPC thread!\n");
1297                 ret = -ENODEV;
1298                 goto probe_failed;
1299         }
1300         INIT_WORK(&ha->dpc_work, qla4xxx_do_dpc);
1301
1302         ret = request_irq(pdev->irq, qla4xxx_intr_handler,
1303                           IRQF_DISABLED | IRQF_SHARED, "qla4xxx", ha);
1304         if (ret) {
1305                 dev_warn(&ha->pdev->dev, "Failed to reserve interrupt %d"
1306                         " already in use.\n", pdev->irq);
1307                 goto probe_failed;
1308         }
1309         set_bit(AF_IRQ_ATTACHED, &ha->flags);
1310         host->irq = pdev->irq;
1311         DEBUG(printk("scsi%d: irq %d attached\n", ha->host_no, ha->pdev->irq));
1312
1313         qla4xxx_enable_intrs(ha);
1314
1315         /* Start timer thread. */
1316         qla4xxx_start_timer(ha, qla4xxx_timer, 1);
1317
1318         set_bit(AF_INIT_DONE, &ha->flags);
1319
1320         pci_set_drvdata(pdev, ha);
1321
1322         ret = scsi_add_host(host, &pdev->dev);
1323         if (ret)
1324                 goto probe_failed;
1325
1326         /* Update transport device information for all devices. */
1327         list_for_each_entry_safe(ddb_entry, ddbtemp, &ha->ddb_list, list) {
1328                 if (ddb_entry->fw_ddb_device_state == DDB_DS_SESSION_ACTIVE)
1329                         if (qla4xxx_add_sess(ddb_entry))
1330                                 goto remove_host;
1331         }
1332
1333         printk(KERN_INFO
1334                " QLogic iSCSI HBA Driver version: %s\n"
1335                "  QLogic ISP%04x @ %s, host#=%ld, fw=%02d.%02d.%02d.%02d\n",
1336                qla4xxx_version_str, ha->pdev->device, pci_name(ha->pdev),
1337                ha->host_no, ha->firmware_version[0], ha->firmware_version[1],
1338                ha->patch_number, ha->build_number);
1339
1340         return 0;
1341
1342 remove_host:
1343         qla4xxx_free_ddb_list(ha);
1344         scsi_remove_host(host);
1345
1346 probe_failed:
1347         qla4xxx_free_adapter(ha);
1348         scsi_host_put(ha->host);
1349
1350 probe_disable_device:
1351         pci_disable_device(pdev);
1352
1353         return ret;
1354 }
1355
1356 /**
1357  * qla4xxx_remove_adapter - calback function to remove adapter.
1358  * @pci_dev: PCI device pointer
1359  **/
1360 static void __devexit qla4xxx_remove_adapter(struct pci_dev *pdev)
1361 {
1362         struct scsi_qla_host *ha;
1363
1364         ha = pci_get_drvdata(pdev);
1365
1366         qla4xxx_disable_intrs(ha);
1367
1368         while (test_bit(DPC_RESET_HA_INTR, &ha->dpc_flags))
1369                 ssleep(1);
1370
1371         /* remove devs from iscsi_sessions to scsi_devices */
1372         qla4xxx_free_ddb_list(ha);
1373
1374         scsi_remove_host(ha->host);
1375
1376         qla4xxx_free_adapter(ha);
1377
1378         scsi_host_put(ha->host);
1379
1380         pci_set_drvdata(pdev, NULL);
1381 }
1382
1383 /**
1384  * qla4xxx_config_dma_addressing() - Configure OS DMA addressing method.
1385  * @ha: HA context
1386  *
1387  * At exit, the @ha's flags.enable_64bit_addressing set to indicated
1388  * supported addressing method.
1389  */
1390 static void qla4xxx_config_dma_addressing(struct scsi_qla_host *ha)
1391 {
1392         int retval;
1393
1394         /* Update our PCI device dma_mask for full 64 bit mask */
1395         if (pci_set_dma_mask(ha->pdev, DMA_64BIT_MASK) == 0) {
1396                 if (pci_set_consistent_dma_mask(ha->pdev, DMA_64BIT_MASK)) {
1397                         dev_dbg(&ha->pdev->dev,
1398                                   "Failed to set 64 bit PCI consistent mask; "
1399                                    "using 32 bit.\n");
1400                         retval = pci_set_consistent_dma_mask(ha->pdev,
1401                                                              DMA_32BIT_MASK);
1402                 }
1403         } else
1404                 retval = pci_set_dma_mask(ha->pdev, DMA_32BIT_MASK);
1405 }
1406
1407 static int qla4xxx_slave_alloc(struct scsi_device *sdev)
1408 {
1409         struct iscsi_cls_session *sess = starget_to_session(sdev->sdev_target);
1410         struct ddb_entry *ddb = sess->dd_data;
1411
1412         sdev->hostdata = ddb;
1413         sdev->tagged_supported = 1;
1414         scsi_activate_tcq(sdev, sdev->host->can_queue);
1415         return 0;
1416 }
1417
1418 static int qla4xxx_slave_configure(struct scsi_device *sdev)
1419 {
1420         sdev->tagged_supported = 1;
1421         return 0;
1422 }
1423
1424 static void qla4xxx_slave_destroy(struct scsi_device *sdev)
1425 {
1426         scsi_deactivate_tcq(sdev, 1);
1427 }
1428
1429 /**
1430  * qla4xxx_del_from_active_array - returns an active srb
1431  * @ha: Pointer to host adapter structure.
1432  * @index: index into to the active_array
1433  *
1434  * This routine removes and returns the srb at the specified index
1435  **/
1436 struct srb * qla4xxx_del_from_active_array(struct scsi_qla_host *ha, uint32_t index)
1437 {
1438         struct srb *srb = NULL;
1439         struct scsi_cmnd *cmd;
1440
1441         if (!(cmd = scsi_host_find_tag(ha->host, index)))
1442                 return srb;
1443
1444         if (!(srb = (struct srb *)cmd->host_scribble))
1445                 return srb;
1446
1447         /* update counters */
1448         if (srb->flags & SRB_DMA_VALID) {
1449                 ha->req_q_count += srb->iocb_cnt;
1450                 ha->iocb_cnt -= srb->iocb_cnt;
1451                 if (srb->cmd)
1452                         srb->cmd->host_scribble = NULL;
1453         }
1454         return srb;
1455 }
1456
1457 /**
1458  * qla4xxx_eh_wait_on_command - waits for command to be returned by firmware
1459  * @ha: actual ha whose done queue will contain the comd returned by firmware.
1460  * @cmd: Scsi Command to wait on.
1461  *
1462  * This routine waits for the command to be returned by the Firmware
1463  * for some max time.
1464  **/
1465 static int qla4xxx_eh_wait_on_command(struct scsi_qla_host *ha,
1466                                       struct scsi_cmnd *cmd)
1467 {
1468         int done = 0;
1469         struct srb *rp;
1470         uint32_t max_wait_time = EH_WAIT_CMD_TOV;
1471
1472         do {
1473                 /* Checking to see if its returned to OS */
1474                 rp = (struct srb *) cmd->SCp.ptr;
1475                 if (rp == NULL) {
1476                         done++;
1477                         break;
1478                 }
1479
1480                 msleep(2000);
1481         } while (max_wait_time--);
1482
1483         return done;
1484 }
1485
1486 /**
1487  * qla4xxx_wait_for_hba_online - waits for HBA to come online
1488  * @ha: Pointer to host adapter structure
1489  **/
1490 static int qla4xxx_wait_for_hba_online(struct scsi_qla_host *ha)
1491 {
1492         unsigned long wait_online;
1493
1494         wait_online = jiffies + (30 * HZ);
1495         while (time_before(jiffies, wait_online)) {
1496
1497                 if (adapter_up(ha))
1498                         return QLA_SUCCESS;
1499                 else if (ha->retry_reset_ha_cnt == 0)
1500                         return QLA_ERROR;
1501
1502                 msleep(2000);
1503         }
1504
1505         return QLA_ERROR;
1506 }
1507
1508 /**
1509  * qla4xxx_eh_wait_for_active_target_commands - wait for active cmds to finish.
1510  * @ha: pointer to to HBA
1511  * @t: target id
1512  * @l: lun id
1513  *
1514  * This function waits for all outstanding commands to a lun to complete. It
1515  * returns 0 if all pending commands are returned and 1 otherwise.
1516  **/
1517 static int qla4xxx_eh_wait_for_active_target_commands(struct scsi_qla_host *ha,
1518                                                  int t, int l)
1519 {
1520         int cnt;
1521         int status = 0;
1522         struct scsi_cmnd *cmd;
1523
1524         /*
1525          * Waiting for all commands for the designated target in the active
1526          * array
1527          */
1528         for (cnt = 0; cnt < ha->host->can_queue; cnt++) {
1529                 cmd = scsi_host_find_tag(ha->host, cnt);
1530                 if (cmd && cmd->device->id == t && cmd->device->lun == l) {
1531                         if (!qla4xxx_eh_wait_on_command(ha, cmd)) {
1532                                 status++;
1533                                 break;
1534                         }
1535                 }
1536         }
1537         return status;
1538 }
1539
1540 /**
1541  * qla4xxx_eh_device_reset - callback for target reset.
1542  * @cmd: Pointer to Linux's SCSI command structure
1543  *
1544  * This routine is called by the Linux OS to reset all luns on the
1545  * specified target.
1546  **/
1547 static int qla4xxx_eh_device_reset(struct scsi_cmnd *cmd)
1548 {
1549         struct scsi_qla_host *ha = to_qla_host(cmd->device->host);
1550         struct ddb_entry *ddb_entry = cmd->device->hostdata;
1551         struct srb *sp;
1552         int ret = FAILED, stat;
1553
1554         sp = (struct srb *) cmd->SCp.ptr;
1555         if (!sp || !ddb_entry)
1556                 return ret;
1557
1558         dev_info(&ha->pdev->dev,
1559                    "scsi%ld:%d:%d:%d: DEVICE RESET ISSUED.\n", ha->host_no,
1560                    cmd->device->channel, cmd->device->id, cmd->device->lun);
1561
1562         DEBUG2(printk(KERN_INFO
1563                       "scsi%ld: DEVICE_RESET cmd=%p jiffies = 0x%lx, to=%x,"
1564                       "dpc_flags=%lx, status=%x allowed=%d\n", ha->host_no,
1565                       cmd, jiffies, cmd->timeout_per_command / HZ,
1566                       ha->dpc_flags, cmd->result, cmd->allowed));
1567
1568         /* FIXME: wait for hba to go online */
1569         stat = qla4xxx_reset_lun(ha, ddb_entry, cmd->device->lun);
1570         if (stat != QLA_SUCCESS) {
1571                 dev_info(&ha->pdev->dev, "DEVICE RESET FAILED. %d\n", stat);
1572                 goto eh_dev_reset_done;
1573         }
1574
1575         /* Send marker. */
1576         ha->marker_needed = 1;
1577
1578         /*
1579          * If we are coming down the EH path, wait for all commands to complete
1580          * for the device.
1581          */
1582         if (cmd->device->host->shost_state == SHOST_RECOVERY) {
1583                 if (qla4xxx_eh_wait_for_active_target_commands(ha,
1584                                                           cmd->device->id,
1585                                                           cmd->device->lun)){
1586                         dev_info(&ha->pdev->dev,
1587                                    "DEVICE RESET FAILED - waiting for "
1588                                    "commands.\n");
1589                         goto eh_dev_reset_done;
1590                 }
1591         }
1592
1593         dev_info(&ha->pdev->dev,
1594                    "scsi(%ld:%d:%d:%d): DEVICE RESET SUCCEEDED.\n",
1595                    ha->host_no, cmd->device->channel, cmd->device->id,
1596                    cmd->device->lun);
1597
1598         ret = SUCCESS;
1599
1600 eh_dev_reset_done:
1601
1602         return ret;
1603 }
1604
1605 /**
1606  * qla4xxx_eh_host_reset - kernel callback
1607  * @cmd: Pointer to Linux's SCSI command structure
1608  *
1609  * This routine is invoked by the Linux kernel to perform fatal error
1610  * recovery on the specified adapter.
1611  **/
1612 static int qla4xxx_eh_host_reset(struct scsi_cmnd *cmd)
1613 {
1614         int return_status = FAILED;
1615         struct scsi_qla_host *ha;
1616
1617         ha = (struct scsi_qla_host *) cmd->device->host->hostdata;
1618
1619         dev_info(&ha->pdev->dev,
1620                    "scsi(%ld:%d:%d:%d): ADAPTER RESET ISSUED.\n", ha->host_no,
1621                    cmd->device->channel, cmd->device->id, cmd->device->lun);
1622
1623         if (qla4xxx_wait_for_hba_online(ha) != QLA_SUCCESS) {
1624                 DEBUG2(printk("scsi%ld:%d: %s: Unable to reset host.  Adapter "
1625                               "DEAD.\n", ha->host_no, cmd->device->channel,
1626                               __func__));
1627
1628                 return FAILED;
1629         }
1630
1631         if (qla4xxx_recover_adapter(ha, PRESERVE_DDB_LIST) == QLA_SUCCESS) {
1632                 return_status = SUCCESS;
1633         }
1634
1635         dev_info(&ha->pdev->dev, "HOST RESET %s.\n",
1636                    return_status == FAILED ? "FAILED" : "SUCCEDED");
1637
1638         return return_status;
1639 }
1640
1641
1642 static struct pci_device_id qla4xxx_pci_tbl[] = {
1643         {
1644                 .vendor         = PCI_VENDOR_ID_QLOGIC,
1645                 .device         = PCI_DEVICE_ID_QLOGIC_ISP4010,
1646                 .subvendor      = PCI_ANY_ID,
1647                 .subdevice      = PCI_ANY_ID,
1648         },
1649         {
1650                 .vendor         = PCI_VENDOR_ID_QLOGIC,
1651                 .device         = PCI_DEVICE_ID_QLOGIC_ISP4022,
1652                 .subvendor      = PCI_ANY_ID,
1653                 .subdevice      = PCI_ANY_ID,
1654         },
1655         {
1656                 .vendor         = PCI_VENDOR_ID_QLOGIC,
1657                 .device         = PCI_DEVICE_ID_QLOGIC_ISP4032,
1658                 .subvendor      = PCI_ANY_ID,
1659                 .subdevice      = PCI_ANY_ID,
1660         },
1661         {0, 0},
1662 };
1663 MODULE_DEVICE_TABLE(pci, qla4xxx_pci_tbl);
1664
1665 static struct pci_driver qla4xxx_pci_driver = {
1666         .name           = DRIVER_NAME,
1667         .id_table       = qla4xxx_pci_tbl,
1668         .probe          = qla4xxx_probe_adapter,
1669         .remove         = qla4xxx_remove_adapter,
1670 };
1671
1672 static int __init qla4xxx_module_init(void)
1673 {
1674         int ret;
1675
1676         /* Allocate cache for SRBs. */
1677         srb_cachep = kmem_cache_create("qla4xxx_srbs", sizeof(struct srb), 0,
1678                                        SLAB_HWCACHE_ALIGN, NULL);
1679         if (srb_cachep == NULL) {
1680                 printk(KERN_ERR
1681                        "%s: Unable to allocate SRB cache..."
1682                        "Failing load!\n", DRIVER_NAME);
1683                 ret = -ENOMEM;
1684                 goto no_srp_cache;
1685         }
1686
1687         /* Derive version string. */
1688         strcpy(qla4xxx_version_str, QLA4XXX_DRIVER_VERSION);
1689         if (ql4xextended_error_logging)
1690                 strcat(qla4xxx_version_str, "-debug");
1691
1692         qla4xxx_scsi_transport =
1693                 iscsi_register_transport(&qla4xxx_iscsi_transport);
1694         if (!qla4xxx_scsi_transport){
1695                 ret = -ENODEV;
1696                 goto release_srb_cache;
1697         }
1698
1699         ret = pci_register_driver(&qla4xxx_pci_driver);
1700         if (ret)
1701                 goto unregister_transport;
1702
1703         printk(KERN_INFO "QLogic iSCSI HBA Driver\n");
1704         return 0;
1705
1706 unregister_transport:
1707         iscsi_unregister_transport(&qla4xxx_iscsi_transport);
1708 release_srb_cache:
1709         kmem_cache_destroy(srb_cachep);
1710 no_srp_cache:
1711         return ret;
1712 }
1713
1714 static void __exit qla4xxx_module_exit(void)
1715 {
1716         ql4_mod_unload = 1;
1717         pci_unregister_driver(&qla4xxx_pci_driver);
1718         iscsi_unregister_transport(&qla4xxx_iscsi_transport);
1719         kmem_cache_destroy(srb_cachep);
1720 }
1721
1722 module_init(qla4xxx_module_init);
1723 module_exit(qla4xxx_module_exit);
1724
1725 MODULE_AUTHOR("QLogic Corporation");
1726 MODULE_DESCRIPTION("QLogic iSCSI HBA Driver");
1727 MODULE_LICENSE("GPL");
1728 MODULE_VERSION(QLA4XXX_DRIVER_VERSION);