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