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 /* Strings to describe the manufacturer, hardware, and software. This data
45 * is queriable through the version stats message. */
46 static char mfr_desc[VERSION_STR_LEN] = "Nicira Networks";
47 static char hw_desc[VERSION_STR_LEN] = "Reference Linux Kernel Module";
48 static char sw_desc[VERSION_STR_LEN] = VERSION;
50 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
51 module_param_string(mfr_desc, mfr_desc, sizeof mfr_desc, 0444);
52 module_param_string(hw_desc, hw_desc, sizeof hw_desc, 0444);
53 module_param_string(sw_desc, sw_desc, sizeof sw_desc, 0444);
55 MODULE_PARM(mfr_desc, "s");
56 MODULE_PARM(hw_desc, "s");
57 MODULE_PARM(sw_desc, "s");
61 /* Number of milliseconds between runs of the maintenance thread. */
62 #define MAINT_SLEEP_MSECS 1000
64 #define BRIDGE_PORT_NO_FLOOD 0x00000001
66 #define UINT32_MAX 4294967295U
67 #define UINT16_MAX 65535
68 #define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
70 struct net_bridge_port {
74 struct net_device *dev;
75 struct list_head node; /* Element in datapath.ports. */
78 static struct genl_family dp_genl_family;
79 static struct genl_multicast_group mc_group;
81 /* It's hard to imagine wanting more than one datapath, but... */
84 /* Datapaths. Protected on the read side by rcu_read_lock, on the write side
85 * by dp_mutex. dp_mutex is almost completely redundant with genl_mutex
86 * maintained by the Generic Netlink code, but the timeout path needs mutual
89 * It is safe to access the datapath and net_bridge_port structures with just
92 static struct datapath *dps[DP_MAX];
93 DEFINE_MUTEX(dp_mutex);
94 EXPORT_SYMBOL(dp_mutex);
96 static int dp_maint_func(void *data);
97 static int send_port_status(struct net_bridge_port *p, uint8_t status);
98 static int dp_genl_openflow_done(struct netlink_callback *);
99 static struct net_bridge_port *new_nbp(struct datapath *,
100 struct net_device *, int port_no);
101 static int del_switch_port(struct net_bridge_port *);
103 /* nla_shrink - reduce amount of space reserved by nla_reserve
104 * @skb: socket buffer from which to recover room
105 * @nla: netlink attribute to adjust
106 * @len: new length of attribute payload
108 * Reduces amount of space reserved by a call to nla_reserve.
110 * No other attributes may be added between calling nla_reserve and this
111 * function, since it will create a hole in the message.
113 void nla_shrink(struct sk_buff *skb, struct nlattr *nla, int len)
115 int delta = nla_total_size(len) - nla_total_size(nla_len(nla));
119 nla->nla_len = nla_attr_size(len);
122 /* Puts a set of openflow headers for a message of the given 'type' into 'skb'.
123 * If 'sender' is nonnull, then it is used as the message's destination. 'dp'
124 * must specify the datapath to use.
126 * '*max_openflow_len' receives the maximum number of bytes that are available
127 * for the embedded OpenFlow message. The caller must call
128 * resize_openflow_skb() to set the actual size of the message to this number
131 * Returns the openflow header if successful, otherwise (if 'skb' is too small)
134 put_openflow_headers(struct datapath *dp, struct sk_buff *skb, uint8_t type,
135 const struct sender *sender, int *max_openflow_len)
137 struct ofp_header *oh;
141 /* Assemble the Generic Netlink wrapper. */
142 if (!genlmsg_put(skb,
143 sender ? sender->pid : 0,
144 sender ? sender->seq : 0,
145 &dp_genl_family, 0, DP_GENL_C_OPENFLOW))
146 return ERR_PTR(-ENOBUFS);
147 if (nla_put_u32(skb, DP_GENL_A_DP_IDX, dp->dp_idx) < 0)
148 return ERR_PTR(-ENOBUFS);
149 openflow_len = (skb_tailroom(skb) - NLA_HDRLEN) & ~(NLA_ALIGNTO - 1);
150 if (openflow_len < sizeof *oh)
151 return ERR_PTR(-ENOBUFS);
152 *max_openflow_len = openflow_len;
153 attr = nla_reserve(skb, DP_GENL_A_OPENFLOW, openflow_len);
156 /* Fill in the header. The caller is responsible for the length. */
158 oh->version = OFP_VERSION;
160 oh->xid = sender ? sender->xid : 0;
165 /* Resizes OpenFlow header 'oh', which must be at the tail end of 'skb', to new
166 * length 'new_length' (in bytes), adjusting pointers and size values as
169 resize_openflow_skb(struct sk_buff *skb,
170 struct ofp_header *oh, size_t new_length)
172 struct nlattr *attr = ((void *) oh) - NLA_HDRLEN;
173 nla_shrink(skb, attr, new_length);
174 oh->length = htons(new_length);
175 nlmsg_end(skb, (struct nlmsghdr *) skb->data);
178 /* Allocates a new skb to contain an OpenFlow message 'openflow_len' bytes in
179 * length. Returns a null pointer if memory is unavailable, otherwise returns
180 * the OpenFlow header and stores a pointer to the skb in '*pskb'.
182 * 'type' is the OpenFlow message type. If 'sender' is nonnull, then it is
183 * used as the message's destination. 'dp' must specify the datapath to
186 alloc_openflow_skb(struct datapath *dp, size_t openflow_len, uint8_t type,
187 const struct sender *sender, struct sk_buff **pskb)
189 struct ofp_header *oh;
192 int max_openflow_len;
194 if ((openflow_len + sizeof(struct ofp_header)) > UINT16_MAX) {
196 printk("alloc_openflow_skb: openflow message too large: %zu\n",
201 genl_len = nlmsg_total_size(GENL_HDRLEN + dp_genl_family.hdrsize);
202 genl_len += nla_total_size(sizeof(uint32_t)); /* DP_GENL_A_DP_IDX */
203 genl_len += nla_total_size(openflow_len); /* DP_GENL_A_OPENFLOW */
204 skb = *pskb = genlmsg_new(genl_len, GFP_ATOMIC);
207 printk("alloc_openflow_skb: genlmsg_new failed\n");
211 oh = put_openflow_headers(dp, skb, type, sender, &max_openflow_len);
212 BUG_ON(!oh || IS_ERR(oh));
213 resize_openflow_skb(skb, oh, openflow_len);
218 /* Sends 'skb' to 'sender' if it is nonnull, otherwise multicasts 'skb' to all
221 send_openflow_skb(struct sk_buff *skb, const struct sender *sender)
224 ? genlmsg_unicast(skb, sender->pid)
225 : genlmsg_multicast(skb, 0, mc_group.id, GFP_ATOMIC));
228 /* Generates a unique datapath id. It incorporates the datapath index
229 * and a hardware address, if available. If not, it generates a random
233 uint64_t gen_datapath_id(uint16_t dp_idx)
237 struct net_device *dev;
239 /* The top 16 bits are used to identify the datapath. The lower 48 bits
240 * use an interface address. */
241 id = (uint64_t)dp_idx << 48;
242 if ((dev = dev_get_by_name(&init_net, "ctl0"))
243 || (dev = dev_get_by_name(&init_net, "eth0"))) {
244 for (i=0; i<ETH_ALEN; i++) {
245 id |= (uint64_t)dev->dev_addr[i] << (8*(ETH_ALEN-1 - i));
249 /* Randomly choose the lower 48 bits if we cannot find an
250 * address and mark the most significant bit to indicate that
251 * this was randomly generated. */
252 uint8_t rand[ETH_ALEN];
253 get_random_bytes(rand, ETH_ALEN);
254 id |= (uint64_t)1 << 63;
255 for (i=0; i<ETH_ALEN; i++) {
256 id |= (uint64_t)rand[i] << (8*(ETH_ALEN-1 - i));
263 /* Creates a new datapath numbered 'dp_idx'. Returns 0 for success or a
264 * negative error code. */
265 static int new_dp(int dp_idx)
270 if (dp_idx < 0 || dp_idx >= DP_MAX)
273 if (!try_module_get(THIS_MODULE))
276 /* Exit early if a datapath with that number already exists. */
283 dp = kzalloc(sizeof *dp, GFP_KERNEL);
287 /* Setup our "of" device */
288 err = dp_dev_setup(dp);
293 dp->id = gen_datapath_id(dp_idx);
294 dp->chain = chain_create(dp);
295 if (dp->chain == NULL)
296 goto err_destroy_dp_dev;
297 INIT_LIST_HEAD(&dp->port_list);
299 dp->local_port = new_nbp(dp, dp->netdev, OFPP_LOCAL);
300 if (IS_ERR(dp->local_port)) {
301 err = PTR_ERR(dp->local_port);
302 goto err_destroy_local_port;
306 dp->miss_send_len = OFP_DEFAULT_MISS_SEND_LEN;
308 dp->dp_task = kthread_run(dp_maint_func, dp, "dp%d", dp_idx);
309 if (IS_ERR(dp->dp_task))
310 goto err_destroy_chain;
316 err_destroy_local_port:
317 del_switch_port(dp->local_port);
319 chain_destroy(dp->chain);
325 module_put(THIS_MODULE);
329 /* Find and return a free port number under 'dp'. */
330 static int find_portno(struct datapath *dp)
333 for (i = 0; i < OFPP_MAX; i++)
334 if (dp->ports[i] == NULL)
339 static struct net_bridge_port *new_nbp(struct datapath *dp,
340 struct net_device *dev, int port_no)
342 struct net_bridge_port *p;
344 if (dev->br_port != NULL)
345 return ERR_PTR(-EBUSY);
347 p = kzalloc(sizeof(*p), GFP_KERNEL);
349 return ERR_PTR(-ENOMEM);
352 dev_set_promiscuity(dev, 1);
357 p->port_no = port_no;
358 if (port_no != OFPP_LOCAL)
359 rcu_assign_pointer(dev->br_port, p);
360 if (port_no < OFPP_MAX)
361 rcu_assign_pointer(dp->ports[port_no], p);
362 list_add_rcu(&p->node, &dp->port_list);
367 int add_switch_port(struct datapath *dp, struct net_device *dev)
369 struct net_bridge_port *p;
372 if (dev->flags & IFF_LOOPBACK || dev->type != ARPHRD_ETHER
376 port_no = find_portno(dp);
380 p = new_nbp(dp, dev, port_no);
384 /* Notify the ctlpath that this port has been added */
385 send_port_status(p, OFPPR_ADD);
390 /* Delete 'p' from switch. */
391 static int del_switch_port(struct net_bridge_port *p)
393 /* First drop references to device. */
395 dev_set_promiscuity(p->dev, -1);
397 list_del_rcu(&p->node);
398 if (p->port_no != OFPP_LOCAL)
399 rcu_assign_pointer(p->dp->ports[p->port_no], NULL);
400 rcu_assign_pointer(p->dev->br_port, NULL);
402 /* Then wait until no one is still using it, and destroy it. */
405 /* Notify the ctlpath that this port no longer exists */
406 send_port_status(p, OFPPR_DELETE);
414 static void del_dp(struct datapath *dp)
416 struct net_bridge_port *p, *n;
418 kthread_stop(dp->dp_task);
420 /* Drop references to DP. */
421 list_for_each_entry_safe (p, n, &dp->port_list, node)
423 rcu_assign_pointer(dps[dp->dp_idx], NULL);
425 /* Kill off local_port dev references from buffered packets that have
426 * associated dst entries. */
430 /* Destroy dp->netdev. (Must follow deleting switch ports since
431 * dp->local_port has a reference to it.) */
434 /* Wait until no longer in use, then destroy it. */
436 chain_destroy(dp->chain);
438 module_put(THIS_MODULE);
441 static int dp_maint_func(void *data)
443 struct datapath *dp = (struct datapath *) data;
445 while (!kthread_should_stop()) {
446 chain_timeout(dp->chain);
447 msleep_interruptible(MAINT_SLEEP_MSECS);
454 do_port_input(struct net_bridge_port *p, struct sk_buff *skb)
456 /* Push the Ethernet header back on. */
457 skb_push(skb, ETH_HLEN);
458 fwd_port_input(p->dp->chain, skb, p->port_no);
462 * Used as br_handle_frame_hook. (Cannot run bridge at the same time, even on
463 * different set of devices!)
465 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
466 /* Called with rcu_read_lock. */
467 static struct sk_buff *dp_frame_hook(struct net_bridge_port *p,
470 do_port_input(p, skb);
473 #elif LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
474 static int dp_frame_hook(struct net_bridge_port *p, struct sk_buff **pskb)
476 do_port_input(p, *pskb);
480 /* NB: This has only been tested on 2.4.35 */
481 static void dp_frame_hook(struct sk_buff *skb)
483 struct net_bridge_port *p = skb->dev->br_port;
486 do_port_input(p, skb);
493 /* Forwarding output path.
494 * Based on net/bridge/br_forward.c. */
496 static inline unsigned packet_length(const struct sk_buff *skb)
498 int length = skb->len - ETH_HLEN;
499 if (skb->protocol == htons(ETH_P_8021Q))
504 /* Send packets out all the ports except the originating one. If the
505 * "flood" argument is set, only send along the minimum spanning tree.
508 output_all(struct datapath *dp, struct sk_buff *skb, int flood)
510 u32 disable = flood ? BRIDGE_PORT_NO_FLOOD : 0;
511 struct net_bridge_port *p;
514 list_for_each_entry_rcu (p, &dp->port_list, node) {
515 if (skb->dev == p->dev || p->flags & disable)
517 if (prev_port != -1) {
518 struct sk_buff *clone = skb_clone(skb, GFP_ATOMIC);
523 dp_output_port(dp, clone, prev_port);
525 prev_port = p->port_no;
528 dp_output_port(dp, skb, prev_port);
535 /* Marks 'skb' as having originated from 'in_port' in 'dp'.
536 FIXME: how are devices reference counted? */
537 int dp_set_origin(struct datapath *dp, uint16_t in_port,
540 struct net_bridge_port *p = (in_port < OFPP_MAX ? dp->ports[in_port]
541 : in_port == OFPP_LOCAL ? dp->local_port
550 static int xmit_skb(struct sk_buff *skb)
553 if (packet_length(skb) > skb->dev->mtu) {
554 printk("dropped over-mtu packet: %d > %d\n",
555 packet_length(skb), skb->dev->mtu);
565 /* Takes ownership of 'skb' and transmits it to 'out_port' on 'dp'.
567 int dp_output_port(struct datapath *dp, struct sk_buff *skb, int out_port)
572 /* Send it out the port it came in on, which is already set in
576 printk("skb device not set forwarding to in_port\n");
580 return xmit_skb(skb);
583 struct net_bridge_port *p = skb->dev->br_port;
585 retval = run_flow_through_tables(dp->chain, skb,
586 p ? p->port_no : OFPP_LOCAL);
593 return output_all(dp, skb, 1);
596 return output_all(dp, skb, 0);
598 case OFPP_CONTROLLER:
599 return dp_output_control(dp, skb, fwd_save_skb(skb), 0,
603 struct net_device *dev = dp->netdev;
604 return dev ? dp_dev_recv(dev, skb) : -ESRCH;
607 case 0 ... OFPP_MAX-1: {
608 struct net_bridge_port *p = dp->ports[out_port];
611 if (p->dev == skb->dev) {
612 /* To send to the input port, must use OFPP_IN_PORT */
615 printk("can't directly forward to input port\n");
619 return xmit_skb(skb);
629 printk("can't forward to bad port %d\n", out_port);
633 /* Takes ownership of 'skb' and transmits it to 'dp''s control path. If
634 * 'buffer_id' != -1, then only the first 64 bytes of 'skb' are sent;
635 * otherwise, all of 'skb' is sent. 'reason' indicates why 'skb' is being
636 * sent. 'max_len' sets the maximum number of bytes that the caller
637 * wants to be sent; a value of 0 indicates the entire packet should be
640 dp_output_control(struct datapath *dp, struct sk_buff *skb,
641 uint32_t buffer_id, size_t max_len, int reason)
643 /* FIXME? Can we avoid creating a new skbuff in the case where we
644 * forward the whole packet? */
645 struct sk_buff *f_skb;
646 struct ofp_packet_in *opi;
647 struct net_bridge_port *p;
648 size_t fwd_len, opi_len;
652 if ((buffer_id != (uint32_t) -1) && max_len)
653 fwd_len = min(fwd_len, max_len);
655 opi_len = offsetof(struct ofp_packet_in, data) + fwd_len;
656 opi = alloc_openflow_skb(dp, opi_len, OFPT_PACKET_IN, NULL, &f_skb);
661 opi->buffer_id = htonl(buffer_id);
662 opi->total_len = htons(skb->len);
663 p = skb->dev->br_port;
664 opi->in_port = htons(p ? p->port_no : OFPP_LOCAL);
665 opi->reason = reason;
667 memcpy(opi->data, skb_mac_header(skb), fwd_len);
668 err = send_openflow_skb(f_skb, NULL);
675 static void fill_port_desc(struct net_bridge_port *p, struct ofp_phy_port *desc)
677 desc->port_no = htons(p->port_no);
678 strncpy(desc->name, p->dev->name, OFP_MAX_PORT_NAME_LEN);
679 desc->name[OFP_MAX_PORT_NAME_LEN-1] = '\0';
680 memcpy(desc->hw_addr, p->dev->dev_addr, ETH_ALEN);
681 desc->flags = htonl(p->flags);
685 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,24)
686 if (p->dev->ethtool_ops && p->dev->ethtool_ops->get_settings) {
687 struct ethtool_cmd ecmd = { .cmd = ETHTOOL_GSET };
689 if (!p->dev->ethtool_ops->get_settings(p->dev, &ecmd)) {
690 if (ecmd.supported & SUPPORTED_10baseT_Half)
691 desc->features |= OFPPF_10MB_HD;
692 if (ecmd.supported & SUPPORTED_10baseT_Full)
693 desc->features |= OFPPF_10MB_FD;
694 if (ecmd.supported & SUPPORTED_100baseT_Half)
695 desc->features |= OFPPF_100MB_HD;
696 if (ecmd.supported & SUPPORTED_100baseT_Full)
697 desc->features |= OFPPF_100MB_FD;
698 if (ecmd.supported & SUPPORTED_1000baseT_Half)
699 desc->features |= OFPPF_1GB_HD;
700 if (ecmd.supported & SUPPORTED_1000baseT_Full)
701 desc->features |= OFPPF_1GB_FD;
702 /* 10Gbps half-duplex doesn't exist... */
703 if (ecmd.supported & SUPPORTED_10000baseT_Full)
704 desc->features |= OFPPF_10GB_FD;
706 desc->features = htonl(desc->features);
707 desc->speed = htonl(ecmd.speed);
714 fill_features_reply(struct datapath *dp, struct ofp_switch_features *ofr)
716 struct net_bridge_port *p;
719 ofr->datapath_id = cpu_to_be64(dp->id);
721 ofr->n_exact = htonl(2 * TABLE_HASH_MAX_FLOWS);
722 ofr->n_compression = 0; /* Not supported */
723 ofr->n_general = htonl(TABLE_LINEAR_MAX_FLOWS);
724 ofr->buffer_mb = htonl(UINT32_MAX);
725 ofr->n_buffers = htonl(N_PKT_BUFFERS);
726 ofr->capabilities = htonl(OFP_SUPPORTED_CAPABILITIES);
727 ofr->actions = htonl(OFP_SUPPORTED_ACTIONS);
729 list_for_each_entry_rcu (p, &dp->port_list, node) {
730 fill_port_desc(p, &ofr->ports[port_count]);
738 dp_send_features_reply(struct datapath *dp, const struct sender *sender)
741 struct ofp_switch_features *ofr;
742 size_t ofr_len, port_max_len;
746 port_max_len = sizeof(struct ofp_phy_port) * OFPP_MAX;
747 ofr = alloc_openflow_skb(dp, sizeof(*ofr) + port_max_len,
748 OFPT_FEATURES_REPLY, sender, &skb);
753 port_count = fill_features_reply(dp, ofr);
756 ofr_len = sizeof(*ofr) + (sizeof(struct ofp_phy_port) * port_count);
757 resize_openflow_skb(skb, &ofr->header, ofr_len);
758 return send_openflow_skb(skb, sender);
762 dp_send_config_reply(struct datapath *dp, const struct sender *sender)
765 struct ofp_switch_config *osc;
767 osc = alloc_openflow_skb(dp, sizeof *osc, OFPT_GET_CONFIG_REPLY, sender,
772 osc->flags = htons(dp->flags);
773 osc->miss_send_len = htons(dp->miss_send_len);
775 return send_openflow_skb(skb, sender);
779 dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp)
781 int port_no = ntohs(opp->port_no);
782 struct net_bridge_port *p = (port_no < OFPP_MAX ? dp->ports[port_no]
783 : port_no == OFPP_LOCAL ? dp->local_port
785 /* Make sure the port id hasn't changed since this was sent */
786 if (!p || memcmp(opp->hw_addr, p->dev->dev_addr, ETH_ALEN))
788 p->flags = htonl(opp->flags);
794 send_port_status(struct net_bridge_port *p, uint8_t status)
797 struct ofp_port_status *ops;
799 ops = alloc_openflow_skb(p->dp, sizeof *ops, OFPT_PORT_STATUS, NULL,
803 ops->reason = status;
804 memset(ops->pad, 0, sizeof ops->pad);
805 fill_port_desc(p, &ops->desc);
807 return send_openflow_skb(skb, NULL);
811 dp_send_flow_expired(struct datapath *dp, struct sw_flow *flow,
812 enum ofp_flow_expired_reason reason)
815 struct ofp_flow_expired *ofe;
817 if (!(dp->flags & OFPC_SEND_FLOW_EXP))
820 ofe = alloc_openflow_skb(dp, sizeof *ofe, OFPT_FLOW_EXPIRED, 0, &skb);
824 flow_fill_match(&ofe->match, &flow->key);
826 ofe->priority = htons(flow->priority);
827 ofe->reason = reason;
828 memset(ofe->pad, 0, sizeof ofe->pad);
830 ofe->duration = htonl((jiffies - flow->init_time) / HZ);
831 memset(ofe->pad2, 0, sizeof ofe->pad2);
832 ofe->packet_count = cpu_to_be64(flow->packet_count);
833 ofe->byte_count = cpu_to_be64(flow->byte_count);
835 return send_openflow_skb(skb, NULL);
837 EXPORT_SYMBOL(dp_send_flow_expired);
840 dp_send_error_msg(struct datapath *dp, const struct sender *sender,
841 uint16_t type, uint16_t code, const uint8_t *data, size_t len)
844 struct ofp_error_msg *oem;
847 oem = alloc_openflow_skb(dp, sizeof(*oem)+len, OFPT_ERROR_MSG,
852 oem->type = htons(type);
853 oem->code = htons(code);
854 memcpy(oem->data, data, len);
856 return send_openflow_skb(skb, sender);
860 dp_send_echo_reply(struct datapath *dp, const struct sender *sender,
861 const struct ofp_header *rq)
864 struct ofp_header *reply;
866 reply = alloc_openflow_skb(dp, ntohs(rq->length), OFPT_ECHO_REPLY,
871 memcpy(reply + 1, rq + 1, ntohs(rq->length) - sizeof *rq);
872 return send_openflow_skb(skb, sender);
875 /* Generic Netlink interface.
877 * See netlink(7) for an introduction to netlink. See
878 * http://linux-net.osdl.org/index.php/Netlink for more information and
879 * pointers on how to work with netlink and Generic Netlink in the kernel and
882 static struct genl_family dp_genl_family = {
883 .id = GENL_ID_GENERATE,
885 .name = DP_GENL_FAMILY_NAME,
887 .maxattr = DP_GENL_A_MAX,
890 /* Attribute policy: what each attribute may contain. */
891 static struct nla_policy dp_genl_policy[DP_GENL_A_MAX + 1] = {
892 [DP_GENL_A_DP_IDX] = { .type = NLA_U32 },
893 [DP_GENL_A_MC_GROUP] = { .type = NLA_U32 },
894 [DP_GENL_A_PORTNAME] = { .type = NLA_STRING }
897 static int dp_genl_add(struct sk_buff *skb, struct genl_info *info)
899 if (!info->attrs[DP_GENL_A_DP_IDX])
902 return new_dp(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
905 static struct genl_ops dp_genl_ops_add_dp = {
906 .cmd = DP_GENL_C_ADD_DP,
907 .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
908 .policy = dp_genl_policy,
913 struct datapath *dp_get(int dp_idx)
915 if (dp_idx < 0 || dp_idx > DP_MAX)
917 return rcu_dereference(dps[dp_idx]);
920 static int dp_genl_del(struct sk_buff *skb, struct genl_info *info)
925 if (!info->attrs[DP_GENL_A_DP_IDX])
928 dp = dp_get(nla_get_u32((info->attrs[DP_GENL_A_DP_IDX])));
938 static struct genl_ops dp_genl_ops_del_dp = {
939 .cmd = DP_GENL_C_DEL_DP,
940 .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
941 .policy = dp_genl_policy,
946 /* Queries a datapath for related information. Currently the only relevant
947 * information is the datapath's multicast group ID. Really we want one
948 * multicast group per datapath, but because of locking issues[*] we can't
949 * easily get one. Thus, every datapath will currently return the same
950 * global multicast group ID, but in the future it would be nice to fix that.
952 * [*] dp_genl_add, to add a new datapath, is called under the genl_lock
953 * mutex, and genl_register_mc_group, called to acquire a new multicast
954 * group ID, also acquires genl_lock, thus deadlock.
956 static int dp_genl_query(struct sk_buff *skb, struct genl_info *info)
959 struct sk_buff *ans_skb = NULL;
963 if (!info->attrs[DP_GENL_A_DP_IDX])
967 dp_idx = nla_get_u32((info->attrs[DP_GENL_A_DP_IDX]));
973 ans_skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
978 data = genlmsg_put_reply(ans_skb, info, &dp_genl_family,
979 0, DP_GENL_C_QUERY_DP);
984 NLA_PUT_U32(ans_skb, DP_GENL_A_DP_IDX, dp_idx);
985 NLA_PUT_U32(ans_skb, DP_GENL_A_MC_GROUP, mc_group.id);
987 genlmsg_end(ans_skb, data);
988 err = genlmsg_reply(ans_skb, info);
1000 static struct genl_ops dp_genl_ops_query_dp = {
1001 .cmd = DP_GENL_C_QUERY_DP,
1002 .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1003 .policy = dp_genl_policy,
1004 .doit = dp_genl_query,
1008 static int dp_genl_add_del_port(struct sk_buff *skb, struct genl_info *info)
1010 struct datapath *dp;
1011 struct net_device *port;
1014 if (!info->attrs[DP_GENL_A_DP_IDX] || !info->attrs[DP_GENL_A_PORTNAME])
1018 dp = dp_get(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
1024 /* Get interface to add/remove. */
1025 port = dev_get_by_name(&init_net,
1026 nla_data(info->attrs[DP_GENL_A_PORTNAME]));
1032 /* Execute operation. */
1033 if (info->genlhdr->cmd == DP_GENL_C_ADD_PORT)
1034 err = add_switch_port(dp, port);
1036 if (port->br_port == NULL || port->br_port->dp != dp) {
1040 err = del_switch_port(port->br_port);
1049 static struct genl_ops dp_genl_ops_add_port = {
1050 .cmd = DP_GENL_C_ADD_PORT,
1051 .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1052 .policy = dp_genl_policy,
1053 .doit = dp_genl_add_del_port,
1057 static struct genl_ops dp_genl_ops_del_port = {
1058 .cmd = DP_GENL_C_DEL_PORT,
1059 .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1060 .policy = dp_genl_policy,
1061 .doit = dp_genl_add_del_port,
1065 static int dp_genl_openflow(struct sk_buff *skb, struct genl_info *info)
1067 struct nlattr *va = info->attrs[DP_GENL_A_OPENFLOW];
1068 struct datapath *dp;
1069 struct ofp_header *oh;
1070 struct sender sender;
1073 if (!info->attrs[DP_GENL_A_DP_IDX] || !va)
1076 dp = dp_get(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
1080 if (nla_len(va) < sizeof(struct ofp_header))
1084 sender.xid = oh->xid;
1085 sender.pid = info->snd_pid;
1086 sender.seq = info->snd_seq;
1088 mutex_lock(&dp_mutex);
1089 err = fwd_control_input(dp->chain, &sender,
1090 nla_data(va), nla_len(va));
1091 mutex_unlock(&dp_mutex);
1095 static struct nla_policy dp_genl_openflow_policy[DP_GENL_A_MAX + 1] = {
1096 [DP_GENL_A_DP_IDX] = { .type = NLA_U32 },
1099 static int version_stats_dump(struct datapath *dp, void *state,
1100 void *body, int *body_len)
1102 struct ofp_version_stats *ovs = body;
1103 int n_bytes = sizeof *ovs;
1105 if (n_bytes > *body_len) {
1108 *body_len = n_bytes;
1110 strncpy(ovs->mfr_desc, mfr_desc, sizeof ovs->mfr_desc);
1111 strncpy(ovs->hw_desc, hw_desc, sizeof ovs->hw_desc);
1112 strncpy(ovs->sw_desc, sw_desc, sizeof ovs->sw_desc);
1117 struct flow_stats_state {
1119 struct sw_table_position position;
1120 const struct ofp_flow_stats_request *rq;
1123 int bytes_used, bytes_allocated;
1126 static int flow_stats_init(struct datapath *dp, const void *body, int body_len,
1129 const struct ofp_flow_stats_request *fsr = body;
1130 struct flow_stats_state *s = kmalloc(sizeof *s, GFP_ATOMIC);
1133 s->table_idx = fsr->table_id == 0xff ? 0 : fsr->table_id;
1134 memset(&s->position, 0, sizeof s->position);
1140 static int flow_stats_dump_callback(struct sw_flow *flow, void *private)
1142 struct flow_stats_state *s = private;
1143 struct ofp_flow_stats *ofs;
1147 actions_length = sizeof *ofs->actions * flow->n_actions;
1148 length = sizeof *ofs + sizeof *ofs->actions * flow->n_actions;
1149 if (length + s->bytes_used > s->bytes_allocated)
1152 ofs = s->body + s->bytes_used;
1153 ofs->length = htons(length);
1154 ofs->table_id = s->table_idx;
1156 ofs->match.wildcards = htonl(flow->key.wildcards);
1157 ofs->match.in_port = flow->key.in_port;
1158 memcpy(ofs->match.dl_src, flow->key.dl_src, ETH_ALEN);
1159 memcpy(ofs->match.dl_dst, flow->key.dl_dst, ETH_ALEN);
1160 ofs->match.dl_vlan = flow->key.dl_vlan;
1161 ofs->match.dl_type = flow->key.dl_type;
1162 ofs->match.nw_src = flow->key.nw_src;
1163 ofs->match.nw_dst = flow->key.nw_dst;
1164 ofs->match.nw_proto = flow->key.nw_proto;
1166 ofs->match.tp_src = flow->key.tp_src;
1167 ofs->match.tp_dst = flow->key.tp_dst;
1168 ofs->duration = htonl((jiffies - flow->init_time) / HZ);
1169 ofs->priority = htons(flow->priority);
1170 ofs->idle_timeout = htons(flow->idle_timeout);
1171 ofs->hard_timeout = htons(flow->hard_timeout);
1172 memset(ofs->pad2, 0, sizeof ofs->pad2);
1173 ofs->packet_count = cpu_to_be64(flow->packet_count);
1174 ofs->byte_count = cpu_to_be64(flow->byte_count);
1175 memcpy(ofs->actions, flow->actions, actions_length);
1177 s->bytes_used += length;
1181 static int flow_stats_dump(struct datapath *dp, void *state,
1182 void *body, int *body_len)
1184 struct flow_stats_state *s = state;
1185 struct sw_flow_key match_key;
1189 s->bytes_allocated = *body_len;
1192 flow_extract_match(&match_key, &s->rq->match);
1193 while (s->table_idx < dp->chain->n_tables
1194 && (s->rq->table_id == 0xff || s->rq->table_id == s->table_idx))
1196 struct sw_table *table = dp->chain->tables[s->table_idx];
1198 error = table->iterate(table, &match_key, &s->position,
1199 flow_stats_dump_callback, s);
1204 memset(&s->position, 0, sizeof s->position);
1206 *body_len = s->bytes_used;
1208 /* If error is 0, we're done.
1209 * Otherwise, if some bytes were used, there are more flows to come.
1210 * Otherwise, we were not able to fit even a single flow in the body,
1211 * which indicates that we have a single flow with too many actions to
1212 * fit. We won't ever make any progress at that rate, so give up. */
1213 return !error ? 0 : s->bytes_used ? 1 : -ENOMEM;
1216 static void flow_stats_done(void *state)
1221 static int aggregate_stats_init(struct datapath *dp,
1222 const void *body, int body_len,
1225 *state = (void *)body;
1229 static int aggregate_stats_dump_callback(struct sw_flow *flow, void *private)
1231 struct ofp_aggregate_stats_reply *rpy = private;
1232 rpy->packet_count += flow->packet_count;
1233 rpy->byte_count += flow->byte_count;
1238 static int aggregate_stats_dump(struct datapath *dp, void *state,
1239 void *body, int *body_len)
1241 struct ofp_aggregate_stats_request *rq = state;
1242 struct ofp_aggregate_stats_reply *rpy;
1243 struct sw_table_position position;
1244 struct sw_flow_key match_key;
1247 if (*body_len < sizeof *rpy)
1250 *body_len = sizeof *rpy;
1252 memset(rpy, 0, sizeof *rpy);
1254 flow_extract_match(&match_key, &rq->match);
1255 table_idx = rq->table_id == 0xff ? 0 : rq->table_id;
1256 memset(&position, 0, sizeof position);
1257 while (table_idx < dp->chain->n_tables
1258 && (rq->table_id == 0xff || rq->table_id == table_idx))
1260 struct sw_table *table = dp->chain->tables[table_idx];
1263 error = table->iterate(table, &match_key, &position,
1264 aggregate_stats_dump_callback, rpy);
1269 memset(&position, 0, sizeof position);
1272 rpy->packet_count = cpu_to_be64(rpy->packet_count);
1273 rpy->byte_count = cpu_to_be64(rpy->byte_count);
1274 rpy->flow_count = htonl(rpy->flow_count);
1278 static int table_stats_dump(struct datapath *dp, void *state,
1279 void *body, int *body_len)
1281 struct ofp_table_stats *ots;
1282 int n_bytes = dp->chain->n_tables * sizeof *ots;
1284 if (n_bytes > *body_len)
1286 *body_len = n_bytes;
1287 for (i = 0, ots = body; i < dp->chain->n_tables; i++, ots++) {
1288 struct sw_table_stats stats;
1289 dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
1290 strncpy(ots->name, stats.name, sizeof ots->name);
1292 memset(ots->pad, 0, sizeof ots->pad);
1293 ots->max_entries = htonl(stats.max_flows);
1294 ots->active_count = htonl(stats.n_flows);
1295 ots->matched_count = cpu_to_be64(stats.n_matched);
1300 struct port_stats_state {
1304 static int port_stats_init(struct datapath *dp, const void *body, int body_len,
1307 struct port_stats_state *s = kmalloc(sizeof *s, GFP_ATOMIC);
1315 static int port_stats_dump(struct datapath *dp, void *state,
1316 void *body, int *body_len)
1318 struct port_stats_state *s = state;
1319 struct ofp_port_stats *ops;
1320 int n_ports, max_ports;
1323 max_ports = *body_len / sizeof *ops;
1329 for (i = s->port; i < OFPP_MAX && n_ports < max_ports; i++) {
1330 struct net_bridge_port *p = dp->ports[i];
1331 struct net_device_stats *stats;
1334 stats = p->dev->get_stats(p->dev);
1335 ops->port_no = htons(p->port_no);
1336 memset(ops->pad, 0, sizeof ops->pad);
1337 ops->rx_packets = cpu_to_be64(stats->rx_packets);
1338 ops->tx_packets = cpu_to_be64(stats->tx_packets);
1339 ops->rx_bytes = cpu_to_be64(stats->rx_bytes);
1340 ops->tx_bytes = cpu_to_be64(stats->tx_bytes);
1341 ops->rx_dropped = cpu_to_be64(stats->rx_dropped);
1342 ops->tx_dropped = cpu_to_be64(stats->tx_dropped);
1343 ops->rx_errors = cpu_to_be64(stats->rx_errors);
1344 ops->tx_errors = cpu_to_be64(stats->tx_errors);
1345 ops->rx_frame_err = cpu_to_be64(stats->rx_frame_errors);
1346 ops->rx_over_err = cpu_to_be64(stats->rx_over_errors);
1347 ops->rx_crc_err = cpu_to_be64(stats->rx_crc_errors);
1348 ops->collisions = cpu_to_be64(stats->collisions);
1353 *body_len = n_ports * sizeof *ops;
1354 return n_ports >= max_ports;
1357 static void port_stats_done(void *state)
1363 /* Minimum and maximum acceptable number of bytes in body member of
1364 * struct ofp_stats_request. */
1365 size_t min_body, max_body;
1367 /* Prepares to dump some kind of statistics on 'dp'. 'body' and
1368 * 'body_len' are the 'body' member of the struct ofp_stats_request.
1369 * Returns zero if successful, otherwise a negative error code.
1370 * May initialize '*state' to state information. May be null if no
1371 * initialization is required.*/
1372 int (*init)(struct datapath *dp, const void *body, int body_len,
1375 /* Dumps statistics for 'dp' into the '*body_len' bytes at 'body', and
1376 * modifies '*body_len' to reflect the number of bytes actually used.
1377 * ('body' will be transmitted as the 'body' member of struct
1378 * ofp_stats_reply.) */
1379 int (*dump)(struct datapath *dp, void *state,
1380 void *body, int *body_len);
1382 /* Cleans any state created by the init or dump functions. May be null
1383 * if no cleanup is required. */
1384 void (*done)(void *state);
1387 static const struct stats_type stats[] = {
1396 sizeof(struct ofp_flow_stats_request),
1397 sizeof(struct ofp_flow_stats_request),
1402 [OFPST_AGGREGATE] = {
1403 sizeof(struct ofp_aggregate_stats_request),
1404 sizeof(struct ofp_aggregate_stats_request),
1405 aggregate_stats_init,
1406 aggregate_stats_dump,
1426 dp_genl_openflow_dumpit(struct sk_buff *skb, struct netlink_callback *cb)
1428 struct datapath *dp;
1429 struct sender sender;
1430 const struct stats_type *s;
1431 struct ofp_stats_reply *osr;
1433 int max_openflow_len, body_len;
1437 /* Set up the cleanup function for this dump. Linux 2.6.20 and later
1438 * support setting up cleanup functions via the .doneit member of
1439 * struct genl_ops. This kluge supports earlier versions also. */
1440 cb->done = dp_genl_openflow_done;
1443 struct nlattr *attrs[DP_GENL_A_MAX + 1];
1444 struct ofp_stats_request *rq;
1446 size_t len, body_len;
1449 err = nlmsg_parse(cb->nlh, GENL_HDRLEN, attrs, DP_GENL_A_MAX,
1450 dp_genl_openflow_policy);
1454 if (!attrs[DP_GENL_A_DP_IDX])
1456 dp_idx = nla_get_u16(attrs[DP_GENL_A_DP_IDX]);
1457 dp = dp_get(dp_idx);
1461 va = attrs[DP_GENL_A_OPENFLOW];
1463 if (!va || len < sizeof *rq)
1467 type = ntohs(rq->type);
1468 if (rq->header.version != OFP_VERSION
1469 || rq->header.type != OFPT_STATS_REQUEST
1470 || ntohs(rq->header.length) != len
1471 || type >= ARRAY_SIZE(stats)
1472 || !stats[type].dump)
1476 body_len = len - offsetof(struct ofp_stats_request, body);
1477 if (body_len < s->min_body || body_len > s->max_body)
1481 cb->args[1] = dp_idx;
1483 cb->args[3] = rq->header.xid;
1486 err = s->init(dp, rq->body, body_len, &state);
1489 cb->args[4] = (long) state;
1491 } else if (cb->args[0] == 1) {
1492 dp_idx = cb->args[1];
1493 s = &stats[cb->args[2]];
1495 dp = dp_get(dp_idx);
1502 sender.xid = cb->args[3];
1503 sender.pid = NETLINK_CB(cb->skb).pid;
1504 sender.seq = cb->nlh->nlmsg_seq;
1506 osr = put_openflow_headers(dp, skb, OFPT_STATS_REPLY, &sender,
1509 return PTR_ERR(osr);
1510 osr->type = htons(s - stats);
1512 resize_openflow_skb(skb, &osr->header, max_openflow_len);
1514 body_len = max_openflow_len - offsetof(struct ofp_stats_reply, body);
1516 err = s->dump(dp, (void *) cb->args[4], body, &body_len);
1521 osr->flags = ntohs(OFPSF_REPLY_MORE);
1522 resize_openflow_skb(skb, &osr->header,
1523 (offsetof(struct ofp_stats_reply, body)
1532 dp_genl_openflow_done(struct netlink_callback *cb)
1535 const struct stats_type *s = &stats[cb->args[2]];
1537 s->done((void *) cb->args[4]);
1542 static struct genl_ops dp_genl_ops_openflow = {
1543 .cmd = DP_GENL_C_OPENFLOW,
1544 .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1545 .policy = dp_genl_openflow_policy,
1546 .doit = dp_genl_openflow,
1547 .dumpit = dp_genl_openflow_dumpit,
1550 static struct genl_ops *dp_genl_all_ops[] = {
1551 /* Keep this operation first. Generic Netlink dispatching
1552 * looks up operations with linear search, so we want it at the
1554 &dp_genl_ops_openflow,
1556 &dp_genl_ops_add_dp,
1557 &dp_genl_ops_del_dp,
1558 &dp_genl_ops_query_dp,
1559 &dp_genl_ops_add_port,
1560 &dp_genl_ops_del_port,
1563 static int dp_init_netlink(void)
1568 err = genl_register_family(&dp_genl_family);
1572 for (i = 0; i < ARRAY_SIZE(dp_genl_all_ops); i++) {
1573 err = genl_register_ops(&dp_genl_family, dp_genl_all_ops[i]);
1575 goto err_unregister;
1578 strcpy(mc_group.name, "openflow");
1579 err = genl_register_mc_group(&dp_genl_family, &mc_group);
1581 goto err_unregister;
1586 genl_unregister_family(&dp_genl_family);
1590 static void dp_uninit_netlink(void)
1592 genl_unregister_family(&dp_genl_family);
1595 #define DRV_NAME "openflow"
1596 #define DRV_VERSION VERSION
1597 #define DRV_DESCRIPTION "OpenFlow switching datapath implementation"
1598 #define DRV_COPYRIGHT "Copyright (c) 2007, 2008 The Board of Trustees of The Leland Stanford Junior University"
1601 static int __init dp_init(void)
1605 printk(KERN_INFO DRV_NAME ": " DRV_DESCRIPTION "\n");
1606 printk(KERN_INFO DRV_NAME ": " VERSION" built on "__DATE__" "__TIME__"\n");
1607 printk(KERN_INFO DRV_NAME ": " DRV_COPYRIGHT "\n");
1613 err = dp_init_netlink();
1615 goto error_flow_exit;
1617 /* Hook into callback used by the bridge to intercept packets.
1618 * Parasites we are. */
1619 if (br_handle_frame_hook)
1620 printk("openflow: hijacking bridge hook\n");
1621 br_handle_frame_hook = dp_frame_hook;
1628 printk(KERN_EMERG "openflow: failed to install!");
1632 static void dp_cleanup(void)
1635 dp_uninit_netlink();
1637 br_handle_frame_hook = NULL;
1640 module_init(dp_init);
1641 module_exit(dp_cleanup);
1643 MODULE_DESCRIPTION(DRV_DESCRIPTION);
1644 MODULE_AUTHOR(DRV_COPYRIGHT);
1645 MODULE_LICENSE("GPL");