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 <linux/time.h>
66 #include <asm/uaccess.h>
70 #define sem_lock(id) ((struct sem_array*)ipc_lock(&sem_ids,id))
71 #define sem_unlock(id) ipc_unlock(&sem_ids,id)
72 #define sem_rmid(id) ((struct sem_array*)ipc_rmid(&sem_ids,id))
73 #define sem_checkid(sma, semid) \
74 ipc_checkid(&sem_ids,&sma->sem_perm,semid)
75 #define sem_buildid(id, seq) \
76 ipc_buildid(&sem_ids, id, seq)
77 static struct ipc_ids sem_ids;
79 static int newary (key_t, int, int);
80 static void freeary (int id);
82 static int sysvipc_sem_read_proc(char *buffer, char **start, off_t offset, int length, int *eof, void *data);
85 #define SEMMSL_FAST 256 /* 512 bytes on stack */
86 #define SEMOPM_FAST 64 /* ~ 372 bytes on stack */
89 * linked list protection:
91 * sem_array.sem_pending{,last},
92 * sem_array.sem_undo: sem_lock() for read/write
93 * sem_undo.proc_next: only "current" is allowed to read/write that field.
97 int sem_ctls[4] = {SEMMSL, SEMMNS, SEMOPM, SEMMNI};
98 #define sc_semmsl (sem_ctls[0])
99 #define sc_semmns (sem_ctls[1])
100 #define sc_semopm (sem_ctls[2])
101 #define sc_semmni (sem_ctls[3])
103 static int used_sems;
105 void __init sem_init (void)
108 ipc_init_ids(&sem_ids,sc_semmni);
110 #ifdef CONFIG_PROC_FS
111 create_proc_read_entry("sysvipc/sem", 0, 0, sysvipc_sem_read_proc, NULL);
115 static int newary (key_t key, int nsems, int semflg)
118 struct sem_array *sma;
123 if (used_sems + nsems > sc_semmns)
126 size = sizeof (*sma) + nsems * sizeof (struct sem);
127 sma = (struct sem_array *) ipc_alloc(size);
131 memset (sma, 0, size);
132 id = ipc_addid(&sem_ids, &sma->sem_perm, sc_semmni);
139 sma->sem_perm.mode = (semflg & S_IRWXUGO);
140 sma->sem_perm.key = key;
142 sma->sem_base = (struct sem *) &sma[1];
143 /* sma->sem_pending = NULL; */
144 sma->sem_pending_last = &sma->sem_pending;
145 /* sma->undo = NULL; */
146 sma->sem_nsems = nsems;
147 sma->sem_ctime = CURRENT_TIME;
150 return sem_buildid(id, sma->sem_perm.seq);
153 asmlinkage long sys_semget (key_t key, int nsems, int semflg)
155 int id, err = -EINVAL;
156 struct sem_array *sma;
158 if (nsems < 0 || nsems > sc_semmsl)
162 if (key == IPC_PRIVATE) {
163 err = newary(key, nsems, semflg);
164 } else if ((id = ipc_findkey(&sem_ids, key)) == -1) { /* key not used */
165 if (!(semflg & IPC_CREAT))
168 err = newary(key, nsems, semflg);
169 } else if (semflg & IPC_CREAT && semflg & IPC_EXCL) {
175 if (nsems > sma->sem_nsems)
177 else if (ipcperms(&sma->sem_perm, semflg))
180 err = sem_buildid(id, sma->sem_perm.seq);
188 /* doesn't acquire the sem_lock on error! */
189 static int sem_revalidate(int semid, struct sem_array* sma, int nsems, short flg)
191 struct sem_array* smanew;
193 smanew = sem_lock(semid);
196 if(smanew != sma || sem_checkid(sma,semid) || sma->sem_nsems != nsems) {
201 if (ipcperms(&sma->sem_perm, flg)) {
207 /* Manage the doubly linked list sma->sem_pending as a FIFO:
208 * insert new queue elements at the tail sma->sem_pending_last.
210 static inline void append_to_queue (struct sem_array * sma,
211 struct sem_queue * q)
213 *(q->prev = sma->sem_pending_last) = q;
214 *(sma->sem_pending_last = &q->next) = NULL;
217 static inline void prepend_to_queue (struct sem_array * sma,
218 struct sem_queue * q)
220 q->next = sma->sem_pending;
221 *(q->prev = &sma->sem_pending) = q;
223 q->next->prev = &q->next;
224 else /* sma->sem_pending_last == &sma->sem_pending */
225 sma->sem_pending_last = &q->next;
228 static inline void remove_from_queue (struct sem_array * sma,
229 struct sem_queue * q)
231 *(q->prev) = q->next;
233 q->next->prev = q->prev;
234 else /* sma->sem_pending_last == &q->next */
235 sma->sem_pending_last = q->prev;
236 q->prev = NULL; /* mark as removed */
240 * Determine whether a sequence of semaphore operations would succeed
241 * all at once. Return 0 if yes, 1 if need to sleep, else return error code.
244 static int try_atomic_semop (struct sem_array * sma, struct sembuf * sops,
245 int nsops, struct sem_undo *un, int pid,
252 for (sop = sops; sop < sops + nsops; sop++) {
253 curr = sma->sem_base + sop->sem_num;
254 sem_op = sop->sem_op;
255 result = curr->semval;
257 if (!sem_op && result)
265 if (sop->sem_flg & SEM_UNDO) {
266 int undo = un->semadj[sop->sem_num] - sem_op;
268 * Exceeding the undo range is an error.
270 if (undo < (-SEMAEM - 1) || undo > SEMAEM)
273 curr->semval = result;
281 while (sop >= sops) {
282 sma->sem_base[sop->sem_num].sempid = pid;
283 if (sop->sem_flg & SEM_UNDO)
284 un->semadj[sop->sem_num] -= sop->sem_op;
287 sma->sem_otime = CURRENT_TIME;
295 if (sop->sem_flg & IPC_NOWAIT)
302 while (sop >= sops) {
303 sma->sem_base[sop->sem_num].semval -= sop->sem_op;
310 /* Go through the pending queue for the indicated semaphore
311 * looking for tasks that can be completed.
313 static void update_queue (struct sem_array * sma)
316 struct sem_queue * q;
318 for (q = sma->sem_pending; q; q = q->next) {
321 continue; /* this one was woken up before */
323 error = try_atomic_semop(sma, q->sops, q->nsops,
324 q->undo, q->pid, q->alter);
326 /* Does q->sleeper still need to sleep? */
328 /* Found one, wake it up */
329 wake_up_process(q->sleeper);
330 if (error == 0 && q->alter) {
331 /* if q-> alter let it self try */
336 remove_from_queue(sma,q);
341 /* The following counts are associated to each semaphore:
342 * semncnt number of tasks waiting on semval being nonzero
343 * semzcnt number of tasks waiting on semval being zero
344 * This model assumes that a task waits on exactly one semaphore.
345 * Since semaphore operations are to be performed atomically, tasks actually
346 * wait on a whole sequence of semaphores simultaneously.
347 * The counts we return here are a rough approximation, but still
348 * warrant that semncnt+semzcnt>0 if the task is on the pending queue.
350 static int count_semncnt (struct sem_array * sma, ushort semnum)
353 struct sem_queue * q;
356 for (q = sma->sem_pending; q; q = q->next) {
357 struct sembuf * sops = q->sops;
358 int nsops = q->nsops;
360 for (i = 0; i < nsops; i++)
361 if (sops[i].sem_num == semnum
362 && (sops[i].sem_op < 0)
363 && !(sops[i].sem_flg & IPC_NOWAIT))
368 static int count_semzcnt (struct sem_array * sma, ushort semnum)
371 struct sem_queue * q;
374 for (q = sma->sem_pending; q; q = q->next) {
375 struct sembuf * sops = q->sops;
376 int nsops = q->nsops;
378 for (i = 0; i < nsops; i++)
379 if (sops[i].sem_num == semnum
380 && (sops[i].sem_op == 0)
381 && !(sops[i].sem_flg & IPC_NOWAIT))
387 /* Free a semaphore set. */
388 static void freeary (int id)
390 struct sem_array *sma;
397 /* Invalidate the existing undo structures for this semaphore set.
398 * (They will be freed without any further action in sem_exit()
399 * or during the next semop.)
401 for (un = sma->undo; un; un = un->id_next)
404 /* Wake up all pending processes and let them fail with EIDRM. */
405 for (q = sma->sem_pending; q; q = q->next) {
408 wake_up_process(q->sleeper); /* doesn't sleep */
412 used_sems -= sma->sem_nsems;
413 size = sizeof (*sma) + sma->sem_nsems * sizeof (struct sem);
417 static unsigned long copy_semid_to_user(void *buf, struct semid64_ds *in, int version)
421 return copy_to_user(buf, in, sizeof(*in));
426 ipc64_perm_to_ipc_perm(&in->sem_perm, &out.sem_perm);
428 out.sem_otime = in->sem_otime;
429 out.sem_ctime = in->sem_ctime;
430 out.sem_nsems = in->sem_nsems;
432 return copy_to_user(buf, &out, sizeof(out));
439 static int semctl_nolock(int semid, int semnum, int cmd, int version, union semun arg)
447 struct seminfo seminfo;
450 memset(&seminfo,0,sizeof(seminfo));
451 seminfo.semmni = sc_semmni;
452 seminfo.semmns = sc_semmns;
453 seminfo.semmsl = sc_semmsl;
454 seminfo.semopm = sc_semopm;
455 seminfo.semvmx = SEMVMX;
456 seminfo.semmnu = SEMMNU;
457 seminfo.semmap = SEMMAP;
458 seminfo.semume = SEMUME;
460 if (cmd == SEM_INFO) {
461 seminfo.semusz = sem_ids.in_use;
462 seminfo.semaem = used_sems;
464 seminfo.semusz = SEMUSZ;
465 seminfo.semaem = SEMAEM;
467 max_id = sem_ids.max_id;
469 if (copy_to_user (arg.__buf, &seminfo, sizeof(struct seminfo)))
471 return (max_id < 0) ? 0: max_id;
475 struct sem_array *sma;
476 struct semid64_ds tbuf;
479 if(semid >= sem_ids.size)
482 memset(&tbuf,0,sizeof(tbuf));
484 sma = sem_lock(semid);
489 if (ipcperms (&sma->sem_perm, S_IRUGO))
491 id = sem_buildid(semid, sma->sem_perm.seq);
493 kernel_to_ipc64_perm(&sma->sem_perm, &tbuf.sem_perm);
494 tbuf.sem_otime = sma->sem_otime;
495 tbuf.sem_ctime = sma->sem_ctime;
496 tbuf.sem_nsems = sma->sem_nsems;
498 if (copy_semid_to_user (arg.buf, &tbuf, version))
511 static int semctl_main(int semid, int semnum, int cmd, int version, union semun arg)
513 struct sem_array *sma;
516 ushort fast_sem_io[SEMMSL_FAST];
517 ushort* sem_io = fast_sem_io;
520 sma = sem_lock(semid);
524 nsems = sma->sem_nsems;
527 if (sem_checkid(sma,semid))
531 if (ipcperms (&sma->sem_perm, (cmd==SETVAL||cmd==SETALL)?S_IWUGO:S_IRUGO))
537 ushort *array = arg.array;
540 if(nsems > SEMMSL_FAST) {
542 sem_io = ipc_alloc(sizeof(ushort)*nsems);
545 err = sem_revalidate(semid, sma, nsems, S_IRUGO);
550 for (i = 0; i < sma->sem_nsems; i++)
551 sem_io[i] = sma->sem_base[i].semval;
554 if(copy_to_user(array, sem_io, nsems*sizeof(ushort)))
565 if(nsems > SEMMSL_FAST) {
566 sem_io = ipc_alloc(sizeof(ushort)*nsems);
571 if (copy_from_user (sem_io, arg.array, nsems*sizeof(ushort))) {
576 for (i = 0; i < nsems; i++) {
577 if (sem_io[i] > SEMVMX) {
582 err = sem_revalidate(semid, sma, nsems, S_IWUGO);
586 for (i = 0; i < nsems; i++)
587 sma->sem_base[i].semval = sem_io[i];
588 for (un = sma->undo; un; un = un->id_next)
589 for (i = 0; i < nsems; i++)
591 sma->sem_ctime = CURRENT_TIME;
592 /* maybe some queued-up processes were waiting for this */
599 struct semid64_ds tbuf;
600 memset(&tbuf,0,sizeof(tbuf));
601 kernel_to_ipc64_perm(&sma->sem_perm, &tbuf.sem_perm);
602 tbuf.sem_otime = sma->sem_otime;
603 tbuf.sem_ctime = sma->sem_ctime;
604 tbuf.sem_nsems = sma->sem_nsems;
606 if (copy_semid_to_user (arg.buf, &tbuf, version))
610 /* GETVAL, GETPID, GETNCTN, GETZCNT, SETVAL: fall-through */
613 if(semnum < 0 || semnum >= nsems)
616 curr = &sma->sem_base[semnum];
626 err = count_semncnt(sma,semnum);
629 err = count_semzcnt(sma,semnum);
636 if (val > SEMVMX || val < 0)
639 for (un = sma->undo; un; un = un->id_next)
640 un->semadj[semnum] = 0;
642 curr->sempid = current->pid;
643 sma->sem_ctime = CURRENT_TIME;
644 /* maybe some queued-up processes were waiting for this */
653 if(sem_io != fast_sem_io)
654 ipc_free(sem_io, sizeof(ushort)*nsems);
664 static inline unsigned long copy_semid_from_user(struct sem_setbuf *out, void *buf, int version)
669 struct semid64_ds tbuf;
671 if(copy_from_user(&tbuf, buf, sizeof(tbuf)))
674 out->uid = tbuf.sem_perm.uid;
675 out->gid = tbuf.sem_perm.gid;
676 out->mode = tbuf.sem_perm.mode;
682 struct semid_ds tbuf_old;
684 if(copy_from_user(&tbuf_old, buf, sizeof(tbuf_old)))
687 out->uid = tbuf_old.sem_perm.uid;
688 out->gid = tbuf_old.sem_perm.gid;
689 out->mode = tbuf_old.sem_perm.mode;
698 static int semctl_down(int semid, int semnum, int cmd, int version, union semun arg)
700 struct sem_array *sma;
702 struct sem_setbuf setbuf;
703 struct kern_ipc_perm *ipcp;
706 if(copy_semid_from_user (&setbuf, arg.buf, version))
709 sma = sem_lock(semid);
713 if (sem_checkid(sma,semid)) {
717 ipcp = &sma->sem_perm;
719 if (current->euid != ipcp->cuid &&
720 current->euid != ipcp->uid && !capable(CAP_SYS_ADMIN)) {
731 ipcp->uid = setbuf.uid;
732 ipcp->gid = setbuf.gid;
733 ipcp->mode = (ipcp->mode & ~S_IRWXUGO)
734 | (setbuf.mode & S_IRWXUGO);
735 sma->sem_ctime = CURRENT_TIME;
751 asmlinkage long sys_semctl (int semid, int semnum, int cmd, union semun arg)
759 version = ipc_parse_version(&cmd);
765 err = semctl_nolock(semid,semnum,cmd,version,arg);
775 err = semctl_main(semid,semnum,cmd,version,arg);
780 err = semctl_down(semid,semnum,cmd,version,arg);
788 static struct sem_undo* freeundos(struct sem_array *sma, struct sem_undo* un)
791 struct sem_undo** up;
793 for(up = ¤t->semundo;(u=*up);up=&u->proc_next) {
801 printk ("freeundos undo list error id=%d\n", un->semid);
802 return un->proc_next;
805 /* returns without sem_lock on error! */
806 static int alloc_undo(struct sem_array *sma, struct sem_undo** unp, int semid, int alter)
808 int size, nsems, error;
811 nsems = sma->sem_nsems;
812 size = sizeof(struct sem_undo) + sizeof(short)*nsems;
815 un = (struct sem_undo *) kmalloc(size, GFP_KERNEL);
820 error = sem_revalidate(semid, sma, nsems, alter ? S_IWUGO : S_IRUGO);
826 un->semadj = (short *) &un[1];
828 un->proc_next = current->semundo;
829 current->semundo = un;
830 un->id_next = sma->undo;
836 asmlinkage long sys_semop (int semid, struct sembuf *tsops, unsigned nsops)
838 return sys_semtimedop(semid, tsops, nsops, NULL);
841 asmlinkage long sys_semtimedop (int semid, struct sembuf *tsops,
842 unsigned nsops, const struct timespec *timeout)
845 struct sem_array *sma;
846 struct sembuf fast_sops[SEMOPM_FAST];
847 struct sembuf* sops = fast_sops, *sop;
849 int undos = 0, decrease = 0, alter = 0;
850 struct sem_queue queue;
851 unsigned long jiffies_left = 0;
853 if (nsops < 1 || semid < 0)
855 if (nsops > sc_semopm)
857 if(nsops > SEMOPM_FAST) {
858 sops = kmalloc(sizeof(*sops)*nsops,GFP_KERNEL);
862 if (copy_from_user (sops, tsops, nsops * sizeof(*tsops))) {
867 struct timespec _timeout;
868 if (copy_from_user(&_timeout, timeout, sizeof(*timeout))) {
872 if (_timeout.tv_sec < 0 || _timeout.tv_nsec < 0 ||
873 _timeout.tv_nsec >= 1000000000L) {
877 jiffies_left = timespec_to_jiffies(&_timeout);
879 sma = sem_lock(semid);
884 if (sem_checkid(sma,semid))
885 goto out_unlock_free;
887 for (sop = sops; sop < sops + nsops; sop++) {
888 if (sop->sem_num >= sma->sem_nsems)
889 goto out_unlock_free;
890 if (sop->sem_flg & SEM_UNDO)
900 if (ipcperms(&sma->sem_perm, alter ? S_IWUGO : S_IRUGO))
901 goto out_unlock_free;
903 /* Make sure we have an undo structure
904 * for this process and this semaphore set.
911 un=freeundos(sma,un);
916 error = alloc_undo(sma,&un,semid,alter);
923 error = try_atomic_semop (sma, sops, nsops, un, current->pid, 0);
927 /* We need to sleep on this operation, so we put the current
928 * task into the pending queue and go to sleep.
935 queue.pid = current->pid;
936 queue.alter = decrease;
939 append_to_queue(sma ,&queue);
941 prepend_to_queue(sma ,&queue);
942 current->semsleeping = &queue;
945 struct sem_array* tmp;
946 queue.status = -EINTR;
947 queue.sleeper = current;
948 current->state = TASK_INTERRUPTIBLE;
952 jiffies_left = schedule_timeout(jiffies_left);
956 tmp = sem_lock(semid);
958 if(queue.prev != NULL)
960 current->semsleeping = NULL;
965 * If queue.status == 1 we where woken up and
966 * have to retry else we simply return.
967 * If an interrupt occurred we have to clean up the
971 if (queue.status == 1)
973 error = try_atomic_semop (sma, sops, nsops, un,
978 error = queue.status;
979 if (error == -EINTR && timeout && jiffies_left == 0)
981 if (queue.prev) /* got Interrupt */
983 /* Everything done by update_queue */
984 current->semsleeping = NULL;
985 goto out_unlock_free;
988 current->semsleeping = NULL;
989 remove_from_queue(sma,&queue);
996 if(sops != fast_sops)
1002 * add semadj values to semaphores, free undo structures.
1003 * undo structures are not freed when semaphore arrays are destroyed
1004 * so some of them may be out of date.
1005 * IMPLEMENTATION NOTE: There is some confusion over whether the
1006 * set of adjustments that needs to be done should be done in an atomic
1007 * manner or not. That is, if we are attempting to decrement the semval
1008 * should we queue up and wait until we can do so legally?
1009 * The original implementation attempted to do this (queue and wait).
1010 * The current implementation does not do so. The POSIX standard
1011 * and SVID should be consulted to determine what behavior is mandated.
1013 void sem_exit (void)
1015 struct sem_queue *q;
1016 struct sem_undo *u, *un = NULL, **up, **unp;
1017 struct sem_array *sma;
1020 /* If the current process was sleeping for a semaphore,
1021 * remove it from the queue.
1023 if ((q = current->semsleeping)) {
1025 sma = sem_lock(semid);
1026 current->semsleeping = NULL;
1031 remove_from_queue(q->sma,q);
1037 for (up = ¤t->semundo; (u = *up); *up = u->proc_next, kfree(u)) {
1038 int semid = u->semid;
1041 sma = sem_lock(semid);
1048 if (sem_checkid(sma,u->semid))
1051 /* remove u from the sma->undo list */
1052 for (unp = &sma->undo; (un = *unp); unp = &un->id_next) {
1056 printk ("sem_exit undo list error id=%d\n", u->semid);
1060 /* perform adjustments registered in u */
1061 nsems = sma->sem_nsems;
1062 for (i = 0; i < nsems; i++) {
1063 struct sem * sem = &sma->sem_base[i];
1064 sem->semval += u->semadj[i];
1065 if (sem->semval < 0)
1066 sem->semval = 0; /* shouldn't happen */
1067 sem->sempid = current->pid;
1069 sma->sem_otime = CURRENT_TIME;
1070 /* maybe some queued-up processes were waiting for this */
1075 current->semundo = NULL;
1078 #ifdef CONFIG_PROC_FS
1079 static int sysvipc_sem_read_proc(char *buffer, char **start, off_t offset, int length, int *eof, void *data)
1085 len += sprintf(buffer, " key semid perms nsems uid gid cuid cgid otime ctime\n");
1088 for(i = 0; i <= sem_ids.max_id; i++) {
1089 struct sem_array *sma;
1092 len += sprintf(buffer + len, "%10d %10d %4o %10lu %5u %5u %5u %5u %10lu %10lu\n",
1094 sem_buildid(i,sma->sem_perm.seq),
1110 if(pos > offset + length)
1117 *start = buffer + (offset - begin);
1118 len -= (offset - begin);