Fedora kernel-2.6.17-1.2142_FC4 patched with stable patch-2.6.17.4-vs2.0.2-rc26.diff
[linux-2.6.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  * IMPLEMENTATION NOTES ON CODE REWRITE (Eric Schenk, January 1995):
7  * This code underwent a massive rewrite in order to solve some problems
8  * with the original code. In particular the original code failed to
9  * wake up processes that were waiting for semval to go to 0 if the
10  * value went to 0 and was then incremented rapidly enough. In solving
11  * this problem I have also modified the implementation so that it
12  * processes pending operations in a FIFO manner, thus give a guarantee
13  * that processes waiting for a lock on the semaphore won't starve
14  * unless another locking process fails to unlock.
15  * In addition the following two changes in behavior have been introduced:
16  * - The original implementation of semop returned the value
17  *   last semaphore element examined on success. This does not
18  *   match the manual page specifications, and effectively
19  *   allows the user to read the semaphore even if they do not
20  *   have read permissions. The implementation now returns 0
21  *   on success as stated in the manual page.
22  * - There is some confusion over whether the set of undo adjustments
23  *   to be performed at exit should be done in an atomic manner.
24  *   That is, if we are attempting to decrement the semval should we queue
25  *   up and wait until we can do so legally?
26  *   The original implementation attempted to do this.
27  *   The current implementation does not do so. This is because I don't
28  *   think it is the right thing (TM) to do, and because I couldn't
29  *   see a clean way to get the old behavior with the new design.
30  *   The POSIX standard and SVID should be consulted to determine
31  *   what behavior is mandated.
32  *
33  * Further notes on refinement (Christoph Rohland, December 1998):
34  * - The POSIX standard says, that the undo adjustments simply should
35  *   redo. So the current implementation is o.K.
36  * - The previous code had two flaws:
37  *   1) It actively gave the semaphore to the next waiting process
38  *      sleeping on the semaphore. Since this process did not have the
39  *      cpu this led to many unnecessary context switches and bad
40  *      performance. Now we only check which process should be able to
41  *      get the semaphore and if this process wants to reduce some
42  *      semaphore value we simply wake it up without doing the
43  *      operation. So it has to try to get it later. Thus e.g. the
44  *      running process may reacquire the semaphore during the current
45  *      time slice. If it only waits for zero or increases the semaphore,
46  *      we do the operation in advance and wake it up.
47  *   2) It did not wake up all zero waiting processes. We try to do
48  *      better but only get the semops right which only wait for zero or
49  *      increase. If there are decrement operations in the operations
50  *      array we do the same as before.
51  *
52  * With the incarnation of O(1) scheduler, it becomes unnecessary to perform
53  * check/retry algorithm for waking up blocked processes as the new scheduler
54  * is better at handling thread switch than the old one.
55  *
56  * /proc/sysvipc/sem support (c) 1999 Dragos Acostachioaie <dragos@iname.com>
57  *
58  * SMP-threaded, sysctl's added
59  * (c) 1999 Manfred Spraul <manfred@colorfullife.com>
60  * Enforced range limit on SEM_UNDO
61  * (c) 2001 Red Hat Inc <alan@redhat.com>
62  * Lockless wakeup
63  * (c) 2003 Manfred Spraul <manfred@colorfullife.com>
64  *
65  * support for audit of ipc object properties and permission changes
66  * Dustin Kirkland <dustin.kirkland@us.ibm.com>
67  */
68
69 #include <linux/config.h>
70 #include <linux/slab.h>
71 #include <linux/spinlock.h>
72 #include <linux/init.h>
73 #include <linux/proc_fs.h>
74 #include <linux/time.h>
75 #include <linux/smp_lock.h>
76 #include <linux/security.h>
77 #include <linux/syscalls.h>
78 #include <linux/audit.h>
79 #include <linux/capability.h>
80 #include <linux/seq_file.h>
81 #include <linux/mutex.h>
82
83 #include <asm/uaccess.h>
84 #include "util.h"
85
86
87 #define sem_lock(id)    ((struct sem_array*)ipc_lock(&sem_ids,id))
88 #define sem_unlock(sma) ipc_unlock(&(sma)->sem_perm)
89 #define sem_rmid(id)    ((struct sem_array*)ipc_rmid(&sem_ids,id))
90 #define sem_checkid(sma, semid) \
91         ipc_checkid(&sem_ids,&sma->sem_perm,semid)
92 #define sem_buildid(id, seq) \
93         ipc_buildid(&sem_ids, id, seq)
94 static struct ipc_ids sem_ids;
95
96 static int newary (key_t, int, int);
97 static void freeary (struct sem_array *sma, int id);
98 #ifdef CONFIG_PROC_FS
99 static int sysvipc_sem_proc_show(struct seq_file *s, void *it);
100 #endif
101
102 #define SEMMSL_FAST     256 /* 512 bytes on stack */
103 #define SEMOPM_FAST     64  /* ~ 372 bytes on stack */
104
105 /*
106  * linked list protection:
107  *      sem_undo.id_next,
108  *      sem_array.sem_pending{,last},
109  *      sem_array.sem_undo: sem_lock() for read/write
110  *      sem_undo.proc_next: only "current" is allowed to read/write that field.
111  *      
112  */
113
114 int sem_ctls[4] = {SEMMSL, SEMMNS, SEMOPM, SEMMNI};
115 #define sc_semmsl       (sem_ctls[0])
116 #define sc_semmns       (sem_ctls[1])
117 #define sc_semopm       (sem_ctls[2])
118 #define sc_semmni       (sem_ctls[3])
119
120 static int used_sems;
121
122 void __init sem_init (void)
123 {
124         used_sems = 0;
125         ipc_init_ids(&sem_ids,sc_semmni);
126         ipc_init_proc_interface("sysvipc/sem",
127                                 "       key      semid perms      nsems   uid   gid  cuid  cgid      otime      ctime\n",
128                                 &sem_ids,
129                                 sysvipc_sem_proc_show);
130 }
131
132 /*
133  * Lockless wakeup algorithm:
134  * Without the check/retry algorithm a lockless wakeup is possible:
135  * - queue.status is initialized to -EINTR before blocking.
136  * - wakeup is performed by
137  *      * unlinking the queue entry from sma->sem_pending
138  *      * setting queue.status to IN_WAKEUP
139  *        This is the notification for the blocked thread that a
140  *        result value is imminent.
141  *      * call wake_up_process
142  *      * set queue.status to the final value.
143  * - the previously blocked thread checks queue.status:
144  *      * if it's IN_WAKEUP, then it must wait until the value changes
145  *      * if it's not -EINTR, then the operation was completed by
146  *        update_queue. semtimedop can return queue.status without
147  *        performing any operation on the sem array.
148  *      * otherwise it must acquire the spinlock and check what's up.
149  *
150  * The two-stage algorithm is necessary to protect against the following
151  * races:
152  * - if queue.status is set after wake_up_process, then the woken up idle
153  *   thread could race forward and try (and fail) to acquire sma->lock
154  *   before update_queue had a chance to set queue.status
155  * - if queue.status is written before wake_up_process and if the
156  *   blocked process is woken up by a signal between writing
157  *   queue.status and the wake_up_process, then the woken up
158  *   process could return from semtimedop and die by calling
159  *   sys_exit before wake_up_process is called. Then wake_up_process
160  *   will oops, because the task structure is already invalid.
161  *   (yes, this happened on s390 with sysv msg).
162  *
163  */
164 #define IN_WAKEUP       1
165
166 static int newary (key_t key, int nsems, int semflg)
167 {
168         int id;
169         int retval;
170         struct sem_array *sma;
171         int size;
172
173         if (!nsems)
174                 return -EINVAL;
175         if (used_sems + nsems > sc_semmns)
176                 return -ENOSPC;
177
178         size = sizeof (*sma) + nsems * sizeof (struct sem);
179         sma = ipc_rcu_alloc(size);
180         if (!sma) {
181                 return -ENOMEM;
182         }
183         memset (sma, 0, size);
184
185         sma->sem_perm.mode = (semflg & S_IRWXUGO);
186         sma->sem_perm.key = key;
187         sma->sem_perm.xid = vx_current_xid();
188
189         sma->sem_perm.security = NULL;
190         retval = security_sem_alloc(sma);
191         if (retval) {
192                 ipc_rcu_putref(sma);
193                 return retval;
194         }
195
196         id = ipc_addid(&sem_ids, &sma->sem_perm, sc_semmni);
197         if(id == -1) {
198                 security_sem_free(sma);
199                 ipc_rcu_putref(sma);
200                 return -ENOSPC;
201         }
202         used_sems += nsems;
203
204         sma->sem_id = sem_buildid(id, sma->sem_perm.seq);
205         sma->sem_base = (struct sem *) &sma[1];
206         /* sma->sem_pending = NULL; */
207         sma->sem_pending_last = &sma->sem_pending;
208         /* sma->undo = NULL; */
209         sma->sem_nsems = nsems;
210         sma->sem_ctime = get_seconds();
211         sem_unlock(sma);
212
213         return sma->sem_id;
214 }
215
216 asmlinkage long sys_semget (key_t key, int nsems, int semflg)
217 {
218         int id, err = -EINVAL;
219         struct sem_array *sma;
220
221         if (nsems < 0 || nsems > sc_semmsl)
222                 return -EINVAL;
223         mutex_lock(&sem_ids.mutex);
224         
225         if (key == IPC_PRIVATE) {
226                 err = newary(key, nsems, semflg);
227         } else if ((id = ipc_findkey(&sem_ids, key)) == -1) {  /* key not used */
228                 if (!(semflg & IPC_CREAT))
229                         err = -ENOENT;
230                 else
231                         err = newary(key, nsems, semflg);
232         } else if (semflg & IPC_CREAT && semflg & IPC_EXCL) {
233                 err = -EEXIST;
234         } else {
235                 sma = sem_lock(id);
236                 BUG_ON(sma==NULL);
237                 if (nsems > sma->sem_nsems)
238                         err = -EINVAL;
239                 else if (ipcperms(&sma->sem_perm, semflg))
240                         err = -EACCES;
241                 else {
242                         int semid = sem_buildid(id, sma->sem_perm.seq);
243                         err = security_sem_associate(sma, semflg);
244                         if (!err)
245                                 err = semid;
246                 }
247                 sem_unlock(sma);
248         }
249
250         mutex_unlock(&sem_ids.mutex);
251         return err;
252 }
253
254 /* Manage the doubly linked list sma->sem_pending as a FIFO:
255  * insert new queue elements at the tail sma->sem_pending_last.
256  */
257 static inline void append_to_queue (struct sem_array * sma,
258                                     struct sem_queue * q)
259 {
260         *(q->prev = sma->sem_pending_last) = q;
261         *(sma->sem_pending_last = &q->next) = NULL;
262 }
263
264 static inline void prepend_to_queue (struct sem_array * sma,
265                                      struct sem_queue * q)
266 {
267         q->next = sma->sem_pending;
268         *(q->prev = &sma->sem_pending) = q;
269         if (q->next)
270                 q->next->prev = &q->next;
271         else /* sma->sem_pending_last == &sma->sem_pending */
272                 sma->sem_pending_last = &q->next;
273 }
274
275 static inline void remove_from_queue (struct sem_array * sma,
276                                       struct sem_queue * q)
277 {
278         *(q->prev) = q->next;
279         if (q->next)
280                 q->next->prev = q->prev;
281         else /* sma->sem_pending_last == &q->next */
282                 sma->sem_pending_last = q->prev;
283         q->prev = NULL; /* mark as removed */
284 }
285
286 /*
287  * Determine whether a sequence of semaphore operations would succeed
288  * all at once. Return 0 if yes, 1 if need to sleep, else return error code.
289  */
290
291 static int try_atomic_semop (struct sem_array * sma, struct sembuf * sops,
292                              int nsops, struct sem_undo *un, int pid)
293 {
294         int result, sem_op;
295         struct sembuf *sop;
296         struct sem * curr;
297
298         for (sop = sops; sop < sops + nsops; sop++) {
299                 curr = sma->sem_base + sop->sem_num;
300                 sem_op = sop->sem_op;
301                 result = curr->semval;
302   
303                 if (!sem_op && result)
304                         goto would_block;
305
306                 result += sem_op;
307                 if (result < 0)
308                         goto would_block;
309                 if (result > SEMVMX)
310                         goto out_of_range;
311                 if (sop->sem_flg & SEM_UNDO) {
312                         int undo = un->semadj[sop->sem_num] - sem_op;
313                         /*
314                          *      Exceeding the undo range is an error.
315                          */
316                         if (undo < (-SEMAEM - 1) || undo > SEMAEM)
317                                 goto out_of_range;
318                 }
319                 curr->semval = result;
320         }
321
322         sop--;
323         while (sop >= sops) {
324                 sma->sem_base[sop->sem_num].sempid = pid;
325                 if (sop->sem_flg & SEM_UNDO)
326                         un->semadj[sop->sem_num] -= sop->sem_op;
327                 sop--;
328         }
329         
330         sma->sem_otime = get_seconds();
331         return 0;
332
333 out_of_range:
334         result = -ERANGE;
335         goto undo;
336
337 would_block:
338         if (sop->sem_flg & IPC_NOWAIT)
339                 result = -EAGAIN;
340         else
341                 result = 1;
342
343 undo:
344         sop--;
345         while (sop >= sops) {
346                 sma->sem_base[sop->sem_num].semval -= sop->sem_op;
347                 sop--;
348         }
349
350         return result;
351 }
352
353 /* Go through the pending queue for the indicated semaphore
354  * looking for tasks that can be completed.
355  */
356 static void update_queue (struct sem_array * sma)
357 {
358         int error;
359         struct sem_queue * q;
360
361         q = sma->sem_pending;
362         while(q) {
363                 error = try_atomic_semop(sma, q->sops, q->nsops,
364                                          q->undo, q->pid);
365
366                 /* Does q->sleeper still need to sleep? */
367                 if (error <= 0) {
368                         struct sem_queue *n;
369                         remove_from_queue(sma,q);
370                         q->status = IN_WAKEUP;
371                         /*
372                          * Continue scanning. The next operation
373                          * that must be checked depends on the type of the
374                          * completed operation:
375                          * - if the operation modified the array, then
376                          *   restart from the head of the queue and
377                          *   check for threads that might be waiting
378                          *   for semaphore values to become 0.
379                          * - if the operation didn't modify the array,
380                          *   then just continue.
381                          */
382                         if (q->alter)
383                                 n = sma->sem_pending;
384                         else
385                                 n = q->next;
386                         wake_up_process(q->sleeper);
387                         /* hands-off: q will disappear immediately after
388                          * writing q->status.
389                          */
390                         smp_wmb();
391                         q->status = error;
392                         q = n;
393                 } else {
394                         q = q->next;
395                 }
396         }
397 }
398
399 /* The following counts are associated to each semaphore:
400  *   semncnt        number of tasks waiting on semval being nonzero
401  *   semzcnt        number of tasks waiting on semval being zero
402  * This model assumes that a task waits on exactly one semaphore.
403  * Since semaphore operations are to be performed atomically, tasks actually
404  * wait on a whole sequence of semaphores simultaneously.
405  * The counts we return here are a rough approximation, but still
406  * warrant that semncnt+semzcnt>0 if the task is on the pending queue.
407  */
408 static int count_semncnt (struct sem_array * sma, ushort semnum)
409 {
410         int semncnt;
411         struct sem_queue * q;
412
413         semncnt = 0;
414         for (q = sma->sem_pending; q; q = q->next) {
415                 struct sembuf * sops = q->sops;
416                 int nsops = q->nsops;
417                 int i;
418                 for (i = 0; i < nsops; i++)
419                         if (sops[i].sem_num == semnum
420                             && (sops[i].sem_op < 0)
421                             && !(sops[i].sem_flg & IPC_NOWAIT))
422                                 semncnt++;
423         }
424         return semncnt;
425 }
426 static int count_semzcnt (struct sem_array * sma, ushort semnum)
427 {
428         int semzcnt;
429         struct sem_queue * q;
430
431         semzcnt = 0;
432         for (q = sma->sem_pending; q; q = q->next) {
433                 struct sembuf * sops = q->sops;
434                 int nsops = q->nsops;
435                 int i;
436                 for (i = 0; i < nsops; i++)
437                         if (sops[i].sem_num == semnum
438                             && (sops[i].sem_op == 0)
439                             && !(sops[i].sem_flg & IPC_NOWAIT))
440                                 semzcnt++;
441         }
442         return semzcnt;
443 }
444
445 /* Free a semaphore set. freeary() is called with sem_ids.mutex locked and
446  * the spinlock for this semaphore set hold. sem_ids.mutex remains locked
447  * on exit.
448  */
449 static void freeary (struct sem_array *sma, int id)
450 {
451         struct sem_undo *un;
452         struct sem_queue *q;
453         int size;
454
455         /* Invalidate the existing undo structures for this semaphore set.
456          * (They will be freed without any further action in exit_sem()
457          * or during the next semop.)
458          */
459         for (un = sma->undo; un; un = un->id_next)
460                 un->semid = -1;
461
462         /* Wake up all pending processes and let them fail with EIDRM. */
463         q = sma->sem_pending;
464         while(q) {
465                 struct sem_queue *n;
466                 /* lazy remove_from_queue: we are killing the whole queue */
467                 q->prev = NULL;
468                 n = q->next;
469                 q->status = IN_WAKEUP;
470                 wake_up_process(q->sleeper); /* doesn't sleep */
471                 smp_wmb();
472                 q->status = -EIDRM;     /* hands-off q */
473                 q = n;
474         }
475
476         /* Remove the semaphore set from the ID array*/
477         sma = sem_rmid(id);
478         sem_unlock(sma);
479
480         used_sems -= sma->sem_nsems;
481         size = sizeof (*sma) + sma->sem_nsems * sizeof (struct sem);
482         security_sem_free(sma);
483         ipc_rcu_putref(sma);
484 }
485
486 static unsigned long copy_semid_to_user(void __user *buf, struct semid64_ds *in, int version)
487 {
488         switch(version) {
489         case IPC_64:
490                 return copy_to_user(buf, in, sizeof(*in));
491         case IPC_OLD:
492             {
493                 struct semid_ds out;
494
495                 ipc64_perm_to_ipc_perm(&in->sem_perm, &out.sem_perm);
496
497                 out.sem_otime   = in->sem_otime;
498                 out.sem_ctime   = in->sem_ctime;
499                 out.sem_nsems   = in->sem_nsems;
500
501                 return copy_to_user(buf, &out, sizeof(out));
502             }
503         default:
504                 return -EINVAL;
505         }
506 }
507
508 static int semctl_nolock(int semid, int semnum, int cmd, int version, union semun arg)
509 {
510         int err = -EINVAL;
511         struct sem_array *sma;
512
513         switch(cmd) {
514         case IPC_INFO:
515         case SEM_INFO:
516         {
517                 struct seminfo seminfo;
518                 int max_id;
519
520                 err = security_sem_semctl(NULL, cmd);
521                 if (err)
522                         return err;
523                 
524                 memset(&seminfo,0,sizeof(seminfo));
525                 seminfo.semmni = sc_semmni;
526                 seminfo.semmns = sc_semmns;
527                 seminfo.semmsl = sc_semmsl;
528                 seminfo.semopm = sc_semopm;
529                 seminfo.semvmx = SEMVMX;
530                 seminfo.semmnu = SEMMNU;
531                 seminfo.semmap = SEMMAP;
532                 seminfo.semume = SEMUME;
533                 mutex_lock(&sem_ids.mutex);
534                 if (cmd == SEM_INFO) {
535                         seminfo.semusz = sem_ids.in_use;
536                         seminfo.semaem = used_sems;
537                 } else {
538                         seminfo.semusz = SEMUSZ;
539                         seminfo.semaem = SEMAEM;
540                 }
541                 max_id = sem_ids.max_id;
542                 mutex_unlock(&sem_ids.mutex);
543                 if (copy_to_user (arg.__buf, &seminfo, sizeof(struct seminfo))) 
544                         return -EFAULT;
545                 return (max_id < 0) ? 0: max_id;
546         }
547         case SEM_STAT:
548         {
549                 struct semid64_ds tbuf;
550                 int id;
551
552                 if(semid >= sem_ids.entries->size)
553                         return -EINVAL;
554
555                 memset(&tbuf,0,sizeof(tbuf));
556
557                 sma = sem_lock(semid);
558                 if(sma == NULL)
559                         return -EINVAL;
560
561                 err = -EACCES;
562                 if (ipcperms (&sma->sem_perm, S_IRUGO))
563                         goto out_unlock;
564
565                 err = security_sem_semctl(sma, cmd);
566                 if (err)
567                         goto out_unlock;
568
569                 id = sem_buildid(semid, sma->sem_perm.seq);
570
571                 kernel_to_ipc64_perm(&sma->sem_perm, &tbuf.sem_perm);
572                 tbuf.sem_otime  = sma->sem_otime;
573                 tbuf.sem_ctime  = sma->sem_ctime;
574                 tbuf.sem_nsems  = sma->sem_nsems;
575                 sem_unlock(sma);
576                 if (copy_semid_to_user (arg.buf, &tbuf, version))
577                         return -EFAULT;
578                 return id;
579         }
580         default:
581                 return -EINVAL;
582         }
583         return err;
584 out_unlock:
585         sem_unlock(sma);
586         return err;
587 }
588
589 static int semctl_main(int semid, int semnum, int cmd, int version, union semun arg)
590 {
591         struct sem_array *sma;
592         struct sem* curr;
593         int err;
594         ushort fast_sem_io[SEMMSL_FAST];
595         ushort* sem_io = fast_sem_io;
596         int nsems;
597
598         sma = sem_lock(semid);
599         if(sma==NULL)
600                 return -EINVAL;
601
602         nsems = sma->sem_nsems;
603
604         err=-EIDRM;
605         if (sem_checkid(sma,semid))
606                 goto out_unlock;
607
608         err = -EACCES;
609         if (ipcperms (&sma->sem_perm, (cmd==SETVAL||cmd==SETALL)?S_IWUGO:S_IRUGO))
610                 goto out_unlock;
611
612         err = security_sem_semctl(sma, cmd);
613         if (err)
614                 goto out_unlock;
615
616         err = -EACCES;
617         switch (cmd) {
618         case GETALL:
619         {
620                 ushort __user *array = arg.array;
621                 int i;
622
623                 if(nsems > SEMMSL_FAST) {
624                         ipc_rcu_getref(sma);
625                         sem_unlock(sma);                        
626
627                         sem_io = ipc_alloc(sizeof(ushort)*nsems);
628                         if(sem_io == NULL) {
629                                 ipc_lock_by_ptr(&sma->sem_perm);
630                                 ipc_rcu_putref(sma);
631                                 sem_unlock(sma);
632                                 return -ENOMEM;
633                         }
634
635                         ipc_lock_by_ptr(&sma->sem_perm);
636                         ipc_rcu_putref(sma);
637                         if (sma->sem_perm.deleted) {
638                                 sem_unlock(sma);
639                                 err = -EIDRM;
640                                 goto out_free;
641                         }
642                 }
643
644                 for (i = 0; i < sma->sem_nsems; i++)
645                         sem_io[i] = sma->sem_base[i].semval;
646                 sem_unlock(sma);
647                 err = 0;
648                 if(copy_to_user(array, sem_io, nsems*sizeof(ushort)))
649                         err = -EFAULT;
650                 goto out_free;
651         }
652         case SETALL:
653         {
654                 int i;
655                 struct sem_undo *un;
656
657                 ipc_rcu_getref(sma);
658                 sem_unlock(sma);
659
660                 if(nsems > SEMMSL_FAST) {
661                         sem_io = ipc_alloc(sizeof(ushort)*nsems);
662                         if(sem_io == NULL) {
663                                 ipc_lock_by_ptr(&sma->sem_perm);
664                                 ipc_rcu_putref(sma);
665                                 sem_unlock(sma);
666                                 return -ENOMEM;
667                         }
668                 }
669
670                 if (copy_from_user (sem_io, arg.array, nsems*sizeof(ushort))) {
671                         ipc_lock_by_ptr(&sma->sem_perm);
672                         ipc_rcu_putref(sma);
673                         sem_unlock(sma);
674                         err = -EFAULT;
675                         goto out_free;
676                 }
677
678                 for (i = 0; i < nsems; i++) {
679                         if (sem_io[i] > SEMVMX) {
680                                 ipc_lock_by_ptr(&sma->sem_perm);
681                                 ipc_rcu_putref(sma);
682                                 sem_unlock(sma);
683                                 err = -ERANGE;
684                                 goto out_free;
685                         }
686                 }
687                 ipc_lock_by_ptr(&sma->sem_perm);
688                 ipc_rcu_putref(sma);
689                 if (sma->sem_perm.deleted) {
690                         sem_unlock(sma);
691                         err = -EIDRM;
692                         goto out_free;
693                 }
694
695                 for (i = 0; i < nsems; i++)
696                         sma->sem_base[i].semval = sem_io[i];
697                 for (un = sma->undo; un; un = un->id_next)
698                         for (i = 0; i < nsems; i++)
699                                 un->semadj[i] = 0;
700                 sma->sem_ctime = get_seconds();
701                 /* maybe some queued-up processes were waiting for this */
702                 update_queue(sma);
703                 err = 0;
704                 goto out_unlock;
705         }
706         case IPC_STAT:
707         {
708                 struct semid64_ds tbuf;
709                 memset(&tbuf,0,sizeof(tbuf));
710                 kernel_to_ipc64_perm(&sma->sem_perm, &tbuf.sem_perm);
711                 tbuf.sem_otime  = sma->sem_otime;
712                 tbuf.sem_ctime  = sma->sem_ctime;
713                 tbuf.sem_nsems  = sma->sem_nsems;
714                 sem_unlock(sma);
715                 if (copy_semid_to_user (arg.buf, &tbuf, version))
716                         return -EFAULT;
717                 return 0;
718         }
719         /* GETVAL, GETPID, GETNCTN, GETZCNT, SETVAL: fall-through */
720         }
721         err = -EINVAL;
722         if(semnum < 0 || semnum >= nsems)
723                 goto out_unlock;
724
725         curr = &sma->sem_base[semnum];
726
727         switch (cmd) {
728         case GETVAL:
729                 err = curr->semval;
730                 goto out_unlock;
731         case GETPID:
732                 err = curr->sempid;
733                 goto out_unlock;
734         case GETNCNT:
735                 err = count_semncnt(sma,semnum);
736                 goto out_unlock;
737         case GETZCNT:
738                 err = count_semzcnt(sma,semnum);
739                 goto out_unlock;
740         case SETVAL:
741         {
742                 int val = arg.val;
743                 struct sem_undo *un;
744                 err = -ERANGE;
745                 if (val > SEMVMX || val < 0)
746                         goto out_unlock;
747
748                 for (un = sma->undo; un; un = un->id_next)
749                         un->semadj[semnum] = 0;
750                 curr->semval = val;
751                 curr->sempid = current->tgid;
752                 sma->sem_ctime = get_seconds();
753                 /* maybe some queued-up processes were waiting for this */
754                 update_queue(sma);
755                 err = 0;
756                 goto out_unlock;
757         }
758         }
759 out_unlock:
760         sem_unlock(sma);
761 out_free:
762         if(sem_io != fast_sem_io)
763                 ipc_free(sem_io, sizeof(ushort)*nsems);
764         return err;
765 }
766
767 struct sem_setbuf {
768         uid_t   uid;
769         gid_t   gid;
770         mode_t  mode;
771 };
772
773 static inline unsigned long copy_semid_from_user(struct sem_setbuf *out, void __user *buf, int version)
774 {
775         switch(version) {
776         case IPC_64:
777             {
778                 struct semid64_ds tbuf;
779
780                 if(copy_from_user(&tbuf, buf, sizeof(tbuf)))
781                         return -EFAULT;
782
783                 out->uid        = tbuf.sem_perm.uid;
784                 out->gid        = tbuf.sem_perm.gid;
785                 out->mode       = tbuf.sem_perm.mode;
786
787                 return 0;
788             }
789         case IPC_OLD:
790             {
791                 struct semid_ds tbuf_old;
792
793                 if(copy_from_user(&tbuf_old, buf, sizeof(tbuf_old)))
794                         return -EFAULT;
795
796                 out->uid        = tbuf_old.sem_perm.uid;
797                 out->gid        = tbuf_old.sem_perm.gid;
798                 out->mode       = tbuf_old.sem_perm.mode;
799
800                 return 0;
801             }
802         default:
803                 return -EINVAL;
804         }
805 }
806
807 static int semctl_down(int semid, int semnum, int cmd, int version, union semun arg)
808 {
809         struct sem_array *sma;
810         int err;
811         struct sem_setbuf setbuf;
812         struct kern_ipc_perm *ipcp;
813
814         if(cmd == IPC_SET) {
815                 if(copy_semid_from_user (&setbuf, arg.buf, version))
816                         return -EFAULT;
817         }
818         sma = sem_lock(semid);
819         if(sma==NULL)
820                 return -EINVAL;
821
822         if (sem_checkid(sma,semid)) {
823                 err=-EIDRM;
824                 goto out_unlock;
825         }       
826         ipcp = &sma->sem_perm;
827
828         err = audit_ipc_obj(ipcp);
829         if (err)
830                 goto out_unlock;
831
832         if (current->euid != ipcp->cuid && 
833             current->euid != ipcp->uid && !capable(CAP_SYS_ADMIN)) {
834                 err=-EPERM;
835                 goto out_unlock;
836         }
837
838         err = security_sem_semctl(sma, cmd);
839         if (err)
840                 goto out_unlock;
841
842         switch(cmd){
843         case IPC_RMID:
844                 freeary(sma, semid);
845                 err = 0;
846                 break;
847         case IPC_SET:
848                 err = audit_ipc_set_perm(0, setbuf.uid, setbuf.gid, setbuf.mode, ipcp);
849                 if (err)
850                         goto out_unlock;
851                 ipcp->uid = setbuf.uid;
852                 ipcp->gid = setbuf.gid;
853                 ipcp->mode = (ipcp->mode & ~S_IRWXUGO)
854                                 | (setbuf.mode & S_IRWXUGO);
855                 sma->sem_ctime = get_seconds();
856                 sem_unlock(sma);
857                 err = 0;
858                 break;
859         default:
860                 sem_unlock(sma);
861                 err = -EINVAL;
862                 break;
863         }
864         return err;
865
866 out_unlock:
867         sem_unlock(sma);
868         return err;
869 }
870
871 asmlinkage long sys_semctl (int semid, int semnum, int cmd, union semun arg)
872 {
873         int err = -EINVAL;
874         int version;
875
876         if (semid < 0)
877                 return -EINVAL;
878
879         version = ipc_parse_version(&cmd);
880
881         switch(cmd) {
882         case IPC_INFO:
883         case SEM_INFO:
884         case SEM_STAT:
885                 err = semctl_nolock(semid,semnum,cmd,version,arg);
886                 return err;
887         case GETALL:
888         case GETVAL:
889         case GETPID:
890         case GETNCNT:
891         case GETZCNT:
892         case IPC_STAT:
893         case SETVAL:
894         case SETALL:
895                 err = semctl_main(semid,semnum,cmd,version,arg);
896                 return err;
897         case IPC_RMID:
898         case IPC_SET:
899                 mutex_lock(&sem_ids.mutex);
900                 err = semctl_down(semid,semnum,cmd,version,arg);
901                 mutex_unlock(&sem_ids.mutex);
902                 return err;
903         default:
904                 return -EINVAL;
905         }
906 }
907
908 static inline void lock_semundo(void)
909 {
910         struct sem_undo_list *undo_list;
911
912         undo_list = current->sysvsem.undo_list;
913         if (undo_list)
914                 spin_lock(&undo_list->lock);
915 }
916
917 /* This code has an interaction with copy_semundo().
918  * Consider; two tasks are sharing the undo_list. task1
919  * acquires the undo_list lock in lock_semundo().  If task2 now
920  * exits before task1 releases the lock (by calling
921  * unlock_semundo()), then task1 will never call spin_unlock().
922  * This leave the sem_undo_list in a locked state.  If task1 now creats task3
923  * and once again shares the sem_undo_list, the sem_undo_list will still be
924  * locked, and future SEM_UNDO operations will deadlock.  This case is
925  * dealt with in copy_semundo() by having it reinitialize the spin lock when 
926  * the refcnt goes from 1 to 2.
927  */
928 static inline void unlock_semundo(void)
929 {
930         struct sem_undo_list *undo_list;
931
932         undo_list = current->sysvsem.undo_list;
933         if (undo_list)
934                 spin_unlock(&undo_list->lock);
935 }
936
937
938 /* If the task doesn't already have a undo_list, then allocate one
939  * here.  We guarantee there is only one thread using this undo list,
940  * and current is THE ONE
941  *
942  * If this allocation and assignment succeeds, but later
943  * portions of this code fail, there is no need to free the sem_undo_list.
944  * Just let it stay associated with the task, and it'll be freed later
945  * at exit time.
946  *
947  * This can block, so callers must hold no locks.
948  */
949 static inline int get_undo_list(struct sem_undo_list **undo_listp)
950 {
951         struct sem_undo_list *undo_list;
952         int size;
953
954         undo_list = current->sysvsem.undo_list;
955         if (!undo_list) {
956                 size = sizeof(struct sem_undo_list);
957                 undo_list = (struct sem_undo_list *) kmalloc(size, GFP_KERNEL);
958                 if (undo_list == NULL)
959                         return -ENOMEM;
960                 memset(undo_list, 0, size);
961                 spin_lock_init(&undo_list->lock);
962                 atomic_set(&undo_list->refcnt, 1);
963                 current->sysvsem.undo_list = undo_list;
964         }
965         *undo_listp = undo_list;
966         return 0;
967 }
968
969 static struct sem_undo *lookup_undo(struct sem_undo_list *ulp, int semid)
970 {
971         struct sem_undo **last, *un;
972
973         last = &ulp->proc_list;
974         un = *last;
975         while(un != NULL) {
976                 if(un->semid==semid)
977                         break;
978                 if(un->semid==-1) {
979                         *last=un->proc_next;
980                         kfree(un);
981                 } else {
982                         last=&un->proc_next;
983                 }
984                 un=*last;
985         }
986         return un;
987 }
988
989 static struct sem_undo *find_undo(int semid)
990 {
991         struct sem_array *sma;
992         struct sem_undo_list *ulp;
993         struct sem_undo *un, *new;
994         int nsems;
995         int error;
996
997         error = get_undo_list(&ulp);
998         if (error)
999                 return ERR_PTR(error);
1000
1001         lock_semundo();
1002         un = lookup_undo(ulp, semid);
1003         unlock_semundo();
1004         if (likely(un!=NULL))
1005                 goto out;
1006
1007         /* no undo structure around - allocate one. */
1008         sma = sem_lock(semid);
1009         un = ERR_PTR(-EINVAL);
1010         if(sma==NULL)
1011                 goto out;
1012         un = ERR_PTR(-EIDRM);
1013         if (sem_checkid(sma,semid)) {
1014                 sem_unlock(sma);
1015                 goto out;
1016         }
1017         nsems = sma->sem_nsems;
1018         ipc_rcu_getref(sma);
1019         sem_unlock(sma);
1020
1021         new = (struct sem_undo *) kmalloc(sizeof(struct sem_undo) + sizeof(short)*nsems, GFP_KERNEL);
1022         if (!new) {
1023                 ipc_lock_by_ptr(&sma->sem_perm);
1024                 ipc_rcu_putref(sma);
1025                 sem_unlock(sma);
1026                 return ERR_PTR(-ENOMEM);
1027         }
1028         memset(new, 0, sizeof(struct sem_undo) + sizeof(short)*nsems);
1029         new->semadj = (short *) &new[1];
1030         new->semid = semid;
1031
1032         lock_semundo();
1033         un = lookup_undo(ulp, semid);
1034         if (un) {
1035                 unlock_semundo();
1036                 kfree(new);
1037                 ipc_lock_by_ptr(&sma->sem_perm);
1038                 ipc_rcu_putref(sma);
1039                 sem_unlock(sma);
1040                 goto out;
1041         }
1042         ipc_lock_by_ptr(&sma->sem_perm);
1043         ipc_rcu_putref(sma);
1044         if (sma->sem_perm.deleted) {
1045                 sem_unlock(sma);
1046                 unlock_semundo();
1047                 kfree(new);
1048                 un = ERR_PTR(-EIDRM);
1049                 goto out;
1050         }
1051         new->proc_next = ulp->proc_list;
1052         ulp->proc_list = new;
1053         new->id_next = sma->undo;
1054         sma->undo = new;
1055         sem_unlock(sma);
1056         un = new;
1057         unlock_semundo();
1058 out:
1059         return un;
1060 }
1061
1062 asmlinkage long sys_semtimedop(int semid, struct sembuf __user *tsops,
1063                         unsigned nsops, const struct timespec __user *timeout)
1064 {
1065         int error = -EINVAL;
1066         struct sem_array *sma;
1067         struct sembuf fast_sops[SEMOPM_FAST];
1068         struct sembuf* sops = fast_sops, *sop;
1069         struct sem_undo *un;
1070         int undos = 0, alter = 0, max;
1071         struct sem_queue queue;
1072         unsigned long jiffies_left = 0;
1073
1074         if (nsops < 1 || semid < 0)
1075                 return -EINVAL;
1076         if (nsops > sc_semopm)
1077                 return -E2BIG;
1078         if(nsops > SEMOPM_FAST) {
1079                 sops = kmalloc(sizeof(*sops)*nsops,GFP_KERNEL);
1080                 if(sops==NULL)
1081                         return -ENOMEM;
1082         }
1083         if (copy_from_user (sops, tsops, nsops * sizeof(*tsops))) {
1084                 error=-EFAULT;
1085                 goto out_free;
1086         }
1087         if (timeout) {
1088                 struct timespec _timeout;
1089                 if (copy_from_user(&_timeout, timeout, sizeof(*timeout))) {
1090                         error = -EFAULT;
1091                         goto out_free;
1092                 }
1093                 if (_timeout.tv_sec < 0 || _timeout.tv_nsec < 0 ||
1094                         _timeout.tv_nsec >= 1000000000L) {
1095                         error = -EINVAL;
1096                         goto out_free;
1097                 }
1098                 jiffies_left = timespec_to_jiffies(&_timeout);
1099         }
1100         max = 0;
1101         for (sop = sops; sop < sops + nsops; sop++) {
1102                 if (sop->sem_num >= max)
1103                         max = sop->sem_num;
1104                 if (sop->sem_flg & SEM_UNDO)
1105                         undos = 1;
1106                 if (sop->sem_op != 0)
1107                         alter = 1;
1108         }
1109
1110 retry_undos:
1111         if (undos) {
1112                 un = find_undo(semid);
1113                 if (IS_ERR(un)) {
1114                         error = PTR_ERR(un);
1115                         goto out_free;
1116                 }
1117         } else
1118                 un = NULL;
1119
1120         sma = sem_lock(semid);
1121         error=-EINVAL;
1122         if(sma==NULL)
1123                 goto out_free;
1124         error = -EIDRM;
1125         if (sem_checkid(sma,semid))
1126                 goto out_unlock_free;
1127         /*
1128          * semid identifies are not unique - find_undo may have
1129          * allocated an undo structure, it was invalidated by an RMID
1130          * and now a new array with received the same id. Check and retry.
1131          */
1132         if (un && un->semid == -1) {
1133                 sem_unlock(sma);
1134                 goto retry_undos;
1135         }
1136         error = -EFBIG;
1137         if (max >= sma->sem_nsems)
1138                 goto out_unlock_free;
1139
1140         error = -EACCES;
1141         if (ipcperms(&sma->sem_perm, alter ? S_IWUGO : S_IRUGO))
1142                 goto out_unlock_free;
1143
1144         error = security_sem_semop(sma, sops, nsops, alter);
1145         if (error)
1146                 goto out_unlock_free;
1147
1148         error = try_atomic_semop (sma, sops, nsops, un, current->tgid);
1149         if (error <= 0) {
1150                 if (alter && error == 0)
1151                         update_queue (sma);
1152                 goto out_unlock_free;
1153         }
1154
1155         /* We need to sleep on this operation, so we put the current
1156          * task into the pending queue and go to sleep.
1157          */
1158                 
1159         queue.sma = sma;
1160         queue.sops = sops;
1161         queue.nsops = nsops;
1162         queue.undo = un;
1163         queue.pid = current->tgid;
1164         queue.id = semid;
1165         queue.alter = alter;
1166         if (alter)
1167                 append_to_queue(sma ,&queue);
1168         else
1169                 prepend_to_queue(sma ,&queue);
1170
1171         queue.status = -EINTR;
1172         queue.sleeper = current;
1173         current->state = TASK_INTERRUPTIBLE;
1174         sem_unlock(sma);
1175
1176         if (timeout)
1177                 jiffies_left = schedule_timeout(jiffies_left);
1178         else
1179                 schedule();
1180
1181         error = queue.status;
1182         while(unlikely(error == IN_WAKEUP)) {
1183                 cpu_relax();
1184                 error = queue.status;
1185         }
1186
1187         if (error != -EINTR) {
1188                 /* fast path: update_queue already obtained all requested
1189                  * resources */
1190                 goto out_free;
1191         }
1192
1193         sma = sem_lock(semid);
1194         if(sma==NULL) {
1195                 BUG_ON(queue.prev != NULL);
1196                 error = -EIDRM;
1197                 goto out_free;
1198         }
1199
1200         /*
1201          * If queue.status != -EINTR we are woken up by another process
1202          */
1203         error = queue.status;
1204         if (error != -EINTR) {
1205                 goto out_unlock_free;
1206         }
1207
1208         /*
1209          * If an interrupt occurred we have to clean up the queue
1210          */
1211         if (timeout && jiffies_left == 0)
1212                 error = -EAGAIN;
1213         remove_from_queue(sma,&queue);
1214         goto out_unlock_free;
1215
1216 out_unlock_free:
1217         sem_unlock(sma);
1218 out_free:
1219         if(sops != fast_sops)
1220                 kfree(sops);
1221         return error;
1222 }
1223
1224 asmlinkage long sys_semop (int semid, struct sembuf __user *tsops, unsigned nsops)
1225 {
1226         return sys_semtimedop(semid, tsops, nsops, NULL);
1227 }
1228
1229 /* If CLONE_SYSVSEM is set, establish sharing of SEM_UNDO state between
1230  * parent and child tasks.
1231  *
1232  * See the notes above unlock_semundo() regarding the spin_lock_init()
1233  * in this code.  Initialize the undo_list->lock here instead of get_undo_list()
1234  * because of the reasoning in the comment above unlock_semundo.
1235  */
1236
1237 int copy_semundo(unsigned long clone_flags, struct task_struct *tsk)
1238 {
1239         struct sem_undo_list *undo_list;
1240         int error;
1241
1242         if (clone_flags & CLONE_SYSVSEM) {
1243                 error = get_undo_list(&undo_list);
1244                 if (error)
1245                         return error;
1246                 atomic_inc(&undo_list->refcnt);
1247                 tsk->sysvsem.undo_list = undo_list;
1248         } else 
1249                 tsk->sysvsem.undo_list = NULL;
1250
1251         return 0;
1252 }
1253
1254 /*
1255  * add semadj values to semaphores, free undo structures.
1256  * undo structures are not freed when semaphore arrays are destroyed
1257  * so some of them may be out of date.
1258  * IMPLEMENTATION NOTE: There is some confusion over whether the
1259  * set of adjustments that needs to be done should be done in an atomic
1260  * manner or not. That is, if we are attempting to decrement the semval
1261  * should we queue up and wait until we can do so legally?
1262  * The original implementation attempted to do this (queue and wait).
1263  * The current implementation does not do so. The POSIX standard
1264  * and SVID should be consulted to determine what behavior is mandated.
1265  */
1266 void exit_sem(struct task_struct *tsk)
1267 {
1268         struct sem_undo_list *undo_list;
1269         struct sem_undo *u, **up;
1270
1271         undo_list = tsk->sysvsem.undo_list;
1272         if (!undo_list)
1273                 return;
1274
1275         if (!atomic_dec_and_test(&undo_list->refcnt))
1276                 return;
1277
1278         /* There's no need to hold the semundo list lock, as current
1279          * is the last task exiting for this undo list.
1280          */
1281         for (up = &undo_list->proc_list; (u = *up); *up = u->proc_next, kfree(u)) {
1282                 struct sem_array *sma;
1283                 int nsems, i;
1284                 struct sem_undo *un, **unp;
1285                 int semid;
1286                
1287                 semid = u->semid;
1288
1289                 if(semid == -1)
1290                         continue;
1291                 sma = sem_lock(semid);
1292                 if (sma == NULL)
1293                         continue;
1294
1295                 if (u->semid == -1)
1296                         goto next_entry;
1297
1298                 BUG_ON(sem_checkid(sma,u->semid));
1299
1300                 /* remove u from the sma->undo list */
1301                 for (unp = &sma->undo; (un = *unp); unp = &un->id_next) {
1302                         if (u == un)
1303                                 goto found;
1304                 }
1305                 printk ("exit_sem undo list error id=%d\n", u->semid);
1306                 goto next_entry;
1307 found:
1308                 *unp = un->id_next;
1309                 /* perform adjustments registered in u */
1310                 nsems = sma->sem_nsems;
1311                 for (i = 0; i < nsems; i++) {
1312                         struct sem * semaphore = &sma->sem_base[i];
1313                         if (u->semadj[i]) {
1314                                 semaphore->semval += u->semadj[i];
1315                                 /*
1316                                  * Range checks of the new semaphore value,
1317                                  * not defined by sus:
1318                                  * - Some unices ignore the undo entirely
1319                                  *   (e.g. HP UX 11i 11.22, Tru64 V5.1)
1320                                  * - some cap the value (e.g. FreeBSD caps
1321                                  *   at 0, but doesn't enforce SEMVMX)
1322                                  *
1323                                  * Linux caps the semaphore value, both at 0
1324                                  * and at SEMVMX.
1325                                  *
1326                                  *      Manfred <manfred@colorfullife.com>
1327                                  */
1328                                 if (semaphore->semval < 0)
1329                                         semaphore->semval = 0;
1330                                 if (semaphore->semval > SEMVMX)
1331                                         semaphore->semval = SEMVMX;
1332                                 semaphore->sempid = current->tgid;
1333                         }
1334                 }
1335                 sma->sem_otime = get_seconds();
1336                 /* maybe some queued-up processes were waiting for this */
1337                 update_queue(sma);
1338 next_entry:
1339                 sem_unlock(sma);
1340         }
1341         kfree(undo_list);
1342 }
1343
1344 #ifdef CONFIG_PROC_FS
1345 static int sysvipc_sem_proc_show(struct seq_file *s, void *it)
1346 {
1347         struct sem_array *sma = it;
1348
1349         if (!vx_check(sma->sem_perm.xid, VX_IDENT))
1350                 return 0;
1351
1352         return seq_printf(s,
1353                           "%10d %10d  %4o %10lu %5u %5u %5u %5u %10lu %10lu\n",
1354                           sma->sem_perm.key,
1355                           sma->sem_id,
1356                           sma->sem_perm.mode,
1357                           sma->sem_nsems,
1358                           sma->sem_perm.uid,
1359                           sma->sem_perm.gid,
1360                           sma->sem_perm.cuid,
1361                           sma->sem_perm.cgid,
1362                           sma->sem_otime,
1363                           sma->sem_ctime);
1364 }
1365 #endif