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