Merge tag 'scsi-fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/jejb/scsi
[platform/kernel/linux-rpi.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_wait_for_ops - Wait for ops to complete
2376  * @vhost:      ibmvfc host struct
2377  * @device:     device to match (starget or sdev)
2378  * @match:      match function
2379  *
2380  * Returns:
2381  *      SUCCESS / FAILED
2382  **/
2383 static int ibmvfc_wait_for_ops(struct ibmvfc_host *vhost, void *device,
2384                                int (*match) (struct ibmvfc_event *, void *))
2385 {
2386         struct ibmvfc_event *evt;
2387         DECLARE_COMPLETION_ONSTACK(comp);
2388         int wait;
2389         unsigned long flags;
2390         signed long timeout = IBMVFC_ABORT_WAIT_TIMEOUT * HZ;
2391
2392         ENTER;
2393         do {
2394                 wait = 0;
2395                 spin_lock_irqsave(&vhost->crq.l_lock, flags);
2396                 list_for_each_entry(evt, &vhost->crq.sent, queue_list) {
2397                         if (match(evt, device)) {
2398                                 evt->eh_comp = &comp;
2399                                 wait++;
2400                         }
2401                 }
2402                 spin_unlock_irqrestore(&vhost->crq.l_lock, flags);
2403
2404                 if (wait) {
2405                         timeout = wait_for_completion_timeout(&comp, timeout);
2406
2407                         if (!timeout) {
2408                                 wait = 0;
2409                                 spin_lock_irqsave(&vhost->crq.l_lock, flags);
2410                                 list_for_each_entry(evt, &vhost->crq.sent, queue_list) {
2411                                         if (match(evt, device)) {
2412                                                 evt->eh_comp = NULL;
2413                                                 wait++;
2414                                         }
2415                                 }
2416                                 spin_unlock_irqrestore(&vhost->crq.l_lock, flags);
2417                                 if (wait)
2418                                         dev_err(vhost->dev, "Timed out waiting for aborted commands\n");
2419                                 LEAVE;
2420                                 return wait ? FAILED : SUCCESS;
2421                         }
2422                 }
2423         } while (wait);
2424
2425         LEAVE;
2426         return SUCCESS;
2427 }
2428
2429 static struct ibmvfc_event *ibmvfc_init_tmf(struct ibmvfc_queue *queue,
2430                                             struct scsi_device *sdev,
2431                                             int type)
2432 {
2433         struct ibmvfc_host *vhost = shost_priv(sdev->host);
2434         struct scsi_target *starget = scsi_target(sdev);
2435         struct fc_rport *rport = starget_to_rport(starget);
2436         struct ibmvfc_event *evt;
2437         struct ibmvfc_tmf *tmf;
2438
2439         evt = ibmvfc_get_event(queue);
2440         ibmvfc_init_event(evt, ibmvfc_sync_completion, IBMVFC_MAD_FORMAT);
2441
2442         tmf = &evt->iu.tmf;
2443         memset(tmf, 0, sizeof(*tmf));
2444         if (ibmvfc_check_caps(vhost, IBMVFC_HANDLE_VF_WWPN)) {
2445                 tmf->common.version = cpu_to_be32(2);
2446                 tmf->target_wwpn = cpu_to_be64(rport->port_name);
2447         } else {
2448                 tmf->common.version = cpu_to_be32(1);
2449         }
2450         tmf->common.opcode = cpu_to_be32(IBMVFC_TMF_MAD);
2451         tmf->common.length = cpu_to_be16(sizeof(*tmf));
2452         tmf->scsi_id = cpu_to_be64(rport->port_id);
2453         int_to_scsilun(sdev->lun, &tmf->lun);
2454         if (!ibmvfc_check_caps(vhost, IBMVFC_CAN_SUPPRESS_ABTS))
2455                 type &= ~IBMVFC_TMF_SUPPRESS_ABTS;
2456         if (vhost->state == IBMVFC_ACTIVE)
2457                 tmf->flags = cpu_to_be32((type | IBMVFC_TMF_LUA_VALID));
2458         else
2459                 tmf->flags = cpu_to_be32(((type & IBMVFC_TMF_SUPPRESS_ABTS) | IBMVFC_TMF_LUA_VALID));
2460         tmf->cancel_key = cpu_to_be32((unsigned long)sdev->hostdata);
2461         tmf->my_cancel_key = cpu_to_be32((unsigned long)starget->hostdata);
2462
2463         init_completion(&evt->comp);
2464
2465         return evt;
2466 }
2467
2468 static int ibmvfc_cancel_all_mq(struct scsi_device *sdev, int type)
2469 {
2470         struct ibmvfc_host *vhost = shost_priv(sdev->host);
2471         struct ibmvfc_event *evt, *found_evt, *temp;
2472         struct ibmvfc_queue *queues = vhost->scsi_scrqs.scrqs;
2473         unsigned long flags;
2474         int num_hwq, i;
2475         int fail = 0;
2476         LIST_HEAD(cancelq);
2477         u16 status;
2478
2479         ENTER;
2480         spin_lock_irqsave(vhost->host->host_lock, flags);
2481         num_hwq = vhost->scsi_scrqs.active_queues;
2482         for (i = 0; i < num_hwq; i++) {
2483                 spin_lock(queues[i].q_lock);
2484                 spin_lock(&queues[i].l_lock);
2485                 found_evt = NULL;
2486                 list_for_each_entry(evt, &queues[i].sent, queue_list) {
2487                         if (evt->cmnd && evt->cmnd->device == sdev) {
2488                                 found_evt = evt;
2489                                 break;
2490                         }
2491                 }
2492                 spin_unlock(&queues[i].l_lock);
2493
2494                 if (found_evt && vhost->logged_in) {
2495                         evt = ibmvfc_init_tmf(&queues[i], sdev, type);
2496                         evt->sync_iu = &queues[i].cancel_rsp;
2497                         ibmvfc_send_event(evt, vhost, default_timeout);
2498                         list_add_tail(&evt->cancel, &cancelq);
2499                 }
2500
2501                 spin_unlock(queues[i].q_lock);
2502         }
2503         spin_unlock_irqrestore(vhost->host->host_lock, flags);
2504
2505         if (list_empty(&cancelq)) {
2506                 if (vhost->log_level > IBMVFC_DEFAULT_LOG_LEVEL)
2507                         sdev_printk(KERN_INFO, sdev, "No events found to cancel\n");
2508                 return 0;
2509         }
2510
2511         sdev_printk(KERN_INFO, sdev, "Cancelling outstanding commands.\n");
2512
2513         list_for_each_entry_safe(evt, temp, &cancelq, cancel) {
2514                 wait_for_completion(&evt->comp);
2515                 status = be16_to_cpu(evt->queue->cancel_rsp.mad_common.status);
2516                 list_del(&evt->cancel);
2517                 ibmvfc_free_event(evt);
2518
2519                 if (status != IBMVFC_MAD_SUCCESS) {
2520                         sdev_printk(KERN_WARNING, sdev, "Cancel failed with rc=%x\n", status);
2521                         switch (status) {
2522                         case IBMVFC_MAD_DRIVER_FAILED:
2523                         case IBMVFC_MAD_CRQ_ERROR:
2524                         /* Host adapter most likely going through reset, return success to
2525                          * the caller will wait for the command being cancelled to get returned
2526                          */
2527                                 break;
2528                         default:
2529                                 fail = 1;
2530                                 break;
2531                         }
2532                 }
2533         }
2534
2535         if (fail)
2536                 return -EIO;
2537
2538         sdev_printk(KERN_INFO, sdev, "Successfully cancelled outstanding commands\n");
2539         LEAVE;
2540         return 0;
2541 }
2542
2543 static int ibmvfc_cancel_all_sq(struct scsi_device *sdev, int type)
2544 {
2545         struct ibmvfc_host *vhost = shost_priv(sdev->host);
2546         struct ibmvfc_event *evt, *found_evt;
2547         union ibmvfc_iu rsp;
2548         int rsp_rc = -EBUSY;
2549         unsigned long flags;
2550         u16 status;
2551
2552         ENTER;
2553         found_evt = NULL;
2554         spin_lock_irqsave(vhost->host->host_lock, flags);
2555         spin_lock(&vhost->crq.l_lock);
2556         list_for_each_entry(evt, &vhost->crq.sent, queue_list) {
2557                 if (evt->cmnd && evt->cmnd->device == sdev) {
2558                         found_evt = evt;
2559                         break;
2560                 }
2561         }
2562         spin_unlock(&vhost->crq.l_lock);
2563
2564         if (!found_evt) {
2565                 if (vhost->log_level > IBMVFC_DEFAULT_LOG_LEVEL)
2566                         sdev_printk(KERN_INFO, sdev, "No events found to cancel\n");
2567                 spin_unlock_irqrestore(vhost->host->host_lock, flags);
2568                 return 0;
2569         }
2570
2571         if (vhost->logged_in) {
2572                 evt = ibmvfc_init_tmf(&vhost->crq, sdev, type);
2573                 evt->sync_iu = &rsp;
2574                 rsp_rc = ibmvfc_send_event(evt, vhost, default_timeout);
2575         }
2576
2577         spin_unlock_irqrestore(vhost->host->host_lock, flags);
2578
2579         if (rsp_rc != 0) {
2580                 sdev_printk(KERN_ERR, sdev, "Failed to send cancel event. rc=%d\n", rsp_rc);
2581                 /* If failure is received, the host adapter is most likely going
2582                  through reset, return success so the caller will wait for the command
2583                  being cancelled to get returned */
2584                 return 0;
2585         }
2586
2587         sdev_printk(KERN_INFO, sdev, "Cancelling outstanding commands.\n");
2588
2589         wait_for_completion(&evt->comp);
2590         status = be16_to_cpu(rsp.mad_common.status);
2591         spin_lock_irqsave(vhost->host->host_lock, flags);
2592         ibmvfc_free_event(evt);
2593         spin_unlock_irqrestore(vhost->host->host_lock, flags);
2594
2595         if (status != IBMVFC_MAD_SUCCESS) {
2596                 sdev_printk(KERN_WARNING, sdev, "Cancel failed with rc=%x\n", status);
2597                 switch (status) {
2598                 case IBMVFC_MAD_DRIVER_FAILED:
2599                 case IBMVFC_MAD_CRQ_ERROR:
2600                         /* Host adapter most likely going through reset, return success to
2601                          the caller will wait for the command being cancelled to get returned */
2602                         return 0;
2603                 default:
2604                         return -EIO;
2605                 };
2606         }
2607
2608         sdev_printk(KERN_INFO, sdev, "Successfully cancelled outstanding commands\n");
2609         return 0;
2610 }
2611
2612 /**
2613  * ibmvfc_cancel_all - Cancel all outstanding commands to the device
2614  * @sdev:       scsi device to cancel commands
2615  * @type:       type of error recovery being performed
2616  *
2617  * This sends a cancel to the VIOS for the specified device. This does
2618  * NOT send any abort to the actual device. That must be done separately.
2619  *
2620  * Returns:
2621  *      0 on success / other on failure
2622  **/
2623 static int ibmvfc_cancel_all(struct scsi_device *sdev, int type)
2624 {
2625         struct ibmvfc_host *vhost = shost_priv(sdev->host);
2626
2627         if (vhost->mq_enabled && vhost->using_channels)
2628                 return ibmvfc_cancel_all_mq(sdev, type);
2629         else
2630                 return ibmvfc_cancel_all_sq(sdev, type);
2631 }
2632
2633 /**
2634  * ibmvfc_match_key - Match function for specified cancel key
2635  * @evt:        ibmvfc event struct
2636  * @key:        cancel key to match
2637  *
2638  * Returns:
2639  *      1 if event matches key / 0 if event does not match key
2640  **/
2641 static int ibmvfc_match_key(struct ibmvfc_event *evt, void *key)
2642 {
2643         unsigned long cancel_key = (unsigned long)key;
2644
2645         if (evt->crq.format == IBMVFC_CMD_FORMAT &&
2646             be32_to_cpu(evt->iu.cmd.cancel_key) == cancel_key)
2647                 return 1;
2648         return 0;
2649 }
2650
2651 /**
2652  * ibmvfc_match_evt - Match function for specified event
2653  * @evt:        ibmvfc event struct
2654  * @match:      event to match
2655  *
2656  * Returns:
2657  *      1 if event matches key / 0 if event does not match key
2658  **/
2659 static int ibmvfc_match_evt(struct ibmvfc_event *evt, void *match)
2660 {
2661         if (evt == match)
2662                 return 1;
2663         return 0;
2664 }
2665
2666 /**
2667  * ibmvfc_abort_task_set - Abort outstanding commands to the device
2668  * @sdev:       scsi device to abort commands
2669  *
2670  * This sends an Abort Task Set to the VIOS for the specified device. This does
2671  * NOT send any cancel to the VIOS. That must be done separately.
2672  *
2673  * Returns:
2674  *      0 on success / other on failure
2675  **/
2676 static int ibmvfc_abort_task_set(struct scsi_device *sdev)
2677 {
2678         struct ibmvfc_host *vhost = shost_priv(sdev->host);
2679         struct fc_rport *rport = starget_to_rport(scsi_target(sdev));
2680         struct ibmvfc_cmd *tmf;
2681         struct ibmvfc_event *evt, *found_evt;
2682         union ibmvfc_iu rsp_iu;
2683         struct ibmvfc_fcp_cmd_iu *iu;
2684         struct ibmvfc_fcp_rsp *fc_rsp = ibmvfc_get_fcp_rsp(vhost, &rsp_iu.cmd);
2685         int rc, rsp_rc = -EBUSY;
2686         unsigned long flags, timeout = IBMVFC_ABORT_TIMEOUT;
2687         int rsp_code = 0;
2688
2689         found_evt = NULL;
2690         spin_lock_irqsave(vhost->host->host_lock, flags);
2691         spin_lock(&vhost->crq.l_lock);
2692         list_for_each_entry(evt, &vhost->crq.sent, queue_list) {
2693                 if (evt->cmnd && evt->cmnd->device == sdev) {
2694                         found_evt = evt;
2695                         break;
2696                 }
2697         }
2698         spin_unlock(&vhost->crq.l_lock);
2699
2700         if (!found_evt) {
2701                 if (vhost->log_level > IBMVFC_DEFAULT_LOG_LEVEL)
2702                         sdev_printk(KERN_INFO, sdev, "No events found to abort\n");
2703                 spin_unlock_irqrestore(vhost->host->host_lock, flags);
2704                 return 0;
2705         }
2706
2707         if (vhost->state == IBMVFC_ACTIVE) {
2708                 evt = ibmvfc_get_event(&vhost->crq);
2709                 ibmvfc_init_event(evt, ibmvfc_sync_completion, IBMVFC_CMD_FORMAT);
2710                 tmf = ibmvfc_init_vfc_cmd(evt, sdev);
2711                 iu = ibmvfc_get_fcp_iu(vhost, tmf);
2712
2713                 if (ibmvfc_check_caps(vhost, IBMVFC_HANDLE_VF_WWPN))
2714                         tmf->target_wwpn = cpu_to_be64(rport->port_name);
2715                 iu->tmf_flags = IBMVFC_ABORT_TASK_SET;
2716                 tmf->flags = cpu_to_be16((IBMVFC_NO_MEM_DESC | IBMVFC_TMF));
2717                 evt->sync_iu = &rsp_iu;
2718
2719                 tmf->correlation = cpu_to_be64((u64)evt);
2720
2721                 init_completion(&evt->comp);
2722                 rsp_rc = ibmvfc_send_event(evt, vhost, default_timeout);
2723         }
2724
2725         spin_unlock_irqrestore(vhost->host->host_lock, flags);
2726
2727         if (rsp_rc != 0) {
2728                 sdev_printk(KERN_ERR, sdev, "Failed to send abort. rc=%d\n", rsp_rc);
2729                 return -EIO;
2730         }
2731
2732         sdev_printk(KERN_INFO, sdev, "Aborting outstanding commands\n");
2733         timeout = wait_for_completion_timeout(&evt->comp, timeout);
2734
2735         if (!timeout) {
2736                 rc = ibmvfc_cancel_all(sdev, 0);
2737                 if (!rc) {
2738                         rc = ibmvfc_wait_for_ops(vhost, sdev->hostdata, ibmvfc_match_key);
2739                         if (rc == SUCCESS)
2740                                 rc = 0;
2741                 }
2742
2743                 if (rc) {
2744                         sdev_printk(KERN_INFO, sdev, "Cancel failed, resetting host\n");
2745                         ibmvfc_reset_host(vhost);
2746                         rsp_rc = -EIO;
2747                         rc = ibmvfc_wait_for_ops(vhost, sdev->hostdata, ibmvfc_match_key);
2748
2749                         if (rc == SUCCESS)
2750                                 rsp_rc = 0;
2751
2752                         rc = ibmvfc_wait_for_ops(vhost, evt, ibmvfc_match_evt);
2753                         if (rc != SUCCESS) {
2754                                 spin_lock_irqsave(vhost->host->host_lock, flags);
2755                                 ibmvfc_hard_reset_host(vhost);
2756                                 spin_unlock_irqrestore(vhost->host->host_lock, flags);
2757                                 rsp_rc = 0;
2758                         }
2759
2760                         goto out;
2761                 }
2762         }
2763
2764         if (rsp_iu.cmd.status)
2765                 rsp_code = ibmvfc_get_err_result(vhost, &rsp_iu.cmd);
2766
2767         if (rsp_code) {
2768                 if (fc_rsp->flags & FCP_RSP_LEN_VALID)
2769                         rsp_code = fc_rsp->data.info.rsp_code;
2770
2771                 sdev_printk(KERN_ERR, sdev, "Abort failed: %s (%x:%x) "
2772                             "flags: %x fcp_rsp: %x, scsi_status: %x\n",
2773                             ibmvfc_get_cmd_error(be16_to_cpu(rsp_iu.cmd.status), be16_to_cpu(rsp_iu.cmd.error)),
2774                             be16_to_cpu(rsp_iu.cmd.status), be16_to_cpu(rsp_iu.cmd.error), fc_rsp->flags, rsp_code,
2775                             fc_rsp->scsi_status);
2776                 rsp_rc = -EIO;
2777         } else
2778                 sdev_printk(KERN_INFO, sdev, "Abort successful\n");
2779
2780 out:
2781         spin_lock_irqsave(vhost->host->host_lock, flags);
2782         ibmvfc_free_event(evt);
2783         spin_unlock_irqrestore(vhost->host->host_lock, flags);
2784         return rsp_rc;
2785 }
2786
2787 /**
2788  * ibmvfc_eh_abort_handler - Abort a command
2789  * @cmd:        scsi command to abort
2790  *
2791  * Returns:
2792  *      SUCCESS / FAST_IO_FAIL / FAILED
2793  **/
2794 static int ibmvfc_eh_abort_handler(struct scsi_cmnd *cmd)
2795 {
2796         struct scsi_device *sdev = cmd->device;
2797         struct ibmvfc_host *vhost = shost_priv(sdev->host);
2798         int cancel_rc, block_rc;
2799         int rc = FAILED;
2800
2801         ENTER;
2802         block_rc = fc_block_scsi_eh(cmd);
2803         ibmvfc_wait_while_resetting(vhost);
2804         if (block_rc != FAST_IO_FAIL) {
2805                 cancel_rc = ibmvfc_cancel_all(sdev, IBMVFC_TMF_ABORT_TASK_SET);
2806                 ibmvfc_abort_task_set(sdev);
2807         } else
2808                 cancel_rc = ibmvfc_cancel_all(sdev, IBMVFC_TMF_SUPPRESS_ABTS);
2809
2810         if (!cancel_rc)
2811                 rc = ibmvfc_wait_for_ops(vhost, sdev, ibmvfc_match_lun);
2812
2813         if (block_rc == FAST_IO_FAIL && rc != FAILED)
2814                 rc = FAST_IO_FAIL;
2815
2816         LEAVE;
2817         return rc;
2818 }
2819
2820 /**
2821  * ibmvfc_eh_device_reset_handler - Reset a single LUN
2822  * @cmd:        scsi command struct
2823  *
2824  * Returns:
2825  *      SUCCESS / FAST_IO_FAIL / FAILED
2826  **/
2827 static int ibmvfc_eh_device_reset_handler(struct scsi_cmnd *cmd)
2828 {
2829         struct scsi_device *sdev = cmd->device;
2830         struct ibmvfc_host *vhost = shost_priv(sdev->host);
2831         int cancel_rc, block_rc, reset_rc = 0;
2832         int rc = FAILED;
2833
2834         ENTER;
2835         block_rc = fc_block_scsi_eh(cmd);
2836         ibmvfc_wait_while_resetting(vhost);
2837         if (block_rc != FAST_IO_FAIL) {
2838                 cancel_rc = ibmvfc_cancel_all(sdev, IBMVFC_TMF_LUN_RESET);
2839                 reset_rc = ibmvfc_reset_device(sdev, IBMVFC_LUN_RESET, "LUN");
2840         } else
2841                 cancel_rc = ibmvfc_cancel_all(sdev, IBMVFC_TMF_SUPPRESS_ABTS);
2842
2843         if (!cancel_rc && !reset_rc)
2844                 rc = ibmvfc_wait_for_ops(vhost, sdev, ibmvfc_match_lun);
2845
2846         if (block_rc == FAST_IO_FAIL && rc != FAILED)
2847                 rc = FAST_IO_FAIL;
2848
2849         LEAVE;
2850         return rc;
2851 }
2852
2853 /**
2854  * ibmvfc_dev_cancel_all_noreset - Device iterated cancel all function
2855  * @sdev:       scsi device struct
2856  * @data:       return code
2857  *
2858  **/
2859 static void ibmvfc_dev_cancel_all_noreset(struct scsi_device *sdev, void *data)
2860 {
2861         unsigned long *rc = data;
2862         *rc |= ibmvfc_cancel_all(sdev, IBMVFC_TMF_SUPPRESS_ABTS);
2863 }
2864
2865 /**
2866  * ibmvfc_dev_cancel_all_reset - Device iterated cancel all function
2867  * @sdev:       scsi device struct
2868  * @data:       return code
2869  *
2870  **/
2871 static void ibmvfc_dev_cancel_all_reset(struct scsi_device *sdev, void *data)
2872 {
2873         unsigned long *rc = data;
2874         *rc |= ibmvfc_cancel_all(sdev, IBMVFC_TMF_TGT_RESET);
2875 }
2876
2877 /**
2878  * ibmvfc_eh_target_reset_handler - Reset the target
2879  * @cmd:        scsi command struct
2880  *
2881  * Returns:
2882  *      SUCCESS / FAST_IO_FAIL / FAILED
2883  **/
2884 static int ibmvfc_eh_target_reset_handler(struct scsi_cmnd *cmd)
2885 {
2886         struct scsi_device *sdev = cmd->device;
2887         struct ibmvfc_host *vhost = shost_priv(sdev->host);
2888         struct scsi_target *starget = scsi_target(sdev);
2889         int block_rc;
2890         int reset_rc = 0;
2891         int rc = FAILED;
2892         unsigned long cancel_rc = 0;
2893
2894         ENTER;
2895         block_rc = fc_block_scsi_eh(cmd);
2896         ibmvfc_wait_while_resetting(vhost);
2897         if (block_rc != FAST_IO_FAIL) {
2898                 starget_for_each_device(starget, &cancel_rc, ibmvfc_dev_cancel_all_reset);
2899                 reset_rc = ibmvfc_reset_device(sdev, IBMVFC_TARGET_RESET, "target");
2900         } else
2901                 starget_for_each_device(starget, &cancel_rc, ibmvfc_dev_cancel_all_noreset);
2902
2903         if (!cancel_rc && !reset_rc)
2904                 rc = ibmvfc_wait_for_ops(vhost, starget, ibmvfc_match_target);
2905
2906         if (block_rc == FAST_IO_FAIL && rc != FAILED)
2907                 rc = FAST_IO_FAIL;
2908
2909         LEAVE;
2910         return rc;
2911 }
2912
2913 /**
2914  * ibmvfc_eh_host_reset_handler - Reset the connection to the server
2915  * @cmd:        struct scsi_cmnd having problems
2916  *
2917  **/
2918 static int ibmvfc_eh_host_reset_handler(struct scsi_cmnd *cmd)
2919 {
2920         int rc;
2921         struct ibmvfc_host *vhost = shost_priv(cmd->device->host);
2922
2923         dev_err(vhost->dev, "Resetting connection due to error recovery\n");
2924         rc = ibmvfc_issue_fc_host_lip(vhost->host);
2925
2926         return rc ? FAILED : SUCCESS;
2927 }
2928
2929 /**
2930  * ibmvfc_terminate_rport_io - Terminate all pending I/O to the rport.
2931  * @rport:              rport struct
2932  *
2933  * Return value:
2934  *      none
2935  **/
2936 static void ibmvfc_terminate_rport_io(struct fc_rport *rport)
2937 {
2938         struct Scsi_Host *shost = rport_to_shost(rport);
2939         struct ibmvfc_host *vhost = shost_priv(shost);
2940         struct fc_rport *dev_rport;
2941         struct scsi_device *sdev;
2942         struct ibmvfc_target *tgt;
2943         unsigned long rc, flags;
2944         unsigned int found;
2945
2946         ENTER;
2947         shost_for_each_device(sdev, shost) {
2948                 dev_rport = starget_to_rport(scsi_target(sdev));
2949                 if (dev_rport != rport)
2950                         continue;
2951                 ibmvfc_cancel_all(sdev, IBMVFC_TMF_SUPPRESS_ABTS);
2952         }
2953
2954         rc = ibmvfc_wait_for_ops(vhost, rport, ibmvfc_match_rport);
2955
2956         if (rc == FAILED)
2957                 ibmvfc_issue_fc_host_lip(shost);
2958
2959         spin_lock_irqsave(shost->host_lock, flags);
2960         found = 0;
2961         list_for_each_entry(tgt, &vhost->targets, queue) {
2962                 if (tgt->scsi_id == rport->port_id) {
2963                         found++;
2964                         break;
2965                 }
2966         }
2967
2968         if (found && tgt->action == IBMVFC_TGT_ACTION_LOGOUT_DELETED_RPORT) {
2969                 /*
2970                  * If we get here, that means we previously attempted to send
2971                  * an implicit logout to the target but it failed, most likely
2972                  * due to I/O being pending, so we need to send it again
2973                  */
2974                 ibmvfc_del_tgt(tgt);
2975                 ibmvfc_reinit_host(vhost);
2976         }
2977
2978         spin_unlock_irqrestore(shost->host_lock, flags);
2979         LEAVE;
2980 }
2981
2982 static const struct ibmvfc_async_desc ae_desc [] = {
2983         { "PLOGI",      IBMVFC_AE_ELS_PLOGI,    IBMVFC_DEFAULT_LOG_LEVEL + 1 },
2984         { "LOGO",       IBMVFC_AE_ELS_LOGO,     IBMVFC_DEFAULT_LOG_LEVEL + 1 },
2985         { "PRLO",       IBMVFC_AE_ELS_PRLO,     IBMVFC_DEFAULT_LOG_LEVEL + 1 },
2986         { "N-Port SCN", IBMVFC_AE_SCN_NPORT,    IBMVFC_DEFAULT_LOG_LEVEL + 1 },
2987         { "Group SCN",  IBMVFC_AE_SCN_GROUP,    IBMVFC_DEFAULT_LOG_LEVEL + 1 },
2988         { "Domain SCN", IBMVFC_AE_SCN_DOMAIN,   IBMVFC_DEFAULT_LOG_LEVEL },
2989         { "Fabric SCN", IBMVFC_AE_SCN_FABRIC,   IBMVFC_DEFAULT_LOG_LEVEL },
2990         { "Link Up",    IBMVFC_AE_LINK_UP,      IBMVFC_DEFAULT_LOG_LEVEL },
2991         { "Link Down",  IBMVFC_AE_LINK_DOWN,    IBMVFC_DEFAULT_LOG_LEVEL },
2992         { "Link Dead",  IBMVFC_AE_LINK_DEAD,    IBMVFC_DEFAULT_LOG_LEVEL },
2993         { "Halt",       IBMVFC_AE_HALT,         IBMVFC_DEFAULT_LOG_LEVEL },
2994         { "Resume",     IBMVFC_AE_RESUME,       IBMVFC_DEFAULT_LOG_LEVEL },
2995         { "Adapter Failed", IBMVFC_AE_ADAPTER_FAILED, IBMVFC_DEFAULT_LOG_LEVEL },
2996 };
2997
2998 static const struct ibmvfc_async_desc unknown_ae = {
2999         "Unknown async", 0, IBMVFC_DEFAULT_LOG_LEVEL
3000 };
3001
3002 /**
3003  * ibmvfc_get_ae_desc - Get text description for async event
3004  * @ae: async event
3005  *
3006  **/
3007 static const struct ibmvfc_async_desc *ibmvfc_get_ae_desc(u64 ae)
3008 {
3009         int i;
3010
3011         for (i = 0; i < ARRAY_SIZE(ae_desc); i++)
3012                 if (ae_desc[i].ae == ae)
3013                         return &ae_desc[i];
3014
3015         return &unknown_ae;
3016 }
3017
3018 static const struct {
3019         enum ibmvfc_ae_link_state state;
3020         const char *desc;
3021 } link_desc [] = {
3022         { IBMVFC_AE_LS_LINK_UP,         " link up" },
3023         { IBMVFC_AE_LS_LINK_BOUNCED,    " link bounced" },
3024         { IBMVFC_AE_LS_LINK_DOWN,       " link down" },
3025         { IBMVFC_AE_LS_LINK_DEAD,       " link dead" },
3026 };
3027
3028 /**
3029  * ibmvfc_get_link_state - Get text description for link state
3030  * @state:      link state
3031  *
3032  **/
3033 static const char *ibmvfc_get_link_state(enum ibmvfc_ae_link_state state)
3034 {
3035         int i;
3036
3037         for (i = 0; i < ARRAY_SIZE(link_desc); i++)
3038                 if (link_desc[i].state == state)
3039                         return link_desc[i].desc;
3040
3041         return "";
3042 }
3043
3044 /**
3045  * ibmvfc_handle_async - Handle an async event from the adapter
3046  * @crq:        crq to process
3047  * @vhost:      ibmvfc host struct
3048  *
3049  **/
3050 static void ibmvfc_handle_async(struct ibmvfc_async_crq *crq,
3051                                 struct ibmvfc_host *vhost)
3052 {
3053         const struct ibmvfc_async_desc *desc = ibmvfc_get_ae_desc(be64_to_cpu(crq->event));
3054         struct ibmvfc_target *tgt;
3055
3056         ibmvfc_log(vhost, desc->log_level, "%s event received. scsi_id: %llx, wwpn: %llx,"
3057                    " node_name: %llx%s\n", desc->desc, be64_to_cpu(crq->scsi_id),
3058                    be64_to_cpu(crq->wwpn), be64_to_cpu(crq->node_name),
3059                    ibmvfc_get_link_state(crq->link_state));
3060
3061         switch (be64_to_cpu(crq->event)) {
3062         case IBMVFC_AE_RESUME:
3063                 switch (crq->link_state) {
3064                 case IBMVFC_AE_LS_LINK_DOWN:
3065                         ibmvfc_link_down(vhost, IBMVFC_LINK_DOWN);
3066                         break;
3067                 case IBMVFC_AE_LS_LINK_DEAD:
3068                         ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
3069                         break;
3070                 case IBMVFC_AE_LS_LINK_UP:
3071                 case IBMVFC_AE_LS_LINK_BOUNCED:
3072                 default:
3073                         vhost->events_to_log |= IBMVFC_AE_LINKUP;
3074                         vhost->delay_init = 1;
3075                         __ibmvfc_reset_host(vhost);
3076                         break;
3077                 }
3078
3079                 break;
3080         case IBMVFC_AE_LINK_UP:
3081                 vhost->events_to_log |= IBMVFC_AE_LINKUP;
3082                 vhost->delay_init = 1;
3083                 __ibmvfc_reset_host(vhost);
3084                 break;
3085         case IBMVFC_AE_SCN_FABRIC:
3086         case IBMVFC_AE_SCN_DOMAIN:
3087                 vhost->events_to_log |= IBMVFC_AE_RSCN;
3088                 if (vhost->state < IBMVFC_HALTED) {
3089                         vhost->delay_init = 1;
3090                         __ibmvfc_reset_host(vhost);
3091                 }
3092                 break;
3093         case IBMVFC_AE_SCN_NPORT:
3094         case IBMVFC_AE_SCN_GROUP:
3095                 vhost->events_to_log |= IBMVFC_AE_RSCN;
3096                 ibmvfc_reinit_host(vhost);
3097                 break;
3098         case IBMVFC_AE_ELS_LOGO:
3099         case IBMVFC_AE_ELS_PRLO:
3100         case IBMVFC_AE_ELS_PLOGI:
3101                 list_for_each_entry(tgt, &vhost->targets, queue) {
3102                         if (!crq->scsi_id && !crq->wwpn && !crq->node_name)
3103                                 break;
3104                         if (crq->scsi_id && cpu_to_be64(tgt->scsi_id) != crq->scsi_id)
3105                                 continue;
3106                         if (crq->wwpn && cpu_to_be64(tgt->ids.port_name) != crq->wwpn)
3107                                 continue;
3108                         if (crq->node_name && cpu_to_be64(tgt->ids.node_name) != crq->node_name)
3109                                 continue;
3110                         if (tgt->need_login && be64_to_cpu(crq->event) == IBMVFC_AE_ELS_LOGO)
3111                                 tgt->logo_rcvd = 1;
3112                         if (!tgt->need_login || be64_to_cpu(crq->event) == IBMVFC_AE_ELS_PLOGI) {
3113                                 ibmvfc_del_tgt(tgt);
3114                                 ibmvfc_reinit_host(vhost);
3115                         }
3116                 }
3117                 break;
3118         case IBMVFC_AE_LINK_DOWN:
3119         case IBMVFC_AE_ADAPTER_FAILED:
3120                 ibmvfc_link_down(vhost, IBMVFC_LINK_DOWN);
3121                 break;
3122         case IBMVFC_AE_LINK_DEAD:
3123                 ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
3124                 break;
3125         case IBMVFC_AE_HALT:
3126                 ibmvfc_link_down(vhost, IBMVFC_HALTED);
3127                 break;
3128         default:
3129                 dev_err(vhost->dev, "Unknown async event received: %lld\n", crq->event);
3130                 break;
3131         }
3132 }
3133
3134 /**
3135  * ibmvfc_handle_crq - Handles and frees received events in the CRQ
3136  * @crq:        Command/Response queue
3137  * @vhost:      ibmvfc host struct
3138  *
3139  **/
3140 static void ibmvfc_handle_crq(struct ibmvfc_crq *crq, struct ibmvfc_host *vhost,
3141                               struct list_head *evt_doneq)
3142 {
3143         long rc;
3144         struct ibmvfc_event *evt = (struct ibmvfc_event *)be64_to_cpu(crq->ioba);
3145
3146         switch (crq->valid) {
3147         case IBMVFC_CRQ_INIT_RSP:
3148                 switch (crq->format) {
3149                 case IBMVFC_CRQ_INIT:
3150                         dev_info(vhost->dev, "Partner initialized\n");
3151                         /* Send back a response */
3152                         rc = ibmvfc_send_crq_init_complete(vhost);
3153                         if (rc == 0)
3154                                 ibmvfc_init_host(vhost);
3155                         else
3156                                 dev_err(vhost->dev, "Unable to send init rsp. rc=%ld\n", rc);
3157                         break;
3158                 case IBMVFC_CRQ_INIT_COMPLETE:
3159                         dev_info(vhost->dev, "Partner initialization complete\n");
3160                         ibmvfc_init_host(vhost);
3161                         break;
3162                 default:
3163                         dev_err(vhost->dev, "Unknown crq message type: %d\n", crq->format);
3164                 }
3165                 return;
3166         case IBMVFC_CRQ_XPORT_EVENT:
3167                 vhost->state = IBMVFC_NO_CRQ;
3168                 vhost->logged_in = 0;
3169                 ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_NONE);
3170                 if (crq->format == IBMVFC_PARTITION_MIGRATED) {
3171                         /* We need to re-setup the interpartition connection */
3172                         dev_info(vhost->dev, "Partition migrated, Re-enabling adapter\n");
3173                         vhost->client_migrated = 1;
3174                         ibmvfc_purge_requests(vhost, DID_REQUEUE);
3175                         ibmvfc_link_down(vhost, IBMVFC_LINK_DOWN);
3176                         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_REENABLE);
3177                 } else if (crq->format == IBMVFC_PARTNER_FAILED || crq->format == IBMVFC_PARTNER_DEREGISTER) {
3178                         dev_err(vhost->dev, "Host partner adapter deregistered or failed (rc=%d)\n", crq->format);
3179                         ibmvfc_purge_requests(vhost, DID_ERROR);
3180                         ibmvfc_link_down(vhost, IBMVFC_LINK_DOWN);
3181                         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_RESET);
3182                 } else {
3183                         dev_err(vhost->dev, "Received unknown transport event from partner (rc=%d)\n", crq->format);
3184                 }
3185                 return;
3186         case IBMVFC_CRQ_CMD_RSP:
3187                 break;
3188         default:
3189                 dev_err(vhost->dev, "Got an invalid message type 0x%02x\n", crq->valid);
3190                 return;
3191         }
3192
3193         if (crq->format == IBMVFC_ASYNC_EVENT)
3194                 return;
3195
3196         /* The only kind of payload CRQs we should get are responses to
3197          * things we send. Make sure this response is to something we
3198          * actually sent
3199          */
3200         if (unlikely(!ibmvfc_valid_event(&vhost->crq.evt_pool, evt))) {
3201                 dev_err(vhost->dev, "Returned correlation_token 0x%08llx is invalid!\n",
3202                         crq->ioba);
3203                 return;
3204         }
3205
3206         if (unlikely(atomic_read(&evt->free))) {
3207                 dev_err(vhost->dev, "Received duplicate correlation_token 0x%08llx!\n",
3208                         crq->ioba);
3209                 return;
3210         }
3211
3212         spin_lock(&evt->queue->l_lock);
3213         list_move_tail(&evt->queue_list, evt_doneq);
3214         spin_unlock(&evt->queue->l_lock);
3215 }
3216
3217 /**
3218  * ibmvfc_scan_finished - Check if the device scan is done.
3219  * @shost:      scsi host struct
3220  * @time:       current elapsed time
3221  *
3222  * Returns:
3223  *      0 if scan is not done / 1 if scan is done
3224  **/
3225 static int ibmvfc_scan_finished(struct Scsi_Host *shost, unsigned long time)
3226 {
3227         unsigned long flags;
3228         struct ibmvfc_host *vhost = shost_priv(shost);
3229         int done = 0;
3230
3231         spin_lock_irqsave(shost->host_lock, flags);
3232         if (time >= (init_timeout * HZ)) {
3233                 dev_info(vhost->dev, "Scan taking longer than %d seconds, "
3234                          "continuing initialization\n", init_timeout);
3235                 done = 1;
3236         }
3237
3238         if (vhost->scan_complete)
3239                 done = 1;
3240         spin_unlock_irqrestore(shost->host_lock, flags);
3241         return done;
3242 }
3243
3244 /**
3245  * ibmvfc_slave_alloc - Setup the device's task set value
3246  * @sdev:       struct scsi_device device to configure
3247  *
3248  * Set the device's task set value so that error handling works as
3249  * expected.
3250  *
3251  * Returns:
3252  *      0 on success / -ENXIO if device does not exist
3253  **/
3254 static int ibmvfc_slave_alloc(struct scsi_device *sdev)
3255 {
3256         struct Scsi_Host *shost = sdev->host;
3257         struct fc_rport *rport = starget_to_rport(scsi_target(sdev));
3258         struct ibmvfc_host *vhost = shost_priv(shost);
3259         unsigned long flags = 0;
3260
3261         if (!rport || fc_remote_port_chkready(rport))
3262                 return -ENXIO;
3263
3264         spin_lock_irqsave(shost->host_lock, flags);
3265         sdev->hostdata = (void *)(unsigned long)vhost->task_set++;
3266         spin_unlock_irqrestore(shost->host_lock, flags);
3267         return 0;
3268 }
3269
3270 /**
3271  * ibmvfc_target_alloc - Setup the target's task set value
3272  * @starget:    struct scsi_target
3273  *
3274  * Set the target's task set value so that error handling works as
3275  * expected.
3276  *
3277  * Returns:
3278  *      0 on success / -ENXIO if device does not exist
3279  **/
3280 static int ibmvfc_target_alloc(struct scsi_target *starget)
3281 {
3282         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
3283         struct ibmvfc_host *vhost = shost_priv(shost);
3284         unsigned long flags = 0;
3285
3286         spin_lock_irqsave(shost->host_lock, flags);
3287         starget->hostdata = (void *)(unsigned long)vhost->task_set++;
3288         spin_unlock_irqrestore(shost->host_lock, flags);
3289         return 0;
3290 }
3291
3292 /**
3293  * ibmvfc_slave_configure - Configure the device
3294  * @sdev:       struct scsi_device device to configure
3295  *
3296  * Enable allow_restart for a device if it is a disk. Adjust the
3297  * queue_depth here also.
3298  *
3299  * Returns:
3300  *      0
3301  **/
3302 static int ibmvfc_slave_configure(struct scsi_device *sdev)
3303 {
3304         struct Scsi_Host *shost = sdev->host;
3305         unsigned long flags = 0;
3306
3307         spin_lock_irqsave(shost->host_lock, flags);
3308         if (sdev->type == TYPE_DISK) {
3309                 sdev->allow_restart = 1;
3310                 blk_queue_rq_timeout(sdev->request_queue, 120 * HZ);
3311         }
3312         spin_unlock_irqrestore(shost->host_lock, flags);
3313         return 0;
3314 }
3315
3316 /**
3317  * ibmvfc_change_queue_depth - Change the device's queue depth
3318  * @sdev:       scsi device struct
3319  * @qdepth:     depth to set
3320  * @reason:     calling context
3321  *
3322  * Return value:
3323  *      actual depth set
3324  **/
3325 static int ibmvfc_change_queue_depth(struct scsi_device *sdev, int qdepth)
3326 {
3327         if (qdepth > IBMVFC_MAX_CMDS_PER_LUN)
3328                 qdepth = IBMVFC_MAX_CMDS_PER_LUN;
3329
3330         return scsi_change_queue_depth(sdev, qdepth);
3331 }
3332
3333 static ssize_t ibmvfc_show_host_partition_name(struct device *dev,
3334                                                  struct device_attribute *attr, char *buf)
3335 {
3336         struct Scsi_Host *shost = class_to_shost(dev);
3337         struct ibmvfc_host *vhost = shost_priv(shost);
3338
3339         return snprintf(buf, PAGE_SIZE, "%s\n",
3340                         vhost->login_buf->resp.partition_name);
3341 }
3342
3343 static ssize_t ibmvfc_show_host_device_name(struct device *dev,
3344                                             struct device_attribute *attr, char *buf)
3345 {
3346         struct Scsi_Host *shost = class_to_shost(dev);
3347         struct ibmvfc_host *vhost = shost_priv(shost);
3348
3349         return snprintf(buf, PAGE_SIZE, "%s\n",
3350                         vhost->login_buf->resp.device_name);
3351 }
3352
3353 static ssize_t ibmvfc_show_host_loc_code(struct device *dev,
3354                                          struct device_attribute *attr, char *buf)
3355 {
3356         struct Scsi_Host *shost = class_to_shost(dev);
3357         struct ibmvfc_host *vhost = shost_priv(shost);
3358
3359         return snprintf(buf, PAGE_SIZE, "%s\n",
3360                         vhost->login_buf->resp.port_loc_code);
3361 }
3362
3363 static ssize_t ibmvfc_show_host_drc_name(struct device *dev,
3364                                          struct device_attribute *attr, char *buf)
3365 {
3366         struct Scsi_Host *shost = class_to_shost(dev);
3367         struct ibmvfc_host *vhost = shost_priv(shost);
3368
3369         return snprintf(buf, PAGE_SIZE, "%s\n",
3370                         vhost->login_buf->resp.drc_name);
3371 }
3372
3373 static ssize_t ibmvfc_show_host_npiv_version(struct device *dev,
3374                                              struct device_attribute *attr, char *buf)
3375 {
3376         struct Scsi_Host *shost = class_to_shost(dev);
3377         struct ibmvfc_host *vhost = shost_priv(shost);
3378         return snprintf(buf, PAGE_SIZE, "%d\n", be32_to_cpu(vhost->login_buf->resp.version));
3379 }
3380
3381 static ssize_t ibmvfc_show_host_capabilities(struct device *dev,
3382                                              struct device_attribute *attr, char *buf)
3383 {
3384         struct Scsi_Host *shost = class_to_shost(dev);
3385         struct ibmvfc_host *vhost = shost_priv(shost);
3386         return snprintf(buf, PAGE_SIZE, "%llx\n", be64_to_cpu(vhost->login_buf->resp.capabilities));
3387 }
3388
3389 /**
3390  * ibmvfc_show_log_level - Show the adapter's error logging level
3391  * @dev:        class device struct
3392  * @buf:        buffer
3393  *
3394  * Return value:
3395  *      number of bytes printed to buffer
3396  **/
3397 static ssize_t ibmvfc_show_log_level(struct device *dev,
3398                                      struct device_attribute *attr, char *buf)
3399 {
3400         struct Scsi_Host *shost = class_to_shost(dev);
3401         struct ibmvfc_host *vhost = shost_priv(shost);
3402         unsigned long flags = 0;
3403         int len;
3404
3405         spin_lock_irqsave(shost->host_lock, flags);
3406         len = snprintf(buf, PAGE_SIZE, "%d\n", vhost->log_level);
3407         spin_unlock_irqrestore(shost->host_lock, flags);
3408         return len;
3409 }
3410
3411 /**
3412  * ibmvfc_store_log_level - Change the adapter's error logging level
3413  * @dev:        class device struct
3414  * @buf:        buffer
3415  *
3416  * Return value:
3417  *      number of bytes printed to buffer
3418  **/
3419 static ssize_t ibmvfc_store_log_level(struct device *dev,
3420                                       struct device_attribute *attr,
3421                                       const char *buf, size_t count)
3422 {
3423         struct Scsi_Host *shost = class_to_shost(dev);
3424         struct ibmvfc_host *vhost = shost_priv(shost);
3425         unsigned long flags = 0;
3426
3427         spin_lock_irqsave(shost->host_lock, flags);
3428         vhost->log_level = simple_strtoul(buf, NULL, 10);
3429         spin_unlock_irqrestore(shost->host_lock, flags);
3430         return strlen(buf);
3431 }
3432
3433 static ssize_t ibmvfc_show_scsi_channels(struct device *dev,
3434                                          struct device_attribute *attr, char *buf)
3435 {
3436         struct Scsi_Host *shost = class_to_shost(dev);
3437         struct ibmvfc_host *vhost = shost_priv(shost);
3438         unsigned long flags = 0;
3439         int len;
3440
3441         spin_lock_irqsave(shost->host_lock, flags);
3442         len = snprintf(buf, PAGE_SIZE, "%d\n", vhost->client_scsi_channels);
3443         spin_unlock_irqrestore(shost->host_lock, flags);
3444         return len;
3445 }
3446
3447 static ssize_t ibmvfc_store_scsi_channels(struct device *dev,
3448                                          struct device_attribute *attr,
3449                                          const char *buf, size_t count)
3450 {
3451         struct Scsi_Host *shost = class_to_shost(dev);
3452         struct ibmvfc_host *vhost = shost_priv(shost);
3453         unsigned long flags = 0;
3454         unsigned int channels;
3455
3456         spin_lock_irqsave(shost->host_lock, flags);
3457         channels = simple_strtoul(buf, NULL, 10);
3458         vhost->client_scsi_channels = min(channels, nr_scsi_hw_queues);
3459         ibmvfc_hard_reset_host(vhost);
3460         spin_unlock_irqrestore(shost->host_lock, flags);
3461         return strlen(buf);
3462 }
3463
3464 static DEVICE_ATTR(partition_name, S_IRUGO, ibmvfc_show_host_partition_name, NULL);
3465 static DEVICE_ATTR(device_name, S_IRUGO, ibmvfc_show_host_device_name, NULL);
3466 static DEVICE_ATTR(port_loc_code, S_IRUGO, ibmvfc_show_host_loc_code, NULL);
3467 static DEVICE_ATTR(drc_name, S_IRUGO, ibmvfc_show_host_drc_name, NULL);
3468 static DEVICE_ATTR(npiv_version, S_IRUGO, ibmvfc_show_host_npiv_version, NULL);
3469 static DEVICE_ATTR(capabilities, S_IRUGO, ibmvfc_show_host_capabilities, NULL);
3470 static DEVICE_ATTR(log_level, S_IRUGO | S_IWUSR,
3471                    ibmvfc_show_log_level, ibmvfc_store_log_level);
3472 static DEVICE_ATTR(nr_scsi_channels, S_IRUGO | S_IWUSR,
3473                    ibmvfc_show_scsi_channels, ibmvfc_store_scsi_channels);
3474
3475 #ifdef CONFIG_SCSI_IBMVFC_TRACE
3476 /**
3477  * ibmvfc_read_trace - Dump the adapter trace
3478  * @filp:               open sysfs file
3479  * @kobj:               kobject struct
3480  * @bin_attr:   bin_attribute struct
3481  * @buf:                buffer
3482  * @off:                offset
3483  * @count:              buffer size
3484  *
3485  * Return value:
3486  *      number of bytes printed to buffer
3487  **/
3488 static ssize_t ibmvfc_read_trace(struct file *filp, struct kobject *kobj,
3489                                  struct bin_attribute *bin_attr,
3490                                  char *buf, loff_t off, size_t count)
3491 {
3492         struct device *dev = container_of(kobj, struct device, kobj);
3493         struct Scsi_Host *shost = class_to_shost(dev);
3494         struct ibmvfc_host *vhost = shost_priv(shost);
3495         unsigned long flags = 0;
3496         int size = IBMVFC_TRACE_SIZE;
3497         char *src = (char *)vhost->trace;
3498
3499         if (off > size)
3500                 return 0;
3501         if (off + count > size) {
3502                 size -= off;
3503                 count = size;
3504         }
3505
3506         spin_lock_irqsave(shost->host_lock, flags);
3507         memcpy(buf, &src[off], count);
3508         spin_unlock_irqrestore(shost->host_lock, flags);
3509         return count;
3510 }
3511
3512 static struct bin_attribute ibmvfc_trace_attr = {
3513         .attr = {
3514                 .name = "trace",
3515                 .mode = S_IRUGO,
3516         },
3517         .size = 0,
3518         .read = ibmvfc_read_trace,
3519 };
3520 #endif
3521
3522 static struct device_attribute *ibmvfc_attrs[] = {
3523         &dev_attr_partition_name,
3524         &dev_attr_device_name,
3525         &dev_attr_port_loc_code,
3526         &dev_attr_drc_name,
3527         &dev_attr_npiv_version,
3528         &dev_attr_capabilities,
3529         &dev_attr_log_level,
3530         &dev_attr_nr_scsi_channels,
3531         NULL
3532 };
3533
3534 static struct scsi_host_template driver_template = {
3535         .module = THIS_MODULE,
3536         .name = "IBM POWER Virtual FC Adapter",
3537         .proc_name = IBMVFC_NAME,
3538         .queuecommand = ibmvfc_queuecommand,
3539         .eh_timed_out = fc_eh_timed_out,
3540         .eh_abort_handler = ibmvfc_eh_abort_handler,
3541         .eh_device_reset_handler = ibmvfc_eh_device_reset_handler,
3542         .eh_target_reset_handler = ibmvfc_eh_target_reset_handler,
3543         .eh_host_reset_handler = ibmvfc_eh_host_reset_handler,
3544         .slave_alloc = ibmvfc_slave_alloc,
3545         .slave_configure = ibmvfc_slave_configure,
3546         .target_alloc = ibmvfc_target_alloc,
3547         .scan_finished = ibmvfc_scan_finished,
3548         .change_queue_depth = ibmvfc_change_queue_depth,
3549         .cmd_per_lun = 16,
3550         .can_queue = IBMVFC_MAX_REQUESTS_DEFAULT,
3551         .this_id = -1,
3552         .sg_tablesize = SG_ALL,
3553         .max_sectors = IBMVFC_MAX_SECTORS,
3554         .shost_attrs = ibmvfc_attrs,
3555         .track_queue_depth = 1,
3556         .host_tagset = 1,
3557 };
3558
3559 /**
3560  * ibmvfc_next_async_crq - Returns the next entry in async queue
3561  * @vhost:      ibmvfc host struct
3562  *
3563  * Returns:
3564  *      Pointer to next entry in queue / NULL if empty
3565  **/
3566 static struct ibmvfc_async_crq *ibmvfc_next_async_crq(struct ibmvfc_host *vhost)
3567 {
3568         struct ibmvfc_queue *async_crq = &vhost->async_crq;
3569         struct ibmvfc_async_crq *crq;
3570
3571         crq = &async_crq->msgs.async[async_crq->cur];
3572         if (crq->valid & 0x80) {
3573                 if (++async_crq->cur == async_crq->size)
3574                         async_crq->cur = 0;
3575                 rmb();
3576         } else
3577                 crq = NULL;
3578
3579         return crq;
3580 }
3581
3582 /**
3583  * ibmvfc_next_crq - Returns the next entry in message queue
3584  * @vhost:      ibmvfc host struct
3585  *
3586  * Returns:
3587  *      Pointer to next entry in queue / NULL if empty
3588  **/
3589 static struct ibmvfc_crq *ibmvfc_next_crq(struct ibmvfc_host *vhost)
3590 {
3591         struct ibmvfc_queue *queue = &vhost->crq;
3592         struct ibmvfc_crq *crq;
3593
3594         crq = &queue->msgs.crq[queue->cur];
3595         if (crq->valid & 0x80) {
3596                 if (++queue->cur == queue->size)
3597                         queue->cur = 0;
3598                 rmb();
3599         } else
3600                 crq = NULL;
3601
3602         return crq;
3603 }
3604
3605 /**
3606  * ibmvfc_interrupt - Interrupt handler
3607  * @irq:                number of irq to handle, not used
3608  * @dev_instance: ibmvfc_host that received interrupt
3609  *
3610  * Returns:
3611  *      IRQ_HANDLED
3612  **/
3613 static irqreturn_t ibmvfc_interrupt(int irq, void *dev_instance)
3614 {
3615         struct ibmvfc_host *vhost = (struct ibmvfc_host *)dev_instance;
3616         unsigned long flags;
3617
3618         spin_lock_irqsave(vhost->host->host_lock, flags);
3619         vio_disable_interrupts(to_vio_dev(vhost->dev));
3620         tasklet_schedule(&vhost->tasklet);
3621         spin_unlock_irqrestore(vhost->host->host_lock, flags);
3622         return IRQ_HANDLED;
3623 }
3624
3625 /**
3626  * ibmvfc_tasklet - Interrupt handler tasklet
3627  * @data:               ibmvfc host struct
3628  *
3629  * Returns:
3630  *      Nothing
3631  **/
3632 static void ibmvfc_tasklet(void *data)
3633 {
3634         struct ibmvfc_host *vhost = data;
3635         struct vio_dev *vdev = to_vio_dev(vhost->dev);
3636         struct ibmvfc_crq *crq;
3637         struct ibmvfc_async_crq *async;
3638         struct ibmvfc_event *evt, *temp;
3639         unsigned long flags;
3640         int done = 0;
3641         LIST_HEAD(evt_doneq);
3642
3643         spin_lock_irqsave(vhost->host->host_lock, flags);
3644         spin_lock(vhost->crq.q_lock);
3645         while (!done) {
3646                 /* Pull all the valid messages off the async CRQ */
3647                 while ((async = ibmvfc_next_async_crq(vhost)) != NULL) {
3648                         ibmvfc_handle_async(async, vhost);
3649                         async->valid = 0;
3650                         wmb();
3651                 }
3652
3653                 /* Pull all the valid messages off the CRQ */
3654                 while ((crq = ibmvfc_next_crq(vhost)) != NULL) {
3655                         ibmvfc_handle_crq(crq, vhost, &evt_doneq);
3656                         crq->valid = 0;
3657                         wmb();
3658                 }
3659
3660                 vio_enable_interrupts(vdev);
3661                 if ((async = ibmvfc_next_async_crq(vhost)) != NULL) {
3662                         vio_disable_interrupts(vdev);
3663                         ibmvfc_handle_async(async, vhost);
3664                         async->valid = 0;
3665                         wmb();
3666                 } else if ((crq = ibmvfc_next_crq(vhost)) != NULL) {
3667                         vio_disable_interrupts(vdev);
3668                         ibmvfc_handle_crq(crq, vhost, &evt_doneq);
3669                         crq->valid = 0;
3670                         wmb();
3671                 } else
3672                         done = 1;
3673         }
3674
3675         spin_unlock(vhost->crq.q_lock);
3676         spin_unlock_irqrestore(vhost->host->host_lock, flags);
3677
3678         list_for_each_entry_safe(evt, temp, &evt_doneq, queue_list) {
3679                 del_timer(&evt->timer);
3680                 list_del(&evt->queue_list);
3681                 ibmvfc_trc_end(evt);
3682                 evt->done(evt);
3683         }
3684 }
3685
3686 static int ibmvfc_toggle_scrq_irq(struct ibmvfc_queue *scrq, int enable)
3687 {
3688         struct device *dev = scrq->vhost->dev;
3689         struct vio_dev *vdev = to_vio_dev(dev);
3690         unsigned long rc;
3691         int irq_action = H_ENABLE_VIO_INTERRUPT;
3692
3693         if (!enable)
3694                 irq_action = H_DISABLE_VIO_INTERRUPT;
3695
3696         rc = plpar_hcall_norets(H_VIOCTL, vdev->unit_address, irq_action,
3697                                 scrq->hw_irq, 0, 0);
3698
3699         if (rc)
3700                 dev_err(dev, "Couldn't %s sub-crq[%lu] irq. rc=%ld\n",
3701                         enable ? "enable" : "disable", scrq->hwq_id, rc);
3702
3703         return rc;
3704 }
3705
3706 static void ibmvfc_handle_scrq(struct ibmvfc_crq *crq, struct ibmvfc_host *vhost,
3707                                struct list_head *evt_doneq)
3708 {
3709         struct ibmvfc_event *evt = (struct ibmvfc_event *)be64_to_cpu(crq->ioba);
3710
3711         switch (crq->valid) {
3712         case IBMVFC_CRQ_CMD_RSP:
3713                 break;
3714         case IBMVFC_CRQ_XPORT_EVENT:
3715                 return;
3716         default:
3717                 dev_err(vhost->dev, "Got and invalid message type 0x%02x\n", crq->valid);
3718                 return;
3719         }
3720
3721         /* The only kind of payload CRQs we should get are responses to
3722          * things we send. Make sure this response is to something we
3723          * actually sent
3724          */
3725         if (unlikely(!ibmvfc_valid_event(&evt->queue->evt_pool, evt))) {
3726                 dev_err(vhost->dev, "Returned correlation_token 0x%08llx is invalid!\n",
3727                         crq->ioba);
3728                 return;
3729         }
3730
3731         if (unlikely(atomic_read(&evt->free))) {
3732                 dev_err(vhost->dev, "Received duplicate correlation_token 0x%08llx!\n",
3733                         crq->ioba);
3734                 return;
3735         }
3736
3737         spin_lock(&evt->queue->l_lock);
3738         list_move_tail(&evt->queue_list, evt_doneq);
3739         spin_unlock(&evt->queue->l_lock);
3740 }
3741
3742 static struct ibmvfc_crq *ibmvfc_next_scrq(struct ibmvfc_queue *scrq)
3743 {
3744         struct ibmvfc_crq *crq;
3745
3746         crq = &scrq->msgs.scrq[scrq->cur].crq;
3747         if (crq->valid & 0x80) {
3748                 if (++scrq->cur == scrq->size)
3749                         scrq->cur = 0;
3750                 rmb();
3751         } else
3752                 crq = NULL;
3753
3754         return crq;
3755 }
3756
3757 static void ibmvfc_drain_sub_crq(struct ibmvfc_queue *scrq)
3758 {
3759         struct ibmvfc_crq *crq;
3760         struct ibmvfc_event *evt, *temp;
3761         unsigned long flags;
3762         int done = 0;
3763         LIST_HEAD(evt_doneq);
3764
3765         spin_lock_irqsave(scrq->q_lock, flags);
3766         while (!done) {
3767                 while ((crq = ibmvfc_next_scrq(scrq)) != NULL) {
3768                         ibmvfc_handle_scrq(crq, scrq->vhost, &evt_doneq);
3769                         crq->valid = 0;
3770                         wmb();
3771                 }
3772
3773                 ibmvfc_toggle_scrq_irq(scrq, 1);
3774                 if ((crq = ibmvfc_next_scrq(scrq)) != NULL) {
3775                         ibmvfc_toggle_scrq_irq(scrq, 0);
3776                         ibmvfc_handle_scrq(crq, scrq->vhost, &evt_doneq);
3777                         crq->valid = 0;
3778                         wmb();
3779                 } else
3780                         done = 1;
3781         }
3782         spin_unlock_irqrestore(scrq->q_lock, flags);
3783
3784         list_for_each_entry_safe(evt, temp, &evt_doneq, queue_list) {
3785                 del_timer(&evt->timer);
3786                 list_del(&evt->queue_list);
3787                 ibmvfc_trc_end(evt);
3788                 evt->done(evt);
3789         }
3790 }
3791
3792 static irqreturn_t ibmvfc_interrupt_scsi(int irq, void *scrq_instance)
3793 {
3794         struct ibmvfc_queue *scrq = (struct ibmvfc_queue *)scrq_instance;
3795
3796         ibmvfc_toggle_scrq_irq(scrq, 0);
3797         ibmvfc_drain_sub_crq(scrq);
3798
3799         return IRQ_HANDLED;
3800 }
3801
3802 /**
3803  * ibmvfc_init_tgt - Set the next init job step for the target
3804  * @tgt:                ibmvfc target struct
3805  * @job_step:   job step to perform
3806  *
3807  **/
3808 static void ibmvfc_init_tgt(struct ibmvfc_target *tgt,
3809                             void (*job_step) (struct ibmvfc_target *))
3810 {
3811         if (!ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_INIT))
3812                 tgt->job_step = job_step;
3813         wake_up(&tgt->vhost->work_wait_q);
3814 }
3815
3816 /**
3817  * ibmvfc_retry_tgt_init - Attempt to retry a step in target initialization
3818  * @tgt:                ibmvfc target struct
3819  * @job_step:   initialization job step
3820  *
3821  * Returns: 1 if step will be retried / 0 if not
3822  *
3823  **/
3824 static int ibmvfc_retry_tgt_init(struct ibmvfc_target *tgt,
3825                                   void (*job_step) (struct ibmvfc_target *))
3826 {
3827         if (++tgt->init_retries > IBMVFC_MAX_TGT_INIT_RETRIES) {
3828                 ibmvfc_del_tgt(tgt);
3829                 wake_up(&tgt->vhost->work_wait_q);
3830                 return 0;
3831         } else
3832                 ibmvfc_init_tgt(tgt, job_step);
3833         return 1;
3834 }
3835
3836 /* Defined in FC-LS */
3837 static const struct {
3838         int code;
3839         int retry;
3840         int logged_in;
3841 } prli_rsp [] = {
3842         { 0, 1, 0 },
3843         { 1, 0, 1 },
3844         { 2, 1, 0 },
3845         { 3, 1, 0 },
3846         { 4, 0, 0 },
3847         { 5, 0, 0 },
3848         { 6, 0, 1 },
3849         { 7, 0, 0 },
3850         { 8, 1, 0 },
3851 };
3852
3853 /**
3854  * ibmvfc_get_prli_rsp - Find PRLI response index
3855  * @flags:      PRLI response flags
3856  *
3857  **/
3858 static int ibmvfc_get_prli_rsp(u16 flags)
3859 {
3860         int i;
3861         int code = (flags & 0x0f00) >> 8;
3862
3863         for (i = 0; i < ARRAY_SIZE(prli_rsp); i++)
3864                 if (prli_rsp[i].code == code)
3865                         return i;
3866
3867         return 0;
3868 }
3869
3870 /**
3871  * ibmvfc_tgt_prli_done - Completion handler for Process Login
3872  * @evt:        ibmvfc event struct
3873  *
3874  **/
3875 static void ibmvfc_tgt_prli_done(struct ibmvfc_event *evt)
3876 {
3877         struct ibmvfc_target *tgt = evt->tgt;
3878         struct ibmvfc_host *vhost = evt->vhost;
3879         struct ibmvfc_process_login *rsp = &evt->xfer_iu->prli;
3880         struct ibmvfc_prli_svc_parms *parms = &rsp->parms;
3881         u32 status = be16_to_cpu(rsp->common.status);
3882         int index, level = IBMVFC_DEFAULT_LOG_LEVEL;
3883
3884         vhost->discovery_threads--;
3885         ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_NONE);
3886         switch (status) {
3887         case IBMVFC_MAD_SUCCESS:
3888                 tgt_dbg(tgt, "Process Login succeeded: %X %02X %04X\n",
3889                         parms->type, parms->flags, parms->service_parms);
3890
3891                 if (parms->type == IBMVFC_SCSI_FCP_TYPE) {
3892                         index = ibmvfc_get_prli_rsp(be16_to_cpu(parms->flags));
3893                         if (prli_rsp[index].logged_in) {
3894                                 if (be16_to_cpu(parms->flags) & IBMVFC_PRLI_EST_IMG_PAIR) {
3895                                         tgt->need_login = 0;
3896                                         tgt->ids.roles = 0;
3897                                         if (be32_to_cpu(parms->service_parms) & IBMVFC_PRLI_TARGET_FUNC)
3898                                                 tgt->ids.roles |= FC_PORT_ROLE_FCP_TARGET;
3899                                         if (be32_to_cpu(parms->service_parms) & IBMVFC_PRLI_INITIATOR_FUNC)
3900                                                 tgt->ids.roles |= FC_PORT_ROLE_FCP_INITIATOR;
3901                                         tgt->add_rport = 1;
3902                                 } else
3903                                         ibmvfc_del_tgt(tgt);
3904                         } else if (prli_rsp[index].retry)
3905                                 ibmvfc_retry_tgt_init(tgt, ibmvfc_tgt_send_prli);
3906                         else
3907                                 ibmvfc_del_tgt(tgt);
3908                 } else
3909                         ibmvfc_del_tgt(tgt);
3910                 break;
3911         case IBMVFC_MAD_DRIVER_FAILED:
3912                 break;
3913         case IBMVFC_MAD_CRQ_ERROR:
3914                 ibmvfc_retry_tgt_init(tgt, ibmvfc_tgt_send_prli);
3915                 break;
3916         case IBMVFC_MAD_FAILED:
3917         default:
3918                 if ((be16_to_cpu(rsp->status) & IBMVFC_VIOS_FAILURE) &&
3919                      be16_to_cpu(rsp->error) == IBMVFC_PLOGI_REQUIRED)
3920                         level += ibmvfc_retry_tgt_init(tgt, ibmvfc_tgt_send_plogi);
3921                 else if (tgt->logo_rcvd)
3922                         level += ibmvfc_retry_tgt_init(tgt, ibmvfc_tgt_send_plogi);
3923                 else if (ibmvfc_retry_cmd(be16_to_cpu(rsp->status), be16_to_cpu(rsp->error)))
3924                         level += ibmvfc_retry_tgt_init(tgt, ibmvfc_tgt_send_prli);
3925                 else
3926                         ibmvfc_del_tgt(tgt);
3927
3928                 tgt_log(tgt, level, "Process Login failed: %s (%x:%x) rc=0x%02X\n",
3929                         ibmvfc_get_cmd_error(be16_to_cpu(rsp->status), be16_to_cpu(rsp->error)),
3930                         be16_to_cpu(rsp->status), be16_to_cpu(rsp->error), status);
3931                 break;
3932         }
3933
3934         kref_put(&tgt->kref, ibmvfc_release_tgt);
3935         ibmvfc_free_event(evt);
3936         wake_up(&vhost->work_wait_q);
3937 }
3938
3939 /**
3940  * ibmvfc_tgt_send_prli - Send a process login
3941  * @tgt:        ibmvfc target struct
3942  *
3943  **/
3944 static void ibmvfc_tgt_send_prli(struct ibmvfc_target *tgt)
3945 {
3946         struct ibmvfc_process_login *prli;
3947         struct ibmvfc_host *vhost = tgt->vhost;
3948         struct ibmvfc_event *evt;
3949
3950         if (vhost->discovery_threads >= disc_threads)
3951                 return;
3952
3953         kref_get(&tgt->kref);
3954         evt = ibmvfc_get_event(&vhost->crq);
3955         vhost->discovery_threads++;
3956         ibmvfc_init_event(evt, ibmvfc_tgt_prli_done, IBMVFC_MAD_FORMAT);
3957         evt->tgt = tgt;
3958         prli = &evt->iu.prli;
3959         memset(prli, 0, sizeof(*prli));
3960         if (ibmvfc_check_caps(vhost, IBMVFC_HANDLE_VF_WWPN)) {
3961                 prli->common.version = cpu_to_be32(2);
3962                 prli->target_wwpn = cpu_to_be64(tgt->wwpn);
3963         } else {
3964                 prli->common.version = cpu_to_be32(1);
3965         }
3966         prli->common.opcode = cpu_to_be32(IBMVFC_PROCESS_LOGIN);
3967         prli->common.length = cpu_to_be16(sizeof(*prli));
3968         prli->scsi_id = cpu_to_be64(tgt->scsi_id);
3969
3970         prli->parms.type = IBMVFC_SCSI_FCP_TYPE;
3971         prli->parms.flags = cpu_to_be16(IBMVFC_PRLI_EST_IMG_PAIR);
3972         prli->parms.service_parms = cpu_to_be32(IBMVFC_PRLI_INITIATOR_FUNC);
3973         prli->parms.service_parms |= cpu_to_be32(IBMVFC_PRLI_READ_FCP_XFER_RDY_DISABLED);
3974
3975         if (cls3_error)
3976                 prli->parms.service_parms |= cpu_to_be32(IBMVFC_PRLI_RETRY);
3977
3978         ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_INIT_WAIT);
3979         if (ibmvfc_send_event(evt, vhost, default_timeout)) {
3980                 vhost->discovery_threads--;
3981                 ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_NONE);
3982                 kref_put(&tgt->kref, ibmvfc_release_tgt);
3983         } else
3984                 tgt_dbg(tgt, "Sent process login\n");
3985 }
3986
3987 /**
3988  * ibmvfc_tgt_plogi_done - Completion handler for Port Login
3989  * @evt:        ibmvfc event struct
3990  *
3991  **/
3992 static void ibmvfc_tgt_plogi_done(struct ibmvfc_event *evt)
3993 {
3994         struct ibmvfc_target *tgt = evt->tgt;
3995         struct ibmvfc_host *vhost = evt->vhost;
3996         struct ibmvfc_port_login *rsp = &evt->xfer_iu->plogi;
3997         u32 status = be16_to_cpu(rsp->common.status);
3998         int level = IBMVFC_DEFAULT_LOG_LEVEL;
3999
4000         vhost->discovery_threads--;
4001         ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_NONE);
4002         switch (status) {
4003         case IBMVFC_MAD_SUCCESS:
4004                 tgt_dbg(tgt, "Port Login succeeded\n");
4005                 if (tgt->ids.port_name &&
4006                     tgt->ids.port_name != wwn_to_u64(rsp->service_parms.port_name)) {
4007                         vhost->reinit = 1;
4008                         tgt_dbg(tgt, "Port re-init required\n");
4009                         break;
4010                 }
4011                 tgt->ids.node_name = wwn_to_u64(rsp->service_parms.node_name);
4012                 tgt->ids.port_name = wwn_to_u64(rsp->service_parms.port_name);
4013                 tgt->ids.port_id = tgt->scsi_id;
4014                 memcpy(&tgt->service_parms, &rsp->service_parms,
4015                        sizeof(tgt->service_parms));
4016                 memcpy(&tgt->service_parms_change, &rsp->service_parms_change,
4017                        sizeof(tgt->service_parms_change));
4018                 ibmvfc_init_tgt(tgt, ibmvfc_tgt_send_prli);
4019                 break;
4020         case IBMVFC_MAD_DRIVER_FAILED:
4021                 break;
4022         case IBMVFC_MAD_CRQ_ERROR:
4023                 ibmvfc_retry_tgt_init(tgt, ibmvfc_tgt_send_plogi);
4024                 break;
4025         case IBMVFC_MAD_FAILED:
4026         default:
4027                 if (ibmvfc_retry_cmd(be16_to_cpu(rsp->status), be16_to_cpu(rsp->error)))
4028                         level += ibmvfc_retry_tgt_init(tgt, ibmvfc_tgt_send_plogi);
4029                 else
4030                         ibmvfc_del_tgt(tgt);
4031
4032                 tgt_log(tgt, level, "Port Login failed: %s (%x:%x) %s (%x) %s (%x) rc=0x%02X\n",
4033                         ibmvfc_get_cmd_error(be16_to_cpu(rsp->status), be16_to_cpu(rsp->error)),
4034                                              be16_to_cpu(rsp->status), be16_to_cpu(rsp->error),
4035                         ibmvfc_get_fc_type(be16_to_cpu(rsp->fc_type)), be16_to_cpu(rsp->fc_type),
4036                         ibmvfc_get_ls_explain(be16_to_cpu(rsp->fc_explain)), be16_to_cpu(rsp->fc_explain), status);
4037                 break;
4038         }
4039
4040         kref_put(&tgt->kref, ibmvfc_release_tgt);
4041         ibmvfc_free_event(evt);
4042         wake_up(&vhost->work_wait_q);
4043 }
4044
4045 /**
4046  * ibmvfc_tgt_send_plogi - Send PLOGI to the specified target
4047  * @tgt:        ibmvfc target struct
4048  *
4049  **/
4050 static void ibmvfc_tgt_send_plogi(struct ibmvfc_target *tgt)
4051 {
4052         struct ibmvfc_port_login *plogi;
4053         struct ibmvfc_host *vhost = tgt->vhost;
4054         struct ibmvfc_event *evt;
4055
4056         if (vhost->discovery_threads >= disc_threads)
4057                 return;
4058
4059         kref_get(&tgt->kref);
4060         tgt->logo_rcvd = 0;
4061         evt = ibmvfc_get_event(&vhost->crq);
4062         vhost->discovery_threads++;
4063         ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_INIT_WAIT);
4064         ibmvfc_init_event(evt, ibmvfc_tgt_plogi_done, IBMVFC_MAD_FORMAT);
4065         evt->tgt = tgt;
4066         plogi = &evt->iu.plogi;
4067         memset(plogi, 0, sizeof(*plogi));
4068         if (ibmvfc_check_caps(vhost, IBMVFC_HANDLE_VF_WWPN)) {
4069                 plogi->common.version = cpu_to_be32(2);
4070                 plogi->target_wwpn = cpu_to_be64(tgt->wwpn);
4071         } else {
4072                 plogi->common.version = cpu_to_be32(1);
4073         }
4074         plogi->common.opcode = cpu_to_be32(IBMVFC_PORT_LOGIN);
4075         plogi->common.length = cpu_to_be16(sizeof(*plogi));
4076         plogi->scsi_id = cpu_to_be64(tgt->scsi_id);
4077
4078         if (ibmvfc_send_event(evt, vhost, default_timeout)) {
4079                 vhost->discovery_threads--;
4080                 ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_NONE);
4081                 kref_put(&tgt->kref, ibmvfc_release_tgt);
4082         } else
4083                 tgt_dbg(tgt, "Sent port login\n");
4084 }
4085
4086 /**
4087  * ibmvfc_tgt_implicit_logout_done - Completion handler for Implicit Logout MAD
4088  * @evt:        ibmvfc event struct
4089  *
4090  **/
4091 static void ibmvfc_tgt_implicit_logout_done(struct ibmvfc_event *evt)
4092 {
4093         struct ibmvfc_target *tgt = evt->tgt;
4094         struct ibmvfc_host *vhost = evt->vhost;
4095         struct ibmvfc_implicit_logout *rsp = &evt->xfer_iu->implicit_logout;
4096         u32 status = be16_to_cpu(rsp->common.status);
4097
4098         vhost->discovery_threads--;
4099         ibmvfc_free_event(evt);
4100         ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_NONE);
4101
4102         switch (status) {
4103         case IBMVFC_MAD_SUCCESS:
4104                 tgt_dbg(tgt, "Implicit Logout succeeded\n");
4105                 break;
4106         case IBMVFC_MAD_DRIVER_FAILED:
4107                 kref_put(&tgt->kref, ibmvfc_release_tgt);
4108                 wake_up(&vhost->work_wait_q);
4109                 return;
4110         case IBMVFC_MAD_FAILED:
4111         default:
4112                 tgt_err(tgt, "Implicit Logout failed: rc=0x%02X\n", status);
4113                 break;
4114         }
4115
4116         ibmvfc_init_tgt(tgt, ibmvfc_tgt_send_plogi);
4117         kref_put(&tgt->kref, ibmvfc_release_tgt);
4118         wake_up(&vhost->work_wait_q);
4119 }
4120
4121 /**
4122  * __ibmvfc_tgt_get_implicit_logout_evt - Allocate and init an event for implicit logout
4123  * @tgt:                ibmvfc target struct
4124  *
4125  * Returns:
4126  *      Allocated and initialized ibmvfc_event struct
4127  **/
4128 static struct ibmvfc_event *__ibmvfc_tgt_get_implicit_logout_evt(struct ibmvfc_target *tgt,
4129                                                                  void (*done) (struct ibmvfc_event *))
4130 {
4131         struct ibmvfc_implicit_logout *mad;
4132         struct ibmvfc_host *vhost = tgt->vhost;
4133         struct ibmvfc_event *evt;
4134
4135         kref_get(&tgt->kref);
4136         evt = ibmvfc_get_event(&vhost->crq);
4137         ibmvfc_init_event(evt, done, IBMVFC_MAD_FORMAT);
4138         evt->tgt = tgt;
4139         mad = &evt->iu.implicit_logout;
4140         memset(mad, 0, sizeof(*mad));
4141         mad->common.version = cpu_to_be32(1);
4142         mad->common.opcode = cpu_to_be32(IBMVFC_IMPLICIT_LOGOUT);
4143         mad->common.length = cpu_to_be16(sizeof(*mad));
4144         mad->old_scsi_id = cpu_to_be64(tgt->scsi_id);
4145         return evt;
4146 }
4147
4148 /**
4149  * ibmvfc_tgt_implicit_logout - Initiate an Implicit Logout for specified target
4150  * @tgt:                ibmvfc target struct
4151  *
4152  **/
4153 static void ibmvfc_tgt_implicit_logout(struct ibmvfc_target *tgt)
4154 {
4155         struct ibmvfc_host *vhost = tgt->vhost;
4156         struct ibmvfc_event *evt;
4157
4158         if (vhost->discovery_threads >= disc_threads)
4159                 return;
4160
4161         vhost->discovery_threads++;
4162         evt = __ibmvfc_tgt_get_implicit_logout_evt(tgt,
4163                                                    ibmvfc_tgt_implicit_logout_done);
4164
4165         ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_INIT_WAIT);
4166         if (ibmvfc_send_event(evt, vhost, default_timeout)) {
4167                 vhost->discovery_threads--;
4168                 ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_NONE);
4169                 kref_put(&tgt->kref, ibmvfc_release_tgt);
4170         } else
4171                 tgt_dbg(tgt, "Sent Implicit Logout\n");
4172 }
4173
4174 /**
4175  * ibmvfc_tgt_implicit_logout_and_del_done - Completion handler for Implicit Logout MAD
4176  * @evt:        ibmvfc event struct
4177  *
4178  **/
4179 static void ibmvfc_tgt_implicit_logout_and_del_done(struct ibmvfc_event *evt)
4180 {
4181         struct ibmvfc_target *tgt = evt->tgt;
4182         struct ibmvfc_host *vhost = evt->vhost;
4183         struct ibmvfc_passthru_mad *mad = &evt->xfer_iu->passthru;
4184         u32 status = be16_to_cpu(mad->common.status);
4185
4186         vhost->discovery_threads--;
4187         ibmvfc_free_event(evt);
4188
4189         /*
4190          * If our state is IBMVFC_HOST_OFFLINE, we could be unloading the
4191          * driver in which case we need to free up all the targets. If we are
4192          * not unloading, we will still go through a hard reset to get out of
4193          * offline state, so there is no need to track the old targets in that
4194          * case.
4195          */
4196         if (status == IBMVFC_MAD_SUCCESS || vhost->state == IBMVFC_HOST_OFFLINE)
4197                 ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_DEL_RPORT);
4198         else
4199                 ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_DEL_AND_LOGOUT_RPORT);
4200
4201         tgt_dbg(tgt, "Implicit Logout %s\n", (status == IBMVFC_MAD_SUCCESS) ? "succeeded" : "failed");
4202         kref_put(&tgt->kref, ibmvfc_release_tgt);
4203         wake_up(&vhost->work_wait_q);
4204 }
4205
4206 /**
4207  * ibmvfc_tgt_implicit_logout_and_del - Initiate an Implicit Logout for specified target
4208  * @tgt:                ibmvfc target struct
4209  *
4210  **/
4211 static void ibmvfc_tgt_implicit_logout_and_del(struct ibmvfc_target *tgt)
4212 {
4213         struct ibmvfc_host *vhost = tgt->vhost;
4214         struct ibmvfc_event *evt;
4215
4216         if (!vhost->logged_in) {
4217                 ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_DEL_RPORT);
4218                 return;
4219         }
4220
4221         if (vhost->discovery_threads >= disc_threads)
4222                 return;
4223
4224         vhost->discovery_threads++;
4225         evt = __ibmvfc_tgt_get_implicit_logout_evt(tgt,
4226                                                    ibmvfc_tgt_implicit_logout_and_del_done);
4227
4228         ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_LOGOUT_RPORT_WAIT);
4229         if (ibmvfc_send_event(evt, vhost, default_timeout)) {
4230                 vhost->discovery_threads--;
4231                 ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_DEL_RPORT);
4232                 kref_put(&tgt->kref, ibmvfc_release_tgt);
4233         } else
4234                 tgt_dbg(tgt, "Sent Implicit Logout\n");
4235 }
4236
4237 /**
4238  * ibmvfc_tgt_move_login_done - Completion handler for Move Login
4239  * @evt:        ibmvfc event struct
4240  *
4241  **/
4242 static void ibmvfc_tgt_move_login_done(struct ibmvfc_event *evt)
4243 {
4244         struct ibmvfc_target *tgt = evt->tgt;
4245         struct ibmvfc_host *vhost = evt->vhost;
4246         struct ibmvfc_move_login *rsp = &evt->xfer_iu->move_login;
4247         u32 status = be16_to_cpu(rsp->common.status);
4248         int level = IBMVFC_DEFAULT_LOG_LEVEL;
4249
4250         vhost->discovery_threads--;
4251         ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_NONE);
4252         switch (status) {
4253         case IBMVFC_MAD_SUCCESS:
4254                 tgt_dbg(tgt, "Move Login succeeded for old scsi_id: %llX\n", tgt->old_scsi_id);
4255                 tgt->ids.node_name = wwn_to_u64(rsp->service_parms.node_name);
4256                 tgt->ids.port_name = wwn_to_u64(rsp->service_parms.port_name);
4257                 tgt->ids.port_id = tgt->scsi_id;
4258                 memcpy(&tgt->service_parms, &rsp->service_parms,
4259                        sizeof(tgt->service_parms));
4260                 memcpy(&tgt->service_parms_change, &rsp->service_parms_change,
4261                        sizeof(tgt->service_parms_change));
4262                 ibmvfc_init_tgt(tgt, ibmvfc_tgt_send_prli);
4263                 break;
4264         case IBMVFC_MAD_DRIVER_FAILED:
4265                 break;
4266         case IBMVFC_MAD_CRQ_ERROR:
4267                 ibmvfc_retry_tgt_init(tgt, ibmvfc_tgt_move_login);
4268                 break;
4269         case IBMVFC_MAD_FAILED:
4270         default:
4271                 level += ibmvfc_retry_tgt_init(tgt, ibmvfc_tgt_move_login);
4272
4273                 tgt_log(tgt, level,
4274                         "Move Login failed: old scsi_id: %llX, flags:%x, vios_flags:%x, rc=0x%02X\n",
4275                         tgt->old_scsi_id, be32_to_cpu(rsp->flags), be16_to_cpu(rsp->vios_flags),
4276                         status);
4277                 break;
4278         }
4279
4280         kref_put(&tgt->kref, ibmvfc_release_tgt);
4281         ibmvfc_free_event(evt);
4282         wake_up(&vhost->work_wait_q);
4283 }
4284
4285
4286 /**
4287  * ibmvfc_tgt_move_login - Initiate a move login for specified target
4288  * @tgt:                ibmvfc target struct
4289  *
4290  **/
4291 static void ibmvfc_tgt_move_login(struct ibmvfc_target *tgt)
4292 {
4293         struct ibmvfc_host *vhost = tgt->vhost;
4294         struct ibmvfc_move_login *move;
4295         struct ibmvfc_event *evt;
4296
4297         if (vhost->discovery_threads >= disc_threads)
4298                 return;
4299
4300         kref_get(&tgt->kref);
4301         evt = ibmvfc_get_event(&vhost->crq);
4302         vhost->discovery_threads++;
4303         ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_INIT_WAIT);
4304         ibmvfc_init_event(evt, ibmvfc_tgt_move_login_done, IBMVFC_MAD_FORMAT);
4305         evt->tgt = tgt;
4306         move = &evt->iu.move_login;
4307         memset(move, 0, sizeof(*move));
4308         move->common.version = cpu_to_be32(1);
4309         move->common.opcode = cpu_to_be32(IBMVFC_MOVE_LOGIN);
4310         move->common.length = cpu_to_be16(sizeof(*move));
4311
4312         move->old_scsi_id = cpu_to_be64(tgt->old_scsi_id);
4313         move->new_scsi_id = cpu_to_be64(tgt->scsi_id);
4314         move->wwpn = cpu_to_be64(tgt->wwpn);
4315         move->node_name = cpu_to_be64(tgt->ids.node_name);
4316
4317         if (ibmvfc_send_event(evt, vhost, default_timeout)) {
4318                 vhost->discovery_threads--;
4319                 ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_DEL_RPORT);
4320                 kref_put(&tgt->kref, ibmvfc_release_tgt);
4321         } else
4322                 tgt_dbg(tgt, "Sent Move Login for old scsi_id: %llX\n", tgt->old_scsi_id);
4323 }
4324
4325 /**
4326  * ibmvfc_adisc_needs_plogi - Does device need PLOGI?
4327  * @mad:        ibmvfc passthru mad struct
4328  * @tgt:        ibmvfc target struct
4329  *
4330  * Returns:
4331  *      1 if PLOGI needed / 0 if PLOGI not needed
4332  **/
4333 static int ibmvfc_adisc_needs_plogi(struct ibmvfc_passthru_mad *mad,
4334                                     struct ibmvfc_target *tgt)
4335 {
4336         if (wwn_to_u64((u8 *)&mad->fc_iu.response[2]) != tgt->ids.port_name)
4337                 return 1;
4338         if (wwn_to_u64((u8 *)&mad->fc_iu.response[4]) != tgt->ids.node_name)
4339                 return 1;
4340         if (be32_to_cpu(mad->fc_iu.response[6]) != tgt->scsi_id)
4341                 return 1;
4342         return 0;
4343 }
4344
4345 /**
4346  * ibmvfc_tgt_adisc_done - Completion handler for ADISC
4347  * @evt:        ibmvfc event struct
4348  *
4349  **/
4350 static void ibmvfc_tgt_adisc_done(struct ibmvfc_event *evt)
4351 {
4352         struct ibmvfc_target *tgt = evt->tgt;
4353         struct ibmvfc_host *vhost = evt->vhost;
4354         struct ibmvfc_passthru_mad *mad = &evt->xfer_iu->passthru;
4355         u32 status = be16_to_cpu(mad->common.status);
4356         u8 fc_reason, fc_explain;
4357
4358         vhost->discovery_threads--;
4359         ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_NONE);
4360         del_timer(&tgt->timer);
4361
4362         switch (status) {
4363         case IBMVFC_MAD_SUCCESS:
4364                 tgt_dbg(tgt, "ADISC succeeded\n");
4365                 if (ibmvfc_adisc_needs_plogi(mad, tgt))
4366                         ibmvfc_del_tgt(tgt);
4367                 break;
4368         case IBMVFC_MAD_DRIVER_FAILED:
4369                 break;
4370         case IBMVFC_MAD_FAILED:
4371         default:
4372                 ibmvfc_del_tgt(tgt);
4373                 fc_reason = (be32_to_cpu(mad->fc_iu.response[1]) & 0x00ff0000) >> 16;
4374                 fc_explain = (be32_to_cpu(mad->fc_iu.response[1]) & 0x0000ff00) >> 8;
4375                 tgt_info(tgt, "ADISC failed: %s (%x:%x) %s (%x) %s (%x) rc=0x%02X\n",
4376                          ibmvfc_get_cmd_error(be16_to_cpu(mad->iu.status), be16_to_cpu(mad->iu.error)),
4377                          be16_to_cpu(mad->iu.status), be16_to_cpu(mad->iu.error),
4378                          ibmvfc_get_fc_type(fc_reason), fc_reason,
4379                          ibmvfc_get_ls_explain(fc_explain), fc_explain, status);
4380                 break;
4381         }
4382
4383         kref_put(&tgt->kref, ibmvfc_release_tgt);
4384         ibmvfc_free_event(evt);
4385         wake_up(&vhost->work_wait_q);
4386 }
4387
4388 /**
4389  * ibmvfc_init_passthru - Initialize an event struct for FC passthru
4390  * @evt:                ibmvfc event struct
4391  *
4392  **/
4393 static void ibmvfc_init_passthru(struct ibmvfc_event *evt)
4394 {
4395         struct ibmvfc_passthru_mad *mad = &evt->iu.passthru;
4396
4397         memset(mad, 0, sizeof(*mad));
4398         mad->common.version = cpu_to_be32(1);
4399         mad->common.opcode = cpu_to_be32(IBMVFC_PASSTHRU);
4400         mad->common.length = cpu_to_be16(sizeof(*mad) - sizeof(mad->fc_iu) - sizeof(mad->iu));
4401         mad->cmd_ioba.va = cpu_to_be64((u64)be64_to_cpu(evt->crq.ioba) +
4402                 offsetof(struct ibmvfc_passthru_mad, iu));
4403         mad->cmd_ioba.len = cpu_to_be32(sizeof(mad->iu));
4404         mad->iu.cmd_len = cpu_to_be32(sizeof(mad->fc_iu.payload));
4405         mad->iu.rsp_len = cpu_to_be32(sizeof(mad->fc_iu.response));
4406         mad->iu.cmd.va = cpu_to_be64((u64)be64_to_cpu(evt->crq.ioba) +
4407                 offsetof(struct ibmvfc_passthru_mad, fc_iu) +
4408                 offsetof(struct ibmvfc_passthru_fc_iu, payload));
4409         mad->iu.cmd.len = cpu_to_be32(sizeof(mad->fc_iu.payload));
4410         mad->iu.rsp.va = cpu_to_be64((u64)be64_to_cpu(evt->crq.ioba) +
4411                 offsetof(struct ibmvfc_passthru_mad, fc_iu) +
4412                 offsetof(struct ibmvfc_passthru_fc_iu, response));
4413         mad->iu.rsp.len = cpu_to_be32(sizeof(mad->fc_iu.response));
4414 }
4415
4416 /**
4417  * ibmvfc_tgt_adisc_cancel_done - Completion handler when cancelling an ADISC
4418  * @evt:                ibmvfc event struct
4419  *
4420  * Just cleanup this event struct. Everything else is handled by
4421  * the ADISC completion handler. If the ADISC never actually comes
4422  * back, we still have the timer running on the ADISC event struct
4423  * which will fire and cause the CRQ to get reset.
4424  *
4425  **/
4426 static void ibmvfc_tgt_adisc_cancel_done(struct ibmvfc_event *evt)
4427 {
4428         struct ibmvfc_host *vhost = evt->vhost;
4429         struct ibmvfc_target *tgt = evt->tgt;
4430
4431         tgt_dbg(tgt, "ADISC cancel complete\n");
4432         vhost->abort_threads--;
4433         ibmvfc_free_event(evt);
4434         kref_put(&tgt->kref, ibmvfc_release_tgt);
4435         wake_up(&vhost->work_wait_q);
4436 }
4437
4438 /**
4439  * ibmvfc_adisc_timeout - Handle an ADISC timeout
4440  * @tgt:                ibmvfc target struct
4441  *
4442  * If an ADISC times out, send a cancel. If the cancel times
4443  * out, reset the CRQ. When the ADISC comes back as cancelled,
4444  * log back into the target.
4445  **/
4446 static void ibmvfc_adisc_timeout(struct timer_list *t)
4447 {
4448         struct ibmvfc_target *tgt = from_timer(tgt, t, timer);
4449         struct ibmvfc_host *vhost = tgt->vhost;
4450         struct ibmvfc_event *evt;
4451         struct ibmvfc_tmf *tmf;
4452         unsigned long flags;
4453         int rc;
4454
4455         tgt_dbg(tgt, "ADISC timeout\n");
4456         spin_lock_irqsave(vhost->host->host_lock, flags);
4457         if (vhost->abort_threads >= disc_threads ||
4458             tgt->action != IBMVFC_TGT_ACTION_INIT_WAIT ||
4459             vhost->state != IBMVFC_INITIALIZING ||
4460             vhost->action != IBMVFC_HOST_ACTION_QUERY_TGTS) {
4461                 spin_unlock_irqrestore(vhost->host->host_lock, flags);
4462                 return;
4463         }
4464
4465         vhost->abort_threads++;
4466         kref_get(&tgt->kref);
4467         evt = ibmvfc_get_event(&vhost->crq);
4468         ibmvfc_init_event(evt, ibmvfc_tgt_adisc_cancel_done, IBMVFC_MAD_FORMAT);
4469
4470         evt->tgt = tgt;
4471         tmf = &evt->iu.tmf;
4472         memset(tmf, 0, sizeof(*tmf));
4473         if (ibmvfc_check_caps(vhost, IBMVFC_HANDLE_VF_WWPN)) {
4474                 tmf->common.version = cpu_to_be32(2);
4475                 tmf->target_wwpn = cpu_to_be64(tgt->wwpn);
4476         } else {
4477                 tmf->common.version = cpu_to_be32(1);
4478         }
4479         tmf->common.opcode = cpu_to_be32(IBMVFC_TMF_MAD);
4480         tmf->common.length = cpu_to_be16(sizeof(*tmf));
4481         tmf->scsi_id = cpu_to_be64(tgt->scsi_id);
4482         tmf->cancel_key = cpu_to_be32(tgt->cancel_key);
4483
4484         rc = ibmvfc_send_event(evt, vhost, default_timeout);
4485
4486         if (rc) {
4487                 tgt_err(tgt, "Failed to send cancel event for ADISC. rc=%d\n", rc);
4488                 vhost->abort_threads--;
4489                 kref_put(&tgt->kref, ibmvfc_release_tgt);
4490                 __ibmvfc_reset_host(vhost);
4491         } else
4492                 tgt_dbg(tgt, "Attempting to cancel ADISC\n");
4493         spin_unlock_irqrestore(vhost->host->host_lock, flags);
4494 }
4495
4496 /**
4497  * ibmvfc_tgt_adisc - Initiate an ADISC for specified target
4498  * @tgt:                ibmvfc target struct
4499  *
4500  * When sending an ADISC we end up with two timers running. The
4501  * first timer is the timer in the ibmvfc target struct. If this
4502  * fires, we send a cancel to the target. The second timer is the
4503  * timer on the ibmvfc event for the ADISC, which is longer. If that
4504  * fires, it means the ADISC timed out and our attempt to cancel it
4505  * also failed, so we need to reset the CRQ.
4506  **/
4507 static void ibmvfc_tgt_adisc(struct ibmvfc_target *tgt)
4508 {
4509         struct ibmvfc_passthru_mad *mad;
4510         struct ibmvfc_host *vhost = tgt->vhost;
4511         struct ibmvfc_event *evt;
4512
4513         if (vhost->discovery_threads >= disc_threads)
4514                 return;
4515
4516         kref_get(&tgt->kref);
4517         evt = ibmvfc_get_event(&vhost->crq);
4518         vhost->discovery_threads++;
4519         ibmvfc_init_event(evt, ibmvfc_tgt_adisc_done, IBMVFC_MAD_FORMAT);
4520         evt->tgt = tgt;
4521
4522         ibmvfc_init_passthru(evt);
4523         mad = &evt->iu.passthru;
4524         mad->iu.flags = cpu_to_be32(IBMVFC_FC_ELS);
4525         mad->iu.scsi_id = cpu_to_be64(tgt->scsi_id);
4526         mad->iu.cancel_key = cpu_to_be32(tgt->cancel_key);
4527
4528         mad->fc_iu.payload[0] = cpu_to_be32(IBMVFC_ADISC);
4529         memcpy(&mad->fc_iu.payload[2], &vhost->login_buf->resp.port_name,
4530                sizeof(vhost->login_buf->resp.port_name));
4531         memcpy(&mad->fc_iu.payload[4], &vhost->login_buf->resp.node_name,
4532                sizeof(vhost->login_buf->resp.node_name));
4533         mad->fc_iu.payload[6] = cpu_to_be32(be64_to_cpu(vhost->login_buf->resp.scsi_id) & 0x00ffffff);
4534
4535         if (timer_pending(&tgt->timer))
4536                 mod_timer(&tgt->timer, jiffies + (IBMVFC_ADISC_TIMEOUT * HZ));
4537         else {
4538                 tgt->timer.expires = jiffies + (IBMVFC_ADISC_TIMEOUT * HZ);
4539                 add_timer(&tgt->timer);
4540         }
4541
4542         ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_INIT_WAIT);
4543         if (ibmvfc_send_event(evt, vhost, IBMVFC_ADISC_PLUS_CANCEL_TIMEOUT)) {
4544                 vhost->discovery_threads--;
4545                 del_timer(&tgt->timer);
4546                 ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_NONE);
4547                 kref_put(&tgt->kref, ibmvfc_release_tgt);
4548         } else
4549                 tgt_dbg(tgt, "Sent ADISC\n");
4550 }
4551
4552 /**
4553  * ibmvfc_tgt_query_target_done - Completion handler for Query Target MAD
4554  * @evt:        ibmvfc event struct
4555  *
4556  **/
4557 static void ibmvfc_tgt_query_target_done(struct ibmvfc_event *evt)
4558 {
4559         struct ibmvfc_target *tgt = evt->tgt;
4560         struct ibmvfc_host *vhost = evt->vhost;
4561         struct ibmvfc_query_tgt *rsp = &evt->xfer_iu->query_tgt;
4562         u32 status = be16_to_cpu(rsp->common.status);
4563         int level = IBMVFC_DEFAULT_LOG_LEVEL;
4564
4565         vhost->discovery_threads--;
4566         ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_NONE);
4567         switch (status) {
4568         case IBMVFC_MAD_SUCCESS:
4569                 tgt_dbg(tgt, "Query Target succeeded\n");
4570                 if (be64_to_cpu(rsp->scsi_id) != tgt->scsi_id)
4571                         ibmvfc_del_tgt(tgt);
4572                 else
4573                         ibmvfc_init_tgt(tgt, ibmvfc_tgt_adisc);
4574                 break;
4575         case IBMVFC_MAD_DRIVER_FAILED:
4576                 break;
4577         case IBMVFC_MAD_CRQ_ERROR:
4578                 ibmvfc_retry_tgt_init(tgt, ibmvfc_tgt_query_target);
4579                 break;
4580         case IBMVFC_MAD_FAILED:
4581         default:
4582                 if ((be16_to_cpu(rsp->status) & IBMVFC_FABRIC_MAPPED) == IBMVFC_FABRIC_MAPPED &&
4583                     be16_to_cpu(rsp->error) == IBMVFC_UNABLE_TO_PERFORM_REQ &&
4584                     be16_to_cpu(rsp->fc_explain) == IBMVFC_PORT_NAME_NOT_REG)
4585                         ibmvfc_del_tgt(tgt);
4586                 else if (ibmvfc_retry_cmd(be16_to_cpu(rsp->status), be16_to_cpu(rsp->error)))
4587                         level += ibmvfc_retry_tgt_init(tgt, ibmvfc_tgt_query_target);
4588                 else
4589                         ibmvfc_del_tgt(tgt);
4590
4591                 tgt_log(tgt, level, "Query Target failed: %s (%x:%x) %s (%x) %s (%x) rc=0x%02X\n",
4592                         ibmvfc_get_cmd_error(be16_to_cpu(rsp->status), be16_to_cpu(rsp->error)),
4593                         be16_to_cpu(rsp->status), be16_to_cpu(rsp->error),
4594                         ibmvfc_get_fc_type(be16_to_cpu(rsp->fc_type)), be16_to_cpu(rsp->fc_type),
4595                         ibmvfc_get_gs_explain(be16_to_cpu(rsp->fc_explain)), be16_to_cpu(rsp->fc_explain),
4596                         status);
4597                 break;
4598         }
4599
4600         kref_put(&tgt->kref, ibmvfc_release_tgt);
4601         ibmvfc_free_event(evt);
4602         wake_up(&vhost->work_wait_q);
4603 }
4604
4605 /**
4606  * ibmvfc_tgt_query_target - Initiate a Query Target for specified target
4607  * @tgt:        ibmvfc target struct
4608  *
4609  **/
4610 static void ibmvfc_tgt_query_target(struct ibmvfc_target *tgt)
4611 {
4612         struct ibmvfc_query_tgt *query_tgt;
4613         struct ibmvfc_host *vhost = tgt->vhost;
4614         struct ibmvfc_event *evt;
4615
4616         if (vhost->discovery_threads >= disc_threads)
4617                 return;
4618
4619         kref_get(&tgt->kref);
4620         evt = ibmvfc_get_event(&vhost->crq);
4621         vhost->discovery_threads++;
4622         evt->tgt = tgt;
4623         ibmvfc_init_event(evt, ibmvfc_tgt_query_target_done, IBMVFC_MAD_FORMAT);
4624         query_tgt = &evt->iu.query_tgt;
4625         memset(query_tgt, 0, sizeof(*query_tgt));
4626         query_tgt->common.version = cpu_to_be32(1);
4627         query_tgt->common.opcode = cpu_to_be32(IBMVFC_QUERY_TARGET);
4628         query_tgt->common.length = cpu_to_be16(sizeof(*query_tgt));
4629         query_tgt->wwpn = cpu_to_be64(tgt->ids.port_name);
4630
4631         ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_INIT_WAIT);
4632         if (ibmvfc_send_event(evt, vhost, default_timeout)) {
4633                 vhost->discovery_threads--;
4634                 ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_NONE);
4635                 kref_put(&tgt->kref, ibmvfc_release_tgt);
4636         } else
4637                 tgt_dbg(tgt, "Sent Query Target\n");
4638 }
4639
4640 /**
4641  * ibmvfc_alloc_target - Allocate and initialize an ibmvfc target
4642  * @vhost:              ibmvfc host struct
4643  * @scsi_id:    SCSI ID to allocate target for
4644  *
4645  * Returns:
4646  *      0 on success / other on failure
4647  **/
4648 static int ibmvfc_alloc_target(struct ibmvfc_host *vhost,
4649                                struct ibmvfc_discover_targets_entry *target)
4650 {
4651         struct ibmvfc_target *stgt = NULL;
4652         struct ibmvfc_target *wtgt = NULL;
4653         struct ibmvfc_target *tgt;
4654         unsigned long flags;
4655         u64 scsi_id = be32_to_cpu(target->scsi_id) & IBMVFC_DISC_TGT_SCSI_ID_MASK;
4656         u64 wwpn = be64_to_cpu(target->wwpn);
4657
4658         /* Look to see if we already have a target allocated for this SCSI ID or WWPN */
4659         spin_lock_irqsave(vhost->host->host_lock, flags);
4660         list_for_each_entry(tgt, &vhost->targets, queue) {
4661                 if (tgt->wwpn == wwpn) {
4662                         wtgt = tgt;
4663                         break;
4664                 }
4665         }
4666
4667         list_for_each_entry(tgt, &vhost->targets, queue) {
4668                 if (tgt->scsi_id == scsi_id) {
4669                         stgt = tgt;
4670                         break;
4671                 }
4672         }
4673
4674         if (wtgt && !stgt) {
4675                 /*
4676                  * A WWPN target has moved and we still are tracking the old
4677                  * SCSI ID.  The only way we should be able to get here is if
4678                  * we attempted to send an implicit logout for the old SCSI ID
4679                  * and it failed for some reason, such as there being I/O
4680                  * pending to the target. In this case, we will have already
4681                  * deleted the rport from the FC transport so we do a move
4682                  * login, which works even with I/O pending, as it will cancel
4683                  * any active commands.
4684                  */
4685                 if (wtgt->action == IBMVFC_TGT_ACTION_LOGOUT_DELETED_RPORT) {
4686                         /*
4687                          * Do a move login here. The old target is no longer
4688                          * known to the transport layer We don't use the
4689                          * normal ibmvfc_set_tgt_action to set this, as we
4690                          * don't normally want to allow this state change.
4691                          */
4692                         wtgt->old_scsi_id = wtgt->scsi_id;
4693                         wtgt->scsi_id = scsi_id;
4694                         wtgt->action = IBMVFC_TGT_ACTION_INIT;
4695                         ibmvfc_init_tgt(wtgt, ibmvfc_tgt_move_login);
4696                         goto unlock_out;
4697                 } else {
4698                         tgt_err(wtgt, "Unexpected target state: %d, %p\n",
4699                                 wtgt->action, wtgt->rport);
4700                 }
4701         } else if (stgt) {
4702                 if (tgt->need_login)
4703                         ibmvfc_init_tgt(tgt, ibmvfc_tgt_implicit_logout);
4704                 goto unlock_out;
4705         }
4706         spin_unlock_irqrestore(vhost->host->host_lock, flags);
4707
4708         tgt = mempool_alloc(vhost->tgt_pool, GFP_NOIO);
4709         memset(tgt, 0, sizeof(*tgt));
4710         tgt->scsi_id = scsi_id;
4711         tgt->wwpn = wwpn;
4712         tgt->vhost = vhost;
4713         tgt->need_login = 1;
4714         timer_setup(&tgt->timer, ibmvfc_adisc_timeout, 0);
4715         kref_init(&tgt->kref);
4716         ibmvfc_init_tgt(tgt, ibmvfc_tgt_implicit_logout);
4717         spin_lock_irqsave(vhost->host->host_lock, flags);
4718         tgt->cancel_key = vhost->task_set++;
4719         list_add_tail(&tgt->queue, &vhost->targets);
4720
4721 unlock_out:
4722         spin_unlock_irqrestore(vhost->host->host_lock, flags);
4723         return 0;
4724 }
4725
4726 /**
4727  * ibmvfc_alloc_targets - Allocate and initialize ibmvfc targets
4728  * @vhost:              ibmvfc host struct
4729  *
4730  * Returns:
4731  *      0 on success / other on failure
4732  **/
4733 static int ibmvfc_alloc_targets(struct ibmvfc_host *vhost)
4734 {
4735         int i, rc;
4736
4737         for (i = 0, rc = 0; !rc && i < vhost->num_targets; i++)
4738                 rc = ibmvfc_alloc_target(vhost, &vhost->disc_buf[i]);
4739
4740         return rc;
4741 }
4742
4743 /**
4744  * ibmvfc_discover_targets_done - Completion handler for discover targets MAD
4745  * @evt:        ibmvfc event struct
4746  *
4747  **/
4748 static void ibmvfc_discover_targets_done(struct ibmvfc_event *evt)
4749 {
4750         struct ibmvfc_host *vhost = evt->vhost;
4751         struct ibmvfc_discover_targets *rsp = &evt->xfer_iu->discover_targets;
4752         u32 mad_status = be16_to_cpu(rsp->common.status);
4753         int level = IBMVFC_DEFAULT_LOG_LEVEL;
4754
4755         switch (mad_status) {
4756         case IBMVFC_MAD_SUCCESS:
4757                 ibmvfc_dbg(vhost, "Discover Targets succeeded\n");
4758                 vhost->num_targets = be32_to_cpu(rsp->num_written);
4759                 ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_ALLOC_TGTS);
4760                 break;
4761         case IBMVFC_MAD_FAILED:
4762                 level += ibmvfc_retry_host_init(vhost);
4763                 ibmvfc_log(vhost, level, "Discover Targets failed: %s (%x:%x)\n",
4764                            ibmvfc_get_cmd_error(be16_to_cpu(rsp->status), be16_to_cpu(rsp->error)),
4765                            be16_to_cpu(rsp->status), be16_to_cpu(rsp->error));
4766                 break;
4767         case IBMVFC_MAD_DRIVER_FAILED:
4768                 break;
4769         default:
4770                 dev_err(vhost->dev, "Invalid Discover Targets response: 0x%x\n", mad_status);
4771                 ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
4772                 break;
4773         }
4774
4775         ibmvfc_free_event(evt);
4776         wake_up(&vhost->work_wait_q);
4777 }
4778
4779 /**
4780  * ibmvfc_discover_targets - Send Discover Targets MAD
4781  * @vhost:      ibmvfc host struct
4782  *
4783  **/
4784 static void ibmvfc_discover_targets(struct ibmvfc_host *vhost)
4785 {
4786         struct ibmvfc_discover_targets *mad;
4787         struct ibmvfc_event *evt = ibmvfc_get_event(&vhost->crq);
4788
4789         ibmvfc_init_event(evt, ibmvfc_discover_targets_done, IBMVFC_MAD_FORMAT);
4790         mad = &evt->iu.discover_targets;
4791         memset(mad, 0, sizeof(*mad));
4792         mad->common.version = cpu_to_be32(1);
4793         mad->common.opcode = cpu_to_be32(IBMVFC_DISC_TARGETS);
4794         mad->common.length = cpu_to_be16(sizeof(*mad));
4795         mad->bufflen = cpu_to_be32(vhost->disc_buf_sz);
4796         mad->buffer.va = cpu_to_be64(vhost->disc_buf_dma);
4797         mad->buffer.len = cpu_to_be32(vhost->disc_buf_sz);
4798         mad->flags = cpu_to_be32(IBMVFC_DISC_TGT_PORT_ID_WWPN_LIST);
4799         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_INIT_WAIT);
4800
4801         if (!ibmvfc_send_event(evt, vhost, default_timeout))
4802                 ibmvfc_dbg(vhost, "Sent discover targets\n");
4803         else
4804                 ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
4805 }
4806
4807 static void ibmvfc_channel_setup_done(struct ibmvfc_event *evt)
4808 {
4809         struct ibmvfc_host *vhost = evt->vhost;
4810         struct ibmvfc_channel_setup *setup = vhost->channel_setup_buf;
4811         struct ibmvfc_scsi_channels *scrqs = &vhost->scsi_scrqs;
4812         u32 mad_status = be16_to_cpu(evt->xfer_iu->channel_setup.common.status);
4813         int level = IBMVFC_DEFAULT_LOG_LEVEL;
4814         int flags, active_queues, i;
4815
4816         ibmvfc_free_event(evt);
4817
4818         switch (mad_status) {
4819         case IBMVFC_MAD_SUCCESS:
4820                 ibmvfc_dbg(vhost, "Channel Setup succeeded\n");
4821                 flags = be32_to_cpu(setup->flags);
4822                 vhost->do_enquiry = 0;
4823                 active_queues = be32_to_cpu(setup->num_scsi_subq_channels);
4824                 scrqs->active_queues = active_queues;
4825
4826                 if (flags & IBMVFC_CHANNELS_CANCELED) {
4827                         ibmvfc_dbg(vhost, "Channels Canceled\n");
4828                         vhost->using_channels = 0;
4829                 } else {
4830                         if (active_queues)
4831                                 vhost->using_channels = 1;
4832                         for (i = 0; i < active_queues; i++)
4833                                 scrqs->scrqs[i].vios_cookie =
4834                                         be64_to_cpu(setup->channel_handles[i]);
4835
4836                         ibmvfc_dbg(vhost, "Using %u channels\n",
4837                                    vhost->scsi_scrqs.active_queues);
4838                 }
4839                 break;
4840         case IBMVFC_MAD_FAILED:
4841                 level += ibmvfc_retry_host_init(vhost);
4842                 ibmvfc_log(vhost, level, "Channel Setup failed\n");
4843                 fallthrough;
4844         case IBMVFC_MAD_DRIVER_FAILED:
4845                 return;
4846         default:
4847                 dev_err(vhost->dev, "Invalid Channel Setup response: 0x%x\n",
4848                         mad_status);
4849                 ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
4850                 return;
4851         }
4852
4853         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_QUERY);
4854         wake_up(&vhost->work_wait_q);
4855 }
4856
4857 static void ibmvfc_channel_setup(struct ibmvfc_host *vhost)
4858 {
4859         struct ibmvfc_channel_setup_mad *mad;
4860         struct ibmvfc_channel_setup *setup_buf = vhost->channel_setup_buf;
4861         struct ibmvfc_event *evt = ibmvfc_get_event(&vhost->crq);
4862         struct ibmvfc_scsi_channels *scrqs = &vhost->scsi_scrqs;
4863         unsigned int num_channels =
4864                 min(vhost->client_scsi_channels, vhost->max_vios_scsi_channels);
4865         int i;
4866
4867         memset(setup_buf, 0, sizeof(*setup_buf));
4868         if (num_channels == 0)
4869                 setup_buf->flags = cpu_to_be32(IBMVFC_CANCEL_CHANNELS);
4870         else {
4871                 setup_buf->num_scsi_subq_channels = cpu_to_be32(num_channels);
4872                 for (i = 0; i < num_channels; i++)
4873                         setup_buf->channel_handles[i] = cpu_to_be64(scrqs->scrqs[i].cookie);
4874         }
4875
4876         ibmvfc_init_event(evt, ibmvfc_channel_setup_done, IBMVFC_MAD_FORMAT);
4877         mad = &evt->iu.channel_setup;
4878         memset(mad, 0, sizeof(*mad));
4879         mad->common.version = cpu_to_be32(1);
4880         mad->common.opcode = cpu_to_be32(IBMVFC_CHANNEL_SETUP);
4881         mad->common.length = cpu_to_be16(sizeof(*mad));
4882         mad->buffer.va = cpu_to_be64(vhost->channel_setup_dma);
4883         mad->buffer.len = cpu_to_be32(sizeof(*vhost->channel_setup_buf));
4884
4885         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_INIT_WAIT);
4886
4887         if (!ibmvfc_send_event(evt, vhost, default_timeout))
4888                 ibmvfc_dbg(vhost, "Sent channel setup\n");
4889         else
4890                 ibmvfc_link_down(vhost, IBMVFC_LINK_DOWN);
4891 }
4892
4893 static void ibmvfc_channel_enquiry_done(struct ibmvfc_event *evt)
4894 {
4895         struct ibmvfc_host *vhost = evt->vhost;
4896         struct ibmvfc_channel_enquiry *rsp = &evt->xfer_iu->channel_enquiry;
4897         u32 mad_status = be16_to_cpu(rsp->common.status);
4898         int level = IBMVFC_DEFAULT_LOG_LEVEL;
4899
4900         switch (mad_status) {
4901         case IBMVFC_MAD_SUCCESS:
4902                 ibmvfc_dbg(vhost, "Channel Enquiry succeeded\n");
4903                 vhost->max_vios_scsi_channels = be32_to_cpu(rsp->num_scsi_subq_channels);
4904                 ibmvfc_free_event(evt);
4905                 break;
4906         case IBMVFC_MAD_FAILED:
4907                 level += ibmvfc_retry_host_init(vhost);
4908                 ibmvfc_log(vhost, level, "Channel Enquiry failed\n");
4909                 fallthrough;
4910         case IBMVFC_MAD_DRIVER_FAILED:
4911                 ibmvfc_free_event(evt);
4912                 return;
4913         default:
4914                 dev_err(vhost->dev, "Invalid Channel Enquiry response: 0x%x\n",
4915                         mad_status);
4916                 ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
4917                 ibmvfc_free_event(evt);
4918                 return;
4919         }
4920
4921         ibmvfc_channel_setup(vhost);
4922 }
4923
4924 static void ibmvfc_channel_enquiry(struct ibmvfc_host *vhost)
4925 {
4926         struct ibmvfc_channel_enquiry *mad;
4927         struct ibmvfc_event *evt = ibmvfc_get_event(&vhost->crq);
4928
4929         ibmvfc_init_event(evt, ibmvfc_channel_enquiry_done, IBMVFC_MAD_FORMAT);
4930         mad = &evt->iu.channel_enquiry;
4931         memset(mad, 0, sizeof(*mad));
4932         mad->common.version = cpu_to_be32(1);
4933         mad->common.opcode = cpu_to_be32(IBMVFC_CHANNEL_ENQUIRY);
4934         mad->common.length = cpu_to_be16(sizeof(*mad));
4935
4936         if (mig_channels_only)
4937                 mad->flags |= cpu_to_be32(IBMVFC_NO_CHANNELS_TO_CRQ_SUPPORT);
4938         if (mig_no_less_channels)
4939                 mad->flags |= cpu_to_be32(IBMVFC_NO_N_TO_M_CHANNELS_SUPPORT);
4940
4941         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_INIT_WAIT);
4942
4943         if (!ibmvfc_send_event(evt, vhost, default_timeout))
4944                 ibmvfc_dbg(vhost, "Send channel enquiry\n");
4945         else
4946                 ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
4947 }
4948
4949 /**
4950  * ibmvfc_npiv_login_done - Completion handler for NPIV Login
4951  * @evt:        ibmvfc event struct
4952  *
4953  **/
4954 static void ibmvfc_npiv_login_done(struct ibmvfc_event *evt)
4955 {
4956         struct ibmvfc_host *vhost = evt->vhost;
4957         u32 mad_status = be16_to_cpu(evt->xfer_iu->npiv_login.common.status);
4958         struct ibmvfc_npiv_login_resp *rsp = &vhost->login_buf->resp;
4959         unsigned int npiv_max_sectors;
4960         int level = IBMVFC_DEFAULT_LOG_LEVEL;
4961
4962         switch (mad_status) {
4963         case IBMVFC_MAD_SUCCESS:
4964                 ibmvfc_free_event(evt);
4965                 break;
4966         case IBMVFC_MAD_FAILED:
4967                 if (ibmvfc_retry_cmd(be16_to_cpu(rsp->status), be16_to_cpu(rsp->error)))
4968                         level += ibmvfc_retry_host_init(vhost);
4969                 else
4970                         ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
4971                 ibmvfc_log(vhost, level, "NPIV Login failed: %s (%x:%x)\n",
4972                            ibmvfc_get_cmd_error(be16_to_cpu(rsp->status), be16_to_cpu(rsp->error)),
4973                                                 be16_to_cpu(rsp->status), be16_to_cpu(rsp->error));
4974                 ibmvfc_free_event(evt);
4975                 return;
4976         case IBMVFC_MAD_CRQ_ERROR:
4977                 ibmvfc_retry_host_init(vhost);
4978                 fallthrough;
4979         case IBMVFC_MAD_DRIVER_FAILED:
4980                 ibmvfc_free_event(evt);
4981                 return;
4982         default:
4983                 dev_err(vhost->dev, "Invalid NPIV Login response: 0x%x\n", mad_status);
4984                 ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
4985                 ibmvfc_free_event(evt);
4986                 return;
4987         }
4988
4989         vhost->client_migrated = 0;
4990
4991         if (!(be32_to_cpu(rsp->flags) & IBMVFC_NATIVE_FC)) {
4992                 dev_err(vhost->dev, "Virtual adapter does not support FC. %x\n",
4993                         rsp->flags);
4994                 ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
4995                 wake_up(&vhost->work_wait_q);
4996                 return;
4997         }
4998
4999         if (be32_to_cpu(rsp->max_cmds) <= IBMVFC_NUM_INTERNAL_REQ) {
5000                 dev_err(vhost->dev, "Virtual adapter supported queue depth too small: %d\n",
5001                         rsp->max_cmds);
5002                 ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
5003                 wake_up(&vhost->work_wait_q);
5004                 return;
5005         }
5006
5007         vhost->logged_in = 1;
5008         npiv_max_sectors = min((uint)(be64_to_cpu(rsp->max_dma_len) >> 9), IBMVFC_MAX_SECTORS);
5009         dev_info(vhost->dev, "Host partition: %s, device: %s %s %s max sectors %u\n",
5010                  rsp->partition_name, rsp->device_name, rsp->port_loc_code,
5011                  rsp->drc_name, npiv_max_sectors);
5012
5013         fc_host_fabric_name(vhost->host) = be64_to_cpu(rsp->node_name);
5014         fc_host_node_name(vhost->host) = be64_to_cpu(rsp->node_name);
5015         fc_host_port_name(vhost->host) = be64_to_cpu(rsp->port_name);
5016         fc_host_port_id(vhost->host) = be64_to_cpu(rsp->scsi_id);
5017         fc_host_port_type(vhost->host) = FC_PORTTYPE_NPIV;
5018         fc_host_supported_classes(vhost->host) = 0;
5019         if (be32_to_cpu(rsp->service_parms.class1_parms[0]) & 0x80000000)
5020                 fc_host_supported_classes(vhost->host) |= FC_COS_CLASS1;
5021         if (be32_to_cpu(rsp->service_parms.class2_parms[0]) & 0x80000000)
5022                 fc_host_supported_classes(vhost->host) |= FC_COS_CLASS2;
5023         if (be32_to_cpu(rsp->service_parms.class3_parms[0]) & 0x80000000)
5024                 fc_host_supported_classes(vhost->host) |= FC_COS_CLASS3;
5025         fc_host_maxframe_size(vhost->host) =
5026                 be16_to_cpu(rsp->service_parms.common.bb_rcv_sz) & 0x0fff;
5027
5028         vhost->host->can_queue = be32_to_cpu(rsp->max_cmds) - IBMVFC_NUM_INTERNAL_REQ;
5029         vhost->host->max_sectors = npiv_max_sectors;
5030
5031         if (ibmvfc_check_caps(vhost, IBMVFC_CAN_SUPPORT_CHANNELS) && vhost->do_enquiry) {
5032                 ibmvfc_channel_enquiry(vhost);
5033         } else {
5034                 vhost->do_enquiry = 0;
5035                 ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_QUERY);
5036                 wake_up(&vhost->work_wait_q);
5037         }
5038 }
5039
5040 /**
5041  * ibmvfc_npiv_login - Sends NPIV login
5042  * @vhost:      ibmvfc host struct
5043  *
5044  **/
5045 static void ibmvfc_npiv_login(struct ibmvfc_host *vhost)
5046 {
5047         struct ibmvfc_npiv_login_mad *mad;
5048         struct ibmvfc_event *evt = ibmvfc_get_event(&vhost->crq);
5049
5050         ibmvfc_gather_partition_info(vhost);
5051         ibmvfc_set_login_info(vhost);
5052         ibmvfc_init_event(evt, ibmvfc_npiv_login_done, IBMVFC_MAD_FORMAT);
5053
5054         memcpy(vhost->login_buf, &vhost->login_info, sizeof(vhost->login_info));
5055         mad = &evt->iu.npiv_login;
5056         memset(mad, 0, sizeof(struct ibmvfc_npiv_login_mad));
5057         mad->common.version = cpu_to_be32(1);
5058         mad->common.opcode = cpu_to_be32(IBMVFC_NPIV_LOGIN);
5059         mad->common.length = cpu_to_be16(sizeof(struct ibmvfc_npiv_login_mad));
5060         mad->buffer.va = cpu_to_be64(vhost->login_buf_dma);
5061         mad->buffer.len = cpu_to_be32(sizeof(*vhost->login_buf));
5062
5063         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_INIT_WAIT);
5064
5065         if (!ibmvfc_send_event(evt, vhost, default_timeout))
5066                 ibmvfc_dbg(vhost, "Sent NPIV login\n");
5067         else
5068                 ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
5069 }
5070
5071 /**
5072  * ibmvfc_npiv_logout_done - Completion handler for NPIV Logout
5073  * @vhost:              ibmvfc host struct
5074  *
5075  **/
5076 static void ibmvfc_npiv_logout_done(struct ibmvfc_event *evt)
5077 {
5078         struct ibmvfc_host *vhost = evt->vhost;
5079         u32 mad_status = be16_to_cpu(evt->xfer_iu->npiv_logout.common.status);
5080
5081         ibmvfc_free_event(evt);
5082
5083         switch (mad_status) {
5084         case IBMVFC_MAD_SUCCESS:
5085                 if (list_empty(&vhost->crq.sent) &&
5086                     vhost->action == IBMVFC_HOST_ACTION_LOGO_WAIT) {
5087                         ibmvfc_init_host(vhost);
5088                         return;
5089                 }
5090                 break;
5091         case IBMVFC_MAD_FAILED:
5092         case IBMVFC_MAD_NOT_SUPPORTED:
5093         case IBMVFC_MAD_CRQ_ERROR:
5094         case IBMVFC_MAD_DRIVER_FAILED:
5095         default:
5096                 ibmvfc_dbg(vhost, "NPIV Logout failed. 0x%X\n", mad_status);
5097                 break;
5098         }
5099
5100         ibmvfc_hard_reset_host(vhost);
5101 }
5102
5103 /**
5104  * ibmvfc_npiv_logout - Issue an NPIV Logout
5105  * @vhost:              ibmvfc host struct
5106  *
5107  **/
5108 static void ibmvfc_npiv_logout(struct ibmvfc_host *vhost)
5109 {
5110         struct ibmvfc_npiv_logout_mad *mad;
5111         struct ibmvfc_event *evt;
5112
5113         evt = ibmvfc_get_event(&vhost->crq);
5114         ibmvfc_init_event(evt, ibmvfc_npiv_logout_done, IBMVFC_MAD_FORMAT);
5115
5116         mad = &evt->iu.npiv_logout;
5117         memset(mad, 0, sizeof(*mad));
5118         mad->common.version = cpu_to_be32(1);
5119         mad->common.opcode = cpu_to_be32(IBMVFC_NPIV_LOGOUT);
5120         mad->common.length = cpu_to_be16(sizeof(struct ibmvfc_npiv_logout_mad));
5121
5122         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_LOGO_WAIT);
5123
5124         if (!ibmvfc_send_event(evt, vhost, default_timeout))
5125                 ibmvfc_dbg(vhost, "Sent NPIV logout\n");
5126         else
5127                 ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
5128 }
5129
5130 /**
5131  * ibmvfc_dev_init_to_do - Is there target initialization work to do?
5132  * @vhost:              ibmvfc host struct
5133  *
5134  * Returns:
5135  *      1 if work to do / 0 if not
5136  **/
5137 static int ibmvfc_dev_init_to_do(struct ibmvfc_host *vhost)
5138 {
5139         struct ibmvfc_target *tgt;
5140
5141         list_for_each_entry(tgt, &vhost->targets, queue) {
5142                 if (tgt->action == IBMVFC_TGT_ACTION_INIT ||
5143                     tgt->action == IBMVFC_TGT_ACTION_INIT_WAIT)
5144                         return 1;
5145         }
5146
5147         return 0;
5148 }
5149
5150 /**
5151  * ibmvfc_dev_logo_to_do - Is there target logout work to do?
5152  * @vhost:              ibmvfc host struct
5153  *
5154  * Returns:
5155  *      1 if work to do / 0 if not
5156  **/
5157 static int ibmvfc_dev_logo_to_do(struct ibmvfc_host *vhost)
5158 {
5159         struct ibmvfc_target *tgt;
5160
5161         list_for_each_entry(tgt, &vhost->targets, queue) {
5162                 if (tgt->action == IBMVFC_TGT_ACTION_LOGOUT_RPORT ||
5163                     tgt->action == IBMVFC_TGT_ACTION_LOGOUT_RPORT_WAIT)
5164                         return 1;
5165         }
5166         return 0;
5167 }
5168
5169 /**
5170  * __ibmvfc_work_to_do - Is there task level work to do? (no locking)
5171  * @vhost:              ibmvfc host struct
5172  *
5173  * Returns:
5174  *      1 if work to do / 0 if not
5175  **/
5176 static int __ibmvfc_work_to_do(struct ibmvfc_host *vhost)
5177 {
5178         struct ibmvfc_target *tgt;
5179
5180         if (kthread_should_stop())
5181                 return 1;
5182         switch (vhost->action) {
5183         case IBMVFC_HOST_ACTION_NONE:
5184         case IBMVFC_HOST_ACTION_INIT_WAIT:
5185         case IBMVFC_HOST_ACTION_LOGO_WAIT:
5186                 return 0;
5187         case IBMVFC_HOST_ACTION_TGT_INIT:
5188         case IBMVFC_HOST_ACTION_QUERY_TGTS:
5189                 if (vhost->discovery_threads == disc_threads)
5190                         return 0;
5191                 list_for_each_entry(tgt, &vhost->targets, queue)
5192                         if (tgt->action == IBMVFC_TGT_ACTION_INIT)
5193                                 return 1;
5194                 list_for_each_entry(tgt, &vhost->targets, queue)
5195                         if (tgt->action == IBMVFC_TGT_ACTION_INIT_WAIT)
5196                                 return 0;
5197                 return 1;
5198         case IBMVFC_HOST_ACTION_TGT_DEL:
5199         case IBMVFC_HOST_ACTION_TGT_DEL_FAILED:
5200                 if (vhost->discovery_threads == disc_threads)
5201                         return 0;
5202                 list_for_each_entry(tgt, &vhost->targets, queue)
5203                         if (tgt->action == IBMVFC_TGT_ACTION_LOGOUT_RPORT)
5204                                 return 1;
5205                 list_for_each_entry(tgt, &vhost->targets, queue)
5206                         if (tgt->action == IBMVFC_TGT_ACTION_LOGOUT_RPORT_WAIT)
5207                                 return 0;
5208                 return 1;
5209         case IBMVFC_HOST_ACTION_LOGO:
5210         case IBMVFC_HOST_ACTION_INIT:
5211         case IBMVFC_HOST_ACTION_ALLOC_TGTS:
5212         case IBMVFC_HOST_ACTION_QUERY:
5213         case IBMVFC_HOST_ACTION_RESET:
5214         case IBMVFC_HOST_ACTION_REENABLE:
5215         default:
5216                 break;
5217         }
5218
5219         return 1;
5220 }
5221
5222 /**
5223  * ibmvfc_work_to_do - Is there task level work to do?
5224  * @vhost:              ibmvfc host struct
5225  *
5226  * Returns:
5227  *      1 if work to do / 0 if not
5228  **/
5229 static int ibmvfc_work_to_do(struct ibmvfc_host *vhost)
5230 {
5231         unsigned long flags;
5232         int rc;
5233
5234         spin_lock_irqsave(vhost->host->host_lock, flags);
5235         rc = __ibmvfc_work_to_do(vhost);
5236         spin_unlock_irqrestore(vhost->host->host_lock, flags);
5237         return rc;
5238 }
5239
5240 /**
5241  * ibmvfc_log_ae - Log async events if necessary
5242  * @vhost:              ibmvfc host struct
5243  * @events:             events to log
5244  *
5245  **/
5246 static void ibmvfc_log_ae(struct ibmvfc_host *vhost, int events)
5247 {
5248         if (events & IBMVFC_AE_RSCN)
5249                 fc_host_post_event(vhost->host, fc_get_event_number(), FCH_EVT_RSCN, 0);
5250         if ((events & IBMVFC_AE_LINKDOWN) &&
5251             vhost->state >= IBMVFC_HALTED)
5252                 fc_host_post_event(vhost->host, fc_get_event_number(), FCH_EVT_LINKDOWN, 0);
5253         if ((events & IBMVFC_AE_LINKUP) &&
5254             vhost->state == IBMVFC_INITIALIZING)
5255                 fc_host_post_event(vhost->host, fc_get_event_number(), FCH_EVT_LINKUP, 0);
5256 }
5257
5258 /**
5259  * ibmvfc_tgt_add_rport - Tell the FC transport about a new remote port
5260  * @tgt:                ibmvfc target struct
5261  *
5262  **/
5263 static void ibmvfc_tgt_add_rport(struct ibmvfc_target *tgt)
5264 {
5265         struct ibmvfc_host *vhost = tgt->vhost;
5266         struct fc_rport *rport;
5267         unsigned long flags;
5268
5269         tgt_dbg(tgt, "Adding rport\n");
5270         rport = fc_remote_port_add(vhost->host, 0, &tgt->ids);
5271         spin_lock_irqsave(vhost->host->host_lock, flags);
5272
5273         if (rport && tgt->action == IBMVFC_TGT_ACTION_DEL_RPORT) {
5274                 tgt_dbg(tgt, "Deleting rport\n");
5275                 list_del(&tgt->queue);
5276                 ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_DELETED_RPORT);
5277                 spin_unlock_irqrestore(vhost->host->host_lock, flags);
5278                 fc_remote_port_delete(rport);
5279                 del_timer_sync(&tgt->timer);
5280                 kref_put(&tgt->kref, ibmvfc_release_tgt);
5281                 return;
5282         } else if (rport && tgt->action == IBMVFC_TGT_ACTION_DEL_AND_LOGOUT_RPORT) {
5283                 tgt_dbg(tgt, "Deleting rport with outstanding I/O\n");
5284                 ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_LOGOUT_DELETED_RPORT);
5285                 tgt->rport = NULL;
5286                 spin_unlock_irqrestore(vhost->host->host_lock, flags);
5287                 fc_remote_port_delete(rport);
5288                 return;
5289         } else if (rport && tgt->action == IBMVFC_TGT_ACTION_DELETED_RPORT) {
5290                 spin_unlock_irqrestore(vhost->host->host_lock, flags);
5291                 return;
5292         }
5293
5294         if (rport) {
5295                 tgt_dbg(tgt, "rport add succeeded\n");
5296                 tgt->rport = rport;
5297                 rport->maxframe_size = be16_to_cpu(tgt->service_parms.common.bb_rcv_sz) & 0x0fff;
5298                 rport->supported_classes = 0;
5299                 tgt->target_id = rport->scsi_target_id;
5300                 if (be32_to_cpu(tgt->service_parms.class1_parms[0]) & 0x80000000)
5301                         rport->supported_classes |= FC_COS_CLASS1;
5302                 if (be32_to_cpu(tgt->service_parms.class2_parms[0]) & 0x80000000)
5303                         rport->supported_classes |= FC_COS_CLASS2;
5304                 if (be32_to_cpu(tgt->service_parms.class3_parms[0]) & 0x80000000)
5305                         rport->supported_classes |= FC_COS_CLASS3;
5306                 if (rport->rqst_q)
5307                         blk_queue_max_segments(rport->rqst_q, 1);
5308         } else
5309                 tgt_dbg(tgt, "rport add failed\n");
5310         spin_unlock_irqrestore(vhost->host->host_lock, flags);
5311 }
5312
5313 /**
5314  * ibmvfc_do_work - Do task level work
5315  * @vhost:              ibmvfc host struct
5316  *
5317  **/
5318 static void ibmvfc_do_work(struct ibmvfc_host *vhost)
5319 {
5320         struct ibmvfc_target *tgt;
5321         unsigned long flags;
5322         struct fc_rport *rport;
5323         LIST_HEAD(purge);
5324         int rc;
5325
5326         ibmvfc_log_ae(vhost, vhost->events_to_log);
5327         spin_lock_irqsave(vhost->host->host_lock, flags);
5328         vhost->events_to_log = 0;
5329         switch (vhost->action) {
5330         case IBMVFC_HOST_ACTION_NONE:
5331         case IBMVFC_HOST_ACTION_LOGO_WAIT:
5332         case IBMVFC_HOST_ACTION_INIT_WAIT:
5333                 break;
5334         case IBMVFC_HOST_ACTION_RESET:
5335                 vhost->action = IBMVFC_HOST_ACTION_TGT_DEL;
5336                 list_splice_init(&vhost->purge, &purge);
5337                 spin_unlock_irqrestore(vhost->host->host_lock, flags);
5338                 ibmvfc_complete_purge(&purge);
5339                 rc = ibmvfc_reset_crq(vhost);
5340                 spin_lock_irqsave(vhost->host->host_lock, flags);
5341                 if (rc == H_CLOSED)
5342                         vio_enable_interrupts(to_vio_dev(vhost->dev));
5343                 if (rc || (rc = ibmvfc_send_crq_init(vhost)) ||
5344                     (rc = vio_enable_interrupts(to_vio_dev(vhost->dev)))) {
5345                         ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
5346                         dev_err(vhost->dev, "Error after reset (rc=%d)\n", rc);
5347                 }
5348                 break;
5349         case IBMVFC_HOST_ACTION_REENABLE:
5350                 vhost->action = IBMVFC_HOST_ACTION_TGT_DEL;
5351                 list_splice_init(&vhost->purge, &purge);
5352                 spin_unlock_irqrestore(vhost->host->host_lock, flags);
5353                 ibmvfc_complete_purge(&purge);
5354                 rc = ibmvfc_reenable_crq_queue(vhost);
5355                 spin_lock_irqsave(vhost->host->host_lock, flags);
5356                 if (rc || (rc = ibmvfc_send_crq_init(vhost))) {
5357                         ibmvfc_link_down(vhost, IBMVFC_LINK_DEAD);
5358                         dev_err(vhost->dev, "Error after enable (rc=%d)\n", rc);
5359                 }
5360                 break;
5361         case IBMVFC_HOST_ACTION_LOGO:
5362                 vhost->job_step(vhost);
5363                 break;
5364         case IBMVFC_HOST_ACTION_INIT:
5365                 BUG_ON(vhost->state != IBMVFC_INITIALIZING);
5366                 if (vhost->delay_init) {
5367                         vhost->delay_init = 0;
5368                         spin_unlock_irqrestore(vhost->host->host_lock, flags);
5369                         ssleep(15);
5370                         return;
5371                 } else
5372                         vhost->job_step(vhost);
5373                 break;
5374         case IBMVFC_HOST_ACTION_QUERY:
5375                 list_for_each_entry(tgt, &vhost->targets, queue)
5376                         ibmvfc_init_tgt(tgt, ibmvfc_tgt_query_target);
5377                 ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_QUERY_TGTS);
5378                 break;
5379         case IBMVFC_HOST_ACTION_QUERY_TGTS:
5380                 list_for_each_entry(tgt, &vhost->targets, queue) {
5381                         if (tgt->action == IBMVFC_TGT_ACTION_INIT) {
5382                                 tgt->job_step(tgt);
5383                                 break;
5384                         }
5385                 }
5386
5387                 if (!ibmvfc_dev_init_to_do(vhost))
5388                         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_TGT_DEL);
5389                 break;
5390         case IBMVFC_HOST_ACTION_TGT_DEL:
5391         case IBMVFC_HOST_ACTION_TGT_DEL_FAILED:
5392                 list_for_each_entry(tgt, &vhost->targets, queue) {
5393                         if (tgt->action == IBMVFC_TGT_ACTION_LOGOUT_RPORT) {
5394                                 tgt->job_step(tgt);
5395                                 break;
5396                         }
5397                 }
5398
5399                 if (ibmvfc_dev_logo_to_do(vhost)) {
5400                         spin_unlock_irqrestore(vhost->host->host_lock, flags);
5401                         return;
5402                 }
5403
5404                 list_for_each_entry(tgt, &vhost->targets, queue) {
5405                         if (tgt->action == IBMVFC_TGT_ACTION_DEL_RPORT) {
5406                                 tgt_dbg(tgt, "Deleting rport\n");
5407                                 rport = tgt->rport;
5408                                 tgt->rport = NULL;
5409                                 list_del(&tgt->queue);
5410                                 ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_DELETED_RPORT);
5411                                 spin_unlock_irqrestore(vhost->host->host_lock, flags);
5412                                 if (rport)
5413                                         fc_remote_port_delete(rport);
5414                                 del_timer_sync(&tgt->timer);
5415                                 kref_put(&tgt->kref, ibmvfc_release_tgt);
5416                                 return;
5417                         } else if (tgt->action == IBMVFC_TGT_ACTION_DEL_AND_LOGOUT_RPORT) {
5418                                 tgt_dbg(tgt, "Deleting rport with I/O outstanding\n");
5419                                 rport = tgt->rport;
5420                                 tgt->rport = NULL;
5421                                 ibmvfc_set_tgt_action(tgt, IBMVFC_TGT_ACTION_LOGOUT_DELETED_RPORT);
5422                                 spin_unlock_irqrestore(vhost->host->host_lock, flags);
5423                                 if (rport)
5424                                         fc_remote_port_delete(rport);
5425                                 return;
5426                         }
5427                 }
5428
5429                 if (vhost->state == IBMVFC_INITIALIZING) {
5430                         if (vhost->action == IBMVFC_HOST_ACTION_TGT_DEL_FAILED) {
5431                                 if (vhost->reinit) {
5432                                         vhost->reinit = 0;
5433                                         scsi_block_requests(vhost->host);
5434                                         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_QUERY);
5435                                         spin_unlock_irqrestore(vhost->host->host_lock, flags);
5436                                 } else {
5437                                         ibmvfc_set_host_state(vhost, IBMVFC_ACTIVE);
5438                                         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_NONE);
5439                                         wake_up(&vhost->init_wait_q);
5440                                         schedule_work(&vhost->rport_add_work_q);
5441                                         vhost->init_retries = 0;
5442                                         spin_unlock_irqrestore(vhost->host->host_lock, flags);
5443                                         scsi_unblock_requests(vhost->host);
5444                                 }
5445
5446                                 return;
5447                         } else {
5448                                 ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_INIT);
5449                                 vhost->job_step = ibmvfc_discover_targets;
5450                         }
5451                 } else {
5452                         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_NONE);
5453                         spin_unlock_irqrestore(vhost->host->host_lock, flags);
5454                         scsi_unblock_requests(vhost->host);
5455                         wake_up(&vhost->init_wait_q);
5456                         return;
5457                 }
5458                 break;
5459         case IBMVFC_HOST_ACTION_ALLOC_TGTS:
5460                 ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_TGT_INIT);
5461                 spin_unlock_irqrestore(vhost->host->host_lock, flags);
5462                 ibmvfc_alloc_targets(vhost);
5463                 spin_lock_irqsave(vhost->host->host_lock, flags);
5464                 break;
5465         case IBMVFC_HOST_ACTION_TGT_INIT:
5466                 list_for_each_entry(tgt, &vhost->targets, queue) {
5467                         if (tgt->action == IBMVFC_TGT_ACTION_INIT) {
5468                                 tgt->job_step(tgt);
5469                                 break;
5470                         }
5471                 }
5472
5473                 if (!ibmvfc_dev_init_to_do(vhost))
5474                         ibmvfc_set_host_action(vhost, IBMVFC_HOST_ACTION_TGT_DEL_FAILED);
5475                 break;
5476         default:
5477                 break;
5478         }
5479
5480         spin_unlock_irqrestore(vhost->host->host_lock, flags);
5481 }
5482
5483 /**
5484  * ibmvfc_work - Do task level work
5485  * @data:               ibmvfc host struct
5486  *
5487  * Returns:
5488  *      zero
5489  **/
5490 static int ibmvfc_work(void *data)
5491 {
5492         struct ibmvfc_host *vhost = data;
5493         int rc;
5494
5495         set_user_nice(current, MIN_NICE);
5496
5497         while (1) {
5498                 rc = wait_event_interruptible(vhost->work_wait_q,
5499                                               ibmvfc_work_to_do(vhost));
5500
5501                 BUG_ON(rc);
5502
5503                 if (kthread_should_stop())
5504                         break;
5505
5506                 ibmvfc_do_work(vhost);
5507         }
5508
5509         ibmvfc_dbg(vhost, "ibmvfc kthread exiting...\n");
5510         return 0;
5511 }
5512
5513 /**
5514  * ibmvfc_alloc_queue - Allocate queue
5515  * @vhost:      ibmvfc host struct
5516  * @queue:      ibmvfc queue to allocate
5517  * @fmt:        queue format to allocate
5518  *
5519  * Returns:
5520  *      0 on success / non-zero on failure
5521  **/
5522 static int ibmvfc_alloc_queue(struct ibmvfc_host *vhost,
5523                               struct ibmvfc_queue *queue,
5524                               enum ibmvfc_msg_fmt fmt)
5525 {
5526         struct device *dev = vhost->dev;
5527         size_t fmt_size;
5528         unsigned int pool_size = 0;
5529
5530         ENTER;
5531         spin_lock_init(&queue->_lock);
5532         queue->q_lock = &queue->_lock;
5533
5534         switch (fmt) {
5535         case IBMVFC_CRQ_FMT:
5536                 fmt_size = sizeof(*queue->msgs.crq);
5537                 pool_size = max_requests + IBMVFC_NUM_INTERNAL_REQ;
5538                 break;
5539         case IBMVFC_ASYNC_FMT:
5540                 fmt_size = sizeof(*queue->msgs.async);
5541                 break;
5542         case IBMVFC_SUB_CRQ_FMT:
5543                 fmt_size = sizeof(*queue->msgs.scrq);
5544                 /* We need one extra event for Cancel Commands */
5545                 pool_size = max_requests + 1;
5546                 break;
5547         default:
5548                 dev_warn(dev, "Unknown command/response queue message format: %d\n", fmt);
5549                 return -EINVAL;
5550         }
5551
5552         if (ibmvfc_init_event_pool(vhost, queue, pool_size)) {
5553                 dev_err(dev, "Couldn't initialize event pool.\n");
5554                 return -ENOMEM;
5555         }
5556
5557         queue->msgs.handle = (void *)get_zeroed_page(GFP_KERNEL);
5558         if (!queue->msgs.handle)
5559                 return -ENOMEM;
5560
5561         queue->msg_token = dma_map_single(dev, queue->msgs.handle, PAGE_SIZE,
5562                                           DMA_BIDIRECTIONAL);
5563
5564         if (dma_mapping_error(dev, queue->msg_token)) {
5565                 free_page((unsigned long)queue->msgs.handle);
5566                 queue->msgs.handle = NULL;
5567                 return -ENOMEM;
5568         }
5569
5570         queue->cur = 0;
5571         queue->fmt = fmt;
5572         queue->size = PAGE_SIZE / fmt_size;
5573         return 0;
5574 }
5575
5576 /**
5577  * ibmvfc_init_crq - Initializes and registers CRQ with hypervisor
5578  * @vhost:      ibmvfc host struct
5579  *
5580  * Allocates a page for messages, maps it for dma, and registers
5581  * the crq with the hypervisor.
5582  *
5583  * Return value:
5584  *      zero on success / other on failure
5585  **/
5586 static int ibmvfc_init_crq(struct ibmvfc_host *vhost)
5587 {
5588         int rc, retrc = -ENOMEM;
5589         struct device *dev = vhost->dev;
5590         struct vio_dev *vdev = to_vio_dev(dev);
5591         struct ibmvfc_queue *crq = &vhost->crq;
5592
5593         ENTER;
5594         if (ibmvfc_alloc_queue(vhost, crq, IBMVFC_CRQ_FMT))
5595                 return -ENOMEM;
5596
5597         retrc = rc = plpar_hcall_norets(H_REG_CRQ, vdev->unit_address,
5598                                         crq->msg_token, PAGE_SIZE);
5599
5600         if (rc == H_RESOURCE)
5601                 /* maybe kexecing and resource is busy. try a reset */
5602                 retrc = rc = ibmvfc_reset_crq(vhost);
5603
5604         if (rc == H_CLOSED)
5605                 dev_warn(dev, "Partner adapter not ready\n");
5606         else if (rc) {
5607                 dev_warn(dev, "Error %d opening adapter\n", rc);
5608                 goto reg_crq_failed;
5609         }
5610
5611         retrc = 0;
5612
5613         tasklet_init(&vhost->tasklet, (void *)ibmvfc_tasklet, (unsigned long)vhost);
5614
5615         if ((rc = request_irq(vdev->irq, ibmvfc_interrupt, 0, IBMVFC_NAME, vhost))) {
5616                 dev_err(dev, "Couldn't register irq 0x%x. rc=%d\n", vdev->irq, rc);
5617                 goto req_irq_failed;
5618         }
5619
5620         if ((rc = vio_enable_interrupts(vdev))) {
5621                 dev_err(dev, "Error %d enabling interrupts\n", rc);
5622                 goto req_irq_failed;
5623         }
5624
5625         LEAVE;
5626         return retrc;
5627
5628 req_irq_failed:
5629         tasklet_kill(&vhost->tasklet);
5630         do {
5631                 rc = plpar_hcall_norets(H_FREE_CRQ, vdev->unit_address);
5632         } while (rc == H_BUSY || H_IS_LONG_BUSY(rc));
5633 reg_crq_failed:
5634         ibmvfc_free_queue(vhost, crq);
5635         return retrc;
5636 }
5637
5638 static int ibmvfc_register_scsi_channel(struct ibmvfc_host *vhost,
5639                                   int index)
5640 {
5641         struct device *dev = vhost->dev;
5642         struct vio_dev *vdev = to_vio_dev(dev);
5643         struct ibmvfc_queue *scrq = &vhost->scsi_scrqs.scrqs[index];
5644         int rc = -ENOMEM;
5645
5646         ENTER;
5647
5648         if (ibmvfc_alloc_queue(vhost, scrq, IBMVFC_SUB_CRQ_FMT))
5649                 return -ENOMEM;
5650
5651         rc = h_reg_sub_crq(vdev->unit_address, scrq->msg_token, PAGE_SIZE,
5652                            &scrq->cookie, &scrq->hw_irq);
5653
5654         /* H_CLOSED indicates successful register, but no CRQ partner */
5655         if (rc && rc != H_CLOSED) {
5656                 dev_warn(dev, "Error registering sub-crq: %d\n", rc);
5657                 if (rc == H_PARAMETER)
5658                         dev_warn_once(dev, "Firmware may not support MQ\n");
5659                 goto reg_failed;
5660         }
5661
5662         scrq->irq = irq_create_mapping(NULL, scrq->hw_irq);
5663
5664         if (!scrq->irq) {
5665                 rc = -EINVAL;
5666                 dev_err(dev, "Error mapping sub-crq[%d] irq\n", index);
5667                 goto irq_failed;
5668         }
5669
5670         snprintf(scrq->name, sizeof(scrq->name), "ibmvfc-%x-scsi%d",
5671                  vdev->unit_address, index);
5672         rc = request_irq(scrq->irq, ibmvfc_interrupt_scsi, 0, scrq->name, scrq);
5673
5674         if (rc) {
5675                 dev_err(dev, "Couldn't register sub-crq[%d] irq\n", index);
5676                 irq_dispose_mapping(scrq->irq);
5677                 goto irq_failed;
5678         }
5679
5680         scrq->hwq_id = index;
5681         scrq->vhost = vhost;
5682
5683         LEAVE;
5684         return 0;
5685
5686 irq_failed:
5687         do {
5688                 rc = plpar_hcall_norets(H_FREE_SUB_CRQ, vdev->unit_address, scrq->cookie);
5689         } while (rtas_busy_delay(rc));
5690 reg_failed:
5691         ibmvfc_free_queue(vhost, scrq);
5692         LEAVE;
5693         return rc;
5694 }
5695
5696 static void ibmvfc_deregister_scsi_channel(struct ibmvfc_host *vhost, int index)
5697 {
5698         struct device *dev = vhost->dev;
5699         struct vio_dev *vdev = to_vio_dev(dev);
5700         struct ibmvfc_queue *scrq = &vhost->scsi_scrqs.scrqs[index];
5701         long rc;
5702
5703         ENTER;
5704
5705         free_irq(scrq->irq, scrq);
5706         irq_dispose_mapping(scrq->irq);
5707         scrq->irq = 0;
5708
5709         do {
5710                 rc = plpar_hcall_norets(H_FREE_SUB_CRQ, vdev->unit_address,
5711                                         scrq->cookie);
5712         } while (rc == H_BUSY || H_IS_LONG_BUSY(rc));
5713
5714         if (rc)
5715                 dev_err(dev, "Failed to free sub-crq[%d]: rc=%ld\n", index, rc);
5716
5717         ibmvfc_free_queue(vhost, scrq);
5718         LEAVE;
5719 }
5720
5721 static void ibmvfc_init_sub_crqs(struct ibmvfc_host *vhost)
5722 {
5723         int i, j;
5724
5725         ENTER;
5726         if (!vhost->mq_enabled)
5727                 return;
5728
5729         vhost->scsi_scrqs.scrqs = kcalloc(nr_scsi_hw_queues,
5730                                           sizeof(*vhost->scsi_scrqs.scrqs),
5731                                           GFP_KERNEL);
5732         if (!vhost->scsi_scrqs.scrqs) {
5733                 vhost->do_enquiry = 0;
5734                 return;
5735         }
5736
5737         for (i = 0; i < nr_scsi_hw_queues; i++) {
5738                 if (ibmvfc_register_scsi_channel(vhost, i)) {
5739                         for (j = i; j > 0; j--)
5740                                 ibmvfc_deregister_scsi_channel(vhost, j - 1);
5741                         kfree(vhost->scsi_scrqs.scrqs);
5742                         vhost->scsi_scrqs.scrqs = NULL;
5743                         vhost->scsi_scrqs.active_queues = 0;
5744                         vhost->do_enquiry = 0;
5745                         break;
5746                 }
5747         }
5748
5749         LEAVE;
5750 }
5751
5752 static void ibmvfc_release_sub_crqs(struct ibmvfc_host *vhost)
5753 {
5754         int i;
5755
5756         ENTER;
5757         if (!vhost->scsi_scrqs.scrqs)
5758                 return;
5759
5760         for (i = 0; i < nr_scsi_hw_queues; i++)
5761                 ibmvfc_deregister_scsi_channel(vhost, i);
5762
5763         kfree(vhost->scsi_scrqs.scrqs);
5764         vhost->scsi_scrqs.scrqs = NULL;
5765         vhost->scsi_scrqs.active_queues = 0;
5766         LEAVE;
5767 }
5768
5769 /**
5770  * ibmvfc_free_mem - Free memory for vhost
5771  * @vhost:      ibmvfc host struct
5772  *
5773  * Return value:
5774  *      none
5775  **/
5776 static void ibmvfc_free_mem(struct ibmvfc_host *vhost)
5777 {
5778         struct ibmvfc_queue *async_q = &vhost->async_crq;
5779
5780         ENTER;
5781         mempool_destroy(vhost->tgt_pool);
5782         kfree(vhost->trace);
5783         dma_free_coherent(vhost->dev, vhost->disc_buf_sz, vhost->disc_buf,
5784                           vhost->disc_buf_dma);
5785         dma_free_coherent(vhost->dev, sizeof(*vhost->login_buf),
5786                           vhost->login_buf, vhost->login_buf_dma);
5787         dma_pool_destroy(vhost->sg_pool);
5788         ibmvfc_free_queue(vhost, async_q);
5789         LEAVE;
5790 }
5791
5792 /**
5793  * ibmvfc_alloc_mem - Allocate memory for vhost
5794  * @vhost:      ibmvfc host struct
5795  *
5796  * Return value:
5797  *      0 on success / non-zero on failure
5798  **/
5799 static int ibmvfc_alloc_mem(struct ibmvfc_host *vhost)
5800 {
5801         struct ibmvfc_queue *async_q = &vhost->async_crq;
5802         struct device *dev = vhost->dev;
5803
5804         ENTER;
5805         if (ibmvfc_alloc_queue(vhost, async_q, IBMVFC_ASYNC_FMT)) {
5806                 dev_err(dev, "Couldn't allocate/map async queue.\n");
5807                 goto nomem;
5808         }
5809
5810         vhost->sg_pool = dma_pool_create(IBMVFC_NAME, dev,
5811                                          SG_ALL * sizeof(struct srp_direct_buf),
5812                                          sizeof(struct srp_direct_buf), 0);
5813
5814         if (!vhost->sg_pool) {
5815                 dev_err(dev, "Failed to allocate sg pool\n");
5816                 goto unmap_async_crq;
5817         }
5818
5819         vhost->login_buf = dma_alloc_coherent(dev, sizeof(*vhost->login_buf),
5820                                               &vhost->login_buf_dma, GFP_KERNEL);
5821
5822         if (!vhost->login_buf) {
5823                 dev_err(dev, "Couldn't allocate NPIV login buffer\n");
5824                 goto free_sg_pool;
5825         }
5826
5827         vhost->disc_buf_sz = sizeof(*vhost->disc_buf) * max_targets;
5828         vhost->disc_buf = dma_alloc_coherent(dev, vhost->disc_buf_sz,
5829                                              &vhost->disc_buf_dma, GFP_KERNEL);
5830
5831         if (!vhost->disc_buf) {
5832                 dev_err(dev, "Couldn't allocate Discover Targets buffer\n");
5833                 goto free_login_buffer;
5834         }
5835
5836         vhost->trace = kcalloc(IBMVFC_NUM_TRACE_ENTRIES,
5837                                sizeof(struct ibmvfc_trace_entry), GFP_KERNEL);
5838         atomic_set(&vhost->trace_index, -1);
5839
5840         if (!vhost->trace)
5841                 goto free_disc_buffer;
5842
5843         vhost->tgt_pool = mempool_create_kmalloc_pool(IBMVFC_TGT_MEMPOOL_SZ,
5844                                                       sizeof(struct ibmvfc_target));
5845
5846         if (!vhost->tgt_pool) {
5847                 dev_err(dev, "Couldn't allocate target memory pool\n");
5848                 goto free_trace;
5849         }
5850
5851         vhost->channel_setup_buf = dma_alloc_coherent(dev, sizeof(*vhost->channel_setup_buf),
5852                                                       &vhost->channel_setup_dma,
5853                                                       GFP_KERNEL);
5854
5855         if (!vhost->channel_setup_buf) {
5856                 dev_err(dev, "Couldn't allocate Channel Setup buffer\n");
5857                 goto free_tgt_pool;
5858         }
5859
5860         LEAVE;
5861         return 0;
5862
5863 free_tgt_pool:
5864         mempool_destroy(vhost->tgt_pool);
5865 free_trace:
5866         kfree(vhost->trace);
5867 free_disc_buffer:
5868         dma_free_coherent(dev, vhost->disc_buf_sz, vhost->disc_buf,
5869                           vhost->disc_buf_dma);
5870 free_login_buffer:
5871         dma_free_coherent(dev, sizeof(*vhost->login_buf),
5872                           vhost->login_buf, vhost->login_buf_dma);
5873 free_sg_pool:
5874         dma_pool_destroy(vhost->sg_pool);
5875 unmap_async_crq:
5876         ibmvfc_free_queue(vhost, async_q);
5877 nomem:
5878         LEAVE;
5879         return -ENOMEM;
5880 }
5881
5882 /**
5883  * ibmvfc_rport_add_thread - Worker thread for rport adds
5884  * @work:       work struct
5885  *
5886  **/
5887 static void ibmvfc_rport_add_thread(struct work_struct *work)
5888 {
5889         struct ibmvfc_host *vhost = container_of(work, struct ibmvfc_host,
5890                                                  rport_add_work_q);
5891         struct ibmvfc_target *tgt;
5892         struct fc_rport *rport;
5893         unsigned long flags;
5894         int did_work;
5895
5896         ENTER;
5897         spin_lock_irqsave(vhost->host->host_lock, flags);
5898         do {
5899                 did_work = 0;
5900                 if (vhost->state != IBMVFC_ACTIVE)
5901                         break;
5902
5903                 list_for_each_entry(tgt, &vhost->targets, queue) {
5904                         if (tgt->add_rport) {
5905                                 did_work = 1;
5906                                 tgt->add_rport = 0;
5907                                 kref_get(&tgt->kref);
5908                                 rport = tgt->rport;
5909                                 if (!rport) {
5910                                         spin_unlock_irqrestore(vhost->host->host_lock, flags);
5911                                         ibmvfc_tgt_add_rport(tgt);
5912                                 } else if (get_device(&rport->dev)) {
5913                                         spin_unlock_irqrestore(vhost->host->host_lock, flags);
5914                                         tgt_dbg(tgt, "Setting rport roles\n");
5915                                         fc_remote_port_rolechg(rport, tgt->ids.roles);
5916                                         put_device(&rport->dev);
5917                                 } else {
5918                                         spin_unlock_irqrestore(vhost->host->host_lock, flags);
5919                                 }
5920
5921                                 kref_put(&tgt->kref, ibmvfc_release_tgt);
5922                                 spin_lock_irqsave(vhost->host->host_lock, flags);
5923                                 break;
5924                         }
5925                 }
5926         } while(did_work);
5927
5928         if (vhost->state == IBMVFC_ACTIVE)
5929                 vhost->scan_complete = 1;
5930         spin_unlock_irqrestore(vhost->host->host_lock, flags);
5931         LEAVE;
5932 }
5933
5934 /**
5935  * ibmvfc_probe - Adapter hot plug add entry point
5936  * @vdev:       vio device struct
5937  * @id: vio device id struct
5938  *
5939  * Return value:
5940  *      0 on success / non-zero on failure
5941  **/
5942 static int ibmvfc_probe(struct vio_dev *vdev, const struct vio_device_id *id)
5943 {
5944         struct ibmvfc_host *vhost;
5945         struct Scsi_Host *shost;
5946         struct device *dev = &vdev->dev;
5947         int rc = -ENOMEM;
5948         unsigned int max_scsi_queues = IBMVFC_MAX_SCSI_QUEUES;
5949
5950         ENTER;
5951         shost = scsi_host_alloc(&driver_template, sizeof(*vhost));
5952         if (!shost) {
5953                 dev_err(dev, "Couldn't allocate host data\n");
5954                 goto out;
5955         }
5956
5957         shost->transportt = ibmvfc_transport_template;
5958         shost->can_queue = max_requests;
5959         shost->max_lun = max_lun;
5960         shost->max_id = max_targets;
5961         shost->max_sectors = IBMVFC_MAX_SECTORS;
5962         shost->max_cmd_len = IBMVFC_MAX_CDB_LEN;
5963         shost->unique_id = shost->host_no;
5964         shost->nr_hw_queues = mq_enabled ? min(max_scsi_queues, nr_scsi_hw_queues) : 1;
5965
5966         vhost = shost_priv(shost);
5967         INIT_LIST_HEAD(&vhost->targets);
5968         INIT_LIST_HEAD(&vhost->purge);
5969         sprintf(vhost->name, IBMVFC_NAME);
5970         vhost->host = shost;
5971         vhost->dev = dev;
5972         vhost->partition_number = -1;
5973         vhost->log_level = log_level;
5974         vhost->task_set = 1;
5975
5976         vhost->mq_enabled = mq_enabled;
5977         vhost->client_scsi_channels = min(shost->nr_hw_queues, nr_scsi_channels);
5978         vhost->using_channels = 0;
5979         vhost->do_enquiry = 1;
5980
5981         strcpy(vhost->partition_name, "UNKNOWN");
5982         init_waitqueue_head(&vhost->work_wait_q);
5983         init_waitqueue_head(&vhost->init_wait_q);
5984         INIT_WORK(&vhost->rport_add_work_q, ibmvfc_rport_add_thread);
5985         mutex_init(&vhost->passthru_mutex);
5986
5987         if ((rc = ibmvfc_alloc_mem(vhost)))
5988                 goto free_scsi_host;
5989
5990         vhost->work_thread = kthread_run(ibmvfc_work, vhost, "%s_%d", IBMVFC_NAME,
5991                                          shost->host_no);
5992
5993         if (IS_ERR(vhost->work_thread)) {
5994                 dev_err(dev, "Couldn't create kernel thread: %ld\n",
5995                         PTR_ERR(vhost->work_thread));
5996                 rc = PTR_ERR(vhost->work_thread);
5997                 goto free_host_mem;
5998         }
5999
6000         if ((rc = ibmvfc_init_crq(vhost))) {
6001                 dev_err(dev, "Couldn't initialize crq. rc=%d\n", rc);
6002                 goto kill_kthread;
6003         }
6004
6005         if ((rc = scsi_add_host(shost, dev)))
6006                 goto release_crq;
6007
6008         fc_host_dev_loss_tmo(shost) = IBMVFC_DEV_LOSS_TMO;
6009
6010         if ((rc = ibmvfc_create_trace_file(&shost->shost_dev.kobj,
6011                                            &ibmvfc_trace_attr))) {
6012                 dev_err(dev, "Failed to create trace file. rc=%d\n", rc);
6013                 goto remove_shost;
6014         }
6015
6016         ibmvfc_init_sub_crqs(vhost);
6017
6018         if (shost_to_fc_host(shost)->rqst_q)
6019                 blk_queue_max_segments(shost_to_fc_host(shost)->rqst_q, 1);
6020         dev_set_drvdata(dev, vhost);
6021         spin_lock(&ibmvfc_driver_lock);
6022         list_add_tail(&vhost->queue, &ibmvfc_head);
6023         spin_unlock(&ibmvfc_driver_lock);
6024
6025         ibmvfc_send_crq_init(vhost);
6026         scsi_scan_host(shost);
6027         return 0;
6028
6029 remove_shost:
6030         scsi_remove_host(shost);
6031 release_crq:
6032         ibmvfc_release_crq_queue(vhost);
6033 kill_kthread:
6034         kthread_stop(vhost->work_thread);
6035 free_host_mem:
6036         ibmvfc_free_mem(vhost);
6037 free_scsi_host:
6038         scsi_host_put(shost);
6039 out:
6040         LEAVE;
6041         return rc;
6042 }
6043
6044 /**
6045  * ibmvfc_remove - Adapter hot plug remove entry point
6046  * @vdev:       vio device struct
6047  *
6048  * Return value:
6049  *      0
6050  **/
6051 static void ibmvfc_remove(struct vio_dev *vdev)
6052 {
6053         struct ibmvfc_host *vhost = dev_get_drvdata(&vdev->dev);
6054         LIST_HEAD(purge);
6055         unsigned long flags;
6056
6057         ENTER;
6058         ibmvfc_remove_trace_file(&vhost->host->shost_dev.kobj, &ibmvfc_trace_attr);
6059
6060         spin_lock_irqsave(vhost->host->host_lock, flags);
6061         ibmvfc_link_down(vhost, IBMVFC_HOST_OFFLINE);
6062         spin_unlock_irqrestore(vhost->host->host_lock, flags);
6063
6064         ibmvfc_wait_while_resetting(vhost);
6065         kthread_stop(vhost->work_thread);
6066         fc_remove_host(vhost->host);
6067         scsi_remove_host(vhost->host);
6068
6069         spin_lock_irqsave(vhost->host->host_lock, flags);
6070         ibmvfc_purge_requests(vhost, DID_ERROR);
6071         list_splice_init(&vhost->purge, &purge);
6072         spin_unlock_irqrestore(vhost->host->host_lock, flags);
6073         ibmvfc_complete_purge(&purge);
6074         ibmvfc_release_sub_crqs(vhost);
6075         ibmvfc_release_crq_queue(vhost);
6076
6077         ibmvfc_free_mem(vhost);
6078         spin_lock(&ibmvfc_driver_lock);
6079         list_del(&vhost->queue);
6080         spin_unlock(&ibmvfc_driver_lock);
6081         scsi_host_put(vhost->host);
6082         LEAVE;
6083 }
6084
6085 /**
6086  * ibmvfc_resume - Resume from suspend
6087  * @dev:        device struct
6088  *
6089  * We may have lost an interrupt across suspend/resume, so kick the
6090  * interrupt handler
6091  *
6092  */
6093 static int ibmvfc_resume(struct device *dev)
6094 {
6095         unsigned long flags;
6096         struct ibmvfc_host *vhost = dev_get_drvdata(dev);
6097         struct vio_dev *vdev = to_vio_dev(dev);
6098
6099         spin_lock_irqsave(vhost->host->host_lock, flags);
6100         vio_disable_interrupts(vdev);
6101         tasklet_schedule(&vhost->tasklet);
6102         spin_unlock_irqrestore(vhost->host->host_lock, flags);
6103         return 0;
6104 }
6105
6106 /**
6107  * ibmvfc_get_desired_dma - Calculate DMA resources needed by the driver
6108  * @vdev:       vio device struct
6109  *
6110  * Return value:
6111  *      Number of bytes the driver will need to DMA map at the same time in
6112  *      order to perform well.
6113  */
6114 static unsigned long ibmvfc_get_desired_dma(struct vio_dev *vdev)
6115 {
6116         unsigned long pool_dma = max_requests * sizeof(union ibmvfc_iu);
6117         return pool_dma + ((512 * 1024) * driver_template.cmd_per_lun);
6118 }
6119
6120 static const struct vio_device_id ibmvfc_device_table[] = {
6121         {"fcp", "IBM,vfc-client"},
6122         { "", "" }
6123 };
6124 MODULE_DEVICE_TABLE(vio, ibmvfc_device_table);
6125
6126 static const struct dev_pm_ops ibmvfc_pm_ops = {
6127         .resume = ibmvfc_resume
6128 };
6129
6130 static struct vio_driver ibmvfc_driver = {
6131         .id_table = ibmvfc_device_table,
6132         .probe = ibmvfc_probe,
6133         .remove = ibmvfc_remove,
6134         .get_desired_dma = ibmvfc_get_desired_dma,
6135         .name = IBMVFC_NAME,
6136         .pm = &ibmvfc_pm_ops,
6137 };
6138
6139 static struct fc_function_template ibmvfc_transport_functions = {
6140         .show_host_fabric_name = 1,
6141         .show_host_node_name = 1,
6142         .show_host_port_name = 1,
6143         .show_host_supported_classes = 1,
6144         .show_host_port_type = 1,
6145         .show_host_port_id = 1,
6146         .show_host_maxframe_size = 1,
6147
6148         .get_host_port_state = ibmvfc_get_host_port_state,
6149         .show_host_port_state = 1,
6150
6151         .get_host_speed = ibmvfc_get_host_speed,
6152         .show_host_speed = 1,
6153
6154         .issue_fc_host_lip = ibmvfc_issue_fc_host_lip,
6155         .terminate_rport_io = ibmvfc_terminate_rport_io,
6156
6157         .show_rport_maxframe_size = 1,
6158         .show_rport_supported_classes = 1,
6159
6160         .set_rport_dev_loss_tmo = ibmvfc_set_rport_dev_loss_tmo,
6161         .show_rport_dev_loss_tmo = 1,
6162
6163         .get_starget_node_name = ibmvfc_get_starget_node_name,
6164         .show_starget_node_name = 1,
6165
6166         .get_starget_port_name = ibmvfc_get_starget_port_name,
6167         .show_starget_port_name = 1,
6168
6169         .get_starget_port_id = ibmvfc_get_starget_port_id,
6170         .show_starget_port_id = 1,
6171
6172         .bsg_request = ibmvfc_bsg_request,
6173         .bsg_timeout = ibmvfc_bsg_timeout,
6174 };
6175
6176 /**
6177  * ibmvfc_module_init - Initialize the ibmvfc module
6178  *
6179  * Return value:
6180  *      0 on success / other on failure
6181  **/
6182 static int __init ibmvfc_module_init(void)
6183 {
6184         int rc;
6185
6186         if (!firmware_has_feature(FW_FEATURE_VIO))
6187                 return -ENODEV;
6188
6189         printk(KERN_INFO IBMVFC_NAME": IBM Virtual Fibre Channel Driver version: %s %s\n",
6190                IBMVFC_DRIVER_VERSION, IBMVFC_DRIVER_DATE);
6191
6192         ibmvfc_transport_template = fc_attach_transport(&ibmvfc_transport_functions);
6193         if (!ibmvfc_transport_template)
6194                 return -ENOMEM;
6195
6196         rc = vio_register_driver(&ibmvfc_driver);
6197         if (rc)
6198                 fc_release_transport(ibmvfc_transport_template);
6199         return rc;
6200 }
6201
6202 /**
6203  * ibmvfc_module_exit - Teardown the ibmvfc module
6204  *
6205  * Return value:
6206  *      nothing
6207  **/
6208 static void __exit ibmvfc_module_exit(void)
6209 {
6210         vio_unregister_driver(&ibmvfc_driver);
6211         fc_release_transport(ibmvfc_transport_template);
6212 }
6213
6214 module_init(ibmvfc_module_init);
6215 module_exit(ibmvfc_module_exit);