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