Add max_idle field to flow stats messages.
[openvswitch] / 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
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: %d\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 or with flooding disabled */
511 static inline int should_deliver(const struct net_bridge_port *p,
512                         const struct sk_buff *skb)
513 {
514         if ((skb->dev == p->dev) || (p->flags & BRIDGE_PORT_NO_FLOOD)) {
515                 return 0;
516         } 
517
518         return 1;
519 }
520
521 static inline unsigned packet_length(const struct sk_buff *skb)
522 {
523         int length = skb->len - ETH_HLEN;
524         if (skb->protocol == htons(ETH_P_8021Q))
525                 length -= VLAN_HLEN;
526         return length;
527 }
528
529 static int
530 flood(struct datapath *dp, struct sk_buff *skb)
531 {
532         struct net_bridge_port *p;
533         int prev_port;
534
535         prev_port = -1;
536         list_for_each_entry_rcu (p, &dp->port_list, node) {
537                 if (!should_deliver(p, skb))
538                         continue;
539                 if (prev_port != -1) {
540                         struct sk_buff *clone = skb_clone(skb, GFP_ATOMIC);
541                         if (!clone) {
542                                 kfree_skb(skb);
543                                 return -ENOMEM;
544                         }
545                         dp_output_port(dp, clone, prev_port); 
546                 }
547                 prev_port = p->port_no;
548         }
549         if (prev_port != -1)
550                 dp_output_port(dp, skb, prev_port);
551         else
552                 kfree_skb(skb);
553
554         return 0;
555 }
556
557 /* Marks 'skb' as having originated from 'in_port' in 'dp'.
558    FIXME: how are devices reference counted? */
559 int dp_set_origin(struct datapath *dp, uint16_t in_port,
560                            struct sk_buff *skb)
561 {
562         if (in_port < OFPP_MAX && dp->ports[in_port]) {
563                 skb->dev = dp->ports[in_port]->dev;
564                 return 0;
565         }
566         return -ENOENT;
567 }
568
569 /* Takes ownership of 'skb' and transmits it to 'out_port' on 'dp'.
570  */
571 int dp_output_port(struct datapath *dp, struct sk_buff *skb, int out_port)
572 {
573         struct net_bridge_port *p;
574         int len = skb->len;
575
576         BUG_ON(!skb);
577         if (out_port == OFPP_FLOOD)
578                 return flood(dp, skb);
579         else if (out_port == OFPP_CONTROLLER)
580                 return dp_output_control(dp, skb, fwd_save_skb(skb), 0,
581                                                   OFPR_ACTION);
582         else if (out_port == OFPP_TABLE) {
583                 struct sw_flow_key key;
584                 struct sw_flow *flow;
585
586                 flow_extract(skb, skb->dev->br_port->port_no, &key);
587                 flow = chain_lookup(dp->chain, &key);
588                 if (likely(flow != NULL)) {
589                         flow_used(flow, skb);
590                         execute_actions(dp, skb, &key, flow->actions, flow->n_actions);
591                         return 0;
592                 }
593                 return -ESRCH;
594         } else if (out_port >= OFPP_MAX)
595                 goto bad_port;
596
597         p = dp->ports[out_port];
598         if (p == NULL)
599                 goto bad_port;
600
601         skb->dev = p->dev;
602         if (packet_length(skb) > skb->dev->mtu) {
603                 printk("dropped over-mtu packet: %d > %d\n",
604                                         packet_length(skb), skb->dev->mtu);
605                 kfree_skb(skb);
606                 return -E2BIG;
607         }
608
609         dev_queue_xmit(skb);
610
611         return len;
612
613 bad_port:
614         kfree_skb(skb);
615         if (net_ratelimit())
616                 printk("can't forward to bad port %d\n", out_port);
617         return -ENOENT;
618 }
619
620 /* Takes ownership of 'skb' and transmits it to 'dp''s control path.  If
621  * 'buffer_id' != -1, then only the first 64 bytes of 'skb' are sent;
622  * otherwise, all of 'skb' is sent.  'reason' indicates why 'skb' is being
623  * sent. 'max_len' sets the maximum number of bytes that the caller
624  * wants to be sent; a value of 0 indicates the entire packet should be
625  * sent. */
626 int
627 dp_output_control(struct datapath *dp, struct sk_buff *skb,
628                            uint32_t buffer_id, size_t max_len, int reason)
629 {
630         /* FIXME?  Can we avoid creating a new skbuff in the case where we
631          * forward the whole packet? */
632         struct sk_buff *f_skb;
633         struct ofp_packet_in *opi;
634         size_t fwd_len, opi_len;
635         int err;
636
637         fwd_len = skb->len;
638         if ((buffer_id != (uint32_t) -1) && max_len)
639                 fwd_len = min(fwd_len, max_len);
640
641         opi_len = offsetof(struct ofp_packet_in, data) + fwd_len;
642         opi = alloc_openflow_skb(dp, opi_len, OFPT_PACKET_IN, NULL, &f_skb);
643         if (!opi) {
644                 err = -ENOMEM;
645                 goto out;
646         }
647         opi->buffer_id      = htonl(buffer_id);
648         opi->total_len      = htons(skb->len);
649         opi->in_port        = htons(skb->dev->br_port->port_no);
650         opi->reason         = reason;
651         opi->pad            = 0;
652         memcpy(opi->data, skb_mac_header(skb), fwd_len);
653         err = send_openflow_skb(f_skb, NULL);
654
655 out:
656         kfree_skb(skb);
657         return err;
658 }
659
660 static void fill_port_desc(struct net_bridge_port *p, struct ofp_phy_port *desc)
661 {
662         desc->port_no = htons(p->port_no);
663         strncpy(desc->name, p->dev->name, OFP_MAX_PORT_NAME_LEN);
664         desc->name[OFP_MAX_PORT_NAME_LEN-1] = '\0';
665         memcpy(desc->hw_addr, p->dev->dev_addr, ETH_ALEN);
666         desc->flags = htonl(p->flags);
667         desc->features = 0;
668         desc->speed = 0;
669
670 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,24)
671         if (p->dev->ethtool_ops && p->dev->ethtool_ops->get_settings) {
672                 struct ethtool_cmd ecmd = { .cmd = ETHTOOL_GSET };
673
674                 if (!p->dev->ethtool_ops->get_settings(p->dev, &ecmd)) {
675                         if (ecmd.supported & SUPPORTED_10baseT_Half) 
676                                 desc->features |= OFPPF_10MB_HD;
677                         if (ecmd.supported & SUPPORTED_10baseT_Full)
678                                 desc->features |= OFPPF_10MB_FD;
679                         if (ecmd.supported & SUPPORTED_100baseT_Half) 
680                                 desc->features |= OFPPF_100MB_HD;
681                         if (ecmd.supported & SUPPORTED_100baseT_Full)
682                                 desc->features |= OFPPF_100MB_FD;
683                         if (ecmd.supported & SUPPORTED_1000baseT_Half)
684                                 desc->features |= OFPPF_1GB_HD;
685                         if (ecmd.supported & SUPPORTED_1000baseT_Full)
686                                 desc->features |= OFPPF_1GB_FD;
687                         /* 10Gbps half-duplex doesn't exist... */
688                         if (ecmd.supported & SUPPORTED_10000baseT_Full)
689                                 desc->features |= OFPPF_10GB_FD;
690
691                         desc->features = htonl(desc->features);
692                         desc->speed = htonl(ecmd.speed);
693                 }
694         }
695 #endif
696 }
697
698 static int 
699 fill_features_reply(struct datapath *dp, struct ofp_switch_features *ofr)
700 {
701         struct net_bridge_port *p;
702         int port_count = 0;
703
704         ofr->datapath_id    = cpu_to_be64(dp->id); 
705
706         ofr->n_exact        = htonl(2 * TABLE_HASH_MAX_FLOWS);
707         ofr->n_compression  = 0;                                           /* Not supported */
708         ofr->n_general      = htonl(TABLE_LINEAR_MAX_FLOWS);
709         ofr->buffer_mb      = htonl(UINT32_MAX);
710         ofr->n_buffers      = htonl(N_PKT_BUFFERS);
711         ofr->capabilities   = htonl(OFP_SUPPORTED_CAPABILITIES);
712         ofr->actions        = htonl(OFP_SUPPORTED_ACTIONS);
713
714         list_for_each_entry_rcu (p, &dp->port_list, node) {
715                 fill_port_desc(p, &ofr->ports[port_count]);
716                 port_count++;
717         }
718
719         return port_count;
720 }
721
722 int
723 dp_send_features_reply(struct datapath *dp, const struct sender *sender)
724 {
725         struct sk_buff *skb;
726         struct ofp_switch_features *ofr;
727         size_t ofr_len, port_max_len;
728         int port_count;
729
730         /* Overallocate. */
731         port_max_len = sizeof(struct ofp_phy_port) * OFPP_MAX;
732         ofr = alloc_openflow_skb(dp, sizeof(*ofr) + port_max_len,
733                                  OFPT_FEATURES_REPLY, sender, &skb);
734         if (!ofr)
735                 return -ENOMEM;
736
737         /* Fill. */
738         port_count = fill_features_reply(dp, ofr);
739
740         /* Shrink to fit. */
741         ofr_len = sizeof(*ofr) + (sizeof(struct ofp_phy_port) * port_count);
742         resize_openflow_skb(skb, &ofr->header, ofr_len);
743         return send_openflow_skb(skb, sender);
744 }
745
746 int
747 dp_send_config_reply(struct datapath *dp, const struct sender *sender)
748 {
749         struct sk_buff *skb;
750         struct ofp_switch_config *osc;
751
752         osc = alloc_openflow_skb(dp, sizeof *osc, OFPT_GET_CONFIG_REPLY, sender,
753                                  &skb);
754         if (!osc)
755                 return -ENOMEM;
756
757         osc->flags = htons(dp->flags);
758         osc->miss_send_len = htons(dp->miss_send_len);
759
760         return send_openflow_skb(skb, sender);
761 }
762
763 int
764 dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp)
765 {
766         struct net_bridge_port *p;
767
768         p = dp->ports[htons(opp->port_no)];
769
770         /* Make sure the port id hasn't changed since this was sent */
771         if (!p || memcmp(opp->hw_addr, p->dev->dev_addr, ETH_ALEN) != 0) 
772                 return -1;
773         
774         p->flags = htonl(opp->flags);
775
776         return 0;
777 }
778
779
780 static int
781 send_port_status(struct net_bridge_port *p, uint8_t status)
782 {
783         struct sk_buff *skb;
784         struct ofp_port_status *ops;
785
786         ops = alloc_openflow_skb(p->dp, sizeof *ops, OFPT_PORT_STATUS, NULL,
787                                  &skb);
788         if (!ops)
789                 return -ENOMEM;
790         ops->reason = status;
791         memset(ops->pad, 0, sizeof ops->pad);
792         fill_port_desc(p, &ops->desc);
793
794         return send_openflow_skb(skb, NULL);
795 }
796
797 int 
798 dp_send_flow_expired(struct datapath *dp, struct sw_flow *flow)
799 {
800         struct sk_buff *skb;
801         struct ofp_flow_expired *ofe;
802         unsigned long duration_j;
803
804         ofe = alloc_openflow_skb(dp, sizeof *ofe, OFPT_FLOW_EXPIRED, 0, &skb);
805         if (!ofe)
806                 return -ENOMEM;
807
808         flow_fill_match(&ofe->match, &flow->key);
809
810         memset(ofe->pad, 0, sizeof ofe->pad);
811         ofe->priority = htons(flow->priority);
812
813         duration_j = (flow->timeout - HZ * flow->max_idle) - flow->init_time;
814         ofe->duration     = htonl(duration_j / HZ);
815         ofe->packet_count = cpu_to_be64(flow->packet_count);
816         ofe->byte_count   = cpu_to_be64(flow->byte_count);
817
818         return send_openflow_skb(skb, NULL);
819 }
820
821 int
822 dp_send_error_msg(struct datapath *dp, const struct sender *sender, 
823                 uint16_t type, uint16_t code, const uint8_t *data, size_t len)
824 {
825         struct sk_buff *skb;
826         struct ofp_error_msg *oem;
827
828
829         oem = alloc_openflow_skb(dp, sizeof(*oem)+len, OFPT_ERROR_MSG, 
830                         sender, &skb);
831         if (!oem)
832                 return -ENOMEM;
833
834         oem->type = htons(type);
835         oem->code = htons(code);
836         memcpy(oem->data, data, len);
837
838         return send_openflow_skb(skb, sender);
839 }
840
841 static void
842 fill_flow_stats(struct ofp_flow_stats *ofs, struct sw_flow *flow,
843                 int table_idx)
844 {
845         ofs->match.wildcards = htons(flow->key.wildcards);
846         ofs->match.in_port   = flow->key.in_port;
847         memcpy(ofs->match.dl_src, flow->key.dl_src, ETH_ALEN);
848         memcpy(ofs->match.dl_dst, flow->key.dl_dst, ETH_ALEN);
849         ofs->match.dl_vlan   = flow->key.dl_vlan;
850         ofs->match.dl_type   = flow->key.dl_type;
851         ofs->match.nw_src    = flow->key.nw_src;
852         ofs->match.nw_dst    = flow->key.nw_dst;
853         ofs->match.nw_proto  = flow->key.nw_proto;
854         memset(ofs->match.pad, 0, sizeof ofs->match.pad);
855         ofs->match.tp_src    = flow->key.tp_src;
856         ofs->match.tp_dst    = flow->key.tp_dst;
857         ofs->duration        = htonl((jiffies - flow->init_time) / HZ);
858         ofs->packet_count    = cpu_to_be64(flow->packet_count);
859         ofs->byte_count      = cpu_to_be64(flow->byte_count);
860         ofs->priority        = htons(flow->priority);
861         ofs->max_idle        = htons(flow->max_idle);
862         ofs->table_id        = table_idx;
863         memset(ofs->pad, 0, sizeof ofs->pad);
864 }
865
866 /* Generic Netlink interface.
867  *
868  * See netlink(7) for an introduction to netlink.  See
869  * http://linux-net.osdl.org/index.php/Netlink for more information and
870  * pointers on how to work with netlink and Generic Netlink in the kernel and
871  * in userspace. */
872
873 static struct genl_family dp_genl_family = {
874         .id = GENL_ID_GENERATE,
875         .hdrsize = 0,
876         .name = DP_GENL_FAMILY_NAME,
877         .version = 1,
878         .maxattr = DP_GENL_A_MAX,
879 };
880
881 /* Attribute policy: what each attribute may contain.  */
882 static struct nla_policy dp_genl_policy[DP_GENL_A_MAX + 1] = {
883         [DP_GENL_A_DP_IDX] = { .type = NLA_U32 },
884         [DP_GENL_A_MC_GROUP] = { .type = NLA_U32 },
885         [DP_GENL_A_PORTNAME] = { .type = NLA_STRING }
886 };
887
888 static int dp_genl_add(struct sk_buff *skb, struct genl_info *info)
889 {
890         if (!info->attrs[DP_GENL_A_DP_IDX])
891                 return -EINVAL;
892
893         return new_dp(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
894 }
895
896 static struct genl_ops dp_genl_ops_add_dp = {
897         .cmd = DP_GENL_C_ADD_DP,
898         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
899         .policy = dp_genl_policy,
900         .doit = dp_genl_add,
901         .dumpit = NULL,
902 };
903
904 struct datapath *dp_get(int dp_idx)
905 {
906         if (dp_idx < 0 || dp_idx > DP_MAX)
907                 return NULL;
908         return rcu_dereference(dps[dp_idx]);
909 }
910
911 static int dp_genl_del(struct sk_buff *skb, struct genl_info *info)
912 {
913         struct datapath *dp;
914         int err;
915
916         if (!info->attrs[DP_GENL_A_DP_IDX])
917                 return -EINVAL;
918
919         mutex_lock(&dp_mutex);
920         dp = dp_get(nla_get_u32((info->attrs[DP_GENL_A_DP_IDX])));
921         if (!dp)
922                 err = -ENOENT;
923         else {
924                 del_dp(dp);
925                 err = 0;
926         }
927         mutex_unlock(&dp_mutex);
928         return err;
929 }
930
931 static struct genl_ops dp_genl_ops_del_dp = {
932         .cmd = DP_GENL_C_DEL_DP,
933         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
934         .policy = dp_genl_policy,
935         .doit = dp_genl_del,
936         .dumpit = NULL,
937 };
938
939 /* Queries a datapath for related information.  Currently the only relevant
940  * information is the datapath's multicast group ID.  Really we want one
941  * multicast group per datapath, but because of locking issues[*] we can't
942  * easily get one.  Thus, every datapath will currently return the same
943  * global multicast group ID, but in the future it would be nice to fix that.
944  *
945  * [*] dp_genl_add, to add a new datapath, is called under the genl_lock
946  *       mutex, and genl_register_mc_group, called to acquire a new multicast
947  *       group ID, also acquires genl_lock, thus deadlock.
948  */
949 static int dp_genl_query(struct sk_buff *skb, struct genl_info *info)
950 {
951         struct datapath *dp;
952         struct sk_buff *ans_skb = NULL;
953         int dp_idx;
954         int err = -ENOMEM;
955
956         if (!info->attrs[DP_GENL_A_DP_IDX])
957                 return -EINVAL;
958
959         rcu_read_lock();
960         dp_idx = nla_get_u32((info->attrs[DP_GENL_A_DP_IDX]));
961         dp = dp_get(dp_idx);
962         if (!dp)
963                 err = -ENOENT;
964         else {
965                 void *data;
966                 ans_skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
967                 if (!ans_skb) {
968                         err = -ENOMEM;
969                         goto err;
970                 }
971                 data = genlmsg_put_reply(ans_skb, info, &dp_genl_family,
972                                          0, DP_GENL_C_QUERY_DP);
973                 if (data == NULL) {
974                         err = -ENOMEM;
975                         goto err;
976                 }
977                 NLA_PUT_U32(ans_skb, DP_GENL_A_DP_IDX, dp_idx);
978                 NLA_PUT_U32(ans_skb, DP_GENL_A_MC_GROUP, mc_group.id);
979
980                 genlmsg_end(ans_skb, data);
981                 err = genlmsg_reply(ans_skb, info);
982                 if (!err)
983                         ans_skb = NULL;
984         }
985 err:
986 nla_put_failure:
987         if (ans_skb)
988                 kfree_skb(ans_skb);
989         rcu_read_unlock();
990         return err;
991 }
992
993 static struct genl_ops dp_genl_ops_query_dp = {
994         .cmd = DP_GENL_C_QUERY_DP,
995         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
996         .policy = dp_genl_policy,
997         .doit = dp_genl_query,
998         .dumpit = NULL,
999 };
1000
1001 static int dp_genl_add_del_port(struct sk_buff *skb, struct genl_info *info)
1002 {
1003         struct datapath *dp;
1004         struct net_device *port;
1005         int err;
1006
1007         if (!info->attrs[DP_GENL_A_DP_IDX] || !info->attrs[DP_GENL_A_PORTNAME])
1008                 return -EINVAL;
1009
1010         /* Get datapath. */
1011         mutex_lock(&dp_mutex);
1012         dp = dp_get(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
1013         if (!dp) {
1014                 err = -ENOENT;
1015                 goto out;
1016         }
1017
1018         /* Get interface to add/remove. */
1019         port = dev_get_by_name(&init_net, 
1020                         nla_data(info->attrs[DP_GENL_A_PORTNAME]));
1021         if (!port) {
1022                 err = -ENOENT;
1023                 goto out;
1024         }
1025
1026         /* Execute operation. */
1027         if (info->genlhdr->cmd == DP_GENL_C_ADD_PORT)
1028                 err = add_switch_port(dp, port);
1029         else {
1030                 if (port->br_port == NULL || port->br_port->dp != dp) {
1031                         err = -ENOENT;
1032                         goto out_put;
1033                 }
1034                 err = del_switch_port(port->br_port);
1035         }
1036
1037 out_put:
1038         dev_put(port);
1039 out:
1040         mutex_unlock(&dp_mutex);
1041         return err;
1042 }
1043
1044 static struct genl_ops dp_genl_ops_add_port = {
1045         .cmd = DP_GENL_C_ADD_PORT,
1046         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1047         .policy = dp_genl_policy,
1048         .doit = dp_genl_add_del_port,
1049         .dumpit = NULL,
1050 };
1051
1052 static struct genl_ops dp_genl_ops_del_port = {
1053         .cmd = DP_GENL_C_DEL_PORT,
1054         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1055         .policy = dp_genl_policy,
1056         .doit = dp_genl_add_del_port,
1057         .dumpit = NULL,
1058 };
1059
1060 static int dp_genl_openflow(struct sk_buff *skb, struct genl_info *info)
1061 {
1062         struct nlattr *va = info->attrs[DP_GENL_A_OPENFLOW];
1063         struct datapath *dp;
1064         struct ofp_header *oh;
1065         struct sender sender;
1066         int err;
1067
1068         if (!info->attrs[DP_GENL_A_DP_IDX] || !va)
1069                 return -EINVAL;
1070
1071         rcu_read_lock();
1072         dp = dp_get(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
1073         if (!dp) {
1074                 err = -ENOENT;
1075                 goto out;
1076         }
1077
1078         if (nla_len(va) < sizeof(struct ofp_header)) {
1079                 err = -EINVAL;
1080                 goto out;
1081         }
1082         oh = nla_data(va);
1083
1084         sender.xid = oh->xid;
1085         sender.pid = info->snd_pid;
1086         sender.seq = info->snd_seq;
1087         err = fwd_control_input(dp->chain, &sender, nla_data(va), nla_len(va));
1088
1089 out:
1090         rcu_read_unlock();
1091         return err;
1092 }
1093
1094 static struct nla_policy dp_genl_openflow_policy[DP_GENL_A_MAX + 1] = {
1095         [DP_GENL_A_DP_IDX] = { .type = NLA_U32 },
1096 };
1097
1098 struct flow_stats_state {
1099         int table_idx;
1100         struct sw_table_position position;
1101         const struct ofp_flow_stats_request *rq;
1102
1103         struct ofp_flow_stats *flows;
1104         int n_flows, max_flows;
1105 };
1106
1107 static int flow_stats_init(struct datapath *dp, const void *body, int body_len,
1108                            void **state)
1109 {
1110         const struct ofp_flow_stats_request *fsr = body;
1111         struct flow_stats_state *s = kmalloc(sizeof *s, GFP_ATOMIC);
1112         if (!s)
1113                 return -ENOMEM;
1114         s->table_idx = fsr->table_id == 0xff ? 0 : fsr->table_id;
1115         memset(&s->position, 0, sizeof s->position);
1116         s->rq = fsr;
1117         *state = s;
1118         return 0;
1119 }
1120
1121 static int flow_stats_dump_callback(struct sw_flow *flow, void *private)
1122 {
1123         struct flow_stats_state *s = private;
1124
1125         fill_flow_stats(&s->flows[s->n_flows], flow, s->table_idx);
1126         return ++s->n_flows >= s->max_flows;
1127 }
1128
1129 static int flow_stats_dump(struct datapath *dp, void *state,
1130                            void *body, int *body_len)
1131 {
1132         struct flow_stats_state *s = state;
1133         struct ofp_flow_stats *ofs;
1134         struct sw_flow_key match_key;
1135
1136         s->max_flows = *body_len / sizeof *ofs;
1137         if (!s->max_flows)
1138                 return -ENOMEM;
1139         s->flows = body;
1140
1141         flow_extract_match(&match_key, &s->rq->match);
1142         s->n_flows = 0;
1143         while (s->table_idx < dp->chain->n_tables
1144                && (s->rq->table_id == 0xff || s->rq->table_id == s->table_idx))
1145         {
1146                 struct sw_table *table = dp->chain->tables[s->table_idx];
1147
1148                 if (table->iterate(table, &match_key, &s->position,
1149                                    flow_stats_dump_callback, s))
1150                         break;
1151
1152                 s->table_idx++;
1153                 memset(&s->position, 0, sizeof s->position);
1154         }
1155         *body_len = sizeof *ofs * s->n_flows;
1156         return s->n_flows >= s->max_flows;
1157 }
1158
1159 static void flow_stats_done(void *state)
1160 {
1161         kfree(state);
1162 }
1163
1164 static int table_stats_dump(struct datapath *dp, void *state,
1165                             void *body, int *body_len)
1166 {
1167         struct ofp_table_stats *ots;
1168         int nbytes = dp->chain->n_tables * sizeof *ots;
1169         int i;
1170         if (nbytes > *body_len)
1171                 return -ENOBUFS;
1172         *body_len = nbytes;
1173         for (i = 0, ots = body; i < dp->chain->n_tables; i++, ots++) {
1174                 struct sw_table_stats stats;
1175                 dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
1176                 strncpy(ots->name, stats.name, sizeof ots->name);
1177                 ots->table_id = i;
1178                 memset(ots->pad, 0, sizeof ots->pad);
1179                 ots->max_entries = htonl(stats.max_flows);
1180                 ots->active_count = htonl(stats.n_flows);
1181                 ots->matched_count = cpu_to_be64(0); /* FIXME */
1182         }
1183         return 0;
1184 }
1185
1186 struct port_stats_state {
1187         int port;
1188 };
1189
1190 static int port_stats_init(struct datapath *dp, const void *body, int body_len,
1191                            void **state)
1192 {
1193         struct port_stats_state *s = kmalloc(sizeof *s, GFP_ATOMIC);
1194         if (!s)
1195                 return -ENOMEM;
1196         s->port = 0;
1197         *state = s;
1198         return 0;
1199 }
1200
1201 static int port_stats_dump(struct datapath *dp, void *state,
1202                            void *body, int *body_len)
1203 {
1204         struct port_stats_state *s = state;
1205         struct ofp_port_stats *ops;
1206         int n_ports, max_ports;
1207         int i;
1208
1209         max_ports = *body_len / sizeof *ops;
1210         if (!max_ports)
1211                 return -ENOMEM;
1212         ops = body;
1213
1214         n_ports = 0;
1215         for (i = s->port; i < OFPP_MAX && n_ports < max_ports; i++) {
1216                 struct net_bridge_port *p = dp->ports[i];
1217                 struct net_device_stats *stats;
1218                 if (!p)
1219                         continue;
1220                 stats = p->dev->get_stats(p->dev);
1221                 ops->port_no = htons(p->port_no);
1222                 memset(ops->pad, 0, sizeof ops->pad);
1223                 ops->rx_count = cpu_to_be64(stats->rx_packets);
1224                 ops->tx_count = cpu_to_be64(stats->tx_packets);
1225                 ops->drop_count = cpu_to_be64(stats->rx_dropped
1226                                               + stats->tx_dropped);
1227                 n_ports++;
1228                 ops++;
1229         }
1230         s->port = i;
1231         *body_len = n_ports * sizeof *ops;
1232         return n_ports >= max_ports;
1233 }
1234
1235 static void port_stats_done(void *state)
1236 {
1237         kfree(state);
1238 }
1239
1240 struct stats_type {
1241         /* Minimum and maximum acceptable number of bytes in body member of
1242          * struct ofp_stats_request. */
1243         size_t min_body, max_body;
1244
1245         /* Prepares to dump some kind of statistics on 'dp'.  'body' and
1246          * 'body_len' are the 'body' member of the struct ofp_stats_request.
1247          * Returns zero if successful, otherwise a negative error code.
1248          * May initialize '*state' to state information.  May be null if no
1249          * initialization is required.*/
1250         int (*init)(struct datapath *dp, const void *body, int body_len,
1251                     void **state);
1252
1253         /* Dumps statistics for 'dp' into the '*body_len' bytes at 'body', and
1254          * modifies '*body_len' to reflect the number of bytes actually used.
1255          * ('body' will be transmitted as the 'body' member of struct
1256          * ofp_stats_reply.) */
1257         int (*dump)(struct datapath *dp, void *state,
1258                     void *body, int *body_len);
1259
1260         /* Cleans any state created by the init or dump functions.  May be null
1261          * if no cleanup is required. */
1262         void (*done)(void *state);
1263 };
1264
1265 static const struct stats_type stats[] = {
1266         [OFPST_FLOW] = {
1267                 sizeof(struct ofp_flow_stats_request),
1268                 sizeof(struct ofp_flow_stats_request),
1269                 flow_stats_init,
1270                 flow_stats_dump,
1271                 flow_stats_done
1272         },
1273         [OFPST_TABLE] = {
1274                 0,
1275                 0,
1276                 NULL,
1277                 table_stats_dump,
1278                 NULL
1279         },
1280         [OFPST_PORT] = {
1281                 0,
1282                 0,
1283                 port_stats_init,
1284                 port_stats_dump,
1285                 port_stats_done
1286         },
1287 };
1288
1289 static int
1290 dp_genl_openflow_dumpit(struct sk_buff *skb, struct netlink_callback *cb)
1291 {
1292         struct datapath *dp;
1293         struct sender sender;
1294         const struct stats_type *s;
1295         struct ofp_stats_reply *osr;
1296         int dp_idx;
1297         int max_openflow_len, body_len;
1298         void *body;
1299         int err;
1300
1301         rcu_read_lock();
1302         if (!cb->args[0]) {
1303                 struct nlattr *attrs[DP_GENL_A_MAX + 1];
1304                 struct ofp_stats_request *rq;
1305                 struct nlattr *va;
1306                 size_t len, body_len;
1307                 int type;
1308
1309                 err = nlmsg_parse(cb->nlh, GENL_HDRLEN, attrs, DP_GENL_A_MAX,
1310                                   dp_genl_openflow_policy);
1311                 if (err < 0)
1312                         return err;
1313
1314                 err = -EINVAL;
1315
1316                 if (!attrs[DP_GENL_A_DP_IDX])
1317                         goto out;
1318                 dp_idx = nla_get_u16(attrs[DP_GENL_A_DP_IDX]);
1319                 dp = dp_get(dp_idx);
1320                 if (!dp) {
1321                         err = -ENOENT;
1322                         goto out;
1323                 }
1324
1325                 va = attrs[DP_GENL_A_OPENFLOW];
1326                 len = nla_len(va);
1327                 if (!va || len < sizeof *rq)
1328                         goto out;
1329
1330                 rq = nla_data(va);
1331                 type = ntohs(rq->type);
1332                 if (rq->header.version != OFP_VERSION
1333                     || rq->header.type != OFPT_STATS_REQUEST
1334                     || ntohs(rq->header.length) != len
1335                     || type >= ARRAY_SIZE(stats)
1336                     || !stats[type].dump)
1337                         goto out;
1338
1339                 s = &stats[type];
1340                 body_len = len - offsetof(struct ofp_stats_request, body);
1341                 if (body_len < s->min_body || body_len > s->max_body)
1342                         goto out;
1343
1344                 cb->args[0] = 1;
1345                 cb->args[1] = dp_idx;
1346                 cb->args[2] = type;
1347                 cb->args[3] = rq->header.xid;
1348                 if (s->init) {
1349                         void *state;
1350                         err = s->init(dp, rq->body, body_len, &state);
1351                         if (err)
1352                                 goto out;
1353                         cb->args[4] = (long) state;
1354                 }
1355         } else if (cb->args[0] == 1) {
1356                 dp_idx = cb->args[1];
1357                 s = &stats[cb->args[2]];
1358
1359                 dp = dp_get(dp_idx);
1360                 if (!dp) {
1361                         err = -ENOENT;
1362                         goto out;
1363                 }
1364         } else {
1365                 err = 0;
1366                 goto out;
1367         }
1368
1369         sender.xid = cb->args[3];
1370         sender.pid = NETLINK_CB(cb->skb).pid;
1371         sender.seq = cb->nlh->nlmsg_seq;
1372
1373         osr = put_openflow_headers(dp, skb, OFPT_STATS_REPLY, &sender,
1374                                    &max_openflow_len);
1375         if (IS_ERR(osr)) {
1376                 err = PTR_ERR(osr);
1377                 goto out;
1378         }
1379         osr->type = htons(s - stats);
1380         osr->flags = 0;
1381         resize_openflow_skb(skb, &osr->header, max_openflow_len);
1382         body = osr->body;
1383         body_len = max_openflow_len - offsetof(struct ofp_stats_reply, body);
1384
1385         err = s->dump(dp, (void *) cb->args[4], body, &body_len);
1386         if (err >= 0) {
1387                 if (!err)
1388                         cb->args[0] = 2;
1389                 else
1390                         osr->flags = ntohs(OFPSF_REPLY_MORE);
1391                 resize_openflow_skb(skb, &osr->header,
1392                                     (offsetof(struct ofp_stats_reply, body)
1393                                      + body_len));
1394                 err = skb->len;
1395         }
1396
1397 out:
1398         rcu_read_unlock();
1399         return err;
1400 }
1401
1402 static int
1403 dp_genl_openflow_done(struct netlink_callback *cb)
1404 {
1405         if (cb->args[0]) {
1406                 const struct stats_type *s = &stats[cb->args[2]];
1407                 if (s->done)
1408                         s->done((void *) cb->args[4]);
1409         }
1410         return 0;
1411 }
1412
1413 static struct genl_ops dp_genl_ops_openflow = {
1414         .cmd = DP_GENL_C_OPENFLOW,
1415         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1416         .policy = dp_genl_openflow_policy,
1417         .doit = dp_genl_openflow,
1418         .dumpit = dp_genl_openflow_dumpit,
1419         .done = dp_genl_openflow_done,
1420 };
1421
1422 static struct nla_policy dp_genl_benchmark_policy[DP_GENL_A_MAX + 1] = {
1423         [DP_GENL_A_DP_IDX] = { .type = NLA_U32 },
1424         [DP_GENL_A_NPACKETS] = { .type = NLA_U32 },
1425         [DP_GENL_A_PSIZE] = { .type = NLA_U32 },
1426 };
1427
1428 static struct genl_ops dp_genl_ops_benchmark_nl = {
1429         .cmd = DP_GENL_C_BENCHMARK_NL,
1430         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1431         .policy = dp_genl_benchmark_policy,
1432         .doit = dp_genl_benchmark_nl,
1433         .dumpit = NULL,
1434 };
1435
1436 static struct genl_ops *dp_genl_all_ops[] = {
1437         /* Keep this operation first.  Generic Netlink dispatching
1438          * looks up operations with linear search, so we want it at the
1439          * front. */
1440         &dp_genl_ops_openflow,
1441
1442         &dp_genl_ops_add_dp,
1443         &dp_genl_ops_del_dp,
1444         &dp_genl_ops_query_dp,
1445         &dp_genl_ops_add_port,
1446         &dp_genl_ops_del_port,
1447         &dp_genl_ops_benchmark_nl,
1448 };
1449
1450 static int dp_init_netlink(void)
1451 {
1452         int err;
1453         int i;
1454
1455         err = genl_register_family(&dp_genl_family);
1456         if (err)
1457                 return err;
1458
1459         for (i = 0; i < ARRAY_SIZE(dp_genl_all_ops); i++) {
1460                 err = genl_register_ops(&dp_genl_family, dp_genl_all_ops[i]);
1461                 if (err)
1462                         goto err_unregister;
1463         }
1464
1465         strcpy(mc_group.name, "openflow");
1466         err = genl_register_mc_group(&dp_genl_family, &mc_group);
1467         if (err < 0)
1468                 goto err_unregister;
1469
1470         return 0;
1471
1472 err_unregister:
1473         genl_unregister_family(&dp_genl_family);
1474                 return err;
1475 }
1476
1477 static void dp_uninit_netlink(void)
1478 {
1479         genl_unregister_family(&dp_genl_family);
1480 }
1481
1482 #define DRV_NAME                "openflow"
1483 #define DRV_VERSION      VERSION
1484 #define DRV_DESCRIPTION "OpenFlow switching datapath implementation"
1485 #define DRV_COPYRIGHT   "Copyright (c) 2007, 2008 The Board of Trustees of The Leland Stanford Junior University"
1486
1487
1488 static int __init dp_init(void)
1489 {
1490         int err;
1491
1492         printk(KERN_INFO DRV_NAME ": " DRV_DESCRIPTION "\n");
1493         printk(KERN_INFO DRV_NAME ": " VERSION" built on "__DATE__" "__TIME__"\n");
1494         printk(KERN_INFO DRV_NAME ": " DRV_COPYRIGHT "\n");
1495
1496         err = flow_init();
1497         if (err)
1498                 goto error;
1499
1500         err = dp_init_netlink();
1501         if (err)
1502                 goto error_flow_exit;
1503
1504         /* Hook into callback used by the bridge to intercept packets.
1505          * Parasites we are. */
1506         if (br_handle_frame_hook)
1507                 printk("openflow: hijacking bridge hook\n");
1508         br_handle_frame_hook = dp_frame_hook;
1509
1510         return 0;
1511
1512 error_flow_exit:
1513         flow_exit();
1514 error:
1515         printk(KERN_EMERG "openflow: failed to install!");
1516         return err;
1517 }
1518
1519 static void dp_cleanup(void)
1520 {
1521         fwd_exit();
1522         dp_uninit_netlink();
1523         flow_exit();
1524         br_handle_frame_hook = NULL;
1525 }
1526
1527 module_init(dp_init);
1528 module_exit(dp_cleanup);
1529
1530 MODULE_DESCRIPTION(DRV_DESCRIPTION);
1531 MODULE_AUTHOR(DRV_COPYRIGHT);
1532 MODULE_LICENSE("GPL");