- Как написать свой первый Linux device driver
- Подготовительные работы
- Инициализация
- Удаление
- Linux Device Drivers, Third Edition
- LDD3 chapter files
- Downloads
- Essential Linux Device Drivers
- Материалы для изучения Linux Kernel и написания модулей/драйверов
- Essential Linux Device Drivers
- If You’re an Educator
- If You’re a Student
- Overview
- Description
- Series
Как написать свой первый Linux device driver
Здравствуйте, дорогие хабрачитатели.
Цель данной статьи — показать принцип реализации драйверов устройств в системе Linux, на примере простого символьного драйвера.
Для меня же, главной целью является подвести итог и сформировать базовые знания для написания будущих модулей ядра, а также получить опыт изложения технической литературы для публики, т.к. через полгода я буду выступать со своим дипломным проектом (да я студент).
Это моя первая статья, пожалуйста не судите строго!
Получилось слишком много букв, поэтому я принял решение разделить статью на три части:
Часть 1 — Введение, инициализация и очистка модуля ядра.
Часть 2 — Функции open, read, write и trim.
Часть 3 — Пишем Makefile и тестируем устройство.
Перед вступлением, хочу сказать, что здесь будут изложены базовые вещи, более подробная информация будет изложена во второй и последней части данной статьи.
Подготовительные работы
Спасибо Kolyuchkin за уточнения.
Символьный драйвер (Char driver) — это, драйвер, который работает с символьными устройствами.
Символьные устройства — это устройства, к которым можно обращаться как к потоку байтов.
Пример символьного устройства — /dev/ttyS0, /dev/tty1.
К вопросу про проверсию ядра:
Драйвер представляет каждое символьное устройство структурой scull_dev, а также предостовляет интерфейс cdev к ядру.
Устройство будет представлять связный список указателей, каждый из которых указывает на структуру scull_qset.
Для наглядности посмотрите на картинку.
Для регистрации устройства, нужно задать специальные номера, а именно:
MAJOR — старший номер (является уникальным в системе).
MINOR — младший номер (не является уникальным в системе).
В ядре есть механизм, который позволяет регистрировать специализированные номера вручную, но такой подход нежелателен и лучше вежливо попросить ядро динамически выделить их для нас. Пример кода будет ниже.
После того как мы определили номера для нашего устройства, мы должны установить связь между этими номерами и операциями драйвера. Это можно сделать используя структуру file_operations.
В ядре есть специальные макросы module_init/module_exit, которые указывают путь к функциям инициализации/удаления модуля. Без этих определений функции инициализации/удаления никогда не будут вызваны.
Здесь будем хранить базовую информацию об устройстве.
Последним этапом подготовительной работы будет подключение заголовочных файлов.
Краткое описание приведено ниже, но если вы хотите копнуть поглубже, то добро пожаловать на прекрасный сайт: lxr
Инициализация
Теперь давайте посмотрим на функцию инициализации устройства.
Первым делом, вызывая alloc_chrdev_region мы регистрируем диапазон символьных номеров устройств и указываем имя устройства. После вызовом MAJOR(dev) мы получаем старший номер.
Далее проверяется вернувшееся значение, если оно является кодом ошибки, то выходим из функции. Стоит отметить, что при разработке реального драйвера устройства следует всегда проверять возвращаемые значения, а также указатели на любые элементы (NULL?).
Если вернувшееся значение не является кодом ошибки, продолжаем выполнять инициализацию.
Выделяем память, делая вызов функции kmalloc и обязательно проверяем указатель на NULL.
Стоит упомянуть, что вместо вызова двух функций kmalloc и memset, можно использовать один вызов kzalloc, который выделят область памяти и инициализирует ее нулями.
Продолжаем инициализацию. Главная здесь функция — это scull_setup_cdev, о ней мы поговорим чуть ниже. MKDEV служит для хранения старший и младших номеров устройств.
Возвращаем значение или обрабатываем ошибку и удаляем устройство.
Выше были представлены структуры scull_dev и cdev, которые реализуют интерфейс между нашим устройством и ядром. Функция scull_setup_cdev выполняет инициализацию и добавление структуры в систему.
Удаление
Функция scull_cleanup_module вызывается при удалении модуля устройства из ядра.
Обратный процесс инициализации, удаляем структуры устройств, освобождаем память и удаляем выделенные ядром младшие и старшие номера.
С удовольствием выслушаю конструктивную критику и буду ждать feedback’a.
Если вы нашли ошибки или я не правильно изложил материал, пожалуйста, укажите мне на это.
Для более быстрой реакции пишите в ЛС.
Источник
Linux Device Drivers, Third Edition
This book is available under the terms of the Creative Commons Attribution-ShareAlike 2.0 license. That means that you are free to download and redistribute it. The development of the book was made possible, however, by those who purchase a copy from O’Reilly or elsewhere.
LDD3 is current as of the 2.6.10 kernel. See the LWN 2.6 API changes page for information on subsequent changes.
LDD3 chapter files
Title page Copyright and credits Table of Contents Preface Chapter 1: An Introduction to Device Drivers Chapter 2: Building and Running Modules Chapter 3: Char Drivers Chapter 4: Debugging Techniques Chapter 5: Concurrency and Race Conditions Chapter 6: Advanced Char Driver Operations Chapter 7: Time, Delays, and Deferred Work Chapter 8: Allocating Memory Chapter 9: Communicating with Hardware Chapter 10: Interrupt Handling Chapter 11: Data Types in the Kernel Chapter 12: PCI Drivers Chapter 13: USB Drivers Chapter 14: The Linux Device Model Chapter 15: Memory Mapping and DMA Chapter 16: Block Drivers Chapter 17: Network Drivers Chapter 18: TTY Drivers Index
Downloads
Copyright © 2021, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds
Источник
Essential Linux Device Drivers
“Probably the most wide ranging and complete Linux device driver book I’ve read.”
—Alan Cox, Linux Guru and Key Kernel Developer
“Very comprehensive and detailed, covering almost every single Linux device driver type.”
— Theodore Ts’o, First Linux Kernel Developer in North America and Chief Platform Strategist of the Linux Foundation
The Most Practical Guide to Writing Linux Device Drivers
Linux now offers an exceptionally robust environment for driver development: with today’s kernels, what once required years of development time can be accomplished in days. In this practical, example-driven book, one of the world’s most experienced Linux driver developers systematically demonstrates how to develop reliable Linux drivers for virtually any device. Essential Linux Device Drivers is for any programmer with a working knowledge of operating systems and C, including programmers who have never written drivers before. Sreekrishnan Venkateswaran focuses on the essentials, bringing together all the concepts and techniques you need, while avoiding topics that only matter in highly specialized situations. Venkateswaran begins by reviewing the Linux 2.6 kernel capabilities that are most relevant to driver developers. He introduces simple device classes; then turns to serial buses such as I2C and SPI; external buses such as PCMCIA, PCI, and USB; video, audio, block, network, and wireless device drivers; user-space drivers; and drivers for embedded Linux–one of today’s fastest growing areas of Linux development. For each, Venkateswaran explains the technology, inspects relevant kernel source files, and walks through developing a complete example.
• Addresses drivers discussed in no other book, including drivers for I2C, video, sound, PCMCIA, and different types of flash memory
• Demystifies essential kernel services and facilities, including kernel threads and helper interfaces
• Teaches polling, asynchronous notification, and I/O control
• Introduces the Inter-Integrated Circuit Protocol for embedded Linux drivers
• Covers multimedia device drivers using the Linux-Video subsystem and Linux-Audio framework
• Shows how Linux implements support for wireless technologies such as Bluetooth, Infrared, WiFi, and cellular networking
• Describes the entire driver development lifecycle, through debugging and maintenance
• Includes reference appendixes covering Linux assembly, BIOS calls, and Seq files
Источник
Материалы для изучения Linux Kernel и написания модулей/драйверов
Всё на английском! |
1) Самая лучшая книга по ядру — это исходники. Лучший сайт по исходникам ядра, я считаю
Поиск по идентификатору, например вводите struct file и вперед, смотреть как и что.
2) Начнем с русского языка. Очень хорошо описал написание дров, модулей и проччих вещей в ядре — Олег Цилюрик. Очень редко можно встретить более менее актуальный материал по ядру на русском! Очень рекомендую.
http://rus-linux.net/MyLDP/BOO. index.html
3) На opennet.ru тоже есть материал на русском, но там немного посложнее, средний уровень подготовки я считаю, но мне как новичку помогло.
4) Теперь перейдем к топовым книгам. Коротенькая, информативная, стандарт для разработчиков ядра, это конечно же Linux Device Driver, 3 издание и Adison.Wesley.Linux.Kernel.Development.3rd.Edition . По первой (LDD) я делал мноиге примеры, очень рекомендую ее. Вторая как раз по структуре ядра, идеальная прям, открываете оглавление и читаете то что интересно.
Первая книга есть в октрытом доступе, вот оффициальная ссылка.
http://lwn.net/Kernel/LDD3/
5) По написанию дров под линь, очень мало современных материалов и книг, очень прям мало. Потому что ядро развивается очень быстро, каждый день сотни коммитов, поэтому уследить трудно. Но есть еще одна хорошенькая книга. Называется Essential Linux Device Drivers.
6) Фундаментальный труд по ядру, это конечно же книга — Undestanding the linux kernel,3rd edition (почти 1000 страниц)
Рекомендую Adison.Wesley.Linux.Kernel.Development и Цирюльника, для старта самое то.
Есть еще очень хороший сайт
http://eudyptula-challenge.org/
Который высылает вам задание на почту по программированию в ядре, сложность нарастающая, начиная с hello world, заканчивая патчами в РЕАЛЬНОЕ ядро. Многие после прохождения всех заданий, реально получают работу как kernel developer\kernel hacker.[/QUOTE]
На моем гитхабе вы можете посмотреть следующие примеры (которые перекликаются с примерами из книги Linux Device Driver):
Источник
Essential Linux Device Drivers
©2008 | Pearson | Out of print
If You’re an Educator
If You’re a Student
Introducing Pearson+ 1500+ eTexts and study tools, all in one place. Subscriptions starting at $9.99/month.
K-12 educators : This link is for individuals purchasing with credit cards or PayPal only. Contact your Savvas Learning Company Account General Manager for purchase options.
Overview
Description
“Probably the most wide ranging and complete Linux device driver book I’ve read.”
—Alan Cox, Linux Guru and Key Kernel Developer
“Very comprehensive and detailed, covering almost every single Linux device driver type.”
—Theodore Ts’o, First Linux Kernel Developer in North America and Chief Platform Strategist of the Linux Foundation
The Most Practical Guide to Writing Linux Device Drivers
Linux now offers an exceptionally robust environment for driver development: with today’s kernels, what once required years of development time can be accomplished in days. In this practical, example-driven book, one of the world’s most experienced Linux driver developers systematically demonstrates how to develop reliable Linux drivers for virtually any device. Essential Linux Device Drivers is for any programmer with a working knowledge of operating systems and C, including programmers who have never written drivers before. Sreekrishnan Venkateswaran focuses on the essentials, bringing together all the concepts and techniques you need, while avoiding topics that only matter in highly specialized situations. Venkateswaran begins by reviewing the Linux 2.6 kernel capabilities that are most relevant to driver developers. He introduces simple device classes; then turns to serial buses such as I2C and SPI; external buses such as PCMCIA, PCI, and USB; video, audio, block, network, and wireless device drivers; user-space drivers; and drivers for embedded Linux–one of today’s fastest growing areas of Linux development. For each, Venkateswaran explains the technology, inspects relevant kernel source files, and walks through developing a complete example.
• Addresses drivers discussed in no other book, including drivers for I2C, video, sound, PCMCIA, and different types of flash memory
• Demystifies essential kernel services and facilities, including kernel threads and helper interfaces
• Teaches polling, asynchronous notification, and I/O control
• Introduces the Inter-Integrated Circuit Protocol for embedded Linux drivers
• Covers multimedia device drivers using the Linux-Video subsystem and Linux-Audio framework
• Shows how Linux implements support for wireless technologies such as Bluetooth, Infrared, WiFi, and cellular networking
• Describes the entire driver development lifecycle, through debugging and maintenance
• Includes reference appendixes covering Linux assembly, BIOS calls, and Seq files
Series
This product is part of the following series. Click on a series title to see the full list of products in the series.
Источник