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