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