eventpoll.c 50 KB

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