Subject: [PATCH 5/6] ipc/sem.c: fully initialize sem_array before making it visible

From: Manfred Spraul <[email-masked]>
Date: Tue, 2 Dec 2014 15:59:34 -0800

commit e8577d1f0329d4842e8302e289fb2c22156abef4 upstream.

ipc_addid() makes a new ipc identifier visible to everyone.  New objects
start as locked, so that the caller can complete the initialization
after the call.  Within struct sem_array, at least sma->sem_base and
sma->sem_nsems are accessed without any locks, therefore this approach
doesn't work.

Thus: Move the ipc_addid() to the end of the initialization.

Signed-off-by: Manfred Spraul <[email-masked]>
Reported-by: Rik van Riel <[email-masked]>
Acked-by: Rik van Riel <[email-masked]>
Acked-by: Davidlohr Bueso <[email-masked]>
Acked-by: Rafael Aquini <[email-masked]>
Signed-off-by: Andrew Morton <[email-masked]>
Signed-off-by: Linus Torvalds <[email-masked]>
[bwh: Backported to 2.6.32:
 - Adjust context
 - The error path being moved looks a little different]
Signed-off-by: Ben Hutchings <[email-masked]>
---
 ipc/sem.c | 11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)

diff --git a/ipc/sem.c b/ipc/sem.c
index b781007..26dc5b1 100644
--- a/ipc/sem.c
+++ b/ipc/sem.c
@@ -264,6 +264,12 @@ static int newary(struct ipc_namespace *ns, struct ipc_params *params)
 		return retval;
 	}
 
+	sma->sem_base = (struct sem *) &sma[1];
+	INIT_LIST_HEAD(&sma->sem_pending);
+	INIT_LIST_HEAD(&sma->list_id);
+	sma->sem_nsems = nsems;
+	sma->sem_ctime = get_seconds();
+
 	id = ipc_addid(&sem_ids(ns), &sma->sem_perm, ns->sc_semmni);
 	if (id < 0) {
 		security_sem_free(sma);
@@ -272,11 +278,6 @@ static int newary(struct ipc_namespace *ns, struct ipc_params *params)
 	}
 	ns->used_sems += nsems;
 
-	sma->sem_base = (struct sem *) &sma[1];
-	INIT_LIST_HEAD(&sma->sem_pending);
-	INIT_LIST_HEAD(&sma->list_id);
-	sma->sem_nsems = nsems;
-	sma->sem_ctime = get_seconds();
 	sem_unlock(sma);
 
 	return sma->sem_perm.id;