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