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