新增一個bus的範例程式如下,這個範例新增了一個bus叫testbus。這是一個空的bus,只有基本的sysfs entry,沒有任何的device和driver註冊到該bus,所以/sys/bus/testbus下的devices和drivers folder都是空的。
範例程式很短,一目了然,不需要說明。
空的bus
#include <linux/module.h>
#include <linux/kobject.h>
#include <linux/device.h>
static int test_bus_match(struct device* device, struct device_driver* driver);
extern struct bus_type test_bus_type;
struct bus_type test_bus_type =
{
.name = "testbus",
.match= test_bus_match
};
EXPORT_SYMBOL(test_bus_type); //export這個structure,若有driver要掛上可以引用
static int test_bus_match(struct device* device, struct device_driver* driver)
{
printk(" in bus match\n");
return 0;
}
EXPORT_SYMBOL(test_bus_match);
static int test_bus_init(void)
{
int res;
if((res = bus_register(&test_bus_type)))
{
if(!res )
{
bus_unregister(&test_bus_type);
printk("res=%d\n",res);
}
return res;
}
return 0;
}
static void test_bus_exit(void)
{
bus_unregister(&test_bus_type);
}
MODULE_LICENSE("GPL");
module_init(test_bus_init);
module_exit(test_bus_exit);
再來是一個空的driver
#include <linux/module.h>
#include <linux/kobject.h>
#include <linux/device.h>
static int test_driver_probe(struct device* dev);
extern struct bus_type test_bus_type;
struct device_driver testdriver =
{
.name="testdriver",
.probe=test_driver_probe,
.bus=&test_bus_type,
};
static int test_driver_probe(struct device* dev)
{
printk(KERN_INFO"in driver probe\n");
return 1;
}
static int testdriver_init(void)
{
int res;
if((res = driver_register(&testdriver)))
{
printk("res=%d\n",res);
return res;
}
return 0;
}
static void testdriver_exit(void)
{
driver_unregister(&testdriver);
}
MODULE_LICENSE("GPL");
module_init(testdriver_init);
module_exit(testdriver_exit);
這樣就會在/sys/bus/testbus/drivers/下多出一個testdriver的folder。目前這個driver並沒有id_table,將來若有id_table,加上掛上的deivice有match,就可以bind在一起了。