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