Skip to contentSkip to conversation

nvdimm: check for null return of devm_kmalloc in nd_pfn_probe

PATCH In review Kang Chen 2 participants 2 messages Feb 26, 2023 libnvdimm: non-volatile memory device

lore
Share & tools
lore

Kang Chen

author
#0 lore raw

PATCH 1/1 nvdimm: check for null return of devm_kmalloc in nd_pfn_probe

devm_kmalloc may fails, pfn_sb might be null and will cause null pointer dereference later.

---
 drivers/nvdimm/pfn_devs.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/nvdimm/pfn_devs.c +2 -0
index af7d93015..d24fad175 100644
@@ -640,6 +640,8 @@ int nd_pfn_probe(struct device *dev, struct nd_namespace_common *ndns)
 	if (!pfn_dev)
 		return -ENOMEM;
 	pfn_sb = devm_kmalloc(dev, sizeof(*pfn_sb), GFP_KERNEL);
+	if (!pfn_sb)
+		return -ENOMEM;
 	nd_pfn = to_nd_pfn(pfn_dev);
 	nd_pfn->pfn_sb = pfn_sb;
 	rc = nd_pfn_validate(nd_pfn, PFN_SIG);
Signature · 1 line
2.34.1
maintainer
#1 lore raw
Quoted 13 lines · Kang Chen

devm_kmalloc may fails, pfn_sb might be null and will cause null pointer dereference later.

---
 drivers/nvdimm/pfn_devs.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/nvdimm/pfn_devs.c +0 -0
index af7d93015..d24fad175 100644

drivers/nvdimm/pfn_devs.c int nd_pfn_probe(struct device *dev, struct nd_namespace_common *ndns) · line 647

Quoted 8 lines
drivers/nvdimm/pfn_devs.c +2 -0
@@ -640,6 +640,8 @@ int nd_pfn_probe(struct device *dev, struct nd_namespace_common *ndns)
 	if (!pfn_dev)
 		return -ENOMEM;
 	pfn_sb = devm_kmalloc(dev, sizeof(*pfn_sb), GFP_KERNEL);
+	if (!pfn_sb)
+		return -ENOMEM;
 	nd_pfn = to_nd_pfn(pfn_dev);
 	nd_pfn->pfn_sb = pfn_sb;
 	rc = nd_pfn_validate(nd_pfn, PFN_SIG);

Hi Kang,

I too, think the code is clearer if the failure to alloc is addressed immediately. In this case, it seems we can't just return -ENOMEM. The original code is detecting that NULL pfn_sb in nd_pfn_validate(), and then doing this cleanup upon return:

	if (rc < 0) {
                nd_detach_ndns(pfn_dev, &nd_pfn->ndns);
                put_device(pfn_dev);

Perhaps refactor a bit to go right to the cleanup, as opposed to calling nd_pfn_validate() when !pfn_sb.

Alison

Quoted 4 lines
Signature · 1 line
2.34.1