7b99a93385c39e4599931c716a019b55c650ba64
[sliver-openvswitch.git] / lib / learning-switch.c
1 /*
2  * Copyright (c) 2008, 2009, 2010 Nicira Networks.
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-parse.h"
33 #include "ofp-print.h"
34 #include "ofp-util.h"
35 #include "openflow/openflow.h"
36 #include "poll-loop.h"
37 #include "rconn.h"
38 #include "shash.h"
39 #include "timeval.h"
40 #include "vconn.h"
41 #include "vlog.h"
42
43 VLOG_DEFINE_THIS_MODULE(learning_switch);
44
45 struct lswitch_port {
46     struct hmap_node hmap_node; /* Hash node for port number. */
47     uint16_t port_no;           /* OpenFlow port number, in host byte order. */
48     uint32_t queue_id;          /* OpenFlow queue number. */
49 };
50
51 struct lswitch {
52     /* If nonnegative, the switch sets up flows that expire after the given
53      * number of seconds (or never expire, if the value is OFP_FLOW_PERMANENT).
54      * Otherwise, the switch processes every packet. */
55     int max_idle;
56
57     unsigned long long int datapath_id;
58     time_t last_features_request;
59     struct mac_learning *ml;    /* NULL to act as hub instead of switch. */
60     struct flow_wildcards wc;   /* Wildcards to apply to flows. */
61     bool action_normal;         /* Use OFPP_NORMAL? */
62
63     /* Queue distribution. */
64     uint32_t default_queue;     /* Default OpenFlow queue, or UINT32_MAX. */
65     struct hmap queue_numbers;  /* Map from port number to lswitch_port. */
66     struct shash queue_names;   /* Map from port name to lswitch_port. */
67
68     /* Number of outgoing queued packets on the rconn. */
69     struct rconn_packet_counter *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 ofpbuf *);
77 static void send_features_request(struct lswitch *, struct rconn *);
78
79 typedef void packet_handler_func(struct lswitch *, struct rconn *, void *);
80 static packet_handler_func process_switch_features;
81 static packet_handler_func process_packet_in;
82 static packet_handler_func process_echo_request;
83
84 /* Creates and returns a new learning switch whose configuration is given by
85  * 'cfg'.
86  *
87  * 'rconn' is used to send out an OpenFlow features request. */
88 struct lswitch *
89 lswitch_create(struct rconn *rconn, const struct lswitch_config *cfg)
90 {
91     struct lswitch *sw;
92
93     sw = xzalloc(sizeof *sw);
94     sw->max_idle = cfg->max_idle;
95     sw->datapath_id = 0;
96     sw->last_features_request = time_now() - 1;
97     sw->ml = cfg->mode == LSW_LEARN ? mac_learning_create() : NULL;
98     sw->action_normal = cfg->mode == LSW_NORMAL;
99
100     flow_wildcards_init_exact(&sw->wc);
101     if (!cfg->exact_flows) {
102         /* We cannot wildcard all fields.
103          * We need in_port to detect moves.
104          * We need both SA and DA to do learning. */
105         sw->wc.wildcards = (FWW_DL_TYPE | FWW_NW_PROTO
106                             | FWW_TP_SRC | FWW_TP_DST);
107         sw->wc.nw_src_mask = htonl(0);
108         sw->wc.nw_dst_mask = htonl(0);
109     }
110
111     sw->default_queue = cfg->default_queue;
112     hmap_init(&sw->queue_numbers);
113     shash_init(&sw->queue_names);
114     if (cfg->port_queues) {
115         struct shash_node *node;
116
117         SHASH_FOR_EACH (node, cfg->port_queues) {
118             struct lswitch_port *port = xmalloc(sizeof *port);
119             hmap_node_nullify(&port->hmap_node);
120             port->queue_id = (uintptr_t) node->data;
121             shash_add(&sw->queue_names, node->name, port);
122         }
123     }
124
125     sw->queued = rconn_packet_counter_create();
126     send_features_request(sw, rconn);
127
128     if (cfg->default_flows) {
129         const struct ofpbuf *b;
130
131         LIST_FOR_EACH (b, list_node, cfg->default_flows) {
132             queue_tx(sw, rconn, ofpbuf_clone(b));
133         }
134     }
135     
136     return sw;
137 }
138
139 /* Destroys 'sw'. */
140 void
141 lswitch_destroy(struct lswitch *sw)
142 {
143     if (sw) {
144         struct lswitch_port *node, *next;
145
146         HMAP_FOR_EACH_SAFE (node, next, hmap_node, &sw->queue_numbers) {
147             hmap_remove(&sw->queue_numbers, &node->hmap_node);
148             free(node);
149         }
150         shash_destroy(&sw->queue_names);
151         mac_learning_destroy(sw->ml);
152         rconn_packet_counter_destroy(sw->queued);
153         free(sw);
154     }
155 }
156
157 /* Takes care of necessary 'sw' activity, except for receiving packets (which
158  * the caller must do). */
159 void
160 lswitch_run(struct lswitch *sw)
161 {
162     if (sw->ml) {
163         mac_learning_run(sw->ml, NULL);
164     }
165 }
166
167 void
168 lswitch_wait(struct lswitch *sw)
169 {
170     if (sw->ml) {
171         mac_learning_wait(sw->ml);
172     }
173 }
174
175 /* Processes 'msg', which should be an OpenFlow received on 'rconn', according
176  * to the learning switch state in 'sw'.  The most likely result of processing
177  * is that flow-setup and packet-out OpenFlow messages will be sent out on
178  * 'rconn'.  */
179 void
180 lswitch_process_packet(struct lswitch *sw, struct rconn *rconn,
181                        const struct ofpbuf *msg)
182 {
183     struct processor {
184         uint8_t type;
185         size_t min_size;
186         packet_handler_func *handler;
187     };
188     static const struct processor processors[] = {
189         {
190             OFPT_ECHO_REQUEST,
191             sizeof(struct ofp_header),
192             process_echo_request
193         },
194         {
195             OFPT_FEATURES_REPLY,
196             sizeof(struct ofp_switch_features),
197             process_switch_features
198         },
199         {
200             OFPT_PACKET_IN,
201             offsetof(struct ofp_packet_in, data),
202             process_packet_in
203         },
204         {
205             OFPT_FLOW_REMOVED,
206             sizeof(struct ofp_flow_removed),
207             NULL
208         },
209     };
210     const size_t n_processors = ARRAY_SIZE(processors);
211     const struct processor *p;
212     struct ofp_header *oh;
213
214     oh = msg->data;
215     if (sw->datapath_id == 0
216         && oh->type != OFPT_ECHO_REQUEST
217         && oh->type != OFPT_FEATURES_REPLY) {
218         send_features_request(sw, rconn);
219         return;
220     }
221
222     for (p = processors; p < &processors[n_processors]; p++) {
223         if (oh->type == p->type) {
224             if (msg->size < p->min_size) {
225                 VLOG_WARN_RL(&rl, "%016llx: %s: too short (%zu bytes) for "
226                              "type %"PRIu8" (min %zu)", sw->datapath_id,
227                              rconn_get_name(rconn), msg->size, oh->type,
228                              p->min_size);
229                 return;
230             }
231             if (p->handler) {
232                 (p->handler)(sw, rconn, msg->data);
233             }
234             return;
235         }
236     }
237     if (VLOG_IS_DBG_ENABLED()) {
238         char *s = ofp_to_string(msg->data, msg->size, 2);
239         VLOG_DBG_RL(&rl, "%016llx: OpenFlow packet ignored: %s",
240                     sw->datapath_id, s);
241         free(s);
242     }
243 }
244 \f
245 static void
246 send_features_request(struct lswitch *sw, struct rconn *rconn)
247 {
248     time_t now = time_now();
249     if (now >= sw->last_features_request + 1) {
250         struct ofpbuf *b;
251         struct ofp_switch_config *osc;
252
253         /* Send OFPT_FEATURES_REQUEST. */
254         make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &b);
255         queue_tx(sw, rconn, b);
256
257         /* Send OFPT_SET_CONFIG. */
258         osc = make_openflow(sizeof *osc, OFPT_SET_CONFIG, &b);
259         osc->miss_send_len = htons(OFP_DEFAULT_MISS_SEND_LEN);
260         queue_tx(sw, rconn, b);
261
262         sw->last_features_request = now;
263     }
264 }
265
266 static void
267 queue_tx(struct lswitch *sw, struct rconn *rconn, struct ofpbuf *b)
268 {
269     int retval = rconn_send_with_limit(rconn, b, sw->queued, 10);
270     if (retval && retval != ENOTCONN) {
271         if (retval == EAGAIN) {
272             VLOG_INFO_RL(&rl, "%016llx: %s: tx queue overflow",
273                          sw->datapath_id, rconn_get_name(rconn));
274         } else {
275             VLOG_WARN_RL(&rl, "%016llx: %s: send: %s",
276                          sw->datapath_id, rconn_get_name(rconn),
277                          strerror(retval));
278         }
279     }
280 }
281
282 static void
283 process_switch_features(struct lswitch *sw, struct rconn *rconn OVS_UNUSED,
284                         void *osf_)
285 {
286     struct ofp_switch_features *osf = osf_;
287     size_t n_ports;
288     size_t i;
289
290     if (check_ofp_message_array(&osf->header, OFPT_FEATURES_REPLY,
291                                 sizeof *osf, sizeof *osf->ports, &n_ports)) {
292         return;
293     }
294
295     sw->datapath_id = ntohll(osf->datapath_id);
296
297     for (i = 0; i < n_ports; i++) {
298         struct ofp_phy_port *opp = &osf->ports[i];
299         struct lswitch_port *lp;
300
301         opp->name[OFP_MAX_PORT_NAME_LEN - 1] = '\0';
302         lp = shash_find_data(&sw->queue_names, opp->name);
303         if (lp && hmap_node_is_null(&lp->hmap_node)) {
304             lp->port_no = ntohs(opp->port_no);
305             hmap_insert(&sw->queue_numbers, &lp->hmap_node,
306                         hash_int(lp->port_no, 0));
307         }
308     }
309 }
310
311 static uint16_t
312 lswitch_choose_destination(struct lswitch *sw, const struct flow *flow)
313 {
314     uint16_t out_port;
315
316     /* Learn the source MAC. */
317     if (sw->ml) {
318         if (mac_learning_learn(sw->ml, flow->dl_src, 0, flow->in_port,
319                                GRAT_ARP_LOCK_NONE)) {
320             VLOG_DBG_RL(&rl, "%016llx: learned that "ETH_ADDR_FMT" is on "
321                         "port %"PRIu16, sw->datapath_id,
322                         ETH_ADDR_ARGS(flow->dl_src), flow->in_port);
323         }
324     }
325
326     /* Drop frames for reserved multicast addresses. */
327     if (eth_addr_is_reserved(flow->dl_dst)) {
328         return OFPP_NONE;
329     }
330
331     out_port = OFPP_FLOOD;
332     if (sw->ml) {
333         int learned_port = mac_learning_lookup(sw->ml, flow->dl_dst, 0, NULL);
334         if (learned_port >= 0) {
335             out_port = learned_port;
336             if (out_port == flow->in_port) {
337                 /* Don't send a packet back out its input port. */
338                 return OFPP_NONE;
339             }
340         }
341     }
342
343     /* Check if we need to use "NORMAL" action. */
344     if (sw->action_normal && out_port != OFPP_FLOOD) {
345         return OFPP_NORMAL;
346     }
347
348     return out_port;
349 }
350
351 static uint32_t
352 get_queue_id(const struct lswitch *sw, uint16_t in_port)
353 {
354     const struct lswitch_port *port;
355
356     HMAP_FOR_EACH_WITH_HASH (port, hmap_node, hash_int(in_port, 0),
357                              &sw->queue_numbers) {
358         if (port->port_no == in_port) {
359             return port->queue_id;
360         }
361     }
362
363     return sw->default_queue;
364 }
365
366 static void
367 process_packet_in(struct lswitch *sw, struct rconn *rconn, void *opi_)
368 {
369     struct ofp_packet_in *opi = opi_;
370     uint16_t in_port = ntohs(opi->in_port);
371     uint32_t queue_id;
372     uint16_t out_port;
373
374     struct ofp_action_header actions[2];
375     size_t actions_len;
376
377     size_t pkt_ofs, pkt_len;
378     struct ofpbuf pkt;
379     struct flow flow;
380
381     /* Ignore packets sent via output to OFPP_CONTROLLER.  This library never
382      * uses such an action.  You never know what experiments might be going on,
383      * though, and it seems best not to interfere with them. */
384     if (opi->reason != OFPR_NO_MATCH) {
385         return;
386     }
387
388     /* Extract flow data from 'opi' into 'flow'. */
389     pkt_ofs = offsetof(struct ofp_packet_in, data);
390     pkt_len = ntohs(opi->header.length) - pkt_ofs;
391     pkt.data = opi->data;
392     pkt.size = pkt_len;
393     flow_extract(&pkt, 0, in_port, &flow);
394
395     /* Choose output port. */
396     out_port = lswitch_choose_destination(sw, &flow);
397
398     /* Make actions. */
399     queue_id = get_queue_id(sw, in_port);
400     if (out_port == OFPP_NONE) {
401         actions_len = 0;
402     } else if (queue_id == UINT32_MAX || out_port >= OFPP_MAX) {
403         struct ofp_action_output oao;
404
405         memset(&oao, 0, sizeof oao);
406         oao.type = htons(OFPAT_OUTPUT);
407         oao.len = htons(sizeof oao);
408         oao.port = htons(out_port);
409
410         memcpy(actions, &oao, sizeof oao);
411         actions_len = sizeof oao;
412     } else {
413         struct ofp_action_enqueue oae;
414
415         memset(&oae, 0, sizeof oae);
416         oae.type = htons(OFPAT_ENQUEUE);
417         oae.len = htons(sizeof oae);
418         oae.port = htons(out_port);
419         oae.queue_id = htonl(queue_id);
420
421         memcpy(actions, &oae, sizeof oae);
422         actions_len = sizeof oae;
423     }
424     assert(actions_len <= sizeof actions);
425
426     /* Send the packet, and possibly the whole flow, to the output port. */
427     if (sw->max_idle >= 0 && (!sw->ml || out_port != OFPP_FLOOD)) {
428         struct ofpbuf *buffer;
429         struct ofp_flow_mod *ofm;
430         struct cls_rule rule;
431
432         /* The output port is known, or we always flood everything, so add a
433          * new flow. */
434         cls_rule_init(&flow, &sw->wc, 0, &rule);
435         buffer = make_add_flow(&rule, ntohl(opi->buffer_id),
436                                sw->max_idle, actions_len);
437         ofpbuf_put(buffer, actions, actions_len);
438         ofm = buffer->data;
439         queue_tx(sw, rconn, buffer);
440
441         /* If the switch didn't buffer the packet, we need to send a copy. */
442         if (ntohl(opi->buffer_id) == UINT32_MAX && actions_len > 0) {
443             queue_tx(sw, rconn,
444                      make_packet_out(&pkt, UINT32_MAX, in_port,
445                                      actions, actions_len / sizeof *actions));
446         }
447     } else {
448         /* We don't know that MAC, or we don't set up flows.  Send along the
449          * packet without setting up a flow. */
450         if (ntohl(opi->buffer_id) != UINT32_MAX || actions_len > 0) {
451             queue_tx(sw, rconn,
452                      make_packet_out(&pkt, ntohl(opi->buffer_id), in_port,
453                                      actions, actions_len / sizeof *actions));
454         }
455     }
456 }
457
458 static void
459 process_echo_request(struct lswitch *sw, struct rconn *rconn, void *rq_)
460 {
461     struct ofp_header *rq = rq_;
462     queue_tx(sw, rconn, make_echo_reply(rq));
463 }