lib/kunit/device.c

Source file repositories/reference/linux-study-clean/lib/kunit/device.c

File Facts

System
Linux kernel
Corpus path
lib/kunit/device.c
Extension
.c
Size
5230 bytes
Lines
202
Domain
Kernel Services
Bucket
lib
Inferred role
Kernel Services: operation-table or driver-model contract
Status
pattern implementation candidate

Why This File Exists

Shared kernel service surface used by multiple subsystems, including helpers, cryptography, virtualization support, and async I/O infrastructure.

Dependency Surface

Detected Declarations

Annotated Snippet

KUNIT_DEFINE_ACTION_WRAPPER(driver_unregister_wrapper, driver_unregister, struct device_driver *);

/* The root device for the KUnit bus, parent of all kunit_devices. */
static struct device *kunit_bus_device;

/* A device owned by a KUnit test. */
struct kunit_device {
	struct device dev;
	/* The KUnit test which owns this device. */
	struct kunit *owner;
	/* If the driver is managed by KUnit and unique to this device. */
	const struct device_driver *driver;
};

#define to_kunit_device(d) container_of_const(d, struct kunit_device, dev)

static const struct bus_type kunit_bus_type = {
	.name		= "kunit",
};

/* Register the 'kunit_bus' used for fake devices. */
int kunit_bus_init(void)
{
	int error;

	kunit_bus_device = root_device_register("kunit");
	if (IS_ERR(kunit_bus_device))
		return PTR_ERR(kunit_bus_device);

	error = bus_register(&kunit_bus_type);
	if (error)
		root_device_unregister(kunit_bus_device);
	return error;
}

/* Unregister the 'kunit_bus' in case the KUnit module is unloaded. */
void kunit_bus_shutdown(void)
{
	/* Make sure the bus exists before we unregister it. */
	if (IS_ERR_OR_NULL(kunit_bus_device))
		return;

	bus_unregister(&kunit_bus_type);

	root_device_unregister(kunit_bus_device);

	kunit_bus_device = NULL;
}

/* Release a 'fake' KUnit device. */
static void kunit_device_release(struct device *d)
{
	kfree(to_kunit_device(d));
}

/*
 * Create and register a KUnit-managed struct device_driver on the kunit_bus.
 * Returns an error pointer on failure.
 */
struct device_driver *kunit_driver_create(struct kunit *test, const char *name)
{
	struct device_driver *driver;
	int err = -ENOMEM;

	driver = kunit_kzalloc(test, sizeof(*driver), GFP_KERNEL);

	if (!driver)
		return ERR_PTR(err);

	driver->name = kunit_kstrdup_const(test, name, GFP_KERNEL);
	driver->bus = &kunit_bus_type;
	driver->owner = THIS_MODULE;

	err = driver_register(driver);
	if (err) {
		kunit_kfree(test, driver);
		return ERR_PTR(err);
	}

	kunit_add_action(test, driver_unregister_wrapper, driver);
	return driver;
}
EXPORT_SYMBOL_GPL(kunit_driver_create);

/* Helper which creates a kunit_device, attaches it to the kunit_bus*/
static struct kunit_device *kunit_device_register_internal(struct kunit *test,
							   const char *name)
{
	struct kunit_device *kunit_dev;
	int err = -ENOMEM;

Annotation

Implementation Notes