]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blame - ipc/sem.c
ipc,sem: open code and rename sem_lock
[mirror_ubuntu-bionic-kernel.git] / ipc / sem.c
CommitLineData
1da177e4
LT
1/*
2 * linux/ipc/sem.c
3 * Copyright (C) 1992 Krishna Balasubramanian
4 * Copyright (C) 1995 Eric Schenk, Bruno Haible
5 *
1da177e4
LT
6 * /proc/sysvipc/sem support (c) 1999 Dragos Acostachioaie <dragos@iname.com>
7 *
8 * SMP-threaded, sysctl's added
624dffcb 9 * (c) 1999 Manfred Spraul <manfred@colorfullife.com>
1da177e4 10 * Enforced range limit on SEM_UNDO
046c6884 11 * (c) 2001 Red Hat Inc
1da177e4
LT
12 * Lockless wakeup
13 * (c) 2003 Manfred Spraul <manfred@colorfullife.com>
c5cf6359
MS
14 * Further wakeup optimizations, documentation
15 * (c) 2010 Manfred Spraul <manfred@colorfullife.com>
073115d6
SG
16 *
17 * support for audit of ipc object properties and permission changes
18 * Dustin Kirkland <dustin.kirkland@us.ibm.com>
e3893534
KK
19 *
20 * namespaces support
21 * OpenVZ, SWsoft Inc.
22 * Pavel Emelianov <xemul@openvz.org>
c5cf6359
MS
23 *
24 * Implementation notes: (May 2010)
25 * This file implements System V semaphores.
26 *
27 * User space visible behavior:
28 * - FIFO ordering for semop() operations (just FIFO, not starvation
29 * protection)
30 * - multiple semaphore operations that alter the same semaphore in
31 * one semop() are handled.
32 * - sem_ctime (time of last semctl()) is updated in the IPC_SET, SETVAL and
33 * SETALL calls.
34 * - two Linux specific semctl() commands: SEM_STAT, SEM_INFO.
35 * - undo adjustments at process exit are limited to 0..SEMVMX.
36 * - namespace are supported.
37 * - SEMMSL, SEMMNS, SEMOPM and SEMMNI can be configured at runtine by writing
38 * to /proc/sys/kernel/sem.
39 * - statistics about the usage are reported in /proc/sysvipc/sem.
40 *
41 * Internals:
42 * - scalability:
43 * - all global variables are read-mostly.
44 * - semop() calls and semctl(RMID) are synchronized by RCU.
45 * - most operations do write operations (actually: spin_lock calls) to
46 * the per-semaphore array structure.
47 * Thus: Perfect SMP scaling between independent semaphore arrays.
48 * If multiple semaphores in one array are used, then cache line
49 * trashing on the semaphore array spinlock will limit the scaling.
50 * - semncnt and semzcnt are calculated on demand in count_semncnt() and
51 * count_semzcnt()
52 * - the task that performs a successful semop() scans the list of all
53 * sleeping tasks and completes any pending operations that can be fulfilled.
54 * Semaphores are actively given to waiting tasks (necessary for FIFO).
55 * (see update_queue())
56 * - To improve the scalability, the actual wake-up calls are performed after
57 * dropping all locks. (see wake_up_sem_queue_prepare(),
58 * wake_up_sem_queue_do())
59 * - All work is done by the waker, the woken up task does not have to do
60 * anything - not even acquiring a lock or dropping a refcount.
61 * - A woken up task may not even touch the semaphore array anymore, it may
62 * have been destroyed already by a semctl(RMID).
63 * - The synchronizations between wake-ups due to a timeout/signal and a
64 * wake-up due to a completed semaphore operation is achieved by using an
65 * intermediate state (IN_WAKEUP).
66 * - UNDO values are stored in an array (one per process and per
67 * semaphore array, lazily allocated). For backwards compatibility, multiple
68 * modes for the UNDO variables are supported (per process, per thread)
69 * (see copy_semundo, CLONE_SYSVSEM)
70 * - There are two lists of the pending operations: a per-array list
71 * and per-semaphore list (stored in the array). This allows to achieve FIFO
72 * ordering without always scanning all pending operations.
73 * The worst-case behavior is nevertheless O(N^2) for N wakeups.
1da177e4
LT
74 */
75
1da177e4
LT
76#include <linux/slab.h>
77#include <linux/spinlock.h>
78#include <linux/init.h>
79#include <linux/proc_fs.h>
80#include <linux/time.h>
1da177e4
LT
81#include <linux/security.h>
82#include <linux/syscalls.h>
83#include <linux/audit.h>
c59ede7b 84#include <linux/capability.h>
19b4946c 85#include <linux/seq_file.h>
3e148c79 86#include <linux/rwsem.h>
e3893534 87#include <linux/nsproxy.h>
ae5e1b22 88#include <linux/ipc_namespace.h>
5f921ae9 89
1da177e4
LT
90#include <asm/uaccess.h>
91#include "util.h"
92
e57940d7
MS
93/* One semaphore structure for each semaphore in the system. */
94struct sem {
95 int semval; /* current value */
96 int sempid; /* pid of last operation */
97 struct list_head sem_pending; /* pending single-sop operations */
98};
99
100/* One queue for each sleeping process in the system. */
101struct sem_queue {
102 struct list_head simple_list; /* queue of pending operations */
103 struct list_head list; /* queue of pending operations */
104 struct task_struct *sleeper; /* this process */
105 struct sem_undo *undo; /* undo structure */
106 int pid; /* process id of requesting process */
107 int status; /* completion status of operation */
108 struct sembuf *sops; /* array of pending operations */
109 int nsops; /* number of operations */
110 int alter; /* does *sops alter the array? */
111};
112
113/* Each task has a list of undo requests. They are executed automatically
114 * when the process exits.
115 */
116struct sem_undo {
117 struct list_head list_proc; /* per-process list: *
118 * all undos from one process
119 * rcu protected */
120 struct rcu_head rcu; /* rcu struct for sem_undo */
121 struct sem_undo_list *ulp; /* back ptr to sem_undo_list */
122 struct list_head list_id; /* per semaphore array list:
123 * all undos for one array */
124 int semid; /* semaphore set identifier */
125 short *semadj; /* array of adjustments */
126 /* one per semaphore */
127};
128
129/* sem_undo_list controls shared access to the list of sem_undo structures
130 * that may be shared among all a CLONE_SYSVSEM task group.
131 */
132struct sem_undo_list {
133 atomic_t refcnt;
134 spinlock_t lock;
135 struct list_head list_proc;
136};
137
138
ed2ddbf8 139#define sem_ids(ns) ((ns)->ids[IPC_SEM_IDS])
e3893534 140
e3893534 141#define sem_unlock(sma) ipc_unlock(&(sma)->sem_perm)
1b531f21 142#define sem_checkid(sma, semid) ipc_checkid(&sma->sem_perm, semid)
1da177e4 143
7748dbfa 144static int newary(struct ipc_namespace *, struct ipc_params *);
01b8b07a 145static void freeary(struct ipc_namespace *, struct kern_ipc_perm *);
1da177e4 146#ifdef CONFIG_PROC_FS
19b4946c 147static int sysvipc_sem_proc_show(struct seq_file *s, void *it);
1da177e4
LT
148#endif
149
150#define SEMMSL_FAST 256 /* 512 bytes on stack */
151#define SEMOPM_FAST 64 /* ~ 372 bytes on stack */
152
153/*
154 * linked list protection:
155 * sem_undo.id_next,
156 * sem_array.sem_pending{,last},
157 * sem_array.sem_undo: sem_lock() for read/write
158 * sem_undo.proc_next: only "current" is allowed to read/write that field.
159 *
160 */
161
e3893534
KK
162#define sc_semmsl sem_ctls[0]
163#define sc_semmns sem_ctls[1]
164#define sc_semopm sem_ctls[2]
165#define sc_semmni sem_ctls[3]
166
ed2ddbf8 167void sem_init_ns(struct ipc_namespace *ns)
e3893534 168{
e3893534
KK
169 ns->sc_semmsl = SEMMSL;
170 ns->sc_semmns = SEMMNS;
171 ns->sc_semopm = SEMOPM;
172 ns->sc_semmni = SEMMNI;
173 ns->used_sems = 0;
ed2ddbf8 174 ipc_init_ids(&ns->ids[IPC_SEM_IDS]);
e3893534
KK
175}
176
ae5e1b22 177#ifdef CONFIG_IPC_NS
e3893534
KK
178void sem_exit_ns(struct ipc_namespace *ns)
179{
01b8b07a 180 free_ipcs(ns, &sem_ids(ns), freeary);
7d6feeb2 181 idr_destroy(&ns->ids[IPC_SEM_IDS].ipcs_idr);
e3893534 182}
ae5e1b22 183#endif
1da177e4
LT
184
185void __init sem_init (void)
186{
ed2ddbf8 187 sem_init_ns(&init_ipc_ns);
19b4946c
MW
188 ipc_init_proc_interface("sysvipc/sem",
189 " key semid perms nsems uid gid cuid cgid otime ctime\n",
e3893534 190 IPC_SEM_IDS, sysvipc_sem_proc_show);
1da177e4
LT
191}
192
3e148c79
ND
193/*
194 * sem_lock_(check_) routines are called in the paths where the rw_mutex
195 * is not held.
196 */
c460b662 197static inline struct sem_array *sem_obtain_lock(struct ipc_namespace *ns, int id)
023a5355 198{
c460b662
RR
199 struct kern_ipc_perm *ipcp;
200 struct sem_array *sma;
03f02c76 201
c460b662
RR
202 rcu_read_lock();
203 ipcp = ipc_obtain_object(&sem_ids(ns), id);
204 if (IS_ERR(ipcp)) {
205 sma = ERR_CAST(ipcp);
206 goto err;
207 }
b1ed88b4 208
c460b662
RR
209 spin_lock(&ipcp->lock);
210
211 /* ipc_rmid() may have already freed the ID while sem_lock
212 * was spinning: verify that the structure is still valid
213 */
214 if (!ipcp->deleted)
215 return container_of(ipcp, struct sem_array, sem_perm);
216
217 spin_unlock(&ipcp->lock);
218 sma = ERR_PTR(-EINVAL);
219err:
220 rcu_read_unlock();
221 return sma;
023a5355
ND
222}
223
16df3674
DB
224static inline struct sem_array *sem_obtain_object(struct ipc_namespace *ns, int id)
225{
226 struct kern_ipc_perm *ipcp = ipc_obtain_object(&sem_ids(ns), id);
227
228 if (IS_ERR(ipcp))
229 return ERR_CAST(ipcp);
230
231 return container_of(ipcp, struct sem_array, sem_perm);
232}
233
023a5355
ND
234static inline struct sem_array *sem_lock_check(struct ipc_namespace *ns,
235 int id)
236{
03f02c76
ND
237 struct kern_ipc_perm *ipcp = ipc_lock_check(&sem_ids(ns), id);
238
b1ed88b4 239 if (IS_ERR(ipcp))
16df3674
DB
240 return ERR_CAST(ipcp);
241
242 return container_of(ipcp, struct sem_array, sem_perm);
243}
244
245static inline struct sem_array *sem_obtain_object_check(struct ipc_namespace *ns,
246 int id)
247{
248 struct kern_ipc_perm *ipcp = ipc_obtain_object_check(&sem_ids(ns), id);
249
250 if (IS_ERR(ipcp))
251 return ERR_CAST(ipcp);
b1ed88b4 252
03f02c76 253 return container_of(ipcp, struct sem_array, sem_perm);
023a5355
ND
254}
255
6ff37972
PP
256static inline void sem_lock_and_putref(struct sem_array *sma)
257{
258 ipc_lock_by_ptr(&sma->sem_perm);
259 ipc_rcu_putref(sma);
260}
261
262static inline void sem_getref_and_unlock(struct sem_array *sma)
263{
264 ipc_rcu_getref(sma);
265 ipc_unlock(&(sma)->sem_perm);
266}
267
268static inline void sem_putref(struct sem_array *sma)
269{
270 ipc_lock_by_ptr(&sma->sem_perm);
271 ipc_rcu_putref(sma);
272 ipc_unlock(&(sma)->sem_perm);
273}
274
16df3674
DB
275/*
276 * Call inside the rcu read section.
277 */
278static inline void sem_getref(struct sem_array *sma)
279{
280 spin_lock(&(sma)->sem_perm.lock);
281 ipc_rcu_getref(sma);
282 ipc_unlock(&(sma)->sem_perm);
283}
284
7ca7e564
ND
285static inline void sem_rmid(struct ipc_namespace *ns, struct sem_array *s)
286{
287 ipc_rmid(&sem_ids(ns), &s->sem_perm);
288}
289
1da177e4
LT
290/*
291 * Lockless wakeup algorithm:
292 * Without the check/retry algorithm a lockless wakeup is possible:
293 * - queue.status is initialized to -EINTR before blocking.
294 * - wakeup is performed by
295 * * unlinking the queue entry from sma->sem_pending
296 * * setting queue.status to IN_WAKEUP
297 * This is the notification for the blocked thread that a
298 * result value is imminent.
299 * * call wake_up_process
300 * * set queue.status to the final value.
301 * - the previously blocked thread checks queue.status:
302 * * if it's IN_WAKEUP, then it must wait until the value changes
303 * * if it's not -EINTR, then the operation was completed by
304 * update_queue. semtimedop can return queue.status without
5f921ae9 305 * performing any operation on the sem array.
1da177e4
LT
306 * * otherwise it must acquire the spinlock and check what's up.
307 *
308 * The two-stage algorithm is necessary to protect against the following
309 * races:
310 * - if queue.status is set after wake_up_process, then the woken up idle
311 * thread could race forward and try (and fail) to acquire sma->lock
312 * before update_queue had a chance to set queue.status
313 * - if queue.status is written before wake_up_process and if the
314 * blocked process is woken up by a signal between writing
315 * queue.status and the wake_up_process, then the woken up
316 * process could return from semtimedop and die by calling
317 * sys_exit before wake_up_process is called. Then wake_up_process
318 * will oops, because the task structure is already invalid.
319 * (yes, this happened on s390 with sysv msg).
320 *
321 */
322#define IN_WAKEUP 1
323
f4566f04
ND
324/**
325 * newary - Create a new semaphore set
326 * @ns: namespace
327 * @params: ptr to the structure that contains key, semflg and nsems
328 *
3e148c79 329 * Called with sem_ids.rw_mutex held (as a writer)
f4566f04
ND
330 */
331
7748dbfa 332static int newary(struct ipc_namespace *ns, struct ipc_params *params)
1da177e4
LT
333{
334 int id;
335 int retval;
336 struct sem_array *sma;
337 int size;
7748dbfa
ND
338 key_t key = params->key;
339 int nsems = params->u.nsems;
340 int semflg = params->flg;
b97e820f 341 int i;
1da177e4
LT
342
343 if (!nsems)
344 return -EINVAL;
e3893534 345 if (ns->used_sems + nsems > ns->sc_semmns)
1da177e4
LT
346 return -ENOSPC;
347
348 size = sizeof (*sma) + nsems * sizeof (struct sem);
349 sma = ipc_rcu_alloc(size);
350 if (!sma) {
351 return -ENOMEM;
352 }
353 memset (sma, 0, size);
354
355 sma->sem_perm.mode = (semflg & S_IRWXUGO);
356 sma->sem_perm.key = key;
357
358 sma->sem_perm.security = NULL;
359 retval = security_sem_alloc(sma);
360 if (retval) {
361 ipc_rcu_putref(sma);
362 return retval;
363 }
364
e3893534 365 id = ipc_addid(&sem_ids(ns), &sma->sem_perm, ns->sc_semmni);
283bb7fa 366 if (id < 0) {
1da177e4
LT
367 security_sem_free(sma);
368 ipc_rcu_putref(sma);
283bb7fa 369 return id;
1da177e4 370 }
e3893534 371 ns->used_sems += nsems;
1da177e4
LT
372
373 sma->sem_base = (struct sem *) &sma[1];
b97e820f
MS
374
375 for (i = 0; i < nsems; i++)
376 INIT_LIST_HEAD(&sma->sem_base[i].sem_pending);
377
378 sma->complex_count = 0;
a1193f8e 379 INIT_LIST_HEAD(&sma->sem_pending);
4daa28f6 380 INIT_LIST_HEAD(&sma->list_id);
1da177e4
LT
381 sma->sem_nsems = nsems;
382 sma->sem_ctime = get_seconds();
383 sem_unlock(sma);
384
7ca7e564 385 return sma->sem_perm.id;
1da177e4
LT
386}
387
7748dbfa 388
f4566f04 389/*
3e148c79 390 * Called with sem_ids.rw_mutex and ipcp locked.
f4566f04 391 */
03f02c76 392static inline int sem_security(struct kern_ipc_perm *ipcp, int semflg)
7748dbfa 393{
03f02c76
ND
394 struct sem_array *sma;
395
396 sma = container_of(ipcp, struct sem_array, sem_perm);
397 return security_sem_associate(sma, semflg);
7748dbfa
ND
398}
399
f4566f04 400/*
3e148c79 401 * Called with sem_ids.rw_mutex and ipcp locked.
f4566f04 402 */
03f02c76
ND
403static inline int sem_more_checks(struct kern_ipc_perm *ipcp,
404 struct ipc_params *params)
7748dbfa 405{
03f02c76
ND
406 struct sem_array *sma;
407
408 sma = container_of(ipcp, struct sem_array, sem_perm);
409 if (params->u.nsems > sma->sem_nsems)
7748dbfa
ND
410 return -EINVAL;
411
412 return 0;
413}
414
d5460c99 415SYSCALL_DEFINE3(semget, key_t, key, int, nsems, int, semflg)
1da177e4 416{
e3893534 417 struct ipc_namespace *ns;
7748dbfa
ND
418 struct ipc_ops sem_ops;
419 struct ipc_params sem_params;
e3893534
KK
420
421 ns = current->nsproxy->ipc_ns;
1da177e4 422
e3893534 423 if (nsems < 0 || nsems > ns->sc_semmsl)
1da177e4 424 return -EINVAL;
7ca7e564 425
7748dbfa
ND
426 sem_ops.getnew = newary;
427 sem_ops.associate = sem_security;
428 sem_ops.more_checks = sem_more_checks;
429
430 sem_params.key = key;
431 sem_params.flg = semflg;
432 sem_params.u.nsems = nsems;
1da177e4 433
7748dbfa 434 return ipcget(ns, &sem_ids(ns), &sem_ops, &sem_params);
1da177e4
LT
435}
436
1da177e4
LT
437/*
438 * Determine whether a sequence of semaphore operations would succeed
439 * all at once. Return 0 if yes, 1 if need to sleep, else return error code.
440 */
441
442static int try_atomic_semop (struct sem_array * sma, struct sembuf * sops,
443 int nsops, struct sem_undo *un, int pid)
444{
445 int result, sem_op;
446 struct sembuf *sop;
447 struct sem * curr;
448
449 for (sop = sops; sop < sops + nsops; sop++) {
450 curr = sma->sem_base + sop->sem_num;
451 sem_op = sop->sem_op;
452 result = curr->semval;
453
454 if (!sem_op && result)
455 goto would_block;
456
457 result += sem_op;
458 if (result < 0)
459 goto would_block;
460 if (result > SEMVMX)
461 goto out_of_range;
462 if (sop->sem_flg & SEM_UNDO) {
463 int undo = un->semadj[sop->sem_num] - sem_op;
464 /*
465 * Exceeding the undo range is an error.
466 */
467 if (undo < (-SEMAEM - 1) || undo > SEMAEM)
468 goto out_of_range;
469 }
470 curr->semval = result;
471 }
472
473 sop--;
474 while (sop >= sops) {
475 sma->sem_base[sop->sem_num].sempid = pid;
476 if (sop->sem_flg & SEM_UNDO)
477 un->semadj[sop->sem_num] -= sop->sem_op;
478 sop--;
479 }
480
1da177e4
LT
481 return 0;
482
483out_of_range:
484 result = -ERANGE;
485 goto undo;
486
487would_block:
488 if (sop->sem_flg & IPC_NOWAIT)
489 result = -EAGAIN;
490 else
491 result = 1;
492
493undo:
494 sop--;
495 while (sop >= sops) {
496 sma->sem_base[sop->sem_num].semval -= sop->sem_op;
497 sop--;
498 }
499
500 return result;
501}
502
0a2b9d4c
MS
503/** wake_up_sem_queue_prepare(q, error): Prepare wake-up
504 * @q: queue entry that must be signaled
505 * @error: Error value for the signal
506 *
507 * Prepare the wake-up of the queue entry q.
d4212093 508 */
0a2b9d4c
MS
509static void wake_up_sem_queue_prepare(struct list_head *pt,
510 struct sem_queue *q, int error)
d4212093 511{
0a2b9d4c
MS
512 if (list_empty(pt)) {
513 /*
514 * Hold preempt off so that we don't get preempted and have the
515 * wakee busy-wait until we're scheduled back on.
516 */
517 preempt_disable();
518 }
d4212093 519 q->status = IN_WAKEUP;
0a2b9d4c
MS
520 q->pid = error;
521
522 list_add_tail(&q->simple_list, pt);
523}
524
525/**
526 * wake_up_sem_queue_do(pt) - do the actual wake-up
527 * @pt: list of tasks to be woken up
528 *
529 * Do the actual wake-up.
530 * The function is called without any locks held, thus the semaphore array
531 * could be destroyed already and the tasks can disappear as soon as the
532 * status is set to the actual return code.
533 */
534static void wake_up_sem_queue_do(struct list_head *pt)
535{
536 struct sem_queue *q, *t;
537 int did_something;
538
539 did_something = !list_empty(pt);
540 list_for_each_entry_safe(q, t, pt, simple_list) {
541 wake_up_process(q->sleeper);
542 /* q can disappear immediately after writing q->status. */
543 smp_wmb();
544 q->status = q->pid;
545 }
546 if (did_something)
547 preempt_enable();
d4212093
NP
548}
549
b97e820f
MS
550static void unlink_queue(struct sem_array *sma, struct sem_queue *q)
551{
552 list_del(&q->list);
553 if (q->nsops == 1)
554 list_del(&q->simple_list);
555 else
556 sma->complex_count--;
557}
558
fd5db422
MS
559/** check_restart(sma, q)
560 * @sma: semaphore array
561 * @q: the operation that just completed
562 *
563 * update_queue is O(N^2) when it restarts scanning the whole queue of
564 * waiting operations. Therefore this function checks if the restart is
565 * really necessary. It is called after a previously waiting operation
566 * was completed.
567 */
568static int check_restart(struct sem_array *sma, struct sem_queue *q)
569{
570 struct sem *curr;
571 struct sem_queue *h;
572
573 /* if the operation didn't modify the array, then no restart */
574 if (q->alter == 0)
575 return 0;
576
577 /* pending complex operations are too difficult to analyse */
578 if (sma->complex_count)
579 return 1;
580
581 /* we were a sleeping complex operation. Too difficult */
582 if (q->nsops > 1)
583 return 1;
584
585 curr = sma->sem_base + q->sops[0].sem_num;
586
587 /* No-one waits on this queue */
588 if (list_empty(&curr->sem_pending))
589 return 0;
590
591 /* the new semaphore value */
592 if (curr->semval) {
593 /* It is impossible that someone waits for the new value:
594 * - q is a previously sleeping simple operation that
595 * altered the array. It must be a decrement, because
596 * simple increments never sleep.
597 * - The value is not 0, thus wait-for-zero won't proceed.
598 * - If there are older (higher priority) decrements
599 * in the queue, then they have observed the original
600 * semval value and couldn't proceed. The operation
601 * decremented to value - thus they won't proceed either.
602 */
603 BUG_ON(q->sops[0].sem_op >= 0);
604 return 0;
605 }
606 /*
607 * semval is 0. Check if there are wait-for-zero semops.
608 * They must be the first entries in the per-semaphore simple queue
609 */
610 h = list_first_entry(&curr->sem_pending, struct sem_queue, simple_list);
611 BUG_ON(h->nsops != 1);
612 BUG_ON(h->sops[0].sem_num != q->sops[0].sem_num);
613
614 /* Yes, there is a wait-for-zero semop. Restart */
615 if (h->sops[0].sem_op == 0)
616 return 1;
617
618 /* Again - no-one is waiting for the new value. */
619 return 0;
620}
621
636c6be8
MS
622
623/**
624 * update_queue(sma, semnum): Look for tasks that can be completed.
625 * @sma: semaphore array.
626 * @semnum: semaphore that was modified.
0a2b9d4c 627 * @pt: list head for the tasks that must be woken up.
636c6be8
MS
628 *
629 * update_queue must be called after a semaphore in a semaphore array
630 * was modified. If multiple semaphore were modified, then @semnum
631 * must be set to -1.
0a2b9d4c
MS
632 * The tasks that must be woken up are added to @pt. The return code
633 * is stored in q->pid.
634 * The function return 1 if at least one semop was completed successfully.
1da177e4 635 */
0a2b9d4c 636static int update_queue(struct sem_array *sma, int semnum, struct list_head *pt)
1da177e4 637{
636c6be8
MS
638 struct sem_queue *q;
639 struct list_head *walk;
640 struct list_head *pending_list;
641 int offset;
0a2b9d4c 642 int semop_completed = 0;
636c6be8
MS
643
644 /* if there are complex operations around, then knowing the semaphore
645 * that was modified doesn't help us. Assume that multiple semaphores
646 * were modified.
647 */
648 if (sma->complex_count)
649 semnum = -1;
650
651 if (semnum == -1) {
652 pending_list = &sma->sem_pending;
653 offset = offsetof(struct sem_queue, list);
654 } else {
655 pending_list = &sma->sem_base[semnum].sem_pending;
656 offset = offsetof(struct sem_queue, simple_list);
657 }
9cad200c
NP
658
659again:
636c6be8
MS
660 walk = pending_list->next;
661 while (walk != pending_list) {
fd5db422 662 int error, restart;
636c6be8
MS
663
664 q = (struct sem_queue *)((char *)walk - offset);
665 walk = walk->next;
1da177e4 666
d987f8b2
MS
667 /* If we are scanning the single sop, per-semaphore list of
668 * one semaphore and that semaphore is 0, then it is not
669 * necessary to scan the "alter" entries: simple increments
670 * that affect only one entry succeed immediately and cannot
671 * be in the per semaphore pending queue, and decrements
672 * cannot be successful if the value is already 0.
673 */
674 if (semnum != -1 && sma->sem_base[semnum].semval == 0 &&
675 q->alter)
676 break;
677
1da177e4
LT
678 error = try_atomic_semop(sma, q->sops, q->nsops,
679 q->undo, q->pid);
680
681 /* Does q->sleeper still need to sleep? */
9cad200c
NP
682 if (error > 0)
683 continue;
684
b97e820f 685 unlink_queue(sma, q);
9cad200c 686
0a2b9d4c 687 if (error) {
fd5db422 688 restart = 0;
0a2b9d4c
MS
689 } else {
690 semop_completed = 1;
fd5db422 691 restart = check_restart(sma, q);
0a2b9d4c 692 }
fd5db422 693
0a2b9d4c 694 wake_up_sem_queue_prepare(pt, q, error);
fd5db422 695 if (restart)
9cad200c 696 goto again;
1da177e4 697 }
0a2b9d4c 698 return semop_completed;
1da177e4
LT
699}
700
0a2b9d4c
MS
701/**
702 * do_smart_update(sma, sops, nsops, otime, pt) - optimized update_queue
fd5db422
MS
703 * @sma: semaphore array
704 * @sops: operations that were performed
705 * @nsops: number of operations
0a2b9d4c
MS
706 * @otime: force setting otime
707 * @pt: list head of the tasks that must be woken up.
fd5db422
MS
708 *
709 * do_smart_update() does the required called to update_queue, based on the
710 * actual changes that were performed on the semaphore array.
0a2b9d4c
MS
711 * Note that the function does not do the actual wake-up: the caller is
712 * responsible for calling wake_up_sem_queue_do(@pt).
713 * It is safe to perform this call after dropping all locks.
fd5db422 714 */
0a2b9d4c
MS
715static void do_smart_update(struct sem_array *sma, struct sembuf *sops, int nsops,
716 int otime, struct list_head *pt)
fd5db422
MS
717{
718 int i;
719
720 if (sma->complex_count || sops == NULL) {
0a2b9d4c
MS
721 if (update_queue(sma, -1, pt))
722 otime = 1;
723 goto done;
fd5db422
MS
724 }
725
726 for (i = 0; i < nsops; i++) {
727 if (sops[i].sem_op > 0 ||
728 (sops[i].sem_op < 0 &&
729 sma->sem_base[sops[i].sem_num].semval == 0))
0a2b9d4c
MS
730 if (update_queue(sma, sops[i].sem_num, pt))
731 otime = 1;
fd5db422 732 }
0a2b9d4c
MS
733done:
734 if (otime)
735 sma->sem_otime = get_seconds();
fd5db422
MS
736}
737
738
1da177e4
LT
739/* The following counts are associated to each semaphore:
740 * semncnt number of tasks waiting on semval being nonzero
741 * semzcnt number of tasks waiting on semval being zero
742 * This model assumes that a task waits on exactly one semaphore.
743 * Since semaphore operations are to be performed atomically, tasks actually
744 * wait on a whole sequence of semaphores simultaneously.
745 * The counts we return here are a rough approximation, but still
746 * warrant that semncnt+semzcnt>0 if the task is on the pending queue.
747 */
748static int count_semncnt (struct sem_array * sma, ushort semnum)
749{
750 int semncnt;
751 struct sem_queue * q;
752
753 semncnt = 0;
a1193f8e 754 list_for_each_entry(q, &sma->sem_pending, list) {
1da177e4
LT
755 struct sembuf * sops = q->sops;
756 int nsops = q->nsops;
757 int i;
758 for (i = 0; i < nsops; i++)
759 if (sops[i].sem_num == semnum
760 && (sops[i].sem_op < 0)
761 && !(sops[i].sem_flg & IPC_NOWAIT))
762 semncnt++;
763 }
764 return semncnt;
765}
a1193f8e 766
1da177e4
LT
767static int count_semzcnt (struct sem_array * sma, ushort semnum)
768{
769 int semzcnt;
770 struct sem_queue * q;
771
772 semzcnt = 0;
a1193f8e 773 list_for_each_entry(q, &sma->sem_pending, list) {
1da177e4
LT
774 struct sembuf * sops = q->sops;
775 int nsops = q->nsops;
776 int i;
777 for (i = 0; i < nsops; i++)
778 if (sops[i].sem_num == semnum
779 && (sops[i].sem_op == 0)
780 && !(sops[i].sem_flg & IPC_NOWAIT))
781 semzcnt++;
782 }
783 return semzcnt;
784}
785
3e148c79
ND
786/* Free a semaphore set. freeary() is called with sem_ids.rw_mutex locked
787 * as a writer and the spinlock for this semaphore set hold. sem_ids.rw_mutex
788 * remains locked on exit.
1da177e4 789 */
01b8b07a 790static void freeary(struct ipc_namespace *ns, struct kern_ipc_perm *ipcp)
1da177e4 791{
380af1b3
MS
792 struct sem_undo *un, *tu;
793 struct sem_queue *q, *tq;
01b8b07a 794 struct sem_array *sma = container_of(ipcp, struct sem_array, sem_perm);
0a2b9d4c 795 struct list_head tasks;
1da177e4 796
380af1b3 797 /* Free the existing undo structures for this semaphore set. */
4daa28f6 798 assert_spin_locked(&sma->sem_perm.lock);
380af1b3
MS
799 list_for_each_entry_safe(un, tu, &sma->list_id, list_id) {
800 list_del(&un->list_id);
801 spin_lock(&un->ulp->lock);
1da177e4 802 un->semid = -1;
380af1b3
MS
803 list_del_rcu(&un->list_proc);
804 spin_unlock(&un->ulp->lock);
693a8b6e 805 kfree_rcu(un, rcu);
380af1b3 806 }
1da177e4
LT
807
808 /* Wake up all pending processes and let them fail with EIDRM. */
0a2b9d4c 809 INIT_LIST_HEAD(&tasks);
380af1b3 810 list_for_each_entry_safe(q, tq, &sma->sem_pending, list) {
b97e820f 811 unlink_queue(sma, q);
0a2b9d4c 812 wake_up_sem_queue_prepare(&tasks, q, -EIDRM);
1da177e4
LT
813 }
814
7ca7e564
ND
815 /* Remove the semaphore set from the IDR */
816 sem_rmid(ns, sma);
1da177e4
LT
817 sem_unlock(sma);
818
0a2b9d4c 819 wake_up_sem_queue_do(&tasks);
e3893534 820 ns->used_sems -= sma->sem_nsems;
1da177e4
LT
821 security_sem_free(sma);
822 ipc_rcu_putref(sma);
823}
824
825static unsigned long copy_semid_to_user(void __user *buf, struct semid64_ds *in, int version)
826{
827 switch(version) {
828 case IPC_64:
829 return copy_to_user(buf, in, sizeof(*in));
830 case IPC_OLD:
831 {
832 struct semid_ds out;
833
982f7c2b
DR
834 memset(&out, 0, sizeof(out));
835
1da177e4
LT
836 ipc64_perm_to_ipc_perm(&in->sem_perm, &out.sem_perm);
837
838 out.sem_otime = in->sem_otime;
839 out.sem_ctime = in->sem_ctime;
840 out.sem_nsems = in->sem_nsems;
841
842 return copy_to_user(buf, &out, sizeof(out));
843 }
844 default:
845 return -EINVAL;
846 }
847}
848
4b9fcb0e 849static int semctl_nolock(struct ipc_namespace *ns, int semid,
e1fd1f49 850 int cmd, int version, void __user *p)
1da177e4 851{
e5cc9c7b 852 int err;
1da177e4
LT
853 struct sem_array *sma;
854
855 switch(cmd) {
856 case IPC_INFO:
857 case SEM_INFO:
858 {
859 struct seminfo seminfo;
860 int max_id;
861
862 err = security_sem_semctl(NULL, cmd);
863 if (err)
864 return err;
865
866 memset(&seminfo,0,sizeof(seminfo));
e3893534
KK
867 seminfo.semmni = ns->sc_semmni;
868 seminfo.semmns = ns->sc_semmns;
869 seminfo.semmsl = ns->sc_semmsl;
870 seminfo.semopm = ns->sc_semopm;
1da177e4
LT
871 seminfo.semvmx = SEMVMX;
872 seminfo.semmnu = SEMMNU;
873 seminfo.semmap = SEMMAP;
874 seminfo.semume = SEMUME;
3e148c79 875 down_read(&sem_ids(ns).rw_mutex);
1da177e4 876 if (cmd == SEM_INFO) {
e3893534
KK
877 seminfo.semusz = sem_ids(ns).in_use;
878 seminfo.semaem = ns->used_sems;
1da177e4
LT
879 } else {
880 seminfo.semusz = SEMUSZ;
881 seminfo.semaem = SEMAEM;
882 }
7ca7e564 883 max_id = ipc_get_maxid(&sem_ids(ns));
3e148c79 884 up_read(&sem_ids(ns).rw_mutex);
e1fd1f49 885 if (copy_to_user(p, &seminfo, sizeof(struct seminfo)))
1da177e4
LT
886 return -EFAULT;
887 return (max_id < 0) ? 0: max_id;
888 }
4b9fcb0e 889 case IPC_STAT:
1da177e4
LT
890 case SEM_STAT:
891 {
892 struct semid64_ds tbuf;
16df3674
DB
893 int id = 0;
894
895 memset(&tbuf, 0, sizeof(tbuf));
1da177e4 896
4b9fcb0e 897 if (cmd == SEM_STAT) {
16df3674
DB
898 rcu_read_lock();
899 sma = sem_obtain_object(ns, semid);
900 if (IS_ERR(sma)) {
901 err = PTR_ERR(sma);
902 goto out_unlock;
903 }
4b9fcb0e
PP
904 id = sma->sem_perm.id;
905 } else {
16df3674
DB
906 rcu_read_lock();
907 sma = sem_obtain_object_check(ns, semid);
908 if (IS_ERR(sma)) {
909 err = PTR_ERR(sma);
910 goto out_unlock;
911 }
4b9fcb0e 912 }
1da177e4
LT
913
914 err = -EACCES;
b0e77598 915 if (ipcperms(ns, &sma->sem_perm, S_IRUGO))
1da177e4
LT
916 goto out_unlock;
917
918 err = security_sem_semctl(sma, cmd);
919 if (err)
920 goto out_unlock;
921
1da177e4
LT
922 kernel_to_ipc64_perm(&sma->sem_perm, &tbuf.sem_perm);
923 tbuf.sem_otime = sma->sem_otime;
924 tbuf.sem_ctime = sma->sem_ctime;
925 tbuf.sem_nsems = sma->sem_nsems;
16df3674 926 rcu_read_unlock();
e1fd1f49 927 if (copy_semid_to_user(p, &tbuf, version))
1da177e4
LT
928 return -EFAULT;
929 return id;
930 }
931 default:
932 return -EINVAL;
933 }
1da177e4 934out_unlock:
16df3674 935 rcu_read_unlock();
1da177e4
LT
936 return err;
937}
938
e1fd1f49
AV
939static int semctl_setval(struct ipc_namespace *ns, int semid, int semnum,
940 unsigned long arg)
941{
942 struct sem_undo *un;
943 struct sem_array *sma;
944 struct sem* curr;
945 int err;
946 int nsems;
947 struct list_head tasks;
948 int val;
949#if defined(CONFIG_64BIT) && defined(__BIG_ENDIAN)
950 /* big-endian 64bit */
951 val = arg >> 32;
952#else
953 /* 32bit or little-endian 64bit */
954 val = arg;
955#endif
956
957 sma = sem_lock_check(ns, semid);
958 if (IS_ERR(sma))
959 return PTR_ERR(sma);
960
961 INIT_LIST_HEAD(&tasks);
962 nsems = sma->sem_nsems;
963
964 err = -EACCES;
965 if (ipcperms(ns, &sma->sem_perm, S_IWUGO))
966 goto out_unlock;
967
968 err = security_sem_semctl(sma, SETVAL);
969 if (err)
970 goto out_unlock;
971
972 err = -EINVAL;
973 if(semnum < 0 || semnum >= nsems)
974 goto out_unlock;
975
976 curr = &sma->sem_base[semnum];
977
978 err = -ERANGE;
979 if (val > SEMVMX || val < 0)
980 goto out_unlock;
981
982 assert_spin_locked(&sma->sem_perm.lock);
983 list_for_each_entry(un, &sma->list_id, list_id)
984 un->semadj[semnum] = 0;
985
986 curr->semval = val;
987 curr->sempid = task_tgid_vnr(current);
988 sma->sem_ctime = get_seconds();
989 /* maybe some queued-up processes were waiting for this */
990 do_smart_update(sma, NULL, 0, 0, &tasks);
991 err = 0;
992out_unlock:
993 sem_unlock(sma);
994 wake_up_sem_queue_do(&tasks);
995 return err;
996}
997
e3893534 998static int semctl_main(struct ipc_namespace *ns, int semid, int semnum,
e1fd1f49 999 int cmd, void __user *p)
1da177e4
LT
1000{
1001 struct sem_array *sma;
1002 struct sem* curr;
16df3674 1003 int err, nsems;
1da177e4
LT
1004 ushort fast_sem_io[SEMMSL_FAST];
1005 ushort* sem_io = fast_sem_io;
0a2b9d4c 1006 struct list_head tasks;
1da177e4 1007
16df3674
DB
1008 INIT_LIST_HEAD(&tasks);
1009
1010 rcu_read_lock();
1011 sma = sem_obtain_object_check(ns, semid);
1012 if (IS_ERR(sma)) {
1013 rcu_read_unlock();
023a5355 1014 return PTR_ERR(sma);
16df3674 1015 }
1da177e4
LT
1016
1017 nsems = sma->sem_nsems;
1018
1da177e4 1019 err = -EACCES;
b0e77598 1020 if (ipcperms(ns, &sma->sem_perm,
16df3674
DB
1021 cmd == SETALL ? S_IWUGO : S_IRUGO)) {
1022 rcu_read_unlock();
1023 goto out_wakeup;
1024 }
1da177e4
LT
1025
1026 err = security_sem_semctl(sma, cmd);
16df3674
DB
1027 if (err) {
1028 rcu_read_unlock();
1029 goto out_wakeup;
1030 }
1da177e4
LT
1031
1032 err = -EACCES;
1033 switch (cmd) {
1034 case GETALL:
1035 {
e1fd1f49 1036 ushort __user *array = p;
1da177e4
LT
1037 int i;
1038
1039 if(nsems > SEMMSL_FAST) {
16df3674 1040 sem_getref(sma);
1da177e4
LT
1041
1042 sem_io = ipc_alloc(sizeof(ushort)*nsems);
1043 if(sem_io == NULL) {
6ff37972 1044 sem_putref(sma);
1da177e4
LT
1045 return -ENOMEM;
1046 }
1047
6ff37972 1048 sem_lock_and_putref(sma);
1da177e4
LT
1049 if (sma->sem_perm.deleted) {
1050 sem_unlock(sma);
1051 err = -EIDRM;
1052 goto out_free;
1053 }
1054 }
1055
16df3674 1056 spin_lock(&sma->sem_perm.lock);
1da177e4
LT
1057 for (i = 0; i < sma->sem_nsems; i++)
1058 sem_io[i] = sma->sem_base[i].semval;
1059 sem_unlock(sma);
1060 err = 0;
1061 if(copy_to_user(array, sem_io, nsems*sizeof(ushort)))
1062 err = -EFAULT;
1063 goto out_free;
1064 }
1065 case SETALL:
1066 {
1067 int i;
1068 struct sem_undo *un;
1069
16df3674
DB
1070 ipc_rcu_getref(sma);
1071 rcu_read_unlock();
1da177e4
LT
1072
1073 if(nsems > SEMMSL_FAST) {
1074 sem_io = ipc_alloc(sizeof(ushort)*nsems);
1075 if(sem_io == NULL) {
6ff37972 1076 sem_putref(sma);
1da177e4
LT
1077 return -ENOMEM;
1078 }
1079 }
1080
e1fd1f49 1081 if (copy_from_user (sem_io, p, nsems*sizeof(ushort))) {
6ff37972 1082 sem_putref(sma);
1da177e4
LT
1083 err = -EFAULT;
1084 goto out_free;
1085 }
1086
1087 for (i = 0; i < nsems; i++) {
1088 if (sem_io[i] > SEMVMX) {
6ff37972 1089 sem_putref(sma);
1da177e4
LT
1090 err = -ERANGE;
1091 goto out_free;
1092 }
1093 }
6ff37972 1094 sem_lock_and_putref(sma);
1da177e4
LT
1095 if (sma->sem_perm.deleted) {
1096 sem_unlock(sma);
1097 err = -EIDRM;
1098 goto out_free;
1099 }
1100
1101 for (i = 0; i < nsems; i++)
1102 sma->sem_base[i].semval = sem_io[i];
4daa28f6
MS
1103
1104 assert_spin_locked(&sma->sem_perm.lock);
1105 list_for_each_entry(un, &sma->list_id, list_id) {
1da177e4
LT
1106 for (i = 0; i < nsems; i++)
1107 un->semadj[i] = 0;
4daa28f6 1108 }
1da177e4
LT
1109 sma->sem_ctime = get_seconds();
1110 /* maybe some queued-up processes were waiting for this */
0a2b9d4c 1111 do_smart_update(sma, NULL, 0, 0, &tasks);
1da177e4
LT
1112 err = 0;
1113 goto out_unlock;
1114 }
e1fd1f49 1115 /* GETVAL, GETPID, GETNCTN, GETZCNT: fall-through */
1da177e4
LT
1116 }
1117 err = -EINVAL;
16df3674
DB
1118 if (semnum < 0 || semnum >= nsems) {
1119 rcu_read_unlock();
1120 goto out_wakeup;
1121 }
1da177e4 1122
16df3674 1123 spin_lock(&sma->sem_perm.lock);
1da177e4
LT
1124 curr = &sma->sem_base[semnum];
1125
1126 switch (cmd) {
1127 case GETVAL:
1128 err = curr->semval;
1129 goto out_unlock;
1130 case GETPID:
1131 err = curr->sempid;
1132 goto out_unlock;
1133 case GETNCNT:
1134 err = count_semncnt(sma,semnum);
1135 goto out_unlock;
1136 case GETZCNT:
1137 err = count_semzcnt(sma,semnum);
1138 goto out_unlock;
1da177e4 1139 }
16df3674 1140
1da177e4
LT
1141out_unlock:
1142 sem_unlock(sma);
16df3674 1143out_wakeup:
0a2b9d4c 1144 wake_up_sem_queue_do(&tasks);
1da177e4
LT
1145out_free:
1146 if(sem_io != fast_sem_io)
1147 ipc_free(sem_io, sizeof(ushort)*nsems);
1148 return err;
1149}
1150
016d7132
PP
1151static inline unsigned long
1152copy_semid_from_user(struct semid64_ds *out, void __user *buf, int version)
1da177e4
LT
1153{
1154 switch(version) {
1155 case IPC_64:
016d7132 1156 if (copy_from_user(out, buf, sizeof(*out)))
1da177e4 1157 return -EFAULT;
1da177e4 1158 return 0;
1da177e4
LT
1159 case IPC_OLD:
1160 {
1161 struct semid_ds tbuf_old;
1162
1163 if(copy_from_user(&tbuf_old, buf, sizeof(tbuf_old)))
1164 return -EFAULT;
1165
016d7132
PP
1166 out->sem_perm.uid = tbuf_old.sem_perm.uid;
1167 out->sem_perm.gid = tbuf_old.sem_perm.gid;
1168 out->sem_perm.mode = tbuf_old.sem_perm.mode;
1da177e4
LT
1169
1170 return 0;
1171 }
1172 default:
1173 return -EINVAL;
1174 }
1175}
1176
522bb2a2
PP
1177/*
1178 * This function handles some semctl commands which require the rw_mutex
1179 * to be held in write mode.
1180 * NOTE: no locks must be held, the rw_mutex is taken inside this function.
1181 */
21a4826a 1182static int semctl_down(struct ipc_namespace *ns, int semid,
e1fd1f49 1183 int cmd, int version, void __user *p)
1da177e4
LT
1184{
1185 struct sem_array *sma;
1186 int err;
016d7132 1187 struct semid64_ds semid64;
1da177e4
LT
1188 struct kern_ipc_perm *ipcp;
1189
1190 if(cmd == IPC_SET) {
e1fd1f49 1191 if (copy_semid_from_user(&semid64, p, version))
1da177e4 1192 return -EFAULT;
1da177e4 1193 }
073115d6 1194
16df3674
DB
1195 ipcp = ipcctl_pre_down_nolock(ns, &sem_ids(ns), semid, cmd,
1196 &semid64.sem_perm, 0);
a5f75e7f
PP
1197 if (IS_ERR(ipcp))
1198 return PTR_ERR(ipcp);
073115d6 1199
a5f75e7f 1200 sma = container_of(ipcp, struct sem_array, sem_perm);
1da177e4
LT
1201
1202 err = security_sem_semctl(sma, cmd);
16df3674
DB
1203 if (err) {
1204 rcu_read_unlock();
1da177e4 1205 goto out_unlock;
16df3674 1206 }
1da177e4
LT
1207
1208 switch(cmd){
1209 case IPC_RMID:
16df3674 1210 ipc_lock_object(&sma->sem_perm);
01b8b07a 1211 freeary(ns, ipcp);
522bb2a2 1212 goto out_up;
1da177e4 1213 case IPC_SET:
16df3674 1214 ipc_lock_object(&sma->sem_perm);
1efdb69b
EB
1215 err = ipc_update_perm(&semid64.sem_perm, ipcp);
1216 if (err)
1217 goto out_unlock;
1da177e4 1218 sma->sem_ctime = get_seconds();
1da177e4
LT
1219 break;
1220 default:
16df3674 1221 rcu_read_unlock();
1da177e4 1222 err = -EINVAL;
16df3674 1223 goto out_up;
1da177e4 1224 }
1da177e4
LT
1225
1226out_unlock:
1227 sem_unlock(sma);
522bb2a2
PP
1228out_up:
1229 up_write(&sem_ids(ns).rw_mutex);
1da177e4
LT
1230 return err;
1231}
1232
e1fd1f49 1233SYSCALL_DEFINE4(semctl, int, semid, int, semnum, int, cmd, unsigned long, arg)
1da177e4 1234{
1da177e4 1235 int version;
e3893534 1236 struct ipc_namespace *ns;
e1fd1f49 1237 void __user *p = (void __user *)arg;
1da177e4
LT
1238
1239 if (semid < 0)
1240 return -EINVAL;
1241
1242 version = ipc_parse_version(&cmd);
e3893534 1243 ns = current->nsproxy->ipc_ns;
1da177e4
LT
1244
1245 switch(cmd) {
1246 case IPC_INFO:
1247 case SEM_INFO:
4b9fcb0e 1248 case IPC_STAT:
1da177e4 1249 case SEM_STAT:
e1fd1f49 1250 return semctl_nolock(ns, semid, cmd, version, p);
1da177e4
LT
1251 case GETALL:
1252 case GETVAL:
1253 case GETPID:
1254 case GETNCNT:
1255 case GETZCNT:
1da177e4 1256 case SETALL:
e1fd1f49
AV
1257 return semctl_main(ns, semid, semnum, cmd, p);
1258 case SETVAL:
1259 return semctl_setval(ns, semid, semnum, arg);
1da177e4
LT
1260 case IPC_RMID:
1261 case IPC_SET:
e1fd1f49 1262 return semctl_down(ns, semid, cmd, version, p);
1da177e4
LT
1263 default:
1264 return -EINVAL;
1265 }
1266}
1267
1da177e4
LT
1268/* If the task doesn't already have a undo_list, then allocate one
1269 * here. We guarantee there is only one thread using this undo list,
1270 * and current is THE ONE
1271 *
1272 * If this allocation and assignment succeeds, but later
1273 * portions of this code fail, there is no need to free the sem_undo_list.
1274 * Just let it stay associated with the task, and it'll be freed later
1275 * at exit time.
1276 *
1277 * This can block, so callers must hold no locks.
1278 */
1279static inline int get_undo_list(struct sem_undo_list **undo_listp)
1280{
1281 struct sem_undo_list *undo_list;
1da177e4
LT
1282
1283 undo_list = current->sysvsem.undo_list;
1284 if (!undo_list) {
2453a306 1285 undo_list = kzalloc(sizeof(*undo_list), GFP_KERNEL);
1da177e4
LT
1286 if (undo_list == NULL)
1287 return -ENOMEM;
00a5dfdb 1288 spin_lock_init(&undo_list->lock);
1da177e4 1289 atomic_set(&undo_list->refcnt, 1);
4daa28f6
MS
1290 INIT_LIST_HEAD(&undo_list->list_proc);
1291
1da177e4
LT
1292 current->sysvsem.undo_list = undo_list;
1293 }
1294 *undo_listp = undo_list;
1295 return 0;
1296}
1297
bf17bb71 1298static struct sem_undo *__lookup_undo(struct sem_undo_list *ulp, int semid)
1da177e4 1299{
bf17bb71 1300 struct sem_undo *un;
4daa28f6 1301
bf17bb71
NP
1302 list_for_each_entry_rcu(un, &ulp->list_proc, list_proc) {
1303 if (un->semid == semid)
1304 return un;
1da177e4 1305 }
4daa28f6 1306 return NULL;
1da177e4
LT
1307}
1308
bf17bb71
NP
1309static struct sem_undo *lookup_undo(struct sem_undo_list *ulp, int semid)
1310{
1311 struct sem_undo *un;
1312
1313 assert_spin_locked(&ulp->lock);
1314
1315 un = __lookup_undo(ulp, semid);
1316 if (un) {
1317 list_del_rcu(&un->list_proc);
1318 list_add_rcu(&un->list_proc, &ulp->list_proc);
1319 }
1320 return un;
1321}
1322
4daa28f6
MS
1323/**
1324 * find_alloc_undo - Lookup (and if not present create) undo array
1325 * @ns: namespace
1326 * @semid: semaphore array id
1327 *
1328 * The function looks up (and if not present creates) the undo structure.
1329 * The size of the undo structure depends on the size of the semaphore
1330 * array, thus the alloc path is not that straightforward.
380af1b3
MS
1331 * Lifetime-rules: sem_undo is rcu-protected, on success, the function
1332 * performs a rcu_read_lock().
4daa28f6
MS
1333 */
1334static struct sem_undo *find_alloc_undo(struct ipc_namespace *ns, int semid)
1da177e4
LT
1335{
1336 struct sem_array *sma;
1337 struct sem_undo_list *ulp;
1338 struct sem_undo *un, *new;
1339 int nsems;
1340 int error;
1341
1342 error = get_undo_list(&ulp);
1343 if (error)
1344 return ERR_PTR(error);
1345
380af1b3 1346 rcu_read_lock();
c530c6ac 1347 spin_lock(&ulp->lock);
1da177e4 1348 un = lookup_undo(ulp, semid);
c530c6ac 1349 spin_unlock(&ulp->lock);
1da177e4
LT
1350 if (likely(un!=NULL))
1351 goto out;
1352
1353 /* no undo structure around - allocate one. */
4daa28f6 1354 /* step 1: figure out the size of the semaphore array */
16df3674
DB
1355 sma = sem_obtain_object_check(ns, semid);
1356 if (IS_ERR(sma)) {
1357 rcu_read_unlock();
4de85cd6 1358 return ERR_CAST(sma);
16df3674 1359 }
023a5355 1360
1da177e4 1361 nsems = sma->sem_nsems;
16df3674
DB
1362 ipc_rcu_getref(sma);
1363 rcu_read_unlock();
1da177e4 1364
4daa28f6 1365 /* step 2: allocate new undo structure */
4668edc3 1366 new = kzalloc(sizeof(struct sem_undo) + sizeof(short)*nsems, GFP_KERNEL);
1da177e4 1367 if (!new) {
6ff37972 1368 sem_putref(sma);
1da177e4
LT
1369 return ERR_PTR(-ENOMEM);
1370 }
1da177e4 1371
380af1b3 1372 /* step 3: Acquire the lock on semaphore array */
6ff37972 1373 sem_lock_and_putref(sma);
1da177e4
LT
1374 if (sma->sem_perm.deleted) {
1375 sem_unlock(sma);
1da177e4
LT
1376 kfree(new);
1377 un = ERR_PTR(-EIDRM);
1378 goto out;
1379 }
380af1b3
MS
1380 spin_lock(&ulp->lock);
1381
1382 /*
1383 * step 4: check for races: did someone else allocate the undo struct?
1384 */
1385 un = lookup_undo(ulp, semid);
1386 if (un) {
1387 kfree(new);
1388 goto success;
1389 }
4daa28f6
MS
1390 /* step 5: initialize & link new undo structure */
1391 new->semadj = (short *) &new[1];
380af1b3 1392 new->ulp = ulp;
4daa28f6
MS
1393 new->semid = semid;
1394 assert_spin_locked(&ulp->lock);
380af1b3 1395 list_add_rcu(&new->list_proc, &ulp->list_proc);
4daa28f6
MS
1396 assert_spin_locked(&sma->sem_perm.lock);
1397 list_add(&new->list_id, &sma->list_id);
380af1b3 1398 un = new;
4daa28f6 1399
380af1b3 1400success:
c530c6ac 1401 spin_unlock(&ulp->lock);
380af1b3
MS
1402 rcu_read_lock();
1403 sem_unlock(sma);
1da177e4
LT
1404out:
1405 return un;
1406}
1407
c61284e9
MS
1408
1409/**
1410 * get_queue_result - Retrieve the result code from sem_queue
1411 * @q: Pointer to queue structure
1412 *
1413 * Retrieve the return code from the pending queue. If IN_WAKEUP is found in
1414 * q->status, then we must loop until the value is replaced with the final
1415 * value: This may happen if a task is woken up by an unrelated event (e.g.
1416 * signal) and in parallel the task is woken up by another task because it got
1417 * the requested semaphores.
1418 *
1419 * The function can be called with or without holding the semaphore spinlock.
1420 */
1421static int get_queue_result(struct sem_queue *q)
1422{
1423 int error;
1424
1425 error = q->status;
1426 while (unlikely(error == IN_WAKEUP)) {
1427 cpu_relax();
1428 error = q->status;
1429 }
1430
1431 return error;
1432}
1433
1434
d5460c99
HC
1435SYSCALL_DEFINE4(semtimedop, int, semid, struct sembuf __user *, tsops,
1436 unsigned, nsops, const struct timespec __user *, timeout)
1da177e4
LT
1437{
1438 int error = -EINVAL;
1439 struct sem_array *sma;
1440 struct sembuf fast_sops[SEMOPM_FAST];
1441 struct sembuf* sops = fast_sops, *sop;
1442 struct sem_undo *un;
b78755ab 1443 int undos = 0, alter = 0, max;
1da177e4
LT
1444 struct sem_queue queue;
1445 unsigned long jiffies_left = 0;
e3893534 1446 struct ipc_namespace *ns;
0a2b9d4c 1447 struct list_head tasks;
e3893534
KK
1448
1449 ns = current->nsproxy->ipc_ns;
1da177e4
LT
1450
1451 if (nsops < 1 || semid < 0)
1452 return -EINVAL;
e3893534 1453 if (nsops > ns->sc_semopm)
1da177e4
LT
1454 return -E2BIG;
1455 if(nsops > SEMOPM_FAST) {
1456 sops = kmalloc(sizeof(*sops)*nsops,GFP_KERNEL);
1457 if(sops==NULL)
1458 return -ENOMEM;
1459 }
1460 if (copy_from_user (sops, tsops, nsops * sizeof(*tsops))) {
1461 error=-EFAULT;
1462 goto out_free;
1463 }
1464 if (timeout) {
1465 struct timespec _timeout;
1466 if (copy_from_user(&_timeout, timeout, sizeof(*timeout))) {
1467 error = -EFAULT;
1468 goto out_free;
1469 }
1470 if (_timeout.tv_sec < 0 || _timeout.tv_nsec < 0 ||
1471 _timeout.tv_nsec >= 1000000000L) {
1472 error = -EINVAL;
1473 goto out_free;
1474 }
1475 jiffies_left = timespec_to_jiffies(&_timeout);
1476 }
1477 max = 0;
1478 for (sop = sops; sop < sops + nsops; sop++) {
1479 if (sop->sem_num >= max)
1480 max = sop->sem_num;
1481 if (sop->sem_flg & SEM_UNDO)
b78755ab
MS
1482 undos = 1;
1483 if (sop->sem_op != 0)
1da177e4
LT
1484 alter = 1;
1485 }
1da177e4 1486
1da177e4 1487 if (undos) {
4daa28f6 1488 un = find_alloc_undo(ns, semid);
1da177e4
LT
1489 if (IS_ERR(un)) {
1490 error = PTR_ERR(un);
1491 goto out_free;
1492 }
1493 } else
1494 un = NULL;
1495
0a2b9d4c
MS
1496 INIT_LIST_HEAD(&tasks);
1497
16df3674
DB
1498 rcu_read_lock();
1499 sma = sem_obtain_object_check(ns, semid);
023a5355 1500 if (IS_ERR(sma)) {
380af1b3
MS
1501 if (un)
1502 rcu_read_unlock();
023a5355 1503 error = PTR_ERR(sma);
1da177e4 1504 goto out_free;
023a5355
ND
1505 }
1506
16df3674
DB
1507 error = -EFBIG;
1508 if (max >= sma->sem_nsems) {
1509 rcu_read_unlock();
1510 goto out_wakeup;
1511 }
1512
1513 error = -EACCES;
1514 if (ipcperms(ns, &sma->sem_perm, alter ? S_IWUGO : S_IRUGO)) {
1515 rcu_read_unlock();
1516 goto out_wakeup;
1517 }
1518
1519 error = security_sem_semop(sma, sops, nsops, alter);
1520 if (error) {
1521 rcu_read_unlock();
1522 goto out_wakeup;
1523 }
1524
1da177e4 1525 /*
4daa28f6 1526 * semid identifiers are not unique - find_alloc_undo may have
1da177e4 1527 * allocated an undo structure, it was invalidated by an RMID
4daa28f6 1528 * and now a new array with received the same id. Check and fail.
25985edc 1529 * This case can be detected checking un->semid. The existence of
380af1b3 1530 * "un" itself is guaranteed by rcu.
1da177e4 1531 */
4daa28f6 1532 error = -EIDRM;
16df3674 1533 ipc_lock_object(&sma->sem_perm);
380af1b3
MS
1534 if (un) {
1535 if (un->semid == -1) {
1536 rcu_read_unlock();
1537 goto out_unlock_free;
1538 } else {
1539 /*
1540 * rcu lock can be released, "un" cannot disappear:
1541 * - sem_lock is acquired, thus IPC_RMID is
1542 * impossible.
1543 * - exit_sem is impossible, it always operates on
1544 * current (or a dead task).
1545 */
1546
1547 rcu_read_unlock();
1548 }
1549 }
4daa28f6 1550
b488893a 1551 error = try_atomic_semop (sma, sops, nsops, un, task_tgid_vnr(current));
1da177e4
LT
1552 if (error <= 0) {
1553 if (alter && error == 0)
0a2b9d4c 1554 do_smart_update(sma, sops, nsops, 1, &tasks);
636c6be8 1555
1da177e4
LT
1556 goto out_unlock_free;
1557 }
1558
1559 /* We need to sleep on this operation, so we put the current
1560 * task into the pending queue and go to sleep.
1561 */
1562
1da177e4
LT
1563 queue.sops = sops;
1564 queue.nsops = nsops;
1565 queue.undo = un;
b488893a 1566 queue.pid = task_tgid_vnr(current);
1da177e4
LT
1567 queue.alter = alter;
1568 if (alter)
a1193f8e 1569 list_add_tail(&queue.list, &sma->sem_pending);
1da177e4 1570 else
a1193f8e 1571 list_add(&queue.list, &sma->sem_pending);
1da177e4 1572
b97e820f
MS
1573 if (nsops == 1) {
1574 struct sem *curr;
1575 curr = &sma->sem_base[sops->sem_num];
1576
1577 if (alter)
1578 list_add_tail(&queue.simple_list, &curr->sem_pending);
1579 else
1580 list_add(&queue.simple_list, &curr->sem_pending);
1581 } else {
1582 INIT_LIST_HEAD(&queue.simple_list);
1583 sma->complex_count++;
1584 }
1585
1da177e4
LT
1586 queue.status = -EINTR;
1587 queue.sleeper = current;
0b0577f6
MS
1588
1589sleep_again:
1da177e4
LT
1590 current->state = TASK_INTERRUPTIBLE;
1591 sem_unlock(sma);
1592
1593 if (timeout)
1594 jiffies_left = schedule_timeout(jiffies_left);
1595 else
1596 schedule();
1597
c61284e9 1598 error = get_queue_result(&queue);
1da177e4
LT
1599
1600 if (error != -EINTR) {
1601 /* fast path: update_queue already obtained all requested
c61284e9
MS
1602 * resources.
1603 * Perform a smp_mb(): User space could assume that semop()
1604 * is a memory barrier: Without the mb(), the cpu could
1605 * speculatively read in user space stale data that was
1606 * overwritten by the previous owner of the semaphore.
1607 */
1608 smp_mb();
1609
1da177e4
LT
1610 goto out_free;
1611 }
1612
c460b662 1613 sma = sem_obtain_lock(ns, semid);
d694ad62
MS
1614
1615 /*
1616 * Wait until it's guaranteed that no wakeup_sem_queue_do() is ongoing.
1617 */
1618 error = get_queue_result(&queue);
1619
1620 /*
1621 * Array removed? If yes, leave without sem_unlock().
1622 */
023a5355 1623 if (IS_ERR(sma)) {
1da177e4
LT
1624 goto out_free;
1625 }
1626
c61284e9 1627
1da177e4 1628 /*
d694ad62
MS
1629 * If queue.status != -EINTR we are woken up by another process.
1630 * Leave without unlink_queue(), but with sem_unlock().
1da177e4 1631 */
c61284e9 1632
1da177e4
LT
1633 if (error != -EINTR) {
1634 goto out_unlock_free;
1635 }
1636
1637 /*
1638 * If an interrupt occurred we have to clean up the queue
1639 */
1640 if (timeout && jiffies_left == 0)
1641 error = -EAGAIN;
0b0577f6
MS
1642
1643 /*
1644 * If the wakeup was spurious, just retry
1645 */
1646 if (error == -EINTR && !signal_pending(current))
1647 goto sleep_again;
1648
b97e820f 1649 unlink_queue(sma, &queue);
1da177e4
LT
1650
1651out_unlock_free:
1652 sem_unlock(sma);
16df3674 1653out_wakeup:
0a2b9d4c 1654 wake_up_sem_queue_do(&tasks);
1da177e4
LT
1655out_free:
1656 if(sops != fast_sops)
1657 kfree(sops);
1658 return error;
1659}
1660
d5460c99
HC
1661SYSCALL_DEFINE3(semop, int, semid, struct sembuf __user *, tsops,
1662 unsigned, nsops)
1da177e4
LT
1663{
1664 return sys_semtimedop(semid, tsops, nsops, NULL);
1665}
1666
1667/* If CLONE_SYSVSEM is set, establish sharing of SEM_UNDO state between
1668 * parent and child tasks.
1da177e4
LT
1669 */
1670
1671int copy_semundo(unsigned long clone_flags, struct task_struct *tsk)
1672{
1673 struct sem_undo_list *undo_list;
1674 int error;
1675
1676 if (clone_flags & CLONE_SYSVSEM) {
1677 error = get_undo_list(&undo_list);
1678 if (error)
1679 return error;
1da177e4
LT
1680 atomic_inc(&undo_list->refcnt);
1681 tsk->sysvsem.undo_list = undo_list;
1682 } else
1683 tsk->sysvsem.undo_list = NULL;
1684
1685 return 0;
1686}
1687
1688/*
1689 * add semadj values to semaphores, free undo structures.
1690 * undo structures are not freed when semaphore arrays are destroyed
1691 * so some of them may be out of date.
1692 * IMPLEMENTATION NOTE: There is some confusion over whether the
1693 * set of adjustments that needs to be done should be done in an atomic
1694 * manner or not. That is, if we are attempting to decrement the semval
1695 * should we queue up and wait until we can do so legally?
1696 * The original implementation attempted to do this (queue and wait).
1697 * The current implementation does not do so. The POSIX standard
1698 * and SVID should be consulted to determine what behavior is mandated.
1699 */
1700void exit_sem(struct task_struct *tsk)
1701{
4daa28f6 1702 struct sem_undo_list *ulp;
1da177e4 1703
4daa28f6
MS
1704 ulp = tsk->sysvsem.undo_list;
1705 if (!ulp)
1da177e4 1706 return;
9edff4ab 1707 tsk->sysvsem.undo_list = NULL;
1da177e4 1708
4daa28f6 1709 if (!atomic_dec_and_test(&ulp->refcnt))
1da177e4
LT
1710 return;
1711
380af1b3 1712 for (;;) {
1da177e4 1713 struct sem_array *sma;
380af1b3 1714 struct sem_undo *un;
0a2b9d4c 1715 struct list_head tasks;
380af1b3 1716 int semid;
4daa28f6
MS
1717 int i;
1718
380af1b3 1719 rcu_read_lock();
05725f7e
JP
1720 un = list_entry_rcu(ulp->list_proc.next,
1721 struct sem_undo, list_proc);
380af1b3
MS
1722 if (&un->list_proc == &ulp->list_proc)
1723 semid = -1;
1724 else
1725 semid = un->semid;
1726 rcu_read_unlock();
4daa28f6 1727
380af1b3
MS
1728 if (semid == -1)
1729 break;
1da177e4 1730
380af1b3 1731 sma = sem_lock_check(tsk->nsproxy->ipc_ns, un->semid);
1da177e4 1732
380af1b3
MS
1733 /* exit_sem raced with IPC_RMID, nothing to do */
1734 if (IS_ERR(sma))
1735 continue;
1da177e4 1736
bf17bb71 1737 un = __lookup_undo(ulp, semid);
380af1b3
MS
1738 if (un == NULL) {
1739 /* exit_sem raced with IPC_RMID+semget() that created
1740 * exactly the same semid. Nothing to do.
1741 */
1742 sem_unlock(sma);
1743 continue;
1744 }
1745
1746 /* remove un from the linked lists */
4daa28f6
MS
1747 assert_spin_locked(&sma->sem_perm.lock);
1748 list_del(&un->list_id);
1749
380af1b3
MS
1750 spin_lock(&ulp->lock);
1751 list_del_rcu(&un->list_proc);
1752 spin_unlock(&ulp->lock);
1753
4daa28f6
MS
1754 /* perform adjustments registered in un */
1755 for (i = 0; i < sma->sem_nsems; i++) {
5f921ae9 1756 struct sem * semaphore = &sma->sem_base[i];
4daa28f6
MS
1757 if (un->semadj[i]) {
1758 semaphore->semval += un->semadj[i];
1da177e4
LT
1759 /*
1760 * Range checks of the new semaphore value,
1761 * not defined by sus:
1762 * - Some unices ignore the undo entirely
1763 * (e.g. HP UX 11i 11.22, Tru64 V5.1)
1764 * - some cap the value (e.g. FreeBSD caps
1765 * at 0, but doesn't enforce SEMVMX)
1766 *
1767 * Linux caps the semaphore value, both at 0
1768 * and at SEMVMX.
1769 *
1770 * Manfred <manfred@colorfullife.com>
1771 */
5f921ae9
IM
1772 if (semaphore->semval < 0)
1773 semaphore->semval = 0;
1774 if (semaphore->semval > SEMVMX)
1775 semaphore->semval = SEMVMX;
b488893a 1776 semaphore->sempid = task_tgid_vnr(current);
1da177e4
LT
1777 }
1778 }
1da177e4 1779 /* maybe some queued-up processes were waiting for this */
0a2b9d4c
MS
1780 INIT_LIST_HEAD(&tasks);
1781 do_smart_update(sma, NULL, 0, 1, &tasks);
1da177e4 1782 sem_unlock(sma);
0a2b9d4c 1783 wake_up_sem_queue_do(&tasks);
380af1b3 1784
693a8b6e 1785 kfree_rcu(un, rcu);
1da177e4 1786 }
4daa28f6 1787 kfree(ulp);
1da177e4
LT
1788}
1789
1790#ifdef CONFIG_PROC_FS
19b4946c 1791static int sysvipc_sem_proc_show(struct seq_file *s, void *it)
1da177e4 1792{
1efdb69b 1793 struct user_namespace *user_ns = seq_user_ns(s);
19b4946c
MW
1794 struct sem_array *sma = it;
1795
1796 return seq_printf(s,
b97e820f 1797 "%10d %10d %4o %10u %5u %5u %5u %5u %10lu %10lu\n",
19b4946c 1798 sma->sem_perm.key,
7ca7e564 1799 sma->sem_perm.id,
19b4946c
MW
1800 sma->sem_perm.mode,
1801 sma->sem_nsems,
1efdb69b
EB
1802 from_kuid_munged(user_ns, sma->sem_perm.uid),
1803 from_kgid_munged(user_ns, sma->sem_perm.gid),
1804 from_kuid_munged(user_ns, sma->sem_perm.cuid),
1805 from_kgid_munged(user_ns, sma->sem_perm.cgid),
19b4946c
MW
1806 sma->sem_otime,
1807 sma->sem_ctime);
1da177e4
LT
1808}
1809#endif