# SOME DESCRIPTIVE TITLE # Copyright (C) YEAR The FreeBSD Project # This file is distributed under the same license as the FreeBSD Documentation package. # Vladlen Popolitov , 2025, 2026. msgid "" msgstr "" "Project-Id-Version: FreeBSD Documentation VERSION\n" "POT-Creation-Date: 2025-11-08 16:17+0000\n" "PO-Revision-Date: 2026-03-04 20:01+0000\n" "Last-Translator: Vladlen Popolitov \n" "Language-Team: Russian \n" "Language: ru\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && " "n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n" "X-Generator: Weblate 4.17\n" #. type: YAML Front Matter: description #: documentation/content/en/books/arch-handbook/usb/_index.adoc:1 #, no-wrap msgid "USB Devices in FreeBSD" msgstr "Устройства USB в FreeBSD" #. type: YAML Front Matter: title #: documentation/content/en/books/arch-handbook/usb/_index.adoc:1 #, no-wrap msgid "Chapter 13. USB Devices" msgstr "Глава 13. USB-устройства" #. type: Title = #: documentation/content/en/books/arch-handbook/usb/_index.adoc:14 #, no-wrap msgid "USB Devices" msgstr "Устройства USB" #. type: Title == #: documentation/content/en/books/arch-handbook/usb/_index.adoc:52 #, no-wrap msgid "Introduction" msgstr "Введение" #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:55 msgid "" "The Universal Serial Bus (USB) is a new way of attaching devices to personal " "computers. The bus architecture features two-way communication and has been " "developed as a response to devices becoming smarter and requiring more " "interaction with the host. USB support is included in all current PC " "chipsets and is therefore available in all recently built PCs. Apple's " "introduction of the USB-only iMac has been a major incentive for hardware " "manufacturers to produce USB versions of their devices. The future PC " "specifications specify that all legacy connectors on PCs should be replaced " "by one or more USB connectors, providing generic plug and play capabilities. " "Support for USB hardware was available at a very early stage in NetBSD and " "was developed by Lennart Augustsson for the NetBSD project. The code has " "been ported to FreeBSD and we are currently maintaining a shared code base. " "For the implementation of the USB subsystem a number of features of USB are " "important." msgstr "" "Универсальная последовательная шина (USB) — это новый способ подключения " "устройств к персональным компьютерам. Архитектура шины поддерживает " "двустороннюю связь и была разработана в ответ на усложнение устройств, " "требующих большего взаимодействия с хостом. Поддержка USB включена во все " "современные чипсеты ПК и, следовательно, доступна во всех недавно собранных " "компьютерах. Выпуск Apple iMac только с USB стал серьёзным стимулом для " "производителей оборудования выпускать USB-версии своих устройств. Согласно " "будущим спецификациям ПК, все устаревшие разъёмы должны быть заменены одним " "или несколькими USB-разъёмами, обеспечивающими универсальные возможности " "plug and play. Поддержка USB-оборудования появилась в NetBSD на очень раннем " "этапе и была разработана Леннартом Аугустссоном для проекта NetBSD. Код был " "портирован в FreeBSD, и в настоящее время мы поддерживаем общую кодовая " "базу. Для реализации подсистемы USB важны некоторые особенности USB." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:57 msgid "" "_Lennart Augustsson has done most of the implementation of the USB support " "for the NetBSD project. Many thanks for this incredible amount of work. Many " "thanks also to Ardy and Dirk for their comments and proofreading of this " "paper._" msgstr "" "_Леннарт Аугустссон выполнил большую часть работы по реализации поддержки " "USB для проекта NetBSD. Огромная благодарность за этот невероятный объём " "работы. Также большое спасибо Арди и Дирку за их комментарии и вычитку этой " "статьи._" #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:59 msgid "" "Devices connect to ports on the computer directly or on devices called hubs, " "forming a treelike device structure." msgstr "" "Устройства подключаются к портам компьютера напрямую или через устройства, " "называемые концентраторами, образуя древовидную структуру устройств." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:60 msgid "The devices can be connected and disconnected at run time." msgstr "Устройства можно подключать и отключать во время работы." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:61 msgid "Devices can suspend themselves and trigger resumes of the host system" msgstr "" "Устройства могут приостанавливать свою работу и инициировать возобновление " "работы основной системы" #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:62 msgid "" "As the devices can be powered from the bus, the host software has to keep " "track of power budgets for each hub." msgstr "" "Поскольку устройства могут получать питание от шины, программное обеспечение " "хоста должно отслеживать энергопотребление для каждого концентратора." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:63 msgid "" "Different quality of service requirements by the different device types " "together with the maximum of 126 devices that can be connected to the same " "bus, require proper scheduling of transfers on the shared bus to take full " "advantage of the 12Mbps bandwidth available. (over 400Mbps with USB 2.0)" msgstr "" "Различные требования к качеству обслуживания для разных типов устройств, а " "также максимум в 126 устройств, которые могут быть подключены к одной шине, " "требуют правильного планирования передач по общей шине, чтобы полностью " "использовать доступную пропускную способность в 12 Мбит/с (более 400 Мбит/с " "для USB 2.0)" #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:64 msgid "" "Devices are intelligent and contain easily accessible information about " "themselves" msgstr "" "Устройства являются интеллектуальными и содержат легко доступную информацию " "о себе" #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:66 msgid "" "The development of drivers for the USB subsystem and devices connected to it " "is supported by the specifications that have been developed and will be " "developed. These specifications are publicly available from the USB home " "pages. Apple has been very strong in pushing for standards based drivers, by " "making drivers for the generic classes available in their operating system " "MacOS and discouraging the use of separate drivers for each new device. This " "chapter tries to collate essential information for a basic understanding of " "the USB 2.0 implementation stack in FreeBSD/NetBSD. It is recommended " "however to read it together with the relevant 2.0 specifications and other " "developer resources:" msgstr "" "Разработка драйверов для подсистемы USB и подключенных к ней устройств " "поддерживается спецификациями, которые были разработаны и будут " "разрабатываться. Эти спецификации общедоступны на домашних страницах USB. " "Apple активно продвигает стандартизированные драйверы, предоставляя драйверы " "для универсальных классов в своей операционной системе MacOS и не поощряя " "использование отдельных драйверов для каждого нового устройства. Эта глава " "пытается собрать основную информацию для базового понимания реализации стека " "USB 2.0 в FreeBSD/NetBSD. Однако рекомендуется читать её вместе с " "соответствующими спецификациями 2.0 и другими ресурсами для разработчиков:" #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:68 msgid "" "USB 2.0 Specification (http://www.usb.org/developers/docs/usb20_docs/[http://" "www.usb.org/developers/docs/usb20_docs/])" msgstr "" "Спецификация USB 2.0 (http://www.usb.org/developers/docs/usb20_docs/[http://" "www.usb.org/developers/docs/usb20_docs/])" #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:69 msgid "" "Universal Host Controller Interface (UHCI) Specification (link:ftp://ftp." "netbsd.org/pub/NetBSD/misc/blymn/uhci11d.pdf[ftp://ftp.netbsd.org/pub/NetBSD/" "misc/blymn/uhci11d.pdf])" msgstr "" "Универсальный интерфейс хост-контроллера (UHCI) Спецификация (link:ftp://ftp." "netbsd.org/pub/NetBSD/misc/blymn/uhci11d.pdf[ftp://ftp.netbsd.org/pub/NetBSD/" "misc/blymn/uhci11d.pdf])" #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:70 msgid "" "Open Host Controller Interface (OHCI) Specification(link:ftp://ftp.compaq." "com/pub/supportinformation/papers/hcir1_0a.pdf[ftp://ftp.compaq.com/pub/" "supportinformation/papers/hcir1_0a.pdf])" msgstr "" "Спецификация интерфейса Open Host Controller (OHCI)(link:ftp://ftp.compaq." "com/pub/supportinformation/papers/hcir1_0a.pdf[ftp://ftp.compaq.com/pub/" "supportinformation/papers/hcir1_0a.pdf])" #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:71 msgid "" "Developer section of USB home page (http://www.usb.org/developers/[http://" "www.usb.org/developers/])" msgstr "" "Раздел для разработчиков на домашней странице USB (http://www.usb.org/" "developers/[http://www.usb.org/developers/])" #. type: Title === #: documentation/content/en/books/arch-handbook/usb/_index.adoc:72 #, no-wrap msgid "Structure of the USB Stack" msgstr "Структура стека USB" #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:75 msgid "" "The USB support in FreeBSD can be split into three layers. The lowest layer " "contains the host controller driver, providing a generic interface to the " "hardware and its scheduling facilities. It supports initialisation of the " "hardware, scheduling of transfers and handling of completed and/or failed " "transfers. Each host controller driver implements a virtual hub providing " "hardware independent access to the registers controlling the root ports on " "the back of the machine." msgstr "" "Поддержка USB в FreeBSD может быть разделена на три уровня. Самый нижний " "уровень содержит драйвер контроллера хоста, предоставляющий универсальный " "интерфейс к оборудованию и его механизмам планирования. Он поддерживает " "инициализацию оборудования, планирование передач и обработку завершённых и/" "или неудачных передач. Каждый драйвер контроллера хоста реализует " "виртуальный концентратор, обеспечивающий независимый от оборудования доступ " "к регистрам, управляющим корневыми портами на задней панели машины." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:77 msgid "" "The middle layer handles the device connection and disconnection, basic " "initialisation of the device, driver selection, the communication channels " "(pipes) and does resource management. This services layer also controls the " "default pipes and the device requests transferred over them." msgstr "" "Средний уровень обрабатывает подключение и отключение устройства, базовую " "инициализацию устройства, выбор драйвера, каналы связи (pipe) и управляет " "ресурсами. Этот сервисный уровень также контролирует стандартные каналы и " "запросы устройств, передаваемые через них." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:79 msgid "" "The top layer contains the individual drivers supporting specific (classes " "of) devices. These drivers implement the protocol that is used over the " "pipes other than the default pipe. They also implement additional " "functionality to make the device available to other parts of the kernel or " "userland. They use the USB driver interface (USBDI) exposed by the services " "layer." msgstr "" "Верхний уровень содержит отдельные драйверы, поддерживающие конкретные " "(классы) устройств. Эти драйверы реализуют протокол, используемый в каналах, " "отличных от стандартного. Они также реализуют дополнительную " "функциональность для обеспечения доступа к устройству другим частям ядра или " "пользовательского пространства. Они используют интерфейс драйвера USB " "(USBDI), предоставляемый уровнем сервисов." #. type: Title == #: documentation/content/en/books/arch-handbook/usb/_index.adoc:81 #, no-wrap msgid "Host Controllers" msgstr "Контроллеры хоста" #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:84 msgid "" "The host controller (HC) controls the transmission of packets on the bus. " "Frames of 1 millisecond are used. At the start of each frame the host " "controller generates a Start of Frame (SOF) packet." msgstr "" "Хост-контроллер (HC) управляет передачей пакетов на шине. Используются кадры " "длительностью 1 миллисекунда. В начале каждого кадра хост-контроллер " "генерирует пакет Start of Frame (SOF)." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:86 msgid "" "The SOF packet is used to synchronise to the start of the frame and to keep " "track of the frame number. Within each frame packets are transferred, either " "from host to device (out) or from device to host (in). Transfers are always " "initiated by the host (polled transfers). Therefore there can only be one " "host per USB bus. Each transfer of a packet has a status stage in which the " "recipient of the data can return either ACK (acknowledge reception), NAK " "(retry), STALL (error condition) or nothing (garbled data stage, device not " "available or disconnected). Section 8.5 of the USB 2.0 Specification " "explains the details of packets in more detail. Four different types of " "transfers can occur on a USB bus: control, bulk, interrupt and isochronous. " "The types of transfers and their characteristics are described below." msgstr "" "Пакет SOF используется для синхронизации начала кадра и отслеживания номера " "кадра. Внутри каждого кадра передаются пакеты, либо от хоста к устройству " "(исходящие), либо от устройства к хосту (входящие). Передачи всегда " "инициируются хостом (опросные передачи). Поэтому на каждой шине USB может " "быть только один хост. Каждая передача пакета имеет стадию статуса, в " "которой получатель данных может вернуть либо ACK (подтверждение приема), NAK " "(повторить), STALL (ошибка) либо ничего (искаженная стадия данных, " "устройство недоступно или отключено). В разделе 8.5 спецификации USB 2.0 " "подробно объясняются детали пакетов. На шине USB могут происходить четыре " "различных типа передач: управляющие, массовые, прерывания и изохронные. Типы " "передач и их характеристики описаны ниже." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:88 msgid "" "Large transfers between the device on the USB bus and the device driver are " "split up into multiple packets by the host controller or the HC driver." msgstr "" "Крупные передачи между устройством на шине USB и драйвером устройства " "разделяются на несколько пакетов хост-контроллером или драйвером HC." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:90 msgid "" "Device requests (control transfers) to the default endpoints are special. " "They consist of two or three phases: SETUP, DATA (optional) and STATUS. The " "set-up packet is sent to the device. If there is a data phase, the direction " "of the data packet(s) is given in the set-up packet. The direction in the " "status phase is the opposite of the direction during the data phase, or IN " "if there was no data phase. The host controller hardware also provides " "registers with the current status of the root ports and the changes that " "have occurred since the last reset of the status change register. Access to " "these registers is provided through a virtualised hub as suggested in the " "USB specification. The virtual hub must comply with the hub device class " "given in chapter 11 of that specification. It must provide a default pipe " "through which device requests can be sent to it. It returns the standard " "andhub class specific set of descriptors. It should also provide an " "interrupt pipe that reports changes happening at its ports. There are " "currently two specifications for host controllers available: Universal Host " "Controller Interface (UHCI) from Intel and Open Host Controller Interface " "(OHCI) from Compaq, Microsoft, and National Semiconductor. The UHCI " "specification has been designed to reduce hardware complexity by requiring " "the host controller driver to supply a complete schedule of the transfers " "for each frame. OHCI type controllers are much more independent by providing " "a more abstract interface doing a lot of work themselves." msgstr "" "Запросы устройств (управляющие передачи) к конечным точкам по умолчанию " "являются особыми. Они состоят из двух или трёх фаз: SETUP, DATA " "(опционально) и STATUS. Пакет настройки отправляется на устройство. Если " "присутствует фаза данных, направление пакета(ов) данных указывается в пакете " "настройки. Направление в фазе статуса противоположно направлению во время " "фазы данных или IN, если фазы данных не было. Аппаратное обеспечение хост-" "контроллера также предоставляет регистры с текущим состоянием корневых " "портов и изменениями, произошедшими с момента последнего сброса регистра " "изменений статуса. Доступ к этим регистрам предоставляется через " "виртуализированный концентратор, как предложено в спецификации USB. " "Виртуальный концентратор должен соответствовать классу устройств " "концентратора, указанному в главе 11 этой спецификации. Он должен " "предоставлять канал по умолчанию, через который можно отправлять запросы " "устройств. Он возвращает стандартные и специфичные для класса концентратора " "наборы дескрипторов. Также он должен предоставлять прерывающий канал, " "сообщающий об изменениях, происходящих на его портах. В настоящее время " "доступны две спецификации для хост-контроллеров: - Universal Host Controller " "Interface (UHCI) от Intel и Open Host Controller Interface (OHCI) от Compaq, " "Microsoft и National Semiconductor. Спецификация UHCI разработана для " "уменьшения аппаратной сложности, требуя от драйвера хост-контроллера " "предоставления полного расписания передач для каждого кадра. Контроллеры " "типа OHCI гораздо более независимы, предоставляя более абстрактный интерфейс " "и выполняя большую часть работы самостоятельно." #. type: Title === #: documentation/content/en/books/arch-handbook/usb/_index.adoc:91 #, no-wrap msgid "UHCI" msgstr "UHCI" #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:94 msgid "" "The UHCI host controller maintains a framelist with 1024 pointers to per " "frame data structures. It understands two different data types: transfer " "descriptors (TD) and queue heads (QH). Each TD represents a packet to be " "communicated to or from a device endpoint. QHs are a means to groupTDs (and " "QHs) together." msgstr "" "Контроллер UHCI поддерживает список кадров (framelist) с 1024 указателями на " "структуры данных для каждого кадра. Он распознаёт два типа данных: " "дескрипторы передачи (TD) и головы очередей (QH). Каждый TD представляет " "пакет для передачи в конечную точку устройства или из неё. QH служат для " "группировки TD (и других QH) вместе." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:96 msgid "" "Each transfer consists of one or more packets. The UHCI driver splits large " "transfers into multiple packets. For every transfer, apart from isochronous " "transfers, a QH is allocated. For every type of transfer these QHs are " "collected at a QH for that type. Isochronous transfers have to be executed " "first because of the fixed latency requirement and are directly referred to " "by the pointer in the framelist. The last isochronous TD refers to the QH " "for interrupt transfers for that frame. All QHs for interrupt transfers " "point at the QH for control transfers, which in turn points at the QH for " "bulk transfers. The following diagram gives a graphical overview of this:" msgstr "" "Каждая передача состоит из одного или нескольких пакетов. Драйвер UHCI " "разделяет большие передачи на несколько пакетов. Для каждой передачи, за " "исключением изохронных, выделяется QH. Для каждого типа передачи эти QH " "собираются в QH для соответствующего типа. Изохронные передачи должны " "выполняться первыми из-за требования фиксированной задержки и " "непосредственно указываются указателем в списке кадров. Последний изохронный " "TD ссылается на QH для прерывающих передач для этого кадра. Все QH для " "прерывающих передач указывают на QH для управляющих передач, который, в свою " "очередь, указывает на QH для массовых передач. Следующая диаграмма даёт " "графическое представление этого:" #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:98 msgid "" "This results in the following schedule being run in each frame. After " "fetching the pointer for the current frame from the framelist the controller " "first executes the TDs for all the isochronous packets in that frame. The " "last of these TDs refers to the QH for the interrupt transfers for that " "frame. The host controller will then descend from that QH to the QHs for the " "individual interrupt transfers. After finishing that queue, the QH for the " "interrupt transfers will refer the controller to the QH for all control " "transfers. It will execute all the subqueues scheduled there, followed by " "all the transfers queued at the bulk QH. To facilitate the handling of " "finished or failed transfers different types of interrupts are generated by " "the hardware at the end of each frame. In the last TD for a transfer the " "Interrupt-On Completion bit is set by the HC driver to flag an interrupt " "when the transfer has completed. An error interrupt is flagged if a TD " "reaches its maximum error count. If the short packet detect bit is set in a " "TD and less than the set packet length is transferred this interrupt is " "flagged to notify the controller driver of the completed transfer. It is the " "host controller driver's task to find out which transfer has completed or " "produced an error. When called the interrupt service routine will locate all " "the finished transfers and call their callbacks." msgstr "" "В результате выполняется следующее расписание в каждом кадре. После " "получения указателя на текущий кадр из списка кадров контроллер сначала " "выполняет TDs для всех изохронных пакетов в этом кадре. Последний из этих " "TDs ссылается на QH для прерывающих передач этого кадра. Хост-контроллер " "затем переходит от этого QH к QHs для отдельных прерывающих передач. После " "завершения этой очереди, QH для прерывающих передач ссылается на QH для всех " "управляющих передач. Он выполняет все подочереди, запланированные там, а " "затем все передачи, поставленные в очередь в QH для массовых передач. Для " "упрощения обработки завершенных или неудачных передач аппаратное обеспечение " "генерирует различные типы прерываний в конце каждого кадра. В последнем TD " "для передачи бит *Interrupt-On Completion* устанавливается драйвером HC, " "чтобы вызвать прерывание по завершении передачи. Прерывание ошибки " "возникает, если TD достигает максимального количества ошибок. Если в TD " "установлен бит *short packet detect* и передано меньше установленной длины " "пакета, это прерывание уведомляет драйвер контроллера о завершении передачи. " "Задача драйвера хост-контроллера — определить, какая передача завершилась " "или вызвала ошибку. При вызове процедура обслуживания прерывания находит все " "завершенные передачи и вызывает их callback-функции." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:100 msgid "Refer to the UHCI Specification for a more elaborate description." msgstr "Обратитесь к спецификации UHCI для более подробного описания." #. type: Title === #: documentation/content/en/books/arch-handbook/usb/_index.adoc:101 #, no-wrap msgid "OHCI" msgstr "OHCI" #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:104 msgid "" "Programming an OHCI host controller is much simpler. The controller assumes " "that a set of endpoints is available, and is aware of scheduling priorities " "and the ordering of the types of transfers in a frame. The main data " "structure used by the host controller is the endpoint descriptor (ED) to " "which a queue of transfer descriptors (TDs) is attached. The ED contains the " "maximum packet size allowed for an endpoint and the controller hardware does " "the splitting into packets. The pointers to the data buffers are updated " "after each transfer and when the start and end pointer are equal, the TD is " "retired to the done-queue. The four types of endpoints (interrupt, " "isochronous, control, and bulk) have their own queues. Control and bulk " "endpoints are queued each at their own queue. Interrupt EDs are queued in a " "tree, with the level in the tree defining the frequency at which they run." msgstr "" "Программирование OHCI-контроллера значительно проще. Контроллер " "предполагает, что доступен набор конечных точек, и учитывает приоритеты " "планирования и порядок типов передач в кадре. Основная структура данных, " "используемая хост-контроллером, — это дескриптор конечной точки (ED), к " "которому присоединена очередь дескрипторов передачи (TD). ED содержит " "максимальный размер пакета, разрешенный для конечной точки, а аппаратное " "обеспечение контроллера выполняет разделение на пакеты. Указатели на буферы " "данных обновляются после каждой передачи, и когда начальный и конечный " "указатели становятся равны, TD перемещается в очередь завершенных (done-" "queue). Четыре типа конечных точек (прерывание, изохронная, управление и " "массовая) имеют свои собственные очереди. Управляющие и массовые конечные " "точки помещаются каждая в свою очередь. ED прерываний организуются в дерево, " "где уровень в дереве определяет частоту их выполнения." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:106 msgid "" "The schedule being run by the host controller in each frame looks as " "follows. The controller will first run the non-periodic control and bulk " "queues, up to a time limit set by the HC driver. Then the interrupt " "transfers for that frame number are run, by using the lower five bits of the " "frame number as an index into level 0 of the tree of interrupts EDs. At the " "end of this tree the isochronous EDs are connected and these are traversed " "subsequently. The isochronous TDs contain the frame number of the first " "frame the transfer should be run in. After all the periodic transfers have " "been run, the control and bulk queues are traversed again. Periodically the " "interrupt service routine is called to process the done queue and call the " "callbacks for each transfer and reschedule interrupt and isochronous " "endpoints." msgstr "" "Порядок действий, выполняемых хост-контроллером в каждом кадре, выглядит " "следующим образом. Контроллер сначала запускает непериодические очереди " "управления и массовых передач, вплоть до ограничения времени, установленного " "драйвером HC. Затем выполняются прерывающие передачи для данного номера " "кадра, используя младшие пять битов номера кадра в качестве индекса уровня 0 " "дерева ED прерываний. В конце этого дерева подключены изохронные ED, которые " "затем обходятся. Изохронные TD содержат номер кадра, в котором должна быть " "запущена первая передача. После выполнения всех периодических передач " "очереди управления и массовых передач обходятся снова. Периодически " "вызывается процедура обслуживания прерывания для обработки очереди " "завершенных операций и вызова обратных вызовов для каждой передачи, а также " "для перепланирования прерывающих и изохронных конечных точек." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:108 msgid "" "See the UHCI Specification for a more elaborate description. The middle " "layer provides access to the device in a controlled way and maintains " "resources in use by the different drivers and the services layer. The layer " "takes care of the following aspects:" msgstr "" "См. UHCI Specification для более подробного описания. Средний уровень " "обеспечивает контролируемый доступ к устройству и управляет ресурсами, " "используемыми различными драйверами и уровнем сервисов. Этот уровень " "отвечает за следующие аспекты:" #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:110 msgid "The device configuration information" msgstr "Информация о конфигурации устройства" #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:111 msgid "The pipes to communicate with a device" msgstr "Каналы для взаимодействия с устройством" #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:112 msgid "Probing and attaching and detaching form a device." msgstr "Обнаружение, подключение и отключение от устройства." #. type: Title == #: documentation/content/en/books/arch-handbook/usb/_index.adoc:114 #, no-wrap msgid "USB Device Information" msgstr "Информация об устройстве USB" #. type: Title === #: documentation/content/en/books/arch-handbook/usb/_index.adoc:116 #, no-wrap msgid "Device Configuration Information" msgstr "Информация о конфигурации устройства" #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:119 msgid "" "Each device provides different levels of configuration information. Each " "device has one or more configurations, of which one is selected during probe/" "attach. A configuration provides power and bandwidth requirements. Within " "each configuration there can be multiple interfaces. A device interface is a " "collection of endpoints. For example USB speakers can have an interface for " "the audio data (Audio Class) and an interface for the knobs, dials and " "buttons (HID Class). All interfaces in a configuration are active at the " "same time and can be attached to by different drivers. Each interface can " "have alternates, providing different quality of service parameters. In for " "example cameras this is used to provide different frame sizes and numbers of " "frames per second." msgstr "" "Каждое устройство предоставляет различные уровни информации о конфигурации. " "У каждого устройства есть одна или несколько конфигураций, из которых одна " "выбирается во время обнаружения/подключения. Конфигурация определяет " "требования к питанию и пропускной способности. В каждой конфигурации может " "быть несколько интерфейсов. Интерфейс устройства — это набор конечных точек. " "Например, USB-колонки могут иметь интерфейс для аудиоданных (Audio Class) и " "интерфейс для регуляторов, ручек и кнопок (HID Class). Все интерфейсы в " "конфигурации активны одновременно и могут быть подключены разными " "драйверами. Каждый интерфейс может иметь альтернативные варианты, " "предоставляющие различные параметры качества обслуживания. Например, в " "камерах это используется для поддержки разных размеров кадра и количества " "кадров в секунду." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:121 msgid "" "Within each interface, 0 or more endpoints can be specified. Endpoints are " "the unidirectional access points for communicating with a device. They " "provide buffers to temporarily store incoming or outgoing data from the " "device. Each endpoint has a unique address within a configuration, the " "endpoint's number plus its direction. The default endpoint, endpoint 0, is " "not part of any interface and available in all configurations. It is managed " "by the services layer and not directly available to device drivers." msgstr "" "В каждом интерфейсе может быть указано 0 или более конечных точек. Конечные " "точки — это однонаправленные точки доступа для связи с устройством. Они " "предоставляют буферы для временного хранения входящих или исходящих данных " "устройства. Каждая конечная точка имеет уникальный адрес в конфигурации — " "номер конечной точки плюс её направление. Конечная точка по умолчанию, " "конечная точка 0, не является частью какого-либо интерфейса и доступна во " "всех конфигурациях. Она управляется уровнем сервисов и не доступна напрямую " "драйверам устройств." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:123 msgid "" "This hierarchical configuration information is described in the device by a " "standard set of descriptors (see section 9.6 of the USB specification). They " "can be requested through the Get Descriptor Request. The services layer " "caches these descriptors to avoid unnecessary transfers on the USB bus. " "Access to the descriptors is provided through function calls." msgstr "" "Эта иерархическая конфигурационная информация описывается в устройстве " "стандартным набором дескрипторов (см. раздел 9.6 спецификации USB). Они " "могут быть запрошены через Get Descriptor Request. Сервисный уровень " "кэширует эти дескрипторы, чтобы избежать ненужных передач по шине USB. " "Доступ к дескрипторам предоставляется через вызовы функций." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:125 msgid "" "Device descriptors: General information about the device, like Vendor, " "Product and Revision Id, supported device class, subclass and protocol if " "applicable, maximum packet size for the default endpoint, etc." msgstr "" "Дескрипторы устройств: Общая информация об устройстве, такая как Vendor " "(производитель), Product (продукт) и Revision Id (идентификатор ревизии), " "поддерживаемый класс устройства, подкласс и протокол, если применимо, " "максимальный размер пакета для конечной точки по умолчанию и т. д." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:126 msgid "" "Configuration descriptors: The number of interfaces in this configuration, " "suspend and resume functionality supported and power requirements." msgstr "" "Дескрипторы конфигурации: количество интерфейсов в данной конфигурации, " "поддержка функций приостановки и возобновления работы, а также требования к " "питанию." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:127 msgid "" "Interface descriptors: interface class, subclass and protocol if applicable, " "number of alternate settings for the interface and the number of endpoints." msgstr "" "Дескрипторы интерфейса: класс интерфейса, подкласс и протокол (если " "применимо), количество альтернативных настроек интерфейса и количество " "конечных точек." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:128 msgid "" "Endpoint descriptors: Endpoint address, direction and type, maximum packet " "size supported and polling frequency if type is interrupt endpoint. There is " "no descriptor for the default endpoint (endpoint 0) and it is never counted " "in an interface descriptor." msgstr "" "Дескрипторы конечных точек: Адрес конечной точки, направление и тип, " "максимальный поддерживаемый размер пакета и частота опроса, если тип " "является конечной точкой прерывания. Для конечной точки по умолчанию " "(конечная точка 0) дескриптора не существует, и она никогда не учитывается в " "дескрипторе интерфейса." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:129 msgid "" "String descriptors: In the other descriptors string indices are supplied for " "some fields.These can be used to retrieve descriptive strings, possibly in " "multiple languages." msgstr "" "Дескрипторы строк: В остальных дескрипторах для некоторых полей указываются " "индексы строк. Эти индексы могут использоваться для получения описательных " "строк, возможно, на нескольких языках." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:131 msgid "" "Class specifications can add their own descriptor types that are available " "through the GetDescriptor Request." msgstr "" "Спецификации классов могут добавлять свои собственные типы дескрипторов, " "которые доступны через запрос GetDescriptor." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:133 msgid "" "Pipes Communication to end points on a device flows through so-called pipes. " "Drivers submit transfers to endpoints to a pipe and provide a callback to be " "called on completion or failure of the transfer (asynchronous transfers) or " "wait for completion (synchronous transfer). Transfers to an endpoint are " "serialised in the pipe. A transfer can either complete, fail or time-out (if " "a time-out has been set). There are two types of time-outs for transfers. " "Time-outs can happen due to time-out on the USBbus (milliseconds). These " "time-outs are seen as failures and can be due to disconnection of the " "device. A second form of time-out is implemented in software and is " "triggered when a transfer does not complete within a specified amount of " "time (seconds). These are caused by a device acknowledging negatively (NAK) " "the transferred packets. The cause for this is the device not being ready to " "receive data, buffer under- or overrun or protocol errors." msgstr "" "Канальный обмен данными с конечными точками устройства осуществляется через " "так называемые *каналы*. Драйверы передают данные конечным точкам через " "канал и предоставляют функцию обратного вызова, которая вызывается при " "завершении или сбое передачи (асинхронные передачи) или ожидают завершения " "(синхронная передача). Передачи данных в конечную точку сериализуются в " "канале. Передача может завершиться успешно, завершиться с ошибкой или " "превысить время ожидания (если оно было задано). Существует два типа " "таймаутов для передач. Таймауты могут происходить из-за истечения времени на " "шине USB (миллисекунды). Эти таймауты рассматриваются как сбои и могут быть " "вызваны отключением устройства. Вторая форма таймаута реализована на уровне " "программного обеспечения и срабатывает, если передача не завершается в " "течение заданного времени (секунды). Это происходит, когда устройство " "отрицательно подтверждает (NAK) переданные пакеты. Причинами могут быть " "неготовность устройства к приему данных, переполнение буфера или пустой " "буфер, либо ошибки протокола." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:135 msgid "" "If a transfer over a pipe is larger than the maximum packet size specified " "in the associated endpoint descriptor, the host controller (OHCI) or the HC " "driver (UHCI) will split the transfer into packets of maximum packet size, " "with the last packet possibly smaller than the maximum packet size." msgstr "" "Если передача через канал превышает максимальный размер пакета, указанный в " "соответствующем дескрипторе конечной точки, хост-контроллер (OHCI) или " "драйвер HC (UHCI) разделит передачу на пакеты максимального размера, при " "этом последний пакет может быть меньше максимального размера." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:137 msgid "" "Sometimes it is not a problem for a device to return less data than " "requested. For example abulk-in-transfer to a modem might request 200 bytes " "of data, but the modem has only 5 bytes available at that time. The driver " "can set the short packet (SPD) flag. It allows the host controller to accept " "a packet even if the amount of data transferred is less than requested. This " "flag is only valid for in-transfers, as the amount of data to be sent to a " "device is always known beforehand. If an unrecoverable error occurs in a " "device during a transfer the pipe is stalled. Before any more data is " "accepted or sent the driver needs to resolve the cause of the stall and " "clear the endpoint stall condition through send the clear endpoint halt " "device request over the default pipe. The default endpoint should never " "stall." msgstr "" "Иногда для устройства не является проблемой вернуть меньше данных, чем " "запрошено. Например, при передаче данных в режиме bulk-in на модем может " "быть запрошено 200 байт данных, но у модема в данный момент доступно только " "5 байт. Драйвер может установить флаг короткого пакета (SPD). Это позволяет " "хост-контроллеру принять пакет, даже если объём переданных данных меньше " "запрошенного. Этот флаг действителен только для in-передач, так как объём " "данных, отправляемых на устройство, всегда известен заранее. Если во время " "передачи в устройстве происходит неустранимая ошибка, канал останавливается " "(stalled). Прежде чем принимать или отправлять дополнительные данные, " "драйвер должен устранить причину остановки и сбросить условие остановки " "конечной точки, отправив запрос `clear endpoint halt` через канал по " "умолчанию. Конечная точка по умолчанию никогда не должна останавливаться." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:139 msgid "" "There are four different types of endpoints and corresponding pipes: - " "Control pipe / default pipe: There is one control pipe per device, connected " "to the default endpoint (endpoint 0). The pipe carries the device requests " "and associated data. The difference between transfers over the default pipe " "and other pipes is that the protocol for the transfers is described in the " "USB specification. These requests are used to reset and configure the " "device. A basic set of commands that must be supported by each device is " "provided in chapter 9 of the USB specification. The commands supported on " "this pipe can be extended by a device class specification to support " "additional functionality." msgstr "" "Существует четыре различных типа конечных точек и соответствующих каналов: - " "Управляющий канал / канал по умолчанию: На каждое устройство приходится один " "управляющий канал, подключенный к конечной точке по умолчанию (конечная " "точка 0). Этот канал передаёт запросы устройства и связанные с ними данные. " "Разница между передачами через канал по умолчанию и другими каналами " "заключается в том, что протокол для этих передач описан в спецификации USB. " "Эти запросы используются для сброса и настройки устройства. Базовый набор " "команд, который должен поддерживаться каждым устройством, приведен в главе 9 " "спецификации USB. Команды, поддерживаемые на этом канале, могут быть " "расширены спецификацией класса устройства для обеспечения дополнительной " "функциональности." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:141 msgid "Bulk pipe: This is the USB equivalent to a raw transmission medium." msgstr "Массовый канал: Это USB-эквивалент среды передачи данных в сыром виде." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:142 msgid "" "Interrupt pipe: The host sends a request for data to the device and if the " "device has nothing to send, it will NAK the data packet. Interrupt transfers " "are scheduled at a frequency specified when creating the pipe." msgstr "" "Прерывающий канал: Хост отправляет запрос данных на устройство, и если " "устройству нечего отправлять, оно отвечает NAK на пакет данных. Прерывающие " "передачи планируются с частотой, указанной при создании канала." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:143 msgid "" "Isochronous pipe: These pipes are intended for isochronous data, for example " "video or audio streams, with fixed latency, but no guaranteed delivery. Some " "support for pipes of this type is available in the current implementation. " "Packets in control, bulk and interrupt transfers are retried if an error " "occurs during transmission or the device acknowledges the packet negatively " "(NAK) due to for example lack of buffer space to store the incoming data. " "Isochronous packets are however not retried in case of failed delivery or " "NAK of a packet as this might violate the timing constraints." msgstr "" "Изохронный канал: Эти каналы предназначены для изохронных данных, например, " "видео- или аудиопотоков, с фиксированной задержкой, но без гарантированной " "доставки. В текущей реализации доступна некоторая поддержка каналов этого " "типа. Пакеты в управляющих, массовых и прерывающих передачах повторяются, " "если во время передачи возникает ошибка или устройство отрицательно " "подтверждает пакет (NAK) из-за, например, нехватки буферного пространства " "для хранения входящих данных. Однако изохронные пакеты не повторяются в " "случае неудачной доставки или NAK пакета, так как это может нарушить " "временные ограничения." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:145 msgid "" "The availability of the necessary bandwidth is calculated during the " "creation of the pipe. Transfers are scheduled within frames of 1 " "millisecond. The bandwidth allocation within a frame is prescribed by the " "USB specification, section 5.6 [ 2]. Isochronous and interrupt transfers are " "allowed to consume up to 90% of the bandwidth within a frame. Packets for " "control and bulk transfers are scheduled after all isochronous and interrupt " "packets and will consume all the remaining bandwidth." msgstr "" "Доступность необходимой полосы пропускания рассчитывается во время создания " "канала. Передачи планируются в рамках интервалов в 1 миллисекунду. " "Распределение полосы пропускания внутри интервала регламентируется " "спецификацией USB, раздел 5.6 [2]. Изохронные и прерывающие передачи могут " "использовать до 90% полосы пропускания в рамках интервала. Пакеты для " "управляющих и массовых передач планируются после всех изохронных и " "прерывающих пакетов и используют всю оставшуюся полосу пропускания." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:147 msgid "" "More information on scheduling of transfers and bandwidth reclamation can be " "found in chapter 5 of the USB specification, section 1.3 of the UHCI " "specification, and section 3.4.2 of the OHCI specification." msgstr "" "Дополнительная информация о планировании передач и освобождении пропускной " "способности доступна в главе 5 спецификации USB, разделе 1.3 спецификации " "UHCI и разделе 3.4.2 спецификации OHCI." #. type: Title == #: documentation/content/en/books/arch-handbook/usb/_index.adoc:149 #, no-wrap msgid "Device Probe and Attach" msgstr "Обнаружение устройства и подключение" #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:152 msgid "" "After the notification by the hub that a new device has been connected, the " "service layer switches on the port, providing the device with 100 mA of " "current. At this point the device is in its default state and listening to " "device address 0. The services layer will proceed to retrieve the various " "descriptors through the default pipe. After that it will send a Set Address " "request to move the device away from the default device address (address 0). " "Multiple device drivers might be able to support the device. For example a " "modem driver might be able to support an ISDN TA through the AT " "compatibility interface. A driver for that specific model of the ISDN " "adapter might however be able to provide much better support for this " "device. To support this flexibility, the probes return priorities indicating " "their level of support. Support for a specific revision of a product ranks " "the highest and the generic driver the lowest priority. It might also be " "that multiple drivers could attach to one device if there are multiple " "interfaces within one configuration. Each driver only needs to support a " "subset of the interfaces." msgstr "" "После уведомления от концентратора о подключении нового устройства сервисный " "уровень включает порт, предоставляя устройству ток 100 мА. На этом этапе " "устройство находится в своём исходном состоянии и прослушивает адрес " "устройства 0. Сервисный уровень продолжит получение различных дескрипторов " "через стандартный канал. После этого он отправит запрос Set Address, чтобы " "переместить устройство с исходного адреса (адрес 0). Несколько драйверов " "устройств могут поддерживать данное устройство. Например, драйвер модема " "может поддерживать ISDN TA через интерфейс совместимости AT. Однако драйвер, " "предназначенный для конкретной модели ISDN-адаптера, может обеспечить " "гораздо лучшую поддержку этого устройства. Для обеспечения такой гибкости " "пробы возвращают приоритеты, указывающие уровень их поддержки. Поддержка " "конкретной версии продукта имеет наивысший приоритет, а универсальный " "драйвер — самый низкий. Также возможно, что несколько драйверов могут быть " "подключены к одному устройству, если в одной конфигурации присутствует " "несколько интерфейсов. Каждому драйверу требуется поддерживать только " "подмножество интерфейсов." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:154 msgid "" "The probing for a driver for a newly attached device checks first for device " "specific drivers. If not found, the probe code iterates over all supported " "configurations until a driver attaches in a configuration. To support " "devices with multiple drivers on different interfaces, the probe iterates " "over all interfaces in a configuration that have not yet been claimed by a " "driver. Configurations that exceed the power budget for the hub are ignored. " "During attach the driver should initialise the device to its proper state, " "but not reset it, as this will make the device disconnect itself from the " "bus and restart the probing process for it. To avoid consuming unnecessary " "bandwidth should not claim the interrupt pipe at attach time, but should " "postpone allocating the pipe until the file is opened and the data is " "actually used. When the file is closed the pipe should be closed again, even " "though the device might still be attached." msgstr "" "Поиск драйвера для нового подключенного устройства сначала проверяет наличие " "специфичных для устройства драйверов. Если они не найдены, код проверки " "перебирает все поддерживаемые конфигурации, пока драйвер не будет подключен " "в одной из них. Для поддержки устройств с несколькими драйверами на разных " "интерфейсах проверка перебирает все интерфейсы в конфигурации, которые ещё " "не были заняты драйвером. Конфигурации, превышающие выделенный бюджет " "мощности для концентратора, игнорируются. Во время подключения драйвер " "должен инициализировать устройство в его рабочее состояние, но не сбрасывать " "его, так как это приведёт к отключению устройства от шины и перезапуску " "процесса проверки. Чтобы избежать излишнего потребления пропускной " "способности, не следует запрашивать канал прерывания во время подключения, а " "отложить его выделение до момента открытия файла и фактического " "использования данных. При закрытии файла канал следует снова закрыть, даже " "если устройство остаётся подключенным." #. type: Title === #: documentation/content/en/books/arch-handbook/usb/_index.adoc:155 #, no-wrap msgid "Device Disconnect and Detach" msgstr "Отключение и извлечение устройства" #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:158 msgid "" "A device driver should expect to receive errors during any transaction with " "the device. The design of USB supports and encourages the disconnection of " "devices at any point in time. Drivers should make sure that they do the " "right thing when the device disappears." msgstr "" "Драйвер устройства должен ожидать получения ошибок во время любой транзакции " "с устройством. Дизайн USB поддерживает и поощряет отключение устройств в " "любой момент времени. Драйверы должны гарантировать корректную обработку " "ситуаций, когда устройство исчезает." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:160 msgid "" "Furthermore a device that has been disconnected and reconnected will not be " "reattached at the same device instance. This might change in the future when " "more devices support serial numbers (see the device descriptor) or other " "means of defining an identity for a device have been developed." msgstr "" "Кроме того, устройство, которое было отключено и снова подключено, не будет " "повторно присоединено к тому же экземпляру устройства. Это может измениться " "в будущем, когда больше устройств будут поддерживать серийные номера (см. " "дескриптор устройства) или будут разработаны другие способы определения " "идентификатора устройства." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:162 msgid "" "The disconnection of a device is signaled by a hub in the interrupt packet " "delivered to the hub driver. The status change information indicates which " "port has seen a connection change. The device detach method for all device " "drivers for the device connected on that port are called and the structures " "cleaned up. If the port status indicates that in the mean time a device has " "been connected to that port, the procedure for probing and attaching the " "device will be started. A device reset will produce a disconnect-connect " "sequence on the hub and will be handled as described above." msgstr "" "Отключение устройства сигнализируется концентратором в пакете прерывания, " "передаваемом драйверу концентратора. Информация об изменении состояния " "указывает, на каком порту произошло изменение подключения. Метод отключения " "устройства для всех драйверов устройств, подключенных к этому порту, " "вызывается, и структуры очищаются. Если состояние порта указывает, что за " "это время к порту было подключено устройство, начнется процедура обнаружения " "и подключения устройства. Сброс устройства вызовет последовательность " "отключения-подключения на концентраторе и будет обработан, как описано выше." #. type: Title == #: documentation/content/en/books/arch-handbook/usb/_index.adoc:164 #, no-wrap msgid "USB Drivers Protocol Information" msgstr "Информация о протоколе драйверов USB" #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:167 msgid "" "The protocol used over pipes other than the default pipe is undefined by the " "USB specification. Information on this can be found from various sources. " "The most accurate source is the developer's section on the USB home pages. " "From these pages, a growing number of deviceclass specifications are " "available. These specifications specify what a compliant device should look " "like from a driver perspective, basic functionality it needs to provide and " "the protocol that is to be used over the communication channels. The USB " "specification includes the description of the Hub Class. A class " "specification for Human Interface Devices (HID) has been created to cater " "for keyboards, tablets, bar-code readers, buttons, knobs, switches, etc. A " "third example is the class specification for mass storage devices. For a " "full list of device classes see the developers section on the USB home pages." msgstr "" "Используемый протокол для каналов, отличных от стандартного, не определен " "спецификацией USB. Информацию об этом можно найти из различных источников. " "Наиболее точный источник — раздел для разработчиков на домашних страницах " "USB. На этих страницах доступно растущее количество спецификаций классов " "устройств. Эти спецификации определяют, каким должно быть совместимое " "устройство с точки зрения драйвера, базовую функциональность, которую оно " "должно предоставлять, и протокол, используемый на каналах связи. " "Спецификация USB включает описание класса концентраторов (Hub Class). " "Спецификация класса устройств человеко-машинного интерфейса (HID) была " "создана для поддержки клавиатур, планшетов, сканеров штрих-кодов, кнопок, " "регуляторов, переключателей и т. д. Третий пример — спецификация класса " "устройств хранения данных (Mass Storage). Полный список классов устройств " "можно найти в разделе для разработчиков на домашних страницах USB." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:169 msgid "" "For many devices the protocol information has not yet been published " "however. Information on the protocol being used might be available from the " "company making the device. Some companies will require you to sign a Non -" "Disclosure Agreement (NDA) before giving you the specifications. This in " "most cases precludes making the driver open source." msgstr "" "Для многих устройств информация о протоколе ещё не опубликована. Сведения об " "используемом протоколе могут быть доступны у компании-производителя " "устройства. Некоторые компании потребуют подписания соглашения о " "неразглашении (NDA), прежде чем предоставить спецификации. В большинстве " "случаев это исключает возможность сделать драйвер открытым." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:171 msgid "" "Another good source of information is the Linux driver sources, as a number " "of companies have started to provide drivers for Linux for their devices. It " "is always a good idea to contact the authors of those drivers for their " "source of information." msgstr "" "Еще один хороший источник информации — исходные коды драйверов Linux, так " "как ряд компаний начал предоставлять драйверы для Linux для своих устройств. " "Всегда полезно связаться с авторами этих драйверов для получения информации." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:173 msgid "" "Example: Human Interface Devices The specification for the Human Interface " "Devices like keyboards, mice, tablets, buttons, dials,etc. is referred to in " "other device class specifications and is used in many devices." msgstr "" "Пример: Устройства интерфейса пользователя (HID) — Спецификация для " "устройств интерфейса пользователя, таких как клавиатуры, мыши, планшеты, " "кнопки, регуляторы и т.д., упоминается в других спецификациях классов " "устройств и используется во многих устройствах." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:175 msgid "" "For example audio speakers provide endpoints to the digital to analogue " "converters and possibly an extra pipe for a microphone. They also provide a " "HID endpoint in a separate interface for the buttons and dials on the front " "of the device. The same is true for the monitor control class. It is " "straightforward to build support for these interfaces through the available " "kernel and userland libraries together with the HID class driver or the " "generic driver. Another device that serves as an example for interfaces " "within one configuration driven by different device drivers is a cheap " "keyboard with built-in legacy mouse port. To avoid having the cost of " "including the hardware for a USB hub in the device, manufacturers combined " "the mouse data received from the PS/2 port on the back of the keyboard and " "the key presses from the keyboard into two separate interfaces in the same " "configuration. The mouse and keyboard drivers each attach to the appropriate " "interface and allocate the pipes to the two independent endpoints." msgstr "" "Например, аудиоколонки предоставляют конечные точки для цифро-аналоговых " "преобразователей и, возможно, дополнительный канал для микрофона. Они также " "предоставляют конечную точку HID в отдельном интерфейсе для кнопок и " "регуляторов на передней панели устройства. То же самое справедливо для " "класса управления монитором. Реализовать поддержку этих интерфейсов " "достаточно просто с помощью доступных библиотек ядра и пользовательского " "пространства, а также драйвера класса HID или универсального драйвера. " "Другим примером устройства с несколькими интерфейсами в одной конфигурации, " "управляемыми разными драйверами, является недорогая клавиатура со встроенным " "устаревшим портом для мыши. Чтобы избежать затрат на включение аппаратного " "обеспечения USB-концентратора в устройство, производители объединили данные " "мыши, полученные с порта PS/2 на задней панели клавиатуры, и нажатия клавиш " "в два отдельных интерфейса в одной конфигурации. Драйверы мыши и клавиатуры " "подключаются к соответствующему интерфейсу и выделяют каналы для двух " "независимых конечных точек." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:177 msgid "" "Example: Firmware download Many devices that have been developed are based " "on a general purpose processor with an additional USB core added to it. " "Since the development of drivers and firmware for USB devices is still very " "new, many devices require the downloading of the firmware after they have " "been connected." msgstr "" "Пример: Загрузка микропрограммы — многие разработанные устройства основаны " "на процессоре общего назначения с добавленным USB-ядром. Поскольку " "разработка драйверов и микропрограмм для USB-устройств всё ещё очень нова, " "многие устройства требуют загрузки микропрограммы после подключения." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:179 msgid "" "The procedure followed is straightforward. The device identifies itself " "through a vendor and product Id. The first driver probes and attaches to it " "and downloads the firmware into it. After that the device soft resets itself " "and the driver is detached. After a short pause the device announces its " "presence on the bus. The device will have changed its vendor/product/" "revision Id to reflect the fact that it has been supplied with firmware and " "as a consequence a second driver will probe it and attach to it." msgstr "" "Процедура выполняется следующим образом. Устройство идентифицирует себя " "через идентификаторы производителя и продукта. Первый драйвер проверяет его " "и подключается к нему, затем загружает в него микропрограмму. После этого " "устройство выполняет мягкую перезагрузку, и драйвер отключается. После " "небольшой паузы устройство снова появляется на шине. При этом идентификаторы " "производителя, продукта и версии устройства изменятся, что отражает факт " "загрузки микропрограммы, и в результате второй драйвер проверит его и " "подключится к нему." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:181 msgid "" "An example of these types of devices is the ActiveWire I/O board, based on " "the EZ-USB chip. For this chip a generic firmware downloader is available. " "The firmware downloaded into the ActiveWire board changes the revision Id. " "It will then perform a soft reset of the USB part of the EZ-USB chip to " "disconnect from the USB bus and again reconnect." msgstr "" "Примером таких устройств является плата ввода-вывода ActiveWire, основанная " "на чипе EZ-USB. Для этого чипа доступен универсальный загрузчик " "микропрограмм. Микропрограмма, загруженная в плату ActiveWire, изменяет " "идентификатор ревизии. Затем выполняется мягкий сброс USB-части чипа EZ-USB " "для отключения от USB-шины и повторного подключения." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:183 msgid "" "Example: Mass Storage Devices Support for mass storage devices is mainly " "built around existing protocols. The Iomega USB Zipdrive is based on the " "SCSI version of their drive. The SCSI commands and status messages are " "wrapped in blocks and transferred over the bulk pipes to and from the " "device, emulating a SCSI controller over the USB wire. ATAPI and UFI " "commands are supported in a similar fashion." msgstr "" "Пример: Поддержка устройств хранения данных в основном построена на " "существующих протоколах. Устройство Iomega USB Zipdrive основано на SCSI-" "версии их накопителя. SCSI-команды и статусные сообщения упаковываются в " "блоки и передаются через массовые каналы к устройству и от него, эмулируя " "SCSI-контроллер через USB-соединение. ATAPI и UFI команды поддерживаются " "аналогичным образом." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:185 msgid "" "The Mass Storage Specification supports 2 different types of wrapping of the " "command block.The initial attempt was based on sending the command and " "status through the default pipe and using bulk transfers for the data to be " "moved between the host and the device. Based on experience a second approach " "was designed that was based on wrapping the command and status blocks and " "sending them over the bulk out and in endpoint. The specification specifies " "exactly what has to happen when and what has to be done in case an error " "condition is encountered. The biggest challenge when writing drivers for " "these devices is to fit USB based protocol into the existing support for " "mass storage devices. CAM provides hooks to do this in a fairly straight " "forward way. ATAPI is less simple as historically the IDE interface has " "never had many different appearances." msgstr "" "Спецификация Mass Storage поддерживает 2 различных типа обёртки командного " "блока. Первоначальная попытка была основана на отправке команды и состояния " "через канал по умолчанию с использованием массовых передач для данных, " "перемещаемых между хостом и устройством. На основе опыта был разработан " "второй подход, основанный на обёртке командных и статусных блоков и их " "отправке через конечные точки массовой передачи (bulk out и bulk in). " "Спецификация точно определяет, что должно происходить и когда, а также что " "необходимо делать в случае возникновения ошибки. Наибольшую сложность при " "написании драйверов для таких устройств представляет встраивание USB-" "ориентированного протокола в существующую поддержку устройств хранения " "данных. CAM предоставляет механизмы для этого достаточно прямолинейным " "способом. С ATAPI всё менее просто, так как исторически интерфейс IDE " "никогда не имел множества различных вариантов реализации." #. type: Plain text #: documentation/content/en/books/arch-handbook/usb/_index.adoc:186 msgid "" "The support for the USB floppy from Y-E Data is again less straightforward " "as a new command set has been designed." msgstr "" "Поддержка USB-дисковода от Y-E Data также не прямолинейна, так как был " "разработан новый набор команд."