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