poll-loop: New function poll_timer_wait_until().
[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 "flow.h"
27 #include "mac-learning.h"
28 #include "ofpbuf.h"
29 #include "ofp-print.h"
30 #include "openflow/openflow.h"
31 #include "poll-loop.h"
32 #include "queue.h"
33 #include "rconn.h"
34 #include "stp.h"
35 #include "timeval.h"
36 #include "vconn.h"
37 #include "xtoxll.h"
38
39 #define THIS_MODULE VLM_learning_switch
40 #include "vlog.h"
41
42 enum port_state {
43     P_DISABLED = 1 << 0,
44     P_LISTENING = 1 << 1,
45     P_LEARNING = 1 << 2,
46     P_FORWARDING = 1 << 3,
47     P_BLOCKING = 1 << 4
48 };
49
50 struct lswitch {
51     /* If nonnegative, the switch sets up flows that expire after the given
52      * number of seconds (or never expire, if the value is OFP_FLOW_PERMANENT).
53      * Otherwise, the switch processes every packet. */
54     int max_idle;
55
56     unsigned long long int datapath_id;
57     uint32_t capabilities;
58     time_t last_features_request;
59     struct mac_learning *ml;    /* NULL to act as hub instead of switch. */
60     bool exact_flows;           /* Use exact-match flows? */
61     bool action_normal;         /* Use OFPP_NORMAL? */
62
63     /* Number of outgoing queued packets on the rconn. */
64     struct rconn_packet_counter *queued;
65
66     /* Spanning tree protocol implementation.
67      *
68      * We implement STP states by, whenever a port's STP state changes,
69      * querying all the flows on the switch and then deleting any of them that
70      * are inappropriate for a port's STP state. */
71     long long int next_query;   /* Next time at which to query all flows. */
72     long long int last_query;   /* Last time we sent a query. */
73     long long int last_reply;   /* Last time we received a query reply. */
74     unsigned int port_states[STP_MAX_PORTS];
75     uint32_t query_xid;         /* XID used for query. */
76     int n_flows, n_no_recv, n_no_send;
77 };
78
79 /* The log messages here could actually be useful in debugging, so keep the
80  * rate limit relatively high. */
81 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
82
83 static void queue_tx(struct lswitch *, struct rconn *, struct ofpbuf *);
84 static void send_features_request(struct lswitch *, struct rconn *);
85 static void schedule_query(struct lswitch *, long long int delay);
86 static bool may_learn(const struct lswitch *, uint16_t port_no);
87 static bool may_recv(const struct lswitch *, uint16_t port_no,
88                      bool any_actions);
89 static bool may_send(const struct lswitch *, uint16_t port_no);
90
91 typedef void packet_handler_func(struct lswitch *, struct rconn *, void *);
92 static packet_handler_func process_switch_features;
93 static packet_handler_func process_packet_in;
94 static packet_handler_func process_echo_request;
95 static packet_handler_func process_port_status;
96 static packet_handler_func process_phy_port;
97 static packet_handler_func process_stats_reply;
98
99 /* Creates and returns a new learning switch.
100  *
101  * If 'learn_macs' is true, the new switch will learn the ports on which MAC
102  * addresses appear.  Otherwise, the new switch will flood all packets.
103  *
104  * If 'max_idle' is nonnegative, the new switch will set up flows that expire
105  * after the given number of seconds (or never expire, if 'max_idle' is
106  * OFP_FLOW_PERMANENT).  Otherwise, the new switch will process every packet.
107  *
108  * 'rconn' is used to send out an OpenFlow features request. */
109 struct lswitch *
110 lswitch_create(struct rconn *rconn, bool learn_macs,
111                bool exact_flows, int max_idle, bool action_normal)
112 {
113     struct lswitch *sw;
114     size_t i;
115
116     sw = xzalloc(sizeof *sw);
117     sw->max_idle = max_idle;
118     sw->datapath_id = 0;
119     sw->last_features_request = time_now() - 1;
120     sw->ml = learn_macs ? mac_learning_create() : NULL;
121     sw->action_normal = action_normal;
122     sw->exact_flows = exact_flows;
123     sw->queued = rconn_packet_counter_create();
124     sw->next_query = LLONG_MIN;
125     sw->last_query = LLONG_MIN;
126     sw->last_reply = LLONG_MIN;
127     for (i = 0; i < STP_MAX_PORTS; i++) {
128         sw->port_states[i] = P_DISABLED;
129     }
130     send_features_request(sw, rconn);
131     return sw;
132 }
133
134 /* Destroys 'sw'. */
135 void
136 lswitch_destroy(struct lswitch *sw)
137 {
138     if (sw) {
139         mac_learning_destroy(sw->ml);
140         rconn_packet_counter_destroy(sw->queued);
141         free(sw);
142     }
143 }
144
145 /* Takes care of necessary 'sw' activity, except for receiving packets (which
146  * the caller must do). */
147 void
148 lswitch_run(struct lswitch *sw, struct rconn *rconn)
149 {
150     long long int now = time_msec();
151
152     if (sw->ml) {
153         mac_learning_run(sw->ml, NULL);
154     }
155
156     /* If we're waiting for more replies, keeping waiting for up to 10 s. */
157     if (sw->last_reply != LLONG_MIN) {
158         if (now - sw->last_reply > 10000) {
159             VLOG_ERR_RL(&rl, "%016llx: No more flow stat replies last 10 s",
160                         sw->datapath_id);
161             sw->last_reply = LLONG_MIN;
162             sw->last_query = LLONG_MIN;
163             schedule_query(sw, 0);
164         } else {
165             return;
166         }
167     }
168
169     /* If we're waiting for any reply at all, keep waiting for up to 10 s. */
170     if (sw->last_query != LLONG_MIN) {
171         if (now - sw->last_query > 10000) {
172             VLOG_ERR_RL(&rl, "%016llx: No flow stat replies in last 10 s",
173                         sw->datapath_id);
174             sw->last_query = LLONG_MIN;
175             schedule_query(sw, 0);
176         } else {
177             return;
178         }
179     }
180
181     /* If it's time to send another query, do so. */
182     if (sw->next_query != LLONG_MIN && now >= sw->next_query) {
183         sw->next_query = LLONG_MIN;
184         if (!rconn_is_connected(rconn)) {
185             schedule_query(sw, 1000);
186         } else {
187             struct ofp_stats_request *osr;
188             struct ofp_flow_stats_request *ofsr;
189             struct ofpbuf *b;
190             int error;
191
192             VLOG_DBG("%016llx: Sending flow stats request to implement STP",
193                      sw->datapath_id);
194
195             sw->last_query = now;
196             sw->query_xid = random_uint32();
197             sw->n_flows = 0;
198             sw->n_no_recv = 0;
199             sw->n_no_send = 0;
200             osr = make_openflow_xid(sizeof *osr + sizeof *ofsr,
201                                     OFPT_STATS_REQUEST, sw->query_xid, &b);
202             osr->type = htons(OFPST_FLOW);
203             osr->flags = htons(0);
204             ofsr = (struct ofp_flow_stats_request *) osr->body;
205             ofsr->match.wildcards = htonl(OFPFW_ALL);
206             ofsr->table_id = 0xff;
207             ofsr->out_port = htons(OFPP_NONE);
208
209             error = rconn_send(rconn, b, NULL);
210             if (error) {
211                 VLOG_WARN_RL(&rl, "%016llx: sending flow stats request "
212                              "failed: %s", sw->datapath_id, strerror(error));
213                 ofpbuf_delete(b);
214                 schedule_query(sw, 1000);
215             }
216         }
217     }
218 }
219
220 static void
221 wait_timeout(long long int started)
222 {
223     poll_timer_wait_until(started + 10000);
224 }
225
226 void
227 lswitch_wait(struct lswitch *sw)
228 {
229     if (sw->ml) {
230         mac_learning_wait(sw->ml);
231     }
232
233     if (sw->last_reply != LLONG_MIN) {
234         wait_timeout(sw->last_reply);
235     } else if (sw->last_query != LLONG_MIN) {
236         wait_timeout(sw->last_query);
237     }
238 }
239
240 /* Processes 'msg', which should be an OpenFlow received on 'rconn', according
241  * to the learning switch state in 'sw'.  The most likely result of processing
242  * is that flow-setup and packet-out OpenFlow messages will be sent out on
243  * 'rconn'.  */
244 void
245 lswitch_process_packet(struct lswitch *sw, struct rconn *rconn,
246                        const struct ofpbuf *msg)
247 {
248     struct processor {
249         uint8_t type;
250         size_t min_size;
251         packet_handler_func *handler;
252     };
253     static const struct processor processors[] = {
254         {
255             OFPT_ECHO_REQUEST,
256             sizeof(struct ofp_header),
257             process_echo_request
258         },
259         {
260             OFPT_FEATURES_REPLY,
261             sizeof(struct ofp_switch_features),
262             process_switch_features
263         },
264         {
265             OFPT_PACKET_IN,
266             offsetof(struct ofp_packet_in, data),
267             process_packet_in
268         },
269         {
270             OFPT_PORT_STATUS,
271             sizeof(struct ofp_port_status),
272             process_port_status
273         },
274         {
275             OFPT_STATS_REPLY,
276             offsetof(struct ofp_stats_reply, body),
277             process_stats_reply
278         },
279         {
280             OFPT_FLOW_REMOVED,
281             sizeof(struct ofp_flow_removed),
282             NULL
283         },
284     };
285     const size_t n_processors = ARRAY_SIZE(processors);
286     const struct processor *p;
287     struct ofp_header *oh;
288
289     oh = msg->data;
290     if (sw->datapath_id == 0
291         && oh->type != OFPT_ECHO_REQUEST
292         && oh->type != OFPT_FEATURES_REPLY) {
293         send_features_request(sw, rconn);
294         return;
295     }
296
297     for (p = processors; p < &processors[n_processors]; p++) {
298         if (oh->type == p->type) {
299             if (msg->size < p->min_size) {
300                 VLOG_WARN_RL(&rl, "%016llx: %s: too short (%zu bytes) for "
301                              "type %"PRIu8" (min %zu)", sw->datapath_id,
302                              rconn_get_name(rconn), msg->size, oh->type,
303                              p->min_size);
304                 return;
305             }
306             if (p->handler) {
307                 (p->handler)(sw, rconn, msg->data);
308             }
309             return;
310         }
311     }
312     if (VLOG_IS_DBG_ENABLED()) {
313         char *p = ofp_to_string(msg->data, msg->size, 2);
314         VLOG_DBG_RL(&rl, "%016llx: OpenFlow packet ignored: %s",
315                     sw->datapath_id, p);
316         free(p);
317     }
318 }
319 \f
320 static void
321 send_features_request(struct lswitch *sw, struct rconn *rconn)
322 {
323     time_t now = time_now();
324     if (now >= sw->last_features_request + 1) {
325         struct ofpbuf *b;
326         struct ofp_switch_config *osc;
327
328         /* Send OFPT_FEATURES_REQUEST. */
329         make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &b);
330         queue_tx(sw, rconn, b);
331
332         /* Send OFPT_SET_CONFIG. */
333         osc = make_openflow(sizeof *osc, OFPT_SET_CONFIG, &b);
334         osc->miss_send_len = htons(OFP_DEFAULT_MISS_SEND_LEN);
335         queue_tx(sw, rconn, b);
336
337         sw->last_features_request = now;
338     }
339 }
340
341 static void
342 queue_tx(struct lswitch *sw, struct rconn *rconn, struct ofpbuf *b)
343 {
344     int retval = rconn_send_with_limit(rconn, b, sw->queued, 10);
345     if (retval && retval != ENOTCONN) {
346         if (retval == EAGAIN) {
347             VLOG_INFO_RL(&rl, "%016llx: %s: tx queue overflow",
348                          sw->datapath_id, rconn_get_name(rconn));
349         } else {
350             VLOG_WARN_RL(&rl, "%016llx: %s: send: %s",
351                          sw->datapath_id, rconn_get_name(rconn),
352                          strerror(retval));
353         }
354     }
355 }
356
357 static void
358 schedule_query(struct lswitch *sw, long long int delay)
359 {
360     long long int now = time_msec();
361     if (sw->next_query == LLONG_MIN || sw->next_query > now + delay) {
362         sw->next_query = now + delay;
363     }
364 }
365
366 static void
367 process_switch_features(struct lswitch *sw, struct rconn *rconn, void *osf_)
368 {
369     struct ofp_switch_features *osf = osf_;
370     size_t n_ports = ((ntohs(osf->header.length)
371                        - offsetof(struct ofp_switch_features, ports))
372                       / sizeof *osf->ports);
373     size_t i;
374
375     sw->datapath_id = ntohll(osf->datapath_id);
376     sw->capabilities = ntohl(osf->capabilities);
377     for (i = 0; i < n_ports; i++) {
378         process_phy_port(sw, rconn, &osf->ports[i]);
379     }
380     if (sw->capabilities & OFPC_STP) {
381         schedule_query(sw, 1000);
382     }
383 }
384
385 static void
386 process_packet_in(struct lswitch *sw, struct rconn *rconn, void *opi_)
387 {
388     struct ofp_packet_in *opi = opi_;
389     uint16_t in_port = ntohs(opi->in_port);
390     uint16_t out_port = OFPP_FLOOD;
391
392     size_t pkt_ofs, pkt_len;
393     struct ofpbuf pkt;
394     flow_t flow;
395
396     /* Extract flow data from 'opi' into 'flow'. */
397     pkt_ofs = offsetof(struct ofp_packet_in, data);
398     pkt_len = ntohs(opi->header.length) - pkt_ofs;
399     pkt.data = opi->data;
400     pkt.size = pkt_len;
401     flow_extract(&pkt, 0, in_port, &flow);
402
403     if (may_learn(sw, in_port) && sw->ml) {
404         if (mac_learning_learn(sw->ml, flow.dl_src, 0, in_port)) {
405             VLOG_DBG_RL(&rl, "%016llx: learned that "ETH_ADDR_FMT" is on "
406                         "port %"PRIu16, sw->datapath_id,
407                         ETH_ADDR_ARGS(flow.dl_src), in_port);
408         }
409     }
410
411     if (eth_addr_is_reserved(flow.dl_src)) {
412         goto drop_it;
413     }
414
415     if (!may_recv(sw, in_port, false)) {
416         /* STP prevents receiving anything on this port. */
417         goto drop_it;
418     }
419
420     if (sw->ml) {
421         int learned_port = mac_learning_lookup(sw->ml, flow.dl_dst, 0);
422         if (learned_port >= 0 && may_send(sw, learned_port)) {
423             out_port = learned_port;
424         }
425     }
426
427     if (in_port == out_port) {
428         /* Don't send out packets on their input ports. */
429         goto drop_it;
430     } else if (sw->max_idle >= 0 && (!sw->ml || out_port != OFPP_FLOOD)) {
431         struct ofpbuf *buffer;
432         struct ofp_flow_mod *ofm;
433         uint32_t wildcards;
434
435         /* Check if we need to wildcard the flows. */
436         if (!sw->exact_flows) {
437             /* We can not wildcard all fields.
438              * We need in_port to detect moves.
439              * We need both SA and DA to do learning. */
440             wildcards = (OFPFW_DL_TYPE | OFPFW_NW_SRC_MASK | OFPFW_NW_DST_MASK
441                          | OFPFW_NW_PROTO | OFPFW_TP_SRC | OFPFW_TP_DST);
442         } else {
443             /* Exact match */
444             wildcards = 0;
445         }
446
447         /* Check if we need to use "NORMAL" action. */
448         if (sw->action_normal && out_port != OFPP_FLOOD) {
449             out_port = OFPP_NORMAL;
450         }
451
452         /* The output port is known, or we always flood everything, so add a
453          * new flow. */
454         buffer = make_add_simple_flow(&flow, ntohl(opi->buffer_id),
455                                       out_port, sw->max_idle);
456         ofm = buffer->data;
457         ofm->match.wildcards = htonl(wildcards);
458         queue_tx(sw, rconn, buffer);
459
460         /* If the switch didn't buffer the packet, we need to send a copy. */
461         if (ntohl(opi->buffer_id) == UINT32_MAX) {
462             queue_tx(sw, rconn,
463                      make_unbuffered_packet_out(&pkt, in_port, out_port));
464         }
465     } else {
466         struct ofpbuf *b;
467
468         /* Check if we need to use "NORMAL" action. */
469         if (sw->action_normal && out_port != OFPP_FLOOD) {
470             out_port = OFPP_NORMAL;
471         }
472
473         /* We don't know that MAC, or we don't set up flows.  Send along the
474          * packet without setting up a flow. */
475         if (ntohl(opi->buffer_id) == UINT32_MAX) {
476             b = make_unbuffered_packet_out(&pkt, in_port, out_port);
477         } else {
478             b = make_buffered_packet_out(ntohl(opi->buffer_id),
479                                          in_port, out_port);
480         }
481         queue_tx(sw, rconn, b);
482     }
483     return;
484
485 drop_it:
486     if (sw->max_idle >= 0) {
487         /* Set up a flow to drop packets. */
488         queue_tx(sw, rconn, make_add_flow(&flow, ntohl(opi->buffer_id),
489                                           sw->max_idle, 0));
490     } else {
491         /* Just drop the packet, since we don't set up flows at all.
492          * XXX we should send a packet_out with no actions if buffer_id !=
493          * UINT32_MAX, to avoid clogging the kernel buffers. */
494     }
495     return;
496 }
497
498 static void
499 process_echo_request(struct lswitch *sw, struct rconn *rconn, void *rq_)
500 {
501     struct ofp_header *rq = rq_;
502     queue_tx(sw, rconn, make_echo_reply(rq));
503 }
504
505 static void
506 process_port_status(struct lswitch *sw, struct rconn *rconn, void *ops_)
507 {
508     struct ofp_port_status *ops = ops_;
509     process_phy_port(sw, rconn, &ops->desc);
510 }
511
512 static void
513 process_phy_port(struct lswitch *sw, struct rconn *rconn OVS_UNUSED,
514                  void *opp_)
515 {
516     const struct ofp_phy_port *opp = opp_;
517     uint16_t port_no = ntohs(opp->port_no);
518     if (sw->capabilities & OFPC_STP && port_no < STP_MAX_PORTS) {
519         uint32_t config = ntohl(opp->config);
520         uint32_t state = ntohl(opp->state);
521         unsigned int *port_state = &sw->port_states[port_no];
522         unsigned int new_port_state;
523
524         if (!(config & (OFPPC_NO_STP | OFPPC_PORT_DOWN))
525             && !(state & OFPPS_LINK_DOWN))
526         {
527             switch (state & OFPPS_STP_MASK) {
528             case OFPPS_STP_LISTEN:
529                 new_port_state = P_LISTENING;
530                 break;
531             case OFPPS_STP_LEARN:
532                 new_port_state = P_LEARNING;
533                 break;
534             case OFPPS_STP_FORWARD:
535                 new_port_state = P_FORWARDING;
536                 break;
537             case OFPPS_STP_BLOCK:
538                 new_port_state = P_BLOCKING;
539                 break;
540             default:
541                 new_port_state = P_DISABLED;
542                 break;
543             }
544         } else {
545             new_port_state = P_FORWARDING;
546         }
547         if (*port_state != new_port_state) {
548             *port_state = new_port_state;
549             schedule_query(sw, 1000);
550         }
551     }
552 }
553
554 static unsigned int
555 get_port_state(const struct lswitch *sw, uint16_t port_no)
556 {
557     return (port_no >= STP_MAX_PORTS || !(sw->capabilities & OFPC_STP)
558             ? P_FORWARDING
559             : sw->port_states[port_no]);
560 }
561
562 static bool
563 may_learn(const struct lswitch *sw, uint16_t port_no)
564 {
565     return get_port_state(sw, port_no) & (P_LEARNING | P_FORWARDING);
566 }
567
568 static bool
569 may_recv(const struct lswitch *sw, uint16_t port_no, bool any_actions)
570 {
571     unsigned int state = get_port_state(sw, port_no);
572     return !(any_actions
573              ? state & (P_DISABLED | P_LISTENING | P_BLOCKING)
574              : state & (P_DISABLED | P_LISTENING | P_BLOCKING | P_LEARNING));
575 }
576
577 static bool
578 may_send(const struct lswitch *sw, uint16_t port_no)
579 {
580     return get_port_state(sw, port_no) & P_FORWARDING;
581 }
582
583 static void
584 process_flow_stats(struct lswitch *sw, struct rconn *rconn,
585                    const struct ofp_flow_stats *ofs)
586 {
587     const char *end = (char *) ofs + ntohs(ofs->length);
588     bool delete = false;
589
590     /* Decide to delete the flow if it matches on an STP-disabled physical
591      * port.  But don't delete it if the flow just drops all received packets,
592      * because that's a perfectly reasonable thing to do for disabled physical
593      * ports. */
594     if (!(ofs->match.wildcards & htonl(OFPFW_IN_PORT))) {
595         if (!may_recv(sw, ntohs(ofs->match.in_port),
596                       end > (char *) ofs->actions)) {
597             delete = true;
598             sw->n_no_recv++;
599         }
600     }
601
602     /* Decide to delete the flow if it forwards to an STP-disabled physical
603      * port. */
604     if (!delete) {
605         const struct ofp_action_header *a;
606         size_t len;
607
608         for (a = ofs->actions; (char *) a < end; a += len / 8) {
609             len = ntohs(a->len);
610             if (len > end - (char *) a) {
611                 VLOG_DBG_RL(&rl, "%016llx: action exceeds available space "
612                             "(%zu > %td)",
613                             sw->datapath_id, len, end - (char *) a);
614                 break;
615             } else if (len % 8) {
616                 VLOG_DBG_RL(&rl, "%016llx: action length (%zu) not multiple "
617                             "of 8 bytes", sw->datapath_id, len);
618                 break;
619             }
620
621             if (a->type == htons(OFPAT_OUTPUT)) {
622                 struct ofp_action_output *oao = (struct ofp_action_output *) a;
623                 if (!may_send(sw, ntohs(oao->port))) {
624                     delete = true;
625                     sw->n_no_send++;
626                     break;
627                 }
628             }
629         }
630     }
631
632     /* Delete the flow. */
633     if (delete) {
634         struct ofp_flow_mod *ofm;
635         struct ofpbuf *b;
636
637         ofm = make_openflow(offsetof(struct ofp_flow_mod, actions),
638                             OFPT_FLOW_MOD, &b);
639         ofm->match = ofs->match;
640         ofm->command = OFPFC_DELETE_STRICT;
641         rconn_send(rconn, b, NULL);
642     }
643 }
644
645 static void
646 process_stats_reply(struct lswitch *sw, struct rconn *rconn, void *osr_)
647 {
648     struct ofp_stats_reply *osr = osr_;
649     struct flow_stats_iterator i;
650     const struct ofp_flow_stats *fs;
651
652     if (sw->last_query == LLONG_MIN
653         || osr->type != htons(OFPST_FLOW)
654         || osr->header.xid != sw->query_xid) {
655         return;
656     }
657     for (fs = flow_stats_first(&i, osr); fs; fs = flow_stats_next(&i)) {
658         sw->n_flows++;
659         process_flow_stats(sw, rconn, fs);
660     }
661     if (!(osr->flags & htons(OFPSF_REPLY_MORE))) {
662         VLOG_DBG("%016llx: Deleted %d of %d received flows to "
663                  "implement STP, %d because of no-recv, %d because of "
664                  "no-send", sw->datapath_id,
665                  sw->n_no_recv + sw->n_no_send, sw->n_flows,
666                  sw->n_no_recv, sw->n_no_send);
667         sw->last_query = LLONG_MIN;
668         sw->last_reply = LLONG_MIN;
669     } else {
670         sw->last_reply = time_msec();
671     }
672 }
673