1. Why Manage Multiple Devices?
In actual projects, we often encounter scenarios like this:
- A chip has multiple identical peripherals (e.g., 3 UARTs, 4 SPIs)
- The same driver needs to support different models of devices (e.g., LED driver supports red, green, blue three LEDs)
- Multiple devices share the same operation logic, just with different parameters
Platform driver supports multiple devices; each device has an independent device node, and parameters can be individually modified in the device tree.
2. Managing Three Devices
- Define 3 device nodes in device tree
- One driver automatically identifies and manages these 3 devices
- Create 3 independent device nodes:
/dev/mychardev0,/dev/mychardev1,/dev/mychardev2 - Each device has its own
dev-id, which the driver can distinguish
3. Device Tree Modification
1. Write Device Tree Node
Modify based on the previous chapter "Device Tree + Platform Driver" as the source file
/ {
mychardev0: mychardev@0 {
compatible = "lckfb,mychardev";
reg = <0x0 0xfec00000 0x0 0x1000>;
buffer-len = <64>;
dev-id = <0x01>; // Device 1 ID
status = "okay";
};
mychardev1: mychardev@1 {
compatible = "lckfb,mychardev";
reg = <0x0 0xfec01000 0x0 0x1000>;
buffer-len = <128>;
dev-id = <0x02>; // Device 2 ID
status = "okay";
};
mychardev2: mychardev@2 {
compatible = "lckfb,mychardev";
reg = <0x0 0xfec02000 0x0 0x1000>;
buffer-len = <256>;
dev-id = <0x03>; // Device 3 ID
status = "okay";
};
};2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Key points:
- All 3 nodes have exactly the same
compatible, which is"lckfb,mychardev" - Each device has a different
dev-id(used to distinguish in the driver) - Each device has a different
buffer-len(simulating different hardware parameters) - Each device has a different
regaddress (to avoid conflicts)
2. Compile and Flash
According to the Debian12 Kernel Compilation tutorial, recompile the kernel to generate boot.img, and flash the kernel image separately to replace the device tree.
After flashing is complete, boot the board and verify the device tree nodes:
View the unpacked device tree nodes
ls /sys/firmware/devicetree/base/mychardev@*You can see devices 0~2, and the related fields are effective!
4. Write Driver
1. Create Project Directory
mkdir 13_platform_multi_deviceAnd enter the directory:
cd 13_platform_multi_device2. Driver File
In the 13_platform_multi_device directory, create the platform_multi_chardev.c driver file and write the following code:
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/of.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/slab.h>
#define DEV_NAME_PREFIX "mychardev"
#define CLASS_NAME "class_mychardev"
#define MAX_DEVICES 10
// Global variables
static struct class *class_test;
static int device_count = 0; // Current device count
// Private data for each device
struct mychardev_private {
struct cdev cdev; // Character device structure
dev_t dev_num; // Device number
u32 dev_id; // Device ID
u32 buffer_len; // Buffer size
resource_size_t reg_base; // Register base address
int minor; // Minor device number
struct device *device; // Device pointer
};
// ==================== Character Device Operations ====================
static int chrdev_open(struct inode *inode, struct file *file)
{
struct mychardev_private *priv;
// Get cdev via inode, then get private data via container_of
priv = container_of(inode->i_cdev, struct mychardev_private, cdev);
file->private_data = priv; // Save to file private data
printk(KERN_INFO "mychardev%d: open (dev-id=0x%02X)\n",
priv->minor, priv->dev_id);
return 0;
}
static ssize_t chrdev_read(struct file *file, char __user *buf, size_t size, loff_t *off)
{
struct mychardev_private *priv = file->private_data;
printk(KERN_INFO "mychardev%d: read (dev-id=0x%02X, buffer-len=%u)\n",
priv->minor, priv->dev_id, priv->buffer_len);
return 0;
}
static ssize_t chrdev_write(struct file *file, const char __user *buf, size_t size, loff_t *off)
{
struct mychardev_private *priv = file->private_data;
printk(KERN_INFO "mychardev%d: write (dev-id=0x%02X, size=%zu)\n",
priv->minor, priv->dev_id, size);
return size;
}
static int chrdev_release(struct inode *inode, struct file *file)
{
struct mychardev_private *priv = file->private_data;
printk(KERN_INFO "mychardev%d: release\n", priv->minor);
return 0;
}
static struct file_operations cdev_fops = {
.owner = THIS_MODULE,
.open = chrdev_open,
.read = chrdev_read,
.write = chrdev_write,
.release = chrdev_release,
};
// ==================== Platform Driver Functions ====================
static const struct of_device_id mychardev_of_match[] = {
{ .compatible = "lckfb,mychardev" },
{ }
};
MODULE_DEVICE_TABLE(of, mychardev_of_match);
static int mychardev_probe(struct platform_device *pdev)
{
int ret;
struct mychardev_private *priv;
struct resource *res;
char dev_name[32];
printk(KERN_INFO "========================================\n");
printk(KERN_INFO "mychardev: probe called (device %d)\n", device_count);
// Allocate private data
priv = devm_kzalloc(&pdev->dev, sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
priv->minor = device_count++; // Allocate minor device number
// ========== Get device tree resources ==========
// Get register resource
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (res) {
priv->reg_base = res->start;
printk(KERN_INFO "mychardev%d: Register base address=0x%llx\n",
priv->minor, (unsigned long long)priv->reg_base);
}
// Read buffer-len property
if (of_property_read_u32(pdev->dev.of_node, "buffer-len", &priv->buffer_len)) {
priv->buffer_len = 64; // Default value
}
printk(KERN_INFO "mychardev%d: buffer-len=%u\n", priv->minor, priv->buffer_len);
// Read dev-id property
if (of_property_read_u32(pdev->dev.of_node, "dev-id", &priv->dev_id)) {
priv->dev_id = 0;
}
printk(KERN_INFO "mychardev%d: dev-id=0x%02X\n", priv->minor, priv->dev_id);
// ========== Register character device ==========
// Allocate device number (minor device number starts from minor)
ret = alloc_chrdev_region(&priv->dev_num, priv->minor, 1, DEV_NAME_PREFIX);
if (ret < 0) {
printk(KERN_ERR "mychardev%d: alloc_chrdev_region failed\n", priv->minor);
return ret;
}
printk(KERN_INFO "mychardev%d: Device number major=%d, minor=%d\n",
priv->minor, MAJOR(priv->dev_num), MINOR(priv->dev_num));
// Initialize and register cdev
cdev_init(&priv->cdev, &cdev_fops);
priv->cdev.owner = THIS_MODULE;
ret = cdev_add(&priv->cdev, priv->dev_num, 1);
if (ret < 0) {
unregister_chrdev_region(priv->dev_num, 1);
return ret;
}
// Create device class (only when first device is created)
if (!class_test) {
class_test = class_create(THIS_MODULE, CLASS_NAME);
if (IS_ERR(class_test)) {
cdev_del(&priv->cdev);
unregister_chrdev_region(priv->dev_num, 1);
return PTR_ERR(class_test);
}
}
// Create device node (names: mychardev0, mychardev1, mychardev2)
snprintf(dev_name, sizeof(dev_name), "%s%d", DEV_NAME_PREFIX, priv->minor);
priv->device = device_create(class_test, &pdev->dev, priv->dev_num, NULL, dev_name);
if (IS_ERR(priv->device)) {
cdev_del(&priv->cdev);
unregister_chrdev_region(priv->dev_num, 1);
return PTR_ERR(priv->device);
}
platform_set_drvdata(pdev, priv);
printk(KERN_INFO "mychardev%d: Driver loaded successfully!/dev/%s created\n",
priv->minor, dev_name);
printk(KERN_INFO "========================================\n");
return 0;
}
static void mychardev_remove(struct platform_device *pdev)
{
struct mychardev_private *priv = platform_get_drvdata(pdev);
printk(KERN_INFO "mychardev%d: remove (dev-id=0x%02X)\n",
priv->minor, priv->dev_id);
device_destroy(class_test, priv->dev_num);
cdev_del(&priv->cdev);
unregister_chrdev_region(priv->dev_num, 1);
device_count--;
// If all devices are removed, destroy device class
if (device_count == 0) {
class_destroy(class_test);
class_test = NULL;
}
printk(KERN_INFO "mychardev%d: Driver unloaded successfully!\n", priv->minor);
}
static struct platform_driver mychardev_driver = {
.probe = mychardev_probe,
.remove_new = mychardev_remove,
.driver = {
.name = "mychardev",
.of_match_table = mychardev_of_match,
},
};
module_platform_driver(mychardev_driver);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("LCKFB");
MODULE_DESCRIPTION("Platform Driver for Multiple Devices");2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
3. Driver Explanation
Key differences from single-device driver:
Core private data structure:
struct mychardev_private {
struct cdev cdev; // Character device structure (independent for each device)
dev_t dev_num; // Device number (different for each device)
u32 dev_id; // Device ID read from device tree
u32 buffer_len; // Buffer size read from device tree
resource_size_t reg_base; // Register base address
int minor; // Minor device number (0, 1, 2, ... )
struct device *device; // Pointer to device created by device_create
};2
3
4
5
6
7
8
9
This data structure uses
devm_kzallocto allocate space for storing each device's instantiatedmychardev_privatedata. We don't need to manually destroy it in theremovefunction; it is automatically released when the relevant device is removed.
Device number:
static int device_count = 0; // Current device count
priv->minor = device_count++; // Allocate minor device number
// Allocate device number (minor device number starts from minor)
ret = alloc_chrdev_region(&priv->dev_num, priv->minor, 1, DEV_NAME_PREFIX);
if (ret < 0) {
printk(KERN_ERR "mychardev%d: alloc_chrdev_region failed\n", priv->minor);
return ret;
}2
3
4
5
6
7
8
9
10
When allocating device numbers, we don't need to manage the major device number; it's automatically allocated. We need to set a starting value for the minor device number. A global variable records what the next minor device number starting value should be, preventing minor device number duplication and confusion.
Register character device:
// Initialize and register cdev
cdev_init(&priv->cdev, &cdev_fops);
priv->cdev.owner = THIS_MODULE;
ret = cdev_add(&priv->cdev, priv->dev_num, 1);
if (ret < 0) {
unregister_chrdev_region(priv->dev_num, 1);
return ret;
}2
3
4
5
6
7
8
The function registers different devices based on the different device numbers (major + minor device number).
Create device class (create only once):
// Create device class (only when first device is created)
if (!class_test) {
class_test = class_create(THIS_MODULE, CLASS_NAME);
if (IS_ERR(class_test)) {
cdev_del(&priv->cdev);
unregister_chrdev_region(priv->dev_num, 1);
return PTR_ERR(class_test);
}
}2
3
4
5
6
7
8
9
All devices use the same driver and belong to the same class, so it only needs to be created once.
Create device node (each device is independent):
// Create device node (names: mychardev0, mychardev1, mychardev2)
snprintf(dev_name, sizeof(dev_name), "%s%d", DEV_NAME_PREFIX, priv->minor);
priv->device = device_create(class_test, &pdev->dev, priv->dev_num, NULL, dev_name);2
3
We need to concatenate names based on device name and device number, creating different device nodes under
/dev, so we can directly access different devices:/dev/mychardev0/dev/mychardev1/dev/mychardev2
Save private data:
platform_set_drvdata(pdev, priv);This allows retrieving private data in
removeand targeting destruction of the specified device.
Device removal:
static void mychardev_remove(struct platform_device *pdev)
{
struct mychardev_private *priv = platform_get_drvdata(pdev);
printk(KERN_INFO "mychardev%d: remove (dev-id=0x%02X)\n",
priv->minor, priv->dev_id);
device_destroy(class_test, priv->dev_num);
cdev_del(&priv->cdev);
unregister_chrdev_region(priv->dev_num, 1);
device_count--;
// If all devices are removed, destroy device class
if (device_count == 0) {
class_destroy(class_test);
class_test = NULL;
}
printk(KERN_INFO "mychardev%d: Driver unloaded successfully!\n", priv->minor);
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
removewill be called multiple times (once for each device)- Device class is only destroyed when the last device is removed
Completion flow chart:
Memory layout:
Summary:
| Purpose | Code | |
|---|---|---|
| Private data structure | Independently store data for each device | mychardev_private |
| container_of | Get structure address via member address | container_of(inode->i_cdev, ...) |
| platform_set_drvdata | Save private data to pdev | platform_set_drvdata(pdev, priv) |
| platform_get_drvdata | Get private data from pdev | platform_get_drvdata(pdev) |
| devm_kzalloc | Automatic memory management | Auto-released on device removal |
| device_count | Allocate minor device numbers | 0, 1, 2, ... |
| file->private_data | Pass data between open/read/write | Stores priv |
4. Makefile
In the 13_platform_multi_device directory, create the Makefile file and write the following code:
export ARCH=arm64
# Cross compiler path
export CROSS_COMPILE=/home/lckfb/TaishanPi-3-Linux/prebuilts/gcc/linux-x86/aarch64/gcc-arm-10.3-2021.07-x86_64-aarch64-none-linux-gnu/bin/aarch64-none-linux-gnu-
# Driver module name
obj-m += platform_multi_chardev.o
# Kernel source directory
KDIR := /home/lckfb/TaishanPi-3-Linux/kernel-6.1
PWD ? = $(shell pwd)
all:
make -C $(KDIR) M=$(PWD) modules
clean:
make -C $(KDIR) M=$(PWD) clean2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
CROSS_COMPILE: Still the compiler path prefix from the SDK.KDIR: Still the kernel source directory.- Need to change what follows
obj-m +=toplatform_multi_chardev.o
5. Compile
We run the following command in the 13_platform_multi_device directory:
makeIt will compile and generate the .ko file.
5. Testing
Copy platform_multi_chardev.ko to the development board (USB drive, TF card, or SSH), and use the following command to load:
sudo insmod platform_multi_chardev.koAll three devices have been created.
View all mychardev devices under /dev:
ls /dev/mychardev*Test writing to each device:
# Grant permissions to all mychardev devices
sudo chmod 666 /dev/mychardev*
# Run the following commands in order to see output
echo "test0" > /dev/mychardev0
echo "test1" > /dev/mychardev1
echo "test2" > /dev/mychardev22
3
4
5
6
7
Unload driver:
sudo rmmod platform_multi_chardevYou can use
sudo lsmodcommand to view currently loaded module information.