3 * Copyright (C) 1992 Krishna Balasubramanian
4 * Copyright (C) 1995 Eric Schenk, Bruno Haible
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.
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.
52 * /proc/sysvipc/sem support (c) 1999 Dragos Acostachioaie <dragos@iname.com>
54 * SMP-threaded, sysctl's added
55 * (c) 1999 Manfred Spraul <manfreds@colorfullife.com>
56 * Enforced range limit on SEM_UNDO
57 * (c) 2001 Red Hat Inc <alan@redhat.com>
60 #include <linux/config.h>
61 #include <linux/slab.h>
62 #include <linux/spinlock.h>
63 #include <linux/init.h>
64 #include <linux/proc_fs.h>
65 #include <asm/uaccess.h>
69 #define sem_lock(id) ((struct sem_array*)ipc_lock(&sem_ids,id))
70 #define sem_unlock(id) ipc_unlock(&sem_ids,id)
71 #define sem_rmid(id) ((struct sem_array*)ipc_rmid(&sem_ids,id))
72 #define sem_checkid(sma, semid) \
73 ipc_checkid(&sem_ids,&sma->sem_perm,semid)
74 #define sem_buildid(id, seq) \
75 ipc_buildid(&sem_ids, id, seq)
76 static struct ipc_ids sem_ids;
78 static int newary (key_t, int, int);
79 static void freeary (int id);
81 static int sysvipc_sem_read_proc(char *buffer, char **start, off_t offset, int length, int *eof, void *data);
84 #define SEMMSL_FAST 256 /* 512 bytes on stack */
85 #define SEMOPM_FAST 64 /* ~ 372 bytes on stack */
88 * linked list protection:
90 * sem_array.sem_pending{,last},
91 * sem_array.sem_undo: sem_lock() for read/write
92 * sem_undo.proc_next: only "current" is allowed to read/write that field.
96 int sem_ctls[4] = {SEMMSL, SEMMNS, SEMOPM, SEMMNI};
97 #define sc_semmsl (sem_ctls[0])
98 #define sc_semmns (sem_ctls[1])
99 #define sc_semopm (sem_ctls[2])
100 #define sc_semmni (sem_ctls[3])
102 static int used_sems;
104 void __init sem_init (void)
107 ipc_init_ids(&sem_ids,sc_semmni);
109 #ifdef CONFIG_PROC_FS
110 create_proc_read_entry("sysvipc/sem", 0, 0, sysvipc_sem_read_proc, NULL);
114 static int newary (key_t key, int nsems, int semflg)
117 struct sem_array *sma;
122 if (used_sems + nsems > sc_semmns)
125 size = sizeof (*sma) + nsems * sizeof (struct sem);
126 sma = (struct sem_array *) ipc_alloc(size);
130 memset (sma, 0, size);
131 id = ipc_addid(&sem_ids, &sma->sem_perm, sc_semmni);
138 sma->sem_perm.mode = (semflg & S_IRWXUGO);
139 sma->sem_perm.key = key;
141 sma->sem_base = (struct sem *) &sma[1];
142 /* sma->sem_pending = NULL; */
143 sma->sem_pending_last = &sma->sem_pending;
144 /* sma->undo = NULL; */
145 sma->sem_nsems = nsems;
146 sma->sem_ctime = CURRENT_TIME;
149 return sem_buildid(id, sma->sem_perm.seq);
152 asmlinkage long sys_semget (key_t key, int nsems, int semflg)
154 int id, err = -EINVAL;
155 struct sem_array *sma;
157 if (nsems < 0 || nsems > sc_semmsl)
161 if (key == IPC_PRIVATE) {
162 err = newary(key, nsems, semflg);
163 } else if ((id = ipc_findkey(&sem_ids, key)) == -1) { /* key not used */
164 if (!(semflg & IPC_CREAT))
167 err = newary(key, nsems, semflg);
168 } else if (semflg & IPC_CREAT && semflg & IPC_EXCL) {
174 if (nsems > sma->sem_nsems)
176 else if (ipcperms(&sma->sem_perm, semflg))
179 err = sem_buildid(id, sma->sem_perm.seq);
187 /* doesn't acquire the sem_lock on error! */
188 static int sem_revalidate(int semid, struct sem_array* sma, int nsems, short flg)
190 struct sem_array* smanew;
192 smanew = sem_lock(semid);
195 if(smanew != sma || sem_checkid(sma,semid) || sma->sem_nsems != nsems) {
200 if (ipcperms(&sma->sem_perm, flg)) {
206 /* Manage the doubly linked list sma->sem_pending as a FIFO:
207 * insert new queue elements at the tail sma->sem_pending_last.
209 static inline void append_to_queue (struct sem_array * sma,
210 struct sem_queue * q)
212 *(q->prev = sma->sem_pending_last) = q;
213 *(sma->sem_pending_last = &q->next) = NULL;
216 static inline void prepend_to_queue (struct sem_array * sma,
217 struct sem_queue * q)
219 q->next = sma->sem_pending;
220 *(q->prev = &sma->sem_pending) = q;
222 q->next->prev = &q->next;
223 else /* sma->sem_pending_last == &sma->sem_pending */
224 sma->sem_pending_last = &q->next;
227 static inline void remove_from_queue (struct sem_array * sma,
228 struct sem_queue * q)
230 *(q->prev) = q->next;
232 q->next->prev = q->prev;
233 else /* sma->sem_pending_last == &q->next */
234 sma->sem_pending_last = q->prev;
235 q->prev = NULL; /* mark as removed */
239 * Determine whether a sequence of semaphore operations would succeed
240 * all at once. Return 0 if yes, 1 if need to sleep, else return error code.
243 static int try_atomic_semop (struct sem_array * sma, struct sembuf * sops,
244 int nsops, struct sem_undo *un, int pid,
251 for (sop = sops; sop < sops + nsops; sop++) {
252 curr = sma->sem_base + sop->sem_num;
253 sem_op = sop->sem_op;
255 if (!sem_op && curr->semval)
258 curr->sempid = (curr->sempid << 16) | pid;
259 curr->semval += sem_op;
260 if (sop->sem_flg & SEM_UNDO)
262 int undo = un->semadj[sop->sem_num] - sem_op;
264 * Exceeding the undo range is an error.
266 if (undo < (-SEMAEM - 1) || undo > SEMAEM)
268 /* Don't undo the undo */
269 sop->sem_flg &= ~SEM_UNDO;
272 un->semadj[sop->sem_num] = undo;
274 if (curr->semval < 0)
276 if (curr->semval > SEMVMX)
287 sma->sem_otime = CURRENT_TIME;
295 if (sop->sem_flg & IPC_NOWAIT)
301 while (sop >= sops) {
302 curr = sma->sem_base + sop->sem_num;
303 curr->semval -= sop->sem_op;
306 if (sop->sem_flg & SEM_UNDO)
307 un->semadj[sop->sem_num] += sop->sem_op;
314 /* Go through the pending queue for the indicated semaphore
315 * looking for tasks that can be completed.
317 static void update_queue (struct sem_array * sma)
320 struct sem_queue * q;
322 for (q = sma->sem_pending; q; q = q->next) {
325 continue; /* this one was woken up before */
327 error = try_atomic_semop(sma, q->sops, q->nsops,
328 q->undo, q->pid, q->alter);
330 /* Does q->sleeper still need to sleep? */
332 /* Found one, wake it up */
333 wake_up_process(q->sleeper);
334 if (error == 0 && q->alter) {
335 /* if q-> alter let it self try */
340 remove_from_queue(sma,q);
345 /* The following counts are associated to each semaphore:
346 * semncnt number of tasks waiting on semval being nonzero
347 * semzcnt number of tasks waiting on semval being zero
348 * This model assumes that a task waits on exactly one semaphore.
349 * Since semaphore operations are to be performed atomically, tasks actually
350 * wait on a whole sequence of semaphores simultaneously.
351 * The counts we return here are a rough approximation, but still
352 * warrant that semncnt+semzcnt>0 if the task is on the pending queue.
354 static int count_semncnt (struct sem_array * sma, ushort semnum)
357 struct sem_queue * q;
360 for (q = sma->sem_pending; q; q = q->next) {
361 struct sembuf * sops = q->sops;
362 int nsops = q->nsops;
364 for (i = 0; i < nsops; i++)
365 if (sops[i].sem_num == semnum
366 && (sops[i].sem_op < 0)
367 && !(sops[i].sem_flg & IPC_NOWAIT))
372 static int count_semzcnt (struct sem_array * sma, ushort semnum)
375 struct sem_queue * q;
378 for (q = sma->sem_pending; q; q = q->next) {
379 struct sembuf * sops = q->sops;
380 int nsops = q->nsops;
382 for (i = 0; i < nsops; i++)
383 if (sops[i].sem_num == semnum
384 && (sops[i].sem_op == 0)
385 && !(sops[i].sem_flg & IPC_NOWAIT))
391 /* Free a semaphore set. */
392 static void freeary (int id)
394 struct sem_array *sma;
401 /* Invalidate the existing undo structures for this semaphore set.
402 * (They will be freed without any further action in sem_exit()
403 * or during the next semop.)
405 for (un = sma->undo; un; un = un->id_next)
408 /* Wake up all pending processes and let them fail with EIDRM. */
409 for (q = sma->sem_pending; q; q = q->next) {
412 wake_up_process(q->sleeper); /* doesn't sleep */
416 used_sems -= sma->sem_nsems;
417 size = sizeof (*sma) + sma->sem_nsems * sizeof (struct sem);
421 static unsigned long copy_semid_to_user(void *buf, struct semid64_ds *in, int version)
425 return copy_to_user(buf, in, sizeof(*in));
430 ipc64_perm_to_ipc_perm(&in->sem_perm, &out.sem_perm);
432 out.sem_otime = in->sem_otime;
433 out.sem_ctime = in->sem_ctime;
434 out.sem_nsems = in->sem_nsems;
436 return copy_to_user(buf, &out, sizeof(out));
443 static int semctl_nolock(int semid, int semnum, int cmd, int version, union semun arg)
451 struct seminfo seminfo;
454 memset(&seminfo,0,sizeof(seminfo));
455 seminfo.semmni = sc_semmni;
456 seminfo.semmns = sc_semmns;
457 seminfo.semmsl = sc_semmsl;
458 seminfo.semopm = sc_semopm;
459 seminfo.semvmx = SEMVMX;
460 seminfo.semmnu = SEMMNU;
461 seminfo.semmap = SEMMAP;
462 seminfo.semume = SEMUME;
464 if (cmd == SEM_INFO) {
465 seminfo.semusz = sem_ids.in_use;
466 seminfo.semaem = used_sems;
468 seminfo.semusz = SEMUSZ;
469 seminfo.semaem = SEMAEM;
471 max_id = sem_ids.max_id;
473 if (copy_to_user (arg.__buf, &seminfo, sizeof(struct seminfo)))
475 return (max_id < 0) ? 0: max_id;
479 struct sem_array *sma;
480 struct semid64_ds tbuf;
483 if(semid >= sem_ids.size)
486 memset(&tbuf,0,sizeof(tbuf));
488 sma = sem_lock(semid);
493 if (ipcperms (&sma->sem_perm, S_IRUGO))
495 id = sem_buildid(semid, sma->sem_perm.seq);
497 kernel_to_ipc64_perm(&sma->sem_perm, &tbuf.sem_perm);
498 tbuf.sem_otime = sma->sem_otime;
499 tbuf.sem_ctime = sma->sem_ctime;
500 tbuf.sem_nsems = sma->sem_nsems;
502 if (copy_semid_to_user (arg.buf, &tbuf, version))
515 static int semctl_main(int semid, int semnum, int cmd, int version, union semun arg)
517 struct sem_array *sma;
520 ushort fast_sem_io[SEMMSL_FAST];
521 ushort* sem_io = fast_sem_io;
524 sma = sem_lock(semid);
528 nsems = sma->sem_nsems;
531 if (sem_checkid(sma,semid))
535 if (ipcperms (&sma->sem_perm, (cmd==SETVAL||cmd==SETALL)?S_IWUGO:S_IRUGO))
541 ushort *array = arg.array;
544 if(nsems > SEMMSL_FAST) {
546 sem_io = ipc_alloc(sizeof(ushort)*nsems);
549 err = sem_revalidate(semid, sma, nsems, S_IRUGO);
554 for (i = 0; i < sma->sem_nsems; i++)
555 sem_io[i] = sma->sem_base[i].semval;
558 if(copy_to_user(array, sem_io, nsems*sizeof(ushort)))
569 if(nsems > SEMMSL_FAST) {
570 sem_io = ipc_alloc(sizeof(ushort)*nsems);
575 if (copy_from_user (sem_io, arg.array, nsems*sizeof(ushort))) {
580 for (i = 0; i < nsems; i++) {
581 if (sem_io[i] > SEMVMX) {
586 err = sem_revalidate(semid, sma, nsems, S_IWUGO);
590 for (i = 0; i < nsems; i++)
591 sma->sem_base[i].semval = sem_io[i];
592 for (un = sma->undo; un; un = un->id_next)
593 for (i = 0; i < nsems; i++)
595 sma->sem_ctime = CURRENT_TIME;
596 /* maybe some queued-up processes were waiting for this */
603 struct semid64_ds tbuf;
604 memset(&tbuf,0,sizeof(tbuf));
605 kernel_to_ipc64_perm(&sma->sem_perm, &tbuf.sem_perm);
606 tbuf.sem_otime = sma->sem_otime;
607 tbuf.sem_ctime = sma->sem_ctime;
608 tbuf.sem_nsems = sma->sem_nsems;
610 if (copy_semid_to_user (arg.buf, &tbuf, version))
614 /* GETVAL, GETPID, GETNCTN, GETZCNT, SETVAL: fall-through */
617 if(semnum < 0 || semnum >= nsems)
620 curr = &sma->sem_base[semnum];
627 err = curr->sempid & 0xffff;
630 err = count_semncnt(sma,semnum);
633 err = count_semzcnt(sma,semnum);
640 if (val > SEMVMX || val < 0)
643 for (un = sma->undo; un; un = un->id_next)
644 un->semadj[semnum] = 0;
646 curr->sempid = current->pid;
647 sma->sem_ctime = CURRENT_TIME;
648 /* maybe some queued-up processes were waiting for this */
657 if(sem_io != fast_sem_io)
658 ipc_free(sem_io, sizeof(ushort)*nsems);
668 static inline unsigned long copy_semid_from_user(struct sem_setbuf *out, void *buf, int version)
673 struct semid64_ds tbuf;
675 if(copy_from_user(&tbuf, buf, sizeof(tbuf)))
678 out->uid = tbuf.sem_perm.uid;
679 out->gid = tbuf.sem_perm.gid;
680 out->mode = tbuf.sem_perm.mode;
686 struct semid_ds tbuf_old;
688 if(copy_from_user(&tbuf_old, buf, sizeof(tbuf_old)))
691 out->uid = tbuf_old.sem_perm.uid;
692 out->gid = tbuf_old.sem_perm.gid;
693 out->mode = tbuf_old.sem_perm.mode;
702 static int semctl_down(int semid, int semnum, int cmd, int version, union semun arg)
704 struct sem_array *sma;
706 struct sem_setbuf setbuf;
707 struct kern_ipc_perm *ipcp;
710 if(copy_semid_from_user (&setbuf, arg.buf, version))
713 sma = sem_lock(semid);
717 if (sem_checkid(sma,semid)) {
721 ipcp = &sma->sem_perm;
723 if (current->euid != ipcp->cuid &&
724 current->euid != ipcp->uid && !capable(CAP_SYS_ADMIN)) {
735 ipcp->uid = setbuf.uid;
736 ipcp->gid = setbuf.gid;
737 ipcp->mode = (ipcp->mode & ~S_IRWXUGO)
738 | (setbuf.mode & S_IRWXUGO);
739 sma->sem_ctime = CURRENT_TIME;
755 asmlinkage long sys_semctl (int semid, int semnum, int cmd, union semun arg)
763 version = ipc_parse_version(&cmd);
769 err = semctl_nolock(semid,semnum,cmd,version,arg);
779 err = semctl_main(semid,semnum,cmd,version,arg);
784 err = semctl_down(semid,semnum,cmd,version,arg);
792 static struct sem_undo* freeundos(struct sem_array *sma, struct sem_undo* un)
795 struct sem_undo** up;
797 for(up = ¤t->semundo;(u=*up);up=&u->proc_next) {
805 printk ("freeundos undo list error id=%d\n", un->semid);
806 return un->proc_next;
809 /* returns without sem_lock on error! */
810 static int alloc_undo(struct sem_array *sma, struct sem_undo** unp, int semid, int alter)
812 int size, nsems, error;
815 nsems = sma->sem_nsems;
816 size = sizeof(struct sem_undo) + sizeof(short)*nsems;
819 un = (struct sem_undo *) kmalloc(size, GFP_KERNEL);
824 error = sem_revalidate(semid, sma, nsems, alter ? S_IWUGO : S_IRUGO);
830 un->semadj = (short *) &un[1];
832 un->proc_next = current->semundo;
833 current->semundo = un;
834 un->id_next = sma->undo;
840 asmlinkage long sys_semop (int semid, struct sembuf *tsops, unsigned nsops)
843 struct sem_array *sma;
844 struct sembuf fast_sops[SEMOPM_FAST];
845 struct sembuf* sops = fast_sops, *sop;
847 int undos = 0, decrease = 0, alter = 0;
848 struct sem_queue queue;
850 if (nsops < 1 || semid < 0)
852 if (nsops > sc_semopm)
854 if(nsops > SEMOPM_FAST) {
855 sops = kmalloc(sizeof(*sops)*nsops,GFP_KERNEL);
859 if (copy_from_user (sops, tsops, nsops * sizeof(*tsops))) {
863 sma = sem_lock(semid);
868 if (sem_checkid(sma,semid))
869 goto out_unlock_free;
871 for (sop = sops; sop < sops + nsops; sop++) {
872 if (sop->sem_num >= sma->sem_nsems)
873 goto out_unlock_free;
874 if (sop->sem_flg & SEM_UNDO)
884 if (ipcperms(&sma->sem_perm, alter ? S_IWUGO : S_IRUGO))
885 goto out_unlock_free;
887 /* Make sure we have an undo structure
888 * for this process and this semaphore set.
895 un=freeundos(sma,un);
900 error = alloc_undo(sma,&un,semid,alter);
907 error = try_atomic_semop (sma, sops, nsops, un, current->pid, 0);
911 /* We need to sleep on this operation, so we put the current
912 * task into the pending queue and go to sleep.
919 queue.pid = current->pid;
920 queue.alter = decrease;
923 append_to_queue(sma ,&queue);
925 prepend_to_queue(sma ,&queue);
926 current->semsleeping = &queue;
929 struct sem_array* tmp;
930 queue.status = -EINTR;
931 queue.sleeper = current;
932 current->state = TASK_INTERRUPTIBLE;
937 tmp = sem_lock(semid);
939 if(queue.prev != NULL)
941 current->semsleeping = NULL;
946 * If queue.status == 1 we where woken up and
947 * have to retry else we simply return.
948 * If an interrupt occurred we have to clean up the
952 if (queue.status == 1)
954 error = try_atomic_semop (sma, sops, nsops, un,
959 error = queue.status;
960 if (queue.prev) /* got Interrupt */
962 /* Everything done by update_queue */
963 current->semsleeping = NULL;
964 goto out_unlock_free;
967 current->semsleeping = NULL;
968 remove_from_queue(sma,&queue);
975 if(sops != fast_sops)
981 * add semadj values to semaphores, free undo structures.
982 * undo structures are not freed when semaphore arrays are destroyed
983 * so some of them may be out of date.
984 * IMPLEMENTATION NOTE: There is some confusion over whether the
985 * set of adjustments that needs to be done should be done in an atomic
986 * manner or not. That is, if we are attempting to decrement the semval
987 * should we queue up and wait until we can do so legally?
988 * The original implementation attempted to do this (queue and wait).
989 * The current implementation does not do so. The POSIX standard
990 * and SVID should be consulted to determine what behavior is mandated.
995 struct sem_undo *u, *un = NULL, **up, **unp;
996 struct sem_array *sma;
999 /* If the current process was sleeping for a semaphore,
1000 * remove it from the queue.
1002 if ((q = current->semsleeping)) {
1004 sma = sem_lock(semid);
1005 current->semsleeping = NULL;
1010 remove_from_queue(q->sma,q);
1016 for (up = ¤t->semundo; (u = *up); *up = u->proc_next, kfree(u)) {
1017 int semid = u->semid;
1020 sma = sem_lock(semid);
1027 if (sem_checkid(sma,u->semid))
1030 /* remove u from the sma->undo list */
1031 for (unp = &sma->undo; (un = *unp); unp = &un->id_next) {
1035 printk ("sem_exit undo list error id=%d\n", u->semid);
1039 /* perform adjustments registered in u */
1040 nsems = sma->sem_nsems;
1041 for (i = 0; i < nsems; i++) {
1042 struct sem * sem = &sma->sem_base[i];
1043 sem->semval += u->semadj[i];
1044 if (sem->semval < 0)
1045 sem->semval = 0; /* shouldn't happen */
1046 sem->sempid = current->pid;
1048 sma->sem_otime = CURRENT_TIME;
1049 /* maybe some queued-up processes were waiting for this */
1054 current->semundo = NULL;
1057 #ifdef CONFIG_PROC_FS
1058 static int sysvipc_sem_read_proc(char *buffer, char **start, off_t offset, int length, int *eof, void *data)
1064 len += sprintf(buffer, " key semid perms nsems uid gid cuid cgid otime ctime\n");
1067 for(i = 0; i <= sem_ids.max_id; i++) {
1068 struct sem_array *sma;
1071 len += sprintf(buffer + len, "%10d %10d %4o %10lu %5u %5u %5u %5u %10lu %10lu\n",
1073 sem_buildid(i,sma->sem_perm.seq),
1089 if(pos > offset + length)
1096 *start = buffer + (offset - begin);
1097 len -= (offset - begin);