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