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