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