ovs-ctl: Remove vport_* modules when downgrade from branches > 2.3.
[cascardo/ovs.git] / lib / stp.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /* Based on sample implementation in 802.1D-1998.  Above copyright and license
18  * applies to all modifications. */
19
20 #include <config.h>
21
22 #include "stp.h"
23 #include <sys/types.h>
24 #include <netinet/in.h>
25 #include <arpa/inet.h>
26 #include <inttypes.h>
27 #include <stdlib.h>
28 #include "byte-order.h"
29 #include "connectivity.h"
30 #include "ofpbuf.h"
31 #include "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     struct ovs_refcount 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     ovs_refcount_init(&stp->ref_cnt);
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         ovs_refcount_ref(&stp->ref_cnt);
322     }
323     return stp;
324 }
325
326 /* Destroys 'stp'. */
327 void
328 stp_unref(struct stp *stp)
329 {
330     if (stp && ovs_refcount_unref(&stp->ref_cnt) == 1) {
331         ovs_mutex_lock(&mutex);
332         list_remove(&stp->node);
333         ovs_mutex_unlock(&mutex);
334         free(stp->name);
335         free(stp);
336     }
337 }
338
339 /* Runs 'stp' given that 'ms' milliseconds have passed. */
340 void
341 stp_tick(struct stp *stp, int ms)
342 {
343     struct stp_port *p;
344     int elapsed;
345
346     ovs_mutex_lock(&mutex);
347     /* Convert 'ms' to STP timer ticks.  Preserve any leftover milliseconds
348      * from previous stp_tick() calls so that we don't lose STP ticks when we
349      * are called too frequently. */
350     ms = clamp(ms, 0, INT_MAX - 1000) + stp->elapsed_remainder;
351     elapsed = ms_to_timer(ms);
352     stp->elapsed_remainder = ms - timer_to_ms(elapsed);
353     if (!elapsed) {
354         goto out;
355     }
356
357     if (stp_timer_expired(&stp->hello_timer, elapsed, stp->hello_time)) {
358         stp_hello_timer_expiry(stp);
359     }
360     if (stp_timer_expired(&stp->tcn_timer, elapsed, stp->bridge_hello_time)) {
361         stp_tcn_timer_expiry(stp);
362     }
363     if (stp_timer_expired(&stp->topology_change_timer, elapsed,
364                           stp->max_age + stp->forward_delay)) {
365         stp_topology_change_timer_expiry(stp);
366     }
367     FOR_EACH_ENABLED_PORT (p, stp) {
368         if (stp_timer_expired(&p->message_age_timer, elapsed, stp->max_age)) {
369             stp_message_age_timer_expiry(p);
370         }
371     }
372     FOR_EACH_ENABLED_PORT (p, stp) {
373         if (stp_timer_expired(&p->forward_delay_timer, elapsed,
374                               stp->forward_delay)) {
375             stp_forward_delay_timer_expiry(p);
376         }
377         if (stp_timer_expired(&p->hold_timer, elapsed, ms_to_timer(1000))) {
378             stp_hold_timer_expiry(p);
379         }
380     }
381
382 out:
383     ovs_mutex_unlock(&mutex);
384 }
385
386 static void
387 set_bridge_id(struct stp *stp, stp_identifier new_bridge_id)
388     OVS_REQUIRES(mutex)
389 {
390     if (new_bridge_id != stp->bridge_id) {
391         bool root;
392         struct stp_port *p;
393
394         root = stp_is_root_bridge(stp);
395         FOR_EACH_ENABLED_PORT (p, stp) {
396             if (stp_is_designated_port(p)) {
397                 p->designated_bridge = new_bridge_id;
398             }
399         }
400         stp->bridge_id = new_bridge_id;
401         stp_configuration_update(stp);
402         stp_port_state_selection(stp);
403         if (stp_is_root_bridge(stp) && !root) {
404             stp_become_root_bridge(stp);
405         }
406     }
407 }
408
409 void
410 stp_set_bridge_id(struct stp *stp, stp_identifier bridge_id)
411 {
412     const uint64_t mac_bits = (UINT64_C(1) << 48) - 1;
413     const uint64_t pri_bits = ~mac_bits;
414     ovs_mutex_lock(&mutex);
415     set_bridge_id(stp, (stp->bridge_id & pri_bits) | (bridge_id & mac_bits));
416     ovs_mutex_unlock(&mutex);
417 }
418
419 void
420 stp_set_bridge_priority(struct stp *stp, uint16_t new_priority)
421 {
422     const uint64_t mac_bits = (UINT64_C(1) << 48) - 1;
423     ovs_mutex_lock(&mutex);
424     set_bridge_id(stp, ((stp->bridge_id & mac_bits)
425                         | ((uint64_t) new_priority << 48)));
426     ovs_mutex_unlock(&mutex);
427 }
428
429 /* Sets the desired hello time for 'stp' to 'ms', in milliseconds.  The actual
430  * hello time is clamped to the range of 1 to 10 seconds and subject to the
431  * relationship (bridge_max_age >= 2 * (bridge_hello_time + 1 s)).  The bridge
432  * hello time is only used when 'stp' is the root bridge. */
433 void
434 stp_set_hello_time(struct stp *stp, int ms)
435 {
436     ovs_mutex_lock(&mutex);
437     stp->rq_hello_time = ms;
438     stp_update_bridge_timers(stp);
439     ovs_mutex_unlock(&mutex);
440 }
441
442 /* Sets the desired max age for 'stp' to 'ms', in milliseconds.  The actual max
443  * age is clamped to the range of 6 to 40 seconds and subject to the
444  * relationships (2 * (bridge_forward_delay - 1 s) >= bridge_max_age) and
445  * (bridge_max_age >= 2 * (bridge_hello_time + 1 s)).  The bridge max age is
446  * only used when 'stp' is the root bridge. */
447 void
448 stp_set_max_age(struct stp *stp, int ms)
449 {
450     ovs_mutex_lock(&mutex);
451     stp->rq_max_age = ms;
452     stp_update_bridge_timers(stp);
453     ovs_mutex_unlock(&mutex);
454 }
455
456 /* Sets the desired forward delay for 'stp' to 'ms', in milliseconds.  The
457  * actual forward delay is clamped to the range of 4 to 30 seconds and subject
458  * to the relationship (2 * (bridge_forward_delay - 1 s) >= bridge_max_age).
459  * The bridge forward delay is only used when 'stp' is the root bridge. */
460 void
461 stp_set_forward_delay(struct stp *stp, int ms)
462 {
463     ovs_mutex_lock(&mutex);
464     stp->rq_forward_delay = ms;
465     stp_update_bridge_timers(stp);
466     ovs_mutex_unlock(&mutex);
467 }
468
469 /* Returns the name given to 'stp' in the call to stp_create(). */
470 const char *
471 stp_get_name(const struct stp *stp)
472 {
473     char *name;
474
475     ovs_mutex_lock(&mutex);
476     name = stp->name;
477     ovs_mutex_unlock(&mutex);
478     return name;
479 }
480
481 /* Returns the bridge ID for 'stp'. */
482 stp_identifier
483 stp_get_bridge_id(const struct stp *stp)
484 {
485     stp_identifier bridge_id;
486
487     ovs_mutex_lock(&mutex);
488     bridge_id = stp->bridge_id;
489     ovs_mutex_unlock(&mutex);
490     return bridge_id;
491 }
492
493 /* Returns the bridge ID of the bridge currently believed to be the root. */
494 stp_identifier
495 stp_get_designated_root(const struct stp *stp)
496 {
497     stp_identifier designated_root;
498
499     ovs_mutex_lock(&mutex);
500     designated_root = stp->designated_root;
501     ovs_mutex_unlock(&mutex);
502     return designated_root;
503 }
504
505 /* Returns true if 'stp' believes itself to the be root of the spanning tree,
506  * false otherwise. */
507 bool
508 stp_is_root_bridge(const struct stp *stp)
509 {
510     bool is_root;
511
512     ovs_mutex_lock(&mutex);
513     is_root = stp->bridge_id == stp->designated_root;
514     ovs_mutex_unlock(&mutex);
515     return is_root;
516 }
517
518 /* Returns the cost of the path from 'stp' to the root of the spanning tree. */
519 int
520 stp_get_root_path_cost(const struct stp *stp)
521 {
522     int cost;
523
524     ovs_mutex_lock(&mutex);
525     cost = stp->root_path_cost;
526     ovs_mutex_unlock(&mutex);
527     return cost;
528 }
529
530 /* Returns the bridge hello time, in ms.  The returned value is not necessarily
531  * the value passed to stp_set_hello_time(): it is clamped to the valid range
532  * and quantized to the STP timer resolution.  */
533 int
534 stp_get_hello_time(const struct stp *stp)
535 {
536     int time;
537
538     ovs_mutex_lock(&mutex);
539     time = timer_to_ms(stp->bridge_hello_time);
540     ovs_mutex_unlock(&mutex);
541     return time;
542 }
543
544 /* Returns the bridge max age, in ms.  The returned value is not necessarily
545  * the value passed to stp_set_max_age(): it is clamped to the valid range,
546  * quantized to the STP timer resolution, and adjusted to match the constraints
547  * due to the hello time.  */
548 int
549 stp_get_max_age(const struct stp *stp)
550 {
551     int time;
552
553     ovs_mutex_lock(&mutex);
554     time = timer_to_ms(stp->bridge_max_age);
555     ovs_mutex_unlock(&mutex);
556     return time;
557 }
558
559 /* Returns the bridge forward delay, in ms.  The returned value is not
560  * necessarily the value passed to stp_set_forward_delay(): it is clamped to
561  * the valid range, quantized to the STP timer resolution, and adjusted to
562  * match the constraints due to the forward delay.  */
563 int
564 stp_get_forward_delay(const struct stp *stp)
565 {
566     int time;
567
568     ovs_mutex_lock(&mutex);
569     time = timer_to_ms(stp->bridge_forward_delay);
570     ovs_mutex_unlock(&mutex);
571     return time;
572 }
573
574 /* Returns true if something has happened to 'stp' which necessitates flushing
575  * the client's MAC learning table.  Calling this function resets 'stp' so that
576  * future calls will return false until flushing is required again. */
577 bool
578 stp_check_and_reset_fdb_flush(struct stp *stp)
579 {
580     bool needs_flush;
581
582     ovs_mutex_lock(&mutex);
583     needs_flush = stp->fdb_needs_flush;
584     stp->fdb_needs_flush = false;
585     ovs_mutex_unlock(&mutex);
586     return needs_flush;
587 }
588
589 /* Returns the port in 'stp' with index 'port_no', which must be between 0 and
590  * STP_MAX_PORTS. */
591 struct stp_port *
592 stp_get_port(struct stp *stp, int port_no)
593 {
594     struct stp_port *port;
595
596     ovs_mutex_lock(&mutex);
597     ovs_assert(port_no >= 0 && port_no < ARRAY_SIZE(stp->ports));
598     port = &stp->ports[port_no];
599     ovs_mutex_unlock(&mutex);
600     return port;
601 }
602
603 /* Returns the port connecting 'stp' to the root bridge, or a null pointer if
604  * there is no such port. */
605 struct stp_port *
606 stp_get_root_port(struct stp *stp)
607 {
608     struct stp_port *port;
609
610     ovs_mutex_lock(&mutex);
611     port = stp->root_port;
612     ovs_mutex_unlock(&mutex);
613     return port;
614 }
615
616 /* Finds a port whose state has changed.  If successful, stores the port whose
617  * state changed in '*portp' and returns true.  If no port has changed, stores
618  * NULL in '*portp' and returns false. */
619 bool
620 stp_get_changed_port(struct stp *stp, struct stp_port **portp)
621 {
622     struct stp_port *end, *p;
623     bool changed = false;
624
625     ovs_mutex_lock(&mutex);
626     end = &stp->ports[ARRAY_SIZE(stp->ports)];
627     for (p = stp->first_changed_port; p < end; p++) {
628         if (p->state_changed) {
629             p->state_changed = false;
630             stp->first_changed_port = p + 1;
631             *portp = p;
632             changed = true;
633             goto out;
634         }
635     }
636     stp->first_changed_port = end;
637     *portp = NULL;
638
639 out:
640     ovs_mutex_unlock(&mutex);
641     return changed;
642 }
643
644 /* Returns the name for the given 'state' (for use in debugging and log
645  * messages). */
646 const char *
647 stp_state_name(enum stp_state state)
648 {
649     switch (state) {
650     case STP_DISABLED:
651         return "disabled";
652     case STP_LISTENING:
653         return "listening";
654     case STP_LEARNING:
655         return "learning";
656     case STP_FORWARDING:
657         return "forwarding";
658     case STP_BLOCKING:
659         return "blocking";
660     default:
661         OVS_NOT_REACHED();
662     }
663 }
664
665 /* Returns true if 'state' is one in which packets received on a port should
666  * be forwarded, false otherwise.
667  *
668  * Returns true if 'state' is STP_DISABLED, since presumably in that case the
669  * port should still work, just not have STP applied to it. */
670 bool
671 stp_forward_in_state(enum stp_state state)
672 {
673     return (state & (STP_DISABLED | STP_FORWARDING)) != 0;
674 }
675
676 /* Returns true if 'state' is one in which MAC learning should be done on
677  * packets received on a port, 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_learn_in_state(enum stp_state state)
683 {
684     return (state & (STP_DISABLED | STP_LEARNING | STP_FORWARDING)) != 0;
685 }
686
687 /* Returns true if 'state' is one in which bpdus should be forwarded on a
688  * port, false otherwise.
689  *
690  * Returns true if 'state' is STP_DISABLED, since in that case the port does
691  * not generate the bpdu and should just forward it (e.g. patch port on pif
692  * bridge). */
693 bool
694 stp_should_forward_bpdu(enum stp_state state)
695 {
696     return (state &
697             ( STP_DISABLED | STP_LISTENING | STP_LEARNING
698               | STP_FORWARDING)) != 0;
699 }
700
701 /* Returns the name for the given 'role' (for use in debugging and log
702  * messages). */
703 const char *
704 stp_role_name(enum stp_role role)
705 {
706     switch (role) {
707     case STP_ROLE_ROOT:
708         return "root";
709     case STP_ROLE_DESIGNATED:
710         return "designated";
711     case STP_ROLE_ALTERNATE:
712         return "alternate";
713     case STP_ROLE_DISABLED:
714         return "disabled";
715     default:
716         OVS_NOT_REACHED();
717     }
718 }
719
720 /* Notifies the STP entity that bridge protocol data unit 'bpdu', which is
721  * 'bpdu_size' bytes in length, was received on port 'p'.
722  *
723  * This function may call the 'send_bpdu' function provided to stp_create(). */
724 void
725 stp_received_bpdu(struct stp_port *p, const void *bpdu, size_t bpdu_size)
726 {
727     struct stp *stp = p->stp;
728     const struct stp_bpdu_header *header;
729
730     ovs_mutex_lock(&mutex);
731     if (p->state == STP_DISABLED) {
732         goto out;
733     }
734
735     if (bpdu_size < sizeof(struct stp_bpdu_header)) {
736         VLOG_WARN("%s: received runt %"PRIuSIZE"-byte BPDU", stp->name, bpdu_size);
737         p->error_count++;
738         goto out;
739     }
740
741     header = bpdu;
742     if (header->protocol_id != htons(STP_PROTOCOL_ID)) {
743         VLOG_WARN("%s: received BPDU with unexpected protocol ID %"PRIu16,
744                   stp->name, ntohs(header->protocol_id));
745         p->error_count++;
746         goto out;
747     }
748     if (header->protocol_version != STP_PROTOCOL_VERSION) {
749         VLOG_DBG("%s: received BPDU with unexpected protocol version %"PRIu8,
750                  stp->name, header->protocol_version);
751     }
752
753     switch (header->bpdu_type) {
754     case STP_TYPE_CONFIG:
755         if (bpdu_size < sizeof(struct stp_config_bpdu)) {
756             VLOG_WARN("%s: received config BPDU with invalid size %"PRIuSIZE,
757                       stp->name, bpdu_size);
758             p->error_count++;
759             goto out;
760         }
761         stp_received_config_bpdu(stp, p, bpdu);
762         break;
763
764     case STP_TYPE_TCN:
765         if (bpdu_size != sizeof(struct stp_tcn_bpdu)) {
766             VLOG_WARN("%s: received TCN BPDU with invalid size %"PRIuSIZE,
767                       stp->name, bpdu_size);
768             p->error_count++;
769             goto out;
770         }
771         stp_received_tcn_bpdu(stp, p);
772         break;
773
774     default:
775         VLOG_WARN("%s: received BPDU of unexpected type %"PRIu8,
776                   stp->name, header->bpdu_type);
777         p->error_count++;
778         goto out;
779     }
780     p->rx_count++;
781
782 out:
783     ovs_mutex_unlock(&mutex);
784 }
785
786 /* Returns the STP entity in which 'p' is nested. */
787 struct stp *
788 stp_port_get_stp(struct stp_port *p)
789 {
790     struct stp *stp;
791
792     ovs_mutex_lock(&mutex);
793     stp = p->stp;
794     ovs_mutex_unlock(&mutex);
795     return stp;
796 }
797
798 /* Sets the 'aux' member of 'p'.
799  *
800  * The 'aux' member will be reset to NULL when stp_port_disable() is
801  * called or stp_port_enable() is called when the port is in a Disabled
802  * state. */
803 void
804 stp_port_set_aux(struct stp_port *p, void *aux)
805 {
806     ovs_mutex_lock(&mutex);
807     p->aux = aux;
808     ovs_mutex_unlock(&mutex);
809 }
810
811 /* Returns the 'aux' member of 'p'. */
812 void *
813 stp_port_get_aux(struct stp_port *p)
814 {
815     void *aux;
816
817     ovs_mutex_lock(&mutex);
818     aux = p->aux;
819     ovs_mutex_unlock(&mutex);
820     return aux;
821 }
822
823 /* Returns the index of port 'p' within its bridge. */
824 int
825 stp_port_no(const struct stp_port *p)
826 {
827     struct stp *stp;
828     int index;
829
830     ovs_mutex_lock(&mutex);
831     stp = p->stp;
832     ovs_assert(p >= stp->ports && p < &stp->ports[ARRAY_SIZE(stp->ports)]);
833     index = p - p->stp->ports;
834     ovs_mutex_unlock(&mutex);
835     return index;
836 }
837
838 /* Returns the port ID for 'p'. */
839 int
840 stp_port_get_id(const struct stp_port *p)
841 {
842     int port_id;
843
844     ovs_mutex_lock(&mutex);
845     port_id = p->port_id;
846     ovs_mutex_unlock(&mutex);
847     return port_id;
848 }
849
850 /* Returns the state of port 'p'. */
851 enum stp_state
852 stp_port_get_state(const struct stp_port *p)
853 {
854     enum stp_state state;
855
856     ovs_mutex_lock(&mutex);
857     state = p->state;
858     ovs_mutex_unlock(&mutex);
859     return state;
860 }
861
862 /* Returns the role of port 'p'. */
863 enum stp_role
864 stp_port_get_role(const struct stp_port *p)
865 {
866     struct stp_port *root_port;
867     enum stp_role role;
868
869     ovs_mutex_lock(&mutex);
870     root_port = p->stp->root_port;
871     if (root_port && root_port->port_id == p->port_id) {
872         role = STP_ROLE_ROOT;
873     } else if (stp_is_designated_port(p)) {
874         role = STP_ROLE_DESIGNATED;
875     } else if (p->state == STP_DISABLED) {
876         role = STP_ROLE_DISABLED;
877     } else {
878         role = STP_ROLE_ALTERNATE;
879     }
880     ovs_mutex_unlock(&mutex);
881     return role;
882 }
883
884 /* Retrieves BPDU transmit and receive counts for 'p'. */
885 void
886 stp_port_get_counts(const struct stp_port *p,
887                     int *tx_count, int *rx_count, int *error_count)
888 {
889     ovs_mutex_lock(&mutex);
890     *tx_count = p->tx_count;
891     *rx_count = p->rx_count;
892     *error_count = p->error_count;
893     ovs_mutex_unlock(&mutex);
894 }
895
896 /* Disables STP on port 'p'. */
897 void
898 stp_port_disable(struct stp_port *p)
899 {
900     struct stp *stp;
901
902     ovs_mutex_lock(&mutex);
903     stp = p->stp;
904     if (p->state != STP_DISABLED) {
905         bool root = stp_is_root_bridge(stp);
906         stp_become_designated_port(p);
907         stp_set_port_state(p, STP_DISABLED);
908         p->topology_change_ack = false;
909         p->config_pending = false;
910         stp_stop_timer(&p->message_age_timer);
911         stp_stop_timer(&p->forward_delay_timer);
912         stp_configuration_update(stp);
913         stp_port_state_selection(stp);
914         if (stp_is_root_bridge(stp) && !root) {
915             stp_become_root_bridge(stp);
916         }
917         p->aux = NULL;
918     }
919     ovs_mutex_unlock(&mutex);
920 }
921
922 /* Enables STP on port 'p'.  The port will initially be in "blocking" state. */
923 void
924 stp_port_enable(struct stp_port *p)
925 {
926     ovs_mutex_lock(&mutex);
927     if (p->state == STP_DISABLED) {
928         stp_initialize_port(p, STP_BLOCKING);
929         stp_port_state_selection(p->stp);
930     }
931     ovs_mutex_unlock(&mutex);
932 }
933
934 /* Sets the priority of port 'p' to 'new_priority'.  Lower numerical values
935  * are interpreted as higher priorities. */
936 void
937 stp_port_set_priority(struct stp_port *p, uint8_t new_priority)
938 {
939     uint16_t new_port_id;
940
941     ovs_mutex_lock(&mutex);
942     new_port_id  = (p->port_id & 0xff) | (new_priority << 8);
943     if (p->port_id != new_port_id) {
944         struct stp *stp = p->stp;
945         if (stp_is_designated_port(p)) {
946             p->designated_port = new_port_id;
947         }
948         p->port_id = new_port_id;
949         if (stp->bridge_id == p->designated_bridge
950             && p->port_id < p->designated_port) {
951             stp_become_designated_port(p);
952             stp_port_state_selection(stp);
953         }
954     }
955     ovs_mutex_unlock(&mutex);
956 }
957
958 /* Convert 'speed' (measured in Mb/s) into the path cost. */
959 uint16_t
960 stp_convert_speed_to_cost(unsigned int speed)
961 {
962     uint16_t ret;
963
964     ovs_mutex_lock(&mutex);
965     ret = speed >= 10000 ? 2  /* 10 Gb/s. */
966         : speed >= 1000 ? 4 /* 1 Gb/s. */
967         : speed >= 100 ? 19 /* 100 Mb/s. */
968         : speed >= 16 ? 62  /* 16 Mb/s. */
969         : speed >= 10 ? 100 /* 10 Mb/s. */
970         : speed >= 4 ? 250  /* 4 Mb/s. */
971         : 19;             /* 100 Mb/s (guess). */
972     ovs_mutex_unlock(&mutex);
973     return ret;
974 }
975
976 /* Sets the path cost of port 'p' to 'path_cost'.  Lower values are generally
977  * used to indicate faster links.  Use stp_port_set_speed() to automatically
978  * generate a default path cost from a link speed. */
979 void
980 stp_port_set_path_cost(struct stp_port *p, uint16_t path_cost)
981 {
982     ovs_mutex_lock(&mutex);
983     if (p->path_cost != path_cost) {
984         struct stp *stp = p->stp;
985         p->path_cost = path_cost;
986         stp_configuration_update(stp);
987         stp_port_state_selection(stp);
988     }
989     ovs_mutex_unlock(&mutex);
990 }
991
992 /* Sets the path cost of port 'p' based on 'speed' (measured in Mb/s). */
993 void
994 stp_port_set_speed(struct stp_port *p, unsigned int speed)
995 {
996     stp_port_set_path_cost(p, stp_convert_speed_to_cost(speed));
997 }
998
999 /* Enables topology change detection on port 'p'. */
1000 void
1001 stp_port_enable_change_detection(struct stp_port *p)
1002 {
1003     p->change_detection_enabled = true;
1004 }
1005
1006 /* Disables topology change detection on port 'p'. */
1007 void
1008 stp_port_disable_change_detection(struct stp_port *p)
1009 {
1010     p->change_detection_enabled = false;
1011 }
1012 \f
1013 static void
1014 stp_transmit_config(struct stp_port *p) OVS_REQUIRES(mutex)
1015 {
1016     struct stp *stp = p->stp;
1017     bool root = stp_is_root_bridge(stp);
1018     if (!root && !stp->root_port) {
1019         return;
1020     }
1021     if (p->hold_timer.active) {
1022         p->config_pending = true;
1023     } else {
1024         struct stp_config_bpdu config;
1025         memset(&config, 0, sizeof config);
1026         config.header.protocol_id = htons(STP_PROTOCOL_ID);
1027         config.header.protocol_version = STP_PROTOCOL_VERSION;
1028         config.header.bpdu_type = STP_TYPE_CONFIG;
1029         config.flags = 0;
1030         if (p->topology_change_ack) {
1031             config.flags |= STP_CONFIG_TOPOLOGY_CHANGE_ACK;
1032         }
1033         if (stp->topology_change) {
1034             config.flags |= STP_CONFIG_TOPOLOGY_CHANGE;
1035         }
1036         config.root_id = htonll(stp->designated_root);
1037         config.root_path_cost = htonl(stp->root_path_cost);
1038         config.bridge_id = htonll(stp->bridge_id);
1039         config.port_id = htons(p->port_id);
1040         if (root) {
1041             config.message_age = htons(0);
1042         } else {
1043             config.message_age = htons(stp->root_port->message_age_timer.value
1044                                        + MESSAGE_AGE_INCREMENT);
1045         }
1046         config.max_age = htons(stp->max_age);
1047         config.hello_time = htons(stp->hello_time);
1048         config.forward_delay = htons(stp->forward_delay);
1049         if (ntohs(config.message_age) < stp->max_age) {
1050             p->topology_change_ack = false;
1051             p->config_pending = false;
1052             stp_send_bpdu(p, &config, sizeof config);
1053             stp_start_timer(&p->hold_timer, 0);
1054         }
1055     }
1056 }
1057
1058 static bool
1059 stp_supersedes_port_info(const struct stp_port *p,
1060                          const struct stp_config_bpdu *config)
1061      OVS_REQUIRES(mutex)
1062 {
1063     if (ntohll(config->root_id) != p->designated_root) {
1064         return ntohll(config->root_id) < p->designated_root;
1065     } else if (ntohl(config->root_path_cost) != p->designated_cost) {
1066         return ntohl(config->root_path_cost) < p->designated_cost;
1067     } else if (ntohll(config->bridge_id) != p->designated_bridge) {
1068         return ntohll(config->bridge_id) < p->designated_bridge;
1069     } else {
1070         return (ntohll(config->bridge_id) != p->stp->bridge_id
1071                 || ntohs(config->port_id) <= p->designated_port);
1072     }
1073 }
1074
1075 static void
1076 stp_record_config_information(struct stp_port *p,
1077                               const struct stp_config_bpdu *config)
1078      OVS_REQUIRES(mutex)
1079 {
1080     p->designated_root = ntohll(config->root_id);
1081     p->designated_cost = ntohl(config->root_path_cost);
1082     p->designated_bridge = ntohll(config->bridge_id);
1083     p->designated_port = ntohs(config->port_id);
1084     stp_start_timer(&p->message_age_timer, ntohs(config->message_age));
1085 }
1086
1087 static void
1088 stp_record_config_timeout_values(struct stp *stp,
1089                                  const struct stp_config_bpdu  *config)
1090      OVS_REQUIRES(mutex)
1091 {
1092     stp->max_age = ntohs(config->max_age);
1093     stp->hello_time = ntohs(config->hello_time);
1094     stp->forward_delay = ntohs(config->forward_delay);
1095     stp->topology_change = config->flags & STP_CONFIG_TOPOLOGY_CHANGE;
1096 }
1097
1098 static bool
1099 stp_is_designated_port(const struct stp_port *p) OVS_REQUIRES(mutex)
1100 {
1101     return (p->designated_bridge == p->stp->bridge_id
1102             && p->designated_port == p->port_id);
1103 }
1104
1105 static void
1106 stp_config_bpdu_generation(struct stp *stp) OVS_REQUIRES(mutex)
1107 {
1108     struct stp_port *p;
1109
1110     FOR_EACH_ENABLED_PORT (p, stp) {
1111         if (stp_is_designated_port(p)) {
1112             stp_transmit_config(p);
1113         }
1114     }
1115 }
1116
1117 static void
1118 stp_transmit_tcn(struct stp *stp) OVS_REQUIRES(mutex)
1119 {
1120     struct stp_port *p = stp->root_port;
1121     struct stp_tcn_bpdu tcn_bpdu;
1122     if (!p) {
1123         return;
1124     }
1125     tcn_bpdu.header.protocol_id = htons(STP_PROTOCOL_ID);
1126     tcn_bpdu.header.protocol_version = STP_PROTOCOL_VERSION;
1127     tcn_bpdu.header.bpdu_type = STP_TYPE_TCN;
1128     stp_send_bpdu(p, &tcn_bpdu, sizeof tcn_bpdu);
1129 }
1130
1131 static void
1132 stp_configuration_update(struct stp *stp) OVS_REQUIRES(mutex)
1133 {
1134     stp_root_selection(stp);
1135     stp_designated_port_selection(stp);
1136     seq_change(connectivity_seq_get());
1137 }
1138
1139 static bool
1140 stp_supersedes_root(const struct stp_port *root, const struct stp_port *p)
1141     OVS_REQUIRES(mutex)
1142 {
1143     int p_cost = p->designated_cost + p->path_cost;
1144     int root_cost = root->designated_cost + root->path_cost;
1145
1146     if (p->designated_root != root->designated_root) {
1147         return p->designated_root < root->designated_root;
1148     } else if (p_cost != root_cost) {
1149         return p_cost < root_cost;
1150     } else if (p->designated_bridge != root->designated_bridge) {
1151         return p->designated_bridge < root->designated_bridge;
1152     } else if (p->designated_port != root->designated_port) {
1153         return p->designated_port < root->designated_port;
1154     } else {
1155         return p->port_id < root->port_id;
1156     }
1157 }
1158
1159 static void
1160 stp_root_selection(struct stp *stp) OVS_REQUIRES(mutex)
1161 {
1162     struct stp_port *p, *root;
1163
1164     root = NULL;
1165     FOR_EACH_ENABLED_PORT (p, stp) {
1166         if (stp_is_designated_port(p)
1167             || p->designated_root >= stp->bridge_id) {
1168             continue;
1169         }
1170         if (root && !stp_supersedes_root(root, p)) {
1171             continue;
1172         }
1173         root = p;
1174     }
1175     stp->root_port = root;
1176     if (!root) {
1177         stp->designated_root = stp->bridge_id;
1178         stp->root_path_cost = 0;
1179     } else {
1180         stp->designated_root = root->designated_root;
1181         stp->root_path_cost = root->designated_cost + root->path_cost;
1182     }
1183 }
1184
1185 static void
1186 stp_designated_port_selection(struct stp *stp) OVS_REQUIRES(mutex)
1187 {
1188     struct stp_port *p;
1189
1190     FOR_EACH_ENABLED_PORT (p, stp) {
1191         if (stp_is_designated_port(p)
1192             || p->designated_root != stp->designated_root
1193             || stp->root_path_cost < p->designated_cost
1194             || (stp->root_path_cost == p->designated_cost
1195                 && (stp->bridge_id < p->designated_bridge
1196                     || (stp->bridge_id == p->designated_bridge
1197                         && p->port_id <= p->designated_port))))
1198         {
1199             stp_become_designated_port(p);
1200         }
1201     }
1202 }
1203
1204 static void
1205 stp_become_designated_port(struct stp_port *p) OVS_REQUIRES(mutex)
1206 {
1207     struct stp *stp = p->stp;
1208     p->designated_root = stp->designated_root;
1209     p->designated_cost = stp->root_path_cost;
1210     p->designated_bridge = stp->bridge_id;
1211     p->designated_port = p->port_id;
1212 }
1213
1214 static void
1215 stp_port_state_selection(struct stp *stp) OVS_REQUIRES(mutex)
1216 {
1217     struct stp_port *p;
1218
1219     FOR_EACH_ENABLED_PORT (p, stp) {
1220         if (p == stp->root_port) {
1221             p->config_pending = false;
1222             p->topology_change_ack = false;
1223             stp_make_forwarding(p);
1224         } else if (stp_is_designated_port(p)) {
1225             stp_stop_timer(&p->message_age_timer);
1226             stp_make_forwarding(p);
1227         } else {
1228             p->config_pending = false;
1229             p->topology_change_ack = false;
1230             stp_make_blocking(p);
1231         }
1232     }
1233 }
1234
1235 static void
1236 stp_make_forwarding(struct stp_port *p) OVS_REQUIRES(mutex)
1237 {
1238     if (p->state == STP_BLOCKING) {
1239         stp_set_port_state(p, STP_LISTENING);
1240         stp_start_timer(&p->forward_delay_timer, 0);
1241     }
1242 }
1243
1244 static void
1245 stp_make_blocking(struct stp_port *p) OVS_REQUIRES(mutex)
1246 {
1247     if (!(p->state & (STP_DISABLED | STP_BLOCKING))) {
1248         if (p->state & (STP_FORWARDING | STP_LEARNING)) {
1249             if (p->change_detection_enabled) {
1250                 stp_topology_change_detection(p->stp);
1251             }
1252         }
1253         stp_set_port_state(p, STP_BLOCKING);
1254         stp_stop_timer(&p->forward_delay_timer);
1255     }
1256 }
1257
1258 static void
1259 stp_set_port_state(struct stp_port *p, enum stp_state state)
1260     OVS_REQUIRES(mutex)
1261 {
1262     if (state != p->state && !p->state_changed) {
1263         p->state_changed = true;
1264         if (p < p->stp->first_changed_port) {
1265             p->stp->first_changed_port = p;
1266         }
1267         seq_change(connectivity_seq_get());
1268     }
1269     p->state = state;
1270 }
1271
1272 static void
1273 stp_topology_change_detection(struct stp *stp) OVS_REQUIRES(mutex)
1274 {
1275     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1276
1277     if (stp_is_root_bridge(stp)) {
1278         stp->topology_change = true;
1279         stp_start_timer(&stp->topology_change_timer, 0);
1280     } else if (!stp->topology_change_detected) {
1281         stp_transmit_tcn(stp);
1282         stp_start_timer(&stp->tcn_timer, 0);
1283     }
1284     stp->fdb_needs_flush = true;
1285     stp->topology_change_detected = true;
1286     seq_change(connectivity_seq_get());
1287     VLOG_INFO_RL(&rl, "%s: detected topology change.", stp->name);
1288 }
1289
1290 static void
1291 stp_topology_change_acknowledged(struct stp *stp) OVS_REQUIRES(mutex)
1292 {
1293     stp->topology_change_detected = false;
1294     stp_stop_timer(&stp->tcn_timer);
1295 }
1296
1297 static void
1298 stp_acknowledge_topology_change(struct stp_port *p) OVS_REQUIRES(mutex)
1299 {
1300     p->topology_change_ack = true;
1301     stp_transmit_config(p);
1302 }
1303
1304 static void
1305 stp_received_config_bpdu(struct stp *stp, struct stp_port *p,
1306                          const struct stp_config_bpdu *config)
1307     OVS_REQUIRES(mutex)
1308 {
1309     if (ntohs(config->message_age) >= ntohs(config->max_age)) {
1310         VLOG_WARN("%s: received config BPDU with message age (%u) greater "
1311                   "than max age (%u)",
1312                   stp->name,
1313                   ntohs(config->message_age), ntohs(config->max_age));
1314         return;
1315     }
1316     if (p->state != STP_DISABLED) {
1317         bool root = stp_is_root_bridge(stp);
1318         if (stp_supersedes_port_info(p, config)) {
1319             stp_record_config_information(p, config);
1320             stp_configuration_update(stp);
1321             stp_port_state_selection(stp);
1322             if (!stp_is_root_bridge(stp) && root) {
1323                 stp_stop_timer(&stp->hello_timer);
1324                 if (stp->topology_change_detected) {
1325                     stp_stop_timer(&stp->topology_change_timer);
1326                     stp_transmit_tcn(stp);
1327                     stp_start_timer(&stp->tcn_timer, 0);
1328                 }
1329             }
1330             if (p == stp->root_port) {
1331                 stp_record_config_timeout_values(stp, config);
1332                 stp_config_bpdu_generation(stp);
1333                 if (config->flags & STP_CONFIG_TOPOLOGY_CHANGE_ACK) {
1334                     stp_topology_change_acknowledged(stp);
1335                 }
1336                 if (config->flags & STP_CONFIG_TOPOLOGY_CHANGE) {
1337                     stp->fdb_needs_flush = true;
1338                 }
1339             }
1340         } else if (stp_is_designated_port(p)) {
1341             stp_transmit_config(p);
1342         }
1343     }
1344 }
1345
1346 static void
1347 stp_received_tcn_bpdu(struct stp *stp, struct stp_port *p)
1348     OVS_REQUIRES(mutex)
1349 {
1350     if (p->state != STP_DISABLED) {
1351         if (stp_is_designated_port(p)) {
1352             stp_topology_change_detection(stp);
1353             stp_acknowledge_topology_change(p);
1354         }
1355     }
1356 }
1357
1358 static void
1359 stp_hello_timer_expiry(struct stp *stp) OVS_REQUIRES(mutex)
1360 {
1361     stp_config_bpdu_generation(stp);
1362     stp_start_timer(&stp->hello_timer, 0);
1363 }
1364
1365 static void
1366 stp_message_age_timer_expiry(struct stp_port *p) OVS_REQUIRES(mutex)
1367 {
1368     struct stp *stp = p->stp;
1369     bool root = stp_is_root_bridge(stp);
1370     stp_become_designated_port(p);
1371     stp_configuration_update(stp);
1372     stp_port_state_selection(stp);
1373     if (stp_is_root_bridge(stp) && !root) {
1374         stp->max_age = stp->bridge_max_age;
1375         stp->hello_time = stp->bridge_hello_time;
1376         stp->forward_delay = stp->bridge_forward_delay;
1377         stp_topology_change_detection(stp);
1378         stp_stop_timer(&stp->tcn_timer);
1379         stp_config_bpdu_generation(stp);
1380         stp_start_timer(&stp->hello_timer, 0);
1381     }
1382 }
1383
1384 static bool
1385 stp_is_designated_for_some_port(const struct stp *stp) OVS_REQUIRES(mutex)
1386 {
1387     const struct stp_port *p;
1388
1389     FOR_EACH_ENABLED_PORT (p, stp) {
1390         if (p->designated_bridge == stp->bridge_id) {
1391             return true;
1392         }
1393     }
1394     return false;
1395 }
1396
1397 static void
1398 stp_forward_delay_timer_expiry(struct stp_port *p) OVS_REQUIRES(mutex)
1399 {
1400     if (p->state == STP_LISTENING) {
1401         stp_set_port_state(p, STP_LEARNING);
1402         stp_start_timer(&p->forward_delay_timer, 0);
1403     } else if (p->state == STP_LEARNING) {
1404         stp_set_port_state(p, STP_FORWARDING);
1405         if (stp_is_designated_for_some_port(p->stp)) {
1406             if (p->change_detection_enabled) {
1407                 stp_topology_change_detection(p->stp);
1408             }
1409         }
1410     }
1411 }
1412
1413 static void
1414 stp_tcn_timer_expiry(struct stp *stp) OVS_REQUIRES(mutex)
1415 {
1416     stp_transmit_tcn(stp);
1417     stp_start_timer(&stp->tcn_timer, 0);
1418 }
1419
1420 static void
1421 stp_topology_change_timer_expiry(struct stp *stp) OVS_REQUIRES(mutex)
1422 {
1423     stp->topology_change_detected = false;
1424     stp->topology_change = false;
1425 }
1426
1427 static void
1428 stp_hold_timer_expiry(struct stp_port *p) OVS_REQUIRES(mutex)
1429 {
1430     if (p->config_pending) {
1431         stp_transmit_config(p);
1432     }
1433 }
1434
1435 static void
1436 stp_initialize_port(struct stp_port *p, enum stp_state state)
1437     OVS_REQUIRES(mutex)
1438 {
1439     ovs_assert(state & (STP_DISABLED | STP_BLOCKING));
1440     stp_become_designated_port(p);
1441     stp_set_port_state(p, state);
1442     p->topology_change_ack = false;
1443     p->config_pending = false;
1444     p->change_detection_enabled = true;
1445     p->aux = NULL;
1446     stp_stop_timer(&p->message_age_timer);
1447     stp_stop_timer(&p->forward_delay_timer);
1448     stp_stop_timer(&p->hold_timer);
1449     p->tx_count = p->rx_count = p->error_count = 0;
1450 }
1451
1452 static void
1453 stp_become_root_bridge(struct stp *stp) OVS_REQUIRES(mutex)
1454 {
1455     stp->max_age = stp->bridge_max_age;
1456     stp->hello_time = stp->bridge_hello_time;
1457     stp->forward_delay = stp->bridge_forward_delay;
1458     stp_topology_change_detection(stp);
1459     stp_stop_timer(&stp->tcn_timer);
1460     stp_config_bpdu_generation(stp);
1461     stp_start_timer(&stp->hello_timer, 0);
1462 }
1463
1464 static void
1465 stp_start_timer(struct stp_timer *timer, int value) OVS_REQUIRES(mutex)
1466 {
1467     timer->value = value;
1468     timer->active = true;
1469 }
1470
1471 static void
1472 stp_stop_timer(struct stp_timer *timer) OVS_REQUIRES(mutex)
1473 {
1474     timer->active = false;
1475 }
1476
1477 static bool
1478 stp_timer_expired(struct stp_timer *timer, int elapsed, int timeout)
1479     OVS_REQUIRES(mutex)
1480 {
1481     if (timer->active) {
1482         timer->value += elapsed;
1483         if (timer->value >= timeout) {
1484             timer->active = false;
1485             return true;
1486         }
1487     }
1488     return false;
1489 }
1490
1491 /* Returns the number of whole STP timer ticks in 'ms' milliseconds.  There
1492  * are 256 STP timer ticks per second. */
1493 static int
1494 ms_to_timer(int ms)
1495 {
1496     return ms * 0x100 / 1000;
1497 }
1498
1499 /* Returns the number of whole milliseconds in 'timer' STP timer ticks.  There
1500  * are 256 STP timer ticks per second. */
1501 static int
1502 timer_to_ms(int timer)
1503 {
1504     return timer * 1000 / 0x100;
1505 }
1506
1507 static int
1508 clamp(int x, int min, int max)
1509 {
1510     return x < min ? min : x > max ? max : x;
1511 }
1512
1513 static void
1514 stp_update_bridge_timers(struct stp *stp) OVS_REQUIRES(mutex)
1515 {
1516     int ht, ma, fd;
1517
1518     ht = clamp(stp->rq_hello_time, 1000, 10000);
1519     ma = clamp(stp->rq_max_age, MAX(2 * (ht + 1000), 6000), 40000);
1520     fd = clamp(stp->rq_forward_delay, ma / 2 + 1000, 30000);
1521
1522     stp->bridge_hello_time = ms_to_timer(ht);
1523     stp->bridge_max_age = ms_to_timer(ma);
1524     stp->bridge_forward_delay = ms_to_timer(fd);
1525
1526     if (stp_is_root_bridge(stp)) {
1527         stp->max_age = stp->bridge_max_age;
1528         stp->hello_time = stp->bridge_hello_time;
1529         stp->forward_delay = stp->bridge_forward_delay;
1530     }
1531 }
1532
1533 static void
1534 stp_send_bpdu(struct stp_port *p, const void *bpdu, size_t bpdu_size)
1535     OVS_REQUIRES(mutex)
1536 {
1537     struct eth_header *eth;
1538     struct llc_header *llc;
1539     struct ofpbuf *pkt;
1540
1541     /* Skeleton. */
1542     pkt = ofpbuf_new(ETH_HEADER_LEN + LLC_HEADER_LEN + bpdu_size);
1543     eth = ofpbuf_put_zeros(pkt, sizeof *eth);
1544     llc = ofpbuf_put_zeros(pkt, sizeof *llc);
1545     ofpbuf_set_frame(pkt, eth);
1546     ofpbuf_set_l3(pkt, ofpbuf_put(pkt, bpdu, bpdu_size));
1547
1548     /* 802.2 header. */
1549     memcpy(eth->eth_dst, eth_addr_stp, ETH_ADDR_LEN);
1550     /* p->stp->send_bpdu() must fill in source address. */
1551     eth->eth_type = htons(ofpbuf_size(pkt) - ETH_HEADER_LEN);
1552
1553     /* LLC header. */
1554     llc->llc_dsap = STP_LLC_DSAP;
1555     llc->llc_ssap = STP_LLC_SSAP;
1556     llc->llc_cntl = STP_LLC_CNTL;
1557
1558     p->stp->send_bpdu(pkt, stp_port_no(p), p->stp->aux);
1559     p->tx_count++;
1560 }
1561 \f
1562 /* Unixctl. */
1563
1564 static struct stp *
1565 stp_find(const char *name) OVS_REQUIRES(mutex)
1566 {
1567     struct stp *stp;
1568
1569     LIST_FOR_EACH (stp, node, all_stps) {
1570         if (!strcmp(stp->name, name)) {
1571             return stp;
1572         }
1573     }
1574     return NULL;
1575 }
1576
1577 static void
1578 stp_unixctl_tcn(struct unixctl_conn *conn, int argc,
1579                 const char *argv[], void *aux OVS_UNUSED)
1580 {
1581     ovs_mutex_lock(&mutex);
1582     if (argc > 1) {
1583         struct stp *stp = stp_find(argv[1]);
1584
1585         if (!stp) {
1586             unixctl_command_reply_error(conn, "no such stp object");
1587             goto out;
1588         }
1589         stp_topology_change_detection(stp);
1590     } else {
1591         struct stp *stp;
1592
1593         LIST_FOR_EACH (stp, node, all_stps) {
1594             stp_topology_change_detection(stp);
1595         }
1596     }
1597
1598     unixctl_command_reply(conn, "OK");
1599
1600 out:
1601     ovs_mutex_unlock(&mutex);
1602 }