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"
54 #define THIS_MODULE VLM_datapath
57 #define BRIDGE_PORT_NO_FLOOD 0x00000001
59 /* Capabilities supported by this implementation. */
60 #define OFP_SUPPORTED_CAPABILITIES ( OFPC_FLOW_STATS \
65 /* Actions supported by this implementation. */
66 #define OFP_SUPPORTED_ACTIONS ( (1 << OFPAT_OUTPUT) \
67 | (1 << OFPAT_SET_DL_VLAN) \
68 | (1 << OFPAT_SET_DL_SRC) \
69 | (1 << OFPAT_SET_DL_DST) \
70 | (1 << OFPAT_SET_NW_SRC) \
71 | (1 << OFPAT_SET_NW_DST) \
72 | (1 << OFPAT_SET_TP_SRC) \
73 | (1 << OFPAT_SET_TP_DST) )
78 struct netdev *netdev;
79 struct list node; /* Element in datapath.ports. */
80 unsigned long long int rx_count, tx_count, drop_count;
83 /* The origin of a received OpenFlow message, to enable sending a reply. */
85 struct remote *remote; /* The device that sent the message. */
86 uint32_t xid; /* The OpenFlow transaction ID. */
89 /* A connection to a controller or a management device. */
94 /* Support for reliable, multi-message replies to requests.
96 * If an incoming request needs to have a reliable reply that might
97 * require multiple messages, it can use remote_start_dump() to set up
98 * a callback that will be called as buffer space for replies. */
99 int (*cb_dump)(struct datapath *, void *aux);
100 void (*cb_done)(void *aux);
105 /* Remote connections. */
106 struct remote *controller; /* Connection to controller. */
107 struct list remotes; /* All connections (including controller). */
108 struct vconn *listen_vconn;
112 /* Unique identifier for this datapath */
115 struct sw_chain *chain; /* Forwarding rules. */
117 /* Configuration set from controller. */
119 uint16_t miss_send_len;
122 struct sw_port ports[OFPP_MAX];
123 struct list port_list; /* List of ports, for flooding. */
126 static struct remote *remote_create(struct datapath *, struct rconn *);
127 static void remote_run(struct datapath *, struct remote *);
128 static void remote_wait(struct remote *);
129 static void remote_destroy(struct remote *);
131 void dp_output_port(struct datapath *, struct buffer *,
132 int in_port, int out_port);
133 void dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp);
134 void dp_output_control(struct datapath *, struct buffer *, int in_port,
135 size_t max_len, int reason);
136 static void send_flow_expired(struct datapath *, struct sw_flow *,
137 enum ofp_flow_expired_reason);
138 static void send_port_status(struct sw_port *p, uint8_t status);
139 static void del_switch_port(struct sw_port *p);
140 static void execute_actions(struct datapath *, struct buffer *,
141 int in_port, const struct sw_flow_key *,
142 const struct ofp_action *, int n_actions);
143 static void modify_vlan(struct buffer *buffer, const struct sw_flow_key *key,
144 const struct ofp_action *a);
145 static void modify_nh(struct buffer *buffer, uint16_t eth_proto,
146 uint8_t nw_proto, const struct ofp_action *a);
147 static void modify_th(struct buffer *buffer, uint16_t eth_proto,
148 uint8_t nw_proto, const struct ofp_action *a);
150 /* Buffers are identified to userspace by a 31-bit opaque ID. We divide the ID
151 * into a buffer number (low bits) and a cookie (high bits). The buffer number
152 * is an index into an array of buffers. The cookie distinguishes between
153 * different packets that have occupied a single buffer. Thus, the more
154 * buffers we have, the lower-quality the cookie... */
155 #define PKT_BUFFER_BITS 8
156 #define N_PKT_BUFFERS (1 << PKT_BUFFER_BITS)
157 #define PKT_BUFFER_MASK (N_PKT_BUFFERS - 1)
159 #define PKT_COOKIE_BITS (32 - PKT_BUFFER_BITS)
161 int run_flow_through_tables(struct datapath *, struct buffer *, int in_port);
162 void fwd_port_input(struct datapath *, struct buffer *, int in_port);
163 int fwd_control_input(struct datapath *, const struct sender *,
164 const void *, size_t);
166 uint32_t save_buffer(struct buffer *);
167 static struct buffer *retrieve_buffer(uint32_t id);
168 static void discard_buffer(uint32_t id);
170 static int port_no(struct datapath *dp, struct sw_port *p)
172 assert(p >= dp->ports && p < &dp->ports[ARRAY_SIZE(dp->ports)]);
173 return p - dp->ports;
176 /* Generates and returns a random datapath id. */
178 gen_datapath_id(void)
180 uint8_t ea[ETH_ADDR_LEN];
182 return eth_addr_to_uint64(ea);
186 dp_new(struct datapath **dp_, uint64_t dpid, struct rconn *rconn)
190 dp = calloc(1, sizeof *dp);
195 dp->last_timeout = time_now();
196 list_init(&dp->remotes);
197 dp->controller = remote_create(dp, rconn);
198 dp->listen_vconn = NULL;
199 dp->id = dpid <= UINT64_C(0xffffffffffff) ? dpid : gen_datapath_id();
200 dp->chain = chain_create();
202 VLOG_ERR("could not create chain");
207 list_init(&dp->port_list);
209 dp->miss_send_len = OFP_DEFAULT_MISS_SEND_LEN;
215 dp_add_port(struct datapath *dp, const char *name)
217 struct netdev *netdev;
223 error = netdev_open(name, NETDEV_ETH_TYPE_ANY, &netdev);
227 error = netdev_set_flags(netdev, NETDEV_UP | NETDEV_PROMISC, false);
229 VLOG_ERR("Couldn't set promiscuous mode on %s device", name);
230 netdev_close(netdev);
233 if (netdev_get_in4(netdev, &in4)) {
234 VLOG_ERR("%s device has assigned IP address %s", name, inet_ntoa(in4));
236 if (netdev_get_in6(netdev, &in6)) {
237 char in6_name[INET6_ADDRSTRLEN + 1];
238 inet_ntop(AF_INET6, &in6, in6_name, sizeof in6_name);
239 VLOG_ERR("%s device has assigned IPv6 address %s", name, in6_name);
242 for (p = dp->ports; ; p++) {
243 if (p >= &dp->ports[ARRAY_SIZE(dp->ports)]) {
245 } else if (!p->netdev) {
255 list_push_back(&dp->port_list, &p->node);
257 /* Notify the ctlpath that this port has been added */
258 send_port_status(p, OFPPR_ADD);
264 dp_add_listen_vconn(struct datapath *dp, struct vconn *listen_vconn)
266 assert(!dp->listen_vconn);
267 dp->listen_vconn = listen_vconn;
271 dp_run(struct datapath *dp)
273 time_t now = time_now();
274 struct sw_port *p, *pn;
275 struct remote *r, *rn;
276 struct buffer *buffer = NULL;
278 if (now != dp->last_timeout) {
279 struct list deleted = LIST_INITIALIZER(&deleted);
280 struct sw_flow *f, *n;
282 chain_timeout(dp->chain, &deleted);
283 LIST_FOR_EACH_SAFE (f, n, struct sw_flow, node, &deleted) {
284 send_flow_expired(dp, f, f->reason);
285 list_remove(&f->node);
288 dp->last_timeout = now;
290 poll_timer_wait(1000);
292 LIST_FOR_EACH_SAFE (p, pn, struct sw_port, node, &dp->port_list) {
296 /* Allocate buffer with some headroom to add headers in forwarding
297 * to the controller or adding a vlan tag, plus an extra 2 bytes to
298 * allow IP headers to be aligned on a 4-byte boundary. */
299 const int headroom = 128 + 2;
300 const int hard_header = VLAN_ETH_HEADER_LEN;
301 const int mtu = netdev_get_mtu(p->netdev);
302 buffer = buffer_new(headroom + hard_header + mtu);
303 buffer->data += headroom;
305 error = netdev_recv(p->netdev, buffer);
308 fwd_port_input(dp, buffer, port_no(dp, p));
310 } else if (error != EAGAIN) {
311 VLOG_ERR("Error receiving data from %s: %s",
312 netdev_get_name(p->netdev), strerror(error));
316 buffer_delete(buffer);
318 /* Talk to remotes. */
319 LIST_FOR_EACH_SAFE (r, rn, struct remote, node, &dp->remotes) {
322 if (dp->listen_vconn) {
324 struct vconn *new_vconn;
327 retval = vconn_accept(dp->listen_vconn, &new_vconn);
329 if (retval != EAGAIN) {
330 VLOG_WARN("accept failed (%s)", strerror(retval));
334 remote_create(dp, rconn_new_from_vconn("passive", 128, new_vconn));
340 remote_run(struct datapath *dp, struct remote *r)
346 /* Do some remote processing, but cap it at a reasonable amount so that
347 * other processing doesn't starve. */
348 for (i = 0; i < 50; i++) {
350 struct buffer *buffer;
351 struct ofp_header *oh;
353 buffer = rconn_recv(r->rconn);
358 if (buffer->size >= sizeof *oh) {
359 struct sender sender;
363 sender.xid = oh->xid;
364 fwd_control_input(dp, &sender, buffer->data, buffer->size);
366 VLOG_WARN("received too-short OpenFlow message");
368 buffer_delete(buffer);
370 if (!rconn_is_full(r->rconn)) {
371 int error = r->cb_dump(dp, r->cb_aux);
374 VLOG_WARN("dump callback error: %s", strerror(-error));
376 r->cb_done(r->cb_aux);
385 if (!rconn_is_alive(r->rconn)) {
391 remote_wait(struct remote *r)
393 rconn_run_wait(r->rconn);
394 rconn_recv_wait(r->rconn);
398 remote_destroy(struct remote *r)
401 if (r->cb_dump && r->cb_done) {
402 r->cb_done(r->cb_aux);
404 list_remove(&r->node);
405 rconn_destroy(r->rconn);
410 static struct remote *
411 remote_create(struct datapath *dp, struct rconn *rconn)
413 struct remote *remote = xmalloc(sizeof *remote);
414 list_push_back(&dp->remotes, &remote->node);
415 remote->rconn = rconn;
416 remote->cb_dump = NULL;
420 /* Starts a callback-based, reliable, possibly multi-message reply to a
421 * request made by 'remote'.
423 * 'dump' designates a function that will be called when the 'remote' send
424 * queue has an empty slot. It should compose a message and send it on
425 * 'remote'. On success, it should return 1 if it should be called again when
426 * another send queue slot opens up, 0 if its transmissions are complete, or a
427 * negative errno value on failure.
429 * 'done' designates a function to clean up any resources allocated for the
430 * dump. It must handle being called before the dump is complete (which will
431 * happen if 'remote' is closed unexpectedly).
433 * 'aux' is passed to 'dump' and 'done'. */
435 remote_start_dump(struct remote *remote,
436 int (*dump)(struct datapath *, void *),
437 void (*done)(void *),
440 assert(!remote->cb_dump);
441 remote->cb_dump = dump;
442 remote->cb_done = done;
443 remote->cb_aux = aux;
447 dp_wait(struct datapath *dp)
452 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
453 netdev_recv_wait(p->netdev);
455 LIST_FOR_EACH (r, struct remote, node, &dp->remotes) {
458 if (dp->listen_vconn) {
459 vconn_accept_wait(dp->listen_vconn);
463 /* Delete 'p' from switch. */
465 del_switch_port(struct sw_port *p)
467 send_port_status(p, OFPPR_DELETE);
468 netdev_close(p->netdev);
470 list_remove(&p->node);
474 dp_destroy(struct datapath *dp)
476 struct sw_port *p, *n;
482 LIST_FOR_EACH_SAFE (p, n, struct sw_port, node, &dp->port_list) {
485 chain_destroy(dp->chain);
489 /* Send packets out all the ports except the originating one. If the
490 * "flood" argument is set, don't send out ports with flooding disabled.
493 output_all(struct datapath *dp, struct buffer *buffer, int in_port, int flood)
499 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
500 if (port_no(dp, p) == in_port) {
503 if (flood && p->flags & BRIDGE_PORT_NO_FLOOD) {
506 if (prev_port != -1) {
507 dp_output_port(dp, buffer_clone(buffer), in_port, prev_port);
509 prev_port = port_no(dp, p);
512 dp_output_port(dp, buffer, in_port, prev_port);
514 buffer_delete(buffer);
520 output_packet(struct datapath *dp, struct buffer *buffer, int out_port)
522 if (out_port >= 0 && out_port < OFPP_MAX) {
523 struct sw_port *p = &dp->ports[out_port];
524 if (p->netdev != NULL) {
525 if (!netdev_send(p->netdev, buffer)) {
534 buffer_delete(buffer);
535 /* FIXME: ratelimit */
536 VLOG_DBG("can't forward to bad port %d\n", out_port);
539 /* Takes ownership of 'buffer' and transmits it to 'out_port' on 'dp'.
542 dp_output_port(struct datapath *dp, struct buffer *buffer,
543 int in_port, int out_port)
547 if (out_port == OFPP_FLOOD) {
548 output_all(dp, buffer, in_port, 1);
549 } else if (out_port == OFPP_ALL) {
550 output_all(dp, buffer, in_port, 0);
551 } else if (out_port == OFPP_CONTROLLER) {
552 dp_output_control(dp, buffer, in_port, 0, OFPR_ACTION);
553 } else if (out_port == OFPP_TABLE) {
554 if (run_flow_through_tables(dp, buffer, in_port)) {
555 buffer_delete(buffer);
558 output_packet(dp, buffer, out_port);
563 make_openflow_reply(size_t openflow_len, uint8_t type,
564 const struct sender *sender, struct buffer **bufferp)
566 return make_openflow_xid(openflow_len, type, sender ? sender->xid : 0,
571 send_openflow_buffer(struct datapath *dp, struct buffer *buffer,
572 const struct sender *sender)
574 struct remote *remote = sender ? sender->remote : dp->controller;
575 struct rconn *rconn = remote->rconn;
578 update_openflow_length(buffer);
579 retval = rconn_send(rconn, buffer);
581 VLOG_WARN("send to %s failed: %s",
582 rconn_get_name(rconn), strerror(retval));
583 buffer_delete(buffer);
588 /* Takes ownership of 'buffer' and transmits it to 'dp''s controller. If the
589 * packet can be saved in a buffer, then only the first max_len bytes of
590 * 'buffer' are sent; otherwise, all of 'buffer' is sent. 'reason' indicates
591 * why 'buffer' is being sent. 'max_len' sets the maximum number of bytes that
592 * the caller wants to be sent; a value of 0 indicates the entire packet should
595 dp_output_control(struct datapath *dp, struct buffer *buffer, int in_port,
596 size_t max_len, int reason)
598 struct ofp_packet_in *opi;
602 buffer_id = save_buffer(buffer);
603 total_len = buffer->size;
604 if (buffer_id != UINT32_MAX && buffer->size > max_len) {
605 buffer->size = max_len;
608 opi = buffer_push_uninit(buffer, offsetof(struct ofp_packet_in, data));
609 opi->header.version = OFP_VERSION;
610 opi->header.type = OFPT_PACKET_IN;
611 opi->header.length = htons(buffer->size);
612 opi->header.xid = htonl(0);
613 opi->buffer_id = htonl(buffer_id);
614 opi->total_len = htons(total_len);
615 opi->in_port = htons(in_port);
616 opi->reason = reason;
618 send_openflow_buffer(dp, buffer, NULL);
621 static void fill_port_desc(struct datapath *dp, struct sw_port *p,
622 struct ofp_phy_port *desc)
624 desc->port_no = htons(port_no(dp, p));
625 strncpy((char *) desc->name, netdev_get_name(p->netdev),
627 desc->name[sizeof desc->name - 1] = '\0';
628 memcpy(desc->hw_addr, netdev_get_etheraddr(p->netdev), ETH_ADDR_LEN);
629 desc->flags = htonl(p->flags);
630 desc->features = htonl(netdev_get_features(p->netdev));
631 desc->speed = htonl(netdev_get_speed(p->netdev));
635 dp_send_features_reply(struct datapath *dp, const struct sender *sender)
637 struct buffer *buffer;
638 struct ofp_switch_features *ofr;
641 ofr = make_openflow_reply(sizeof *ofr, OFPT_FEATURES_REPLY,
643 ofr->datapath_id = htonll(dp->id);
644 ofr->n_exact = htonl(2 * TABLE_HASH_MAX_FLOWS);
645 ofr->n_compression = 0; /* Not supported */
646 ofr->n_general = htonl(TABLE_LINEAR_MAX_FLOWS);
647 ofr->buffer_mb = htonl(UINT32_MAX);
648 ofr->n_buffers = htonl(N_PKT_BUFFERS);
649 ofr->capabilities = htonl(OFP_SUPPORTED_CAPABILITIES);
650 ofr->actions = htonl(OFP_SUPPORTED_ACTIONS);
651 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
652 struct ofp_phy_port *opp = buffer_put_uninit(buffer, sizeof *opp);
653 memset(opp, 0, sizeof *opp);
654 fill_port_desc(dp, p, opp);
656 send_openflow_buffer(dp, buffer, sender);
660 dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp)
662 int port_no = ntohs(opp->port_no);
663 if (port_no < OFPP_MAX) {
664 struct sw_port *p = &dp->ports[port_no];
666 /* Make sure the port id hasn't changed since this was sent */
667 if (!p || memcmp(opp->hw_addr, netdev_get_etheraddr(p->netdev),
668 ETH_ADDR_LEN) != 0) {
671 p->flags = htonl(opp->flags);
676 send_port_status(struct sw_port *p, uint8_t status)
678 struct buffer *buffer;
679 struct ofp_port_status *ops;
680 ops = make_openflow_xid(sizeof *ops, OFPT_PORT_STATUS, 0, &buffer);
681 ops->reason = status;
682 memset(ops->pad, 0, sizeof ops->pad);
683 fill_port_desc(p->dp, p, &ops->desc);
685 send_openflow_buffer(p->dp, buffer, NULL);
689 send_flow_expired(struct datapath *dp, struct sw_flow *flow,
690 enum ofp_flow_expired_reason reason)
692 struct buffer *buffer;
693 struct ofp_flow_expired *ofe;
694 ofe = make_openflow_xid(sizeof *ofe, OFPT_FLOW_EXPIRED, 0, &buffer);
695 flow_fill_match(&ofe->match, &flow->key);
697 ofe->priority = htons(flow->priority);
698 ofe->reason = reason;
699 memset(ofe->pad, 0, sizeof ofe->pad);
701 ofe->duration = htonl(time_now() - flow->created);
702 memset(ofe->pad2, 0, sizeof ofe->pad2);
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->priority = htons(flow->priority);
746 ofs->idle_timeout = htons(flow->idle_timeout);
747 ofs->hard_timeout = htons(flow->hard_timeout);
748 memset(ofs->pad2, 0, sizeof ofs->pad2);
749 ofs->packet_count = htonll(flow->packet_count);
750 ofs->byte_count = htonll(flow->byte_count);
751 memcpy(ofs->actions, flow->actions,
752 sizeof *ofs->actions * flow->n_actions);
756 /* 'buffer' was received on 'in_port', a physical switch port between 0 and
757 * OFPP_MAX. Process it according to 'dp''s flow table. Returns 0 if
758 * successful, in which case 'buffer' is destroyed, or -ESRCH if there is no
759 * matching flow, in which case 'buffer' still belongs to the caller. */
760 int run_flow_through_tables(struct datapath *dp, struct buffer *buffer,
763 struct sw_flow_key key;
764 struct sw_flow *flow;
767 if (flow_extract(buffer, in_port, &key.flow)
768 && (dp->flags & OFPC_FRAG_MASK) == OFPC_FRAG_DROP) {
770 buffer_delete(buffer);
774 flow = chain_lookup(dp->chain, &key);
776 flow_used(flow, buffer);
777 execute_actions(dp, buffer, in_port, &key,
778 flow->actions, flow->n_actions);
785 /* 'buffer' was received on 'in_port', a physical switch port between 0 and
786 * OFPP_MAX. Process it according to 'dp''s flow table, sending it up to the
787 * controller if no flow matches. Takes ownership of 'buffer'. */
788 void fwd_port_input(struct datapath *dp, struct buffer *buffer, int in_port)
790 if (run_flow_through_tables(dp, buffer, in_port)) {
791 dp_output_control(dp, buffer, in_port, dp->miss_send_len,
797 do_output(struct datapath *dp, struct buffer *buffer, int in_port,
798 size_t max_len, int out_port)
800 if (out_port != OFPP_CONTROLLER) {
801 dp_output_port(dp, buffer, in_port, out_port);
803 dp_output_control(dp, buffer, in_port, max_len, OFPR_ACTION);
808 execute_actions(struct datapath *dp, struct buffer *buffer,
809 int in_port, const struct sw_flow_key *key,
810 const struct ofp_action *actions, int n_actions)
812 /* Every output action needs a separate clone of 'buffer', but the common
813 * case is just a single output action, so that doing a clone and then
814 * freeing the original buffer is wasteful. So the following code is
815 * slightly obscure just to avoid that. */
817 size_t max_len=0; /* Initialze to make compiler happy */
822 eth_proto = ntohs(key->flow.dl_type);
824 for (i = 0; i < n_actions; i++) {
825 const struct ofp_action *a = &actions[i];
826 struct eth_header *eh = buffer->l2;
828 if (prev_port != -1) {
829 do_output(dp, buffer_clone(buffer), in_port, max_len, prev_port);
833 switch (ntohs(a->type)) {
835 prev_port = ntohs(a->arg.output.port);
836 max_len = ntohs(a->arg.output.max_len);
839 case OFPAT_SET_DL_VLAN:
840 modify_vlan(buffer, key, a);
843 case OFPAT_SET_DL_SRC:
844 memcpy(eh->eth_src, a->arg.dl_addr, sizeof eh->eth_src);
847 case OFPAT_SET_DL_DST:
848 memcpy(eh->eth_dst, a->arg.dl_addr, sizeof eh->eth_dst);
851 case OFPAT_SET_NW_SRC:
852 case OFPAT_SET_NW_DST:
853 modify_nh(buffer, eth_proto, key->flow.nw_proto, a);
856 case OFPAT_SET_TP_SRC:
857 case OFPAT_SET_TP_DST:
858 modify_th(buffer, eth_proto, key->flow.nw_proto, a);
866 do_output(dp, buffer, in_port, max_len, prev_port);
868 buffer_delete(buffer);
871 static void modify_nh(struct buffer *buffer, uint16_t eth_proto,
872 uint8_t nw_proto, const struct ofp_action *a)
874 if (eth_proto == ETH_TYPE_IP) {
875 struct ip_header *nh = buffer->l3;
876 uint32_t new, *field;
878 new = a->arg.nw_addr;
879 field = a->type == OFPAT_SET_NW_SRC ? &nh->ip_src : &nh->ip_dst;
880 if (nw_proto == IP_TYPE_TCP) {
881 struct tcp_header *th = buffer->l4;
882 th->tcp_csum = recalc_csum32(th->tcp_csum, *field, new);
883 } else if (nw_proto == IP_TYPE_UDP) {
884 struct udp_header *th = buffer->l4;
886 th->udp_csum = recalc_csum32(th->udp_csum, *field, new);
888 th->udp_csum = 0xffff;
892 nh->ip_csum = recalc_csum32(nh->ip_csum, *field, new);
897 static void modify_th(struct buffer *buffer, uint16_t eth_proto,
898 uint8_t nw_proto, const struct ofp_action *a)
900 if (eth_proto == ETH_TYPE_IP) {
901 uint16_t new, *field;
905 if (nw_proto == IP_TYPE_TCP) {
906 struct tcp_header *th = buffer->l4;
907 field = a->type == OFPAT_SET_TP_SRC ? &th->tcp_src : &th->tcp_dst;
908 th->tcp_csum = recalc_csum16(th->tcp_csum, *field, new);
910 } else if (nw_proto == IP_TYPE_UDP) {
911 struct udp_header *th = buffer->l4;
912 field = a->type == OFPAT_SET_TP_SRC ? &th->udp_src : &th->udp_dst;
913 th->udp_csum = recalc_csum16(th->udp_csum, *field, new);
920 modify_vlan(struct buffer *buffer,
921 const struct sw_flow_key *key, const struct ofp_action *a)
923 uint16_t new_id = a->arg.vlan_id;
924 struct vlan_eth_header *veh;
926 if (new_id != htons(OFP_VLAN_NONE)) {
927 if (key->flow.dl_vlan != htons(OFP_VLAN_NONE)) {
928 /* Modify vlan id, but maintain other TCI values */
930 veh->veth_tci &= ~htons(VLAN_VID);
931 veh->veth_tci |= new_id;
933 /* Insert new vlan id. */
934 struct eth_header *eh = buffer->l2;
935 struct vlan_eth_header tmp;
936 memcpy(tmp.veth_dst, eh->eth_dst, ETH_ADDR_LEN);
937 memcpy(tmp.veth_src, eh->eth_src, ETH_ADDR_LEN);
938 tmp.veth_type = htons(ETH_TYPE_VLAN);
939 tmp.veth_tci = new_id;
940 tmp.veth_next_type = eh->eth_type;
942 veh = buffer_push_uninit(buffer, VLAN_HEADER_LEN);
943 memcpy(veh, &tmp, sizeof tmp);
944 buffer->l2 -= VLAN_HEADER_LEN;
947 /* Remove an existing vlan header if it exists */
949 if (veh->veth_type == htons(ETH_TYPE_VLAN)) {
950 struct eth_header tmp;
952 memcpy(tmp.eth_dst, veh->veth_dst, ETH_ADDR_LEN);
953 memcpy(tmp.eth_src, veh->veth_src, ETH_ADDR_LEN);
954 tmp.eth_type = veh->veth_next_type;
956 buffer->size -= VLAN_HEADER_LEN;
957 buffer->data += VLAN_HEADER_LEN;
958 buffer->l2 += VLAN_HEADER_LEN;
959 memcpy(buffer->data, &tmp, sizeof tmp);
965 recv_features_request(struct datapath *dp, const struct sender *sender,
968 dp_send_features_reply(dp, sender);
973 recv_get_config_request(struct datapath *dp, const struct sender *sender,
976 struct buffer *buffer;
977 struct ofp_switch_config *osc;
979 osc = make_openflow_reply(sizeof *osc, OFPT_GET_CONFIG_REPLY,
982 osc->flags = htons(dp->flags);
983 osc->miss_send_len = htons(dp->miss_send_len);
985 return send_openflow_buffer(dp, buffer, sender);
989 recv_set_config(struct datapath *dp, const struct sender *sender UNUSED,
992 const struct ofp_switch_config *osc = msg;
995 flags = ntohs(osc->flags) & (OFPC_SEND_FLOW_EXP | OFPC_FRAG_MASK);
996 if ((flags & OFPC_FRAG_MASK) != OFPC_FRAG_NORMAL
997 && (flags & OFPC_FRAG_MASK) != OFPC_FRAG_DROP) {
998 flags = (flags & ~OFPC_FRAG_MASK) | OFPC_FRAG_DROP;
1001 dp->miss_send_len = ntohs(osc->miss_send_len);
1006 recv_packet_out(struct datapath *dp, const struct sender *sender UNUSED,
1009 const struct ofp_packet_out *opo = msg;
1011 if (ntohl(opo->buffer_id) == (uint32_t) -1) {
1012 /* FIXME: can we avoid copying data here? */
1013 int data_len = ntohs(opo->header.length) - sizeof *opo;
1014 struct buffer *buffer = buffer_new(data_len);
1015 buffer_put(buffer, opo->u.data, data_len);
1016 dp_output_port(dp, buffer,
1017 ntohs(opo->in_port), ntohs(opo->out_port));
1019 struct sw_flow_key key;
1020 struct buffer *buffer;
1023 buffer = retrieve_buffer(ntohl(opo->buffer_id));
1028 n_acts = (ntohs(opo->header.length) - sizeof *opo)
1029 / sizeof *opo->u.actions;
1030 flow_extract(buffer, ntohs(opo->in_port), &key.flow);
1031 execute_actions(dp, buffer, ntohs(opo->in_port),
1032 &key, opo->u.actions, n_acts);
1038 recv_port_mod(struct datapath *dp, const struct sender *sender UNUSED,
1041 const struct ofp_port_mod *opm = msg;
1043 dp_update_port_flags(dp, &opm->desc);
1049 add_flow(struct datapath *dp, const struct ofp_flow_mod *ofm)
1051 int error = -ENOMEM;
1054 struct sw_flow *flow;
1057 /* To prevent loops, make sure there's no action to send to the
1058 * OFP_TABLE virtual port.
1060 n_acts = (ntohs(ofm->header.length) - sizeof *ofm) / sizeof *ofm->actions;
1061 for (i=0; i<n_acts; i++) {
1062 const struct ofp_action *a = &ofm->actions[i];
1064 if (a->type == htons(OFPAT_OUTPUT)
1065 && (a->arg.output.port == htons(OFPP_TABLE)
1066 || a->arg.output.port == htons(OFPP_NONE))) {
1067 /* xxx Send fancy new error message? */
1072 /* Allocate memory. */
1073 flow = flow_alloc(n_acts);
1077 /* Fill out flow. */
1078 flow_extract_match(&flow->key, &ofm->match);
1079 flow->priority = flow->key.wildcards ? ntohs(ofm->priority) : -1;
1080 flow->idle_timeout = ntohs(ofm->idle_timeout);
1081 flow->hard_timeout = ntohs(ofm->hard_timeout);
1082 flow->used = flow->created = time_now();
1083 flow->n_actions = n_acts;
1084 flow->byte_count = 0;
1085 flow->packet_count = 0;
1086 memcpy(flow->actions, ofm->actions, n_acts * sizeof *flow->actions);
1089 error = chain_insert(dp->chain, flow);
1091 goto error_free_flow;
1094 if (ntohl(ofm->buffer_id) != UINT32_MAX) {
1095 struct buffer *buffer = retrieve_buffer(ntohl(ofm->buffer_id));
1097 struct sw_flow_key key;
1098 uint16_t in_port = ntohs(ofm->match.in_port);
1099 flow_used(flow, buffer);
1100 flow_extract(buffer, in_port, &key.flow);
1101 execute_actions(dp, buffer, in_port, &key, ofm->actions, n_acts);
1111 if (ntohl(ofm->buffer_id) != (uint32_t) -1)
1112 discard_buffer(ntohl(ofm->buffer_id));
1117 recv_flow(struct datapath *dp, const struct sender *sender UNUSED,
1120 const struct ofp_flow_mod *ofm = msg;
1121 uint16_t command = ntohs(ofm->command);
1123 if (command == OFPFC_ADD) {
1124 return add_flow(dp, ofm);
1125 } else if (command == OFPFC_DELETE) {
1126 struct sw_flow_key key;
1127 flow_extract_match(&key, &ofm->match);
1128 return chain_delete(dp->chain, &key, 0, 0) ? 0 : -ESRCH;
1129 } else if (command == OFPFC_DELETE_STRICT) {
1130 struct sw_flow_key key;
1132 flow_extract_match(&key, &ofm->match);
1133 priority = key.wildcards ? ntohs(ofm->priority) : -1;
1134 return chain_delete(dp->chain, &key, priority, 1) ? 0 : -ESRCH;
1140 struct flow_stats_state {
1142 struct sw_table_position position;
1143 struct ofp_flow_stats_request rq;
1146 struct buffer *buffer;
1149 #define MAX_FLOW_STATS_BYTES 4096
1151 static int flow_stats_init(struct datapath *dp, const void *body, int body_len,
1154 const struct ofp_flow_stats_request *fsr = body;
1155 struct flow_stats_state *s = xmalloc(sizeof *s);
1156 s->table_idx = fsr->table_id == 0xff ? 0 : fsr->table_id;
1157 memset(&s->position, 0, sizeof s->position);
1163 static int flow_stats_dump_callback(struct sw_flow *flow, void *private)
1165 struct flow_stats_state *s = private;
1166 fill_flow_stats(s->buffer, flow, s->table_idx, s->now);
1167 return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1170 static int flow_stats_dump(struct datapath *dp, void *state,
1171 struct buffer *buffer)
1173 struct flow_stats_state *s = state;
1174 struct sw_flow_key match_key;
1176 flow_extract_match(&match_key, &s->rq.match);
1178 s->now = time_now();
1179 while (s->table_idx < dp->chain->n_tables
1180 && (s->rq.table_id == 0xff || s->rq.table_id == s->table_idx))
1182 struct sw_table *table = dp->chain->tables[s->table_idx];
1184 if (table->iterate(table, &match_key, &s->position,
1185 flow_stats_dump_callback, s))
1189 memset(&s->position, 0, sizeof s->position);
1191 return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1194 static void flow_stats_done(void *state)
1199 struct aggregate_stats_state {
1200 struct ofp_aggregate_stats_request rq;
1203 static int aggregate_stats_init(struct datapath *dp,
1204 const void *body, int body_len,
1207 const struct ofp_aggregate_stats_request *rq = body;
1208 struct aggregate_stats_state *s = xmalloc(sizeof *s);
1214 static int aggregate_stats_dump_callback(struct sw_flow *flow, void *private)
1216 struct ofp_aggregate_stats_reply *rpy = private;
1217 rpy->packet_count += flow->packet_count;
1218 rpy->byte_count += flow->byte_count;
1223 static int aggregate_stats_dump(struct datapath *dp, void *state,
1224 struct buffer *buffer)
1226 struct aggregate_stats_state *s = state;
1227 struct ofp_aggregate_stats_request *rq = &s->rq;
1228 struct ofp_aggregate_stats_reply *rpy;
1229 struct sw_table_position position;
1230 struct sw_flow_key match_key;
1233 rpy = buffer_put_uninit(buffer, sizeof *rpy);
1234 memset(rpy, 0, sizeof *rpy);
1236 flow_extract_match(&match_key, &rq->match);
1237 table_idx = rq->table_id == 0xff ? 0 : rq->table_id;
1238 memset(&position, 0, sizeof position);
1239 while (table_idx < dp->chain->n_tables
1240 && (rq->table_id == 0xff || rq->table_id == table_idx))
1242 struct sw_table *table = dp->chain->tables[table_idx];
1245 error = table->iterate(table, &match_key, &position,
1246 aggregate_stats_dump_callback, rpy);
1251 memset(&position, 0, sizeof position);
1254 rpy->packet_count = htonll(rpy->packet_count);
1255 rpy->byte_count = htonll(rpy->byte_count);
1256 rpy->flow_count = htonl(rpy->flow_count);
1260 static void aggregate_stats_done(void *state)
1265 static int table_stats_dump(struct datapath *dp, void *state,
1266 struct buffer *buffer)
1269 for (i = 0; i < dp->chain->n_tables; i++) {
1270 struct ofp_table_stats *ots = buffer_put_uninit(buffer, sizeof *ots);
1271 struct sw_table_stats stats;
1272 dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
1273 strncpy(ots->name, stats.name, sizeof ots->name);
1275 memset(ots->pad, 0, sizeof ots->pad);
1276 ots->max_entries = htonl(stats.max_flows);
1277 ots->active_count = htonl(stats.n_flows);
1278 ots->matched_count = htonll(stats.n_matched);
1283 struct port_stats_state {
1287 static int port_stats_init(struct datapath *dp, const void *body, int body_len,
1290 struct port_stats_state *s = xmalloc(sizeof *s);
1296 static int port_stats_dump(struct datapath *dp, void *state,
1297 struct buffer *buffer)
1299 struct port_stats_state *s = state;
1302 for (i = s->port; i < OFPP_MAX; i++) {
1303 struct sw_port *p = &dp->ports[i];
1304 struct ofp_port_stats *ops;
1308 ops = buffer_put_uninit(buffer, sizeof *ops);
1309 ops->port_no = htons(port_no(dp, p));
1310 memset(ops->pad, 0, sizeof ops->pad);
1311 ops->rx_count = htonll(p->rx_count);
1312 ops->tx_count = htonll(p->tx_count);
1313 ops->drop_count = htonll(p->drop_count);
1320 static void port_stats_done(void *state)
1326 /* Minimum and maximum acceptable number of bytes in body member of
1327 * struct ofp_stats_request. */
1328 size_t min_body, max_body;
1330 /* Prepares to dump some kind of statistics on 'dp'. 'body' and
1331 * 'body_len' are the 'body' member of the struct ofp_stats_request.
1332 * Returns zero if successful, otherwise a negative error code.
1333 * May initialize '*state' to state information. May be null if no
1334 * initialization is required.*/
1335 int (*init)(struct datapath *dp, const void *body, int body_len,
1338 /* Appends statistics for 'dp' to 'buffer', which initially contains a
1339 * struct ofp_stats_reply. On success, it should return 1 if it should be
1340 * called again later with another buffer, 0 if it is done, or a negative
1341 * errno value on failure. */
1342 int (*dump)(struct datapath *dp, void *state, struct buffer *buffer);
1344 /* Cleans any state created by the init or dump functions. May be null
1345 * if no cleanup is required. */
1346 void (*done)(void *state);
1349 static const struct stats_type stats[] = {
1351 sizeof(struct ofp_flow_stats_request),
1352 sizeof(struct ofp_flow_stats_request),
1357 [OFPST_AGGREGATE] = {
1358 sizeof(struct ofp_aggregate_stats_request),
1359 sizeof(struct ofp_aggregate_stats_request),
1360 aggregate_stats_init,
1361 aggregate_stats_dump,
1362 aggregate_stats_done
1380 struct stats_dump_cb {
1382 struct ofp_stats_request *rq;
1383 struct sender sender;
1384 const struct stats_type *s;
1389 stats_dump(struct datapath *dp, void *cb_)
1391 struct stats_dump_cb *cb = cb_;
1392 struct ofp_stats_reply *osr;
1393 struct buffer *buffer;
1400 osr = make_openflow_reply(sizeof *osr, OFPT_STATS_REPLY, &cb->sender,
1402 osr->type = htons(cb->s - stats);
1405 err = cb->s->dump(dp, cb->state, buffer);
1411 /* Buffer might have been reallocated, so find our data again. */
1412 osr = buffer_at_assert(buffer, 0, sizeof *osr);
1413 osr->flags = ntohs(OFPSF_REPLY_MORE);
1415 err2 = send_openflow_buffer(dp, buffer, &cb->sender);
1425 stats_done(void *cb_)
1427 struct stats_dump_cb *cb = cb_;
1430 cb->s->done(cb->state);
1437 recv_stats_request(struct datapath *dp, const struct sender *sender,
1440 const struct ofp_stats_request *rq = oh;
1441 size_t rq_len = ntohs(rq->header.length);
1442 struct stats_dump_cb *cb;
1446 type = ntohs(rq->type);
1447 if (type >= ARRAY_SIZE(stats) || !stats[type].dump) {
1448 VLOG_WARN("received stats request of unknown type %d", type);
1452 cb = xmalloc(sizeof *cb);
1454 cb->rq = xmemdup(rq, rq_len);
1455 cb->sender = *sender;
1456 cb->s = &stats[type];
1459 body_len = rq_len - offsetof(struct ofp_stats_request, body);
1460 if (body_len < cb->s->min_body || body_len > cb->s->max_body) {
1461 VLOG_WARN("stats request type %d with bad body length %d",
1468 err = cb->s->init(dp, rq->body, body_len, &cb->state);
1470 VLOG_WARN("failed initialization of stats request type %d: %s",
1471 type, strerror(-err));
1476 remote_start_dump(sender->remote, stats_dump, stats_done, cb);
1486 recv_echo_request(struct datapath *dp, const struct sender *sender,
1489 return send_openflow_buffer(dp, make_echo_reply(oh), sender);
1493 recv_echo_reply(struct datapath *dp UNUSED, const struct sender *sender UNUSED,
1494 const void *oh UNUSED)
1499 /* 'msg', which is 'length' bytes long, was received from the control path.
1500 * Apply it to 'chain'. */
1502 fwd_control_input(struct datapath *dp, const struct sender *sender,
1503 const void *msg, size_t length)
1505 struct openflow_packet {
1507 int (*handler)(struct datapath *, const struct sender *, const void *);
1510 static const struct openflow_packet packets[] = {
1511 [OFPT_FEATURES_REQUEST] = {
1512 sizeof (struct ofp_header),
1513 recv_features_request,
1515 [OFPT_GET_CONFIG_REQUEST] = {
1516 sizeof (struct ofp_header),
1517 recv_get_config_request,
1519 [OFPT_SET_CONFIG] = {
1520 sizeof (struct ofp_switch_config),
1523 [OFPT_PACKET_OUT] = {
1524 sizeof (struct ofp_packet_out),
1528 sizeof (struct ofp_flow_mod),
1532 sizeof (struct ofp_port_mod),
1535 [OFPT_STATS_REQUEST] = {
1536 sizeof (struct ofp_stats_request),
1539 [OFPT_ECHO_REQUEST] = {
1540 sizeof (struct ofp_header),
1543 [OFPT_ECHO_REPLY] = {
1544 sizeof (struct ofp_header),
1549 const struct openflow_packet *pkt;
1550 struct ofp_header *oh;
1552 oh = (struct ofp_header *) msg;
1553 assert(oh->version == OFP_VERSION);
1554 if (oh->type >= ARRAY_SIZE(packets) || 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_now() < 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_now() + 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);