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>
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);
120 /* Remote connections. */
121 struct remote *controller; /* Connection to controller. */
122 struct list remotes; /* All connections (including controller). */
123 struct pvconn *listen_pvconn;
127 /* Unique identifier for this datapath */
130 struct sw_chain *chain; /* Forwarding rules. */
132 /* Configuration set from controller. */
134 uint16_t miss_send_len;
137 struct sw_port ports[OFPP_MAX];
138 struct list port_list; /* List of ports, for flooding. */
141 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 60);
143 static struct remote *remote_create(struct datapath *, struct rconn *);
144 static void remote_run(struct datapath *, struct remote *);
145 static void remote_wait(struct remote *);
146 static void remote_destroy(struct remote *);
148 void dp_update_port_flags(struct datapath *dp, const struct ofp_port_mod *opm);
149 static void send_flow_expired(struct datapath *, struct sw_flow *,
150 enum ofp_flow_expired_reason);
151 static int update_port_status(struct sw_port *p);
152 static void send_port_status(struct sw_port *p, uint8_t status);
153 static void del_switch_port(struct sw_port *p);
155 /* Buffers are identified to userspace by a 31-bit opaque ID. We divide the ID
156 * into a buffer number (low bits) and a cookie (high bits). The buffer number
157 * is an index into an array of buffers. The cookie distinguishes between
158 * different packets that have occupied a single buffer. Thus, the more
159 * buffers we have, the lower-quality the cookie... */
160 #define PKT_BUFFER_BITS 8
161 #define N_PKT_BUFFERS (1 << PKT_BUFFER_BITS)
162 #define PKT_BUFFER_MASK (N_PKT_BUFFERS - 1)
164 #define PKT_COOKIE_BITS (32 - PKT_BUFFER_BITS)
166 int run_flow_through_tables(struct datapath *, struct ofpbuf *,
168 void fwd_port_input(struct datapath *, struct ofpbuf *, struct sw_port *);
169 int fwd_control_input(struct datapath *, const struct sender *,
170 const void *, size_t);
172 uint32_t save_buffer(struct ofpbuf *);
173 static struct ofpbuf *retrieve_buffer(uint32_t id);
174 static void discard_buffer(uint32_t id);
176 static int port_no(struct datapath *dp, struct sw_port *p)
178 assert(p >= dp->ports && p < &dp->ports[ARRAY_SIZE(dp->ports)]);
179 return p - dp->ports;
182 /* Generates and returns a random datapath id. */
184 gen_datapath_id(void)
186 uint8_t ea[ETH_ADDR_LEN];
188 return eth_addr_to_uint64(ea);
192 dp_new(struct datapath **dp_, uint64_t dpid, struct rconn *rconn)
196 dp = calloc(1, sizeof *dp);
201 dp->last_timeout = time_now();
202 list_init(&dp->remotes);
203 dp->controller = remote_create(dp, rconn);
204 dp->listen_pvconn = NULL;
205 dp->id = dpid <= UINT64_C(0xffffffffffff) ? dpid : gen_datapath_id();
206 dp->chain = chain_create();
208 VLOG_ERR("could not create chain");
213 list_init(&dp->port_list);
215 dp->miss_send_len = OFP_DEFAULT_MISS_SEND_LEN;
221 dp_add_port(struct datapath *dp, const char *name)
223 struct netdev *netdev;
229 error = netdev_open(name, NETDEV_ETH_TYPE_ANY, &netdev);
233 error = netdev_set_flags(netdev, NETDEV_UP | NETDEV_PROMISC, false);
235 VLOG_ERR("couldn't set promiscuous mode on %s device", name);
236 netdev_close(netdev);
239 if (netdev_get_in4(netdev, &in4)) {
240 VLOG_ERR("%s device has assigned IP address %s", name, inet_ntoa(in4));
242 if (netdev_get_in6(netdev, &in6)) {
243 char in6_name[INET6_ADDRSTRLEN + 1];
244 inet_ntop(AF_INET6, &in6, in6_name, sizeof in6_name);
245 VLOG_ERR("%s device has assigned IPv6 address %s", name, in6_name);
248 for (p = dp->ports; ; p++) {
249 if (p >= &dp->ports[ARRAY_SIZE(dp->ports)]) {
251 } else if (!p->netdev) {
256 memset(p, '\0', sizeof *p);
260 list_push_back(&dp->port_list, &p->node);
262 /* Notify the ctlpath that this port has been added */
263 send_port_status(p, OFPPR_ADD);
269 dp_add_listen_pvconn(struct datapath *dp, struct pvconn *listen_pvconn)
271 assert(!dp->listen_pvconn);
272 dp->listen_pvconn = listen_pvconn;
276 dp_run(struct datapath *dp)
278 time_t now = time_now();
279 struct sw_port *p, *pn;
280 struct remote *r, *rn;
281 struct ofpbuf *buffer = NULL;
283 if (now != dp->last_timeout) {
284 struct list deleted = LIST_INITIALIZER(&deleted);
285 struct sw_flow *f, *n;
287 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
288 if (update_port_status(p)) {
289 send_port_status(p, OFPPR_MODIFY);
293 chain_timeout(dp->chain, &deleted);
294 LIST_FOR_EACH_SAFE (f, n, struct sw_flow, node, &deleted) {
295 send_flow_expired(dp, f, f->reason);
296 list_remove(&f->node);
299 dp->last_timeout = now;
301 poll_timer_wait(1000);
303 LIST_FOR_EACH_SAFE (p, pn, struct sw_port, node, &dp->port_list) {
307 /* Allocate buffer with some headroom to add headers in forwarding
308 * to the controller or adding a vlan tag, plus an extra 2 bytes to
309 * allow IP headers to be aligned on a 4-byte boundary. */
310 const int headroom = 128 + 2;
311 const int hard_header = VLAN_ETH_HEADER_LEN;
312 const int mtu = netdev_get_mtu(p->netdev);
313 buffer = ofpbuf_new(headroom + hard_header + mtu);
314 buffer->data = (char*)buffer->data + headroom;
316 error = netdev_recv(p->netdev, buffer);
319 p->rx_bytes += buffer->size;
320 fwd_port_input(dp, buffer, p);
322 } else if (error != EAGAIN) {
323 VLOG_ERR_RL(&rl, "error receiving data from %s: %s",
324 netdev_get_name(p->netdev), strerror(error));
327 ofpbuf_delete(buffer);
329 /* Talk to remotes. */
330 LIST_FOR_EACH_SAFE (r, rn, struct remote, node, &dp->remotes) {
333 if (dp->listen_pvconn) {
335 struct vconn *new_vconn;
338 retval = pvconn_accept(dp->listen_pvconn, OFP_VERSION, &new_vconn);
340 if (retval != EAGAIN) {
341 VLOG_WARN_RL(&rl, "accept failed (%s)", strerror(retval));
345 remote_create(dp, rconn_new_from_vconn("passive", new_vconn));
351 remote_run(struct datapath *dp, struct remote *r)
357 /* Do some remote processing, but cap it at a reasonable amount so that
358 * other processing doesn't starve. */
359 for (i = 0; i < 50; i++) {
361 struct ofpbuf *buffer;
362 struct ofp_header *oh;
364 buffer = rconn_recv(r->rconn);
369 if (buffer->size >= sizeof *oh) {
370 struct sender sender;
374 sender.xid = oh->xid;
375 fwd_control_input(dp, &sender, buffer->data, buffer->size);
377 VLOG_WARN_RL(&rl, "received too-short OpenFlow message");
379 ofpbuf_delete(buffer);
381 if (r->n_txq < TXQ_LIMIT) {
382 int error = r->cb_dump(dp, r->cb_aux);
385 VLOG_WARN_RL(&rl, "dump callback error: %s",
388 r->cb_done(r->cb_aux);
397 if (!rconn_is_alive(r->rconn)) {
403 remote_wait(struct remote *r)
405 rconn_run_wait(r->rconn);
406 rconn_recv_wait(r->rconn);
410 remote_destroy(struct remote *r)
413 if (r->cb_dump && r->cb_done) {
414 r->cb_done(r->cb_aux);
416 list_remove(&r->node);
417 rconn_destroy(r->rconn);
422 static struct remote *
423 remote_create(struct datapath *dp, struct rconn *rconn)
425 struct remote *remote = xmalloc(sizeof *remote);
426 list_push_back(&dp->remotes, &remote->node);
427 remote->rconn = rconn;
428 remote->cb_dump = NULL;
433 /* Starts a callback-based, reliable, possibly multi-message reply to a
434 * request made by 'remote'.
436 * 'dump' designates a function that will be called when the 'remote' send
437 * queue has an empty slot. It should compose a message and send it on
438 * 'remote'. On success, it should return 1 if it should be called again when
439 * another send queue slot opens up, 0 if its transmissions are complete, or a
440 * negative errno value on failure.
442 * 'done' designates a function to clean up any resources allocated for the
443 * dump. It must handle being called before the dump is complete (which will
444 * happen if 'remote' is closed unexpectedly).
446 * 'aux' is passed to 'dump' and 'done'. */
448 remote_start_dump(struct remote *remote,
449 int (*dump)(struct datapath *, void *),
450 void (*done)(void *),
453 assert(!remote->cb_dump);
454 remote->cb_dump = dump;
455 remote->cb_done = done;
456 remote->cb_aux = aux;
460 dp_wait(struct datapath *dp)
465 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
466 netdev_recv_wait(p->netdev);
468 LIST_FOR_EACH (r, struct remote, node, &dp->remotes) {
471 if (dp->listen_pvconn) {
472 pvconn_wait(dp->listen_pvconn);
476 /* Delete 'p' from switch. */
478 del_switch_port(struct sw_port *p)
480 send_port_status(p, OFPPR_DELETE);
481 netdev_close(p->netdev);
483 list_remove(&p->node);
487 dp_destroy(struct datapath *dp)
489 struct sw_port *p, *n;
495 LIST_FOR_EACH_SAFE (p, n, struct sw_port, node, &dp->port_list) {
498 chain_destroy(dp->chain);
502 /* Send packets out all the ports except the originating one. If the
503 * "flood" argument is set, don't send out ports with flooding disabled.
506 output_all(struct datapath *dp, struct ofpbuf *buffer, int in_port, int flood)
512 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
513 if (port_no(dp, p) == in_port) {
516 if (flood && p->config & OFPPC_NO_FLOOD) {
519 if (prev_port != -1) {
520 dp_output_port(dp, ofpbuf_clone(buffer), in_port, prev_port,
523 prev_port = port_no(dp, p);
526 dp_output_port(dp, buffer, in_port, prev_port, false);
528 ofpbuf_delete(buffer);
534 output_packet(struct datapath *dp, struct ofpbuf *buffer, int out_port)
536 if (out_port >= 0 && out_port < OFPP_MAX) {
537 struct sw_port *p = &dp->ports[out_port];
538 if (p->netdev != NULL && !(p->config & OFPPC_PORT_DOWN)) {
539 if (!netdev_send(p->netdev, buffer)) {
541 p->tx_bytes += buffer->size;
549 ofpbuf_delete(buffer);
550 VLOG_DBG_RL(&rl, "can't forward to bad port %d\n", out_port);
553 /* Takes ownership of 'buffer' and transmits it to 'out_port' on 'dp'.
556 dp_output_port(struct datapath *dp, struct ofpbuf *buffer,
557 int in_port, int out_port, bool ignore_no_fwd)
561 if (out_port == OFPP_FLOOD) {
562 output_all(dp, buffer, in_port, 1);
563 } else if (out_port == OFPP_ALL) {
564 output_all(dp, buffer, in_port, 0);
565 } else if (out_port == OFPP_CONTROLLER) {
566 dp_output_control(dp, buffer, in_port, 0, OFPR_ACTION);
567 } else if (out_port == OFPP_IN_PORT) {
568 output_packet(dp, buffer, in_port);
569 } else if (out_port == OFPP_TABLE) {
570 struct sw_port *p = in_port < OFPP_MAX ? &dp->ports[in_port] : 0;
571 if (run_flow_through_tables(dp, buffer, p)) {
572 ofpbuf_delete(buffer);
575 if (in_port == out_port) {
576 VLOG_DBG_RL(&rl, "can't directly forward to input port");
579 output_packet(dp, buffer, out_port);
584 make_openflow_reply(size_t openflow_len, uint8_t type,
585 const struct sender *sender, struct ofpbuf **bufferp)
587 return make_openflow_xid(openflow_len, type, sender ? sender->xid : 0,
592 send_openflow_buffer(struct datapath *dp, struct ofpbuf *buffer,
593 const struct sender *sender)
595 struct remote *remote = sender ? sender->remote : dp->controller;
596 struct rconn *rconn = remote->rconn;
599 update_openflow_length(buffer);
600 retval = rconn_send_with_limit(rconn, buffer, &remote->n_txq, TXQ_LIMIT);
602 VLOG_WARN_RL(&rl, "send to %s failed: %s",
603 rconn_get_name(rconn), strerror(retval));
608 /* Takes ownership of 'buffer' and transmits it to 'dp''s controller. If the
609 * packet can be saved in a buffer, then only the first max_len bytes of
610 * 'buffer' are sent; otherwise, all of 'buffer' is sent. 'reason' indicates
611 * why 'buffer' is being sent. 'max_len' sets the maximum number of bytes that
612 * the caller wants to be sent; a value of 0 indicates the entire packet should
615 dp_output_control(struct datapath *dp, struct ofpbuf *buffer, int in_port,
616 size_t max_len, int reason)
618 struct ofp_packet_in *opi;
622 buffer_id = save_buffer(buffer);
623 total_len = buffer->size;
624 if (buffer_id != UINT32_MAX && max_len && buffer->size > max_len) {
625 buffer->size = max_len;
628 opi = ofpbuf_push_uninit(buffer, offsetof(struct ofp_packet_in, data));
629 opi->header.version = OFP_VERSION;
630 opi->header.type = OFPT_PACKET_IN;
631 opi->header.length = htons(buffer->size);
632 opi->header.xid = htonl(0);
633 opi->buffer_id = htonl(buffer_id);
634 opi->total_len = htons(total_len);
635 opi->in_port = htons(in_port);
636 opi->reason = reason;
638 send_openflow_buffer(dp, buffer, NULL);
641 static void fill_port_desc(struct datapath *dp, struct sw_port *p,
642 struct ofp_phy_port *desc)
644 desc->port_no = htons(port_no(dp, p));
645 strncpy((char *) desc->name, netdev_get_name(p->netdev),
647 desc->name[sizeof desc->name - 1] = '\0';
648 memcpy(desc->hw_addr, netdev_get_etheraddr(p->netdev), ETH_ADDR_LEN);
649 desc->config = htonl(p->config);
650 desc->state = htonl(p->state);
651 desc->curr = htonl(netdev_get_features(p->netdev, NETDEV_FEAT_CURRENT));
652 desc->supported = htonl(netdev_get_features(p->netdev,
653 NETDEV_FEAT_SUPPORTED));
654 desc->advertised = htonl(netdev_get_features(p->netdev,
655 NETDEV_FEAT_ADVERTISED));
656 desc->peer = htonl(netdev_get_features(p->netdev, NETDEV_FEAT_PEER));
660 dp_send_features_reply(struct datapath *dp, const struct sender *sender)
662 struct ofpbuf *buffer;
663 struct ofp_switch_features *ofr;
666 ofr = make_openflow_reply(sizeof *ofr, OFPT_FEATURES_REPLY,
668 ofr->datapath_id = htonll(dp->id);
669 ofr->n_tables = dp->chain->n_tables;
670 ofr->n_buffers = htonl(N_PKT_BUFFERS);
671 ofr->capabilities = htonl(OFP_SUPPORTED_CAPABILITIES);
672 ofr->actions = htonl(OFP_SUPPORTED_ACTIONS);
673 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
674 struct ofp_phy_port *opp = ofpbuf_put_uninit(buffer, sizeof *opp);
675 memset(opp, 0, sizeof *opp);
676 fill_port_desc(dp, p, opp);
678 send_openflow_buffer(dp, buffer, sender);
682 dp_update_port_flags(struct datapath *dp, const struct ofp_port_mod *opm)
684 int port_no = ntohs(opm->port_no);
685 if (port_no < OFPP_MAX) {
686 struct sw_port *p = &dp->ports[port_no];
688 /* Make sure the port id hasn't changed since this was sent */
689 if (!p || memcmp(opm->hw_addr, netdev_get_etheraddr(p->netdev),
690 ETH_ADDR_LEN) != 0) {
696 uint32_t config_mask = ntohl(opm->mask);
697 p->config &= ~config_mask;
698 p->config |= ntohl(opm->config) & config_mask;
701 if (opm->mask & htonl(OFPPC_PORT_DOWN)) {
702 if ((opm->config & htonl(OFPPC_PORT_DOWN))
703 && (p->config & OFPPC_PORT_DOWN) == 0) {
704 p->config |= OFPPC_PORT_DOWN;
705 netdev_turn_flags_off(p->netdev, NETDEV_UP, true);
706 } else if ((opm->config & htonl(OFPPC_PORT_DOWN)) == 0
707 && (p->config & OFPPC_PORT_DOWN)) {
708 p->config &= ~OFPPC_PORT_DOWN;
709 netdev_turn_flags_on(p->netdev, NETDEV_UP, true);
715 /* Update the port status field of the bridge port. A non-zero return
716 * value indicates some field has changed.
718 * NB: Callers of this function may hold the RCU read lock, so any
719 * additional checks must not sleep.
722 update_port_status(struct sw_port *p)
725 enum netdev_flags flags;
726 uint32_t orig_config = p->config;
727 uint32_t orig_state = p->state;
729 if (netdev_get_flags(p->netdev, &flags) < 0) {
730 VLOG_WARN_RL(&rl, "could not get netdev flags for %s",
731 netdev_get_name(p->netdev));
734 if (flags & NETDEV_UP) {
735 p->config &= ~OFPPC_PORT_DOWN;
737 p->config |= OFPPC_PORT_DOWN;
741 /* Not all cards support this getting link status, so don't warn on
743 retval = netdev_get_link_status(p->netdev);
745 p->state &= ~OFPPS_LINK_DOWN;
746 } else if (retval == 0) {
747 p->state |= OFPPS_LINK_DOWN;
750 return ((orig_config != p->config) || (orig_state != p->state));
754 send_port_status(struct sw_port *p, uint8_t status)
756 struct ofpbuf *buffer;
757 struct ofp_port_status *ops;
758 ops = make_openflow_xid(sizeof *ops, OFPT_PORT_STATUS, 0, &buffer);
759 ops->reason = status;
760 memset(ops->pad, 0, sizeof ops->pad);
761 fill_port_desc(p->dp, p, &ops->desc);
763 send_openflow_buffer(p->dp, buffer, NULL);
767 send_flow_expired(struct datapath *dp, struct sw_flow *flow,
768 enum ofp_flow_expired_reason reason)
770 struct ofpbuf *buffer;
771 struct ofp_flow_expired *ofe;
772 ofe = make_openflow_xid(sizeof *ofe, OFPT_FLOW_EXPIRED, 0, &buffer);
773 flow_fill_match(&ofe->match, &flow->key);
775 ofe->priority = htons(flow->priority);
776 ofe->reason = reason;
777 memset(ofe->pad, 0, sizeof ofe->pad);
779 ofe->duration = htonl(time_now() - flow->created);
780 memset(ofe->pad2, 0, sizeof ofe->pad2);
781 ofe->packet_count = htonll(flow->packet_count);
782 ofe->byte_count = htonll(flow->byte_count);
783 send_openflow_buffer(dp, buffer, NULL);
787 dp_send_error_msg(struct datapath *dp, const struct sender *sender,
788 uint16_t type, uint16_t code, const void *data, size_t len)
790 struct ofpbuf *buffer;
791 struct ofp_error_msg *oem;
792 oem = make_openflow_reply(sizeof(*oem)+len, OFPT_ERROR, sender, &buffer);
793 oem->type = htons(type);
794 oem->code = htons(code);
795 memcpy(oem->data, data, len);
796 send_openflow_buffer(dp, buffer, sender);
800 fill_flow_stats(struct ofpbuf *buffer, struct sw_flow *flow,
801 int table_idx, time_t now)
803 struct ofp_flow_stats *ofs;
804 int length = sizeof *ofs + flow->sf_acts->actions_len;
805 ofs = ofpbuf_put_uninit(buffer, length);
806 ofs->length = htons(length);
807 ofs->table_id = table_idx;
809 ofs->match.wildcards = htonl(flow->key.wildcards);
810 ofs->match.in_port = flow->key.flow.in_port;
811 memcpy(ofs->match.dl_src, flow->key.flow.dl_src, ETH_ADDR_LEN);
812 memcpy(ofs->match.dl_dst, flow->key.flow.dl_dst, ETH_ADDR_LEN);
813 ofs->match.dl_vlan = flow->key.flow.dl_vlan;
814 ofs->match.dl_type = flow->key.flow.dl_type;
815 ofs->match.nw_src = flow->key.flow.nw_src;
816 ofs->match.nw_dst = flow->key.flow.nw_dst;
817 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 memset(ofs->pad2, 0, sizeof ofs->pad2);
826 ofs->packet_count = htonll(flow->packet_count);
827 ofs->byte_count = htonll(flow->byte_count);
828 memcpy(ofs->actions, flow->sf_acts->actions, flow->sf_acts->actions_len);
832 /* 'buffer' was received on 'p', which may be a a physical switch port or a
833 * null pointer. Process it according to 'dp''s flow table. Returns 0 if
834 * successful, in which case 'buffer' is destroyed, or -ESRCH if there is no
835 * matching flow, in which case 'buffer' still belongs to the caller. */
836 int run_flow_through_tables(struct datapath *dp, struct ofpbuf *buffer,
839 struct sw_flow_key key;
840 struct sw_flow *flow;
843 if (flow_extract(buffer, p ? port_no(dp, p) : OFPP_NONE, &key.flow)
844 && (dp->flags & OFPC_FRAG_MASK) == OFPC_FRAG_DROP) {
846 ofpbuf_delete(buffer);
849 if (p && p->config & (OFPPC_NO_RECV | OFPPC_NO_RECV_STP)
850 && p->config & (!eth_addr_equals(key.flow.dl_dst, stp_eth_addr)
851 ? OFPPC_NO_RECV : OFPPC_NO_RECV_STP)) {
852 ofpbuf_delete(buffer);
856 flow = chain_lookup(dp->chain, &key);
858 flow_used(flow, buffer);
859 execute_actions(dp, buffer, &key, flow->sf_acts->actions,
860 flow->sf_acts->actions_len, false);
867 /* 'buffer' was received on 'p', which may be a a physical switch port or a
868 * null pointer. Process it according to 'dp''s flow table, sending it up to
869 * the controller if no flow matches. Takes ownership of 'buffer'. */
870 void fwd_port_input(struct datapath *dp, struct ofpbuf *buffer,
873 if (run_flow_through_tables(dp, buffer, p)) {
874 dp_output_control(dp, buffer, port_no(dp, p),
875 dp->miss_send_len, OFPR_NO_MATCH);
880 recv_features_request(struct datapath *dp, const struct sender *sender,
883 dp_send_features_reply(dp, sender);
888 recv_get_config_request(struct datapath *dp, const struct sender *sender,
891 struct ofpbuf *buffer;
892 struct ofp_switch_config *osc;
894 osc = make_openflow_reply(sizeof *osc, OFPT_GET_CONFIG_REPLY,
897 osc->flags = htons(dp->flags);
898 osc->miss_send_len = htons(dp->miss_send_len);
900 return send_openflow_buffer(dp, buffer, sender);
904 recv_set_config(struct datapath *dp, const struct sender *sender UNUSED,
907 const struct ofp_switch_config *osc = msg;
910 flags = ntohs(osc->flags) & (OFPC_SEND_FLOW_EXP | OFPC_FRAG_MASK);
911 if ((flags & OFPC_FRAG_MASK) != OFPC_FRAG_NORMAL
912 && (flags & OFPC_FRAG_MASK) != OFPC_FRAG_DROP) {
913 flags = (flags & ~OFPC_FRAG_MASK) | OFPC_FRAG_DROP;
916 dp->miss_send_len = ntohs(osc->miss_send_len);
921 recv_packet_out(struct datapath *dp, const struct sender *sender,
924 const struct ofp_packet_out *opo = msg;
925 struct sw_flow_key key;
927 struct ofpbuf *buffer;
928 size_t actions_len = ntohs(opo->actions_len);
930 if (actions_len > (ntohs(opo->header.length) - sizeof *opo)) {
931 VLOG_DBG_RL(&rl, "message too short for number of actions");
935 if (ntohl(opo->buffer_id) == (uint32_t) -1) {
936 /* FIXME: can we avoid copying data here? */
937 int data_len = ntohs(opo->header.length) - sizeof *opo - actions_len;
938 buffer = ofpbuf_new(data_len);
939 ofpbuf_put(buffer, (uint8_t *)opo->actions + actions_len, data_len);
941 buffer = retrieve_buffer(ntohl(opo->buffer_id));
947 flow_extract(buffer, ntohs(opo->in_port), &key.flow);
949 v_code = validate_actions(dp, &key, opo->actions, actions_len);
950 if (v_code != ACT_VALIDATION_OK) {
951 dp_send_error_msg(dp, sender, OFPET_BAD_ACTION, v_code,
952 msg, ntohs(opo->header.length));
956 execute_actions(dp, buffer, &key, opo->actions, actions_len, true);
961 ofpbuf_delete(buffer);
966 recv_port_mod(struct datapath *dp, const struct sender *sender UNUSED,
969 const struct ofp_port_mod *opm = msg;
971 dp_update_port_flags(dp, opm);
977 add_flow(struct datapath *dp, const struct sender *sender,
978 const struct ofp_flow_mod *ofm)
982 struct sw_flow *flow;
983 size_t actions_len = ntohs(ofm->header.length) - sizeof *ofm;
985 /* Allocate memory. */
986 flow = flow_alloc(actions_len);
990 flow_extract_match(&flow->key, &ofm->match);
992 v_code = validate_actions(dp, &flow->key, ofm->actions, actions_len);
993 if (v_code != ACT_VALIDATION_OK) {
994 dp_send_error_msg(dp, sender, OFPET_BAD_ACTION, v_code,
995 ofm, ntohs(ofm->header.length));
1000 flow->priority = flow->key.wildcards ? ntohs(ofm->priority) : -1;
1001 flow->idle_timeout = ntohs(ofm->idle_timeout);
1002 flow->hard_timeout = ntohs(ofm->hard_timeout);
1003 flow->used = flow->created = time_now();
1004 flow->sf_acts->actions_len = actions_len;
1005 flow->byte_count = 0;
1006 flow->packet_count = 0;
1007 memcpy(flow->sf_acts->actions, ofm->actions, actions_len);
1010 error = chain_insert(dp->chain, flow);
1012 goto error_free_flow;
1015 if (ntohl(ofm->buffer_id) != UINT32_MAX) {
1016 struct ofpbuf *buffer = retrieve_buffer(ntohl(ofm->buffer_id));
1018 struct sw_flow_key key;
1019 uint16_t in_port = ntohs(ofm->match.in_port);
1020 flow_used(flow, buffer);
1021 flow_extract(buffer, in_port, &key.flow);
1022 execute_actions(dp, buffer, &key,
1023 ofm->actions, actions_len, false);
1033 if (ntohl(ofm->buffer_id) != (uint32_t) -1)
1034 discard_buffer(ntohl(ofm->buffer_id));
1039 mod_flow(struct datapath *dp, const struct sender *sender,
1040 const struct ofp_flow_mod *ofm)
1042 int error = -ENOMEM;
1045 struct sw_flow_key key;
1049 flow_extract_match(&key, &ofm->match);
1051 actions_len = ntohs(ofm->header.length) - sizeof *ofm;
1053 v_code = validate_actions(dp, &key, ofm->actions, actions_len);
1054 if (v_code != ACT_VALIDATION_OK) {
1055 dp_send_error_msg(dp, sender, OFPET_BAD_ACTION, v_code,
1056 ofm, ntohs(ofm->header.length));
1060 priority = key.wildcards ? ntohs(ofm->priority) : -1;
1061 strict = (ofm->command == htons(OFPFC_MODIFY_STRICT)) ? 1 : 0;
1062 chain_modify(dp->chain, &key, priority, strict, ofm->actions, actions_len);
1064 if (ntohl(ofm->buffer_id) != UINT32_MAX) {
1065 struct ofpbuf *buffer = retrieve_buffer(ntohl(ofm->buffer_id));
1067 struct sw_flow_key skb_key;
1068 uint16_t in_port = ntohs(ofm->match.in_port);
1069 flow_extract(buffer, in_port, &skb_key.flow);
1070 execute_actions(dp, buffer, &skb_key,
1071 ofm->actions, actions_len, false);
1079 if (ntohl(ofm->buffer_id) != (uint32_t) -1)
1080 discard_buffer(ntohl(ofm->buffer_id));
1085 recv_flow(struct datapath *dp, const struct sender *sender,
1088 const struct ofp_flow_mod *ofm = msg;
1089 uint16_t command = ntohs(ofm->command);
1091 if (command == OFPFC_ADD) {
1092 return add_flow(dp, sender, ofm);
1093 } else if ((command == OFPFC_MODIFY) || (command == OFPFC_MODIFY_STRICT)) {
1094 return mod_flow(dp, sender, ofm);
1095 } else if (command == OFPFC_DELETE) {
1096 struct sw_flow_key key;
1097 flow_extract_match(&key, &ofm->match);
1098 return chain_delete(dp->chain, &key, 0, 0) ? 0 : -ESRCH;
1099 } else if (command == OFPFC_DELETE_STRICT) {
1100 struct sw_flow_key key;
1102 flow_extract_match(&key, &ofm->match);
1103 priority = key.wildcards ? ntohs(ofm->priority) : -1;
1104 return chain_delete(dp->chain, &key, priority, 1) ? 0 : -ESRCH;
1110 static int desc_stats_dump(struct datapath *dp, void *state,
1111 struct ofpbuf *buffer)
1113 struct ofp_desc_stats *ods = ofpbuf_put_uninit(buffer, sizeof *ods);
1115 strncpy(ods->mfr_desc, &mfr_desc, sizeof ods->mfr_desc);
1116 strncpy(ods->hw_desc, &hw_desc, sizeof ods->hw_desc);
1117 strncpy(ods->sw_desc, &sw_desc, sizeof ods->sw_desc);
1118 strncpy(ods->serial_num, &serial_num, sizeof ods->serial_num);
1123 struct flow_stats_state {
1125 struct sw_table_position position;
1126 struct ofp_flow_stats_request rq;
1129 struct ofpbuf *buffer;
1132 #define MAX_FLOW_STATS_BYTES 4096
1134 static int flow_stats_init(struct datapath *dp, const void *body, int body_len,
1137 const struct ofp_flow_stats_request *fsr = body;
1138 struct flow_stats_state *s = xmalloc(sizeof *s);
1139 s->table_idx = fsr->table_id == 0xff ? 0 : fsr->table_id;
1140 memset(&s->position, 0, sizeof s->position);
1146 static int flow_stats_dump_callback(struct sw_flow *flow, void *private)
1148 struct flow_stats_state *s = private;
1149 fill_flow_stats(s->buffer, flow, s->table_idx, s->now);
1150 return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1153 static int flow_stats_dump(struct datapath *dp, void *state,
1154 struct ofpbuf *buffer)
1156 struct flow_stats_state *s = state;
1157 struct sw_flow_key match_key;
1159 flow_extract_match(&match_key, &s->rq.match);
1161 s->now = time_now();
1162 while (s->table_idx < dp->chain->n_tables
1163 && (s->rq.table_id == 0xff || s->rq.table_id == s->table_idx))
1165 struct sw_table *table = dp->chain->tables[s->table_idx];
1167 if (table->iterate(table, &match_key, &s->position,
1168 flow_stats_dump_callback, s))
1172 memset(&s->position, 0, sizeof s->position);
1174 return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1177 static void flow_stats_done(void *state)
1182 struct aggregate_stats_state {
1183 struct ofp_aggregate_stats_request rq;
1186 static int aggregate_stats_init(struct datapath *dp,
1187 const void *body, int body_len,
1190 const struct ofp_aggregate_stats_request *rq = body;
1191 struct aggregate_stats_state *s = xmalloc(sizeof *s);
1197 static int aggregate_stats_dump_callback(struct sw_flow *flow, void *private)
1199 struct ofp_aggregate_stats_reply *rpy = private;
1200 rpy->packet_count += flow->packet_count;
1201 rpy->byte_count += flow->byte_count;
1206 static int aggregate_stats_dump(struct datapath *dp, void *state,
1207 struct ofpbuf *buffer)
1209 struct aggregate_stats_state *s = state;
1210 struct ofp_aggregate_stats_request *rq = &s->rq;
1211 struct ofp_aggregate_stats_reply *rpy;
1212 struct sw_table_position position;
1213 struct sw_flow_key match_key;
1216 rpy = ofpbuf_put_uninit(buffer, sizeof *rpy);
1217 memset(rpy, 0, sizeof *rpy);
1219 flow_extract_match(&match_key, &rq->match);
1220 table_idx = rq->table_id == 0xff ? 0 : rq->table_id;
1221 memset(&position, 0, sizeof position);
1222 while (table_idx < dp->chain->n_tables
1223 && (rq->table_id == 0xff || rq->table_id == table_idx))
1225 struct sw_table *table = dp->chain->tables[table_idx];
1228 error = table->iterate(table, &match_key, &position,
1229 aggregate_stats_dump_callback, rpy);
1234 memset(&position, 0, sizeof position);
1237 rpy->packet_count = htonll(rpy->packet_count);
1238 rpy->byte_count = htonll(rpy->byte_count);
1239 rpy->flow_count = htonl(rpy->flow_count);
1243 static void aggregate_stats_done(void *state)
1248 static int table_stats_dump(struct datapath *dp, void *state,
1249 struct ofpbuf *buffer)
1252 for (i = 0; i < dp->chain->n_tables; i++) {
1253 struct ofp_table_stats *ots = ofpbuf_put_uninit(buffer, sizeof *ots);
1254 struct sw_table_stats stats;
1255 dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
1256 strncpy(ots->name, stats.name, sizeof ots->name);
1258 ots->wildcards = htonl(stats.wildcards);
1259 memset(ots->pad, 0, sizeof ots->pad);
1260 ots->max_entries = htonl(stats.max_flows);
1261 ots->active_count = htonl(stats.n_flows);
1262 ots->lookup_count = htonll(stats.n_lookup);
1263 ots->matched_count = htonll(stats.n_matched);
1268 struct port_stats_state {
1272 static int port_stats_init(struct datapath *dp, const void *body, int body_len,
1275 struct port_stats_state *s = xmalloc(sizeof *s);
1281 static int port_stats_dump(struct datapath *dp, void *state,
1282 struct ofpbuf *buffer)
1284 struct port_stats_state *s = state;
1287 for (i = s->port; i < OFPP_MAX; i++) {
1288 struct sw_port *p = &dp->ports[i];
1289 struct ofp_port_stats *ops;
1293 ops = ofpbuf_put_uninit(buffer, sizeof *ops);
1294 ops->port_no = htons(port_no(dp, p));
1295 memset(ops->pad, 0, sizeof ops->pad);
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);