eventpoll.c 59 KB

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