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