7.1 Процедура выбора корневого коммутатора
Каждому коммутатору, подключаемому к сети в которой для определения логической структуры используется STP, администратором назначается специальный уникальный идентификатор BID (bridge ID). Этот идентификатор имеет длину в 8 байт. Первые 2 байта – поле приоритета. По умолчанию его значение 32768 (1000 0000 0000 0000 в двоичном виде). В качестве следующих 6 байт идентификатора используется MAC адрес коммутатора.
Корневым выбирается коммутатор с самым маленьким значением поля приоритета, поэтому если администратор планирует использовать некий коммутатор в роли корневого, он должен назначить ему некоторое значение приоритета, меньшее значения по умолчанию. Если значения полей приоритета окажутся равными, то сравниваются MAC адреса и в качестве корневого выбирается коммутатор с меньшим их значением.
При подключении нового коммутатора к сети он по умолчанию позиционирует себя как корневой и рассылает BPDU со своим BID всем соседям. Если вы были не аккуратны при задании значения приоритета или вы используете значения этого поля по умолчанию для всех коммутаторов сети, то возможно весьма серьёзное перестроение её логической структуры.
7.2 Выбор пути к корню дерева
Разобравшись кто является корнем дерева, коммутаторы должны определить для каждого не корневого по одному порту, ближайшему к корню. Для каждого порта каждый некорневой коммутатор определяет длину маршрута из этого порта до корня и выбирается порт с наименьшим значением этого параметра.
Длина маршрута определяется как сумма длин всех составляющих его соединений (коллизионных доменов) Длина каждого соединения определяется по специальной шкале В первоначальной версии протокола эта длина определялась безразмерной величиной, равной частному от деления 1000 Мбит/с на полосу пропускания канала, выраженную в Мбит/с. Соответственно для стандартного 10 Мбит/с Ethernet получалось 100, а для 1 Гбит/с Ethernet 1. С появлением технологий со скоростью передачи данных более чем 1 Гбит/с эта шкала оказалась неработоспособной (отметим, что область применения STP не ограничена Ethernet). Поскольку скорости канальных технологий растут очень быстро, комитету IEEE 802.1D приходилось неоднократно возвращаться к этому вопросу. В редакции стандарта от 2004 года было решено использовать для оценки длины маршрута 32 битные значения вместо 16 битных и определять длину отдельного соединение как частное от деления 20 000 000 000 Кбит/с на скорость соединения, выраженную в Кбит/с. Диапазон скоростей, охватываемых этим вариантом определения, начинается от 100 Кбит/с (рекомендованное значение – 200 000 000) и простирается до 10 Тбит/с (! Терабит в секунду ! рекомендованное значение – 2).
Корневым назначается порт с минимальной длиной маршрута до корня.
7.3 Определение назначенных портов и назначенных коммутаторов
Построение древовидной структуры завершается определением каждому коллизионному домену сети единственного назначенного порта в коммутаторе, который тоже становится после этого назначенным для данного сегмента.
Корневой коммутатор при нормальном функционировании сконфигурированной сети каждые 2 секунды рассылает BPDU, которые ретранслируются по всей сети и служат подтверждением работоспособности её текущей конфигурации. Если любой из коммутаторов не получит подтверждающего сообщения в течении 20 секунд, он должен начать процедуру пересмотра структуры сети.
Протокол STP не очень быстр. На установление конфигурации сети или её перестройку при сбое ему требуется до 50 секунд. Для борьбы с этим недостатком была разработана его «ускоренная» версия RSTP, в которой, в частности, дополнительно заранее определяются альтернативные маршруты к корню дерева и некоторые другие ускоряющие алгоритмы.
8. Flow control IEEE 802.1x и back pressure
Сколь быстрые технологии передачи и обработки данных мы бы не использовали, всегда возможна ситуация, когда скорость работы передатчика превышает возможности приёмника по обработке или пересылке данных. В Ehternet по умолчанию имеется возможность только отбрасывать кадры при невозможности их обработать. Для регулирования работы в сети в таких ситуациях были разработаны специальные решения.
Для Ethernet возможен как полудуплексный режим работы, так и полный дуплекс. В первом случае если отправитель забрасывает порт получателя пакетами, которые тот не может обработать, возможности вежливо попросить отправителя уменьшить активность нет и возможен только достаточно «грубый» метод обратного давления (back pressure). Суть метода заключается в том, что получатель сам начинает отправлять пакеты, не обращая внимание на занятость среды передачи. Это немедленно приводит к появлению коллизий, которые обнаруживает отправитель и оказывается вынужден прекратить передачу.
Для дуплексного режима работы стандарт IEEE 802.1x предлагает гораздо более элегантно решение. В этом случае получатель отправляет специальный кадр PAUSE. Признаком кадра этого типа является наличие кода 8808 в поле LENGTH/TYPE и 0001 в следующих за ними двух байтах (поле OPCODE). В качестве адреса получателя такого кадра должен быть размещен код 01-80-C2-00-00-01, который представляет собой Multicast адрес станций, поддерживащих выполнение данной процедуры, или Unicast адрес конкретного абонента в сети, формирующего избыточный трафик для данной станции. В поле адрес отправителя кадра типа «Пауза» помещается MAC — адрес станции, которая инициирует выполнение процедуры управления потоком.
Код 8808, помещаемый в поле LENGTH/TYPE этого кадра зарезервирован IEEE для кадров, которые используются в процедурах управления на уровне MAC. Поле OPCODE содержит признак кадра управления потоком 0001. В последующих двух байтах указывается размер предлагаемой паузы, выраженному в битовых интервалах. Единица младшего разряда этого кода соответствует 512 битовым интервалам используемой технологии. Таким образом, размер предлагаемой паузы для технологий Fast Ethernet может иметь значение от 0 до 0.3 секунды.
Тренинг Cisco 200-125 CCNA v3.0. День 37. STP: выбор Root Bridge, функции PortFast и BPDU guard. Часть 2
Предположим, что STP находится в состоянии сходимости. Что произойдет, если я возьму кабель и соединю свитч Н напрямую с корневым свитчем А? Root Bridge «увидит», что у него появился новый задействованный порт, и отошлет по нему BPDU.
Свитч Н, получив этот фрейм с нулевой стоимостью, определит стоимость маршрута через новый порт как 0+19 =19 при том, что стоимость его корневого порта равна 76. После этого порт свитча Н, который ранее пребывал в состоянии disabled, пройдёт все стадии transition и переключится в режим передачи только через 50 секунд. Если к данному свитчу подключены другие устройства, то все они на 50 секунд потеряют соединение с корневым свитчем и с сетью в целом.
Аналогичным образом поступает свитч G, получив от свитча Н фрейм BPDU с уведомлением о стоимости 19. Он меняет стоимость своего назначенного порта на 19+19= 38 и переназначает его в качестве нового корневого порта, потому что стоимость его прежнего Root Port равна 57, что больше 38. При этом снова начинаются все стадии переназначения портов длительностью 50 с, и, в конечном итоге, вся сеть обрушивается.

Теперь давайте рассмотрим, что будет происходить в аналогичной ситуации при использовании RSTP. Корневой свитч точно так же отошлет BPDU подключившемуся к нему свитчу Н, но сразу после этого заблокирует свой порт. Получив этот фрейм, свитч Н определит, что данный маршрут имеет меньшую стоимость, чем его корневой порт, и тут же его заблокирует. После этого Н вышлет корневому свитчу Proposal с просьбой открыть новый порт, потому что его стоимость меньше, чем стоимость уже имеющегося корневого порта. После того, как корневой свитч согласится с просьбой, он разблокирует свой порт и отошлет Agreement свитчу Н, после чего последний сделает новый порт своим корневым портом.

