eventpoll.c 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042
  1. /*
  2. * fs/eventpoll.c (Efficient event retrieval implementation)
  3. * Copyright (C) 2001,...,2009 Davide Libenzi
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * Davide Libenzi <davidel@xmailserver.org>
  11. *
  12. */
  13. #include <linux/init.h>
  14. #include <linux/kernel.h>
  15. #include <linux/sched.h>
  16. #include <linux/fs.h>
  17. #include <linux/file.h>
  18. #include <linux/signal.h>
  19. #include <linux/errno.h>
  20. #include <linux/mm.h>
  21. #include <linux/slab.h>
  22. #include <linux/poll.h>
  23. #include <linux/string.h>
  24. #include <linux/list.h>
  25. #include <linux/hash.h>
  26. #include <linux/spinlock.h>
  27. #include <linux/syscalls.h>
  28. #include <linux/rbtree.h>
  29. #include <linux/wait.h>
  30. #include <linux/eventpoll.h>
  31. #include <linux/mount.h>
  32. #include <linux/bitops.h>
  33. #include <linux/mutex.h>
  34. #include <linux/anon_inodes.h>
  35. #include <linux/device.h>
  36. #include <linux/freezer.h>
  37. #include <asm/uaccess.h>
  38. #include <asm/io.h>
  39. #include <asm/mman.h>
  40. #include <linux/atomic.h>
  41. #include <linux/rculist.h>
  42. /*
  43. * LOCKING:
  44. * There are three level of locking required by epoll :
  45. *
  46. * 1) epmutex (mutex)
  47. * 2) ep->mtx (mutex)
  48. * 3) ep->lock (spinlock)
  49. *
  50. * The acquire order is the one listed above, from 1 to 3.
  51. * We need a spinlock (ep->lock) because we manipulate objects
  52. * from inside the poll callback, that might be triggered from
  53. * a wake_up() that in turn might be called from IRQ context.
  54. * So we can't sleep inside the poll callback and hence we need
  55. * a spinlock. During the event transfer loop (from kernel to
  56. * user space) we could end up sleeping due a copy_to_user(), so
  57. * we need a lock that will allow us to sleep. This lock is a
  58. * mutex (ep->mtx). It is acquired during the event transfer loop,
  59. * during epoll_ctl(EPOLL_CTL_DEL) and during eventpoll_release_file().
  60. * Then we also need a global mutex to serialize eventpoll_release_file()
  61. * and ep_free().
  62. * This mutex is acquired by ep_free() during the epoll file
  63. * cleanup path and it is also acquired by eventpoll_release_file()
  64. * if a file has been pushed inside an epoll set and it is then
  65. * close()d without a previous call to epoll_ctl(EPOLL_CTL_DEL).
  66. * It is also acquired when inserting an epoll fd onto another epoll
  67. * fd. We do this so that we walk the epoll tree and ensure that this
  68. * insertion does not create a cycle of epoll file descriptors, which
  69. * could lead to deadlock. We need a global mutex to prevent two
  70. * simultaneous inserts (A into B and B into A) from racing and
  71. * constructing a cycle without either insert observing that it is
  72. * going to.
  73. * It is necessary to acquire multiple "ep->mtx"es at once in the
  74. * case when one epoll fd is added to another. In this case, we
  75. * always acquire the locks in the order of nesting (i.e. after
  76. * epoll_ctl(e1, EPOLL_CTL_ADD, e2), e1->mtx will always be acquired
  77. * before e2->mtx). Since we disallow cycles of epoll file
  78. * descriptors, this ensures that the mutexes are well-ordered. In
  79. * order to communicate this nesting to lockdep, when walking a tree
  80. * of epoll file descriptors, we use the current recursion depth as
  81. * the lockdep subkey.
  82. * It is possible to drop the "ep->mtx" and to use the global
  83. * mutex "epmutex" (together with "ep->lock") to have it working,
  84. * but having "ep->mtx" will make the interface more scalable.
  85. * Events that require holding "epmutex" are very rare, while for
  86. * normal operations the epoll private "ep->mtx" will guarantee
  87. * a better scalability.
  88. */
  89. /* Epoll private bits inside the event mask */
  90. #define EP_PRIVATE_BITS (EPOLLWAKEUP | EPOLLONESHOT | EPOLLET)
  91. /* Maximum number of nesting allowed inside epoll sets */
  92. #define EP_MAX_NESTS 4
  93. #define EP_MAX_EVENTS (INT_MAX / sizeof(struct epoll_event))
  94. #define EP_UNACTIVE_PTR ((void *) -1L)
  95. #define EP_ITEM_COST (sizeof(struct epitem) + sizeof(struct eppoll_entry))
  96. struct epoll_filefd {
  97. struct file *file;
  98. int fd;
  99. } __packed;
  100. /*
  101. * Structure used to track possible nested calls, for too deep recursions
  102. * and loop cycles.
  103. */
  104. struct nested_call_node {
  105. struct list_head llink;
  106. void *cookie;
  107. void *ctx;
  108. };
  109. /*
  110. * This structure is used as collector for nested calls, to check for
  111. * maximum recursion dept and loop cycles.
  112. */
  113. struct nested_calls {
  114. struct list_head tasks_call_list;
  115. spinlock_t lock;
  116. };
  117. /*
  118. * Each file descriptor added to the eventpoll interface will
  119. * have an entry of this type linked to the "rbr" RB tree.
  120. * Avoid increasing the size of this struct, there can be many thousands
  121. * of these on a server and we do not want this to take another cache line.
  122. */
  123. struct epitem {
  124. union {
  125. /* RB tree node links this structure to the eventpoll RB tree */
  126. struct rb_node rbn;
  127. /* Used to free the struct epitem */
  128. struct rcu_head rcu;
  129. };
  130. /* List header used to link this structure to the eventpoll ready list */
  131. struct list_head rdllink;
  132. /*
  133. * Works together "struct eventpoll"->ovflist in keeping the
  134. * single linked chain of items.
  135. */
  136. struct epitem *next;
  137. /* The file descriptor information this item refers to */
  138. struct epoll_filefd ffd;
  139. /* Number of active wait queue attached to poll operations */
  140. int nwait;
  141. /* List containing poll wait queues */
  142. struct list_head pwqlist;
  143. /* The "container" of this item */
  144. struct eventpoll *ep;
  145. /* List header used to link this item to the "struct file" items list */
  146. struct list_head fllink;
  147. /* wakeup_source used when EPOLLWAKEUP is set */
  148. struct wakeup_source __rcu *ws;
  149. /* The structure that describe the interested events and the source fd */
  150. struct epoll_event event;
  151. };
  152. /*
  153. * This structure is stored inside the "private_data" member of the file
  154. * structure and represents the main data structure for the eventpoll
  155. * interface.
  156. */
  157. struct eventpoll {
  158. /* Protect the access to this structure */
  159. spinlock_t lock;
  160. /*
  161. * This mutex is used to ensure that files are not removed
  162. * while epoll is using them. This is held during the event
  163. * collection loop, the file cleanup path, the epoll file exit
  164. * code and the ctl operations.
  165. */
  166. struct mutex mtx;
  167. /* Wait queue used by sys_epoll_wait() */
  168. wait_queue_head_t wq;
  169. /* Wait queue used by file->poll() */
  170. wait_queue_head_t poll_wait;
  171. /* List of ready file descriptors */
  172. struct list_head rdllist;
  173. /* RB tree root used to store monitored fd structs */
  174. struct rb_root rbr;
  175. /*
  176. * This is a single linked list that chains all the "struct epitem" that
  177. * happened while transferring ready events to userspace w/out
  178. * holding ->lock.
  179. */
  180. struct epitem *ovflist;
  181. /* wakeup_source used when ep_scan_ready_list is running */
  182. struct wakeup_source *ws;
  183. /* The user that created the eventpoll descriptor */
  184. struct user_struct *user;
  185. struct file *file;
  186. /* used to optimize loop detection check */
  187. int visited;
  188. struct list_head visited_list_link;
  189. };
  190. /* Wait structure used by the poll hooks */
  191. struct eppoll_entry {
  192. /* List header used to link this structure to the "struct epitem" */
  193. struct list_head llink;
  194. /* The "base" pointer is set to the container "struct epitem" */
  195. struct epitem *base;
  196. /*
  197. * Wait queue item that will be linked to the target file wait
  198. * queue head.
  199. */
  200. wait_queue_t wait;
  201. /* The wait queue head that linked the "wait" wait queue item */
  202. wait_queue_head_t *whead;
  203. };
  204. /* Wrapper struct used by poll queueing */
  205. struct ep_pqueue {
  206. poll_table pt;
  207. struct epitem *epi;
  208. };
  209. /* Used by the ep_send_events() function as callback private data */
  210. struct ep_send_events_data {
  211. int maxevents;
  212. struct epoll_event __user *events;
  213. };
  214. /*
  215. * Configuration options available inside /proc/sys/fs/epoll/
  216. */
  217. /* Maximum number of epoll watched descriptors, per user */
  218. static long max_user_watches __read_mostly;
  219. /*
  220. * This mutex is used to serialize ep_free() and eventpoll_release_file().
  221. */
  222. static DEFINE_MUTEX(epmutex);
  223. /* Used to check for epoll file descriptor inclusion loops */
  224. static struct nested_calls poll_loop_ncalls;
  225. /* Used for safe wake up implementation */
  226. static struct nested_calls poll_safewake_ncalls;
  227. /* Used to call file's f_op->poll() under the nested calls boundaries */
  228. static struct nested_calls poll_readywalk_ncalls;
  229. /* Slab cache used to allocate "struct epitem" */
  230. static struct kmem_cache *epi_cache __read_mostly;
  231. /* Slab cache used to allocate "struct eppoll_entry" */
  232. static struct kmem_cache *pwq_cache __read_mostly;
  233. /* Visited nodes during ep_loop_check(), so we can unset them when we finish */
  234. static LIST_HEAD(visited_list);
  235. /*
  236. * List of files with newly added links, where we may need to limit the number
  237. * of emanating paths. Protected by the epmutex.
  238. */
  239. static LIST_HEAD(tfile_check_list);
  240. #ifdef CONFIG_SYSCTL
  241. #include <linux/sysctl.h>
  242. static long zero;
  243. static long long_max = LONG_MAX;
  244. ctl_table epoll_table[] = {
  245. {
  246. .procname = "max_user_watches",
  247. .data = &max_user_watches,
  248. .maxlen = sizeof(max_user_watches),
  249. .mode = 0644,
  250. .proc_handler = proc_doulongvec_minmax,
  251. .extra1 = &zero,
  252. .extra2 = &long_max,
  253. },
  254. { }
  255. };
  256. #endif /* CONFIG_SYSCTL */
  257. static const struct file_operations eventpoll_fops;
  258. static inline int is_file_epoll(struct file *f)
  259. {
  260. return f->f_op == &eventpoll_fops;
  261. }
  262. /* Setup the structure that is used as key for the RB tree */
  263. static inline void ep_set_ffd(struct epoll_filefd *ffd,
  264. struct file *file, int fd)
  265. {
  266. ffd->file = file;
  267. ffd->fd = fd;
  268. }
  269. /* Compare RB tree keys */
  270. static inline int ep_cmp_ffd(struct epoll_filefd *p1,
  271. struct epoll_filefd *p2)
  272. {
  273. return (p1->file > p2->file ? +1:
  274. (p1->file < p2->file ? -1 : p1->fd - p2->fd));
  275. }
  276. /* Tells us if the item is currently linked */
  277. static inline int ep_is_linked(struct list_head *p)
  278. {
  279. return !list_empty(p);
  280. }
  281. static inline struct eppoll_entry *ep_pwq_from_wait(wait_queue_t *p)
  282. {
  283. return container_of(p, struct eppoll_entry, wait);
  284. }
  285. /* Get the "struct epitem" from a wait queue pointer */
  286. static inline struct epitem *ep_item_from_wait(wait_queue_t *p)
  287. {
  288. return container_of(p, struct eppoll_entry, wait)->base;
  289. }
  290. /* Get the "struct epitem" from an epoll queue wrapper */
  291. static inline struct epitem *ep_item_from_epqueue(poll_table *p)
  292. {
  293. return container_of(p, struct ep_pqueue, pt)->epi;
  294. }
  295. /* Tells if the epoll_ctl(2) operation needs an event copy from userspace */
  296. static inline int ep_op_has_event(int op)
  297. {
  298. return op != EPOLL_CTL_DEL;
  299. }
  300. /* Initialize the poll safe wake up structure */
  301. static void ep_nested_calls_init(struct nested_calls *ncalls)
  302. {
  303. INIT_LIST_HEAD(&ncalls->tasks_call_list);
  304. spin_lock_init(&ncalls->lock);
  305. }
  306. /**
  307. * ep_events_available - Checks if ready events might be available.
  308. *
  309. * @ep: Pointer to the eventpoll context.
  310. *
  311. * Returns: Returns a value different than zero if ready events are available,
  312. * or zero otherwise.
  313. */
  314. static inline int ep_events_available(struct eventpoll *ep)
  315. {
  316. return !list_empty(&ep->rdllist) || ep->ovflist != EP_UNACTIVE_PTR;
  317. }
  318. /**
  319. * ep_call_nested - Perform a bound (possibly) nested call, by checking
  320. * that the recursion limit is not exceeded, and that
  321. * the same nested call (by the meaning of same cookie) is
  322. * no re-entered.
  323. *
  324. * @ncalls: Pointer to the nested_calls structure to be used for this call.
  325. * @max_nests: Maximum number of allowed nesting calls.
  326. * @nproc: Nested call core function pointer.
  327. * @priv: Opaque data to be passed to the @nproc callback.
  328. * @cookie: Cookie to be used to identify this nested call.
  329. * @ctx: This instance context.
  330. *
  331. * Returns: Returns the code returned by the @nproc callback, or -1 if
  332. * the maximum recursion limit has been exceeded.
  333. */
  334. static int ep_call_nested(struct nested_calls *ncalls, int max_nests,
  335. int (*nproc)(void *, void *, int), void *priv,
  336. void *cookie, void *ctx)
  337. {
  338. int error, call_nests = 0;
  339. unsigned long flags;
  340. struct list_head *lsthead = &ncalls->tasks_call_list;
  341. struct nested_call_node *tncur;
  342. struct nested_call_node tnode;
  343. spin_lock_irqsave(&ncalls->lock, flags);
  344. /*
  345. * Try to see if the current task is already inside this wakeup call.
  346. * We use a list here, since the population inside this set is always
  347. * very much limited.
  348. */
  349. list_for_each_entry(tncur, lsthead, llink) {
  350. if (tncur->ctx == ctx &&
  351. (tncur->cookie == cookie || ++call_nests > max_nests)) {
  352. /*
  353. * Ops ... loop detected or maximum nest level reached.
  354. * We abort this wake by breaking the cycle itself.
  355. */
  356. error = -1;
  357. goto out_unlock;
  358. }
  359. }
  360. /* Add the current task and cookie to the list */
  361. tnode.ctx = ctx;
  362. tnode.cookie = cookie;
  363. list_add(&tnode.llink, lsthead);
  364. spin_unlock_irqrestore(&ncalls->lock, flags);
  365. /* Call the nested function */
  366. error = (*nproc)(priv, cookie, call_nests);
  367. /* Remove the current task from the list */
  368. spin_lock_irqsave(&ncalls->lock, flags);
  369. list_del(&tnode.llink);
  370. out_unlock:
  371. spin_unlock_irqrestore(&ncalls->lock, flags);
  372. return error;
  373. }
  374. /*
  375. * As described in commit 0ccf831cb lockdep: annotate epoll
  376. * the use of wait queues used by epoll is done in a very controlled
  377. * manner. Wake ups can nest inside each other, but are never done
  378. * with the same locking. For example:
  379. *
  380. * dfd = socket(...);
  381. * efd1 = epoll_create();
  382. * efd2 = epoll_create();
  383. * epoll_ctl(efd1, EPOLL_CTL_ADD, dfd, ...);
  384. * epoll_ctl(efd2, EPOLL_CTL_ADD, efd1, ...);
  385. *
  386. * When a packet arrives to the device underneath "dfd", the net code will
  387. * issue a wake_up() on its poll wake list. Epoll (efd1) has installed a
  388. * callback wakeup entry on that queue, and the wake_up() performed by the
  389. * "dfd" net code will end up in ep_poll_callback(). At this point epoll
  390. * (efd1) notices that it may have some event ready, so it needs to wake up
  391. * the waiters on its poll wait list (efd2). So it calls ep_poll_safewake()
  392. * that ends up in another wake_up(), after having checked about the
  393. * recursion constraints. That are, no more than EP_MAX_POLLWAKE_NESTS, to
  394. * avoid stack blasting.
  395. *
  396. * When CONFIG_DEBUG_LOCK_ALLOC is enabled, make sure lockdep can handle
  397. * this special case of epoll.
  398. */
  399. #ifdef CONFIG_DEBUG_LOCK_ALLOC
  400. static inline void ep_wake_up_nested(wait_queue_head_t *wqueue,
  401. unsigned long events, int subclass)
  402. {
  403. unsigned long flags;
  404. spin_lock_irqsave_nested(&wqueue->lock, flags, subclass);
  405. wake_up_locked_poll(wqueue, events);
  406. spin_unlock_irqrestore(&wqueue->lock, flags);
  407. }
  408. #else
  409. static inline void ep_wake_up_nested(wait_queue_head_t *wqueue,
  410. unsigned long events, int subclass)
  411. {
  412. wake_up_poll(wqueue, events);
  413. }
  414. #endif
  415. static int ep_poll_wakeup_proc(void *priv, void *cookie, int call_nests)
  416. {
  417. ep_wake_up_nested((wait_queue_head_t *) cookie, POLLIN,
  418. 1 + call_nests);
  419. return 0;
  420. }
  421. /*
  422. * Perform a safe wake up of the poll wait list. The problem is that
  423. * with the new callback'd wake up system, it is possible that the
  424. * poll callback is reentered from inside the call to wake_up() done
  425. * on the poll wait queue head. The rule is that we cannot reenter the
  426. * wake up code from the same task more than EP_MAX_NESTS times,
  427. * and we cannot reenter the same wait queue head at all. This will
  428. * enable to have a hierarchy of epoll file descriptor of no more than
  429. * EP_MAX_NESTS deep.
  430. */
  431. static void ep_poll_safewake(wait_queue_head_t *wq)
  432. {
  433. int this_cpu = get_cpu();
  434. ep_call_nested(&poll_safewake_ncalls, EP_MAX_NESTS,
  435. ep_poll_wakeup_proc, NULL, wq, (void *) (long) this_cpu);
  436. put_cpu();
  437. }
  438. static void ep_remove_wait_queue(struct eppoll_entry *pwq)
  439. {
  440. wait_queue_head_t *whead;
  441. rcu_read_lock();
  442. /* If it is cleared by POLLFREE, it should be rcu-safe */
  443. whead = rcu_dereference(pwq->whead);
  444. if (whead)
  445. remove_wait_queue(whead, &pwq->wait);
  446. rcu_read_unlock();
  447. }
  448. /*
  449. * This function unregisters poll callbacks from the associated file
  450. * descriptor. Must be called with "mtx" held (or "epmutex" if called from
  451. * ep_free).
  452. */
  453. static void ep_unregister_pollwait(struct eventpoll *ep, struct epitem *epi)
  454. {
  455. struct list_head *lsthead = &epi->pwqlist;
  456. struct eppoll_entry *pwq;
  457. while (!list_empty(lsthead)) {
  458. pwq = list_first_entry(lsthead, struct eppoll_entry, llink);
  459. list_del(&pwq->llink);
  460. ep_remove_wait_queue(pwq);
  461. kmem_cache_free(pwq_cache, pwq);
  462. }
  463. }
  464. /* call only when ep->mtx is held */
  465. static inline struct wakeup_source *ep_wakeup_source(struct epitem *epi)
  466. {
  467. return rcu_dereference_check(epi->ws, lockdep_is_held(&epi->ep->mtx));
  468. }
  469. /* call only when ep->mtx is held */
  470. static inline void ep_pm_stay_awake(struct epitem *epi)
  471. {
  472. struct wakeup_source *ws = ep_wakeup_source(epi);
  473. if (ws)
  474. __pm_stay_awake(ws);
  475. }
  476. static inline bool ep_has_wakeup_source(struct epitem *epi)
  477. {
  478. return rcu_access_pointer(epi->ws) ? true : false;
  479. }
  480. /* call when ep->mtx cannot be held (ep_poll_callback) */
  481. static inline void ep_pm_stay_awake_rcu(struct epitem *epi)
  482. {
  483. struct wakeup_source *ws;
  484. rcu_read_lock();
  485. ws = rcu_dereference(epi->ws);
  486. if (ws)
  487. __pm_stay_awake(ws);
  488. rcu_read_unlock();
  489. }
  490. /**
  491. * ep_scan_ready_list - Scans the ready list in a way that makes possible for
  492. * the scan code, to call f_op->poll(). Also allows for
  493. * O(NumReady) performance.
  494. *
  495. * @ep: Pointer to the epoll private data structure.
  496. * @sproc: Pointer to the scan callback.
  497. * @priv: Private opaque data passed to the @sproc callback.
  498. * @depth: The current depth of recursive f_op->poll calls.
  499. *
  500. * Returns: The same integer error code returned by the @sproc callback.
  501. */
  502. static int ep_scan_ready_list(struct eventpoll *ep,
  503. int (*sproc)(struct eventpoll *,
  504. struct list_head *, void *),
  505. void *priv,
  506. int depth)
  507. {
  508. int error, pwake = 0;
  509. unsigned long flags;
  510. struct epitem *epi, *nepi;
  511. LIST_HEAD(txlist);
  512. /*
  513. * We need to lock this because we could be hit by
  514. * eventpoll_release_file() and epoll_ctl().
  515. */
  516. mutex_lock_nested(&ep->mtx, depth);
  517. /*
  518. * Steal the ready list, and re-init the original one to the
  519. * empty list. Also, set ep->ovflist to NULL so that events
  520. * happening while looping w/out locks, are not lost. We cannot
  521. * have the poll callback to queue directly on ep->rdllist,
  522. * because we want the "sproc" callback to be able to do it
  523. * in a lockless way.
  524. */
  525. spin_lock_irqsave(&ep->lock, flags);
  526. list_splice_init(&ep->rdllist, &txlist);
  527. ep->ovflist = NULL;
  528. spin_unlock_irqrestore(&ep->lock, flags);
  529. /*
  530. * Now call the callback function.
  531. */
  532. error = (*sproc)(ep, &txlist, priv);
  533. spin_lock_irqsave(&ep->lock, flags);
  534. /*
  535. * During the time we spent inside the "sproc" callback, some
  536. * other events might have been queued by the poll callback.
  537. * We re-insert them inside the main ready-list here.
  538. */
  539. for (nepi = ep->ovflist; (epi = nepi) != NULL;
  540. nepi = epi->next, epi->next = EP_UNACTIVE_PTR) {
  541. /*
  542. * We need to check if the item is already in the list.
  543. * During the "sproc" callback execution time, items are
  544. * queued into ->ovflist but the "txlist" might already
  545. * contain them, and the list_splice() below takes care of them.
  546. */
  547. if (!ep_is_linked(&epi->rdllink)) {
  548. list_add_tail(&epi->rdllink, &ep->rdllist);
  549. ep_pm_stay_awake(epi);
  550. }
  551. }
  552. /*
  553. * We need to set back ep->ovflist to EP_UNACTIVE_PTR, so that after
  554. * releasing the lock, events will be queued in the normal way inside
  555. * ep->rdllist.
  556. */
  557. ep->ovflist = EP_UNACTIVE_PTR;
  558. /*
  559. * Quickly re-inject items left on "txlist".
  560. */
  561. list_splice(&txlist, &ep->rdllist);
  562. __pm_relax(ep->ws);
  563. if (!list_empty(&ep->rdllist)) {
  564. /*
  565. * Wake up (if active) both the eventpoll wait list and
  566. * the ->poll() wait list (delayed after we release the lock).
  567. */
  568. if (waitqueue_active(&ep->wq))
  569. wake_up_locked(&ep->wq);
  570. if (waitqueue_active(&ep->poll_wait))
  571. pwake++;
  572. }
  573. spin_unlock_irqrestore(&ep->lock, flags);
  574. mutex_unlock(&ep->mtx);
  575. /* We have to call this outside the lock */
  576. if (pwake)
  577. ep_poll_safewake(&ep->poll_wait);
  578. return error;
  579. }
  580. static void epi_rcu_free(struct rcu_head *head)
  581. {
  582. struct epitem *epi = container_of(head, struct epitem, rcu);
  583. kmem_cache_free(epi_cache, epi);
  584. }
  585. /*
  586. * Removes a "struct epitem" from the eventpoll RB tree and deallocates
  587. * all the associated resources. Must be called with "mtx" held.
  588. */
  589. static int ep_remove(struct eventpoll *ep, struct epitem *epi)
  590. {
  591. unsigned long flags;
  592. struct file *file = epi->ffd.file;
  593. /*
  594. * Removes poll wait queue hooks. We _have_ to do this without holding
  595. * the "ep->lock" otherwise a deadlock might occur. This because of the
  596. * sequence of the lock acquisition. Here we do "ep->lock" then the wait
  597. * queue head lock when unregistering the wait queue. The wakeup callback
  598. * will run by holding the wait queue head lock and will call our callback
  599. * that will try to get "ep->lock".
  600. */
  601. ep_unregister_pollwait(ep, epi);
  602. /* Remove the current item from the list of epoll hooks */
  603. spin_lock(&file->f_lock);
  604. list_del_rcu(&epi->fllink);
  605. spin_unlock(&file->f_lock);
  606. rb_erase(&epi->rbn, &ep->rbr);
  607. spin_lock_irqsave(&ep->lock, flags);
  608. if (ep_is_linked(&epi->rdllink))
  609. list_del_init(&epi->rdllink);
  610. spin_unlock_irqrestore(&ep->lock, flags);
  611. wakeup_source_unregister(ep_wakeup_source(epi));
  612. /*
  613. * At this point it is safe to free the eventpoll item. Use the union
  614. * field epi->rcu, since we are trying to minimize the size of
  615. * 'struct epitem'. The 'rbn' field is no longer in use. Protected by
  616. * ep->mtx. The rcu read side, reverse_path_check_proc(), does not make
  617. * use of the rbn field.
  618. */
  619. call_rcu(&epi->rcu, epi_rcu_free);
  620. atomic_long_dec(&ep->user->epoll_watches);
  621. return 0;
  622. }
  623. static void ep_free(struct eventpoll *ep)
  624. {
  625. struct rb_node *rbp;
  626. struct epitem *epi;
  627. /* We need to release all tasks waiting for these file */
  628. if (waitqueue_active(&ep->poll_wait))
  629. ep_poll_safewake(&ep->poll_wait);
  630. /*
  631. * We need to lock this because we could be hit by
  632. * eventpoll_release_file() while we're freeing the "struct eventpoll".
  633. * We do not need to hold "ep->mtx" here because the epoll file
  634. * is on the way to be removed and no one has references to it
  635. * anymore. The only hit might come from eventpoll_release_file() but
  636. * holding "epmutex" is sufficient here.
  637. */
  638. mutex_lock(&epmutex);
  639. /*
  640. * Walks through the whole tree by unregistering poll callbacks.
  641. */
  642. for (rbp = rb_first(&ep->rbr); rbp; rbp = rb_next(rbp)) {
  643. epi = rb_entry(rbp, struct epitem, rbn);
  644. ep_unregister_pollwait(ep, epi);
  645. cond_resched();
  646. }
  647. /*
  648. * Walks through the whole tree by freeing each "struct epitem". At this
  649. * point we are sure no poll callbacks will be lingering around, and also by
  650. * holding "epmutex" we can be sure that no file cleanup code will hit
  651. * us during this operation. So we can avoid the lock on "ep->lock".
  652. * We do not need to lock ep->mtx, either, we only do it to prevent
  653. * a lockdep warning.
  654. */
  655. mutex_lock(&ep->mtx);
  656. while ((rbp = rb_first(&ep->rbr)) != NULL) {
  657. epi = rb_entry(rbp, struct epitem, rbn);
  658. ep_remove(ep, epi);
  659. cond_resched();
  660. }
  661. mutex_unlock(&ep->mtx);
  662. mutex_unlock(&epmutex);
  663. mutex_destroy(&ep->mtx);
  664. free_uid(ep->user);
  665. wakeup_source_unregister(ep->ws);
  666. kfree(ep);
  667. }
  668. static int ep_eventpoll_release(struct inode *inode, struct file *file)
  669. {
  670. struct eventpoll *ep = file->private_data;
  671. if (ep)
  672. ep_free(ep);
  673. return 0;
  674. }
  675. static inline unsigned int ep_item_poll(struct epitem *epi, poll_table *pt)
  676. {
  677. pt->_key = epi->event.events;
  678. return epi->ffd.file->f_op->poll(epi->ffd.file, pt) & epi->event.events;
  679. }
  680. static int ep_read_events_proc(struct eventpoll *ep, struct list_head *head,
  681. void *priv)
  682. {
  683. struct epitem *epi, *tmp;
  684. poll_table pt;
  685. init_poll_funcptr(&pt, NULL);
  686. list_for_each_entry_safe(epi, tmp, head, rdllink) {
  687. if (ep_item_poll(epi, &pt))
  688. return POLLIN | POLLRDNORM;
  689. else {
  690. /*
  691. * Item has been dropped into the ready list by the poll
  692. * callback, but it's not actually ready, as far as
  693. * caller requested events goes. We can remove it here.
  694. */
  695. __pm_relax(ep_wakeup_source(epi));
  696. list_del_init(&epi->rdllink);
  697. }
  698. }
  699. return 0;
  700. }
  701. static int ep_poll_readyevents_proc(void *priv, void *cookie, int call_nests)
  702. {
  703. return ep_scan_ready_list(priv, ep_read_events_proc, NULL, call_nests + 1);
  704. }
  705. static unsigned int ep_eventpoll_poll(struct file *file, poll_table *wait)
  706. {
  707. int pollflags;
  708. struct eventpoll *ep = file->private_data;
  709. /* Insert inside our poll wait queue */
  710. poll_wait(file, &ep->poll_wait, wait);
  711. /*
  712. * Proceed to find out if wanted events are really available inside
  713. * the ready list. This need to be done under ep_call_nested()
  714. * supervision, since the call to f_op->poll() done on listed files
  715. * could re-enter here.
  716. */
  717. pollflags = ep_call_nested(&poll_readywalk_ncalls, EP_MAX_NESTS,
  718. ep_poll_readyevents_proc, ep, ep, current);
  719. return pollflags != -1 ? pollflags : 0;
  720. }
  721. /* File callbacks that implement the eventpoll file behaviour */
  722. static const struct file_operations eventpoll_fops = {
  723. .release = ep_eventpoll_release,
  724. .poll = ep_eventpoll_poll,
  725. .llseek = noop_llseek,
  726. };
  727. /*
  728. * This is called from eventpoll_release() to unlink files from the eventpoll
  729. * interface. We need to have this facility to cleanup correctly files that are
  730. * closed without being removed from the eventpoll interface.
  731. */
  732. void eventpoll_release_file(struct file *file)
  733. {
  734. struct eventpoll *ep;
  735. struct epitem *epi, *next;
  736. /*
  737. * We don't want to get "file->f_lock" because it is not
  738. * necessary. It is not necessary because we're in the "struct file"
  739. * cleanup path, and this means that no one is using this file anymore.
  740. * So, for example, epoll_ctl() cannot hit here since if we reach this
  741. * point, the file counter already went to zero and fget() would fail.
  742. * The only hit might come from ep_free() but by holding the mutex
  743. * will correctly serialize the operation. We do need to acquire
  744. * "ep->mtx" after "epmutex" because ep_remove() requires it when called
  745. * from anywhere but ep_free().
  746. *
  747. * Besides, ep_remove() acquires the lock, so we can't hold it here.
  748. */
  749. mutex_lock(&epmutex);
  750. list_for_each_entry_safe(epi, next, &file->f_ep_links, fllink) {
  751. ep = epi->ep;
  752. mutex_lock_nested(&ep->mtx, 0);
  753. ep_remove(ep, epi);
  754. mutex_unlock(&ep->mtx);
  755. }
  756. mutex_unlock(&epmutex);
  757. }
  758. static int ep_alloc(struct eventpoll **pep)
  759. {
  760. int error;
  761. struct user_struct *user;
  762. struct eventpoll *ep;
  763. user = get_current_user();
  764. error = -ENOMEM;
  765. ep = kzalloc(sizeof(*ep), GFP_KERNEL);
  766. if (unlikely(!ep))
  767. goto free_uid;
  768. spin_lock_init(&ep->lock);
  769. mutex_init(&ep->mtx);
  770. init_waitqueue_head(&ep->wq);
  771. init_waitqueue_head(&ep->poll_wait);
  772. INIT_LIST_HEAD(&ep->rdllist);
  773. ep->rbr = RB_ROOT;
  774. ep->ovflist = EP_UNACTIVE_PTR;
  775. ep->user = user;
  776. *pep = ep;
  777. return 0;
  778. free_uid:
  779. free_uid(user);
  780. return error;
  781. }
  782. /*
  783. * Search the file inside the eventpoll tree. The RB tree operations
  784. * are protected by the "mtx" mutex, and ep_find() must be called with
  785. * "mtx" held.
  786. */
  787. static struct epitem *ep_find(struct eventpoll *ep, struct file *file, int fd)
  788. {
  789. int kcmp;
  790. struct rb_node *rbp;
  791. struct epitem *epi, *epir = NULL;
  792. struct epoll_filefd ffd;
  793. ep_set_ffd(&ffd, file, fd);
  794. for (rbp = ep->rbr.rb_node; rbp; ) {
  795. epi = rb_entry(rbp, struct epitem, rbn);
  796. kcmp = ep_cmp_ffd(&ffd, &epi->ffd);
  797. if (kcmp > 0)
  798. rbp = rbp->rb_right;
  799. else if (kcmp < 0)
  800. rbp = rbp->rb_left;
  801. else {
  802. epir = epi;
  803. break;
  804. }
  805. }
  806. return epir;
  807. }
  808. /*
  809. * This is the callback that is passed to the wait queue wakeup
  810. * mechanism. It is called by the stored file descriptors when they
  811. * have events to report.
  812. */
  813. static int ep_poll_callback(wait_queue_t *wait, unsigned mode, int sync, void *key)
  814. {
  815. int pwake = 0;
  816. unsigned long flags;
  817. struct epitem *epi = ep_item_from_wait(wait);
  818. struct eventpoll *ep = epi->ep;
  819. if ((unsigned long)key & POLLFREE) {
  820. ep_pwq_from_wait(wait)->whead = NULL;
  821. /*
  822. * whead = NULL above can race with ep_remove_wait_queue()
  823. * which can do another remove_wait_queue() after us, so we
  824. * can't use __remove_wait_queue(). whead->lock is held by
  825. * the caller.
  826. */
  827. list_del_init(&wait->task_list);
  828. }
  829. spin_lock_irqsave(&ep->lock, flags);
  830. /*
  831. * If the event mask does not contain any poll(2) event, we consider the
  832. * descriptor to be disabled. This condition is likely the effect of the
  833. * EPOLLONESHOT bit that disables the descriptor when an event is received,
  834. * until the next EPOLL_CTL_MOD will be issued.
  835. */
  836. if (!(epi->event.events & ~EP_PRIVATE_BITS))
  837. goto out_unlock;
  838. /*
  839. * Check the events coming with the callback. At this stage, not
  840. * every device reports the events in the "key" parameter of the
  841. * callback. We need to be able to handle both cases here, hence the
  842. * test for "key" != NULL before the event match test.
  843. */
  844. if (key && !((unsigned long) key & epi->event.events))
  845. goto out_unlock;
  846. /*
  847. * If we are transferring events to userspace, we can hold no locks
  848. * (because we're accessing user memory, and because of linux f_op->poll()
  849. * semantics). All the events that happen during that period of time are
  850. * chained in ep->ovflist and requeued later on.
  851. */
  852. if (unlikely(ep->ovflist != EP_UNACTIVE_PTR)) {
  853. if (epi->next == EP_UNACTIVE_PTR) {
  854. epi->next = ep->ovflist;
  855. ep->ovflist = epi;
  856. if (epi->ws) {
  857. /*
  858. * Activate ep->ws since epi->ws may get
  859. * deactivated at any time.
  860. */
  861. __pm_stay_awake(ep->ws);
  862. }
  863. }
  864. goto out_unlock;
  865. }
  866. /* If this file is already in the ready list we exit soon */
  867. if (!ep_is_linked(&epi->rdllink)) {
  868. list_add_tail(&epi->rdllink, &ep->rdllist);
  869. ep_pm_stay_awake_rcu(epi);
  870. }
  871. /*
  872. * Wake up ( if active ) both the eventpoll wait list and the ->poll()
  873. * wait list.
  874. */
  875. if (waitqueue_active(&ep->wq))
  876. wake_up_locked(&ep->wq);
  877. if (waitqueue_active(&ep->poll_wait))
  878. pwake++;
  879. out_unlock:
  880. spin_unlock_irqrestore(&ep->lock, flags);
  881. /* We have to call this outside the lock */
  882. if (pwake)
  883. ep_poll_safewake(&ep->poll_wait);
  884. return 1;
  885. }
  886. /*
  887. * This is the callback that is used to add our wait queue to the
  888. * target file wakeup lists.
  889. */
  890. static void ep_ptable_queue_proc(struct file *file, wait_queue_head_t *whead,
  891. poll_table *pt)
  892. {
  893. struct epitem *epi = ep_item_from_epqueue(pt);
  894. struct eppoll_entry *pwq;
  895. if (epi->nwait >= 0 && (pwq = kmem_cache_alloc(pwq_cache, GFP_KERNEL))) {
  896. init_waitqueue_func_entry(&pwq->wait, ep_poll_callback);
  897. pwq->whead = whead;
  898. pwq->base = epi;
  899. add_wait_queue(whead, &pwq->wait);
  900. list_add_tail(&pwq->llink, &epi->pwqlist);
  901. epi->nwait++;
  902. } else {
  903. /* We have to signal that an error occurred */
  904. epi->nwait = -1;
  905. }
  906. }
  907. static void ep_rbtree_insert(struct eventpoll *ep, struct epitem *epi)
  908. {
  909. int kcmp;
  910. struct rb_node **p = &ep->rbr.rb_node, *parent = NULL;
  911. struct epitem *epic;
  912. while (*p) {
  913. parent = *p;
  914. epic = rb_entry(parent, struct epitem, rbn);
  915. kcmp = ep_cmp_ffd(&epi->ffd, &epic->ffd);
  916. if (kcmp > 0)
  917. p = &parent->rb_right;
  918. else
  919. p = &parent->rb_left;
  920. }
  921. rb_link_node(&epi->rbn, parent, p);
  922. rb_insert_color(&epi->rbn, &ep->rbr);
  923. }
  924. #define PATH_ARR_SIZE 5
  925. /*
  926. * These are the number paths of length 1 to 5, that we are allowing to emanate
  927. * from a single file of interest. For example, we allow 1000 paths of length
  928. * 1, to emanate from each file of interest. This essentially represents the
  929. * potential wakeup paths, which need to be limited in order to avoid massive
  930. * uncontrolled wakeup storms. The common use case should be a single ep which
  931. * is connected to n file sources. In this case each file source has 1 path
  932. * of length 1. Thus, the numbers below should be more than sufficient. These
  933. * path limits are enforced during an EPOLL_CTL_ADD operation, since a modify
  934. * and delete can't add additional paths. Protected by the epmutex.
  935. */
  936. static const int path_limits[PATH_ARR_SIZE] = { 1000, 500, 100, 50, 10 };
  937. static int path_count[PATH_ARR_SIZE];
  938. static int path_count_inc(int nests)
  939. {
  940. /* Allow an arbitrary number of depth 1 paths */
  941. if (nests == 0)
  942. return 0;
  943. if (++path_count[nests] > path_limits[nests])
  944. return -1;
  945. return 0;
  946. }
  947. static void path_count_init(void)
  948. {
  949. int i;
  950. for (i = 0; i < PATH_ARR_SIZE; i++)
  951. path_count[i] = 0;
  952. }
  953. static int reverse_path_check_proc(void *priv, void *cookie, int call_nests)
  954. {
  955. int error = 0;
  956. struct file *file = priv;
  957. struct file *child_file;
  958. struct epitem *epi;
  959. /* CTL_DEL can remove links here, but that can't increase our count */
  960. rcu_read_lock();
  961. list_for_each_entry_rcu(epi, &file->f_ep_links, fllink) {
  962. child_file = epi->ep->file;
  963. if (is_file_epoll(child_file)) {
  964. if (list_empty(&child_file->f_ep_links)) {
  965. if (path_count_inc(call_nests)) {
  966. error = -1;
  967. break;
  968. }
  969. } else {
  970. error = ep_call_nested(&poll_loop_ncalls,
  971. EP_MAX_NESTS,
  972. reverse_path_check_proc,
  973. child_file, child_file,
  974. current);
  975. }
  976. if (error != 0)
  977. break;
  978. } else {
  979. printk(KERN_ERR "reverse_path_check_proc: "
  980. "file is not an ep!\n");
  981. }
  982. }
  983. rcu_read_unlock();
  984. return error;
  985. }
  986. /**
  987. * reverse_path_check - The tfile_check_list is list of file *, which have
  988. * links that are proposed to be newly added. We need to
  989. * make sure that those added links don't add too many
  990. * paths such that we will spend all our time waking up
  991. * eventpoll objects.
  992. *
  993. * Returns: Returns zero if the proposed links don't create too many paths,
  994. * -1 otherwise.
  995. */
  996. static int reverse_path_check(void)
  997. {
  998. int error = 0;
  999. struct file *current_file;
  1000. /* let's call this for all tfiles */
  1001. list_for_each_entry(current_file, &tfile_check_list, f_tfile_llink) {
  1002. path_count_init();
  1003. error = ep_call_nested(&poll_loop_ncalls, EP_MAX_NESTS,
  1004. reverse_path_check_proc, current_file,
  1005. current_file, current);
  1006. if (error)
  1007. break;
  1008. }
  1009. return error;
  1010. }
  1011. static int ep_create_wakeup_source(struct epitem *epi)
  1012. {
  1013. const char *name;
  1014. struct wakeup_source *ws;
  1015. if (!epi->ep->ws) {
  1016. epi->ep->ws = wakeup_source_register("eventpoll");
  1017. if (!epi->ep->ws)
  1018. return -ENOMEM;
  1019. }
  1020. name = epi->ffd.file->f_path.dentry->d_name.name;
  1021. ws = wakeup_source_register(name);
  1022. if (!ws)
  1023. return -ENOMEM;
  1024. rcu_assign_pointer(epi->ws, ws);
  1025. return 0;
  1026. }
  1027. /* rare code path, only used when EPOLL_CTL_MOD removes a wakeup source */
  1028. static noinline void ep_destroy_wakeup_source(struct epitem *epi)
  1029. {
  1030. struct wakeup_source *ws = ep_wakeup_source(epi);
  1031. RCU_INIT_POINTER(epi->ws, NULL);
  1032. /*
  1033. * wait for ep_pm_stay_awake_rcu to finish, synchronize_rcu is
  1034. * used internally by wakeup_source_remove, too (called by
  1035. * wakeup_source_unregister), so we cannot use call_rcu
  1036. */
  1037. synchronize_rcu();
  1038. wakeup_source_unregister(ws);
  1039. }
  1040. /*
  1041. * Must be called with "mtx" held.
  1042. */
  1043. static int ep_insert(struct eventpoll *ep, struct epoll_event *event,
  1044. struct file *tfile, int fd)
  1045. {
  1046. int error, revents, pwake = 0;
  1047. unsigned long flags;
  1048. long user_watches;
  1049. struct epitem *epi;
  1050. struct ep_pqueue epq;
  1051. user_watches = atomic_long_read(&ep->user->epoll_watches);
  1052. if (unlikely(user_watches >= max_user_watches))
  1053. return -ENOSPC;
  1054. if (!(epi = kmem_cache_alloc(epi_cache, GFP_KERNEL)))
  1055. return -ENOMEM;
  1056. /* Item initialization follow here ... */
  1057. INIT_LIST_HEAD(&epi->rdllink);
  1058. INIT_LIST_HEAD(&epi->fllink);
  1059. INIT_LIST_HEAD(&epi->pwqlist);
  1060. epi->ep = ep;
  1061. ep_set_ffd(&epi->ffd, tfile, fd);
  1062. epi->event = *event;
  1063. epi->nwait = 0;
  1064. epi->next = EP_UNACTIVE_PTR;
  1065. if (epi->event.events & EPOLLWAKEUP) {
  1066. error = ep_create_wakeup_source(epi);
  1067. if (error)
  1068. goto error_create_wakeup_source;
  1069. } else {
  1070. RCU_INIT_POINTER(epi->ws, NULL);
  1071. }
  1072. /* Initialize the poll table using the queue callback */
  1073. epq.epi = epi;
  1074. init_poll_funcptr(&epq.pt, ep_ptable_queue_proc);
  1075. /*
  1076. * Attach the item to the poll hooks and get current event bits.
  1077. * We can safely use the file* here because its usage count has
  1078. * been increased by the caller of this function. Note that after
  1079. * this operation completes, the poll callback can start hitting
  1080. * the new item.
  1081. */
  1082. revents = ep_item_poll(epi, &epq.pt);
  1083. /*
  1084. * We have to check if something went wrong during the poll wait queue
  1085. * install process. Namely an allocation for a wait queue failed due
  1086. * high memory pressure.
  1087. */
  1088. error = -ENOMEM;
  1089. if (epi->nwait < 0)
  1090. goto error_unregister;
  1091. /* Add the current item to the list of active epoll hook for this file */
  1092. spin_lock(&tfile->f_lock);
  1093. list_add_tail_rcu(&epi->fllink, &tfile->f_ep_links);
  1094. spin_unlock(&tfile->f_lock);
  1095. /*
  1096. * Add the current item to the RB tree. All RB tree operations are
  1097. * protected by "mtx", and ep_insert() is called with "mtx" held.
  1098. */
  1099. ep_rbtree_insert(ep, epi);
  1100. /* now check if we've created too many backpaths */
  1101. error = -EINVAL;
  1102. if (reverse_path_check())
  1103. goto error_remove_epi;
  1104. /* We have to drop the new item inside our item list to keep track of it */
  1105. spin_lock_irqsave(&ep->lock, flags);
  1106. /* If the file is already "ready" we drop it inside the ready list */
  1107. if ((revents & event->events) && !ep_is_linked(&epi->rdllink)) {
  1108. list_add_tail(&epi->rdllink, &ep->rdllist);
  1109. ep_pm_stay_awake(epi);
  1110. /* Notify waiting tasks that events are available */
  1111. if (waitqueue_active(&ep->wq))
  1112. wake_up_locked(&ep->wq);
  1113. if (waitqueue_active(&ep->poll_wait))
  1114. pwake++;
  1115. }
  1116. spin_unlock_irqrestore(&ep->lock, flags);
  1117. atomic_long_inc(&ep->user->epoll_watches);
  1118. /* We have to call this outside the lock */
  1119. if (pwake)
  1120. ep_poll_safewake(&ep->poll_wait);
  1121. return 0;
  1122. error_remove_epi:
  1123. spin_lock(&tfile->f_lock);
  1124. list_del_rcu(&epi->fllink);
  1125. spin_unlock(&tfile->f_lock);
  1126. rb_erase(&epi->rbn, &ep->rbr);
  1127. error_unregister:
  1128. ep_unregister_pollwait(ep, epi);
  1129. /*
  1130. * We need to do this because an event could have been arrived on some
  1131. * allocated wait queue. Note that we don't care about the ep->ovflist
  1132. * list, since that is used/cleaned only inside a section bound by "mtx".
  1133. * And ep_insert() is called with "mtx" held.
  1134. */
  1135. spin_lock_irqsave(&ep->lock, flags);
  1136. if (ep_is_linked(&epi->rdllink))
  1137. list_del_init(&epi->rdllink);
  1138. spin_unlock_irqrestore(&ep->lock, flags);
  1139. wakeup_source_unregister(ep_wakeup_source(epi));
  1140. error_create_wakeup_source:
  1141. kmem_cache_free(epi_cache, epi);
  1142. return error;
  1143. }
  1144. /*
  1145. * Modify the interest event mask by dropping an event if the new mask
  1146. * has a match in the current file status. Must be called with "mtx" held.
  1147. */
  1148. static int ep_modify(struct eventpoll *ep, struct epitem *epi, struct epoll_event *event)
  1149. {
  1150. int pwake = 0;
  1151. unsigned int revents;
  1152. poll_table pt;
  1153. init_poll_funcptr(&pt, NULL);
  1154. /*
  1155. * Set the new event interest mask before calling f_op->poll();
  1156. * otherwise we might miss an event that happens between the
  1157. * f_op->poll() call and the new event set registering.
  1158. */
  1159. epi->event.events = event->events; /* need barrier below */
  1160. epi->event.data = event->data; /* protected by mtx */
  1161. if (epi->event.events & EPOLLWAKEUP) {
  1162. if (!ep_has_wakeup_source(epi))
  1163. ep_create_wakeup_source(epi);
  1164. } else if (ep_has_wakeup_source(epi)) {
  1165. ep_destroy_wakeup_source(epi);
  1166. }
  1167. /*
  1168. * The following barrier has two effects:
  1169. *
  1170. * 1) Flush epi changes above to other CPUs. This ensures
  1171. * we do not miss events from ep_poll_callback if an
  1172. * event occurs immediately after we call f_op->poll().
  1173. * We need this because we did not take ep->lock while
  1174. * changing epi above (but ep_poll_callback does take
  1175. * ep->lock).
  1176. *
  1177. * 2) We also need to ensure we do not miss _past_ events
  1178. * when calling f_op->poll(). This barrier also
  1179. * pairs with the barrier in wq_has_sleeper (see
  1180. * comments for wq_has_sleeper).
  1181. *
  1182. * This barrier will now guarantee ep_poll_callback or f_op->poll
  1183. * (or both) will notice the readiness of an item.
  1184. */
  1185. smp_mb();
  1186. /*
  1187. * Get current event bits. We can safely use the file* here because
  1188. * its usage count has been increased by the caller of this function.
  1189. */
  1190. revents = ep_item_poll(epi, &pt);
  1191. /*
  1192. * If the item is "hot" and it is not registered inside the ready
  1193. * list, push it inside.
  1194. */
  1195. if (revents & event->events) {
  1196. spin_lock_irq(&ep->lock);
  1197. if (!ep_is_linked(&epi->rdllink)) {
  1198. list_add_tail(&epi->rdllink, &ep->rdllist);
  1199. ep_pm_stay_awake(epi);
  1200. /* Notify waiting tasks that events are available */
  1201. if (waitqueue_active(&ep->wq))
  1202. wake_up_locked(&ep->wq);
  1203. if (waitqueue_active(&ep->poll_wait))
  1204. pwake++;
  1205. }
  1206. spin_unlock_irq(&ep->lock);
  1207. }
  1208. /* We have to call this outside the lock */
  1209. if (pwake)
  1210. ep_poll_safewake(&ep->poll_wait);
  1211. return 0;
  1212. }
  1213. static int ep_send_events_proc(struct eventpoll *ep, struct list_head *head,
  1214. void *priv)
  1215. {
  1216. struct ep_send_events_data *esed = priv;
  1217. int eventcnt;
  1218. unsigned int revents;
  1219. struct epitem *epi;
  1220. struct epoll_event __user *uevent;
  1221. struct wakeup_source *ws;
  1222. poll_table pt;
  1223. init_poll_funcptr(&pt, NULL);
  1224. /*
  1225. * We can loop without lock because we are passed a task private list.
  1226. * Items cannot vanish during the loop because ep_scan_ready_list() is
  1227. * holding "mtx" during this call.
  1228. */
  1229. for (eventcnt = 0, uevent = esed->events;
  1230. !list_empty(head) && eventcnt < esed->maxevents;) {
  1231. epi = list_first_entry(head, struct epitem, rdllink);
  1232. /*
  1233. * Activate ep->ws before deactivating epi->ws to prevent
  1234. * triggering auto-suspend here (in case we reactive epi->ws
  1235. * below).
  1236. *
  1237. * This could be rearranged to delay the deactivation of epi->ws
  1238. * instead, but then epi->ws would temporarily be out of sync
  1239. * with ep_is_linked().
  1240. */
  1241. ws = ep_wakeup_source(epi);
  1242. if (ws) {
  1243. if (ws->active)
  1244. __pm_stay_awake(ep->ws);
  1245. __pm_relax(ws);
  1246. }
  1247. list_del_init(&epi->rdllink);
  1248. revents = ep_item_poll(epi, &pt);
  1249. /*
  1250. * If the event mask intersect the caller-requested one,
  1251. * deliver the event to userspace. Again, ep_scan_ready_list()
  1252. * is holding "mtx", so no operations coming from userspace
  1253. * can change the item.
  1254. */
  1255. if (revents) {
  1256. if (__put_user(revents, &uevent->events) ||
  1257. __put_user(epi->event.data, &uevent->data)) {
  1258. list_add(&epi->rdllink, head);
  1259. ep_pm_stay_awake(epi);
  1260. return eventcnt ? eventcnt : -EFAULT;
  1261. }
  1262. eventcnt++;
  1263. uevent++;
  1264. if (epi->event.events & EPOLLONESHOT)
  1265. epi->event.events &= EP_PRIVATE_BITS;
  1266. else if (!(epi->event.events & EPOLLET)) {
  1267. /*
  1268. * If this file has been added with Level
  1269. * Trigger mode, we need to insert back inside
  1270. * the ready list, so that the next call to
  1271. * epoll_wait() will check again the events
  1272. * availability. At this point, no one can insert
  1273. * into ep->rdllist besides us. The epoll_ctl()
  1274. * callers are locked out by
  1275. * ep_scan_ready_list() holding "mtx" and the
  1276. * poll callback will queue them in ep->ovflist.
  1277. */
  1278. list_add_tail(&epi->rdllink, &ep->rdllist);
  1279. ep_pm_stay_awake(epi);
  1280. }
  1281. }
  1282. }
  1283. return eventcnt;
  1284. }
  1285. static int ep_send_events(struct eventpoll *ep,
  1286. struct epoll_event __user *events, int maxevents)
  1287. {
  1288. struct ep_send_events_data esed;
  1289. esed.maxevents = maxevents;
  1290. esed.events = events;
  1291. return ep_scan_ready_list(ep, ep_send_events_proc, &esed, 0);
  1292. }
  1293. static inline struct timespec ep_set_mstimeout(long ms)
  1294. {
  1295. struct timespec now, ts = {
  1296. .tv_sec = ms / MSEC_PER_SEC,
  1297. .tv_nsec = NSEC_PER_MSEC * (ms % MSEC_PER_SEC),
  1298. };
  1299. ktime_get_ts(&now);
  1300. return timespec_add_safe(now, ts);
  1301. }
  1302. /**
  1303. * ep_poll - Retrieves ready events, and delivers them to the caller supplied
  1304. * event buffer.
  1305. *
  1306. * @ep: Pointer to the eventpoll context.
  1307. * @events: Pointer to the userspace buffer where the ready events should be
  1308. * stored.
  1309. * @maxevents: Size (in terms of number of events) of the caller event buffer.
  1310. * @timeout: Maximum timeout for the ready events fetch operation, in
  1311. * milliseconds. If the @timeout is zero, the function will not block,
  1312. * while if the @timeout is less than zero, the function will block
  1313. * until at least one event has been retrieved (or an error
  1314. * occurred).
  1315. *
  1316. * Returns: Returns the number of ready events which have been fetched, or an
  1317. * error code, in case of error.
  1318. */
  1319. static int ep_poll(struct eventpoll *ep, struct epoll_event __user *events,
  1320. int maxevents, long timeout)
  1321. {
  1322. int res = 0, eavail, timed_out = 0;
  1323. unsigned long flags;
  1324. u64 slack = 0;
  1325. wait_queue_t wait;
  1326. ktime_t expires, *to = NULL;
  1327. if (timeout > 0) {
  1328. struct timespec end_time = ep_set_mstimeout(timeout);
  1329. slack = select_estimate_accuracy(&end_time);
  1330. to = &expires;
  1331. *to = timespec_to_ktime(end_time);
  1332. } else if (timeout == 0) {
  1333. /*
  1334. * Avoid the unnecessary trip to the wait queue loop, if the
  1335. * caller specified a non blocking operation.
  1336. */
  1337. timed_out = 1;
  1338. spin_lock_irqsave(&ep->lock, flags);
  1339. goto check_events;
  1340. }
  1341. fetch_events:
  1342. spin_lock_irqsave(&ep->lock, flags);
  1343. if (!ep_events_available(ep)) {
  1344. /*
  1345. * We don't have any available event to return to the caller.
  1346. * We need to sleep here, and we will be wake up by
  1347. * ep_poll_callback() when events will become available.
  1348. */
  1349. init_waitqueue_entry(&wait, current);
  1350. __add_wait_queue_exclusive(&ep->wq, &wait);
  1351. for (;;) {
  1352. /*
  1353. * We don't want to sleep if the ep_poll_callback() sends us
  1354. * a wakeup in between. That's why we set the task state
  1355. * to TASK_INTERRUPTIBLE before doing the checks.
  1356. */
  1357. set_current_state(TASK_INTERRUPTIBLE);
  1358. if (ep_events_available(ep) || timed_out)
  1359. break;
  1360. if (signal_pending(current)) {
  1361. res = -EINTR;
  1362. break;
  1363. }
  1364. spin_unlock_irqrestore(&ep->lock, flags);
  1365. if (!freezable_schedule_hrtimeout_range(to, slack,
  1366. HRTIMER_MODE_ABS))
  1367. timed_out = 1;
  1368. spin_lock_irqsave(&ep->lock, flags);
  1369. }
  1370. __remove_wait_queue(&ep->wq, &wait);
  1371. set_current_state(TASK_RUNNING);
  1372. }
  1373. check_events:
  1374. /* Is it worth to try to dig for events ? */
  1375. eavail = ep_events_available(ep);
  1376. spin_unlock_irqrestore(&ep->lock, flags);
  1377. /*
  1378. * Try to transfer events to user space. In case we get 0 events and
  1379. * there's still timeout left over, we go trying again in search of
  1380. * more luck.
  1381. */
  1382. if (!res && eavail &&
  1383. !(res = ep_send_events(ep, events, maxevents)) && !timed_out)
  1384. goto fetch_events;
  1385. return res;
  1386. }
  1387. /**
  1388. * ep_loop_check_proc - Callback function to be passed to the @ep_call_nested()
  1389. * API, to verify that adding an epoll file inside another
  1390. * epoll structure, does not violate the constraints, in
  1391. * terms of closed loops, or too deep chains (which can
  1392. * result in excessive stack usage).
  1393. *
  1394. * @priv: Pointer to the epoll file to be currently checked.
  1395. * @cookie: Original cookie for this call. This is the top-of-the-chain epoll
  1396. * data structure pointer.
  1397. * @call_nests: Current dept of the @ep_call_nested() call stack.
  1398. *
  1399. * Returns: Returns zero if adding the epoll @file inside current epoll
  1400. * structure @ep does not violate the constraints, or -1 otherwise.
  1401. */
  1402. static int ep_loop_check_proc(void *priv, void *cookie, int call_nests)
  1403. {
  1404. int error = 0;
  1405. struct file *file = priv;
  1406. struct eventpoll *ep = file->private_data;
  1407. struct eventpoll *ep_tovisit;
  1408. struct rb_node *rbp;
  1409. struct epitem *epi;
  1410. mutex_lock_nested(&ep->mtx, call_nests + 1);
  1411. ep->visited = 1;
  1412. list_add(&ep->visited_list_link, &visited_list);
  1413. for (rbp = rb_first(&ep->rbr); rbp; rbp = rb_next(rbp)) {
  1414. epi = rb_entry(rbp, struct epitem, rbn);
  1415. if (unlikely(is_file_epoll(epi->ffd.file))) {
  1416. ep_tovisit = epi->ffd.file->private_data;
  1417. if (ep_tovisit->visited)
  1418. continue;
  1419. error = ep_call_nested(&poll_loop_ncalls, EP_MAX_NESTS,
  1420. ep_loop_check_proc, epi->ffd.file,
  1421. ep_tovisit, current);
  1422. if (error != 0)
  1423. break;
  1424. } else {
  1425. /*
  1426. * If we've reached a file that is not associated with
  1427. * an ep, then we need to check if the newly added
  1428. * links are going to add too many wakeup paths. We do
  1429. * this by adding it to the tfile_check_list, if it's
  1430. * not already there, and calling reverse_path_check()
  1431. * during ep_insert().
  1432. */
  1433. if (list_empty(&epi->ffd.file->f_tfile_llink)) {
  1434. if (get_file_rcu(epi->ffd.file))
  1435. list_add(&epi->ffd.file->f_tfile_llink,
  1436. &tfile_check_list);
  1437. }
  1438. }
  1439. }
  1440. mutex_unlock(&ep->mtx);
  1441. return error;
  1442. }
  1443. /**
  1444. * ep_loop_check - Performs a check to verify that adding an epoll file (@file)
  1445. * another epoll file (represented by @ep) does not create
  1446. * closed loops or too deep chains.
  1447. *
  1448. * @ep: Pointer to the epoll private data structure.
  1449. * @file: Pointer to the epoll file to be checked.
  1450. *
  1451. * Returns: Returns zero if adding the epoll @file inside current epoll
  1452. * structure @ep does not violate the constraints, or -1 otherwise.
  1453. */
  1454. static int ep_loop_check(struct eventpoll *ep, struct file *file)
  1455. {
  1456. int ret;
  1457. struct eventpoll *ep_cur, *ep_next;
  1458. ret = ep_call_nested(&poll_loop_ncalls, EP_MAX_NESTS,
  1459. ep_loop_check_proc, file, ep, current);
  1460. /* clear visited list */
  1461. list_for_each_entry_safe(ep_cur, ep_next, &visited_list,
  1462. visited_list_link) {
  1463. ep_cur->visited = 0;
  1464. list_del(&ep_cur->visited_list_link);
  1465. }
  1466. return ret;
  1467. }
  1468. static void clear_tfile_check_list(void)
  1469. {
  1470. struct file *file;
  1471. /* first clear the tfile_check_list */
  1472. while (!list_empty(&tfile_check_list)) {
  1473. file = list_first_entry(&tfile_check_list, struct file,
  1474. f_tfile_llink);
  1475. list_del_init(&file->f_tfile_llink);
  1476. fput(file);
  1477. }
  1478. INIT_LIST_HEAD(&tfile_check_list);
  1479. }
  1480. /*
  1481. * Open an eventpoll file descriptor.
  1482. */
  1483. SYSCALL_DEFINE1(epoll_create1, int, flags)
  1484. {
  1485. int error, fd;
  1486. struct eventpoll *ep = NULL;
  1487. struct file *file;
  1488. /* Check the EPOLL_* constant for consistency. */
  1489. BUILD_BUG_ON(EPOLL_CLOEXEC != O_CLOEXEC);
  1490. if (flags & ~EPOLL_CLOEXEC)
  1491. return -EINVAL;
  1492. /*
  1493. * Create the internal data structure ("struct eventpoll").
  1494. */
  1495. error = ep_alloc(&ep);
  1496. if (error < 0)
  1497. return error;
  1498. /*
  1499. * Creates all the items needed to setup an eventpoll file. That is,
  1500. * a file structure and a free file descriptor.
  1501. */
  1502. fd = get_unused_fd_flags(O_RDWR | (flags & O_CLOEXEC));
  1503. if (fd < 0) {
  1504. error = fd;
  1505. goto out_free_ep;
  1506. }
  1507. file = anon_inode_getfile("[eventpoll]", &eventpoll_fops, ep,
  1508. O_RDWR | (flags & O_CLOEXEC));
  1509. if (IS_ERR(file)) {
  1510. error = PTR_ERR(file);
  1511. goto out_free_fd;
  1512. }
  1513. fd_install(fd, file);
  1514. ep->file = file;
  1515. return fd;
  1516. out_free_fd:
  1517. put_unused_fd(fd);
  1518. out_free_ep:
  1519. ep_free(ep);
  1520. return error;
  1521. }
  1522. SYSCALL_DEFINE1(epoll_create, int, size)
  1523. {
  1524. if (size <= 0)
  1525. return -EINVAL;
  1526. return sys_epoll_create1(0);
  1527. }
  1528. /*
  1529. * The following function implements the controller interface for
  1530. * the eventpoll file that enables the insertion/removal/change of
  1531. * file descriptors inside the interest set.
  1532. */
  1533. SYSCALL_DEFINE4(epoll_ctl, int, epfd, int, op, int, fd,
  1534. struct epoll_event __user *, event)
  1535. {
  1536. int error;
  1537. int did_lock_epmutex = 0;
  1538. struct file *file, *tfile;
  1539. struct eventpoll *ep;
  1540. struct epitem *epi;
  1541. struct epoll_event epds;
  1542. error = -EFAULT;
  1543. if (ep_op_has_event(op) &&
  1544. copy_from_user(&epds, event, sizeof(struct epoll_event)))
  1545. goto error_return;
  1546. /* Get the "struct file *" for the eventpoll file */
  1547. error = -EBADF;
  1548. file = fget(epfd);
  1549. if (!file)
  1550. goto error_return;
  1551. /* Get the "struct file *" for the target file */
  1552. tfile = fget(fd);
  1553. if (!tfile)
  1554. goto error_fput;
  1555. /* The target file descriptor must support poll */
  1556. error = -EPERM;
  1557. if (!tfile->f_op || !tfile->f_op->poll)
  1558. goto error_tgt_fput;
  1559. /* Check if EPOLLWAKEUP is allowed */
  1560. if ((epds.events & EPOLLWAKEUP) && !capable(CAP_BLOCK_SUSPEND))
  1561. epds.events &= ~EPOLLWAKEUP;
  1562. /*
  1563. * We have to check that the file structure underneath the file descriptor
  1564. * the user passed to us _is_ an eventpoll file. And also we do not permit
  1565. * adding an epoll file descriptor inside itself.
  1566. */
  1567. error = -EINVAL;
  1568. if (file == tfile || !is_file_epoll(file))
  1569. goto error_tgt_fput;
  1570. /*
  1571. * At this point it is safe to assume that the "private_data" contains
  1572. * our own data structure.
  1573. */
  1574. ep = file->private_data;
  1575. /*
  1576. * When we insert an epoll file descriptor, inside another epoll file
  1577. * descriptor, there is the change of creating closed loops, which are
  1578. * better be handled here, than in more critical paths. While we are
  1579. * checking for loops we also determine the list of files reachable
  1580. * and hang them on the tfile_check_list, so we can check that we
  1581. * haven't created too many possible wakeup paths.
  1582. *
  1583. * We need to hold the epmutex across ep_insert to prevent
  1584. * multple adds from creating loops in parallel.
  1585. */
  1586. if (op == EPOLL_CTL_ADD) {
  1587. mutex_lock(&epmutex);
  1588. did_lock_epmutex = 1;
  1589. if (is_file_epoll(tfile)) {
  1590. error = -ELOOP;
  1591. if (ep_loop_check(ep, tfile) != 0) {
  1592. clear_tfile_check_list();
  1593. goto error_tgt_fput;
  1594. }
  1595. } else {
  1596. get_file(tfile);
  1597. list_add(&tfile->f_tfile_llink, &tfile_check_list);
  1598. }
  1599. }
  1600. mutex_lock_nested(&ep->mtx, 0);
  1601. /*
  1602. * Try to lookup the file inside our RB tree, Since we grabbed "mtx"
  1603. * above, we can be sure to be able to use the item looked up by
  1604. * ep_find() till we release the mutex.
  1605. */
  1606. epi = ep_find(ep, tfile, fd);
  1607. error = -EINVAL;
  1608. switch (op) {
  1609. case EPOLL_CTL_ADD:
  1610. if (!epi) {
  1611. epds.events |= POLLERR | POLLHUP;
  1612. error = ep_insert(ep, &epds, tfile, fd);
  1613. } else
  1614. error = -EEXIST;
  1615. clear_tfile_check_list();
  1616. break;
  1617. case EPOLL_CTL_DEL:
  1618. if (epi)
  1619. error = ep_remove(ep, epi);
  1620. else
  1621. error = -ENOENT;
  1622. break;
  1623. case EPOLL_CTL_MOD:
  1624. if (epi) {
  1625. epds.events |= POLLERR | POLLHUP;
  1626. error = ep_modify(ep, epi, &epds);
  1627. } else
  1628. error = -ENOENT;
  1629. break;
  1630. }
  1631. mutex_unlock(&ep->mtx);
  1632. error_tgt_fput:
  1633. if (did_lock_epmutex)
  1634. mutex_unlock(&epmutex);
  1635. fput(tfile);
  1636. error_fput:
  1637. fput(file);
  1638. error_return:
  1639. return error;
  1640. }
  1641. /*
  1642. * Implement the event wait interface for the eventpoll file. It is the kernel
  1643. * part of the user space epoll_wait(2).
  1644. */
  1645. SYSCALL_DEFINE4(epoll_wait, int, epfd, struct epoll_event __user *, events,
  1646. int, maxevents, int, timeout)
  1647. {
  1648. int error;
  1649. struct file *file;
  1650. struct eventpoll *ep;
  1651. /* The maximum number of event must be greater than zero */
  1652. if (maxevents <= 0 || maxevents > EP_MAX_EVENTS)
  1653. return -EINVAL;
  1654. /* Verify that the area passed by the user is writeable */
  1655. if (!access_ok(VERIFY_WRITE, events, maxevents * sizeof(struct epoll_event))) {
  1656. error = -EFAULT;
  1657. goto error_return;
  1658. }
  1659. /* Get the "struct file *" for the eventpoll file */
  1660. error = -EBADF;
  1661. file = fget(epfd);
  1662. if (!file)
  1663. goto error_return;
  1664. /*
  1665. * We have to check that the file structure underneath the fd
  1666. * the user passed to us _is_ an eventpoll file.
  1667. */
  1668. error = -EINVAL;
  1669. if (!is_file_epoll(file))
  1670. goto error_fput;
  1671. /*
  1672. * At this point it is safe to assume that the "private_data" contains
  1673. * our own data structure.
  1674. */
  1675. ep = file->private_data;
  1676. /* Time to fish for events ... */
  1677. error = ep_poll(ep, events, maxevents, timeout);
  1678. error_fput:
  1679. fput(file);
  1680. error_return:
  1681. return error;
  1682. }
  1683. #ifdef HAVE_SET_RESTORE_SIGMASK
  1684. /*
  1685. * Implement the event wait interface for the eventpoll file. It is the kernel
  1686. * part of the user space epoll_pwait(2).
  1687. */
  1688. SYSCALL_DEFINE6(epoll_pwait, int, epfd, struct epoll_event __user *, events,
  1689. int, maxevents, int, timeout, const sigset_t __user *, sigmask,
  1690. size_t, sigsetsize)
  1691. {
  1692. int error;
  1693. sigset_t ksigmask, sigsaved;
  1694. /*
  1695. * If the caller wants a certain signal mask to be set during the wait,
  1696. * we apply it here.
  1697. */
  1698. if (sigmask) {
  1699. if (sigsetsize != sizeof(sigset_t))
  1700. return -EINVAL;
  1701. if (copy_from_user(&ksigmask, sigmask, sizeof(ksigmask)))
  1702. return -EFAULT;
  1703. sigdelsetmask(&ksigmask, sigmask(SIGKILL) | sigmask(SIGSTOP));
  1704. sigprocmask(SIG_SETMASK, &ksigmask, &sigsaved);
  1705. }
  1706. error = sys_epoll_wait(epfd, events, maxevents, timeout);
  1707. /*
  1708. * If we changed the signal mask, we need to restore the original one.
  1709. * In case we've got a signal while waiting, we do not restore the
  1710. * signal mask yet, and we allow do_signal() to deliver the signal on
  1711. * the way back to userspace, before the signal mask is restored.
  1712. */
  1713. if (sigmask) {
  1714. if (error == -EINTR) {
  1715. memcpy(&current->saved_sigmask, &sigsaved,
  1716. sizeof(sigsaved));
  1717. set_restore_sigmask();
  1718. } else
  1719. sigprocmask(SIG_SETMASK, &sigsaved, NULL);
  1720. }
  1721. return error;
  1722. }
  1723. #endif /* HAVE_SET_RESTORE_SIGMASK */
  1724. static int __init eventpoll_init(void)
  1725. {
  1726. struct sysinfo si;
  1727. si_meminfo(&si);
  1728. /*
  1729. * Allows top 4% of lomem to be allocated for epoll watches (per user).
  1730. */
  1731. max_user_watches = (((si.totalram - si.totalhigh) / 25) << PAGE_SHIFT) /
  1732. EP_ITEM_COST;
  1733. BUG_ON(max_user_watches < 0);
  1734. /*
  1735. * Initialize the structure used to perform epoll file descriptor
  1736. * inclusion loops checks.
  1737. */
  1738. ep_nested_calls_init(&poll_loop_ncalls);
  1739. /* Initialize the structure used to perform safe poll wait head wake ups */
  1740. ep_nested_calls_init(&poll_safewake_ncalls);
  1741. /* Initialize the structure used to perform file's f_op->poll() calls */
  1742. ep_nested_calls_init(&poll_readywalk_ncalls);
  1743. /*
  1744. * We can have many thousands of epitems, so prevent this from
  1745. * using an extra cache line on 64-bit (and smaller) CPUs
  1746. */
  1747. BUILD_BUG_ON(sizeof(void *) <= 8 && sizeof(struct epitem) > 128);
  1748. /* Allocates slab cache used to allocate "struct epitem" items */
  1749. epi_cache = kmem_cache_create("eventpoll_epi", sizeof(struct epitem),
  1750. 0, SLAB_HWCACHE_ALIGN | SLAB_PANIC, NULL);
  1751. /* Allocates slab cache used to allocate "struct eppoll_entry" */
  1752. pwq_cache = kmem_cache_create("eventpoll_pwq",
  1753. sizeof(struct eppoll_entry), 0, SLAB_PANIC, NULL);
  1754. return 0;
  1755. }
  1756. fs_initcall(eventpoll_init);