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