Re: [PATCH] Detect and warn on atomic_inc/atomic_dec wrappingaround

From: Ingo Molnar
Date: Thu Apr 30 2009 - 08:50:29 EST



* Nikanth Karthikesan <knikanth@xxxxxxxxxx> wrote:

> diff --git a/include/asm-generic/atomic.h b/include/asm-generic/atomic.h
> index 7abdaa9..edf5619 100644
> --- a/include/asm-generic/atomic.h
> +++ b/include/asm-generic/atomic.h
> @@ -4,15 +4,71 @@
> * Copyright (C) 2005 Silicon Graphics, Inc.
> * Christoph Lameter
> *
> - * Allows to provide arch independent atomic definitions without the need to
> - * edit all arch specific atomic.h files.
> */
>
> +#include <linux/kernel.h>
> #include <asm/types.h>
> +#include <asm/bug.h>
> +
> +#ifdef CONFIG_ENABLE_WARN_ATOMIC_INC_WRAP
> +
> +/**
> + * atomic_inc - increment atomic variable
> + * @v: pointer of type atomic_t
> + *
> + * Atomically increments @v by 1.
> + * Prints a warning if it wraps around.
> + */
> +static inline void atomic_inc(atomic_t *v)
> +{
> + WARN_ON(atomic_add_unless(v, 1, INT_MAX) == 0);
> +}
> +
> +/**
> + * atomic_dec - decrement atomic variable
> + * @v: pointer of type atomic_t
> + *
> + * Atomically decrements @v by 1.
> + * Prints a warning if it wraps around.
> + */
> +static inline void atomic_dec(atomic_t *v)
> +{
> + WARN_ON(atomic_add_unless(v, -1, INT_MIN) == 0);
> +}
> +
> +#else
> +
> +/**
> + * atomic_inc - increment atomic variable
> + * @v: pointer of type atomic_t
> + *
> + * Atomically increments @v by 1.
> + */
> +static inline void atomic_inc(atomic_t *v)
> +{
> + raw_atomic_inc(v);
> +}
> +
> +/**
> + * atomic_dec - increment atomic variable
> + * @v: pointer of type atomic_t
> + *
> + * Atomically decrements @v by 1.
> + */
> +static inline void atomic_dec(atomic_t *v)
> +{
> + raw_atomic_dec(v);
> +}
> +
> +#endif

Here i think it makes sense to have a single definition:

static inline void atomic_inc(atomic_t *v)
{
#ifdef CONFIG_ENABLE_WARN_ATOMIC_INC_WRAP
WARN_ON(atomic_add_unless(v, 1, INT_MAX) == 0);
#else
raw_atomic_inc(v);
#endif
}

Or, better yet, i'd suggest to define an 'invalid value' range for
atomic integer types - not restricted to the single value of
INT_MAX, but in the range of: [ UINT_MAX/4 ... INT_MAX/4*3 ].

Then there could be a single, straightforward value check:

static inline void atomic_inc(atomic_t *v)
{
debug_atomic_check_value(v);
raw_atomic_inc(v);
}

Where debug_atomic_check_value() is just an atomic_read():

static inline void debug_atomic_check_value(atomic_t *v)
{
WARN_ONCE(in_range(atomic_read(v), UINT_MAX/4, UINT_MAX/4*3),
KERN_ERR "atomic counter check failure!");
}

It's a constant check.

If are overflowing on such a massive rate, it doesnt matter how
early or late we check the value.

Agreed?

Ingo
--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/