242af24375f49b14793d3f19ea63b0bfb06a4a87
[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/time.h>
19 #include <linux/etherdevice.h>
20 #include <linux/kernel.h>
21 #include <linux/kthread.h>
22 #include <linux/mutex.h>
23 #include <linux/rtnetlink.h>
24 #include <linux/rcupdate.h>
25 #include <linux/version.h>
26 #include <linux/ethtool.h>
27 #include <linux/random.h>
28 #include <asm/system.h>
29 #include <asm/div64.h>
30 #include <linux/netfilter_bridge.h>
31 #include <linux/netfilter_ipv4.h>
32 #include <linux/inetdevice.h>
33 #include <linux/list.h>
34 #include <linux/rculist.h>
35 #include <linux/workqueue.h>
36 #include <linux/dmi.h>
37
38 #include "openflow/nicira-ext.h"
39 #include "openflow/openflow-netlink.h"
40 #include "datapath.h"
41 #include "nx_act_snat.h"
42 #include "table.h"
43 #include "chain.h"
44 #include "dp_dev.h"
45 #include "forward.h"
46 #include "flow.h"
47
48 #include "compat.h"
49
50
51 /* Strings to describe the manufacturer, hardware, and software.  This data 
52  * is queriable through the switch description stats message. */
53 static char mfr_desc[DESC_STR_LEN] = "Nicira Networks, Inc.";
54 static char hw_desc[DESC_STR_LEN] = "Reference Linux Kernel Module";
55 static char sw_desc[DESC_STR_LEN] = VERSION BUILDNR;
56 static char serial_num[SERIAL_NUM_LEN] = "None";
57
58 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
59 module_param_string(mfr_desc, mfr_desc, sizeof mfr_desc, 0444);
60 module_param_string(hw_desc, hw_desc, sizeof hw_desc, 0444);
61 module_param_string(sw_desc, sw_desc, sizeof sw_desc, 0444);
62 module_param_string(serial_num, serial_num, sizeof serial_num, 0444);
63 #else
64 MODULE_PARM(mfr_desc, "s");
65 MODULE_PARM(hw_desc, "s");
66 MODULE_PARM(sw_desc, "s");
67 MODULE_PARM(serial_num, "s");
68 #endif
69
70
71 /* Number of milliseconds between runs of the maintenance thread. */
72 #define MAINT_SLEEP_MSECS 1000
73
74 #define UINT32_MAX                        4294967295U
75 #define UINT16_MAX                        65535
76 #define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
77
78 static struct genl_family dp_genl_family;
79 static struct genl_multicast_group mc_group;
80
81 /* It's hard to imagine wanting more than one datapath, but... */
82 #define DP_MAX 32
83
84 /* Datapaths.  Protected on the read side by rcu_read_lock, on the write side
85  * by dp_mutex.  dp_mutex is almost completely redundant with genl_mutex
86  * maintained by the Generic Netlink code, but the timeout path needs mutual
87  * exclusion too.
88  *
89  * It is safe to access the datapath and net_bridge_port structures with just
90  * dp_mutex.
91  */
92 static struct datapath *dps[DP_MAX];
93 DEFINE_MUTEX(dp_mutex);
94 EXPORT_SYMBOL(dp_mutex);
95
96 static int dp_maint_func(void *data);
97 static void init_port_status(struct net_bridge_port *p);
98 static int dp_genl_openflow_done(struct netlink_callback *);
99 static struct net_bridge_port *new_nbp(struct datapath *,
100                                        struct net_device *, int port_no);
101
102 /* nla_shrink - reduce amount of space reserved by nla_reserve
103  * @skb: socket buffer from which to recover room
104  * @nla: netlink attribute to adjust
105  * @len: new length of attribute payload
106  *
107  * Reduces amount of space reserved by a call to nla_reserve.
108  *
109  * No other attributes may be added between calling nla_reserve and this
110  * function, since it will create a hole in the message.
111  */
112 void nla_shrink(struct sk_buff *skb, struct nlattr *nla, int len)
113 {
114         int delta = nla_total_size(len) - nla_total_size(nla_len(nla));
115         BUG_ON(delta > 0);
116         skb->tail += delta;
117         skb->len  += delta;
118         nla->nla_len = nla_attr_size(len);
119 }
120
121 /* Puts a set of openflow headers for a message of the given 'type' into 'skb'.
122  * If 'sender' is nonnull, then it is used as the message's destination.  'dp'
123  * must specify the datapath to use.
124  *
125  * '*max_openflow_len' receives the maximum number of bytes that are available
126  * for the embedded OpenFlow message.  The caller must call
127  * resize_openflow_skb() to set the actual size of the message to this number
128  * of bytes or less.
129  *
130  * Returns the openflow header if successful, otherwise (if 'skb' is too small)
131  * an error code. */
132 static void *
133 put_openflow_headers(struct datapath *dp, struct sk_buff *skb, uint8_t type,
134                      const struct sender *sender, int *max_openflow_len)
135 {
136         struct ofp_header *oh;
137         struct nlattr *attr;
138         int openflow_len;
139
140         /* Assemble the Generic Netlink wrapper. */
141         if (!genlmsg_put(skb,
142                          sender ? sender->pid : 0,
143                          sender ? sender->seq : 0,
144                          &dp_genl_family, 0, DP_GENL_C_OPENFLOW))
145                 return ERR_PTR(-ENOBUFS);
146         if (nla_put_u32(skb, DP_GENL_A_DP_IDX, dp->dp_idx) < 0)
147                 return ERR_PTR(-ENOBUFS);
148         openflow_len = (skb_tailroom(skb) - NLA_HDRLEN) & ~(NLA_ALIGNTO - 1);
149         if (openflow_len < sizeof *oh)
150                 return ERR_PTR(-ENOBUFS);
151         *max_openflow_len = openflow_len;
152         attr = nla_reserve(skb, DP_GENL_A_OPENFLOW, openflow_len);
153         BUG_ON(!attr);
154
155         /* Fill in the header.  The caller is responsible for the length. */
156         oh = nla_data(attr);
157         oh->version = OFP_VERSION;
158         oh->type = type;
159         oh->xid = sender ? sender->xid : 0;
160
161         return oh;
162 }
163
164 /* Resizes OpenFlow header 'oh', which must be at the tail end of 'skb', to new
165  * length 'new_length' (in bytes), adjusting pointers and size values as
166  * necessary. */
167 static void
168 resize_openflow_skb(struct sk_buff *skb,
169                     struct ofp_header *oh, size_t new_length)
170 {
171         struct nlattr *attr = ((void *) oh) - NLA_HDRLEN;
172         nla_shrink(skb, attr, new_length);
173         oh->length = htons(new_length);
174         nlmsg_end(skb, (struct nlmsghdr *) skb->data);
175 }
176
177 /* Allocates a new skb to contain an OpenFlow message 'openflow_len' bytes in
178  * length.  Returns a null pointer if memory is unavailable, otherwise returns
179  * the OpenFlow header and stores a pointer to the skb in '*pskb'. 
180  *
181  * 'type' is the OpenFlow message type.  If 'sender' is nonnull, then it is
182  * used as the message's destination.  'dp' must specify the datapath to
183  * use.  */
184 static void *
185 alloc_openflow_skb(struct datapath *dp, size_t openflow_len, uint8_t type,
186                    const struct sender *sender, struct sk_buff **pskb) 
187 {
188         struct ofp_header *oh;
189         size_t genl_len;
190         struct sk_buff *skb;
191         int max_openflow_len;
192
193         if ((openflow_len + sizeof(struct ofp_header)) > UINT16_MAX) {
194                 if (net_ratelimit())
195                         printk("alloc_openflow_skb: openflow message too large: %zu\n", 
196                                         openflow_len);
197                 return NULL;
198         }
199
200         genl_len = nlmsg_total_size(GENL_HDRLEN + dp_genl_family.hdrsize);
201         genl_len += nla_total_size(sizeof(uint32_t)); /* DP_GENL_A_DP_IDX */
202         genl_len += nla_total_size(openflow_len);    /* DP_GENL_A_OPENFLOW */
203         skb = *pskb = genlmsg_new(genl_len, GFP_ATOMIC);
204         if (!skb) {
205                 if (net_ratelimit())
206                         printk("alloc_openflow_skb: genlmsg_new failed\n");
207                 return NULL;
208         }
209
210         oh = put_openflow_headers(dp, skb, type, sender, &max_openflow_len);
211         BUG_ON(!oh || IS_ERR(oh));
212         resize_openflow_skb(skb, oh, openflow_len);
213
214         return oh;
215 }
216
217 /* Sends 'skb' to 'sender' if it is nonnull, otherwise multicasts 'skb' to all
218  * listeners. */
219 static int
220 send_openflow_skb(struct sk_buff *skb, const struct sender *sender) 
221 {
222         return (sender
223                 ? genlmsg_unicast(skb, sender->pid)
224                 : genlmsg_multicast(skb, 0, mc_group.id, GFP_ATOMIC));
225 }
226
227 /* Retrieves the datapath id, which is the MAC address of the "of" device. */
228 static 
229 uint64_t get_datapath_id(struct net_device *dev)
230 {
231         uint64_t id = 0;
232         int i;
233
234         for (i=0; i<ETH_ALEN; i++) 
235                 id |= (uint64_t)dev->dev_addr[i] << (8*(ETH_ALEN-1 - i));
236
237         return id;
238 }
239
240 /* Creates a new datapath numbered 'dp_idx'.  Returns 0 for success or a
241  * negative error code. */
242 static int new_dp(int dp_idx)
243 {
244         struct datapath *dp;
245         int err;
246
247         if (dp_idx < 0 || dp_idx >= DP_MAX)
248                 return -EINVAL;
249
250         if (!try_module_get(THIS_MODULE))
251                 return -ENODEV;
252
253         /* Exit early if a datapath with that number already exists. */
254         if (dps[dp_idx]) {
255                 err = -EEXIST;
256                 goto err_unlock;
257         }
258
259         err = -ENOMEM;
260         dp = kzalloc(sizeof *dp, GFP_KERNEL);
261         if (dp == NULL)
262                 goto err_unlock;
263
264         dp->dp_idx = dp_idx;
265
266         /* Setup our "of" device */
267         err = dp_dev_setup(dp);
268         if (err)
269                 goto err_free_dp;
270
271         dp->chain = chain_create(dp);
272         if (dp->chain == NULL)
273                 goto err_destroy_dp_dev;
274         INIT_LIST_HEAD(&dp->port_list);
275
276         dp->local_port = new_nbp(dp, dp->netdev, OFPP_LOCAL);
277         if (IS_ERR(dp->local_port)) {
278                 err = PTR_ERR(dp->local_port);
279                 goto err_destroy_local_port;
280         }
281
282         dp->flags = 0;
283         dp->miss_send_len = OFP_DEFAULT_MISS_SEND_LEN;
284
285         dp->dp_task = kthread_run(dp_maint_func, dp, "dp%d", dp_idx);
286         if (IS_ERR(dp->dp_task))
287                 goto err_destroy_chain;
288
289         dps[dp_idx] = dp;
290
291         return 0;
292
293 err_destroy_local_port:
294         dp_del_switch_port(dp->local_port);
295 err_destroy_chain:
296         chain_destroy(dp->chain);
297 err_destroy_dp_dev:
298         dp_dev_destroy(dp);
299 err_free_dp:
300         kfree(dp);
301 err_unlock:
302         module_put(THIS_MODULE);
303                 return err;
304 }
305
306 /* Find and return a free port number under 'dp'. */
307 static int find_portno(struct datapath *dp)
308 {
309         int i;
310         for (i = 0; i < DP_MAX_PORTS; i++)
311                 if (dp->ports[i] == NULL)
312                         return i;
313         return -EXFULL;
314 }
315
316 static struct net_bridge_port *new_nbp(struct datapath *dp,
317                                        struct net_device *dev, int port_no)
318 {
319         struct net_bridge_port *p;
320
321         if (dev->br_port != NULL)
322                 return ERR_PTR(-EBUSY);
323
324         p = kzalloc(sizeof(*p), GFP_KERNEL);
325         if (p == NULL)
326                 return ERR_PTR(-ENOMEM);
327
328         rtnl_lock();
329         dev_set_promiscuity(dev, 1);
330         rtnl_unlock();
331         dev_hold(dev);
332         p->dp = dp;
333         p->dev = dev;
334         p->port_no = port_no;
335         spin_lock_init(&p->lock);
336         INIT_WORK(&p->port_task, NULL);
337         if (port_no != OFPP_LOCAL)
338                 rcu_assign_pointer(dev->br_port, p);
339         if (port_no < DP_MAX_PORTS)
340                 rcu_assign_pointer(dp->ports[port_no], p); 
341         list_add_rcu(&p->node, &dp->port_list);
342
343         return p;
344 }
345
346 int add_switch_port(struct datapath *dp, struct net_device *dev)
347 {
348         struct net_bridge_port *p;
349         int port_no;
350
351         if (dev->flags & IFF_LOOPBACK || dev->type != ARPHRD_ETHER
352             || is_dp_dev(dev))
353                 return -EINVAL;
354
355         port_no = find_portno(dp);
356         if (port_no < 0)
357                 return port_no;
358
359         p = new_nbp(dp, dev, port_no);
360         if (IS_ERR(p))
361                 return PTR_ERR(p);
362
363         init_port_status(p);
364
365         /* Notify the ctlpath that this port has been added */
366         dp_send_port_status(p, OFPPR_ADD);
367
368         return 0;
369 }
370
371 /* Delete 'p' from switch. */
372 int dp_del_switch_port(struct net_bridge_port *p)
373 {
374 #ifdef SUPPORT_SNAT
375         unsigned long flags;
376 #endif
377
378         /* First drop references to device. */
379         cancel_work_sync(&p->port_task);
380         rtnl_lock();
381         dev_set_promiscuity(p->dev, -1);
382         rtnl_unlock();
383         list_del_rcu(&p->node);
384         if (p->port_no != OFPP_LOCAL)
385                 rcu_assign_pointer(p->dp->ports[p->port_no], NULL);
386         rcu_assign_pointer(p->dev->br_port, NULL);
387
388         /* Then wait until no one is still using it, and destroy it. */
389         synchronize_rcu();
390
391 #ifdef SUPPORT_SNAT
392         /* Free any SNAT configuration on the port. */
393         spin_lock_irqsave(&p->lock, flags);
394         snat_free_conf(p);
395         spin_unlock_irqrestore(&p->lock, flags);
396 #endif
397
398         /* Notify the ctlpath that this port no longer exists */
399         dp_send_port_status(p, OFPPR_DELETE);
400
401         dev_put(p->dev);
402         kfree(p);
403
404         return 0;
405 }
406
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                 dp_del_switch_port(p);
416         rcu_assign_pointer(dps[dp->dp_idx], NULL);
417
418         /* Kill off local_port dev references from buffered packets that have
419          * associated dst entries. */
420         synchronize_rcu();
421         fwd_discard_all();
422
423         /* Destroy dp->netdev.  (Must follow deleting switch ports since
424          * dp->local_port has a reference to it.) */
425         dp_dev_destroy(dp);
426
427         /* Wait until no longer in use, then destroy it. */
428         synchronize_rcu();
429         chain_destroy(dp->chain);
430         kfree(dp);
431         module_put(THIS_MODULE);
432 }
433
434 static int dp_maint_func(void *data)
435 {
436         struct datapath *dp = (struct datapath *) data;
437
438         while (!kthread_should_stop()) {
439 #ifdef SUPPORT_SNAT
440                 struct net_bridge_port *p;
441
442                 /* Expire old SNAT entries */
443                 rcu_read_lock();
444                 list_for_each_entry_rcu (p, &dp->port_list, node) 
445                         snat_maint(p);
446                 rcu_read_unlock();
447 #endif
448
449                 /* Timeout old entries */
450                 chain_timeout(dp->chain);
451                 msleep_interruptible(MAINT_SLEEP_MSECS);
452         }
453                 
454         return 0;
455 }
456
457 static void
458 do_port_input(struct net_bridge_port *p, struct sk_buff *skb) 
459 {
460         /* Make our own copy of the packet.  Otherwise we will mangle the
461          * packet for anyone who came before us (e.g. tcpdump via AF_PACKET).
462          * (No one comes after us, since we tell handle_bridge() that we took
463          * the packet.) */
464         skb = skb_share_check(skb, GFP_ATOMIC);
465         if (!skb)
466                 return;
467
468 #ifdef SUPPORT_SNAT
469         /* Check if this packet needs early SNAT processing. */
470         if (snat_pre_route(skb)) 
471                 return;
472 #endif
473
474         /* Push the Ethernet header back on. */
475         skb_push(skb, ETH_HLEN);
476         skb_reset_mac_header(skb);
477         fwd_port_input(p->dp->chain, skb, p);
478 }
479
480 /*
481  * Used as br_handle_frame_hook.  (Cannot run bridge at the same time, even on
482  * different set of devices!)
483  */
484 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
485 /* Called with rcu_read_lock. */
486 static struct sk_buff *dp_frame_hook(struct net_bridge_port *p,
487                                          struct sk_buff *skb)
488 {
489         do_port_input(p, skb);
490         return NULL;
491 }
492 #elif LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
493 static int dp_frame_hook(struct net_bridge_port *p, struct sk_buff **pskb)
494 {
495         do_port_input(p, *pskb);
496         return 1;
497 }
498 #else
499 /* NB: This has only been tested on 2.4.35 */
500 static void dp_frame_hook(struct sk_buff *skb)
501 {
502         struct net_bridge_port *p = skb->dev->br_port;
503         if (p) {
504                 rcu_read_lock();
505                 do_port_input(p, skb);
506                 rcu_read_unlock();
507         } else
508                 kfree_skb(skb);
509 }
510 #endif
511
512 /* Forwarding output path.
513  * Based on net/bridge/br_forward.c. */
514
515 static inline unsigned packet_length(const struct sk_buff *skb)
516 {
517         int length = skb->len - ETH_HLEN;
518         if (skb->protocol == htons(ETH_P_8021Q))
519                 length -= VLAN_HLEN;
520         return length;
521 }
522
523 /* Send packets out all the ports except the originating one.  If the
524  * "flood" argument is set, only send along the minimum spanning tree.
525  */
526 static int
527 output_all(struct datapath *dp, struct sk_buff *skb, int flood)
528 {
529         u32 disable = flood ? OFPPC_NO_FLOOD : 0;
530         struct net_bridge_port *p;
531         int prev_port = -1;
532
533         list_for_each_entry_rcu (p, &dp->port_list, node) {
534                 if (skb->dev == p->dev || p->config & disable)
535                         continue;
536                 if (prev_port != -1) {
537                         struct sk_buff *clone = skb_clone(skb, GFP_ATOMIC);
538                         if (!clone) {
539                                 kfree_skb(skb);
540                                 return -ENOMEM;
541                         }
542                         dp_output_port(dp, clone, prev_port, 0); 
543                 }
544                 prev_port = p->port_no;
545         }
546         if (prev_port != -1)
547                 dp_output_port(dp, skb, prev_port, 0);
548         else
549                 kfree_skb(skb);
550
551         return 0;
552 }
553
554 /* Marks 'skb' as having originated from 'in_port' in 'dp'.
555    FIXME: how are devices reference counted? */
556 void dp_set_origin(struct datapath *dp, uint16_t in_port,
557                            struct sk_buff *skb)
558 {
559         struct net_bridge_port *p;
560         p = (in_port < DP_MAX_PORTS ? dp->ports[in_port]
561              : in_port == OFPP_LOCAL ? dp->local_port
562              : NULL);
563         if (p) 
564                 skb->dev = p->dev;
565          else 
566                 skb->dev = NULL;
567 }
568
569 #ifdef SUPPORT_SNAT
570 static int 
571 dp_xmit_skb_finish(struct sk_buff *skb)
572 {
573         /* Copy back the Ethernet header that was stowed earlier. */
574         if (skb->protocol == htons(ETH_P_IP) && snat_copy_header(skb)) {
575                 kfree_skb(skb);
576                 return -EINVAL;
577         }
578         skb_reset_mac_header(skb);
579
580         if (packet_length(skb) > skb->dev->mtu && !skb_is_gso(skb)) {
581                 printk("dropped over-mtu packet: %d > %d\n",
582                            packet_length(skb), skb->dev->mtu);
583                 kfree_skb(skb);
584                 return -E2BIG;
585         }
586
587         skb_push(skb, ETH_HLEN);
588         dev_queue_xmit(skb);
589
590         return 0;
591 }
592
593 int
594 dp_xmit_skb(struct sk_buff *skb)
595 {
596         int len = skb->len;
597         int err;
598
599         skb_pull(skb, ETH_HLEN);
600
601         /* The ip_fragment function does not copy the Ethernet header into
602          * the newly generated frames, so stow the original. */
603         if (skb->protocol == htons(ETH_P_IP))
604                 snat_save_header(skb);
605
606         if (skb->protocol == htons(ETH_P_IP) &&
607                         skb->len > skb->dev->mtu &&
608                         !skb_is_gso(skb)) {
609                 err = ip_fragment(skb, dp_xmit_skb_finish);
610         } else {
611                 err = dp_xmit_skb_finish(skb);
612         }
613         if (err)
614                 return err;
615
616         return len;
617 }
618 #else
619 int 
620 dp_xmit_skb(struct sk_buff *skb)
621 {
622         int len = skb->len;
623         if (packet_length(skb) > skb->dev->mtu && !skb_is_gso(skb)) {
624                 printk("dropped over-mtu packet: %d > %d\n",
625                            packet_length(skb), skb->dev->mtu);
626                 kfree_skb(skb);
627                 return -E2BIG;
628         }
629
630         dev_queue_xmit(skb);
631
632         return len;
633 }
634 #endif
635
636 /* Takes ownership of 'skb' and transmits it to 'out_port' on 'dp'.
637  */
638 int dp_output_port(struct datapath *dp, struct sk_buff *skb, int out_port,
639                    int ignore_no_fwd)
640 {
641         BUG_ON(!skb);
642         switch (out_port){
643         case OFPP_IN_PORT:
644                 /* Send it out the port it came in on, which is already set in
645                  * the skb. */
646                 if (!skb->dev) {
647                         if (net_ratelimit())
648                                 printk("skb device not set forwarding to in_port\n");
649                         kfree_skb(skb);
650                         return -ESRCH;
651                 }
652                 return dp_xmit_skb(skb);
653                 
654         case OFPP_TABLE: {
655                 int retval = run_flow_through_tables(dp->chain, skb,
656                                                      skb->dev->br_port);
657                 if (retval)
658                         kfree_skb(skb);
659                 return retval;
660         }
661
662         case OFPP_FLOOD:
663                 return output_all(dp, skb, 1);
664
665         case OFPP_ALL:
666                 return output_all(dp, skb, 0);
667
668         case OFPP_CONTROLLER:
669                 return dp_output_control(dp, skb, fwd_save_skb(skb), 0,
670                                                   OFPR_ACTION);
671
672         case OFPP_LOCAL: {
673                 struct net_device *dev = dp->netdev;
674 #ifdef SUPPORT_SNAT
675                 snat_local_in(skb);
676 #endif
677                 return dev ? dp_dev_recv(dev, skb) : -ESRCH;
678         }
679
680         case 0 ... DP_MAX_PORTS - 1: {
681                 struct net_bridge_port *p = dp->ports[out_port];
682                 if (p == NULL)
683                         goto bad_port;
684                 if (p->dev == skb->dev) {
685                         /* To send to the input port, must use OFPP_IN_PORT */
686                         kfree_skb(skb);
687                         if (net_ratelimit())
688                                 printk("can't directly forward to input port\n");
689                         return -EINVAL;
690                 }
691                 if (p->config & OFPPC_NO_FWD && !ignore_no_fwd) {
692                         kfree_skb(skb);
693                         return 0;
694                 }
695                 skb->dev = p->dev; 
696                 return dp_xmit_skb(skb);
697         }
698
699         default:
700                 goto bad_port;
701         }
702
703 bad_port:
704         kfree_skb(skb);
705         if (net_ratelimit())
706                 printk("can't forward to bad port %d\n", out_port);
707         return -ENOENT;
708 }
709
710 /* Takes ownership of 'skb' and transmits it to 'dp''s control path.  If
711  * 'buffer_id' != -1, then only the first 64 bytes of 'skb' are sent;
712  * otherwise, all of 'skb' is sent.  'reason' indicates why 'skb' is being
713  * sent. 'max_len' sets the maximum number of bytes that the caller
714  * wants to be sent; a value of 0 indicates the entire packet should be
715  * sent. */
716 int
717 dp_output_control(struct datapath *dp, struct sk_buff *skb,
718                            uint32_t buffer_id, size_t max_len, int reason)
719 {
720         /* FIXME?  Can we avoid creating a new skbuff in the case where we
721          * forward the whole packet? */
722         struct sk_buff *f_skb;
723         struct ofp_packet_in *opi;
724         size_t fwd_len, opi_len;
725         int err;
726
727         fwd_len = skb->len;
728         if ((buffer_id != (uint32_t) -1) && max_len)
729                 fwd_len = min(fwd_len, max_len);
730
731         opi_len = offsetof(struct ofp_packet_in, data) + fwd_len;
732         opi = alloc_openflow_skb(dp, opi_len, OFPT_PACKET_IN, NULL, &f_skb);
733         if (!opi) {
734                 err = -ENOMEM;
735                 goto out;
736         }
737         opi->buffer_id      = htonl(buffer_id);
738         opi->total_len      = htons(skb->len);
739         opi->in_port        = htons(skb->dev && skb->dev->br_port
740                                     ? skb->dev->br_port->port_no
741                                     : OFPP_LOCAL);
742         opi->reason         = reason;
743         opi->pad            = 0;
744         skb_copy_bits(skb, 0, opi->data, fwd_len);
745         err = send_openflow_skb(f_skb, NULL);
746
747 out:
748         kfree_skb(skb);
749         return err;
750 }
751
752 static void fill_port_desc(struct net_bridge_port *p, struct ofp_phy_port *desc)
753 {
754         unsigned long flags;
755         desc->port_no = htons(p->port_no);
756         strncpy(desc->name, p->dev->name, OFP_MAX_PORT_NAME_LEN);
757         desc->name[OFP_MAX_PORT_NAME_LEN-1] = '\0';
758         memcpy(desc->hw_addr, p->dev->dev_addr, ETH_ALEN);
759         desc->curr = 0;
760         desc->supported = 0;
761         desc->advertised = 0;
762         desc->peer = 0;
763
764         spin_lock_irqsave(&p->lock, flags);
765         desc->config = htonl(p->config);
766         desc->state = htonl(p->state);
767         spin_unlock_irqrestore(&p->lock, flags);
768
769 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,24)
770         if (p->dev->ethtool_ops && p->dev->ethtool_ops->get_settings) {
771                 struct ethtool_cmd ecmd = { .cmd = ETHTOOL_GSET };
772
773                 if (!p->dev->ethtool_ops->get_settings(p->dev, &ecmd)) {
774                         /* Set the supported features */
775                         if (ecmd.supported & SUPPORTED_10baseT_Half) 
776                                 desc->supported |= OFPPF_10MB_HD;
777                         if (ecmd.supported & SUPPORTED_10baseT_Full)
778                                 desc->supported |= OFPPF_10MB_FD;
779                         if (ecmd.supported & SUPPORTED_100baseT_Half) 
780                                 desc->supported |= OFPPF_100MB_HD;
781                         if (ecmd.supported & SUPPORTED_100baseT_Full)
782                                 desc->supported |= OFPPF_100MB_FD;
783                         if (ecmd.supported & SUPPORTED_1000baseT_Half)
784                                 desc->supported |= OFPPF_1GB_HD;
785                         if (ecmd.supported & SUPPORTED_1000baseT_Full)
786                                 desc->supported |= OFPPF_1GB_FD;
787                         if (ecmd.supported & SUPPORTED_10000baseT_Full)
788                                 desc->supported |= OFPPF_10GB_FD;
789                         if (ecmd.supported & SUPPORTED_TP)
790                                 desc->supported |= OFPPF_COPPER;
791                         if (ecmd.supported & SUPPORTED_FIBRE)
792                                 desc->supported |= OFPPF_FIBER;
793                         if (ecmd.supported & SUPPORTED_Autoneg)
794                                 desc->supported |= OFPPF_AUTONEG;
795 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,14)
796                         if (ecmd.supported & SUPPORTED_Pause)
797                                 desc->supported |= OFPPF_PAUSE;
798                         if (ecmd.supported & SUPPORTED_Asym_Pause)
799                                 desc->supported |= OFPPF_PAUSE_ASYM;
800 #endif /* kernel >= 2.6.14 */
801
802                         /* Set the advertised features */
803                         if (ecmd.advertising & ADVERTISED_10baseT_Half) 
804                                 desc->advertised |= OFPPF_10MB_HD;
805                         if (ecmd.advertising & ADVERTISED_10baseT_Full)
806                                 desc->advertised |= OFPPF_10MB_FD;
807                         if (ecmd.advertising & ADVERTISED_100baseT_Half) 
808                                 desc->advertised |= OFPPF_100MB_HD;
809                         if (ecmd.advertising & ADVERTISED_100baseT_Full)
810                                 desc->advertised |= OFPPF_100MB_FD;
811                         if (ecmd.advertising & ADVERTISED_1000baseT_Half)
812                                 desc->advertised |= OFPPF_1GB_HD;
813                         if (ecmd.advertising & ADVERTISED_1000baseT_Full)
814                                 desc->advertised |= OFPPF_1GB_FD;
815                         if (ecmd.advertising & ADVERTISED_10000baseT_Full)
816                                 desc->advertised |= OFPPF_10GB_FD;
817                         if (ecmd.advertising & ADVERTISED_TP)
818                                 desc->advertised |= OFPPF_COPPER;
819                         if (ecmd.advertising & ADVERTISED_FIBRE)
820                                 desc->advertised |= OFPPF_FIBER;
821                         if (ecmd.advertising & ADVERTISED_Autoneg)
822                                 desc->advertised |= OFPPF_AUTONEG;
823 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,14)
824                         if (ecmd.advertising & ADVERTISED_Pause)
825                                 desc->advertised |= OFPPF_PAUSE;
826                         if (ecmd.advertising & ADVERTISED_Asym_Pause)
827                                 desc->advertised |= OFPPF_PAUSE_ASYM;
828 #endif /* kernel >= 2.6.14 */
829
830                         /* Set the current features */
831                         if (ecmd.speed == SPEED_10)
832                                 desc->curr = (ecmd.duplex) ? OFPPF_10MB_FD : OFPPF_10MB_HD;
833                         else if (ecmd.speed == SPEED_100)
834                                 desc->curr = (ecmd.duplex) ? OFPPF_100MB_FD : OFPPF_100MB_HD;
835                         else if (ecmd.speed == SPEED_1000)
836                                 desc->curr = (ecmd.duplex) ? OFPPF_1GB_FD : OFPPF_1GB_HD;
837                         else if (ecmd.speed == SPEED_10000)
838                                 desc->curr = OFPPF_10GB_FD;
839
840                         if (ecmd.port == PORT_TP) 
841                                 desc->curr |= OFPPF_COPPER;
842                         else if (ecmd.port == PORT_FIBRE) 
843                                 desc->curr |= OFPPF_FIBER;
844
845                         if (ecmd.autoneg)
846                                 desc->curr |= OFPPF_AUTONEG;
847                 }
848         }
849 #endif
850         desc->curr = htonl(desc->curr);
851         desc->supported = htonl(desc->supported);
852         desc->advertised = htonl(desc->advertised);
853         desc->peer = htonl(desc->peer);
854 }
855
856 static int 
857 fill_features_reply(struct datapath *dp, struct ofp_switch_features *ofr)
858 {
859         struct net_bridge_port *p;
860         uint64_t dpid = get_datapath_id(dp->netdev);
861         int port_count = 0;
862
863         ofr->datapath_id  = cpu_to_be64(dpid);
864
865         ofr->n_buffers    = htonl(N_PKT_BUFFERS);
866         ofr->n_tables     = dp->chain->n_tables;
867         ofr->capabilities = htonl(OFP_SUPPORTED_CAPABILITIES);
868         ofr->actions      = htonl(OFP_SUPPORTED_ACTIONS);
869         memset(ofr->pad, 0, sizeof ofr->pad);
870
871         list_for_each_entry_rcu (p, &dp->port_list, node) {
872                 fill_port_desc(p, &ofr->ports[port_count]);
873                 port_count++;
874         }
875
876         return port_count;
877 }
878
879 int
880 dp_send_features_reply(struct datapath *dp, const struct sender *sender)
881 {
882         struct sk_buff *skb;
883         struct ofp_switch_features *ofr;
884         size_t ofr_len, port_max_len;
885         int port_count;
886
887         /* Overallocate. */
888         port_max_len = sizeof(struct ofp_phy_port) * DP_MAX_PORTS;
889         ofr = alloc_openflow_skb(dp, sizeof(*ofr) + port_max_len,
890                                  OFPT_FEATURES_REPLY, sender, &skb);
891         if (!ofr)
892                 return -ENOMEM;
893
894         /* Fill. */
895         port_count = fill_features_reply(dp, ofr);
896
897         /* Shrink to fit. */
898         ofr_len = sizeof(*ofr) + (sizeof(struct ofp_phy_port) * port_count);
899         resize_openflow_skb(skb, &ofr->header, ofr_len);
900         return send_openflow_skb(skb, sender);
901 }
902
903 int
904 dp_send_config_reply(struct datapath *dp, const struct sender *sender)
905 {
906         struct sk_buff *skb;
907         struct ofp_switch_config *osc;
908
909         osc = alloc_openflow_skb(dp, sizeof *osc, OFPT_GET_CONFIG_REPLY, sender,
910                                  &skb);
911         if (!osc)
912                 return -ENOMEM;
913
914         osc->flags = htons(dp->flags);
915         osc->miss_send_len = htons(dp->miss_send_len);
916
917         return send_openflow_skb(skb, sender);
918 }
919
920 int
921 dp_send_hello(struct datapath *dp, const struct sender *sender,
922               const struct ofp_header *request)
923 {
924         if (request->version < OFP_VERSION) {
925                 char err[64];
926                 sprintf(err, "Only version 0x%02x supported", OFP_VERSION);
927                 dp_send_error_msg(dp, sender, OFPET_HELLO_FAILED,
928                                   OFPHFC_INCOMPATIBLE, err, strlen(err));
929                 return -EINVAL;
930         } else {
931                 struct sk_buff *skb;
932                 struct ofp_header *reply;
933
934                 reply = alloc_openflow_skb(dp, sizeof *reply,
935                                            OFPT_HELLO, sender, &skb);
936                 if (!reply)
937                         return -ENOMEM;
938
939                 return send_openflow_skb(skb, sender);
940         }
941 }
942
943 /* Callback function for a workqueue to disable an interface */
944 static void
945 down_port_cb(struct work_struct *work)
946 {
947         struct net_bridge_port *p = container_of(work, struct net_bridge_port, 
948                         port_task);
949
950         rtnl_lock();
951         if (dev_change_flags(p->dev, p->dev->flags & ~IFF_UP) < 0)
952                 if (net_ratelimit())
953                         printk("problem bringing up port %s\n", p->dev->name);
954         rtnl_unlock();
955         p->config |= OFPPC_PORT_DOWN;
956 }
957
958 /* Callback function for a workqueue to enable an interface */
959 static void
960 up_port_cb(struct work_struct *work)
961 {
962         struct net_bridge_port *p = container_of(work, struct net_bridge_port, 
963                         port_task);
964
965         rtnl_lock();
966         if (dev_change_flags(p->dev, p->dev->flags | IFF_UP) < 0)
967                 if (net_ratelimit())
968                         printk("problem bringing down port %s\n", p->dev->name);
969         rtnl_unlock();
970         p->config &= ~OFPPC_PORT_DOWN;
971 }
972
973 int
974 dp_update_port_flags(struct datapath *dp, const struct ofp_port_mod *opm)
975 {
976         unsigned long int flags;
977         int port_no = ntohs(opm->port_no);
978         struct net_bridge_port *p;
979         p = (port_no < DP_MAX_PORTS ? dp->ports[port_no]
980              : port_no == OFPP_LOCAL ? dp->local_port
981              : NULL);
982
983         /* Make sure the port id hasn't changed since this was sent */
984         if (!p || memcmp(opm->hw_addr, p->dev->dev_addr, ETH_ALEN))
985                 return -1;
986
987         spin_lock_irqsave(&p->lock, flags);
988         if (opm->mask) {
989                 uint32_t config_mask = ntohl(opm->mask);
990                 p->config &= ~config_mask;
991                 p->config |= ntohl(opm->config) & config_mask;
992         }
993
994         /* Modifying the status of an interface requires taking a lock
995          * that cannot be done from here.  For this reason, we use a shared 
996          * workqueue, which will cause it to be executed from a safer 
997          * context. */
998         if (opm->mask & htonl(OFPPC_PORT_DOWN)) {
999                 if ((opm->config & htonl(OFPPC_PORT_DOWN))
1000                     && (p->config & OFPPC_PORT_DOWN) == 0) {
1001                         PREPARE_WORK(&p->port_task, down_port_cb);
1002                         schedule_work(&p->port_task);
1003                 } else if ((opm->config & htonl(OFPPC_PORT_DOWN)) == 0
1004                            && (p->config & OFPPC_PORT_DOWN)) {
1005                         PREPARE_WORK(&p->port_task, up_port_cb);
1006                         schedule_work(&p->port_task);
1007                 }
1008         }
1009         spin_unlock_irqrestore(&p->lock, flags);
1010
1011         return 0;
1012 }
1013
1014 /* Initialize the port status field of the bridge port. */
1015 static void
1016 init_port_status(struct net_bridge_port *p)
1017 {
1018         unsigned long int flags;
1019
1020         spin_lock_irqsave(&p->lock, flags);
1021
1022         if (p->dev->flags & IFF_UP) 
1023                 p->config &= ~OFPPC_PORT_DOWN;
1024         else
1025                 p->config |= OFPPC_PORT_DOWN;
1026
1027         if (netif_carrier_ok(p->dev))
1028                 p->state &= ~OFPPS_LINK_DOWN;
1029         else
1030                 p->state |= OFPPS_LINK_DOWN;
1031
1032         spin_unlock_irqrestore(&p->lock, flags);
1033 }
1034
1035 int
1036 dp_send_port_status(struct net_bridge_port *p, uint8_t status)
1037 {
1038         struct sk_buff *skb;
1039         struct ofp_port_status *ops;
1040
1041         ops = alloc_openflow_skb(p->dp, sizeof *ops, OFPT_PORT_STATUS, NULL,
1042                                  &skb);
1043         if (!ops)
1044                 return -ENOMEM;
1045         ops->reason = status;
1046         memset(ops->pad, 0, sizeof ops->pad);
1047         fill_port_desc(p, &ops->desc);
1048
1049         return send_openflow_skb(skb, NULL);
1050 }
1051
1052 /* Convert jiffies_64 to milliseconds. */
1053 static u64 inline jiffies_64_to_msecs(const u64 j)
1054 {
1055 #if HZ <= MSEC_PER_SEC && !(MSEC_PER_SEC % HZ)
1056                 return (MSEC_PER_SEC / HZ) * j;
1057 #elif HZ > MSEC_PER_SEC && !(HZ % MSEC_PER_SEC)
1058                 return (j + (HZ / MSEC_PER_SEC) - 1)/(HZ / MSEC_PER_SEC);
1059 #else
1060                 return (j * MSEC_PER_SEC) / HZ;
1061 #endif
1062 }
1063
1064 int 
1065 dp_send_flow_end(struct datapath *dp, struct sw_flow *flow,
1066                      enum nx_flow_end_reason reason)
1067 {
1068         struct sk_buff *skb;
1069         struct nx_flow_end *nfe;
1070
1071         if (!dp->send_flow_end)
1072                 return 0;
1073
1074         nfe = alloc_openflow_skb(dp, sizeof *nfe, OFPT_VENDOR, 0, &skb);
1075         if (!nfe)
1076                 return -ENOMEM;
1077
1078         nfe->header.vendor = htonl(NX_VENDOR_ID);
1079         nfe->header.subtype = htonl(NXT_FLOW_END);
1080
1081         flow_fill_match(&nfe->match, &flow->key);
1082
1083         nfe->priority = htons(flow->priority);
1084         nfe->reason = reason;
1085
1086         nfe->tcp_flags = flow->tcp_flags;
1087         nfe->ip_tos = flow->ip_tos;
1088
1089         memset(nfe->pad, 0, sizeof nfe->pad);
1090
1091         nfe->init_time = cpu_to_be64(jiffies_64_to_msecs(flow->created));
1092         nfe->used_time = cpu_to_be64(jiffies_64_to_msecs(flow->used));
1093         nfe->end_time = cpu_to_be64(jiffies_64_to_msecs(get_jiffies_64()));
1094
1095         nfe->packet_count = cpu_to_be64(flow->packet_count);
1096         nfe->byte_count   = cpu_to_be64(flow->byte_count);
1097
1098         return send_openflow_skb(skb, NULL);
1099 }
1100 EXPORT_SYMBOL(dp_send_flow_end);
1101
1102 int
1103 dp_send_error_msg(struct datapath *dp, const struct sender *sender, 
1104                 uint16_t type, uint16_t code, const void *data, size_t len)
1105 {
1106         struct sk_buff *skb;
1107         struct ofp_error_msg *oem;
1108
1109
1110         oem = alloc_openflow_skb(dp, sizeof(*oem)+len, OFPT_ERROR, 
1111                         sender, &skb);
1112         if (!oem)
1113                 return -ENOMEM;
1114
1115         oem->type = htons(type);
1116         oem->code = htons(code);
1117         memcpy(oem->data, data, len);
1118
1119         return send_openflow_skb(skb, sender);
1120 }
1121
1122 int
1123 dp_send_echo_reply(struct datapath *dp, const struct sender *sender,
1124                    const struct ofp_header *rq)
1125 {
1126         struct sk_buff *skb;
1127         struct ofp_header *reply;
1128
1129         reply = alloc_openflow_skb(dp, ntohs(rq->length), OFPT_ECHO_REPLY,
1130                                    sender, &skb);
1131         if (!reply)
1132                 return -ENOMEM;
1133
1134         memcpy(reply + 1, rq + 1, ntohs(rq->length) - sizeof *rq);
1135         return send_openflow_skb(skb, sender);
1136 }
1137
1138 /* Generic Netlink interface.
1139  *
1140  * See netlink(7) for an introduction to netlink.  See
1141  * http://linux-net.osdl.org/index.php/Netlink for more information and
1142  * pointers on how to work with netlink and Generic Netlink in the kernel and
1143  * in userspace. */
1144
1145 static struct genl_family dp_genl_family = {
1146         .id = GENL_ID_GENERATE,
1147         .hdrsize = 0,
1148         .name = DP_GENL_FAMILY_NAME,
1149         .version = 1,
1150         .maxattr = DP_GENL_A_MAX,
1151 };
1152
1153 /* Attribute policy: what each attribute may contain.  */
1154 static struct nla_policy dp_genl_policy[DP_GENL_A_MAX + 1] = {
1155         [DP_GENL_A_DP_IDX] = { .type = NLA_U32 },
1156         [DP_GENL_A_MC_GROUP] = { .type = NLA_U32 },
1157         [DP_GENL_A_PORTNAME] = { .type = NLA_STRING }
1158 };
1159
1160 static int dp_genl_add(struct sk_buff *skb, struct genl_info *info)
1161 {
1162         if (!info->attrs[DP_GENL_A_DP_IDX])
1163                 return -EINVAL;
1164
1165         return new_dp(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
1166 }
1167
1168 static struct genl_ops dp_genl_ops_add_dp = {
1169         .cmd = DP_GENL_C_ADD_DP,
1170         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1171         .policy = dp_genl_policy,
1172         .doit = dp_genl_add,
1173         .dumpit = NULL,
1174 };
1175
1176 struct datapath *dp_get(int dp_idx)
1177 {
1178         if (dp_idx < 0 || dp_idx >= DP_MAX)
1179                 return NULL;
1180         return rcu_dereference(dps[dp_idx]);
1181 }
1182
1183 static int dp_genl_del(struct sk_buff *skb, struct genl_info *info)
1184 {
1185         struct datapath *dp;
1186         int err;
1187
1188         if (!info->attrs[DP_GENL_A_DP_IDX])
1189                 return -EINVAL;
1190
1191         dp = dp_get(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
1192         if (!dp)
1193                 err = -ENOENT;
1194         else {
1195                 del_dp(dp);
1196                 err = 0;
1197         }
1198         return err;
1199 }
1200
1201 static struct genl_ops dp_genl_ops_del_dp = {
1202         .cmd = DP_GENL_C_DEL_DP,
1203         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1204         .policy = dp_genl_policy,
1205         .doit = dp_genl_del,
1206         .dumpit = NULL,
1207 };
1208
1209 /* Queries a datapath for related information.  Currently the only relevant
1210  * information is the datapath's multicast group ID.  Really we want one
1211  * multicast group per datapath, but because of locking issues[*] we can't
1212  * easily get one.  Thus, every datapath will currently return the same
1213  * global multicast group ID, but in the future it would be nice to fix that.
1214  *
1215  * [*] dp_genl_add, to add a new datapath, is called under the genl_lock
1216  *       mutex, and genl_register_mc_group, called to acquire a new multicast
1217  *       group ID, also acquires genl_lock, thus deadlock.
1218  */
1219 static int dp_genl_query(struct sk_buff *skb, struct genl_info *info)
1220 {
1221         struct datapath *dp;
1222         struct sk_buff *ans_skb = NULL;
1223         int dp_idx;
1224         int err = -ENOMEM;
1225
1226         if (!info->attrs[DP_GENL_A_DP_IDX])
1227                 return -EINVAL;
1228
1229         rcu_read_lock();
1230         dp_idx = nla_get_u32((info->attrs[DP_GENL_A_DP_IDX]));
1231         dp = dp_get(dp_idx);
1232         if (!dp)
1233                 err = -ENOENT;
1234         else {
1235                 void *data;
1236                 ans_skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
1237                 if (!ans_skb) {
1238                         err = -ENOMEM;
1239                         goto err;
1240                 }
1241                 data = genlmsg_put_reply(ans_skb, info, &dp_genl_family,
1242                                          0, DP_GENL_C_QUERY_DP);
1243                 if (data == NULL) {
1244                         err = -ENOMEM;
1245                         goto err;
1246                 }
1247                 NLA_PUT_U32(ans_skb, DP_GENL_A_DP_IDX, dp_idx);
1248                 NLA_PUT_U32(ans_skb, DP_GENL_A_MC_GROUP, mc_group.id);
1249
1250                 genlmsg_end(ans_skb, data);
1251                 err = genlmsg_reply(ans_skb, info);
1252                 ans_skb = NULL;
1253         }
1254 err:
1255 nla_put_failure:
1256         kfree_skb(ans_skb);
1257         rcu_read_unlock();
1258         return err;
1259 }
1260
1261 static struct genl_ops dp_genl_ops_query_dp = {
1262         .cmd = DP_GENL_C_QUERY_DP,
1263         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1264         .policy = dp_genl_policy,
1265         .doit = dp_genl_query,
1266         .dumpit = NULL,
1267 };
1268
1269 static int dp_genl_add_del_port(struct sk_buff *skb, struct genl_info *info)
1270 {
1271         struct datapath *dp;
1272         struct net_device *port;
1273         int err;
1274
1275         if (!info->attrs[DP_GENL_A_DP_IDX] || !info->attrs[DP_GENL_A_PORTNAME])
1276                 return -EINVAL;
1277
1278         /* Get datapath. */
1279         dp = dp_get(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
1280         if (!dp) {
1281                 err = -ENOENT;
1282                 goto out;
1283         }
1284
1285         /* Get interface to add/remove. */
1286         port = dev_get_by_name(&init_net, 
1287                         nla_data(info->attrs[DP_GENL_A_PORTNAME]));
1288         if (!port) {
1289                 err = -ENOENT;
1290                 goto out;
1291         }
1292
1293         /* Execute operation. */
1294         if (info->genlhdr->cmd == DP_GENL_C_ADD_PORT)
1295                 err = add_switch_port(dp, port);
1296         else {
1297                 if (port->br_port == NULL || port->br_port->dp != dp) {
1298                         err = -ENOENT;
1299                         goto out_put;
1300                 }
1301                 err = dp_del_switch_port(port->br_port);
1302         }
1303
1304 out_put:
1305         dev_put(port);
1306 out:
1307         return err;
1308 }
1309
1310 static struct genl_ops dp_genl_ops_add_port = {
1311         .cmd = DP_GENL_C_ADD_PORT,
1312         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1313         .policy = dp_genl_policy,
1314         .doit = dp_genl_add_del_port,
1315         .dumpit = NULL,
1316 };
1317
1318 static struct genl_ops dp_genl_ops_del_port = {
1319         .cmd = DP_GENL_C_DEL_PORT,
1320         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1321         .policy = dp_genl_policy,
1322         .doit = dp_genl_add_del_port,
1323         .dumpit = NULL,
1324 };
1325
1326 static int dp_genl_openflow(struct sk_buff *skb, struct genl_info *info)
1327 {
1328         struct nlattr *va = info->attrs[DP_GENL_A_OPENFLOW];
1329         struct datapath *dp;
1330         struct ofp_header *oh;
1331         struct sender sender;
1332         int err;
1333
1334         if (!info->attrs[DP_GENL_A_DP_IDX] || !va)
1335                 return -EINVAL;
1336
1337         dp = dp_get(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
1338         if (!dp)
1339                 return -ENOENT;
1340
1341         if (nla_len(va) < sizeof(struct ofp_header))
1342                 return -EINVAL;
1343         oh = nla_data(va);
1344
1345         sender.xid = oh->xid;
1346         sender.pid = info->snd_pid;
1347         sender.seq = info->snd_seq;
1348
1349         mutex_lock(&dp_mutex);
1350         err = fwd_control_input(dp->chain, &sender,
1351                                 nla_data(va), nla_len(va));
1352         mutex_unlock(&dp_mutex);
1353         return err;
1354 }
1355
1356 static struct nla_policy dp_genl_openflow_policy[DP_GENL_A_MAX + 1] = {
1357         [DP_GENL_A_DP_IDX] = { .type = NLA_U32 },
1358 };
1359
1360 static int desc_stats_dump(struct datapath *dp, void *state,
1361                             void *body, int *body_len)
1362 {
1363         struct ofp_desc_stats *ods = body;
1364         int n_bytes = sizeof *ods;
1365
1366         if (n_bytes > *body_len) {
1367                 return -ENOBUFS;
1368         }
1369         *body_len = n_bytes;
1370
1371         strncpy(ods->mfr_desc, mfr_desc, sizeof ods->mfr_desc);
1372         strncpy(ods->hw_desc, hw_desc, sizeof ods->hw_desc);
1373         strncpy(ods->sw_desc, sw_desc, sizeof ods->sw_desc);
1374         strncpy(ods->serial_num, serial_num, sizeof ods->serial_num);
1375
1376         return 0;
1377 }
1378
1379 struct flow_stats_state {
1380         int table_idx;
1381         struct sw_table_position position;
1382         const struct ofp_flow_stats_request *rq;
1383
1384         void *body;
1385         int bytes_used, bytes_allocated;
1386 };
1387
1388 static int flow_stats_init(struct datapath *dp, const void *body, int body_len,
1389                            void **state)
1390 {
1391         const struct ofp_flow_stats_request *fsr = body;
1392         struct flow_stats_state *s = kmalloc(sizeof *s, GFP_ATOMIC);
1393         if (!s)
1394                 return -ENOMEM;
1395         s->table_idx = fsr->table_id == 0xff ? 0 : fsr->table_id;
1396         memset(&s->position, 0, sizeof s->position);
1397         s->rq = fsr;
1398         *state = s;
1399         return 0;
1400 }
1401
1402 static int flow_stats_dump_callback(struct sw_flow *flow, void *private)
1403 {
1404         struct sw_flow_actions *sf_acts = rcu_dereference(flow->sf_acts);
1405         struct flow_stats_state *s = private;
1406         struct ofp_flow_stats *ofs;
1407         int length;
1408         uint64_t duration;
1409
1410         length = sizeof *ofs + sf_acts->actions_len;
1411         if (length + s->bytes_used > s->bytes_allocated)
1412                 return 1;
1413
1414         ofs = s->body + s->bytes_used;
1415         ofs->length          = htons(length);
1416         ofs->table_id        = s->table_idx;
1417         ofs->pad             = 0;
1418         ofs->match.wildcards = htonl(flow->key.wildcards);
1419         ofs->match.in_port   = flow->key.in_port;
1420         memcpy(ofs->match.dl_src, flow->key.dl_src, ETH_ALEN);
1421         memcpy(ofs->match.dl_dst, flow->key.dl_dst, ETH_ALEN);
1422         ofs->match.dl_vlan   = flow->key.dl_vlan;
1423         ofs->match.dl_type   = flow->key.dl_type;
1424         ofs->match.nw_src    = flow->key.nw_src;
1425         ofs->match.nw_dst    = flow->key.nw_dst;
1426         ofs->match.nw_proto  = flow->key.nw_proto;
1427         ofs->match.pad       = 0;
1428         ofs->match.tp_src    = flow->key.tp_src;
1429         ofs->match.tp_dst    = flow->key.tp_dst;
1430
1431         /* The kernel doesn't support 64-bit division, so use the 'do_div' 
1432          * macro instead.  The first argument is replaced with the quotient,
1433          * while the remainder is the return value. */
1434         duration = get_jiffies_64() - flow->created;
1435         do_div(duration, HZ);
1436         ofs->duration        = htonl(duration);
1437
1438         ofs->priority        = htons(flow->priority);
1439         ofs->idle_timeout    = htons(flow->idle_timeout);
1440         ofs->hard_timeout    = htons(flow->hard_timeout);
1441         memset(ofs->pad2, 0, sizeof ofs->pad2);
1442         ofs->packet_count    = cpu_to_be64(flow->packet_count);
1443         ofs->byte_count      = cpu_to_be64(flow->byte_count);
1444         memcpy(ofs->actions, sf_acts->actions, sf_acts->actions_len);
1445
1446         s->bytes_used += length;
1447         return 0;
1448 }
1449
1450 static int flow_stats_dump(struct datapath *dp, void *state,
1451                            void *body, int *body_len)
1452 {
1453         struct flow_stats_state *s = state;
1454         struct sw_flow_key match_key;
1455         int error = 0;
1456
1457         s->bytes_used = 0;
1458         s->bytes_allocated = *body_len;
1459         s->body = body;
1460
1461         flow_extract_match(&match_key, &s->rq->match);
1462         while (s->table_idx < dp->chain->n_tables
1463                && (s->rq->table_id == 0xff || s->rq->table_id == s->table_idx))
1464         {
1465                 struct sw_table *table = dp->chain->tables[s->table_idx];
1466
1467                 error = table->iterate(table, &match_key, s->rq->out_port, 
1468                                 &s->position, flow_stats_dump_callback, s);
1469                 if (error)
1470                         break;
1471
1472                 s->table_idx++;
1473                 memset(&s->position, 0, sizeof s->position);
1474         }
1475         *body_len = s->bytes_used;
1476
1477         /* If error is 0, we're done.
1478          * Otherwise, if some bytes were used, there are more flows to come.
1479          * Otherwise, we were not able to fit even a single flow in the body,
1480          * which indicates that we have a single flow with too many actions to
1481          * fit.  We won't ever make any progress at that rate, so give up. */
1482         return !error ? 0 : s->bytes_used ? 1 : -ENOMEM;
1483 }
1484
1485 static void flow_stats_done(void *state)
1486 {
1487         kfree(state);
1488 }
1489
1490 static int aggregate_stats_init(struct datapath *dp,
1491                                 const void *body, int body_len,
1492                                 void **state)
1493 {
1494         *state = (void *)body;
1495         return 0;
1496 }
1497
1498 static int aggregate_stats_dump_callback(struct sw_flow *flow, void *private)
1499 {
1500         struct ofp_aggregate_stats_reply *rpy = private;
1501         rpy->packet_count += flow->packet_count;
1502         rpy->byte_count += flow->byte_count;
1503         rpy->flow_count++;
1504         return 0;
1505 }
1506
1507 static int aggregate_stats_dump(struct datapath *dp, void *state,
1508                                 void *body, int *body_len)
1509 {
1510         struct ofp_aggregate_stats_request *rq = state;
1511         struct ofp_aggregate_stats_reply *rpy;
1512         struct sw_table_position position;
1513         struct sw_flow_key match_key;
1514         int table_idx;
1515
1516         if (*body_len < sizeof *rpy)
1517                 return -ENOBUFS;
1518         rpy = body;
1519         *body_len = sizeof *rpy;
1520
1521         memset(rpy, 0, sizeof *rpy);
1522
1523         flow_extract_match(&match_key, &rq->match);
1524         table_idx = rq->table_id == 0xff ? 0 : rq->table_id;
1525         memset(&position, 0, sizeof position);
1526         while (table_idx < dp->chain->n_tables
1527                && (rq->table_id == 0xff || rq->table_id == table_idx))
1528         {
1529                 struct sw_table *table = dp->chain->tables[table_idx];
1530                 int error;
1531
1532                 error = table->iterate(table, &match_key, rq->out_port, &position,
1533                                        aggregate_stats_dump_callback, rpy);
1534                 if (error)
1535                         return error;
1536
1537                 table_idx++;
1538                 memset(&position, 0, sizeof position);
1539         }
1540
1541         rpy->packet_count = cpu_to_be64(rpy->packet_count);
1542         rpy->byte_count = cpu_to_be64(rpy->byte_count);
1543         rpy->flow_count = htonl(rpy->flow_count);
1544         return 0;
1545 }
1546
1547 static int table_stats_dump(struct datapath *dp, void *state,
1548                             void *body, int *body_len)
1549 {
1550         struct ofp_table_stats *ots;
1551         int n_bytes = dp->chain->n_tables * sizeof *ots;
1552         int i;
1553         if (n_bytes > *body_len)
1554                 return -ENOBUFS;
1555         *body_len = n_bytes;
1556         for (i = 0, ots = body; i < dp->chain->n_tables; i++, ots++) {
1557                 struct sw_table_stats stats;
1558                 dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
1559                 strncpy(ots->name, stats.name, sizeof ots->name);
1560                 ots->table_id = i;
1561                 ots->wildcards = htonl(stats.wildcards);
1562                 memset(ots->pad, 0, sizeof ots->pad);
1563                 ots->max_entries = htonl(stats.max_flows);
1564                 ots->active_count = htonl(stats.n_flows);
1565                 ots->lookup_count = cpu_to_be64(stats.n_lookup);
1566                 ots->matched_count = cpu_to_be64(stats.n_matched);
1567         }
1568         return 0;
1569 }
1570
1571 struct port_stats_state {
1572         int port;
1573 };
1574
1575 static int port_stats_init(struct datapath *dp, const void *body, int body_len,
1576                            void **state)
1577 {
1578         struct port_stats_state *s = kmalloc(sizeof *s, GFP_ATOMIC);
1579         if (!s)
1580                 return -ENOMEM;
1581         s->port = 0;
1582         *state = s;
1583         return 0;
1584 }
1585
1586 static int port_stats_dump(struct datapath *dp, void *state,
1587                            void *body, int *body_len)
1588 {
1589         struct port_stats_state *s = state;
1590         struct ofp_port_stats *ops;
1591         int n_ports, max_ports;
1592         int i;
1593
1594         max_ports = *body_len / sizeof *ops;
1595         if (!max_ports)
1596                 return -ENOMEM;
1597         ops = body;
1598
1599         n_ports = 0;
1600         for (i = s->port; i < DP_MAX_PORTS && n_ports < max_ports; i++) {
1601                 struct net_bridge_port *p = dp->ports[i];
1602                 struct net_device_stats *stats;
1603                 if (!p)
1604                         continue;
1605                 stats = p->dev->get_stats(p->dev);
1606                 ops->port_no = htons(p->port_no);
1607                 memset(ops->pad, 0, sizeof ops->pad);
1608                 ops->rx_packets   = cpu_to_be64(stats->rx_packets);
1609                 ops->tx_packets   = cpu_to_be64(stats->tx_packets);
1610                 ops->rx_bytes     = cpu_to_be64(stats->rx_bytes);
1611                 ops->tx_bytes     = cpu_to_be64(stats->tx_bytes);
1612                 ops->rx_dropped   = cpu_to_be64(stats->rx_dropped);
1613                 ops->tx_dropped   = cpu_to_be64(stats->tx_dropped);
1614                 ops->rx_errors    = cpu_to_be64(stats->rx_errors);
1615                 ops->tx_errors    = cpu_to_be64(stats->tx_errors);
1616                 ops->rx_frame_err = cpu_to_be64(stats->rx_frame_errors);
1617                 ops->rx_over_err  = cpu_to_be64(stats->rx_over_errors);
1618                 ops->rx_crc_err   = cpu_to_be64(stats->rx_crc_errors);
1619                 ops->collisions   = cpu_to_be64(stats->collisions);
1620                 n_ports++;
1621                 ops++;
1622         }
1623         s->port = i;
1624         *body_len = n_ports * sizeof *ops;
1625         return n_ports >= max_ports;
1626 }
1627
1628 static void port_stats_done(void *state)
1629 {
1630         kfree(state);
1631 }
1632
1633 struct stats_type {
1634         /* Minimum and maximum acceptable number of bytes in body member of
1635          * struct ofp_stats_request. */
1636         size_t min_body, max_body;
1637
1638         /* Prepares to dump some kind of statistics on 'dp'.  'body' and
1639          * 'body_len' are the 'body' member of the struct ofp_stats_request.
1640          * Returns zero if successful, otherwise a negative error code.
1641          * May initialize '*state' to state information.  May be null if no
1642          * initialization is required.*/
1643         int (*init)(struct datapath *dp, const void *body, int body_len,
1644                     void **state);
1645
1646         /* Dumps statistics for 'dp' into the '*body_len' bytes at 'body', and
1647          * modifies '*body_len' to reflect the number of bytes actually used.
1648          * ('body' will be transmitted as the 'body' member of struct
1649          * ofp_stats_reply.) */
1650         int (*dump)(struct datapath *dp, void *state,
1651                     void *body, int *body_len);
1652
1653         /* Cleans any state created by the init or dump functions.  May be null
1654          * if no cleanup is required. */
1655         void (*done)(void *state);
1656 };
1657
1658 static const struct stats_type stats[] = {
1659         [OFPST_DESC] = {
1660                 0,
1661                 0,
1662                 NULL,
1663                 desc_stats_dump,
1664                 NULL
1665         },
1666         [OFPST_FLOW] = {
1667                 sizeof(struct ofp_flow_stats_request),
1668                 sizeof(struct ofp_flow_stats_request),
1669                 flow_stats_init,
1670                 flow_stats_dump,
1671                 flow_stats_done
1672         },
1673         [OFPST_AGGREGATE] = {
1674                 sizeof(struct ofp_aggregate_stats_request),
1675                 sizeof(struct ofp_aggregate_stats_request),
1676                 aggregate_stats_init,
1677                 aggregate_stats_dump,
1678                 NULL
1679         },
1680         [OFPST_TABLE] = {
1681                 0,
1682                 0,
1683                 NULL,
1684                 table_stats_dump,
1685                 NULL
1686         },
1687         [OFPST_PORT] = {
1688                 0,
1689                 0,
1690                 port_stats_init,
1691                 port_stats_dump,
1692                 port_stats_done
1693         },
1694 };
1695
1696 static int
1697 dp_genl_openflow_dumpit(struct sk_buff *skb, struct netlink_callback *cb)
1698 {
1699         struct datapath *dp;
1700         struct sender sender;
1701         const struct stats_type *s;
1702         struct ofp_stats_reply *osr;
1703         int dp_idx;
1704         int max_openflow_len, body_len;
1705         void *body;
1706         int err;
1707
1708         /* Set up the cleanup function for this dump.  Linux 2.6.20 and later
1709          * support setting up cleanup functions via the .doneit member of
1710          * struct genl_ops.  This kluge supports earlier versions also. */
1711         cb->done = dp_genl_openflow_done;
1712
1713         sender.pid = NETLINK_CB(cb->skb).pid;
1714         sender.seq = cb->nlh->nlmsg_seq;
1715         if (!cb->args[0]) {
1716                 struct nlattr *attrs[DP_GENL_A_MAX + 1];
1717                 struct ofp_stats_request *rq;
1718                 struct nlattr *va;
1719                 size_t len, body_len;
1720                 int type;
1721
1722                 err = nlmsg_parse(cb->nlh, GENL_HDRLEN, attrs, DP_GENL_A_MAX,
1723                                   dp_genl_openflow_policy);
1724                 if (err < 0)
1725                         return err;
1726
1727                 if (!attrs[DP_GENL_A_DP_IDX])
1728                         return -EINVAL;
1729                 dp_idx = nla_get_u16(attrs[DP_GENL_A_DP_IDX]);
1730                 dp = dp_get(dp_idx);
1731                 if (!dp)
1732                         return -ENOENT;
1733
1734                 va = attrs[DP_GENL_A_OPENFLOW];
1735                 len = nla_len(va);
1736                 if (!va || len < sizeof *rq)
1737                         return -EINVAL;
1738
1739                 rq = nla_data(va);
1740                 sender.xid = rq->header.xid;
1741                 type = ntohs(rq->type);
1742                 if (rq->header.version != OFP_VERSION) {
1743                         dp_send_error_msg(dp, &sender, OFPET_BAD_REQUEST,
1744                                           OFPBRC_BAD_VERSION, rq, len);
1745                         return -EINVAL;
1746                 }
1747                 if (rq->header.type != OFPT_STATS_REQUEST
1748                     || ntohs(rq->header.length) != len)
1749                         return -EINVAL;
1750
1751                 if (type >= ARRAY_SIZE(stats) || !stats[type].dump) {
1752                         dp_send_error_msg(dp, &sender, OFPET_BAD_REQUEST,
1753                                           OFPBRC_BAD_STAT, rq, len);
1754                         return -EINVAL;
1755                 }
1756
1757                 s = &stats[type];
1758                 body_len = len - offsetof(struct ofp_stats_request, body);
1759                 if (body_len < s->min_body || body_len > s->max_body)
1760                         return -EINVAL;
1761
1762                 cb->args[0] = 1;
1763                 cb->args[1] = dp_idx;
1764                 cb->args[2] = type;
1765                 cb->args[3] = rq->header.xid;
1766                 if (s->init) {
1767                         void *state;
1768                         err = s->init(dp, rq->body, body_len, &state);
1769                         if (err)
1770                                 return err;
1771                         cb->args[4] = (long) state;
1772                 }
1773         } else if (cb->args[0] == 1) {
1774                 sender.xid = cb->args[3];
1775                 dp_idx = cb->args[1];
1776                 s = &stats[cb->args[2]];
1777
1778                 dp = dp_get(dp_idx);
1779                 if (!dp)
1780                         return -ENOENT;
1781         } else {
1782                 return 0;
1783         }
1784
1785         osr = put_openflow_headers(dp, skb, OFPT_STATS_REPLY, &sender,
1786                                    &max_openflow_len);
1787         if (IS_ERR(osr))
1788                 return PTR_ERR(osr);
1789         osr->type = htons(s - stats);
1790         osr->flags = 0;
1791         resize_openflow_skb(skb, &osr->header, max_openflow_len);
1792         body = osr->body;
1793         body_len = max_openflow_len - offsetof(struct ofp_stats_reply, body);
1794
1795         err = s->dump(dp, (void *) cb->args[4], body, &body_len);
1796         if (err >= 0) {
1797                 if (!err)
1798                         cb->args[0] = 2;
1799                 else
1800                         osr->flags = ntohs(OFPSF_REPLY_MORE);
1801                 resize_openflow_skb(skb, &osr->header,
1802                                     (offsetof(struct ofp_stats_reply, body)
1803                                      + body_len));
1804                 err = skb->len;
1805         }
1806
1807         return err;
1808 }
1809
1810 static int
1811 dp_genl_openflow_done(struct netlink_callback *cb)
1812 {
1813         if (cb->args[0]) {
1814                 const struct stats_type *s = &stats[cb->args[2]];
1815                 if (s->done)
1816                         s->done((void *) cb->args[4]);
1817         }
1818         return 0;
1819 }
1820
1821 static struct genl_ops dp_genl_ops_openflow = {
1822         .cmd = DP_GENL_C_OPENFLOW,
1823         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1824         .policy = dp_genl_openflow_policy,
1825         .doit = dp_genl_openflow,
1826         .dumpit = dp_genl_openflow_dumpit,
1827 };
1828
1829 static struct genl_ops *dp_genl_all_ops[] = {
1830         /* Keep this operation first.  Generic Netlink dispatching
1831          * looks up operations with linear search, so we want it at the
1832          * front. */
1833         &dp_genl_ops_openflow,
1834
1835         &dp_genl_ops_add_dp,
1836         &dp_genl_ops_del_dp,
1837         &dp_genl_ops_query_dp,
1838         &dp_genl_ops_add_port,
1839         &dp_genl_ops_del_port,
1840 };
1841
1842 static int dp_init_netlink(void)
1843 {
1844         int err;
1845         int i;
1846
1847         err = genl_register_family(&dp_genl_family);
1848         if (err)
1849                 return err;
1850
1851         for (i = 0; i < ARRAY_SIZE(dp_genl_all_ops); i++) {
1852                 err = genl_register_ops(&dp_genl_family, dp_genl_all_ops[i]);
1853                 if (err)
1854                         goto err_unregister;
1855         }
1856
1857         strcpy(mc_group.name, "openflow");
1858         err = genl_register_mc_group(&dp_genl_family, &mc_group);
1859         if (err < 0)
1860                 goto err_unregister;
1861
1862         return 0;
1863
1864 err_unregister:
1865         genl_unregister_family(&dp_genl_family);
1866                 return err;
1867 }
1868
1869 static void dp_uninit_netlink(void)
1870 {
1871         genl_unregister_family(&dp_genl_family);
1872 }
1873
1874 /* Set the description strings if appropriate values are available from
1875  * the DMI. */
1876 static void set_desc(void)
1877 {
1878         const char *uuid = dmi_get_system_info(DMI_PRODUCT_UUID);
1879         const char *vendor = dmi_get_system_info(DMI_SYS_VENDOR);
1880         const char *name = dmi_get_system_info(DMI_PRODUCT_NAME);
1881         const char *version = dmi_get_system_info(DMI_PRODUCT_VERSION);
1882         const char *serial = dmi_get_system_info(DMI_PRODUCT_SERIAL);
1883         const char *uptr;
1884
1885         if (!uuid || *uuid == '\0' || strlen(uuid) != 36) 
1886                 return;
1887
1888         /* We are only interested version 1 UUIDs, since the last six bytes
1889          * are an IEEE 802 MAC address. */
1890         if (uuid[14] != '1') 
1891                 return;
1892
1893         /* Only set if the UUID is from Nicira. */
1894         uptr = uuid + 24;
1895         if (strncmp(uptr, NICIRA_OUI_STR, strlen(NICIRA_OUI_STR)))
1896                 return;
1897
1898         if (vendor)
1899                 strlcpy(mfr_desc, vendor, sizeof(mfr_desc));
1900         if (name || version)
1901                 snprintf(hw_desc, sizeof(hw_desc), "%s %s",
1902                          name ? name : "",
1903                          version ? version : "");
1904         if (serial)
1905                 strlcpy(serial_num, serial, sizeof(serial_num));
1906 }
1907
1908 static int __init dp_init(void)
1909 {
1910         int err;
1911
1912         printk("OpenFlow %s, built "__DATE__" "__TIME__", "
1913                "protocol 0x%02x\n", VERSION BUILDNR, OFP_VERSION);
1914
1915         err = flow_init();
1916         if (err)
1917                 goto error;
1918
1919         err = register_netdevice_notifier(&dp_device_notifier);
1920         if (err)
1921                 goto error_flow_exit;
1922
1923         err = dp_init_netlink();
1924         if (err)
1925                 goto error_unreg_notifier;
1926
1927         /* Check if better descriptions of the switch are available than the
1928          * defaults. */
1929         set_desc();
1930
1931         /* Hook into callback used by the bridge to intercept packets.
1932          * Parasites we are. */
1933         if (br_handle_frame_hook)
1934                 printk("openflow: hijacking bridge hook\n");
1935         br_handle_frame_hook = dp_frame_hook;
1936
1937         return 0;
1938
1939 error_unreg_notifier:
1940         unregister_netdevice_notifier(&dp_device_notifier);
1941 error_flow_exit:
1942         flow_exit();
1943 error:
1944         printk(KERN_EMERG "openflow: failed to install!");
1945         return err;
1946 }
1947
1948 static void dp_cleanup(void)
1949 {
1950         fwd_exit();
1951         dp_uninit_netlink();
1952         unregister_netdevice_notifier(&dp_device_notifier);
1953         flow_exit();
1954         br_handle_frame_hook = NULL;
1955 }
1956
1957 module_init(dp_init);
1958 module_exit(dp_cleanup);
1959
1960 MODULE_DESCRIPTION("OpenFlow switching datapath");
1961 MODULE_AUTHOR("Copyright (c) 2007, 2008 The Board of Trustees of The Leland Stanford Junior University");
1962 MODULE_LICENSE("GPL");