sem.c 58 KB

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