fat-rwlock: Don't forget to destroy a mutex
[cascardo/ovs.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         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  * Returns true if 'state' is STP_DISABLED, since presumably in that case the
679  * port should still work, just not have STP applied to it. */
680 bool
681 stp_forward_in_state(enum stp_state state)
682 {
683     return (state & (STP_DISABLED | STP_FORWARDING)) != 0;
684 }
685
686 /* Returns true if 'state' is one in which MAC learning should be done on
687  * packets received on a port, false otherwise.
688  *
689  * Returns true if 'state' is STP_DISABLED, since presumably in that case the
690  * port should still work, just not have STP applied to it. */
691 bool
692 stp_learn_in_state(enum stp_state state)
693 {
694     return (state & (STP_DISABLED | STP_LEARNING | STP_FORWARDING)) != 0;
695 }
696
697 /* Returns the name for the given 'role' (for use in debugging and log
698  * messages). */
699 const char *
700 stp_role_name(enum stp_role role)
701 {
702     switch (role) {
703     case STP_ROLE_ROOT:
704         return "root";
705     case STP_ROLE_DESIGNATED:
706         return "designated";
707     case STP_ROLE_ALTERNATE:
708         return "alternate";
709     case STP_ROLE_DISABLED:
710         return "disabled";
711     default:
712         OVS_NOT_REACHED();
713     }
714 }
715
716 /* Notifies the STP entity that bridge protocol data unit 'bpdu', which is
717  * 'bpdu_size' bytes in length, was received on port 'p'.
718  *
719  * This function may call the 'send_bpdu' function provided to stp_create(). */
720 void
721 stp_received_bpdu(struct stp_port *p, const void *bpdu, size_t bpdu_size)
722 {
723     struct stp *stp = p->stp;
724     const struct stp_bpdu_header *header;
725
726     ovs_mutex_lock(&mutex);
727     if (p->state == STP_DISABLED) {
728         goto out;
729     }
730
731     if (bpdu_size < sizeof(struct stp_bpdu_header)) {
732         VLOG_WARN("%s: received runt %"PRIuSIZE"-byte BPDU", stp->name, bpdu_size);
733         p->error_count++;
734         goto out;
735     }
736
737     header = bpdu;
738     if (header->protocol_id != htons(STP_PROTOCOL_ID)) {
739         VLOG_WARN("%s: received BPDU with unexpected protocol ID %"PRIu16,
740                   stp->name, ntohs(header->protocol_id));
741         p->error_count++;
742         goto out;
743     }
744     if (header->protocol_version != STP_PROTOCOL_VERSION) {
745         VLOG_DBG("%s: received BPDU with unexpected protocol version %"PRIu8,
746                  stp->name, header->protocol_version);
747     }
748
749     switch (header->bpdu_type) {
750     case STP_TYPE_CONFIG:
751         if (bpdu_size < sizeof(struct stp_config_bpdu)) {
752             VLOG_WARN("%s: received config BPDU with invalid size %"PRIuSIZE,
753                       stp->name, bpdu_size);
754             p->error_count++;
755             goto out;
756         }
757         stp_received_config_bpdu(stp, p, bpdu);
758         break;
759
760     case STP_TYPE_TCN:
761         if (bpdu_size != sizeof(struct stp_tcn_bpdu)) {
762             VLOG_WARN("%s: received TCN BPDU with invalid size %"PRIuSIZE,
763                       stp->name, bpdu_size);
764             p->error_count++;
765             goto out;
766         }
767         stp_received_tcn_bpdu(stp, p);
768         break;
769
770     default:
771         VLOG_WARN("%s: received BPDU of unexpected type %"PRIu8,
772                   stp->name, header->bpdu_type);
773         p->error_count++;
774         goto out;
775     }
776     p->rx_count++;
777
778 out:
779     ovs_mutex_unlock(&mutex);
780 }
781
782 /* Returns the STP entity in which 'p' is nested. */
783 struct stp *
784 stp_port_get_stp(struct stp_port *p)
785 {
786     struct stp *stp;
787
788     ovs_mutex_lock(&mutex);
789     stp = p->stp;
790     ovs_mutex_unlock(&mutex);
791     return stp;
792 }
793
794 /* Sets the 'aux' member of 'p'.
795  *
796  * The 'aux' member will be reset to NULL when stp_port_disable() is
797  * called or stp_port_enable() is called when the port is in a Disabled
798  * state. */
799 void
800 stp_port_set_aux(struct stp_port *p, void *aux)
801 {
802     ovs_mutex_lock(&mutex);
803     p->aux = aux;
804     ovs_mutex_unlock(&mutex);
805 }
806
807 /* Returns the 'aux' member of 'p'. */
808 void *
809 stp_port_get_aux(struct stp_port *p)
810 {
811     void *aux;
812
813     ovs_mutex_lock(&mutex);
814     aux = p->aux;
815     ovs_mutex_unlock(&mutex);
816     return aux;
817 }
818
819 /* Returns the index of port 'p' within its bridge. */
820 int
821 stp_port_no(const struct stp_port *p)
822 {
823     struct stp *stp;
824     int index;
825
826     ovs_mutex_lock(&mutex);
827     stp = p->stp;
828     ovs_assert(p >= stp->ports && p < &stp->ports[ARRAY_SIZE(stp->ports)]);
829     index = p - p->stp->ports;
830     ovs_mutex_unlock(&mutex);
831     return index;
832 }
833
834 /* Returns the port ID for 'p'. */
835 int
836 stp_port_get_id(const struct stp_port *p)
837 {
838     int port_id;
839
840     ovs_mutex_lock(&mutex);
841     port_id = p->port_id;
842     ovs_mutex_unlock(&mutex);
843     return port_id;
844 }
845
846 /* Returns the state of port 'p'. */
847 enum stp_state
848 stp_port_get_state(const struct stp_port *p)
849 {
850     enum stp_state state;
851
852     ovs_mutex_lock(&mutex);
853     state = p->state;
854     ovs_mutex_unlock(&mutex);
855     return state;
856 }
857
858 /* Returns the role of port 'p'. */
859 enum stp_role
860 stp_port_get_role(const struct stp_port *p)
861 {
862     struct stp_port *root_port;
863     enum stp_role role;
864
865     ovs_mutex_lock(&mutex);
866     root_port = p->stp->root_port;
867     if (root_port && root_port->port_id == p->port_id) {
868         role = STP_ROLE_ROOT;
869     } else if (stp_is_designated_port(p)) {
870         role = STP_ROLE_DESIGNATED;
871     } else if (p->state == STP_DISABLED) {
872         role = STP_ROLE_DISABLED;
873     } else {
874         role = STP_ROLE_ALTERNATE;
875     }
876     ovs_mutex_unlock(&mutex);
877     return role;
878 }
879
880 /* Retrieves BPDU transmit and receive counts for 'p'. */
881 void
882 stp_port_get_counts(const struct stp_port *p,
883                     int *tx_count, int *rx_count, int *error_count)
884 {
885     ovs_mutex_lock(&mutex);
886     *tx_count = p->tx_count;
887     *rx_count = p->rx_count;
888     *error_count = p->error_count;
889     ovs_mutex_unlock(&mutex);
890 }
891
892 /* Disables STP on port 'p'. */
893 void
894 stp_port_disable(struct stp_port *p)
895 {
896     struct stp *stp;
897
898     ovs_mutex_lock(&mutex);
899     stp = p->stp;
900     if (p->state != STP_DISABLED) {
901         bool root = stp_is_root_bridge(stp);
902         stp_become_designated_port(p);
903         stp_set_port_state(p, STP_DISABLED);
904         p->topology_change_ack = false;
905         p->config_pending = false;
906         stp_stop_timer(&p->message_age_timer);
907         stp_stop_timer(&p->forward_delay_timer);
908         stp_configuration_update(stp);
909         stp_port_state_selection(stp);
910         if (stp_is_root_bridge(stp) && !root) {
911             stp_become_root_bridge(stp);
912         }
913         p->aux = NULL;
914     }
915     ovs_mutex_unlock(&mutex);
916 }
917
918 /* Enables STP on port 'p'.  The port will initially be in "blocking" state. */
919 void
920 stp_port_enable(struct stp_port *p)
921 {
922     ovs_mutex_lock(&mutex);
923     if (p->state == STP_DISABLED) {
924         stp_initialize_port(p, STP_BLOCKING);
925         stp_port_state_selection(p->stp);
926     }
927     ovs_mutex_unlock(&mutex);
928 }
929
930 /* Sets the priority of port 'p' to 'new_priority'.  Lower numerical values
931  * are interpreted as higher priorities. */
932 void
933 stp_port_set_priority(struct stp_port *p, uint8_t new_priority)
934 {
935     uint16_t new_port_id;
936
937     ovs_mutex_lock(&mutex);
938     new_port_id  = (p->port_id & 0xff) | (new_priority << 8);
939     if (p->port_id != new_port_id) {
940         struct stp *stp = p->stp;
941         if (stp_is_designated_port(p)) {
942             p->designated_port = new_port_id;
943         }
944         p->port_id = new_port_id;
945         if (stp->bridge_id == p->designated_bridge
946             && p->port_id < p->designated_port) {
947             stp_become_designated_port(p);
948             stp_port_state_selection(stp);
949         }
950     }
951     ovs_mutex_unlock(&mutex);
952 }
953
954 /* Convert 'speed' (measured in Mb/s) into the path cost. */
955 uint16_t
956 stp_convert_speed_to_cost(unsigned int speed)
957 {
958     uint16_t ret;
959
960     ovs_mutex_lock(&mutex);
961     ret = speed >= 10000 ? 2  /* 10 Gb/s. */
962         : speed >= 1000 ? 4 /* 1 Gb/s. */
963         : speed >= 100 ? 19 /* 100 Mb/s. */
964         : speed >= 16 ? 62  /* 16 Mb/s. */
965         : speed >= 10 ? 100 /* 10 Mb/s. */
966         : speed >= 4 ? 250  /* 4 Mb/s. */
967         : 19;             /* 100 Mb/s (guess). */
968     ovs_mutex_unlock(&mutex);
969     return ret;
970 }
971
972 /* Sets the path cost of port 'p' to 'path_cost'.  Lower values are generally
973  * used to indicate faster links.  Use stp_port_set_speed() to automatically
974  * generate a default path cost from a link speed. */
975 void
976 stp_port_set_path_cost(struct stp_port *p, uint16_t path_cost)
977 {
978     ovs_mutex_lock(&mutex);
979     if (p->path_cost != path_cost) {
980         struct stp *stp = p->stp;
981         p->path_cost = path_cost;
982         stp_configuration_update(stp);
983         stp_port_state_selection(stp);
984     }
985     ovs_mutex_unlock(&mutex);
986 }
987
988 /* Sets the path cost of port 'p' based on 'speed' (measured in Mb/s). */
989 void
990 stp_port_set_speed(struct stp_port *p, unsigned int speed)
991 {
992     stp_port_set_path_cost(p, stp_convert_speed_to_cost(speed));
993 }
994
995 /* Enables topology change detection on port 'p'. */
996 void
997 stp_port_enable_change_detection(struct stp_port *p)
998 {
999     p->change_detection_enabled = true;
1000 }
1001
1002 /* Disables topology change detection on port 'p'. */
1003 void
1004 stp_port_disable_change_detection(struct stp_port *p)
1005 {
1006     p->change_detection_enabled = false;
1007 }
1008 \f
1009 static void
1010 stp_transmit_config(struct stp_port *p) OVS_REQUIRES(mutex)
1011 {
1012     struct stp *stp = p->stp;
1013     bool root = stp_is_root_bridge(stp);
1014     if (!root && !stp->root_port) {
1015         return;
1016     }
1017     if (p->hold_timer.active) {
1018         p->config_pending = true;
1019     } else {
1020         struct stp_config_bpdu config;
1021         memset(&config, 0, sizeof config);
1022         config.header.protocol_id = htons(STP_PROTOCOL_ID);
1023         config.header.protocol_version = STP_PROTOCOL_VERSION;
1024         config.header.bpdu_type = STP_TYPE_CONFIG;
1025         config.flags = 0;
1026         if (p->topology_change_ack) {
1027             config.flags |= STP_CONFIG_TOPOLOGY_CHANGE_ACK;
1028         }
1029         if (stp->topology_change) {
1030             config.flags |= STP_CONFIG_TOPOLOGY_CHANGE;
1031         }
1032         config.root_id = htonll(stp->designated_root);
1033         config.root_path_cost = htonl(stp->root_path_cost);
1034         config.bridge_id = htonll(stp->bridge_id);
1035         config.port_id = htons(p->port_id);
1036         if (root) {
1037             config.message_age = htons(0);
1038         } else {
1039             config.message_age = htons(stp->root_port->message_age_timer.value
1040                                        + MESSAGE_AGE_INCREMENT);
1041         }
1042         config.max_age = htons(stp->max_age);
1043         config.hello_time = htons(stp->hello_time);
1044         config.forward_delay = htons(stp->forward_delay);
1045         if (ntohs(config.message_age) < stp->max_age) {
1046             p->topology_change_ack = false;
1047             p->config_pending = false;
1048             stp_send_bpdu(p, &config, sizeof config);
1049             stp_start_timer(&p->hold_timer, 0);
1050         }
1051     }
1052 }
1053
1054 static bool
1055 stp_supersedes_port_info(const struct stp_port *p,
1056                          const struct stp_config_bpdu *config)
1057      OVS_REQUIRES(mutex)
1058 {
1059     if (ntohll(config->root_id) != p->designated_root) {
1060         return ntohll(config->root_id) < p->designated_root;
1061     } else if (ntohl(config->root_path_cost) != p->designated_cost) {
1062         return ntohl(config->root_path_cost) < p->designated_cost;
1063     } else if (ntohll(config->bridge_id) != p->designated_bridge) {
1064         return ntohll(config->bridge_id) < p->designated_bridge;
1065     } else {
1066         return (ntohll(config->bridge_id) != p->stp->bridge_id
1067                 || ntohs(config->port_id) <= p->designated_port);
1068     }
1069 }
1070
1071 static void
1072 stp_record_config_information(struct stp_port *p,
1073                               const struct stp_config_bpdu *config)
1074      OVS_REQUIRES(mutex)
1075 {
1076     p->designated_root = ntohll(config->root_id);
1077     p->designated_cost = ntohl(config->root_path_cost);
1078     p->designated_bridge = ntohll(config->bridge_id);
1079     p->designated_port = ntohs(config->port_id);
1080     stp_start_timer(&p->message_age_timer, ntohs(config->message_age));
1081 }
1082
1083 static void
1084 stp_record_config_timeout_values(struct stp *stp,
1085                                  const struct stp_config_bpdu  *config)
1086      OVS_REQUIRES(mutex)
1087 {
1088     stp->max_age = ntohs(config->max_age);
1089     stp->hello_time = ntohs(config->hello_time);
1090     stp->forward_delay = ntohs(config->forward_delay);
1091     stp->topology_change = config->flags & STP_CONFIG_TOPOLOGY_CHANGE;
1092 }
1093
1094 static bool
1095 stp_is_designated_port(const struct stp_port *p) OVS_REQUIRES(mutex)
1096 {
1097     return (p->designated_bridge == p->stp->bridge_id
1098             && p->designated_port == p->port_id);
1099 }
1100
1101 static void
1102 stp_config_bpdu_generation(struct stp *stp) OVS_REQUIRES(mutex)
1103 {
1104     struct stp_port *p;
1105
1106     FOR_EACH_ENABLED_PORT (p, stp) {
1107         if (stp_is_designated_port(p)) {
1108             stp_transmit_config(p);
1109         }
1110     }
1111 }
1112
1113 static void
1114 stp_transmit_tcn(struct stp *stp) OVS_REQUIRES(mutex)
1115 {
1116     struct stp_port *p = stp->root_port;
1117     struct stp_tcn_bpdu tcn_bpdu;
1118     if (!p) {
1119         return;
1120     }
1121     tcn_bpdu.header.protocol_id = htons(STP_PROTOCOL_ID);
1122     tcn_bpdu.header.protocol_version = STP_PROTOCOL_VERSION;
1123     tcn_bpdu.header.bpdu_type = STP_TYPE_TCN;
1124     stp_send_bpdu(p, &tcn_bpdu, sizeof tcn_bpdu);
1125 }
1126
1127 static void
1128 stp_configuration_update(struct stp *stp) OVS_REQUIRES(mutex)
1129 {
1130     stp_root_selection(stp);
1131     stp_designated_port_selection(stp);
1132     seq_change(connectivity_seq_get());
1133 }
1134
1135 static bool
1136 stp_supersedes_root(const struct stp_port *root, const struct stp_port *p)
1137     OVS_REQUIRES(mutex)
1138 {
1139     int p_cost = p->designated_cost + p->path_cost;
1140     int root_cost = root->designated_cost + root->path_cost;
1141
1142     if (p->designated_root != root->designated_root) {
1143         return p->designated_root < root->designated_root;
1144     } else if (p_cost != root_cost) {
1145         return p_cost < root_cost;
1146     } else if (p->designated_bridge != root->designated_bridge) {
1147         return p->designated_bridge < root->designated_bridge;
1148     } else if (p->designated_port != root->designated_port) {
1149         return p->designated_port < root->designated_port;
1150     } else {
1151         return p->port_id < root->port_id;
1152     }
1153 }
1154
1155 static void
1156 stp_root_selection(struct stp *stp) OVS_REQUIRES(mutex)
1157 {
1158     struct stp_port *p, *root;
1159
1160     root = NULL;
1161     FOR_EACH_ENABLED_PORT (p, stp) {
1162         if (stp_is_designated_port(p)
1163             || p->designated_root >= stp->bridge_id) {
1164             continue;
1165         }
1166         if (root && !stp_supersedes_root(root, p)) {
1167             continue;
1168         }
1169         root = p;
1170     }
1171     stp->root_port = root;
1172     if (!root) {
1173         stp->designated_root = stp->bridge_id;
1174         stp->root_path_cost = 0;
1175     } else {
1176         stp->designated_root = root->designated_root;
1177         stp->root_path_cost = root->designated_cost + root->path_cost;
1178     }
1179 }
1180
1181 static void
1182 stp_designated_port_selection(struct stp *stp) OVS_REQUIRES(mutex)
1183 {
1184     struct stp_port *p;
1185
1186     FOR_EACH_ENABLED_PORT (p, stp) {
1187         if (stp_is_designated_port(p)
1188             || p->designated_root != stp->designated_root
1189             || stp->root_path_cost < p->designated_cost
1190             || (stp->root_path_cost == p->designated_cost
1191                 && (stp->bridge_id < p->designated_bridge
1192                     || (stp->bridge_id == p->designated_bridge
1193                         && p->port_id <= p->designated_port))))
1194         {
1195             stp_become_designated_port(p);
1196         }
1197     }
1198 }
1199
1200 static void
1201 stp_become_designated_port(struct stp_port *p) OVS_REQUIRES(mutex)
1202 {
1203     struct stp *stp = p->stp;
1204     p->designated_root = stp->designated_root;
1205     p->designated_cost = stp->root_path_cost;
1206     p->designated_bridge = stp->bridge_id;
1207     p->designated_port = p->port_id;
1208 }
1209
1210 static void
1211 stp_port_state_selection(struct stp *stp) OVS_REQUIRES(mutex)
1212 {
1213     struct stp_port *p;
1214
1215     FOR_EACH_ENABLED_PORT (p, stp) {
1216         if (p == stp->root_port) {
1217             p->config_pending = false;
1218             p->topology_change_ack = false;
1219             stp_make_forwarding(p);
1220         } else if (stp_is_designated_port(p)) {
1221             stp_stop_timer(&p->message_age_timer);
1222             stp_make_forwarding(p);
1223         } else {
1224             p->config_pending = false;
1225             p->topology_change_ack = false;
1226             stp_make_blocking(p);
1227         }
1228     }
1229 }
1230
1231 static void
1232 stp_make_forwarding(struct stp_port *p) OVS_REQUIRES(mutex)
1233 {
1234     if (p->state == STP_BLOCKING) {
1235         stp_set_port_state(p, STP_LISTENING);
1236         stp_start_timer(&p->forward_delay_timer, 0);
1237     }
1238 }
1239
1240 static void
1241 stp_make_blocking(struct stp_port *p) OVS_REQUIRES(mutex)
1242 {
1243     if (!(p->state & (STP_DISABLED | STP_BLOCKING))) {
1244         if (p->state & (STP_FORWARDING | STP_LEARNING)) {
1245             if (p->change_detection_enabled) {
1246                 stp_topology_change_detection(p->stp);
1247             }
1248         }
1249         stp_set_port_state(p, STP_BLOCKING);
1250         stp_stop_timer(&p->forward_delay_timer);
1251     }
1252 }
1253
1254 static void
1255 stp_set_port_state(struct stp_port *p, enum stp_state state)
1256     OVS_REQUIRES(mutex)
1257 {
1258     if (state != p->state && !p->state_changed) {
1259         p->state_changed = true;
1260         if (p < p->stp->first_changed_port) {
1261             p->stp->first_changed_port = p;
1262         }
1263         seq_change(connectivity_seq_get());
1264     }
1265     p->state = state;
1266 }
1267
1268 static void
1269 stp_topology_change_detection(struct stp *stp) OVS_REQUIRES(mutex)
1270 {
1271     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1272
1273     if (stp_is_root_bridge(stp)) {
1274         stp->topology_change = true;
1275         stp_start_timer(&stp->topology_change_timer, 0);
1276     } else if (!stp->topology_change_detected) {
1277         stp_transmit_tcn(stp);
1278         stp_start_timer(&stp->tcn_timer, 0);
1279     }
1280     stp->fdb_needs_flush = true;
1281     stp->topology_change_detected = true;
1282     seq_change(connectivity_seq_get());
1283     VLOG_INFO_RL(&rl, "%s: detected topology change.", stp->name);
1284 }
1285
1286 static void
1287 stp_topology_change_acknowledged(struct stp *stp) OVS_REQUIRES(mutex)
1288 {
1289     stp->topology_change_detected = false;
1290     stp_stop_timer(&stp->tcn_timer);
1291 }
1292
1293 static void
1294 stp_acknowledge_topology_change(struct stp_port *p) OVS_REQUIRES(mutex)
1295 {
1296     p->topology_change_ack = true;
1297     stp_transmit_config(p);
1298 }
1299
1300 static void
1301 stp_received_config_bpdu(struct stp *stp, struct stp_port *p,
1302                          const struct stp_config_bpdu *config)
1303     OVS_REQUIRES(mutex)
1304 {
1305     if (ntohs(config->message_age) >= ntohs(config->max_age)) {
1306         VLOG_WARN("%s: received config BPDU with message age (%u) greater "
1307                   "than max age (%u)",
1308                   stp->name,
1309                   ntohs(config->message_age), ntohs(config->max_age));
1310         return;
1311     }
1312     if (p->state != STP_DISABLED) {
1313         bool root = stp_is_root_bridge(stp);
1314         if (stp_supersedes_port_info(p, config)) {
1315             stp_record_config_information(p, config);
1316             stp_configuration_update(stp);
1317             stp_port_state_selection(stp);
1318             if (!stp_is_root_bridge(stp) && root) {
1319                 stp_stop_timer(&stp->hello_timer);
1320                 if (stp->topology_change_detected) {
1321                     stp_stop_timer(&stp->topology_change_timer);
1322                     stp_transmit_tcn(stp);
1323                     stp_start_timer(&stp->tcn_timer, 0);
1324                 }
1325             }
1326             if (p == stp->root_port) {
1327                 stp_record_config_timeout_values(stp, config);
1328                 stp_config_bpdu_generation(stp);
1329                 if (config->flags & STP_CONFIG_TOPOLOGY_CHANGE_ACK) {
1330                     stp_topology_change_acknowledged(stp);
1331                 }
1332                 if (config->flags & STP_CONFIG_TOPOLOGY_CHANGE) {
1333                     stp->fdb_needs_flush = true;
1334                 }
1335             }
1336         } else if (stp_is_designated_port(p)) {
1337             stp_transmit_config(p);
1338         }
1339     }
1340 }
1341
1342 static void
1343 stp_received_tcn_bpdu(struct stp *stp, struct stp_port *p)
1344     OVS_REQUIRES(mutex)
1345 {
1346     if (p->state != STP_DISABLED) {
1347         if (stp_is_designated_port(p)) {
1348             stp_topology_change_detection(stp);
1349             stp_acknowledge_topology_change(p);
1350         }
1351     }
1352 }
1353
1354 static void
1355 stp_hello_timer_expiry(struct stp *stp) OVS_REQUIRES(mutex)
1356 {
1357     stp_config_bpdu_generation(stp);
1358     stp_start_timer(&stp->hello_timer, 0);
1359 }
1360
1361 static void
1362 stp_message_age_timer_expiry(struct stp_port *p) OVS_REQUIRES(mutex)
1363 {
1364     struct stp *stp = p->stp;
1365     bool root = stp_is_root_bridge(stp);
1366     stp_become_designated_port(p);
1367     stp_configuration_update(stp);
1368     stp_port_state_selection(stp);
1369     if (stp_is_root_bridge(stp) && !root) {
1370         stp->max_age = stp->bridge_max_age;
1371         stp->hello_time = stp->bridge_hello_time;
1372         stp->forward_delay = stp->bridge_forward_delay;
1373         stp_topology_change_detection(stp);
1374         stp_stop_timer(&stp->tcn_timer);
1375         stp_config_bpdu_generation(stp);
1376         stp_start_timer(&stp->hello_timer, 0);
1377     }
1378 }
1379
1380 static bool
1381 stp_is_designated_for_some_port(const struct stp *stp) OVS_REQUIRES(mutex)
1382 {
1383     const struct stp_port *p;
1384
1385     FOR_EACH_ENABLED_PORT (p, stp) {
1386         if (p->designated_bridge == stp->bridge_id) {
1387             return true;
1388         }
1389     }
1390     return false;
1391 }
1392
1393 static void
1394 stp_forward_delay_timer_expiry(struct stp_port *p) OVS_REQUIRES(mutex)
1395 {
1396     if (p->state == STP_LISTENING) {
1397         stp_set_port_state(p, STP_LEARNING);
1398         stp_start_timer(&p->forward_delay_timer, 0);
1399     } else if (p->state == STP_LEARNING) {
1400         stp_set_port_state(p, STP_FORWARDING);
1401         if (stp_is_designated_for_some_port(p->stp)) {
1402             if (p->change_detection_enabled) {
1403                 stp_topology_change_detection(p->stp);
1404             }
1405         }
1406     }
1407 }
1408
1409 static void
1410 stp_tcn_timer_expiry(struct stp *stp) OVS_REQUIRES(mutex)
1411 {
1412     stp_transmit_tcn(stp);
1413     stp_start_timer(&stp->tcn_timer, 0);
1414 }
1415
1416 static void
1417 stp_topology_change_timer_expiry(struct stp *stp) OVS_REQUIRES(mutex)
1418 {
1419     stp->topology_change_detected = false;
1420     stp->topology_change = false;
1421 }
1422
1423 static void
1424 stp_hold_timer_expiry(struct stp_port *p) OVS_REQUIRES(mutex)
1425 {
1426     if (p->config_pending) {
1427         stp_transmit_config(p);
1428     }
1429 }
1430
1431 static void
1432 stp_initialize_port(struct stp_port *p, enum stp_state state)
1433     OVS_REQUIRES(mutex)
1434 {
1435     ovs_assert(state & (STP_DISABLED | STP_BLOCKING));
1436     stp_become_designated_port(p);
1437     stp_set_port_state(p, state);
1438     p->topology_change_ack = false;
1439     p->config_pending = false;
1440     p->change_detection_enabled = true;
1441     p->aux = NULL;
1442     stp_stop_timer(&p->message_age_timer);
1443     stp_stop_timer(&p->forward_delay_timer);
1444     stp_stop_timer(&p->hold_timer);
1445     p->tx_count = p->rx_count = p->error_count = 0;
1446 }
1447
1448 static void
1449 stp_become_root_bridge(struct stp *stp) OVS_REQUIRES(mutex)
1450 {
1451     stp->max_age = stp->bridge_max_age;
1452     stp->hello_time = stp->bridge_hello_time;
1453     stp->forward_delay = stp->bridge_forward_delay;
1454     stp_topology_change_detection(stp);
1455     stp_stop_timer(&stp->tcn_timer);
1456     stp_config_bpdu_generation(stp);
1457     stp_start_timer(&stp->hello_timer, 0);
1458 }
1459
1460 static void
1461 stp_start_timer(struct stp_timer *timer, int value) OVS_REQUIRES(mutex)
1462 {
1463     timer->value = value;
1464     timer->active = true;
1465 }
1466
1467 static void
1468 stp_stop_timer(struct stp_timer *timer) OVS_REQUIRES(mutex)
1469 {
1470     timer->active = false;
1471 }
1472
1473 static bool
1474 stp_timer_expired(struct stp_timer *timer, int elapsed, int timeout)
1475     OVS_REQUIRES(mutex)
1476 {
1477     if (timer->active) {
1478         timer->value += elapsed;
1479         if (timer->value >= timeout) {
1480             timer->active = false;
1481             return true;
1482         }
1483     }
1484     return false;
1485 }
1486
1487 /* Returns the number of whole STP timer ticks in 'ms' milliseconds.  There
1488  * are 256 STP timer ticks per second. */
1489 static int
1490 ms_to_timer(int ms)
1491 {
1492     return ms * 0x100 / 1000;
1493 }
1494
1495 /* Returns the number of whole milliseconds in 'timer' STP timer ticks.  There
1496  * are 256 STP timer ticks per second. */
1497 static int
1498 timer_to_ms(int timer)
1499 {
1500     return timer * 1000 / 0x100;
1501 }
1502
1503 static int
1504 clamp(int x, int min, int max)
1505 {
1506     return x < min ? min : x > max ? max : x;
1507 }
1508
1509 static void
1510 stp_update_bridge_timers(struct stp *stp) OVS_REQUIRES(mutex)
1511 {
1512     int ht, ma, fd;
1513
1514     ht = clamp(stp->rq_hello_time, 1000, 10000);
1515     ma = clamp(stp->rq_max_age, MAX(2 * (ht + 1000), 6000), 40000);
1516     fd = clamp(stp->rq_forward_delay, ma / 2 + 1000, 30000);
1517
1518     stp->bridge_hello_time = ms_to_timer(ht);
1519     stp->bridge_max_age = ms_to_timer(ma);
1520     stp->bridge_forward_delay = ms_to_timer(fd);
1521
1522     if (stp_is_root_bridge(stp)) {
1523         stp->max_age = stp->bridge_max_age;
1524         stp->hello_time = stp->bridge_hello_time;
1525         stp->forward_delay = stp->bridge_forward_delay;
1526     }
1527 }
1528
1529 static void
1530 stp_send_bpdu(struct stp_port *p, const void *bpdu, size_t bpdu_size)
1531     OVS_REQUIRES(mutex)
1532 {
1533     struct eth_header *eth;
1534     struct llc_header *llc;
1535     struct ofpbuf *pkt;
1536
1537     /* Skeleton. */
1538     pkt = ofpbuf_new(ETH_HEADER_LEN + LLC_HEADER_LEN + bpdu_size);
1539     pkt->l2 = eth = ofpbuf_put_zeros(pkt, sizeof *eth);
1540     llc = ofpbuf_put_zeros(pkt, sizeof *llc);
1541     pkt->l3 = ofpbuf_put(pkt, bpdu, bpdu_size);
1542
1543     /* 802.2 header. */
1544     memcpy(eth->eth_dst, eth_addr_stp, ETH_ADDR_LEN);
1545     /* p->stp->send_bpdu() must fill in source address. */
1546     eth->eth_type = htons(pkt->size - ETH_HEADER_LEN);
1547
1548     /* LLC header. */
1549     llc->llc_dsap = STP_LLC_DSAP;
1550     llc->llc_ssap = STP_LLC_SSAP;
1551     llc->llc_cntl = STP_LLC_CNTL;
1552
1553     p->stp->send_bpdu(pkt, stp_port_no(p), p->stp->aux);
1554     p->tx_count++;
1555 }
1556 \f
1557 /* Unixctl. */
1558
1559 static struct stp *
1560 stp_find(const char *name) OVS_REQUIRES(mutex)
1561 {
1562     struct stp *stp;
1563
1564     LIST_FOR_EACH (stp, node, all_stps) {
1565         if (!strcmp(stp->name, name)) {
1566             return stp;
1567         }
1568     }
1569     return NULL;
1570 }
1571
1572 static void
1573 stp_unixctl_tcn(struct unixctl_conn *conn, int argc,
1574                 const char *argv[], void *aux OVS_UNUSED)
1575 {
1576     ovs_mutex_lock(&mutex);
1577     if (argc > 1) {
1578         struct stp *stp = stp_find(argv[1]);
1579
1580         if (!stp) {
1581             unixctl_command_reply_error(conn, "no such stp object");
1582             goto out;
1583         }
1584         stp_topology_change_detection(stp);
1585     } else {
1586         struct stp *stp;
1587
1588         LIST_FOR_EACH (stp, node, all_stps) {
1589             stp_topology_change_detection(stp);
1590         }
1591     }
1592
1593     unixctl_command_reply(conn, "OK");
1594
1595 out:
1596     ovs_mutex_unlock(&mutex);
1597 }