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>
45 #include "poll-loop.h"
51 #define THIS_MODULE VLM_datapath
54 #define BRIDGE_PORT_NO_FLOOD 0x00000001
56 /* Capabilities supported by this implementation. */
57 #define OFP_SUPPORTED_CAPABILITIES (OFPC_MULTI_PHY_TX)
59 /* Actions supported by this implementation. */
60 #define OFP_SUPPORTED_ACTIONS ( (1 << OFPAT_OUTPUT) \
61 | (1 << OFPAT_SET_DL_VLAN) \
62 | (1 << OFPAT_SET_DL_SRC) \
63 | (1 << OFPAT_SET_DL_DST) \
64 | (1 << OFPAT_SET_NW_SRC) \
65 | (1 << OFPAT_SET_NW_DST) \
66 | (1 << OFPAT_SET_TP_SRC) \
67 | (1 << OFPAT_SET_TP_DST) )
72 struct netdev *netdev;
73 struct list node; /* Element in datapath.ports. */
74 unsigned long long int rx_count, tx_count, drop_count;
77 /* A connection to a controller or a management device. */
83 /* The origin of a received OpenFlow message, to enable sending a reply. */
85 struct remote *remote; /* The device that sent the message. */
86 uint32_t xid; /* The OpenFlow transaction ID. */
90 /* Remote connections. */
91 struct remote *controller; /* Connection to controller. */
92 struct list remotes; /* All connections (including controller). */
93 struct vconn *listen_vconn;
97 /* Unique identifier for this datapath */
100 struct sw_chain *chain; /* Forwarding rules. */
102 struct ofp_switch_config config;
105 struct sw_port ports[OFPP_MAX];
106 struct list port_list; /* List of ports, for flooding. */
109 static struct remote *remote_create(struct datapath *, struct rconn *);
110 static void remote_run(struct datapath *, struct remote *);
111 static void remote_wait(struct remote *);
112 static void remote_destroy(struct remote *);
114 void dp_output_port(struct datapath *, struct buffer *,
115 int in_port, int out_port);
116 void dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp);
117 void dp_output_control(struct datapath *, struct buffer *, int in_port,
118 size_t max_len, int reason);
119 static void send_flow_expired(struct datapath *, struct sw_flow *);
120 static void send_port_status(struct sw_port *p, uint8_t status);
121 static void del_switch_port(struct sw_port *p);
122 static void execute_actions(struct datapath *, struct buffer *,
123 int in_port, const struct sw_flow_key *,
124 const struct ofp_action *, int n_actions);
125 static void modify_vlan(struct buffer *buffer, const struct sw_flow_key *key,
126 const struct ofp_action *a);
127 static void modify_nh(struct buffer *buffer, uint16_t eth_proto,
128 uint8_t nw_proto, const struct ofp_action *a);
129 static void modify_th(struct buffer *buffer, uint16_t eth_proto,
130 uint8_t nw_proto, const struct ofp_action *a);
132 /* Buffers are identified to userspace by a 31-bit opaque ID. We divide the ID
133 * into a buffer number (low bits) and a cookie (high bits). The buffer number
134 * is an index into an array of buffers. The cookie distinguishes between
135 * different packets that have occupied a single buffer. Thus, the more
136 * buffers we have, the lower-quality the cookie... */
137 #define PKT_BUFFER_BITS 8
138 #define N_PKT_BUFFERS (1 << PKT_BUFFER_BITS)
139 #define PKT_BUFFER_MASK (N_PKT_BUFFERS - 1)
141 #define PKT_COOKIE_BITS (32 - PKT_BUFFER_BITS)
143 void fwd_port_input(struct datapath *, struct buffer *, int in_port);
144 int fwd_control_input(struct datapath *, const struct sender *,
145 const void *, size_t);
147 uint32_t save_buffer(struct buffer *);
148 static struct buffer *retrieve_buffer(uint32_t id);
149 static void discard_buffer(uint32_t id);
151 static int port_no(struct datapath *dp, struct sw_port *p)
153 assert(p >= dp->ports && p < &dp->ports[ARRAY_SIZE(dp->ports)]);
154 return p - dp->ports;
157 /* Generates a unique datapath id. It incorporates the datapath index
158 * and a hardware address, if available. If not, it generates a random
162 gen_datapath_id(void)
164 /* Choose a random datapath id. */
170 for (i = 0; i < ETH_ADDR_LEN; i++) {
171 id |= (uint64_t)(rand() & 0xff) << (8*(ETH_ADDR_LEN-1 - i));
178 dp_new(struct datapath **dp_, uint64_t dpid, struct rconn *rconn)
182 dp = calloc(1, sizeof *dp);
187 dp->last_timeout = time(0);
188 list_init(&dp->remotes);
189 dp->controller = remote_create(dp, rconn);
190 dp->listen_vconn = NULL;
191 dp->id = dpid <= UINT64_C(0xffffffffffff) ? dpid : gen_datapath_id();
192 dp->chain = chain_create();
194 VLOG_ERR("could not create chain");
199 list_init(&dp->port_list);
200 dp->config.flags = 0;
201 dp->config.miss_send_len = htons(OFP_DEFAULT_MISS_SEND_LEN);
207 dp_add_port(struct datapath *dp, const char *name)
209 struct netdev *netdev;
213 error = netdev_open(name, &netdev);
218 for (p = dp->ports; ; p++) {
219 if (p >= &dp->ports[ARRAY_SIZE(dp->ports)]) {
221 } else if (!p->netdev) {
231 list_push_back(&dp->port_list, &p->node);
233 /* Notify the ctlpath that this port has been added */
234 send_port_status(p, OFPPR_ADD);
240 dp_add_listen_vconn(struct datapath *dp, struct vconn *listen_vconn)
242 assert(!dp->listen_vconn);
243 dp->listen_vconn = listen_vconn;
247 dp_run(struct datapath *dp)
249 time_t now = time(0);
250 struct sw_port *p, *pn;
251 struct remote *r, *rn;
252 struct buffer *buffer = NULL;
254 if (now != dp->last_timeout) {
255 struct list deleted = LIST_INITIALIZER(&deleted);
256 struct sw_flow *f, *n;
258 chain_timeout(dp->chain, &deleted);
259 LIST_FOR_EACH_SAFE (f, n, struct sw_flow, node, &deleted) {
260 send_flow_expired(dp, f);
261 list_remove(&f->node);
264 dp->last_timeout = now;
266 poll_timer_wait(1000);
268 LIST_FOR_EACH_SAFE (p, pn, struct sw_port, node, &dp->port_list) {
272 /* Allocate buffer with some headroom to add headers in forwarding
273 * to the controller or adding a vlan tag, plus an extra 2 bytes to
274 * allow IP headers to be aligned on a 4-byte boundary. */
275 const int headroom = 128 + 2;
276 const int hard_header = VLAN_ETH_HEADER_LEN;
277 const int mtu = netdev_get_mtu(p->netdev);
278 buffer = buffer_new(headroom + hard_header + mtu);
279 buffer->data += headroom;
281 error = netdev_recv(p->netdev, buffer);
284 fwd_port_input(dp, buffer, port_no(dp, p));
286 } else if (error != EAGAIN) {
287 VLOG_ERR("Error receiving data from %s: %s",
288 netdev_get_name(p->netdev), strerror(error));
292 buffer_delete(buffer);
294 /* Talk to remotes. */
295 LIST_FOR_EACH_SAFE (r, rn, struct remote, node, &dp->remotes) {
298 if (dp->listen_vconn) {
300 struct vconn *new_vconn;
303 retval = vconn_accept(dp->listen_vconn, &new_vconn);
305 if (retval != EAGAIN) {
306 VLOG_WARN("accept failed (%s)", strerror(retval));
310 remote_create(dp, rconn_new_from_vconn("passive", 128, new_vconn));
316 remote_run(struct datapath *dp, struct remote *r)
322 /* Process a number of commands from the remote, but cap them at a
323 * reasonable number so that other processing doesn't starve. */
324 for (i = 0; i < 50; i++) {
325 struct buffer *buffer;
326 struct ofp_header *oh;
328 buffer = rconn_recv(r->rconn);
333 if (buffer->size >= sizeof *oh) {
334 struct sender sender;
338 sender.xid = oh->xid;
339 fwd_control_input(dp, &sender, buffer->data, buffer->size);
341 VLOG_WARN("received too-short OpenFlow message");
343 buffer_delete(buffer);
346 if (!rconn_is_alive(r->rconn)) {
352 remote_wait(struct remote *r)
354 rconn_run_wait(r->rconn);
355 rconn_recv_wait(r->rconn);
359 remote_destroy(struct remote *r)
362 list_remove(&r->node);
363 rconn_destroy(r->rconn);
368 static struct remote *
369 remote_create(struct datapath *dp, struct rconn *rconn)
371 struct remote *remote = xmalloc(sizeof *remote);
372 list_push_back(&dp->remotes, &remote->node);
373 remote->rconn = rconn;
378 dp_wait(struct datapath *dp)
383 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
384 netdev_recv_wait(p->netdev);
386 LIST_FOR_EACH (r, struct remote, node, &dp->remotes) {
389 if (dp->listen_vconn) {
390 vconn_accept_wait(dp->listen_vconn);
394 /* Delete 'p' from switch. */
396 del_switch_port(struct sw_port *p)
398 send_port_status(p, OFPPR_DELETE);
399 netdev_close(p->netdev);
401 list_remove(&p->node);
405 dp_destroy(struct datapath *dp)
407 struct sw_port *p, *n;
413 LIST_FOR_EACH_SAFE (p, n, struct sw_port, node, &dp->port_list) {
416 chain_destroy(dp->chain);
421 flood(struct datapath *dp, struct buffer *buffer, int in_port)
427 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
428 if (port_no(dp, p) == in_port || p->flags & BRIDGE_PORT_NO_FLOOD) {
431 if (prev_port != -1) {
432 dp_output_port(dp, buffer_clone(buffer), in_port, prev_port);
434 prev_port = port_no(dp, p);
437 dp_output_port(dp, buffer, in_port, prev_port);
439 buffer_delete(buffer);
445 output_packet(struct datapath *dp, struct buffer *buffer, int out_port)
447 if (out_port >= 0 && out_port < OFPP_MAX) {
448 struct sw_port *p = &dp->ports[out_port];
449 if (p->netdev != NULL) {
450 if (!netdev_send(p->netdev, buffer)) {
459 buffer_delete(buffer);
460 /* FIXME: ratelimit */
461 VLOG_DBG("can't forward to bad port %d\n", out_port);
464 /* Takes ownership of 'buffer' and transmits it to 'out_port' on 'dp'.
467 dp_output_port(struct datapath *dp, struct buffer *buffer,
468 int in_port, int out_port)
472 if (out_port == OFPP_FLOOD) {
473 flood(dp, buffer, in_port);
474 } else if (out_port == OFPP_CONTROLLER) {
475 dp_output_control(dp, buffer, in_port, 0, OFPR_ACTION);
476 } else if (out_port == OFPP_TABLE) {
477 struct sw_flow_key key;
478 struct sw_flow *flow;
481 flow_extract(buffer, in_port, &key.flow);
482 flow = chain_lookup(dp->chain, &key);
484 flow_used(flow, buffer);
485 execute_actions(dp, buffer, in_port, &key,
486 flow->actions, flow->n_actions);
489 output_packet(dp, buffer, out_port);
494 alloc_openflow_buffer(struct datapath *dp, size_t openflow_len, uint8_t type,
495 const struct sender *sender, struct buffer **bufferp)
497 struct buffer *buffer;
498 struct ofp_header *oh;
500 buffer = *bufferp = buffer_new(openflow_len);
501 oh = buffer_put_uninit(buffer, openflow_len);
502 oh->version = OFP_VERSION;
504 oh->length = 0; /* Filled in by send_openflow_buffer(). */
505 oh->xid = sender ? sender->xid : 0;
510 send_openflow_buffer(struct datapath *dp, struct buffer *buffer,
511 const struct sender *sender)
513 struct remote *remote = sender ? sender->remote : dp->controller;
514 struct rconn *rconn = remote->rconn;
515 struct ofp_header *oh;
518 oh = buffer_at_assert(buffer, 0, sizeof *oh);
519 oh->length = htons(buffer->size);
521 retval = rconn_send(rconn, buffer);
523 VLOG_WARN("send to %s failed: %s",
524 rconn_get_name(rconn), strerror(retval));
525 buffer_delete(buffer);
530 /* Takes ownership of 'buffer' and transmits it to 'dp''s controller. If the
531 * packet can be saved in a buffer, then only the first max_len bytes of
532 * 'buffer' are sent; otherwise, all of 'buffer' is sent. 'reason' indicates
533 * why 'buffer' is being sent. 'max_len' sets the maximum number of bytes that
534 * the caller wants to be sent; a value of 0 indicates the entire packet should
537 dp_output_control(struct datapath *dp, struct buffer *buffer, int in_port,
538 size_t max_len, int reason)
540 struct ofp_packet_in *opi;
544 buffer_id = save_buffer(buffer);
545 total_len = buffer->size;
546 if (buffer_id != UINT32_MAX && buffer->size > max_len) {
547 buffer->size = max_len;
550 opi = buffer_push_uninit(buffer, offsetof(struct ofp_packet_in, data));
551 opi->header.version = OFP_VERSION;
552 opi->header.type = OFPT_PACKET_IN;
553 opi->header.length = htons(buffer->size);
554 opi->header.xid = htonl(0);
555 opi->buffer_id = htonl(buffer_id);
556 opi->total_len = htons(total_len);
557 opi->in_port = htons(in_port);
558 opi->reason = reason;
560 send_openflow_buffer(dp, buffer, NULL);
563 static void fill_port_desc(struct datapath *dp, struct sw_port *p,
564 struct ofp_phy_port *desc)
566 desc->port_no = htons(port_no(dp, p));
567 strncpy((char *) desc->name, netdev_get_name(p->netdev),
569 desc->name[sizeof desc->name - 1] = '\0';
570 memcpy(desc->hw_addr, netdev_get_etheraddr(p->netdev), ETH_ADDR_LEN);
571 desc->flags = htonl(p->flags);
572 desc->features = htonl(netdev_get_features(p->netdev));
573 desc->speed = htonl(netdev_get_speed(p->netdev));
577 dp_send_features_reply(struct datapath *dp, const struct sender *sender)
579 struct buffer *buffer;
580 struct ofp_switch_features *ofr;
583 ofr = alloc_openflow_buffer(dp, sizeof *ofr, OFPT_FEATURES_REPLY,
585 ofr->datapath_id = htonll(dp->id);
586 ofr->n_exact = htonl(2 * TABLE_HASH_MAX_FLOWS);
587 ofr->n_compression = 0; /* Not supported */
588 ofr->n_general = htonl(TABLE_LINEAR_MAX_FLOWS);
589 ofr->buffer_mb = htonl(UINT32_MAX);
590 ofr->n_buffers = htonl(N_PKT_BUFFERS);
591 ofr->capabilities = htonl(OFP_SUPPORTED_CAPABILITIES);
592 ofr->actions = htonl(OFP_SUPPORTED_ACTIONS);
593 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
594 struct ofp_phy_port *opp = buffer_put_uninit(buffer, sizeof *opp);
595 memset(opp, 0, sizeof *opp);
596 fill_port_desc(dp, p, opp);
598 send_openflow_buffer(dp, buffer, sender);
602 dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp)
606 p = &dp->ports[htons(opp->port_no)];
608 /* Make sure the port id hasn't changed since this was sent */
609 if (!p || memcmp(opp->hw_addr, netdev_get_etheraddr(p->netdev),
613 p->flags = htonl(opp->flags);
617 send_port_status(struct sw_port *p, uint8_t status)
619 struct buffer *buffer;
620 struct ofp_port_status *ops;
621 ops = alloc_openflow_buffer(p->dp, sizeof *ops, OFPT_PORT_STATUS, NULL,
623 ops->reason = status;
624 fill_port_desc(p->dp, p, &ops->desc);
625 send_openflow_buffer(p->dp, buffer, NULL);
629 send_flow_expired(struct datapath *dp, struct sw_flow *flow)
631 struct buffer *buffer;
632 struct ofp_flow_expired *ofe;
633 ofe = alloc_openflow_buffer(dp, sizeof *ofe, OFPT_FLOW_EXPIRED, NULL,
635 flow_fill_match(&ofe->match, &flow->key);
636 ofe->duration = htonl(flow->timeout - flow->max_idle - flow->created);
637 ofe->packet_count = htonll(flow->packet_count);
638 ofe->byte_count = htonll(flow->byte_count);
639 send_openflow_buffer(dp, buffer, NULL);
643 dp_send_error_msg(struct datapath *dp, const struct sender *sender,
644 uint16_t type, uint16_t code, const uint8_t *data, size_t len)
646 struct buffer *buffer;
647 struct ofp_error_msg *oem;
648 oem = alloc_openflow_buffer(dp, sizeof(*oem)+len, OFPT_ERROR_MSG,
650 oem->type = htons(type);
651 oem->code = htons(code);
652 memcpy(oem->data, data, len);
653 send_openflow_buffer(dp, buffer, sender);
657 fill_flow_stats(struct ofp_flow_stats *ofs, struct sw_flow *flow,
658 int table_idx, time_t now)
660 ofs->match.wildcards = htons(flow->key.wildcards);
661 ofs->match.in_port = flow->key.flow.in_port;
662 memcpy(ofs->match.dl_src, flow->key.flow.dl_src, ETH_ADDR_LEN);
663 memcpy(ofs->match.dl_dst, flow->key.flow.dl_dst, ETH_ADDR_LEN);
664 ofs->match.dl_vlan = flow->key.flow.dl_vlan;
665 ofs->match.dl_type = flow->key.flow.dl_type;
666 ofs->match.nw_src = flow->key.flow.nw_src;
667 ofs->match.nw_dst = flow->key.flow.nw_dst;
668 ofs->match.nw_proto = flow->key.flow.nw_proto;
669 memset(ofs->match.pad, 0, sizeof ofs->match.pad);
670 ofs->match.tp_src = flow->key.flow.tp_src;
671 ofs->match.tp_dst = flow->key.flow.tp_dst;
672 ofs->duration = htonl(now - flow->created);
673 ofs->priority = htons(flow->priority);
674 ofs->table_id = table_idx;
675 ofs->packet_count = htonll(flow->packet_count);
676 ofs->byte_count = htonll(flow->byte_count);
680 dp_send_flow_stats(struct datapath *dp, const struct sender *sender,
681 const struct ofp_match *match)
683 struct buffer *buffer;
684 struct ofp_flow_stats_reply *fsr;
685 size_t header_size, fudge, flow_size;
686 struct sw_flow_key match_key;
687 int table_idx, n_flows, max_flows;
690 header_size = offsetof(struct ofp_flow_stats_reply, flows);
692 flow_size = sizeof fsr->flows[0];
693 max_flows = (65536 - header_size - fudge) / flow_size;
694 fsr = alloc_openflow_buffer(dp, header_size,
695 OFPT_FLOW_STATS_REPLY, sender, &buffer);
698 flow_extract_match(&match_key, match);
700 for (table_idx = 0; table_idx < dp->chain->n_tables; table_idx++) {
701 struct sw_table *table = dp->chain->tables[table_idx];
702 struct swt_iterator iter;
704 if (n_flows >= max_flows) {
708 if (!table->iterator(table, &iter)) {
709 printf("iterator failed for table %d\n", table_idx);
713 for (; iter.flow; table->iterator_next(&iter)) {
714 if (flow_matches(&match_key, &iter.flow->key)) {
715 struct ofp_flow_stats *ofs = buffer_put_uninit(buffer,
717 fill_flow_stats(ofs, iter.flow, table_idx, now);
718 if (++n_flows >= max_flows) {
723 table->iterator_destroy(&iter);
725 return send_openflow_buffer(dp, buffer, sender);
729 dp_send_port_stats(struct datapath *dp, const struct sender *sender)
731 struct buffer *buffer;
732 struct ofp_port_stats_reply *psr;
735 psr = alloc_openflow_buffer(dp, offsetof(struct ofp_port_stats_reply,
737 OFPT_PORT_STATS_REPLY, sender, &buffer);
738 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
739 struct ofp_port_stats *ps = buffer_put_uninit(buffer, sizeof *ps);
740 ps->port_no = htons(port_no(dp, p));
741 memset(ps->pad, 0, sizeof ps->pad);
742 ps->rx_count = htonll(p->rx_count);
743 ps->tx_count = htonll(p->tx_count);
744 ps->drop_count = htonll(p->drop_count);
746 return send_openflow_buffer(dp, buffer, sender);
750 dp_send_table_stats(struct datapath *dp, const struct sender *sender)
752 struct buffer *buffer;
753 struct ofp_table_stats_reply *tsr;
756 tsr = alloc_openflow_buffer(dp, offsetof(struct ofp_table_stats_reply,
758 OFPT_TABLE_STATS_REPLY, sender, &buffer);
759 for (i = 0; i < dp->chain->n_tables; i++) {
760 struct ofp_table_stats *ots = buffer_put_uninit(buffer, sizeof *ots);
761 struct sw_table_stats stats;
762 dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
763 strncpy(ots->name, stats.name, sizeof ots->name);
765 ots->pad[0] = ots->pad[1] = 0;
766 ots->max_entries = htonl(stats.max_flows);
767 ots->active_count = htonl(stats.n_flows);
768 ots->matched_count = htonll(0); /* FIXME */
770 return send_openflow_buffer(dp, buffer, sender);
773 /* 'buffer' was received on 'in_port', a physical switch port between 0 and
774 * OFPP_MAX. Process it according to 'chain'. */
775 void fwd_port_input(struct datapath *dp, struct buffer *buffer, int in_port)
777 struct sw_flow_key key;
778 struct sw_flow *flow;
781 flow_extract(buffer, in_port, &key.flow);
782 flow = chain_lookup(dp->chain, &key);
784 flow_used(flow, buffer);
785 execute_actions(dp, buffer, in_port, &key,
786 flow->actions, flow->n_actions);
788 dp_output_control(dp, buffer, in_port, ntohs(dp->config.miss_send_len),
794 do_output(struct datapath *dp, struct buffer *buffer, int in_port,
795 size_t max_len, int out_port)
797 if (out_port != OFPP_CONTROLLER) {
798 dp_output_port(dp, buffer, in_port, out_port);
800 dp_output_control(dp, buffer, in_port, max_len, OFPR_ACTION);
805 execute_actions(struct datapath *dp, struct buffer *buffer,
806 int in_port, const struct sw_flow_key *key,
807 const struct ofp_action *actions, int n_actions)
809 /* Every output action needs a separate clone of 'buffer', but the common
810 * case is just a single output action, so that doing a clone and then
811 * freeing the original buffer is wasteful. So the following code is
812 * slightly obscure just to avoid that. */
814 size_t max_len=0; /* Initialze to make compiler happy */
819 eth_proto = ntohs(key->flow.dl_type);
821 for (i = 0; i < n_actions; i++) {
822 const struct ofp_action *a = &actions[i];
823 struct eth_header *eh = buffer->l2;
825 if (prev_port != -1) {
826 do_output(dp, buffer_clone(buffer), in_port, max_len, prev_port);
830 switch (ntohs(a->type)) {
832 prev_port = ntohs(a->arg.output.port);
833 max_len = ntohs(a->arg.output.max_len);
836 case OFPAT_SET_DL_VLAN:
837 modify_vlan(buffer, key, a);
840 case OFPAT_SET_DL_SRC:
841 memcpy(eh->eth_src, a->arg.dl_addr, sizeof eh->eth_src);
844 case OFPAT_SET_DL_DST:
845 memcpy(eh->eth_dst, a->arg.dl_addr, sizeof eh->eth_dst);
848 case OFPAT_SET_NW_SRC:
849 case OFPAT_SET_NW_DST:
850 modify_nh(buffer, eth_proto, key->flow.nw_proto, a);
853 case OFPAT_SET_TP_SRC:
854 case OFPAT_SET_TP_DST:
855 modify_th(buffer, eth_proto, key->flow.nw_proto, a);
863 do_output(dp, buffer, in_port, max_len, prev_port);
865 buffer_delete(buffer);
868 /* Returns the new checksum for a packet in which the checksum field previously
869 * contained 'old_csum' and in which a field that contained 'old_u16' was
870 * changed to contain 'new_u16'. */
872 recalc_csum16(uint16_t old_csum, uint16_t old_u16, uint16_t new_u16)
874 /* Ones-complement arithmetic is endian-independent, so this code does not
875 * use htons() or ntohs().
877 * See RFC 1624 for formula and explanation. */
878 uint16_t hc_complement = ~old_csum;
879 uint16_t m_complement = ~old_u16;
880 uint16_t m_prime = new_u16;
881 uint32_t sum = hc_complement + m_complement + m_prime;
882 uint16_t hc_prime_complement = sum + (sum >> 16);
883 return ~hc_prime_complement;
886 /* Returns the new checksum for a packet in which the checksum field previously
887 * contained 'old_csum' and in which a field that contained 'old_u32' was
888 * changed to contain 'new_u32'. */
890 recalc_csum32(uint16_t old_csum, uint32_t old_u32, uint32_t new_u32)
892 return recalc_csum16(recalc_csum16(old_csum, old_u32, new_u32),
893 old_u32 >> 16, new_u32 >> 16);
896 static void modify_nh(struct buffer *buffer, uint16_t eth_proto,
897 uint8_t nw_proto, const struct ofp_action *a)
899 if (eth_proto == ETH_TYPE_IP) {
900 struct ip_header *nh = buffer->l3;
901 uint32_t new, *field;
903 new = a->arg.nw_addr;
904 field = a->type == OFPAT_SET_NW_SRC ? &nh->ip_src : &nh->ip_dst;
905 if (nw_proto == IP_TYPE_TCP) {
906 struct tcp_header *th = buffer->l4;
907 th->tcp_csum = recalc_csum32(th->tcp_csum, *field, new);
908 } else if (nw_proto == IP_TYPE_UDP) {
909 struct udp_header *th = buffer->l4;
911 th->udp_csum = recalc_csum32(th->udp_csum, *field, new);
913 th->udp_csum = 0xffff;
917 nh->ip_csum = recalc_csum32(nh->ip_csum, *field, new);
922 static void modify_th(struct buffer *buffer, uint16_t eth_proto,
923 uint8_t nw_proto, const struct ofp_action *a)
925 if (eth_proto == ETH_TYPE_IP) {
926 uint16_t new, *field;
930 if (nw_proto == IP_TYPE_TCP) {
931 struct tcp_header *th = buffer->l4;
932 field = a->type == OFPAT_SET_TP_SRC ? &th->tcp_src : &th->tcp_dst;
933 th->tcp_csum = recalc_csum16(th->tcp_csum, *field, new);
935 } else if (nw_proto == IP_TYPE_UDP) {
936 struct udp_header *th = buffer->l4;
937 field = a->type == OFPAT_SET_TP_SRC ? &th->udp_src : &th->udp_dst;
938 th->udp_csum = recalc_csum16(th->udp_csum, *field, new);
945 modify_vlan(struct buffer *buffer,
946 const struct sw_flow_key *key, const struct ofp_action *a)
948 uint16_t new_id = a->arg.vlan_id;
949 struct vlan_eth_header *veh;
951 if (new_id != OFP_VLAN_NONE) {
952 if (key->flow.dl_vlan != htons(OFP_VLAN_NONE)) {
953 /* Modify vlan id, but maintain other TCI values */
955 veh->veth_tci &= ~htons(VLAN_VID);
956 veh->veth_tci |= htons(new_id);
958 /* Insert new vlan id. */
959 struct eth_header *eh = buffer->l2;
960 struct vlan_eth_header tmp;
961 memcpy(tmp.veth_dst, eh->eth_dst, ETH_ADDR_LEN);
962 memcpy(tmp.veth_src, eh->eth_src, ETH_ADDR_LEN);
963 tmp.veth_type = htons(ETH_TYPE_VLAN);
964 tmp.veth_tci = new_id;
965 tmp.veth_next_type = eh->eth_type;
967 veh = buffer_push_uninit(buffer, VLAN_HEADER_LEN);
968 memcpy(veh, &tmp, sizeof tmp);
969 buffer->l2 -= VLAN_HEADER_LEN;
972 /* Remove an existing vlan header if it exists */
974 if (veh->veth_type == htons(ETH_TYPE_VLAN)) {
975 struct eth_header tmp;
977 memcpy(tmp.eth_dst, veh->veth_dst, ETH_ADDR_LEN);
978 memcpy(tmp.eth_src, veh->veth_src, ETH_ADDR_LEN);
979 tmp.eth_type = veh->veth_next_type;
981 buffer->size -= VLAN_HEADER_LEN;
982 buffer->data += VLAN_HEADER_LEN;
983 buffer->l2 += VLAN_HEADER_LEN;
984 memcpy(buffer->data, &tmp, sizeof tmp);
990 recv_features_request(struct datapath *dp, const struct sender *sender,
993 dp_send_features_reply(dp, sender);
998 recv_get_config_request(struct datapath *dp, const struct sender *sender,
1001 struct buffer *buffer;
1002 struct ofp_switch_config *osc;
1004 osc = alloc_openflow_buffer(dp, sizeof *osc, OFPT_GET_CONFIG_REPLY,
1007 assert(sizeof *osc == sizeof dp->config);
1008 memcpy(((char *)osc) + sizeof osc->header,
1009 ((char *)&dp->config) + sizeof dp->config.header,
1010 sizeof dp->config - sizeof dp->config.header);
1012 return send_openflow_buffer(dp, buffer, sender);
1016 recv_set_config(struct datapath *dp, const struct sender *sender UNUSED,
1019 const struct ofp_switch_config *osc = msg;
1025 recv_packet_out(struct datapath *dp, const struct sender *sender UNUSED,
1028 const struct ofp_packet_out *opo = msg;
1030 if (ntohl(opo->buffer_id) == (uint32_t) -1) {
1031 /* FIXME: can we avoid copying data here? */
1032 int data_len = ntohs(opo->header.length) - sizeof *opo;
1033 struct buffer *buffer = buffer_new(data_len);
1034 buffer_put(buffer, opo->u.data, data_len);
1035 dp_output_port(dp, buffer,
1036 ntohs(opo->in_port), ntohs(opo->out_port));
1038 struct sw_flow_key key;
1039 struct buffer *buffer;
1042 buffer = retrieve_buffer(ntohl(opo->buffer_id));
1047 n_acts = (ntohs(opo->header.length) - sizeof *opo)
1048 / sizeof *opo->u.actions;
1049 flow_extract(buffer, ntohs(opo->in_port), &key.flow);
1050 execute_actions(dp, buffer, ntohs(opo->in_port),
1051 &key, opo->u.actions, n_acts);
1057 recv_port_mod(struct datapath *dp, const struct sender *sender UNUSED,
1060 const struct ofp_port_mod *opm = msg;
1062 dp_update_port_flags(dp, &opm->desc);
1068 add_flow(struct datapath *dp, const struct ofp_flow_mod *ofm)
1070 int error = -ENOMEM;
1073 struct sw_flow *flow;
1076 /* Check number of actions. */
1077 n_acts = (ntohs(ofm->header.length) - sizeof *ofm) / sizeof *ofm->actions;
1078 if (n_acts > MAX_ACTIONS) {
1083 /* To prevent loops, make sure there's no action to send to the
1084 * OFP_TABLE virtual port.
1086 for (i=0; i<n_acts; i++) {
1087 const struct ofp_action *a = &ofm->actions[i];
1089 if (a->type == htons(OFPAT_OUTPUT)
1090 && a->arg.output.port == htons(OFPP_TABLE)) {
1091 /* xxx Send fancy new error message? */
1096 /* Allocate memory. */
1097 flow = flow_alloc(n_acts);
1101 /* Fill out flow. */
1102 flow_extract_match(&flow->key, &ofm->match);
1103 flow->max_idle = ntohs(ofm->max_idle);
1104 flow->priority = ntohs(ofm->priority);
1105 flow->timeout = time(0) + flow->max_idle; /* FIXME */
1106 flow->n_actions = n_acts;
1107 flow->created = time(0); /* FIXME */
1108 flow->byte_count = 0;
1109 flow->packet_count = 0;
1110 memcpy(flow->actions, ofm->actions, n_acts * sizeof *flow->actions);
1113 error = chain_insert(dp->chain, flow);
1115 goto error_free_flow;
1118 if (ntohl(ofm->buffer_id) != UINT32_MAX) {
1119 struct buffer *buffer = retrieve_buffer(ntohl(ofm->buffer_id));
1121 struct sw_flow_key key;
1122 uint16_t in_port = ntohs(ofm->match.in_port);
1123 flow_used(flow, buffer);
1124 flow_extract(buffer, in_port, &key.flow);
1125 execute_actions(dp, buffer, in_port, &key, ofm->actions, n_acts);
1135 if (ntohl(ofm->buffer_id) != (uint32_t) -1)
1136 discard_buffer(ntohl(ofm->buffer_id));
1141 recv_flow(struct datapath *dp, const struct sender *sender UNUSED,
1144 const struct ofp_flow_mod *ofm = msg;
1145 uint16_t command = ntohs(ofm->command);
1147 if (command == OFPFC_ADD) {
1148 return add_flow(dp, ofm);
1149 } else if (command == OFPFC_DELETE) {
1150 struct sw_flow_key key;
1151 flow_extract_match(&key, &ofm->match);
1152 return chain_delete(dp->chain, &key, 0, 0) ? 0 : -ESRCH;
1153 } else if (command == OFPFC_DELETE_STRICT) {
1154 struct sw_flow_key key;
1155 flow_extract_match(&key, &ofm->match);
1156 return chain_delete(dp->chain, &key,
1157 ntohs(ofm->priority), 1) ? 0 : -ESRCH;
1164 recv_flow_stats_request(struct datapath *dp, const struct sender *sender,
1167 const struct ofp_flow_stats_request *fsr = msg;
1168 if (fsr->type == OFPFS_INDIV) {
1169 return dp_send_flow_stats(dp, sender, &fsr->match);
1177 recv_port_stats_request(struct datapath *dp, const struct sender *sender,
1180 return dp_send_port_stats(dp, sender);
1184 recv_table_stats_request(struct datapath *dp, const struct sender *sender,
1187 return dp_send_table_stats(dp, sender);
1190 /* 'msg', which is 'length' bytes long, was received from the control path.
1191 * Apply it to 'chain'. */
1193 fwd_control_input(struct datapath *dp, const struct sender *sender,
1194 const void *msg, size_t length)
1196 struct openflow_packet {
1198 int (*handler)(struct datapath *, const struct sender *, const void *);
1201 static const struct openflow_packet packets[] = {
1202 [OFPT_FEATURES_REQUEST] = {
1203 sizeof (struct ofp_header),
1204 recv_features_request,
1206 [OFPT_GET_CONFIG_REQUEST] = {
1207 sizeof (struct ofp_header),
1208 recv_get_config_request,
1210 [OFPT_SET_CONFIG] = {
1211 sizeof (struct ofp_switch_config),
1214 [OFPT_PACKET_OUT] = {
1215 sizeof (struct ofp_packet_out),
1219 sizeof (struct ofp_flow_mod),
1223 sizeof (struct ofp_port_mod),
1226 [OFPT_FLOW_STATS_REQUEST] = {
1227 sizeof (struct ofp_flow_stats_request),
1228 recv_flow_stats_request,
1230 [OFPT_PORT_STATS_REQUEST] = {
1231 sizeof (struct ofp_port_stats_request),
1232 recv_port_stats_request,
1234 [OFPT_TABLE_STATS_REQUEST] = {
1235 sizeof (struct ofp_table_stats_request),
1236 recv_table_stats_request,
1240 const struct openflow_packet *pkt;
1241 struct ofp_header *oh;
1243 oh = (struct ofp_header *) msg;
1244 if (oh->version != OFP_VERSION || oh->type >= ARRAY_SIZE(packets)
1245 || ntohs(oh->length) > length)
1248 pkt = &packets[oh->type];
1251 if (length < pkt->min_size)
1254 return pkt->handler(dp, sender, msg);
1257 /* Packet buffering. */
1259 #define OVERWRITE_SECS 1
1261 struct packet_buffer {
1262 struct buffer *buffer;
1267 static struct packet_buffer buffers[N_PKT_BUFFERS];
1268 static unsigned int buffer_idx;
1270 uint32_t save_buffer(struct buffer *buffer)
1272 struct packet_buffer *p;
1275 buffer_idx = (buffer_idx + 1) & PKT_BUFFER_MASK;
1276 p = &buffers[buffer_idx];
1278 /* Don't buffer packet if existing entry is less than
1279 * OVERWRITE_SECS old. */
1280 if (time(0) < p->timeout) { /* FIXME */
1283 buffer_delete(p->buffer);
1286 /* Don't use maximum cookie value since the all-bits-1 id is
1288 if (++p->cookie >= (1u << PKT_COOKIE_BITS) - 1)
1290 p->buffer = buffer_clone(buffer); /* FIXME */
1291 p->timeout = time(0) + OVERWRITE_SECS; /* FIXME */
1292 id = buffer_idx | (p->cookie << PKT_BUFFER_BITS);
1297 static struct buffer *retrieve_buffer(uint32_t id)
1299 struct buffer *buffer = NULL;
1300 struct packet_buffer *p;
1302 p = &buffers[id & PKT_BUFFER_MASK];
1303 if (p->cookie == id >> PKT_BUFFER_BITS) {
1307 printf("cookie mismatch: %x != %x\n",
1308 id >> PKT_BUFFER_BITS, p->cookie);
1314 static void discard_buffer(uint32_t id)
1316 struct packet_buffer *p;
1318 p = &buffers[id & PKT_BUFFER_MASK];
1319 if (p->cookie == id >> PKT_BUFFER_BITS) {
1320 buffer_delete(p->buffer);