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