sem.c 58 KB

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