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