What is linux driver model

Platform Devices and DriversВ¶

See
for the driver model interface to the platform bus: platform_device, and platform_driver. This pseudo-bus is used to connect devices on busses with minimal infrastructure, like those used to integrate peripherals on many system-on-chip processors, or some “legacy” PC interconnects; as opposed to large formally specified ones like PCI or USB.

Platform devicesВ¶

Platform devices are devices that typically appear as autonomous entities in the system. This includes legacy port-based devices and host bridges to peripheral buses, and most controllers integrated into system-on-chip platforms. What they usually have in common is direct addressing from a CPU bus. Rarely, a platform_device will be connected through a segment of some other kind of bus; but its registers will still be directly addressable.

Platform devices are given a name, used in driver binding, and a list of resources such as addresses and IRQs:

Platform driversВ¶

Platform drivers follow the standard driver model convention, where discovery/enumeration is handled outside the drivers, and drivers provide probe() and remove() methods. They support power management and shutdown notifications using the standard conventions:

Note that probe() should in general verify that the specified device hardware actually exists; sometimes platform setup code can’t be sure. The probing can use device resources, including clocks, and device platform_data.

Platform drivers register themselves the normal way:

Or, in common situations where the device is known not to be hot-pluggable, the probe() routine can live in an init section to reduce the driver’s runtime memory footprint:

Kernel modules can be composed of several platform drivers. The platform core provides helpers to register and unregister an array of drivers:

If one of the drivers fails to register, all drivers registered up to that point will be unregistered in reverse order. Note that there is a convenience macro that passes THIS_MODULE as owner parameter:

Device EnumerationВ¶

As a rule, platform specific (and often board-specific) setup code will register platform devices:

The general rule is to register only those devices that actually exist, but in some cases extra devices might be registered. For example, a kernel might be configured to work with an external network adapter that might not be populated on all boards, or likewise to work with an integrated controller that some boards might not hook up to any peripherals.

In some cases, boot firmware will export tables describing the devices that are populated on a given board. Without such tables, often the only way for system setup code to set up the correct devices is to build a kernel for a specific target board. Such board-specific kernels are common with embedded and custom systems development.

In many cases, the memory and IRQ resources associated with the platform device are not enough to let the device’s driver work. Board setup code will often provide additional information using the device’s platform_data field to hold additional information.

Embedded systems frequently need one or more clocks for platform devices, which are normally kept off until they’re actively needed (to save power). System setup also associates those clocks with the device, so that calls to clk_get(&pdev->dev, clock_name) return them as needed.

Legacy Drivers: Device ProbingВ¶

Some drivers are not fully converted to the driver model, because they take on a non-driver role: the driver registers its platform device, rather than leaving that for system infrastructure. Such drivers can’t be hotplugged or coldplugged, since those mechanisms require device creation to be in a different system component than the driver.

The only “good” reason for this is to handle older system designs which, like original IBM PCs, rely on error-prone “probe-the-hardware” models for hardware configuration. Newer systems have largely abandoned that model, in favor of bus-level support for dynamic configuration (PCI, USB), or device tables provided by the boot firmware (e.g. PNPACPI on x86). There are too many conflicting options about what might be where, and even educated guesses by an operating system will be wrong often enough to make trouble.

Читайте также:  Windows 10 иконки после перезагрузки

This style of driver is discouraged. If you’re updating such a driver, please try to move the device enumeration to a more appropriate location, outside the driver. This will usually be cleanup, since such drivers tend to already have “normal” modes, such as ones using device nodes that were created by PNP or by platform device setup.

None the less, there are some APIs to support such legacy drivers. Avoid using these calls except with such hotplug-deficient drivers:

You can use platform_device_alloc() to dynamically allocate a device, which you will then initialize with resources and platform_device_register() . A better solution is usually:

You can use platform_device_register_simple() as a one-step call to allocate and register a device.

Device Naming and Driver BindingВ¶

The platform_device.dev.bus_id is the canonical name for the devices. It’s built from two components:

platform_device.name … which is also used to for driver matching.

platform_device.id … the device instance number, or else “-1” to indicate there’s only one.

These are concatenated, so name/id “serial”/0 indicates bus_id “serial.0”, and “serial/3” indicates bus_id “serial.3”; both would use the platform_driver named “serial”. While “my_rtc”/-1 would be bus_id “my_rtc” (no instance id) and use the platform_driver called “my_rtc”.

