|
| 1 | +// SPDX-License-Identifier: GPL-2.0-only |
| 2 | +/* Copyright(c) 2024-2025 Intel Corporation. All rights reserved. */ |
| 3 | + |
| 4 | +#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt |
| 5 | + |
| 6 | +#include <linux/tsm.h> |
| 7 | +#include <linux/rwsem.h> |
| 8 | +#include <linux/device.h> |
| 9 | +#include <linux/module.h> |
| 10 | +#include <linux/cleanup.h> |
| 11 | + |
| 12 | +static struct class *tsm_class; |
| 13 | +static DECLARE_RWSEM(tsm_rwsem); |
| 14 | +static DEFINE_IDA(tsm_ida); |
| 15 | + |
| 16 | +static struct tsm_dev *alloc_tsm_dev(struct device *parent) |
| 17 | +{ |
| 18 | + struct device *dev; |
| 19 | + int id; |
| 20 | + |
| 21 | + struct tsm_dev *tsm_dev __free(kfree) = |
| 22 | + kzalloc(sizeof(*tsm_dev), GFP_KERNEL); |
| 23 | + if (!tsm_dev) |
| 24 | + return ERR_PTR(-ENOMEM); |
| 25 | + |
| 26 | + id = ida_alloc(&tsm_ida, GFP_KERNEL); |
| 27 | + if (id < 0) |
| 28 | + return ERR_PTR(id); |
| 29 | + |
| 30 | + tsm_dev->id = id; |
| 31 | + dev = &tsm_dev->dev; |
| 32 | + dev->parent = parent; |
| 33 | + dev->class = tsm_class; |
| 34 | + device_initialize(dev); |
| 35 | + |
| 36 | + return no_free_ptr(tsm_dev); |
| 37 | +} |
| 38 | + |
| 39 | +struct tsm_dev *tsm_register(struct device *parent) |
| 40 | +{ |
| 41 | + struct tsm_dev *tsm_dev __free(put_tsm_dev) = alloc_tsm_dev(parent); |
| 42 | + struct device *dev; |
| 43 | + int rc; |
| 44 | + |
| 45 | + if (IS_ERR(tsm_dev)) |
| 46 | + return tsm_dev; |
| 47 | + |
| 48 | + dev = &tsm_dev->dev; |
| 49 | + rc = dev_set_name(dev, "tsm%d", tsm_dev->id); |
| 50 | + if (rc) |
| 51 | + return ERR_PTR(rc); |
| 52 | + |
| 53 | + rc = device_add(dev); |
| 54 | + if (rc) |
| 55 | + return ERR_PTR(rc); |
| 56 | + |
| 57 | + return no_free_ptr(tsm_dev); |
| 58 | +} |
| 59 | +EXPORT_SYMBOL_GPL(tsm_register); |
| 60 | + |
| 61 | +void tsm_unregister(struct tsm_dev *tsm_dev) |
| 62 | +{ |
| 63 | + device_unregister(&tsm_dev->dev); |
| 64 | +} |
| 65 | +EXPORT_SYMBOL_GPL(tsm_unregister); |
| 66 | + |
| 67 | +static void tsm_release(struct device *dev) |
| 68 | +{ |
| 69 | + struct tsm_dev *tsm_dev = container_of(dev, typeof(*tsm_dev), dev); |
| 70 | + |
| 71 | + ida_free(&tsm_ida, tsm_dev->id); |
| 72 | + kfree(tsm_dev); |
| 73 | +} |
| 74 | + |
| 75 | +static int __init tsm_init(void) |
| 76 | +{ |
| 77 | + tsm_class = class_create("tsm"); |
| 78 | + if (IS_ERR(tsm_class)) |
| 79 | + return PTR_ERR(tsm_class); |
| 80 | + |
| 81 | + tsm_class->dev_release = tsm_release; |
| 82 | + return 0; |
| 83 | +} |
| 84 | +module_init(tsm_init) |
| 85 | + |
| 86 | +static void __exit tsm_exit(void) |
| 87 | +{ |
| 88 | + class_destroy(tsm_class); |
| 89 | +} |
| 90 | +module_exit(tsm_exit) |
| 91 | + |
| 92 | +MODULE_LICENSE("GPL"); |
| 93 | +MODULE_DESCRIPTION("TEE Security Manager Class Device"); |
0 commit comments