sem.c 58 KB

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