sem.c revision 3d3653f9
1/*
2 * linux/ipc/sem.c
3 * Copyright (C) 1992 Krishna Balasubramanian
4 * Copyright (C) 1995 Eric Schenk, Bruno Haible
5 *
6 * /proc/sysvipc/sem support (c) 1999 Dragos Acostachioaie <dragos@iname.com>
7 *
8 * SMP-threaded, sysctl's added
9 * (c) 1999 Manfred Spraul <manfred@colorfullife.com>
10 * Enforced range limit on SEM_UNDO
11 * (c) 2001 Red Hat Inc
12 * Lockless wakeup
13 * (c) 2003 Manfred Spraul <manfred@colorfullife.com>
14 * (c) 2016 Davidlohr Bueso <dave@stgolabs.net>
15 * Further wakeup optimizations, documentation
16 * (c) 2010 Manfred Spraul <manfred@colorfullife.com>
17 *
18 * support for audit of ipc object properties and permission changes
19 * Dustin Kirkland <dustin.kirkland@us.ibm.com>
20 *
21 * namespaces support
22 * OpenVZ, SWsoft Inc.
23 * Pavel Emelianov <xemul@openvz.org>
24 *
25 * Implementation notes: (May 2010)
26 * This file implements System V semaphores.
27 *
28 * User space visible behavior:
29 * - FIFO ordering for semop() operations (just FIFO, not starvation
30 *   protection)
31 * - multiple semaphore operations that alter the same semaphore in
32 *   one semop() are handled.
33 * - sem_ctime (time of last semctl()) is updated in the IPC_SET, SETVAL and
34 *   SETALL calls.
35 * - two Linux specific semctl() commands: SEM_STAT, SEM_INFO.
36 * - undo adjustments at process exit are limited to 0..SEMVMX.
37 * - namespace are supported.
38 * - SEMMSL, SEMMNS, SEMOPM and SEMMNI can be configured at runtine by writing
39 *   to /proc/sys/kernel/sem.
40 * - statistics about the usage are reported in /proc/sysvipc/sem.
41 *
42 * Internals:
43 * - scalability:
44 *   - all global variables are read-mostly.
45 *   - semop() calls and semctl(RMID) are synchronized by RCU.
46 *   - most operations do write operations (actually: spin_lock calls) to
47 *     the per-semaphore array structure.
48 *   Thus: Perfect SMP scaling between independent semaphore arrays.
49 *         If multiple semaphores in one array are used, then cache line
50 *         trashing on the semaphore array spinlock will limit the scaling.
51 * - semncnt and semzcnt are calculated on demand in count_semcnt()
52 * - the task that performs a successful semop() scans the list of all
53 *   sleeping tasks and completes any pending operations that can be fulfilled.
54 *   Semaphores are actively given to waiting tasks (necessary for FIFO).
55 *   (see update_queue())
56 * - To improve the scalability, the actual wake-up calls are performed after
57 *   dropping all locks. (see wake_up_sem_queue_prepare())
58 * - All work is done by the waker, the woken up task does not have to do
59 *   anything - not even acquiring a lock or dropping a refcount.
60 * - A woken up task may not even touch the semaphore array anymore, it may
61 *   have been destroyed already by a semctl(RMID).
62 * - UNDO values are stored in an array (one per process and per
63 *   semaphore array, lazily allocated). For backwards compatibility, multiple
64 *   modes for the UNDO variables are supported (per process, per thread)
65 *   (see copy_semundo, CLONE_SYSVSEM)
66 * - There are two lists of the pending operations: a per-array list
67 *   and per-semaphore list (stored in the array). This allows to achieve FIFO
68 *   ordering without always scanning all pending operations.
69 *   The worst-case behavior is nevertheless O(N^2) for N wakeups.
70 */
71
72#include <linux/slab.h>
73#include <linux/spinlock.h>
74#include <linux/init.h>
75#include <linux/proc_fs.h>
76#include <linux/time.h>
77#include <linux/security.h>
78#include <linux/syscalls.h>
79#include <linux/audit.h>
80#include <linux/capability.h>
81#include <linux/seq_file.h>
82#include <linux/rwsem.h>
83#include <linux/nsproxy.h>
84#include <linux/ipc_namespace.h>
85#include <linux/sched/wake_q.h>
86
87#include <linux/uaccess.h>
88#include "util.h"
89
90
91/* One queue for each sleeping process in the system. */
92struct sem_queue {
93	struct list_head	list;	 /* queue of pending operations */
94	struct task_struct	*sleeper; /* this process */
95	struct sem_undo		*undo;	 /* undo structure */
96	int			pid;	 /* process id of requesting process */
97	int			status;	 /* completion status of operation */
98	struct sembuf		*sops;	 /* array of pending operations */
99	struct sembuf		*blocking; /* the operation that blocked */
100	int			nsops;	 /* number of operations */
101	bool			alter;	 /* does *sops alter the array? */
102	bool                    dupsop;	 /* sops on more than one sem_num */
103};
104
105/* Each task has a list of undo requests. They are executed automatically
106 * when the process exits.
107 */
108struct sem_undo {
109	struct list_head	list_proc;	/* per-process list: *
110						 * all undos from one process
111						 * rcu protected */
112	struct rcu_head		rcu;		/* rcu struct for sem_undo */
113	struct sem_undo_list	*ulp;		/* back ptr to sem_undo_list */
114	struct list_head	list_id;	/* per semaphore array list:
115						 * all undos for one array */
116	int			semid;		/* semaphore set identifier */
117	short			*semadj;	/* array of adjustments */
118						/* one per semaphore */
119};
120
121/* sem_undo_list controls shared access to the list of sem_undo structures
122 * that may be shared among all a CLONE_SYSVSEM task group.
123 */
124struct sem_undo_list {
125	atomic_t		refcnt;
126	spinlock_t		lock;
127	struct list_head	list_proc;
128};
129
130
131#define sem_ids(ns)	((ns)->ids[IPC_SEM_IDS])
132
133#define sem_checkid(sma, semid)	ipc_checkid(&sma->sem_perm, semid)
134
135static int newary(struct ipc_namespace *, struct ipc_params *);
136static void freeary(struct ipc_namespace *, struct kern_ipc_perm *);
137#ifdef CONFIG_PROC_FS
138static int sysvipc_sem_proc_show(struct seq_file *s, void *it);
139#endif
140
141#define SEMMSL_FAST	256 /* 512 bytes on stack */
142#define SEMOPM_FAST	64  /* ~ 372 bytes on stack */
143
144/*
145 * Switching from the mode suitable for simple ops
146 * to the mode for complex ops is costly. Therefore:
147 * use some hysteresis
148 */
149#define USE_GLOBAL_LOCK_HYSTERESIS	10
150
151/*
152 * Locking:
153 * a) global sem_lock() for read/write
154 *	sem_undo.id_next,
155 *	sem_array.complex_count,
156 *	sem_array.pending{_alter,_const},
157 *	sem_array.sem_undo
158 *
159 * b) global or semaphore sem_lock() for read/write:
160 *	sem_array.sems[i].pending_{const,alter}:
161 *
162 * c) special:
163 *	sem_undo_list.list_proc:
164 *	* undo_list->lock for write
165 *	* rcu for read
166 *	use_global_lock:
167 *	* global sem_lock() for write
168 *	* either local or global sem_lock() for read.
169 *
170 * Memory ordering:
171 * Most ordering is enforced by using spin_lock() and spin_unlock().
172 * The special case is use_global_lock:
173 * Setting it from non-zero to 0 is a RELEASE, this is ensured by
174 * using smp_store_release().
175 * Testing if it is non-zero is an ACQUIRE, this is ensured by using
176 * smp_load_acquire().
177 * Setting it from 0 to non-zero must be ordered with regards to
178 * this smp_load_acquire(), this is guaranteed because the smp_load_acquire()
179 * is inside a spin_lock() and after a write from 0 to non-zero a
180 * spin_lock()+spin_unlock() is done.
181 */
182
183#define sc_semmsl	sem_ctls[0]
184#define sc_semmns	sem_ctls[1]
185#define sc_semopm	sem_ctls[2]
186#define sc_semmni	sem_ctls[3]
187
188void sem_init_ns(struct ipc_namespace *ns)
189{
190	ns->sc_semmsl = SEMMSL;
191	ns->sc_semmns = SEMMNS;
192	ns->sc_semopm = SEMOPM;
193	ns->sc_semmni = SEMMNI;
194	ns->used_sems = 0;
195	ipc_init_ids(&ns->ids[IPC_SEM_IDS]);
196}
197
198#ifdef CONFIG_IPC_NS
199void sem_exit_ns(struct ipc_namespace *ns)
200{
201	free_ipcs(ns, &sem_ids(ns), freeary);
202	idr_destroy(&ns->ids[IPC_SEM_IDS].ipcs_idr);
203}
204#endif
205
206void __init sem_init(void)
207{
208	sem_init_ns(&init_ipc_ns);
209	ipc_init_proc_interface("sysvipc/sem",
210				"       key      semid perms      nsems   uid   gid  cuid  cgid      otime      ctime\n",
211				IPC_SEM_IDS, sysvipc_sem_proc_show);
212}
213
214/**
215 * unmerge_queues - unmerge queues, if possible.
216 * @sma: semaphore array
217 *
218 * The function unmerges the wait queues if complex_count is 0.
219 * It must be called prior to dropping the global semaphore array lock.
220 */
221static void unmerge_queues(struct sem_array *sma)
222{
223	struct sem_queue *q, *tq;
224
225	/* complex operations still around? */
226	if (sma->complex_count)
227		return;
228	/*
229	 * We will switch back to simple mode.
230	 * Move all pending operation back into the per-semaphore
231	 * queues.
232	 */
233	list_for_each_entry_safe(q, tq, &sma->pending_alter, list) {
234		struct sem *curr;
235		curr = &sma->sems[q->sops[0].sem_num];
236
237		list_add_tail(&q->list, &curr->pending_alter);
238	}
239	INIT_LIST_HEAD(&sma->pending_alter);
240}
241
242/**
243 * merge_queues - merge single semop queues into global queue
244 * @sma: semaphore array
245 *
246 * This function merges all per-semaphore queues into the global queue.
247 * It is necessary to achieve FIFO ordering for the pending single-sop
248 * operations when a multi-semop operation must sleep.
249 * Only the alter operations must be moved, the const operations can stay.
250 */
251static void merge_queues(struct sem_array *sma)
252{
253	int i;
254	for (i = 0; i < sma->sem_nsems; i++) {
255		struct sem *sem = &sma->sems[i];
256
257		list_splice_init(&sem->pending_alter, &sma->pending_alter);
258	}
259}
260
261static void __sem_free(struct sem_array *sma)
262{
263	kvfree(sma);
264}
265
266static void sem_rcu_free(struct rcu_head *head)
267{
268	struct kern_ipc_perm *p = container_of(head, struct kern_ipc_perm, rcu);
269	struct sem_array *sma = container_of(p, struct sem_array, sem_perm);
270
271	security_sem_free(sma);
272	__sem_free(sma);
273}
274
275/*
276 * Enter the mode suitable for non-simple operations:
277 * Caller must own sem_perm.lock.
278 */
279static void complexmode_enter(struct sem_array *sma)
280{
281	int i;
282	struct sem *sem;
283
284	if (sma->use_global_lock > 0)  {
285		/*
286		 * We are already in global lock mode.
287		 * Nothing to do, just reset the
288		 * counter until we return to simple mode.
289		 */
290		sma->use_global_lock = USE_GLOBAL_LOCK_HYSTERESIS;
291		return;
292	}
293	sma->use_global_lock = USE_GLOBAL_LOCK_HYSTERESIS;
294
295	for (i = 0; i < sma->sem_nsems; i++) {
296		sem = &sma->sems[i];
297		spin_lock(&sem->lock);
298		spin_unlock(&sem->lock);
299	}
300}
301
302/*
303 * Try to leave the mode that disallows simple operations:
304 * Caller must own sem_perm.lock.
305 */
306static void complexmode_tryleave(struct sem_array *sma)
307{
308	if (sma->complex_count)  {
309		/* Complex ops are sleeping.
310		 * We must stay in complex mode
311		 */
312		return;
313	}
314	if (sma->use_global_lock == 1) {
315		/*
316		 * Immediately after setting use_global_lock to 0,
317		 * a simple op can start. Thus: all memory writes
318		 * performed by the current operation must be visible
319		 * before we set use_global_lock to 0.
320		 */
321		smp_store_release(&sma->use_global_lock, 0);
322	} else {
323		sma->use_global_lock--;
324	}
325}
326
327#define SEM_GLOBAL_LOCK	(-1)
328/*
329 * If the request contains only one semaphore operation, and there are
330 * no complex transactions pending, lock only the semaphore involved.
331 * Otherwise, lock the entire semaphore array, since we either have
332 * multiple semaphores in our own semops, or we need to look at
333 * semaphores from other pending complex operations.
334 */
335static inline int sem_lock(struct sem_array *sma, struct sembuf *sops,
336			      int nsops)
337{
338	struct sem *sem;
339
340	if (nsops != 1) {
341		/* Complex operation - acquire a full lock */
342		ipc_lock_object(&sma->sem_perm);
343
344		/* Prevent parallel simple ops */
345		complexmode_enter(sma);
346		return SEM_GLOBAL_LOCK;
347	}
348
349	/*
350	 * Only one semaphore affected - try to optimize locking.
351	 * Optimized locking is possible if no complex operation
352	 * is either enqueued or processed right now.
353	 *
354	 * Both facts are tracked by use_global_mode.
355	 */
356	sem = &sma->sems[sops->sem_num];
357
358	/*
359	 * Initial check for use_global_lock. Just an optimization,
360	 * no locking, no memory barrier.
361	 */
362	if (!sma->use_global_lock) {
363		/*
364		 * It appears that no complex operation is around.
365		 * Acquire the per-semaphore lock.
366		 */
367		spin_lock(&sem->lock);
368
369		/* pairs with smp_store_release() */
370		if (!smp_load_acquire(&sma->use_global_lock)) {
371			/* fast path successful! */
372			return sops->sem_num;
373		}
374		spin_unlock(&sem->lock);
375	}
376
377	/* slow path: acquire the full lock */
378	ipc_lock_object(&sma->sem_perm);
379
380	if (sma->use_global_lock == 0) {
381		/*
382		 * The use_global_lock mode ended while we waited for
383		 * sma->sem_perm.lock. Thus we must switch to locking
384		 * with sem->lock.
385		 * Unlike in the fast path, there is no need to recheck
386		 * sma->use_global_lock after we have acquired sem->lock:
387		 * We own sma->sem_perm.lock, thus use_global_lock cannot
388		 * change.
389		 */
390		spin_lock(&sem->lock);
391
392		ipc_unlock_object(&sma->sem_perm);
393		return sops->sem_num;
394	} else {
395		/*
396		 * Not a false alarm, thus continue to use the global lock
397		 * mode. No need for complexmode_enter(), this was done by
398		 * the caller that has set use_global_mode to non-zero.
399		 */
400		return SEM_GLOBAL_LOCK;
401	}
402}
403
404static inline void sem_unlock(struct sem_array *sma, int locknum)
405{
406	if (locknum == SEM_GLOBAL_LOCK) {
407		unmerge_queues(sma);
408		complexmode_tryleave(sma);
409		ipc_unlock_object(&sma->sem_perm);
410	} else {
411		struct sem *sem = &sma->sems[locknum];
412		spin_unlock(&sem->lock);
413	}
414}
415
416/*
417 * sem_lock_(check_) routines are called in the paths where the rwsem
418 * is not held.
419 *
420 * The caller holds the RCU read lock.
421 */
422static inline struct sem_array *sem_obtain_object(struct ipc_namespace *ns, int id)
423{
424	struct kern_ipc_perm *ipcp = ipc_obtain_object_idr(&sem_ids(ns), id);
425
426	if (IS_ERR(ipcp))
427		return ERR_CAST(ipcp);
428
429	return container_of(ipcp, struct sem_array, sem_perm);
430}
431
432static inline struct sem_array *sem_obtain_object_check(struct ipc_namespace *ns,
433							int id)
434{
435	struct kern_ipc_perm *ipcp = ipc_obtain_object_check(&sem_ids(ns), id);
436
437	if (IS_ERR(ipcp))
438		return ERR_CAST(ipcp);
439
440	return container_of(ipcp, struct sem_array, sem_perm);
441}
442
443static inline void sem_lock_and_putref(struct sem_array *sma)
444{
445	sem_lock(sma, NULL, -1);
446	ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
447}
448
449static inline void sem_rmid(struct ipc_namespace *ns, struct sem_array *s)
450{
451	ipc_rmid(&sem_ids(ns), &s->sem_perm);
452}
453
454static struct sem_array *sem_alloc(size_t nsems)
455{
456	struct sem_array *sma;
457	size_t size;
458
459	if (nsems > (INT_MAX - sizeof(*sma)) / sizeof(sma->sems[0]))
460		return NULL;
461
462	size = sizeof(*sma) + nsems * sizeof(sma->sems[0]);
463	sma = kvmalloc(size, GFP_KERNEL);
464	if (unlikely(!sma))
465		return NULL;
466
467	memset(sma, 0, size);
468
469	return sma;
470}
471
472/**
473 * newary - Create a new semaphore set
474 * @ns: namespace
475 * @params: ptr to the structure that contains key, semflg and nsems
476 *
477 * Called with sem_ids.rwsem held (as a writer)
478 */
479static int newary(struct ipc_namespace *ns, struct ipc_params *params)
480{
481	int retval;
482	struct sem_array *sma;
483	key_t key = params->key;
484	int nsems = params->u.nsems;
485	int semflg = params->flg;
486	int i;
487
488	if (!nsems)
489		return -EINVAL;
490	if (ns->used_sems + nsems > ns->sc_semmns)
491		return -ENOSPC;
492
493	sma = sem_alloc(nsems);
494	if (!sma)
495		return -ENOMEM;
496
497	sma->sem_perm.mode = (semflg & S_IRWXUGO);
498	sma->sem_perm.key = key;
499
500	sma->sem_perm.security = NULL;
501	retval = security_sem_alloc(sma);
502	if (retval) {
503		__sem_free(sma);
504		return retval;
505	}
506
507	for (i = 0; i < nsems; i++) {
508		INIT_LIST_HEAD(&sma->sems[i].pending_alter);
509		INIT_LIST_HEAD(&sma->sems[i].pending_const);
510		spin_lock_init(&sma->sems[i].lock);
511	}
512
513	sma->complex_count = 0;
514	sma->use_global_lock = USE_GLOBAL_LOCK_HYSTERESIS;
515	INIT_LIST_HEAD(&sma->pending_alter);
516	INIT_LIST_HEAD(&sma->pending_const);
517	INIT_LIST_HEAD(&sma->list_id);
518	sma->sem_nsems = nsems;
519	sma->sem_ctime = get_seconds();
520
521	retval = ipc_addid(&sem_ids(ns), &sma->sem_perm, ns->sc_semmni);
522	if (retval < 0) {
523		call_rcu(&sma->sem_perm.rcu, sem_rcu_free);
524		return retval;
525	}
526	ns->used_sems += nsems;
527
528	sem_unlock(sma, -1);
529	rcu_read_unlock();
530
531	return sma->sem_perm.id;
532}
533
534
535/*
536 * Called with sem_ids.rwsem and ipcp locked.
537 */
538static inline int sem_security(struct kern_ipc_perm *ipcp, int semflg)
539{
540	struct sem_array *sma;
541
542	sma = container_of(ipcp, struct sem_array, sem_perm);
543	return security_sem_associate(sma, semflg);
544}
545
546/*
547 * Called with sem_ids.rwsem and ipcp locked.
548 */
549static inline int sem_more_checks(struct kern_ipc_perm *ipcp,
550				struct ipc_params *params)
551{
552	struct sem_array *sma;
553
554	sma = container_of(ipcp, struct sem_array, sem_perm);
555	if (params->u.nsems > sma->sem_nsems)
556		return -EINVAL;
557
558	return 0;
559}
560
561SYSCALL_DEFINE3(semget, key_t, key, int, nsems, int, semflg)
562{
563	struct ipc_namespace *ns;
564	static const struct ipc_ops sem_ops = {
565		.getnew = newary,
566		.associate = sem_security,
567		.more_checks = sem_more_checks,
568	};
569	struct ipc_params sem_params;
570
571	ns = current->nsproxy->ipc_ns;
572
573	if (nsems < 0 || nsems > ns->sc_semmsl)
574		return -EINVAL;
575
576	sem_params.key = key;
577	sem_params.flg = semflg;
578	sem_params.u.nsems = nsems;
579
580	return ipcget(ns, &sem_ids(ns), &sem_ops, &sem_params);
581}
582
583/**
584 * perform_atomic_semop[_slow] - Attempt to perform semaphore
585 *                               operations on a given array.
586 * @sma: semaphore array
587 * @q: struct sem_queue that describes the operation
588 *
589 * Caller blocking are as follows, based the value
590 * indicated by the semaphore operation (sem_op):
591 *
592 *  (1) >0 never blocks.
593 *  (2)  0 (wait-for-zero operation): semval is non-zero.
594 *  (3) <0 attempting to decrement semval to a value smaller than zero.
595 *
596 * Returns 0 if the operation was possible.
597 * Returns 1 if the operation is impossible, the caller must sleep.
598 * Returns <0 for error codes.
599 */
600static int perform_atomic_semop_slow(struct sem_array *sma, struct sem_queue *q)
601{
602	int result, sem_op, nsops, pid;
603	struct sembuf *sop;
604	struct sem *curr;
605	struct sembuf *sops;
606	struct sem_undo *un;
607
608	sops = q->sops;
609	nsops = q->nsops;
610	un = q->undo;
611
612	for (sop = sops; sop < sops + nsops; sop++) {
613		curr = &sma->sems[sop->sem_num];
614		sem_op = sop->sem_op;
615		result = curr->semval;
616
617		if (!sem_op && result)
618			goto would_block;
619
620		result += sem_op;
621		if (result < 0)
622			goto would_block;
623		if (result > SEMVMX)
624			goto out_of_range;
625
626		if (sop->sem_flg & SEM_UNDO) {
627			int undo = un->semadj[sop->sem_num] - sem_op;
628			/* Exceeding the undo range is an error. */
629			if (undo < (-SEMAEM - 1) || undo > SEMAEM)
630				goto out_of_range;
631			un->semadj[sop->sem_num] = undo;
632		}
633
634		curr->semval = result;
635	}
636
637	sop--;
638	pid = q->pid;
639	while (sop >= sops) {
640		sma->sems[sop->sem_num].sempid = pid;
641		sop--;
642	}
643
644	return 0;
645
646out_of_range:
647	result = -ERANGE;
648	goto undo;
649
650would_block:
651	q->blocking = sop;
652
653	if (sop->sem_flg & IPC_NOWAIT)
654		result = -EAGAIN;
655	else
656		result = 1;
657
658undo:
659	sop--;
660	while (sop >= sops) {
661		sem_op = sop->sem_op;
662		sma->sems[sop->sem_num].semval -= sem_op;
663		if (sop->sem_flg & SEM_UNDO)
664			un->semadj[sop->sem_num] += sem_op;
665		sop--;
666	}
667
668	return result;
669}
670
671static int perform_atomic_semop(struct sem_array *sma, struct sem_queue *q)
672{
673	int result, sem_op, nsops;
674	struct sembuf *sop;
675	struct sem *curr;
676	struct sembuf *sops;
677	struct sem_undo *un;
678
679	sops = q->sops;
680	nsops = q->nsops;
681	un = q->undo;
682
683	if (unlikely(q->dupsop))
684		return perform_atomic_semop_slow(sma, q);
685
686	/*
687	 * We scan the semaphore set twice, first to ensure that the entire
688	 * operation can succeed, therefore avoiding any pointless writes
689	 * to shared memory and having to undo such changes in order to block
690	 * until the operations can go through.
691	 */
692	for (sop = sops; sop < sops + nsops; sop++) {
693		curr = &sma->sems[sop->sem_num];
694		sem_op = sop->sem_op;
695		result = curr->semval;
696
697		if (!sem_op && result)
698			goto would_block; /* wait-for-zero */
699
700		result += sem_op;
701		if (result < 0)
702			goto would_block;
703
704		if (result > SEMVMX)
705			return -ERANGE;
706
707		if (sop->sem_flg & SEM_UNDO) {
708			int undo = un->semadj[sop->sem_num] - sem_op;
709
710			/* Exceeding the undo range is an error. */
711			if (undo < (-SEMAEM - 1) || undo > SEMAEM)
712				return -ERANGE;
713		}
714	}
715
716	for (sop = sops; sop < sops + nsops; sop++) {
717		curr = &sma->sems[sop->sem_num];
718		sem_op = sop->sem_op;
719		result = curr->semval;
720
721		if (sop->sem_flg & SEM_UNDO) {
722			int undo = un->semadj[sop->sem_num] - sem_op;
723
724			un->semadj[sop->sem_num] = undo;
725		}
726		curr->semval += sem_op;
727		curr->sempid = q->pid;
728	}
729
730	return 0;
731
732would_block:
733	q->blocking = sop;
734	return sop->sem_flg & IPC_NOWAIT ? -EAGAIN : 1;
735}
736
737static inline void wake_up_sem_queue_prepare(struct sem_queue *q, int error,
738					     struct wake_q_head *wake_q)
739{
740	wake_q_add(wake_q, q->sleeper);
741	/*
742	 * Rely on the above implicit barrier, such that we can
743	 * ensure that we hold reference to the task before setting
744	 * q->status. Otherwise we could race with do_exit if the
745	 * task is awoken by an external event before calling
746	 * wake_up_process().
747	 */
748	WRITE_ONCE(q->status, error);
749}
750
751static void unlink_queue(struct sem_array *sma, struct sem_queue *q)
752{
753	list_del(&q->list);
754	if (q->nsops > 1)
755		sma->complex_count--;
756}
757
758/** check_restart(sma, q)
759 * @sma: semaphore array
760 * @q: the operation that just completed
761 *
762 * update_queue is O(N^2) when it restarts scanning the whole queue of
763 * waiting operations. Therefore this function checks if the restart is
764 * really necessary. It is called after a previously waiting operation
765 * modified the array.
766 * Note that wait-for-zero operations are handled without restart.
767 */
768static inline int check_restart(struct sem_array *sma, struct sem_queue *q)
769{
770	/* pending complex alter operations are too difficult to analyse */
771	if (!list_empty(&sma->pending_alter))
772		return 1;
773
774	/* we were a sleeping complex operation. Too difficult */
775	if (q->nsops > 1)
776		return 1;
777
778	/* It is impossible that someone waits for the new value:
779	 * - complex operations always restart.
780	 * - wait-for-zero are handled seperately.
781	 * - q is a previously sleeping simple operation that
782	 *   altered the array. It must be a decrement, because
783	 *   simple increments never sleep.
784	 * - If there are older (higher priority) decrements
785	 *   in the queue, then they have observed the original
786	 *   semval value and couldn't proceed. The operation
787	 *   decremented to value - thus they won't proceed either.
788	 */
789	return 0;
790}
791
792/**
793 * wake_const_ops - wake up non-alter tasks
794 * @sma: semaphore array.
795 * @semnum: semaphore that was modified.
796 * @wake_q: lockless wake-queue head.
797 *
798 * wake_const_ops must be called after a semaphore in a semaphore array
799 * was set to 0. If complex const operations are pending, wake_const_ops must
800 * be called with semnum = -1, as well as with the number of each modified
801 * semaphore.
802 * The tasks that must be woken up are added to @wake_q. The return code
803 * is stored in q->pid.
804 * The function returns 1 if at least one operation was completed successfully.
805 */
806static int wake_const_ops(struct sem_array *sma, int semnum,
807			  struct wake_q_head *wake_q)
808{
809	struct sem_queue *q, *tmp;
810	struct list_head *pending_list;
811	int semop_completed = 0;
812
813	if (semnum == -1)
814		pending_list = &sma->pending_const;
815	else
816		pending_list = &sma->sems[semnum].pending_const;
817
818	list_for_each_entry_safe(q, tmp, pending_list, list) {
819		int error = perform_atomic_semop(sma, q);
820
821		if (error > 0)
822			continue;
823		/* operation completed, remove from queue & wakeup */
824		unlink_queue(sma, q);
825
826		wake_up_sem_queue_prepare(q, error, wake_q);
827		if (error == 0)
828			semop_completed = 1;
829	}
830
831	return semop_completed;
832}
833
834/**
835 * do_smart_wakeup_zero - wakeup all wait for zero tasks
836 * @sma: semaphore array
837 * @sops: operations that were performed
838 * @nsops: number of operations
839 * @wake_q: lockless wake-queue head
840 *
841 * Checks all required queue for wait-for-zero operations, based
842 * on the actual changes that were performed on the semaphore array.
843 * The function returns 1 if at least one operation was completed successfully.
844 */
845static int do_smart_wakeup_zero(struct sem_array *sma, struct sembuf *sops,
846				int nsops, struct wake_q_head *wake_q)
847{
848	int i;
849	int semop_completed = 0;
850	int got_zero = 0;
851
852	/* first: the per-semaphore queues, if known */
853	if (sops) {
854		for (i = 0; i < nsops; i++) {
855			int num = sops[i].sem_num;
856
857			if (sma->sems[num].semval == 0) {
858				got_zero = 1;
859				semop_completed |= wake_const_ops(sma, num, wake_q);
860			}
861		}
862	} else {
863		/*
864		 * No sops means modified semaphores not known.
865		 * Assume all were changed.
866		 */
867		for (i = 0; i < sma->sem_nsems; i++) {
868			if (sma->sems[i].semval == 0) {
869				got_zero = 1;
870				semop_completed |= wake_const_ops(sma, i, wake_q);
871			}
872		}
873	}
874	/*
875	 * If one of the modified semaphores got 0,
876	 * then check the global queue, too.
877	 */
878	if (got_zero)
879		semop_completed |= wake_const_ops(sma, -1, wake_q);
880
881	return semop_completed;
882}
883
884
885/**
886 * update_queue - look for tasks that can be completed.
887 * @sma: semaphore array.
888 * @semnum: semaphore that was modified.
889 * @wake_q: lockless wake-queue head.
890 *
891 * update_queue must be called after a semaphore in a semaphore array
892 * was modified. If multiple semaphores were modified, update_queue must
893 * be called with semnum = -1, as well as with the number of each modified
894 * semaphore.
895 * The tasks that must be woken up are added to @wake_q. The return code
896 * is stored in q->pid.
897 * The function internally checks if const operations can now succeed.
898 *
899 * The function return 1 if at least one semop was completed successfully.
900 */
901static int update_queue(struct sem_array *sma, int semnum, struct wake_q_head *wake_q)
902{
903	struct sem_queue *q, *tmp;
904	struct list_head *pending_list;
905	int semop_completed = 0;
906
907	if (semnum == -1)
908		pending_list = &sma->pending_alter;
909	else
910		pending_list = &sma->sems[semnum].pending_alter;
911
912again:
913	list_for_each_entry_safe(q, tmp, pending_list, list) {
914		int error, restart;
915
916		/* If we are scanning the single sop, per-semaphore list of
917		 * one semaphore and that semaphore is 0, then it is not
918		 * necessary to scan further: simple increments
919		 * that affect only one entry succeed immediately and cannot
920		 * be in the  per semaphore pending queue, and decrements
921		 * cannot be successful if the value is already 0.
922		 */
923		if (semnum != -1 && sma->sems[semnum].semval == 0)
924			break;
925
926		error = perform_atomic_semop(sma, q);
927
928		/* Does q->sleeper still need to sleep? */
929		if (error > 0)
930			continue;
931
932		unlink_queue(sma, q);
933
934		if (error) {
935			restart = 0;
936		} else {
937			semop_completed = 1;
938			do_smart_wakeup_zero(sma, q->sops, q->nsops, wake_q);
939			restart = check_restart(sma, q);
940		}
941
942		wake_up_sem_queue_prepare(q, error, wake_q);
943		if (restart)
944			goto again;
945	}
946	return semop_completed;
947}
948
949/**
950 * set_semotime - set sem_otime
951 * @sma: semaphore array
952 * @sops: operations that modified the array, may be NULL
953 *
954 * sem_otime is replicated to avoid cache line trashing.
955 * This function sets one instance to the current time.
956 */
957static void set_semotime(struct sem_array *sma, struct sembuf *sops)
958{
959	if (sops == NULL) {
960		sma->sems[0].sem_otime = get_seconds();
961	} else {
962		sma->sems[sops[0].sem_num].sem_otime =
963							get_seconds();
964	}
965}
966
967/**
968 * do_smart_update - optimized update_queue
969 * @sma: semaphore array
970 * @sops: operations that were performed
971 * @nsops: number of operations
972 * @otime: force setting otime
973 * @wake_q: lockless wake-queue head
974 *
975 * do_smart_update() does the required calls to update_queue and wakeup_zero,
976 * based on the actual changes that were performed on the semaphore array.
977 * Note that the function does not do the actual wake-up: the caller is
978 * responsible for calling wake_up_q().
979 * It is safe to perform this call after dropping all locks.
980 */
981static void do_smart_update(struct sem_array *sma, struct sembuf *sops, int nsops,
982			    int otime, struct wake_q_head *wake_q)
983{
984	int i;
985
986	otime |= do_smart_wakeup_zero(sma, sops, nsops, wake_q);
987
988	if (!list_empty(&sma->pending_alter)) {
989		/* semaphore array uses the global queue - just process it. */
990		otime |= update_queue(sma, -1, wake_q);
991	} else {
992		if (!sops) {
993			/*
994			 * No sops, thus the modified semaphores are not
995			 * known. Check all.
996			 */
997			for (i = 0; i < sma->sem_nsems; i++)
998				otime |= update_queue(sma, i, wake_q);
999		} else {
1000			/*
1001			 * Check the semaphores that were increased:
1002			 * - No complex ops, thus all sleeping ops are
1003			 *   decrease.
1004			 * - if we decreased the value, then any sleeping
1005			 *   semaphore ops wont be able to run: If the
1006			 *   previous value was too small, then the new
1007			 *   value will be too small, too.
1008			 */
1009			for (i = 0; i < nsops; i++) {
1010				if (sops[i].sem_op > 0) {
1011					otime |= update_queue(sma,
1012							      sops[i].sem_num, wake_q);
1013				}
1014			}
1015		}
1016	}
1017	if (otime)
1018		set_semotime(sma, sops);
1019}
1020
1021/*
1022 * check_qop: Test if a queued operation sleeps on the semaphore semnum
1023 */
1024static int check_qop(struct sem_array *sma, int semnum, struct sem_queue *q,
1025			bool count_zero)
1026{
1027	struct sembuf *sop = q->blocking;
1028
1029	/*
1030	 * Linux always (since 0.99.10) reported a task as sleeping on all
1031	 * semaphores. This violates SUS, therefore it was changed to the
1032	 * standard compliant behavior.
1033	 * Give the administrators a chance to notice that an application
1034	 * might misbehave because it relies on the Linux behavior.
1035	 */
1036	pr_info_once("semctl(GETNCNT/GETZCNT) is since 3.16 Single Unix Specification compliant.\n"
1037			"The task %s (%d) triggered the difference, watch for misbehavior.\n",
1038			current->comm, task_pid_nr(current));
1039
1040	if (sop->sem_num != semnum)
1041		return 0;
1042
1043	if (count_zero && sop->sem_op == 0)
1044		return 1;
1045	if (!count_zero && sop->sem_op < 0)
1046		return 1;
1047
1048	return 0;
1049}
1050
1051/* The following counts are associated to each semaphore:
1052 *   semncnt        number of tasks waiting on semval being nonzero
1053 *   semzcnt        number of tasks waiting on semval being zero
1054 *
1055 * Per definition, a task waits only on the semaphore of the first semop
1056 * that cannot proceed, even if additional operation would block, too.
1057 */
1058static int count_semcnt(struct sem_array *sma, ushort semnum,
1059			bool count_zero)
1060{
1061	struct list_head *l;
1062	struct sem_queue *q;
1063	int semcnt;
1064
1065	semcnt = 0;
1066	/* First: check the simple operations. They are easy to evaluate */
1067	if (count_zero)
1068		l = &sma->sems[semnum].pending_const;
1069	else
1070		l = &sma->sems[semnum].pending_alter;
1071
1072	list_for_each_entry(q, l, list) {
1073		/* all task on a per-semaphore list sleep on exactly
1074		 * that semaphore
1075		 */
1076		semcnt++;
1077	}
1078
1079	/* Then: check the complex operations. */
1080	list_for_each_entry(q, &sma->pending_alter, list) {
1081		semcnt += check_qop(sma, semnum, q, count_zero);
1082	}
1083	if (count_zero) {
1084		list_for_each_entry(q, &sma->pending_const, list) {
1085			semcnt += check_qop(sma, semnum, q, count_zero);
1086		}
1087	}
1088	return semcnt;
1089}
1090
1091/* Free a semaphore set. freeary() is called with sem_ids.rwsem locked
1092 * as a writer and the spinlock for this semaphore set hold. sem_ids.rwsem
1093 * remains locked on exit.
1094 */
1095static void freeary(struct ipc_namespace *ns, struct kern_ipc_perm *ipcp)
1096{
1097	struct sem_undo *un, *tu;
1098	struct sem_queue *q, *tq;
1099	struct sem_array *sma = container_of(ipcp, struct sem_array, sem_perm);
1100	int i;
1101	DEFINE_WAKE_Q(wake_q);
1102
1103	/* Free the existing undo structures for this semaphore set.  */
1104	ipc_assert_locked_object(&sma->sem_perm);
1105	list_for_each_entry_safe(un, tu, &sma->list_id, list_id) {
1106		list_del(&un->list_id);
1107		spin_lock(&un->ulp->lock);
1108		un->semid = -1;
1109		list_del_rcu(&un->list_proc);
1110		spin_unlock(&un->ulp->lock);
1111		kfree_rcu(un, rcu);
1112	}
1113
1114	/* Wake up all pending processes and let them fail with EIDRM. */
1115	list_for_each_entry_safe(q, tq, &sma->pending_const, list) {
1116		unlink_queue(sma, q);
1117		wake_up_sem_queue_prepare(q, -EIDRM, &wake_q);
1118	}
1119
1120	list_for_each_entry_safe(q, tq, &sma->pending_alter, list) {
1121		unlink_queue(sma, q);
1122		wake_up_sem_queue_prepare(q, -EIDRM, &wake_q);
1123	}
1124	for (i = 0; i < sma->sem_nsems; i++) {
1125		struct sem *sem = &sma->sems[i];
1126		list_for_each_entry_safe(q, tq, &sem->pending_const, list) {
1127			unlink_queue(sma, q);
1128			wake_up_sem_queue_prepare(q, -EIDRM, &wake_q);
1129		}
1130		list_for_each_entry_safe(q, tq, &sem->pending_alter, list) {
1131			unlink_queue(sma, q);
1132			wake_up_sem_queue_prepare(q, -EIDRM, &wake_q);
1133		}
1134	}
1135
1136	/* Remove the semaphore set from the IDR */
1137	sem_rmid(ns, sma);
1138	sem_unlock(sma, -1);
1139	rcu_read_unlock();
1140
1141	wake_up_q(&wake_q);
1142	ns->used_sems -= sma->sem_nsems;
1143	ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
1144}
1145
1146static unsigned long copy_semid_to_user(void __user *buf, struct semid64_ds *in, int version)
1147{
1148	switch (version) {
1149	case IPC_64:
1150		return copy_to_user(buf, in, sizeof(*in));
1151	case IPC_OLD:
1152	    {
1153		struct semid_ds out;
1154
1155		memset(&out, 0, sizeof(out));
1156
1157		ipc64_perm_to_ipc_perm(&in->sem_perm, &out.sem_perm);
1158
1159		out.sem_otime	= in->sem_otime;
1160		out.sem_ctime	= in->sem_ctime;
1161		out.sem_nsems	= in->sem_nsems;
1162
1163		return copy_to_user(buf, &out, sizeof(out));
1164	    }
1165	default:
1166		return -EINVAL;
1167	}
1168}
1169
1170static time_t get_semotime(struct sem_array *sma)
1171{
1172	int i;
1173	time_t res;
1174
1175	res = sma->sems[0].sem_otime;
1176	for (i = 1; i < sma->sem_nsems; i++) {
1177		time_t to = sma->sems[i].sem_otime;
1178
1179		if (to > res)
1180			res = to;
1181	}
1182	return res;
1183}
1184
1185static int semctl_nolock(struct ipc_namespace *ns, int semid,
1186			 int cmd, int version, void __user *p)
1187{
1188	int err;
1189	struct sem_array *sma;
1190
1191	switch (cmd) {
1192	case IPC_INFO:
1193	case SEM_INFO:
1194	{
1195		struct seminfo seminfo;
1196		int max_id;
1197
1198		err = security_sem_semctl(NULL, cmd);
1199		if (err)
1200			return err;
1201
1202		memset(&seminfo, 0, sizeof(seminfo));
1203		seminfo.semmni = ns->sc_semmni;
1204		seminfo.semmns = ns->sc_semmns;
1205		seminfo.semmsl = ns->sc_semmsl;
1206		seminfo.semopm = ns->sc_semopm;
1207		seminfo.semvmx = SEMVMX;
1208		seminfo.semmnu = SEMMNU;
1209		seminfo.semmap = SEMMAP;
1210		seminfo.semume = SEMUME;
1211		down_read(&sem_ids(ns).rwsem);
1212		if (cmd == SEM_INFO) {
1213			seminfo.semusz = sem_ids(ns).in_use;
1214			seminfo.semaem = ns->used_sems;
1215		} else {
1216			seminfo.semusz = SEMUSZ;
1217			seminfo.semaem = SEMAEM;
1218		}
1219		max_id = ipc_get_maxid(&sem_ids(ns));
1220		up_read(&sem_ids(ns).rwsem);
1221		if (copy_to_user(p, &seminfo, sizeof(struct seminfo)))
1222			return -EFAULT;
1223		return (max_id < 0) ? 0 : max_id;
1224	}
1225	case IPC_STAT:
1226	case SEM_STAT:
1227	{
1228		struct semid64_ds tbuf;
1229		int id = 0;
1230
1231		memset(&tbuf, 0, sizeof(tbuf));
1232
1233		rcu_read_lock();
1234		if (cmd == SEM_STAT) {
1235			sma = sem_obtain_object(ns, semid);
1236			if (IS_ERR(sma)) {
1237				err = PTR_ERR(sma);
1238				goto out_unlock;
1239			}
1240			id = sma->sem_perm.id;
1241		} else {
1242			sma = sem_obtain_object_check(ns, semid);
1243			if (IS_ERR(sma)) {
1244				err = PTR_ERR(sma);
1245				goto out_unlock;
1246			}
1247		}
1248
1249		err = -EACCES;
1250		if (ipcperms(ns, &sma->sem_perm, S_IRUGO))
1251			goto out_unlock;
1252
1253		err = security_sem_semctl(sma, cmd);
1254		if (err)
1255			goto out_unlock;
1256
1257		kernel_to_ipc64_perm(&sma->sem_perm, &tbuf.sem_perm);
1258		tbuf.sem_otime = get_semotime(sma);
1259		tbuf.sem_ctime = sma->sem_ctime;
1260		tbuf.sem_nsems = sma->sem_nsems;
1261		rcu_read_unlock();
1262		if (copy_semid_to_user(p, &tbuf, version))
1263			return -EFAULT;
1264		return id;
1265	}
1266	default:
1267		return -EINVAL;
1268	}
1269out_unlock:
1270	rcu_read_unlock();
1271	return err;
1272}
1273
1274static int semctl_setval(struct ipc_namespace *ns, int semid, int semnum,
1275		unsigned long arg)
1276{
1277	struct sem_undo *un;
1278	struct sem_array *sma;
1279	struct sem *curr;
1280	int err, val;
1281	DEFINE_WAKE_Q(wake_q);
1282
1283#if defined(CONFIG_64BIT) && defined(__BIG_ENDIAN)
1284	/* big-endian 64bit */
1285	val = arg >> 32;
1286#else
1287	/* 32bit or little-endian 64bit */
1288	val = arg;
1289#endif
1290
1291	if (val > SEMVMX || val < 0)
1292		return -ERANGE;
1293
1294	rcu_read_lock();
1295	sma = sem_obtain_object_check(ns, semid);
1296	if (IS_ERR(sma)) {
1297		rcu_read_unlock();
1298		return PTR_ERR(sma);
1299	}
1300
1301	if (semnum < 0 || semnum >= sma->sem_nsems) {
1302		rcu_read_unlock();
1303		return -EINVAL;
1304	}
1305
1306
1307	if (ipcperms(ns, &sma->sem_perm, S_IWUGO)) {
1308		rcu_read_unlock();
1309		return -EACCES;
1310	}
1311
1312	err = security_sem_semctl(sma, SETVAL);
1313	if (err) {
1314		rcu_read_unlock();
1315		return -EACCES;
1316	}
1317
1318	sem_lock(sma, NULL, -1);
1319
1320	if (!ipc_valid_object(&sma->sem_perm)) {
1321		sem_unlock(sma, -1);
1322		rcu_read_unlock();
1323		return -EIDRM;
1324	}
1325
1326	curr = &sma->sems[semnum];
1327
1328	ipc_assert_locked_object(&sma->sem_perm);
1329	list_for_each_entry(un, &sma->list_id, list_id)
1330		un->semadj[semnum] = 0;
1331
1332	curr->semval = val;
1333	curr->sempid = task_tgid_vnr(current);
1334	sma->sem_ctime = get_seconds();
1335	/* maybe some queued-up processes were waiting for this */
1336	do_smart_update(sma, NULL, 0, 0, &wake_q);
1337	sem_unlock(sma, -1);
1338	rcu_read_unlock();
1339	wake_up_q(&wake_q);
1340	return 0;
1341}
1342
1343static int semctl_main(struct ipc_namespace *ns, int semid, int semnum,
1344		int cmd, void __user *p)
1345{
1346	struct sem_array *sma;
1347	struct sem *curr;
1348	int err, nsems;
1349	ushort fast_sem_io[SEMMSL_FAST];
1350	ushort *sem_io = fast_sem_io;
1351	DEFINE_WAKE_Q(wake_q);
1352
1353	rcu_read_lock();
1354	sma = sem_obtain_object_check(ns, semid);
1355	if (IS_ERR(sma)) {
1356		rcu_read_unlock();
1357		return PTR_ERR(sma);
1358	}
1359
1360	nsems = sma->sem_nsems;
1361
1362	err = -EACCES;
1363	if (ipcperms(ns, &sma->sem_perm, cmd == SETALL ? S_IWUGO : S_IRUGO))
1364		goto out_rcu_wakeup;
1365
1366	err = security_sem_semctl(sma, cmd);
1367	if (err)
1368		goto out_rcu_wakeup;
1369
1370	err = -EACCES;
1371	switch (cmd) {
1372	case GETALL:
1373	{
1374		ushort __user *array = p;
1375		int i;
1376
1377		sem_lock(sma, NULL, -1);
1378		if (!ipc_valid_object(&sma->sem_perm)) {
1379			err = -EIDRM;
1380			goto out_unlock;
1381		}
1382		if (nsems > SEMMSL_FAST) {
1383			if (!ipc_rcu_getref(&sma->sem_perm)) {
1384				err = -EIDRM;
1385				goto out_unlock;
1386			}
1387			sem_unlock(sma, -1);
1388			rcu_read_unlock();
1389			sem_io = kvmalloc_array(nsems, sizeof(ushort),
1390						GFP_KERNEL);
1391			if (sem_io == NULL) {
1392				ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
1393				return -ENOMEM;
1394			}
1395
1396			rcu_read_lock();
1397			sem_lock_and_putref(sma);
1398			if (!ipc_valid_object(&sma->sem_perm)) {
1399				err = -EIDRM;
1400				goto out_unlock;
1401			}
1402		}
1403		for (i = 0; i < sma->sem_nsems; i++)
1404			sem_io[i] = sma->sems[i].semval;
1405		sem_unlock(sma, -1);
1406		rcu_read_unlock();
1407		err = 0;
1408		if (copy_to_user(array, sem_io, nsems*sizeof(ushort)))
1409			err = -EFAULT;
1410		goto out_free;
1411	}
1412	case SETALL:
1413	{
1414		int i;
1415		struct sem_undo *un;
1416
1417		if (!ipc_rcu_getref(&sma->sem_perm)) {
1418			err = -EIDRM;
1419			goto out_rcu_wakeup;
1420		}
1421		rcu_read_unlock();
1422
1423		if (nsems > SEMMSL_FAST) {
1424			sem_io = kvmalloc_array(nsems, sizeof(ushort),
1425						GFP_KERNEL);
1426			if (sem_io == NULL) {
1427				ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
1428				return -ENOMEM;
1429			}
1430		}
1431
1432		if (copy_from_user(sem_io, p, nsems*sizeof(ushort))) {
1433			ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
1434			err = -EFAULT;
1435			goto out_free;
1436		}
1437
1438		for (i = 0; i < nsems; i++) {
1439			if (sem_io[i] > SEMVMX) {
1440				ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
1441				err = -ERANGE;
1442				goto out_free;
1443			}
1444		}
1445		rcu_read_lock();
1446		sem_lock_and_putref(sma);
1447		if (!ipc_valid_object(&sma->sem_perm)) {
1448			err = -EIDRM;
1449			goto out_unlock;
1450		}
1451
1452		for (i = 0; i < nsems; i++) {
1453			sma->sems[i].semval = sem_io[i];
1454			sma->sems[i].sempid = task_tgid_vnr(current);
1455		}
1456
1457		ipc_assert_locked_object(&sma->sem_perm);
1458		list_for_each_entry(un, &sma->list_id, list_id) {
1459			for (i = 0; i < nsems; i++)
1460				un->semadj[i] = 0;
1461		}
1462		sma->sem_ctime = get_seconds();
1463		/* maybe some queued-up processes were waiting for this */
1464		do_smart_update(sma, NULL, 0, 0, &wake_q);
1465		err = 0;
1466		goto out_unlock;
1467	}
1468	/* GETVAL, GETPID, GETNCTN, GETZCNT: fall-through */
1469	}
1470	err = -EINVAL;
1471	if (semnum < 0 || semnum >= nsems)
1472		goto out_rcu_wakeup;
1473
1474	sem_lock(sma, NULL, -1);
1475	if (!ipc_valid_object(&sma->sem_perm)) {
1476		err = -EIDRM;
1477		goto out_unlock;
1478	}
1479	curr = &sma->sems[semnum];
1480
1481	switch (cmd) {
1482	case GETVAL:
1483		err = curr->semval;
1484		goto out_unlock;
1485	case GETPID:
1486		err = curr->sempid;
1487		goto out_unlock;
1488	case GETNCNT:
1489		err = count_semcnt(sma, semnum, 0);
1490		goto out_unlock;
1491	case GETZCNT:
1492		err = count_semcnt(sma, semnum, 1);
1493		goto out_unlock;
1494	}
1495
1496out_unlock:
1497	sem_unlock(sma, -1);
1498out_rcu_wakeup:
1499	rcu_read_unlock();
1500	wake_up_q(&wake_q);
1501out_free:
1502	if (sem_io != fast_sem_io)
1503		kvfree(sem_io);
1504	return err;
1505}
1506
1507static inline unsigned long
1508copy_semid_from_user(struct semid64_ds *out, void __user *buf, int version)
1509{
1510	switch (version) {
1511	case IPC_64:
1512		if (copy_from_user(out, buf, sizeof(*out)))
1513			return -EFAULT;
1514		return 0;
1515	case IPC_OLD:
1516	    {
1517		struct semid_ds tbuf_old;
1518
1519		if (copy_from_user(&tbuf_old, buf, sizeof(tbuf_old)))
1520			return -EFAULT;
1521
1522		out->sem_perm.uid	= tbuf_old.sem_perm.uid;
1523		out->sem_perm.gid	= tbuf_old.sem_perm.gid;
1524		out->sem_perm.mode	= tbuf_old.sem_perm.mode;
1525
1526		return 0;
1527	    }
1528	default:
1529		return -EINVAL;
1530	}
1531}
1532
1533/*
1534 * This function handles some semctl commands which require the rwsem
1535 * to be held in write mode.
1536 * NOTE: no locks must be held, the rwsem is taken inside this function.
1537 */
1538static int semctl_down(struct ipc_namespace *ns, int semid,
1539		       int cmd, int version, void __user *p)
1540{
1541	struct sem_array *sma;
1542	int err;
1543	struct semid64_ds semid64;
1544	struct kern_ipc_perm *ipcp;
1545
1546	if (cmd == IPC_SET) {
1547		if (copy_semid_from_user(&semid64, p, version))
1548			return -EFAULT;
1549	}
1550
1551	down_write(&sem_ids(ns).rwsem);
1552	rcu_read_lock();
1553
1554	ipcp = ipcctl_pre_down_nolock(ns, &sem_ids(ns), semid, cmd,
1555				      &semid64.sem_perm, 0);
1556	if (IS_ERR(ipcp)) {
1557		err = PTR_ERR(ipcp);
1558		goto out_unlock1;
1559	}
1560
1561	sma = container_of(ipcp, struct sem_array, sem_perm);
1562
1563	err = security_sem_semctl(sma, cmd);
1564	if (err)
1565		goto out_unlock1;
1566
1567	switch (cmd) {
1568	case IPC_RMID:
1569		sem_lock(sma, NULL, -1);
1570		/* freeary unlocks the ipc object and rcu */
1571		freeary(ns, ipcp);
1572		goto out_up;
1573	case IPC_SET:
1574		sem_lock(sma, NULL, -1);
1575		err = ipc_update_perm(&semid64.sem_perm, ipcp);
1576		if (err)
1577			goto out_unlock0;
1578		sma->sem_ctime = get_seconds();
1579		break;
1580	default:
1581		err = -EINVAL;
1582		goto out_unlock1;
1583	}
1584
1585out_unlock0:
1586	sem_unlock(sma, -1);
1587out_unlock1:
1588	rcu_read_unlock();
1589out_up:
1590	up_write(&sem_ids(ns).rwsem);
1591	return err;
1592}
1593
1594SYSCALL_DEFINE4(semctl, int, semid, int, semnum, int, cmd, unsigned long, arg)
1595{
1596	int version;
1597	struct ipc_namespace *ns;
1598	void __user *p = (void __user *)arg;
1599
1600	if (semid < 0)
1601		return -EINVAL;
1602
1603	version = ipc_parse_version(&cmd);
1604	ns = current->nsproxy->ipc_ns;
1605
1606	switch (cmd) {
1607	case IPC_INFO:
1608	case SEM_INFO:
1609	case IPC_STAT:
1610	case SEM_STAT:
1611		return semctl_nolock(ns, semid, cmd, version, p);
1612	case GETALL:
1613	case GETVAL:
1614	case GETPID:
1615	case GETNCNT:
1616	case GETZCNT:
1617	case SETALL:
1618		return semctl_main(ns, semid, semnum, cmd, p);
1619	case SETVAL:
1620		return semctl_setval(ns, semid, semnum, arg);
1621	case IPC_RMID:
1622	case IPC_SET:
1623		return semctl_down(ns, semid, cmd, version, p);
1624	default:
1625		return -EINVAL;
1626	}
1627}
1628
1629/* If the task doesn't already have a undo_list, then allocate one
1630 * here.  We guarantee there is only one thread using this undo list,
1631 * and current is THE ONE
1632 *
1633 * If this allocation and assignment succeeds, but later
1634 * portions of this code fail, there is no need to free the sem_undo_list.
1635 * Just let it stay associated with the task, and it'll be freed later
1636 * at exit time.
1637 *
1638 * This can block, so callers must hold no locks.
1639 */
1640static inline int get_undo_list(struct sem_undo_list **undo_listp)
1641{
1642	struct sem_undo_list *undo_list;
1643
1644	undo_list = current->sysvsem.undo_list;
1645	if (!undo_list) {
1646		undo_list = kzalloc(sizeof(*undo_list), GFP_KERNEL);
1647		if (undo_list == NULL)
1648			return -ENOMEM;
1649		spin_lock_init(&undo_list->lock);
1650		atomic_set(&undo_list->refcnt, 1);
1651		INIT_LIST_HEAD(&undo_list->list_proc);
1652
1653		current->sysvsem.undo_list = undo_list;
1654	}
1655	*undo_listp = undo_list;
1656	return 0;
1657}
1658
1659static struct sem_undo *__lookup_undo(struct sem_undo_list *ulp, int semid)
1660{
1661	struct sem_undo *un;
1662
1663	list_for_each_entry_rcu(un, &ulp->list_proc, list_proc) {
1664		if (un->semid == semid)
1665			return un;
1666	}
1667	return NULL;
1668}
1669
1670static struct sem_undo *lookup_undo(struct sem_undo_list *ulp, int semid)
1671{
1672	struct sem_undo *un;
1673
1674	assert_spin_locked(&ulp->lock);
1675
1676	un = __lookup_undo(ulp, semid);
1677	if (un) {
1678		list_del_rcu(&un->list_proc);
1679		list_add_rcu(&un->list_proc, &ulp->list_proc);
1680	}
1681	return un;
1682}
1683
1684/**
1685 * find_alloc_undo - lookup (and if not present create) undo array
1686 * @ns: namespace
1687 * @semid: semaphore array id
1688 *
1689 * The function looks up (and if not present creates) the undo structure.
1690 * The size of the undo structure depends on the size of the semaphore
1691 * array, thus the alloc path is not that straightforward.
1692 * Lifetime-rules: sem_undo is rcu-protected, on success, the function
1693 * performs a rcu_read_lock().
1694 */
1695static struct sem_undo *find_alloc_undo(struct ipc_namespace *ns, int semid)
1696{
1697	struct sem_array *sma;
1698	struct sem_undo_list *ulp;
1699	struct sem_undo *un, *new;
1700	int nsems, error;
1701
1702	error = get_undo_list(&ulp);
1703	if (error)
1704		return ERR_PTR(error);
1705
1706	rcu_read_lock();
1707	spin_lock(&ulp->lock);
1708	un = lookup_undo(ulp, semid);
1709	spin_unlock(&ulp->lock);
1710	if (likely(un != NULL))
1711		goto out;
1712
1713	/* no undo structure around - allocate one. */
1714	/* step 1: figure out the size of the semaphore array */
1715	sma = sem_obtain_object_check(ns, semid);
1716	if (IS_ERR(sma)) {
1717		rcu_read_unlock();
1718		return ERR_CAST(sma);
1719	}
1720
1721	nsems = sma->sem_nsems;
1722	if (!ipc_rcu_getref(&sma->sem_perm)) {
1723		rcu_read_unlock();
1724		un = ERR_PTR(-EIDRM);
1725		goto out;
1726	}
1727	rcu_read_unlock();
1728
1729	/* step 2: allocate new undo structure */
1730	new = kzalloc(sizeof(struct sem_undo) + sizeof(short)*nsems, GFP_KERNEL);
1731	if (!new) {
1732		ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
1733		return ERR_PTR(-ENOMEM);
1734	}
1735
1736	/* step 3: Acquire the lock on semaphore array */
1737	rcu_read_lock();
1738	sem_lock_and_putref(sma);
1739	if (!ipc_valid_object(&sma->sem_perm)) {
1740		sem_unlock(sma, -1);
1741		rcu_read_unlock();
1742		kfree(new);
1743		un = ERR_PTR(-EIDRM);
1744		goto out;
1745	}
1746	spin_lock(&ulp->lock);
1747
1748	/*
1749	 * step 4: check for races: did someone else allocate the undo struct?
1750	 */
1751	un = lookup_undo(ulp, semid);
1752	if (un) {
1753		kfree(new);
1754		goto success;
1755	}
1756	/* step 5: initialize & link new undo structure */
1757	new->semadj = (short *) &new[1];
1758	new->ulp = ulp;
1759	new->semid = semid;
1760	assert_spin_locked(&ulp->lock);
1761	list_add_rcu(&new->list_proc, &ulp->list_proc);
1762	ipc_assert_locked_object(&sma->sem_perm);
1763	list_add(&new->list_id, &sma->list_id);
1764	un = new;
1765
1766success:
1767	spin_unlock(&ulp->lock);
1768	sem_unlock(sma, -1);
1769out:
1770	return un;
1771}
1772
1773SYSCALL_DEFINE4(semtimedop, int, semid, struct sembuf __user *, tsops,
1774		unsigned, nsops, const struct timespec __user *, timeout)
1775{
1776	int error = -EINVAL;
1777	struct sem_array *sma;
1778	struct sembuf fast_sops[SEMOPM_FAST];
1779	struct sembuf *sops = fast_sops, *sop;
1780	struct sem_undo *un;
1781	int max, locknum;
1782	bool undos = false, alter = false, dupsop = false;
1783	struct sem_queue queue;
1784	unsigned long dup = 0, jiffies_left = 0;
1785	struct ipc_namespace *ns;
1786
1787	ns = current->nsproxy->ipc_ns;
1788
1789	if (nsops < 1 || semid < 0)
1790		return -EINVAL;
1791	if (nsops > ns->sc_semopm)
1792		return -E2BIG;
1793	if (nsops > SEMOPM_FAST) {
1794		sops = kmalloc(sizeof(*sops)*nsops, GFP_KERNEL);
1795		if (sops == NULL)
1796			return -ENOMEM;
1797	}
1798
1799	if (copy_from_user(sops, tsops, nsops * sizeof(*tsops))) {
1800		error =  -EFAULT;
1801		goto out_free;
1802	}
1803
1804	if (timeout) {
1805		struct timespec _timeout;
1806		if (copy_from_user(&_timeout, timeout, sizeof(*timeout))) {
1807			error = -EFAULT;
1808			goto out_free;
1809		}
1810		if (_timeout.tv_sec < 0 || _timeout.tv_nsec < 0 ||
1811			_timeout.tv_nsec >= 1000000000L) {
1812			error = -EINVAL;
1813			goto out_free;
1814		}
1815		jiffies_left = timespec_to_jiffies(&_timeout);
1816	}
1817
1818	max = 0;
1819	for (sop = sops; sop < sops + nsops; sop++) {
1820		unsigned long mask = 1ULL << ((sop->sem_num) % BITS_PER_LONG);
1821
1822		if (sop->sem_num >= max)
1823			max = sop->sem_num;
1824		if (sop->sem_flg & SEM_UNDO)
1825			undos = true;
1826		if (dup & mask) {
1827			/*
1828			 * There was a previous alter access that appears
1829			 * to have accessed the same semaphore, thus use
1830			 * the dupsop logic. "appears", because the detection
1831			 * can only check % BITS_PER_LONG.
1832			 */
1833			dupsop = true;
1834		}
1835		if (sop->sem_op != 0) {
1836			alter = true;
1837			dup |= mask;
1838		}
1839	}
1840
1841	if (undos) {
1842		/* On success, find_alloc_undo takes the rcu_read_lock */
1843		un = find_alloc_undo(ns, semid);
1844		if (IS_ERR(un)) {
1845			error = PTR_ERR(un);
1846			goto out_free;
1847		}
1848	} else {
1849		un = NULL;
1850		rcu_read_lock();
1851	}
1852
1853	sma = sem_obtain_object_check(ns, semid);
1854	if (IS_ERR(sma)) {
1855		rcu_read_unlock();
1856		error = PTR_ERR(sma);
1857		goto out_free;
1858	}
1859
1860	error = -EFBIG;
1861	if (max >= sma->sem_nsems) {
1862		rcu_read_unlock();
1863		goto out_free;
1864	}
1865
1866	error = -EACCES;
1867	if (ipcperms(ns, &sma->sem_perm, alter ? S_IWUGO : S_IRUGO)) {
1868		rcu_read_unlock();
1869		goto out_free;
1870	}
1871
1872	error = security_sem_semop(sma, sops, nsops, alter);
1873	if (error) {
1874		rcu_read_unlock();
1875		goto out_free;
1876	}
1877
1878	error = -EIDRM;
1879	locknum = sem_lock(sma, sops, nsops);
1880	/*
1881	 * We eventually might perform the following check in a lockless
1882	 * fashion, considering ipc_valid_object() locking constraints.
1883	 * If nsops == 1 and there is no contention for sem_perm.lock, then
1884	 * only a per-semaphore lock is held and it's OK to proceed with the
1885	 * check below. More details on the fine grained locking scheme
1886	 * entangled here and why it's RMID race safe on comments at sem_lock()
1887	 */
1888	if (!ipc_valid_object(&sma->sem_perm))
1889		goto out_unlock_free;
1890	/*
1891	 * semid identifiers are not unique - find_alloc_undo may have
1892	 * allocated an undo structure, it was invalidated by an RMID
1893	 * and now a new array with received the same id. Check and fail.
1894	 * This case can be detected checking un->semid. The existence of
1895	 * "un" itself is guaranteed by rcu.
1896	 */
1897	if (un && un->semid == -1)
1898		goto out_unlock_free;
1899
1900	queue.sops = sops;
1901	queue.nsops = nsops;
1902	queue.undo = un;
1903	queue.pid = task_tgid_vnr(current);
1904	queue.alter = alter;
1905	queue.dupsop = dupsop;
1906
1907	error = perform_atomic_semop(sma, &queue);
1908	if (error == 0) { /* non-blocking succesfull path */
1909		DEFINE_WAKE_Q(wake_q);
1910
1911		/*
1912		 * If the operation was successful, then do
1913		 * the required updates.
1914		 */
1915		if (alter)
1916			do_smart_update(sma, sops, nsops, 1, &wake_q);
1917		else
1918			set_semotime(sma, sops);
1919
1920		sem_unlock(sma, locknum);
1921		rcu_read_unlock();
1922		wake_up_q(&wake_q);
1923
1924		goto out_free;
1925	}
1926	if (error < 0) /* non-blocking error path */
1927		goto out_unlock_free;
1928
1929	/*
1930	 * We need to sleep on this operation, so we put the current
1931	 * task into the pending queue and go to sleep.
1932	 */
1933	if (nsops == 1) {
1934		struct sem *curr;
1935		curr = &sma->sems[sops->sem_num];
1936
1937		if (alter) {
1938			if (sma->complex_count) {
1939				list_add_tail(&queue.list,
1940						&sma->pending_alter);
1941			} else {
1942
1943				list_add_tail(&queue.list,
1944						&curr->pending_alter);
1945			}
1946		} else {
1947			list_add_tail(&queue.list, &curr->pending_const);
1948		}
1949	} else {
1950		if (!sma->complex_count)
1951			merge_queues(sma);
1952
1953		if (alter)
1954			list_add_tail(&queue.list, &sma->pending_alter);
1955		else
1956			list_add_tail(&queue.list, &sma->pending_const);
1957
1958		sma->complex_count++;
1959	}
1960
1961	do {
1962		queue.status = -EINTR;
1963		queue.sleeper = current;
1964
1965		__set_current_state(TASK_INTERRUPTIBLE);
1966		sem_unlock(sma, locknum);
1967		rcu_read_unlock();
1968
1969		if (timeout)
1970			jiffies_left = schedule_timeout(jiffies_left);
1971		else
1972			schedule();
1973
1974		/*
1975		 * fastpath: the semop has completed, either successfully or
1976		 * not, from the syscall pov, is quite irrelevant to us at this
1977		 * point; we're done.
1978		 *
1979		 * We _do_ care, nonetheless, about being awoken by a signal or
1980		 * spuriously.  The queue.status is checked again in the
1981		 * slowpath (aka after taking sem_lock), such that we can detect
1982		 * scenarios where we were awakened externally, during the
1983		 * window between wake_q_add() and wake_up_q().
1984		 */
1985		error = READ_ONCE(queue.status);
1986		if (error != -EINTR) {
1987			/*
1988			 * User space could assume that semop() is a memory
1989			 * barrier: Without the mb(), the cpu could
1990			 * speculatively read in userspace stale data that was
1991			 * overwritten by the previous owner of the semaphore.
1992			 */
1993			smp_mb();
1994			goto out_free;
1995		}
1996
1997		rcu_read_lock();
1998		locknum = sem_lock(sma, sops, nsops);
1999
2000		if (!ipc_valid_object(&sma->sem_perm))
2001			goto out_unlock_free;
2002
2003		error = READ_ONCE(queue.status);
2004
2005		/*
2006		 * If queue.status != -EINTR we are woken up by another process.
2007		 * Leave without unlink_queue(), but with sem_unlock().
2008		 */
2009		if (error != -EINTR)
2010			goto out_unlock_free;
2011
2012		/*
2013		 * If an interrupt occurred we have to clean up the queue.
2014		 */
2015		if (timeout && jiffies_left == 0)
2016			error = -EAGAIN;
2017	} while (error == -EINTR && !signal_pending(current)); /* spurious */
2018
2019	unlink_queue(sma, &queue);
2020
2021out_unlock_free:
2022	sem_unlock(sma, locknum);
2023	rcu_read_unlock();
2024out_free:
2025	if (sops != fast_sops)
2026		kfree(sops);
2027	return error;
2028}
2029
2030SYSCALL_DEFINE3(semop, int, semid, struct sembuf __user *, tsops,
2031		unsigned, nsops)
2032{
2033	return sys_semtimedop(semid, tsops, nsops, NULL);
2034}
2035
2036/* If CLONE_SYSVSEM is set, establish sharing of SEM_UNDO state between
2037 * parent and child tasks.
2038 */
2039
2040int copy_semundo(unsigned long clone_flags, struct task_struct *tsk)
2041{
2042	struct sem_undo_list *undo_list;
2043	int error;
2044
2045	if (clone_flags & CLONE_SYSVSEM) {
2046		error = get_undo_list(&undo_list);
2047		if (error)
2048			return error;
2049		atomic_inc(&undo_list->refcnt);
2050		tsk->sysvsem.undo_list = undo_list;
2051	} else
2052		tsk->sysvsem.undo_list = NULL;
2053
2054	return 0;
2055}
2056
2057/*
2058 * add semadj values to semaphores, free undo structures.
2059 * undo structures are not freed when semaphore arrays are destroyed
2060 * so some of them may be out of date.
2061 * IMPLEMENTATION NOTE: There is some confusion over whether the
2062 * set of adjustments that needs to be done should be done in an atomic
2063 * manner or not. That is, if we are attempting to decrement the semval
2064 * should we queue up and wait until we can do so legally?
2065 * The original implementation attempted to do this (queue and wait).
2066 * The current implementation does not do so. The POSIX standard
2067 * and SVID should be consulted to determine what behavior is mandated.
2068 */
2069void exit_sem(struct task_struct *tsk)
2070{
2071	struct sem_undo_list *ulp;
2072
2073	ulp = tsk->sysvsem.undo_list;
2074	if (!ulp)
2075		return;
2076	tsk->sysvsem.undo_list = NULL;
2077
2078	if (!atomic_dec_and_test(&ulp->refcnt))
2079		return;
2080
2081	for (;;) {
2082		struct sem_array *sma;
2083		struct sem_undo *un;
2084		int semid, i;
2085		DEFINE_WAKE_Q(wake_q);
2086
2087		cond_resched();
2088
2089		rcu_read_lock();
2090		un = list_entry_rcu(ulp->list_proc.next,
2091				    struct sem_undo, list_proc);
2092		if (&un->list_proc == &ulp->list_proc) {
2093			/*
2094			 * We must wait for freeary() before freeing this ulp,
2095			 * in case we raced with last sem_undo. There is a small
2096			 * possibility where we exit while freeary() didn't
2097			 * finish unlocking sem_undo_list.
2098			 */
2099			spin_unlock_wait(&ulp->lock);
2100			rcu_read_unlock();
2101			break;
2102		}
2103		spin_lock(&ulp->lock);
2104		semid = un->semid;
2105		spin_unlock(&ulp->lock);
2106
2107		/* exit_sem raced with IPC_RMID, nothing to do */
2108		if (semid == -1) {
2109			rcu_read_unlock();
2110			continue;
2111		}
2112
2113		sma = sem_obtain_object_check(tsk->nsproxy->ipc_ns, semid);
2114		/* exit_sem raced with IPC_RMID, nothing to do */
2115		if (IS_ERR(sma)) {
2116			rcu_read_unlock();
2117			continue;
2118		}
2119
2120		sem_lock(sma, NULL, -1);
2121		/* exit_sem raced with IPC_RMID, nothing to do */
2122		if (!ipc_valid_object(&sma->sem_perm)) {
2123			sem_unlock(sma, -1);
2124			rcu_read_unlock();
2125			continue;
2126		}
2127		un = __lookup_undo(ulp, semid);
2128		if (un == NULL) {
2129			/* exit_sem raced with IPC_RMID+semget() that created
2130			 * exactly the same semid. Nothing to do.
2131			 */
2132			sem_unlock(sma, -1);
2133			rcu_read_unlock();
2134			continue;
2135		}
2136
2137		/* remove un from the linked lists */
2138		ipc_assert_locked_object(&sma->sem_perm);
2139		list_del(&un->list_id);
2140
2141		/* we are the last process using this ulp, acquiring ulp->lock
2142		 * isn't required. Besides that, we are also protected against
2143		 * IPC_RMID as we hold sma->sem_perm lock now
2144		 */
2145		list_del_rcu(&un->list_proc);
2146
2147		/* perform adjustments registered in un */
2148		for (i = 0; i < sma->sem_nsems; i++) {
2149			struct sem *semaphore = &sma->sems[i];
2150			if (un->semadj[i]) {
2151				semaphore->semval += un->semadj[i];
2152				/*
2153				 * Range checks of the new semaphore value,
2154				 * not defined by sus:
2155				 * - Some unices ignore the undo entirely
2156				 *   (e.g. HP UX 11i 11.22, Tru64 V5.1)
2157				 * - some cap the value (e.g. FreeBSD caps
2158				 *   at 0, but doesn't enforce SEMVMX)
2159				 *
2160				 * Linux caps the semaphore value, both at 0
2161				 * and at SEMVMX.
2162				 *
2163				 *	Manfred <manfred@colorfullife.com>
2164				 */
2165				if (semaphore->semval < 0)
2166					semaphore->semval = 0;
2167				if (semaphore->semval > SEMVMX)
2168					semaphore->semval = SEMVMX;
2169				semaphore->sempid = task_tgid_vnr(current);
2170			}
2171		}
2172		/* maybe some queued-up processes were waiting for this */
2173		do_smart_update(sma, NULL, 0, 1, &wake_q);
2174		sem_unlock(sma, -1);
2175		rcu_read_unlock();
2176		wake_up_q(&wake_q);
2177
2178		kfree_rcu(un, rcu);
2179	}
2180	kfree(ulp);
2181}
2182
2183#ifdef CONFIG_PROC_FS
2184static int sysvipc_sem_proc_show(struct seq_file *s, void *it)
2185{
2186	struct user_namespace *user_ns = seq_user_ns(s);
2187	struct sem_array *sma = it;
2188	time_t sem_otime;
2189
2190	/*
2191	 * The proc interface isn't aware of sem_lock(), it calls
2192	 * ipc_lock_object() directly (in sysvipc_find_ipc).
2193	 * In order to stay compatible with sem_lock(), we must
2194	 * enter / leave complex_mode.
2195	 */
2196	complexmode_enter(sma);
2197
2198	sem_otime = get_semotime(sma);
2199
2200	seq_printf(s,
2201		   "%10d %10d  %4o %10u %5u %5u %5u %5u %10lu %10lu\n",
2202		   sma->sem_perm.key,
2203		   sma->sem_perm.id,
2204		   sma->sem_perm.mode,
2205		   sma->sem_nsems,
2206		   from_kuid_munged(user_ns, sma->sem_perm.uid),
2207		   from_kgid_munged(user_ns, sma->sem_perm.gid),
2208		   from_kuid_munged(user_ns, sma->sem_perm.cuid),
2209		   from_kgid_munged(user_ns, sma->sem_perm.cgid),
2210		   sem_otime,
2211		   sma->sem_ctime);
2212
2213	complexmode_tryleave(sma);
2214
2215	return 0;
2216}
2217#endif
2218