При этом благодаря механизму Proposal/Agreement переназначение корневого порта произойдет практически мгновенно, и все устройства, подсоединенные к свитчу Н, не утратят связи с сетью.
Назначив новый Root Port, свитч Н превратит старый корневой порт в альтернативный порт. То же самое произойдёт со свитчем G – он обменяется со свитчем Н сообщениями Proposal/Agreement, назначит новый корневой порт и заблокирует остальные порты. Затем процесс продолжится в следующем сегменте сети со свитчем F.

Свитч F, проанализировав стоимости, увидит, что маршрут к корневому свитчу через нижний порт будет стоить 57 при том, что уже имеющийся маршрут через верхний порт стоит 38, и оставит всё как есть. Узнав об этом, свитч G заблокирует порт, обращенный к F, и будет пересылать трафик корневому свитчу по новому маршруту G-H-A.
Пока свитч F не получит Proposal/Agreement от свитча G, он будет держать свой нижний порт заблокированным, чтобы предотвратить образование петель. Таким образом, вы видите, что RSTP – это очень быстрый протокол, который не создает в сети проблем, свойственных STP.
Теперь давайте перейдём к рассмотрению команд. Вам нужно зайти в режим глобальной конфигурации свитча и выбрать режим PVST или RPVST с помощью команды spanning-tree mode <pvst/rpvst>. Затем вам нужно решить, как изменить приоритет конкретной VLAN. Для этого используется команда spanning-tree vlan <номер сети VLAN> priority < значение >. Из последнего видеоурока вы должны помнить, что приоритет представляет собой число, кратное 4096 и по умолчанию это число равно 32768 плюс номер сети VLAN. Если вы выбрали VLAN1, то приоритет по умолчанию будет 32768+1= 32769.

Зачем может понадобиться изменять приоритет сетей? Мы знаем, что BID состоит из числового значения приоритета и MAC-адреса. MAC-адрес устройства невозможно изменить, он имеет постоянное значение, поэтому можно изменить только величину приоритета.
Предположим, что существует крупная сеть, где все устройства Cisco соединены по круговой схеме. При этом по умолчанию активирован PVST, поэтому системой будет выбран корневой свитч. Если все устройства имеют одинаковый приоритет, то преимущество будет иметь свитч с самым старым MAC-адресом. Однако это может быть 10-12 летний коммутатор устаревшей модели, у которого даже не хватает мощности и производительности «возглавлять» такую обширную сеть.
В то же время у вас в сети может быть новейший свитч за несколько тысяч долларов, который в силу большего значения MAC-адреса вынужден «подчиняться» старому свитчу ценой в пару сотен долларов. Если старый свитч становится корневым коммутатором, это свидетельствует о серьезной ошибке дизайна сети.
Поэтому вы должны зайти в настройки нового свитча и присвоить ему минимальное значение приоритета, например, 0. При использовании VLAN1 суммарное значение приоритета будет равно 0+1=1, и все остальные устройства постоянно будут считать его корневым свитчем.
Теперь вообразим такую ситуацию. Если корневой свитч по какой-то причине становится недоступным, вы можете захотеть, чтобы новым корневым свитчем стал не любой коммутатор с низшим приоритетом, а какой-то конкретный свитч с лучшими сетевыми функциями. В этом случае в настройках Root Bridge используется команда, назначающая основной и второстепенный корневые свитчи: spanning-tree vlan <номер сети VLAN> root <основной/второстепенный>. Значение приоритета для основного свитча Primary будет равно 32768 – 4096 – 4096 = 24576. Для второстепенного свитча Secondary оно вычисляется по формуле 32768 – 4096 = 28672.
Вы можете не вводить эти числа вручную – система сделает это для вас автоматически. Таким образом, корневым будет свитч с приоритетом 24576, а при его недоступности – свитч с приоритетом 28672 при том, что приоритет всех остальных свитчей по умолчанию не меньше 32768. Так следует поступать, если вы не хотите, чтобы система автоматически назначала корневой свитч.
Если вы хотите посмотреть настройки протокола STP, нужно использовать команду show spanning-tree summary. Давайте теперь рассмотрим все изученные сегодня темы с помощью Packet Tracer. Я использую топологию сети из 4-х свитчей модели 2690, это не имеет значения, поскольку все модели свитчей Cisco поддерживают STP. Они соединены друг с другом так, что сеть образует замкнутый круг.
По умолчанию устройства Cisco работают в режиме PSTV+, то есть для конвергенции каждому порту потребуется не более 20 с. Панель симуляции позволяет изобразить отправку трафика и просмотреть параметры работы созданной сети.

Вы видите, что представляет собой фрейм STP BPDU. Если вы видите обозначение версии 0, значит, перед вами STP, потому что для RSTP используется версия 2. Здесь приведено также значение Root ID, состоящее из приоритета и MAC-адреса корневого свитча, и равное ему значение Bridge ID.

Эти величины равны, поскольку стоимость маршрута к корневому свитчу для SW0 равна 0, следовательно, он сам является корневым свитчем. Таким образом, после включения свитчей благодаря использованию STP произошел автоматический выбор Root Bridge и сеть заработала. Вы видите, что для предотвращения петли верхний порт Fa0/2 свитча SW2 был переведен в состояние Blocking, на что указывает оранжевый цвет маркера.

Перейдем к консоли настроек свитча SW0 и используем пару команд. Первая это команда show spanning-tree, после ввода которой на экране нам будет показана информация о режиме PSTV+ для сети VLAN1. Если мы будем использовать несколько VLAN, в нижней части окна появится еще один блок информации для второй и последующих используемых сетей.

Вы видите, что протокол STP доступен по стандарту IEEE, что означает использование PVSTP+. Технически это не является стандартом .1d. Здесь также приведена информация Root ID: приоритет 32769, MAC-адрес корневого устройства, стоимость 19 и т.д. Далее следует информация Bridge ID, в которой расшифровывается значение приоритета 32768 +1, и следует другой MAC-адрес. Как видите, я ошибся — свитч SW0 не является корневым свитчем, корневой свитч имеет другой MAC-адрес, приведенный в параметрах Root ID. Я думаю, это связано с тем, что SW0 получил фрейм BPDU с информацией о том, что какой-то свитч в сети имеет большие основания играть роль корневого. Сейчас мы это рассмотрим.
(примечание переводчика: Root ID – идентификатор корневого свитча, одинаковый для всех устройств одной и той же сети VLAN, работающей по протоколу STP, Bridge ID – идентификатор локального свитча в составе Root Bridge, который может быть разным для разных свитчей и разных VLAN).
Еще одно обстоятельство, которое указывает на то, что SW0 не является корневым свитчем – это то, что корневой свитч не имеет Root Port, а в данном случае имеется и Root Port, и Designated Port, находящиеся в состоянии forwarding. Вы также видите тип соединения p2p, или «точка-точка». Это означает, что порты fa0/1 и fa0/2 напрямую соединены с соседними свитчами.
Если бы какой-то порт был подсоединен к хабу, тип соединения обозначался бы как shared, позже мы это рассмотрим. Если я введу команду для просмотра итоговой информации show spanning-tree summary, мы увидим, что данный свитч находится в режиме PVSTP, далее идет перечисление недоступных функций порта.

