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