要点:
(1)第一次调用of_find_compatible_node的时候,第一个参数为NULL
(2)后续第n次调用of_find_compatible_node,第一个参数为第n-1次调用of_find_compatible_node的返回值
(3)of_find_compatible_node的返回值node,使用完毕后必须调用of_find_compatible_node或of_node_put释放掉
#include <linux/of.h>
#include <linux/of_address.h> // of_address_to_resource
#include <linux/of_irq.h> // irq_of_parse_and_map
#include <linux/module.h>
static int __init test_init(void)
{
int ret;
struct device_node *node;
struct resource res;
unsigned int irq = 0;
// 循环遍历设备树中所有指定compatible的节点
// node使用完毕后必须调用of_find_compatible_node或of_node_put释放掉
node = NULL;
while ((node = of_find_compatible_node(node, NULL, "fsl,imx6ul-gpt")) != NULL)
{
ret = of_address_to_resource(node, 0, &res);
if (ret == 0)
{
pr_err("name=%s, full_name=%s, start=0x%08x\n", node->name, node->full_name, res.start);
if (res.start == 0x020e8000)
{
// 已找到gpt2节点
irq = irq_of_parse_and_map(node, 0); // 解析interrupts属性, 得到linux中断号
pr_err("found gpt2 node: irq=%d\n", irq);
of_node_put(node); // 释放节点
break;
}
}
else
pr_err("name=%s, full_name=%s\n", node->name, node->full_name);
}
if (irq == 0)
{
// 没有找到gpt2节点, 或者解析gpt2节点的interrupts属性失败
pr_err("no IRQ found\n");
return -ENODEV;
}
return 0;
}
static void __exit test_exit(void)
{
}
module_init(test_init);
module_exit(test_exit);
MODULE_AUTHOR("Oct1158");
MODULE_LICENSE("GPL");
程序运行结果:
oct1158@alientek:~/learn_drivers/dts_myboard2/gpiospi_test$ sudo insmod search_nodes.ko
[ 1265.669315] name=gpt, full_name=/soc/aips-bus@02000000/gpt@02098000, start=0x02098000
[ 1265.677645] name=gpt, full_name=/soc/aips-bus@02000000/gpt@020e8000, start=0x020e8000
[ 1265.687307] found gpt2 node: irq=213