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