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