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_packets, tx_packets;
81 unsigned long long int rx_bytes, tx_bytes;
82 unsigned long long int tx_dropped;
85 /* The origin of a received OpenFlow message, to enable sending a reply. */
87 struct remote *remote; /* The device that sent the message. */
88 uint32_t xid; /* The OpenFlow transaction ID. */
91 /* A connection to a controller or a management device. */
95 #define TXQ_LIMIT 128 /* Max number of packets to queue for tx. */
96 int n_txq; /* Number of packets queued for tx on rconn. */
98 /* Support for reliable, multi-message replies to requests.
100 * If an incoming request needs to have a reliable reply that might
101 * require multiple messages, it can use remote_start_dump() to set up
102 * a callback that will be called as buffer space for replies. */
103 int (*cb_dump)(struct datapath *, void *aux);
104 void (*cb_done)(void *aux);
109 /* Remote connections. */
110 struct remote *controller; /* Connection to controller. */
111 struct list remotes; /* All connections (including controller). */
112 struct vconn *listen_vconn;
116 /* Unique identifier for this datapath */
119 struct sw_chain *chain; /* Forwarding rules. */
121 /* Configuration set from controller. */
123 uint16_t miss_send_len;
126 struct sw_port ports[OFPP_MAX];
127 struct list port_list; /* List of ports, for flooding. */
130 static struct remote *remote_create(struct datapath *, struct rconn *);
131 static void remote_run(struct datapath *, struct remote *);
132 static void remote_wait(struct remote *);
133 static void remote_destroy(struct remote *);
135 void dp_output_port(struct datapath *, struct buffer *,
136 int in_port, int out_port);
137 void dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp);
138 void dp_output_control(struct datapath *, struct buffer *, int in_port,
139 size_t max_len, int reason);
140 static void send_flow_expired(struct datapath *, struct sw_flow *,
141 enum ofp_flow_expired_reason);
142 static void send_port_status(struct sw_port *p, uint8_t status);
143 static void del_switch_port(struct sw_port *p);
144 static void execute_actions(struct datapath *, struct buffer *,
145 int in_port, const struct sw_flow_key *,
146 const struct ofp_action *, int n_actions);
147 static void modify_vlan(struct buffer *buffer, const struct sw_flow_key *key,
148 const struct ofp_action *a);
149 static void modify_nh(struct buffer *buffer, uint16_t eth_proto,
150 uint8_t nw_proto, const struct ofp_action *a);
151 static void modify_th(struct buffer *buffer, uint16_t eth_proto,
152 uint8_t nw_proto, const struct ofp_action *a);
154 /* Buffers are identified to userspace by a 31-bit opaque ID. We divide the ID
155 * into a buffer number (low bits) and a cookie (high bits). The buffer number
156 * is an index into an array of buffers. The cookie distinguishes between
157 * different packets that have occupied a single buffer. Thus, the more
158 * buffers we have, the lower-quality the cookie... */
159 #define PKT_BUFFER_BITS 8
160 #define N_PKT_BUFFERS (1 << PKT_BUFFER_BITS)
161 #define PKT_BUFFER_MASK (N_PKT_BUFFERS - 1)
163 #define PKT_COOKIE_BITS (32 - PKT_BUFFER_BITS)
165 int run_flow_through_tables(struct datapath *, struct buffer *, int in_port);
166 void fwd_port_input(struct datapath *, struct buffer *, int in_port);
167 int fwd_control_input(struct datapath *, const struct sender *,
168 const void *, size_t);
170 uint32_t save_buffer(struct buffer *);
171 static struct buffer *retrieve_buffer(uint32_t id);
172 static void discard_buffer(uint32_t id);
174 static int port_no(struct datapath *dp, struct sw_port *p)
176 assert(p >= dp->ports && p < &dp->ports[ARRAY_SIZE(dp->ports)]);
177 return p - dp->ports;
180 /* Generates and returns a random datapath id. */
182 gen_datapath_id(void)
184 uint8_t ea[ETH_ADDR_LEN];
186 return eth_addr_to_uint64(ea);
190 dp_new(struct datapath **dp_, uint64_t dpid, struct rconn *rconn)
194 dp = calloc(1, sizeof *dp);
199 dp->last_timeout = time_now();
200 list_init(&dp->remotes);
201 dp->controller = remote_create(dp, rconn);
202 dp->listen_vconn = NULL;
203 dp->id = dpid <= UINT64_C(0xffffffffffff) ? dpid : gen_datapath_id();
204 dp->chain = chain_create();
206 VLOG_ERR("could not create chain");
211 list_init(&dp->port_list);
213 dp->miss_send_len = OFP_DEFAULT_MISS_SEND_LEN;
219 dp_add_port(struct datapath *dp, const char *name)
221 struct netdev *netdev;
227 error = netdev_open(name, NETDEV_ETH_TYPE_ANY, &netdev);
231 error = netdev_set_flags(netdev, NETDEV_UP | NETDEV_PROMISC, false);
233 VLOG_ERR("Couldn't set promiscuous mode on %s device", name);
234 netdev_close(netdev);
237 if (netdev_get_in4(netdev, &in4)) {
238 VLOG_ERR("%s device has assigned IP address %s", name, inet_ntoa(in4));
240 if (netdev_get_in6(netdev, &in6)) {
241 char in6_name[INET6_ADDRSTRLEN + 1];
242 inet_ntop(AF_INET6, &in6, in6_name, sizeof in6_name);
243 VLOG_ERR("%s device has assigned IPv6 address %s", name, in6_name);
246 for (p = dp->ports; ; p++) {
247 if (p >= &dp->ports[ARRAY_SIZE(dp->ports)]) {
249 } else if (!p->netdev) {
254 memset(p, '\0', sizeof *p);
258 list_push_back(&dp->port_list, &p->node);
260 /* Notify the ctlpath that this port has been added */
261 send_port_status(p, OFPPR_ADD);
267 dp_add_listen_vconn(struct datapath *dp, struct vconn *listen_vconn)
269 assert(!dp->listen_vconn);
270 dp->listen_vconn = listen_vconn;
274 dp_run(struct datapath *dp)
276 time_t now = time_now();
277 struct sw_port *p, *pn;
278 struct remote *r, *rn;
279 struct buffer *buffer = NULL;
281 if (now != dp->last_timeout) {
282 struct list deleted = LIST_INITIALIZER(&deleted);
283 struct sw_flow *f, *n;
285 chain_timeout(dp->chain, &deleted);
286 LIST_FOR_EACH_SAFE (f, n, struct sw_flow, node, &deleted) {
287 send_flow_expired(dp, f, f->reason);
288 list_remove(&f->node);
291 dp->last_timeout = now;
293 poll_timer_wait(1000);
295 LIST_FOR_EACH_SAFE (p, pn, struct sw_port, node, &dp->port_list) {
299 /* Allocate buffer with some headroom to add headers in forwarding
300 * to the controller or adding a vlan tag, plus an extra 2 bytes to
301 * allow IP headers to be aligned on a 4-byte boundary. */
302 const int headroom = 128 + 2;
303 const int hard_header = VLAN_ETH_HEADER_LEN;
304 const int mtu = netdev_get_mtu(p->netdev);
305 buffer = buffer_new(headroom + hard_header + mtu);
306 buffer->data += headroom;
308 error = netdev_recv(p->netdev, buffer);
311 p->rx_bytes += buffer->size;
312 fwd_port_input(dp, buffer, port_no(dp, p));
314 } else if (error != EAGAIN) {
315 VLOG_ERR("Error receiving data from %s: %s",
316 netdev_get_name(p->netdev), strerror(error));
320 buffer_delete(buffer);
322 /* Talk to remotes. */
323 LIST_FOR_EACH_SAFE (r, rn, struct remote, node, &dp->remotes) {
326 if (dp->listen_vconn) {
328 struct vconn *new_vconn;
331 retval = vconn_accept(dp->listen_vconn, &new_vconn);
333 if (retval != EAGAIN) {
334 VLOG_WARN("accept failed (%s)", strerror(retval));
338 remote_create(dp, rconn_new_from_vconn("passive", new_vconn));
344 remote_run(struct datapath *dp, struct remote *r)
350 /* Do some remote processing, but cap it at a reasonable amount so that
351 * other processing doesn't starve. */
352 for (i = 0; i < 50; i++) {
354 struct buffer *buffer;
355 struct ofp_header *oh;
357 buffer = rconn_recv(r->rconn);
362 if (buffer->size >= sizeof *oh) {
363 struct sender sender;
367 sender.xid = oh->xid;
368 fwd_control_input(dp, &sender, buffer->data, buffer->size);
370 VLOG_WARN("received too-short OpenFlow message");
372 buffer_delete(buffer);
374 if (r->n_txq < TXQ_LIMIT) {
375 int error = r->cb_dump(dp, r->cb_aux);
378 VLOG_WARN("dump callback error: %s", strerror(-error));
380 r->cb_done(r->cb_aux);
389 if (!rconn_is_alive(r->rconn)) {
395 remote_wait(struct remote *r)
397 rconn_run_wait(r->rconn);
398 rconn_recv_wait(r->rconn);
402 remote_destroy(struct remote *r)
405 if (r->cb_dump && r->cb_done) {
406 r->cb_done(r->cb_aux);
408 list_remove(&r->node);
409 rconn_destroy(r->rconn);
414 static struct remote *
415 remote_create(struct datapath *dp, struct rconn *rconn)
417 struct remote *remote = xmalloc(sizeof *remote);
418 list_push_back(&dp->remotes, &remote->node);
419 remote->rconn = rconn;
420 remote->cb_dump = NULL;
424 /* Starts a callback-based, reliable, possibly multi-message reply to a
425 * request made by 'remote'.
427 * 'dump' designates a function that will be called when the 'remote' send
428 * queue has an empty slot. It should compose a message and send it on
429 * 'remote'. On success, it should return 1 if it should be called again when
430 * another send queue slot opens up, 0 if its transmissions are complete, or a
431 * negative errno value on failure.
433 * 'done' designates a function to clean up any resources allocated for the
434 * dump. It must handle being called before the dump is complete (which will
435 * happen if 'remote' is closed unexpectedly).
437 * 'aux' is passed to 'dump' and 'done'. */
439 remote_start_dump(struct remote *remote,
440 int (*dump)(struct datapath *, void *),
441 void (*done)(void *),
444 assert(!remote->cb_dump);
445 remote->cb_dump = dump;
446 remote->cb_done = done;
447 remote->cb_aux = aux;
451 dp_wait(struct datapath *dp)
456 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
457 netdev_recv_wait(p->netdev);
459 LIST_FOR_EACH (r, struct remote, node, &dp->remotes) {
462 if (dp->listen_vconn) {
463 vconn_accept_wait(dp->listen_vconn);
467 /* Delete 'p' from switch. */
469 del_switch_port(struct sw_port *p)
471 send_port_status(p, OFPPR_DELETE);
472 netdev_close(p->netdev);
474 list_remove(&p->node);
478 dp_destroy(struct datapath *dp)
480 struct sw_port *p, *n;
486 LIST_FOR_EACH_SAFE (p, n, struct sw_port, node, &dp->port_list) {
489 chain_destroy(dp->chain);
493 /* Send packets out all the ports except the originating one. If the
494 * "flood" argument is set, don't send out ports with flooding disabled.
497 output_all(struct datapath *dp, struct buffer *buffer, int in_port, int flood)
503 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
504 if (port_no(dp, p) == in_port) {
507 if (flood && p->flags & BRIDGE_PORT_NO_FLOOD) {
510 if (prev_port != -1) {
511 dp_output_port(dp, buffer_clone(buffer), in_port, prev_port);
513 prev_port = port_no(dp, p);
516 dp_output_port(dp, buffer, in_port, prev_port);
518 buffer_delete(buffer);
524 output_packet(struct datapath *dp, struct buffer *buffer, int out_port)
526 if (out_port >= 0 && out_port < OFPP_MAX) {
527 struct sw_port *p = &dp->ports[out_port];
528 if (p->netdev != NULL) {
529 if (!netdev_send(p->netdev, buffer)) {
531 p->tx_bytes += buffer->size;
539 buffer_delete(buffer);
540 /* FIXME: ratelimit */
541 VLOG_DBG("can't forward to bad port %d\n", out_port);
544 /* Takes ownership of 'buffer' and transmits it to 'out_port' on 'dp'.
547 dp_output_port(struct datapath *dp, struct buffer *buffer,
548 int in_port, int out_port)
552 if (out_port == OFPP_FLOOD) {
553 output_all(dp, buffer, in_port, 1);
554 } else if (out_port == OFPP_ALL) {
555 output_all(dp, buffer, in_port, 0);
556 } else if (out_port == OFPP_CONTROLLER) {
557 dp_output_control(dp, buffer, in_port, 0, OFPR_ACTION);
558 } else if (out_port == OFPP_IN_PORT) {
559 output_packet(dp, buffer, in_port);
560 } else if (out_port == OFPP_TABLE) {
561 if (run_flow_through_tables(dp, buffer, in_port)) {
562 buffer_delete(buffer);
565 if (in_port == out_port) {
566 /* FIXME: ratelimit */
567 VLOG_DBG("can't directly forward to input port");
570 output_packet(dp, buffer, out_port);
575 make_openflow_reply(size_t openflow_len, uint8_t type,
576 const struct sender *sender, struct buffer **bufferp)
578 return make_openflow_xid(openflow_len, type, sender ? sender->xid : 0,
583 send_openflow_buffer(struct datapath *dp, struct buffer *buffer,
584 const struct sender *sender)
586 struct remote *remote = sender ? sender->remote : dp->controller;
587 struct rconn *rconn = remote->rconn;
590 update_openflow_length(buffer);
591 retval = (remote->n_txq < TXQ_LIMIT
592 ? rconn_send(rconn, buffer, &remote->n_txq)
595 VLOG_WARN("send to %s failed: %s",
596 rconn_get_name(rconn), strerror(retval));
597 buffer_delete(buffer);
602 /* Takes ownership of 'buffer' and transmits it to 'dp''s controller. If the
603 * packet can be saved in a buffer, then only the first max_len bytes of
604 * 'buffer' are sent; otherwise, all of 'buffer' is sent. 'reason' indicates
605 * why 'buffer' is being sent. 'max_len' sets the maximum number of bytes that
606 * the caller wants to be sent; a value of 0 indicates the entire packet should
609 dp_output_control(struct datapath *dp, struct buffer *buffer, int in_port,
610 size_t max_len, int reason)
612 struct ofp_packet_in *opi;
616 buffer_id = save_buffer(buffer);
617 total_len = buffer->size;
618 if (buffer_id != UINT32_MAX && buffer->size > max_len) {
619 buffer->size = max_len;
622 opi = buffer_push_uninit(buffer, offsetof(struct ofp_packet_in, data));
623 opi->header.version = OFP_VERSION;
624 opi->header.type = OFPT_PACKET_IN;
625 opi->header.length = htons(buffer->size);
626 opi->header.xid = htonl(0);
627 opi->buffer_id = htonl(buffer_id);
628 opi->total_len = htons(total_len);
629 opi->in_port = htons(in_port);
630 opi->reason = reason;
632 send_openflow_buffer(dp, buffer, NULL);
635 static void fill_port_desc(struct datapath *dp, struct sw_port *p,
636 struct ofp_phy_port *desc)
638 desc->port_no = htons(port_no(dp, p));
639 strncpy((char *) desc->name, netdev_get_name(p->netdev),
641 desc->name[sizeof desc->name - 1] = '\0';
642 memcpy(desc->hw_addr, netdev_get_etheraddr(p->netdev), ETH_ADDR_LEN);
643 desc->flags = htonl(p->flags);
644 desc->features = htonl(netdev_get_features(p->netdev));
645 desc->speed = htonl(netdev_get_speed(p->netdev));
649 dp_send_features_reply(struct datapath *dp, const struct sender *sender)
651 struct buffer *buffer;
652 struct ofp_switch_features *ofr;
655 ofr = make_openflow_reply(sizeof *ofr, OFPT_FEATURES_REPLY,
657 ofr->datapath_id = htonll(dp->id);
658 ofr->n_exact = htonl(2 * TABLE_HASH_MAX_FLOWS);
659 ofr->n_compression = 0; /* Not supported */
660 ofr->n_general = htonl(TABLE_LINEAR_MAX_FLOWS);
661 ofr->buffer_mb = htonl(UINT32_MAX);
662 ofr->n_buffers = htonl(N_PKT_BUFFERS);
663 ofr->capabilities = htonl(OFP_SUPPORTED_CAPABILITIES);
664 ofr->actions = htonl(OFP_SUPPORTED_ACTIONS);
665 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
666 struct ofp_phy_port *opp = buffer_put_uninit(buffer, sizeof *opp);
667 memset(opp, 0, sizeof *opp);
668 fill_port_desc(dp, p, opp);
670 send_openflow_buffer(dp, buffer, sender);
674 dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp)
676 int port_no = ntohs(opp->port_no);
677 if (port_no < OFPP_MAX) {
678 struct sw_port *p = &dp->ports[port_no];
680 /* Make sure the port id hasn't changed since this was sent */
681 if (!p || memcmp(opp->hw_addr, netdev_get_etheraddr(p->netdev),
682 ETH_ADDR_LEN) != 0) {
685 p->flags = htonl(opp->flags);
690 send_port_status(struct sw_port *p, uint8_t status)
692 struct buffer *buffer;
693 struct ofp_port_status *ops;
694 ops = make_openflow_xid(sizeof *ops, OFPT_PORT_STATUS, 0, &buffer);
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,
704 enum ofp_flow_expired_reason reason)
706 struct buffer *buffer;
707 struct ofp_flow_expired *ofe;
708 ofe = make_openflow_xid(sizeof *ofe, OFPT_FLOW_EXPIRED, 0, &buffer);
709 flow_fill_match(&ofe->match, &flow->key);
711 ofe->priority = htons(flow->priority);
712 ofe->reason = reason;
713 memset(ofe->pad, 0, sizeof ofe->pad);
715 ofe->duration = htonl(time_now() - flow->created);
716 memset(ofe->pad2, 0, sizeof ofe->pad2);
717 ofe->packet_count = htonll(flow->packet_count);
718 ofe->byte_count = htonll(flow->byte_count);
719 send_openflow_buffer(dp, buffer, NULL);
723 dp_send_error_msg(struct datapath *dp, const struct sender *sender,
724 uint16_t type, uint16_t code, const uint8_t *data, size_t len)
726 struct buffer *buffer;
727 struct ofp_error_msg *oem;
728 oem = make_openflow_reply(sizeof(*oem)+len, OFPT_ERROR_MSG,
730 oem->type = htons(type);
731 oem->code = htons(code);
732 memcpy(oem->data, data, len);
733 send_openflow_buffer(dp, buffer, sender);
737 fill_flow_stats(struct buffer *buffer, struct sw_flow *flow,
738 int table_idx, time_t now)
740 struct ofp_flow_stats *ofs;
741 int length = sizeof *ofs + sizeof *ofs->actions * flow->n_actions;
742 ofs = buffer_put_uninit(buffer, length);
743 ofs->length = htons(length);
744 ofs->table_id = table_idx;
746 ofs->match.wildcards = htons(flow->key.wildcards);
747 ofs->match.in_port = flow->key.flow.in_port;
748 memcpy(ofs->match.dl_src, flow->key.flow.dl_src, ETH_ADDR_LEN);
749 memcpy(ofs->match.dl_dst, flow->key.flow.dl_dst, ETH_ADDR_LEN);
750 ofs->match.dl_vlan = flow->key.flow.dl_vlan;
751 ofs->match.dl_type = flow->key.flow.dl_type;
752 ofs->match.nw_src = flow->key.flow.nw_src;
753 ofs->match.nw_dst = flow->key.flow.nw_dst;
754 ofs->match.nw_proto = flow->key.flow.nw_proto;
755 memset(ofs->match.pad, 0, sizeof ofs->match.pad);
756 ofs->match.tp_src = flow->key.flow.tp_src;
757 ofs->match.tp_dst = flow->key.flow.tp_dst;
758 ofs->duration = htonl(now - flow->created);
759 ofs->priority = htons(flow->priority);
760 ofs->idle_timeout = htons(flow->idle_timeout);
761 ofs->hard_timeout = htons(flow->hard_timeout);
762 memset(ofs->pad2, 0, sizeof ofs->pad2);
763 ofs->packet_count = htonll(flow->packet_count);
764 ofs->byte_count = htonll(flow->byte_count);
765 memcpy(ofs->actions, flow->actions,
766 sizeof *ofs->actions * flow->n_actions);
770 /* 'buffer' was received on 'in_port', a physical switch port between 0 and
771 * OFPP_MAX. Process it according to 'dp''s flow table. Returns 0 if
772 * successful, in which case 'buffer' is destroyed, or -ESRCH if there is no
773 * matching flow, in which case 'buffer' still belongs to the caller. */
774 int run_flow_through_tables(struct datapath *dp, struct buffer *buffer,
777 struct sw_flow_key key;
778 struct sw_flow *flow;
781 if (flow_extract(buffer, in_port, &key.flow)
782 && (dp->flags & OFPC_FRAG_MASK) == OFPC_FRAG_DROP) {
784 buffer_delete(buffer);
788 flow = chain_lookup(dp->chain, &key);
790 flow_used(flow, buffer);
791 execute_actions(dp, buffer, in_port, &key,
792 flow->actions, flow->n_actions);
799 /* 'buffer' was received on 'in_port', a physical switch port between 0 and
800 * OFPP_MAX. Process it according to 'dp''s flow table, sending it up to the
801 * controller if no flow matches. Takes ownership of 'buffer'. */
802 void fwd_port_input(struct datapath *dp, struct buffer *buffer, int in_port)
804 if (run_flow_through_tables(dp, buffer, in_port)) {
805 dp_output_control(dp, buffer, in_port, dp->miss_send_len,
811 do_output(struct datapath *dp, struct buffer *buffer, int in_port,
812 size_t max_len, int out_port)
814 if (out_port != OFPP_CONTROLLER) {
815 dp_output_port(dp, buffer, in_port, out_port);
817 dp_output_control(dp, buffer, in_port, max_len, OFPR_ACTION);
822 execute_actions(struct datapath *dp, struct buffer *buffer,
823 int in_port, const struct sw_flow_key *key,
824 const struct ofp_action *actions, int n_actions)
826 /* Every output action needs a separate clone of 'buffer', but the common
827 * case is just a single output action, so that doing a clone and then
828 * freeing the original buffer is wasteful. So the following code is
829 * slightly obscure just to avoid that. */
831 size_t max_len=0; /* Initialze to make compiler happy */
836 eth_proto = ntohs(key->flow.dl_type);
838 for (i = 0; i < n_actions; i++) {
839 const struct ofp_action *a = &actions[i];
840 struct eth_header *eh = buffer->l2;
842 if (prev_port != -1) {
843 do_output(dp, buffer_clone(buffer), in_port, max_len, prev_port);
847 switch (ntohs(a->type)) {
849 prev_port = ntohs(a->arg.output.port);
850 max_len = ntohs(a->arg.output.max_len);
853 case OFPAT_SET_DL_VLAN:
854 modify_vlan(buffer, key, a);
857 case OFPAT_SET_DL_SRC:
858 memcpy(eh->eth_src, a->arg.dl_addr, sizeof eh->eth_src);
861 case OFPAT_SET_DL_DST:
862 memcpy(eh->eth_dst, a->arg.dl_addr, sizeof eh->eth_dst);
865 case OFPAT_SET_NW_SRC:
866 case OFPAT_SET_NW_DST:
867 modify_nh(buffer, eth_proto, key->flow.nw_proto, a);
870 case OFPAT_SET_TP_SRC:
871 case OFPAT_SET_TP_DST:
872 modify_th(buffer, eth_proto, key->flow.nw_proto, a);
880 do_output(dp, buffer, in_port, max_len, prev_port);
882 buffer_delete(buffer);
885 static void modify_nh(struct buffer *buffer, uint16_t eth_proto,
886 uint8_t nw_proto, const struct ofp_action *a)
888 if (eth_proto == ETH_TYPE_IP) {
889 struct ip_header *nh = buffer->l3;
890 uint32_t new, *field;
892 new = a->arg.nw_addr;
893 field = a->type == OFPAT_SET_NW_SRC ? &nh->ip_src : &nh->ip_dst;
894 if (nw_proto == IP_TYPE_TCP) {
895 struct tcp_header *th = buffer->l4;
896 th->tcp_csum = recalc_csum32(th->tcp_csum, *field, new);
897 } else if (nw_proto == IP_TYPE_UDP) {
898 struct udp_header *th = buffer->l4;
900 th->udp_csum = recalc_csum32(th->udp_csum, *field, new);
902 th->udp_csum = 0xffff;
906 nh->ip_csum = recalc_csum32(nh->ip_csum, *field, new);
911 static void modify_th(struct buffer *buffer, uint16_t eth_proto,
912 uint8_t nw_proto, const struct ofp_action *a)
914 if (eth_proto == ETH_TYPE_IP) {
915 uint16_t new, *field;
919 if (nw_proto == IP_TYPE_TCP) {
920 struct tcp_header *th = buffer->l4;
921 field = a->type == OFPAT_SET_TP_SRC ? &th->tcp_src : &th->tcp_dst;
922 th->tcp_csum = recalc_csum16(th->tcp_csum, *field, new);
924 } else if (nw_proto == IP_TYPE_UDP) {
925 struct udp_header *th = buffer->l4;
926 field = a->type == OFPAT_SET_TP_SRC ? &th->udp_src : &th->udp_dst;
927 th->udp_csum = recalc_csum16(th->udp_csum, *field, new);
934 modify_vlan(struct buffer *buffer,
935 const struct sw_flow_key *key, const struct ofp_action *a)
937 uint16_t new_id = a->arg.vlan_id;
938 struct vlan_eth_header *veh;
940 if (new_id != htons(OFP_VLAN_NONE)) {
941 if (key->flow.dl_vlan != htons(OFP_VLAN_NONE)) {
942 /* Modify vlan id, but maintain other TCI values */
944 veh->veth_tci &= ~htons(VLAN_VID);
945 veh->veth_tci |= new_id;
947 /* Insert new vlan id. */
948 struct eth_header *eh = buffer->l2;
949 struct vlan_eth_header tmp;
950 memcpy(tmp.veth_dst, eh->eth_dst, ETH_ADDR_LEN);
951 memcpy(tmp.veth_src, eh->eth_src, ETH_ADDR_LEN);
952 tmp.veth_type = htons(ETH_TYPE_VLAN);
953 tmp.veth_tci = new_id;
954 tmp.veth_next_type = eh->eth_type;
956 veh = buffer_push_uninit(buffer, VLAN_HEADER_LEN);
957 memcpy(veh, &tmp, sizeof tmp);
958 buffer->l2 -= VLAN_HEADER_LEN;
961 /* Remove an existing vlan header if it exists */
963 if (veh->veth_type == htons(ETH_TYPE_VLAN)) {
964 struct eth_header tmp;
966 memcpy(tmp.eth_dst, veh->veth_dst, ETH_ADDR_LEN);
967 memcpy(tmp.eth_src, veh->veth_src, ETH_ADDR_LEN);
968 tmp.eth_type = veh->veth_next_type;
970 buffer->size -= VLAN_HEADER_LEN;
971 buffer->data += VLAN_HEADER_LEN;
972 buffer->l2 += VLAN_HEADER_LEN;
973 memcpy(buffer->data, &tmp, sizeof tmp);
979 recv_features_request(struct datapath *dp, const struct sender *sender,
982 dp_send_features_reply(dp, sender);
987 recv_get_config_request(struct datapath *dp, const struct sender *sender,
990 struct buffer *buffer;
991 struct ofp_switch_config *osc;
993 osc = make_openflow_reply(sizeof *osc, OFPT_GET_CONFIG_REPLY,
996 osc->flags = htons(dp->flags);
997 osc->miss_send_len = htons(dp->miss_send_len);
999 return send_openflow_buffer(dp, buffer, sender);
1003 recv_set_config(struct datapath *dp, const struct sender *sender UNUSED,
1006 const struct ofp_switch_config *osc = msg;
1009 flags = ntohs(osc->flags) & (OFPC_SEND_FLOW_EXP | OFPC_FRAG_MASK);
1010 if ((flags & OFPC_FRAG_MASK) != OFPC_FRAG_NORMAL
1011 && (flags & OFPC_FRAG_MASK) != OFPC_FRAG_DROP) {
1012 flags = (flags & ~OFPC_FRAG_MASK) | OFPC_FRAG_DROP;
1015 dp->miss_send_len = ntohs(osc->miss_send_len);
1020 recv_packet_out(struct datapath *dp, const struct sender *sender UNUSED,
1023 const struct ofp_packet_out *opo = msg;
1024 struct sw_flow_key key;
1025 struct buffer *buffer;
1026 int n_actions = ntohs(opo->n_actions);
1027 int act_len = n_actions * sizeof opo->actions[0];
1029 if (act_len > (ntohs(opo->header.length) - sizeof *opo)) {
1030 VLOG_DBG("message too short for number of actions");
1034 if (ntohl(opo->buffer_id) == (uint32_t) -1) {
1035 /* FIXME: can we avoid copying data here? */
1036 int data_len = ntohs(opo->header.length) - sizeof *opo - act_len;
1037 buffer = buffer_new(data_len);
1038 buffer_put(buffer, &opo->actions[n_actions], data_len);
1040 buffer = retrieve_buffer(ntohl(opo->buffer_id));
1046 flow_extract(buffer, ntohs(opo->in_port), &key.flow);
1047 execute_actions(dp, buffer, ntohs(opo->in_port),
1048 &key, opo->actions, n_actions);
1054 recv_port_mod(struct datapath *dp, const struct sender *sender UNUSED,
1057 const struct ofp_port_mod *opm = msg;
1059 dp_update_port_flags(dp, &opm->desc);
1065 add_flow(struct datapath *dp, const struct ofp_flow_mod *ofm)
1067 int error = -ENOMEM;
1070 struct sw_flow *flow;
1073 /* To prevent loops, make sure there's no action to send to the
1074 * OFP_TABLE virtual port.
1076 n_actions = (ntohs(ofm->header.length) - sizeof *ofm)
1077 / sizeof *ofm->actions;
1078 for (i=0; i<n_actions; i++) {
1079 const struct ofp_action *a = &ofm->actions[i];
1081 if (a->type == htons(OFPAT_OUTPUT)
1082 && (a->arg.output.port == htons(OFPP_TABLE)
1083 || a->arg.output.port == htons(OFPP_NONE)
1084 || a->arg.output.port == ofm->match.in_port)) {
1085 /* xxx Send fancy new error message? */
1090 /* Allocate memory. */
1091 flow = flow_alloc(n_actions);
1095 /* Fill out flow. */
1096 flow_extract_match(&flow->key, &ofm->match);
1097 flow->priority = flow->key.wildcards ? ntohs(ofm->priority) : -1;
1098 flow->idle_timeout = ntohs(ofm->idle_timeout);
1099 flow->hard_timeout = ntohs(ofm->hard_timeout);
1100 flow->used = flow->created = time_now();
1101 flow->n_actions = n_actions;
1102 flow->byte_count = 0;
1103 flow->packet_count = 0;
1104 memcpy(flow->actions, ofm->actions, n_actions * sizeof *flow->actions);
1107 error = chain_insert(dp->chain, flow);
1109 goto error_free_flow;
1112 if (ntohl(ofm->buffer_id) != UINT32_MAX) {
1113 struct buffer *buffer = retrieve_buffer(ntohl(ofm->buffer_id));
1115 struct sw_flow_key key;
1116 uint16_t in_port = ntohs(ofm->match.in_port);
1117 flow_used(flow, buffer);
1118 flow_extract(buffer, in_port, &key.flow);
1119 execute_actions(dp, buffer, in_port, &key, ofm->actions, n_actions);
1129 if (ntohl(ofm->buffer_id) != (uint32_t) -1)
1130 discard_buffer(ntohl(ofm->buffer_id));
1135 recv_flow(struct datapath *dp, const struct sender *sender UNUSED,
1138 const struct ofp_flow_mod *ofm = msg;
1139 uint16_t command = ntohs(ofm->command);
1141 if (command == OFPFC_ADD) {
1142 return add_flow(dp, ofm);
1143 } else if (command == OFPFC_DELETE) {
1144 struct sw_flow_key key;
1145 flow_extract_match(&key, &ofm->match);
1146 return chain_delete(dp->chain, &key, 0, 0) ? 0 : -ESRCH;
1147 } else if (command == OFPFC_DELETE_STRICT) {
1148 struct sw_flow_key key;
1150 flow_extract_match(&key, &ofm->match);
1151 priority = key.wildcards ? ntohs(ofm->priority) : -1;
1152 return chain_delete(dp->chain, &key, priority, 1) ? 0 : -ESRCH;
1158 struct flow_stats_state {
1160 struct sw_table_position position;
1161 struct ofp_flow_stats_request rq;
1164 struct buffer *buffer;
1167 #define MAX_FLOW_STATS_BYTES 4096
1169 static int flow_stats_init(struct datapath *dp, const void *body, int body_len,
1172 const struct ofp_flow_stats_request *fsr = body;
1173 struct flow_stats_state *s = xmalloc(sizeof *s);
1174 s->table_idx = fsr->table_id == 0xff ? 0 : fsr->table_id;
1175 memset(&s->position, 0, sizeof s->position);
1181 static int flow_stats_dump_callback(struct sw_flow *flow, void *private)
1183 struct flow_stats_state *s = private;
1184 fill_flow_stats(s->buffer, flow, s->table_idx, s->now);
1185 return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1188 static int flow_stats_dump(struct datapath *dp, void *state,
1189 struct buffer *buffer)
1191 struct flow_stats_state *s = state;
1192 struct sw_flow_key match_key;
1194 flow_extract_match(&match_key, &s->rq.match);
1196 s->now = time_now();
1197 while (s->table_idx < dp->chain->n_tables
1198 && (s->rq.table_id == 0xff || s->rq.table_id == s->table_idx))
1200 struct sw_table *table = dp->chain->tables[s->table_idx];
1202 if (table->iterate(table, &match_key, &s->position,
1203 flow_stats_dump_callback, s))
1207 memset(&s->position, 0, sizeof s->position);
1209 return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1212 static void flow_stats_done(void *state)
1217 struct aggregate_stats_state {
1218 struct ofp_aggregate_stats_request rq;
1221 static int aggregate_stats_init(struct datapath *dp,
1222 const void *body, int body_len,
1225 const struct ofp_aggregate_stats_request *rq = body;
1226 struct aggregate_stats_state *s = xmalloc(sizeof *s);
1232 static int aggregate_stats_dump_callback(struct sw_flow *flow, void *private)
1234 struct ofp_aggregate_stats_reply *rpy = private;
1235 rpy->packet_count += flow->packet_count;
1236 rpy->byte_count += flow->byte_count;
1241 static int aggregate_stats_dump(struct datapath *dp, void *state,
1242 struct buffer *buffer)
1244 struct aggregate_stats_state *s = state;
1245 struct ofp_aggregate_stats_request *rq = &s->rq;
1246 struct ofp_aggregate_stats_reply *rpy;
1247 struct sw_table_position position;
1248 struct sw_flow_key match_key;
1251 rpy = buffer_put_uninit(buffer, sizeof *rpy);
1252 memset(rpy, 0, sizeof *rpy);
1254 flow_extract_match(&match_key, &rq->match);
1255 table_idx = rq->table_id == 0xff ? 0 : rq->table_id;
1256 memset(&position, 0, sizeof position);
1257 while (table_idx < dp->chain->n_tables
1258 && (rq->table_id == 0xff || rq->table_id == table_idx))
1260 struct sw_table *table = dp->chain->tables[table_idx];
1263 error = table->iterate(table, &match_key, &position,
1264 aggregate_stats_dump_callback, rpy);
1269 memset(&position, 0, sizeof position);
1272 rpy->packet_count = htonll(rpy->packet_count);
1273 rpy->byte_count = htonll(rpy->byte_count);
1274 rpy->flow_count = htonl(rpy->flow_count);
1278 static void aggregate_stats_done(void *state)
1283 static int table_stats_dump(struct datapath *dp, void *state,
1284 struct buffer *buffer)
1287 for (i = 0; i < dp->chain->n_tables; i++) {
1288 struct ofp_table_stats *ots = buffer_put_uninit(buffer, sizeof *ots);
1289 struct sw_table_stats stats;
1290 dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
1291 strncpy(ots->name, stats.name, sizeof ots->name);
1293 memset(ots->pad, 0, sizeof ots->pad);
1294 ots->max_entries = htonl(stats.max_flows);
1295 ots->active_count = htonl(stats.n_flows);
1296 ots->matched_count = htonll(stats.n_matched);
1301 struct port_stats_state {
1305 static int port_stats_init(struct datapath *dp, const void *body, int body_len,
1308 struct port_stats_state *s = xmalloc(sizeof *s);
1314 static int port_stats_dump(struct datapath *dp, void *state,
1315 struct buffer *buffer)
1317 struct port_stats_state *s = state;
1320 for (i = s->port; i < OFPP_MAX; i++) {
1321 struct sw_port *p = &dp->ports[i];
1322 struct ofp_port_stats *ops;
1326 ops = buffer_put_uninit(buffer, sizeof *ops);
1327 ops->port_no = htons(port_no(dp, p));
1328 memset(ops->pad, 0, sizeof ops->pad);
1329 ops->rx_packets = htonll(p->rx_packets);
1330 ops->tx_packets = htonll(p->tx_packets);
1331 ops->rx_bytes = htonll(p->rx_bytes);
1332 ops->tx_bytes = htonll(p->tx_bytes);
1333 ops->rx_dropped = htonll(-1);
1334 ops->tx_dropped = htonll(p->tx_dropped);
1335 ops->rx_errors = htonll(-1);
1336 ops->tx_errors = htonll(-1);
1337 ops->rx_frame_err = htonll(-1);
1338 ops->rx_over_err = htonll(-1);
1339 ops->rx_crc_err = htonll(-1);
1340 ops->collisions = htonll(-1);
1347 static void port_stats_done(void *state)
1353 /* Minimum and maximum acceptable number of bytes in body member of
1354 * struct ofp_stats_request. */
1355 size_t min_body, max_body;
1357 /* Prepares to dump some kind of statistics on 'dp'. 'body' and
1358 * 'body_len' are the 'body' member of the struct ofp_stats_request.
1359 * Returns zero if successful, otherwise a negative error code.
1360 * May initialize '*state' to state information. May be null if no
1361 * initialization is required.*/
1362 int (*init)(struct datapath *dp, const void *body, int body_len,
1365 /* Appends statistics for 'dp' to 'buffer', which initially contains a
1366 * struct ofp_stats_reply. On success, it should return 1 if it should be
1367 * called again later with another buffer, 0 if it is done, or a negative
1368 * errno value on failure. */
1369 int (*dump)(struct datapath *dp, void *state, struct buffer *buffer);
1371 /* Cleans any state created by the init or dump functions. May be null
1372 * if no cleanup is required. */
1373 void (*done)(void *state);
1376 static const struct stats_type stats[] = {
1378 sizeof(struct ofp_flow_stats_request),
1379 sizeof(struct ofp_flow_stats_request),
1384 [OFPST_AGGREGATE] = {
1385 sizeof(struct ofp_aggregate_stats_request),
1386 sizeof(struct ofp_aggregate_stats_request),
1387 aggregate_stats_init,
1388 aggregate_stats_dump,
1389 aggregate_stats_done
1407 struct stats_dump_cb {
1409 struct ofp_stats_request *rq;
1410 struct sender sender;
1411 const struct stats_type *s;
1416 stats_dump(struct datapath *dp, void *cb_)
1418 struct stats_dump_cb *cb = cb_;
1419 struct ofp_stats_reply *osr;
1420 struct buffer *buffer;
1427 osr = make_openflow_reply(sizeof *osr, OFPT_STATS_REPLY, &cb->sender,
1429 osr->type = htons(cb->s - stats);
1432 err = cb->s->dump(dp, cb->state, buffer);
1438 /* Buffer might have been reallocated, so find our data again. */
1439 osr = buffer_at_assert(buffer, 0, sizeof *osr);
1440 osr->flags = ntohs(OFPSF_REPLY_MORE);
1442 err2 = send_openflow_buffer(dp, buffer, &cb->sender);
1452 stats_done(void *cb_)
1454 struct stats_dump_cb *cb = cb_;
1457 cb->s->done(cb->state);
1464 recv_stats_request(struct datapath *dp, const struct sender *sender,
1467 const struct ofp_stats_request *rq = oh;
1468 size_t rq_len = ntohs(rq->header.length);
1469 struct stats_dump_cb *cb;
1473 type = ntohs(rq->type);
1474 if (type >= ARRAY_SIZE(stats) || !stats[type].dump) {
1475 VLOG_WARN("received stats request of unknown type %d", type);
1479 cb = xmalloc(sizeof *cb);
1481 cb->rq = xmemdup(rq, rq_len);
1482 cb->sender = *sender;
1483 cb->s = &stats[type];
1486 body_len = rq_len - offsetof(struct ofp_stats_request, body);
1487 if (body_len < cb->s->min_body || body_len > cb->s->max_body) {
1488 VLOG_WARN("stats request type %d with bad body length %d",
1495 err = cb->s->init(dp, rq->body, body_len, &cb->state);
1497 VLOG_WARN("failed initialization of stats request type %d: %s",
1498 type, strerror(-err));
1503 remote_start_dump(sender->remote, stats_dump, stats_done, cb);
1513 recv_echo_request(struct datapath *dp, const struct sender *sender,
1516 return send_openflow_buffer(dp, make_echo_reply(oh), sender);
1520 recv_echo_reply(struct datapath *dp UNUSED, const struct sender *sender UNUSED,
1521 const void *oh UNUSED)
1526 /* 'msg', which is 'length' bytes long, was received from the control path.
1527 * Apply it to 'chain'. */
1529 fwd_control_input(struct datapath *dp, const struct sender *sender,
1530 const void *msg, size_t length)
1532 struct openflow_packet {
1534 int (*handler)(struct datapath *, const struct sender *, const void *);
1537 static const struct openflow_packet packets[] = {
1538 [OFPT_FEATURES_REQUEST] = {
1539 sizeof (struct ofp_header),
1540 recv_features_request,
1542 [OFPT_GET_CONFIG_REQUEST] = {
1543 sizeof (struct ofp_header),
1544 recv_get_config_request,
1546 [OFPT_SET_CONFIG] = {
1547 sizeof (struct ofp_switch_config),
1550 [OFPT_PACKET_OUT] = {
1551 sizeof (struct ofp_packet_out),
1555 sizeof (struct ofp_flow_mod),
1559 sizeof (struct ofp_port_mod),
1562 [OFPT_STATS_REQUEST] = {
1563 sizeof (struct ofp_stats_request),
1566 [OFPT_ECHO_REQUEST] = {
1567 sizeof (struct ofp_header),
1570 [OFPT_ECHO_REPLY] = {
1571 sizeof (struct ofp_header),
1576 const struct openflow_packet *pkt;
1577 struct ofp_header *oh;
1579 oh = (struct ofp_header *) msg;
1580 assert(oh->version == OFP_VERSION);
1581 if (oh->type >= ARRAY_SIZE(packets) || ntohs(oh->length) > length)
1584 pkt = &packets[oh->type];
1587 if (length < pkt->min_size)
1590 return pkt->handler(dp, sender, msg);
1593 /* Packet buffering. */
1595 #define OVERWRITE_SECS 1
1597 struct packet_buffer {
1598 struct buffer *buffer;
1603 static struct packet_buffer buffers[N_PKT_BUFFERS];
1604 static unsigned int buffer_idx;
1606 uint32_t save_buffer(struct buffer *buffer)
1608 struct packet_buffer *p;
1611 buffer_idx = (buffer_idx + 1) & PKT_BUFFER_MASK;
1612 p = &buffers[buffer_idx];
1614 /* Don't buffer packet if existing entry is less than
1615 * OVERWRITE_SECS old. */
1616 if (time_now() < p->timeout) { /* FIXME */
1619 buffer_delete(p->buffer);
1622 /* Don't use maximum cookie value since the all-bits-1 id is
1624 if (++p->cookie >= (1u << PKT_COOKIE_BITS) - 1)
1626 p->buffer = buffer_clone(buffer); /* FIXME */
1627 p->timeout = time_now() + OVERWRITE_SECS; /* FIXME */
1628 id = buffer_idx | (p->cookie << PKT_BUFFER_BITS);
1633 static struct buffer *retrieve_buffer(uint32_t id)
1635 struct buffer *buffer = NULL;
1636 struct packet_buffer *p;
1638 p = &buffers[id & PKT_BUFFER_MASK];
1639 if (p->cookie == id >> PKT_BUFFER_BITS) {
1643 printf("cookie mismatch: %x != %x\n",
1644 id >> PKT_BUFFER_BITS, p->cookie);
1650 static void discard_buffer(uint32_t id)
1652 struct packet_buffer *p;
1654 p = &buffers[id & PKT_BUFFER_MASK];
1655 if (p->cookie == id >> PKT_BUFFER_BITS) {
1656 buffer_delete(p->buffer);