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