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