ofp-parse: Factor out duplicated code into new functions.
[openvswitch] / 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 "flow.h"
27 #include "mac-learning.h"
28 #include "ofpbuf.h"
29 #include "ofp-parse.h"
30 #include "ofp-print.h"
31 #include "ofp-util.h"
32 #include "openflow/openflow.h"
33 #include "poll-loop.h"
34 #include "queue.h"
35 #include "rconn.h"
36 #include "timeval.h"
37 #include "vconn.h"
38 #include "vlog.h"
39 #include "xtoxll.h"
40
41 VLOG_DEFINE_THIS_MODULE(learning_switch)
42
43 struct lswitch {
44     /* If nonnegative, the switch sets up flows that expire after the given
45      * number of seconds (or never expire, if the value is OFP_FLOW_PERMANENT).
46      * Otherwise, the switch processes every packet. */
47     int max_idle;
48
49     unsigned long long int datapath_id;
50     time_t last_features_request;
51     struct mac_learning *ml;    /* NULL to act as hub instead of switch. */
52     uint32_t wildcards;         /* Wildcards to apply to flows. */
53     bool action_normal;         /* Use OFPP_NORMAL? */
54     uint32_t queue;             /* OpenFlow queue to use, or UINT32_MAX. */
55
56     /* Number of outgoing queued packets on the rconn. */
57     struct rconn_packet_counter *queued;
58 };
59
60 /* The log messages here could actually be useful in debugging, so keep the
61  * rate limit relatively high. */
62 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
63
64 static void queue_tx(struct lswitch *, struct rconn *, struct ofpbuf *);
65 static void send_features_request(struct lswitch *, struct rconn *);
66 static void send_default_flows(struct lswitch *sw, struct rconn *rconn,
67                                FILE *default_flows);
68
69 typedef void packet_handler_func(struct lswitch *, struct rconn *, void *);
70 static packet_handler_func process_switch_features;
71 static packet_handler_func process_packet_in;
72 static packet_handler_func process_echo_request;
73
74 /* Creates and returns a new learning switch.
75  *
76  * If 'learn_macs' is true, the new switch will learn the ports on which MAC
77  * addresses appear.  Otherwise, the new switch will flood all packets.
78  *
79  * If 'max_idle' is nonnegative, the new switch will set up flows that expire
80  * after the given number of seconds (or never expire, if 'max_idle' is
81  * OFP_FLOW_PERMANENT).  Otherwise, the new switch will process every packet.
82  *
83  * The caller may provide the file stream 'default_flows' that defines
84  * default flows that should be pushed when a switch connects.  Each
85  * line is a flow entry in the format described for "add-flows" command
86  * in the Flow Syntax section of the ovs-ofct(8) man page.  The caller
87  * is responsible for closing the stream.
88  *
89  * 'rconn' is used to send out an OpenFlow features request. */
90 struct lswitch *
91 lswitch_create(struct rconn *rconn, bool learn_macs,
92                bool exact_flows, int max_idle, bool action_normal,
93                FILE *default_flows)
94 {
95     struct lswitch *sw;
96
97     sw = xzalloc(sizeof *sw);
98     sw->max_idle = max_idle;
99     sw->datapath_id = 0;
100     sw->last_features_request = time_now() - 1;
101     sw->ml = learn_macs ? mac_learning_create() : NULL;
102     sw->action_normal = action_normal;
103     if (exact_flows) {
104         /* Exact match. */
105         sw->wildcards = 0;
106     } else {
107         /* We cannot wildcard all fields.
108          * We need in_port to detect moves.
109          * We need both SA and DA to do learning. */
110         sw->wildcards = (OFPFW_DL_TYPE | OFPFW_NW_SRC_MASK | OFPFW_NW_DST_MASK
111                          | OFPFW_NW_PROTO | OFPFW_TP_SRC | OFPFW_TP_DST);
112     }
113     sw->queue = UINT32_MAX;
114     sw->queued = rconn_packet_counter_create();
115     send_features_request(sw, rconn);
116     if (default_flows) {
117         send_default_flows(sw, rconn, default_flows);
118     }
119     return sw;
120 }
121
122 /* Destroys 'sw'. */
123 void
124 lswitch_destroy(struct lswitch *sw)
125 {
126     if (sw) {
127         mac_learning_destroy(sw->ml);
128         rconn_packet_counter_destroy(sw->queued);
129         free(sw);
130     }
131 }
132
133 /* Sets 'queue' as the OpenFlow queue used by packets and flows set up by 'sw'.
134  * Specify UINT32_MAX to avoid specifying a particular queue, which is also the
135  * default if this function is never called for 'sw'.  */
136 void
137 lswitch_set_queue(struct lswitch *sw, uint32_t queue)
138 {
139     sw->queue = queue;
140 }
141
142 /* Takes care of necessary 'sw' activity, except for receiving packets (which
143  * the caller must do). */
144 void
145 lswitch_run(struct lswitch *sw)
146 {
147     if (sw->ml) {
148         mac_learning_run(sw->ml, NULL);
149     }
150 }
151
152 void
153 lswitch_wait(struct lswitch *sw)
154 {
155     if (sw->ml) {
156         mac_learning_wait(sw->ml);
157     }
158 }
159
160 /* Processes 'msg', which should be an OpenFlow received on 'rconn', according
161  * to the learning switch state in 'sw'.  The most likely result of processing
162  * is that flow-setup and packet-out OpenFlow messages will be sent out on
163  * 'rconn'.  */
164 void
165 lswitch_process_packet(struct lswitch *sw, struct rconn *rconn,
166                        const struct ofpbuf *msg)
167 {
168     struct processor {
169         uint8_t type;
170         size_t min_size;
171         packet_handler_func *handler;
172     };
173     static const struct processor processors[] = {
174         {
175             OFPT_ECHO_REQUEST,
176             sizeof(struct ofp_header),
177             process_echo_request
178         },
179         {
180             OFPT_FEATURES_REPLY,
181             sizeof(struct ofp_switch_features),
182             process_switch_features
183         },
184         {
185             OFPT_PACKET_IN,
186             offsetof(struct ofp_packet_in, data),
187             process_packet_in
188         },
189         {
190             OFPT_FLOW_REMOVED,
191             sizeof(struct ofp_flow_removed),
192             NULL
193         },
194     };
195     const size_t n_processors = ARRAY_SIZE(processors);
196     const struct processor *p;
197     struct ofp_header *oh;
198
199     oh = msg->data;
200     if (sw->datapath_id == 0
201         && oh->type != OFPT_ECHO_REQUEST
202         && oh->type != OFPT_FEATURES_REPLY) {
203         send_features_request(sw, rconn);
204         return;
205     }
206
207     for (p = processors; p < &processors[n_processors]; p++) {
208         if (oh->type == p->type) {
209             if (msg->size < p->min_size) {
210                 VLOG_WARN_RL(&rl, "%016llx: %s: too short (%zu bytes) for "
211                              "type %"PRIu8" (min %zu)", sw->datapath_id,
212                              rconn_get_name(rconn), msg->size, oh->type,
213                              p->min_size);
214                 return;
215             }
216             if (p->handler) {
217                 (p->handler)(sw, rconn, msg->data);
218             }
219             return;
220         }
221     }
222     if (VLOG_IS_DBG_ENABLED()) {
223         char *s = ofp_to_string(msg->data, msg->size, 2);
224         VLOG_DBG_RL(&rl, "%016llx: OpenFlow packet ignored: %s",
225                     sw->datapath_id, s);
226         free(s);
227     }
228 }
229 \f
230 static void
231 send_features_request(struct lswitch *sw, struct rconn *rconn)
232 {
233     time_t now = time_now();
234     if (now >= sw->last_features_request + 1) {
235         struct ofpbuf *b;
236         struct ofp_switch_config *osc;
237
238         /* Send OFPT_FEATURES_REQUEST. */
239         make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &b);
240         queue_tx(sw, rconn, b);
241
242         /* Send OFPT_SET_CONFIG. */
243         osc = make_openflow(sizeof *osc, OFPT_SET_CONFIG, &b);
244         osc->miss_send_len = htons(OFP_DEFAULT_MISS_SEND_LEN);
245         queue_tx(sw, rconn, b);
246
247         sw->last_features_request = now;
248     }
249 }
250
251 static void
252 send_default_flows(struct lswitch *sw, struct rconn *rconn,
253                    FILE *default_flows)
254 {
255     struct ofpbuf *b;
256
257     while ((b = parse_ofp_add_flow_file(default_flows)) != NULL) {
258         queue_tx(sw, rconn, b);
259     }
260 }
261
262 static void
263 queue_tx(struct lswitch *sw, struct rconn *rconn, struct ofpbuf *b)
264 {
265     int retval = rconn_send_with_limit(rconn, b, sw->queued, 10);
266     if (retval && retval != ENOTCONN) {
267         if (retval == EAGAIN) {
268             VLOG_INFO_RL(&rl, "%016llx: %s: tx queue overflow",
269                          sw->datapath_id, rconn_get_name(rconn));
270         } else {
271             VLOG_WARN_RL(&rl, "%016llx: %s: send: %s",
272                          sw->datapath_id, rconn_get_name(rconn),
273                          strerror(retval));
274         }
275     }
276 }
277
278 static void
279 process_switch_features(struct lswitch *sw, struct rconn *rconn OVS_UNUSED,
280                         void *osf_)
281 {
282     struct ofp_switch_features *osf = osf_;
283
284     sw->datapath_id = ntohll(osf->datapath_id);
285 }
286
287 static uint16_t
288 lswitch_choose_destination(struct lswitch *sw, const flow_t *flow)
289 {
290     uint16_t out_port;
291
292     /* Learn the source MAC. */
293     if (sw->ml) {
294         if (mac_learning_learn(sw->ml, flow->dl_src, 0, flow->in_port,
295                                GRAT_ARP_LOCK_NONE)) {
296             VLOG_DBG_RL(&rl, "%016llx: learned that "ETH_ADDR_FMT" is on "
297                         "port %"PRIu16, sw->datapath_id,
298                         ETH_ADDR_ARGS(flow->dl_src), flow->in_port);
299         }
300     }
301
302     /* Drop frames for reserved multicast addresses. */
303     if (eth_addr_is_reserved(flow->dl_dst)) {
304         return OFPP_NONE;
305     }
306
307     out_port = OFPP_FLOOD;
308     if (sw->ml) {
309         int learned_port = mac_learning_lookup(sw->ml, flow->dl_dst, 0, NULL);
310         if (learned_port >= 0) {
311             out_port = learned_port;
312             if (out_port == flow->in_port) {
313                 /* Don't send a packet back out its input port. */
314                 return OFPP_NONE;
315             }
316         }
317     }
318
319     /* Check if we need to use "NORMAL" action. */
320     if (sw->action_normal && out_port != OFPP_FLOOD) {
321         return OFPP_NORMAL;
322     }
323
324     return out_port;
325 }
326
327 static void
328 process_packet_in(struct lswitch *sw, struct rconn *rconn, void *opi_)
329 {
330     struct ofp_packet_in *opi = opi_;
331     uint16_t in_port = ntohs(opi->in_port);
332     uint16_t out_port;
333
334     struct ofp_action_header actions[2];
335     size_t actions_len;
336
337     size_t pkt_ofs, pkt_len;
338     struct ofpbuf pkt;
339     flow_t flow;
340
341     /* Ignore packets sent via output to OFPP_CONTROLLER.  This library never
342      * uses such an action.  You never know what experiments might be going on,
343      * though, and it seems best not to interfere with them. */
344     if (opi->reason != OFPR_NO_MATCH) {
345         return;
346     }
347
348     /* Extract flow data from 'opi' into 'flow'. */
349     pkt_ofs = offsetof(struct ofp_packet_in, data);
350     pkt_len = ntohs(opi->header.length) - pkt_ofs;
351     pkt.data = opi->data;
352     pkt.size = pkt_len;
353     flow_extract(&pkt, 0, in_port, &flow);
354
355     /* Choose output port. */
356     out_port = lswitch_choose_destination(sw, &flow);
357
358     /* Make actions. */
359     if (out_port == OFPP_NONE) {
360         actions_len = 0;
361     } else if (sw->queue == UINT32_MAX || out_port >= OFPP_MAX) {
362         struct ofp_action_output oao;
363
364         memset(&oao, 0, sizeof oao);
365         oao.type = htons(OFPAT_OUTPUT);
366         oao.len = htons(sizeof oao);
367         oao.port = htons(out_port);
368
369         memcpy(actions, &oao, sizeof oao);
370         actions_len = sizeof oao;
371     } else {
372         struct ofp_action_enqueue oae;
373
374         memset(&oae, 0, sizeof oae);
375         oae.type = htons(OFPAT_ENQUEUE);
376         oae.len = htons(sizeof oae);
377         oae.port = htons(out_port);
378         oae.queue_id = htonl(sw->queue);
379
380         memcpy(actions, &oae, sizeof oae);
381         actions_len = sizeof oae;
382     }
383     assert(actions_len <= sizeof actions);
384
385     /* Send the packet, and possibly the whole flow, to the output port. */
386     if (sw->max_idle >= 0 && (!sw->ml || out_port != OFPP_FLOOD)) {
387         struct ofpbuf *buffer;
388         struct ofp_flow_mod *ofm;
389
390         /* The output port is known, or we always flood everything, so add a
391          * new flow. */
392         buffer = make_add_flow(&flow, ntohl(opi->buffer_id),
393                                sw->max_idle, actions_len);
394         ofpbuf_put(buffer, actions, actions_len);
395         ofm = buffer->data;
396         ofm->match.wildcards = htonl(sw->wildcards);
397         queue_tx(sw, rconn, buffer);
398
399         /* If the switch didn't buffer the packet, we need to send a copy. */
400         if (ntohl(opi->buffer_id) == UINT32_MAX && actions_len > 0) {
401             queue_tx(sw, rconn,
402                      make_packet_out(&pkt, UINT32_MAX, in_port,
403                                      actions, actions_len / sizeof *actions));
404         }
405     } else {
406         /* We don't know that MAC, or we don't set up flows.  Send along the
407          * packet without setting up a flow. */
408         if (ntohl(opi->buffer_id) != UINT32_MAX || actions_len > 0) {
409             queue_tx(sw, rconn,
410                      make_packet_out(&pkt, ntohl(opi->buffer_id), in_port,
411                                      actions, actions_len / sizeof *actions));
412         }
413     }
414 }
415
416 static void
417 process_echo_request(struct lswitch *sw, struct rconn *rconn, void *rq_)
418 {
419     struct ofp_header *rq = rq_;
420     queue_tx(sw, rconn, make_echo_reply(rq));
421 }