694a65e81eb78b64da0d490278774a7d8ab05c4d
[openvswitch] / switch / forward.c
1 /* Copyright (C) 2008 Board of Trustees, Leland Stanford Jr. University.
2  *
3  * Permission is hereby granted, free of charge, to any person obtaining a copy
4  * of this software and associated documentation files (the "Software"), to
5  * deal in the Software without restriction, including without limitation the
6  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7  * sell copies of the Software, and to permit persons to whom the Software is
8  * furnished to do so, subject to the following conditions:
9  *
10  * The above copyright notice and this permission notice shall be included in
11  * all copies or substantial portions of the Software.
12  *
13  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
19  * IN THE SOFTWARE.
20  */
21
22 #include "forward.h"
23 #include <arpa/inet.h>
24 #include <assert.h>
25 #include <errno.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include "datapath.h"
29 #include "chain.h"
30 #include "flow.h"
31 #include "packets.h"
32
33 static void execute_actions(struct datapath *, struct buffer *,
34                             int in_port, const struct sw_flow_key *,
35                             const struct ofp_action *, int n_actions);
36
37 static struct buffer *retrieve_buffer(uint32_t id);
38 static void discard_buffer(uint32_t id);
39
40 /* 'buffer' was received on 'in_port', a physical switch port between 0 and
41  * OFPP_MAX.  Process it according to 'chain'. */
42 void fwd_port_input(struct datapath *dp, struct buffer *buffer, int in_port)
43 {
44     struct sw_flow_key key;
45     struct sw_flow *flow;
46
47     key.wildcards = 0;
48     flow_extract(buffer, in_port, &key.flow);
49     flow = chain_lookup(dp->chain, &key);
50     if (flow != NULL) {
51         flow_used(flow, buffer);
52         execute_actions(dp, buffer, in_port, &key,
53                         flow->actions, flow->n_actions);
54     } else {
55         dp_output_control(dp, buffer, in_port, fwd_save_buffer(buffer),
56                           dp->miss_send_len, OFPR_NO_MATCH);
57     }
58 }
59
60 static void
61 do_output(struct datapath *dp, struct buffer *buffer, int in_port,
62           size_t max_len, int out_port)
63 {
64     if (out_port != OFPP_CONTROLLER) {
65         dp_output_port(dp, buffer, in_port, out_port);
66     } else {
67         dp_output_control(dp, buffer, in_port, fwd_save_buffer(buffer),
68                           max_len, OFPR_ACTION);
69     }
70 }
71
72 static void execute_actions(struct datapath *dp, struct buffer *buffer,
73                             int in_port, const struct sw_flow_key *key,
74                             const struct ofp_action *actions, int n_actions)
75 {
76     /* Every output action needs a separate clone of 'buffer', but the common
77      * case is just a single output action, so that doing a clone and then
78      * freeing the original buffer is wasteful.  So the following code is
79      * slightly obscure just to avoid that. */
80     int prev_port;
81     size_t max_len=0;        /* Initialze to make compiler happy */
82     uint16_t eth_proto;
83     int i;
84
85     prev_port = -1;
86     eth_proto = ntohs(key->flow.dl_type);
87
88     for (i = 0; i < n_actions; i++) {
89         const struct ofp_action *a = &actions[i];
90
91         if (prev_port != -1) {
92             do_output(dp, buffer_clone(buffer), in_port, max_len, prev_port);
93             prev_port = -1;
94         }
95
96         if (a->type == ntohs(OFPAT_OUTPUT)) {
97             prev_port = ntohs(a->arg.output.port);
98             max_len = ntohs(a->arg.output.max_len);
99         } else {
100             buffer = execute_setter(buffer, eth_proto, key, a);
101         }
102     }
103     if (prev_port != -1)
104         do_output(dp, buffer, in_port, max_len, prev_port);
105     else
106         buffer_delete(buffer);
107 }
108
109 /* Returns the new checksum for a packet in which the checksum field previously
110  * contained 'old_csum' and in which a field that contained 'old_u16' was
111  * changed to contain 'new_u16'. */
112 static uint16_t
113 recalc_csum16(uint16_t old_csum, uint16_t old_u16, uint16_t new_u16)
114 {
115     /* Ones-complement arithmetic is endian-independent, so this code does not
116      * use htons() or ntohs().
117      *
118      * See RFC 1624 for formula and explanation. */
119     uint16_t hc_complement = ~old_csum;
120     uint16_t m_complement = ~old_u16;
121     uint16_t m_prime = new_u16;
122     uint32_t sum = hc_complement + m_complement + m_prime;
123     uint16_t hc_prime_complement = sum + (sum >> 16);
124     return ~hc_prime_complement;
125 }
126
127 /* Returns the new checksum for a packet in which the checksum field previously
128  * contained 'old_csum' and in which a field that contained 'old_u32' was
129  * changed to contain 'new_u32'. */
130 static uint16_t
131 recalc_csum32(uint16_t old_csum, uint32_t old_u32, uint32_t new_u32)
132 {
133     return recalc_csum16(recalc_csum16(old_csum, old_u32, new_u32),
134                          old_u32 >> 16, new_u32 >> 16);
135 }
136
137 static void modify_nh(struct buffer *buffer, uint16_t eth_proto,
138                       uint8_t nw_proto, const struct ofp_action *a)
139 {
140     if (eth_proto == ETH_TYPE_IP) {
141         struct ip_header *nh = buffer->l3;
142         uint32_t new, *field;
143
144         new = a->arg.nw_addr;
145         field = a->type == OFPAT_SET_NW_SRC ? &nh->ip_src : &nh->ip_dst;
146         if (nw_proto == IP_TYPE_TCP) {
147             struct tcp_header *th = buffer->l4;
148             th->tcp_csum = recalc_csum32(th->tcp_csum, *field, new);
149         } else if (nw_proto == IP_TYPE_UDP) {
150             struct udp_header *th = buffer->l4;
151             if (th->udp_csum) {
152                 th->udp_csum = recalc_csum32(th->udp_csum, *field, new);
153                 if (!th->udp_csum) {
154                     th->udp_csum = 0xffff;
155                 }
156             }
157         }
158         nh->ip_csum = recalc_csum32(nh->ip_csum, *field, new);
159         *field = new;
160     }
161 }
162
163 static void modify_th(struct buffer *buffer, uint16_t eth_proto,
164                       uint8_t nw_proto, const struct ofp_action *a)
165 {
166     if (eth_proto == ETH_TYPE_IP) {
167         uint16_t new, *field;
168
169         new = a->arg.tp;
170
171         if (nw_proto == IP_TYPE_TCP) {
172             struct tcp_header *th = buffer->l4;
173             field = a->type == OFPAT_SET_TP_SRC ? &th->tcp_src : &th->tcp_dst;
174             th->tcp_csum = recalc_csum16(th->tcp_csum, *field, new);
175             *field = new;
176         } else if (nw_proto == IP_TYPE_UDP) {
177             struct udp_header *th = buffer->l4;
178             field = a->type == OFPAT_SET_TP_SRC ? &th->udp_src : &th->udp_dst;
179             th->udp_csum = recalc_csum16(th->udp_csum, *field, new);
180             *field = new;
181         }
182     }
183 }
184
185 static struct buffer *
186 modify_vlan(struct buffer *buffer,
187             const struct sw_flow_key *key, const struct ofp_action *a)
188 {
189     uint16_t new_id = a->arg.vlan_id;
190     struct vlan_eth_header *veh;
191
192     if (new_id != OFP_VLAN_NONE) {
193         if (key->flow.dl_vlan != htons(OFP_VLAN_NONE)) {
194             /* Modify vlan id, but maintain other TCI values */
195             veh = buffer->l2;
196             veh->veth_tci &= ~htons(VLAN_VID);
197             veh->veth_tci |= htons(new_id);
198         } else {
199             /* Insert new vlan id. */
200             struct eth_header *eh = buffer->l2;
201             struct vlan_eth_header tmp;
202             memcpy(tmp.veth_dst, eh->eth_dst, ETH_ADDR_LEN);
203             memcpy(tmp.veth_src, eh->eth_src, ETH_ADDR_LEN);
204             tmp.veth_type = htons(ETH_TYPE_VLAN);
205             tmp.veth_tci = new_id;
206             tmp.veth_next_type = eh->eth_type;
207             
208             veh = buffer_push_uninit(buffer, VLAN_HEADER_LEN);
209             memcpy(veh, &tmp, sizeof tmp);
210             buffer->l2 -= VLAN_HEADER_LEN;
211         }
212     } else  {
213         /* Remove an existing vlan header if it exists */
214         veh = buffer->l2;
215         if (veh->veth_type == htons(ETH_TYPE_VLAN)) {
216             struct eth_header tmp;
217             
218             memcpy(tmp.eth_dst, veh->veth_dst, ETH_ADDR_LEN);
219             memcpy(tmp.eth_src, veh->veth_src, ETH_ADDR_LEN);
220             tmp.eth_type = veh->veth_next_type;
221             
222             buffer->size -= VLAN_HEADER_LEN;
223             buffer->data += VLAN_HEADER_LEN;
224             buffer->l2 += VLAN_HEADER_LEN;
225             memcpy(buffer->data, &tmp, sizeof tmp);
226         }
227     }
228
229     return buffer;
230 }
231
232 struct buffer *execute_setter(struct buffer *buffer, uint16_t eth_proto,
233                               const struct sw_flow_key *key, const struct ofp_action *a)
234 {
235     switch (a->type) {
236     case OFPAT_SET_DL_VLAN:
237         buffer = modify_vlan(buffer, key, a);
238         break;
239
240     case OFPAT_SET_DL_SRC: {
241         struct eth_header *eh = buffer->l2;
242         memcpy(eh->eth_src, a->arg.dl_addr, sizeof eh->eth_src);
243         break;
244     }
245     case OFPAT_SET_DL_DST: {
246         struct eth_header *eh = buffer->l2;
247         memcpy(eh->eth_dst, a->arg.dl_addr, sizeof eh->eth_dst);
248         break;
249     }
250
251     case OFPAT_SET_NW_SRC:
252     case OFPAT_SET_NW_DST:
253         modify_nh(buffer, eth_proto, key->flow.nw_proto, a);
254         break;
255
256     case OFPAT_SET_TP_SRC:
257     case OFPAT_SET_TP_DST:
258         modify_th(buffer, eth_proto, key->flow.nw_proto, a);
259         break;
260         
261     default:
262         NOT_REACHED();
263     }
264
265     return buffer;
266 }
267
268 static int
269 recv_control_hello(struct datapath *dp, const void *msg)
270 {
271     const struct ofp_control_hello *och = msg;
272
273     printf("control_hello(version=%d)\n", ntohl(och->version));
274
275     if (ntohs(och->miss_send_len) != OFP_MISS_SEND_LEN_UNCHANGED) {
276         dp->miss_send_len = ntohs(och->miss_send_len);
277     }
278
279     dp->hello_flags = ntohs(och->flags);
280
281     dp_send_hello(dp);
282
283     return 0;
284 }
285
286 static int
287 recv_packet_out(struct datapath *dp, const void *msg)
288 {
289     const struct ofp_packet_out *opo = msg;
290
291     if (ntohl(opo->buffer_id) == (uint32_t) -1) {
292         /* FIXME: can we avoid copying data here? */
293         int data_len = ntohs(opo->header.length) - sizeof *opo;
294         struct buffer *buffer = buffer_new(data_len);
295         buffer_put(buffer, opo->u.data, data_len);
296         dp_output_port(dp, buffer,
297                        ntohs(opo->in_port), ntohs(opo->out_port));
298     } else {
299         struct sw_flow_key key;
300         struct buffer *buffer;
301         int n_acts;
302
303         buffer = retrieve_buffer(ntohl(opo->buffer_id));
304         if (!buffer) {
305             return -ESRCH; 
306         }
307
308         n_acts = (ntohs(opo->header.length) - sizeof *opo) 
309             / sizeof *opo->u.actions;
310         flow_extract(buffer, ntohs(opo->in_port), &key.flow);
311         execute_actions(dp, buffer, ntohs(opo->in_port),
312                         &key, opo->u.actions, n_acts);
313     }
314     return 0;
315 }
316
317 static int
318 recv_port_mod(struct datapath *dp, const void *msg)
319 {
320     const struct ofp_port_mod *opm = msg;
321
322     dp_update_port_flags(dp, &opm->desc);
323
324     return 0;
325 }
326
327 static int
328 add_flow(struct datapath *dp, const struct ofp_flow_mod *ofm)
329 {
330     int error = -ENOMEM;
331     int n_acts;
332     struct sw_flow *flow;
333
334
335     /* Check number of actions. */
336     n_acts = (ntohs(ofm->header.length) - sizeof *ofm) / sizeof *ofm->actions;
337     if (n_acts > MAX_ACTIONS) {
338         error = -E2BIG;
339         goto error;
340     }
341
342     /* Allocate memory. */
343     flow = flow_alloc(n_acts);
344     if (flow == NULL)
345         goto error;
346
347     /* Fill out flow. */
348     flow_extract_match(&flow->key, &ofm->match);
349     flow->group_id = ntohl(ofm->group_id);
350     flow->max_idle = ntohs(ofm->max_idle);
351     flow->timeout = time(0) + flow->max_idle; /* FIXME */
352     flow->n_actions = n_acts;
353     flow->created = time(0);    /* FIXME */
354     flow->byte_count = 0;
355     flow->packet_count = 0;
356     memcpy(flow->actions, ofm->actions, n_acts * sizeof *flow->actions);
357
358     /* Act. */
359     error = chain_insert(dp->chain, flow);
360     if (error) {
361         goto error_free_flow; 
362     }
363     error = 0;
364     if (ntohl(ofm->buffer_id) != UINT32_MAX) {
365         struct buffer *buffer = retrieve_buffer(ntohl(ofm->buffer_id));
366         if (buffer) {
367             struct sw_flow_key key;
368             uint16_t in_port = ntohs(ofm->match.in_port);
369             flow_used(flow, buffer);
370             flow_extract(buffer, in_port, &key.flow);
371             execute_actions(dp, buffer, in_port,
372                             &key, ofm->actions, n_acts);
373         } else {
374             error = -ESRCH; 
375         }
376     }
377     return error;
378
379 error_free_flow:
380     flow_free(flow);
381 error:
382     if (ntohl(ofm->buffer_id) != (uint32_t) -1)
383         discard_buffer(ntohl(ofm->buffer_id));
384     return error;
385 }
386
387 static int
388 recv_flow(struct datapath *dp, const void *msg)
389 {
390     const struct ofp_flow_mod *ofm = msg;
391     uint16_t command = ntohs(ofm->command);
392
393     if (command == OFPFC_ADD) {
394         return add_flow(dp, ofm);
395     }  else if (command == OFPFC_DELETE) {
396         struct sw_flow_key key;
397         flow_extract_match(&key, &ofm->match);
398         return chain_delete(dp->chain, &key, 0) ? 0 : -ESRCH;
399     } else if (command == OFPFC_DELETE_STRICT) {
400         struct sw_flow_key key;
401         flow_extract_match(&key, &ofm->match);
402         return chain_delete(dp->chain, &key, 1) ? 0 : -ESRCH;
403     } else {
404         return -ENODEV;
405     }
406 }
407
408 /* 'msg', which is 'length' bytes long, was received from the control path.
409  * Apply it to 'chain'. */
410 int
411 fwd_control_input(struct datapath *dp, const void *msg, size_t length)
412 {
413
414     struct openflow_packet {
415         size_t min_size;
416         int (*handler)(struct datapath *, const void *);
417     };
418
419     static const struct openflow_packet packets[] = {
420         [OFPT_CONTROL_HELLO] = {
421             sizeof (struct ofp_control_hello),
422             recv_control_hello,
423         },
424         [OFPT_PACKET_OUT] = {
425             sizeof (struct ofp_packet_out),
426             recv_packet_out,
427         },
428         [OFPT_FLOW_MOD] = {
429             sizeof (struct ofp_flow_mod),
430             recv_flow,
431         },
432         [OFPT_PORT_MOD] = {
433             sizeof (struct ofp_port_mod),
434             recv_port_mod,
435         },
436     };
437
438     const struct openflow_packet *pkt;
439     struct ofp_header *oh;
440
441     if (length < sizeof(struct ofp_header))
442         return -EINVAL;
443
444     oh = (struct ofp_header *) msg;
445     if (oh->version != 1 || oh->type >= ARRAY_SIZE(packets)
446         || ntohs(oh->length) > length)
447         return -EINVAL;
448
449     pkt = &packets[oh->type];
450     if (!pkt->handler)
451         return -ENOSYS;
452     if (length < pkt->min_size)
453         return -EFAULT;
454
455     return pkt->handler(dp, msg);
456 }
457
458 /* Packet buffering. */
459
460 #define OVERWRITE_SECS  1
461
462 struct packet_buffer {
463     struct buffer *buffer;
464     uint32_t cookie;
465     time_t timeout;
466 };
467
468 static struct packet_buffer buffers[N_PKT_BUFFERS];
469 static unsigned int buffer_idx;
470
471 uint32_t fwd_save_buffer(struct buffer *buffer)
472 {
473     struct packet_buffer *p;
474     uint32_t id;
475
476     buffer_idx = (buffer_idx + 1) & PKT_BUFFER_MASK;
477     p = &buffers[buffer_idx];
478     if (p->buffer) {
479         /* Don't buffer packet if existing entry is less than
480          * OVERWRITE_SECS old. */
481         if (time(0) < p->timeout) { /* FIXME */
482             return -1;
483         } else {
484             buffer_delete(p->buffer); 
485         }
486     }
487     /* Don't use maximum cookie value since the all-bits-1 id is
488      * special. */
489     if (++p->cookie >= (1u << PKT_COOKIE_BITS) - 1)
490         p->cookie = 0;
491     p->buffer = buffer_clone(buffer);      /* FIXME */
492     p->timeout = time(0) + OVERWRITE_SECS; /* FIXME */
493     id = buffer_idx | (p->cookie << PKT_BUFFER_BITS);
494
495     return id;
496 }
497
498 static struct buffer *retrieve_buffer(uint32_t id)
499 {
500     struct buffer *buffer = NULL;
501     struct packet_buffer *p;
502
503     p = &buffers[id & PKT_BUFFER_MASK];
504     if (p->cookie == id >> PKT_BUFFER_BITS) {
505         buffer = p->buffer;
506         p->buffer = NULL;
507     } else {
508         printf("cookie mismatch: %x != %x\n",
509                id >> PKT_BUFFER_BITS, p->cookie);
510     }
511
512     return buffer;
513 }
514
515 static void discard_buffer(uint32_t id)
516 {
517     struct packet_buffer *p;
518
519     p = &buffers[id & PKT_BUFFER_MASK];
520     if (p->cookie == id >> PKT_BUFFER_BITS) {
521         buffer_delete(p->buffer);
522         p->buffer = NULL;
523     }
524 }
525
526 void fwd_exit(void)
527 {
528     int i;
529
530     for (i = 0; i < N_PKT_BUFFERS; i++)
531         buffer_delete(buffers[i].buffer);
532 }