xref: /linux/ipc/sem.c (revision de2fe5e07d58424bc286fff3fd3c1b0bf933cd58)
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 <linux/mutex.h>
79 
80 #include <asm/uaccess.h>
81 #include "util.h"
82 
83 
84 #define sem_lock(id)	((struct sem_array*)ipc_lock(&sem_ids,id))
85 #define sem_unlock(sma)	ipc_unlock(&(sma)->sem_perm)
86 #define sem_rmid(id)	((struct sem_array*)ipc_rmid(&sem_ids,id))
87 #define sem_checkid(sma, semid)	\
88 	ipc_checkid(&sem_ids,&sma->sem_perm,semid)
89 #define sem_buildid(id, seq) \
90 	ipc_buildid(&sem_ids, id, seq)
91 static struct ipc_ids sem_ids;
92 
93 static int newary (key_t, int, int);
94 static void freeary (struct sem_array *sma, int id);
95 #ifdef CONFIG_PROC_FS
96 static int sysvipc_sem_proc_show(struct seq_file *s, void *it);
97 #endif
98 
99 #define SEMMSL_FAST	256 /* 512 bytes on stack */
100 #define SEMOPM_FAST	64  /* ~ 372 bytes on stack */
101 
102 /*
103  * linked list protection:
104  *	sem_undo.id_next,
105  *	sem_array.sem_pending{,last},
106  *	sem_array.sem_undo: sem_lock() for read/write
107  *	sem_undo.proc_next: only "current" is allowed to read/write that field.
108  *
109  */
110 
111 int sem_ctls[4] = {SEMMSL, SEMMNS, SEMOPM, SEMMNI};
112 #define sc_semmsl	(sem_ctls[0])
113 #define sc_semmns	(sem_ctls[1])
114 #define sc_semopm	(sem_ctls[2])
115 #define sc_semmni	(sem_ctls[3])
116 
117 static int used_sems;
118 
119 void __init sem_init (void)
120 {
121 	used_sems = 0;
122 	ipc_init_ids(&sem_ids,sc_semmni);
123 	ipc_init_proc_interface("sysvipc/sem",
124 				"       key      semid perms      nsems   uid   gid  cuid  cgid      otime      ctime\n",
125 				&sem_ids,
126 				sysvipc_sem_proc_show);
127 }
128 
129 /*
130  * Lockless wakeup algorithm:
131  * Without the check/retry algorithm a lockless wakeup is possible:
132  * - queue.status is initialized to -EINTR before blocking.
133  * - wakeup is performed by
134  *	* unlinking the queue entry from sma->sem_pending
135  *	* setting queue.status to IN_WAKEUP
136  *	  This is the notification for the blocked thread that a
137  *	  result value is imminent.
138  *	* call wake_up_process
139  *	* set queue.status to the final value.
140  * - the previously blocked thread checks queue.status:
141  *   	* if it's IN_WAKEUP, then it must wait until the value changes
142  *   	* if it's not -EINTR, then the operation was completed by
143  *   	  update_queue. semtimedop can return queue.status without
144  *   	  performing any operation on the sem array.
145  *   	* otherwise it must acquire the spinlock and check what's up.
146  *
147  * The two-stage algorithm is necessary to protect against the following
148  * races:
149  * - if queue.status is set after wake_up_process, then the woken up idle
150  *   thread could race forward and try (and fail) to acquire sma->lock
151  *   before update_queue had a chance to set queue.status
152  * - if queue.status is written before wake_up_process and if the
153  *   blocked process is woken up by a signal between writing
154  *   queue.status and the wake_up_process, then the woken up
155  *   process could return from semtimedop and die by calling
156  *   sys_exit before wake_up_process is called. Then wake_up_process
157  *   will oops, because the task structure is already invalid.
158  *   (yes, this happened on s390 with sysv msg).
159  *
160  */
161 #define IN_WAKEUP	1
162 
163 static int newary (key_t key, int nsems, int semflg)
164 {
165 	int id;
166 	int retval;
167 	struct sem_array *sma;
168 	int size;
169 
170 	if (!nsems)
171 		return -EINVAL;
172 	if (used_sems + nsems > sc_semmns)
173 		return -ENOSPC;
174 
175 	size = sizeof (*sma) + nsems * sizeof (struct sem);
176 	sma = ipc_rcu_alloc(size);
177 	if (!sma) {
178 		return -ENOMEM;
179 	}
180 	memset (sma, 0, size);
181 
182 	sma->sem_perm.mode = (semflg & S_IRWXUGO);
183 	sma->sem_perm.key = key;
184 
185 	sma->sem_perm.security = NULL;
186 	retval = security_sem_alloc(sma);
187 	if (retval) {
188 		ipc_rcu_putref(sma);
189 		return retval;
190 	}
191 
192 	id = ipc_addid(&sem_ids, &sma->sem_perm, sc_semmni);
193 	if(id == -1) {
194 		security_sem_free(sma);
195 		ipc_rcu_putref(sma);
196 		return -ENOSPC;
197 	}
198 	used_sems += nsems;
199 
200 	sma->sem_id = sem_buildid(id, sma->sem_perm.seq);
201 	sma->sem_base = (struct sem *) &sma[1];
202 	/* sma->sem_pending = NULL; */
203 	sma->sem_pending_last = &sma->sem_pending;
204 	/* sma->undo = NULL; */
205 	sma->sem_nsems = nsems;
206 	sma->sem_ctime = get_seconds();
207 	sem_unlock(sma);
208 
209 	return sma->sem_id;
210 }
211 
212 asmlinkage long sys_semget (key_t key, int nsems, int semflg)
213 {
214 	int id, err = -EINVAL;
215 	struct sem_array *sma;
216 
217 	if (nsems < 0 || nsems > sc_semmsl)
218 		return -EINVAL;
219 	mutex_lock(&sem_ids.mutex);
220 
221 	if (key == IPC_PRIVATE) {
222 		err = newary(key, nsems, semflg);
223 	} else if ((id = ipc_findkey(&sem_ids, key)) == -1) {  /* key not used */
224 		if (!(semflg & IPC_CREAT))
225 			err = -ENOENT;
226 		else
227 			err = newary(key, nsems, semflg);
228 	} else if (semflg & IPC_CREAT && semflg & IPC_EXCL) {
229 		err = -EEXIST;
230 	} else {
231 		sma = sem_lock(id);
232 		BUG_ON(sma==NULL);
233 		if (nsems > sma->sem_nsems)
234 			err = -EINVAL;
235 		else if (ipcperms(&sma->sem_perm, semflg))
236 			err = -EACCES;
237 		else {
238 			int semid = sem_buildid(id, sma->sem_perm.seq);
239 			err = security_sem_associate(sma, semflg);
240 			if (!err)
241 				err = semid;
242 		}
243 		sem_unlock(sma);
244 	}
245 
246 	mutex_unlock(&sem_ids.mutex);
247 	return err;
248 }
249 
250 /* Manage the doubly linked list sma->sem_pending as a FIFO:
251  * insert new queue elements at the tail sma->sem_pending_last.
252  */
253 static inline void append_to_queue (struct sem_array * sma,
254 				    struct sem_queue * q)
255 {
256 	*(q->prev = sma->sem_pending_last) = q;
257 	*(sma->sem_pending_last = &q->next) = NULL;
258 }
259 
260 static inline void prepend_to_queue (struct sem_array * sma,
261 				     struct sem_queue * q)
262 {
263 	q->next = sma->sem_pending;
264 	*(q->prev = &sma->sem_pending) = q;
265 	if (q->next)
266 		q->next->prev = &q->next;
267 	else /* sma->sem_pending_last == &sma->sem_pending */
268 		sma->sem_pending_last = &q->next;
269 }
270 
271 static inline void remove_from_queue (struct sem_array * sma,
272 				      struct sem_queue * q)
273 {
274 	*(q->prev) = q->next;
275 	if (q->next)
276 		q->next->prev = q->prev;
277 	else /* sma->sem_pending_last == &q->next */
278 		sma->sem_pending_last = q->prev;
279 	q->prev = NULL; /* mark as removed */
280 }
281 
282 /*
283  * Determine whether a sequence of semaphore operations would succeed
284  * all at once. Return 0 if yes, 1 if need to sleep, else return error code.
285  */
286 
287 static int try_atomic_semop (struct sem_array * sma, struct sembuf * sops,
288 			     int nsops, struct sem_undo *un, int pid)
289 {
290 	int result, sem_op;
291 	struct sembuf *sop;
292 	struct sem * curr;
293 
294 	for (sop = sops; sop < sops + nsops; sop++) {
295 		curr = sma->sem_base + sop->sem_num;
296 		sem_op = sop->sem_op;
297 		result = curr->semval;
298 
299 		if (!sem_op && result)
300 			goto would_block;
301 
302 		result += sem_op;
303 		if (result < 0)
304 			goto would_block;
305 		if (result > SEMVMX)
306 			goto out_of_range;
307 		if (sop->sem_flg & SEM_UNDO) {
308 			int undo = un->semadj[sop->sem_num] - sem_op;
309 			/*
310 	 		 *	Exceeding the undo range is an error.
311 			 */
312 			if (undo < (-SEMAEM - 1) || undo > SEMAEM)
313 				goto out_of_range;
314 		}
315 		curr->semval = result;
316 	}
317 
318 	sop--;
319 	while (sop >= sops) {
320 		sma->sem_base[sop->sem_num].sempid = pid;
321 		if (sop->sem_flg & SEM_UNDO)
322 			un->semadj[sop->sem_num] -= sop->sem_op;
323 		sop--;
324 	}
325 
326 	sma->sem_otime = get_seconds();
327 	return 0;
328 
329 out_of_range:
330 	result = -ERANGE;
331 	goto undo;
332 
333 would_block:
334 	if (sop->sem_flg & IPC_NOWAIT)
335 		result = -EAGAIN;
336 	else
337 		result = 1;
338 
339 undo:
340 	sop--;
341 	while (sop >= sops) {
342 		sma->sem_base[sop->sem_num].semval -= sop->sem_op;
343 		sop--;
344 	}
345 
346 	return result;
347 }
348 
349 /* Go through the pending queue for the indicated semaphore
350  * looking for tasks that can be completed.
351  */
352 static void update_queue (struct sem_array * sma)
353 {
354 	int error;
355 	struct sem_queue * q;
356 
357 	q = sma->sem_pending;
358 	while(q) {
359 		error = try_atomic_semop(sma, q->sops, q->nsops,
360 					 q->undo, q->pid);
361 
362 		/* Does q->sleeper still need to sleep? */
363 		if (error <= 0) {
364 			struct sem_queue *n;
365 			remove_from_queue(sma,q);
366 			q->status = IN_WAKEUP;
367 			/*
368 			 * Continue scanning. The next operation
369 			 * that must be checked depends on the type of the
370 			 * completed operation:
371 			 * - if the operation modified the array, then
372 			 *   restart from the head of the queue and
373 			 *   check for threads that might be waiting
374 			 *   for semaphore values to become 0.
375 			 * - if the operation didn't modify the array,
376 			 *   then just continue.
377 			 */
378 			if (q->alter)
379 				n = sma->sem_pending;
380 			else
381 				n = q->next;
382 			wake_up_process(q->sleeper);
383 			/* hands-off: q will disappear immediately after
384 			 * writing q->status.
385 			 */
386 			smp_wmb();
387 			q->status = error;
388 			q = n;
389 		} else {
390 			q = q->next;
391 		}
392 	}
393 }
394 
395 /* The following counts are associated to each semaphore:
396  *   semncnt        number of tasks waiting on semval being nonzero
397  *   semzcnt        number of tasks waiting on semval being zero
398  * This model assumes that a task waits on exactly one semaphore.
399  * Since semaphore operations are to be performed atomically, tasks actually
400  * wait on a whole sequence of semaphores simultaneously.
401  * The counts we return here are a rough approximation, but still
402  * warrant that semncnt+semzcnt>0 if the task is on the pending queue.
403  */
404 static int count_semncnt (struct sem_array * sma, ushort semnum)
405 {
406 	int semncnt;
407 	struct sem_queue * q;
408 
409 	semncnt = 0;
410 	for (q = sma->sem_pending; q; q = q->next) {
411 		struct sembuf * sops = q->sops;
412 		int nsops = q->nsops;
413 		int i;
414 		for (i = 0; i < nsops; i++)
415 			if (sops[i].sem_num == semnum
416 			    && (sops[i].sem_op < 0)
417 			    && !(sops[i].sem_flg & IPC_NOWAIT))
418 				semncnt++;
419 	}
420 	return semncnt;
421 }
422 static int count_semzcnt (struct sem_array * sma, ushort semnum)
423 {
424 	int semzcnt;
425 	struct sem_queue * q;
426 
427 	semzcnt = 0;
428 	for (q = sma->sem_pending; q; q = q->next) {
429 		struct sembuf * sops = q->sops;
430 		int nsops = q->nsops;
431 		int i;
432 		for (i = 0; i < nsops; i++)
433 			if (sops[i].sem_num == semnum
434 			    && (sops[i].sem_op == 0)
435 			    && !(sops[i].sem_flg & IPC_NOWAIT))
436 				semzcnt++;
437 	}
438 	return semzcnt;
439 }
440 
441 /* Free a semaphore set. freeary() is called with sem_ids.mutex locked and
442  * the spinlock for this semaphore set hold. sem_ids.mutex remains locked
443  * on exit.
444  */
445 static void freeary (struct sem_array *sma, int id)
446 {
447 	struct sem_undo *un;
448 	struct sem_queue *q;
449 	int size;
450 
451 	/* Invalidate the existing undo structures for this semaphore set.
452 	 * (They will be freed without any further action in exit_sem()
453 	 * or during the next semop.)
454 	 */
455 	for (un = sma->undo; un; un = un->id_next)
456 		un->semid = -1;
457 
458 	/* Wake up all pending processes and let them fail with EIDRM. */
459 	q = sma->sem_pending;
460 	while(q) {
461 		struct sem_queue *n;
462 		/* lazy remove_from_queue: we are killing the whole queue */
463 		q->prev = NULL;
464 		n = q->next;
465 		q->status = IN_WAKEUP;
466 		wake_up_process(q->sleeper); /* doesn't sleep */
467 		smp_wmb();
468 		q->status = -EIDRM;	/* hands-off q */
469 		q = n;
470 	}
471 
472 	/* Remove the semaphore set from the ID array*/
473 	sma = sem_rmid(id);
474 	sem_unlock(sma);
475 
476 	used_sems -= sma->sem_nsems;
477 	size = sizeof (*sma) + sma->sem_nsems * sizeof (struct sem);
478 	security_sem_free(sma);
479 	ipc_rcu_putref(sma);
480 }
481 
482 static unsigned long copy_semid_to_user(void __user *buf, struct semid64_ds *in, int version)
483 {
484 	switch(version) {
485 	case IPC_64:
486 		return copy_to_user(buf, in, sizeof(*in));
487 	case IPC_OLD:
488 	    {
489 		struct semid_ds out;
490 
491 		ipc64_perm_to_ipc_perm(&in->sem_perm, &out.sem_perm);
492 
493 		out.sem_otime	= in->sem_otime;
494 		out.sem_ctime	= in->sem_ctime;
495 		out.sem_nsems	= in->sem_nsems;
496 
497 		return copy_to_user(buf, &out, sizeof(out));
498 	    }
499 	default:
500 		return -EINVAL;
501 	}
502 }
503 
504 static int semctl_nolock(int semid, int semnum, int cmd, int version, union semun arg)
505 {
506 	int err = -EINVAL;
507 	struct sem_array *sma;
508 
509 	switch(cmd) {
510 	case IPC_INFO:
511 	case SEM_INFO:
512 	{
513 		struct seminfo seminfo;
514 		int max_id;
515 
516 		err = security_sem_semctl(NULL, cmd);
517 		if (err)
518 			return err;
519 
520 		memset(&seminfo,0,sizeof(seminfo));
521 		seminfo.semmni = sc_semmni;
522 		seminfo.semmns = sc_semmns;
523 		seminfo.semmsl = sc_semmsl;
524 		seminfo.semopm = sc_semopm;
525 		seminfo.semvmx = SEMVMX;
526 		seminfo.semmnu = SEMMNU;
527 		seminfo.semmap = SEMMAP;
528 		seminfo.semume = SEMUME;
529 		mutex_lock(&sem_ids.mutex);
530 		if (cmd == SEM_INFO) {
531 			seminfo.semusz = sem_ids.in_use;
532 			seminfo.semaem = used_sems;
533 		} else {
534 			seminfo.semusz = SEMUSZ;
535 			seminfo.semaem = SEMAEM;
536 		}
537 		max_id = sem_ids.max_id;
538 		mutex_unlock(&sem_ids.mutex);
539 		if (copy_to_user (arg.__buf, &seminfo, sizeof(struct seminfo)))
540 			return -EFAULT;
541 		return (max_id < 0) ? 0: max_id;
542 	}
543 	case SEM_STAT:
544 	{
545 		struct semid64_ds tbuf;
546 		int id;
547 
548 		if(semid >= sem_ids.entries->size)
549 			return -EINVAL;
550 
551 		memset(&tbuf,0,sizeof(tbuf));
552 
553 		sma = sem_lock(semid);
554 		if(sma == NULL)
555 			return -EINVAL;
556 
557 		err = -EACCES;
558 		if (ipcperms (&sma->sem_perm, S_IRUGO))
559 			goto out_unlock;
560 
561 		err = security_sem_semctl(sma, cmd);
562 		if (err)
563 			goto out_unlock;
564 
565 		id = sem_buildid(semid, sma->sem_perm.seq);
566 
567 		kernel_to_ipc64_perm(&sma->sem_perm, &tbuf.sem_perm);
568 		tbuf.sem_otime  = sma->sem_otime;
569 		tbuf.sem_ctime  = sma->sem_ctime;
570 		tbuf.sem_nsems  = sma->sem_nsems;
571 		sem_unlock(sma);
572 		if (copy_semid_to_user (arg.buf, &tbuf, version))
573 			return -EFAULT;
574 		return id;
575 	}
576 	default:
577 		return -EINVAL;
578 	}
579 	return err;
580 out_unlock:
581 	sem_unlock(sma);
582 	return err;
583 }
584 
585 static int semctl_main(int semid, int semnum, int cmd, int version, union semun arg)
586 {
587 	struct sem_array *sma;
588 	struct sem* curr;
589 	int err;
590 	ushort fast_sem_io[SEMMSL_FAST];
591 	ushort* sem_io = fast_sem_io;
592 	int nsems;
593 
594 	sma = sem_lock(semid);
595 	if(sma==NULL)
596 		return -EINVAL;
597 
598 	nsems = sma->sem_nsems;
599 
600 	err=-EIDRM;
601 	if (sem_checkid(sma,semid))
602 		goto out_unlock;
603 
604 	err = -EACCES;
605 	if (ipcperms (&sma->sem_perm, (cmd==SETVAL||cmd==SETALL)?S_IWUGO:S_IRUGO))
606 		goto out_unlock;
607 
608 	err = security_sem_semctl(sma, cmd);
609 	if (err)
610 		goto out_unlock;
611 
612 	err = -EACCES;
613 	switch (cmd) {
614 	case GETALL:
615 	{
616 		ushort __user *array = arg.array;
617 		int i;
618 
619 		if(nsems > SEMMSL_FAST) {
620 			ipc_rcu_getref(sma);
621 			sem_unlock(sma);
622 
623 			sem_io = ipc_alloc(sizeof(ushort)*nsems);
624 			if(sem_io == NULL) {
625 				ipc_lock_by_ptr(&sma->sem_perm);
626 				ipc_rcu_putref(sma);
627 				sem_unlock(sma);
628 				return -ENOMEM;
629 			}
630 
631 			ipc_lock_by_ptr(&sma->sem_perm);
632 			ipc_rcu_putref(sma);
633 			if (sma->sem_perm.deleted) {
634 				sem_unlock(sma);
635 				err = -EIDRM;
636 				goto out_free;
637 			}
638 		}
639 
640 		for (i = 0; i < sma->sem_nsems; i++)
641 			sem_io[i] = sma->sem_base[i].semval;
642 		sem_unlock(sma);
643 		err = 0;
644 		if(copy_to_user(array, sem_io, nsems*sizeof(ushort)))
645 			err = -EFAULT;
646 		goto out_free;
647 	}
648 	case SETALL:
649 	{
650 		int i;
651 		struct sem_undo *un;
652 
653 		ipc_rcu_getref(sma);
654 		sem_unlock(sma);
655 
656 		if(nsems > SEMMSL_FAST) {
657 			sem_io = ipc_alloc(sizeof(ushort)*nsems);
658 			if(sem_io == NULL) {
659 				ipc_lock_by_ptr(&sma->sem_perm);
660 				ipc_rcu_putref(sma);
661 				sem_unlock(sma);
662 				return -ENOMEM;
663 			}
664 		}
665 
666 		if (copy_from_user (sem_io, arg.array, nsems*sizeof(ushort))) {
667 			ipc_lock_by_ptr(&sma->sem_perm);
668 			ipc_rcu_putref(sma);
669 			sem_unlock(sma);
670 			err = -EFAULT;
671 			goto out_free;
672 		}
673 
674 		for (i = 0; i < nsems; i++) {
675 			if (sem_io[i] > SEMVMX) {
676 				ipc_lock_by_ptr(&sma->sem_perm);
677 				ipc_rcu_putref(sma);
678 				sem_unlock(sma);
679 				err = -ERANGE;
680 				goto out_free;
681 			}
682 		}
683 		ipc_lock_by_ptr(&sma->sem_perm);
684 		ipc_rcu_putref(sma);
685 		if (sma->sem_perm.deleted) {
686 			sem_unlock(sma);
687 			err = -EIDRM;
688 			goto out_free;
689 		}
690 
691 		for (i = 0; i < nsems; i++)
692 			sma->sem_base[i].semval = sem_io[i];
693 		for (un = sma->undo; un; un = un->id_next)
694 			for (i = 0; i < nsems; i++)
695 				un->semadj[i] = 0;
696 		sma->sem_ctime = get_seconds();
697 		/* maybe some queued-up processes were waiting for this */
698 		update_queue(sma);
699 		err = 0;
700 		goto out_unlock;
701 	}
702 	case IPC_STAT:
703 	{
704 		struct semid64_ds tbuf;
705 		memset(&tbuf,0,sizeof(tbuf));
706 		kernel_to_ipc64_perm(&sma->sem_perm, &tbuf.sem_perm);
707 		tbuf.sem_otime  = sma->sem_otime;
708 		tbuf.sem_ctime  = sma->sem_ctime;
709 		tbuf.sem_nsems  = sma->sem_nsems;
710 		sem_unlock(sma);
711 		if (copy_semid_to_user (arg.buf, &tbuf, version))
712 			return -EFAULT;
713 		return 0;
714 	}
715 	/* GETVAL, GETPID, GETNCTN, GETZCNT, SETVAL: fall-through */
716 	}
717 	err = -EINVAL;
718 	if(semnum < 0 || semnum >= nsems)
719 		goto out_unlock;
720 
721 	curr = &sma->sem_base[semnum];
722 
723 	switch (cmd) {
724 	case GETVAL:
725 		err = curr->semval;
726 		goto out_unlock;
727 	case GETPID:
728 		err = curr->sempid;
729 		goto out_unlock;
730 	case GETNCNT:
731 		err = count_semncnt(sma,semnum);
732 		goto out_unlock;
733 	case GETZCNT:
734 		err = count_semzcnt(sma,semnum);
735 		goto out_unlock;
736 	case SETVAL:
737 	{
738 		int val = arg.val;
739 		struct sem_undo *un;
740 		err = -ERANGE;
741 		if (val > SEMVMX || val < 0)
742 			goto out_unlock;
743 
744 		for (un = sma->undo; un; un = un->id_next)
745 			un->semadj[semnum] = 0;
746 		curr->semval = val;
747 		curr->sempid = current->tgid;
748 		sma->sem_ctime = get_seconds();
749 		/* maybe some queued-up processes were waiting for this */
750 		update_queue(sma);
751 		err = 0;
752 		goto out_unlock;
753 	}
754 	}
755 out_unlock:
756 	sem_unlock(sma);
757 out_free:
758 	if(sem_io != fast_sem_io)
759 		ipc_free(sem_io, sizeof(ushort)*nsems);
760 	return err;
761 }
762 
763 struct sem_setbuf {
764 	uid_t	uid;
765 	gid_t	gid;
766 	mode_t	mode;
767 };
768 
769 static inline unsigned long copy_semid_from_user(struct sem_setbuf *out, void __user *buf, int version)
770 {
771 	switch(version) {
772 	case IPC_64:
773 	    {
774 		struct semid64_ds tbuf;
775 
776 		if(copy_from_user(&tbuf, buf, sizeof(tbuf)))
777 			return -EFAULT;
778 
779 		out->uid	= tbuf.sem_perm.uid;
780 		out->gid	= tbuf.sem_perm.gid;
781 		out->mode	= tbuf.sem_perm.mode;
782 
783 		return 0;
784 	    }
785 	case IPC_OLD:
786 	    {
787 		struct semid_ds tbuf_old;
788 
789 		if(copy_from_user(&tbuf_old, buf, sizeof(tbuf_old)))
790 			return -EFAULT;
791 
792 		out->uid	= tbuf_old.sem_perm.uid;
793 		out->gid	= tbuf_old.sem_perm.gid;
794 		out->mode	= tbuf_old.sem_perm.mode;
795 
796 		return 0;
797 	    }
798 	default:
799 		return -EINVAL;
800 	}
801 }
802 
803 static int semctl_down(int semid, int semnum, int cmd, int version, union semun arg)
804 {
805 	struct sem_array *sma;
806 	int err;
807 	struct sem_setbuf setbuf;
808 	struct kern_ipc_perm *ipcp;
809 
810 	if(cmd == IPC_SET) {
811 		if(copy_semid_from_user (&setbuf, arg.buf, version))
812 			return -EFAULT;
813 	}
814 	sma = sem_lock(semid);
815 	if(sma==NULL)
816 		return -EINVAL;
817 
818 	if (sem_checkid(sma,semid)) {
819 		err=-EIDRM;
820 		goto out_unlock;
821 	}
822 	ipcp = &sma->sem_perm;
823 	if (current->euid != ipcp->cuid &&
824 	    current->euid != ipcp->uid && !capable(CAP_SYS_ADMIN)) {
825 	    	err=-EPERM;
826 		goto out_unlock;
827 	}
828 
829 	err = security_sem_semctl(sma, cmd);
830 	if (err)
831 		goto out_unlock;
832 
833 	switch(cmd){
834 	case IPC_RMID:
835 		freeary(sma, semid);
836 		err = 0;
837 		break;
838 	case IPC_SET:
839 		if ((err = audit_ipc_perms(0, setbuf.uid, setbuf.gid, setbuf.mode, ipcp)))
840 			goto out_unlock;
841 		ipcp->uid = setbuf.uid;
842 		ipcp->gid = setbuf.gid;
843 		ipcp->mode = (ipcp->mode & ~S_IRWXUGO)
844 				| (setbuf.mode & S_IRWXUGO);
845 		sma->sem_ctime = get_seconds();
846 		sem_unlock(sma);
847 		err = 0;
848 		break;
849 	default:
850 		sem_unlock(sma);
851 		err = -EINVAL;
852 		break;
853 	}
854 	return err;
855 
856 out_unlock:
857 	sem_unlock(sma);
858 	return err;
859 }
860 
861 asmlinkage long sys_semctl (int semid, int semnum, int cmd, union semun arg)
862 {
863 	int err = -EINVAL;
864 	int version;
865 
866 	if (semid < 0)
867 		return -EINVAL;
868 
869 	version = ipc_parse_version(&cmd);
870 
871 	switch(cmd) {
872 	case IPC_INFO:
873 	case SEM_INFO:
874 	case SEM_STAT:
875 		err = semctl_nolock(semid,semnum,cmd,version,arg);
876 		return err;
877 	case GETALL:
878 	case GETVAL:
879 	case GETPID:
880 	case GETNCNT:
881 	case GETZCNT:
882 	case IPC_STAT:
883 	case SETVAL:
884 	case SETALL:
885 		err = semctl_main(semid,semnum,cmd,version,arg);
886 		return err;
887 	case IPC_RMID:
888 	case IPC_SET:
889 		mutex_lock(&sem_ids.mutex);
890 		err = semctl_down(semid,semnum,cmd,version,arg);
891 		mutex_unlock(&sem_ids.mutex);
892 		return err;
893 	default:
894 		return -EINVAL;
895 	}
896 }
897 
898 static inline void lock_semundo(void)
899 {
900 	struct sem_undo_list *undo_list;
901 
902 	undo_list = current->sysvsem.undo_list;
903 	if (undo_list)
904 		spin_lock(&undo_list->lock);
905 }
906 
907 /* This code has an interaction with copy_semundo().
908  * Consider; two tasks are sharing the undo_list. task1
909  * acquires the undo_list lock in lock_semundo().  If task2 now
910  * exits before task1 releases the lock (by calling
911  * unlock_semundo()), then task1 will never call spin_unlock().
912  * This leave the sem_undo_list in a locked state.  If task1 now creats task3
913  * and once again shares the sem_undo_list, the sem_undo_list will still be
914  * locked, and future SEM_UNDO operations will deadlock.  This case is
915  * dealt with in copy_semundo() by having it reinitialize the spin lock when
916  * the refcnt goes from 1 to 2.
917  */
918 static inline void unlock_semundo(void)
919 {
920 	struct sem_undo_list *undo_list;
921 
922 	undo_list = current->sysvsem.undo_list;
923 	if (undo_list)
924 		spin_unlock(&undo_list->lock);
925 }
926 
927 
928 /* If the task doesn't already have a undo_list, then allocate one
929  * here.  We guarantee there is only one thread using this undo list,
930  * and current is THE ONE
931  *
932  * If this allocation and assignment succeeds, but later
933  * portions of this code fail, there is no need to free the sem_undo_list.
934  * Just let it stay associated with the task, and it'll be freed later
935  * at exit time.
936  *
937  * This can block, so callers must hold no locks.
938  */
939 static inline int get_undo_list(struct sem_undo_list **undo_listp)
940 {
941 	struct sem_undo_list *undo_list;
942 	int size;
943 
944 	undo_list = current->sysvsem.undo_list;
945 	if (!undo_list) {
946 		size = sizeof(struct sem_undo_list);
947 		undo_list = (struct sem_undo_list *) kmalloc(size, GFP_KERNEL);
948 		if (undo_list == NULL)
949 			return -ENOMEM;
950 		memset(undo_list, 0, size);
951 		spin_lock_init(&undo_list->lock);
952 		atomic_set(&undo_list->refcnt, 1);
953 		current->sysvsem.undo_list = undo_list;
954 	}
955 	*undo_listp = undo_list;
956 	return 0;
957 }
958 
959 static struct sem_undo *lookup_undo(struct sem_undo_list *ulp, int semid)
960 {
961 	struct sem_undo **last, *un;
962 
963 	last = &ulp->proc_list;
964 	un = *last;
965 	while(un != NULL) {
966 		if(un->semid==semid)
967 			break;
968 		if(un->semid==-1) {
969 			*last=un->proc_next;
970 			kfree(un);
971 		} else {
972 			last=&un->proc_next;
973 		}
974 		un=*last;
975 	}
976 	return un;
977 }
978 
979 static struct sem_undo *find_undo(int semid)
980 {
981 	struct sem_array *sma;
982 	struct sem_undo_list *ulp;
983 	struct sem_undo *un, *new;
984 	int nsems;
985 	int error;
986 
987 	error = get_undo_list(&ulp);
988 	if (error)
989 		return ERR_PTR(error);
990 
991 	lock_semundo();
992 	un = lookup_undo(ulp, semid);
993 	unlock_semundo();
994 	if (likely(un!=NULL))
995 		goto out;
996 
997 	/* no undo structure around - allocate one. */
998 	sma = sem_lock(semid);
999 	un = ERR_PTR(-EINVAL);
1000 	if(sma==NULL)
1001 		goto out;
1002 	un = ERR_PTR(-EIDRM);
1003 	if (sem_checkid(sma,semid)) {
1004 		sem_unlock(sma);
1005 		goto out;
1006 	}
1007 	nsems = sma->sem_nsems;
1008 	ipc_rcu_getref(sma);
1009 	sem_unlock(sma);
1010 
1011 	new = (struct sem_undo *) kmalloc(sizeof(struct sem_undo) + sizeof(short)*nsems, GFP_KERNEL);
1012 	if (!new) {
1013 		ipc_lock_by_ptr(&sma->sem_perm);
1014 		ipc_rcu_putref(sma);
1015 		sem_unlock(sma);
1016 		return ERR_PTR(-ENOMEM);
1017 	}
1018 	memset(new, 0, sizeof(struct sem_undo) + sizeof(short)*nsems);
1019 	new->semadj = (short *) &new[1];
1020 	new->semid = semid;
1021 
1022 	lock_semundo();
1023 	un = lookup_undo(ulp, semid);
1024 	if (un) {
1025 		unlock_semundo();
1026 		kfree(new);
1027 		ipc_lock_by_ptr(&sma->sem_perm);
1028 		ipc_rcu_putref(sma);
1029 		sem_unlock(sma);
1030 		goto out;
1031 	}
1032 	ipc_lock_by_ptr(&sma->sem_perm);
1033 	ipc_rcu_putref(sma);
1034 	if (sma->sem_perm.deleted) {
1035 		sem_unlock(sma);
1036 		unlock_semundo();
1037 		kfree(new);
1038 		un = ERR_PTR(-EIDRM);
1039 		goto out;
1040 	}
1041 	new->proc_next = ulp->proc_list;
1042 	ulp->proc_list = new;
1043 	new->id_next = sma->undo;
1044 	sma->undo = new;
1045 	sem_unlock(sma);
1046 	un = new;
1047 	unlock_semundo();
1048 out:
1049 	return un;
1050 }
1051 
1052 asmlinkage long sys_semtimedop(int semid, struct sembuf __user *tsops,
1053 			unsigned nsops, const struct timespec __user *timeout)
1054 {
1055 	int error = -EINVAL;
1056 	struct sem_array *sma;
1057 	struct sembuf fast_sops[SEMOPM_FAST];
1058 	struct sembuf* sops = fast_sops, *sop;
1059 	struct sem_undo *un;
1060 	int undos = 0, alter = 0, max;
1061 	struct sem_queue queue;
1062 	unsigned long jiffies_left = 0;
1063 
1064 	if (nsops < 1 || semid < 0)
1065 		return -EINVAL;
1066 	if (nsops > sc_semopm)
1067 		return -E2BIG;
1068 	if(nsops > SEMOPM_FAST) {
1069 		sops = kmalloc(sizeof(*sops)*nsops,GFP_KERNEL);
1070 		if(sops==NULL)
1071 			return -ENOMEM;
1072 	}
1073 	if (copy_from_user (sops, tsops, nsops * sizeof(*tsops))) {
1074 		error=-EFAULT;
1075 		goto out_free;
1076 	}
1077 	if (timeout) {
1078 		struct timespec _timeout;
1079 		if (copy_from_user(&_timeout, timeout, sizeof(*timeout))) {
1080 			error = -EFAULT;
1081 			goto out_free;
1082 		}
1083 		if (_timeout.tv_sec < 0 || _timeout.tv_nsec < 0 ||
1084 			_timeout.tv_nsec >= 1000000000L) {
1085 			error = -EINVAL;
1086 			goto out_free;
1087 		}
1088 		jiffies_left = timespec_to_jiffies(&_timeout);
1089 	}
1090 	max = 0;
1091 	for (sop = sops; sop < sops + nsops; sop++) {
1092 		if (sop->sem_num >= max)
1093 			max = sop->sem_num;
1094 		if (sop->sem_flg & SEM_UNDO)
1095 			undos = 1;
1096 		if (sop->sem_op != 0)
1097 			alter = 1;
1098 	}
1099 
1100 retry_undos:
1101 	if (undos) {
1102 		un = find_undo(semid);
1103 		if (IS_ERR(un)) {
1104 			error = PTR_ERR(un);
1105 			goto out_free;
1106 		}
1107 	} else
1108 		un = NULL;
1109 
1110 	sma = sem_lock(semid);
1111 	error=-EINVAL;
1112 	if(sma==NULL)
1113 		goto out_free;
1114 	error = -EIDRM;
1115 	if (sem_checkid(sma,semid))
1116 		goto out_unlock_free;
1117 	/*
1118 	 * semid identifies are not unique - find_undo may have
1119 	 * allocated an undo structure, it was invalidated by an RMID
1120 	 * and now a new array with received the same id. Check and retry.
1121 	 */
1122 	if (un && un->semid == -1) {
1123 		sem_unlock(sma);
1124 		goto retry_undos;
1125 	}
1126 	error = -EFBIG;
1127 	if (max >= sma->sem_nsems)
1128 		goto out_unlock_free;
1129 
1130 	error = -EACCES;
1131 	if (ipcperms(&sma->sem_perm, alter ? S_IWUGO : S_IRUGO))
1132 		goto out_unlock_free;
1133 
1134 	error = security_sem_semop(sma, sops, nsops, alter);
1135 	if (error)
1136 		goto out_unlock_free;
1137 
1138 	error = try_atomic_semop (sma, sops, nsops, un, current->tgid);
1139 	if (error <= 0) {
1140 		if (alter && error == 0)
1141 			update_queue (sma);
1142 		goto out_unlock_free;
1143 	}
1144 
1145 	/* We need to sleep on this operation, so we put the current
1146 	 * task into the pending queue and go to sleep.
1147 	 */
1148 
1149 	queue.sma = sma;
1150 	queue.sops = sops;
1151 	queue.nsops = nsops;
1152 	queue.undo = un;
1153 	queue.pid = current->tgid;
1154 	queue.id = semid;
1155 	queue.alter = alter;
1156 	if (alter)
1157 		append_to_queue(sma ,&queue);
1158 	else
1159 		prepend_to_queue(sma ,&queue);
1160 
1161 	queue.status = -EINTR;
1162 	queue.sleeper = current;
1163 	current->state = TASK_INTERRUPTIBLE;
1164 	sem_unlock(sma);
1165 
1166 	if (timeout)
1167 		jiffies_left = schedule_timeout(jiffies_left);
1168 	else
1169 		schedule();
1170 
1171 	error = queue.status;
1172 	while(unlikely(error == IN_WAKEUP)) {
1173 		cpu_relax();
1174 		error = queue.status;
1175 	}
1176 
1177 	if (error != -EINTR) {
1178 		/* fast path: update_queue already obtained all requested
1179 		 * resources */
1180 		goto out_free;
1181 	}
1182 
1183 	sma = sem_lock(semid);
1184 	if(sma==NULL) {
1185 		BUG_ON(queue.prev != NULL);
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 * semaphore = &sma->sem_base[i];
1303 			if (u->semadj[i]) {
1304 				semaphore->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 (semaphore->semval < 0)
1319 					semaphore->semval = 0;
1320 				if (semaphore->semval > SEMVMX)
1321 					semaphore->semval = SEMVMX;
1322 				semaphore->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
1353