Далее показано состояние и количество портов, обслуживающих VLAN1: blocking 0, listening 0, learning 0, в состоянии forwarding в режиме STP находится 2 порта.
Перед тем, как перейти к свитчу SW2, посмотрим на настройки свитча SW1. Для этого мы используем ту же команду show spanning-tree.

Вы видите, что MAC-адрес Root ID у свитча SW1 такой же, как и у SW0, потому что все устройства в сети при схождении получают один и тот же адрес устройства Root Bridge, так как доверяют выбору, сделанному протоколом STP. Как видите, SW1 и есть корневой свитч, потому что адреса Root ID и Bridge ID совпадают. Кроме того, здесь имеется сообщение «этот свитч является корневым».
Еще одним признаком корневого свитча является то, что у него нет Root-портов, оба порта обозначаются как Designated. Если все порты показаны как Designated и находятся в состоянии forwarding, то перед вами корневой свитч.
Свитч SW3 содержит аналогичную информацию, и теперь я перехожу к SW2, потому что один из его портов находится в состоянии Blocking. Я использую команду show spanning-tree и мы видим, что информация Root ID и значение приоритета такие же, как и у остальных свитчей.
Далее указано, что один из портов является Alternative. Пусть вас это не смущает, стандарт 802.1d называет это Blocking Port, а в PVSTP заблокированный порт всегда обозначается как Alternative. Итак, этот альтернативный Fa0/2 порт находится в заблокированном состоянии, а порт Fa0/1 выступает в качестве Root Port.
Заблокированный порт находится в сегменте сети между свитчем SW0 и свитчем SW2, благодаря чему у нас не образуется петля. Как видите, свитчи использую соединение типа p2p, потому что к ним не подсоединены никакие другие устройства.

У нас имеется сеть, сходящаяся по протоколу STP. Теперь я возьму кабель и соединю напрямую свитч SW2 с коневым свитчем SW1. После этого все порты SW2 станут обозначаться оранжевыми маркерами.
Если использовать команду show spanning-tree summary, мы увидим, что сначала два порта находятся в состоянии Listening, затем переходят в состояние Learning и через несколько секунд в состояние Forwarding, при этом цвет маркера меняется на зеленый. Если сейчас ввести команду show spanning-tree, видно, что Fa0/1, который раньше был Root-портом, теперь перешел в состояние блокировки и стал называться Alternative-портом.

Порт Fa0/3, к которому подсоединен кабель корневого свитча, стал Root-портом, а порт Fa0/2 превратился в назначенный Designated-порт. Давайте ещё раз рассмотрим происходящий процесс конвергенции. Я отсоединю кабель SW2-SW1 и вернусь к предыдущей топологии. Вы видите, что порты SW2 сначала блокируются и снова становятся оранжевыми, затем последовательно переходят через состояния Listening и Learning и оказываются в состоянии Forwarding. При этом один порт становится зеленым, а второй, соединенный со свитчем SW0, остается оранжевым. Процесс сходимости занял довольно длительное время, таковы издержки работы STP.

Теперь давайте рассмотрим, как работает RSTP. Начнем со свитча SW2 и введем в его настройках команду spanning-tree mode rapid-pvst. У данной команды есть всего два варианта параметров: pvst и rapid-pvst, я использую второй. После ввода команды свитч переходит в режим RPVST, проверить это можно командой show spanning-tree.

В начале вы видите сообщение о том, что теперь у нас работает протокол RSTP. Все остальное осталось без изменений. Затем я должен проделать то же самое для всех остальных устройств, и на этом настройка RSTP завершена. Давайте рассмотрим работу этого протокола так, как мы делали это для STP.
Я снова соединяю кабелем свитч SW2 напрямую с корневым свитчем SW1 –посмотрим, как быстро произойдет схождение. Я набираю команду show spanning-tree summary и вижу, что два порта свитча находятся в состоянии Blocking, 1 в состоянии Forwarding.

Вы видите, что схождение произошло практически мгновенно, так что можете судить, насколько RSTP быстрее, чем STP. Далее мы можем использовать команду spanning-tree portfast default, которая переведет все порты свитча в режим portfast по умолчанию. Это актуально в случае, если большинство портов свитча являются Edge-портами, напрямую соединенными с хостами. Если у нас имеется какой-то порт, не являющийся Edge, мы настраиваем его обратно в режим spanning-tree.
Для настройки работы с VLAN можно использовать команду spanning-tree vlan < номер > с параметрами priority (задает приоритет свитча для spanning-tree) или root (назначает свитч корневым). Мы используем команду spanning-tree vlan 1 priority, указав в качестве приоритета любое число, кратное 4096, в диапазоне от 0 до 61440. Таким образом можно вручную изменить приоритет любой VLAN.
Можно набрать команду spanning-tree vlan 1 root с параметрами primary или secondary, чтобы настроить основной или резервный root-порт для конкретной сети. Если я использую spanning-tree vlan 1 root primary, данный порт будет основным корневым портом для сети VLAN1.
Я введу команду show spanning-tree, и мы увидим, что данный свитч SW2 имеет приоритет 24577, MAC-адреса Root ID и Bridge ID совпадают, значит, теперь он стал корневым свитчем.

Вы видите, насколько быстро произошло схождение и смена роли свитчей. Сейчас я отменю режим основного свитча командой no spanning-tree vlan 1 root primary, после чего его приоритет вернется к предыдущему значению 32769, а роль корневого свитча снова перейдет к SW1.
Посмотрим, как работает portfast. Я введу команду int f0/1, зайду в настройки данного порта и использую команду spanning-tree, после чего система выдаст подсказки значений параметров.

Далее я использую команду spanning-tree portfast, которую можно ввести с параметрами disable (отключает функцию portfast для данного порта) или trunk (включает функцию portfast для данного порта даже в режиме транка).
Если ввести spanning-tree portfast, то функция просто включится на данном порту. Для активации функции BPDU Guard нужно использовать команду spanning-tree bpduguard enable, команда spanning-tree bpduguard disable отключает данную функцию.
Я быстро расскажу ещё об одной вещи. Если для VLAN1 интерфейс свитча SW2 в направлении SW3 будет заблокирован, то при других параметрах настройки для другой VLAN, например, VLAN2, этот же интерфейс может стать корневым портом. Таким образом в системе может реализовываться механизм балансировки нагрузки трафика – в одном случае данный сегмент сети не используется, в другом – используется.
Я покажу, что происходит, когда при подключении хаба у нас возникает shared-интерфейс. Я добавлю хаб на схему и соединю его со свитчем SW2 двумя кабелями.

Команда show spanning-tree отразит следующую картину.

Fa0/5 (левый нижний порт свитча) становится backup-портом, а порт Fa0/4 (правый нижний порт свитча) становится назначенным designated-портом. Тип обоих портов – общий, или shared. Это означает, что сегмент интерфейсов хаб-свитч является общей сетью.
Благодаря использованию RSTP мы получили разделение на альтернативный и резервный порты. Если мы переведём свитч SW2 в режим pvst командой spanning-tree mode pvst, то увидим, что интерфейс Fa0/5 снова перешел в состояние Alternative, потому что сейчас нет отличия между backup-портом и alternative-портом.

