diff --git a/drivers/mtd/ubi/build.c b/drivers/mtd/ubi/build.c
index 30be4ed68fad..dae569f48b87 100644
--- a/drivers/mtd/ubi/build.c
+++ b/drivers/mtd/ubi/build.c
@@ -920,7 +920,7 @@ int ubi_attach_mtd_dev(struct mtd_info *mtd, int ubi_num,
 			return -ENFILE;
 		}
 	} else {
-		if (ubi_num >= UBI_MAX_DEVICES)
+		if (ubi_num < UBI_DEV_NUM_AUTO || ubi_num >= UBI_MAX_DEVICES)
 			return -EINVAL;
 
 		/* Make sure ubi_num is not busy */