Driver binding is performed automatically by the driver core, invoking driver probe() after finding a match between device and driver. If the probe() succeeds, the driver and device are bound as usual. There are three different ways to find such a match:

Whenever a device is registered, the drivers for that bus are checked for matches. Platform devices should be registered very early during system boot.

When a driver is registered using platform_driver_register(), all unbound devices on that bus are checked for matches. Drivers usually register later during booting, or by module loading.

Registering a driver using platform_driver_probe() works just like using platform_driver_register(), except that the driver won’t be probed later if another device registers. (Which is OK, since this interface is only for use with non-hotpluggable devices.)

Early Platform Devices and DriversВ¶

The early platform interfaces provide platform data to platform device drivers early on during the system boot. The code is built on top of the early_param() command line parsing and can be executed very early on.

Example: “earlyprintk” class early serial console in 6 steps

1. Registering early platform device dataВ¶

The architecture code registers platform device data using the function early_platform_add_devices(). In the case of early serial console this should be hardware configuration for the serial port. Devices registered at this point will later on be matched against early platform drivers.

2. Parsing kernel command lineВ¶

The architecture code calls parse_early_param() to parse the kernel command line. This will execute all matching early_param() callbacks. User specified early platform devices will be registered at this point. For the early serial console case the user can specify port on the kernel command line as “earlyprintk=serial.0” where “earlyprintk” is the class string, “serial” is the name of the platform driver and 0 is the platform device id. If the id is -1 then the dot and the id can be omitted.

3. Installing early platform drivers belonging to a certain classВ¶

The architecture code may optionally force registration of all early platform drivers belonging to a certain class using the function early_platform_driver_register_all(). User specified devices from step 2 have priority over these. This step is omitted by the serial driver example since the early serial driver code should be disabled unless the user has specified port on the kernel command line.

4. Early platform driver registrationВ¶

Compiled-in platform drivers making use of early_platform_init() are automatically registered during step 2 or 3. The serial driver example should use early_platform_init(“earlyprintk”, &platform_driver).

5. Probing of early platform drivers belonging to a certain classВ¶

The architecture code calls early_platform_driver_probe() to match registered early platform devices associated with a certain class with registered early platform drivers. Matched devices will get probed(). This step can be executed at any point during the early boot. As soon as possible may be good for the serial port case.

Читайте также:  При загрузке windows иероглифы

6. Inside the early platform driver probe()В¶

The driver code needs to take special care during early boot, especially when it comes to memory allocation and interrupt registration. The code in the probe() function can use is_early_platform_device() to check if it is called at early platform device or at the regular platform device time. The early serial driver performs register_console() at this point.

For further information, see
.

© Copyright The kernel development community.

Источник

Русские Блоги

Модель драйвера платформы драйвера LINUX

1. Введение

Начиная с Linux2.6, в Linux добавлен набор механизмов управления дисками и регистрации —Модель водителя автобуса платформы, платформа platform bus — это виртуальная шина, platform_device — соответствующее устройство, platform_driver — это соответствующий драйвер, в этой модели устройства вам нужно позаботиться о трех объектах: bus, device и driver, а шина связывает устройство и драйвер. .В системе Каждый раз, когда устройство регистрируется, оно будет искать соответствующий драйвер. Напротив, каждый раз, когда система регистрирует драйвер, она будет искать подходящее устройство, и сопоставление выполняется шиной. -c named platform_device не является символьным устройством. Концепция сопоставления блочных и сетевых устройств — это дополнительный метод, предоставляемый системой Linux. Преимущество этого заключается в том, что разработчики могут разделять относительно стабильные и неизменяемые драйверы и могут соединять соответствующие устройства через автобусная шина. Устройство-устройство должно только предоставить конфигурацию базового оборудования, связанного с оборудованием, например io, прерывания и т. д. (То есть разделить мысль, а подсистема ввода представляет собой многоуровневую мысль), если параметры устройства изменены, или если изменено устройство того же типа, то нужно изменить только данные, и устройством можно управлять без изменения кода.
Структура модели драйвера устройства показана на рисунке ниже.

