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