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