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