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