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