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