# Resource API

_Peios Kernel / Kernel development / Development tools / kunit / api_

> This file documents the KUnit resource API.

<a id="rst-resource-api"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This file documents the KUnit resource API.

Most users won't need to use this API directly, power users can use it to store state on a per-test basis, register custom cleanup actions, and more.


#### <a id="c-struct-kunit_resource"></a>`struct kunit_resource`

represents a *test managed resource*

**Definition**

```c
struct kunit_resource {
    void *data;
    const char *name;
    kunit_resource_free_t free;
};
```

**Members**

- `data`: for the user to store arbitrary data.
- `name`: optional name
- `free`: a user supplied function to free the resource.

**Description**

Represents a *test managed resource*, a resource which will automatically be
cleaned up at the end of a test case. This cleanup is performed by the 'free'
function. The struct kunit_resource itself is freed automatically with
[`kfree()`](/kernel/internals/core-api/mm-api.md#c-kfree) if it was allocated by KUnit (e.g., by [`kunit_alloc_resource()`](#c-kunit_alloc_resource)), but
must be freed by the user otherwise.

Resources are reference counted so if a resource is retrieved via
[`kunit_alloc_and_get_resource()`](#c-kunit_alloc_and_get_resource) or [`kunit_find_resource()`](#c-kunit_find_resource), we need
to call [`kunit_put_resource()`](#c-kunit_put_resource) to reduce the resource reference count
when finished with it.  Note that [`kunit_alloc_resource()`](#c-kunit_alloc_resource) does not require a
`kunit_resource_put()` because it does not retrieve the resource itself.

**Example**

```c
struct kunit_kmalloc_params {
        size_t size;
        gfp_t gfp;
};

static int kunit_kmalloc_init(struct kunit_resource *res, void *context)
{
        struct kunit_kmalloc_params *params = context;
        res->data = kmalloc(params->size, params->gfp);

        if (!res->data)
                return -ENOMEM;

        return 0;
}

static void kunit_kmalloc_free(struct kunit_resource *res)
{
        kfree(res->data);
}

void *kunit_kmalloc(struct kunit *test, size_t size, gfp_t gfp)
{
        struct kunit_kmalloc_params params;

        params.size = size;
        params.gfp = gfp;

        return kunit_alloc_resource(test, kunit_kmalloc_init,
                kunit_kmalloc_free, gfp, &params);
}
```

Resources can also be named, with lookup/removal done on a name
basis also.  [`kunit_add_named_resource()`](#c-kunit_add_named_resource), [`kunit_find_named_resource()`](#c-kunit_find_named_resource)
and `kunit_destroy_named_resource()`.  Resource names must be
unique within the test instance.

#### <a id="c-kunit_get_resource"></a>`kunit_get_resource()`

```c
void kunit_get_resource(struct kunit_resource *res)
```

Hold resource for use. Should not need to be used by most users as we automatically get resources retrieved by kunit_find_resource*().

**Parameters**

- `struct kunit_resource *res`: resource

#### <a id="c-kunit_put_resource"></a>`kunit_put_resource()`

```c
void kunit_put_resource(struct kunit_resource *res)
```

When caller is done with retrieved resource, [`kunit_put_resource()`](#c-kunit_put_resource) should be called to drop reference count. The resource list maintains a reference count on resources, so if no users are utilizing a resource and it is removed from the resource list, it will be freed via the associated free function (if any). Only needs to be used if we `alloc_and_get()` or `find()` resource.

**Parameters**

- `struct kunit_resource *res`: resource

#### <a id="c-__kunit_add_resource"></a>`__kunit_add_resource()`

```c
int __kunit_add_resource(struct kunit *test, kunit_resource_init_t init, kunit_resource_free_t free, struct kunit_resource *res, void *data)
```

Internal helper to add a resource.

**Parameters**

- `struct kunit *test`: The test context object.
- `kunit_resource_init_t init`: a user-supplied function to initialize the result (if needed).  If
  none is supplied, the resource data value is simply set to **data**.
  If an init function is supplied, **data** is passed to it instead.
- `kunit_resource_free_t free`: a user-supplied function to free the resource (if needed).
- `struct kunit_resource *res`: The resource.
- `void *data`: value to pass to init function or set in resource data field.

**Description**

res->should_kfree is not initialised.

#### <a id="c-kunit_add_resource"></a>`kunit_add_resource()`

```c
int kunit_add_resource(struct kunit *test, kunit_resource_init_t init, kunit_resource_free_t free, struct kunit_resource *res, void *data)
```

Add a *test managed resource*.

**Parameters**

- `struct kunit *test`: The test context object.
- `kunit_resource_init_t init`: a user-supplied function to initialize the result (if needed).  If
  none is supplied, the resource data value is simply set to **data**.
  If an init function is supplied, **data** is passed to it instead.
- `kunit_resource_free_t free`: a user-supplied function to free the resource (if needed).
- `struct kunit_resource *res`: The resource.
- `void *data`: value to pass to init function or set in resource data field.

#### <a id="c-kunit_add_named_resource"></a>`kunit_add_named_resource()`

```c
int kunit_add_named_resource(struct kunit *test, kunit_resource_init_t init, kunit_resource_free_t free, struct kunit_resource *res, const char *name, void *data)
```

Add a named *test managed resource*.

**Parameters**

- `struct kunit *test`: The test context object.
- `kunit_resource_init_t init`: a user-supplied function to initialize the resource data, if needed.
- `kunit_resource_free_t free`: a user-supplied function to free the resource data, if needed.
- `struct kunit_resource *res`: The resource.
- `const char *name`: name to be set for resource.
- `void *data`: value to pass to init function or set in resource data field.

#### <a id="c-kunit_alloc_and_get_resource"></a>`kunit_alloc_and_get_resource()`

```c
struct kunit_resource * kunit_alloc_and_get_resource(struct kunit *test, kunit_resource_init_t init, kunit_resource_free_t free, gfp_t internal_gfp, void *context)
```

Allocates and returns a *test managed resource*.

**Parameters**

- `struct kunit *test`: The test context object.
- `kunit_resource_init_t init`: a user supplied function to initialize the resource.
- `kunit_resource_free_t free`: a user supplied function to free the resource (if needed).
- `gfp_t internal_gfp`: gfp to use for internal allocations, if unsure, use GFP_KERNEL
- `void *context`: for the user to pass in arbitrary data to the init function.

**Description**

Allocates a *test managed resource*, a resource which will automatically be
cleaned up at the end of a test case. See [`struct kunit_resource`](#c-struct-kunit_resource) for an
example.

This is effectively identical to kunit_alloc_resource, but returns the
struct kunit_resource pointer, not just the 'data' pointer. It therefore
also increments the resource's refcount, so [`kunit_put_resource()`](#c-kunit_put_resource) should be
called when you've finished with it.

**Note**

KUnit needs to allocate memory for a kunit_resource object. You must
specify an **internal_gfp** that is compatible with the use context of your
resource.

#### <a id="c-kunit_alloc_resource"></a>`kunit_alloc_resource()`

```c
void * kunit_alloc_resource(struct kunit *test, kunit_resource_init_t init, kunit_resource_free_t free, gfp_t internal_gfp, void *context)
```

Allocates a *test managed resource*.

**Parameters**

- `struct kunit *test`: The test context object.
- `kunit_resource_init_t init`: a user supplied function to initialize the resource.
- `kunit_resource_free_t free`: a user supplied function to free the resource (if needed).
- `gfp_t internal_gfp`: gfp to use for internal allocations, if unsure, use GFP_KERNEL
- `void *context`: for the user to pass in arbitrary data to the init function.

**Description**

Allocates a *test managed resource*, a resource which will automatically be
cleaned up at the end of a test case. See [`struct kunit_resource`](#c-struct-kunit_resource) for an
example.

**Note**

KUnit needs to allocate memory for a kunit_resource object. You must
specify an **internal_gfp** that is compatible with the use context of your
resource.

#### <a id="c-kunit_resource_name_match"></a>`kunit_resource_name_match()`

```c
bool kunit_resource_name_match(struct kunit *test, struct kunit_resource *res, void *match_name)
```

Match a resource with the same name.

**Parameters**

- `struct kunit *test`: Test case to which the resource belongs.
- `struct kunit_resource *res`: The resource.
- `void *match_name`: The name to match against.

#### <a id="c-kunit_find_resource"></a>`kunit_find_resource()`

```c
struct kunit_resource * kunit_find_resource(struct kunit *test, kunit_resource_match_t match, void *match_data)
```

Find a resource using match function/data.

**Parameters**

- `struct kunit *test`: Test case to which the resource belongs.
- `kunit_resource_match_t match`: match function to be applied to resources/match data.
- `void *match_data`: data to be used in matching.

#### <a id="c-kunit_find_named_resource"></a>`kunit_find_named_resource()`

```c
struct kunit_resource * kunit_find_named_resource(struct kunit *test, const char *name)
```

Find a resource using match name.

**Parameters**

- `struct kunit *test`: Test case to which the resource belongs.
- `const char *name`: match name.

#### <a id="c-kunit_destroy_resource"></a>`kunit_destroy_resource()`

```c
int kunit_destroy_resource(struct kunit *test, kunit_resource_match_t match, void *match_data)
```

Find a kunit_resource and destroy it.

**Parameters**

- `struct kunit *test`: Test case to which the resource belongs.
- `kunit_resource_match_t match`: Match function. Returns whether a given resource matches **match_data**.
- `void *match_data`: Data passed into **match**.

**Return**

0 if kunit_resource is found and freed, -ENOENT if not found.

#### <a id="c-kunit_remove_resource"></a>`kunit_remove_resource()`

```c
void kunit_remove_resource(struct kunit *test, struct kunit_resource *res)
```

remove resource from resource list associated with test.

**Parameters**

- `struct kunit *test`: The test context object.
- `struct kunit_resource *res`: The resource to be removed.

**Description**

Note that the resource will not be immediately freed since it is likely
the caller has a reference to it via `alloc_and_get()` or `find()`;
in this case a final call to [`kunit_put_resource()`](#c-kunit_put_resource) is required.

#### <a id="c-KUNIT_DEFINE_ACTION_WRAPPER"></a>`KUNIT_DEFINE_ACTION_WRAPPER()`

```c
KUNIT_DEFINE_ACTION_WRAPPER(wrapper, orig, arg_type)
```

Wrap a function for use as a deferred action.

**Parameters**

- `wrapper`: The name of the new wrapper function define.
- `orig`: The original function to wrap.
- `arg_type`: The type of the argument accepted by **orig**.

**Description**

Defines a wrapper for a function which accepts a single, pointer-sized
argument. This wrapper can then be passed to [`kunit_add_action()`](#c-kunit_add_action) and
similar. This should be used in preference to casting a function
directly to kunit_action_t, as casting function pointers will break
control flow integrity (CFI), leading to crashes.

#### <a id="c-kunit_add_action"></a>`kunit_add_action()`

```c
int kunit_add_action(struct kunit *test, kunit_action_t *action, void *ctx)
```

Call a function when the test ends.

**Parameters**

- `struct kunit *test`: Test case to associate the action with.
- `kunit_action_t *action`: The function to run on test exit
- `void *ctx`: Data passed into **func**

**Description**

Defer the execution of a function until the test exits, either normally or
due to a failure.  **ctx** is passed as additional context. All functions
registered with [`kunit_add_action()`](#c-kunit_add_action) will execute in the opposite order to that
they were registered in.

This is useful for cleaning up allocated memory and resources, as these
functions are called even if the test aborts early due to, e.g., a failed
assertion.

See also: `devm_add_action()` for the devres equivalent.

**Return**

0 on success, an error if the action could not be deferred.

#### <a id="c-kunit_add_action_or_reset"></a>`kunit_add_action_or_reset()`

```c
int kunit_add_action_or_reset(struct kunit *test, kunit_action_t *action, void *ctx)
```

Call a function when the test ends.

**Parameters**

- `struct kunit *test`: Test case to associate the action with.
- `kunit_action_t *action`: The function to run on test exit
- `void *ctx`: Data passed into **func**

**Description**

Defer the execution of a function until the test exits, either normally or
due to a failure.  **ctx** is passed as additional context. All functions
registered with [`kunit_add_action()`](#c-kunit_add_action) will execute in the opposite order to that
they were registered in.

This is useful for cleaning up allocated memory and resources, as these
functions are called even if the test aborts early due to, e.g., a failed
assertion.

If the action cannot be created (e.g., due to the system being out of memory),
then action(ctx) will be called immediately, and an error will be returned.

See also: `devm_add_action_or_reset()` for the devres equivalent.

**Return**

0 on success, an error if the action could not be deferred.

#### <a id="c-kunit_remove_action"></a>`kunit_remove_action()`

```c
void kunit_remove_action(struct kunit *test, kunit_action_t *action, void *ctx)
```

Cancel a matching deferred action.

**Parameters**

- `struct kunit *test`: Test case the action is associated with.
- `kunit_action_t *action`: The deferred function to cancel.
- `void *ctx`: The context passed to the deferred function to trigger.

**Description**

Prevent an action deferred via [`kunit_add_action()`](#c-kunit_add_action) from executing when the
test terminates.

If the function/context pair was deferred multiple times, only the most
recent one will be cancelled.

See also: `devm_remove_action()` for the devres equivalent.

#### <a id="c-kunit_release_action"></a>`kunit_release_action()`

```c
void kunit_release_action(struct kunit *test, kunit_action_t *action, void *ctx)
```

Run a matching action call immediately.

**Parameters**

- `struct kunit *test`: Test case the action is associated with.
- `kunit_action_t *action`: The deferred function to trigger.
- `void *ctx`: The context passed to the deferred function to trigger.

**Description**

Execute a function deferred via [`kunit_add_action()`](#c-kunit_add_action)) immediately, rather than
when the test ends.

If the function/context pair was deferred multiple times, it will only be
executed once here. The most recent deferral will no longer execute when
the test ends.

kunit_release_action(test, func, ctx);
is equivalent to
func(ctx);
kunit_remove_action(test, func, ctx);

See also: [`devm_release_action()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-devm_release_action) for the devres equivalent.


<a id="rst-managed-devices"></a>

## Managed Devices

Functions for using KUnit-managed struct device and struct device_driver. Include `kunit/device.h` to use these.


#### <a id="c-kunit_driver_create"></a>`kunit_driver_create()`

```c
struct device_driver * kunit_driver_create(struct kunit *test, const char *name)
```

Create a struct device_driver attached to the kunit_bus

**Parameters**

- `struct kunit *test`: The test context object.
- `const char *name`: The name to give the created driver.

**Description**

Creates a struct device_driver attached to the kunit_bus, with the name **name**.
This driver will automatically be cleaned up on test exit.

**Return**

a stub struct device_driver, managed by KUnit, with the name **name**.

#### <a id="c-kunit_device_register"></a>`kunit_device_register()`

```c
struct device * kunit_device_register(struct kunit *test, const char *name)
```

Create a struct device for use in KUnit tests

**Parameters**

- `struct kunit *test`: The test context object.
- `const char *name`: The name to give the created device.

**Description**

Creates a struct kunit_device (which is a struct device) with the given name,
and a corresponding driver. The device and driver will be cleaned up on test
exit, or when kunit_device_unregister is called. See also
kunit_device_register_with_driver, if you wish to provide your own
struct device_driver.

**Return**

a pointer to a struct device which will be cleaned up when the test
exits, or an error pointer if the device could not be allocated or registered.

#### <a id="c-kunit_device_register_with_driver"></a>`kunit_device_register_with_driver()`

```c
struct device * kunit_device_register_with_driver(struct kunit *test, const char *name, const struct device_driver *drv)
```

Create a struct device for use in KUnit tests

**Parameters**

- `struct kunit *test`: The test context object.
- `const char *name`: The name to give the created device.
- `const struct device_driver *drv`: The struct device_driver to associate with the device.

**Description**

Creates a struct kunit_device (which is a struct device) with the given
name, and driver. The device will be cleaned up on test exit, or when
kunit_device_unregister is called. See also kunit_device_register, if you
wish KUnit to create and manage a driver for you.

**Return**

a pointer to a struct device which will be cleaned up when the test
exits, or an error pointer if the device could not be allocated or registered.

#### <a id="c-kunit_device_unregister"></a>`kunit_device_unregister()`

```c
void kunit_device_unregister(struct kunit *test, struct device *dev)
```

Unregister a KUnit-managed device

**Parameters**

- `struct kunit *test`: The test context object which created the device
- `struct device *dev`: The device.

**Description**

Unregisters and destroys a struct device which was created with
kunit_device_register or kunit_device_register_with_driver. If KUnit created
a driver, cleans it up as well.
