Make duration in ofp_flow_stats a 32-bit quantity (instead of 16).
[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/delay.h>
17 #include <linux/etherdevice.h>
18 #include <linux/kernel.h>
19 #include <linux/kthread.h>
20 #include <linux/mutex.h>
21 #include <linux/rtnetlink.h>
22 #include <linux/rcupdate.h>
23 #include <linux/version.h>
24 #include <linux/ethtool.h>
25 #include <linux/random.h>
26 #include <asm/system.h>
27 #include <linux/netfilter_bridge.h>
28 #include <linux/inetdevice.h>
29 #include <linux/list.h>
30
31 #include "openflow-netlink.h"
32 #include "datapath.h"
33 #include "table.h"
34 #include "chain.h"
35 #include "forward.h"
36 #include "flow.h"
37 #include "datapath_t.h"
38
39 #include "compat.h"
40
41
42 /* Number of milliseconds between runs of the maintenance thread. */
43 #define MAINT_SLEEP_MSECS 1000
44
45 #define BRIDGE_PORT_NO_FLOOD    0x00000001 
46
47 #define UINT32_MAX                        4294967295U
48 #define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
49
50 struct net_bridge_port {
51         u16     port_no;
52         u32 flags;
53         struct datapath *dp;
54         struct net_device *dev;
55         struct list_head node; /* Element in datapath.ports. */
56 };
57
58 static struct genl_family dp_genl_family;
59 static struct genl_multicast_group mc_group;
60
61 int dp_dev_setup(struct net_device *dev);  
62
63 /* It's hard to imagine wanting more than one datapath, but... */
64 #define DP_MAX 32
65
66 /* datapaths.  Protected on the read side by rcu_read_lock, on the write side
67  * by dp_mutex.
68  *
69  * It is safe to access the datapath and net_bridge_port structures with just
70  * the dp_mutex, but to access the chain you need to take the rcu_read_lock
71  * also (because dp_mutex doesn't prevent flows from being destroyed).
72  */
73 static struct datapath *dps[DP_MAX];
74 static DEFINE_MUTEX(dp_mutex);
75
76 static int dp_maint_func(void *data);
77 static int send_port_status(struct net_bridge_port *p, uint8_t status);
78
79
80 /* nla_unreserve - reduce amount of space reserved by nla_reserve  
81  * @skb: socket buffer from which to recover room
82  * @nla: netlink attribute to adjust
83  * @len: amount by which to reduce attribute payload
84  *
85  * Reduces amount of space reserved by a call to nla_reserve.
86  *
87  * No other attributes may be added between calling nla_reserve and this
88  * function, since it will create a hole in the message.
89  */
90 void nla_unreserve(struct sk_buff *skb, struct nlattr *nla, int len)
91 {
92         skb->tail -= len;
93         skb->len  -= len;
94
95         nla->nla_len -= len;
96 }
97
98 static void *
99 alloc_openflow_skb(struct datapath *dp, size_t openflow_len, uint8_t type,
100                    const struct sender *sender, struct sk_buff **pskb) 
101 {
102         size_t genl_len;
103         struct sk_buff *skb;
104         struct nlattr *attr;
105         struct ofp_header *oh;
106
107         genl_len = nla_total_size(sizeof(uint32_t)); /* DP_GENL_A_DP_IDX */
108         genl_len += nla_total_size(openflow_len);    /* DP_GENL_A_OPENFLOW */
109         skb = *pskb = genlmsg_new(genl_len, GFP_ATOMIC);
110         if (!skb) {
111                 if (net_ratelimit())
112                         printk("alloc_openflow_skb: genlmsg_new failed\n");
113                 return NULL;
114         }
115
116         /* Assemble the Generic Netlink wrapper. */
117         if (!genlmsg_put(skb,
118                          sender ? sender->pid : 0,
119                          sender ? sender->seq : 0,
120                          &dp_genl_family, 0, DP_GENL_C_OPENFLOW))
121                 BUG();
122         if (nla_put_u32(skb, DP_GENL_A_DP_IDX, dp->dp_idx) < 0)
123                 BUG();
124         attr = nla_reserve(skb, DP_GENL_A_OPENFLOW, openflow_len);
125         BUG_ON(!attr);
126         nlmsg_end(skb, (struct nlmsghdr *) skb->data);
127
128         /* Fill in the header. */
129         oh = nla_data(attr);
130         oh->version = OFP_VERSION;
131         oh->type = type;
132         oh->length = htons(openflow_len);
133         oh->xid = sender ? sender->xid : 0;
134
135         return oh;
136 }
137
138 static void
139 resize_openflow_skb(struct sk_buff *skb,
140                     struct ofp_header *oh, size_t new_length)
141 {
142         struct nlattr *attr;
143
144         BUG_ON(new_length > ntohs(oh->length));
145         attr = ((void *) oh) - NLA_HDRLEN;
146         nla_unreserve(skb, attr, ntohs(oh->length) - new_length);
147         oh->length = htons(new_length);
148         nlmsg_end(skb, (struct nlmsghdr *) skb->data);
149 }
150
151 static int
152 send_openflow_skb(struct sk_buff *skb, const struct sender *sender) 
153 {
154         int err = (sender
155                    ? genlmsg_unicast(skb, sender->pid)
156                    : genlmsg_multicast(skb, 0, mc_group.id, GFP_ATOMIC));
157         if (err && net_ratelimit())
158                 printk(KERN_WARNING "send_openflow_skb: send failed: %d\n",
159                        err);
160         return err;
161 }
162
163 /* Generates a unique datapath id.  It incorporates the datapath index
164  * and a hardware address, if available.  If not, it generates a random
165  * one.
166  */
167 static 
168 uint64_t gen_datapath_id(uint16_t dp_idx)
169 {
170         uint64_t id;
171         int i;
172         struct net_device *dev;
173
174         /* The top 16 bits are used to identify the datapath.  The lower 48 bits
175          * use an interface address.  */
176         id = (uint64_t)dp_idx << 48;
177         if ((dev = dev_get_by_name(&init_net, "ctl0")) 
178                         || (dev = dev_get_by_name(&init_net, "eth0"))) {
179                 for (i=0; i<ETH_ALEN; i++) {
180                         id |= (uint64_t)dev->dev_addr[i] << (8*(ETH_ALEN-1 - i));
181                 }
182                 dev_put(dev);
183         } else {
184                 /* Randomly choose the lower 48 bits if we cannot find an
185                  * address and mark the most significant bit to indicate that
186                  * this was randomly generated. */
187                 uint8_t rand[ETH_ALEN];
188                 get_random_bytes(rand, ETH_ALEN);
189                 id |= (uint64_t)1 << 63;
190                 for (i=0; i<ETH_ALEN; i++) {
191                         id |= (uint64_t)rand[i] << (8*(ETH_ALEN-1 - i));
192                 }
193         }
194
195         return id;
196 }
197
198 /* Creates a new datapath numbered 'dp_idx'.  Returns 0 for success or a
199  * negative error code.
200  *
201  * Not called with any locks. */
202 static int new_dp(int dp_idx)
203 {
204         struct datapath *dp;
205         int err;
206
207         if (dp_idx < 0 || dp_idx >= DP_MAX)
208                 return -EINVAL;
209
210         if (!try_module_get(THIS_MODULE))
211                 return -ENODEV;
212
213         mutex_lock(&dp_mutex);
214         dp = rcu_dereference(dps[dp_idx]);
215         if (dp != NULL) {
216                 err = -EEXIST;
217                 goto err_unlock;
218         }
219
220         err = -ENOMEM;
221         dp = kzalloc(sizeof *dp, GFP_KERNEL);
222         if (dp == NULL)
223                 goto err_unlock;
224
225         dp->dp_idx = dp_idx;
226         dp->id = gen_datapath_id(dp_idx);
227         dp->chain = chain_create(dp);
228         if (dp->chain == NULL)
229                 goto err_free_dp;
230         INIT_LIST_HEAD(&dp->port_list);
231
232 #if 0
233         /* Setup our "of" device */
234         dp->dev.priv = dp;
235         rtnl_lock();
236         err = dp_dev_setup(&dp->dev);
237         rtnl_unlock();
238         if (err != 0) 
239                 printk("datapath: problem setting up 'of' device\n");
240 #endif
241
242         dp->config.flags = 0;
243         dp->config.miss_send_len = htons(OFP_DEFAULT_MISS_SEND_LEN);
244
245         dp->dp_task = kthread_run(dp_maint_func, dp, "dp%d", dp_idx);
246         if (IS_ERR(dp->dp_task))
247                 goto err_free_dp;
248
249         rcu_assign_pointer(dps[dp_idx], dp);
250         mutex_unlock(&dp_mutex);
251
252         return 0;
253
254 err_free_dp:
255         kfree(dp);
256 err_unlock:
257         mutex_unlock(&dp_mutex);
258         module_put(THIS_MODULE);
259                 return err;
260 }
261
262 /* Find and return a free port number under 'dp'.  Called under dp_mutex. */
263 static int find_portno(struct datapath *dp)
264 {
265         int i;
266         for (i = 0; i < OFPP_MAX; i++)
267                 if (dp->ports[i] == NULL)
268                         return i;
269         return -EXFULL;
270 }
271
272 static struct net_bridge_port *new_nbp(struct datapath *dp,
273                                                                            struct net_device *dev)
274 {
275         struct net_bridge_port *p;
276         int port_no;
277
278         port_no = find_portno(dp);
279         if (port_no < 0)
280                 return ERR_PTR(port_no);
281
282         p = kzalloc(sizeof(*p), GFP_KERNEL);
283         if (p == NULL)
284                 return ERR_PTR(-ENOMEM);
285
286         p->dp = dp;
287         dev_hold(dev);
288         p->dev = dev;
289         p->port_no = port_no;
290
291         return p;
292 }
293
294 /* Called with dp_mutex. */
295 int add_switch_port(struct datapath *dp, struct net_device *dev)
296 {
297         struct net_bridge_port *p;
298
299         if (dev->flags & IFF_LOOPBACK || dev->type != ARPHRD_ETHER)
300                 return -EINVAL;
301
302         if (dev->br_port != NULL)
303                 return -EBUSY;
304
305         p = new_nbp(dp, dev);
306         if (IS_ERR(p))
307                 return PTR_ERR(p);
308
309         dev_hold(dev);
310         rcu_assign_pointer(dev->br_port, p);
311         rtnl_lock();
312         dev_set_promiscuity(dev, 1);
313         rtnl_unlock();
314
315         rcu_assign_pointer(dp->ports[p->port_no], p);
316         list_add_rcu(&p->node, &dp->port_list);
317
318         /* Notify the ctlpath that this port has been added */
319         send_port_status(p, OFPPR_ADD);
320
321         return 0;
322 }
323
324 /* Delete 'p' from switch.
325  * Called with dp_mutex. */
326 static int del_switch_port(struct net_bridge_port *p)
327 {
328         /* First drop references to device. */
329         rtnl_lock();
330         dev_set_promiscuity(p->dev, -1);
331         rtnl_unlock();
332         list_del_rcu(&p->node);
333         rcu_assign_pointer(p->dp->ports[p->port_no], NULL);
334         rcu_assign_pointer(p->dev->br_port, NULL);
335
336         /* Then wait until no one is still using it, and destroy it. */
337         synchronize_rcu();
338
339         /* Notify the ctlpath that this port no longer exists */
340         send_port_status(p, OFPPR_DELETE);
341
342         dev_put(p->dev);
343         kfree(p);
344
345         return 0;
346 }
347
348 /* Called with dp_mutex. */
349 static void del_dp(struct datapath *dp)
350 {
351         struct net_bridge_port *p, *n;
352
353 #if 0
354         /* Unregister the "of" device of this dp */
355         rtnl_lock();
356         unregister_netdevice(&dp->dev);
357         rtnl_unlock();
358 #endif
359
360         kthread_stop(dp->dp_task);
361
362         /* Drop references to DP. */
363         list_for_each_entry_safe (p, n, &dp->port_list, node)
364                 del_switch_port(p);
365         rcu_assign_pointer(dps[dp->dp_idx], NULL);
366
367         /* Wait until no longer in use, then destroy it. */
368         synchronize_rcu();
369         chain_destroy(dp->chain);
370         kfree(dp);
371         module_put(THIS_MODULE);
372 }
373
374 static int dp_maint_func(void *data)
375 {
376         struct datapath *dp = (struct datapath *) data;
377
378         while (!kthread_should_stop()) {
379 #if 1
380                 chain_timeout(dp->chain);
381 #else
382                 int count = chain_timeout(dp->chain);
383                 chain_print_stats(dp->chain);
384                 if (count)
385                         printk("%d flows timed out\n", count);
386 #endif
387                 msleep_interruptible(MAINT_SLEEP_MSECS);
388         }
389                 
390         return 0;
391 }
392
393 /*
394  * Used as br_handle_frame_hook.  (Cannot run bridge at the same time, even on
395  * different set of devices!)  Returns 0 if *pskb should be processed further,
396  * 1 if *pskb is handled. */
397 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
398 /* Called with rcu_read_lock. */
399 static struct sk_buff *dp_frame_hook(struct net_bridge_port *p,
400                                          struct sk_buff *skb)
401 {
402         struct ethhdr *eh = eth_hdr(skb);
403         struct sk_buff *skb_local = NULL;
404
405
406         if (compare_ether_addr(eh->h_dest, skb->dev->dev_addr) == 0) 
407                 return skb;
408
409         if (is_broadcast_ether_addr(eh->h_dest)
410                                 || is_multicast_ether_addr(eh->h_dest)
411                                 || is_local_ether_addr(eh->h_dest)) 
412                 skb_local = skb_clone(skb, GFP_ATOMIC);
413
414         /* Push the Ethernet header back on. */
415         if (skb->protocol == htons(ETH_P_8021Q))
416                 skb_push(skb, VLAN_ETH_HLEN);
417         else
418                 skb_push(skb, ETH_HLEN);
419
420         fwd_port_input(p->dp->chain, skb, p->port_no);
421
422         return skb_local;
423 }
424 #elif LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
425 static int dp_frame_hook(struct net_bridge_port *p, struct sk_buff **pskb)
426 {
427         /* Push the Ethernet header back on. */
428         if ((*pskb)->protocol == htons(ETH_P_8021Q))
429                 skb_push(*pskb, VLAN_ETH_HLEN);
430         else
431                 skb_push(*pskb, ETH_HLEN);
432
433         fwd_port_input(p->dp->chain, *pskb, p->port_no);
434         return 1;
435 }
436 #else 
437 /* NB: This has only been tested on 2.4.35 */
438
439 /* Called without any locks (?) */
440 static void dp_frame_hook(struct sk_buff *skb)
441 {
442         struct net_bridge_port *p = skb->dev->br_port;
443
444         /* Push the Ethernet header back on. */
445         if (skb->protocol == htons(ETH_P_8021Q))
446                 skb_push(skb, VLAN_ETH_HLEN);
447         else
448                 skb_push(skb, ETH_HLEN);
449
450         if (p) {
451                 rcu_read_lock();
452                 fwd_port_input(p->dp->chain, skb, p->port_no);
453                 rcu_read_unlock();
454         } else
455                 kfree_skb(skb);
456 }
457 #endif
458
459 /* Forwarding output path.
460  * Based on net/bridge/br_forward.c. */
461
462 /* Don't forward packets to originating port or with flooding disabled */
463 static inline int should_deliver(const struct net_bridge_port *p,
464                         const struct sk_buff *skb)
465 {
466         if ((skb->dev == p->dev) || (p->flags & BRIDGE_PORT_NO_FLOOD)) {
467                 return 0;
468         } 
469
470         return 1;
471 }
472
473 static inline unsigned packet_length(const struct sk_buff *skb)
474 {
475         int length = skb->len - ETH_HLEN;
476         if (skb->protocol == htons(ETH_P_8021Q))
477                 length -= VLAN_HLEN;
478         return length;
479 }
480
481 static int
482 flood(struct datapath *dp, struct sk_buff *skb)
483 {
484         struct net_bridge_port *p;
485         int prev_port;
486
487         prev_port = -1;
488         list_for_each_entry_rcu (p, &dp->port_list, node) {
489                 if (!should_deliver(p, skb))
490                         continue;
491                 if (prev_port != -1) {
492                         struct sk_buff *clone = skb_clone(skb, GFP_ATOMIC);
493                         if (!clone) {
494                                 kfree_skb(skb);
495                                 return -ENOMEM;
496                         }
497                         dp_output_port(dp, clone, prev_port); 
498                 }
499                 prev_port = p->port_no;
500         }
501         if (prev_port != -1)
502                 dp_output_port(dp, skb, prev_port);
503         else
504                 kfree_skb(skb);
505
506         return 0;
507 }
508
509 /* Marks 'skb' as having originated from 'in_port' in 'dp'.
510    FIXME: how are devices reference counted? */
511 int dp_set_origin(struct datapath *dp, uint16_t in_port,
512                            struct sk_buff *skb)
513 {
514         if (in_port < OFPP_MAX && dp->ports[in_port]) {
515                 skb->dev = dp->ports[in_port]->dev;
516                 return 0;
517         }
518         return -ENOENT;
519 }
520
521 /* Takes ownership of 'skb' and transmits it to 'out_port' on 'dp'.
522  */
523 int dp_output_port(struct datapath *dp, struct sk_buff *skb, int out_port)
524 {
525         struct net_bridge_port *p;
526         int len = skb->len;
527
528         BUG_ON(!skb);
529         if (out_port == OFPP_FLOOD)
530                 return flood(dp, skb);
531         else if (out_port == OFPP_CONTROLLER)
532                 return dp_output_control(dp, skb, fwd_save_skb(skb), 0,
533                                                   OFPR_ACTION);
534         else if (out_port >= OFPP_MAX)
535                 goto bad_port;
536
537         p = dp->ports[out_port];
538         if (p == NULL)
539                 goto bad_port;
540
541         skb->dev = p->dev;
542         if (packet_length(skb) > skb->dev->mtu) {
543                 printk("dropped over-mtu packet: %d > %d\n",
544                                         packet_length(skb), skb->dev->mtu);
545                 kfree_skb(skb);
546                 return -E2BIG;
547         }
548
549         dev_queue_xmit(skb);
550
551         return len;
552
553 bad_port:
554         kfree_skb(skb);
555         if (net_ratelimit())
556                 printk("can't forward to bad port %d\n", out_port);
557         return -ENOENT;
558 }
559
560 /* Takes ownership of 'skb' and transmits it to 'dp''s control path.  If
561  * 'buffer_id' != -1, then only the first 64 bytes of 'skb' are sent;
562  * otherwise, all of 'skb' is sent.  'reason' indicates why 'skb' is being
563  * sent. 'max_len' sets the maximum number of bytes that the caller
564  * wants to be sent; a value of 0 indicates the entire packet should be
565  * sent. */
566 int
567 dp_output_control(struct datapath *dp, struct sk_buff *skb,
568                            uint32_t buffer_id, size_t max_len, int reason)
569 {
570         /* FIXME?  Can we avoid creating a new skbuff in the case where we
571          * forward the whole packet? */
572         struct sk_buff *f_skb;
573         struct ofp_packet_in *opi;
574         size_t fwd_len, opi_len;
575         int err;
576
577         fwd_len = skb->len;
578         if ((buffer_id != (uint32_t) -1) && max_len)
579                 fwd_len = min(fwd_len, max_len);
580
581         opi_len = offsetof(struct ofp_packet_in, data) + fwd_len;
582         opi = alloc_openflow_skb(dp, opi_len, OFPT_PACKET_IN, NULL, &f_skb);
583         opi->buffer_id      = htonl(buffer_id);
584         opi->total_len      = htons(skb->len);
585         opi->in_port        = htons(skb->dev->br_port->port_no);
586         opi->reason         = reason;
587         opi->pad            = 0;
588         memcpy(opi->data, skb_mac_header(skb), fwd_len);
589         err = send_openflow_skb(f_skb, NULL);
590
591         kfree_skb(skb);
592
593         return err;
594 }
595
596 static void fill_port_desc(struct net_bridge_port *p, struct ofp_phy_port *desc)
597 {
598         desc->port_no = htons(p->port_no);
599         strncpy(desc->name, p->dev->name, OFP_MAX_PORT_NAME_LEN);
600         desc->name[OFP_MAX_PORT_NAME_LEN-1] = '\0';
601         memcpy(desc->hw_addr, p->dev->dev_addr, ETH_ALEN);
602         desc->flags = htonl(p->flags);
603         desc->features = 0;
604         desc->speed = 0;
605
606 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,24)
607         if (p->dev->ethtool_ops && p->dev->ethtool_ops->get_settings) {
608                 struct ethtool_cmd ecmd = { .cmd = ETHTOOL_GSET };
609
610                 if (!p->dev->ethtool_ops->get_settings(p->dev, &ecmd)) {
611                         if (ecmd.supported & SUPPORTED_10baseT_Half) 
612                                 desc->features |= OFPPF_10MB_HD;
613                         if (ecmd.supported & SUPPORTED_10baseT_Full)
614                                 desc->features |= OFPPF_10MB_FD;
615                         if (ecmd.supported & SUPPORTED_100baseT_Half) 
616                                 desc->features |= OFPPF_100MB_HD;
617                         if (ecmd.supported & SUPPORTED_100baseT_Full)
618                                 desc->features |= OFPPF_100MB_FD;
619                         if (ecmd.supported & SUPPORTED_1000baseT_Half)
620                                 desc->features |= OFPPF_1GB_HD;
621                         if (ecmd.supported & SUPPORTED_1000baseT_Full)
622                                 desc->features |= OFPPF_1GB_FD;
623                         /* 10Gbps half-duplex doesn't exist... */
624                         if (ecmd.supported & SUPPORTED_10000baseT_Full)
625                                 desc->features |= OFPPF_10GB_FD;
626
627                         desc->features = htonl(desc->features);
628                         desc->speed = htonl(ecmd.speed);
629                 }
630         }
631 #endif
632 }
633
634 static int 
635 fill_features_reply(struct datapath *dp, struct ofp_switch_features *ofr)
636 {
637         struct net_bridge_port *p;
638         int port_count = 0;
639
640         ofr->datapath_id    = cpu_to_be64(dp->id); 
641
642         ofr->n_exact        = htonl(2 * TABLE_HASH_MAX_FLOWS);
643         ofr->n_mac_only     = htonl(TABLE_MAC_MAX_FLOWS);
644         ofr->n_compression  = 0;                                           /* Not supported */
645         ofr->n_general      = htonl(TABLE_LINEAR_MAX_FLOWS);
646         ofr->buffer_mb      = htonl(UINT32_MAX);
647         ofr->n_buffers      = htonl(N_PKT_BUFFERS);
648         ofr->capabilities   = htonl(OFP_SUPPORTED_CAPABILITIES);
649         ofr->actions        = htonl(OFP_SUPPORTED_ACTIONS);
650
651         list_for_each_entry_rcu (p, &dp->port_list, node) {
652                 fill_port_desc(p, &ofr->ports[port_count]);
653                 port_count++;
654         }
655
656         return port_count;
657 }
658
659 int
660 dp_send_features_reply(struct datapath *dp, const struct sender *sender)
661 {
662         struct sk_buff *skb;
663         struct ofp_switch_features *ofr;
664         size_t ofr_len, port_max_len;
665         int port_count;
666
667         /* Overallocate. */
668         port_max_len = sizeof(struct ofp_phy_port) * OFPP_MAX;
669         ofr = alloc_openflow_skb(dp, sizeof(*ofr) + port_max_len,
670                                  OFPT_FEATURES_REPLY, sender, &skb);
671         if (!ofr)
672                 return -ENOMEM;
673
674         /* Fill. */
675         port_count = fill_features_reply(dp, ofr);
676
677         /* Shrink to fit. */
678         ofr_len = sizeof(*ofr) + (sizeof(struct ofp_phy_port) * port_count);
679         resize_openflow_skb(skb, &ofr->header, ofr_len);
680         return send_openflow_skb(skb, sender);
681 }
682
683 int
684 dp_send_config_reply(struct datapath *dp, const struct sender *sender)
685 {
686         struct sk_buff *skb;
687         struct ofp_switch_config *osc;
688
689         osc = alloc_openflow_skb(dp, sizeof *osc, OFPT_PORT_STATUS, sender,
690                                  &skb);
691         if (!osc)
692                 return -ENOMEM;
693         memcpy(((char *)osc) + sizeof osc->header,
694                ((char *)&dp->config) + sizeof dp->config.header,
695                sizeof dp->config - sizeof dp->config.header);
696         return send_openflow_skb(skb, sender);
697 }
698
699 int
700 dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp)
701 {
702         struct net_bridge_port *p;
703
704         p = dp->ports[htons(opp->port_no)];
705
706         /* Make sure the port id hasn't changed since this was sent */
707         if (!p || memcmp(opp->hw_addr, p->dev->dev_addr, ETH_ALEN) != 0) 
708                 return -1;
709         
710         p->flags = htonl(opp->flags);
711
712         return 0;
713 }
714
715
716 static int
717 send_port_status(struct net_bridge_port *p, uint8_t status)
718 {
719         struct sk_buff *skb;
720         struct ofp_port_status *ops;
721
722         ops = alloc_openflow_skb(p->dp, sizeof *ops, OFPT_PORT_STATUS, NULL,
723                                  &skb);
724         if (!ops)
725                 return -ENOMEM;
726         ops->reason = status;
727         fill_port_desc(p, &ops->desc);
728
729         return send_openflow_skb(skb, NULL);
730 }
731
732 int 
733 dp_send_flow_expired(struct datapath *dp, struct sw_flow *flow)
734 {
735         struct sk_buff *skb;
736         struct ofp_flow_expired *ofe;
737         unsigned long duration_j;
738
739         ofe = alloc_openflow_skb(dp, sizeof *ofe, OFPT_FLOW_EXPIRED, 0, &skb);
740         if (!ofe)
741                 return -ENOMEM;
742
743         flow_fill_match(&ofe->match, &flow->key);
744         duration_j = (flow->timeout - HZ * flow->max_idle) - flow->init_time;
745         ofe->duration   = htonl(duration_j / HZ);
746         ofe->packet_count   = cpu_to_be64(flow->packet_count);
747         ofe->byte_count     = cpu_to_be64(flow->byte_count);
748         return send_openflow_skb(skb, NULL);
749 }
750
751 static void
752 fill_flow_stats(struct ofp_flow_stats *ofs, struct sw_flow *flow,
753                 int table_idx)
754 {
755         ofs->match.wildcards = htons(flow->key.wildcards);
756         ofs->match.in_port   = flow->key.in_port;
757         memcpy(ofs->match.dl_src, flow->key.dl_src, ETH_ALEN);
758         memcpy(ofs->match.dl_dst, flow->key.dl_dst, ETH_ALEN);
759         ofs->match.dl_vlan   = flow->key.dl_vlan;
760         ofs->match.dl_type   = flow->key.dl_type;
761         ofs->match.nw_src    = flow->key.nw_src;
762         ofs->match.nw_dst    = flow->key.nw_dst;
763         ofs->match.nw_proto  = flow->key.nw_proto;
764         memset(ofs->match.pad, 0, sizeof ofs->match.pad);
765         ofs->match.tp_src    = flow->key.tp_src;
766         ofs->match.tp_dst    = flow->key.tp_dst;
767         ofs->duration        = htonl((jiffies - flow->init_time) / HZ);
768         ofs->table_id        = htons(table_idx);
769         ofs->packet_count    = cpu_to_be64(flow->packet_count);
770         ofs->byte_count      = cpu_to_be64(flow->byte_count);
771 }
772
773 int
774 dp_send_flow_stats(struct datapath *dp, const struct sender *sender,
775                    const struct ofp_match *match)
776 {
777         struct sk_buff *skb;
778         struct ofp_flow_stat_reply *fsr;
779         size_t header_size, fudge, flow_size;
780         struct sw_flow_key match_key;
781         int table_idx, n_flows, max_flows;
782
783         header_size = offsetof(struct ofp_flow_stat_reply, flows);
784         fudge = 128;
785         flow_size = sizeof fsr->flows[0];
786         max_flows = (NLMSG_GOODSIZE - header_size - fudge) / flow_size;
787         fsr = alloc_openflow_skb(dp, header_size + max_flows * flow_size,
788                                  OFPT_FLOW_STAT_REPLY, sender, &skb);
789         if (!fsr)
790                 return -ENOMEM;
791
792         n_flows = 0;
793         flow_extract_match(&match_key, match);
794         for (table_idx = 0; table_idx < dp->chain->n_tables; table_idx++) {
795                 struct sw_table *table = dp->chain->tables[table_idx];
796                 struct swt_iterator iter;
797
798                 if (n_flows >= max_flows) {
799                         break;
800                 }
801
802                 if (!table->iterator(table, &iter)) {
803                         if (net_ratelimit())
804                                 printk("iterator failed for table %d\n",
805                                        table_idx);
806                         continue;
807                 }
808
809                 for (; iter.flow; table->iterator_next(&iter)) {
810                         if (flow_matches(&match_key, &iter.flow->key)) {
811                                 fill_flow_stats(&fsr->flows[n_flows],
812                                                 iter.flow, table_idx);
813                                 if (++n_flows >= max_flows) {
814                                         break;
815                                 }
816                         }
817                 }
818                 table->iterator_destroy(&iter);
819         }
820         resize_openflow_skb(skb, &fsr->header,
821                             header_size + flow_size * n_flows);
822         return send_openflow_skb(skb, sender);
823 }
824
825 static int 
826 fill_port_stat_reply(struct datapath *dp, struct ofp_port_stat_reply *psr)
827 {
828         struct net_bridge_port *p;
829         int port_count = 0;
830
831         list_for_each_entry_rcu (p, &dp->port_list, node) {
832                 struct ofp_port_stats *ps = &psr->ports[port_count++];
833                 struct net_device_stats *stats = p->dev->get_stats(p->dev);
834                 ps->port_no = htons(p->port_no);
835                 memset(ps->pad, 0, sizeof ps->pad);
836                 ps->rx_count = cpu_to_be64(stats->rx_packets);
837                 ps->tx_count = cpu_to_be64(stats->tx_packets);
838                 ps->drop_count = cpu_to_be64(stats->rx_dropped
839                                              + stats->tx_dropped);
840         }
841
842         return port_count;
843 }
844
845 int
846 dp_send_port_stats(struct datapath *dp, const struct sender *sender)
847 {
848         struct sk_buff *skb;
849         struct ofp_port_stat_reply *psr;
850         size_t psr_len, port_max_len;
851         int port_count;
852
853         /* Overallocate. */
854         port_max_len = sizeof(struct ofp_port_stats) * OFPP_MAX;
855         psr = alloc_openflow_skb(dp, sizeof *psr + port_max_len,
856                                  OFPT_PORT_STAT_REPLY, sender, &skb);
857         if (!psr)
858                 return -ENOMEM;
859
860         /* Fill. */
861         port_count = fill_port_stat_reply(dp, psr);
862
863         /* Shrink to fit. */
864         psr_len = sizeof *psr + sizeof(struct ofp_port_stats) * port_count;
865         resize_openflow_skb(skb, &psr->header, psr_len);
866         return send_openflow_skb(skb, sender);
867 }
868
869 int
870 dp_send_table_stats(struct datapath *dp, const struct sender *sender)
871 {
872         struct sk_buff *skb;
873         struct ofp_table_stat_reply *tsr;
874         int i, n_tables;
875
876         n_tables = dp->chain->n_tables;
877         tsr = alloc_openflow_skb(dp, (offsetof(struct ofp_table_stat_reply,
878                                                tables)
879                                       + sizeof tsr->tables[0] * n_tables),
880                                  OFPT_TABLE_STAT_REPLY, sender, &skb);
881         if (!tsr)
882                 return -ENOMEM;
883         for (i = 0; i < n_tables; i++) {
884                 struct ofp_table_stats *ots = &tsr->tables[i];
885                 struct sw_table_stats stats;
886                 dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
887                 strncpy(ots->name, stats.name, sizeof ots->name);
888                 ots->table_id = htons(i);
889                 ots->pad[0] = ots->pad[1] = 0;
890                 ots->max_entries = htonl(stats.max_flows);
891                 ots->active_count = htonl(stats.n_flows);
892                 ots->matched_count = cpu_to_be64(0); /* FIXME */
893         }
894         return send_openflow_skb(skb, sender);
895 }
896
897 /* Generic Netlink interface.
898  *
899  * See netlink(7) for an introduction to netlink.  See
900  * http://linux-net.osdl.org/index.php/Netlink for more information and
901  * pointers on how to work with netlink and Generic Netlink in the kernel and
902  * in userspace. */
903
904 static struct genl_family dp_genl_family = {
905         .id = GENL_ID_GENERATE,
906         .hdrsize = 0,
907         .name = DP_GENL_FAMILY_NAME,
908         .version = 1,
909         .maxattr = DP_GENL_A_MAX,
910 };
911
912 /* Attribute policy: what each attribute may contain.  */
913 static struct nla_policy dp_genl_policy[DP_GENL_A_MAX + 1] = {
914         [DP_GENL_A_DP_IDX] = { .type = NLA_U32 },
915         [DP_GENL_A_MC_GROUP] = { .type = NLA_U32 },
916         [DP_GENL_A_PORTNAME] = { .type = NLA_STRING }
917 };
918
919 static int dp_genl_add(struct sk_buff *skb, struct genl_info *info)
920 {
921         if (!info->attrs[DP_GENL_A_DP_IDX])
922                 return -EINVAL;
923
924         return new_dp(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
925 }
926
927 static struct genl_ops dp_genl_ops_add_dp = {
928         .cmd = DP_GENL_C_ADD_DP,
929         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
930         .policy = dp_genl_policy,
931         .doit = dp_genl_add,
932         .dumpit = NULL,
933 };
934
935 struct datapath *dp_get(int dp_idx)
936 {
937         if (dp_idx < 0 || dp_idx > DP_MAX)
938                 return NULL;
939         return rcu_dereference(dps[dp_idx]);
940 }
941
942 static int dp_genl_del(struct sk_buff *skb, struct genl_info *info)
943 {
944         struct datapath *dp;
945         int err;
946
947         if (!info->attrs[DP_GENL_A_DP_IDX])
948                 return -EINVAL;
949
950         mutex_lock(&dp_mutex);
951         dp = dp_get(nla_get_u32((info->attrs[DP_GENL_A_DP_IDX])));
952         if (!dp)
953                 err = -ENOENT;
954         else {
955                 del_dp(dp);
956                 err = 0;
957         }
958         mutex_unlock(&dp_mutex);
959         return err;
960 }
961
962 static struct genl_ops dp_genl_ops_del_dp = {
963         .cmd = DP_GENL_C_DEL_DP,
964         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
965         .policy = dp_genl_policy,
966         .doit = dp_genl_del,
967         .dumpit = NULL,
968 };
969
970 /* Queries a datapath for related information.  Currently the only relevant
971  * information is the datapath's multicast group ID.  Really we want one
972  * multicast group per datapath, but because of locking issues[*] we can't
973  * easily get one.  Thus, every datapath will currently return the same
974  * global multicast group ID, but in the future it would be nice to fix that.
975  *
976  * [*] dp_genl_add, to add a new datapath, is called under the genl_lock
977  *       mutex, and genl_register_mc_group, called to acquire a new multicast
978  *       group ID, also acquires genl_lock, thus deadlock.
979  */
980 static int dp_genl_query(struct sk_buff *skb, struct genl_info *info)
981 {
982         struct datapath *dp;
983         struct sk_buff *ans_skb = NULL;
984         int dp_idx;
985         int err = -ENOMEM;
986
987         if (!info->attrs[DP_GENL_A_DP_IDX])
988                 return -EINVAL;
989
990         rcu_read_lock();
991         dp_idx = nla_get_u32((info->attrs[DP_GENL_A_DP_IDX]));
992         dp = dp_get(dp_idx);
993         if (!dp)
994                 err = -ENOENT;
995         else {
996                 void *data;
997                 ans_skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
998                 if (!ans_skb) {
999                         err = -ENOMEM;
1000                         goto err;
1001                 }
1002                 data = genlmsg_put_reply(ans_skb, info, &dp_genl_family,
1003                                          0, DP_GENL_C_QUERY_DP);
1004                 if (data == NULL) {
1005                         err = -ENOMEM;
1006                         goto err;
1007                 }
1008                 NLA_PUT_U32(ans_skb, DP_GENL_A_DP_IDX, dp_idx);
1009                 NLA_PUT_U32(ans_skb, DP_GENL_A_MC_GROUP, mc_group.id);
1010
1011                 genlmsg_end(ans_skb, data);
1012                 err = genlmsg_reply(ans_skb, info);
1013                 if (!err)
1014                         ans_skb = NULL;
1015         }
1016 err:
1017 nla_put_failure:
1018         if (ans_skb)
1019                 kfree_skb(ans_skb);
1020         rcu_read_unlock();
1021         return err;
1022 }
1023
1024 static struct genl_ops dp_genl_ops_query_dp = {
1025         .cmd = DP_GENL_C_QUERY_DP,
1026         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1027         .policy = dp_genl_policy,
1028         .doit = dp_genl_query,
1029         .dumpit = NULL,
1030 };
1031
1032 static int dp_genl_add_del_port(struct sk_buff *skb, struct genl_info *info)
1033 {
1034         struct datapath *dp;
1035         struct net_device *port;
1036         int err;
1037
1038         if (!info->attrs[DP_GENL_A_DP_IDX] || !info->attrs[DP_GENL_A_PORTNAME])
1039                 return -EINVAL;
1040
1041         /* Get datapath. */
1042         mutex_lock(&dp_mutex);
1043         dp = dp_get(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
1044         if (!dp) {
1045                 err = -ENOENT;
1046                 goto out;
1047         }
1048
1049         /* Get interface to add/remove. */
1050         port = dev_get_by_name(&init_net, 
1051                         nla_data(info->attrs[DP_GENL_A_PORTNAME]));
1052         if (!port) {
1053                 err = -ENOENT;
1054                 goto out;
1055         }
1056
1057         /* Execute operation. */
1058         if (info->genlhdr->cmd == DP_GENL_C_ADD_PORT)
1059                 err = add_switch_port(dp, port);
1060         else {
1061                 if (port->br_port == NULL || port->br_port->dp != dp) {
1062                         err = -ENOENT;
1063                         goto out_put;
1064                 }
1065                 err = del_switch_port(port->br_port);
1066         }
1067
1068 out_put:
1069         dev_put(port);
1070 out:
1071         mutex_unlock(&dp_mutex);
1072         return err;
1073 }
1074
1075 static struct genl_ops dp_genl_ops_add_port = {
1076         .cmd = DP_GENL_C_ADD_PORT,
1077         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1078         .policy = dp_genl_policy,
1079         .doit = dp_genl_add_del_port,
1080         .dumpit = NULL,
1081 };
1082
1083 static struct genl_ops dp_genl_ops_del_port = {
1084         .cmd = DP_GENL_C_DEL_PORT,
1085         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1086         .policy = dp_genl_policy,
1087         .doit = dp_genl_add_del_port,
1088         .dumpit = NULL,
1089 };
1090
1091 static int dp_genl_openflow(struct sk_buff *skb, struct genl_info *info)
1092 {
1093         struct nlattr *va = info->attrs[DP_GENL_A_OPENFLOW];
1094         struct datapath *dp;
1095         struct ofp_header *oh;
1096         struct sender sender;
1097         int err;
1098
1099         if (!info->attrs[DP_GENL_A_DP_IDX] || !va)
1100                 return -EINVAL;
1101
1102         rcu_read_lock();
1103         dp = dp_get(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
1104         if (!dp) {
1105                 err = -ENOENT;
1106                 goto out;
1107         }
1108
1109         if (nla_len(va) < sizeof(struct ofp_header)) {
1110                 err = -EINVAL;
1111                 goto out;
1112         }
1113         oh = nla_data(va);
1114
1115         sender.xid = oh->xid;
1116         sender.pid = info->snd_pid;
1117         sender.seq = info->snd_seq;
1118         err = fwd_control_input(dp->chain, &sender, nla_data(va), nla_len(va));
1119
1120 out:
1121         rcu_read_unlock();
1122         return err;
1123 }
1124
1125 static struct nla_policy dp_genl_openflow_policy[DP_GENL_A_MAX + 1] = {
1126         [DP_GENL_A_DP_IDX] = { .type = NLA_U32 },
1127 };
1128
1129 static struct genl_ops dp_genl_ops_openflow = {
1130         .cmd = DP_GENL_C_OPENFLOW,
1131         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1132         .policy = dp_genl_openflow_policy,
1133         .doit = dp_genl_openflow,
1134         .dumpit = NULL,
1135 };
1136
1137 static struct nla_policy dp_genl_benchmark_policy[DP_GENL_A_MAX + 1] = {
1138         [DP_GENL_A_DP_IDX] = { .type = NLA_U32 },
1139         [DP_GENL_A_NPACKETS] = { .type = NLA_U32 },
1140         [DP_GENL_A_PSIZE] = { .type = NLA_U32 },
1141 };
1142
1143 static struct genl_ops dp_genl_ops_benchmark_nl = {
1144         .cmd = DP_GENL_C_BENCHMARK_NL,
1145         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1146         .policy = dp_genl_benchmark_policy,
1147         .doit = dp_genl_benchmark_nl,
1148         .dumpit = NULL,
1149 };
1150
1151 static struct genl_ops *dp_genl_all_ops[] = {
1152         /* Keep this operation first.  Generic Netlink dispatching
1153          * looks up operations with linear search, so we want it at the
1154          * front. */
1155         &dp_genl_ops_openflow,
1156
1157         &dp_genl_ops_add_dp,
1158         &dp_genl_ops_del_dp,
1159         &dp_genl_ops_query_dp,
1160         &dp_genl_ops_add_port,
1161         &dp_genl_ops_del_port,
1162         &dp_genl_ops_benchmark_nl,
1163 };
1164
1165 static int dp_init_netlink(void)
1166 {
1167         int err;
1168         int i;
1169
1170         err = genl_register_family(&dp_genl_family);
1171         if (err)
1172                 return err;
1173
1174         for (i = 0; i < ARRAY_SIZE(dp_genl_all_ops); i++) {
1175                 err = genl_register_ops(&dp_genl_family, dp_genl_all_ops[i]);
1176                 if (err)
1177                         goto err_unregister;
1178         }
1179
1180         strcpy(mc_group.name, "openflow");
1181         err = genl_register_mc_group(&dp_genl_family, &mc_group);
1182         if (err < 0)
1183                 goto err_unregister;
1184
1185         return 0;
1186
1187 err_unregister:
1188         genl_unregister_family(&dp_genl_family);
1189                 return err;
1190 }
1191
1192 static void dp_uninit_netlink(void)
1193 {
1194         genl_unregister_family(&dp_genl_family);
1195 }
1196
1197 #define DRV_NAME                "openflow"
1198 #define DRV_VERSION      VERSION
1199 #define DRV_DESCRIPTION "OpenFlow switching datapath implementation"
1200 #define DRV_COPYRIGHT   "Copyright (c) 2007, 2008 The Board of Trustees of The Leland Stanford Junior University"
1201
1202
1203 static int __init dp_init(void)
1204 {
1205         int err;
1206
1207         printk(KERN_INFO DRV_NAME ": " DRV_DESCRIPTION "\n");
1208         printk(KERN_INFO DRV_NAME ": " VERSION" built on "__DATE__" "__TIME__"\n");
1209         printk(KERN_INFO DRV_NAME ": " DRV_COPYRIGHT "\n");
1210
1211         err = flow_init();
1212         if (err)
1213                 goto error;
1214
1215         err = dp_init_netlink();
1216         if (err)
1217                 goto error_flow_exit;
1218
1219         /* Hook into callback used by the bridge to intercept packets.
1220          * Parasites we are. */
1221         if (br_handle_frame_hook)
1222                 printk("openflow: hijacking bridge hook\n");
1223         br_handle_frame_hook = dp_frame_hook;
1224
1225         return 0;
1226
1227 error_flow_exit:
1228         flow_exit();
1229 error:
1230         printk(KERN_EMERG "openflow: failed to install!");
1231         return err;
1232 }
1233
1234 static void dp_cleanup(void)
1235 {
1236         fwd_exit();
1237         dp_uninit_netlink();
1238         flow_exit();
1239         br_handle_frame_hook = NULL;
1240 }
1241
1242 module_init(dp_init);
1243 module_exit(dp_cleanup);
1244
1245 MODULE_DESCRIPTION(DRV_DESCRIPTION);
1246 MODULE_AUTHOR(DRV_COPYRIGHT);
1247 MODULE_LICENSE("GPL");