[PATCH 4.4-cip 06/23] perf/core: Fix Undefined behaviour in rb_alloc()

Ben Hutchings <ben.hutchings@...>

From: Peter Zijlstra <peterz@...>

commit 8184059e93c200757f5c0805dae0f14e880eab5d upstream.

Sasha reported:

[ 3494.030114] UBSAN: Undefined behaviour in kernel/events/ring_buffer.c:685:22
[ 3494.030647] shift exponent -1 is negative

Andrey spotted that this is because:

It happens if nr_pages = 0:
rb->page_order = ilog2(nr_pages);

Fix it by making both assignments conditional on nr_pages; since
otherwise they should both be 0 anyway, and will be because of the
kzalloc() used to allocate the structure.

Reported-by: Sasha Levin <sasha.levin@...>
Reported-by: Andrey Ryabinin <ryabinin.a.a@...>
Signed-off-by: Peter Zijlstra (Intel) <peterz@...>
Cc: Alexander Shishkin <alexander.shishkin@...>
Cc: Andy Lutomirski <luto@...>
Cc: Arnaldo Carvalho de Melo <acme@...>
Cc: Arnaldo Carvalho de Melo <acme@...>
Cc: Borislav Petkov <bp@...>
Cc: Brian Gerst <brgerst@...>
Cc: David Ahern <dsahern@...>
Cc: Denys Vlasenko <dvlasenk@...>
Cc: H. Peter Anvin <hpa@...>
Cc: Jiri Olsa <jolsa@...>
Cc: Linus Torvalds <torvalds@...>
Cc: Namhyung Kim <namhyung@...>
Cc: Peter Zijlstra <peterz@...>
Cc: Stephane Eranian <eranian@...>
Cc: Thomas Gleixner <tglx@...>
Cc: Vince Weaver <vincent.weaver@...>
Link: http://lkml.kernel.org/r/20160129141751.GA407@worktop
Signed-off-by: Ingo Molnar <mingo@...>
Signed-off-by: Ben Hutchings <ben.hutchings@...>
kernel/events/ring_buffer.c | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/kernel/events/ring_buffer.c b/kernel/events/ring_buffer.c
index 014b69528194..7beb02f40cb4 100644
--- a/kernel/events/ring_buffer.c
+++ b/kernel/events/ring_buffer.c
@@ -754,8 +754,10 @@ struct ring_buffer *rb_alloc(int nr_pages, long watermark, int cpu, int flags)

rb->user_page = all_buf;
rb->data_pages[0] = all_buf + PAGE_SIZE;
- rb->page_order = ilog2(nr_pages);
- rb->nr_pages = !!nr_pages;
+ if (nr_pages) {
+ rb->nr_pages = 1;
+ rb->page_order = ilog2(nr_pages);
+ }

ring_buffer_init(rb, watermark, flags);


Ben Hutchings
Software Developer, Codethink Ltd.