]> git.ipfire.org Git - thirdparty/linux.git/blame - ipc/sem.c
ipc/sem: drop sem_checkid helper
[thirdparty/linux.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>
9ae949fa 14 * (c) 2016 Davidlohr Bueso <dave@stgolabs.net>
c5cf6359
MS
15 * Further wakeup optimizations, documentation
16 * (c) 2010 Manfred Spraul <manfred@colorfullife.com>
073115d6
SG
17 *
18 * support for audit of ipc object properties and permission changes
19 * Dustin Kirkland <dustin.kirkland@us.ibm.com>
e3893534
KK
20 *
21 * namespaces support
22 * OpenVZ, SWsoft Inc.
23 * Pavel Emelianov <xemul@openvz.org>
c5cf6359
MS
24 *
25 * Implementation notes: (May 2010)
26 * This file implements System V semaphores.
27 *
28 * User space visible behavior:
29 * - FIFO ordering for semop() operations (just FIFO, not starvation
30 * protection)
31 * - multiple semaphore operations that alter the same semaphore in
32 * one semop() are handled.
33 * - sem_ctime (time of last semctl()) is updated in the IPC_SET, SETVAL and
34 * SETALL calls.
35 * - two Linux specific semctl() commands: SEM_STAT, SEM_INFO.
36 * - undo adjustments at process exit are limited to 0..SEMVMX.
37 * - namespace are supported.
38 * - SEMMSL, SEMMNS, SEMOPM and SEMMNI can be configured at runtine by writing
39 * to /proc/sys/kernel/sem.
40 * - statistics about the usage are reported in /proc/sysvipc/sem.
41 *
42 * Internals:
43 * - scalability:
44 * - all global variables are read-mostly.
45 * - semop() calls and semctl(RMID) are synchronized by RCU.
46 * - most operations do write operations (actually: spin_lock calls) to
47 * the per-semaphore array structure.
48 * Thus: Perfect SMP scaling between independent semaphore arrays.
49 * If multiple semaphores in one array are used, then cache line
50 * trashing on the semaphore array spinlock will limit the scaling.
2f2ed41d 51 * - semncnt and semzcnt are calculated on demand in count_semcnt()
c5cf6359
MS
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
9ae949fa 57 * dropping all locks. (see wake_up_sem_queue_prepare())
c5cf6359
MS
58 * - All work is done by the waker, the woken up task does not have to do
59 * anything - not even acquiring a lock or dropping a refcount.
60 * - A woken up task may not even touch the semaphore array anymore, it may
61 * have been destroyed already by a semctl(RMID).
c5cf6359
MS
62 * - UNDO values are stored in an array (one per process and per
63 * semaphore array, lazily allocated). For backwards compatibility, multiple
64 * modes for the UNDO variables are supported (per process, per thread)
65 * (see copy_semundo, CLONE_SYSVSEM)
66 * - There are two lists of the pending operations: a per-array list
67 * and per-semaphore list (stored in the array). This allows to achieve FIFO
68 * ordering without always scanning all pending operations.
69 * The worst-case behavior is nevertheless O(N^2) for N wakeups.
1da177e4
LT
70 */
71
1da177e4
LT
72#include <linux/slab.h>
73#include <linux/spinlock.h>
74#include <linux/init.h>
75#include <linux/proc_fs.h>
76#include <linux/time.h>
1da177e4
LT
77#include <linux/security.h>
78#include <linux/syscalls.h>
79#include <linux/audit.h>
c59ede7b 80#include <linux/capability.h>
19b4946c 81#include <linux/seq_file.h>
3e148c79 82#include <linux/rwsem.h>
e3893534 83#include <linux/nsproxy.h>
ae5e1b22 84#include <linux/ipc_namespace.h>
84f001e1 85#include <linux/sched/wake_q.h>
5f921ae9 86
7153e402 87#include <linux/uaccess.h>
1da177e4
LT
88#include "util.h"
89
e57940d7
MS
90
91/* One queue for each sleeping process in the system. */
92struct sem_queue {
e57940d7
MS
93 struct list_head list; /* queue of pending operations */
94 struct task_struct *sleeper; /* this process */
95 struct sem_undo *undo; /* undo structure */
96 int pid; /* process id of requesting process */
97 int status; /* completion status of operation */
98 struct sembuf *sops; /* array of pending operations */
ed247b7c 99 struct sembuf *blocking; /* the operation that blocked */
e57940d7 100 int nsops; /* number of operations */
4ce33ec2
DB
101 bool alter; /* does *sops alter the array? */
102 bool dupsop; /* sops on more than one sem_num */
e57940d7
MS
103};
104
105/* Each task has a list of undo requests. They are executed automatically
106 * when the process exits.
107 */
108struct sem_undo {
109 struct list_head list_proc; /* per-process list: *
110 * all undos from one process
111 * rcu protected */
112 struct rcu_head rcu; /* rcu struct for sem_undo */
113 struct sem_undo_list *ulp; /* back ptr to sem_undo_list */
114 struct list_head list_id; /* per semaphore array list:
115 * all undos for one array */
116 int semid; /* semaphore set identifier */
117 short *semadj; /* array of adjustments */
118 /* one per semaphore */
119};
120
121/* sem_undo_list controls shared access to the list of sem_undo structures
122 * that may be shared among all a CLONE_SYSVSEM task group.
123 */
124struct sem_undo_list {
f74370b8 125 refcount_t refcnt;
e57940d7
MS
126 spinlock_t lock;
127 struct list_head list_proc;
128};
129
130
ed2ddbf8 131#define sem_ids(ns) ((ns)->ids[IPC_SEM_IDS])
e3893534 132
7748dbfa 133static int newary(struct ipc_namespace *, struct ipc_params *);
01b8b07a 134static void freeary(struct ipc_namespace *, struct kern_ipc_perm *);
1da177e4 135#ifdef CONFIG_PROC_FS
19b4946c 136static int sysvipc_sem_proc_show(struct seq_file *s, void *it);
1da177e4
LT
137#endif
138
139#define SEMMSL_FAST 256 /* 512 bytes on stack */
140#define SEMOPM_FAST 64 /* ~ 372 bytes on stack */
141
9de5ab8a
MS
142/*
143 * Switching from the mode suitable for simple ops
144 * to the mode for complex ops is costly. Therefore:
145 * use some hysteresis
146 */
147#define USE_GLOBAL_LOCK_HYSTERESIS 10
148
1da177e4 149/*
758a6ba3 150 * Locking:
5864a2fd 151 * a) global sem_lock() for read/write
1da177e4 152 * sem_undo.id_next,
758a6ba3 153 * sem_array.complex_count,
5864a2fd
MS
154 * sem_array.pending{_alter,_const},
155 * sem_array.sem_undo
46c0a8ca 156 *
5864a2fd 157 * b) global or semaphore sem_lock() for read/write:
1a233956 158 * sem_array.sems[i].pending_{const,alter}:
5864a2fd
MS
159 *
160 * c) special:
161 * sem_undo_list.list_proc:
162 * * undo_list->lock for write
163 * * rcu for read
9de5ab8a
MS
164 * use_global_lock:
165 * * global sem_lock() for write
166 * * either local or global sem_lock() for read.
167 *
168 * Memory ordering:
169 * Most ordering is enforced by using spin_lock() and spin_unlock().
170 * The special case is use_global_lock:
171 * Setting it from non-zero to 0 is a RELEASE, this is ensured by
172 * using smp_store_release().
173 * Testing if it is non-zero is an ACQUIRE, this is ensured by using
174 * smp_load_acquire().
175 * Setting it from 0 to non-zero must be ordered with regards to
176 * this smp_load_acquire(), this is guaranteed because the smp_load_acquire()
177 * is inside a spin_lock() and after a write from 0 to non-zero a
178 * spin_lock()+spin_unlock() is done.
1da177e4
LT
179 */
180
e3893534
KK
181#define sc_semmsl sem_ctls[0]
182#define sc_semmns sem_ctls[1]
183#define sc_semopm sem_ctls[2]
184#define sc_semmni sem_ctls[3]
185
ed2ddbf8 186void sem_init_ns(struct ipc_namespace *ns)
e3893534 187{
e3893534
KK
188 ns->sc_semmsl = SEMMSL;
189 ns->sc_semmns = SEMMNS;
190 ns->sc_semopm = SEMOPM;
191 ns->sc_semmni = SEMMNI;
192 ns->used_sems = 0;
ed2ddbf8 193 ipc_init_ids(&ns->ids[IPC_SEM_IDS]);
e3893534
KK
194}
195
ae5e1b22 196#ifdef CONFIG_IPC_NS
e3893534
KK
197void sem_exit_ns(struct ipc_namespace *ns)
198{
01b8b07a 199 free_ipcs(ns, &sem_ids(ns), freeary);
7d6feeb2 200 idr_destroy(&ns->ids[IPC_SEM_IDS].ipcs_idr);
e3893534 201}
ae5e1b22 202#endif
1da177e4 203
239521f3 204void __init sem_init(void)
1da177e4 205{
ed2ddbf8 206 sem_init_ns(&init_ipc_ns);
19b4946c
MW
207 ipc_init_proc_interface("sysvipc/sem",
208 " key semid perms nsems uid gid cuid cgid otime ctime\n",
e3893534 209 IPC_SEM_IDS, sysvipc_sem_proc_show);
1da177e4
LT
210}
211
f269f40a
MS
212/**
213 * unmerge_queues - unmerge queues, if possible.
214 * @sma: semaphore array
215 *
216 * The function unmerges the wait queues if complex_count is 0.
217 * It must be called prior to dropping the global semaphore array lock.
218 */
219static void unmerge_queues(struct sem_array *sma)
220{
221 struct sem_queue *q, *tq;
222
223 /* complex operations still around? */
224 if (sma->complex_count)
225 return;
226 /*
227 * We will switch back to simple mode.
228 * Move all pending operation back into the per-semaphore
229 * queues.
230 */
231 list_for_each_entry_safe(q, tq, &sma->pending_alter, list) {
232 struct sem *curr;
1a233956 233 curr = &sma->sems[q->sops[0].sem_num];
f269f40a
MS
234
235 list_add_tail(&q->list, &curr->pending_alter);
236 }
237 INIT_LIST_HEAD(&sma->pending_alter);
238}
239
240/**
8001c858 241 * merge_queues - merge single semop queues into global queue
f269f40a
MS
242 * @sma: semaphore array
243 *
244 * This function merges all per-semaphore queues into the global queue.
245 * It is necessary to achieve FIFO ordering for the pending single-sop
246 * operations when a multi-semop operation must sleep.
247 * Only the alter operations must be moved, the const operations can stay.
248 */
249static void merge_queues(struct sem_array *sma)
250{
251 int i;
252 for (i = 0; i < sma->sem_nsems; i++) {
1a233956 253 struct sem *sem = &sma->sems[i];
f269f40a
MS
254
255 list_splice_init(&sem->pending_alter, &sma->pending_alter);
256 }
257}
258
53dad6d3
DB
259static void sem_rcu_free(struct rcu_head *head)
260{
dba4cdd3
MS
261 struct kern_ipc_perm *p = container_of(head, struct kern_ipc_perm, rcu);
262 struct sem_array *sma = container_of(p, struct sem_array, sem_perm);
53dad6d3
DB
263
264 security_sem_free(sma);
e2029dfe 265 kvfree(sma);
53dad6d3
DB
266}
267
5e9d5275 268/*
5864a2fd 269 * Enter the mode suitable for non-simple operations:
5e9d5275 270 * Caller must own sem_perm.lock.
5e9d5275 271 */
5864a2fd 272static void complexmode_enter(struct sem_array *sma)
5e9d5275
MS
273{
274 int i;
275 struct sem *sem;
276
9de5ab8a
MS
277 if (sma->use_global_lock > 0) {
278 /*
279 * We are already in global lock mode.
280 * Nothing to do, just reset the
281 * counter until we return to simple mode.
282 */
283 sma->use_global_lock = USE_GLOBAL_LOCK_HYSTERESIS;
6d07b68c
MS
284 return;
285 }
9de5ab8a 286 sma->use_global_lock = USE_GLOBAL_LOCK_HYSTERESIS;
5864a2fd 287
5e9d5275 288 for (i = 0; i < sma->sem_nsems; i++) {
1a233956 289 sem = &sma->sems[i];
27d7be18
MS
290 spin_lock(&sem->lock);
291 spin_unlock(&sem->lock);
5e9d5275 292 }
5864a2fd
MS
293}
294
295/*
296 * Try to leave the mode that disallows simple operations:
297 * Caller must own sem_perm.lock.
298 */
299static void complexmode_tryleave(struct sem_array *sma)
300{
301 if (sma->complex_count) {
302 /* Complex ops are sleeping.
303 * We must stay in complex mode
304 */
305 return;
306 }
9de5ab8a
MS
307 if (sma->use_global_lock == 1) {
308 /*
309 * Immediately after setting use_global_lock to 0,
310 * a simple op can start. Thus: all memory writes
311 * performed by the current operation must be visible
312 * before we set use_global_lock to 0.
313 */
314 smp_store_release(&sma->use_global_lock, 0);
315 } else {
316 sma->use_global_lock--;
317 }
5e9d5275
MS
318}
319
5864a2fd 320#define SEM_GLOBAL_LOCK (-1)
6062a8dc
RR
321/*
322 * If the request contains only one semaphore operation, and there are
323 * no complex transactions pending, lock only the semaphore involved.
324 * Otherwise, lock the entire semaphore array, since we either have
325 * multiple semaphores in our own semops, or we need to look at
326 * semaphores from other pending complex operations.
6062a8dc
RR
327 */
328static inline int sem_lock(struct sem_array *sma, struct sembuf *sops,
329 int nsops)
330{
5e9d5275 331 struct sem *sem;
6062a8dc 332
5e9d5275
MS
333 if (nsops != 1) {
334 /* Complex operation - acquire a full lock */
335 ipc_lock_object(&sma->sem_perm);
6062a8dc 336
5864a2fd
MS
337 /* Prevent parallel simple ops */
338 complexmode_enter(sma);
339 return SEM_GLOBAL_LOCK;
5e9d5275
MS
340 }
341
342 /*
343 * Only one semaphore affected - try to optimize locking.
5864a2fd
MS
344 * Optimized locking is possible if no complex operation
345 * is either enqueued or processed right now.
346 *
9de5ab8a 347 * Both facts are tracked by use_global_mode.
5e9d5275 348 */
1a233956 349 sem = &sma->sems[sops->sem_num];
6062a8dc 350
5864a2fd 351 /*
9de5ab8a 352 * Initial check for use_global_lock. Just an optimization,
5864a2fd
MS
353 * no locking, no memory barrier.
354 */
9de5ab8a 355 if (!sma->use_global_lock) {
6062a8dc 356 /*
5e9d5275
MS
357 * It appears that no complex operation is around.
358 * Acquire the per-semaphore lock.
6062a8dc 359 */
5e9d5275
MS
360 spin_lock(&sem->lock);
361
9de5ab8a
MS
362 /* pairs with smp_store_release() */
363 if (!smp_load_acquire(&sma->use_global_lock)) {
5864a2fd
MS
364 /* fast path successful! */
365 return sops->sem_num;
6062a8dc 366 }
5e9d5275
MS
367 spin_unlock(&sem->lock);
368 }
369
370 /* slow path: acquire the full lock */
371 ipc_lock_object(&sma->sem_perm);
6062a8dc 372
9de5ab8a
MS
373 if (sma->use_global_lock == 0) {
374 /*
375 * The use_global_lock mode ended while we waited for
376 * sma->sem_perm.lock. Thus we must switch to locking
377 * with sem->lock.
378 * Unlike in the fast path, there is no need to recheck
379 * sma->use_global_lock after we have acquired sem->lock:
380 * We own sma->sem_perm.lock, thus use_global_lock cannot
381 * change.
5e9d5275
MS
382 */
383 spin_lock(&sem->lock);
9de5ab8a 384
5e9d5275
MS
385 ipc_unlock_object(&sma->sem_perm);
386 return sops->sem_num;
6062a8dc 387 } else {
9de5ab8a
MS
388 /*
389 * Not a false alarm, thus continue to use the global lock
390 * mode. No need for complexmode_enter(), this was done by
391 * the caller that has set use_global_mode to non-zero.
6062a8dc 392 */
5864a2fd 393 return SEM_GLOBAL_LOCK;
6062a8dc 394 }
6062a8dc
RR
395}
396
397static inline void sem_unlock(struct sem_array *sma, int locknum)
398{
5864a2fd 399 if (locknum == SEM_GLOBAL_LOCK) {
f269f40a 400 unmerge_queues(sma);
5864a2fd 401 complexmode_tryleave(sma);
cf9d5d78 402 ipc_unlock_object(&sma->sem_perm);
6062a8dc 403 } else {
1a233956 404 struct sem *sem = &sma->sems[locknum];
6062a8dc
RR
405 spin_unlock(&sem->lock);
406 }
6062a8dc
RR
407}
408
3e148c79 409/*
d9a605e4 410 * sem_lock_(check_) routines are called in the paths where the rwsem
3e148c79 411 * is not held.
321310ce
LT
412 *
413 * The caller holds the RCU read lock.
3e148c79 414 */
16df3674
DB
415static inline struct sem_array *sem_obtain_object(struct ipc_namespace *ns, int id)
416{
55b7ae50 417 struct kern_ipc_perm *ipcp = ipc_obtain_object_idr(&sem_ids(ns), id);
16df3674
DB
418
419 if (IS_ERR(ipcp))
420 return ERR_CAST(ipcp);
421
422 return container_of(ipcp, struct sem_array, sem_perm);
423}
424
16df3674
DB
425static inline struct sem_array *sem_obtain_object_check(struct ipc_namespace *ns,
426 int id)
427{
428 struct kern_ipc_perm *ipcp = ipc_obtain_object_check(&sem_ids(ns), id);
429
430 if (IS_ERR(ipcp))
431 return ERR_CAST(ipcp);
b1ed88b4 432
03f02c76 433 return container_of(ipcp, struct sem_array, sem_perm);
023a5355
ND
434}
435
6ff37972
PP
436static inline void sem_lock_and_putref(struct sem_array *sma)
437{
6062a8dc 438 sem_lock(sma, NULL, -1);
dba4cdd3 439 ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
6ff37972
PP
440}
441
7ca7e564
ND
442static inline void sem_rmid(struct ipc_namespace *ns, struct sem_array *s)
443{
444 ipc_rmid(&sem_ids(ns), &s->sem_perm);
445}
446
101ede01
KC
447static struct sem_array *sem_alloc(size_t nsems)
448{
449 struct sem_array *sma;
450 size_t size;
451
452 if (nsems > (INT_MAX - sizeof(*sma)) / sizeof(sma->sems[0]))
453 return NULL;
454
455 size = sizeof(*sma) + nsems * sizeof(sma->sems[0]);
456 sma = kvmalloc(size, GFP_KERNEL);
457 if (unlikely(!sma))
458 return NULL;
459
460 memset(sma, 0, size);
101ede01
KC
461
462 return sma;
463}
464
f4566f04
ND
465/**
466 * newary - Create a new semaphore set
467 * @ns: namespace
468 * @params: ptr to the structure that contains key, semflg and nsems
469 *
d9a605e4 470 * Called with sem_ids.rwsem held (as a writer)
f4566f04 471 */
7748dbfa 472static int newary(struct ipc_namespace *ns, struct ipc_params *params)
1da177e4 473{
1da177e4
LT
474 int retval;
475 struct sem_array *sma;
7748dbfa
ND
476 key_t key = params->key;
477 int nsems = params->u.nsems;
478 int semflg = params->flg;
b97e820f 479 int i;
1da177e4
LT
480
481 if (!nsems)
482 return -EINVAL;
e3893534 483 if (ns->used_sems + nsems > ns->sc_semmns)
1da177e4
LT
484 return -ENOSPC;
485
101ede01 486 sma = sem_alloc(nsems);
3ab08fe2 487 if (!sma)
1da177e4 488 return -ENOMEM;
3ab08fe2 489
1da177e4
LT
490 sma->sem_perm.mode = (semflg & S_IRWXUGO);
491 sma->sem_perm.key = key;
492
493 sma->sem_perm.security = NULL;
494 retval = security_sem_alloc(sma);
495 if (retval) {
e2029dfe 496 kvfree(sma);
1da177e4
LT
497 return retval;
498 }
499
6062a8dc 500 for (i = 0; i < nsems; i++) {
1a233956
MS
501 INIT_LIST_HEAD(&sma->sems[i].pending_alter);
502 INIT_LIST_HEAD(&sma->sems[i].pending_const);
503 spin_lock_init(&sma->sems[i].lock);
6062a8dc 504 }
b97e820f
MS
505
506 sma->complex_count = 0;
9de5ab8a 507 sma->use_global_lock = USE_GLOBAL_LOCK_HYSTERESIS;
1a82e9e1
MS
508 INIT_LIST_HEAD(&sma->pending_alter);
509 INIT_LIST_HEAD(&sma->pending_const);
4daa28f6 510 INIT_LIST_HEAD(&sma->list_id);
1da177e4
LT
511 sma->sem_nsems = nsems;
512 sma->sem_ctime = get_seconds();
e8577d1f 513
2ec55f80
MS
514 retval = ipc_addid(&sem_ids(ns), &sma->sem_perm, ns->sc_semmni);
515 if (retval < 0) {
516 call_rcu(&sma->sem_perm.rcu, sem_rcu_free);
517 return retval;
e8577d1f
MS
518 }
519 ns->used_sems += nsems;
520
6062a8dc 521 sem_unlock(sma, -1);
6d49dab8 522 rcu_read_unlock();
1da177e4 523
7ca7e564 524 return sma->sem_perm.id;
1da177e4
LT
525}
526
7748dbfa 527
f4566f04 528/*
d9a605e4 529 * Called with sem_ids.rwsem and ipcp locked.
f4566f04 530 */
03f02c76 531static inline int sem_security(struct kern_ipc_perm *ipcp, int semflg)
7748dbfa 532{
03f02c76
ND
533 struct sem_array *sma;
534
535 sma = container_of(ipcp, struct sem_array, sem_perm);
536 return security_sem_associate(sma, semflg);
7748dbfa
ND
537}
538
f4566f04 539/*
d9a605e4 540 * Called with sem_ids.rwsem and ipcp locked.
f4566f04 541 */
03f02c76
ND
542static inline int sem_more_checks(struct kern_ipc_perm *ipcp,
543 struct ipc_params *params)
7748dbfa 544{
03f02c76
ND
545 struct sem_array *sma;
546
547 sma = container_of(ipcp, struct sem_array, sem_perm);
548 if (params->u.nsems > sma->sem_nsems)
7748dbfa
ND
549 return -EINVAL;
550
551 return 0;
552}
553
d5460c99 554SYSCALL_DEFINE3(semget, key_t, key, int, nsems, int, semflg)
1da177e4 555{
e3893534 556 struct ipc_namespace *ns;
eb66ec44
MK
557 static const struct ipc_ops sem_ops = {
558 .getnew = newary,
559 .associate = sem_security,
560 .more_checks = sem_more_checks,
561 };
7748dbfa 562 struct ipc_params sem_params;
e3893534
KK
563
564 ns = current->nsproxy->ipc_ns;
1da177e4 565
e3893534 566 if (nsems < 0 || nsems > ns->sc_semmsl)
1da177e4 567 return -EINVAL;
7ca7e564 568
7748dbfa
ND
569 sem_params.key = key;
570 sem_params.flg = semflg;
571 sem_params.u.nsems = nsems;
1da177e4 572
7748dbfa 573 return ipcget(ns, &sem_ids(ns), &sem_ops, &sem_params);
1da177e4
LT
574}
575
78f5009c 576/**
4ce33ec2
DB
577 * perform_atomic_semop[_slow] - Attempt to perform semaphore
578 * operations on a given array.
758a6ba3 579 * @sma: semaphore array
d198cd6d 580 * @q: struct sem_queue that describes the operation
758a6ba3 581 *
4ce33ec2
DB
582 * Caller blocking are as follows, based the value
583 * indicated by the semaphore operation (sem_op):
584 *
585 * (1) >0 never blocks.
586 * (2) 0 (wait-for-zero operation): semval is non-zero.
587 * (3) <0 attempting to decrement semval to a value smaller than zero.
588 *
758a6ba3
MS
589 * Returns 0 if the operation was possible.
590 * Returns 1 if the operation is impossible, the caller must sleep.
4ce33ec2 591 * Returns <0 for error codes.
1da177e4 592 */
4ce33ec2 593static int perform_atomic_semop_slow(struct sem_array *sma, struct sem_queue *q)
1da177e4 594{
d198cd6d 595 int result, sem_op, nsops, pid;
1da177e4 596 struct sembuf *sop;
239521f3 597 struct sem *curr;
d198cd6d
MS
598 struct sembuf *sops;
599 struct sem_undo *un;
600
601 sops = q->sops;
602 nsops = q->nsops;
603 un = q->undo;
1da177e4
LT
604
605 for (sop = sops; sop < sops + nsops; sop++) {
1a233956 606 curr = &sma->sems[sop->sem_num];
1da177e4
LT
607 sem_op = sop->sem_op;
608 result = curr->semval;
78f5009c 609
1da177e4
LT
610 if (!sem_op && result)
611 goto would_block;
612
613 result += sem_op;
614 if (result < 0)
615 goto would_block;
616 if (result > SEMVMX)
617 goto out_of_range;
78f5009c 618
1da177e4
LT
619 if (sop->sem_flg & SEM_UNDO) {
620 int undo = un->semadj[sop->sem_num] - sem_op;
78f5009c 621 /* Exceeding the undo range is an error. */
1da177e4
LT
622 if (undo < (-SEMAEM - 1) || undo > SEMAEM)
623 goto out_of_range;
78f5009c 624 un->semadj[sop->sem_num] = undo;
1da177e4 625 }
78f5009c 626
1da177e4
LT
627 curr->semval = result;
628 }
629
630 sop--;
d198cd6d 631 pid = q->pid;
1da177e4 632 while (sop >= sops) {
1a233956 633 sma->sems[sop->sem_num].sempid = pid;
1da177e4
LT
634 sop--;
635 }
78f5009c 636
1da177e4
LT
637 return 0;
638
639out_of_range:
640 result = -ERANGE;
641 goto undo;
642
643would_block:
ed247b7c
MS
644 q->blocking = sop;
645
1da177e4
LT
646 if (sop->sem_flg & IPC_NOWAIT)
647 result = -EAGAIN;
648 else
649 result = 1;
650
651undo:
652 sop--;
653 while (sop >= sops) {
78f5009c 654 sem_op = sop->sem_op;
1a233956 655 sma->sems[sop->sem_num].semval -= sem_op;
78f5009c
PM
656 if (sop->sem_flg & SEM_UNDO)
657 un->semadj[sop->sem_num] += sem_op;
1da177e4
LT
658 sop--;
659 }
660
661 return result;
662}
663
4ce33ec2
DB
664static int perform_atomic_semop(struct sem_array *sma, struct sem_queue *q)
665{
666 int result, sem_op, nsops;
667 struct sembuf *sop;
668 struct sem *curr;
669 struct sembuf *sops;
670 struct sem_undo *un;
671
672 sops = q->sops;
673 nsops = q->nsops;
674 un = q->undo;
675
676 if (unlikely(q->dupsop))
677 return perform_atomic_semop_slow(sma, q);
678
679 /*
680 * We scan the semaphore set twice, first to ensure that the entire
681 * operation can succeed, therefore avoiding any pointless writes
682 * to shared memory and having to undo such changes in order to block
683 * until the operations can go through.
684 */
685 for (sop = sops; sop < sops + nsops; sop++) {
1a233956 686 curr = &sma->sems[sop->sem_num];
4ce33ec2
DB
687 sem_op = sop->sem_op;
688 result = curr->semval;
689
690 if (!sem_op && result)
691 goto would_block; /* wait-for-zero */
692
693 result += sem_op;
694 if (result < 0)
695 goto would_block;
696
697 if (result > SEMVMX)
698 return -ERANGE;
699
700 if (sop->sem_flg & SEM_UNDO) {
701 int undo = un->semadj[sop->sem_num] - sem_op;
702
703 /* Exceeding the undo range is an error. */
704 if (undo < (-SEMAEM - 1) || undo > SEMAEM)
705 return -ERANGE;
706 }
707 }
708
709 for (sop = sops; sop < sops + nsops; sop++) {
1a233956 710 curr = &sma->sems[sop->sem_num];
4ce33ec2
DB
711 sem_op = sop->sem_op;
712 result = curr->semval;
713
714 if (sop->sem_flg & SEM_UNDO) {
715 int undo = un->semadj[sop->sem_num] - sem_op;
716
717 un->semadj[sop->sem_num] = undo;
718 }
719 curr->semval += sem_op;
720 curr->sempid = q->pid;
721 }
722
723 return 0;
724
725would_block:
726 q->blocking = sop;
727 return sop->sem_flg & IPC_NOWAIT ? -EAGAIN : 1;
728}
729
9ae949fa
DB
730static inline void wake_up_sem_queue_prepare(struct sem_queue *q, int error,
731 struct wake_q_head *wake_q)
0a2b9d4c 732{
9ae949fa
DB
733 wake_q_add(wake_q, q->sleeper);
734 /*
735 * Rely on the above implicit barrier, such that we can
736 * ensure that we hold reference to the task before setting
737 * q->status. Otherwise we could race with do_exit if the
738 * task is awoken by an external event before calling
739 * wake_up_process().
740 */
741 WRITE_ONCE(q->status, error);
d4212093
NP
742}
743
b97e820f
MS
744static void unlink_queue(struct sem_array *sma, struct sem_queue *q)
745{
746 list_del(&q->list);
9f1bc2c9 747 if (q->nsops > 1)
b97e820f
MS
748 sma->complex_count--;
749}
750
fd5db422
MS
751/** check_restart(sma, q)
752 * @sma: semaphore array
753 * @q: the operation that just completed
754 *
755 * update_queue is O(N^2) when it restarts scanning the whole queue of
756 * waiting operations. Therefore this function checks if the restart is
757 * really necessary. It is called after a previously waiting operation
1a82e9e1
MS
758 * modified the array.
759 * Note that wait-for-zero operations are handled without restart.
fd5db422 760 */
4663d3e8 761static inline int check_restart(struct sem_array *sma, struct sem_queue *q)
fd5db422 762{
1a82e9e1
MS
763 /* pending complex alter operations are too difficult to analyse */
764 if (!list_empty(&sma->pending_alter))
fd5db422
MS
765 return 1;
766
767 /* we were a sleeping complex operation. Too difficult */
768 if (q->nsops > 1)
769 return 1;
770
1a82e9e1
MS
771 /* It is impossible that someone waits for the new value:
772 * - complex operations always restart.
773 * - wait-for-zero are handled seperately.
774 * - q is a previously sleeping simple operation that
775 * altered the array. It must be a decrement, because
776 * simple increments never sleep.
777 * - If there are older (higher priority) decrements
778 * in the queue, then they have observed the original
779 * semval value and couldn't proceed. The operation
780 * decremented to value - thus they won't proceed either.
781 */
782 return 0;
783}
fd5db422 784
1a82e9e1 785/**
8001c858 786 * wake_const_ops - wake up non-alter tasks
1a82e9e1
MS
787 * @sma: semaphore array.
788 * @semnum: semaphore that was modified.
9ae949fa 789 * @wake_q: lockless wake-queue head.
1a82e9e1
MS
790 *
791 * wake_const_ops must be called after a semaphore in a semaphore array
792 * was set to 0. If complex const operations are pending, wake_const_ops must
793 * be called with semnum = -1, as well as with the number of each modified
794 * semaphore.
9ae949fa 795 * The tasks that must be woken up are added to @wake_q. The return code
1a82e9e1
MS
796 * is stored in q->pid.
797 * The function returns 1 if at least one operation was completed successfully.
798 */
799static int wake_const_ops(struct sem_array *sma, int semnum,
9ae949fa 800 struct wake_q_head *wake_q)
1a82e9e1 801{
f150f02c 802 struct sem_queue *q, *tmp;
1a82e9e1
MS
803 struct list_head *pending_list;
804 int semop_completed = 0;
805
806 if (semnum == -1)
807 pending_list = &sma->pending_const;
808 else
1a233956 809 pending_list = &sma->sems[semnum].pending_const;
fd5db422 810
f150f02c
DB
811 list_for_each_entry_safe(q, tmp, pending_list, list) {
812 int error = perform_atomic_semop(sma, q);
1a82e9e1 813
f150f02c
DB
814 if (error > 0)
815 continue;
816 /* operation completed, remove from queue & wakeup */
817 unlink_queue(sma, q);
1a82e9e1 818
f150f02c
DB
819 wake_up_sem_queue_prepare(q, error, wake_q);
820 if (error == 0)
821 semop_completed = 1;
1a82e9e1 822 }
f150f02c 823
1a82e9e1
MS
824 return semop_completed;
825}
826
827/**
8001c858 828 * do_smart_wakeup_zero - wakeup all wait for zero tasks
1a82e9e1
MS
829 * @sma: semaphore array
830 * @sops: operations that were performed
831 * @nsops: number of operations
9ae949fa 832 * @wake_q: lockless wake-queue head
1a82e9e1 833 *
8001c858
DB
834 * Checks all required queue for wait-for-zero operations, based
835 * on the actual changes that were performed on the semaphore array.
1a82e9e1
MS
836 * The function returns 1 if at least one operation was completed successfully.
837 */
838static int do_smart_wakeup_zero(struct sem_array *sma, struct sembuf *sops,
9ae949fa 839 int nsops, struct wake_q_head *wake_q)
1a82e9e1
MS
840{
841 int i;
842 int semop_completed = 0;
843 int got_zero = 0;
844
845 /* first: the per-semaphore queues, if known */
846 if (sops) {
847 for (i = 0; i < nsops; i++) {
848 int num = sops[i].sem_num;
849
1a233956 850 if (sma->sems[num].semval == 0) {
1a82e9e1 851 got_zero = 1;
9ae949fa 852 semop_completed |= wake_const_ops(sma, num, wake_q);
1a82e9e1
MS
853 }
854 }
855 } else {
856 /*
857 * No sops means modified semaphores not known.
858 * Assume all were changed.
fd5db422 859 */
1a82e9e1 860 for (i = 0; i < sma->sem_nsems; i++) {
1a233956 861 if (sma->sems[i].semval == 0) {
1a82e9e1 862 got_zero = 1;
9ae949fa 863 semop_completed |= wake_const_ops(sma, i, wake_q);
1a82e9e1
MS
864 }
865 }
fd5db422
MS
866 }
867 /*
1a82e9e1
MS
868 * If one of the modified semaphores got 0,
869 * then check the global queue, too.
fd5db422 870 */
1a82e9e1 871 if (got_zero)
9ae949fa 872 semop_completed |= wake_const_ops(sma, -1, wake_q);
fd5db422 873
1a82e9e1 874 return semop_completed;
fd5db422
MS
875}
876
636c6be8
MS
877
878/**
8001c858 879 * update_queue - look for tasks that can be completed.
636c6be8
MS
880 * @sma: semaphore array.
881 * @semnum: semaphore that was modified.
9ae949fa 882 * @wake_q: lockless wake-queue head.
636c6be8
MS
883 *
884 * update_queue must be called after a semaphore in a semaphore array
9f1bc2c9
RR
885 * was modified. If multiple semaphores were modified, update_queue must
886 * be called with semnum = -1, as well as with the number of each modified
887 * semaphore.
9ae949fa 888 * The tasks that must be woken up are added to @wake_q. The return code
0a2b9d4c 889 * is stored in q->pid.
1a82e9e1
MS
890 * The function internally checks if const operations can now succeed.
891 *
0a2b9d4c 892 * The function return 1 if at least one semop was completed successfully.
1da177e4 893 */
9ae949fa 894static int update_queue(struct sem_array *sma, int semnum, struct wake_q_head *wake_q)
1da177e4 895{
f150f02c 896 struct sem_queue *q, *tmp;
636c6be8 897 struct list_head *pending_list;
0a2b9d4c 898 int semop_completed = 0;
636c6be8 899
9f1bc2c9 900 if (semnum == -1)
1a82e9e1 901 pending_list = &sma->pending_alter;
9f1bc2c9 902 else
1a233956 903 pending_list = &sma->sems[semnum].pending_alter;
9cad200c
NP
904
905again:
f150f02c 906 list_for_each_entry_safe(q, tmp, pending_list, list) {
fd5db422 907 int error, restart;
636c6be8 908
d987f8b2
MS
909 /* If we are scanning the single sop, per-semaphore list of
910 * one semaphore and that semaphore is 0, then it is not
1a82e9e1 911 * necessary to scan further: simple increments
d987f8b2
MS
912 * that affect only one entry succeed immediately and cannot
913 * be in the per semaphore pending queue, and decrements
914 * cannot be successful if the value is already 0.
915 */
1a233956 916 if (semnum != -1 && sma->sems[semnum].semval == 0)
d987f8b2
MS
917 break;
918
d198cd6d 919 error = perform_atomic_semop(sma, q);
1da177e4
LT
920
921 /* Does q->sleeper still need to sleep? */
9cad200c
NP
922 if (error > 0)
923 continue;
924
b97e820f 925 unlink_queue(sma, q);
9cad200c 926
0a2b9d4c 927 if (error) {
fd5db422 928 restart = 0;
0a2b9d4c
MS
929 } else {
930 semop_completed = 1;
9ae949fa 931 do_smart_wakeup_zero(sma, q->sops, q->nsops, wake_q);
fd5db422 932 restart = check_restart(sma, q);
0a2b9d4c 933 }
fd5db422 934
9ae949fa 935 wake_up_sem_queue_prepare(q, error, wake_q);
fd5db422 936 if (restart)
9cad200c 937 goto again;
1da177e4 938 }
0a2b9d4c 939 return semop_completed;
1da177e4
LT
940}
941
0e8c6656 942/**
8001c858 943 * set_semotime - set sem_otime
0e8c6656
MS
944 * @sma: semaphore array
945 * @sops: operations that modified the array, may be NULL
946 *
947 * sem_otime is replicated to avoid cache line trashing.
948 * This function sets one instance to the current time.
949 */
950static void set_semotime(struct sem_array *sma, struct sembuf *sops)
951{
952 if (sops == NULL) {
1a233956 953 sma->sems[0].sem_otime = get_seconds();
0e8c6656 954 } else {
1a233956 955 sma->sems[sops[0].sem_num].sem_otime =
0e8c6656
MS
956 get_seconds();
957 }
958}
959
0a2b9d4c 960/**
8001c858 961 * do_smart_update - optimized update_queue
fd5db422
MS
962 * @sma: semaphore array
963 * @sops: operations that were performed
964 * @nsops: number of operations
0a2b9d4c 965 * @otime: force setting otime
9ae949fa 966 * @wake_q: lockless wake-queue head
fd5db422 967 *
1a82e9e1
MS
968 * do_smart_update() does the required calls to update_queue and wakeup_zero,
969 * based on the actual changes that were performed on the semaphore array.
0a2b9d4c 970 * Note that the function does not do the actual wake-up: the caller is
9ae949fa 971 * responsible for calling wake_up_q().
0a2b9d4c 972 * It is safe to perform this call after dropping all locks.
fd5db422 973 */
0a2b9d4c 974static void do_smart_update(struct sem_array *sma, struct sembuf *sops, int nsops,
9ae949fa 975 int otime, struct wake_q_head *wake_q)
fd5db422
MS
976{
977 int i;
978
9ae949fa 979 otime |= do_smart_wakeup_zero(sma, sops, nsops, wake_q);
1a82e9e1 980
f269f40a
MS
981 if (!list_empty(&sma->pending_alter)) {
982 /* semaphore array uses the global queue - just process it. */
9ae949fa 983 otime |= update_queue(sma, -1, wake_q);
f269f40a
MS
984 } else {
985 if (!sops) {
986 /*
987 * No sops, thus the modified semaphores are not
988 * known. Check all.
989 */
990 for (i = 0; i < sma->sem_nsems; i++)
9ae949fa 991 otime |= update_queue(sma, i, wake_q);
f269f40a
MS
992 } else {
993 /*
994 * Check the semaphores that were increased:
995 * - No complex ops, thus all sleeping ops are
996 * decrease.
997 * - if we decreased the value, then any sleeping
998 * semaphore ops wont be able to run: If the
999 * previous value was too small, then the new
1000 * value will be too small, too.
1001 */
1002 for (i = 0; i < nsops; i++) {
1003 if (sops[i].sem_op > 0) {
1004 otime |= update_queue(sma,
9ae949fa 1005 sops[i].sem_num, wake_q);
f269f40a 1006 }
ab465df9 1007 }
9f1bc2c9 1008 }
fd5db422 1009 }
0e8c6656
MS
1010 if (otime)
1011 set_semotime(sma, sops);
fd5db422
MS
1012}
1013
2f2ed41d 1014/*
b220c57a 1015 * check_qop: Test if a queued operation sleeps on the semaphore semnum
2f2ed41d
MS
1016 */
1017static int check_qop(struct sem_array *sma, int semnum, struct sem_queue *q,
1018 bool count_zero)
1019{
b220c57a 1020 struct sembuf *sop = q->blocking;
2f2ed41d 1021
9b44ee2e
MS
1022 /*
1023 * Linux always (since 0.99.10) reported a task as sleeping on all
1024 * semaphores. This violates SUS, therefore it was changed to the
1025 * standard compliant behavior.
1026 * Give the administrators a chance to notice that an application
1027 * might misbehave because it relies on the Linux behavior.
1028 */
1029 pr_info_once("semctl(GETNCNT/GETZCNT) is since 3.16 Single Unix Specification compliant.\n"
1030 "The task %s (%d) triggered the difference, watch for misbehavior.\n",
1031 current->comm, task_pid_nr(current));
1032
b220c57a
MS
1033 if (sop->sem_num != semnum)
1034 return 0;
2f2ed41d 1035
b220c57a
MS
1036 if (count_zero && sop->sem_op == 0)
1037 return 1;
1038 if (!count_zero && sop->sem_op < 0)
1039 return 1;
1040
1041 return 0;
2f2ed41d
MS
1042}
1043
1da177e4
LT
1044/* The following counts are associated to each semaphore:
1045 * semncnt number of tasks waiting on semval being nonzero
1046 * semzcnt number of tasks waiting on semval being zero
b220c57a
MS
1047 *
1048 * Per definition, a task waits only on the semaphore of the first semop
1049 * that cannot proceed, even if additional operation would block, too.
1da177e4 1050 */
2f2ed41d
MS
1051static int count_semcnt(struct sem_array *sma, ushort semnum,
1052 bool count_zero)
1da177e4 1053{
2f2ed41d 1054 struct list_head *l;
239521f3 1055 struct sem_queue *q;
2f2ed41d 1056 int semcnt;
1da177e4 1057
2f2ed41d
MS
1058 semcnt = 0;
1059 /* First: check the simple operations. They are easy to evaluate */
1060 if (count_zero)
1a233956 1061 l = &sma->sems[semnum].pending_const;
2f2ed41d 1062 else
1a233956 1063 l = &sma->sems[semnum].pending_alter;
1da177e4 1064
2f2ed41d
MS
1065 list_for_each_entry(q, l, list) {
1066 /* all task on a per-semaphore list sleep on exactly
1067 * that semaphore
1068 */
1069 semcnt++;
ebc2e5e6
RR
1070 }
1071
2f2ed41d 1072 /* Then: check the complex operations. */
1994862d 1073 list_for_each_entry(q, &sma->pending_alter, list) {
2f2ed41d
MS
1074 semcnt += check_qop(sma, semnum, q, count_zero);
1075 }
1076 if (count_zero) {
1077 list_for_each_entry(q, &sma->pending_const, list) {
1078 semcnt += check_qop(sma, semnum, q, count_zero);
1079 }
1994862d 1080 }
2f2ed41d 1081 return semcnt;
1da177e4
LT
1082}
1083
d9a605e4
DB
1084/* Free a semaphore set. freeary() is called with sem_ids.rwsem locked
1085 * as a writer and the spinlock for this semaphore set hold. sem_ids.rwsem
3e148c79 1086 * remains locked on exit.
1da177e4 1087 */
01b8b07a 1088static void freeary(struct ipc_namespace *ns, struct kern_ipc_perm *ipcp)
1da177e4 1089{
380af1b3
MS
1090 struct sem_undo *un, *tu;
1091 struct sem_queue *q, *tq;
01b8b07a 1092 struct sem_array *sma = container_of(ipcp, struct sem_array, sem_perm);
9f1bc2c9 1093 int i;
9ae949fa 1094 DEFINE_WAKE_Q(wake_q);
1da177e4 1095
380af1b3 1096 /* Free the existing undo structures for this semaphore set. */
cf9d5d78 1097 ipc_assert_locked_object(&sma->sem_perm);
380af1b3
MS
1098 list_for_each_entry_safe(un, tu, &sma->list_id, list_id) {
1099 list_del(&un->list_id);
1100 spin_lock(&un->ulp->lock);
1da177e4 1101 un->semid = -1;
380af1b3
MS
1102 list_del_rcu(&un->list_proc);
1103 spin_unlock(&un->ulp->lock);
693a8b6e 1104 kfree_rcu(un, rcu);
380af1b3 1105 }
1da177e4
LT
1106
1107 /* Wake up all pending processes and let them fail with EIDRM. */
1a82e9e1
MS
1108 list_for_each_entry_safe(q, tq, &sma->pending_const, list) {
1109 unlink_queue(sma, q);
9ae949fa 1110 wake_up_sem_queue_prepare(q, -EIDRM, &wake_q);
1a82e9e1
MS
1111 }
1112
1113 list_for_each_entry_safe(q, tq, &sma->pending_alter, list) {
b97e820f 1114 unlink_queue(sma, q);
9ae949fa 1115 wake_up_sem_queue_prepare(q, -EIDRM, &wake_q);
1da177e4 1116 }
9f1bc2c9 1117 for (i = 0; i < sma->sem_nsems; i++) {
1a233956 1118 struct sem *sem = &sma->sems[i];
1a82e9e1
MS
1119 list_for_each_entry_safe(q, tq, &sem->pending_const, list) {
1120 unlink_queue(sma, q);
9ae949fa 1121 wake_up_sem_queue_prepare(q, -EIDRM, &wake_q);
1a82e9e1
MS
1122 }
1123 list_for_each_entry_safe(q, tq, &sem->pending_alter, list) {
9f1bc2c9 1124 unlink_queue(sma, q);
9ae949fa 1125 wake_up_sem_queue_prepare(q, -EIDRM, &wake_q);
9f1bc2c9
RR
1126 }
1127 }
1da177e4 1128
7ca7e564
ND
1129 /* Remove the semaphore set from the IDR */
1130 sem_rmid(ns, sma);
6062a8dc 1131 sem_unlock(sma, -1);
6d49dab8 1132 rcu_read_unlock();
1da177e4 1133
9ae949fa 1134 wake_up_q(&wake_q);
e3893534 1135 ns->used_sems -= sma->sem_nsems;
dba4cdd3 1136 ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
1da177e4
LT
1137}
1138
1139static unsigned long copy_semid_to_user(void __user *buf, struct semid64_ds *in, int version)
1140{
239521f3 1141 switch (version) {
1da177e4
LT
1142 case IPC_64:
1143 return copy_to_user(buf, in, sizeof(*in));
1144 case IPC_OLD:
1145 {
1146 struct semid_ds out;
1147
982f7c2b
DR
1148 memset(&out, 0, sizeof(out));
1149
1da177e4
LT
1150 ipc64_perm_to_ipc_perm(&in->sem_perm, &out.sem_perm);
1151
1152 out.sem_otime = in->sem_otime;
1153 out.sem_ctime = in->sem_ctime;
1154 out.sem_nsems = in->sem_nsems;
1155
1156 return copy_to_user(buf, &out, sizeof(out));
1157 }
1158 default:
1159 return -EINVAL;
1160 }
1161}
1162
d12e1e50
MS
1163static time_t get_semotime(struct sem_array *sma)
1164{
1165 int i;
1166 time_t res;
1167
1a233956 1168 res = sma->sems[0].sem_otime;
d12e1e50 1169 for (i = 1; i < sma->sem_nsems; i++) {
1a233956 1170 time_t to = sma->sems[i].sem_otime;
d12e1e50
MS
1171
1172 if (to > res)
1173 res = to;
1174 }
1175 return res;
1176}
1177
4b9fcb0e 1178static int semctl_nolock(struct ipc_namespace *ns, int semid,
e1fd1f49 1179 int cmd, int version, void __user *p)
1da177e4 1180{
e5cc9c7b 1181 int err;
1da177e4
LT
1182 struct sem_array *sma;
1183
239521f3 1184 switch (cmd) {
1da177e4
LT
1185 case IPC_INFO:
1186 case SEM_INFO:
1187 {
1188 struct seminfo seminfo;
1189 int max_id;
1190
1191 err = security_sem_semctl(NULL, cmd);
1192 if (err)
1193 return err;
46c0a8ca 1194
239521f3 1195 memset(&seminfo, 0, sizeof(seminfo));
e3893534
KK
1196 seminfo.semmni = ns->sc_semmni;
1197 seminfo.semmns = ns->sc_semmns;
1198 seminfo.semmsl = ns->sc_semmsl;
1199 seminfo.semopm = ns->sc_semopm;
1da177e4
LT
1200 seminfo.semvmx = SEMVMX;
1201 seminfo.semmnu = SEMMNU;
1202 seminfo.semmap = SEMMAP;
1203 seminfo.semume = SEMUME;
d9a605e4 1204 down_read(&sem_ids(ns).rwsem);
1da177e4 1205 if (cmd == SEM_INFO) {
e3893534
KK
1206 seminfo.semusz = sem_ids(ns).in_use;
1207 seminfo.semaem = ns->used_sems;
1da177e4
LT
1208 } else {
1209 seminfo.semusz = SEMUSZ;
1210 seminfo.semaem = SEMAEM;
1211 }
7ca7e564 1212 max_id = ipc_get_maxid(&sem_ids(ns));
d9a605e4 1213 up_read(&sem_ids(ns).rwsem);
46c0a8ca 1214 if (copy_to_user(p, &seminfo, sizeof(struct seminfo)))
1da177e4 1215 return -EFAULT;
239521f3 1216 return (max_id < 0) ? 0 : max_id;
1da177e4 1217 }
4b9fcb0e 1218 case IPC_STAT:
1da177e4
LT
1219 case SEM_STAT:
1220 {
1221 struct semid64_ds tbuf;
16df3674
DB
1222 int id = 0;
1223
1224 memset(&tbuf, 0, sizeof(tbuf));
1da177e4 1225
941b0304 1226 rcu_read_lock();
4b9fcb0e 1227 if (cmd == SEM_STAT) {
16df3674
DB
1228 sma = sem_obtain_object(ns, semid);
1229 if (IS_ERR(sma)) {
1230 err = PTR_ERR(sma);
1231 goto out_unlock;
1232 }
4b9fcb0e
PP
1233 id = sma->sem_perm.id;
1234 } else {
16df3674
DB
1235 sma = sem_obtain_object_check(ns, semid);
1236 if (IS_ERR(sma)) {
1237 err = PTR_ERR(sma);
1238 goto out_unlock;
1239 }
4b9fcb0e 1240 }
1da177e4
LT
1241
1242 err = -EACCES;
b0e77598 1243 if (ipcperms(ns, &sma->sem_perm, S_IRUGO))
1da177e4
LT
1244 goto out_unlock;
1245
1246 err = security_sem_semctl(sma, cmd);
1247 if (err)
1248 goto out_unlock;
1249
1da177e4 1250 kernel_to_ipc64_perm(&sma->sem_perm, &tbuf.sem_perm);
d12e1e50
MS
1251 tbuf.sem_otime = get_semotime(sma);
1252 tbuf.sem_ctime = sma->sem_ctime;
1253 tbuf.sem_nsems = sma->sem_nsems;
16df3674 1254 rcu_read_unlock();
e1fd1f49 1255 if (copy_semid_to_user(p, &tbuf, version))
1da177e4
LT
1256 return -EFAULT;
1257 return id;
1258 }
1259 default:
1260 return -EINVAL;
1261 }
1da177e4 1262out_unlock:
16df3674 1263 rcu_read_unlock();
1da177e4
LT
1264 return err;
1265}
1266
e1fd1f49
AV
1267static int semctl_setval(struct ipc_namespace *ns, int semid, int semnum,
1268 unsigned long arg)
1269{
1270 struct sem_undo *un;
1271 struct sem_array *sma;
239521f3 1272 struct sem *curr;
9ae949fa
DB
1273 int err, val;
1274 DEFINE_WAKE_Q(wake_q);
1275
e1fd1f49
AV
1276#if defined(CONFIG_64BIT) && defined(__BIG_ENDIAN)
1277 /* big-endian 64bit */
1278 val = arg >> 32;
1279#else
1280 /* 32bit or little-endian 64bit */
1281 val = arg;
1282#endif
1283
6062a8dc
RR
1284 if (val > SEMVMX || val < 0)
1285 return -ERANGE;
e1fd1f49 1286
6062a8dc
RR
1287 rcu_read_lock();
1288 sma = sem_obtain_object_check(ns, semid);
1289 if (IS_ERR(sma)) {
1290 rcu_read_unlock();
1291 return PTR_ERR(sma);
1292 }
1293
1294 if (semnum < 0 || semnum >= sma->sem_nsems) {
1295 rcu_read_unlock();
1296 return -EINVAL;
1297 }
1298
1299
1300 if (ipcperms(ns, &sma->sem_perm, S_IWUGO)) {
1301 rcu_read_unlock();
1302 return -EACCES;
1303 }
e1fd1f49
AV
1304
1305 err = security_sem_semctl(sma, SETVAL);
6062a8dc
RR
1306 if (err) {
1307 rcu_read_unlock();
1308 return -EACCES;
1309 }
e1fd1f49 1310
6062a8dc 1311 sem_lock(sma, NULL, -1);
e1fd1f49 1312
0f3d2b01 1313 if (!ipc_valid_object(&sma->sem_perm)) {
6e224f94
MS
1314 sem_unlock(sma, -1);
1315 rcu_read_unlock();
1316 return -EIDRM;
1317 }
1318
1a233956 1319 curr = &sma->sems[semnum];
e1fd1f49 1320
cf9d5d78 1321 ipc_assert_locked_object(&sma->sem_perm);
e1fd1f49
AV
1322 list_for_each_entry(un, &sma->list_id, list_id)
1323 un->semadj[semnum] = 0;
1324
1325 curr->semval = val;
1326 curr->sempid = task_tgid_vnr(current);
1327 sma->sem_ctime = get_seconds();
1328 /* maybe some queued-up processes were waiting for this */
9ae949fa 1329 do_smart_update(sma, NULL, 0, 0, &wake_q);
6062a8dc 1330 sem_unlock(sma, -1);
6d49dab8 1331 rcu_read_unlock();
9ae949fa 1332 wake_up_q(&wake_q);
6062a8dc 1333 return 0;
e1fd1f49
AV
1334}
1335
e3893534 1336static int semctl_main(struct ipc_namespace *ns, int semid, int semnum,
e1fd1f49 1337 int cmd, void __user *p)
1da177e4
LT
1338{
1339 struct sem_array *sma;
239521f3 1340 struct sem *curr;
16df3674 1341 int err, nsems;
1da177e4 1342 ushort fast_sem_io[SEMMSL_FAST];
239521f3 1343 ushort *sem_io = fast_sem_io;
9ae949fa 1344 DEFINE_WAKE_Q(wake_q);
16df3674
DB
1345
1346 rcu_read_lock();
1347 sma = sem_obtain_object_check(ns, semid);
1348 if (IS_ERR(sma)) {
1349 rcu_read_unlock();
023a5355 1350 return PTR_ERR(sma);
16df3674 1351 }
1da177e4
LT
1352
1353 nsems = sma->sem_nsems;
1354
1da177e4 1355 err = -EACCES;
c728b9c8
LT
1356 if (ipcperms(ns, &sma->sem_perm, cmd == SETALL ? S_IWUGO : S_IRUGO))
1357 goto out_rcu_wakeup;
1da177e4
LT
1358
1359 err = security_sem_semctl(sma, cmd);
c728b9c8
LT
1360 if (err)
1361 goto out_rcu_wakeup;
1da177e4
LT
1362
1363 err = -EACCES;
1364 switch (cmd) {
1365 case GETALL:
1366 {
e1fd1f49 1367 ushort __user *array = p;
1da177e4
LT
1368 int i;
1369
ce857229 1370 sem_lock(sma, NULL, -1);
0f3d2b01 1371 if (!ipc_valid_object(&sma->sem_perm)) {
6e224f94
MS
1372 err = -EIDRM;
1373 goto out_unlock;
1374 }
239521f3 1375 if (nsems > SEMMSL_FAST) {
dba4cdd3 1376 if (!ipc_rcu_getref(&sma->sem_perm)) {
ce857229 1377 err = -EIDRM;
6e224f94 1378 goto out_unlock;
ce857229
AV
1379 }
1380 sem_unlock(sma, -1);
6d49dab8 1381 rcu_read_unlock();
f8dbe8d2
KC
1382 sem_io = kvmalloc_array(nsems, sizeof(ushort),
1383 GFP_KERNEL);
239521f3 1384 if (sem_io == NULL) {
dba4cdd3 1385 ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
1da177e4
LT
1386 return -ENOMEM;
1387 }
1388
4091fd94 1389 rcu_read_lock();
6ff37972 1390 sem_lock_and_putref(sma);
0f3d2b01 1391 if (!ipc_valid_object(&sma->sem_perm)) {
1da177e4 1392 err = -EIDRM;
6e224f94 1393 goto out_unlock;
1da177e4 1394 }
ce857229 1395 }
1da177e4 1396 for (i = 0; i < sma->sem_nsems; i++)
1a233956 1397 sem_io[i] = sma->sems[i].semval;
6062a8dc 1398 sem_unlock(sma, -1);
6d49dab8 1399 rcu_read_unlock();
1da177e4 1400 err = 0;
239521f3 1401 if (copy_to_user(array, sem_io, nsems*sizeof(ushort)))
1da177e4
LT
1402 err = -EFAULT;
1403 goto out_free;
1404 }
1405 case SETALL:
1406 {
1407 int i;
1408 struct sem_undo *un;
1409
dba4cdd3 1410 if (!ipc_rcu_getref(&sma->sem_perm)) {
6e224f94
MS
1411 err = -EIDRM;
1412 goto out_rcu_wakeup;
6062a8dc 1413 }
16df3674 1414 rcu_read_unlock();
1da177e4 1415
239521f3 1416 if (nsems > SEMMSL_FAST) {
f8dbe8d2
KC
1417 sem_io = kvmalloc_array(nsems, sizeof(ushort),
1418 GFP_KERNEL);
239521f3 1419 if (sem_io == NULL) {
dba4cdd3 1420 ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
1da177e4
LT
1421 return -ENOMEM;
1422 }
1423 }
1424
239521f3 1425 if (copy_from_user(sem_io, p, nsems*sizeof(ushort))) {
dba4cdd3 1426 ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
1da177e4
LT
1427 err = -EFAULT;
1428 goto out_free;
1429 }
1430
1431 for (i = 0; i < nsems; i++) {
1432 if (sem_io[i] > SEMVMX) {
dba4cdd3 1433 ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
1da177e4
LT
1434 err = -ERANGE;
1435 goto out_free;
1436 }
1437 }
4091fd94 1438 rcu_read_lock();
6ff37972 1439 sem_lock_and_putref(sma);
0f3d2b01 1440 if (!ipc_valid_object(&sma->sem_perm)) {
1da177e4 1441 err = -EIDRM;
6e224f94 1442 goto out_unlock;
1da177e4
LT
1443 }
1444
a5f4db87 1445 for (i = 0; i < nsems; i++) {
1a233956
MS
1446 sma->sems[i].semval = sem_io[i];
1447 sma->sems[i].sempid = task_tgid_vnr(current);
a5f4db87 1448 }
4daa28f6 1449
cf9d5d78 1450 ipc_assert_locked_object(&sma->sem_perm);
4daa28f6 1451 list_for_each_entry(un, &sma->list_id, list_id) {
1da177e4
LT
1452 for (i = 0; i < nsems; i++)
1453 un->semadj[i] = 0;
4daa28f6 1454 }
1da177e4
LT
1455 sma->sem_ctime = get_seconds();
1456 /* maybe some queued-up processes were waiting for this */
9ae949fa 1457 do_smart_update(sma, NULL, 0, 0, &wake_q);
1da177e4
LT
1458 err = 0;
1459 goto out_unlock;
1460 }
e1fd1f49 1461 /* GETVAL, GETPID, GETNCTN, GETZCNT: fall-through */
1da177e4
LT
1462 }
1463 err = -EINVAL;
c728b9c8
LT
1464 if (semnum < 0 || semnum >= nsems)
1465 goto out_rcu_wakeup;
1da177e4 1466
6062a8dc 1467 sem_lock(sma, NULL, -1);
0f3d2b01 1468 if (!ipc_valid_object(&sma->sem_perm)) {
6e224f94
MS
1469 err = -EIDRM;
1470 goto out_unlock;
1471 }
1a233956 1472 curr = &sma->sems[semnum];
1da177e4
LT
1473
1474 switch (cmd) {
1475 case GETVAL:
1476 err = curr->semval;
1477 goto out_unlock;
1478 case GETPID:
1479 err = curr->sempid;
1480 goto out_unlock;
1481 case GETNCNT:
2f2ed41d 1482 err = count_semcnt(sma, semnum, 0);
1da177e4
LT
1483 goto out_unlock;
1484 case GETZCNT:
2f2ed41d 1485 err = count_semcnt(sma, semnum, 1);
1da177e4 1486 goto out_unlock;
1da177e4 1487 }
16df3674 1488
1da177e4 1489out_unlock:
6062a8dc 1490 sem_unlock(sma, -1);
c728b9c8 1491out_rcu_wakeup:
6d49dab8 1492 rcu_read_unlock();
9ae949fa 1493 wake_up_q(&wake_q);
1da177e4 1494out_free:
239521f3 1495 if (sem_io != fast_sem_io)
f8dbe8d2 1496 kvfree(sem_io);
1da177e4
LT
1497 return err;
1498}
1499
016d7132
PP
1500static inline unsigned long
1501copy_semid_from_user(struct semid64_ds *out, void __user *buf, int version)
1da177e4 1502{
239521f3 1503 switch (version) {
1da177e4 1504 case IPC_64:
016d7132 1505 if (copy_from_user(out, buf, sizeof(*out)))
1da177e4 1506 return -EFAULT;
1da177e4 1507 return 0;
1da177e4
LT
1508 case IPC_OLD:
1509 {
1510 struct semid_ds tbuf_old;
1511
239521f3 1512 if (copy_from_user(&tbuf_old, buf, sizeof(tbuf_old)))
1da177e4
LT
1513 return -EFAULT;
1514
016d7132
PP
1515 out->sem_perm.uid = tbuf_old.sem_perm.uid;
1516 out->sem_perm.gid = tbuf_old.sem_perm.gid;
1517 out->sem_perm.mode = tbuf_old.sem_perm.mode;
1da177e4
LT
1518
1519 return 0;
1520 }
1521 default:
1522 return -EINVAL;
1523 }
1524}
1525
522bb2a2 1526/*
d9a605e4 1527 * This function handles some semctl commands which require the rwsem
522bb2a2 1528 * to be held in write mode.
d9a605e4 1529 * NOTE: no locks must be held, the rwsem is taken inside this function.
522bb2a2 1530 */
21a4826a 1531static int semctl_down(struct ipc_namespace *ns, int semid,
e1fd1f49 1532 int cmd, int version, void __user *p)
1da177e4
LT
1533{
1534 struct sem_array *sma;
1535 int err;
016d7132 1536 struct semid64_ds semid64;
1da177e4
LT
1537 struct kern_ipc_perm *ipcp;
1538
239521f3 1539 if (cmd == IPC_SET) {
e1fd1f49 1540 if (copy_semid_from_user(&semid64, p, version))
1da177e4 1541 return -EFAULT;
1da177e4 1542 }
073115d6 1543
d9a605e4 1544 down_write(&sem_ids(ns).rwsem);
7b4cc5d8
DB
1545 rcu_read_lock();
1546
16df3674
DB
1547 ipcp = ipcctl_pre_down_nolock(ns, &sem_ids(ns), semid, cmd,
1548 &semid64.sem_perm, 0);
7b4cc5d8
DB
1549 if (IS_ERR(ipcp)) {
1550 err = PTR_ERR(ipcp);
7b4cc5d8
DB
1551 goto out_unlock1;
1552 }
073115d6 1553
a5f75e7f 1554 sma = container_of(ipcp, struct sem_array, sem_perm);
1da177e4
LT
1555
1556 err = security_sem_semctl(sma, cmd);
7b4cc5d8
DB
1557 if (err)
1558 goto out_unlock1;
1da177e4 1559
7b4cc5d8 1560 switch (cmd) {
1da177e4 1561 case IPC_RMID:
6062a8dc 1562 sem_lock(sma, NULL, -1);
7b4cc5d8 1563 /* freeary unlocks the ipc object and rcu */
01b8b07a 1564 freeary(ns, ipcp);
522bb2a2 1565 goto out_up;
1da177e4 1566 case IPC_SET:
6062a8dc 1567 sem_lock(sma, NULL, -1);
1efdb69b
EB
1568 err = ipc_update_perm(&semid64.sem_perm, ipcp);
1569 if (err)
7b4cc5d8 1570 goto out_unlock0;
1da177e4 1571 sma->sem_ctime = get_seconds();
1da177e4
LT
1572 break;
1573 default:
1da177e4 1574 err = -EINVAL;
7b4cc5d8 1575 goto out_unlock1;
1da177e4 1576 }
1da177e4 1577
7b4cc5d8 1578out_unlock0:
6062a8dc 1579 sem_unlock(sma, -1);
7b4cc5d8 1580out_unlock1:
6d49dab8 1581 rcu_read_unlock();
522bb2a2 1582out_up:
d9a605e4 1583 up_write(&sem_ids(ns).rwsem);
1da177e4
LT
1584 return err;
1585}
1586
e1fd1f49 1587SYSCALL_DEFINE4(semctl, int, semid, int, semnum, int, cmd, unsigned long, arg)
1da177e4 1588{
1da177e4 1589 int version;
e3893534 1590 struct ipc_namespace *ns;
e1fd1f49 1591 void __user *p = (void __user *)arg;
1da177e4
LT
1592
1593 if (semid < 0)
1594 return -EINVAL;
1595
1596 version = ipc_parse_version(&cmd);
e3893534 1597 ns = current->nsproxy->ipc_ns;
1da177e4 1598
239521f3 1599 switch (cmd) {
1da177e4
LT
1600 case IPC_INFO:
1601 case SEM_INFO:
4b9fcb0e 1602 case IPC_STAT:
1da177e4 1603 case SEM_STAT:
e1fd1f49 1604 return semctl_nolock(ns, semid, cmd, version, p);
1da177e4
LT
1605 case GETALL:
1606 case GETVAL:
1607 case GETPID:
1608 case GETNCNT:
1609 case GETZCNT:
1da177e4 1610 case SETALL:
e1fd1f49
AV
1611 return semctl_main(ns, semid, semnum, cmd, p);
1612 case SETVAL:
1613 return semctl_setval(ns, semid, semnum, arg);
1da177e4
LT
1614 case IPC_RMID:
1615 case IPC_SET:
e1fd1f49 1616 return semctl_down(ns, semid, cmd, version, p);
1da177e4
LT
1617 default:
1618 return -EINVAL;
1619 }
1620}
1621
1da177e4
LT
1622/* If the task doesn't already have a undo_list, then allocate one
1623 * here. We guarantee there is only one thread using this undo list,
1624 * and current is THE ONE
1625 *
1626 * If this allocation and assignment succeeds, but later
1627 * portions of this code fail, there is no need to free the sem_undo_list.
1628 * Just let it stay associated with the task, and it'll be freed later
1629 * at exit time.
1630 *
1631 * This can block, so callers must hold no locks.
1632 */
1633static inline int get_undo_list(struct sem_undo_list **undo_listp)
1634{
1635 struct sem_undo_list *undo_list;
1da177e4
LT
1636
1637 undo_list = current->sysvsem.undo_list;
1638 if (!undo_list) {
2453a306 1639 undo_list = kzalloc(sizeof(*undo_list), GFP_KERNEL);
1da177e4
LT
1640 if (undo_list == NULL)
1641 return -ENOMEM;
00a5dfdb 1642 spin_lock_init(&undo_list->lock);
f74370b8 1643 refcount_set(&undo_list->refcnt, 1);
4daa28f6
MS
1644 INIT_LIST_HEAD(&undo_list->list_proc);
1645
1da177e4
LT
1646 current->sysvsem.undo_list = undo_list;
1647 }
1648 *undo_listp = undo_list;
1649 return 0;
1650}
1651
bf17bb71 1652static struct sem_undo *__lookup_undo(struct sem_undo_list *ulp, int semid)
1da177e4 1653{
bf17bb71 1654 struct sem_undo *un;
4daa28f6 1655
bf17bb71
NP
1656 list_for_each_entry_rcu(un, &ulp->list_proc, list_proc) {
1657 if (un->semid == semid)
1658 return un;
1da177e4 1659 }
4daa28f6 1660 return NULL;
1da177e4
LT
1661}
1662
bf17bb71
NP
1663static struct sem_undo *lookup_undo(struct sem_undo_list *ulp, int semid)
1664{
1665 struct sem_undo *un;
1666
239521f3 1667 assert_spin_locked(&ulp->lock);
bf17bb71
NP
1668
1669 un = __lookup_undo(ulp, semid);
1670 if (un) {
1671 list_del_rcu(&un->list_proc);
1672 list_add_rcu(&un->list_proc, &ulp->list_proc);
1673 }
1674 return un;
1675}
1676
4daa28f6 1677/**
8001c858 1678 * find_alloc_undo - lookup (and if not present create) undo array
4daa28f6
MS
1679 * @ns: namespace
1680 * @semid: semaphore array id
1681 *
1682 * The function looks up (and if not present creates) the undo structure.
1683 * The size of the undo structure depends on the size of the semaphore
1684 * array, thus the alloc path is not that straightforward.
380af1b3
MS
1685 * Lifetime-rules: sem_undo is rcu-protected, on success, the function
1686 * performs a rcu_read_lock().
4daa28f6
MS
1687 */
1688static struct sem_undo *find_alloc_undo(struct ipc_namespace *ns, int semid)
1da177e4
LT
1689{
1690 struct sem_array *sma;
1691 struct sem_undo_list *ulp;
1692 struct sem_undo *un, *new;
6062a8dc 1693 int nsems, error;
1da177e4
LT
1694
1695 error = get_undo_list(&ulp);
1696 if (error)
1697 return ERR_PTR(error);
1698
380af1b3 1699 rcu_read_lock();
c530c6ac 1700 spin_lock(&ulp->lock);
1da177e4 1701 un = lookup_undo(ulp, semid);
c530c6ac 1702 spin_unlock(&ulp->lock);
239521f3 1703 if (likely(un != NULL))
1da177e4
LT
1704 goto out;
1705
1706 /* no undo structure around - allocate one. */
4daa28f6 1707 /* step 1: figure out the size of the semaphore array */
16df3674
DB
1708 sma = sem_obtain_object_check(ns, semid);
1709 if (IS_ERR(sma)) {
1710 rcu_read_unlock();
4de85cd6 1711 return ERR_CAST(sma);
16df3674 1712 }
023a5355 1713
1da177e4 1714 nsems = sma->sem_nsems;
dba4cdd3 1715 if (!ipc_rcu_getref(&sma->sem_perm)) {
6062a8dc
RR
1716 rcu_read_unlock();
1717 un = ERR_PTR(-EIDRM);
1718 goto out;
1719 }
16df3674 1720 rcu_read_unlock();
1da177e4 1721
4daa28f6 1722 /* step 2: allocate new undo structure */
4668edc3 1723 new = kzalloc(sizeof(struct sem_undo) + sizeof(short)*nsems, GFP_KERNEL);
1da177e4 1724 if (!new) {
dba4cdd3 1725 ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
1da177e4
LT
1726 return ERR_PTR(-ENOMEM);
1727 }
1da177e4 1728
380af1b3 1729 /* step 3: Acquire the lock on semaphore array */
4091fd94 1730 rcu_read_lock();
6ff37972 1731 sem_lock_and_putref(sma);
0f3d2b01 1732 if (!ipc_valid_object(&sma->sem_perm)) {
6062a8dc 1733 sem_unlock(sma, -1);
6d49dab8 1734 rcu_read_unlock();
1da177e4
LT
1735 kfree(new);
1736 un = ERR_PTR(-EIDRM);
1737 goto out;
1738 }
380af1b3
MS
1739 spin_lock(&ulp->lock);
1740
1741 /*
1742 * step 4: check for races: did someone else allocate the undo struct?
1743 */
1744 un = lookup_undo(ulp, semid);
1745 if (un) {
1746 kfree(new);
1747 goto success;
1748 }
4daa28f6
MS
1749 /* step 5: initialize & link new undo structure */
1750 new->semadj = (short *) &new[1];
380af1b3 1751 new->ulp = ulp;
4daa28f6
MS
1752 new->semid = semid;
1753 assert_spin_locked(&ulp->lock);
380af1b3 1754 list_add_rcu(&new->list_proc, &ulp->list_proc);
cf9d5d78 1755 ipc_assert_locked_object(&sma->sem_perm);
4daa28f6 1756 list_add(&new->list_id, &sma->list_id);
380af1b3 1757 un = new;
4daa28f6 1758
380af1b3 1759success:
c530c6ac 1760 spin_unlock(&ulp->lock);
6062a8dc 1761 sem_unlock(sma, -1);
1da177e4
LT
1762out:
1763 return un;
1764}
1765
d5460c99
HC
1766SYSCALL_DEFINE4(semtimedop, int, semid, struct sembuf __user *, tsops,
1767 unsigned, nsops, const struct timespec __user *, timeout)
1da177e4
LT
1768{
1769 int error = -EINVAL;
1770 struct sem_array *sma;
1771 struct sembuf fast_sops[SEMOPM_FAST];
239521f3 1772 struct sembuf *sops = fast_sops, *sop;
1da177e4 1773 struct sem_undo *un;
4ce33ec2
DB
1774 int max, locknum;
1775 bool undos = false, alter = false, dupsop = false;
1da177e4 1776 struct sem_queue queue;
4ce33ec2 1777 unsigned long dup = 0, jiffies_left = 0;
e3893534
KK
1778 struct ipc_namespace *ns;
1779
1780 ns = current->nsproxy->ipc_ns;
1da177e4
LT
1781
1782 if (nsops < 1 || semid < 0)
1783 return -EINVAL;
e3893534 1784 if (nsops > ns->sc_semopm)
1da177e4 1785 return -E2BIG;
239521f3
MS
1786 if (nsops > SEMOPM_FAST) {
1787 sops = kmalloc(sizeof(*sops)*nsops, GFP_KERNEL);
1788 if (sops == NULL)
1da177e4
LT
1789 return -ENOMEM;
1790 }
4ce33ec2 1791
239521f3
MS
1792 if (copy_from_user(sops, tsops, nsops * sizeof(*tsops))) {
1793 error = -EFAULT;
1da177e4
LT
1794 goto out_free;
1795 }
4ce33ec2 1796
1da177e4
LT
1797 if (timeout) {
1798 struct timespec _timeout;
1799 if (copy_from_user(&_timeout, timeout, sizeof(*timeout))) {
1800 error = -EFAULT;
1801 goto out_free;
1802 }
1803 if (_timeout.tv_sec < 0 || _timeout.tv_nsec < 0 ||
1804 _timeout.tv_nsec >= 1000000000L) {
1805 error = -EINVAL;
1806 goto out_free;
1807 }
1808 jiffies_left = timespec_to_jiffies(&_timeout);
1809 }
4ce33ec2 1810
1da177e4
LT
1811 max = 0;
1812 for (sop = sops; sop < sops + nsops; sop++) {
4ce33ec2
DB
1813 unsigned long mask = 1ULL << ((sop->sem_num) % BITS_PER_LONG);
1814
1da177e4
LT
1815 if (sop->sem_num >= max)
1816 max = sop->sem_num;
1817 if (sop->sem_flg & SEM_UNDO)
4ce33ec2
DB
1818 undos = true;
1819 if (dup & mask) {
1820 /*
1821 * There was a previous alter access that appears
1822 * to have accessed the same semaphore, thus use
1823 * the dupsop logic. "appears", because the detection
1824 * can only check % BITS_PER_LONG.
1825 */
1826 dupsop = true;
1827 }
1828 if (sop->sem_op != 0) {
1829 alter = true;
1830 dup |= mask;
1831 }
1da177e4 1832 }
1da177e4 1833
1da177e4 1834 if (undos) {
6062a8dc 1835 /* On success, find_alloc_undo takes the rcu_read_lock */
4daa28f6 1836 un = find_alloc_undo(ns, semid);
1da177e4
LT
1837 if (IS_ERR(un)) {
1838 error = PTR_ERR(un);
1839 goto out_free;
1840 }
6062a8dc 1841 } else {
1da177e4 1842 un = NULL;
6062a8dc
RR
1843 rcu_read_lock();
1844 }
1da177e4 1845
16df3674 1846 sma = sem_obtain_object_check(ns, semid);
023a5355 1847 if (IS_ERR(sma)) {
6062a8dc 1848 rcu_read_unlock();
023a5355 1849 error = PTR_ERR(sma);
1da177e4 1850 goto out_free;
023a5355
ND
1851 }
1852
16df3674 1853 error = -EFBIG;
248e7357
DB
1854 if (max >= sma->sem_nsems) {
1855 rcu_read_unlock();
1856 goto out_free;
1857 }
16df3674
DB
1858
1859 error = -EACCES;
248e7357
DB
1860 if (ipcperms(ns, &sma->sem_perm, alter ? S_IWUGO : S_IRUGO)) {
1861 rcu_read_unlock();
1862 goto out_free;
1863 }
16df3674
DB
1864
1865 error = security_sem_semop(sma, sops, nsops, alter);
248e7357
DB
1866 if (error) {
1867 rcu_read_unlock();
1868 goto out_free;
1869 }
16df3674 1870
6e224f94
MS
1871 error = -EIDRM;
1872 locknum = sem_lock(sma, sops, nsops);
0f3d2b01
RA
1873 /*
1874 * We eventually might perform the following check in a lockless
1875 * fashion, considering ipc_valid_object() locking constraints.
1876 * If nsops == 1 and there is no contention for sem_perm.lock, then
1877 * only a per-semaphore lock is held and it's OK to proceed with the
1878 * check below. More details on the fine grained locking scheme
1879 * entangled here and why it's RMID race safe on comments at sem_lock()
1880 */
1881 if (!ipc_valid_object(&sma->sem_perm))
6e224f94 1882 goto out_unlock_free;
1da177e4 1883 /*
4daa28f6 1884 * semid identifiers are not unique - find_alloc_undo may have
1da177e4 1885 * allocated an undo structure, it was invalidated by an RMID
4daa28f6 1886 * and now a new array with received the same id. Check and fail.
25985edc 1887 * This case can be detected checking un->semid. The existence of
380af1b3 1888 * "un" itself is guaranteed by rcu.
1da177e4 1889 */
6062a8dc
RR
1890 if (un && un->semid == -1)
1891 goto out_unlock_free;
4daa28f6 1892
d198cd6d
MS
1893 queue.sops = sops;
1894 queue.nsops = nsops;
1895 queue.undo = un;
1896 queue.pid = task_tgid_vnr(current);
1897 queue.alter = alter;
4ce33ec2 1898 queue.dupsop = dupsop;
d198cd6d
MS
1899
1900 error = perform_atomic_semop(sma, &queue);
9ae949fa
DB
1901 if (error == 0) { /* non-blocking succesfull path */
1902 DEFINE_WAKE_Q(wake_q);
1903
1904 /*
1905 * If the operation was successful, then do
0e8c6656
MS
1906 * the required updates.
1907 */
1908 if (alter)
9ae949fa 1909 do_smart_update(sma, sops, nsops, 1, &wake_q);
0e8c6656
MS
1910 else
1911 set_semotime(sma, sops);
9ae949fa
DB
1912
1913 sem_unlock(sma, locknum);
1914 rcu_read_unlock();
1915 wake_up_q(&wake_q);
1916
1917 goto out_free;
1da177e4 1918 }
9ae949fa 1919 if (error < 0) /* non-blocking error path */
0e8c6656 1920 goto out_unlock_free;
1da177e4 1921
9ae949fa
DB
1922 /*
1923 * We need to sleep on this operation, so we put the current
1da177e4
LT
1924 * task into the pending queue and go to sleep.
1925 */
b97e820f
MS
1926 if (nsops == 1) {
1927 struct sem *curr;
1a233956 1928 curr = &sma->sems[sops->sem_num];
b97e820f 1929
f269f40a
MS
1930 if (alter) {
1931 if (sma->complex_count) {
1932 list_add_tail(&queue.list,
1933 &sma->pending_alter);
1934 } else {
1935
1936 list_add_tail(&queue.list,
1937 &curr->pending_alter);
1938 }
1939 } else {
1a82e9e1 1940 list_add_tail(&queue.list, &curr->pending_const);
f269f40a 1941 }
b97e820f 1942 } else {
f269f40a
MS
1943 if (!sma->complex_count)
1944 merge_queues(sma);
1945
9f1bc2c9 1946 if (alter)
1a82e9e1 1947 list_add_tail(&queue.list, &sma->pending_alter);
9f1bc2c9 1948 else
1a82e9e1
MS
1949 list_add_tail(&queue.list, &sma->pending_const);
1950
b97e820f
MS
1951 sma->complex_count++;
1952 }
1953
b5fa01a2
DB
1954 do {
1955 queue.status = -EINTR;
1956 queue.sleeper = current;
0b0577f6 1957
b5fa01a2
DB
1958 __set_current_state(TASK_INTERRUPTIBLE);
1959 sem_unlock(sma, locknum);
1960 rcu_read_unlock();
1da177e4 1961
b5fa01a2
DB
1962 if (timeout)
1963 jiffies_left = schedule_timeout(jiffies_left);
1964 else
1965 schedule();
1da177e4 1966
9ae949fa 1967 /*
b5fa01a2
DB
1968 * fastpath: the semop has completed, either successfully or
1969 * not, from the syscall pov, is quite irrelevant to us at this
1970 * point; we're done.
1971 *
1972 * We _do_ care, nonetheless, about being awoken by a signal or
1973 * spuriously. The queue.status is checked again in the
1974 * slowpath (aka after taking sem_lock), such that we can detect
1975 * scenarios where we were awakened externally, during the
1976 * window between wake_q_add() and wake_up_q().
c61284e9 1977 */
b5fa01a2
DB
1978 error = READ_ONCE(queue.status);
1979 if (error != -EINTR) {
1980 /*
1981 * User space could assume that semop() is a memory
1982 * barrier: Without the mb(), the cpu could
1983 * speculatively read in userspace stale data that was
1984 * overwritten by the previous owner of the semaphore.
1985 */
1986 smp_mb();
1987 goto out_free;
1988 }
d694ad62 1989
b5fa01a2 1990 rcu_read_lock();
c626bc46 1991 locknum = sem_lock(sma, sops, nsops);
1da177e4 1992
370b262c
DB
1993 if (!ipc_valid_object(&sma->sem_perm))
1994 goto out_unlock_free;
1995
1996 error = READ_ONCE(queue.status);
1da177e4 1997
b5fa01a2
DB
1998 /*
1999 * If queue.status != -EINTR we are woken up by another process.
2000 * Leave without unlink_queue(), but with sem_unlock().
2001 */
2002 if (error != -EINTR)
2003 goto out_unlock_free;
0b0577f6 2004
b5fa01a2
DB
2005 /*
2006 * If an interrupt occurred we have to clean up the queue.
2007 */
2008 if (timeout && jiffies_left == 0)
2009 error = -EAGAIN;
2010 } while (error == -EINTR && !signal_pending(current)); /* spurious */
0b0577f6 2011
b97e820f 2012 unlink_queue(sma, &queue);
1da177e4
LT
2013
2014out_unlock_free:
6062a8dc 2015 sem_unlock(sma, locknum);
6d49dab8 2016 rcu_read_unlock();
1da177e4 2017out_free:
239521f3 2018 if (sops != fast_sops)
1da177e4
LT
2019 kfree(sops);
2020 return error;
2021}
2022
d5460c99
HC
2023SYSCALL_DEFINE3(semop, int, semid, struct sembuf __user *, tsops,
2024 unsigned, nsops)
1da177e4
LT
2025{
2026 return sys_semtimedop(semid, tsops, nsops, NULL);
2027}
2028
2029/* If CLONE_SYSVSEM is set, establish sharing of SEM_UNDO state between
2030 * parent and child tasks.
1da177e4
LT
2031 */
2032
2033int copy_semundo(unsigned long clone_flags, struct task_struct *tsk)
2034{
2035 struct sem_undo_list *undo_list;
2036 int error;
2037
2038 if (clone_flags & CLONE_SYSVSEM) {
2039 error = get_undo_list(&undo_list);
2040 if (error)
2041 return error;
f74370b8 2042 refcount_inc(&undo_list->refcnt);
1da177e4 2043 tsk->sysvsem.undo_list = undo_list;
46c0a8ca 2044 } else
1da177e4
LT
2045 tsk->sysvsem.undo_list = NULL;
2046
2047 return 0;
2048}
2049
2050/*
2051 * add semadj values to semaphores, free undo structures.
2052 * undo structures are not freed when semaphore arrays are destroyed
2053 * so some of them may be out of date.
2054 * IMPLEMENTATION NOTE: There is some confusion over whether the
2055 * set of adjustments that needs to be done should be done in an atomic
2056 * manner or not. That is, if we are attempting to decrement the semval
2057 * should we queue up and wait until we can do so legally?
2058 * The original implementation attempted to do this (queue and wait).
2059 * The current implementation does not do so. The POSIX standard
2060 * and SVID should be consulted to determine what behavior is mandated.
2061 */
2062void exit_sem(struct task_struct *tsk)
2063{
4daa28f6 2064 struct sem_undo_list *ulp;
1da177e4 2065
4daa28f6
MS
2066 ulp = tsk->sysvsem.undo_list;
2067 if (!ulp)
1da177e4 2068 return;
9edff4ab 2069 tsk->sysvsem.undo_list = NULL;
1da177e4 2070
f74370b8 2071 if (!refcount_dec_and_test(&ulp->refcnt))
1da177e4
LT
2072 return;
2073
380af1b3 2074 for (;;) {
1da177e4 2075 struct sem_array *sma;
380af1b3 2076 struct sem_undo *un;
6062a8dc 2077 int semid, i;
9ae949fa 2078 DEFINE_WAKE_Q(wake_q);
4daa28f6 2079
2a1613a5
NB
2080 cond_resched();
2081
380af1b3 2082 rcu_read_lock();
05725f7e
JP
2083 un = list_entry_rcu(ulp->list_proc.next,
2084 struct sem_undo, list_proc);
602b8593
HK
2085 if (&un->list_proc == &ulp->list_proc) {
2086 /*
2087 * We must wait for freeary() before freeing this ulp,
2088 * in case we raced with last sem_undo. There is a small
2089 * possibility where we exit while freeary() didn't
2090 * finish unlocking sem_undo_list.
2091 */
e0892e08
PM
2092 spin_lock(&ulp->lock);
2093 spin_unlock(&ulp->lock);
602b8593
HK
2094 rcu_read_unlock();
2095 break;
2096 }
2097 spin_lock(&ulp->lock);
2098 semid = un->semid;
2099 spin_unlock(&ulp->lock);
4daa28f6 2100
602b8593 2101 /* exit_sem raced with IPC_RMID, nothing to do */
6062a8dc
RR
2102 if (semid == -1) {
2103 rcu_read_unlock();
602b8593 2104 continue;
6062a8dc 2105 }
1da177e4 2106
602b8593 2107 sma = sem_obtain_object_check(tsk->nsproxy->ipc_ns, semid);
380af1b3 2108 /* exit_sem raced with IPC_RMID, nothing to do */
6062a8dc
RR
2109 if (IS_ERR(sma)) {
2110 rcu_read_unlock();
380af1b3 2111 continue;
6062a8dc 2112 }
1da177e4 2113
6062a8dc 2114 sem_lock(sma, NULL, -1);
6e224f94 2115 /* exit_sem raced with IPC_RMID, nothing to do */
0f3d2b01 2116 if (!ipc_valid_object(&sma->sem_perm)) {
6e224f94
MS
2117 sem_unlock(sma, -1);
2118 rcu_read_unlock();
2119 continue;
2120 }
bf17bb71 2121 un = __lookup_undo(ulp, semid);
380af1b3
MS
2122 if (un == NULL) {
2123 /* exit_sem raced with IPC_RMID+semget() that created
2124 * exactly the same semid. Nothing to do.
2125 */
6062a8dc 2126 sem_unlock(sma, -1);
6d49dab8 2127 rcu_read_unlock();
380af1b3
MS
2128 continue;
2129 }
2130
2131 /* remove un from the linked lists */
cf9d5d78 2132 ipc_assert_locked_object(&sma->sem_perm);
4daa28f6
MS
2133 list_del(&un->list_id);
2134
a9795584
HK
2135 /* we are the last process using this ulp, acquiring ulp->lock
2136 * isn't required. Besides that, we are also protected against
2137 * IPC_RMID as we hold sma->sem_perm lock now
2138 */
380af1b3 2139 list_del_rcu(&un->list_proc);
380af1b3 2140
4daa28f6
MS
2141 /* perform adjustments registered in un */
2142 for (i = 0; i < sma->sem_nsems; i++) {
1a233956 2143 struct sem *semaphore = &sma->sems[i];
4daa28f6
MS
2144 if (un->semadj[i]) {
2145 semaphore->semval += un->semadj[i];
1da177e4
LT
2146 /*
2147 * Range checks of the new semaphore value,
2148 * not defined by sus:
2149 * - Some unices ignore the undo entirely
2150 * (e.g. HP UX 11i 11.22, Tru64 V5.1)
2151 * - some cap the value (e.g. FreeBSD caps
2152 * at 0, but doesn't enforce SEMVMX)
2153 *
2154 * Linux caps the semaphore value, both at 0
2155 * and at SEMVMX.
2156 *
239521f3 2157 * Manfred <manfred@colorfullife.com>
1da177e4 2158 */
5f921ae9
IM
2159 if (semaphore->semval < 0)
2160 semaphore->semval = 0;
2161 if (semaphore->semval > SEMVMX)
2162 semaphore->semval = SEMVMX;
b488893a 2163 semaphore->sempid = task_tgid_vnr(current);
1da177e4
LT
2164 }
2165 }
1da177e4 2166 /* maybe some queued-up processes were waiting for this */
9ae949fa 2167 do_smart_update(sma, NULL, 0, 1, &wake_q);
6062a8dc 2168 sem_unlock(sma, -1);
6d49dab8 2169 rcu_read_unlock();
9ae949fa 2170 wake_up_q(&wake_q);
380af1b3 2171
693a8b6e 2172 kfree_rcu(un, rcu);
1da177e4 2173 }
4daa28f6 2174 kfree(ulp);
1da177e4
LT
2175}
2176
2177#ifdef CONFIG_PROC_FS
19b4946c 2178static int sysvipc_sem_proc_show(struct seq_file *s, void *it)
1da177e4 2179{
1efdb69b 2180 struct user_namespace *user_ns = seq_user_ns(s);
ade9f91b
KC
2181 struct kern_ipc_perm *ipcp = it;
2182 struct sem_array *sma = container_of(ipcp, struct sem_array, sem_perm);
d12e1e50
MS
2183 time_t sem_otime;
2184
d8c63376
MS
2185 /*
2186 * The proc interface isn't aware of sem_lock(), it calls
2187 * ipc_lock_object() directly (in sysvipc_find_ipc).
5864a2fd
MS
2188 * In order to stay compatible with sem_lock(), we must
2189 * enter / leave complex_mode.
d8c63376 2190 */
5864a2fd 2191 complexmode_enter(sma);
d8c63376 2192
d12e1e50 2193 sem_otime = get_semotime(sma);
19b4946c 2194
7f032d6e
JP
2195 seq_printf(s,
2196 "%10d %10d %4o %10u %5u %5u %5u %5u %10lu %10lu\n",
2197 sma->sem_perm.key,
2198 sma->sem_perm.id,
2199 sma->sem_perm.mode,
2200 sma->sem_nsems,
2201 from_kuid_munged(user_ns, sma->sem_perm.uid),
2202 from_kgid_munged(user_ns, sma->sem_perm.gid),
2203 from_kuid_munged(user_ns, sma->sem_perm.cuid),
2204 from_kgid_munged(user_ns, sma->sem_perm.cgid),
2205 sem_otime,
2206 sma->sem_ctime);
2207
5864a2fd
MS
2208 complexmode_tryleave(sma);
2209
7f032d6e 2210 return 0;
1da177e4
LT
2211}
2212#endif