Implement OpenFlow statistics in switches and in dpctl.
[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 = 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         int duration;
756         
757         ofs->match.wildcards = htons(flow->key.wildcards);
758         ofs->match.in_port   = flow->key.in_port;
759         memcpy(ofs->match.dl_src, flow->key.dl_src, ETH_ALEN);
760         memcpy(ofs->match.dl_dst, flow->key.dl_dst, ETH_ALEN);
761         ofs->match.dl_vlan   = flow->key.dl_vlan;
762         ofs->match.dl_type   = flow->key.dl_type;
763         ofs->match.nw_src    = flow->key.nw_src;
764         ofs->match.nw_dst    = flow->key.nw_dst;
765         ofs->match.nw_proto  = flow->key.nw_proto;
766         memset(ofs->match.pad, 0, sizeof ofs->match.pad);
767         ofs->match.tp_src    = flow->key.tp_src;
768         ofs->match.tp_dst    = flow->key.tp_dst;
769         duration = (jiffies - flow->init_time) / HZ;
770         ofs->duration        = htons(min(65535, duration));
771         ofs->table_id        = htons(table_idx);
772         ofs->packet_count    = cpu_to_be64(flow->packet_count);
773         ofs->byte_count      = cpu_to_be64(flow->byte_count);
774 }
775
776 int
777 dp_send_flow_stats(struct datapath *dp, const struct sender *sender,
778                    const struct ofp_match *match)
779 {
780         struct sk_buff *skb;
781         struct ofp_flow_stat_reply *fsr;
782         size_t header_size, fudge, flow_size;
783         struct sw_flow_key match_key;
784         int table_idx, n_flows, max_flows;
785
786         header_size = offsetof(struct ofp_flow_stat_reply, flows);
787         fudge = 128;
788         flow_size = sizeof fsr->flows[0];
789         max_flows = (NLMSG_GOODSIZE - header_size - fudge) / flow_size;
790         fsr = alloc_openflow_skb(dp, header_size + max_flows * flow_size,
791                                  OFPT_FLOW_STAT_REPLY, sender, &skb);
792         if (!fsr)
793                 return -ENOMEM;
794
795         n_flows = 0;
796         flow_extract_match(&match_key, match);
797         for (table_idx = 0; table_idx < dp->chain->n_tables; table_idx++) {
798                 struct sw_table *table = dp->chain->tables[table_idx];
799                 struct swt_iterator iter;
800
801                 if (n_flows >= max_flows) {
802                         break;
803                 }
804
805                 if (!table->iterator(table, &iter)) {
806                         if (net_ratelimit())
807                                 printk("iterator failed for table %d\n",
808                                        table_idx);
809                         continue;
810                 }
811
812                 for (; iter.flow; table->iterator_next(&iter)) {
813                         if (flow_matches(&match_key, &iter.flow->key)) {
814                                 fill_flow_stats(&fsr->flows[n_flows],
815                                                 iter.flow, table_idx);
816                                 if (++n_flows >= max_flows) {
817                                         break;
818                                 }
819                         }
820                 }
821                 table->iterator_destroy(&iter);
822         }
823         resize_openflow_skb(skb, &fsr->header,
824                             header_size + flow_size * n_flows);
825         return send_openflow_skb(skb, sender);
826 }
827
828 static int 
829 fill_port_stat_reply(struct datapath *dp, struct ofp_port_stat_reply *psr)
830 {
831         struct net_bridge_port *p;
832         int port_count = 0;
833
834         list_for_each_entry_rcu (p, &dp->port_list, node) {
835                 struct ofp_port_stats *ps = &psr->ports[port_count++];
836                 struct net_device_stats *stats = p->dev->get_stats(p->dev);
837                 ps->port_no = htons(p->port_no);
838                 memset(ps->pad, 0, sizeof ps->pad);
839                 ps->rx_count = cpu_to_be64(stats->rx_packets);
840                 ps->tx_count = cpu_to_be64(stats->tx_packets);
841                 ps->drop_count = cpu_to_be64(stats->rx_dropped
842                                              + stats->tx_dropped);
843         }
844
845         return port_count;
846 }
847
848 int
849 dp_send_port_stats(struct datapath *dp, const struct sender *sender)
850 {
851         struct sk_buff *skb;
852         struct ofp_port_stat_reply *psr;
853         size_t psr_len, port_max_len;
854         int port_count;
855
856         /* Overallocate. */
857         port_max_len = sizeof(struct ofp_port_stats) * OFPP_MAX;
858         psr = alloc_openflow_skb(dp, sizeof *psr + port_max_len,
859                                  OFPT_PORT_STAT_REPLY, sender, &skb);
860         if (!psr)
861                 return -ENOMEM;
862
863         /* Fill. */
864         port_count = fill_port_stat_reply(dp, psr);
865
866         /* Shrink to fit. */
867         psr_len = sizeof *psr + sizeof(struct ofp_port_stats) * port_count;
868         resize_openflow_skb(skb, &psr->header, psr_len);
869         return send_openflow_skb(skb, sender);
870 }
871
872 int
873 dp_send_table_stats(struct datapath *dp, const struct sender *sender)
874 {
875         struct sk_buff *skb;
876         struct ofp_table_stat_reply *tsr;
877         int i, n_tables;
878
879         n_tables = dp->chain->n_tables;
880         tsr = alloc_openflow_skb(dp, (offsetof(struct ofp_table_stat_reply,
881                                                tables)
882                                       + sizeof tsr->tables[0] * n_tables),
883                                  OFPT_TABLE_STAT_REPLY, sender, &skb);
884         if (!tsr)
885                 return -ENOMEM;
886         for (i = 0; i < n_tables; i++) {
887                 struct ofp_table_stats *ots = &tsr->tables[i];
888                 struct sw_table_stats stats;
889                 dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
890                 strncpy(ots->name, stats.name, sizeof ots->name);
891                 ots->table_id = htons(i);
892                 ots->pad[0] = ots->pad[1] = 0;
893                 ots->max_entries = htonl(stats.max_flows);
894                 ots->active_count = htonl(stats.n_flows);
895                 ots->matched_count = cpu_to_be64(0); /* FIXME */
896         }
897         return send_openflow_skb(skb, sender);
898 }
899
900 /* Generic Netlink interface.
901  *
902  * See netlink(7) for an introduction to netlink.  See
903  * http://linux-net.osdl.org/index.php/Netlink for more information and
904  * pointers on how to work with netlink and Generic Netlink in the kernel and
905  * in userspace. */
906
907 static struct genl_family dp_genl_family = {
908         .id = GENL_ID_GENERATE,
909         .hdrsize = 0,
910         .name = DP_GENL_FAMILY_NAME,
911         .version = 1,
912         .maxattr = DP_GENL_A_MAX,
913 };
914
915 /* Attribute policy: what each attribute may contain.  */
916 static struct nla_policy dp_genl_policy[DP_GENL_A_MAX + 1] = {
917         [DP_GENL_A_DP_IDX] = { .type = NLA_U32 },
918         [DP_GENL_A_MC_GROUP] = { .type = NLA_U32 },
919         [DP_GENL_A_PORTNAME] = { .type = NLA_STRING }
920 };
921
922 static int dp_genl_add(struct sk_buff *skb, struct genl_info *info)
923 {
924         if (!info->attrs[DP_GENL_A_DP_IDX])
925                 return -EINVAL;
926
927         return new_dp(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
928 }
929
930 static struct genl_ops dp_genl_ops_add_dp = {
931         .cmd = DP_GENL_C_ADD_DP,
932         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
933         .policy = dp_genl_policy,
934         .doit = dp_genl_add,
935         .dumpit = NULL,
936 };
937
938 struct datapath *dp_get(int dp_idx)
939 {
940         if (dp_idx < 0 || dp_idx > DP_MAX)
941                 return NULL;
942         return rcu_dereference(dps[dp_idx]);
943 }
944
945 static int dp_genl_del(struct sk_buff *skb, struct genl_info *info)
946 {
947         struct datapath *dp;
948         int err;
949
950         if (!info->attrs[DP_GENL_A_DP_IDX])
951                 return -EINVAL;
952
953         mutex_lock(&dp_mutex);
954         dp = dp_get(nla_get_u32((info->attrs[DP_GENL_A_DP_IDX])));
955         if (!dp)
956                 err = -ENOENT;
957         else {
958                 del_dp(dp);
959                 err = 0;
960         }
961         mutex_unlock(&dp_mutex);
962         return err;
963 }
964
965 static struct genl_ops dp_genl_ops_del_dp = {
966         .cmd = DP_GENL_C_DEL_DP,
967         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
968         .policy = dp_genl_policy,
969         .doit = dp_genl_del,
970         .dumpit = NULL,
971 };
972
973 /* Queries a datapath for related information.  Currently the only relevant
974  * information is the datapath's multicast group ID.  Really we want one
975  * multicast group per datapath, but because of locking issues[*] we can't
976  * easily get one.  Thus, every datapath will currently return the same
977  * global multicast group ID, but in the future it would be nice to fix that.
978  *
979  * [*] dp_genl_add, to add a new datapath, is called under the genl_lock
980  *       mutex, and genl_register_mc_group, called to acquire a new multicast
981  *       group ID, also acquires genl_lock, thus deadlock.
982  */
983 static int dp_genl_query(struct sk_buff *skb, struct genl_info *info)
984 {
985         struct datapath *dp;
986         struct sk_buff *ans_skb = NULL;
987         int dp_idx;
988         int err = -ENOMEM;
989
990         if (!info->attrs[DP_GENL_A_DP_IDX])
991                 return -EINVAL;
992
993         rcu_read_lock();
994         dp_idx = nla_get_u32((info->attrs[DP_GENL_A_DP_IDX]));
995         dp = dp_get(dp_idx);
996         if (!dp)
997                 err = -ENOENT;
998         else {
999                 void *data;
1000                 ans_skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
1001                 if (!ans_skb) {
1002                         err = -ENOMEM;
1003                         goto err;
1004                 }
1005                 data = genlmsg_put_reply(ans_skb, info, &dp_genl_family,
1006                                          0, DP_GENL_C_QUERY_DP);
1007                 if (data == NULL) {
1008                         err = -ENOMEM;
1009                         goto err;
1010                 }
1011                 NLA_PUT_U32(ans_skb, DP_GENL_A_DP_IDX, dp_idx);
1012                 NLA_PUT_U32(ans_skb, DP_GENL_A_MC_GROUP, mc_group.id);
1013
1014                 genlmsg_end(ans_skb, data);
1015                 err = genlmsg_reply(ans_skb, info);
1016                 if (!err)
1017                         ans_skb = NULL;
1018         }
1019 err:
1020 nla_put_failure:
1021         if (ans_skb)
1022                 kfree_skb(ans_skb);
1023         rcu_read_unlock();
1024         return err;
1025 }
1026
1027 static struct genl_ops dp_genl_ops_query_dp = {
1028         .cmd = DP_GENL_C_QUERY_DP,
1029         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1030         .policy = dp_genl_policy,
1031         .doit = dp_genl_query,
1032         .dumpit = NULL,
1033 };
1034
1035 static int dp_genl_add_del_port(struct sk_buff *skb, struct genl_info *info)
1036 {
1037         struct datapath *dp;
1038         struct net_device *port;
1039         int err;
1040
1041         if (!info->attrs[DP_GENL_A_DP_IDX] || !info->attrs[DP_GENL_A_PORTNAME])
1042                 return -EINVAL;
1043
1044         /* Get datapath. */
1045         mutex_lock(&dp_mutex);
1046         dp = dp_get(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
1047         if (!dp) {
1048                 err = -ENOENT;
1049                 goto out;
1050         }
1051
1052         /* Get interface to add/remove. */
1053         port = dev_get_by_name(&init_net, 
1054                         nla_data(info->attrs[DP_GENL_A_PORTNAME]));
1055         if (!port) {
1056                 err = -ENOENT;
1057                 goto out;
1058         }
1059
1060         /* Execute operation. */
1061         if (info->genlhdr->cmd == DP_GENL_C_ADD_PORT)
1062                 err = add_switch_port(dp, port);
1063         else {
1064                 if (port->br_port == NULL || port->br_port->dp != dp) {
1065                         err = -ENOENT;
1066                         goto out_put;
1067                 }
1068                 err = del_switch_port(port->br_port);
1069         }
1070
1071 out_put:
1072         dev_put(port);
1073 out:
1074         mutex_unlock(&dp_mutex);
1075         return err;
1076 }
1077
1078 static struct genl_ops dp_genl_ops_add_port = {
1079         .cmd = DP_GENL_C_ADD_PORT,
1080         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1081         .policy = dp_genl_policy,
1082         .doit = dp_genl_add_del_port,
1083         .dumpit = NULL,
1084 };
1085
1086 static struct genl_ops dp_genl_ops_del_port = {
1087         .cmd = DP_GENL_C_DEL_PORT,
1088         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1089         .policy = dp_genl_policy,
1090         .doit = dp_genl_add_del_port,
1091         .dumpit = NULL,
1092 };
1093
1094 static int dp_genl_openflow(struct sk_buff *skb, struct genl_info *info)
1095 {
1096         struct nlattr *va = info->attrs[DP_GENL_A_OPENFLOW];
1097         struct datapath *dp;
1098         struct ofp_header *oh;
1099         struct sender sender;
1100         int err;
1101
1102         if (!info->attrs[DP_GENL_A_DP_IDX] || !va)
1103                 return -EINVAL;
1104
1105         rcu_read_lock();
1106         dp = dp_get(nla_get_u32(info->attrs[DP_GENL_A_DP_IDX]));
1107         if (!dp) {
1108                 err = -ENOENT;
1109                 goto out;
1110         }
1111
1112         va = info->attrs[DP_GENL_A_OPENFLOW];
1113         if (nla_len(va) < sizeof(struct ofp_header)) {
1114                 err = -EINVAL;
1115                 goto out;
1116         }
1117         oh = nla_data(va);
1118
1119         sender.xid = oh->xid;
1120         sender.pid = info->snd_pid;
1121         sender.seq = info->snd_seq;
1122         err = fwd_control_input(dp->chain, &sender, nla_data(va), nla_len(va));
1123
1124 out:
1125         rcu_read_unlock();
1126         return err;
1127 }
1128
1129 static struct nla_policy dp_genl_openflow_policy[DP_GENL_A_MAX + 1] = {
1130         [DP_GENL_A_DP_IDX] = { .type = NLA_U32 },
1131 };
1132
1133 static struct genl_ops dp_genl_ops_openflow = {
1134         .cmd = DP_GENL_C_OPENFLOW,
1135         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1136         .policy = dp_genl_openflow_policy,
1137         .doit = dp_genl_openflow,
1138         .dumpit = NULL,
1139 };
1140
1141 static struct nla_policy dp_genl_benchmark_policy[DP_GENL_A_MAX + 1] = {
1142         [DP_GENL_A_DP_IDX] = { .type = NLA_U32 },
1143         [DP_GENL_A_NPACKETS] = { .type = NLA_U32 },
1144         [DP_GENL_A_PSIZE] = { .type = NLA_U32 },
1145 };
1146
1147 static struct genl_ops dp_genl_ops_benchmark_nl = {
1148         .cmd = DP_GENL_C_BENCHMARK_NL,
1149         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1150         .policy = dp_genl_benchmark_policy,
1151         .doit = dp_genl_benchmark_nl,
1152         .dumpit = NULL,
1153 };
1154
1155 static struct genl_ops *dp_genl_all_ops[] = {
1156         /* Keep this operation first.  Generic Netlink dispatching
1157          * looks up operations with linear search, so we want it at the
1158          * front. */
1159         &dp_genl_ops_openflow,
1160
1161         &dp_genl_ops_add_dp,
1162         &dp_genl_ops_del_dp,
1163         &dp_genl_ops_query_dp,
1164         &dp_genl_ops_add_port,
1165         &dp_genl_ops_del_port,
1166         &dp_genl_ops_benchmark_nl,
1167 };
1168
1169 static int dp_init_netlink(void)
1170 {
1171         int err;
1172         int i;
1173
1174         err = genl_register_family(&dp_genl_family);
1175         if (err)
1176                 return err;
1177
1178         for (i = 0; i < ARRAY_SIZE(dp_genl_all_ops); i++) {
1179                 err = genl_register_ops(&dp_genl_family, dp_genl_all_ops[i]);
1180                 if (err)
1181                         goto err_unregister;
1182         }
1183
1184         strcpy(mc_group.name, "openflow");
1185         err = genl_register_mc_group(&dp_genl_family, &mc_group);
1186         if (err < 0)
1187                 goto err_unregister;
1188
1189         return 0;
1190
1191 err_unregister:
1192         genl_unregister_family(&dp_genl_family);
1193                 return err;
1194 }
1195
1196 static void dp_uninit_netlink(void)
1197 {
1198         genl_unregister_family(&dp_genl_family);
1199 }
1200
1201 #define DRV_NAME                "openflow"
1202 #define DRV_VERSION      VERSION
1203 #define DRV_DESCRIPTION "OpenFlow switching datapath implementation"
1204 #define DRV_COPYRIGHT   "Copyright (c) 2007, 2008 The Board of Trustees of The Leland Stanford Junior University"
1205
1206
1207 static int __init dp_init(void)
1208 {
1209         int err;
1210
1211         printk(KERN_INFO DRV_NAME ": " DRV_DESCRIPTION "\n");
1212         printk(KERN_INFO DRV_NAME ": " VERSION" built on "__DATE__" "__TIME__"\n");
1213         printk(KERN_INFO DRV_NAME ": " DRV_COPYRIGHT "\n");
1214
1215         err = flow_init();
1216         if (err)
1217                 goto error;
1218
1219         err = dp_init_netlink();
1220         if (err)
1221                 goto error_flow_exit;
1222
1223         /* Hook into callback used by the bridge to intercept packets.
1224          * Parasites we are. */
1225         if (br_handle_frame_hook)
1226                 printk("openflow: hijacking bridge hook\n");
1227         br_handle_frame_hook = dp_frame_hook;
1228
1229         return 0;
1230
1231 error_flow_exit:
1232         flow_exit();
1233 error:
1234         printk(KERN_EMERG "openflow: failed to install!");
1235         return err;
1236 }
1237
1238 static void dp_cleanup(void)
1239 {
1240         fwd_exit();
1241         dp_uninit_netlink();
1242         flow_exit();
1243         br_handle_frame_hook = NULL;
1244 }
1245
1246 module_init(dp_init);
1247 module_exit(dp_cleanup);
1248
1249 MODULE_DESCRIPTION(DRV_DESCRIPTION);
1250 MODULE_AUTHOR(DRV_COPYRIGHT);
1251 MODULE_LICENSE("GPL");