]> git.karo-electronics.de Git - linux-beck.git/blob - ipc/sem.c
ipc/sem.c: remove code duplication
[linux-beck.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  * @sops: array with operations that should be checked
589  * @nsops: number of operations
590  * @un: undo array
591  * @pid: pid that did the change
592  *
593  * Returns 0 if the operation was possible.
594  * Returns 1 if the operation is impossible, the caller must sleep.
595  * Negative values are error codes.
596  */
597 static int perform_atomic_semop(struct sem_array *sma, struct sembuf *sops,
598                              int nsops, struct sem_undo *un, int pid)
599 {
600         int result, sem_op;
601         struct sembuf *sop;
602         struct sem *curr;
603
604         for (sop = sops; sop < sops + nsops; sop++) {
605                 curr = sma->sem_base + sop->sem_num;
606                 sem_op = sop->sem_op;
607                 result = curr->semval;
608
609                 if (!sem_op && result)
610                         goto would_block;
611
612                 result += sem_op;
613                 if (result < 0)
614                         goto would_block;
615                 if (result > SEMVMX)
616                         goto out_of_range;
617
618                 if (sop->sem_flg & SEM_UNDO) {
619                         int undo = un->semadj[sop->sem_num] - sem_op;
620                         /* Exceeding the undo range is an error. */
621                         if (undo < (-SEMAEM - 1) || undo > SEMAEM)
622                                 goto out_of_range;
623                         un->semadj[sop->sem_num] = undo;
624                 }
625
626                 curr->semval = result;
627         }
628
629         sop--;
630         while (sop >= sops) {
631                 sma->sem_base[sop->sem_num].sempid = pid;
632                 sop--;
633         }
634
635         return 0;
636
637 out_of_range:
638         result = -ERANGE;
639         goto undo;
640
641 would_block:
642         if (sop->sem_flg & IPC_NOWAIT)
643                 result = -EAGAIN;
644         else
645                 result = 1;
646
647 undo:
648         sop--;
649         while (sop >= sops) {
650                 sem_op = sop->sem_op;
651                 sma->sem_base[sop->sem_num].semval -= sem_op;
652                 if (sop->sem_flg & SEM_UNDO)
653                         un->semadj[sop->sem_num] += sem_op;
654                 sop--;
655         }
656
657         return result;
658 }
659
660 /** wake_up_sem_queue_prepare(q, error): Prepare wake-up
661  * @q: queue entry that must be signaled
662  * @error: Error value for the signal
663  *
664  * Prepare the wake-up of the queue entry q.
665  */
666 static void wake_up_sem_queue_prepare(struct list_head *pt,
667                                 struct sem_queue *q, int error)
668 {
669         if (list_empty(pt)) {
670                 /*
671                  * Hold preempt off so that we don't get preempted and have the
672                  * wakee busy-wait until we're scheduled back on.
673                  */
674                 preempt_disable();
675         }
676         q->status = IN_WAKEUP;
677         q->pid = error;
678
679         list_add_tail(&q->list, pt);
680 }
681
682 /**
683  * wake_up_sem_queue_do - do the actual wake-up
684  * @pt: list of tasks to be woken up
685  *
686  * Do the actual wake-up.
687  * The function is called without any locks held, thus the semaphore array
688  * could be destroyed already and the tasks can disappear as soon as the
689  * status is set to the actual return code.
690  */
691 static void wake_up_sem_queue_do(struct list_head *pt)
692 {
693         struct sem_queue *q, *t;
694         int did_something;
695
696         did_something = !list_empty(pt);
697         list_for_each_entry_safe(q, t, pt, list) {
698                 wake_up_process(q->sleeper);
699                 /* q can disappear immediately after writing q->status. */
700                 smp_wmb();
701                 q->status = q->pid;
702         }
703         if (did_something)
704                 preempt_enable();
705 }
706
707 static void unlink_queue(struct sem_array *sma, struct sem_queue *q)
708 {
709         list_del(&q->list);
710         if (q->nsops > 1)
711                 sma->complex_count--;
712 }
713
714 /** check_restart(sma, q)
715  * @sma: semaphore array
716  * @q: the operation that just completed
717  *
718  * update_queue is O(N^2) when it restarts scanning the whole queue of
719  * waiting operations. Therefore this function checks if the restart is
720  * really necessary. It is called after a previously waiting operation
721  * modified the array.
722  * Note that wait-for-zero operations are handled without restart.
723  */
724 static int check_restart(struct sem_array *sma, struct sem_queue *q)
725 {
726         /* pending complex alter operations are too difficult to analyse */
727         if (!list_empty(&sma->pending_alter))
728                 return 1;
729
730         /* we were a sleeping complex operation. Too difficult */
731         if (q->nsops > 1)
732                 return 1;
733
734         /* It is impossible that someone waits for the new value:
735          * - complex operations always restart.
736          * - wait-for-zero are handled seperately.
737          * - q is a previously sleeping simple operation that
738          *   altered the array. It must be a decrement, because
739          *   simple increments never sleep.
740          * - If there are older (higher priority) decrements
741          *   in the queue, then they have observed the original
742          *   semval value and couldn't proceed. The operation
743          *   decremented to value - thus they won't proceed either.
744          */
745         return 0;
746 }
747
748 /**
749  * wake_const_ops - wake up non-alter tasks
750  * @sma: semaphore array.
751  * @semnum: semaphore that was modified.
752  * @pt: list head for the tasks that must be woken up.
753  *
754  * wake_const_ops must be called after a semaphore in a semaphore array
755  * was set to 0. If complex const operations are pending, wake_const_ops must
756  * be called with semnum = -1, as well as with the number of each modified
757  * semaphore.
758  * The tasks that must be woken up are added to @pt. The return code
759  * is stored in q->pid.
760  * The function returns 1 if at least one operation was completed successfully.
761  */
762 static int wake_const_ops(struct sem_array *sma, int semnum,
763                                 struct list_head *pt)
764 {
765         struct sem_queue *q;
766         struct list_head *walk;
767         struct list_head *pending_list;
768         int semop_completed = 0;
769
770         if (semnum == -1)
771                 pending_list = &sma->pending_const;
772         else
773                 pending_list = &sma->sem_base[semnum].pending_const;
774
775         walk = pending_list->next;
776         while (walk != pending_list) {
777                 int error;
778
779                 q = container_of(walk, struct sem_queue, list);
780                 walk = walk->next;
781
782                 error = perform_atomic_semop(sma, q->sops, q->nsops,
783                                                  q->undo, q->pid);
784
785                 if (error <= 0) {
786                         /* operation completed, remove from queue & wakeup */
787
788                         unlink_queue(sma, q);
789
790                         wake_up_sem_queue_prepare(pt, q, error);
791                         if (error == 0)
792                                 semop_completed = 1;
793                 }
794         }
795         return semop_completed;
796 }
797
798 /**
799  * do_smart_wakeup_zero - wakeup all wait for zero tasks
800  * @sma: semaphore array
801  * @sops: operations that were performed
802  * @nsops: number of operations
803  * @pt: list head of the tasks that must be woken up.
804  *
805  * Checks all required queue for wait-for-zero operations, based
806  * on the actual changes that were performed on the semaphore array.
807  * The function returns 1 if at least one operation was completed successfully.
808  */
809 static int do_smart_wakeup_zero(struct sem_array *sma, struct sembuf *sops,
810                                         int nsops, struct list_head *pt)
811 {
812         int i;
813         int semop_completed = 0;
814         int got_zero = 0;
815
816         /* first: the per-semaphore queues, if known */
817         if (sops) {
818                 for (i = 0; i < nsops; i++) {
819                         int num = sops[i].sem_num;
820
821                         if (sma->sem_base[num].semval == 0) {
822                                 got_zero = 1;
823                                 semop_completed |= wake_const_ops(sma, num, pt);
824                         }
825                 }
826         } else {
827                 /*
828                  * No sops means modified semaphores not known.
829                  * Assume all were changed.
830                  */
831                 for (i = 0; i < sma->sem_nsems; i++) {
832                         if (sma->sem_base[i].semval == 0) {
833                                 got_zero = 1;
834                                 semop_completed |= wake_const_ops(sma, i, pt);
835                         }
836                 }
837         }
838         /*
839          * If one of the modified semaphores got 0,
840          * then check the global queue, too.
841          */
842         if (got_zero)
843                 semop_completed |= wake_const_ops(sma, -1, pt);
844
845         return semop_completed;
846 }
847
848
849 /**
850  * update_queue - look for tasks that can be completed.
851  * @sma: semaphore array.
852  * @semnum: semaphore that was modified.
853  * @pt: list head for the tasks that must be woken up.
854  *
855  * update_queue must be called after a semaphore in a semaphore array
856  * was modified. If multiple semaphores were modified, update_queue must
857  * be called with semnum = -1, as well as with the number of each modified
858  * semaphore.
859  * The tasks that must be woken up are added to @pt. The return code
860  * is stored in q->pid.
861  * The function internally checks if const operations can now succeed.
862  *
863  * The function return 1 if at least one semop was completed successfully.
864  */
865 static int update_queue(struct sem_array *sma, int semnum, struct list_head *pt)
866 {
867         struct sem_queue *q;
868         struct list_head *walk;
869         struct list_head *pending_list;
870         int semop_completed = 0;
871
872         if (semnum == -1)
873                 pending_list = &sma->pending_alter;
874         else
875                 pending_list = &sma->sem_base[semnum].pending_alter;
876
877 again:
878         walk = pending_list->next;
879         while (walk != pending_list) {
880                 int error, restart;
881
882                 q = container_of(walk, struct sem_queue, list);
883                 walk = walk->next;
884
885                 /* If we are scanning the single sop, per-semaphore list of
886                  * one semaphore and that semaphore is 0, then it is not
887                  * necessary to scan further: simple increments
888                  * that affect only one entry succeed immediately and cannot
889                  * be in the  per semaphore pending queue, and decrements
890                  * cannot be successful if the value is already 0.
891                  */
892                 if (semnum != -1 && sma->sem_base[semnum].semval == 0)
893                         break;
894
895                 error = perform_atomic_semop(sma, q->sops, q->nsops,
896                                          q->undo, q->pid);
897
898                 /* Does q->sleeper still need to sleep? */
899                 if (error > 0)
900                         continue;
901
902                 unlink_queue(sma, q);
903
904                 if (error) {
905                         restart = 0;
906                 } else {
907                         semop_completed = 1;
908                         do_smart_wakeup_zero(sma, q->sops, q->nsops, pt);
909                         restart = check_restart(sma, q);
910                 }
911
912                 wake_up_sem_queue_prepare(pt, q, error);
913                 if (restart)
914                         goto again;
915         }
916         return semop_completed;
917 }
918
919 /**
920  * set_semotime - set sem_otime
921  * @sma: semaphore array
922  * @sops: operations that modified the array, may be NULL
923  *
924  * sem_otime is replicated to avoid cache line trashing.
925  * This function sets one instance to the current time.
926  */
927 static void set_semotime(struct sem_array *sma, struct sembuf *sops)
928 {
929         if (sops == NULL) {
930                 sma->sem_base[0].sem_otime = get_seconds();
931         } else {
932                 sma->sem_base[sops[0].sem_num].sem_otime =
933                                                         get_seconds();
934         }
935 }
936
937 /**
938  * do_smart_update - optimized update_queue
939  * @sma: semaphore array
940  * @sops: operations that were performed
941  * @nsops: number of operations
942  * @otime: force setting otime
943  * @pt: list head of the tasks that must be woken up.
944  *
945  * do_smart_update() does the required calls to update_queue and wakeup_zero,
946  * based on the actual changes that were performed on the semaphore array.
947  * Note that the function does not do the actual wake-up: the caller is
948  * responsible for calling wake_up_sem_queue_do(@pt).
949  * It is safe to perform this call after dropping all locks.
950  */
951 static void do_smart_update(struct sem_array *sma, struct sembuf *sops, int nsops,
952                         int otime, struct list_head *pt)
953 {
954         int i;
955
956         otime |= do_smart_wakeup_zero(sma, sops, nsops, pt);
957
958         if (!list_empty(&sma->pending_alter)) {
959                 /* semaphore array uses the global queue - just process it. */
960                 otime |= update_queue(sma, -1, pt);
961         } else {
962                 if (!sops) {
963                         /*
964                          * No sops, thus the modified semaphores are not
965                          * known. Check all.
966                          */
967                         for (i = 0; i < sma->sem_nsems; i++)
968                                 otime |= update_queue(sma, i, pt);
969                 } else {
970                         /*
971                          * Check the semaphores that were increased:
972                          * - No complex ops, thus all sleeping ops are
973                          *   decrease.
974                          * - if we decreased the value, then any sleeping
975                          *   semaphore ops wont be able to run: If the
976                          *   previous value was too small, then the new
977                          *   value will be too small, too.
978                          */
979                         for (i = 0; i < nsops; i++) {
980                                 if (sops[i].sem_op > 0) {
981                                         otime |= update_queue(sma,
982                                                         sops[i].sem_num, pt);
983                                 }
984                         }
985                 }
986         }
987         if (otime)
988                 set_semotime(sma, sops);
989 }
990
991 /*
992  * check_qop: Test how often a queued operation sleeps on the semaphore semnum
993  */
994 static int check_qop(struct sem_array *sma, int semnum, struct sem_queue *q,
995                         bool count_zero)
996 {
997         struct sembuf *sops = q->sops;
998         int nsops = q->nsops;
999         int i, semcnt;
1000
1001         semcnt = 0;
1002
1003         for (i = 0; i < nsops; i++) {
1004                 if (sops[i].sem_num != semnum)
1005                         continue;
1006                 if (sops[i].sem_flg & IPC_NOWAIT)
1007                         continue;
1008                 if (count_zero && sops[i].sem_op == 0)
1009                         semcnt++;
1010                 if (!count_zero && sops[i].sem_op < 0)
1011                         semcnt++;
1012         }
1013         return semcnt;
1014 }
1015
1016 /* The following counts are associated to each semaphore:
1017  *   semncnt        number of tasks waiting on semval being nonzero
1018  *   semzcnt        number of tasks waiting on semval being zero
1019  * This model assumes that a task waits on exactly one semaphore.
1020  * Since semaphore operations are to be performed atomically, tasks actually
1021  * wait on a whole sequence of semaphores simultaneously.
1022  * The counts we return here are a rough approximation, but still
1023  * warrant that semncnt+semzcnt>0 if the task is on the pending queue.
1024  */
1025 static int count_semcnt(struct sem_array *sma, ushort semnum,
1026                         bool count_zero)
1027 {
1028         struct list_head *l;
1029         struct sem_queue *q;
1030         int semcnt;
1031
1032         semcnt = 0;
1033         /* First: check the simple operations. They are easy to evaluate */
1034         if (count_zero)
1035                 l = &sma->sem_base[semnum].pending_const;
1036         else
1037                 l = &sma->sem_base[semnum].pending_alter;
1038
1039         list_for_each_entry(q, l, list) {
1040                 /* all task on a per-semaphore list sleep on exactly
1041                  * that semaphore
1042                  */
1043                 semcnt++;
1044         }
1045
1046         /* Then: check the complex operations. */
1047         list_for_each_entry(q, &sma->pending_alter, list) {
1048                 semcnt += check_qop(sma, semnum, q, count_zero);
1049         }
1050         if (count_zero) {
1051                 list_for_each_entry(q, &sma->pending_const, list) {
1052                         semcnt += check_qop(sma, semnum, q, count_zero);
1053                 }
1054         }
1055         return semcnt;
1056 }
1057
1058 /* Free a semaphore set. freeary() is called with sem_ids.rwsem locked
1059  * as a writer and the spinlock for this semaphore set hold. sem_ids.rwsem
1060  * remains locked on exit.
1061  */
1062 static void freeary(struct ipc_namespace *ns, struct kern_ipc_perm *ipcp)
1063 {
1064         struct sem_undo *un, *tu;
1065         struct sem_queue *q, *tq;
1066         struct sem_array *sma = container_of(ipcp, struct sem_array, sem_perm);
1067         struct list_head tasks;
1068         int i;
1069
1070         /* Free the existing undo structures for this semaphore set.  */
1071         ipc_assert_locked_object(&sma->sem_perm);
1072         list_for_each_entry_safe(un, tu, &sma->list_id, list_id) {
1073                 list_del(&un->list_id);
1074                 spin_lock(&un->ulp->lock);
1075                 un->semid = -1;
1076                 list_del_rcu(&un->list_proc);
1077                 spin_unlock(&un->ulp->lock);
1078                 kfree_rcu(un, rcu);
1079         }
1080
1081         /* Wake up all pending processes and let them fail with EIDRM. */
1082         INIT_LIST_HEAD(&tasks);
1083         list_for_each_entry_safe(q, tq, &sma->pending_const, list) {
1084                 unlink_queue(sma, q);
1085                 wake_up_sem_queue_prepare(&tasks, q, -EIDRM);
1086         }
1087
1088         list_for_each_entry_safe(q, tq, &sma->pending_alter, list) {
1089                 unlink_queue(sma, q);
1090                 wake_up_sem_queue_prepare(&tasks, q, -EIDRM);
1091         }
1092         for (i = 0; i < sma->sem_nsems; i++) {
1093                 struct sem *sem = sma->sem_base + i;
1094                 list_for_each_entry_safe(q, tq, &sem->pending_const, list) {
1095                         unlink_queue(sma, q);
1096                         wake_up_sem_queue_prepare(&tasks, q, -EIDRM);
1097                 }
1098                 list_for_each_entry_safe(q, tq, &sem->pending_alter, list) {
1099                         unlink_queue(sma, q);
1100                         wake_up_sem_queue_prepare(&tasks, q, -EIDRM);
1101                 }
1102         }
1103
1104         /* Remove the semaphore set from the IDR */
1105         sem_rmid(ns, sma);
1106         sem_unlock(sma, -1);
1107         rcu_read_unlock();
1108
1109         wake_up_sem_queue_do(&tasks);
1110         ns->used_sems -= sma->sem_nsems;
1111         ipc_rcu_putref(sma, sem_rcu_free);
1112 }
1113
1114 static unsigned long copy_semid_to_user(void __user *buf, struct semid64_ds *in, int version)
1115 {
1116         switch (version) {
1117         case IPC_64:
1118                 return copy_to_user(buf, in, sizeof(*in));
1119         case IPC_OLD:
1120             {
1121                 struct semid_ds out;
1122
1123                 memset(&out, 0, sizeof(out));
1124
1125                 ipc64_perm_to_ipc_perm(&in->sem_perm, &out.sem_perm);
1126
1127                 out.sem_otime   = in->sem_otime;
1128                 out.sem_ctime   = in->sem_ctime;
1129                 out.sem_nsems   = in->sem_nsems;
1130
1131                 return copy_to_user(buf, &out, sizeof(out));
1132             }
1133         default:
1134                 return -EINVAL;
1135         }
1136 }
1137
1138 static time_t get_semotime(struct sem_array *sma)
1139 {
1140         int i;
1141         time_t res;
1142
1143         res = sma->sem_base[0].sem_otime;
1144         for (i = 1; i < sma->sem_nsems; i++) {
1145                 time_t to = sma->sem_base[i].sem_otime;
1146
1147                 if (to > res)
1148                         res = to;
1149         }
1150         return res;
1151 }
1152
1153 static int semctl_nolock(struct ipc_namespace *ns, int semid,
1154                          int cmd, int version, void __user *p)
1155 {
1156         int err;
1157         struct sem_array *sma;
1158
1159         switch (cmd) {
1160         case IPC_INFO:
1161         case SEM_INFO:
1162         {
1163                 struct seminfo seminfo;
1164                 int max_id;
1165
1166                 err = security_sem_semctl(NULL, cmd);
1167                 if (err)
1168                         return err;
1169
1170                 memset(&seminfo, 0, sizeof(seminfo));
1171                 seminfo.semmni = ns->sc_semmni;
1172                 seminfo.semmns = ns->sc_semmns;
1173                 seminfo.semmsl = ns->sc_semmsl;
1174                 seminfo.semopm = ns->sc_semopm;
1175                 seminfo.semvmx = SEMVMX;
1176                 seminfo.semmnu = SEMMNU;
1177                 seminfo.semmap = SEMMAP;
1178                 seminfo.semume = SEMUME;
1179                 down_read(&sem_ids(ns).rwsem);
1180                 if (cmd == SEM_INFO) {
1181                         seminfo.semusz = sem_ids(ns).in_use;
1182                         seminfo.semaem = ns->used_sems;
1183                 } else {
1184                         seminfo.semusz = SEMUSZ;
1185                         seminfo.semaem = SEMAEM;
1186                 }
1187                 max_id = ipc_get_maxid(&sem_ids(ns));
1188                 up_read(&sem_ids(ns).rwsem);
1189                 if (copy_to_user(p, &seminfo, sizeof(struct seminfo)))
1190                         return -EFAULT;
1191                 return (max_id < 0) ? 0 : max_id;
1192         }
1193         case IPC_STAT:
1194         case SEM_STAT:
1195         {
1196                 struct semid64_ds tbuf;
1197                 int id = 0;
1198
1199                 memset(&tbuf, 0, sizeof(tbuf));
1200
1201                 rcu_read_lock();
1202                 if (cmd == SEM_STAT) {
1203                         sma = sem_obtain_object(ns, semid);
1204                         if (IS_ERR(sma)) {
1205                                 err = PTR_ERR(sma);
1206                                 goto out_unlock;
1207                         }
1208                         id = sma->sem_perm.id;
1209                 } else {
1210                         sma = sem_obtain_object_check(ns, semid);
1211                         if (IS_ERR(sma)) {
1212                                 err = PTR_ERR(sma);
1213                                 goto out_unlock;
1214                         }
1215                 }
1216
1217                 err = -EACCES;
1218                 if (ipcperms(ns, &sma->sem_perm, S_IRUGO))
1219                         goto out_unlock;
1220
1221                 err = security_sem_semctl(sma, cmd);
1222                 if (err)
1223                         goto out_unlock;
1224
1225                 kernel_to_ipc64_perm(&sma->sem_perm, &tbuf.sem_perm);
1226                 tbuf.sem_otime = get_semotime(sma);
1227                 tbuf.sem_ctime = sma->sem_ctime;
1228                 tbuf.sem_nsems = sma->sem_nsems;
1229                 rcu_read_unlock();
1230                 if (copy_semid_to_user(p, &tbuf, version))
1231                         return -EFAULT;
1232                 return id;
1233         }
1234         default:
1235                 return -EINVAL;
1236         }
1237 out_unlock:
1238         rcu_read_unlock();
1239         return err;
1240 }
1241
1242 static int semctl_setval(struct ipc_namespace *ns, int semid, int semnum,
1243                 unsigned long arg)
1244 {
1245         struct sem_undo *un;
1246         struct sem_array *sma;
1247         struct sem *curr;
1248         int err;
1249         struct list_head tasks;
1250         int val;
1251 #if defined(CONFIG_64BIT) && defined(__BIG_ENDIAN)
1252         /* big-endian 64bit */
1253         val = arg >> 32;
1254 #else
1255         /* 32bit or little-endian 64bit */
1256         val = arg;
1257 #endif
1258
1259         if (val > SEMVMX || val < 0)
1260                 return -ERANGE;
1261
1262         INIT_LIST_HEAD(&tasks);
1263
1264         rcu_read_lock();
1265         sma = sem_obtain_object_check(ns, semid);
1266         if (IS_ERR(sma)) {
1267                 rcu_read_unlock();
1268                 return PTR_ERR(sma);
1269         }
1270
1271         if (semnum < 0 || semnum >= sma->sem_nsems) {
1272                 rcu_read_unlock();
1273                 return -EINVAL;
1274         }
1275
1276
1277         if (ipcperms(ns, &sma->sem_perm, S_IWUGO)) {
1278                 rcu_read_unlock();
1279                 return -EACCES;
1280         }
1281
1282         err = security_sem_semctl(sma, SETVAL);
1283         if (err) {
1284                 rcu_read_unlock();
1285                 return -EACCES;
1286         }
1287
1288         sem_lock(sma, NULL, -1);
1289
1290         if (!ipc_valid_object(&sma->sem_perm)) {
1291                 sem_unlock(sma, -1);
1292                 rcu_read_unlock();
1293                 return -EIDRM;
1294         }
1295
1296         curr = &sma->sem_base[semnum];
1297
1298         ipc_assert_locked_object(&sma->sem_perm);
1299         list_for_each_entry(un, &sma->list_id, list_id)
1300                 un->semadj[semnum] = 0;
1301
1302         curr->semval = val;
1303         curr->sempid = task_tgid_vnr(current);
1304         sma->sem_ctime = get_seconds();
1305         /* maybe some queued-up processes were waiting for this */
1306         do_smart_update(sma, NULL, 0, 0, &tasks);
1307         sem_unlock(sma, -1);
1308         rcu_read_unlock();
1309         wake_up_sem_queue_do(&tasks);
1310         return 0;
1311 }
1312
1313 static int semctl_main(struct ipc_namespace *ns, int semid, int semnum,
1314                 int cmd, void __user *p)
1315 {
1316         struct sem_array *sma;
1317         struct sem *curr;
1318         int err, nsems;
1319         ushort fast_sem_io[SEMMSL_FAST];
1320         ushort *sem_io = fast_sem_io;
1321         struct list_head tasks;
1322
1323         INIT_LIST_HEAD(&tasks);
1324
1325         rcu_read_lock();
1326         sma = sem_obtain_object_check(ns, semid);
1327         if (IS_ERR(sma)) {
1328                 rcu_read_unlock();
1329                 return PTR_ERR(sma);
1330         }
1331
1332         nsems = sma->sem_nsems;
1333
1334         err = -EACCES;
1335         if (ipcperms(ns, &sma->sem_perm, cmd == SETALL ? S_IWUGO : S_IRUGO))
1336                 goto out_rcu_wakeup;
1337
1338         err = security_sem_semctl(sma, cmd);
1339         if (err)
1340                 goto out_rcu_wakeup;
1341
1342         err = -EACCES;
1343         switch (cmd) {
1344         case GETALL:
1345         {
1346                 ushort __user *array = p;
1347                 int i;
1348
1349                 sem_lock(sma, NULL, -1);
1350                 if (!ipc_valid_object(&sma->sem_perm)) {
1351                         err = -EIDRM;
1352                         goto out_unlock;
1353                 }
1354                 if (nsems > SEMMSL_FAST) {
1355                         if (!ipc_rcu_getref(sma)) {
1356                                 err = -EIDRM;
1357                                 goto out_unlock;
1358                         }
1359                         sem_unlock(sma, -1);
1360                         rcu_read_unlock();
1361                         sem_io = ipc_alloc(sizeof(ushort)*nsems);
1362                         if (sem_io == NULL) {
1363                                 ipc_rcu_putref(sma, ipc_rcu_free);
1364                                 return -ENOMEM;
1365                         }
1366
1367                         rcu_read_lock();
1368                         sem_lock_and_putref(sma);
1369                         if (!ipc_valid_object(&sma->sem_perm)) {
1370                                 err = -EIDRM;
1371                                 goto out_unlock;
1372                         }
1373                 }
1374                 for (i = 0; i < sma->sem_nsems; i++)
1375                         sem_io[i] = sma->sem_base[i].semval;
1376                 sem_unlock(sma, -1);
1377                 rcu_read_unlock();
1378                 err = 0;
1379                 if (copy_to_user(array, sem_io, nsems*sizeof(ushort)))
1380                         err = -EFAULT;
1381                 goto out_free;
1382         }
1383         case SETALL:
1384         {
1385                 int i;
1386                 struct sem_undo *un;
1387
1388                 if (!ipc_rcu_getref(sma)) {
1389                         err = -EIDRM;
1390                         goto out_rcu_wakeup;
1391                 }
1392                 rcu_read_unlock();
1393
1394                 if (nsems > SEMMSL_FAST) {
1395                         sem_io = ipc_alloc(sizeof(ushort)*nsems);
1396                         if (sem_io == NULL) {
1397                                 ipc_rcu_putref(sma, ipc_rcu_free);
1398                                 return -ENOMEM;
1399                         }
1400                 }
1401
1402                 if (copy_from_user(sem_io, p, nsems*sizeof(ushort))) {
1403                         ipc_rcu_putref(sma, ipc_rcu_free);
1404                         err = -EFAULT;
1405                         goto out_free;
1406                 }
1407
1408                 for (i = 0; i < nsems; i++) {
1409                         if (sem_io[i] > SEMVMX) {
1410                                 ipc_rcu_putref(sma, ipc_rcu_free);
1411                                 err = -ERANGE;
1412                                 goto out_free;
1413                         }
1414                 }
1415                 rcu_read_lock();
1416                 sem_lock_and_putref(sma);
1417                 if (!ipc_valid_object(&sma->sem_perm)) {
1418                         err = -EIDRM;
1419                         goto out_unlock;
1420                 }
1421
1422                 for (i = 0; i < nsems; i++)
1423                         sma->sem_base[i].semval = sem_io[i];
1424
1425                 ipc_assert_locked_object(&sma->sem_perm);
1426                 list_for_each_entry(un, &sma->list_id, list_id) {
1427                         for (i = 0; i < nsems; i++)
1428                                 un->semadj[i] = 0;
1429                 }
1430                 sma->sem_ctime = get_seconds();
1431                 /* maybe some queued-up processes were waiting for this */
1432                 do_smart_update(sma, NULL, 0, 0, &tasks);
1433                 err = 0;
1434                 goto out_unlock;
1435         }
1436         /* GETVAL, GETPID, GETNCTN, GETZCNT: fall-through */
1437         }
1438         err = -EINVAL;
1439         if (semnum < 0 || semnum >= nsems)
1440                 goto out_rcu_wakeup;
1441
1442         sem_lock(sma, NULL, -1);
1443         if (!ipc_valid_object(&sma->sem_perm)) {
1444                 err = -EIDRM;
1445                 goto out_unlock;
1446         }
1447         curr = &sma->sem_base[semnum];
1448
1449         switch (cmd) {
1450         case GETVAL:
1451                 err = curr->semval;
1452                 goto out_unlock;
1453         case GETPID:
1454                 err = curr->sempid;
1455                 goto out_unlock;
1456         case GETNCNT:
1457                 err = count_semcnt(sma, semnum, 0);
1458                 goto out_unlock;
1459         case GETZCNT:
1460                 err = count_semcnt(sma, semnum, 1);
1461                 goto out_unlock;
1462         }
1463
1464 out_unlock:
1465         sem_unlock(sma, -1);
1466 out_rcu_wakeup:
1467         rcu_read_unlock();
1468         wake_up_sem_queue_do(&tasks);
1469 out_free:
1470         if (sem_io != fast_sem_io)
1471                 ipc_free(sem_io, sizeof(ushort)*nsems);
1472         return err;
1473 }
1474
1475 static inline unsigned long
1476 copy_semid_from_user(struct semid64_ds *out, void __user *buf, int version)
1477 {
1478         switch (version) {
1479         case IPC_64:
1480                 if (copy_from_user(out, buf, sizeof(*out)))
1481                         return -EFAULT;
1482                 return 0;
1483         case IPC_OLD:
1484             {
1485                 struct semid_ds tbuf_old;
1486
1487                 if (copy_from_user(&tbuf_old, buf, sizeof(tbuf_old)))
1488                         return -EFAULT;
1489
1490                 out->sem_perm.uid       = tbuf_old.sem_perm.uid;
1491                 out->sem_perm.gid       = tbuf_old.sem_perm.gid;
1492                 out->sem_perm.mode      = tbuf_old.sem_perm.mode;
1493
1494                 return 0;
1495             }
1496         default:
1497                 return -EINVAL;
1498         }
1499 }
1500
1501 /*
1502  * This function handles some semctl commands which require the rwsem
1503  * to be held in write mode.
1504  * NOTE: no locks must be held, the rwsem is taken inside this function.
1505  */
1506 static int semctl_down(struct ipc_namespace *ns, int semid,
1507                        int cmd, int version, void __user *p)
1508 {
1509         struct sem_array *sma;
1510         int err;
1511         struct semid64_ds semid64;
1512         struct kern_ipc_perm *ipcp;
1513
1514         if (cmd == IPC_SET) {
1515                 if (copy_semid_from_user(&semid64, p, version))
1516                         return -EFAULT;
1517         }
1518
1519         down_write(&sem_ids(ns).rwsem);
1520         rcu_read_lock();
1521
1522         ipcp = ipcctl_pre_down_nolock(ns, &sem_ids(ns), semid, cmd,
1523                                       &semid64.sem_perm, 0);
1524         if (IS_ERR(ipcp)) {
1525                 err = PTR_ERR(ipcp);
1526                 goto out_unlock1;
1527         }
1528
1529         sma = container_of(ipcp, struct sem_array, sem_perm);
1530
1531         err = security_sem_semctl(sma, cmd);
1532         if (err)
1533                 goto out_unlock1;
1534
1535         switch (cmd) {
1536         case IPC_RMID:
1537                 sem_lock(sma, NULL, -1);
1538                 /* freeary unlocks the ipc object and rcu */
1539                 freeary(ns, ipcp);
1540                 goto out_up;
1541         case IPC_SET:
1542                 sem_lock(sma, NULL, -1);
1543                 err = ipc_update_perm(&semid64.sem_perm, ipcp);
1544                 if (err)
1545                         goto out_unlock0;
1546                 sma->sem_ctime = get_seconds();
1547                 break;
1548         default:
1549                 err = -EINVAL;
1550                 goto out_unlock1;
1551         }
1552
1553 out_unlock0:
1554         sem_unlock(sma, -1);
1555 out_unlock1:
1556         rcu_read_unlock();
1557 out_up:
1558         up_write(&sem_ids(ns).rwsem);
1559         return err;
1560 }
1561
1562 SYSCALL_DEFINE4(semctl, int, semid, int, semnum, int, cmd, unsigned long, arg)
1563 {
1564         int version;
1565         struct ipc_namespace *ns;
1566         void __user *p = (void __user *)arg;
1567
1568         if (semid < 0)
1569                 return -EINVAL;
1570
1571         version = ipc_parse_version(&cmd);
1572         ns = current->nsproxy->ipc_ns;
1573
1574         switch (cmd) {
1575         case IPC_INFO:
1576         case SEM_INFO:
1577         case IPC_STAT:
1578         case SEM_STAT:
1579                 return semctl_nolock(ns, semid, cmd, version, p);
1580         case GETALL:
1581         case GETVAL:
1582         case GETPID:
1583         case GETNCNT:
1584         case GETZCNT:
1585         case SETALL:
1586                 return semctl_main(ns, semid, semnum, cmd, p);
1587         case SETVAL:
1588                 return semctl_setval(ns, semid, semnum, arg);
1589         case IPC_RMID:
1590         case IPC_SET:
1591                 return semctl_down(ns, semid, cmd, version, p);
1592         default:
1593                 return -EINVAL;
1594         }
1595 }
1596
1597 /* If the task doesn't already have a undo_list, then allocate one
1598  * here.  We guarantee there is only one thread using this undo list,
1599  * and current is THE ONE
1600  *
1601  * If this allocation and assignment succeeds, but later
1602  * portions of this code fail, there is no need to free the sem_undo_list.
1603  * Just let it stay associated with the task, and it'll be freed later
1604  * at exit time.
1605  *
1606  * This can block, so callers must hold no locks.
1607  */
1608 static inline int get_undo_list(struct sem_undo_list **undo_listp)
1609 {
1610         struct sem_undo_list *undo_list;
1611
1612         undo_list = current->sysvsem.undo_list;
1613         if (!undo_list) {
1614                 undo_list = kzalloc(sizeof(*undo_list), GFP_KERNEL);
1615                 if (undo_list == NULL)
1616                         return -ENOMEM;
1617                 spin_lock_init(&undo_list->lock);
1618                 atomic_set(&undo_list->refcnt, 1);
1619                 INIT_LIST_HEAD(&undo_list->list_proc);
1620
1621                 current->sysvsem.undo_list = undo_list;
1622         }
1623         *undo_listp = undo_list;
1624         return 0;
1625 }
1626
1627 static struct sem_undo *__lookup_undo(struct sem_undo_list *ulp, int semid)
1628 {
1629         struct sem_undo *un;
1630
1631         list_for_each_entry_rcu(un, &ulp->list_proc, list_proc) {
1632                 if (un->semid == semid)
1633                         return un;
1634         }
1635         return NULL;
1636 }
1637
1638 static struct sem_undo *lookup_undo(struct sem_undo_list *ulp, int semid)
1639 {
1640         struct sem_undo *un;
1641
1642         assert_spin_locked(&ulp->lock);
1643
1644         un = __lookup_undo(ulp, semid);
1645         if (un) {
1646                 list_del_rcu(&un->list_proc);
1647                 list_add_rcu(&un->list_proc, &ulp->list_proc);
1648         }
1649         return un;
1650 }
1651
1652 /**
1653  * find_alloc_undo - lookup (and if not present create) undo array
1654  * @ns: namespace
1655  * @semid: semaphore array id
1656  *
1657  * The function looks up (and if not present creates) the undo structure.
1658  * The size of the undo structure depends on the size of the semaphore
1659  * array, thus the alloc path is not that straightforward.
1660  * Lifetime-rules: sem_undo is rcu-protected, on success, the function
1661  * performs a rcu_read_lock().
1662  */
1663 static struct sem_undo *find_alloc_undo(struct ipc_namespace *ns, int semid)
1664 {
1665         struct sem_array *sma;
1666         struct sem_undo_list *ulp;
1667         struct sem_undo *un, *new;
1668         int nsems, error;
1669
1670         error = get_undo_list(&ulp);
1671         if (error)
1672                 return ERR_PTR(error);
1673
1674         rcu_read_lock();
1675         spin_lock(&ulp->lock);
1676         un = lookup_undo(ulp, semid);
1677         spin_unlock(&ulp->lock);
1678         if (likely(un != NULL))
1679                 goto out;
1680
1681         /* no undo structure around - allocate one. */
1682         /* step 1: figure out the size of the semaphore array */
1683         sma = sem_obtain_object_check(ns, semid);
1684         if (IS_ERR(sma)) {
1685                 rcu_read_unlock();
1686                 return ERR_CAST(sma);
1687         }
1688
1689         nsems = sma->sem_nsems;
1690         if (!ipc_rcu_getref(sma)) {
1691                 rcu_read_unlock();
1692                 un = ERR_PTR(-EIDRM);
1693                 goto out;
1694         }
1695         rcu_read_unlock();
1696
1697         /* step 2: allocate new undo structure */
1698         new = kzalloc(sizeof(struct sem_undo) + sizeof(short)*nsems, GFP_KERNEL);
1699         if (!new) {
1700                 ipc_rcu_putref(sma, ipc_rcu_free);
1701                 return ERR_PTR(-ENOMEM);
1702         }
1703
1704         /* step 3: Acquire the lock on semaphore array */
1705         rcu_read_lock();
1706         sem_lock_and_putref(sma);
1707         if (!ipc_valid_object(&sma->sem_perm)) {
1708                 sem_unlock(sma, -1);
1709                 rcu_read_unlock();
1710                 kfree(new);
1711                 un = ERR_PTR(-EIDRM);
1712                 goto out;
1713         }
1714         spin_lock(&ulp->lock);
1715
1716         /*
1717          * step 4: check for races: did someone else allocate the undo struct?
1718          */
1719         un = lookup_undo(ulp, semid);
1720         if (un) {
1721                 kfree(new);
1722                 goto success;
1723         }
1724         /* step 5: initialize & link new undo structure */
1725         new->semadj = (short *) &new[1];
1726         new->ulp = ulp;
1727         new->semid = semid;
1728         assert_spin_locked(&ulp->lock);
1729         list_add_rcu(&new->list_proc, &ulp->list_proc);
1730         ipc_assert_locked_object(&sma->sem_perm);
1731         list_add(&new->list_id, &sma->list_id);
1732         un = new;
1733
1734 success:
1735         spin_unlock(&ulp->lock);
1736         sem_unlock(sma, -1);
1737 out:
1738         return un;
1739 }
1740
1741
1742 /**
1743  * get_queue_result - retrieve the result code from sem_queue
1744  * @q: Pointer to queue structure
1745  *
1746  * Retrieve the return code from the pending queue. If IN_WAKEUP is found in
1747  * q->status, then we must loop until the value is replaced with the final
1748  * value: This may happen if a task is woken up by an unrelated event (e.g.
1749  * signal) and in parallel the task is woken up by another task because it got
1750  * the requested semaphores.
1751  *
1752  * The function can be called with or without holding the semaphore spinlock.
1753  */
1754 static int get_queue_result(struct sem_queue *q)
1755 {
1756         int error;
1757
1758         error = q->status;
1759         while (unlikely(error == IN_WAKEUP)) {
1760                 cpu_relax();
1761                 error = q->status;
1762         }
1763
1764         return error;
1765 }
1766
1767 SYSCALL_DEFINE4(semtimedop, int, semid, struct sembuf __user *, tsops,
1768                 unsigned, nsops, const struct timespec __user *, timeout)
1769 {
1770         int error = -EINVAL;
1771         struct sem_array *sma;
1772         struct sembuf fast_sops[SEMOPM_FAST];
1773         struct sembuf *sops = fast_sops, *sop;
1774         struct sem_undo *un;
1775         int undos = 0, alter = 0, max, locknum;
1776         struct sem_queue queue;
1777         unsigned long jiffies_left = 0;
1778         struct ipc_namespace *ns;
1779         struct list_head tasks;
1780
1781         ns = current->nsproxy->ipc_ns;
1782
1783         if (nsops < 1 || semid < 0)
1784                 return -EINVAL;
1785         if (nsops > ns->sc_semopm)
1786                 return -E2BIG;
1787         if (nsops > SEMOPM_FAST) {
1788                 sops = kmalloc(sizeof(*sops)*nsops, GFP_KERNEL);
1789                 if (sops == NULL)
1790                         return -ENOMEM;
1791         }
1792         if (copy_from_user(sops, tsops, nsops * sizeof(*tsops))) {
1793                 error =  -EFAULT;
1794                 goto out_free;
1795         }
1796         if (timeout) {
1797                 struct timespec _timeout;
1798                 if (copy_from_user(&_timeout, timeout, sizeof(*timeout))) {
1799                         error = -EFAULT;
1800                         goto out_free;
1801                 }
1802                 if (_timeout.tv_sec < 0 || _timeout.tv_nsec < 0 ||
1803                         _timeout.tv_nsec >= 1000000000L) {
1804                         error = -EINVAL;
1805                         goto out_free;
1806                 }
1807                 jiffies_left = timespec_to_jiffies(&_timeout);
1808         }
1809         max = 0;
1810         for (sop = sops; sop < sops + nsops; sop++) {
1811                 if (sop->sem_num >= max)
1812                         max = sop->sem_num;
1813                 if (sop->sem_flg & SEM_UNDO)
1814                         undos = 1;
1815                 if (sop->sem_op != 0)
1816                         alter = 1;
1817         }
1818
1819         INIT_LIST_HEAD(&tasks);
1820
1821         if (undos) {
1822                 /* On success, find_alloc_undo takes the rcu_read_lock */
1823                 un = find_alloc_undo(ns, semid);
1824                 if (IS_ERR(un)) {
1825                         error = PTR_ERR(un);
1826                         goto out_free;
1827                 }
1828         } else {
1829                 un = NULL;
1830                 rcu_read_lock();
1831         }
1832
1833         sma = sem_obtain_object_check(ns, semid);
1834         if (IS_ERR(sma)) {
1835                 rcu_read_unlock();
1836                 error = PTR_ERR(sma);
1837                 goto out_free;
1838         }
1839
1840         error = -EFBIG;
1841         if (max >= sma->sem_nsems)
1842                 goto out_rcu_wakeup;
1843
1844         error = -EACCES;
1845         if (ipcperms(ns, &sma->sem_perm, alter ? S_IWUGO : S_IRUGO))
1846                 goto out_rcu_wakeup;
1847
1848         error = security_sem_semop(sma, sops, nsops, alter);
1849         if (error)
1850                 goto out_rcu_wakeup;
1851
1852         error = -EIDRM;
1853         locknum = sem_lock(sma, sops, nsops);
1854         /*
1855          * We eventually might perform the following check in a lockless
1856          * fashion, considering ipc_valid_object() locking constraints.
1857          * If nsops == 1 and there is no contention for sem_perm.lock, then
1858          * only a per-semaphore lock is held and it's OK to proceed with the
1859          * check below. More details on the fine grained locking scheme
1860          * entangled here and why it's RMID race safe on comments at sem_lock()
1861          */
1862         if (!ipc_valid_object(&sma->sem_perm))
1863                 goto out_unlock_free;
1864         /*
1865          * semid identifiers are not unique - find_alloc_undo may have
1866          * allocated an undo structure, it was invalidated by an RMID
1867          * and now a new array with received the same id. Check and fail.
1868          * This case can be detected checking un->semid. The existence of
1869          * "un" itself is guaranteed by rcu.
1870          */
1871         if (un && un->semid == -1)
1872                 goto out_unlock_free;
1873
1874         error = perform_atomic_semop(sma, sops, nsops, un,
1875                                         task_tgid_vnr(current));
1876         if (error == 0) {
1877                 /* If the operation was successful, then do
1878                  * the required updates.
1879                  */
1880                 if (alter)
1881                         do_smart_update(sma, sops, nsops, 1, &tasks);
1882                 else
1883                         set_semotime(sma, sops);
1884         }
1885         if (error <= 0)
1886                 goto out_unlock_free;
1887
1888         /* We need to sleep on this operation, so we put the current
1889          * task into the pending queue and go to sleep.
1890          */
1891
1892         queue.sops = sops;
1893         queue.nsops = nsops;
1894         queue.undo = un;
1895         queue.pid = task_tgid_vnr(current);
1896         queue.alter = alter;
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