learning-switch: Send Features Request and Set Config with correct version
[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-actions.h"
33 #include "ofp-errors.h"
34 #include "ofp-msgs.h"
35 #include "ofp-parse.h"
36 #include "ofp-print.h"
37 #include "ofp-util.h"
38 #include "openflow/openflow.h"
39 #include "poll-loop.h"
40 #include "rconn.h"
41 #include "shash.h"
42 #include "simap.h"
43 #include "timeval.h"
44 #include "vconn.h"
45 #include "vlog.h"
46
47 VLOG_DEFINE_THIS_MODULE(learning_switch);
48
49 struct lswitch_port {
50     struct hmap_node hmap_node; /* Hash node for port number. */
51     uint16_t port_no;           /* OpenFlow port number, in host byte order. */
52     uint32_t queue_id;          /* OpenFlow queue number. */
53 };
54
55 struct lswitch {
56     /* If nonnegative, the switch sets up flows that expire after the given
57      * number of seconds (or never expire, if the value is OFP_FLOW_PERMANENT).
58      * Otherwise, the switch processes every packet. */
59     int max_idle;
60
61     enum ofputil_protocol protocol;
62     unsigned long long int datapath_id;
63     time_t last_features_request;
64     struct mac_learning *ml;    /* NULL to act as hub instead of switch. */
65     struct flow_wildcards wc;   /* Wildcards to apply to flows. */
66     bool action_normal;         /* Use OFPP_NORMAL? */
67
68     /* Queue distribution. */
69     uint32_t default_queue;     /* Default OpenFlow queue, or UINT32_MAX. */
70     struct hmap queue_numbers;  /* Map from port number to lswitch_port. */
71     struct shash queue_names;   /* Map from port name to lswitch_port. */
72
73     /* Number of outgoing queued packets on the rconn. */
74     struct rconn_packet_counter *queued;
75 };
76
77 /* The log messages here could actually be useful in debugging, so keep the
78  * rate limit relatively high. */
79 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
80
81 static void queue_tx(struct lswitch *, struct rconn *, struct ofpbuf *);
82 static void send_features_request(struct lswitch *, struct rconn *);
83
84 static enum ofperr process_switch_features(struct lswitch *,
85                                            struct ofp_header *);
86 static void process_packet_in(struct lswitch *, struct rconn *,
87                               const struct ofp_header *);
88 static void process_echo_request(struct lswitch *, struct rconn *,
89                                  const struct ofp_header *);
90
91 /* Creates and returns a new learning switch whose configuration is given by
92  * 'cfg'.
93  *
94  * 'rconn' is used to send out an OpenFlow features request. */
95 struct lswitch *
96 lswitch_create(struct rconn *rconn, const struct lswitch_config *cfg)
97 {
98     enum ofputil_protocol protocol;
99     struct lswitch *sw;
100
101     sw = xzalloc(sizeof *sw);
102     sw->max_idle = cfg->max_idle;
103     sw->datapath_id = 0;
104     sw->last_features_request = time_now() - 1;
105     sw->ml = (cfg->mode == LSW_LEARN
106               ? mac_learning_create(MAC_ENTRY_DEFAULT_IDLE_TIME)
107               : NULL);
108     sw->action_normal = cfg->mode == LSW_NORMAL;
109
110     flow_wildcards_init_exact(&sw->wc);
111     if (cfg->wildcards) {
112         uint32_t ofpfw;
113
114         if (cfg->wildcards == UINT32_MAX) {
115             /* Try to wildcard as many fields as possible, but we cannot
116              * wildcard all fields.  We need in_port to detect moves.  We need
117              * Ethernet source and dest and VLAN VID to do L2 learning. */
118             ofpfw = (OFPFW10_DL_TYPE | OFPFW10_DL_VLAN_PCP
119                      | OFPFW10_NW_SRC_ALL | OFPFW10_NW_DST_ALL
120                      | OFPFW10_NW_TOS | OFPFW10_NW_PROTO
121                      | OFPFW10_TP_SRC | OFPFW10_TP_DST);
122         } else {
123             ofpfw = cfg->wildcards;
124         }
125
126         ofputil_wildcard_from_ofpfw10(ofpfw, &sw->wc);
127     }
128
129     sw->default_queue = cfg->default_queue;
130     hmap_init(&sw->queue_numbers);
131     shash_init(&sw->queue_names);
132     if (cfg->port_queues) {
133         struct simap_node *node;
134
135         SIMAP_FOR_EACH (node, cfg->port_queues) {
136             struct lswitch_port *port = xmalloc(sizeof *port);
137             hmap_node_nullify(&port->hmap_node);
138             port->queue_id = node->data;
139             shash_add(&sw->queue_names, node->name, port);
140         }
141     }
142
143     sw->queued = rconn_packet_counter_create();
144     send_features_request(sw, rconn);
145
146     protocol = ofputil_protocol_from_ofp_version(rconn_get_version(rconn));
147     if (cfg->default_flows) {
148         enum ofputil_protocol usable_protocols;
149         struct ofpbuf *msg = NULL;
150         int error = 0;
151         size_t i;
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     sw->protocol = protocol;
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     enum ofptype type;
233     struct ofpbuf b;
234
235     b = *msg;
236     if (ofptype_pull(&type, &b)) {
237         return;
238     }
239
240     if (sw->datapath_id == 0
241         && type != OFPTYPE_ECHO_REQUEST
242         && type != OFPTYPE_FEATURES_REPLY) {
243         send_features_request(sw, rconn);
244         return;
245     }
246
247     switch (type) {
248     case OFPTYPE_ECHO_REQUEST:
249         process_echo_request(sw, rconn, msg->data);
250         break;
251
252     case OFPTYPE_FEATURES_REPLY:
253         process_switch_features(sw, msg->data);
254         break;
255
256     case OFPTYPE_PACKET_IN:
257         process_packet_in(sw, rconn, msg->data);
258         break;
259
260     case OFPTYPE_FLOW_REMOVED:
261         /* Nothing to do. */
262         break;
263
264     case OFPTYPE_HELLO:
265     case OFPTYPE_ERROR:
266     case OFPTYPE_ECHO_REPLY:
267     case OFPTYPE_FEATURES_REQUEST:
268     case OFPTYPE_GET_CONFIG_REQUEST:
269     case OFPTYPE_GET_CONFIG_REPLY:
270     case OFPTYPE_SET_CONFIG:
271     case OFPTYPE_PORT_STATUS:
272     case OFPTYPE_PACKET_OUT:
273     case OFPTYPE_FLOW_MOD:
274     case OFPTYPE_PORT_MOD:
275     case OFPTYPE_BARRIER_REQUEST:
276     case OFPTYPE_BARRIER_REPLY:
277     case OFPTYPE_DESC_STATS_REQUEST:
278     case OFPTYPE_DESC_STATS_REPLY:
279     case OFPTYPE_FLOW_STATS_REQUEST:
280     case OFPTYPE_FLOW_STATS_REPLY:
281     case OFPTYPE_AGGREGATE_STATS_REQUEST:
282     case OFPTYPE_AGGREGATE_STATS_REPLY:
283     case OFPTYPE_TABLE_STATS_REQUEST:
284     case OFPTYPE_TABLE_STATS_REPLY:
285     case OFPTYPE_PORT_STATS_REQUEST:
286     case OFPTYPE_PORT_STATS_REPLY:
287     case OFPTYPE_QUEUE_STATS_REQUEST:
288     case OFPTYPE_QUEUE_STATS_REPLY:
289     case OFPTYPE_PORT_DESC_STATS_REQUEST:
290     case OFPTYPE_PORT_DESC_STATS_REPLY:
291     case OFPTYPE_ROLE_REQUEST:
292     case OFPTYPE_ROLE_REPLY:
293     case OFPTYPE_SET_FLOW_FORMAT:
294     case OFPTYPE_FLOW_MOD_TABLE_ID:
295     case OFPTYPE_SET_PACKET_IN_FORMAT:
296     case OFPTYPE_FLOW_AGE:
297     case OFPTYPE_SET_ASYNC_CONFIG:
298     case OFPTYPE_SET_CONTROLLER_ID:
299     case OFPTYPE_FLOW_MONITOR_STATS_REQUEST:
300     case OFPTYPE_FLOW_MONITOR_STATS_REPLY:
301     case OFPTYPE_FLOW_MONITOR_CANCEL:
302     case OFPTYPE_FLOW_MONITOR_PAUSED:
303     case OFPTYPE_FLOW_MONITOR_RESUMED:
304     default:
305         if (VLOG_IS_DBG_ENABLED()) {
306             char *s = ofp_to_string(msg->data, msg->size, 2);
307             VLOG_DBG_RL(&rl, "%016llx: OpenFlow packet ignored: %s",
308                         sw->datapath_id, s);
309             free(s);
310         }
311     }
312 }
313 \f
314 static void
315 send_features_request(struct lswitch *sw, struct rconn *rconn)
316 {
317     time_t now = time_now();
318     if (now >= sw->last_features_request + 1) {
319         struct ofpbuf *b;
320         struct ofp_switch_config *osc;
321         int ofp_version = rconn_get_version(rconn);
322
323         assert(ofp_version > 0 && ofp_version < 0xff);
324
325         /* Send OFPT_FEATURES_REQUEST. */
326         b = ofpraw_alloc(OFPRAW_OFPT_FEATURES_REQUEST, ofp_version, 0);
327         queue_tx(sw, rconn, b);
328
329         /* Send OFPT_SET_CONFIG. */
330         b = ofpraw_alloc(OFPRAW_OFPT_SET_CONFIG, ofp_version, sizeof *osc);
331         osc = ofpbuf_put_zeros(b, sizeof *osc);
332         osc->miss_send_len = htons(OFP_DEFAULT_MISS_SEND_LEN);
333         queue_tx(sw, rconn, b);
334
335         sw->last_features_request = now;
336     }
337 }
338
339 static void
340 queue_tx(struct lswitch *sw, struct rconn *rconn, struct ofpbuf *b)
341 {
342     int retval = rconn_send_with_limit(rconn, b, sw->queued, 10);
343     if (retval && retval != ENOTCONN) {
344         if (retval == EAGAIN) {
345             VLOG_INFO_RL(&rl, "%016llx: %s: tx queue overflow",
346                          sw->datapath_id, rconn_get_name(rconn));
347         } else {
348             VLOG_WARN_RL(&rl, "%016llx: %s: send: %s",
349                          sw->datapath_id, rconn_get_name(rconn),
350                          strerror(retval));
351         }
352     }
353 }
354
355 static enum ofperr
356 process_switch_features(struct lswitch *sw, struct ofp_header *oh)
357 {
358     struct ofputil_switch_features features;
359     struct ofputil_phy_port port;
360     enum ofperr error;
361     struct ofpbuf b;
362
363     error = ofputil_decode_switch_features(oh, &features, &b);
364     if (error) {
365         VLOG_ERR("received invalid switch feature reply (%s)",
366                  ofperr_to_string(error));
367         return error;
368     }
369
370     sw->datapath_id = features.datapath_id;
371
372     while (!ofputil_pull_phy_port(oh->version, &b, &port)) {
373         struct lswitch_port *lp = shash_find_data(&sw->queue_names, port.name);
374         if (lp && hmap_node_is_null(&lp->hmap_node)) {
375             lp->port_no = port.port_no;
376             hmap_insert(&sw->queue_numbers, &lp->hmap_node,
377                         hash_int(lp->port_no, 0));
378         }
379     }
380     return 0;
381 }
382
383 static uint16_t
384 lswitch_choose_destination(struct lswitch *sw, const struct flow *flow)
385 {
386     uint16_t out_port;
387
388     /* Learn the source MAC. */
389     if (mac_learning_may_learn(sw->ml, flow->dl_src, 0)) {
390         struct mac_entry *mac = mac_learning_insert(sw->ml, flow->dl_src, 0);
391         if (mac_entry_is_new(mac) || mac->port.i != flow->in_port) {
392             VLOG_DBG_RL(&rl, "%016llx: learned that "ETH_ADDR_FMT" is on "
393                         "port %"PRIu16, sw->datapath_id,
394                         ETH_ADDR_ARGS(flow->dl_src), flow->in_port);
395
396             mac->port.i = flow->in_port;
397             mac_learning_changed(sw->ml, mac);
398         }
399     }
400
401     /* Drop frames for reserved multicast addresses. */
402     if (eth_addr_is_reserved(flow->dl_dst)) {
403         return OFPP_NONE;
404     }
405
406     out_port = OFPP_FLOOD;
407     if (sw->ml) {
408         struct mac_entry *mac;
409
410         mac = mac_learning_lookup(sw->ml, flow->dl_dst, 0, NULL);
411         if (mac) {
412             out_port = mac->port.i;
413             if (out_port == flow->in_port) {
414                 /* Don't send a packet back out its input port. */
415                 return OFPP_NONE;
416             }
417         }
418     }
419
420     /* Check if we need to use "NORMAL" action. */
421     if (sw->action_normal && out_port != OFPP_FLOOD) {
422         return OFPP_NORMAL;
423     }
424
425     return out_port;
426 }
427
428 static uint32_t
429 get_queue_id(const struct lswitch *sw, uint16_t in_port)
430 {
431     const struct lswitch_port *port;
432
433     HMAP_FOR_EACH_WITH_HASH (port, hmap_node, hash_int(in_port, 0),
434                              &sw->queue_numbers) {
435         if (port->port_no == in_port) {
436             return port->queue_id;
437         }
438     }
439
440     return sw->default_queue;
441 }
442
443 static void
444 process_packet_in(struct lswitch *sw, struct rconn *rconn,
445                   const struct ofp_header *oh)
446 {
447     struct ofputil_packet_in pi;
448     uint32_t queue_id;
449     uint16_t out_port;
450
451     uint64_t ofpacts_stub[64 / 8];
452     struct ofpbuf ofpacts;
453
454     struct ofputil_packet_out po;
455     enum ofperr error;
456
457     struct ofpbuf pkt;
458     struct flow flow;
459
460     error = ofputil_decode_packet_in(&pi, oh);
461     if (error) {
462         VLOG_WARN_RL(&rl, "failed to decode packet-in: %s",
463                      ofperr_to_string(error));
464         return;
465     }
466
467     /* Ignore packets sent via output to OFPP_CONTROLLER.  This library never
468      * uses such an action.  You never know what experiments might be going on,
469      * though, and it seems best not to interfere with them. */
470     if (pi.reason != OFPR_NO_MATCH) {
471         return;
472     }
473
474     /* Extract flow data from 'opi' into 'flow'. */
475     ofpbuf_use_const(&pkt, pi.packet, pi.packet_len);
476     flow_extract(&pkt, 0, pi.fmd.tun_id, pi.fmd.in_port, &flow);
477
478     /* Choose output port. */
479     out_port = lswitch_choose_destination(sw, &flow);
480
481     /* Make actions. */
482     queue_id = get_queue_id(sw, pi.fmd.in_port);
483     ofpbuf_use_stack(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
484     if (out_port == OFPP_NONE) {
485         /* No actions. */
486     } else if (queue_id == UINT32_MAX || out_port >= OFPP_MAX) {
487         ofpact_put_OUTPUT(&ofpacts)->port = out_port;
488     } else {
489         struct ofpact_enqueue *enqueue = ofpact_put_ENQUEUE(&ofpacts);
490         enqueue->port = out_port;
491         enqueue->queue = queue_id;
492     }
493     ofpact_pad(&ofpacts);
494
495     /* Prepare packet_out in case we need one. */
496     po.buffer_id = pi.buffer_id;
497     if (po.buffer_id == UINT32_MAX) {
498         po.packet = pkt.data;
499         po.packet_len = pkt.size;
500     } else {
501         po.packet = NULL;
502         po.packet_len = 0;
503     }
504     po.in_port = pi.fmd.in_port;
505     po.ofpacts = ofpacts.data;
506     po.ofpacts_len = ofpacts.size;
507
508     /* Send the packet, and possibly the whole flow, to the output port. */
509     if (sw->max_idle >= 0 && (!sw->ml || out_port != OFPP_FLOOD)) {
510         struct ofputil_flow_mod fm;
511         struct ofpbuf *buffer;
512
513         /* The output port is known, or we always flood everything, so add a
514          * new flow. */
515         memset(&fm, 0, sizeof fm);
516         cls_rule_init(&flow, &sw->wc, 0, &fm.cr);
517         fm.table_id = 0xff;
518         fm.command = OFPFC_ADD;
519         fm.idle_timeout = sw->max_idle;
520         fm.buffer_id = pi.buffer_id;
521         fm.out_port = OFPP_NONE;
522         fm.ofpacts = ofpacts.data;
523         fm.ofpacts_len = ofpacts.size;
524         buffer = ofputil_encode_flow_mod(&fm, sw->protocol);
525
526         queue_tx(sw, rconn, buffer);
527
528         /* If the switch didn't buffer the packet, we need to send a copy. */
529         if (pi.buffer_id == UINT32_MAX && out_port != OFPP_NONE) {
530             queue_tx(sw, rconn, ofputil_encode_packet_out(&po));
531         }
532     } else {
533         /* We don't know that MAC, or we don't set up flows.  Send along the
534          * packet without setting up a flow. */
535         if (pi.buffer_id != UINT32_MAX || out_port != OFPP_NONE) {
536             queue_tx(sw, rconn, ofputil_encode_packet_out(&po));
537         }
538     }
539 }
540
541 static void
542 process_echo_request(struct lswitch *sw, struct rconn *rconn,
543                      const struct ofp_header *rq)
544 {
545     queue_tx(sw, rconn, make_echo_reply(rq));
546 }