[SCSI] qla4xxx: fix flash/ddb support
[pandora-kernel.git] / drivers / scsi / qla4xxx / ql4_os.c
1 /*
2  * QLogic iSCSI HBA Driver
3  * Copyright (c)  2003-2010 QLogic Corporation
4  *
5  * See LICENSE.qla4xxx for copyright and licensing details.
6  */
7 #include <linux/moduleparam.h>
8 #include <linux/slab.h>
9 #include <linux/blkdev.h>
10 #include <linux/iscsi_boot_sysfs.h>
11 #include <linux/inet.h>
12
13 #include <scsi/scsi_tcq.h>
14 #include <scsi/scsicam.h>
15
16 #include "ql4_def.h"
17 #include "ql4_version.h"
18 #include "ql4_glbl.h"
19 #include "ql4_dbg.h"
20 #include "ql4_inline.h"
21
22 /*
23  * Driver version
24  */
25 static char qla4xxx_version_str[40];
26
27 /*
28  * SRB allocation cache
29  */
30 static struct kmem_cache *srb_cachep;
31
32 /*
33  * Module parameter information and variables
34  */
35 int ql4xdisablesysfsboot = 1;
36 module_param(ql4xdisablesysfsboot, int, S_IRUGO | S_IWUSR);
37 MODULE_PARM_DESC(ql4xdisablesysfsboot,
38                 "Set to disable exporting boot targets to sysfs\n"
39                 " 0 - Export boot targets\n"
40                 " 1 - Do not export boot targets (Default)");
41
42 int ql4xdontresethba = 0;
43 module_param(ql4xdontresethba, int, S_IRUGO | S_IWUSR);
44 MODULE_PARM_DESC(ql4xdontresethba,
45                 "Don't reset the HBA for driver recovery \n"
46                 " 0 - It will reset HBA (Default)\n"
47                 " 1 - It will NOT reset HBA");
48
49 int ql4xextended_error_logging = 0; /* 0 = off, 1 = log errors */
50 module_param(ql4xextended_error_logging, int, S_IRUGO | S_IWUSR);
51 MODULE_PARM_DESC(ql4xextended_error_logging,
52                  "Option to enable extended error logging, "
53                  "Default is 0 - no logging, 1 - debug logging");
54
55 int ql4xenablemsix = 1;
56 module_param(ql4xenablemsix, int, S_IRUGO|S_IWUSR);
57 MODULE_PARM_DESC(ql4xenablemsix,
58                 "Set to enable MSI or MSI-X interrupt mechanism.\n"
59                 " 0 = enable INTx interrupt mechanism.\n"
60                 " 1 = enable MSI-X interrupt mechanism (Default).\n"
61                 " 2 = enable MSI interrupt mechanism.");
62
63 #define QL4_DEF_QDEPTH 32
64 static int ql4xmaxqdepth = QL4_DEF_QDEPTH;
65 module_param(ql4xmaxqdepth, int, S_IRUGO | S_IWUSR);
66 MODULE_PARM_DESC(ql4xmaxqdepth,
67                 "Maximum queue depth to report for target devices.\n"
68                 " Default: 32.");
69
70 static int ql4xsess_recovery_tmo = QL4_SESS_RECOVERY_TMO;
71 module_param(ql4xsess_recovery_tmo, int, S_IRUGO);
72 MODULE_PARM_DESC(ql4xsess_recovery_tmo,
73                 "Target Session Recovery Timeout.\n"
74                 " Default: 120 sec.");
75
76 static int qla4xxx_wait_for_hba_online(struct scsi_qla_host *ha);
77 /*
78  * SCSI host template entry points
79  */
80 static void qla4xxx_config_dma_addressing(struct scsi_qla_host *ha);
81
82 /*
83  * iSCSI template entry points
84  */
85 static int qla4xxx_conn_get_param(struct iscsi_cls_conn *conn,
86                                   enum iscsi_param param, char *buf);
87 static int qla4xxx_host_get_param(struct Scsi_Host *shost,
88                                   enum iscsi_host_param param, char *buf);
89 static int qla4xxx_iface_set_param(struct Scsi_Host *shost, void *data,
90                                    uint32_t len);
91 static int qla4xxx_get_iface_param(struct iscsi_iface *iface,
92                                    enum iscsi_param_type param_type,
93                                    int param, char *buf);
94 static enum blk_eh_timer_return qla4xxx_eh_cmd_timed_out(struct scsi_cmnd *sc);
95 static struct iscsi_endpoint *qla4xxx_ep_connect(struct Scsi_Host *shost,
96                                                  struct sockaddr *dst_addr,
97                                                  int non_blocking);
98 static int qla4xxx_ep_poll(struct iscsi_endpoint *ep, int timeout_ms);
99 static void qla4xxx_ep_disconnect(struct iscsi_endpoint *ep);
100 static int qla4xxx_get_ep_param(struct iscsi_endpoint *ep,
101                                 enum iscsi_param param, char *buf);
102 static int qla4xxx_conn_start(struct iscsi_cls_conn *conn);
103 static struct iscsi_cls_conn *
104 qla4xxx_conn_create(struct iscsi_cls_session *cls_sess, uint32_t conn_idx);
105 static int qla4xxx_conn_bind(struct iscsi_cls_session *cls_session,
106                              struct iscsi_cls_conn *cls_conn,
107                              uint64_t transport_fd, int is_leading);
108 static void qla4xxx_conn_destroy(struct iscsi_cls_conn *conn);
109 static struct iscsi_cls_session *
110 qla4xxx_session_create(struct iscsi_endpoint *ep, uint16_t cmds_max,
111                         uint16_t qdepth, uint32_t initial_cmdsn);
112 static void qla4xxx_session_destroy(struct iscsi_cls_session *sess);
113 static void qla4xxx_task_work(struct work_struct *wdata);
114 static int qla4xxx_alloc_pdu(struct iscsi_task *, uint8_t);
115 static int qla4xxx_task_xmit(struct iscsi_task *);
116 static void qla4xxx_task_cleanup(struct iscsi_task *);
117 static void qla4xxx_fail_session(struct iscsi_cls_session *cls_session);
118 static void qla4xxx_conn_get_stats(struct iscsi_cls_conn *cls_conn,
119                                    struct iscsi_stats *stats);
120 /*
121  * SCSI host template entry points
122  */
123 static int qla4xxx_queuecommand(struct Scsi_Host *h, struct scsi_cmnd *cmd);
124 static int qla4xxx_eh_abort(struct scsi_cmnd *cmd);
125 static int qla4xxx_eh_device_reset(struct scsi_cmnd *cmd);
126 static int qla4xxx_eh_target_reset(struct scsi_cmnd *cmd);
127 static int qla4xxx_eh_host_reset(struct scsi_cmnd *cmd);
128 static int qla4xxx_slave_alloc(struct scsi_device *device);
129 static int qla4xxx_slave_configure(struct scsi_device *device);
130 static void qla4xxx_slave_destroy(struct scsi_device *sdev);
131 static mode_t ql4_attr_is_visible(int param_type, int param);
132 static int qla4xxx_host_reset(struct Scsi_Host *shost, int reset_type);
133
134 static struct qla4_8xxx_legacy_intr_set legacy_intr[] =
135     QLA82XX_LEGACY_INTR_CONFIG;
136
137 static struct scsi_host_template qla4xxx_driver_template = {
138         .module                 = THIS_MODULE,
139         .name                   = DRIVER_NAME,
140         .proc_name              = DRIVER_NAME,
141         .queuecommand           = qla4xxx_queuecommand,
142
143         .eh_abort_handler       = qla4xxx_eh_abort,
144         .eh_device_reset_handler = qla4xxx_eh_device_reset,
145         .eh_target_reset_handler = qla4xxx_eh_target_reset,
146         .eh_host_reset_handler  = qla4xxx_eh_host_reset,
147         .eh_timed_out           = qla4xxx_eh_cmd_timed_out,
148
149         .slave_configure        = qla4xxx_slave_configure,
150         .slave_alloc            = qla4xxx_slave_alloc,
151         .slave_destroy          = qla4xxx_slave_destroy,
152
153         .this_id                = -1,
154         .cmd_per_lun            = 3,
155         .use_clustering         = ENABLE_CLUSTERING,
156         .sg_tablesize           = SG_ALL,
157
158         .max_sectors            = 0xFFFF,
159         .shost_attrs            = qla4xxx_host_attrs,
160         .host_reset             = qla4xxx_host_reset,
161         .vendor_id              = SCSI_NL_VID_TYPE_PCI | PCI_VENDOR_ID_QLOGIC,
162 };
163
164 static struct iscsi_transport qla4xxx_iscsi_transport = {
165         .owner                  = THIS_MODULE,
166         .name                   = DRIVER_NAME,
167         .caps                   = CAP_TEXT_NEGO |
168                                   CAP_DATA_PATH_OFFLOAD | CAP_HDRDGST |
169                                   CAP_DATADGST | CAP_LOGIN_OFFLOAD |
170                                   CAP_MULTI_R2T,
171         .attr_is_visible        = ql4_attr_is_visible,
172         .create_session         = qla4xxx_session_create,
173         .destroy_session        = qla4xxx_session_destroy,
174         .start_conn             = qla4xxx_conn_start,
175         .create_conn            = qla4xxx_conn_create,
176         .bind_conn              = qla4xxx_conn_bind,
177         .stop_conn              = iscsi_conn_stop,
178         .destroy_conn           = qla4xxx_conn_destroy,
179         .set_param              = iscsi_set_param,
180         .get_conn_param         = qla4xxx_conn_get_param,
181         .get_session_param      = iscsi_session_get_param,
182         .get_ep_param           = qla4xxx_get_ep_param,
183         .ep_connect             = qla4xxx_ep_connect,
184         .ep_poll                = qla4xxx_ep_poll,
185         .ep_disconnect          = qla4xxx_ep_disconnect,
186         .get_stats              = qla4xxx_conn_get_stats,
187         .send_pdu               = iscsi_conn_send_pdu,
188         .xmit_task              = qla4xxx_task_xmit,
189         .cleanup_task           = qla4xxx_task_cleanup,
190         .alloc_pdu              = qla4xxx_alloc_pdu,
191
192         .get_host_param         = qla4xxx_host_get_param,
193         .set_iface_param        = qla4xxx_iface_set_param,
194         .get_iface_param        = qla4xxx_get_iface_param,
195         .bsg_request            = qla4xxx_bsg_request,
196 };
197
198 static struct scsi_transport_template *qla4xxx_scsi_transport;
199
200 static mode_t ql4_attr_is_visible(int param_type, int param)
201 {
202         switch (param_type) {
203         case ISCSI_HOST_PARAM:
204                 switch (param) {
205                 case ISCSI_HOST_PARAM_HWADDRESS:
206                 case ISCSI_HOST_PARAM_IPADDRESS:
207                 case ISCSI_HOST_PARAM_INITIATOR_NAME:
208                         return S_IRUGO;
209                 default:
210                         return 0;
211                 }
212         case ISCSI_PARAM:
213                 switch (param) {
214                 case ISCSI_PARAM_PERSISTENT_ADDRESS:
215                 case ISCSI_PARAM_PERSISTENT_PORT:
216                 case ISCSI_PARAM_CONN_ADDRESS:
217                 case ISCSI_PARAM_CONN_PORT:
218                 case ISCSI_PARAM_TARGET_NAME:
219                 case ISCSI_PARAM_TPGT:
220                 case ISCSI_PARAM_TARGET_ALIAS:
221                 case ISCSI_PARAM_MAX_BURST:
222                 case ISCSI_PARAM_MAX_R2T:
223                 case ISCSI_PARAM_FIRST_BURST:
224                 case ISCSI_PARAM_MAX_RECV_DLENGTH:
225                 case ISCSI_PARAM_MAX_XMIT_DLENGTH:
226                 case ISCSI_PARAM_IFACE_NAME:
227                         return S_IRUGO;
228                 default:
229                         return 0;
230                 }
231         case ISCSI_NET_PARAM:
232                 switch (param) {
233                 case ISCSI_NET_PARAM_IPV4_ADDR:
234                 case ISCSI_NET_PARAM_IPV4_SUBNET:
235                 case ISCSI_NET_PARAM_IPV4_GW:
236                 case ISCSI_NET_PARAM_IPV4_BOOTPROTO:
237                 case ISCSI_NET_PARAM_IFACE_ENABLE:
238                 case ISCSI_NET_PARAM_IPV6_LINKLOCAL:
239                 case ISCSI_NET_PARAM_IPV6_ADDR:
240                 case ISCSI_NET_PARAM_IPV6_ROUTER:
241                 case ISCSI_NET_PARAM_IPV6_ADDR_AUTOCFG:
242                 case ISCSI_NET_PARAM_IPV6_LINKLOCAL_AUTOCFG:
243                 case ISCSI_NET_PARAM_VLAN_ID:
244                 case ISCSI_NET_PARAM_VLAN_PRIORITY:
245                 case ISCSI_NET_PARAM_VLAN_ENABLED:
246                 case ISCSI_NET_PARAM_MTU:
247                 case ISCSI_NET_PARAM_PORT:
248                         return S_IRUGO;
249                 default:
250                         return 0;
251                 }
252         }
253
254         return 0;
255 }
256
257 static int qla4xxx_get_iface_param(struct iscsi_iface *iface,
258                                    enum iscsi_param_type param_type,
259                                    int param, char *buf)
260 {
261         struct Scsi_Host *shost = iscsi_iface_to_shost(iface);
262         struct scsi_qla_host *ha = to_qla_host(shost);
263         int len = -ENOSYS;
264
265         if (param_type != ISCSI_NET_PARAM)
266                 return -ENOSYS;
267
268         switch (param) {
269         case ISCSI_NET_PARAM_IPV4_ADDR:
270                 len = sprintf(buf, "%pI4\n", &ha->ip_config.ip_address);
271                 break;
272         case ISCSI_NET_PARAM_IPV4_SUBNET:
273                 len = sprintf(buf, "%pI4\n", &ha->ip_config.subnet_mask);
274                 break;
275         case ISCSI_NET_PARAM_IPV4_GW:
276                 len = sprintf(buf, "%pI4\n", &ha->ip_config.gateway);
277                 break;
278         case ISCSI_NET_PARAM_IFACE_ENABLE:
279                 if (iface->iface_type == ISCSI_IFACE_TYPE_IPV4)
280                         len = sprintf(buf, "%s\n",
281                                       (ha->ip_config.ipv4_options &
282                                        IPOPT_IPV4_PROTOCOL_ENABLE) ?
283                                       "enabled" : "disabled");
284                 else if (iface->iface_type == ISCSI_IFACE_TYPE_IPV6)
285                         len = sprintf(buf, "%s\n",
286                                       (ha->ip_config.ipv6_options &
287                                        IPV6_OPT_IPV6_PROTOCOL_ENABLE) ?
288                                        "enabled" : "disabled");
289                 break;
290         case ISCSI_NET_PARAM_IPV4_BOOTPROTO:
291                 len = sprintf(buf, "%s\n",
292                               (ha->ip_config.tcp_options & TCPOPT_DHCP_ENABLE) ?
293                               "dhcp" : "static");
294                 break;
295         case ISCSI_NET_PARAM_IPV6_ADDR:
296                 if (iface->iface_num == 0)
297                         len = sprintf(buf, "%pI6\n", &ha->ip_config.ipv6_addr0);
298                 if (iface->iface_num == 1)
299                         len = sprintf(buf, "%pI6\n", &ha->ip_config.ipv6_addr1);
300                 break;
301         case ISCSI_NET_PARAM_IPV6_LINKLOCAL:
302                 len = sprintf(buf, "%pI6\n",
303                               &ha->ip_config.ipv6_link_local_addr);
304                 break;
305         case ISCSI_NET_PARAM_IPV6_ROUTER:
306                 len = sprintf(buf, "%pI6\n",
307                               &ha->ip_config.ipv6_default_router_addr);
308                 break;
309         case ISCSI_NET_PARAM_IPV6_ADDR_AUTOCFG:
310                 len = sprintf(buf, "%s\n",
311                               (ha->ip_config.ipv6_addl_options &
312                                IPV6_ADDOPT_NEIGHBOR_DISCOVERY_ADDR_ENABLE) ?
313                                "nd" : "static");
314                 break;
315         case ISCSI_NET_PARAM_IPV6_LINKLOCAL_AUTOCFG:
316                 len = sprintf(buf, "%s\n",
317                               (ha->ip_config.ipv6_addl_options &
318                                IPV6_ADDOPT_AUTOCONFIG_LINK_LOCAL_ADDR) ?
319                                "auto" : "static");
320                 break;
321         case ISCSI_NET_PARAM_VLAN_ID:
322                 if (iface->iface_type == ISCSI_IFACE_TYPE_IPV4)
323                         len = sprintf(buf, "%d\n",
324                                       (ha->ip_config.ipv4_vlan_tag &
325                                        ISCSI_MAX_VLAN_ID));
326                 else if (iface->iface_type == ISCSI_IFACE_TYPE_IPV6)
327                         len = sprintf(buf, "%d\n",
328                                       (ha->ip_config.ipv6_vlan_tag &
329                                        ISCSI_MAX_VLAN_ID));
330                 break;
331         case ISCSI_NET_PARAM_VLAN_PRIORITY:
332                 if (iface->iface_type == ISCSI_IFACE_TYPE_IPV4)
333                         len = sprintf(buf, "%d\n",
334                                       ((ha->ip_config.ipv4_vlan_tag >> 13) &
335                                         ISCSI_MAX_VLAN_PRIORITY));
336                 else if (iface->iface_type == ISCSI_IFACE_TYPE_IPV6)
337                         len = sprintf(buf, "%d\n",
338                                       ((ha->ip_config.ipv6_vlan_tag >> 13) &
339                                         ISCSI_MAX_VLAN_PRIORITY));
340                 break;
341         case ISCSI_NET_PARAM_VLAN_ENABLED:
342                 if (iface->iface_type == ISCSI_IFACE_TYPE_IPV4)
343                         len = sprintf(buf, "%s\n",
344                                       (ha->ip_config.ipv4_options &
345                                        IPOPT_VLAN_TAGGING_ENABLE) ?
346                                        "enabled" : "disabled");
347                 else if (iface->iface_type == ISCSI_IFACE_TYPE_IPV6)
348                         len = sprintf(buf, "%s\n",
349                                       (ha->ip_config.ipv6_options &
350                                        IPV6_OPT_VLAN_TAGGING_ENABLE) ?
351                                        "enabled" : "disabled");
352                 break;
353         case ISCSI_NET_PARAM_MTU:
354                 len = sprintf(buf, "%d\n", ha->ip_config.eth_mtu_size);
355                 break;
356         case ISCSI_NET_PARAM_PORT:
357                 if (iface->iface_type == ISCSI_IFACE_TYPE_IPV4)
358                         len = sprintf(buf, "%d\n", ha->ip_config.ipv4_port);
359                 else if (iface->iface_type == ISCSI_IFACE_TYPE_IPV6)
360                         len = sprintf(buf, "%d\n", ha->ip_config.ipv6_port);
361                 break;
362         default:
363                 len = -ENOSYS;
364         }
365
366         return len;
367 }
368
369 static struct iscsi_endpoint *
370 qla4xxx_ep_connect(struct Scsi_Host *shost, struct sockaddr *dst_addr,
371                    int non_blocking)
372 {
373         int ret;
374         struct iscsi_endpoint *ep;
375         struct qla_endpoint *qla_ep;
376         struct scsi_qla_host *ha;
377         struct sockaddr_in *addr;
378         struct sockaddr_in6 *addr6;
379
380         DEBUG2(printk(KERN_INFO "Func: %s\n", __func__));
381         if (!shost) {
382                 ret = -ENXIO;
383                 printk(KERN_ERR "%s: shost is NULL\n",
384                        __func__);
385                 return ERR_PTR(ret);
386         }
387
388         ha = iscsi_host_priv(shost);
389
390         ep = iscsi_create_endpoint(sizeof(struct qla_endpoint));
391         if (!ep) {
392                 ret = -ENOMEM;
393                 return ERR_PTR(ret);
394         }
395
396         qla_ep = ep->dd_data;
397         memset(qla_ep, 0, sizeof(struct qla_endpoint));
398         if (dst_addr->sa_family == AF_INET) {
399                 memcpy(&qla_ep->dst_addr, dst_addr, sizeof(struct sockaddr_in));
400                 addr = (struct sockaddr_in *)&qla_ep->dst_addr;
401                 DEBUG2(ql4_printk(KERN_INFO, ha, "%s: %pI4\n", __func__,
402                                   (char *)&addr->sin_addr));
403         } else if (dst_addr->sa_family == AF_INET6) {
404                 memcpy(&qla_ep->dst_addr, dst_addr,
405                        sizeof(struct sockaddr_in6));
406                 addr6 = (struct sockaddr_in6 *)&qla_ep->dst_addr;
407                 DEBUG2(ql4_printk(KERN_INFO, ha, "%s: %pI6\n", __func__,
408                                   (char *)&addr6->sin6_addr));
409         }
410
411         qla_ep->host = shost;
412
413         return ep;
414 }
415
416 static int qla4xxx_ep_poll(struct iscsi_endpoint *ep, int timeout_ms)
417 {
418         struct qla_endpoint *qla_ep;
419         struct scsi_qla_host *ha;
420         int ret = 0;
421
422         DEBUG2(printk(KERN_INFO "Func: %s\n", __func__));
423         qla_ep = ep->dd_data;
424         ha = to_qla_host(qla_ep->host);
425
426         if (adapter_up(ha) && !test_bit(AF_BUILD_DDB_LIST, &ha->flags))
427                 ret = 1;
428
429         return ret;
430 }
431
432 static void qla4xxx_ep_disconnect(struct iscsi_endpoint *ep)
433 {
434         DEBUG2(printk(KERN_INFO "Func: %s\n", __func__));
435         iscsi_destroy_endpoint(ep);
436 }
437
438 static int qla4xxx_get_ep_param(struct iscsi_endpoint *ep,
439                                 enum iscsi_param param,
440                                 char *buf)
441 {
442         struct qla_endpoint *qla_ep = ep->dd_data;
443         struct sockaddr *dst_addr;
444
445         DEBUG2(printk(KERN_INFO "Func: %s\n", __func__));
446
447         switch (param) {
448         case ISCSI_PARAM_CONN_PORT:
449         case ISCSI_PARAM_CONN_ADDRESS:
450                 if (!qla_ep)
451                         return -ENOTCONN;
452
453                 dst_addr = (struct sockaddr *)&qla_ep->dst_addr;
454                 if (!dst_addr)
455                         return -ENOTCONN;
456
457                 return iscsi_conn_get_addr_param((struct sockaddr_storage *)
458                                                  &qla_ep->dst_addr, param, buf);
459         default:
460                 return -ENOSYS;
461         }
462 }
463
464 static void qla4xxx_conn_get_stats(struct iscsi_cls_conn *cls_conn,
465                                    struct iscsi_stats *stats)
466 {
467         struct iscsi_session *sess;
468         struct iscsi_cls_session *cls_sess;
469         struct ddb_entry *ddb_entry;
470         struct scsi_qla_host *ha;
471         struct ql_iscsi_stats *ql_iscsi_stats;
472         int stats_size;
473         int ret;
474         dma_addr_t iscsi_stats_dma;
475
476         DEBUG2(printk(KERN_INFO "Func: %s\n", __func__));
477
478         cls_sess = iscsi_conn_to_session(cls_conn);
479         sess = cls_sess->dd_data;
480         ddb_entry = sess->dd_data;
481         ha = ddb_entry->ha;
482
483         stats_size = PAGE_ALIGN(sizeof(struct ql_iscsi_stats));
484         /* Allocate memory */
485         ql_iscsi_stats = dma_alloc_coherent(&ha->pdev->dev, stats_size,
486                                             &iscsi_stats_dma, GFP_KERNEL);
487         if (!ql_iscsi_stats) {
488                 ql4_printk(KERN_ERR, ha,
489                            "Unable to allocate memory for iscsi stats\n");
490                 goto exit_get_stats;
491         }
492
493         ret =  qla4xxx_get_mgmt_data(ha, ddb_entry->fw_ddb_index, stats_size,
494                                      iscsi_stats_dma);
495         if (ret != QLA_SUCCESS) {
496                 ql4_printk(KERN_ERR, ha,
497                            "Unable to retreive iscsi stats\n");
498                 goto free_stats;
499         }
500
501         /* octets */
502         stats->txdata_octets = le64_to_cpu(ql_iscsi_stats->tx_data_octets);
503         stats->rxdata_octets = le64_to_cpu(ql_iscsi_stats->rx_data_octets);
504         /* xmit pdus */
505         stats->noptx_pdus = le32_to_cpu(ql_iscsi_stats->tx_nopout_pdus);
506         stats->scsicmd_pdus = le32_to_cpu(ql_iscsi_stats->tx_scsi_cmd_pdus);
507         stats->tmfcmd_pdus = le32_to_cpu(ql_iscsi_stats->tx_tmf_cmd_pdus);
508         stats->login_pdus = le32_to_cpu(ql_iscsi_stats->tx_login_cmd_pdus);
509         stats->text_pdus = le32_to_cpu(ql_iscsi_stats->tx_text_cmd_pdus);
510         stats->dataout_pdus = le32_to_cpu(ql_iscsi_stats->tx_scsi_write_pdus);
511         stats->logout_pdus = le32_to_cpu(ql_iscsi_stats->tx_logout_cmd_pdus);
512         stats->snack_pdus = le32_to_cpu(ql_iscsi_stats->tx_snack_req_pdus);
513         /* recv pdus */
514         stats->noprx_pdus = le32_to_cpu(ql_iscsi_stats->rx_nopin_pdus);
515         stats->scsirsp_pdus = le32_to_cpu(ql_iscsi_stats->rx_scsi_resp_pdus);
516         stats->tmfrsp_pdus = le32_to_cpu(ql_iscsi_stats->rx_tmf_resp_pdus);
517         stats->textrsp_pdus = le32_to_cpu(ql_iscsi_stats->rx_text_resp_pdus);
518         stats->datain_pdus = le32_to_cpu(ql_iscsi_stats->rx_scsi_read_pdus);
519         stats->logoutrsp_pdus =
520                         le32_to_cpu(ql_iscsi_stats->rx_logout_resp_pdus);
521         stats->r2t_pdus = le32_to_cpu(ql_iscsi_stats->rx_r2t_pdus);
522         stats->async_pdus = le32_to_cpu(ql_iscsi_stats->rx_async_pdus);
523         stats->rjt_pdus = le32_to_cpu(ql_iscsi_stats->rx_reject_pdus);
524
525 free_stats:
526         dma_free_coherent(&ha->pdev->dev, stats_size, ql_iscsi_stats,
527                           iscsi_stats_dma);
528 exit_get_stats:
529         return;
530 }
531
532 static enum blk_eh_timer_return qla4xxx_eh_cmd_timed_out(struct scsi_cmnd *sc)
533 {
534         struct iscsi_cls_session *session;
535         struct iscsi_session *sess;
536         unsigned long flags;
537         enum blk_eh_timer_return ret = BLK_EH_NOT_HANDLED;
538
539         session = starget_to_session(scsi_target(sc->device));
540         sess = session->dd_data;
541
542         spin_lock_irqsave(&session->lock, flags);
543         if (session->state == ISCSI_SESSION_FAILED)
544                 ret = BLK_EH_RESET_TIMER;
545         spin_unlock_irqrestore(&session->lock, flags);
546
547         return ret;
548 }
549
550 static int qla4xxx_host_get_param(struct Scsi_Host *shost,
551                                   enum iscsi_host_param param, char *buf)
552 {
553         struct scsi_qla_host *ha = to_qla_host(shost);
554         int len;
555
556         switch (param) {
557         case ISCSI_HOST_PARAM_HWADDRESS:
558                 len = sysfs_format_mac(buf, ha->my_mac, MAC_ADDR_LEN);
559                 break;
560         case ISCSI_HOST_PARAM_IPADDRESS:
561                 len = sprintf(buf, "%pI4\n", &ha->ip_config.ip_address);
562                 break;
563         case ISCSI_HOST_PARAM_INITIATOR_NAME:
564                 len = sprintf(buf, "%s\n", ha->name_string);
565                 break;
566         default:
567                 return -ENOSYS;
568         }
569
570         return len;
571 }
572
573 static void qla4xxx_create_ipv4_iface(struct scsi_qla_host *ha)
574 {
575         if (ha->iface_ipv4)
576                 return;
577
578         /* IPv4 */
579         ha->iface_ipv4 = iscsi_create_iface(ha->host,
580                                             &qla4xxx_iscsi_transport,
581                                             ISCSI_IFACE_TYPE_IPV4, 0, 0);
582         if (!ha->iface_ipv4)
583                 ql4_printk(KERN_ERR, ha, "Could not create IPv4 iSCSI "
584                            "iface0.\n");
585 }
586
587 static void qla4xxx_create_ipv6_iface(struct scsi_qla_host *ha)
588 {
589         if (!ha->iface_ipv6_0)
590                 /* IPv6 iface-0 */
591                 ha->iface_ipv6_0 = iscsi_create_iface(ha->host,
592                                                       &qla4xxx_iscsi_transport,
593                                                       ISCSI_IFACE_TYPE_IPV6, 0,
594                                                       0);
595         if (!ha->iface_ipv6_0)
596                 ql4_printk(KERN_ERR, ha, "Could not create IPv6 iSCSI "
597                            "iface0.\n");
598
599         if (!ha->iface_ipv6_1)
600                 /* IPv6 iface-1 */
601                 ha->iface_ipv6_1 = iscsi_create_iface(ha->host,
602                                                       &qla4xxx_iscsi_transport,
603                                                       ISCSI_IFACE_TYPE_IPV6, 1,
604                                                       0);
605         if (!ha->iface_ipv6_1)
606                 ql4_printk(KERN_ERR, ha, "Could not create IPv6 iSCSI "
607                            "iface1.\n");
608 }
609
610 static void qla4xxx_create_ifaces(struct scsi_qla_host *ha)
611 {
612         if (ha->ip_config.ipv4_options & IPOPT_IPV4_PROTOCOL_ENABLE)
613                 qla4xxx_create_ipv4_iface(ha);
614
615         if (ha->ip_config.ipv6_options & IPV6_OPT_IPV6_PROTOCOL_ENABLE)
616                 qla4xxx_create_ipv6_iface(ha);
617 }
618
619 static void qla4xxx_destroy_ipv4_iface(struct scsi_qla_host *ha)
620 {
621         if (ha->iface_ipv4) {
622                 iscsi_destroy_iface(ha->iface_ipv4);
623                 ha->iface_ipv4 = NULL;
624         }
625 }
626
627 static void qla4xxx_destroy_ipv6_iface(struct scsi_qla_host *ha)
628 {
629         if (ha->iface_ipv6_0) {
630                 iscsi_destroy_iface(ha->iface_ipv6_0);
631                 ha->iface_ipv6_0 = NULL;
632         }
633         if (ha->iface_ipv6_1) {
634                 iscsi_destroy_iface(ha->iface_ipv6_1);
635                 ha->iface_ipv6_1 = NULL;
636         }
637 }
638
639 static void qla4xxx_destroy_ifaces(struct scsi_qla_host *ha)
640 {
641         qla4xxx_destroy_ipv4_iface(ha);
642         qla4xxx_destroy_ipv6_iface(ha);
643 }
644
645 static void qla4xxx_set_ipv6(struct scsi_qla_host *ha,
646                              struct iscsi_iface_param_info *iface_param,
647                              struct addr_ctrl_blk *init_fw_cb)
648 {
649         /*
650          * iface_num 0 is valid for IPv6 Addr, linklocal, router, autocfg.
651          * iface_num 1 is valid only for IPv6 Addr.
652          */
653         switch (iface_param->param) {
654         case ISCSI_NET_PARAM_IPV6_ADDR:
655                 if (iface_param->iface_num & 0x1)
656                         /* IPv6 Addr 1 */
657                         memcpy(init_fw_cb->ipv6_addr1, iface_param->value,
658                                sizeof(init_fw_cb->ipv6_addr1));
659                 else
660                         /* IPv6 Addr 0 */
661                         memcpy(init_fw_cb->ipv6_addr0, iface_param->value,
662                                sizeof(init_fw_cb->ipv6_addr0));
663                 break;
664         case ISCSI_NET_PARAM_IPV6_LINKLOCAL:
665                 if (iface_param->iface_num & 0x1)
666                         break;
667                 memcpy(init_fw_cb->ipv6_if_id, &iface_param->value[8],
668                        sizeof(init_fw_cb->ipv6_if_id));
669                 break;
670         case ISCSI_NET_PARAM_IPV6_ROUTER:
671                 if (iface_param->iface_num & 0x1)
672                         break;
673                 memcpy(init_fw_cb->ipv6_dflt_rtr_addr, iface_param->value,
674                        sizeof(init_fw_cb->ipv6_dflt_rtr_addr));
675                 break;
676         case ISCSI_NET_PARAM_IPV6_ADDR_AUTOCFG:
677                 /* Autocfg applies to even interface */
678                 if (iface_param->iface_num & 0x1)
679                         break;
680
681                 if (iface_param->value[0] == ISCSI_IPV6_AUTOCFG_DISABLE)
682                         init_fw_cb->ipv6_addtl_opts &=
683                                 cpu_to_le16(
684                                   ~IPV6_ADDOPT_NEIGHBOR_DISCOVERY_ADDR_ENABLE);
685                 else if (iface_param->value[0] == ISCSI_IPV6_AUTOCFG_ND_ENABLE)
686                         init_fw_cb->ipv6_addtl_opts |=
687                                 cpu_to_le16(
688                                   IPV6_ADDOPT_NEIGHBOR_DISCOVERY_ADDR_ENABLE);
689                 else
690                         ql4_printk(KERN_ERR, ha, "Invalid autocfg setting for "
691                                    "IPv6 addr\n");
692                 break;
693         case ISCSI_NET_PARAM_IPV6_LINKLOCAL_AUTOCFG:
694                 /* Autocfg applies to even interface */
695                 if (iface_param->iface_num & 0x1)
696                         break;
697
698                 if (iface_param->value[0] ==
699                     ISCSI_IPV6_LINKLOCAL_AUTOCFG_ENABLE)
700                         init_fw_cb->ipv6_addtl_opts |= cpu_to_le16(
701                                         IPV6_ADDOPT_AUTOCONFIG_LINK_LOCAL_ADDR);
702                 else if (iface_param->value[0] ==
703                          ISCSI_IPV6_LINKLOCAL_AUTOCFG_DISABLE)
704                         init_fw_cb->ipv6_addtl_opts &= cpu_to_le16(
705                                        ~IPV6_ADDOPT_AUTOCONFIG_LINK_LOCAL_ADDR);
706                 else
707                         ql4_printk(KERN_ERR, ha, "Invalid autocfg setting for "
708                                    "IPv6 linklocal addr\n");
709                 break;
710         case ISCSI_NET_PARAM_IPV6_ROUTER_AUTOCFG:
711                 /* Autocfg applies to even interface */
712                 if (iface_param->iface_num & 0x1)
713                         break;
714
715                 if (iface_param->value[0] == ISCSI_IPV6_ROUTER_AUTOCFG_ENABLE)
716                         memset(init_fw_cb->ipv6_dflt_rtr_addr, 0,
717                                sizeof(init_fw_cb->ipv6_dflt_rtr_addr));
718                 break;
719         case ISCSI_NET_PARAM_IFACE_ENABLE:
720                 if (iface_param->value[0] == ISCSI_IFACE_ENABLE) {
721                         init_fw_cb->ipv6_opts |=
722                                 cpu_to_le16(IPV6_OPT_IPV6_PROTOCOL_ENABLE);
723                         qla4xxx_create_ipv6_iface(ha);
724                 } else {
725                         init_fw_cb->ipv6_opts &=
726                                 cpu_to_le16(~IPV6_OPT_IPV6_PROTOCOL_ENABLE &
727                                             0xFFFF);
728                         qla4xxx_destroy_ipv6_iface(ha);
729                 }
730                 break;
731         case ISCSI_NET_PARAM_VLAN_TAG:
732                 if (iface_param->len != sizeof(init_fw_cb->ipv6_vlan_tag))
733                         break;
734                 init_fw_cb->ipv6_vlan_tag =
735                                 cpu_to_be16(*(uint16_t *)iface_param->value);
736                 break;
737         case ISCSI_NET_PARAM_VLAN_ENABLED:
738                 if (iface_param->value[0] == ISCSI_VLAN_ENABLE)
739                         init_fw_cb->ipv6_opts |=
740                                 cpu_to_le16(IPV6_OPT_VLAN_TAGGING_ENABLE);
741                 else
742                         init_fw_cb->ipv6_opts &=
743                                 cpu_to_le16(~IPV6_OPT_VLAN_TAGGING_ENABLE);
744                 break;
745         case ISCSI_NET_PARAM_MTU:
746                 init_fw_cb->eth_mtu_size =
747                                 cpu_to_le16(*(uint16_t *)iface_param->value);
748                 break;
749         case ISCSI_NET_PARAM_PORT:
750                 /* Autocfg applies to even interface */
751                 if (iface_param->iface_num & 0x1)
752                         break;
753
754                 init_fw_cb->ipv6_port =
755                                 cpu_to_le16(*(uint16_t *)iface_param->value);
756                 break;
757         default:
758                 ql4_printk(KERN_ERR, ha, "Unknown IPv6 param = %d\n",
759                            iface_param->param);
760                 break;
761         }
762 }
763
764 static void qla4xxx_set_ipv4(struct scsi_qla_host *ha,
765                              struct iscsi_iface_param_info *iface_param,
766                              struct addr_ctrl_blk *init_fw_cb)
767 {
768         switch (iface_param->param) {
769         case ISCSI_NET_PARAM_IPV4_ADDR:
770                 memcpy(init_fw_cb->ipv4_addr, iface_param->value,
771                        sizeof(init_fw_cb->ipv4_addr));
772                 break;
773         case ISCSI_NET_PARAM_IPV4_SUBNET:
774                 memcpy(init_fw_cb->ipv4_subnet, iface_param->value,
775                        sizeof(init_fw_cb->ipv4_subnet));
776                 break;
777         case ISCSI_NET_PARAM_IPV4_GW:
778                 memcpy(init_fw_cb->ipv4_gw_addr, iface_param->value,
779                        sizeof(init_fw_cb->ipv4_gw_addr));
780                 break;
781         case ISCSI_NET_PARAM_IPV4_BOOTPROTO:
782                 if (iface_param->value[0] == ISCSI_BOOTPROTO_DHCP)
783                         init_fw_cb->ipv4_tcp_opts |=
784                                         cpu_to_le16(TCPOPT_DHCP_ENABLE);
785                 else if (iface_param->value[0] == ISCSI_BOOTPROTO_STATIC)
786                         init_fw_cb->ipv4_tcp_opts &=
787                                         cpu_to_le16(~TCPOPT_DHCP_ENABLE);
788                 else
789                         ql4_printk(KERN_ERR, ha, "Invalid IPv4 bootproto\n");
790                 break;
791         case ISCSI_NET_PARAM_IFACE_ENABLE:
792                 if (iface_param->value[0] == ISCSI_IFACE_ENABLE) {
793                         init_fw_cb->ipv4_ip_opts |=
794                                 cpu_to_le16(IPOPT_IPV4_PROTOCOL_ENABLE);
795                         qla4xxx_create_ipv4_iface(ha);
796                 } else {
797                         init_fw_cb->ipv4_ip_opts &=
798                                 cpu_to_le16(~IPOPT_IPV4_PROTOCOL_ENABLE &
799                                             0xFFFF);
800                         qla4xxx_destroy_ipv4_iface(ha);
801                 }
802                 break;
803         case ISCSI_NET_PARAM_VLAN_TAG:
804                 if (iface_param->len != sizeof(init_fw_cb->ipv4_vlan_tag))
805                         break;
806                 init_fw_cb->ipv4_vlan_tag =
807                                 cpu_to_be16(*(uint16_t *)iface_param->value);
808                 break;
809         case ISCSI_NET_PARAM_VLAN_ENABLED:
810                 if (iface_param->value[0] == ISCSI_VLAN_ENABLE)
811                         init_fw_cb->ipv4_ip_opts |=
812                                         cpu_to_le16(IPOPT_VLAN_TAGGING_ENABLE);
813                 else
814                         init_fw_cb->ipv4_ip_opts &=
815                                         cpu_to_le16(~IPOPT_VLAN_TAGGING_ENABLE);
816                 break;
817         case ISCSI_NET_PARAM_MTU:
818                 init_fw_cb->eth_mtu_size =
819                                 cpu_to_le16(*(uint16_t *)iface_param->value);
820                 break;
821         case ISCSI_NET_PARAM_PORT:
822                 init_fw_cb->ipv4_port =
823                                 cpu_to_le16(*(uint16_t *)iface_param->value);
824                 break;
825         default:
826                 ql4_printk(KERN_ERR, ha, "Unknown IPv4 param = %d\n",
827                            iface_param->param);
828                 break;
829         }
830 }
831
832 static void
833 qla4xxx_initcb_to_acb(struct addr_ctrl_blk *init_fw_cb)
834 {
835         struct addr_ctrl_blk_def *acb;
836         acb = (struct addr_ctrl_blk_def *)init_fw_cb;
837         memset(acb->reserved1, 0, sizeof(acb->reserved1));
838         memset(acb->reserved2, 0, sizeof(acb->reserved2));
839         memset(acb->reserved3, 0, sizeof(acb->reserved3));
840         memset(acb->reserved4, 0, sizeof(acb->reserved4));
841         memset(acb->reserved5, 0, sizeof(acb->reserved5));
842         memset(acb->reserved6, 0, sizeof(acb->reserved6));
843         memset(acb->reserved7, 0, sizeof(acb->reserved7));
844         memset(acb->reserved8, 0, sizeof(acb->reserved8));
845         memset(acb->reserved9, 0, sizeof(acb->reserved9));
846         memset(acb->reserved10, 0, sizeof(acb->reserved10));
847         memset(acb->reserved11, 0, sizeof(acb->reserved11));
848         memset(acb->reserved12, 0, sizeof(acb->reserved12));
849         memset(acb->reserved13, 0, sizeof(acb->reserved13));
850         memset(acb->reserved14, 0, sizeof(acb->reserved14));
851         memset(acb->reserved15, 0, sizeof(acb->reserved15));
852 }
853
854 static int
855 qla4xxx_iface_set_param(struct Scsi_Host *shost, void *data, uint32_t len)
856 {
857         struct scsi_qla_host *ha = to_qla_host(shost);
858         int rval = 0;
859         struct iscsi_iface_param_info *iface_param = NULL;
860         struct addr_ctrl_blk *init_fw_cb = NULL;
861         dma_addr_t init_fw_cb_dma;
862         uint32_t mbox_cmd[MBOX_REG_COUNT];
863         uint32_t mbox_sts[MBOX_REG_COUNT];
864         uint32_t rem = len;
865         struct nlattr *attr;
866
867         init_fw_cb = dma_alloc_coherent(&ha->pdev->dev,
868                                         sizeof(struct addr_ctrl_blk),
869                                         &init_fw_cb_dma, GFP_KERNEL);
870         if (!init_fw_cb) {
871                 ql4_printk(KERN_ERR, ha, "%s: Unable to alloc init_cb\n",
872                            __func__);
873                 return -ENOMEM;
874         }
875
876         memset(init_fw_cb, 0, sizeof(struct addr_ctrl_blk));
877         memset(&mbox_cmd, 0, sizeof(mbox_cmd));
878         memset(&mbox_sts, 0, sizeof(mbox_sts));
879
880         if (qla4xxx_get_ifcb(ha, &mbox_cmd[0], &mbox_sts[0], init_fw_cb_dma)) {
881                 ql4_printk(KERN_ERR, ha, "%s: get ifcb failed\n", __func__);
882                 rval = -EIO;
883                 goto exit_init_fw_cb;
884         }
885
886         nla_for_each_attr(attr, data, len, rem) {
887                 iface_param = nla_data(attr);
888
889                 if (iface_param->param_type != ISCSI_NET_PARAM)
890                         continue;
891
892                 switch (iface_param->iface_type) {
893                 case ISCSI_IFACE_TYPE_IPV4:
894                         switch (iface_param->iface_num) {
895                         case 0:
896                                 qla4xxx_set_ipv4(ha, iface_param, init_fw_cb);
897                                 break;
898                         default:
899                                 /* Cannot have more than one IPv4 interface */
900                                 ql4_printk(KERN_ERR, ha, "Invalid IPv4 iface "
901                                            "number = %d\n",
902                                            iface_param->iface_num);
903                                 break;
904                         }
905                         break;
906                 case ISCSI_IFACE_TYPE_IPV6:
907                         switch (iface_param->iface_num) {
908                         case 0:
909                         case 1:
910                                 qla4xxx_set_ipv6(ha, iface_param, init_fw_cb);
911                                 break;
912                         default:
913                                 /* Cannot have more than two IPv6 interface */
914                                 ql4_printk(KERN_ERR, ha, "Invalid IPv6 iface "
915                                            "number = %d\n",
916                                            iface_param->iface_num);
917                                 break;
918                         }
919                         break;
920                 default:
921                         ql4_printk(KERN_ERR, ha, "Invalid iface type\n");
922                         break;
923                 }
924         }
925
926         init_fw_cb->cookie = cpu_to_le32(0x11BEAD5A);
927
928         rval = qla4xxx_set_flash(ha, init_fw_cb_dma, FLASH_SEGMENT_IFCB,
929                                  sizeof(struct addr_ctrl_blk),
930                                  FLASH_OPT_RMW_COMMIT);
931         if (rval != QLA_SUCCESS) {
932                 ql4_printk(KERN_ERR, ha, "%s: set flash mbx failed\n",
933                            __func__);
934                 rval = -EIO;
935                 goto exit_init_fw_cb;
936         }
937
938         qla4xxx_disable_acb(ha);
939
940         qla4xxx_initcb_to_acb(init_fw_cb);
941
942         rval = qla4xxx_set_acb(ha, &mbox_cmd[0], &mbox_sts[0], init_fw_cb_dma);
943         if (rval != QLA_SUCCESS) {
944                 ql4_printk(KERN_ERR, ha, "%s: set acb mbx failed\n",
945                            __func__);
946                 rval = -EIO;
947                 goto exit_init_fw_cb;
948         }
949
950         memset(init_fw_cb, 0, sizeof(struct addr_ctrl_blk));
951         qla4xxx_update_local_ifcb(ha, &mbox_cmd[0], &mbox_sts[0], init_fw_cb,
952                                   init_fw_cb_dma);
953
954 exit_init_fw_cb:
955         dma_free_coherent(&ha->pdev->dev, sizeof(struct addr_ctrl_blk),
956                           init_fw_cb, init_fw_cb_dma);
957
958         return rval;
959 }
960
961 static int qla4xxx_conn_get_param(struct iscsi_cls_conn *cls_conn,
962                                   enum iscsi_param param, char *buf)
963 {
964         struct iscsi_conn *conn;
965         struct qla_conn *qla_conn;
966         struct sockaddr *dst_addr;
967         int len = 0;
968
969         conn = cls_conn->dd_data;
970         qla_conn = conn->dd_data;
971         dst_addr = &qla_conn->qla_ep->dst_addr;
972
973         switch (param) {
974         case ISCSI_PARAM_CONN_PORT:
975         case ISCSI_PARAM_CONN_ADDRESS:
976                 return iscsi_conn_get_addr_param((struct sockaddr_storage *)
977                                                  dst_addr, param, buf);
978         default:
979                 return iscsi_conn_get_param(cls_conn, param, buf);
980         }
981
982         return len;
983
984 }
985
986 int qla4xxx_get_ddb_index(struct scsi_qla_host *ha, uint16_t *ddb_index)
987 {
988         uint32_t mbx_sts = 0;
989         uint16_t tmp_ddb_index;
990         int ret;
991
992 get_ddb_index:
993         tmp_ddb_index = find_first_zero_bit(ha->ddb_idx_map, MAX_DDB_ENTRIES);
994
995         if (tmp_ddb_index >= MAX_DDB_ENTRIES) {
996                 DEBUG2(ql4_printk(KERN_INFO, ha,
997                                   "Free DDB index not available\n"));
998                 ret = QLA_ERROR;
999                 goto exit_get_ddb_index;
1000         }
1001
1002         if (test_and_set_bit(tmp_ddb_index, ha->ddb_idx_map))
1003                 goto get_ddb_index;
1004
1005         DEBUG2(ql4_printk(KERN_INFO, ha,
1006                           "Found a free DDB index at %d\n", tmp_ddb_index));
1007         ret = qla4xxx_req_ddb_entry(ha, tmp_ddb_index, &mbx_sts);
1008         if (ret == QLA_ERROR) {
1009                 if (mbx_sts == MBOX_STS_COMMAND_ERROR) {
1010                         ql4_printk(KERN_INFO, ha,
1011                                    "DDB index = %d not available trying next\n",
1012                                    tmp_ddb_index);
1013                         goto get_ddb_index;
1014                 }
1015                 DEBUG2(ql4_printk(KERN_INFO, ha,
1016                                   "Free FW DDB not available\n"));
1017         }
1018
1019         *ddb_index = tmp_ddb_index;
1020
1021 exit_get_ddb_index:
1022         return ret;
1023 }
1024
1025 static int qla4xxx_match_ipaddress(struct scsi_qla_host *ha,
1026                                    struct ddb_entry *ddb_entry,
1027                                    char *existing_ipaddr,
1028                                    char *user_ipaddr)
1029 {
1030         uint8_t dst_ipaddr[IPv6_ADDR_LEN];
1031         char formatted_ipaddr[DDB_IPADDR_LEN];
1032         int status = QLA_SUCCESS, ret = 0;
1033
1034         if (ddb_entry->fw_ddb_entry.options & DDB_OPT_IPV6_DEVICE) {
1035                 ret = in6_pton(user_ipaddr, strlen(user_ipaddr), dst_ipaddr,
1036                                '\0', NULL);
1037                 if (ret == 0) {
1038                         status = QLA_ERROR;
1039                         goto out_match;
1040                 }
1041                 ret = sprintf(formatted_ipaddr, "%pI6", dst_ipaddr);
1042         } else {
1043                 ret = in4_pton(user_ipaddr, strlen(user_ipaddr), dst_ipaddr,
1044                                '\0', NULL);
1045                 if (ret == 0) {
1046                         status = QLA_ERROR;
1047                         goto out_match;
1048                 }
1049                 ret = sprintf(formatted_ipaddr, "%pI4", dst_ipaddr);
1050         }
1051
1052         if (strcmp(existing_ipaddr, formatted_ipaddr))
1053                 status = QLA_ERROR;
1054
1055 out_match:
1056         return status;
1057 }
1058
1059 static int qla4xxx_match_fwdb_session(struct scsi_qla_host *ha,
1060                                       struct iscsi_cls_conn *cls_conn)
1061 {
1062         int idx = 0, max_ddbs, rval;
1063         struct iscsi_cls_session *cls_sess = iscsi_conn_to_session(cls_conn);
1064         struct iscsi_session *sess, *existing_sess;
1065         struct iscsi_conn *conn, *existing_conn;
1066         struct ddb_entry *ddb_entry;
1067
1068         sess = cls_sess->dd_data;
1069         conn = cls_conn->dd_data;
1070
1071         if (sess->targetname == NULL ||
1072             conn->persistent_address == NULL ||
1073             conn->persistent_port == 0)
1074                 return QLA_ERROR;
1075
1076         max_ddbs =  is_qla40XX(ha) ? MAX_DEV_DB_ENTRIES_40XX :
1077                                      MAX_DEV_DB_ENTRIES;
1078
1079         for (idx = 0; idx < max_ddbs; idx++) {
1080                 ddb_entry = qla4xxx_lookup_ddb_by_fw_index(ha, idx);
1081                 if (ddb_entry == NULL)
1082                         continue;
1083
1084                 if (ddb_entry->ddb_type != FLASH_DDB)
1085                         continue;
1086
1087                 existing_sess = ddb_entry->sess->dd_data;
1088                 existing_conn = ddb_entry->conn->dd_data;
1089
1090                 if (existing_sess->targetname == NULL ||
1091                     existing_conn->persistent_address == NULL ||
1092                     existing_conn->persistent_port == 0)
1093                         continue;
1094
1095                 DEBUG2(ql4_printk(KERN_INFO, ha,
1096                                   "IQN = %s User IQN = %s\n",
1097                                   existing_sess->targetname,
1098                                   sess->targetname));
1099
1100                 DEBUG2(ql4_printk(KERN_INFO, ha,
1101                                   "IP = %s User IP = %s\n",
1102                                   existing_conn->persistent_address,
1103                                   conn->persistent_address));
1104
1105                 DEBUG2(ql4_printk(KERN_INFO, ha,
1106                                   "Port = %d User Port = %d\n",
1107                                   existing_conn->persistent_port,
1108                                   conn->persistent_port));
1109
1110                 if (strcmp(existing_sess->targetname, sess->targetname))
1111                         continue;
1112                 rval = qla4xxx_match_ipaddress(ha, ddb_entry,
1113                                         existing_conn->persistent_address,
1114                                         conn->persistent_address);
1115                 if (rval == QLA_ERROR)
1116                         continue;
1117                 if (existing_conn->persistent_port != conn->persistent_port)
1118                         continue;
1119                 break;
1120         }
1121
1122         if (idx == max_ddbs)
1123                 return QLA_ERROR;
1124
1125         DEBUG2(ql4_printk(KERN_INFO, ha,
1126                           "Match found in fwdb sessions\n"));
1127         return QLA_SUCCESS;
1128 }
1129
1130 static struct iscsi_cls_session *
1131 qla4xxx_session_create(struct iscsi_endpoint *ep,
1132                         uint16_t cmds_max, uint16_t qdepth,
1133                         uint32_t initial_cmdsn)
1134 {
1135         struct iscsi_cls_session *cls_sess;
1136         struct scsi_qla_host *ha;
1137         struct qla_endpoint *qla_ep;
1138         struct ddb_entry *ddb_entry;
1139         uint16_t ddb_index;
1140         struct iscsi_session *sess;
1141         struct sockaddr *dst_addr;
1142         int ret;
1143
1144         DEBUG2(printk(KERN_INFO "Func: %s\n", __func__));
1145         if (!ep) {
1146                 printk(KERN_ERR "qla4xxx: missing ep.\n");
1147                 return NULL;
1148         }
1149
1150         qla_ep = ep->dd_data;
1151         dst_addr = (struct sockaddr *)&qla_ep->dst_addr;
1152         ha = to_qla_host(qla_ep->host);
1153
1154         ret = qla4xxx_get_ddb_index(ha, &ddb_index);
1155         if (ret == QLA_ERROR)
1156                 return NULL;
1157
1158         cls_sess = iscsi_session_setup(&qla4xxx_iscsi_transport, qla_ep->host,
1159                                        cmds_max, sizeof(struct ddb_entry),
1160                                        sizeof(struct ql4_task_data),
1161                                        initial_cmdsn, ddb_index);
1162         if (!cls_sess)
1163                 return NULL;
1164
1165         sess = cls_sess->dd_data;
1166         ddb_entry = sess->dd_data;
1167         ddb_entry->fw_ddb_index = ddb_index;
1168         ddb_entry->fw_ddb_device_state = DDB_DS_NO_CONNECTION_ACTIVE;
1169         ddb_entry->ha = ha;
1170         ddb_entry->sess = cls_sess;
1171         ddb_entry->unblock_sess = qla4xxx_unblock_ddb;
1172         ddb_entry->ddb_change = qla4xxx_ddb_change;
1173         cls_sess->recovery_tmo = ql4xsess_recovery_tmo;
1174         ha->fw_ddb_index_map[ddb_entry->fw_ddb_index] = ddb_entry;
1175         ha->tot_ddbs++;
1176
1177         return cls_sess;
1178 }
1179
1180 static void qla4xxx_session_destroy(struct iscsi_cls_session *cls_sess)
1181 {
1182         struct iscsi_session *sess;
1183         struct ddb_entry *ddb_entry;
1184         struct scsi_qla_host *ha;
1185         unsigned long flags;
1186
1187         DEBUG2(printk(KERN_INFO "Func: %s\n", __func__));
1188         sess = cls_sess->dd_data;
1189         ddb_entry = sess->dd_data;
1190         ha = ddb_entry->ha;
1191
1192         qla4xxx_clear_ddb_entry(ha, ddb_entry->fw_ddb_index);
1193
1194         spin_lock_irqsave(&ha->hardware_lock, flags);
1195         qla4xxx_free_ddb(ha, ddb_entry);
1196         spin_unlock_irqrestore(&ha->hardware_lock, flags);
1197         iscsi_session_teardown(cls_sess);
1198 }
1199
1200 static struct iscsi_cls_conn *
1201 qla4xxx_conn_create(struct iscsi_cls_session *cls_sess, uint32_t conn_idx)
1202 {
1203         struct iscsi_cls_conn *cls_conn;
1204         struct iscsi_session *sess;
1205         struct ddb_entry *ddb_entry;
1206
1207         DEBUG2(printk(KERN_INFO "Func: %s\n", __func__));
1208         cls_conn = iscsi_conn_setup(cls_sess, sizeof(struct qla_conn),
1209                                     conn_idx);
1210         sess = cls_sess->dd_data;
1211         ddb_entry = sess->dd_data;
1212         ddb_entry->conn = cls_conn;
1213
1214         return cls_conn;
1215 }
1216
1217 static int qla4xxx_conn_bind(struct iscsi_cls_session *cls_session,
1218                              struct iscsi_cls_conn *cls_conn,
1219                              uint64_t transport_fd, int is_leading)
1220 {
1221         struct iscsi_conn *conn;
1222         struct qla_conn *qla_conn;
1223         struct iscsi_endpoint *ep;
1224
1225         DEBUG2(printk(KERN_INFO "Func: %s\n", __func__));
1226
1227         if (iscsi_conn_bind(cls_session, cls_conn, is_leading))
1228                 return -EINVAL;
1229         ep = iscsi_lookup_endpoint(transport_fd);
1230         conn = cls_conn->dd_data;
1231         qla_conn = conn->dd_data;
1232         qla_conn->qla_ep = ep->dd_data;
1233         return 0;
1234 }
1235
1236 static int qla4xxx_conn_start(struct iscsi_cls_conn *cls_conn)
1237 {
1238         struct iscsi_cls_session *cls_sess = iscsi_conn_to_session(cls_conn);
1239         struct iscsi_session *sess;
1240         struct ddb_entry *ddb_entry;
1241         struct scsi_qla_host *ha;
1242         struct dev_db_entry *fw_ddb_entry = NULL;
1243         dma_addr_t fw_ddb_entry_dma;
1244         uint32_t mbx_sts = 0;
1245         int ret = 0;
1246         int status = QLA_SUCCESS;
1247
1248         DEBUG2(printk(KERN_INFO "Func: %s\n", __func__));
1249         sess = cls_sess->dd_data;
1250         ddb_entry = sess->dd_data;
1251         ha = ddb_entry->ha;
1252
1253         /* Check if we have  matching FW DDB, if yes then do not
1254          * login to this target. This could cause target to logout previous
1255          * connection
1256          */
1257         ret = qla4xxx_match_fwdb_session(ha, cls_conn);
1258         if (ret == QLA_SUCCESS) {
1259                 ql4_printk(KERN_INFO, ha,
1260                            "Session already exist in FW.\n");
1261                 ret = -EEXIST;
1262                 goto exit_conn_start;
1263         }
1264
1265         fw_ddb_entry = dma_alloc_coherent(&ha->pdev->dev, sizeof(*fw_ddb_entry),
1266                                           &fw_ddb_entry_dma, GFP_KERNEL);
1267         if (!fw_ddb_entry) {
1268                 ql4_printk(KERN_ERR, ha,
1269                            "%s: Unable to allocate dma buffer\n", __func__);
1270                 ret = -ENOMEM;
1271                 goto exit_conn_start;
1272         }
1273
1274         ret = qla4xxx_set_param_ddbentry(ha, ddb_entry, cls_conn, &mbx_sts);
1275         if (ret) {
1276                 /* If iscsid is stopped and started then no need to do
1277                 * set param again since ddb state will be already
1278                 * active and FW does not allow set ddb to an
1279                 * active session.
1280                 */
1281                 if (mbx_sts)
1282                         if (ddb_entry->fw_ddb_device_state ==
1283                                                 DDB_DS_SESSION_ACTIVE) {
1284                                 ddb_entry->unblock_sess(ddb_entry->sess);
1285                                 goto exit_set_param;
1286                         }
1287
1288                 ql4_printk(KERN_ERR, ha, "%s: Failed set param for index[%d]\n",
1289                            __func__, ddb_entry->fw_ddb_index);
1290                 goto exit_conn_start;
1291         }
1292
1293         status = qla4xxx_conn_open(ha, ddb_entry->fw_ddb_index);
1294         if (status == QLA_ERROR) {
1295                 ql4_printk(KERN_ERR, ha, "%s: Login failed: %s\n", __func__,
1296                            sess->targetname);
1297                 ret = -EINVAL;
1298                 goto exit_conn_start;
1299         }
1300
1301         if (ddb_entry->fw_ddb_device_state == DDB_DS_NO_CONNECTION_ACTIVE)
1302                 ddb_entry->fw_ddb_device_state = DDB_DS_LOGIN_IN_PROCESS;
1303
1304         DEBUG2(printk(KERN_INFO "%s: DDB state [%d]\n", __func__,
1305                       ddb_entry->fw_ddb_device_state));
1306
1307 exit_set_param:
1308         ret = 0;
1309
1310 exit_conn_start:
1311         if (fw_ddb_entry)
1312                 dma_free_coherent(&ha->pdev->dev, sizeof(*fw_ddb_entry),
1313                                   fw_ddb_entry, fw_ddb_entry_dma);
1314         return ret;
1315 }
1316
1317 static void qla4xxx_conn_destroy(struct iscsi_cls_conn *cls_conn)
1318 {
1319         struct iscsi_cls_session *cls_sess = iscsi_conn_to_session(cls_conn);
1320         struct iscsi_session *sess;
1321         struct scsi_qla_host *ha;
1322         struct ddb_entry *ddb_entry;
1323         int options;
1324
1325         DEBUG2(printk(KERN_INFO "Func: %s\n", __func__));
1326         sess = cls_sess->dd_data;
1327         ddb_entry = sess->dd_data;
1328         ha = ddb_entry->ha;
1329
1330         options = LOGOUT_OPTION_CLOSE_SESSION;
1331         if (qla4xxx_session_logout_ddb(ha, ddb_entry, options) == QLA_ERROR)
1332                 ql4_printk(KERN_ERR, ha, "%s: Logout failed\n", __func__);
1333 }
1334
1335 static void qla4xxx_task_work(struct work_struct *wdata)
1336 {
1337         struct ql4_task_data *task_data;
1338         struct scsi_qla_host *ha;
1339         struct passthru_status *sts;
1340         struct iscsi_task *task;
1341         struct iscsi_hdr *hdr;
1342         uint8_t *data;
1343         uint32_t data_len;
1344         struct iscsi_conn *conn;
1345         int hdr_len;
1346         itt_t itt;
1347
1348         task_data = container_of(wdata, struct ql4_task_data, task_work);
1349         ha = task_data->ha;
1350         task = task_data->task;
1351         sts = &task_data->sts;
1352         hdr_len = sizeof(struct iscsi_hdr);
1353
1354         DEBUG3(printk(KERN_INFO "Status returned\n"));
1355         DEBUG3(qla4xxx_dump_buffer(sts, 64));
1356         DEBUG3(printk(KERN_INFO "Response buffer"));
1357         DEBUG3(qla4xxx_dump_buffer(task_data->resp_buffer, 64));
1358
1359         conn = task->conn;
1360
1361         switch (sts->completionStatus) {
1362         case PASSTHRU_STATUS_COMPLETE:
1363                 hdr = (struct iscsi_hdr *)task_data->resp_buffer;
1364                 /* Assign back the itt in hdr, until we use the PREASSIGN_TAG */
1365                 itt = sts->handle;
1366                 hdr->itt = itt;
1367                 data = task_data->resp_buffer + hdr_len;
1368                 data_len = task_data->resp_len - hdr_len;
1369                 iscsi_complete_pdu(conn, hdr, data, data_len);
1370                 break;
1371         default:
1372                 ql4_printk(KERN_ERR, ha, "Passthru failed status = 0x%x\n",
1373                            sts->completionStatus);
1374                 break;
1375         }
1376         return;
1377 }
1378
1379 static int qla4xxx_alloc_pdu(struct iscsi_task *task, uint8_t opcode)
1380 {
1381         struct ql4_task_data *task_data;
1382         struct iscsi_session *sess;
1383         struct ddb_entry *ddb_entry;
1384         struct scsi_qla_host *ha;
1385         int hdr_len;
1386
1387         sess = task->conn->session;
1388         ddb_entry = sess->dd_data;
1389         ha = ddb_entry->ha;
1390         task_data = task->dd_data;
1391         memset(task_data, 0, sizeof(struct ql4_task_data));
1392
1393         if (task->sc) {
1394                 ql4_printk(KERN_INFO, ha,
1395                            "%s: SCSI Commands not implemented\n", __func__);
1396                 return -EINVAL;
1397         }
1398
1399         hdr_len = sizeof(struct iscsi_hdr);
1400         task_data->ha = ha;
1401         task_data->task = task;
1402
1403         if (task->data_count) {
1404                 task_data->data_dma = dma_map_single(&ha->pdev->dev, task->data,
1405                                                      task->data_count,
1406                                                      PCI_DMA_TODEVICE);
1407         }
1408
1409         DEBUG2(ql4_printk(KERN_INFO, ha, "%s: MaxRecvLen %u, iscsi hrd %d\n",
1410                       __func__, task->conn->max_recv_dlength, hdr_len));
1411
1412         task_data->resp_len = task->conn->max_recv_dlength + hdr_len;
1413         task_data->resp_buffer = dma_alloc_coherent(&ha->pdev->dev,
1414                                                     task_data->resp_len,
1415                                                     &task_data->resp_dma,
1416                                                     GFP_ATOMIC);
1417         if (!task_data->resp_buffer)
1418                 goto exit_alloc_pdu;
1419
1420         task_data->req_len = task->data_count + hdr_len;
1421         task_data->req_buffer = dma_alloc_coherent(&ha->pdev->dev,
1422                                                    task_data->req_len,
1423                                                    &task_data->req_dma,
1424                                                    GFP_ATOMIC);
1425         if (!task_data->req_buffer)
1426                 goto exit_alloc_pdu;
1427
1428         task->hdr = task_data->req_buffer;
1429
1430         INIT_WORK(&task_data->task_work, qla4xxx_task_work);
1431
1432         return 0;
1433
1434 exit_alloc_pdu:
1435         if (task_data->resp_buffer)
1436                 dma_free_coherent(&ha->pdev->dev, task_data->resp_len,
1437                                   task_data->resp_buffer, task_data->resp_dma);
1438
1439         if (task_data->req_buffer)
1440                 dma_free_coherent(&ha->pdev->dev, task_data->req_len,
1441                                   task_data->req_buffer, task_data->req_dma);
1442         return -ENOMEM;
1443 }
1444
1445 static void qla4xxx_task_cleanup(struct iscsi_task *task)
1446 {
1447         struct ql4_task_data *task_data;
1448         struct iscsi_session *sess;
1449         struct ddb_entry *ddb_entry;
1450         struct scsi_qla_host *ha;
1451         int hdr_len;
1452
1453         hdr_len = sizeof(struct iscsi_hdr);
1454         sess = task->conn->session;
1455         ddb_entry = sess->dd_data;
1456         ha = ddb_entry->ha;
1457         task_data = task->dd_data;
1458
1459         if (task->data_count) {
1460                 dma_unmap_single(&ha->pdev->dev, task_data->data_dma,
1461                                  task->data_count, PCI_DMA_TODEVICE);
1462         }
1463
1464         DEBUG2(ql4_printk(KERN_INFO, ha, "%s: MaxRecvLen %u, iscsi hrd %d\n",
1465                       __func__, task->conn->max_recv_dlength, hdr_len));
1466
1467         dma_free_coherent(&ha->pdev->dev, task_data->resp_len,
1468                           task_data->resp_buffer, task_data->resp_dma);
1469         dma_free_coherent(&ha->pdev->dev, task_data->req_len,
1470                           task_data->req_buffer, task_data->req_dma);
1471         return;
1472 }
1473
1474 static int qla4xxx_task_xmit(struct iscsi_task *task)
1475 {
1476         struct scsi_cmnd *sc = task->sc;
1477         struct iscsi_session *sess = task->conn->session;
1478         struct ddb_entry *ddb_entry = sess->dd_data;
1479         struct scsi_qla_host *ha = ddb_entry->ha;
1480
1481         if (!sc)
1482                 return qla4xxx_send_passthru0(task);
1483
1484         ql4_printk(KERN_INFO, ha, "%s: scsi cmd xmit not implemented\n",
1485                    __func__);
1486         return -ENOSYS;
1487 }
1488
1489 static void qla4xxx_copy_fwddb_param(struct scsi_qla_host *ha,
1490                                      struct dev_db_entry *fw_ddb_entry,
1491                                      struct iscsi_cls_session *cls_sess,
1492                                      struct iscsi_cls_conn *cls_conn)
1493 {
1494         int buflen = 0;
1495         struct iscsi_session *sess;
1496         struct iscsi_conn *conn;
1497         char ip_addr[DDB_IPADDR_LEN];
1498         uint16_t options = 0;
1499
1500         sess = cls_sess->dd_data;
1501         conn = cls_conn->dd_data;
1502
1503         conn->max_recv_dlength = BYTE_UNITS *
1504                           le16_to_cpu(fw_ddb_entry->iscsi_max_rcv_data_seg_len);
1505
1506         conn->max_xmit_dlength = BYTE_UNITS *
1507                           le16_to_cpu(fw_ddb_entry->iscsi_max_snd_data_seg_len);
1508
1509         sess->initial_r2t_en =
1510                             (BIT_10 & le16_to_cpu(fw_ddb_entry->iscsi_options));
1511
1512         sess->max_r2t = le16_to_cpu(fw_ddb_entry->iscsi_max_outsnd_r2t);
1513
1514         sess->imm_data_en = (BIT_11 & le16_to_cpu(fw_ddb_entry->iscsi_options));
1515
1516         sess->first_burst = BYTE_UNITS *
1517                                le16_to_cpu(fw_ddb_entry->iscsi_first_burst_len);
1518
1519         sess->max_burst = BYTE_UNITS *
1520                                  le16_to_cpu(fw_ddb_entry->iscsi_max_burst_len);
1521
1522         sess->time2wait = le16_to_cpu(fw_ddb_entry->iscsi_def_time2wait);
1523
1524         sess->time2retain = le16_to_cpu(fw_ddb_entry->iscsi_def_time2retain);
1525
1526         conn->persistent_port = le16_to_cpu(fw_ddb_entry->port);
1527
1528         sess->tpgt = le32_to_cpu(fw_ddb_entry->tgt_portal_grp);
1529
1530         options = le16_to_cpu(fw_ddb_entry->options);
1531         if (options & DDB_OPT_IPV6_DEVICE)
1532                 sprintf(ip_addr, "%pI6", fw_ddb_entry->ip_addr);
1533         else
1534                 sprintf(ip_addr, "%pI4", fw_ddb_entry->ip_addr);
1535
1536         iscsi_set_param(cls_conn, ISCSI_PARAM_TARGET_NAME,
1537                         (char *)fw_ddb_entry->iscsi_name, buflen);
1538         iscsi_set_param(cls_conn, ISCSI_PARAM_INITIATOR_NAME,
1539                         (char *)ha->name_string, buflen);
1540         iscsi_set_param(cls_conn, ISCSI_PARAM_PERSISTENT_ADDRESS,
1541                         (char *)ip_addr, buflen);
1542 }
1543
1544 void qla4xxx_update_session_conn_fwddb_param(struct scsi_qla_host *ha,
1545                                              struct ddb_entry *ddb_entry)
1546 {
1547         struct iscsi_cls_session *cls_sess;
1548         struct iscsi_cls_conn *cls_conn;
1549         uint32_t ddb_state;
1550         dma_addr_t fw_ddb_entry_dma;
1551         struct dev_db_entry *fw_ddb_entry;
1552
1553         fw_ddb_entry = dma_alloc_coherent(&ha->pdev->dev, sizeof(*fw_ddb_entry),
1554                                           &fw_ddb_entry_dma, GFP_KERNEL);
1555         if (!fw_ddb_entry) {
1556                 ql4_printk(KERN_ERR, ha,
1557                            "%s: Unable to allocate dma buffer\n", __func__);
1558                 goto exit_session_conn_fwddb_param;
1559         }
1560
1561         if (qla4xxx_get_fwddb_entry(ha, ddb_entry->fw_ddb_index, fw_ddb_entry,
1562                                     fw_ddb_entry_dma, NULL, NULL, &ddb_state,
1563                                     NULL, NULL, NULL) == QLA_ERROR) {
1564                 DEBUG2(ql4_printk(KERN_ERR, ha, "scsi%ld: %s: failed "
1565                                   "get_ddb_entry for fw_ddb_index %d\n",
1566                                   ha->host_no, __func__,
1567                                   ddb_entry->fw_ddb_index));
1568                 goto exit_session_conn_fwddb_param;
1569         }
1570
1571         cls_sess = ddb_entry->sess;
1572
1573         cls_conn = ddb_entry->conn;
1574
1575         /* Update params */
1576         qla4xxx_copy_fwddb_param(ha, fw_ddb_entry, cls_sess, cls_conn);
1577
1578 exit_session_conn_fwddb_param:
1579         if (fw_ddb_entry)
1580                 dma_free_coherent(&ha->pdev->dev, sizeof(*fw_ddb_entry),
1581                                   fw_ddb_entry, fw_ddb_entry_dma);
1582 }
1583
1584 void qla4xxx_update_session_conn_param(struct scsi_qla_host *ha,
1585                                        struct ddb_entry *ddb_entry)
1586 {
1587         struct iscsi_cls_session *cls_sess;
1588         struct iscsi_cls_conn *cls_conn;
1589         struct iscsi_session *sess;
1590         struct iscsi_conn *conn;
1591         uint32_t ddb_state;
1592         dma_addr_t fw_ddb_entry_dma;
1593         struct dev_db_entry *fw_ddb_entry;
1594
1595         fw_ddb_entry = dma_alloc_coherent(&ha->pdev->dev, sizeof(*fw_ddb_entry),
1596                                           &fw_ddb_entry_dma, GFP_KERNEL);
1597         if (!fw_ddb_entry) {
1598                 ql4_printk(KERN_ERR, ha,
1599                            "%s: Unable to allocate dma buffer\n", __func__);
1600                 goto exit_session_conn_param;
1601         }
1602
1603         if (qla4xxx_get_fwddb_entry(ha, ddb_entry->fw_ddb_index, fw_ddb_entry,
1604                                     fw_ddb_entry_dma, NULL, NULL, &ddb_state,
1605                                     NULL, NULL, NULL) == QLA_ERROR) {
1606                 DEBUG2(ql4_printk(KERN_ERR, ha, "scsi%ld: %s: failed "
1607                                   "get_ddb_entry for fw_ddb_index %d\n",
1608                                   ha->host_no, __func__,
1609                                   ddb_entry->fw_ddb_index));
1610                 goto exit_session_conn_param;
1611         }
1612
1613         cls_sess = ddb_entry->sess;
1614         sess = cls_sess->dd_data;
1615
1616         cls_conn = ddb_entry->conn;
1617         conn = cls_conn->dd_data;
1618
1619         /* Update timers after login */
1620         ddb_entry->default_relogin_timeout =
1621                                 le16_to_cpu(fw_ddb_entry->def_timeout);
1622         ddb_entry->default_time2wait =
1623                                 le16_to_cpu(fw_ddb_entry->iscsi_def_time2wait);
1624
1625         /* Update params */
1626         conn->max_recv_dlength = BYTE_UNITS *
1627                           le16_to_cpu(fw_ddb_entry->iscsi_max_rcv_data_seg_len);
1628
1629         conn->max_xmit_dlength = BYTE_UNITS *
1630                           le16_to_cpu(fw_ddb_entry->iscsi_max_snd_data_seg_len);
1631
1632         sess->initial_r2t_en =
1633                             (BIT_10 & le16_to_cpu(fw_ddb_entry->iscsi_options));
1634
1635         sess->max_r2t = le16_to_cpu(fw_ddb_entry->iscsi_max_outsnd_r2t);
1636
1637         sess->imm_data_en = (BIT_11 & le16_to_cpu(fw_ddb_entry->iscsi_options));
1638
1639         sess->first_burst = BYTE_UNITS *
1640                                le16_to_cpu(fw_ddb_entry->iscsi_first_burst_len);
1641
1642         sess->max_burst = BYTE_UNITS *
1643                                  le16_to_cpu(fw_ddb_entry->iscsi_max_burst_len);
1644
1645         sess->time2wait = le16_to_cpu(fw_ddb_entry->iscsi_def_time2wait);
1646
1647         sess->time2retain = le16_to_cpu(fw_ddb_entry->iscsi_def_time2retain);
1648
1649         sess->tpgt = le32_to_cpu(fw_ddb_entry->tgt_portal_grp);
1650
1651         memcpy(sess->initiatorname, ha->name_string,
1652                min(sizeof(ha->name_string), sizeof(sess->initiatorname)));
1653
1654 exit_session_conn_param:
1655         if (fw_ddb_entry)
1656                 dma_free_coherent(&ha->pdev->dev, sizeof(*fw_ddb_entry),
1657                                   fw_ddb_entry, fw_ddb_entry_dma);
1658 }
1659
1660 /*
1661  * Timer routines
1662  */
1663
1664 static void qla4xxx_start_timer(struct scsi_qla_host *ha, void *func,
1665                                 unsigned long interval)
1666 {
1667         DEBUG(printk("scsi: %s: Starting timer thread for adapter %d\n",
1668                      __func__, ha->host->host_no));
1669         init_timer(&ha->timer);
1670         ha->timer.expires = jiffies + interval * HZ;
1671         ha->timer.data = (unsigned long)ha;
1672         ha->timer.function = (void (*)(unsigned long))func;
1673         add_timer(&ha->timer);
1674         ha->timer_active = 1;
1675 }
1676
1677 static void qla4xxx_stop_timer(struct scsi_qla_host *ha)
1678 {
1679         del_timer_sync(&ha->timer);
1680         ha->timer_active = 0;
1681 }
1682
1683 /***
1684  * qla4xxx_mark_device_missing - blocks the session
1685  * @cls_session: Pointer to the session to be blocked
1686  * @ddb_entry: Pointer to device database entry
1687  *
1688  * This routine marks a device missing and close connection.
1689  **/
1690 void qla4xxx_mark_device_missing(struct iscsi_cls_session *cls_session)
1691 {
1692         iscsi_block_session(cls_session);
1693 }
1694
1695 /**
1696  * qla4xxx_mark_all_devices_missing - mark all devices as missing.
1697  * @ha: Pointer to host adapter structure.
1698  *
1699  * This routine marks a device missing and resets the relogin retry count.
1700  **/
1701 void qla4xxx_mark_all_devices_missing(struct scsi_qla_host *ha)
1702 {
1703         iscsi_host_for_each_session(ha->host, qla4xxx_mark_device_missing);
1704 }
1705
1706 static struct srb* qla4xxx_get_new_srb(struct scsi_qla_host *ha,
1707                                        struct ddb_entry *ddb_entry,
1708                                        struct scsi_cmnd *cmd)
1709 {
1710         struct srb *srb;
1711
1712         srb = mempool_alloc(ha->srb_mempool, GFP_ATOMIC);
1713         if (!srb)
1714                 return srb;
1715
1716         kref_init(&srb->srb_ref);
1717         srb->ha = ha;
1718         srb->ddb = ddb_entry;
1719         srb->cmd = cmd;
1720         srb->flags = 0;
1721         CMD_SP(cmd) = (void *)srb;
1722
1723         return srb;
1724 }
1725
1726 static void qla4xxx_srb_free_dma(struct scsi_qla_host *ha, struct srb *srb)
1727 {
1728         struct scsi_cmnd *cmd = srb->cmd;
1729
1730         if (srb->flags & SRB_DMA_VALID) {
1731                 scsi_dma_unmap(cmd);
1732                 srb->flags &= ~SRB_DMA_VALID;
1733         }
1734         CMD_SP(cmd) = NULL;
1735 }
1736
1737 void qla4xxx_srb_compl(struct kref *ref)
1738 {
1739         struct srb *srb = container_of(ref, struct srb, srb_ref);
1740         struct scsi_cmnd *cmd = srb->cmd;
1741         struct scsi_qla_host *ha = srb->ha;
1742
1743         qla4xxx_srb_free_dma(ha, srb);
1744
1745         mempool_free(srb, ha->srb_mempool);
1746
1747         cmd->scsi_done(cmd);
1748 }
1749
1750 /**
1751  * qla4xxx_queuecommand - scsi layer issues scsi command to driver.
1752  * @host: scsi host
1753  * @cmd: Pointer to Linux's SCSI command structure
1754  *
1755  * Remarks:
1756  * This routine is invoked by Linux to send a SCSI command to the driver.
1757  * The mid-level driver tries to ensure that queuecommand never gets
1758  * invoked concurrently with itself or the interrupt handler (although
1759  * the interrupt handler may call this routine as part of request-
1760  * completion handling).   Unfortunely, it sometimes calls the scheduler
1761  * in interrupt context which is a big NO! NO!.
1762  **/
1763 static int qla4xxx_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
1764 {
1765         struct scsi_qla_host *ha = to_qla_host(host);
1766         struct ddb_entry *ddb_entry = cmd->device->hostdata;
1767         struct iscsi_cls_session *sess = ddb_entry->sess;
1768         struct srb *srb;
1769         int rval;
1770
1771         if (test_bit(AF_EEH_BUSY, &ha->flags)) {
1772                 if (test_bit(AF_PCI_CHANNEL_IO_PERM_FAILURE, &ha->flags))
1773                         cmd->result = DID_NO_CONNECT << 16;
1774                 else
1775                         cmd->result = DID_REQUEUE << 16;
1776                 goto qc_fail_command;
1777         }
1778
1779         if (!sess) {
1780                 cmd->result = DID_IMM_RETRY << 16;
1781                 goto qc_fail_command;
1782         }
1783
1784         rval = iscsi_session_chkready(sess);
1785         if (rval) {
1786                 cmd->result = rval;
1787                 goto qc_fail_command;
1788         }
1789
1790         if (test_bit(DPC_RESET_HA_INTR, &ha->dpc_flags) ||
1791             test_bit(DPC_RESET_ACTIVE, &ha->dpc_flags) ||
1792             test_bit(DPC_RESET_HA, &ha->dpc_flags) ||
1793             test_bit(DPC_HA_UNRECOVERABLE, &ha->dpc_flags) ||
1794             test_bit(DPC_HA_NEED_QUIESCENT, &ha->dpc_flags) ||
1795             !test_bit(AF_ONLINE, &ha->flags) ||
1796             !test_bit(AF_LINK_UP, &ha->flags) ||
1797             test_bit(DPC_RESET_HA_FW_CONTEXT, &ha->dpc_flags))
1798                 goto qc_host_busy;
1799
1800         srb = qla4xxx_get_new_srb(ha, ddb_entry, cmd);
1801         if (!srb)
1802                 goto qc_host_busy;
1803
1804         rval = qla4xxx_send_command_to_isp(ha, srb);
1805         if (rval != QLA_SUCCESS)
1806                 goto qc_host_busy_free_sp;
1807
1808         return 0;
1809
1810 qc_host_busy_free_sp:
1811         qla4xxx_srb_free_dma(ha, srb);
1812         mempool_free(srb, ha->srb_mempool);
1813
1814 qc_host_busy:
1815         return SCSI_MLQUEUE_HOST_BUSY;
1816
1817 qc_fail_command:
1818         cmd->scsi_done(cmd);
1819
1820         return 0;
1821 }
1822
1823 /**
1824  * qla4xxx_mem_free - frees memory allocated to adapter
1825  * @ha: Pointer to host adapter structure.
1826  *
1827  * Frees memory previously allocated by qla4xxx_mem_alloc
1828  **/
1829 static void qla4xxx_mem_free(struct scsi_qla_host *ha)
1830 {
1831         if (ha->queues)
1832                 dma_free_coherent(&ha->pdev->dev, ha->queues_len, ha->queues,
1833                                   ha->queues_dma);
1834
1835         ha->queues_len = 0;
1836         ha->queues = NULL;
1837         ha->queues_dma = 0;
1838         ha->request_ring = NULL;
1839         ha->request_dma = 0;
1840         ha->response_ring = NULL;
1841         ha->response_dma = 0;
1842         ha->shadow_regs = NULL;
1843         ha->shadow_regs_dma = 0;
1844
1845         /* Free srb pool. */
1846         if (ha->srb_mempool)
1847                 mempool_destroy(ha->srb_mempool);
1848
1849         ha->srb_mempool = NULL;
1850
1851         if (ha->chap_dma_pool)
1852                 dma_pool_destroy(ha->chap_dma_pool);
1853
1854         if (ha->chap_list)
1855                 vfree(ha->chap_list);
1856         ha->chap_list = NULL;
1857
1858         if (ha->fw_ddb_dma_pool)
1859                 dma_pool_destroy(ha->fw_ddb_dma_pool);
1860
1861         /* release io space registers  */
1862         if (is_qla8022(ha)) {
1863                 if (ha->nx_pcibase)
1864                         iounmap(
1865                             (struct device_reg_82xx __iomem *)ha->nx_pcibase);
1866         } else if (ha->reg)
1867                 iounmap(ha->reg);
1868         pci_release_regions(ha->pdev);
1869 }
1870
1871 /**
1872  * qla4xxx_mem_alloc - allocates memory for use by adapter.
1873  * @ha: Pointer to host adapter structure
1874  *
1875  * Allocates DMA memory for request and response queues. Also allocates memory
1876  * for srbs.
1877  **/
1878 static int qla4xxx_mem_alloc(struct scsi_qla_host *ha)
1879 {
1880         unsigned long align;
1881
1882         /* Allocate contiguous block of DMA memory for queues. */
1883         ha->queues_len = ((REQUEST_QUEUE_DEPTH * QUEUE_SIZE) +
1884                           (RESPONSE_QUEUE_DEPTH * QUEUE_SIZE) +
1885                           sizeof(struct shadow_regs) +
1886                           MEM_ALIGN_VALUE +
1887                           (PAGE_SIZE - 1)) & ~(PAGE_SIZE - 1);
1888         ha->queues = dma_alloc_coherent(&ha->pdev->dev, ha->queues_len,
1889                                         &ha->queues_dma, GFP_KERNEL);
1890         if (ha->queues == NULL) {
1891                 ql4_printk(KERN_WARNING, ha,
1892                     "Memory Allocation failed - queues.\n");
1893
1894                 goto mem_alloc_error_exit;
1895         }
1896         memset(ha->queues, 0, ha->queues_len);
1897
1898         /*
1899          * As per RISC alignment requirements -- the bus-address must be a
1900          * multiple of the request-ring size (in bytes).
1901          */
1902         align = 0;
1903         if ((unsigned long)ha->queues_dma & (MEM_ALIGN_VALUE - 1))
1904                 align = MEM_ALIGN_VALUE - ((unsigned long)ha->queues_dma &
1905                                            (MEM_ALIGN_VALUE - 1));
1906
1907         /* Update request and response queue pointers. */
1908         ha->request_dma = ha->queues_dma + align;
1909         ha->request_ring = (struct queue_entry *) (ha->queues + align);
1910         ha->response_dma = ha->queues_dma + align +
1911                 (REQUEST_QUEUE_DEPTH * QUEUE_SIZE);
1912         ha->response_ring = (struct queue_entry *) (ha->queues + align +
1913                                                     (REQUEST_QUEUE_DEPTH *
1914                                                      QUEUE_SIZE));
1915         ha->shadow_regs_dma = ha->queues_dma + align +
1916                 (REQUEST_QUEUE_DEPTH * QUEUE_SIZE) +
1917                 (RESPONSE_QUEUE_DEPTH * QUEUE_SIZE);
1918         ha->shadow_regs = (struct shadow_regs *) (ha->queues + align +
1919                                                   (REQUEST_QUEUE_DEPTH *
1920                                                    QUEUE_SIZE) +
1921                                                   (RESPONSE_QUEUE_DEPTH *
1922                                                    QUEUE_SIZE));
1923
1924         /* Allocate memory for srb pool. */
1925         ha->srb_mempool = mempool_create(SRB_MIN_REQ, mempool_alloc_slab,
1926                                          mempool_free_slab, srb_cachep);
1927         if (ha->srb_mempool == NULL) {
1928                 ql4_printk(KERN_WARNING, ha,
1929                     "Memory Allocation failed - SRB Pool.\n");
1930
1931                 goto mem_alloc_error_exit;
1932         }
1933
1934         ha->chap_dma_pool = dma_pool_create("ql4_chap", &ha->pdev->dev,
1935                                             CHAP_DMA_BLOCK_SIZE, 8, 0);
1936
1937         if (ha->chap_dma_pool == NULL) {
1938                 ql4_printk(KERN_WARNING, ha,
1939                     "%s: chap_dma_pool allocation failed..\n", __func__);
1940                 goto mem_alloc_error_exit;
1941         }
1942
1943         ha->fw_ddb_dma_pool = dma_pool_create("ql4_fw_ddb", &ha->pdev->dev,
1944                                               DDB_DMA_BLOCK_SIZE, 8, 0);
1945
1946         if (ha->fw_ddb_dma_pool == NULL) {
1947                 ql4_printk(KERN_WARNING, ha,
1948                            "%s: fw_ddb_dma_pool allocation failed..\n",
1949                            __func__);
1950                 goto mem_alloc_error_exit;
1951         }
1952
1953         return QLA_SUCCESS;
1954
1955 mem_alloc_error_exit:
1956         qla4xxx_mem_free(ha);
1957         return QLA_ERROR;
1958 }
1959
1960 /**
1961  * qla4_8xxx_check_fw_alive  - Check firmware health
1962  * @ha: Pointer to host adapter structure.
1963  *
1964  * Context: Interrupt
1965  **/
1966 static void qla4_8xxx_check_fw_alive(struct scsi_qla_host *ha)
1967 {
1968         uint32_t fw_heartbeat_counter, halt_status;
1969
1970         fw_heartbeat_counter = qla4_8xxx_rd_32(ha, QLA82XX_PEG_ALIVE_COUNTER);
1971         /* If PEG_ALIVE_COUNTER is 0xffffffff, AER/EEH is in progress, ignore */
1972         if (fw_heartbeat_counter == 0xffffffff) {
1973                 DEBUG2(printk(KERN_WARNING "scsi%ld: %s: Device in frozen "
1974                     "state, QLA82XX_PEG_ALIVE_COUNTER is 0xffffffff\n",
1975                     ha->host_no, __func__));
1976                 return;
1977         }
1978
1979         if (ha->fw_heartbeat_counter == fw_heartbeat_counter) {
1980                 ha->seconds_since_last_heartbeat++;
1981                 /* FW not alive after 2 seconds */
1982                 if (ha->seconds_since_last_heartbeat == 2) {
1983                         ha->seconds_since_last_heartbeat = 0;
1984                         halt_status = qla4_8xxx_rd_32(ha,
1985                                                       QLA82XX_PEG_HALT_STATUS1);
1986
1987                         ql4_printk(KERN_INFO, ha,
1988                                    "scsi(%ld): %s, Dumping hw/fw registers:\n "
1989                                    " PEG_HALT_STATUS1: 0x%x, PEG_HALT_STATUS2:"
1990                                    " 0x%x,\n PEG_NET_0_PC: 0x%x, PEG_NET_1_PC:"
1991                                    " 0x%x,\n PEG_NET_2_PC: 0x%x, PEG_NET_3_PC:"
1992                                    " 0x%x,\n PEG_NET_4_PC: 0x%x\n",
1993                                    ha->host_no, __func__, halt_status,
1994                                    qla4_8xxx_rd_32(ha,
1995                                                    QLA82XX_PEG_HALT_STATUS2),
1996                                    qla4_8xxx_rd_32(ha, QLA82XX_CRB_PEG_NET_0 +
1997                                                    0x3c),
1998                                    qla4_8xxx_rd_32(ha, QLA82XX_CRB_PEG_NET_1 +
1999                                                    0x3c),
2000                                    qla4_8xxx_rd_32(ha, QLA82XX_CRB_PEG_NET_2 +
2001                                                    0x3c),
2002                                    qla4_8xxx_rd_32(ha, QLA82XX_CRB_PEG_NET_3 +
2003                                                    0x3c),
2004                                    qla4_8xxx_rd_32(ha, QLA82XX_CRB_PEG_NET_4 +
2005                                                    0x3c));
2006
2007                         /* Since we cannot change dev_state in interrupt
2008                          * context, set appropriate DPC flag then wakeup
2009                          * DPC */
2010                         if (halt_status & HALT_STATUS_UNRECOVERABLE)
2011                                 set_bit(DPC_HA_UNRECOVERABLE, &ha->dpc_flags);
2012                         else {
2013                                 printk("scsi%ld: %s: detect abort needed!\n",
2014                                     ha->host_no, __func__);
2015                                 set_bit(DPC_RESET_HA, &ha->dpc_flags);
2016                         }
2017                         qla4xxx_wake_dpc(ha);
2018                         qla4xxx_mailbox_premature_completion(ha);
2019                 }
2020         } else
2021                 ha->seconds_since_last_heartbeat = 0;
2022
2023         ha->fw_heartbeat_counter = fw_heartbeat_counter;
2024 }
2025
2026 /**
2027  * qla4_8xxx_watchdog - Poll dev state
2028  * @ha: Pointer to host adapter structure.
2029  *
2030  * Context: Interrupt
2031  **/
2032 void qla4_8xxx_watchdog(struct scsi_qla_host *ha)
2033 {
2034         uint32_t dev_state;
2035
2036         dev_state = qla4_8xxx_rd_32(ha, QLA82XX_CRB_DEV_STATE);
2037
2038         /* don't poll if reset is going on */
2039         if (!(test_bit(DPC_RESET_ACTIVE, &ha->dpc_flags) ||
2040             test_bit(DPC_RESET_HA, &ha->dpc_flags) ||
2041             test_bit(DPC_RETRY_RESET_HA, &ha->dpc_flags))) {
2042                 if (dev_state == QLA82XX_DEV_NEED_RESET &&
2043                     !test_bit(DPC_RESET_HA, &ha->dpc_flags)) {
2044                         if (!ql4xdontresethba) {
2045                                 ql4_printk(KERN_INFO, ha, "%s: HW State: "
2046                                     "NEED RESET!\n", __func__);
2047                                 set_bit(DPC_RESET_HA, &ha->dpc_flags);
2048                                 qla4xxx_wake_dpc(ha);
2049                                 qla4xxx_mailbox_premature_completion(ha);
2050                         }
2051                 } else if (dev_state == QLA82XX_DEV_NEED_QUIESCENT &&
2052                     !test_bit(DPC_HA_NEED_QUIESCENT, &ha->dpc_flags)) {
2053                         ql4_printk(KERN_INFO, ha, "%s: HW State: NEED QUIES!\n",
2054                             __func__);
2055                         set_bit(DPC_HA_NEED_QUIESCENT, &ha->dpc_flags);
2056                         qla4xxx_wake_dpc(ha);
2057                 } else  {
2058                         /* Check firmware health */
2059                         qla4_8xxx_check_fw_alive(ha);
2060                 }
2061         }
2062 }
2063
2064 void qla4xxx_check_relogin_flash_ddb(struct iscsi_cls_session *cls_sess)
2065 {
2066         struct iscsi_session *sess;
2067         struct ddb_entry *ddb_entry;
2068         struct scsi_qla_host *ha;
2069
2070         sess = cls_sess->dd_data;
2071         ddb_entry = sess->dd_data;
2072         ha = ddb_entry->ha;
2073
2074         if (!(ddb_entry->ddb_type == FLASH_DDB))
2075                 return;
2076
2077         if (adapter_up(ha) && !test_bit(DF_RELOGIN, &ddb_entry->flags) &&
2078             !iscsi_is_session_online(cls_sess)) {
2079                 if (atomic_read(&ddb_entry->retry_relogin_timer) !=
2080                     INVALID_ENTRY) {
2081                         if (atomic_read(&ddb_entry->retry_relogin_timer) ==
2082                                         0) {
2083                                 atomic_set(&ddb_entry->retry_relogin_timer,
2084                                            INVALID_ENTRY);
2085                                 set_bit(DPC_RELOGIN_DEVICE, &ha->dpc_flags);
2086                                 set_bit(DF_RELOGIN, &ddb_entry->flags);
2087                                 DEBUG2(ql4_printk(KERN_INFO, ha,
2088                                        "%s: index [%d] login device\n",
2089                                         __func__, ddb_entry->fw_ddb_index));
2090                         } else
2091                                 atomic_dec(&ddb_entry->retry_relogin_timer);
2092                 }
2093         }
2094
2095         /* Wait for relogin to timeout */
2096         if (atomic_read(&ddb_entry->relogin_timer) &&
2097             (atomic_dec_and_test(&ddb_entry->relogin_timer) != 0)) {
2098                 /*
2099                  * If the relogin times out and the device is
2100                  * still NOT ONLINE then try and relogin again.
2101                  */
2102                 if (!iscsi_is_session_online(cls_sess)) {
2103                         /* Reset retry relogin timer */
2104                         atomic_inc(&ddb_entry->relogin_retry_count);
2105                         DEBUG2(ql4_printk(KERN_INFO, ha,
2106                                 "%s: index[%d] relogin timed out-retrying"
2107                                 " relogin (%d), retry (%d)\n", __func__,
2108                                 ddb_entry->fw_ddb_index,
2109                                 atomic_read(&ddb_entry->relogin_retry_count),
2110                                 ddb_entry->default_time2wait + 4));
2111                         set_bit(DPC_RELOGIN_DEVICE, &ha->dpc_flags);
2112                         atomic_set(&ddb_entry->retry_relogin_timer,
2113                                    ddb_entry->default_time2wait + 4);
2114                 }
2115         }
2116 }
2117
2118 /**
2119  * qla4xxx_timer - checks every second for work to do.
2120  * @ha: Pointer to host adapter structure.
2121  **/
2122 static void qla4xxx_timer(struct scsi_qla_host *ha)
2123 {
2124         int start_dpc = 0;
2125         uint16_t w;
2126
2127         iscsi_host_for_each_session(ha->host, qla4xxx_check_relogin_flash_ddb);
2128
2129         /* If we are in the middle of AER/EEH processing
2130          * skip any processing and reschedule the timer
2131          */
2132         if (test_bit(AF_EEH_BUSY, &ha->flags)) {
2133                 mod_timer(&ha->timer, jiffies + HZ);
2134                 return;
2135         }
2136
2137         /* Hardware read to trigger an EEH error during mailbox waits. */
2138         if (!pci_channel_offline(ha->pdev))
2139                 pci_read_config_word(ha->pdev, PCI_VENDOR_ID, &w);
2140
2141         if (is_qla8022(ha)) {
2142                 qla4_8xxx_watchdog(ha);
2143         }
2144
2145         if (!is_qla8022(ha)) {
2146                 /* Check for heartbeat interval. */
2147                 if (ha->firmware_options & FWOPT_HEARTBEAT_ENABLE &&
2148                     ha->heartbeat_interval != 0) {
2149                         ha->seconds_since_last_heartbeat++;
2150                         if (ha->seconds_since_last_heartbeat >
2151                             ha->heartbeat_interval + 2)
2152                                 set_bit(DPC_RESET_HA, &ha->dpc_flags);
2153                 }
2154         }
2155
2156         /* Wakeup the dpc routine for this adapter, if needed. */
2157         if (start_dpc ||
2158              test_bit(DPC_RESET_HA, &ha->dpc_flags) ||
2159              test_bit(DPC_RETRY_RESET_HA, &ha->dpc_flags) ||
2160              test_bit(DPC_RELOGIN_DEVICE, &ha->dpc_flags) ||
2161              test_bit(DPC_RESET_HA_FW_CONTEXT, &ha->dpc_flags) ||
2162              test_bit(DPC_RESET_HA_INTR, &ha->dpc_flags) ||
2163              test_bit(DPC_GET_DHCP_IP_ADDR, &ha->dpc_flags) ||
2164              test_bit(DPC_LINK_CHANGED, &ha->dpc_flags) ||
2165              test_bit(DPC_HA_UNRECOVERABLE, &ha->dpc_flags) ||
2166              test_bit(DPC_HA_NEED_QUIESCENT, &ha->dpc_flags) ||
2167              test_bit(DPC_AEN, &ha->dpc_flags)) {
2168                 DEBUG2(printk("scsi%ld: %s: scheduling dpc routine"
2169                               " - dpc flags = 0x%lx\n",
2170                               ha->host_no, __func__, ha->dpc_flags));
2171                 qla4xxx_wake_dpc(ha);
2172         }
2173
2174         /* Reschedule timer thread to call us back in one second */
2175         mod_timer(&ha->timer, jiffies + HZ);
2176
2177         DEBUG2(ha->seconds_since_last_intr++);
2178 }
2179
2180 /**
2181  * qla4xxx_cmd_wait - waits for all outstanding commands to complete
2182  * @ha: Pointer to host adapter structure.
2183  *
2184  * This routine stalls the driver until all outstanding commands are returned.
2185  * Caller must release the Hardware Lock prior to calling this routine.
2186  **/
2187 static int qla4xxx_cmd_wait(struct scsi_qla_host *ha)
2188 {
2189         uint32_t index = 0;
2190         unsigned long flags;
2191         struct scsi_cmnd *cmd;
2192
2193         unsigned long wtime = jiffies + (WAIT_CMD_TOV * HZ);
2194
2195         DEBUG2(ql4_printk(KERN_INFO, ha, "Wait up to %d seconds for cmds to "
2196             "complete\n", WAIT_CMD_TOV));
2197
2198         while (!time_after_eq(jiffies, wtime)) {
2199                 spin_lock_irqsave(&ha->hardware_lock, flags);
2200                 /* Find a command that hasn't completed. */
2201                 for (index = 0; index < ha->host->can_queue; index++) {
2202                         cmd = scsi_host_find_tag(ha->host, index);
2203                         /*
2204                          * We cannot just check if the index is valid,
2205                          * becase if we are run from the scsi eh, then
2206                          * the scsi/block layer is going to prevent
2207                          * the tag from being released.
2208                          */
2209                         if (cmd != NULL && CMD_SP(cmd))
2210                                 break;
2211                 }
2212                 spin_unlock_irqrestore(&ha->hardware_lock, flags);
2213
2214                 /* If No Commands are pending, wait is complete */
2215                 if (index == ha->host->can_queue)
2216                         return QLA_SUCCESS;
2217
2218                 msleep(1000);
2219         }
2220         /* If we timed out on waiting for commands to come back
2221          * return ERROR. */
2222         return QLA_ERROR;
2223 }
2224
2225 int qla4xxx_hw_reset(struct scsi_qla_host *ha)
2226 {
2227         uint32_t ctrl_status;
2228         unsigned long flags = 0;
2229
2230         DEBUG2(printk(KERN_ERR "scsi%ld: %s\n", ha->host_no, __func__));
2231
2232         if (ql4xxx_lock_drvr_wait(ha) != QLA_SUCCESS)
2233                 return QLA_ERROR;
2234
2235         spin_lock_irqsave(&ha->hardware_lock, flags);
2236
2237         /*
2238          * If the SCSI Reset Interrupt bit is set, clear it.
2239          * Otherwise, the Soft Reset won't work.
2240          */
2241         ctrl_status = readw(&ha->reg->ctrl_status);
2242         if ((ctrl_status & CSR_SCSI_RESET_INTR) != 0)
2243                 writel(set_rmask(CSR_SCSI_RESET_INTR), &ha->reg->ctrl_status);
2244
2245         /* Issue Soft Reset */
2246         writel(set_rmask(CSR_SOFT_RESET), &ha->reg->ctrl_status);
2247         readl(&ha->reg->ctrl_status);
2248
2249         spin_unlock_irqrestore(&ha->hardware_lock, flags);
2250         return QLA_SUCCESS;
2251 }
2252
2253 /**
2254  * qla4xxx_soft_reset - performs soft reset.
2255  * @ha: Pointer to host adapter structure.
2256  **/
2257 int qla4xxx_soft_reset(struct scsi_qla_host *ha)
2258 {
2259         uint32_t max_wait_time;
2260         unsigned long flags = 0;
2261         int status;
2262         uint32_t ctrl_status;
2263
2264         status = qla4xxx_hw_reset(ha);
2265         if (status != QLA_SUCCESS)
2266                 return status;
2267
2268         status = QLA_ERROR;
2269         /* Wait until the Network Reset Intr bit is cleared */
2270         max_wait_time = RESET_INTR_TOV;
2271         do {
2272                 spin_lock_irqsave(&ha->hardware_lock, flags);
2273                 ctrl_status = readw(&ha->reg->ctrl_status);
2274                 spin_unlock_irqrestore(&ha->hardware_lock, flags);
2275
2276                 if ((ctrl_status & CSR_NET_RESET_INTR) == 0)
2277                         break;
2278
2279                 msleep(1000);
2280         } while ((--max_wait_time));
2281
2282         if ((ctrl_status & CSR_NET_RESET_INTR) != 0) {
2283                 DEBUG2(printk(KERN_WARNING
2284                               "scsi%ld: Network Reset Intr not cleared by "
2285                               "Network function, clearing it now!\n",
2286                               ha->host_no));
2287                 spin_lock_irqsave(&ha->hardware_lock, flags);
2288                 writel(set_rmask(CSR_NET_RESET_INTR), &ha->reg->ctrl_status);
2289                 readl(&ha->reg->ctrl_status);
2290                 spin_unlock_irqrestore(&ha->hardware_lock, flags);
2291         }
2292
2293         /* Wait until the firmware tells us the Soft Reset is done */
2294         max_wait_time = SOFT_RESET_TOV;
2295         do {
2296                 spin_lock_irqsave(&ha->hardware_lock, flags);
2297                 ctrl_status = readw(&ha->reg->ctrl_status);
2298                 spin_unlock_irqrestore(&ha->hardware_lock, flags);
2299
2300                 if ((ctrl_status & CSR_SOFT_RESET) == 0) {
2301                         status = QLA_SUCCESS;
2302                         break;
2303                 }
2304
2305                 msleep(1000);
2306         } while ((--max_wait_time));
2307
2308         /*
2309          * Also, make sure that the SCSI Reset Interrupt bit has been cleared
2310          * after the soft reset has taken place.
2311          */
2312         spin_lock_irqsave(&ha->hardware_lock, flags);
2313         ctrl_status = readw(&ha->reg->ctrl_status);
2314         if ((ctrl_status & CSR_SCSI_RESET_INTR) != 0) {
2315                 writel(set_rmask(CSR_SCSI_RESET_INTR), &ha->reg->ctrl_status);
2316                 readl(&ha->reg->ctrl_status);
2317         }
2318         spin_unlock_irqrestore(&ha->hardware_lock, flags);
2319
2320         /* If soft reset fails then most probably the bios on other
2321          * function is also enabled.
2322          * Since the initialization is sequential the other fn
2323          * wont be able to acknowledge the soft reset.
2324          * Issue a force soft reset to workaround this scenario.
2325          */
2326         if (max_wait_time == 0) {
2327                 /* Issue Force Soft Reset */
2328                 spin_lock_irqsave(&ha->hardware_lock, flags);
2329                 writel(set_rmask(CSR_FORCE_SOFT_RESET), &ha->reg->ctrl_status);
2330                 readl(&ha->reg->ctrl_status);
2331                 spin_unlock_irqrestore(&ha->hardware_lock, flags);
2332                 /* Wait until the firmware tells us the Soft Reset is done */
2333                 max_wait_time = SOFT_RESET_TOV;
2334                 do {
2335                         spin_lock_irqsave(&ha->hardware_lock, flags);
2336                         ctrl_status = readw(&ha->reg->ctrl_status);
2337                         spin_unlock_irqrestore(&ha->hardware_lock, flags);
2338
2339                         if ((ctrl_status & CSR_FORCE_SOFT_RESET) == 0) {
2340                                 status = QLA_SUCCESS;
2341                                 break;
2342                         }
2343
2344                         msleep(1000);
2345                 } while ((--max_wait_time));
2346         }
2347
2348         return status;
2349 }
2350
2351 /**
2352  * qla4xxx_abort_active_cmds - returns all outstanding i/o requests to O.S.
2353  * @ha: Pointer to host adapter structure.
2354  * @res: returned scsi status
2355  *
2356  * This routine is called just prior to a HARD RESET to return all
2357  * outstanding commands back to the Operating System.
2358  * Caller should make sure that the following locks are released
2359  * before this calling routine: Hardware lock, and io_request_lock.
2360  **/
2361 static void qla4xxx_abort_active_cmds(struct scsi_qla_host *ha, int res)
2362 {
2363         struct srb *srb;
2364         int i;
2365         unsigned long flags;
2366
2367         spin_lock_irqsave(&ha->hardware_lock, flags);
2368         for (i = 0; i < ha->host->can_queue; i++) {
2369                 srb = qla4xxx_del_from_active_array(ha, i);
2370                 if (srb != NULL) {
2371                         srb->cmd->result = res;
2372                         kref_put(&srb->srb_ref, qla4xxx_srb_compl);
2373                 }
2374         }
2375         spin_unlock_irqrestore(&ha->hardware_lock, flags);
2376 }
2377
2378 void qla4xxx_dead_adapter_cleanup(struct scsi_qla_host *ha)
2379 {
2380         clear_bit(AF_ONLINE, &ha->flags);
2381
2382         /* Disable the board */
2383         ql4_printk(KERN_INFO, ha, "Disabling the board\n");
2384
2385         qla4xxx_abort_active_cmds(ha, DID_NO_CONNECT << 16);
2386         qla4xxx_mark_all_devices_missing(ha);
2387         clear_bit(AF_INIT_DONE, &ha->flags);
2388 }
2389
2390 static void qla4xxx_fail_session(struct iscsi_cls_session *cls_session)
2391 {
2392         struct iscsi_session *sess;
2393         struct ddb_entry *ddb_entry;
2394
2395         sess = cls_session->dd_data;
2396         ddb_entry = sess->dd_data;
2397         ddb_entry->fw_ddb_device_state = DDB_DS_SESSION_FAILED;
2398
2399         if (ddb_entry->ddb_type == FLASH_DDB)
2400                 iscsi_block_session(ddb_entry->sess);
2401         else
2402                 iscsi_session_failure(cls_session->dd_data,
2403                                       ISCSI_ERR_CONN_FAILED);
2404 }
2405
2406 /**
2407  * qla4xxx_recover_adapter - recovers adapter after a fatal error
2408  * @ha: Pointer to host adapter structure.
2409  **/
2410 static int qla4xxx_recover_adapter(struct scsi_qla_host *ha)
2411 {
2412         int status = QLA_ERROR;
2413         uint8_t reset_chip = 0;
2414
2415         /* Stall incoming I/O until we are done */
2416         scsi_block_requests(ha->host);
2417         clear_bit(AF_ONLINE, &ha->flags);
2418         clear_bit(AF_LINK_UP, &ha->flags);
2419
2420         DEBUG2(ql4_printk(KERN_INFO, ha, "%s: adapter OFFLINE\n", __func__));
2421
2422         set_bit(DPC_RESET_ACTIVE, &ha->dpc_flags);
2423
2424         iscsi_host_for_each_session(ha->host, qla4xxx_fail_session);
2425
2426         if (test_bit(DPC_RESET_HA, &ha->dpc_flags))
2427                 reset_chip = 1;
2428
2429         /* For the DPC_RESET_HA_INTR case (ISP-4xxx specific)
2430          * do not reset adapter, jump to initialize_adapter */
2431         if (test_bit(DPC_RESET_HA_INTR, &ha->dpc_flags)) {
2432                 status = QLA_SUCCESS;
2433                 goto recover_ha_init_adapter;
2434         }
2435
2436         /* For the ISP-82xx adapter, issue a stop_firmware if invoked
2437          * from eh_host_reset or ioctl module */
2438         if (is_qla8022(ha) && !reset_chip &&
2439             test_bit(DPC_RESET_HA_FW_CONTEXT, &ha->dpc_flags)) {
2440
2441                 DEBUG2(ql4_printk(KERN_INFO, ha,
2442                     "scsi%ld: %s - Performing stop_firmware...\n",
2443                     ha->host_no, __func__));
2444                 status = ha->isp_ops->reset_firmware(ha);
2445                 if (status == QLA_SUCCESS) {
2446                         if (!test_bit(AF_FW_RECOVERY, &ha->flags))
2447                                 qla4xxx_cmd_wait(ha);
2448                         ha->isp_ops->disable_intrs(ha);
2449                         qla4xxx_process_aen(ha, FLUSH_DDB_CHANGED_AENS);
2450                         qla4xxx_abort_active_cmds(ha, DID_RESET << 16);
2451                 } else {
2452                         /* If the stop_firmware fails then
2453                          * reset the entire chip */
2454                         reset_chip = 1;
2455                         clear_bit(DPC_RESET_HA_FW_CONTEXT, &ha->dpc_flags);
2456                         set_bit(DPC_RESET_HA, &ha->dpc_flags);
2457                 }
2458         }
2459
2460         /* Issue full chip reset if recovering from a catastrophic error,
2461          * or if stop_firmware fails for ISP-82xx.
2462          * This is the default case for ISP-4xxx */
2463         if (!is_qla8022(ha) || reset_chip) {
2464                 if (!test_bit(AF_FW_RECOVERY, &ha->flags))
2465                         qla4xxx_cmd_wait(ha);
2466                 qla4xxx_process_aen(ha, FLUSH_DDB_CHANGED_AENS);
2467                 qla4xxx_abort_active_cmds(ha, DID_RESET << 16);
2468                 DEBUG2(ql4_printk(KERN_INFO, ha,
2469                     "scsi%ld: %s - Performing chip reset..\n",
2470                     ha->host_no, __func__));
2471                 status = ha->isp_ops->reset_chip(ha);
2472         }
2473
2474         /* Flush any pending ddb changed AENs */
2475         qla4xxx_process_aen(ha, FLUSH_DDB_CHANGED_AENS);
2476
2477 recover_ha_init_adapter:
2478         /* Upon successful firmware/chip reset, re-initialize the adapter */
2479         if (status == QLA_SUCCESS) {
2480                 /* For ISP-4xxx, force function 1 to always initialize
2481                  * before function 3 to prevent both funcions from
2482                  * stepping on top of the other */
2483                 if (!is_qla8022(ha) && (ha->mac_index == 3))
2484                         ssleep(6);
2485
2486                 /* NOTE: AF_ONLINE flag set upon successful completion of
2487                  *       qla4xxx_initialize_adapter */
2488                 status = qla4xxx_initialize_adapter(ha, RESET_ADAPTER);
2489         }
2490
2491         /* Retry failed adapter initialization, if necessary
2492          * Do not retry initialize_adapter for RESET_HA_INTR (ISP-4xxx specific)
2493          * case to prevent ping-pong resets between functions */
2494         if (!test_bit(AF_ONLINE, &ha->flags) &&
2495             !test_bit(DPC_RESET_HA_INTR, &ha->dpc_flags)) {
2496                 /* Adapter initialization failed, see if we can retry
2497                  * resetting the ha.
2498                  * Since we don't want to block the DPC for too long
2499                  * with multiple resets in the same thread,
2500                  * utilize DPC to retry */
2501                 if (!test_bit(DPC_RETRY_RESET_HA, &ha->dpc_flags)) {
2502                         ha->retry_reset_ha_cnt = MAX_RESET_HA_RETRIES;
2503                         DEBUG2(printk("scsi%ld: recover adapter - retrying "
2504                                       "(%d) more times\n", ha->host_no,
2505                                       ha->retry_reset_ha_cnt));
2506                         set_bit(DPC_RETRY_RESET_HA, &ha->dpc_flags);
2507                         status = QLA_ERROR;
2508                 } else {
2509                         if (ha->retry_reset_ha_cnt > 0) {
2510                                 /* Schedule another Reset HA--DPC will retry */
2511                                 ha->retry_reset_ha_cnt--;
2512                                 DEBUG2(printk("scsi%ld: recover adapter - "
2513                                               "retry remaining %d\n",
2514                                               ha->host_no,
2515                                               ha->retry_reset_ha_cnt));
2516                                 status = QLA_ERROR;
2517                         }
2518
2519                         if (ha->retry_reset_ha_cnt == 0) {
2520                                 /* Recover adapter retries have been exhausted.
2521                                  * Adapter DEAD */
2522                                 DEBUG2(printk("scsi%ld: recover adapter "
2523                                               "failed - board disabled\n",
2524                                               ha->host_no));
2525                                 qla4xxx_dead_adapter_cleanup(ha);
2526                                 clear_bit(DPC_RETRY_RESET_HA, &ha->dpc_flags);
2527                                 clear_bit(DPC_RESET_HA, &ha->dpc_flags);
2528                                 clear_bit(DPC_RESET_HA_FW_CONTEXT,
2529                                           &ha->dpc_flags);
2530                                 status = QLA_ERROR;
2531                         }
2532                 }
2533         } else {
2534                 clear_bit(DPC_RESET_HA, &ha->dpc_flags);
2535                 clear_bit(DPC_RESET_HA_FW_CONTEXT, &ha->dpc_flags);
2536                 clear_bit(DPC_RETRY_RESET_HA, &ha->dpc_flags);
2537         }
2538
2539         ha->adapter_error_count++;
2540
2541         if (test_bit(AF_ONLINE, &ha->flags))
2542                 ha->isp_ops->enable_intrs(ha);
2543
2544         scsi_unblock_requests(ha->host);
2545
2546         clear_bit(DPC_RESET_ACTIVE, &ha->dpc_flags);
2547         DEBUG2(printk("scsi%ld: recover adapter: %s\n", ha->host_no,
2548             status == QLA_ERROR ? "FAILED" : "SUCCEEDED"));
2549
2550         return status;
2551 }
2552
2553 static void qla4xxx_relogin_devices(struct iscsi_cls_session *cls_session)
2554 {
2555         struct iscsi_session *sess;
2556         struct ddb_entry *ddb_entry;
2557         struct scsi_qla_host *ha;
2558
2559         sess = cls_session->dd_data;
2560         ddb_entry = sess->dd_data;
2561         ha = ddb_entry->ha;
2562         if (!iscsi_is_session_online(cls_session)) {
2563                 if (ddb_entry->fw_ddb_device_state == DDB_DS_SESSION_ACTIVE) {
2564                         ql4_printk(KERN_INFO, ha, "scsi%ld: %s: ddb[%d]"
2565                                    " unblock session\n", ha->host_no, __func__,
2566                                    ddb_entry->fw_ddb_index);
2567                         iscsi_unblock_session(ddb_entry->sess);
2568                 } else {
2569                         /* Trigger relogin */
2570                         if (ddb_entry->ddb_type == FLASH_DDB) {
2571                                 if (!test_bit(DF_RELOGIN, &ddb_entry->flags))
2572                                         qla4xxx_arm_relogin_timer(ddb_entry);
2573                         } else
2574                                 iscsi_session_failure(cls_session->dd_data,
2575                                                       ISCSI_ERR_CONN_FAILED);
2576                 }
2577         }
2578 }
2579
2580 int qla4xxx_unblock_flash_ddb(struct iscsi_cls_session *cls_session)
2581 {
2582         struct iscsi_session *sess;
2583         struct ddb_entry *ddb_entry;
2584         struct scsi_qla_host *ha;
2585
2586         sess = cls_session->dd_data;
2587         ddb_entry = sess->dd_data;
2588         ha = ddb_entry->ha;
2589         ql4_printk(KERN_INFO, ha, "scsi%ld: %s: ddb[%d]"
2590                    " unblock session\n", ha->host_no, __func__,
2591                    ddb_entry->fw_ddb_index);
2592
2593         iscsi_unblock_session(ddb_entry->sess);
2594
2595         /* Start scan target */
2596         if (test_bit(AF_ONLINE, &ha->flags)) {
2597                 ql4_printk(KERN_INFO, ha, "scsi%ld: %s: ddb[%d]"
2598                            " start scan\n", ha->host_no, __func__,
2599                            ddb_entry->fw_ddb_index);
2600                 scsi_queue_work(ha->host, &ddb_entry->sess->scan_work);
2601         }
2602         return QLA_SUCCESS;
2603 }
2604
2605 int qla4xxx_unblock_ddb(struct iscsi_cls_session *cls_session)
2606 {
2607         struct iscsi_session *sess;
2608         struct ddb_entry *ddb_entry;
2609         struct scsi_qla_host *ha;
2610
2611         sess = cls_session->dd_data;
2612         ddb_entry = sess->dd_data;
2613         ha = ddb_entry->ha;
2614         ql4_printk(KERN_INFO, ha, "scsi%ld: %s: ddb[%d]"
2615                    " unblock user space session\n", ha->host_no, __func__,
2616                    ddb_entry->fw_ddb_index);
2617         iscsi_conn_start(ddb_entry->conn);
2618         iscsi_conn_login_event(ddb_entry->conn,
2619                                ISCSI_CONN_STATE_LOGGED_IN);
2620
2621         return QLA_SUCCESS;
2622 }
2623
2624 static void qla4xxx_relogin_all_devices(struct scsi_qla_host *ha)
2625 {
2626         iscsi_host_for_each_session(ha->host, qla4xxx_relogin_devices);
2627 }
2628
2629 static void qla4xxx_relogin_flash_ddb(struct iscsi_cls_session *cls_sess)
2630 {
2631         uint16_t relogin_timer;
2632         struct iscsi_session *sess;
2633         struct ddb_entry *ddb_entry;
2634         struct scsi_qla_host *ha;
2635
2636         sess = cls_sess->dd_data;
2637         ddb_entry = sess->dd_data;
2638         ha = ddb_entry->ha;
2639
2640         relogin_timer = max(ddb_entry->default_relogin_timeout,
2641                             (uint16_t)RELOGIN_TOV);
2642         atomic_set(&ddb_entry->relogin_timer, relogin_timer);
2643
2644         DEBUG2(ql4_printk(KERN_INFO, ha,
2645                           "scsi%ld: Relogin index [%d]. TOV=%d\n", ha->host_no,
2646                           ddb_entry->fw_ddb_index, relogin_timer));
2647
2648         qla4xxx_login_flash_ddb(cls_sess);
2649 }
2650
2651 static void qla4xxx_dpc_relogin(struct iscsi_cls_session *cls_sess)
2652 {
2653         struct iscsi_session *sess;
2654         struct ddb_entry *ddb_entry;
2655         struct scsi_qla_host *ha;
2656
2657         sess = cls_sess->dd_data;
2658         ddb_entry = sess->dd_data;
2659         ha = ddb_entry->ha;
2660
2661         if (!(ddb_entry->ddb_type == FLASH_DDB))
2662                 return;
2663
2664         if (test_and_clear_bit(DF_RELOGIN, &ddb_entry->flags) &&
2665             !iscsi_is_session_online(cls_sess)) {
2666                 DEBUG2(ql4_printk(KERN_INFO, ha,
2667                                   "relogin issued\n"));
2668                 qla4xxx_relogin_flash_ddb(cls_sess);
2669         }
2670 }
2671
2672 void qla4xxx_wake_dpc(struct scsi_qla_host *ha)
2673 {
2674         if (ha->dpc_thread)
2675                 queue_work(ha->dpc_thread, &ha->dpc_work);
2676 }
2677
2678 /**
2679  * qla4xxx_do_dpc - dpc routine
2680  * @data: in our case pointer to adapter structure
2681  *
2682  * This routine is a task that is schedule by the interrupt handler
2683  * to perform the background processing for interrupts.  We put it
2684  * on a task queue that is consumed whenever the scheduler runs; that's
2685  * so you can do anything (i.e. put the process to sleep etc).  In fact,
2686  * the mid-level tries to sleep when it reaches the driver threshold
2687  * "host->can_queue". This can cause a panic if we were in our interrupt code.
2688  **/
2689 static void qla4xxx_do_dpc(struct work_struct *work)
2690 {
2691         struct scsi_qla_host *ha =
2692                 container_of(work, struct scsi_qla_host, dpc_work);
2693         int status = QLA_ERROR;
2694
2695         DEBUG2(printk("scsi%ld: %s: DPC handler waking up."
2696             "flags = 0x%08lx, dpc_flags = 0x%08lx\n",
2697             ha->host_no, __func__, ha->flags, ha->dpc_flags))
2698
2699         /* Initialization not yet finished. Don't do anything yet. */
2700         if (!test_bit(AF_INIT_DONE, &ha->flags))
2701                 return;
2702
2703         if (test_bit(AF_EEH_BUSY, &ha->flags)) {
2704                 DEBUG2(printk(KERN_INFO "scsi%ld: %s: flags = %lx\n",
2705                     ha->host_no, __func__, ha->flags));
2706                 return;
2707         }
2708
2709         if (is_qla8022(ha)) {
2710                 if (test_bit(DPC_HA_UNRECOVERABLE, &ha->dpc_flags)) {
2711                         qla4_8xxx_idc_lock(ha);
2712                         qla4_8xxx_wr_32(ha, QLA82XX_CRB_DEV_STATE,
2713                             QLA82XX_DEV_FAILED);
2714                         qla4_8xxx_idc_unlock(ha);
2715                         ql4_printk(KERN_INFO, ha, "HW State: FAILED\n");
2716                         qla4_8xxx_device_state_handler(ha);
2717                 }
2718                 if (test_and_clear_bit(DPC_HA_NEED_QUIESCENT, &ha->dpc_flags)) {
2719                         qla4_8xxx_need_qsnt_handler(ha);
2720                 }
2721         }
2722
2723         if (!test_bit(DPC_RESET_ACTIVE, &ha->dpc_flags) &&
2724             (test_bit(DPC_RESET_HA, &ha->dpc_flags) ||
2725             test_bit(DPC_RESET_HA_INTR, &ha->dpc_flags) ||
2726             test_bit(DPC_RESET_HA_FW_CONTEXT, &ha->dpc_flags))) {
2727                 if (ql4xdontresethba) {
2728                         DEBUG2(printk("scsi%ld: %s: Don't Reset HBA\n",
2729                             ha->host_no, __func__));
2730                         clear_bit(DPC_RESET_HA, &ha->dpc_flags);
2731                         clear_bit(DPC_RESET_HA_INTR, &ha->dpc_flags);
2732                         clear_bit(DPC_RESET_HA_FW_CONTEXT, &ha->dpc_flags);
2733                         goto dpc_post_reset_ha;
2734                 }
2735                 if (test_bit(DPC_RESET_HA_FW_CONTEXT, &ha->dpc_flags) ||
2736                     test_bit(DPC_RESET_HA, &ha->dpc_flags))
2737                         qla4xxx_recover_adapter(ha);
2738
2739                 if (test_bit(DPC_RESET_HA_INTR, &ha->dpc_flags)) {
2740                         uint8_t wait_time = RESET_INTR_TOV;
2741
2742                         while ((readw(&ha->reg->ctrl_status) &
2743                                 (CSR_SOFT_RESET | CSR_FORCE_SOFT_RESET)) != 0) {
2744                                 if (--wait_time == 0)
2745                                         break;
2746                                 msleep(1000);
2747                         }
2748                         if (wait_time == 0)
2749                                 DEBUG2(printk("scsi%ld: %s: SR|FSR "
2750                                               "bit not cleared-- resetting\n",
2751                                               ha->host_no, __func__));
2752                         qla4xxx_abort_active_cmds(ha, DID_RESET << 16);
2753                         if (ql4xxx_lock_drvr_wait(ha) == QLA_SUCCESS) {
2754                                 qla4xxx_process_aen(ha, FLUSH_DDB_CHANGED_AENS);
2755                                 status = qla4xxx_recover_adapter(ha);
2756                         }
2757                         clear_bit(DPC_RESET_HA_INTR, &ha->dpc_flags);
2758                         if (status == QLA_SUCCESS)
2759                                 ha->isp_ops->enable_intrs(ha);
2760                 }
2761         }
2762
2763 dpc_post_reset_ha:
2764         /* ---- process AEN? --- */
2765         if (test_and_clear_bit(DPC_AEN, &ha->dpc_flags))
2766                 qla4xxx_process_aen(ha, PROCESS_ALL_AENS);
2767
2768         /* ---- Get DHCP IP Address? --- */
2769         if (test_and_clear_bit(DPC_GET_DHCP_IP_ADDR, &ha->dpc_flags))
2770                 qla4xxx_get_dhcp_ip_address(ha);
2771
2772         /* ---- relogin device? --- */
2773         if (adapter_up(ha) &&
2774             test_and_clear_bit(DPC_RELOGIN_DEVICE, &ha->dpc_flags)) {
2775                 iscsi_host_for_each_session(ha->host, qla4xxx_dpc_relogin);
2776         }
2777
2778         /* ---- link change? --- */
2779         if (test_and_clear_bit(DPC_LINK_CHANGED, &ha->dpc_flags)) {
2780                 if (!test_bit(AF_LINK_UP, &ha->flags)) {
2781                         /* ---- link down? --- */
2782                         qla4xxx_mark_all_devices_missing(ha);
2783                 } else {
2784                         /* ---- link up? --- *
2785                          * F/W will auto login to all devices ONLY ONCE after
2786                          * link up during driver initialization and runtime
2787                          * fatal error recovery.  Therefore, the driver must
2788                          * manually relogin to devices when recovering from
2789                          * connection failures, logouts, expired KATO, etc. */
2790                         if (test_and_clear_bit(AF_BUILD_DDB_LIST, &ha->flags)) {
2791                                 qla4xxx_build_ddb_list(ha, ha->is_reset);
2792                                 iscsi_host_for_each_session(ha->host,
2793                                                 qla4xxx_login_flash_ddb);
2794                         } else
2795                                 qla4xxx_relogin_all_devices(ha);
2796                 }
2797         }
2798 }
2799
2800 /**
2801  * qla4xxx_free_adapter - release the adapter
2802  * @ha: pointer to adapter structure
2803  **/
2804 static void qla4xxx_free_adapter(struct scsi_qla_host *ha)
2805 {
2806
2807         if (test_bit(AF_INTERRUPTS_ON, &ha->flags)) {
2808                 /* Turn-off interrupts on the card. */
2809                 ha->isp_ops->disable_intrs(ha);
2810         }
2811
2812         /* Remove timer thread, if present */
2813         if (ha->timer_active)
2814                 qla4xxx_stop_timer(ha);
2815
2816         /* Kill the kernel thread for this host */
2817         if (ha->dpc_thread)
2818                 destroy_workqueue(ha->dpc_thread);
2819
2820         /* Kill the kernel thread for this host */
2821         if (ha->task_wq)
2822                 destroy_workqueue(ha->task_wq);
2823
2824         /* Put firmware in known state */
2825         ha->isp_ops->reset_firmware(ha);
2826
2827         if (is_qla8022(ha)) {
2828                 qla4_8xxx_idc_lock(ha);
2829                 qla4_8xxx_clear_drv_active(ha);
2830                 qla4_8xxx_idc_unlock(ha);
2831         }
2832
2833         /* Detach interrupts */
2834         if (test_and_clear_bit(AF_IRQ_ATTACHED, &ha->flags))
2835                 qla4xxx_free_irqs(ha);
2836
2837         /* free extra memory */
2838         qla4xxx_mem_free(ha);
2839 }
2840
2841 int qla4_8xxx_iospace_config(struct scsi_qla_host *ha)
2842 {
2843         int status = 0;
2844         uint8_t revision_id;
2845         unsigned long mem_base, mem_len, db_base, db_len;
2846         struct pci_dev *pdev = ha->pdev;
2847
2848         status = pci_request_regions(pdev, DRIVER_NAME);
2849         if (status) {
2850                 printk(KERN_WARNING
2851                     "scsi(%ld) Failed to reserve PIO regions (%s) "
2852                     "status=%d\n", ha->host_no, pci_name(pdev), status);
2853                 goto iospace_error_exit;
2854         }
2855
2856         pci_read_config_byte(pdev, PCI_REVISION_ID, &revision_id);
2857         DEBUG2(printk(KERN_INFO "%s: revision-id=%d\n",
2858             __func__, revision_id));
2859         ha->revision_id = revision_id;
2860
2861         /* remap phys address */
2862         mem_base = pci_resource_start(pdev, 0); /* 0 is for BAR 0 */
2863         mem_len = pci_resource_len(pdev, 0);
2864         DEBUG2(printk(KERN_INFO "%s: ioremap from %lx a size of %lx\n",
2865             __func__, mem_base, mem_len));
2866
2867         /* mapping of pcibase pointer */
2868         ha->nx_pcibase = (unsigned long)ioremap(mem_base, mem_len);
2869         if (!ha->nx_pcibase) {
2870                 printk(KERN_ERR
2871                     "cannot remap MMIO (%s), aborting\n", pci_name(pdev));
2872                 pci_release_regions(ha->pdev);
2873                 goto iospace_error_exit;
2874         }
2875
2876         /* Mapping of IO base pointer, door bell read and write pointer */
2877
2878         /* mapping of IO base pointer */
2879         ha->qla4_8xxx_reg =
2880             (struct device_reg_82xx  __iomem *)((uint8_t *)ha->nx_pcibase +
2881             0xbc000 + (ha->pdev->devfn << 11));
2882
2883         db_base = pci_resource_start(pdev, 4);  /* doorbell is on bar 4 */
2884         db_len = pci_resource_len(pdev, 4);
2885
2886         ha->nx_db_wr_ptr = (ha->pdev->devfn == 4 ? QLA82XX_CAM_RAM_DB1 :
2887             QLA82XX_CAM_RAM_DB2);
2888
2889         return 0;
2890 iospace_error_exit:
2891         return -ENOMEM;
2892 }
2893
2894 /***
2895  * qla4xxx_iospace_config - maps registers
2896  * @ha: pointer to adapter structure
2897  *
2898  * This routines maps HBA's registers from the pci address space
2899  * into the kernel virtual address space for memory mapped i/o.
2900  **/
2901 int qla4xxx_iospace_config(struct scsi_qla_host *ha)
2902 {
2903         unsigned long pio, pio_len, pio_flags;
2904         unsigned long mmio, mmio_len, mmio_flags;
2905
2906         pio = pci_resource_start(ha->pdev, 0);
2907         pio_len = pci_resource_len(ha->pdev, 0);
2908         pio_flags = pci_resource_flags(ha->pdev, 0);
2909         if (pio_flags & IORESOURCE_IO) {
2910                 if (pio_len < MIN_IOBASE_LEN) {
2911                         ql4_printk(KERN_WARNING, ha,
2912                                 "Invalid PCI I/O region size\n");
2913                         pio = 0;
2914                 }
2915         } else {
2916                 ql4_printk(KERN_WARNING, ha, "region #0 not a PIO resource\n");
2917                 pio = 0;
2918         }
2919
2920         /* Use MMIO operations for all accesses. */
2921         mmio = pci_resource_start(ha->pdev, 1);
2922         mmio_len = pci_resource_len(ha->pdev, 1);
2923         mmio_flags = pci_resource_flags(ha->pdev, 1);
2924
2925         if (!(mmio_flags & IORESOURCE_MEM)) {
2926                 ql4_printk(KERN_ERR, ha,
2927                     "region #0 not an MMIO resource, aborting\n");
2928
2929                 goto iospace_error_exit;
2930         }
2931
2932         if (mmio_len < MIN_IOBASE_LEN) {
2933                 ql4_printk(KERN_ERR, ha,
2934                     "Invalid PCI mem region size, aborting\n");
2935                 goto iospace_error_exit;
2936         }
2937
2938         if (pci_request_regions(ha->pdev, DRIVER_NAME)) {
2939                 ql4_printk(KERN_WARNING, ha,
2940                     "Failed to reserve PIO/MMIO regions\n");
2941
2942                 goto iospace_error_exit;
2943         }
2944
2945         ha->pio_address = pio;
2946         ha->pio_length = pio_len;
2947         ha->reg = ioremap(mmio, MIN_IOBASE_LEN);
2948         if (!ha->reg) {
2949                 ql4_printk(KERN_ERR, ha,
2950                     "cannot remap MMIO, aborting\n");
2951
2952                 goto iospace_error_exit;
2953         }
2954
2955         return 0;
2956
2957 iospace_error_exit:
2958         return -ENOMEM;
2959 }
2960
2961 static struct isp_operations qla4xxx_isp_ops = {
2962         .iospace_config         = qla4xxx_iospace_config,
2963         .pci_config             = qla4xxx_pci_config,
2964         .disable_intrs          = qla4xxx_disable_intrs,
2965         .enable_intrs           = qla4xxx_enable_intrs,
2966         .start_firmware         = qla4xxx_start_firmware,
2967         .intr_handler           = qla4xxx_intr_handler,
2968         .interrupt_service_routine = qla4xxx_interrupt_service_routine,
2969         .reset_chip             = qla4xxx_soft_reset,
2970         .reset_firmware         = qla4xxx_hw_reset,
2971         .queue_iocb             = qla4xxx_queue_iocb,
2972         .complete_iocb          = qla4xxx_complete_iocb,
2973         .rd_shdw_req_q_out      = qla4xxx_rd_shdw_req_q_out,
2974         .rd_shdw_rsp_q_in       = qla4xxx_rd_shdw_rsp_q_in,
2975         .get_sys_info           = qla4xxx_get_sys_info,
2976 };
2977
2978 static struct isp_operations qla4_8xxx_isp_ops = {
2979         .iospace_config         = qla4_8xxx_iospace_config,
2980         .pci_config             = qla4_8xxx_pci_config,
2981         .disable_intrs          = qla4_8xxx_disable_intrs,
2982         .enable_intrs           = qla4_8xxx_enable_intrs,
2983         .start_firmware         = qla4_8xxx_load_risc,
2984         .intr_handler           = qla4_8xxx_intr_handler,
2985         .interrupt_service_routine = qla4_8xxx_interrupt_service_routine,
2986         .reset_chip             = qla4_8xxx_isp_reset,
2987         .reset_firmware         = qla4_8xxx_stop_firmware,
2988         .queue_iocb             = qla4_8xxx_queue_iocb,
2989         .complete_iocb          = qla4_8xxx_complete_iocb,
2990         .rd_shdw_req_q_out      = qla4_8xxx_rd_shdw_req_q_out,
2991         .rd_shdw_rsp_q_in       = qla4_8xxx_rd_shdw_rsp_q_in,
2992         .get_sys_info           = qla4_8xxx_get_sys_info,
2993 };
2994
2995 uint16_t qla4xxx_rd_shdw_req_q_out(struct scsi_qla_host *ha)
2996 {
2997         return (uint16_t)le32_to_cpu(ha->shadow_regs->req_q_out);
2998 }
2999
3000 uint16_t qla4_8xxx_rd_shdw_req_q_out(struct scsi_qla_host *ha)
3001 {
3002         return (uint16_t)le32_to_cpu(readl(&ha->qla4_8xxx_reg->req_q_out));
3003 }
3004
3005 uint16_t qla4xxx_rd_shdw_rsp_q_in(struct scsi_qla_host *ha)
3006 {
3007         return (uint16_t)le32_to_cpu(ha->shadow_regs->rsp_q_in);
3008 }
3009
3010 uint16_t qla4_8xxx_rd_shdw_rsp_q_in(struct scsi_qla_host *ha)
3011 {
3012         return (uint16_t)le32_to_cpu(readl(&ha->qla4_8xxx_reg->rsp_q_in));
3013 }
3014
3015 static ssize_t qla4xxx_show_boot_eth_info(void *data, int type, char *buf)
3016 {
3017         struct scsi_qla_host *ha = data;
3018         char *str = buf;
3019         int rc;
3020
3021         switch (type) {
3022         case ISCSI_BOOT_ETH_FLAGS:
3023                 rc = sprintf(str, "%d\n", SYSFS_FLAG_FW_SEL_BOOT);
3024                 break;
3025         case ISCSI_BOOT_ETH_INDEX:
3026                 rc = sprintf(str, "0\n");
3027                 break;
3028         case ISCSI_BOOT_ETH_MAC:
3029                 rc = sysfs_format_mac(str, ha->my_mac,
3030                                       MAC_ADDR_LEN);
3031                 break;
3032         default:
3033                 rc = -ENOSYS;
3034                 break;
3035         }
3036         return rc;
3037 }
3038
3039 static mode_t qla4xxx_eth_get_attr_visibility(void *data, int type)
3040 {
3041         int rc;
3042
3043         switch (type) {
3044         case ISCSI_BOOT_ETH_FLAGS:
3045         case ISCSI_BOOT_ETH_MAC:
3046         case ISCSI_BOOT_ETH_INDEX:
3047                 rc = S_IRUGO;
3048                 break;
3049         default:
3050                 rc = 0;
3051                 break;
3052         }
3053         return rc;
3054 }
3055
3056 static ssize_t qla4xxx_show_boot_ini_info(void *data, int type, char *buf)
3057 {
3058         struct scsi_qla_host *ha = data;
3059         char *str = buf;
3060         int rc;
3061
3062         switch (type) {
3063         case ISCSI_BOOT_INI_INITIATOR_NAME:
3064                 rc = sprintf(str, "%s\n", ha->name_string);
3065                 break;
3066         default:
3067                 rc = -ENOSYS;
3068                 break;
3069         }
3070         return rc;
3071 }
3072
3073 static mode_t qla4xxx_ini_get_attr_visibility(void *data, int type)
3074 {
3075         int rc;
3076
3077         switch (type) {
3078         case ISCSI_BOOT_INI_INITIATOR_NAME:
3079                 rc = S_IRUGO;
3080                 break;
3081         default:
3082                 rc = 0;
3083                 break;
3084         }
3085         return rc;
3086 }
3087
3088 static ssize_t
3089 qla4xxx_show_boot_tgt_info(struct ql4_boot_session_info *boot_sess, int type,
3090                            char *buf)
3091 {
3092         struct ql4_conn_info *boot_conn = &boot_sess->conn_list[0];
3093         char *str = buf;
3094         int rc;
3095
3096         switch (type) {
3097         case ISCSI_BOOT_TGT_NAME:
3098                 rc = sprintf(buf, "%s\n", (char *)&boot_sess->target_name);
3099                 break;
3100         case ISCSI_BOOT_TGT_IP_ADDR:
3101                 if (boot_sess->conn_list[0].dest_ipaddr.ip_type == 0x1)
3102                         rc = sprintf(buf, "%pI4\n",
3103                                      &boot_conn->dest_ipaddr.ip_address);
3104                 else
3105                         rc = sprintf(str, "%pI6\n",
3106                                      &boot_conn->dest_ipaddr.ip_address);
3107                 break;
3108         case ISCSI_BOOT_TGT_PORT:
3109                         rc = sprintf(str, "%d\n", boot_conn->dest_port);
3110                 break;
3111         case ISCSI_BOOT_TGT_CHAP_NAME:
3112                 rc = sprintf(str,  "%.*s\n",
3113                              boot_conn->chap.target_chap_name_length,
3114                              (char *)&boot_conn->chap.target_chap_name);
3115                 break;
3116         case ISCSI_BOOT_TGT_CHAP_SECRET:
3117                 rc = sprintf(str,  "%.*s\n",
3118                              boot_conn->chap.target_secret_length,
3119                              (char *)&boot_conn->chap.target_secret);
3120                 break;
3121         case ISCSI_BOOT_TGT_REV_CHAP_NAME:
3122                 rc = sprintf(str,  "%.*s\n",
3123                              boot_conn->chap.intr_chap_name_length,
3124                              (char *)&boot_conn->chap.intr_chap_name);
3125                 break;
3126         case ISCSI_BOOT_TGT_REV_CHAP_SECRET:
3127                 rc = sprintf(str,  "%.*s\n",
3128                              boot_conn->chap.intr_secret_length,
3129                              (char *)&boot_conn->chap.intr_secret);
3130                 break;
3131         case ISCSI_BOOT_TGT_FLAGS:
3132                 rc = sprintf(str, "%d\n", SYSFS_FLAG_FW_SEL_BOOT);
3133                 break;
3134         case ISCSI_BOOT_TGT_NIC_ASSOC:
3135                 rc = sprintf(str, "0\n");
3136                 break;
3137         default:
3138                 rc = -ENOSYS;
3139                 break;
3140         }
3141         return rc;
3142 }
3143
3144 static ssize_t qla4xxx_show_boot_tgt_pri_info(void *data, int type, char *buf)
3145 {
3146         struct scsi_qla_host *ha = data;
3147         struct ql4_boot_session_info *boot_sess = &(ha->boot_tgt.boot_pri_sess);
3148
3149         return qla4xxx_show_boot_tgt_info(boot_sess, type, buf);
3150 }
3151
3152 static ssize_t qla4xxx_show_boot_tgt_sec_info(void *data, int type, char *buf)
3153 {
3154         struct scsi_qla_host *ha = data;
3155         struct ql4_boot_session_info *boot_sess = &(ha->boot_tgt.boot_sec_sess);
3156
3157         return qla4xxx_show_boot_tgt_info(boot_sess, type, buf);
3158 }
3159
3160 static mode_t qla4xxx_tgt_get_attr_visibility(void *data, int type)
3161 {
3162         int rc;
3163
3164         switch (type) {
3165         case ISCSI_BOOT_TGT_NAME:
3166         case ISCSI_BOOT_TGT_IP_ADDR:
3167         case ISCSI_BOOT_TGT_PORT:
3168         case ISCSI_BOOT_TGT_CHAP_NAME:
3169         case ISCSI_BOOT_TGT_CHAP_SECRET:
3170         case ISCSI_BOOT_TGT_REV_CHAP_NAME:
3171         case ISCSI_BOOT_TGT_REV_CHAP_SECRET:
3172         case ISCSI_BOOT_TGT_NIC_ASSOC:
3173         case ISCSI_BOOT_TGT_FLAGS:
3174                 rc = S_IRUGO;
3175                 break;
3176         default:
3177                 rc = 0;
3178                 break;
3179         }
3180         return rc;
3181 }
3182
3183 static void qla4xxx_boot_release(void *data)
3184 {
3185         struct scsi_qla_host *ha = data;
3186
3187         scsi_host_put(ha->host);
3188 }
3189
3190 static int get_fw_boot_info(struct scsi_qla_host *ha, uint16_t ddb_index[])
3191 {
3192         dma_addr_t buf_dma;
3193         uint32_t addr, pri_addr, sec_addr;
3194         uint32_t offset;
3195         uint16_t func_num;
3196         uint8_t val;
3197         uint8_t *buf = NULL;
3198         size_t size = 13 * sizeof(uint8_t);
3199         int ret = QLA_SUCCESS;
3200
3201         func_num = PCI_FUNC(ha->pdev->devfn);
3202
3203         ql4_printk(KERN_INFO, ha, "%s: Get FW boot info for 0x%x func %d\n",
3204                    __func__, ha->pdev->device, func_num);
3205
3206         if (is_qla40XX(ha)) {
3207                 if (func_num == 1) {
3208                         addr = NVRAM_PORT0_BOOT_MODE;
3209                         pri_addr = NVRAM_PORT0_BOOT_PRI_TGT;
3210                         sec_addr = NVRAM_PORT0_BOOT_SEC_TGT;
3211                 } else if (func_num == 3) {
3212                         addr = NVRAM_PORT1_BOOT_MODE;
3213                         pri_addr = NVRAM_PORT1_BOOT_PRI_TGT;
3214                         sec_addr = NVRAM_PORT1_BOOT_SEC_TGT;
3215                 } else {
3216                         ret = QLA_ERROR;
3217                         goto exit_boot_info;
3218                 }
3219
3220                 /* Check Boot Mode */
3221                 val = rd_nvram_byte(ha, addr);
3222                 if (!(val & 0x07)) {
3223                         DEBUG2(ql4_printk(KERN_ERR, ha,
3224                                           "%s: Failed Boot options : 0x%x\n",
3225                                           __func__, val));
3226                         ret = QLA_ERROR;
3227                         goto exit_boot_info;
3228                 }
3229
3230                 /* get primary valid target index */
3231                 val = rd_nvram_byte(ha, pri_addr);
3232                 if (val & BIT_7)
3233                         ddb_index[0] = (val & 0x7f);
3234
3235                 /* get secondary valid target index */
3236                 val = rd_nvram_byte(ha, sec_addr);
3237                 if (val & BIT_7)
3238                         ddb_index[1] = (val & 0x7f);
3239
3240         } else if (is_qla8022(ha)) {
3241                 buf = dma_alloc_coherent(&ha->pdev->dev, size,
3242                                          &buf_dma, GFP_KERNEL);
3243                 if (!buf) {
3244                         DEBUG2(ql4_printk(KERN_ERR, ha,
3245                                           "%s: Unable to allocate dma buffer\n",
3246                                            __func__));
3247                         ret = QLA_ERROR;
3248                         goto exit_boot_info;
3249                 }
3250
3251                 if (ha->port_num == 0)
3252                         offset = BOOT_PARAM_OFFSET_PORT0;
3253                 else if (ha->port_num == 1)
3254                         offset = BOOT_PARAM_OFFSET_PORT1;
3255                 else {
3256                         ret = QLA_ERROR;
3257                         goto exit_boot_info_free;
3258                 }
3259                 addr = FLASH_RAW_ACCESS_ADDR + (ha->hw.flt_iscsi_param * 4) +
3260                        offset;
3261                 if (qla4xxx_get_flash(ha, buf_dma, addr,
3262                                       13 * sizeof(uint8_t)) != QLA_SUCCESS) {
3263                         DEBUG2(ql4_printk(KERN_ERR, ha, "scsi%ld: %s: Get Flash"
3264                                           "failed\n", ha->host_no, __func__));
3265                         ret = QLA_ERROR;
3266                         goto exit_boot_info_free;
3267                 }
3268                 /* Check Boot Mode */
3269                 if (!(buf[1] & 0x07)) {
3270                         DEBUG2(ql4_printk(KERN_INFO, ha,
3271                                           "Failed: Boot options : 0x%x\n",
3272                                           buf[1]));
3273                         ret = QLA_ERROR;
3274                         goto exit_boot_info_free;
3275                 }
3276
3277                 /* get primary valid target index */
3278                 if (buf[2] & BIT_7)
3279                         ddb_index[0] = buf[2] & 0x7f;
3280
3281                 /* get secondary valid target index */
3282                 if (buf[11] & BIT_7)
3283                         ddb_index[1] = buf[11] & 0x7f;
3284         } else {
3285                 ret = QLA_ERROR;
3286                 goto exit_boot_info;
3287         }
3288
3289         DEBUG2(ql4_printk(KERN_INFO, ha, "%s: Primary target ID %d, Secondary"
3290                           " target ID %d\n", __func__, ddb_index[0],
3291                           ddb_index[1]));
3292
3293         ha->pri_ddb_idx = ddb_index[0];
3294         ha->sec_ddb_idx = ddb_index[1];
3295
3296 exit_boot_info_free:
3297         dma_free_coherent(&ha->pdev->dev, size, buf, buf_dma);
3298 exit_boot_info:
3299         return ret;
3300 }
3301
3302 /**
3303  * qla4xxx_get_bidi_chap - Get a BIDI CHAP user and password
3304  * @ha: pointer to adapter structure
3305  * @username: CHAP username to be returned
3306  * @password: CHAP password to be returned
3307  *
3308  * If a boot entry has BIDI CHAP enabled then we need to set the BIDI CHAP
3309  * user and password in the sysfs entry in /sys/firmware/iscsi_boot#/.
3310  * So from the CHAP cache find the first BIDI CHAP entry and set it
3311  * to the boot record in sysfs.
3312  **/
3313 static int qla4xxx_get_bidi_chap(struct scsi_qla_host *ha, char *username,
3314                             char *password)
3315 {
3316         int i, ret = -EINVAL;
3317         int max_chap_entries = 0;
3318         struct ql4_chap_table *chap_table;
3319
3320         if (is_qla8022(ha))
3321                 max_chap_entries = (ha->hw.flt_chap_size / 2) /
3322                                                 sizeof(struct ql4_chap_table);
3323         else
3324                 max_chap_entries = MAX_CHAP_ENTRIES_40XX;
3325
3326         if (!ha->chap_list) {
3327                 ql4_printk(KERN_ERR, ha, "Do not have CHAP table cache\n");
3328                 return ret;
3329         }
3330
3331         mutex_lock(&ha->chap_sem);
3332         for (i = 0; i < max_chap_entries; i++) {
3333                 chap_table = (struct ql4_chap_table *)ha->chap_list + i;
3334                 if (chap_table->cookie !=
3335                     __constant_cpu_to_le16(CHAP_VALID_COOKIE)) {
3336                         continue;
3337                 }
3338
3339                 if (chap_table->flags & BIT_7) /* local */
3340                         continue;
3341
3342                 if (!(chap_table->flags & BIT_6)) /* Not BIDI */
3343                         continue;
3344
3345                 strncpy(password, chap_table->secret, QL4_CHAP_MAX_SECRET_LEN);
3346                 strncpy(username, chap_table->name, QL4_CHAP_MAX_NAME_LEN);
3347                 ret = 0;
3348                 break;
3349         }
3350         mutex_unlock(&ha->chap_sem);
3351
3352         return ret;
3353 }
3354
3355
3356 static int qla4xxx_get_boot_target(struct scsi_qla_host *ha,
3357                                    struct ql4_boot_session_info *boot_sess,
3358                                    uint16_t ddb_index)
3359 {
3360         struct ql4_conn_info *boot_conn = &boot_sess->conn_list[0];
3361         struct dev_db_entry *fw_ddb_entry;
3362         dma_addr_t fw_ddb_entry_dma;
3363         uint16_t idx;
3364         uint16_t options;
3365         int ret = QLA_SUCCESS;
3366
3367         fw_ddb_entry = dma_alloc_coherent(&ha->pdev->dev, sizeof(*fw_ddb_entry),
3368                                           &fw_ddb_entry_dma, GFP_KERNEL);
3369         if (!fw_ddb_entry) {
3370                 DEBUG2(ql4_printk(KERN_ERR, ha,
3371                                   "%s: Unable to allocate dma buffer.\n",
3372                                   __func__));
3373                 ret = QLA_ERROR;
3374                 return ret;
3375         }
3376
3377         if (qla4xxx_bootdb_by_index(ha, fw_ddb_entry,
3378                                    fw_ddb_entry_dma, ddb_index)) {
3379                 DEBUG2(ql4_printk(KERN_ERR, ha,
3380                                   "%s: Flash DDB read Failed\n", __func__));
3381                 ret = QLA_ERROR;
3382                 goto exit_boot_target;
3383         }
3384
3385         /* Update target name and IP from DDB */
3386         memcpy(boot_sess->target_name, fw_ddb_entry->iscsi_name,
3387                min(sizeof(boot_sess->target_name),
3388                    sizeof(fw_ddb_entry->iscsi_name)));
3389
3390         options = le16_to_cpu(fw_ddb_entry->options);
3391         if (options & DDB_OPT_IPV6_DEVICE) {
3392                 memcpy(&boot_conn->dest_ipaddr.ip_address,
3393                        &fw_ddb_entry->ip_addr[0], IPv6_ADDR_LEN);
3394         } else {
3395                 boot_conn->dest_ipaddr.ip_type = 0x1;
3396                 memcpy(&boot_conn->dest_ipaddr.ip_address,
3397                        &fw_ddb_entry->ip_addr[0], IP_ADDR_LEN);
3398         }
3399
3400         boot_conn->dest_port = le16_to_cpu(fw_ddb_entry->port);
3401
3402         /* update chap information */
3403         idx = __le16_to_cpu(fw_ddb_entry->chap_tbl_idx);
3404
3405         if (BIT_7 & le16_to_cpu(fw_ddb_entry->iscsi_options))   {
3406
3407                 DEBUG2(ql4_printk(KERN_INFO, ha, "Setting chap\n"));
3408
3409                 ret = qla4xxx_get_chap(ha, (char *)&boot_conn->chap.
3410                                        target_chap_name,
3411                                        (char *)&boot_conn->chap.target_secret,
3412                                        idx);
3413                 if (ret) {
3414                         ql4_printk(KERN_ERR, ha, "Failed to set chap\n");
3415                         ret = QLA_ERROR;
3416                         goto exit_boot_target;
3417                 }
3418
3419                 boot_conn->chap.target_chap_name_length = QL4_CHAP_MAX_NAME_LEN;
3420                 boot_conn->chap.target_secret_length = QL4_CHAP_MAX_SECRET_LEN;
3421         }
3422
3423         if (BIT_4 & le16_to_cpu(fw_ddb_entry->iscsi_options)) {
3424
3425                 DEBUG2(ql4_printk(KERN_INFO, ha, "Setting BIDI chap\n"));
3426
3427                 ret = qla4xxx_get_bidi_chap(ha,
3428                                     (char *)&boot_conn->chap.intr_chap_name,
3429                                     (char *)&boot_conn->chap.intr_secret);
3430
3431                 if (ret) {
3432                         ql4_printk(KERN_ERR, ha, "Failed to set BIDI chap\n");
3433                         ret = QLA_ERROR;
3434                         goto exit_boot_target;
3435                 }
3436
3437                 boot_conn->chap.intr_chap_name_length = QL4_CHAP_MAX_NAME_LEN;
3438                 boot_conn->chap.intr_secret_length = QL4_CHAP_MAX_SECRET_LEN;
3439         }
3440
3441 exit_boot_target:
3442         dma_free_coherent(&ha->pdev->dev, sizeof(*fw_ddb_entry),
3443                           fw_ddb_entry, fw_ddb_entry_dma);
3444         return ret;
3445 }
3446
3447 static int qla4xxx_get_boot_info(struct scsi_qla_host *ha)
3448 {
3449         uint16_t ddb_index[2];
3450         int ret = QLA_ERROR;
3451         int rval;
3452
3453         memset(ddb_index, 0, sizeof(ddb_index));
3454         ddb_index[0] = 0xffff;
3455         ddb_index[1] = 0xffff;
3456         ret = get_fw_boot_info(ha, ddb_index);
3457         if (ret != QLA_SUCCESS) {
3458                 DEBUG2(ql4_printk(KERN_ERR, ha,
3459                                   "%s: Failed to set boot info.\n", __func__));
3460                 return ret;
3461         }
3462
3463         if (ql4xdisablesysfsboot)
3464                 return QLA_SUCCESS;
3465
3466         if (ddb_index[0] == 0xffff)
3467                 goto sec_target;
3468
3469         rval = qla4xxx_get_boot_target(ha, &(ha->boot_tgt.boot_pri_sess),
3470                                       ddb_index[0]);
3471         if (rval != QLA_SUCCESS) {
3472                 DEBUG2(ql4_printk(KERN_ERR, ha, "%s: Failed to get "
3473                                   "primary target\n", __func__));
3474         } else
3475                 ret = QLA_SUCCESS;
3476
3477 sec_target:
3478         if (ddb_index[1] == 0xffff)
3479                 goto exit_get_boot_info;
3480
3481         rval = qla4xxx_get_boot_target(ha, &(ha->boot_tgt.boot_sec_sess),
3482                                       ddb_index[1]);
3483         if (rval != QLA_SUCCESS) {
3484                 DEBUG2(ql4_printk(KERN_ERR, ha, "%s: Failed to get "
3485                                   "secondary target\n", __func__));
3486         } else
3487                 ret = QLA_SUCCESS;
3488
3489 exit_get_boot_info:
3490         return ret;
3491 }
3492
3493 static int qla4xxx_setup_boot_info(struct scsi_qla_host *ha)
3494 {
3495         struct iscsi_boot_kobj *boot_kobj;
3496
3497         if (qla4xxx_get_boot_info(ha) != QLA_SUCCESS)
3498                 return QLA_ERROR;
3499
3500         if (ql4xdisablesysfsboot) {
3501                 ql4_printk(KERN_INFO, ha,
3502                            "%s: syfsboot disabled - driver will trigger login"
3503                            "and publish session for discovery .\n", __func__);
3504                 return QLA_SUCCESS;
3505         }
3506
3507
3508         ha->boot_kset = iscsi_boot_create_host_kset(ha->host->host_no);
3509         if (!ha->boot_kset)
3510                 goto kset_free;
3511
3512         if (!scsi_host_get(ha->host))
3513                 goto kset_free;
3514         boot_kobj = iscsi_boot_create_target(ha->boot_kset, 0, ha,
3515                                              qla4xxx_show_boot_tgt_pri_info,
3516                                              qla4xxx_tgt_get_attr_visibility,
3517                                              qla4xxx_boot_release);
3518         if (!boot_kobj)
3519                 goto put_host;
3520
3521         if (!scsi_host_get(ha->host))
3522                 goto kset_free;
3523         boot_kobj = iscsi_boot_create_target(ha->boot_kset, 1, ha,
3524                                              qla4xxx_show_boot_tgt_sec_info,
3525                                              qla4xxx_tgt_get_attr_visibility,
3526                                              qla4xxx_boot_release);
3527         if (!boot_kobj)
3528                 goto put_host;
3529
3530         if (!scsi_host_get(ha->host))
3531                 goto kset_free;
3532         boot_kobj = iscsi_boot_create_initiator(ha->boot_kset, 0, ha,
3533                                                qla4xxx_show_boot_ini_info,
3534                                                qla4xxx_ini_get_attr_visibility,
3535                                                qla4xxx_boot_release);
3536         if (!boot_kobj)
3537                 goto put_host;
3538
3539         if (!scsi_host_get(ha->host))
3540                 goto kset_free;
3541         boot_kobj = iscsi_boot_create_ethernet(ha->boot_kset, 0, ha,
3542                                                qla4xxx_show_boot_eth_info,
3543                                                qla4xxx_eth_get_attr_visibility,
3544                                                qla4xxx_boot_release);
3545         if (!boot_kobj)
3546                 goto put_host;
3547
3548         return QLA_SUCCESS;
3549
3550 put_host:
3551         scsi_host_put(ha->host);
3552 kset_free:
3553         iscsi_boot_destroy_kset(ha->boot_kset);
3554         return -ENOMEM;
3555 }
3556
3557
3558 /**
3559  * qla4xxx_create chap_list - Create CHAP list from FLASH
3560  * @ha: pointer to adapter structure
3561  *
3562  * Read flash and make a list of CHAP entries, during login when a CHAP entry
3563  * is received, it will be checked in this list. If entry exist then the CHAP
3564  * entry index is set in the DDB. If CHAP entry does not exist in this list
3565  * then a new entry is added in FLASH in CHAP table and the index obtained is
3566  * used in the DDB.
3567  **/
3568 static void qla4xxx_create_chap_list(struct scsi_qla_host *ha)
3569 {
3570         int rval = 0;
3571         uint8_t *chap_flash_data = NULL;
3572         uint32_t offset;
3573         dma_addr_t chap_dma;
3574         uint32_t chap_size = 0;
3575
3576         if (is_qla40XX(ha))
3577                 chap_size = MAX_CHAP_ENTRIES_40XX  *
3578                                         sizeof(struct ql4_chap_table);
3579         else    /* Single region contains CHAP info for both
3580                  * ports which is divided into half for each port.
3581                  */
3582                 chap_size = ha->hw.flt_chap_size / 2;
3583
3584         chap_flash_data = dma_alloc_coherent(&ha->pdev->dev, chap_size,
3585                                           &chap_dma, GFP_KERNEL);
3586         if (!chap_flash_data) {
3587                 ql4_printk(KERN_ERR, ha, "No memory for chap_flash_data\n");
3588                 return;
3589         }
3590         if (is_qla40XX(ha))
3591                 offset = FLASH_CHAP_OFFSET;
3592         else {
3593                 offset = FLASH_RAW_ACCESS_ADDR + (ha->hw.flt_region_chap << 2);
3594                 if (ha->port_num == 1)
3595                         offset += chap_size;
3596         }
3597
3598         rval = qla4xxx_get_flash(ha, chap_dma, offset, chap_size);
3599         if (rval != QLA_SUCCESS)
3600                 goto exit_chap_list;
3601
3602         if (ha->chap_list == NULL)
3603                 ha->chap_list = vmalloc(chap_size);
3604         if (ha->chap_list == NULL) {
3605                 ql4_printk(KERN_ERR, ha, "No memory for ha->chap_list\n");
3606                 goto exit_chap_list;
3607         }
3608
3609         memcpy(ha->chap_list, chap_flash_data, chap_size);
3610
3611 exit_chap_list:
3612         dma_free_coherent(&ha->pdev->dev, chap_size,
3613                         chap_flash_data, chap_dma);
3614 }
3615
3616 static void qla4xxx_get_param_ddb(struct ddb_entry *ddb_entry,
3617                                   struct ql4_tuple_ddb *tddb)
3618 {
3619         struct scsi_qla_host *ha;
3620         struct iscsi_cls_session *cls_sess;
3621         struct iscsi_cls_conn *cls_conn;
3622         struct iscsi_session *sess;
3623         struct iscsi_conn *conn;
3624
3625         DEBUG2(printk(KERN_INFO "Func: %s\n", __func__));
3626         ha = ddb_entry->ha;
3627         cls_sess = ddb_entry->sess;
3628         sess = cls_sess->dd_data;
3629         cls_conn = ddb_entry->conn;
3630         conn = cls_conn->dd_data;
3631
3632         tddb->tpgt = sess->tpgt;
3633         tddb->port = conn->persistent_port;
3634         strncpy(tddb->iscsi_name, sess->targetname, ISCSI_NAME_SIZE);
3635         strncpy(tddb->ip_addr, conn->persistent_address, DDB_IPADDR_LEN);
3636 }
3637
3638 static void qla4xxx_convert_param_ddb(struct dev_db_entry *fw_ddb_entry,
3639                                       struct ql4_tuple_ddb *tddb)
3640 {
3641         uint16_t options = 0;
3642
3643         tddb->tpgt = le32_to_cpu(fw_ddb_entry->tgt_portal_grp);
3644         memcpy(&tddb->iscsi_name[0], &fw_ddb_entry->iscsi_name[0],
3645                min(sizeof(tddb->iscsi_name), sizeof(fw_ddb_entry->iscsi_name)));
3646
3647         options = le16_to_cpu(fw_ddb_entry->options);
3648         if (options & DDB_OPT_IPV6_DEVICE)
3649                 sprintf(tddb->ip_addr, "%pI6", fw_ddb_entry->ip_addr);
3650         else
3651                 sprintf(tddb->ip_addr, "%pI4", fw_ddb_entry->ip_addr);
3652
3653         tddb->port = le16_to_cpu(fw_ddb_entry->port);
3654 }
3655
3656 static int qla4xxx_compare_tuple_ddb(struct scsi_qla_host *ha,
3657                                      struct ql4_tuple_ddb *old_tddb,
3658                                      struct ql4_tuple_ddb *new_tddb)
3659 {
3660         if (strcmp(old_tddb->iscsi_name, new_tddb->iscsi_name))
3661                 return QLA_ERROR;
3662
3663         if (strcmp(old_tddb->ip_addr, new_tddb->ip_addr))
3664                 return QLA_ERROR;
3665
3666         if (old_tddb->port != new_tddb->port)
3667                 return QLA_ERROR;
3668
3669         DEBUG2(ql4_printk(KERN_INFO, ha,
3670                           "Match Found, fw[%d,%d,%s,%s], [%d,%d,%s,%s]",
3671                           old_tddb->port, old_tddb->tpgt, old_tddb->ip_addr,
3672                           old_tddb->iscsi_name, new_tddb->port, new_tddb->tpgt,
3673                           new_tddb->ip_addr, new_tddb->iscsi_name));
3674
3675         return QLA_SUCCESS;
3676 }
3677
3678 static int qla4xxx_is_session_exists(struct scsi_qla_host *ha,
3679                                      struct dev_db_entry *fw_ddb_entry)
3680 {
3681         struct ddb_entry *ddb_entry;
3682         struct ql4_tuple_ddb *fw_tddb = NULL;
3683         struct ql4_tuple_ddb *tmp_tddb = NULL;
3684         int idx;
3685         int ret = QLA_ERROR;
3686
3687         fw_tddb = vzalloc(sizeof(*fw_tddb));
3688         if (!fw_tddb) {
3689                 DEBUG2(ql4_printk(KERN_WARNING, ha,
3690                                   "Memory Allocation failed.\n"));
3691                 ret = QLA_SUCCESS;
3692                 goto exit_check;
3693         }
3694
3695         tmp_tddb = vzalloc(sizeof(*tmp_tddb));
3696         if (!tmp_tddb) {
3697                 DEBUG2(ql4_printk(KERN_WARNING, ha,
3698                                   "Memory Allocation failed.\n"));
3699                 ret = QLA_SUCCESS;
3700                 goto exit_check;
3701         }
3702
3703         qla4xxx_convert_param_ddb(fw_ddb_entry, fw_tddb);
3704
3705         for (idx = 0; idx < MAX_DDB_ENTRIES; idx++) {
3706                 ddb_entry = qla4xxx_lookup_ddb_by_fw_index(ha, idx);
3707                 if (ddb_entry == NULL)
3708                         continue;
3709
3710                 qla4xxx_get_param_ddb(ddb_entry, tmp_tddb);
3711                 if (!qla4xxx_compare_tuple_ddb(ha, fw_tddb, tmp_tddb)) {
3712                         ret = QLA_SUCCESS; /* found */
3713                         goto exit_check;
3714                 }
3715         }
3716
3717 exit_check:
3718         if (fw_tddb)
3719                 vfree(fw_tddb);
3720         if (tmp_tddb)
3721                 vfree(tmp_tddb);
3722         return ret;
3723 }
3724
3725 static int qla4xxx_is_flash_ddb_exists(struct scsi_qla_host *ha,
3726                                        struct list_head *list_nt,
3727                                        struct dev_db_entry *fw_ddb_entry)
3728 {
3729         struct qla_ddb_index  *nt_ddb_idx, *nt_ddb_idx_tmp;
3730         struct ql4_tuple_ddb *fw_tddb = NULL;
3731         struct ql4_tuple_ddb *tmp_tddb = NULL;
3732         int ret = QLA_ERROR;
3733
3734         fw_tddb = vzalloc(sizeof(*fw_tddb));
3735         if (!fw_tddb) {
3736                 DEBUG2(ql4_printk(KERN_WARNING, ha,
3737                                   "Memory Allocation failed.\n"));
3738                 ret = QLA_SUCCESS;
3739                 goto exit_check;
3740         }
3741
3742         tmp_tddb = vzalloc(sizeof(*tmp_tddb));
3743         if (!tmp_tddb) {
3744                 DEBUG2(ql4_printk(KERN_WARNING, ha,
3745                                   "Memory Allocation failed.\n"));
3746                 ret = QLA_SUCCESS;
3747                 goto exit_check;
3748         }
3749
3750         qla4xxx_convert_param_ddb(fw_ddb_entry, fw_tddb);
3751
3752         list_for_each_entry_safe(nt_ddb_idx, nt_ddb_idx_tmp, list_nt, list) {
3753                 qla4xxx_convert_param_ddb(&nt_ddb_idx->fw_ddb, tmp_tddb);
3754                 if (!qla4xxx_compare_tuple_ddb(ha, fw_tddb, tmp_tddb)) {
3755                         ret = QLA_SUCCESS; /* found */
3756                         goto exit_check;
3757                 }
3758         }
3759
3760 exit_check:
3761         if (fw_tddb)
3762                 vfree(fw_tddb);
3763         if (tmp_tddb)
3764                 vfree(tmp_tddb);
3765         return ret;
3766 }
3767
3768 static void qla4xxx_free_nt_list(struct list_head *list_nt)
3769 {
3770         struct qla_ddb_index  *nt_ddb_idx, *nt_ddb_idx_tmp;
3771
3772         /* Free up the normaltargets list */
3773         list_for_each_entry_safe(nt_ddb_idx, nt_ddb_idx_tmp, list_nt, list) {
3774                 list_del_init(&nt_ddb_idx->list);
3775                 vfree(nt_ddb_idx);
3776         }
3777
3778 }
3779
3780 static struct iscsi_endpoint *qla4xxx_get_ep_fwdb(struct scsi_qla_host *ha,
3781                                         struct dev_db_entry *fw_ddb_entry)
3782 {
3783         struct iscsi_endpoint *ep;
3784         struct sockaddr_in *addr;
3785         struct sockaddr_in6 *addr6;
3786         struct sockaddr *dst_addr;
3787         char *ip;
3788
3789         /* TODO: need to destroy on unload iscsi_endpoint*/
3790         dst_addr = vmalloc(sizeof(*dst_addr));
3791         if (!dst_addr)
3792                 return NULL;
3793
3794         if (fw_ddb_entry->options & DDB_OPT_IPV6_DEVICE) {
3795                 dst_addr->sa_family = AF_INET6;
3796                 addr6 = (struct sockaddr_in6 *)dst_addr;
3797                 ip = (char *)&addr6->sin6_addr;
3798                 memcpy(ip, fw_ddb_entry->ip_addr, IPv6_ADDR_LEN);
3799                 addr6->sin6_port = htons(le16_to_cpu(fw_ddb_entry->port));
3800
3801         } else {
3802                 dst_addr->sa_family = AF_INET;
3803                 addr = (struct sockaddr_in *)dst_addr;
3804                 ip = (char *)&addr->sin_addr;
3805                 memcpy(ip, fw_ddb_entry->ip_addr, IP_ADDR_LEN);
3806                 addr->sin_port = htons(le16_to_cpu(fw_ddb_entry->port));
3807         }
3808
3809         ep = qla4xxx_ep_connect(ha->host, dst_addr, 0);
3810         vfree(dst_addr);
3811         return ep;
3812 }
3813
3814 static int qla4xxx_verify_boot_idx(struct scsi_qla_host *ha, uint16_t idx)
3815 {
3816         if (ql4xdisablesysfsboot)
3817                 return QLA_SUCCESS;
3818         if (idx == ha->pri_ddb_idx || idx == ha->sec_ddb_idx)
3819                 return QLA_ERROR;
3820         return QLA_SUCCESS;
3821 }
3822
3823 static void qla4xxx_setup_flash_ddb_entry(struct scsi_qla_host *ha,
3824                                           struct ddb_entry *ddb_entry)
3825 {
3826         ddb_entry->ddb_type = FLASH_DDB;
3827         ddb_entry->fw_ddb_index = INVALID_ENTRY;
3828         ddb_entry->fw_ddb_device_state = DDB_DS_NO_CONNECTION_ACTIVE;
3829         ddb_entry->ha = ha;
3830         ddb_entry->unblock_sess = qla4xxx_unblock_flash_ddb;
3831         ddb_entry->ddb_change = qla4xxx_flash_ddb_change;
3832
3833         atomic_set(&ddb_entry->retry_relogin_timer, INVALID_ENTRY);
3834         atomic_set(&ddb_entry->relogin_timer, 0);
3835         atomic_set(&ddb_entry->relogin_retry_count, 0);
3836
3837         ddb_entry->default_relogin_timeout =
3838                 le16_to_cpu(ddb_entry->fw_ddb_entry.def_timeout);
3839         ddb_entry->default_time2wait =
3840                 le16_to_cpu(ddb_entry->fw_ddb_entry.iscsi_def_time2wait);
3841 }
3842
3843 static void qla4xxx_wait_for_ip_configuration(struct scsi_qla_host *ha)
3844 {
3845         uint32_t idx = 0;
3846         uint32_t ip_idx[IP_ADDR_COUNT] = {0, 1, 2, 3}; /* 4 IP interfaces */
3847         uint32_t sts[MBOX_REG_COUNT];
3848         uint32_t ip_state;
3849         unsigned long wtime;
3850         int ret;
3851
3852         wtime = jiffies + (HZ * IP_CONFIG_TOV);
3853         do {
3854                 for (idx = 0; idx < IP_ADDR_COUNT; idx++) {
3855                         if (ip_idx[idx] == -1)
3856                                 continue;
3857
3858                         ret = qla4xxx_get_ip_state(ha, 0, ip_idx[idx], sts);
3859
3860                         if (ret == QLA_ERROR) {
3861                                 ip_idx[idx] = -1;
3862                                 continue;
3863                         }
3864
3865                         ip_state = (sts[1] & IP_STATE_MASK) >> IP_STATE_SHIFT;
3866
3867                         DEBUG2(ql4_printk(KERN_INFO, ha,
3868                                           "Waiting for IP state for idx = %d, state = 0x%x\n",
3869                                           ip_idx[idx], ip_state));
3870                         if (ip_state == IP_ADDRSTATE_UNCONFIGURED ||
3871                             ip_state == IP_ADDRSTATE_INVALID ||
3872                             ip_state == IP_ADDRSTATE_PREFERRED ||
3873                             ip_state == IP_ADDRSTATE_DEPRICATED ||
3874                             ip_state == IP_ADDRSTATE_DISABLING)
3875                                 ip_idx[idx] = -1;
3876
3877                 }
3878
3879                 /* Break if all IP states checked */
3880                 if ((ip_idx[0] == -1) &&
3881                     (ip_idx[1] == -1) &&
3882                     (ip_idx[2] == -1) &&
3883                     (ip_idx[3] == -1))
3884                         break;
3885                 schedule_timeout_uninterruptible(HZ);
3886         } while (time_after(wtime, jiffies));
3887 }
3888
3889 void qla4xxx_build_ddb_list(struct scsi_qla_host *ha, int is_reset)
3890 {
3891         int max_ddbs;
3892         int ret;
3893         uint32_t idx = 0, next_idx = 0;
3894         uint32_t state = 0, conn_err = 0;
3895         uint16_t conn_id;
3896         struct dev_db_entry *fw_ddb_entry;
3897         struct ddb_entry *ddb_entry = NULL;
3898         dma_addr_t fw_ddb_dma;
3899         struct iscsi_cls_session *cls_sess;
3900         struct iscsi_session *sess;
3901         struct iscsi_cls_conn *cls_conn;
3902         struct iscsi_endpoint *ep;
3903         uint16_t cmds_max = 32, tmo = 0;
3904         uint32_t initial_cmdsn = 0;
3905         struct list_head list_st, list_nt; /* List of sendtargets */
3906         struct qla_ddb_index  *st_ddb_idx, *st_ddb_idx_tmp;
3907         int fw_idx_size;
3908         unsigned long wtime;
3909         struct qla_ddb_index  *nt_ddb_idx;
3910
3911         if (!test_bit(AF_LINK_UP, &ha->flags)) {
3912                 set_bit(AF_BUILD_DDB_LIST, &ha->flags);
3913                 ha->is_reset = is_reset;
3914                 return;
3915         }
3916         max_ddbs =  is_qla40XX(ha) ? MAX_DEV_DB_ENTRIES_40XX :
3917                                      MAX_DEV_DB_ENTRIES;
3918
3919         fw_ddb_entry = dma_pool_alloc(ha->fw_ddb_dma_pool, GFP_KERNEL,
3920                                       &fw_ddb_dma);
3921         if (fw_ddb_entry == NULL) {
3922                 DEBUG2(ql4_printk(KERN_ERR, ha, "Out of memory\n"));
3923                 goto exit_ddb_list;
3924         }
3925
3926         INIT_LIST_HEAD(&list_st);
3927         INIT_LIST_HEAD(&list_nt);
3928         fw_idx_size = sizeof(struct qla_ddb_index);
3929
3930         for (idx = 0; idx < max_ddbs; idx = next_idx) {
3931                 ret = qla4xxx_get_fwddb_entry(ha, idx, fw_ddb_entry,
3932                                               fw_ddb_dma, NULL,
3933                                               &next_idx, &state, &conn_err,
3934                                               NULL, &conn_id);
3935                 if (ret == QLA_ERROR)
3936                         break;
3937
3938                 if (qla4xxx_verify_boot_idx(ha, idx) != QLA_SUCCESS)
3939                         goto continue_next_st;
3940
3941                 /* Check if ST, add to the list_st */
3942                 if (strlen((char *) fw_ddb_entry->iscsi_name) != 0)
3943                         goto continue_next_st;
3944
3945                 st_ddb_idx = vzalloc(fw_idx_size);
3946                 if (!st_ddb_idx)
3947                         break;
3948
3949                 st_ddb_idx->fw_ddb_idx = idx;
3950
3951                 list_add_tail(&st_ddb_idx->list, &list_st);
3952 continue_next_st:
3953                 if (next_idx == 0)
3954                         break;
3955         }
3956
3957         /* Before issuing conn open mbox, ensure all IPs states are configured
3958          * Note, conn open fails if IPs are not configured
3959          */
3960         qla4xxx_wait_for_ip_configuration(ha);
3961
3962         /* Go thru the STs and fire the sendtargets by issuing conn open mbx */
3963         list_for_each_entry_safe(st_ddb_idx, st_ddb_idx_tmp, &list_st, list) {
3964                 qla4xxx_conn_open(ha, st_ddb_idx->fw_ddb_idx);
3965         }
3966
3967         /* Wait to ensure all sendtargets are done for min 12 sec wait */
3968         tmo = ((ha->def_timeout < LOGIN_TOV) ? LOGIN_TOV : ha->def_timeout);
3969         DEBUG2(ql4_printk(KERN_INFO, ha,
3970                           "Default time to wait for build ddb %d\n", tmo));
3971
3972         wtime = jiffies + (HZ * tmo);
3973         do {
3974                 list_for_each_entry_safe(st_ddb_idx, st_ddb_idx_tmp, &list_st,
3975                                          list) {
3976                         ret = qla4xxx_get_fwddb_entry(ha,
3977                                                       st_ddb_idx->fw_ddb_idx,
3978                                                       NULL, 0, NULL, &next_idx,
3979                                                       &state, &conn_err, NULL,
3980                                                       NULL);
3981                         if (ret == QLA_ERROR)
3982                                 continue;
3983
3984                         if (state == DDB_DS_NO_CONNECTION_ACTIVE ||
3985                             state == DDB_DS_SESSION_FAILED) {
3986                                 list_del_init(&st_ddb_idx->list);
3987                                 vfree(st_ddb_idx);
3988                         }
3989                 }
3990                 schedule_timeout_uninterruptible(HZ / 10);
3991         } while (time_after(wtime, jiffies));
3992
3993         /* Free up the sendtargets list */
3994         list_for_each_entry_safe(st_ddb_idx, st_ddb_idx_tmp, &list_st, list) {
3995                 list_del_init(&st_ddb_idx->list);
3996                 vfree(st_ddb_idx);
3997         }
3998
3999         for (idx = 0; idx < max_ddbs; idx = next_idx) {
4000                 ret = qla4xxx_get_fwddb_entry(ha, idx, fw_ddb_entry,
4001                                               fw_ddb_dma, NULL,
4002                                               &next_idx, &state, &conn_err,
4003                                               NULL, &conn_id);
4004                 if (ret == QLA_ERROR)
4005                         break;
4006
4007                 if (qla4xxx_verify_boot_idx(ha, idx) != QLA_SUCCESS)
4008                         goto continue_next_nt;
4009
4010                 /* Check if NT, then add to list it */
4011                 if (strlen((char *) fw_ddb_entry->iscsi_name) == 0)
4012                         goto continue_next_nt;
4013
4014                 if (state == DDB_DS_NO_CONNECTION_ACTIVE ||
4015                     state == DDB_DS_SESSION_FAILED) {
4016                         DEBUG2(ql4_printk(KERN_INFO, ha,
4017                                           "Adding  DDB to session = 0x%x\n",
4018                                           idx));
4019                         if (is_reset == INIT_ADAPTER) {
4020                                 nt_ddb_idx = vmalloc(fw_idx_size);
4021                                 if (!nt_ddb_idx)
4022                                         break;
4023
4024                                 nt_ddb_idx->fw_ddb_idx = idx;
4025
4026                                 memcpy(&nt_ddb_idx->fw_ddb, fw_ddb_entry,
4027                                        sizeof(struct dev_db_entry));
4028
4029                                 if (qla4xxx_is_flash_ddb_exists(ha, &list_nt,
4030                                                 fw_ddb_entry) == QLA_SUCCESS) {
4031                                         vfree(nt_ddb_idx);
4032                                         goto continue_next_nt;
4033                                 }
4034                                 list_add_tail(&nt_ddb_idx->list, &list_nt);
4035                         } else if (is_reset == RESET_ADAPTER) {
4036                                 if (qla4xxx_is_session_exists(ha,
4037                                                    fw_ddb_entry) == QLA_SUCCESS)
4038                                         goto continue_next_nt;
4039                         }
4040
4041                         /* Create session object, with INVALID_ENTRY,
4042                          * the targer_id would get set when we issue the login
4043                          */
4044                         cls_sess = iscsi_session_setup(&qla4xxx_iscsi_transport,
4045                                                 ha->host, cmds_max,
4046                                                 sizeof(struct ddb_entry),
4047                                                 sizeof(struct ql4_task_data),
4048                                                 initial_cmdsn, INVALID_ENTRY);
4049                         if (!cls_sess)
4050                                 goto exit_ddb_list;
4051
4052                         /*
4053                          * iscsi_session_setup increments the driver reference
4054                          * count which wouldn't let the driver to be unloaded.
4055                          * so calling module_put function to decrement the
4056                          * reference count.
4057                          **/
4058                         module_put(qla4xxx_iscsi_transport.owner);
4059                         sess = cls_sess->dd_data;
4060                         ddb_entry = sess->dd_data;
4061                         ddb_entry->sess = cls_sess;
4062
4063                         cls_sess->recovery_tmo = ql4xsess_recovery_tmo;
4064                         memcpy(&ddb_entry->fw_ddb_entry, fw_ddb_entry,
4065                                sizeof(struct dev_db_entry));
4066
4067                         qla4xxx_setup_flash_ddb_entry(ha, ddb_entry);
4068
4069                         cls_conn = iscsi_conn_setup(cls_sess,
4070                                                     sizeof(struct qla_conn),
4071                                                     conn_id);
4072                         if (!cls_conn)
4073                                 goto exit_ddb_list;
4074
4075                         ddb_entry->conn = cls_conn;
4076
4077                         /* Setup ep, for displaying attributes in sysfs */
4078                         ep = qla4xxx_get_ep_fwdb(ha, fw_ddb_entry);
4079                         if (ep) {
4080                                 ep->conn = cls_conn;
4081                                 cls_conn->ep = ep;
4082                         } else {
4083                                 DEBUG2(ql4_printk(KERN_ERR, ha,
4084                                                   "Unable to get ep\n"));
4085                         }
4086
4087                         /* Update sess/conn params */
4088                         qla4xxx_copy_fwddb_param(ha, fw_ddb_entry, cls_sess,
4089                                                  cls_conn);
4090
4091                         if (is_reset == RESET_ADAPTER) {
4092                                 iscsi_block_session(cls_sess);
4093                                 /* Use the relogin path to discover new devices
4094                                  *  by short-circuting the logic of setting
4095                                  *  timer to relogin - instead set the flags
4096                                  *  to initiate login right away.
4097                                  */
4098                                 set_bit(DPC_RELOGIN_DEVICE, &ha->dpc_flags);
4099                                 set_bit(DF_RELOGIN, &ddb_entry->flags);
4100                         }
4101                 }
4102 continue_next_nt:
4103                 if (next_idx == 0)
4104                         break;
4105         }
4106 exit_ddb_list:
4107         qla4xxx_free_nt_list(&list_nt);
4108         if (fw_ddb_entry)
4109                 dma_pool_free(ha->fw_ddb_dma_pool, fw_ddb_entry, fw_ddb_dma);
4110
4111         qla4xxx_free_ddb_index(ha);
4112 }
4113
4114
4115 /**
4116  * qla4xxx_probe_adapter - callback function to probe HBA
4117  * @pdev: pointer to pci_dev structure
4118  * @pci_device_id: pointer to pci_device entry
4119  *
4120  * This routine will probe for Qlogic 4xxx iSCSI host adapters.
4121  * It returns zero if successful. It also initializes all data necessary for
4122  * the driver.
4123  **/
4124 static int __devinit qla4xxx_probe_adapter(struct pci_dev *pdev,
4125                                            const struct pci_device_id *ent)
4126 {
4127         int ret = -ENODEV, status;
4128         struct Scsi_Host *host;
4129         struct scsi_qla_host *ha;
4130         uint8_t init_retry_count = 0;
4131         char buf[34];
4132         struct qla4_8xxx_legacy_intr_set *nx_legacy_intr;
4133         uint32_t dev_state;
4134
4135         if (pci_enable_device(pdev))
4136                 return -1;
4137
4138         host = iscsi_host_alloc(&qla4xxx_driver_template, sizeof(*ha), 0);
4139         if (host == NULL) {
4140                 printk(KERN_WARNING
4141                        "qla4xxx: Couldn't allocate host from scsi layer!\n");
4142                 goto probe_disable_device;
4143         }
4144
4145         /* Clear our data area */
4146         ha = to_qla_host(host);
4147         memset(ha, 0, sizeof(*ha));
4148
4149         /* Save the information from PCI BIOS.  */
4150         ha->pdev = pdev;
4151         ha->host = host;
4152         ha->host_no = host->host_no;
4153
4154         pci_enable_pcie_error_reporting(pdev);
4155
4156         /* Setup Runtime configurable options */
4157         if (is_qla8022(ha)) {
4158                 ha->isp_ops = &qla4_8xxx_isp_ops;
4159                 rwlock_init(&ha->hw_lock);
4160                 ha->qdr_sn_window = -1;
4161                 ha->ddr_mn_window = -1;
4162                 ha->curr_window = 255;
4163                 ha->func_num = PCI_FUNC(ha->pdev->devfn);
4164                 nx_legacy_intr = &legacy_intr[ha->func_num];
4165                 ha->nx_legacy_intr.int_vec_bit = nx_legacy_intr->int_vec_bit;
4166                 ha->nx_legacy_intr.tgt_status_reg =
4167                         nx_legacy_intr->tgt_status_reg;
4168                 ha->nx_legacy_intr.tgt_mask_reg = nx_legacy_intr->tgt_mask_reg;
4169                 ha->nx_legacy_intr.pci_int_reg = nx_legacy_intr->pci_int_reg;
4170         } else {
4171                 ha->isp_ops = &qla4xxx_isp_ops;
4172         }
4173
4174         /* Set EEH reset type to fundamental if required by hba */
4175         if (is_qla8022(ha))
4176                 pdev->needs_freset = 1;
4177
4178         /* Configure PCI I/O space. */
4179         ret = ha->isp_ops->iospace_config(ha);
4180         if (ret)
4181                 goto probe_failed_ioconfig;
4182
4183         ql4_printk(KERN_INFO, ha, "Found an ISP%04x, irq %d, iobase 0x%p\n",
4184                    pdev->device, pdev->irq, ha->reg);
4185
4186         qla4xxx_config_dma_addressing(ha);
4187
4188         /* Initialize lists and spinlocks. */
4189         INIT_LIST_HEAD(&ha->free_srb_q);
4190
4191         mutex_init(&ha->mbox_sem);
4192         mutex_init(&ha->chap_sem);
4193         init_completion(&ha->mbx_intr_comp);
4194         init_completion(&ha->disable_acb_comp);
4195
4196         spin_lock_init(&ha->hardware_lock);
4197
4198         /* Allocate dma buffers */
4199         if (qla4xxx_mem_alloc(ha)) {
4200                 ql4_printk(KERN_WARNING, ha,
4201                     "[ERROR] Failed to allocate memory for adapter\n");
4202
4203                 ret = -ENOMEM;
4204                 goto probe_failed;
4205         }
4206
4207         host->cmd_per_lun = 3;
4208         host->max_channel = 0;
4209         host->max_lun = MAX_LUNS - 1;
4210         host->max_id = MAX_TARGETS;
4211         host->max_cmd_len = IOCB_MAX_CDB_LEN;
4212         host->can_queue = MAX_SRBS ;
4213         host->transportt = qla4xxx_scsi_transport;
4214
4215         ret = scsi_init_shared_tag_map(host, MAX_SRBS);
4216         if (ret) {
4217                 ql4_printk(KERN_WARNING, ha,
4218                            "%s: scsi_init_shared_tag_map failed\n", __func__);
4219                 goto probe_failed;
4220         }
4221
4222         pci_set_drvdata(pdev, ha);
4223
4224         ret = scsi_add_host(host, &pdev->dev);
4225         if (ret)
4226                 goto probe_failed;
4227
4228         if (is_qla8022(ha))
4229                 (void) qla4_8xxx_get_flash_info(ha);
4230
4231         /*
4232          * Initialize the Host adapter request/response queues and
4233          * firmware
4234          * NOTE: interrupts enabled upon successful completion
4235          */
4236         status = qla4xxx_initialize_adapter(ha, INIT_ADAPTER);
4237         while ((!test_bit(AF_ONLINE, &ha->flags)) &&
4238             init_retry_count++ < MAX_INIT_RETRIES) {
4239
4240                 if (is_qla8022(ha)) {
4241                         qla4_8xxx_idc_lock(ha);
4242                         dev_state = qla4_8xxx_rd_32(ha, QLA82XX_CRB_DEV_STATE);
4243                         qla4_8xxx_idc_unlock(ha);
4244                         if (dev_state == QLA82XX_DEV_FAILED) {
4245                                 ql4_printk(KERN_WARNING, ha, "%s: don't retry "
4246                                     "initialize adapter. H/W is in failed state\n",
4247                                     __func__);
4248                                 break;
4249                         }
4250                 }
4251                 DEBUG2(printk("scsi: %s: retrying adapter initialization "
4252                               "(%d)\n", __func__, init_retry_count));
4253
4254                 if (ha->isp_ops->reset_chip(ha) == QLA_ERROR)
4255                         continue;
4256
4257                 status = qla4xxx_initialize_adapter(ha, INIT_ADAPTER);
4258         }
4259
4260         if (!test_bit(AF_ONLINE, &ha->flags)) {
4261                 ql4_printk(KERN_WARNING, ha, "Failed to initialize adapter\n");
4262
4263                 if (is_qla8022(ha) && ql4xdontresethba) {
4264                         /* Put the device in failed state. */
4265                         DEBUG2(printk(KERN_ERR "HW STATE: FAILED\n"));
4266                         qla4_8xxx_idc_lock(ha);
4267                         qla4_8xxx_wr_32(ha, QLA82XX_CRB_DEV_STATE,
4268                             QLA82XX_DEV_FAILED);
4269                         qla4_8xxx_idc_unlock(ha);
4270                 }
4271                 ret = -ENODEV;
4272                 goto remove_host;
4273         }
4274
4275         /* Startup the kernel thread for this host adapter. */
4276         DEBUG2(printk("scsi: %s: Starting kernel thread for "
4277                       "qla4xxx_dpc\n", __func__));
4278         sprintf(buf, "qla4xxx_%lu_dpc", ha->host_no);
4279         ha->dpc_thread = create_singlethread_workqueue(buf);
4280         if (!ha->dpc_thread) {
4281                 ql4_printk(KERN_WARNING, ha, "Unable to start DPC thread!\n");
4282                 ret = -ENODEV;
4283                 goto remove_host;
4284         }
4285         INIT_WORK(&ha->dpc_work, qla4xxx_do_dpc);
4286
4287         sprintf(buf, "qla4xxx_%lu_task", ha->host_no);
4288         ha->task_wq = alloc_workqueue(buf, WQ_MEM_RECLAIM, 1);
4289         if (!ha->task_wq) {
4290                 ql4_printk(KERN_WARNING, ha, "Unable to start task thread!\n");
4291                 ret = -ENODEV;
4292                 goto remove_host;
4293         }
4294
4295         /* For ISP-82XX, request_irqs is called in qla4_8xxx_load_risc
4296          * (which is called indirectly by qla4xxx_initialize_adapter),
4297          * so that irqs will be registered after crbinit but before
4298          * mbx_intr_enable.
4299          */
4300         if (!is_qla8022(ha)) {
4301                 ret = qla4xxx_request_irqs(ha);
4302                 if (ret) {
4303                         ql4_printk(KERN_WARNING, ha, "Failed to reserve "
4304                             "interrupt %d already in use.\n", pdev->irq);
4305                         goto remove_host;
4306                 }
4307         }
4308
4309         pci_save_state(ha->pdev);
4310         ha->isp_ops->enable_intrs(ha);
4311
4312         /* Start timer thread. */
4313         qla4xxx_start_timer(ha, qla4xxx_timer, 1);
4314
4315         set_bit(AF_INIT_DONE, &ha->flags);
4316
4317         printk(KERN_INFO
4318                " QLogic iSCSI HBA Driver version: %s\n"
4319                "  QLogic ISP%04x @ %s, host#=%ld, fw=%02d.%02d.%02d.%02d\n",
4320                qla4xxx_version_str, ha->pdev->device, pci_name(ha->pdev),
4321                ha->host_no, ha->firmware_version[0], ha->firmware_version[1],
4322                ha->patch_number, ha->build_number);
4323
4324         if (qla4xxx_setup_boot_info(ha))
4325                 ql4_printk(KERN_ERR, ha, "%s:ISCSI boot info setup failed\n",
4326                            __func__);
4327
4328                 /* Perform the build ddb list and login to each */
4329         qla4xxx_build_ddb_list(ha, INIT_ADAPTER);
4330         iscsi_host_for_each_session(ha->host, qla4xxx_login_flash_ddb);
4331
4332         qla4xxx_create_chap_list(ha);
4333
4334         qla4xxx_create_ifaces(ha);
4335         return 0;
4336
4337 remove_host:
4338         scsi_remove_host(ha->host);
4339
4340 probe_failed:
4341         qla4xxx_free_adapter(ha);
4342
4343 probe_failed_ioconfig:
4344         pci_disable_pcie_error_reporting(pdev);
4345         scsi_host_put(ha->host);
4346
4347 probe_disable_device:
4348         pci_disable_device(pdev);
4349
4350         return ret;
4351 }
4352
4353 /**
4354  * qla4xxx_prevent_other_port_reinit - prevent other port from re-initialize
4355  * @ha: pointer to adapter structure
4356  *
4357  * Mark the other ISP-4xxx port to indicate that the driver is being removed,
4358  * so that the other port will not re-initialize while in the process of
4359  * removing the ha due to driver unload or hba hotplug.
4360  **/
4361 static void qla4xxx_prevent_other_port_reinit(struct scsi_qla_host *ha)
4362 {
4363         struct scsi_qla_host *other_ha = NULL;
4364         struct pci_dev *other_pdev = NULL;
4365         int fn = ISP4XXX_PCI_FN_2;
4366
4367         /*iscsi function numbers for ISP4xxx is 1 and 3*/
4368         if (PCI_FUNC(ha->pdev->devfn) & BIT_1)
4369                 fn = ISP4XXX_PCI_FN_1;
4370
4371         other_pdev =
4372                 pci_get_domain_bus_and_slot(pci_domain_nr(ha->pdev->bus),
4373                 ha->pdev->bus->number, PCI_DEVFN(PCI_SLOT(ha->pdev->devfn),
4374                 fn));
4375
4376         /* Get other_ha if other_pdev is valid and state is enable*/
4377         if (other_pdev) {
4378                 if (atomic_read(&other_pdev->enable_cnt)) {
4379                         other_ha = pci_get_drvdata(other_pdev);
4380                         if (other_ha) {
4381                                 set_bit(AF_HA_REMOVAL, &other_ha->flags);
4382                                 DEBUG2(ql4_printk(KERN_INFO, ha, "%s: "
4383                                     "Prevent %s reinit\n", __func__,
4384                                     dev_name(&other_ha->pdev->dev)));
4385                         }
4386                 }
4387                 pci_dev_put(other_pdev);
4388         }
4389 }
4390
4391 static void qla4xxx_destroy_fw_ddb_session(struct scsi_qla_host *ha)
4392 {
4393         struct ddb_entry *ddb_entry;
4394         int options;
4395         int idx;
4396
4397         for (idx = 0; idx < MAX_DDB_ENTRIES; idx++) {
4398
4399                 ddb_entry = qla4xxx_lookup_ddb_by_fw_index(ha, idx);
4400                 if ((ddb_entry != NULL) &&
4401                     (ddb_entry->ddb_type == FLASH_DDB)) {
4402
4403                         options = LOGOUT_OPTION_CLOSE_SESSION;
4404                         if (qla4xxx_session_logout_ddb(ha, ddb_entry, options)
4405                             == QLA_ERROR)
4406                                 ql4_printk(KERN_ERR, ha, "%s: Logout failed\n",
4407                                            __func__);
4408
4409                         qla4xxx_clear_ddb_entry(ha, ddb_entry->fw_ddb_index);
4410                         /*
4411                          * we have decremented the reference count of the driver
4412                          * when we setup the session to have the driver unload
4413                          * to be seamless without actually destroying the
4414                          * session
4415                          **/
4416                         try_module_get(qla4xxx_iscsi_transport.owner);
4417                         iscsi_destroy_endpoint(ddb_entry->conn->ep);
4418                         qla4xxx_free_ddb(ha, ddb_entry);
4419                         iscsi_session_teardown(ddb_entry->sess);
4420                 }
4421         }
4422 }
4423 /**
4424  * qla4xxx_remove_adapter - calback function to remove adapter.
4425  * @pci_dev: PCI device pointer
4426  **/
4427 static void __devexit qla4xxx_remove_adapter(struct pci_dev *pdev)
4428 {
4429         struct scsi_qla_host *ha;
4430
4431         ha = pci_get_drvdata(pdev);
4432
4433         if (!is_qla8022(ha))
4434                 qla4xxx_prevent_other_port_reinit(ha);
4435
4436         /* destroy iface from sysfs */
4437         qla4xxx_destroy_ifaces(ha);
4438
4439         if ((!ql4xdisablesysfsboot) && ha->boot_kset)
4440                 iscsi_boot_destroy_kset(ha->boot_kset);
4441
4442         qla4xxx_destroy_fw_ddb_session(ha);
4443
4444         scsi_remove_host(ha->host);
4445
4446         qla4xxx_free_adapter(ha);
4447
4448         scsi_host_put(ha->host);
4449
4450         pci_disable_pcie_error_reporting(pdev);
4451         pci_disable_device(pdev);
4452         pci_set_drvdata(pdev, NULL);
4453 }
4454
4455 /**
4456  * qla4xxx_config_dma_addressing() - Configure OS DMA addressing method.
4457  * @ha: HA context
4458  *
4459  * At exit, the @ha's flags.enable_64bit_addressing set to indicated
4460  * supported addressing method.
4461  */
4462 static void qla4xxx_config_dma_addressing(struct scsi_qla_host *ha)
4463 {
4464         int retval;
4465
4466         /* Update our PCI device dma_mask for full 64 bit mask */
4467         if (pci_set_dma_mask(ha->pdev, DMA_BIT_MASK(64)) == 0) {
4468                 if (pci_set_consistent_dma_mask(ha->pdev, DMA_BIT_MASK(64))) {
4469                         dev_dbg(&ha->pdev->dev,
4470                                   "Failed to set 64 bit PCI consistent mask; "
4471                                    "using 32 bit.\n");
4472                         retval = pci_set_consistent_dma_mask(ha->pdev,
4473                                                              DMA_BIT_MASK(32));
4474                 }
4475         } else
4476                 retval = pci_set_dma_mask(ha->pdev, DMA_BIT_MASK(32));
4477 }
4478
4479 static int qla4xxx_slave_alloc(struct scsi_device *sdev)
4480 {
4481         struct iscsi_cls_session *cls_sess;
4482         struct iscsi_session *sess;
4483         struct ddb_entry *ddb;
4484         int queue_depth = QL4_DEF_QDEPTH;
4485
4486         cls_sess = starget_to_session(sdev->sdev_target);
4487         sess = cls_sess->dd_data;
4488         ddb = sess->dd_data;
4489
4490         sdev->hostdata = ddb;
4491         sdev->tagged_supported = 1;
4492
4493         if (ql4xmaxqdepth != 0 && ql4xmaxqdepth <= 0xffffU)
4494                 queue_depth = ql4xmaxqdepth;
4495
4496         scsi_activate_tcq(sdev, queue_depth);
4497         return 0;
4498 }
4499
4500 static int qla4xxx_slave_configure(struct scsi_device *sdev)
4501 {
4502         sdev->tagged_supported = 1;
4503         return 0;
4504 }
4505
4506 static void qla4xxx_slave_destroy(struct scsi_device *sdev)
4507 {
4508         scsi_deactivate_tcq(sdev, 1);
4509 }
4510
4511 /**
4512  * qla4xxx_del_from_active_array - returns an active srb
4513  * @ha: Pointer to host adapter structure.
4514  * @index: index into the active_array
4515  *
4516  * This routine removes and returns the srb at the specified index
4517  **/
4518 struct srb *qla4xxx_del_from_active_array(struct scsi_qla_host *ha,
4519     uint32_t index)
4520 {
4521         struct srb *srb = NULL;
4522         struct scsi_cmnd *cmd = NULL;
4523
4524         cmd = scsi_host_find_tag(ha->host, index);
4525         if (!cmd)
4526                 return srb;
4527
4528         srb = (struct srb *)CMD_SP(cmd);
4529         if (!srb)
4530                 return srb;
4531
4532         /* update counters */
4533         if (srb->flags & SRB_DMA_VALID) {
4534                 ha->req_q_count += srb->iocb_cnt;
4535                 ha->iocb_cnt -= srb->iocb_cnt;
4536                 if (srb->cmd)
4537                         srb->cmd->host_scribble =
4538                                 (unsigned char *)(unsigned long) MAX_SRBS;
4539         }
4540         return srb;
4541 }
4542
4543 /**
4544  * qla4xxx_eh_wait_on_command - waits for command to be returned by firmware
4545  * @ha: Pointer to host adapter structure.
4546  * @cmd: Scsi Command to wait on.
4547  *
4548  * This routine waits for the command to be returned by the Firmware
4549  * for some max time.
4550  **/
4551 static int qla4xxx_eh_wait_on_command(struct scsi_qla_host *ha,
4552                                       struct scsi_cmnd *cmd)
4553 {
4554         int done = 0;
4555         struct srb *rp;
4556         uint32_t max_wait_time = EH_WAIT_CMD_TOV;
4557         int ret = SUCCESS;
4558
4559         /* Dont wait on command if PCI error is being handled
4560          * by PCI AER driver
4561          */
4562         if (unlikely(pci_channel_offline(ha->pdev)) ||
4563             (test_bit(AF_EEH_BUSY, &ha->flags))) {
4564                 ql4_printk(KERN_WARNING, ha, "scsi%ld: Return from %s\n",
4565                     ha->host_no, __func__);
4566                 return ret;
4567         }
4568
4569         do {
4570                 /* Checking to see if its returned to OS */
4571                 rp = (struct srb *) CMD_SP(cmd);
4572                 if (rp == NULL) {
4573                         done++;
4574                         break;
4575                 }
4576
4577                 msleep(2000);
4578         } while (max_wait_time--);
4579
4580         return done;
4581 }
4582
4583 /**
4584  * qla4xxx_wait_for_hba_online - waits for HBA to come online
4585  * @ha: Pointer to host adapter structure
4586  **/
4587 static int qla4xxx_wait_for_hba_online(struct scsi_qla_host *ha)
4588 {
4589         unsigned long wait_online;
4590
4591         wait_online = jiffies + (HBA_ONLINE_TOV * HZ);
4592         while (time_before(jiffies, wait_online)) {
4593
4594                 if (adapter_up(ha))
4595                         return QLA_SUCCESS;
4596
4597                 msleep(2000);
4598         }
4599
4600         return QLA_ERROR;
4601 }
4602
4603 /**
4604  * qla4xxx_eh_wait_for_commands - wait for active cmds to finish.
4605  * @ha: pointer to HBA
4606  * @t: target id
4607  * @l: lun id
4608  *
4609  * This function waits for all outstanding commands to a lun to complete. It
4610  * returns 0 if all pending commands are returned and 1 otherwise.
4611  **/
4612 static int qla4xxx_eh_wait_for_commands(struct scsi_qla_host *ha,
4613                                         struct scsi_target *stgt,
4614                                         struct scsi_device *sdev)
4615 {
4616         int cnt;
4617         int status = 0;
4618         struct scsi_cmnd *cmd;
4619
4620         /*
4621          * Waiting for all commands for the designated target or dev
4622          * in the active array
4623          */
4624         for (cnt = 0; cnt < ha->host->can_queue; cnt++) {
4625                 cmd = scsi_host_find_tag(ha->host, cnt);
4626                 if (cmd && stgt == scsi_target(cmd->device) &&
4627                     (!sdev || sdev == cmd->device)) {
4628                         if (!qla4xxx_eh_wait_on_command(ha, cmd)) {
4629                                 status++;
4630                                 break;
4631                         }
4632                 }
4633         }
4634         return status;
4635 }
4636
4637 /**
4638  * qla4xxx_eh_abort - callback for abort task.
4639  * @cmd: Pointer to Linux's SCSI command structure
4640  *
4641  * This routine is called by the Linux OS to abort the specified
4642  * command.
4643  **/
4644 static int qla4xxx_eh_abort(struct scsi_cmnd *cmd)
4645 {
4646         struct scsi_qla_host *ha = to_qla_host(cmd->device->host);
4647         unsigned int id = cmd->device->id;
4648         unsigned int lun = cmd->device->lun;
4649         unsigned long flags;
4650         struct srb *srb = NULL;
4651         int ret = SUCCESS;
4652         int wait = 0;
4653
4654         ql4_printk(KERN_INFO, ha,
4655             "scsi%ld:%d:%d: Abort command issued cmd=%p\n",
4656             ha->host_no, id, lun, cmd);
4657
4658         spin_lock_irqsave(&ha->hardware_lock, flags);
4659         srb = (struct srb *) CMD_SP(cmd);
4660         if (!srb) {
4661                 spin_unlock_irqrestore(&ha->hardware_lock, flags);
4662                 return SUCCESS;
4663         }
4664         kref_get(&srb->srb_ref);
4665         spin_unlock_irqrestore(&ha->hardware_lock, flags);
4666
4667         if (qla4xxx_abort_task(ha, srb) != QLA_SUCCESS) {
4668                 DEBUG3(printk("scsi%ld:%d:%d: Abort_task mbx failed.\n",
4669                     ha->host_no, id, lun));
4670                 ret = FAILED;
4671         } else {
4672                 DEBUG3(printk("scsi%ld:%d:%d: Abort_task mbx success.\n",
4673                     ha->host_no, id, lun));
4674                 wait = 1;
4675         }
4676
4677         kref_put(&srb->srb_ref, qla4xxx_srb_compl);
4678
4679         /* Wait for command to complete */
4680         if (wait) {
4681                 if (!qla4xxx_eh_wait_on_command(ha, cmd)) {
4682                         DEBUG2(printk("scsi%ld:%d:%d: Abort handler timed out\n",
4683                             ha->host_no, id, lun));
4684                         ret = FAILED;
4685                 }
4686         }
4687
4688         ql4_printk(KERN_INFO, ha,
4689             "scsi%ld:%d:%d: Abort command - %s\n",
4690             ha->host_no, id, lun, (ret == SUCCESS) ? "succeeded" : "failed");
4691
4692         return ret;
4693 }
4694
4695 /**
4696  * qla4xxx_eh_device_reset - callback for target reset.
4697  * @cmd: Pointer to Linux's SCSI command structure
4698  *
4699  * This routine is called by the Linux OS to reset all luns on the
4700  * specified target.
4701  **/
4702 static int qla4xxx_eh_device_reset(struct scsi_cmnd *cmd)
4703 {
4704         struct scsi_qla_host *ha = to_qla_host(cmd->device->host);
4705         struct ddb_entry *ddb_entry = cmd->device->hostdata;
4706         int ret = FAILED, stat;
4707
4708         if (!ddb_entry)
4709                 return ret;
4710
4711         ret = iscsi_block_scsi_eh(cmd);
4712         if (ret)
4713                 return ret;
4714         ret = FAILED;
4715
4716         ql4_printk(KERN_INFO, ha,
4717                    "scsi%ld:%d:%d:%d: DEVICE RESET ISSUED.\n", ha->host_no,
4718                    cmd->device->channel, cmd->device->id, cmd->device->lun);
4719
4720         DEBUG2(printk(KERN_INFO
4721                       "scsi%ld: DEVICE_RESET cmd=%p jiffies = 0x%lx, to=%x,"
4722                       "dpc_flags=%lx, status=%x allowed=%d\n", ha->host_no,
4723                       cmd, jiffies, cmd->request->timeout / HZ,
4724                       ha->dpc_flags, cmd->result, cmd->allowed));
4725
4726         /* FIXME: wait for hba to go online */
4727         stat = qla4xxx_reset_lun(ha, ddb_entry, cmd->device->lun);
4728         if (stat != QLA_SUCCESS) {
4729                 ql4_printk(KERN_INFO, ha, "DEVICE RESET FAILED. %d\n", stat);
4730                 goto eh_dev_reset_done;
4731         }
4732
4733         if (qla4xxx_eh_wait_for_commands(ha, scsi_target(cmd->device),
4734                                          cmd->device)) {
4735                 ql4_printk(KERN_INFO, ha,
4736                            "DEVICE RESET FAILED - waiting for "
4737                            "commands.\n");
4738                 goto eh_dev_reset_done;
4739         }
4740
4741         /* Send marker. */
4742         if (qla4xxx_send_marker_iocb(ha, ddb_entry, cmd->device->lun,
4743                 MM_LUN_RESET) != QLA_SUCCESS)
4744                 goto eh_dev_reset_done;
4745
4746         ql4_printk(KERN_INFO, ha,
4747                    "scsi(%ld:%d:%d:%d): DEVICE RESET SUCCEEDED.\n",
4748                    ha->host_no, cmd->device->channel, cmd->device->id,
4749                    cmd->device->lun);
4750
4751         ret = SUCCESS;
4752
4753 eh_dev_reset_done:
4754
4755         return ret;
4756 }
4757
4758 /**
4759  * qla4xxx_eh_target_reset - callback for target reset.
4760  * @cmd: Pointer to Linux's SCSI command structure
4761  *
4762  * This routine is called by the Linux OS to reset the target.
4763  **/
4764 static int qla4xxx_eh_target_reset(struct scsi_cmnd *cmd)
4765 {
4766         struct scsi_qla_host *ha = to_qla_host(cmd->device->host);
4767         struct ddb_entry *ddb_entry = cmd->device->hostdata;
4768         int stat, ret;
4769
4770         if (!ddb_entry)
4771                 return FAILED;
4772
4773         ret = iscsi_block_scsi_eh(cmd);
4774         if (ret)
4775                 return ret;
4776
4777         starget_printk(KERN_INFO, scsi_target(cmd->device),
4778                        "WARM TARGET RESET ISSUED.\n");
4779
4780         DEBUG2(printk(KERN_INFO
4781                       "scsi%ld: TARGET_DEVICE_RESET cmd=%p jiffies = 0x%lx, "
4782                       "to=%x,dpc_flags=%lx, status=%x allowed=%d\n",
4783                       ha->host_no, cmd, jiffies, cmd->request->timeout / HZ,
4784                       ha->dpc_flags, cmd->result, cmd->allowed));
4785
4786         stat = qla4xxx_reset_target(ha, ddb_entry);
4787         if (stat != QLA_SUCCESS) {
4788                 starget_printk(KERN_INFO, scsi_target(cmd->device),
4789                                "WARM TARGET RESET FAILED.\n");
4790                 return FAILED;
4791         }
4792
4793         if (qla4xxx_eh_wait_for_commands(ha, scsi_target(cmd->device),
4794                                          NULL)) {
4795                 starget_printk(KERN_INFO, scsi_target(cmd->device),
4796                                "WARM TARGET DEVICE RESET FAILED - "
4797                                "waiting for commands.\n");
4798                 return FAILED;
4799         }
4800
4801         /* Send marker. */
4802         if (qla4xxx_send_marker_iocb(ha, ddb_entry, cmd->device->lun,
4803                 MM_TGT_WARM_RESET) != QLA_SUCCESS) {
4804                 starget_printk(KERN_INFO, scsi_target(cmd->device),
4805                                "WARM TARGET DEVICE RESET FAILED - "
4806                                "marker iocb failed.\n");
4807                 return FAILED;
4808         }
4809
4810         starget_printk(KERN_INFO, scsi_target(cmd->device),
4811                        "WARM TARGET RESET SUCCEEDED.\n");
4812         return SUCCESS;
4813 }
4814
4815 /**
4816  * qla4xxx_eh_host_reset - kernel callback
4817  * @cmd: Pointer to Linux's SCSI command structure
4818  *
4819  * This routine is invoked by the Linux kernel to perform fatal error
4820  * recovery on the specified adapter.
4821  **/
4822 static int qla4xxx_eh_host_reset(struct scsi_cmnd *cmd)
4823 {
4824         int return_status = FAILED;
4825         struct scsi_qla_host *ha;
4826
4827         ha = to_qla_host(cmd->device->host);
4828
4829         if (ql4xdontresethba) {
4830                 DEBUG2(printk("scsi%ld: %s: Don't Reset HBA\n",
4831                      ha->host_no, __func__));
4832                 return FAILED;
4833         }
4834
4835         ql4_printk(KERN_INFO, ha,
4836                    "scsi(%ld:%d:%d:%d): HOST RESET ISSUED.\n", ha->host_no,
4837                    cmd->device->channel, cmd->device->id, cmd->device->lun);
4838
4839         if (qla4xxx_wait_for_hba_online(ha) != QLA_SUCCESS) {
4840                 DEBUG2(printk("scsi%ld:%d: %s: Unable to reset host.  Adapter "
4841                               "DEAD.\n", ha->host_no, cmd->device->channel,
4842                               __func__));
4843
4844                 return FAILED;
4845         }
4846
4847         if (!test_bit(DPC_RESET_HA, &ha->dpc_flags)) {
4848                 if (is_qla8022(ha))
4849                         set_bit(DPC_RESET_HA_FW_CONTEXT, &ha->dpc_flags);
4850                 else
4851                         set_bit(DPC_RESET_HA, &ha->dpc_flags);
4852         }
4853
4854         if (qla4xxx_recover_adapter(ha) == QLA_SUCCESS)
4855                 return_status = SUCCESS;
4856
4857         ql4_printk(KERN_INFO, ha, "HOST RESET %s.\n",
4858                    return_status == FAILED ? "FAILED" : "SUCCEEDED");
4859
4860         return return_status;
4861 }
4862
4863 static int qla4xxx_context_reset(struct scsi_qla_host *ha)
4864 {
4865         uint32_t mbox_cmd[MBOX_REG_COUNT];
4866         uint32_t mbox_sts[MBOX_REG_COUNT];
4867         struct addr_ctrl_blk_def *acb = NULL;
4868         uint32_t acb_len = sizeof(struct addr_ctrl_blk_def);
4869         int rval = QLA_SUCCESS;
4870         dma_addr_t acb_dma;
4871
4872         acb = dma_alloc_coherent(&ha->pdev->dev,
4873                                  sizeof(struct addr_ctrl_blk_def),
4874                                  &acb_dma, GFP_KERNEL);
4875         if (!acb) {
4876                 ql4_printk(KERN_ERR, ha, "%s: Unable to alloc acb\n",
4877                            __func__);
4878                 rval = -ENOMEM;
4879                 goto exit_port_reset;
4880         }
4881
4882         memset(acb, 0, acb_len);
4883
4884         rval = qla4xxx_get_acb(ha, acb_dma, PRIMARI_ACB, acb_len);
4885         if (rval != QLA_SUCCESS) {
4886                 rval = -EIO;
4887                 goto exit_free_acb;
4888         }
4889
4890         rval = qla4xxx_disable_acb(ha);
4891         if (rval != QLA_SUCCESS) {
4892                 rval = -EIO;
4893                 goto exit_free_acb;
4894         }
4895
4896         wait_for_completion_timeout(&ha->disable_acb_comp,
4897                                     DISABLE_ACB_TOV * HZ);
4898
4899         rval = qla4xxx_set_acb(ha, &mbox_cmd[0], &mbox_sts[0], acb_dma);
4900         if (rval != QLA_SUCCESS) {
4901                 rval = -EIO;
4902                 goto exit_free_acb;
4903         }
4904
4905 exit_free_acb:
4906         dma_free_coherent(&ha->pdev->dev, sizeof(struct addr_ctrl_blk_def),
4907                           acb, acb_dma);
4908 exit_port_reset:
4909         DEBUG2(ql4_printk(KERN_INFO, ha, "%s %s\n", __func__,
4910                           rval == QLA_SUCCESS ? "SUCCEEDED" : "FAILED"));
4911         return rval;
4912 }
4913
4914 static int qla4xxx_host_reset(struct Scsi_Host *shost, int reset_type)
4915 {
4916         struct scsi_qla_host *ha = to_qla_host(shost);
4917         int rval = QLA_SUCCESS;
4918
4919         if (ql4xdontresethba) {
4920                 DEBUG2(ql4_printk(KERN_INFO, ha, "%s: Don't Reset HBA\n",
4921                                   __func__));
4922                 rval = -EPERM;
4923                 goto exit_host_reset;
4924         }
4925
4926         rval = qla4xxx_wait_for_hba_online(ha);
4927         if (rval != QLA_SUCCESS) {
4928                 DEBUG2(ql4_printk(KERN_INFO, ha, "%s: Unable to reset host "
4929                                   "adapter\n", __func__));
4930                 rval = -EIO;
4931                 goto exit_host_reset;
4932         }
4933
4934         if (test_bit(DPC_RESET_HA, &ha->dpc_flags))
4935                 goto recover_adapter;
4936
4937         switch (reset_type) {
4938         case SCSI_ADAPTER_RESET:
4939                 set_bit(DPC_RESET_HA, &ha->dpc_flags);
4940                 break;
4941         case SCSI_FIRMWARE_RESET:
4942                 if (!test_bit(DPC_RESET_HA, &ha->dpc_flags)) {
4943                         if (is_qla8022(ha))
4944                                 /* set firmware context reset */
4945                                 set_bit(DPC_RESET_HA_FW_CONTEXT,
4946                                         &ha->dpc_flags);
4947                         else {
4948                                 rval = qla4xxx_context_reset(ha);
4949                                 goto exit_host_reset;
4950                         }
4951                 }
4952                 break;
4953         }
4954
4955 recover_adapter:
4956         rval = qla4xxx_recover_adapter(ha);
4957         if (rval != QLA_SUCCESS) {
4958                 DEBUG2(ql4_printk(KERN_INFO, ha, "%s: recover adapter fail\n",
4959                                   __func__));
4960                 rval = -EIO;
4961         }
4962
4963 exit_host_reset:
4964         return rval;
4965 }
4966
4967 /* PCI AER driver recovers from all correctable errors w/o
4968  * driver intervention. For uncorrectable errors PCI AER
4969  * driver calls the following device driver's callbacks
4970  *
4971  * - Fatal Errors - link_reset
4972  * - Non-Fatal Errors - driver's pci_error_detected() which
4973  * returns CAN_RECOVER, NEED_RESET or DISCONNECT.
4974  *
4975  * PCI AER driver calls
4976  * CAN_RECOVER - driver's pci_mmio_enabled(), mmio_enabled
4977  *               returns RECOVERED or NEED_RESET if fw_hung
4978  * NEED_RESET - driver's slot_reset()
4979  * DISCONNECT - device is dead & cannot recover
4980  * RECOVERED - driver's pci_resume()
4981  */
4982 static pci_ers_result_t
4983 qla4xxx_pci_error_detected(struct pci_dev *pdev, pci_channel_state_t state)
4984 {
4985         struct scsi_qla_host *ha = pci_get_drvdata(pdev);
4986
4987         ql4_printk(KERN_WARNING, ha, "scsi%ld: %s: error detected:state %x\n",
4988             ha->host_no, __func__, state);
4989
4990         if (!is_aer_supported(ha))
4991                 return PCI_ERS_RESULT_NONE;
4992
4993         switch (state) {
4994         case pci_channel_io_normal:
4995                 clear_bit(AF_EEH_BUSY, &ha->flags);
4996                 return PCI_ERS_RESULT_CAN_RECOVER;
4997         case pci_channel_io_frozen:
4998                 set_bit(AF_EEH_BUSY, &ha->flags);
4999                 qla4xxx_mailbox_premature_completion(ha);
5000                 qla4xxx_free_irqs(ha);
5001                 pci_disable_device(pdev);
5002                 /* Return back all IOs */
5003                 qla4xxx_abort_active_cmds(ha, DID_RESET << 16);
5004                 return PCI_ERS_RESULT_NEED_RESET;
5005         case pci_channel_io_perm_failure:
5006                 set_bit(AF_EEH_BUSY, &ha->flags);
5007                 set_bit(AF_PCI_CHANNEL_IO_PERM_FAILURE, &ha->flags);
5008                 qla4xxx_abort_active_cmds(ha, DID_NO_CONNECT << 16);
5009                 return PCI_ERS_RESULT_DISCONNECT;
5010         }
5011         return PCI_ERS_RESULT_NEED_RESET;
5012 }
5013
5014 /**
5015  * qla4xxx_pci_mmio_enabled() gets called if
5016  * qla4xxx_pci_error_detected() returns PCI_ERS_RESULT_CAN_RECOVER
5017  * and read/write to the device still works.
5018  **/
5019 static pci_ers_result_t
5020 qla4xxx_pci_mmio_enabled(struct pci_dev *pdev)
5021 {
5022         struct scsi_qla_host *ha = pci_get_drvdata(pdev);
5023
5024         if (!is_aer_supported(ha))
5025                 return PCI_ERS_RESULT_NONE;
5026
5027         return PCI_ERS_RESULT_RECOVERED;
5028 }
5029
5030 static uint32_t qla4_8xxx_error_recovery(struct scsi_qla_host *ha)
5031 {
5032         uint32_t rval = QLA_ERROR;
5033         uint32_t ret = 0;
5034         int fn;
5035         struct pci_dev *other_pdev = NULL;
5036
5037         ql4_printk(KERN_WARNING, ha, "scsi%ld: In %s\n", ha->host_no, __func__);
5038
5039         set_bit(DPC_RESET_ACTIVE, &ha->dpc_flags);
5040
5041         if (test_bit(AF_ONLINE, &ha->flags)) {
5042                 clear_bit(AF_ONLINE, &ha->flags);
5043                 clear_bit(AF_LINK_UP, &ha->flags);
5044                 iscsi_host_for_each_session(ha->host, qla4xxx_fail_session);
5045                 qla4xxx_process_aen(ha, FLUSH_DDB_CHANGED_AENS);
5046         }
5047
5048         fn = PCI_FUNC(ha->pdev->devfn);
5049         while (fn > 0) {
5050                 fn--;
5051                 ql4_printk(KERN_INFO, ha, "scsi%ld: %s: Finding PCI device at "
5052                     "func %x\n", ha->host_no, __func__, fn);
5053                 /* Get the pci device given the domain, bus,
5054                  * slot/function number */
5055                 other_pdev =
5056                     pci_get_domain_bus_and_slot(pci_domain_nr(ha->pdev->bus),
5057                     ha->pdev->bus->number, PCI_DEVFN(PCI_SLOT(ha->pdev->devfn),
5058                     fn));
5059
5060                 if (!other_pdev)
5061                         continue;
5062
5063                 if (atomic_read(&other_pdev->enable_cnt)) {
5064                         ql4_printk(KERN_INFO, ha, "scsi%ld: %s: Found PCI "
5065                             "func in enabled state%x\n", ha->host_no,
5066                             __func__, fn);
5067                         pci_dev_put(other_pdev);
5068                         break;
5069                 }
5070                 pci_dev_put(other_pdev);
5071         }
5072
5073         /* The first function on the card, the reset owner will
5074          * start & initialize the firmware. The other functions
5075          * on the card will reset the firmware context
5076          */
5077         if (!fn) {
5078                 ql4_printk(KERN_INFO, ha, "scsi%ld: %s: devfn being reset "
5079                     "0x%x is the owner\n", ha->host_no, __func__,
5080                     ha->pdev->devfn);
5081
5082                 qla4_8xxx_idc_lock(ha);
5083                 qla4_8xxx_wr_32(ha, QLA82XX_CRB_DEV_STATE,
5084                     QLA82XX_DEV_COLD);
5085
5086                 qla4_8xxx_wr_32(ha, QLA82XX_CRB_DRV_IDC_VERSION,
5087                     QLA82XX_IDC_VERSION);
5088
5089                 qla4_8xxx_idc_unlock(ha);
5090                 clear_bit(AF_FW_RECOVERY, &ha->flags);
5091                 rval = qla4xxx_initialize_adapter(ha, RESET_ADAPTER);
5092                 qla4_8xxx_idc_lock(ha);
5093
5094                 if (rval != QLA_SUCCESS) {
5095                         ql4_printk(KERN_INFO, ha, "scsi%ld: %s: HW State: "
5096                             "FAILED\n", ha->host_no, __func__);
5097                         qla4_8xxx_clear_drv_active(ha);
5098                         qla4_8xxx_wr_32(ha, QLA82XX_CRB_DEV_STATE,
5099                             QLA82XX_DEV_FAILED);
5100                 } else {
5101                         ql4_printk(KERN_INFO, ha, "scsi%ld: %s: HW State: "
5102                             "READY\n", ha->host_no, __func__);
5103                         qla4_8xxx_wr_32(ha, QLA82XX_CRB_DEV_STATE,
5104                             QLA82XX_DEV_READY);
5105                         /* Clear driver state register */
5106                         qla4_8xxx_wr_32(ha, QLA82XX_CRB_DRV_STATE, 0);
5107                         qla4_8xxx_set_drv_active(ha);
5108                         ret = qla4xxx_request_irqs(ha);
5109                         if (ret) {
5110                                 ql4_printk(KERN_WARNING, ha, "Failed to "
5111                                     "reserve interrupt %d already in use.\n",
5112                                     ha->pdev->irq);
5113                                 rval = QLA_ERROR;
5114                         } else {
5115                                 ha->isp_ops->enable_intrs(ha);
5116                                 rval = QLA_SUCCESS;
5117                         }
5118                 }
5119                 qla4_8xxx_idc_unlock(ha);
5120         } else {
5121                 ql4_printk(KERN_INFO, ha, "scsi%ld: %s: devfn 0x%x is not "
5122                     "the reset owner\n", ha->host_no, __func__,
5123                     ha->pdev->devfn);
5124                 if ((qla4_8xxx_rd_32(ha, QLA82XX_CRB_DEV_STATE) ==
5125                     QLA82XX_DEV_READY)) {
5126                         clear_bit(AF_FW_RECOVERY, &ha->flags);
5127                         rval = qla4xxx_initialize_adapter(ha, RESET_ADAPTER);
5128                         if (rval == QLA_SUCCESS) {
5129                                 ret = qla4xxx_request_irqs(ha);
5130                                 if (ret) {
5131                                         ql4_printk(KERN_WARNING, ha, "Failed to"
5132                                             " reserve interrupt %d already in"
5133                                             " use.\n", ha->pdev->irq);
5134                                         rval = QLA_ERROR;
5135                                 } else {
5136                                         ha->isp_ops->enable_intrs(ha);
5137                                         rval = QLA_SUCCESS;
5138                                 }
5139                         }
5140                         qla4_8xxx_idc_lock(ha);
5141                         qla4_8xxx_set_drv_active(ha);
5142                         qla4_8xxx_idc_unlock(ha);
5143                 }
5144         }
5145         clear_bit(DPC_RESET_ACTIVE, &ha->dpc_flags);
5146         return rval;
5147 }
5148
5149 static pci_ers_result_t
5150 qla4xxx_pci_slot_reset(struct pci_dev *pdev)
5151 {
5152         pci_ers_result_t ret = PCI_ERS_RESULT_DISCONNECT;
5153         struct scsi_qla_host *ha = pci_get_drvdata(pdev);
5154         int rc;
5155
5156         ql4_printk(KERN_WARNING, ha, "scsi%ld: %s: slot_reset\n",
5157             ha->host_no, __func__);
5158
5159         if (!is_aer_supported(ha))
5160                 return PCI_ERS_RESULT_NONE;
5161
5162         /* Restore the saved state of PCIe device -
5163          * BAR registers, PCI Config space, PCIX, MSI,
5164          * IOV states
5165          */
5166         pci_restore_state(pdev);
5167
5168         /* pci_restore_state() clears the saved_state flag of the device
5169          * save restored state which resets saved_state flag
5170          */
5171         pci_save_state(pdev);
5172
5173         /* Initialize device or resume if in suspended state */
5174         rc = pci_enable_device(pdev);
5175         if (rc) {
5176                 ql4_printk(KERN_WARNING, ha, "scsi%ld: %s: Can't re-enable "
5177                     "device after reset\n", ha->host_no, __func__);
5178                 goto exit_slot_reset;
5179         }
5180
5181         ha->isp_ops->disable_intrs(ha);
5182
5183         if (is_qla8022(ha)) {
5184                 if (qla4_8xxx_error_recovery(ha) == QLA_SUCCESS) {
5185                         ret = PCI_ERS_RESULT_RECOVERED;
5186                         goto exit_slot_reset;
5187                 } else
5188                         goto exit_slot_reset;
5189         }
5190
5191 exit_slot_reset:
5192         ql4_printk(KERN_WARNING, ha, "scsi%ld: %s: Return=%x\n"
5193             "device after reset\n", ha->host_no, __func__, ret);
5194         return ret;
5195 }
5196
5197 static void
5198 qla4xxx_pci_resume(struct pci_dev *pdev)
5199 {
5200         struct scsi_qla_host *ha = pci_get_drvdata(pdev);
5201         int ret;
5202
5203         ql4_printk(KERN_WARNING, ha, "scsi%ld: %s: pci_resume\n",
5204             ha->host_no, __func__);
5205
5206         ret = qla4xxx_wait_for_hba_online(ha);
5207         if (ret != QLA_SUCCESS) {
5208                 ql4_printk(KERN_ERR, ha, "scsi%ld: %s: the device failed to "
5209                     "resume I/O from slot/link_reset\n", ha->host_no,
5210                      __func__);
5211         }
5212
5213         pci_cleanup_aer_uncorrect_error_status(pdev);
5214         clear_bit(AF_EEH_BUSY, &ha->flags);
5215 }
5216
5217 static struct pci_error_handlers qla4xxx_err_handler = {
5218         .error_detected = qla4xxx_pci_error_detected,
5219         .mmio_enabled = qla4xxx_pci_mmio_enabled,
5220         .slot_reset = qla4xxx_pci_slot_reset,
5221         .resume = qla4xxx_pci_resume,
5222 };
5223
5224 static struct pci_device_id qla4xxx_pci_tbl[] = {
5225         {
5226                 .vendor         = PCI_VENDOR_ID_QLOGIC,
5227                 .device         = PCI_DEVICE_ID_QLOGIC_ISP4010,
5228                 .subvendor      = PCI_ANY_ID,
5229                 .subdevice      = PCI_ANY_ID,
5230         },
5231         {
5232                 .vendor         = PCI_VENDOR_ID_QLOGIC,
5233                 .device         = PCI_DEVICE_ID_QLOGIC_ISP4022,
5234                 .subvendor      = PCI_ANY_ID,
5235                 .subdevice      = PCI_ANY_ID,
5236         },
5237         {
5238                 .vendor         = PCI_VENDOR_ID_QLOGIC,
5239                 .device         = PCI_DEVICE_ID_QLOGIC_ISP4032,
5240                 .subvendor      = PCI_ANY_ID,
5241                 .subdevice      = PCI_ANY_ID,
5242         },
5243         {
5244                 .vendor         = PCI_VENDOR_ID_QLOGIC,
5245                 .device         = PCI_DEVICE_ID_QLOGIC_ISP8022,
5246                 .subvendor      = PCI_ANY_ID,
5247                 .subdevice      = PCI_ANY_ID,
5248         },
5249         {0, 0},
5250 };
5251 MODULE_DEVICE_TABLE(pci, qla4xxx_pci_tbl);
5252
5253 static struct pci_driver qla4xxx_pci_driver = {
5254         .name           = DRIVER_NAME,
5255         .id_table       = qla4xxx_pci_tbl,
5256         .probe          = qla4xxx_probe_adapter,
5257         .remove         = qla4xxx_remove_adapter,
5258         .err_handler = &qla4xxx_err_handler,
5259 };
5260
5261 static int __init qla4xxx_module_init(void)
5262 {
5263         int ret;
5264
5265         /* Allocate cache for SRBs. */
5266         srb_cachep = kmem_cache_create("qla4xxx_srbs", sizeof(struct srb), 0,
5267                                        SLAB_HWCACHE_ALIGN, NULL);
5268         if (srb_cachep == NULL) {
5269                 printk(KERN_ERR
5270                        "%s: Unable to allocate SRB cache..."
5271                        "Failing load!\n", DRIVER_NAME);
5272                 ret = -ENOMEM;
5273                 goto no_srp_cache;
5274         }
5275
5276         /* Derive version string. */
5277         strcpy(qla4xxx_version_str, QLA4XXX_DRIVER_VERSION);
5278         if (ql4xextended_error_logging)
5279                 strcat(qla4xxx_version_str, "-debug");
5280
5281         qla4xxx_scsi_transport =
5282                 iscsi_register_transport(&qla4xxx_iscsi_transport);
5283         if (!qla4xxx_scsi_transport){
5284                 ret = -ENODEV;
5285                 goto release_srb_cache;
5286         }
5287
5288         ret = pci_register_driver(&qla4xxx_pci_driver);
5289         if (ret)
5290                 goto unregister_transport;
5291
5292         printk(KERN_INFO "QLogic iSCSI HBA Driver\n");
5293         return 0;
5294
5295 unregister_transport:
5296         iscsi_unregister_transport(&qla4xxx_iscsi_transport);
5297 release_srb_cache:
5298         kmem_cache_destroy(srb_cachep);
5299 no_srp_cache:
5300         return ret;
5301 }
5302
5303 static void __exit qla4xxx_module_exit(void)
5304 {
5305         pci_unregister_driver(&qla4xxx_pci_driver);
5306         iscsi_unregister_transport(&qla4xxx_iscsi_transport);
5307         kmem_cache_destroy(srb_cachep);
5308 }
5309
5310 module_init(qla4xxx_module_init);
5311 module_exit(qla4xxx_module_exit);
5312
5313 MODULE_AUTHOR("QLogic Corporation");
5314 MODULE_DESCRIPTION("QLogic iSCSI HBA Driver");
5315 MODULE_LICENSE("GPL");
5316 MODULE_VERSION(QLA4XXX_DRIVER_VERSION);