6b74f82fb1952eb5b4be1138ff37c47aa6395351
[sliver-openvswitch.git] / lib / learning-switch.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "learning-switch.h"
19
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <netinet/in.h>
23 #include <stdlib.h>
24 #include <time.h>
25
26 #include "byte-order.h"
27 #include "classifier.h"
28 #include "flow.h"
29 #include "hmap.h"
30 #include "mac-learning.h"
31 #include "ofpbuf.h"
32 #include "ofp-errors.h"
33 #include "ofp-parse.h"
34 #include "ofp-print.h"
35 #include "ofp-util.h"
36 #include "openflow/openflow.h"
37 #include "poll-loop.h"
38 #include "rconn.h"
39 #include "shash.h"
40 #include "simap.h"
41 #include "timeval.h"
42 #include "vconn.h"
43 #include "vlog.h"
44
45 VLOG_DEFINE_THIS_MODULE(learning_switch);
46
47 struct lswitch_port {
48     struct hmap_node hmap_node; /* Hash node for port number. */
49     uint16_t port_no;           /* OpenFlow port number, in host byte order. */
50     uint32_t queue_id;          /* OpenFlow queue number. */
51 };
52
53 struct lswitch {
54     /* If nonnegative, the switch sets up flows that expire after the given
55      * number of seconds (or never expire, if the value is OFP_FLOW_PERMANENT).
56      * Otherwise, the switch processes every packet. */
57     int max_idle;
58
59     unsigned long long int datapath_id;
60     time_t last_features_request;
61     struct mac_learning *ml;    /* NULL to act as hub instead of switch. */
62     struct flow_wildcards wc;   /* Wildcards to apply to flows. */
63     bool action_normal;         /* Use OFPP_NORMAL? */
64
65     /* Queue distribution. */
66     uint32_t default_queue;     /* Default OpenFlow queue, or UINT32_MAX. */
67     struct hmap queue_numbers;  /* Map from port number to lswitch_port. */
68     struct shash queue_names;   /* Map from port name to lswitch_port. */
69
70     /* Number of outgoing queued packets on the rconn. */
71     struct rconn_packet_counter *queued;
72 };
73
74 /* The log messages here could actually be useful in debugging, so keep the
75  * rate limit relatively high. */
76 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
77
78 static void queue_tx(struct lswitch *, struct rconn *, struct ofpbuf *);
79 static void send_features_request(struct lswitch *, struct rconn *);
80
81 static enum ofperr process_switch_features(struct lswitch *,
82                                            struct ofp_switch_features *);
83 static void process_packet_in(struct lswitch *, struct rconn *,
84                               const struct ofp_packet_in *);
85 static void process_echo_request(struct lswitch *, struct rconn *,
86                                  const struct ofp_header *);
87
88 /* Creates and returns a new learning switch whose configuration is given by
89  * 'cfg'.
90  *
91  * 'rconn' is used to send out an OpenFlow features request. */
92 struct lswitch *
93 lswitch_create(struct rconn *rconn, const struct lswitch_config *cfg)
94 {
95     struct lswitch *sw;
96
97     sw = xzalloc(sizeof *sw);
98     sw->max_idle = cfg->max_idle;
99     sw->datapath_id = 0;
100     sw->last_features_request = time_now() - 1;
101     sw->ml = (cfg->mode == LSW_LEARN
102               ? mac_learning_create(MAC_ENTRY_DEFAULT_IDLE_TIME)
103               : NULL);
104     sw->action_normal = cfg->mode == LSW_NORMAL;
105
106     flow_wildcards_init_exact(&sw->wc);
107     if (cfg->wildcards) {
108         uint32_t ofpfw;
109
110         if (cfg->wildcards == UINT32_MAX) {
111             /* Try to wildcard as many fields as possible, but we cannot
112              * wildcard all fields.  We need in_port to detect moves.  We need
113              * Ethernet source and dest and VLAN VID to do L2 learning. */
114             ofpfw = (OFPFW10_DL_TYPE | OFPFW10_DL_VLAN_PCP
115                      | OFPFW10_NW_SRC_ALL | OFPFW10_NW_DST_ALL
116                      | OFPFW10_NW_TOS | OFPFW10_NW_PROTO
117                      | OFPFW10_TP_SRC | OFPFW10_TP_DST);
118         } else {
119             ofpfw = cfg->wildcards;
120         }
121
122         ofputil_wildcard_from_ofpfw10(ofpfw, &sw->wc);
123     }
124
125     sw->default_queue = cfg->default_queue;
126     hmap_init(&sw->queue_numbers);
127     shash_init(&sw->queue_names);
128     if (cfg->port_queues) {
129         struct simap_node *node;
130
131         SIMAP_FOR_EACH (node, cfg->port_queues) {
132             struct lswitch_port *port = xmalloc(sizeof *port);
133             hmap_node_nullify(&port->hmap_node);
134             port->queue_id = node->data;
135             shash_add(&sw->queue_names, node->name, port);
136         }
137     }
138
139     sw->queued = rconn_packet_counter_create();
140     send_features_request(sw, rconn);
141
142     if (cfg->default_flows) {
143         enum ofputil_protocol usable_protocols;
144         enum ofputil_protocol protocol;
145         struct ofpbuf *msg = NULL;
146         int ofp_version;
147         int error = 0;
148         size_t i;
149
150         /* Figure out the initial protocol on the connection. */
151         ofp_version = rconn_get_version(rconn);
152         protocol = ofputil_protocol_from_ofp_version(ofp_version);
153
154         /* If the initial protocol isn't good enough for default_flows, then
155          * pick one that will work and encode messages to set up that
156          * protocol.
157          *
158          * This could be improved by actually negotiating a mutually acceptable
159          * flow format with the switch, but that would require an asynchronous
160          * state machine.  This version ought to work fine in practice. */
161         usable_protocols = ofputil_flow_mod_usable_protocols(
162             cfg->default_flows, cfg->n_default_flows);
163         if (!(protocol & usable_protocols)) {
164             enum ofputil_protocol want = rightmost_1bit(usable_protocols);
165             while (!error) {
166                 msg = ofputil_encode_set_protocol(protocol, want, &protocol);
167                 if (!msg) {
168                     break;
169                 }
170                 error = rconn_send(rconn, msg, NULL);
171             }
172         }
173
174         for (i = 0; !error && i < cfg->n_default_flows; i++) {
175             msg = ofputil_encode_flow_mod(&cfg->default_flows[i], protocol);
176             error = rconn_send(rconn, msg, NULL);
177         }
178
179         if (error) {
180             VLOG_INFO_RL(&rl, "%s: failed to queue default flows (%s)",
181                          rconn_get_name(rconn), strerror(error));
182         }
183     }
184
185     return sw;
186 }
187
188 /* Destroys 'sw'. */
189 void
190 lswitch_destroy(struct lswitch *sw)
191 {
192     if (sw) {
193         struct lswitch_port *node, *next;
194
195         HMAP_FOR_EACH_SAFE (node, next, hmap_node, &sw->queue_numbers) {
196             hmap_remove(&sw->queue_numbers, &node->hmap_node);
197             free(node);
198         }
199         shash_destroy(&sw->queue_names);
200         mac_learning_destroy(sw->ml);
201         rconn_packet_counter_destroy(sw->queued);
202         free(sw);
203     }
204 }
205
206 /* Takes care of necessary 'sw' activity, except for receiving packets (which
207  * the caller must do). */
208 void
209 lswitch_run(struct lswitch *sw)
210 {
211     if (sw->ml) {
212         mac_learning_run(sw->ml, NULL);
213     }
214 }
215
216 void
217 lswitch_wait(struct lswitch *sw)
218 {
219     if (sw->ml) {
220         mac_learning_wait(sw->ml);
221     }
222 }
223
224 /* Processes 'msg', which should be an OpenFlow received on 'rconn', according
225  * to the learning switch state in 'sw'.  The most likely result of processing
226  * is that flow-setup and packet-out OpenFlow messages will be sent out on
227  * 'rconn'.  */
228 void
229 lswitch_process_packet(struct lswitch *sw, struct rconn *rconn,
230                        const struct ofpbuf *msg)
231 {
232     const struct ofp_header *oh = msg->data;
233     const struct ofputil_msg_type *type;
234
235     if (sw->datapath_id == 0
236         && oh->type != OFPT_ECHO_REQUEST
237         && oh->type != OFPT_FEATURES_REPLY) {
238         send_features_request(sw, rconn);
239         return;
240     }
241
242     ofputil_decode_msg_type(oh, &type);
243     switch (ofputil_msg_type_code(type)) {
244     case OFPUTIL_OFPT_ECHO_REQUEST:
245         process_echo_request(sw, rconn, msg->data);
246         break;
247
248     case OFPUTIL_OFPT_FEATURES_REPLY:
249         process_switch_features(sw, msg->data);
250         break;
251
252     case OFPUTIL_OFPT_PACKET_IN:
253         process_packet_in(sw, rconn, msg->data);
254         break;
255
256     case OFPUTIL_OFPT_FLOW_REMOVED:
257         /* Nothing to do. */
258         break;
259
260     case OFPUTIL_MSG_INVALID:
261     case OFPUTIL_OFPT_HELLO:
262     case OFPUTIL_OFPT_ERROR:
263     case OFPUTIL_OFPT_ECHO_REPLY:
264     case OFPUTIL_OFPT_FEATURES_REQUEST:
265     case OFPUTIL_OFPT_GET_CONFIG_REQUEST:
266     case OFPUTIL_OFPT_GET_CONFIG_REPLY:
267     case OFPUTIL_OFPT_SET_CONFIG:
268     case OFPUTIL_OFPT_PORT_STATUS:
269     case OFPUTIL_OFPT_PACKET_OUT:
270     case OFPUTIL_OFPT_FLOW_MOD:
271     case OFPUTIL_OFPT_PORT_MOD:
272     case OFPUTIL_OFPT_BARRIER_REQUEST:
273     case OFPUTIL_OFPT_BARRIER_REPLY:
274     case OFPUTIL_OFPT_QUEUE_GET_CONFIG_REQUEST:
275     case OFPUTIL_OFPT_QUEUE_GET_CONFIG_REPLY:
276     case OFPUTIL_OFPST_DESC_REQUEST:
277     case OFPUTIL_OFPST_FLOW_REQUEST:
278     case OFPUTIL_OFPST_AGGREGATE_REQUEST:
279     case OFPUTIL_OFPST_TABLE_REQUEST:
280     case OFPUTIL_OFPST_PORT_REQUEST:
281     case OFPUTIL_OFPST_QUEUE_REQUEST:
282     case OFPUTIL_OFPST_PORT_DESC_REQUEST:
283     case OFPUTIL_OFPST_DESC_REPLY:
284     case OFPUTIL_OFPST_FLOW_REPLY:
285     case OFPUTIL_OFPST_QUEUE_REPLY:
286     case OFPUTIL_OFPST_PORT_REPLY:
287     case OFPUTIL_OFPST_TABLE_REPLY:
288     case OFPUTIL_OFPST_AGGREGATE_REPLY:
289     case OFPUTIL_OFPST_PORT_DESC_REPLY:
290     case OFPUTIL_NXT_ROLE_REQUEST:
291     case OFPUTIL_NXT_ROLE_REPLY:
292     case OFPUTIL_NXT_FLOW_MOD_TABLE_ID:
293     case OFPUTIL_NXT_SET_FLOW_FORMAT:
294     case OFPUTIL_NXT_SET_PACKET_IN_FORMAT:
295     case OFPUTIL_NXT_PACKET_IN:
296     case OFPUTIL_NXT_FLOW_MOD:
297     case OFPUTIL_NXT_FLOW_REMOVED:
298     case OFPUTIL_NXT_FLOW_AGE:
299     case OFPUTIL_NXT_SET_ASYNC_CONFIG:
300     case OFPUTIL_NXT_SET_CONTROLLER_ID:
301     case OFPUTIL_NXST_FLOW_REQUEST:
302     case OFPUTIL_NXST_AGGREGATE_REQUEST:
303     case OFPUTIL_NXST_FLOW_REPLY:
304     case OFPUTIL_NXST_AGGREGATE_REPLY:
305     default:
306         if (VLOG_IS_DBG_ENABLED()) {
307             char *s = ofp_to_string(msg->data, msg->size, 2);
308             VLOG_DBG_RL(&rl, "%016llx: OpenFlow packet ignored: %s",
309                         sw->datapath_id, s);
310             free(s);
311         }
312     }
313 }
314 \f
315 static void
316 send_features_request(struct lswitch *sw, struct rconn *rconn)
317 {
318     time_t now = time_now();
319     if (now >= sw->last_features_request + 1) {
320         struct ofpbuf *b;
321         struct ofp_switch_config *osc;
322
323         /* Send OFPT_FEATURES_REQUEST. */
324         make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &b);
325         queue_tx(sw, rconn, b);
326
327         /* Send OFPT_SET_CONFIG. */
328         osc = make_openflow(sizeof *osc, OFPT_SET_CONFIG, &b);
329         osc->miss_send_len = htons(OFP_DEFAULT_MISS_SEND_LEN);
330         queue_tx(sw, rconn, b);
331
332         sw->last_features_request = now;
333     }
334 }
335
336 static void
337 queue_tx(struct lswitch *sw, struct rconn *rconn, struct ofpbuf *b)
338 {
339     int retval = rconn_send_with_limit(rconn, b, sw->queued, 10);
340     if (retval && retval != ENOTCONN) {
341         if (retval == EAGAIN) {
342             VLOG_INFO_RL(&rl, "%016llx: %s: tx queue overflow",
343                          sw->datapath_id, rconn_get_name(rconn));
344         } else {
345             VLOG_WARN_RL(&rl, "%016llx: %s: send: %s",
346                          sw->datapath_id, rconn_get_name(rconn),
347                          strerror(retval));
348         }
349     }
350 }
351
352 static enum ofperr
353 process_switch_features(struct lswitch *sw, struct ofp_switch_features *osf)
354 {
355     struct ofputil_switch_features features;
356     struct ofputil_phy_port port;
357     enum ofperr error;
358     struct ofpbuf b;
359
360     error = ofputil_decode_switch_features(osf, &features, &b);
361     if (error) {
362         VLOG_ERR("received invalid switch feature reply (%s)",
363                  ofperr_to_string(error));
364         return error;
365     }
366
367     sw->datapath_id = features.datapath_id;
368
369     while (!ofputil_pull_phy_port(osf->header.version, &b, &port)) {
370         struct lswitch_port *lp = shash_find_data(&sw->queue_names, port.name);
371         if (lp && hmap_node_is_null(&lp->hmap_node)) {
372             lp->port_no = port.port_no;
373             hmap_insert(&sw->queue_numbers, &lp->hmap_node,
374                         hash_int(lp->port_no, 0));
375         }
376     }
377     return 0;
378 }
379
380 static uint16_t
381 lswitch_choose_destination(struct lswitch *sw, const struct flow *flow)
382 {
383     uint16_t out_port;
384
385     /* Learn the source MAC. */
386     if (mac_learning_may_learn(sw->ml, flow->dl_src, 0)) {
387         struct mac_entry *mac = mac_learning_insert(sw->ml, flow->dl_src, 0);
388         if (mac_entry_is_new(mac) || mac->port.i != flow->in_port) {
389             VLOG_DBG_RL(&rl, "%016llx: learned that "ETH_ADDR_FMT" is on "
390                         "port %"PRIu16, sw->datapath_id,
391                         ETH_ADDR_ARGS(flow->dl_src), flow->in_port);
392
393             mac->port.i = flow->in_port;
394             mac_learning_changed(sw->ml, mac);
395         }
396     }
397
398     /* Drop frames for reserved multicast addresses. */
399     if (eth_addr_is_reserved(flow->dl_dst)) {
400         return OFPP_NONE;
401     }
402
403     out_port = OFPP_FLOOD;
404     if (sw->ml) {
405         struct mac_entry *mac;
406
407         mac = mac_learning_lookup(sw->ml, flow->dl_dst, 0, NULL);
408         if (mac) {
409             out_port = mac->port.i;
410             if (out_port == flow->in_port) {
411                 /* Don't send a packet back out its input port. */
412                 return OFPP_NONE;
413             }
414         }
415     }
416
417     /* Check if we need to use "NORMAL" action. */
418     if (sw->action_normal && out_port != OFPP_FLOOD) {
419         return OFPP_NORMAL;
420     }
421
422     return out_port;
423 }
424
425 static uint32_t
426 get_queue_id(const struct lswitch *sw, uint16_t in_port)
427 {
428     const struct lswitch_port *port;
429
430     HMAP_FOR_EACH_WITH_HASH (port, hmap_node, hash_int(in_port, 0),
431                              &sw->queue_numbers) {
432         if (port->port_no == in_port) {
433             return port->queue_id;
434         }
435     }
436
437     return sw->default_queue;
438 }
439
440 static void
441 process_packet_in(struct lswitch *sw, struct rconn *rconn,
442                   const struct ofp_packet_in *opi)
443 {
444     uint16_t in_port = ntohs(opi->in_port);
445     uint32_t queue_id;
446     uint16_t out_port;
447
448     struct ofp_action_header actions[2];
449     size_t actions_len;
450
451     struct ofputil_packet_out po;
452
453     size_t pkt_ofs, pkt_len;
454     struct ofpbuf pkt;
455     struct flow flow;
456
457     /* Ignore packets sent via output to OFPP_CONTROLLER.  This library never
458      * uses such an action.  You never know what experiments might be going on,
459      * though, and it seems best not to interfere with them. */
460     if (opi->reason != OFPR_NO_MATCH) {
461         return;
462     }
463
464     /* Extract flow data from 'opi' into 'flow'. */
465     pkt_ofs = offsetof(struct ofp_packet_in, data);
466     pkt_len = ntohs(opi->header.length) - pkt_ofs;
467     ofpbuf_use_const(&pkt, opi->data, pkt_len);
468     flow_extract(&pkt, 0, 0, in_port, &flow);
469
470     /* Choose output port. */
471     out_port = lswitch_choose_destination(sw, &flow);
472
473     /* Make actions. */
474     queue_id = get_queue_id(sw, in_port);
475     if (out_port == OFPP_NONE) {
476         actions_len = 0;
477     } else if (queue_id == UINT32_MAX || out_port >= OFPP_MAX) {
478         struct ofp_action_output oao;
479
480         memset(&oao, 0, sizeof oao);
481         oao.type = htons(OFPAT10_OUTPUT);
482         oao.len = htons(sizeof oao);
483         oao.port = htons(out_port);
484
485         memcpy(actions, &oao, sizeof oao);
486         actions_len = sizeof oao;
487     } else {
488         struct ofp_action_enqueue oae;
489
490         memset(&oae, 0, sizeof oae);
491         oae.type = htons(OFPAT10_ENQUEUE);
492         oae.len = htons(sizeof oae);
493         oae.port = htons(out_port);
494         oae.queue_id = htonl(queue_id);
495
496         memcpy(actions, &oae, sizeof oae);
497         actions_len = sizeof oae;
498     }
499     assert(actions_len <= sizeof actions);
500
501     /* Prepare packet_out in case we need one. */
502     po.buffer_id = ntohl(opi->buffer_id);
503     if (po.buffer_id == UINT32_MAX) {
504         po.packet = pkt.data;
505         po.packet_len = pkt.size;
506     } else {
507         po.packet = NULL;
508         po.packet_len = 0;
509     }
510     po.in_port = in_port;
511     po.actions = (union ofp_action *) actions;
512     po.n_actions = actions_len / sizeof *actions;
513
514     /* Send the packet, and possibly the whole flow, to the output port. */
515     if (sw->max_idle >= 0 && (!sw->ml || out_port != OFPP_FLOOD)) {
516         struct ofpbuf *buffer;
517         struct cls_rule rule;
518
519         /* The output port is known, or we always flood everything, so add a
520          * new flow. */
521         cls_rule_init(&flow, &sw->wc, 0, &rule);
522         buffer = make_add_flow(&rule, ntohl(opi->buffer_id),
523                                sw->max_idle, actions_len);
524         ofpbuf_put(buffer, actions, actions_len);
525         queue_tx(sw, rconn, buffer);
526
527         /* If the switch didn't buffer the packet, we need to send a copy. */
528         if (ntohl(opi->buffer_id) == UINT32_MAX && actions_len > 0) {
529             queue_tx(sw, rconn, ofputil_encode_packet_out(&po));
530         }
531     } else {
532         /* We don't know that MAC, or we don't set up flows.  Send along the
533          * packet without setting up a flow. */
534         if (ntohl(opi->buffer_id) != UINT32_MAX || actions_len > 0) {
535             queue_tx(sw, rconn, ofputil_encode_packet_out(&po));
536         }
537     }
538 }
539
540 static void
541 process_echo_request(struct lswitch *sw, struct rconn *rconn,
542                      const struct ofp_header *rq)
543 {
544     queue_tx(sw, rconn, make_echo_reply(rq));
545 }