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