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