eventpoll.c 63 KB

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