bus:
Шина используется в качестве канала связи между хостом и периферийными устройствами. Некоторые шины относительно стандартизированы и образуют множество протоколов. Например, PCI, USB, 1394, IIC и т. д. Любое устройство может выбрать подходящая шина. Подключение к хосту. Конечно, хост также может быть самим процессором.
driver:
Драйвер — это программный интерфейс, который обеспечивает работу при работающем ЦП. Для нормальной работы все устройства должны иметь соответствующий драйвер. Драйвер может управлять несколькими похожими или совершенно разными. Код устройства. и часть драйвера — относительно стабильный код
device:
Устройство — это физический объект, подключенный к шине. Устройство разделено на функции. Устройства с одинаковой функцией классифицируются в класс (Class). Например, звуковое оборудование (относящееся к звук) счетчик), устройства ввода (мышь, клавиатура, джойстик и т. д.), код в части устройства — это код, связанный с оборудованием

2. Углубленный анализ

2.1 инициализация модуля платформы

Инициализация шаблона платформы завершается функцией platform_bus_init. Эта функция вызывается на этапе запуска ядра. Видно, что функция регистрирует шину (platform_bus_type) на этапе запуска. После вызова функции bus_register, связанные с платформой файлы будут сгенерированы в пользовательском пространстве (топологии), sys / bus / platform / devices используется для хранения устройств платформы, а / sys / bus / platform / drivers используется для хранения драйверов платформы. Давайте сначала обратим внимание на переданные параметры in функцией регистрации шины bus_register Структура данных, посмотрите вниз

Видно, что bus_register (& platform_bus_type) зарегистрировал шину с именем «платформа», установил свойства шины, добавил переменные среды и т. Д. Мы фокусируемся на platform_match и platform_probe, platform_match — это функция сопоставления драйверов, которая определяет, будет ли устройство и совпадение драйвера, да Связано с системой шины. Ядро драйвера завершает сопоставление путем сопоставления. Каждый раз, когда устройство добавляется к шине, ядро ​​драйвера просматривает список драйверов на шине, чтобы найти драйвер устройства. Каждый раз, когда драйвер добавляется в шина, ядро ​​драйвера проходит через устройства на шине. Связанный список ищет устройства, которые могут управляться драйвером. В настоящее время match обычно выполняет только обработку сопоставления, зависящую от шины. В зондировании зонд выполняет обнаружение сопоставления, связанного с устройством, инициализация устройства, выделение ресурсов и т. д. Для совпадения обхода, если совпадение и Если все зонды успешны, конец совпадения успешен. Если совпадение успешное, а зонд не соответствует, продолжайте поиск, чтобы найти совпадение. Если обход заканчивается и не найдено успешного совпадения, это означает, что для драйвера нет управляемого устройства и нет подходящего устройства для устройства.

посмотрите вниз

Можно видеть, что в функции сопоставления переменная типа struct platform_device * получается с помощью макроса container_of. Переменная указывает на устройство устройства на платформе. Устройство и имя члена драйвера сравниваются. То же самое то же самое, совпадение прошло успешно.Теперь, когда шина уже есть, затем нам нужно зарегистрировать платформенное устройство platform_device (функция platform_device_register), зарегистрировать драйвер платформы platform_driver (функция platform_driver_register), продолжить смотреть вниз

Читайте также:  Windows расшарить сетевую папку

Функциональный прототип устройства, зарегистрированного на платформе удаления, показан выше (drivers / base / platform.c), давайте посмотрим на конкретную структуру данных ниже.

2.2 структура данных платформы

2.2.1 platform_device

заplatform_deviceОпределение выглядит следующим образом (include / linux / platform_devices.h)

Значение параметра:
name: имя устройства, которое заменит device-> dev_id и будет использоваться в качестве имени каталога, отображаемого в sys / device.
id: идентификатор устройства, используемый для нумерации устройства, вставленного в шину и имеющего то же имя. Если устройство только одно, введите -1.
dev: структура устройства, соответствующая / sys / platform / device
num_resources: количество ресурсов.
resource: resource: описание ресурса устройства, выделенное структурой struct resource (include / linux / ioport.h).
Структура ресурсов структуры также находится в центре внимания оборудования платформы нашей платформы, которое используется для хранения информации о ресурсах оборудования, такой как адрес ввода-вывода, номер прерывания и т. д. Определение: следующее:

