sem.c revision 1b4654ef
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
454/**
455 * newary - Create a new semaphore set
456 * @ns: namespace
457 * @params: ptr to the structure that contains key, semflg and nsems
458 *
459 * Called with sem_ids.rwsem held (as a writer)
460 */
461static int newary(struct ipc_namespace *ns, struct ipc_params *params)
462{
463	int id;
464	int retval;
465	struct sem_array *sma;
466	int size;
467	key_t key = params->key;
468	int nsems = params->u.nsems;
469	int semflg = params->flg;
470	int i;
471
472	if (!nsems)
473		return -EINVAL;
474	if (ns->used_sems + nsems > ns->sc_semmns)
475		return -ENOSPC;
476
477	BUILD_BUG_ON(offsetof(struct sem_array, sem_perm) != 0);
478
479	size = sizeof(*sma) + nsems * sizeof(sma->sems[0]);
480	sma = container_of(ipc_rcu_alloc(size), struct sem_array, sem_perm);
481	if (!sma)
482		return -ENOMEM;
483
484	sma->sem_perm.mode = (semflg & S_IRWXUGO);
485	sma->sem_perm.key = key;
486
487	sma->sem_perm.security = NULL;
488	retval = security_sem_alloc(sma);
489	if (retval) {
490		__sem_free(sma);
491		return retval;
492	}
493
494	for (i = 0; i < nsems; i++) {
495		INIT_LIST_HEAD(&sma->sems[i].pending_alter);
496		INIT_LIST_HEAD(&sma->sems[i].pending_const);
497		spin_lock_init(&sma->sems[i].lock);
498	}
499
500	sma->complex_count = 0;
501	sma->use_global_lock = USE_GLOBAL_LOCK_HYSTERESIS;
502	INIT_LIST_HEAD(&sma->pending_alter);
503	INIT_LIST_HEAD(&sma->pending_const);
504	INIT_LIST_HEAD(&sma->list_id);
505	sma->sem_nsems = nsems;
506	sma->sem_ctime = get_seconds();
507
508	id = ipc_addid(&sem_ids(ns), &sma->sem_perm, ns->sc_semmni);
509	if (id < 0) {
510		ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
511		return id;
512	}
513	ns->used_sems += nsems;
514
515	sem_unlock(sma, -1);
516	rcu_read_unlock();
517
518	return sma->sem_perm.id;
519}
520
521
522/*
523 * Called with sem_ids.rwsem and ipcp locked.
524 */
525static inline int sem_security(struct kern_ipc_perm *ipcp, int semflg)
526{
527	struct sem_array *sma;
528
529	sma = container_of(ipcp, struct sem_array, sem_perm);
530	return security_sem_associate(sma, semflg);
531}
532
533/*
534 * Called with sem_ids.rwsem and ipcp locked.
535 */
536static inline int sem_more_checks(struct kern_ipc_perm *ipcp,
537				struct ipc_params *params)
538{
539	struct sem_array *sma;
540
541	sma = container_of(ipcp, struct sem_array, sem_perm);
542	if (params->u.nsems > sma->sem_nsems)
543		return -EINVAL;
544
545	return 0;
546}
547
548SYSCALL_DEFINE3(semget, key_t, key, int, nsems, int, semflg)
549{
550	struct ipc_namespace *ns;
551	static const struct ipc_ops sem_ops = {
552		.getnew = newary,
553		.associate = sem_security,
554		.more_checks = sem_more_checks,
555	};
556	struct ipc_params sem_params;
557
558	ns = current->nsproxy->ipc_ns;
559
560	if (nsems < 0 || nsems > ns->sc_semmsl)
561		return -EINVAL;
562
563	sem_params.key = key;
564	sem_params.flg = semflg;
565	sem_params.u.nsems = nsems;
566
567	return ipcget(ns, &sem_ids(ns), &sem_ops, &sem_params);
568}
569
570/**
571 * perform_atomic_semop[_slow] - Attempt to perform semaphore
572 *                               operations on a given array.
573 * @sma: semaphore array
574 * @q: struct sem_queue that describes the operation
575 *
576 * Caller blocking are as follows, based the value
577 * indicated by the semaphore operation (sem_op):
578 *
579 *  (1) >0 never blocks.
580 *  (2)  0 (wait-for-zero operation): semval is non-zero.
581 *  (3) <0 attempting to decrement semval to a value smaller than zero.
582 *
583 * Returns 0 if the operation was possible.
584 * Returns 1 if the operation is impossible, the caller must sleep.
585 * Returns <0 for error codes.
586 */
587static int perform_atomic_semop_slow(struct sem_array *sma, struct sem_queue *q)
588{
589	int result, sem_op, nsops, pid;
590	struct sembuf *sop;
591	struct sem *curr;
592	struct sembuf *sops;
593	struct sem_undo *un;
594
595	sops = q->sops;
596	nsops = q->nsops;
597	un = q->undo;
598
599	for (sop = sops; sop < sops + nsops; sop++) {
600		curr = &sma->sems[sop->sem_num];
601		sem_op = sop->sem_op;
602		result = curr->semval;
603
604		if (!sem_op && result)
605			goto would_block;
606
607		result += sem_op;
608		if (result < 0)
609			goto would_block;
610		if (result > SEMVMX)
611			goto out_of_range;
612
613		if (sop->sem_flg & SEM_UNDO) {
614			int undo = un->semadj[sop->sem_num] - sem_op;
615			/* Exceeding the undo range is an error. */
616			if (undo < (-SEMAEM - 1) || undo > SEMAEM)
617				goto out_of_range;
618			un->semadj[sop->sem_num] = undo;
619		}
620
621		curr->semval = result;
622	}
623
624	sop--;
625	pid = q->pid;
626	while (sop >= sops) {
627		sma->sems[sop->sem_num].sempid = pid;
628		sop--;
629	}
630
631	return 0;
632
633out_of_range:
634	result = -ERANGE;
635	goto undo;
636
637would_block:
638	q->blocking = sop;
639
640	if (sop->sem_flg & IPC_NOWAIT)
641		result = -EAGAIN;
642	else
643		result = 1;
644
645undo:
646	sop--;
647	while (sop >= sops) {
648		sem_op = sop->sem_op;
649		sma->sems[sop->sem_num].semval -= sem_op;
650		if (sop->sem_flg & SEM_UNDO)
651			un->semadj[sop->sem_num] += sem_op;
652		sop--;
653	}
654
655	return result;
656}
657
658static int perform_atomic_semop(struct sem_array *sma, struct sem_queue *q)
659{
660	int result, sem_op, nsops;
661	struct sembuf *sop;
662	struct sem *curr;
663	struct sembuf *sops;
664	struct sem_undo *un;
665
666	sops = q->sops;
667	nsops = q->nsops;
668	un = q->undo;
669
670	if (unlikely(q->dupsop))
671		return perform_atomic_semop_slow(sma, q);
672
673	/*
674	 * We scan the semaphore set twice, first to ensure that the entire
675	 * operation can succeed, therefore avoiding any pointless writes
676	 * to shared memory and having to undo such changes in order to block
677	 * until the operations can go through.
678	 */
679	for (sop = sops; sop < sops + nsops; sop++) {
680		curr = &sma->sems[sop->sem_num];
681		sem_op = sop->sem_op;
682		result = curr->semval;
683
684		if (!sem_op && result)
685			goto would_block; /* wait-for-zero */
686
687		result += sem_op;
688		if (result < 0)
689			goto would_block;
690
691		if (result > SEMVMX)
692			return -ERANGE;
693
694		if (sop->sem_flg & SEM_UNDO) {
695			int undo = un->semadj[sop->sem_num] - sem_op;
696
697			/* Exceeding the undo range is an error. */
698			if (undo < (-SEMAEM - 1) || undo > SEMAEM)
699				return -ERANGE;
700		}
701	}
702
703	for (sop = sops; sop < sops + nsops; sop++) {
704		curr = &sma->sems[sop->sem_num];
705		sem_op = sop->sem_op;
706		result = curr->semval;
707
708		if (sop->sem_flg & SEM_UNDO) {
709			int undo = un->semadj[sop->sem_num] - sem_op;
710
711			un->semadj[sop->sem_num] = undo;
712		}
713		curr->semval += sem_op;
714		curr->sempid = q->pid;
715	}
716
717	return 0;
718
719would_block:
720	q->blocking = sop;
721	return sop->sem_flg & IPC_NOWAIT ? -EAGAIN : 1;
722}
723
724static inline void wake_up_sem_queue_prepare(struct sem_queue *q, int error,
725					     struct wake_q_head *wake_q)
726{
727	wake_q_add(wake_q, q->sleeper);
728	/*
729	 * Rely on the above implicit barrier, such that we can
730	 * ensure that we hold reference to the task before setting
731	 * q->status. Otherwise we could race with do_exit if the
732	 * task is awoken by an external event before calling
733	 * wake_up_process().
734	 */
735	WRITE_ONCE(q->status, error);
736}
737
738static void unlink_queue(struct sem_array *sma, struct sem_queue *q)
739{
740	list_del(&q->list);
741	if (q->nsops > 1)
742		sma->complex_count--;
743}
744
745/** check_restart(sma, q)
746 * @sma: semaphore array
747 * @q: the operation that just completed
748 *
749 * update_queue is O(N^2) when it restarts scanning the whole queue of
750 * waiting operations. Therefore this function checks if the restart is
751 * really necessary. It is called after a previously waiting operation
752 * modified the array.
753 * Note that wait-for-zero operations are handled without restart.
754 */
755static inline int check_restart(struct sem_array *sma, struct sem_queue *q)
756{
757	/* pending complex alter operations are too difficult to analyse */
758	if (!list_empty(&sma->pending_alter))
759		return 1;
760
761	/* we were a sleeping complex operation. Too difficult */
762	if (q->nsops > 1)
763		return 1;
764
765	/* It is impossible that someone waits for the new value:
766	 * - complex operations always restart.
767	 * - wait-for-zero are handled seperately.
768	 * - q is a previously sleeping simple operation that
769	 *   altered the array. It must be a decrement, because
770	 *   simple increments never sleep.
771	 * - If there are older (higher priority) decrements
772	 *   in the queue, then they have observed the original
773	 *   semval value and couldn't proceed. The operation
774	 *   decremented to value - thus they won't proceed either.
775	 */
776	return 0;
777}
778
779/**
780 * wake_const_ops - wake up non-alter tasks
781 * @sma: semaphore array.
782 * @semnum: semaphore that was modified.
783 * @wake_q: lockless wake-queue head.
784 *
785 * wake_const_ops must be called after a semaphore in a semaphore array
786 * was set to 0. If complex const operations are pending, wake_const_ops must
787 * be called with semnum = -1, as well as with the number of each modified
788 * semaphore.
789 * The tasks that must be woken up are added to @wake_q. The return code
790 * is stored in q->pid.
791 * The function returns 1 if at least one operation was completed successfully.
792 */
793static int wake_const_ops(struct sem_array *sma, int semnum,
794			  struct wake_q_head *wake_q)
795{
796	struct sem_queue *q, *tmp;
797	struct list_head *pending_list;
798	int semop_completed = 0;
799
800	if (semnum == -1)
801		pending_list = &sma->pending_const;
802	else
803		pending_list = &sma->sems[semnum].pending_const;
804
805	list_for_each_entry_safe(q, tmp, pending_list, list) {
806		int error = perform_atomic_semop(sma, q);
807
808		if (error > 0)
809			continue;
810		/* operation completed, remove from queue & wakeup */
811		unlink_queue(sma, q);
812
813		wake_up_sem_queue_prepare(q, error, wake_q);
814		if (error == 0)
815			semop_completed = 1;
816	}
817
818	return semop_completed;
819}
820
821/**
822 * do_smart_wakeup_zero - wakeup all wait for zero tasks
823 * @sma: semaphore array
824 * @sops: operations that were performed
825 * @nsops: number of operations
826 * @wake_q: lockless wake-queue head
827 *
828 * Checks all required queue for wait-for-zero operations, based
829 * on the actual changes that were performed on the semaphore array.
830 * The function returns 1 if at least one operation was completed successfully.
831 */
832static int do_smart_wakeup_zero(struct sem_array *sma, struct sembuf *sops,
833				int nsops, struct wake_q_head *wake_q)
834{
835	int i;
836	int semop_completed = 0;
837	int got_zero = 0;
838
839	/* first: the per-semaphore queues, if known */
840	if (sops) {
841		for (i = 0; i < nsops; i++) {
842			int num = sops[i].sem_num;
843
844			if (sma->sems[num].semval == 0) {
845				got_zero = 1;
846				semop_completed |= wake_const_ops(sma, num, wake_q);
847			}
848		}
849	} else {
850		/*
851		 * No sops means modified semaphores not known.
852		 * Assume all were changed.
853		 */
854		for (i = 0; i < sma->sem_nsems; i++) {
855			if (sma->sems[i].semval == 0) {
856				got_zero = 1;
857				semop_completed |= wake_const_ops(sma, i, wake_q);
858			}
859		}
860	}
861	/*
862	 * If one of the modified semaphores got 0,
863	 * then check the global queue, too.
864	 */
865	if (got_zero)
866		semop_completed |= wake_const_ops(sma, -1, wake_q);
867
868	return semop_completed;
869}
870
871
872/**
873 * update_queue - look for tasks that can be completed.
874 * @sma: semaphore array.
875 * @semnum: semaphore that was modified.
876 * @wake_q: lockless wake-queue head.
877 *
878 * update_queue must be called after a semaphore in a semaphore array
879 * was modified. If multiple semaphores were modified, update_queue must
880 * be called with semnum = -1, as well as with the number of each modified
881 * semaphore.
882 * The tasks that must be woken up are added to @wake_q. The return code
883 * is stored in q->pid.
884 * The function internally checks if const operations can now succeed.
885 *
886 * The function return 1 if at least one semop was completed successfully.
887 */
888static int update_queue(struct sem_array *sma, int semnum, struct wake_q_head *wake_q)
889{
890	struct sem_queue *q, *tmp;
891	struct list_head *pending_list;
892	int semop_completed = 0;
893
894	if (semnum == -1)
895		pending_list = &sma->pending_alter;
896	else
897		pending_list = &sma->sems[semnum].pending_alter;
898
899again:
900	list_for_each_entry_safe(q, tmp, pending_list, list) {
901		int error, restart;
902
903		/* If we are scanning the single sop, per-semaphore list of
904		 * one semaphore and that semaphore is 0, then it is not
905		 * necessary to scan further: simple increments
906		 * that affect only one entry succeed immediately and cannot
907		 * be in the  per semaphore pending queue, and decrements
908		 * cannot be successful if the value is already 0.
909		 */
910		if (semnum != -1 && sma->sems[semnum].semval == 0)
911			break;
912
913		error = perform_atomic_semop(sma, q);
914
915		/* Does q->sleeper still need to sleep? */
916		if (error > 0)
917			continue;
918
919		unlink_queue(sma, q);
920
921		if (error) {
922			restart = 0;
923		} else {
924			semop_completed = 1;
925			do_smart_wakeup_zero(sma, q->sops, q->nsops, wake_q);
926			restart = check_restart(sma, q);
927		}
928
929		wake_up_sem_queue_prepare(q, error, wake_q);
930		if (restart)
931			goto again;
932	}
933	return semop_completed;
934}
935
936/**
937 * set_semotime - set sem_otime
938 * @sma: semaphore array
939 * @sops: operations that modified the array, may be NULL
940 *
941 * sem_otime is replicated to avoid cache line trashing.
942 * This function sets one instance to the current time.
943 */
944static void set_semotime(struct sem_array *sma, struct sembuf *sops)
945{
946	if (sops == NULL) {
947		sma->sems[0].sem_otime = get_seconds();
948	} else {
949		sma->sems[sops[0].sem_num].sem_otime =
950							get_seconds();
951	}
952}
953
954/**
955 * do_smart_update - optimized update_queue
956 * @sma: semaphore array
957 * @sops: operations that were performed
958 * @nsops: number of operations
959 * @otime: force setting otime
960 * @wake_q: lockless wake-queue head
961 *
962 * do_smart_update() does the required calls to update_queue and wakeup_zero,
963 * based on the actual changes that were performed on the semaphore array.
964 * Note that the function does not do the actual wake-up: the caller is
965 * responsible for calling wake_up_q().
966 * It is safe to perform this call after dropping all locks.
967 */
968static void do_smart_update(struct sem_array *sma, struct sembuf *sops, int nsops,
969			    int otime, struct wake_q_head *wake_q)
970{
971	int i;
972
973	otime |= do_smart_wakeup_zero(sma, sops, nsops, wake_q);
974
975	if (!list_empty(&sma->pending_alter)) {
976		/* semaphore array uses the global queue - just process it. */
977		otime |= update_queue(sma, -1, wake_q);
978	} else {
979		if (!sops) {
980			/*
981			 * No sops, thus the modified semaphores are not
982			 * known. Check all.
983			 */
984			for (i = 0; i < sma->sem_nsems; i++)
985				otime |= update_queue(sma, i, wake_q);
986		} else {
987			/*
988			 * Check the semaphores that were increased:
989			 * - No complex ops, thus all sleeping ops are
990			 *   decrease.
991			 * - if we decreased the value, then any sleeping
992			 *   semaphore ops wont be able to run: If the
993			 *   previous value was too small, then the new
994			 *   value will be too small, too.
995			 */
996			for (i = 0; i < nsops; i++) {
997				if (sops[i].sem_op > 0) {
998					otime |= update_queue(sma,
999							      sops[i].sem_num, wake_q);
1000				}
1001			}
1002		}
1003	}
1004	if (otime)
1005		set_semotime(sma, sops);
1006}
1007
1008/*
1009 * check_qop: Test if a queued operation sleeps on the semaphore semnum
1010 */
1011static int check_qop(struct sem_array *sma, int semnum, struct sem_queue *q,
1012			bool count_zero)
1013{
1014	struct sembuf *sop = q->blocking;
1015
1016	/*
1017	 * Linux always (since 0.99.10) reported a task as sleeping on all
1018	 * semaphores. This violates SUS, therefore it was changed to the
1019	 * standard compliant behavior.
1020	 * Give the administrators a chance to notice that an application
1021	 * might misbehave because it relies on the Linux behavior.
1022	 */
1023	pr_info_once("semctl(GETNCNT/GETZCNT) is since 3.16 Single Unix Specification compliant.\n"
1024			"The task %s (%d) triggered the difference, watch for misbehavior.\n",
1025			current->comm, task_pid_nr(current));
1026
1027	if (sop->sem_num != semnum)
1028		return 0;
1029
1030	if (count_zero && sop->sem_op == 0)
1031		return 1;
1032	if (!count_zero && sop->sem_op < 0)
1033		return 1;
1034
1035	return 0;
1036}
1037
1038/* The following counts are associated to each semaphore:
1039 *   semncnt        number of tasks waiting on semval being nonzero
1040 *   semzcnt        number of tasks waiting on semval being zero
1041 *
1042 * Per definition, a task waits only on the semaphore of the first semop
1043 * that cannot proceed, even if additional operation would block, too.
1044 */
1045static int count_semcnt(struct sem_array *sma, ushort semnum,
1046			bool count_zero)
1047{
1048	struct list_head *l;
1049	struct sem_queue *q;
1050	int semcnt;
1051
1052	semcnt = 0;
1053	/* First: check the simple operations. They are easy to evaluate */
1054	if (count_zero)
1055		l = &sma->sems[semnum].pending_const;
1056	else
1057		l = &sma->sems[semnum].pending_alter;
1058
1059	list_for_each_entry(q, l, list) {
1060		/* all task on a per-semaphore list sleep on exactly
1061		 * that semaphore
1062		 */
1063		semcnt++;
1064	}
1065
1066	/* Then: check the complex operations. */
1067	list_for_each_entry(q, &sma->pending_alter, list) {
1068		semcnt += check_qop(sma, semnum, q, count_zero);
1069	}
1070	if (count_zero) {
1071		list_for_each_entry(q, &sma->pending_const, list) {
1072			semcnt += check_qop(sma, semnum, q, count_zero);
1073		}
1074	}
1075	return semcnt;
1076}
1077
1078/* Free a semaphore set. freeary() is called with sem_ids.rwsem locked
1079 * as a writer and the spinlock for this semaphore set hold. sem_ids.rwsem
1080 * remains locked on exit.
1081 */
1082static void freeary(struct ipc_namespace *ns, struct kern_ipc_perm *ipcp)
1083{
1084	struct sem_undo *un, *tu;
1085	struct sem_queue *q, *tq;
1086	struct sem_array *sma = container_of(ipcp, struct sem_array, sem_perm);
1087	int i;
1088	DEFINE_WAKE_Q(wake_q);
1089
1090	/* Free the existing undo structures for this semaphore set.  */
1091	ipc_assert_locked_object(&sma->sem_perm);
1092	list_for_each_entry_safe(un, tu, &sma->list_id, list_id) {
1093		list_del(&un->list_id);
1094		spin_lock(&un->ulp->lock);
1095		un->semid = -1;
1096		list_del_rcu(&un->list_proc);
1097		spin_unlock(&un->ulp->lock);
1098		kfree_rcu(un, rcu);
1099	}
1100
1101	/* Wake up all pending processes and let them fail with EIDRM. */
1102	list_for_each_entry_safe(q, tq, &sma->pending_const, list) {
1103		unlink_queue(sma, q);
1104		wake_up_sem_queue_prepare(q, -EIDRM, &wake_q);
1105	}
1106
1107	list_for_each_entry_safe(q, tq, &sma->pending_alter, list) {
1108		unlink_queue(sma, q);
1109		wake_up_sem_queue_prepare(q, -EIDRM, &wake_q);
1110	}
1111	for (i = 0; i < sma->sem_nsems; i++) {
1112		struct sem *sem = &sma->sems[i];
1113		list_for_each_entry_safe(q, tq, &sem->pending_const, list) {
1114			unlink_queue(sma, q);
1115			wake_up_sem_queue_prepare(q, -EIDRM, &wake_q);
1116		}
1117		list_for_each_entry_safe(q, tq, &sem->pending_alter, list) {
1118			unlink_queue(sma, q);
1119			wake_up_sem_queue_prepare(q, -EIDRM, &wake_q);
1120		}
1121	}
1122
1123	/* Remove the semaphore set from the IDR */
1124	sem_rmid(ns, sma);
1125	sem_unlock(sma, -1);
1126	rcu_read_unlock();
1127
1128	wake_up_q(&wake_q);
1129	ns->used_sems -= sma->sem_nsems;
1130	ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
1131}
1132
1133static unsigned long copy_semid_to_user(void __user *buf, struct semid64_ds *in, int version)
1134{
1135	switch (version) {
1136	case IPC_64:
1137		return copy_to_user(buf, in, sizeof(*in));
1138	case IPC_OLD:
1139	    {
1140		struct semid_ds out;
1141
1142		memset(&out, 0, sizeof(out));
1143
1144		ipc64_perm_to_ipc_perm(&in->sem_perm, &out.sem_perm);
1145
1146		out.sem_otime	= in->sem_otime;
1147		out.sem_ctime	= in->sem_ctime;
1148		out.sem_nsems	= in->sem_nsems;
1149
1150		return copy_to_user(buf, &out, sizeof(out));
1151	    }
1152	default:
1153		return -EINVAL;
1154	}
1155}
1156
1157static time_t get_semotime(struct sem_array *sma)
1158{
1159	int i;
1160	time_t res;
1161
1162	res = sma->sems[0].sem_otime;
1163	for (i = 1; i < sma->sem_nsems; i++) {
1164		time_t to = sma->sems[i].sem_otime;
1165
1166		if (to > res)
1167			res = to;
1168	}
1169	return res;
1170}
1171
1172static int semctl_nolock(struct ipc_namespace *ns, int semid,
1173			 int cmd, int version, void __user *p)
1174{
1175	int err;
1176	struct sem_array *sma;
1177
1178	switch (cmd) {
1179	case IPC_INFO:
1180	case SEM_INFO:
1181	{
1182		struct seminfo seminfo;
1183		int max_id;
1184
1185		err = security_sem_semctl(NULL, cmd);
1186		if (err)
1187			return err;
1188
1189		memset(&seminfo, 0, sizeof(seminfo));
1190		seminfo.semmni = ns->sc_semmni;
1191		seminfo.semmns = ns->sc_semmns;
1192		seminfo.semmsl = ns->sc_semmsl;
1193		seminfo.semopm = ns->sc_semopm;
1194		seminfo.semvmx = SEMVMX;
1195		seminfo.semmnu = SEMMNU;
1196		seminfo.semmap = SEMMAP;
1197		seminfo.semume = SEMUME;
1198		down_read(&sem_ids(ns).rwsem);
1199		if (cmd == SEM_INFO) {
1200			seminfo.semusz = sem_ids(ns).in_use;
1201			seminfo.semaem = ns->used_sems;
1202		} else {
1203			seminfo.semusz = SEMUSZ;
1204			seminfo.semaem = SEMAEM;
1205		}
1206		max_id = ipc_get_maxid(&sem_ids(ns));
1207		up_read(&sem_ids(ns).rwsem);
1208		if (copy_to_user(p, &seminfo, sizeof(struct seminfo)))
1209			return -EFAULT;
1210		return (max_id < 0) ? 0 : max_id;
1211	}
1212	case IPC_STAT:
1213	case SEM_STAT:
1214	{
1215		struct semid64_ds tbuf;
1216		int id = 0;
1217
1218		memset(&tbuf, 0, sizeof(tbuf));
1219
1220		rcu_read_lock();
1221		if (cmd == SEM_STAT) {
1222			sma = sem_obtain_object(ns, semid);
1223			if (IS_ERR(sma)) {
1224				err = PTR_ERR(sma);
1225				goto out_unlock;
1226			}
1227			id = sma->sem_perm.id;
1228		} else {
1229			sma = sem_obtain_object_check(ns, semid);
1230			if (IS_ERR(sma)) {
1231				err = PTR_ERR(sma);
1232				goto out_unlock;
1233			}
1234		}
1235
1236		err = -EACCES;
1237		if (ipcperms(ns, &sma->sem_perm, S_IRUGO))
1238			goto out_unlock;
1239
1240		err = security_sem_semctl(sma, cmd);
1241		if (err)
1242			goto out_unlock;
1243
1244		kernel_to_ipc64_perm(&sma->sem_perm, &tbuf.sem_perm);
1245		tbuf.sem_otime = get_semotime(sma);
1246		tbuf.sem_ctime = sma->sem_ctime;
1247		tbuf.sem_nsems = sma->sem_nsems;
1248		rcu_read_unlock();
1249		if (copy_semid_to_user(p, &tbuf, version))
1250			return -EFAULT;
1251		return id;
1252	}
1253	default:
1254		return -EINVAL;
1255	}
1256out_unlock:
1257	rcu_read_unlock();
1258	return err;
1259}
1260
1261static int semctl_setval(struct ipc_namespace *ns, int semid, int semnum,
1262		unsigned long arg)
1263{
1264	struct sem_undo *un;
1265	struct sem_array *sma;
1266	struct sem *curr;
1267	int err, val;
1268	DEFINE_WAKE_Q(wake_q);
1269
1270#if defined(CONFIG_64BIT) && defined(__BIG_ENDIAN)
1271	/* big-endian 64bit */
1272	val = arg >> 32;
1273#else
1274	/* 32bit or little-endian 64bit */
1275	val = arg;
1276#endif
1277
1278	if (val > SEMVMX || val < 0)
1279		return -ERANGE;
1280
1281	rcu_read_lock();
1282	sma = sem_obtain_object_check(ns, semid);
1283	if (IS_ERR(sma)) {
1284		rcu_read_unlock();
1285		return PTR_ERR(sma);
1286	}
1287
1288	if (semnum < 0 || semnum >= sma->sem_nsems) {
1289		rcu_read_unlock();
1290		return -EINVAL;
1291	}
1292
1293
1294	if (ipcperms(ns, &sma->sem_perm, S_IWUGO)) {
1295		rcu_read_unlock();
1296		return -EACCES;
1297	}
1298
1299	err = security_sem_semctl(sma, SETVAL);
1300	if (err) {
1301		rcu_read_unlock();
1302		return -EACCES;
1303	}
1304
1305	sem_lock(sma, NULL, -1);
1306
1307	if (!ipc_valid_object(&sma->sem_perm)) {
1308		sem_unlock(sma, -1);
1309		rcu_read_unlock();
1310		return -EIDRM;
1311	}
1312
1313	curr = &sma->sems[semnum];
1314
1315	ipc_assert_locked_object(&sma->sem_perm);
1316	list_for_each_entry(un, &sma->list_id, list_id)
1317		un->semadj[semnum] = 0;
1318
1319	curr->semval = val;
1320	curr->sempid = task_tgid_vnr(current);
1321	sma->sem_ctime = get_seconds();
1322	/* maybe some queued-up processes were waiting for this */
1323	do_smart_update(sma, NULL, 0, 0, &wake_q);
1324	sem_unlock(sma, -1);
1325	rcu_read_unlock();
1326	wake_up_q(&wake_q);
1327	return 0;
1328}
1329
1330static int semctl_main(struct ipc_namespace *ns, int semid, int semnum,
1331		int cmd, void __user *p)
1332{
1333	struct sem_array *sma;
1334	struct sem *curr;
1335	int err, nsems;
1336	ushort fast_sem_io[SEMMSL_FAST];
1337	ushort *sem_io = fast_sem_io;
1338	DEFINE_WAKE_Q(wake_q);
1339
1340	rcu_read_lock();
1341	sma = sem_obtain_object_check(ns, semid);
1342	if (IS_ERR(sma)) {
1343		rcu_read_unlock();
1344		return PTR_ERR(sma);
1345	}
1346
1347	nsems = sma->sem_nsems;
1348
1349	err = -EACCES;
1350	if (ipcperms(ns, &sma->sem_perm, cmd == SETALL ? S_IWUGO : S_IRUGO))
1351		goto out_rcu_wakeup;
1352
1353	err = security_sem_semctl(sma, cmd);
1354	if (err)
1355		goto out_rcu_wakeup;
1356
1357	err = -EACCES;
1358	switch (cmd) {
1359	case GETALL:
1360	{
1361		ushort __user *array = p;
1362		int i;
1363
1364		sem_lock(sma, NULL, -1);
1365		if (!ipc_valid_object(&sma->sem_perm)) {
1366			err = -EIDRM;
1367			goto out_unlock;
1368		}
1369		if (nsems > SEMMSL_FAST) {
1370			if (!ipc_rcu_getref(&sma->sem_perm)) {
1371				err = -EIDRM;
1372				goto out_unlock;
1373			}
1374			sem_unlock(sma, -1);
1375			rcu_read_unlock();
1376			sem_io = kvmalloc_array(nsems, sizeof(ushort),
1377						GFP_KERNEL);
1378			if (sem_io == NULL) {
1379				ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
1380				return -ENOMEM;
1381			}
1382
1383			rcu_read_lock();
1384			sem_lock_and_putref(sma);
1385			if (!ipc_valid_object(&sma->sem_perm)) {
1386				err = -EIDRM;
1387				goto out_unlock;
1388			}
1389		}
1390		for (i = 0; i < sma->sem_nsems; i++)
1391			sem_io[i] = sma->sems[i].semval;
1392		sem_unlock(sma, -1);
1393		rcu_read_unlock();
1394		err = 0;
1395		if (copy_to_user(array, sem_io, nsems*sizeof(ushort)))
1396			err = -EFAULT;
1397		goto out_free;
1398	}
1399	case SETALL:
1400	{
1401		int i;
1402		struct sem_undo *un;
1403
1404		if (!ipc_rcu_getref(&sma->sem_perm)) {
1405			err = -EIDRM;
1406			goto out_rcu_wakeup;
1407		}
1408		rcu_read_unlock();
1409
1410		if (nsems > SEMMSL_FAST) {
1411			sem_io = kvmalloc_array(nsems, sizeof(ushort),
1412						GFP_KERNEL);
1413			if (sem_io == NULL) {
1414				ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
1415				return -ENOMEM;
1416			}
1417		}
1418
1419		if (copy_from_user(sem_io, p, nsems*sizeof(ushort))) {
1420			ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
1421			err = -EFAULT;
1422			goto out_free;
1423		}
1424
1425		for (i = 0; i < nsems; i++) {
1426			if (sem_io[i] > SEMVMX) {
1427				ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
1428				err = -ERANGE;
1429				goto out_free;
1430			}
1431		}
1432		rcu_read_lock();
1433		sem_lock_and_putref(sma);
1434		if (!ipc_valid_object(&sma->sem_perm)) {
1435			err = -EIDRM;
1436			goto out_unlock;
1437		}
1438
1439		for (i = 0; i < nsems; i++) {
1440			sma->sems[i].semval = sem_io[i];
1441			sma->sems[i].sempid = task_tgid_vnr(current);
1442		}
1443
1444		ipc_assert_locked_object(&sma->sem_perm);
1445		list_for_each_entry(un, &sma->list_id, list_id) {
1446			for (i = 0; i < nsems; i++)
1447				un->semadj[i] = 0;
1448		}
1449		sma->sem_ctime = get_seconds();
1450		/* maybe some queued-up processes were waiting for this */
1451		do_smart_update(sma, NULL, 0, 0, &wake_q);
1452		err = 0;
1453		goto out_unlock;
1454	}
1455	/* GETVAL, GETPID, GETNCTN, GETZCNT: fall-through */
1456	}
1457	err = -EINVAL;
1458	if (semnum < 0 || semnum >= nsems)
1459		goto out_rcu_wakeup;
1460
1461	sem_lock(sma, NULL, -1);
1462	if (!ipc_valid_object(&sma->sem_perm)) {
1463		err = -EIDRM;
1464		goto out_unlock;
1465	}
1466	curr = &sma->sems[semnum];
1467
1468	switch (cmd) {
1469	case GETVAL:
1470		err = curr->semval;
1471		goto out_unlock;
1472	case GETPID:
1473		err = curr->sempid;
1474		goto out_unlock;
1475	case GETNCNT:
1476		err = count_semcnt(sma, semnum, 0);
1477		goto out_unlock;
1478	case GETZCNT:
1479		err = count_semcnt(sma, semnum, 1);
1480		goto out_unlock;
1481	}
1482
1483out_unlock:
1484	sem_unlock(sma, -1);
1485out_rcu_wakeup:
1486	rcu_read_unlock();
1487	wake_up_q(&wake_q);
1488out_free:
1489	if (sem_io != fast_sem_io)
1490		kvfree(sem_io);
1491	return err;
1492}
1493
1494static inline unsigned long
1495copy_semid_from_user(struct semid64_ds *out, void __user *buf, int version)
1496{
1497	switch (version) {
1498	case IPC_64:
1499		if (copy_from_user(out, buf, sizeof(*out)))
1500			return -EFAULT;
1501		return 0;
1502	case IPC_OLD:
1503	    {
1504		struct semid_ds tbuf_old;
1505
1506		if (copy_from_user(&tbuf_old, buf, sizeof(tbuf_old)))
1507			return -EFAULT;
1508
1509		out->sem_perm.uid	= tbuf_old.sem_perm.uid;
1510		out->sem_perm.gid	= tbuf_old.sem_perm.gid;
1511		out->sem_perm.mode	= tbuf_old.sem_perm.mode;
1512
1513		return 0;
1514	    }
1515	default:
1516		return -EINVAL;
1517	}
1518}
1519
1520/*
1521 * This function handles some semctl commands which require the rwsem
1522 * to be held in write mode.
1523 * NOTE: no locks must be held, the rwsem is taken inside this function.
1524 */
1525static int semctl_down(struct ipc_namespace *ns, int semid,
1526		       int cmd, int version, void __user *p)
1527{
1528	struct sem_array *sma;
1529	int err;
1530	struct semid64_ds semid64;
1531	struct kern_ipc_perm *ipcp;
1532
1533	if (cmd == IPC_SET) {
1534		if (copy_semid_from_user(&semid64, p, version))
1535			return -EFAULT;
1536	}
1537
1538	down_write(&sem_ids(ns).rwsem);
1539	rcu_read_lock();
1540
1541	ipcp = ipcctl_pre_down_nolock(ns, &sem_ids(ns), semid, cmd,
1542				      &semid64.sem_perm, 0);
1543	if (IS_ERR(ipcp)) {
1544		err = PTR_ERR(ipcp);
1545		goto out_unlock1;
1546	}
1547
1548	sma = container_of(ipcp, struct sem_array, sem_perm);
1549
1550	err = security_sem_semctl(sma, cmd);
1551	if (err)
1552		goto out_unlock1;
1553
1554	switch (cmd) {
1555	case IPC_RMID:
1556		sem_lock(sma, NULL, -1);
1557		/* freeary unlocks the ipc object and rcu */
1558		freeary(ns, ipcp);
1559		goto out_up;
1560	case IPC_SET:
1561		sem_lock(sma, NULL, -1);
1562		err = ipc_update_perm(&semid64.sem_perm, ipcp);
1563		if (err)
1564			goto out_unlock0;
1565		sma->sem_ctime = get_seconds();
1566		break;
1567	default:
1568		err = -EINVAL;
1569		goto out_unlock1;
1570	}
1571
1572out_unlock0:
1573	sem_unlock(sma, -1);
1574out_unlock1:
1575	rcu_read_unlock();
1576out_up:
1577	up_write(&sem_ids(ns).rwsem);
1578	return err;
1579}
1580
1581SYSCALL_DEFINE4(semctl, int, semid, int, semnum, int, cmd, unsigned long, arg)
1582{
1583	int version;
1584	struct ipc_namespace *ns;
1585	void __user *p = (void __user *)arg;
1586
1587	if (semid < 0)
1588		return -EINVAL;
1589
1590	version = ipc_parse_version(&cmd);
1591	ns = current->nsproxy->ipc_ns;
1592
1593	switch (cmd) {
1594	case IPC_INFO:
1595	case SEM_INFO:
1596	case IPC_STAT:
1597	case SEM_STAT:
1598		return semctl_nolock(ns, semid, cmd, version, p);
1599	case GETALL:
1600	case GETVAL:
1601	case GETPID:
1602	case GETNCNT:
1603	case GETZCNT:
1604	case SETALL:
1605		return semctl_main(ns, semid, semnum, cmd, p);
1606	case SETVAL:
1607		return semctl_setval(ns, semid, semnum, arg);
1608	case IPC_RMID:
1609	case IPC_SET:
1610		return semctl_down(ns, semid, cmd, version, p);
1611	default:
1612		return -EINVAL;
1613	}
1614}
1615
1616/* If the task doesn't already have a undo_list, then allocate one
1617 * here.  We guarantee there is only one thread using this undo list,
1618 * and current is THE ONE
1619 *
1620 * If this allocation and assignment succeeds, but later
1621 * portions of this code fail, there is no need to free the sem_undo_list.
1622 * Just let it stay associated with the task, and it'll be freed later
1623 * at exit time.
1624 *
1625 * This can block, so callers must hold no locks.
1626 */
1627static inline int get_undo_list(struct sem_undo_list **undo_listp)
1628{
1629	struct sem_undo_list *undo_list;
1630
1631	undo_list = current->sysvsem.undo_list;
1632	if (!undo_list) {
1633		undo_list = kzalloc(sizeof(*undo_list), GFP_KERNEL);
1634		if (undo_list == NULL)
1635			return -ENOMEM;
1636		spin_lock_init(&undo_list->lock);
1637		atomic_set(&undo_list->refcnt, 1);
1638		INIT_LIST_HEAD(&undo_list->list_proc);
1639
1640		current->sysvsem.undo_list = undo_list;
1641	}
1642	*undo_listp = undo_list;
1643	return 0;
1644}
1645
1646static struct sem_undo *__lookup_undo(struct sem_undo_list *ulp, int semid)
1647{
1648	struct sem_undo *un;
1649
1650	list_for_each_entry_rcu(un, &ulp->list_proc, list_proc) {
1651		if (un->semid == semid)
1652			return un;
1653	}
1654	return NULL;
1655}
1656
1657static struct sem_undo *lookup_undo(struct sem_undo_list *ulp, int semid)
1658{
1659	struct sem_undo *un;
1660
1661	assert_spin_locked(&ulp->lock);
1662
1663	un = __lookup_undo(ulp, semid);
1664	if (un) {
1665		list_del_rcu(&un->list_proc);
1666		list_add_rcu(&un->list_proc, &ulp->list_proc);
1667	}
1668	return un;
1669}
1670
1671/**
1672 * find_alloc_undo - lookup (and if not present create) undo array
1673 * @ns: namespace
1674 * @semid: semaphore array id
1675 *
1676 * The function looks up (and if not present creates) the undo structure.
1677 * The size of the undo structure depends on the size of the semaphore
1678 * array, thus the alloc path is not that straightforward.
1679 * Lifetime-rules: sem_undo is rcu-protected, on success, the function
1680 * performs a rcu_read_lock().
1681 */
1682static struct sem_undo *find_alloc_undo(struct ipc_namespace *ns, int semid)
1683{
1684	struct sem_array *sma;
1685	struct sem_undo_list *ulp;
1686	struct sem_undo *un, *new;
1687	int nsems, error;
1688
1689	error = get_undo_list(&ulp);
1690	if (error)
1691		return ERR_PTR(error);
1692
1693	rcu_read_lock();
1694	spin_lock(&ulp->lock);
1695	un = lookup_undo(ulp, semid);
1696	spin_unlock(&ulp->lock);
1697	if (likely(un != NULL))
1698		goto out;
1699
1700	/* no undo structure around - allocate one. */
1701	/* step 1: figure out the size of the semaphore array */
1702	sma = sem_obtain_object_check(ns, semid);
1703	if (IS_ERR(sma)) {
1704		rcu_read_unlock();
1705		return ERR_CAST(sma);
1706	}
1707
1708	nsems = sma->sem_nsems;
1709	if (!ipc_rcu_getref(&sma->sem_perm)) {
1710		rcu_read_unlock();
1711		un = ERR_PTR(-EIDRM);
1712		goto out;
1713	}
1714	rcu_read_unlock();
1715
1716	/* step 2: allocate new undo structure */
1717	new = kzalloc(sizeof(struct sem_undo) + sizeof(short)*nsems, GFP_KERNEL);
1718	if (!new) {
1719		ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
1720		return ERR_PTR(-ENOMEM);
1721	}
1722
1723	/* step 3: Acquire the lock on semaphore array */
1724	rcu_read_lock();
1725	sem_lock_and_putref(sma);
1726	if (!ipc_valid_object(&sma->sem_perm)) {
1727		sem_unlock(sma, -1);
1728		rcu_read_unlock();
1729		kfree(new);
1730		un = ERR_PTR(-EIDRM);
1731		goto out;
1732	}
1733	spin_lock(&ulp->lock);
1734
1735	/*
1736	 * step 4: check for races: did someone else allocate the undo struct?
1737	 */
1738	un = lookup_undo(ulp, semid);
1739	if (un) {
1740		kfree(new);
1741		goto success;
1742	}
1743	/* step 5: initialize & link new undo structure */
1744	new->semadj = (short *) &new[1];
1745	new->ulp = ulp;
1746	new->semid = semid;
1747	assert_spin_locked(&ulp->lock);
1748	list_add_rcu(&new->list_proc, &ulp->list_proc);
1749	ipc_assert_locked_object(&sma->sem_perm);
1750	list_add(&new->list_id, &sma->list_id);
1751	un = new;
1752
1753success:
1754	spin_unlock(&ulp->lock);
1755	sem_unlock(sma, -1);
1756out:
1757	return un;
1758}
1759
1760SYSCALL_DEFINE4(semtimedop, int, semid, struct sembuf __user *, tsops,
1761		unsigned, nsops, const struct timespec __user *, timeout)
1762{
1763	int error = -EINVAL;
1764	struct sem_array *sma;
1765	struct sembuf fast_sops[SEMOPM_FAST];
1766	struct sembuf *sops = fast_sops, *sop;
1767	struct sem_undo *un;
1768	int max, locknum;
1769	bool undos = false, alter = false, dupsop = false;
1770	struct sem_queue queue;
1771	unsigned long dup = 0, jiffies_left = 0;
1772	struct ipc_namespace *ns;
1773
1774	ns = current->nsproxy->ipc_ns;
1775
1776	if (nsops < 1 || semid < 0)
1777		return -EINVAL;
1778	if (nsops > ns->sc_semopm)
1779		return -E2BIG;
1780	if (nsops > SEMOPM_FAST) {
1781		sops = kmalloc(sizeof(*sops)*nsops, GFP_KERNEL);
1782		if (sops == NULL)
1783			return -ENOMEM;
1784	}
1785
1786	if (copy_from_user(sops, tsops, nsops * sizeof(*tsops))) {
1787		error =  -EFAULT;
1788		goto out_free;
1789	}
1790
1791	if (timeout) {
1792		struct timespec _timeout;
1793		if (copy_from_user(&_timeout, timeout, sizeof(*timeout))) {
1794			error = -EFAULT;
1795			goto out_free;
1796		}
1797		if (_timeout.tv_sec < 0 || _timeout.tv_nsec < 0 ||
1798			_timeout.tv_nsec >= 1000000000L) {
1799			error = -EINVAL;
1800			goto out_free;
1801		}
1802		jiffies_left = timespec_to_jiffies(&_timeout);
1803	}
1804
1805	max = 0;
1806	for (sop = sops; sop < sops + nsops; sop++) {
1807		unsigned long mask = 1ULL << ((sop->sem_num) % BITS_PER_LONG);
1808
1809		if (sop->sem_num >= max)
1810			max = sop->sem_num;
1811		if (sop->sem_flg & SEM_UNDO)
1812			undos = true;
1813		if (dup & mask) {
1814			/*
1815			 * There was a previous alter access that appears
1816			 * to have accessed the same semaphore, thus use
1817			 * the dupsop logic. "appears", because the detection
1818			 * can only check % BITS_PER_LONG.
1819			 */
1820			dupsop = true;
1821		}
1822		if (sop->sem_op != 0) {
1823			alter = true;
1824			dup |= mask;
1825		}
1826	}
1827
1828	if (undos) {
1829		/* On success, find_alloc_undo takes the rcu_read_lock */
1830		un = find_alloc_undo(ns, semid);
1831		if (IS_ERR(un)) {
1832			error = PTR_ERR(un);
1833			goto out_free;
1834		}
1835	} else {
1836		un = NULL;
1837		rcu_read_lock();
1838	}
1839
1840	sma = sem_obtain_object_check(ns, semid);
1841	if (IS_ERR(sma)) {
1842		rcu_read_unlock();
1843		error = PTR_ERR(sma);
1844		goto out_free;
1845	}
1846
1847	error = -EFBIG;
1848	if (max >= sma->sem_nsems) {
1849		rcu_read_unlock();
1850		goto out_free;
1851	}
1852
1853	error = -EACCES;
1854	if (ipcperms(ns, &sma->sem_perm, alter ? S_IWUGO : S_IRUGO)) {
1855		rcu_read_unlock();
1856		goto out_free;
1857	}
1858
1859	error = security_sem_semop(sma, sops, nsops, alter);
1860	if (error) {
1861		rcu_read_unlock();
1862		goto out_free;
1863	}
1864
1865	error = -EIDRM;
1866	locknum = sem_lock(sma, sops, nsops);
1867	/*
1868	 * We eventually might perform the following check in a lockless
1869	 * fashion, considering ipc_valid_object() locking constraints.
1870	 * If nsops == 1 and there is no contention for sem_perm.lock, then
1871	 * only a per-semaphore lock is held and it's OK to proceed with the
1872	 * check below. More details on the fine grained locking scheme
1873	 * entangled here and why it's RMID race safe on comments at sem_lock()
1874	 */
1875	if (!ipc_valid_object(&sma->sem_perm))
1876		goto out_unlock_free;
1877	/*
1878	 * semid identifiers are not unique - find_alloc_undo may have
1879	 * allocated an undo structure, it was invalidated by an RMID
1880	 * and now a new array with received the same id. Check and fail.
1881	 * This case can be detected checking un->semid. The existence of
1882	 * "un" itself is guaranteed by rcu.
1883	 */
1884	if (un && un->semid == -1)
1885		goto out_unlock_free;
1886
1887	queue.sops = sops;
1888	queue.nsops = nsops;
1889	queue.undo = un;
1890	queue.pid = task_tgid_vnr(current);
1891	queue.alter = alter;
1892	queue.dupsop = dupsop;
1893
1894	error = perform_atomic_semop(sma, &queue);
1895	if (error == 0) { /* non-blocking succesfull path */
1896		DEFINE_WAKE_Q(wake_q);
1897
1898		/*
1899		 * If the operation was successful, then do
1900		 * the required updates.
1901		 */
1902		if (alter)
1903			do_smart_update(sma, sops, nsops, 1, &wake_q);
1904		else
1905			set_semotime(sma, sops);
1906
1907		sem_unlock(sma, locknum);
1908		rcu_read_unlock();
1909		wake_up_q(&wake_q);
1910
1911		goto out_free;
1912	}
1913	if (error < 0) /* non-blocking error path */
1914		goto out_unlock_free;
1915
1916	/*
1917	 * We need to sleep on this operation, so we put the current
1918	 * task into the pending queue and go to sleep.
1919	 */
1920	if (nsops == 1) {
1921		struct sem *curr;
1922		curr = &sma->sems[sops->sem_num];
1923
1924		if (alter) {
1925			if (sma->complex_count) {
1926				list_add_tail(&queue.list,
1927						&sma->pending_alter);
1928			} else {
1929
1930				list_add_tail(&queue.list,
1931						&curr->pending_alter);
1932			}
1933		} else {
1934			list_add_tail(&queue.list, &curr->pending_const);
1935		}
1936	} else {
1937		if (!sma->complex_count)
1938			merge_queues(sma);
1939
1940		if (alter)
1941			list_add_tail(&queue.list, &sma->pending_alter);
1942		else
1943			list_add_tail(&queue.list, &sma->pending_const);
1944
1945		sma->complex_count++;
1946	}
1947
1948	do {
1949		queue.status = -EINTR;
1950		queue.sleeper = current;
1951
1952		__set_current_state(TASK_INTERRUPTIBLE);
1953		sem_unlock(sma, locknum);
1954		rcu_read_unlock();
1955
1956		if (timeout)
1957			jiffies_left = schedule_timeout(jiffies_left);
1958		else
1959			schedule();
1960
1961		/*
1962		 * fastpath: the semop has completed, either successfully or
1963		 * not, from the syscall pov, is quite irrelevant to us at this
1964		 * point; we're done.
1965		 *
1966		 * We _do_ care, nonetheless, about being awoken by a signal or
1967		 * spuriously.  The queue.status is checked again in the
1968		 * slowpath (aka after taking sem_lock), such that we can detect
1969		 * scenarios where we were awakened externally, during the
1970		 * window between wake_q_add() and wake_up_q().
1971		 */
1972		error = READ_ONCE(queue.status);
1973		if (error != -EINTR) {
1974			/*
1975			 * User space could assume that semop() is a memory
1976			 * barrier: Without the mb(), the cpu could
1977			 * speculatively read in userspace stale data that was
1978			 * overwritten by the previous owner of the semaphore.
1979			 */
1980			smp_mb();
1981			goto out_free;
1982		}
1983
1984		rcu_read_lock();
1985		locknum = sem_lock(sma, sops, nsops);
1986
1987		if (!ipc_valid_object(&sma->sem_perm))
1988			goto out_unlock_free;
1989
1990		error = READ_ONCE(queue.status);
1991
1992		/*
1993		 * If queue.status != -EINTR we are woken up by another process.
1994		 * Leave without unlink_queue(), but with sem_unlock().
1995		 */
1996		if (error != -EINTR)
1997			goto out_unlock_free;
1998
1999		/*
2000		 * If an interrupt occurred we have to clean up the queue.
2001		 */
2002		if (timeout && jiffies_left == 0)
2003			error = -EAGAIN;
2004	} while (error == -EINTR && !signal_pending(current)); /* spurious */
2005
2006	unlink_queue(sma, &queue);
2007
2008out_unlock_free:
2009	sem_unlock(sma, locknum);
2010	rcu_read_unlock();
2011out_free:
2012	if (sops != fast_sops)
2013		kfree(sops);
2014	return error;
2015}
2016
2017SYSCALL_DEFINE3(semop, int, semid, struct sembuf __user *, tsops,
2018		unsigned, nsops)
2019{
2020	return sys_semtimedop(semid, tsops, nsops, NULL);
2021}
2022
2023/* If CLONE_SYSVSEM is set, establish sharing of SEM_UNDO state between
2024 * parent and child tasks.
2025 */
2026
2027int copy_semundo(unsigned long clone_flags, struct task_struct *tsk)
2028{
2029	struct sem_undo_list *undo_list;
2030	int error;
2031
2032	if (clone_flags & CLONE_SYSVSEM) {
2033		error = get_undo_list(&undo_list);
2034		if (error)
2035			return error;
2036		atomic_inc(&undo_list->refcnt);
2037		tsk->sysvsem.undo_list = undo_list;
2038	} else
2039		tsk->sysvsem.undo_list = NULL;
2040
2041	return 0;
2042}
2043
2044/*
2045 * add semadj values to semaphores, free undo structures.
2046 * undo structures are not freed when semaphore arrays are destroyed
2047 * so some of them may be out of date.
2048 * IMPLEMENTATION NOTE: There is some confusion over whether the
2049 * set of adjustments that needs to be done should be done in an atomic
2050 * manner or not. That is, if we are attempting to decrement the semval
2051 * should we queue up and wait until we can do so legally?
2052 * The original implementation attempted to do this (queue and wait).
2053 * The current implementation does not do so. The POSIX standard
2054 * and SVID should be consulted to determine what behavior is mandated.
2055 */
2056void exit_sem(struct task_struct *tsk)
2057{
2058	struct sem_undo_list *ulp;
2059
2060	ulp = tsk->sysvsem.undo_list;
2061	if (!ulp)
2062		return;
2063	tsk->sysvsem.undo_list = NULL;
2064
2065	if (!atomic_dec_and_test(&ulp->refcnt))
2066		return;
2067
2068	for (;;) {
2069		struct sem_array *sma;
2070		struct sem_undo *un;
2071		int semid, i;
2072		DEFINE_WAKE_Q(wake_q);
2073
2074		cond_resched();
2075
2076		rcu_read_lock();
2077		un = list_entry_rcu(ulp->list_proc.next,
2078				    struct sem_undo, list_proc);
2079		if (&un->list_proc == &ulp->list_proc) {
2080			/*
2081			 * We must wait for freeary() before freeing this ulp,
2082			 * in case we raced with last sem_undo. There is a small
2083			 * possibility where we exit while freeary() didn't
2084			 * finish unlocking sem_undo_list.
2085			 */
2086			spin_unlock_wait(&ulp->lock);
2087			rcu_read_unlock();
2088			break;
2089		}
2090		spin_lock(&ulp->lock);
2091		semid = un->semid;
2092		spin_unlock(&ulp->lock);
2093
2094		/* exit_sem raced with IPC_RMID, nothing to do */
2095		if (semid == -1) {
2096			rcu_read_unlock();
2097			continue;
2098		}
2099
2100		sma = sem_obtain_object_check(tsk->nsproxy->ipc_ns, semid);
2101		/* exit_sem raced with IPC_RMID, nothing to do */
2102		if (IS_ERR(sma)) {
2103			rcu_read_unlock();
2104			continue;
2105		}
2106
2107		sem_lock(sma, NULL, -1);
2108		/* exit_sem raced with IPC_RMID, nothing to do */
2109		if (!ipc_valid_object(&sma->sem_perm)) {
2110			sem_unlock(sma, -1);
2111			rcu_read_unlock();
2112			continue;
2113		}
2114		un = __lookup_undo(ulp, semid);
2115		if (un == NULL) {
2116			/* exit_sem raced with IPC_RMID+semget() that created
2117			 * exactly the same semid. Nothing to do.
2118			 */
2119			sem_unlock(sma, -1);
2120			rcu_read_unlock();
2121			continue;
2122		}
2123
2124		/* remove un from the linked lists */
2125		ipc_assert_locked_object(&sma->sem_perm);
2126		list_del(&un->list_id);
2127
2128		/* we are the last process using this ulp, acquiring ulp->lock
2129		 * isn't required. Besides that, we are also protected against
2130		 * IPC_RMID as we hold sma->sem_perm lock now
2131		 */
2132		list_del_rcu(&un->list_proc);
2133
2134		/* perform adjustments registered in un */
2135		for (i = 0; i < sma->sem_nsems; i++) {
2136			struct sem *semaphore = &sma->sems[i];
2137			if (un->semadj[i]) {
2138				semaphore->semval += un->semadj[i];
2139				/*
2140				 * Range checks of the new semaphore value,
2141				 * not defined by sus:
2142				 * - Some unices ignore the undo entirely
2143				 *   (e.g. HP UX 11i 11.22, Tru64 V5.1)
2144				 * - some cap the value (e.g. FreeBSD caps
2145				 *   at 0, but doesn't enforce SEMVMX)
2146				 *
2147				 * Linux caps the semaphore value, both at 0
2148				 * and at SEMVMX.
2149				 *
2150				 *	Manfred <manfred@colorfullife.com>
2151				 */
2152				if (semaphore->semval < 0)
2153					semaphore->semval = 0;
2154				if (semaphore->semval > SEMVMX)
2155					semaphore->semval = SEMVMX;
2156				semaphore->sempid = task_tgid_vnr(current);
2157			}
2158		}
2159		/* maybe some queued-up processes were waiting for this */
2160		do_smart_update(sma, NULL, 0, 1, &wake_q);
2161		sem_unlock(sma, -1);
2162		rcu_read_unlock();
2163		wake_up_q(&wake_q);
2164
2165		kfree_rcu(un, rcu);
2166	}
2167	kfree(ulp);
2168}
2169
2170#ifdef CONFIG_PROC_FS
2171static int sysvipc_sem_proc_show(struct seq_file *s, void *it)
2172{
2173	struct user_namespace *user_ns = seq_user_ns(s);
2174	struct sem_array *sma = it;
2175	time_t sem_otime;
2176
2177	/*
2178	 * The proc interface isn't aware of sem_lock(), it calls
2179	 * ipc_lock_object() directly (in sysvipc_find_ipc).
2180	 * In order to stay compatible with sem_lock(), we must
2181	 * enter / leave complex_mode.
2182	 */
2183	complexmode_enter(sma);
2184
2185	sem_otime = get_semotime(sma);
2186
2187	seq_printf(s,
2188		   "%10d %10d  %4o %10u %5u %5u %5u %5u %10lu %10lu\n",
2189		   sma->sem_perm.key,
2190		   sma->sem_perm.id,
2191		   sma->sem_perm.mode,
2192		   sma->sem_nsems,
2193		   from_kuid_munged(user_ns, sma->sem_perm.uid),
2194		   from_kgid_munged(user_ns, sma->sem_perm.gid),
2195		   from_kuid_munged(user_ns, sma->sem_perm.cuid),
2196		   from_kgid_munged(user_ns, sma->sem_perm.cgid),
2197		   sem_otime,
2198		   sma->sem_ctime);
2199
2200	complexmode_tryleave(sma);
2201
2202	return 0;
2203}
2204#endif
2205