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