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