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