Break data_hello and control_hello messages into multiple messages.
[sliver-openvswitch.git] / switch / datapath.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 "datapath.h"
35 #include <arpa/inet.h>
36 #include <assert.h>
37 #include <errno.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include "buffer.h"
41 #include "chain.h"
42 #include "flow.h"
43 #include "netdev.h"
44 #include "packets.h"
45 #include "poll-loop.h"
46 #include "rconn.h"
47 #include "table.h"
48 #include "xtoxll.h"
49
50 #define THIS_MODULE VLM_datapath
51 #include "vlog.h"
52
53 #define BRIDGE_PORT_NO_FLOOD    0x00000001
54
55 /* Capabilities supported by this implementation. */
56 #define OFP_SUPPORTED_CAPABILITIES (OFPC_MULTI_PHY_TX)
57
58 /* Actions supported by this implementation. */
59 #define OFP_SUPPORTED_ACTIONS ( (1 << OFPAT_OUTPUT)         \
60                                 | (1 << OFPAT_SET_DL_VLAN)  \
61                                 | (1 << OFPAT_SET_DL_SRC)   \
62                                 | (1 << OFPAT_SET_DL_DST)   \
63                                 | (1 << OFPAT_SET_NW_SRC)   \
64                                 | (1 << OFPAT_SET_NW_DST)   \
65                                 | (1 << OFPAT_SET_TP_SRC)   \
66                                 | (1 << OFPAT_SET_TP_DST) )
67
68 struct sw_port {
69     uint32_t flags;
70     struct datapath *dp;
71     struct netdev *netdev;
72     struct list node; /* Element in datapath.ports. */
73 };
74
75 struct datapath {
76     struct rconn *rconn;
77
78     time_t last_timeout;
79
80     /* Unique identifier for this datapath */
81     uint64_t  id;
82
83     struct sw_chain *chain;  /* Forwarding rules. */
84
85     struct ofp_switch_config config;
86
87     /* Switch ports. */
88     struct sw_port ports[OFPP_MAX];
89     struct list port_list; /* List of ports, for flooding. */
90 };
91
92 void dp_output_port(struct datapath *, struct buffer *,
93                     int in_port, int out_port);
94 void dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp);
95 void dp_output_control(struct datapath *, struct buffer *, int in_port,
96                        size_t max_len, int reason);
97 static void send_flow_expired(struct datapath *, struct sw_flow *);
98 static void send_port_status(struct sw_port *p, uint8_t status);
99 static void del_switch_port(struct sw_port *p);
100 static void execute_actions(struct datapath *, struct buffer *,
101                             int in_port, const struct sw_flow_key *,
102                             const struct ofp_action *, int n_actions);
103 static void modify_vlan(struct buffer *buffer, const struct sw_flow_key *key,
104                         const struct ofp_action *a);
105 static void modify_nh(struct buffer *buffer, uint16_t eth_proto,
106                       uint8_t nw_proto, const struct ofp_action *a);
107 static void modify_th(struct buffer *buffer, uint16_t eth_proto,
108                           uint8_t nw_proto, const struct ofp_action *a);
109
110 /* Buffers are identified to userspace by a 31-bit opaque ID.  We divide the ID
111  * into a buffer number (low bits) and a cookie (high bits).  The buffer number
112  * is an index into an array of buffers.  The cookie distinguishes between
113  * different packets that have occupied a single buffer.  Thus, the more
114  * buffers we have, the lower-quality the cookie... */
115 #define PKT_BUFFER_BITS 8
116 #define N_PKT_BUFFERS (1 << PKT_BUFFER_BITS)
117 #define PKT_BUFFER_MASK (N_PKT_BUFFERS - 1)
118
119 #define PKT_COOKIE_BITS (32 - PKT_BUFFER_BITS)
120
121 void fwd_port_input(struct datapath *, struct buffer *, int in_port);
122 int fwd_control_input(struct datapath *, const void *, size_t);
123
124 uint32_t save_buffer(struct buffer *);
125 static struct buffer *retrieve_buffer(uint32_t id);
126 static void discard_buffer(uint32_t id);
127
128 static int port_no(struct datapath *dp, struct sw_port *p) 
129 {
130     assert(p >= dp->ports && p < &dp->ports[ARRAY_SIZE(dp->ports)]);
131     return p - dp->ports;
132 }
133
134 /* Generates a unique datapath id.  It incorporates the datapath index
135  * and a hardware address, if available.  If not, it generates a random
136  * one.
137  */
138 static uint64_t
139 gen_datapath_id(void)
140 {
141     /* Choose a random datapath id. */
142     uint64_t id = 0;
143     int i;
144
145     srand(time(0));
146
147     for (i = 0; i < ETH_ADDR_LEN; i++) {
148         id |= (uint64_t)(rand() & 0xff) << (8*(ETH_ADDR_LEN-1 - i));
149     }
150
151     return id;
152 }
153
154 int
155 dp_new(struct datapath **dp_, uint64_t dpid, struct rconn *rconn)
156 {
157     struct datapath *dp;
158
159     dp = calloc(1, sizeof *dp);
160     if (!dp) {
161         return ENOMEM;
162     }
163
164     dp->last_timeout = time(0);
165     dp->rconn = rconn;
166     dp->id = dpid <= UINT64_C(0xffffffffffff) ? dpid : gen_datapath_id();
167     dp->chain = chain_create();
168     if (!dp->chain) {
169         VLOG_ERR("could not create chain");
170         free(dp);
171         return ENOMEM;
172     }
173
174     list_init(&dp->port_list);
175     dp->config.flags = 0;
176     dp->config.miss_send_len = OFP_DEFAULT_MISS_SEND_LEN;
177     *dp_ = dp;
178     return 0;
179 }
180
181 int
182 dp_add_port(struct datapath *dp, const char *name)
183 {
184     struct netdev *netdev;
185     struct sw_port *p;
186     int error;
187
188     error = netdev_open(name, &netdev);
189     if (error) {
190         return error;
191     }
192
193     for (p = dp->ports; ; p++) {
194         if (p >= &dp->ports[ARRAY_SIZE(dp->ports)]) {
195             return EXFULL;
196         } else if (!p->netdev) {
197             break;
198         }
199     }
200
201     p->dp = dp;
202     p->netdev = netdev;
203     list_push_back(&dp->port_list, &p->node);
204
205     /* Notify the ctlpath that this port has been added */
206     send_port_status(p, OFPPR_ADD);
207
208     return 0;
209 }
210
211 void
212 dp_run(struct datapath *dp) 
213 {
214     time_t now = time(0);
215     struct sw_port *p, *n;
216     struct buffer *buffer = NULL;
217     int i;
218
219     if (now != dp->last_timeout) {
220         struct list deleted = LIST_INITIALIZER(&deleted);
221         struct sw_flow *f, *n;
222
223         chain_timeout(dp->chain, &deleted);
224         LIST_FOR_EACH_SAFE (f, n, struct sw_flow, node, &deleted) {
225             send_flow_expired(dp, f);
226             list_remove(&f->node);
227             flow_free(f);
228         }
229         dp->last_timeout = now;
230     }
231     poll_timer_wait(1000);
232     
233     LIST_FOR_EACH_SAFE (p, n, struct sw_port, node, &dp->port_list) {
234         int error;
235
236         if (!buffer) {
237             /* Allocate buffer with some headroom to add headers in forwarding
238              * to the controller or adding a vlan tag, plus an extra 2 bytes to
239              * allow IP headers to be aligned on a 4-byte boundary.  */
240             const int headroom = 128 + 2;
241             const int hard_header = VLAN_ETH_HEADER_LEN;
242             const int mtu = netdev_get_mtu(p->netdev);
243             buffer = buffer_new(headroom + hard_header + mtu);
244             buffer->data += headroom;
245         }
246         error = netdev_recv(p->netdev, buffer);
247         if (!error) {
248             fwd_port_input(dp, buffer, port_no(dp, p));
249             buffer = NULL;
250         } else if (error != EAGAIN) {
251             VLOG_ERR("Error receiving data from %s: %s",
252                      netdev_get_name(p->netdev), strerror(error));
253             del_switch_port(p);
254         }
255     }
256     buffer_delete(buffer);
257
258     /* Process a number of commands from the controller, but cap it at a
259      * reasonable number so that other processing doesn't starve. */
260     for (i = 0; i < 50; i++) {
261         struct buffer *buffer = rconn_recv(dp->rconn);
262         if (!buffer) {
263             break;
264         }
265         fwd_control_input(dp, buffer->data, buffer->size);
266         buffer_delete(buffer);
267     }
268
269     rconn_run(dp->rconn);
270 }
271
272 void
273 dp_wait(struct datapath *dp) 
274 {
275     struct sw_port *p;
276
277     LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
278         netdev_recv_wait(p->netdev);
279     }
280     rconn_recv_wait(dp->rconn);
281 }
282
283 /* Delete 'p' from switch. */
284 static void
285 del_switch_port(struct sw_port *p)
286 {
287     send_port_status(p, OFPPR_DELETE);
288     netdev_close(p->netdev);
289     p->netdev = NULL;
290     list_remove(&p->node);
291 }
292
293 void
294 dp_destroy(struct datapath *dp)
295 {
296     struct sw_port *p, *n;
297
298     if (!dp) {
299         return;
300     }
301
302     LIST_FOR_EACH_SAFE (p, n, struct sw_port, node, &dp->port_list) {
303         del_switch_port(p); 
304     }
305     chain_destroy(dp->chain);
306     free(dp);
307 }
308
309 static int
310 flood(struct datapath *dp, struct buffer *buffer, int in_port)
311 {
312     struct sw_port *p;
313     int prev_port;
314
315     prev_port = -1;
316     LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
317         if (port_no(dp, p) == in_port || p->flags & BRIDGE_PORT_NO_FLOOD) {
318             continue;
319         }
320         if (prev_port != -1) {
321             dp_output_port(dp, buffer_clone(buffer), in_port, prev_port);
322         }
323         prev_port = port_no(dp, p);
324     }
325     if (prev_port != -1)
326         dp_output_port(dp, buffer, in_port, prev_port);
327     else
328         buffer_delete(buffer);
329
330     return 0;
331 }
332
333 void
334 output_packet(struct datapath *dp, struct buffer *buffer, int out_port) 
335 {
336     if (out_port >= 0 && out_port < OFPP_MAX) { 
337         struct sw_port *p = &dp->ports[out_port];
338         if (p->netdev != NULL) {
339             netdev_send(p->netdev, buffer);
340             return;
341         }
342     }
343
344     buffer_delete(buffer);
345     /* FIXME: ratelimit */
346     VLOG_DBG("can't forward to bad port %d\n", out_port);
347 }
348
349 /* Takes ownership of 'buffer' and transmits it to 'out_port' on 'dp'.
350  */
351 void
352 dp_output_port(struct datapath *dp, struct buffer *buffer,
353                int in_port, int out_port)
354 {
355
356     assert(buffer);
357     if (out_port == OFPP_FLOOD) {
358         flood(dp, buffer, in_port); 
359     } else if (out_port == OFPP_CONTROLLER) {
360         dp_output_control(dp, buffer, in_port, 0, OFPR_ACTION); 
361     } else {
362         output_packet(dp, buffer, out_port);
363     }
364 }
365
366 /* Takes ownership of 'buffer' and transmits it to 'dp''s controller.  If the
367  * packet can be saved in a buffer, then only the first max_len bytes of
368  * 'buffer' are sent; otherwise, all of 'buffer' is sent.  'reason' indicates
369  * why 'buffer' is being sent. 'max_len' sets the maximum number of bytes that
370  * the caller wants to be sent; a value of 0 indicates the entire packet should
371  * be sent. */
372 void
373 dp_output_control(struct datapath *dp, struct buffer *buffer, int in_port,
374                   size_t max_len, int reason)
375 {
376     struct ofp_packet_in *opi;
377     size_t total_len;
378     uint32_t buffer_id;
379
380     buffer_id = save_buffer(buffer);
381     total_len = buffer->size;
382     if (buffer_id != UINT32_MAX && buffer->size > max_len) {
383         buffer->size = max_len;
384     }
385
386     opi = buffer_push_uninit(buffer, offsetof(struct ofp_packet_in, data));
387     opi->header.version = OFP_VERSION;
388     opi->header.type    = OFPT_PACKET_IN;
389     opi->header.length  = htons(buffer->size);
390     opi->header.xid     = htonl(0);
391     opi->buffer_id      = htonl(buffer_id);
392     opi->total_len      = htons(total_len);
393     opi->in_port        = htons(in_port);
394     opi->reason         = reason;
395     opi->pad            = 0;
396     rconn_send(dp->rconn, buffer);
397 }
398
399 static void fill_port_desc(struct datapath *dp, struct sw_port *p,
400                            struct ofp_phy_port *desc)
401 {
402     desc->port_no = htons(port_no(dp, p));
403     strncpy((char *) desc->name, netdev_get_name(p->netdev),
404             sizeof desc->name);
405     desc->name[sizeof desc->name - 1] = '\0';
406     memcpy(desc->hw_addr, netdev_get_etheraddr(p->netdev), ETH_ADDR_LEN);
407     desc->flags = htonl(p->flags);
408     desc->features = htonl(netdev_get_features(p->netdev));
409     desc->speed = htonl(netdev_get_speed(p->netdev));
410 }
411
412 static void
413 dp_send_features_reply(struct datapath *dp, uint32_t xid)
414 {
415     struct buffer *buffer;
416     struct ofp_switch_features *ofr;
417     struct sw_port *p;
418
419     buffer = buffer_new(sizeof *ofr);
420     ofr = buffer_put_uninit(buffer, sizeof *ofr);
421     memset(ofr, 0, sizeof *ofr);
422     ofr->header.version = OFP_VERSION;
423     ofr->header.type    = OFPT_FEATURES_REPLY;
424     ofr->header.xid     = xid;
425     ofr->datapath_id    = htonll(dp->id); 
426     ofr->n_exact        = htonl(2 * TABLE_HASH_MAX_FLOWS);
427     ofr->n_mac_only     = htonl(TABLE_MAC_MAX_FLOWS);
428     ofr->n_compression  = 0;                                           /* Not supported */
429     ofr->n_general      = htonl(TABLE_LINEAR_MAX_FLOWS);
430     ofr->buffer_mb      = htonl(UINT32_MAX);
431     ofr->n_buffers      = htonl(N_PKT_BUFFERS);
432     ofr->capabilities   = htonl(OFP_SUPPORTED_CAPABILITIES);
433     ofr->actions        = htonl(OFP_SUPPORTED_ACTIONS);
434     LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
435         struct ofp_phy_port *opp = buffer_put_uninit(buffer, sizeof *opp);
436         memset(opp, 0, sizeof *opp);
437         fill_port_desc(dp, p, opp);
438     }
439     ofr = buffer_at_assert(buffer, 0, sizeof *ofr);
440     ofr->header.length = htons(buffer->size);
441     rconn_send(dp->rconn, buffer);
442 }
443
444 void
445 dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp)
446 {
447     struct sw_port *p;
448
449     p = &dp->ports[htons(opp->port_no)];
450
451     /* Make sure the port id hasn't changed since this was sent */
452     if (!p || memcmp(opp->hw_addr, netdev_get_etheraddr(p->netdev),
453                      ETH_ADDR_LEN) != 0) 
454         return;
455         
456     p->flags = htonl(opp->flags);
457 }
458
459 static void
460 send_port_status(struct sw_port *p, uint8_t status) 
461 {
462     struct buffer *buffer;
463     struct ofp_port_status *ops;
464     buffer = buffer_new(sizeof *ops);
465     ops = buffer_put_uninit(buffer, sizeof *ops);
466     ops->header.version = OFP_VERSION;
467     ops->header.type    = OFPT_PORT_STATUS;
468     ops->header.length  = htons(sizeof(*ops));
469     ops->header.xid     = htonl(0);
470     ops->reason         = status;
471     fill_port_desc(p->dp, p, &ops->desc);
472     rconn_send(p->dp->rconn, buffer);
473 }
474
475 void
476 send_flow_expired(struct datapath *dp, struct sw_flow *flow)
477 {
478     struct buffer *buffer;
479     struct ofp_flow_expired *ofe;
480     buffer = buffer_new(sizeof *ofe);
481     ofe = buffer_put_uninit(buffer, sizeof *ofe);
482     ofe->header.version = OFP_VERSION;
483     ofe->header.type    = OFPT_FLOW_EXPIRED;
484     ofe->header.length  = htons(sizeof(*ofe));
485     ofe->header.xid     = htonl(0);
486     flow_fill_match(&ofe->match, &flow->key);
487     ofe->duration   = htonl(flow->timeout - flow->max_idle - flow->created);
488     ofe->packet_count   = htonll(flow->packet_count);
489     ofe->byte_count     = htonll(flow->byte_count);
490     rconn_send(dp->rconn, buffer);
491 }
492 \f
493 /* 'buffer' was received on 'in_port', a physical switch port between 0 and
494  * OFPP_MAX.  Process it according to 'chain'. */
495 void fwd_port_input(struct datapath *dp, struct buffer *buffer, int in_port)
496 {
497     struct sw_flow_key key;
498     struct sw_flow *flow;
499
500     key.wildcards = 0;
501     flow_extract(buffer, in_port, &key.flow);
502     flow = chain_lookup(dp->chain, &key);
503     if (flow != NULL) {
504         flow_used(flow, buffer);
505         execute_actions(dp, buffer, in_port, &key,
506                         flow->actions, flow->n_actions);
507     } else {
508         dp_output_control(dp, buffer, in_port, dp->config.miss_send_len,
509                           OFPR_NO_MATCH);
510     }
511 }
512
513 static void
514 do_output(struct datapath *dp, struct buffer *buffer, int in_port,
515           size_t max_len, int out_port)
516 {
517     if (out_port != OFPP_CONTROLLER) {
518         dp_output_port(dp, buffer, in_port, out_port);
519     } else {
520         dp_output_control(dp, buffer, in_port, max_len, OFPR_ACTION);
521     }
522 }
523
524 static void
525 execute_actions(struct datapath *dp, struct buffer *buffer,
526                 int in_port, const struct sw_flow_key *key,
527                 const struct ofp_action *actions, int n_actions)
528 {
529     /* Every output action needs a separate clone of 'buffer', but the common
530      * case is just a single output action, so that doing a clone and then
531      * freeing the original buffer is wasteful.  So the following code is
532      * slightly obscure just to avoid that. */
533     int prev_port;
534     size_t max_len=0;        /* Initialze to make compiler happy */
535     uint16_t eth_proto;
536     int i;
537
538     prev_port = -1;
539     eth_proto = ntohs(key->flow.dl_type);
540
541     for (i = 0; i < n_actions; i++) {
542         const struct ofp_action *a = &actions[i];
543         struct eth_header *eh = buffer->l2;
544
545         if (prev_port != -1) {
546             do_output(dp, buffer_clone(buffer), in_port, max_len, prev_port);
547             prev_port = -1;
548         }
549
550         switch (ntohs(a->type)) {
551         case OFPAT_OUTPUT:
552             prev_port = ntohs(a->arg.output.port);
553             max_len = ntohs(a->arg.output.max_len);
554             break;
555
556         case OFPAT_SET_DL_VLAN:
557             modify_vlan(buffer, key, a);
558             break;
559
560         case OFPAT_SET_DL_SRC:
561             memcpy(eh->eth_src, a->arg.dl_addr, sizeof eh->eth_src);
562             break;
563
564         case OFPAT_SET_DL_DST:
565             memcpy(eh->eth_dst, a->arg.dl_addr, sizeof eh->eth_dst);
566             break;
567
568         case OFPAT_SET_NW_SRC:
569         case OFPAT_SET_NW_DST:
570             modify_nh(buffer, eth_proto, key->flow.nw_proto, a);
571             break;
572
573         case OFPAT_SET_TP_SRC:
574         case OFPAT_SET_TP_DST:
575             modify_th(buffer, eth_proto, key->flow.nw_proto, a);
576             break;
577
578         default:
579             NOT_REACHED();
580         }
581     }
582     if (prev_port != -1)
583         do_output(dp, buffer, in_port, max_len, prev_port);
584     else
585         buffer_delete(buffer);
586 }
587
588 /* Returns the new checksum for a packet in which the checksum field previously
589  * contained 'old_csum' and in which a field that contained 'old_u16' was
590  * changed to contain 'new_u16'. */
591 static uint16_t
592 recalc_csum16(uint16_t old_csum, uint16_t old_u16, uint16_t new_u16)
593 {
594     /* Ones-complement arithmetic is endian-independent, so this code does not
595      * use htons() or ntohs().
596      *
597      * See RFC 1624 for formula and explanation. */
598     uint16_t hc_complement = ~old_csum;
599     uint16_t m_complement = ~old_u16;
600     uint16_t m_prime = new_u16;
601     uint32_t sum = hc_complement + m_complement + m_prime;
602     uint16_t hc_prime_complement = sum + (sum >> 16);
603     return ~hc_prime_complement;
604 }
605
606 /* Returns the new checksum for a packet in which the checksum field previously
607  * contained 'old_csum' and in which a field that contained 'old_u32' was
608  * changed to contain 'new_u32'. */
609 static uint16_t
610 recalc_csum32(uint16_t old_csum, uint32_t old_u32, uint32_t new_u32)
611 {
612     return recalc_csum16(recalc_csum16(old_csum, old_u32, new_u32),
613                          old_u32 >> 16, new_u32 >> 16);
614 }
615
616 static void modify_nh(struct buffer *buffer, uint16_t eth_proto,
617                       uint8_t nw_proto, const struct ofp_action *a)
618 {
619     if (eth_proto == ETH_TYPE_IP) {
620         struct ip_header *nh = buffer->l3;
621         uint32_t new, *field;
622
623         new = a->arg.nw_addr;
624         field = a->type == OFPAT_SET_NW_SRC ? &nh->ip_src : &nh->ip_dst;
625         if (nw_proto == IP_TYPE_TCP) {
626             struct tcp_header *th = buffer->l4;
627             th->tcp_csum = recalc_csum32(th->tcp_csum, *field, new);
628         } else if (nw_proto == IP_TYPE_UDP) {
629             struct udp_header *th = buffer->l4;
630             if (th->udp_csum) {
631                 th->udp_csum = recalc_csum32(th->udp_csum, *field, new);
632                 if (!th->udp_csum) {
633                     th->udp_csum = 0xffff;
634                 }
635             }
636         }
637         nh->ip_csum = recalc_csum32(nh->ip_csum, *field, new);
638         *field = new;
639     }
640 }
641
642 static void modify_th(struct buffer *buffer, uint16_t eth_proto,
643                       uint8_t nw_proto, const struct ofp_action *a)
644 {
645     if (eth_proto == ETH_TYPE_IP) {
646         uint16_t new, *field;
647
648         new = a->arg.tp;
649
650         if (nw_proto == IP_TYPE_TCP) {
651             struct tcp_header *th = buffer->l4;
652             field = a->type == OFPAT_SET_TP_SRC ? &th->tcp_src : &th->tcp_dst;
653             th->tcp_csum = recalc_csum16(th->tcp_csum, *field, new);
654             *field = new;
655         } else if (nw_proto == IP_TYPE_UDP) {
656             struct udp_header *th = buffer->l4;
657             field = a->type == OFPAT_SET_TP_SRC ? &th->udp_src : &th->udp_dst;
658             th->udp_csum = recalc_csum16(th->udp_csum, *field, new);
659             *field = new;
660         }
661     }
662 }
663
664 static void
665 modify_vlan(struct buffer *buffer,
666             const struct sw_flow_key *key, const struct ofp_action *a)
667 {
668     uint16_t new_id = a->arg.vlan_id;
669     struct vlan_eth_header *veh;
670
671     if (new_id != OFP_VLAN_NONE) {
672         if (key->flow.dl_vlan != htons(OFP_VLAN_NONE)) {
673             /* Modify vlan id, but maintain other TCI values */
674             veh = buffer->l2;
675             veh->veth_tci &= ~htons(VLAN_VID);
676             veh->veth_tci |= htons(new_id);
677         } else {
678             /* Insert new vlan id. */
679             struct eth_header *eh = buffer->l2;
680             struct vlan_eth_header tmp;
681             memcpy(tmp.veth_dst, eh->eth_dst, ETH_ADDR_LEN);
682             memcpy(tmp.veth_src, eh->eth_src, ETH_ADDR_LEN);
683             tmp.veth_type = htons(ETH_TYPE_VLAN);
684             tmp.veth_tci = new_id;
685             tmp.veth_next_type = eh->eth_type;
686             
687             veh = buffer_push_uninit(buffer, VLAN_HEADER_LEN);
688             memcpy(veh, &tmp, sizeof tmp);
689             buffer->l2 -= VLAN_HEADER_LEN;
690         }
691     } else  {
692         /* Remove an existing vlan header if it exists */
693         veh = buffer->l2;
694         if (veh->veth_type == htons(ETH_TYPE_VLAN)) {
695             struct eth_header tmp;
696             
697             memcpy(tmp.eth_dst, veh->veth_dst, ETH_ADDR_LEN);
698             memcpy(tmp.eth_src, veh->veth_src, ETH_ADDR_LEN);
699             tmp.eth_type = veh->veth_next_type;
700             
701             buffer->size -= VLAN_HEADER_LEN;
702             buffer->data += VLAN_HEADER_LEN;
703             buffer->l2 += VLAN_HEADER_LEN;
704             memcpy(buffer->data, &tmp, sizeof tmp);
705         }
706     }
707 }
708
709 static int
710 recv_features_request(struct datapath *dp, const void *msg) 
711 {
712     struct ofp_header *ofr = msg;
713     dp_send_features_reply(dp, ofr->xid);
714     return 0;
715 }
716
717 static int
718 recv_get_config_request(struct datapath *dp, const void *msg) 
719 {
720     struct ofp_header *gcr = msg;
721     struct buffer *buffer;
722     struct ofp_switch_config *osc;
723
724     buffer = buffer_new(sizeof dp->config);
725     osc = buffer_put(buffer, &dp->config, sizeof dp->config);
726     osc->header.version = OFP_VERSION;
727     osc->header.type = OFPT_GET_CONFIG_REPLY;
728     osc->header.length = htons(sizeof *osc);
729     osc->header.xid = gcr->xid;
730     rconn_send(dp->rconn, buffer);
731     return 0;
732 }
733
734 static int
735 recv_set_config(struct datapath *dp, const void *msg)
736 {
737     const struct ofp_switch_config *osc = msg;
738     dp->config = *osc;
739     return 0;
740 }
741
742 static int
743 recv_packet_out(struct datapath *dp, const void *msg)
744 {
745     const struct ofp_packet_out *opo = msg;
746
747     if (ntohl(opo->buffer_id) == (uint32_t) -1) {
748         /* FIXME: can we avoid copying data here? */
749         int data_len = ntohs(opo->header.length) - sizeof *opo;
750         struct buffer *buffer = buffer_new(data_len);
751         buffer_put(buffer, opo->u.data, data_len);
752         dp_output_port(dp, buffer,
753                        ntohs(opo->in_port), ntohs(opo->out_port));
754     } else {
755         struct sw_flow_key key;
756         struct buffer *buffer;
757         int n_acts;
758
759         buffer = retrieve_buffer(ntohl(opo->buffer_id));
760         if (!buffer) {
761             return -ESRCH; 
762         }
763
764         n_acts = (ntohs(opo->header.length) - sizeof *opo) 
765             / sizeof *opo->u.actions;
766         flow_extract(buffer, ntohs(opo->in_port), &key.flow);
767         execute_actions(dp, buffer, ntohs(opo->in_port),
768                         &key, opo->u.actions, n_acts);
769     }
770     return 0;
771 }
772
773 static int
774 recv_port_mod(struct datapath *dp, const void *msg)
775 {
776     const struct ofp_port_mod *opm = msg;
777
778     dp_update_port_flags(dp, &opm->desc);
779
780     return 0;
781 }
782
783 static int
784 add_flow(struct datapath *dp, const struct ofp_flow_mod *ofm)
785 {
786     int error = -ENOMEM;
787     int n_acts;
788     struct sw_flow *flow;
789
790
791     /* Check number of actions. */
792     n_acts = (ntohs(ofm->header.length) - sizeof *ofm) / sizeof *ofm->actions;
793     if (n_acts > MAX_ACTIONS) {
794         error = -E2BIG;
795         goto error;
796     }
797
798     /* Allocate memory. */
799     flow = flow_alloc(n_acts);
800     if (flow == NULL)
801         goto error;
802
803     /* Fill out flow. */
804     flow_extract_match(&flow->key, &ofm->match);
805     flow->group_id = ntohl(ofm->group_id);
806     flow->max_idle = ntohs(ofm->max_idle);
807     flow->timeout = time(0) + flow->max_idle; /* FIXME */
808     flow->n_actions = n_acts;
809     flow->created = time(0);    /* FIXME */
810     flow->byte_count = 0;
811     flow->packet_count = 0;
812     memcpy(flow->actions, ofm->actions, n_acts * sizeof *flow->actions);
813
814     /* Act. */
815     error = chain_insert(dp->chain, flow);
816     if (error) {
817         goto error_free_flow; 
818     }
819     error = 0;
820     if (ntohl(ofm->buffer_id) != UINT32_MAX) {
821         struct buffer *buffer = retrieve_buffer(ntohl(ofm->buffer_id));
822         if (buffer) {
823             struct sw_flow_key key;
824             uint16_t in_port = ntohs(ofm->match.in_port);
825             flow_used(flow, buffer);
826             flow_extract(buffer, in_port, &key.flow);
827             execute_actions(dp, buffer, in_port, &key, ofm->actions, n_acts);
828         } else {
829             error = -ESRCH; 
830         }
831     }
832     return error;
833
834 error_free_flow:
835     flow_free(flow);
836 error:
837     if (ntohl(ofm->buffer_id) != (uint32_t) -1)
838         discard_buffer(ntohl(ofm->buffer_id));
839     return error;
840 }
841
842 static int
843 recv_flow(struct datapath *dp, const void *msg)
844 {
845     const struct ofp_flow_mod *ofm = msg;
846     uint16_t command = ntohs(ofm->command);
847
848     if (command == OFPFC_ADD) {
849         return add_flow(dp, ofm);
850     }  else if (command == OFPFC_DELETE) {
851         struct sw_flow_key key;
852         flow_extract_match(&key, &ofm->match);
853         return chain_delete(dp->chain, &key, 0) ? 0 : -ESRCH;
854     } else if (command == OFPFC_DELETE_STRICT) {
855         struct sw_flow_key key;
856         flow_extract_match(&key, &ofm->match);
857         return chain_delete(dp->chain, &key, 1) ? 0 : -ESRCH;
858     } else {
859         return -ENODEV;
860     }
861 }
862
863 /* 'msg', which is 'length' bytes long, was received from the control path.
864  * Apply it to 'chain'. */
865 int
866 fwd_control_input(struct datapath *dp, const void *msg, size_t length)
867 {
868
869     struct openflow_packet {
870         size_t min_size;
871         int (*handler)(struct datapath *, const void *);
872     };
873
874     static const struct openflow_packet packets[] = {
875         [OFPT_FEATURES_REQUEST] = {
876             sizeof (struct ofp_header),
877             recv_features_request,
878         },
879         [OFPT_GET_CONFIG_REQUEST] = {
880             sizeof (struct ofp_header),
881             recv_get_config_request,
882         },
883         [OFPT_SET_CONFIG] = {
884             sizeof (struct ofp_switch_config),
885             recv_set_config,
886         },
887         [OFPT_PACKET_OUT] = {
888             sizeof (struct ofp_packet_out),
889             recv_packet_out,
890         },
891         [OFPT_FLOW_MOD] = {
892             sizeof (struct ofp_flow_mod),
893             recv_flow,
894         },
895         [OFPT_PORT_MOD] = {
896             sizeof (struct ofp_port_mod),
897             recv_port_mod,
898         },
899     };
900
901     const struct openflow_packet *pkt;
902     struct ofp_header *oh;
903
904     if (length < sizeof(struct ofp_header))
905         return -EINVAL;
906
907     oh = (struct ofp_header *) msg;
908     if (oh->version != 1 || oh->type >= ARRAY_SIZE(packets)
909         || ntohs(oh->length) > length)
910         return -EINVAL;
911
912     pkt = &packets[oh->type];
913     if (!pkt->handler)
914         return -ENOSYS;
915     if (length < pkt->min_size)
916         return -EFAULT;
917
918     return pkt->handler(dp, msg);
919 }
920 \f
921 /* Packet buffering. */
922
923 #define OVERWRITE_SECS  1
924
925 struct packet_buffer {
926     struct buffer *buffer;
927     uint32_t cookie;
928     time_t timeout;
929 };
930
931 static struct packet_buffer buffers[N_PKT_BUFFERS];
932 static unsigned int buffer_idx;
933
934 uint32_t save_buffer(struct buffer *buffer)
935 {
936     struct packet_buffer *p;
937     uint32_t id;
938
939     buffer_idx = (buffer_idx + 1) & PKT_BUFFER_MASK;
940     p = &buffers[buffer_idx];
941     if (p->buffer) {
942         /* Don't buffer packet if existing entry is less than
943          * OVERWRITE_SECS old. */
944         if (time(0) < p->timeout) { /* FIXME */
945             return -1;
946         } else {
947             buffer_delete(p->buffer); 
948         }
949     }
950     /* Don't use maximum cookie value since the all-bits-1 id is
951      * special. */
952     if (++p->cookie >= (1u << PKT_COOKIE_BITS) - 1)
953         p->cookie = 0;
954     p->buffer = buffer_clone(buffer);      /* FIXME */
955     p->timeout = time(0) + OVERWRITE_SECS; /* FIXME */
956     id = buffer_idx | (p->cookie << PKT_BUFFER_BITS);
957
958     return id;
959 }
960
961 static struct buffer *retrieve_buffer(uint32_t id)
962 {
963     struct buffer *buffer = NULL;
964     struct packet_buffer *p;
965
966     p = &buffers[id & PKT_BUFFER_MASK];
967     if (p->cookie == id >> PKT_BUFFER_BITS) {
968         buffer = p->buffer;
969         p->buffer = NULL;
970     } else {
971         printf("cookie mismatch: %x != %x\n",
972                id >> PKT_BUFFER_BITS, p->cookie);
973     }
974
975     return buffer;
976 }
977
978 static void discard_buffer(uint32_t id)
979 {
980     struct packet_buffer *p;
981
982     p = &buffers[id & PKT_BUFFER_MASK];
983     if (p->cookie == id >> PKT_BUFFER_BITS) {
984         buffer_delete(p->buffer);
985         p->buffer = NULL;
986     }
987 }