1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
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:
17 * The above copyright notice and this permission notice shall be
18 * included in all copies or substantial portions of the Software.
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
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.
35 #include <arpa/inet.h>
46 #include "poll-loop.h"
52 #define THIS_MODULE VLM_datapath
55 #define BRIDGE_PORT_NO_FLOOD 0x00000001
57 /* Capabilities supported by this implementation. */
58 #define OFP_SUPPORTED_CAPABILITIES ( OFPC_FLOW_STATS \
63 /* Actions supported by this implementation. */
64 #define OFP_SUPPORTED_ACTIONS ( (1 << OFPAT_OUTPUT) \
65 | (1 << OFPAT_SET_DL_VLAN) \
66 | (1 << OFPAT_SET_DL_SRC) \
67 | (1 << OFPAT_SET_DL_DST) \
68 | (1 << OFPAT_SET_NW_SRC) \
69 | (1 << OFPAT_SET_NW_DST) \
70 | (1 << OFPAT_SET_TP_SRC) \
71 | (1 << OFPAT_SET_TP_DST) )
76 struct netdev *netdev;
77 struct list node; /* Element in datapath.ports. */
78 unsigned long long int rx_count, tx_count, drop_count;
81 /* The origin of a received OpenFlow message, to enable sending a reply. */
83 struct remote *remote; /* The device that sent the message. */
84 uint32_t xid; /* The OpenFlow transaction ID. */
87 /* A connection to a controller or a management device. */
92 /* Support for reliable, multi-message replies to requests.
94 * If an incoming request needs to have a reliable reply that might
95 * require multiple messages, it can use remote_start_dump() to set up
96 * a callback that will be called as buffer space for replies. */
97 int (*cb_dump)(struct datapath *, void *aux);
98 void (*cb_done)(void *aux);
103 /* Remote connections. */
104 struct remote *controller; /* Connection to controller. */
105 struct list remotes; /* All connections (including controller). */
106 struct vconn *listen_vconn;
110 /* Unique identifier for this datapath */
113 struct sw_chain *chain; /* Forwarding rules. */
115 struct ofp_switch_config config;
118 struct sw_port ports[OFPP_MAX];
119 struct list port_list; /* List of ports, for flooding. */
122 static struct remote *remote_create(struct datapath *, struct rconn *);
123 static void remote_run(struct datapath *, struct remote *);
124 static void remote_wait(struct remote *);
125 static void remote_destroy(struct remote *);
127 void dp_output_port(struct datapath *, struct buffer *,
128 int in_port, int out_port);
129 void dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp);
130 void dp_output_control(struct datapath *, struct buffer *, int in_port,
131 size_t max_len, int reason);
132 static void send_flow_expired(struct datapath *, struct sw_flow *);
133 static void send_port_status(struct sw_port *p, uint8_t status);
134 static void del_switch_port(struct sw_port *p);
135 static void execute_actions(struct datapath *, struct buffer *,
136 int in_port, const struct sw_flow_key *,
137 const struct ofp_action *, int n_actions);
138 static void modify_vlan(struct buffer *buffer, const struct sw_flow_key *key,
139 const struct ofp_action *a);
140 static void modify_nh(struct buffer *buffer, uint16_t eth_proto,
141 uint8_t nw_proto, const struct ofp_action *a);
142 static void modify_th(struct buffer *buffer, uint16_t eth_proto,
143 uint8_t nw_proto, const struct ofp_action *a);
145 /* Buffers are identified to userspace by a 31-bit opaque ID. We divide the ID
146 * into a buffer number (low bits) and a cookie (high bits). The buffer number
147 * is an index into an array of buffers. The cookie distinguishes between
148 * different packets that have occupied a single buffer. Thus, the more
149 * buffers we have, the lower-quality the cookie... */
150 #define PKT_BUFFER_BITS 8
151 #define N_PKT_BUFFERS (1 << PKT_BUFFER_BITS)
152 #define PKT_BUFFER_MASK (N_PKT_BUFFERS - 1)
154 #define PKT_COOKIE_BITS (32 - PKT_BUFFER_BITS)
156 void fwd_port_input(struct datapath *, struct buffer *, int in_port);
157 int fwd_control_input(struct datapath *, const struct sender *,
158 const void *, size_t);
160 uint32_t save_buffer(struct buffer *);
161 static struct buffer *retrieve_buffer(uint32_t id);
162 static void discard_buffer(uint32_t id);
164 static int port_no(struct datapath *dp, struct sw_port *p)
166 assert(p >= dp->ports && p < &dp->ports[ARRAY_SIZE(dp->ports)]);
167 return p - dp->ports;
170 /* Generates a unique datapath id. It incorporates the datapath index
171 * and a hardware address, if available. If not, it generates a random
175 gen_datapath_id(void)
177 /* Choose a random datapath id. */
183 for (i = 0; i < ETH_ADDR_LEN; i++) {
184 id |= (uint64_t)(rand() & 0xff) << (8*(ETH_ADDR_LEN-1 - i));
191 dp_new(struct datapath **dp_, uint64_t dpid, struct rconn *rconn)
195 dp = calloc(1, sizeof *dp);
200 dp->last_timeout = time(0);
201 list_init(&dp->remotes);
202 dp->controller = remote_create(dp, rconn);
203 dp->listen_vconn = NULL;
204 dp->id = dpid <= UINT64_C(0xffffffffffff) ? dpid : gen_datapath_id();
205 dp->chain = chain_create();
207 VLOG_ERR("could not create chain");
212 list_init(&dp->port_list);
213 dp->config.flags = 0;
214 dp->config.miss_send_len = htons(OFP_DEFAULT_MISS_SEND_LEN);
220 dp_add_port(struct datapath *dp, const char *name)
222 struct netdev *netdev;
228 error = netdev_open(name, &netdev);
232 error = netdev_set_flags(netdev, NETDEV_UP | NETDEV_PROMISC);
234 VLOG_ERR("Couldn't set promiscuous mode on %s device", name);
235 netdev_close(netdev);
238 if (netdev_get_in4(netdev, &in4)) {
239 VLOG_ERR("%s device has assigned IP address %s", name, inet_ntoa(in4));
241 if (netdev_get_in6(netdev, &in6)) {
242 char in6_name[INET6_ADDRSTRLEN + 1];
243 inet_ntop(AF_INET6, &in6, in6_name, sizeof in6_name);
244 VLOG_ERR("%s device has assigned IPv6 address %s", name, in6_name);
247 for (p = dp->ports; ; p++) {
248 if (p >= &dp->ports[ARRAY_SIZE(dp->ports)]) {
250 } else if (!p->netdev) {
260 list_push_back(&dp->port_list, &p->node);
262 /* Notify the ctlpath that this port has been added */
263 send_port_status(p, OFPPR_ADD);
269 dp_add_listen_vconn(struct datapath *dp, struct vconn *listen_vconn)
271 assert(!dp->listen_vconn);
272 dp->listen_vconn = listen_vconn;
276 dp_run(struct datapath *dp)
278 time_t now = time(0);
279 struct sw_port *p, *pn;
280 struct remote *r, *rn;
281 struct buffer *buffer = NULL;
283 if (now != dp->last_timeout) {
284 struct list deleted = LIST_INITIALIZER(&deleted);
285 struct sw_flow *f, *n;
287 chain_timeout(dp->chain, &deleted);
288 LIST_FOR_EACH_SAFE (f, n, struct sw_flow, node, &deleted) {
289 send_flow_expired(dp, f);
290 list_remove(&f->node);
293 dp->last_timeout = now;
295 poll_timer_wait(1000);
297 LIST_FOR_EACH_SAFE (p, pn, struct sw_port, node, &dp->port_list) {
301 /* Allocate buffer with some headroom to add headers in forwarding
302 * to the controller or adding a vlan tag, plus an extra 2 bytes to
303 * allow IP headers to be aligned on a 4-byte boundary. */
304 const int headroom = 128 + 2;
305 const int hard_header = VLAN_ETH_HEADER_LEN;
306 const int mtu = netdev_get_mtu(p->netdev);
307 buffer = buffer_new(headroom + hard_header + mtu);
308 buffer->data += headroom;
310 error = netdev_recv(p->netdev, buffer);
313 fwd_port_input(dp, buffer, port_no(dp, p));
315 } else if (error != EAGAIN) {
316 VLOG_ERR("Error receiving data from %s: %s",
317 netdev_get_name(p->netdev), strerror(error));
321 buffer_delete(buffer);
323 /* Talk to remotes. */
324 LIST_FOR_EACH_SAFE (r, rn, struct remote, node, &dp->remotes) {
327 if (dp->listen_vconn) {
329 struct vconn *new_vconn;
332 retval = vconn_accept(dp->listen_vconn, &new_vconn);
334 if (retval != EAGAIN) {
335 VLOG_WARN("accept failed (%s)", strerror(retval));
339 remote_create(dp, rconn_new_from_vconn("passive", 128, new_vconn));
345 remote_run(struct datapath *dp, struct remote *r)
351 /* Do some remote processing, but cap it at a reasonable amount so that
352 * other processing doesn't starve. */
353 for (i = 0; i < 50; i++) {
355 struct buffer *buffer;
356 struct ofp_header *oh;
358 buffer = rconn_recv(r->rconn);
363 if (buffer->size >= sizeof *oh) {
364 struct sender sender;
368 sender.xid = oh->xid;
369 fwd_control_input(dp, &sender, buffer->data, buffer->size);
371 VLOG_WARN("received too-short OpenFlow message");
373 buffer_delete(buffer);
375 if (!rconn_is_full(r->rconn)) {
376 int error = r->cb_dump(dp, r->cb_aux);
379 VLOG_WARN("dump callback error: %s", strerror(-error));
381 r->cb_done(r->cb_aux);
390 if (!rconn_is_alive(r->rconn)) {
396 remote_wait(struct remote *r)
398 rconn_run_wait(r->rconn);
399 rconn_recv_wait(r->rconn);
403 remote_destroy(struct remote *r)
406 if (r->cb_dump && r->cb_done) {
407 r->cb_done(r->cb_aux);
409 list_remove(&r->node);
410 rconn_destroy(r->rconn);
415 static struct remote *
416 remote_create(struct datapath *dp, struct rconn *rconn)
418 struct remote *remote = xmalloc(sizeof *remote);
419 list_push_back(&dp->remotes, &remote->node);
420 remote->rconn = rconn;
421 remote->cb_dump = NULL;
425 /* Starts a callback-based, reliable, possibly multi-message reply to a
426 * request made by 'remote'.
428 * 'dump' designates a function that will be called when the 'remote' send
429 * queue has an empty slot. It should compose a message and send it on
430 * 'remote'. On success, it should return 1 if it should be called again when
431 * another send queue slot opens up, 0 if its transmissions are complete, or a
432 * negative errno value on failure.
434 * 'done' designates a function to clean up any resources allocated for the
435 * dump. It must handle being called before the dump is complete (which will
436 * happen if 'remote' is closed unexpectedly).
438 * 'aux' is passed to 'dump' and 'done'. */
440 remote_start_dump(struct remote *remote,
441 int (*dump)(struct datapath *, void *),
442 void (*done)(void *),
445 assert(!remote->cb_dump);
446 remote->cb_dump = dump;
447 remote->cb_done = done;
448 remote->cb_aux = aux;
452 dp_wait(struct datapath *dp)
457 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
458 netdev_recv_wait(p->netdev);
460 LIST_FOR_EACH (r, struct remote, node, &dp->remotes) {
463 if (dp->listen_vconn) {
464 vconn_accept_wait(dp->listen_vconn);
468 /* Delete 'p' from switch. */
470 del_switch_port(struct sw_port *p)
472 send_port_status(p, OFPPR_DELETE);
473 netdev_close(p->netdev);
475 list_remove(&p->node);
479 dp_destroy(struct datapath *dp)
481 struct sw_port *p, *n;
487 LIST_FOR_EACH_SAFE (p, n, struct sw_port, node, &dp->port_list) {
490 chain_destroy(dp->chain);
494 /* Send packets out all the ports except the originating one. If the
495 * "flood" argument is set, don't send out ports with flooding disabled.
498 output_all(struct datapath *dp, struct buffer *buffer, int in_port, int flood)
504 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
505 if (port_no(dp, p) == in_port) {
508 if (flood && p->flags & BRIDGE_PORT_NO_FLOOD) {
511 if (prev_port != -1) {
512 dp_output_port(dp, buffer_clone(buffer), in_port, prev_port);
514 prev_port = port_no(dp, p);
517 dp_output_port(dp, buffer, in_port, prev_port);
519 buffer_delete(buffer);
525 output_packet(struct datapath *dp, struct buffer *buffer, int out_port)
527 if (out_port >= 0 && out_port < OFPP_MAX) {
528 struct sw_port *p = &dp->ports[out_port];
529 if (p->netdev != NULL) {
530 if (!netdev_send(p->netdev, buffer)) {
539 buffer_delete(buffer);
540 /* FIXME: ratelimit */
541 VLOG_DBG("can't forward to bad port %d\n", out_port);
544 /* Takes ownership of 'buffer' and transmits it to 'out_port' on 'dp'.
547 dp_output_port(struct datapath *dp, struct buffer *buffer,
548 int in_port, int out_port)
552 if (out_port == OFPP_FLOOD) {
553 output_all(dp, buffer, in_port, 1);
554 } else if (out_port == OFPP_ALL) {
555 output_all(dp, buffer, in_port, 0);
556 } else if (out_port == OFPP_CONTROLLER) {
557 dp_output_control(dp, buffer, in_port, 0, OFPR_ACTION);
558 } else if (out_port == OFPP_TABLE) {
559 struct sw_flow_key key;
560 struct sw_flow *flow;
563 flow_extract(buffer, in_port, &key.flow);
564 flow = chain_lookup(dp->chain, &key);
566 flow_used(flow, buffer);
567 execute_actions(dp, buffer, in_port, &key,
568 flow->actions, flow->n_actions);
571 output_packet(dp, buffer, out_port);
576 alloc_openflow_buffer(struct datapath *dp, size_t openflow_len, uint8_t type,
577 const struct sender *sender, struct buffer **bufferp)
579 struct buffer *buffer;
580 struct ofp_header *oh;
582 buffer = *bufferp = buffer_new(openflow_len);
583 oh = buffer_put_uninit(buffer, openflow_len);
584 oh->version = OFP_VERSION;
586 oh->length = 0; /* Filled in by send_openflow_buffer(). */
587 oh->xid = sender ? sender->xid : 0;
592 send_openflow_buffer(struct datapath *dp, struct buffer *buffer,
593 const struct sender *sender)
595 struct remote *remote = sender ? sender->remote : dp->controller;
596 struct rconn *rconn = remote->rconn;
597 struct ofp_header *oh;
600 oh = buffer_at_assert(buffer, 0, sizeof *oh);
601 oh->length = htons(buffer->size);
603 retval = rconn_send(rconn, buffer);
605 VLOG_WARN("send to %s failed: %s",
606 rconn_get_name(rconn), strerror(retval));
607 buffer_delete(buffer);
612 /* Takes ownership of 'buffer' and transmits it to 'dp''s controller. If the
613 * packet can be saved in a buffer, then only the first max_len bytes of
614 * 'buffer' are sent; otherwise, all of 'buffer' is sent. 'reason' indicates
615 * why 'buffer' is being sent. 'max_len' sets the maximum number of bytes that
616 * the caller wants to be sent; a value of 0 indicates the entire packet should
619 dp_output_control(struct datapath *dp, struct buffer *buffer, int in_port,
620 size_t max_len, int reason)
622 struct ofp_packet_in *opi;
626 buffer_id = save_buffer(buffer);
627 total_len = buffer->size;
628 if (buffer_id != UINT32_MAX && buffer->size > max_len) {
629 buffer->size = max_len;
632 opi = buffer_push_uninit(buffer, offsetof(struct ofp_packet_in, data));
633 opi->header.version = OFP_VERSION;
634 opi->header.type = OFPT_PACKET_IN;
635 opi->header.length = htons(buffer->size);
636 opi->header.xid = htonl(0);
637 opi->buffer_id = htonl(buffer_id);
638 opi->total_len = htons(total_len);
639 opi->in_port = htons(in_port);
640 opi->reason = reason;
642 send_openflow_buffer(dp, buffer, NULL);
645 static void fill_port_desc(struct datapath *dp, struct sw_port *p,
646 struct ofp_phy_port *desc)
648 desc->port_no = htons(port_no(dp, p));
649 strncpy((char *) desc->name, netdev_get_name(p->netdev),
651 desc->name[sizeof desc->name - 1] = '\0';
652 memcpy(desc->hw_addr, netdev_get_etheraddr(p->netdev), ETH_ADDR_LEN);
653 desc->flags = htonl(p->flags);
654 desc->features = htonl(netdev_get_features(p->netdev));
655 desc->speed = htonl(netdev_get_speed(p->netdev));
659 dp_send_features_reply(struct datapath *dp, const struct sender *sender)
661 struct buffer *buffer;
662 struct ofp_switch_features *ofr;
665 ofr = alloc_openflow_buffer(dp, sizeof *ofr, OFPT_FEATURES_REPLY,
667 ofr->datapath_id = htonll(dp->id);
668 ofr->n_exact = htonl(2 * TABLE_HASH_MAX_FLOWS);
669 ofr->n_compression = 0; /* Not supported */
670 ofr->n_general = htonl(TABLE_LINEAR_MAX_FLOWS);
671 ofr->buffer_mb = htonl(UINT32_MAX);
672 ofr->n_buffers = htonl(N_PKT_BUFFERS);
673 ofr->capabilities = htonl(OFP_SUPPORTED_CAPABILITIES);
674 ofr->actions = htonl(OFP_SUPPORTED_ACTIONS);
675 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
676 struct ofp_phy_port *opp = buffer_put_uninit(buffer, sizeof *opp);
677 memset(opp, 0, sizeof *opp);
678 fill_port_desc(dp, p, opp);
680 send_openflow_buffer(dp, buffer, sender);
684 dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp)
686 int port_no = ntohs(opp->port_no);
687 if (port_no < OFPP_MAX) {
688 struct sw_port *p = &dp->ports[port_no];
690 /* Make sure the port id hasn't changed since this was sent */
691 if (!p || memcmp(opp->hw_addr, netdev_get_etheraddr(p->netdev),
692 ETH_ADDR_LEN) != 0) {
695 p->flags = htonl(opp->flags);
700 send_port_status(struct sw_port *p, uint8_t status)
702 struct buffer *buffer;
703 struct ofp_port_status *ops;
704 ops = alloc_openflow_buffer(p->dp, sizeof *ops, OFPT_PORT_STATUS, NULL,
706 ops->reason = status;
707 memset(ops->pad, 0, sizeof ops->pad);
708 fill_port_desc(p->dp, p, &ops->desc);
710 send_openflow_buffer(p->dp, buffer, NULL);
714 send_flow_expired(struct datapath *dp, struct sw_flow *flow)
716 struct buffer *buffer;
717 struct ofp_flow_expired *ofe;
718 ofe = alloc_openflow_buffer(dp, sizeof *ofe, OFPT_FLOW_EXPIRED, NULL,
720 flow_fill_match(&ofe->match, &flow->key);
722 memset(ofe->pad, 0, sizeof ofe->pad);
723 ofe->priority = htons(flow->priority);
725 ofe->duration = htonl(flow->timeout - flow->max_idle - flow->created);
726 ofe->packet_count = htonll(flow->packet_count);
727 ofe->byte_count = htonll(flow->byte_count);
728 send_openflow_buffer(dp, buffer, NULL);
732 dp_send_error_msg(struct datapath *dp, const struct sender *sender,
733 uint16_t type, uint16_t code, const uint8_t *data, size_t len)
735 struct buffer *buffer;
736 struct ofp_error_msg *oem;
737 oem = alloc_openflow_buffer(dp, sizeof(*oem)+len, OFPT_ERROR_MSG,
739 oem->type = htons(type);
740 oem->code = htons(code);
741 memcpy(oem->data, data, len);
742 send_openflow_buffer(dp, buffer, sender);
746 fill_flow_stats(struct buffer *buffer, struct sw_flow *flow,
747 int table_idx, time_t now)
749 struct ofp_flow_stats *ofs;
750 int length = sizeof *ofs + sizeof *ofs->actions * flow->n_actions;
751 ofs = buffer_put_uninit(buffer, length);
752 ofs->length = htons(length);
753 ofs->table_id = table_idx;
755 ofs->match.wildcards = htons(flow->key.wildcards);
756 ofs->match.in_port = flow->key.flow.in_port;
757 memcpy(ofs->match.dl_src, flow->key.flow.dl_src, ETH_ADDR_LEN);
758 memcpy(ofs->match.dl_dst, flow->key.flow.dl_dst, ETH_ADDR_LEN);
759 ofs->match.dl_vlan = flow->key.flow.dl_vlan;
760 ofs->match.dl_type = flow->key.flow.dl_type;
761 ofs->match.nw_src = flow->key.flow.nw_src;
762 ofs->match.nw_dst = flow->key.flow.nw_dst;
763 ofs->match.nw_proto = flow->key.flow.nw_proto;
764 memset(ofs->match.pad, 0, sizeof ofs->match.pad);
765 ofs->match.tp_src = flow->key.flow.tp_src;
766 ofs->match.tp_dst = flow->key.flow.tp_dst;
767 ofs->duration = htonl(now - flow->created);
768 ofs->packet_count = htonll(flow->packet_count);
769 ofs->byte_count = htonll(flow->byte_count);
770 ofs->priority = htons(flow->priority);
771 ofs->max_idle = htons(flow->max_idle);
772 memcpy(ofs->actions, flow->actions,
773 sizeof *ofs->actions * flow->n_actions);
777 /* 'buffer' was received on 'in_port', a physical switch port between 0 and
778 * OFPP_MAX. Process it according to 'chain'. */
779 void fwd_port_input(struct datapath *dp, struct buffer *buffer, int in_port)
781 struct sw_flow_key key;
782 struct sw_flow *flow;
785 flow_extract(buffer, in_port, &key.flow);
786 flow = chain_lookup(dp->chain, &key);
788 flow_used(flow, buffer);
789 execute_actions(dp, buffer, in_port, &key,
790 flow->actions, flow->n_actions);
792 dp_output_control(dp, buffer, in_port, ntohs(dp->config.miss_send_len),
798 do_output(struct datapath *dp, struct buffer *buffer, int in_port,
799 size_t max_len, int out_port)
801 if (out_port != OFPP_CONTROLLER) {
802 dp_output_port(dp, buffer, in_port, out_port);
804 dp_output_control(dp, buffer, in_port, max_len, OFPR_ACTION);
809 execute_actions(struct datapath *dp, struct buffer *buffer,
810 int in_port, const struct sw_flow_key *key,
811 const struct ofp_action *actions, int n_actions)
813 /* Every output action needs a separate clone of 'buffer', but the common
814 * case is just a single output action, so that doing a clone and then
815 * freeing the original buffer is wasteful. So the following code is
816 * slightly obscure just to avoid that. */
818 size_t max_len=0; /* Initialze to make compiler happy */
823 eth_proto = ntohs(key->flow.dl_type);
825 for (i = 0; i < n_actions; i++) {
826 const struct ofp_action *a = &actions[i];
827 struct eth_header *eh = buffer->l2;
829 if (prev_port != -1) {
830 do_output(dp, buffer_clone(buffer), in_port, max_len, prev_port);
834 switch (ntohs(a->type)) {
836 prev_port = ntohs(a->arg.output.port);
837 max_len = ntohs(a->arg.output.max_len);
840 case OFPAT_SET_DL_VLAN:
841 modify_vlan(buffer, key, a);
844 case OFPAT_SET_DL_SRC:
845 memcpy(eh->eth_src, a->arg.dl_addr, sizeof eh->eth_src);
848 case OFPAT_SET_DL_DST:
849 memcpy(eh->eth_dst, a->arg.dl_addr, sizeof eh->eth_dst);
852 case OFPAT_SET_NW_SRC:
853 case OFPAT_SET_NW_DST:
854 modify_nh(buffer, eth_proto, key->flow.nw_proto, a);
857 case OFPAT_SET_TP_SRC:
858 case OFPAT_SET_TP_DST:
859 modify_th(buffer, eth_proto, key->flow.nw_proto, a);
867 do_output(dp, buffer, in_port, max_len, prev_port);
869 buffer_delete(buffer);
872 /* Returns the new checksum for a packet in which the checksum field previously
873 * contained 'old_csum' and in which a field that contained 'old_u16' was
874 * changed to contain 'new_u16'. */
876 recalc_csum16(uint16_t old_csum, uint16_t old_u16, uint16_t new_u16)
878 /* Ones-complement arithmetic is endian-independent, so this code does not
879 * use htons() or ntohs().
881 * See RFC 1624 for formula and explanation. */
882 uint16_t hc_complement = ~old_csum;
883 uint16_t m_complement = ~old_u16;
884 uint16_t m_prime = new_u16;
885 uint32_t sum = hc_complement + m_complement + m_prime;
886 uint16_t hc_prime_complement = sum + (sum >> 16);
887 return ~hc_prime_complement;
890 /* Returns the new checksum for a packet in which the checksum field previously
891 * contained 'old_csum' and in which a field that contained 'old_u32' was
892 * changed to contain 'new_u32'. */
894 recalc_csum32(uint16_t old_csum, uint32_t old_u32, uint32_t new_u32)
896 return recalc_csum16(recalc_csum16(old_csum, old_u32, new_u32),
897 old_u32 >> 16, new_u32 >> 16);
900 static void modify_nh(struct buffer *buffer, uint16_t eth_proto,
901 uint8_t nw_proto, const struct ofp_action *a)
903 if (eth_proto == ETH_TYPE_IP) {
904 struct ip_header *nh = buffer->l3;
905 uint32_t new, *field;
907 new = a->arg.nw_addr;
908 field = a->type == OFPAT_SET_NW_SRC ? &nh->ip_src : &nh->ip_dst;
909 if (nw_proto == IP_TYPE_TCP) {
910 struct tcp_header *th = buffer->l4;
911 th->tcp_csum = recalc_csum32(th->tcp_csum, *field, new);
912 } else if (nw_proto == IP_TYPE_UDP) {
913 struct udp_header *th = buffer->l4;
915 th->udp_csum = recalc_csum32(th->udp_csum, *field, new);
917 th->udp_csum = 0xffff;
921 nh->ip_csum = recalc_csum32(nh->ip_csum, *field, new);
926 static void modify_th(struct buffer *buffer, uint16_t eth_proto,
927 uint8_t nw_proto, const struct ofp_action *a)
929 if (eth_proto == ETH_TYPE_IP) {
930 uint16_t new, *field;
934 if (nw_proto == IP_TYPE_TCP) {
935 struct tcp_header *th = buffer->l4;
936 field = a->type == OFPAT_SET_TP_SRC ? &th->tcp_src : &th->tcp_dst;
937 th->tcp_csum = recalc_csum16(th->tcp_csum, *field, new);
939 } else if (nw_proto == IP_TYPE_UDP) {
940 struct udp_header *th = buffer->l4;
941 field = a->type == OFPAT_SET_TP_SRC ? &th->udp_src : &th->udp_dst;
942 th->udp_csum = recalc_csum16(th->udp_csum, *field, new);
949 modify_vlan(struct buffer *buffer,
950 const struct sw_flow_key *key, const struct ofp_action *a)
952 uint16_t new_id = a->arg.vlan_id;
953 struct vlan_eth_header *veh;
955 if (new_id != htons(OFP_VLAN_NONE)) {
956 if (key->flow.dl_vlan != htons(OFP_VLAN_NONE)) {
957 /* Modify vlan id, but maintain other TCI values */
959 veh->veth_tci &= ~htons(VLAN_VID);
960 veh->veth_tci |= new_id;
962 /* Insert new vlan id. */
963 struct eth_header *eh = buffer->l2;
964 struct vlan_eth_header tmp;
965 memcpy(tmp.veth_dst, eh->eth_dst, ETH_ADDR_LEN);
966 memcpy(tmp.veth_src, eh->eth_src, ETH_ADDR_LEN);
967 tmp.veth_type = htons(ETH_TYPE_VLAN);
968 tmp.veth_tci = new_id;
969 tmp.veth_next_type = eh->eth_type;
971 veh = buffer_push_uninit(buffer, VLAN_HEADER_LEN);
972 memcpy(veh, &tmp, sizeof tmp);
973 buffer->l2 -= VLAN_HEADER_LEN;
976 /* Remove an existing vlan header if it exists */
978 if (veh->veth_type == htons(ETH_TYPE_VLAN)) {
979 struct eth_header tmp;
981 memcpy(tmp.eth_dst, veh->veth_dst, ETH_ADDR_LEN);
982 memcpy(tmp.eth_src, veh->veth_src, ETH_ADDR_LEN);
983 tmp.eth_type = veh->veth_next_type;
985 buffer->size -= VLAN_HEADER_LEN;
986 buffer->data += VLAN_HEADER_LEN;
987 buffer->l2 += VLAN_HEADER_LEN;
988 memcpy(buffer->data, &tmp, sizeof tmp);
994 recv_features_request(struct datapath *dp, const struct sender *sender,
997 dp_send_features_reply(dp, sender);
1002 recv_get_config_request(struct datapath *dp, const struct sender *sender,
1005 struct buffer *buffer;
1006 struct ofp_switch_config *osc;
1008 osc = alloc_openflow_buffer(dp, sizeof *osc, OFPT_GET_CONFIG_REPLY,
1011 assert(sizeof *osc == sizeof dp->config);
1012 memcpy(((char *)osc) + sizeof osc->header,
1013 ((char *)&dp->config) + sizeof dp->config.header,
1014 sizeof dp->config - sizeof dp->config.header);
1016 return send_openflow_buffer(dp, buffer, sender);
1020 recv_set_config(struct datapath *dp, const struct sender *sender UNUSED,
1023 const struct ofp_switch_config *osc = msg;
1029 recv_packet_out(struct datapath *dp, const struct sender *sender UNUSED,
1032 const struct ofp_packet_out *opo = msg;
1034 if (ntohl(opo->buffer_id) == (uint32_t) -1) {
1035 /* FIXME: can we avoid copying data here? */
1036 int data_len = ntohs(opo->header.length) - sizeof *opo;
1037 struct buffer *buffer = buffer_new(data_len);
1038 buffer_put(buffer, opo->u.data, data_len);
1039 dp_output_port(dp, buffer,
1040 ntohs(opo->in_port), ntohs(opo->out_port));
1042 struct sw_flow_key key;
1043 struct buffer *buffer;
1046 buffer = retrieve_buffer(ntohl(opo->buffer_id));
1051 n_acts = (ntohs(opo->header.length) - sizeof *opo)
1052 / sizeof *opo->u.actions;
1053 flow_extract(buffer, ntohs(opo->in_port), &key.flow);
1054 execute_actions(dp, buffer, ntohs(opo->in_port),
1055 &key, opo->u.actions, n_acts);
1061 recv_port_mod(struct datapath *dp, const struct sender *sender UNUSED,
1064 const struct ofp_port_mod *opm = msg;
1066 dp_update_port_flags(dp, &opm->desc);
1072 add_flow(struct datapath *dp, const struct ofp_flow_mod *ofm)
1074 int error = -ENOMEM;
1077 struct sw_flow *flow;
1080 /* To prevent loops, make sure there's no action to send to the
1081 * OFP_TABLE virtual port.
1083 n_acts = (ntohs(ofm->header.length) - sizeof *ofm) / sizeof *ofm->actions;
1084 for (i=0; i<n_acts; i++) {
1085 const struct ofp_action *a = &ofm->actions[i];
1087 if (a->type == htons(OFPAT_OUTPUT)
1088 && a->arg.output.port == htons(OFPP_TABLE)) {
1089 /* xxx Send fancy new error message? */
1094 /* Allocate memory. */
1095 flow = flow_alloc(n_acts);
1099 /* Fill out flow. */
1100 flow_extract_match(&flow->key, &ofm->match);
1101 flow->max_idle = ntohs(ofm->max_idle);
1102 flow->priority = flow->key.wildcards ? ntohs(ofm->priority) : -1;
1103 flow->timeout = time(0) + flow->max_idle; /* FIXME */
1104 flow->n_actions = n_acts;
1105 flow->created = time(0); /* FIXME */
1106 flow->byte_count = 0;
1107 flow->packet_count = 0;
1108 memcpy(flow->actions, ofm->actions, n_acts * sizeof *flow->actions);
1111 error = chain_insert(dp->chain, flow);
1113 goto error_free_flow;
1116 if (ntohl(ofm->buffer_id) != UINT32_MAX) {
1117 struct buffer *buffer = retrieve_buffer(ntohl(ofm->buffer_id));
1119 struct sw_flow_key key;
1120 uint16_t in_port = ntohs(ofm->match.in_port);
1121 flow_used(flow, buffer);
1122 flow_extract(buffer, in_port, &key.flow);
1123 execute_actions(dp, buffer, in_port, &key, ofm->actions, n_acts);
1133 if (ntohl(ofm->buffer_id) != (uint32_t) -1)
1134 discard_buffer(ntohl(ofm->buffer_id));
1139 recv_flow(struct datapath *dp, const struct sender *sender UNUSED,
1142 const struct ofp_flow_mod *ofm = msg;
1143 uint16_t command = ntohs(ofm->command);
1145 if (command == OFPFC_ADD) {
1146 return add_flow(dp, ofm);
1147 } else if (command == OFPFC_DELETE) {
1148 struct sw_flow_key key;
1149 flow_extract_match(&key, &ofm->match);
1150 return chain_delete(dp->chain, &key, 0, 0) ? 0 : -ESRCH;
1151 } else if (command == OFPFC_DELETE_STRICT) {
1152 struct sw_flow_key key;
1154 flow_extract_match(&key, &ofm->match);
1155 priority = key.wildcards ? ntohs(ofm->priority) : -1;
1156 return chain_delete(dp->chain, &key, priority, 1) ? 0 : -ESRCH;
1162 struct flow_stats_state {
1164 struct sw_table_position position;
1165 struct ofp_flow_stats_request rq;
1168 struct buffer *buffer;
1171 #define MAX_FLOW_STATS_BYTES 4096
1173 static int flow_stats_init(struct datapath *dp, const void *body, int body_len,
1176 const struct ofp_flow_stats_request *fsr = body;
1177 struct flow_stats_state *s = xmalloc(sizeof *s);
1178 s->table_idx = fsr->table_id == 0xff ? 0 : fsr->table_id;
1179 memset(&s->position, 0, sizeof s->position);
1185 static int flow_stats_dump_callback(struct sw_flow *flow, void *private)
1187 struct flow_stats_state *s = private;
1188 fill_flow_stats(s->buffer, flow, s->table_idx, s->now);
1189 return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1192 static int flow_stats_dump(struct datapath *dp, void *state,
1193 struct buffer *buffer)
1195 struct flow_stats_state *s = state;
1196 struct sw_flow_key match_key;
1198 flow_extract_match(&match_key, &s->rq.match);
1201 while (s->table_idx < dp->chain->n_tables
1202 && (s->rq.table_id == 0xff || s->rq.table_id == s->table_idx))
1204 struct sw_table *table = dp->chain->tables[s->table_idx];
1206 if (table->iterate(table, &match_key, &s->position,
1207 flow_stats_dump_callback, s))
1211 memset(&s->position, 0, sizeof s->position);
1213 return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1216 static void flow_stats_done(void *state)
1221 struct aggregate_stats_state {
1222 struct ofp_aggregate_stats_request rq;
1225 static int aggregate_stats_init(struct datapath *dp,
1226 const void *body, int body_len,
1229 const struct ofp_aggregate_stats_request *rq = body;
1230 struct aggregate_stats_state *s = xmalloc(sizeof *s);
1236 static int aggregate_stats_dump_callback(struct sw_flow *flow, void *private)
1238 struct ofp_aggregate_stats_reply *rpy = private;
1239 rpy->packet_count += flow->packet_count;
1240 rpy->byte_count += flow->byte_count;
1245 static int aggregate_stats_dump(struct datapath *dp, void *state,
1246 struct buffer *buffer)
1248 struct aggregate_stats_state *s = state;
1249 struct ofp_aggregate_stats_request *rq = &s->rq;
1250 struct ofp_aggregate_stats_reply *rpy;
1251 struct sw_table_position position;
1252 struct sw_flow_key match_key;
1255 rpy = buffer_put_uninit(buffer, sizeof *rpy);
1256 memset(rpy, 0, sizeof *rpy);
1258 flow_extract_match(&match_key, &rq->match);
1259 table_idx = rq->table_id == 0xff ? 0 : rq->table_id;
1260 memset(&position, 0, sizeof position);
1261 while (table_idx < dp->chain->n_tables
1262 && (rq->table_id == 0xff || rq->table_id == table_idx))
1264 struct sw_table *table = dp->chain->tables[table_idx];
1267 error = table->iterate(table, &match_key, &position,
1268 aggregate_stats_dump_callback, rpy);
1273 memset(&position, 0, sizeof position);
1276 rpy->packet_count = htonll(rpy->packet_count);
1277 rpy->byte_count = htonll(rpy->byte_count);
1278 rpy->flow_count = htonl(rpy->flow_count);
1282 static void aggregate_stats_done(void *state)
1287 static int table_stats_dump(struct datapath *dp, void *state,
1288 struct buffer *buffer)
1291 for (i = 0; i < dp->chain->n_tables; i++) {
1292 struct ofp_table_stats *ots = buffer_put_uninit(buffer, sizeof *ots);
1293 struct sw_table_stats stats;
1294 dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
1295 strncpy(ots->name, stats.name, sizeof ots->name);
1297 memset(ots->pad, 0, sizeof ots->pad);
1298 ots->max_entries = htonl(stats.max_flows);
1299 ots->active_count = htonl(stats.n_flows);
1300 ots->matched_count = htonll(0); /* FIXME */
1305 struct port_stats_state {
1309 static int port_stats_init(struct datapath *dp, const void *body, int body_len,
1312 struct port_stats_state *s = xmalloc(sizeof *s);
1318 static int port_stats_dump(struct datapath *dp, void *state,
1319 struct buffer *buffer)
1321 struct port_stats_state *s = state;
1324 for (i = s->port; i < OFPP_MAX; i++) {
1325 struct sw_port *p = &dp->ports[i];
1326 struct ofp_port_stats *ops;
1330 ops = buffer_put_uninit(buffer, sizeof *ops);
1331 ops->port_no = htons(port_no(dp, p));
1332 memset(ops->pad, 0, sizeof ops->pad);
1333 ops->rx_count = htonll(p->rx_count);
1334 ops->tx_count = htonll(p->tx_count);
1335 ops->drop_count = htonll(p->drop_count);
1342 static void port_stats_done(void *state)
1348 /* Minimum and maximum acceptable number of bytes in body member of
1349 * struct ofp_stats_request. */
1350 size_t min_body, max_body;
1352 /* Prepares to dump some kind of statistics on 'dp'. 'body' and
1353 * 'body_len' are the 'body' member of the struct ofp_stats_request.
1354 * Returns zero if successful, otherwise a negative error code.
1355 * May initialize '*state' to state information. May be null if no
1356 * initialization is required.*/
1357 int (*init)(struct datapath *dp, const void *body, int body_len,
1360 /* Appends statistics for 'dp' to 'buffer', which initially contains a
1361 * struct ofp_stats_reply. On success, it should return 1 if it should be
1362 * called again later with another buffer, 0 if it is done, or a negative
1363 * errno value on failure. */
1364 int (*dump)(struct datapath *dp, void *state, struct buffer *buffer);
1366 /* Cleans any state created by the init or dump functions. May be null
1367 * if no cleanup is required. */
1368 void (*done)(void *state);
1371 static const struct stats_type stats[] = {
1373 sizeof(struct ofp_flow_stats_request),
1374 sizeof(struct ofp_flow_stats_request),
1379 [OFPST_AGGREGATE] = {
1380 sizeof(struct ofp_aggregate_stats_request),
1381 sizeof(struct ofp_aggregate_stats_request),
1382 aggregate_stats_init,
1383 aggregate_stats_dump,
1384 aggregate_stats_done
1402 struct stats_dump_cb {
1404 struct ofp_stats_request *rq;
1405 struct sender sender;
1406 const struct stats_type *s;
1411 stats_dump(struct datapath *dp, void *cb_)
1413 struct stats_dump_cb *cb = cb_;
1414 struct ofp_stats_reply *osr;
1415 struct buffer *buffer;
1422 osr = alloc_openflow_buffer(dp, sizeof *osr, OFPT_STATS_REPLY, &cb->sender,
1424 osr->type = htons(cb->s - stats);
1427 err = cb->s->dump(dp, cb->state, buffer);
1433 /* Buffer might have been reallocated, so find our data again. */
1434 osr = buffer_at_assert(buffer, 0, sizeof *osr);
1435 osr->flags = ntohs(OFPSF_REPLY_MORE);
1437 err2 = send_openflow_buffer(dp, buffer, &cb->sender);
1447 stats_done(void *cb_)
1449 struct stats_dump_cb *cb = cb_;
1452 cb->s->done(cb->state);
1459 recv_stats_request(struct datapath *dp, const struct sender *sender,
1462 const struct ofp_stats_request *rq = oh;
1463 size_t rq_len = ntohs(rq->header.length);
1464 struct stats_dump_cb *cb;
1468 type = ntohs(rq->type);
1469 if (type >= ARRAY_SIZE(stats) || !stats[type].dump) {
1470 VLOG_WARN("received stats request of unknown type %d", type);
1474 cb = xmalloc(sizeof *cb);
1476 cb->rq = xmemdup(rq, rq_len);
1477 cb->sender = *sender;
1478 cb->s = &stats[type];
1481 body_len = rq_len - offsetof(struct ofp_stats_request, body);
1482 if (body_len < cb->s->min_body || body_len > cb->s->max_body) {
1483 VLOG_WARN("stats request type %d with bad body length %d",
1490 err = cb->s->init(dp, rq->body, body_len, &cb->state);
1492 VLOG_WARN("failed initialization of stats request type %d: %s",
1493 type, strerror(-err));
1498 remote_start_dump(sender->remote, stats_dump, stats_done, cb);
1507 /* 'msg', which is 'length' bytes long, was received from the control path.
1508 * Apply it to 'chain'. */
1510 fwd_control_input(struct datapath *dp, const struct sender *sender,
1511 const void *msg, size_t length)
1513 struct openflow_packet {
1515 int (*handler)(struct datapath *, const struct sender *, const void *);
1518 static const struct openflow_packet packets[] = {
1519 [OFPT_FEATURES_REQUEST] = {
1520 sizeof (struct ofp_header),
1521 recv_features_request,
1523 [OFPT_GET_CONFIG_REQUEST] = {
1524 sizeof (struct ofp_header),
1525 recv_get_config_request,
1527 [OFPT_SET_CONFIG] = {
1528 sizeof (struct ofp_switch_config),
1531 [OFPT_PACKET_OUT] = {
1532 sizeof (struct ofp_packet_out),
1536 sizeof (struct ofp_flow_mod),
1540 sizeof (struct ofp_port_mod),
1543 [OFPT_STATS_REQUEST] = {
1544 sizeof (struct ofp_stats_request),
1549 const struct openflow_packet *pkt;
1550 struct ofp_header *oh;
1552 oh = (struct ofp_header *) msg;
1553 if (oh->version != OFP_VERSION || oh->type >= ARRAY_SIZE(packets)
1554 || ntohs(oh->length) > length)
1557 pkt = &packets[oh->type];
1560 if (length < pkt->min_size)
1563 return pkt->handler(dp, sender, msg);
1566 /* Packet buffering. */
1568 #define OVERWRITE_SECS 1
1570 struct packet_buffer {
1571 struct buffer *buffer;
1576 static struct packet_buffer buffers[N_PKT_BUFFERS];
1577 static unsigned int buffer_idx;
1579 uint32_t save_buffer(struct buffer *buffer)
1581 struct packet_buffer *p;
1584 buffer_idx = (buffer_idx + 1) & PKT_BUFFER_MASK;
1585 p = &buffers[buffer_idx];
1587 /* Don't buffer packet if existing entry is less than
1588 * OVERWRITE_SECS old. */
1589 if (time(0) < p->timeout) { /* FIXME */
1592 buffer_delete(p->buffer);
1595 /* Don't use maximum cookie value since the all-bits-1 id is
1597 if (++p->cookie >= (1u << PKT_COOKIE_BITS) - 1)
1599 p->buffer = buffer_clone(buffer); /* FIXME */
1600 p->timeout = time(0) + OVERWRITE_SECS; /* FIXME */
1601 id = buffer_idx | (p->cookie << PKT_BUFFER_BITS);
1606 static struct buffer *retrieve_buffer(uint32_t id)
1608 struct buffer *buffer = NULL;
1609 struct packet_buffer *p;
1611 p = &buffers[id & PKT_BUFFER_MASK];
1612 if (p->cookie == id >> PKT_BUFFER_BITS) {
1616 printf("cookie mismatch: %x != %x\n",
1617 id >> PKT_BUFFER_BITS, p->cookie);
1623 static void discard_buffer(uint32_t id)
1625 struct packet_buffer *p;
1627 p = &buffers[id & PKT_BUFFER_MASK];
1628 if (p->cookie == id >> PKT_BUFFER_BITS) {
1629 buffer_delete(p->buffer);