Merge tag 'netfs-lib-20210426' of git://git.kernel.org/pub/scm/linux/kernel/git/dhowe...
[linux-2.6-microblaze.git] / drivers / scsi / ibmvscsi / ibmvfc.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * ibmvfc.c -- driver for IBM Power Virtual Fibre Channel Adapter
4  *
5  * Written By: Brian King <brking@linux.vnet.ibm.com>, IBM Corporation
6  *
7  * Copyright (C) IBM Corporation, 2008
8  */
9
10 #include <linux/module.h>
11 #include <linux/moduleparam.h>
12 #include <linux/dma-mapping.h>
13 #include <linux/dmapool.h>
14 #include <linux/delay.h>
15 #include <linux/interrupt.h>
16 #include <linux/kthread.h>
17 #include <linux/slab.h>
18 #include <linux/of.h>
19 #include <linux/pm.h>
20 #include <linux/stringify.h>
21 #include <linux/bsg-lib.h>
22 #include <asm/firmware.h>
23 #include <asm/irq.h>
24 #include <asm/rtas.h>
25 #include <asm/vio.h>
26 #include <scsi/scsi.h>
27 #include <scsi/scsi_cmnd.h>
28 #include <scsi/scsi_host.h>
29 #include <scsi/scsi_device.h>
30 #include <scsi/scsi_tcq.h>
31 #include <scsi/scsi_transport_fc.h>
32 #include <scsi/scsi_bsg_fc.h>
33 #include "ibmvfc.h"
34
35 static unsigned int init_timeout = IBMVFC_INIT_TIMEOUT;
36 static unsigned int default_timeout = IBMVFC_DEFAULT_TIMEOUT;
37 static u64 max_lun = IBMVFC_MAX_LUN;
38 static unsigned int max_targets = IBMVFC_MAX_TARGETS;
39 static unsigned int max_requests = IBMVFC_MAX_REQUESTS_DEFAULT;
40 static unsigned int disc_threads = IBMVFC_MAX_DISC_THREADS;
41 static unsigned int ibmvfc_debug = IBMVFC_DEBUG;
42 static unsigned int log_level = IBMVFC_DEFAULT_LOG_LEVEL;
43 static unsigned int cls3_error = IBMVFC_CLS3_ERROR;
44 static unsigned int mq_enabled = IBMVFC_MQ;
45 static unsigned int nr_scsi_hw_queues = IBMVFC_SCSI_HW_QUEUES;
46 static unsigned int nr_scsi_channels = IBMVFC_SCSI_CHANNELS;
47 static unsigned int mig_channels_only = IBMVFC_MIG_NO_SUB_TO_CRQ;
48 static unsigned int mig_no_less_channels = IBMVFC_MIG_NO_N_TO_M;
49
50 static LIST_HEAD(ibmvfc_head);
51 static DEFINE_SPINLOCK(ibmvfc_driver_lock);
52 static struct scsi_transport_template *ibmvfc_transport_template;
53
54 MODULE_DESCRIPTION("IBM Virtual Fibre Channel Driver");
55 MODULE_AUTHOR("Brian King <brking@linux.vnet.ibm.com>");
56 MODULE_LICENSE("GPL");
57 MODULE_VERSION(IBMVFC_DRIVER_VERSION);
58
59 module_param_named(mq, mq_enabled, uint, S_IRUGO);
60 MODULE_PARM_DESC(mq, "Enable multiqueue support. "
61                  "[Default=" __stringify(IBMVFC_MQ) "]");
62 module_param_named(scsi_host_queues, nr_scsi_hw_queues, uint, S_IRUGO);
63 MODULE_PARM_DESC(scsi_host_queues, "Number of SCSI Host submission queues. "
64                  "[Default=" __stringify(IBMVFC_SCSI_HW_QUEUES) "]");
65 module_param_named(scsi_hw_channels, nr_scsi_channels, uint, S_IRUGO);
66 MODULE_PARM_DESC(scsi_hw_channels, "Number of hw scsi channels to request. "
67                  "[Default=" __stringify(IBMVFC_SCSI_CHANNELS) "]");
68 module_param_named(mig_channels_only, mig_channels_only, uint, S_IRUGO);
69 MODULE_PARM_DESC(mig_channels_only, "Prevent migration to non-channelized system. "
70                  "[Default=" __stringify(IBMVFC_MIG_NO_SUB_TO_CRQ) "]");
71 module_param_named(mig_no_less_channels, mig_no_less_channels, uint, S_IRUGO);
72 MODULE_PARM_DESC(mig_no_less_channels, "Prevent migration to system with less channels. "
73                  "[Default=" __stringify(IBMVFC_MIG_NO_N_TO_M) "]");
74
75 module_param_named(init_timeout, init_timeout, uint, S_IRUGO | S_IWUSR);
76 MODULE_PARM_DESC(init_timeout, "Initialization timeout in seconds. "
77                  "[Default=" __stringify(IBMVFC_INIT_TIMEOUT) "]");
78 module_param_named(default_timeout, default_timeout, uint, S_IRUGO | S_IWUSR);
79 MODULE_PARM_DESC(default_timeout,
80                  "Default timeout in seconds for initialization and EH commands. "
81                  "[Default=" __stringify(IBMVFC_DEFAULT_TIMEOUT) "]");
82 module_param_named(max_requests, max_requests, uint, S_IRUGO);
83 MODULE_PARM_DESC(max_requests, "Maximum requests for this adapter. "
84                  "[Default=" __stringify(IBMVFC_MAX_REQUESTS_DEFAULT) "]");
85 module_param_named(max_lun, max_lun, ullong, S_IRUGO);
86 MODULE_PARM_DESC(max_lun, "Maximum allowed LUN. "
87                  "[Default=" __stringify(IBMVFC_MAX_LUN) "]");
88 module_param_named(max_targets, max_targets, uint, S_IRUGO);
89 MODULE_PARM_DESC(max_targets, "Maximum allowed targets. "
90                  "[Default=" __stringify(IBMVFC_MAX_TARGETS) "]");
91 module_param_named(disc_threads, disc_threads, uint, S_IRUGO);
92 MODULE_PARM_DESC(disc_threads, "Number of device discovery threads to use. "
93                  "[Default=" __stringify(IBMVFC_MAX_DISC_THREADS) "]");
94 module_param_named(debug, ibmvfc_debug, uint, S_IRUGO | S_IWUSR);
95 MODULE_PARM_DESC(debug, "Enable driver debug information. "
96                  "[Default=" __stringify(IBMVFC_DEBUG) "]");
97 module_param_named(log_level, log_level, uint, 0);
98 MODULE_PARM_DESC(log_level, "Set to 0 - 4 for increasing verbosity of device driver. "
99                  "[Default=" __stringify(IBMVFC_DEFAULT_LOG_LEVEL) "]");
100 module_param_named(cls3_error, cls3_error, uint, 0);
101 MODULE_PARM_DESC(cls3_error, "Enable FC Class 3 Error Recovery. "
102                  "[Default=" __stringify(IBMVFC_CLS3_ERROR) "]");
103
104 static const struct {
105         u16 status;
106         u16 error;
107         u8 result;
108         u8 retry;
109         int log;
110         char *name;
111 } cmd_status [] = {
112         { IBMVFC_FABRIC_MAPPED, IBMVFC_UNABLE_TO_ESTABLISH, DID_ERROR, 1, 1, "unable to establish" },
113         { IBMVFC_FABRIC_MAPPED, IBMVFC_XPORT_FAULT, DID_OK, 1, 0, "transport fault" },
114         { IBMVFC_FABRIC_MAPPED, IBMVFC_CMD_TIMEOUT, DID_TIME_OUT, 1, 1, "command timeout" },
115         { IBMVFC_FABRIC_MAPPED, IBMVFC_ENETDOWN, DID_TRANSPORT_DISRUPTED, 1, 1, "network down" },
116         { IBMVFC_FABRIC_MAPPED, IBMVFC_HW_FAILURE, DID_ERROR, 1, 1, "hardware failure" },
117         { IBMVFC_FABRIC_MAPPED, IBMVFC_LINK_DOWN_ERR, DID_REQUEUE, 0, 0, "link down" },
118         { IBMVFC_FABRIC_MAPPED, IBMVFC_LINK_DEAD_ERR, DID_ERROR, 0, 0, "link dead" },
119         { IBMVFC_FABRIC_MAPPED, IBMVFC_UNABLE_TO_REGISTER, DID_ERROR, 1, 1, "unable to register" },
120         { IBMVFC_FABRIC_MAPPED, IBMVFC_XPORT_BUSY, DID_BUS_BUSY, 1, 0, "transport busy" },
121         { IBMVFC_FABRIC_MAPPED, IBMVFC_XPORT_DEAD, DID_ERROR, 0, 1, "transport dead" },
122         { IBMVFC_FABRIC_MAPPED, IBMVFC_CONFIG_ERROR, DID_ERROR, 1, 1, "configuration error" },
123         { IBMVFC_FABRIC_MAPPED, IBMVFC_NAME_SERVER_FAIL, DID_ERROR, 1, 1, "name server failure" },
124         { IBMVFC_FABRIC_MAPPED, IBMVFC_LINK_HALTED, DID_REQUEUE, 1, 0, "link halted" },
125         { IBMVFC_FABRIC_MAPPED, IBMVFC_XPORT_GENERAL, DID_OK, 1, 0, "general transport error" },
126
127         { IBMVFC_VIOS_FAILURE, IBMVFC_CRQ_FAILURE, DID_REQUEUE, 1, 1, "CRQ failure" },
128         { IBMVFC_VIOS_FAILURE, IBMVFC_SW_FAILURE, DID_ERROR, 0, 1, "software failure" },
129         { IBMVFC_VIOS_FAILURE, IBMVFC_INVALID_PARAMETER, DID_ERROR, 0, 1, "invalid parameter" },
130         { IBMVFC_VIOS_FAILURE, IBMVFC_MISSING_PARAMETER, DID_ERROR, 0, 1, "missing parameter" },
131         { IBMVFC_VIOS_FAILURE, IBMVFC_HOST_IO_BUS, DID_ERROR, 1, 1, "host I/O bus failure" },
132         { IBMVFC_VIOS_FAILURE, IBMVFC_TRANS_CANCELLED, DID_ERROR, 0, 1, "transaction cancelled" },
133         { IBMVFC_VIOS_FAILURE, IBMVFC_TRANS_CANCELLED_IMPLICIT, DID_ERROR, 0, 1, "transaction cancelled implicit" },
134         { IBMVFC_VIOS_FAILURE, IBMVFC_INSUFFICIENT_RESOURCE, DID_REQUEUE, 1, 1, "insufficient resources" },
135         { IBMVFC_VIOS_FAILURE, IBMVFC_PLOGI_REQUIRED, DID_ERROR, 0, 1, "port login required" },
136         { IBMVFC_VIOS_FAILURE, IBMVFC_COMMAND_FAILED, DID_ERROR, 1, 1, "command failed" },
137
138         { IBMVFC_FC_FAILURE, IBMVFC_INVALID_ELS_CMD_CODE, DID_ERROR, 0, 1, "invalid ELS command code" },
139         { IBMVFC_FC_FAILURE, IBMVFC_INVALID_VERSION, DID_ERROR, 0, 1, "invalid version level" },
140         { IBMVFC_FC_FAILURE, IBMVFC_LOGICAL_ERROR, DID_ERROR, 1, 1, "logical error" },
141         { IBMVFC_FC_FAILURE, IBMVFC_INVALID_CT_IU_SIZE, DID_ERROR, 0, 1, "invalid CT_IU size" },
142         { IBMVFC_FC_FAILURE, IBMVFC_LOGICAL_BUSY, DID_REQUEUE, 1, 0, "logical busy" },
143         { IBMVFC_FC_FAILURE, IBMVFC_PROTOCOL_ERROR, DID_ERROR, 1, 1, "protocol error" },
144         { IBMVFC_FC_FAILURE, IBMVFC_UNABLE_TO_PERFORM_REQ, DID_ERROR, 1, 1, "unable to perform request" },
145         { IBMVFC_FC_FAILURE, IBMVFC_CMD_NOT_SUPPORTED, DID_ERROR, 0, 0, "command not supported" },
146         { IBMVFC_FC_FAILURE, IBMVFC_SERVER_NOT_AVAIL, DID_ERROR, 0, 1, "server not available" },
147         { IBMVFC_FC_FAILURE, IBMVFC_CMD_IN_PROGRESS, DID_ERROR, 0, 1, "command already in progress" },
148         { IBMVFC_FC_FAILURE, IBMVFC_VENDOR_SPECIFIC, DID_ERROR, 1, 1, "vendor specific" },
149
150         { IBMVFC_FC_SCSI_ERROR, 0, DID_OK, 1, 0, "SCSI error" },
151         { IBMVFC_FC_SCSI_ERROR, IBMVFC_COMMAND_FAILED, DID_ERROR, 0, 1, "PRLI to device failed." },
152 };
153
154 static void ibmvfc_npiv_login(struct ibmvfc_host *);
155 static void ibmvfc_tgt_send_prli(struct ibmvfc_target *);
156 static void ibmvfc_tgt_send_plogi(struct ibmvfc_target *);
157 static void ibmvfc_tgt_query_target(struct ibmvfc_target *);
158 static void ibmvfc_npiv_logout(struct ibmvfc_host *);
159 static void ibmvfc_tgt_implicit_logout_and_del(struct ibmvfc_target *);
160 static void ibmvfc_tgt_move_login(struct ibmvfc_target *);
161
162 static void ibmvfc_release_sub_crqs(struct ibmvfc_host *);
163 static void ibmvfc_init_sub_crqs(struct ibmvfc_host *);
164
165 static const char *unknown_error = "unknown error";
166
167 static long h_reg_sub_crq(unsigned long unit_address, unsigned long ioba,
168                           unsigned long length, unsigned long *cookie,
169                           unsigned long *irq)
170 {
171         unsigned long retbuf[PLPAR_HCALL_BUFSIZE];
172         long rc;
173
174         rc = plpar_hcall(H_REG_SUB_CRQ, retbuf, unit_address, ioba, length);
175         *cookie = retbuf[0];
176         *irq = retbuf[1];
177
178         return rc;
179 }
180
181 static int ibmvfc_check_caps(struct ibmvfc_host *vhost, unsigned long cap_flags)
182 {
183         u64 host_caps = be64_to_cpu(vhost->login_buf->resp.capabilities);
184
185         return (host_caps & cap_flags) ? 1 : 0;
186 }
187
188 static struct ibmvfc_fcp_cmd_iu *ibmvfc_get_fcp_iu(struct ibmvfc_host *vhost,
189                                                    struct ibmvfc_cmd *vfc_cmd)
190 {
191         if (ibmvfc_check_caps(vhost, IBMVFC_HANDLE_VF_WWPN))
192                 return &vfc_cmd->v2.iu;
193         else
194                 return &vfc_cmd->v1.iu;
195 }
196
197 static struct ibmvfc_fcp_rsp *ibmvfc_get_fcp_rsp(struct ibmvfc_host *vhost,
198                                                  struct ibmvfc_cmd *vfc_cmd)
199 {
200         if (ibmvfc_check_caps(vhost, IBMVFC_HANDLE_VF_WWPN))
201                 return &vfc_cmd->v2.rsp;
202         else
203                 return &vfc_cmd->v1.rsp;
204 }
205
206 #ifdef CONFIG_SCSI_IBMVFC_TRACE
207 /**
208  * ibmvfc_trc_start - Log a start trace entry
209  * @evt:                ibmvfc event struct
210  *
211  **/
212 static void ibmvfc_trc_start(struct ibmvfc_event *evt)
213 {
214         struct ibmvfc_host *vhost = evt->vhost;
215         struct ibmvfc_cmd *vfc_cmd = &evt->iu.cmd;
216         struct ibmvfc_mad_common *mad = &evt->iu.mad_common;
217         struct ibmvfc_fcp_cmd_iu *iu = ibmvfc_get_fcp_iu(vhost, vfc_cmd);
218         struct ibmvfc_trace_entry *entry;
219         int index = atomic_inc_return(&vhost->trace_index) & IBMVFC_TRACE_INDEX_MASK;
220
221         entry = &vhost->trace[index];
222         entry->evt = evt;
223         entry->time = jiffies;
224         entry->fmt = evt->crq.format;
225         entry->type = IBMVFC_TRC_START;
226
227         switch (entry->fmt) {
228         case IBMVFC_CMD_FORMAT:
229                 entry->op_code = iu->cdb[0];
230                 entry->scsi_id = be64_to_cpu(vfc_cmd->tgt_scsi_id);
231                 entry->lun = scsilun_to_int(&iu->lun);
232                 entry->tmf_flags = iu->tmf_flags;
233                 entry->u.start.xfer_len = be32_to_cpu(iu->xfer_len);
234                 break;
235         case IBMVFC_MAD_FORMAT:
236                 entry->op_code = be32_to_cpu(mad->opcode);
237                 break;
238         default:
239                 break;
240         }
241 }
242
243 /**
244  * ibmvfc_trc_end - Log an end trace entry
245  * @evt:                ibmvfc event struct
246  *
247  **/
248 static void ibmvfc_trc_end(struct ibmvfc_event *evt)
249 {
250         struct ibmvfc_host *vhost = evt->vhost;
251         struct ibmvfc_cmd *vfc_cmd = &evt->xfer_iu->cmd;
252         struct ibmvfc_mad_common *mad = &evt->xfer_iu->mad_common;
253         struct ibmvfc_fcp_cmd_iu *iu = ibmvfc_get_fcp_iu(vhost, vfc_cmd);
254         struct ibmvfc_fcp_rsp *rsp = ibmvfc_get_fcp_rsp(vhost, vfc_cmd);
255         struct ibmvfc_trace_entry *entry;
256         int index = atomic_inc_return(&vhost->trace_index) & IBMVFC_TRACE_INDEX_MASK;
257
258         entry = &vhost->trace[index];
259         entry->evt = evt;
260         entry->time = jiffies;
261         entry->fmt = evt->crq.format;
262         entry->type = IBMVFC_TRC_END;
263
264         switch (entry->fmt) {
265         case IBMVFC_CMD_FORMAT:
266                 entry->op_code = iu->cdb[0];
267                 entry->scsi_id = be64_to_cpu(vfc_cmd->tgt_scsi_id);
268                 entry->lun = scsilun_to_int(&iu->lun);
269                 entry->tmf_flags = iu->tmf_flags;
270                 entry->u.end.status = be16_to_cpu(vfc_cmd->status);
271                 entry->u.end.error = be16_to_cpu(vfc_cmd->error);
272                 entry->u.end.fcp_rsp_flags = rsp->flags;
273                 entry->u.end.rsp_code = rsp->data.info.rsp_code;
274                 entry->u.end.scsi_status = rsp->scsi_status;
275                 break;
276         case IBMVFC_MAD_FORMAT:
277                 entry->op_code = be32_to_cpu(mad->opcode);
278                 entry->u.end.status = be16_to_cpu(mad->status);
279                 break;
280         default:
281                 break;
282
283         }
284 }
285
286 #else
287 #define ibmvfc_trc_start(evt) do { } while (0)
288 #define ibmvfc_trc_end(evt) do { } while (0)
289 #endif
290
291 /**
292  * ibmvfc_get_err_index - Find the index into cmd_status for the fcp response
293  * @status:             status / error class
294  * @error:              error
295  *
296  * Return value:
297  *      index into cmd_status / -EINVAL on failure
298  **/
299 static int ibmvfc_get_err_index(u16 status, u16 error)
300 {
301         int i;
302
303         for (i = 0; i < ARRAY_SIZE(cmd_status); i++)
304                 if ((cmd_status[i].status & status) == cmd_status[i].status &&
305                     cmd_status[i].error == error)
306                         return i;
307
308         return -EINVAL;
309 }
310
311 /**
312  * ibmvfc_get_cmd_error - Find the error description for the fcp response
313  * @status:             status / error class
314  * @error:              error
315  *
316  * Return value:
317  *      error description string
318  **/
319 static const char *ibmvfc_get_cmd_error(u16 status, u16 error)
320 {
321         int rc = ibmvfc_get_err_index(status, error);
322         if (rc >= 0)
323                 return cmd_status[rc].name;
324         return unknown_error;
325 }
326
327 /**
328  * ibmvfc_get_err_result - Find the scsi status to return for the fcp response
329  * @vfc_cmd:    ibmvfc command struct
330  *
331  * Return value:
332  *      SCSI result value to return for completed command
333  **/
334 static int ibmvfc_get_err_result(struct ibmvfc_host *vhost, struct ibmvfc_cmd *vfc_cmd)
335 {
336         int err;
337         struct ibmvfc_fcp_rsp *rsp = ibmvfc_get_fcp_rsp(vhost, vfc_cmd);
338         int fc_rsp_len = be32_to_cpu(rsp->fcp_rsp_len);
339
340         if ((rsp->flags & FCP_RSP_LEN_VALID) &&
341             ((fc_rsp_len && fc_rsp_len != 4 && fc_rsp_len != 8) ||
342              rsp->data.info.rsp_code))
343                 return DID_ERROR << 16;
344
345         err = ibmvfc_get_err_index(be16_to_cpu(vfc_cmd->status), be16_to_cpu(vfc_cmd->error));
346         if (err >= 0)
347                 return rsp->scsi_status | (cmd_status[err].result << 16);
348         return rsp->scsi_status | (DID_ERROR << 16);
349 }
350
351 /**
352  * ibmvfc_retry_cmd - Determine if error status is retryable
353  * @status:             status / error class
354  * @error:              error
355  *
356  * Return value:
357  *      1 if error should be retried / 0 if it should not
358  **/
359 static int ibmvfc_retry_cmd(u16 status, u16 error)
360 {
361         int rc = ibmvfc_get_err_index(status, error);
362
363         if (rc >= 0)
364                 return cmd_status[rc].retry;
365         return 1;
366 }
367
368 static const char *unknown_fc_explain = "unknown fc explain";
369
370 static const struct {
371         u16 fc_explain;
372         char *name;
373 } ls_explain [] = {
374         { 0x00, "no additional explanation" },
375         { 0x01, "service parameter error - options" },
376         { 0x03, "service parameter error - initiator control" },
377         { 0x05, "service parameter error - recipient control" },
378         { 0x07, "service parameter error - received data field size" },
379         { 0x09, "service parameter error - concurrent seq" },
380         { 0x0B, "service parameter error - credit" },
381         { 0x0D, "invalid N_Port/F_Port_Name" },
382         { 0x0E, "invalid node/Fabric Name" },
383         { 0x0F, "invalid common service parameters" },
384         { 0x11, "invalid association header" },
385         { 0x13, "association header required" },
386         { 0x15, "invalid originator S_ID" },
387         { 0x17, "invalid OX_ID-RX-ID combination" },
388         { 0x19, "command (request) already in progress" },
389         { 0x1E, "N_Port Login requested" },
390         { 0x1F, "Invalid N_Port_ID" },
391 };
392
393 static const struct {
394         u16 fc_explain;
395         char *name;
396 } gs_explain [] = {
397         { 0x00, "no additional explanation" },
398         { 0x01, "port identifier not registered" },
399         { 0x02, "port name not registered" },
400         { 0x03, "node name not registered" },
401         { 0x04, "class of service not registered" },
402         { 0x06, "initial process associator not registered" },
403         { 0x07, "FC-4 TYPEs not registered" },
404         { 0x08, "symbolic port name not registered" },
405         { 0x09, "symbolic node name not registered" },
406         { 0x0A, "port type not registered" },
407         { 0xF0, "authorization exception" },
408         { 0xF1, "authentication exception" },
409         { 0xF2, "data base full" },
410         { 0xF3, "data base empty" },
411         { 0xF4, "processing request" },
412         { 0xF5, "unable to verify connection" },
413         { 0xF6, "devices not in a common zone" },
414 };
415
416 /**
417  * ibmvfc_get_ls_explain - Return the FC Explain description text
418  * @status:     FC Explain status
419  *
420  * Returns:
421  *      error string
422  **/
423 static const char *ibmvfc_get_ls_explain(u16 status)
424 {
425         int i;
426
427         for (i = 0; i < ARRAY_SIZE(ls_explain); i++)
428                 if (ls_explain[i].fc_explain == status)
429                         return ls_explain[i].name;
430
431         return unknown_fc_explain;
432 }
433
434 /**
435  * ibmvfc_get_gs_explain - Return the FC Explain description text
436  * @status:     FC Explain status
437  *
438  * Returns:
439  *      error string
440  **/
441 static const char *ibmvfc_get_gs_explain(u16 status)
442 {
443         int i;
444
445         for (i = 0; i < ARRAY_SIZE(gs_explain); i++)
446                 if (gs_explain[i].fc_explain == status)
447                         return gs_explain[i].name;
448
449         return unknown_fc_explain;
450 }
451
452 static const struct {
453         enum ibmvfc_fc_type fc_type;
454         char *name;
455 } fc_type [] = {
456         { IBMVFC_FABRIC_REJECT, "fabric reject" },
457         { IBMVFC_PORT_REJECT, "port reject" },
458         { IBMVFC_LS_REJECT, "ELS reject" },
459         { IBMVFC_FABRIC_BUSY, "fabric busy" },
460         { IBMVFC_PORT_BUSY, "port busy" },
461         { IBMVFC_BASIC_REJECT, "basic reject" },
462 };
463
464 static const char *unknown_fc_type = "unknown fc type";
465
466 /**
467  * ibmvfc_get_fc_type - Return the FC Type description text
468  * @status:     FC Type error status
469  *
470  * Returns:
471  *      error string
472  **/
473 static const char *ibmvfc_get_fc_type(u16 status)
474 {
475         int i;
476
477         for (i = 0; i < ARRAY_SIZE(fc_type); i++)
478                 if (fc_type[i].fc_type == status)
479                         return fc_type[i].name;
480
481         return unknown_fc_type;
482 }
483
484 /**
485  * ibmvfc_set_tgt_action - Set the next init action for the target
486  * @tgt:                ibmvfc target struct
487  * @action:             action to perform
488  *
489  * Returns:
490  *      0 if action changed / non-zero if not changed
491  **/
492 static int ibmvfc_set_tgt_action(struct ibmvfc_target *tgt,
493                                   enum ibmvfc_target_action action)
494 {
495         int rc = -EINVAL;
496
497         switch (tgt->action) {
498         case IBMVFC_TGT_ACTION_LOGOUT_RPORT:
499                 if (action == IBMVFC_TGT_ACTION_LOGOUT_RPORT_WAIT ||
500                     action == IBMVFC_TGT_ACTION_DEL_RPORT) {
501                         tgt->action = action;
502                         rc = 0;
503                 }
504                 break;
505         case IBMVFC_TGT_ACTION_LOGOUT_RPORT_WAIT:
506                 if (action == IBMVFC_TGT_ACTION_DEL_RPORT ||
507                     action == IBMVFC_TGT_ACTION_DEL_AND_LOGOUT_RPORT) {
508                         tgt->action = action;
509                         rc = 0;
510                 }
511                 break;
512         case IBMVFC_TGT_ACTION_LOGOUT_DELETED_RPORT:
513                 if (action == IBMVFC_TGT_ACTION_LOGOUT_RPORT) {
514                         tgt->action = action;
515                         rc = 0;
516                 }
517                 break;
518         case IBMVFC_TGT_ACTION_DEL_AND_LOGOUT_RPORT:
519                 if (action == IBMVFC_TGT_ACTION_LOGOUT_DELETED_RPORT) {
520                         tgt->action = action;
521                         rc = 0;
522                 }
523                 break;
524         case IBMVFC_TGT_ACTION_DEL_RPORT:
525                 if (action == IBMVFC_TGT_ACTION_DELETED_RPORT) {
526                         tgt->action = action;
527                         rc = 0;
528                 }
529                 break;
530         case IBMVFC_TGT_ACTION_DELETED_RPORT:
531                 break;
532         default:
533                 tgt->action = action;
534                 rc = 0;
535                 break;
536         }
537
538         if (action >= IBMVFC_TGT_ACTION_LOGOUT_RPORT)
539                 tgt->add_rport = 0;
540
541         return rc;
542 }
543
544 /**
545  * ibmvfc_set_host_state - Set the state for the host
546  * @vhost:              ibmvfc host struct
547  * @state:              state to set host to
548  *
549  * Returns:
550  *      0 if state changed / non-zero if not changed
551  **/
552 static int ibmvfc_set_host_state(struct ibmvfc_host *vhost,
553                                   enum ibmvfc_host_state state)
554 {
555         int rc = 0;
556
557         switch (vhost->state) {
558         case IBMVFC_HOST_OFFLINE:
559                 rc = -EINVAL;
560                 break;
561         default:
562                 vhost->state = state;
563                 break;
564         }
565
566         return rc;
567 }
568
569 /**
570  * ibmvfc_set_host_action - Set the next init action for the host
571  * @vhost:              ibmvfc host struct
572  * @action:             action to perform
573  *
574  **/
575 static void ibmvfc_set_host_action(struct ibmvfc_host *vhost,
576                                    enum ibmvfc_host_action action)
577 {
578         switch (action) {
579         case IBMVFC_HOST_ACTION_ALLOC_TGTS:
580                 if (vhost->action == IBMVFC_HOST_ACTION_INIT_WAIT)
581                         vhost->action = action;
582                 break;
583         case IBMVFC_HOST_ACTION_LOGO_WAIT:
584                 if (vhost->action == IBMVFC_HOST_ACTION_LOGO)
585                         vhost->action = action;
586                 break;
587         case IBMVFC_HOST_ACTION_INIT_WAIT:
588                 if (vhost->action == IBMVFC_HOST_ACTION_INIT)
589                         vhost->action = action;
590                 break;
591         case IBMVFC_HOST_ACTION_QUERY:
592                 switch (vhost->action) {
593                 case IBMVFC_HOST_ACTION_INIT_WAIT:
594                 case IBMVFC_HOST_ACTION_NONE:
595                 case IBMVFC_HOST_ACTION_TGT_DEL_FAILED:
596                         vhost->action = action;
597                         break;
598                 default:
599                         break;
600                 }
601                 break;
602         case IBMVFC_HOST_ACTION_TGT_INIT:
603                 if (vhost->action == IBMVFC_HOST_ACTION_ALLOC_TGTS)
604                         vhost->action = action;
605                 break;
606         case IBMVFC_HOST_ACTION_INIT:
607         case IBMVFC_HOST_ACTION_TGT_DEL:
608                 switch (vhost->action) {
609                 case IBMVFC_HOST_ACTION_RESET:
610                 case IBMVFC_HOST_ACTION_REENABLE:
611                         break;
612                 default:
613                         vhost->action = action;
614                         break;
615                 }
616                 break;
617         case IBMVFC_HOST_ACTION_LOGO:
618         case IBMVFC_HOST_ACTION_QUERY_TGTS:
619         case IBMVFC_HOST_ACTION_TGT_DEL_FAILED:
620         case IBMVFC_HOST_ACTION_NONE:
621         case IBMVFC_HOST_ACTION_RESET:
622         case IBMVFC_HOST_ACTION_REENABLE:
623         default:
624                 vhost->action = action;
625                 break;
626         }
627 }
628
629 /**
630  * ibmvfc_reinit_host - Re-start host initialization (no NPIV Login)
631  * @vhost:              ibmvfc host struct
632  *
633  * Return value:
634  *      nothing
635  **/
636 static void ibmvfc_reinit_host(struct ibmvfc_host *vhost)
637 {
638         if (vhost->action == IBMVFC_HOST_ACTION_NONE &&
639             vhost->state == IBMVFC_ACTIVE) {
640                 if (!ibmvfc_set_host_state(vhost, IBMVFC_INITIALIZING)) {
641                         scsi_block_requests(vhost->host);
642                         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_QUERY);
643                 }
644         } else
645                 vhost->reinit = 1;
646
647         wake_up(&vhost->work_wait_q);
648 }
649
650 /**
651  * ibmvfc_del_tgt - Schedule cleanup and removal of the target
652  * @tgt:                ibmvfc target struct
653  * @job_step:   job step to perform
654  *
655  **/
656 static void ibmvfc_del_tgt(struct ibmvfc_target *tgt)
657 {
658         if (!ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_LOGOUT_RPORT))
659                 tgt->job_step = ibmvfc_tgt_implicit_logout_and_del;
660         wake_up(&tgt->vhost->work_wait_q);
661 }
662
663 /**
664  * ibmvfc_link_down - Handle a link down event from the adapter
665  * @vhost:      ibmvfc host struct
666  * @state:      ibmvfc host state to enter
667  *
668  **/
669 static void ibmvfc_link_down(struct ibmvfc_host *vhost,
670                              enum ibmvfc_host_state state)
671 {
672         struct ibmvfc_target *tgt;
673
674         ENTER;
675         scsi_block_requests(vhost->host);
676         list_for_each_entry(tgt, &vhost->targets, queue)
677                 ibmvfc_del_tgt(tgt);
678         ibmvfc_set_host_state(vhost, state);
679         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_TGT_DEL);
680         vhost->events_to_log |= IBMVFC_AE_LINKDOWN;
681         wake_up(&vhost->work_wait_q);
682         LEAVE;
683 }
684
685 /**
686  * ibmvfc_init_host - Start host initialization
687  * @vhost:              ibmvfc host struct
688  *
689  * Return value:
690  *      nothing
691  **/
692 static void ibmvfc_init_host(struct ibmvfc_host *vhost)
693 {
694         struct ibmvfc_target *tgt;
695
696         if (vhost->action == IBMVFC_HOST_ACTION_INIT_WAIT) {
697                 if (++vhost->init_retries > IBMVFC_MAX_HOST_INIT_RETRIES) {
698                         dev_err(vhost->dev,
699                                 "Host initialization retries exceeded. Taking adapter offline\n");
700                         ibmvfc_link_down(vhost, IBMVFC_HOST_OFFLINE);
701                         return;
702                 }
703         }
704
705         if (!ibmvfc_set_host_state(vhost, IBMVFC_INITIALIZING)) {
706                 memset(vhost->async_crq.msgs.async, 0, PAGE_SIZE);
707                 vhost->async_crq.cur = 0;
708
709                 list_for_each_entry(tgt, &vhost->targets, queue)
710                         ibmvfc_del_tgt(tgt);
711                 scsi_block_requests(vhost->host);
712                 ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_INIT);
713                 vhost->job_step = ibmvfc_npiv_login;
714                 wake_up(&vhost->work_wait_q);
715         }
716 }
717
718 /**
719  * ibmvfc_send_crq - Send a CRQ
720  * @vhost:      ibmvfc host struct
721  * @word1:      the first 64 bits of the data
722  * @word2:      the second 64 bits of the data
723  *
724  * Return value:
725  *      0 on success / other on failure
726  **/
727 static int ibmvfc_send_crq(struct ibmvfc_host *vhost, u64 word1, u64 word2)
728 {
729         struct vio_dev *vdev = to_vio_dev(vhost->dev);
730         return plpar_hcall_norets(H_SEND_CRQ, vdev->unit_address, word1, word2);
731 }
732
733 static int ibmvfc_send_sub_crq(struct ibmvfc_host *vhost, u64 cookie, u64 word1,
734                                u64 word2, u64 word3, u64 word4)
735 {
736         struct vio_dev *vdev = to_vio_dev(vhost->dev);
737
738         return plpar_hcall_norets(H_SEND_SUB_CRQ, vdev->unit_address, cookie,
739                                   word1, word2, word3, word4);
740 }
741
742 /**
743  * ibmvfc_send_crq_init - Send a CRQ init message
744  * @vhost:      ibmvfc host struct
745  *
746  * Return value:
747  *      0 on success / other on failure
748  **/
749 static int ibmvfc_send_crq_init(struct ibmvfc_host *vhost)
750 {
751         ibmvfc_dbg(vhost, "Sending CRQ init\n");
752         return ibmvfc_send_crq(vhost, 0xC001000000000000LL, 0);
753 }
754
755 /**
756  * ibmvfc_send_crq_init_complete - Send a CRQ init complete message
757  * @vhost:      ibmvfc host struct
758  *
759  * Return value:
760  *      0 on success / other on failure
761  **/
762 static int ibmvfc_send_crq_init_complete(struct ibmvfc_host *vhost)
763 {
764         ibmvfc_dbg(vhost, "Sending CRQ init complete\n");
765         return ibmvfc_send_crq(vhost, 0xC002000000000000LL, 0);
766 }
767
768 /**
769  * ibmvfc_init_event_pool - Allocates and initializes the event pool for a host
770  * @vhost:      ibmvfc host who owns the event pool
771  *
772  * Returns zero on success.
773  **/
774 static int ibmvfc_init_event_pool(struct ibmvfc_host *vhost,
775                                   struct ibmvfc_queue *queue,
776                                   unsigned int size)
777 {
778         int i;
779         struct ibmvfc_event_pool *pool = &queue->evt_pool;
780
781         ENTER;
782         if (!size)
783                 return 0;
784
785         pool->size = size;
786         pool->events = kcalloc(size, sizeof(*pool->events), GFP_KERNEL);
787         if (!pool->events)
788                 return -ENOMEM;
789
790         pool->iu_storage = dma_alloc_coherent(vhost->dev,
791                                               size * sizeof(*pool->iu_storage),
792                                               &pool->iu_token, 0);
793
794         if (!pool->iu_storage) {
795                 kfree(pool->events);
796                 return -ENOMEM;
797         }
798
799         INIT_LIST_HEAD(&queue->sent);
800         INIT_LIST_HEAD(&queue->free);
801         spin_lock_init(&queue->l_lock);
802
803         for (i = 0; i < size; ++i) {
804                 struct ibmvfc_event *evt = &pool->events[i];
805
806                 atomic_set(&evt->free, 1);
807                 evt->crq.valid = 0x80;
808                 evt->crq.ioba = cpu_to_be64(pool->iu_token + (sizeof(*evt->xfer_iu) * i));
809                 evt->xfer_iu = pool->iu_storage + i;
810                 evt->vhost = vhost;
811                 evt->queue = queue;
812                 evt->ext_list = NULL;
813                 list_add_tail(&evt->queue_list, &queue->free);
814         }
815
816         LEAVE;
817         return 0;
818 }
819
820 /**
821  * ibmvfc_free_event_pool - Frees memory of the event pool of a host
822  * @vhost:      ibmvfc host who owns the event pool
823  *
824  **/
825 static void ibmvfc_free_event_pool(struct ibmvfc_host *vhost,
826                                    struct ibmvfc_queue *queue)
827 {
828         int i;
829         struct ibmvfc_event_pool *pool = &queue->evt_pool;
830
831         ENTER;
832         for (i = 0; i < pool->size; ++i) {
833                 list_del(&pool->events[i].queue_list);
834                 BUG_ON(atomic_read(&pool->events[i].free) != 1);
835                 if (pool->events[i].ext_list)
836                         dma_pool_free(vhost->sg_pool,
837                                       pool->events[i].ext_list,
838                                       pool->events[i].ext_list_token);
839         }
840
841         kfree(pool->events);
842         dma_free_coherent(vhost->dev,
843                           pool->size * sizeof(*pool->iu_storage),
844                           pool->iu_storage, pool->iu_token);
845         LEAVE;
846 }
847
848 /**
849  * ibmvfc_free_queue - Deallocate queue
850  * @vhost:      ibmvfc host struct
851  * @queue:      ibmvfc queue struct
852  *
853  * Unmaps dma and deallocates page for messages
854  **/
855 static void ibmvfc_free_queue(struct ibmvfc_host *vhost,
856                               struct ibmvfc_queue *queue)
857 {
858         struct device *dev = vhost->dev;
859
860         dma_unmap_single(dev, queue->msg_token, PAGE_SIZE, DMA_BIDIRECTIONAL);
861         free_page((unsigned long)queue->msgs.handle);
862         queue->msgs.handle = NULL;
863
864         ibmvfc_free_event_pool(vhost, queue);
865 }
866
867 /**
868  * ibmvfc_release_crq_queue - Deallocates data and unregisters CRQ
869  * @vhost:      ibmvfc host struct
870  *
871  * Frees irq, deallocates a page for messages, unmaps dma, and unregisters
872  * the crq with the hypervisor.
873  **/
874 static void ibmvfc_release_crq_queue(struct ibmvfc_host *vhost)
875 {
876         long rc = 0;
877         struct vio_dev *vdev = to_vio_dev(vhost->dev);
878         struct ibmvfc_queue *crq = &vhost->crq;
879
880         ibmvfc_dbg(vhost, "Releasing CRQ\n");
881         free_irq(vdev->irq, vhost);
882         tasklet_kill(&vhost->tasklet);
883         do {
884                 if (rc)
885                         msleep(100);
886                 rc = plpar_hcall_norets(H_FREE_CRQ, vdev->unit_address);
887         } while (rc == H_BUSY || H_IS_LONG_BUSY(rc));
888
889         vhost->state = IBMVFC_NO_CRQ;
890         vhost->logged_in = 0;
891
892         ibmvfc_free_queue(vhost, crq);
893 }
894
895 /**
896  * ibmvfc_reenable_crq_queue - reenables the CRQ
897  * @vhost:      ibmvfc host struct
898  *
899  * Return value:
900  *      0 on success / other on failure
901  **/
902 static int ibmvfc_reenable_crq_queue(struct ibmvfc_host *vhost)
903 {
904         int rc = 0;
905         struct vio_dev *vdev = to_vio_dev(vhost->dev);
906         unsigned long flags;
907
908         ibmvfc_release_sub_crqs(vhost);
909
910         /* Re-enable the CRQ */
911         do {
912                 if (rc)
913                         msleep(100);
914                 rc = plpar_hcall_norets(H_ENABLE_CRQ, vdev->unit_address);
915         } while (rc == H_IN_PROGRESS || rc == H_BUSY || H_IS_LONG_BUSY(rc));
916
917         if (rc)
918                 dev_err(vhost->dev, "Error enabling adapter (rc=%d)\n", rc);
919
920         spin_lock_irqsave(vhost->host->host_lock, flags);
921         spin_lock(vhost->crq.q_lock);
922         vhost->do_enquiry = 1;
923         vhost->using_channels = 0;
924         spin_unlock(vhost->crq.q_lock);
925         spin_unlock_irqrestore(vhost->host->host_lock, flags);
926
927         ibmvfc_init_sub_crqs(vhost);
928
929         return rc;
930 }
931
932 /**
933  * ibmvfc_reset_crq - resets a crq after a failure
934  * @vhost:      ibmvfc host struct
935  *
936  * Return value:
937  *      0 on success / other on failure
938  **/
939 static int ibmvfc_reset_crq(struct ibmvfc_host *vhost)
940 {
941         int rc = 0;
942         unsigned long flags;
943         struct vio_dev *vdev = to_vio_dev(vhost->dev);
944         struct ibmvfc_queue *crq = &vhost->crq;
945
946         ibmvfc_release_sub_crqs(vhost);
947
948         /* Close the CRQ */
949         do {
950                 if (rc)
951                         msleep(100);
952                 rc = plpar_hcall_norets(H_FREE_CRQ, vdev->unit_address);
953         } while (rc == H_BUSY || H_IS_LONG_BUSY(rc));
954
955         spin_lock_irqsave(vhost->host->host_lock, flags);
956         spin_lock(vhost->crq.q_lock);
957         vhost->state = IBMVFC_NO_CRQ;
958         vhost->logged_in = 0;
959         vhost->do_enquiry = 1;
960         vhost->using_channels = 0;
961
962         /* Clean out the queue */
963         memset(crq->msgs.crq, 0, PAGE_SIZE);
964         crq->cur = 0;
965
966         /* And re-open it again */
967         rc = plpar_hcall_norets(H_REG_CRQ, vdev->unit_address,
968                                 crq->msg_token, PAGE_SIZE);
969
970         if (rc == H_CLOSED)
971                 /* Adapter is good, but other end is not ready */
972                 dev_warn(vhost->dev, "Partner adapter not ready\n");
973         else if (rc != 0)
974                 dev_warn(vhost->dev, "Couldn't register crq (rc=%d)\n", rc);
975
976         spin_unlock(vhost->crq.q_lock);
977         spin_unlock_irqrestore(vhost->host->host_lock, flags);
978
979         ibmvfc_init_sub_crqs(vhost);
980
981         return rc;
982 }
983
984 /**
985  * ibmvfc_valid_event - Determines if event is valid.
986  * @pool:       event_pool that contains the event
987  * @evt:        ibmvfc event to be checked for validity
988  *
989  * Return value:
990  *      1 if event is valid / 0 if event is not valid
991  **/
992 static int ibmvfc_valid_event(struct ibmvfc_event_pool *pool,
993                               struct ibmvfc_event *evt)
994 {
995         int index = evt - pool->events;
996         if (index < 0 || index >= pool->size)   /* outside of bounds */
997                 return 0;
998         if (evt != pool->events + index)        /* unaligned */
999                 return 0;
1000         return 1;
1001 }
1002
1003 /**
1004  * ibmvfc_free_event - Free the specified event
1005  * @evt:        ibmvfc_event to be freed
1006  *
1007  **/
1008 static void ibmvfc_free_event(struct ibmvfc_event *evt)
1009 {
1010         struct ibmvfc_event_pool *pool = &evt->queue->evt_pool;
1011         unsigned long flags;
1012
1013         BUG_ON(!ibmvfc_valid_event(pool, evt));
1014         BUG_ON(atomic_inc_return(&evt->free) != 1);
1015
1016         spin_lock_irqsave(&evt->queue->l_lock, flags);
1017         list_add_tail(&evt->queue_list, &evt->queue->free);
1018         if (evt->eh_comp)
1019                 complete(evt->eh_comp);
1020         spin_unlock_irqrestore(&evt->queue->l_lock, flags);
1021 }
1022
1023 /**
1024  * ibmvfc_scsi_eh_done - EH done function for queuecommand commands
1025  * @evt:        ibmvfc event struct
1026  *
1027  * This function does not setup any error status, that must be done
1028  * before this function gets called.
1029  **/
1030 static void ibmvfc_scsi_eh_done(struct ibmvfc_event *evt)
1031 {
1032         struct scsi_cmnd *cmnd = evt->cmnd;
1033
1034         if (cmnd) {
1035                 scsi_dma_unmap(cmnd);
1036                 cmnd->scsi_done(cmnd);
1037         }
1038
1039         ibmvfc_free_event(evt);
1040 }
1041
1042 /**
1043  * ibmvfc_complete_purge - Complete failed command list
1044  * @purge_list:         list head of failed commands
1045  *
1046  * This function runs completions on commands to fail as a result of a
1047  * host reset or platform migration.
1048  **/
1049 static void ibmvfc_complete_purge(struct list_head *purge_list)
1050 {
1051         struct ibmvfc_event *evt, *pos;
1052
1053         list_for_each_entry_safe(evt, pos, purge_list, queue_list) {
1054                 list_del(&evt->queue_list);
1055                 ibmvfc_trc_end(evt);
1056                 evt->done(evt);
1057         }
1058 }
1059
1060 /**
1061  * ibmvfc_fail_request - Fail request with specified error code
1062  * @evt:                ibmvfc event struct
1063  * @error_code: error code to fail request with
1064  *
1065  * Return value:
1066  *      none
1067  **/
1068 static void ibmvfc_fail_request(struct ibmvfc_event *evt, int error_code)
1069 {
1070         if (evt->cmnd) {
1071                 evt->cmnd->result = (error_code << 16);
1072                 evt->done = ibmvfc_scsi_eh_done;
1073         } else
1074                 evt->xfer_iu->mad_common.status = cpu_to_be16(IBMVFC_MAD_DRIVER_FAILED);
1075
1076         del_timer(&evt->timer);
1077 }
1078
1079 /**
1080  * ibmvfc_purge_requests - Our virtual adapter just shut down. Purge any sent requests
1081  * @vhost:              ibmvfc host struct
1082  * @error_code: error code to fail requests with
1083  *
1084  * Return value:
1085  *      none
1086  **/
1087 static void ibmvfc_purge_requests(struct ibmvfc_host *vhost, int error_code)
1088 {
1089         struct ibmvfc_event *evt, *pos;
1090         struct ibmvfc_queue *queues = vhost->scsi_scrqs.scrqs;
1091         unsigned long flags;
1092         int hwqs = 0;
1093         int i;
1094
1095         if (vhost->using_channels)
1096                 hwqs = vhost->scsi_scrqs.active_queues;
1097
1098         ibmvfc_dbg(vhost, "Purging all requests\n");
1099         spin_lock_irqsave(&vhost->crq.l_lock, flags);
1100         list_for_each_entry_safe(evt, pos, &vhost->crq.sent, queue_list)
1101                 ibmvfc_fail_request(evt, error_code);
1102         list_splice_init(&vhost->crq.sent, &vhost->purge);
1103         spin_unlock_irqrestore(&vhost->crq.l_lock, flags);
1104
1105         for (i = 0; i < hwqs; i++) {
1106                 spin_lock_irqsave(queues[i].q_lock, flags);
1107                 spin_lock(&queues[i].l_lock);
1108                 list_for_each_entry_safe(evt, pos, &queues[i].sent, queue_list)
1109                         ibmvfc_fail_request(evt, error_code);
1110                 list_splice_init(&queues[i].sent, &vhost->purge);
1111                 spin_unlock(&queues[i].l_lock);
1112                 spin_unlock_irqrestore(queues[i].q_lock, flags);
1113         }
1114 }
1115
1116 /**
1117  * ibmvfc_hard_reset_host - Reset the connection to the server by breaking the CRQ
1118  * @vhost:      struct ibmvfc host to reset
1119  **/
1120 static void ibmvfc_hard_reset_host(struct ibmvfc_host *vhost)
1121 {
1122         ibmvfc_purge_requests(vhost, DID_ERROR);
1123         ibmvfc_link_down(vhost, IBMVFC_LINK_DOWN);
1124         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_RESET);
1125 }
1126
1127 /**
1128  * __ibmvfc_reset_host - Reset the connection to the server (no locking)
1129  * @vhost:      struct ibmvfc host to reset
1130  **/
1131 static void __ibmvfc_reset_host(struct ibmvfc_host *vhost)
1132 {
1133         if (vhost->logged_in && vhost->action != IBMVFC_HOST_ACTION_LOGO_WAIT &&
1134             !ibmvfc_set_host_state(vhost, IBMVFC_INITIALIZING)) {
1135                 scsi_block_requests(vhost->host);
1136                 ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_LOGO);
1137                 vhost->job_step = ibmvfc_npiv_logout;
1138                 wake_up(&vhost->work_wait_q);
1139         } else
1140                 ibmvfc_hard_reset_host(vhost);
1141 }
1142
1143 /**
1144  * ibmvfc_reset_host - Reset the connection to the server
1145  * @vhost:      ibmvfc host struct
1146  **/
1147 static void ibmvfc_reset_host(struct ibmvfc_host *vhost)
1148 {
1149         unsigned long flags;
1150
1151         spin_lock_irqsave(vhost->host->host_lock, flags);
1152         __ibmvfc_reset_host(vhost);
1153         spin_unlock_irqrestore(vhost->host->host_lock, flags);
1154 }
1155
1156 /**
1157  * ibmvfc_retry_host_init - Retry host initialization if allowed
1158  * @vhost:      ibmvfc host struct
1159  *
1160  * Returns: 1 if init will be retried / 0 if not
1161  *
1162  **/
1163 static int ibmvfc_retry_host_init(struct ibmvfc_host *vhost)
1164 {
1165         int retry = 0;
1166
1167         if (vhost->action == IBMVFC_HOST_ACTION_INIT_WAIT) {
1168                 vhost->delay_init = 1;
1169                 if (++vhost->init_retries > IBMVFC_MAX_HOST_INIT_RETRIES) {
1170                         dev_err(vhost->dev,
1171                                 "Host initialization retries exceeded. Taking adapter offline\n");
1172                         ibmvfc_link_down(vhost, IBMVFC_HOST_OFFLINE);
1173                 } else if (vhost->init_retries == IBMVFC_MAX_HOST_INIT_RETRIES)
1174                         __ibmvfc_reset_host(vhost);
1175                 else {
1176                         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_INIT);
1177                         retry = 1;
1178                 }
1179         }
1180
1181         wake_up(&vhost->work_wait_q);
1182         return retry;
1183 }
1184
1185 /**
1186  * __ibmvfc_get_target - Find the specified scsi_target (no locking)
1187  * @starget:    scsi target struct
1188  *
1189  * Return value:
1190  *      ibmvfc_target struct / NULL if not found
1191  **/
1192 static struct ibmvfc_target *__ibmvfc_get_target(struct scsi_target *starget)
1193 {
1194         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
1195         struct ibmvfc_host *vhost = shost_priv(shost);
1196         struct ibmvfc_target *tgt;
1197
1198         list_for_each_entry(tgt, &vhost->targets, queue)
1199                 if (tgt->target_id == starget->id) {
1200                         kref_get(&tgt->kref);
1201                         return tgt;
1202                 }
1203         return NULL;
1204 }
1205
1206 /**
1207  * ibmvfc_get_target - Find the specified scsi_target
1208  * @starget:    scsi target struct
1209  *
1210  * Return value:
1211  *      ibmvfc_target struct / NULL if not found
1212  **/
1213 static struct ibmvfc_target *ibmvfc_get_target(struct scsi_target *starget)
1214 {
1215         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
1216         struct ibmvfc_target *tgt;
1217         unsigned long flags;
1218
1219         spin_lock_irqsave(shost->host_lock, flags);
1220         tgt = __ibmvfc_get_target(starget);
1221         spin_unlock_irqrestore(shost->host_lock, flags);
1222         return tgt;
1223 }
1224
1225 /**
1226  * ibmvfc_get_host_speed - Get host port speed
1227  * @shost:              scsi host struct
1228  *
1229  * Return value:
1230  *      none
1231  **/
1232 static void ibmvfc_get_host_speed(struct Scsi_Host *shost)
1233 {
1234         struct ibmvfc_host *vhost = shost_priv(shost);
1235         unsigned long flags;
1236
1237         spin_lock_irqsave(shost->host_lock, flags);
1238         if (vhost->state == IBMVFC_ACTIVE) {
1239                 switch (be64_to_cpu(vhost->login_buf->resp.link_speed) / 100) {
1240                 case 1:
1241                         fc_host_speed(shost) = FC_PORTSPEED_1GBIT;
1242                         break;
1243                 case 2:
1244                         fc_host_speed(shost) = FC_PORTSPEED_2GBIT;
1245                         break;
1246                 case 4:
1247                         fc_host_speed(shost) = FC_PORTSPEED_4GBIT;
1248                         break;
1249                 case 8:
1250                         fc_host_speed(shost) = FC_PORTSPEED_8GBIT;
1251                         break;
1252                 case 10:
1253                         fc_host_speed(shost) = FC_PORTSPEED_10GBIT;
1254                         break;
1255                 case 16:
1256                         fc_host_speed(shost) = FC_PORTSPEED_16GBIT;
1257                         break;
1258                 default:
1259                         ibmvfc_log(vhost, 3, "Unknown port speed: %lld Gbit\n",
1260                                    be64_to_cpu(vhost->login_buf->resp.link_speed) / 100);
1261                         fc_host_speed(shost) = FC_PORTSPEED_UNKNOWN;
1262                         break;
1263                 }
1264         } else
1265                 fc_host_speed(shost) = FC_PORTSPEED_UNKNOWN;
1266         spin_unlock_irqrestore(shost->host_lock, flags);
1267 }
1268
1269 /**
1270  * ibmvfc_get_host_port_state - Get host port state
1271  * @shost:              scsi host struct
1272  *
1273  * Return value:
1274  *      none
1275  **/
1276 static void ibmvfc_get_host_port_state(struct Scsi_Host *shost)
1277 {
1278         struct ibmvfc_host *vhost = shost_priv(shost);
1279         unsigned long flags;
1280
1281         spin_lock_irqsave(shost->host_lock, flags);
1282         switch (vhost->state) {
1283         case IBMVFC_INITIALIZING:
1284         case IBMVFC_ACTIVE:
1285                 fc_host_port_state(shost) = FC_PORTSTATE_ONLINE;
1286                 break;
1287         case IBMVFC_LINK_DOWN:
1288                 fc_host_port_state(shost) = FC_PORTSTATE_LINKDOWN;
1289                 break;
1290         case IBMVFC_LINK_DEAD:
1291         case IBMVFC_HOST_OFFLINE:
1292                 fc_host_port_state(shost) = FC_PORTSTATE_OFFLINE;
1293                 break;
1294         case IBMVFC_HALTED:
1295                 fc_host_port_state(shost) = FC_PORTSTATE_BLOCKED;
1296                 break;
1297         case IBMVFC_NO_CRQ:
1298                 fc_host_port_state(shost) = FC_PORTSTATE_UNKNOWN;
1299                 break;
1300         default:
1301                 ibmvfc_log(vhost, 3, "Unknown port state: %d\n", vhost->state);
1302                 fc_host_port_state(shost) = FC_PORTSTATE_UNKNOWN;
1303                 break;
1304         }
1305         spin_unlock_irqrestore(shost->host_lock, flags);
1306 }
1307
1308 /**
1309  * ibmvfc_set_rport_dev_loss_tmo - Set rport's device loss timeout
1310  * @rport:              rport struct
1311  * @timeout:    timeout value
1312  *
1313  * Return value:
1314  *      none
1315  **/
1316 static void ibmvfc_set_rport_dev_loss_tmo(struct fc_rport *rport, u32 timeout)
1317 {
1318         if (timeout)
1319                 rport->dev_loss_tmo = timeout;
1320         else
1321                 rport->dev_loss_tmo = 1;
1322 }
1323
1324 /**
1325  * ibmvfc_release_tgt - Free memory allocated for a target
1326  * @kref:               kref struct
1327  *
1328  **/
1329 static void ibmvfc_release_tgt(struct kref *kref)
1330 {
1331         struct ibmvfc_target *tgt = container_of(kref, struct ibmvfc_target, kref);
1332         kfree(tgt);
1333 }
1334
1335 /**
1336  * ibmvfc_get_starget_node_name - Get SCSI target's node name
1337  * @starget:    scsi target struct
1338  *
1339  * Return value:
1340  *      none
1341  **/
1342 static void ibmvfc_get_starget_node_name(struct scsi_target *starget)
1343 {
1344         struct ibmvfc_target *tgt = ibmvfc_get_target(starget);
1345         fc_starget_port_name(starget) = tgt ? tgt->ids.node_name : 0;
1346         if (tgt)
1347                 kref_put(&tgt->kref, ibmvfc_release_tgt);
1348 }
1349
1350 /**
1351  * ibmvfc_get_starget_port_name - Get SCSI target's port name
1352  * @starget:    scsi target struct
1353  *
1354  * Return value:
1355  *      none
1356  **/
1357 static void ibmvfc_get_starget_port_name(struct scsi_target *starget)
1358 {
1359         struct ibmvfc_target *tgt = ibmvfc_get_target(starget);
1360         fc_starget_port_name(starget) = tgt ? tgt->ids.port_name : 0;
1361         if (tgt)
1362                 kref_put(&tgt->kref, ibmvfc_release_tgt);
1363 }
1364
1365 /**
1366  * ibmvfc_get_starget_port_id - Get SCSI target's port ID
1367  * @starget:    scsi target struct
1368  *
1369  * Return value:
1370  *      none
1371  **/
1372 static void ibmvfc_get_starget_port_id(struct scsi_target *starget)
1373 {
1374         struct ibmvfc_target *tgt = ibmvfc_get_target(starget);
1375         fc_starget_port_id(starget) = tgt ? tgt->scsi_id : -1;
1376         if (tgt)
1377                 kref_put(&tgt->kref, ibmvfc_release_tgt);
1378 }
1379
1380 /**
1381  * ibmvfc_wait_while_resetting - Wait while the host resets
1382  * @vhost:              ibmvfc host struct
1383  *
1384  * Return value:
1385  *      0 on success / other on failure
1386  **/
1387 static int ibmvfc_wait_while_resetting(struct ibmvfc_host *vhost)
1388 {
1389         long timeout = wait_event_timeout(vhost->init_wait_q,
1390                                           ((vhost->state == IBMVFC_ACTIVE ||
1391                                             vhost->state == IBMVFC_HOST_OFFLINE ||
1392                                             vhost->state == IBMVFC_LINK_DEAD) &&
1393                                            vhost->action == IBMVFC_HOST_ACTION_NONE),
1394                                           (init_timeout * HZ));
1395
1396         return timeout ? 0 : -EIO;
1397 }
1398
1399 /**
1400  * ibmvfc_issue_fc_host_lip - Re-initiate link initialization
1401  * @shost:              scsi host struct
1402  *
1403  * Return value:
1404  *      0 on success / other on failure
1405  **/
1406 static int ibmvfc_issue_fc_host_lip(struct Scsi_Host *shost)
1407 {
1408         struct ibmvfc_host *vhost = shost_priv(shost);
1409
1410         dev_err(vhost->dev, "Initiating host LIP. Resetting connection\n");
1411         ibmvfc_reset_host(vhost);
1412         return ibmvfc_wait_while_resetting(vhost);
1413 }
1414
1415 /**
1416  * ibmvfc_gather_partition_info - Gather info about the LPAR
1417  *
1418  * Return value:
1419  *      none
1420  **/
1421 static void ibmvfc_gather_partition_info(struct ibmvfc_host *vhost)
1422 {
1423         struct device_node *rootdn;
1424         const char *name;
1425         const unsigned int *num;
1426
1427         rootdn = of_find_node_by_path("/");
1428         if (!rootdn)
1429                 return;
1430
1431         name = of_get_property(rootdn, "ibm,partition-name", NULL);
1432         if (name)
1433                 strncpy(vhost->partition_name, name, sizeof(vhost->partition_name));
1434         num = of_get_property(rootdn, "ibm,partition-no", NULL);
1435         if (num)
1436                 vhost->partition_number = *num;
1437         of_node_put(rootdn);
1438 }
1439
1440 /**
1441  * ibmvfc_set_login_info - Setup info for NPIV login
1442  * @vhost:      ibmvfc host struct
1443  *
1444  * Return value:
1445  *      none
1446  **/
1447 static void ibmvfc_set_login_info(struct ibmvfc_host *vhost)
1448 {
1449         struct ibmvfc_npiv_login *login_info = &vhost->login_info;
1450         struct ibmvfc_queue *async_crq = &vhost->async_crq;
1451         struct device_node *of_node = vhost->dev->of_node;
1452         const char *location;
1453
1454         memset(login_info, 0, sizeof(*login_info));
1455
1456         login_info->ostype = cpu_to_be32(IBMVFC_OS_LINUX);
1457         login_info->max_dma_len = cpu_to_be64(IBMVFC_MAX_SECTORS << 9);
1458         login_info->max_payload = cpu_to_be32(sizeof(struct ibmvfc_fcp_cmd_iu));
1459         login_info->max_response = cpu_to_be32(sizeof(struct ibmvfc_fcp_rsp));
1460         login_info->partition_num = cpu_to_be32(vhost->partition_number);
1461         login_info->vfc_frame_version = cpu_to_be32(1);
1462         login_info->fcp_version = cpu_to_be16(3);
1463         login_info->flags = cpu_to_be16(IBMVFC_FLUSH_ON_HALT);
1464         if (vhost->client_migrated)
1465                 login_info->flags |= cpu_to_be16(IBMVFC_CLIENT_MIGRATED);
1466
1467         login_info->max_cmds = cpu_to_be32(max_requests + IBMVFC_NUM_INTERNAL_REQ);
1468         login_info->capabilities = cpu_to_be64(IBMVFC_CAN_MIGRATE | IBMVFC_CAN_SEND_VF_WWPN);
1469
1470         if (vhost->mq_enabled || vhost->using_channels)
1471                 login_info->capabilities |= cpu_to_be64(IBMVFC_CAN_USE_CHANNELS);
1472
1473         login_info->async.va = cpu_to_be64(vhost->async_crq.msg_token);
1474         login_info->async.len = cpu_to_be32(async_crq->size *
1475                                             sizeof(*async_crq->msgs.async));
1476         strncpy(login_info->partition_name, vhost->partition_name, IBMVFC_MAX_NAME);
1477         strncpy(login_info->device_name,
1478                 dev_name(&vhost->host->shost_gendev), IBMVFC_MAX_NAME);
1479
1480         location = of_get_property(of_node, "ibm,loc-code", NULL);
1481         location = location ? location : dev_name(vhost->dev);
1482         strncpy(login_info->drc_name, location, IBMVFC_MAX_NAME);
1483 }
1484
1485 /**
1486  * ibmvfc_get_event - Gets the next free event in pool
1487  * @vhost:      ibmvfc host struct
1488  *
1489  * Returns a free event from the pool.
1490  **/
1491 static struct ibmvfc_event *ibmvfc_get_event(struct ibmvfc_queue *queue)
1492 {
1493         struct ibmvfc_event *evt;
1494         unsigned long flags;
1495
1496         spin_lock_irqsave(&queue->l_lock, flags);
1497         BUG_ON(list_empty(&queue->free));
1498         evt = list_entry(queue->free.next, struct ibmvfc_event, queue_list);
1499         atomic_set(&evt->free, 0);
1500         list_del(&evt->queue_list);
1501         spin_unlock_irqrestore(&queue->l_lock, flags);
1502         return evt;
1503 }
1504
1505 /**
1506  * ibmvfc_locked_done - Calls evt completion with host_lock held
1507  * @evt:        ibmvfc evt to complete
1508  *
1509  * All non-scsi command completion callbacks have the expectation that the
1510  * host_lock is held. This callback is used by ibmvfc_init_event to wrap a
1511  * MAD evt with the host_lock.
1512  **/
1513 static void ibmvfc_locked_done(struct ibmvfc_event *evt)
1514 {
1515         unsigned long flags;
1516
1517         spin_lock_irqsave(evt->vhost->host->host_lock, flags);
1518         evt->_done(evt);
1519         spin_unlock_irqrestore(evt->vhost->host->host_lock, flags);
1520 }
1521
1522 /**
1523  * ibmvfc_init_event - Initialize fields in an event struct that are always
1524  *                              required.
1525  * @evt:        The event
1526  * @done:       Routine to call when the event is responded to
1527  * @format:     SRP or MAD format
1528  **/
1529 static void ibmvfc_init_event(struct ibmvfc_event *evt,
1530                               void (*done) (struct ibmvfc_event *), u8 format)
1531 {
1532         evt->cmnd = NULL;
1533         evt->sync_iu = NULL;
1534         evt->eh_comp = NULL;
1535         evt->crq.format = format;
1536         if (format == IBMVFC_CMD_FORMAT)
1537                 evt->done = done;
1538         else {
1539                 evt->_done = done;
1540                 evt->done = ibmvfc_locked_done;
1541         }
1542         evt->hwq = 0;
1543 }
1544
1545 /**
1546  * ibmvfc_map_sg_list - Initialize scatterlist
1547  * @scmd:       scsi command struct
1548  * @nseg:       number of scatterlist segments
1549  * @md: memory descriptor list to initialize
1550  **/
1551 static void ibmvfc_map_sg_list(struct scsi_cmnd *scmd, int nseg,
1552                                struct srp_direct_buf *md)
1553 {
1554         int i;
1555         struct scatterlist *sg;
1556
1557         scsi_for_each_sg(scmd, sg, nseg, i) {
1558                 md[i].va = cpu_to_be64(sg_dma_address(sg));
1559                 md[i].len = cpu_to_be32(sg_dma_len(sg));
1560                 md[i].key = 0;
1561         }
1562 }
1563
1564 /**
1565  * ibmvfc_map_sg_data - Maps dma for a scatterlist and initializes descriptor fields
1566  * @scmd:               struct scsi_cmnd with the scatterlist
1567  * @evt:                ibmvfc event struct
1568  * @vfc_cmd:    vfc_cmd that contains the memory descriptor
1569  * @dev:                device for which to map dma memory
1570  *
1571  * Returns:
1572  *      0 on success / non-zero on failure
1573  **/
1574 static int ibmvfc_map_sg_data(struct scsi_cmnd *scmd,
1575                               struct ibmvfc_event *evt,
1576                               struct ibmvfc_cmd *vfc_cmd, struct device *dev)
1577 {
1578
1579         int sg_mapped;
1580         struct srp_direct_buf *data = &vfc_cmd->ioba;
1581         struct ibmvfc_host *vhost = dev_get_drvdata(dev);
1582         struct ibmvfc_fcp_cmd_iu *iu = ibmvfc_get_fcp_iu(evt->vhost, vfc_cmd);
1583
1584         if (cls3_error)
1585                 vfc_cmd->flags |= cpu_to_be16(IBMVFC_CLASS_3_ERR);
1586
1587         sg_mapped = scsi_dma_map(scmd);
1588         if (!sg_mapped) {
1589                 vfc_cmd->flags |= cpu_to_be16(IBMVFC_NO_MEM_DESC);
1590                 return 0;
1591         } else if (unlikely(sg_mapped < 0)) {
1592                 if (vhost->log_level > IBMVFC_DEFAULT_LOG_LEVEL)
1593                         scmd_printk(KERN_ERR, scmd, "Failed to map DMA buffer for command\n");
1594                 return sg_mapped;
1595         }
1596
1597         if (scmd->sc_data_direction == DMA_TO_DEVICE) {
1598                 vfc_cmd->flags |= cpu_to_be16(IBMVFC_WRITE);
1599                 iu->add_cdb_len |= IBMVFC_WRDATA;
1600         } else {
1601                 vfc_cmd->flags |= cpu_to_be16(IBMVFC_READ);
1602                 iu->add_cdb_len |= IBMVFC_RDDATA;
1603         }
1604
1605         if (sg_mapped == 1) {
1606                 ibmvfc_map_sg_list(scmd, sg_mapped, data);
1607                 return 0;
1608         }
1609
1610         vfc_cmd->flags |= cpu_to_be16(IBMVFC_SCATTERLIST);
1611
1612         if (!evt->ext_list) {
1613                 evt->ext_list = dma_pool_alloc(vhost->sg_pool, GFP_ATOMIC,
1614                                                &evt->ext_list_token);
1615
1616                 if (!evt->ext_list) {
1617                         scsi_dma_unmap(scmd);
1618                         if (vhost->log_level > IBMVFC_DEFAULT_LOG_LEVEL)
1619                                 scmd_printk(KERN_ERR, scmd, "Can't allocate memory for scatterlist\n");
1620                         return -ENOMEM;
1621                 }
1622         }
1623
1624         ibmvfc_map_sg_list(scmd, sg_mapped, evt->ext_list);
1625
1626         data->va = cpu_to_be64(evt->ext_list_token);
1627         data->len = cpu_to_be32(sg_mapped * sizeof(struct srp_direct_buf));
1628         data->key = 0;
1629         return 0;
1630 }
1631
1632 /**
1633  * ibmvfc_timeout - Internal command timeout handler
1634  * @evt:        struct ibmvfc_event that timed out
1635  *
1636  * Called when an internally generated command times out
1637  **/
1638 static void ibmvfc_timeout(struct timer_list *t)
1639 {
1640         struct ibmvfc_event *evt = from_timer(evt, t, timer);
1641         struct ibmvfc_host *vhost = evt->vhost;
1642         dev_err(vhost->dev, "Command timed out (%p). Resetting connection\n", evt);
1643         ibmvfc_reset_host(vhost);
1644 }
1645
1646 /**
1647  * ibmvfc_send_event - Transforms event to u64 array and calls send_crq()
1648  * @evt:                event to be sent
1649  * @vhost:              ibmvfc host struct
1650  * @timeout:    timeout in seconds - 0 means do not time command
1651  *
1652  * Returns the value returned from ibmvfc_send_crq(). (Zero for success)
1653  **/
1654 static int ibmvfc_send_event(struct ibmvfc_event *evt,
1655                              struct ibmvfc_host *vhost, unsigned long timeout)
1656 {
1657         __be64 *crq_as_u64 = (__be64 *) &evt->crq;
1658         unsigned long flags;
1659         int rc;
1660
1661         /* Copy the IU into the transfer area */
1662         *evt->xfer_iu = evt->iu;
1663         if (evt->crq.format == IBMVFC_CMD_FORMAT)
1664                 evt->xfer_iu->cmd.tag = cpu_to_be64((u64)evt);
1665         else if (evt->crq.format == IBMVFC_MAD_FORMAT)
1666                 evt->xfer_iu->mad_common.tag = cpu_to_be64((u64)evt);
1667         else
1668                 BUG();
1669
1670         timer_setup(&evt->timer, ibmvfc_timeout, 0);
1671
1672         if (timeout) {
1673                 evt->timer.expires = jiffies + (timeout * HZ);
1674                 add_timer(&evt->timer);
1675         }
1676
1677         spin_lock_irqsave(&evt->queue->l_lock, flags);
1678         list_add_tail(&evt->queue_list, &evt->queue->sent);
1679
1680         mb();
1681
1682         if (evt->queue->fmt == IBMVFC_SUB_CRQ_FMT)
1683                 rc = ibmvfc_send_sub_crq(vhost,
1684                                          evt->queue->vios_cookie,
1685                                          be64_to_cpu(crq_as_u64[0]),
1686                                          be64_to_cpu(crq_as_u64[1]),
1687                                          0, 0);
1688         else
1689                 rc = ibmvfc_send_crq(vhost, be64_to_cpu(crq_as_u64[0]),
1690                                      be64_to_cpu(crq_as_u64[1]));
1691
1692         if (rc) {
1693                 list_del(&evt->queue_list);
1694                 spin_unlock_irqrestore(&evt->queue->l_lock, flags);
1695                 del_timer(&evt->timer);
1696
1697                 /* If send_crq returns H_CLOSED, return SCSI_MLQUEUE_HOST_BUSY.
1698                  * Firmware will send a CRQ with a transport event (0xFF) to
1699                  * tell this client what has happened to the transport. This
1700                  * will be handled in ibmvfc_handle_crq()
1701                  */
1702                 if (rc == H_CLOSED) {
1703                         if (printk_ratelimit())
1704                                 dev_warn(vhost->dev, "Send warning. Receive queue closed, will retry.\n");
1705                         if (evt->cmnd)
1706                                 scsi_dma_unmap(evt->cmnd);
1707                         ibmvfc_free_event(evt);
1708                         return SCSI_MLQUEUE_HOST_BUSY;
1709                 }
1710
1711                 dev_err(vhost->dev, "Send error (rc=%d)\n", rc);
1712                 if (evt->cmnd) {
1713                         evt->cmnd->result = DID_ERROR << 16;
1714                         evt->done = ibmvfc_scsi_eh_done;
1715                 } else
1716                         evt->xfer_iu->mad_common.status = cpu_to_be16(IBMVFC_MAD_CRQ_ERROR);
1717
1718                 evt->done(evt);
1719         } else {
1720                 spin_unlock_irqrestore(&evt->queue->l_lock, flags);
1721                 ibmvfc_trc_start(evt);
1722         }
1723
1724         return 0;
1725 }
1726
1727 /**
1728  * ibmvfc_log_error - Log an error for the failed command if appropriate
1729  * @evt:        ibmvfc event to log
1730  *
1731  **/
1732 static void ibmvfc_log_error(struct ibmvfc_event *evt)
1733 {
1734         struct ibmvfc_cmd *vfc_cmd = &evt->xfer_iu->cmd;
1735         struct ibmvfc_host *vhost = evt->vhost;
1736         struct ibmvfc_fcp_rsp *rsp = ibmvfc_get_fcp_rsp(vhost, vfc_cmd);
1737         struct scsi_cmnd *cmnd = evt->cmnd;
1738         const char *err = unknown_error;
1739         int index = ibmvfc_get_err_index(be16_to_cpu(vfc_cmd->status), be16_to_cpu(vfc_cmd->error));
1740         int logerr = 0;
1741         int rsp_code = 0;
1742
1743         if (index >= 0) {
1744                 logerr = cmd_status[index].log;
1745                 err = cmd_status[index].name;
1746         }
1747
1748         if (!logerr && (vhost->log_level <= (IBMVFC_DEFAULT_LOG_LEVEL + 1)))
1749                 return;
1750
1751         if (rsp->flags & FCP_RSP_LEN_VALID)
1752                 rsp_code = rsp->data.info.rsp_code;
1753
1754         scmd_printk(KERN_ERR, cmnd, "Command (%02X) : %s (%x:%x) "
1755                     "flags: %x fcp_rsp: %x, resid=%d, scsi_status: %x\n",
1756                     cmnd->cmnd[0], err, be16_to_cpu(vfc_cmd->status), be16_to_cpu(vfc_cmd->error),
1757                     rsp->flags, rsp_code, scsi_get_resid(cmnd), rsp->scsi_status);
1758 }
1759
1760 /**
1761  * ibmvfc_relogin - Log back into the specified device
1762  * @sdev:       scsi device struct
1763  *
1764  **/
1765 static void ibmvfc_relogin(struct scsi_device *sdev)
1766 {
1767         struct ibmvfc_host *vhost = shost_priv(sdev->host);
1768         struct fc_rport *rport = starget_to_rport(scsi_target(sdev));
1769         struct ibmvfc_target *tgt;
1770         unsigned long flags;
1771
1772         spin_lock_irqsave(vhost->host->host_lock, flags);
1773         list_for_each_entry(tgt, &vhost->targets, queue) {
1774                 if (rport == tgt->rport) {
1775                         ibmvfc_del_tgt(tgt);
1776                         break;
1777                 }
1778         }
1779
1780         ibmvfc_reinit_host(vhost);
1781         spin_unlock_irqrestore(vhost->host->host_lock, flags);
1782 }
1783
1784 /**
1785  * ibmvfc_scsi_done - Handle responses from commands
1786  * @evt:        ibmvfc event to be handled
1787  *
1788  * Used as a callback when sending scsi cmds.
1789  **/
1790 static void ibmvfc_scsi_done(struct ibmvfc_event *evt)
1791 {
1792         struct ibmvfc_cmd *vfc_cmd = &evt->xfer_iu->cmd;
1793         struct ibmvfc_fcp_rsp *rsp = ibmvfc_get_fcp_rsp(evt->vhost, vfc_cmd);
1794         struct scsi_cmnd *cmnd = evt->cmnd;
1795         u32 rsp_len = 0;
1796         u32 sense_len = be32_to_cpu(rsp->fcp_sense_len);
1797
1798         if (cmnd) {
1799                 if (be16_to_cpu(vfc_cmd->response_flags) & IBMVFC_ADAPTER_RESID_VALID)
1800                         scsi_set_resid(cmnd, be32_to_cpu(vfc_cmd->adapter_resid));
1801                 else if (rsp->flags & FCP_RESID_UNDER)
1802                         scsi_set_resid(cmnd, be32_to_cpu(rsp->fcp_resid));
1803                 else
1804                         scsi_set_resid(cmnd, 0);
1805
1806                 if (vfc_cmd->status) {
1807                         cmnd->result = ibmvfc_get_err_result(evt->vhost, vfc_cmd);
1808
1809                         if (rsp->flags & FCP_RSP_LEN_VALID)
1810                                 rsp_len = be32_to_cpu(rsp->fcp_rsp_len);
1811                         if ((sense_len + rsp_len) > SCSI_SENSE_BUFFERSIZE)
1812                                 sense_len = SCSI_SENSE_BUFFERSIZE - rsp_len;
1813                         if ((rsp->flags & FCP_SNS_LEN_VALID) && rsp->fcp_sense_len && rsp_len <= 8)
1814                                 memcpy(cmnd->sense_buffer, rsp->data.sense + rsp_len, sense_len);
1815                         if ((be16_to_cpu(vfc_cmd->status) & IBMVFC_VIOS_FAILURE) &&
1816                             (be16_to_cpu(vfc_cmd->error) == IBMVFC_PLOGI_REQUIRED))
1817                                 ibmvfc_relogin(cmnd->device);
1818
1819                         if (!cmnd->result && (!scsi_get_resid(cmnd) || (rsp->flags & FCP_RESID_OVER)))
1820                                 cmnd->result = (DID_ERROR << 16);
1821
1822                         ibmvfc_log_error(evt);
1823                 }
1824
1825                 if (!cmnd->result &&
1826                     (scsi_bufflen(cmnd) - scsi_get_resid(cmnd) < cmnd->underflow))
1827                         cmnd->result = (DID_ERROR << 16);
1828
1829                 scsi_dma_unmap(cmnd);
1830                 cmnd->scsi_done(cmnd);
1831         }
1832
1833         ibmvfc_free_event(evt);
1834 }
1835
1836 /**
1837  * ibmvfc_host_chkready - Check if the host can accept commands
1838  * @vhost:       struct ibmvfc host
1839  *
1840  * Returns:
1841  *      1 if host can accept command / 0 if not
1842  **/
1843 static inline int ibmvfc_host_chkready(struct ibmvfc_host *vhost)
1844 {
1845         int result = 0;
1846
1847         switch (vhost->state) {
1848         case IBMVFC_LINK_DEAD:
1849         case IBMVFC_HOST_OFFLINE:
1850                 result = DID_NO_CONNECT << 16;
1851                 break;
1852         case IBMVFC_NO_CRQ:
1853         case IBMVFC_INITIALIZING:
1854         case IBMVFC_HALTED:
1855         case IBMVFC_LINK_DOWN:
1856                 result = DID_REQUEUE << 16;
1857                 break;
1858         case IBMVFC_ACTIVE:
1859                 result = 0;
1860                 break;
1861         }
1862
1863         return result;
1864 }
1865
1866 static struct ibmvfc_cmd *ibmvfc_init_vfc_cmd(struct ibmvfc_event *evt, struct scsi_device *sdev)
1867 {
1868         struct fc_rport *rport = starget_to_rport(scsi_target(sdev));
1869         struct ibmvfc_host *vhost = evt->vhost;
1870         struct ibmvfc_cmd *vfc_cmd = &evt->iu.cmd;
1871         struct ibmvfc_fcp_cmd_iu *iu = ibmvfc_get_fcp_iu(vhost, vfc_cmd);
1872         struct ibmvfc_fcp_rsp *rsp = ibmvfc_get_fcp_rsp(vhost, vfc_cmd);
1873         size_t offset;
1874
1875         memset(vfc_cmd, 0, sizeof(*vfc_cmd));
1876         if (ibmvfc_check_caps(vhost, IBMVFC_HANDLE_VF_WWPN)) {
1877                 offset = offsetof(struct ibmvfc_cmd, v2.rsp);
1878                 vfc_cmd->target_wwpn = cpu_to_be64(rport->port_name);
1879         } else
1880                 offset = offsetof(struct ibmvfc_cmd, v1.rsp);
1881         vfc_cmd->resp.va = cpu_to_be64(be64_to_cpu(evt->crq.ioba) + offset);
1882         vfc_cmd->resp.len = cpu_to_be32(sizeof(*rsp));
1883         vfc_cmd->frame_type = cpu_to_be32(IBMVFC_SCSI_FCP_TYPE);
1884         vfc_cmd->payload_len = cpu_to_be32(sizeof(*iu));
1885         vfc_cmd->resp_len = cpu_to_be32(sizeof(*rsp));
1886         vfc_cmd->cancel_key = cpu_to_be32((unsigned long)sdev->hostdata);
1887         vfc_cmd->tgt_scsi_id = cpu_to_be64(rport->port_id);
1888         int_to_scsilun(sdev->lun, &iu->lun);
1889
1890         return vfc_cmd;
1891 }
1892
1893 /**
1894  * ibmvfc_queuecommand - The queuecommand function of the scsi template
1895  * @cmnd:       struct scsi_cmnd to be executed
1896  * @done:       Callback function to be called when cmnd is completed
1897  *
1898  * Returns:
1899  *      0 on success / other on failure
1900  **/
1901 static int ibmvfc_queuecommand(struct Scsi_Host *shost, struct scsi_cmnd *cmnd)
1902 {
1903         struct ibmvfc_host *vhost = shost_priv(shost);
1904         struct fc_rport *rport = starget_to_rport(scsi_target(cmnd->device));
1905         struct ibmvfc_cmd *vfc_cmd;
1906         struct ibmvfc_fcp_cmd_iu *iu;
1907         struct ibmvfc_event *evt;
1908         u32 tag_and_hwq = blk_mq_unique_tag(cmnd->request);
1909         u16 hwq = blk_mq_unique_tag_to_hwq(tag_and_hwq);
1910         u16 scsi_channel;
1911         int rc;
1912
1913         if (unlikely((rc = fc_remote_port_chkready(rport))) ||
1914             unlikely((rc = ibmvfc_host_chkready(vhost)))) {
1915                 cmnd->result = rc;
1916                 cmnd->scsi_done(cmnd);
1917                 return 0;
1918         }
1919
1920         cmnd->result = (DID_OK << 16);
1921         if (vhost->using_channels) {
1922                 scsi_channel = hwq % vhost->scsi_scrqs.active_queues;
1923                 evt = ibmvfc_get_event(&vhost->scsi_scrqs.scrqs[scsi_channel]);
1924                 evt->hwq = hwq % vhost->scsi_scrqs.active_queues;
1925         } else
1926                 evt = ibmvfc_get_event(&vhost->crq);
1927
1928         ibmvfc_init_event(evt, ibmvfc_scsi_done, IBMVFC_CMD_FORMAT);
1929         evt->cmnd = cmnd;
1930
1931         vfc_cmd = ibmvfc_init_vfc_cmd(evt, cmnd->device);
1932         iu = ibmvfc_get_fcp_iu(vhost, vfc_cmd);
1933
1934         iu->xfer_len = cpu_to_be32(scsi_bufflen(cmnd));
1935         memcpy(iu->cdb, cmnd->cmnd, cmnd->cmd_len);
1936
1937         if (cmnd->flags & SCMD_TAGGED) {
1938                 vfc_cmd->task_tag = cpu_to_be64(cmnd->tag);
1939                 iu->pri_task_attr = IBMVFC_SIMPLE_TASK;
1940         }
1941
1942         vfc_cmd->correlation = cpu_to_be64((u64)evt);
1943
1944         if (likely(!(rc = ibmvfc_map_sg_data(cmnd, evt, vfc_cmd, vhost->dev))))
1945                 return ibmvfc_send_event(evt, vhost, 0);
1946
1947         ibmvfc_free_event(evt);
1948         if (rc == -ENOMEM)
1949                 return SCSI_MLQUEUE_HOST_BUSY;
1950
1951         if (vhost->log_level > IBMVFC_DEFAULT_LOG_LEVEL)
1952                 scmd_printk(KERN_ERR, cmnd,
1953                             "Failed to map DMA buffer for command. rc=%d\n", rc);
1954
1955         cmnd->result = DID_ERROR << 16;
1956         cmnd->scsi_done(cmnd);
1957         return 0;
1958 }
1959
1960 /**
1961  * ibmvfc_sync_completion - Signal that a synchronous command has completed
1962  * @evt:        ibmvfc event struct
1963  *
1964  **/
1965 static void ibmvfc_sync_completion(struct ibmvfc_event *evt)
1966 {
1967         /* copy the response back */
1968         if (evt->sync_iu)
1969                 *evt->sync_iu = *evt->xfer_iu;
1970
1971         complete(&evt->comp);
1972 }
1973
1974 /**
1975  * ibmvfc_bsg_timeout_done - Completion handler for cancelling BSG commands
1976  * @evt:        struct ibmvfc_event
1977  *
1978  **/
1979 static void ibmvfc_bsg_timeout_done(struct ibmvfc_event *evt)
1980 {
1981         struct ibmvfc_host *vhost = evt->vhost;
1982
1983         ibmvfc_free_event(evt);
1984         vhost->aborting_passthru = 0;
1985         dev_info(vhost->dev, "Passthru command cancelled\n");
1986 }
1987
1988 /**
1989  * ibmvfc_bsg_timeout - Handle a BSG timeout
1990  * @job:        struct bsg_job that timed out
1991  *
1992  * Returns:
1993  *      0 on success / other on failure
1994  **/
1995 static int ibmvfc_bsg_timeout(struct bsg_job *job)
1996 {
1997         struct ibmvfc_host *vhost = shost_priv(fc_bsg_to_shost(job));
1998         unsigned long port_id = (unsigned long)job->dd_data;
1999         struct ibmvfc_event *evt;
2000         struct ibmvfc_tmf *tmf;
2001         unsigned long flags;
2002         int rc;
2003
2004         ENTER;
2005         spin_lock_irqsave(vhost->host->host_lock, flags);
2006         if (vhost->aborting_passthru || vhost->state != IBMVFC_ACTIVE) {
2007                 __ibmvfc_reset_host(vhost);
2008                 spin_unlock_irqrestore(vhost->host->host_lock, flags);
2009                 return 0;
2010         }
2011
2012         vhost->aborting_passthru = 1;
2013         evt = ibmvfc_get_event(&vhost->crq);
2014         ibmvfc_init_event(evt, ibmvfc_bsg_timeout_done, IBMVFC_MAD_FORMAT);
2015
2016         tmf = &evt->iu.tmf;
2017         memset(tmf, 0, sizeof(*tmf));
2018         tmf->common.version = cpu_to_be32(1);
2019         tmf->common.opcode = cpu_to_be32(IBMVFC_TMF_MAD);
2020         tmf->common.length = cpu_to_be16(sizeof(*tmf));
2021         tmf->scsi_id = cpu_to_be64(port_id);
2022         tmf->cancel_key = cpu_to_be32(IBMVFC_PASSTHRU_CANCEL_KEY);
2023         tmf->my_cancel_key = cpu_to_be32(IBMVFC_INTERNAL_CANCEL_KEY);
2024         rc = ibmvfc_send_event(evt, vhost, default_timeout);
2025
2026         if (rc != 0) {
2027                 vhost->aborting_passthru = 0;
2028                 dev_err(vhost->dev, "Failed to send cancel event. rc=%d\n", rc);
2029                 rc = -EIO;
2030         } else
2031                 dev_info(vhost->dev, "Cancelling passthru command to port id 0x%lx\n",
2032                          port_id);
2033
2034         spin_unlock_irqrestore(vhost->host->host_lock, flags);
2035
2036         LEAVE;
2037         return rc;
2038 }
2039
2040 /**
2041  * ibmvfc_bsg_plogi - PLOGI into a target to handle a BSG command
2042  * @vhost:              struct ibmvfc_host to send command
2043  * @port_id:    port ID to send command
2044  *
2045  * Returns:
2046  *      0 on success / other on failure
2047  **/
2048 static int ibmvfc_bsg_plogi(struct ibmvfc_host *vhost, unsigned int port_id)
2049 {
2050         struct ibmvfc_port_login *plogi;
2051         struct ibmvfc_target *tgt;
2052         struct ibmvfc_event *evt;
2053         union ibmvfc_iu rsp_iu;
2054         unsigned long flags;
2055         int rc = 0, issue_login = 1;
2056
2057         ENTER;
2058         spin_lock_irqsave(vhost->host->host_lock, flags);
2059         list_for_each_entry(tgt, &vhost->targets, queue) {
2060                 if (tgt->scsi_id == port_id) {
2061                         issue_login = 0;
2062                         break;
2063                 }
2064         }
2065
2066         if (!issue_login)
2067                 goto unlock_out;
2068         if (unlikely((rc = ibmvfc_host_chkready(vhost))))
2069                 goto unlock_out;
2070
2071         evt = ibmvfc_get_event(&vhost->crq);
2072         ibmvfc_init_event(evt, ibmvfc_sync_completion, IBMVFC_MAD_FORMAT);
2073         plogi = &evt->iu.plogi;
2074         memset(plogi, 0, sizeof(*plogi));
2075         plogi->common.version = cpu_to_be32(1);
2076         plogi->common.opcode = cpu_to_be32(IBMVFC_PORT_LOGIN);
2077         plogi->common.length = cpu_to_be16(sizeof(*plogi));
2078         plogi->scsi_id = cpu_to_be64(port_id);
2079         evt->sync_iu = &rsp_iu;
2080         init_completion(&evt->comp);
2081
2082         rc = ibmvfc_send_event(evt, vhost, default_timeout);
2083         spin_unlock_irqrestore(vhost->host->host_lock, flags);
2084
2085         if (rc)
2086                 return -EIO;
2087
2088         wait_for_completion(&evt->comp);
2089
2090         if (rsp_iu.plogi.common.status)
2091                 rc = -EIO;
2092
2093         spin_lock_irqsave(vhost->host->host_lock, flags);
2094         ibmvfc_free_event(evt);
2095 unlock_out:
2096         spin_unlock_irqrestore(vhost->host->host_lock, flags);
2097         LEAVE;
2098         return rc;
2099 }
2100
2101 /**
2102  * ibmvfc_bsg_request - Handle a BSG request
2103  * @job:        struct bsg_job to be executed
2104  *
2105  * Returns:
2106  *      0 on success / other on failure
2107  **/
2108 static int ibmvfc_bsg_request(struct bsg_job *job)
2109 {
2110         struct ibmvfc_host *vhost = shost_priv(fc_bsg_to_shost(job));
2111         struct fc_rport *rport = fc_bsg_to_rport(job);
2112         struct ibmvfc_passthru_mad *mad;
2113         struct ibmvfc_event *evt;
2114         union ibmvfc_iu rsp_iu;
2115         unsigned long flags, port_id = -1;
2116         struct fc_bsg_request *bsg_request = job->request;
2117         struct fc_bsg_reply *bsg_reply = job->reply;
2118         unsigned int code = bsg_request->msgcode;
2119         int rc = 0, req_seg, rsp_seg, issue_login = 0;
2120         u32 fc_flags, rsp_len;
2121
2122         ENTER;
2123         bsg_reply->reply_payload_rcv_len = 0;
2124         if (rport)
2125                 port_id = rport->port_id;
2126
2127         switch (code) {
2128         case FC_BSG_HST_ELS_NOLOGIN:
2129                 port_id = (bsg_request->rqst_data.h_els.port_id[0] << 16) |
2130                         (bsg_request->rqst_data.h_els.port_id[1] << 8) |
2131                         bsg_request->rqst_data.h_els.port_id[2];
2132                 fallthrough;
2133         case FC_BSG_RPT_ELS:
2134                 fc_flags = IBMVFC_FC_ELS;
2135                 break;
2136         case FC_BSG_HST_CT:
2137                 issue_login = 1;
2138                 port_id = (bsg_request->rqst_data.h_ct.port_id[0] << 16) |
2139                         (bsg_request->rqst_data.h_ct.port_id[1] << 8) |
2140                         bsg_request->rqst_data.h_ct.port_id[2];
2141                 fallthrough;
2142         case FC_BSG_RPT_CT:
2143                 fc_flags = IBMVFC_FC_CT_IU;
2144                 break;
2145         default:
2146                 return -ENOTSUPP;
2147         }
2148
2149         if (port_id == -1)
2150                 return -EINVAL;
2151         if (!mutex_trylock(&vhost->passthru_mutex))
2152                 return -EBUSY;
2153
2154         job->dd_data = (void *)port_id;
2155         req_seg = dma_map_sg(vhost->dev, job->request_payload.sg_list,
2156                              job->request_payload.sg_cnt, DMA_TO_DEVICE);
2157
2158         if (!req_seg) {
2159                 mutex_unlock(&vhost->passthru_mutex);
2160                 return -ENOMEM;
2161         }
2162
2163         rsp_seg = dma_map_sg(vhost->dev, job->reply_payload.sg_list,
2164                              job->reply_payload.sg_cnt, DMA_FROM_DEVICE);
2165
2166         if (!rsp_seg) {
2167                 dma_unmap_sg(vhost->dev, job->request_payload.sg_list,
2168                              job->request_payload.sg_cnt, DMA_TO_DEVICE);
2169                 mutex_unlock(&vhost->passthru_mutex);
2170                 return -ENOMEM;
2171         }
2172
2173         if (req_seg > 1 || rsp_seg > 1) {
2174                 rc = -EINVAL;
2175                 goto out;
2176         }
2177
2178         if (issue_login)
2179                 rc = ibmvfc_bsg_plogi(vhost, port_id);
2180
2181         spin_lock_irqsave(vhost->host->host_lock, flags);
2182
2183         if (unlikely(rc || (rport && (rc = fc_remote_port_chkready(rport)))) ||
2184             unlikely((rc = ibmvfc_host_chkready(vhost)))) {
2185                 spin_unlock_irqrestore(vhost->host->host_lock, flags);
2186                 goto out;
2187         }
2188
2189         evt = ibmvfc_get_event(&vhost->crq);
2190         ibmvfc_init_event(evt, ibmvfc_sync_completion, IBMVFC_MAD_FORMAT);
2191         mad = &evt->iu.passthru;
2192
2193         memset(mad, 0, sizeof(*mad));
2194         mad->common.version = cpu_to_be32(1);
2195         mad->common.opcode = cpu_to_be32(IBMVFC_PASSTHRU);
2196         mad->common.length = cpu_to_be16(sizeof(*mad) - sizeof(mad->fc_iu) - sizeof(mad->iu));
2197
2198         mad->cmd_ioba.va = cpu_to_be64(be64_to_cpu(evt->crq.ioba) +
2199                 offsetof(struct ibmvfc_passthru_mad, iu));
2200         mad->cmd_ioba.len = cpu_to_be32(sizeof(mad->iu));
2201
2202         mad->iu.cmd_len = cpu_to_be32(job->request_payload.payload_len);
2203         mad->iu.rsp_len = cpu_to_be32(job->reply_payload.payload_len);
2204         mad->iu.flags = cpu_to_be32(fc_flags);
2205         mad->iu.cancel_key = cpu_to_be32(IBMVFC_PASSTHRU_CANCEL_KEY);
2206
2207         mad->iu.cmd.va = cpu_to_be64(sg_dma_address(job->request_payload.sg_list));
2208         mad->iu.cmd.len = cpu_to_be32(sg_dma_len(job->request_payload.sg_list));
2209         mad->iu.rsp.va = cpu_to_be64(sg_dma_address(job->reply_payload.sg_list));
2210         mad->iu.rsp.len = cpu_to_be32(sg_dma_len(job->reply_payload.sg_list));
2211         mad->iu.scsi_id = cpu_to_be64(port_id);
2212         mad->iu.tag = cpu_to_be64((u64)evt);
2213         rsp_len = be32_to_cpu(mad->iu.rsp.len);
2214
2215         evt->sync_iu = &rsp_iu;
2216         init_completion(&evt->comp);
2217         rc = ibmvfc_send_event(evt, vhost, 0);
2218         spin_unlock_irqrestore(vhost->host->host_lock, flags);
2219
2220         if (rc) {
2221                 rc = -EIO;
2222                 goto out;
2223         }
2224
2225         wait_for_completion(&evt->comp);
2226
2227         if (rsp_iu.passthru.common.status)
2228                 rc = -EIO;
2229         else
2230                 bsg_reply->reply_payload_rcv_len = rsp_len;
2231
2232         spin_lock_irqsave(vhost->host->host_lock, flags);
2233         ibmvfc_free_event(evt);
2234         spin_unlock_irqrestore(vhost->host->host_lock, flags);
2235         bsg_reply->result = rc;
2236         bsg_job_done(job, bsg_reply->result,
2237                        bsg_reply->reply_payload_rcv_len);
2238         rc = 0;
2239 out:
2240         dma_unmap_sg(vhost->dev, job->request_payload.sg_list,
2241                      job->request_payload.sg_cnt, DMA_TO_DEVICE);
2242         dma_unmap_sg(vhost->dev, job->reply_payload.sg_list,
2243                      job->reply_payload.sg_cnt, DMA_FROM_DEVICE);
2244         mutex_unlock(&vhost->passthru_mutex);
2245         LEAVE;
2246         return rc;
2247 }
2248
2249 /**
2250  * ibmvfc_reset_device - Reset the device with the specified reset type
2251  * @sdev:       scsi device to reset
2252  * @type:       reset type
2253  * @desc:       reset type description for log messages
2254  *
2255  * Returns:
2256  *      0 on success / other on failure
2257  **/
2258 static int ibmvfc_reset_device(struct scsi_device *sdev, int type, char *desc)
2259 {
2260         struct ibmvfc_host *vhost = shost_priv(sdev->host);
2261         struct fc_rport *rport = starget_to_rport(scsi_target(sdev));
2262         struct ibmvfc_cmd *tmf;
2263         struct ibmvfc_event *evt = NULL;
2264         union ibmvfc_iu rsp_iu;
2265         struct ibmvfc_fcp_cmd_iu *iu;
2266         struct ibmvfc_fcp_rsp *fc_rsp = ibmvfc_get_fcp_rsp(vhost, &rsp_iu.cmd);
2267         int rsp_rc = -EBUSY;
2268         unsigned long flags;
2269         int rsp_code = 0;
2270
2271         spin_lock_irqsave(vhost->host->host_lock, flags);
2272         if (vhost->state == IBMVFC_ACTIVE) {
2273                 if (vhost->using_channels)
2274                         evt = ibmvfc_get_event(&vhost->scsi_scrqs.scrqs[0]);
2275                 else
2276                         evt = ibmvfc_get_event(&vhost->crq);
2277
2278                 ibmvfc_init_event(evt, ibmvfc_sync_completion, IBMVFC_CMD_FORMAT);
2279                 tmf = ibmvfc_init_vfc_cmd(evt, sdev);
2280                 iu = ibmvfc_get_fcp_iu(vhost, tmf);
2281
2282                 tmf->flags = cpu_to_be16((IBMVFC_NO_MEM_DESC | IBMVFC_TMF));
2283                 if (ibmvfc_check_caps(vhost, IBMVFC_HANDLE_VF_WWPN))
2284                         tmf->target_wwpn = cpu_to_be64(rport->port_name);
2285                 iu->tmf_flags = type;
2286                 evt->sync_iu = &rsp_iu;
2287
2288                 init_completion(&evt->comp);
2289                 rsp_rc = ibmvfc_send_event(evt, vhost, default_timeout);
2290         }
2291         spin_unlock_irqrestore(vhost->host->host_lock, flags);
2292
2293         if (rsp_rc != 0) {
2294                 sdev_printk(KERN_ERR, sdev, "Failed to send %s reset event. rc=%d\n",
2295                             desc, rsp_rc);
2296                 return -EIO;
2297         }
2298
2299         sdev_printk(KERN_INFO, sdev, "Resetting %s\n", desc);
2300         wait_for_completion(&evt->comp);
2301
2302         if (rsp_iu.cmd.status)
2303                 rsp_code = ibmvfc_get_err_result(vhost, &rsp_iu.cmd);
2304
2305         if (rsp_code) {
2306                 if (fc_rsp->flags & FCP_RSP_LEN_VALID)
2307                         rsp_code = fc_rsp->data.info.rsp_code;
2308
2309                 sdev_printk(KERN_ERR, sdev, "%s reset failed: %s (%x:%x) "
2310                             "flags: %x fcp_rsp: %x, scsi_status: %x\n", desc,
2311                             ibmvfc_get_cmd_error(be16_to_cpu(rsp_iu.cmd.status), be16_to_cpu(rsp_iu.cmd.error)),
2312                             be16_to_cpu(rsp_iu.cmd.status), be16_to_cpu(rsp_iu.cmd.error), fc_rsp->flags, rsp_code,
2313                             fc_rsp->scsi_status);
2314                 rsp_rc = -EIO;
2315         } else
2316                 sdev_printk(KERN_INFO, sdev, "%s reset successful\n", desc);
2317
2318         spin_lock_irqsave(vhost->host->host_lock, flags);
2319         ibmvfc_free_event(evt);
2320         spin_unlock_irqrestore(vhost->host->host_lock, flags);
2321         return rsp_rc;
2322 }
2323
2324 /**
2325  * ibmvfc_match_rport - Match function for specified remote port
2326  * @evt:        ibmvfc event struct
2327  * @device:     device to match (rport)
2328  *
2329  * Returns:
2330  *      1 if event matches rport / 0 if event does not match rport
2331  **/
2332 static int ibmvfc_match_rport(struct ibmvfc_event *evt, void *rport)
2333 {
2334         struct fc_rport *cmd_rport;
2335
2336         if (evt->cmnd) {
2337                 cmd_rport = starget_to_rport(scsi_target(evt->cmnd->device));
2338                 if (cmd_rport == rport)
2339                         return 1;
2340         }
2341         return 0;
2342 }
2343
2344 /**
2345  * ibmvfc_match_target - Match function for specified target
2346  * @evt:        ibmvfc event struct
2347  * @device:     device to match (starget)
2348  *
2349  * Returns:
2350  *      1 if event matches starget / 0 if event does not match starget
2351  **/
2352 static int ibmvfc_match_target(struct ibmvfc_event *evt, void *device)
2353 {
2354         if (evt->cmnd && scsi_target(evt->cmnd->device) == device)
2355                 return 1;
2356         return 0;
2357 }
2358
2359 /**
2360  * ibmvfc_match_lun - Match function for specified LUN
2361  * @evt:        ibmvfc event struct
2362  * @device:     device to match (sdev)
2363  *
2364  * Returns:
2365  *      1 if event matches sdev / 0 if event does not match sdev
2366  **/
2367 static int ibmvfc_match_lun(struct ibmvfc_event *evt, void *device)
2368 {
2369         if (evt->cmnd && evt->cmnd->device == device)
2370                 return 1;
2371         return 0;
2372 }
2373
2374 /**
2375  * ibmvfc_event_is_free - Check if event is free or not
2376  * @evt:        ibmvfc event struct
2377  *
2378  * Returns:
2379  *      true / false
2380  **/
2381 static bool ibmvfc_event_is_free(struct ibmvfc_event *evt)
2382 {
2383         struct ibmvfc_event *loop_evt;
2384
2385         list_for_each_entry(loop_evt, &evt->queue->free, queue_list)
2386                 if (loop_evt == evt)
2387                         return true;
2388
2389         return false;
2390 }
2391
2392 /**
2393  * ibmvfc_wait_for_ops - Wait for ops to complete
2394  * @vhost:      ibmvfc host struct
2395  * @device:     device to match (starget or sdev)
2396  * @match:      match function
2397  *
2398  * Returns:
2399  *      SUCCESS / FAILED
2400  **/
2401 static int ibmvfc_wait_for_ops(struct ibmvfc_host *vhost, void *device,
2402                                int (*match) (struct ibmvfc_event *, void *))
2403 {
2404         struct ibmvfc_event *evt;
2405         DECLARE_COMPLETION_ONSTACK(comp);
2406         int wait, i, q_index, q_size;
2407         unsigned long flags;
2408         signed long timeout = IBMVFC_ABORT_WAIT_TIMEOUT * HZ;
2409         struct ibmvfc_queue *queues;
2410
2411         ENTER;
2412         if (vhost->mq_enabled && vhost->using_channels) {
2413                 queues = vhost->scsi_scrqs.scrqs;
2414                 q_size = vhost->scsi_scrqs.active_queues;
2415         } else {
2416                 queues = &vhost->crq;
2417                 q_size = 1;
2418         }
2419
2420         do {
2421                 wait = 0;
2422                 spin_lock_irqsave(vhost->host->host_lock, flags);
2423                 for (q_index = 0; q_index < q_size; q_index++) {
2424                         spin_lock(&queues[q_index].l_lock);
2425                         for (i = 0; i < queues[q_index].evt_pool.size; i++) {
2426                                 evt = &queues[q_index].evt_pool.events[i];
2427                                 if (!ibmvfc_event_is_free(evt)) {
2428                                         if (match(evt, device)) {
2429                                                 evt->eh_comp = &comp;
2430                                                 wait++;
2431                                         }
2432                                 }
2433                         }
2434                         spin_unlock(&queues[q_index].l_lock);
2435                 }
2436                 spin_unlock_irqrestore(vhost->host->host_lock, flags);
2437
2438                 if (wait) {
2439                         timeout = wait_for_completion_timeout(&comp, timeout);
2440
2441                         if (!timeout) {
2442                                 wait = 0;
2443                                 spin_lock_irqsave(vhost->host->host_lock, flags);
2444                                 for (q_index = 0; q_index < q_size; q_index++) {
2445                                         spin_lock(&queues[q_index].l_lock);
2446                                         for (i = 0; i < queues[q_index].evt_pool.size; i++) {
2447                                                 evt = &queues[q_index].evt_pool.events[i];
2448                                                 if (!ibmvfc_event_is_free(evt)) {
2449                                                         if (match(evt, device)) {
2450                                                                 evt->eh_comp = NULL;
2451                                                                 wait++;
2452                                                         }
2453                                                 }
2454                                         }
2455                                         spin_unlock(&queues[q_index].l_lock);
2456                                 }
2457                                 spin_unlock_irqrestore(vhost->host->host_lock, flags);
2458                                 if (wait)
2459                                         dev_err(vhost->dev, "Timed out waiting for aborted commands\n");
2460                                 LEAVE;
2461                                 return wait ? FAILED : SUCCESS;
2462                         }
2463                 }
2464         } while (wait);
2465
2466         LEAVE;
2467         return SUCCESS;
2468 }
2469
2470 static struct ibmvfc_event *ibmvfc_init_tmf(struct ibmvfc_queue *queue,
2471                                             struct scsi_device *sdev,
2472                                             int type)
2473 {
2474         struct ibmvfc_host *vhost = shost_priv(sdev->host);
2475         struct scsi_target *starget = scsi_target(sdev);
2476         struct fc_rport *rport = starget_to_rport(starget);
2477         struct ibmvfc_event *evt;
2478         struct ibmvfc_tmf *tmf;
2479
2480         evt = ibmvfc_get_event(queue);
2481         ibmvfc_init_event(evt, ibmvfc_sync_completion, IBMVFC_MAD_FORMAT);
2482
2483         tmf = &evt->iu.tmf;
2484         memset(tmf, 0, sizeof(*tmf));
2485         if (ibmvfc_check_caps(vhost, IBMVFC_HANDLE_VF_WWPN)) {
2486                 tmf->common.version = cpu_to_be32(2);
2487                 tmf->target_wwpn = cpu_to_be64(rport->port_name);
2488         } else {
2489                 tmf->common.version = cpu_to_be32(1);
2490         }
2491         tmf->common.opcode = cpu_to_be32(IBMVFC_TMF_MAD);
2492         tmf->common.length = cpu_to_be16(sizeof(*tmf));
2493         tmf->scsi_id = cpu_to_be64(rport->port_id);
2494         int_to_scsilun(sdev->lun, &tmf->lun);
2495         if (!ibmvfc_check_caps(vhost, IBMVFC_CAN_SUPPRESS_ABTS))
2496                 type &= ~IBMVFC_TMF_SUPPRESS_ABTS;
2497         if (vhost->state == IBMVFC_ACTIVE)
2498                 tmf->flags = cpu_to_be32((type | IBMVFC_TMF_LUA_VALID));
2499         else
2500                 tmf->flags = cpu_to_be32(((type & IBMVFC_TMF_SUPPRESS_ABTS) | IBMVFC_TMF_LUA_VALID));
2501         tmf->cancel_key = cpu_to_be32((unsigned long)sdev->hostdata);
2502         tmf->my_cancel_key = cpu_to_be32((unsigned long)starget->hostdata);
2503
2504         init_completion(&evt->comp);
2505
2506         return evt;
2507 }
2508
2509 static int ibmvfc_cancel_all_mq(struct scsi_device *sdev, int type)
2510 {
2511         struct ibmvfc_host *vhost = shost_priv(sdev->host);
2512         struct ibmvfc_event *evt, *found_evt, *temp;
2513         struct ibmvfc_queue *queues = vhost->scsi_scrqs.scrqs;
2514         unsigned long flags;
2515         int num_hwq, i;
2516         int fail = 0;
2517         LIST_HEAD(cancelq);
2518         u16 status;
2519
2520         ENTER;
2521         spin_lock_irqsave(vhost->host->host_lock, flags);
2522         num_hwq = vhost->scsi_scrqs.active_queues;
2523         for (i = 0; i < num_hwq; i++) {
2524                 spin_lock(queues[i].q_lock);
2525                 spin_lock(&queues[i].l_lock);
2526                 found_evt = NULL;
2527                 list_for_each_entry(evt, &queues[i].sent, queue_list) {
2528                         if (evt->cmnd && evt->cmnd->device == sdev) {
2529                                 found_evt = evt;
2530                                 break;
2531                         }
2532                 }
2533                 spin_unlock(&queues[i].l_lock);
2534
2535                 if (found_evt && vhost->logged_in) {
2536                         evt = ibmvfc_init_tmf(&queues[i], sdev, type);
2537                         evt->sync_iu = &queues[i].cancel_rsp;
2538                         ibmvfc_send_event(evt, vhost, default_timeout);
2539                         list_add_tail(&evt->cancel, &cancelq);
2540                 }
2541
2542                 spin_unlock(queues[i].q_lock);
2543         }
2544         spin_unlock_irqrestore(vhost->host->host_lock, flags);
2545
2546         if (list_empty(&cancelq)) {
2547                 if (vhost->log_level > IBMVFC_DEFAULT_LOG_LEVEL)
2548                         sdev_printk(KERN_INFO, sdev, "No events found to cancel\n");
2549                 return 0;
2550         }
2551
2552         sdev_printk(KERN_INFO, sdev, "Cancelling outstanding commands.\n");
2553
2554         list_for_each_entry_safe(evt, temp, &cancelq, cancel) {
2555                 wait_for_completion(&evt->comp);
2556                 status = be16_to_cpu(evt->queue->cancel_rsp.mad_common.status);
2557                 list_del(&evt->cancel);
2558                 ibmvfc_free_event(evt);
2559
2560                 if (status != IBMVFC_MAD_SUCCESS) {
2561                         sdev_printk(KERN_WARNING, sdev, "Cancel failed with rc=%x\n", status);
2562                         switch (status) {
2563                         case IBMVFC_MAD_DRIVER_FAILED:
2564                         case IBMVFC_MAD_CRQ_ERROR:
2565                         /* Host adapter most likely going through reset, return success to
2566                          * the caller will wait for the command being cancelled to get returned
2567                          */
2568                                 break;
2569                         default:
2570                                 fail = 1;
2571                                 break;
2572                         }
2573                 }
2574         }
2575
2576         if (fail)
2577                 return -EIO;
2578
2579         sdev_printk(KERN_INFO, sdev, "Successfully cancelled outstanding commands\n");
2580         LEAVE;
2581         return 0;
2582 }
2583
2584 static int ibmvfc_cancel_all_sq(struct scsi_device *sdev, int type)
2585 {
2586         struct ibmvfc_host *vhost = shost_priv(sdev->host);
2587         struct ibmvfc_event *evt, *found_evt;
2588         union ibmvfc_iu rsp;
2589         int rsp_rc = -EBUSY;
2590         unsigned long flags;
2591         u16 status;
2592
2593         ENTER;
2594         found_evt = NULL;
2595         spin_lock_irqsave(vhost->host->host_lock, flags);
2596         spin_lock(&vhost->crq.l_lock);
2597         list_for_each_entry(evt, &vhost->crq.sent, queue_list) {
2598                 if (evt->cmnd && evt->cmnd->device == sdev) {
2599                         found_evt = evt;
2600                         break;
2601                 }
2602         }
2603         spin_unlock(&vhost->crq.l_lock);
2604
2605         if (!found_evt) {
2606                 if (vhost->log_level > IBMVFC_DEFAULT_LOG_LEVEL)
2607                         sdev_printk(KERN_INFO, sdev, "No events found to cancel\n");
2608                 spin_unlock_irqrestore(vhost->host->host_lock, flags);
2609                 return 0;
2610         }
2611
2612         if (vhost->logged_in) {
2613                 evt = ibmvfc_init_tmf(&vhost->crq, sdev, type);
2614                 evt->sync_iu = &rsp;
2615                 rsp_rc = ibmvfc_send_event(evt, vhost, default_timeout);
2616         }
2617
2618         spin_unlock_irqrestore(vhost->host->host_lock, flags);
2619
2620         if (rsp_rc != 0) {
2621                 sdev_printk(KERN_ERR, sdev, "Failed to send cancel event. rc=%d\n", rsp_rc);
2622                 /* If failure is received, the host adapter is most likely going
2623                  through reset, return success so the caller will wait for the command
2624                  being cancelled to get returned */
2625                 return 0;
2626         }
2627
2628         sdev_printk(KERN_INFO, sdev, "Cancelling outstanding commands.\n");
2629
2630         wait_for_completion(&evt->comp);
2631         status = be16_to_cpu(rsp.mad_common.status);
2632         spin_lock_irqsave(vhost->host->host_lock, flags);
2633         ibmvfc_free_event(evt);
2634         spin_unlock_irqrestore(vhost->host->host_lock, flags);
2635
2636         if (status != IBMVFC_MAD_SUCCESS) {
2637                 sdev_printk(KERN_WARNING, sdev, "Cancel failed with rc=%x\n", status);
2638                 switch (status) {
2639                 case IBMVFC_MAD_DRIVER_FAILED:
2640                 case IBMVFC_MAD_CRQ_ERROR:
2641                         /* Host adapter most likely going through reset, return success to
2642                          the caller will wait for the command being cancelled to get returned */
2643                         return 0;
2644                 default:
2645                         return -EIO;
2646                 };
2647         }
2648
2649         sdev_printk(KERN_INFO, sdev, "Successfully cancelled outstanding commands\n");
2650         return 0;
2651 }
2652
2653 /**
2654  * ibmvfc_cancel_all - Cancel all outstanding commands to the device
2655  * @sdev:       scsi device to cancel commands
2656  * @type:       type of error recovery being performed
2657  *
2658  * This sends a cancel to the VIOS for the specified device. This does
2659  * NOT send any abort to the actual device. That must be done separately.
2660  *
2661  * Returns:
2662  *      0 on success / other on failure
2663  **/
2664 static int ibmvfc_cancel_all(struct scsi_device *sdev, int type)
2665 {
2666         struct ibmvfc_host *vhost = shost_priv(sdev->host);
2667
2668         if (vhost->mq_enabled && vhost->using_channels)
2669                 return ibmvfc_cancel_all_mq(sdev, type);
2670         else
2671                 return ibmvfc_cancel_all_sq(sdev, type);
2672 }
2673
2674 /**
2675  * ibmvfc_match_key - Match function for specified cancel key
2676  * @evt:        ibmvfc event struct
2677  * @key:        cancel key to match
2678  *
2679  * Returns:
2680  *      1 if event matches key / 0 if event does not match key
2681  **/
2682 static int ibmvfc_match_key(struct ibmvfc_event *evt, void *key)
2683 {
2684         unsigned long cancel_key = (unsigned long)key;
2685
2686         if (evt->crq.format == IBMVFC_CMD_FORMAT &&
2687             be32_to_cpu(evt->iu.cmd.cancel_key) == cancel_key)
2688                 return 1;
2689         return 0;
2690 }
2691
2692 /**
2693  * ibmvfc_match_evt - Match function for specified event
2694  * @evt:        ibmvfc event struct
2695  * @match:      event to match
2696  *
2697  * Returns:
2698  *      1 if event matches key / 0 if event does not match key
2699  **/
2700 static int ibmvfc_match_evt(struct ibmvfc_event *evt, void *match)
2701 {
2702         if (evt == match)
2703                 return 1;
2704         return 0;
2705 }
2706
2707 /**
2708  * ibmvfc_abort_task_set - Abort outstanding commands to the device
2709  * @sdev:       scsi device to abort commands
2710  *
2711  * This sends an Abort Task Set to the VIOS for the specified device. This does
2712  * NOT send any cancel to the VIOS. That must be done separately.
2713  *
2714  * Returns:
2715  *      0 on success / other on failure
2716  **/
2717 static int ibmvfc_abort_task_set(struct scsi_device *sdev)
2718 {
2719         struct ibmvfc_host *vhost = shost_priv(sdev->host);
2720         struct fc_rport *rport = starget_to_rport(scsi_target(sdev));
2721         struct ibmvfc_cmd *tmf;
2722         struct ibmvfc_event *evt, *found_evt;
2723         union ibmvfc_iu rsp_iu;
2724         struct ibmvfc_fcp_cmd_iu *iu;
2725         struct ibmvfc_fcp_rsp *fc_rsp = ibmvfc_get_fcp_rsp(vhost, &rsp_iu.cmd);
2726         int rc, rsp_rc = -EBUSY;
2727         unsigned long flags, timeout = IBMVFC_ABORT_TIMEOUT;
2728         int rsp_code = 0;
2729
2730         found_evt = NULL;
2731         spin_lock_irqsave(vhost->host->host_lock, flags);
2732         spin_lock(&vhost->crq.l_lock);
2733         list_for_each_entry(evt, &vhost->crq.sent, queue_list) {
2734                 if (evt->cmnd && evt->cmnd->device == sdev) {
2735                         found_evt = evt;
2736                         break;
2737                 }
2738         }
2739         spin_unlock(&vhost->crq.l_lock);
2740
2741         if (!found_evt) {
2742                 if (vhost->log_level > IBMVFC_DEFAULT_LOG_LEVEL)
2743                         sdev_printk(KERN_INFO, sdev, "No events found to abort\n");
2744                 spin_unlock_irqrestore(vhost->host->host_lock, flags);
2745                 return 0;
2746         }
2747
2748         if (vhost->state == IBMVFC_ACTIVE) {
2749                 evt = ibmvfc_get_event(&vhost->crq);
2750                 ibmvfc_init_event(evt, ibmvfc_sync_completion, IBMVFC_CMD_FORMAT);
2751                 tmf = ibmvfc_init_vfc_cmd(evt, sdev);
2752                 iu = ibmvfc_get_fcp_iu(vhost, tmf);
2753
2754                 if (ibmvfc_check_caps(vhost, IBMVFC_HANDLE_VF_WWPN))
2755                         tmf->target_wwpn = cpu_to_be64(rport->port_name);
2756                 iu->tmf_flags = IBMVFC_ABORT_TASK_SET;
2757                 tmf->flags = cpu_to_be16((IBMVFC_NO_MEM_DESC | IBMVFC_TMF));
2758                 evt->sync_iu = &rsp_iu;
2759
2760                 tmf->correlation = cpu_to_be64((u64)evt);
2761
2762                 init_completion(&evt->comp);
2763                 rsp_rc = ibmvfc_send_event(evt, vhost, default_timeout);
2764         }
2765
2766         spin_unlock_irqrestore(vhost->host->host_lock, flags);
2767
2768         if (rsp_rc != 0) {
2769                 sdev_printk(KERN_ERR, sdev, "Failed to send abort. rc=%d\n", rsp_rc);
2770                 return -EIO;
2771         }
2772
2773         sdev_printk(KERN_INFO, sdev, "Aborting outstanding commands\n");
2774         timeout = wait_for_completion_timeout(&evt->comp, timeout);
2775
2776         if (!timeout) {
2777                 rc = ibmvfc_cancel_all(sdev, 0);
2778                 if (!rc) {
2779                         rc = ibmvfc_wait_for_ops(vhost, sdev->hostdata, ibmvfc_match_key);
2780                         if (rc == SUCCESS)
2781                                 rc = 0;
2782                 }
2783
2784                 if (rc) {
2785                         sdev_printk(KERN_INFO, sdev, "Cancel failed, resetting host\n");
2786                         ibmvfc_reset_host(vhost);
2787                         rsp_rc = -EIO;
2788                         rc = ibmvfc_wait_for_ops(vhost, sdev->hostdata, ibmvfc_match_key);
2789
2790                         if (rc == SUCCESS)
2791                                 rsp_rc = 0;
2792
2793                         rc = ibmvfc_wait_for_ops(vhost, evt, ibmvfc_match_evt);
2794                         if (rc != SUCCESS) {
2795                                 spin_lock_irqsave(vhost->host->host_lock, flags);
2796                                 ibmvfc_hard_reset_host(vhost);
2797                                 spin_unlock_irqrestore(vhost->host->host_lock, flags);
2798                                 rsp_rc = 0;
2799                         }
2800
2801                         goto out;
2802                 }
2803         }
2804
2805         if (rsp_iu.cmd.status)
2806                 rsp_code = ibmvfc_get_err_result(vhost, &rsp_iu.cmd);
2807
2808         if (rsp_code) {
2809                 if (fc_rsp->flags & FCP_RSP_LEN_VALID)
2810                         rsp_code = fc_rsp->data.info.rsp_code;
2811
2812                 sdev_printk(KERN_ERR, sdev, "Abort failed: %s (%x:%x) "
2813                             "flags: %x fcp_rsp: %x, scsi_status: %x\n",
2814                             ibmvfc_get_cmd_error(be16_to_cpu(rsp_iu.cmd.status), be16_to_cpu(rsp_iu.cmd.error)),
2815                             be16_to_cpu(rsp_iu.cmd.status), be16_to_cpu(rsp_iu.cmd.error), fc_rsp->flags, rsp_code,
2816                             fc_rsp->scsi_status);
2817                 rsp_rc = -EIO;
2818         } else
2819                 sdev_printk(KERN_INFO, sdev, "Abort successful\n");
2820
2821 out:
2822         spin_lock_irqsave(vhost->host->host_lock, flags);
2823         ibmvfc_free_event(evt);
2824         spin_unlock_irqrestore(vhost->host->host_lock, flags);
2825         return rsp_rc;
2826 }
2827
2828 /**
2829  * ibmvfc_eh_abort_handler - Abort a command
2830  * @cmd:        scsi command to abort
2831  *
2832  * Returns:
2833  *      SUCCESS / FAST_IO_FAIL / FAILED
2834  **/
2835 static int ibmvfc_eh_abort_handler(struct scsi_cmnd *cmd)
2836 {
2837         struct scsi_device *sdev = cmd->device;
2838         struct ibmvfc_host *vhost = shost_priv(sdev->host);
2839         int cancel_rc, block_rc;
2840         int rc = FAILED;
2841
2842         ENTER;
2843         block_rc = fc_block_scsi_eh(cmd);
2844         ibmvfc_wait_while_resetting(vhost);
2845         if (block_rc != FAST_IO_FAIL) {
2846                 cancel_rc = ibmvfc_cancel_all(sdev, IBMVFC_TMF_ABORT_TASK_SET);
2847                 ibmvfc_abort_task_set(sdev);
2848         } else
2849                 cancel_rc = ibmvfc_cancel_all(sdev, IBMVFC_TMF_SUPPRESS_ABTS);
2850
2851         if (!cancel_rc)
2852                 rc = ibmvfc_wait_for_ops(vhost, sdev, ibmvfc_match_lun);
2853
2854         if (block_rc == FAST_IO_FAIL && rc != FAILED)
2855                 rc = FAST_IO_FAIL;
2856
2857         LEAVE;
2858         return rc;
2859 }
2860
2861 /**
2862  * ibmvfc_eh_device_reset_handler - Reset a single LUN
2863  * @cmd:        scsi command struct
2864  *
2865  * Returns:
2866  *      SUCCESS / FAST_IO_FAIL / FAILED
2867  **/
2868 static int ibmvfc_eh_device_reset_handler(struct scsi_cmnd *cmd)
2869 {
2870         struct scsi_device *sdev = cmd->device;
2871         struct ibmvfc_host *vhost = shost_priv(sdev->host);
2872         int cancel_rc, block_rc, reset_rc = 0;
2873         int rc = FAILED;
2874
2875         ENTER;
2876         block_rc = fc_block_scsi_eh(cmd);
2877         ibmvfc_wait_while_resetting(vhost);
2878         if (block_rc != FAST_IO_FAIL) {
2879                 cancel_rc = ibmvfc_cancel_all(sdev, IBMVFC_TMF_LUN_RESET);
2880                 reset_rc = ibmvfc_reset_device(sdev, IBMVFC_LUN_RESET, "LUN");
2881         } else
2882                 cancel_rc = ibmvfc_cancel_all(sdev, IBMVFC_TMF_SUPPRESS_ABTS);
2883
2884         if (!cancel_rc && !reset_rc)
2885                 rc = ibmvfc_wait_for_ops(vhost, sdev, ibmvfc_match_lun);
2886
2887         if (block_rc == FAST_IO_FAIL && rc != FAILED)
2888                 rc = FAST_IO_FAIL;
2889
2890         LEAVE;
2891         return rc;
2892 }
2893
2894 /**
2895  * ibmvfc_dev_cancel_all_noreset - Device iterated cancel all function
2896  * @sdev:       scsi device struct
2897  * @data:       return code
2898  *
2899  **/
2900 static void ibmvfc_dev_cancel_all_noreset(struct scsi_device *sdev, void *data)
2901 {
2902         unsigned long *rc = data;
2903         *rc |= ibmvfc_cancel_all(sdev, IBMVFC_TMF_SUPPRESS_ABTS);
2904 }
2905
2906 /**
2907  * ibmvfc_dev_cancel_all_reset - Device iterated cancel all function
2908  * @sdev:       scsi device struct
2909  * @data:       return code
2910  *
2911  **/
2912 static void ibmvfc_dev_cancel_all_reset(struct scsi_device *sdev, void *data)
2913 {
2914         unsigned long *rc = data;
2915         *rc |= ibmvfc_cancel_all(sdev, IBMVFC_TMF_TGT_RESET);
2916 }
2917
2918 /**
2919  * ibmvfc_eh_target_reset_handler - Reset the target
2920  * @cmd:        scsi command struct
2921  *
2922  * Returns:
2923  *      SUCCESS / FAST_IO_FAIL / FAILED
2924  **/
2925 static int ibmvfc_eh_target_reset_handler(struct scsi_cmnd *cmd)
2926 {
2927         struct scsi_device *sdev = cmd->device;
2928         struct ibmvfc_host *vhost = shost_priv(sdev->host);
2929         struct scsi_target *starget = scsi_target(sdev);
2930         int block_rc;
2931         int reset_rc = 0;
2932         int rc = FAILED;
2933         unsigned long cancel_rc = 0;
2934
2935         ENTER;
2936         block_rc = fc_block_scsi_eh(cmd);
2937         ibmvfc_wait_while_resetting(vhost);
2938         if (block_rc != FAST_IO_FAIL) {
2939                 starget_for_each_device(starget, &cancel_rc, ibmvfc_dev_cancel_all_reset);
2940                 reset_rc = ibmvfc_reset_device(sdev, IBMVFC_TARGET_RESET, "target");
2941         } else
2942                 starget_for_each_device(starget, &cancel_rc, ibmvfc_dev_cancel_all_noreset);
2943
2944         if (!cancel_rc && !reset_rc)
2945                 rc = ibmvfc_wait_for_ops(vhost, starget, ibmvfc_match_target);
2946
2947         if (block_rc == FAST_IO_FAIL && rc != FAILED)
2948                 rc = FAST_IO_FAIL;
2949
2950         LEAVE;
2951         return rc;
2952 }
2953
2954 /**
2955  * ibmvfc_eh_host_reset_handler - Reset the connection to the server
2956  * @cmd:        struct scsi_cmnd having problems
2957  *
2958  **/
2959 static int ibmvfc_eh_host_reset_handler(struct scsi_cmnd *cmd)
2960 {
2961         int rc;
2962         struct ibmvfc_host *vhost = shost_priv(cmd->device->host);
2963
2964         dev_err(vhost->dev, "Resetting connection due to error recovery\n");
2965         rc = ibmvfc_issue_fc_host_lip(vhost->host);
2966
2967         return rc ? FAILED : SUCCESS;
2968 }
2969
2970 /**
2971  * ibmvfc_terminate_rport_io - Terminate all pending I/O to the rport.
2972  * @rport:              rport struct
2973  *
2974  * Return value:
2975  *      none
2976  **/
2977 static void ibmvfc_terminate_rport_io(struct fc_rport *rport)
2978 {
2979         struct Scsi_Host *shost = rport_to_shost(rport);
2980         struct ibmvfc_host *vhost = shost_priv(shost);
2981         struct fc_rport *dev_rport;
2982         struct scsi_device *sdev;
2983         struct ibmvfc_target *tgt;
2984         unsigned long rc, flags;
2985         unsigned int found;
2986
2987         ENTER;
2988         shost_for_each_device(sdev, shost) {
2989                 dev_rport = starget_to_rport(scsi_target(sdev));
2990                 if (dev_rport != rport)
2991                         continue;
2992                 ibmvfc_cancel_all(sdev, IBMVFC_TMF_SUPPRESS_ABTS);
2993         }
2994
2995         rc = ibmvfc_wait_for_ops(vhost, rport, ibmvfc_match_rport);
2996
2997         if (rc == FAILED)
2998                 ibmvfc_issue_fc_host_lip(shost);
2999
3000         spin_lock_irqsave(shost->host_lock, flags);
3001         found = 0;
3002         list_for_each_entry(tgt, &vhost->targets, queue) {
3003                 if (tgt->scsi_id == rport->port_id) {
3004                         found++;
3005                         break;
3006                 }
3007         }
3008
3009         if (found && tgt->action == IBMVFC_TGT_ACTION_LOGOUT_DELETED_RPORT) {
3010                 /*
3011                  * If we get here, that means we previously attempted to send
3012                  * an implicit logout to the target but it failed, most likely
3013                  * due to I/O being pending, so we need to send it again
3014                  */
3015                 ibmvfc_del_tgt(tgt);
3016                 ibmvfc_reinit_host(vhost);
3017         }
3018
3019         spin_unlock_irqrestore(shost->host_lock, flags);
3020         LEAVE;
3021 }
3022
3023 static const struct ibmvfc_async_desc ae_desc [] = {
3024         { "PLOGI",      IBMVFC_AE_ELS_PLOGI,    IBMVFC_DEFAULT_LOG_LEVEL + 1 },
3025         { "LOGO",       IBMVFC_AE_ELS_LOGO,     IBMVFC_DEFAULT_LOG_LEVEL + 1 },
3026         { "PRLO",       IBMVFC_AE_ELS_PRLO,     IBMVFC_DEFAULT_LOG_LEVEL + 1 },
3027         { "N-Port SCN", IBMVFC_AE_SCN_NPORT,    IBMVFC_DEFAULT_LOG_LEVEL + 1 },
3028         { "Group SCN",  IBMVFC_AE_SCN_GROUP,    IBMVFC_DEFAULT_LOG_LEVEL + 1 },
3029         { "Domain SCN", IBMVFC_AE_SCN_DOMAIN,   IBMVFC_DEFAULT_LOG_LEVEL },
3030         { "Fabric SCN", IBMVFC_AE_SCN_FABRIC,   IBMVFC_DEFAULT_LOG_LEVEL },
3031         { "Link Up",    IBMVFC_AE_LINK_UP,      IBMVFC_DEFAULT_LOG_LEVEL },
3032         { "Link Down",  IBMVFC_AE_LINK_DOWN,    IBMVFC_DEFAULT_LOG_LEVEL },
3033         { "Link Dead",  IBMVFC_AE_LINK_DEAD,    IBMVFC_DEFAULT_LOG_LEVEL },
3034         { "Halt",       IBMVFC_AE_HALT,         IBMVFC_DEFAULT_LOG_LEVEL },
3035         { "Resume",     IBMVFC_AE_RESUME,       IBMVFC_DEFAULT_LOG_LEVEL },
3036         { "Adapter Failed", IBMVFC_AE_ADAPTER_FAILED, IBMVFC_DEFAULT_LOG_LEVEL },
3037 };
3038
3039 static const struct ibmvfc_async_desc unknown_ae = {
3040         "Unknown async", 0, IBMVFC_DEFAULT_LOG_LEVEL
3041 };
3042
3043 /**
3044  * ibmvfc_get_ae_desc - Get text description for async event
3045  * @ae: async event
3046  *
3047  **/
3048 static const struct ibmvfc_async_desc *ibmvfc_get_ae_desc(u64 ae)
3049 {
3050         int i;
3051
3052         for (i = 0; i < ARRAY_SIZE(ae_desc); i++)
3053                 if (ae_desc[i].ae == ae)
3054                         return &ae_desc[i];
3055
3056         return &unknown_ae;
3057 }
3058
3059 static const struct {
3060         enum ibmvfc_ae_link_state state;
3061         const char *desc;
3062 } link_desc [] = {
3063         { IBMVFC_AE_LS_LINK_UP,         " link up" },
3064         { IBMVFC_AE_LS_LINK_BOUNCED,    " link bounced" },
3065         { IBMVFC_AE_LS_LINK_DOWN,       " link down" },
3066         { IBMVFC_AE_LS_LINK_DEAD,       " link dead" },
3067 };
3068
3069 /**
3070  * ibmvfc_get_link_state - Get text description for link state
3071  * @state:      link state
3072  *
3073  **/
3074 static const char *ibmvfc_get_link_state(enum ibmvfc_ae_link_state state)
3075 {
3076         int i;
3077
3078         for (i = 0; i < ARRAY_SIZE(link_desc); i++)
3079                 if (link_desc[i].state == state)
3080                         return link_desc[i].desc;
3081
3082         return "";
3083 }
3084
3085 /**
3086  * ibmvfc_handle_async - Handle an async event from the adapter
3087  * @crq:        crq to process
3088  * @vhost:      ibmvfc host struct
3089  *
3090  **/
3091 static void ibmvfc_handle_async(struct ibmvfc_async_crq *crq,
3092                                 struct ibmvfc_host *vhost)
3093 {
3094         const struct ibmvfc_async_desc *desc = ibmvfc_get_ae_desc(be64_to_cpu(crq->event));
3095         struct ibmvfc_target *tgt;
3096
3097         ibmvfc_log(vhost, desc->log_level, "%s event received. scsi_id: %llx, wwpn: %llx,"
3098                    " node_name: %llx%s\n", desc->desc, be64_to_cpu(crq->scsi_id),
3099                    be64_to_cpu(crq->wwpn), be64_to_cpu(crq->node_name),
3100                    ibmvfc_get_link_state(crq->link_state));
3101
3102         switch (be64_to_cpu(crq->event)) {
3103         case IBMVFC_AE_RESUME:
3104                 switch (crq->link_state) {
3105                 case IBMVFC_AE_LS_LINK_DOWN:
3106                         ibmvfc_link_down(vhost, IBMVFC_LINK_DOWN);
3107                         break;
3108                 case IBMVFC_AE_LS_LINK_DEAD:
3109                         ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
3110                         break;
3111                 case IBMVFC_AE_LS_LINK_UP:
3112                 case IBMVFC_AE_LS_LINK_BOUNCED:
3113                 default:
3114                         vhost->events_to_log |= IBMVFC_AE_LINKUP;
3115                         vhost->delay_init = 1;
3116                         __ibmvfc_reset_host(vhost);
3117                         break;
3118                 }
3119
3120                 break;
3121         case IBMVFC_AE_LINK_UP:
3122                 vhost->events_to_log |= IBMVFC_AE_LINKUP;
3123                 vhost->delay_init = 1;
3124                 __ibmvfc_reset_host(vhost);
3125                 break;
3126         case IBMVFC_AE_SCN_FABRIC:
3127         case IBMVFC_AE_SCN_DOMAIN:
3128                 vhost->events_to_log |= IBMVFC_AE_RSCN;
3129                 if (vhost->state < IBMVFC_HALTED) {
3130                         vhost->delay_init = 1;
3131                         __ibmvfc_reset_host(vhost);
3132                 }
3133                 break;
3134         case IBMVFC_AE_SCN_NPORT:
3135         case IBMVFC_AE_SCN_GROUP:
3136                 vhost->events_to_log |= IBMVFC_AE_RSCN;
3137                 ibmvfc_reinit_host(vhost);
3138                 break;
3139         case IBMVFC_AE_ELS_LOGO:
3140         case IBMVFC_AE_ELS_PRLO:
3141         case IBMVFC_AE_ELS_PLOGI:
3142                 list_for_each_entry(tgt, &vhost->targets, queue) {
3143                         if (!crq->scsi_id && !crq->wwpn && !crq->node_name)
3144                                 break;
3145                         if (crq->scsi_id && cpu_to_be64(tgt->scsi_id) != crq->scsi_id)
3146                                 continue;
3147                         if (crq->wwpn && cpu_to_be64(tgt->ids.port_name) != crq->wwpn)
3148                                 continue;
3149                         if (crq->node_name && cpu_to_be64(tgt->ids.node_name) != crq->node_name)
3150                                 continue;
3151                         if (tgt->need_login && be64_to_cpu(crq->event) == IBMVFC_AE_ELS_LOGO)
3152                                 tgt->logo_rcvd = 1;
3153                         if (!tgt->need_login || be64_to_cpu(crq->event) == IBMVFC_AE_ELS_PLOGI) {
3154                                 ibmvfc_del_tgt(tgt);
3155                                 ibmvfc_reinit_host(vhost);
3156                         }
3157                 }
3158                 break;
3159         case IBMVFC_AE_LINK_DOWN:
3160         case IBMVFC_AE_ADAPTER_FAILED:
3161                 ibmvfc_link_down(vhost, IBMVFC_LINK_DOWN);
3162                 break;
3163         case IBMVFC_AE_LINK_DEAD:
3164                 ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
3165                 break;
3166         case IBMVFC_AE_HALT:
3167                 ibmvfc_link_down(vhost, IBMVFC_HALTED);
3168                 break;
3169         default:
3170                 dev_err(vhost->dev, "Unknown async event received: %lld\n", crq->event);
3171                 break;
3172         }
3173 }
3174
3175 /**
3176  * ibmvfc_handle_crq - Handles and frees received events in the CRQ
3177  * @crq:        Command/Response queue
3178  * @vhost:      ibmvfc host struct
3179  *
3180  **/
3181 static void ibmvfc_handle_crq(struct ibmvfc_crq *crq, struct ibmvfc_host *vhost,
3182                               struct list_head *evt_doneq)
3183 {
3184         long rc;
3185         struct ibmvfc_event *evt = (struct ibmvfc_event *)be64_to_cpu(crq->ioba);
3186
3187         switch (crq->valid) {
3188         case IBMVFC_CRQ_INIT_RSP:
3189                 switch (crq->format) {
3190                 case IBMVFC_CRQ_INIT:
3191                         dev_info(vhost->dev, "Partner initialized\n");
3192                         /* Send back a response */
3193                         rc = ibmvfc_send_crq_init_complete(vhost);
3194                         if (rc == 0)
3195                                 ibmvfc_init_host(vhost);
3196                         else
3197                                 dev_err(vhost->dev, "Unable to send init rsp. rc=%ld\n", rc);
3198                         break;
3199                 case IBMVFC_CRQ_INIT_COMPLETE:
3200                         dev_info(vhost->dev, "Partner initialization complete\n");
3201                         ibmvfc_init_host(vhost);
3202                         break;
3203                 default:
3204                         dev_err(vhost->dev, "Unknown crq message type: %d\n", crq->format);
3205                 }
3206                 return;
3207         case IBMVFC_CRQ_XPORT_EVENT:
3208                 vhost->state = IBMVFC_NO_CRQ;
3209                 vhost->logged_in = 0;
3210                 ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_NONE);
3211                 if (crq->format == IBMVFC_PARTITION_MIGRATED) {
3212                         /* We need to re-setup the interpartition connection */
3213                         dev_info(vhost->dev, "Partition migrated, Re-enabling adapter\n");
3214                         vhost->client_migrated = 1;
3215                         ibmvfc_purge_requests(vhost, DID_REQUEUE);
3216                         ibmvfc_link_down(vhost, IBMVFC_LINK_DOWN);
3217                         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_REENABLE);
3218                 } else if (crq->format == IBMVFC_PARTNER_FAILED || crq->format == IBMVFC_PARTNER_DEREGISTER) {
3219                         dev_err(vhost->dev, "Host partner adapter deregistered or failed (rc=%d)\n", crq->format);
3220                         ibmvfc_purge_requests(vhost, DID_ERROR);
3221                         ibmvfc_link_down(vhost, IBMVFC_LINK_DOWN);
3222                         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_RESET);
3223                 } else {
3224                         dev_err(vhost->dev, "Received unknown transport event from partner (rc=%d)\n", crq->format);
3225                 }
3226                 return;
3227         case IBMVFC_CRQ_CMD_RSP:
3228                 break;
3229         default:
3230                 dev_err(vhost->dev, "Got an invalid message type 0x%02x\n", crq->valid);
3231                 return;
3232         }
3233
3234         if (crq->format == IBMVFC_ASYNC_EVENT)
3235                 return;
3236
3237         /* The only kind of payload CRQs we should get are responses to
3238          * things we send. Make sure this response is to something we
3239          * actually sent
3240          */
3241         if (unlikely(!ibmvfc_valid_event(&vhost->crq.evt_pool, evt))) {
3242                 dev_err(vhost->dev, "Returned correlation_token 0x%08llx is invalid!\n",
3243                         crq->ioba);
3244                 return;
3245         }
3246
3247         if (unlikely(atomic_read(&evt->free))) {
3248                 dev_err(vhost->dev, "Received duplicate correlation_token 0x%08llx!\n",
3249                         crq->ioba);
3250                 return;
3251         }
3252
3253         spin_lock(&evt->queue->l_lock);
3254         list_move_tail(&evt->queue_list, evt_doneq);
3255         spin_unlock(&evt->queue->l_lock);
3256 }
3257
3258 /**
3259  * ibmvfc_scan_finished - Check if the device scan is done.
3260  * @shost:      scsi host struct
3261  * @time:       current elapsed time
3262  *
3263  * Returns:
3264  *      0 if scan is not done / 1 if scan is done
3265  **/
3266 static int ibmvfc_scan_finished(struct Scsi_Host *shost, unsigned long time)
3267 {
3268         unsigned long flags;
3269         struct ibmvfc_host *vhost = shost_priv(shost);
3270         int done = 0;
3271
3272         spin_lock_irqsave(shost->host_lock, flags);
3273         if (time >= (init_timeout * HZ)) {
3274                 dev_info(vhost->dev, "Scan taking longer than %d seconds, "
3275                          "continuing initialization\n", init_timeout);
3276                 done = 1;
3277         }
3278
3279         if (vhost->scan_complete)
3280                 done = 1;
3281         spin_unlock_irqrestore(shost->host_lock, flags);
3282         return done;
3283 }
3284
3285 /**
3286  * ibmvfc_slave_alloc - Setup the device's task set value
3287  * @sdev:       struct scsi_device device to configure
3288  *
3289  * Set the device's task set value so that error handling works as
3290  * expected.
3291  *
3292  * Returns:
3293  *      0 on success / -ENXIO if device does not exist
3294  **/
3295 static int ibmvfc_slave_alloc(struct scsi_device *sdev)
3296 {
3297         struct Scsi_Host *shost = sdev->host;
3298         struct fc_rport *rport = starget_to_rport(scsi_target(sdev));
3299         struct ibmvfc_host *vhost = shost_priv(shost);
3300         unsigned long flags = 0;
3301
3302         if (!rport || fc_remote_port_chkready(rport))
3303                 return -ENXIO;
3304
3305         spin_lock_irqsave(shost->host_lock, flags);
3306         sdev->hostdata = (void *)(unsigned long)vhost->task_set++;
3307         spin_unlock_irqrestore(shost->host_lock, flags);
3308         return 0;
3309 }
3310
3311 /**
3312  * ibmvfc_target_alloc - Setup the target's task set value
3313  * @starget:    struct scsi_target
3314  *
3315  * Set the target's task set value so that error handling works as
3316  * expected.
3317  *
3318  * Returns:
3319  *      0 on success / -ENXIO if device does not exist
3320  **/
3321 static int ibmvfc_target_alloc(struct scsi_target *starget)
3322 {
3323         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
3324         struct ibmvfc_host *vhost = shost_priv(shost);
3325         unsigned long flags = 0;
3326
3327         spin_lock_irqsave(shost->host_lock, flags);
3328         starget->hostdata = (void *)(unsigned long)vhost->task_set++;
3329         spin_unlock_irqrestore(shost->host_lock, flags);
3330         return 0;
3331 }
3332
3333 /**
3334  * ibmvfc_slave_configure - Configure the device
3335  * @sdev:       struct scsi_device device to configure
3336  *
3337  * Enable allow_restart for a device if it is a disk. Adjust the
3338  * queue_depth here also.
3339  *
3340  * Returns:
3341  *      0
3342  **/
3343 static int ibmvfc_slave_configure(struct scsi_device *sdev)
3344 {
3345         struct Scsi_Host *shost = sdev->host;
3346         unsigned long flags = 0;
3347
3348         spin_lock_irqsave(shost->host_lock, flags);
3349         if (sdev->type == TYPE_DISK) {
3350                 sdev->allow_restart = 1;
3351                 blk_queue_rq_timeout(sdev->request_queue, 120 * HZ);
3352         }
3353         spin_unlock_irqrestore(shost->host_lock, flags);
3354         return 0;
3355 }
3356
3357 /**
3358  * ibmvfc_change_queue_depth - Change the device's queue depth
3359  * @sdev:       scsi device struct
3360  * @qdepth:     depth to set
3361  * @reason:     calling context
3362  *
3363  * Return value:
3364  *      actual depth set
3365  **/
3366 static int ibmvfc_change_queue_depth(struct scsi_device *sdev, int qdepth)
3367 {
3368         if (qdepth > IBMVFC_MAX_CMDS_PER_LUN)
3369                 qdepth = IBMVFC_MAX_CMDS_PER_LUN;
3370
3371         return scsi_change_queue_depth(sdev, qdepth);
3372 }
3373
3374 static ssize_t ibmvfc_show_host_partition_name(struct device *dev,
3375                                                  struct device_attribute *attr, char *buf)
3376 {
3377         struct Scsi_Host *shost = class_to_shost(dev);
3378         struct ibmvfc_host *vhost = shost_priv(shost);
3379
3380         return snprintf(buf, PAGE_SIZE, "%s\n",
3381                         vhost->login_buf->resp.partition_name);
3382 }
3383
3384 static ssize_t ibmvfc_show_host_device_name(struct device *dev,
3385                                             struct device_attribute *attr, char *buf)
3386 {
3387         struct Scsi_Host *shost = class_to_shost(dev);
3388         struct ibmvfc_host *vhost = shost_priv(shost);
3389
3390         return snprintf(buf, PAGE_SIZE, "%s\n",
3391                         vhost->login_buf->resp.device_name);
3392 }
3393
3394 static ssize_t ibmvfc_show_host_loc_code(struct device *dev,
3395                                          struct device_attribute *attr, char *buf)
3396 {
3397         struct Scsi_Host *shost = class_to_shost(dev);
3398         struct ibmvfc_host *vhost = shost_priv(shost);
3399
3400         return snprintf(buf, PAGE_SIZE, "%s\n",
3401                         vhost->login_buf->resp.port_loc_code);
3402 }
3403
3404 static ssize_t ibmvfc_show_host_drc_name(struct device *dev,
3405                                          struct device_attribute *attr, char *buf)
3406 {
3407         struct Scsi_Host *shost = class_to_shost(dev);
3408         struct ibmvfc_host *vhost = shost_priv(shost);
3409
3410         return snprintf(buf, PAGE_SIZE, "%s\n",
3411                         vhost->login_buf->resp.drc_name);
3412 }
3413
3414 static ssize_t ibmvfc_show_host_npiv_version(struct device *dev,
3415                                              struct device_attribute *attr, char *buf)
3416 {
3417         struct Scsi_Host *shost = class_to_shost(dev);
3418         struct ibmvfc_host *vhost = shost_priv(shost);
3419         return snprintf(buf, PAGE_SIZE, "%d\n", be32_to_cpu(vhost->login_buf->resp.version));
3420 }
3421
3422 static ssize_t ibmvfc_show_host_capabilities(struct device *dev,
3423                                              struct device_attribute *attr, char *buf)
3424 {
3425         struct Scsi_Host *shost = class_to_shost(dev);
3426         struct ibmvfc_host *vhost = shost_priv(shost);
3427         return snprintf(buf, PAGE_SIZE, "%llx\n", be64_to_cpu(vhost->login_buf->resp.capabilities));
3428 }
3429
3430 /**
3431  * ibmvfc_show_log_level - Show the adapter's error logging level
3432  * @dev:        class device struct
3433  * @buf:        buffer
3434  *
3435  * Return value:
3436  *      number of bytes printed to buffer
3437  **/
3438 static ssize_t ibmvfc_show_log_level(struct device *dev,
3439                                      struct device_attribute *attr, char *buf)
3440 {
3441         struct Scsi_Host *shost = class_to_shost(dev);
3442         struct ibmvfc_host *vhost = shost_priv(shost);
3443         unsigned long flags = 0;
3444         int len;
3445
3446         spin_lock_irqsave(shost->host_lock, flags);
3447         len = snprintf(buf, PAGE_SIZE, "%d\n", vhost->log_level);
3448         spin_unlock_irqrestore(shost->host_lock, flags);
3449         return len;
3450 }
3451
3452 /**
3453  * ibmvfc_store_log_level - Change the adapter's error logging level
3454  * @dev:        class device struct
3455  * @buf:        buffer
3456  *
3457  * Return value:
3458  *      number of bytes printed to buffer
3459  **/
3460 static ssize_t ibmvfc_store_log_level(struct device *dev,
3461                                       struct device_attribute *attr,
3462                                       const char *buf, size_t count)
3463 {
3464         struct Scsi_Host *shost = class_to_shost(dev);
3465         struct ibmvfc_host *vhost = shost_priv(shost);
3466         unsigned long flags = 0;
3467
3468         spin_lock_irqsave(shost->host_lock, flags);
3469         vhost->log_level = simple_strtoul(buf, NULL, 10);
3470         spin_unlock_irqrestore(shost->host_lock, flags);
3471         return strlen(buf);
3472 }
3473
3474 static ssize_t ibmvfc_show_scsi_channels(struct device *dev,
3475                                          struct device_attribute *attr, char *buf)
3476 {
3477         struct Scsi_Host *shost = class_to_shost(dev);
3478         struct ibmvfc_host *vhost = shost_priv(shost);
3479         unsigned long flags = 0;
3480         int len;
3481
3482         spin_lock_irqsave(shost->host_lock, flags);
3483         len = snprintf(buf, PAGE_SIZE, "%d\n", vhost->client_scsi_channels);
3484         spin_unlock_irqrestore(shost->host_lock, flags);
3485         return len;
3486 }
3487
3488 static ssize_t ibmvfc_store_scsi_channels(struct device *dev,
3489                                          struct device_attribute *attr,
3490                                          const char *buf, size_t count)
3491 {
3492         struct Scsi_Host *shost = class_to_shost(dev);
3493         struct ibmvfc_host *vhost = shost_priv(shost);
3494         unsigned long flags = 0;
3495         unsigned int channels;
3496
3497         spin_lock_irqsave(shost->host_lock, flags);
3498         channels = simple_strtoul(buf, NULL, 10);
3499         vhost->client_scsi_channels = min(channels, nr_scsi_hw_queues);
3500         ibmvfc_hard_reset_host(vhost);
3501         spin_unlock_irqrestore(shost->host_lock, flags);
3502         return strlen(buf);
3503 }
3504
3505 static DEVICE_ATTR(partition_name, S_IRUGO, ibmvfc_show_host_partition_name, NULL);
3506 static DEVICE_ATTR(device_name, S_IRUGO, ibmvfc_show_host_device_name, NULL);
3507 static DEVICE_ATTR(port_loc_code, S_IRUGO, ibmvfc_show_host_loc_code, NULL);
3508 static DEVICE_ATTR(drc_name, S_IRUGO, ibmvfc_show_host_drc_name, NULL);
3509 static DEVICE_ATTR(npiv_version, S_IRUGO, ibmvfc_show_host_npiv_version, NULL);
3510 static DEVICE_ATTR(capabilities, S_IRUGO, ibmvfc_show_host_capabilities, NULL);
3511 static DEVICE_ATTR(log_level, S_IRUGO | S_IWUSR,
3512                    ibmvfc_show_log_level, ibmvfc_store_log_level);
3513 static DEVICE_ATTR(nr_scsi_channels, S_IRUGO | S_IWUSR,
3514                    ibmvfc_show_scsi_channels, ibmvfc_store_scsi_channels);
3515
3516 #ifdef CONFIG_SCSI_IBMVFC_TRACE
3517 /**
3518  * ibmvfc_read_trace - Dump the adapter trace
3519  * @filp:               open sysfs file
3520  * @kobj:               kobject struct
3521  * @bin_attr:   bin_attribute struct
3522  * @buf:                buffer
3523  * @off:                offset
3524  * @count:              buffer size
3525  *
3526  * Return value:
3527  *      number of bytes printed to buffer
3528  **/
3529 static ssize_t ibmvfc_read_trace(struct file *filp, struct kobject *kobj,
3530                                  struct bin_attribute *bin_attr,
3531                                  char *buf, loff_t off, size_t count)
3532 {
3533         struct device *dev = container_of(kobj, struct device, kobj);
3534         struct Scsi_Host *shost = class_to_shost(dev);
3535         struct ibmvfc_host *vhost = shost_priv(shost);
3536         unsigned long flags = 0;
3537         int size = IBMVFC_TRACE_SIZE;
3538         char *src = (char *)vhost->trace;
3539
3540         if (off > size)
3541                 return 0;
3542         if (off + count > size) {
3543                 size -= off;
3544                 count = size;
3545         }
3546
3547         spin_lock_irqsave(shost->host_lock, flags);
3548         memcpy(buf, &src[off], count);
3549         spin_unlock_irqrestore(shost->host_lock, flags);
3550         return count;
3551 }
3552
3553 static struct bin_attribute ibmvfc_trace_attr = {
3554         .attr = {
3555                 .name = "trace",
3556                 .mode = S_IRUGO,
3557         },
3558         .size = 0,
3559         .read = ibmvfc_read_trace,
3560 };
3561 #endif
3562
3563 static struct device_attribute *ibmvfc_attrs[] = {
3564         &dev_attr_partition_name,
3565         &dev_attr_device_name,
3566         &dev_attr_port_loc_code,
3567         &dev_attr_drc_name,
3568         &dev_attr_npiv_version,
3569         &dev_attr_capabilities,
3570         &dev_attr_log_level,
3571         &dev_attr_nr_scsi_channels,
3572         NULL
3573 };
3574
3575 static struct scsi_host_template driver_template = {
3576         .module = THIS_MODULE,
3577         .name = "IBM POWER Virtual FC Adapter",
3578         .proc_name = IBMVFC_NAME,
3579         .queuecommand = ibmvfc_queuecommand,
3580         .eh_timed_out = fc_eh_timed_out,
3581         .eh_abort_handler = ibmvfc_eh_abort_handler,
3582         .eh_device_reset_handler = ibmvfc_eh_device_reset_handler,
3583         .eh_target_reset_handler = ibmvfc_eh_target_reset_handler,
3584         .eh_host_reset_handler = ibmvfc_eh_host_reset_handler,
3585         .slave_alloc = ibmvfc_slave_alloc,
3586         .slave_configure = ibmvfc_slave_configure,
3587         .target_alloc = ibmvfc_target_alloc,
3588         .scan_finished = ibmvfc_scan_finished,
3589         .change_queue_depth = ibmvfc_change_queue_depth,
3590         .cmd_per_lun = 16,
3591         .can_queue = IBMVFC_MAX_REQUESTS_DEFAULT,
3592         .this_id = -1,
3593         .sg_tablesize = SG_ALL,
3594         .max_sectors = IBMVFC_MAX_SECTORS,
3595         .shost_attrs = ibmvfc_attrs,
3596         .track_queue_depth = 1,
3597         .host_tagset = 1,
3598 };
3599
3600 /**
3601  * ibmvfc_next_async_crq - Returns the next entry in async queue
3602  * @vhost:      ibmvfc host struct
3603  *
3604  * Returns:
3605  *      Pointer to next entry in queue / NULL if empty
3606  **/
3607 static struct ibmvfc_async_crq *ibmvfc_next_async_crq(struct ibmvfc_host *vhost)
3608 {
3609         struct ibmvfc_queue *async_crq = &vhost->async_crq;
3610         struct ibmvfc_async_crq *crq;
3611
3612         crq = &async_crq->msgs.async[async_crq->cur];
3613         if (crq->valid & 0x80) {
3614                 if (++async_crq->cur == async_crq->size)
3615                         async_crq->cur = 0;
3616                 rmb();
3617         } else
3618                 crq = NULL;
3619
3620         return crq;
3621 }
3622
3623 /**
3624  * ibmvfc_next_crq - Returns the next entry in message queue
3625  * @vhost:      ibmvfc host struct
3626  *
3627  * Returns:
3628  *      Pointer to next entry in queue / NULL if empty
3629  **/
3630 static struct ibmvfc_crq *ibmvfc_next_crq(struct ibmvfc_host *vhost)
3631 {
3632         struct ibmvfc_queue *queue = &vhost->crq;
3633         struct ibmvfc_crq *crq;
3634
3635         crq = &queue->msgs.crq[queue->cur];
3636         if (crq->valid & 0x80) {
3637                 if (++queue->cur == queue->size)
3638                         queue->cur = 0;
3639                 rmb();
3640         } else
3641                 crq = NULL;
3642
3643         return crq;
3644 }
3645
3646 /**
3647  * ibmvfc_interrupt - Interrupt handler
3648  * @irq:                number of irq to handle, not used
3649  * @dev_instance: ibmvfc_host that received interrupt
3650  *
3651  * Returns:
3652  *      IRQ_HANDLED
3653  **/
3654 static irqreturn_t ibmvfc_interrupt(int irq, void *dev_instance)
3655 {
3656         struct ibmvfc_host *vhost = (struct ibmvfc_host *)dev_instance;
3657         unsigned long flags;
3658
3659         spin_lock_irqsave(vhost->host->host_lock, flags);
3660         vio_disable_interrupts(to_vio_dev(vhost->dev));
3661         tasklet_schedule(&vhost->tasklet);
3662         spin_unlock_irqrestore(vhost->host->host_lock, flags);
3663         return IRQ_HANDLED;
3664 }
3665
3666 /**
3667  * ibmvfc_tasklet - Interrupt handler tasklet
3668  * @data:               ibmvfc host struct
3669  *
3670  * Returns:
3671  *      Nothing
3672  **/
3673 static void ibmvfc_tasklet(void *data)
3674 {
3675         struct ibmvfc_host *vhost = data;
3676         struct vio_dev *vdev = to_vio_dev(vhost->dev);
3677         struct ibmvfc_crq *crq;
3678         struct ibmvfc_async_crq *async;
3679         struct ibmvfc_event *evt, *temp;
3680         unsigned long flags;
3681         int done = 0;
3682         LIST_HEAD(evt_doneq);
3683
3684         spin_lock_irqsave(vhost->host->host_lock, flags);
3685         spin_lock(vhost->crq.q_lock);
3686         while (!done) {
3687                 /* Pull all the valid messages off the async CRQ */
3688                 while ((async = ibmvfc_next_async_crq(vhost)) != NULL) {
3689                         ibmvfc_handle_async(async, vhost);
3690                         async->valid = 0;
3691                         wmb();
3692                 }
3693
3694                 /* Pull all the valid messages off the CRQ */
3695                 while ((crq = ibmvfc_next_crq(vhost)) != NULL) {
3696                         ibmvfc_handle_crq(crq, vhost, &evt_doneq);
3697                         crq->valid = 0;
3698                         wmb();
3699                 }
3700
3701                 vio_enable_interrupts(vdev);
3702                 if ((async = ibmvfc_next_async_crq(vhost)) != NULL) {
3703                         vio_disable_interrupts(vdev);
3704                         ibmvfc_handle_async(async, vhost);
3705                         async->valid = 0;
3706                         wmb();
3707                 } else if ((crq = ibmvfc_next_crq(vhost)) != NULL) {
3708                         vio_disable_interrupts(vdev);
3709                         ibmvfc_handle_crq(crq, vhost, &evt_doneq);
3710                         crq->valid = 0;
3711                         wmb();
3712                 } else
3713                         done = 1;
3714         }
3715
3716         spin_unlock(vhost->crq.q_lock);
3717         spin_unlock_irqrestore(vhost->host->host_lock, flags);
3718
3719         list_for_each_entry_safe(evt, temp, &evt_doneq, queue_list) {
3720                 del_timer(&evt->timer);
3721                 list_del(&evt->queue_list);
3722                 ibmvfc_trc_end(evt);
3723                 evt->done(evt);
3724         }
3725 }
3726
3727 static int ibmvfc_toggle_scrq_irq(struct ibmvfc_queue *scrq, int enable)
3728 {
3729         struct device *dev = scrq->vhost->dev;
3730         struct vio_dev *vdev = to_vio_dev(dev);
3731         unsigned long rc;
3732         int irq_action = H_ENABLE_VIO_INTERRUPT;
3733
3734         if (!enable)
3735                 irq_action = H_DISABLE_VIO_INTERRUPT;
3736
3737         rc = plpar_hcall_norets(H_VIOCTL, vdev->unit_address, irq_action,
3738                                 scrq->hw_irq, 0, 0);
3739
3740         if (rc)
3741                 dev_err(dev, "Couldn't %s sub-crq[%lu] irq. rc=%ld\n",
3742                         enable ? "enable" : "disable", scrq->hwq_id, rc);
3743
3744         return rc;
3745 }
3746
3747 static void ibmvfc_handle_scrq(struct ibmvfc_crq *crq, struct ibmvfc_host *vhost,
3748                                struct list_head *evt_doneq)
3749 {
3750         struct ibmvfc_event *evt = (struct ibmvfc_event *)be64_to_cpu(crq->ioba);
3751
3752         switch (crq->valid) {
3753         case IBMVFC_CRQ_CMD_RSP:
3754                 break;
3755         case IBMVFC_CRQ_XPORT_EVENT:
3756                 return;
3757         default:
3758                 dev_err(vhost->dev, "Got and invalid message type 0x%02x\n", crq->valid);
3759                 return;
3760         }
3761
3762         /* The only kind of payload CRQs we should get are responses to
3763          * things we send. Make sure this response is to something we
3764          * actually sent
3765          */
3766         if (unlikely(!ibmvfc_valid_event(&evt->queue->evt_pool, evt))) {
3767                 dev_err(vhost->dev, "Returned correlation_token 0x%08llx is invalid!\n",
3768                         crq->ioba);
3769                 return;
3770         }
3771
3772         if (unlikely(atomic_read(&evt->free))) {
3773                 dev_err(vhost->dev, "Received duplicate correlation_token 0x%08llx!\n",
3774                         crq->ioba);
3775                 return;
3776         }
3777
3778         spin_lock(&evt->queue->l_lock);
3779         list_move_tail(&evt->queue_list, evt_doneq);
3780         spin_unlock(&evt->queue->l_lock);
3781 }
3782
3783 static struct ibmvfc_crq *ibmvfc_next_scrq(struct ibmvfc_queue *scrq)
3784 {
3785         struct ibmvfc_crq *crq;
3786
3787         crq = &scrq->msgs.scrq[scrq->cur].crq;
3788         if (crq->valid & 0x80) {
3789                 if (++scrq->cur == scrq->size)
3790                         scrq->cur = 0;
3791                 rmb();
3792         } else
3793                 crq = NULL;
3794
3795         return crq;
3796 }
3797
3798 static void ibmvfc_drain_sub_crq(struct ibmvfc_queue *scrq)
3799 {
3800         struct ibmvfc_crq *crq;
3801         struct ibmvfc_event *evt, *temp;
3802         unsigned long flags;
3803         int done = 0;
3804         LIST_HEAD(evt_doneq);
3805
3806         spin_lock_irqsave(scrq->q_lock, flags);
3807         while (!done) {
3808                 while ((crq = ibmvfc_next_scrq(scrq)) != NULL) {
3809                         ibmvfc_handle_scrq(crq, scrq->vhost, &evt_doneq);
3810                         crq->valid = 0;
3811                         wmb();
3812                 }
3813
3814                 ibmvfc_toggle_scrq_irq(scrq, 1);
3815                 if ((crq = ibmvfc_next_scrq(scrq)) != NULL) {
3816                         ibmvfc_toggle_scrq_irq(scrq, 0);
3817                         ibmvfc_handle_scrq(crq, scrq->vhost, &evt_doneq);
3818                         crq->valid = 0;
3819                         wmb();
3820                 } else
3821                         done = 1;
3822         }
3823         spin_unlock_irqrestore(scrq->q_lock, flags);
3824
3825         list_for_each_entry_safe(evt, temp, &evt_doneq, queue_list) {
3826                 del_timer(&evt->timer);
3827                 list_del(&evt->queue_list);
3828                 ibmvfc_trc_end(evt);
3829                 evt->done(evt);
3830         }
3831 }
3832
3833 static irqreturn_t ibmvfc_interrupt_scsi(int irq, void *scrq_instance)
3834 {
3835         struct ibmvfc_queue *scrq = (struct ibmvfc_queue *)scrq_instance;
3836
3837         ibmvfc_toggle_scrq_irq(scrq, 0);
3838         ibmvfc_drain_sub_crq(scrq);
3839
3840         return IRQ_HANDLED;
3841 }
3842
3843 /**
3844  * ibmvfc_init_tgt - Set the next init job step for the target
3845  * @tgt:                ibmvfc target struct
3846  * @job_step:   job step to perform
3847  *
3848  **/
3849 static void ibmvfc_init_tgt(struct ibmvfc_target *tgt,
3850                             void (*job_step) (struct ibmvfc_target *))
3851 {
3852         if (!ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_INIT))
3853                 tgt->job_step = job_step;
3854         wake_up(&tgt->vhost->work_wait_q);
3855 }
3856
3857 /**
3858  * ibmvfc_retry_tgt_init - Attempt to retry a step in target initialization
3859  * @tgt:                ibmvfc target struct
3860  * @job_step:   initialization job step
3861  *
3862  * Returns: 1 if step will be retried / 0 if not
3863  *
3864  **/
3865 static int ibmvfc_retry_tgt_init(struct ibmvfc_target *tgt,
3866                                   void (*job_step) (struct ibmvfc_target *))
3867 {
3868         if (++tgt->init_retries > IBMVFC_MAX_TGT_INIT_RETRIES) {
3869                 ibmvfc_del_tgt(tgt);
3870                 wake_up(&tgt->vhost->work_wait_q);
3871                 return 0;
3872         } else
3873                 ibmvfc_init_tgt(tgt, job_step);
3874         return 1;
3875 }
3876
3877 /* Defined in FC-LS */
3878 static const struct {
3879         int code;
3880         int retry;
3881         int logged_in;
3882 } prli_rsp [] = {
3883         { 0, 1, 0 },
3884         { 1, 0, 1 },
3885         { 2, 1, 0 },
3886         { 3, 1, 0 },
3887         { 4, 0, 0 },
3888         { 5, 0, 0 },
3889         { 6, 0, 1 },
3890         { 7, 0, 0 },
3891         { 8, 1, 0 },
3892 };
3893
3894 /**
3895  * ibmvfc_get_prli_rsp - Find PRLI response index
3896  * @flags:      PRLI response flags
3897  *
3898  **/
3899 static int ibmvfc_get_prli_rsp(u16 flags)
3900 {
3901         int i;
3902         int code = (flags & 0x0f00) >> 8;
3903
3904         for (i = 0; i < ARRAY_SIZE(prli_rsp); i++)
3905                 if (prli_rsp[i].code == code)
3906                         return i;
3907
3908         return 0;
3909 }
3910
3911 /**
3912  * ibmvfc_tgt_prli_done - Completion handler for Process Login
3913  * @evt:        ibmvfc event struct
3914  *
3915  **/
3916 static void ibmvfc_tgt_prli_done(struct ibmvfc_event *evt)
3917 {
3918         struct ibmvfc_target *tgt = evt->tgt;
3919         struct ibmvfc_host *vhost = evt->vhost;
3920         struct ibmvfc_process_login *rsp = &evt->xfer_iu->prli;
3921         struct ibmvfc_prli_svc_parms *parms = &rsp->parms;
3922         u32 status = be16_to_cpu(rsp->common.status);
3923         int index, level = IBMVFC_DEFAULT_LOG_LEVEL;
3924
3925         vhost->discovery_threads--;
3926         ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_NONE);
3927         switch (status) {
3928         case IBMVFC_MAD_SUCCESS:
3929                 tgt_dbg(tgt, "Process Login succeeded: %X %02X %04X\n",
3930                         parms->type, parms->flags, parms->service_parms);
3931
3932                 if (parms->type == IBMVFC_SCSI_FCP_TYPE) {
3933                         index = ibmvfc_get_prli_rsp(be16_to_cpu(parms->flags));
3934                         if (prli_rsp[index].logged_in) {
3935                                 if (be16_to_cpu(parms->flags) & IBMVFC_PRLI_EST_IMG_PAIR) {
3936                                         tgt->need_login = 0;
3937                                         tgt->ids.roles = 0;
3938                                         if (be32_to_cpu(parms->service_parms) & IBMVFC_PRLI_TARGET_FUNC)
3939                                                 tgt->ids.roles |= FC_PORT_ROLE_FCP_TARGET;
3940                                         if (be32_to_cpu(parms->service_parms) & IBMVFC_PRLI_INITIATOR_FUNC)
3941                                                 tgt->ids.roles |= FC_PORT_ROLE_FCP_INITIATOR;
3942                                         tgt->add_rport = 1;
3943                                 } else
3944                                         ibmvfc_del_tgt(tgt);
3945                         } else if (prli_rsp[index].retry)
3946                                 ibmvfc_retry_tgt_init(tgt, ibmvfc_tgt_send_prli);
3947                         else
3948                                 ibmvfc_del_tgt(tgt);
3949                 } else
3950                         ibmvfc_del_tgt(tgt);
3951                 break;
3952         case IBMVFC_MAD_DRIVER_FAILED:
3953                 break;
3954         case IBMVFC_MAD_CRQ_ERROR:
3955                 ibmvfc_retry_tgt_init(tgt, ibmvfc_tgt_send_prli);
3956                 break;
3957         case IBMVFC_MAD_FAILED:
3958         default:
3959                 if ((be16_to_cpu(rsp->status) & IBMVFC_VIOS_FAILURE) &&
3960                      be16_to_cpu(rsp->error) == IBMVFC_PLOGI_REQUIRED)
3961                         level += ibmvfc_retry_tgt_init(tgt, ibmvfc_tgt_send_plogi);
3962                 else if (tgt->logo_rcvd)
3963                         level += ibmvfc_retry_tgt_init(tgt, ibmvfc_tgt_send_plogi);
3964                 else if (ibmvfc_retry_cmd(be16_to_cpu(rsp->status), be16_to_cpu(rsp->error)))
3965                         level += ibmvfc_retry_tgt_init(tgt, ibmvfc_tgt_send_prli);
3966                 else
3967                         ibmvfc_del_tgt(tgt);
3968
3969                 tgt_log(tgt, level, "Process Login failed: %s (%x:%x) rc=0x%02X\n",
3970                         ibmvfc_get_cmd_error(be16_to_cpu(rsp->status), be16_to_cpu(rsp->error)),
3971                         be16_to_cpu(rsp->status), be16_to_cpu(rsp->error), status);
3972                 break;
3973         }
3974
3975         kref_put(&tgt->kref, ibmvfc_release_tgt);
3976         ibmvfc_free_event(evt);
3977         wake_up(&vhost->work_wait_q);
3978 }
3979
3980 /**
3981  * ibmvfc_tgt_send_prli - Send a process login
3982  * @tgt:        ibmvfc target struct
3983  *
3984  **/
3985 static void ibmvfc_tgt_send_prli(struct ibmvfc_target *tgt)
3986 {
3987         struct ibmvfc_process_login *prli;
3988         struct ibmvfc_host *vhost = tgt->vhost;
3989         struct ibmvfc_event *evt;
3990
3991         if (vhost->discovery_threads >= disc_threads)
3992                 return;
3993
3994         kref_get(&tgt->kref);
3995         evt = ibmvfc_get_event(&vhost->crq);
3996         vhost->discovery_threads++;
3997         ibmvfc_init_event(evt, ibmvfc_tgt_prli_done, IBMVFC_MAD_FORMAT);
3998         evt->tgt = tgt;
3999         prli = &evt->iu.prli;
4000         memset(prli, 0, sizeof(*prli));
4001         if (ibmvfc_check_caps(vhost, IBMVFC_HANDLE_VF_WWPN)) {
4002                 prli->common.version = cpu_to_be32(2);
4003                 prli->target_wwpn = cpu_to_be64(tgt->wwpn);
4004         } else {
4005                 prli->common.version = cpu_to_be32(1);
4006         }
4007         prli->common.opcode = cpu_to_be32(IBMVFC_PROCESS_LOGIN);
4008         prli->common.length = cpu_to_be16(sizeof(*prli));
4009         prli->scsi_id = cpu_to_be64(tgt->scsi_id);
4010
4011         prli->parms.type = IBMVFC_SCSI_FCP_TYPE;
4012         prli->parms.flags = cpu_to_be16(IBMVFC_PRLI_EST_IMG_PAIR);
4013         prli->parms.service_parms = cpu_to_be32(IBMVFC_PRLI_INITIATOR_FUNC);
4014         prli->parms.service_parms |= cpu_to_be32(IBMVFC_PRLI_READ_FCP_XFER_RDY_DISABLED);
4015
4016         if (cls3_error)
4017                 prli->parms.service_parms |= cpu_to_be32(IBMVFC_PRLI_RETRY);
4018
4019         ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_INIT_WAIT);
4020         if (ibmvfc_send_event(evt, vhost, default_timeout)) {
4021                 vhost->discovery_threads--;
4022                 ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_NONE);
4023                 kref_put(&tgt->kref, ibmvfc_release_tgt);
4024         } else
4025                 tgt_dbg(tgt, "Sent process login\n");
4026 }
4027
4028 /**
4029  * ibmvfc_tgt_plogi_done - Completion handler for Port Login
4030  * @evt:        ibmvfc event struct
4031  *
4032  **/
4033 static void ibmvfc_tgt_plogi_done(struct ibmvfc_event *evt)
4034 {
4035         struct ibmvfc_target *tgt = evt->tgt;
4036         struct ibmvfc_host *vhost = evt->vhost;
4037         struct ibmvfc_port_login *rsp = &evt->xfer_iu->plogi;
4038         u32 status = be16_to_cpu(rsp->common.status);
4039         int level = IBMVFC_DEFAULT_LOG_LEVEL;
4040
4041         vhost->discovery_threads--;
4042         ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_NONE);
4043         switch (status) {
4044         case IBMVFC_MAD_SUCCESS:
4045                 tgt_dbg(tgt, "Port Login succeeded\n");
4046                 if (tgt->ids.port_name &&
4047                     tgt->ids.port_name != wwn_to_u64(rsp->service_parms.port_name)) {
4048                         vhost->reinit = 1;
4049                         tgt_dbg(tgt, "Port re-init required\n");
4050                         break;
4051                 }
4052                 tgt->ids.node_name = wwn_to_u64(rsp->service_parms.node_name);
4053                 tgt->ids.port_name = wwn_to_u64(rsp->service_parms.port_name);
4054                 tgt->ids.port_id = tgt->scsi_id;
4055                 memcpy(&tgt->service_parms, &rsp->service_parms,
4056                        sizeof(tgt->service_parms));
4057                 memcpy(&tgt->service_parms_change, &rsp->service_parms_change,
4058                        sizeof(tgt->service_parms_change));
4059                 ibmvfc_init_tgt(tgt, ibmvfc_tgt_send_prli);
4060                 break;
4061         case IBMVFC_MAD_DRIVER_FAILED:
4062                 break;
4063         case IBMVFC_MAD_CRQ_ERROR:
4064                 ibmvfc_retry_tgt_init(tgt, ibmvfc_tgt_send_plogi);
4065                 break;
4066         case IBMVFC_MAD_FAILED:
4067         default:
4068                 if (ibmvfc_retry_cmd(be16_to_cpu(rsp->status), be16_to_cpu(rsp->error)))
4069                         level += ibmvfc_retry_tgt_init(tgt, ibmvfc_tgt_send_plogi);
4070                 else
4071                         ibmvfc_del_tgt(tgt);
4072
4073                 tgt_log(tgt, level, "Port Login failed: %s (%x:%x) %s (%x) %s (%x) rc=0x%02X\n",
4074                         ibmvfc_get_cmd_error(be16_to_cpu(rsp->status), be16_to_cpu(rsp->error)),
4075                                              be16_to_cpu(rsp->status), be16_to_cpu(rsp->error),
4076                         ibmvfc_get_fc_type(be16_to_cpu(rsp->fc_type)), be16_to_cpu(rsp->fc_type),
4077                         ibmvfc_get_ls_explain(be16_to_cpu(rsp->fc_explain)), be16_to_cpu(rsp->fc_explain), status);
4078                 break;
4079         }
4080
4081         kref_put(&tgt->kref, ibmvfc_release_tgt);
4082         ibmvfc_free_event(evt);
4083         wake_up(&vhost->work_wait_q);
4084 }
4085
4086 /**
4087  * ibmvfc_tgt_send_plogi - Send PLOGI to the specified target
4088  * @tgt:        ibmvfc target struct
4089  *
4090  **/
4091 static void ibmvfc_tgt_send_plogi(struct ibmvfc_target *tgt)
4092 {
4093         struct ibmvfc_port_login *plogi;
4094         struct ibmvfc_host *vhost = tgt->vhost;
4095         struct ibmvfc_event *evt;
4096
4097         if (vhost->discovery_threads >= disc_threads)
4098                 return;
4099
4100         kref_get(&tgt->kref);
4101         tgt->logo_rcvd = 0;
4102         evt = ibmvfc_get_event(&vhost->crq);
4103         vhost->discovery_threads++;
4104         ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_INIT_WAIT);
4105         ibmvfc_init_event(evt, ibmvfc_tgt_plogi_done, IBMVFC_MAD_FORMAT);
4106         evt->tgt = tgt;
4107         plogi = &evt->iu.plogi;
4108         memset(plogi, 0, sizeof(*plogi));
4109         if (ibmvfc_check_caps(vhost, IBMVFC_HANDLE_VF_WWPN)) {
4110                 plogi->common.version = cpu_to_be32(2);
4111                 plogi->target_wwpn = cpu_to_be64(tgt->wwpn);
4112         } else {
4113                 plogi->common.version = cpu_to_be32(1);
4114         }
4115         plogi->common.opcode = cpu_to_be32(IBMVFC_PORT_LOGIN);
4116         plogi->common.length = cpu_to_be16(sizeof(*plogi));
4117         plogi->scsi_id = cpu_to_be64(tgt->scsi_id);
4118
4119         if (ibmvfc_send_event(evt, vhost, default_timeout)) {
4120                 vhost->discovery_threads--;
4121                 ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_NONE);
4122                 kref_put(&tgt->kref, ibmvfc_release_tgt);
4123         } else
4124                 tgt_dbg(tgt, "Sent port login\n");
4125 }
4126
4127 /**
4128  * ibmvfc_tgt_implicit_logout_done - Completion handler for Implicit Logout MAD
4129  * @evt:        ibmvfc event struct
4130  *
4131  **/
4132 static void ibmvfc_tgt_implicit_logout_done(struct ibmvfc_event *evt)
4133 {
4134         struct ibmvfc_target *tgt = evt->tgt;
4135         struct ibmvfc_host *vhost = evt->vhost;
4136         struct ibmvfc_implicit_logout *rsp = &evt->xfer_iu->implicit_logout;
4137         u32 status = be16_to_cpu(rsp->common.status);
4138
4139         vhost->discovery_threads--;
4140         ibmvfc_free_event(evt);
4141         ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_NONE);
4142
4143         switch (status) {
4144         case IBMVFC_MAD_SUCCESS:
4145                 tgt_dbg(tgt, "Implicit Logout succeeded\n");
4146                 break;
4147         case IBMVFC_MAD_DRIVER_FAILED:
4148                 kref_put(&tgt->kref, ibmvfc_release_tgt);
4149                 wake_up(&vhost->work_wait_q);
4150                 return;
4151         case IBMVFC_MAD_FAILED:
4152         default:
4153                 tgt_err(tgt, "Implicit Logout failed: rc=0x%02X\n", status);
4154                 break;
4155         }
4156
4157         ibmvfc_init_tgt(tgt, ibmvfc_tgt_send_plogi);
4158         kref_put(&tgt->kref, ibmvfc_release_tgt);
4159         wake_up(&vhost->work_wait_q);
4160 }
4161
4162 /**
4163  * __ibmvfc_tgt_get_implicit_logout_evt - Allocate and init an event for implicit logout
4164  * @tgt:                ibmvfc target struct
4165  *
4166  * Returns:
4167  *      Allocated and initialized ibmvfc_event struct
4168  **/
4169 static struct ibmvfc_event *__ibmvfc_tgt_get_implicit_logout_evt(struct ibmvfc_target *tgt,
4170                                                                  void (*done) (struct ibmvfc_event *))
4171 {
4172         struct ibmvfc_implicit_logout *mad;
4173         struct ibmvfc_host *vhost = tgt->vhost;
4174         struct ibmvfc_event *evt;
4175
4176         kref_get(&tgt->kref);
4177         evt = ibmvfc_get_event(&vhost->crq);
4178         ibmvfc_init_event(evt, done, IBMVFC_MAD_FORMAT);
4179         evt->tgt = tgt;
4180         mad = &evt->iu.implicit_logout;
4181         memset(mad, 0, sizeof(*mad));
4182         mad->common.version = cpu_to_be32(1);
4183         mad->common.opcode = cpu_to_be32(IBMVFC_IMPLICIT_LOGOUT);
4184         mad->common.length = cpu_to_be16(sizeof(*mad));
4185         mad->old_scsi_id = cpu_to_be64(tgt->scsi_id);
4186         return evt;
4187 }
4188
4189 /**
4190  * ibmvfc_tgt_implicit_logout - Initiate an Implicit Logout for specified target
4191  * @tgt:                ibmvfc target struct
4192  *
4193  **/
4194 static void ibmvfc_tgt_implicit_logout(struct ibmvfc_target *tgt)
4195 {
4196         struct ibmvfc_host *vhost = tgt->vhost;
4197         struct ibmvfc_event *evt;
4198
4199         if (vhost->discovery_threads >= disc_threads)
4200                 return;
4201
4202         vhost->discovery_threads++;
4203         evt = __ibmvfc_tgt_get_implicit_logout_evt(tgt,
4204                                                    ibmvfc_tgt_implicit_logout_done);
4205
4206         ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_INIT_WAIT);
4207         if (ibmvfc_send_event(evt, vhost, default_timeout)) {
4208                 vhost->discovery_threads--;
4209                 ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_NONE);
4210                 kref_put(&tgt->kref, ibmvfc_release_tgt);
4211         } else
4212                 tgt_dbg(tgt, "Sent Implicit Logout\n");
4213 }
4214
4215 /**
4216  * ibmvfc_tgt_implicit_logout_and_del_done - Completion handler for Implicit Logout MAD
4217  * @evt:        ibmvfc event struct
4218  *
4219  **/
4220 static void ibmvfc_tgt_implicit_logout_and_del_done(struct ibmvfc_event *evt)
4221 {
4222         struct ibmvfc_target *tgt = evt->tgt;
4223         struct ibmvfc_host *vhost = evt->vhost;
4224         struct ibmvfc_passthru_mad *mad = &evt->xfer_iu->passthru;
4225         u32 status = be16_to_cpu(mad->common.status);
4226
4227         vhost->discovery_threads--;
4228         ibmvfc_free_event(evt);
4229
4230         /*
4231          * If our state is IBMVFC_HOST_OFFLINE, we could be unloading the
4232          * driver in which case we need to free up all the targets. If we are
4233          * not unloading, we will still go through a hard reset to get out of
4234          * offline state, so there is no need to track the old targets in that
4235          * case.
4236          */
4237         if (status == IBMVFC_MAD_SUCCESS || vhost->state == IBMVFC_HOST_OFFLINE)
4238                 ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_DEL_RPORT);
4239         else
4240                 ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_DEL_AND_LOGOUT_RPORT);
4241
4242         tgt_dbg(tgt, "Implicit Logout %s\n", (status == IBMVFC_MAD_SUCCESS) ? "succeeded" : "failed");
4243         kref_put(&tgt->kref, ibmvfc_release_tgt);
4244         wake_up(&vhost->work_wait_q);
4245 }
4246
4247 /**
4248  * ibmvfc_tgt_implicit_logout_and_del - Initiate an Implicit Logout for specified target
4249  * @tgt:                ibmvfc target struct
4250  *
4251  **/
4252 static void ibmvfc_tgt_implicit_logout_and_del(struct ibmvfc_target *tgt)
4253 {
4254         struct ibmvfc_host *vhost = tgt->vhost;
4255         struct ibmvfc_event *evt;
4256
4257         if (!vhost->logged_in) {
4258                 ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_DEL_RPORT);
4259                 return;
4260         }
4261
4262         if (vhost->discovery_threads >= disc_threads)
4263                 return;
4264
4265         vhost->discovery_threads++;
4266         evt = __ibmvfc_tgt_get_implicit_logout_evt(tgt,
4267                                                    ibmvfc_tgt_implicit_logout_and_del_done);
4268
4269         ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_LOGOUT_RPORT_WAIT);
4270         if (ibmvfc_send_event(evt, vhost, default_timeout)) {
4271                 vhost->discovery_threads--;
4272                 ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_DEL_RPORT);
4273                 kref_put(&tgt->kref, ibmvfc_release_tgt);
4274         } else
4275                 tgt_dbg(tgt, "Sent Implicit Logout\n");
4276 }
4277
4278 /**
4279  * ibmvfc_tgt_move_login_done - Completion handler for Move Login
4280  * @evt:        ibmvfc event struct
4281  *
4282  **/
4283 static void ibmvfc_tgt_move_login_done(struct ibmvfc_event *evt)
4284 {
4285         struct ibmvfc_target *tgt = evt->tgt;
4286         struct ibmvfc_host *vhost = evt->vhost;
4287         struct ibmvfc_move_login *rsp = &evt->xfer_iu->move_login;
4288         u32 status = be16_to_cpu(rsp->common.status);
4289         int level = IBMVFC_DEFAULT_LOG_LEVEL;
4290
4291         vhost->discovery_threads--;
4292         ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_NONE);
4293         switch (status) {
4294         case IBMVFC_MAD_SUCCESS:
4295                 tgt_dbg(tgt, "Move Login succeeded for old scsi_id: %llX\n", tgt->old_scsi_id);
4296                 tgt->ids.node_name = wwn_to_u64(rsp->service_parms.node_name);
4297                 tgt->ids.port_name = wwn_to_u64(rsp->service_parms.port_name);
4298                 tgt->ids.port_id = tgt->scsi_id;
4299                 memcpy(&tgt->service_parms, &rsp->service_parms,
4300                        sizeof(tgt->service_parms));
4301                 memcpy(&tgt->service_parms_change, &rsp->service_parms_change,
4302                        sizeof(tgt->service_parms_change));
4303                 ibmvfc_init_tgt(tgt, ibmvfc_tgt_send_prli);
4304                 break;
4305         case IBMVFC_MAD_DRIVER_FAILED:
4306                 break;
4307         case IBMVFC_MAD_CRQ_ERROR:
4308                 ibmvfc_retry_tgt_init(tgt, ibmvfc_tgt_move_login);
4309                 break;
4310         case IBMVFC_MAD_FAILED:
4311         default:
4312                 level += ibmvfc_retry_tgt_init(tgt, ibmvfc_tgt_move_login);
4313
4314                 tgt_log(tgt, level,
4315                         "Move Login failed: old scsi_id: %llX, flags:%x, vios_flags:%x, rc=0x%02X\n",
4316                         tgt->old_scsi_id, be32_to_cpu(rsp->flags), be16_to_cpu(rsp->vios_flags),
4317                         status);
4318                 break;
4319         }
4320
4321         kref_put(&tgt->kref, ibmvfc_release_tgt);
4322         ibmvfc_free_event(evt);
4323         wake_up(&vhost->work_wait_q);
4324 }
4325
4326
4327 /**
4328  * ibmvfc_tgt_move_login - Initiate a move login for specified target
4329  * @tgt:                ibmvfc target struct
4330  *
4331  **/
4332 static void ibmvfc_tgt_move_login(struct ibmvfc_target *tgt)
4333 {
4334         struct ibmvfc_host *vhost = tgt->vhost;
4335         struct ibmvfc_move_login *move;
4336         struct ibmvfc_event *evt;
4337
4338         if (vhost->discovery_threads >= disc_threads)
4339                 return;
4340
4341         kref_get(&tgt->kref);
4342         evt = ibmvfc_get_event(&vhost->crq);
4343         vhost->discovery_threads++;
4344         ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_INIT_WAIT);
4345         ibmvfc_init_event(evt, ibmvfc_tgt_move_login_done, IBMVFC_MAD_FORMAT);
4346         evt->tgt = tgt;
4347         move = &evt->iu.move_login;
4348         memset(move, 0, sizeof(*move));
4349         move->common.version = cpu_to_be32(1);
4350         move->common.opcode = cpu_to_be32(IBMVFC_MOVE_LOGIN);
4351         move->common.length = cpu_to_be16(sizeof(*move));
4352
4353         move->old_scsi_id = cpu_to_be64(tgt->old_scsi_id);
4354         move->new_scsi_id = cpu_to_be64(tgt->scsi_id);
4355         move->wwpn = cpu_to_be64(tgt->wwpn);
4356         move->node_name = cpu_to_be64(tgt->ids.node_name);
4357
4358         if (ibmvfc_send_event(evt, vhost, default_timeout)) {
4359                 vhost->discovery_threads--;
4360                 ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_DEL_RPORT);
4361                 kref_put(&tgt->kref, ibmvfc_release_tgt);
4362         } else
4363                 tgt_dbg(tgt, "Sent Move Login for old scsi_id: %llX\n", tgt->old_scsi_id);
4364 }
4365
4366 /**
4367  * ibmvfc_adisc_needs_plogi - Does device need PLOGI?
4368  * @mad:        ibmvfc passthru mad struct
4369  * @tgt:        ibmvfc target struct
4370  *
4371  * Returns:
4372  *      1 if PLOGI needed / 0 if PLOGI not needed
4373  **/
4374 static int ibmvfc_adisc_needs_plogi(struct ibmvfc_passthru_mad *mad,
4375                                     struct ibmvfc_target *tgt)
4376 {
4377         if (wwn_to_u64((u8 *)&mad->fc_iu.response[2]) != tgt->ids.port_name)
4378                 return 1;
4379         if (wwn_to_u64((u8 *)&mad->fc_iu.response[4]) != tgt->ids.node_name)
4380                 return 1;
4381         if (be32_to_cpu(mad->fc_iu.response[6]) != tgt->scsi_id)
4382                 return 1;
4383         return 0;
4384 }
4385
4386 /**
4387  * ibmvfc_tgt_adisc_done - Completion handler for ADISC
4388  * @evt:        ibmvfc event struct
4389  *
4390  **/
4391 static void ibmvfc_tgt_adisc_done(struct ibmvfc_event *evt)
4392 {
4393         struct ibmvfc_target *tgt = evt->tgt;
4394         struct ibmvfc_host *vhost = evt->vhost;
4395         struct ibmvfc_passthru_mad *mad = &evt->xfer_iu->passthru;
4396         u32 status = be16_to_cpu(mad->common.status);
4397         u8 fc_reason, fc_explain;
4398
4399         vhost->discovery_threads--;
4400         ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_NONE);
4401         del_timer(&tgt->timer);
4402
4403         switch (status) {
4404         case IBMVFC_MAD_SUCCESS:
4405                 tgt_dbg(tgt, "ADISC succeeded\n");
4406                 if (ibmvfc_adisc_needs_plogi(mad, tgt))
4407                         ibmvfc_del_tgt(tgt);
4408                 break;
4409         case IBMVFC_MAD_DRIVER_FAILED:
4410                 break;
4411         case IBMVFC_MAD_FAILED:
4412         default:
4413                 ibmvfc_del_tgt(tgt);
4414                 fc_reason = (be32_to_cpu(mad->fc_iu.response[1]) & 0x00ff0000) >> 16;
4415                 fc_explain = (be32_to_cpu(mad->fc_iu.response[1]) & 0x0000ff00) >> 8;
4416                 tgt_info(tgt, "ADISC failed: %s (%x:%x) %s (%x) %s (%x) rc=0x%02X\n",
4417                          ibmvfc_get_cmd_error(be16_to_cpu(mad->iu.status), be16_to_cpu(mad->iu.error)),
4418                          be16_to_cpu(mad->iu.status), be16_to_cpu(mad->iu.error),
4419                          ibmvfc_get_fc_type(fc_reason), fc_reason,
4420                          ibmvfc_get_ls_explain(fc_explain), fc_explain, status);
4421                 break;
4422         }
4423
4424         kref_put(&tgt->kref, ibmvfc_release_tgt);
4425         ibmvfc_free_event(evt);
4426         wake_up(&vhost->work_wait_q);
4427 }
4428
4429 /**
4430  * ibmvfc_init_passthru - Initialize an event struct for FC passthru
4431  * @evt:                ibmvfc event struct
4432  *
4433  **/
4434 static void ibmvfc_init_passthru(struct ibmvfc_event *evt)
4435 {
4436         struct ibmvfc_passthru_mad *mad = &evt->iu.passthru;
4437
4438         memset(mad, 0, sizeof(*mad));
4439         mad->common.version = cpu_to_be32(1);
4440         mad->common.opcode = cpu_to_be32(IBMVFC_PASSTHRU);
4441         mad->common.length = cpu_to_be16(sizeof(*mad) - sizeof(mad->fc_iu) - sizeof(mad->iu));
4442         mad->cmd_ioba.va = cpu_to_be64((u64)be64_to_cpu(evt->crq.ioba) +
4443                 offsetof(struct ibmvfc_passthru_mad, iu));
4444         mad->cmd_ioba.len = cpu_to_be32(sizeof(mad->iu));
4445         mad->iu.cmd_len = cpu_to_be32(sizeof(mad->fc_iu.payload));
4446         mad->iu.rsp_len = cpu_to_be32(sizeof(mad->fc_iu.response));
4447         mad->iu.cmd.va = cpu_to_be64((u64)be64_to_cpu(evt->crq.ioba) +
4448                 offsetof(struct ibmvfc_passthru_mad, fc_iu) +
4449                 offsetof(struct ibmvfc_passthru_fc_iu, payload));
4450         mad->iu.cmd.len = cpu_to_be32(sizeof(mad->fc_iu.payload));
4451         mad->iu.rsp.va = cpu_to_be64((u64)be64_to_cpu(evt->crq.ioba) +
4452                 offsetof(struct ibmvfc_passthru_mad, fc_iu) +
4453                 offsetof(struct ibmvfc_passthru_fc_iu, response));
4454         mad->iu.rsp.len = cpu_to_be32(sizeof(mad->fc_iu.response));
4455 }
4456
4457 /**
4458  * ibmvfc_tgt_adisc_cancel_done - Completion handler when cancelling an ADISC
4459  * @evt:                ibmvfc event struct
4460  *
4461  * Just cleanup this event struct. Everything else is handled by
4462  * the ADISC completion handler. If the ADISC never actually comes
4463  * back, we still have the timer running on the ADISC event struct
4464  * which will fire and cause the CRQ to get reset.
4465  *
4466  **/
4467 static void ibmvfc_tgt_adisc_cancel_done(struct ibmvfc_event *evt)
4468 {
4469         struct ibmvfc_host *vhost = evt->vhost;
4470         struct ibmvfc_target *tgt = evt->tgt;
4471
4472         tgt_dbg(tgt, "ADISC cancel complete\n");
4473         vhost->abort_threads--;
4474         ibmvfc_free_event(evt);
4475         kref_put(&tgt->kref, ibmvfc_release_tgt);
4476         wake_up(&vhost->work_wait_q);
4477 }
4478
4479 /**
4480  * ibmvfc_adisc_timeout - Handle an ADISC timeout
4481  * @tgt:                ibmvfc target struct
4482  *
4483  * If an ADISC times out, send a cancel. If the cancel times
4484  * out, reset the CRQ. When the ADISC comes back as cancelled,
4485  * log back into the target.
4486  **/
4487 static void ibmvfc_adisc_timeout(struct timer_list *t)
4488 {
4489         struct ibmvfc_target *tgt = from_timer(tgt, t, timer);
4490         struct ibmvfc_host *vhost = tgt->vhost;
4491         struct ibmvfc_event *evt;
4492         struct ibmvfc_tmf *tmf;
4493         unsigned long flags;
4494         int rc;
4495
4496         tgt_dbg(tgt, "ADISC timeout\n");
4497         spin_lock_irqsave(vhost->host->host_lock, flags);
4498         if (vhost->abort_threads >= disc_threads ||
4499             tgt->action != IBMVFC_TGT_ACTION_INIT_WAIT ||
4500             vhost->state != IBMVFC_INITIALIZING ||
4501             vhost->action != IBMVFC_HOST_ACTION_QUERY_TGTS) {
4502                 spin_unlock_irqrestore(vhost->host->host_lock, flags);
4503                 return;
4504         }
4505
4506         vhost->abort_threads++;
4507         kref_get(&tgt->kref);
4508         evt = ibmvfc_get_event(&vhost->crq);
4509         ibmvfc_init_event(evt, ibmvfc_tgt_adisc_cancel_done, IBMVFC_MAD_FORMAT);
4510
4511         evt->tgt = tgt;
4512         tmf = &evt->iu.tmf;
4513         memset(tmf, 0, sizeof(*tmf));
4514         if (ibmvfc_check_caps(vhost, IBMVFC_HANDLE_VF_WWPN)) {
4515                 tmf->common.version = cpu_to_be32(2);
4516                 tmf->target_wwpn = cpu_to_be64(tgt->wwpn);
4517         } else {
4518                 tmf->common.version = cpu_to_be32(1);
4519         }
4520         tmf->common.opcode = cpu_to_be32(IBMVFC_TMF_MAD);
4521         tmf->common.length = cpu_to_be16(sizeof(*tmf));
4522         tmf->scsi_id = cpu_to_be64(tgt->scsi_id);
4523         tmf->cancel_key = cpu_to_be32(tgt->cancel_key);
4524
4525         rc = ibmvfc_send_event(evt, vhost, default_timeout);
4526
4527         if (rc) {
4528                 tgt_err(tgt, "Failed to send cancel event for ADISC. rc=%d\n", rc);
4529                 vhost->abort_threads--;
4530                 kref_put(&tgt->kref, ibmvfc_release_tgt);
4531                 __ibmvfc_reset_host(vhost);
4532         } else
4533                 tgt_dbg(tgt, "Attempting to cancel ADISC\n");
4534         spin_unlock_irqrestore(vhost->host->host_lock, flags);
4535 }
4536
4537 /**
4538  * ibmvfc_tgt_adisc - Initiate an ADISC for specified target
4539  * @tgt:                ibmvfc target struct
4540  *
4541  * When sending an ADISC we end up with two timers running. The
4542  * first timer is the timer in the ibmvfc target struct. If this
4543  * fires, we send a cancel to the target. The second timer is the
4544  * timer on the ibmvfc event for the ADISC, which is longer. If that
4545  * fires, it means the ADISC timed out and our attempt to cancel it
4546  * also failed, so we need to reset the CRQ.
4547  **/
4548 static void ibmvfc_tgt_adisc(struct ibmvfc_target *tgt)
4549 {
4550         struct ibmvfc_passthru_mad *mad;
4551         struct ibmvfc_host *vhost = tgt->vhost;
4552         struct ibmvfc_event *evt;
4553
4554         if (vhost->discovery_threads >= disc_threads)
4555                 return;
4556
4557         kref_get(&tgt->kref);
4558         evt = ibmvfc_get_event(&vhost->crq);
4559         vhost->discovery_threads++;
4560         ibmvfc_init_event(evt, ibmvfc_tgt_adisc_done, IBMVFC_MAD_FORMAT);
4561         evt->tgt = tgt;
4562
4563         ibmvfc_init_passthru(evt);
4564         mad = &evt->iu.passthru;
4565         mad->iu.flags = cpu_to_be32(IBMVFC_FC_ELS);
4566         mad->iu.scsi_id = cpu_to_be64(tgt->scsi_id);
4567         mad->iu.cancel_key = cpu_to_be32(tgt->cancel_key);
4568
4569         mad->fc_iu.payload[0] = cpu_to_be32(IBMVFC_ADISC);
4570         memcpy(&mad->fc_iu.payload[2], &vhost->login_buf->resp.port_name,
4571                sizeof(vhost->login_buf->resp.port_name));
4572         memcpy(&mad->fc_iu.payload[4], &vhost->login_buf->resp.node_name,
4573                sizeof(vhost->login_buf->resp.node_name));
4574         mad->fc_iu.payload[6] = cpu_to_be32(be64_to_cpu(vhost->login_buf->resp.scsi_id) & 0x00ffffff);
4575
4576         if (timer_pending(&tgt->timer))
4577                 mod_timer(&tgt->timer, jiffies + (IBMVFC_ADISC_TIMEOUT * HZ));
4578         else {
4579                 tgt->timer.expires = jiffies + (IBMVFC_ADISC_TIMEOUT * HZ);
4580                 add_timer(&tgt->timer);
4581         }
4582
4583         ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_INIT_WAIT);
4584         if (ibmvfc_send_event(evt, vhost, IBMVFC_ADISC_PLUS_CANCEL_TIMEOUT)) {
4585                 vhost->discovery_threads--;
4586                 del_timer(&tgt->timer);
4587                 ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_NONE);
4588                 kref_put(&tgt->kref, ibmvfc_release_tgt);
4589         } else
4590                 tgt_dbg(tgt, "Sent ADISC\n");
4591 }
4592
4593 /**
4594  * ibmvfc_tgt_query_target_done - Completion handler for Query Target MAD
4595  * @evt:        ibmvfc event struct
4596  *
4597  **/
4598 static void ibmvfc_tgt_query_target_done(struct ibmvfc_event *evt)
4599 {
4600         struct ibmvfc_target *tgt = evt->tgt;
4601         struct ibmvfc_host *vhost = evt->vhost;
4602         struct ibmvfc_query_tgt *rsp = &evt->xfer_iu->query_tgt;
4603         u32 status = be16_to_cpu(rsp->common.status);
4604         int level = IBMVFC_DEFAULT_LOG_LEVEL;
4605
4606         vhost->discovery_threads--;
4607         ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_NONE);
4608         switch (status) {
4609         case IBMVFC_MAD_SUCCESS:
4610                 tgt_dbg(tgt, "Query Target succeeded\n");
4611                 if (be64_to_cpu(rsp->scsi_id) != tgt->scsi_id)
4612                         ibmvfc_del_tgt(tgt);
4613                 else
4614                         ibmvfc_init_tgt(tgt, ibmvfc_tgt_adisc);
4615                 break;
4616         case IBMVFC_MAD_DRIVER_FAILED:
4617                 break;
4618         case IBMVFC_MAD_CRQ_ERROR:
4619                 ibmvfc_retry_tgt_init(tgt, ibmvfc_tgt_query_target);
4620                 break;
4621         case IBMVFC_MAD_FAILED:
4622         default:
4623                 if ((be16_to_cpu(rsp->status) & IBMVFC_FABRIC_MAPPED) == IBMVFC_FABRIC_MAPPED &&
4624                     be16_to_cpu(rsp->error) == IBMVFC_UNABLE_TO_PERFORM_REQ &&
4625                     be16_to_cpu(rsp->fc_explain) == IBMVFC_PORT_NAME_NOT_REG)
4626                         ibmvfc_del_tgt(tgt);
4627                 else if (ibmvfc_retry_cmd(be16_to_cpu(rsp->status), be16_to_cpu(rsp->error)))
4628                         level += ibmvfc_retry_tgt_init(tgt, ibmvfc_tgt_query_target);
4629                 else
4630                         ibmvfc_del_tgt(tgt);
4631
4632                 tgt_log(tgt, level, "Query Target failed: %s (%x:%x) %s (%x) %s (%x) rc=0x%02X\n",
4633                         ibmvfc_get_cmd_error(be16_to_cpu(rsp->status), be16_to_cpu(rsp->error)),
4634                         be16_to_cpu(rsp->status), be16_to_cpu(rsp->error),
4635                         ibmvfc_get_fc_type(be16_to_cpu(rsp->fc_type)), be16_to_cpu(rsp->fc_type),
4636                         ibmvfc_get_gs_explain(be16_to_cpu(rsp->fc_explain)), be16_to_cpu(rsp->fc_explain),
4637                         status);
4638                 break;
4639         }
4640
4641         kref_put(&tgt->kref, ibmvfc_release_tgt);
4642         ibmvfc_free_event(evt);
4643         wake_up(&vhost->work_wait_q);
4644 }
4645
4646 /**
4647  * ibmvfc_tgt_query_target - Initiate a Query Target for specified target
4648  * @tgt:        ibmvfc target struct
4649  *
4650  **/
4651 static void ibmvfc_tgt_query_target(struct ibmvfc_target *tgt)
4652 {
4653         struct ibmvfc_query_tgt *query_tgt;
4654         struct ibmvfc_host *vhost = tgt->vhost;
4655         struct ibmvfc_event *evt;
4656
4657         if (vhost->discovery_threads >= disc_threads)
4658                 return;
4659
4660         kref_get(&tgt->kref);
4661         evt = ibmvfc_get_event(&vhost->crq);
4662         vhost->discovery_threads++;
4663         evt->tgt = tgt;
4664         ibmvfc_init_event(evt, ibmvfc_tgt_query_target_done, IBMVFC_MAD_FORMAT);
4665         query_tgt = &evt->iu.query_tgt;
4666         memset(query_tgt, 0, sizeof(*query_tgt));
4667         query_tgt->common.version = cpu_to_be32(1);
4668         query_tgt->common.opcode = cpu_to_be32(IBMVFC_QUERY_TARGET);
4669         query_tgt->common.length = cpu_to_be16(sizeof(*query_tgt));
4670         query_tgt->wwpn = cpu_to_be64(tgt->ids.port_name);
4671
4672         ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_INIT_WAIT);
4673         if (ibmvfc_send_event(evt, vhost, default_timeout)) {
4674                 vhost->discovery_threads--;
4675                 ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_NONE);
4676                 kref_put(&tgt->kref, ibmvfc_release_tgt);
4677         } else
4678                 tgt_dbg(tgt, "Sent Query Target\n");
4679 }
4680
4681 /**
4682  * ibmvfc_alloc_target - Allocate and initialize an ibmvfc target
4683  * @vhost:              ibmvfc host struct
4684  * @scsi_id:    SCSI ID to allocate target for
4685  *
4686  * Returns:
4687  *      0 on success / other on failure
4688  **/
4689 static int ibmvfc_alloc_target(struct ibmvfc_host *vhost,
4690                                struct ibmvfc_discover_targets_entry *target)
4691 {
4692         struct ibmvfc_target *stgt = NULL;
4693         struct ibmvfc_target *wtgt = NULL;
4694         struct ibmvfc_target *tgt;
4695         unsigned long flags;
4696         u64 scsi_id = be32_to_cpu(target->scsi_id) & IBMVFC_DISC_TGT_SCSI_ID_MASK;
4697         u64 wwpn = be64_to_cpu(target->wwpn);
4698
4699         /* Look to see if we already have a target allocated for this SCSI ID or WWPN */
4700         spin_lock_irqsave(vhost->host->host_lock, flags);
4701         list_for_each_entry(tgt, &vhost->targets, queue) {
4702                 if (tgt->wwpn == wwpn) {
4703                         wtgt = tgt;
4704                         break;
4705                 }
4706         }
4707
4708         list_for_each_entry(tgt, &vhost->targets, queue) {
4709                 if (tgt->scsi_id == scsi_id) {
4710                         stgt = tgt;
4711                         break;
4712                 }
4713         }
4714
4715         if (wtgt && !stgt) {
4716                 /*
4717                  * A WWPN target has moved and we still are tracking the old
4718                  * SCSI ID.  The only way we should be able to get here is if
4719                  * we attempted to send an implicit logout for the old SCSI ID
4720                  * and it failed for some reason, such as there being I/O
4721                  * pending to the target. In this case, we will have already
4722                  * deleted the rport from the FC transport so we do a move
4723                  * login, which works even with I/O pending, as it will cancel
4724                  * any active commands.
4725                  */
4726                 if (wtgt->action == IBMVFC_TGT_ACTION_LOGOUT_DELETED_RPORT) {
4727                         /*
4728                          * Do a move login here. The old target is no longer
4729                          * known to the transport layer We don't use the
4730                          * normal ibmvfc_set_tgt_action to set this, as we
4731                          * don't normally want to allow this state change.
4732                          */
4733                         wtgt->old_scsi_id = wtgt->scsi_id;
4734                         wtgt->scsi_id = scsi_id;
4735                         wtgt->action = IBMVFC_TGT_ACTION_INIT;
4736                         ibmvfc_init_tgt(wtgt, ibmvfc_tgt_move_login);
4737                         goto unlock_out;
4738                 } else {
4739                         tgt_err(wtgt, "Unexpected target state: %d, %p\n",
4740                                 wtgt->action, wtgt->rport);
4741                 }
4742         } else if (stgt) {
4743                 if (tgt->need_login)
4744                         ibmvfc_init_tgt(tgt, ibmvfc_tgt_implicit_logout);
4745                 goto unlock_out;
4746         }
4747         spin_unlock_irqrestore(vhost->host->host_lock, flags);
4748
4749         tgt = mempool_alloc(vhost->tgt_pool, GFP_NOIO);
4750         memset(tgt, 0, sizeof(*tgt));
4751         tgt->scsi_id = scsi_id;
4752         tgt->wwpn = wwpn;
4753         tgt->vhost = vhost;
4754         tgt->need_login = 1;
4755         timer_setup(&tgt->timer, ibmvfc_adisc_timeout, 0);
4756         kref_init(&tgt->kref);
4757         ibmvfc_init_tgt(tgt, ibmvfc_tgt_implicit_logout);
4758         spin_lock_irqsave(vhost->host->host_lock, flags);
4759         tgt->cancel_key = vhost->task_set++;
4760         list_add_tail(&tgt->queue, &vhost->targets);
4761
4762 unlock_out:
4763         spin_unlock_irqrestore(vhost->host->host_lock, flags);
4764         return 0;
4765 }
4766
4767 /**
4768  * ibmvfc_alloc_targets - Allocate and initialize ibmvfc targets
4769  * @vhost:              ibmvfc host struct
4770  *
4771  * Returns:
4772  *      0 on success / other on failure
4773  **/
4774 static int ibmvfc_alloc_targets(struct ibmvfc_host *vhost)
4775 {
4776         int i, rc;
4777
4778         for (i = 0, rc = 0; !rc && i < vhost->num_targets; i++)
4779                 rc = ibmvfc_alloc_target(vhost, &vhost->disc_buf[i]);
4780
4781         return rc;
4782 }
4783
4784 /**
4785  * ibmvfc_discover_targets_done - Completion handler for discover targets MAD
4786  * @evt:        ibmvfc event struct
4787  *
4788  **/
4789 static void ibmvfc_discover_targets_done(struct ibmvfc_event *evt)
4790 {
4791         struct ibmvfc_host *vhost = evt->vhost;
4792         struct ibmvfc_discover_targets *rsp = &evt->xfer_iu->discover_targets;
4793         u32 mad_status = be16_to_cpu(rsp->common.status);
4794         int level = IBMVFC_DEFAULT_LOG_LEVEL;
4795
4796         switch (mad_status) {
4797         case IBMVFC_MAD_SUCCESS:
4798                 ibmvfc_dbg(vhost, "Discover Targets succeeded\n");
4799                 vhost->num_targets = be32_to_cpu(rsp->num_written);
4800                 ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_ALLOC_TGTS);
4801                 break;
4802         case IBMVFC_MAD_FAILED:
4803                 level += ibmvfc_retry_host_init(vhost);
4804                 ibmvfc_log(vhost, level, "Discover Targets failed: %s (%x:%x)\n",
4805                            ibmvfc_get_cmd_error(be16_to_cpu(rsp->status), be16_to_cpu(rsp->error)),
4806                            be16_to_cpu(rsp->status), be16_to_cpu(rsp->error));
4807                 break;
4808         case IBMVFC_MAD_DRIVER_FAILED:
4809                 break;
4810         default:
4811                 dev_err(vhost->dev, "Invalid Discover Targets response: 0x%x\n", mad_status);
4812                 ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
4813                 break;
4814         }
4815
4816         ibmvfc_free_event(evt);
4817         wake_up(&vhost->work_wait_q);
4818 }
4819
4820 /**
4821  * ibmvfc_discover_targets - Send Discover Targets MAD
4822  * @vhost:      ibmvfc host struct
4823  *
4824  **/
4825 static void ibmvfc_discover_targets(struct ibmvfc_host *vhost)
4826 {
4827         struct ibmvfc_discover_targets *mad;
4828         struct ibmvfc_event *evt = ibmvfc_get_event(&vhost->crq);
4829
4830         ibmvfc_init_event(evt, ibmvfc_discover_targets_done, IBMVFC_MAD_FORMAT);
4831         mad = &evt->iu.discover_targets;
4832         memset(mad, 0, sizeof(*mad));
4833         mad->common.version = cpu_to_be32(1);
4834         mad->common.opcode = cpu_to_be32(IBMVFC_DISC_TARGETS);
4835         mad->common.length = cpu_to_be16(sizeof(*mad));
4836         mad->bufflen = cpu_to_be32(vhost->disc_buf_sz);
4837         mad->buffer.va = cpu_to_be64(vhost->disc_buf_dma);
4838         mad->buffer.len = cpu_to_be32(vhost->disc_buf_sz);
4839         mad->flags = cpu_to_be32(IBMVFC_DISC_TGT_PORT_ID_WWPN_LIST);
4840         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_INIT_WAIT);
4841
4842         if (!ibmvfc_send_event(evt, vhost, default_timeout))
4843                 ibmvfc_dbg(vhost, "Sent discover targets\n");
4844         else
4845                 ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
4846 }
4847
4848 static void ibmvfc_channel_setup_done(struct ibmvfc_event *evt)
4849 {
4850         struct ibmvfc_host *vhost = evt->vhost;
4851         struct ibmvfc_channel_setup *setup = vhost->channel_setup_buf;
4852         struct ibmvfc_scsi_channels *scrqs = &vhost->scsi_scrqs;
4853         u32 mad_status = be16_to_cpu(evt->xfer_iu->channel_setup.common.status);
4854         int level = IBMVFC_DEFAULT_LOG_LEVEL;
4855         int flags, active_queues, i;
4856
4857         ibmvfc_free_event(evt);
4858
4859         switch (mad_status) {
4860         case IBMVFC_MAD_SUCCESS:
4861                 ibmvfc_dbg(vhost, "Channel Setup succeeded\n");
4862                 flags = be32_to_cpu(setup->flags);
4863                 vhost->do_enquiry = 0;
4864                 active_queues = be32_to_cpu(setup->num_scsi_subq_channels);
4865                 scrqs->active_queues = active_queues;
4866
4867                 if (flags & IBMVFC_CHANNELS_CANCELED) {
4868                         ibmvfc_dbg(vhost, "Channels Canceled\n");
4869                         vhost->using_channels = 0;
4870                 } else {
4871                         if (active_queues)
4872                                 vhost->using_channels = 1;
4873                         for (i = 0; i < active_queues; i++)
4874                                 scrqs->scrqs[i].vios_cookie =
4875                                         be64_to_cpu(setup->channel_handles[i]);
4876
4877                         ibmvfc_dbg(vhost, "Using %u channels\n",
4878                                    vhost->scsi_scrqs.active_queues);
4879                 }
4880                 break;
4881         case IBMVFC_MAD_FAILED:
4882                 level += ibmvfc_retry_host_init(vhost);
4883                 ibmvfc_log(vhost, level, "Channel Setup failed\n");
4884                 fallthrough;
4885         case IBMVFC_MAD_DRIVER_FAILED:
4886                 return;
4887         default:
4888                 dev_err(vhost->dev, "Invalid Channel Setup response: 0x%x\n",
4889                         mad_status);
4890                 ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
4891                 return;
4892         }
4893
4894         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_QUERY);
4895         wake_up(&vhost->work_wait_q);
4896 }
4897
4898 static void ibmvfc_channel_setup(struct ibmvfc_host *vhost)
4899 {
4900         struct ibmvfc_channel_setup_mad *mad;
4901         struct ibmvfc_channel_setup *setup_buf = vhost->channel_setup_buf;
4902         struct ibmvfc_event *evt = ibmvfc_get_event(&vhost->crq);
4903         struct ibmvfc_scsi_channels *scrqs = &vhost->scsi_scrqs;
4904         unsigned int num_channels =
4905                 min(vhost->client_scsi_channels, vhost->max_vios_scsi_channels);
4906         int i;
4907
4908         memset(setup_buf, 0, sizeof(*setup_buf));
4909         if (num_channels == 0)
4910                 setup_buf->flags = cpu_to_be32(IBMVFC_CANCEL_CHANNELS);
4911         else {
4912                 setup_buf->num_scsi_subq_channels = cpu_to_be32(num_channels);
4913                 for (i = 0; i < num_channels; i++)
4914                         setup_buf->channel_handles[i] = cpu_to_be64(scrqs->scrqs[i].cookie);
4915         }
4916
4917         ibmvfc_init_event(evt, ibmvfc_channel_setup_done, IBMVFC_MAD_FORMAT);
4918         mad = &evt->iu.channel_setup;
4919         memset(mad, 0, sizeof(*mad));
4920         mad->common.version = cpu_to_be32(1);
4921         mad->common.opcode = cpu_to_be32(IBMVFC_CHANNEL_SETUP);
4922         mad->common.length = cpu_to_be16(sizeof(*mad));
4923         mad->buffer.va = cpu_to_be64(vhost->channel_setup_dma);
4924         mad->buffer.len = cpu_to_be32(sizeof(*vhost->channel_setup_buf));
4925
4926         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_INIT_WAIT);
4927
4928         if (!ibmvfc_send_event(evt, vhost, default_timeout))
4929                 ibmvfc_dbg(vhost, "Sent channel setup\n");
4930         else
4931                 ibmvfc_link_down(vhost, IBMVFC_LINK_DOWN);
4932 }
4933
4934 static void ibmvfc_channel_enquiry_done(struct ibmvfc_event *evt)
4935 {
4936         struct ibmvfc_host *vhost = evt->vhost;
4937         struct ibmvfc_channel_enquiry *rsp = &evt->xfer_iu->channel_enquiry;
4938         u32 mad_status = be16_to_cpu(rsp->common.status);
4939         int level = IBMVFC_DEFAULT_LOG_LEVEL;
4940
4941         switch (mad_status) {
4942         case IBMVFC_MAD_SUCCESS:
4943                 ibmvfc_dbg(vhost, "Channel Enquiry succeeded\n");
4944                 vhost->max_vios_scsi_channels = be32_to_cpu(rsp->num_scsi_subq_channels);
4945                 ibmvfc_free_event(evt);
4946                 break;
4947         case IBMVFC_MAD_FAILED:
4948                 level += ibmvfc_retry_host_init(vhost);
4949                 ibmvfc_log(vhost, level, "Channel Enquiry failed\n");
4950                 fallthrough;
4951         case IBMVFC_MAD_DRIVER_FAILED:
4952                 ibmvfc_free_event(evt);
4953                 return;
4954         default:
4955                 dev_err(vhost->dev, "Invalid Channel Enquiry response: 0x%x\n",
4956                         mad_status);
4957                 ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
4958                 ibmvfc_free_event(evt);
4959                 return;
4960         }
4961
4962         ibmvfc_channel_setup(vhost);
4963 }
4964
4965 static void ibmvfc_channel_enquiry(struct ibmvfc_host *vhost)
4966 {
4967         struct ibmvfc_channel_enquiry *mad;
4968         struct ibmvfc_event *evt = ibmvfc_get_event(&vhost->crq);
4969
4970         ibmvfc_init_event(evt, ibmvfc_channel_enquiry_done, IBMVFC_MAD_FORMAT);
4971         mad = &evt->iu.channel_enquiry;
4972         memset(mad, 0, sizeof(*mad));
4973         mad->common.version = cpu_to_be32(1);
4974         mad->common.opcode = cpu_to_be32(IBMVFC_CHANNEL_ENQUIRY);
4975         mad->common.length = cpu_to_be16(sizeof(*mad));
4976
4977         if (mig_channels_only)
4978                 mad->flags |= cpu_to_be32(IBMVFC_NO_CHANNELS_TO_CRQ_SUPPORT);
4979         if (mig_no_less_channels)
4980                 mad->flags |= cpu_to_be32(IBMVFC_NO_N_TO_M_CHANNELS_SUPPORT);
4981
4982         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_INIT_WAIT);
4983
4984         if (!ibmvfc_send_event(evt, vhost, default_timeout))
4985                 ibmvfc_dbg(vhost, "Send channel enquiry\n");
4986         else
4987                 ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
4988 }
4989
4990 /**
4991  * ibmvfc_npiv_login_done - Completion handler for NPIV Login
4992  * @evt:        ibmvfc event struct
4993  *
4994  **/
4995 static void ibmvfc_npiv_login_done(struct ibmvfc_event *evt)
4996 {
4997         struct ibmvfc_host *vhost = evt->vhost;
4998         u32 mad_status = be16_to_cpu(evt->xfer_iu->npiv_login.common.status);
4999         struct ibmvfc_npiv_login_resp *rsp = &vhost->login_buf->resp;
5000         unsigned int npiv_max_sectors;
5001         int level = IBMVFC_DEFAULT_LOG_LEVEL;
5002
5003         switch (mad_status) {
5004         case IBMVFC_MAD_SUCCESS:
5005                 ibmvfc_free_event(evt);
5006                 break;
5007         case IBMVFC_MAD_FAILED:
5008                 if (ibmvfc_retry_cmd(be16_to_cpu(rsp->status), be16_to_cpu(rsp->error)))
5009                         level += ibmvfc_retry_host_init(vhost);
5010                 else
5011                         ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
5012                 ibmvfc_log(vhost, level, "NPIV Login failed: %s (%x:%x)\n",
5013                            ibmvfc_get_cmd_error(be16_to_cpu(rsp->status), be16_to_cpu(rsp->error)),
5014                                                 be16_to_cpu(rsp->status), be16_to_cpu(rsp->error));
5015                 ibmvfc_free_event(evt);
5016                 return;
5017         case IBMVFC_MAD_CRQ_ERROR:
5018                 ibmvfc_retry_host_init(vhost);
5019                 fallthrough;
5020         case IBMVFC_MAD_DRIVER_FAILED:
5021                 ibmvfc_free_event(evt);
5022                 return;
5023         default:
5024                 dev_err(vhost->dev, "Invalid NPIV Login response: 0x%x\n", mad_status);
5025                 ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
5026                 ibmvfc_free_event(evt);
5027                 return;
5028         }
5029
5030         vhost->client_migrated = 0;
5031
5032         if (!(be32_to_cpu(rsp->flags) & IBMVFC_NATIVE_FC)) {
5033                 dev_err(vhost->dev, "Virtual adapter does not support FC. %x\n",
5034                         rsp->flags);
5035                 ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
5036                 wake_up(&vhost->work_wait_q);
5037                 return;
5038         }
5039
5040         if (be32_to_cpu(rsp->max_cmds) <= IBMVFC_NUM_INTERNAL_REQ) {
5041                 dev_err(vhost->dev, "Virtual adapter supported queue depth too small: %d\n",
5042                         rsp->max_cmds);
5043                 ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
5044                 wake_up(&vhost->work_wait_q);
5045                 return;
5046         }
5047
5048         vhost->logged_in = 1;
5049         npiv_max_sectors = min((uint)(be64_to_cpu(rsp->max_dma_len) >> 9), IBMVFC_MAX_SECTORS);
5050         dev_info(vhost->dev, "Host partition: %s, device: %s %s %s max sectors %u\n",
5051                  rsp->partition_name, rsp->device_name, rsp->port_loc_code,
5052                  rsp->drc_name, npiv_max_sectors);
5053
5054         fc_host_fabric_name(vhost->host) = be64_to_cpu(rsp->node_name);
5055         fc_host_node_name(vhost->host) = be64_to_cpu(rsp->node_name);
5056         fc_host_port_name(vhost->host) = be64_to_cpu(rsp->port_name);
5057         fc_host_port_id(vhost->host) = be64_to_cpu(rsp->scsi_id);
5058         fc_host_port_type(vhost->host) = FC_PORTTYPE_NPIV;
5059         fc_host_supported_classes(vhost->host) = 0;
5060         if (be32_to_cpu(rsp->service_parms.class1_parms[0]) & 0x80000000)
5061                 fc_host_supported_classes(vhost->host) |= FC_COS_CLASS1;
5062         if (be32_to_cpu(rsp->service_parms.class2_parms[0]) & 0x80000000)
5063                 fc_host_supported_classes(vhost->host) |= FC_COS_CLASS2;
5064         if (be32_to_cpu(rsp->service_parms.class3_parms[0]) & 0x80000000)
5065                 fc_host_supported_classes(vhost->host) |= FC_COS_CLASS3;
5066         fc_host_maxframe_size(vhost->host) =
5067                 be16_to_cpu(rsp->service_parms.common.bb_rcv_sz) & 0x0fff;
5068
5069         vhost->host->can_queue = be32_to_cpu(rsp->max_cmds) - IBMVFC_NUM_INTERNAL_REQ;
5070         vhost->host->max_sectors = npiv_max_sectors;
5071
5072         if (ibmvfc_check_caps(vhost, IBMVFC_CAN_SUPPORT_CHANNELS) && vhost->do_enquiry) {
5073                 ibmvfc_channel_enquiry(vhost);
5074         } else {
5075                 vhost->do_enquiry = 0;
5076                 ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_QUERY);
5077                 wake_up(&vhost->work_wait_q);
5078         }
5079 }
5080
5081 /**
5082  * ibmvfc_npiv_login - Sends NPIV login
5083  * @vhost:      ibmvfc host struct
5084  *
5085  **/
5086 static void ibmvfc_npiv_login(struct ibmvfc_host *vhost)
5087 {
5088         struct ibmvfc_npiv_login_mad *mad;
5089         struct ibmvfc_event *evt = ibmvfc_get_event(&vhost->crq);
5090
5091         ibmvfc_gather_partition_info(vhost);
5092         ibmvfc_set_login_info(vhost);
5093         ibmvfc_init_event(evt, ibmvfc_npiv_login_done, IBMVFC_MAD_FORMAT);
5094
5095         memcpy(vhost->login_buf, &vhost->login_info, sizeof(vhost->login_info));
5096         mad = &evt->iu.npiv_login;
5097         memset(mad, 0, sizeof(struct ibmvfc_npiv_login_mad));
5098         mad->common.version = cpu_to_be32(1);
5099         mad->common.opcode = cpu_to_be32(IBMVFC_NPIV_LOGIN);
5100         mad->common.length = cpu_to_be16(sizeof(struct ibmvfc_npiv_login_mad));
5101         mad->buffer.va = cpu_to_be64(vhost->login_buf_dma);
5102         mad->buffer.len = cpu_to_be32(sizeof(*vhost->login_buf));
5103
5104         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_INIT_WAIT);
5105
5106         if (!ibmvfc_send_event(evt, vhost, default_timeout))
5107                 ibmvfc_dbg(vhost, "Sent NPIV login\n");
5108         else
5109                 ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
5110 }
5111
5112 /**
5113  * ibmvfc_npiv_logout_done - Completion handler for NPIV Logout
5114  * @vhost:              ibmvfc host struct
5115  *
5116  **/
5117 static void ibmvfc_npiv_logout_done(struct ibmvfc_event *evt)
5118 {
5119         struct ibmvfc_host *vhost = evt->vhost;
5120         u32 mad_status = be16_to_cpu(evt->xfer_iu->npiv_logout.common.status);
5121
5122         ibmvfc_free_event(evt);
5123
5124         switch (mad_status) {
5125         case IBMVFC_MAD_SUCCESS:
5126                 if (list_empty(&vhost->crq.sent) &&
5127                     vhost->action == IBMVFC_HOST_ACTION_LOGO_WAIT) {
5128                         ibmvfc_init_host(vhost);
5129                         return;
5130                 }
5131                 break;
5132         case IBMVFC_MAD_FAILED:
5133         case IBMVFC_MAD_NOT_SUPPORTED:
5134         case IBMVFC_MAD_CRQ_ERROR:
5135         case IBMVFC_MAD_DRIVER_FAILED:
5136         default:
5137                 ibmvfc_dbg(vhost, "NPIV Logout failed. 0x%X\n", mad_status);
5138                 break;
5139         }
5140
5141         ibmvfc_hard_reset_host(vhost);
5142 }
5143
5144 /**
5145  * ibmvfc_npiv_logout - Issue an NPIV Logout
5146  * @vhost:              ibmvfc host struct
5147  *
5148  **/
5149 static void ibmvfc_npiv_logout(struct ibmvfc_host *vhost)
5150 {
5151         struct ibmvfc_npiv_logout_mad *mad;
5152         struct ibmvfc_event *evt;
5153
5154         evt = ibmvfc_get_event(&vhost->crq);
5155         ibmvfc_init_event(evt, ibmvfc_npiv_logout_done, IBMVFC_MAD_FORMAT);
5156
5157         mad = &evt->iu.npiv_logout;
5158         memset(mad, 0, sizeof(*mad));
5159         mad->common.version = cpu_to_be32(1);
5160         mad->common.opcode = cpu_to_be32(IBMVFC_NPIV_LOGOUT);
5161         mad->common.length = cpu_to_be16(sizeof(struct ibmvfc_npiv_logout_mad));
5162
5163         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_LOGO_WAIT);
5164
5165         if (!ibmvfc_send_event(evt, vhost, default_timeout))
5166                 ibmvfc_dbg(vhost, "Sent NPIV logout\n");
5167         else
5168                 ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
5169 }
5170
5171 /**
5172  * ibmvfc_dev_init_to_do - Is there target initialization work to do?
5173  * @vhost:              ibmvfc host struct
5174  *
5175  * Returns:
5176  *      1 if work to do / 0 if not
5177  **/
5178 static int ibmvfc_dev_init_to_do(struct ibmvfc_host *vhost)
5179 {
5180         struct ibmvfc_target *tgt;
5181
5182         list_for_each_entry(tgt, &vhost->targets, queue) {
5183                 if (tgt->action == IBMVFC_TGT_ACTION_INIT ||
5184                     tgt->action == IBMVFC_TGT_ACTION_INIT_WAIT)
5185                         return 1;
5186         }
5187
5188         return 0;
5189 }
5190
5191 /**
5192  * ibmvfc_dev_logo_to_do - Is there target logout work to do?
5193  * @vhost:              ibmvfc host struct
5194  *
5195  * Returns:
5196  *      1 if work to do / 0 if not
5197  **/
5198 static int ibmvfc_dev_logo_to_do(struct ibmvfc_host *vhost)
5199 {
5200         struct ibmvfc_target *tgt;
5201
5202         list_for_each_entry(tgt, &vhost->targets, queue) {
5203                 if (tgt->action == IBMVFC_TGT_ACTION_LOGOUT_RPORT ||
5204                     tgt->action == IBMVFC_TGT_ACTION_LOGOUT_RPORT_WAIT)
5205                         return 1;
5206         }
5207         return 0;
5208 }
5209
5210 /**
5211  * __ibmvfc_work_to_do - Is there task level work to do? (no locking)
5212  * @vhost:              ibmvfc host struct
5213  *
5214  * Returns:
5215  *      1 if work to do / 0 if not
5216  **/
5217 static int __ibmvfc_work_to_do(struct ibmvfc_host *vhost)
5218 {
5219         struct ibmvfc_target *tgt;
5220
5221         if (kthread_should_stop())
5222                 return 1;
5223         switch (vhost->action) {
5224         case IBMVFC_HOST_ACTION_NONE:
5225         case IBMVFC_HOST_ACTION_INIT_WAIT:
5226         case IBMVFC_HOST_ACTION_LOGO_WAIT:
5227                 return 0;
5228         case IBMVFC_HOST_ACTION_TGT_INIT:
5229         case IBMVFC_HOST_ACTION_QUERY_TGTS:
5230                 if (vhost->discovery_threads == disc_threads)
5231                         return 0;
5232                 list_for_each_entry(tgt, &vhost->targets, queue)
5233                         if (tgt->action == IBMVFC_TGT_ACTION_INIT)
5234                                 return 1;
5235                 list_for_each_entry(tgt, &vhost->targets, queue)
5236                         if (tgt->action == IBMVFC_TGT_ACTION_INIT_WAIT)
5237                                 return 0;
5238                 return 1;
5239         case IBMVFC_HOST_ACTION_TGT_DEL:
5240         case IBMVFC_HOST_ACTION_TGT_DEL_FAILED:
5241                 if (vhost->discovery_threads == disc_threads)
5242                         return 0;
5243                 list_for_each_entry(tgt, &vhost->targets, queue)
5244                         if (tgt->action == IBMVFC_TGT_ACTION_LOGOUT_RPORT)
5245                                 return 1;
5246                 list_for_each_entry(tgt, &vhost->targets, queue)
5247                         if (tgt->action == IBMVFC_TGT_ACTION_LOGOUT_RPORT_WAIT)
5248                                 return 0;
5249                 return 1;
5250         case IBMVFC_HOST_ACTION_LOGO:
5251         case IBMVFC_HOST_ACTION_INIT:
5252         case IBMVFC_HOST_ACTION_ALLOC_TGTS:
5253         case IBMVFC_HOST_ACTION_QUERY:
5254         case IBMVFC_HOST_ACTION_RESET:
5255         case IBMVFC_HOST_ACTION_REENABLE:
5256         default:
5257                 break;
5258         }
5259
5260         return 1;
5261 }
5262
5263 /**
5264  * ibmvfc_work_to_do - Is there task level work to do?
5265  * @vhost:              ibmvfc host struct
5266  *
5267  * Returns:
5268  *      1 if work to do / 0 if not
5269  **/
5270 static int ibmvfc_work_to_do(struct ibmvfc_host *vhost)
5271 {
5272         unsigned long flags;
5273         int rc;
5274
5275         spin_lock_irqsave(vhost->host->host_lock, flags);
5276         rc = __ibmvfc_work_to_do(vhost);
5277         spin_unlock_irqrestore(vhost->host->host_lock, flags);
5278         return rc;
5279 }
5280
5281 /**
5282  * ibmvfc_log_ae - Log async events if necessary
5283  * @vhost:              ibmvfc host struct
5284  * @events:             events to log
5285  *
5286  **/
5287 static void ibmvfc_log_ae(struct ibmvfc_host *vhost, int events)
5288 {
5289         if (events & IBMVFC_AE_RSCN)
5290                 fc_host_post_event(vhost->host, fc_get_event_number(), FCH_EVT_RSCN, 0);
5291         if ((events & IBMVFC_AE_LINKDOWN) &&
5292             vhost->state >= IBMVFC_HALTED)
5293                 fc_host_post_event(vhost->host, fc_get_event_number(), FCH_EVT_LINKDOWN, 0);
5294         if ((events & IBMVFC_AE_LINKUP) &&
5295             vhost->state == IBMVFC_INITIALIZING)
5296                 fc_host_post_event(vhost->host, fc_get_event_number(), FCH_EVT_LINKUP, 0);
5297 }
5298
5299 /**
5300  * ibmvfc_tgt_add_rport - Tell the FC transport about a new remote port
5301  * @tgt:                ibmvfc target struct
5302  *
5303  **/
5304 static void ibmvfc_tgt_add_rport(struct ibmvfc_target *tgt)
5305 {
5306         struct ibmvfc_host *vhost = tgt->vhost;
5307         struct fc_rport *rport;
5308         unsigned long flags;
5309
5310         tgt_dbg(tgt, "Adding rport\n");
5311         rport = fc_remote_port_add(vhost->host, 0, &tgt->ids);
5312         spin_lock_irqsave(vhost->host->host_lock, flags);
5313
5314         if (rport && tgt->action == IBMVFC_TGT_ACTION_DEL_RPORT) {
5315                 tgt_dbg(tgt, "Deleting rport\n");
5316                 list_del(&tgt->queue);
5317                 ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_DELETED_RPORT);
5318                 spin_unlock_irqrestore(vhost->host->host_lock, flags);
5319                 fc_remote_port_delete(rport);
5320                 del_timer_sync(&tgt->timer);
5321                 kref_put(&tgt->kref, ibmvfc_release_tgt);
5322                 return;
5323         } else if (rport && tgt->action == IBMVFC_TGT_ACTION_DEL_AND_LOGOUT_RPORT) {
5324                 tgt_dbg(tgt, "Deleting rport with outstanding I/O\n");
5325                 ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_LOGOUT_DELETED_RPORT);
5326                 tgt->rport = NULL;
5327                 spin_unlock_irqrestore(vhost->host->host_lock, flags);
5328                 fc_remote_port_delete(rport);
5329                 return;
5330         } else if (rport && tgt->action == IBMVFC_TGT_ACTION_DELETED_RPORT) {
5331                 spin_unlock_irqrestore(vhost->host->host_lock, flags);
5332                 return;
5333         }
5334
5335         if (rport) {
5336                 tgt_dbg(tgt, "rport add succeeded\n");
5337                 tgt->rport = rport;
5338                 rport->maxframe_size = be16_to_cpu(tgt->service_parms.common.bb_rcv_sz) & 0x0fff;
5339                 rport->supported_classes = 0;
5340                 tgt->target_id = rport->scsi_target_id;
5341                 if (be32_to_cpu(tgt->service_parms.class1_parms[0]) & 0x80000000)
5342                         rport->supported_classes |= FC_COS_CLASS1;
5343                 if (be32_to_cpu(tgt->service_parms.class2_parms[0]) & 0x80000000)
5344                         rport->supported_classes |= FC_COS_CLASS2;
5345                 if (be32_to_cpu(tgt->service_parms.class3_parms[0]) & 0x80000000)
5346                         rport->supported_classes |= FC_COS_CLASS3;
5347                 if (rport->rqst_q)
5348                         blk_queue_max_segments(rport->rqst_q, 1);
5349         } else
5350                 tgt_dbg(tgt, "rport add failed\n");
5351         spin_unlock_irqrestore(vhost->host->host_lock, flags);
5352 }
5353
5354 /**
5355  * ibmvfc_do_work - Do task level work
5356  * @vhost:              ibmvfc host struct
5357  *
5358  **/
5359 static void ibmvfc_do_work(struct ibmvfc_host *vhost)
5360 {
5361         struct ibmvfc_target *tgt;
5362         unsigned long flags;
5363         struct fc_rport *rport;
5364         LIST_HEAD(purge);
5365         int rc;
5366
5367         ibmvfc_log_ae(vhost, vhost->events_to_log);
5368         spin_lock_irqsave(vhost->host->host_lock, flags);
5369         vhost->events_to_log = 0;
5370         switch (vhost->action) {
5371         case IBMVFC_HOST_ACTION_NONE:
5372         case IBMVFC_HOST_ACTION_LOGO_WAIT:
5373         case IBMVFC_HOST_ACTION_INIT_WAIT:
5374                 break;
5375         case IBMVFC_HOST_ACTION_RESET:
5376                 vhost->action = IBMVFC_HOST_ACTION_TGT_DEL;
5377                 list_splice_init(&vhost->purge, &purge);
5378                 spin_unlock_irqrestore(vhost->host->host_lock, flags);
5379                 ibmvfc_complete_purge(&purge);
5380                 rc = ibmvfc_reset_crq(vhost);
5381                 spin_lock_irqsave(vhost->host->host_lock, flags);
5382                 if (rc == H_CLOSED)
5383                         vio_enable_interrupts(to_vio_dev(vhost->dev));
5384                 if (rc || (rc = ibmvfc_send_crq_init(vhost)) ||
5385                     (rc = vio_enable_interrupts(to_vio_dev(vhost->dev)))) {
5386                         ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
5387                         dev_err(vhost->dev, "Error after reset (rc=%d)\n", rc);
5388                 }
5389                 break;
5390         case IBMVFC_HOST_ACTION_REENABLE:
5391                 vhost->action = IBMVFC_HOST_ACTION_TGT_DEL;
5392                 list_splice_init(&vhost->purge, &purge);
5393                 spin_unlock_irqrestore(vhost->host->host_lock, flags);
5394                 ibmvfc_complete_purge(&purge);
5395                 rc = ibmvfc_reenable_crq_queue(vhost);
5396                 spin_lock_irqsave(vhost->host->host_lock, flags);
5397                 if (rc || (rc = ibmvfc_send_crq_init(vhost))) {
5398                         ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
5399                         dev_err(vhost->dev, "Error after enable (rc=%d)\n", rc);
5400                 }
5401                 break;
5402         case IBMVFC_HOST_ACTION_LOGO:
5403                 vhost->job_step(vhost);
5404                 break;
5405         case IBMVFC_HOST_ACTION_INIT:
5406                 BUG_ON(vhost->state != IBMVFC_INITIALIZING);
5407                 if (vhost->delay_init) {
5408                         vhost->delay_init = 0;
5409                         spin_unlock_irqrestore(vhost->host->host_lock, flags);
5410                         ssleep(15);
5411                         return;
5412                 } else
5413                         vhost->job_step(vhost);
5414                 break;
5415         case IBMVFC_HOST_ACTION_QUERY:
5416                 list_for_each_entry(tgt, &vhost->targets, queue)
5417                         ibmvfc_init_tgt(tgt, ibmvfc_tgt_query_target);
5418                 ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_QUERY_TGTS);
5419                 break;
5420         case IBMVFC_HOST_ACTION_QUERY_TGTS:
5421                 list_for_each_entry(tgt, &vhost->targets, queue) {
5422                         if (tgt->action == IBMVFC_TGT_ACTION_INIT) {
5423                                 tgt->job_step(tgt);
5424                                 break;
5425                         }
5426                 }
5427
5428                 if (!ibmvfc_dev_init_to_do(vhost))
5429                         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_TGT_DEL);
5430                 break;
5431         case IBMVFC_HOST_ACTION_TGT_DEL:
5432         case IBMVFC_HOST_ACTION_TGT_DEL_FAILED:
5433                 list_for_each_entry(tgt, &vhost->targets, queue) {
5434                         if (tgt->action == IBMVFC_TGT_ACTION_LOGOUT_RPORT) {
5435                                 tgt->job_step(tgt);
5436                                 break;
5437                         }
5438                 }
5439
5440                 if (ibmvfc_dev_logo_to_do(vhost)) {
5441                         spin_unlock_irqrestore(vhost->host->host_lock, flags);
5442                         return;
5443                 }
5444
5445                 list_for_each_entry(tgt, &vhost->targets, queue) {
5446                         if (tgt->action == IBMVFC_TGT_ACTION_DEL_RPORT) {
5447                                 tgt_dbg(tgt, "Deleting rport\n");
5448                                 rport = tgt->rport;
5449                                 tgt->rport = NULL;
5450                                 list_del(&tgt->queue);
5451                                 ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_DELETED_RPORT);
5452                                 spin_unlock_irqrestore(vhost->host->host_lock, flags);
5453                                 if (rport)
5454                                         fc_remote_port_delete(rport);
5455                                 del_timer_sync(&tgt->timer);
5456                                 kref_put(&tgt->kref, ibmvfc_release_tgt);
5457                                 return;
5458                         } else if (tgt->action == IBMVFC_TGT_ACTION_DEL_AND_LOGOUT_RPORT) {
5459                                 tgt_dbg(tgt, "Deleting rport with I/O outstanding\n");
5460                                 rport = tgt->rport;
5461                                 tgt->rport = NULL;
5462                                 ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_LOGOUT_DELETED_RPORT);
5463                                 spin_unlock_irqrestore(vhost->host->host_lock, flags);
5464                                 if (rport)
5465                                         fc_remote_port_delete(rport);
5466                                 return;
5467                         }
5468                 }
5469
5470                 if (vhost->state == IBMVFC_INITIALIZING) {
5471                         if (vhost->action == IBMVFC_HOST_ACTION_TGT_DEL_FAILED) {
5472                                 if (vhost->reinit) {
5473                                         vhost->reinit = 0;
5474                                         scsi_block_requests(vhost->host);
5475                                         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_QUERY);
5476                                         spin_unlock_irqrestore(vhost->host->host_lock, flags);
5477                                 } else {
5478                                         ibmvfc_set_host_state(vhost, IBMVFC_ACTIVE);
5479                                         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_NONE);
5480                                         wake_up(&vhost->init_wait_q);
5481                                         schedule_work(&vhost->rport_add_work_q);
5482                                         vhost->init_retries = 0;
5483                                         spin_unlock_irqrestore(vhost->host->host_lock, flags);
5484                                         scsi_unblock_requests(vhost->host);
5485                                 }
5486
5487                                 return;
5488                         } else {
5489                                 ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_INIT);
5490                                 vhost->job_step = ibmvfc_discover_targets;
5491                         }
5492                 } else {
5493                         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_NONE);
5494                         spin_unlock_irqrestore(vhost->host->host_lock, flags);
5495                         scsi_unblock_requests(vhost->host);
5496                         wake_up(&vhost->init_wait_q);
5497                         return;
5498                 }
5499                 break;
5500         case IBMVFC_HOST_ACTION_ALLOC_TGTS:
5501                 ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_TGT_INIT);
5502                 spin_unlock_irqrestore(vhost->host->host_lock, flags);
5503                 ibmvfc_alloc_targets(vhost);
5504                 spin_lock_irqsave(vhost->host->host_lock, flags);
5505                 break;
5506         case IBMVFC_HOST_ACTION_TGT_INIT:
5507                 list_for_each_entry(tgt, &vhost->targets, queue) {
5508                         if (tgt->action == IBMVFC_TGT_ACTION_INIT) {
5509                                 tgt->job_step(tgt);
5510                                 break;
5511                         }
5512                 }
5513
5514                 if (!ibmvfc_dev_init_to_do(vhost))
5515                         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_TGT_DEL_FAILED);
5516                 break;
5517         default:
5518                 break;
5519         }
5520
5521         spin_unlock_irqrestore(vhost->host->host_lock, flags);
5522 }
5523
5524 /**
5525  * ibmvfc_work - Do task level work
5526  * @data:               ibmvfc host struct
5527  *
5528  * Returns:
5529  *      zero
5530  **/
5531 static int ibmvfc_work(void *data)
5532 {
5533         struct ibmvfc_host *vhost = data;
5534         int rc;
5535
5536         set_user_nice(current, MIN_NICE);
5537
5538         while (1) {
5539                 rc = wait_event_interruptible(vhost->work_wait_q,
5540                                               ibmvfc_work_to_do(vhost));
5541
5542                 BUG_ON(rc);
5543
5544                 if (kthread_should_stop())
5545                         break;
5546
5547                 ibmvfc_do_work(vhost);
5548         }
5549
5550         ibmvfc_dbg(vhost, "ibmvfc kthread exiting...\n");
5551         return 0;
5552 }
5553
5554 /**
5555  * ibmvfc_alloc_queue - Allocate queue
5556  * @vhost:      ibmvfc host struct
5557  * @queue:      ibmvfc queue to allocate
5558  * @fmt:        queue format to allocate
5559  *
5560  * Returns:
5561  *      0 on success / non-zero on failure
5562  **/
5563 static int ibmvfc_alloc_queue(struct ibmvfc_host *vhost,
5564                               struct ibmvfc_queue *queue,
5565                               enum ibmvfc_msg_fmt fmt)
5566 {
5567         struct device *dev = vhost->dev;
5568         size_t fmt_size;
5569         unsigned int pool_size = 0;
5570
5571         ENTER;
5572         spin_lock_init(&queue->_lock);
5573         queue->q_lock = &queue->_lock;
5574
5575         switch (fmt) {
5576         case IBMVFC_CRQ_FMT:
5577                 fmt_size = sizeof(*queue->msgs.crq);
5578                 pool_size = max_requests + IBMVFC_NUM_INTERNAL_REQ;
5579                 break;
5580         case IBMVFC_ASYNC_FMT:
5581                 fmt_size = sizeof(*queue->msgs.async);
5582                 break;
5583         case IBMVFC_SUB_CRQ_FMT:
5584                 fmt_size = sizeof(*queue->msgs.scrq);
5585                 /* We need one extra event for Cancel Commands */
5586                 pool_size = max_requests + 1;
5587                 break;
5588         default:
5589                 dev_warn(dev, "Unknown command/response queue message format: %d\n", fmt);
5590                 return -EINVAL;
5591         }
5592
5593         if (ibmvfc_init_event_pool(vhost, queue, pool_size)) {
5594                 dev_err(dev, "Couldn't initialize event pool.\n");
5595                 return -ENOMEM;
5596         }
5597
5598         queue->msgs.handle = (void *)get_zeroed_page(GFP_KERNEL);
5599         if (!queue->msgs.handle)
5600                 return -ENOMEM;
5601
5602         queue->msg_token = dma_map_single(dev, queue->msgs.handle, PAGE_SIZE,
5603                                           DMA_BIDIRECTIONAL);
5604
5605         if (dma_mapping_error(dev, queue->msg_token)) {
5606                 free_page((unsigned long)queue->msgs.handle);
5607                 queue->msgs.handle = NULL;
5608                 return -ENOMEM;
5609         }
5610
5611         queue->cur = 0;
5612         queue->fmt = fmt;
5613         queue->size = PAGE_SIZE / fmt_size;
5614         return 0;
5615 }
5616
5617 /**
5618  * ibmvfc_init_crq - Initializes and registers CRQ with hypervisor
5619  * @vhost:      ibmvfc host struct
5620  *
5621  * Allocates a page for messages, maps it for dma, and registers
5622  * the crq with the hypervisor.
5623  *
5624  * Return value:
5625  *      zero on success / other on failure
5626  **/
5627 static int ibmvfc_init_crq(struct ibmvfc_host *vhost)
5628 {
5629         int rc, retrc = -ENOMEM;
5630         struct device *dev = vhost->dev;
5631         struct vio_dev *vdev = to_vio_dev(dev);
5632         struct ibmvfc_queue *crq = &vhost->crq;
5633
5634         ENTER;
5635         if (ibmvfc_alloc_queue(vhost, crq, IBMVFC_CRQ_FMT))
5636                 return -ENOMEM;
5637
5638         retrc = rc = plpar_hcall_norets(H_REG_CRQ, vdev->unit_address,
5639                                         crq->msg_token, PAGE_SIZE);
5640
5641         if (rc == H_RESOURCE)
5642                 /* maybe kexecing and resource is busy. try a reset */
5643                 retrc = rc = ibmvfc_reset_crq(vhost);
5644
5645         if (rc == H_CLOSED)
5646                 dev_warn(dev, "Partner adapter not ready\n");
5647         else if (rc) {
5648                 dev_warn(dev, "Error %d opening adapter\n", rc);
5649                 goto reg_crq_failed;
5650         }
5651
5652         retrc = 0;
5653
5654         tasklet_init(&vhost->tasklet, (void *)ibmvfc_tasklet, (unsigned long)vhost);
5655
5656         if ((rc = request_irq(vdev->irq, ibmvfc_interrupt, 0, IBMVFC_NAME, vhost))) {
5657                 dev_err(dev, "Couldn't register irq 0x%x. rc=%d\n", vdev->irq, rc);
5658                 goto req_irq_failed;
5659         }
5660
5661         if ((rc = vio_enable_interrupts(vdev))) {
5662                 dev_err(dev, "Error %d enabling interrupts\n", rc);
5663                 goto req_irq_failed;
5664         }
5665
5666         LEAVE;
5667         return retrc;
5668
5669 req_irq_failed:
5670         tasklet_kill(&vhost->tasklet);
5671         do {
5672                 rc = plpar_hcall_norets(H_FREE_CRQ, vdev->unit_address);
5673         } while (rc == H_BUSY || H_IS_LONG_BUSY(rc));
5674 reg_crq_failed:
5675         ibmvfc_free_queue(vhost, crq);
5676         return retrc;
5677 }
5678
5679 static int ibmvfc_register_scsi_channel(struct ibmvfc_host *vhost,
5680                                   int index)
5681 {
5682         struct device *dev = vhost->dev;
5683         struct vio_dev *vdev = to_vio_dev(dev);
5684         struct ibmvfc_queue *scrq = &vhost->scsi_scrqs.scrqs[index];
5685         int rc = -ENOMEM;
5686
5687         ENTER;
5688
5689         if (ibmvfc_alloc_queue(vhost, scrq, IBMVFC_SUB_CRQ_FMT))
5690                 return -ENOMEM;
5691
5692         rc = h_reg_sub_crq(vdev->unit_address, scrq->msg_token, PAGE_SIZE,
5693                            &scrq->cookie, &scrq->hw_irq);
5694
5695         /* H_CLOSED indicates successful register, but no CRQ partner */
5696         if (rc && rc != H_CLOSED) {
5697                 dev_warn(dev, "Error registering sub-crq: %d\n", rc);
5698                 if (rc == H_PARAMETER)
5699                         dev_warn_once(dev, "Firmware may not support MQ\n");
5700                 goto reg_failed;
5701         }
5702
5703         scrq->irq = irq_create_mapping(NULL, scrq->hw_irq);
5704
5705         if (!scrq->irq) {
5706                 rc = -EINVAL;
5707                 dev_err(dev, "Error mapping sub-crq[%d] irq\n", index);
5708                 goto irq_failed;
5709         }
5710
5711         snprintf(scrq->name, sizeof(scrq->name), "ibmvfc-%x-scsi%d",
5712                  vdev->unit_address, index);
5713         rc = request_irq(scrq->irq, ibmvfc_interrupt_scsi, 0, scrq->name, scrq);
5714
5715         if (rc) {
5716                 dev_err(dev, "Couldn't register sub-crq[%d] irq\n", index);
5717                 irq_dispose_mapping(scrq->irq);
5718                 goto irq_failed;
5719         }
5720
5721         scrq->hwq_id = index;
5722         scrq->vhost = vhost;
5723
5724         LEAVE;
5725         return 0;
5726
5727 irq_failed:
5728         do {
5729                 rc = plpar_hcall_norets(H_FREE_SUB_CRQ, vdev->unit_address, scrq->cookie);
5730         } while (rtas_busy_delay(rc));
5731 reg_failed:
5732         ibmvfc_free_queue(vhost, scrq);
5733         LEAVE;
5734         return rc;
5735 }
5736
5737 static void ibmvfc_deregister_scsi_channel(struct ibmvfc_host *vhost, int index)
5738 {
5739         struct device *dev = vhost->dev;
5740         struct vio_dev *vdev = to_vio_dev(dev);
5741         struct ibmvfc_queue *scrq = &vhost->scsi_scrqs.scrqs[index];
5742         long rc;
5743
5744         ENTER;
5745
5746         free_irq(scrq->irq, scrq);
5747         irq_dispose_mapping(scrq->irq);
5748         scrq->irq = 0;
5749
5750         do {
5751                 rc = plpar_hcall_norets(H_FREE_SUB_CRQ, vdev->unit_address,
5752                                         scrq->cookie);
5753         } while (rc == H_BUSY || H_IS_LONG_BUSY(rc));
5754
5755         if (rc)
5756                 dev_err(dev, "Failed to free sub-crq[%d]: rc=%ld\n", index, rc);
5757
5758         ibmvfc_free_queue(vhost, scrq);
5759         LEAVE;
5760 }
5761
5762 static void ibmvfc_init_sub_crqs(struct ibmvfc_host *vhost)
5763 {
5764         int i, j;
5765
5766         ENTER;
5767         if (!vhost->mq_enabled)
5768                 return;
5769
5770         vhost->scsi_scrqs.scrqs = kcalloc(nr_scsi_hw_queues,
5771                                           sizeof(*vhost->scsi_scrqs.scrqs),
5772                                           GFP_KERNEL);
5773         if (!vhost->scsi_scrqs.scrqs) {
5774                 vhost->do_enquiry = 0;
5775                 return;
5776         }
5777
5778         for (i = 0; i < nr_scsi_hw_queues; i++) {
5779                 if (ibmvfc_register_scsi_channel(vhost, i)) {
5780                         for (j = i; j > 0; j--)
5781                                 ibmvfc_deregister_scsi_channel(vhost, j - 1);
5782                         kfree(vhost->scsi_scrqs.scrqs);
5783                         vhost->scsi_scrqs.scrqs = NULL;
5784                         vhost->scsi_scrqs.active_queues = 0;
5785                         vhost->do_enquiry = 0;
5786                         break;
5787                 }
5788         }
5789
5790         LEAVE;
5791 }
5792
5793 static void ibmvfc_release_sub_crqs(struct ibmvfc_host *vhost)
5794 {
5795         int i;
5796
5797         ENTER;
5798         if (!vhost->scsi_scrqs.scrqs)
5799                 return;
5800
5801         for (i = 0; i < nr_scsi_hw_queues; i++)
5802                 ibmvfc_deregister_scsi_channel(vhost, i);
5803
5804         kfree(vhost->scsi_scrqs.scrqs);
5805         vhost->scsi_scrqs.scrqs = NULL;
5806         vhost->scsi_scrqs.active_queues = 0;
5807         LEAVE;
5808 }
5809
5810 /**
5811  * ibmvfc_free_mem - Free memory for vhost
5812  * @vhost:      ibmvfc host struct
5813  *
5814  * Return value:
5815  *      none
5816  **/
5817 static void ibmvfc_free_mem(struct ibmvfc_host *vhost)
5818 {
5819         struct ibmvfc_queue *async_q = &vhost->async_crq;
5820
5821         ENTER;
5822         mempool_destroy(vhost->tgt_pool);
5823         kfree(vhost->trace);
5824         dma_free_coherent(vhost->dev, vhost->disc_buf_sz, vhost->disc_buf,
5825                           vhost->disc_buf_dma);
5826         dma_free_coherent(vhost->dev, sizeof(*vhost->login_buf),
5827                           vhost->login_buf, vhost->login_buf_dma);
5828         dma_free_coherent(vhost->dev, sizeof(*vhost->channel_setup_buf),
5829                           vhost->channel_setup_buf, vhost->channel_setup_dma);
5830         dma_pool_destroy(vhost->sg_pool);
5831         ibmvfc_free_queue(vhost, async_q);
5832         LEAVE;
5833 }
5834
5835 /**
5836  * ibmvfc_alloc_mem - Allocate memory for vhost
5837  * @vhost:      ibmvfc host struct
5838  *
5839  * Return value:
5840  *      0 on success / non-zero on failure
5841  **/
5842 static int ibmvfc_alloc_mem(struct ibmvfc_host *vhost)
5843 {
5844         struct ibmvfc_queue *async_q = &vhost->async_crq;
5845         struct device *dev = vhost->dev;
5846
5847         ENTER;
5848         if (ibmvfc_alloc_queue(vhost, async_q, IBMVFC_ASYNC_FMT)) {
5849                 dev_err(dev, "Couldn't allocate/map async queue.\n");
5850                 goto nomem;
5851         }
5852
5853         vhost->sg_pool = dma_pool_create(IBMVFC_NAME, dev,
5854                                          SG_ALL * sizeof(struct srp_direct_buf),
5855                                          sizeof(struct srp_direct_buf), 0);
5856
5857         if (!vhost->sg_pool) {
5858                 dev_err(dev, "Failed to allocate sg pool\n");
5859                 goto unmap_async_crq;
5860         }
5861
5862         vhost->login_buf = dma_alloc_coherent(dev, sizeof(*vhost->login_buf),
5863                                               &vhost->login_buf_dma, GFP_KERNEL);
5864
5865         if (!vhost->login_buf) {
5866                 dev_err(dev, "Couldn't allocate NPIV login buffer\n");
5867                 goto free_sg_pool;
5868         }
5869
5870         vhost->disc_buf_sz = sizeof(*vhost->disc_buf) * max_targets;
5871         vhost->disc_buf = dma_alloc_coherent(dev, vhost->disc_buf_sz,
5872                                              &vhost->disc_buf_dma, GFP_KERNEL);
5873
5874         if (!vhost->disc_buf) {
5875                 dev_err(dev, "Couldn't allocate Discover Targets buffer\n");
5876                 goto free_login_buffer;
5877         }
5878
5879         vhost->trace = kcalloc(IBMVFC_NUM_TRACE_ENTRIES,
5880                                sizeof(struct ibmvfc_trace_entry), GFP_KERNEL);
5881         atomic_set(&vhost->trace_index, -1);
5882
5883         if (!vhost->trace)
5884                 goto free_disc_buffer;
5885
5886         vhost->tgt_pool = mempool_create_kmalloc_pool(IBMVFC_TGT_MEMPOOL_SZ,
5887                                                       sizeof(struct ibmvfc_target));
5888
5889         if (!vhost->tgt_pool) {
5890                 dev_err(dev, "Couldn't allocate target memory pool\n");
5891                 goto free_trace;
5892         }
5893
5894         vhost->channel_setup_buf = dma_alloc_coherent(dev, sizeof(*vhost->channel_setup_buf),
5895                                                       &vhost->channel_setup_dma,
5896                                                       GFP_KERNEL);
5897
5898         if (!vhost->channel_setup_buf) {
5899                 dev_err(dev, "Couldn't allocate Channel Setup buffer\n");
5900                 goto free_tgt_pool;
5901         }
5902
5903         LEAVE;
5904         return 0;
5905
5906 free_tgt_pool:
5907         mempool_destroy(vhost->tgt_pool);
5908 free_trace:
5909         kfree(vhost->trace);
5910 free_disc_buffer:
5911         dma_free_coherent(dev, vhost->disc_buf_sz, vhost->disc_buf,
5912                           vhost->disc_buf_dma);
5913 free_login_buffer:
5914         dma_free_coherent(dev, sizeof(*vhost->login_buf),
5915                           vhost->login_buf, vhost->login_buf_dma);
5916 free_sg_pool:
5917         dma_pool_destroy(vhost->sg_pool);
5918 unmap_async_crq:
5919         ibmvfc_free_queue(vhost, async_q);
5920 nomem:
5921         LEAVE;
5922         return -ENOMEM;
5923 }
5924
5925 /**
5926  * ibmvfc_rport_add_thread - Worker thread for rport adds
5927  * @work:       work struct
5928  *
5929  **/
5930 static void ibmvfc_rport_add_thread(struct work_struct *work)
5931 {
5932         struct ibmvfc_host *vhost = container_of(work, struct ibmvfc_host,
5933                                                  rport_add_work_q);
5934         struct ibmvfc_target *tgt;
5935         struct fc_rport *rport;
5936         unsigned long flags;
5937         int did_work;
5938
5939         ENTER;
5940         spin_lock_irqsave(vhost->host->host_lock, flags);
5941         do {
5942                 did_work = 0;
5943                 if (vhost->state != IBMVFC_ACTIVE)
5944                         break;
5945
5946                 list_for_each_entry(tgt, &vhost->targets, queue) {
5947                         if (tgt->add_rport) {
5948                                 did_work = 1;
5949                                 tgt->add_rport = 0;
5950                                 kref_get(&tgt->kref);
5951                                 rport = tgt->rport;
5952                                 if (!rport) {
5953                                         spin_unlock_irqrestore(vhost->host->host_lock, flags);
5954                                         ibmvfc_tgt_add_rport(tgt);
5955                                 } else if (get_device(&rport->dev)) {
5956                                         spin_unlock_irqrestore(vhost->host->host_lock, flags);
5957                                         tgt_dbg(tgt, "Setting rport roles\n");
5958                                         fc_remote_port_rolechg(rport, tgt->ids.roles);
5959                                         put_device(&rport->dev);
5960                                 } else {
5961                                         spin_unlock_irqrestore(vhost->host->host_lock, flags);
5962                                 }
5963
5964                                 kref_put(&tgt->kref, ibmvfc_release_tgt);
5965                                 spin_lock_irqsave(vhost->host->host_lock, flags);
5966                                 break;
5967                         }
5968                 }
5969         } while(did_work);
5970
5971         if (vhost->state == IBMVFC_ACTIVE)
5972                 vhost->scan_complete = 1;
5973         spin_unlock_irqrestore(vhost->host->host_lock, flags);
5974         LEAVE;
5975 }
5976
5977 /**
5978  * ibmvfc_probe - Adapter hot plug add entry point
5979  * @vdev:       vio device struct
5980  * @id: vio device id struct
5981  *
5982  * Return value:
5983  *      0 on success / non-zero on failure
5984  **/
5985 static int ibmvfc_probe(struct vio_dev *vdev, const struct vio_device_id *id)
5986 {
5987         struct ibmvfc_host *vhost;
5988         struct Scsi_Host *shost;
5989         struct device *dev = &vdev->dev;
5990         int rc = -ENOMEM;
5991         unsigned int max_scsi_queues = IBMVFC_MAX_SCSI_QUEUES;
5992
5993         ENTER;
5994         shost = scsi_host_alloc(&driver_template, sizeof(*vhost));
5995         if (!shost) {
5996                 dev_err(dev, "Couldn't allocate host data\n");
5997                 goto out;
5998         }
5999
6000         shost->transportt = ibmvfc_transport_template;
6001         shost->can_queue = max_requests;
6002         shost->max_lun = max_lun;
6003         shost->max_id = max_targets;
6004         shost->max_sectors = IBMVFC_MAX_SECTORS;
6005         shost->max_cmd_len = IBMVFC_MAX_CDB_LEN;
6006         shost->unique_id = shost->host_no;
6007         shost->nr_hw_queues = mq_enabled ? min(max_scsi_queues, nr_scsi_hw_queues) : 1;
6008
6009         vhost = shost_priv(shost);
6010         INIT_LIST_HEAD(&vhost->targets);
6011         INIT_LIST_HEAD(&vhost->purge);
6012         sprintf(vhost->name, IBMVFC_NAME);
6013         vhost->host = shost;
6014         vhost->dev = dev;
6015         vhost->partition_number = -1;
6016         vhost->log_level = log_level;
6017         vhost->task_set = 1;
6018
6019         vhost->mq_enabled = mq_enabled;
6020         vhost->client_scsi_channels = min(shost->nr_hw_queues, nr_scsi_channels);
6021         vhost->using_channels = 0;
6022         vhost->do_enquiry = 1;
6023
6024         strcpy(vhost->partition_name, "UNKNOWN");
6025         init_waitqueue_head(&vhost->work_wait_q);
6026         init_waitqueue_head(&vhost->init_wait_q);
6027         INIT_WORK(&vhost->rport_add_work_q, ibmvfc_rport_add_thread);
6028         mutex_init(&vhost->passthru_mutex);
6029
6030         if ((rc = ibmvfc_alloc_mem(vhost)))
6031                 goto free_scsi_host;
6032
6033         vhost->work_thread = kthread_run(ibmvfc_work, vhost, "%s_%d", IBMVFC_NAME,
6034                                          shost->host_no);
6035
6036         if (IS_ERR(vhost->work_thread)) {
6037                 dev_err(dev, "Couldn't create kernel thread: %ld\n",
6038                         PTR_ERR(vhost->work_thread));
6039                 rc = PTR_ERR(vhost->work_thread);
6040                 goto free_host_mem;
6041         }
6042
6043         if ((rc = ibmvfc_init_crq(vhost))) {
6044                 dev_err(dev, "Couldn't initialize crq. rc=%d\n", rc);
6045                 goto kill_kthread;
6046         }
6047
6048         if ((rc = scsi_add_host(shost, dev)))
6049                 goto release_crq;
6050
6051         fc_host_dev_loss_tmo(shost) = IBMVFC_DEV_LOSS_TMO;
6052
6053         if ((rc = ibmvfc_create_trace_file(&shost->shost_dev.kobj,
6054                                            &ibmvfc_trace_attr))) {
6055                 dev_err(dev, "Failed to create trace file. rc=%d\n", rc);
6056                 goto remove_shost;
6057         }
6058
6059         ibmvfc_init_sub_crqs(vhost);
6060
6061         if (shost_to_fc_host(shost)->rqst_q)
6062                 blk_queue_max_segments(shost_to_fc_host(shost)->rqst_q, 1);
6063         dev_set_drvdata(dev, vhost);
6064         spin_lock(&ibmvfc_driver_lock);
6065         list_add_tail(&vhost->queue, &ibmvfc_head);
6066         spin_unlock(&ibmvfc_driver_lock);
6067
6068         ibmvfc_send_crq_init(vhost);
6069         scsi_scan_host(shost);
6070         return 0;
6071
6072 remove_shost:
6073         scsi_remove_host(shost);
6074 release_crq:
6075         ibmvfc_release_crq_queue(vhost);
6076 kill_kthread:
6077         kthread_stop(vhost->work_thread);
6078 free_host_mem:
6079         ibmvfc_free_mem(vhost);
6080 free_scsi_host:
6081         scsi_host_put(shost);
6082 out:
6083         LEAVE;
6084         return rc;
6085 }
6086
6087 /**
6088  * ibmvfc_remove - Adapter hot plug remove entry point
6089  * @vdev:       vio device struct
6090  *
6091  * Return value:
6092  *      0
6093  **/
6094 static void ibmvfc_remove(struct vio_dev *vdev)
6095 {
6096         struct ibmvfc_host *vhost = dev_get_drvdata(&vdev->dev);
6097         LIST_HEAD(purge);
6098         unsigned long flags;
6099
6100         ENTER;
6101         ibmvfc_remove_trace_file(&vhost->host->shost_dev.kobj, &ibmvfc_trace_attr);
6102
6103         spin_lock_irqsave(vhost->host->host_lock, flags);
6104         ibmvfc_link_down(vhost, IBMVFC_HOST_OFFLINE);
6105         spin_unlock_irqrestore(vhost->host->host_lock, flags);
6106
6107         ibmvfc_wait_while_resetting(vhost);
6108         kthread_stop(vhost->work_thread);
6109         fc_remove_host(vhost->host);
6110         scsi_remove_host(vhost->host);
6111
6112         spin_lock_irqsave(vhost->host->host_lock, flags);
6113         ibmvfc_purge_requests(vhost, DID_ERROR);
6114         list_splice_init(&vhost->purge, &purge);
6115         spin_unlock_irqrestore(vhost->host->host_lock, flags);
6116         ibmvfc_complete_purge(&purge);
6117         ibmvfc_release_sub_crqs(vhost);
6118         ibmvfc_release_crq_queue(vhost);
6119
6120         ibmvfc_free_mem(vhost);
6121         spin_lock(&ibmvfc_driver_lock);
6122         list_del(&vhost->queue);
6123         spin_unlock(&ibmvfc_driver_lock);
6124         scsi_host_put(vhost->host);
6125         LEAVE;
6126 }
6127
6128 /**
6129  * ibmvfc_resume - Resume from suspend
6130  * @dev:        device struct
6131  *
6132  * We may have lost an interrupt across suspend/resume, so kick the
6133  * interrupt handler
6134  *
6135  */
6136 static int ibmvfc_resume(struct device *dev)
6137 {
6138         unsigned long flags;
6139         struct ibmvfc_host *vhost = dev_get_drvdata(dev);
6140         struct vio_dev *vdev = to_vio_dev(dev);
6141
6142         spin_lock_irqsave(vhost->host->host_lock, flags);
6143         vio_disable_interrupts(vdev);
6144         tasklet_schedule(&vhost->tasklet);
6145         spin_unlock_irqrestore(vhost->host->host_lock, flags);
6146         return 0;
6147 }
6148
6149 /**
6150  * ibmvfc_get_desired_dma - Calculate DMA resources needed by the driver
6151  * @vdev:       vio device struct
6152  *
6153  * Return value:
6154  *      Number of bytes the driver will need to DMA map at the same time in
6155  *      order to perform well.
6156  */
6157 static unsigned long ibmvfc_get_desired_dma(struct vio_dev *vdev)
6158 {
6159         unsigned long pool_dma = max_requests * sizeof(union ibmvfc_iu);
6160         return pool_dma + ((512 * 1024) * driver_template.cmd_per_lun);
6161 }
6162
6163 static const struct vio_device_id ibmvfc_device_table[] = {
6164         {"fcp", "IBM,vfc-client"},
6165         { "", "" }
6166 };
6167 MODULE_DEVICE_TABLE(vio, ibmvfc_device_table);
6168
6169 static const struct dev_pm_ops ibmvfc_pm_ops = {
6170         .resume = ibmvfc_resume
6171 };
6172
6173 static struct vio_driver ibmvfc_driver = {
6174         .id_table = ibmvfc_device_table,
6175         .probe = ibmvfc_probe,
6176         .remove = ibmvfc_remove,
6177         .get_desired_dma = ibmvfc_get_desired_dma,
6178         .name = IBMVFC_NAME,
6179         .pm = &ibmvfc_pm_ops,
6180 };
6181
6182 static struct fc_function_template ibmvfc_transport_functions = {
6183         .show_host_fabric_name = 1,
6184         .show_host_node_name = 1,
6185         .show_host_port_name = 1,
6186         .show_host_supported_classes = 1,
6187         .show_host_port_type = 1,
6188         .show_host_port_id = 1,
6189         .show_host_maxframe_size = 1,
6190
6191         .get_host_port_state = ibmvfc_get_host_port_state,
6192         .show_host_port_state = 1,
6193
6194         .get_host_speed = ibmvfc_get_host_speed,
6195         .show_host_speed = 1,
6196
6197         .issue_fc_host_lip = ibmvfc_issue_fc_host_lip,
6198         .terminate_rport_io = ibmvfc_terminate_rport_io,
6199
6200         .show_rport_maxframe_size = 1,
6201         .show_rport_supported_classes = 1,
6202
6203         .set_rport_dev_loss_tmo = ibmvfc_set_rport_dev_loss_tmo,
6204         .show_rport_dev_loss_tmo = 1,
6205
6206         .get_starget_node_name = ibmvfc_get_starget_node_name,
6207         .show_starget_node_name = 1,
6208
6209         .get_starget_port_name = ibmvfc_get_starget_port_name,
6210         .show_starget_port_name = 1,
6211
6212         .get_starget_port_id = ibmvfc_get_starget_port_id,
6213         .show_starget_port_id = 1,
6214
6215         .bsg_request = ibmvfc_bsg_request,
6216         .bsg_timeout = ibmvfc_bsg_timeout,
6217 };
6218
6219 /**
6220  * ibmvfc_module_init - Initialize the ibmvfc module
6221  *
6222  * Return value:
6223  *      0 on success / other on failure
6224  **/
6225 static int __init ibmvfc_module_init(void)
6226 {
6227         int rc;
6228
6229         if (!firmware_has_feature(FW_FEATURE_VIO))
6230                 return -ENODEV;
6231
6232         printk(KERN_INFO IBMVFC_NAME": IBM Virtual Fibre Channel Driver version: %s %s\n",
6233                IBMVFC_DRIVER_VERSION, IBMVFC_DRIVER_DATE);
6234
6235         ibmvfc_transport_template = fc_attach_transport(&ibmvfc_transport_functions);
6236         if (!ibmvfc_transport_template)
6237                 return -ENOMEM;
6238
6239         rc = vio_register_driver(&ibmvfc_driver);
6240         if (rc)
6241                 fc_release_transport(ibmvfc_transport_template);
6242         return rc;
6243 }
6244
6245 /**
6246  * ibmvfc_module_exit - Teardown the ibmvfc module
6247  *
6248  * Return value:
6249  *      nothing
6250  **/
6251 static void __exit ibmvfc_module_exit(void)
6252 {
6253         vio_unregister_driver(&ibmvfc_driver);
6254         fc_release_transport(ibmvfc_transport_template);
6255 }
6256
6257 module_init(ibmvfc_module_init);
6258 module_exit(ibmvfc_module_exit);