sem.c 61 KB

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