Это был очень длинный урок, и если вы чего-то не поняли, советую пересмотреть его ещё раз.
Спасибо, что остаётесь с нами. Вам нравятся наши статьи? Хотите видеть больше интересных материалов? Поддержите нас оформив заказ или порекомендовав знакомым, 30% скидка для пользователей Хабра на уникальный аналог entry-level серверов, который был придуман нами для Вас: Вся правда о VPS (KVM) E5-2650 v4 (6 Cores) 10GB DDR4 240GB SSD 1Gbps от $20 или как правильно делить сервер? (доступны варианты с RAID1 и RAID10, до 24 ядер и до 40GB DDR4).
Configuring Spanning Tree
The documentation set for this product strives to use bias-free language. For the purposes of this documentation set, bias-free is defined as language that does not imply discrimination based on age, disability, gender, racial identity, ethnic identity, sexual orientation, socioeconomic status, and intersectionality. Exceptions may be present in the documentation due to language that is hardcoded in the user interfaces of the product software, language used based on RFP documentation, or language that is used by a referenced third-party product. Learn more about how Cisco is using Inclusive Language.
Table Of Contents
Configuring Spanning Tree
This chapter describes the IEEE 802.1D bridge Spanning Tree Protocol (STP) and how to use and configure Cisco’s proprietary STPs, Per VLAN Spanning Tree + (PVST+), and Multi-Instance Spanning Tree Protocol (MISTP) on the Catalyst enterprise LAN switches.
Note For complete syntax and usage information for the commands that are used in this chapter, refer to the Catalyst 4500 Series, Catalyst 2948G, Catalyst 2948G-GE-TX, and Catalyst 2980G Switches Command Reference.
Understanding How STPs Work
This section describes the specific functions that are common to all spanning tree protocols. The Cisco proprietary spanning tree protocols, PVST+ and MISTP, are based on the IEEE 802.1D STP. (See the "Understanding How PVST+ and MISTP Modes Work" section for information about PVST+ and MISTP.) The 802.1D STP is a Layer 2 management protocol that provides path redundancy in a network while preventing undesirable loops. All spanning tree protocols use an algorithm that calculates the best loop-free path through the network.
STP uses a distributed algorithm that selects one bridge of a redundantly connected network as the root of a spanning tree-connected active topology. STP assigns roles to each port depending on what the port’s function is in the active topology. Port roles are as follows:
•Root—A forwarding port that is elected for the spanning tree topology
•Designated—A forwarding port that is elected for every switched LAN segment
•Alternate—A blocked port providing an alternate path to the root port in the spanning tree
•Backup—A blocked port in a loopback configuration
Switches that have ports with these assigned roles are called root or designated switches. For more information, see the "Understanding How a Topology Is Created" section.
In Ethernet networks, only one active path may exist between any two stations. Multiple active paths between stations can cause loops in the network. When loops occur, some switches recognize stations on both sides of the switch. This situation causes the forwarding algorithm to malfunction allowing duplicate frames to be forwarded.
Spanning tree algorithms provide path redundancy by defining a tree that spans all of the switches in an extended network and then forces certain redundant data paths into a standby (blocked) state. At regular intervals, the switches in the network send and receive spanning tree packets which they use to identify the active path. If one network segment becomes unreachable, or if spanning tree costs change, the spanning tree algorithm reconfigures the spanning tree topology and reestablishes the link by activating a standby path.
Spanning tree operation is transparent to end stations, which do not detect whether they are connected to a single LAN segment or a switched LAN of multiple segments.
Understanding How a Topology Is Created
All switches in an extended LAN participating in a spanning tree gather information about other switches in the network through an exchange of data messages known as bridge protocol data units (BPDUs). This exchange of messages results in the following actions:
•A unique root switch is elected for the spanning tree network topology.
•A designated switch is elected for every switched LAN segment.
•Any loops in the switched network are eliminated by placing redundant switch ports in a backup state; all paths that are not needed to reach the root switch from anywhere in the switched network are placed in STP-blocked mode.
The following three things determine the topology of an active switched network:
•The unique switch identifier (MAC address of the switch) that is associated with each switch
•The path cost to the root that is associated with each switch port
•The port identifier (MAC address of the port) that is associated with each switch port
In a switched network, the root switch is the logical center of the spanning tree topology. A spanning tree protocol uses BPDUs to elect the root switch and root port for the switched network and the root port and designated port for each switched segment.
Understanding How a Switch or Port Becomes the Root Switch or Root Port
If all switches in a network are enabled with default settings, the switch with the lowest MAC address becomes the root switch. In Figure 7-1, Switch A, with the lowest MAC address, is the root switch. However, due to traffic patterns, number of forwarding ports, or line types, Switch A might not be the ideal root switch. You can force a switch to become the root switch by increasing the priority (lowering the priority number) on the preferred switch. This action causes the spanning tree to recalculate the topology and make the selected switch the root switch.
Figure 7-1 Configuring a Loop-Free Topology

You can also change the priority of a port to make it the root port. When the spanning tree topology is based on default parameters, the path between the source and the destination stations in a switched network might not be ideal. The goal is to make the fastest link the root port, connecting higher-speed links to a port that has a higher number than the current root port can cause a root-port change.
For example, assume that a port on Switch B is a fiber-optic link. Also, another port on Switch B (an unshielded twisted-pair [UTP] link) is the root port. Network traffic might be more efficient over the high-speed fiber-optic link. By changing the Port Priority parameter for the UTP port to a higher priority (lower numerical value) than the fiber-optic port, the UTP port becomes the root port. You could also accomplish this scenario by changing the port cost parameter for the UTP port to a lower value than that of the fiber-optic port.
Understanding BPDUs
BPDUs contain configuration information about the transmitting switch and its ports, including switch and port MAC addresses, switch priority, port priority, and port cost. Each configuration BPDU contains this information:
•The unique identifier of the switch that the transmitting switch believes to be the root switch
•The cost of the path to the root from the transmitting port
•The identifier of the transmitting port
The switch sends configuration BPDUs to communicate with and compute the spanning tree topology. A MAC frame conveying a BPDU sends the switch group address to the destination address field. All switches connected to the LAN on which the frame is transmitted receive the BPDU. BPDUs are not directly forwarded by the switch, but the receiving switch uses the information in the frame to calculate a BPDU. If the topology changes, the receiving switch initiates a BPDU transmission.
A BPDU exchange results in the following:
•One switch is elected as the root switch.
•The shortest distance to the root switch is calculated for each switch.
•A designated switch is selected. This is the switch that is closest to the root switch through which frames will be forwarded to the root.
•A port for each switch is selected. This is the port that provides the best path from the switch to the root switch.
•Ports included in the STP are selected.
Calculating and Assigning Port Costs
By calculating and assigning the port cost of the switch ports, you can ensure that the shortest (lowest cost) distance to the root switch is used to transmit data. You can calculate and assign lower path cost values (port costs) to higher bandwidth ports by using either the short method (which is the default) or the long method. The short method uses a 16-bit format that yields values from 1-65535. The long method uses a 32-bit format that yields values from 1-200,000,000. For more information on setting the default cost mode, see the "Configuring the PVST+ Default Port Cost Mode" section.
Note You should configure all switches in your network to use the same method for calculating port cost. The short method (default) will be used to calculate the port cost unless you specify the long method. You can specify the calculation method using the CLI.
Calculating the Port Cost Using the Short Method
The IEEE 802.1D specification assigns 16-bit (short) default port cost values to each port that is based on bandwidth. You can also manually assign port costs between 1-65535. The 16-bit values are only used for ports that have not been specifically configured for port cost. Table 7-1 shows the default port cost values that are assigned by the switch for each type of port when you use the short method to calculate the port cost.
Calculating the Port Cost Using the Long Method
802.1t assigns 32-bit (long) default port cost values to each port using a formula that is based on the port bandwidth. You can also manually assign port costs between 1-200,000,000. The formula for obtaining default 32-bit port costs is to divide the bandwidth of the port by 200,000,000. Table 7-2 shows the default port cost values that are assigned by the switch and the recommended cost values and ranges for each type of port when you use the long method to calculate port cost.
Calculating the Port Cost for Aggregate Links
As individual links are added or removed from an aggregate link (port bundle), the bandwidth of the aggregate link increases or decreases. These changes in bandwidth lead to the recalculation of the default port cost for the aggregated port. Changes to the default port cost or changes resulting from links that autonegotiate their bandwidth could lead to recalculation of the spanning tree topology. Recalculation may not be desirable, especially if the added or removed link is of little consequence to the bandwidth of the aggregate link (for example, if a 10-Mbps link is removed from a 10-Gbps aggregate link). Because of the limitations that are presented by automatically recalculating the topology, 802.1t states that changes in bandwidth will not result in changes to the cost of the port concerned. Therefore, the aggregated port uses the same port cost parameters as a standalone port.
Understanding Spanning Tree Port States
Topology changes can take place in a switched network due to a link coming up or going down (failing). When a switch port transitions directly from nonparticipation in the topology to the forwarding state, it can create temporary data loops. Ports must wait for new topology information to propagate through the switches in the LAN before they can start forwarding frames. They must also allow the frame lifetime to expire for frames that have been forwarded using the old topology.
At any given time, each port on a switch using STP is in one of these states:
•Blocking
•Listening
•Learning
•Forwarding
•Disabled
A port moves through these states:
•From initialization to blocking
•From blocking to either listening or disabled
•From listening to either listening or disabled
•From learning to either forwarding or disabled
•From forwarding to disabled
Figure 7-2 illustrates how a port moves through the states.
Figure 7-2 STP Port States

