Avoid wild pointer write in del_switch_port().
[sliver-openvswitch.git] / datapath / datapath.c
1 /*
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
5  */
6
7 /* Functions for managing the dp interface/device. */
8
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>
14 #include <linux/in.h>
15 #include <net/genetlink.h>
16 #include <linux/ip.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
32 #include "openflow-netlink.h"
33 #include "datapath.h"
34 #include "table.h"
35 #include "chain.h"
36 #include "dp_dev.h"
37 #include "forward.h"
38 #include "flow.h"
39 #include "datapath_t.h"
40
41 #include "compat.h"
42
43
44 /* Number of milliseconds between runs of the maintenance thread. */
45 #define MAINT_SLEEP_MSECS 1000
46
47 #define BRIDGE_PORT_NO_FLOOD    0x00000001 
48
49 #define UINT32_MAX                        4294967295U
50 #define UINT16_MAX                        65535
51 #define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
52
53 struct net_bridge_port {
54         u16     port_no;
55         u32 flags;
56         struct datapath *dp;
57         struct net_device *dev;
58         struct list_head node; /* Element in datapath.ports. */
59 };
60
61 static struct genl_family dp_genl_family;
62 static struct genl_multicast_group mc_group;
63
64 /* It's hard to imagine wanting more than one datapath, but... */
65 #define DP_MAX 32
66
67 /* datapaths.  Protected on the read side by rcu_read_lock, on the write side
68  * by dp_mutex.
69  *
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).
73  */
74 static struct datapath *dps[DP_MAX];
75 static DEFINE_MUTEX(dp_mutex);
76
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 *);
83
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
88  *
89  * Reduces amount of space reserved by a call to nla_reserve.
90  *
91  * No other attributes may be added between calling nla_reserve and this
92  * function, since it will create a hole in the message.
93  */
94 void nla_shrink(struct sk_buff *skb, struct nlattr *nla, int len)
95 {
96         int delta = nla_total_size(len) - nla_total_size(nla_len(nla));
97         BUG_ON(delta > 0);
98         skb->tail += delta;
99         skb->len  += delta;
100         nla->nla_len = nla_attr_size(len);
101 }
102
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.
106  *
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
110  * of bytes or less.
111  *
112  * Returns the openflow header if successful, otherwise (if 'skb' is too small)
113  * an error code. */
114 static void *
115 put_openflow_headers(struct datapath *dp, struct sk_buff *skb, uint8_t type,
116                      const struct sender *sender, int *max_openflow_len)
117 {
118         struct ofp_header *oh;
119         struct nlattr *attr;
120         int openflow_len;
121
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);
135         BUG_ON(!attr);
136
137         /* Fill in the header.  The caller is responsible for the length. */
138         oh = nla_data(attr);
139         oh->version = OFP_VERSION;
140         oh->type = type;
141         oh->xid = sender ? sender->xid : 0;
142
143         return oh;
144 }
145
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
148  * necessary. */
149 static void
150 resize_openflow_skb(struct sk_buff *skb,
151                     struct ofp_header *oh, size_t new_length)
152 {
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);
157 }
158
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'. 
162  *
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
165  * use.  */
166 static void *
167 alloc_openflow_skb(struct datapath *dp, size_t openflow_len, uint8_t type,
168                    const struct sender *sender, struct sk_buff **pskb) 
169 {
170         struct ofp_header *oh;
171         size_t genl_len;
172         struct sk_buff *skb;
173         int max_openflow_len;
174
175         if ((openflow_len + sizeof(struct ofp_header)) > UINT16_MAX) {
176                 if (net_ratelimit())
177                         printk("alloc_openflow_skb: openflow message too large: %zu\n", 
178                                         openflow_len);
179                 return NULL;
180         }
181
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);
186         if (!skb) {
187                 if (net_ratelimit())
188                         printk("alloc_openflow_skb: genlmsg_new failed\n");
189                 return NULL;
190         }
191
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);
195
196         return oh;
197 }
198
199 /* Sends 'skb' to 'sender' if it is nonnull, otherwise multicasts 'skb' to all
200  * listeners. */
201 static int
202 send_openflow_skb(struct sk_buff *skb, const struct sender *sender) 
203 {
204         int err = (sender
205                    ? genlmsg_unicast(skb, sender->pid)
206                    : genlmsg_multicast(skb, 0, mc_group.id, GFP_ATOMIC));
207         if (err && net_ratelimit())
208                 printk(KERN_WARNING "send_openflow_skb: send failed: %d\n",
209                        err);
210         return err;
211 }
212
213 /* Generates a unique datapath id.  It incorporates the datapath index
214  * and a hardware address, if available.  If not, it generates a random
215  * one.
216  */
217 static 
218 uint64_t gen_datapath_id(uint16_t dp_idx)
219 {
220         uint64_t id;
221         int i;
222         struct net_device *dev;
223
224         /* The top 16 bits are used to identify the datapath.  The lower 48 bits
225          * use an interface address.  */
226         id = (uint64_t)dp_idx << 48;
227         if ((dev = dev_get_by_name(&init_net, "ctl0")) 
228                         || (dev = dev_get_by_name(&init_net, "eth0"))) {
229                 for (i=0; i<ETH_ALEN; i++) {
230                         id |= (uint64_t)dev->dev_addr[i] << (8*(ETH_ALEN-1 - i));
231                 }
232                 dev_put(dev);
233         } else {
234                 /* Randomly choose the lower 48 bits if we cannot find an
235                  * address and mark the most significant bit to indicate that
236                  * this was randomly generated. */
237                 uint8_t rand[ETH_ALEN];
238                 get_random_bytes(rand, ETH_ALEN);
239                 id |= (uint64_t)1 << 63;
240                 for (i=0; i<ETH_ALEN; i++) {
241                         id |= (uint64_t)rand[i] << (8*(ETH_ALEN-1 - i));
242                 }
243         }
244
245         return id;
246 }
247
248 /* Creates a new datapath numbered 'dp_idx'.  Returns 0 for success or a
249  * negative error code.
250  *
251  * Not called with any locks. */
252 static int new_dp(int dp_idx)
253 {
254         struct datapath *dp;
255         int err;
256
257         if (dp_idx < 0 || dp_idx >= DP_MAX)
258                 return -EINVAL;
259
260         if (!try_module_get(THIS_MODULE))
261                 return -ENODEV;
262
263         mutex_lock(&dp_mutex);
264         dp = rcu_dereference(dps[dp_idx]);
265         if (dp != NULL) {
266                 err = -EEXIST;
267                 goto err_unlock;
268         }
269
270         err = -ENOMEM;
271         dp = kzalloc(sizeof *dp, GFP_KERNEL);
272         if (dp == NULL)
273                 goto err_unlock;
274
275         /* Setup our "of" device */
276         err = dp_dev_setup(dp);
277         if (err)
278                 goto err_free_dp;
279
280         dp->dp_idx = dp_idx;
281         dp->id = gen_datapath_id(dp_idx);
282         dp->chain = chain_create(dp);
283         if (dp->chain == NULL)
284                 goto err_destroy_dp_dev;
285         INIT_LIST_HEAD(&dp->port_list);
286
287         dp->local_port = new_nbp(dp, dp->netdev, OFPP_LOCAL);
288         if (IS_ERR(dp->local_port)) {
289                 err = PTR_ERR(dp->local_port);
290                 goto err_destroy_local_port;
291         }
292
293         dp->flags = 0;
294         dp->miss_send_len = OFP_DEFAULT_MISS_SEND_LEN;
295
296         dp->dp_task = kthread_run(dp_maint_func, dp, "dp%d", dp_idx);
297         if (IS_ERR(dp->dp_task))
298                 goto err_destroy_chain;
299
300         rcu_assign_pointer(dps[dp_idx], dp);
301         mutex_unlock(&dp_mutex);
302
303         return 0;
304
305 err_destroy_local_port:
306         del_switch_port(dp->local_port);
307 err_destroy_chain:
308         chain_destroy(dp->chain);
309 err_destroy_dp_dev:
310         dp_dev_destroy(dp);
311 err_free_dp:
312         kfree(dp);
313 err_unlock:
314         mutex_unlock(&dp_mutex);
315         module_put(THIS_MODULE);
316                 return err;
317 }
318
319 /* Find and return a free port number under 'dp'.  Called under dp_mutex. */
320 static int find_portno(struct datapath *dp)
321 {
322         int i;
323         for (i = 0; i < OFPP_MAX; i++)
324                 if (dp->ports[i] == NULL)
325                         return i;
326         return -EXFULL;
327 }
328
329 static struct net_bridge_port *new_nbp(struct datapath *dp,
330                                        struct net_device *dev, int port_no)
331 {
332         struct net_bridge_port *p;
333
334         if (dev->br_port != NULL)
335                 return ERR_PTR(-EBUSY);
336
337         p = kzalloc(sizeof(*p), GFP_KERNEL);
338         if (p == NULL)
339                 return ERR_PTR(-ENOMEM);
340
341         rtnl_lock();
342         dev_set_promiscuity(dev, 1);
343         rtnl_unlock();
344         dev_hold(dev);
345         p->dp = dp;
346         p->dev = dev;
347         p->port_no = port_no;
348         if (port_no != OFPP_LOCAL)
349                 rcu_assign_pointer(dev->br_port, p);
350         if (port_no < OFPP_MAX)
351                 rcu_assign_pointer(dp->ports[port_no], p); 
352         list_add_rcu(&p->node, &dp->port_list);
353
354         return p;
355 }
356
357 /* Called with dp_mutex. */
358 int add_switch_port(struct datapath *dp, struct net_device *dev)
359 {
360         struct net_bridge_port *p;
361         int port_no;
362
363         if (dev->flags & IFF_LOOPBACK || dev->type != ARPHRD_ETHER
364             || is_dp_dev(dev))
365                 return -EINVAL;
366
367         port_no = find_portno(dp);
368         if (port_no < 0)
369                 return port_no;
370
371         p = new_nbp(dp, dev, port_no);
372         if (IS_ERR(p))
373                 return PTR_ERR(p);
374
375         /* Notify the ctlpath that this port has been added */
376         send_port_status(p, OFPPR_ADD);
377
378         return 0;
379 }
380
381 /* Delete 'p' from switch.
382  * Called with dp_mutex. */
383 static int del_switch_port(struct net_bridge_port *p)
384 {
385         /* First drop references to device. */
386         rtnl_lock();
387         dev_set_promiscuity(p->dev, -1);
388         rtnl_unlock();
389         list_del_rcu(&p->node);
390         if (p->port_no != OFPP_LOCAL)
391                 rcu_assign_pointer(p->dp->ports[p->port_no], NULL);
392         rcu_assign_pointer(p->dev->br_port, NULL);
393
394         /* Then wait until no one is still using it, and destroy it. */
395         synchronize_rcu();
396
397         /* Notify the ctlpath that this port no longer exists */
398         send_port_status(p, OFPPR_DELETE);
399
400         dev_put(p->dev);
401         kfree(p);
402
403         return 0;
404 }
405
406 /* Called with dp_mutex. */
407 static void del_dp(struct datapath *dp)
408 {
409         struct net_bridge_port *p;
410
411         dp_dev_destroy(dp);
412         kthread_stop(dp->dp_task);
413
414         /* Drop references to DP. */
415         list_for_each_entry_rcu (p, &dp->port_list, node)
416                 del_switch_port(p);
417         rcu_assign_pointer(dps[dp->dp_idx], NULL);
418
419         /* Wait until no longer in use, then destroy it. */
420         synchronize_rcu();
421         chain_destroy(dp->chain);
422         kfree(dp);
423         module_put(THIS_MODULE);
424 }
425
426 static int dp_maint_func(void *data)
427 {
428         struct datapath *dp = (struct datapath *) data;
429
430         while (!kthread_should_stop()) {
431                 chain_timeout(dp->chain);
432                 msleep_interruptible(MAINT_SLEEP_MSECS);
433         }
434                 
435         return 0;
436 }
437
438 static void
439 do_port_input(struct net_bridge_port *p, struct sk_buff *skb) 
440 {
441         /* Push the Ethernet header back on. */
442         if (skb->protocol == htons(ETH_P_8021Q))
443                 skb_push(skb, VLAN_ETH_HLEN);
444         else
445                 skb_push(skb, ETH_HLEN);
446         fwd_port_input(p->dp->chain, skb, p->port_no);
447 }
448
449 /*
450  * Used as br_handle_frame_hook.  (Cannot run bridge at the same time, even on
451  * different set of devices!)
452  */
453 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
454 /* Called with rcu_read_lock. */
455 static struct sk_buff *dp_frame_hook(struct net_bridge_port *p,
456                                          struct sk_buff *skb)
457 {
458         do_port_input(p, skb);
459         return NULL;
460 }
461 #elif LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
462 static int dp_frame_hook(struct net_bridge_port *p, struct sk_buff **pskb)
463 {
464         do_port_input(p, *pskb);
465         return 1;
466 }
467 #else
468 /* NB: This has only been tested on 2.4.35 */
469
470 /* Called without any locks (?) */
471 static void dp_frame_hook(struct sk_buff *skb)
472 {
473         struct net_bridge_port *p = skb->dev->br_port;
474         if (p) {
475                 rcu_read_lock();
476                 do_port_input(p, skb);
477                 rcu_read_unlock();
478         } else
479                 kfree_skb(skb);
480 }
481 #endif
482
483 /* Forwarding output path.
484  * Based on net/bridge/br_forward.c. */
485
486 static inline unsigned packet_length(const struct sk_buff *skb)
487 {
488         int length = skb->len - ETH_HLEN;
489         if (skb->protocol == htons(ETH_P_8021Q))
490                 length -= VLAN_HLEN;
491         return length;
492 }
493
494 /* Send packets out all the ports except the originating one.  If the
495  * "flood" argument is set, only send along the minimum spanning tree.
496  */
497 static int
498 output_all(struct datapath *dp, struct sk_buff *skb, int flood)
499 {
500         u32 disable = flood ? BRIDGE_PORT_NO_FLOOD : 0;
501         struct net_bridge_port *p;
502         int prev_port = -1;
503
504         list_for_each_entry_rcu (p, &dp->port_list, node) {
505                 if (skb->dev == p->dev || p->flags & disable)
506                         continue;
507                 if (prev_port != -1) {
508                         struct sk_buff *clone = skb_clone(skb, GFP_ATOMIC);
509                         if (!clone) {
510                                 kfree_skb(skb);
511                                 return -ENOMEM;
512                         }
513                         dp_output_port(dp, clone, prev_port); 
514                 }
515                 prev_port = p->port_no;
516         }
517         if (prev_port != -1)
518                 dp_output_port(dp, skb, prev_port);
519         else
520                 kfree_skb(skb);
521
522         return 0;
523 }
524
525 /* Marks 'skb' as having originated from 'in_port' in 'dp'.
526    FIXME: how are devices reference counted? */
527 int dp_set_origin(struct datapath *dp, uint16_t in_port,
528                            struct sk_buff *skb)
529 {
530         struct net_bridge_port *p = (in_port < OFPP_MAX ? dp->ports[in_port]
531                                      : in_port == OFPP_LOCAL ? dp->local_port
532                                      : NULL);
533         if (p) {
534                 skb->dev = p->dev;
535                 return 0;
536         }
537         return -ENOENT;
538 }
539
540 /* Takes ownership of 'skb' and transmits it to 'out_port' on 'dp'.
541  */
542 int dp_output_port(struct datapath *dp, struct sk_buff *skb, int out_port)
543 {
544         BUG_ON(!skb);
545         if (out_port == OFPP_FLOOD)
546                 return output_all(dp, skb, 1);
547         else if (out_port == OFPP_ALL)
548                 return output_all(dp, skb, 0);
549         else if (out_port == OFPP_CONTROLLER)
550                 return dp_output_control(dp, skb, fwd_save_skb(skb), 0,
551                                                   OFPR_ACTION);
552         else if (out_port == OFPP_TABLE) {
553                 struct net_bridge_port *p = skb->dev->br_port;
554                 struct sw_flow_key key;
555                 struct sw_flow *flow;
556
557                 flow_extract(skb, p ? p->port_no : OFPP_LOCAL, &key);
558                 flow = chain_lookup(dp->chain, &key);
559                 if (likely(flow != NULL)) {
560                         flow_used(flow, skb);
561                         execute_actions(dp, skb, &key, flow->actions, flow->n_actions);
562                         return 0;
563                 }
564                 return -ESRCH;
565         } else if (out_port == OFPP_LOCAL) {
566                 struct net_device *dev = dp->netdev;
567                 return dev ? dp_dev_recv(dev, skb) : -ESRCH;
568         } else if (out_port >= 0 && out_port < OFPP_MAX) {
569                 struct net_bridge_port *p = dp->ports[out_port];
570                 int len = skb->len;
571                 if (p == NULL)
572                         goto bad_port;
573                 skb->dev = p->dev; 
574                 if (packet_length(skb) > skb->dev->mtu) {
575                         printk("dropped over-mtu packet: %d > %d\n",
576                                packet_length(skb), skb->dev->mtu);
577                         kfree_skb(skb);
578                         return -E2BIG;
579                 }
580
581                 dev_queue_xmit(skb);
582
583                 return len;
584         }
585
586 bad_port:
587         kfree_skb(skb);
588         if (net_ratelimit())
589                 printk("can't forward to bad port %d\n", out_port);
590         return -ENOENT;
591 }
592
593 /* Takes ownership of 'skb' and transmits it to 'dp''s control path.  If
594  * 'buffer_id' != -1, then only the first 64 bytes of 'skb' are sent;
595  * otherwise, all of 'skb' is sent.  'reason' indicates why 'skb' is being
596  * sent. 'max_len' sets the maximum number of bytes that the caller
597  * wants to be sent; a value of 0 indicates the entire packet should be
598  * sent. */
599 int
600 dp_output_control(struct datapath *dp, struct sk_buff *skb,
601                            uint32_t buffer_id, size_t max_len, int reason)
602 {
603         /* FIXME?  Can we avoid creating a new skbuff in the case where we
604          * forward the whole packet? */
605         struct sk_buff *f_skb;
606         struct ofp_packet_in *opi;
607         struct net_bridge_port *p;
608         size_t fwd_len, opi_len;
609         int err;
610
611         fwd_len = skb->len;
612         if ((buffer_id != (uint32_t) -1) && max_len)
613                 fwd_len = min(fwd_len, max_len);
614
615         opi_len = offsetof(struct ofp_packet_in, data) + fwd_len;
616         opi = alloc_openflow_skb(dp, opi_len, OFPT_PACKET_IN, NULL, &f_skb);
617         if (!opi) {
618                 err = -ENOMEM;
619                 goto out;
620         }
621         opi->buffer_id      = htonl(buffer_id);
622         opi->total_len      = htons(skb->len);
623         p = skb->dev->br_port;
624         opi->in_port        = htons(p ? p->port_no : OFPP_LOCAL);
625         opi->reason         = reason;
626         opi->pad            = 0;
627         memcpy(opi->data, skb_mac_header(skb), fwd_len);
628         err = send_openflow_skb(f_skb, NULL);
629
630 out:
631         kfree_skb(skb);
632         return err;
633 }
634
635 static void fill_port_desc(struct net_bridge_port *p, struct ofp_phy_port *desc)
636 {
637         desc->port_no = htons(p->port_no);
638         strncpy(desc->name, p->dev->name, OFP_MAX_PORT_NAME_LEN);
639         desc->name[OFP_MAX_PORT_NAME_LEN-1] = '\0';
640         memcpy(desc->hw_addr, p->dev->dev_addr, ETH_ALEN);
641         desc->flags = htonl(p->flags);
642         desc->features = 0;
643         desc->speed = 0;
644
645 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,24)
646         if (p->dev->ethtool_ops && p->dev->ethtool_ops->get_settings) {
647                 struct ethtool_cmd ecmd = { .cmd = ETHTOOL_GSET };
648
649                 if (!p->dev->ethtool_ops->get_settings(p->dev, &ecmd)) {
650                         if (ecmd.supported & SUPPORTED_10baseT_Half) 
651                                 desc->features |= OFPPF_10MB_HD;
652                         if (ecmd.supported & SUPPORTED_10baseT_Full)
653                                 desc->features |= OFPPF_10MB_FD;
654                         if (ecmd.supported & SUPPORTED_100baseT_Half) 
655                                 desc->features |= OFPPF_100MB_HD;
656                         if (ecmd.supported & SUPPORTED_100baseT_Full)
657                                 desc->features |= OFPPF_100MB_FD;
658                         if (ecmd.supported & SUPPORTED_1000baseT_Half)
659                                 desc->features |= OFPPF_1GB_HD;
660                         if (ecmd.supported & SUPPORTED_1000baseT_Full)
661                                 desc->features |= OFPPF_1GB_FD;
662                         /* 10Gbps half-duplex doesn't exist... */
663                         if (ecmd.supported & SUPPORTED_10000baseT_Full)
664                                 desc->features |= OFPPF_10GB_FD;
665
666                         desc->features = htonl(desc->features);
667                         desc->speed = htonl(ecmd.speed);
668                 }
669         }
670 #endif
671 }
672
673 static int 
674 fill_features_reply(struct datapath *dp, struct ofp_switch_features *ofr)
675 {
676         struct net_bridge_port *p;
677         int port_count = 0;
678
679         ofr->datapath_id    = cpu_to_be64(dp->id); 
680
681         ofr->n_exact        = htonl(2 * TABLE_HASH_MAX_FLOWS);
682         ofr->n_compression  = 0;                                           /* Not supported */
683         ofr->n_general      = htonl(TABLE_LINEAR_MAX_FLOWS);
684         ofr->buffer_mb      = htonl(UINT32_MAX);
685         ofr->n_buffers      = htonl(N_PKT_BUFFERS);
686         ofr->capabilities   = htonl(OFP_SUPPORTED_CAPABILITIES);
687         ofr->actions        = htonl(OFP_SUPPORTED_ACTIONS);
688
689         list_for_each_entry_rcu (p, &dp->port_list, node) {
690                 fill_port_desc(p, &ofr->ports[port_count]);
691                 port_count++;
692         }
693
694         return port_count;
695 }
696
697 int
698 dp_send_features_reply(struct datapath *dp, const struct sender *sender)
699 {
700         struct sk_buff *skb;
701         struct ofp_switch_features *ofr;
702         size_t ofr_len, port_max_len;
703         int port_count;
704
705         /* Overallocate. */
706         port_max_len = sizeof(struct ofp_phy_port) * OFPP_MAX;
707         ofr = alloc_openflow_skb(dp, sizeof(*ofr) + port_max_len,
708                                  OFPT_FEATURES_REPLY, sender, &skb);
709         if (!ofr)
710                 return -ENOMEM;
711
712         /* Fill. */
713         port_count = fill_features_reply(dp, ofr);
714
715         /* Shrink to fit. */
716         ofr_len = sizeof(*ofr) + (sizeof(struct ofp_phy_port) * port_count);
717         resize_openflow_skb(skb, &ofr->header, ofr_len);
718         return send_openflow_skb(skb, sender);
719 }
720
721 int
722 dp_send_config_reply(struct datapath *dp, const struct sender *sender)
723 {
724         struct sk_buff *skb;
725         struct ofp_switch_config *osc;
726
727         osc = alloc_openflow_skb(dp, sizeof *osc, OFPT_GET_CONFIG_REPLY, sender,
728                                  &skb);
729         if (!osc)
730                 return -ENOMEM;
731
732         osc->flags = htons(dp->flags);
733         osc->miss_send_len = htons(dp->miss_send_len);
734
735         return send_openflow_skb(skb, sender);
736 }
737
738 int
739 dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp)
740 {
741         int port_no = ntohs(opp->port_no);
742         struct net_bridge_port *p = (port_no < OFPP_MAX ? dp->ports[port_no]
743                                      : port_no == OFPP_LOCAL ? dp->local_port
744                                      : NULL);
745         /* Make sure the port id hasn't changed since this was sent */
746         if (!p || memcmp(opp->hw_addr, p->dev->dev_addr, ETH_ALEN))
747                 return -1;
748         p->flags = htonl(opp->flags);
749         return 0;
750 }
751
752
753 static int
754 send_port_status(struct net_bridge_port *p, uint8_t status)
755 {
756         struct sk_buff *skb;
757         struct ofp_port_status *ops;
758
759         ops = alloc_openflow_skb(p->dp, sizeof *ops, OFPT_PORT_STATUS, NULL,
760                                  &skb);
761         if (!ops)
762                 return -ENOMEM;
763         ops->reason = status;
764         memset(ops->pad, 0, sizeof ops->pad);
765         fill_port_desc(p, &ops->desc);
766
767         return send_openflow_skb(skb, NULL);
768 }
769
770 int 
771 dp_send_flow_expired(struct datapath *dp, struct sw_flow *flow)
772 {
773         struct sk_buff *skb;
774         struct ofp_flow_expired *ofe;
775         unsigned long duration_j;
776
777         ofe = alloc_openflow_skb(dp, sizeof *ofe, OFPT_FLOW_EXPIRED, 0, &skb);
778         if (!ofe)
779                 return -ENOMEM;
780
781         flow_fill_match(&ofe->match, &flow->key);
782
783         memset(ofe->pad, 0, sizeof ofe->pad);
784         ofe->priority = htons(flow->priority);
785
786         duration_j = (flow->timeout - HZ * flow->max_idle) - flow->init_time;
787         ofe->duration     = htonl(duration_j / HZ);
788         ofe->packet_count = cpu_to_be64(flow->packet_count);
789         ofe->byte_count   = cpu_to_be64(flow->byte_count);
790
791         return send_openflow_skb(skb, NULL);
792 }
793 EXPORT_SYMBOL(dp_send_flow_expired);
794
795 int
796 dp_send_error_msg(struct datapath *dp, const struct sender *sender, 
797                 uint16_t type, uint16_t code, const uint8_t *data, size_t len)
798 {
799         struct sk_buff *skb;
800         struct ofp_error_msg *oem;
801
802
803         oem = alloc_openflow_skb(dp, sizeof(*oem)+len, OFPT_ERROR_MSG, 
804                         sender, &skb);
805         if (!oem)
806                 return -ENOMEM;
807
808         oem->type = htons(type);
809         oem->code = htons(code);
810         memcpy(oem->data, data, len);
811
812         return send_openflow_skb(skb, sender);
813 }
814
815 /* Generic Netlink interface.
816  *
817  * See netlink(7) for an introduction to netlink.  See
818  * http://linux-net.osdl.org/index.php/Netlink for more information and
819  * pointers on how to work with netlink and Generic Netlink in the kernel and
820  * in userspace. */
821
822 static struct genl_family dp_genl_family = {
823         .id = GENL_ID_GENERATE,
824         .hdrsize = 0,
825         .name = DP_GENL_FAMILY_NAME,
826         .version = 1,
827         .maxattr = DP_GENL_A_MAX,
828 };
829
830 /* Attribute policy: what each attribute may contain.  */
831 static struct nla_policy dp_genl_policy[DP_GENL_A_MAX + 1] = {
832         [DP_GENL_A_DP_IDX] = { .type = NLA_U32 },
833         [DP_GENL_A_MC_GROUP] = { .type = NLA_U32 },
834         [DP_GENL_A_PORTNAME] = { .type = NLA_STRING }
835 };
836
837 static int dp_genl_add(struct sk_buff *skb, struct genl_info *info)
838 {
839         if (!info->attrs[DP_GENL_A_DP_IDX])
840                 return -EINVAL;
841
842         return new_dp(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
843 }
844
845 static struct genl_ops dp_genl_ops_add_dp = {
846         .cmd = DP_GENL_C_ADD_DP,
847         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
848         .policy = dp_genl_policy,
849         .doit = dp_genl_add,
850         .dumpit = NULL,
851 };
852
853 struct datapath *dp_get(int dp_idx)
854 {
855         if (dp_idx < 0 || dp_idx > DP_MAX)
856                 return NULL;
857         return rcu_dereference(dps[dp_idx]);
858 }
859
860 static int dp_genl_del(struct sk_buff *skb, struct genl_info *info)
861 {
862         struct datapath *dp;
863         int err;
864
865         if (!info->attrs[DP_GENL_A_DP_IDX])
866                 return -EINVAL;
867
868         mutex_lock(&dp_mutex);
869         dp = dp_get(nla_get_u32((info->attrs[DP_GENL_A_DP_IDX])));
870         if (!dp)
871                 err = -ENOENT;
872         else {
873                 del_dp(dp);
874                 err = 0;
875         }
876         mutex_unlock(&dp_mutex);
877         return err;
878 }
879
880 static struct genl_ops dp_genl_ops_del_dp = {
881         .cmd = DP_GENL_C_DEL_DP,
882         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
883         .policy = dp_genl_policy,
884         .doit = dp_genl_del,
885         .dumpit = NULL,
886 };
887
888 /* Queries a datapath for related information.  Currently the only relevant
889  * information is the datapath's multicast group ID.  Really we want one
890  * multicast group per datapath, but because of locking issues[*] we can't
891  * easily get one.  Thus, every datapath will currently return the same
892  * global multicast group ID, but in the future it would be nice to fix that.
893  *
894  * [*] dp_genl_add, to add a new datapath, is called under the genl_lock
895  *       mutex, and genl_register_mc_group, called to acquire a new multicast
896  *       group ID, also acquires genl_lock, thus deadlock.
897  */
898 static int dp_genl_query(struct sk_buff *skb, struct genl_info *info)
899 {
900         struct datapath *dp;
901         struct sk_buff *ans_skb = NULL;
902         int dp_idx;
903         int err = -ENOMEM;
904
905         if (!info->attrs[DP_GENL_A_DP_IDX])
906                 return -EINVAL;
907
908         rcu_read_lock();
909         dp_idx = nla_get_u32((info->attrs[DP_GENL_A_DP_IDX]));
910         dp = dp_get(dp_idx);
911         if (!dp)
912                 err = -ENOENT;
913         else {
914                 void *data;
915                 ans_skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
916                 if (!ans_skb) {
917                         err = -ENOMEM;
918                         goto err;
919                 }
920                 data = genlmsg_put_reply(ans_skb, info, &dp_genl_family,
921                                          0, DP_GENL_C_QUERY_DP);
922                 if (data == NULL) {
923                         err = -ENOMEM;
924                         goto err;
925                 }
926                 NLA_PUT_U32(ans_skb, DP_GENL_A_DP_IDX, dp_idx);
927                 NLA_PUT_U32(ans_skb, DP_GENL_A_MC_GROUP, mc_group.id);
928
929                 genlmsg_end(ans_skb, data);
930                 err = genlmsg_reply(ans_skb, info);
931                 if (!err)
932                         ans_skb = NULL;
933         }
934 err:
935 nla_put_failure:
936         if (ans_skb)
937                 kfree_skb(ans_skb);
938         rcu_read_unlock();
939         return err;
940 }
941
942 static struct genl_ops dp_genl_ops_query_dp = {
943         .cmd = DP_GENL_C_QUERY_DP,
944         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
945         .policy = dp_genl_policy,
946         .doit = dp_genl_query,
947         .dumpit = NULL,
948 };
949
950 static int dp_genl_add_del_port(struct sk_buff *skb, struct genl_info *info)
951 {
952         struct datapath *dp;
953         struct net_device *port;
954         int err;
955
956         if (!info->attrs[DP_GENL_A_DP_IDX] || !info->attrs[DP_GENL_A_PORTNAME])
957                 return -EINVAL;
958
959         /* Get datapath. */
960         mutex_lock(&dp_mutex);
961         dp = dp_get(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
962         if (!dp) {
963                 err = -ENOENT;
964                 goto out;
965         }
966
967         /* Get interface to add/remove. */
968         port = dev_get_by_name(&init_net, 
969                         nla_data(info->attrs[DP_GENL_A_PORTNAME]));
970         if (!port) {
971                 err = -ENOENT;
972                 goto out;
973         }
974
975         /* Execute operation. */
976         if (info->genlhdr->cmd == DP_GENL_C_ADD_PORT)
977                 err = add_switch_port(dp, port);
978         else {
979                 if (port->br_port == NULL || port->br_port->dp != dp) {
980                         err = -ENOENT;
981                         goto out_put;
982                 }
983                 err = del_switch_port(port->br_port);
984         }
985
986 out_put:
987         dev_put(port);
988 out:
989         mutex_unlock(&dp_mutex);
990         return err;
991 }
992
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,
998         .dumpit = NULL,
999 };
1000
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,
1006         .dumpit = NULL,
1007 };
1008
1009 static int dp_genl_openflow(struct sk_buff *skb, struct genl_info *info)
1010 {
1011         struct nlattr *va = info->attrs[DP_GENL_A_OPENFLOW];
1012         struct datapath *dp;
1013         struct ofp_header *oh;
1014         struct sender sender;
1015         int err;
1016
1017         if (!info->attrs[DP_GENL_A_DP_IDX] || !va)
1018                 return -EINVAL;
1019
1020         rcu_read_lock();
1021         dp = dp_get(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
1022         if (!dp) {
1023                 err = -ENOENT;
1024                 goto out;
1025         }
1026
1027         if (nla_len(va) < sizeof(struct ofp_header)) {
1028                 err = -EINVAL;
1029                 goto out;
1030         }
1031         oh = nla_data(va);
1032
1033         sender.xid = oh->xid;
1034         sender.pid = info->snd_pid;
1035         sender.seq = info->snd_seq;
1036         err = fwd_control_input(dp->chain, &sender, nla_data(va), nla_len(va));
1037
1038 out:
1039         rcu_read_unlock();
1040         return err;
1041 }
1042
1043 static struct nla_policy dp_genl_openflow_policy[DP_GENL_A_MAX + 1] = {
1044         [DP_GENL_A_DP_IDX] = { .type = NLA_U32 },
1045 };
1046
1047 struct flow_stats_state {
1048         int table_idx;
1049         struct sw_table_position position;
1050         const struct ofp_flow_stats_request *rq;
1051
1052         void *body;
1053         int bytes_used, bytes_allocated;
1054 };
1055
1056 static int flow_stats_init(struct datapath *dp, const void *body, int body_len,
1057                            void **state)
1058 {
1059         const struct ofp_flow_stats_request *fsr = body;
1060         struct flow_stats_state *s = kmalloc(sizeof *s, GFP_ATOMIC);
1061         if (!s)
1062                 return -ENOMEM;
1063         s->table_idx = fsr->table_id == 0xff ? 0 : fsr->table_id;
1064         memset(&s->position, 0, sizeof s->position);
1065         s->rq = fsr;
1066         *state = s;
1067         return 0;
1068 }
1069
1070 static int flow_stats_dump_callback(struct sw_flow *flow, void *private)
1071 {
1072         struct flow_stats_state *s = private;
1073         struct ofp_flow_stats *ofs;
1074         int actions_length;
1075         int length;
1076
1077         actions_length = sizeof *ofs->actions * flow->n_actions;
1078         length = sizeof *ofs + sizeof *ofs->actions * flow->n_actions;
1079         if (length + s->bytes_used > s->bytes_allocated)
1080                 return 1;
1081
1082         ofs = s->body + s->bytes_used;
1083         ofs->length          = htons(length);
1084         ofs->table_id        = s->table_idx;
1085         ofs->pad             = 0;
1086         ofs->match.wildcards = htons(flow->key.wildcards);
1087         ofs->match.in_port   = flow->key.in_port;
1088         memcpy(ofs->match.dl_src, flow->key.dl_src, ETH_ALEN);
1089         memcpy(ofs->match.dl_dst, flow->key.dl_dst, ETH_ALEN);
1090         ofs->match.dl_vlan   = flow->key.dl_vlan;
1091         ofs->match.dl_type   = flow->key.dl_type;
1092         ofs->match.nw_src    = flow->key.nw_src;
1093         ofs->match.nw_dst    = flow->key.nw_dst;
1094         ofs->match.nw_proto  = flow->key.nw_proto;
1095         memset(ofs->match.pad, 0, sizeof ofs->match.pad);
1096         ofs->match.tp_src    = flow->key.tp_src;
1097         ofs->match.tp_dst    = flow->key.tp_dst;
1098         ofs->duration        = htonl((jiffies - flow->init_time) / HZ);
1099         ofs->packet_count    = cpu_to_be64(flow->packet_count);
1100         ofs->byte_count      = cpu_to_be64(flow->byte_count);
1101         ofs->priority        = htons(flow->priority);
1102         ofs->max_idle        = htons(flow->max_idle);
1103         memcpy(ofs->actions, flow->actions, actions_length);
1104
1105         s->bytes_used += length;
1106         return 0;
1107 }
1108
1109 static int flow_stats_dump(struct datapath *dp, void *state,
1110                            void *body, int *body_len)
1111 {
1112         struct flow_stats_state *s = state;
1113         struct sw_flow_key match_key;
1114         int error = 0;
1115
1116         s->bytes_used = 0;
1117         s->bytes_allocated = *body_len;
1118         s->body = body;
1119
1120         flow_extract_match(&match_key, &s->rq->match);
1121         while (s->table_idx < dp->chain->n_tables
1122                && (s->rq->table_id == 0xff || s->rq->table_id == s->table_idx))
1123         {
1124                 struct sw_table *table = dp->chain->tables[s->table_idx];
1125
1126                 error = table->iterate(table, &match_key, &s->position,
1127                                        flow_stats_dump_callback, s);
1128                 if (error)
1129                         break;
1130
1131                 s->table_idx++;
1132                 memset(&s->position, 0, sizeof s->position);
1133         }
1134         *body_len = s->bytes_used;
1135
1136         /* If error is 0, we're done.
1137          * Otherwise, if some bytes were used, there are more flows to come.
1138          * Otherwise, we were not able to fit even a single flow in the body,
1139          * which indicates that we have a single flow with too many actions to
1140          * fit.  We won't ever make any progress at that rate, so give up. */
1141         return !error ? 0 : s->bytes_used ? 1 : -ENOMEM;
1142 }
1143
1144 static void flow_stats_done(void *state)
1145 {
1146         kfree(state);
1147 }
1148
1149 static int aggregate_stats_init(struct datapath *dp,
1150                                 const void *body, int body_len,
1151                                 void **state)
1152 {
1153         *state = (void *)body;
1154         return 0;
1155 }
1156
1157 static int aggregate_stats_dump_callback(struct sw_flow *flow, void *private)
1158 {
1159         struct ofp_aggregate_stats_reply *rpy = private;
1160         rpy->packet_count += flow->packet_count;
1161         rpy->byte_count += flow->byte_count;
1162         rpy->flow_count++;
1163         return 0;
1164 }
1165
1166 static int aggregate_stats_dump(struct datapath *dp, void *state,
1167                                 void *body, int *body_len)
1168 {
1169         struct ofp_aggregate_stats_request *rq = state;
1170         struct ofp_aggregate_stats_reply *rpy;
1171         struct sw_table_position position;
1172         struct sw_flow_key match_key;
1173         int table_idx;
1174
1175         if (*body_len < sizeof *rpy)
1176                 return -ENOBUFS;
1177         rpy = body;
1178         *body_len = sizeof *rpy;
1179
1180         memset(rpy, 0, sizeof *rpy);
1181
1182         flow_extract_match(&match_key, &rq->match);
1183         table_idx = rq->table_id == 0xff ? 0 : rq->table_id;
1184         memset(&position, 0, sizeof position);
1185         while (table_idx < dp->chain->n_tables
1186                && (rq->table_id == 0xff || rq->table_id == table_idx))
1187         {
1188                 struct sw_table *table = dp->chain->tables[table_idx];
1189                 int error;
1190
1191                 error = table->iterate(table, &match_key, &position,
1192                                        aggregate_stats_dump_callback, rpy);
1193                 if (error)
1194                         return error;
1195
1196                 table_idx++;
1197                 memset(&position, 0, sizeof position);
1198         }
1199
1200         rpy->packet_count = cpu_to_be64(rpy->packet_count);
1201         rpy->byte_count = cpu_to_be64(rpy->byte_count);
1202         rpy->flow_count = htonl(rpy->flow_count);
1203         return 0;
1204 }
1205
1206 static int table_stats_dump(struct datapath *dp, void *state,
1207                             void *body, int *body_len)
1208 {
1209         struct ofp_table_stats *ots;
1210         int nbytes = dp->chain->n_tables * sizeof *ots;
1211         int i;
1212         if (nbytes > *body_len)
1213                 return -ENOBUFS;
1214         *body_len = nbytes;
1215         for (i = 0, ots = body; i < dp->chain->n_tables; i++, ots++) {
1216                 struct sw_table_stats stats;
1217                 dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
1218                 strncpy(ots->name, stats.name, sizeof ots->name);
1219                 ots->table_id = i;
1220                 memset(ots->pad, 0, sizeof ots->pad);
1221                 ots->max_entries = htonl(stats.max_flows);
1222                 ots->active_count = htonl(stats.n_flows);
1223                 ots->matched_count = cpu_to_be64(0); /* FIXME */
1224         }
1225         return 0;
1226 }
1227
1228 struct port_stats_state {
1229         int port;
1230 };
1231
1232 static int port_stats_init(struct datapath *dp, const void *body, int body_len,
1233                            void **state)
1234 {
1235         struct port_stats_state *s = kmalloc(sizeof *s, GFP_ATOMIC);
1236         if (!s)
1237                 return -ENOMEM;
1238         s->port = 0;
1239         *state = s;
1240         return 0;
1241 }
1242
1243 static int port_stats_dump(struct datapath *dp, void *state,
1244                            void *body, int *body_len)
1245 {
1246         struct port_stats_state *s = state;
1247         struct ofp_port_stats *ops;
1248         int n_ports, max_ports;
1249         int i;
1250
1251         max_ports = *body_len / sizeof *ops;
1252         if (!max_ports)
1253                 return -ENOMEM;
1254         ops = body;
1255
1256         n_ports = 0;
1257         for (i = s->port; i < OFPP_MAX && n_ports < max_ports; i++) {
1258                 struct net_bridge_port *p = dp->ports[i];
1259                 struct net_device_stats *stats;
1260                 if (!p)
1261                         continue;
1262                 stats = p->dev->get_stats(p->dev);
1263                 ops->port_no = htons(p->port_no);
1264                 memset(ops->pad, 0, sizeof ops->pad);
1265                 ops->rx_count = cpu_to_be64(stats->rx_packets);
1266                 ops->tx_count = cpu_to_be64(stats->tx_packets);
1267                 ops->drop_count = cpu_to_be64(stats->rx_dropped
1268                                               + stats->tx_dropped);
1269                 n_ports++;
1270                 ops++;
1271         }
1272         s->port = i;
1273         *body_len = n_ports * sizeof *ops;
1274         return n_ports >= max_ports;
1275 }
1276
1277 static void port_stats_done(void *state)
1278 {
1279         kfree(state);
1280 }
1281
1282 struct stats_type {
1283         /* Minimum and maximum acceptable number of bytes in body member of
1284          * struct ofp_stats_request. */
1285         size_t min_body, max_body;
1286
1287         /* Prepares to dump some kind of statistics on 'dp'.  'body' and
1288          * 'body_len' are the 'body' member of the struct ofp_stats_request.
1289          * Returns zero if successful, otherwise a negative error code.
1290          * May initialize '*state' to state information.  May be null if no
1291          * initialization is required.*/
1292         int (*init)(struct datapath *dp, const void *body, int body_len,
1293                     void **state);
1294
1295         /* Dumps statistics for 'dp' into the '*body_len' bytes at 'body', and
1296          * modifies '*body_len' to reflect the number of bytes actually used.
1297          * ('body' will be transmitted as the 'body' member of struct
1298          * ofp_stats_reply.) */
1299         int (*dump)(struct datapath *dp, void *state,
1300                     void *body, int *body_len);
1301
1302         /* Cleans any state created by the init or dump functions.  May be null
1303          * if no cleanup is required. */
1304         void (*done)(void *state);
1305 };
1306
1307 static const struct stats_type stats[] = {
1308         [OFPST_FLOW] = {
1309                 sizeof(struct ofp_flow_stats_request),
1310                 sizeof(struct ofp_flow_stats_request),
1311                 flow_stats_init,
1312                 flow_stats_dump,
1313                 flow_stats_done
1314         },
1315         [OFPST_AGGREGATE] = {
1316                 sizeof(struct ofp_aggregate_stats_request),
1317                 sizeof(struct ofp_aggregate_stats_request),
1318                 aggregate_stats_init,
1319                 aggregate_stats_dump,
1320                 NULL
1321         },
1322         [OFPST_TABLE] = {
1323                 0,
1324                 0,
1325                 NULL,
1326                 table_stats_dump,
1327                 NULL
1328         },
1329         [OFPST_PORT] = {
1330                 0,
1331                 0,
1332                 port_stats_init,
1333                 port_stats_dump,
1334                 port_stats_done
1335         },
1336 };
1337
1338 static int
1339 dp_genl_openflow_dumpit(struct sk_buff *skb, struct netlink_callback *cb)
1340 {
1341         struct datapath *dp;
1342         struct sender sender;
1343         const struct stats_type *s;
1344         struct ofp_stats_reply *osr;
1345         int dp_idx;
1346         int max_openflow_len, body_len;
1347         void *body;
1348         int err;
1349
1350         /* Set up the cleanup function for this dump.  Linux 2.6.20 and later
1351          * support setting up cleanup functions via the .doneit member of
1352          * struct genl_ops.  This kluge supports earlier versions also. */
1353         cb->done = dp_genl_openflow_done;
1354
1355         rcu_read_lock();
1356         if (!cb->args[0]) {
1357                 struct nlattr *attrs[DP_GENL_A_MAX + 1];
1358                 struct ofp_stats_request *rq;
1359                 struct nlattr *va;
1360                 size_t len, body_len;
1361                 int type;
1362
1363                 err = nlmsg_parse(cb->nlh, GENL_HDRLEN, attrs, DP_GENL_A_MAX,
1364                                   dp_genl_openflow_policy);
1365                 if (err < 0)
1366                         return err;
1367
1368                 err = -EINVAL;
1369
1370                 if (!attrs[DP_GENL_A_DP_IDX])
1371                         goto out;
1372                 dp_idx = nla_get_u16(attrs[DP_GENL_A_DP_IDX]);
1373                 dp = dp_get(dp_idx);
1374                 if (!dp) {
1375                         err = -ENOENT;
1376                         goto out;
1377                 }
1378
1379                 va = attrs[DP_GENL_A_OPENFLOW];
1380                 len = nla_len(va);
1381                 if (!va || len < sizeof *rq)
1382                         goto out;
1383
1384                 rq = nla_data(va);
1385                 type = ntohs(rq->type);
1386                 if (rq->header.version != OFP_VERSION
1387                     || rq->header.type != OFPT_STATS_REQUEST
1388                     || ntohs(rq->header.length) != len
1389                     || type >= ARRAY_SIZE(stats)
1390                     || !stats[type].dump)
1391                         goto out;
1392
1393                 s = &stats[type];
1394                 body_len = len - offsetof(struct ofp_stats_request, body);
1395                 if (body_len < s->min_body || body_len > s->max_body)
1396                         goto out;
1397
1398                 cb->args[0] = 1;
1399                 cb->args[1] = dp_idx;
1400                 cb->args[2] = type;
1401                 cb->args[3] = rq->header.xid;
1402                 if (s->init) {
1403                         void *state;
1404                         err = s->init(dp, rq->body, body_len, &state);
1405                         if (err)
1406                                 goto out;
1407                         cb->args[4] = (long) state;
1408                 }
1409         } else if (cb->args[0] == 1) {
1410                 dp_idx = cb->args[1];
1411                 s = &stats[cb->args[2]];
1412
1413                 dp = dp_get(dp_idx);
1414                 if (!dp) {
1415                         err = -ENOENT;
1416                         goto out;
1417                 }
1418         } else {
1419                 err = 0;
1420                 goto out;
1421         }
1422
1423         sender.xid = cb->args[3];
1424         sender.pid = NETLINK_CB(cb->skb).pid;
1425         sender.seq = cb->nlh->nlmsg_seq;
1426
1427         osr = put_openflow_headers(dp, skb, OFPT_STATS_REPLY, &sender,
1428                                    &max_openflow_len);
1429         if (IS_ERR(osr)) {
1430                 err = PTR_ERR(osr);
1431                 goto out;
1432         }
1433         osr->type = htons(s - stats);
1434         osr->flags = 0;
1435         resize_openflow_skb(skb, &osr->header, max_openflow_len);
1436         body = osr->body;
1437         body_len = max_openflow_len - offsetof(struct ofp_stats_reply, body);
1438
1439         err = s->dump(dp, (void *) cb->args[4], body, &body_len);
1440         if (err >= 0) {
1441                 if (!err)
1442                         cb->args[0] = 2;
1443                 else
1444                         osr->flags = ntohs(OFPSF_REPLY_MORE);
1445                 resize_openflow_skb(skb, &osr->header,
1446                                     (offsetof(struct ofp_stats_reply, body)
1447                                      + body_len));
1448                 err = skb->len;
1449         }
1450
1451 out:
1452         rcu_read_unlock();
1453         return err;
1454 }
1455
1456 static int
1457 dp_genl_openflow_done(struct netlink_callback *cb)
1458 {
1459         if (cb->args[0]) {
1460                 const struct stats_type *s = &stats[cb->args[2]];
1461                 if (s->done)
1462                         s->done((void *) cb->args[4]);
1463         }
1464         return 0;
1465 }
1466
1467 static struct genl_ops dp_genl_ops_openflow = {
1468         .cmd = DP_GENL_C_OPENFLOW,
1469         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1470         .policy = dp_genl_openflow_policy,
1471         .doit = dp_genl_openflow,
1472         .dumpit = dp_genl_openflow_dumpit,
1473 };
1474
1475 static struct nla_policy dp_genl_benchmark_policy[DP_GENL_A_MAX + 1] = {
1476         [DP_GENL_A_DP_IDX] = { .type = NLA_U32 },
1477         [DP_GENL_A_NPACKETS] = { .type = NLA_U32 },
1478         [DP_GENL_A_PSIZE] = { .type = NLA_U32 },
1479 };
1480
1481 static struct genl_ops dp_genl_ops_benchmark_nl = {
1482         .cmd = DP_GENL_C_BENCHMARK_NL,
1483         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1484         .policy = dp_genl_benchmark_policy,
1485         .doit = dp_genl_benchmark_nl,
1486         .dumpit = NULL,
1487 };
1488
1489 static struct genl_ops *dp_genl_all_ops[] = {
1490         /* Keep this operation first.  Generic Netlink dispatching
1491          * looks up operations with linear search, so we want it at the
1492          * front. */
1493         &dp_genl_ops_openflow,
1494
1495         &dp_genl_ops_add_dp,
1496         &dp_genl_ops_del_dp,
1497         &dp_genl_ops_query_dp,
1498         &dp_genl_ops_add_port,
1499         &dp_genl_ops_del_port,
1500         &dp_genl_ops_benchmark_nl,
1501 };
1502
1503 static int dp_init_netlink(void)
1504 {
1505         int err;
1506         int i;
1507
1508         err = genl_register_family(&dp_genl_family);
1509         if (err)
1510                 return err;
1511
1512         for (i = 0; i < ARRAY_SIZE(dp_genl_all_ops); i++) {
1513                 err = genl_register_ops(&dp_genl_family, dp_genl_all_ops[i]);
1514                 if (err)
1515                         goto err_unregister;
1516         }
1517
1518         strcpy(mc_group.name, "openflow");
1519         err = genl_register_mc_group(&dp_genl_family, &mc_group);
1520         if (err < 0)
1521                 goto err_unregister;
1522
1523         return 0;
1524
1525 err_unregister:
1526         genl_unregister_family(&dp_genl_family);
1527                 return err;
1528 }
1529
1530 static void dp_uninit_netlink(void)
1531 {
1532         genl_unregister_family(&dp_genl_family);
1533 }
1534
1535 #define DRV_NAME                "openflow"
1536 #define DRV_VERSION      VERSION
1537 #define DRV_DESCRIPTION "OpenFlow switching datapath implementation"
1538 #define DRV_COPYRIGHT   "Copyright (c) 2007, 2008 The Board of Trustees of The Leland Stanford Junior University"
1539
1540
1541 static int __init dp_init(void)
1542 {
1543         int err;
1544
1545         printk(KERN_INFO DRV_NAME ": " DRV_DESCRIPTION "\n");
1546         printk(KERN_INFO DRV_NAME ": " VERSION" built on "__DATE__" "__TIME__"\n");
1547         printk(KERN_INFO DRV_NAME ": " DRV_COPYRIGHT "\n");
1548
1549         err = flow_init();
1550         if (err)
1551                 goto error;
1552
1553         err = dp_init_netlink();
1554         if (err)
1555                 goto error_flow_exit;
1556
1557         /* Hook into callback used by the bridge to intercept packets.
1558          * Parasites we are. */
1559         if (br_handle_frame_hook)
1560                 printk("openflow: hijacking bridge hook\n");
1561         br_handle_frame_hook = dp_frame_hook;
1562
1563         return 0;
1564
1565 error_flow_exit:
1566         flow_exit();
1567 error:
1568         printk(KERN_EMERG "openflow: failed to install!");
1569         return err;
1570 }
1571
1572 static void dp_cleanup(void)
1573 {
1574         fwd_exit();
1575         dp_uninit_netlink();
1576         flow_exit();
1577         br_handle_frame_hook = NULL;
1578 }
1579
1580 module_init(dp_init);
1581 module_exit(dp_cleanup);
1582
1583 MODULE_DESCRIPTION(DRV_DESCRIPTION);
1584 MODULE_AUTHOR(DRV_COPYRIGHT);
1585 MODULE_LICENSE("GPL");