Initial import
[sliver-openvswitch.git] / datapath / forward.c
1 /*
2  * Distributed under the terms of the GNU GPL version 2.
3  * Copyright (c) 2007 The Board of Trustees of The Leland Stanford Junior Univer
4 sity
5  */
6
7 #include <linux/if_ether.h>
8 #include <linux/if_vlan.h>
9 #include <linux/in.h>
10 #include <linux/ip.h>
11 #include <linux/tcp.h>
12 #include <linux/udp.h>
13 #include <linux/in6.h>
14 #include <asm/uaccess.h>
15 #include <linux/types.h>
16 #include <net/checksum.h>
17 #include "forward.h"
18 #include "datapath.h"
19 #include "chain.h"
20 #include "flow.h"
21
22 /* FIXME: do we need to use GFP_ATOMIC everywhere here? */
23
24 static void execute_actions(struct datapath *, struct sk_buff *,
25                                 const struct sw_flow_key *,
26                                 const struct ofp_action *, int n_actions);
27 static int make_writable(struct sk_buff **);
28
29 static struct sk_buff *retrieve_skb(uint32_t id);
30 static void discard_skb(uint32_t id);
31
32 /* 'skb' was received on 'in_port', a physical switch port between 0 and
33  * OFPP_MAX.  Process it according to 'chain'. */
34 void fwd_port_input(struct sw_chain *chain, struct sk_buff *skb, int in_port)
35 {
36         struct sw_flow_key key;
37         struct sw_flow *flow;
38
39         flow_extract(skb, in_port, &key);
40         flow = chain_lookup(chain, &key);
41         if (likely(flow != NULL)) {
42                 flow_used(flow, skb);
43                 execute_actions(chain->dp, skb, &key,
44                                 flow->actions, flow->n_actions);
45         } else {
46                 dp_output_control(chain->dp, skb, fwd_save_skb(skb), 
47                                 chain->dp->miss_send_len, OFPR_NO_MATCH);
48         }
49 }
50
51 static int do_output(struct datapath *dp, struct sk_buff *skb, size_t max_len,
52                         int out_port)
53 {
54         if (!skb)
55                 return -ENOMEM;
56         return (likely(out_port != OFPP_CONTROLLER)
57                 ? dp_output_port(dp, skb, out_port)
58                 : dp_output_control(dp, skb, fwd_save_skb(skb),
59                                          max_len, OFPR_ACTION));
60 }
61
62 static void execute_actions(struct datapath *dp, struct sk_buff *skb,
63                                 const struct sw_flow_key *key,
64                                 const struct ofp_action *actions, int n_actions)
65 {
66         /* Every output action needs a separate clone of 'skb', but the common
67          * case is just a single output action, so that doing a clone and
68          * then freeing the original skbuff is wasteful.  So the following code
69          * is slightly obscure just to avoid that. */
70         int prev_port;
71         size_t max_len=0;        /* Initialze to make compiler happy */
72         uint16_t eth_proto;
73         int i;
74
75         prev_port = -1;
76         eth_proto = ntohs(key->dl_type);
77
78         for (i = 0; i < n_actions; i++) {
79                 const struct ofp_action *a = &actions[i];
80
81                 if (prev_port != -1) {
82                         do_output(dp, skb_clone(skb, GFP_ATOMIC),
83                                   max_len, prev_port);
84                         prev_port = -1;
85                 }
86
87                 if (likely(a->type == ntohs(OFPAT_OUTPUT))) {
88                         prev_port = ntohs(a->arg.output.port);
89                         max_len = ntohs(a->arg.output.max_len);
90                 } else {
91                         if (!make_writable(&skb)) {
92                                 printk("make_writable failed\n");
93                                 break;
94                         }
95                         skb = execute_setter(skb, eth_proto, key, a);
96                 }
97         }
98         if (prev_port != -1)
99                 do_output(dp, skb, max_len, prev_port);
100         else
101                 kfree_skb(skb);
102 }
103
104 /* Updates 'sum', which is a field in 'skb''s data, given that a 4-byte field
105  * covered by the sum has been changed from 'from' to 'to'.  If set,
106  * 'pseudohdr' indicates that the field is in the TCP or UDP pseudo-header.
107  * Based on nf_proto_csum_replace4. */
108 static void update_csum(__sum16 *sum, struct sk_buff *skb,
109                         __be32 from, __be32 to, int pseudohdr)
110 {
111         __be32 diff[] = { ~from, to };
112         if (skb->ip_summed != CHECKSUM_PARTIAL) {
113                 *sum = csum_fold(csum_partial((char *)diff, sizeof(diff),
114                                 ~csum_unfold(*sum)));
115                 if (skb->ip_summed == CHECKSUM_COMPLETE && pseudohdr)
116                         skb->csum = ~csum_partial((char *)diff, sizeof(diff),
117                                                 ~skb->csum);
118         } else if (pseudohdr)
119                 *sum = ~csum_fold(csum_partial((char *)diff, sizeof(diff),
120                                 csum_unfold(*sum)));
121 }
122
123 static void modify_nh(struct sk_buff *skb, uint16_t eth_proto,
124                         uint8_t nw_proto, const struct ofp_action *a)
125 {
126         if (eth_proto == ETH_P_IP) {
127                 struct iphdr *nh = ip_hdr(skb);
128                 uint32_t new, *field;
129
130                 new = a->arg.nw_addr;
131
132                 if (a->type == OFPAT_SET_NW_SRC)
133                         field = &nh->saddr;
134                 else
135                         field = &nh->daddr;
136
137                 if (nw_proto == IPPROTO_TCP) {
138                         struct tcphdr *th = tcp_hdr(skb);
139                         update_csum(&th->check, skb, *field, new, 1);
140                 } else if (nw_proto == IPPROTO_UDP) {
141                         struct udphdr *th = udp_hdr(skb);
142                         update_csum(&th->check, skb, *field, new, 1);
143                 }
144                 update_csum(&nh->check, skb, *field, new, 0);
145                 *field = new;
146         }
147 }
148
149 static void modify_th(struct sk_buff *skb, uint16_t eth_proto,
150                         uint8_t nw_proto, const struct ofp_action *a)
151 {
152         if (eth_proto == ETH_P_IP) {
153                 uint16_t new, *field;
154
155                 new = a->arg.tp;
156
157                 if (nw_proto == IPPROTO_TCP) {
158                         struct tcphdr *th = tcp_hdr(skb);
159
160                         if (a->type == OFPAT_SET_TP_SRC)
161                                 field = &th->source;
162                         else
163                                 field = &th->dest;
164
165                         update_csum(&th->check, skb, *field, new, 1);
166                         *field = new;
167                 } else if (nw_proto == IPPROTO_UDP) {
168                         struct udphdr *th = udp_hdr(skb);
169
170                         if (a->type == OFPAT_SET_TP_SRC)
171                                 field = &th->source;
172                         else
173                                 field = &th->dest;
174
175                         update_csum(&th->check, skb, *field, new, 1);
176                         *field = new;
177                 }
178         }
179 }
180
181 static struct sk_buff *vlan_pull_tag(struct sk_buff *skb)
182 {
183         struct vlan_ethhdr *vh = vlan_eth_hdr(skb);
184         struct ethhdr *eh;
185
186
187         /* Verify we were given a vlan packet */
188         if (vh->h_vlan_proto != __constant_htons(ETH_P_8021Q))
189                 return skb;
190
191         memmove(skb->data + VLAN_HLEN, skb->data, 2 * VLAN_ETH_ALEN);
192
193         eh = (struct ethhdr *)skb_pull(skb, VLAN_HLEN);
194
195         skb->protocol = eh->h_proto;
196         skb->mac_header += VLAN_HLEN;
197
198         return skb;
199 }
200
201 static struct sk_buff *modify_vlan(struct sk_buff *skb, 
202                 const struct sw_flow_key *key, const struct ofp_action *a)
203 {
204         uint16_t new_id = a->arg.vlan_id;
205
206         if (new_id != OFP_VLAN_NONE) {
207                 if (key->dl_vlan != __constant_htons(OFP_VLAN_NONE)) {
208                         /* Modify vlan id, but maintain other TCI values */
209                         struct vlan_ethhdr *vh = vlan_eth_hdr(skb);
210                         vh->h_vlan_TCI = (vh->h_vlan_TCI 
211                                         & ~(__constant_htons(VLAN_VID_MASK))) | htons(new_id);
212                 } else  {
213                         /* Add vlan header */
214                         skb = vlan_put_tag(skb, new_id);
215                 }
216         } else  {
217                 /* Remove an existing vlan header if it exists */
218                 vlan_pull_tag(skb);
219         }
220
221         return skb;
222 }
223
224 struct sk_buff *execute_setter(struct sk_buff *skb, uint16_t eth_proto,
225                         const struct sw_flow_key *key, const struct ofp_action *a)
226 {
227         switch (a->type) {
228         case OFPAT_SET_DL_VLAN:
229                 skb = modify_vlan(skb, key, a);
230                 break;
231
232         case OFPAT_SET_DL_SRC: {
233                 struct ethhdr *eh = eth_hdr(skb);
234                 memcpy(eh->h_source, a->arg.dl_addr, sizeof eh->h_source);
235                 break;
236         }
237         case OFPAT_SET_DL_DST: {
238                 struct ethhdr *eh = eth_hdr(skb);
239                 memcpy(eh->h_dest, a->arg.dl_addr, sizeof eh->h_dest);
240                 break;
241         }
242
243         case OFPAT_SET_NW_SRC:
244         case OFPAT_SET_NW_DST:
245                 modify_nh(skb, eth_proto, key->nw_proto, a);
246                 break;
247
248         case OFPAT_SET_TP_SRC:
249         case OFPAT_SET_TP_DST:
250                 modify_th(skb, eth_proto, key->nw_proto, a);
251                 break;
252         
253         default:
254                 BUG();
255         }
256
257         return skb;
258 }
259
260 static int
261 recv_control_hello(struct sw_chain *chain, const void *msg)
262 {
263         const struct ofp_control_hello *och = msg;
264
265         printk("control_hello(version=%d)\n", ntohl(och->version));
266
267         if (ntohs(och->miss_send_len) != OFP_MISS_SEND_LEN_UNCHANGED) {
268                 chain->dp->miss_send_len = ntohs(och->miss_send_len);
269         }
270
271         chain->dp->hello_flags = ntohs(och->flags);
272
273         dp_send_hello(chain->dp);
274
275         return 0;
276 }
277
278 static int
279 recv_packet_out(struct sw_chain *chain, const void *msg)
280 {
281         const struct ofp_packet_out *opo = msg;
282         struct sk_buff *skb;
283         struct vlan_ethhdr *mac;
284         int nh_ofs;
285
286         if (ntohl(opo->buffer_id) == (uint32_t) -1) {
287                 int data_len = ntohs(opo->header.length) - sizeof *opo;
288
289                 /* FIXME: there is likely a way to reuse the data in msg. */
290                 skb = alloc_skb(data_len, GFP_ATOMIC);
291                 if (!skb)
292                         return -ENOMEM;
293
294                 /* FIXME?  We don't reserve NET_IP_ALIGN or NET_SKB_PAD since
295                  * we're just transmitting this raw without examining anything
296                  * at those layers. */
297                 memcpy(skb_put(skb, data_len), opo->u.data, data_len);
298                 dp_set_origin(chain->dp, ntohs(opo->in_port), skb);
299
300                 skb_set_mac_header(skb, 0);
301                 mac = vlan_eth_hdr(skb);
302                 if (likely(mac->h_vlan_proto != htons(ETH_P_8021Q)))
303                         nh_ofs = sizeof(struct ethhdr);
304                 else
305                         nh_ofs = sizeof(struct vlan_ethhdr);
306                 skb_set_network_header(skb, nh_ofs);
307
308                 dp_output_port(chain->dp, skb, ntohs(opo->out_port));
309         } else {
310                 struct sw_flow_key key;
311                 int n_acts;
312
313                 skb = retrieve_skb(ntohl(opo->buffer_id));
314                 if (!skb)
315                         return -ESRCH;
316                 dp_set_origin(chain->dp, ntohs(opo->in_port), skb);
317
318                 n_acts = (ntohs(opo->header.length) - sizeof *opo) 
319                                 / sizeof *opo->u.actions;
320                 flow_extract(skb, ntohs(opo->in_port), &key);
321                 execute_actions(chain->dp, skb, &key, opo->u.actions, n_acts);
322         }
323         return 0;
324 }
325
326 static int
327 recv_port_mod(struct sw_chain *chain, const void *msg)
328 {
329         const struct ofp_port_mod *opm = msg;
330
331         dp_update_port_flags(chain->dp, &opm->desc);
332
333         return 0;
334 }
335
336 static int
337 add_flow(struct sw_chain *chain, const struct ofp_flow_mod *ofm)
338 {
339         int error = -ENOMEM;
340         int n_acts;
341         struct sw_flow *flow;
342
343
344         /* Check number of actions. */
345         n_acts = (ntohs(ofm->header.length) - sizeof *ofm) / sizeof *ofm->actions;
346         if (n_acts > MAX_ACTIONS) {
347                 error = -E2BIG;
348                 goto error;
349         }
350
351         /* Allocate memory. */
352         flow = flow_alloc(n_acts, GFP_ATOMIC);
353         if (flow == NULL)
354                 goto error;
355
356         /* Fill out flow. */
357         flow_extract_match(&flow->key, &ofm->match);
358         flow->group_id = ntohl(ofm->group_id);
359         flow->max_idle = ntohs(ofm->max_idle);
360         flow->timeout = jiffies + flow->max_idle * HZ;
361         flow->n_actions = n_acts;
362         flow->init_time = jiffies;
363         flow->byte_count = 0;
364         flow->packet_count = 0;
365         atomic_set(&flow->deleted, 0);
366         spin_lock_init(&flow->lock);
367         memcpy(flow->actions, ofm->actions, n_acts * sizeof *flow->actions);
368
369         /* Act. */
370         error = chain_insert(chain, flow);
371         if (error)
372                 goto error_free_flow;
373         error = 0;
374         if (ntohl(ofm->buffer_id) != (uint32_t) -1) {
375                 struct sk_buff *skb = retrieve_skb(ntohl(ofm->buffer_id));
376                 if (skb) {
377                         struct sw_flow_key key;
378                         flow_used(flow, skb);
379                         flow_extract(skb, ntohs(ofm->match.in_port), &key);
380                         execute_actions(chain->dp, skb, &key,
381                                         ofm->actions, n_acts);
382                 }
383                 else
384                         error = -ESRCH;
385         }
386         return error;
387
388 error_free_flow:
389         flow_free(flow);
390 error:
391         if (ntohl(ofm->buffer_id) != (uint32_t) -1)
392                 discard_skb(ntohl(ofm->buffer_id));
393         return error;
394 }
395
396 static int
397 recv_flow(struct sw_chain *chain, const void *msg)
398 {
399         const struct ofp_flow_mod *ofm = msg;
400         uint16_t command = ntohs(ofm->command);
401
402         if (command == OFPFC_ADD) {
403                 return add_flow(chain, ofm);
404         }  else if (command == OFPFC_DELETE) {
405                 struct sw_flow_key key;
406                 flow_extract_match(&key, &ofm->match);
407                 return chain_delete(chain, &key, 0) ? 0 : -ESRCH;
408         } else if (command == OFPFC_DELETE_STRICT) {
409                 struct sw_flow_key key;
410                 flow_extract_match(&key, &ofm->match);
411                 return chain_delete(chain, &key, 1) ? 0 : -ESRCH;
412         } else {
413                 return -ENOTSUPP;
414         }
415 }
416
417 /* 'msg', which is 'length' bytes long, was received from the control path.
418  * Apply it to 'chain'. */
419 int
420 fwd_control_input(struct sw_chain *chain, const void *msg, size_t length)
421 {
422
423         struct openflow_packet {
424                 size_t min_size;
425                 int (*handler)(struct sw_chain *, const void *);
426         };
427
428         static const struct openflow_packet packets[] = {
429                 [OFPT_CONTROL_HELLO] = {
430                         sizeof (struct ofp_control_hello),
431                         recv_control_hello,
432                 },
433                 [OFPT_PACKET_OUT] = {
434                         sizeof (struct ofp_packet_out),
435                         recv_packet_out,
436                 },
437                 [OFPT_FLOW_MOD] = {
438                         sizeof (struct ofp_flow_mod),
439                         recv_flow,
440                 },
441                 [OFPT_PORT_MOD] = {
442                         sizeof (struct ofp_port_mod),
443                         recv_port_mod,
444                 },
445         };
446
447         const struct openflow_packet *pkt;
448         struct ofp_header *oh;
449
450         if (length < sizeof(struct ofp_header))
451                 return -EINVAL;
452
453         oh = (struct ofp_header *) msg;
454         if (oh->version != 1 || oh->type >= ARRAY_SIZE(packets)
455                 || ntohs(oh->length) > length)
456                 return -EINVAL;
457
458         pkt = &packets[oh->type];
459         if (!pkt->handler)
460                 return -ENOSYS;
461         if (length < pkt->min_size)
462                 return -EFAULT;
463
464         return pkt->handler(chain, msg);
465 }
466
467 /* Packet buffering. */
468
469 #define OVERWRITE_SECS  1
470 #define OVERWRITE_JIFFIES (OVERWRITE_SECS * HZ)
471
472 struct packet_buffer {
473         struct sk_buff *skb;
474         uint32_t cookie;
475         unsigned long exp_jiffies;
476 };
477
478 static struct packet_buffer buffers[N_PKT_BUFFERS];
479 static unsigned int buffer_idx;
480 static DEFINE_SPINLOCK(buffer_lock);
481
482 uint32_t fwd_save_skb(struct sk_buff *skb)
483 {
484         struct packet_buffer *p;
485         unsigned long int flags;
486         uint32_t id;
487
488         spin_lock_irqsave(&buffer_lock, flags);
489         buffer_idx = (buffer_idx + 1) & PKT_BUFFER_MASK;
490         p = &buffers[buffer_idx];
491         if (p->skb) {
492                 /* Don't buffer packet if existing entry is less than
493                  * OVERWRITE_SECS old. */
494                 if (time_before(jiffies, p->exp_jiffies)) {
495                         spin_unlock_irqrestore(&buffer_lock, flags);
496                         return -1;
497                 } else 
498                         kfree_skb(p->skb);
499         }
500         /* Don't use maximum cookie value since the all-bits-1 id is
501          * special. */
502         if (++p->cookie >= (1u << PKT_COOKIE_BITS) - 1)
503                 p->cookie = 0;
504         skb_get(skb);
505         p->skb = skb;
506         p->exp_jiffies = jiffies + OVERWRITE_JIFFIES;
507         id = buffer_idx | (p->cookie << PKT_BUFFER_BITS);
508         spin_unlock_irqrestore(&buffer_lock, flags);
509
510         return id;
511 }
512
513 static struct sk_buff *retrieve_skb(uint32_t id)
514 {
515         unsigned long int flags;
516         struct sk_buff *skb = NULL;
517         struct packet_buffer *p;
518
519         spin_lock_irqsave(&buffer_lock, flags);
520         p = &buffers[id & PKT_BUFFER_MASK];
521         if (p->cookie == id >> PKT_BUFFER_BITS) {
522                 skb = p->skb;
523                 p->skb = NULL;
524         } else {
525                 printk("cookie mismatch: %x != %x\n",
526                                 id >> PKT_BUFFER_BITS, p->cookie);
527         }
528         spin_unlock_irqrestore(&buffer_lock, flags);
529
530         return skb;
531 }
532
533 static void discard_skb(uint32_t id)
534 {
535         unsigned long int flags;
536         struct packet_buffer *p;
537
538         spin_lock_irqsave(&buffer_lock, flags);
539         p = &buffers[id & PKT_BUFFER_MASK];
540         if (p->cookie == id >> PKT_BUFFER_BITS) {
541                 kfree_skb(p->skb);
542                 p->skb = NULL;
543         }
544         spin_unlock_irqrestore(&buffer_lock, flags);
545 }
546
547 void fwd_exit(void)
548 {
549         int i;
550
551         for (i = 0; i < N_PKT_BUFFERS; i++)
552                 kfree_skb(buffers[i].skb);
553 }
554
555 /* Utility functions. */
556
557 /* Makes '*pskb' writable, possibly copying it and setting '*pskb' to point to
558  * the copy.
559  * Returns 1 if successful, 0 on failure. */
560 static int
561 make_writable(struct sk_buff **pskb)
562 {
563         /* Based on skb_make_writable() in net/netfilter/core.c. */
564         struct sk_buff *nskb;
565
566         /* Not exclusive use of packet?  Must copy. */
567         if (skb_shared(*pskb) || skb_cloned(*pskb))
568                 goto copy_skb;
569
570         return pskb_may_pull(*pskb, 64); /* FIXME? */
571
572 copy_skb:
573         nskb = skb_copy(*pskb, GFP_ATOMIC);
574         if (!nskb)
575                 return 0;
576         BUG_ON(skb_is_nonlinear(nskb));
577
578         /* Rest of kernel will get very unhappy if we pass it a
579            suddenly-orphaned skbuff */
580         if ((*pskb)->sk)
581                 skb_set_owner_w(nskb, (*pskb)->sk);
582         kfree_skb(*pskb);
583         *pskb = nskb;
584         return 1;
585 }