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