Привет.
Сетевая подсистема в Windows NT прошла достаточно длительный путь – изначально являясь сетевой операционной системой, NT сразу ставила задачу предоставлять надежные, сбалансированные и эффективные сетевые решения.
Беда в том, что с точки зрения большинства админов под “настройкой сетевых параметров” понимаются видные глазом базовые минимальные пункты – как задание IP-адреса, маски и шлюза, а даже тот факт, что IP-адресов на интерфейсе может быть несколько, уже вызывает удивление.
Фактически же количество сетевых настроек в Windows NT достаточно велико, и, хорошо зная работу сетевой подсистемы, можно ощутимо улучшить работу ОС. И наоборот тоже. Поэтому данная статья обязательна к ознакомлению тем, кто хочет “покрутить параметры”.
Диспозиция
Я предполагаю, что Вы, товарищ читатель, знаете на приемлемом уровне протокол TCP, да и вообще протоколы сетевого и транспортного уровней. Чем лучше знаете – тем больше КПД будет от прочтения данной статьи.
Речь будет идти про настройку для ядра NT 6.1 (Windows 7 и Windows Server 2008 R2). Всякие исторические ссылки будут, но сами настройки и команды будут применимы к указанным ОС, если явно не указано иное.
В тексте будут упоминаться ключи реестра. Некоторые из упоминаемых ключей будут отсутствовать в официальной документации. Это не страшно, но перед любой серьёзной модификацией рабочей системы лучше фиксировать то, что Вы с ней делаете, и всегда иметь возможность удалённого доступа, не зависящую от состояния сетевого интерфейса (например KVM).
Это – первая часть статьи. Потому что настроек достаточно много. В следующей части я расскажу про другие.
Содержание
- Работаем с RSS
- Работаем с CTCP
- Работаем с NetDMA
- Работаем с DCA
- Работаем с ECN
- Работаем с TCP Timestamps
- Работаем с WSH
- Работаем с MPP
Поехали.
Настраиваем RSS в Windows
Аббревиатура RSS обычно ассоциируется совсем с другим, нежели с настройкой TCP. Хотя, в общем, это у всех по-разному – кто-то PHP с ходу расшифровывает как Penultimate Hop Popping, а кто-то думает, что КВД – это НКВД без первой буквы. Все люди разные. Мы будем говорить про тот RSS, который Receive Side Scaling.
Суть технологии RSS достаточно проста – входящий поток данных сетевого уровня разбивается на несколько очередей, обработка каждой из которых (вызов прерываний, копирование информации) производится выделенным виртуальным процессором (т.е. или отдельным физическим, или ядром). То есть в случае наличия нескольких процессоров Вы можете распределить интенсивный сетевой трафик по ним, снизив количество вызовов прерываний, переключений контекста, очистки кэша и прочих неприятностей, которые, если происходят много тысяч раз в секунду, могут ощутимо навредить производительности системы в целом.
Суть-то простая, да вот в реализации столько тонкостей, что можно написать отдельную статью. Пока это не является целью, поэтому постараюсь описать оные тонкости сжато и компактно 
Для начала необходимо, чтобы сетевая карта умела формировать вышеупомянутые очереди, и умела делать это хорошо. По сути, эта задача требует от сетевой карты функционала, отдалённо напоминающего CEF (который Cisco Express Forwarding) – коммутации 3го уровня с определением и разделением отдельных потоков пакетов. Давайте попробуем разобраться на примере, как и зачем это может работать.
Допустим, у Вас есть быстрый сетевой адаптер (например, 10Гбит), и по нему к Вам приходит много данных. И эти данные хорошо разделяются на много потоков (например, когда мы ведём вебинары, на каждого слушателя идёт почти по десятку TCP-сессий, а слушателей бывает и 40). По сути, все эти потоки данных выглядят потоками только на транспортном уровне, а на сетевом сливаются в общий поток. Это, в общем, и есть работа протоколов транспортного уровня – мультиплексировать потоки данных от различных приложений на различных хостах. Но от этого нашей принимающей стороне не легче – ведь ей надо из входящего потока сформировать:
- Отдельные сессии TCP – т.е. для каждой поддерживать session state, буферы данных, состояние cwnd/rwnd, состояние sack’ов и ack’ов вообще
- Отдельные буферы для каждого фрагментированного IP-пакета
- Отдельные очереди (ведь трафик может обладать приоритетами)
И практически каждое событие во всей этой пачке сессий – это вызов прерывания и его обработка. Крайне затратно, особенно учитывая, допустим, негативный сценарий (10 гигабит поток, ip-пакеты по 1КБ). Можно даже сказать проще – ощутимое количество процентов мощности процессора (весьма дорогого, заметим) уйдёт на решение этих задач тех.обслуживания. Как с этим бороться? Да просто – пусть адаптер формирует отдельные очереди пакетов – тогда на каждую из них можно “привязать” свой процессор/ядро, и нагрузка в плане прерываний и прочего распределится. Но тут нас поджидает неочевидная проблема.
Дело в том, что просто так распределить не получится. Т.е. если мы придумаем очень простой критерий распределения (например, две очереди, четные пакеты – налево, нечетные – направо), то у нас может получиться следующая ситуация – у потоков данных часть пакетов попадёт в “четную” очередь, а часть – в “нечетную”. А в этом случае мы потеряем все возможные бонусы, возникающие при обработке непрерывного потока пакетов (обычно эти бонусы выглядят как “первый пакет обрабатываем по-полной, кэшируем все возможные результаты обработки, и все последующие пакеты обрабатываем по аналогии”). Т.е. нам надо всячески избегать ситуации, когда одному процессору придётся, обрабатывая, например, поток очень однотипных мультимедийных пакетов (какой-нибудь RTP например), пытаться “сбегать почитать” в соседнюю очередь. Скажем проще – никуда он вообще бегать тогда не будет, а придётся тогда нам выключать всяческие ускорения обработки TCP/UDP/IP-потоков, потому что работать они будут только в случае ситуации, когда весь поток однотипных пакетов обрабатывается одним ядром/процессором. А это приведёт к тому, что на процессоры придётся переводить вообще всю нагрузку по обработке сетевых данных, что с гарантией “убьёт” даже достаточно мощный CPU.
То есть, наша задача-максимум – это распределить входящие данные по нескольким отдельным очередям приёма, да так, чтобы потоки пакетов легли в очереди “целиком”, да и ещё желательно, чтобы заполнились эти очереди равномерно. Тогда мы и распределим нагрузку по процессорным ядрам, и не потеряем другие возможности по ускорению обработки потоков пакетов. Для решения этой задачи нам надо будет действовать сообща – и ОС, и оборудованию.
Хороший RSS начинается с сетевой карты. В сетевых картах, которые умеют RSS (а уже понятно, что это не карты минимального уровня), такой функционал есть – например в очень даже недорогой Intel 82576 (в моём случае – встроена в сервер) есть функционал и включения RSS сразу, и выбора количества очередей – 1, 2, 4 или 8.
Почему же количество очередей RSS будет выбираться из целочисленных степеней двойки? Тут начинается интересное, что будет роднить логику работы RSS и, допустим, логику балансировки у etherchannel.
Дело в том, что для того, чтобы определить “принадлежность” пакета к потоку, RSS использует следующую логику – берутся несколько ключевых полей пакета – SRC IP, DST IP, код протокола L4, SRC PORT, DST PORT – и от них вычисляется хэш, по последним битам которого (соответственно, для 2х очередей достаточно и одного бита, для 4х – двух, для 8 – трёх) и определяется принадлежность пакета к буферу. Соответственно, пакеты одного протокола, идущие с одного фиксированного порта и IP-адреса на другой адрес и порт, будут формировать поток и попадать в одну очередь. Такой подход достаточно быстр и прост с точки зрения балансировщика, но, как понятно, никак не решает ситуацию “Есть два стула две TCP-сессии – одна 1% канала занимает, другая 99%”. И даже не гарантирует, что обе эти сессии не попадут (с вероятностью 1/2) в одну и ту же очередь, что вообще превратит всю задачу в бессмыслицу.
Поэтому, в общем-то, остановимся на следующем факте – если у сетевой карты есть поддержка RSS, то её надо как минимум включить, чтобы первичное разделение входящего трафика на несколько очередей, притом с сохранением потоков, происходило без участия CPU.
Ну а вот дальше – уже задача операционной системы – что есть не один, а несколько потоков, и на каждый надо выделить свой процессор или ядро. Это как раз и будет тот самый RSS, который мы будем включать. Он уже будет создавать в драйвере NDIS отдельные очереди и выделять на каждую из них по процессору/ядру.
Нововведением в Windows Server 2008 R2 является то, что этим можно управлять – правда, только через реестр. В частности, управлению будут поддаваться 2 параметра – стартовое количество процессорных ядер, выделяемое для всех RSS-очередей на адаптере, и максимальное количество ядер для данной задачи. Параметры эти будут находиться по адресу HKLM\SYSTEM\CurrentControlSet\Control\Class\гуид сетевого адаптера\номер сетевого адаптера\ и называться, соответственно, *RssBaseProcNumber и *MaxRSSProcessors.
Пример использования данных параметров – допустим, у Вас есть сервер с 16 ядрами (2 процессора по 8 ядер или 4 по 4 – не суть). Есть три сетевых адаптера – один используется для управления системой, два других – для привязки к ним виртуальных машин. Вы можете выставить указанные параметры только у двух интерфейсов, на которых будет подразумеваться высокая нагрузка, притом следующим образом – поставить RssBaseProcNumber равным 2, а MaxRSSProcessors – например, 12. Тогда тот интерфейс, который будет активнее принимать трафик, сможет “отъесть” до 12 ядер системы на обработку очередей, при этом не надо будет жестко задавать этот параметр вручную (это удобно, если нагрузка переместится на другой интерфейс). Безусловно, в этом примере надо, чтобы сетевые адаптеры тоже поддерживали RSS, и, желательно, хотя бы очередей 8.
Подводя итоги – RSS – это достаточно практичная и нужная технология, требующая поддержку и со стороны оборудования, и со стороны операционной системы. И становящаяся всё более актуальной, так как на данный момент скорости сетевых интерфейсов растут, равно как и количество процессорных ядер, а, следовательно, старый подход, когда одно ядро “разгребает” единую входящую очередь, становится всё менее эффективным.
Как включить RSS в Windows
netsh interface tcp set global rss=enabled
Настраиваем логику алгоритма контроля перегрузки (CTCP) в Windows
Compound TCP – это Microsoft’овский протокол управления “окном перегрузки” (congestion window). Адресно предназначен для форсированного изменения окна при работе в сетевых средах с относительно большой задержкой (например, по WiMax или спутниковым каналам). Соответственно, не сильно полезен в сценарии широкополосного доступа в Интернет или работе по локальной сети.
По сути, всё, что он делает, это форсирует быстрое увеличение окна со стороны отправителя в случае, если обнаруживается, что сеть имеет малое время отклика, и быстро уменьшает окно в случае задержек на канале.
Как включить CTCP в Windows
netsh interface tcp set global congestionprovider=ctcp
Настраиваем использование NetDMA в Windows
NetDMA – достаточно интересная функция. Смысл её применения есть тогда, когда у Вас не поддерживается Chimney Offload и Вы хотите ускорить обработку сетевых подключений. NetDMA позволяет копировать без участия CPU данные (в общем, как и любой DMA-доступ) из приемных буферов сетевого стека сразу в буферы приложений, чем снимает с CPU данную задачу по тупому выполнению чего-то типа rep movsd.
Говоря проще, если Ваша сетевая плата не может “вытащить” на себя полную обработку TCP-соединений, то NetDMA хотя бы разгрузит процессор от самой унылой части задачи по обслуживанию сетевых соединений – копированию данных между сетевой подсистемой и использующими её приложениями.
Что нужно для включения NetDMA в Windows
Нужно оборудование, которое поддерживает NetDMA – в случае Windows это процессор с поддержкой технологий семейства Intel® I/O Acceleration Technology (I/OAT), которые, в свою очередь, входят в Intel Virtual Technology for Connectivity (VT-c). Включение NetDMA на оборудовании AMD эффекта, увы, не принесёт – не поверив, проверил на домашнем феноме 1055T – действительно, NetDMA не включается.
Как включить NetDMA в Windows
Локально:
netsh interface tcp set global netdma=enabled
Через Group Policy:
Откройте ключ HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\, создайте в нём параметр EnableTCPA вида 32bit DWORD и поставьте его в единицу
Секретный уровень
Если Вы дочитали до этого места, то дальше не читайте – опасно. Но вообще, в том же ключе – HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\ – есть параметр MinPacketSizeToDma, тоже типа 32bit DWORD, который, что и логично, исходя из его названия, указывает минимальный размер пакета, для которого имеет смысл инициировать DMA-передачу. Параметр данный выставляется автоматически и его тюнинг имеет слабый практический смысл – т.е. в принципе можно представить ситуацию, когда система поставит слишком малый параметр, и будет слишком часто переключаться на DMA, а Вы это поправите вручную, но очень слабо могу представить себе КПД этой операции – выяснять сие путём достаточно кропотливых синтетических тестов, чтобы выиграть призрачные доли процента на единственной операции в единственной подсистеме, притом доли эти будут укладываться в погрешность измерений, весьма уныло.
Настраиваем использование DCA (прямого доступа к кэшу NetDMA) в Windows
По сути, Direct Cache Access – это дополнение к NetDMA, которое появляется только в NetDMA 2.0 и является опциональным (т.е. факт наличия NetDMA не говорит о том, что DCA будет работать). Задачи, которые решает DCA, просты – он “привязывает” конкретную сетевую сессию к определённому ядру процессора, и позволяет копировать данные не по трассе “сетевой интерфейс”->”оперативная память”->”кэш процессора”, а напрямую с сетевого интерфейса в кэш процессора. В ряде сценариев (быстрая сеть и много сессий и ядер CPU) выигрыш может быть ощутимым – судя по исследованиям IEEE за 2009й год, в случае загруженной на ~80% 10Gbit сети плюс 12ти ядер нагрузка CPU падает примерно на треть.
Технология работоспособна для гигабитных и более быстрых сетевых адаптеров. И, как понятно, имеет смысл только в случае, когда сетевой адаптер не умеет Chimney Offload (что, в общем-то, уже достаточно сложно – в случае наличия нагрузки, при которой DCA эффективен, обычно используются сетевые адаптеры, которые на аппаратном уровне умеют обрабатывать TCP).
Кстати, интересный момент – DCA есть в Windows Server 2008, но не работает в Vista. В NT 6.1 работает везде, включая Windows 7.
Как включить DCA в Windows
Предварительно – обязательно включить NetDMA.
Локально:
netsh interface tcp set global dca=enabled
Через Group Policy:
Откройте ключ HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\, создайте в нём параметр EnableDCA вида 32bit DWORD и поставьте его в единицу
Настраиваем уведомления о перегрузке (ECN’ы) в Windows
Технология ECN в явном виде относится и к IP, а не только к TCP, но все равно про неё стоит тут написать.
Протокол IP изначально не особо любил технологии класса Quality of Service – QOS, поэтому в заголовке IPv4 выделен байт с целью “использовать для целей управления качеством”. Притом этот байт может содержать данные в разных форматах, и то, как его интерпретировать, решает конкретный хост. Используется два возможных формата данного байта – DSCP (он же DiffServ) и IP Precedence. По умолчанию этот байт (называющийся ToS – Type of Service) обрабатывается как IP Precedence и представляет собой копию данных канального уровня (в него копируются три бита от CoS – Class of Service, которые передаются в 802.3 кадре в составе 802.1p компонента заголовка 802.1Q).
Но нас будет интересовать ситуация, когда в заголовке IP-пакета – в поле ToS, разумеется – данные интерпретируются в формате DSCP. В этом случае на номер класса трафика отдаётся 6 бит (что даёт возможность сделать в организации 2^6 = 64 класса трафика и удобно управлять приоритетами), а оставшиеся 2 бита отдаются как раз на сигнализацию о “заторах”.
Говоря проще, если у промежуточного устройства буфер пакетов близок к перегрузке, то оно сигнализирует Вам, отправляя служебный пакет на IP отправителя, что “пакеты скоро будет некуда девать и придётся их выбрасывать, притормози”. Отправляет их, выставляя как раз специфические биты в поле ToS. Соответственно, включая поддержку данной технологии, Вы будете включать и возможность генерации подобных пакетов, и возможность анализа оных.
Простейший пример ситуации, в которой это поможет – на пути Вашего трафика стоит маршрутизатор, который в Вашу сторону смотрит интерфейсом со скоростью 1 Gbit, а дальше – интерфейсом со скоростью 100 Mbit. Если Вы будете отдавать ему трафик с максимально возможной скоростью, то его очередь пакетов, пытающихся “выйти” через интерфейс со скорость 100 Mbit, очень быстро переполнится, и если он не сможет Вам об этом сказать (ну или если Вы не включите со своей стороны возможность услышать эти сообщения от него), то ему придётся просто в определённый момент перестать принимать пакеты, сбрасывая их. А это приведёт к тому, что начнётся потеря данных, которые надо будет восстанавливать – а служебный трафик при восстановлении данных достаточно значителен. Т.е. гораздо проще передать чуть медленнее, чем потерять много пакетов и выяснить это на уровне TCP-подключения, после чего запрашивать их повторно, теряя время и тратя трафик.
Кстати, проверить поддержку ECN ближайшим маршрутизатором можно бесплатной утилитой Internet Connectivity Evaluation Tool.
Как включить ECN в Windows
netsh interface tcp set global ecn=enabled
Настраиваем TCP Timestamps (по RFC 1323) в Windows
TCP Timestamps – базовая низкоуровневая технология, которая позволяет стеку TCP измерять два важных параметра для соединения: RTTM (задержку канала) и PAWS (защита от дублирующихся TCP-сегментов). В случае, если TCP Timestamps не включены хотя бы с одной стороны подключения, оба механизма вычисления этих параметров отключены и система не может высчитать данные значения. Это приводит к тому, что становится невозможным быстро и эффективно менять размер окна TCP (без знания времени задержки на канале-то). Поэтому включать TCP Timestamps в случае работы с большими объёмами данных (например, обращение к быстрому серверу в локальной сети – типовой сценарий корпоративной LAN) необходимо – ведь иначе протокол TCP не сможет быстро “раскачать” окно передачи.
Как включить TCP Timestamps в Windows
netsh interface tcp set global timestamps=enabled
Побочные эффекты включения TCP Timestamps в Windows
Практически не наблюдаются. Рост локальной загрузки CPU отсутствует, т.к. алгоритм достаточно прост, рост объёмов служебного трафика – так же (RTTM высчитывается, исходя из “времени оборота” обычных сегментов TCP, а не каких-то специальных дополнительных).
Настраиваем автоматический подбор размера окна TCP (WSH) в Windows
Данный параметр достаточно прост. Эта настройка – Window Scale Heuristic – говорит о том, будете ли Вы сами выбирать логику поведения протокола TCP для выбора размеров окна, либо отдадите это на усмотрение операционной системе.
То есть при включенном алгоритме WSH вышеупомянутый тюнинг окна TCP – выбор между disabled/highlyrestricted/restricted/normal/experiemental – будет делаться автоматически и Ваша настройка параметра autotuninglevel будет просто игнорироваться. При просмотре будет появляться служебное окно с текстом "The above autotuninglevel setting is the result of Windows Scaling heuristics overriding any local/policy configuration on at least one profile".
Как включить Window Scaling Heuristic в Windows
netsh interface tcp set heuristics wsh=enabled
Настраиваем базовую безопасность TCP (параметр Memory Pressure Protection) в Windows
Данная функция предназначена для защиты от достаточно известной атаки – локального отказа в обслуживании, вызванного тем, что удалённый атакующий инициирует множество TCP-сессий к нашей системе, система выделяет под каждую сессию буферы и оперативная память, возможно, заканчивается (ну или просто забивается до степени, когда начинается свопинг и производительность ощутимо падает.
Параметр включен по умолчанию в Windows Server 2008 R2, поэтому обычно нет смысла его настраивать, но если что – Вы можете его включить вручную. Более того, Вы можете выбрать, на каких портах эту защиту включать, а на каких – нет. Это имеет смысл, если доступны снаружи лишь некоторые порты, а не все.
Как включить Memory Pressure Protection в Windows
netsh interface tcp set security mpp=enabled
Включение MPP для отдельного порта (например, у нас наружу опубликован веб-сервер)
netsh int tcp set security startport=80 numberofports=1 mpp=enabled
Выключение MPP для всех портов, кроме указанного (например, кроме LDAP)
netsh int tcp set security startport=1 numberofports=65535 mpp=disabled
netsh int tcp set security startport=389 numberofports=1 mpp=enabled
netsh int tcp set security startport=636 numberofports=1 mpp=enabled
Дополнительно
На самом деле, можно включать или выключать MPP для протоколов IP разных версий отдельно, а не глобально для всех. Для этого будут два ключа реестра с предсказуемыми названиями:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\EnableMPPHKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters\EnableMPP
Параметр EnableMPP в каждом из случаев имеет тип 32bit DWORD и ставится либо в единицу, либо в нуль.
Вместо заключения
Данный краткий обзор части возможностей настроек сетевой подсистемы Windows имеет собой цель не побудить к немедленной правке всего вышеупомянутого, а показать то, что в данной ОС присутствует достаточно много инструментов тюнинга, хорошее знание которых может очень позитивно повлиять на работу системы. Только надо учитывать, что хорошее знание – это не “какая утилитка какие ключики правит”, а в первую очередь – отличное знание базовых сетевых технологий, которое, увы, сейчас в сообществе специалистов по Windows встречается крайне редко. Но я верю, что у Вас, при надлежащем системном подходе, всё будет хорошо.
UPDATE
Написал вторую часть статьи.
Shortcuts
Tweaking Windows 7 / Vista TCP/IP settings for broadband internet connections
2008-04-24 (updated: 2016-09-05) by
Tags: patch, Nagle, QoS, SynAttackProtect, DNS, DefaultTTL, NetDMA, TCP 1323 Options, MTU, auto-tuning, Compound TCP, Chimney Offload, CTCP, TCP Window, Registry, TCP/IP, tweak, Vista, Windows 7
Windows Vista introduces a number of new features to the TCP/IP stack, including CTCP, and TCP Window Auto-Tuning. This new implementation works much better by default than previous Windows versions with broadband internet connections, and is able to adjust the RWIN value on the fly, depending on the BDP (bandwidth-delay product). This, however, introduces some problems with older routers and restricts the user from tweaking some of the TCP/IP parameters. Still, there is always some room for improvement, and this article explains the known tweakable TCP/IP parameters.
To enter some of the commands below, you will need to run «elevated» command prompt. To do so, click the Start icon > Run > type: cmd , then click CTRL+SHIFT+ENTER. Alternatively, you can navigate to Start > All Programs > Accessories > right-click Command Prompt and choose «Run as Administrator».
Check the TCP/IP state
To check the current status of the Vista TCP/IP tweakable parameters, in elevated command prompt type the following command:
netsh int tcp show global
You will be presented with something like the following:
The settings, as well as their default and recommended state are explained below. The two most important tweakable parameters are «Auto-Tuning Level» and «Congestion Control Provider».
When checking the TCP state with the «netsh int tcp show global» command, it is also possible to see the following message below all those parameters:
** The above autotuninglevel setting is the result of Windows Scaling heuristics overriding any local/policy configuration on at least one profile.
It is displayed when the «Receive Window Auto-Tuning Level» is not explicitly set, or if the system deemed it necessary to make a change because of user prompted «repairing» of your network connection, for example.
Disable Windows Scaling heuristics
Windows Vista/7 has the ability to automatically change its own TCP Window auto-tuning behavior to a more conservative state regardless of any user settings. It is possible for Windows to override the autotuninlevel even after an user sets their custom TCP auto-tuning level. When that behavior occurs, it can have a very noticeable negative impact on throughput, and it does not automatically correct itself. If auto-tuning gets limited, the «netsh int tcp show global» command displays the following message:
** The above autotuninglevel setting is the result of Windows Scaling heuristics
overriding any local/policy configuration on at least one profile.
To prevent that behavior and enforce any user-set TCP Window auto-tuning level, you should execute the following command:
netsh int tcp set heuristics disabled
possible settings are: disabled,enabled,default (sets to the Windows default state)
recommended: disabled (to retain user-set auto-tuning level)
Note this should be executed in elevated command prompt (with admin priviledges) before setting the autotuninlevel in next section. If the command is accepted by the OS you will see an «Ok.» on a new line.
The corresponding Registry value (not necessary to edit if setting via netsh) is located in:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Tcpip\Parameters
EnableWsd=0 (default: 1, recommended: 0)
Note: This automatic limitation of the TCP Window usually occurs in the presence of some packet loss, which can be common in longer transfers and server applications.
TCP Auto-Tuning
To turn off the default RWIN auto tuning behavior, (in elevated command prompt) type:
netsh int tcp set global autotuninglevel=disabled
The default auto-tuning level is «normal», and the possible settings for the above command are:
disabled: uses a fixed value for the tcp receive window. Limits it to 64KB (limited at 65535).
highlyrestricted: allows the receive window to grow beyond its default value, very conservatively
restricted: somewhat restricted growth of the tcp receive window beyond its default value
normal: default value, allows the receive window to grow to accommodate most conditions
experimental: allows the receive window to grow to accommodate extreme scenarios (not recommended, it can degrade performance in common scenarios, only intended for research purposes. It enables RWIN values of over 16 MB)
Our recommendation: normal (unless you’re experiencing problems).
If you’re experiencing problems with your NAT router or SPI firewall, try the «restricted», «highlyrestricted», or even «disabled» state.
Notes:
— Reportedly, some older residential NAT routers with a SPI firewall may have problems with enabled tcp auto-tuning in it’s «normal» state, resulting in slow speeds, packet loss, reduced network performance in general.
— auto-tuning also causes problems with really old routers that do not support TCP Windows scaling. See MSKB 935400
— netsh set commands take effect immediately after executing, there is no need to reboot.
— sometimes when using «normal» mode and long lasting connections (p2p software / torrents), tcp windows can get very large and consume too much resources, if you’re experiencing problems try a more conservative (restricted) setting.
If you’re experiencing problems with Auto-Tuning, see also:
MSKB 835400 — email issues
MSKB 934430 — network connectivity behind firewall problems
MSKB 940646 — 3G WWAN throughput issues
MSKB 929868 — web browsing issues
MSKB 932170 — slow network file transfer
Compound TCP — Improve throughput
Add-On Congestion Control Provider
The traditional slow-start and congestion avoidance algorithms in TCP help avoid network congestion by gradually increasing the TCP window at the beginning of transfers until the TCP Receive Window boundary is reached, or packet loss occurs. For broadband internet connections that combine high TCP Window with higher latency (high BDP), these algorithms do not increase the TCP windows fast enough to fully utilize the bandwidth of the connection.
Compound TCP (CTCP) is a newer method, available in Vista and Server 2008 (there is also a hotfix available for XP x64 and 2003 Server — MSKB 949316). CTCP increases the TCP send window more aggressively for broadband connections (with large RWIN and BDP). CTCP attempts to maximize throughput by monitoring delay variations and packet loss. It also ensures that its behavior does not impact other TCP connections negatively.
By default, Vista and Windows 7 have CTCP turned off, it is only on by default under Server 2008. Turning this option on can significantly increase throughput and packet loss recovery.
To enable CTCP, in elevated command prompt type:
netsh int tcp set global congestionprovider=ctcp
To disable CTCP:
netsh int tcp set global congestionprovider=none
Possible options are: ctcp, none, default (restores the system default value).
Recommended setting: ctcp
It is better to use this newer generation CTCP congestion control algorithm for most broadband connections, we highly recommend it being turned on.
ECN Capability
ECN (Explicit Congestion Notification, RFC 3168) is a mechanism that provides routers with an alternate method of communicating network congestion. It is aimed to decrease retransmissions. In essence, ECN assumes that the cause of any packet loss is router congestion. It allows routers experiencing congestion to mark packets and allow clients to automatically lower their transfer rate to prevent further packet loss. Traditionally, TCP/IP networks signal congestion by dropping packets. When ECN is successfully negotiated, an ECN-aware router may set a bit in the IP header (in the DiffServ field) instead of dropping a packet in order to signal congestion. The receiver echoes the congestion indication to the sender, which must react as though a packet drop were detected.
ECN is disabled by default in Vista and other modern TCP/IP implementations, as it is possible that it may cause problems with some outdated routers that drop packets with the ECN bit set, rather than ignoring the bit. To check whether your router supports ECN, you can use the Microsoft Internet Connectivity Evaluation Tool. The results will be displayed under «Traffic Congestion Test».
To change ECN, in elevated command prompt type:
netsh int tcp set global ecncapability=default
Possible settings are: enabled, disabled, default (restores the state to the system default).
The default state is: disabled
Recommendation: enabled (only for short-lived, interactive connections and HTTP requests with routers that support it, in the presense of congestion/packet loss), disabled otherwise (for pure bulk throughput with large TCP Window, no regular congestion/packet loss, or outdated routers without ECN support).
Notes: ECN is only effective in combination with AQM (Active Queue Management) router policy. It has more noticeable effect on performance with interactive connections and HTTP requests, in the presence of router congestion/packet loss. Its effect on bulk throughput with large TCP Window are less clear.
Currently, we do not recommend enabling this setting, as reportedly it has negative impact on throughput with some residential US ISPs. EA multiplayer games that require a profile logon do not support ECN as well (you will not be able to logon). However, it can also reduce latency in some games with ECN-capable routers in the presence of packet loss (dropped packets).
More information on ECN: Explicit Congestion Notification (ECN) for TCP/IP
RSS — Receive-side Scaling
The receive-side scaling setting enables parallelized processing of received packets on multiple processors, while avoiding packet reordering. It avoids packet reordering y separating packets into «flows», and using a single processor for processing all the packets for a given flow. Packets are separated into flows by computing a hash value based on specific fields in each packet, and the resulting hash values are used to select a processor for processing the flow. This approach ensures that all packets belonging to a given TCP connection will be queued to the same processor, in the same order that they were received by the network adapter.
To set RSS:
netsh int tcp set global rss=enabled
Possible rss settings are: disabled, enabled, default (restores rss state to the system default).
Default state is: enabled
Recommended: enabled (if you have 2 or more processor cores and a NIC that can handle RSS)
In Windows Server 2008, the system default is for RSS to be enabled and to use a maximum of four CPUs. While this is usually enough, administrators can adjust the maximum number of RSS processors by setting the MaxNumRssCpus registry value in HKLM\System\CurrentControlSet\Services\NDIS\Parameters. The value type is DWORD, and if not present, the default value of four processors is assumed (do not use value greater than 32).
See also: Receive-Side Scaling Enhancements in Windows Seerver 2008
TCP Chimney Offload
TCP chimney offload enables Windows to offload all TCP processing for a connection to a network adapter. Offloads are initiated on a per-connection basis. Compared to task offload, TCP chimney offload further reduces networking-related CPU overhead, enabling better overall system performance by freeing up CPU time for other tasks.
To set TCP Chimney Offload:
netsh int tcp set global chimney=enabled
Default state: disabled (under Vista), automatic (under Windows 7 and 2008 Server)
Recommended: enabled
The possible states are disabled, enabled, default (Vista), automatic (only Windows 7 and 2008 Server) as follows:
automatic — This default setting is only available under Windows 7 and 2008 Server, it is not available udner Vista. It offloads if the connection is 10 GbE, has a RTT
default — this setting restores chimney offload to the system default. Setting this «default» state under Windows 7 and 2008 Server is possible, but it sets the system to the «automatic» mode described above.
disabled — this setting is maually configured as disabled.
enabled — this setting is manually configured as enabled.
Notes:
Under Windows 7 and Server 2008 the «default» and the additional «automatic» parameter set the system to the same «automatic» state.
For Chimney Offload to work, it needs to be enabled in both the OS and NIC. To enable the «TCP Offloading» setting in your NIC, navigate to the Device Manager, under Network Adapters, in the Advanced tab, and check «Enabled» in the box next to the TCP offload entry.
Direct Cache Access (DCA)
Windows 7 and 2008 Server (but not Vista) add NETDMA 2.0 Direct cache access support. Direct Cache Access (DCA) allows a capable I/O device, such as a network controller, to deliver data directly into a CPU cache. The objective of DCA is to reduce memory latency and the memory bandwidth requirement in high bandwidth (Gigabit) environments. DCA requires support from the I/O device, system chipset, and CPUs.
To enable DCA:
netsh int tcp set global dca=enabled
Available states are: enabled, disabled.
Default state: disabled
Recommended: enabled (provided the CPU/Chipset/NIC support it)
It is also possible to enable this setting by editing the Windows Registry instead of using netsh as follows:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
EnableDCA=1(DWORD, entry does not exist by default. Set to 1 to enable, 0 to disable)
Setting MTU
It is sometimes useful to view and set the MTU value for a specific network interface manually. To view a list of active network interfaces and their MTU values in Vista using netsh, open command prompt as administrator and execute the following command:
netsh interface ipv4 show subinterface
You will be presented with a list of interfaces, and their respective MTU values as follows:
To change the MTU value of a specific network card, type the following in command prompt:
netsh interface ipv4 set subinterface «network interface name» mtu=#### store=persistent
Where «network interface name» is your specific network adapter name as obtained above (or viewable under Network adapters), and mtu=#### is the desired MTU value.
For example, if the name of your network card is «Wireless Network Connection» and you’d like to set its MTU to 1500, you’d have to type:
netsh interface ipv4 set subinterface «Wireless Network Connection» mtu=1500 store=persistent
Note: The maximum MTU value is usually 1500, and up to 1492 for PPPoE connections.
Manually tuning Registry Parameters
Many of the registry keys tuning TCP/IP parameters from previous Windows versions no longer work in Vista and Server 2008. Below is a list of the few we’ve confirmed to still work, as well as some new additions. Note that for changes to these settings to take effect the computer needs to be rebooted. As always, a registry backup is recommended if making any changes, and some proficiency in using regedit is required.
In regedit (Start icon > Run > type: regedit while logged in as administrator), you can navigate and edit the following keys.
MTU (Maximum Transmission Unit) — the maximum packet size.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\{…}\
MTU=1500 (DWORD, entry does not exist by default)
The {….} part of the above path is the unique identifier of your network adapter. You can recognize the correct adapter by looking at it’s IP address, if obtaining IP automatically labeled by: DhcpIPAddress=192.168.x.x text value, for example.
We recommend leaving this at default, unless you want to lower it. Vista uses the largest possible packet size for the underlying network by default.
Note: In some test environments, the correct MTU entry may be offset by 8. The 8 offset seems to coincide with the size of the PPPoE overhead. Check the result with the TCP Analyzer.
SMB Large MTU (SMB 2, CIFS network shares)
SMB 2 implementation in Windows 7 and Windows Server 2008 R2 allows for using a large MTU value for very high speed/low latency Gigabit networks by enabling a new registry parameter, as follows:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
DisableLargeMtu=0 (DWORD, default: 1, to enable Large MTUs: 0)
Note that client workstations may have to enable lare SMB MTU in this hive instead:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\LanmanWorkstation\Parameters
DisableLargeMtu=0
Note: This setting should only be applicable to SMB2 shares
TCP 1323 Options
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
Tcp1323Opts=1 (DWORD, entry created automatically by Windows when you run the «netsh int tcp set global autotuninglvl=…» command, set to 0 by default).
Setting this seems to have no effect, since auto-tuning uses the TCP 1323 scale factor and changes it on the fly, disregarding this setting. Additional testing may be required to determine it’s effect if auto-tuning is turned off. Setting it to 1 is best for broadband connections.
NetDMA (TCPA)
NetDMA enables support for advanced direct memory access. In essence, it provides the ability to more efficiently move network data by minimizing CPU usage. NetDMA frees the CPU from handling memory data transfers between network card data buffers and application buffers by using a DMA engine.
Under Windows 7, NetDMA can be set directly using the netsh interface (not available under Vista):
netsh int tcp set global netdma=enabled
Under Vista/2008/7, you can set NetDMA/TCPA using the following Registry parameter:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
EnableTCPA=1 (DWORD, not in registry by default. Set to 1 to enable, 0 to disable NetDMA)
Recommended setting is 1 (if not using Chimney Offload), zero otherwise. A new DWORD value may need to be created if not already present in the registry.
For NetDMA to work, it must be enabled in BIOS, your CPU must support Intel I/O Acceleration Technology (I/OAT), and it does not work together with Chimney Offload. More info available -here-
Checksum Offloading (DisableTaskOffload)
This NDIS 5 setting allows for reducing CPU load by offloading some tasks required to maintain the TCP/IP stack to the network card. Theoretically, Widnows should automatically detect capable network hardware.
The tasks offloaded are as follows:
— TCP/IP checksum calculation — each packet sent includes a verification checksum.
— TCP/IP segmentation — also known as «TCP Large Send» where Windows sends a large amount of data to the network card, and the NIC is then responsible for dividing it according to the network MTU. Experimental feature, not enabled by default
— IPSec Encryption cyphers and message digests — provides encryption of packets at the hardware level.
To change the checksum offloading setting in the Windows Registry:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
DisableTaskOffload=0 (DWORD value, default: not set, recommended: 0=enable offload, 1=disable offload)
Also see: MS KB888750, MS KB904946, MS KB936702, MS KB942861
EnableRSS
It is possible to edit receive-side scaling (RSS) in the Windows Registry, however, we recommend using the netsh command instead.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
EnableRSS (DWORD, default: not in registry, recommended: edit using netsh)
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\NDIS\Parameters
MaxNumRssCpus (DWORD, default: not present in registry, assuming 4 CPUs, recommended: don’t edit, possible values: 1-32)
DefaultTTL
TTL can be safely left alone in many cases. It is a limit to the time and number of hops/routers a packet will travel before being discarded. A number that’s too small risks packets being discarded before reaching their destination. A number that’s too large (over 128) will cause delay in when lost IP packets are discarded.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
DefaultTTL=64 (DWORD, set to a decimal value between 32 and 128. Recommended: 64)
TcpMaxDataRetransmissions
Determines how many times unacknowledged data (non-connect segment) is retransmitted before TCP aborts the connection. The retransmission timeout is doubled with each successive retransmission on a connection. It is reset when responses resume.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
TCPMaxDataRetransmissions=5 (DWORD, recommended: between 3 and 10, not present in registry by default)
Note: When not present in the registry, the default behavior is 255 retransmissions (5 in documentation).
SynAttackProtect
This undocumented for Windows 7 setting provides protection against SYN denial of service (DoS) attacks. When enabled, connections timeout sooner if SYN attack is detected. When set at 1, TCPMaxDataRetransmissions can be lowered further.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
SynAttackProtect=1 (DWORD, recommended: 1, not present in registry by default)
Note: MSDN suggests a value of 2 for Windows 2k — http://msdn.microsoft.com/en-us/library/aa302363.aspx
EnableConnectionRateLimiting
This parameter sets (or disables) the half-open TCP connection limit in Windows 7, Vista (SP2), Server 2008, or later. Some Microsoft OSes, such as, Vista before SP2, and 2008 Server before SP2, may limit the number of half-open TCP connections to 10. Limiting the half-open (incomplete) TCP connections per second may lead to log errors which read as follows: «Event ID 4226: TCP/IP has reached the security limit imposed on the number of concurrent TCP connect attempts». It may cause P2P and other programs that open a large number of connections to be somewhat limited in ramping up their transfers. It is recommended to remove this limitation. Just check the below key and make sure it is either not present, or set to zero. Windows 7, and Windows Server 2008 SP2 or later should not have to make any changes.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
EnableConnectionRateLimiting=0 (DWORD, recommended: 0, or delete key)
Network Throttling Index (Gaming)
By default, Windows Vista/7 implements a network throttling mechanism to restrict the processing of non-multimedia network traffic to 10 packets per millisecond (a bit over 100 Mbits/second). The idea behind such throttling is that processing of network packets can be a resource-intensive task, and it may need to be throttled to give prioritized CPU access to multimedia programs. In some cases, such as Gigabit networks and some online games, for example, it may be benefitial to turn off such throttling all together.
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile
NetworkThrottlingIndex=ffffffff (DWORD, default: 10, recommended: 10 for media sharing, ffffffff for gaming and max throughput, valid range: 1 through 70 decimal or ffffffff to completely disable throttling)
It is only recommended to change this setting in saturated Gigabit LAN environments, where you do not want to give priority to multimedia playback. Reportedly, disabling throttling by using ffffffff can also help reduce ping spikes in some online games.
Notes: Setting is available in Windows 7, Vista (SP1), 2008 Server. Default value is 10 under Windows 7, similar behavior if the setting is not present in the Registry.
Games that may be affected by this throttling: Source Engine games (TF2, Left 4 Dead, CS:S), HoN, CoD, Overlord series.
Reference: MSKB 948066
SystemResponsiveness (Gaming and Multimedia playback)
In Windows 7, multimedia applications use the «Multimedia Class Scheduler service» (MMCSS) to ensure priritized access to CPU resources, without denying CPU resources to lower-priority background applications. However, this also reserves 20% of CPU by default for background processes, your multimedia streaming and some games can only utilize up to 80% of the CPU. This setting, in combination with the above «NetworkThrottlingIndex» can help some games and video streaming. We recommend reducing the reserved CPU for background processes from the default.
Navigate to:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile
SystemResponsiveness=0 (DWORD, default is 20 denoting 20% of CPU reserved, recommended: decimal 10, or 0 for pure multimedia/gaming performance)
Notes: The number in this key is rounded by the MMCSS to the nearest 10. Under Windows 2008/2012 Server, SystemResponsiveness is set to 100 by default, denoting that background processes take priority over multimedia applications.
See also: MSDN ms684247
Set DNS and Hosts Priority
As with previous versions of Windows, one can improve DNS and hostname resolution by increasing the priority of of related services, while keeping their order. This is explained in more defail in our Host Resolution article. Lower numbers mean higher process priority. The corresponding registry settings in Vista are as follows:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\ServiceProvider
LocalPriority=4 (DWORD, recommended: 4, default: 499) — local names cache
HostsPriority=5 (DWORD, recommended: 5, default: 500) — the HOSTS file
DnsPriority=6 (DWORD, recommended: 6, default: 2000) — DNS
NetbtPriority=7 (DWORD, recommended: 7, default: 2001) — NetBT name resolution, including WINS
TcpTimedWaitDelay (port allocation)
Short lived (ephemeral) TCP/IP ports above 1024 are allocated as needed by the OS. The default Vista values have improved from previous Windows versions, and are usually sufficient under normal load. However, in some instances under heavy load it it may be necessary to adjust the settings below to tweak the availability of user ports requested by an application.
If the default limits are exceeded under heavy loads, the following error may be observed: «address in use: connect exception». By default under Vista (when the values are not presend in the registry), the OS can allocate up to 16384 ephemeral ports above port 1024, and the OS waits for 120 seconds before reclaiming ports after an application closes the TCP connection. This is a considerable improvement over older Windows versions. However, if necessary, the following registry values can be added/edited:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
MaxUserPort=65534 (DWORD, not in the registry by default. Recommended: leave at default, or use a number above 16384 up to 65534 decimal as necessary) — maximum number of ports to use. 1024 is automatically subtracted from entered value to allow for reserved ports under 1024.
TcpTimedWaitDelay=30 (DWORD, not present or 0xffffffff in registry by default. Recommended: 30 decimal, denoting 30 seconds) — time to wait before reclaiming ports, in seconds. Default time before reclaiming ports, if value is at 0xffffffff or not present in the registry is 120 seconds. Just reducing the delay is often sufficient without changing MaxUserPort, as it allows for reusing ports more efficiently.
Ephemeral ports can be checked and changed using netsh as well.
To query the current values, in command prompt, type:
netsh int ipv4 show dynamicportrange tcp (for UDP, use the same command, replacing only «tcp» with «udp» at the end)
To set both the starting, and max user port using netsh, in elevated command prompt run:
netsh int ipv4 set dynamicportrange protocol=tcp start=1025 num=64511 (start=NNN denoting the starting port, and num=NNN denoting the number of ports)
Notes:
By default, dynamic ports are allocated between ports 49152 and 65535 (for a total of 16384 ephemeral ports).
Using netsh allows to set both the starting port and port range. Editing the Registry allows for setting the port range, and the starting port is fixed at 1025. Deleting the MaxUserPort registry entry (or setting it to a value outside the allowed range) causes the OS to revert to using the default values.
Some system processes can install port filters to block certain port ranges. If ephemeral ports run into these filtered port ranges, TCP/IP applications will be unable to bind to any ports.
See also: TechNet article, MSKB 328476, MSKB 319502
MaxFreeTcbs and MaxHashTableSize
MaxFreeTcbs determines the number of TCP Control Blocks (TCBs) the system creates to support active connections. Each connection requires such control block, so this value determines how many active connections TCP can support simultaneously. Normally, TCP does not release a connection or reuse its resources until the connection has remained closed for a period of time (specified by the value of the TcpTimedWaitDelay entry). This interval is known as the TIME_WAIT state. The default value for this entry is determined both by the amount of physical memory on the computer when TCP/IP starts and by the Windows version. We recommend increasing it from the default if using network intensive applications that open many simultaneous connections, such as P2P.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
MaxFreeTcbs=65535 (dword, not present in registry by default, recommended 65535 decimal)
MaxHashTableSize specifies the size of the hash table in which TCP Control Blocks (TCBs) are stored. TCP stores control blocks in a hash table so it can find them very quickly. If you adjust the number of TCBs the system creates (as specified by the value of MaxFreeTcbs), you should also adjust the value of the hash table proportionally.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
MaxHashTableSize=65535 (dword, not present in registry by default, recommended 65535 decimal)
Note: The need for larger MaxFreeTcbs and MaxHashTableSize values is directly related to the value of TcpTimedWaitDelay because a large TcpTimedWaitDelay increases the number of ports that remain in WAIT states before being released.
QoS Reserved Bandwidth
As with Windows XP, nework adapters have a «QoS Packet Scheduler» enabled by default, which reserves 20% of bandwidth by default for QoS applications that request priority traffic. Note this only has effect in the presence of running QoS applications that request priority traffic. Registry value is undocumented for the Vista version of Windows. To customize this setting, in the Windows Registry:
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\Psched
NonBestEffortLimit=0 (DWORD, not present in the registry by default. Recommended: 0 , possible values between 0 and 100) — indicates the percentage value of reserved bandwidth for QoS applications. Set to 0 to disable.
Notes: This tweak applies only to Windows versions that have Qos Packet Scheduler enabled. It will ONLY have effect in the presense of running QoS applications.
QoS Policy
QoS Policy settings under Windows 7 can be edited using the Group Policy Editor (gpedit.msc): Computer Configuration -> Windows Settings -> Policy-based QoS
In order to define DiffServ (DSCP) values, according to Microsoft the machine needs to have joined a domain, and interfaces have to see the domain controller. To overcome this limitation, so that you can tag DSCP values even for adapters that do not have access to a domain, use the following hidden registry key:
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Tcpip\QoS (you may have to create the QoS key)
«Do not use NLA»=»1» (REG_SZ string value, not DWORD, not present by default, recommended: 1 if you plan to edit Diffserv values via gpedit.msc)
Notes:
gpedit.msc is only provided with the Professional/Ultimate and Server Windows variants, it is not included in Starter/Home editions.
This registry key may also be needed in systems with multiple network adapters present.
Network Memory Allocation (Event ID 2017 error)
When using Windows Vista/7 to serve many/large files over the local network, it is possible to sometimes run into memory allocation errors related to the Windows share. This can happen with Linux, Mac, or Windows XP clients. When this happens, you can usually see the following error in the Event Viewer System log:
Source: srv
Event ID: 2017
Level: Error
The server was unable to allocate from the system nonpaged pool because the server reached the configured limit for nonpaged pool allocations.
It is also possible to get an error indicating that: «Not enough server storage is available to process this command». To avoid those errors, you need to change the way Windows allocates memory for network services and file sharing. The below settings optimze the machine as a file server so it would allocate resources accordingly. There are two related registry settings:
HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management
LargeSystemCache=1 (DWORD, default value: 0, recommended value: 1)
A value of zero above establishes a cache of ~8 MB, a value of 1 allows the cache to expand to physical memory minus 4 MB, if needed.
HKLM\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters
Size=3 (DWORD, default value: 1, recommended value: 3)
Size=1 minimizes used memory
Size=2 balance used memory
Size=3 optimal setting for file sharing and network applications
Note: Even though this tweak is from older Windows server OSes, it works on workstation versions, as well as Windows Vista and 7 (32 and 64 bit).
Gaming Tweak — Disable Nagle’s algorithm
The tweak below allows for tweaking or disabling Nagle’s alogrithm. Disabling «nagling» allows for very small packets to be transferred immediately without delay. Note that disabling Nagle’s algorithm is only recommended for some games, and it may have negative impact on file transfers/throughput. The dafault state (Nagling enabled) improves performance by allowing several small packets to be combined together into a single, larger packet for more efficient transmission. While this improves overall performance and reduces TCP/IP overhead, it may briefly delay transmission of smaller packets. Keep in mind that disabling Nagle’s algorithm may have some negative effect on file transfers, and can only help reduce delay in some games. To implement this tweak, in the registry editor (Start>Run>regedit) find:
This setting configures the maximum number of outstanding ACKs in Windows XP/2003/Vista/2008:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\{NIC-id}
There will be multiple NIC interfaces listed there, for example: {1660430C-B14A-4AC2-8F83-B653E83E8297}. Find the correct one with your IP address listed. Under this {NIC-id} key, create a new DWORD value:
TcpAckFrequency=1 (DWORD value, 1=disable, 2=default, 2-n=send ACKs if outstanding ACKs before timed interval. Setting not present by default).
For gaming performance, recommended is 1 (disable). For pure throughput and data streaming, you can experiment with values over 2. If you try larger values, just make sure TcpAckFrequency*MTU is less than RWIN, since the sender may stop sending data if RWIN fills witout acknowledgement. Wifi performance may see a slight improvement with disabled TcpAckFrequency as well.
In the same location, add:
TCPNoDelay=1 (DWORD, not present by default, 0 to enable Nagle’s algorithm, 1 to disable)
For Server Operating Systems that have Microsoft Message Queuing (MSMQ) installed, or if you have the MSMQ registry hive present, also add TCPNoDelay to:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSMQ\Parameters
TCPNoDelay=1 (DWORD, not present by default, 0 to enable Nagle’s algorithm, 1 to disable)
To configure the ACK interval timeout (only has effect if nagling is enabled), find the following key:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\{NIC-id}
TcpDelAckTicks=0 (DWORD value, not present by default interpreted as 2, 0=disable nagling, 1-6=100-600 ms). Note you can also set this to 1 to reduce the nagle effect from the default of 200ms without disabling it.
Notes:
Reportedly, the above gaming tweak (disabling nagle’s algorithm) can reduce many MMOs like Diablo and WoW (World of Warcraft) latency by almost half!
XP/2003 needs hotfix or SP2 for it to work (MS KB 815230)
Vista needs hotfix or SP1 for it to work (MS KB 935458)
See also: NetworkThrottlingIndex setting above
SG TCP Optimizer (version 3.x)
The TCP Optimizer version 3.x allows for easy application of the above settings under all current Windows versions. This free software provides an intuitive interface for tuning your internet connection, backing up/restoring to the Windows defaults, etc. There is no installation required, you can just save it to the desktop, right-click > run as administrator and choose your settings. More detailed information about all available options is provided in the online documentation, answers to frequently asked questions are available in the Optimizer FAQ, and personalized help is available through our broadband tweaking forum.
SG TCP Optimizer download
For user convenience, we also provide a quick way to apply all optimal values as recommended above using our SG Vista TCP/IP Patch. It allows for tweaking all the above netsh settings and registry values in one simple step (with the exception of the «gaming tweak» section). The patch also provides for easily reverting the settings to their Windows default values. To apply, save to your desktop and run as administrator (right-click -> run as administrator). Click Y when prompted to apply settings.
Note: If for some reason Windows renames the file and adds .txt extension to it, you may have to manually rename it back to have a .cmd (or .bat) extension before running it as administrator.
See Also
Windows Vista tcpip.sys connection limit patch for Event ID 4226 — removing the limit on half-open TCP connections.
Windows 8, 10, 2012 Server TCP/IP Tweaks — updated tweaks for Windows 8, 8.1, 10, Server 2012 and 2012 R2.
Wireless Network Speed Tweaks and Network Adapter Optimization.
References
Windows Server 2008 Network Shell (Netsh) Technical Reference
Microsoft KB951037
RFC 2581
Wikipedia: Nagle’s algorithm
Technet: TCPNoDelay
Technet: LargeSystemCache
MS KB 311833
MS KB 328890
MS KB 321098
MS KB 321169
MS KB 951037 — TCP Chimney Offload, Receive Side Scaling, and Network DMA in Windows Server 2008
To speed up the internet using cmd, we’d have to use some of its built-in tricks. Some of these tweaks and tricks include dealing with DNS cache, pinging to the default gateway, and using ‘netsh int tcp’ command alongside certain parameters to increase the internet speed.
There are times when we are stuck with a slow internet connection and don’t really know what to do next. In most of these cases, the most we do is restart our device or the router and then check for an improved internet speed.
If that does not work, we usually reach out to our ISP. And, if the slow internet speed still persists after that, people end up changing their ISP. So, to help you possibly avoid all that fuss, here are some tips and tricks for speeding up your internet using cmd.
Many of us don’t realize that there are several built-in useful windows commands and tools that can resolve the most common issues, such as slow internet. To execute with these cmd tricks, you don’t necessarily have to be a pro but just do what’s mentioned in the steps.
1. Check internet speed using cmd pings to default gateway
You can check your internet connection speed by sending ping packets to your default gateway. To know your default gateway, you can use ipconfig /all command. Once you get the IP address of your default gateway, start running a continuous ping by typing ping -t <your default gateway address>. The time field value will show you the time taken to get an acknowledgment from the gateway.
A lower time value is an indication that your network is faster. However, running a lot of pings consumes network bandwidth as well as your default gateway resources. Though the data packets for ping are very negligible in size and you might not observe any change in internet speed but it does consume bandwidth.
Moreover, if you are interested in learning how to DDoS an IP using command prompt here!
2. IP release and renew
If you are using a WiFi connection, you may experience a temporary speed boost by typing in ipconfig /release and ipconfig /renew. However, in the case of LAN, this command won’t affect speed.
3. Flushdns
Our computer maintains a list of the websites and their corresponding IP addresses that we access the most in the DNS resolver cache. Sometimes, this data becomes obsolete after weeks or months. When we flush our DNS resolver cache using ipconfig /flushdns command, we actually flush out the obsolete data and make new entries in the DNS resolver cache table.
Using this command, you might initially experience a slower connection because of the requirement of the new DNS lookups for every resource. However, you will soon experience faster loading of the websites in your browser. Also, check out the list of useful commands that you might not know.
4. Speed up internet using cmd ‘Netsh int tcp’ command:
Type this command in your command prompt window and observe carefully:
If you do not see Receive Window Autotuning level as ‘Normal’ as shown above then run the following command:
- netsh int tcp set global autotuninglevel=normal
This command will set your TCP receive window to Normal from the disabled or restricted state. The TCP receive window is one of the key factors in the internet download speed. Thus making the TCP receive window to ‘Normal’ will surely help you in increasing your internet speed.
After this command, let’s check for another parameter of Windows in terms of the slow internet connection called ‘Windows scaling heuristics’. To check for this parameter, type
- netsh interface tcp show heuristics
Well, in my case, it’s disabled. However, in some other cases, it might be enabled. That means Microsoft in some ways, is trying to limit your internet connection. To bypass this and get unrestricted internet, type the command below and press enter:
- netsh interface tcp set heuristics disabled
Once you press enter, you will see an ‘OK’ message confirming that your internet speed successfully received a boost.
After you are done with the aforementioned steps, you can follow Step 1 again to measure the time value in getting a ping acknowledgment from the default gateway and check if your internet speed has truly gone up or not.
Boost streaming speed by disabling throttling
If you enjoy good speeds generally but are struggling to get the same experience during streaming, your ISP might be the reason. Some ISPs throttle speeds for certain kind of content. To overcome this, you’ll need to add a firewall rule. Just type the following command in cmd and hit enter:
netsh advfirewall firewall add rule name="StopThrottling" dir=in action=block remoteip=173.194.55.0/24,206.111.0.0/16 enable=yes
Conclusion
The cmd tricks mentioned above are some built-in quick fixes that you can use to make the most of your internet connection. Executing these commands is the first self-help routine you should follow whenever your internet hits a snag.
If you know any other Windows tweaks to get the best download speeds or some handy cmd commands, let us know in the comments below.
FAQs
1. What is the netsh command to fix the internet?
Netsh is a cmd tool in Windows computers that can be used to tweak the network configuration. A popular command to rest the TCP/IP configuration is: netsh int ip reset
2. Which cmd tool can I use to test Internet speed?
You can use Python-based speedtest-cli on Windows to test your internet speed. After installing Python, run this command to install: pip install speedtest-cli
3. Why are some internet connections fast and some connections slow?
Internet speed that you get is the result of multiple factors such as your router, quality of cables, signal strength, device modem, and finally your ISP. With all these factors into account, the internet speed is bound to vary.
4. Does flushing DNS speed up the internet?
It doesn’t directly affect your internet, but it speeds up certain websites that might not have been working optimally before.
5. How do I run a speed test from the command line?
The simplest way to run a speed test is to ping any site you want to access. For instance, type “ping google.com” in Command Prompt and hit enter. The results will show stats related to your internet speed.
The command netsh interface tcp is used in the Windows Command Prompt (cmd) or PowerShell to enter a specific context within the netsh (Network Shell) utility.
The netsh interface tcp command in Windows is used to configure TCP settings for network interfaces. It allows you to view or modify TCP parameters, such as congestion control, window scaling, and other performance-related settings.
Enters the TCP/IP Interface Context: Running netsh interface tcp by itself doesn’t perform an action like showing or changing settings. Instead, it changes the prompt within netsh to netsh interface tcp>, indicating you are now focused on commands related to the TCP protocol settings for network interfaces.
Here are some common subcommands and their uses:
- show global:
- Purpose: Displays the main, system-wide TCP configuration parameters.
- Example: netsh interface tcp show global
- Output includes settings like Receive Window Auto-Tuning Level, Congestion Control Provider, and ECN Capability.
- show heuristics:
- Purpose: Shows the status of Windows TCP heuristics.
- Details: Heuristics are adaptive behaviors. This command typically shows whether Window Scaling heuristics are enabled, which allows Windows to automatically adjust TCP window scaling based on network conditions, potentially disabling it if it detects problematic network devices that don’t support scaling correctly.
- Example: netsh interface tcp show heuristics
- set global: Modifies global TCP settings.
- Example: netsh interface tcp set global autotuninglevel=normal
- Options for autotuninglevel: disabled, highlyrestricted, restricted, normal, experimental.
- show rscstats:
- Purpose: Displays statistics related to Receive Segment Coalescing (RSC).
- Details: RSC is a feature where the network adapter combines multiple received TCP segments into a single larger segment before passing it up the network stack, reducing CPU overhead. This command shows statistics like the number of packets coalesced and saved, but only for network interfaces that support and have RSC enabled.
- show security:
- Purpose: Displays TCP parameters related to security.
- Details: This might show settings configured to mitigate certain types of network attacks, such as SYN flood attacks (e.g., related to SYN Attack Protection features). The specific parameters shown can vary depending on the Windows version.
- show supplemental:
- Purpose: Shows parameters related to supplemental TCP templates.
- Details: Windows allows defining custom TCP settings (like specific congestion control algorithms, initial RTO, etc.) through templates. These templates can then be applied to specific traffic based on ports or subnets (using the Transport Filter Platform). This command displays the parameters configured in these supplemental templates.
- Example: netsh interface tcp show supplemental
- show supplementalports:
- Purpose: Lists the port ranges defined in the TCP supplemental filter table.
- Details: This command shows which specific source or destination TCP port numbers (or ranges) will trigger the use of the supplemental TCP settings defined via
show supplemental.
- show supplementalsubnets:
- Purpose: Lists the destination IP subnets defined in the TCP supplemental filter table.
- Details: Similar to
show supplementalports, this command shows which destination IP address subnets will trigger the use of the supplemental TCP settings.
- set supplemental: Configures supplemental TCP settings.
- Example: netsh interface tcp set supplemental template=internet
- set heuristics: Enables or disables TCP heuristics.
- Example: netsh interface tcp set heuristics disabled
Shows the current configuration of global TCP parameters
netsh interface tcp show global command displays the current configuration of global TCP parameters, which affect how TCP connections are handled across the system.
TCP Global Parameters Explained
- Receive-Side Scaling State:
- Determines whether Receive-Side Scaling (RSS) is enabled, which allows incoming packets to be distributed across multiple CPU cores for better performance.
- Typical values: enabled or disabled.
- Example: enabled improves performance on multi-core systems.
- Receive Window Auto-Tuning Level:
- Controls how Windows automatically adjusts the TCP receive window size to optimize throughput.
- Possible values: disabled, highlyrestricted, restricted, normal, experimental.
- Example: normal is the default and works well for most scenarios; experimental may increase throughput but can cause compatibility issues.
- Add-On Congestion Control Provider:
- Specifies the TCP congestion control algorithm used to manage network congestion.
- Common values: none, ctcp (Compound TCP), dctcp (Data Center TCP), or default.
- Example: ctcp can improve throughput on high-latency networks.
- ECN Capability:
- Indicates whether Explicit Congestion Notification (ECN) is enabled, allowing routers to signal congestion without dropping packets.
- Values: enabled or disabled.
- Example: enabled can reduce packet loss but requires network support.
- RFC 1323 Timestamps:
- Controls whether TCP timestamps (per RFC 1323) are enabled to improve round-trip time (RTT) measurements and protect against wrapped sequence numbers.
- Values: enabled or disabled.
- Example: enabled is recommended for modern networks.
- Initial RTO:
- Sets the initial Retransmission Timeout (RTO) value in milliseconds, which determines how long TCP waits before retransmitting a packet.
- Example: 1000 (1 second) is a common default.
- Receive Segment Coalescing State:
- Indicates whether Receive Segment Coalescing (RSC) is enabled, which combines multiple TCP segments into fewer larger ones to reduce CPU overhead.
- Values: enabled or disabled.
- Example: enabled improves performance for high-throughput networks.
- Non Sack Rtt Resiliency:
- Controls whether TCP connections without Selective Acknowledgments (SACK) are resilient to variations in round-trip time.
- Values: enabled or disabled.
- Example: disabled is typical unless specific network conditions require it.
- Max SYN Retransmissions:
- Specifies the maximum number of times a TCP SYN (synchronize) packet is retransmitted before giving up on establishing a connection.
- Example: 2 or 3 is common.
- Fast Open:
- Indicates whether TCP Fast Open is enabled, allowing data to be sent in the initial SYN packet to reduce connection latency.
- Values: enabled or disabled.
- Example: enabled can improve performance for short-lived connections.
- Fast Open Fallback:
- Determines whether TCP falls back to standard connection setup if Fast Open fails.
- Values: enabled or disabled.
- Example: enabled ensures compatibility.
- HyStart:
- Controls whether the Hybrid Start algorithm is used to optimize the TCP slow-start phase, reducing packet loss.
- Values: enabled or disabled.
- Example: enabled is typical for better performance.
- Proportional Rate Reduction:
- Indicates whether Proportional Rate Reduction (PRR) is used during TCP recovery to smoothly adjust the sending rate after packet loss.
- Values: enabled or disabled.
- Example: enabled is recommended for modern networks.
- Pacing Profile:
- Specifies the TCP pacing profile, which controls how packets are spaced out to avoid bursts that could cause congestion.
- Values: off, standard, or others depending on the system.
- Example: standard helps smooth out traffic.
Displays the current configuration of TCP Window Scaling heuristics
The netsh interface tcp show heuristics command in Windows displays the configuration of TCP Window Scaling heuristics, which are algorithms used by the system to dynamically adjust the TCP receive window size based on network conditions and connection profiles. These heuristics help optimize network performance by balancing throughput and compatibility.
TCP Window Scaling Heuristics Parameters Explained
- Window Scaling Heuristics:
- Purpose: Indicates whether TCP Window Scaling heuristics are turned on or off.
- Typical Values: enabled or disabled.
- Meaning:
- enabled: Windows automatically adjusts the TCP receive window size to improve performance based on network conditions.
- disabled: No dynamic adjustments are made, which might be set for troubleshooting or specific network needs.
- Example: enabled allows adaptive scaling; disabled may be used for troubleshooting or specific network requirements.
- Qualifying Destination Threshold:
- Purpose: Specifies the number of connections to a destination that must occur before Windows applies heuristics to adjust the TCP window.
- Typical Value: A number like 3.
- Meaning: For example, if set to 3, Windows waits until it observes three connections to the same destination before enabling dynamic adjustments. This prevents unnecessary changes for rarely accessed destinations.
- Profile Type Unknown:
- Indicates the Window Scaling heuristics setting for network connections with an unknown profile (e.g., unidentified networks).
- This setting applies when the network connection’s profile cannot be determined. The possible values are:
- normal: Window scaling behaves normally.
- restricted: Window scaling is more conservative, limiting growth in some scenarios.
- highlyrestricted: Window scaling is very conservative.
- disabled: Window scaling is disabled for this profile type.
- Profile Type Public:
- Specifies the Window Scaling heuristics setting for public network profiles (e.g., Wi-Fi hotspots).
- This setting applies when the network connection is identified as a public network (e.g., in a coffee shop or airport). Public networks often have unpredictable characteristics, so Windows might use more restrictive heuristics. The possible values are the same as for “Profile type unknown.”
- Profile Type Private:
- This setting applies when the network connection is identified as a private network (e.g., your home or a trusted local network). Windows might be less restrictive with window scaling on private networks. The possible values are the same as above.
- Profile Type Domain:
- This setting applies when the computer is connected to a domain network (typically in a corporate environment). Domain networks are usually more controlled and predictable. The possible values are the same as the other profile types.
Additional Notes
- Checking Your Settings:
- Open Command Prompt as Administrator and type netsh interface tcp show heuristics to view your system’s configuration.
- Modifying Settings:
- You can change the global heuristics state with:
- Disable: netsh interface tcp set heuristics disabled
- Enable: netsh interface tcp set heuristics enabled
Note: Profile-specific settings (e.g., Profile type public) are managed by Windows based on the global state and cannot be directly set via netsh.
- You can change the global heuristics state with:
Displays Receive Segment Coalescing (RSC) statistics for TCP connections
The netsh interface tcp show rscstats [[interface=]<string>] command in Windows displays Receive Segment Coalescing (RSC) statistics for TCP connections, either for a specific network interface or as a summary across all RSC-capable interfaces. RSC is a feature that allows network adapters to combine multiple TCP segments into fewer, larger segments, reducing CPU overhead and improving performance for high-throughput network tasks.
Since your query asks for this specific command, I’ll explain the expected output, what each statistic means, and how to interpret it. Note that the actual output depends on your system’s network activity and whether RSC is supported and enabled on your network adapter.
Command Syntax
- netsh interface tcp show rscstats [[interface=]]
- interface=<string>: The name or index of a network interface (e.g., “Ethernet”, “Wi-Fi”, or an index like “12”).
- Use netsh interface show interface to list available interfaces and their names or indices.
- If interface=<string> is specified, detailed RSC statistics are shown for the named interface (e.g., “Ethernet” or its index).
- If omitted, summary statistics are displayed for all RSC-capable interfaces.
1. Without interface Parameter (Summary Statistics)
When you run netsh interface tcp show rscstats without specifying an interface, it provides a summary of RSC statistics across all RSC-capable interfaces.
2. With interface Parameter (Detailed Statistics)
When you specify an interface (e.g., netsh interface tcp show rscstats interface=”16″), the command provides detailed RSC statistics for that specific interface with Interface index 16.
Output Parameters Explained
When you run the command with a specific interface, it returns detailed statistics. Here’s what each parameter means:
- Interface Index
- The unique numeric identifier assigned to the network interface.
- Example: 12 (could correspond to “Ethernet”).
- Supports IPv4 RSC
- Indicates whether the network adapter and its driver support Receive Segment Coalescing for IPv4 traffic.
- Possible Values: Yes (supported) or No (not supported).
- Supports IPv6 RSC
- Indicates whether the network adapter and its driver support Receive Segment Coalescing for IPv6 traffic.
- Possible Values: Yes or No.
- Current IPv4 RSC State
- Shows whether RSC is currently active for IPv4 on this interface.
- Possible Values: Enabled (RSC is on), Disabled (RSC is off), or Not Supported (adapter doesn’t support it).
- Current IPv6 RSC State
- Shows the current RSC state for IPv6 on this interface.
- Possible Values: Enabled, Disabled, or Not Supported.
- Number of TCP connections under RSC
- This counter shows the number of active TCP connections for which RSC is currently being applied on this interface.
- Example: 5 (five connections are benefiting from RSC).
- Total number of SCUs indicated
- The total number of Segment Coalescing Units (SCUs) reported by the adapter. An SCU is a single coalesced packet created from multiple smaller packets.
- Example: 1000 SCUs.
- Total size of all indicated SCUs
- The total size (in bytes) of all SCUs processed by the adapter.
- Example: 1500000 bytes.
- Total number of Coalesced Packets
- The total number of individual packets that have been combined into SCUs.
- Example: 5000 packets.
- Total number of Coalesced Bytes
- The total size (in bytes) of all packets that were coalesced.
- Example: 7500000 bytes.
- Total number of Coalesce Events
- The total number of times the adapter performed coalescing (i.e., grouped packets into an SCU).
- Example: 1000 events.
- Total number of Aborts
- The number of times RSC coalescing was interrupted or failed (e.g., due to incompatible packets or errors).
- Example: 10 aborts.
- Reason last attempt to enable V4 RSC failed
- If an attempt to enable RSC for IPv4 failed, this explains why.
- Example: No failure (successful) or Hardware not supported (adapter limitation).
- Reason last attempt to enable V6 RSC failed
- If an attempt to enable RSC for IPv6 failed, this provides the reason.
- Example: No failure or a specific error message.
Additional Notes
Requirements: RSC depends on hardware support in your network adapter. Check your adapter’s documentation or properties in Device Manager to confirm compatibility.
Administrator Access: Run the command in an elevated Command Prompt (as Administrator).
Reset Behavior: Statistics reset when the system reboots or RSC is toggled off and on.
Related Commands:
- Check global RSC settings: netsh interface tcp show global
- Enable/disable RSC: netsh interface tcp set global rsc=enabled or rsc=disabled
Receive Segment Coalescing (RSC) for TCP Connections
Receive Segment Coalescing (RSC) is a network optimization feature designed to enhance the performance of TCP connections by reducing the processing overhead on the CPU. It achieves this by combining multiple incoming TCP segments into a single larger segment before they are passed to the operating system’s TCP/IP stack. This process is particularly beneficial in high-throughput scenarios, such as large file transfers, streaming, or data center operations.
How RSC Works
RSC can be implemented either in the network interface card (NIC) or the operating system’s network stack. When enabled, it monitors incoming TCP segments that belong to the same connection. If multiple segments arrive in quick succession, RSC coalesces them into a single larger unit, often called a Segment Coalescing Unit (SCU). This reduces the number of individual packets that the CPU must process. For example, instead of handling 10 small packets separately, RSC might combine them into 2 larger packets, decreasing the overhead from packet headers and CPU interrupts.
Benefits of RSC
- Reduced CPU Utilization: By processing fewer packets, RSC lowers the CPU resources required for network operations, making it valuable in environments with heavy network traffic.
- Improved Throughput: The reduction in overhead can boost overall network performance, especially for bulk data transfers.
- Potential Latency Reduction: While RSC introduces a slight delay to coalesce segments, the decreased processing time can lead to lower overall latency for large data streams.
Potential Downsides
- Larger Impact of Packet Loss: If a coalesced segment is lost or corrupted, it affects a bigger chunk of data, which may result in more retransmissions.
- Unsuitable for Real-Time Applications: Applications like gaming or VoIP, which prioritize low latency and immediate packet delivery, may experience issues due to the coalescing delay.
- Hardware Dependency: RSC requires support from the network adapter, so it may not be available on older or less capable hardware.
Managing RSC in Windows
In Windows, you can manage RSC through the netsh command-line tool or the network adapter’s properties in Device Manager. Here are some useful commands:
- Check RSC Status: netsh interface tcp show global
- Look for the “Receive Segment Coalescing State” (e.g., enabled or disabled).
- Enable RSC: netsh interface tcp set global rsc=enabled
- Disable RSC: netsh interface tcp set global rsc=disabled
Understanding Segment Coalescing Units (SCUs)
Segment Coalescing Units (SCUs) are a key component of Receive Segment Coalescing (RSC), a network optimization feature supported by certain network adapters. RSC enables the network adapter to combine multiple incoming TCP segments into fewer, larger segments before passing them to the operating system’s TCP stack. This process reduces the CPU overhead associated with handling a large number of small packets, making it particularly valuable in high-throughput network scenarios like file transfers, streaming, or data center operations.
What Are SCUs?
- Definition: An SCU is a single coalesced packet created by the network adapter by merging multiple smaller TCP segments into one larger segment.
- Purpose: The creation of SCUs reduces the number of individual packets the CPU needs to process, improving network performance by lowering the processing load.
For example, instead of the CPU handling 5,000 small packets individually, the network adapter might combine them into 1,000 SCUs, cutting the CPU’s workload by 80%.
How SCUs Work in RSC
- Packet Reception: The network adapter receives multiple small TCP segments from the network.
- Coalescing: If RSC is enabled and supported, the adapter groups these segments into larger SCUs.
- Delivery: Each SCU is delivered to the TCP stack as a single unit, reducing CPU interrupts and processing cycles.
- Result: Fewer, larger packets mean more efficient data processing, especially for high-bandwidth tasks.
Why SCUs Matter
- Performance Boost: A high SCU count relative to total packets indicates RSC is effectively reducing CPU workload, ideal for high-throughput environments.
- Use Case Dependency: While beneficial for large data transfers, SCUs might introduce latency in real-time applications (e.g., gaming or VoIP), where immediate packet processing is critical. In such cases, disabling RSC could be better.
Displays the TCP/IP security settings related to TCP connections
The netsh interface tcp show security command you ran displays the TCP/IP security settings related to TCP connections on your Windows system.
1. Memory Pressure Protection (MPP)
- Definition: Memory Pressure Protection is a security feature in Windows that helps protect the TCP stack from resource exhaustion attacks, such as SYN flood attacks. It dynamically manages TCP connection resources when the system is under memory pressure, prioritizing legitimate connections and mitigating denial-of-service (DoS) risks.
- Status: enabled
- Meaning: MPP is active on your system. When the TCP stack detects high memory usage or potential attack patterns (e.g., excessive half-open connections), it will take protective actions, such as dropping suspicious connections or limiting resource allocation.
- Implications: This is a good default setting for security, especially on systems exposed to public networks. However, in rare cases, it might interfere with high-connection-volume applications (e.g., servers handling thousands of simultaneous connections).
2. Profiles
- Definition: In this context, “Profiles” refers to the configuration of network security profiles that apply TCP security settings based on the network type (e.g., public, private, domain). These profiles can influence how TCP connections are handled, including firewall rules and other security policies.
- Status: enabled
- Meaning: Security profiles are active, meaning Windows is applying TCP-related security settings tailored to the network profile of each interface (e.g., stricter rules for public networks vs. more permissive rules for domain networks).
- Implications: This ensures that TCP traffic is managed according to the security requirements of the network environment, enhancing protection on untrusted networks.
Display TCP Supplemental Parameters
The netsh interface tcp show supplemental command in Windows displays the supplemental TCP parameters that fine-tune the behavior of TCP connections. These parameters control advanced aspects of TCP performance, such as congestion control, retransmission timeouts, and loss recovery mechanisms. They are particularly relevant for optimizing network performance in specific scenarios, like high-latency networks, data centers, or environments with packet loss.
TCP Supplemental Parameters Explained
- Minimum RTO (msec)
- Description: The minimum Retransmission Timeout (RTO) in milliseconds. This is the minimum amount of time (in milliseconds) that TCP will wait for an acknowledgment (ACK) after sending a segment before retransmitting that segment.
- Typical Value: 300 (0.3 seconds) or lower (e.g., 200 in modern systems).
- Significance: A lower value reduces latency for retransmissions but may increase unnecessary retransmissions in high-latency networks.
- Initial Congestion Window (MSS)
- Description: The initial size of the TCP congestion window, measured in Maximum Segment Size (MSS) units. The Initial Congestion Window (ICW) determines the maximum number of TCP segments (in units of Maximum Segment Size, or MSS) that can be sent initially before receiving any acknowledgments.
- Typical Value: 10 (modern default, per RFC 6928) or 4 (older systems).
- Significance: A larger initial window (e.g., 10) improves performance for short-lived connections by allowing more data to be sent initially, but it risks congestion on low-bandwidth networks.
- Congestion Control Provider
- Description: The algorithm used to manage TCP congestion, controlling how the sender adjusts the data rate in response to network conditions.
- Typical Values: default, ctcp (Compound TCP), dctcp (Data Center TCP), or cubic (on some systems).
- Significance:
- ctcp: Optimizes for high-latency, high-bandwidth networks.
- dctcp: Designed for data centers with low latency and high bandwidth.
- default: Uses the system’s standard algorithm (often NewReno or a variant).
- Enable Congestion Window Restart
- Description: Indicates whether the TCP congestion window is reset after an idle period, restarting the slow-start phase.
- Typical Values: enabled or disabled.
- Significance:
- Enabled: Ensures conservative behavior after idle periods, reducing the risk of congestion.
- Disabled: Maintains the congestion window, which can improve performance for applications with intermittent traffic but risks overwhelming the network.
- Delayed ACK Timeout (msec)
- Description: The time TCP waits before sending an acknowledgment (ACK) for received data, allowing multiple segments to be acknowledged together.
- Typical Value: 200 (0.2 seconds) or lower.
- Significance: A shorter timeout reduces latency but increases ACK packet overhead; a longer timeout saves bandwidth but may delay data flow.
- Delayed ACK Frequency
- Description: The number of segments received before sending an ACK, if the delayed ACK timer hasn’t expired. A value of 2 means that an ACK will be sent for approximately every other received data segment (unless the delayed ACK timeout expires sooner).
- Typical Value: 2 (ACK sent after every two segments).
- Significance: Higher values reduce ACK overhead but may delay sender’s data transmission if segments arrive slowly.
- Enable RACK
- Description: Indicates whether Recent Acknowledgment (RACK) is enabled. RACK is a loss detection algorithm that uses the time packets were sent and received to identify losses more accurately than traditional methods.
- Typical Values: enabled or disabled.
- Significance:
- Enabled: Improves recovery from packet loss, especially in networks with reordering or high latency.
- Disabled: Falls back to older loss detection (e.g., duplicate ACKs), which may be less efficient.
- Enable Tail Loss Probe
- Description: Indicates whether Tail Loss Probe (TLP) is enabled. Tail Loss Probe (TLP) is another TCP enhancement designed to improve performance in high-bandwidth, high-latency networks. It helps to quickly recover from the loss of the last few packets in a transmission window (tail losses) by proactively sending a few probe packets. TLP sends a probe packet to detect and recover from losses at the end of a data burst (tail losses), reducing delays.
- Typical Values: enabled or disabled.
- Significance:
- Enabled: Speeds up recovery from tail losses, improving performance in lossy networks.
- Disabled: May result in longer delays for tail loss recovery.
Configure global TCP parameters
The netsh interface tcp set global command in Windows allows you to configure global TCP parameters that affect the behavior of TCP connections across all network interfaces. These settings control aspects like performance optimization, congestion control, retransmission behavior, and security features.
Command Syntax
- netsh interface tcp set global
- rss= disabled|enabled|default
- [[autotuninglevel=]disabled|highlyrestricted|restricted|normal|experimental]
- [[ecncapability=]disabled|enabled|default]
- [[timestamps=]disabled|enabled|default]
- [[initialrto=]<300-3000>]
- [[rsc=]disabled|enabled|default]
- [[nonsackrttresiliency=]disabled|enabled|default]
- [[maxsynretransmissions=]<2-8>]
- [[fastopen=]disabled|enabled|default]
- [[fastopenfallback=]disabled|enabled|default]
- [[hystart=]disabled|enabled|default]
- [[prr=]disabled|enabled|default]
- [[pacingprofile=]off|initialwindow|slowstart|always|default]
- Usage: Run this command in an elevated Command Prompt (as Administrator) to modify TCP settings.
- Parameters: Each parameter is optional, and you can specify one or more in a single command. If a parameter is omitted, its current value remains unchanged.
- Default: Setting a parameter to default reverts it to the system’s default configuration.
Here’s a breakdown of each parameter you can set:
1. rss= disabled|enabled|default
- RSS (Receive Side Scaling): This feature enables network adapters to distribute the processing of incoming network traffic across multiple CPU cores. Enabling RSS can significantly improve network performance, especially on multi-core systems with high network throughput.
- Options:
- disabled: Turns off RSS.
- enabled: Turns on RSS.
- default: Reverts to the system’s default RSS setting.
- Example: netsh interface tcp set global rss=enabled
- Options:
[[autotuninglevel=]disabled|highlyrestricted|restricted|normal|experimental]
- Autotuning Level: This parameter controls the TCP receive window auto-tuning mechanism. Auto-tuning dynamically adjusts the TCP receive window size based on network conditions (e.g., bandwidth, latency, and congestion). The receive window determines how much data the sender can transmit before receiving an acknowledgment, impacting throughput.
- disabled
- Description: Disables auto-tuning entirely. The TCP receive window size is fixed and does not adjust dynamically.
- When to Use:
- For troubleshooting network issues where auto-tuning might be causing problems.
- On older networks or devices that don’t handle dynamic window sizes well.
- When you need precise control over the receive window (rare).
- Drawbacks: May result in suboptimal performance, especially on modern high-speed networks, as the fixed window size might not adapt to changing conditions.
- highlyrestricted
- Description: Allows minimal dynamic adjustments to the receive window, staying close to a conservative fixed size.
- When to Use:
- In environments with legacy network equipment that struggles with aggressive window scaling.
- When you want some tuning but need to avoid significant changes.
- Drawbacks: Limits performance benefits compared to normal or experimental, but safer than disabled.
- restricted
- Description: Permits moderate dynamic adjustments to the receive window, balancing performance and compatibility.
- When to Use:
- In mixed environments where some network devices support modern TCP features but others are less capable.
- When you need a middle ground between performance and stability.
- Drawbacks: May not fully optimize throughput on high-bandwidth networks.
- normal
- Description: The default setting in modern Windows systems. It enables full dynamic auto-tuning, adjusting the receive window based on network conditions to maximize throughput.
- When to Use:
- For most general-purpose scenarios, including home, office, or internet-facing networks.
- Works well for typical applications like web browsing, streaming, and file transfers.
- Drawbacks: May cause issues with older routers or firewalls that mishandle large window sizes.
- experimental
- Description: Enables aggressive auto-tuning, allowing the receive window to scale to very large sizes for maximum throughput.
- When to Use:
- In high-bandwidth, low-latency environments (e.g., data centers, high-speed LANs).
- For applications requiring maximum network performance (e.g., large file transfers, cloud services).
- Drawbacks:
- Can cause compatibility issues with some routers, firewalls, or network devices that don’t handle large windows well.Increases memory usage due to larger buffers.Should be tested thoroughly before use in production.
- disabled
[[ecncapability=]disabled|enabled|default]
- ECN (Explicit Congestion Notification): This is an optional extension to the IP protocol that allows routers to signal network congestion to the endpoints without dropping packets. Enabling ECN can lead to smoother throughput and reduced packet loss on networks that support it. ECN is an extension to the TCP/IP protocol (defined in RFC 3168) that allows routers to mark packets with a congestion signal when network queues are filling up, rather than dropping them.
- How It Works:
- Routers set ECN bits in the IP header (ECN-Capable Transport, ECT) to indicate congestion.
- The receiving endpoint detects these marks and informs the sender via TCP acknowledgments.
- The sender reduces its transmission rate (similar to how it responds to packet loss) to alleviate congestion.
- Key Benefit: Reduces packet loss, which improves throughput and reduces retransmissions, especially in high-traffic or congested networks.
- Options
- disabled: Disables ECN. Prevents TCP from using ECN, falling back to traditional packet-dropping behavior for congestion control.
- enabled: Enables ECN. Allows TCP to negotiate and use ECN for connections, provided the remote endpoint and network devices support it.
- default: Reverts to the system’s default ECN setting.
- Use Case: Enable for modern networks to reduce packet loss; disable for compatibility with older routers that mishandle ECN.
- Example: netsh interface tcp set global ecncapability=enabled
[[timestamps=]disabled|enabled|default]
- TCP Timestamps: These are options included in TCP headers that can help with Round-Trip Time (RTT) measurement and other performance optimizations.
- Options:
- disabled: Disables TCP timestamps.
- enabled: Enables TCP timestamps.
- default: Reverts to the system’s default TCP timestamp setting.
- Use Case: Enable for modern, high-speed networks; disable for older networks where timestamps increase overhead.
- Example: netsh interface tcp set global timestamps=enabled
- Options:
[[initialrto=]<300-3000>]
- Initial RTO (Retransmission Timeout): This parameter allows you to set the initial timeout value (in milliseconds) that TCP uses before retransmitting an unacknowledged segment during connection establishment. This setting applies globally to all TCP connections on the system and can significantly impact network performance, especially in scenarios with varying latency or packet loss.
- Range: The value must be between 300 and 3000 milliseconds.
- Use Case: Lower values (e.g., 300) reduce latency in low-latency networks; higher values (e.g., 1000) are better for high-latency networks to avoid premature retransmissions.
- Modifying this is generally not recommended unless you have a specific reason related to unusual network conditions.
- Example: netsh interface tcp set global initialrto=500
[[rsc=]disabled|enabled|default]
- RSC (Receive Segment Coalescing): As we discussed earlier, this feature helps reduce CPU utilization by combining multiple incoming TCP/IP packets into larger segments before they are processed.
- Options:
- disabled: Disables RSC.
- enabled: Enables RSC.
- default: Reverts to the system’s default RSC setting.
- Use Case: Enable for high-throughput scenarios (e.g., file transfers); disable for latency-sensitive applications (e.g., gaming).
- Example: netsh interface tcp set global rsc=enabled
- Options:
[[nonsackrttresiliency=]disabled|enabled|default]
- Non-SACK RTT Resiliency: This setting likely relates to how TCP estimates the Round-Trip Time (RTT) for connections that do not support Selective Acknowledgment (SACK). Enabling this might improve performance on networks with older equipment or protocols.
- Options:
- disabled: Disables this resiliency feature.
- enabled: Enables this resiliency feature.
- default: Reverts to the system’s default setting.
- Use Case: Enable for networks with fluctuating latency; disable for stable networks to avoid unnecessary adjustments.
- Example: netsh interface tcp set global nonsackrttresiliency=enabled
- Options:
[[maxsynretransmissions=]<2-8>]
- Max SYN Retransmissions: This parameter controls the number of times TCP will retransmit the initial SYN (synchronize) packet when attempting to establish a new connection before giving up.
- Range: The value must be between 2 and 8.
- Use Case: Increase (e.g., 4) for unreliable networks; decrease (e.g., 2) for faster failure detection in responsive networks.
- Increasing this might help in very unreliable networks where initial connection attempts are often dropped, but it can also delay connection failure if the destination is unreachable.
- Example: netsh interface tcp set global maxsynretransmissions=3
[[fastopen=]disabled|enabled|default]
- TCP Fast Open: This is a TCP extension that allows data to be included in the initial SYN packet during the connection establishment, potentially reducing the round trips needed for the start of data transfer for subsequent connections to the same server.
- Options:
- disabled: Disables TCP Fast Open.
- enabled: Enables TCP Fast Open.
- default: Reverts to the system’s default TCP Fast Open setting.
- Use Case: Enable for faster web browsing or short-lived connections; disable for compatibility with networks that block TFO.
- Options:
[[fastopenfallback=]disabled|enabled|default]
- TCP Fast Open Fallback: This setting likely controls whether TCP should fall back to a standard three-way handshake if the Fast Open attempt fails (e.g., the server doesn’t support it).
- Options:
- disabled: Disables the fallback mechanism.
- enabled: Enables the fallback mechanism.
- default: Reverts to the system’s default fallback setting.
- Use Case: Enable for compatibility; disable to enforce Fast Open (rarely needed).
- Options:
[[hystart=]disabled|enabled|default]
- HyStart (Hybrid Start): This is an enhancement to the TCP slow start algorithm that aims to more quickly reach the available bandwidth by using RTT measurements to detect the onset of congestion.
- Options:
- disabled: Disables HyStart.
- enabled: Enables HyStart.
- default: Reverts to the system’s default HyStart setting.
- Use Case: Enable for better performance in congested networks; disable for highly stable networks.
- Example: netsh interface tcp set global hystart=enabled
- Options:
[[prr=]disabled|enabled|default]
- PRR (Proportional Rate Reduction): This is a TCP congestion control mechanism used during recovery after packet loss. It aims to send a number of bytes proportional to the number of acknowledged bytes during the recovery phase, leading to smoother bandwidth utilization.
- Options:
- disabled: Disables PRR.
- enabled: Enables PRR.
- default: Reverts to the system’s default PRR setting.
- Use Case: Enable for modern networks to improve recovery; disable for compatibility with older systems.
- Example: netsh interface tcp set global prr=enabled
- Options:
[[pacingprofile=]off|initialwindow|slowstart|always|default]
- TCP Pacing Profile: TCP pacing aims to smooth out packet transmission over time, potentially reducing bursts and improving network stability, especially on congested links. Different profiles might apply pacing during different phases of the connection.
- Options:
- off: Disables TCP pacing.
- initialwindow: Applies pacing during the initial congestion window phase.
- slowstart: Applies pacing during the slow start phase.
- always: Pacing for all transmissions.
- default: Reverts to the system’s default pacing profile (often off or slowstart).
- Use Case: Set to always or slowstart for congested networks; use off for low-latency, high-bandwidth networks.
- Example: netsh interface tcp set global pacingprofile=slowstart
- Options:
Example_1
Set the auto-tuning level to Normal, run the command:
- netsh interface tcp set global autotuninglevel=normal
To verify the configuration, run the command:
- netsh interface tcp show global store=active
Example_2
What is Explicit Congestion Notification (ECN)?
- Definition: ECN is an extension to the TCP/IP protocol (defined in RFC 3168) that allows routers to mark packets with a congestion signal when network queues are filling up, rather than dropping them.
Benefits of Enabling ECN
- Reduced Packet Loss: By signaling congestion without dropping packets, ECN helps maintain data flow and reduces the need for retransmissions.
- Improved Throughput: Fewer dropped packets mean more consistent performance, especially in high-bandwidth or congested networks (e.g., data centers, busy Wi-Fi networks).
- Better Congestion Management: ECN allows endpoints to proactively reduce transmission rates, preventing network overload.
- Modern Network Compatibility: Many modern networks and applications (e.g., cloud services, streaming) benefit from ECN support.
Potential Issues with ECN
- Compatibility Problems:
- Some older routers, firewalls, or network devices may not support ECN or may mishandle ECN-marked packets, leading to connection issues or dropped packets.
- Certain ISPs or enterprise networks may block or misinterpret ECN, causing performance degradation.
- Limited Adoption:
- ECN requires support from both endpoints (sender and receiver) and intermediate network devices. If any part of the path doesn’t support ECN, it falls back to traditional congestion control.
- Debugging Challenges:
- Misconfigured ECN can be hard to diagnose, as issues may appear as generic connectivity problems.
- Minimal Impact in Low-Congestion Networks:
- In stable, low-traffic networks (e.g., a small LAN), ECN’s benefits may be negligible.
When to Enable or Disable ECN
- Enable ECN (enabled):
- Use Case: Modern networks with ECN-capable devices, such as data centers, cloud environments, or high-traffic internet connections.
- Scenarios: File transfers, streaming, web browsing, or any application benefiting from reduced packet loss.
- Example Environments: Home networks with modern routers, enterprise networks, or cloud-hosted servers.
- Disable ECN (disabled):
- Use Case: Legacy networks or environments with known ECN compatibility issues.
- Scenarios: Older routers/firewalls, certain ISP networks, or when troubleshooting connectivity issues.
- Example Environments: Legacy corporate networks, outdated home routers, or specific VPN setups.
To Enable the Explicit Congestion Notification (ECN), run the command:
- netsh interface tcp set global ecncapability=enabled
To verify the configuration, run the command:
- netsh interface tcp show global store=active
This policy setting allows you to configure Window Scaling Heuristics. Window Scaling Heuristics is an algorithm to identify connectivity and throughput problems caused by many Firewalls and other middle boxes that don’t interpret Window Scaling option correctly.If you do not configure this policy setting the local host settings are used.If you enable this policy setting Window Scaling Heuristics will be enabled and system will try to identify connectivity and throughput problems and take appropriate measures.If you disable this policy setting Window Scaling Heuristics will be disabled and system will not try to identify connectivity and throughput problems casued by Firewalls or other middle boxes.
Policy path:
Network\TCPIP Settings\Parameters
Scope:
Supported on:
At least Windows Vista Service Pack 1
Registry settings:
HKLM\System\CurrentControlSet\Services\Tcpip\Parameters!EnableWsd
Filename:
