eventpoll.c 51 KB

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