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>
32 #include "openflow-netlink.h"
39 #include "datapath_t.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
70 * It is safe to access the datapath and net_bridge_port structures with just
71 * the dp_mutex, but to access the chain you need to take the rcu_read_lock
72 * also (because dp_mutex doesn't prevent flows from being destroyed).
74 static struct datapath *dps[DP_MAX];
75 static DEFINE_MUTEX(dp_mutex);
77 static int dp_maint_func(void *data);
78 static int send_port_status(struct net_bridge_port *p, uint8_t status);
79 static int dp_genl_openflow_done(struct netlink_callback *);
80 static struct net_bridge_port *new_nbp(struct datapath *,
81 struct net_device *, int port_no);
82 static int del_switch_port(struct net_bridge_port *);
84 /* nla_shrink - reduce amount of space reserved by nla_reserve
85 * @skb: socket buffer from which to recover room
86 * @nla: netlink attribute to adjust
87 * @len: new length of attribute payload
89 * Reduces amount of space reserved by a call to nla_reserve.
91 * No other attributes may be added between calling nla_reserve and this
92 * function, since it will create a hole in the message.
94 void nla_shrink(struct sk_buff *skb, struct nlattr *nla, int len)
96 int delta = nla_total_size(len) - nla_total_size(nla_len(nla));
100 nla->nla_len = nla_attr_size(len);
103 /* Puts a set of openflow headers for a message of the given 'type' into 'skb'.
104 * If 'sender' is nonnull, then it is used as the message's destination. 'dp'
105 * must specify the datapath to use.
107 * '*max_openflow_len' receives the maximum number of bytes that are available
108 * for the embedded OpenFlow message. The caller must call
109 * resize_openflow_skb() to set the actual size of the message to this number
112 * Returns the openflow header if successful, otherwise (if 'skb' is too small)
115 put_openflow_headers(struct datapath *dp, struct sk_buff *skb, uint8_t type,
116 const struct sender *sender, int *max_openflow_len)
118 struct ofp_header *oh;
122 /* Assemble the Generic Netlink wrapper. */
123 if (!genlmsg_put(skb,
124 sender ? sender->pid : 0,
125 sender ? sender->seq : 0,
126 &dp_genl_family, 0, DP_GENL_C_OPENFLOW))
127 return ERR_PTR(-ENOBUFS);
128 if (nla_put_u32(skb, DP_GENL_A_DP_IDX, dp->dp_idx) < 0)
129 return ERR_PTR(-ENOBUFS);
130 openflow_len = (skb_tailroom(skb) - NLA_HDRLEN) & ~(NLA_ALIGNTO - 1);
131 if (openflow_len < sizeof *oh)
132 return ERR_PTR(-ENOBUFS);
133 *max_openflow_len = openflow_len;
134 attr = nla_reserve(skb, DP_GENL_A_OPENFLOW, openflow_len);
137 /* Fill in the header. The caller is responsible for the length. */
139 oh->version = OFP_VERSION;
141 oh->xid = sender ? sender->xid : 0;
146 /* Resizes OpenFlow header 'oh', which must be at the tail end of 'skb', to new
147 * length 'new_length' (in bytes), adjusting pointers and size values as
150 resize_openflow_skb(struct sk_buff *skb,
151 struct ofp_header *oh, size_t new_length)
153 struct nlattr *attr = ((void *) oh) - NLA_HDRLEN;
154 nla_shrink(skb, attr, new_length);
155 oh->length = htons(new_length);
156 nlmsg_end(skb, (struct nlmsghdr *) skb->data);
159 /* Allocates a new skb to contain an OpenFlow message 'openflow_len' bytes in
160 * length. Returns a null pointer if memory is unavailable, otherwise returns
161 * the OpenFlow header and stores a pointer to the skb in '*pskb'.
163 * 'type' is the OpenFlow message type. If 'sender' is nonnull, then it is
164 * used as the message's destination. 'dp' must specify the datapath to
167 alloc_openflow_skb(struct datapath *dp, size_t openflow_len, uint8_t type,
168 const struct sender *sender, struct sk_buff **pskb)
170 struct ofp_header *oh;
173 int max_openflow_len;
175 if ((openflow_len + sizeof(struct ofp_header)) > UINT16_MAX) {
177 printk("alloc_openflow_skb: openflow message too large: %zu\n",
182 genl_len = nlmsg_total_size(GENL_HDRLEN + dp_genl_family.hdrsize);
183 genl_len += nla_total_size(sizeof(uint32_t)); /* DP_GENL_A_DP_IDX */
184 genl_len += nla_total_size(openflow_len); /* DP_GENL_A_OPENFLOW */
185 skb = *pskb = genlmsg_new(genl_len, GFP_ATOMIC);
188 printk("alloc_openflow_skb: genlmsg_new failed\n");
192 oh = put_openflow_headers(dp, skb, type, sender, &max_openflow_len);
193 BUG_ON(!oh || IS_ERR(oh));
194 resize_openflow_skb(skb, oh, openflow_len);
199 /* Sends 'skb' to 'sender' if it is nonnull, otherwise multicasts 'skb' to all
202 send_openflow_skb(struct sk_buff *skb, const struct sender *sender)
205 ? genlmsg_unicast(skb, sender->pid)
206 : genlmsg_multicast(skb, 0, mc_group.id, GFP_ATOMIC));
209 /* Generates a unique datapath id. It incorporates the datapath index
210 * and a hardware address, if available. If not, it generates a random
214 uint64_t gen_datapath_id(uint16_t dp_idx)
218 struct net_device *dev;
220 /* The top 16 bits are used to identify the datapath. The lower 48 bits
221 * use an interface address. */
222 id = (uint64_t)dp_idx << 48;
223 if ((dev = dev_get_by_name(&init_net, "ctl0"))
224 || (dev = dev_get_by_name(&init_net, "eth0"))) {
225 for (i=0; i<ETH_ALEN; i++) {
226 id |= (uint64_t)dev->dev_addr[i] << (8*(ETH_ALEN-1 - i));
230 /* Randomly choose the lower 48 bits if we cannot find an
231 * address and mark the most significant bit to indicate that
232 * this was randomly generated. */
233 uint8_t rand[ETH_ALEN];
234 get_random_bytes(rand, ETH_ALEN);
235 id |= (uint64_t)1 << 63;
236 for (i=0; i<ETH_ALEN; i++) {
237 id |= (uint64_t)rand[i] << (8*(ETH_ALEN-1 - i));
244 /* Creates a new datapath numbered 'dp_idx'. Returns 0 for success or a
245 * negative error code.
247 * Not called with any locks. */
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 mutex_lock(&dp_mutex);
260 dp = rcu_dereference(dps[dp_idx]);
267 dp = kzalloc(sizeof *dp, GFP_KERNEL);
271 /* Setup our "of" device */
272 err = dp_dev_setup(dp);
277 dp->id = gen_datapath_id(dp_idx);
278 dp->chain = chain_create(dp);
279 if (dp->chain == NULL)
280 goto err_destroy_dp_dev;
281 INIT_LIST_HEAD(&dp->port_list);
283 dp->local_port = new_nbp(dp, dp->netdev, OFPP_LOCAL);
284 if (IS_ERR(dp->local_port)) {
285 err = PTR_ERR(dp->local_port);
286 goto err_destroy_local_port;
290 dp->miss_send_len = OFP_DEFAULT_MISS_SEND_LEN;
292 dp->dp_task = kthread_run(dp_maint_func, dp, "dp%d", dp_idx);
293 if (IS_ERR(dp->dp_task))
294 goto err_destroy_chain;
296 rcu_assign_pointer(dps[dp_idx], dp);
297 mutex_unlock(&dp_mutex);
301 err_destroy_local_port:
302 del_switch_port(dp->local_port);
304 chain_destroy(dp->chain);
310 mutex_unlock(&dp_mutex);
311 module_put(THIS_MODULE);
315 /* Find and return a free port number under 'dp'. Called under dp_mutex. */
316 static int find_portno(struct datapath *dp)
319 for (i = 0; i < OFPP_MAX; i++)
320 if (dp->ports[i] == NULL)
325 static struct net_bridge_port *new_nbp(struct datapath *dp,
326 struct net_device *dev, int port_no)
328 struct net_bridge_port *p;
330 if (dev->br_port != NULL)
331 return ERR_PTR(-EBUSY);
333 p = kzalloc(sizeof(*p), GFP_KERNEL);
335 return ERR_PTR(-ENOMEM);
338 dev_set_promiscuity(dev, 1);
343 p->port_no = port_no;
344 if (port_no != OFPP_LOCAL)
345 rcu_assign_pointer(dev->br_port, p);
346 if (port_no < OFPP_MAX)
347 rcu_assign_pointer(dp->ports[port_no], p);
348 list_add_rcu(&p->node, &dp->port_list);
353 /* Called with dp_mutex. */
354 int add_switch_port(struct datapath *dp, struct net_device *dev)
356 struct net_bridge_port *p;
359 if (dev->flags & IFF_LOOPBACK || dev->type != ARPHRD_ETHER
363 port_no = find_portno(dp);
367 p = new_nbp(dp, dev, port_no);
371 /* Notify the ctlpath that this port has been added */
372 send_port_status(p, OFPPR_ADD);
377 /* Delete 'p' from switch.
378 * Called with dp_mutex. */
379 static int del_switch_port(struct net_bridge_port *p)
381 /* First drop references to device. */
383 dev_set_promiscuity(p->dev, -1);
385 list_del_rcu(&p->node);
386 if (p->port_no != OFPP_LOCAL)
387 rcu_assign_pointer(p->dp->ports[p->port_no], NULL);
388 rcu_assign_pointer(p->dev->br_port, NULL);
390 /* Then wait until no one is still using it, and destroy it. */
393 /* Notify the ctlpath that this port no longer exists */
394 send_port_status(p, OFPPR_DELETE);
402 /* Called with dp_mutex. */
403 static void del_dp(struct datapath *dp)
405 struct net_bridge_port *p, *n;
407 kthread_stop(dp->dp_task);
409 /* Drop references to DP. */
410 list_for_each_entry_safe (p, n, &dp->port_list, node)
412 rcu_assign_pointer(dps[dp->dp_idx], NULL);
414 /* Kill off local_port dev references from buffered packets that have
415 * associated dst entries. */
419 /* Destroy dp->netdev. (Must follow deleting switch ports since
420 * dp->local_port has a reference to it.) */
423 /* Wait until no longer in use, then destroy it. */
425 chain_destroy(dp->chain);
427 module_put(THIS_MODULE);
430 static int dp_maint_func(void *data)
432 struct datapath *dp = (struct datapath *) data;
434 while (!kthread_should_stop()) {
435 chain_timeout(dp->chain);
436 msleep_interruptible(MAINT_SLEEP_MSECS);
443 do_port_input(struct net_bridge_port *p, struct sk_buff *skb)
445 /* Push the Ethernet header back on. */
446 skb_push(skb, ETH_HLEN);
447 fwd_port_input(p->dp->chain, skb, p->port_no);
451 * Used as br_handle_frame_hook. (Cannot run bridge at the same time, even on
452 * different set of devices!)
454 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
455 /* Called with rcu_read_lock. */
456 static struct sk_buff *dp_frame_hook(struct net_bridge_port *p,
459 do_port_input(p, skb);
462 #elif LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
463 static int dp_frame_hook(struct net_bridge_port *p, struct sk_buff **pskb)
465 do_port_input(p, *pskb);
469 /* NB: This has only been tested on 2.4.35 */
471 /* Called without any locks (?) */
472 static void dp_frame_hook(struct sk_buff *skb)
474 struct net_bridge_port *p = skb->dev->br_port;
477 do_port_input(p, skb);
484 /* Forwarding output path.
485 * Based on net/bridge/br_forward.c. */
487 static inline unsigned packet_length(const struct sk_buff *skb)
489 int length = skb->len - ETH_HLEN;
490 if (skb->protocol == htons(ETH_P_8021Q))
495 /* Send packets out all the ports except the originating one. If the
496 * "flood" argument is set, only send along the minimum spanning tree.
499 output_all(struct datapath *dp, struct sk_buff *skb, int flood)
501 u32 disable = flood ? BRIDGE_PORT_NO_FLOOD : 0;
502 struct net_bridge_port *p;
505 list_for_each_entry_rcu (p, &dp->port_list, node) {
506 if (skb->dev == p->dev || p->flags & disable)
508 if (prev_port != -1) {
509 struct sk_buff *clone = skb_clone(skb, GFP_ATOMIC);
514 dp_output_port(dp, clone, prev_port);
516 prev_port = p->port_no;
519 dp_output_port(dp, skb, prev_port);
526 /* Marks 'skb' as having originated from 'in_port' in 'dp'.
527 FIXME: how are devices reference counted? */
528 int dp_set_origin(struct datapath *dp, uint16_t in_port,
531 struct net_bridge_port *p = (in_port < OFPP_MAX ? dp->ports[in_port]
532 : in_port == OFPP_LOCAL ? dp->local_port
541 /* Takes ownership of 'skb' and transmits it to 'out_port' on 'dp'.
543 int dp_output_port(struct datapath *dp, struct sk_buff *skb, int out_port)
546 if (out_port == OFPP_FLOOD)
547 return output_all(dp, skb, 1);
548 else if (out_port == OFPP_ALL)
549 return output_all(dp, skb, 0);
550 else if (out_port == OFPP_CONTROLLER)
551 return dp_output_control(dp, skb, fwd_save_skb(skb), 0,
553 else if (out_port == OFPP_TABLE) {
554 struct net_bridge_port *p = skb->dev->br_port;
555 struct sw_flow_key key;
556 struct sw_flow *flow;
558 flow_extract(skb, p ? p->port_no : OFPP_LOCAL, &key);
559 flow = chain_lookup(dp->chain, &key);
560 if (likely(flow != NULL)) {
561 flow_used(flow, skb);
562 execute_actions(dp, skb, &key, flow->actions, flow->n_actions);
566 } else if (out_port == OFPP_LOCAL) {
567 struct net_device *dev = dp->netdev;
568 return dev ? dp_dev_recv(dev, skb) : -ESRCH;
569 } else if (out_port >= 0 && out_port < OFPP_MAX) {
570 struct net_bridge_port *p = dp->ports[out_port];
575 if (packet_length(skb) > skb->dev->mtu) {
576 printk("dropped over-mtu packet: %d > %d\n",
577 packet_length(skb), skb->dev->mtu);
590 printk("can't forward to bad port %d\n", out_port);
594 /* Takes ownership of 'skb' and transmits it to 'dp''s control path. If
595 * 'buffer_id' != -1, then only the first 64 bytes of 'skb' are sent;
596 * otherwise, all of 'skb' is sent. 'reason' indicates why 'skb' is being
597 * sent. 'max_len' sets the maximum number of bytes that the caller
598 * wants to be sent; a value of 0 indicates the entire packet should be
601 dp_output_control(struct datapath *dp, struct sk_buff *skb,
602 uint32_t buffer_id, size_t max_len, int reason)
604 /* FIXME? Can we avoid creating a new skbuff in the case where we
605 * forward the whole packet? */
606 struct sk_buff *f_skb;
607 struct ofp_packet_in *opi;
608 struct net_bridge_port *p;
609 size_t fwd_len, opi_len;
613 if ((buffer_id != (uint32_t) -1) && max_len)
614 fwd_len = min(fwd_len, max_len);
616 opi_len = offsetof(struct ofp_packet_in, data) + fwd_len;
617 opi = alloc_openflow_skb(dp, opi_len, OFPT_PACKET_IN, NULL, &f_skb);
622 opi->buffer_id = htonl(buffer_id);
623 opi->total_len = htons(skb->len);
624 p = skb->dev->br_port;
625 opi->in_port = htons(p ? p->port_no : OFPP_LOCAL);
626 opi->reason = reason;
628 memcpy(opi->data, skb_mac_header(skb), fwd_len);
629 err = send_openflow_skb(f_skb, NULL);
636 static void fill_port_desc(struct net_bridge_port *p, struct ofp_phy_port *desc)
638 desc->port_no = htons(p->port_no);
639 strncpy(desc->name, p->dev->name, OFP_MAX_PORT_NAME_LEN);
640 desc->name[OFP_MAX_PORT_NAME_LEN-1] = '\0';
641 memcpy(desc->hw_addr, p->dev->dev_addr, ETH_ALEN);
642 desc->flags = htonl(p->flags);
646 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,24)
647 if (p->dev->ethtool_ops && p->dev->ethtool_ops->get_settings) {
648 struct ethtool_cmd ecmd = { .cmd = ETHTOOL_GSET };
650 if (!p->dev->ethtool_ops->get_settings(p->dev, &ecmd)) {
651 if (ecmd.supported & SUPPORTED_10baseT_Half)
652 desc->features |= OFPPF_10MB_HD;
653 if (ecmd.supported & SUPPORTED_10baseT_Full)
654 desc->features |= OFPPF_10MB_FD;
655 if (ecmd.supported & SUPPORTED_100baseT_Half)
656 desc->features |= OFPPF_100MB_HD;
657 if (ecmd.supported & SUPPORTED_100baseT_Full)
658 desc->features |= OFPPF_100MB_FD;
659 if (ecmd.supported & SUPPORTED_1000baseT_Half)
660 desc->features |= OFPPF_1GB_HD;
661 if (ecmd.supported & SUPPORTED_1000baseT_Full)
662 desc->features |= OFPPF_1GB_FD;
663 /* 10Gbps half-duplex doesn't exist... */
664 if (ecmd.supported & SUPPORTED_10000baseT_Full)
665 desc->features |= OFPPF_10GB_FD;
667 desc->features = htonl(desc->features);
668 desc->speed = htonl(ecmd.speed);
675 fill_features_reply(struct datapath *dp, struct ofp_switch_features *ofr)
677 struct net_bridge_port *p;
680 ofr->datapath_id = cpu_to_be64(dp->id);
682 ofr->n_exact = htonl(2 * TABLE_HASH_MAX_FLOWS);
683 ofr->n_compression = 0; /* Not supported */
684 ofr->n_general = htonl(TABLE_LINEAR_MAX_FLOWS);
685 ofr->buffer_mb = htonl(UINT32_MAX);
686 ofr->n_buffers = htonl(N_PKT_BUFFERS);
687 ofr->capabilities = htonl(OFP_SUPPORTED_CAPABILITIES);
688 ofr->actions = htonl(OFP_SUPPORTED_ACTIONS);
690 list_for_each_entry_rcu (p, &dp->port_list, node) {
691 fill_port_desc(p, &ofr->ports[port_count]);
699 dp_send_features_reply(struct datapath *dp, const struct sender *sender)
702 struct ofp_switch_features *ofr;
703 size_t ofr_len, port_max_len;
707 port_max_len = sizeof(struct ofp_phy_port) * OFPP_MAX;
708 ofr = alloc_openflow_skb(dp, sizeof(*ofr) + port_max_len,
709 OFPT_FEATURES_REPLY, sender, &skb);
714 port_count = fill_features_reply(dp, ofr);
717 ofr_len = sizeof(*ofr) + (sizeof(struct ofp_phy_port) * port_count);
718 resize_openflow_skb(skb, &ofr->header, ofr_len);
719 return send_openflow_skb(skb, sender);
723 dp_send_config_reply(struct datapath *dp, const struct sender *sender)
726 struct ofp_switch_config *osc;
728 osc = alloc_openflow_skb(dp, sizeof *osc, OFPT_GET_CONFIG_REPLY, sender,
733 osc->flags = htons(dp->flags);
734 osc->miss_send_len = htons(dp->miss_send_len);
736 return send_openflow_skb(skb, sender);
740 dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp)
742 int port_no = ntohs(opp->port_no);
743 struct net_bridge_port *p = (port_no < OFPP_MAX ? dp->ports[port_no]
744 : port_no == OFPP_LOCAL ? dp->local_port
746 /* Make sure the port id hasn't changed since this was sent */
747 if (!p || memcmp(opp->hw_addr, p->dev->dev_addr, ETH_ALEN))
749 p->flags = htonl(opp->flags);
755 send_port_status(struct net_bridge_port *p, uint8_t status)
758 struct ofp_port_status *ops;
760 ops = alloc_openflow_skb(p->dp, sizeof *ops, OFPT_PORT_STATUS, NULL,
764 ops->reason = status;
765 memset(ops->pad, 0, sizeof ops->pad);
766 fill_port_desc(p, &ops->desc);
768 return send_openflow_skb(skb, NULL);
772 dp_send_flow_expired(struct datapath *dp, struct sw_flow *flow)
775 struct ofp_flow_expired *ofe;
776 unsigned long duration_j;
778 ofe = alloc_openflow_skb(dp, sizeof *ofe, OFPT_FLOW_EXPIRED, 0, &skb);
782 flow_fill_match(&ofe->match, &flow->key);
784 memset(ofe->pad, 0, sizeof ofe->pad);
785 ofe->priority = htons(flow->priority);
787 duration_j = (flow->timeout - HZ * flow->max_idle) - flow->init_time;
788 ofe->duration = htonl(duration_j / HZ);
789 ofe->packet_count = cpu_to_be64(flow->packet_count);
790 ofe->byte_count = cpu_to_be64(flow->byte_count);
792 return send_openflow_skb(skb, NULL);
794 EXPORT_SYMBOL(dp_send_flow_expired);
797 dp_send_error_msg(struct datapath *dp, const struct sender *sender,
798 uint16_t type, uint16_t code, const uint8_t *data, size_t len)
801 struct ofp_error_msg *oem;
804 oem = alloc_openflow_skb(dp, sizeof(*oem)+len, OFPT_ERROR_MSG,
809 oem->type = htons(type);
810 oem->code = htons(code);
811 memcpy(oem->data, data, len);
813 return send_openflow_skb(skb, sender);
817 dp_send_echo_reply(struct datapath *dp, const struct sender *sender,
818 const struct ofp_header *rq)
821 struct ofp_header *reply;
823 reply = alloc_openflow_skb(dp, ntohs(rq->length), OFPT_ECHO_REPLY,
828 memcpy(reply + 1, rq + 1, ntohs(rq->length) - sizeof *rq);
829 return send_openflow_skb(skb, sender);
832 /* Generic Netlink interface.
834 * See netlink(7) for an introduction to netlink. See
835 * http://linux-net.osdl.org/index.php/Netlink for more information and
836 * pointers on how to work with netlink and Generic Netlink in the kernel and
839 static struct genl_family dp_genl_family = {
840 .id = GENL_ID_GENERATE,
842 .name = DP_GENL_FAMILY_NAME,
844 .maxattr = DP_GENL_A_MAX,
847 /* Attribute policy: what each attribute may contain. */
848 static struct nla_policy dp_genl_policy[DP_GENL_A_MAX + 1] = {
849 [DP_GENL_A_DP_IDX] = { .type = NLA_U32 },
850 [DP_GENL_A_MC_GROUP] = { .type = NLA_U32 },
851 [DP_GENL_A_PORTNAME] = { .type = NLA_STRING }
854 static int dp_genl_add(struct sk_buff *skb, struct genl_info *info)
856 if (!info->attrs[DP_GENL_A_DP_IDX])
859 return new_dp(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
862 static struct genl_ops dp_genl_ops_add_dp = {
863 .cmd = DP_GENL_C_ADD_DP,
864 .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
865 .policy = dp_genl_policy,
870 struct datapath *dp_get(int dp_idx)
872 if (dp_idx < 0 || dp_idx > DP_MAX)
874 return rcu_dereference(dps[dp_idx]);
877 static int dp_genl_del(struct sk_buff *skb, struct genl_info *info)
882 if (!info->attrs[DP_GENL_A_DP_IDX])
885 mutex_lock(&dp_mutex);
886 dp = dp_get(nla_get_u32((info->attrs[DP_GENL_A_DP_IDX])));
893 mutex_unlock(&dp_mutex);
897 static struct genl_ops dp_genl_ops_del_dp = {
898 .cmd = DP_GENL_C_DEL_DP,
899 .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
900 .policy = dp_genl_policy,
905 /* Queries a datapath for related information. Currently the only relevant
906 * information is the datapath's multicast group ID. Really we want one
907 * multicast group per datapath, but because of locking issues[*] we can't
908 * easily get one. Thus, every datapath will currently return the same
909 * global multicast group ID, but in the future it would be nice to fix that.
911 * [*] dp_genl_add, to add a new datapath, is called under the genl_lock
912 * mutex, and genl_register_mc_group, called to acquire a new multicast
913 * group ID, also acquires genl_lock, thus deadlock.
915 static int dp_genl_query(struct sk_buff *skb, struct genl_info *info)
918 struct sk_buff *ans_skb = NULL;
922 if (!info->attrs[DP_GENL_A_DP_IDX])
926 dp_idx = nla_get_u32((info->attrs[DP_GENL_A_DP_IDX]));
932 ans_skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
937 data = genlmsg_put_reply(ans_skb, info, &dp_genl_family,
938 0, DP_GENL_C_QUERY_DP);
943 NLA_PUT_U32(ans_skb, DP_GENL_A_DP_IDX, dp_idx);
944 NLA_PUT_U32(ans_skb, DP_GENL_A_MC_GROUP, mc_group.id);
946 genlmsg_end(ans_skb, data);
947 err = genlmsg_reply(ans_skb, info);
959 static struct genl_ops dp_genl_ops_query_dp = {
960 .cmd = DP_GENL_C_QUERY_DP,
961 .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
962 .policy = dp_genl_policy,
963 .doit = dp_genl_query,
967 static int dp_genl_add_del_port(struct sk_buff *skb, struct genl_info *info)
970 struct net_device *port;
973 if (!info->attrs[DP_GENL_A_DP_IDX] || !info->attrs[DP_GENL_A_PORTNAME])
977 mutex_lock(&dp_mutex);
978 dp = dp_get(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
984 /* Get interface to add/remove. */
985 port = dev_get_by_name(&init_net,
986 nla_data(info->attrs[DP_GENL_A_PORTNAME]));
992 /* Execute operation. */
993 if (info->genlhdr->cmd == DP_GENL_C_ADD_PORT)
994 err = add_switch_port(dp, port);
996 if (port->br_port == NULL || port->br_port->dp != dp) {
1000 err = del_switch_port(port->br_port);
1006 mutex_unlock(&dp_mutex);
1010 static struct genl_ops dp_genl_ops_add_port = {
1011 .cmd = DP_GENL_C_ADD_PORT,
1012 .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1013 .policy = dp_genl_policy,
1014 .doit = dp_genl_add_del_port,
1018 static struct genl_ops dp_genl_ops_del_port = {
1019 .cmd = DP_GENL_C_DEL_PORT,
1020 .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1021 .policy = dp_genl_policy,
1022 .doit = dp_genl_add_del_port,
1026 static int dp_genl_openflow(struct sk_buff *skb, struct genl_info *info)
1028 struct nlattr *va = info->attrs[DP_GENL_A_OPENFLOW];
1029 struct datapath *dp;
1030 struct ofp_header *oh;
1031 struct sender sender;
1034 if (!info->attrs[DP_GENL_A_DP_IDX] || !va)
1038 dp = dp_get(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
1044 if (nla_len(va) < sizeof(struct ofp_header)) {
1050 sender.xid = oh->xid;
1051 sender.pid = info->snd_pid;
1052 sender.seq = info->snd_seq;
1053 err = fwd_control_input(dp->chain, &sender, nla_data(va), nla_len(va));
1060 static struct nla_policy dp_genl_openflow_policy[DP_GENL_A_MAX + 1] = {
1061 [DP_GENL_A_DP_IDX] = { .type = NLA_U32 },
1064 struct flow_stats_state {
1066 struct sw_table_position position;
1067 const struct ofp_flow_stats_request *rq;
1070 int bytes_used, bytes_allocated;
1073 static int flow_stats_init(struct datapath *dp, const void *body, int body_len,
1076 const struct ofp_flow_stats_request *fsr = body;
1077 struct flow_stats_state *s = kmalloc(sizeof *s, GFP_ATOMIC);
1080 s->table_idx = fsr->table_id == 0xff ? 0 : fsr->table_id;
1081 memset(&s->position, 0, sizeof s->position);
1087 static int flow_stats_dump_callback(struct sw_flow *flow, void *private)
1089 struct flow_stats_state *s = private;
1090 struct ofp_flow_stats *ofs;
1094 actions_length = sizeof *ofs->actions * flow->n_actions;
1095 length = sizeof *ofs + sizeof *ofs->actions * flow->n_actions;
1096 if (length + s->bytes_used > s->bytes_allocated)
1099 ofs = s->body + s->bytes_used;
1100 ofs->length = htons(length);
1101 ofs->table_id = s->table_idx;
1103 ofs->match.wildcards = htons(flow->key.wildcards);
1104 ofs->match.in_port = flow->key.in_port;
1105 memcpy(ofs->match.dl_src, flow->key.dl_src, ETH_ALEN);
1106 memcpy(ofs->match.dl_dst, flow->key.dl_dst, ETH_ALEN);
1107 ofs->match.dl_vlan = flow->key.dl_vlan;
1108 ofs->match.dl_type = flow->key.dl_type;
1109 ofs->match.nw_src = flow->key.nw_src;
1110 ofs->match.nw_dst = flow->key.nw_dst;
1111 ofs->match.nw_proto = flow->key.nw_proto;
1112 memset(ofs->match.pad, 0, sizeof ofs->match.pad);
1113 ofs->match.tp_src = flow->key.tp_src;
1114 ofs->match.tp_dst = flow->key.tp_dst;
1115 ofs->duration = htonl((jiffies - flow->init_time) / HZ);
1116 ofs->packet_count = cpu_to_be64(flow->packet_count);
1117 ofs->byte_count = cpu_to_be64(flow->byte_count);
1118 ofs->priority = htons(flow->priority);
1119 ofs->max_idle = htons(flow->max_idle);
1120 memcpy(ofs->actions, flow->actions, actions_length);
1122 s->bytes_used += length;
1126 static int flow_stats_dump(struct datapath *dp, void *state,
1127 void *body, int *body_len)
1129 struct flow_stats_state *s = state;
1130 struct sw_flow_key match_key;
1134 s->bytes_allocated = *body_len;
1137 flow_extract_match(&match_key, &s->rq->match);
1138 while (s->table_idx < dp->chain->n_tables
1139 && (s->rq->table_id == 0xff || s->rq->table_id == s->table_idx))
1141 struct sw_table *table = dp->chain->tables[s->table_idx];
1143 error = table->iterate(table, &match_key, &s->position,
1144 flow_stats_dump_callback, s);
1149 memset(&s->position, 0, sizeof s->position);
1151 *body_len = s->bytes_used;
1153 /* If error is 0, we're done.
1154 * Otherwise, if some bytes were used, there are more flows to come.
1155 * Otherwise, we were not able to fit even a single flow in the body,
1156 * which indicates that we have a single flow with too many actions to
1157 * fit. We won't ever make any progress at that rate, so give up. */
1158 return !error ? 0 : s->bytes_used ? 1 : -ENOMEM;
1161 static void flow_stats_done(void *state)
1166 static int aggregate_stats_init(struct datapath *dp,
1167 const void *body, int body_len,
1170 *state = (void *)body;
1174 static int aggregate_stats_dump_callback(struct sw_flow *flow, void *private)
1176 struct ofp_aggregate_stats_reply *rpy = private;
1177 rpy->packet_count += flow->packet_count;
1178 rpy->byte_count += flow->byte_count;
1183 static int aggregate_stats_dump(struct datapath *dp, void *state,
1184 void *body, int *body_len)
1186 struct ofp_aggregate_stats_request *rq = state;
1187 struct ofp_aggregate_stats_reply *rpy;
1188 struct sw_table_position position;
1189 struct sw_flow_key match_key;
1192 if (*body_len < sizeof *rpy)
1195 *body_len = sizeof *rpy;
1197 memset(rpy, 0, sizeof *rpy);
1199 flow_extract_match(&match_key, &rq->match);
1200 table_idx = rq->table_id == 0xff ? 0 : rq->table_id;
1201 memset(&position, 0, sizeof position);
1202 while (table_idx < dp->chain->n_tables
1203 && (rq->table_id == 0xff || rq->table_id == table_idx))
1205 struct sw_table *table = dp->chain->tables[table_idx];
1208 error = table->iterate(table, &match_key, &position,
1209 aggregate_stats_dump_callback, rpy);
1214 memset(&position, 0, sizeof position);
1217 rpy->packet_count = cpu_to_be64(rpy->packet_count);
1218 rpy->byte_count = cpu_to_be64(rpy->byte_count);
1219 rpy->flow_count = htonl(rpy->flow_count);
1223 static int table_stats_dump(struct datapath *dp, void *state,
1224 void *body, int *body_len)
1226 struct ofp_table_stats *ots;
1227 int nbytes = dp->chain->n_tables * sizeof *ots;
1229 if (nbytes > *body_len)
1232 for (i = 0, ots = body; i < dp->chain->n_tables; i++, ots++) {
1233 struct sw_table_stats stats;
1234 dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
1235 strncpy(ots->name, stats.name, sizeof ots->name);
1237 memset(ots->pad, 0, sizeof ots->pad);
1238 ots->max_entries = htonl(stats.max_flows);
1239 ots->active_count = htonl(stats.n_flows);
1240 ots->matched_count = cpu_to_be64(0); /* FIXME */
1245 struct port_stats_state {
1249 static int port_stats_init(struct datapath *dp, const void *body, int body_len,
1252 struct port_stats_state *s = kmalloc(sizeof *s, GFP_ATOMIC);
1260 static int port_stats_dump(struct datapath *dp, void *state,
1261 void *body, int *body_len)
1263 struct port_stats_state *s = state;
1264 struct ofp_port_stats *ops;
1265 int n_ports, max_ports;
1268 max_ports = *body_len / sizeof *ops;
1274 for (i = s->port; i < OFPP_MAX && n_ports < max_ports; i++) {
1275 struct net_bridge_port *p = dp->ports[i];
1276 struct net_device_stats *stats;
1279 stats = p->dev->get_stats(p->dev);
1280 ops->port_no = htons(p->port_no);
1281 memset(ops->pad, 0, sizeof ops->pad);
1282 ops->rx_count = cpu_to_be64(stats->rx_packets);
1283 ops->tx_count = cpu_to_be64(stats->tx_packets);
1284 ops->drop_count = cpu_to_be64(stats->rx_dropped
1285 + stats->tx_dropped);
1290 *body_len = n_ports * sizeof *ops;
1291 return n_ports >= max_ports;
1294 static void port_stats_done(void *state)
1300 /* Minimum and maximum acceptable number of bytes in body member of
1301 * struct ofp_stats_request. */
1302 size_t min_body, max_body;
1304 /* Prepares to dump some kind of statistics on 'dp'. 'body' and
1305 * 'body_len' are the 'body' member of the struct ofp_stats_request.
1306 * Returns zero if successful, otherwise a negative error code.
1307 * May initialize '*state' to state information. May be null if no
1308 * initialization is required.*/
1309 int (*init)(struct datapath *dp, const void *body, int body_len,
1312 /* Dumps statistics for 'dp' into the '*body_len' bytes at 'body', and
1313 * modifies '*body_len' to reflect the number of bytes actually used.
1314 * ('body' will be transmitted as the 'body' member of struct
1315 * ofp_stats_reply.) */
1316 int (*dump)(struct datapath *dp, void *state,
1317 void *body, int *body_len);
1319 /* Cleans any state created by the init or dump functions. May be null
1320 * if no cleanup is required. */
1321 void (*done)(void *state);
1324 static const struct stats_type stats[] = {
1326 sizeof(struct ofp_flow_stats_request),
1327 sizeof(struct ofp_flow_stats_request),
1332 [OFPST_AGGREGATE] = {
1333 sizeof(struct ofp_aggregate_stats_request),
1334 sizeof(struct ofp_aggregate_stats_request),
1335 aggregate_stats_init,
1336 aggregate_stats_dump,
1356 dp_genl_openflow_dumpit(struct sk_buff *skb, struct netlink_callback *cb)
1358 struct datapath *dp;
1359 struct sender sender;
1360 const struct stats_type *s;
1361 struct ofp_stats_reply *osr;
1363 int max_openflow_len, body_len;
1367 /* Set up the cleanup function for this dump. Linux 2.6.20 and later
1368 * support setting up cleanup functions via the .doneit member of
1369 * struct genl_ops. This kluge supports earlier versions also. */
1370 cb->done = dp_genl_openflow_done;
1374 struct nlattr *attrs[DP_GENL_A_MAX + 1];
1375 struct ofp_stats_request *rq;
1377 size_t len, body_len;
1380 err = nlmsg_parse(cb->nlh, GENL_HDRLEN, attrs, DP_GENL_A_MAX,
1381 dp_genl_openflow_policy);
1387 if (!attrs[DP_GENL_A_DP_IDX])
1389 dp_idx = nla_get_u16(attrs[DP_GENL_A_DP_IDX]);
1390 dp = dp_get(dp_idx);
1396 va = attrs[DP_GENL_A_OPENFLOW];
1398 if (!va || len < sizeof *rq)
1402 type = ntohs(rq->type);
1403 if (rq->header.version != OFP_VERSION
1404 || rq->header.type != OFPT_STATS_REQUEST
1405 || ntohs(rq->header.length) != len
1406 || type >= ARRAY_SIZE(stats)
1407 || !stats[type].dump)
1411 body_len = len - offsetof(struct ofp_stats_request, body);
1412 if (body_len < s->min_body || body_len > s->max_body)
1416 cb->args[1] = dp_idx;
1418 cb->args[3] = rq->header.xid;
1421 err = s->init(dp, rq->body, body_len, &state);
1424 cb->args[4] = (long) state;
1426 } else if (cb->args[0] == 1) {
1427 dp_idx = cb->args[1];
1428 s = &stats[cb->args[2]];
1430 dp = dp_get(dp_idx);
1440 sender.xid = cb->args[3];
1441 sender.pid = NETLINK_CB(cb->skb).pid;
1442 sender.seq = cb->nlh->nlmsg_seq;
1444 osr = put_openflow_headers(dp, skb, OFPT_STATS_REPLY, &sender,
1450 osr->type = htons(s - stats);
1452 resize_openflow_skb(skb, &osr->header, max_openflow_len);
1454 body_len = max_openflow_len - offsetof(struct ofp_stats_reply, body);
1456 err = s->dump(dp, (void *) cb->args[4], body, &body_len);
1461 osr->flags = ntohs(OFPSF_REPLY_MORE);
1462 resize_openflow_skb(skb, &osr->header,
1463 (offsetof(struct ofp_stats_reply, body)
1474 dp_genl_openflow_done(struct netlink_callback *cb)
1477 const struct stats_type *s = &stats[cb->args[2]];
1479 s->done((void *) cb->args[4]);
1484 static struct genl_ops dp_genl_ops_openflow = {
1485 .cmd = DP_GENL_C_OPENFLOW,
1486 .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1487 .policy = dp_genl_openflow_policy,
1488 .doit = dp_genl_openflow,
1489 .dumpit = dp_genl_openflow_dumpit,
1492 static struct nla_policy dp_genl_benchmark_policy[DP_GENL_A_MAX + 1] = {
1493 [DP_GENL_A_DP_IDX] = { .type = NLA_U32 },
1494 [DP_GENL_A_NPACKETS] = { .type = NLA_U32 },
1495 [DP_GENL_A_PSIZE] = { .type = NLA_U32 },
1498 static struct genl_ops dp_genl_ops_benchmark_nl = {
1499 .cmd = DP_GENL_C_BENCHMARK_NL,
1500 .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1501 .policy = dp_genl_benchmark_policy,
1502 .doit = dp_genl_benchmark_nl,
1506 static struct genl_ops *dp_genl_all_ops[] = {
1507 /* Keep this operation first. Generic Netlink dispatching
1508 * looks up operations with linear search, so we want it at the
1510 &dp_genl_ops_openflow,
1512 &dp_genl_ops_add_dp,
1513 &dp_genl_ops_del_dp,
1514 &dp_genl_ops_query_dp,
1515 &dp_genl_ops_add_port,
1516 &dp_genl_ops_del_port,
1517 &dp_genl_ops_benchmark_nl,
1520 static int dp_init_netlink(void)
1525 err = genl_register_family(&dp_genl_family);
1529 for (i = 0; i < ARRAY_SIZE(dp_genl_all_ops); i++) {
1530 err = genl_register_ops(&dp_genl_family, dp_genl_all_ops[i]);
1532 goto err_unregister;
1535 strcpy(mc_group.name, "openflow");
1536 err = genl_register_mc_group(&dp_genl_family, &mc_group);
1538 goto err_unregister;
1543 genl_unregister_family(&dp_genl_family);
1547 static void dp_uninit_netlink(void)
1549 genl_unregister_family(&dp_genl_family);
1552 #define DRV_NAME "openflow"
1553 #define DRV_VERSION VERSION
1554 #define DRV_DESCRIPTION "OpenFlow switching datapath implementation"
1555 #define DRV_COPYRIGHT "Copyright (c) 2007, 2008 The Board of Trustees of The Leland Stanford Junior University"
1558 static int __init dp_init(void)
1562 printk(KERN_INFO DRV_NAME ": " DRV_DESCRIPTION "\n");
1563 printk(KERN_INFO DRV_NAME ": " VERSION" built on "__DATE__" "__TIME__"\n");
1564 printk(KERN_INFO DRV_NAME ": " DRV_COPYRIGHT "\n");
1570 err = dp_init_netlink();
1572 goto error_flow_exit;
1574 /* Hook into callback used by the bridge to intercept packets.
1575 * Parasites we are. */
1576 if (br_handle_frame_hook)
1577 printk("openflow: hijacking bridge hook\n");
1578 br_handle_frame_hook = dp_frame_hook;
1585 printk(KERN_EMERG "openflow: failed to install!");
1589 static void dp_cleanup(void)
1592 dp_uninit_netlink();
1594 br_handle_frame_hook = NULL;
1597 module_init(dp_init);
1598 module_exit(dp_cleanup);
1600 MODULE_DESCRIPTION(DRV_DESCRIPTION);
1601 MODULE_AUTHOR(DRV_COPYRIGHT);
1602 MODULE_LICENSE("GPL");