Don't oops on deldp, by avoiding use-after-free on net_bridge_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, *n;
410
411         kthread_stop(dp->dp_task);
412
413         /* Drop references to DP. */
414         list_for_each_entry_safe (p, n, &dp->port_list, node)
415                 del_switch_port(p);
416         rcu_assign_pointer(dps[dp->dp_idx], NULL);
417
418         /* Destroy dp->netdev.  (Must follow deleting switch ports since
419          * dp->local_port has a reference to it.) */
420         dp_dev_destroy(dp);
421
422         /* Wait until no longer in use, then destroy it. */
423         synchronize_rcu();
424         chain_destroy(dp->chain);
425         kfree(dp);
426         module_put(THIS_MODULE);
427 }
428
429 static int dp_maint_func(void *data)
430 {
431         struct datapath *dp = (struct datapath *) data;
432
433         while (!kthread_should_stop()) {
434                 chain_timeout(dp->chain);
435                 msleep_interruptible(MAINT_SLEEP_MSECS);
436         }
437                 
438         return 0;
439 }
440
441 static void
442 do_port_input(struct net_bridge_port *p, struct sk_buff *skb) 
443 {
444         /* Push the Ethernet header back on. */
445         if (skb->protocol == htons(ETH_P_8021Q))
446                 skb_push(skb, VLAN_ETH_HLEN);
447         else
448                 skb_push(skb, ETH_HLEN);
449         fwd_port_input(p->dp->chain, skb, p->port_no);
450 }
451
452 /*
453  * Used as br_handle_frame_hook.  (Cannot run bridge at the same time, even on
454  * different set of devices!)
455  */
456 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
457 /* Called with rcu_read_lock. */
458 static struct sk_buff *dp_frame_hook(struct net_bridge_port *p,
459                                          struct sk_buff *skb)
460 {
461         do_port_input(p, skb);
462         return NULL;
463 }
464 #elif LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
465 static int dp_frame_hook(struct net_bridge_port *p, struct sk_buff **pskb)
466 {
467         do_port_input(p, *pskb);
468         return 1;
469 }
470 #else
471 /* NB: This has only been tested on 2.4.35 */
472
473 /* Called without any locks (?) */
474 static void dp_frame_hook(struct sk_buff *skb)
475 {
476         struct net_bridge_port *p = skb->dev->br_port;
477         if (p) {
478                 rcu_read_lock();
479                 do_port_input(p, skb);
480                 rcu_read_unlock();
481         } else
482                 kfree_skb(skb);
483 }
484 #endif
485
486 /* Forwarding output path.
487  * Based on net/bridge/br_forward.c. */
488
489 static inline unsigned packet_length(const struct sk_buff *skb)
490 {
491         int length = skb->len - ETH_HLEN;
492         if (skb->protocol == htons(ETH_P_8021Q))
493                 length -= VLAN_HLEN;
494         return length;
495 }
496
497 /* Send packets out all the ports except the originating one.  If the
498  * "flood" argument is set, only send along the minimum spanning tree.
499  */
500 static int
501 output_all(struct datapath *dp, struct sk_buff *skb, int flood)
502 {
503         u32 disable = flood ? BRIDGE_PORT_NO_FLOOD : 0;
504         struct net_bridge_port *p;
505         int prev_port = -1;
506
507         list_for_each_entry_rcu (p, &dp->port_list, node) {
508                 if (skb->dev == p->dev || p->flags & disable)
509                         continue;
510                 if (prev_port != -1) {
511                         struct sk_buff *clone = skb_clone(skb, GFP_ATOMIC);
512                         if (!clone) {
513                                 kfree_skb(skb);
514                                 return -ENOMEM;
515                         }
516                         dp_output_port(dp, clone, prev_port); 
517                 }
518                 prev_port = p->port_no;
519         }
520         if (prev_port != -1)
521                 dp_output_port(dp, skb, prev_port);
522         else
523                 kfree_skb(skb);
524
525         return 0;
526 }
527
528 /* Marks 'skb' as having originated from 'in_port' in 'dp'.
529    FIXME: how are devices reference counted? */
530 int dp_set_origin(struct datapath *dp, uint16_t in_port,
531                            struct sk_buff *skb)
532 {
533         struct net_bridge_port *p = (in_port < OFPP_MAX ? dp->ports[in_port]
534                                      : in_port == OFPP_LOCAL ? dp->local_port
535                                      : NULL);
536         if (p) {
537                 skb->dev = p->dev;
538                 return 0;
539         }
540         return -ENOENT;
541 }
542
543 /* Takes ownership of 'skb' and transmits it to 'out_port' on 'dp'.
544  */
545 int dp_output_port(struct datapath *dp, struct sk_buff *skb, int out_port)
546 {
547         BUG_ON(!skb);
548         if (out_port == OFPP_FLOOD)
549                 return output_all(dp, skb, 1);
550         else if (out_port == OFPP_ALL)
551                 return output_all(dp, skb, 0);
552         else if (out_port == OFPP_CONTROLLER)
553                 return dp_output_control(dp, skb, fwd_save_skb(skb), 0,
554                                                   OFPR_ACTION);
555         else if (out_port == OFPP_TABLE) {
556                 struct net_bridge_port *p = skb->dev->br_port;
557                 struct sw_flow_key key;
558                 struct sw_flow *flow;
559
560                 flow_extract(skb, p ? p->port_no : OFPP_LOCAL, &key);
561                 flow = chain_lookup(dp->chain, &key);
562                 if (likely(flow != NULL)) {
563                         flow_used(flow, skb);
564                         execute_actions(dp, skb, &key, flow->actions, flow->n_actions);
565                         return 0;
566                 }
567                 return -ESRCH;
568         } else if (out_port == OFPP_LOCAL) {
569                 struct net_device *dev = dp->netdev;
570                 return dev ? dp_dev_recv(dev, skb) : -ESRCH;
571         } else if (out_port >= 0 && out_port < OFPP_MAX) {
572                 struct net_bridge_port *p = dp->ports[out_port];
573                 int len = skb->len;
574                 if (p == NULL)
575                         goto bad_port;
576                 skb->dev = p->dev; 
577                 if (packet_length(skb) > skb->dev->mtu) {
578                         printk("dropped over-mtu packet: %d > %d\n",
579                                packet_length(skb), skb->dev->mtu);
580                         kfree_skb(skb);
581                         return -E2BIG;
582                 }
583
584                 dev_queue_xmit(skb);
585
586                 return len;
587         }
588
589 bad_port:
590         kfree_skb(skb);
591         if (net_ratelimit())
592                 printk("can't forward to bad port %d\n", out_port);
593         return -ENOENT;
594 }
595
596 /* Takes ownership of 'skb' and transmits it to 'dp''s control path.  If
597  * 'buffer_id' != -1, then only the first 64 bytes of 'skb' are sent;
598  * otherwise, all of 'skb' is sent.  'reason' indicates why 'skb' is being
599  * sent. 'max_len' sets the maximum number of bytes that the caller
600  * wants to be sent; a value of 0 indicates the entire packet should be
601  * sent. */
602 int
603 dp_output_control(struct datapath *dp, struct sk_buff *skb,
604                            uint32_t buffer_id, size_t max_len, int reason)
605 {
606         /* FIXME?  Can we avoid creating a new skbuff in the case where we
607          * forward the whole packet? */
608         struct sk_buff *f_skb;
609         struct ofp_packet_in *opi;
610         struct net_bridge_port *p;
611         size_t fwd_len, opi_len;
612         int err;
613
614         fwd_len = skb->len;
615         if ((buffer_id != (uint32_t) -1) && max_len)
616                 fwd_len = min(fwd_len, max_len);
617
618         opi_len = offsetof(struct ofp_packet_in, data) + fwd_len;
619         opi = alloc_openflow_skb(dp, opi_len, OFPT_PACKET_IN, NULL, &f_skb);
620         if (!opi) {
621                 err = -ENOMEM;
622                 goto out;
623         }
624         opi->buffer_id      = htonl(buffer_id);
625         opi->total_len      = htons(skb->len);
626         p = skb->dev->br_port;
627         opi->in_port        = htons(p ? p->port_no : OFPP_LOCAL);
628         opi->reason         = reason;
629         opi->pad            = 0;
630         memcpy(opi->data, skb_mac_header(skb), fwd_len);
631         err = send_openflow_skb(f_skb, NULL);
632
633 out:
634         kfree_skb(skb);
635         return err;
636 }
637
638 static void fill_port_desc(struct net_bridge_port *p, struct ofp_phy_port *desc)
639 {
640         desc->port_no = htons(p->port_no);
641         strncpy(desc->name, p->dev->name, OFP_MAX_PORT_NAME_LEN);
642         desc->name[OFP_MAX_PORT_NAME_LEN-1] = '\0';
643         memcpy(desc->hw_addr, p->dev->dev_addr, ETH_ALEN);
644         desc->flags = htonl(p->flags);
645         desc->features = 0;
646         desc->speed = 0;
647
648 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,24)
649         if (p->dev->ethtool_ops && p->dev->ethtool_ops->get_settings) {
650                 struct ethtool_cmd ecmd = { .cmd = ETHTOOL_GSET };
651
652                 if (!p->dev->ethtool_ops->get_settings(p->dev, &ecmd)) {
653                         if (ecmd.supported & SUPPORTED_10baseT_Half) 
654                                 desc->features |= OFPPF_10MB_HD;
655                         if (ecmd.supported & SUPPORTED_10baseT_Full)
656                                 desc->features |= OFPPF_10MB_FD;
657                         if (ecmd.supported & SUPPORTED_100baseT_Half) 
658                                 desc->features |= OFPPF_100MB_HD;
659                         if (ecmd.supported & SUPPORTED_100baseT_Full)
660                                 desc->features |= OFPPF_100MB_FD;
661                         if (ecmd.supported & SUPPORTED_1000baseT_Half)
662                                 desc->features |= OFPPF_1GB_HD;
663                         if (ecmd.supported & SUPPORTED_1000baseT_Full)
664                                 desc->features |= OFPPF_1GB_FD;
665                         /* 10Gbps half-duplex doesn't exist... */
666                         if (ecmd.supported & SUPPORTED_10000baseT_Full)
667                                 desc->features |= OFPPF_10GB_FD;
668
669                         desc->features = htonl(desc->features);
670                         desc->speed = htonl(ecmd.speed);
671                 }
672         }
673 #endif
674 }
675
676 static int 
677 fill_features_reply(struct datapath *dp, struct ofp_switch_features *ofr)
678 {
679         struct net_bridge_port *p;
680         int port_count = 0;
681
682         ofr->datapath_id    = cpu_to_be64(dp->id); 
683
684         ofr->n_exact        = htonl(2 * TABLE_HASH_MAX_FLOWS);
685         ofr->n_compression  = 0;                                           /* Not supported */
686         ofr->n_general      = htonl(TABLE_LINEAR_MAX_FLOWS);
687         ofr->buffer_mb      = htonl(UINT32_MAX);
688         ofr->n_buffers      = htonl(N_PKT_BUFFERS);
689         ofr->capabilities   = htonl(OFP_SUPPORTED_CAPABILITIES);
690         ofr->actions        = htonl(OFP_SUPPORTED_ACTIONS);
691
692         list_for_each_entry_rcu (p, &dp->port_list, node) {
693                 fill_port_desc(p, &ofr->ports[port_count]);
694                 port_count++;
695         }
696
697         return port_count;
698 }
699
700 int
701 dp_send_features_reply(struct datapath *dp, const struct sender *sender)
702 {
703         struct sk_buff *skb;
704         struct ofp_switch_features *ofr;
705         size_t ofr_len, port_max_len;
706         int port_count;
707
708         /* Overallocate. */
709         port_max_len = sizeof(struct ofp_phy_port) * OFPP_MAX;
710         ofr = alloc_openflow_skb(dp, sizeof(*ofr) + port_max_len,
711                                  OFPT_FEATURES_REPLY, sender, &skb);
712         if (!ofr)
713                 return -ENOMEM;
714
715         /* Fill. */
716         port_count = fill_features_reply(dp, ofr);
717
718         /* Shrink to fit. */
719         ofr_len = sizeof(*ofr) + (sizeof(struct ofp_phy_port) * port_count);
720         resize_openflow_skb(skb, &ofr->header, ofr_len);
721         return send_openflow_skb(skb, sender);
722 }
723
724 int
725 dp_send_config_reply(struct datapath *dp, const struct sender *sender)
726 {
727         struct sk_buff *skb;
728         struct ofp_switch_config *osc;
729
730         osc = alloc_openflow_skb(dp, sizeof *osc, OFPT_GET_CONFIG_REPLY, sender,
731                                  &skb);
732         if (!osc)
733                 return -ENOMEM;
734
735         osc->flags = htons(dp->flags);
736         osc->miss_send_len = htons(dp->miss_send_len);
737
738         return send_openflow_skb(skb, sender);
739 }
740
741 int
742 dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp)
743 {
744         int port_no = ntohs(opp->port_no);
745         struct net_bridge_port *p = (port_no < OFPP_MAX ? dp->ports[port_no]
746                                      : port_no == OFPP_LOCAL ? dp->local_port
747                                      : NULL);
748         /* Make sure the port id hasn't changed since this was sent */
749         if (!p || memcmp(opp->hw_addr, p->dev->dev_addr, ETH_ALEN))
750                 return -1;
751         p->flags = htonl(opp->flags);
752         return 0;
753 }
754
755
756 static int
757 send_port_status(struct net_bridge_port *p, uint8_t status)
758 {
759         struct sk_buff *skb;
760         struct ofp_port_status *ops;
761
762         ops = alloc_openflow_skb(p->dp, sizeof *ops, OFPT_PORT_STATUS, NULL,
763                                  &skb);
764         if (!ops)
765                 return -ENOMEM;
766         ops->reason = status;
767         memset(ops->pad, 0, sizeof ops->pad);
768         fill_port_desc(p, &ops->desc);
769
770         return send_openflow_skb(skb, NULL);
771 }
772
773 int 
774 dp_send_flow_expired(struct datapath *dp, struct sw_flow *flow)
775 {
776         struct sk_buff *skb;
777         struct ofp_flow_expired *ofe;
778         unsigned long duration_j;
779
780         ofe = alloc_openflow_skb(dp, sizeof *ofe, OFPT_FLOW_EXPIRED, 0, &skb);
781         if (!ofe)
782                 return -ENOMEM;
783
784         flow_fill_match(&ofe->match, &flow->key);
785
786         memset(ofe->pad, 0, sizeof ofe->pad);
787         ofe->priority = htons(flow->priority);
788
789         duration_j = (flow->timeout - HZ * flow->max_idle) - flow->init_time;
790         ofe->duration     = htonl(duration_j / HZ);
791         ofe->packet_count = cpu_to_be64(flow->packet_count);
792         ofe->byte_count   = cpu_to_be64(flow->byte_count);
793
794         return send_openflow_skb(skb, NULL);
795 }
796 EXPORT_SYMBOL(dp_send_flow_expired);
797
798 int
799 dp_send_error_msg(struct datapath *dp, const struct sender *sender, 
800                 uint16_t type, uint16_t code, const uint8_t *data, size_t len)
801 {
802         struct sk_buff *skb;
803         struct ofp_error_msg *oem;
804
805
806         oem = alloc_openflow_skb(dp, sizeof(*oem)+len, OFPT_ERROR_MSG, 
807                         sender, &skb);
808         if (!oem)
809                 return -ENOMEM;
810
811         oem->type = htons(type);
812         oem->code = htons(code);
813         memcpy(oem->data, data, len);
814
815         return send_openflow_skb(skb, sender);
816 }
817
818 /* Generic Netlink interface.
819  *
820  * See netlink(7) for an introduction to netlink.  See
821  * http://linux-net.osdl.org/index.php/Netlink for more information and
822  * pointers on how to work with netlink and Generic Netlink in the kernel and
823  * in userspace. */
824
825 static struct genl_family dp_genl_family = {
826         .id = GENL_ID_GENERATE,
827         .hdrsize = 0,
828         .name = DP_GENL_FAMILY_NAME,
829         .version = 1,
830         .maxattr = DP_GENL_A_MAX,
831 };
832
833 /* Attribute policy: what each attribute may contain.  */
834 static struct nla_policy dp_genl_policy[DP_GENL_A_MAX + 1] = {
835         [DP_GENL_A_DP_IDX] = { .type = NLA_U32 },
836         [DP_GENL_A_MC_GROUP] = { .type = NLA_U32 },
837         [DP_GENL_A_PORTNAME] = { .type = NLA_STRING }
838 };
839
840 static int dp_genl_add(struct sk_buff *skb, struct genl_info *info)
841 {
842         if (!info->attrs[DP_GENL_A_DP_IDX])
843                 return -EINVAL;
844
845         return new_dp(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
846 }
847
848 static struct genl_ops dp_genl_ops_add_dp = {
849         .cmd = DP_GENL_C_ADD_DP,
850         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
851         .policy = dp_genl_policy,
852         .doit = dp_genl_add,
853         .dumpit = NULL,
854 };
855
856 struct datapath *dp_get(int dp_idx)
857 {
858         if (dp_idx < 0 || dp_idx > DP_MAX)
859                 return NULL;
860         return rcu_dereference(dps[dp_idx]);
861 }
862
863 static int dp_genl_del(struct sk_buff *skb, struct genl_info *info)
864 {
865         struct datapath *dp;
866         int err;
867
868         if (!info->attrs[DP_GENL_A_DP_IDX])
869                 return -EINVAL;
870
871         mutex_lock(&dp_mutex);
872         dp = dp_get(nla_get_u32((info->attrs[DP_GENL_A_DP_IDX])));
873         if (!dp)
874                 err = -ENOENT;
875         else {
876                 del_dp(dp);
877                 err = 0;
878         }
879         mutex_unlock(&dp_mutex);
880         return err;
881 }
882
883 static struct genl_ops dp_genl_ops_del_dp = {
884         .cmd = DP_GENL_C_DEL_DP,
885         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
886         .policy = dp_genl_policy,
887         .doit = dp_genl_del,
888         .dumpit = NULL,
889 };
890
891 /* Queries a datapath for related information.  Currently the only relevant
892  * information is the datapath's multicast group ID.  Really we want one
893  * multicast group per datapath, but because of locking issues[*] we can't
894  * easily get one.  Thus, every datapath will currently return the same
895  * global multicast group ID, but in the future it would be nice to fix that.
896  *
897  * [*] dp_genl_add, to add a new datapath, is called under the genl_lock
898  *       mutex, and genl_register_mc_group, called to acquire a new multicast
899  *       group ID, also acquires genl_lock, thus deadlock.
900  */
901 static int dp_genl_query(struct sk_buff *skb, struct genl_info *info)
902 {
903         struct datapath *dp;
904         struct sk_buff *ans_skb = NULL;
905         int dp_idx;
906         int err = -ENOMEM;
907
908         if (!info->attrs[DP_GENL_A_DP_IDX])
909                 return -EINVAL;
910
911         rcu_read_lock();
912         dp_idx = nla_get_u32((info->attrs[DP_GENL_A_DP_IDX]));
913         dp = dp_get(dp_idx);
914         if (!dp)
915                 err = -ENOENT;
916         else {
917                 void *data;
918                 ans_skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
919                 if (!ans_skb) {
920                         err = -ENOMEM;
921                         goto err;
922                 }
923                 data = genlmsg_put_reply(ans_skb, info, &dp_genl_family,
924                                          0, DP_GENL_C_QUERY_DP);
925                 if (data == NULL) {
926                         err = -ENOMEM;
927                         goto err;
928                 }
929                 NLA_PUT_U32(ans_skb, DP_GENL_A_DP_IDX, dp_idx);
930                 NLA_PUT_U32(ans_skb, DP_GENL_A_MC_GROUP, mc_group.id);
931
932                 genlmsg_end(ans_skb, data);
933                 err = genlmsg_reply(ans_skb, info);
934                 if (!err)
935                         ans_skb = NULL;
936         }
937 err:
938 nla_put_failure:
939         if (ans_skb)
940                 kfree_skb(ans_skb);
941         rcu_read_unlock();
942         return err;
943 }
944
945 static struct genl_ops dp_genl_ops_query_dp = {
946         .cmd = DP_GENL_C_QUERY_DP,
947         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
948         .policy = dp_genl_policy,
949         .doit = dp_genl_query,
950         .dumpit = NULL,
951 };
952
953 static int dp_genl_add_del_port(struct sk_buff *skb, struct genl_info *info)
954 {
955         struct datapath *dp;
956         struct net_device *port;
957         int err;
958
959         if (!info->attrs[DP_GENL_A_DP_IDX] || !info->attrs[DP_GENL_A_PORTNAME])
960                 return -EINVAL;
961
962         /* Get datapath. */
963         mutex_lock(&dp_mutex);
964         dp = dp_get(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
965         if (!dp) {
966                 err = -ENOENT;
967                 goto out;
968         }
969
970         /* Get interface to add/remove. */
971         port = dev_get_by_name(&init_net, 
972                         nla_data(info->attrs[DP_GENL_A_PORTNAME]));
973         if (!port) {
974                 err = -ENOENT;
975                 goto out;
976         }
977
978         /* Execute operation. */
979         if (info->genlhdr->cmd == DP_GENL_C_ADD_PORT)
980                 err = add_switch_port(dp, port);
981         else {
982                 if (port->br_port == NULL || port->br_port->dp != dp) {
983                         err = -ENOENT;
984                         goto out_put;
985                 }
986                 err = del_switch_port(port->br_port);
987         }
988
989 out_put:
990         dev_put(port);
991 out:
992         mutex_unlock(&dp_mutex);
993         return err;
994 }
995
996 static struct genl_ops dp_genl_ops_add_port = {
997         .cmd = DP_GENL_C_ADD_PORT,
998         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
999         .policy = dp_genl_policy,
1000         .doit = dp_genl_add_del_port,
1001         .dumpit = NULL,
1002 };
1003
1004 static struct genl_ops dp_genl_ops_del_port = {
1005         .cmd = DP_GENL_C_DEL_PORT,
1006         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1007         .policy = dp_genl_policy,
1008         .doit = dp_genl_add_del_port,
1009         .dumpit = NULL,
1010 };
1011
1012 static int dp_genl_openflow(struct sk_buff *skb, struct genl_info *info)
1013 {
1014         struct nlattr *va = info->attrs[DP_GENL_A_OPENFLOW];
1015         struct datapath *dp;
1016         struct ofp_header *oh;
1017         struct sender sender;
1018         int err;
1019
1020         if (!info->attrs[DP_GENL_A_DP_IDX] || !va)
1021                 return -EINVAL;
1022
1023         rcu_read_lock();
1024         dp = dp_get(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
1025         if (!dp) {
1026                 err = -ENOENT;
1027                 goto out;
1028         }
1029
1030         if (nla_len(va) < sizeof(struct ofp_header)) {
1031                 err = -EINVAL;
1032                 goto out;
1033         }
1034         oh = nla_data(va);
1035
1036         sender.xid = oh->xid;
1037         sender.pid = info->snd_pid;
1038         sender.seq = info->snd_seq;
1039         err = fwd_control_input(dp->chain, &sender, nla_data(va), nla_len(va));
1040
1041 out:
1042         rcu_read_unlock();
1043         return err;
1044 }
1045
1046 static struct nla_policy dp_genl_openflow_policy[DP_GENL_A_MAX + 1] = {
1047         [DP_GENL_A_DP_IDX] = { .type = NLA_U32 },
1048 };
1049
1050 struct flow_stats_state {
1051         int table_idx;
1052         struct sw_table_position position;
1053         const struct ofp_flow_stats_request *rq;
1054
1055         void *body;
1056         int bytes_used, bytes_allocated;
1057 };
1058
1059 static int flow_stats_init(struct datapath *dp, const void *body, int body_len,
1060                            void **state)
1061 {
1062         const struct ofp_flow_stats_request *fsr = body;
1063         struct flow_stats_state *s = kmalloc(sizeof *s, GFP_ATOMIC);
1064         if (!s)
1065                 return -ENOMEM;
1066         s->table_idx = fsr->table_id == 0xff ? 0 : fsr->table_id;
1067         memset(&s->position, 0, sizeof s->position);
1068         s->rq = fsr;
1069         *state = s;
1070         return 0;
1071 }
1072
1073 static int flow_stats_dump_callback(struct sw_flow *flow, void *private)
1074 {
1075         struct flow_stats_state *s = private;
1076         struct ofp_flow_stats *ofs;
1077         int actions_length;
1078         int length;
1079
1080         actions_length = sizeof *ofs->actions * flow->n_actions;
1081         length = sizeof *ofs + sizeof *ofs->actions * flow->n_actions;
1082         if (length + s->bytes_used > s->bytes_allocated)
1083                 return 1;
1084
1085         ofs = s->body + s->bytes_used;
1086         ofs->length          = htons(length);
1087         ofs->table_id        = s->table_idx;
1088         ofs->pad             = 0;
1089         ofs->match.wildcards = htons(flow->key.wildcards);
1090         ofs->match.in_port   = flow->key.in_port;
1091         memcpy(ofs->match.dl_src, flow->key.dl_src, ETH_ALEN);
1092         memcpy(ofs->match.dl_dst, flow->key.dl_dst, ETH_ALEN);
1093         ofs->match.dl_vlan   = flow->key.dl_vlan;
1094         ofs->match.dl_type   = flow->key.dl_type;
1095         ofs->match.nw_src    = flow->key.nw_src;
1096         ofs->match.nw_dst    = flow->key.nw_dst;
1097         ofs->match.nw_proto  = flow->key.nw_proto;
1098         memset(ofs->match.pad, 0, sizeof ofs->match.pad);
1099         ofs->match.tp_src    = flow->key.tp_src;
1100         ofs->match.tp_dst    = flow->key.tp_dst;
1101         ofs->duration        = htonl((jiffies - flow->init_time) / HZ);
1102         ofs->packet_count    = cpu_to_be64(flow->packet_count);
1103         ofs->byte_count      = cpu_to_be64(flow->byte_count);
1104         ofs->priority        = htons(flow->priority);
1105         ofs->max_idle        = htons(flow->max_idle);
1106         memcpy(ofs->actions, flow->actions, actions_length);
1107
1108         s->bytes_used += length;
1109         return 0;
1110 }
1111
1112 static int flow_stats_dump(struct datapath *dp, void *state,
1113                            void *body, int *body_len)
1114 {
1115         struct flow_stats_state *s = state;
1116         struct sw_flow_key match_key;
1117         int error = 0;
1118
1119         s->bytes_used = 0;
1120         s->bytes_allocated = *body_len;
1121         s->body = body;
1122
1123         flow_extract_match(&match_key, &s->rq->match);
1124         while (s->table_idx < dp->chain->n_tables
1125                && (s->rq->table_id == 0xff || s->rq->table_id == s->table_idx))
1126         {
1127                 struct sw_table *table = dp->chain->tables[s->table_idx];
1128
1129                 error = table->iterate(table, &match_key, &s->position,
1130                                        flow_stats_dump_callback, s);
1131                 if (error)
1132                         break;
1133
1134                 s->table_idx++;
1135                 memset(&s->position, 0, sizeof s->position);
1136         }
1137         *body_len = s->bytes_used;
1138
1139         /* If error is 0, we're done.
1140          * Otherwise, if some bytes were used, there are more flows to come.
1141          * Otherwise, we were not able to fit even a single flow in the body,
1142          * which indicates that we have a single flow with too many actions to
1143          * fit.  We won't ever make any progress at that rate, so give up. */
1144         return !error ? 0 : s->bytes_used ? 1 : -ENOMEM;
1145 }
1146
1147 static void flow_stats_done(void *state)
1148 {
1149         kfree(state);
1150 }
1151
1152 static int aggregate_stats_init(struct datapath *dp,
1153                                 const void *body, int body_len,
1154                                 void **state)
1155 {
1156         *state = (void *)body;
1157         return 0;
1158 }
1159
1160 static int aggregate_stats_dump_callback(struct sw_flow *flow, void *private)
1161 {
1162         struct ofp_aggregate_stats_reply *rpy = private;
1163         rpy->packet_count += flow->packet_count;
1164         rpy->byte_count += flow->byte_count;
1165         rpy->flow_count++;
1166         return 0;
1167 }
1168
1169 static int aggregate_stats_dump(struct datapath *dp, void *state,
1170                                 void *body, int *body_len)
1171 {
1172         struct ofp_aggregate_stats_request *rq = state;
1173         struct ofp_aggregate_stats_reply *rpy;
1174         struct sw_table_position position;
1175         struct sw_flow_key match_key;
1176         int table_idx;
1177
1178         if (*body_len < sizeof *rpy)
1179                 return -ENOBUFS;
1180         rpy = body;
1181         *body_len = sizeof *rpy;
1182
1183         memset(rpy, 0, sizeof *rpy);
1184
1185         flow_extract_match(&match_key, &rq->match);
1186         table_idx = rq->table_id == 0xff ? 0 : rq->table_id;
1187         memset(&position, 0, sizeof position);
1188         while (table_idx < dp->chain->n_tables
1189                && (rq->table_id == 0xff || rq->table_id == table_idx))
1190         {
1191                 struct sw_table *table = dp->chain->tables[table_idx];
1192                 int error;
1193
1194                 error = table->iterate(table, &match_key, &position,
1195                                        aggregate_stats_dump_callback, rpy);
1196                 if (error)
1197                         return error;
1198
1199                 table_idx++;
1200                 memset(&position, 0, sizeof position);
1201         }
1202
1203         rpy->packet_count = cpu_to_be64(rpy->packet_count);
1204         rpy->byte_count = cpu_to_be64(rpy->byte_count);
1205         rpy->flow_count = htonl(rpy->flow_count);
1206         return 0;
1207 }
1208
1209 static int table_stats_dump(struct datapath *dp, void *state,
1210                             void *body, int *body_len)
1211 {
1212         struct ofp_table_stats *ots;
1213         int nbytes = dp->chain->n_tables * sizeof *ots;
1214         int i;
1215         if (nbytes > *body_len)
1216                 return -ENOBUFS;
1217         *body_len = nbytes;
1218         for (i = 0, ots = body; i < dp->chain->n_tables; i++, ots++) {
1219                 struct sw_table_stats stats;
1220                 dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
1221                 strncpy(ots->name, stats.name, sizeof ots->name);
1222                 ots->table_id = i;
1223                 memset(ots->pad, 0, sizeof ots->pad);
1224                 ots->max_entries = htonl(stats.max_flows);
1225                 ots->active_count = htonl(stats.n_flows);
1226                 ots->matched_count = cpu_to_be64(0); /* FIXME */
1227         }
1228         return 0;
1229 }
1230
1231 struct port_stats_state {
1232         int port;
1233 };
1234
1235 static int port_stats_init(struct datapath *dp, const void *body, int body_len,
1236                            void **state)
1237 {
1238         struct port_stats_state *s = kmalloc(sizeof *s, GFP_ATOMIC);
1239         if (!s)
1240                 return -ENOMEM;
1241         s->port = 0;
1242         *state = s;
1243         return 0;
1244 }
1245
1246 static int port_stats_dump(struct datapath *dp, void *state,
1247                            void *body, int *body_len)
1248 {
1249         struct port_stats_state *s = state;
1250         struct ofp_port_stats *ops;
1251         int n_ports, max_ports;
1252         int i;
1253
1254         max_ports = *body_len / sizeof *ops;
1255         if (!max_ports)
1256                 return -ENOMEM;
1257         ops = body;
1258
1259         n_ports = 0;
1260         for (i = s->port; i < OFPP_MAX && n_ports < max_ports; i++) {
1261                 struct net_bridge_port *p = dp->ports[i];
1262                 struct net_device_stats *stats;
1263                 if (!p)
1264                         continue;
1265                 stats = p->dev->get_stats(p->dev);
1266                 ops->port_no = htons(p->port_no);
1267                 memset(ops->pad, 0, sizeof ops->pad);
1268                 ops->rx_count = cpu_to_be64(stats->rx_packets);
1269                 ops->tx_count = cpu_to_be64(stats->tx_packets);
1270                 ops->drop_count = cpu_to_be64(stats->rx_dropped
1271                                               + stats->tx_dropped);
1272                 n_ports++;
1273                 ops++;
1274         }
1275         s->port = i;
1276         *body_len = n_ports * sizeof *ops;
1277         return n_ports >= max_ports;
1278 }
1279
1280 static void port_stats_done(void *state)
1281 {
1282         kfree(state);
1283 }
1284
1285 struct stats_type {
1286         /* Minimum and maximum acceptable number of bytes in body member of
1287          * struct ofp_stats_request. */
1288         size_t min_body, max_body;
1289
1290         /* Prepares to dump some kind of statistics on 'dp'.  'body' and
1291          * 'body_len' are the 'body' member of the struct ofp_stats_request.
1292          * Returns zero if successful, otherwise a negative error code.
1293          * May initialize '*state' to state information.  May be null if no
1294          * initialization is required.*/
1295         int (*init)(struct datapath *dp, const void *body, int body_len,
1296                     void **state);
1297
1298         /* Dumps statistics for 'dp' into the '*body_len' bytes at 'body', and
1299          * modifies '*body_len' to reflect the number of bytes actually used.
1300          * ('body' will be transmitted as the 'body' member of struct
1301          * ofp_stats_reply.) */
1302         int (*dump)(struct datapath *dp, void *state,
1303                     void *body, int *body_len);
1304
1305         /* Cleans any state created by the init or dump functions.  May be null
1306          * if no cleanup is required. */
1307         void (*done)(void *state);
1308 };
1309
1310 static const struct stats_type stats[] = {
1311         [OFPST_FLOW] = {
1312                 sizeof(struct ofp_flow_stats_request),
1313                 sizeof(struct ofp_flow_stats_request),
1314                 flow_stats_init,
1315                 flow_stats_dump,
1316                 flow_stats_done
1317         },
1318         [OFPST_AGGREGATE] = {
1319                 sizeof(struct ofp_aggregate_stats_request),
1320                 sizeof(struct ofp_aggregate_stats_request),
1321                 aggregate_stats_init,
1322                 aggregate_stats_dump,
1323                 NULL
1324         },
1325         [OFPST_TABLE] = {
1326                 0,
1327                 0,
1328                 NULL,
1329                 table_stats_dump,
1330                 NULL
1331         },
1332         [OFPST_PORT] = {
1333                 0,
1334                 0,
1335                 port_stats_init,
1336                 port_stats_dump,
1337                 port_stats_done
1338         },
1339 };
1340
1341 static int
1342 dp_genl_openflow_dumpit(struct sk_buff *skb, struct netlink_callback *cb)
1343 {
1344         struct datapath *dp;
1345         struct sender sender;
1346         const struct stats_type *s;
1347         struct ofp_stats_reply *osr;
1348         int dp_idx;
1349         int max_openflow_len, body_len;
1350         void *body;
1351         int err;
1352
1353         /* Set up the cleanup function for this dump.  Linux 2.6.20 and later
1354          * support setting up cleanup functions via the .doneit member of
1355          * struct genl_ops.  This kluge supports earlier versions also. */
1356         cb->done = dp_genl_openflow_done;
1357
1358         rcu_read_lock();
1359         if (!cb->args[0]) {
1360                 struct nlattr *attrs[DP_GENL_A_MAX + 1];
1361                 struct ofp_stats_request *rq;
1362                 struct nlattr *va;
1363                 size_t len, body_len;
1364                 int type;
1365
1366                 err = nlmsg_parse(cb->nlh, GENL_HDRLEN, attrs, DP_GENL_A_MAX,
1367                                   dp_genl_openflow_policy);
1368                 if (err < 0)
1369                         return err;
1370
1371                 err = -EINVAL;
1372
1373                 if (!attrs[DP_GENL_A_DP_IDX])
1374                         goto out;
1375                 dp_idx = nla_get_u16(attrs[DP_GENL_A_DP_IDX]);
1376                 dp = dp_get(dp_idx);
1377                 if (!dp) {
1378                         err = -ENOENT;
1379                         goto out;
1380                 }
1381
1382                 va = attrs[DP_GENL_A_OPENFLOW];
1383                 len = nla_len(va);
1384                 if (!va || len < sizeof *rq)
1385                         goto out;
1386
1387                 rq = nla_data(va);
1388                 type = ntohs(rq->type);
1389                 if (rq->header.version != OFP_VERSION
1390                     || rq->header.type != OFPT_STATS_REQUEST
1391                     || ntohs(rq->header.length) != len
1392                     || type >= ARRAY_SIZE(stats)
1393                     || !stats[type].dump)
1394                         goto out;
1395
1396                 s = &stats[type];
1397                 body_len = len - offsetof(struct ofp_stats_request, body);
1398                 if (body_len < s->min_body || body_len > s->max_body)
1399                         goto out;
1400
1401                 cb->args[0] = 1;
1402                 cb->args[1] = dp_idx;
1403                 cb->args[2] = type;
1404                 cb->args[3] = rq->header.xid;
1405                 if (s->init) {
1406                         void *state;
1407                         err = s->init(dp, rq->body, body_len, &state);
1408                         if (err)
1409                                 goto out;
1410                         cb->args[4] = (long) state;
1411                 }
1412         } else if (cb->args[0] == 1) {
1413                 dp_idx = cb->args[1];
1414                 s = &stats[cb->args[2]];
1415
1416                 dp = dp_get(dp_idx);
1417                 if (!dp) {
1418                         err = -ENOENT;
1419                         goto out;
1420                 }
1421         } else {
1422                 err = 0;
1423                 goto out;
1424         }
1425
1426         sender.xid = cb->args[3];
1427         sender.pid = NETLINK_CB(cb->skb).pid;
1428         sender.seq = cb->nlh->nlmsg_seq;
1429
1430         osr = put_openflow_headers(dp, skb, OFPT_STATS_REPLY, &sender,
1431                                    &max_openflow_len);
1432         if (IS_ERR(osr)) {
1433                 err = PTR_ERR(osr);
1434                 goto out;
1435         }
1436         osr->type = htons(s - stats);
1437         osr->flags = 0;
1438         resize_openflow_skb(skb, &osr->header, max_openflow_len);
1439         body = osr->body;
1440         body_len = max_openflow_len - offsetof(struct ofp_stats_reply, body);
1441
1442         err = s->dump(dp, (void *) cb->args[4], body, &body_len);
1443         if (err >= 0) {
1444                 if (!err)
1445                         cb->args[0] = 2;
1446                 else
1447                         osr->flags = ntohs(OFPSF_REPLY_MORE);
1448                 resize_openflow_skb(skb, &osr->header,
1449                                     (offsetof(struct ofp_stats_reply, body)
1450                                      + body_len));
1451                 err = skb->len;
1452         }
1453
1454 out:
1455         rcu_read_unlock();
1456         return err;
1457 }
1458
1459 static int
1460 dp_genl_openflow_done(struct netlink_callback *cb)
1461 {
1462         if (cb->args[0]) {
1463                 const struct stats_type *s = &stats[cb->args[2]];
1464                 if (s->done)
1465                         s->done((void *) cb->args[4]);
1466         }
1467         return 0;
1468 }
1469
1470 static struct genl_ops dp_genl_ops_openflow = {
1471         .cmd = DP_GENL_C_OPENFLOW,
1472         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1473         .policy = dp_genl_openflow_policy,
1474         .doit = dp_genl_openflow,
1475         .dumpit = dp_genl_openflow_dumpit,
1476 };
1477
1478 static struct nla_policy dp_genl_benchmark_policy[DP_GENL_A_MAX + 1] = {
1479         [DP_GENL_A_DP_IDX] = { .type = NLA_U32 },
1480         [DP_GENL_A_NPACKETS] = { .type = NLA_U32 },
1481         [DP_GENL_A_PSIZE] = { .type = NLA_U32 },
1482 };
1483
1484 static struct genl_ops dp_genl_ops_benchmark_nl = {
1485         .cmd = DP_GENL_C_BENCHMARK_NL,
1486         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1487         .policy = dp_genl_benchmark_policy,
1488         .doit = dp_genl_benchmark_nl,
1489         .dumpit = NULL,
1490 };
1491
1492 static struct genl_ops *dp_genl_all_ops[] = {
1493         /* Keep this operation first.  Generic Netlink dispatching
1494          * looks up operations with linear search, so we want it at the
1495          * front. */
1496         &dp_genl_ops_openflow,
1497
1498         &dp_genl_ops_add_dp,
1499         &dp_genl_ops_del_dp,
1500         &dp_genl_ops_query_dp,
1501         &dp_genl_ops_add_port,
1502         &dp_genl_ops_del_port,
1503         &dp_genl_ops_benchmark_nl,
1504 };
1505
1506 static int dp_init_netlink(void)
1507 {
1508         int err;
1509         int i;
1510
1511         err = genl_register_family(&dp_genl_family);
1512         if (err)
1513                 return err;
1514
1515         for (i = 0; i < ARRAY_SIZE(dp_genl_all_ops); i++) {
1516                 err = genl_register_ops(&dp_genl_family, dp_genl_all_ops[i]);
1517                 if (err)
1518                         goto err_unregister;
1519         }
1520
1521         strcpy(mc_group.name, "openflow");
1522         err = genl_register_mc_group(&dp_genl_family, &mc_group);
1523         if (err < 0)
1524                 goto err_unregister;
1525
1526         return 0;
1527
1528 err_unregister:
1529         genl_unregister_family(&dp_genl_family);
1530                 return err;
1531 }
1532
1533 static void dp_uninit_netlink(void)
1534 {
1535         genl_unregister_family(&dp_genl_family);
1536 }
1537
1538 #define DRV_NAME                "openflow"
1539 #define DRV_VERSION      VERSION
1540 #define DRV_DESCRIPTION "OpenFlow switching datapath implementation"
1541 #define DRV_COPYRIGHT   "Copyright (c) 2007, 2008 The Board of Trustees of The Leland Stanford Junior University"
1542
1543
1544 static int __init dp_init(void)
1545 {
1546         int err;
1547
1548         printk(KERN_INFO DRV_NAME ": " DRV_DESCRIPTION "\n");
1549         printk(KERN_INFO DRV_NAME ": " VERSION" built on "__DATE__" "__TIME__"\n");
1550         printk(KERN_INFO DRV_NAME ": " DRV_COPYRIGHT "\n");
1551
1552         err = flow_init();
1553         if (err)
1554                 goto error;
1555
1556         err = dp_init_netlink();
1557         if (err)
1558                 goto error_flow_exit;
1559
1560         /* Hook into callback used by the bridge to intercept packets.
1561          * Parasites we are. */
1562         if (br_handle_frame_hook)
1563                 printk("openflow: hijacking bridge hook\n");
1564         br_handle_frame_hook = dp_frame_hook;
1565
1566         return 0;
1567
1568 error_flow_exit:
1569         flow_exit();
1570 error:
1571         printk(KERN_EMERG "openflow: failed to install!");
1572         return err;
1573 }
1574
1575 static void dp_cleanup(void)
1576 {
1577         fwd_exit();
1578         dp_uninit_netlink();
1579         flow_exit();
1580         br_handle_frame_hook = NULL;
1581 }
1582
1583 module_init(dp_init);
1584 module_exit(dp_cleanup);
1585
1586 MODULE_DESCRIPTION(DRV_DESCRIPTION);
1587 MODULE_AUTHOR(DRV_COPYRIGHT);
1588 MODULE_LICENSE("GPL");