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