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