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