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 "openflow/openflow.h"
49 #include "poll-loop.h"
52 #include "switch-flow.h"
59 #define THIS_MODULE VLM_datapath
65 extern char serial_num;
67 /* Capabilities supported by this implementation. */
68 #define OFP_SUPPORTED_CAPABILITIES ( OFPC_FLOW_STATS \
73 /* Actions supported by this implementation. */
74 #define OFP_SUPPORTED_ACTIONS ( (1 << OFPAT_OUTPUT) \
75 | (1 << OFPAT_SET_VLAN_VID) \
76 | (1 << OFPAT_SET_VLAN_PCP) \
77 | (1 << OFPAT_STRIP_VLAN) \
78 | (1 << OFPAT_SET_DL_SRC) \
79 | (1 << OFPAT_SET_DL_DST) \
80 | (1 << OFPAT_SET_NW_SRC) \
81 | (1 << OFPAT_SET_NW_DST) \
82 | (1 << OFPAT_SET_TP_SRC) \
83 | (1 << OFPAT_SET_TP_DST) )
86 uint32_t config; /* Some subset of OFPPC_* flags. */
87 uint32_t state; /* Some subset of OFPPS_* flags. */
89 struct netdev *netdev;
90 struct list node; /* Element in datapath.ports. */
91 unsigned long long int rx_packets, tx_packets;
92 unsigned long long int rx_bytes, tx_bytes;
93 unsigned long long int tx_dropped;
96 /* The origin of a received OpenFlow message, to enable sending a reply. */
98 struct remote *remote; /* The device that sent the message. */
99 uint32_t xid; /* The OpenFlow transaction ID. */
102 /* A connection to a controller or a management device. */
106 #define TXQ_LIMIT 128 /* Max number of packets to queue for tx. */
107 int n_txq; /* Number of packets queued for tx on rconn. */
109 /* Support for reliable, multi-message replies to requests.
111 * If an incoming request needs to have a reliable reply that might
112 * require multiple messages, it can use remote_start_dump() to set up
113 * a callback that will be called as buffer space for replies. */
114 int (*cb_dump)(struct datapath *, void *aux);
115 void (*cb_done)(void *aux);
119 #define DP_MAX_PORTS 255
120 BUILD_ASSERT_DECL(DP_MAX_PORTS <= OFPP_MAX);
123 /* Remote connections. */
124 struct remote *controller; /* Connection to controller. */
125 struct list remotes; /* All connections (including controller). */
126 struct pvconn *listen_pvconn;
130 /* Unique identifier for this datapath */
133 struct sw_chain *chain; /* Forwarding rules. */
135 /* Configuration set from controller. */
137 uint16_t miss_send_len;
140 struct sw_port ports[DP_MAX_PORTS];
141 struct list port_list; /* List of ports, for flooding. */
144 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 60);
146 static struct remote *remote_create(struct datapath *, struct rconn *);
147 static void remote_run(struct datapath *, struct remote *);
148 static void remote_wait(struct remote *);
149 static void remote_destroy(struct remote *);
151 void dp_update_port_flags(struct datapath *dp, const struct ofp_port_mod *opm);
152 static void send_flow_expired(struct datapath *, struct sw_flow *,
153 enum ofp_flow_expired_reason);
154 static int update_port_status(struct sw_port *p);
155 static void send_port_status(struct sw_port *p, uint8_t status);
156 static void del_switch_port(struct sw_port *p);
158 /* Buffers are identified to userspace by a 31-bit opaque ID. We divide the ID
159 * into a buffer number (low bits) and a cookie (high bits). The buffer number
160 * is an index into an array of buffers. The cookie distinguishes between
161 * different packets that have occupied a single buffer. Thus, the more
162 * buffers we have, the lower-quality the cookie... */
163 #define PKT_BUFFER_BITS 8
164 #define N_PKT_BUFFERS (1 << PKT_BUFFER_BITS)
165 #define PKT_BUFFER_MASK (N_PKT_BUFFERS - 1)
167 #define PKT_COOKIE_BITS (32 - PKT_BUFFER_BITS)
169 int run_flow_through_tables(struct datapath *, struct ofpbuf *,
171 void fwd_port_input(struct datapath *, struct ofpbuf *, struct sw_port *);
172 int fwd_control_input(struct datapath *, const struct sender *,
173 const void *, size_t);
175 uint32_t save_buffer(struct ofpbuf *);
176 static struct ofpbuf *retrieve_buffer(uint32_t id);
177 static void discard_buffer(uint32_t id);
179 static int port_no(struct datapath *dp, struct sw_port *p)
181 assert(p >= dp->ports && p < &dp->ports[ARRAY_SIZE(dp->ports)]);
182 return p - dp->ports;
185 /* Generates and returns a random datapath id. */
187 gen_datapath_id(void)
189 uint8_t ea[ETH_ADDR_LEN];
191 return eth_addr_to_uint64(ea);
195 dp_new(struct datapath **dp_, uint64_t dpid, struct rconn *rconn)
199 dp = calloc(1, sizeof *dp);
204 dp->last_timeout = time_now();
205 list_init(&dp->remotes);
206 dp->controller = remote_create(dp, rconn);
207 dp->listen_pvconn = NULL;
208 dp->id = dpid <= UINT64_C(0xffffffffffff) ? dpid : gen_datapath_id();
209 dp->chain = chain_create();
211 VLOG_ERR("could not create chain");
216 list_init(&dp->port_list);
218 dp->miss_send_len = OFP_DEFAULT_MISS_SEND_LEN;
224 dp_add_port(struct datapath *dp, const char *name)
226 struct netdev *netdev;
232 error = netdev_open(name, NETDEV_ETH_TYPE_ANY, &netdev);
236 error = netdev_set_flags(netdev, NETDEV_UP | NETDEV_PROMISC, false);
238 VLOG_ERR("couldn't set promiscuous mode on %s device", name);
239 netdev_close(netdev);
242 if (netdev_get_in4(netdev, &in4)) {
243 VLOG_ERR("%s device has assigned IP address %s", name, inet_ntoa(in4));
245 if (netdev_get_in6(netdev, &in6)) {
246 char in6_name[INET6_ADDRSTRLEN + 1];
247 inet_ntop(AF_INET6, &in6, in6_name, sizeof in6_name);
248 VLOG_ERR("%s device has assigned IPv6 address %s", name, in6_name);
251 for (p = dp->ports; ; p++) {
252 if (p >= &dp->ports[ARRAY_SIZE(dp->ports)]) {
254 } else if (!p->netdev) {
259 memset(p, '\0', sizeof *p);
263 list_push_back(&dp->port_list, &p->node);
265 /* Notify the ctlpath that this port has been added */
266 send_port_status(p, OFPPR_ADD);
272 dp_add_listen_pvconn(struct datapath *dp, struct pvconn *listen_pvconn)
274 assert(!dp->listen_pvconn);
275 dp->listen_pvconn = listen_pvconn;
279 dp_run(struct datapath *dp)
281 time_t now = time_now();
282 struct sw_port *p, *pn;
283 struct remote *r, *rn;
284 struct ofpbuf *buffer = NULL;
286 if (now != dp->last_timeout) {
287 struct list deleted = LIST_INITIALIZER(&deleted);
288 struct sw_flow *f, *n;
290 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
291 if (update_port_status(p)) {
292 send_port_status(p, OFPPR_MODIFY);
296 chain_timeout(dp->chain, &deleted);
297 LIST_FOR_EACH_SAFE (f, n, struct sw_flow, node, &deleted) {
298 send_flow_expired(dp, f, f->reason);
299 list_remove(&f->node);
302 dp->last_timeout = now;
304 poll_timer_wait(1000);
306 LIST_FOR_EACH_SAFE (p, pn, struct sw_port, node, &dp->port_list) {
310 /* Allocate buffer with some headroom to add headers in forwarding
311 * to the controller or adding a vlan tag, plus an extra 2 bytes to
312 * allow IP headers to be aligned on a 4-byte boundary. */
313 const int headroom = 128 + 2;
314 const int hard_header = VLAN_ETH_HEADER_LEN;
315 const int mtu = netdev_get_mtu(p->netdev);
316 buffer = ofpbuf_new(headroom + hard_header + mtu);
317 buffer->data = (char*)buffer->data + headroom;
319 error = netdev_recv(p->netdev, buffer);
322 p->rx_bytes += buffer->size;
323 fwd_port_input(dp, buffer, p);
325 } else if (error != EAGAIN) {
326 VLOG_ERR_RL(&rl, "error receiving data from %s: %s",
327 netdev_get_name(p->netdev), strerror(error));
330 ofpbuf_delete(buffer);
332 /* Talk to remotes. */
333 LIST_FOR_EACH_SAFE (r, rn, struct remote, node, &dp->remotes) {
336 if (dp->listen_pvconn) {
338 struct vconn *new_vconn;
341 retval = pvconn_accept(dp->listen_pvconn, OFP_VERSION, &new_vconn);
343 if (retval != EAGAIN) {
344 VLOG_WARN_RL(&rl, "accept failed (%s)", strerror(retval));
348 remote_create(dp, rconn_new_from_vconn("passive", new_vconn));
354 remote_run(struct datapath *dp, struct remote *r)
360 /* Do some remote processing, but cap it at a reasonable amount so that
361 * other processing doesn't starve. */
362 for (i = 0; i < 50; i++) {
364 struct ofpbuf *buffer;
365 struct ofp_header *oh;
367 buffer = rconn_recv(r->rconn);
372 if (buffer->size >= sizeof *oh) {
373 struct sender sender;
377 sender.xid = oh->xid;
378 fwd_control_input(dp, &sender, buffer->data, buffer->size);
380 VLOG_WARN_RL(&rl, "received too-short OpenFlow message");
382 ofpbuf_delete(buffer);
384 if (r->n_txq < TXQ_LIMIT) {
385 int error = r->cb_dump(dp, r->cb_aux);
388 VLOG_WARN_RL(&rl, "dump callback error: %s",
391 r->cb_done(r->cb_aux);
400 if (!rconn_is_alive(r->rconn)) {
406 remote_wait(struct remote *r)
408 rconn_run_wait(r->rconn);
409 rconn_recv_wait(r->rconn);
413 remote_destroy(struct remote *r)
416 if (r->cb_dump && r->cb_done) {
417 r->cb_done(r->cb_aux);
419 list_remove(&r->node);
420 rconn_destroy(r->rconn);
425 static struct remote *
426 remote_create(struct datapath *dp, struct rconn *rconn)
428 struct remote *remote = xmalloc(sizeof *remote);
429 list_push_back(&dp->remotes, &remote->node);
430 remote->rconn = rconn;
431 remote->cb_dump = NULL;
436 /* Starts a callback-based, reliable, possibly multi-message reply to a
437 * request made by 'remote'.
439 * 'dump' designates a function that will be called when the 'remote' send
440 * queue has an empty slot. It should compose a message and send it on
441 * 'remote'. On success, it should return 1 if it should be called again when
442 * another send queue slot opens up, 0 if its transmissions are complete, or a
443 * negative errno value on failure.
445 * 'done' designates a function to clean up any resources allocated for the
446 * dump. It must handle being called before the dump is complete (which will
447 * happen if 'remote' is closed unexpectedly).
449 * 'aux' is passed to 'dump' and 'done'. */
451 remote_start_dump(struct remote *remote,
452 int (*dump)(struct datapath *, void *),
453 void (*done)(void *),
456 assert(!remote->cb_dump);
457 remote->cb_dump = dump;
458 remote->cb_done = done;
459 remote->cb_aux = aux;
463 dp_wait(struct datapath *dp)
468 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
469 netdev_recv_wait(p->netdev);
471 LIST_FOR_EACH (r, struct remote, node, &dp->remotes) {
474 if (dp->listen_pvconn) {
475 pvconn_wait(dp->listen_pvconn);
479 /* Delete 'p' from switch. */
481 del_switch_port(struct sw_port *p)
483 send_port_status(p, OFPPR_DELETE);
484 netdev_close(p->netdev);
486 list_remove(&p->node);
490 dp_destroy(struct datapath *dp)
492 struct sw_port *p, *n;
498 LIST_FOR_EACH_SAFE (p, n, struct sw_port, node, &dp->port_list) {
501 chain_destroy(dp->chain);
505 /* Send packets out all the ports except the originating one. If the
506 * "flood" argument is set, don't send out ports with flooding disabled.
509 output_all(struct datapath *dp, struct ofpbuf *buffer, int in_port, int flood)
515 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
516 if (port_no(dp, p) == in_port) {
519 if (flood && p->config & OFPPC_NO_FLOOD) {
522 if (prev_port != -1) {
523 dp_output_port(dp, ofpbuf_clone(buffer), in_port, prev_port,
526 prev_port = port_no(dp, p);
529 dp_output_port(dp, buffer, in_port, prev_port, false);
531 ofpbuf_delete(buffer);
537 output_packet(struct datapath *dp, struct ofpbuf *buffer, int out_port)
539 if (out_port >= 0 && out_port < DP_MAX_PORTS) {
540 struct sw_port *p = &dp->ports[out_port];
541 if (p->netdev != NULL && !(p->config & OFPPC_PORT_DOWN)) {
542 if (!netdev_send(p->netdev, buffer)) {
544 p->tx_bytes += buffer->size;
552 ofpbuf_delete(buffer);
553 VLOG_DBG_RL(&rl, "can't forward to bad port %d\n", out_port);
556 /* Takes ownership of 'buffer' and transmits it to 'out_port' on 'dp'.
559 dp_output_port(struct datapath *dp, struct ofpbuf *buffer,
560 int in_port, int out_port, bool ignore_no_fwd)
564 if (out_port == OFPP_FLOOD) {
565 output_all(dp, buffer, in_port, 1);
566 } else if (out_port == OFPP_ALL) {
567 output_all(dp, buffer, in_port, 0);
568 } else if (out_port == OFPP_CONTROLLER) {
569 dp_output_control(dp, buffer, in_port, 0, OFPR_ACTION);
570 } else if (out_port == OFPP_IN_PORT) {
571 output_packet(dp, buffer, in_port);
572 } else if (out_port == OFPP_TABLE) {
573 struct sw_port *p = in_port < DP_MAX_PORTS ? &dp->ports[in_port] : 0;
574 if (run_flow_through_tables(dp, buffer, p)) {
575 ofpbuf_delete(buffer);
578 if (in_port == out_port) {
579 VLOG_DBG_RL(&rl, "can't directly forward to input port");
582 output_packet(dp, buffer, out_port);
587 make_openflow_reply(size_t openflow_len, uint8_t type,
588 const struct sender *sender, struct ofpbuf **bufferp)
590 return make_openflow_xid(openflow_len, type, sender ? sender->xid : 0,
595 send_openflow_buffer(struct datapath *dp, struct ofpbuf *buffer,
596 const struct sender *sender)
598 struct remote *remote = sender ? sender->remote : dp->controller;
599 struct rconn *rconn = remote->rconn;
602 update_openflow_length(buffer);
603 retval = rconn_send_with_limit(rconn, buffer, &remote->n_txq, TXQ_LIMIT);
605 VLOG_WARN_RL(&rl, "send to %s failed: %s",
606 rconn_get_name(rconn), strerror(retval));
611 /* Takes ownership of 'buffer' and transmits it to 'dp''s controller. If the
612 * packet can be saved in a buffer, then only the first max_len bytes of
613 * 'buffer' are sent; otherwise, all of 'buffer' is sent. 'reason' indicates
614 * why 'buffer' is being sent. 'max_len' sets the maximum number of bytes that
615 * the caller wants to be sent; a value of 0 indicates the entire packet should
618 dp_output_control(struct datapath *dp, struct ofpbuf *buffer, int in_port,
619 size_t max_len, int reason)
621 struct ofp_packet_in *opi;
625 buffer_id = save_buffer(buffer);
626 total_len = buffer->size;
627 if (buffer_id != UINT32_MAX && max_len && buffer->size > max_len) {
628 buffer->size = max_len;
631 opi = ofpbuf_push_uninit(buffer, offsetof(struct ofp_packet_in, data));
632 opi->header.version = OFP_VERSION;
633 opi->header.type = OFPT_PACKET_IN;
634 opi->header.length = htons(buffer->size);
635 opi->header.xid = htonl(0);
636 opi->buffer_id = htonl(buffer_id);
637 opi->total_len = htons(total_len);
638 opi->in_port = htons(in_port);
639 opi->reason = reason;
641 send_openflow_buffer(dp, buffer, NULL);
644 static void fill_port_desc(struct datapath *dp, struct sw_port *p,
645 struct ofp_phy_port *desc)
647 desc->port_no = htons(port_no(dp, p));
648 strncpy((char *) desc->name, netdev_get_name(p->netdev),
650 desc->name[sizeof desc->name - 1] = '\0';
651 memcpy(desc->hw_addr, netdev_get_etheraddr(p->netdev), ETH_ADDR_LEN);
652 desc->config = htonl(p->config);
653 desc->state = htonl(p->state);
654 desc->curr = htonl(netdev_get_features(p->netdev, NETDEV_FEAT_CURRENT));
655 desc->supported = htonl(netdev_get_features(p->netdev,
656 NETDEV_FEAT_SUPPORTED));
657 desc->advertised = htonl(netdev_get_features(p->netdev,
658 NETDEV_FEAT_ADVERTISED));
659 desc->peer = htonl(netdev_get_features(p->netdev, NETDEV_FEAT_PEER));
663 dp_send_features_reply(struct datapath *dp, const struct sender *sender)
665 struct ofpbuf *buffer;
666 struct ofp_switch_features *ofr;
669 ofr = make_openflow_reply(sizeof *ofr, OFPT_FEATURES_REPLY,
671 ofr->datapath_id = htonll(dp->id);
672 ofr->n_tables = dp->chain->n_tables;
673 ofr->n_buffers = htonl(N_PKT_BUFFERS);
674 ofr->capabilities = htonl(OFP_SUPPORTED_CAPABILITIES);
675 ofr->actions = htonl(OFP_SUPPORTED_ACTIONS);
676 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
677 struct ofp_phy_port *opp = ofpbuf_put_zeros(buffer, sizeof *opp);
678 fill_port_desc(dp, p, opp);
680 send_openflow_buffer(dp, buffer, sender);
684 dp_update_port_flags(struct datapath *dp, const struct ofp_port_mod *opm)
686 int port_no = ntohs(opm->port_no);
687 if (port_no < DP_MAX_PORTS) {
688 struct sw_port *p = &dp->ports[port_no];
690 /* Make sure the port id hasn't changed since this was sent */
691 if (memcmp(opm->hw_addr, netdev_get_etheraddr(p->netdev),
692 ETH_ADDR_LEN) != 0) {
698 uint32_t config_mask = ntohl(opm->mask);
699 p->config &= ~config_mask;
700 p->config |= ntohl(opm->config) & config_mask;
703 if (opm->mask & htonl(OFPPC_PORT_DOWN)) {
704 if ((opm->config & htonl(OFPPC_PORT_DOWN))
705 && (p->config & OFPPC_PORT_DOWN) == 0) {
706 p->config |= OFPPC_PORT_DOWN;
707 netdev_turn_flags_off(p->netdev, NETDEV_UP, true);
708 } else if ((opm->config & htonl(OFPPC_PORT_DOWN)) == 0
709 && (p->config & OFPPC_PORT_DOWN)) {
710 p->config &= ~OFPPC_PORT_DOWN;
711 netdev_turn_flags_on(p->netdev, NETDEV_UP, true);
717 /* Update the port status field of the bridge port. A non-zero return
718 * value indicates some field has changed.
720 * NB: Callers of this function may hold the RCU read lock, so any
721 * additional checks must not sleep.
724 update_port_status(struct sw_port *p)
727 enum netdev_flags flags;
728 uint32_t orig_config = p->config;
729 uint32_t orig_state = p->state;
731 if (netdev_get_flags(p->netdev, &flags) < 0) {
732 VLOG_WARN_RL(&rl, "could not get netdev flags for %s",
733 netdev_get_name(p->netdev));
736 if (flags & NETDEV_UP) {
737 p->config &= ~OFPPC_PORT_DOWN;
739 p->config |= OFPPC_PORT_DOWN;
743 /* Not all cards support this getting link status, so don't warn on
745 retval = netdev_get_link_status(p->netdev);
747 p->state &= ~OFPPS_LINK_DOWN;
748 } else if (retval == 0) {
749 p->state |= OFPPS_LINK_DOWN;
752 return ((orig_config != p->config) || (orig_state != p->state));
756 send_port_status(struct sw_port *p, uint8_t status)
758 struct ofpbuf *buffer;
759 struct ofp_port_status *ops;
760 ops = make_openflow_xid(sizeof *ops, OFPT_PORT_STATUS, 0, &buffer);
761 ops->reason = status;
762 memset(ops->pad, 0, sizeof ops->pad);
763 fill_port_desc(p->dp, p, &ops->desc);
765 send_openflow_buffer(p->dp, buffer, NULL);
769 send_flow_expired(struct datapath *dp, struct sw_flow *flow,
770 enum ofp_flow_expired_reason reason)
772 struct ofpbuf *buffer;
773 struct ofp_flow_expired *ofe;
774 ofe = make_openflow_xid(sizeof *ofe, OFPT_FLOW_EXPIRED, 0, &buffer);
775 flow_fill_match(&ofe->match, &flow->key);
777 ofe->priority = htons(flow->priority);
778 ofe->reason = reason;
779 memset(ofe->pad, 0, sizeof ofe->pad);
781 ofe->duration = htonl(time_now() - flow->created);
782 memset(ofe->pad2, 0, sizeof ofe->pad2);
783 ofe->packet_count = htonll(flow->packet_count);
784 ofe->byte_count = htonll(flow->byte_count);
785 send_openflow_buffer(dp, buffer, NULL);
789 dp_send_error_msg(struct datapath *dp, const struct sender *sender,
790 uint16_t type, uint16_t code, const void *data, size_t len)
792 struct ofpbuf *buffer;
793 struct ofp_error_msg *oem;
794 oem = make_openflow_reply(sizeof(*oem)+len, OFPT_ERROR, sender, &buffer);
795 oem->type = htons(type);
796 oem->code = htons(code);
797 memcpy(oem->data, data, len);
798 send_openflow_buffer(dp, buffer, sender);
802 fill_flow_stats(struct ofpbuf *buffer, struct sw_flow *flow,
803 int table_idx, time_t now)
805 struct ofp_flow_stats *ofs;
806 int length = sizeof *ofs + flow->sf_acts->actions_len;
807 ofs = ofpbuf_put_zeros(buffer, length);
808 ofs->length = htons(length);
809 ofs->table_id = table_idx;
810 ofs->match.wildcards = htonl(flow->key.wildcards);
811 ofs->match.in_port = flow->key.flow.in_port;
812 memcpy(ofs->match.dl_src, flow->key.flow.dl_src, ETH_ADDR_LEN);
813 memcpy(ofs->match.dl_dst, flow->key.flow.dl_dst, ETH_ADDR_LEN);
814 ofs->match.dl_vlan = flow->key.flow.dl_vlan;
815 ofs->match.dl_type = flow->key.flow.dl_type;
816 ofs->match.nw_src = flow->key.flow.nw_src;
817 ofs->match.nw_dst = flow->key.flow.nw_dst;
818 ofs->match.nw_proto = flow->key.flow.nw_proto;
819 ofs->match.tp_src = flow->key.flow.tp_src;
820 ofs->match.tp_dst = flow->key.flow.tp_dst;
821 ofs->duration = htonl(now - flow->created);
822 ofs->priority = htons(flow->priority);
823 ofs->idle_timeout = htons(flow->idle_timeout);
824 ofs->hard_timeout = htons(flow->hard_timeout);
825 ofs->packet_count = htonll(flow->packet_count);
826 ofs->byte_count = htonll(flow->byte_count);
827 memcpy(ofs->actions, flow->sf_acts->actions, flow->sf_acts->actions_len);
831 /* 'buffer' was received on 'p', which may be a a physical switch port or a
832 * null pointer. Process it according to 'dp''s flow table. Returns 0 if
833 * successful, in which case 'buffer' is destroyed, or -ESRCH if there is no
834 * matching flow, in which case 'buffer' still belongs to the caller. */
835 int run_flow_through_tables(struct datapath *dp, struct ofpbuf *buffer,
838 struct sw_flow_key key;
839 struct sw_flow *flow;
842 if (flow_extract(buffer, p ? port_no(dp, p) : OFPP_NONE, &key.flow)
843 && (dp->flags & OFPC_FRAG_MASK) == OFPC_FRAG_DROP) {
845 ofpbuf_delete(buffer);
848 if (p && p->config & (OFPPC_NO_RECV | OFPPC_NO_RECV_STP)
849 && p->config & (!eth_addr_equals(key.flow.dl_dst, stp_eth_addr)
850 ? OFPPC_NO_RECV : OFPPC_NO_RECV_STP)) {
851 ofpbuf_delete(buffer);
855 flow = chain_lookup(dp->chain, &key);
857 flow_used(flow, buffer);
858 execute_actions(dp, buffer, &key, flow->sf_acts->actions,
859 flow->sf_acts->actions_len, false);
866 /* 'buffer' was received on 'p', which may be a a physical switch port or a
867 * null pointer. Process it according to 'dp''s flow table, sending it up to
868 * the controller if no flow matches. Takes ownership of 'buffer'. */
869 void fwd_port_input(struct datapath *dp, struct ofpbuf *buffer,
872 if (run_flow_through_tables(dp, buffer, p)) {
873 dp_output_control(dp, buffer, port_no(dp, p),
874 dp->miss_send_len, OFPR_NO_MATCH);
879 recv_features_request(struct datapath *dp, const struct sender *sender,
882 dp_send_features_reply(dp, sender);
887 recv_get_config_request(struct datapath *dp, const struct sender *sender,
890 struct ofpbuf *buffer;
891 struct ofp_switch_config *osc;
893 osc = make_openflow_reply(sizeof *osc, OFPT_GET_CONFIG_REPLY,
896 osc->flags = htons(dp->flags);
897 osc->miss_send_len = htons(dp->miss_send_len);
899 return send_openflow_buffer(dp, buffer, sender);
903 recv_set_config(struct datapath *dp, const struct sender *sender UNUSED,
906 const struct ofp_switch_config *osc = msg;
909 flags = ntohs(osc->flags) & (OFPC_SEND_FLOW_EXP | OFPC_FRAG_MASK);
910 if ((flags & OFPC_FRAG_MASK) != OFPC_FRAG_NORMAL
911 && (flags & OFPC_FRAG_MASK) != OFPC_FRAG_DROP) {
912 flags = (flags & ~OFPC_FRAG_MASK) | OFPC_FRAG_DROP;
915 dp->miss_send_len = ntohs(osc->miss_send_len);
920 recv_packet_out(struct datapath *dp, const struct sender *sender,
923 const struct ofp_packet_out *opo = msg;
924 struct sw_flow_key key;
926 struct ofpbuf *buffer;
927 size_t actions_len = ntohs(opo->actions_len);
929 if (actions_len > (ntohs(opo->header.length) - sizeof *opo)) {
930 VLOG_DBG_RL(&rl, "message too short for number of actions");
934 if (ntohl(opo->buffer_id) == (uint32_t) -1) {
935 /* FIXME: can we avoid copying data here? */
936 int data_len = ntohs(opo->header.length) - sizeof *opo - actions_len;
937 buffer = ofpbuf_new(data_len);
938 ofpbuf_put(buffer, (uint8_t *)opo->actions + actions_len, data_len);
940 buffer = retrieve_buffer(ntohl(opo->buffer_id));
946 flow_extract(buffer, ntohs(opo->in_port), &key.flow);
948 v_code = validate_actions(dp, &key, opo->actions, actions_len);
949 if (v_code != ACT_VALIDATION_OK) {
950 dp_send_error_msg(dp, sender, OFPET_BAD_ACTION, v_code,
951 msg, ntohs(opo->header.length));
955 execute_actions(dp, buffer, &key, opo->actions, actions_len, true);
960 ofpbuf_delete(buffer);
965 recv_port_mod(struct datapath *dp, const struct sender *sender UNUSED,
968 const struct ofp_port_mod *opm = msg;
970 dp_update_port_flags(dp, opm);
976 add_flow(struct datapath *dp, const struct sender *sender,
977 const struct ofp_flow_mod *ofm)
981 struct sw_flow *flow;
982 size_t actions_len = ntohs(ofm->header.length) - sizeof *ofm;
984 /* Allocate memory. */
985 flow = flow_alloc(actions_len);
989 flow_extract_match(&flow->key, &ofm->match);
991 v_code = validate_actions(dp, &flow->key, ofm->actions, actions_len);
992 if (v_code != ACT_VALIDATION_OK) {
993 dp_send_error_msg(dp, sender, OFPET_BAD_ACTION, v_code,
994 ofm, ntohs(ofm->header.length));
995 goto error_free_flow;
999 flow->priority = flow->key.wildcards ? ntohs(ofm->priority) : -1;
1000 flow->idle_timeout = ntohs(ofm->idle_timeout);
1001 flow->hard_timeout = ntohs(ofm->hard_timeout);
1002 flow->used = flow->created = time_now();
1003 flow->sf_acts->actions_len = actions_len;
1004 flow->byte_count = 0;
1005 flow->packet_count = 0;
1006 memcpy(flow->sf_acts->actions, ofm->actions, actions_len);
1009 error = chain_insert(dp->chain, flow);
1010 if (error == -ENOBUFS) {
1011 dp_send_error_msg(dp, sender, OFPET_FLOW_MOD_FAILED,
1012 OFPFMFC_ALL_TABLES_FULL, ofm, ntohs(ofm->header.length));
1013 goto error_free_flow;
1015 goto error_free_flow;
1018 if (ntohl(ofm->buffer_id) != UINT32_MAX) {
1019 struct ofpbuf *buffer = retrieve_buffer(ntohl(ofm->buffer_id));
1021 struct sw_flow_key key;
1022 uint16_t in_port = ntohs(ofm->match.in_port);
1023 flow_used(flow, buffer);
1024 flow_extract(buffer, in_port, &key.flow);
1025 execute_actions(dp, buffer, &key,
1026 ofm->actions, actions_len, false);
1036 if (ntohl(ofm->buffer_id) != (uint32_t) -1)
1037 discard_buffer(ntohl(ofm->buffer_id));
1042 mod_flow(struct datapath *dp, const struct sender *sender,
1043 const struct ofp_flow_mod *ofm)
1045 int error = -ENOMEM;
1048 struct sw_flow_key key;
1052 flow_extract_match(&key, &ofm->match);
1054 actions_len = ntohs(ofm->header.length) - sizeof *ofm;
1056 v_code = validate_actions(dp, &key, ofm->actions, actions_len);
1057 if (v_code != ACT_VALIDATION_OK) {
1058 dp_send_error_msg(dp, sender, OFPET_BAD_ACTION, v_code,
1059 ofm, ntohs(ofm->header.length));
1063 priority = key.wildcards ? ntohs(ofm->priority) : -1;
1064 strict = (ofm->command == htons(OFPFC_MODIFY_STRICT)) ? 1 : 0;
1065 chain_modify(dp->chain, &key, priority, strict, ofm->actions, actions_len);
1067 if (ntohl(ofm->buffer_id) != UINT32_MAX) {
1068 struct ofpbuf *buffer = retrieve_buffer(ntohl(ofm->buffer_id));
1070 struct sw_flow_key skb_key;
1071 uint16_t in_port = ntohs(ofm->match.in_port);
1072 flow_extract(buffer, in_port, &skb_key.flow);
1073 execute_actions(dp, buffer, &skb_key,
1074 ofm->actions, actions_len, false);
1082 if (ntohl(ofm->buffer_id) != (uint32_t) -1)
1083 discard_buffer(ntohl(ofm->buffer_id));
1088 recv_flow(struct datapath *dp, const struct sender *sender,
1091 const struct ofp_flow_mod *ofm = msg;
1092 uint16_t command = ntohs(ofm->command);
1094 if (command == OFPFC_ADD) {
1095 return add_flow(dp, sender, ofm);
1096 } else if ((command == OFPFC_MODIFY) || (command == OFPFC_MODIFY_STRICT)) {
1097 return mod_flow(dp, sender, ofm);
1098 } else if (command == OFPFC_DELETE) {
1099 struct sw_flow_key key;
1100 flow_extract_match(&key, &ofm->match);
1101 return chain_delete(dp->chain, &key, 0, 0) ? 0 : -ESRCH;
1102 } else if (command == OFPFC_DELETE_STRICT) {
1103 struct sw_flow_key key;
1105 flow_extract_match(&key, &ofm->match);
1106 priority = key.wildcards ? ntohs(ofm->priority) : -1;
1107 return chain_delete(dp->chain, &key, priority, 1) ? 0 : -ESRCH;
1113 static int desc_stats_dump(struct datapath *dp, void *state,
1114 struct ofpbuf *buffer)
1116 struct ofp_desc_stats *ods = ofpbuf_put_zeros(buffer, sizeof *ods);
1118 strncpy(ods->mfr_desc, &mfr_desc, sizeof ods->mfr_desc);
1119 strncpy(ods->hw_desc, &hw_desc, sizeof ods->hw_desc);
1120 strncpy(ods->sw_desc, &sw_desc, sizeof ods->sw_desc);
1121 strncpy(ods->serial_num, &serial_num, sizeof ods->serial_num);
1126 struct flow_stats_state {
1128 struct sw_table_position position;
1129 struct ofp_flow_stats_request rq;
1132 struct ofpbuf *buffer;
1135 #define MAX_FLOW_STATS_BYTES 4096
1137 static int flow_stats_init(struct datapath *dp, const void *body, int body_len,
1140 const struct ofp_flow_stats_request *fsr = body;
1141 struct flow_stats_state *s = xmalloc(sizeof *s);
1142 s->table_idx = fsr->table_id == 0xff ? 0 : fsr->table_id;
1143 memset(&s->position, 0, sizeof s->position);
1149 static int flow_stats_dump_callback(struct sw_flow *flow, void *private)
1151 struct flow_stats_state *s = private;
1152 fill_flow_stats(s->buffer, flow, s->table_idx, s->now);
1153 return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1156 static int flow_stats_dump(struct datapath *dp, void *state,
1157 struct ofpbuf *buffer)
1159 struct flow_stats_state *s = state;
1160 struct sw_flow_key match_key;
1162 flow_extract_match(&match_key, &s->rq.match);
1164 s->now = time_now();
1165 while (s->table_idx < dp->chain->n_tables
1166 && (s->rq.table_id == 0xff || s->rq.table_id == s->table_idx))
1168 struct sw_table *table = dp->chain->tables[s->table_idx];
1170 if (table->iterate(table, &match_key, &s->position,
1171 flow_stats_dump_callback, s))
1175 memset(&s->position, 0, sizeof s->position);
1177 return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1180 static void flow_stats_done(void *state)
1185 struct aggregate_stats_state {
1186 struct ofp_aggregate_stats_request rq;
1189 static int aggregate_stats_init(struct datapath *dp,
1190 const void *body, int body_len,
1193 const struct ofp_aggregate_stats_request *rq = body;
1194 struct aggregate_stats_state *s = xmalloc(sizeof *s);
1200 static int aggregate_stats_dump_callback(struct sw_flow *flow, void *private)
1202 struct ofp_aggregate_stats_reply *rpy = private;
1203 rpy->packet_count += flow->packet_count;
1204 rpy->byte_count += flow->byte_count;
1209 static int aggregate_stats_dump(struct datapath *dp, void *state,
1210 struct ofpbuf *buffer)
1212 struct aggregate_stats_state *s = state;
1213 struct ofp_aggregate_stats_request *rq = &s->rq;
1214 struct ofp_aggregate_stats_reply *rpy;
1215 struct sw_table_position position;
1216 struct sw_flow_key match_key;
1219 rpy = ofpbuf_put_zeros(buffer, sizeof *rpy);
1221 flow_extract_match(&match_key, &rq->match);
1222 table_idx = rq->table_id == 0xff ? 0 : rq->table_id;
1223 memset(&position, 0, sizeof position);
1224 while (table_idx < dp->chain->n_tables
1225 && (rq->table_id == 0xff || rq->table_id == table_idx))
1227 struct sw_table *table = dp->chain->tables[table_idx];
1230 error = table->iterate(table, &match_key, &position,
1231 aggregate_stats_dump_callback, rpy);
1236 memset(&position, 0, sizeof position);
1239 rpy->packet_count = htonll(rpy->packet_count);
1240 rpy->byte_count = htonll(rpy->byte_count);
1241 rpy->flow_count = htonl(rpy->flow_count);
1245 static void aggregate_stats_done(void *state)
1250 static int table_stats_dump(struct datapath *dp, void *state,
1251 struct ofpbuf *buffer)
1254 for (i = 0; i < dp->chain->n_tables; i++) {
1255 struct ofp_table_stats *ots = ofpbuf_put_zeros(buffer, sizeof *ots);
1256 struct sw_table_stats stats;
1257 dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
1258 strncpy(ots->name, stats.name, sizeof ots->name);
1260 ots->wildcards = htonl(stats.wildcards);
1261 ots->max_entries = htonl(stats.max_flows);
1262 ots->active_count = htonl(stats.n_flows);
1263 ots->lookup_count = htonll(stats.n_lookup);
1264 ots->matched_count = htonll(stats.n_matched);
1269 struct port_stats_state {
1273 static int port_stats_init(struct datapath *dp, const void *body, int body_len,
1276 struct port_stats_state *s = xmalloc(sizeof *s);
1282 static int port_stats_dump(struct datapath *dp, void *state,
1283 struct ofpbuf *buffer)
1285 struct port_stats_state *s = state;
1288 for (i = s->port; i < DP_MAX_PORTS; i++) {
1289 struct sw_port *p = &dp->ports[i];
1290 struct ofp_port_stats *ops;
1294 ops = ofpbuf_put_zeros(buffer, sizeof *ops);
1295 ops->port_no = htons(port_no(dp, p));
1296 ops->rx_packets = htonll(p->rx_packets);
1297 ops->tx_packets = htonll(p->tx_packets);
1298 ops->rx_bytes = htonll(p->rx_bytes);
1299 ops->tx_bytes = htonll(p->tx_bytes);
1300 ops->rx_dropped = htonll(-1);
1301 ops->tx_dropped = htonll(p->tx_dropped);
1302 ops->rx_errors = htonll(-1);
1303 ops->tx_errors = htonll(-1);
1304 ops->rx_frame_err = htonll(-1);
1305 ops->rx_over_err = htonll(-1);
1306 ops->rx_crc_err = htonll(-1);
1307 ops->collisions = htonll(-1);
1314 static void port_stats_done(void *state)
1320 /* Value for 'type' member of struct ofp_stats_request. */
1323 /* Minimum and maximum acceptable number of bytes in body member of
1324 * struct ofp_stats_request. */
1325 size_t min_body, max_body;
1327 /* Prepares to dump some kind of statistics on 'dp'. 'body' and
1328 * 'body_len' are the 'body' member of the struct ofp_stats_request.
1329 * Returns zero if successful, otherwise a negative error code.
1330 * May initialize '*state' to state information. May be null if no
1331 * initialization is required.*/
1332 int (*init)(struct datapath *dp, const void *body, int body_len,
1335 /* Appends statistics for 'dp' to 'buffer', which initially contains a
1336 * struct ofp_stats_reply. On success, it should return 1 if it should be
1337 * called again later with another buffer, 0 if it is done, or a negative
1338 * errno value on failure. */
1339 int (*dump)(struct datapath *dp, void *state, struct ofpbuf *buffer);
1341 /* Cleans any state created by the init or dump functions. May be null
1342 * if no cleanup is required. */
1343 void (*done)(void *state);
1346 static const struct stats_type stats[] = {
1357 sizeof(struct ofp_flow_stats_request),
1358 sizeof(struct ofp_flow_stats_request),
1365 sizeof(struct ofp_aggregate_stats_request),
1366 sizeof(struct ofp_aggregate_stats_request),
1367 aggregate_stats_init,
1368 aggregate_stats_dump,
1369 aggregate_stats_done
1389 struct stats_dump_cb {
1391 struct ofp_stats_request *rq;
1392 struct sender sender;
1393 const struct stats_type *s;
1398 stats_dump(struct datapath *dp, void *cb_)
1400 struct stats_dump_cb *cb = cb_;
1401 struct ofp_stats_reply *osr;
1402 struct ofpbuf *buffer;
1409 osr = make_openflow_reply(sizeof *osr, OFPT_STATS_REPLY, &cb->sender,
1411 osr->type = htons(cb->s->type);
1414 err = cb->s->dump(dp, cb->state, buffer);
1420 /* Buffer might have been reallocated, so find our data again. */
1421 osr = ofpbuf_at_assert(buffer, 0, sizeof *osr);
1422 osr->flags = ntohs(OFPSF_REPLY_MORE);
1424 err2 = send_openflow_buffer(dp, buffer, &cb->sender);
1434 stats_done(void *cb_)
1436 struct stats_dump_cb *cb = cb_;
1439 cb->s->done(cb->state);
1446 recv_stats_request(struct datapath *dp, const struct sender *sender,
1449 const struct ofp_stats_request *rq = oh;
1450 size_t rq_len = ntohs(rq->header.length);
1451 const struct stats_type *st;
1452 struct stats_dump_cb *cb;
1456 type = ntohs(rq->type);
1457 for (st = stats; ; st++) {
1458 if (st >= &stats[ARRAY_SIZE(stats)]) {
1459 VLOG_WARN_RL(&rl, "received stats request of unknown type %d",
1462 } else if (type == st->type) {
1467 cb = xmalloc(sizeof *cb);
1469 cb->rq = xmemdup(rq, rq_len);
1470 cb->sender = *sender;
1474 body_len = rq_len - offsetof(struct ofp_stats_request, body);
1475 if (body_len < cb->s->min_body || body_len > cb->s->max_body) {
1476 VLOG_WARN_RL(&rl, "stats request type %d with bad body length %d",
1483 err = cb->s->init(dp, rq->body, body_len, &cb->state);
1486 "failed initialization of stats request type %d: %s",
1487 type, strerror(-err));
1492 remote_start_dump(sender->remote, stats_dump, stats_done, cb);
1502 recv_echo_request(struct datapath *dp, const struct sender *sender,
1505 return send_openflow_buffer(dp, make_echo_reply(oh), sender);
1509 recv_echo_reply(struct datapath *dp UNUSED, const struct sender *sender UNUSED,
1510 const void *oh UNUSED)
1515 /* 'msg', which is 'length' bytes long, was received from the control path.
1516 * Apply it to 'chain'. */
1518 fwd_control_input(struct datapath *dp, const struct sender *sender,
1519 const void *msg, size_t length)
1521 int (*handler)(struct datapath *, const struct sender *, const void *);
1522 struct ofp_header *oh;
1525 /* Check encapsulated length. */
1526 oh = (struct ofp_header *) msg;
1527 if (ntohs(oh->length) > length) {
1530 assert(oh->version == OFP_VERSION);
1532 /* Figure out how to handle it. */
1534 case OFPT_FEATURES_REQUEST:
1535 min_size = sizeof(struct ofp_header);
1536 handler = recv_features_request;
1538 case OFPT_GET_CONFIG_REQUEST:
1539 min_size = sizeof(struct ofp_header);
1540 handler = recv_get_config_request;
1542 case OFPT_SET_CONFIG:
1543 min_size = sizeof(struct ofp_switch_config);
1544 handler = recv_set_config;
1546 case OFPT_PACKET_OUT:
1547 min_size = sizeof(struct ofp_packet_out);
1548 handler = recv_packet_out;
1551 min_size = sizeof(struct ofp_flow_mod);
1552 handler = recv_flow;
1555 min_size = sizeof(struct ofp_port_mod);
1556 handler = recv_port_mod;
1558 case OFPT_STATS_REQUEST:
1559 min_size = sizeof(struct ofp_stats_request);
1560 handler = recv_stats_request;
1562 case OFPT_ECHO_REQUEST:
1563 min_size = sizeof(struct ofp_header);
1564 handler = recv_echo_request;
1566 case OFPT_ECHO_REPLY:
1567 min_size = sizeof(struct ofp_header);
1568 handler = recv_echo_reply;
1571 dp_send_error_msg(dp, sender, OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE,
1577 if (length < min_size)
1579 return handler(dp, sender, msg);
1582 /* Packet buffering. */
1584 #define OVERWRITE_SECS 1
1586 struct packet_buffer {
1587 struct ofpbuf *buffer;
1592 static struct packet_buffer buffers[N_PKT_BUFFERS];
1593 static unsigned int buffer_idx;
1595 uint32_t save_buffer(struct ofpbuf *buffer)
1597 struct packet_buffer *p;
1600 buffer_idx = (buffer_idx + 1) & PKT_BUFFER_MASK;
1601 p = &buffers[buffer_idx];
1603 /* Don't buffer packet if existing entry is less than
1604 * OVERWRITE_SECS old. */
1605 if (time_now() < p->timeout) { /* FIXME */
1608 ofpbuf_delete(p->buffer);
1611 /* Don't use maximum cookie value since the all-bits-1 id is
1613 if (++p->cookie >= (1u << PKT_COOKIE_BITS) - 1)
1615 p->buffer = ofpbuf_clone(buffer); /* FIXME */
1616 p->timeout = time_now() + OVERWRITE_SECS; /* FIXME */
1617 id = buffer_idx | (p->cookie << PKT_BUFFER_BITS);
1622 static struct ofpbuf *retrieve_buffer(uint32_t id)
1624 struct ofpbuf *buffer = NULL;
1625 struct packet_buffer *p;
1627 p = &buffers[id & PKT_BUFFER_MASK];
1628 if (p->cookie == id >> PKT_BUFFER_BITS) {
1632 printf("cookie mismatch: %x != %x\n",
1633 id >> PKT_BUFFER_BITS, p->cookie);
1639 static void discard_buffer(uint32_t id)
1641 struct packet_buffer *p;
1643 p = &buffers[id & PKT_BUFFER_MASK];
1644 if (p->cookie == id >> PKT_BUFFER_BITS) {
1645 ofpbuf_delete(p->buffer);