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>
47 #include "poll-loop.h"
53 #define THIS_MODULE VLM_datapath
56 #define BRIDGE_PORT_NO_FLOOD 0x00000001
58 /* Capabilities supported by this implementation. */
59 #define OFP_SUPPORTED_CAPABILITIES ( OFPC_FLOW_STATS \
64 /* Actions supported by this implementation. */
65 #define OFP_SUPPORTED_ACTIONS ( (1 << OFPAT_OUTPUT) \
66 | (1 << OFPAT_SET_DL_VLAN) \
67 | (1 << OFPAT_SET_DL_SRC) \
68 | (1 << OFPAT_SET_DL_DST) \
69 | (1 << OFPAT_SET_NW_SRC) \
70 | (1 << OFPAT_SET_NW_DST) \
71 | (1 << OFPAT_SET_TP_SRC) \
72 | (1 << OFPAT_SET_TP_DST) )
77 struct netdev *netdev;
78 struct list node; /* Element in datapath.ports. */
79 unsigned long long int rx_count, tx_count, drop_count;
82 /* The origin of a received OpenFlow message, to enable sending a reply. */
84 struct remote *remote; /* The device that sent the message. */
85 uint32_t xid; /* The OpenFlow transaction ID. */
88 /* A connection to a controller or a management device. */
93 /* Support for reliable, multi-message replies to requests.
95 * If an incoming request needs to have a reliable reply that might
96 * require multiple messages, it can use remote_start_dump() to set up
97 * a callback that will be called as buffer space for replies. */
98 int (*cb_dump)(struct datapath *, void *aux);
99 void (*cb_done)(void *aux);
104 /* Remote connections. */
105 struct remote *controller; /* Connection to controller. */
106 struct list remotes; /* All connections (including controller). */
107 struct vconn *listen_vconn;
111 /* Unique identifier for this datapath */
114 struct sw_chain *chain; /* Forwarding rules. */
116 struct ofp_switch_config config;
119 struct sw_port ports[OFPP_MAX];
120 struct list port_list; /* List of ports, for flooding. */
123 static struct remote *remote_create(struct datapath *, struct rconn *);
124 static void remote_run(struct datapath *, struct remote *);
125 static void remote_wait(struct remote *);
126 static void remote_destroy(struct remote *);
128 void dp_output_port(struct datapath *, struct buffer *,
129 int in_port, int out_port);
130 void dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp);
131 void dp_output_control(struct datapath *, struct buffer *, int in_port,
132 size_t max_len, int reason);
133 static void send_flow_expired(struct datapath *, struct sw_flow *);
134 static void send_port_status(struct sw_port *p, uint8_t status);
135 static void del_switch_port(struct sw_port *p);
136 static void execute_actions(struct datapath *, struct buffer *,
137 int in_port, const struct sw_flow_key *,
138 const struct ofp_action *, int n_actions);
139 static void modify_vlan(struct buffer *buffer, const struct sw_flow_key *key,
140 const struct ofp_action *a);
141 static void modify_nh(struct buffer *buffer, uint16_t eth_proto,
142 uint8_t nw_proto, const struct ofp_action *a);
143 static void modify_th(struct buffer *buffer, uint16_t eth_proto,
144 uint8_t nw_proto, const struct ofp_action *a);
146 /* Buffers are identified to userspace by a 31-bit opaque ID. We divide the ID
147 * into a buffer number (low bits) and a cookie (high bits). The buffer number
148 * is an index into an array of buffers. The cookie distinguishes between
149 * different packets that have occupied a single buffer. Thus, the more
150 * buffers we have, the lower-quality the cookie... */
151 #define PKT_BUFFER_BITS 8
152 #define N_PKT_BUFFERS (1 << PKT_BUFFER_BITS)
153 #define PKT_BUFFER_MASK (N_PKT_BUFFERS - 1)
155 #define PKT_COOKIE_BITS (32 - PKT_BUFFER_BITS)
157 void fwd_port_input(struct datapath *, struct buffer *, int in_port);
158 int fwd_control_input(struct datapath *, const struct sender *,
159 const void *, size_t);
161 uint32_t save_buffer(struct buffer *);
162 static struct buffer *retrieve_buffer(uint32_t id);
163 static void discard_buffer(uint32_t id);
165 static int port_no(struct datapath *dp, struct sw_port *p)
167 assert(p >= dp->ports && p < &dp->ports[ARRAY_SIZE(dp->ports)]);
168 return p - dp->ports;
171 /* Generates and returns a random datapath id. */
173 gen_datapath_id(void)
175 uint8_t ea[ETH_ADDR_LEN];
177 return eth_addr_to_uint64(ea);
181 dp_new(struct datapath **dp_, uint64_t dpid, struct rconn *rconn)
185 dp = calloc(1, sizeof *dp);
190 dp->last_timeout = time(0);
191 list_init(&dp->remotes);
192 dp->controller = remote_create(dp, rconn);
193 dp->listen_vconn = NULL;
194 dp->id = dpid <= UINT64_C(0xffffffffffff) ? dpid : gen_datapath_id();
195 dp->chain = chain_create();
197 VLOG_ERR("could not create chain");
202 list_init(&dp->port_list);
203 dp->config.flags = 0;
204 dp->config.miss_send_len = htons(OFP_DEFAULT_MISS_SEND_LEN);
210 dp_add_port(struct datapath *dp, const char *name)
212 struct netdev *netdev;
218 error = netdev_open(name, NETDEV_ETH_TYPE_ANY, &netdev);
222 error = netdev_set_flags(netdev, NETDEV_UP | NETDEV_PROMISC, false);
224 VLOG_ERR("Couldn't set promiscuous mode on %s device", name);
225 netdev_close(netdev);
228 if (netdev_get_in4(netdev, &in4)) {
229 VLOG_ERR("%s device has assigned IP address %s", name, inet_ntoa(in4));
231 if (netdev_get_in6(netdev, &in6)) {
232 char in6_name[INET6_ADDRSTRLEN + 1];
233 inet_ntop(AF_INET6, &in6, in6_name, sizeof in6_name);
234 VLOG_ERR("%s device has assigned IPv6 address %s", name, in6_name);
237 for (p = dp->ports; ; p++) {
238 if (p >= &dp->ports[ARRAY_SIZE(dp->ports)]) {
240 } else if (!p->netdev) {
250 list_push_back(&dp->port_list, &p->node);
252 /* Notify the ctlpath that this port has been added */
253 send_port_status(p, OFPPR_ADD);
259 dp_add_listen_vconn(struct datapath *dp, struct vconn *listen_vconn)
261 assert(!dp->listen_vconn);
262 dp->listen_vconn = listen_vconn;
266 dp_run(struct datapath *dp)
268 time_t now = time(0);
269 struct sw_port *p, *pn;
270 struct remote *r, *rn;
271 struct buffer *buffer = NULL;
273 if (now != dp->last_timeout) {
274 struct list deleted = LIST_INITIALIZER(&deleted);
275 struct sw_flow *f, *n;
277 chain_timeout(dp->chain, &deleted);
278 LIST_FOR_EACH_SAFE (f, n, struct sw_flow, node, &deleted) {
279 send_flow_expired(dp, f);
280 list_remove(&f->node);
283 dp->last_timeout = now;
285 poll_timer_wait(1000);
287 LIST_FOR_EACH_SAFE (p, pn, struct sw_port, node, &dp->port_list) {
291 /* Allocate buffer with some headroom to add headers in forwarding
292 * to the controller or adding a vlan tag, plus an extra 2 bytes to
293 * allow IP headers to be aligned on a 4-byte boundary. */
294 const int headroom = 128 + 2;
295 const int hard_header = VLAN_ETH_HEADER_LEN;
296 const int mtu = netdev_get_mtu(p->netdev);
297 buffer = buffer_new(headroom + hard_header + mtu);
298 buffer->data += headroom;
300 error = netdev_recv(p->netdev, buffer);
303 fwd_port_input(dp, buffer, port_no(dp, p));
305 } else if (error != EAGAIN) {
306 VLOG_ERR("Error receiving data from %s: %s",
307 netdev_get_name(p->netdev), strerror(error));
311 buffer_delete(buffer);
313 /* Talk to remotes. */
314 LIST_FOR_EACH_SAFE (r, rn, struct remote, node, &dp->remotes) {
317 if (dp->listen_vconn) {
319 struct vconn *new_vconn;
322 retval = vconn_accept(dp->listen_vconn, &new_vconn);
324 if (retval != EAGAIN) {
325 VLOG_WARN("accept failed (%s)", strerror(retval));
329 remote_create(dp, rconn_new_from_vconn("passive", 128, new_vconn));
335 remote_run(struct datapath *dp, struct remote *r)
341 /* Do some remote processing, but cap it at a reasonable amount so that
342 * other processing doesn't starve. */
343 for (i = 0; i < 50; i++) {
345 struct buffer *buffer;
346 struct ofp_header *oh;
348 buffer = rconn_recv(r->rconn);
353 if (buffer->size >= sizeof *oh) {
354 struct sender sender;
358 sender.xid = oh->xid;
359 fwd_control_input(dp, &sender, buffer->data, buffer->size);
361 VLOG_WARN("received too-short OpenFlow message");
363 buffer_delete(buffer);
365 if (!rconn_is_full(r->rconn)) {
366 int error = r->cb_dump(dp, r->cb_aux);
369 VLOG_WARN("dump callback error: %s", strerror(-error));
371 r->cb_done(r->cb_aux);
380 if (!rconn_is_alive(r->rconn)) {
386 remote_wait(struct remote *r)
388 rconn_run_wait(r->rconn);
389 rconn_recv_wait(r->rconn);
393 remote_destroy(struct remote *r)
396 if (r->cb_dump && r->cb_done) {
397 r->cb_done(r->cb_aux);
399 list_remove(&r->node);
400 rconn_destroy(r->rconn);
405 static struct remote *
406 remote_create(struct datapath *dp, struct rconn *rconn)
408 struct remote *remote = xmalloc(sizeof *remote);
409 list_push_back(&dp->remotes, &remote->node);
410 remote->rconn = rconn;
411 remote->cb_dump = NULL;
415 /* Starts a callback-based, reliable, possibly multi-message reply to a
416 * request made by 'remote'.
418 * 'dump' designates a function that will be called when the 'remote' send
419 * queue has an empty slot. It should compose a message and send it on
420 * 'remote'. On success, it should return 1 if it should be called again when
421 * another send queue slot opens up, 0 if its transmissions are complete, or a
422 * negative errno value on failure.
424 * 'done' designates a function to clean up any resources allocated for the
425 * dump. It must handle being called before the dump is complete (which will
426 * happen if 'remote' is closed unexpectedly).
428 * 'aux' is passed to 'dump' and 'done'. */
430 remote_start_dump(struct remote *remote,
431 int (*dump)(struct datapath *, void *),
432 void (*done)(void *),
435 assert(!remote->cb_dump);
436 remote->cb_dump = dump;
437 remote->cb_done = done;
438 remote->cb_aux = aux;
442 dp_wait(struct datapath *dp)
447 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
448 netdev_recv_wait(p->netdev);
450 LIST_FOR_EACH (r, struct remote, node, &dp->remotes) {
453 if (dp->listen_vconn) {
454 vconn_accept_wait(dp->listen_vconn);
458 /* Delete 'p' from switch. */
460 del_switch_port(struct sw_port *p)
462 send_port_status(p, OFPPR_DELETE);
463 netdev_close(p->netdev);
465 list_remove(&p->node);
469 dp_destroy(struct datapath *dp)
471 struct sw_port *p, *n;
477 LIST_FOR_EACH_SAFE (p, n, struct sw_port, node, &dp->port_list) {
480 chain_destroy(dp->chain);
484 /* Send packets out all the ports except the originating one. If the
485 * "flood" argument is set, don't send out ports with flooding disabled.
488 output_all(struct datapath *dp, struct buffer *buffer, int in_port, int flood)
494 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
495 if (port_no(dp, p) == in_port) {
498 if (flood && p->flags & BRIDGE_PORT_NO_FLOOD) {
501 if (prev_port != -1) {
502 dp_output_port(dp, buffer_clone(buffer), in_port, prev_port);
504 prev_port = port_no(dp, p);
507 dp_output_port(dp, buffer, in_port, prev_port);
509 buffer_delete(buffer);
515 output_packet(struct datapath *dp, struct buffer *buffer, int out_port)
517 if (out_port >= 0 && out_port < OFPP_MAX) {
518 struct sw_port *p = &dp->ports[out_port];
519 if (p->netdev != NULL) {
520 if (!netdev_send(p->netdev, buffer)) {
529 buffer_delete(buffer);
530 /* FIXME: ratelimit */
531 VLOG_DBG("can't forward to bad port %d\n", out_port);
534 /* Takes ownership of 'buffer' and transmits it to 'out_port' on 'dp'.
537 dp_output_port(struct datapath *dp, struct buffer *buffer,
538 int in_port, int out_port)
542 if (out_port == OFPP_FLOOD) {
543 output_all(dp, buffer, in_port, 1);
544 } else if (out_port == OFPP_ALL) {
545 output_all(dp, buffer, in_port, 0);
546 } else if (out_port == OFPP_CONTROLLER) {
547 dp_output_control(dp, buffer, in_port, 0, OFPR_ACTION);
548 } else if (out_port == OFPP_TABLE) {
549 struct sw_flow_key key;
550 struct sw_flow *flow;
553 flow_extract(buffer, in_port, &key.flow);
554 flow = chain_lookup(dp->chain, &key);
556 flow_used(flow, buffer);
557 execute_actions(dp, buffer, in_port, &key,
558 flow->actions, flow->n_actions);
561 output_packet(dp, buffer, out_port);
566 make_openflow_reply(size_t openflow_len, uint8_t type,
567 const struct sender *sender, struct buffer **bufferp)
569 return make_openflow_xid(openflow_len, type, sender ? sender->xid : 0,
574 send_openflow_buffer(struct datapath *dp, struct buffer *buffer,
575 const struct sender *sender)
577 struct remote *remote = sender ? sender->remote : dp->controller;
578 struct rconn *rconn = remote->rconn;
581 update_openflow_length(buffer);
582 retval = rconn_send(rconn, buffer);
584 VLOG_WARN("send to %s failed: %s",
585 rconn_get_name(rconn), strerror(retval));
586 buffer_delete(buffer);
591 /* Takes ownership of 'buffer' and transmits it to 'dp''s controller. If the
592 * packet can be saved in a buffer, then only the first max_len bytes of
593 * 'buffer' are sent; otherwise, all of 'buffer' is sent. 'reason' indicates
594 * why 'buffer' is being sent. 'max_len' sets the maximum number of bytes that
595 * the caller wants to be sent; a value of 0 indicates the entire packet should
598 dp_output_control(struct datapath *dp, struct buffer *buffer, int in_port,
599 size_t max_len, int reason)
601 struct ofp_packet_in *opi;
605 buffer_id = save_buffer(buffer);
606 total_len = buffer->size;
607 if (buffer_id != UINT32_MAX && buffer->size > max_len) {
608 buffer->size = max_len;
611 opi = buffer_push_uninit(buffer, offsetof(struct ofp_packet_in, data));
612 opi->header.version = OFP_VERSION;
613 opi->header.type = OFPT_PACKET_IN;
614 opi->header.length = htons(buffer->size);
615 opi->header.xid = htonl(0);
616 opi->buffer_id = htonl(buffer_id);
617 opi->total_len = htons(total_len);
618 opi->in_port = htons(in_port);
619 opi->reason = reason;
621 send_openflow_buffer(dp, buffer, NULL);
624 static void fill_port_desc(struct datapath *dp, struct sw_port *p,
625 struct ofp_phy_port *desc)
627 desc->port_no = htons(port_no(dp, p));
628 strncpy((char *) desc->name, netdev_get_name(p->netdev),
630 desc->name[sizeof desc->name - 1] = '\0';
631 memcpy(desc->hw_addr, netdev_get_etheraddr(p->netdev), ETH_ADDR_LEN);
632 desc->flags = htonl(p->flags);
633 desc->features = htonl(netdev_get_features(p->netdev));
634 desc->speed = htonl(netdev_get_speed(p->netdev));
638 dp_send_features_reply(struct datapath *dp, const struct sender *sender)
640 struct buffer *buffer;
641 struct ofp_switch_features *ofr;
644 ofr = make_openflow_reply(sizeof *ofr, OFPT_FEATURES_REPLY,
646 ofr->datapath_id = htonll(dp->id);
647 ofr->n_exact = htonl(2 * TABLE_HASH_MAX_FLOWS);
648 ofr->n_compression = 0; /* Not supported */
649 ofr->n_general = htonl(TABLE_LINEAR_MAX_FLOWS);
650 ofr->buffer_mb = htonl(UINT32_MAX);
651 ofr->n_buffers = htonl(N_PKT_BUFFERS);
652 ofr->capabilities = htonl(OFP_SUPPORTED_CAPABILITIES);
653 ofr->actions = htonl(OFP_SUPPORTED_ACTIONS);
654 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
655 struct ofp_phy_port *opp = buffer_put_uninit(buffer, sizeof *opp);
656 memset(opp, 0, sizeof *opp);
657 fill_port_desc(dp, p, opp);
659 send_openflow_buffer(dp, buffer, sender);
663 dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp)
665 int port_no = ntohs(opp->port_no);
666 if (port_no < OFPP_MAX) {
667 struct sw_port *p = &dp->ports[port_no];
669 /* Make sure the port id hasn't changed since this was sent */
670 if (!p || memcmp(opp->hw_addr, netdev_get_etheraddr(p->netdev),
671 ETH_ADDR_LEN) != 0) {
674 p->flags = htonl(opp->flags);
679 send_port_status(struct sw_port *p, uint8_t status)
681 struct buffer *buffer;
682 struct ofp_port_status *ops;
683 ops = make_openflow_xid(sizeof *ops, OFPT_PORT_STATUS, 0, &buffer);
684 ops->reason = status;
685 memset(ops->pad, 0, sizeof ops->pad);
686 fill_port_desc(p->dp, p, &ops->desc);
688 send_openflow_buffer(p->dp, buffer, NULL);
692 send_flow_expired(struct datapath *dp, struct sw_flow *flow)
694 struct buffer *buffer;
695 struct ofp_flow_expired *ofe;
696 ofe = make_openflow_xid(sizeof *ofe, OFPT_FLOW_EXPIRED, 0, &buffer);
697 flow_fill_match(&ofe->match, &flow->key);
699 memset(ofe->pad, 0, sizeof ofe->pad);
700 ofe->priority = htons(flow->priority);
702 ofe->duration = htonl(flow->timeout - flow->max_idle - flow->created);
703 ofe->packet_count = htonll(flow->packet_count);
704 ofe->byte_count = htonll(flow->byte_count);
705 send_openflow_buffer(dp, buffer, NULL);
709 dp_send_error_msg(struct datapath *dp, const struct sender *sender,
710 uint16_t type, uint16_t code, const uint8_t *data, size_t len)
712 struct buffer *buffer;
713 struct ofp_error_msg *oem;
714 oem = make_openflow_reply(sizeof(*oem)+len, OFPT_ERROR_MSG,
716 oem->type = htons(type);
717 oem->code = htons(code);
718 memcpy(oem->data, data, len);
719 send_openflow_buffer(dp, buffer, sender);
723 fill_flow_stats(struct buffer *buffer, struct sw_flow *flow,
724 int table_idx, time_t now)
726 struct ofp_flow_stats *ofs;
727 int length = sizeof *ofs + sizeof *ofs->actions * flow->n_actions;
728 ofs = buffer_put_uninit(buffer, length);
729 ofs->length = htons(length);
730 ofs->table_id = table_idx;
732 ofs->match.wildcards = htons(flow->key.wildcards);
733 ofs->match.in_port = flow->key.flow.in_port;
734 memcpy(ofs->match.dl_src, flow->key.flow.dl_src, ETH_ADDR_LEN);
735 memcpy(ofs->match.dl_dst, flow->key.flow.dl_dst, ETH_ADDR_LEN);
736 ofs->match.dl_vlan = flow->key.flow.dl_vlan;
737 ofs->match.dl_type = flow->key.flow.dl_type;
738 ofs->match.nw_src = flow->key.flow.nw_src;
739 ofs->match.nw_dst = flow->key.flow.nw_dst;
740 ofs->match.nw_proto = flow->key.flow.nw_proto;
741 memset(ofs->match.pad, 0, sizeof ofs->match.pad);
742 ofs->match.tp_src = flow->key.flow.tp_src;
743 ofs->match.tp_dst = flow->key.flow.tp_dst;
744 ofs->duration = htonl(now - flow->created);
745 ofs->packet_count = htonll(flow->packet_count);
746 ofs->byte_count = htonll(flow->byte_count);
747 ofs->priority = htons(flow->priority);
748 ofs->max_idle = htons(flow->max_idle);
749 memcpy(ofs->actions, flow->actions,
750 sizeof *ofs->actions * flow->n_actions);
754 /* 'buffer' was received on 'in_port', a physical switch port between 0 and
755 * OFPP_MAX. Process it according to 'chain'. */
756 void fwd_port_input(struct datapath *dp, struct buffer *buffer, int in_port)
758 struct sw_flow_key key;
759 struct sw_flow *flow;
762 flow_extract(buffer, in_port, &key.flow);
763 flow = chain_lookup(dp->chain, &key);
765 flow_used(flow, buffer);
766 execute_actions(dp, buffer, in_port, &key,
767 flow->actions, flow->n_actions);
769 dp_output_control(dp, buffer, in_port, ntohs(dp->config.miss_send_len),
775 do_output(struct datapath *dp, struct buffer *buffer, int in_port,
776 size_t max_len, int out_port)
778 if (out_port != OFPP_CONTROLLER) {
779 dp_output_port(dp, buffer, in_port, out_port);
781 dp_output_control(dp, buffer, in_port, max_len, OFPR_ACTION);
786 execute_actions(struct datapath *dp, struct buffer *buffer,
787 int in_port, const struct sw_flow_key *key,
788 const struct ofp_action *actions, int n_actions)
790 /* Every output action needs a separate clone of 'buffer', but the common
791 * case is just a single output action, so that doing a clone and then
792 * freeing the original buffer is wasteful. So the following code is
793 * slightly obscure just to avoid that. */
795 size_t max_len=0; /* Initialze to make compiler happy */
800 eth_proto = ntohs(key->flow.dl_type);
802 for (i = 0; i < n_actions; i++) {
803 const struct ofp_action *a = &actions[i];
804 struct eth_header *eh = buffer->l2;
806 if (prev_port != -1) {
807 do_output(dp, buffer_clone(buffer), in_port, max_len, prev_port);
811 switch (ntohs(a->type)) {
813 prev_port = ntohs(a->arg.output.port);
814 max_len = ntohs(a->arg.output.max_len);
817 case OFPAT_SET_DL_VLAN:
818 modify_vlan(buffer, key, a);
821 case OFPAT_SET_DL_SRC:
822 memcpy(eh->eth_src, a->arg.dl_addr, sizeof eh->eth_src);
825 case OFPAT_SET_DL_DST:
826 memcpy(eh->eth_dst, a->arg.dl_addr, sizeof eh->eth_dst);
829 case OFPAT_SET_NW_SRC:
830 case OFPAT_SET_NW_DST:
831 modify_nh(buffer, eth_proto, key->flow.nw_proto, a);
834 case OFPAT_SET_TP_SRC:
835 case OFPAT_SET_TP_DST:
836 modify_th(buffer, eth_proto, key->flow.nw_proto, a);
844 do_output(dp, buffer, in_port, max_len, prev_port);
846 buffer_delete(buffer);
849 static void modify_nh(struct buffer *buffer, uint16_t eth_proto,
850 uint8_t nw_proto, const struct ofp_action *a)
852 if (eth_proto == ETH_TYPE_IP) {
853 struct ip_header *nh = buffer->l3;
854 uint32_t new, *field;
856 new = a->arg.nw_addr;
857 field = a->type == OFPAT_SET_NW_SRC ? &nh->ip_src : &nh->ip_dst;
858 if (nw_proto == IP_TYPE_TCP) {
859 struct tcp_header *th = buffer->l4;
860 th->tcp_csum = recalc_csum32(th->tcp_csum, *field, new);
861 } else if (nw_proto == IP_TYPE_UDP) {
862 struct udp_header *th = buffer->l4;
864 th->udp_csum = recalc_csum32(th->udp_csum, *field, new);
866 th->udp_csum = 0xffff;
870 nh->ip_csum = recalc_csum32(nh->ip_csum, *field, new);
875 static void modify_th(struct buffer *buffer, uint16_t eth_proto,
876 uint8_t nw_proto, const struct ofp_action *a)
878 if (eth_proto == ETH_TYPE_IP) {
879 uint16_t new, *field;
883 if (nw_proto == IP_TYPE_TCP) {
884 struct tcp_header *th = buffer->l4;
885 field = a->type == OFPAT_SET_TP_SRC ? &th->tcp_src : &th->tcp_dst;
886 th->tcp_csum = recalc_csum16(th->tcp_csum, *field, new);
888 } else if (nw_proto == IP_TYPE_UDP) {
889 struct udp_header *th = buffer->l4;
890 field = a->type == OFPAT_SET_TP_SRC ? &th->udp_src : &th->udp_dst;
891 th->udp_csum = recalc_csum16(th->udp_csum, *field, new);
898 modify_vlan(struct buffer *buffer,
899 const struct sw_flow_key *key, const struct ofp_action *a)
901 uint16_t new_id = a->arg.vlan_id;
902 struct vlan_eth_header *veh;
904 if (new_id != htons(OFP_VLAN_NONE)) {
905 if (key->flow.dl_vlan != htons(OFP_VLAN_NONE)) {
906 /* Modify vlan id, but maintain other TCI values */
908 veh->veth_tci &= ~htons(VLAN_VID);
909 veh->veth_tci |= new_id;
911 /* Insert new vlan id. */
912 struct eth_header *eh = buffer->l2;
913 struct vlan_eth_header tmp;
914 memcpy(tmp.veth_dst, eh->eth_dst, ETH_ADDR_LEN);
915 memcpy(tmp.veth_src, eh->eth_src, ETH_ADDR_LEN);
916 tmp.veth_type = htons(ETH_TYPE_VLAN);
917 tmp.veth_tci = new_id;
918 tmp.veth_next_type = eh->eth_type;
920 veh = buffer_push_uninit(buffer, VLAN_HEADER_LEN);
921 memcpy(veh, &tmp, sizeof tmp);
922 buffer->l2 -= VLAN_HEADER_LEN;
925 /* Remove an existing vlan header if it exists */
927 if (veh->veth_type == htons(ETH_TYPE_VLAN)) {
928 struct eth_header tmp;
930 memcpy(tmp.eth_dst, veh->veth_dst, ETH_ADDR_LEN);
931 memcpy(tmp.eth_src, veh->veth_src, ETH_ADDR_LEN);
932 tmp.eth_type = veh->veth_next_type;
934 buffer->size -= VLAN_HEADER_LEN;
935 buffer->data += VLAN_HEADER_LEN;
936 buffer->l2 += VLAN_HEADER_LEN;
937 memcpy(buffer->data, &tmp, sizeof tmp);
943 recv_features_request(struct datapath *dp, const struct sender *sender,
946 dp_send_features_reply(dp, sender);
951 recv_get_config_request(struct datapath *dp, const struct sender *sender,
954 struct buffer *buffer;
955 struct ofp_switch_config *osc;
957 osc = make_openflow_reply(sizeof *osc, OFPT_GET_CONFIG_REPLY,
960 assert(sizeof *osc == sizeof dp->config);
961 memcpy(((char *)osc) + sizeof osc->header,
962 ((char *)&dp->config) + sizeof dp->config.header,
963 sizeof dp->config - sizeof dp->config.header);
965 return send_openflow_buffer(dp, buffer, sender);
969 recv_set_config(struct datapath *dp, const struct sender *sender UNUSED,
972 const struct ofp_switch_config *osc = msg;
978 recv_packet_out(struct datapath *dp, const struct sender *sender UNUSED,
981 const struct ofp_packet_out *opo = msg;
983 if (ntohl(opo->buffer_id) == (uint32_t) -1) {
984 /* FIXME: can we avoid copying data here? */
985 int data_len = ntohs(opo->header.length) - sizeof *opo;
986 struct buffer *buffer = buffer_new(data_len);
987 buffer_put(buffer, opo->u.data, data_len);
988 dp_output_port(dp, buffer,
989 ntohs(opo->in_port), ntohs(opo->out_port));
991 struct sw_flow_key key;
992 struct buffer *buffer;
995 buffer = retrieve_buffer(ntohl(opo->buffer_id));
1000 n_acts = (ntohs(opo->header.length) - sizeof *opo)
1001 / sizeof *opo->u.actions;
1002 flow_extract(buffer, ntohs(opo->in_port), &key.flow);
1003 execute_actions(dp, buffer, ntohs(opo->in_port),
1004 &key, opo->u.actions, n_acts);
1010 recv_port_mod(struct datapath *dp, const struct sender *sender UNUSED,
1013 const struct ofp_port_mod *opm = msg;
1015 dp_update_port_flags(dp, &opm->desc);
1021 add_flow(struct datapath *dp, const struct ofp_flow_mod *ofm)
1023 int error = -ENOMEM;
1026 struct sw_flow *flow;
1029 /* To prevent loops, make sure there's no action to send to the
1030 * OFP_TABLE virtual port.
1032 n_acts = (ntohs(ofm->header.length) - sizeof *ofm) / sizeof *ofm->actions;
1033 for (i=0; i<n_acts; i++) {
1034 const struct ofp_action *a = &ofm->actions[i];
1036 if (a->type == htons(OFPAT_OUTPUT)
1037 && (a->arg.output.port == htons(OFPP_TABLE)
1038 || a->arg.output.port == htons(OFPP_NONE))) {
1039 /* xxx Send fancy new error message? */
1044 /* Allocate memory. */
1045 flow = flow_alloc(n_acts);
1049 /* Fill out flow. */
1050 flow_extract_match(&flow->key, &ofm->match);
1051 flow->max_idle = ntohs(ofm->max_idle);
1052 flow->priority = flow->key.wildcards ? ntohs(ofm->priority) : -1;
1053 flow->timeout = time(0) + flow->max_idle; /* FIXME */
1054 flow->n_actions = n_acts;
1055 flow->created = time(0); /* FIXME */
1056 flow->byte_count = 0;
1057 flow->packet_count = 0;
1058 memcpy(flow->actions, ofm->actions, n_acts * sizeof *flow->actions);
1061 error = chain_insert(dp->chain, flow);
1063 goto error_free_flow;
1066 if (ntohl(ofm->buffer_id) != UINT32_MAX) {
1067 struct buffer *buffer = retrieve_buffer(ntohl(ofm->buffer_id));
1069 struct sw_flow_key key;
1070 uint16_t in_port = ntohs(ofm->match.in_port);
1071 flow_used(flow, buffer);
1072 flow_extract(buffer, in_port, &key.flow);
1073 execute_actions(dp, buffer, in_port, &key, ofm->actions, n_acts);
1083 if (ntohl(ofm->buffer_id) != (uint32_t) -1)
1084 discard_buffer(ntohl(ofm->buffer_id));
1089 recv_flow(struct datapath *dp, const struct sender *sender UNUSED,
1092 const struct ofp_flow_mod *ofm = msg;
1093 uint16_t command = ntohs(ofm->command);
1095 if (command == OFPFC_ADD) {
1096 return add_flow(dp, ofm);
1097 } else if (command == OFPFC_DELETE) {
1098 struct sw_flow_key key;
1099 flow_extract_match(&key, &ofm->match);
1100 return chain_delete(dp->chain, &key, 0, 0) ? 0 : -ESRCH;
1101 } else if (command == OFPFC_DELETE_STRICT) {
1102 struct sw_flow_key key;
1104 flow_extract_match(&key, &ofm->match);
1105 priority = key.wildcards ? ntohs(ofm->priority) : -1;
1106 return chain_delete(dp->chain, &key, priority, 1) ? 0 : -ESRCH;
1112 struct flow_stats_state {
1114 struct sw_table_position position;
1115 struct ofp_flow_stats_request rq;
1118 struct buffer *buffer;
1121 #define MAX_FLOW_STATS_BYTES 4096
1123 static int flow_stats_init(struct datapath *dp, const void *body, int body_len,
1126 const struct ofp_flow_stats_request *fsr = body;
1127 struct flow_stats_state *s = xmalloc(sizeof *s);
1128 s->table_idx = fsr->table_id == 0xff ? 0 : fsr->table_id;
1129 memset(&s->position, 0, sizeof s->position);
1135 static int flow_stats_dump_callback(struct sw_flow *flow, void *private)
1137 struct flow_stats_state *s = private;
1138 fill_flow_stats(s->buffer, flow, s->table_idx, s->now);
1139 return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1142 static int flow_stats_dump(struct datapath *dp, void *state,
1143 struct buffer *buffer)
1145 struct flow_stats_state *s = state;
1146 struct sw_flow_key match_key;
1148 flow_extract_match(&match_key, &s->rq.match);
1151 while (s->table_idx < dp->chain->n_tables
1152 && (s->rq.table_id == 0xff || s->rq.table_id == s->table_idx))
1154 struct sw_table *table = dp->chain->tables[s->table_idx];
1156 if (table->iterate(table, &match_key, &s->position,
1157 flow_stats_dump_callback, s))
1161 memset(&s->position, 0, sizeof s->position);
1163 return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1166 static void flow_stats_done(void *state)
1171 struct aggregate_stats_state {
1172 struct ofp_aggregate_stats_request rq;
1175 static int aggregate_stats_init(struct datapath *dp,
1176 const void *body, int body_len,
1179 const struct ofp_aggregate_stats_request *rq = body;
1180 struct aggregate_stats_state *s = xmalloc(sizeof *s);
1186 static int aggregate_stats_dump_callback(struct sw_flow *flow, void *private)
1188 struct ofp_aggregate_stats_reply *rpy = private;
1189 rpy->packet_count += flow->packet_count;
1190 rpy->byte_count += flow->byte_count;
1195 static int aggregate_stats_dump(struct datapath *dp, void *state,
1196 struct buffer *buffer)
1198 struct aggregate_stats_state *s = state;
1199 struct ofp_aggregate_stats_request *rq = &s->rq;
1200 struct ofp_aggregate_stats_reply *rpy;
1201 struct sw_table_position position;
1202 struct sw_flow_key match_key;
1205 rpy = buffer_put_uninit(buffer, sizeof *rpy);
1206 memset(rpy, 0, sizeof *rpy);
1208 flow_extract_match(&match_key, &rq->match);
1209 table_idx = rq->table_id == 0xff ? 0 : rq->table_id;
1210 memset(&position, 0, sizeof position);
1211 while (table_idx < dp->chain->n_tables
1212 && (rq->table_id == 0xff || rq->table_id == table_idx))
1214 struct sw_table *table = dp->chain->tables[table_idx];
1217 error = table->iterate(table, &match_key, &position,
1218 aggregate_stats_dump_callback, rpy);
1223 memset(&position, 0, sizeof position);
1226 rpy->packet_count = htonll(rpy->packet_count);
1227 rpy->byte_count = htonll(rpy->byte_count);
1228 rpy->flow_count = htonl(rpy->flow_count);
1232 static void aggregate_stats_done(void *state)
1237 static int table_stats_dump(struct datapath *dp, void *state,
1238 struct buffer *buffer)
1241 for (i = 0; i < dp->chain->n_tables; i++) {
1242 struct ofp_table_stats *ots = buffer_put_uninit(buffer, sizeof *ots);
1243 struct sw_table_stats stats;
1244 dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
1245 strncpy(ots->name, stats.name, sizeof ots->name);
1247 memset(ots->pad, 0, sizeof ots->pad);
1248 ots->max_entries = htonl(stats.max_flows);
1249 ots->active_count = htonl(stats.n_flows);
1250 ots->matched_count = htonll(0); /* FIXME */
1255 struct port_stats_state {
1259 static int port_stats_init(struct datapath *dp, const void *body, int body_len,
1262 struct port_stats_state *s = xmalloc(sizeof *s);
1268 static int port_stats_dump(struct datapath *dp, void *state,
1269 struct buffer *buffer)
1271 struct port_stats_state *s = state;
1274 for (i = s->port; i < OFPP_MAX; i++) {
1275 struct sw_port *p = &dp->ports[i];
1276 struct ofp_port_stats *ops;
1280 ops = buffer_put_uninit(buffer, sizeof *ops);
1281 ops->port_no = htons(port_no(dp, p));
1282 memset(ops->pad, 0, sizeof ops->pad);
1283 ops->rx_count = htonll(p->rx_count);
1284 ops->tx_count = htonll(p->tx_count);
1285 ops->drop_count = htonll(p->drop_count);
1292 static void port_stats_done(void *state)
1298 /* Minimum and maximum acceptable number of bytes in body member of
1299 * struct ofp_stats_request. */
1300 size_t min_body, max_body;
1302 /* Prepares to dump some kind of statistics on 'dp'. 'body' and
1303 * 'body_len' are the 'body' member of the struct ofp_stats_request.
1304 * Returns zero if successful, otherwise a negative error code.
1305 * May initialize '*state' to state information. May be null if no
1306 * initialization is required.*/
1307 int (*init)(struct datapath *dp, const void *body, int body_len,
1310 /* Appends statistics for 'dp' to 'buffer', which initially contains a
1311 * struct ofp_stats_reply. On success, it should return 1 if it should be
1312 * called again later with another buffer, 0 if it is done, or a negative
1313 * errno value on failure. */
1314 int (*dump)(struct datapath *dp, void *state, struct buffer *buffer);
1316 /* Cleans any state created by the init or dump functions. May be null
1317 * if no cleanup is required. */
1318 void (*done)(void *state);
1321 static const struct stats_type stats[] = {
1323 sizeof(struct ofp_flow_stats_request),
1324 sizeof(struct ofp_flow_stats_request),
1329 [OFPST_AGGREGATE] = {
1330 sizeof(struct ofp_aggregate_stats_request),
1331 sizeof(struct ofp_aggregate_stats_request),
1332 aggregate_stats_init,
1333 aggregate_stats_dump,
1334 aggregate_stats_done
1352 struct stats_dump_cb {
1354 struct ofp_stats_request *rq;
1355 struct sender sender;
1356 const struct stats_type *s;
1361 stats_dump(struct datapath *dp, void *cb_)
1363 struct stats_dump_cb *cb = cb_;
1364 struct ofp_stats_reply *osr;
1365 struct buffer *buffer;
1372 osr = make_openflow_reply(sizeof *osr, OFPT_STATS_REPLY, &cb->sender,
1374 osr->type = htons(cb->s - stats);
1377 err = cb->s->dump(dp, cb->state, buffer);
1383 /* Buffer might have been reallocated, so find our data again. */
1384 osr = buffer_at_assert(buffer, 0, sizeof *osr);
1385 osr->flags = ntohs(OFPSF_REPLY_MORE);
1387 err2 = send_openflow_buffer(dp, buffer, &cb->sender);
1397 stats_done(void *cb_)
1399 struct stats_dump_cb *cb = cb_;
1402 cb->s->done(cb->state);
1409 recv_stats_request(struct datapath *dp, const struct sender *sender,
1412 const struct ofp_stats_request *rq = oh;
1413 size_t rq_len = ntohs(rq->header.length);
1414 struct stats_dump_cb *cb;
1418 type = ntohs(rq->type);
1419 if (type >= ARRAY_SIZE(stats) || !stats[type].dump) {
1420 VLOG_WARN("received stats request of unknown type %d", type);
1424 cb = xmalloc(sizeof *cb);
1426 cb->rq = xmemdup(rq, rq_len);
1427 cb->sender = *sender;
1428 cb->s = &stats[type];
1431 body_len = rq_len - offsetof(struct ofp_stats_request, body);
1432 if (body_len < cb->s->min_body || body_len > cb->s->max_body) {
1433 VLOG_WARN("stats request type %d with bad body length %d",
1440 err = cb->s->init(dp, rq->body, body_len, &cb->state);
1442 VLOG_WARN("failed initialization of stats request type %d: %s",
1443 type, strerror(-err));
1448 remote_start_dump(sender->remote, stats_dump, stats_done, cb);
1458 recv_echo_request(struct datapath *dp, const struct sender *sender,
1461 return send_openflow_buffer(dp, make_echo_reply(oh), sender);
1465 recv_echo_reply(struct datapath *dp UNUSED, const struct sender *sender UNUSED,
1466 const void *oh UNUSED)
1471 /* 'msg', which is 'length' bytes long, was received from the control path.
1472 * Apply it to 'chain'. */
1474 fwd_control_input(struct datapath *dp, const struct sender *sender,
1475 const void *msg, size_t length)
1477 struct openflow_packet {
1479 int (*handler)(struct datapath *, const struct sender *, const void *);
1482 static const struct openflow_packet packets[] = {
1483 [OFPT_FEATURES_REQUEST] = {
1484 sizeof (struct ofp_header),
1485 recv_features_request,
1487 [OFPT_GET_CONFIG_REQUEST] = {
1488 sizeof (struct ofp_header),
1489 recv_get_config_request,
1491 [OFPT_SET_CONFIG] = {
1492 sizeof (struct ofp_switch_config),
1495 [OFPT_PACKET_OUT] = {
1496 sizeof (struct ofp_packet_out),
1500 sizeof (struct ofp_flow_mod),
1504 sizeof (struct ofp_port_mod),
1507 [OFPT_STATS_REQUEST] = {
1508 sizeof (struct ofp_stats_request),
1511 [OFPT_ECHO_REQUEST] = {
1512 sizeof (struct ofp_header),
1515 [OFPT_ECHO_REPLY] = {
1516 sizeof (struct ofp_header),
1521 const struct openflow_packet *pkt;
1522 struct ofp_header *oh;
1524 oh = (struct ofp_header *) msg;
1525 assert(oh->version == OFP_VERSION);
1526 if (oh->type >= ARRAY_SIZE(packets) || ntohs(oh->length) > length)
1529 pkt = &packets[oh->type];
1532 if (length < pkt->min_size)
1535 return pkt->handler(dp, sender, msg);
1538 /* Packet buffering. */
1540 #define OVERWRITE_SECS 1
1542 struct packet_buffer {
1543 struct buffer *buffer;
1548 static struct packet_buffer buffers[N_PKT_BUFFERS];
1549 static unsigned int buffer_idx;
1551 uint32_t save_buffer(struct buffer *buffer)
1553 struct packet_buffer *p;
1556 buffer_idx = (buffer_idx + 1) & PKT_BUFFER_MASK;
1557 p = &buffers[buffer_idx];
1559 /* Don't buffer packet if existing entry is less than
1560 * OVERWRITE_SECS old. */
1561 if (time(0) < p->timeout) { /* FIXME */
1564 buffer_delete(p->buffer);
1567 /* Don't use maximum cookie value since the all-bits-1 id is
1569 if (++p->cookie >= (1u << PKT_COOKIE_BITS) - 1)
1571 p->buffer = buffer_clone(buffer); /* FIXME */
1572 p->timeout = time(0) + OVERWRITE_SECS; /* FIXME */
1573 id = buffer_idx | (p->cookie << PKT_BUFFER_BITS);
1578 static struct buffer *retrieve_buffer(uint32_t id)
1580 struct buffer *buffer = NULL;
1581 struct packet_buffer *p;
1583 p = &buffers[id & PKT_BUFFER_MASK];
1584 if (p->cookie == id >> PKT_BUFFER_BITS) {
1588 printf("cookie mismatch: %x != %x\n",
1589 id >> PKT_BUFFER_BITS, p->cookie);
1595 static void discard_buffer(uint32_t id)
1597 struct packet_buffer *p;
1599 p = &buffers[id & PKT_BUFFER_MASK];
1600 if (p->cookie == id >> PKT_BUFFER_BITS) {
1601 buffer_delete(p->buffer);