Merge branch 'for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/anholt...
[pandora-kernel.git] / drivers / scsi / scsi_transport_fc.c
1 /*
2  *  FiberChannel transport specific attributes exported to sysfs.
3  *
4  *  Copyright (c) 2003 Silicon Graphics, Inc.  All rights reserved.
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 2 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  *  ========
21  *
22  *  Copyright (C) 2004-2007   James Smart, Emulex Corporation
23  *    Rewrite for host, target, device, and remote port attributes,
24  *    statistics, and service functions...
25  *    Add vports, etc
26  *
27  */
28 #include <linux/module.h>
29 #include <linux/init.h>
30 #include <linux/delay.h>
31 #include <scsi/scsi_device.h>
32 #include <scsi/scsi_host.h>
33 #include <scsi/scsi_transport.h>
34 #include <scsi/scsi_transport_fc.h>
35 #include <scsi/scsi_cmnd.h>
36 #include <linux/netlink.h>
37 #include <net/netlink.h>
38 #include <scsi/scsi_netlink_fc.h>
39 #include <scsi/scsi_bsg_fc.h>
40 #include "scsi_priv.h"
41 #include "scsi_transport_fc_internal.h"
42
43 static int fc_queue_work(struct Scsi_Host *, struct work_struct *);
44 static void fc_vport_sched_delete(struct work_struct *work);
45 static int fc_vport_setup(struct Scsi_Host *shost, int channel,
46         struct device *pdev, struct fc_vport_identifiers  *ids,
47         struct fc_vport **vport);
48 static int fc_bsg_hostadd(struct Scsi_Host *, struct fc_host_attrs *);
49 static int fc_bsg_rportadd(struct Scsi_Host *, struct fc_rport *);
50 static void fc_bsg_remove(struct request_queue *);
51 static void fc_bsg_goose_queue(struct fc_rport *);
52
53 /*
54  * Redefine so that we can have same named attributes in the
55  * sdev/starget/host objects.
56  */
57 #define FC_DEVICE_ATTR(_prefix,_name,_mode,_show,_store)                \
58 struct device_attribute device_attr_##_prefix##_##_name =       \
59         __ATTR(_name,_mode,_show,_store)
60
61 #define fc_enum_name_search(title, table_type, table)                   \
62 static const char *get_fc_##title##_name(enum table_type table_key)     \
63 {                                                                       \
64         int i;                                                          \
65         char *name = NULL;                                              \
66                                                                         \
67         for (i = 0; i < ARRAY_SIZE(table); i++) {                       \
68                 if (table[i].value == table_key) {                      \
69                         name = table[i].name;                           \
70                         break;                                          \
71                 }                                                       \
72         }                                                               \
73         return name;                                                    \
74 }
75
76 #define fc_enum_name_match(title, table_type, table)                    \
77 static int get_fc_##title##_match(const char *table_key,                \
78                 enum table_type *value)                                 \
79 {                                                                       \
80         int i;                                                          \
81                                                                         \
82         for (i = 0; i < ARRAY_SIZE(table); i++) {                       \
83                 if (strncmp(table_key, table[i].name,                   \
84                                 table[i].matchlen) == 0) {              \
85                         *value = table[i].value;                        \
86                         return 0; /* success */                         \
87                 }                                                       \
88         }                                                               \
89         return 1; /* failure */                                         \
90 }
91
92
93 /* Convert fc_port_type values to ascii string name */
94 static struct {
95         enum fc_port_type       value;
96         char                    *name;
97 } fc_port_type_names[] = {
98         { FC_PORTTYPE_UNKNOWN,          "Unknown" },
99         { FC_PORTTYPE_OTHER,            "Other" },
100         { FC_PORTTYPE_NOTPRESENT,       "Not Present" },
101         { FC_PORTTYPE_NPORT,    "NPort (fabric via point-to-point)" },
102         { FC_PORTTYPE_NLPORT,   "NLPort (fabric via loop)" },
103         { FC_PORTTYPE_LPORT,    "LPort (private loop)" },
104         { FC_PORTTYPE_PTP,      "Point-To-Point (direct nport connection)" },
105         { FC_PORTTYPE_NPIV,             "NPIV VPORT" },
106 };
107 fc_enum_name_search(port_type, fc_port_type, fc_port_type_names)
108 #define FC_PORTTYPE_MAX_NAMELEN         50
109
110 /* Reuse fc_port_type enum function for vport_type */
111 #define get_fc_vport_type_name get_fc_port_type_name
112
113
114 /* Convert fc_host_event_code values to ascii string name */
115 static const struct {
116         enum fc_host_event_code         value;
117         char                            *name;
118 } fc_host_event_code_names[] = {
119         { FCH_EVT_LIP,                  "lip" },
120         { FCH_EVT_LINKUP,               "link_up" },
121         { FCH_EVT_LINKDOWN,             "link_down" },
122         { FCH_EVT_LIPRESET,             "lip_reset" },
123         { FCH_EVT_RSCN,                 "rscn" },
124         { FCH_EVT_ADAPTER_CHANGE,       "adapter_chg" },
125         { FCH_EVT_PORT_UNKNOWN,         "port_unknown" },
126         { FCH_EVT_PORT_ONLINE,          "port_online" },
127         { FCH_EVT_PORT_OFFLINE,         "port_offline" },
128         { FCH_EVT_PORT_FABRIC,          "port_fabric" },
129         { FCH_EVT_LINK_UNKNOWN,         "link_unknown" },
130         { FCH_EVT_VENDOR_UNIQUE,        "vendor_unique" },
131 };
132 fc_enum_name_search(host_event_code, fc_host_event_code,
133                 fc_host_event_code_names)
134 #define FC_HOST_EVENT_CODE_MAX_NAMELEN  30
135
136
137 /* Convert fc_port_state values to ascii string name */
138 static struct {
139         enum fc_port_state      value;
140         char                    *name;
141 } fc_port_state_names[] = {
142         { FC_PORTSTATE_UNKNOWN,         "Unknown" },
143         { FC_PORTSTATE_NOTPRESENT,      "Not Present" },
144         { FC_PORTSTATE_ONLINE,          "Online" },
145         { FC_PORTSTATE_OFFLINE,         "Offline" },
146         { FC_PORTSTATE_BLOCKED,         "Blocked" },
147         { FC_PORTSTATE_BYPASSED,        "Bypassed" },
148         { FC_PORTSTATE_DIAGNOSTICS,     "Diagnostics" },
149         { FC_PORTSTATE_LINKDOWN,        "Linkdown" },
150         { FC_PORTSTATE_ERROR,           "Error" },
151         { FC_PORTSTATE_LOOPBACK,        "Loopback" },
152         { FC_PORTSTATE_DELETED,         "Deleted" },
153 };
154 fc_enum_name_search(port_state, fc_port_state, fc_port_state_names)
155 #define FC_PORTSTATE_MAX_NAMELEN        20
156
157
158 /* Convert fc_vport_state values to ascii string name */
159 static struct {
160         enum fc_vport_state     value;
161         char                    *name;
162 } fc_vport_state_names[] = {
163         { FC_VPORT_UNKNOWN,             "Unknown" },
164         { FC_VPORT_ACTIVE,              "Active" },
165         { FC_VPORT_DISABLED,            "Disabled" },
166         { FC_VPORT_LINKDOWN,            "Linkdown" },
167         { FC_VPORT_INITIALIZING,        "Initializing" },
168         { FC_VPORT_NO_FABRIC_SUPP,      "No Fabric Support" },
169         { FC_VPORT_NO_FABRIC_RSCS,      "No Fabric Resources" },
170         { FC_VPORT_FABRIC_LOGOUT,       "Fabric Logout" },
171         { FC_VPORT_FABRIC_REJ_WWN,      "Fabric Rejected WWN" },
172         { FC_VPORT_FAILED,              "VPort Failed" },
173 };
174 fc_enum_name_search(vport_state, fc_vport_state, fc_vport_state_names)
175 #define FC_VPORTSTATE_MAX_NAMELEN       24
176
177 /* Reuse fc_vport_state enum function for vport_last_state */
178 #define get_fc_vport_last_state_name get_fc_vport_state_name
179
180
181 /* Convert fc_tgtid_binding_type values to ascii string name */
182 static const struct {
183         enum fc_tgtid_binding_type      value;
184         char                            *name;
185         int                             matchlen;
186 } fc_tgtid_binding_type_names[] = {
187         { FC_TGTID_BIND_NONE, "none", 4 },
188         { FC_TGTID_BIND_BY_WWPN, "wwpn (World Wide Port Name)", 4 },
189         { FC_TGTID_BIND_BY_WWNN, "wwnn (World Wide Node Name)", 4 },
190         { FC_TGTID_BIND_BY_ID, "port_id (FC Address)", 7 },
191 };
192 fc_enum_name_search(tgtid_bind_type, fc_tgtid_binding_type,
193                 fc_tgtid_binding_type_names)
194 fc_enum_name_match(tgtid_bind_type, fc_tgtid_binding_type,
195                 fc_tgtid_binding_type_names)
196 #define FC_BINDTYPE_MAX_NAMELEN 30
197
198
199 #define fc_bitfield_name_search(title, table)                   \
200 static ssize_t                                                  \
201 get_fc_##title##_names(u32 table_key, char *buf)                \
202 {                                                               \
203         char *prefix = "";                                      \
204         ssize_t len = 0;                                        \
205         int i;                                                  \
206                                                                 \
207         for (i = 0; i < ARRAY_SIZE(table); i++) {               \
208                 if (table[i].value & table_key) {               \
209                         len += sprintf(buf + len, "%s%s",       \
210                                 prefix, table[i].name);         \
211                         prefix = ", ";                          \
212                 }                                               \
213         }                                                       \
214         len += sprintf(buf + len, "\n");                        \
215         return len;                                             \
216 }
217
218
219 /* Convert FC_COS bit values to ascii string name */
220 static const struct {
221         u32                     value;
222         char                    *name;
223 } fc_cos_names[] = {
224         { FC_COS_CLASS1,        "Class 1" },
225         { FC_COS_CLASS2,        "Class 2" },
226         { FC_COS_CLASS3,        "Class 3" },
227         { FC_COS_CLASS4,        "Class 4" },
228         { FC_COS_CLASS6,        "Class 6" },
229 };
230 fc_bitfield_name_search(cos, fc_cos_names)
231
232
233 /* Convert FC_PORTSPEED bit values to ascii string name */
234 static const struct {
235         u32                     value;
236         char                    *name;
237 } fc_port_speed_names[] = {
238         { FC_PORTSPEED_1GBIT,           "1 Gbit" },
239         { FC_PORTSPEED_2GBIT,           "2 Gbit" },
240         { FC_PORTSPEED_4GBIT,           "4 Gbit" },
241         { FC_PORTSPEED_10GBIT,          "10 Gbit" },
242         { FC_PORTSPEED_8GBIT,           "8 Gbit" },
243         { FC_PORTSPEED_16GBIT,          "16 Gbit" },
244         { FC_PORTSPEED_NOT_NEGOTIATED,  "Not Negotiated" },
245 };
246 fc_bitfield_name_search(port_speed, fc_port_speed_names)
247
248
249 static int
250 show_fc_fc4s (char *buf, u8 *fc4_list)
251 {
252         int i, len=0;
253
254         for (i = 0; i < FC_FC4_LIST_SIZE; i++, fc4_list++)
255                 len += sprintf(buf + len , "0x%02x ", *fc4_list);
256         len += sprintf(buf + len, "\n");
257         return len;
258 }
259
260
261 /* Convert FC_PORT_ROLE bit values to ascii string name */
262 static const struct {
263         u32                     value;
264         char                    *name;
265 } fc_port_role_names[] = {
266         { FC_PORT_ROLE_FCP_TARGET,      "FCP Target" },
267         { FC_PORT_ROLE_FCP_INITIATOR,   "FCP Initiator" },
268         { FC_PORT_ROLE_IP_PORT,         "IP Port" },
269 };
270 fc_bitfield_name_search(port_roles, fc_port_role_names)
271
272 /*
273  * Define roles that are specific to port_id. Values are relative to ROLE_MASK.
274  */
275 #define FC_WELLKNOWN_PORTID_MASK        0xfffff0
276 #define FC_WELLKNOWN_ROLE_MASK          0x00000f
277 #define FC_FPORT_PORTID                 0x00000e
278 #define FC_FABCTLR_PORTID               0x00000d
279 #define FC_DIRSRVR_PORTID               0x00000c
280 #define FC_TIMESRVR_PORTID              0x00000b
281 #define FC_MGMTSRVR_PORTID              0x00000a
282
283
284 static void fc_timeout_deleted_rport(struct work_struct *work);
285 static void fc_timeout_fail_rport_io(struct work_struct *work);
286 static void fc_scsi_scan_rport(struct work_struct *work);
287
288 /*
289  * Attribute counts pre object type...
290  * Increase these values if you add attributes
291  */
292 #define FC_STARGET_NUM_ATTRS    3
293 #define FC_RPORT_NUM_ATTRS      10
294 #define FC_VPORT_NUM_ATTRS      9
295 #define FC_HOST_NUM_ATTRS       22
296
297 struct fc_internal {
298         struct scsi_transport_template t;
299         struct fc_function_template *f;
300
301         /*
302          * For attributes : each object has :
303          *   An array of the actual attributes structures
304          *   An array of null-terminated pointers to the attribute
305          *     structures - used for mid-layer interaction.
306          *
307          * The attribute containers for the starget and host are are
308          * part of the midlayer. As the remote port is specific to the
309          * fc transport, we must provide the attribute container.
310          */
311         struct device_attribute private_starget_attrs[
312                                                         FC_STARGET_NUM_ATTRS];
313         struct device_attribute *starget_attrs[FC_STARGET_NUM_ATTRS + 1];
314
315         struct device_attribute private_host_attrs[FC_HOST_NUM_ATTRS];
316         struct device_attribute *host_attrs[FC_HOST_NUM_ATTRS + 1];
317
318         struct transport_container rport_attr_cont;
319         struct device_attribute private_rport_attrs[FC_RPORT_NUM_ATTRS];
320         struct device_attribute *rport_attrs[FC_RPORT_NUM_ATTRS + 1];
321
322         struct transport_container vport_attr_cont;
323         struct device_attribute private_vport_attrs[FC_VPORT_NUM_ATTRS];
324         struct device_attribute *vport_attrs[FC_VPORT_NUM_ATTRS + 1];
325 };
326
327 #define to_fc_internal(tmpl)    container_of(tmpl, struct fc_internal, t)
328
329 static int fc_target_setup(struct transport_container *tc, struct device *dev,
330                            struct device *cdev)
331 {
332         struct scsi_target *starget = to_scsi_target(dev);
333         struct fc_rport *rport = starget_to_rport(starget);
334
335         /*
336          * if parent is remote port, use values from remote port.
337          * Otherwise, this host uses the fc_transport, but not the
338          * remote port interface. As such, initialize to known non-values.
339          */
340         if (rport) {
341                 fc_starget_node_name(starget) = rport->node_name;
342                 fc_starget_port_name(starget) = rport->port_name;
343                 fc_starget_port_id(starget) = rport->port_id;
344         } else {
345                 fc_starget_node_name(starget) = -1;
346                 fc_starget_port_name(starget) = -1;
347                 fc_starget_port_id(starget) = -1;
348         }
349
350         return 0;
351 }
352
353 static DECLARE_TRANSPORT_CLASS(fc_transport_class,
354                                "fc_transport",
355                                fc_target_setup,
356                                NULL,
357                                NULL);
358
359 static int fc_host_setup(struct transport_container *tc, struct device *dev,
360                          struct device *cdev)
361 {
362         struct Scsi_Host *shost = dev_to_shost(dev);
363         struct fc_host_attrs *fc_host = shost_to_fc_host(shost);
364
365         /*
366          * Set default values easily detected by the midlayer as
367          * failure cases.  The scsi lldd is responsible for initializing
368          * all transport attributes to valid values per host.
369          */
370         fc_host->node_name = -1;
371         fc_host->port_name = -1;
372         fc_host->permanent_port_name = -1;
373         fc_host->supported_classes = FC_COS_UNSPECIFIED;
374         memset(fc_host->supported_fc4s, 0,
375                 sizeof(fc_host->supported_fc4s));
376         fc_host->supported_speeds = FC_PORTSPEED_UNKNOWN;
377         fc_host->maxframe_size = -1;
378         fc_host->max_npiv_vports = 0;
379         memset(fc_host->serial_number, 0,
380                 sizeof(fc_host->serial_number));
381
382         fc_host->port_id = -1;
383         fc_host->port_type = FC_PORTTYPE_UNKNOWN;
384         fc_host->port_state = FC_PORTSTATE_UNKNOWN;
385         memset(fc_host->active_fc4s, 0,
386                 sizeof(fc_host->active_fc4s));
387         fc_host->speed = FC_PORTSPEED_UNKNOWN;
388         fc_host->fabric_name = -1;
389         memset(fc_host->symbolic_name, 0, sizeof(fc_host->symbolic_name));
390         memset(fc_host->system_hostname, 0, sizeof(fc_host->system_hostname));
391
392         fc_host->tgtid_bind_type = FC_TGTID_BIND_BY_WWPN;
393
394         INIT_LIST_HEAD(&fc_host->rports);
395         INIT_LIST_HEAD(&fc_host->rport_bindings);
396         INIT_LIST_HEAD(&fc_host->vports);
397         fc_host->next_rport_number = 0;
398         fc_host->next_target_id = 0;
399         fc_host->next_vport_number = 0;
400         fc_host->npiv_vports_inuse = 0;
401
402         snprintf(fc_host->work_q_name, sizeof(fc_host->work_q_name),
403                  "fc_wq_%d", shost->host_no);
404         fc_host->work_q = create_singlethread_workqueue(
405                                         fc_host->work_q_name);
406         if (!fc_host->work_q)
407                 return -ENOMEM;
408
409         snprintf(fc_host->devloss_work_q_name,
410                  sizeof(fc_host->devloss_work_q_name),
411                  "fc_dl_%d", shost->host_no);
412         fc_host->devloss_work_q = create_singlethread_workqueue(
413                                         fc_host->devloss_work_q_name);
414         if (!fc_host->devloss_work_q) {
415                 destroy_workqueue(fc_host->work_q);
416                 fc_host->work_q = NULL;
417                 return -ENOMEM;
418         }
419
420         fc_bsg_hostadd(shost, fc_host);
421         /* ignore any bsg add error - we just can't do sgio */
422
423         return 0;
424 }
425
426 static int fc_host_remove(struct transport_container *tc, struct device *dev,
427                          struct device *cdev)
428 {
429         struct Scsi_Host *shost = dev_to_shost(dev);
430         struct fc_host_attrs *fc_host = shost_to_fc_host(shost);
431
432         fc_bsg_remove(fc_host->rqst_q);
433         return 0;
434 }
435
436 static DECLARE_TRANSPORT_CLASS(fc_host_class,
437                                "fc_host",
438                                fc_host_setup,
439                                fc_host_remove,
440                                NULL);
441
442 /*
443  * Setup and Remove actions for remote ports are handled
444  * in the service functions below.
445  */
446 static DECLARE_TRANSPORT_CLASS(fc_rport_class,
447                                "fc_remote_ports",
448                                NULL,
449                                NULL,
450                                NULL);
451
452 /*
453  * Setup and Remove actions for virtual ports are handled
454  * in the service functions below.
455  */
456 static DECLARE_TRANSPORT_CLASS(fc_vport_class,
457                                "fc_vports",
458                                NULL,
459                                NULL,
460                                NULL);
461
462 /*
463  * Module Parameters
464  */
465
466 /*
467  * dev_loss_tmo: the default number of seconds that the FC transport
468  *   should insulate the loss of a remote port.
469  *   The maximum will be capped by the value of SCSI_DEVICE_BLOCK_MAX_TIMEOUT.
470  */
471 static unsigned int fc_dev_loss_tmo = 60;               /* seconds */
472
473 module_param_named(dev_loss_tmo, fc_dev_loss_tmo, uint, S_IRUGO|S_IWUSR);
474 MODULE_PARM_DESC(dev_loss_tmo,
475                  "Maximum number of seconds that the FC transport should"
476                  " insulate the loss of a remote port. Once this value is"
477                  " exceeded, the scsi target is removed. Value should be"
478                  " between 1 and SCSI_DEVICE_BLOCK_MAX_TIMEOUT if"
479                  " fast_io_fail_tmo is not set.");
480
481 /*
482  * Netlink Infrastructure
483  */
484
485 static atomic_t fc_event_seq;
486
487 /**
488  * fc_get_event_number - Obtain the next sequential FC event number
489  *
490  * Notes:
491  *   We could have inlined this, but it would have required fc_event_seq to
492  *   be exposed. For now, live with the subroutine call.
493  *   Atomic used to avoid lock/unlock...
494  */
495 u32
496 fc_get_event_number(void)
497 {
498         return atomic_add_return(1, &fc_event_seq);
499 }
500 EXPORT_SYMBOL(fc_get_event_number);
501
502
503 /**
504  * fc_host_post_event - called to post an even on an fc_host.
505  * @shost:              host the event occurred on
506  * @event_number:       fc event number obtained from get_fc_event_number()
507  * @event_code:         fc_host event being posted
508  * @event_data:         32bits of data for the event being posted
509  *
510  * Notes:
511  *      This routine assumes no locks are held on entry.
512  */
513 void
514 fc_host_post_event(struct Scsi_Host *shost, u32 event_number,
515                 enum fc_host_event_code event_code, u32 event_data)
516 {
517         struct sk_buff *skb;
518         struct nlmsghdr *nlh;
519         struct fc_nl_event *event;
520         const char *name;
521         u32 len, skblen;
522         int err;
523
524         if (!scsi_nl_sock) {
525                 err = -ENOENT;
526                 goto send_fail;
527         }
528
529         len = FC_NL_MSGALIGN(sizeof(*event));
530         skblen = NLMSG_SPACE(len);
531
532         skb = alloc_skb(skblen, GFP_KERNEL);
533         if (!skb) {
534                 err = -ENOBUFS;
535                 goto send_fail;
536         }
537
538         nlh = nlmsg_put(skb, 0, 0, SCSI_TRANSPORT_MSG,
539                                 skblen - sizeof(*nlh), 0);
540         if (!nlh) {
541                 err = -ENOBUFS;
542                 goto send_fail_skb;
543         }
544         event = NLMSG_DATA(nlh);
545
546         INIT_SCSI_NL_HDR(&event->snlh, SCSI_NL_TRANSPORT_FC,
547                                 FC_NL_ASYNC_EVENT, len);
548         event->seconds = get_seconds();
549         event->vendor_id = 0;
550         event->host_no = shost->host_no;
551         event->event_datalen = sizeof(u32);     /* bytes */
552         event->event_num = event_number;
553         event->event_code = event_code;
554         event->event_data = event_data;
555
556         nlmsg_multicast(scsi_nl_sock, skb, 0, SCSI_NL_GRP_FC_EVENTS,
557                         GFP_KERNEL);
558         return;
559
560 send_fail_skb:
561         kfree_skb(skb);
562 send_fail:
563         name = get_fc_host_event_code_name(event_code);
564         printk(KERN_WARNING
565                 "%s: Dropped Event : host %d %s data 0x%08x - err %d\n",
566                 __func__, shost->host_no,
567                 (name) ? name : "<unknown>", event_data, err);
568         return;
569 }
570 EXPORT_SYMBOL(fc_host_post_event);
571
572
573 /**
574  * fc_host_post_vendor_event - called to post a vendor unique event on an fc_host
575  * @shost:              host the event occurred on
576  * @event_number:       fc event number obtained from get_fc_event_number()
577  * @data_len:           amount, in bytes, of vendor unique data
578  * @data_buf:           pointer to vendor unique data
579  * @vendor_id:          Vendor id
580  *
581  * Notes:
582  *      This routine assumes no locks are held on entry.
583  */
584 void
585 fc_host_post_vendor_event(struct Scsi_Host *shost, u32 event_number,
586                 u32 data_len, char * data_buf, u64 vendor_id)
587 {
588         struct sk_buff *skb;
589         struct nlmsghdr *nlh;
590         struct fc_nl_event *event;
591         u32 len, skblen;
592         int err;
593
594         if (!scsi_nl_sock) {
595                 err = -ENOENT;
596                 goto send_vendor_fail;
597         }
598
599         len = FC_NL_MSGALIGN(sizeof(*event) + data_len);
600         skblen = NLMSG_SPACE(len);
601
602         skb = alloc_skb(skblen, GFP_KERNEL);
603         if (!skb) {
604                 err = -ENOBUFS;
605                 goto send_vendor_fail;
606         }
607
608         nlh = nlmsg_put(skb, 0, 0, SCSI_TRANSPORT_MSG,
609                                 skblen - sizeof(*nlh), 0);
610         if (!nlh) {
611                 err = -ENOBUFS;
612                 goto send_vendor_fail_skb;
613         }
614         event = NLMSG_DATA(nlh);
615
616         INIT_SCSI_NL_HDR(&event->snlh, SCSI_NL_TRANSPORT_FC,
617                                 FC_NL_ASYNC_EVENT, len);
618         event->seconds = get_seconds();
619         event->vendor_id = vendor_id;
620         event->host_no = shost->host_no;
621         event->event_datalen = data_len;        /* bytes */
622         event->event_num = event_number;
623         event->event_code = FCH_EVT_VENDOR_UNIQUE;
624         memcpy(&event->event_data, data_buf, data_len);
625
626         nlmsg_multicast(scsi_nl_sock, skb, 0, SCSI_NL_GRP_FC_EVENTS,
627                         GFP_KERNEL);
628         return;
629
630 send_vendor_fail_skb:
631         kfree_skb(skb);
632 send_vendor_fail:
633         printk(KERN_WARNING
634                 "%s: Dropped Event : host %d vendor_unique - err %d\n",
635                 __func__, shost->host_no, err);
636         return;
637 }
638 EXPORT_SYMBOL(fc_host_post_vendor_event);
639
640
641
642 static __init int fc_transport_init(void)
643 {
644         int error;
645
646         atomic_set(&fc_event_seq, 0);
647
648         error = transport_class_register(&fc_host_class);
649         if (error)
650                 return error;
651         error = transport_class_register(&fc_vport_class);
652         if (error)
653                 goto unreg_host_class;
654         error = transport_class_register(&fc_rport_class);
655         if (error)
656                 goto unreg_vport_class;
657         error = transport_class_register(&fc_transport_class);
658         if (error)
659                 goto unreg_rport_class;
660         return 0;
661
662 unreg_rport_class:
663         transport_class_unregister(&fc_rport_class);
664 unreg_vport_class:
665         transport_class_unregister(&fc_vport_class);
666 unreg_host_class:
667         transport_class_unregister(&fc_host_class);
668         return error;
669 }
670
671 static void __exit fc_transport_exit(void)
672 {
673         transport_class_unregister(&fc_transport_class);
674         transport_class_unregister(&fc_rport_class);
675         transport_class_unregister(&fc_host_class);
676         transport_class_unregister(&fc_vport_class);
677 }
678
679 /*
680  * FC Remote Port Attribute Management
681  */
682
683 #define fc_rport_show_function(field, format_string, sz, cast)          \
684 static ssize_t                                                          \
685 show_fc_rport_##field (struct device *dev,                              \
686                        struct device_attribute *attr, char *buf)        \
687 {                                                                       \
688         struct fc_rport *rport = transport_class_to_rport(dev);         \
689         struct Scsi_Host *shost = rport_to_shost(rport);                \
690         struct fc_internal *i = to_fc_internal(shost->transportt);      \
691         if ((i->f->get_rport_##field) &&                                \
692             !((rport->port_state == FC_PORTSTATE_BLOCKED) ||            \
693               (rport->port_state == FC_PORTSTATE_DELETED) ||            \
694               (rport->port_state == FC_PORTSTATE_NOTPRESENT)))          \
695                 i->f->get_rport_##field(rport);                         \
696         return snprintf(buf, sz, format_string, cast rport->field);     \
697 }
698
699 #define fc_rport_store_function(field)                                  \
700 static ssize_t                                                          \
701 store_fc_rport_##field(struct device *dev,                              \
702                        struct device_attribute *attr,                   \
703                        const char *buf, size_t count)                   \
704 {                                                                       \
705         int val;                                                        \
706         struct fc_rport *rport = transport_class_to_rport(dev);         \
707         struct Scsi_Host *shost = rport_to_shost(rport);                \
708         struct fc_internal *i = to_fc_internal(shost->transportt);      \
709         char *cp;                                                       \
710         if ((rport->port_state == FC_PORTSTATE_BLOCKED) ||              \
711             (rport->port_state == FC_PORTSTATE_DELETED) ||              \
712             (rport->port_state == FC_PORTSTATE_NOTPRESENT))             \
713                 return -EBUSY;                                          \
714         val = simple_strtoul(buf, &cp, 0);                              \
715         if (*cp && (*cp != '\n'))                                       \
716                 return -EINVAL;                                         \
717         i->f->set_rport_##field(rport, val);                            \
718         return count;                                                   \
719 }
720
721 #define fc_rport_rd_attr(field, format_string, sz)                      \
722         fc_rport_show_function(field, format_string, sz, )              \
723 static FC_DEVICE_ATTR(rport, field, S_IRUGO,                    \
724                          show_fc_rport_##field, NULL)
725
726 #define fc_rport_rd_attr_cast(field, format_string, sz, cast)           \
727         fc_rport_show_function(field, format_string, sz, (cast))        \
728 static FC_DEVICE_ATTR(rport, field, S_IRUGO,                    \
729                           show_fc_rport_##field, NULL)
730
731 #define fc_rport_rw_attr(field, format_string, sz)                      \
732         fc_rport_show_function(field, format_string, sz, )              \
733         fc_rport_store_function(field)                                  \
734 static FC_DEVICE_ATTR(rport, field, S_IRUGO | S_IWUSR,          \
735                         show_fc_rport_##field,                          \
736                         store_fc_rport_##field)
737
738
739 #define fc_private_rport_show_function(field, format_string, sz, cast)  \
740 static ssize_t                                                          \
741 show_fc_rport_##field (struct device *dev,                              \
742                        struct device_attribute *attr, char *buf)        \
743 {                                                                       \
744         struct fc_rport *rport = transport_class_to_rport(dev);         \
745         return snprintf(buf, sz, format_string, cast rport->field);     \
746 }
747
748 #define fc_private_rport_rd_attr(field, format_string, sz)              \
749         fc_private_rport_show_function(field, format_string, sz, )      \
750 static FC_DEVICE_ATTR(rport, field, S_IRUGO,                    \
751                          show_fc_rport_##field, NULL)
752
753 #define fc_private_rport_rd_attr_cast(field, format_string, sz, cast)   \
754         fc_private_rport_show_function(field, format_string, sz, (cast)) \
755 static FC_DEVICE_ATTR(rport, field, S_IRUGO,                    \
756                           show_fc_rport_##field, NULL)
757
758
759 #define fc_private_rport_rd_enum_attr(title, maxlen)                    \
760 static ssize_t                                                          \
761 show_fc_rport_##title (struct device *dev,                              \
762                        struct device_attribute *attr, char *buf)        \
763 {                                                                       \
764         struct fc_rport *rport = transport_class_to_rport(dev);         \
765         const char *name;                                               \
766         name = get_fc_##title##_name(rport->title);                     \
767         if (!name)                                                      \
768                 return -EINVAL;                                         \
769         return snprintf(buf, maxlen, "%s\n", name);                     \
770 }                                                                       \
771 static FC_DEVICE_ATTR(rport, title, S_IRUGO,                    \
772                         show_fc_rport_##title, NULL)
773
774
775 #define SETUP_RPORT_ATTRIBUTE_RD(field)                                 \
776         i->private_rport_attrs[count] = device_attr_rport_##field; \
777         i->private_rport_attrs[count].attr.mode = S_IRUGO;              \
778         i->private_rport_attrs[count].store = NULL;                     \
779         i->rport_attrs[count] = &i->private_rport_attrs[count];         \
780         if (i->f->show_rport_##field)                                   \
781                 count++
782
783 #define SETUP_PRIVATE_RPORT_ATTRIBUTE_RD(field)                         \
784         i->private_rport_attrs[count] = device_attr_rport_##field; \
785         i->private_rport_attrs[count].attr.mode = S_IRUGO;              \
786         i->private_rport_attrs[count].store = NULL;                     \
787         i->rport_attrs[count] = &i->private_rport_attrs[count];         \
788         count++
789
790 #define SETUP_RPORT_ATTRIBUTE_RW(field)                                 \
791         i->private_rport_attrs[count] = device_attr_rport_##field; \
792         if (!i->f->set_rport_##field) {                                 \
793                 i->private_rport_attrs[count].attr.mode = S_IRUGO;      \
794                 i->private_rport_attrs[count].store = NULL;             \
795         }                                                               \
796         i->rport_attrs[count] = &i->private_rport_attrs[count];         \
797         if (i->f->show_rport_##field)                                   \
798                 count++
799
800 #define SETUP_PRIVATE_RPORT_ATTRIBUTE_RW(field)                         \
801 {                                                                       \
802         i->private_rport_attrs[count] = device_attr_rport_##field; \
803         i->rport_attrs[count] = &i->private_rport_attrs[count];         \
804         count++;                                                        \
805 }
806
807
808 /* The FC Transport Remote Port Attributes: */
809
810 /* Fixed Remote Port Attributes */
811
812 fc_private_rport_rd_attr(maxframe_size, "%u bytes\n", 20);
813
814 static ssize_t
815 show_fc_rport_supported_classes (struct device *dev,
816                                  struct device_attribute *attr, char *buf)
817 {
818         struct fc_rport *rport = transport_class_to_rport(dev);
819         if (rport->supported_classes == FC_COS_UNSPECIFIED)
820                 return snprintf(buf, 20, "unspecified\n");
821         return get_fc_cos_names(rport->supported_classes, buf);
822 }
823 static FC_DEVICE_ATTR(rport, supported_classes, S_IRUGO,
824                 show_fc_rport_supported_classes, NULL);
825
826 /* Dynamic Remote Port Attributes */
827
828 /*
829  * dev_loss_tmo attribute
830  */
831 fc_rport_show_function(dev_loss_tmo, "%d\n", 20, )
832 static ssize_t
833 store_fc_rport_dev_loss_tmo(struct device *dev, struct device_attribute *attr,
834                             const char *buf, size_t count)
835 {
836         int val;
837         struct fc_rport *rport = transport_class_to_rport(dev);
838         struct Scsi_Host *shost = rport_to_shost(rport);
839         struct fc_internal *i = to_fc_internal(shost->transportt);
840         char *cp;
841         if ((rport->port_state == FC_PORTSTATE_BLOCKED) ||
842             (rport->port_state == FC_PORTSTATE_DELETED) ||
843             (rport->port_state == FC_PORTSTATE_NOTPRESENT))
844                 return -EBUSY;
845         val = simple_strtoul(buf, &cp, 0);
846         if ((*cp && (*cp != '\n')) || (val < 0))
847                 return -EINVAL;
848
849         /*
850          * If fast_io_fail is off we have to cap
851          * dev_loss_tmo at SCSI_DEVICE_BLOCK_MAX_TIMEOUT
852          */
853         if (rport->fast_io_fail_tmo == -1 &&
854             val > SCSI_DEVICE_BLOCK_MAX_TIMEOUT)
855                 return -EINVAL;
856
857         i->f->set_rport_dev_loss_tmo(rport, val);
858         return count;
859 }
860 static FC_DEVICE_ATTR(rport, dev_loss_tmo, S_IRUGO | S_IWUSR,
861                 show_fc_rport_dev_loss_tmo, store_fc_rport_dev_loss_tmo);
862
863
864 /* Private Remote Port Attributes */
865
866 fc_private_rport_rd_attr_cast(node_name, "0x%llx\n", 20, unsigned long long);
867 fc_private_rport_rd_attr_cast(port_name, "0x%llx\n", 20, unsigned long long);
868 fc_private_rport_rd_attr(port_id, "0x%06x\n", 20);
869
870 static ssize_t
871 show_fc_rport_roles (struct device *dev, struct device_attribute *attr,
872                      char *buf)
873 {
874         struct fc_rport *rport = transport_class_to_rport(dev);
875
876         /* identify any roles that are port_id specific */
877         if ((rport->port_id != -1) &&
878             (rport->port_id & FC_WELLKNOWN_PORTID_MASK) ==
879                                         FC_WELLKNOWN_PORTID_MASK) {
880                 switch (rport->port_id & FC_WELLKNOWN_ROLE_MASK) {
881                 case FC_FPORT_PORTID:
882                         return snprintf(buf, 30, "Fabric Port\n");
883                 case FC_FABCTLR_PORTID:
884                         return snprintf(buf, 30, "Fabric Controller\n");
885                 case FC_DIRSRVR_PORTID:
886                         return snprintf(buf, 30, "Directory Server\n");
887                 case FC_TIMESRVR_PORTID:
888                         return snprintf(buf, 30, "Time Server\n");
889                 case FC_MGMTSRVR_PORTID:
890                         return snprintf(buf, 30, "Management Server\n");
891                 default:
892                         return snprintf(buf, 30, "Unknown Fabric Entity\n");
893                 }
894         } else {
895                 if (rport->roles == FC_PORT_ROLE_UNKNOWN)
896                         return snprintf(buf, 20, "unknown\n");
897                 return get_fc_port_roles_names(rport->roles, buf);
898         }
899 }
900 static FC_DEVICE_ATTR(rport, roles, S_IRUGO,
901                 show_fc_rport_roles, NULL);
902
903 fc_private_rport_rd_enum_attr(port_state, FC_PORTSTATE_MAX_NAMELEN);
904 fc_private_rport_rd_attr(scsi_target_id, "%d\n", 20);
905
906 /*
907  * fast_io_fail_tmo attribute
908  */
909 static ssize_t
910 show_fc_rport_fast_io_fail_tmo (struct device *dev,
911                                 struct device_attribute *attr, char *buf)
912 {
913         struct fc_rport *rport = transport_class_to_rport(dev);
914
915         if (rport->fast_io_fail_tmo == -1)
916                 return snprintf(buf, 5, "off\n");
917         return snprintf(buf, 20, "%d\n", rport->fast_io_fail_tmo);
918 }
919
920 static ssize_t
921 store_fc_rport_fast_io_fail_tmo(struct device *dev,
922                                 struct device_attribute *attr, const char *buf,
923                                 size_t count)
924 {
925         int val;
926         char *cp;
927         struct fc_rport *rport = transport_class_to_rport(dev);
928
929         if ((rport->port_state == FC_PORTSTATE_BLOCKED) ||
930             (rport->port_state == FC_PORTSTATE_DELETED) ||
931             (rport->port_state == FC_PORTSTATE_NOTPRESENT))
932                 return -EBUSY;
933         if (strncmp(buf, "off", 3) == 0)
934                 rport->fast_io_fail_tmo = -1;
935         else {
936                 val = simple_strtoul(buf, &cp, 0);
937                 if ((*cp && (*cp != '\n')) || (val < 0))
938                         return -EINVAL;
939                 /*
940                  * Cap fast_io_fail by dev_loss_tmo or
941                  * SCSI_DEVICE_BLOCK_MAX_TIMEOUT.
942                  */
943                 if ((val >= rport->dev_loss_tmo) ||
944                     (val > SCSI_DEVICE_BLOCK_MAX_TIMEOUT))
945                         return -EINVAL;
946
947                 rport->fast_io_fail_tmo = val;
948         }
949         return count;
950 }
951 static FC_DEVICE_ATTR(rport, fast_io_fail_tmo, S_IRUGO | S_IWUSR,
952         show_fc_rport_fast_io_fail_tmo, store_fc_rport_fast_io_fail_tmo);
953
954
955 /*
956  * FC SCSI Target Attribute Management
957  */
958
959 /*
960  * Note: in the target show function we recognize when the remote
961  *  port is in the heirarchy and do not allow the driver to get
962  *  involved in sysfs functions. The driver only gets involved if
963  *  it's the "old" style that doesn't use rports.
964  */
965 #define fc_starget_show_function(field, format_string, sz, cast)        \
966 static ssize_t                                                          \
967 show_fc_starget_##field (struct device *dev,                            \
968                          struct device_attribute *attr, char *buf)      \
969 {                                                                       \
970         struct scsi_target *starget = transport_class_to_starget(dev);  \
971         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);    \
972         struct fc_internal *i = to_fc_internal(shost->transportt);      \
973         struct fc_rport *rport = starget_to_rport(starget);             \
974         if (rport)                                                      \
975                 fc_starget_##field(starget) = rport->field;             \
976         else if (i->f->get_starget_##field)                             \
977                 i->f->get_starget_##field(starget);                     \
978         return snprintf(buf, sz, format_string,                         \
979                 cast fc_starget_##field(starget));                      \
980 }
981
982 #define fc_starget_rd_attr(field, format_string, sz)                    \
983         fc_starget_show_function(field, format_string, sz, )            \
984 static FC_DEVICE_ATTR(starget, field, S_IRUGO,                  \
985                          show_fc_starget_##field, NULL)
986
987 #define fc_starget_rd_attr_cast(field, format_string, sz, cast)         \
988         fc_starget_show_function(field, format_string, sz, (cast))      \
989 static FC_DEVICE_ATTR(starget, field, S_IRUGO,                  \
990                           show_fc_starget_##field, NULL)
991
992 #define SETUP_STARGET_ATTRIBUTE_RD(field)                               \
993         i->private_starget_attrs[count] = device_attr_starget_##field; \
994         i->private_starget_attrs[count].attr.mode = S_IRUGO;            \
995         i->private_starget_attrs[count].store = NULL;                   \
996         i->starget_attrs[count] = &i->private_starget_attrs[count];     \
997         if (i->f->show_starget_##field)                                 \
998                 count++
999
1000 #define SETUP_STARGET_ATTRIBUTE_RW(field)                               \
1001         i->private_starget_attrs[count] = device_attr_starget_##field; \
1002         if (!i->f->set_starget_##field) {                               \
1003                 i->private_starget_attrs[count].attr.mode = S_IRUGO;    \
1004                 i->private_starget_attrs[count].store = NULL;           \
1005         }                                                               \
1006         i->starget_attrs[count] = &i->private_starget_attrs[count];     \
1007         if (i->f->show_starget_##field)                                 \
1008                 count++
1009
1010 /* The FC Transport SCSI Target Attributes: */
1011 fc_starget_rd_attr_cast(node_name, "0x%llx\n", 20, unsigned long long);
1012 fc_starget_rd_attr_cast(port_name, "0x%llx\n", 20, unsigned long long);
1013 fc_starget_rd_attr(port_id, "0x%06x\n", 20);
1014
1015
1016 /*
1017  * FC Virtual Port Attribute Management
1018  */
1019
1020 #define fc_vport_show_function(field, format_string, sz, cast)          \
1021 static ssize_t                                                          \
1022 show_fc_vport_##field (struct device *dev,                              \
1023                        struct device_attribute *attr, char *buf)        \
1024 {                                                                       \
1025         struct fc_vport *vport = transport_class_to_vport(dev);         \
1026         struct Scsi_Host *shost = vport_to_shost(vport);                \
1027         struct fc_internal *i = to_fc_internal(shost->transportt);      \
1028         if ((i->f->get_vport_##field) &&                                \
1029             !(vport->flags & (FC_VPORT_DEL | FC_VPORT_CREATING)))       \
1030                 i->f->get_vport_##field(vport);                         \
1031         return snprintf(buf, sz, format_string, cast vport->field);     \
1032 }
1033
1034 #define fc_vport_store_function(field)                                  \
1035 static ssize_t                                                          \
1036 store_fc_vport_##field(struct device *dev,                              \
1037                        struct device_attribute *attr,                   \
1038                        const char *buf, size_t count)                   \
1039 {                                                                       \
1040         int val;                                                        \
1041         struct fc_vport *vport = transport_class_to_vport(dev);         \
1042         struct Scsi_Host *shost = vport_to_shost(vport);                \
1043         struct fc_internal *i = to_fc_internal(shost->transportt);      \
1044         char *cp;                                                       \
1045         if (vport->flags & (FC_VPORT_DEL | FC_VPORT_CREATING))  \
1046                 return -EBUSY;                                          \
1047         val = simple_strtoul(buf, &cp, 0);                              \
1048         if (*cp && (*cp != '\n'))                                       \
1049                 return -EINVAL;                                         \
1050         i->f->set_vport_##field(vport, val);                            \
1051         return count;                                                   \
1052 }
1053
1054 #define fc_vport_store_str_function(field, slen)                        \
1055 static ssize_t                                                          \
1056 store_fc_vport_##field(struct device *dev,                              \
1057                        struct device_attribute *attr,                   \
1058                        const char *buf, size_t count)                   \
1059 {                                                                       \
1060         struct fc_vport *vport = transport_class_to_vport(dev);         \
1061         struct Scsi_Host *shost = vport_to_shost(vport);                \
1062         struct fc_internal *i = to_fc_internal(shost->transportt);      \
1063         unsigned int cnt=count;                                         \
1064                                                                         \
1065         /* count may include a LF at end of string */                   \
1066         if (buf[cnt-1] == '\n')                                         \
1067                 cnt--;                                                  \
1068         if (cnt > ((slen) - 1))                                         \
1069                 return -EINVAL;                                         \
1070         memcpy(vport->field, buf, cnt);                                 \
1071         i->f->set_vport_##field(vport);                                 \
1072         return count;                                                   \
1073 }
1074
1075 #define fc_vport_rd_attr(field, format_string, sz)                      \
1076         fc_vport_show_function(field, format_string, sz, )              \
1077 static FC_DEVICE_ATTR(vport, field, S_IRUGO,                    \
1078                          show_fc_vport_##field, NULL)
1079
1080 #define fc_vport_rd_attr_cast(field, format_string, sz, cast)           \
1081         fc_vport_show_function(field, format_string, sz, (cast))        \
1082 static FC_DEVICE_ATTR(vport, field, S_IRUGO,                    \
1083                           show_fc_vport_##field, NULL)
1084
1085 #define fc_vport_rw_attr(field, format_string, sz)                      \
1086         fc_vport_show_function(field, format_string, sz, )              \
1087         fc_vport_store_function(field)                                  \
1088 static FC_DEVICE_ATTR(vport, field, S_IRUGO | S_IWUSR,          \
1089                         show_fc_vport_##field,                          \
1090                         store_fc_vport_##field)
1091
1092 #define fc_private_vport_show_function(field, format_string, sz, cast)  \
1093 static ssize_t                                                          \
1094 show_fc_vport_##field (struct device *dev,                              \
1095                        struct device_attribute *attr, char *buf)        \
1096 {                                                                       \
1097         struct fc_vport *vport = transport_class_to_vport(dev);         \
1098         return snprintf(buf, sz, format_string, cast vport->field);     \
1099 }
1100
1101 #define fc_private_vport_store_u32_function(field)                      \
1102 static ssize_t                                                          \
1103 store_fc_vport_##field(struct device *dev,                              \
1104                        struct device_attribute *attr,                   \
1105                        const char *buf, size_t count)                   \
1106 {                                                                       \
1107         u32 val;                                                        \
1108         struct fc_vport *vport = transport_class_to_vport(dev);         \
1109         char *cp;                                                       \
1110         if (vport->flags & (FC_VPORT_DEL | FC_VPORT_CREATING))          \
1111                 return -EBUSY;                                          \
1112         val = simple_strtoul(buf, &cp, 0);                              \
1113         if (*cp && (*cp != '\n'))                                       \
1114                 return -EINVAL;                                         \
1115         vport->field = val;                                             \
1116         return count;                                                   \
1117 }
1118
1119
1120 #define fc_private_vport_rd_attr(field, format_string, sz)              \
1121         fc_private_vport_show_function(field, format_string, sz, )      \
1122 static FC_DEVICE_ATTR(vport, field, S_IRUGO,                    \
1123                          show_fc_vport_##field, NULL)
1124
1125 #define fc_private_vport_rd_attr_cast(field, format_string, sz, cast)   \
1126         fc_private_vport_show_function(field, format_string, sz, (cast)) \
1127 static FC_DEVICE_ATTR(vport, field, S_IRUGO,                    \
1128                           show_fc_vport_##field, NULL)
1129
1130 #define fc_private_vport_rw_u32_attr(field, format_string, sz)          \
1131         fc_private_vport_show_function(field, format_string, sz, )      \
1132         fc_private_vport_store_u32_function(field)                      \
1133 static FC_DEVICE_ATTR(vport, field, S_IRUGO | S_IWUSR,          \
1134                         show_fc_vport_##field,                          \
1135                         store_fc_vport_##field)
1136
1137
1138 #define fc_private_vport_rd_enum_attr(title, maxlen)                    \
1139 static ssize_t                                                          \
1140 show_fc_vport_##title (struct device *dev,                              \
1141                        struct device_attribute *attr,                   \
1142                        char *buf)                                       \
1143 {                                                                       \
1144         struct fc_vport *vport = transport_class_to_vport(dev);         \
1145         const char *name;                                               \
1146         name = get_fc_##title##_name(vport->title);                     \
1147         if (!name)                                                      \
1148                 return -EINVAL;                                         \
1149         return snprintf(buf, maxlen, "%s\n", name);                     \
1150 }                                                                       \
1151 static FC_DEVICE_ATTR(vport, title, S_IRUGO,                    \
1152                         show_fc_vport_##title, NULL)
1153
1154
1155 #define SETUP_VPORT_ATTRIBUTE_RD(field)                                 \
1156         i->private_vport_attrs[count] = device_attr_vport_##field; \
1157         i->private_vport_attrs[count].attr.mode = S_IRUGO;              \
1158         i->private_vport_attrs[count].store = NULL;                     \
1159         i->vport_attrs[count] = &i->private_vport_attrs[count];         \
1160         if (i->f->get_##field)                                          \
1161                 count++
1162         /* NOTE: Above MACRO differs: checks function not show bit */
1163
1164 #define SETUP_PRIVATE_VPORT_ATTRIBUTE_RD(field)                         \
1165         i->private_vport_attrs[count] = device_attr_vport_##field; \
1166         i->private_vport_attrs[count].attr.mode = S_IRUGO;              \
1167         i->private_vport_attrs[count].store = NULL;                     \
1168         i->vport_attrs[count] = &i->private_vport_attrs[count];         \
1169         count++
1170
1171 #define SETUP_VPORT_ATTRIBUTE_WR(field)                                 \
1172         i->private_vport_attrs[count] = device_attr_vport_##field; \
1173         i->vport_attrs[count] = &i->private_vport_attrs[count];         \
1174         if (i->f->field)                                                \
1175                 count++
1176         /* NOTE: Above MACRO differs: checks function */
1177
1178 #define SETUP_VPORT_ATTRIBUTE_RW(field)                                 \
1179         i->private_vport_attrs[count] = device_attr_vport_##field; \
1180         if (!i->f->set_vport_##field) {                                 \
1181                 i->private_vport_attrs[count].attr.mode = S_IRUGO;      \
1182                 i->private_vport_attrs[count].store = NULL;             \
1183         }                                                               \
1184         i->vport_attrs[count] = &i->private_vport_attrs[count];         \
1185         count++
1186         /* NOTE: Above MACRO differs: does not check show bit */
1187
1188 #define SETUP_PRIVATE_VPORT_ATTRIBUTE_RW(field)                         \
1189 {                                                                       \
1190         i->private_vport_attrs[count] = device_attr_vport_##field; \
1191         i->vport_attrs[count] = &i->private_vport_attrs[count];         \
1192         count++;                                                        \
1193 }
1194
1195
1196 /* The FC Transport Virtual Port Attributes: */
1197
1198 /* Fixed Virtual Port Attributes */
1199
1200 /* Dynamic Virtual Port Attributes */
1201
1202 /* Private Virtual Port Attributes */
1203
1204 fc_private_vport_rd_enum_attr(vport_state, FC_VPORTSTATE_MAX_NAMELEN);
1205 fc_private_vport_rd_enum_attr(vport_last_state, FC_VPORTSTATE_MAX_NAMELEN);
1206 fc_private_vport_rd_attr_cast(node_name, "0x%llx\n", 20, unsigned long long);
1207 fc_private_vport_rd_attr_cast(port_name, "0x%llx\n", 20, unsigned long long);
1208
1209 static ssize_t
1210 show_fc_vport_roles (struct device *dev, struct device_attribute *attr,
1211                      char *buf)
1212 {
1213         struct fc_vport *vport = transport_class_to_vport(dev);
1214
1215         if (vport->roles == FC_PORT_ROLE_UNKNOWN)
1216                 return snprintf(buf, 20, "unknown\n");
1217         return get_fc_port_roles_names(vport->roles, buf);
1218 }
1219 static FC_DEVICE_ATTR(vport, roles, S_IRUGO, show_fc_vport_roles, NULL);
1220
1221 fc_private_vport_rd_enum_attr(vport_type, FC_PORTTYPE_MAX_NAMELEN);
1222
1223 fc_private_vport_show_function(symbolic_name, "%s\n",
1224                 FC_VPORT_SYMBOLIC_NAMELEN + 1, )
1225 fc_vport_store_str_function(symbolic_name, FC_VPORT_SYMBOLIC_NAMELEN)
1226 static FC_DEVICE_ATTR(vport, symbolic_name, S_IRUGO | S_IWUSR,
1227                 show_fc_vport_symbolic_name, store_fc_vport_symbolic_name);
1228
1229 static ssize_t
1230 store_fc_vport_delete(struct device *dev, struct device_attribute *attr,
1231                       const char *buf, size_t count)
1232 {
1233         struct fc_vport *vport = transport_class_to_vport(dev);
1234         struct Scsi_Host *shost = vport_to_shost(vport);
1235         unsigned long flags;
1236
1237         spin_lock_irqsave(shost->host_lock, flags);
1238         if (vport->flags & (FC_VPORT_DEL | FC_VPORT_CREATING)) {
1239                 spin_unlock_irqrestore(shost->host_lock, flags);
1240                 return -EBUSY;
1241         }
1242         vport->flags |= FC_VPORT_DELETING;
1243         spin_unlock_irqrestore(shost->host_lock, flags);
1244
1245         fc_queue_work(shost, &vport->vport_delete_work);
1246         return count;
1247 }
1248 static FC_DEVICE_ATTR(vport, vport_delete, S_IWUSR,
1249                         NULL, store_fc_vport_delete);
1250
1251
1252 /*
1253  * Enable/Disable vport
1254  *  Write "1" to disable, write "0" to enable
1255  */
1256 static ssize_t
1257 store_fc_vport_disable(struct device *dev, struct device_attribute *attr,
1258                        const char *buf,
1259                            size_t count)
1260 {
1261         struct fc_vport *vport = transport_class_to_vport(dev);
1262         struct Scsi_Host *shost = vport_to_shost(vport);
1263         struct fc_internal *i = to_fc_internal(shost->transportt);
1264         int stat;
1265
1266         if (vport->flags & (FC_VPORT_DEL | FC_VPORT_CREATING))
1267                 return -EBUSY;
1268
1269         if (*buf == '0') {
1270                 if (vport->vport_state != FC_VPORT_DISABLED)
1271                         return -EALREADY;
1272         } else if (*buf == '1') {
1273                 if (vport->vport_state == FC_VPORT_DISABLED)
1274                         return -EALREADY;
1275         } else
1276                 return -EINVAL;
1277
1278         stat = i->f->vport_disable(vport, ((*buf == '0') ? false : true));
1279         return stat ? stat : count;
1280 }
1281 static FC_DEVICE_ATTR(vport, vport_disable, S_IWUSR,
1282                         NULL, store_fc_vport_disable);
1283
1284
1285 /*
1286  * Host Attribute Management
1287  */
1288
1289 #define fc_host_show_function(field, format_string, sz, cast)           \
1290 static ssize_t                                                          \
1291 show_fc_host_##field (struct device *dev,                               \
1292                       struct device_attribute *attr, char *buf)         \
1293 {                                                                       \
1294         struct Scsi_Host *shost = transport_class_to_shost(dev);        \
1295         struct fc_internal *i = to_fc_internal(shost->transportt);      \
1296         if (i->f->get_host_##field)                                     \
1297                 i->f->get_host_##field(shost);                          \
1298         return snprintf(buf, sz, format_string, cast fc_host_##field(shost)); \
1299 }
1300
1301 #define fc_host_store_function(field)                                   \
1302 static ssize_t                                                          \
1303 store_fc_host_##field(struct device *dev,                               \
1304                       struct device_attribute *attr,                    \
1305                       const char *buf,  size_t count)                   \
1306 {                                                                       \
1307         int val;                                                        \
1308         struct Scsi_Host *shost = transport_class_to_shost(dev);        \
1309         struct fc_internal *i = to_fc_internal(shost->transportt);      \
1310         char *cp;                                                       \
1311                                                                         \
1312         val = simple_strtoul(buf, &cp, 0);                              \
1313         if (*cp && (*cp != '\n'))                                       \
1314                 return -EINVAL;                                         \
1315         i->f->set_host_##field(shost, val);                             \
1316         return count;                                                   \
1317 }
1318
1319 #define fc_host_store_str_function(field, slen)                         \
1320 static ssize_t                                                          \
1321 store_fc_host_##field(struct device *dev,                               \
1322                       struct device_attribute *attr,                    \
1323                       const char *buf, size_t count)                    \
1324 {                                                                       \
1325         struct Scsi_Host *shost = transport_class_to_shost(dev);        \
1326         struct fc_internal *i = to_fc_internal(shost->transportt);      \
1327         unsigned int cnt=count;                                         \
1328                                                                         \
1329         /* count may include a LF at end of string */                   \
1330         if (buf[cnt-1] == '\n')                                         \
1331                 cnt--;                                                  \
1332         if (cnt > ((slen) - 1))                                         \
1333                 return -EINVAL;                                         \
1334         memcpy(fc_host_##field(shost), buf, cnt);                       \
1335         i->f->set_host_##field(shost);                                  \
1336         return count;                                                   \
1337 }
1338
1339 #define fc_host_rd_attr(field, format_string, sz)                       \
1340         fc_host_show_function(field, format_string, sz, )               \
1341 static FC_DEVICE_ATTR(host, field, S_IRUGO,                     \
1342                          show_fc_host_##field, NULL)
1343
1344 #define fc_host_rd_attr_cast(field, format_string, sz, cast)            \
1345         fc_host_show_function(field, format_string, sz, (cast))         \
1346 static FC_DEVICE_ATTR(host, field, S_IRUGO,                     \
1347                           show_fc_host_##field, NULL)
1348
1349 #define fc_host_rw_attr(field, format_string, sz)                       \
1350         fc_host_show_function(field, format_string, sz, )               \
1351         fc_host_store_function(field)                                   \
1352 static FC_DEVICE_ATTR(host, field, S_IRUGO | S_IWUSR,           \
1353                         show_fc_host_##field,                           \
1354                         store_fc_host_##field)
1355
1356 #define fc_host_rd_enum_attr(title, maxlen)                             \
1357 static ssize_t                                                          \
1358 show_fc_host_##title (struct device *dev,                               \
1359                       struct device_attribute *attr, char *buf)         \
1360 {                                                                       \
1361         struct Scsi_Host *shost = transport_class_to_shost(dev);        \
1362         struct fc_internal *i = to_fc_internal(shost->transportt);      \
1363         const char *name;                                               \
1364         if (i->f->get_host_##title)                                     \
1365                 i->f->get_host_##title(shost);                          \
1366         name = get_fc_##title##_name(fc_host_##title(shost));           \
1367         if (!name)                                                      \
1368                 return -EINVAL;                                         \
1369         return snprintf(buf, maxlen, "%s\n", name);                     \
1370 }                                                                       \
1371 static FC_DEVICE_ATTR(host, title, S_IRUGO, show_fc_host_##title, NULL)
1372
1373 #define SETUP_HOST_ATTRIBUTE_RD(field)                                  \
1374         i->private_host_attrs[count] = device_attr_host_##field;        \
1375         i->private_host_attrs[count].attr.mode = S_IRUGO;               \
1376         i->private_host_attrs[count].store = NULL;                      \
1377         i->host_attrs[count] = &i->private_host_attrs[count];           \
1378         if (i->f->show_host_##field)                                    \
1379                 count++
1380
1381 #define SETUP_HOST_ATTRIBUTE_RD_NS(field)                               \
1382         i->private_host_attrs[count] = device_attr_host_##field;        \
1383         i->private_host_attrs[count].attr.mode = S_IRUGO;               \
1384         i->private_host_attrs[count].store = NULL;                      \
1385         i->host_attrs[count] = &i->private_host_attrs[count];           \
1386         count++
1387
1388 #define SETUP_HOST_ATTRIBUTE_RW(field)                                  \
1389         i->private_host_attrs[count] = device_attr_host_##field;        \
1390         if (!i->f->set_host_##field) {                                  \
1391                 i->private_host_attrs[count].attr.mode = S_IRUGO;       \
1392                 i->private_host_attrs[count].store = NULL;              \
1393         }                                                               \
1394         i->host_attrs[count] = &i->private_host_attrs[count];           \
1395         if (i->f->show_host_##field)                                    \
1396                 count++
1397
1398
1399 #define fc_private_host_show_function(field, format_string, sz, cast)   \
1400 static ssize_t                                                          \
1401 show_fc_host_##field (struct device *dev,                               \
1402                       struct device_attribute *attr, char *buf)         \
1403 {                                                                       \
1404         struct Scsi_Host *shost = transport_class_to_shost(dev);        \
1405         return snprintf(buf, sz, format_string, cast fc_host_##field(shost)); \
1406 }
1407
1408 #define fc_private_host_rd_attr(field, format_string, sz)               \
1409         fc_private_host_show_function(field, format_string, sz, )       \
1410 static FC_DEVICE_ATTR(host, field, S_IRUGO,                     \
1411                          show_fc_host_##field, NULL)
1412
1413 #define fc_private_host_rd_attr_cast(field, format_string, sz, cast)    \
1414         fc_private_host_show_function(field, format_string, sz, (cast)) \
1415 static FC_DEVICE_ATTR(host, field, S_IRUGO,                     \
1416                           show_fc_host_##field, NULL)
1417
1418 #define SETUP_PRIVATE_HOST_ATTRIBUTE_RD(field)                  \
1419         i->private_host_attrs[count] = device_attr_host_##field;        \
1420         i->private_host_attrs[count].attr.mode = S_IRUGO;               \
1421         i->private_host_attrs[count].store = NULL;                      \
1422         i->host_attrs[count] = &i->private_host_attrs[count];           \
1423         count++
1424
1425 #define SETUP_PRIVATE_HOST_ATTRIBUTE_RW(field)                  \
1426 {                                                                       \
1427         i->private_host_attrs[count] = device_attr_host_##field;        \
1428         i->host_attrs[count] = &i->private_host_attrs[count];           \
1429         count++;                                                        \
1430 }
1431
1432
1433 /* Fixed Host Attributes */
1434
1435 static ssize_t
1436 show_fc_host_supported_classes (struct device *dev,
1437                                 struct device_attribute *attr, char *buf)
1438 {
1439         struct Scsi_Host *shost = transport_class_to_shost(dev);
1440
1441         if (fc_host_supported_classes(shost) == FC_COS_UNSPECIFIED)
1442                 return snprintf(buf, 20, "unspecified\n");
1443
1444         return get_fc_cos_names(fc_host_supported_classes(shost), buf);
1445 }
1446 static FC_DEVICE_ATTR(host, supported_classes, S_IRUGO,
1447                 show_fc_host_supported_classes, NULL);
1448
1449 static ssize_t
1450 show_fc_host_supported_fc4s (struct device *dev,
1451                              struct device_attribute *attr, char *buf)
1452 {
1453         struct Scsi_Host *shost = transport_class_to_shost(dev);
1454         return (ssize_t)show_fc_fc4s(buf, fc_host_supported_fc4s(shost));
1455 }
1456 static FC_DEVICE_ATTR(host, supported_fc4s, S_IRUGO,
1457                 show_fc_host_supported_fc4s, NULL);
1458
1459 static ssize_t
1460 show_fc_host_supported_speeds (struct device *dev,
1461                                struct device_attribute *attr, char *buf)
1462 {
1463         struct Scsi_Host *shost = transport_class_to_shost(dev);
1464
1465         if (fc_host_supported_speeds(shost) == FC_PORTSPEED_UNKNOWN)
1466                 return snprintf(buf, 20, "unknown\n");
1467
1468         return get_fc_port_speed_names(fc_host_supported_speeds(shost), buf);
1469 }
1470 static FC_DEVICE_ATTR(host, supported_speeds, S_IRUGO,
1471                 show_fc_host_supported_speeds, NULL);
1472
1473
1474 fc_private_host_rd_attr_cast(node_name, "0x%llx\n", 20, unsigned long long);
1475 fc_private_host_rd_attr_cast(port_name, "0x%llx\n", 20, unsigned long long);
1476 fc_private_host_rd_attr_cast(permanent_port_name, "0x%llx\n", 20,
1477                              unsigned long long);
1478 fc_private_host_rd_attr(maxframe_size, "%u bytes\n", 20);
1479 fc_private_host_rd_attr(max_npiv_vports, "%u\n", 20);
1480 fc_private_host_rd_attr(serial_number, "%s\n", (FC_SERIAL_NUMBER_SIZE +1));
1481
1482
1483 /* Dynamic Host Attributes */
1484
1485 static ssize_t
1486 show_fc_host_active_fc4s (struct device *dev,
1487                           struct device_attribute *attr, char *buf)
1488 {
1489         struct Scsi_Host *shost = transport_class_to_shost(dev);
1490         struct fc_internal *i = to_fc_internal(shost->transportt);
1491
1492         if (i->f->get_host_active_fc4s)
1493                 i->f->get_host_active_fc4s(shost);
1494
1495         return (ssize_t)show_fc_fc4s(buf, fc_host_active_fc4s(shost));
1496 }
1497 static FC_DEVICE_ATTR(host, active_fc4s, S_IRUGO,
1498                 show_fc_host_active_fc4s, NULL);
1499
1500 static ssize_t
1501 show_fc_host_speed (struct device *dev,
1502                     struct device_attribute *attr, char *buf)
1503 {
1504         struct Scsi_Host *shost = transport_class_to_shost(dev);
1505         struct fc_internal *i = to_fc_internal(shost->transportt);
1506
1507         if (i->f->get_host_speed)
1508                 i->f->get_host_speed(shost);
1509
1510         if (fc_host_speed(shost) == FC_PORTSPEED_UNKNOWN)
1511                 return snprintf(buf, 20, "unknown\n");
1512
1513         return get_fc_port_speed_names(fc_host_speed(shost), buf);
1514 }
1515 static FC_DEVICE_ATTR(host, speed, S_IRUGO,
1516                 show_fc_host_speed, NULL);
1517
1518
1519 fc_host_rd_attr(port_id, "0x%06x\n", 20);
1520 fc_host_rd_enum_attr(port_type, FC_PORTTYPE_MAX_NAMELEN);
1521 fc_host_rd_enum_attr(port_state, FC_PORTSTATE_MAX_NAMELEN);
1522 fc_host_rd_attr_cast(fabric_name, "0x%llx\n", 20, unsigned long long);
1523 fc_host_rd_attr(symbolic_name, "%s\n", FC_SYMBOLIC_NAME_SIZE + 1);
1524
1525 fc_private_host_show_function(system_hostname, "%s\n",
1526                 FC_SYMBOLIC_NAME_SIZE + 1, )
1527 fc_host_store_str_function(system_hostname, FC_SYMBOLIC_NAME_SIZE)
1528 static FC_DEVICE_ATTR(host, system_hostname, S_IRUGO | S_IWUSR,
1529                 show_fc_host_system_hostname, store_fc_host_system_hostname);
1530
1531
1532 /* Private Host Attributes */
1533
1534 static ssize_t
1535 show_fc_private_host_tgtid_bind_type(struct device *dev,
1536                                      struct device_attribute *attr, char *buf)
1537 {
1538         struct Scsi_Host *shost = transport_class_to_shost(dev);
1539         const char *name;
1540
1541         name = get_fc_tgtid_bind_type_name(fc_host_tgtid_bind_type(shost));
1542         if (!name)
1543                 return -EINVAL;
1544         return snprintf(buf, FC_BINDTYPE_MAX_NAMELEN, "%s\n", name);
1545 }
1546
1547 #define get_list_head_entry(pos, head, member)          \
1548         pos = list_entry((head)->next, typeof(*pos), member)
1549
1550 static ssize_t
1551 store_fc_private_host_tgtid_bind_type(struct device *dev,
1552         struct device_attribute *attr, const char *buf, size_t count)
1553 {
1554         struct Scsi_Host *shost = transport_class_to_shost(dev);
1555         struct fc_rport *rport;
1556         enum fc_tgtid_binding_type val;
1557         unsigned long flags;
1558
1559         if (get_fc_tgtid_bind_type_match(buf, &val))
1560                 return -EINVAL;
1561
1562         /* if changing bind type, purge all unused consistent bindings */
1563         if (val != fc_host_tgtid_bind_type(shost)) {
1564                 spin_lock_irqsave(shost->host_lock, flags);
1565                 while (!list_empty(&fc_host_rport_bindings(shost))) {
1566                         get_list_head_entry(rport,
1567                                 &fc_host_rport_bindings(shost), peers);
1568                         list_del(&rport->peers);
1569                         rport->port_state = FC_PORTSTATE_DELETED;
1570                         fc_queue_work(shost, &rport->rport_delete_work);
1571                 }
1572                 spin_unlock_irqrestore(shost->host_lock, flags);
1573         }
1574
1575         fc_host_tgtid_bind_type(shost) = val;
1576         return count;
1577 }
1578
1579 static FC_DEVICE_ATTR(host, tgtid_bind_type, S_IRUGO | S_IWUSR,
1580                         show_fc_private_host_tgtid_bind_type,
1581                         store_fc_private_host_tgtid_bind_type);
1582
1583 static ssize_t
1584 store_fc_private_host_issue_lip(struct device *dev,
1585         struct device_attribute *attr, const char *buf, size_t count)
1586 {
1587         struct Scsi_Host *shost = transport_class_to_shost(dev);
1588         struct fc_internal *i = to_fc_internal(shost->transportt);
1589         int ret;
1590
1591         /* ignore any data value written to the attribute */
1592         if (i->f->issue_fc_host_lip) {
1593                 ret = i->f->issue_fc_host_lip(shost);
1594                 return ret ? ret: count;
1595         }
1596
1597         return -ENOENT;
1598 }
1599
1600 static FC_DEVICE_ATTR(host, issue_lip, S_IWUSR, NULL,
1601                         store_fc_private_host_issue_lip);
1602
1603 fc_private_host_rd_attr(npiv_vports_inuse, "%u\n", 20);
1604
1605
1606 /*
1607  * Host Statistics Management
1608  */
1609
1610 /* Show a given an attribute in the statistics group */
1611 static ssize_t
1612 fc_stat_show(const struct device *dev, char *buf, unsigned long offset)
1613 {
1614         struct Scsi_Host *shost = transport_class_to_shost(dev);
1615         struct fc_internal *i = to_fc_internal(shost->transportt);
1616         struct fc_host_statistics *stats;
1617         ssize_t ret = -ENOENT;
1618
1619         if (offset > sizeof(struct fc_host_statistics) ||
1620             offset % sizeof(u64) != 0)
1621                 WARN_ON(1);
1622
1623         if (i->f->get_fc_host_stats) {
1624                 stats = (i->f->get_fc_host_stats)(shost);
1625                 if (stats)
1626                         ret = snprintf(buf, 20, "0x%llx\n",
1627                               (unsigned long long)*(u64 *)(((u8 *) stats) + offset));
1628         }
1629         return ret;
1630 }
1631
1632
1633 /* generate a read-only statistics attribute */
1634 #define fc_host_statistic(name)                                         \
1635 static ssize_t show_fcstat_##name(struct device *cd,                    \
1636                                   struct device_attribute *attr,        \
1637                                   char *buf)                            \
1638 {                                                                       \
1639         return fc_stat_show(cd, buf,                                    \
1640                             offsetof(struct fc_host_statistics, name)); \
1641 }                                                                       \
1642 static FC_DEVICE_ATTR(host, name, S_IRUGO, show_fcstat_##name, NULL)
1643
1644 fc_host_statistic(seconds_since_last_reset);
1645 fc_host_statistic(tx_frames);
1646 fc_host_statistic(tx_words);
1647 fc_host_statistic(rx_frames);
1648 fc_host_statistic(rx_words);
1649 fc_host_statistic(lip_count);
1650 fc_host_statistic(nos_count);
1651 fc_host_statistic(error_frames);
1652 fc_host_statistic(dumped_frames);
1653 fc_host_statistic(link_failure_count);
1654 fc_host_statistic(loss_of_sync_count);
1655 fc_host_statistic(loss_of_signal_count);
1656 fc_host_statistic(prim_seq_protocol_err_count);
1657 fc_host_statistic(invalid_tx_word_count);
1658 fc_host_statistic(invalid_crc_count);
1659 fc_host_statistic(fcp_input_requests);
1660 fc_host_statistic(fcp_output_requests);
1661 fc_host_statistic(fcp_control_requests);
1662 fc_host_statistic(fcp_input_megabytes);
1663 fc_host_statistic(fcp_output_megabytes);
1664
1665 static ssize_t
1666 fc_reset_statistics(struct device *dev, struct device_attribute *attr,
1667                     const char *buf, size_t count)
1668 {
1669         struct Scsi_Host *shost = transport_class_to_shost(dev);
1670         struct fc_internal *i = to_fc_internal(shost->transportt);
1671
1672         /* ignore any data value written to the attribute */
1673         if (i->f->reset_fc_host_stats) {
1674                 i->f->reset_fc_host_stats(shost);
1675                 return count;
1676         }
1677
1678         return -ENOENT;
1679 }
1680 static FC_DEVICE_ATTR(host, reset_statistics, S_IWUSR, NULL,
1681                                 fc_reset_statistics);
1682
1683 static struct attribute *fc_statistics_attrs[] = {
1684         &device_attr_host_seconds_since_last_reset.attr,
1685         &device_attr_host_tx_frames.attr,
1686         &device_attr_host_tx_words.attr,
1687         &device_attr_host_rx_frames.attr,
1688         &device_attr_host_rx_words.attr,
1689         &device_attr_host_lip_count.attr,
1690         &device_attr_host_nos_count.attr,
1691         &device_attr_host_error_frames.attr,
1692         &device_attr_host_dumped_frames.attr,
1693         &device_attr_host_link_failure_count.attr,
1694         &device_attr_host_loss_of_sync_count.attr,
1695         &device_attr_host_loss_of_signal_count.attr,
1696         &device_attr_host_prim_seq_protocol_err_count.attr,
1697         &device_attr_host_invalid_tx_word_count.attr,
1698         &device_attr_host_invalid_crc_count.attr,
1699         &device_attr_host_fcp_input_requests.attr,
1700         &device_attr_host_fcp_output_requests.attr,
1701         &device_attr_host_fcp_control_requests.attr,
1702         &device_attr_host_fcp_input_megabytes.attr,
1703         &device_attr_host_fcp_output_megabytes.attr,
1704         &device_attr_host_reset_statistics.attr,
1705         NULL
1706 };
1707
1708 static struct attribute_group fc_statistics_group = {
1709         .name = "statistics",
1710         .attrs = fc_statistics_attrs,
1711 };
1712
1713
1714 /* Host Vport Attributes */
1715
1716 static int
1717 fc_parse_wwn(const char *ns, u64 *nm)
1718 {
1719         unsigned int i, j;
1720         u8 wwn[8];
1721
1722         memset(wwn, 0, sizeof(wwn));
1723
1724         /* Validate and store the new name */
1725         for (i=0, j=0; i < 16; i++) {
1726                 if ((*ns >= 'a') && (*ns <= 'f'))
1727                         j = ((j << 4) | ((*ns++ -'a') + 10));
1728                 else if ((*ns >= 'A') && (*ns <= 'F'))
1729                         j = ((j << 4) | ((*ns++ -'A') + 10));
1730                 else if ((*ns >= '0') && (*ns <= '9'))
1731                         j = ((j << 4) | (*ns++ -'0'));
1732                 else
1733                         return -EINVAL;
1734                 if (i % 2) {
1735                         wwn[i/2] = j & 0xff;
1736                         j = 0;
1737                 }
1738         }
1739
1740         *nm = wwn_to_u64(wwn);
1741
1742         return 0;
1743 }
1744
1745
1746 /*
1747  * "Short-cut" sysfs variable to create a new vport on a FC Host.
1748  * Input is a string of the form "<WWPN>:<WWNN>". Other attributes
1749  * will default to a NPIV-based FCP_Initiator; The WWNs are specified
1750  * as hex characters, and may *not* contain any prefixes (e.g. 0x, x, etc)
1751  */
1752 static ssize_t
1753 store_fc_host_vport_create(struct device *dev, struct device_attribute *attr,
1754                            const char *buf, size_t count)
1755 {
1756         struct Scsi_Host *shost = transport_class_to_shost(dev);
1757         struct fc_vport_identifiers vid;
1758         struct fc_vport *vport;
1759         unsigned int cnt=count;
1760         int stat;
1761
1762         memset(&vid, 0, sizeof(vid));
1763
1764         /* count may include a LF at end of string */
1765         if (buf[cnt-1] == '\n')
1766                 cnt--;
1767
1768         /* validate we have enough characters for WWPN */
1769         if ((cnt != (16+1+16)) || (buf[16] != ':'))
1770                 return -EINVAL;
1771
1772         stat = fc_parse_wwn(&buf[0], &vid.port_name);
1773         if (stat)
1774                 return stat;
1775
1776         stat = fc_parse_wwn(&buf[17], &vid.node_name);
1777         if (stat)
1778                 return stat;
1779
1780         vid.roles = FC_PORT_ROLE_FCP_INITIATOR;
1781         vid.vport_type = FC_PORTTYPE_NPIV;
1782         /* vid.symbolic_name is already zero/NULL's */
1783         vid.disable = false;            /* always enabled */
1784
1785         /* we only allow support on Channel 0 !!! */
1786         stat = fc_vport_setup(shost, 0, &shost->shost_gendev, &vid, &vport);
1787         return stat ? stat : count;
1788 }
1789 static FC_DEVICE_ATTR(host, vport_create, S_IWUSR, NULL,
1790                         store_fc_host_vport_create);
1791
1792
1793 /*
1794  * "Short-cut" sysfs variable to delete a vport on a FC Host.
1795  * Vport is identified by a string containing "<WWPN>:<WWNN>".
1796  * The WWNs are specified as hex characters, and may *not* contain
1797  * any prefixes (e.g. 0x, x, etc)
1798  */
1799 static ssize_t
1800 store_fc_host_vport_delete(struct device *dev, struct device_attribute *attr,
1801                            const char *buf, size_t count)
1802 {
1803         struct Scsi_Host *shost = transport_class_to_shost(dev);
1804         struct fc_host_attrs *fc_host = shost_to_fc_host(shost);
1805         struct fc_vport *vport;
1806         u64 wwpn, wwnn;
1807         unsigned long flags;
1808         unsigned int cnt=count;
1809         int stat, match;
1810
1811         /* count may include a LF at end of string */
1812         if (buf[cnt-1] == '\n')
1813                 cnt--;
1814
1815         /* validate we have enough characters for WWPN */
1816         if ((cnt != (16+1+16)) || (buf[16] != ':'))
1817                 return -EINVAL;
1818
1819         stat = fc_parse_wwn(&buf[0], &wwpn);
1820         if (stat)
1821                 return stat;
1822
1823         stat = fc_parse_wwn(&buf[17], &wwnn);
1824         if (stat)
1825                 return stat;
1826
1827         spin_lock_irqsave(shost->host_lock, flags);
1828         match = 0;
1829         /* we only allow support on Channel 0 !!! */
1830         list_for_each_entry(vport, &fc_host->vports, peers) {
1831                 if ((vport->channel == 0) &&
1832                     (vport->port_name == wwpn) && (vport->node_name == wwnn)) {
1833                         if (vport->flags & (FC_VPORT_DEL | FC_VPORT_CREATING))
1834                                 break;
1835                         vport->flags |= FC_VPORT_DELETING;
1836                         match = 1;
1837                         break;
1838                 }
1839         }
1840         spin_unlock_irqrestore(shost->host_lock, flags);
1841
1842         if (!match)
1843                 return -ENODEV;
1844
1845         stat = fc_vport_terminate(vport);
1846         return stat ? stat : count;
1847 }
1848 static FC_DEVICE_ATTR(host, vport_delete, S_IWUSR, NULL,
1849                         store_fc_host_vport_delete);
1850
1851
1852 static int fc_host_match(struct attribute_container *cont,
1853                           struct device *dev)
1854 {
1855         struct Scsi_Host *shost;
1856         struct fc_internal *i;
1857
1858         if (!scsi_is_host_device(dev))
1859                 return 0;
1860
1861         shost = dev_to_shost(dev);
1862         if (!shost->transportt  || shost->transportt->host_attrs.ac.class
1863             != &fc_host_class.class)
1864                 return 0;
1865
1866         i = to_fc_internal(shost->transportt);
1867
1868         return &i->t.host_attrs.ac == cont;
1869 }
1870
1871 static int fc_target_match(struct attribute_container *cont,
1872                             struct device *dev)
1873 {
1874         struct Scsi_Host *shost;
1875         struct fc_internal *i;
1876
1877         if (!scsi_is_target_device(dev))
1878                 return 0;
1879
1880         shost = dev_to_shost(dev->parent);
1881         if (!shost->transportt  || shost->transportt->host_attrs.ac.class
1882             != &fc_host_class.class)
1883                 return 0;
1884
1885         i = to_fc_internal(shost->transportt);
1886
1887         return &i->t.target_attrs.ac == cont;
1888 }
1889
1890 static void fc_rport_dev_release(struct device *dev)
1891 {
1892         struct fc_rport *rport = dev_to_rport(dev);
1893         put_device(dev->parent);
1894         kfree(rport);
1895 }
1896
1897 int scsi_is_fc_rport(const struct device *dev)
1898 {
1899         return dev->release == fc_rport_dev_release;
1900 }
1901 EXPORT_SYMBOL(scsi_is_fc_rport);
1902
1903 static int fc_rport_match(struct attribute_container *cont,
1904                             struct device *dev)
1905 {
1906         struct Scsi_Host *shost;
1907         struct fc_internal *i;
1908
1909         if (!scsi_is_fc_rport(dev))
1910                 return 0;
1911
1912         shost = dev_to_shost(dev->parent);
1913         if (!shost->transportt  || shost->transportt->host_attrs.ac.class
1914             != &fc_host_class.class)
1915                 return 0;
1916
1917         i = to_fc_internal(shost->transportt);
1918
1919         return &i->rport_attr_cont.ac == cont;
1920 }
1921
1922
1923 static void fc_vport_dev_release(struct device *dev)
1924 {
1925         struct fc_vport *vport = dev_to_vport(dev);
1926         put_device(dev->parent);                /* release kobj parent */
1927         kfree(vport);
1928 }
1929
1930 int scsi_is_fc_vport(const struct device *dev)
1931 {
1932         return dev->release == fc_vport_dev_release;
1933 }
1934 EXPORT_SYMBOL(scsi_is_fc_vport);
1935
1936 static int fc_vport_match(struct attribute_container *cont,
1937                             struct device *dev)
1938 {
1939         struct fc_vport *vport;
1940         struct Scsi_Host *shost;
1941         struct fc_internal *i;
1942
1943         if (!scsi_is_fc_vport(dev))
1944                 return 0;
1945         vport = dev_to_vport(dev);
1946
1947         shost = vport_to_shost(vport);
1948         if (!shost->transportt  || shost->transportt->host_attrs.ac.class
1949             != &fc_host_class.class)
1950                 return 0;
1951
1952         i = to_fc_internal(shost->transportt);
1953         return &i->vport_attr_cont.ac == cont;
1954 }
1955
1956
1957 /**
1958  * fc_timed_out - FC Transport I/O timeout intercept handler
1959  * @scmd:       The SCSI command which timed out
1960  *
1961  * This routine protects against error handlers getting invoked while a
1962  * rport is in a blocked state, typically due to a temporarily loss of
1963  * connectivity. If the error handlers are allowed to proceed, requests
1964  * to abort i/o, reset the target, etc will likely fail as there is no way
1965  * to communicate with the device to perform the requested function. These
1966  * failures may result in the midlayer taking the device offline, requiring
1967  * manual intervention to restore operation.
1968  *
1969  * This routine, called whenever an i/o times out, validates the state of
1970  * the underlying rport. If the rport is blocked, it returns
1971  * EH_RESET_TIMER, which will continue to reschedule the timeout.
1972  * Eventually, either the device will return, or devloss_tmo will fire,
1973  * and when the timeout then fires, it will be handled normally.
1974  * If the rport is not blocked, normal error handling continues.
1975  *
1976  * Notes:
1977  *      This routine assumes no locks are held on entry.
1978  */
1979 static enum blk_eh_timer_return
1980 fc_timed_out(struct scsi_cmnd *scmd)
1981 {
1982         struct fc_rport *rport = starget_to_rport(scsi_target(scmd->device));
1983
1984         if (rport->port_state == FC_PORTSTATE_BLOCKED)
1985                 return BLK_EH_RESET_TIMER;
1986
1987         return BLK_EH_NOT_HANDLED;
1988 }
1989
1990 /*
1991  * Called by fc_user_scan to locate an rport on the shost that
1992  * matches the channel and target id, and invoke scsi_scan_target()
1993  * on the rport.
1994  */
1995 static void
1996 fc_user_scan_tgt(struct Scsi_Host *shost, uint channel, uint id, uint lun)
1997 {
1998         struct fc_rport *rport;
1999         unsigned long flags;
2000
2001         spin_lock_irqsave(shost->host_lock, flags);
2002
2003         list_for_each_entry(rport, &fc_host_rports(shost), peers) {
2004                 if (rport->scsi_target_id == -1)
2005                         continue;
2006
2007                 if (rport->port_state != FC_PORTSTATE_ONLINE)
2008                         continue;
2009
2010                 if ((channel == rport->channel) &&
2011                     (id == rport->scsi_target_id)) {
2012                         spin_unlock_irqrestore(shost->host_lock, flags);
2013                         scsi_scan_target(&rport->dev, channel, id, lun, 1);
2014                         return;
2015                 }
2016         }
2017
2018         spin_unlock_irqrestore(shost->host_lock, flags);
2019 }
2020
2021 /*
2022  * Called via sysfs scan routines. Necessary, as the FC transport
2023  * wants to place all target objects below the rport object. So this
2024  * routine must invoke the scsi_scan_target() routine with the rport
2025  * object as the parent.
2026  */
2027 static int
2028 fc_user_scan(struct Scsi_Host *shost, uint channel, uint id, uint lun)
2029 {
2030         uint chlo, chhi;
2031         uint tgtlo, tgthi;
2032
2033         if (((channel != SCAN_WILD_CARD) && (channel > shost->max_channel)) ||
2034             ((id != SCAN_WILD_CARD) && (id >= shost->max_id)) ||
2035             ((lun != SCAN_WILD_CARD) && (lun > shost->max_lun)))
2036                 return -EINVAL;
2037
2038         if (channel == SCAN_WILD_CARD) {
2039                 chlo = 0;
2040                 chhi = shost->max_channel + 1;
2041         } else {
2042                 chlo = channel;
2043                 chhi = channel + 1;
2044         }
2045
2046         if (id == SCAN_WILD_CARD) {
2047                 tgtlo = 0;
2048                 tgthi = shost->max_id;
2049         } else {
2050                 tgtlo = id;
2051                 tgthi = id + 1;
2052         }
2053
2054         for ( ; chlo < chhi; chlo++)
2055                 for ( ; tgtlo < tgthi; tgtlo++)
2056                         fc_user_scan_tgt(shost, chlo, tgtlo, lun);
2057
2058         return 0;
2059 }
2060
2061 static int fc_tsk_mgmt_response(struct Scsi_Host *shost, u64 nexus, u64 tm_id,
2062                                 int result)
2063 {
2064         struct fc_internal *i = to_fc_internal(shost->transportt);
2065         return i->f->tsk_mgmt_response(shost, nexus, tm_id, result);
2066 }
2067
2068 static int fc_it_nexus_response(struct Scsi_Host *shost, u64 nexus, int result)
2069 {
2070         struct fc_internal *i = to_fc_internal(shost->transportt);
2071         return i->f->it_nexus_response(shost, nexus, result);
2072 }
2073
2074 struct scsi_transport_template *
2075 fc_attach_transport(struct fc_function_template *ft)
2076 {
2077         int count;
2078         struct fc_internal *i = kzalloc(sizeof(struct fc_internal),
2079                                         GFP_KERNEL);
2080
2081         if (unlikely(!i))
2082                 return NULL;
2083
2084         i->t.target_attrs.ac.attrs = &i->starget_attrs[0];
2085         i->t.target_attrs.ac.class = &fc_transport_class.class;
2086         i->t.target_attrs.ac.match = fc_target_match;
2087         i->t.target_size = sizeof(struct fc_starget_attrs);
2088         transport_container_register(&i->t.target_attrs);
2089
2090         i->t.host_attrs.ac.attrs = &i->host_attrs[0];
2091         i->t.host_attrs.ac.class = &fc_host_class.class;
2092         i->t.host_attrs.ac.match = fc_host_match;
2093         i->t.host_size = sizeof(struct fc_host_attrs);
2094         if (ft->get_fc_host_stats)
2095                 i->t.host_attrs.statistics = &fc_statistics_group;
2096         transport_container_register(&i->t.host_attrs);
2097
2098         i->rport_attr_cont.ac.attrs = &i->rport_attrs[0];
2099         i->rport_attr_cont.ac.class = &fc_rport_class.class;
2100         i->rport_attr_cont.ac.match = fc_rport_match;
2101         transport_container_register(&i->rport_attr_cont);
2102
2103         i->vport_attr_cont.ac.attrs = &i->vport_attrs[0];
2104         i->vport_attr_cont.ac.class = &fc_vport_class.class;
2105         i->vport_attr_cont.ac.match = fc_vport_match;
2106         transport_container_register(&i->vport_attr_cont);
2107
2108         i->f = ft;
2109
2110         /* Transport uses the shost workq for scsi scanning */
2111         i->t.create_work_queue = 1;
2112
2113         i->t.eh_timed_out = fc_timed_out;
2114
2115         i->t.user_scan = fc_user_scan;
2116
2117         /* target-mode drivers' functions */
2118         i->t.tsk_mgmt_response = fc_tsk_mgmt_response;
2119         i->t.it_nexus_response = fc_it_nexus_response;
2120
2121         /*
2122          * Setup SCSI Target Attributes.
2123          */
2124         count = 0;
2125         SETUP_STARGET_ATTRIBUTE_RD(node_name);
2126         SETUP_STARGET_ATTRIBUTE_RD(port_name);
2127         SETUP_STARGET_ATTRIBUTE_RD(port_id);
2128
2129         BUG_ON(count > FC_STARGET_NUM_ATTRS);
2130
2131         i->starget_attrs[count] = NULL;
2132
2133
2134         /*
2135          * Setup SCSI Host Attributes.
2136          */
2137         count=0;
2138         SETUP_HOST_ATTRIBUTE_RD(node_name);
2139         SETUP_HOST_ATTRIBUTE_RD(port_name);
2140         SETUP_HOST_ATTRIBUTE_RD(permanent_port_name);
2141         SETUP_HOST_ATTRIBUTE_RD(supported_classes);
2142         SETUP_HOST_ATTRIBUTE_RD(supported_fc4s);
2143         SETUP_HOST_ATTRIBUTE_RD(supported_speeds);
2144         SETUP_HOST_ATTRIBUTE_RD(maxframe_size);
2145         if (ft->vport_create) {
2146                 SETUP_HOST_ATTRIBUTE_RD_NS(max_npiv_vports);
2147                 SETUP_HOST_ATTRIBUTE_RD_NS(npiv_vports_inuse);
2148         }
2149         SETUP_HOST_ATTRIBUTE_RD(serial_number);
2150
2151         SETUP_HOST_ATTRIBUTE_RD(port_id);
2152         SETUP_HOST_ATTRIBUTE_RD(port_type);
2153         SETUP_HOST_ATTRIBUTE_RD(port_state);
2154         SETUP_HOST_ATTRIBUTE_RD(active_fc4s);
2155         SETUP_HOST_ATTRIBUTE_RD(speed);
2156         SETUP_HOST_ATTRIBUTE_RD(fabric_name);
2157         SETUP_HOST_ATTRIBUTE_RD(symbolic_name);
2158         SETUP_HOST_ATTRIBUTE_RW(system_hostname);
2159
2160         /* Transport-managed attributes */
2161         SETUP_PRIVATE_HOST_ATTRIBUTE_RW(tgtid_bind_type);
2162         if (ft->issue_fc_host_lip)
2163                 SETUP_PRIVATE_HOST_ATTRIBUTE_RW(issue_lip);
2164         if (ft->vport_create)
2165                 SETUP_PRIVATE_HOST_ATTRIBUTE_RW(vport_create);
2166         if (ft->vport_delete)
2167                 SETUP_PRIVATE_HOST_ATTRIBUTE_RW(vport_delete);
2168
2169         BUG_ON(count > FC_HOST_NUM_ATTRS);
2170
2171         i->host_attrs[count] = NULL;
2172
2173         /*
2174          * Setup Remote Port Attributes.
2175          */
2176         count=0;
2177         SETUP_RPORT_ATTRIBUTE_RD(maxframe_size);
2178         SETUP_RPORT_ATTRIBUTE_RD(supported_classes);
2179         SETUP_RPORT_ATTRIBUTE_RW(dev_loss_tmo);
2180         SETUP_PRIVATE_RPORT_ATTRIBUTE_RD(node_name);
2181         SETUP_PRIVATE_RPORT_ATTRIBUTE_RD(port_name);
2182         SETUP_PRIVATE_RPORT_ATTRIBUTE_RD(port_id);
2183         SETUP_PRIVATE_RPORT_ATTRIBUTE_RD(roles);
2184         SETUP_PRIVATE_RPORT_ATTRIBUTE_RD(port_state);
2185         SETUP_PRIVATE_RPORT_ATTRIBUTE_RD(scsi_target_id);
2186         SETUP_PRIVATE_RPORT_ATTRIBUTE_RW(fast_io_fail_tmo);
2187
2188         BUG_ON(count > FC_RPORT_NUM_ATTRS);
2189
2190         i->rport_attrs[count] = NULL;
2191
2192         /*
2193          * Setup Virtual Port Attributes.
2194          */
2195         count=0;
2196         SETUP_PRIVATE_VPORT_ATTRIBUTE_RD(vport_state);
2197         SETUP_PRIVATE_VPORT_ATTRIBUTE_RD(vport_last_state);
2198         SETUP_PRIVATE_VPORT_ATTRIBUTE_RD(node_name);
2199         SETUP_PRIVATE_VPORT_ATTRIBUTE_RD(port_name);
2200         SETUP_PRIVATE_VPORT_ATTRIBUTE_RD(roles);
2201         SETUP_PRIVATE_VPORT_ATTRIBUTE_RD(vport_type);
2202         SETUP_VPORT_ATTRIBUTE_RW(symbolic_name);
2203         SETUP_VPORT_ATTRIBUTE_WR(vport_delete);
2204         SETUP_VPORT_ATTRIBUTE_WR(vport_disable);
2205
2206         BUG_ON(count > FC_VPORT_NUM_ATTRS);
2207
2208         i->vport_attrs[count] = NULL;
2209
2210         return &i->t;
2211 }
2212 EXPORT_SYMBOL(fc_attach_transport);
2213
2214 void fc_release_transport(struct scsi_transport_template *t)
2215 {
2216         struct fc_internal *i = to_fc_internal(t);
2217
2218         transport_container_unregister(&i->t.target_attrs);
2219         transport_container_unregister(&i->t.host_attrs);
2220         transport_container_unregister(&i->rport_attr_cont);
2221         transport_container_unregister(&i->vport_attr_cont);
2222
2223         kfree(i);
2224 }
2225 EXPORT_SYMBOL(fc_release_transport);
2226
2227 /**
2228  * fc_queue_work - Queue work to the fc_host workqueue.
2229  * @shost:      Pointer to Scsi_Host bound to fc_host.
2230  * @work:       Work to queue for execution.
2231  *
2232  * Return value:
2233  *      1 - work queued for execution
2234  *      0 - work is already queued
2235  *      -EINVAL - work queue doesn't exist
2236  */
2237 static int
2238 fc_queue_work(struct Scsi_Host *shost, struct work_struct *work)
2239 {
2240         if (unlikely(!fc_host_work_q(shost))) {
2241                 printk(KERN_ERR
2242                         "ERROR: FC host '%s' attempted to queue work, "
2243                         "when no workqueue created.\n", shost->hostt->name);
2244                 dump_stack();
2245
2246                 return -EINVAL;
2247         }
2248
2249         return queue_work(fc_host_work_q(shost), work);
2250 }
2251
2252 /**
2253  * fc_flush_work - Flush a fc_host's workqueue.
2254  * @shost:      Pointer to Scsi_Host bound to fc_host.
2255  */
2256 static void
2257 fc_flush_work(struct Scsi_Host *shost)
2258 {
2259         if (!fc_host_work_q(shost)) {
2260                 printk(KERN_ERR
2261                         "ERROR: FC host '%s' attempted to flush work, "
2262                         "when no workqueue created.\n", shost->hostt->name);
2263                 dump_stack();
2264                 return;
2265         }
2266
2267         flush_workqueue(fc_host_work_q(shost));
2268 }
2269
2270 /**
2271  * fc_queue_devloss_work - Schedule work for the fc_host devloss workqueue.
2272  * @shost:      Pointer to Scsi_Host bound to fc_host.
2273  * @work:       Work to queue for execution.
2274  * @delay:      jiffies to delay the work queuing
2275  *
2276  * Return value:
2277  *      1 on success / 0 already queued / < 0 for error
2278  */
2279 static int
2280 fc_queue_devloss_work(struct Scsi_Host *shost, struct delayed_work *work,
2281                                 unsigned long delay)
2282 {
2283         if (unlikely(!fc_host_devloss_work_q(shost))) {
2284                 printk(KERN_ERR
2285                         "ERROR: FC host '%s' attempted to queue work, "
2286                         "when no workqueue created.\n", shost->hostt->name);
2287                 dump_stack();
2288
2289                 return -EINVAL;
2290         }
2291
2292         return queue_delayed_work(fc_host_devloss_work_q(shost), work, delay);
2293 }
2294
2295 /**
2296  * fc_flush_devloss - Flush a fc_host's devloss workqueue.
2297  * @shost:      Pointer to Scsi_Host bound to fc_host.
2298  */
2299 static void
2300 fc_flush_devloss(struct Scsi_Host *shost)
2301 {
2302         if (!fc_host_devloss_work_q(shost)) {
2303                 printk(KERN_ERR
2304                         "ERROR: FC host '%s' attempted to flush work, "
2305                         "when no workqueue created.\n", shost->hostt->name);
2306                 dump_stack();
2307                 return;
2308         }
2309
2310         flush_workqueue(fc_host_devloss_work_q(shost));
2311 }
2312
2313
2314 /**
2315  * fc_remove_host - called to terminate any fc_transport-related elements for a scsi host.
2316  * @shost:      Which &Scsi_Host
2317  *
2318  * This routine is expected to be called immediately preceeding the
2319  * a driver's call to scsi_remove_host().
2320  *
2321  * WARNING: A driver utilizing the fc_transport, which fails to call
2322  *   this routine prior to scsi_remove_host(), will leave dangling
2323  *   objects in /sys/class/fc_remote_ports. Access to any of these
2324  *   objects can result in a system crash !!!
2325  *
2326  * Notes:
2327  *      This routine assumes no locks are held on entry.
2328  */
2329 void
2330 fc_remove_host(struct Scsi_Host *shost)
2331 {
2332         struct fc_vport *vport = NULL, *next_vport = NULL;
2333         struct fc_rport *rport = NULL, *next_rport = NULL;
2334         struct workqueue_struct *work_q;
2335         struct fc_host_attrs *fc_host = shost_to_fc_host(shost);
2336         unsigned long flags;
2337
2338         spin_lock_irqsave(shost->host_lock, flags);
2339
2340         /* Remove any vports */
2341         list_for_each_entry_safe(vport, next_vport, &fc_host->vports, peers)
2342                 fc_queue_work(shost, &vport->vport_delete_work);
2343
2344         /* Remove any remote ports */
2345         list_for_each_entry_safe(rport, next_rport,
2346                         &fc_host->rports, peers) {
2347                 list_del(&rport->peers);
2348                 rport->port_state = FC_PORTSTATE_DELETED;
2349                 fc_queue_work(shost, &rport->rport_delete_work);
2350         }
2351
2352         list_for_each_entry_safe(rport, next_rport,
2353                         &fc_host->rport_bindings, peers) {
2354                 list_del(&rport->peers);
2355                 rport->port_state = FC_PORTSTATE_DELETED;
2356                 fc_queue_work(shost, &rport->rport_delete_work);
2357         }
2358
2359         spin_unlock_irqrestore(shost->host_lock, flags);
2360
2361         /* flush all scan work items */
2362         scsi_flush_work(shost);
2363
2364         /* flush all stgt delete, and rport delete work items, then kill it  */
2365         if (fc_host->work_q) {
2366                 work_q = fc_host->work_q;
2367                 fc_host->work_q = NULL;
2368                 destroy_workqueue(work_q);
2369         }
2370
2371         /* flush all devloss work items, then kill it  */
2372         if (fc_host->devloss_work_q) {
2373                 work_q = fc_host->devloss_work_q;
2374                 fc_host->devloss_work_q = NULL;
2375                 destroy_workqueue(work_q);
2376         }
2377 }
2378 EXPORT_SYMBOL(fc_remove_host);
2379
2380 static void fc_terminate_rport_io(struct fc_rport *rport)
2381 {
2382         struct Scsi_Host *shost = rport_to_shost(rport);
2383         struct fc_internal *i = to_fc_internal(shost->transportt);
2384
2385         /* Involve the LLDD if possible to terminate all io on the rport. */
2386         if (i->f->terminate_rport_io)
2387                 i->f->terminate_rport_io(rport);
2388
2389         /*
2390          * must unblock to flush queued IO. The caller will have set
2391          * the port_state or flags, so that fc_remote_port_chkready will
2392          * fail IO.
2393          */
2394         scsi_target_unblock(&rport->dev);
2395 }
2396
2397 /**
2398  * fc_starget_delete - called to delete the scsi decendents of an rport
2399  * @work:       remote port to be operated on.
2400  *
2401  * Deletes target and all sdevs.
2402  */
2403 static void
2404 fc_starget_delete(struct work_struct *work)
2405 {
2406         struct fc_rport *rport =
2407                 container_of(work, struct fc_rport, stgt_delete_work);
2408
2409         fc_terminate_rport_io(rport);
2410         scsi_remove_target(&rport->dev);
2411 }
2412
2413
2414 /**
2415  * fc_rport_final_delete - finish rport termination and delete it.
2416  * @work:       remote port to be deleted.
2417  */
2418 static void
2419 fc_rport_final_delete(struct work_struct *work)
2420 {
2421         struct fc_rport *rport =
2422                 container_of(work, struct fc_rport, rport_delete_work);
2423         struct device *dev = &rport->dev;
2424         struct Scsi_Host *shost = rport_to_shost(rport);
2425         struct fc_internal *i = to_fc_internal(shost->transportt);
2426         unsigned long flags;
2427         int do_callback = 0;
2428
2429         /*
2430          * if a scan is pending, flush the SCSI Host work_q so that
2431          * that we can reclaim the rport scan work element.
2432          */
2433         if (rport->flags & FC_RPORT_SCAN_PENDING)
2434                 scsi_flush_work(shost);
2435
2436         fc_terminate_rport_io(rport);
2437
2438         /*
2439          * Cancel any outstanding timers. These should really exist
2440          * only when rmmod'ing the LLDD and we're asking for
2441          * immediate termination of the rports
2442          */
2443         spin_lock_irqsave(shost->host_lock, flags);
2444         if (rport->flags & FC_RPORT_DEVLOSS_PENDING) {
2445                 spin_unlock_irqrestore(shost->host_lock, flags);
2446                 if (!cancel_delayed_work(&rport->fail_io_work))
2447                         fc_flush_devloss(shost);
2448                 if (!cancel_delayed_work(&rport->dev_loss_work))
2449                         fc_flush_devloss(shost);
2450                 spin_lock_irqsave(shost->host_lock, flags);
2451                 rport->flags &= ~FC_RPORT_DEVLOSS_PENDING;
2452         }
2453         spin_unlock_irqrestore(shost->host_lock, flags);
2454
2455         /* Delete SCSI target and sdevs */
2456         if (rport->scsi_target_id != -1)
2457                 fc_starget_delete(&rport->stgt_delete_work);
2458
2459         /*
2460          * Notify the driver that the rport is now dead. The LLDD will
2461          * also guarantee that any communication to the rport is terminated
2462          *
2463          * Avoid this call if we already called it when we preserved the
2464          * rport for the binding.
2465          */
2466         spin_lock_irqsave(shost->host_lock, flags);
2467         if (!(rport->flags & FC_RPORT_DEVLOSS_CALLBK_DONE) &&
2468             (i->f->dev_loss_tmo_callbk)) {
2469                 rport->flags |= FC_RPORT_DEVLOSS_CALLBK_DONE;
2470                 do_callback = 1;
2471         }
2472         spin_unlock_irqrestore(shost->host_lock, flags);
2473
2474         if (do_callback)
2475                 i->f->dev_loss_tmo_callbk(rport);
2476
2477         fc_bsg_remove(rport->rqst_q);
2478
2479         transport_remove_device(dev);
2480         device_del(dev);
2481         transport_destroy_device(dev);
2482         put_device(&shost->shost_gendev);       /* for fc_host->rport list */
2483         put_device(dev);                        /* for self-reference */
2484 }
2485
2486
2487 /**
2488  * fc_rport_create - allocates and creates a remote FC port.
2489  * @shost:      scsi host the remote port is connected to.
2490  * @channel:    Channel on shost port connected to.
2491  * @ids:        The world wide names, fc address, and FC4 port
2492  *              roles for the remote port.
2493  *
2494  * Allocates and creates the remoter port structure, including the
2495  * class and sysfs creation.
2496  *
2497  * Notes:
2498  *      This routine assumes no locks are held on entry.
2499  */
2500 static struct fc_rport *
2501 fc_rport_create(struct Scsi_Host *shost, int channel,
2502         struct fc_rport_identifiers  *ids)
2503 {
2504         struct fc_host_attrs *fc_host = shost_to_fc_host(shost);
2505         struct fc_internal *fci = to_fc_internal(shost->transportt);
2506         struct fc_rport *rport;
2507         struct device *dev;
2508         unsigned long flags;
2509         int error;
2510         size_t size;
2511
2512         size = (sizeof(struct fc_rport) + fci->f->dd_fcrport_size);
2513         rport = kzalloc(size, GFP_KERNEL);
2514         if (unlikely(!rport)) {
2515                 printk(KERN_ERR "%s: allocation failure\n", __func__);
2516                 return NULL;
2517         }
2518
2519         rport->maxframe_size = -1;
2520         rport->supported_classes = FC_COS_UNSPECIFIED;
2521         rport->dev_loss_tmo = fc_dev_loss_tmo;
2522         memcpy(&rport->node_name, &ids->node_name, sizeof(rport->node_name));
2523         memcpy(&rport->port_name, &ids->port_name, sizeof(rport->port_name));
2524         rport->port_id = ids->port_id;
2525         rport->roles = ids->roles;
2526         rport->port_state = FC_PORTSTATE_ONLINE;
2527         if (fci->f->dd_fcrport_size)
2528                 rport->dd_data = &rport[1];
2529         rport->channel = channel;
2530         rport->fast_io_fail_tmo = -1;
2531
2532         INIT_DELAYED_WORK(&rport->dev_loss_work, fc_timeout_deleted_rport);
2533         INIT_DELAYED_WORK(&rport->fail_io_work, fc_timeout_fail_rport_io);
2534         INIT_WORK(&rport->scan_work, fc_scsi_scan_rport);
2535         INIT_WORK(&rport->stgt_delete_work, fc_starget_delete);
2536         INIT_WORK(&rport->rport_delete_work, fc_rport_final_delete);
2537
2538         spin_lock_irqsave(shost->host_lock, flags);
2539
2540         rport->number = fc_host->next_rport_number++;
2541         if (rport->roles & FC_PORT_ROLE_FCP_TARGET)
2542                 rport->scsi_target_id = fc_host->next_target_id++;
2543         else
2544                 rport->scsi_target_id = -1;
2545         list_add_tail(&rport->peers, &fc_host->rports);
2546         get_device(&shost->shost_gendev);       /* for fc_host->rport list */
2547
2548         spin_unlock_irqrestore(shost->host_lock, flags);
2549
2550         dev = &rport->dev;
2551         device_initialize(dev);                 /* takes self reference */
2552         dev->parent = get_device(&shost->shost_gendev); /* parent reference */
2553         dev->release = fc_rport_dev_release;
2554         dev_set_name(dev, "rport-%d:%d-%d",
2555                      shost->host_no, channel, rport->number);
2556         transport_setup_device(dev);
2557
2558         error = device_add(dev);
2559         if (error) {
2560                 printk(KERN_ERR "FC Remote Port device_add failed\n");
2561                 goto delete_rport;
2562         }
2563         transport_add_device(dev);
2564         transport_configure_device(dev);
2565
2566         fc_bsg_rportadd(shost, rport);
2567         /* ignore any bsg add error - we just can't do sgio */
2568
2569         if (rport->roles & FC_PORT_ROLE_FCP_TARGET) {
2570                 /* initiate a scan of the target */
2571                 rport->flags |= FC_RPORT_SCAN_PENDING;
2572                 scsi_queue_work(shost, &rport->scan_work);
2573         }
2574
2575         return rport;
2576
2577 delete_rport:
2578         transport_destroy_device(dev);
2579         spin_lock_irqsave(shost->host_lock, flags);
2580         list_del(&rport->peers);
2581         put_device(&shost->shost_gendev);       /* for fc_host->rport list */
2582         spin_unlock_irqrestore(shost->host_lock, flags);
2583         put_device(dev->parent);
2584         kfree(rport);
2585         return NULL;
2586 }
2587
2588 /**
2589  * fc_remote_port_add - notify fc transport of the existence of a remote FC port.
2590  * @shost:      scsi host the remote port is connected to.
2591  * @channel:    Channel on shost port connected to.
2592  * @ids:        The world wide names, fc address, and FC4 port
2593  *              roles for the remote port.
2594  *
2595  * The LLDD calls this routine to notify the transport of the existence
2596  * of a remote port. The LLDD provides the unique identifiers (wwpn,wwn)
2597  * of the port, it's FC address (port_id), and the FC4 roles that are
2598  * active for the port.
2599  *
2600  * For ports that are FCP targets (aka scsi targets), the FC transport
2601  * maintains consistent target id bindings on behalf of the LLDD.
2602  * A consistent target id binding is an assignment of a target id to
2603  * a remote port identifier, which persists while the scsi host is
2604  * attached. The remote port can disappear, then later reappear, and
2605  * it's target id assignment remains the same. This allows for shifts
2606  * in FC addressing (if binding by wwpn or wwnn) with no apparent
2607  * changes to the scsi subsystem which is based on scsi host number and
2608  * target id values.  Bindings are only valid during the attachment of
2609  * the scsi host. If the host detaches, then later re-attaches, target
2610  * id bindings may change.
2611  *
2612  * This routine is responsible for returning a remote port structure.
2613  * The routine will search the list of remote ports it maintains
2614  * internally on behalf of consistent target id mappings. If found, the
2615  * remote port structure will be reused. Otherwise, a new remote port
2616  * structure will be allocated.
2617  *
2618  * Whenever a remote port is allocated, a new fc_remote_port class
2619  * device is created.
2620  *
2621  * Should not be called from interrupt context.
2622  *
2623  * Notes:
2624  *      This routine assumes no locks are held on entry.
2625  */
2626 struct fc_rport *
2627 fc_remote_port_add(struct Scsi_Host *shost, int channel,
2628         struct fc_rport_identifiers  *ids)
2629 {
2630         struct fc_internal *fci = to_fc_internal(shost->transportt);
2631         struct fc_host_attrs *fc_host = shost_to_fc_host(shost);
2632         struct fc_rport *rport;
2633         unsigned long flags;
2634         int match = 0;
2635
2636         /* ensure any stgt delete functions are done */
2637         fc_flush_work(shost);
2638
2639         /*
2640          * Search the list of "active" rports, for an rport that has been
2641          * deleted, but we've held off the real delete while the target
2642          * is in a "blocked" state.
2643          */
2644         spin_lock_irqsave(shost->host_lock, flags);
2645
2646         list_for_each_entry(rport, &fc_host->rports, peers) {
2647
2648                 if ((rport->port_state == FC_PORTSTATE_BLOCKED) &&
2649                         (rport->channel == channel)) {
2650
2651                         switch (fc_host->tgtid_bind_type) {
2652                         case FC_TGTID_BIND_BY_WWPN:
2653                         case FC_TGTID_BIND_NONE:
2654                                 if (rport->port_name == ids->port_name)
2655                                         match = 1;
2656                                 break;
2657                         case FC_TGTID_BIND_BY_WWNN:
2658                                 if (rport->node_name == ids->node_name)
2659                                         match = 1;
2660                                 break;
2661                         case FC_TGTID_BIND_BY_ID:
2662                                 if (rport->port_id == ids->port_id)
2663                                         match = 1;
2664                                 break;
2665                         }
2666
2667                         if (match) {
2668
2669                                 memcpy(&rport->node_name, &ids->node_name,
2670                                         sizeof(rport->node_name));
2671                                 memcpy(&rport->port_name, &ids->port_name,
2672                                         sizeof(rport->port_name));
2673                                 rport->port_id = ids->port_id;
2674
2675                                 rport->port_state = FC_PORTSTATE_ONLINE;
2676                                 rport->roles = ids->roles;
2677
2678                                 spin_unlock_irqrestore(shost->host_lock, flags);
2679
2680                                 if (fci->f->dd_fcrport_size)
2681                                         memset(rport->dd_data, 0,
2682                                                 fci->f->dd_fcrport_size);
2683
2684                                 /*
2685                                  * If we were not a target, cancel the
2686                                  * io terminate and rport timers, and
2687                                  * we're done.
2688                                  *
2689                                  * If we were a target, but our new role
2690                                  * doesn't indicate a target, leave the
2691                                  * timers running expecting the role to
2692                                  * change as the target fully logs in. If
2693                                  * it doesn't, the target will be torn down.
2694                                  *
2695                                  * If we were a target, and our role shows
2696                                  * we're still a target, cancel the timers
2697                                  * and kick off a scan.
2698                                  */
2699
2700                                 /* was a target, not in roles */
2701                                 if ((rport->scsi_target_id != -1) &&
2702                                     (!(ids->roles & FC_PORT_ROLE_FCP_TARGET)))
2703                                         return rport;
2704
2705                                 /*
2706                                  * Stop the fail io and dev_loss timers.
2707                                  * If they flush, the port_state will
2708                                  * be checked and will NOOP the function.
2709                                  */
2710                                 if (!cancel_delayed_work(&rport->fail_io_work))
2711                                         fc_flush_devloss(shost);
2712                                 if (!cancel_delayed_work(&rport->dev_loss_work))
2713                                         fc_flush_devloss(shost);
2714
2715                                 spin_lock_irqsave(shost->host_lock, flags);
2716
2717                                 rport->flags &= ~(FC_RPORT_FAST_FAIL_TIMEDOUT |
2718                                                   FC_RPORT_DEVLOSS_PENDING |
2719                                                   FC_RPORT_DEVLOSS_CALLBK_DONE);
2720
2721                                 /* if target, initiate a scan */
2722                                 if (rport->scsi_target_id != -1) {
2723                                         rport->flags |= FC_RPORT_SCAN_PENDING;
2724                                         scsi_queue_work(shost,
2725                                                         &rport->scan_work);
2726                                         spin_unlock_irqrestore(shost->host_lock,
2727                                                         flags);
2728                                         scsi_target_unblock(&rport->dev);
2729                                 } else
2730                                         spin_unlock_irqrestore(shost->host_lock,
2731                                                         flags);
2732
2733                                 fc_bsg_goose_queue(rport);
2734
2735                                 return rport;
2736                         }
2737                 }
2738         }
2739
2740         /*
2741          * Search the bindings array
2742          * Note: if never a FCP target, you won't be on this list
2743          */
2744         if (fc_host->tgtid_bind_type != FC_TGTID_BIND_NONE) {
2745
2746                 /* search for a matching consistent binding */
2747
2748                 list_for_each_entry(rport, &fc_host->rport_bindings,
2749                                         peers) {
2750                         if (rport->channel != channel)
2751                                 continue;
2752
2753                         switch (fc_host->tgtid_bind_type) {
2754                         case FC_TGTID_BIND_BY_WWPN:
2755                                 if (rport->port_name == ids->port_name)
2756                                         match = 1;
2757                                 break;
2758                         case FC_TGTID_BIND_BY_WWNN:
2759                                 if (rport->node_name == ids->node_name)
2760                                         match = 1;
2761                                 break;
2762                         case FC_TGTID_BIND_BY_ID:
2763                                 if (rport->port_id == ids->port_id)
2764                                         match = 1;
2765                                 break;
2766                         case FC_TGTID_BIND_NONE: /* to keep compiler happy */
2767                                 break;
2768                         }
2769
2770                         if (match) {
2771                                 list_move_tail(&rport->peers, &fc_host->rports);
2772                                 break;
2773                         }
2774                 }
2775
2776                 if (match) {
2777                         memcpy(&rport->node_name, &ids->node_name,
2778                                 sizeof(rport->node_name));
2779                         memcpy(&rport->port_name, &ids->port_name,
2780                                 sizeof(rport->port_name));
2781                         rport->port_id = ids->port_id;
2782                         rport->roles = ids->roles;
2783                         rport->port_state = FC_PORTSTATE_ONLINE;
2784                         rport->flags &= ~FC_RPORT_FAST_FAIL_TIMEDOUT;
2785
2786                         if (fci->f->dd_fcrport_size)
2787                                 memset(rport->dd_data, 0,
2788                                                 fci->f->dd_fcrport_size);
2789
2790                         if (rport->roles & FC_PORT_ROLE_FCP_TARGET) {
2791                                 /* initiate a scan of the target */
2792                                 rport->flags |= FC_RPORT_SCAN_PENDING;
2793                                 scsi_queue_work(shost, &rport->scan_work);
2794                                 spin_unlock_irqrestore(shost->host_lock, flags);
2795                                 scsi_target_unblock(&rport->dev);
2796                         } else
2797                                 spin_unlock_irqrestore(shost->host_lock, flags);
2798
2799                         return rport;
2800                 }
2801         }
2802
2803         spin_unlock_irqrestore(shost->host_lock, flags);
2804
2805         /* No consistent binding found - create new remote port entry */
2806         rport = fc_rport_create(shost, channel, ids);
2807
2808         return rport;
2809 }
2810 EXPORT_SYMBOL(fc_remote_port_add);
2811
2812
2813 /**
2814  * fc_remote_port_delete - notifies the fc transport that a remote port is no longer in existence.
2815  * @rport:      The remote port that no longer exists
2816  *
2817  * The LLDD calls this routine to notify the transport that a remote
2818  * port is no longer part of the topology. Note: Although a port
2819  * may no longer be part of the topology, it may persist in the remote
2820  * ports displayed by the fc_host. We do this under 2 conditions:
2821  * 1) If the port was a scsi target, we delay its deletion by "blocking" it.
2822  *   This allows the port to temporarily disappear, then reappear without
2823  *   disrupting the SCSI device tree attached to it. During the "blocked"
2824  *   period the port will still exist.
2825  * 2) If the port was a scsi target and disappears for longer than we
2826  *   expect, we'll delete the port and the tear down the SCSI device tree
2827  *   attached to it. However, we want to semi-persist the target id assigned
2828  *   to that port if it eventually does exist. The port structure will
2829  *   remain (although with minimal information) so that the target id
2830  *   bindings remails.
2831  *
2832  * If the remote port is not an FCP Target, it will be fully torn down
2833  * and deallocated, including the fc_remote_port class device.
2834  *
2835  * If the remote port is an FCP Target, the port will be placed in a
2836  * temporary blocked state. From the LLDD's perspective, the rport no
2837  * longer exists. From the SCSI midlayer's perspective, the SCSI target
2838  * exists, but all sdevs on it are blocked from further I/O. The following
2839  * is then expected.
2840  *
2841  *   If the remote port does not return (signaled by a LLDD call to
2842  *   fc_remote_port_add()) within the dev_loss_tmo timeout, then the
2843  *   scsi target is removed - killing all outstanding i/o and removing the
2844  *   scsi devices attached ot it. The port structure will be marked Not
2845  *   Present and be partially cleared, leaving only enough information to
2846  *   recognize the remote port relative to the scsi target id binding if
2847  *   it later appears.  The port will remain as long as there is a valid
2848  *   binding (e.g. until the user changes the binding type or unloads the
2849  *   scsi host with the binding).
2850  *
2851  *   If the remote port returns within the dev_loss_tmo value (and matches
2852  *   according to the target id binding type), the port structure will be
2853  *   reused. If it is no longer a SCSI target, the target will be torn
2854  *   down. If it continues to be a SCSI target, then the target will be
2855  *   unblocked (allowing i/o to be resumed), and a scan will be activated
2856  *   to ensure that all luns are detected.
2857  *
2858  * Called from normal process context only - cannot be called from interrupt.
2859  *
2860  * Notes:
2861  *      This routine assumes no locks are held on entry.
2862  */
2863 void
2864 fc_remote_port_delete(struct fc_rport  *rport)
2865 {
2866         struct Scsi_Host *shost = rport_to_shost(rport);
2867         int timeout = rport->dev_loss_tmo;
2868         unsigned long flags;
2869
2870         /*
2871          * No need to flush the fc_host work_q's, as all adds are synchronous.
2872          *
2873          * We do need to reclaim the rport scan work element, so eventually
2874          * (in fc_rport_final_delete()) we'll flush the scsi host work_q if
2875          * there's still a scan pending.
2876          */
2877
2878         spin_lock_irqsave(shost->host_lock, flags);
2879
2880         if (rport->port_state != FC_PORTSTATE_ONLINE) {
2881                 spin_unlock_irqrestore(shost->host_lock, flags);
2882                 return;
2883         }
2884
2885         /*
2886          * In the past, we if this was not an FCP-Target, we would
2887          * unconditionally just jump to deleting the rport.
2888          * However, rports can be used as node containers by the LLDD,
2889          * and its not appropriate to just terminate the rport at the
2890          * first sign of a loss in connectivity. The LLDD may want to
2891          * send ELS traffic to re-validate the login. If the rport is
2892          * immediately deleted, it makes it inappropriate for a node
2893          * container.
2894          * So... we now unconditionally wait dev_loss_tmo before
2895          * destroying an rport.
2896          */
2897
2898         rport->port_state = FC_PORTSTATE_BLOCKED;
2899
2900         rport->flags |= FC_RPORT_DEVLOSS_PENDING;
2901
2902         spin_unlock_irqrestore(shost->host_lock, flags);
2903
2904         if (rport->roles & FC_PORT_ROLE_FCP_INITIATOR &&
2905             shost->active_mode & MODE_TARGET)
2906                 fc_tgt_it_nexus_destroy(shost, (unsigned long)rport);
2907
2908         scsi_target_block(&rport->dev);
2909
2910         /* see if we need to kill io faster than waiting for device loss */
2911         if ((rport->fast_io_fail_tmo != -1) &&
2912             (rport->fast_io_fail_tmo < timeout))
2913                 fc_queue_devloss_work(shost, &rport->fail_io_work,
2914                                         rport->fast_io_fail_tmo * HZ);
2915
2916         /* cap the length the devices can be blocked until they are deleted */
2917         fc_queue_devloss_work(shost, &rport->dev_loss_work, timeout * HZ);
2918 }
2919 EXPORT_SYMBOL(fc_remote_port_delete);
2920
2921 /**
2922  * fc_remote_port_rolechg - notifies the fc transport that the roles on a remote may have changed.
2923  * @rport:      The remote port that changed.
2924  * @roles:      New roles for this port.
2925  *
2926  * Description: The LLDD calls this routine to notify the transport that the
2927  * roles on a remote port may have changed. The largest effect of this is
2928  * if a port now becomes a FCP Target, it must be allocated a
2929  * scsi target id.  If the port is no longer a FCP target, any
2930  * scsi target id value assigned to it will persist in case the
2931  * role changes back to include FCP Target. No changes in the scsi
2932  * midlayer will be invoked if the role changes (in the expectation
2933  * that the role will be resumed. If it doesn't normal error processing
2934  * will take place).
2935  *
2936  * Should not be called from interrupt context.
2937  *
2938  * Notes:
2939  *      This routine assumes no locks are held on entry.
2940  */
2941 void
2942 fc_remote_port_rolechg(struct fc_rport  *rport, u32 roles)
2943 {
2944         struct Scsi_Host *shost = rport_to_shost(rport);
2945         struct fc_host_attrs *fc_host = shost_to_fc_host(shost);
2946         unsigned long flags;
2947         int create = 0;
2948         int ret;
2949
2950         spin_lock_irqsave(shost->host_lock, flags);
2951         if (roles & FC_PORT_ROLE_FCP_TARGET) {
2952                 if (rport->scsi_target_id == -1) {
2953                         rport->scsi_target_id = fc_host->next_target_id++;
2954                         create = 1;
2955                 } else if (!(rport->roles & FC_PORT_ROLE_FCP_TARGET))
2956                         create = 1;
2957         } else if (shost->active_mode & MODE_TARGET) {
2958                 ret = fc_tgt_it_nexus_create(shost, (unsigned long)rport,
2959                                              (char *)&rport->node_name);
2960                 if (ret)
2961                         printk(KERN_ERR "FC Remore Port tgt nexus failed %d\n",
2962                                ret);
2963         }
2964
2965         rport->roles = roles;
2966
2967         spin_unlock_irqrestore(shost->host_lock, flags);
2968
2969         if (create) {
2970                 /*
2971                  * There may have been a delete timer running on the
2972                  * port. Ensure that it is cancelled as we now know
2973                  * the port is an FCP Target.
2974                  * Note: we know the rport is exists and in an online
2975                  *  state as the LLDD would not have had an rport
2976                  *  reference to pass us.
2977                  *
2978                  * Take no action on the del_timer failure as the state
2979                  * machine state change will validate the
2980                  * transaction.
2981                  */
2982                 if (!cancel_delayed_work(&rport->fail_io_work))
2983                         fc_flush_devloss(shost);
2984                 if (!cancel_delayed_work(&rport->dev_loss_work))
2985                         fc_flush_devloss(shost);
2986
2987                 spin_lock_irqsave(shost->host_lock, flags);
2988                 rport->flags &= ~(FC_RPORT_FAST_FAIL_TIMEDOUT |
2989                                   FC_RPORT_DEVLOSS_PENDING);
2990                 spin_unlock_irqrestore(shost->host_lock, flags);
2991
2992                 /* ensure any stgt delete functions are done */
2993                 fc_flush_work(shost);
2994
2995                 /* initiate a scan of the target */
2996                 spin_lock_irqsave(shost->host_lock, flags);
2997                 rport->flags |= FC_RPORT_SCAN_PENDING;
2998                 scsi_queue_work(shost, &rport->scan_work);
2999                 spin_unlock_irqrestore(shost->host_lock, flags);
3000                 scsi_target_unblock(&rport->dev);
3001         }
3002 }
3003 EXPORT_SYMBOL(fc_remote_port_rolechg);
3004
3005 /**
3006  * fc_timeout_deleted_rport - Timeout handler for a deleted remote port.
3007  * @work:       rport target that failed to reappear in the allotted time.
3008  *
3009  * Description: An attempt to delete a remote port blocks, and if it fails
3010  *              to return in the allotted time this gets called.
3011  */
3012 static void
3013 fc_timeout_deleted_rport(struct work_struct *work)
3014 {
3015         struct fc_rport *rport =
3016                 container_of(work, struct fc_rport, dev_loss_work.work);
3017         struct Scsi_Host *shost = rport_to_shost(rport);
3018         struct fc_internal *i = to_fc_internal(shost->transportt);
3019         struct fc_host_attrs *fc_host = shost_to_fc_host(shost);
3020         unsigned long flags;
3021         int do_callback = 0;
3022
3023         spin_lock_irqsave(shost->host_lock, flags);
3024
3025         rport->flags &= ~FC_RPORT_DEVLOSS_PENDING;
3026
3027         /*
3028          * If the port is ONLINE, then it came back. If it was a SCSI
3029          * target, validate it still is. If not, tear down the
3030          * scsi_target on it.
3031          */
3032         if ((rport->port_state == FC_PORTSTATE_ONLINE) &&
3033             (rport->scsi_target_id != -1) &&
3034             !(rport->roles & FC_PORT_ROLE_FCP_TARGET)) {
3035                 dev_printk(KERN_ERR, &rport->dev,
3036                         "blocked FC remote port time out: no longer"
3037                         " a FCP target, removing starget\n");
3038                 spin_unlock_irqrestore(shost->host_lock, flags);
3039                 scsi_target_unblock(&rport->dev);
3040                 fc_queue_work(shost, &rport->stgt_delete_work);
3041                 return;
3042         }
3043
3044         /* NOOP state - we're flushing workq's */
3045         if (rport->port_state != FC_PORTSTATE_BLOCKED) {
3046                 spin_unlock_irqrestore(shost->host_lock, flags);
3047                 dev_printk(KERN_ERR, &rport->dev,
3048                         "blocked FC remote port time out: leaving"
3049                         " rport%s alone\n",
3050                         (rport->scsi_target_id != -1) ?  " and starget" : "");
3051                 return;
3052         }
3053
3054         if ((fc_host->tgtid_bind_type == FC_TGTID_BIND_NONE) ||
3055             (rport->scsi_target_id == -1)) {
3056                 list_del(&rport->peers);
3057                 rport->port_state = FC_PORTSTATE_DELETED;
3058                 dev_printk(KERN_ERR, &rport->dev,
3059                         "blocked FC remote port time out: removing"
3060                         " rport%s\n",
3061                         (rport->scsi_target_id != -1) ?  " and starget" : "");
3062                 fc_queue_work(shost, &rport->rport_delete_work);
3063                 spin_unlock_irqrestore(shost->host_lock, flags);
3064                 return;
3065         }
3066
3067         dev_printk(KERN_ERR, &rport->dev,
3068                 "blocked FC remote port time out: removing target and "
3069                 "saving binding\n");
3070
3071         list_move_tail(&rport->peers, &fc_host->rport_bindings);
3072
3073         /*
3074          * Note: We do not remove or clear the hostdata area. This allows
3075          *   host-specific target data to persist along with the
3076          *   scsi_target_id. It's up to the host to manage it's hostdata area.
3077          */
3078
3079         /*
3080          * Reinitialize port attributes that may change if the port comes back.
3081          */
3082         rport->maxframe_size = -1;
3083         rport->supported_classes = FC_COS_UNSPECIFIED;
3084         rport->roles = FC_PORT_ROLE_UNKNOWN;
3085         rport->port_state = FC_PORTSTATE_NOTPRESENT;
3086         rport->flags &= ~FC_RPORT_FAST_FAIL_TIMEDOUT;
3087
3088         /*
3089          * Pre-emptively kill I/O rather than waiting for the work queue
3090          * item to teardown the starget. (FCOE libFC folks prefer this
3091          * and to have the rport_port_id still set when it's done).
3092          */
3093         spin_unlock_irqrestore(shost->host_lock, flags);
3094         fc_terminate_rport_io(rport);
3095
3096         spin_lock_irqsave(shost->host_lock, flags);
3097
3098         if (rport->port_state == FC_PORTSTATE_NOTPRESENT) {     /* still missing */
3099
3100                 /* remove the identifiers that aren't used in the consisting binding */
3101                 switch (fc_host->tgtid_bind_type) {
3102                 case FC_TGTID_BIND_BY_WWPN:
3103                         rport->node_name = -1;
3104                         rport->port_id = -1;
3105                         break;
3106                 case FC_TGTID_BIND_BY_WWNN:
3107                         rport->port_name = -1;
3108                         rport->port_id = -1;
3109                         break;
3110                 case FC_TGTID_BIND_BY_ID:
3111                         rport->node_name = -1;
3112                         rport->port_name = -1;
3113                         break;
3114                 case FC_TGTID_BIND_NONE:        /* to keep compiler happy */
3115                         break;
3116                 }
3117
3118                 /*
3119                  * As this only occurs if the remote port (scsi target)
3120                  * went away and didn't come back - we'll remove
3121                  * all attached scsi devices.
3122                  */
3123                 rport->flags |= FC_RPORT_DEVLOSS_CALLBK_DONE;
3124                 fc_queue_work(shost, &rport->stgt_delete_work);
3125
3126                 do_callback = 1;
3127         }
3128
3129         spin_unlock_irqrestore(shost->host_lock, flags);
3130
3131         /*
3132          * Notify the driver that the rport is now dead. The LLDD will
3133          * also guarantee that any communication to the rport is terminated
3134          *
3135          * Note: we set the CALLBK_DONE flag above to correspond
3136          */
3137         if (do_callback && i->f->dev_loss_tmo_callbk)
3138                 i->f->dev_loss_tmo_callbk(rport);
3139 }
3140
3141
3142 /**
3143  * fc_timeout_fail_rport_io - Timeout handler for a fast io failing on a disconnected SCSI target.
3144  * @work:       rport to terminate io on.
3145  *
3146  * Notes: Only requests the failure of the io, not that all are flushed
3147  *    prior to returning.
3148  */
3149 static void
3150 fc_timeout_fail_rport_io(struct work_struct *work)
3151 {
3152         struct fc_rport *rport =
3153                 container_of(work, struct fc_rport, fail_io_work.work);
3154
3155         if (rport->port_state != FC_PORTSTATE_BLOCKED)
3156                 return;
3157
3158         rport->flags |= FC_RPORT_FAST_FAIL_TIMEDOUT;
3159         fc_terminate_rport_io(rport);
3160 }
3161
3162 /**
3163  * fc_scsi_scan_rport - called to perform a scsi scan on a remote port.
3164  * @work:       remote port to be scanned.
3165  */
3166 static void
3167 fc_scsi_scan_rport(struct work_struct *work)
3168 {
3169         struct fc_rport *rport =
3170                 container_of(work, struct fc_rport, scan_work);
3171         struct Scsi_Host *shost = rport_to_shost(rport);
3172         struct fc_internal *i = to_fc_internal(shost->transportt);
3173         unsigned long flags;
3174
3175         if ((rport->port_state == FC_PORTSTATE_ONLINE) &&
3176             (rport->roles & FC_PORT_ROLE_FCP_TARGET) &&
3177             !(i->f->disable_target_scan)) {
3178                 scsi_scan_target(&rport->dev, rport->channel,
3179                         rport->scsi_target_id, SCAN_WILD_CARD, 1);
3180         }
3181
3182         spin_lock_irqsave(shost->host_lock, flags);
3183         rport->flags &= ~FC_RPORT_SCAN_PENDING;
3184         spin_unlock_irqrestore(shost->host_lock, flags);
3185 }
3186
3187 /**
3188  * fc_block_scsi_eh - Block SCSI eh thread for blocked fc_rport
3189  * @cmnd: SCSI command that scsi_eh is trying to recover
3190  *
3191  * This routine can be called from a FC LLD scsi_eh callback. It
3192  * blocks the scsi_eh thread until the fc_rport leaves the
3193  * FC_PORTSTATE_BLOCKED. This is necessary to avoid the scsi_eh
3194  * failing recovery actions for blocked rports which would lead to
3195  * offlined SCSI devices.
3196  */
3197 void fc_block_scsi_eh(struct scsi_cmnd *cmnd)
3198 {
3199         struct Scsi_Host *shost = cmnd->device->host;
3200         struct fc_rport *rport = starget_to_rport(scsi_target(cmnd->device));
3201         unsigned long flags;
3202
3203         spin_lock_irqsave(shost->host_lock, flags);
3204         while (rport->port_state == FC_PORTSTATE_BLOCKED) {
3205                 spin_unlock_irqrestore(shost->host_lock, flags);
3206                 msleep(1000);
3207                 spin_lock_irqsave(shost->host_lock, flags);
3208         }
3209         spin_unlock_irqrestore(shost->host_lock, flags);
3210 }
3211 EXPORT_SYMBOL(fc_block_scsi_eh);
3212
3213 /**
3214  * fc_vport_setup - allocates and creates a FC virtual port.
3215  * @shost:      scsi host the virtual port is connected to.
3216  * @channel:    Channel on shost port connected to.
3217  * @pdev:       parent device for vport
3218  * @ids:        The world wide names, FC4 port roles, etc for
3219  *              the virtual port.
3220  * @ret_vport:  The pointer to the created vport.
3221  *
3222  * Allocates and creates the vport structure, calls the parent host
3223  * to instantiate the vport, the completes w/ class and sysfs creation.
3224  *
3225  * Notes:
3226  *      This routine assumes no locks are held on entry.
3227  */
3228 static int
3229 fc_vport_setup(struct Scsi_Host *shost, int channel, struct device *pdev,
3230         struct fc_vport_identifiers  *ids, struct fc_vport **ret_vport)
3231 {
3232         struct fc_host_attrs *fc_host = shost_to_fc_host(shost);
3233         struct fc_internal *fci = to_fc_internal(shost->transportt);
3234         struct fc_vport *vport;
3235         struct device *dev;
3236         unsigned long flags;
3237         size_t size;
3238         int error;
3239
3240         *ret_vport = NULL;
3241
3242         if ( ! fci->f->vport_create)
3243                 return -ENOENT;
3244
3245         size = (sizeof(struct fc_vport) + fci->f->dd_fcvport_size);
3246         vport = kzalloc(size, GFP_KERNEL);
3247         if (unlikely(!vport)) {
3248                 printk(KERN_ERR "%s: allocation failure\n", __func__);
3249                 return -ENOMEM;
3250         }
3251
3252         vport->vport_state = FC_VPORT_UNKNOWN;
3253         vport->vport_last_state = FC_VPORT_UNKNOWN;
3254         vport->node_name = ids->node_name;
3255         vport->port_name = ids->port_name;
3256         vport->roles = ids->roles;
3257         vport->vport_type = ids->vport_type;
3258         if (fci->f->dd_fcvport_size)
3259                 vport->dd_data = &vport[1];
3260         vport->shost = shost;
3261         vport->channel = channel;
3262         vport->flags = FC_VPORT_CREATING;
3263         INIT_WORK(&vport->vport_delete_work, fc_vport_sched_delete);
3264
3265         spin_lock_irqsave(shost->host_lock, flags);
3266
3267         if (fc_host->npiv_vports_inuse >= fc_host->max_npiv_vports) {
3268                 spin_unlock_irqrestore(shost->host_lock, flags);
3269                 kfree(vport);
3270                 return -ENOSPC;
3271         }
3272         fc_host->npiv_vports_inuse++;
3273         vport->number = fc_host->next_vport_number++;
3274         list_add_tail(&vport->peers, &fc_host->vports);
3275         get_device(&shost->shost_gendev);       /* for fc_host->vport list */
3276
3277         spin_unlock_irqrestore(shost->host_lock, flags);
3278
3279         dev = &vport->dev;
3280         device_initialize(dev);                 /* takes self reference */
3281         dev->parent = get_device(pdev);         /* takes parent reference */
3282         dev->release = fc_vport_dev_release;
3283         dev_set_name(dev, "vport-%d:%d-%d",
3284                      shost->host_no, channel, vport->number);
3285         transport_setup_device(dev);
3286
3287         error = device_add(dev);
3288         if (error) {
3289                 printk(KERN_ERR "FC Virtual Port device_add failed\n");
3290                 goto delete_vport;
3291         }
3292         transport_add_device(dev);
3293         transport_configure_device(dev);
3294
3295         error = fci->f->vport_create(vport, ids->disable);
3296         if (error) {
3297                 printk(KERN_ERR "FC Virtual Port LLDD Create failed\n");
3298                 goto delete_vport_all;
3299         }
3300
3301         /*
3302          * if the parent isn't the physical adapter's Scsi_Host, ensure
3303          * the Scsi_Host at least contains ia symlink to the vport.
3304          */
3305         if (pdev != &shost->shost_gendev) {
3306                 error = sysfs_create_link(&shost->shost_gendev.kobj,
3307                                  &dev->kobj, dev_name(dev));
3308                 if (error)
3309                         printk(KERN_ERR
3310                                 "%s: Cannot create vport symlinks for "
3311                                 "%s, err=%d\n",
3312                                 __func__, dev_name(dev), error);
3313         }
3314         spin_lock_irqsave(shost->host_lock, flags);
3315         vport->flags &= ~FC_VPORT_CREATING;
3316         spin_unlock_irqrestore(shost->host_lock, flags);
3317
3318         dev_printk(KERN_NOTICE, pdev,
3319                         "%s created via shost%d channel %d\n", dev_name(dev),
3320                         shost->host_no, channel);
3321
3322         *ret_vport = vport;
3323
3324         return 0;
3325
3326 delete_vport_all:
3327         transport_remove_device(dev);
3328         device_del(dev);
3329 delete_vport:
3330         transport_destroy_device(dev);
3331         spin_lock_irqsave(shost->host_lock, flags);
3332         list_del(&vport->peers);
3333         put_device(&shost->shost_gendev);       /* for fc_host->vport list */
3334         fc_host->npiv_vports_inuse--;
3335         spin_unlock_irqrestore(shost->host_lock, flags);
3336         put_device(dev->parent);
3337         kfree(vport);
3338
3339         return error;
3340 }
3341
3342 /**
3343  * fc_vport_create - Admin App or LLDD requests creation of a vport
3344  * @shost:      scsi host the virtual port is connected to.
3345  * @channel:    channel on shost port connected to.
3346  * @ids:        The world wide names, FC4 port roles, etc for
3347  *              the virtual port.
3348  *
3349  * Notes:
3350  *      This routine assumes no locks are held on entry.
3351  */
3352 struct fc_vport *
3353 fc_vport_create(struct Scsi_Host *shost, int channel,
3354         struct fc_vport_identifiers *ids)
3355 {
3356         int stat;
3357         struct fc_vport *vport;
3358
3359         stat = fc_vport_setup(shost, channel, &shost->shost_gendev,
3360                  ids, &vport);
3361         return stat ? NULL : vport;
3362 }
3363 EXPORT_SYMBOL(fc_vport_create);
3364
3365 /**
3366  * fc_vport_terminate - Admin App or LLDD requests termination of a vport
3367  * @vport:      fc_vport to be terminated
3368  *
3369  * Calls the LLDD vport_delete() function, then deallocates and removes
3370  * the vport from the shost and object tree.
3371  *
3372  * Notes:
3373  *      This routine assumes no locks are held on entry.
3374  */
3375 int
3376 fc_vport_terminate(struct fc_vport *vport)
3377 {
3378         struct Scsi_Host *shost = vport_to_shost(vport);
3379         struct fc_host_attrs *fc_host = shost_to_fc_host(shost);
3380         struct fc_internal *i = to_fc_internal(shost->transportt);
3381         struct device *dev = &vport->dev;
3382         unsigned long flags;
3383         int stat;
3384
3385         if (i->f->vport_delete)
3386                 stat = i->f->vport_delete(vport);
3387         else
3388                 stat = -ENOENT;
3389
3390         spin_lock_irqsave(shost->host_lock, flags);
3391         vport->flags &= ~FC_VPORT_DELETING;
3392         if (!stat) {
3393                 vport->flags |= FC_VPORT_DELETED;
3394                 list_del(&vport->peers);
3395                 fc_host->npiv_vports_inuse--;
3396                 put_device(&shost->shost_gendev);  /* for fc_host->vport list */
3397         }
3398         spin_unlock_irqrestore(shost->host_lock, flags);
3399
3400         if (stat)
3401                 return stat;
3402
3403         if (dev->parent != &shost->shost_gendev)
3404                 sysfs_remove_link(&shost->shost_gendev.kobj, dev_name(dev));
3405         transport_remove_device(dev);
3406         device_del(dev);
3407         transport_destroy_device(dev);
3408
3409         /*
3410          * Removing our self-reference should mean our
3411          * release function gets called, which will drop the remaining
3412          * parent reference and free the data structure.
3413          */
3414         put_device(dev);                        /* for self-reference */
3415
3416         return 0; /* SUCCESS */
3417 }
3418 EXPORT_SYMBOL(fc_vport_terminate);
3419
3420 /**
3421  * fc_vport_sched_delete - workq-based delete request for a vport
3422  * @work:       vport to be deleted.
3423  */
3424 static void
3425 fc_vport_sched_delete(struct work_struct *work)
3426 {
3427         struct fc_vport *vport =
3428                 container_of(work, struct fc_vport, vport_delete_work);
3429         int stat;
3430
3431         stat = fc_vport_terminate(vport);
3432         if (stat)
3433                 dev_printk(KERN_ERR, vport->dev.parent,
3434                         "%s: %s could not be deleted created via "
3435                         "shost%d channel %d - error %d\n", __func__,
3436                         dev_name(&vport->dev), vport->shost->host_no,
3437                         vport->channel, stat);
3438 }
3439
3440
3441 /*
3442  * BSG support
3443  */
3444
3445
3446 /**
3447  * fc_destroy_bsgjob - routine to teardown/delete a fc bsg job
3448  * @job:        fc_bsg_job that is to be torn down
3449  */
3450 static void
3451 fc_destroy_bsgjob(struct fc_bsg_job *job)
3452 {
3453         unsigned long flags;
3454
3455         spin_lock_irqsave(&job->job_lock, flags);
3456         if (job->ref_cnt) {
3457                 spin_unlock_irqrestore(&job->job_lock, flags);
3458                 return;
3459         }
3460         spin_unlock_irqrestore(&job->job_lock, flags);
3461
3462         put_device(job->dev);   /* release reference for the request */
3463
3464         kfree(job->request_payload.sg_list);
3465         kfree(job->reply_payload.sg_list);
3466         kfree(job);
3467 }
3468
3469 /**
3470  * fc_bsg_jobdone - completion routine for bsg requests that the LLD has
3471  *                  completed
3472  * @job:        fc_bsg_job that is complete
3473  */
3474 static void
3475 fc_bsg_jobdone(struct fc_bsg_job *job)
3476 {
3477         struct request *req = job->req;
3478         struct request *rsp = req->next_rq;
3479         int err;
3480
3481         err = job->req->errors = job->reply->result;
3482
3483         if (err < 0)
3484                 /* we're only returning the result field in the reply */
3485                 job->req->sense_len = sizeof(uint32_t);
3486         else
3487                 job->req->sense_len = job->reply_len;
3488
3489         /* we assume all request payload was transferred, residual == 0 */
3490         req->resid_len = 0;
3491
3492         if (rsp) {
3493                 WARN_ON(job->reply->reply_payload_rcv_len > rsp->resid_len);
3494
3495                 /* set reply (bidi) residual */
3496                 rsp->resid_len -= min(job->reply->reply_payload_rcv_len,
3497                                       rsp->resid_len);
3498         }
3499         blk_complete_request(req);
3500 }
3501
3502 /**
3503  * fc_bsg_softirq_done - softirq done routine for destroying the bsg requests
3504  * @rq:        BSG request that holds the job to be destroyed
3505  */
3506 static void fc_bsg_softirq_done(struct request *rq)
3507 {
3508         struct fc_bsg_job *job = rq->special;
3509         unsigned long flags;
3510
3511         spin_lock_irqsave(&job->job_lock, flags);
3512         job->state_flags |= FC_RQST_STATE_DONE;
3513         job->ref_cnt--;
3514         spin_unlock_irqrestore(&job->job_lock, flags);
3515
3516         blk_end_request_all(rq, rq->errors);
3517         fc_destroy_bsgjob(job);
3518 }
3519
3520 /**
3521  * fc_bsg_job_timeout - handler for when a bsg request timesout
3522  * @req:        request that timed out
3523  */
3524 static enum blk_eh_timer_return
3525 fc_bsg_job_timeout(struct request *req)
3526 {
3527         struct fc_bsg_job *job = (void *) req->special;
3528         struct Scsi_Host *shost = job->shost;
3529         struct fc_internal *i = to_fc_internal(shost->transportt);
3530         unsigned long flags;
3531         int err = 0, done = 0;
3532
3533         if (job->rport && job->rport->port_state == FC_PORTSTATE_BLOCKED)
3534                 return BLK_EH_RESET_TIMER;
3535
3536         spin_lock_irqsave(&job->job_lock, flags);
3537         if (job->state_flags & FC_RQST_STATE_DONE)
3538                 done = 1;
3539         else
3540                 job->ref_cnt++;
3541         spin_unlock_irqrestore(&job->job_lock, flags);
3542
3543         if (!done && i->f->bsg_timeout) {
3544                 /* call LLDD to abort the i/o as it has timed out */
3545                 err = i->f->bsg_timeout(job);
3546                 if (err == -EAGAIN) {
3547                         job->ref_cnt--;
3548                         return BLK_EH_RESET_TIMER;
3549                 } else if (err)
3550                         printk(KERN_ERR "ERROR: FC BSG request timeout - LLD "
3551                                 "abort failed with status %d\n", err);
3552         }
3553
3554         /* the blk_end_sync_io() doesn't check the error */
3555         if (done)
3556                 return BLK_EH_NOT_HANDLED;
3557         else
3558                 return BLK_EH_HANDLED;
3559 }
3560
3561 static int
3562 fc_bsg_map_buffer(struct fc_bsg_buffer *buf, struct request *req)
3563 {
3564         size_t sz = (sizeof(struct scatterlist) * req->nr_phys_segments);
3565
3566         BUG_ON(!req->nr_phys_segments);
3567
3568         buf->sg_list = kzalloc(sz, GFP_KERNEL);
3569         if (!buf->sg_list)
3570                 return -ENOMEM;
3571         sg_init_table(buf->sg_list, req->nr_phys_segments);
3572         buf->sg_cnt = blk_rq_map_sg(req->q, req, buf->sg_list);
3573         buf->payload_len = blk_rq_bytes(req);
3574         return 0;
3575 }
3576
3577
3578 /**
3579  * fc_req_to_bsgjob - Allocate/create the fc_bsg_job structure for the
3580  *                   bsg request
3581  * @shost:      SCSI Host corresponding to the bsg object
3582  * @rport:      (optional) FC Remote Port corresponding to the bsg object
3583  * @req:        BSG request that needs a job structure
3584  */
3585 static int
3586 fc_req_to_bsgjob(struct Scsi_Host *shost, struct fc_rport *rport,
3587         struct request *req)
3588 {
3589         struct fc_internal *i = to_fc_internal(shost->transportt);
3590         struct request *rsp = req->next_rq;
3591         struct fc_bsg_job *job;
3592         int ret;
3593
3594         BUG_ON(req->special);
3595
3596         job = kzalloc(sizeof(struct fc_bsg_job) + i->f->dd_bsg_size,
3597                         GFP_KERNEL);
3598         if (!job)
3599                 return -ENOMEM;
3600
3601         /*
3602          * Note: this is a bit silly.
3603          * The request gets formatted as a SGIO v4 ioctl request, which
3604          * then gets reformatted as a blk request, which then gets
3605          * reformatted as a fc bsg request. And on completion, we have
3606          * to wrap return results such that SGIO v4 thinks it was a scsi
3607          * status.  I hope this was all worth it.
3608          */
3609
3610         req->special = job;
3611         job->shost = shost;
3612         job->rport = rport;
3613         job->req = req;
3614         if (i->f->dd_bsg_size)
3615                 job->dd_data = (void *)&job[1];
3616         spin_lock_init(&job->job_lock);
3617         job->request = (struct fc_bsg_request *)req->cmd;
3618         job->request_len = req->cmd_len;
3619         job->reply = req->sense;
3620         job->reply_len = SCSI_SENSE_BUFFERSIZE; /* Size of sense buffer
3621                                                  * allocated */
3622         if (req->bio) {
3623                 ret = fc_bsg_map_buffer(&job->request_payload, req);
3624                 if (ret)
3625                         goto failjob_rls_job;
3626         }
3627         if (rsp && rsp->bio) {
3628                 ret = fc_bsg_map_buffer(&job->reply_payload, rsp);
3629                 if (ret)
3630                         goto failjob_rls_rqst_payload;
3631         }
3632         job->job_done = fc_bsg_jobdone;
3633         if (rport)
3634                 job->dev = &rport->dev;
3635         else
3636                 job->dev = &shost->shost_gendev;
3637         get_device(job->dev);           /* take a reference for the request */
3638
3639         job->ref_cnt = 1;
3640
3641         return 0;
3642
3643
3644 failjob_rls_rqst_payload:
3645         kfree(job->request_payload.sg_list);
3646 failjob_rls_job:
3647         kfree(job);
3648         return -ENOMEM;
3649 }
3650
3651
3652 enum fc_dispatch_result {
3653         FC_DISPATCH_BREAK,      /* on return, q is locked, break from q loop */
3654         FC_DISPATCH_LOCKED,     /* on return, q is locked, continue on */
3655         FC_DISPATCH_UNLOCKED,   /* on return, q is unlocked, continue on */
3656 };
3657
3658
3659 /**
3660  * fc_bsg_host_dispatch - process fc host bsg requests and dispatch to LLDD
3661  * @q:          fc host request queue
3662  * @shost:      scsi host rport attached to
3663  * @job:        bsg job to be processed
3664  */
3665 static enum fc_dispatch_result
3666 fc_bsg_host_dispatch(struct request_queue *q, struct Scsi_Host *shost,
3667                          struct fc_bsg_job *job)
3668 {
3669         struct fc_internal *i = to_fc_internal(shost->transportt);
3670         int cmdlen = sizeof(uint32_t);  /* start with length of msgcode */
3671         int ret;
3672
3673         /* Validate the host command */
3674         switch (job->request->msgcode) {
3675         case FC_BSG_HST_ADD_RPORT:
3676                 cmdlen += sizeof(struct fc_bsg_host_add_rport);
3677                 break;
3678
3679         case FC_BSG_HST_DEL_RPORT:
3680                 cmdlen += sizeof(struct fc_bsg_host_del_rport);
3681                 break;
3682
3683         case FC_BSG_HST_ELS_NOLOGIN:
3684                 cmdlen += sizeof(struct fc_bsg_host_els);
3685                 /* there better be a xmt and rcv payloads */
3686                 if ((!job->request_payload.payload_len) ||
3687                     (!job->reply_payload.payload_len)) {
3688                         ret = -EINVAL;
3689                         goto fail_host_msg;
3690                 }
3691                 break;
3692
3693         case FC_BSG_HST_CT:
3694                 cmdlen += sizeof(struct fc_bsg_host_ct);
3695                 /* there better be xmt and rcv payloads */
3696                 if ((!job->request_payload.payload_len) ||
3697                     (!job->reply_payload.payload_len)) {
3698                         ret = -EINVAL;
3699                         goto fail_host_msg;
3700                 }
3701                 break;
3702
3703         case FC_BSG_HST_VENDOR:
3704                 cmdlen += sizeof(struct fc_bsg_host_vendor);
3705                 if ((shost->hostt->vendor_id == 0L) ||
3706                     (job->request->rqst_data.h_vendor.vendor_id !=
3707                         shost->hostt->vendor_id)) {
3708                         ret = -ESRCH;
3709                         goto fail_host_msg;
3710                 }
3711                 break;
3712
3713         default:
3714                 ret = -EBADR;
3715                 goto fail_host_msg;
3716         }
3717
3718         /* check if we really have all the request data needed */
3719         if (job->request_len < cmdlen) {
3720                 ret = -ENOMSG;
3721                 goto fail_host_msg;
3722         }
3723
3724         ret = i->f->bsg_request(job);
3725         if (!ret)
3726                 return FC_DISPATCH_UNLOCKED;
3727
3728 fail_host_msg:
3729         /* return the errno failure code as the only status */
3730         BUG_ON(job->reply_len < sizeof(uint32_t));
3731         job->reply->reply_payload_rcv_len = 0;
3732         job->reply->result = ret;
3733         job->reply_len = sizeof(uint32_t);
3734         fc_bsg_jobdone(job);
3735         return FC_DISPATCH_UNLOCKED;
3736 }
3737
3738
3739 /*
3740  * fc_bsg_goose_queue - restart rport queue in case it was stopped
3741  * @rport:      rport to be restarted
3742  */
3743 static void
3744 fc_bsg_goose_queue(struct fc_rport *rport)
3745 {
3746         int flagset;
3747         unsigned long flags;
3748
3749         if (!rport->rqst_q)
3750                 return;
3751
3752         get_device(&rport->dev);
3753
3754         spin_lock_irqsave(rport->rqst_q->queue_lock, flags);
3755         flagset = test_bit(QUEUE_FLAG_REENTER, &rport->rqst_q->queue_flags) &&
3756                   !test_bit(QUEUE_FLAG_REENTER, &rport->rqst_q->queue_flags);
3757         if (flagset)
3758                 queue_flag_set(QUEUE_FLAG_REENTER, rport->rqst_q);
3759         __blk_run_queue(rport->rqst_q);
3760         if (flagset)
3761                 queue_flag_clear(QUEUE_FLAG_REENTER, rport->rqst_q);
3762         spin_unlock_irqrestore(rport->rqst_q->queue_lock, flags);
3763
3764         put_device(&rport->dev);
3765 }
3766
3767
3768 /**
3769  * fc_bsg_rport_dispatch - process rport bsg requests and dispatch to LLDD
3770  * @q:          rport request queue
3771  * @shost:      scsi host rport attached to
3772  * @rport:      rport request destined to
3773  * @job:        bsg job to be processed
3774  */
3775 static enum fc_dispatch_result
3776 fc_bsg_rport_dispatch(struct request_queue *q, struct Scsi_Host *shost,
3777                          struct fc_rport *rport, struct fc_bsg_job *job)
3778 {
3779         struct fc_internal *i = to_fc_internal(shost->transportt);
3780         int cmdlen = sizeof(uint32_t);  /* start with length of msgcode */
3781         int ret;
3782
3783         /* Validate the rport command */
3784         switch (job->request->msgcode) {
3785         case FC_BSG_RPT_ELS:
3786                 cmdlen += sizeof(struct fc_bsg_rport_els);
3787                 goto check_bidi;
3788
3789         case FC_BSG_RPT_CT:
3790                 cmdlen += sizeof(struct fc_bsg_rport_ct);
3791 check_bidi:
3792                 /* there better be xmt and rcv payloads */
3793                 if ((!job->request_payload.payload_len) ||
3794                     (!job->reply_payload.payload_len)) {
3795                         ret = -EINVAL;
3796                         goto fail_rport_msg;
3797                 }
3798                 break;
3799         default:
3800                 ret = -EBADR;
3801                 goto fail_rport_msg;
3802         }
3803
3804         /* check if we really have all the request data needed */
3805         if (job->request_len < cmdlen) {
3806                 ret = -ENOMSG;
3807                 goto fail_rport_msg;
3808         }
3809
3810         ret = i->f->bsg_request(job);
3811         if (!ret)
3812                 return FC_DISPATCH_UNLOCKED;
3813
3814 fail_rport_msg:
3815         /* return the errno failure code as the only status */
3816         BUG_ON(job->reply_len < sizeof(uint32_t));
3817         job->reply->reply_payload_rcv_len = 0;
3818         job->reply->result = ret;
3819         job->reply_len = sizeof(uint32_t);
3820         fc_bsg_jobdone(job);
3821         return FC_DISPATCH_UNLOCKED;
3822 }
3823
3824
3825 /**
3826  * fc_bsg_request_handler - generic handler for bsg requests
3827  * @q:          request queue to manage
3828  * @shost:      Scsi_Host related to the bsg object
3829  * @rport:      FC remote port related to the bsg object (optional)
3830  * @dev:        device structure for bsg object
3831  */
3832 static void
3833 fc_bsg_request_handler(struct request_queue *q, struct Scsi_Host *shost,
3834                        struct fc_rport *rport, struct device *dev)
3835 {
3836         struct request *req;
3837         struct fc_bsg_job *job;
3838         enum fc_dispatch_result ret;
3839
3840         if (!get_device(dev))
3841                 return;
3842
3843         while (!blk_queue_plugged(q)) {
3844                 if (rport && (rport->port_state == FC_PORTSTATE_BLOCKED) &&
3845                     !(rport->flags & FC_RPORT_FAST_FAIL_TIMEDOUT))
3846                         break;
3847
3848                 req = blk_fetch_request(q);
3849                 if (!req)
3850                         break;
3851
3852                 if (rport && (rport->port_state != FC_PORTSTATE_ONLINE)) {
3853                         req->errors = -ENXIO;
3854                         spin_unlock_irq(q->queue_lock);
3855                         blk_end_request(req, -ENXIO, blk_rq_bytes(req));
3856                         spin_lock_irq(q->queue_lock);
3857                         continue;
3858                 }
3859
3860                 spin_unlock_irq(q->queue_lock);
3861
3862                 ret = fc_req_to_bsgjob(shost, rport, req);
3863                 if (ret) {
3864                         req->errors = ret;
3865                         blk_end_request(req, ret, blk_rq_bytes(req));
3866                         spin_lock_irq(q->queue_lock);
3867                         continue;
3868                 }
3869
3870                 job = req->special;
3871
3872                 /* check if we have the msgcode value at least */
3873                 if (job->request_len < sizeof(uint32_t)) {
3874                         BUG_ON(job->reply_len < sizeof(uint32_t));
3875                         job->reply->reply_payload_rcv_len = 0;
3876                         job->reply->result = -ENOMSG;
3877                         job->reply_len = sizeof(uint32_t);
3878                         fc_bsg_jobdone(job);
3879                         spin_lock_irq(q->queue_lock);
3880                         continue;
3881                 }
3882
3883                 /* the dispatch routines will unlock the queue_lock */
3884                 if (rport)
3885                         ret = fc_bsg_rport_dispatch(q, shost, rport, job);
3886                 else
3887                         ret = fc_bsg_host_dispatch(q, shost, job);
3888
3889                 /* did dispatcher hit state that can't process any more */
3890                 if (ret == FC_DISPATCH_BREAK)
3891                         break;
3892
3893                 /* did dispatcher had released the lock */
3894                 if (ret == FC_DISPATCH_UNLOCKED)
3895                         spin_lock_irq(q->queue_lock);
3896         }
3897
3898         spin_unlock_irq(q->queue_lock);
3899         put_device(dev);
3900         spin_lock_irq(q->queue_lock);
3901 }
3902
3903
3904 /**
3905  * fc_bsg_host_handler - handler for bsg requests for a fc host
3906  * @q:          fc host request queue
3907  */
3908 static void
3909 fc_bsg_host_handler(struct request_queue *q)
3910 {
3911         struct Scsi_Host *shost = q->queuedata;
3912
3913         fc_bsg_request_handler(q, shost, NULL, &shost->shost_gendev);
3914 }
3915
3916
3917 /**
3918  * fc_bsg_rport_handler - handler for bsg requests for a fc rport
3919  * @q:          rport request queue
3920  */
3921 static void
3922 fc_bsg_rport_handler(struct request_queue *q)
3923 {
3924         struct fc_rport *rport = q->queuedata;
3925         struct Scsi_Host *shost = rport_to_shost(rport);
3926
3927         fc_bsg_request_handler(q, shost, rport, &rport->dev);
3928 }
3929
3930
3931 /**
3932  * fc_bsg_hostadd - Create and add the bsg hooks so we can receive requests
3933  * @shost:      shost for fc_host
3934  * @fc_host:    fc_host adding the structures to
3935  */
3936 static int
3937 fc_bsg_hostadd(struct Scsi_Host *shost, struct fc_host_attrs *fc_host)
3938 {
3939         struct device *dev = &shost->shost_gendev;
3940         struct fc_internal *i = to_fc_internal(shost->transportt);
3941         struct request_queue *q;
3942         int err;
3943         char bsg_name[20];
3944
3945         fc_host->rqst_q = NULL;
3946
3947         if (!i->f->bsg_request)
3948                 return -ENOTSUPP;
3949
3950         snprintf(bsg_name, sizeof(bsg_name),
3951                  "fc_host%d", shost->host_no);
3952
3953         q = __scsi_alloc_queue(shost, fc_bsg_host_handler);
3954         if (!q) {
3955                 printk(KERN_ERR "fc_host%d: bsg interface failed to "
3956                                 "initialize - no request queue\n",
3957                                  shost->host_no);
3958                 return -ENOMEM;
3959         }
3960
3961         q->queuedata = shost;
3962         queue_flag_set_unlocked(QUEUE_FLAG_BIDI, q);
3963         blk_queue_softirq_done(q, fc_bsg_softirq_done);
3964         blk_queue_rq_timed_out(q, fc_bsg_job_timeout);
3965         blk_queue_rq_timeout(q, FC_DEFAULT_BSG_TIMEOUT);
3966
3967         err = bsg_register_queue(q, dev, bsg_name, NULL);
3968         if (err) {
3969                 printk(KERN_ERR "fc_host%d: bsg interface failed to "
3970                                 "initialize - register queue\n",
3971                                 shost->host_no);
3972                 blk_cleanup_queue(q);
3973                 return err;
3974         }
3975
3976         fc_host->rqst_q = q;
3977         return 0;
3978 }
3979
3980
3981 /**
3982  * fc_bsg_rportadd - Create and add the bsg hooks so we can receive requests
3983  * @shost:      shost that rport is attached to
3984  * @rport:      rport that the bsg hooks are being attached to
3985  */
3986 static int
3987 fc_bsg_rportadd(struct Scsi_Host *shost, struct fc_rport *rport)
3988 {
3989         struct device *dev = &rport->dev;
3990         struct fc_internal *i = to_fc_internal(shost->transportt);
3991         struct request_queue *q;
3992         int err;
3993
3994         rport->rqst_q = NULL;
3995
3996         if (!i->f->bsg_request)
3997                 return -ENOTSUPP;
3998
3999         q = __scsi_alloc_queue(shost, fc_bsg_rport_handler);
4000         if (!q) {
4001                 printk(KERN_ERR "%s: bsg interface failed to "
4002                                 "initialize - no request queue\n",
4003                                  dev->kobj.name);
4004                 return -ENOMEM;
4005         }
4006
4007         q->queuedata = rport;
4008         queue_flag_set_unlocked(QUEUE_FLAG_BIDI, q);
4009         blk_queue_softirq_done(q, fc_bsg_softirq_done);
4010         blk_queue_rq_timed_out(q, fc_bsg_job_timeout);
4011         blk_queue_rq_timeout(q, BLK_DEFAULT_SG_TIMEOUT);
4012
4013         err = bsg_register_queue(q, dev, NULL, NULL);
4014         if (err) {
4015                 printk(KERN_ERR "%s: bsg interface failed to "
4016                                 "initialize - register queue\n",
4017                                  dev->kobj.name);
4018                 blk_cleanup_queue(q);
4019                 return err;
4020         }
4021
4022         rport->rqst_q = q;
4023         return 0;
4024 }
4025
4026
4027 /**
4028  * fc_bsg_remove - Deletes the bsg hooks on fchosts/rports
4029  * @q:  the request_queue that is to be torn down.
4030  */
4031 static void
4032 fc_bsg_remove(struct request_queue *q)
4033 {
4034         if (q) {
4035                 bsg_unregister_queue(q);
4036                 blk_cleanup_queue(q);
4037         }
4038 }
4039
4040
4041 /* Original Author:  Martin Hicks */
4042 MODULE_AUTHOR("James Smart");
4043 MODULE_DESCRIPTION("FC Transport Attributes");
4044 MODULE_LICENSE("GPL");
4045
4046 module_init(fc_transport_init);
4047 module_exit(fc_transport_exit);