Merge branch 'locking'
[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 #include <linux/rculist.h>
32
33 #include "openflow-netlink.h"
34 #include "datapath.h"
35 #include "table.h"
36 #include "chain.h"
37 #include "dp_dev.h"
38 #include "forward.h"
39 #include "flow.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.  dp_mutex is almost completely redundant with genl_mutex
69  * maintained by the Generic Netlink code, but the timeout path needs mutual
70  * exclusion too.
71  *
72  * It is safe to access the datapath and net_bridge_port structures with just
73  * dp_mutex.
74  */
75 static struct datapath *dps[DP_MAX];
76 DEFINE_MUTEX(dp_mutex);
77
78 static int dp_maint_func(void *data);
79 static int send_port_status(struct net_bridge_port *p, uint8_t status);
80 static int dp_genl_openflow_done(struct netlink_callback *);
81 static struct net_bridge_port *new_nbp(struct datapath *,
82                                        struct net_device *, int port_no);
83 static int del_switch_port(struct net_bridge_port *);
84
85 /* nla_shrink - reduce amount of space reserved by nla_reserve
86  * @skb: socket buffer from which to recover room
87  * @nla: netlink attribute to adjust
88  * @len: new length of attribute payload
89  *
90  * Reduces amount of space reserved by a call to nla_reserve.
91  *
92  * No other attributes may be added between calling nla_reserve and this
93  * function, since it will create a hole in the message.
94  */
95 void nla_shrink(struct sk_buff *skb, struct nlattr *nla, int len)
96 {
97         int delta = nla_total_size(len) - nla_total_size(nla_len(nla));
98         BUG_ON(delta > 0);
99         skb->tail += delta;
100         skb->len  += delta;
101         nla->nla_len = nla_attr_size(len);
102 }
103
104 /* Puts a set of openflow headers for a message of the given 'type' into 'skb'.
105  * If 'sender' is nonnull, then it is used as the message's destination.  'dp'
106  * must specify the datapath to use.
107  *
108  * '*max_openflow_len' receives the maximum number of bytes that are available
109  * for the embedded OpenFlow message.  The caller must call
110  * resize_openflow_skb() to set the actual size of the message to this number
111  * of bytes or less.
112  *
113  * Returns the openflow header if successful, otherwise (if 'skb' is too small)
114  * an error code. */
115 static void *
116 put_openflow_headers(struct datapath *dp, struct sk_buff *skb, uint8_t type,
117                      const struct sender *sender, int *max_openflow_len)
118 {
119         struct ofp_header *oh;
120         struct nlattr *attr;
121         int openflow_len;
122
123         /* Assemble the Generic Netlink wrapper. */
124         if (!genlmsg_put(skb,
125                          sender ? sender->pid : 0,
126                          sender ? sender->seq : 0,
127                          &dp_genl_family, 0, DP_GENL_C_OPENFLOW))
128                 return ERR_PTR(-ENOBUFS);
129         if (nla_put_u32(skb, DP_GENL_A_DP_IDX, dp->dp_idx) < 0)
130                 return ERR_PTR(-ENOBUFS);
131         openflow_len = (skb_tailroom(skb) - NLA_HDRLEN) & ~(NLA_ALIGNTO - 1);
132         if (openflow_len < sizeof *oh)
133                 return ERR_PTR(-ENOBUFS);
134         *max_openflow_len = openflow_len;
135         attr = nla_reserve(skb, DP_GENL_A_OPENFLOW, openflow_len);
136         BUG_ON(!attr);
137
138         /* Fill in the header.  The caller is responsible for the length. */
139         oh = nla_data(attr);
140         oh->version = OFP_VERSION;
141         oh->type = type;
142         oh->xid = sender ? sender->xid : 0;
143
144         return oh;
145 }
146
147 /* Resizes OpenFlow header 'oh', which must be at the tail end of 'skb', to new
148  * length 'new_length' (in bytes), adjusting pointers and size values as
149  * necessary. */
150 static void
151 resize_openflow_skb(struct sk_buff *skb,
152                     struct ofp_header *oh, size_t new_length)
153 {
154         struct nlattr *attr = ((void *) oh) - NLA_HDRLEN;
155         nla_shrink(skb, attr, new_length);
156         oh->length = htons(new_length);
157         nlmsg_end(skb, (struct nlmsghdr *) skb->data);
158 }
159
160 /* Allocates a new skb to contain an OpenFlow message 'openflow_len' bytes in
161  * length.  Returns a null pointer if memory is unavailable, otherwise returns
162  * the OpenFlow header and stores a pointer to the skb in '*pskb'. 
163  *
164  * 'type' is the OpenFlow message type.  If 'sender' is nonnull, then it is
165  * used as the message's destination.  'dp' must specify the datapath to
166  * use.  */
167 static void *
168 alloc_openflow_skb(struct datapath *dp, size_t openflow_len, uint8_t type,
169                    const struct sender *sender, struct sk_buff **pskb) 
170 {
171         struct ofp_header *oh;
172         size_t genl_len;
173         struct sk_buff *skb;
174         int max_openflow_len;
175
176         if ((openflow_len + sizeof(struct ofp_header)) > UINT16_MAX) {
177                 if (net_ratelimit())
178                         printk("alloc_openflow_skb: openflow message too large: %zu\n", 
179                                         openflow_len);
180                 return NULL;
181         }
182
183         genl_len = nlmsg_total_size(GENL_HDRLEN + dp_genl_family.hdrsize);
184         genl_len += nla_total_size(sizeof(uint32_t)); /* DP_GENL_A_DP_IDX */
185         genl_len += nla_total_size(openflow_len);    /* DP_GENL_A_OPENFLOW */
186         skb = *pskb = genlmsg_new(genl_len, GFP_ATOMIC);
187         if (!skb) {
188                 if (net_ratelimit())
189                         printk("alloc_openflow_skb: genlmsg_new failed\n");
190                 return NULL;
191         }
192
193         oh = put_openflow_headers(dp, skb, type, sender, &max_openflow_len);
194         BUG_ON(!oh || IS_ERR(oh));
195         resize_openflow_skb(skb, oh, openflow_len);
196
197         return oh;
198 }
199
200 /* Sends 'skb' to 'sender' if it is nonnull, otherwise multicasts 'skb' to all
201  * listeners. */
202 static int
203 send_openflow_skb(struct sk_buff *skb, const struct sender *sender) 
204 {
205         return (sender
206                 ? genlmsg_unicast(skb, sender->pid)
207                 : genlmsg_multicast(skb, 0, mc_group.id, GFP_ATOMIC));
208 }
209
210 /* Generates a unique datapath id.  It incorporates the datapath index
211  * and a hardware address, if available.  If not, it generates a random
212  * one.
213  */
214 static 
215 uint64_t gen_datapath_id(uint16_t dp_idx)
216 {
217         uint64_t id;
218         int i;
219         struct net_device *dev;
220
221         /* The top 16 bits are used to identify the datapath.  The lower 48 bits
222          * use an interface address.  */
223         id = (uint64_t)dp_idx << 48;
224         if ((dev = dev_get_by_name(&init_net, "ctl0")) 
225                         || (dev = dev_get_by_name(&init_net, "eth0"))) {
226                 for (i=0; i<ETH_ALEN; i++) {
227                         id |= (uint64_t)dev->dev_addr[i] << (8*(ETH_ALEN-1 - i));
228                 }
229                 dev_put(dev);
230         } else {
231                 /* Randomly choose the lower 48 bits if we cannot find an
232                  * address and mark the most significant bit to indicate that
233                  * this was randomly generated. */
234                 uint8_t rand[ETH_ALEN];
235                 get_random_bytes(rand, ETH_ALEN);
236                 id |= (uint64_t)1 << 63;
237                 for (i=0; i<ETH_ALEN; i++) {
238                         id |= (uint64_t)rand[i] << (8*(ETH_ALEN-1 - i));
239                 }
240         }
241
242         return id;
243 }
244
245 /* Creates a new datapath numbered 'dp_idx'.  Returns 0 for success or a
246  * negative error code. */
247 static int new_dp(int dp_idx)
248 {
249         struct datapath *dp;
250         int err;
251
252         if (dp_idx < 0 || dp_idx >= DP_MAX)
253                 return -EINVAL;
254
255         if (!try_module_get(THIS_MODULE))
256                 return -ENODEV;
257
258         /* Exit early if a datapath with that number already exists. */
259         if (dps[dp_idx]) {
260                 err = -EEXIST;
261                 goto err_unlock;
262         }
263
264         err = -ENOMEM;
265         dp = kzalloc(sizeof *dp, GFP_KERNEL);
266         if (dp == NULL)
267                 goto err_unlock;
268
269         /* Setup our "of" device */
270         err = dp_dev_setup(dp);
271         if (err)
272                 goto err_free_dp;
273
274         dp->dp_idx = dp_idx;
275         dp->id = gen_datapath_id(dp_idx);
276         dp->chain = chain_create(dp);
277         if (dp->chain == NULL)
278                 goto err_destroy_dp_dev;
279         INIT_LIST_HEAD(&dp->port_list);
280
281         dp->local_port = new_nbp(dp, dp->netdev, OFPP_LOCAL);
282         if (IS_ERR(dp->local_port)) {
283                 err = PTR_ERR(dp->local_port);
284                 goto err_destroy_local_port;
285         }
286
287         dp->flags = 0;
288         dp->miss_send_len = OFP_DEFAULT_MISS_SEND_LEN;
289
290         dp->dp_task = kthread_run(dp_maint_func, dp, "dp%d", dp_idx);
291         if (IS_ERR(dp->dp_task))
292                 goto err_destroy_chain;
293
294         dps[dp_idx] = dp;
295
296         return 0;
297
298 err_destroy_local_port:
299         del_switch_port(dp->local_port);
300 err_destroy_chain:
301         chain_destroy(dp->chain);
302 err_destroy_dp_dev:
303         dp_dev_destroy(dp);
304 err_free_dp:
305         kfree(dp);
306 err_unlock:
307         module_put(THIS_MODULE);
308                 return err;
309 }
310
311 /* Find and return a free port number under 'dp'. */
312 static int find_portno(struct datapath *dp)
313 {
314         int i;
315         for (i = 0; i < OFPP_MAX; i++)
316                 if (dp->ports[i] == NULL)
317                         return i;
318         return -EXFULL;
319 }
320
321 static struct net_bridge_port *new_nbp(struct datapath *dp,
322                                        struct net_device *dev, int port_no)
323 {
324         struct net_bridge_port *p;
325
326         if (dev->br_port != NULL)
327                 return ERR_PTR(-EBUSY);
328
329         p = kzalloc(sizeof(*p), GFP_KERNEL);
330         if (p == NULL)
331                 return ERR_PTR(-ENOMEM);
332
333         rtnl_lock();
334         dev_set_promiscuity(dev, 1);
335         rtnl_unlock();
336         dev_hold(dev);
337         p->dp = dp;
338         p->dev = dev;
339         p->port_no = port_no;
340         if (port_no != OFPP_LOCAL)
341                 rcu_assign_pointer(dev->br_port, p);
342         if (port_no < OFPP_MAX)
343                 rcu_assign_pointer(dp->ports[port_no], p); 
344         list_add_rcu(&p->node, &dp->port_list);
345
346         return p;
347 }
348
349 int add_switch_port(struct datapath *dp, struct net_device *dev)
350 {
351         struct net_bridge_port *p;
352         int port_no;
353
354         if (dev->flags & IFF_LOOPBACK || dev->type != ARPHRD_ETHER
355             || is_dp_dev(dev))
356                 return -EINVAL;
357
358         port_no = find_portno(dp);
359         if (port_no < 0)
360                 return port_no;
361
362         p = new_nbp(dp, dev, port_no);
363         if (IS_ERR(p))
364                 return PTR_ERR(p);
365
366         /* Notify the ctlpath that this port has been added */
367         send_port_status(p, OFPPR_ADD);
368
369         return 0;
370 }
371
372 /* Delete 'p' from switch. */
373 static int del_switch_port(struct net_bridge_port *p)
374 {
375         /* First drop references to device. */
376         rtnl_lock();
377         dev_set_promiscuity(p->dev, -1);
378         rtnl_unlock();
379         list_del_rcu(&p->node);
380         if (p->port_no != OFPP_LOCAL)
381                 rcu_assign_pointer(p->dp->ports[p->port_no], NULL);
382         rcu_assign_pointer(p->dev->br_port, NULL);
383
384         /* Then wait until no one is still using it, and destroy it. */
385         synchronize_rcu();
386
387         /* Notify the ctlpath that this port no longer exists */
388         send_port_status(p, OFPPR_DELETE);
389
390         dev_put(p->dev);
391         kfree(p);
392
393         return 0;
394 }
395
396 static void del_dp(struct datapath *dp)
397 {
398         struct net_bridge_port *p, *n;
399
400         kthread_stop(dp->dp_task);
401
402         /* Drop references to DP. */
403         list_for_each_entry_safe (p, n, &dp->port_list, node)
404                 del_switch_port(p);
405         rcu_assign_pointer(dps[dp->dp_idx], NULL);
406
407         /* Kill off local_port dev references from buffered packets that have
408          * associated dst entries. */
409         synchronize_rcu();
410         fwd_discard_all();
411
412         /* Destroy dp->netdev.  (Must follow deleting switch ports since
413          * dp->local_port has a reference to it.) */
414         dp_dev_destroy(dp);
415
416         /* Wait until no longer in use, then destroy it. */
417         synchronize_rcu();
418         chain_destroy(dp->chain);
419         kfree(dp);
420         module_put(THIS_MODULE);
421 }
422
423 static int dp_maint_func(void *data)
424 {
425         struct datapath *dp = (struct datapath *) data;
426
427         while (!kthread_should_stop()) {
428                 chain_timeout(dp->chain);
429                 msleep_interruptible(MAINT_SLEEP_MSECS);
430         }
431                 
432         return 0;
433 }
434
435 static void
436 do_port_input(struct net_bridge_port *p, struct sk_buff *skb) 
437 {
438         /* Push the Ethernet header back on. */
439         skb_push(skb, ETH_HLEN);
440         fwd_port_input(p->dp->chain, skb, p->port_no);
441 }
442
443 /*
444  * Used as br_handle_frame_hook.  (Cannot run bridge at the same time, even on
445  * different set of devices!)
446  */
447 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
448 /* Called with rcu_read_lock. */
449 static struct sk_buff *dp_frame_hook(struct net_bridge_port *p,
450                                          struct sk_buff *skb)
451 {
452         do_port_input(p, skb);
453         return NULL;
454 }
455 #elif LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
456 static int dp_frame_hook(struct net_bridge_port *p, struct sk_buff **pskb)
457 {
458         do_port_input(p, *pskb);
459         return 1;
460 }
461 #else
462 /* NB: This has only been tested on 2.4.35 */
463 static void dp_frame_hook(struct sk_buff *skb)
464 {
465         struct net_bridge_port *p = skb->dev->br_port;
466         if (p) {
467                 rcu_read_lock();
468                 do_port_input(p, skb);
469                 rcu_read_unlock();
470         } else
471                 kfree_skb(skb);
472 }
473 #endif
474
475 /* Forwarding output path.
476  * Based on net/bridge/br_forward.c. */
477
478 static inline unsigned packet_length(const struct sk_buff *skb)
479 {
480         int length = skb->len - ETH_HLEN;
481         if (skb->protocol == htons(ETH_P_8021Q))
482                 length -= VLAN_HLEN;
483         return length;
484 }
485
486 /* Send packets out all the ports except the originating one.  If the
487  * "flood" argument is set, only send along the minimum spanning tree.
488  */
489 static int
490 output_all(struct datapath *dp, struct sk_buff *skb, int flood)
491 {
492         u32 disable = flood ? BRIDGE_PORT_NO_FLOOD : 0;
493         struct net_bridge_port *p;
494         int prev_port = -1;
495
496         list_for_each_entry_rcu (p, &dp->port_list, node) {
497                 if (skb->dev == p->dev || p->flags & disable)
498                         continue;
499                 if (prev_port != -1) {
500                         struct sk_buff *clone = skb_clone(skb, GFP_ATOMIC);
501                         if (!clone) {
502                                 kfree_skb(skb);
503                                 return -ENOMEM;
504                         }
505                         dp_output_port(dp, clone, prev_port); 
506                 }
507                 prev_port = p->port_no;
508         }
509         if (prev_port != -1)
510                 dp_output_port(dp, skb, prev_port);
511         else
512                 kfree_skb(skb);
513
514         return 0;
515 }
516
517 /* Marks 'skb' as having originated from 'in_port' in 'dp'.
518    FIXME: how are devices reference counted? */
519 int dp_set_origin(struct datapath *dp, uint16_t in_port,
520                            struct sk_buff *skb)
521 {
522         struct net_bridge_port *p = (in_port < OFPP_MAX ? dp->ports[in_port]
523                                      : in_port == OFPP_LOCAL ? dp->local_port
524                                      : NULL);
525         if (p) {
526                 skb->dev = p->dev;
527                 return 0;
528         }
529         return -ENOENT;
530 }
531
532 /* Takes ownership of 'skb' and transmits it to 'out_port' on 'dp'.
533  */
534 int dp_output_port(struct datapath *dp, struct sk_buff *skb, int out_port)
535 {
536         BUG_ON(!skb);
537         if (out_port == OFPP_FLOOD)
538                 return output_all(dp, skb, 1);
539         else if (out_port == OFPP_ALL)
540                 return output_all(dp, skb, 0);
541         else if (out_port == OFPP_CONTROLLER)
542                 return dp_output_control(dp, skb, fwd_save_skb(skb), 0,
543                                                   OFPR_ACTION);
544         else if (out_port == OFPP_TABLE) {
545                 struct net_bridge_port *p = skb->dev->br_port;
546                 struct sw_flow_key key;
547                 struct sw_flow *flow;
548
549                 flow_extract(skb, p ? p->port_no : OFPP_LOCAL, &key);
550                 flow = chain_lookup(dp->chain, &key);
551                 if (likely(flow != NULL)) {
552                         flow_used(flow, skb);
553                         execute_actions(dp, skb, &key, flow->actions, flow->n_actions);
554                         return 0;
555                 }
556                 return -ESRCH;
557         } else if (out_port == OFPP_LOCAL) {
558                 struct net_device *dev = dp->netdev;
559                 return dev ? dp_dev_recv(dev, skb) : -ESRCH;
560         } else if (out_port >= 0 && out_port < OFPP_MAX) {
561                 struct net_bridge_port *p = dp->ports[out_port];
562                 int len = skb->len;
563                 if (p == NULL)
564                         goto bad_port;
565                 skb->dev = p->dev; 
566                 if (packet_length(skb) > skb->dev->mtu) {
567                         printk("dropped over-mtu packet: %d > %d\n",
568                                packet_length(skb), skb->dev->mtu);
569                         kfree_skb(skb);
570                         return -E2BIG;
571                 }
572
573                 dev_queue_xmit(skb);
574
575                 return len;
576         }
577
578 bad_port:
579         kfree_skb(skb);
580         if (net_ratelimit())
581                 printk("can't forward to bad port %d\n", out_port);
582         return -ENOENT;
583 }
584
585 /* Takes ownership of 'skb' and transmits it to 'dp''s control path.  If
586  * 'buffer_id' != -1, then only the first 64 bytes of 'skb' are sent;
587  * otherwise, all of 'skb' is sent.  'reason' indicates why 'skb' is being
588  * sent. 'max_len' sets the maximum number of bytes that the caller
589  * wants to be sent; a value of 0 indicates the entire packet should be
590  * sent. */
591 int
592 dp_output_control(struct datapath *dp, struct sk_buff *skb,
593                            uint32_t buffer_id, size_t max_len, int reason)
594 {
595         /* FIXME?  Can we avoid creating a new skbuff in the case where we
596          * forward the whole packet? */
597         struct sk_buff *f_skb;
598         struct ofp_packet_in *opi;
599         struct net_bridge_port *p;
600         size_t fwd_len, opi_len;
601         int err;
602
603         fwd_len = skb->len;
604         if ((buffer_id != (uint32_t) -1) && max_len)
605                 fwd_len = min(fwd_len, max_len);
606
607         opi_len = offsetof(struct ofp_packet_in, data) + fwd_len;
608         opi = alloc_openflow_skb(dp, opi_len, OFPT_PACKET_IN, NULL, &f_skb);
609         if (!opi) {
610                 err = -ENOMEM;
611                 goto out;
612         }
613         opi->buffer_id      = htonl(buffer_id);
614         opi->total_len      = htons(skb->len);
615         p = skb->dev->br_port;
616         opi->in_port        = htons(p ? p->port_no : OFPP_LOCAL);
617         opi->reason         = reason;
618         opi->pad            = 0;
619         memcpy(opi->data, skb_mac_header(skb), fwd_len);
620         err = send_openflow_skb(f_skb, NULL);
621
622 out:
623         kfree_skb(skb);
624         return err;
625 }
626
627 static void fill_port_desc(struct net_bridge_port *p, struct ofp_phy_port *desc)
628 {
629         desc->port_no = htons(p->port_no);
630         strncpy(desc->name, p->dev->name, OFP_MAX_PORT_NAME_LEN);
631         desc->name[OFP_MAX_PORT_NAME_LEN-1] = '\0';
632         memcpy(desc->hw_addr, p->dev->dev_addr, ETH_ALEN);
633         desc->flags = htonl(p->flags);
634         desc->features = 0;
635         desc->speed = 0;
636
637 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,24)
638         if (p->dev->ethtool_ops && p->dev->ethtool_ops->get_settings) {
639                 struct ethtool_cmd ecmd = { .cmd = ETHTOOL_GSET };
640
641                 if (!p->dev->ethtool_ops->get_settings(p->dev, &ecmd)) {
642                         if (ecmd.supported & SUPPORTED_10baseT_Half) 
643                                 desc->features |= OFPPF_10MB_HD;
644                         if (ecmd.supported & SUPPORTED_10baseT_Full)
645                                 desc->features |= OFPPF_10MB_FD;
646                         if (ecmd.supported & SUPPORTED_100baseT_Half) 
647                                 desc->features |= OFPPF_100MB_HD;
648                         if (ecmd.supported & SUPPORTED_100baseT_Full)
649                                 desc->features |= OFPPF_100MB_FD;
650                         if (ecmd.supported & SUPPORTED_1000baseT_Half)
651                                 desc->features |= OFPPF_1GB_HD;
652                         if (ecmd.supported & SUPPORTED_1000baseT_Full)
653                                 desc->features |= OFPPF_1GB_FD;
654                         /* 10Gbps half-duplex doesn't exist... */
655                         if (ecmd.supported & SUPPORTED_10000baseT_Full)
656                                 desc->features |= OFPPF_10GB_FD;
657
658                         desc->features = htonl(desc->features);
659                         desc->speed = htonl(ecmd.speed);
660                 }
661         }
662 #endif
663 }
664
665 static int 
666 fill_features_reply(struct datapath *dp, struct ofp_switch_features *ofr)
667 {
668         struct net_bridge_port *p;
669         int port_count = 0;
670
671         ofr->datapath_id    = cpu_to_be64(dp->id); 
672
673         ofr->n_exact        = htonl(2 * TABLE_HASH_MAX_FLOWS);
674         ofr->n_compression  = 0;                                           /* Not supported */
675         ofr->n_general      = htonl(TABLE_LINEAR_MAX_FLOWS);
676         ofr->buffer_mb      = htonl(UINT32_MAX);
677         ofr->n_buffers      = htonl(N_PKT_BUFFERS);
678         ofr->capabilities   = htonl(OFP_SUPPORTED_CAPABILITIES);
679         ofr->actions        = htonl(OFP_SUPPORTED_ACTIONS);
680
681         list_for_each_entry_rcu (p, &dp->port_list, node) {
682                 fill_port_desc(p, &ofr->ports[port_count]);
683                 port_count++;
684         }
685
686         return port_count;
687 }
688
689 int
690 dp_send_features_reply(struct datapath *dp, const struct sender *sender)
691 {
692         struct sk_buff *skb;
693         struct ofp_switch_features *ofr;
694         size_t ofr_len, port_max_len;
695         int port_count;
696
697         /* Overallocate. */
698         port_max_len = sizeof(struct ofp_phy_port) * OFPP_MAX;
699         ofr = alloc_openflow_skb(dp, sizeof(*ofr) + port_max_len,
700                                  OFPT_FEATURES_REPLY, sender, &skb);
701         if (!ofr)
702                 return -ENOMEM;
703
704         /* Fill. */
705         port_count = fill_features_reply(dp, ofr);
706
707         /* Shrink to fit. */
708         ofr_len = sizeof(*ofr) + (sizeof(struct ofp_phy_port) * port_count);
709         resize_openflow_skb(skb, &ofr->header, ofr_len);
710         return send_openflow_skb(skb, sender);
711 }
712
713 int
714 dp_send_config_reply(struct datapath *dp, const struct sender *sender)
715 {
716         struct sk_buff *skb;
717         struct ofp_switch_config *osc;
718
719         osc = alloc_openflow_skb(dp, sizeof *osc, OFPT_GET_CONFIG_REPLY, sender,
720                                  &skb);
721         if (!osc)
722                 return -ENOMEM;
723
724         osc->flags = htons(dp->flags);
725         osc->miss_send_len = htons(dp->miss_send_len);
726
727         return send_openflow_skb(skb, sender);
728 }
729
730 int
731 dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp)
732 {
733         int port_no = ntohs(opp->port_no);
734         struct net_bridge_port *p = (port_no < OFPP_MAX ? dp->ports[port_no]
735                                      : port_no == OFPP_LOCAL ? dp->local_port
736                                      : NULL);
737         /* Make sure the port id hasn't changed since this was sent */
738         if (!p || memcmp(opp->hw_addr, p->dev->dev_addr, ETH_ALEN))
739                 return -1;
740         p->flags = htonl(opp->flags);
741         return 0;
742 }
743
744
745 static int
746 send_port_status(struct net_bridge_port *p, uint8_t status)
747 {
748         struct sk_buff *skb;
749         struct ofp_port_status *ops;
750
751         ops = alloc_openflow_skb(p->dp, sizeof *ops, OFPT_PORT_STATUS, NULL,
752                                  &skb);
753         if (!ops)
754                 return -ENOMEM;
755         ops->reason = status;
756         memset(ops->pad, 0, sizeof ops->pad);
757         fill_port_desc(p, &ops->desc);
758
759         return send_openflow_skb(skb, NULL);
760 }
761
762 int 
763 dp_send_flow_expired(struct datapath *dp, struct sw_flow *flow)
764 {
765         struct sk_buff *skb;
766         struct ofp_flow_expired *ofe;
767         unsigned long duration_j;
768
769         ofe = alloc_openflow_skb(dp, sizeof *ofe, OFPT_FLOW_EXPIRED, 0, &skb);
770         if (!ofe)
771                 return -ENOMEM;
772
773         flow_fill_match(&ofe->match, &flow->key);
774
775         memset(ofe->pad, 0, sizeof ofe->pad);
776         ofe->priority = htons(flow->priority);
777
778         duration_j = (flow->timeout - HZ * flow->max_idle) - flow->init_time;
779         ofe->duration     = htonl(duration_j / HZ);
780         ofe->packet_count = cpu_to_be64(flow->packet_count);
781         ofe->byte_count   = cpu_to_be64(flow->byte_count);
782
783         return send_openflow_skb(skb, NULL);
784 }
785 EXPORT_SYMBOL(dp_send_flow_expired);
786
787 int
788 dp_send_error_msg(struct datapath *dp, const struct sender *sender, 
789                 uint16_t type, uint16_t code, const uint8_t *data, size_t len)
790 {
791         struct sk_buff *skb;
792         struct ofp_error_msg *oem;
793
794
795         oem = alloc_openflow_skb(dp, sizeof(*oem)+len, OFPT_ERROR_MSG, 
796                         sender, &skb);
797         if (!oem)
798                 return -ENOMEM;
799
800         oem->type = htons(type);
801         oem->code = htons(code);
802         memcpy(oem->data, data, len);
803
804         return send_openflow_skb(skb, sender);
805 }
806
807 int
808 dp_send_echo_reply(struct datapath *dp, const struct sender *sender,
809                    const struct ofp_header *rq)
810 {
811         struct sk_buff *skb;
812         struct ofp_header *reply;
813
814         reply = alloc_openflow_skb(dp, ntohs(rq->length), OFPT_ECHO_REPLY,
815                                    sender, &skb);
816         if (!reply)
817                 return -ENOMEM;
818
819         memcpy(reply + 1, rq + 1, ntohs(rq->length) - sizeof *rq);
820         return send_openflow_skb(skb, sender);
821 }
822
823 /* Generic Netlink interface.
824  *
825  * See netlink(7) for an introduction to netlink.  See
826  * http://linux-net.osdl.org/index.php/Netlink for more information and
827  * pointers on how to work with netlink and Generic Netlink in the kernel and
828  * in userspace. */
829
830 static struct genl_family dp_genl_family = {
831         .id = GENL_ID_GENERATE,
832         .hdrsize = 0,
833         .name = DP_GENL_FAMILY_NAME,
834         .version = 1,
835         .maxattr = DP_GENL_A_MAX,
836 };
837
838 /* Attribute policy: what each attribute may contain.  */
839 static struct nla_policy dp_genl_policy[DP_GENL_A_MAX + 1] = {
840         [DP_GENL_A_DP_IDX] = { .type = NLA_U32 },
841         [DP_GENL_A_MC_GROUP] = { .type = NLA_U32 },
842         [DP_GENL_A_PORTNAME] = { .type = NLA_STRING }
843 };
844
845 static int dp_genl_add(struct sk_buff *skb, struct genl_info *info)
846 {
847         if (!info->attrs[DP_GENL_A_DP_IDX])
848                 return -EINVAL;
849
850         return new_dp(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
851 }
852
853 static struct genl_ops dp_genl_ops_add_dp = {
854         .cmd = DP_GENL_C_ADD_DP,
855         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
856         .policy = dp_genl_policy,
857         .doit = dp_genl_add,
858         .dumpit = NULL,
859 };
860
861 struct datapath *dp_get(int dp_idx)
862 {
863         if (dp_idx < 0 || dp_idx > DP_MAX)
864                 return NULL;
865         return rcu_dereference(dps[dp_idx]);
866 }
867
868 static int dp_genl_del(struct sk_buff *skb, struct genl_info *info)
869 {
870         struct datapath *dp;
871         int err;
872
873         if (!info->attrs[DP_GENL_A_DP_IDX])
874                 return -EINVAL;
875
876         dp = dp_get(nla_get_u32((info->attrs[DP_GENL_A_DP_IDX])));
877         if (!dp)
878                 err = -ENOENT;
879         else {
880                 del_dp(dp);
881                 err = 0;
882         }
883         return err;
884 }
885
886 static struct genl_ops dp_genl_ops_del_dp = {
887         .cmd = DP_GENL_C_DEL_DP,
888         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
889         .policy = dp_genl_policy,
890         .doit = dp_genl_del,
891         .dumpit = NULL,
892 };
893
894 /* Queries a datapath for related information.  Currently the only relevant
895  * information is the datapath's multicast group ID.  Really we want one
896  * multicast group per datapath, but because of locking issues[*] we can't
897  * easily get one.  Thus, every datapath will currently return the same
898  * global multicast group ID, but in the future it would be nice to fix that.
899  *
900  * [*] dp_genl_add, to add a new datapath, is called under the genl_lock
901  *       mutex, and genl_register_mc_group, called to acquire a new multicast
902  *       group ID, also acquires genl_lock, thus deadlock.
903  */
904 static int dp_genl_query(struct sk_buff *skb, struct genl_info *info)
905 {
906         struct datapath *dp;
907         struct sk_buff *ans_skb = NULL;
908         int dp_idx;
909         int err = -ENOMEM;
910
911         if (!info->attrs[DP_GENL_A_DP_IDX])
912                 return -EINVAL;
913
914         rcu_read_lock();
915         dp_idx = nla_get_u32((info->attrs[DP_GENL_A_DP_IDX]));
916         dp = dp_get(dp_idx);
917         if (!dp)
918                 err = -ENOENT;
919         else {
920                 void *data;
921                 ans_skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
922                 if (!ans_skb) {
923                         err = -ENOMEM;
924                         goto err;
925                 }
926                 data = genlmsg_put_reply(ans_skb, info, &dp_genl_family,
927                                          0, DP_GENL_C_QUERY_DP);
928                 if (data == NULL) {
929                         err = -ENOMEM;
930                         goto err;
931                 }
932                 NLA_PUT_U32(ans_skb, DP_GENL_A_DP_IDX, dp_idx);
933                 NLA_PUT_U32(ans_skb, DP_GENL_A_MC_GROUP, mc_group.id);
934
935                 genlmsg_end(ans_skb, data);
936                 err = genlmsg_reply(ans_skb, info);
937                 if (!err)
938                         ans_skb = NULL;
939         }
940 err:
941 nla_put_failure:
942         if (ans_skb)
943                 kfree_skb(ans_skb);
944         rcu_read_unlock();
945         return err;
946 }
947
948 static struct genl_ops dp_genl_ops_query_dp = {
949         .cmd = DP_GENL_C_QUERY_DP,
950         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
951         .policy = dp_genl_policy,
952         .doit = dp_genl_query,
953         .dumpit = NULL,
954 };
955
956 static int dp_genl_add_del_port(struct sk_buff *skb, struct genl_info *info)
957 {
958         struct datapath *dp;
959         struct net_device *port;
960         int err;
961
962         if (!info->attrs[DP_GENL_A_DP_IDX] || !info->attrs[DP_GENL_A_PORTNAME])
963                 return -EINVAL;
964
965         /* Get datapath. */
966         dp = dp_get(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
967         if (!dp) {
968                 err = -ENOENT;
969                 goto out;
970         }
971
972         /* Get interface to add/remove. */
973         port = dev_get_by_name(&init_net, 
974                         nla_data(info->attrs[DP_GENL_A_PORTNAME]));
975         if (!port) {
976                 err = -ENOENT;
977                 goto out;
978         }
979
980         /* Execute operation. */
981         if (info->genlhdr->cmd == DP_GENL_C_ADD_PORT)
982                 err = add_switch_port(dp, port);
983         else {
984                 if (port->br_port == NULL || port->br_port->dp != dp) {
985                         err = -ENOENT;
986                         goto out_put;
987                 }
988                 err = del_switch_port(port->br_port);
989         }
990
991 out_put:
992         dev_put(port);
993 out:
994         return err;
995 }
996
997 static struct genl_ops dp_genl_ops_add_port = {
998         .cmd = DP_GENL_C_ADD_PORT,
999         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1000         .policy = dp_genl_policy,
1001         .doit = dp_genl_add_del_port,
1002         .dumpit = NULL,
1003 };
1004
1005 static struct genl_ops dp_genl_ops_del_port = {
1006         .cmd = DP_GENL_C_DEL_PORT,
1007         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1008         .policy = dp_genl_policy,
1009         .doit = dp_genl_add_del_port,
1010         .dumpit = NULL,
1011 };
1012
1013 static int dp_genl_openflow(struct sk_buff *skb, struct genl_info *info)
1014 {
1015         struct nlattr *va = info->attrs[DP_GENL_A_OPENFLOW];
1016         struct datapath *dp;
1017         struct ofp_header *oh;
1018         struct sender sender;
1019         int err;
1020
1021         if (!info->attrs[DP_GENL_A_DP_IDX] || !va)
1022                 return -EINVAL;
1023
1024         dp = dp_get(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
1025         if (!dp)
1026                 return -ENOENT;
1027
1028         if (nla_len(va) < sizeof(struct ofp_header))
1029                 return -EINVAL;
1030         oh = nla_data(va);
1031
1032         sender.xid = oh->xid;
1033         sender.pid = info->snd_pid;
1034         sender.seq = info->snd_seq;
1035
1036         mutex_lock(&dp_mutex);
1037         err = fwd_control_input(dp->chain, &sender,
1038                                 nla_data(va), nla_len(va));
1039         mutex_unlock(&dp_mutex);
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         if (!cb->args[0]) {
1356                 struct nlattr *attrs[DP_GENL_A_MAX + 1];
1357                 struct ofp_stats_request *rq;
1358                 struct nlattr *va;
1359                 size_t len, body_len;
1360                 int type;
1361
1362                 err = nlmsg_parse(cb->nlh, GENL_HDRLEN, attrs, DP_GENL_A_MAX,
1363                                   dp_genl_openflow_policy);
1364                 if (err < 0)
1365                         return err;
1366
1367                 if (!attrs[DP_GENL_A_DP_IDX])
1368                         return -EINVAL;
1369                 dp_idx = nla_get_u16(attrs[DP_GENL_A_DP_IDX]);
1370                 dp = dp_get(dp_idx);
1371                 if (!dp)
1372                         return -ENOENT;
1373
1374                 va = attrs[DP_GENL_A_OPENFLOW];
1375                 len = nla_len(va);
1376                 if (!va || len < sizeof *rq)
1377                         return -EINVAL;
1378
1379                 rq = nla_data(va);
1380                 type = ntohs(rq->type);
1381                 if (rq->header.version != OFP_VERSION
1382                     || rq->header.type != OFPT_STATS_REQUEST
1383                     || ntohs(rq->header.length) != len
1384                     || type >= ARRAY_SIZE(stats)
1385                     || !stats[type].dump)
1386                         return -EINVAL;
1387
1388                 s = &stats[type];
1389                 body_len = len - offsetof(struct ofp_stats_request, body);
1390                 if (body_len < s->min_body || body_len > s->max_body)
1391                         return -EINVAL;
1392
1393                 cb->args[0] = 1;
1394                 cb->args[1] = dp_idx;
1395                 cb->args[2] = type;
1396                 cb->args[3] = rq->header.xid;
1397                 if (s->init) {
1398                         void *state;
1399                         err = s->init(dp, rq->body, body_len, &state);
1400                         if (err)
1401                                 return err;
1402                         cb->args[4] = (long) state;
1403                 }
1404         } else if (cb->args[0] == 1) {
1405                 dp_idx = cb->args[1];
1406                 s = &stats[cb->args[2]];
1407
1408                 dp = dp_get(dp_idx);
1409                 if (!dp)
1410                         return -ENOENT;
1411         } else {
1412                 return 0;
1413         }
1414
1415         sender.xid = cb->args[3];
1416         sender.pid = NETLINK_CB(cb->skb).pid;
1417         sender.seq = cb->nlh->nlmsg_seq;
1418
1419         osr = put_openflow_headers(dp, skb, OFPT_STATS_REPLY, &sender,
1420                                    &max_openflow_len);
1421         if (IS_ERR(osr))
1422                 return PTR_ERR(osr);
1423         osr->type = htons(s - stats);
1424         osr->flags = 0;
1425         resize_openflow_skb(skb, &osr->header, max_openflow_len);
1426         body = osr->body;
1427         body_len = max_openflow_len - offsetof(struct ofp_stats_reply, body);
1428
1429         err = s->dump(dp, (void *) cb->args[4], body, &body_len);
1430         if (err >= 0) {
1431                 if (!err)
1432                         cb->args[0] = 2;
1433                 else
1434                         osr->flags = ntohs(OFPSF_REPLY_MORE);
1435                 resize_openflow_skb(skb, &osr->header,
1436                                     (offsetof(struct ofp_stats_reply, body)
1437                                      + body_len));
1438                 err = skb->len;
1439         }
1440
1441         return err;
1442 }
1443
1444 static int
1445 dp_genl_openflow_done(struct netlink_callback *cb)
1446 {
1447         if (cb->args[0]) {
1448                 const struct stats_type *s = &stats[cb->args[2]];
1449                 if (s->done)
1450                         s->done((void *) cb->args[4]);
1451         }
1452         return 0;
1453 }
1454
1455 static struct genl_ops dp_genl_ops_openflow = {
1456         .cmd = DP_GENL_C_OPENFLOW,
1457         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1458         .policy = dp_genl_openflow_policy,
1459         .doit = dp_genl_openflow,
1460         .dumpit = dp_genl_openflow_dumpit,
1461 };
1462
1463 static struct genl_ops *dp_genl_all_ops[] = {
1464         /* Keep this operation first.  Generic Netlink dispatching
1465          * looks up operations with linear search, so we want it at the
1466          * front. */
1467         &dp_genl_ops_openflow,
1468
1469         &dp_genl_ops_add_dp,
1470         &dp_genl_ops_del_dp,
1471         &dp_genl_ops_query_dp,
1472         &dp_genl_ops_add_port,
1473         &dp_genl_ops_del_port,
1474 };
1475
1476 static int dp_init_netlink(void)
1477 {
1478         int err;
1479         int i;
1480
1481         err = genl_register_family(&dp_genl_family);
1482         if (err)
1483                 return err;
1484
1485         for (i = 0; i < ARRAY_SIZE(dp_genl_all_ops); i++) {
1486                 err = genl_register_ops(&dp_genl_family, dp_genl_all_ops[i]);
1487                 if (err)
1488                         goto err_unregister;
1489         }
1490
1491         strcpy(mc_group.name, "openflow");
1492         err = genl_register_mc_group(&dp_genl_family, &mc_group);
1493         if (err < 0)
1494                 goto err_unregister;
1495
1496         return 0;
1497
1498 err_unregister:
1499         genl_unregister_family(&dp_genl_family);
1500                 return err;
1501 }
1502
1503 static void dp_uninit_netlink(void)
1504 {
1505         genl_unregister_family(&dp_genl_family);
1506 }
1507
1508 #define DRV_NAME                "openflow"
1509 #define DRV_VERSION      VERSION
1510 #define DRV_DESCRIPTION "OpenFlow switching datapath implementation"
1511 #define DRV_COPYRIGHT   "Copyright (c) 2007, 2008 The Board of Trustees of The Leland Stanford Junior University"
1512
1513
1514 static int __init dp_init(void)
1515 {
1516         int err;
1517
1518         printk(KERN_INFO DRV_NAME ": " DRV_DESCRIPTION "\n");
1519         printk(KERN_INFO DRV_NAME ": " VERSION" built on "__DATE__" "__TIME__"\n");
1520         printk(KERN_INFO DRV_NAME ": " DRV_COPYRIGHT "\n");
1521
1522         err = flow_init();
1523         if (err)
1524                 goto error;
1525
1526         err = dp_init_netlink();
1527         if (err)
1528                 goto error_flow_exit;
1529
1530         /* Hook into callback used by the bridge to intercept packets.
1531          * Parasites we are. */
1532         if (br_handle_frame_hook)
1533                 printk("openflow: hijacking bridge hook\n");
1534         br_handle_frame_hook = dp_frame_hook;
1535
1536         return 0;
1537
1538 error_flow_exit:
1539         flow_exit();
1540 error:
1541         printk(KERN_EMERG "openflow: failed to install!");
1542         return err;
1543 }
1544
1545 static void dp_cleanup(void)
1546 {
1547         fwd_exit();
1548         dp_uninit_netlink();
1549         flow_exit();
1550         br_handle_frame_hook = NULL;
1551 }
1552
1553 module_init(dp_init);
1554 module_exit(dp_cleanup);
1555
1556 MODULE_DESCRIPTION(DRV_DESCRIPTION);
1557 MODULE_AUTHOR(DRV_COPYRIGHT);
1558 MODULE_LICENSE("GPL");