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>
46 #include "poll-loop.h"
52 #define THIS_MODULE VLM_datapath
55 #define BRIDGE_PORT_NO_FLOOD 0x00000001
57 /* Capabilities supported by this implementation. */
58 #define OFP_SUPPORTED_CAPABILITIES (OFPC_MULTI_PHY_TX)
60 /* Actions supported by this implementation. */
61 #define OFP_SUPPORTED_ACTIONS ( (1 << OFPAT_OUTPUT) \
62 | (1 << OFPAT_SET_DL_VLAN) \
63 | (1 << OFPAT_SET_DL_SRC) \
64 | (1 << OFPAT_SET_DL_DST) \
65 | (1 << OFPAT_SET_NW_SRC) \
66 | (1 << OFPAT_SET_NW_DST) \
67 | (1 << OFPAT_SET_TP_SRC) \
68 | (1 << OFPAT_SET_TP_DST) )
73 struct netdev *netdev;
74 struct list node; /* Element in datapath.ports. */
75 unsigned long long int rx_count, tx_count, drop_count;
78 /* The origin of a received OpenFlow message, to enable sending a reply. */
80 struct remote *remote; /* The device that sent the message. */
81 uint32_t xid; /* The OpenFlow transaction ID. */
84 /* A connection to a controller or a management device. */
89 /* Support for reliable, multi-message replies to requests.
91 * If an incoming request needs to have a reliable reply that might
92 * require multiple messages, it can use remote_start_dump() to set up
93 * a callback that will be called as buffer space for replies. */
94 int (*cb_dump)(struct datapath *, void *aux);
95 void (*cb_done)(void *aux);
100 /* Remote connections. */
101 struct remote *controller; /* Connection to controller. */
102 struct list remotes; /* All connections (including controller). */
103 struct vconn *listen_vconn;
107 /* Unique identifier for this datapath */
110 struct sw_chain *chain; /* Forwarding rules. */
112 struct ofp_switch_config config;
115 struct sw_port ports[OFPP_MAX];
116 struct list port_list; /* List of ports, for flooding. */
119 static struct remote *remote_create(struct datapath *, struct rconn *);
120 static void remote_run(struct datapath *, struct remote *);
121 static void remote_wait(struct remote *);
122 static void remote_destroy(struct remote *);
124 void dp_output_port(struct datapath *, struct buffer *,
125 int in_port, int out_port);
126 void dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp);
127 void dp_output_control(struct datapath *, struct buffer *, int in_port,
128 size_t max_len, int reason);
129 static void send_flow_expired(struct datapath *, struct sw_flow *);
130 static void send_port_status(struct sw_port *p, uint8_t status);
131 static void del_switch_port(struct sw_port *p);
132 static void execute_actions(struct datapath *, struct buffer *,
133 int in_port, const struct sw_flow_key *,
134 const struct ofp_action *, int n_actions);
135 static void modify_vlan(struct buffer *buffer, const struct sw_flow_key *key,
136 const struct ofp_action *a);
137 static void modify_nh(struct buffer *buffer, uint16_t eth_proto,
138 uint8_t nw_proto, const struct ofp_action *a);
139 static void modify_th(struct buffer *buffer, uint16_t eth_proto,
140 uint8_t nw_proto, const struct ofp_action *a);
142 /* Buffers are identified to userspace by a 31-bit opaque ID. We divide the ID
143 * into a buffer number (low bits) and a cookie (high bits). The buffer number
144 * is an index into an array of buffers. The cookie distinguishes between
145 * different packets that have occupied a single buffer. Thus, the more
146 * buffers we have, the lower-quality the cookie... */
147 #define PKT_BUFFER_BITS 8
148 #define N_PKT_BUFFERS (1 << PKT_BUFFER_BITS)
149 #define PKT_BUFFER_MASK (N_PKT_BUFFERS - 1)
151 #define PKT_COOKIE_BITS (32 - PKT_BUFFER_BITS)
153 void fwd_port_input(struct datapath *, struct buffer *, int in_port);
154 int fwd_control_input(struct datapath *, const struct sender *,
155 const void *, size_t);
157 uint32_t save_buffer(struct buffer *);
158 static struct buffer *retrieve_buffer(uint32_t id);
159 static void discard_buffer(uint32_t id);
161 static int port_no(struct datapath *dp, struct sw_port *p)
163 assert(p >= dp->ports && p < &dp->ports[ARRAY_SIZE(dp->ports)]);
164 return p - dp->ports;
167 /* Generates a unique datapath id. It incorporates the datapath index
168 * and a hardware address, if available. If not, it generates a random
172 gen_datapath_id(void)
174 /* Choose a random datapath id. */
180 for (i = 0; i < ETH_ADDR_LEN; i++) {
181 id |= (uint64_t)(rand() & 0xff) << (8*(ETH_ADDR_LEN-1 - i));
188 dp_new(struct datapath **dp_, uint64_t dpid, struct rconn *rconn)
192 dp = calloc(1, sizeof *dp);
197 dp->last_timeout = time(0);
198 list_init(&dp->remotes);
199 dp->controller = remote_create(dp, rconn);
200 dp->listen_vconn = NULL;
201 dp->id = dpid <= UINT64_C(0xffffffffffff) ? dpid : gen_datapath_id();
202 dp->chain = chain_create();
204 VLOG_ERR("could not create chain");
209 list_init(&dp->port_list);
210 dp->config.flags = 0;
211 dp->config.miss_send_len = htons(OFP_DEFAULT_MISS_SEND_LEN);
217 dp_add_port(struct datapath *dp, const char *name)
219 struct netdev *netdev;
225 error = netdev_open(name, &netdev);
229 error = netdev_set_flags(netdev, NETDEV_UP | NETDEV_PROMISC);
231 VLOG_ERR("Couldn't set promiscuous mode on %s device", name);
232 netdev_close(netdev);
235 if (netdev_get_in4(netdev, &in4)) {
236 VLOG_ERR("%s device has assigned IP address %s", name, inet_ntoa(in4));
238 if (netdev_get_in6(netdev, &in6)) {
239 char in6_name[INET6_ADDRSTRLEN + 1];
240 inet_ntop(AF_INET6, &in6, in6_name, sizeof in6_name);
241 VLOG_ERR("%s device has assigned IPv6 address %s", name, in6_name);
244 for (p = dp->ports; ; p++) {
245 if (p >= &dp->ports[ARRAY_SIZE(dp->ports)]) {
247 } else if (!p->netdev) {
257 list_push_back(&dp->port_list, &p->node);
259 /* Notify the ctlpath that this port has been added */
260 send_port_status(p, OFPPR_ADD);
266 dp_add_listen_vconn(struct datapath *dp, struct vconn *listen_vconn)
268 assert(!dp->listen_vconn);
269 dp->listen_vconn = listen_vconn;
273 dp_run(struct datapath *dp)
275 time_t now = time(0);
276 struct sw_port *p, *pn;
277 struct remote *r, *rn;
278 struct buffer *buffer = NULL;
280 if (now != dp->last_timeout) {
281 struct list deleted = LIST_INITIALIZER(&deleted);
282 struct sw_flow *f, *n;
284 chain_timeout(dp->chain, &deleted);
285 LIST_FOR_EACH_SAFE (f, n, struct sw_flow, node, &deleted) {
286 send_flow_expired(dp, f);
287 list_remove(&f->node);
290 dp->last_timeout = now;
292 poll_timer_wait(1000);
294 LIST_FOR_EACH_SAFE (p, pn, struct sw_port, node, &dp->port_list) {
298 /* Allocate buffer with some headroom to add headers in forwarding
299 * to the controller or adding a vlan tag, plus an extra 2 bytes to
300 * allow IP headers to be aligned on a 4-byte boundary. */
301 const int headroom = 128 + 2;
302 const int hard_header = VLAN_ETH_HEADER_LEN;
303 const int mtu = netdev_get_mtu(p->netdev);
304 buffer = buffer_new(headroom + hard_header + mtu);
305 buffer->data += headroom;
307 error = netdev_recv(p->netdev, buffer);
310 fwd_port_input(dp, buffer, port_no(dp, p));
312 } else if (error != EAGAIN) {
313 VLOG_ERR("Error receiving data from %s: %s",
314 netdev_get_name(p->netdev), strerror(error));
318 buffer_delete(buffer);
320 /* Talk to remotes. */
321 LIST_FOR_EACH_SAFE (r, rn, struct remote, node, &dp->remotes) {
324 if (dp->listen_vconn) {
326 struct vconn *new_vconn;
329 retval = vconn_accept(dp->listen_vconn, &new_vconn);
331 if (retval != EAGAIN) {
332 VLOG_WARN("accept failed (%s)", strerror(retval));
336 remote_create(dp, rconn_new_from_vconn("passive", 128, new_vconn));
342 remote_run(struct datapath *dp, struct remote *r)
348 /* Do some remote processing, but cap it at a reasonable amount so that
349 * other processing doesn't starve. */
350 for (i = 0; i < 50; i++) {
352 struct buffer *buffer;
353 struct ofp_header *oh;
355 buffer = rconn_recv(r->rconn);
360 if (buffer->size >= sizeof *oh) {
361 struct sender sender;
365 sender.xid = oh->xid;
366 fwd_control_input(dp, &sender, buffer->data, buffer->size);
368 VLOG_WARN("received too-short OpenFlow message");
370 buffer_delete(buffer);
372 if (!rconn_is_full(r->rconn)) {
373 int error = r->cb_dump(dp, r->cb_aux);
376 VLOG_WARN("dump callback error: %s", strerror(-error));
378 r->cb_done(r->cb_aux);
387 if (!rconn_is_alive(r->rconn)) {
393 remote_wait(struct remote *r)
395 rconn_run_wait(r->rconn);
396 rconn_recv_wait(r->rconn);
400 remote_destroy(struct remote *r)
403 if (r->cb_dump && r->cb_done) {
404 r->cb_done(r->cb_aux);
406 list_remove(&r->node);
407 rconn_destroy(r->rconn);
412 static struct remote *
413 remote_create(struct datapath *dp, struct rconn *rconn)
415 struct remote *remote = xmalloc(sizeof *remote);
416 list_push_back(&dp->remotes, &remote->node);
417 remote->rconn = rconn;
418 remote->cb_dump = NULL;
422 /* Starts a callback-based, reliable, possibly multi-message reply to a
423 * request made by 'remote'.
425 * 'dump' designates a function that will be called when the 'remote' send
426 * queue has an empty slot. It should compose a message and send it on
427 * 'remote'. On success, it should return 1 if it should be called again when
428 * another send queue slot opens up, 0 if its transmissions are complete, or a
429 * negative errno value on failure.
431 * 'done' designates a function to clean up any resources allocated for the
432 * dump. It must handle being called before the dump is complete (which will
433 * happen if 'remote' is closed unexpectedly).
435 * 'aux' is passed to 'dump' and 'done'. */
437 remote_start_dump(struct remote *remote,
438 int (*dump)(struct datapath *, void *),
439 void (*done)(void *),
442 assert(!remote->cb_dump);
443 remote->cb_dump = dump;
444 remote->cb_done = done;
445 remote->cb_aux = aux;
449 dp_wait(struct datapath *dp)
454 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
455 netdev_recv_wait(p->netdev);
457 LIST_FOR_EACH (r, struct remote, node, &dp->remotes) {
460 if (dp->listen_vconn) {
461 vconn_accept_wait(dp->listen_vconn);
465 /* Delete 'p' from switch. */
467 del_switch_port(struct sw_port *p)
469 send_port_status(p, OFPPR_DELETE);
470 netdev_close(p->netdev);
472 list_remove(&p->node);
476 dp_destroy(struct datapath *dp)
478 struct sw_port *p, *n;
484 LIST_FOR_EACH_SAFE (p, n, struct sw_port, node, &dp->port_list) {
487 chain_destroy(dp->chain);
491 /* Send packets out all the ports except the originating one. If the
492 * "flood" argument is set, don't send out ports with flooding disabled.
495 output_all(struct datapath *dp, struct buffer *buffer, int in_port, int flood)
501 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
502 if (port_no(dp, p) == in_port) {
505 if (flood && p->flags & BRIDGE_PORT_NO_FLOOD) {
508 if (prev_port != -1) {
509 dp_output_port(dp, buffer_clone(buffer), in_port, prev_port);
511 prev_port = port_no(dp, p);
514 dp_output_port(dp, buffer, in_port, prev_port);
516 buffer_delete(buffer);
522 output_packet(struct datapath *dp, struct buffer *buffer, int out_port)
524 if (out_port >= 0 && out_port < OFPP_MAX) {
525 struct sw_port *p = &dp->ports[out_port];
526 if (p->netdev != NULL) {
527 if (!netdev_send(p->netdev, buffer)) {
536 buffer_delete(buffer);
537 /* FIXME: ratelimit */
538 VLOG_DBG("can't forward to bad port %d\n", out_port);
541 /* Takes ownership of 'buffer' and transmits it to 'out_port' on 'dp'.
544 dp_output_port(struct datapath *dp, struct buffer *buffer,
545 int in_port, int out_port)
549 if (out_port == OFPP_FLOOD) {
550 output_all(dp, buffer, in_port, 1);
551 } else if (out_port == OFPP_ALL) {
552 output_all(dp, buffer, in_port, 0);
553 } else if (out_port == OFPP_CONTROLLER) {
554 dp_output_control(dp, buffer, in_port, 0, OFPR_ACTION);
555 } else if (out_port == OFPP_TABLE) {
556 struct sw_flow_key key;
557 struct sw_flow *flow;
560 flow_extract(buffer, in_port, &key.flow);
561 flow = chain_lookup(dp->chain, &key);
563 flow_used(flow, buffer);
564 execute_actions(dp, buffer, in_port, &key,
565 flow->actions, flow->n_actions);
568 output_packet(dp, buffer, out_port);
573 alloc_openflow_buffer(struct datapath *dp, size_t openflow_len, uint8_t type,
574 const struct sender *sender, struct buffer **bufferp)
576 struct buffer *buffer;
577 struct ofp_header *oh;
579 buffer = *bufferp = buffer_new(openflow_len);
580 oh = buffer_put_uninit(buffer, openflow_len);
581 oh->version = OFP_VERSION;
583 oh->length = 0; /* Filled in by send_openflow_buffer(). */
584 oh->xid = sender ? sender->xid : 0;
589 send_openflow_buffer(struct datapath *dp, struct buffer *buffer,
590 const struct sender *sender)
592 struct remote *remote = sender ? sender->remote : dp->controller;
593 struct rconn *rconn = remote->rconn;
594 struct ofp_header *oh;
597 oh = buffer_at_assert(buffer, 0, sizeof *oh);
598 oh->length = htons(buffer->size);
600 retval = rconn_send(rconn, buffer);
602 VLOG_WARN("send to %s failed: %s",
603 rconn_get_name(rconn), strerror(retval));
604 buffer_delete(buffer);
609 /* Takes ownership of 'buffer' and transmits it to 'dp''s controller. If the
610 * packet can be saved in a buffer, then only the first max_len bytes of
611 * 'buffer' are sent; otherwise, all of 'buffer' is sent. 'reason' indicates
612 * why 'buffer' is being sent. 'max_len' sets the maximum number of bytes that
613 * the caller wants to be sent; a value of 0 indicates the entire packet should
616 dp_output_control(struct datapath *dp, struct buffer *buffer, int in_port,
617 size_t max_len, int reason)
619 struct ofp_packet_in *opi;
623 buffer_id = save_buffer(buffer);
624 total_len = buffer->size;
625 if (buffer_id != UINT32_MAX && buffer->size > max_len) {
626 buffer->size = max_len;
629 opi = buffer_push_uninit(buffer, offsetof(struct ofp_packet_in, data));
630 opi->header.version = OFP_VERSION;
631 opi->header.type = OFPT_PACKET_IN;
632 opi->header.length = htons(buffer->size);
633 opi->header.xid = htonl(0);
634 opi->buffer_id = htonl(buffer_id);
635 opi->total_len = htons(total_len);
636 opi->in_port = htons(in_port);
637 opi->reason = reason;
639 send_openflow_buffer(dp, buffer, NULL);
642 static void fill_port_desc(struct datapath *dp, struct sw_port *p,
643 struct ofp_phy_port *desc)
645 desc->port_no = htons(port_no(dp, p));
646 strncpy((char *) desc->name, netdev_get_name(p->netdev),
648 desc->name[sizeof desc->name - 1] = '\0';
649 memcpy(desc->hw_addr, netdev_get_etheraddr(p->netdev), ETH_ADDR_LEN);
650 desc->flags = htonl(p->flags);
651 desc->features = htonl(netdev_get_features(p->netdev));
652 desc->speed = htonl(netdev_get_speed(p->netdev));
656 dp_send_features_reply(struct datapath *dp, const struct sender *sender)
658 struct buffer *buffer;
659 struct ofp_switch_features *ofr;
662 ofr = alloc_openflow_buffer(dp, sizeof *ofr, OFPT_FEATURES_REPLY,
664 ofr->datapath_id = htonll(dp->id);
665 ofr->n_exact = htonl(2 * TABLE_HASH_MAX_FLOWS);
666 ofr->n_compression = 0; /* Not supported */
667 ofr->n_general = htonl(TABLE_LINEAR_MAX_FLOWS);
668 ofr->buffer_mb = htonl(UINT32_MAX);
669 ofr->n_buffers = htonl(N_PKT_BUFFERS);
670 ofr->capabilities = htonl(OFP_SUPPORTED_CAPABILITIES);
671 ofr->actions = htonl(OFP_SUPPORTED_ACTIONS);
672 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
673 struct ofp_phy_port *opp = buffer_put_uninit(buffer, sizeof *opp);
674 memset(opp, 0, sizeof *opp);
675 fill_port_desc(dp, p, opp);
677 send_openflow_buffer(dp, buffer, sender);
681 dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp)
683 int port_no = ntohs(opp->port_no);
684 if (port_no < OFPP_MAX) {
685 struct sw_port *p = &dp->ports[port_no];
687 /* Make sure the port id hasn't changed since this was sent */
688 if (!p || memcmp(opp->hw_addr, netdev_get_etheraddr(p->netdev),
689 ETH_ADDR_LEN) != 0) {
692 p->flags = htonl(opp->flags);
697 send_port_status(struct sw_port *p, uint8_t status)
699 struct buffer *buffer;
700 struct ofp_port_status *ops;
701 ops = alloc_openflow_buffer(p->dp, sizeof *ops, OFPT_PORT_STATUS, NULL,
703 ops->reason = status;
704 memset(ops->pad, 0, sizeof ops->pad);
705 fill_port_desc(p->dp, p, &ops->desc);
707 send_openflow_buffer(p->dp, buffer, NULL);
711 send_flow_expired(struct datapath *dp, struct sw_flow *flow)
713 struct buffer *buffer;
714 struct ofp_flow_expired *ofe;
715 ofe = alloc_openflow_buffer(dp, sizeof *ofe, OFPT_FLOW_EXPIRED, NULL,
717 flow_fill_match(&ofe->match, &flow->key);
719 memset(ofe->pad, 0, sizeof ofe->pad);
720 ofe->priority = htons(flow->priority);
722 ofe->duration = htonl(flow->timeout - flow->max_idle - flow->created);
723 ofe->packet_count = htonll(flow->packet_count);
724 ofe->byte_count = htonll(flow->byte_count);
725 send_openflow_buffer(dp, buffer, NULL);
729 dp_send_error_msg(struct datapath *dp, const struct sender *sender,
730 uint16_t type, uint16_t code, const uint8_t *data, size_t len)
732 struct buffer *buffer;
733 struct ofp_error_msg *oem;
734 oem = alloc_openflow_buffer(dp, sizeof(*oem)+len, OFPT_ERROR_MSG,
736 oem->type = htons(type);
737 oem->code = htons(code);
738 memcpy(oem->data, data, len);
739 send_openflow_buffer(dp, buffer, sender);
743 fill_flow_stats(struct buffer *buffer, struct sw_flow *flow,
744 int table_idx, time_t now)
746 struct ofp_flow_stats *ofs;
747 int length = sizeof *ofs + sizeof *ofs->actions * flow->n_actions;
748 ofs = buffer_put_uninit(buffer, length);
749 ofs->length = htons(length);
750 ofs->table_id = table_idx;
752 ofs->match.wildcards = htons(flow->key.wildcards);
753 ofs->match.in_port = flow->key.flow.in_port;
754 memcpy(ofs->match.dl_src, flow->key.flow.dl_src, ETH_ADDR_LEN);
755 memcpy(ofs->match.dl_dst, flow->key.flow.dl_dst, ETH_ADDR_LEN);
756 ofs->match.dl_vlan = flow->key.flow.dl_vlan;
757 ofs->match.dl_type = flow->key.flow.dl_type;
758 ofs->match.nw_src = flow->key.flow.nw_src;
759 ofs->match.nw_dst = flow->key.flow.nw_dst;
760 ofs->match.nw_proto = flow->key.flow.nw_proto;
761 memset(ofs->match.pad, 0, sizeof ofs->match.pad);
762 ofs->match.tp_src = flow->key.flow.tp_src;
763 ofs->match.tp_dst = flow->key.flow.tp_dst;
764 ofs->duration = htonl(now - flow->created);
765 ofs->packet_count = htonll(flow->packet_count);
766 ofs->byte_count = htonll(flow->byte_count);
767 ofs->priority = htons(flow->priority);
768 ofs->max_idle = htons(flow->max_idle);
769 memcpy(ofs->actions, flow->actions,
770 sizeof *ofs->actions * flow->n_actions);
774 /* 'buffer' was received on 'in_port', a physical switch port between 0 and
775 * OFPP_MAX. Process it according to 'chain'. */
776 void fwd_port_input(struct datapath *dp, struct buffer *buffer, int in_port)
778 struct sw_flow_key key;
779 struct sw_flow *flow;
782 flow_extract(buffer, in_port, &key.flow);
783 flow = chain_lookup(dp->chain, &key);
785 flow_used(flow, buffer);
786 execute_actions(dp, buffer, in_port, &key,
787 flow->actions, flow->n_actions);
789 dp_output_control(dp, buffer, in_port, ntohs(dp->config.miss_send_len),
795 do_output(struct datapath *dp, struct buffer *buffer, int in_port,
796 size_t max_len, int out_port)
798 if (out_port != OFPP_CONTROLLER) {
799 dp_output_port(dp, buffer, in_port, out_port);
801 dp_output_control(dp, buffer, in_port, max_len, OFPR_ACTION);
806 execute_actions(struct datapath *dp, struct buffer *buffer,
807 int in_port, const struct sw_flow_key *key,
808 const struct ofp_action *actions, int n_actions)
810 /* Every output action needs a separate clone of 'buffer', but the common
811 * case is just a single output action, so that doing a clone and then
812 * freeing the original buffer is wasteful. So the following code is
813 * slightly obscure just to avoid that. */
815 size_t max_len=0; /* Initialze to make compiler happy */
820 eth_proto = ntohs(key->flow.dl_type);
822 for (i = 0; i < n_actions; i++) {
823 const struct ofp_action *a = &actions[i];
824 struct eth_header *eh = buffer->l2;
826 if (prev_port != -1) {
827 do_output(dp, buffer_clone(buffer), in_port, max_len, prev_port);
831 switch (ntohs(a->type)) {
833 prev_port = ntohs(a->arg.output.port);
834 max_len = ntohs(a->arg.output.max_len);
837 case OFPAT_SET_DL_VLAN:
838 modify_vlan(buffer, key, a);
841 case OFPAT_SET_DL_SRC:
842 memcpy(eh->eth_src, a->arg.dl_addr, sizeof eh->eth_src);
845 case OFPAT_SET_DL_DST:
846 memcpy(eh->eth_dst, a->arg.dl_addr, sizeof eh->eth_dst);
849 case OFPAT_SET_NW_SRC:
850 case OFPAT_SET_NW_DST:
851 modify_nh(buffer, eth_proto, key->flow.nw_proto, a);
854 case OFPAT_SET_TP_SRC:
855 case OFPAT_SET_TP_DST:
856 modify_th(buffer, eth_proto, key->flow.nw_proto, a);
864 do_output(dp, buffer, in_port, max_len, prev_port);
866 buffer_delete(buffer);
869 /* Returns the new checksum for a packet in which the checksum field previously
870 * contained 'old_csum' and in which a field that contained 'old_u16' was
871 * changed to contain 'new_u16'. */
873 recalc_csum16(uint16_t old_csum, uint16_t old_u16, uint16_t new_u16)
875 /* Ones-complement arithmetic is endian-independent, so this code does not
876 * use htons() or ntohs().
878 * See RFC 1624 for formula and explanation. */
879 uint16_t hc_complement = ~old_csum;
880 uint16_t m_complement = ~old_u16;
881 uint16_t m_prime = new_u16;
882 uint32_t sum = hc_complement + m_complement + m_prime;
883 uint16_t hc_prime_complement = sum + (sum >> 16);
884 return ~hc_prime_complement;
887 /* Returns the new checksum for a packet in which the checksum field previously
888 * contained 'old_csum' and in which a field that contained 'old_u32' was
889 * changed to contain 'new_u32'. */
891 recalc_csum32(uint16_t old_csum, uint32_t old_u32, uint32_t new_u32)
893 return recalc_csum16(recalc_csum16(old_csum, old_u32, new_u32),
894 old_u32 >> 16, new_u32 >> 16);
897 static void modify_nh(struct buffer *buffer, uint16_t eth_proto,
898 uint8_t nw_proto, const struct ofp_action *a)
900 if (eth_proto == ETH_TYPE_IP) {
901 struct ip_header *nh = buffer->l3;
902 uint32_t new, *field;
904 new = a->arg.nw_addr;
905 field = a->type == OFPAT_SET_NW_SRC ? &nh->ip_src : &nh->ip_dst;
906 if (nw_proto == IP_TYPE_TCP) {
907 struct tcp_header *th = buffer->l4;
908 th->tcp_csum = recalc_csum32(th->tcp_csum, *field, new);
909 } else if (nw_proto == IP_TYPE_UDP) {
910 struct udp_header *th = buffer->l4;
912 th->udp_csum = recalc_csum32(th->udp_csum, *field, new);
914 th->udp_csum = 0xffff;
918 nh->ip_csum = recalc_csum32(nh->ip_csum, *field, new);
923 static void modify_th(struct buffer *buffer, uint16_t eth_proto,
924 uint8_t nw_proto, const struct ofp_action *a)
926 if (eth_proto == ETH_TYPE_IP) {
927 uint16_t new, *field;
931 if (nw_proto == IP_TYPE_TCP) {
932 struct tcp_header *th = buffer->l4;
933 field = a->type == OFPAT_SET_TP_SRC ? &th->tcp_src : &th->tcp_dst;
934 th->tcp_csum = recalc_csum16(th->tcp_csum, *field, new);
936 } else if (nw_proto == IP_TYPE_UDP) {
937 struct udp_header *th = buffer->l4;
938 field = a->type == OFPAT_SET_TP_SRC ? &th->udp_src : &th->udp_dst;
939 th->udp_csum = recalc_csum16(th->udp_csum, *field, new);
946 modify_vlan(struct buffer *buffer,
947 const struct sw_flow_key *key, const struct ofp_action *a)
949 uint16_t new_id = a->arg.vlan_id;
950 struct vlan_eth_header *veh;
952 if (new_id != OFP_VLAN_NONE) {
953 if (key->flow.dl_vlan != htons(OFP_VLAN_NONE)) {
954 /* Modify vlan id, but maintain other TCI values */
956 veh->veth_tci &= ~htons(VLAN_VID);
957 veh->veth_tci |= htons(new_id);
959 /* Insert new vlan id. */
960 struct eth_header *eh = buffer->l2;
961 struct vlan_eth_header tmp;
962 memcpy(tmp.veth_dst, eh->eth_dst, ETH_ADDR_LEN);
963 memcpy(tmp.veth_src, eh->eth_src, ETH_ADDR_LEN);
964 tmp.veth_type = htons(ETH_TYPE_VLAN);
965 tmp.veth_tci = new_id;
966 tmp.veth_next_type = eh->eth_type;
968 veh = buffer_push_uninit(buffer, VLAN_HEADER_LEN);
969 memcpy(veh, &tmp, sizeof tmp);
970 buffer->l2 -= VLAN_HEADER_LEN;
973 /* Remove an existing vlan header if it exists */
975 if (veh->veth_type == htons(ETH_TYPE_VLAN)) {
976 struct eth_header tmp;
978 memcpy(tmp.eth_dst, veh->veth_dst, ETH_ADDR_LEN);
979 memcpy(tmp.eth_src, veh->veth_src, ETH_ADDR_LEN);
980 tmp.eth_type = veh->veth_next_type;
982 buffer->size -= VLAN_HEADER_LEN;
983 buffer->data += VLAN_HEADER_LEN;
984 buffer->l2 += VLAN_HEADER_LEN;
985 memcpy(buffer->data, &tmp, sizeof tmp);
991 recv_features_request(struct datapath *dp, const struct sender *sender,
994 dp_send_features_reply(dp, sender);
999 recv_get_config_request(struct datapath *dp, const struct sender *sender,
1002 struct buffer *buffer;
1003 struct ofp_switch_config *osc;
1005 osc = alloc_openflow_buffer(dp, sizeof *osc, OFPT_GET_CONFIG_REPLY,
1008 assert(sizeof *osc == sizeof dp->config);
1009 memcpy(((char *)osc) + sizeof osc->header,
1010 ((char *)&dp->config) + sizeof dp->config.header,
1011 sizeof dp->config - sizeof dp->config.header);
1013 return send_openflow_buffer(dp, buffer, sender);
1017 recv_set_config(struct datapath *dp, const struct sender *sender UNUSED,
1020 const struct ofp_switch_config *osc = msg;
1026 recv_packet_out(struct datapath *dp, const struct sender *sender UNUSED,
1029 const struct ofp_packet_out *opo = msg;
1031 if (ntohl(opo->buffer_id) == (uint32_t) -1) {
1032 /* FIXME: can we avoid copying data here? */
1033 int data_len = ntohs(opo->header.length) - sizeof *opo;
1034 struct buffer *buffer = buffer_new(data_len);
1035 buffer_put(buffer, opo->u.data, data_len);
1036 dp_output_port(dp, buffer,
1037 ntohs(opo->in_port), ntohs(opo->out_port));
1039 struct sw_flow_key key;
1040 struct buffer *buffer;
1043 buffer = retrieve_buffer(ntohl(opo->buffer_id));
1048 n_acts = (ntohs(opo->header.length) - sizeof *opo)
1049 / sizeof *opo->u.actions;
1050 flow_extract(buffer, ntohs(opo->in_port), &key.flow);
1051 execute_actions(dp, buffer, ntohs(opo->in_port),
1052 &key, opo->u.actions, n_acts);
1058 recv_port_mod(struct datapath *dp, const struct sender *sender UNUSED,
1061 const struct ofp_port_mod *opm = msg;
1063 dp_update_port_flags(dp, &opm->desc);
1069 add_flow(struct datapath *dp, const struct ofp_flow_mod *ofm)
1071 int error = -ENOMEM;
1074 struct sw_flow *flow;
1077 /* To prevent loops, make sure there's no action to send to the
1078 * OFP_TABLE virtual port.
1080 n_acts = (ntohs(ofm->header.length) - sizeof *ofm) / sizeof *ofm->actions;
1081 for (i=0; i<n_acts; i++) {
1082 const struct ofp_action *a = &ofm->actions[i];
1084 if (a->type == htons(OFPAT_OUTPUT)
1085 && a->arg.output.port == htons(OFPP_TABLE)) {
1086 /* xxx Send fancy new error message? */
1091 /* Allocate memory. */
1092 flow = flow_alloc(n_acts);
1096 /* Fill out flow. */
1097 flow_extract_match(&flow->key, &ofm->match);
1098 flow->max_idle = ntohs(ofm->max_idle);
1099 flow->priority = flow->key.wildcards ? ntohs(ofm->priority) : -1;
1100 flow->timeout = time(0) + flow->max_idle; /* FIXME */
1101 flow->n_actions = n_acts;
1102 flow->created = time(0); /* FIXME */
1103 flow->byte_count = 0;
1104 flow->packet_count = 0;
1105 memcpy(flow->actions, ofm->actions, n_acts * sizeof *flow->actions);
1108 error = chain_insert(dp->chain, flow);
1110 goto error_free_flow;
1113 if (ntohl(ofm->buffer_id) != UINT32_MAX) {
1114 struct buffer *buffer = retrieve_buffer(ntohl(ofm->buffer_id));
1116 struct sw_flow_key key;
1117 uint16_t in_port = ntohs(ofm->match.in_port);
1118 flow_used(flow, buffer);
1119 flow_extract(buffer, in_port, &key.flow);
1120 execute_actions(dp, buffer, in_port, &key, ofm->actions, n_acts);
1130 if (ntohl(ofm->buffer_id) != (uint32_t) -1)
1131 discard_buffer(ntohl(ofm->buffer_id));
1136 recv_flow(struct datapath *dp, const struct sender *sender UNUSED,
1139 const struct ofp_flow_mod *ofm = msg;
1140 uint16_t command = ntohs(ofm->command);
1142 if (command == OFPFC_ADD) {
1143 return add_flow(dp, ofm);
1144 } else if (command == OFPFC_DELETE) {
1145 struct sw_flow_key key;
1146 flow_extract_match(&key, &ofm->match);
1147 return chain_delete(dp->chain, &key, 0, 0) ? 0 : -ESRCH;
1148 } else if (command == OFPFC_DELETE_STRICT) {
1149 struct sw_flow_key key;
1151 flow_extract_match(&key, &ofm->match);
1152 priority = key.wildcards ? ntohs(ofm->priority) : -1;
1153 return chain_delete(dp->chain, &key, priority, 1) ? 0 : -ESRCH;
1159 struct flow_stats_state {
1161 struct sw_table_position position;
1162 struct ofp_flow_stats_request rq;
1165 struct buffer *buffer;
1168 #define MAX_FLOW_STATS_BYTES 4096
1170 static int flow_stats_init(struct datapath *dp, const void *body, int body_len,
1173 const struct ofp_flow_stats_request *fsr = body;
1174 struct flow_stats_state *s = xmalloc(sizeof *s);
1175 s->table_idx = fsr->table_id == 0xff ? 0 : fsr->table_id;
1176 memset(&s->position, 0, sizeof s->position);
1182 static int flow_stats_dump_callback(struct sw_flow *flow, void *private)
1184 struct flow_stats_state *s = private;
1185 fill_flow_stats(s->buffer, flow, s->table_idx, s->now);
1186 return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1189 static int flow_stats_dump(struct datapath *dp, void *state,
1190 struct buffer *buffer)
1192 struct flow_stats_state *s = state;
1193 struct sw_flow_key match_key;
1195 flow_extract_match(&match_key, &s->rq.match);
1198 while (s->table_idx < dp->chain->n_tables
1199 && (s->rq.table_id == 0xff || s->rq.table_id == s->table_idx))
1201 struct sw_table *table = dp->chain->tables[s->table_idx];
1203 if (table->iterate(table, &match_key, &s->position,
1204 flow_stats_dump_callback, s))
1208 memset(&s->position, 0, sizeof s->position);
1210 return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1213 static void flow_stats_done(void *state)
1218 struct aggregate_stats_state {
1219 struct ofp_aggregate_stats_request rq;
1222 static int aggregate_stats_init(struct datapath *dp,
1223 const void *body, int body_len,
1226 const struct ofp_aggregate_stats_request *rq = body;
1227 struct aggregate_stats_state *s = xmalloc(sizeof *s);
1233 static int aggregate_stats_dump_callback(struct sw_flow *flow, void *private)
1235 struct ofp_aggregate_stats_reply *rpy = private;
1236 rpy->packet_count += flow->packet_count;
1237 rpy->byte_count += flow->byte_count;
1242 static int aggregate_stats_dump(struct datapath *dp, void *state,
1243 struct buffer *buffer)
1245 struct aggregate_stats_state *s = state;
1246 struct ofp_aggregate_stats_request *rq = &s->rq;
1247 struct ofp_aggregate_stats_reply *rpy;
1248 struct sw_table_position position;
1249 struct sw_flow_key match_key;
1252 rpy = buffer_put_uninit(buffer, sizeof *rpy);
1253 memset(rpy, 0, sizeof *rpy);
1255 flow_extract_match(&match_key, &rq->match);
1256 table_idx = rq->table_id == 0xff ? 0 : rq->table_id;
1257 memset(&position, 0, sizeof position);
1258 while (table_idx < dp->chain->n_tables
1259 && (rq->table_id == 0xff || rq->table_id == table_idx))
1261 struct sw_table *table = dp->chain->tables[table_idx];
1264 error = table->iterate(table, &match_key, &position,
1265 aggregate_stats_dump_callback, rpy);
1270 memset(&position, 0, sizeof position);
1273 rpy->packet_count = htonll(rpy->packet_count);
1274 rpy->byte_count = htonll(rpy->byte_count);
1275 rpy->flow_count = htonl(rpy->flow_count);
1279 static void aggregate_stats_done(void *state)
1284 static int table_stats_dump(struct datapath *dp, void *state,
1285 struct buffer *buffer)
1288 for (i = 0; i < dp->chain->n_tables; i++) {
1289 struct ofp_table_stats *ots = buffer_put_uninit(buffer, sizeof *ots);
1290 struct sw_table_stats stats;
1291 dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
1292 strncpy(ots->name, stats.name, sizeof ots->name);
1294 memset(ots->pad, 0, sizeof ots->pad);
1295 ots->max_entries = htonl(stats.max_flows);
1296 ots->active_count = htonl(stats.n_flows);
1297 ots->matched_count = htonll(0); /* FIXME */
1302 struct port_stats_state {
1306 static int port_stats_init(struct datapath *dp, const void *body, int body_len,
1309 struct port_stats_state *s = xmalloc(sizeof *s);
1315 static int port_stats_dump(struct datapath *dp, void *state,
1316 struct buffer *buffer)
1318 struct port_stats_state *s = state;
1321 for (i = s->port; i < OFPP_MAX; i++) {
1322 struct sw_port *p = &dp->ports[i];
1323 struct ofp_port_stats *ops;
1327 ops = buffer_put_uninit(buffer, sizeof *ops);
1328 ops->port_no = htons(port_no(dp, p));
1329 memset(ops->pad, 0, sizeof ops->pad);
1330 ops->rx_count = htonll(p->rx_count);
1331 ops->tx_count = htonll(p->tx_count);
1332 ops->drop_count = htonll(p->drop_count);
1339 static void port_stats_done(void *state)
1345 /* Minimum and maximum acceptable number of bytes in body member of
1346 * struct ofp_stats_request. */
1347 size_t min_body, max_body;
1349 /* Prepares to dump some kind of statistics on 'dp'. 'body' and
1350 * 'body_len' are the 'body' member of the struct ofp_stats_request.
1351 * Returns zero if successful, otherwise a negative error code.
1352 * May initialize '*state' to state information. May be null if no
1353 * initialization is required.*/
1354 int (*init)(struct datapath *dp, const void *body, int body_len,
1357 /* Appends statistics for 'dp' to 'buffer', which initially contains a
1358 * struct ofp_stats_reply. On success, it should return 1 if it should be
1359 * called again later with another buffer, 0 if it is done, or a negative
1360 * errno value on failure. */
1361 int (*dump)(struct datapath *dp, void *state, struct buffer *buffer);
1363 /* Cleans any state created by the init or dump functions. May be null
1364 * if no cleanup is required. */
1365 void (*done)(void *state);
1368 static const struct stats_type stats[] = {
1370 sizeof(struct ofp_flow_stats_request),
1371 sizeof(struct ofp_flow_stats_request),
1376 [OFPST_AGGREGATE] = {
1377 sizeof(struct ofp_aggregate_stats_request),
1378 sizeof(struct ofp_aggregate_stats_request),
1379 aggregate_stats_init,
1380 aggregate_stats_dump,
1381 aggregate_stats_done
1399 struct stats_dump_cb {
1401 struct ofp_stats_request *rq;
1402 struct sender sender;
1403 const struct stats_type *s;
1408 stats_dump(struct datapath *dp, void *cb_)
1410 struct stats_dump_cb *cb = cb_;
1411 struct ofp_stats_reply *osr;
1412 struct buffer *buffer;
1419 osr = alloc_openflow_buffer(dp, sizeof *osr, OFPT_STATS_REPLY, &cb->sender,
1421 osr->type = htons(cb->s - stats);
1424 err = cb->s->dump(dp, cb->state, buffer);
1430 /* Buffer might have been reallocated, so find our data again. */
1431 osr = buffer_at_assert(buffer, 0, sizeof *osr);
1432 osr->flags = ntohs(OFPSF_REPLY_MORE);
1434 err2 = send_openflow_buffer(dp, buffer, &cb->sender);
1444 stats_done(void *cb_)
1446 struct stats_dump_cb *cb = cb_;
1449 cb->s->done(cb->state);
1456 recv_stats_request(struct datapath *dp, const struct sender *sender,
1459 const struct ofp_stats_request *rq = oh;
1460 size_t rq_len = ntohs(rq->header.length);
1461 struct stats_dump_cb *cb;
1465 type = ntohs(rq->type);
1466 if (type >= ARRAY_SIZE(stats) || !stats[type].dump) {
1467 VLOG_WARN("received stats request of unknown type %d", type);
1471 cb = xmalloc(sizeof *cb);
1473 cb->rq = xmemdup(rq, rq_len);
1474 cb->sender = *sender;
1475 cb->s = &stats[type];
1478 body_len = rq_len - offsetof(struct ofp_stats_request, body);
1479 if (body_len < cb->s->min_body || body_len > cb->s->max_body) {
1480 VLOG_WARN("stats request type %d with bad body length %d",
1487 err = cb->s->init(dp, rq->body, body_len, &cb->state);
1489 VLOG_WARN("failed initialization of stats request type %d: %s",
1490 type, strerror(-err));
1495 remote_start_dump(sender->remote, stats_dump, stats_done, cb);
1504 /* 'msg', which is 'length' bytes long, was received from the control path.
1505 * Apply it to 'chain'. */
1507 fwd_control_input(struct datapath *dp, const struct sender *sender,
1508 const void *msg, size_t length)
1510 struct openflow_packet {
1512 int (*handler)(struct datapath *, const struct sender *, const void *);
1515 static const struct openflow_packet packets[] = {
1516 [OFPT_FEATURES_REQUEST] = {
1517 sizeof (struct ofp_header),
1518 recv_features_request,
1520 [OFPT_GET_CONFIG_REQUEST] = {
1521 sizeof (struct ofp_header),
1522 recv_get_config_request,
1524 [OFPT_SET_CONFIG] = {
1525 sizeof (struct ofp_switch_config),
1528 [OFPT_PACKET_OUT] = {
1529 sizeof (struct ofp_packet_out),
1533 sizeof (struct ofp_flow_mod),
1537 sizeof (struct ofp_port_mod),
1540 [OFPT_STATS_REQUEST] = {
1541 sizeof (struct ofp_stats_request),
1546 const struct openflow_packet *pkt;
1547 struct ofp_header *oh;
1549 oh = (struct ofp_header *) msg;
1550 if (oh->version != OFP_VERSION || oh->type >= ARRAY_SIZE(packets)
1551 || ntohs(oh->length) > length)
1554 pkt = &packets[oh->type];
1557 if (length < pkt->min_size)
1560 return pkt->handler(dp, sender, msg);
1563 /* Packet buffering. */
1565 #define OVERWRITE_SECS 1
1567 struct packet_buffer {
1568 struct buffer *buffer;
1573 static struct packet_buffer buffers[N_PKT_BUFFERS];
1574 static unsigned int buffer_idx;
1576 uint32_t save_buffer(struct buffer *buffer)
1578 struct packet_buffer *p;
1581 buffer_idx = (buffer_idx + 1) & PKT_BUFFER_MASK;
1582 p = &buffers[buffer_idx];
1584 /* Don't buffer packet if existing entry is less than
1585 * OVERWRITE_SECS old. */
1586 if (time(0) < p->timeout) { /* FIXME */
1589 buffer_delete(p->buffer);
1592 /* Don't use maximum cookie value since the all-bits-1 id is
1594 if (++p->cookie >= (1u << PKT_COOKIE_BITS) - 1)
1596 p->buffer = buffer_clone(buffer); /* FIXME */
1597 p->timeout = time(0) + OVERWRITE_SECS; /* FIXME */
1598 id = buffer_idx | (p->cookie << PKT_BUFFER_BITS);
1603 static struct buffer *retrieve_buffer(uint32_t id)
1605 struct buffer *buffer = NULL;
1606 struct packet_buffer *p;
1608 p = &buffers[id & PKT_BUFFER_MASK];
1609 if (p->cookie == id >> PKT_BUFFER_BITS) {
1613 printf("cookie mismatch: %x != %x\n",
1614 id >> PKT_BUFFER_BITS, p->cookie);
1620 static void discard_buffer(uint32_t id)
1622 struct packet_buffer *p;
1624 p = &buffers[id & PKT_BUFFER_MASK];
1625 if (p->cookie == id >> PKT_BUFFER_BITS) {
1626 buffer_delete(p->buffer);