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