Linux kernel Memory Allocation Functions: devm_kmalloc / devm_kzalloc / devm_kfree
Kernel version: 5.10
1.void *devm_kmalloc(struct device *dev, size_t size, gfp_t gfp);
drivers/base.devres.c
813 /**
814 * devm_kmalloc - Resource-managed kmalloc
815 * @dev: Device to allocate memory for
816 * @size: Allocation size
817 * @gfp: Allocation gfp flags
818 *
819 * Managed kmalloc. Memory allocated with this function is
820 * automatically freed on driver detach. Like all other devres
821 * resources, guaranteed alignment is unsigned long long.
822 *
823 * RETURNS:
824 * Pointer to allocated memory on success, NULL on failure.
825 */
826 void *devm_kmalloc(struct device *dev, size_t size, gfp_t gfp)
827 {
828 struct devres *dr;
829
830 if (unlikely(!size))
831 return ZERO_SIZE_PTR;
832
833 /* use raw alloc_dr for kmalloc caller tracing */
834 dr = alloc_dr(devm_kmalloc_release, size, gfp, dev_to_node(dev));
835 if (unlikely(!dr))
836 return NULL;
837
838 /*
839 * This is named devm_kzalloc_release for historical reasons
840 * The initial implementation did not support kmalloc, only kzalloc
841 */
842 set_node_dbginfo(&dr->node, "devm_kzalloc_release", size);
843 devres_add(dev, dr->data);
844 return dr->data;
845 }
846 EXPORT_SYMBOL_GPL(devm_kmalloc);
2.static inline void *devm_kzalloc(struct device *dev, size_t size, gfp_t gfp);
include/linux/device.h
216 static inline void *devm_kzalloc(struct device *dev, size_t size, gfp_t gfp)
217 {
218 return devm_kmalloc(dev, size, gfp | __GFP_ZERO);
219 }
3.void devm_kfree(struct device *dev, const void *p);
drivers/base.devres.c
1049 /**
1050 * devm_kfree - Resource-managed kfree
1051 * @dev: Device this memory belongs to
1052 * @p: Memory to free
1053 *
1054 * Free memory allocated with devm_kmalloc().
1055 */
1056 void devm_kfree(struct device *dev, const void *p)
1057 {
1058 int rc;
1059
1060 /*
1061 * Special cases: pointer to a string in .rodata returned by
1062 * devm_kstrdup_const() or NULL/ZERO ptr.
1063 */
1064 if (unlikely(is_kernel_rodata((unsigned long)p) || ZERO_OR_NULL_PTR(p)))
1065 return;
1066
1067 rc = devres_destroy(dev, devm_kmalloc_release,
1068 devm_kmalloc_match, (void *)p);
1069 WARN_ON(rc);
1070 }
1071 EXPORT_SYMBOL_GPL(devm_kfree);