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