You can modify each port state by using management software, such as the VLAN Trunking Protocol (VTP). When you enable spanning tree, every switch in the network goes through the blocking state and the transitory states of listening and learning at power up. If properly configured, each port stabilizes into the forwarding or blocking state.
When the spanning tree algorithm places a port in the forwarding state, the following occurs:
•The port is put into the listening state while it waits for protocol information that suggests it should go to the blocking state
•The port waits for the expiration of a protocol timer that moves the port to the learning state
•In the learning state, the port continues to block frame forwarding as it learns station location information for the forwarding database
•The expiration of a protocol timer moves the port to the forwarding state, where both learning and forwarding are enabled
Blocking State
A port in the blocking state, such as Port 2 in Figure 7-3, does not participate in frame forwarding. After initialization, a BPDU is sent to each port in the switch. A switch initially assumes that it is the root until it exchanges BPDUs with other switches. This exchange establishes which switch in the network is really the root. If only one switch resides in the network, no exchange occurs, the forward delay timer expires, and the ports move to the listening state. A switch always enters the blocking state following switch initialization.
Figure 7-3 Port 2 in Blocking State

A port in the blocking state performs as follows:
•Discards frames that are received from the attached segment
•Discards frames that are switched from another port for forwarding
•Does not incorporate station location into its address database (there is no learning on a blocking port, so there is no address database update)
•Receives BPDUs and directs them to the system module
•Does not transmit BPDUs that are received from the system module
•Receives and responds to network management messages
Listening State
The listening state is the first transitional state that a port enters after the blocking state. The port enters this state when the spanning tree determines that the port should participate in frame forwarding. Learning is disabled in the listening state. Figure 7-4 shows a port in the listening state.
Figure 7-4 Port 2 in Listening State

A port in the listening state performs as follows:
•Discards frames that are received from the attached segment
•Discards frames that are switched from another port for forwarding
•Does not incorporate station location into its address database (there is no learning at this point, so there is no address database update)
•Receives BPDUs and directs them to the system module
•Processes BPDUs that are received from the system module
•Receives and responds to network management messages
Learning State
A port in the learning state prepares to participate in frame forwarding. The port enters the learning state from the listening state. Figure 7-5 shows a port in the learning state.
Figure 7-5 Port 2 in Learning State

A port in the learning state performs as follows:
•Discards frames that are received from the attached segment
•Discards frames that are switched from another port for forwarding
•Incorporates station location into its address database
•Receives BPDUs and directs them to the system module
•Receives, processes, and transmits BPDUs that are received from the system module
•Receives and responds to network management messages
Forwarding State
A port in the forwarding state forwards frames, as shown in Figure 7-6. The port enters the forwarding state from the learning state.
Figure 7-6 Port 2 in Forwarding State

A port in the forwarding state performs as follows:
•Forwards frames that are received from the attached segment
•Forwards frames that are switched from another port for forwarding
•Incorporates station location information into its address database
•Receives BPDUs and directs them to the system module
•Processes BPDUs that are received from the system module
•Receives and responds to network management messages
Disabled State
A port in the disabled state does not participate in frame forwarding or STP, as shown in Figure 7-7. A port in the disabled state is virtually nonoperational.
Figure 7-7 Port 2 in Disabled State

