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