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