83dd76fefcbd4d6d072c98d72b12b7cc5285cd2d
[sliver-openvswitch.git] / datapath / datapath.c
1 /*
2  * Copyright (c) 2007, 2008, 2009, 2010 Nicira Networks.
3  * Distributed under the terms of the GNU GPL version 2.
4  *
5  * Significant portions of this file may be copied from parts of the Linux
6  * kernel, by Linus Torvalds and others.
7  */
8
9 /* Functions for managing the dp interface/device. */
10
11 #include <linux/init.h>
12 #include <linux/module.h>
13 #include <linux/fs.h>
14 #include <linux/if_arp.h>
15 #include <linux/if_vlan.h>
16 #include <linux/in.h>
17 #include <linux/ip.h>
18 #include <linux/delay.h>
19 #include <linux/time.h>
20 #include <linux/etherdevice.h>
21 #include <linux/kernel.h>
22 #include <linux/kthread.h>
23 #include <linux/mutex.h>
24 #include <linux/percpu.h>
25 #include <linux/rcupdate.h>
26 #include <linux/tcp.h>
27 #include <linux/udp.h>
28 #include <linux/version.h>
29 #include <linux/ethtool.h>
30 #include <linux/random.h>
31 #include <linux/wait.h>
32 #include <asm/system.h>
33 #include <asm/div64.h>
34 #include <asm/bug.h>
35 #include <linux/netfilter_bridge.h>
36 #include <linux/netfilter_ipv4.h>
37 #include <linux/inetdevice.h>
38 #include <linux/list.h>
39 #include <linux/rculist.h>
40 #include <linux/workqueue.h>
41 #include <linux/dmi.h>
42 #include <net/inet_ecn.h>
43
44 #include "openvswitch/datapath-protocol.h"
45 #include "datapath.h"
46 #include "actions.h"
47 #include "flow.h"
48 #include "table.h"
49 #include "vport-internal_dev.h"
50
51 #include "compat.h"
52
53
54 int (*dp_ioctl_hook)(struct net_device *dev, struct ifreq *rq, int cmd);
55 EXPORT_SYMBOL(dp_ioctl_hook);
56
57 /* Datapaths.  Protected on the read side by rcu_read_lock, on the write side
58  * by dp_mutex.
59  *
60  * dp_mutex nests inside the RTNL lock: if you need both you must take the RTNL
61  * lock first.
62  *
63  * It is safe to access the datapath and dp_port structures with just
64  * dp_mutex.
65  */
66 static struct datapath *dps[ODP_MAX];
67 static DEFINE_MUTEX(dp_mutex);
68
69 /* Number of milliseconds between runs of the maintenance thread. */
70 #define MAINT_SLEEP_MSECS 1000
71
72 static int new_dp_port(struct datapath *, struct odp_port *, int port_no);
73
74 /* Must be called with rcu_read_lock or dp_mutex. */
75 struct datapath *get_dp(int dp_idx)
76 {
77         if (dp_idx < 0 || dp_idx >= ODP_MAX)
78                 return NULL;
79         return rcu_dereference(dps[dp_idx]);
80 }
81 EXPORT_SYMBOL_GPL(get_dp);
82
83 static struct datapath *get_dp_locked(int dp_idx)
84 {
85         struct datapath *dp;
86
87         mutex_lock(&dp_mutex);
88         dp = get_dp(dp_idx);
89         if (dp)
90                 mutex_lock(&dp->mutex);
91         mutex_unlock(&dp_mutex);
92         return dp;
93 }
94
95 /* Must be called with rcu_read_lock or RTNL lock. */
96 const char *dp_name(const struct datapath *dp)
97 {
98         return vport_get_name(dp->ports[ODPP_LOCAL]->vport);
99 }
100
101 static inline size_t br_nlmsg_size(void)
102 {
103         return NLMSG_ALIGN(sizeof(struct ifinfomsg))
104                + nla_total_size(IFNAMSIZ) /* IFLA_IFNAME */
105                + nla_total_size(MAX_ADDR_LEN) /* IFLA_ADDRESS */
106                + nla_total_size(4) /* IFLA_MASTER */
107                + nla_total_size(4) /* IFLA_MTU */
108                + nla_total_size(4) /* IFLA_LINK */
109                + nla_total_size(1); /* IFLA_OPERSTATE */
110 }
111
112 static int dp_fill_ifinfo(struct sk_buff *skb,
113                           const struct dp_port *port,
114                           int event, unsigned int flags)
115 {
116         const struct datapath *dp = port->dp;
117         int ifindex = vport_get_ifindex(port->vport);
118         int iflink = vport_get_iflink(port->vport);
119         struct ifinfomsg *hdr;
120         struct nlmsghdr *nlh;
121
122         if (ifindex < 0)
123                 return ifindex;
124
125         if (iflink < 0)
126                 return iflink;
127
128         nlh = nlmsg_put(skb, 0, 0, event, sizeof(*hdr), flags);
129         if (nlh == NULL)
130                 return -EMSGSIZE;
131
132         hdr = nlmsg_data(nlh);
133         hdr->ifi_family = AF_BRIDGE;
134         hdr->__ifi_pad = 0;
135         hdr->ifi_type = ARPHRD_ETHER;
136         hdr->ifi_index = ifindex;
137         hdr->ifi_flags = vport_get_flags(port->vport);
138         hdr->ifi_change = 0;
139
140         NLA_PUT_STRING(skb, IFLA_IFNAME, vport_get_name(port->vport));
141         NLA_PUT_U32(skb, IFLA_MASTER, vport_get_ifindex(dp->ports[ODPP_LOCAL]->vport));
142         NLA_PUT_U32(skb, IFLA_MTU, vport_get_mtu(port->vport));
143 #ifdef IFLA_OPERSTATE
144         NLA_PUT_U8(skb, IFLA_OPERSTATE,
145                    vport_is_running(port->vport)
146                         ? vport_get_operstate(port->vport)
147                         : IF_OPER_DOWN);
148 #endif
149
150         NLA_PUT(skb, IFLA_ADDRESS, ETH_ALEN,
151                                         vport_get_addr(port->vport));
152
153         if (ifindex != iflink)
154                 NLA_PUT_U32(skb, IFLA_LINK,iflink);
155
156         return nlmsg_end(skb, nlh);
157
158 nla_put_failure:
159         nlmsg_cancel(skb, nlh);
160         return -EMSGSIZE;
161 }
162
163 static void dp_ifinfo_notify(int event, struct dp_port *port)
164 {
165         struct sk_buff *skb;
166         int err = -ENOBUFS;
167
168         skb = nlmsg_new(br_nlmsg_size(), GFP_KERNEL);
169         if (skb == NULL)
170                 goto errout;
171
172         err = dp_fill_ifinfo(skb, port, event, 0);
173         if (err < 0) {
174                 /* -EMSGSIZE implies BUG in br_nlmsg_size() */
175                 WARN_ON(err == -EMSGSIZE);
176                 kfree_skb(skb);
177                 goto errout;
178         }
179         rtnl_notify(skb, &init_net, 0, RTNLGRP_LINK, NULL, GFP_KERNEL);
180         return;
181 errout:
182         if (err < 0)
183                 rtnl_set_sk_err(&init_net, RTNLGRP_LINK, err);
184 }
185
186 static void release_dp(struct kobject *kobj)
187 {
188         struct datapath *dp = container_of(kobj, struct datapath, ifobj);
189         kfree(dp);
190 }
191
192 static struct kobj_type dp_ktype = {
193         .release = release_dp
194 };
195
196 static int create_dp(int dp_idx, const char __user *devnamep)
197 {
198         struct odp_port internal_dev_port;
199         char devname[IFNAMSIZ];
200         struct datapath *dp;
201         int err;
202         int i;
203
204         if (devnamep) {
205                 int retval = strncpy_from_user(devname, devnamep, IFNAMSIZ);
206                 if (retval < 0) {
207                         err = -EFAULT;
208                         goto err;
209                 } else if (retval >= IFNAMSIZ) {
210                         err = -ENAMETOOLONG;
211                         goto err;
212                 }
213         } else {
214                 snprintf(devname, sizeof devname, "of%d", dp_idx);
215         }
216
217         rtnl_lock();
218         mutex_lock(&dp_mutex);
219         err = -ENODEV;
220         if (!try_module_get(THIS_MODULE))
221                 goto err_unlock;
222
223         /* Exit early if a datapath with that number already exists.
224          * (We don't use -EEXIST because that's ambiguous with 'devname'
225          * conflicting with an existing network device name.) */
226         err = -EBUSY;
227         if (get_dp(dp_idx))
228                 goto err_put_module;
229
230         err = -ENOMEM;
231         dp = kzalloc(sizeof *dp, GFP_KERNEL);
232         if (dp == NULL)
233                 goto err_put_module;
234         INIT_LIST_HEAD(&dp->port_list);
235         mutex_init(&dp->mutex);
236         dp->dp_idx = dp_idx;
237         for (i = 0; i < DP_N_QUEUES; i++)
238                 skb_queue_head_init(&dp->queues[i]);
239         init_waitqueue_head(&dp->waitqueue);
240
241         /* Initialize kobject for bridge.  This will be added as
242          * /sys/class/net/<devname>/brif later, if sysfs is enabled. */
243         dp->ifobj.kset = NULL;
244         kobject_init(&dp->ifobj, &dp_ktype);
245
246         /* Allocate table. */
247         err = -ENOMEM;
248         rcu_assign_pointer(dp->table, tbl_create(0));
249         if (!dp->table)
250                 goto err_free_dp;
251
252         /* Set up our datapath device. */
253         BUILD_BUG_ON(sizeof(internal_dev_port.devname) != sizeof(devname));
254         strcpy(internal_dev_port.devname, devname);
255         internal_dev_port.flags = ODP_PORT_INTERNAL;
256         err = new_dp_port(dp, &internal_dev_port, ODPP_LOCAL);
257         if (err) {
258                 if (err == -EBUSY)
259                         err = -EEXIST;
260
261                 goto err_destroy_table;
262         }
263
264         dp->drop_frags = 0;
265         dp->stats_percpu = alloc_percpu(struct dp_stats_percpu);
266         if (!dp->stats_percpu)
267                 goto err_destroy_local_port;
268
269         rcu_assign_pointer(dps[dp_idx], dp);
270         mutex_unlock(&dp_mutex);
271         rtnl_unlock();
272
273         dp_sysfs_add_dp(dp);
274
275         return 0;
276
277 err_destroy_local_port:
278         dp_detach_port(dp->ports[ODPP_LOCAL], 1);
279 err_destroy_table:
280         tbl_destroy(dp->table, NULL);
281 err_free_dp:
282         kfree(dp);
283 err_put_module:
284         module_put(THIS_MODULE);
285 err_unlock:
286         mutex_unlock(&dp_mutex);
287         rtnl_unlock();
288 err:
289         return err;
290 }
291
292 static void do_destroy_dp(struct datapath *dp)
293 {
294         struct dp_port *p, *n;
295         int i;
296
297         list_for_each_entry_safe (p, n, &dp->port_list, node)
298                 if (p->port_no != ODPP_LOCAL)
299                         dp_detach_port(p, 1);
300
301         dp_sysfs_del_dp(dp);
302
303         rcu_assign_pointer(dps[dp->dp_idx], NULL);
304
305         dp_detach_port(dp->ports[ODPP_LOCAL], 1);
306
307         tbl_destroy(dp->table, flow_free_tbl);
308
309         for (i = 0; i < DP_N_QUEUES; i++)
310                 skb_queue_purge(&dp->queues[i]);
311         for (i = 0; i < DP_MAX_GROUPS; i++)
312                 kfree(dp->groups[i]);
313         free_percpu(dp->stats_percpu);
314         kobject_put(&dp->ifobj);
315         module_put(THIS_MODULE);
316 }
317
318 static int destroy_dp(int dp_idx)
319 {
320         struct datapath *dp;
321         int err;
322
323         rtnl_lock();
324         mutex_lock(&dp_mutex);
325         dp = get_dp(dp_idx);
326         err = -ENODEV;
327         if (!dp)
328                 goto err_unlock;
329
330         do_destroy_dp(dp);
331         err = 0;
332
333 err_unlock:
334         mutex_unlock(&dp_mutex);
335         rtnl_unlock();
336         return err;
337 }
338
339 static void release_dp_port(struct kobject *kobj)
340 {
341         struct dp_port *p = container_of(kobj, struct dp_port, kobj);
342         kfree(p);
343 }
344
345 static struct kobj_type brport_ktype = {
346 #ifdef CONFIG_SYSFS
347         .sysfs_ops = &brport_sysfs_ops,
348 #endif
349         .release = release_dp_port
350 };
351
352 /* Called with RTNL lock and dp_mutex. */
353 static int new_dp_port(struct datapath *dp, struct odp_port *odp_port, int port_no)
354 {
355         struct vport *vport;
356         struct dp_port *p;
357         int err;
358
359         vport = vport_locate(odp_port->devname);
360         if (!vport) {
361                 vport_lock();
362
363                 if (odp_port->flags & ODP_PORT_INTERNAL)
364                         vport = __vport_add(odp_port->devname, "internal", NULL);
365                 else
366                         vport = __vport_add(odp_port->devname, "netdev", NULL);
367
368                 vport_unlock();
369
370                 if (IS_ERR(vport))
371                         return PTR_ERR(vport);
372         }
373
374         p = kzalloc(sizeof(*p), GFP_KERNEL);
375         if (!p)
376                 return -ENOMEM;
377
378         p->port_no = port_no;
379         p->dp = dp;
380         atomic_set(&p->sflow_pool, 0);
381
382         err = vport_attach(vport, p);
383         if (err) {
384                 kfree(p);
385                 return err;
386         }
387
388         rcu_assign_pointer(dp->ports[port_no], p);
389         list_add_rcu(&p->node, &dp->port_list);
390         dp->n_ports++;
391
392         /* Initialize kobject for bridge.  This will be added as
393          * /sys/class/net/<devname>/brport later, if sysfs is enabled. */
394         p->kobj.kset = NULL;
395         kobject_init(&p->kobj, &brport_ktype);
396
397         dp_ifinfo_notify(RTM_NEWLINK, p);
398
399         return 0;
400 }
401
402 static int attach_port(int dp_idx, struct odp_port __user *portp)
403 {
404         struct datapath *dp;
405         struct odp_port port;
406         int port_no;
407         int err;
408
409         err = -EFAULT;
410         if (copy_from_user(&port, portp, sizeof port))
411                 goto out;
412         port.devname[IFNAMSIZ - 1] = '\0';
413
414         rtnl_lock();
415         dp = get_dp_locked(dp_idx);
416         err = -ENODEV;
417         if (!dp)
418                 goto out_unlock_rtnl;
419
420         for (port_no = 1; port_no < DP_MAX_PORTS; port_no++)
421                 if (!dp->ports[port_no])
422                         goto got_port_no;
423         err = -EFBIG;
424         goto out_unlock_dp;
425
426 got_port_no:
427         err = new_dp_port(dp, &port, port_no);
428         if (err)
429                 goto out_unlock_dp;
430
431         if (!(port.flags & ODP_PORT_INTERNAL))
432                 set_internal_devs_mtu(dp);
433         dp_sysfs_add_if(dp->ports[port_no]);
434
435         err = __put_user(port_no, &portp->port);
436
437 out_unlock_dp:
438         mutex_unlock(&dp->mutex);
439 out_unlock_rtnl:
440         rtnl_unlock();
441 out:
442         return err;
443 }
444
445 int dp_detach_port(struct dp_port *p, int may_delete)
446 {
447         struct vport *vport = p->vport;
448         int err;
449
450         ASSERT_RTNL();
451
452         if (p->port_no != ODPP_LOCAL)
453                 dp_sysfs_del_if(p);
454         dp_ifinfo_notify(RTM_DELLINK, p);
455
456         /* First drop references to device. */
457         p->dp->n_ports--;
458         list_del_rcu(&p->node);
459         rcu_assign_pointer(p->dp->ports[p->port_no], NULL);
460
461         err = vport_detach(vport);
462         if (err)
463                 return err;
464
465         /* Then wait until no one is still using it, and destroy it. */
466         synchronize_rcu();
467
468         if (may_delete) {
469                 const char *port_type = vport_get_type(vport);
470
471                 if (!strcmp(port_type, "netdev") || !strcmp(port_type, "internal")) {
472                         vport_lock();
473                         __vport_del(vport);
474                         vport_unlock();
475                 }
476         }
477
478         kobject_put(&p->kobj);
479
480         return 0;
481 }
482
483 static int detach_port(int dp_idx, int port_no)
484 {
485         struct dp_port *p;
486         struct datapath *dp;
487         int err;
488
489         err = -EINVAL;
490         if (port_no < 0 || port_no >= DP_MAX_PORTS || port_no == ODPP_LOCAL)
491                 goto out;
492
493         rtnl_lock();
494         dp = get_dp_locked(dp_idx);
495         err = -ENODEV;
496         if (!dp)
497                 goto out_unlock_rtnl;
498
499         p = dp->ports[port_no];
500         err = -ENOENT;
501         if (!p)
502                 goto out_unlock_dp;
503
504         err = dp_detach_port(p, 1);
505
506 out_unlock_dp:
507         mutex_unlock(&dp->mutex);
508 out_unlock_rtnl:
509         rtnl_unlock();
510 out:
511         return err;
512 }
513
514 /* Must be called with rcu_read_lock and with bottom-halves disabled. */
515 void dp_process_received_packet(struct dp_port *p, struct sk_buff *skb)
516 {
517         struct datapath *dp = p->dp;
518         struct dp_stats_percpu *stats;
519         struct odp_flow_key key;
520         struct tbl_node *flow_node;
521
522         WARN_ON_ONCE(skb_shared(skb));
523         skb_warn_if_lro(skb);
524
525         OVS_CB(skb)->dp_port = p;
526         compute_ip_summed(skb, false);
527
528         /* BHs are off so we don't have to use get_cpu()/put_cpu() here. */
529         stats = percpu_ptr(dp->stats_percpu, smp_processor_id());
530
531         if (flow_extract(skb, p ? p->port_no : ODPP_NONE, &key)) {
532                 if (dp->drop_frags) {
533                         kfree_skb(skb);
534                         stats->n_frags++;
535                         return;
536                 }
537         }
538
539         flow_node = tbl_lookup(rcu_dereference(dp->table), &key, flow_hash(&key), flow_cmp);
540         if (flow_node) {
541                 struct sw_flow *flow = flow_cast(flow_node);
542                 struct sw_flow_actions *acts = rcu_dereference(flow->sf_acts);
543                 flow_used(flow, skb);
544                 execute_actions(dp, skb, &key, acts->actions, acts->n_actions,
545                                 GFP_ATOMIC);
546                 stats->n_hit++;
547         } else {
548                 stats->n_missed++;
549                 dp_output_control(dp, skb, _ODPL_MISS_NR, OVS_CB(skb)->tun_id);
550         }
551 }
552
553 #if defined(CONFIG_XEN) && defined(HAVE_PROTO_DATA_VALID)
554 /* This code is based on skb_checksum_setup() from Xen's net/dev/core.c.  We
555  * can't call this function directly because it isn't exported in all
556  * versions. */
557 int vswitch_skb_checksum_setup(struct sk_buff *skb)
558 {
559         struct iphdr *iph;
560         unsigned char *th;
561         int err = -EPROTO;
562         __u16 csum_start, csum_offset;
563
564         if (!skb->proto_csum_blank)
565                 return 0;
566
567         if (skb->protocol != htons(ETH_P_IP))
568                 goto out;
569
570         if (!pskb_may_pull(skb, skb_network_header(skb) + sizeof(struct iphdr) - skb->data))
571                 goto out;
572
573         iph = ip_hdr(skb);
574         th = skb_network_header(skb) + 4 * iph->ihl;
575
576         csum_start = th - skb->head;
577         switch (iph->protocol) {
578         case IPPROTO_TCP:
579                 csum_offset = offsetof(struct tcphdr, check);
580                 break;
581         case IPPROTO_UDP:
582                 csum_offset = offsetof(struct udphdr, check);
583                 break;
584         default:
585                 if (net_ratelimit())
586                         printk(KERN_ERR "Attempting to checksum a non-"
587                                "TCP/UDP packet, dropping a protocol"
588                                " %d packet", iph->protocol);
589                 goto out;
590         }
591
592         if (!pskb_may_pull(skb, th + csum_offset + 2 - skb->data))
593                 goto out;
594
595         skb->ip_summed = CHECKSUM_PARTIAL;
596         skb->proto_csum_blank = 0;
597
598 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
599         skb->csum_start = csum_start;
600         skb->csum_offset = csum_offset;
601 #else
602         skb_set_transport_header(skb, csum_start - skb_headroom(skb));
603         skb->csum = csum_offset;
604 #endif
605
606         err = 0;
607
608 out:
609         return err;
610 }
611 #endif /* CONFIG_XEN && HAVE_PROTO_DATA_VALID */
612
613  /* Types of checksums that we can receive (these all refer to L4 checksums):
614  * 1. CHECKSUM_NONE: Device that did not compute checksum, contains full
615  *      (though not verified) checksum in packet but not in skb->csum.  Packets
616  *      from the bridge local port will also have this type.
617  * 2. CHECKSUM_COMPLETE (CHECKSUM_HW): Good device that computes checksums,
618  *      also the GRE module.  This is the same as CHECKSUM_NONE, except it has
619  *      a valid skb->csum.  Importantly, both contain a full checksum (not
620  *      verified) in the packet itself.  The only difference is that if the
621  *      packet gets to L4 processing on this machine (not in DomU) we won't
622  *      have to recompute the checksum to verify.  Most hardware devices do not
623  *      produce packets with this type, even if they support receive checksum
624  *      offloading (they produce type #5).
625  * 3. CHECKSUM_PARTIAL (CHECKSUM_HW): Packet without full checksum and needs to
626  *      be computed if it is sent off box.  Unfortunately on earlier kernels,
627  *      this case is impossible to distinguish from #2, despite having opposite
628  *      meanings.  Xen adds an extra field on earlier kernels (see #4) in order
629  *      to distinguish the different states.  The only real user of this type
630  *      with bridging is Xen (on later kernels).
631  * 4. CHECKSUM_UNNECESSARY (with proto_csum_blank true): This packet was
632  *      generated locally by a Xen DomU and has a partial checksum.  If it is
633  *      handled on this machine (Dom0 or DomU), then the checksum will not be
634  *      computed.  If it goes off box, the checksum in the packet needs to be
635  *      completed.  Calling skb_checksum_setup converts this to CHECKSUM_HW
636  *      (CHECKSUM_PARTIAL) so that the checksum can be completed.  In later
637  *      kernels, this combination is replaced with CHECKSUM_PARTIAL.
638  * 5. CHECKSUM_UNNECESSARY (with proto_csum_blank false): Packet with a correct
639  *      full checksum or using a protocol without a checksum.  skb->csum is
640  *      undefined.  This is common from devices with receive checksum
641  *      offloading.  This is somewhat similar to CHECKSUM_NONE, except that
642  *      nobody will try to verify the checksum with CHECKSUM_UNNECESSARY.
643  *
644  * Note that on earlier kernels, CHECKSUM_COMPLETE and CHECKSUM_PARTIAL are
645  * both defined as CHECKSUM_HW.  Normally the meaning of CHECKSUM_HW is clear
646  * based on whether it is on the transmit or receive path.  After the datapath
647  * it will be intepreted as CHECKSUM_PARTIAL.  If the packet already has a
648  * checksum, we will panic.  Since we can receive packets with checksums, we
649  * assume that all CHECKSUM_HW packets have checksums and map them to
650  * CHECKSUM_NONE, which has a similar meaning (the it is only different if the
651  * packet is processed by the local IP stack, in which case it will need to
652  * be reverified).  If we receive a packet with CHECKSUM_HW that really means
653  * CHECKSUM_PARTIAL, it will be sent with the wrong checksum.  However, there
654  * shouldn't be any devices that do this with bridging.
655  *
656  * The bridge has similar behavior and this function closely resembles
657  * skb_forward_csum().  It is slightly different because we are only concerned
658  * with bridging and not other types of forwarding and can get away with
659  * slightly more optimal behavior.*/
660 void
661 compute_ip_summed(struct sk_buff *skb, bool xmit)
662 {
663         /* For our convenience these defines change repeatedly between kernel
664          * versions, so we can't just copy them over... */
665         switch (skb->ip_summed) {
666         case CHECKSUM_NONE:
667                 OVS_CB(skb)->ip_summed = OVS_CSUM_NONE;
668                 break;
669         case CHECKSUM_UNNECESSARY:
670                 OVS_CB(skb)->ip_summed = OVS_CSUM_UNNECESSARY;
671                 break;
672 #ifdef CHECKSUM_HW
673         /* In theory this could be either CHECKSUM_PARTIAL or CHECKSUM_COMPLETE.
674          * However, we should only get CHECKSUM_PARTIAL packets from Xen, which
675          * uses some special fields to represent this (see below).  Since we
676          * can only make one type work, pick the one that actually happens in
677          * practice.
678          *
679          * The one exception to this is if we are on the transmit path
680          * (basically after skb_checksum_setup() has been run) the type has
681          * already been converted, so we should stay with that. */
682         case CHECKSUM_HW:
683                 if (!xmit)
684                         OVS_CB(skb)->ip_summed = OVS_CSUM_COMPLETE;
685                 else
686                         OVS_CB(skb)->ip_summed = OVS_CSUM_PARTIAL;
687
688                 break;
689 #else
690         case CHECKSUM_COMPLETE:
691                 OVS_CB(skb)->ip_summed = OVS_CSUM_COMPLETE;
692                 break;
693         case CHECKSUM_PARTIAL:
694                 OVS_CB(skb)->ip_summed = OVS_CSUM_PARTIAL;
695                 break;
696 #endif
697         default:
698                 printk(KERN_ERR "openvswitch: unknown checksum type %d\n",
699                        skb->ip_summed);
700                 /* None seems the safest... */
701                 OVS_CB(skb)->ip_summed = OVS_CSUM_NONE;
702         }       
703
704 #if defined(CONFIG_XEN) && defined(HAVE_PROTO_DATA_VALID)
705         /* Xen has a special way of representing CHECKSUM_PARTIAL on older
706          * kernels. It should not be set on the transmit path though. */
707         if (skb->proto_csum_blank)
708                 OVS_CB(skb)->ip_summed = OVS_CSUM_PARTIAL;
709
710         WARN_ON_ONCE(skb->proto_csum_blank && xmit);
711 #endif
712 }
713
714 void
715 forward_ip_summed(struct sk_buff *skb)
716 {
717 #ifdef CHECKSUM_HW
718         if (OVS_CB(skb)->ip_summed == OVS_CSUM_COMPLETE)
719                 skb->ip_summed = CHECKSUM_NONE;
720 #endif
721 }
722
723 /* Append each packet in 'skb' list to 'queue'.  There will be only one packet
724  * unless we broke up a GSO packet. */
725 static int
726 queue_control_packets(struct sk_buff *skb, struct sk_buff_head *queue,
727                       int queue_no, u32 arg)
728 {
729         struct sk_buff *nskb;
730         int port_no;
731         int err;
732
733         if (OVS_CB(skb)->dp_port)
734                 port_no = OVS_CB(skb)->dp_port->port_no;
735         else
736                 port_no = ODPP_LOCAL;
737
738         do {
739                 struct odp_msg *header;
740
741                 nskb = skb->next;
742                 skb->next = NULL;
743
744                 /* If a checksum-deferred packet is forwarded to the
745                  * controller, correct the pointers and checksum.  This happens
746                  * on a regular basis only on Xen, on which VMs can pass up
747                  * packets that do not have their checksum computed.
748                  */
749                 err = vswitch_skb_checksum_setup(skb);
750                 if (err)
751                         goto err_kfree_skbs;
752
753                 if (skb->ip_summed == CHECKSUM_PARTIAL) {
754
755 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
756                         /* Until 2.6.22, the start of the transport header was
757                          * also the start of data to be checksummed.  Linux
758                          * 2.6.22 introduced the csum_start field for this
759                          * purpose, but we should point the transport header to
760                          * it anyway for backward compatibility, as
761                          * dev_queue_xmit() does even in 2.6.28. */
762                         skb_set_transport_header(skb, skb->csum_start -
763                                                  skb_headroom(skb));
764 #endif
765
766                         err = skb_checksum_help(skb);
767                         if (err)
768                                 goto err_kfree_skbs;
769                 }
770
771                 err = skb_cow(skb, sizeof *header);
772                 if (err)
773                         goto err_kfree_skbs;
774
775                 header = (struct odp_msg*)__skb_push(skb, sizeof *header);
776                 header->type = queue_no;
777                 header->length = skb->len;
778                 header->port = port_no;
779                 header->reserved = 0;
780                 header->arg = arg;
781                 skb_queue_tail(queue, skb);
782
783                 skb = nskb;
784         } while (skb);
785         return 0;
786
787 err_kfree_skbs:
788         kfree_skb(skb);
789         while ((skb = nskb) != NULL) {
790                 nskb = skb->next;
791                 kfree_skb(skb);
792         }
793         return err;
794 }
795
796 int
797 dp_output_control(struct datapath *dp, struct sk_buff *skb, int queue_no,
798                   u32 arg)
799 {
800         struct dp_stats_percpu *stats;
801         struct sk_buff_head *queue;
802         int err;
803
804         WARN_ON_ONCE(skb_shared(skb));
805         BUG_ON(queue_no != _ODPL_MISS_NR && queue_no != _ODPL_ACTION_NR && queue_no != _ODPL_SFLOW_NR);
806         queue = &dp->queues[queue_no];
807         err = -ENOBUFS;
808         if (skb_queue_len(queue) >= DP_MAX_QUEUE_LEN)
809                 goto err_kfree_skb;
810
811         forward_ip_summed(skb);
812
813         /* Break apart GSO packets into their component pieces.  Otherwise
814          * userspace may try to stuff a 64kB packet into a 1500-byte MTU. */
815         if (skb_is_gso(skb)) {
816                 struct sk_buff *nskb = skb_gso_segment(skb, 0);
817                 if (nskb) {
818                         kfree_skb(skb);
819                         skb = nskb;
820                         if (unlikely(IS_ERR(skb))) {
821                                 err = PTR_ERR(skb);
822                                 goto err;
823                         }
824                 } else {
825                         /* XXX This case might not be possible.  It's hard to
826                          * tell from the skb_gso_segment() code and comment. */
827                 }
828         }
829
830         err = queue_control_packets(skb, queue, queue_no, arg);
831         wake_up_interruptible(&dp->waitqueue);
832         return err;
833
834 err_kfree_skb:
835         kfree_skb(skb);
836 err:
837         stats = percpu_ptr(dp->stats_percpu, get_cpu());
838         stats->n_lost++;
839         put_cpu();
840
841         return err;
842 }
843
844 static int flush_flows(struct datapath *dp)
845 {
846         struct tbl *old_table = rcu_dereference(dp->table);
847         struct tbl *new_table;
848
849         new_table = tbl_create(0);
850         if (!new_table)
851                 return -ENOMEM;
852
853         rcu_assign_pointer(dp->table, new_table);
854
855         tbl_deferred_destroy(old_table, flow_free_tbl);
856
857         return 0;
858 }
859
860 static int validate_actions(const struct sw_flow_actions *actions)
861 {
862         unsigned int i;
863
864         for (i = 0; i < actions->n_actions; i++) {
865                 const union odp_action *a = &actions->actions[i];
866                 switch (a->type) {
867                 case ODPAT_OUTPUT:
868                         if (a->output.port >= DP_MAX_PORTS)
869                                 return -EINVAL;
870                         break;
871
872                 case ODPAT_OUTPUT_GROUP:
873                         if (a->output_group.group >= DP_MAX_GROUPS)
874                                 return -EINVAL;
875                         break;
876
877                 case ODPAT_SET_VLAN_VID:
878                         if (a->vlan_vid.vlan_vid & htons(~VLAN_VID_MASK))
879                                 return -EINVAL;
880                         break;
881
882                 case ODPAT_SET_VLAN_PCP:
883                         if (a->vlan_pcp.vlan_pcp
884                             & ~(VLAN_PCP_MASK >> VLAN_PCP_SHIFT))
885                                 return -EINVAL;
886                         break;
887
888                 case ODPAT_SET_NW_TOS:
889                         if (a->nw_tos.nw_tos & INET_ECN_MASK)
890                                 return -EINVAL;
891                         break;
892
893                 default:
894                         if (a->type >= ODPAT_N_ACTIONS)
895                                 return -EOPNOTSUPP;
896                         break;
897                 }
898         }
899
900         return 0;
901 }
902
903 static struct sw_flow_actions *get_actions(const struct odp_flow *flow)
904 {
905         struct sw_flow_actions *actions;
906         int error;
907
908         actions = flow_actions_alloc(flow->n_actions);
909         error = PTR_ERR(actions);
910         if (IS_ERR(actions))
911                 goto error;
912
913         error = -EFAULT;
914         if (copy_from_user(actions->actions, flow->actions,
915                            flow->n_actions * sizeof(union odp_action)))
916                 goto error_free_actions;
917         error = validate_actions(actions);
918         if (error)
919                 goto error_free_actions;
920
921         return actions;
922
923 error_free_actions:
924         kfree(actions);
925 error:
926         return ERR_PTR(error);
927 }
928
929 static void get_stats(struct sw_flow *flow, struct odp_flow_stats *stats)
930 {
931         if (flow->used.tv_sec) {
932                 stats->used_sec = flow->used.tv_sec;
933                 stats->used_nsec = flow->used.tv_nsec;
934         } else {
935                 stats->used_sec = 0;
936                 stats->used_nsec = 0;
937         }
938         stats->n_packets = flow->packet_count;
939         stats->n_bytes = flow->byte_count;
940         stats->ip_tos = flow->ip_tos;
941         stats->tcp_flags = flow->tcp_flags;
942         stats->error = 0;
943 }
944
945 static void clear_stats(struct sw_flow *flow)
946 {
947         flow->used.tv_sec = flow->used.tv_nsec = 0;
948         flow->tcp_flags = 0;
949         flow->ip_tos = 0;
950         flow->packet_count = 0;
951         flow->byte_count = 0;
952 }
953
954 static int expand_table(struct datapath *dp)
955 {
956         struct tbl *old_table = rcu_dereference(dp->table);
957         struct tbl *new_table;
958
959         new_table = tbl_expand(old_table);
960         if (IS_ERR(new_table))
961                 return PTR_ERR(new_table);
962
963         rcu_assign_pointer(dp->table, new_table);
964         tbl_deferred_destroy(old_table, NULL);
965
966         return 0;
967 }
968
969 static int put_flow(struct datapath *dp, struct odp_flow_put __user *ufp)
970 {
971         struct odp_flow_put uf;
972         struct tbl_node *flow_node;
973         struct sw_flow *flow;
974         struct tbl *table;
975         struct odp_flow_stats stats;
976         int error;
977
978         error = -EFAULT;
979         if (copy_from_user(&uf, ufp, sizeof(struct odp_flow_put)))
980                 goto error;
981         memset(uf.flow.key.reserved, 0, sizeof uf.flow.key.reserved);
982
983         table = rcu_dereference(dp->table);
984         flow_node = tbl_lookup(table, &uf.flow.key, flow_hash(&uf.flow.key), flow_cmp);
985         if (!flow_node) {
986                 /* No such flow. */
987                 struct sw_flow_actions *acts;
988
989                 error = -ENOENT;
990                 if (!(uf.flags & ODPPF_CREATE))
991                         goto error;
992
993                 /* Expand table, if necessary, to make room. */
994                 if (tbl_count(table) >= tbl_n_buckets(table)) {
995                         error = expand_table(dp);
996                         if (error)
997                                 goto error;
998                         table = rcu_dereference(dp->table);
999                 }
1000
1001                 /* Allocate flow. */
1002                 error = -ENOMEM;
1003                 flow = kmem_cache_alloc(flow_cache, GFP_KERNEL);
1004                 if (flow == NULL)
1005                         goto error;
1006                 flow->key = uf.flow.key;
1007                 spin_lock_init(&flow->lock);
1008                 clear_stats(flow);
1009
1010                 /* Obtain actions. */
1011                 acts = get_actions(&uf.flow);
1012                 error = PTR_ERR(acts);
1013                 if (IS_ERR(acts))
1014                         goto error_free_flow;
1015                 rcu_assign_pointer(flow->sf_acts, acts);
1016
1017                 /* Put flow in bucket. */
1018                 error = tbl_insert(table, &flow->tbl_node, flow_hash(&flow->key));
1019                 if (error)
1020                         goto error_free_flow_acts;
1021
1022                 memset(&stats, 0, sizeof(struct odp_flow_stats));
1023         } else {
1024                 /* We found a matching flow. */
1025                 struct sw_flow_actions *old_acts, *new_acts;
1026                 unsigned long int flags;
1027
1028                 flow = flow_cast(flow_node);
1029
1030                 /* Bail out if we're not allowed to modify an existing flow. */
1031                 error = -EEXIST;
1032                 if (!(uf.flags & ODPPF_MODIFY))
1033                         goto error;
1034
1035                 /* Swap actions. */
1036                 new_acts = get_actions(&uf.flow);
1037                 error = PTR_ERR(new_acts);
1038                 if (IS_ERR(new_acts))
1039                         goto error;
1040                 old_acts = rcu_dereference(flow->sf_acts);
1041                 if (old_acts->n_actions != new_acts->n_actions ||
1042                     memcmp(old_acts->actions, new_acts->actions,
1043                            sizeof(union odp_action) * old_acts->n_actions)) {
1044                         rcu_assign_pointer(flow->sf_acts, new_acts);
1045                         flow_deferred_free_acts(old_acts);
1046                 } else {
1047                         kfree(new_acts);
1048                 }
1049
1050                 /* Fetch stats, then clear them if necessary. */
1051                 spin_lock_irqsave(&flow->lock, flags);
1052                 get_stats(flow, &stats);
1053                 if (uf.flags & ODPPF_ZERO_STATS)
1054                         clear_stats(flow);
1055                 spin_unlock_irqrestore(&flow->lock, flags);
1056         }
1057
1058         /* Copy stats to userspace. */
1059         if (__copy_to_user(&ufp->flow.stats, &stats,
1060                            sizeof(struct odp_flow_stats)))
1061                 return -EFAULT;
1062         return 0;
1063
1064 error_free_flow_acts:
1065         kfree(flow->sf_acts);
1066 error_free_flow:
1067         kmem_cache_free(flow_cache, flow);
1068 error:
1069         return error;
1070 }
1071
1072 static int put_actions(const struct sw_flow *flow, struct odp_flow __user *ufp)
1073 {
1074         union odp_action __user *actions;
1075         struct sw_flow_actions *sf_acts;
1076         u32 n_actions;
1077
1078         if (__get_user(actions, &ufp->actions) ||
1079             __get_user(n_actions, &ufp->n_actions))
1080                 return -EFAULT;
1081
1082         if (!n_actions)
1083                 return 0;
1084
1085         sf_acts = rcu_dereference(flow->sf_acts);
1086         if (__put_user(sf_acts->n_actions, &ufp->n_actions) ||
1087             (actions && copy_to_user(actions, sf_acts->actions,
1088                                      sizeof(union odp_action) *
1089                                      min(sf_acts->n_actions, n_actions))))
1090                 return -EFAULT;
1091
1092         return 0;
1093 }
1094
1095 static int answer_query(struct sw_flow *flow, u32 query_flags,
1096                         struct odp_flow __user *ufp)
1097 {
1098         struct odp_flow_stats stats;
1099         unsigned long int flags;
1100
1101         spin_lock_irqsave(&flow->lock, flags);
1102         get_stats(flow, &stats);
1103
1104         if (query_flags & ODPFF_ZERO_TCP_FLAGS) {
1105                 flow->tcp_flags = 0;
1106         }
1107         spin_unlock_irqrestore(&flow->lock, flags);
1108
1109         if (__copy_to_user(&ufp->stats, &stats, sizeof(struct odp_flow_stats)))
1110                 return -EFAULT;
1111         return put_actions(flow, ufp);
1112 }
1113
1114 static int del_flow(struct datapath *dp, struct odp_flow __user *ufp)
1115 {
1116         struct tbl *table = rcu_dereference(dp->table);
1117         struct odp_flow uf;
1118         struct tbl_node *flow_node;
1119         struct sw_flow *flow;
1120         int error;
1121
1122         error = -EFAULT;
1123         if (copy_from_user(&uf, ufp, sizeof uf))
1124                 goto error;
1125         memset(uf.key.reserved, 0, sizeof uf.key.reserved);
1126
1127         flow_node = tbl_lookup(table, &uf.key, flow_hash(&uf.key), flow_cmp);
1128         error = -ENOENT;
1129         if (!flow_node)
1130                 goto error;
1131
1132         error = tbl_remove(table, flow_node);
1133         if (error)
1134                 goto error;
1135
1136         /* XXX These statistics might lose a few packets, since other CPUs can
1137          * be using this flow.  We used to synchronize_rcu() to make sure that
1138          * we get completely accurate stats, but that blows our performance,
1139          * badly. */
1140
1141         flow = flow_cast(flow_node);
1142         error = answer_query(flow, 0, ufp);
1143         flow_deferred_free(flow);
1144
1145 error:
1146         return error;
1147 }
1148
1149 static int query_flows(struct datapath *dp, const struct odp_flowvec *flowvec)
1150 {
1151         struct tbl *table = rcu_dereference(dp->table);
1152         int i;
1153         for (i = 0; i < flowvec->n_flows; i++) {
1154                 struct __user odp_flow *ufp = &flowvec->flows[i];
1155                 struct odp_flow uf;
1156                 struct tbl_node *flow_node;
1157                 int error;
1158
1159                 if (__copy_from_user(&uf, ufp, sizeof uf))
1160                         return -EFAULT;
1161                 memset(uf.key.reserved, 0, sizeof uf.key.reserved);
1162
1163                 flow_node = tbl_lookup(table, &uf.key, flow_hash(&uf.key), flow_cmp);
1164                 if (!flow_node)
1165                         error = __put_user(ENOENT, &ufp->stats.error);
1166                 else
1167                         error = answer_query(flow_cast(flow_node), uf.flags, ufp);
1168                 if (error)
1169                         return -EFAULT;
1170         }
1171         return flowvec->n_flows;
1172 }
1173
1174 struct list_flows_cbdata {
1175         struct odp_flow __user *uflows;
1176         int n_flows;
1177         int listed_flows;
1178 };
1179
1180 static int list_flow(struct tbl_node *node, void *cbdata_)
1181 {
1182         struct sw_flow *flow = flow_cast(node);
1183         struct list_flows_cbdata *cbdata = cbdata_;
1184         struct odp_flow __user *ufp = &cbdata->uflows[cbdata->listed_flows++];
1185         int error;
1186
1187         if (__copy_to_user(&ufp->key, &flow->key, sizeof flow->key))
1188                 return -EFAULT;
1189         error = answer_query(flow, 0, ufp);
1190         if (error)
1191                 return error;
1192
1193         if (cbdata->listed_flows >= cbdata->n_flows)
1194                 return cbdata->listed_flows;
1195         return 0;
1196 }
1197
1198 static int list_flows(struct datapath *dp, const struct odp_flowvec *flowvec)
1199 {
1200         struct list_flows_cbdata cbdata;
1201         int error;
1202
1203         if (!flowvec->n_flows)
1204                 return 0;
1205
1206         cbdata.uflows = flowvec->flows;
1207         cbdata.n_flows = flowvec->n_flows;
1208         cbdata.listed_flows = 0;
1209         error = tbl_foreach(rcu_dereference(dp->table), list_flow, &cbdata);
1210         return error ? error : cbdata.listed_flows;
1211 }
1212
1213 static int do_flowvec_ioctl(struct datapath *dp, unsigned long argp,
1214                             int (*function)(struct datapath *,
1215                                             const struct odp_flowvec *))
1216 {
1217         struct odp_flowvec __user *uflowvec;
1218         struct odp_flowvec flowvec;
1219         int retval;
1220
1221         uflowvec = (struct odp_flowvec __user *)argp;
1222         if (!access_ok(VERIFY_WRITE, uflowvec, sizeof *uflowvec) ||
1223             copy_from_user(&flowvec, uflowvec, sizeof flowvec))
1224                 return -EFAULT;
1225
1226         if (flowvec.n_flows > INT_MAX / sizeof(struct odp_flow))
1227                 return -EINVAL;
1228
1229         if (!access_ok(VERIFY_WRITE, flowvec.flows,
1230                        flowvec.n_flows * sizeof(struct odp_flow)))
1231                 return -EFAULT;
1232
1233         retval = function(dp, &flowvec);
1234         return (retval < 0 ? retval
1235                 : retval == flowvec.n_flows ? 0
1236                 : __put_user(retval, &uflowvec->n_flows));
1237 }
1238
1239 static int do_execute(struct datapath *dp, const struct odp_execute *executep)
1240 {
1241         struct odp_execute execute;
1242         struct odp_flow_key key;
1243         struct sk_buff *skb;
1244         struct sw_flow_actions *actions;
1245         struct ethhdr *eth;
1246         int err;
1247
1248         err = -EFAULT;
1249         if (copy_from_user(&execute, executep, sizeof execute))
1250                 goto error;
1251
1252         err = -EINVAL;
1253         if (execute.length < ETH_HLEN || execute.length > 65535)
1254                 goto error;
1255
1256         err = -ENOMEM;
1257         actions = flow_actions_alloc(execute.n_actions);
1258         if (!actions)
1259                 goto error;
1260
1261         err = -EFAULT;
1262         if (copy_from_user(actions->actions, execute.actions,
1263                            execute.n_actions * sizeof *execute.actions))
1264                 goto error_free_actions;
1265
1266         err = validate_actions(actions);
1267         if (err)
1268                 goto error_free_actions;
1269
1270         err = -ENOMEM;
1271         skb = alloc_skb(execute.length, GFP_KERNEL);
1272         if (!skb)
1273                 goto error_free_actions;
1274
1275         if (execute.in_port < DP_MAX_PORTS)
1276                 OVS_CB(skb)->dp_port = dp->ports[execute.in_port];
1277         else
1278                 OVS_CB(skb)->dp_port = NULL;
1279
1280         err = -EFAULT;
1281         if (copy_from_user(skb_put(skb, execute.length), execute.data,
1282                            execute.length))
1283                 goto error_free_skb;
1284
1285         skb_reset_mac_header(skb);
1286         eth = eth_hdr(skb);
1287
1288         /* Normally, setting the skb 'protocol' field would be handled by a
1289          * call to eth_type_trans(), but it assumes there's a sending
1290          * device, which we may not have. */
1291         if (ntohs(eth->h_proto) >= 1536)
1292                 skb->protocol = eth->h_proto;
1293         else
1294                 skb->protocol = htons(ETH_P_802_2);
1295
1296         flow_extract(skb, execute.in_port, &key);
1297         err = execute_actions(dp, skb, &key, actions->actions,
1298                               actions->n_actions, GFP_KERNEL);
1299         kfree(actions);
1300         return err;
1301
1302 error_free_skb:
1303         kfree_skb(skb);
1304 error_free_actions:
1305         kfree(actions);
1306 error:
1307         return err;
1308 }
1309
1310 static int get_dp_stats(struct datapath *dp, struct odp_stats __user *statsp)
1311 {
1312         struct tbl *table = rcu_dereference(dp->table);
1313         struct odp_stats stats;
1314         int i;
1315
1316         stats.n_flows = tbl_count(table);
1317         stats.cur_capacity = tbl_n_buckets(table);
1318         stats.max_capacity = TBL_MAX_BUCKETS;
1319         stats.n_ports = dp->n_ports;
1320         stats.max_ports = DP_MAX_PORTS;
1321         stats.max_groups = DP_MAX_GROUPS;
1322         stats.n_frags = stats.n_hit = stats.n_missed = stats.n_lost = 0;
1323         for_each_possible_cpu(i) {
1324                 const struct dp_stats_percpu *s;
1325                 s = percpu_ptr(dp->stats_percpu, i);
1326                 stats.n_frags += s->n_frags;
1327                 stats.n_hit += s->n_hit;
1328                 stats.n_missed += s->n_missed;
1329                 stats.n_lost += s->n_lost;
1330         }
1331         stats.max_miss_queue = DP_MAX_QUEUE_LEN;
1332         stats.max_action_queue = DP_MAX_QUEUE_LEN;
1333         return copy_to_user(statsp, &stats, sizeof stats) ? -EFAULT : 0;
1334 }
1335
1336 /* MTU of the dp pseudo-device: ETH_DATA_LEN or the minimum of the ports */
1337 int dp_min_mtu(const struct datapath *dp)
1338 {
1339         struct dp_port *p;
1340         int mtu = 0;
1341
1342         ASSERT_RTNL();
1343
1344         list_for_each_entry_rcu (p, &dp->port_list, node) {
1345                 int dev_mtu;
1346
1347                 /* Skip any internal ports, since that's what we're trying to
1348                  * set. */
1349                 if (is_internal_vport(p->vport))
1350                         continue;
1351
1352                 dev_mtu = vport_get_mtu(p->vport);
1353                 if (!mtu || dev_mtu < mtu)
1354                         mtu = dev_mtu;
1355         }
1356
1357         return mtu ? mtu : ETH_DATA_LEN;
1358 }
1359
1360 /* Sets the MTU of all datapath devices to the minimum of the ports.  Must
1361  * be called with RTNL lock and dp_mutex. */
1362 void set_internal_devs_mtu(const struct datapath *dp)
1363 {
1364         struct dp_port *p;
1365         int mtu;
1366
1367         ASSERT_RTNL();
1368
1369         mtu = dp_min_mtu(dp);
1370
1371         list_for_each_entry_rcu (p, &dp->port_list, node) {
1372                 if (is_internal_vport(p->vport))
1373                         vport_set_mtu(p->vport, mtu);
1374         }
1375 }
1376
1377 static int
1378 put_port(const struct dp_port *p, struct odp_port __user *uop)
1379 {
1380         struct odp_port op;
1381
1382         memset(&op, 0, sizeof op);
1383
1384         rcu_read_lock();
1385         strncpy(op.devname, vport_get_name(p->vport), sizeof op.devname);
1386         rcu_read_unlock();
1387
1388         op.port = p->port_no;
1389         op.flags = is_internal_vport(p->vport) ? ODP_PORT_INTERNAL : 0;
1390
1391         return copy_to_user(uop, &op, sizeof op) ? -EFAULT : 0;
1392 }
1393
1394 static int
1395 query_port(struct datapath *dp, struct odp_port __user *uport)
1396 {
1397         struct odp_port port;
1398
1399         if (copy_from_user(&port, uport, sizeof port))
1400                 return -EFAULT;
1401
1402         if (port.devname[0]) {
1403                 struct vport *vport;
1404                 struct dp_port *dp_port;
1405                 int err = 0;
1406
1407                 port.devname[IFNAMSIZ - 1] = '\0';
1408
1409                 vport_lock();
1410                 rcu_read_lock();
1411
1412                 vport = vport_locate(port.devname);
1413                 if (!vport) {
1414                         err = -ENODEV;
1415                         goto error_unlock;
1416                 }
1417
1418                 dp_port = vport_get_dp_port(vport);
1419                 if (!dp_port || dp_port->dp != dp) {
1420                         err = -ENOENT;
1421                         goto error_unlock;
1422                 }
1423
1424                 port.port = dp_port->port_no;
1425
1426 error_unlock:
1427                 rcu_read_unlock();
1428                 vport_unlock();
1429
1430                 if (err)
1431                         return err;
1432         } else {
1433                 if (port.port >= DP_MAX_PORTS)
1434                         return -EINVAL;
1435                 if (!dp->ports[port.port])
1436                         return -ENOENT;
1437         }
1438
1439         return put_port(dp->ports[port.port], uport);
1440 }
1441
1442 static int
1443 list_ports(struct datapath *dp, struct odp_portvec __user *pvp)
1444 {
1445         struct odp_portvec pv;
1446         struct dp_port *p;
1447         int idx;
1448
1449         if (copy_from_user(&pv, pvp, sizeof pv))
1450                 return -EFAULT;
1451
1452         idx = 0;
1453         if (pv.n_ports) {
1454                 list_for_each_entry_rcu (p, &dp->port_list, node) {
1455                         if (put_port(p, &pv.ports[idx]))
1456                                 return -EFAULT;
1457                         if (idx++ >= pv.n_ports)
1458                                 break;
1459                 }
1460         }
1461         return put_user(dp->n_ports, &pvp->n_ports);
1462 }
1463
1464 /* RCU callback for freeing a dp_port_group */
1465 static void free_port_group(struct rcu_head *rcu)
1466 {
1467         struct dp_port_group *g = container_of(rcu, struct dp_port_group, rcu);
1468         kfree(g);
1469 }
1470
1471 static int
1472 set_port_group(struct datapath *dp, const struct odp_port_group __user *upg)
1473 {
1474         struct odp_port_group pg;
1475         struct dp_port_group *new_group, *old_group;
1476         int error;
1477
1478         error = -EFAULT;
1479         if (copy_from_user(&pg, upg, sizeof pg))
1480                 goto error;
1481
1482         error = -EINVAL;
1483         if (pg.n_ports > DP_MAX_PORTS || pg.group >= DP_MAX_GROUPS)
1484                 goto error;
1485
1486         error = -ENOMEM;
1487         new_group = kmalloc(sizeof *new_group + sizeof(u16) * pg.n_ports,
1488                             GFP_KERNEL);
1489         if (!new_group)
1490                 goto error;
1491
1492         new_group->n_ports = pg.n_ports;
1493         error = -EFAULT;
1494         if (copy_from_user(new_group->ports, pg.ports,
1495                            sizeof(u16) * pg.n_ports))
1496                 goto error_free;
1497
1498         old_group = rcu_dereference(dp->groups[pg.group]);
1499         rcu_assign_pointer(dp->groups[pg.group], new_group);
1500         if (old_group)
1501                 call_rcu(&old_group->rcu, free_port_group);
1502         return 0;
1503
1504 error_free:
1505         kfree(new_group);
1506 error:
1507         return error;
1508 }
1509
1510 static int
1511 get_port_group(struct datapath *dp, struct odp_port_group *upg)
1512 {
1513         struct odp_port_group pg;
1514         struct dp_port_group *g;
1515         u16 n_copy;
1516
1517         if (copy_from_user(&pg, upg, sizeof pg))
1518                 return -EFAULT;
1519
1520         if (pg.group >= DP_MAX_GROUPS)
1521                 return -EINVAL;
1522
1523         g = dp->groups[pg.group];
1524         n_copy = g ? min_t(int, g->n_ports, pg.n_ports) : 0;
1525         if (n_copy && copy_to_user(pg.ports, g->ports, n_copy * sizeof(u16)))
1526                 return -EFAULT;
1527
1528         if (put_user(g ? g->n_ports : 0, &upg->n_ports))
1529                 return -EFAULT;
1530
1531         return 0;
1532 }
1533
1534 static int get_listen_mask(const struct file *f)
1535 {
1536         return (long)f->private_data;
1537 }
1538
1539 static void set_listen_mask(struct file *f, int listen_mask)
1540 {
1541         f->private_data = (void*)(long)listen_mask;
1542 }
1543
1544 static long openvswitch_ioctl(struct file *f, unsigned int cmd,
1545                            unsigned long argp)
1546 {
1547         int dp_idx = iminor(f->f_dentry->d_inode);
1548         struct datapath *dp;
1549         int drop_frags, listeners, port_no;
1550         unsigned int sflow_probability;
1551         int err;
1552
1553         /* Handle commands with special locking requirements up front. */
1554         switch (cmd) {
1555         case ODP_DP_CREATE:
1556                 err = create_dp(dp_idx, (char __user *)argp);
1557                 goto exit;
1558
1559         case ODP_DP_DESTROY:
1560                 err = destroy_dp(dp_idx);
1561                 goto exit;
1562
1563         case ODP_PORT_ATTACH:
1564                 err = attach_port(dp_idx, (struct odp_port __user *)argp);
1565                 goto exit;
1566
1567         case ODP_PORT_DETACH:
1568                 err = get_user(port_no, (int __user *)argp);
1569                 if (!err)
1570                         err = detach_port(dp_idx, port_no);
1571                 goto exit;
1572
1573         case ODP_VPORT_ADD:
1574                 err = vport_add((struct odp_vport_add __user *)argp);
1575                 goto exit;
1576
1577         case ODP_VPORT_MOD:
1578                 err = vport_mod((struct odp_vport_mod __user *)argp);
1579                 goto exit;
1580
1581         case ODP_VPORT_DEL:
1582                 err = vport_del((char __user *)argp);
1583                 goto exit;
1584
1585         case ODP_VPORT_STATS_GET:
1586                 err = vport_stats_get((struct odp_vport_stats_req __user *)argp);
1587                 goto exit;
1588
1589         case ODP_VPORT_ETHER_GET:
1590                 err = vport_ether_get((struct odp_vport_ether __user *)argp);
1591                 goto exit;
1592
1593         case ODP_VPORT_ETHER_SET:
1594                 err = vport_ether_set((struct odp_vport_ether __user *)argp);
1595                 goto exit;
1596
1597         case ODP_VPORT_MTU_GET:
1598                 err = vport_mtu_get((struct odp_vport_mtu __user *)argp);
1599                 goto exit;
1600
1601         case ODP_VPORT_MTU_SET:
1602                 err = vport_mtu_set((struct odp_vport_mtu __user *)argp);
1603                 goto exit;
1604         }
1605
1606         dp = get_dp_locked(dp_idx);
1607         err = -ENODEV;
1608         if (!dp)
1609                 goto exit;
1610
1611         switch (cmd) {
1612         case ODP_DP_STATS:
1613                 err = get_dp_stats(dp, (struct odp_stats __user *)argp);
1614                 break;
1615
1616         case ODP_GET_DROP_FRAGS:
1617                 err = put_user(dp->drop_frags, (int __user *)argp);
1618                 break;
1619
1620         case ODP_SET_DROP_FRAGS:
1621                 err = get_user(drop_frags, (int __user *)argp);
1622                 if (err)
1623                         break;
1624                 err = -EINVAL;
1625                 if (drop_frags != 0 && drop_frags != 1)
1626                         break;
1627                 dp->drop_frags = drop_frags;
1628                 err = 0;
1629                 break;
1630
1631         case ODP_GET_LISTEN_MASK:
1632                 err = put_user(get_listen_mask(f), (int __user *)argp);
1633                 break;
1634
1635         case ODP_SET_LISTEN_MASK:
1636                 err = get_user(listeners, (int __user *)argp);
1637                 if (err)
1638                         break;
1639                 err = -EINVAL;
1640                 if (listeners & ~ODPL_ALL)
1641                         break;
1642                 err = 0;
1643                 set_listen_mask(f, listeners);
1644                 break;
1645
1646         case ODP_GET_SFLOW_PROBABILITY:
1647                 err = put_user(dp->sflow_probability, (unsigned int __user *)argp);
1648                 break;
1649
1650         case ODP_SET_SFLOW_PROBABILITY:
1651                 err = get_user(sflow_probability, (unsigned int __user *)argp);
1652                 if (!err)
1653                         dp->sflow_probability = sflow_probability;
1654                 break;
1655
1656         case ODP_PORT_QUERY:
1657                 err = query_port(dp, (struct odp_port __user *)argp);
1658                 break;
1659
1660         case ODP_PORT_LIST:
1661                 err = list_ports(dp, (struct odp_portvec __user *)argp);
1662                 break;
1663
1664         case ODP_PORT_GROUP_SET:
1665                 err = set_port_group(dp, (struct odp_port_group __user *)argp);
1666                 break;
1667
1668         case ODP_PORT_GROUP_GET:
1669                 err = get_port_group(dp, (struct odp_port_group __user *)argp);
1670                 break;
1671
1672         case ODP_FLOW_FLUSH:
1673                 err = flush_flows(dp);
1674                 break;
1675
1676         case ODP_FLOW_PUT:
1677                 err = put_flow(dp, (struct odp_flow_put __user *)argp);
1678                 break;
1679
1680         case ODP_FLOW_DEL:
1681                 err = del_flow(dp, (struct odp_flow __user *)argp);
1682                 break;
1683
1684         case ODP_FLOW_GET:
1685                 err = do_flowvec_ioctl(dp, argp, query_flows);
1686                 break;
1687
1688         case ODP_FLOW_LIST:
1689                 err = do_flowvec_ioctl(dp, argp, list_flows);
1690                 break;
1691
1692         case ODP_EXECUTE:
1693                 err = do_execute(dp, (struct odp_execute __user *)argp);
1694                 break;
1695
1696         default:
1697                 err = -ENOIOCTLCMD;
1698                 break;
1699         }
1700         mutex_unlock(&dp->mutex);
1701 exit:
1702         return err;
1703 }
1704
1705 static int dp_has_packet_of_interest(struct datapath *dp, int listeners)
1706 {
1707         int i;
1708         for (i = 0; i < DP_N_QUEUES; i++) {
1709                 if (listeners & (1 << i) && !skb_queue_empty(&dp->queues[i]))
1710                         return 1;
1711         }
1712         return 0;
1713 }
1714
1715 ssize_t openvswitch_read(struct file *f, char __user *buf, size_t nbytes,
1716                       loff_t *ppos)
1717 {
1718         /* XXX is there sufficient synchronization here? */
1719         int listeners = get_listen_mask(f);
1720         int dp_idx = iminor(f->f_dentry->d_inode);
1721         struct datapath *dp = get_dp(dp_idx);
1722         struct sk_buff *skb;
1723         struct iovec __user iov;
1724         size_t copy_bytes;
1725         int retval;
1726
1727         if (!dp)
1728                 return -ENODEV;
1729
1730         if (nbytes == 0 || !listeners)
1731                 return 0;
1732
1733         for (;;) {
1734                 int i;
1735
1736                 for (i = 0; i < DP_N_QUEUES; i++) {
1737                         if (listeners & (1 << i)) {
1738                                 skb = skb_dequeue(&dp->queues[i]);
1739                                 if (skb)
1740                                         goto success;
1741                         }
1742                 }
1743
1744                 if (f->f_flags & O_NONBLOCK) {
1745                         retval = -EAGAIN;
1746                         goto error;
1747                 }
1748
1749                 wait_event_interruptible(dp->waitqueue,
1750                                          dp_has_packet_of_interest(dp,
1751                                                                    listeners));
1752
1753                 if (signal_pending(current)) {
1754                         retval = -ERESTARTSYS;
1755                         goto error;
1756                 }
1757         }
1758 success:
1759         copy_bytes = min_t(size_t, skb->len, nbytes);
1760         iov.iov_base = buf;
1761         iov.iov_len = copy_bytes;
1762         retval = skb_copy_datagram_iovec(skb, 0, &iov, iov.iov_len);
1763         if (!retval)
1764                 retval = copy_bytes;
1765         kfree_skb(skb);
1766
1767 error:
1768         return retval;
1769 }
1770
1771 static unsigned int openvswitch_poll(struct file *file, poll_table *wait)
1772 {
1773         /* XXX is there sufficient synchronization here? */
1774         int dp_idx = iminor(file->f_dentry->d_inode);
1775         struct datapath *dp = get_dp(dp_idx);
1776         unsigned int mask;
1777
1778         if (dp) {
1779                 mask = 0;
1780                 poll_wait(file, &dp->waitqueue, wait);
1781                 if (dp_has_packet_of_interest(dp, get_listen_mask(file)))
1782                         mask |= POLLIN | POLLRDNORM;
1783         } else {
1784                 mask = POLLIN | POLLRDNORM | POLLHUP;
1785         }
1786         return mask;
1787 }
1788
1789 struct file_operations openvswitch_fops = {
1790         /* XXX .aio_read = openvswitch_aio_read, */
1791         .read  = openvswitch_read,
1792         .poll  = openvswitch_poll,
1793         .unlocked_ioctl = openvswitch_ioctl,
1794         /* XXX .fasync = openvswitch_fasync, */
1795 };
1796
1797 static int major;
1798
1799 static int __init dp_init(void)
1800 {
1801         struct sk_buff *dummy_skb;
1802         int err;
1803
1804         BUILD_BUG_ON(sizeof(struct ovs_skb_cb) > sizeof(dummy_skb->cb));
1805
1806         printk("Open vSwitch %s, built "__DATE__" "__TIME__"\n", VERSION BUILDNR);
1807
1808         err = flow_init();
1809         if (err)
1810                 goto error;
1811
1812         err = vport_init();
1813         if (err)
1814                 goto error_flow_exit;
1815
1816         err = register_netdevice_notifier(&dp_device_notifier);
1817         if (err)
1818                 goto error_vport_exit;
1819
1820         major = register_chrdev(0, "openvswitch", &openvswitch_fops);
1821         if (err < 0)
1822                 goto error_unreg_notifier;
1823
1824         return 0;
1825
1826 error_unreg_notifier:
1827         unregister_netdevice_notifier(&dp_device_notifier);
1828 error_vport_exit:
1829         vport_exit();
1830 error_flow_exit:
1831         flow_exit();
1832 error:
1833         return err;
1834 }
1835
1836 static void dp_cleanup(void)
1837 {
1838         rcu_barrier();
1839         unregister_chrdev(major, "openvswitch");
1840         unregister_netdevice_notifier(&dp_device_notifier);
1841         vport_exit();
1842         flow_exit();
1843 }
1844
1845 module_init(dp_init);
1846 module_exit(dp_cleanup);
1847
1848 MODULE_DESCRIPTION("Open vSwitch switching datapath");
1849 MODULE_LICENSE("GPL");