Процесс вызова функции:
platform_device_register // регистрируем платформенное устройство
platform_device_add // Добавить платформенное устройство
device_add // Добавить устройство и сохранить информацию о структуре platform_device в структуре устройства
bus_add_device // Добавить устройство в связанный список разработчиков на шине платформы
bus_attach_device // Устройство соответствует шине платформы
device_attach
bus_for_each_drv // Сопоставление элементов списка drv на шине платформы по очереди
__device_attach
driver_probe_device
drv-> bus-> match (dev, drv) // Вызов функции .match для platform_bus_type для сопоставления

2.2.2 platform_driver

remove () Удалить устройство
После удаления устройства вызовите этот метод, чтобы завершить часть работы по очистке. Например, удалите устройство в списке устройств в драйвере устройства.
shutdown () завершение работы системы
При выключении системы вызовите этот метод, чтобы выключить устройство.
suspend () Устройство засыпает (приостанавливает).
Этот метод вызывается, когда устройство находится в спящем (приостановленном) режиме. Обычно в этом методе устройство находится в состоянии низкого энергопотребления.
возобновить () устройство возобновить
Этот метод вызывается, когда устройство выходит из спящего режима.
pm () управление питанием
У некоторых устройств есть переходы между состояниями питания. Есть много способов реализовать этот процесс внутри структуры.
probe () функция зонда
probe выполняет обнаружение соответствия устройства, инициализацию устройства, выделение ресурсов и т. д.
Процесс вызова функции:
platform_driver_register // зарегистрировать драйвер платформы
driver_register
bus_add_driver // Добавить драйвер в список DRV на шине платформы
driver_attach
bus_for_each_dev // Сопоставьте элементы связанного списка разработчиков на шине платформы по очереди
__driver_attach
driver_probe_device
drv-> bus-> match (dev, drv) // Вызов функции .match для platform_bus_type для сопоставления

2.2.3 Резюме

Когда platform_device_register (или platform_driver_register) вызывается для регистрации platform_device (или platform_driver), он сначала будет добавлен в шину платформы, а platform_driver (или platform_device) на шине платформы будет согласован по очереди. Принцип реализации заключается в сравнении device и член драйвера .name, если совпадение совпадает, совпадение успешное, и затем вызывается функция .probe для platform_driver. Среди них platform_device хранит ресурсы устройства (код, тесно связанный с оборудованием, легко изменить), platform_driver использует ресурсы (более стабильный код), поэтому, когда мы меняем аппаратные ресурсы, наш верхний уровень использует ресурсы. Почти нет необходимости изменять часть кода.

3 написание кода



led_device.c

После компиляции приведенного выше кода формируются файлы led_driver.ko, led_device.ko. Эти два файла будут объединены в пары в соответствии с именами в зарегистрированных led_driver и led_dev после вставки. Если они согласованы, вызовите функцию проверки в led_driver. c, чтобы мы могли видеть, что последовательный порт печатает «led_probe», а затем работу по получению ресурсов устройства. После получения ресурсов GPIO мы выполняем ./test on, чтобы включить свет, и ./test off, чтобы выключить свет. Когда мы выполняем rmmod led_device.ko В это время соответствующий драйвер вызовет свою собственную функцию удаления для освобождения ресурсов

Интеллектуальная рекомендация

Пошаговая загрузка файла Spring MVC-09 (на основе файла загрузки клиента Servlet3.0 + Html5)

пример тестовое задание Исходный код Несмотря на загрузку файлов в Servlet3.0 +, мы можем очень легко программировать на стороне сервера, но пользовательский интерфейс не очень дружелюбен. Одна HTML-ф.

Создайте многоканальное окно в приложениях Win32

Создайте многоканальное окно в приложениях Win32, создайте несколько оконных объектов одного и того же класса Windows, а окна объектов разных классов окон. .

Путь к рефакторингу IOS-APP (3) Введение в модульное тестирование

IOS-APP реконструкция дороги (1) структура сетевых запросов IOS-APP реконструкция дороги (два) Модельный дизайн При рефакторинге нам нужна форма, позволяющая вносить смелые изменения, обеспечивая при .

Tree——No.617 Merge Two Binary Trees

Problem: Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge them into a new bin.

Источник

Оцените статью