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