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