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