2 * Distributed under the terms of the GNU GPL version 2.
3 * Copyright (c) 2007, 2008 The Board of Trustees of The Leland
4 * Stanford Junior University
7 /* Functions for managing the dp interface/device. */
9 #include <linux/init.h>
10 #include <linux/module.h>
11 #include <linux/if_arp.h>
12 #include <linux/if_bridge.h>
13 #include <linux/if_vlan.h>
15 #include <net/genetlink.h>
17 #include <linux/delay.h>
18 #include <linux/etherdevice.h>
19 #include <linux/kernel.h>
20 #include <linux/kthread.h>
21 #include <linux/mutex.h>
22 #include <linux/rtnetlink.h>
23 #include <linux/rcupdate.h>
24 #include <linux/version.h>
25 #include <linux/ethtool.h>
26 #include <linux/random.h>
27 #include <asm/system.h>
28 #include <linux/netfilter_bridge.h>
29 #include <linux/inetdevice.h>
30 #include <linux/list.h>
31 #include <linux/rculist.h>
33 #include "openflow-netlink.h"
44 /* Number of milliseconds between runs of the maintenance thread. */
45 #define MAINT_SLEEP_MSECS 1000
47 #define BRIDGE_PORT_NO_FLOOD 0x00000001
49 #define UINT32_MAX 4294967295U
50 #define UINT16_MAX 65535
51 #define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
53 struct net_bridge_port {
57 struct net_device *dev;
58 struct list_head node; /* Element in datapath.ports. */
61 static struct genl_family dp_genl_family;
62 static struct genl_multicast_group mc_group;
64 /* It's hard to imagine wanting more than one datapath, but... */
67 /* Datapaths. Protected on the read side by rcu_read_lock, on the write side
68 * by dp_mutex. dp_mutex is almost completely redundant with genl_mutex
69 * maintained by the Generic Netlink code, but the timeout path needs mutual
72 * It is safe to access the datapath and net_bridge_port structures with just
75 static struct datapath *dps[DP_MAX];
76 DEFINE_MUTEX(dp_mutex);
77 EXPORT_SYMBOL(dp_mutex);
79 static int dp_maint_func(void *data);
80 static int send_port_status(struct net_bridge_port *p, uint8_t status);
81 static int dp_genl_openflow_done(struct netlink_callback *);
82 static struct net_bridge_port *new_nbp(struct datapath *,
83 struct net_device *, int port_no);
84 static int del_switch_port(struct net_bridge_port *);
86 /* nla_shrink - reduce amount of space reserved by nla_reserve
87 * @skb: socket buffer from which to recover room
88 * @nla: netlink attribute to adjust
89 * @len: new length of attribute payload
91 * Reduces amount of space reserved by a call to nla_reserve.
93 * No other attributes may be added between calling nla_reserve and this
94 * function, since it will create a hole in the message.
96 void nla_shrink(struct sk_buff *skb, struct nlattr *nla, int len)
98 int delta = nla_total_size(len) - nla_total_size(nla_len(nla));
102 nla->nla_len = nla_attr_size(len);
105 /* Puts a set of openflow headers for a message of the given 'type' into 'skb'.
106 * If 'sender' is nonnull, then it is used as the message's destination. 'dp'
107 * must specify the datapath to use.
109 * '*max_openflow_len' receives the maximum number of bytes that are available
110 * for the embedded OpenFlow message. The caller must call
111 * resize_openflow_skb() to set the actual size of the message to this number
114 * Returns the openflow header if successful, otherwise (if 'skb' is too small)
117 put_openflow_headers(struct datapath *dp, struct sk_buff *skb, uint8_t type,
118 const struct sender *sender, int *max_openflow_len)
120 struct ofp_header *oh;
124 /* Assemble the Generic Netlink wrapper. */
125 if (!genlmsg_put(skb,
126 sender ? sender->pid : 0,
127 sender ? sender->seq : 0,
128 &dp_genl_family, 0, DP_GENL_C_OPENFLOW))
129 return ERR_PTR(-ENOBUFS);
130 if (nla_put_u32(skb, DP_GENL_A_DP_IDX, dp->dp_idx) < 0)
131 return ERR_PTR(-ENOBUFS);
132 openflow_len = (skb_tailroom(skb) - NLA_HDRLEN) & ~(NLA_ALIGNTO - 1);
133 if (openflow_len < sizeof *oh)
134 return ERR_PTR(-ENOBUFS);
135 *max_openflow_len = openflow_len;
136 attr = nla_reserve(skb, DP_GENL_A_OPENFLOW, openflow_len);
139 /* Fill in the header. The caller is responsible for the length. */
141 oh->version = OFP_VERSION;
143 oh->xid = sender ? sender->xid : 0;
148 /* Resizes OpenFlow header 'oh', which must be at the tail end of 'skb', to new
149 * length 'new_length' (in bytes), adjusting pointers and size values as
152 resize_openflow_skb(struct sk_buff *skb,
153 struct ofp_header *oh, size_t new_length)
155 struct nlattr *attr = ((void *) oh) - NLA_HDRLEN;
156 nla_shrink(skb, attr, new_length);
157 oh->length = htons(new_length);
158 nlmsg_end(skb, (struct nlmsghdr *) skb->data);
161 /* Allocates a new skb to contain an OpenFlow message 'openflow_len' bytes in
162 * length. Returns a null pointer if memory is unavailable, otherwise returns
163 * the OpenFlow header and stores a pointer to the skb in '*pskb'.
165 * 'type' is the OpenFlow message type. If 'sender' is nonnull, then it is
166 * used as the message's destination. 'dp' must specify the datapath to
169 alloc_openflow_skb(struct datapath *dp, size_t openflow_len, uint8_t type,
170 const struct sender *sender, struct sk_buff **pskb)
172 struct ofp_header *oh;
175 int max_openflow_len;
177 if ((openflow_len + sizeof(struct ofp_header)) > UINT16_MAX) {
179 printk("alloc_openflow_skb: openflow message too large: %zu\n",
184 genl_len = nlmsg_total_size(GENL_HDRLEN + dp_genl_family.hdrsize);
185 genl_len += nla_total_size(sizeof(uint32_t)); /* DP_GENL_A_DP_IDX */
186 genl_len += nla_total_size(openflow_len); /* DP_GENL_A_OPENFLOW */
187 skb = *pskb = genlmsg_new(genl_len, GFP_ATOMIC);
190 printk("alloc_openflow_skb: genlmsg_new failed\n");
194 oh = put_openflow_headers(dp, skb, type, sender, &max_openflow_len);
195 BUG_ON(!oh || IS_ERR(oh));
196 resize_openflow_skb(skb, oh, openflow_len);
201 /* Sends 'skb' to 'sender' if it is nonnull, otherwise multicasts 'skb' to all
204 send_openflow_skb(struct sk_buff *skb, const struct sender *sender)
207 ? genlmsg_unicast(skb, sender->pid)
208 : genlmsg_multicast(skb, 0, mc_group.id, GFP_ATOMIC));
211 /* Generates a unique datapath id. It incorporates the datapath index
212 * and a hardware address, if available. If not, it generates a random
216 uint64_t gen_datapath_id(uint16_t dp_idx)
220 struct net_device *dev;
222 /* The top 16 bits are used to identify the datapath. The lower 48 bits
223 * use an interface address. */
224 id = (uint64_t)dp_idx << 48;
225 if ((dev = dev_get_by_name(&init_net, "ctl0"))
226 || (dev = dev_get_by_name(&init_net, "eth0"))) {
227 for (i=0; i<ETH_ALEN; i++) {
228 id |= (uint64_t)dev->dev_addr[i] << (8*(ETH_ALEN-1 - i));
232 /* Randomly choose the lower 48 bits if we cannot find an
233 * address and mark the most significant bit to indicate that
234 * this was randomly generated. */
235 uint8_t rand[ETH_ALEN];
236 get_random_bytes(rand, ETH_ALEN);
237 id |= (uint64_t)1 << 63;
238 for (i=0; i<ETH_ALEN; i++) {
239 id |= (uint64_t)rand[i] << (8*(ETH_ALEN-1 - i));
246 /* Creates a new datapath numbered 'dp_idx'. Returns 0 for success or a
247 * negative error code. */
248 static int new_dp(int dp_idx)
253 if (dp_idx < 0 || dp_idx >= DP_MAX)
256 if (!try_module_get(THIS_MODULE))
259 /* Exit early if a datapath with that number already exists. */
266 dp = kzalloc(sizeof *dp, GFP_KERNEL);
270 /* Setup our "of" device */
271 err = dp_dev_setup(dp);
276 dp->id = gen_datapath_id(dp_idx);
277 dp->chain = chain_create(dp);
278 if (dp->chain == NULL)
279 goto err_destroy_dp_dev;
280 INIT_LIST_HEAD(&dp->port_list);
282 dp->local_port = new_nbp(dp, dp->netdev, OFPP_LOCAL);
283 if (IS_ERR(dp->local_port)) {
284 err = PTR_ERR(dp->local_port);
285 goto err_destroy_local_port;
289 dp->miss_send_len = OFP_DEFAULT_MISS_SEND_LEN;
291 dp->dp_task = kthread_run(dp_maint_func, dp, "dp%d", dp_idx);
292 if (IS_ERR(dp->dp_task))
293 goto err_destroy_chain;
299 err_destroy_local_port:
300 del_switch_port(dp->local_port);
302 chain_destroy(dp->chain);
308 module_put(THIS_MODULE);
312 /* Find and return a free port number under 'dp'. */
313 static int find_portno(struct datapath *dp)
316 for (i = 0; i < OFPP_MAX; i++)
317 if (dp->ports[i] == NULL)
322 static struct net_bridge_port *new_nbp(struct datapath *dp,
323 struct net_device *dev, int port_no)
325 struct net_bridge_port *p;
327 if (dev->br_port != NULL)
328 return ERR_PTR(-EBUSY);
330 p = kzalloc(sizeof(*p), GFP_KERNEL);
332 return ERR_PTR(-ENOMEM);
335 dev_set_promiscuity(dev, 1);
340 p->port_no = port_no;
341 if (port_no != OFPP_LOCAL)
342 rcu_assign_pointer(dev->br_port, p);
343 if (port_no < OFPP_MAX)
344 rcu_assign_pointer(dp->ports[port_no], p);
345 list_add_rcu(&p->node, &dp->port_list);
350 int add_switch_port(struct datapath *dp, struct net_device *dev)
352 struct net_bridge_port *p;
355 if (dev->flags & IFF_LOOPBACK || dev->type != ARPHRD_ETHER
359 port_no = find_portno(dp);
363 p = new_nbp(dp, dev, port_no);
367 /* Notify the ctlpath that this port has been added */
368 send_port_status(p, OFPPR_ADD);
373 /* Delete 'p' from switch. */
374 static int del_switch_port(struct net_bridge_port *p)
376 /* First drop references to device. */
378 dev_set_promiscuity(p->dev, -1);
380 list_del_rcu(&p->node);
381 if (p->port_no != OFPP_LOCAL)
382 rcu_assign_pointer(p->dp->ports[p->port_no], NULL);
383 rcu_assign_pointer(p->dev->br_port, NULL);
385 /* Then wait until no one is still using it, and destroy it. */
388 /* Notify the ctlpath that this port no longer exists */
389 send_port_status(p, OFPPR_DELETE);
397 static void del_dp(struct datapath *dp)
399 struct net_bridge_port *p, *n;
401 kthread_stop(dp->dp_task);
403 /* Drop references to DP. */
404 list_for_each_entry_safe (p, n, &dp->port_list, node)
406 rcu_assign_pointer(dps[dp->dp_idx], NULL);
408 /* Kill off local_port dev references from buffered packets that have
409 * associated dst entries. */
413 /* Destroy dp->netdev. (Must follow deleting switch ports since
414 * dp->local_port has a reference to it.) */
417 /* Wait until no longer in use, then destroy it. */
419 chain_destroy(dp->chain);
421 module_put(THIS_MODULE);
424 static int dp_maint_func(void *data)
426 struct datapath *dp = (struct datapath *) data;
428 while (!kthread_should_stop()) {
429 chain_timeout(dp->chain);
430 msleep_interruptible(MAINT_SLEEP_MSECS);
437 do_port_input(struct net_bridge_port *p, struct sk_buff *skb)
439 /* Push the Ethernet header back on. */
440 skb_push(skb, ETH_HLEN);
441 fwd_port_input(p->dp->chain, skb, p->port_no);
445 * Used as br_handle_frame_hook. (Cannot run bridge at the same time, even on
446 * different set of devices!)
448 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
449 /* Called with rcu_read_lock. */
450 static struct sk_buff *dp_frame_hook(struct net_bridge_port *p,
453 do_port_input(p, skb);
456 #elif LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
457 static int dp_frame_hook(struct net_bridge_port *p, struct sk_buff **pskb)
459 do_port_input(p, *pskb);
463 /* NB: This has only been tested on 2.4.35 */
464 static void dp_frame_hook(struct sk_buff *skb)
466 struct net_bridge_port *p = skb->dev->br_port;
469 do_port_input(p, skb);
476 /* Forwarding output path.
477 * Based on net/bridge/br_forward.c. */
479 static inline unsigned packet_length(const struct sk_buff *skb)
481 int length = skb->len - ETH_HLEN;
482 if (skb->protocol == htons(ETH_P_8021Q))
487 /* Send packets out all the ports except the originating one. If the
488 * "flood" argument is set, only send along the minimum spanning tree.
491 output_all(struct datapath *dp, struct sk_buff *skb, int flood)
493 u32 disable = flood ? BRIDGE_PORT_NO_FLOOD : 0;
494 struct net_bridge_port *p;
497 list_for_each_entry_rcu (p, &dp->port_list, node) {
498 if (skb->dev == p->dev || p->flags & disable)
500 if (prev_port != -1) {
501 struct sk_buff *clone = skb_clone(skb, GFP_ATOMIC);
506 dp_output_port(dp, clone, prev_port);
508 prev_port = p->port_no;
511 dp_output_port(dp, skb, prev_port);
518 /* Marks 'skb' as having originated from 'in_port' in 'dp'.
519 FIXME: how are devices reference counted? */
520 int dp_set_origin(struct datapath *dp, uint16_t in_port,
523 struct net_bridge_port *p = (in_port < OFPP_MAX ? dp->ports[in_port]
524 : in_port == OFPP_LOCAL ? dp->local_port
533 /* Takes ownership of 'skb' and transmits it to 'out_port' on 'dp'.
535 int dp_output_port(struct datapath *dp, struct sk_buff *skb, int out_port)
538 if (out_port == OFPP_FLOOD)
539 return output_all(dp, skb, 1);
540 else if (out_port == OFPP_ALL)
541 return output_all(dp, skb, 0);
542 else if (out_port == OFPP_CONTROLLER)
543 return dp_output_control(dp, skb, fwd_save_skb(skb), 0,
545 else if (out_port == OFPP_TABLE) {
546 struct net_bridge_port *p = skb->dev->br_port;
548 retval = run_flow_through_tables(dp->chain, skb,
549 p ? p->port_no : OFPP_LOCAL);
553 } else if (out_port == OFPP_LOCAL) {
554 struct net_device *dev = dp->netdev;
555 return dev ? dp_dev_recv(dev, skb) : -ESRCH;
556 } else if (out_port >= 0 && out_port < OFPP_MAX) {
557 struct net_bridge_port *p = dp->ports[out_port];
562 if (packet_length(skb) > skb->dev->mtu) {
563 printk("dropped over-mtu packet: %d > %d\n",
564 packet_length(skb), skb->dev->mtu);
577 printk("can't forward to bad port %d\n", out_port);
581 /* Takes ownership of 'skb' and transmits it to 'dp''s control path. If
582 * 'buffer_id' != -1, then only the first 64 bytes of 'skb' are sent;
583 * otherwise, all of 'skb' is sent. 'reason' indicates why 'skb' is being
584 * sent. 'max_len' sets the maximum number of bytes that the caller
585 * wants to be sent; a value of 0 indicates the entire packet should be
588 dp_output_control(struct datapath *dp, struct sk_buff *skb,
589 uint32_t buffer_id, size_t max_len, int reason)
591 /* FIXME? Can we avoid creating a new skbuff in the case where we
592 * forward the whole packet? */
593 struct sk_buff *f_skb;
594 struct ofp_packet_in *opi;
595 struct net_bridge_port *p;
596 size_t fwd_len, opi_len;
600 if ((buffer_id != (uint32_t) -1) && max_len)
601 fwd_len = min(fwd_len, max_len);
603 opi_len = offsetof(struct ofp_packet_in, data) + fwd_len;
604 opi = alloc_openflow_skb(dp, opi_len, OFPT_PACKET_IN, NULL, &f_skb);
609 opi->buffer_id = htonl(buffer_id);
610 opi->total_len = htons(skb->len);
611 p = skb->dev->br_port;
612 opi->in_port = htons(p ? p->port_no : OFPP_LOCAL);
613 opi->reason = reason;
615 memcpy(opi->data, skb_mac_header(skb), fwd_len);
616 err = send_openflow_skb(f_skb, NULL);
623 static void fill_port_desc(struct net_bridge_port *p, struct ofp_phy_port *desc)
625 desc->port_no = htons(p->port_no);
626 strncpy(desc->name, p->dev->name, OFP_MAX_PORT_NAME_LEN);
627 desc->name[OFP_MAX_PORT_NAME_LEN-1] = '\0';
628 memcpy(desc->hw_addr, p->dev->dev_addr, ETH_ALEN);
629 desc->flags = htonl(p->flags);
633 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,24)
634 if (p->dev->ethtool_ops && p->dev->ethtool_ops->get_settings) {
635 struct ethtool_cmd ecmd = { .cmd = ETHTOOL_GSET };
637 if (!p->dev->ethtool_ops->get_settings(p->dev, &ecmd)) {
638 if (ecmd.supported & SUPPORTED_10baseT_Half)
639 desc->features |= OFPPF_10MB_HD;
640 if (ecmd.supported & SUPPORTED_10baseT_Full)
641 desc->features |= OFPPF_10MB_FD;
642 if (ecmd.supported & SUPPORTED_100baseT_Half)
643 desc->features |= OFPPF_100MB_HD;
644 if (ecmd.supported & SUPPORTED_100baseT_Full)
645 desc->features |= OFPPF_100MB_FD;
646 if (ecmd.supported & SUPPORTED_1000baseT_Half)
647 desc->features |= OFPPF_1GB_HD;
648 if (ecmd.supported & SUPPORTED_1000baseT_Full)
649 desc->features |= OFPPF_1GB_FD;
650 /* 10Gbps half-duplex doesn't exist... */
651 if (ecmd.supported & SUPPORTED_10000baseT_Full)
652 desc->features |= OFPPF_10GB_FD;
654 desc->features = htonl(desc->features);
655 desc->speed = htonl(ecmd.speed);
662 fill_features_reply(struct datapath *dp, struct ofp_switch_features *ofr)
664 struct net_bridge_port *p;
667 ofr->datapath_id = cpu_to_be64(dp->id);
669 ofr->n_exact = htonl(2 * TABLE_HASH_MAX_FLOWS);
670 ofr->n_compression = 0; /* Not supported */
671 ofr->n_general = htonl(TABLE_LINEAR_MAX_FLOWS);
672 ofr->buffer_mb = htonl(UINT32_MAX);
673 ofr->n_buffers = htonl(N_PKT_BUFFERS);
674 ofr->capabilities = htonl(OFP_SUPPORTED_CAPABILITIES);
675 ofr->actions = htonl(OFP_SUPPORTED_ACTIONS);
677 list_for_each_entry_rcu (p, &dp->port_list, node) {
678 fill_port_desc(p, &ofr->ports[port_count]);
686 dp_send_features_reply(struct datapath *dp, const struct sender *sender)
689 struct ofp_switch_features *ofr;
690 size_t ofr_len, port_max_len;
694 port_max_len = sizeof(struct ofp_phy_port) * OFPP_MAX;
695 ofr = alloc_openflow_skb(dp, sizeof(*ofr) + port_max_len,
696 OFPT_FEATURES_REPLY, sender, &skb);
701 port_count = fill_features_reply(dp, ofr);
704 ofr_len = sizeof(*ofr) + (sizeof(struct ofp_phy_port) * port_count);
705 resize_openflow_skb(skb, &ofr->header, ofr_len);
706 return send_openflow_skb(skb, sender);
710 dp_send_config_reply(struct datapath *dp, const struct sender *sender)
713 struct ofp_switch_config *osc;
715 osc = alloc_openflow_skb(dp, sizeof *osc, OFPT_GET_CONFIG_REPLY, sender,
720 osc->flags = htons(dp->flags);
721 osc->miss_send_len = htons(dp->miss_send_len);
723 return send_openflow_skb(skb, sender);
727 dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp)
729 int port_no = ntohs(opp->port_no);
730 struct net_bridge_port *p = (port_no < OFPP_MAX ? dp->ports[port_no]
731 : port_no == OFPP_LOCAL ? dp->local_port
733 /* Make sure the port id hasn't changed since this was sent */
734 if (!p || memcmp(opp->hw_addr, p->dev->dev_addr, ETH_ALEN))
736 p->flags = htonl(opp->flags);
742 send_port_status(struct net_bridge_port *p, uint8_t status)
745 struct ofp_port_status *ops;
747 ops = alloc_openflow_skb(p->dp, sizeof *ops, OFPT_PORT_STATUS, NULL,
751 ops->reason = status;
752 memset(ops->pad, 0, sizeof ops->pad);
753 fill_port_desc(p, &ops->desc);
755 return send_openflow_skb(skb, NULL);
759 dp_send_flow_expired(struct datapath *dp, struct sw_flow *flow)
762 struct ofp_flow_expired *ofe;
763 unsigned long duration_j;
765 ofe = alloc_openflow_skb(dp, sizeof *ofe, OFPT_FLOW_EXPIRED, 0, &skb);
769 flow_fill_match(&ofe->match, &flow->key);
771 memset(ofe->pad, 0, sizeof ofe->pad);
772 ofe->priority = htons(flow->priority);
774 duration_j = (flow->timeout - HZ * flow->max_idle) - flow->init_time;
775 ofe->duration = htonl(duration_j / HZ);
776 ofe->packet_count = cpu_to_be64(flow->packet_count);
777 ofe->byte_count = cpu_to_be64(flow->byte_count);
779 return send_openflow_skb(skb, NULL);
781 EXPORT_SYMBOL(dp_send_flow_expired);
784 dp_send_error_msg(struct datapath *dp, const struct sender *sender,
785 uint16_t type, uint16_t code, const uint8_t *data, size_t len)
788 struct ofp_error_msg *oem;
791 oem = alloc_openflow_skb(dp, sizeof(*oem)+len, OFPT_ERROR_MSG,
796 oem->type = htons(type);
797 oem->code = htons(code);
798 memcpy(oem->data, data, len);
800 return send_openflow_skb(skb, sender);
804 dp_send_echo_reply(struct datapath *dp, const struct sender *sender,
805 const struct ofp_header *rq)
808 struct ofp_header *reply;
810 reply = alloc_openflow_skb(dp, ntohs(rq->length), OFPT_ECHO_REPLY,
815 memcpy(reply + 1, rq + 1, ntohs(rq->length) - sizeof *rq);
816 return send_openflow_skb(skb, sender);
819 /* Generic Netlink interface.
821 * See netlink(7) for an introduction to netlink. See
822 * http://linux-net.osdl.org/index.php/Netlink for more information and
823 * pointers on how to work with netlink and Generic Netlink in the kernel and
826 static struct genl_family dp_genl_family = {
827 .id = GENL_ID_GENERATE,
829 .name = DP_GENL_FAMILY_NAME,
831 .maxattr = DP_GENL_A_MAX,
834 /* Attribute policy: what each attribute may contain. */
835 static struct nla_policy dp_genl_policy[DP_GENL_A_MAX + 1] = {
836 [DP_GENL_A_DP_IDX] = { .type = NLA_U32 },
837 [DP_GENL_A_MC_GROUP] = { .type = NLA_U32 },
838 [DP_GENL_A_PORTNAME] = { .type = NLA_STRING }
841 static int dp_genl_add(struct sk_buff *skb, struct genl_info *info)
843 if (!info->attrs[DP_GENL_A_DP_IDX])
846 return new_dp(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
849 static struct genl_ops dp_genl_ops_add_dp = {
850 .cmd = DP_GENL_C_ADD_DP,
851 .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
852 .policy = dp_genl_policy,
857 struct datapath *dp_get(int dp_idx)
859 if (dp_idx < 0 || dp_idx > DP_MAX)
861 return rcu_dereference(dps[dp_idx]);
864 static int dp_genl_del(struct sk_buff *skb, struct genl_info *info)
869 if (!info->attrs[DP_GENL_A_DP_IDX])
872 dp = dp_get(nla_get_u32((info->attrs[DP_GENL_A_DP_IDX])));
882 static struct genl_ops dp_genl_ops_del_dp = {
883 .cmd = DP_GENL_C_DEL_DP,
884 .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
885 .policy = dp_genl_policy,
890 /* Queries a datapath for related information. Currently the only relevant
891 * information is the datapath's multicast group ID. Really we want one
892 * multicast group per datapath, but because of locking issues[*] we can't
893 * easily get one. Thus, every datapath will currently return the same
894 * global multicast group ID, but in the future it would be nice to fix that.
896 * [*] dp_genl_add, to add a new datapath, is called under the genl_lock
897 * mutex, and genl_register_mc_group, called to acquire a new multicast
898 * group ID, also acquires genl_lock, thus deadlock.
900 static int dp_genl_query(struct sk_buff *skb, struct genl_info *info)
903 struct sk_buff *ans_skb = NULL;
907 if (!info->attrs[DP_GENL_A_DP_IDX])
911 dp_idx = nla_get_u32((info->attrs[DP_GENL_A_DP_IDX]));
917 ans_skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
922 data = genlmsg_put_reply(ans_skb, info, &dp_genl_family,
923 0, DP_GENL_C_QUERY_DP);
928 NLA_PUT_U32(ans_skb, DP_GENL_A_DP_IDX, dp_idx);
929 NLA_PUT_U32(ans_skb, DP_GENL_A_MC_GROUP, mc_group.id);
931 genlmsg_end(ans_skb, data);
932 err = genlmsg_reply(ans_skb, info);
944 static struct genl_ops dp_genl_ops_query_dp = {
945 .cmd = DP_GENL_C_QUERY_DP,
946 .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
947 .policy = dp_genl_policy,
948 .doit = dp_genl_query,
952 static int dp_genl_add_del_port(struct sk_buff *skb, struct genl_info *info)
955 struct net_device *port;
958 if (!info->attrs[DP_GENL_A_DP_IDX] || !info->attrs[DP_GENL_A_PORTNAME])
962 dp = dp_get(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
968 /* Get interface to add/remove. */
969 port = dev_get_by_name(&init_net,
970 nla_data(info->attrs[DP_GENL_A_PORTNAME]));
976 /* Execute operation. */
977 if (info->genlhdr->cmd == DP_GENL_C_ADD_PORT)
978 err = add_switch_port(dp, port);
980 if (port->br_port == NULL || port->br_port->dp != dp) {
984 err = del_switch_port(port->br_port);
993 static struct genl_ops dp_genl_ops_add_port = {
994 .cmd = DP_GENL_C_ADD_PORT,
995 .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
996 .policy = dp_genl_policy,
997 .doit = dp_genl_add_del_port,
1001 static struct genl_ops dp_genl_ops_del_port = {
1002 .cmd = DP_GENL_C_DEL_PORT,
1003 .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1004 .policy = dp_genl_policy,
1005 .doit = dp_genl_add_del_port,
1009 static int dp_genl_openflow(struct sk_buff *skb, struct genl_info *info)
1011 struct nlattr *va = info->attrs[DP_GENL_A_OPENFLOW];
1012 struct datapath *dp;
1013 struct ofp_header *oh;
1014 struct sender sender;
1017 if (!info->attrs[DP_GENL_A_DP_IDX] || !va)
1020 dp = dp_get(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
1024 if (nla_len(va) < sizeof(struct ofp_header))
1028 sender.xid = oh->xid;
1029 sender.pid = info->snd_pid;
1030 sender.seq = info->snd_seq;
1032 mutex_lock(&dp_mutex);
1033 err = fwd_control_input(dp->chain, &sender,
1034 nla_data(va), nla_len(va));
1035 mutex_unlock(&dp_mutex);
1039 static struct nla_policy dp_genl_openflow_policy[DP_GENL_A_MAX + 1] = {
1040 [DP_GENL_A_DP_IDX] = { .type = NLA_U32 },
1043 struct flow_stats_state {
1045 struct sw_table_position position;
1046 const struct ofp_flow_stats_request *rq;
1049 int bytes_used, bytes_allocated;
1052 static int flow_stats_init(struct datapath *dp, const void *body, int body_len,
1055 const struct ofp_flow_stats_request *fsr = body;
1056 struct flow_stats_state *s = kmalloc(sizeof *s, GFP_ATOMIC);
1059 s->table_idx = fsr->table_id == 0xff ? 0 : fsr->table_id;
1060 memset(&s->position, 0, sizeof s->position);
1066 static int flow_stats_dump_callback(struct sw_flow *flow, void *private)
1068 struct flow_stats_state *s = private;
1069 struct ofp_flow_stats *ofs;
1073 actions_length = sizeof *ofs->actions * flow->n_actions;
1074 length = sizeof *ofs + sizeof *ofs->actions * flow->n_actions;
1075 if (length + s->bytes_used > s->bytes_allocated)
1078 ofs = s->body + s->bytes_used;
1079 ofs->length = htons(length);
1080 ofs->table_id = s->table_idx;
1082 ofs->match.wildcards = htons(flow->key.wildcards);
1083 ofs->match.in_port = flow->key.in_port;
1084 memcpy(ofs->match.dl_src, flow->key.dl_src, ETH_ALEN);
1085 memcpy(ofs->match.dl_dst, flow->key.dl_dst, ETH_ALEN);
1086 ofs->match.dl_vlan = flow->key.dl_vlan;
1087 ofs->match.dl_type = flow->key.dl_type;
1088 ofs->match.nw_src = flow->key.nw_src;
1089 ofs->match.nw_dst = flow->key.nw_dst;
1090 ofs->match.nw_proto = flow->key.nw_proto;
1091 memset(ofs->match.pad, 0, sizeof ofs->match.pad);
1092 ofs->match.tp_src = flow->key.tp_src;
1093 ofs->match.tp_dst = flow->key.tp_dst;
1094 ofs->duration = htonl((jiffies - flow->init_time) / HZ);
1095 ofs->packet_count = cpu_to_be64(flow->packet_count);
1096 ofs->byte_count = cpu_to_be64(flow->byte_count);
1097 ofs->priority = htons(flow->priority);
1098 ofs->max_idle = htons(flow->max_idle);
1099 memcpy(ofs->actions, flow->actions, actions_length);
1101 s->bytes_used += length;
1105 static int flow_stats_dump(struct datapath *dp, void *state,
1106 void *body, int *body_len)
1108 struct flow_stats_state *s = state;
1109 struct sw_flow_key match_key;
1113 s->bytes_allocated = *body_len;
1116 flow_extract_match(&match_key, &s->rq->match);
1117 while (s->table_idx < dp->chain->n_tables
1118 && (s->rq->table_id == 0xff || s->rq->table_id == s->table_idx))
1120 struct sw_table *table = dp->chain->tables[s->table_idx];
1122 error = table->iterate(table, &match_key, &s->position,
1123 flow_stats_dump_callback, s);
1128 memset(&s->position, 0, sizeof s->position);
1130 *body_len = s->bytes_used;
1132 /* If error is 0, we're done.
1133 * Otherwise, if some bytes were used, there are more flows to come.
1134 * Otherwise, we were not able to fit even a single flow in the body,
1135 * which indicates that we have a single flow with too many actions to
1136 * fit. We won't ever make any progress at that rate, so give up. */
1137 return !error ? 0 : s->bytes_used ? 1 : -ENOMEM;
1140 static void flow_stats_done(void *state)
1145 static int aggregate_stats_init(struct datapath *dp,
1146 const void *body, int body_len,
1149 *state = (void *)body;
1153 static int aggregate_stats_dump_callback(struct sw_flow *flow, void *private)
1155 struct ofp_aggregate_stats_reply *rpy = private;
1156 rpy->packet_count += flow->packet_count;
1157 rpy->byte_count += flow->byte_count;
1162 static int aggregate_stats_dump(struct datapath *dp, void *state,
1163 void *body, int *body_len)
1165 struct ofp_aggregate_stats_request *rq = state;
1166 struct ofp_aggregate_stats_reply *rpy;
1167 struct sw_table_position position;
1168 struct sw_flow_key match_key;
1171 if (*body_len < sizeof *rpy)
1174 *body_len = sizeof *rpy;
1176 memset(rpy, 0, sizeof *rpy);
1178 flow_extract_match(&match_key, &rq->match);
1179 table_idx = rq->table_id == 0xff ? 0 : rq->table_id;
1180 memset(&position, 0, sizeof position);
1181 while (table_idx < dp->chain->n_tables
1182 && (rq->table_id == 0xff || rq->table_id == table_idx))
1184 struct sw_table *table = dp->chain->tables[table_idx];
1187 error = table->iterate(table, &match_key, &position,
1188 aggregate_stats_dump_callback, rpy);
1193 memset(&position, 0, sizeof position);
1196 rpy->packet_count = cpu_to_be64(rpy->packet_count);
1197 rpy->byte_count = cpu_to_be64(rpy->byte_count);
1198 rpy->flow_count = htonl(rpy->flow_count);
1202 static int table_stats_dump(struct datapath *dp, void *state,
1203 void *body, int *body_len)
1205 struct ofp_table_stats *ots;
1206 int nbytes = dp->chain->n_tables * sizeof *ots;
1208 if (nbytes > *body_len)
1211 for (i = 0, ots = body; i < dp->chain->n_tables; i++, ots++) {
1212 struct sw_table_stats stats;
1213 dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
1214 strncpy(ots->name, stats.name, sizeof ots->name);
1216 memset(ots->pad, 0, sizeof ots->pad);
1217 ots->max_entries = htonl(stats.max_flows);
1218 ots->active_count = htonl(stats.n_flows);
1219 ots->matched_count = cpu_to_be64(stats.n_matched);
1224 struct port_stats_state {
1228 static int port_stats_init(struct datapath *dp, const void *body, int body_len,
1231 struct port_stats_state *s = kmalloc(sizeof *s, GFP_ATOMIC);
1239 static int port_stats_dump(struct datapath *dp, void *state,
1240 void *body, int *body_len)
1242 struct port_stats_state *s = state;
1243 struct ofp_port_stats *ops;
1244 int n_ports, max_ports;
1247 max_ports = *body_len / sizeof *ops;
1253 for (i = s->port; i < OFPP_MAX && n_ports < max_ports; i++) {
1254 struct net_bridge_port *p = dp->ports[i];
1255 struct net_device_stats *stats;
1258 stats = p->dev->get_stats(p->dev);
1259 ops->port_no = htons(p->port_no);
1260 memset(ops->pad, 0, sizeof ops->pad);
1261 ops->rx_count = cpu_to_be64(stats->rx_packets);
1262 ops->tx_count = cpu_to_be64(stats->tx_packets);
1263 ops->drop_count = cpu_to_be64(stats->rx_dropped
1264 + stats->tx_dropped);
1269 *body_len = n_ports * sizeof *ops;
1270 return n_ports >= max_ports;
1273 static void port_stats_done(void *state)
1279 /* Minimum and maximum acceptable number of bytes in body member of
1280 * struct ofp_stats_request. */
1281 size_t min_body, max_body;
1283 /* Prepares to dump some kind of statistics on 'dp'. 'body' and
1284 * 'body_len' are the 'body' member of the struct ofp_stats_request.
1285 * Returns zero if successful, otherwise a negative error code.
1286 * May initialize '*state' to state information. May be null if no
1287 * initialization is required.*/
1288 int (*init)(struct datapath *dp, const void *body, int body_len,
1291 /* Dumps statistics for 'dp' into the '*body_len' bytes at 'body', and
1292 * modifies '*body_len' to reflect the number of bytes actually used.
1293 * ('body' will be transmitted as the 'body' member of struct
1294 * ofp_stats_reply.) */
1295 int (*dump)(struct datapath *dp, void *state,
1296 void *body, int *body_len);
1298 /* Cleans any state created by the init or dump functions. May be null
1299 * if no cleanup is required. */
1300 void (*done)(void *state);
1303 static const struct stats_type stats[] = {
1305 sizeof(struct ofp_flow_stats_request),
1306 sizeof(struct ofp_flow_stats_request),
1311 [OFPST_AGGREGATE] = {
1312 sizeof(struct ofp_aggregate_stats_request),
1313 sizeof(struct ofp_aggregate_stats_request),
1314 aggregate_stats_init,
1315 aggregate_stats_dump,
1335 dp_genl_openflow_dumpit(struct sk_buff *skb, struct netlink_callback *cb)
1337 struct datapath *dp;
1338 struct sender sender;
1339 const struct stats_type *s;
1340 struct ofp_stats_reply *osr;
1342 int max_openflow_len, body_len;
1346 /* Set up the cleanup function for this dump. Linux 2.6.20 and later
1347 * support setting up cleanup functions via the .doneit member of
1348 * struct genl_ops. This kluge supports earlier versions also. */
1349 cb->done = dp_genl_openflow_done;
1352 struct nlattr *attrs[DP_GENL_A_MAX + 1];
1353 struct ofp_stats_request *rq;
1355 size_t len, body_len;
1358 err = nlmsg_parse(cb->nlh, GENL_HDRLEN, attrs, DP_GENL_A_MAX,
1359 dp_genl_openflow_policy);
1363 if (!attrs[DP_GENL_A_DP_IDX])
1365 dp_idx = nla_get_u16(attrs[DP_GENL_A_DP_IDX]);
1366 dp = dp_get(dp_idx);
1370 va = attrs[DP_GENL_A_OPENFLOW];
1372 if (!va || len < sizeof *rq)
1376 type = ntohs(rq->type);
1377 if (rq->header.version != OFP_VERSION
1378 || rq->header.type != OFPT_STATS_REQUEST
1379 || ntohs(rq->header.length) != len
1380 || type >= ARRAY_SIZE(stats)
1381 || !stats[type].dump)
1385 body_len = len - offsetof(struct ofp_stats_request, body);
1386 if (body_len < s->min_body || body_len > s->max_body)
1390 cb->args[1] = dp_idx;
1392 cb->args[3] = rq->header.xid;
1395 err = s->init(dp, rq->body, body_len, &state);
1398 cb->args[4] = (long) state;
1400 } else if (cb->args[0] == 1) {
1401 dp_idx = cb->args[1];
1402 s = &stats[cb->args[2]];
1404 dp = dp_get(dp_idx);
1411 sender.xid = cb->args[3];
1412 sender.pid = NETLINK_CB(cb->skb).pid;
1413 sender.seq = cb->nlh->nlmsg_seq;
1415 osr = put_openflow_headers(dp, skb, OFPT_STATS_REPLY, &sender,
1418 return PTR_ERR(osr);
1419 osr->type = htons(s - stats);
1421 resize_openflow_skb(skb, &osr->header, max_openflow_len);
1423 body_len = max_openflow_len - offsetof(struct ofp_stats_reply, body);
1425 err = s->dump(dp, (void *) cb->args[4], body, &body_len);
1430 osr->flags = ntohs(OFPSF_REPLY_MORE);
1431 resize_openflow_skb(skb, &osr->header,
1432 (offsetof(struct ofp_stats_reply, body)
1441 dp_genl_openflow_done(struct netlink_callback *cb)
1444 const struct stats_type *s = &stats[cb->args[2]];
1446 s->done((void *) cb->args[4]);
1451 static struct genl_ops dp_genl_ops_openflow = {
1452 .cmd = DP_GENL_C_OPENFLOW,
1453 .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1454 .policy = dp_genl_openflow_policy,
1455 .doit = dp_genl_openflow,
1456 .dumpit = dp_genl_openflow_dumpit,
1459 static struct genl_ops *dp_genl_all_ops[] = {
1460 /* Keep this operation first. Generic Netlink dispatching
1461 * looks up operations with linear search, so we want it at the
1463 &dp_genl_ops_openflow,
1465 &dp_genl_ops_add_dp,
1466 &dp_genl_ops_del_dp,
1467 &dp_genl_ops_query_dp,
1468 &dp_genl_ops_add_port,
1469 &dp_genl_ops_del_port,
1472 static int dp_init_netlink(void)
1477 err = genl_register_family(&dp_genl_family);
1481 for (i = 0; i < ARRAY_SIZE(dp_genl_all_ops); i++) {
1482 err = genl_register_ops(&dp_genl_family, dp_genl_all_ops[i]);
1484 goto err_unregister;
1487 strcpy(mc_group.name, "openflow");
1488 err = genl_register_mc_group(&dp_genl_family, &mc_group);
1490 goto err_unregister;
1495 genl_unregister_family(&dp_genl_family);
1499 static void dp_uninit_netlink(void)
1501 genl_unregister_family(&dp_genl_family);
1504 #define DRV_NAME "openflow"
1505 #define DRV_VERSION VERSION
1506 #define DRV_DESCRIPTION "OpenFlow switching datapath implementation"
1507 #define DRV_COPYRIGHT "Copyright (c) 2007, 2008 The Board of Trustees of The Leland Stanford Junior University"
1510 static int __init dp_init(void)
1514 printk(KERN_INFO DRV_NAME ": " DRV_DESCRIPTION "\n");
1515 printk(KERN_INFO DRV_NAME ": " VERSION" built on "__DATE__" "__TIME__"\n");
1516 printk(KERN_INFO DRV_NAME ": " DRV_COPYRIGHT "\n");
1522 err = dp_init_netlink();
1524 goto error_flow_exit;
1526 /* Hook into callback used by the bridge to intercept packets.
1527 * Parasites we are. */
1528 if (br_handle_frame_hook)
1529 printk("openflow: hijacking bridge hook\n");
1530 br_handle_frame_hook = dp_frame_hook;
1537 printk(KERN_EMERG "openflow: failed to install!");
1541 static void dp_cleanup(void)
1544 dp_uninit_netlink();
1546 br_handle_frame_hook = NULL;
1549 module_init(dp_init);
1550 module_exit(dp_cleanup);
1552 MODULE_DESCRIPTION(DRV_DESCRIPTION);
1553 MODULE_AUTHOR(DRV_COPYRIGHT);
1554 MODULE_LICENSE("GPL");