sem.c 56 KB

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