dm stripe: use struct_size() in kmalloc()
authorGustavo A. R. Silva <gustavo@embeddedor.com>
Wed, 2 Oct 2019 19:03:41 +0000 (14:03 -0500)
committerMike Snitzer <snitzer@redhat.com>
Tue, 5 Nov 2019 19:09:59 +0000 (14:09 -0500)
One of the more common cases of allocation size calculations is finding
the size of a structure that has a zero-sized array at the end, along
with memory for some number of elements for that array. For example:

struct stripe_c {
        ...
        struct stripe stripe[0];
};

In this case alloc_context() and dm_array_too_big() are removed and
replaced by the direct use of the struct_size() helper in kmalloc().

Notice that open-coded form is prone to type mistakes.

This code was detected with the help of Coccinelle.

Signed-off-by: Gustavo A. R. Silva <gustavo@embeddedor.com>
Signed-off-by: Mike Snitzer <snitzer@redhat.com>
drivers/md/dm-stripe.c
include/linux/device-mapper.h

index 8547d75943389134af94dfb5aff8cab5834415da..63bbcc20f49aa1a69a72b6fa2fa2901a3207abde 100644 (file)
@@ -55,19 +55,6 @@ static void trigger_event(struct work_struct *work)
        dm_table_event(sc->ti->table);
 }
 
-static inline struct stripe_c *alloc_context(unsigned int stripes)
-{
-       size_t len;
-
-       if (dm_array_too_big(sizeof(struct stripe_c), sizeof(struct stripe),
-                            stripes))
-               return NULL;
-
-       len = sizeof(struct stripe_c) + (sizeof(struct stripe) * stripes);
-
-       return kmalloc(len, GFP_KERNEL);
-}
-
 /*
  * Parse a single <dev> <sector> pair
  */
@@ -142,7 +129,7 @@ static int stripe_ctr(struct dm_target *ti, unsigned int argc, char **argv)
                return -EINVAL;
        }
 
-       sc = alloc_context(stripes);
+       sc = kmalloc(struct_size(sc, stripe, stripes), GFP_KERNEL);
        if (!sc) {
                ti->error = "Memory allocation for striped context "
                    "failed";
index 399ad8632356847f9a8ed0ded4d7f8cd70a8dddc..2e13826898b20a93bbc5292f325adf837ce7cb8d 100644 (file)
@@ -594,9 +594,6 @@ void *dm_vcalloc(unsigned long nmemb, unsigned long elem_size);
  */
 #define dm_round_up(n, sz) (dm_div_up((n), (sz)) * (sz))
 
-#define dm_array_too_big(fixed, obj, num) \
-       ((num) > (UINT_MAX - (fixed)) / (obj))
-
 /*
  * Sector offset taken relative to the start of the target instead of
  * relative to the start of the device.