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