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