A disabled port performs as follows:
•Discards frames that are received from the attached segment
•Discards frames that are switched from another port for forwarding
•Does not incorporate station location into its address database (there is no learning, so there is no address database update)
•Receives BPDUs but does not direct them to the system module
•Does not receive BPDUs for transmission from the system module
•Receives and responds to network management messages
Understanding How PVST+ and MISTP Modes Work
Catalyst 4500 series switches provide two proprietary spanning tree modes based on the IEEE 802.1D standard and one mode that is a combination of the two modes:
•Per VLAN Spanning Tree (PVST+)
•Rapid PVST+
•Multi-Instance Spanning Tree Protocol (MISTP)
•MISTP-PVST+ (combination mode)
The following sections provide an overview of each mode.
PVST+ Mode
PVST+ is the default STP used on all Ethernet, Fast Ethernet, and Gigabit Ethernet port-based VLANs on Catalyst 4500 series switches. PVST+ runs on each VLAN on the switch, ensuring that each has a loop-free path through the network.
PVST+ provides Layer 2 load balancing for the VLAN on which it runs; you can create different logical topologies using the VLANs on your network to ensure that all of your links will be used but no one link will be oversubscribed.
Each instance of PVST+ on a VLAN has a single root switch. This root switch propagates the spanning tree information that is associated with that VLAN to all other switches in the network. Because each switch has the same knowledge about the network, this process ensures that the network topology is maintained.
Rapid PVST+
Rapid PVST+ is the same as PVST+, except that Rapid PVST+ utilizes a Rapid STP that is based on IEEE 802.1w instead of 802.1D. Rapid PVST+ uses the same configuration as PVST+, and you need only minimal extra configuration. With Rapid PVST+, dynamic CAM entries are flushed immediately per port upon any topology change. UplinkFast and BackboneFast are enabled but not active in this mode, because the functionality is built into the rapid STP. This method provides for quick recovery of connectivity following the failure of a bridge, bridge port, or LAN.
MISTP Mode
MISTP is an optional STP that runs on Catalyst 4500 series switches. MISTP allows you to group multiple VLANs under a single instance of spanning tree (an MISTP instance). MISTP combines the Layer 2 load-balancing benefits of PVST+ with the lower CPU load of IEEE 802.1Q.
An MISTP instance is a virtual logical topology that is defined by a set of bridge and port parameters; an MISTP instance becomes a real topology when VLANs are mapped to it. Each MISTP instance has its own root switch and a different set of forwarding links (that is, different bridge and port parameters).
Each MISTP instance has a single root switch, which propagates the information that is associated with that instance of MISTP to all other switches in the network. This process ensures that the network topology is maintained because each switch has the same knowledge about the network.
MISTP builds MISTP instances by exchanging MISTP BPDUs with peer entities in the network. There is only one BPDU for each MISTP instance, rather than for each VLAN as in PVST+. There are fewer BPDUs in an MISTP network; therefore, there is less overhead in the network. MISTP discards any PVST+ BPDUs that it sees.
An MISTP instance can have any number of VLANs that are mapped to it, but a VLAN can only be mapped to a single MISTP instance. You can easily move a VLAN (or VLANs) in an MISTP topology to another MISTP instance if it has converged. (However, if ports are added at the same time that the VLAN is moved, convergence time is required.)
MISTP-PVST+ Mode
MISTP-PVST+ is a transition spanning tree mode that allows you to use the MISTP functionality on Catalyst 4500 series switches while continuing to communicate with the older Catalyst 5000 family and 6500 series switches in your network that use PVST+. A switch using PVST+ mode and a switch using MISTP mode connected together cannot see the BPDUs of the other switch, a condition that can cause loops in the network. MISTP-PVST+ allows interoperability between PVST+ and pure MISTP, because it detects the BPDUs of both modes. If you wish to convert your network to MISTP, you can use MISTP-PVST+ to transition the network from PVST+ to MISTP to avoid problems.
MISTP-PVST+ conforms to the limits of PVST+; for example, you can only configure the amount of VLAN ports on your MISTP-PVST+ switches that you configure on your PVST+ switches.
Understanding How Bridge Identifiers Work
The next two sections explain how MAC addresses are used in PVST+ and MISTP as unique bridge identifiers.
MAC Address Allocation
Catalyst 4000 series switches have a pool of 1024 MAC addresses that can be used as bridge identifiers for VLANs running under PVST+ or for MISTP instances. The Catalyst 4500 series switches have a pool of only 64 MAC addresses. You can use the show module command to view the MAC address range.
MAC addresses are allocated sequentially, with the first MAC address in the range assigned to VLAN 1, the second in the range assigned to VLAN 2, and so forth. The last MAC address in the range is assigned to the supervisor engine in-band (sc0) management interface.
For example, if the MAC address range for the supervisor engine is 00-e0-1e-9b-2e-00 to 00-e0-1e-9b-31-ff, the VLAN 1 bridge ID is 00-e0-1e-9b-2e-00, the VLAN 2 bridge ID is 00-e0-1e-9b-2e-01, the VLAN 3 bridge ID is 00-e0-1e-9b-2e-02, and so forth. The in-band (sc0) interface MAC address is 00-e0-1e-9b-31-ff.
MAC Address Reduction
MAC address reduction is used on Catalyst 6500 series switches to enable extended-range VLAN identification. If you have a Catalyst 6500 series switch in your network and you have MAC address reduction enabled on it, you should also enable MAC address reduction on all your Catalyst 4500 series switches to avoid problems in the spanning tree topology. When MAC address reduction is enabled on Catalyst 4500 series switches, it disables the pool of MAC addresses that are used for the VLAN spanning tree, leaving a single MAC address that identifies the switch. For detailed information on MAC address reduction, refer to the Catalyst 6500 Series Switch Software Configuration Guide.
MAC address reduction is always enabled on the Catalyst 4500 series switches; however, it may or may not be enabled on a Catalyst 4006 switch; this can affect the selection of the root bridge after you migrate your supervisor engine. Here are two scenarios to consider:
•The Catalyst 4006 switch is not a root switch
In this case, the spanning tree topology does not change. If you add a Catalyst 4500 series switch with MAC address reduction enabled and its default spanning tree bridge ID priority set to 32,768 to the network, the bridge ID priority of the new switch becomes the bridge ID priority that is added to the system ID extension. The system ID extension is the VLAN number and can vary from 1 to 4094. If the switch is in VLAN 1, the new bridge ID priority will be 32,769. Because 32,769 is greater than 32,768, this switch cannot become the root switch.
•The Catalyst 4006 is a root switch
In this case, the spanning tree topology might change. If the other switches in the network are not running MAC address reduction, the topology will change after you replace the chassis with a Catalyst 4500 series switch. The bridge ID priority of the new Catalyst 4500 series switch increments in the same manner as in the previous scenario (bridge ID priority + VLAN number). If the switch is in VLAN 1, the new bridge ID will be 32,769. Because 32,769 is greater than 32,768, this switch cannot become the root switch. The network designates a new root switch; the spanning tree topology also changes to reflect the new root switch.
If the bridge priority of the Catalyst 4006 has been lowered administratively and you use the same configuration in the new Catalyst 4500 series switch, then the switch remains the root switch and the spanning tree topology does not change.
For more information on migrating your supervisor engine from a Catalyst 4006 switch to a Catalyst 4500 series switch, see the "Migrating a Supervisor Engine II from a Catalyst 4006 Switch to a Catalyst 4500 Series Switch" section on page 28-10.
Understanding How MST Works
The Multiple Spanning Tree (MST) feature is the IEEE 802.1s and is an amendment to 802.1Q. MST extends the 802.1w Rapid Spanning Tree (RST) algorithm to multiple spanning trees. This extension provides for both rapid convergence and load balancing in a VLAN environment. The MST protocol is currently being further developed; the MST feature for this release is based on a draft version of the IEEE standard. The protocol, as implemented in this release, is backward compatible with 802.1D STP, 802.1w, the Rapid Spanning Tree Protocol (RSTP), and the Cisco PVST+ architecture.
MST allows you to build multiple spanning trees over VLAN trunks. You can group and associate VLANs to spanning tree instances. Each instance can have a topology independent of other spanning tree instances. This new architecture provides multiple forwarding paths for data traffic and enables load balancing. Network fault tolerance is improved because a failure in one instance (forwarding path) does not affect other instances (forwarding paths).
In large networks, having different VLAN-spanning tree instance assignments that are located in different parts of the network makes it easier to administrate and utilize redundant paths. However, a spanning tree instance can exist only on bridges that have compatible VLAN-instance assignments. MST requires that you configure a set of bridges with the same MST configuration information, allowing them to participate in a given set of spanning tree instances. Interconnected bridges that have the same MST configuration are referred to as an MST region.
MST uses the modified RSTP version called the Multiple Spanning Tree Protocol (MSTP). The MST feature has these characteristics:
•MST runs a variant of spanning tree called Internal Spanning Tree (IST). IST augments the Common Spanning Tree (CST) information with internal information about the MST region. The MST region appears as a single bridge to adjacent Single Spanning Tree (SST) and MST regions.
•A bridge running MST provides interoperability with single spanning tree bridges as follows:
–MST bridges run a variant of STP (IST) that augments the Common Spanning Tree (CST) information with internal information about the MST region.
–IST connects all the MST bridges in the region and appears as a subtree in the CST that encompasses the whole bridged domain. The MST region appears as a virtual bridge to adjacent SST bridges and MST regions.
–The collection of ISTs in each MST region, the CST that interconnects the MST regions, and the SST bridges define Common and Internal Spanning Tree (CIST). CIST is the same as an IST inside an MST region and the same as CST outside an MST region. The STP, RSTP, and MSTP together elect a single bridge as the root of CIST.
•MST establishes and maintains additional spanning trees within each MST region. These spanning trees are referred to as MST instances (MSTIs). The IST is numbered 0, and the MSTIs are numbered 1, 2, 3. and so on. Any given MSTI is local to the MST region that is independent of MSTIs in another region, even if the MST regions are interconnected. MST instances combine with the IST at the boundary of MST regions to become the CST as follows:
–Spanning tree information for an MSTI is contained in an MSTP record (M-record).
M-records are always encapsulated within MST BPDUs (MST BPDUs). The original spanning trees computed by MSTP are called M-trees. M-trees are active only within the MST region. M-trees merge with the IST at the boundary of the MST region and form the CST.
•MST provides interoperability with PVST+ by generating PVST+ BPDUs for the non-CST VLANs.
•MST supports some of the PVST+ extensions in MSTP as follows:
–UplinkFast and BackboneFast are not available in MST mode; they are part of RSTP.
–PortFast is supported.
–BPDU filtering and BPDU guard are supported in MST mode.
–Loop guard and root guard are supported in MST. MST preserves the VLAN 1 disabled functionality except that BPDUs are still transmitted in VLAN 1.
–MST switches behave as if MAC reduction is enabled.
–For private VLANs, secondary VLANs are mapped to the same instance as the primary.
Note the following guidelines when using MST:
•Do not disable spanning tree on any VLAN in any of the PVST bridges.
•Ensure that all PVST spanning tree root bridges have lower (numerically higher) priority than the CST root bridge.
•Do not use PVST bridges as the root of CST.
•Ensure that trunks carry all of the VLANs that are mapped to an instance or do not carry any VLANs at all.
•Do not connect switches with access links because access links may partition a VLAN.
•Any MST configuration involving a large number of either existing or new logical VLAN ports should be carried out during the maintenance window. This action should be taken because the complete MST database gets reinitialized for any incremental changes (such as adding new VLANs to instances or moving VLANs across instances).
Rapid Spanning Tree Protocol
RSTP significantly reduces the time that it takes you to reconfigure the active topology of the network when changes to the physical topology or its configurations parameters occur. RSTP selects one switch as the root of a spanning-tree-connected active topology and assigns port roles to individual ports of the switch, depending on whether that port is part of the active topology.
RSTP provides rapid connectivity following the failure of a switch, switch port, or a LAN. A new root port and the designated port on the other side of the bridge transition to forwarding through an explicit handshake between them. RSTP allows switch port configuration so that the ports can transition to forwarding directly when the switch reinitializes.
RSTP, specified in 802.1w, supersedes STP, which is specified in 802.1D, while retaining compatibility with STP. RSTP provides the structure on which the MST operates. You configure RSTP when you configure the MST feature. For more information, see the "Configuring MST" section.
RSTP provides backward compatibility with 802.1D bridges, as follows:
•RSTP selectively sends 802.1D-configured BPDUs and Topology Change Notification (TCN) BPDUs on a per-port basis.
•When a port initializes, the Migration Delay timer starts and RSTP BPDUs are transmitted. While the Migration Delay timer is active, the bridge processes all BPDUs that are received on that port. RSTP BPDUs are not visible on the port. Only version 3 BPDUs are visible on the port.
•If the bridge receives an 802.1D BPDU after a port’s Migration Delay timer expires, the bridge assumes that it is connected to an 802.1D bridge and starts using only 802.1D BPDUs.
•When RSTP uses 802.1D BPDUs on a port and receives an RSTP BPDU after the migration delay expires, RSTP restarts the Migration Delay timer and begins using RSTP BPDUs on that port.
RSTP Port Roles
RSTP uses the following definitions for port roles:
•Root—A forwarding port that is elected for the spanning tree topology.
•Designated—A forwarding port that is elected for every switched LAN segment.
•Alternate—An alternate path to the root bridge to that provided by the current root port.
•Backup—A backup for the path that is provided by a designated port toward the leaves of the spanning tree. Backup ports can exist only where two ports are connected together in a loopback by a point-to-point link or bridge with two or more connections to a shared LAN segment.
•Disabled—A port that has no role within the operation of spanning tree.
Port roles are assigned as follows:
•A root port or designated port role includes the port in the active topology.
•An alternate port or backup port role excludes the port from the active topology.
RSTP Port States
The port state controls the forwarding and learning processes and provides the values of discarding, learning, and forwarding. See Table 7-3 for a comparison between STP port states and RSTP port states.
In a stable topology, RSTP ensures that every root port and designated port transition to forwarding while all alternate ports and backup ports are always in the discarding state.
MST-to-SST Interoperability
A virtual bridged LAN may contain interconnected regions of SST and MST bridges. See Figure 7-8.
Figure 7-8 Network with Interconnected SST and MST Regions

