Implement 802.1D Spanning Tree Protocol.
[openvswitch] / lib / learning-switch.c
1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
2  * Junior University
3  *
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:
16  *
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  *
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
27  * SOFTWARE.
28  *
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.
32  */
33
34 #include <config.h>
35 #include "learning-switch.h"
36
37 #include <errno.h>
38 #include <inttypes.h>
39 #include <netinet/in.h>
40 #include <stdlib.h>
41 #include <time.h>
42
43 #include "buffer.h"
44 #include "flow.h"
45 #include "mac-learning.h"
46 #include "ofp-print.h"
47 #include "openflow.h"
48 #include "queue.h"
49 #include "rconn.h"
50 #include "timeval.h"
51 #include "vconn.h"
52 #include "xtoxll.h"
53
54 #define THIS_MODULE VLM_learning_switch
55 #include "vlog.h"
56
57 struct lswitch {
58     /* If nonnegative, the switch sets up flows that expire after the given
59      * number of seconds (or never expire, if the value is OFP_FLOW_PERMANENT).
60      * Otherwise, the switch processes every packet. */
61     int max_idle;
62
63     uint64_t datapath_id;
64     uint32_t capabilities;
65     time_t last_features_request;
66     struct mac_learning *ml;    /* NULL to act as hub instead of switch. */
67
68     /* Number of outgoing queued packets on the rconn. */
69     int n_queued;
70 };
71
72 /* The log messages here could actually be useful in debugging, so keep the
73  * rate limit relatively high. */
74 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
75
76 static void queue_tx(struct lswitch *, struct rconn *, struct buffer *);
77 static void send_features_request(struct lswitch *, struct rconn *);
78 static void process_switch_features(struct lswitch *, struct rconn *,
79                                     struct ofp_switch_features *);
80 static void process_packet_in(struct lswitch *, struct rconn *,
81                               struct ofp_packet_in *);
82 static void process_echo_request(struct lswitch *, struct rconn *,
83                                  struct ofp_header *);
84 static void process_port_status(struct lswitch *, struct rconn *,
85                                 struct ofp_port_status *);
86 static void process_phy_port(struct lswitch *, struct rconn *,
87                              const struct ofp_phy_port *);
88
89 /* Creates and returns a new learning switch.
90  *
91  * If 'learn_macs' is true, the new switch will learn the ports on which MAC
92  * addresses appear.  Otherwise, the new switch will flood all packets.
93  *
94  * If 'max_idle' is nonnegative, the new switch will set up flows that expire
95  * after the given number of seconds (or never expire, if 'max_idle' is
96  * OFP_FLOW_PERMANENT).  Otherwise, the new switch will process every packet.
97  *
98  * 'rconn' is used to send out an OpenFlow features request. */
99 struct lswitch *
100 lswitch_create(struct rconn *rconn, bool learn_macs, int max_idle)
101 {
102     struct lswitch *sw = xcalloc(1, sizeof *sw);
103     sw->max_idle = max_idle;
104     sw->datapath_id = 0;
105     sw->last_features_request = time_now() - 1;
106     sw->ml = learn_macs ? mac_learning_create() : NULL;
107     send_features_request(sw, rconn);
108     return sw;
109 }
110
111 /* Destroys 'sw'. */
112 void
113 lswitch_destroy(struct lswitch *sw)
114 {
115     if (sw) {
116         mac_learning_destroy(sw->ml);
117         free(sw);
118     }
119 }
120
121 /* Processes 'msg', which should be an OpenFlow received on 'rconn', according
122  * to the learning switch state in 'sw'.  The most likely result of processing
123  * is that flow-setup and packet-out OpenFlow messages will be sent out on
124  * 'rconn'.  */
125 void
126 lswitch_process_packet(struct lswitch *sw, struct rconn *rconn,
127                        const struct buffer *msg)
128 {
129     static const size_t min_size[UINT8_MAX + 1] = {
130         [0 ... UINT8_MAX] = sizeof (struct ofp_header),
131         [OFPT_FEATURES_REPLY] = sizeof (struct ofp_switch_features),
132         [OFPT_PACKET_IN] = offsetof (struct ofp_packet_in, data),
133         [OFPT_PORT_STATUS] = sizeof(struct ofp_port_status),
134     };
135     struct ofp_header *oh;
136
137     oh = msg->data;
138     if (msg->size < min_size[oh->type]) {
139         VLOG_WARN_RL(&rl,
140                      "%s: too short (%zu bytes) for type %"PRIu8" (min %zu)",
141                      rconn_get_name(rconn),
142                      msg->size, oh->type, min_size[oh->type]);
143         return;
144     }
145
146     if (oh->type == OFPT_ECHO_REQUEST) {
147         process_echo_request(sw, rconn, msg->data);
148     } else if (oh->type == OFPT_FEATURES_REPLY) {
149         process_switch_features(sw, rconn, msg->data);
150     } else if (sw->datapath_id == 0) {
151         send_features_request(sw, rconn);
152     } else if (oh->type == OFPT_PACKET_IN) {
153         process_packet_in(sw, rconn, msg->data);
154     } else if (oh->type == OFPT_PORT_STATUS) {
155         process_port_status(sw, rconn, msg->data);
156     } else {
157         if (VLOG_IS_DBG_ENABLED()) {
158             char *p = ofp_to_string(msg->data, msg->size, 2);
159             VLOG_DBG_RL(&rl, "OpenFlow packet ignored: %s", p);
160             free(p);
161         }
162     }
163 }
164 \f
165 static void
166 send_features_request(struct lswitch *sw, struct rconn *rconn)
167 {
168     time_t now = time_now();
169     if (now >= sw->last_features_request + 1) {
170         struct buffer *b;
171         struct ofp_switch_config *osc;
172
173         /* Send OFPT_FEATURES_REQUEST. */
174         make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &b);
175         queue_tx(sw, rconn, b);
176
177         /* Send OFPT_SET_CONFIG. */
178         osc = make_openflow(sizeof *osc, OFPT_SET_CONFIG, &b);
179         osc->flags = htons(OFPC_SEND_FLOW_EXP);
180         osc->miss_send_len = htons(OFP_DEFAULT_MISS_SEND_LEN);
181         queue_tx(sw, rconn, b);
182
183         sw->last_features_request = now;
184     }
185 }
186
187 static void
188 queue_tx(struct lswitch *sw, struct rconn *rconn, struct buffer *b)
189 {
190     int retval = rconn_send_with_limit(rconn, b, &sw->n_queued, 10);
191     if (retval && retval != ENOTCONN) {
192         if (retval == EAGAIN) {
193             VLOG_WARN_RL(&rl, "%s: tx queue overflow", rconn_get_name(rconn));
194         } else {
195             VLOG_WARN_RL(&rl, "%s: send: %s",
196                          rconn_get_name(rconn), strerror(retval));
197         }
198     }
199 }
200
201 static void
202 process_switch_features(struct lswitch *sw, struct rconn *rconn,
203                         struct ofp_switch_features *osf)
204 {
205     size_t n_ports = ((ntohs(osf->header.length)
206                        - offsetof(struct ofp_switch_features, ports))
207                       / sizeof *osf->ports);
208     size_t i;
209
210     sw->datapath_id = osf->datapath_id;
211     sw->capabilities = ntohl(osf->capabilities);
212     for (i = 0; i < n_ports; i++) {
213         process_phy_port(sw, rconn, &osf->ports[i]);
214     }
215 }
216
217 static void
218 process_packet_in(struct lswitch *sw, struct rconn *rconn,
219                   struct ofp_packet_in *opi)
220 {
221     uint16_t in_port = ntohs(opi->in_port);
222     uint16_t out_port = OFPP_FLOOD;
223
224     size_t pkt_ofs, pkt_len;
225     struct buffer pkt;
226     struct flow flow;
227
228     /* Extract flow data from 'opi' into 'flow'. */
229     pkt_ofs = offsetof(struct ofp_packet_in, data);
230     pkt_len = ntohs(opi->header.length) - pkt_ofs;
231     pkt.data = opi->data;
232     pkt.size = pkt_len;
233     flow_extract(&pkt, in_port, &flow);
234
235     if (sw->ml) {
236         if (mac_learning_learn(sw->ml, flow.dl_src, in_port)) {
237             VLOG_DBG_RL(&rl, "learned that "ETH_ADDR_FMT" is on datapath %"
238                         PRIx64" port %"PRIu16, ETH_ADDR_ARGS(flow.dl_src),
239                         ntohll(sw->datapath_id), in_port);
240         }
241         out_port = mac_learning_lookup(sw->ml, flow.dl_dst);
242     }
243
244     if (in_port == out_port) {
245         /* The input and output port match.  Set up a flow to drop packets. */
246         queue_tx(sw, rconn, make_add_flow(&flow, ntohl(opi->buffer_id),
247                                           sw->max_idle, 0));
248     } else if (sw->max_idle >= 0 && (!sw->ml || out_port != OFPP_FLOOD)) {
249         /* The output port is known, or we always flood everything, so add a
250          * new flow. */
251         queue_tx(sw, rconn, make_add_simple_flow(&flow, ntohl(opi->buffer_id),
252                                                  out_port, sw->max_idle));
253
254         /* If the switch didn't buffer the packet, we need to send a copy. */
255         if (ntohl(opi->buffer_id) == UINT32_MAX) {
256             queue_tx(sw, rconn,
257                      make_unbuffered_packet_out(&pkt, in_port, out_port));
258         }
259     } else {
260         /* We don't know that MAC, or we don't set up flows.  Send along the
261          * packet without setting up a flow. */
262         struct buffer *b;
263         if (ntohl(opi->buffer_id) == UINT32_MAX) {
264             b = make_unbuffered_packet_out(&pkt, in_port, out_port);
265         } else {
266             b = make_buffered_packet_out(ntohl(opi->buffer_id),
267                                          in_port, out_port);
268         }
269         queue_tx(sw, rconn, b);
270     }
271 }
272
273 static void
274 process_echo_request(struct lswitch *sw, struct rconn *rconn,
275                      struct ofp_header *rq)
276 {
277     queue_tx(sw, rconn, make_echo_reply(rq));
278 }
279
280 static void
281 process_port_status(struct lswitch *sw, struct rconn *rconn,
282                     struct ofp_port_status *ops)
283 {
284     process_phy_port(sw, rconn, &ops->desc);
285 }
286
287 static void
288 process_phy_port(struct lswitch *sw, struct rconn *rconn,
289                  const struct ofp_phy_port *opp)
290 {
291     if (sw->capabilities & OFPC_STP && opp->features & ntohl(OFPPF_STP)) {
292         uint32_t flags = ntohl(opp->flags);
293         uint32_t new_flags = flags & ~(OFPPFL_NO_RECV | OFPPFL_NO_RECV_STP
294                                        | OFPPFL_NO_FWD | OFPPFL_NO_PACKET_IN);
295         if (!(flags & (OFPPFL_NO_STP | OFPPFL_PORT_DOWN | OFPPFL_LINK_DOWN))) {
296             bool forward = false;
297             bool learn = false;
298             switch (flags & OFPPFL_STP_MASK) {
299             case OFPPFL_STP_LISTEN:
300             case OFPPFL_STP_BLOCK:
301                 break;
302             case OFPPFL_STP_LEARN:
303                 learn = true;
304                 break;
305             case OFPPFL_STP_FORWARD:
306                 forward = learn = true;
307                 break;
308             }
309             if (!forward) {
310                 new_flags |= OFPPFL_NO_RECV | OFPPFL_NO_FWD;
311             }
312             if (!learn) {
313                 new_flags |= OFPPFL_NO_PACKET_IN;
314             }
315         }
316         if (flags != new_flags) {
317             struct ofp_port_mod *opm;
318             struct buffer *b;
319             int retval;
320
321             VLOG_WARN("port %d: flags=%x new_flags=%x",
322                       ntohs(opp->port_no), flags, new_flags);
323             opm = make_openflow(sizeof *opm, OFPT_PORT_MOD, &b);
324             opm->mask = htonl(flags ^ new_flags);
325             opm->desc = *opp;
326             opm->desc.flags = htonl(new_flags);
327             retval = rconn_send(rconn, b, NULL);
328             if (retval) {
329                 if (retval != ENOTCONN) {
330                     VLOG_WARN_RL(&rl, "%s: send: %s",
331                                  rconn_get_name(rconn), strerror(retval));
332                 }
333                 buffer_delete(b);
334             }
335         }
336     }
337 }