1e88cba89a11bbb0a2c654e02ee56372a0f7d513
[cascardo/ovs.git] / lib / stp.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014 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 /* Based on sample implementation in 802.1D-1998.  Above copyright and license
18  * applies to all modifications. */
19
20 #include <config.h>
21
22 #include "stp.h"
23 #include <sys/types.h>
24 #include <netinet/in.h>
25 #include <arpa/inet.h>
26 #include <inttypes.h>
27 #include <stdlib.h>
28 #include "byte-order.h"
29 #include "connectivity.h"
30 #include "ofpbuf.h"
31 #include "ovs-atomic.h"
32 #include "packets.h"
33 #include "seq.h"
34 #include "unixctl.h"
35 #include "util.h"
36 #include "openvswitch/vlog.h"
37
38 VLOG_DEFINE_THIS_MODULE(stp);
39
40 static struct vlog_rate_limit stp_rl = VLOG_RATE_LIMIT_INIT(60, 60);
41
42 #define STP_PROTOCOL_ID 0x0000
43 #define STP_PROTOCOL_VERSION 0x00
44 #define STP_TYPE_CONFIG 0x00
45 #define STP_TYPE_TCN 0x80
46
47 OVS_PACKED(
48 struct stp_bpdu_header {
49     ovs_be16 protocol_id;       /* STP_PROTOCOL_ID. */
50     uint8_t protocol_version;   /* STP_PROTOCOL_VERSION. */
51     uint8_t bpdu_type;          /* One of STP_TYPE_*. */
52 });
53 BUILD_ASSERT_DECL(sizeof(struct stp_bpdu_header) == 4);
54
55 enum stp_config_bpdu_flags {
56     STP_CONFIG_TOPOLOGY_CHANGE_ACK = 0x80,
57     STP_CONFIG_TOPOLOGY_CHANGE = 0x01
58 };
59
60 OVS_PACKED(
61 struct stp_config_bpdu {
62     struct stp_bpdu_header header; /* Type STP_TYPE_CONFIG. */
63     uint8_t flags;                 /* STP_CONFIG_* flags. */
64     ovs_be64 root_id;              /* 8.5.1.1: Bridge believed to be root. */
65     ovs_be32 root_path_cost;       /* 8.5.1.2: Cost of path to root. */
66     ovs_be64 bridge_id;            /* 8.5.1.3: ID of transmitting bridge. */
67     ovs_be16 port_id;              /* 8.5.1.4: Port transmitting the BPDU. */
68     ovs_be16 message_age;          /* 8.5.1.5: Age of BPDU at tx time. */
69     ovs_be16 max_age;              /* 8.5.1.6: Timeout for received data. */
70     ovs_be16 hello_time;           /* 8.5.1.7: Time between BPDU generation. */
71     ovs_be16 forward_delay;        /* 8.5.1.8: State progression delay. */
72 });
73 BUILD_ASSERT_DECL(sizeof(struct stp_config_bpdu) == 35);
74
75 OVS_PACKED(
76 struct stp_tcn_bpdu {
77     struct stp_bpdu_header header; /* Type STP_TYPE_TCN. */
78 });
79 BUILD_ASSERT_DECL(sizeof(struct stp_tcn_bpdu) == 4);
80
81 struct stp_timer {
82     bool active;                 /* Timer in use? */
83     int value;                   /* Current value of timer, counting up. */
84 };
85
86 struct stp_port {
87     struct stp *stp;
88     char *port_name;                /* Human-readable name for log messages. */
89     void *aux;                      /* Auxiliary data the user may retrieve. */
90     int port_id;                    /* 8.5.5.1: Unique port identifier. */
91     enum stp_state state;           /* 8.5.5.2: Current state. */
92     int path_cost;                  /* 8.5.5.3: Cost of tx/rx on this port. */
93     stp_identifier designated_root; /* 8.5.5.4. */
94     int designated_cost;            /* 8.5.5.5: Path cost to root on port. */
95     stp_identifier designated_bridge; /* 8.5.5.6. */
96     int designated_port;            /* 8.5.5.7: Port to send config msgs on. */
97     bool topology_change_ack;       /* 8.5.5.8: Flag for next config BPDU. */
98     bool config_pending;            /* 8.5.5.9: Send BPDU when hold expires? */
99     bool change_detection_enabled;  /* 8.5.5.10: Detect topology changes? */
100
101     struct stp_timer message_age_timer; /* 8.5.6.1: Age of received info. */
102     struct stp_timer forward_delay_timer; /* 8.5.6.2: State change timer. */
103     struct stp_timer hold_timer;        /* 8.5.6.3: BPDU rate limit timer. */
104
105     int tx_count;                   /* Number of BPDUs transmitted. */
106     int rx_count;                   /* Number of valid BPDUs received. */
107     int error_count;                /* Number of bad BPDUs received. */
108
109     bool state_changed;
110 };
111
112 struct stp {
113     struct ovs_list node;           /* Node in all_stps list. */
114
115     /* Static bridge data. */
116     char *name;                     /* Human-readable name for log messages. */
117     stp_identifier bridge_id;       /* 8.5.3.7: This bridge. */
118     int max_age;                    /* 8.5.3.4: Time to drop received data. */
119     int hello_time;                 /* 8.5.3.5: Time between sending BPDUs. */
120     int forward_delay;              /* 8.5.3.6: Delay between state changes. */
121     int bridge_max_age;             /* 8.5.3.8: max_age when we're root. */
122     int bridge_hello_time;          /* 8.5.3.9: hello_time as root. */
123     int bridge_forward_delay;       /* 8.5.3.10: forward_delay as root. */
124     int rq_max_age;                 /* User-requested max age, in ms. */
125     int rq_hello_time;              /* User-requested hello time, in ms. */
126     int rq_forward_delay;           /* User-requested forward delay, in ms. */
127     int elapsed_remainder;          /* Left-over msecs from last stp_tick(). */
128
129     /* Dynamic bridge data. */
130     stp_identifier designated_root; /* 8.5.3.1: Bridge believed to be root. */
131     unsigned int root_path_cost;    /* 8.5.3.2: Cost of path to root. */
132     struct stp_port *root_port;     /* 8.5.3.3: Lowest cost port to root. */
133     bool topology_change_detected;  /* 8.5.3.11: Detected a topology change? */
134     bool topology_change;           /* 8.5.3.12: Received topology change? */
135
136     /* Bridge timers. */
137     struct stp_timer hello_timer;   /* 8.5.4.1: Hello timer. */
138     struct stp_timer tcn_timer;     /* 8.5.4.2: Topology change timer. */
139     struct stp_timer topology_change_timer; /* 8.5.4.3. */
140
141     /* Ports. */
142     struct stp_port ports[STP_MAX_PORTS];
143
144     /* Interface to client. */
145     bool fdb_needs_flush;          /* MAC learning tables needs flushing. */
146     struct stp_port *first_changed_port;
147     void (*send_bpdu)(struct ofpbuf *bpdu, int port_no, void *aux);
148     void *aux;
149
150     struct ovs_refcount ref_cnt;
151 };
152
153 static struct ovs_mutex mutex;
154 static struct ovs_list all_stps__ = OVS_LIST_INITIALIZER(&all_stps__);
155 static struct ovs_list *const all_stps OVS_GUARDED_BY(mutex) = &all_stps__;
156
157 #define FOR_EACH_ENABLED_PORT(PORT, STP)                        \
158     for ((PORT) = stp_next_enabled_port((STP), (STP)->ports);   \
159          (PORT);                                                \
160          (PORT) = stp_next_enabled_port((STP), (PORT) + 1))
161 static struct stp_port *
162 stp_next_enabled_port(const struct stp *stp, const struct stp_port *port)
163     OVS_REQUIRES(mutex)
164 {
165     for (; port < &stp->ports[ARRAY_SIZE(stp->ports)]; port++) {
166         if (port->state != STP_DISABLED) {
167             return CONST_CAST(struct stp_port *, port);
168         }
169     }
170     return NULL;
171 }
172
173 #define MESSAGE_AGE_INCREMENT 1
174
175 static void stp_transmit_config(struct stp_port *) OVS_REQUIRES(mutex);
176 static bool stp_supersedes_port_info(const struct stp_port *,
177                                      const struct stp_config_bpdu *)
178     OVS_REQUIRES(mutex);
179 static void stp_record_config_information(struct stp_port *,
180                                           const struct stp_config_bpdu *)
181     OVS_REQUIRES(mutex);
182 static void stp_record_config_timeout_values(struct stp *,
183                                              const struct stp_config_bpdu  *)
184     OVS_REQUIRES(mutex);
185 static bool stp_is_designated_port(const struct stp_port *)
186     OVS_REQUIRES(mutex);
187 static void stp_config_bpdu_generation(struct stp *) OVS_REQUIRES(mutex);
188 static void stp_transmit_tcn(struct stp *) OVS_REQUIRES(mutex);
189 static void stp_configuration_update(struct stp *) OVS_REQUIRES(mutex);
190 static bool stp_supersedes_root(const struct stp_port *root,
191                                 const struct stp_port *) OVS_REQUIRES(mutex);
192 static void stp_root_selection(struct stp *) OVS_REQUIRES(mutex);
193 static void stp_designated_port_selection(struct stp *) OVS_REQUIRES(mutex);
194 static void stp_become_designated_port(struct stp_port *)
195     OVS_REQUIRES(mutex);
196 static void stp_port_state_selection(struct stp *) OVS_REQUIRES(mutex);
197 static void stp_make_forwarding(struct stp_port *) OVS_REQUIRES(mutex);
198 static void stp_make_blocking(struct stp_port *) OVS_REQUIRES(mutex);
199 static void stp_set_port_state(struct stp_port *, enum stp_state)
200     OVS_REQUIRES(mutex);
201 static void stp_topology_change_detection(struct stp *) OVS_REQUIRES(mutex);
202 static void stp_topology_change_acknowledged(struct stp *)
203     OVS_REQUIRES(mutex);
204 static void stp_acknowledge_topology_change(struct stp_port *)
205     OVS_REQUIRES(mutex);
206 static void stp_received_config_bpdu(struct stp *, struct stp_port *,
207                                      const struct stp_config_bpdu *)
208     OVS_REQUIRES(mutex);
209 static void stp_received_tcn_bpdu(struct stp *, struct stp_port *)
210     OVS_REQUIRES(mutex);
211 static void stp_hello_timer_expiry(struct stp *) OVS_REQUIRES(mutex);
212 static void stp_message_age_timer_expiry(struct stp_port *)
213     OVS_REQUIRES(mutex);
214 static bool stp_is_designated_for_some_port(const struct stp *)
215     OVS_REQUIRES(mutex);
216 static void stp_forward_delay_timer_expiry(struct stp_port *)
217     OVS_REQUIRES(mutex);
218 static void stp_tcn_timer_expiry(struct stp *) OVS_REQUIRES(mutex);
219 static void stp_topology_change_timer_expiry(struct stp *)
220     OVS_REQUIRES(mutex);
221 static void stp_hold_timer_expiry(struct stp_port *) OVS_REQUIRES(mutex);
222 static void stp_initialize_port(struct stp_port *, enum stp_state)
223     OVS_REQUIRES(mutex);
224 static void stp_become_root_bridge(struct stp *) OVS_REQUIRES(mutex);
225 static void stp_update_bridge_timers(struct stp *) OVS_REQUIRES(mutex);
226
227 static int clamp(int x, int min, int max);
228 static int ms_to_timer(int ms);
229 static int timer_to_ms(int timer);
230 static void stp_start_timer(struct stp_timer *, int value);
231 static void stp_stop_timer(struct stp_timer *);
232 static bool stp_timer_expired(struct stp_timer *, int elapsed, int timeout);
233
234 static void stp_send_bpdu(struct stp_port *, const void *, size_t)
235     OVS_REQUIRES(mutex);
236 static void stp_unixctl_tcn(struct unixctl_conn *, int argc,
237                             const char *argv[], void *aux);
238
239 void
240 stp_init(void)
241 {
242     unixctl_command_register("stp/tcn", "[bridge]", 0, 1, stp_unixctl_tcn,
243                              NULL);
244 }
245
246 /* Creates and returns a new STP instance that initially has no ports enabled.
247  *
248  * 'bridge_id' should be a 48-bit MAC address as returned by
249  * eth_addr_to_uint64().  'bridge_id' may also have a priority value in its top
250  * 16 bits; if those bits are set to 0, STP_DEFAULT_BRIDGE_PRIORITY is used.
251  * (This priority may be changed with stp_set_bridge_priority().)
252  *
253  * When the bridge needs to send out a BPDU, it calls 'send_bpdu'.  This
254  * callback may be called from stp_tick() or stp_received_bpdu().  The
255  * arguments to 'send_bpdu' are an STP BPDU encapsulated in 'bpdu',
256  * the spanning tree port number 'port_no' that should transmit the
257  * packet, and auxiliary data to be passed to the callback in 'aux'.
258  */
259 struct stp *
260 stp_create(const char *name, stp_identifier bridge_id,
261            void (*send_bpdu)(struct ofpbuf *bpdu, int port_no, void *aux),
262            void *aux)
263 {
264     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
265     struct stp *stp;
266     struct stp_port *p;
267
268     if (ovsthread_once_start(&once)) {
269         /* We need a recursive mutex because stp_send_bpdu() could loop back
270          * into the stp module through a patch port.  This happens
271          * intentionally as part of the unit tests.  Ideally we'd ditch
272          * the call back function, but for now this is what we have. */
273         ovs_mutex_init_recursive(&mutex);
274         ovsthread_once_done(&once);
275     }
276
277     ovs_mutex_lock(&mutex);
278     stp = xzalloc(sizeof *stp);
279     stp->name = xstrdup(name);
280     stp->bridge_id = bridge_id;
281     if (!(stp->bridge_id >> 48)) {
282         stp->bridge_id |= (uint64_t) STP_DEFAULT_BRIDGE_PRIORITY << 48;
283     }
284
285     stp->rq_max_age = STP_DEFAULT_MAX_AGE;
286     stp->rq_hello_time = STP_DEFAULT_HELLO_TIME;
287     stp->rq_forward_delay = STP_DEFAULT_FWD_DELAY;
288     stp_update_bridge_timers(stp);
289     stp->max_age = stp->bridge_max_age;
290     stp->hello_time = stp->bridge_hello_time;
291     stp->forward_delay = stp->bridge_forward_delay;
292
293     stp->designated_root = stp->bridge_id;
294     stp->root_path_cost = 0;
295     stp->root_port = NULL;
296     stp->topology_change_detected = false;
297     stp->topology_change = false;
298
299     stp_stop_timer(&stp->tcn_timer);
300     stp_stop_timer(&stp->topology_change_timer);
301     stp_start_timer(&stp->hello_timer, 0);
302
303     stp->send_bpdu = send_bpdu;
304     stp->aux = aux;
305
306     stp->first_changed_port = &stp->ports[ARRAY_SIZE(stp->ports)];
307     for (p = stp->ports; p < &stp->ports[ARRAY_SIZE(stp->ports)]; p++) {
308         p->stp = stp;
309         p->port_id = (stp_port_no(p) + 1) | (STP_DEFAULT_PORT_PRIORITY << 8);
310         p->path_cost = 19;      /* Recommended default for 100 Mb/s link. */
311         stp_initialize_port(p, STP_DISABLED);
312     }
313     ovs_refcount_init(&stp->ref_cnt);
314
315     list_push_back(all_stps, &stp->node);
316     ovs_mutex_unlock(&mutex);
317     return stp;
318 }
319
320 struct stp *
321 stp_ref(const struct stp *stp_)
322 {
323     struct stp *stp = CONST_CAST(struct stp *, stp_);
324     if (stp) {
325         ovs_refcount_ref(&stp->ref_cnt);
326     }
327     return stp;
328 }
329
330 /* Destroys 'stp'. */
331 void
332 stp_unref(struct stp *stp)
333 {
334     if (stp && ovs_refcount_unref_relaxed(&stp->ref_cnt) == 1) {
335         size_t i;
336
337         ovs_mutex_lock(&mutex);
338         list_remove(&stp->node);
339         ovs_mutex_unlock(&mutex);
340         free(stp->name);
341
342         for (i = 0; i < STP_MAX_PORTS; i++) {
343             free(stp->ports[i].port_name);
344         }
345         free(stp);
346     }
347 }
348
349 /* Runs 'stp' given that 'ms' milliseconds have passed. */
350 void
351 stp_tick(struct stp *stp, int ms)
352 {
353     struct stp_port *p;
354     int elapsed;
355
356     ovs_mutex_lock(&mutex);
357     /* Convert 'ms' to STP timer ticks.  Preserve any leftover milliseconds
358      * from previous stp_tick() calls so that we don't lose STP ticks when we
359      * are called too frequently. */
360     ms = clamp(ms, 0, INT_MAX - 1000) + stp->elapsed_remainder;
361     elapsed = ms_to_timer(ms);
362     stp->elapsed_remainder = ms - timer_to_ms(elapsed);
363     if (!elapsed) {
364         goto out;
365     }
366
367     if (stp_timer_expired(&stp->hello_timer, elapsed, stp->hello_time)) {
368         stp_hello_timer_expiry(stp);
369     }
370     if (stp_timer_expired(&stp->tcn_timer, elapsed, stp->bridge_hello_time)) {
371         stp_tcn_timer_expiry(stp);
372     }
373     if (stp_timer_expired(&stp->topology_change_timer, elapsed,
374                           stp->max_age + stp->forward_delay)) {
375         stp_topology_change_timer_expiry(stp);
376     }
377     FOR_EACH_ENABLED_PORT (p, stp) {
378         if (stp_timer_expired(&p->message_age_timer, elapsed, stp->max_age)) {
379             stp_message_age_timer_expiry(p);
380         }
381     }
382     FOR_EACH_ENABLED_PORT (p, stp) {
383         if (stp_timer_expired(&p->forward_delay_timer, elapsed,
384                               stp->forward_delay)) {
385             stp_forward_delay_timer_expiry(p);
386         }
387         if (stp_timer_expired(&p->hold_timer, elapsed, ms_to_timer(1000))) {
388             stp_hold_timer_expiry(p);
389         }
390     }
391
392 out:
393     ovs_mutex_unlock(&mutex);
394 }
395
396 static void
397 set_bridge_id(struct stp *stp, stp_identifier new_bridge_id)
398     OVS_REQUIRES(mutex)
399 {
400     if (new_bridge_id != stp->bridge_id) {
401         bool root;
402         struct stp_port *p;
403
404         root = stp_is_root_bridge(stp);
405         FOR_EACH_ENABLED_PORT (p, stp) {
406             if (stp_is_designated_port(p)) {
407                 p->designated_bridge = new_bridge_id;
408             }
409         }
410         stp->bridge_id = new_bridge_id;
411         stp_configuration_update(stp);
412         stp_port_state_selection(stp);
413         if (stp_is_root_bridge(stp) && !root) {
414             stp_become_root_bridge(stp);
415         }
416     }
417 }
418
419 void
420 stp_set_bridge_id(struct stp *stp, stp_identifier bridge_id)
421 {
422     const uint64_t mac_bits = (UINT64_C(1) << 48) - 1;
423     const uint64_t pri_bits = ~mac_bits;
424     ovs_mutex_lock(&mutex);
425     set_bridge_id(stp, (stp->bridge_id & pri_bits) | (bridge_id & mac_bits));
426     ovs_mutex_unlock(&mutex);
427 }
428
429 void
430 stp_set_bridge_priority(struct stp *stp, uint16_t new_priority)
431 {
432     const uint64_t mac_bits = (UINT64_C(1) << 48) - 1;
433     ovs_mutex_lock(&mutex);
434     set_bridge_id(stp, ((stp->bridge_id & mac_bits)
435                         | ((uint64_t) new_priority << 48)));
436     ovs_mutex_unlock(&mutex);
437 }
438
439 /* Sets the desired hello time for 'stp' to 'ms', in milliseconds.  The actual
440  * hello time is clamped to the range of 1 to 10 seconds and subject to the
441  * relationship (bridge_max_age >= 2 * (bridge_hello_time + 1 s)).  The bridge
442  * hello time is only used when 'stp' is the root bridge. */
443 void
444 stp_set_hello_time(struct stp *stp, int ms)
445 {
446     ovs_mutex_lock(&mutex);
447     stp->rq_hello_time = ms;
448     stp_update_bridge_timers(stp);
449     ovs_mutex_unlock(&mutex);
450 }
451
452 /* Sets the desired max age for 'stp' to 'ms', in milliseconds.  The actual max
453  * age is clamped to the range of 6 to 40 seconds and subject to the
454  * relationships (2 * (bridge_forward_delay - 1 s) >= bridge_max_age) and
455  * (bridge_max_age >= 2 * (bridge_hello_time + 1 s)).  The bridge max age is
456  * only used when 'stp' is the root bridge. */
457 void
458 stp_set_max_age(struct stp *stp, int ms)
459 {
460     ovs_mutex_lock(&mutex);
461     stp->rq_max_age = ms;
462     stp_update_bridge_timers(stp);
463     ovs_mutex_unlock(&mutex);
464 }
465
466 /* Sets the desired forward delay for 'stp' to 'ms', in milliseconds.  The
467  * actual forward delay is clamped to the range of 4 to 30 seconds and subject
468  * to the relationship (2 * (bridge_forward_delay - 1 s) >= bridge_max_age).
469  * The bridge forward delay is only used when 'stp' is the root bridge. */
470 void
471 stp_set_forward_delay(struct stp *stp, int ms)
472 {
473     ovs_mutex_lock(&mutex);
474     stp->rq_forward_delay = ms;
475     stp_update_bridge_timers(stp);
476     ovs_mutex_unlock(&mutex);
477 }
478
479 /* Returns the name given to 'stp' in the call to stp_create(). */
480 const char *
481 stp_get_name(const struct stp *stp)
482 {
483     char *name;
484
485     ovs_mutex_lock(&mutex);
486     name = stp->name;
487     ovs_mutex_unlock(&mutex);
488     return name;
489 }
490
491 /* Returns the bridge ID for 'stp'. */
492 stp_identifier
493 stp_get_bridge_id(const struct stp *stp)
494 {
495     stp_identifier bridge_id;
496
497     ovs_mutex_lock(&mutex);
498     bridge_id = stp->bridge_id;
499     ovs_mutex_unlock(&mutex);
500     return bridge_id;
501 }
502
503 /* Returns the bridge ID of the bridge currently believed to be the root. */
504 stp_identifier
505 stp_get_designated_root(const struct stp *stp)
506 {
507     stp_identifier designated_root;
508
509     ovs_mutex_lock(&mutex);
510     designated_root = stp->designated_root;
511     ovs_mutex_unlock(&mutex);
512     return designated_root;
513 }
514
515 /* Returns true if 'stp' believes itself to the be root of the spanning tree,
516  * false otherwise. */
517 bool
518 stp_is_root_bridge(const struct stp *stp)
519 {
520     bool is_root;
521
522     ovs_mutex_lock(&mutex);
523     is_root = stp->bridge_id == stp->designated_root;
524     ovs_mutex_unlock(&mutex);
525     return is_root;
526 }
527
528 /* Returns the cost of the path from 'stp' to the root of the spanning tree. */
529 int
530 stp_get_root_path_cost(const struct stp *stp)
531 {
532     int cost;
533
534     ovs_mutex_lock(&mutex);
535     cost = stp->root_path_cost;
536     ovs_mutex_unlock(&mutex);
537     return cost;
538 }
539
540 /* Returns the bridge hello time, in ms.  The returned value is not necessarily
541  * the value passed to stp_set_hello_time(): it is clamped to the valid range
542  * and quantized to the STP timer resolution.  */
543 int
544 stp_get_hello_time(const struct stp *stp)
545 {
546     int time;
547
548     ovs_mutex_lock(&mutex);
549     time = timer_to_ms(stp->bridge_hello_time);
550     ovs_mutex_unlock(&mutex);
551     return time;
552 }
553
554 /* Returns the bridge max age, in ms.  The returned value is not necessarily
555  * the value passed to stp_set_max_age(): it is clamped to the valid range,
556  * quantized to the STP timer resolution, and adjusted to match the constraints
557  * due to the hello time.  */
558 int
559 stp_get_max_age(const struct stp *stp)
560 {
561     int time;
562
563     ovs_mutex_lock(&mutex);
564     time = timer_to_ms(stp->bridge_max_age);
565     ovs_mutex_unlock(&mutex);
566     return time;
567 }
568
569 /* Returns the bridge forward delay, in ms.  The returned value is not
570  * necessarily the value passed to stp_set_forward_delay(): it is clamped to
571  * the valid range, quantized to the STP timer resolution, and adjusted to
572  * match the constraints due to the forward delay.  */
573 int
574 stp_get_forward_delay(const struct stp *stp)
575 {
576     int time;
577
578     ovs_mutex_lock(&mutex);
579     time = timer_to_ms(stp->bridge_forward_delay);
580     ovs_mutex_unlock(&mutex);
581     return time;
582 }
583
584 /* Returns true if something has happened to 'stp' which necessitates flushing
585  * the client's MAC learning table.  Calling this function resets 'stp' so that
586  * future calls will return false until flushing is required again. */
587 bool
588 stp_check_and_reset_fdb_flush(struct stp *stp)
589 {
590     bool needs_flush;
591
592     ovs_mutex_lock(&mutex);
593     needs_flush = stp->fdb_needs_flush;
594     stp->fdb_needs_flush = false;
595     ovs_mutex_unlock(&mutex);
596     return needs_flush;
597 }
598
599 /* Returns the port in 'stp' with index 'port_no', which must be between 0 and
600  * STP_MAX_PORTS. */
601 struct stp_port *
602 stp_get_port(struct stp *stp, int port_no)
603 {
604     struct stp_port *port;
605
606     ovs_mutex_lock(&mutex);
607     ovs_assert(port_no >= 0 && port_no < ARRAY_SIZE(stp->ports));
608     port = &stp->ports[port_no];
609     ovs_mutex_unlock(&mutex);
610     return port;
611 }
612
613 /* Returns the port connecting 'stp' to the root bridge, or a null pointer if
614  * there is no such port. */
615 struct stp_port *
616 stp_get_root_port(struct stp *stp)
617 {
618     struct stp_port *port;
619
620     ovs_mutex_lock(&mutex);
621     port = stp->root_port;
622     ovs_mutex_unlock(&mutex);
623     return port;
624 }
625
626 /* Finds a port whose state has changed.  If successful, stores the port whose
627  * state changed in '*portp' and returns true.  If no port has changed, stores
628  * NULL in '*portp' and returns false. */
629 bool
630 stp_get_changed_port(struct stp *stp, struct stp_port **portp)
631 {
632     struct stp_port *end, *p;
633     bool changed = false;
634
635     ovs_mutex_lock(&mutex);
636     end = &stp->ports[ARRAY_SIZE(stp->ports)];
637     for (p = stp->first_changed_port; p < end; p++) {
638         if (p->state_changed) {
639             p->state_changed = false;
640             stp->first_changed_port = p + 1;
641             *portp = p;
642             changed = true;
643             goto out;
644         }
645     }
646     stp->first_changed_port = end;
647     *portp = NULL;
648
649 out:
650     ovs_mutex_unlock(&mutex);
651     return changed;
652 }
653
654 /* Returns the name for the given 'state' (for use in debugging and log
655  * messages). */
656 const char *
657 stp_state_name(enum stp_state state)
658 {
659     switch (state) {
660     case STP_DISABLED:
661         return "disabled";
662     case STP_LISTENING:
663         return "listening";
664     case STP_LEARNING:
665         return "learning";
666     case STP_FORWARDING:
667         return "forwarding";
668     case STP_BLOCKING:
669         return "blocking";
670     default:
671         OVS_NOT_REACHED();
672     }
673 }
674
675 /* Returns true if 'state' is one in which packets received on a port should
676  * be forwarded, false otherwise.
677  */
678 bool
679 stp_forward_in_state(enum stp_state state)
680 {
681     return (state & STP_FORWARDING) != 0;
682 }
683
684 /* Returns true if 'state' is one in which MAC learning should be done on
685  * packets received on a port, false otherwise.
686  */
687 bool
688 stp_learn_in_state(enum stp_state state)
689 {
690     return (state & (STP_LEARNING | STP_FORWARDING)) != 0;
691 }
692
693 /* Returns true if 'state' is one in which bpdus should be forwarded on a
694  * port, false otherwise.
695  *
696  * Returns true if 'state' is STP_DISABLED, since in that case the port does
697  * not generate the bpdu and should just forward it (e.g. patch port on pif
698  * bridge). */
699 bool
700 stp_should_forward_bpdu(enum stp_state state)
701 {
702     return (state &
703             ( STP_DISABLED | STP_LISTENING | STP_LEARNING
704               | STP_FORWARDING)) != 0;
705 }
706
707 /* Returns the name for the given 'role' (for use in debugging and log
708  * messages). */
709 const char *
710 stp_role_name(enum stp_role role)
711 {
712     switch (role) {
713     case STP_ROLE_ROOT:
714         return "root";
715     case STP_ROLE_DESIGNATED:
716         return "designated";
717     case STP_ROLE_ALTERNATE:
718         return "alternate";
719     case STP_ROLE_DISABLED:
720         return "disabled";
721     default:
722         OVS_NOT_REACHED();
723     }
724 }
725
726 /* Notifies the STP entity that bridge protocol data unit 'bpdu', which is
727  * 'bpdu_size' bytes in length, was received on port 'p'.
728  *
729  * This function may call the 'send_bpdu' function provided to stp_create(). */
730 void
731 stp_received_bpdu(struct stp_port *p, const void *bpdu, size_t bpdu_size)
732 {
733     struct stp *stp = p->stp;
734     const struct stp_bpdu_header *header;
735
736     ovs_mutex_lock(&mutex);
737     if (p->state == STP_DISABLED) {
738         goto out;
739     }
740
741     if (bpdu_size < sizeof(struct stp_bpdu_header)) {
742         VLOG_WARN("%s: received runt %"PRIuSIZE"-byte BPDU", stp->name, bpdu_size);
743         p->error_count++;
744         goto out;
745     }
746
747     header = bpdu;
748     if (header->protocol_id != htons(STP_PROTOCOL_ID)) {
749         VLOG_WARN("%s: received BPDU with unexpected protocol ID %"PRIu16,
750                   stp->name, ntohs(header->protocol_id));
751         p->error_count++;
752         goto out;
753     }
754     if (header->protocol_version != STP_PROTOCOL_VERSION) {
755         VLOG_DBG("%s: received BPDU with unexpected protocol version %"PRIu8,
756                  stp->name, header->protocol_version);
757     }
758
759     switch (header->bpdu_type) {
760     case STP_TYPE_CONFIG:
761         if (bpdu_size < sizeof(struct stp_config_bpdu)) {
762             VLOG_WARN("%s: received config BPDU with invalid size %"PRIuSIZE,
763                       stp->name, bpdu_size);
764             p->error_count++;
765             goto out;
766         }
767         stp_received_config_bpdu(stp, p, bpdu);
768         break;
769
770     case STP_TYPE_TCN:
771         if (bpdu_size != sizeof(struct stp_tcn_bpdu)) {
772             VLOG_WARN("%s: received TCN BPDU with invalid size %"PRIuSIZE,
773                       stp->name, bpdu_size);
774             p->error_count++;
775             goto out;
776         }
777         stp_received_tcn_bpdu(stp, p);
778         break;
779
780     default:
781         VLOG_WARN("%s: received BPDU of unexpected type %"PRIu8,
782                   stp->name, header->bpdu_type);
783         p->error_count++;
784         goto out;
785     }
786     p->rx_count++;
787
788 out:
789     ovs_mutex_unlock(&mutex);
790 }
791
792 /* Returns the STP entity in which 'p' is nested. */
793 struct stp *
794 stp_port_get_stp(struct stp_port *p)
795 {
796     struct stp *stp;
797
798     ovs_mutex_lock(&mutex);
799     stp = p->stp;
800     ovs_mutex_unlock(&mutex);
801     return stp;
802 }
803
804 void
805 stp_port_set_name(struct stp_port *p, const char *name)
806 {
807     char *old;
808
809     ovs_mutex_lock(&mutex);
810     old = p->port_name;
811     p->port_name = xstrdup(name);
812     free(old);
813     ovs_mutex_unlock(&mutex);
814 }
815
816 /* Sets the 'aux' member of 'p'.
817  *
818  * The 'aux' member will be reset to NULL when stp_port_disable() is
819  * called or stp_port_enable() is called when the port is in a Disabled
820  * state. */
821 void
822 stp_port_set_aux(struct stp_port *p, void *aux)
823 {
824     ovs_mutex_lock(&mutex);
825     p->aux = aux;
826     ovs_mutex_unlock(&mutex);
827 }
828
829 /* Returns the 'aux' member of 'p'. */
830 void *
831 stp_port_get_aux(struct stp_port *p)
832 {
833     void *aux;
834
835     ovs_mutex_lock(&mutex);
836     aux = p->aux;
837     ovs_mutex_unlock(&mutex);
838     return aux;
839 }
840
841 /* Returns the index of port 'p' within its bridge. */
842 int
843 stp_port_no(const struct stp_port *p)
844 {
845     struct stp *stp;
846     int index;
847
848     ovs_mutex_lock(&mutex);
849     stp = p->stp;
850     ovs_assert(p >= stp->ports && p < &stp->ports[ARRAY_SIZE(stp->ports)]);
851     index = p - p->stp->ports;
852     ovs_mutex_unlock(&mutex);
853     return index;
854 }
855
856 /* Returns the port ID for 'p'. */
857 int
858 stp_port_get_id(const struct stp_port *p)
859 {
860     int port_id;
861
862     ovs_mutex_lock(&mutex);
863     port_id = p->port_id;
864     ovs_mutex_unlock(&mutex);
865     return port_id;
866 }
867
868 /* Returns the state of port 'p'. */
869 enum stp_state
870 stp_port_get_state(const struct stp_port *p)
871 {
872     enum stp_state state;
873
874     ovs_mutex_lock(&mutex);
875     state = p->state;
876     ovs_mutex_unlock(&mutex);
877     return state;
878 }
879
880 /* Returns the role of port 'p'. */
881 enum stp_role
882 stp_port_get_role(const struct stp_port *p)
883 {
884     struct stp_port *root_port;
885     enum stp_role role;
886
887     ovs_mutex_lock(&mutex);
888     root_port = p->stp->root_port;
889     if (root_port && root_port->port_id == p->port_id) {
890         role = STP_ROLE_ROOT;
891     } else if (stp_is_designated_port(p)) {
892         role = STP_ROLE_DESIGNATED;
893     } else if (p->state == STP_DISABLED) {
894         role = STP_ROLE_DISABLED;
895     } else {
896         role = STP_ROLE_ALTERNATE;
897     }
898     ovs_mutex_unlock(&mutex);
899     return role;
900 }
901
902 /* Retrieves BPDU transmit and receive counts for 'p'. */
903 void
904 stp_port_get_counts(const struct stp_port *p,
905                     int *tx_count, int *rx_count, int *error_count)
906 {
907     ovs_mutex_lock(&mutex);
908     *tx_count = p->tx_count;
909     *rx_count = p->rx_count;
910     *error_count = p->error_count;
911     ovs_mutex_unlock(&mutex);
912 }
913
914 /* Disables STP on port 'p'. */
915 void
916 stp_port_disable(struct stp_port *p)
917 {
918     struct stp *stp;
919
920     ovs_mutex_lock(&mutex);
921     stp = p->stp;
922     if (p->state != STP_DISABLED) {
923         bool root = stp_is_root_bridge(stp);
924         stp_become_designated_port(p);
925         stp_set_port_state(p, STP_DISABLED);
926         p->topology_change_ack = false;
927         p->config_pending = false;
928         stp_stop_timer(&p->message_age_timer);
929         stp_stop_timer(&p->forward_delay_timer);
930         stp_configuration_update(stp);
931         stp_port_state_selection(stp);
932         if (stp_is_root_bridge(stp) && !root) {
933             stp_become_root_bridge(stp);
934         }
935         p->aux = NULL;
936     }
937     ovs_mutex_unlock(&mutex);
938 }
939
940 /* Enables STP on port 'p'.  The port will initially be in "blocking" state. */
941 void
942 stp_port_enable(struct stp_port *p)
943 {
944     ovs_mutex_lock(&mutex);
945     if (p->state == STP_DISABLED) {
946         stp_initialize_port(p, STP_BLOCKING);
947         stp_port_state_selection(p->stp);
948     }
949     ovs_mutex_unlock(&mutex);
950 }
951
952 /* Sets the priority of port 'p' to 'new_priority'.  Lower numerical values
953  * are interpreted as higher priorities. */
954 void
955 stp_port_set_priority(struct stp_port *p, uint8_t new_priority)
956 {
957     uint16_t new_port_id;
958
959     ovs_mutex_lock(&mutex);
960     new_port_id  = (p->port_id & 0xff) | (new_priority << 8);
961     if (p->port_id != new_port_id) {
962         struct stp *stp = p->stp;
963         if (stp_is_designated_port(p)) {
964             p->designated_port = new_port_id;
965         }
966         p->port_id = new_port_id;
967         if (stp->bridge_id == p->designated_bridge
968             && p->port_id < p->designated_port) {
969             stp_become_designated_port(p);
970             stp_port_state_selection(stp);
971         }
972     }
973     ovs_mutex_unlock(&mutex);
974 }
975
976 /* Convert 'speed' (measured in Mb/s) into the path cost. */
977 uint16_t
978 stp_convert_speed_to_cost(unsigned int speed)
979 {
980     uint16_t ret;
981
982     ovs_mutex_lock(&mutex);
983     ret = speed >= 10000 ? 2  /* 10 Gb/s. */
984         : speed >= 1000 ? 4 /* 1 Gb/s. */
985         : speed >= 100 ? 19 /* 100 Mb/s. */
986         : speed >= 16 ? 62  /* 16 Mb/s. */
987         : speed >= 10 ? 100 /* 10 Mb/s. */
988         : speed >= 4 ? 250  /* 4 Mb/s. */
989         : 19;             /* 100 Mb/s (guess). */
990     ovs_mutex_unlock(&mutex);
991     return ret;
992 }
993
994 /* Sets the path cost of port 'p' to 'path_cost'.  Lower values are generally
995  * used to indicate faster links.  Use stp_port_set_speed() to automatically
996  * generate a default path cost from a link speed. */
997 void
998 stp_port_set_path_cost(struct stp_port *p, uint16_t path_cost)
999 {
1000     ovs_mutex_lock(&mutex);
1001     if (p->path_cost != path_cost) {
1002         struct stp *stp = p->stp;
1003         p->path_cost = path_cost;
1004         stp_configuration_update(stp);
1005         stp_port_state_selection(stp);
1006     }
1007     ovs_mutex_unlock(&mutex);
1008 }
1009
1010 /* Sets the path cost of port 'p' based on 'speed' (measured in Mb/s). */
1011 void
1012 stp_port_set_speed(struct stp_port *p, unsigned int speed)
1013 {
1014     stp_port_set_path_cost(p, stp_convert_speed_to_cost(speed));
1015 }
1016
1017 /* Enables topology change detection on port 'p'. */
1018 void
1019 stp_port_enable_change_detection(struct stp_port *p)
1020 {
1021     p->change_detection_enabled = true;
1022 }
1023
1024 /* Disables topology change detection on port 'p'. */
1025 void
1026 stp_port_disable_change_detection(struct stp_port *p)
1027 {
1028     p->change_detection_enabled = false;
1029 }
1030 \f
1031 static void
1032 stp_transmit_config(struct stp_port *p) OVS_REQUIRES(mutex)
1033 {
1034     struct stp *stp = p->stp;
1035     bool root = stp_is_root_bridge(stp);
1036     if (!root && !stp->root_port) {
1037         return;
1038     }
1039     if (p->hold_timer.active) {
1040         VLOG_DBG_RL(&stp_rl, "bridge: %s, port: %s, transmit config bpdu pending",
1041                     stp->name, p->port_name);
1042         p->config_pending = true;
1043     } else {
1044         struct stp_config_bpdu config;
1045         memset(&config, 0, sizeof config);
1046         config.header.protocol_id = htons(STP_PROTOCOL_ID);
1047         config.header.protocol_version = STP_PROTOCOL_VERSION;
1048         config.header.bpdu_type = STP_TYPE_CONFIG;
1049         config.flags = 0;
1050         if (p->topology_change_ack) {
1051             config.flags |= STP_CONFIG_TOPOLOGY_CHANGE_ACK;
1052         }
1053         if (stp->topology_change) {
1054             config.flags |= STP_CONFIG_TOPOLOGY_CHANGE;
1055         }
1056         config.root_id = htonll(stp->designated_root);
1057         config.root_path_cost = htonl(stp->root_path_cost);
1058         config.bridge_id = htonll(stp->bridge_id);
1059         config.port_id = htons(p->port_id);
1060         if (root) {
1061             config.message_age = htons(0);
1062         } else {
1063             config.message_age = htons(stp->root_port->message_age_timer.value
1064                                        + MESSAGE_AGE_INCREMENT);
1065         }
1066         config.max_age = htons(stp->max_age);
1067         config.hello_time = htons(stp->hello_time);
1068         config.forward_delay = htons(stp->forward_delay);
1069         if (ntohs(config.message_age) < stp->max_age) {
1070             p->topology_change_ack = false;
1071             p->config_pending = false;
1072             VLOG_DBG_RL(&stp_rl, "bridge: %s, port: %s, transmit config bpdu",
1073                         stp->name, p->port_name);
1074             stp_send_bpdu(p, &config, sizeof config);
1075             stp_start_timer(&p->hold_timer, 0);
1076         }
1077     }
1078 }
1079
1080 static bool
1081 stp_supersedes_port_info(const struct stp_port *p,
1082                          const struct stp_config_bpdu *config)
1083      OVS_REQUIRES(mutex)
1084 {
1085     if (ntohll(config->root_id) != p->designated_root) {
1086         return ntohll(config->root_id) < p->designated_root;
1087     } else if (ntohl(config->root_path_cost) != p->designated_cost) {
1088         return ntohl(config->root_path_cost) < p->designated_cost;
1089     } else if (ntohll(config->bridge_id) != p->designated_bridge) {
1090         return ntohll(config->bridge_id) < p->designated_bridge;
1091     } else {
1092         return (ntohll(config->bridge_id) != p->stp->bridge_id
1093                 || ntohs(config->port_id) <= p->designated_port);
1094     }
1095 }
1096
1097 static void
1098 stp_record_config_information(struct stp_port *p,
1099                               const struct stp_config_bpdu *config)
1100      OVS_REQUIRES(mutex)
1101 {
1102     p->designated_root = ntohll(config->root_id);
1103     p->designated_cost = ntohl(config->root_path_cost);
1104     p->designated_bridge = ntohll(config->bridge_id);
1105     p->designated_port = ntohs(config->port_id);
1106     stp_start_timer(&p->message_age_timer, ntohs(config->message_age));
1107 }
1108
1109 static void
1110 stp_record_config_timeout_values(struct stp *stp,
1111                                  const struct stp_config_bpdu  *config)
1112      OVS_REQUIRES(mutex)
1113 {
1114     stp->max_age = ntohs(config->max_age);
1115     stp->hello_time = ntohs(config->hello_time);
1116     stp->forward_delay = ntohs(config->forward_delay);
1117     stp->topology_change = config->flags & STP_CONFIG_TOPOLOGY_CHANGE;
1118 }
1119
1120 static bool
1121 stp_is_designated_port(const struct stp_port *p) OVS_REQUIRES(mutex)
1122 {
1123     return (p->designated_bridge == p->stp->bridge_id
1124             && p->designated_port == p->port_id);
1125 }
1126
1127 static void
1128 stp_config_bpdu_generation(struct stp *stp) OVS_REQUIRES(mutex)
1129 {
1130     struct stp_port *p;
1131
1132     FOR_EACH_ENABLED_PORT (p, stp) {
1133         if (stp_is_designated_port(p)) {
1134             stp_transmit_config(p);
1135         }
1136     }
1137 }
1138
1139 static void
1140 stp_transmit_tcn(struct stp *stp) OVS_REQUIRES(mutex)
1141 {
1142     struct stp_port *p = stp->root_port;
1143     struct stp_tcn_bpdu tcn_bpdu;
1144
1145     if (!p) {
1146         return;
1147     }
1148     VLOG_DBG_RL(&stp_rl, "bridge: %s, root port: %s, transmit tcn", stp->name,
1149                 p->port_name);
1150     tcn_bpdu.header.protocol_id = htons(STP_PROTOCOL_ID);
1151     tcn_bpdu.header.protocol_version = STP_PROTOCOL_VERSION;
1152     tcn_bpdu.header.bpdu_type = STP_TYPE_TCN;
1153     stp_send_bpdu(p, &tcn_bpdu, sizeof tcn_bpdu);
1154 }
1155
1156 static void
1157 stp_configuration_update(struct stp *stp) OVS_REQUIRES(mutex)
1158 {
1159     stp_root_selection(stp);
1160     stp_designated_port_selection(stp);
1161     seq_change(connectivity_seq_get());
1162 }
1163
1164 static bool
1165 stp_supersedes_root(const struct stp_port *root, const struct stp_port *p)
1166     OVS_REQUIRES(mutex)
1167 {
1168     int p_cost = p->designated_cost + p->path_cost;
1169     int root_cost = root->designated_cost + root->path_cost;
1170
1171     if (p->designated_root != root->designated_root) {
1172         return p->designated_root < root->designated_root;
1173     } else if (p_cost != root_cost) {
1174         return p_cost < root_cost;
1175     } else if (p->designated_bridge != root->designated_bridge) {
1176         return p->designated_bridge < root->designated_bridge;
1177     } else if (p->designated_port != root->designated_port) {
1178         return p->designated_port < root->designated_port;
1179     } else {
1180         return p->port_id < root->port_id;
1181     }
1182 }
1183
1184 static void
1185 stp_root_selection(struct stp *stp) OVS_REQUIRES(mutex)
1186 {
1187     struct stp_port *p, *root;
1188
1189     root = NULL;
1190     FOR_EACH_ENABLED_PORT (p, stp) {
1191         if (stp_is_designated_port(p)
1192             || p->designated_root >= stp->bridge_id) {
1193             continue;
1194         }
1195         if (root && !stp_supersedes_root(root, p)) {
1196             continue;
1197         }
1198         root = p;
1199     }
1200     stp->root_port = root;
1201     if (!root) {
1202         stp->designated_root = stp->bridge_id;
1203         stp->root_path_cost = 0;
1204     } else {
1205         stp->designated_root = root->designated_root;
1206         stp->root_path_cost = root->designated_cost + root->path_cost;
1207     }
1208 }
1209
1210 static void
1211 stp_designated_port_selection(struct stp *stp) OVS_REQUIRES(mutex)
1212 {
1213     struct stp_port *p;
1214
1215     FOR_EACH_ENABLED_PORT (p, stp) {
1216         if (stp_is_designated_port(p)
1217             || p->designated_root != stp->designated_root
1218             || stp->root_path_cost < p->designated_cost
1219             || (stp->root_path_cost == p->designated_cost
1220                 && (stp->bridge_id < p->designated_bridge
1221                     || (stp->bridge_id == p->designated_bridge
1222                         && p->port_id <= p->designated_port))))
1223         {
1224             stp_become_designated_port(p);
1225         }
1226     }
1227 }
1228
1229 static void
1230 stp_become_designated_port(struct stp_port *p) OVS_REQUIRES(mutex)
1231 {
1232     struct stp *stp = p->stp;
1233     p->designated_root = stp->designated_root;
1234     p->designated_cost = stp->root_path_cost;
1235     p->designated_bridge = stp->bridge_id;
1236     p->designated_port = p->port_id;
1237 }
1238
1239 static void
1240 stp_port_state_selection(struct stp *stp) OVS_REQUIRES(mutex)
1241 {
1242     struct stp_port *p;
1243
1244     FOR_EACH_ENABLED_PORT (p, stp) {
1245         if (p == stp->root_port) {
1246             p->config_pending = false;
1247             p->topology_change_ack = false;
1248             stp_make_forwarding(p);
1249         } else if (stp_is_designated_port(p)) {
1250             stp_stop_timer(&p->message_age_timer);
1251             stp_make_forwarding(p);
1252         } else {
1253             p->config_pending = false;
1254             p->topology_change_ack = false;
1255             stp_make_blocking(p);
1256         }
1257     }
1258 }
1259
1260 static void
1261 stp_make_forwarding(struct stp_port *p) OVS_REQUIRES(mutex)
1262 {
1263     if (p->state == STP_BLOCKING) {
1264         stp_set_port_state(p, STP_LISTENING);
1265         stp_start_timer(&p->forward_delay_timer, 0);
1266     }
1267 }
1268
1269 static void
1270 stp_make_blocking(struct stp_port *p) OVS_REQUIRES(mutex)
1271 {
1272     if (!(p->state & (STP_DISABLED | STP_BLOCKING))) {
1273         if (p->state & (STP_FORWARDING | STP_LEARNING)) {
1274             if (p->change_detection_enabled) {
1275                 stp_topology_change_detection(p->stp);
1276             }
1277         }
1278         stp_set_port_state(p, STP_BLOCKING);
1279         stp_stop_timer(&p->forward_delay_timer);
1280     }
1281 }
1282
1283 static void
1284 stp_set_port_state(struct stp_port *p, enum stp_state state)
1285     OVS_REQUIRES(mutex)
1286 {
1287     if (state != p->state && !p->state_changed) {
1288         p->state_changed = true;
1289         if (p < p->stp->first_changed_port) {
1290             p->stp->first_changed_port = p;
1291         }
1292         seq_change(connectivity_seq_get());
1293     }
1294     p->state = state;
1295 }
1296
1297 static void
1298 stp_topology_change_detection(struct stp *stp) OVS_REQUIRES(mutex)
1299 {
1300     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1301
1302     if (stp_is_root_bridge(stp)) {
1303         stp->topology_change = true;
1304         stp_start_timer(&stp->topology_change_timer, 0);
1305     } else if (!stp->topology_change_detected) {
1306         stp_transmit_tcn(stp);
1307         stp_start_timer(&stp->tcn_timer, 0);
1308     }
1309     stp->fdb_needs_flush = true;
1310     stp->topology_change_detected = true;
1311     seq_change(connectivity_seq_get());
1312     VLOG_INFO_RL(&rl, "%s: detected topology change.", stp->name);
1313 }
1314
1315 static void
1316 stp_topology_change_acknowledged(struct stp *stp) OVS_REQUIRES(mutex)
1317 {
1318     stp->topology_change_detected = false;
1319     stp_stop_timer(&stp->tcn_timer);
1320 }
1321
1322 static void
1323 stp_acknowledge_topology_change(struct stp_port *p) OVS_REQUIRES(mutex)
1324 {
1325     p->topology_change_ack = true;
1326     stp_transmit_config(p);
1327 }
1328
1329 static void
1330 stp_received_config_bpdu(struct stp *stp, struct stp_port *p,
1331                          const struct stp_config_bpdu *config)
1332     OVS_REQUIRES(mutex)
1333 {
1334     if (ntohs(config->message_age) >= ntohs(config->max_age)) {
1335         VLOG_WARN("%s: received config BPDU with message age (%u) greater "
1336                   "than max age (%u)",
1337                   stp->name,
1338                   ntohs(config->message_age), ntohs(config->max_age));
1339         return;
1340     }
1341     if (p->state != STP_DISABLED) {
1342         bool root = stp_is_root_bridge(stp);
1343         if (stp_supersedes_port_info(p, config)) {
1344             stp_record_config_information(p, config);
1345             stp_configuration_update(stp);
1346             stp_port_state_selection(stp);
1347             if (!stp_is_root_bridge(stp) && root) {
1348                 stp_stop_timer(&stp->hello_timer);
1349                 if (stp->topology_change_detected) {
1350                     stp_stop_timer(&stp->topology_change_timer);
1351                     stp_transmit_tcn(stp);
1352                     stp_start_timer(&stp->tcn_timer, 0);
1353                 }
1354             }
1355             if (p == stp->root_port) {
1356                 stp_record_config_timeout_values(stp, config);
1357                 stp_config_bpdu_generation(stp);
1358                 if (config->flags & STP_CONFIG_TOPOLOGY_CHANGE_ACK) {
1359                     stp_topology_change_acknowledged(stp);
1360                 }
1361                 if (config->flags & STP_CONFIG_TOPOLOGY_CHANGE) {
1362                     stp->fdb_needs_flush = true;
1363                 }
1364             }
1365         } else if (stp_is_designated_port(p)) {
1366             stp_transmit_config(p);
1367         }
1368     }
1369 }
1370
1371 static void
1372 stp_received_tcn_bpdu(struct stp *stp, struct stp_port *p)
1373     OVS_REQUIRES(mutex)
1374 {
1375     if (p->state != STP_DISABLED) {
1376         if (stp_is_designated_port(p)) {
1377             stp_topology_change_detection(stp);
1378             stp_acknowledge_topology_change(p);
1379         }
1380     }
1381 }
1382
1383 static void
1384 stp_hello_timer_expiry(struct stp *stp) OVS_REQUIRES(mutex)
1385 {
1386     stp_config_bpdu_generation(stp);
1387     stp_start_timer(&stp->hello_timer, 0);
1388 }
1389
1390 static void
1391 stp_message_age_timer_expiry(struct stp_port *p) OVS_REQUIRES(mutex)
1392 {
1393     struct stp *stp = p->stp;
1394     bool root = stp_is_root_bridge(stp);
1395
1396     VLOG_DBG_RL(&stp_rl, "bridge: %s, port: %s, message age timer expired",
1397                 stp->name, p->port_name);
1398     stp_become_designated_port(p);
1399     stp_configuration_update(stp);
1400     stp_port_state_selection(stp);
1401     if (stp_is_root_bridge(stp) && !root) {
1402         stp->max_age = stp->bridge_max_age;
1403         stp->hello_time = stp->bridge_hello_time;
1404         stp->forward_delay = stp->bridge_forward_delay;
1405         stp_topology_change_detection(stp);
1406         stp_stop_timer(&stp->tcn_timer);
1407         stp_config_bpdu_generation(stp);
1408         stp_start_timer(&stp->hello_timer, 0);
1409     }
1410 }
1411
1412 static bool
1413 stp_is_designated_for_some_port(const struct stp *stp) OVS_REQUIRES(mutex)
1414 {
1415     const struct stp_port *p;
1416
1417     FOR_EACH_ENABLED_PORT (p, stp) {
1418         if (p->designated_bridge == stp->bridge_id) {
1419             return true;
1420         }
1421     }
1422     return false;
1423 }
1424
1425 static void
1426 stp_forward_delay_timer_expiry(struct stp_port *p) OVS_REQUIRES(mutex)
1427 {
1428     if (p->state == STP_LISTENING) {
1429         stp_set_port_state(p, STP_LEARNING);
1430         stp_start_timer(&p->forward_delay_timer, 0);
1431     } else if (p->state == STP_LEARNING) {
1432         stp_set_port_state(p, STP_FORWARDING);
1433         if (stp_is_designated_for_some_port(p->stp)) {
1434             if (p->change_detection_enabled) {
1435                 stp_topology_change_detection(p->stp);
1436             }
1437         }
1438     }
1439 }
1440
1441 static void
1442 stp_tcn_timer_expiry(struct stp *stp) OVS_REQUIRES(mutex)
1443 {
1444     stp_transmit_tcn(stp);
1445     stp_start_timer(&stp->tcn_timer, 0);
1446 }
1447
1448 static void
1449 stp_topology_change_timer_expiry(struct stp *stp) OVS_REQUIRES(mutex)
1450 {
1451     stp->topology_change_detected = false;
1452     stp->topology_change = false;
1453 }
1454
1455 static void
1456 stp_hold_timer_expiry(struct stp_port *p) OVS_REQUIRES(mutex)
1457 {
1458     if (p->config_pending) {
1459         stp_transmit_config(p);
1460     }
1461 }
1462
1463 static void
1464 stp_initialize_port(struct stp_port *p, enum stp_state state)
1465     OVS_REQUIRES(mutex)
1466 {
1467     ovs_assert(state & (STP_DISABLED | STP_BLOCKING));
1468     stp_become_designated_port(p);
1469
1470     if (!p->state && state == STP_DISABLED) {
1471         p->state = state; /* Do not trigger state change when initializing. */
1472     } else {
1473         stp_set_port_state(p, state);
1474     }
1475     p->topology_change_ack = false;
1476     p->config_pending = false;
1477     p->change_detection_enabled = true;
1478     p->aux = NULL;
1479     stp_stop_timer(&p->message_age_timer);
1480     stp_stop_timer(&p->forward_delay_timer);
1481     stp_stop_timer(&p->hold_timer);
1482     p->tx_count = p->rx_count = p->error_count = 0;
1483 }
1484
1485 static void
1486 stp_become_root_bridge(struct stp *stp) OVS_REQUIRES(mutex)
1487 {
1488     stp->max_age = stp->bridge_max_age;
1489     stp->hello_time = stp->bridge_hello_time;
1490     stp->forward_delay = stp->bridge_forward_delay;
1491     stp_topology_change_detection(stp);
1492     stp_stop_timer(&stp->tcn_timer);
1493     stp_config_bpdu_generation(stp);
1494     stp_start_timer(&stp->hello_timer, 0);
1495 }
1496
1497 static void
1498 stp_start_timer(struct stp_timer *timer, int value) OVS_REQUIRES(mutex)
1499 {
1500     timer->value = value;
1501     timer->active = true;
1502 }
1503
1504 static void
1505 stp_stop_timer(struct stp_timer *timer) OVS_REQUIRES(mutex)
1506 {
1507     timer->active = false;
1508 }
1509
1510 static bool
1511 stp_timer_expired(struct stp_timer *timer, int elapsed, int timeout)
1512     OVS_REQUIRES(mutex)
1513 {
1514     if (timer->active) {
1515         timer->value += elapsed;
1516         if (timer->value >= timeout) {
1517             timer->active = false;
1518             return true;
1519         }
1520     }
1521     return false;
1522 }
1523
1524 /* Returns the number of whole STP timer ticks in 'ms' milliseconds.  There
1525  * are 256 STP timer ticks per second. */
1526 static int
1527 ms_to_timer(int ms)
1528 {
1529     return ms * 0x100 / 1000;
1530 }
1531
1532 /* Returns the number of whole milliseconds in 'timer' STP timer ticks.  There
1533  * are 256 STP timer ticks per second. */
1534 static int
1535 timer_to_ms(int timer)
1536 {
1537     return timer * 1000 / 0x100;
1538 }
1539
1540 static int
1541 clamp(int x, int min, int max)
1542 {
1543     return x < min ? min : x > max ? max : x;
1544 }
1545
1546 static void
1547 stp_update_bridge_timers(struct stp *stp) OVS_REQUIRES(mutex)
1548 {
1549     int ht, ma, fd;
1550
1551     ht = clamp(stp->rq_hello_time, 1000, 10000);
1552     ma = clamp(stp->rq_max_age, MAX(2 * (ht + 1000), 6000), 40000);
1553     fd = clamp(stp->rq_forward_delay, ma / 2 + 1000, 30000);
1554
1555     stp->bridge_hello_time = ms_to_timer(ht);
1556     stp->bridge_max_age = ms_to_timer(ma);
1557     stp->bridge_forward_delay = ms_to_timer(fd);
1558
1559     if (stp_is_root_bridge(stp)) {
1560         stp->max_age = stp->bridge_max_age;
1561         stp->hello_time = stp->bridge_hello_time;
1562         stp->forward_delay = stp->bridge_forward_delay;
1563     }
1564 }
1565
1566 static void
1567 stp_send_bpdu(struct stp_port *p, const void *bpdu, size_t bpdu_size)
1568     OVS_REQUIRES(mutex)
1569 {
1570     struct eth_header *eth;
1571     struct llc_header *llc;
1572     struct ofpbuf *pkt;
1573
1574     /* Skeleton. */
1575     pkt = ofpbuf_new(ETH_HEADER_LEN + LLC_HEADER_LEN + bpdu_size);
1576     eth = ofpbuf_put_zeros(pkt, sizeof *eth);
1577     llc = ofpbuf_put_zeros(pkt, sizeof *llc);
1578     ofpbuf_set_frame(pkt, eth);
1579     ofpbuf_set_l3(pkt, ofpbuf_put(pkt, bpdu, bpdu_size));
1580
1581     /* 802.2 header. */
1582     memcpy(eth->eth_dst, eth_addr_stp, ETH_ADDR_LEN);
1583     /* p->stp->send_bpdu() must fill in source address. */
1584     eth->eth_type = htons(ofpbuf_size(pkt) - ETH_HEADER_LEN);
1585
1586     /* LLC header. */
1587     llc->llc_dsap = STP_LLC_DSAP;
1588     llc->llc_ssap = STP_LLC_SSAP;
1589     llc->llc_cntl = STP_LLC_CNTL;
1590
1591     p->stp->send_bpdu(pkt, stp_port_no(p), p->stp->aux);
1592     p->tx_count++;
1593 }
1594 \f
1595 /* Unixctl. */
1596
1597 static struct stp *
1598 stp_find(const char *name) OVS_REQUIRES(mutex)
1599 {
1600     struct stp *stp;
1601
1602     LIST_FOR_EACH (stp, node, all_stps) {
1603         if (!strcmp(stp->name, name)) {
1604             return stp;
1605         }
1606     }
1607     return NULL;
1608 }
1609
1610 static void
1611 stp_unixctl_tcn(struct unixctl_conn *conn, int argc,
1612                 const char *argv[], void *aux OVS_UNUSED)
1613 {
1614     ovs_mutex_lock(&mutex);
1615     if (argc > 1) {
1616         struct stp *stp = stp_find(argv[1]);
1617
1618         if (!stp) {
1619             unixctl_command_reply_error(conn, "no such stp object");
1620             goto out;
1621         }
1622         stp_topology_change_detection(stp);
1623     } else {
1624         struct stp *stp;
1625
1626         LIST_FOR_EACH (stp, node, all_stps) {
1627             stp_topology_change_detection(stp);
1628         }
1629     }
1630
1631     unixctl_command_reply(conn, "OK");
1632
1633 out:
1634     ovs_mutex_unlock(&mutex);
1635 }