To the spanning tree protocol running in the SST region, an MST region appears as a single SST or pseudobridge. Pseudobridges operate as follows:
•The same values for root identifiers and root path costs are sent in all BPDUs of all the pseudobridge ports. Pseudobridges differ from a single SST bridge as follows:
–The pseudobridge BPDUs have different bridge identifiers. This difference does not affect STP operation in the neighboring SST regions because the root identifier and root cost are the same.
–BPDUs that are sent from the pseudobridge ports may have significantly different message ages. Because the message age increases by 1 second for each hop, the difference in the message age is in the order of seconds.
•Data traffic from one port of a pseudobridge (a port at the edge of a region) to another port follows a path that is entirely contained within the pseudobridge or MST region.
•Data traffic belonging to different VLANs may follow different paths within the MST regions that are established by MST.
•Loop prevention is achieved by either of the following:
–Blocking the appropriate pseudobridge ports by allowing one forwarding port on the boundary and blocking all other ports.
–Setting the CST partitions to block the ports of the SST regions.
•A pseudobridge differs from a single SST bridge because the BPDUs that are sent from the pseudobridge’s ports have different bridge identifiers. The root identifier and root cost are the same for both bridges.
Common Spanning Tree
802.1Q specifies a single spanning tree for all the VLANs called CST. In a Catalyst 4500 series switch running PVST+, the VLAN 1 spanning tree corresponds to CST. In a Catalyst 4500 series switch running MST, IST (instance 0) corresponds to CST.
MST Instances
This release supports up to 16 instances; each spanning tree instance is identified by an instance ID that ranges from 0 to 15. Instance 0 is mandatory and is always present. Instances 1 through 15 are optional.
MST Configuration
MST configuration has three parts as follows:
•Name—A 32-character string (null padded and null terminated) identifying the MST region.
•Revision number—An unsigned 16-bit number that increments each time that a change is made to the configuration.
Note You must set and update the revision number manually, because the number does not auto-increment each time that you commit the MST configuration.
•MST configuration table—An array of 4096 bytes. Each byte, interpreted as an unsigned integer, corresponds to a VLAN. The value is the instance number to which the VLAN is mapped. The first byte that corresponds to VLAN 0 and the 4096th byte that corresponds to VLAN 4095 are unused and always set to zero.
You must configure each byte manually. You can use SNMP or the CLI to perform the configuration.
MST BPDUs contain the MST configuration ID and the checksum. An MST bridge accepts an MST BPDU only if the MST BPDU configuration ID and the checksum match its own MST region configuration ID and checksum. If one value is different, the MST BPDU is treated as an SST BPDU.
When you modify an MST configuration through either a console or Telnet connection, the session exits without committing those changes and the edit buffer locks. Further configuration is impossible until you discard the existing edit buffer and acquire a new edit buffer by entering the set spantree mst config rollback force command.
MST Region
Interconnected bridges that have the same MST configuration are referred to as an MST region. There is no limit on the number of MST regions in the network.
To form an MST region, bridges can be either of the following:
•An MST bridge that is the only member of the MST region.
•An MST bridge that is interconnected by a LAN. A LAN’s designated bridge has the same MST configuration as an MST bridge. All the bridges on the LAN can process MST BPDUs.
If you connect two MST regions with different MST configurations, the MST regions do the following:
•Load balance across redundant paths in the network. If two MST regions are redundantly connected, all traffic flows on a single connection with the MST regions in a network.
•Provide an RSTP handshake to enable rapid connectivity between regions. However, the handshaking is not as fast as between two bridges. To prevent loops, all the bridges inside the region must agree upon the connections to other regions. This situation introduces a certain delay. We do not recommend partitioning the network into a large number of regions.
Boundary Ports
A port that connects an MST region to an SST region running RSTP (802.1w), an SST region running STP (802.1D), or another MST region is a boundary port. A boundary port is a port that connects to a LAN, the designated bridge of which, is either an SST bridge or a bridge with a different MST configuration. A designated port knows that it is on the boundary if it detects an STP bridge or receives an agreement message from an RST or MST bridge with a different configuration.
At the boundary, the role of MST ports do not matter; their state is forced to be the same as the IST port state. If the boundary flag is set for the port, the MSTP Port Role selection mechanism assigns a port role to the boundary and the same state as that of the IST port. The IST port at the boundary can take up any port role except a backup port role.
IST Master
The IST master of an MST region is the bridge with the lowest bridge identifier and the least path cost to the CST root. If an MST bridge is the root bridge for CST, then it is the IST master of that MST region. If the CST root is outside the MST region, then one of the MST bridges at the boundary is selected as the IST master. Other bridges on the boundary that belong to the same region eventually block the boundary ports that lead to the root.
If two or more bridges at the boundary of the region have an identical path to the root, you can set a slightly lower bridge priority to make a specific bridge the IST master.
The root path cost and message age inside a region stays constant, but the IST path cost is incremented and the IST remaining hops is decremented at each hop. Enter the show spantree mst command to display the information about the IST master, path cost, and remaining hops for the bridge.
Edge Ports
A port that is connected to a nonbridging device (for example, a host or a router) is an edge port. A port that connects to a hub is also an edge port, provided that the hub or any LAN that is connected by it does not have a bridge. These ports start forwarding as soon as the link is up.
MST requires that all ports are configured for each host or router. To establish rapid connectivity after a failure, you need to block the nonedge-designated ports of an intermediate bridge. If the port connects to another bridge that can send back an agreement, then the port starts forwarding immediately. Otherwise, the port requires twice the forward delay time to start forwarding again. You must explicitly configure the ports that are connected to the hosts and routers as edge ports while using MST.
Note To configure a port as an edge port, you enable PortFast on that port. See Chapter 8, "Configuring Spanning Tree PortFast, BPDU Guard, BPDU Filter, UplinkFast, BackboneFast, and Loop Guard." When you enter the show spantree portfast mod/port command, if the designation for a port is displayed as edge, that port is also a PortFast port.
To prevent a misconfiguration, PortFast turns off operationally if the port receives a BPDU. You can display the configured and operational status of PortFast by using the show spantree mst mod/port command.
Link Type
You can establish rapid connectivity only on point-to-point links. For correct operation of the protocol, you must explicitly configure ports to a host or router. However, cabling in most networks meets this requirement, and you can avoid explicit configuration by treating all full-duplex links as point-to-point links. Enter the set spantree mst link-type command to configure point-to-point links.
Message Age and Hop Count
IST and MST instances do not use the Message Age and Maximum Age timer settings in the BPDU. IST and MST use a separate hop count mechanism that is very similar to the IP TTL mechanism. You can configure each MST bridge with a maximum hop count. The root bridge of the instance sends a BPDU (or M-record) with the remaining hop count that is equal to the maximum hop count. When a bridge receives a BPDU (or M-record), it decrements the received remaining hop count by one. The bridge discards the BPDU (M-record) and ages out the information held for the port if the count reaches zero after decrementing. The nonroot bridges propagate the decremented count as the remaining hop count in the BPDUs (M-records) they generate.
The Message Age and Maximum Age timer settings in the RST portion of the BPDU remain the same throughout the region, and the same values are propagated by the region’s designated ports at the boundary.
MST-to-PVST+ Interoperability
These guidelines apply in a topology where you configure MST switches (all in the same region) to interact with PVST+ switches that have VLANs 1-100 set up to span throughout the network:
•Configure the root for all VLANs inside the MST region. The ports that belong to the MST switch at the boundary simulate PVST+ and send PVST+ BPDUs for all the VLANs. This example shows the ports simulating PVST:
Настройка STP на коммутаторах D-Link серии DGS-3130
Для обеспечения отказоустойчивости между коммутаторами нужно создать несколько резервных соединений. Но при этом в сети возникнут коммутационные петли, если не использовать дополнительные алгоритмы решения этой проблемы. Одно из средств, которое позволяет избавиться от таких петель и связанных с этим проблем — это использование на коммутаторах протокола Spanning Tree.
Протокол связующего дерева Spanning Tree Protocol (STP) является протоколом 2 уровня модели OSI, который:
- позволяет строить древовидные, свободные от петель, конфигурации связей между коммутаторами локальной сети;
- обеспечивает возможность автоматического резервирования альтернативных каналов связи между коммутаторами на случай выхода активных каналов из строя.
В настоящее время существуют три версии протоколов связующего дерева:
- IEEE 802.1D Spanning Tree Protocol (STP);
- IEEE 802.1w Rapid Spanning Tree Protocol (RSTP);
- IEEE 802.1s Multiple Spanning Tree Protocol (MSTP).
Для построения активной топологии с использованием STP в сети выбирается корневой коммутатор, от которого строится всё дерево. Корневым становится коммутатор с наименьшим значением идентификатора Bridge ID.
Bridge ID состоит из двух частей: 2 байта приоритета (по умолчанию равен 32768) и 6 байт МАС-адреса коммутатора. Настраивая приоритет коммутатора (уменьшая его) администратор может повлиять на то, какой именно коммутатор станет корневым (RB). Все остальные коммутаторы будут некорневыми (NRB).
На следующем этапе у некорневых коммутаторов выбираются корневые порты.
Корневой порт (Root port, RP) — порт на некорневом коммутаторе с самым коротким (лучшим) путем к корневому коммутатору.
Путь до корневого коммутатора оценивается по его стоимости (Path Cost), которая рассчитывается как суммарное условное время на передачу данных от порта данного коммутатора до порта корневого коммутатора. Условное время сегмента рассчитывается как время передачи одного бита информации через канал с определенной полосой пропускания. Стоимости пути по умолчанию для каждого канала (100 МБит/с, 1 Гбит/с и т.д.) определены в стандарте IEEE 802.1D-2004.
Далее определяются назначенные порты (Designated Port, DP).
Назначенный порт (DP) — порт, который находится в состоянии пересылки. Все порты корневого моста являются назначенными.
Назначенный порт определяется путем сравнения значений стоимости пути всех маршрутов от данного сегмента до корневого моста.

Схема сети