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 and returns a random datapath id. */
172 gen_datapath_id(void)
174 uint8_t ea[ETH_ADDR_LEN];
176 return eth_addr_to_uint64(ea);
180 dp_new(struct datapath **dp_, uint64_t dpid, struct rconn *rconn)
184 dp = calloc(1, sizeof *dp);
189 dp->last_timeout = time(0);
190 list_init(&dp->remotes);
191 dp->controller = remote_create(dp, rconn);
192 dp->listen_vconn = NULL;
193 dp->id = dpid <= UINT64_C(0xffffffffffff) ? dpid : gen_datapath_id();
194 dp->chain = chain_create();
196 VLOG_ERR("could not create chain");
201 list_init(&dp->port_list);
202 dp->config.flags = 0;
203 dp->config.miss_send_len = htons(OFP_DEFAULT_MISS_SEND_LEN);
209 dp_add_port(struct datapath *dp, const char *name)
211 struct netdev *netdev;
217 error = netdev_open(name, &netdev);
221 error = netdev_set_flags(netdev, NETDEV_UP | NETDEV_PROMISC);
223 VLOG_ERR("Couldn't set promiscuous mode on %s device", name);
224 netdev_close(netdev);
227 if (netdev_get_in4(netdev, &in4)) {
228 VLOG_ERR("%s device has assigned IP address %s", name, inet_ntoa(in4));
230 if (netdev_get_in6(netdev, &in6)) {
231 char in6_name[INET6_ADDRSTRLEN + 1];
232 inet_ntop(AF_INET6, &in6, in6_name, sizeof in6_name);
233 VLOG_ERR("%s device has assigned IPv6 address %s", name, in6_name);
236 for (p = dp->ports; ; p++) {
237 if (p >= &dp->ports[ARRAY_SIZE(dp->ports)]) {
239 } else if (!p->netdev) {
249 list_push_back(&dp->port_list, &p->node);
251 /* Notify the ctlpath that this port has been added */
252 send_port_status(p, OFPPR_ADD);
258 dp_add_listen_vconn(struct datapath *dp, struct vconn *listen_vconn)
260 assert(!dp->listen_vconn);
261 dp->listen_vconn = listen_vconn;
265 dp_run(struct datapath *dp)
267 time_t now = time(0);
268 struct sw_port *p, *pn;
269 struct remote *r, *rn;
270 struct buffer *buffer = NULL;
272 if (now != dp->last_timeout) {
273 struct list deleted = LIST_INITIALIZER(&deleted);
274 struct sw_flow *f, *n;
276 chain_timeout(dp->chain, &deleted);
277 LIST_FOR_EACH_SAFE (f, n, struct sw_flow, node, &deleted) {
278 send_flow_expired(dp, f);
279 list_remove(&f->node);
282 dp->last_timeout = now;
284 poll_timer_wait(1000);
286 LIST_FOR_EACH_SAFE (p, pn, struct sw_port, node, &dp->port_list) {
290 /* Allocate buffer with some headroom to add headers in forwarding
291 * to the controller or adding a vlan tag, plus an extra 2 bytes to
292 * allow IP headers to be aligned on a 4-byte boundary. */
293 const int headroom = 128 + 2;
294 const int hard_header = VLAN_ETH_HEADER_LEN;
295 const int mtu = netdev_get_mtu(p->netdev);
296 buffer = buffer_new(headroom + hard_header + mtu);
297 buffer->data += headroom;
299 error = netdev_recv(p->netdev, buffer);
302 fwd_port_input(dp, buffer, port_no(dp, p));
304 } else if (error != EAGAIN) {
305 VLOG_ERR("Error receiving data from %s: %s",
306 netdev_get_name(p->netdev), strerror(error));
310 buffer_delete(buffer);
312 /* Talk to remotes. */
313 LIST_FOR_EACH_SAFE (r, rn, struct remote, node, &dp->remotes) {
316 if (dp->listen_vconn) {
318 struct vconn *new_vconn;
321 retval = vconn_accept(dp->listen_vconn, &new_vconn);
323 if (retval != EAGAIN) {
324 VLOG_WARN("accept failed (%s)", strerror(retval));
328 remote_create(dp, rconn_new_from_vconn("passive", 128, new_vconn));
334 remote_run(struct datapath *dp, struct remote *r)
340 /* Do some remote processing, but cap it at a reasonable amount so that
341 * other processing doesn't starve. */
342 for (i = 0; i < 50; i++) {
344 struct buffer *buffer;
345 struct ofp_header *oh;
347 buffer = rconn_recv(r->rconn);
352 if (buffer->size >= sizeof *oh) {
353 struct sender sender;
357 sender.xid = oh->xid;
358 fwd_control_input(dp, &sender, buffer->data, buffer->size);
360 VLOG_WARN("received too-short OpenFlow message");
362 buffer_delete(buffer);
364 if (!rconn_is_full(r->rconn)) {
365 int error = r->cb_dump(dp, r->cb_aux);
368 VLOG_WARN("dump callback error: %s", strerror(-error));
370 r->cb_done(r->cb_aux);
379 if (!rconn_is_alive(r->rconn)) {
385 remote_wait(struct remote *r)
387 rconn_run_wait(r->rconn);
388 rconn_recv_wait(r->rconn);
392 remote_destroy(struct remote *r)
395 if (r->cb_dump && r->cb_done) {
396 r->cb_done(r->cb_aux);
398 list_remove(&r->node);
399 rconn_destroy(r->rconn);
404 static struct remote *
405 remote_create(struct datapath *dp, struct rconn *rconn)
407 struct remote *remote = xmalloc(sizeof *remote);
408 list_push_back(&dp->remotes, &remote->node);
409 remote->rconn = rconn;
410 remote->cb_dump = NULL;
414 /* Starts a callback-based, reliable, possibly multi-message reply to a
415 * request made by 'remote'.
417 * 'dump' designates a function that will be called when the 'remote' send
418 * queue has an empty slot. It should compose a message and send it on
419 * 'remote'. On success, it should return 1 if it should be called again when
420 * another send queue slot opens up, 0 if its transmissions are complete, or a
421 * negative errno value on failure.
423 * 'done' designates a function to clean up any resources allocated for the
424 * dump. It must handle being called before the dump is complete (which will
425 * happen if 'remote' is closed unexpectedly).
427 * 'aux' is passed to 'dump' and 'done'. */
429 remote_start_dump(struct remote *remote,
430 int (*dump)(struct datapath *, void *),
431 void (*done)(void *),
434 assert(!remote->cb_dump);
435 remote->cb_dump = dump;
436 remote->cb_done = done;
437 remote->cb_aux = aux;
441 dp_wait(struct datapath *dp)
446 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
447 netdev_recv_wait(p->netdev);
449 LIST_FOR_EACH (r, struct remote, node, &dp->remotes) {
452 if (dp->listen_vconn) {
453 vconn_accept_wait(dp->listen_vconn);
457 /* Delete 'p' from switch. */
459 del_switch_port(struct sw_port *p)
461 send_port_status(p, OFPPR_DELETE);
462 netdev_close(p->netdev);
464 list_remove(&p->node);
468 dp_destroy(struct datapath *dp)
470 struct sw_port *p, *n;
476 LIST_FOR_EACH_SAFE (p, n, struct sw_port, node, &dp->port_list) {
479 chain_destroy(dp->chain);
483 /* Send packets out all the ports except the originating one. If the
484 * "flood" argument is set, don't send out ports with flooding disabled.
487 output_all(struct datapath *dp, struct buffer *buffer, int in_port, int flood)
493 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
494 if (port_no(dp, p) == in_port) {
497 if (flood && p->flags & BRIDGE_PORT_NO_FLOOD) {
500 if (prev_port != -1) {
501 dp_output_port(dp, buffer_clone(buffer), in_port, prev_port);
503 prev_port = port_no(dp, p);
506 dp_output_port(dp, buffer, in_port, prev_port);
508 buffer_delete(buffer);
514 output_packet(struct datapath *dp, struct buffer *buffer, int out_port)
516 if (out_port >= 0 && out_port < OFPP_MAX) {
517 struct sw_port *p = &dp->ports[out_port];
518 if (p->netdev != NULL) {
519 if (!netdev_send(p->netdev, buffer)) {
528 buffer_delete(buffer);
529 /* FIXME: ratelimit */
530 VLOG_DBG("can't forward to bad port %d\n", out_port);
533 /* Takes ownership of 'buffer' and transmits it to 'out_port' on 'dp'.
536 dp_output_port(struct datapath *dp, struct buffer *buffer,
537 int in_port, int out_port)
541 if (out_port == OFPP_FLOOD) {
542 output_all(dp, buffer, in_port, 1);
543 } else if (out_port == OFPP_ALL) {
544 output_all(dp, buffer, in_port, 0);
545 } else if (out_port == OFPP_CONTROLLER) {
546 dp_output_control(dp, buffer, in_port, 0, OFPR_ACTION);
547 } else if (out_port == OFPP_TABLE) {
548 struct sw_flow_key key;
549 struct sw_flow *flow;
552 flow_extract(buffer, in_port, &key.flow);
553 flow = chain_lookup(dp->chain, &key);
555 flow_used(flow, buffer);
556 execute_actions(dp, buffer, in_port, &key,
557 flow->actions, flow->n_actions);
560 output_packet(dp, buffer, out_port);
565 alloc_openflow_buffer(struct datapath *dp, size_t openflow_len, uint8_t type,
566 const struct sender *sender, struct buffer **bufferp)
568 struct buffer *buffer;
569 struct ofp_header *oh;
571 buffer = *bufferp = buffer_new(openflow_len);
572 oh = buffer_put_uninit(buffer, openflow_len);
573 oh->version = OFP_VERSION;
575 oh->length = 0; /* Filled in by send_openflow_buffer(). */
576 oh->xid = sender ? sender->xid : 0;
581 send_openflow_buffer(struct datapath *dp, struct buffer *buffer,
582 const struct sender *sender)
584 struct remote *remote = sender ? sender->remote : dp->controller;
585 struct rconn *rconn = remote->rconn;
586 struct ofp_header *oh;
589 oh = buffer_at_assert(buffer, 0, sizeof *oh);
590 oh->length = htons(buffer->size);
592 retval = rconn_send(rconn, buffer);
594 VLOG_WARN("send to %s failed: %s",
595 rconn_get_name(rconn), strerror(retval));
596 buffer_delete(buffer);
601 /* Takes ownership of 'buffer' and transmits it to 'dp''s controller. If the
602 * packet can be saved in a buffer, then only the first max_len bytes of
603 * 'buffer' are sent; otherwise, all of 'buffer' is sent. 'reason' indicates
604 * why 'buffer' is being sent. 'max_len' sets the maximum number of bytes that
605 * the caller wants to be sent; a value of 0 indicates the entire packet should
608 dp_output_control(struct datapath *dp, struct buffer *buffer, int in_port,
609 size_t max_len, int reason)
611 struct ofp_packet_in *opi;
615 buffer_id = save_buffer(buffer);
616 total_len = buffer->size;
617 if (buffer_id != UINT32_MAX && buffer->size > max_len) {
618 buffer->size = max_len;
621 opi = buffer_push_uninit(buffer, offsetof(struct ofp_packet_in, data));
622 opi->header.version = OFP_VERSION;
623 opi->header.type = OFPT_PACKET_IN;
624 opi->header.length = htons(buffer->size);
625 opi->header.xid = htonl(0);
626 opi->buffer_id = htonl(buffer_id);
627 opi->total_len = htons(total_len);
628 opi->in_port = htons(in_port);
629 opi->reason = reason;
631 send_openflow_buffer(dp, buffer, NULL);
634 static void fill_port_desc(struct datapath *dp, struct sw_port *p,
635 struct ofp_phy_port *desc)
637 desc->port_no = htons(port_no(dp, p));
638 strncpy((char *) desc->name, netdev_get_name(p->netdev),
640 desc->name[sizeof desc->name - 1] = '\0';
641 memcpy(desc->hw_addr, netdev_get_etheraddr(p->netdev), ETH_ADDR_LEN);
642 desc->flags = htonl(p->flags);
643 desc->features = htonl(netdev_get_features(p->netdev));
644 desc->speed = htonl(netdev_get_speed(p->netdev));
648 dp_send_features_reply(struct datapath *dp, const struct sender *sender)
650 struct buffer *buffer;
651 struct ofp_switch_features *ofr;
654 ofr = alloc_openflow_buffer(dp, sizeof *ofr, OFPT_FEATURES_REPLY,
656 ofr->datapath_id = htonll(dp->id);
657 ofr->n_exact = htonl(2 * TABLE_HASH_MAX_FLOWS);
658 ofr->n_compression = 0; /* Not supported */
659 ofr->n_general = htonl(TABLE_LINEAR_MAX_FLOWS);
660 ofr->buffer_mb = htonl(UINT32_MAX);
661 ofr->n_buffers = htonl(N_PKT_BUFFERS);
662 ofr->capabilities = htonl(OFP_SUPPORTED_CAPABILITIES);
663 ofr->actions = htonl(OFP_SUPPORTED_ACTIONS);
664 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
665 struct ofp_phy_port *opp = buffer_put_uninit(buffer, sizeof *opp);
666 memset(opp, 0, sizeof *opp);
667 fill_port_desc(dp, p, opp);
669 send_openflow_buffer(dp, buffer, sender);
673 dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp)
675 int port_no = ntohs(opp->port_no);
676 if (port_no < OFPP_MAX) {
677 struct sw_port *p = &dp->ports[port_no];
679 /* Make sure the port id hasn't changed since this was sent */
680 if (!p || memcmp(opp->hw_addr, netdev_get_etheraddr(p->netdev),
681 ETH_ADDR_LEN) != 0) {
684 p->flags = htonl(opp->flags);
689 send_port_status(struct sw_port *p, uint8_t status)
691 struct buffer *buffer;
692 struct ofp_port_status *ops;
693 ops = alloc_openflow_buffer(p->dp, sizeof *ops, OFPT_PORT_STATUS, NULL,
695 ops->reason = status;
696 memset(ops->pad, 0, sizeof ops->pad);
697 fill_port_desc(p->dp, p, &ops->desc);
699 send_openflow_buffer(p->dp, buffer, NULL);
703 send_flow_expired(struct datapath *dp, struct sw_flow *flow)
705 struct buffer *buffer;
706 struct ofp_flow_expired *ofe;
707 ofe = alloc_openflow_buffer(dp, sizeof *ofe, OFPT_FLOW_EXPIRED, NULL,
709 flow_fill_match(&ofe->match, &flow->key);
711 memset(ofe->pad, 0, sizeof ofe->pad);
712 ofe->priority = htons(flow->priority);
714 ofe->duration = htonl(flow->timeout - flow->max_idle - flow->created);
715 ofe->packet_count = htonll(flow->packet_count);
716 ofe->byte_count = htonll(flow->byte_count);
717 send_openflow_buffer(dp, buffer, NULL);
721 dp_send_error_msg(struct datapath *dp, const struct sender *sender,
722 uint16_t type, uint16_t code, const uint8_t *data, size_t len)
724 struct buffer *buffer;
725 struct ofp_error_msg *oem;
726 oem = alloc_openflow_buffer(dp, sizeof(*oem)+len, OFPT_ERROR_MSG,
728 oem->type = htons(type);
729 oem->code = htons(code);
730 memcpy(oem->data, data, len);
731 send_openflow_buffer(dp, buffer, sender);
735 fill_flow_stats(struct buffer *buffer, struct sw_flow *flow,
736 int table_idx, time_t now)
738 struct ofp_flow_stats *ofs;
739 int length = sizeof *ofs + sizeof *ofs->actions * flow->n_actions;
740 ofs = buffer_put_uninit(buffer, length);
741 ofs->length = htons(length);
742 ofs->table_id = table_idx;
744 ofs->match.wildcards = htons(flow->key.wildcards);
745 ofs->match.in_port = flow->key.flow.in_port;
746 memcpy(ofs->match.dl_src, flow->key.flow.dl_src, ETH_ADDR_LEN);
747 memcpy(ofs->match.dl_dst, flow->key.flow.dl_dst, ETH_ADDR_LEN);
748 ofs->match.dl_vlan = flow->key.flow.dl_vlan;
749 ofs->match.dl_type = flow->key.flow.dl_type;
750 ofs->match.nw_src = flow->key.flow.nw_src;
751 ofs->match.nw_dst = flow->key.flow.nw_dst;
752 ofs->match.nw_proto = flow->key.flow.nw_proto;
753 memset(ofs->match.pad, 0, sizeof ofs->match.pad);
754 ofs->match.tp_src = flow->key.flow.tp_src;
755 ofs->match.tp_dst = flow->key.flow.tp_dst;
756 ofs->duration = htonl(now - flow->created);
757 ofs->packet_count = htonll(flow->packet_count);
758 ofs->byte_count = htonll(flow->byte_count);
759 ofs->priority = htons(flow->priority);
760 ofs->max_idle = htons(flow->max_idle);
761 memcpy(ofs->actions, flow->actions,
762 sizeof *ofs->actions * flow->n_actions);
766 /* 'buffer' was received on 'in_port', a physical switch port between 0 and
767 * OFPP_MAX. Process it according to 'chain'. */
768 void fwd_port_input(struct datapath *dp, struct buffer *buffer, int in_port)
770 struct sw_flow_key key;
771 struct sw_flow *flow;
774 flow_extract(buffer, in_port, &key.flow);
775 flow = chain_lookup(dp->chain, &key);
777 flow_used(flow, buffer);
778 execute_actions(dp, buffer, in_port, &key,
779 flow->actions, flow->n_actions);
781 dp_output_control(dp, buffer, in_port, ntohs(dp->config.miss_send_len),
787 do_output(struct datapath *dp, struct buffer *buffer, int in_port,
788 size_t max_len, int out_port)
790 if (out_port != OFPP_CONTROLLER) {
791 dp_output_port(dp, buffer, in_port, out_port);
793 dp_output_control(dp, buffer, in_port, max_len, OFPR_ACTION);
798 execute_actions(struct datapath *dp, struct buffer *buffer,
799 int in_port, const struct sw_flow_key *key,
800 const struct ofp_action *actions, int n_actions)
802 /* Every output action needs a separate clone of 'buffer', but the common
803 * case is just a single output action, so that doing a clone and then
804 * freeing the original buffer is wasteful. So the following code is
805 * slightly obscure just to avoid that. */
807 size_t max_len=0; /* Initialze to make compiler happy */
812 eth_proto = ntohs(key->flow.dl_type);
814 for (i = 0; i < n_actions; i++) {
815 const struct ofp_action *a = &actions[i];
816 struct eth_header *eh = buffer->l2;
818 if (prev_port != -1) {
819 do_output(dp, buffer_clone(buffer), in_port, max_len, prev_port);
823 switch (ntohs(a->type)) {
825 prev_port = ntohs(a->arg.output.port);
826 max_len = ntohs(a->arg.output.max_len);
829 case OFPAT_SET_DL_VLAN:
830 modify_vlan(buffer, key, a);
833 case OFPAT_SET_DL_SRC:
834 memcpy(eh->eth_src, a->arg.dl_addr, sizeof eh->eth_src);
837 case OFPAT_SET_DL_DST:
838 memcpy(eh->eth_dst, a->arg.dl_addr, sizeof eh->eth_dst);
841 case OFPAT_SET_NW_SRC:
842 case OFPAT_SET_NW_DST:
843 modify_nh(buffer, eth_proto, key->flow.nw_proto, a);
846 case OFPAT_SET_TP_SRC:
847 case OFPAT_SET_TP_DST:
848 modify_th(buffer, eth_proto, key->flow.nw_proto, a);
856 do_output(dp, buffer, in_port, max_len, prev_port);
858 buffer_delete(buffer);
861 /* Returns the new checksum for a packet in which the checksum field previously
862 * contained 'old_csum' and in which a field that contained 'old_u16' was
863 * changed to contain 'new_u16'. */
865 recalc_csum16(uint16_t old_csum, uint16_t old_u16, uint16_t new_u16)
867 /* Ones-complement arithmetic is endian-independent, so this code does not
868 * use htons() or ntohs().
870 * See RFC 1624 for formula and explanation. */
871 uint16_t hc_complement = ~old_csum;
872 uint16_t m_complement = ~old_u16;
873 uint16_t m_prime = new_u16;
874 uint32_t sum = hc_complement + m_complement + m_prime;
875 uint16_t hc_prime_complement = sum + (sum >> 16);
876 return ~hc_prime_complement;
879 /* Returns the new checksum for a packet in which the checksum field previously
880 * contained 'old_csum' and in which a field that contained 'old_u32' was
881 * changed to contain 'new_u32'. */
883 recalc_csum32(uint16_t old_csum, uint32_t old_u32, uint32_t new_u32)
885 return recalc_csum16(recalc_csum16(old_csum, old_u32, new_u32),
886 old_u32 >> 16, new_u32 >> 16);
889 static void modify_nh(struct buffer *buffer, uint16_t eth_proto,
890 uint8_t nw_proto, const struct ofp_action *a)
892 if (eth_proto == ETH_TYPE_IP) {
893 struct ip_header *nh = buffer->l3;
894 uint32_t new, *field;
896 new = a->arg.nw_addr;
897 field = a->type == OFPAT_SET_NW_SRC ? &nh->ip_src : &nh->ip_dst;
898 if (nw_proto == IP_TYPE_TCP) {
899 struct tcp_header *th = buffer->l4;
900 th->tcp_csum = recalc_csum32(th->tcp_csum, *field, new);
901 } else if (nw_proto == IP_TYPE_UDP) {
902 struct udp_header *th = buffer->l4;
904 th->udp_csum = recalc_csum32(th->udp_csum, *field, new);
906 th->udp_csum = 0xffff;
910 nh->ip_csum = recalc_csum32(nh->ip_csum, *field, new);
915 static void modify_th(struct buffer *buffer, uint16_t eth_proto,
916 uint8_t nw_proto, const struct ofp_action *a)
918 if (eth_proto == ETH_TYPE_IP) {
919 uint16_t new, *field;
923 if (nw_proto == IP_TYPE_TCP) {
924 struct tcp_header *th = buffer->l4;
925 field = a->type == OFPAT_SET_TP_SRC ? &th->tcp_src : &th->tcp_dst;
926 th->tcp_csum = recalc_csum16(th->tcp_csum, *field, new);
928 } else if (nw_proto == IP_TYPE_UDP) {
929 struct udp_header *th = buffer->l4;
930 field = a->type == OFPAT_SET_TP_SRC ? &th->udp_src : &th->udp_dst;
931 th->udp_csum = recalc_csum16(th->udp_csum, *field, new);
938 modify_vlan(struct buffer *buffer,
939 const struct sw_flow_key *key, const struct ofp_action *a)
941 uint16_t new_id = a->arg.vlan_id;
942 struct vlan_eth_header *veh;
944 if (new_id != htons(OFP_VLAN_NONE)) {
945 if (key->flow.dl_vlan != htons(OFP_VLAN_NONE)) {
946 /* Modify vlan id, but maintain other TCI values */
948 veh->veth_tci &= ~htons(VLAN_VID);
949 veh->veth_tci |= new_id;
951 /* Insert new vlan id. */
952 struct eth_header *eh = buffer->l2;
953 struct vlan_eth_header tmp;
954 memcpy(tmp.veth_dst, eh->eth_dst, ETH_ADDR_LEN);
955 memcpy(tmp.veth_src, eh->eth_src, ETH_ADDR_LEN);
956 tmp.veth_type = htons(ETH_TYPE_VLAN);
957 tmp.veth_tci = new_id;
958 tmp.veth_next_type = eh->eth_type;
960 veh = buffer_push_uninit(buffer, VLAN_HEADER_LEN);
961 memcpy(veh, &tmp, sizeof tmp);
962 buffer->l2 -= VLAN_HEADER_LEN;
965 /* Remove an existing vlan header if it exists */
967 if (veh->veth_type == htons(ETH_TYPE_VLAN)) {
968 struct eth_header tmp;
970 memcpy(tmp.eth_dst, veh->veth_dst, ETH_ADDR_LEN);
971 memcpy(tmp.eth_src, veh->veth_src, ETH_ADDR_LEN);
972 tmp.eth_type = veh->veth_next_type;
974 buffer->size -= VLAN_HEADER_LEN;
975 buffer->data += VLAN_HEADER_LEN;
976 buffer->l2 += VLAN_HEADER_LEN;
977 memcpy(buffer->data, &tmp, sizeof tmp);
983 recv_features_request(struct datapath *dp, const struct sender *sender,
986 dp_send_features_reply(dp, sender);
991 recv_get_config_request(struct datapath *dp, const struct sender *sender,
994 struct buffer *buffer;
995 struct ofp_switch_config *osc;
997 osc = alloc_openflow_buffer(dp, sizeof *osc, OFPT_GET_CONFIG_REPLY,
1000 assert(sizeof *osc == sizeof dp->config);
1001 memcpy(((char *)osc) + sizeof osc->header,
1002 ((char *)&dp->config) + sizeof dp->config.header,
1003 sizeof dp->config - sizeof dp->config.header);
1005 return send_openflow_buffer(dp, buffer, sender);
1009 recv_set_config(struct datapath *dp, const struct sender *sender UNUSED,
1012 const struct ofp_switch_config *osc = msg;
1018 recv_packet_out(struct datapath *dp, const struct sender *sender UNUSED,
1021 const struct ofp_packet_out *opo = msg;
1023 if (ntohl(opo->buffer_id) == (uint32_t) -1) {
1024 /* FIXME: can we avoid copying data here? */
1025 int data_len = ntohs(opo->header.length) - sizeof *opo;
1026 struct buffer *buffer = buffer_new(data_len);
1027 buffer_put(buffer, opo->u.data, data_len);
1028 dp_output_port(dp, buffer,
1029 ntohs(opo->in_port), ntohs(opo->out_port));
1031 struct sw_flow_key key;
1032 struct buffer *buffer;
1035 buffer = retrieve_buffer(ntohl(opo->buffer_id));
1040 n_acts = (ntohs(opo->header.length) - sizeof *opo)
1041 / sizeof *opo->u.actions;
1042 flow_extract(buffer, ntohs(opo->in_port), &key.flow);
1043 execute_actions(dp, buffer, ntohs(opo->in_port),
1044 &key, opo->u.actions, n_acts);
1050 recv_port_mod(struct datapath *dp, const struct sender *sender UNUSED,
1053 const struct ofp_port_mod *opm = msg;
1055 dp_update_port_flags(dp, &opm->desc);
1061 add_flow(struct datapath *dp, const struct ofp_flow_mod *ofm)
1063 int error = -ENOMEM;
1066 struct sw_flow *flow;
1069 /* To prevent loops, make sure there's no action to send to the
1070 * OFP_TABLE virtual port.
1072 n_acts = (ntohs(ofm->header.length) - sizeof *ofm) / sizeof *ofm->actions;
1073 for (i=0; i<n_acts; i++) {
1074 const struct ofp_action *a = &ofm->actions[i];
1076 if (a->type == htons(OFPAT_OUTPUT)
1077 && (a->arg.output.port == htons(OFPP_TABLE)
1078 || a->arg.output.port == htons(OFPP_NONE))) {
1079 /* xxx Send fancy new error message? */
1084 /* Allocate memory. */
1085 flow = flow_alloc(n_acts);
1089 /* Fill out flow. */
1090 flow_extract_match(&flow->key, &ofm->match);
1091 flow->max_idle = ntohs(ofm->max_idle);
1092 flow->priority = flow->key.wildcards ? ntohs(ofm->priority) : -1;
1093 flow->timeout = time(0) + flow->max_idle; /* FIXME */
1094 flow->n_actions = n_acts;
1095 flow->created = time(0); /* FIXME */
1096 flow->byte_count = 0;
1097 flow->packet_count = 0;
1098 memcpy(flow->actions, ofm->actions, n_acts * sizeof *flow->actions);
1101 error = chain_insert(dp->chain, flow);
1103 goto error_free_flow;
1106 if (ntohl(ofm->buffer_id) != UINT32_MAX) {
1107 struct buffer *buffer = retrieve_buffer(ntohl(ofm->buffer_id));
1109 struct sw_flow_key key;
1110 uint16_t in_port = ntohs(ofm->match.in_port);
1111 flow_used(flow, buffer);
1112 flow_extract(buffer, in_port, &key.flow);
1113 execute_actions(dp, buffer, in_port, &key, ofm->actions, n_acts);
1123 if (ntohl(ofm->buffer_id) != (uint32_t) -1)
1124 discard_buffer(ntohl(ofm->buffer_id));
1129 recv_flow(struct datapath *dp, const struct sender *sender UNUSED,
1132 const struct ofp_flow_mod *ofm = msg;
1133 uint16_t command = ntohs(ofm->command);
1135 if (command == OFPFC_ADD) {
1136 return add_flow(dp, ofm);
1137 } else if (command == OFPFC_DELETE) {
1138 struct sw_flow_key key;
1139 flow_extract_match(&key, &ofm->match);
1140 return chain_delete(dp->chain, &key, 0, 0) ? 0 : -ESRCH;
1141 } else if (command == OFPFC_DELETE_STRICT) {
1142 struct sw_flow_key key;
1144 flow_extract_match(&key, &ofm->match);
1145 priority = key.wildcards ? ntohs(ofm->priority) : -1;
1146 return chain_delete(dp->chain, &key, priority, 1) ? 0 : -ESRCH;
1152 struct flow_stats_state {
1154 struct sw_table_position position;
1155 struct ofp_flow_stats_request rq;
1158 struct buffer *buffer;
1161 #define MAX_FLOW_STATS_BYTES 4096
1163 static int flow_stats_init(struct datapath *dp, const void *body, int body_len,
1166 const struct ofp_flow_stats_request *fsr = body;
1167 struct flow_stats_state *s = xmalloc(sizeof *s);
1168 s->table_idx = fsr->table_id == 0xff ? 0 : fsr->table_id;
1169 memset(&s->position, 0, sizeof s->position);
1175 static int flow_stats_dump_callback(struct sw_flow *flow, void *private)
1177 struct flow_stats_state *s = private;
1178 fill_flow_stats(s->buffer, flow, s->table_idx, s->now);
1179 return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1182 static int flow_stats_dump(struct datapath *dp, void *state,
1183 struct buffer *buffer)
1185 struct flow_stats_state *s = state;
1186 struct sw_flow_key match_key;
1188 flow_extract_match(&match_key, &s->rq.match);
1191 while (s->table_idx < dp->chain->n_tables
1192 && (s->rq.table_id == 0xff || s->rq.table_id == s->table_idx))
1194 struct sw_table *table = dp->chain->tables[s->table_idx];
1196 if (table->iterate(table, &match_key, &s->position,
1197 flow_stats_dump_callback, s))
1201 memset(&s->position, 0, sizeof s->position);
1203 return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1206 static void flow_stats_done(void *state)
1211 struct aggregate_stats_state {
1212 struct ofp_aggregate_stats_request rq;
1215 static int aggregate_stats_init(struct datapath *dp,
1216 const void *body, int body_len,
1219 const struct ofp_aggregate_stats_request *rq = body;
1220 struct aggregate_stats_state *s = xmalloc(sizeof *s);
1226 static int aggregate_stats_dump_callback(struct sw_flow *flow, void *private)
1228 struct ofp_aggregate_stats_reply *rpy = private;
1229 rpy->packet_count += flow->packet_count;
1230 rpy->byte_count += flow->byte_count;
1235 static int aggregate_stats_dump(struct datapath *dp, void *state,
1236 struct buffer *buffer)
1238 struct aggregate_stats_state *s = state;
1239 struct ofp_aggregate_stats_request *rq = &s->rq;
1240 struct ofp_aggregate_stats_reply *rpy;
1241 struct sw_table_position position;
1242 struct sw_flow_key match_key;
1245 rpy = buffer_put_uninit(buffer, sizeof *rpy);
1246 memset(rpy, 0, sizeof *rpy);
1248 flow_extract_match(&match_key, &rq->match);
1249 table_idx = rq->table_id == 0xff ? 0 : rq->table_id;
1250 memset(&position, 0, sizeof position);
1251 while (table_idx < dp->chain->n_tables
1252 && (rq->table_id == 0xff || rq->table_id == table_idx))
1254 struct sw_table *table = dp->chain->tables[table_idx];
1257 error = table->iterate(table, &match_key, &position,
1258 aggregate_stats_dump_callback, rpy);
1263 memset(&position, 0, sizeof position);
1266 rpy->packet_count = htonll(rpy->packet_count);
1267 rpy->byte_count = htonll(rpy->byte_count);
1268 rpy->flow_count = htonl(rpy->flow_count);
1272 static void aggregate_stats_done(void *state)
1277 static int table_stats_dump(struct datapath *dp, void *state,
1278 struct buffer *buffer)
1281 for (i = 0; i < dp->chain->n_tables; i++) {
1282 struct ofp_table_stats *ots = buffer_put_uninit(buffer, sizeof *ots);
1283 struct sw_table_stats stats;
1284 dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
1285 strncpy(ots->name, stats.name, sizeof ots->name);
1287 memset(ots->pad, 0, sizeof ots->pad);
1288 ots->max_entries = htonl(stats.max_flows);
1289 ots->active_count = htonl(stats.n_flows);
1290 ots->matched_count = htonll(0); /* FIXME */
1295 struct port_stats_state {
1299 static int port_stats_init(struct datapath *dp, const void *body, int body_len,
1302 struct port_stats_state *s = xmalloc(sizeof *s);
1308 static int port_stats_dump(struct datapath *dp, void *state,
1309 struct buffer *buffer)
1311 struct port_stats_state *s = state;
1314 for (i = s->port; i < OFPP_MAX; i++) {
1315 struct sw_port *p = &dp->ports[i];
1316 struct ofp_port_stats *ops;
1320 ops = buffer_put_uninit(buffer, sizeof *ops);
1321 ops->port_no = htons(port_no(dp, p));
1322 memset(ops->pad, 0, sizeof ops->pad);
1323 ops->rx_count = htonll(p->rx_count);
1324 ops->tx_count = htonll(p->tx_count);
1325 ops->drop_count = htonll(p->drop_count);
1332 static void port_stats_done(void *state)
1338 /* Minimum and maximum acceptable number of bytes in body member of
1339 * struct ofp_stats_request. */
1340 size_t min_body, max_body;
1342 /* Prepares to dump some kind of statistics on 'dp'. 'body' and
1343 * 'body_len' are the 'body' member of the struct ofp_stats_request.
1344 * Returns zero if successful, otherwise a negative error code.
1345 * May initialize '*state' to state information. May be null if no
1346 * initialization is required.*/
1347 int (*init)(struct datapath *dp, const void *body, int body_len,
1350 /* Appends statistics for 'dp' to 'buffer', which initially contains a
1351 * struct ofp_stats_reply. On success, it should return 1 if it should be
1352 * called again later with another buffer, 0 if it is done, or a negative
1353 * errno value on failure. */
1354 int (*dump)(struct datapath *dp, void *state, struct buffer *buffer);
1356 /* Cleans any state created by the init or dump functions. May be null
1357 * if no cleanup is required. */
1358 void (*done)(void *state);
1361 static const struct stats_type stats[] = {
1363 sizeof(struct ofp_flow_stats_request),
1364 sizeof(struct ofp_flow_stats_request),
1369 [OFPST_AGGREGATE] = {
1370 sizeof(struct ofp_aggregate_stats_request),
1371 sizeof(struct ofp_aggregate_stats_request),
1372 aggregate_stats_init,
1373 aggregate_stats_dump,
1374 aggregate_stats_done
1392 struct stats_dump_cb {
1394 struct ofp_stats_request *rq;
1395 struct sender sender;
1396 const struct stats_type *s;
1401 stats_dump(struct datapath *dp, void *cb_)
1403 struct stats_dump_cb *cb = cb_;
1404 struct ofp_stats_reply *osr;
1405 struct buffer *buffer;
1412 osr = alloc_openflow_buffer(dp, sizeof *osr, OFPT_STATS_REPLY, &cb->sender,
1414 osr->type = htons(cb->s - stats);
1417 err = cb->s->dump(dp, cb->state, buffer);
1423 /* Buffer might have been reallocated, so find our data again. */
1424 osr = buffer_at_assert(buffer, 0, sizeof *osr);
1425 osr->flags = ntohs(OFPSF_REPLY_MORE);
1427 err2 = send_openflow_buffer(dp, buffer, &cb->sender);
1437 stats_done(void *cb_)
1439 struct stats_dump_cb *cb = cb_;
1442 cb->s->done(cb->state);
1449 recv_stats_request(struct datapath *dp, const struct sender *sender,
1452 const struct ofp_stats_request *rq = oh;
1453 size_t rq_len = ntohs(rq->header.length);
1454 struct stats_dump_cb *cb;
1458 type = ntohs(rq->type);
1459 if (type >= ARRAY_SIZE(stats) || !stats[type].dump) {
1460 VLOG_WARN("received stats request of unknown type %d", type);
1464 cb = xmalloc(sizeof *cb);
1466 cb->rq = xmemdup(rq, rq_len);
1467 cb->sender = *sender;
1468 cb->s = &stats[type];
1471 body_len = rq_len - offsetof(struct ofp_stats_request, body);
1472 if (body_len < cb->s->min_body || body_len > cb->s->max_body) {
1473 VLOG_WARN("stats request type %d with bad body length %d",
1480 err = cb->s->init(dp, rq->body, body_len, &cb->state);
1482 VLOG_WARN("failed initialization of stats request type %d: %s",
1483 type, strerror(-err));
1488 remote_start_dump(sender->remote, stats_dump, stats_done, cb);
1498 recv_echo_request(struct datapath *dp, const struct sender *sender,
1501 return send_openflow_buffer(dp, make_echo_reply(oh), sender);
1504 /* 'msg', which is 'length' bytes long, was received from the control path.
1505 * Apply it to 'chain'. */
1507 fwd_control_input(struct datapath *dp, const struct sender *sender,
1508 const void *msg, size_t length)
1510 struct openflow_packet {
1512 int (*handler)(struct datapath *, const struct sender *, const void *);
1515 static const struct openflow_packet packets[] = {
1516 [OFPT_FEATURES_REQUEST] = {
1517 sizeof (struct ofp_header),
1518 recv_features_request,
1520 [OFPT_GET_CONFIG_REQUEST] = {
1521 sizeof (struct ofp_header),
1522 recv_get_config_request,
1524 [OFPT_SET_CONFIG] = {
1525 sizeof (struct ofp_switch_config),
1528 [OFPT_PACKET_OUT] = {
1529 sizeof (struct ofp_packet_out),
1533 sizeof (struct ofp_flow_mod),
1537 sizeof (struct ofp_port_mod),
1540 [OFPT_STATS_REQUEST] = {
1541 sizeof (struct ofp_stats_request),
1544 [OFPT_ECHO_REQUEST] = {
1545 sizeof (struct ofp_header),
1550 const struct openflow_packet *pkt;
1551 struct ofp_header *oh;
1553 oh = (struct ofp_header *) msg;
1554 if (oh->version != OFP_VERSION || oh->type >= ARRAY_SIZE(packets)
1555 || ntohs(oh->length) > length)
1558 pkt = &packets[oh->type];
1561 if (length < pkt->min_size)
1564 return pkt->handler(dp, sender, msg);
1567 /* Packet buffering. */
1569 #define OVERWRITE_SECS 1
1571 struct packet_buffer {
1572 struct buffer *buffer;
1577 static struct packet_buffer buffers[N_PKT_BUFFERS];
1578 static unsigned int buffer_idx;
1580 uint32_t save_buffer(struct buffer *buffer)
1582 struct packet_buffer *p;
1585 buffer_idx = (buffer_idx + 1) & PKT_BUFFER_MASK;
1586 p = &buffers[buffer_idx];
1588 /* Don't buffer packet if existing entry is less than
1589 * OVERWRITE_SECS old. */
1590 if (time(0) < p->timeout) { /* FIXME */
1593 buffer_delete(p->buffer);
1596 /* Don't use maximum cookie value since the all-bits-1 id is
1598 if (++p->cookie >= (1u << PKT_COOKIE_BITS) - 1)
1600 p->buffer = buffer_clone(buffer); /* FIXME */
1601 p->timeout = time(0) + OVERWRITE_SECS; /* FIXME */
1602 id = buffer_idx | (p->cookie << PKT_BUFFER_BITS);
1607 static struct buffer *retrieve_buffer(uint32_t id)
1609 struct buffer *buffer = NULL;
1610 struct packet_buffer *p;
1612 p = &buffers[id & PKT_BUFFER_MASK];
1613 if (p->cookie == id >> PKT_BUFFER_BITS) {
1617 printf("cookie mismatch: %x != %x\n",
1618 id >> PKT_BUFFER_BITS, p->cookie);
1624 static void discard_buffer(uint32_t id)
1626 struct packet_buffer *p;
1628 p = &buffers[id & PKT_BUFFER_MASK];
1629 if (p->cookie == id >> PKT_BUFFER_BITS) {
1630 buffer_delete(p->buffer);