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