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