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