eventpoll.c 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330
  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 __poll_t ep_eventpoll_poll(struct file *file, poll_table *wait)
  782. {
  783. struct eventpoll *ep = file->private_data;
  784. int depth = 0;
  785. /* Insert inside our poll wait queue */
  786. poll_wait(file, &ep->poll_wait, wait);
  787. /*
  788. * Proceed to find out if wanted events are really available inside
  789. * the ready list.
  790. */
  791. return ep_scan_ready_list(ep, ep_read_events_proc,
  792. &depth, depth, false);
  793. }
  794. #ifdef CONFIG_PROC_FS
  795. static void ep_show_fdinfo(struct seq_file *m, struct file *f)
  796. {
  797. struct eventpoll *ep = f->private_data;
  798. struct rb_node *rbp;
  799. mutex_lock(&ep->mtx);
  800. for (rbp = rb_first_cached(&ep->rbr); rbp; rbp = rb_next(rbp)) {
  801. struct epitem *epi = rb_entry(rbp, struct epitem, rbn);
  802. struct inode *inode = file_inode(epi->ffd.file);
  803. seq_printf(m, "tfd: %8d events: %8x data: %16llx "
  804. " pos:%lli ino:%lx sdev:%x\n",
  805. epi->ffd.fd, epi->event.events,
  806. (long long)epi->event.data,
  807. (long long)epi->ffd.file->f_pos,
  808. inode->i_ino, inode->i_sb->s_dev);
  809. if (seq_has_overflowed(m))
  810. break;
  811. }
  812. mutex_unlock(&ep->mtx);
  813. }
  814. #endif
  815. /* File callbacks that implement the eventpoll file behaviour */
  816. static const struct file_operations eventpoll_fops = {
  817. #ifdef CONFIG_PROC_FS
  818. .show_fdinfo = ep_show_fdinfo,
  819. #endif
  820. .release = ep_eventpoll_release,
  821. .poll = ep_eventpoll_poll,
  822. .llseek = noop_llseek,
  823. };
  824. /*
  825. * This is called from eventpoll_release() to unlink files from the eventpoll
  826. * interface. We need to have this facility to cleanup correctly files that are
  827. * closed without being removed from the eventpoll interface.
  828. */
  829. void eventpoll_release_file(struct file *file)
  830. {
  831. struct eventpoll *ep;
  832. struct epitem *epi, *next;
  833. /*
  834. * We don't want to get "file->f_lock" because it is not
  835. * necessary. It is not necessary because we're in the "struct file"
  836. * cleanup path, and this means that no one is using this file anymore.
  837. * So, for example, epoll_ctl() cannot hit here since if we reach this
  838. * point, the file counter already went to zero and fget() would fail.
  839. * The only hit might come from ep_free() but by holding the mutex
  840. * will correctly serialize the operation. We do need to acquire
  841. * "ep->mtx" after "epmutex" because ep_remove() requires it when called
  842. * from anywhere but ep_free().
  843. *
  844. * Besides, ep_remove() acquires the lock, so we can't hold it here.
  845. */
  846. mutex_lock(&epmutex);
  847. list_for_each_entry_safe(epi, next, &file->f_ep_links, fllink) {
  848. ep = epi->ep;
  849. mutex_lock_nested(&ep->mtx, 0);
  850. ep_remove(ep, epi);
  851. mutex_unlock(&ep->mtx);
  852. }
  853. mutex_unlock(&epmutex);
  854. }
  855. static int ep_alloc(struct eventpoll **pep)
  856. {
  857. int error;
  858. struct user_struct *user;
  859. struct eventpoll *ep;
  860. user = get_current_user();
  861. error = -ENOMEM;
  862. ep = kzalloc(sizeof(*ep), GFP_KERNEL);
  863. if (unlikely(!ep))
  864. goto free_uid;
  865. spin_lock_init(&ep->lock);
  866. mutex_init(&ep->mtx);
  867. init_waitqueue_head(&ep->wq);
  868. init_waitqueue_head(&ep->poll_wait);
  869. INIT_LIST_HEAD(&ep->rdllist);
  870. ep->rbr = RB_ROOT_CACHED;
  871. ep->ovflist = EP_UNACTIVE_PTR;
  872. ep->user = user;
  873. *pep = ep;
  874. return 0;
  875. free_uid:
  876. free_uid(user);
  877. return error;
  878. }
  879. /*
  880. * Search the file inside the eventpoll tree. The RB tree operations
  881. * are protected by the "mtx" mutex, and ep_find() must be called with
  882. * "mtx" held.
  883. */
  884. static struct epitem *ep_find(struct eventpoll *ep, struct file *file, int fd)
  885. {
  886. int kcmp;
  887. struct rb_node *rbp;
  888. struct epitem *epi, *epir = NULL;
  889. struct epoll_filefd ffd;
  890. ep_set_ffd(&ffd, file, fd);
  891. for (rbp = ep->rbr.rb_root.rb_node; rbp; ) {
  892. epi = rb_entry(rbp, struct epitem, rbn);
  893. kcmp = ep_cmp_ffd(&ffd, &epi->ffd);
  894. if (kcmp > 0)
  895. rbp = rbp->rb_right;
  896. else if (kcmp < 0)
  897. rbp = rbp->rb_left;
  898. else {
  899. epir = epi;
  900. break;
  901. }
  902. }
  903. return epir;
  904. }
  905. #ifdef CONFIG_CHECKPOINT_RESTORE
  906. static struct epitem *ep_find_tfd(struct eventpoll *ep, int tfd, unsigned long toff)
  907. {
  908. struct rb_node *rbp;
  909. struct epitem *epi;
  910. for (rbp = rb_first_cached(&ep->rbr); rbp; rbp = rb_next(rbp)) {
  911. epi = rb_entry(rbp, struct epitem, rbn);
  912. if (epi->ffd.fd == tfd) {
  913. if (toff == 0)
  914. return epi;
  915. else
  916. toff--;
  917. }
  918. cond_resched();
  919. }
  920. return NULL;
  921. }
  922. struct file *get_epoll_tfile_raw_ptr(struct file *file, int tfd,
  923. unsigned long toff)
  924. {
  925. struct file *file_raw;
  926. struct eventpoll *ep;
  927. struct epitem *epi;
  928. if (!is_file_epoll(file))
  929. return ERR_PTR(-EINVAL);
  930. ep = file->private_data;
  931. mutex_lock(&ep->mtx);
  932. epi = ep_find_tfd(ep, tfd, toff);
  933. if (epi)
  934. file_raw = epi->ffd.file;
  935. else
  936. file_raw = ERR_PTR(-ENOENT);
  937. mutex_unlock(&ep->mtx);
  938. return file_raw;
  939. }
  940. #endif /* CONFIG_CHECKPOINT_RESTORE */
  941. /*
  942. * This is the callback that is passed to the wait queue wakeup
  943. * mechanism. It is called by the stored file descriptors when they
  944. * have events to report.
  945. */
  946. static int ep_poll_callback(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
  947. {
  948. int pwake = 0;
  949. unsigned long flags;
  950. struct epitem *epi = ep_item_from_wait(wait);
  951. struct eventpoll *ep = epi->ep;
  952. __poll_t pollflags = key_to_poll(key);
  953. int ewake = 0;
  954. spin_lock_irqsave(&ep->lock, flags);
  955. ep_set_busy_poll_napi_id(epi);
  956. /*
  957. * If the event mask does not contain any poll(2) event, we consider the
  958. * descriptor to be disabled. This condition is likely the effect of the
  959. * EPOLLONESHOT bit that disables the descriptor when an event is received,
  960. * until the next EPOLL_CTL_MOD will be issued.
  961. */
  962. if (!(epi->event.events & ~EP_PRIVATE_BITS))
  963. goto out_unlock;
  964. /*
  965. * Check the events coming with the callback. At this stage, not
  966. * every device reports the events in the "key" parameter of the
  967. * callback. We need to be able to handle both cases here, hence the
  968. * test for "key" != NULL before the event match test.
  969. */
  970. if (pollflags && !(pollflags & epi->event.events))
  971. goto out_unlock;
  972. /*
  973. * If we are transferring events to userspace, we can hold no locks
  974. * (because we're accessing user memory, and because of linux f_op->poll()
  975. * semantics). All the events that happen during that period of time are
  976. * chained in ep->ovflist and requeued later on.
  977. */
  978. if (unlikely(ep->ovflist != EP_UNACTIVE_PTR)) {
  979. if (epi->next == EP_UNACTIVE_PTR) {
  980. epi->next = ep->ovflist;
  981. ep->ovflist = epi;
  982. if (epi->ws) {
  983. /*
  984. * Activate ep->ws since epi->ws may get
  985. * deactivated at any time.
  986. */
  987. __pm_stay_awake(ep->ws);
  988. }
  989. }
  990. goto out_unlock;
  991. }
  992. /* If this file is already in the ready list we exit soon */
  993. if (!ep_is_linked(&epi->rdllink)) {
  994. list_add_tail(&epi->rdllink, &ep->rdllist);
  995. ep_pm_stay_awake_rcu(epi);
  996. }
  997. /*
  998. * Wake up ( if active ) both the eventpoll wait list and the ->poll()
  999. * wait list.
  1000. */
  1001. if (waitqueue_active(&ep->wq)) {
  1002. if ((epi->event.events & EPOLLEXCLUSIVE) &&
  1003. !(pollflags & POLLFREE)) {
  1004. switch (pollflags & EPOLLINOUT_BITS) {
  1005. case EPOLLIN:
  1006. if (epi->event.events & EPOLLIN)
  1007. ewake = 1;
  1008. break;
  1009. case EPOLLOUT:
  1010. if (epi->event.events & EPOLLOUT)
  1011. ewake = 1;
  1012. break;
  1013. case 0:
  1014. ewake = 1;
  1015. break;
  1016. }
  1017. }
  1018. wake_up_locked(&ep->wq);
  1019. }
  1020. if (waitqueue_active(&ep->poll_wait))
  1021. pwake++;
  1022. out_unlock:
  1023. spin_unlock_irqrestore(&ep->lock, flags);
  1024. /* We have to call this outside the lock */
  1025. if (pwake)
  1026. ep_poll_safewake(&ep->poll_wait);
  1027. if (!(epi->event.events & EPOLLEXCLUSIVE))
  1028. ewake = 1;
  1029. if (pollflags & POLLFREE) {
  1030. /*
  1031. * If we race with ep_remove_wait_queue() it can miss
  1032. * ->whead = NULL and do another remove_wait_queue() after
  1033. * us, so we can't use __remove_wait_queue().
  1034. */
  1035. list_del_init(&wait->entry);
  1036. /*
  1037. * ->whead != NULL protects us from the race with ep_free()
  1038. * or ep_remove(), ep_remove_wait_queue() takes whead->lock
  1039. * held by the caller. Once we nullify it, nothing protects
  1040. * ep/epi or even wait.
  1041. */
  1042. smp_store_release(&ep_pwq_from_wait(wait)->whead, NULL);
  1043. }
  1044. return ewake;
  1045. }
  1046. /*
  1047. * This is the callback that is used to add our wait queue to the
  1048. * target file wakeup lists.
  1049. */
  1050. static void ep_ptable_queue_proc(struct file *file, wait_queue_head_t *whead,
  1051. poll_table *pt)
  1052. {
  1053. struct epitem *epi = ep_item_from_epqueue(pt);
  1054. struct eppoll_entry *pwq;
  1055. if (epi->nwait >= 0 && (pwq = kmem_cache_alloc(pwq_cache, GFP_KERNEL))) {
  1056. init_waitqueue_func_entry(&pwq->wait, ep_poll_callback);
  1057. pwq->whead = whead;
  1058. pwq->base = epi;
  1059. if (epi->event.events & EPOLLEXCLUSIVE)
  1060. add_wait_queue_exclusive(whead, &pwq->wait);
  1061. else
  1062. add_wait_queue(whead, &pwq->wait);
  1063. list_add_tail(&pwq->llink, &epi->pwqlist);
  1064. epi->nwait++;
  1065. } else {
  1066. /* We have to signal that an error occurred */
  1067. epi->nwait = -1;
  1068. }
  1069. }
  1070. static void ep_rbtree_insert(struct eventpoll *ep, struct epitem *epi)
  1071. {
  1072. int kcmp;
  1073. struct rb_node **p = &ep->rbr.rb_root.rb_node, *parent = NULL;
  1074. struct epitem *epic;
  1075. bool leftmost = true;
  1076. while (*p) {
  1077. parent = *p;
  1078. epic = rb_entry(parent, struct epitem, rbn);
  1079. kcmp = ep_cmp_ffd(&epi->ffd, &epic->ffd);
  1080. if (kcmp > 0) {
  1081. p = &parent->rb_right;
  1082. leftmost = false;
  1083. } else
  1084. p = &parent->rb_left;
  1085. }
  1086. rb_link_node(&epi->rbn, parent, p);
  1087. rb_insert_color_cached(&epi->rbn, &ep->rbr, leftmost);
  1088. }
  1089. #define PATH_ARR_SIZE 5
  1090. /*
  1091. * These are the number paths of length 1 to 5, that we are allowing to emanate
  1092. * from a single file of interest. For example, we allow 1000 paths of length
  1093. * 1, to emanate from each file of interest. This essentially represents the
  1094. * potential wakeup paths, which need to be limited in order to avoid massive
  1095. * uncontrolled wakeup storms. The common use case should be a single ep which
  1096. * is connected to n file sources. In this case each file source has 1 path
  1097. * of length 1. Thus, the numbers below should be more than sufficient. These
  1098. * path limits are enforced during an EPOLL_CTL_ADD operation, since a modify
  1099. * and delete can't add additional paths. Protected by the epmutex.
  1100. */
  1101. static const int path_limits[PATH_ARR_SIZE] = { 1000, 500, 100, 50, 10 };
  1102. static int path_count[PATH_ARR_SIZE];
  1103. static int path_count_inc(int nests)
  1104. {
  1105. /* Allow an arbitrary number of depth 1 paths */
  1106. if (nests == 0)
  1107. return 0;
  1108. if (++path_count[nests] > path_limits[nests])
  1109. return -1;
  1110. return 0;
  1111. }
  1112. static void path_count_init(void)
  1113. {
  1114. int i;
  1115. for (i = 0; i < PATH_ARR_SIZE; i++)
  1116. path_count[i] = 0;
  1117. }
  1118. static int reverse_path_check_proc(void *priv, void *cookie, int call_nests)
  1119. {
  1120. int error = 0;
  1121. struct file *file = priv;
  1122. struct file *child_file;
  1123. struct epitem *epi;
  1124. /* CTL_DEL can remove links here, but that can't increase our count */
  1125. rcu_read_lock();
  1126. list_for_each_entry_rcu(epi, &file->f_ep_links, fllink) {
  1127. child_file = epi->ep->file;
  1128. if (is_file_epoll(child_file)) {
  1129. if (list_empty(&child_file->f_ep_links)) {
  1130. if (path_count_inc(call_nests)) {
  1131. error = -1;
  1132. break;
  1133. }
  1134. } else {
  1135. error = ep_call_nested(&poll_loop_ncalls,
  1136. EP_MAX_NESTS,
  1137. reverse_path_check_proc,
  1138. child_file, child_file,
  1139. current);
  1140. }
  1141. if (error != 0)
  1142. break;
  1143. } else {
  1144. printk(KERN_ERR "reverse_path_check_proc: "
  1145. "file is not an ep!\n");
  1146. }
  1147. }
  1148. rcu_read_unlock();
  1149. return error;
  1150. }
  1151. /**
  1152. * reverse_path_check - The tfile_check_list is list of file *, which have
  1153. * links that are proposed to be newly added. We need to
  1154. * make sure that those added links don't add too many
  1155. * paths such that we will spend all our time waking up
  1156. * eventpoll objects.
  1157. *
  1158. * Returns: Returns zero if the proposed links don't create too many paths,
  1159. * -1 otherwise.
  1160. */
  1161. static int reverse_path_check(void)
  1162. {
  1163. int error = 0;
  1164. struct file *current_file;
  1165. /* let's call this for all tfiles */
  1166. list_for_each_entry(current_file, &tfile_check_list, f_tfile_llink) {
  1167. path_count_init();
  1168. error = ep_call_nested(&poll_loop_ncalls, EP_MAX_NESTS,
  1169. reverse_path_check_proc, current_file,
  1170. current_file, current);
  1171. if (error)
  1172. break;
  1173. }
  1174. return error;
  1175. }
  1176. static int ep_create_wakeup_source(struct epitem *epi)
  1177. {
  1178. const char *name;
  1179. struct wakeup_source *ws;
  1180. if (!epi->ep->ws) {
  1181. epi->ep->ws = wakeup_source_register("eventpoll");
  1182. if (!epi->ep->ws)
  1183. return -ENOMEM;
  1184. }
  1185. name = epi->ffd.file->f_path.dentry->d_name.name;
  1186. ws = wakeup_source_register(name);
  1187. if (!ws)
  1188. return -ENOMEM;
  1189. rcu_assign_pointer(epi->ws, ws);
  1190. return 0;
  1191. }
  1192. /* rare code path, only used when EPOLL_CTL_MOD removes a wakeup source */
  1193. static noinline void ep_destroy_wakeup_source(struct epitem *epi)
  1194. {
  1195. struct wakeup_source *ws = ep_wakeup_source(epi);
  1196. RCU_INIT_POINTER(epi->ws, NULL);
  1197. /*
  1198. * wait for ep_pm_stay_awake_rcu to finish, synchronize_rcu is
  1199. * used internally by wakeup_source_remove, too (called by
  1200. * wakeup_source_unregister), so we cannot use call_rcu
  1201. */
  1202. synchronize_rcu();
  1203. wakeup_source_unregister(ws);
  1204. }
  1205. /*
  1206. * Must be called with "mtx" held.
  1207. */
  1208. static int ep_insert(struct eventpoll *ep, const struct epoll_event *event,
  1209. struct file *tfile, int fd, int full_check)
  1210. {
  1211. int error, pwake = 0;
  1212. __poll_t revents;
  1213. unsigned long flags;
  1214. long user_watches;
  1215. struct epitem *epi;
  1216. struct ep_pqueue epq;
  1217. user_watches = atomic_long_read(&ep->user->epoll_watches);
  1218. if (unlikely(user_watches >= max_user_watches))
  1219. return -ENOSPC;
  1220. if (!(epi = kmem_cache_alloc(epi_cache, GFP_KERNEL)))
  1221. return -ENOMEM;
  1222. /* Item initialization follow here ... */
  1223. INIT_LIST_HEAD(&epi->rdllink);
  1224. INIT_LIST_HEAD(&epi->fllink);
  1225. INIT_LIST_HEAD(&epi->pwqlist);
  1226. epi->ep = ep;
  1227. ep_set_ffd(&epi->ffd, tfile, fd);
  1228. epi->event = *event;
  1229. epi->nwait = 0;
  1230. epi->next = EP_UNACTIVE_PTR;
  1231. if (epi->event.events & EPOLLWAKEUP) {
  1232. error = ep_create_wakeup_source(epi);
  1233. if (error)
  1234. goto error_create_wakeup_source;
  1235. } else {
  1236. RCU_INIT_POINTER(epi->ws, NULL);
  1237. }
  1238. /* Initialize the poll table using the queue callback */
  1239. epq.epi = epi;
  1240. init_poll_funcptr(&epq.pt, ep_ptable_queue_proc);
  1241. /*
  1242. * Attach the item to the poll hooks and get current event bits.
  1243. * We can safely use the file* here because its usage count has
  1244. * been increased by the caller of this function. Note that after
  1245. * this operation completes, the poll callback can start hitting
  1246. * the new item.
  1247. */
  1248. revents = ep_item_poll(epi, &epq.pt, 1);
  1249. /*
  1250. * We have to check if something went wrong during the poll wait queue
  1251. * install process. Namely an allocation for a wait queue failed due
  1252. * high memory pressure.
  1253. */
  1254. error = -ENOMEM;
  1255. if (epi->nwait < 0)
  1256. goto error_unregister;
  1257. /* Add the current item to the list of active epoll hook for this file */
  1258. spin_lock(&tfile->f_lock);
  1259. list_add_tail_rcu(&epi->fllink, &tfile->f_ep_links);
  1260. spin_unlock(&tfile->f_lock);
  1261. /*
  1262. * Add the current item to the RB tree. All RB tree operations are
  1263. * protected by "mtx", and ep_insert() is called with "mtx" held.
  1264. */
  1265. ep_rbtree_insert(ep, epi);
  1266. /* now check if we've created too many backpaths */
  1267. error = -EINVAL;
  1268. if (full_check && reverse_path_check())
  1269. goto error_remove_epi;
  1270. /* We have to drop the new item inside our item list to keep track of it */
  1271. spin_lock_irqsave(&ep->lock, flags);
  1272. /* record NAPI ID of new item if present */
  1273. ep_set_busy_poll_napi_id(epi);
  1274. /* If the file is already "ready" we drop it inside the ready list */
  1275. if (revents && !ep_is_linked(&epi->rdllink)) {
  1276. list_add_tail(&epi->rdllink, &ep->rdllist);
  1277. ep_pm_stay_awake(epi);
  1278. /* Notify waiting tasks that events are available */
  1279. if (waitqueue_active(&ep->wq))
  1280. wake_up_locked(&ep->wq);
  1281. if (waitqueue_active(&ep->poll_wait))
  1282. pwake++;
  1283. }
  1284. spin_unlock_irqrestore(&ep->lock, flags);
  1285. atomic_long_inc(&ep->user->epoll_watches);
  1286. /* We have to call this outside the lock */
  1287. if (pwake)
  1288. ep_poll_safewake(&ep->poll_wait);
  1289. return 0;
  1290. error_remove_epi:
  1291. spin_lock(&tfile->f_lock);
  1292. list_del_rcu(&epi->fllink);
  1293. spin_unlock(&tfile->f_lock);
  1294. rb_erase_cached(&epi->rbn, &ep->rbr);
  1295. error_unregister:
  1296. ep_unregister_pollwait(ep, epi);
  1297. /*
  1298. * We need to do this because an event could have been arrived on some
  1299. * allocated wait queue. Note that we don't care about the ep->ovflist
  1300. * list, since that is used/cleaned only inside a section bound by "mtx".
  1301. * And ep_insert() is called with "mtx" held.
  1302. */
  1303. spin_lock_irqsave(&ep->lock, flags);
  1304. if (ep_is_linked(&epi->rdllink))
  1305. list_del_init(&epi->rdllink);
  1306. spin_unlock_irqrestore(&ep->lock, flags);
  1307. wakeup_source_unregister(ep_wakeup_source(epi));
  1308. error_create_wakeup_source:
  1309. kmem_cache_free(epi_cache, epi);
  1310. return error;
  1311. }
  1312. /*
  1313. * Modify the interest event mask by dropping an event if the new mask
  1314. * has a match in the current file status. Must be called with "mtx" held.
  1315. */
  1316. static int ep_modify(struct eventpoll *ep, struct epitem *epi,
  1317. const struct epoll_event *event)
  1318. {
  1319. int pwake = 0;
  1320. poll_table pt;
  1321. init_poll_funcptr(&pt, NULL);
  1322. /*
  1323. * Set the new event interest mask before calling f_op->poll();
  1324. * otherwise we might miss an event that happens between the
  1325. * f_op->poll() call and the new event set registering.
  1326. */
  1327. epi->event.events = event->events; /* need barrier below */
  1328. epi->event.data = event->data; /* protected by mtx */
  1329. if (epi->event.events & EPOLLWAKEUP) {
  1330. if (!ep_has_wakeup_source(epi))
  1331. ep_create_wakeup_source(epi);
  1332. } else if (ep_has_wakeup_source(epi)) {
  1333. ep_destroy_wakeup_source(epi);
  1334. }
  1335. /*
  1336. * The following barrier has two effects:
  1337. *
  1338. * 1) Flush epi changes above to other CPUs. This ensures
  1339. * we do not miss events from ep_poll_callback if an
  1340. * event occurs immediately after we call f_op->poll().
  1341. * We need this because we did not take ep->lock while
  1342. * changing epi above (but ep_poll_callback does take
  1343. * ep->lock).
  1344. *
  1345. * 2) We also need to ensure we do not miss _past_ events
  1346. * when calling f_op->poll(). This barrier also
  1347. * pairs with the barrier in wq_has_sleeper (see
  1348. * comments for wq_has_sleeper).
  1349. *
  1350. * This barrier will now guarantee ep_poll_callback or f_op->poll
  1351. * (or both) will notice the readiness of an item.
  1352. */
  1353. smp_mb();
  1354. /*
  1355. * Get current event bits. We can safely use the file* here because
  1356. * its usage count has been increased by the caller of this function.
  1357. * If the item is "hot" and it is not registered inside the ready
  1358. * list, push it inside.
  1359. */
  1360. if (ep_item_poll(epi, &pt, 1)) {
  1361. spin_lock_irq(&ep->lock);
  1362. if (!ep_is_linked(&epi->rdllink)) {
  1363. list_add_tail(&epi->rdllink, &ep->rdllist);
  1364. ep_pm_stay_awake(epi);
  1365. /* Notify waiting tasks that events are available */
  1366. if (waitqueue_active(&ep->wq))
  1367. wake_up_locked(&ep->wq);
  1368. if (waitqueue_active(&ep->poll_wait))
  1369. pwake++;
  1370. }
  1371. spin_unlock_irq(&ep->lock);
  1372. }
  1373. /* We have to call this outside the lock */
  1374. if (pwake)
  1375. ep_poll_safewake(&ep->poll_wait);
  1376. return 0;
  1377. }
  1378. static __poll_t ep_send_events_proc(struct eventpoll *ep, struct list_head *head,
  1379. void *priv)
  1380. {
  1381. struct ep_send_events_data *esed = priv;
  1382. __poll_t revents;
  1383. struct epitem *epi;
  1384. struct epoll_event __user *uevent;
  1385. struct wakeup_source *ws;
  1386. poll_table pt;
  1387. init_poll_funcptr(&pt, NULL);
  1388. /*
  1389. * We can loop without lock because we are passed a task private list.
  1390. * Items cannot vanish during the loop because ep_scan_ready_list() is
  1391. * holding "mtx" during this call.
  1392. */
  1393. for (esed->res = 0, uevent = esed->events;
  1394. !list_empty(head) && esed->res < esed->maxevents;) {
  1395. epi = list_first_entry(head, struct epitem, rdllink);
  1396. /*
  1397. * Activate ep->ws before deactivating epi->ws to prevent
  1398. * triggering auto-suspend here (in case we reactive epi->ws
  1399. * below).
  1400. *
  1401. * This could be rearranged to delay the deactivation of epi->ws
  1402. * instead, but then epi->ws would temporarily be out of sync
  1403. * with ep_is_linked().
  1404. */
  1405. ws = ep_wakeup_source(epi);
  1406. if (ws) {
  1407. if (ws->active)
  1408. __pm_stay_awake(ep->ws);
  1409. __pm_relax(ws);
  1410. }
  1411. list_del_init(&epi->rdllink);
  1412. revents = ep_item_poll(epi, &pt, 1);
  1413. /*
  1414. * If the event mask intersect the caller-requested one,
  1415. * deliver the event to userspace. Again, ep_scan_ready_list()
  1416. * is holding "mtx", so no operations coming from userspace
  1417. * can change the item.
  1418. */
  1419. if (revents) {
  1420. if (__put_user(revents, &uevent->events) ||
  1421. __put_user(epi->event.data, &uevent->data)) {
  1422. list_add(&epi->rdllink, head);
  1423. ep_pm_stay_awake(epi);
  1424. if (!esed->res)
  1425. esed->res = -EFAULT;
  1426. return 0;
  1427. }
  1428. esed->res++;
  1429. uevent++;
  1430. if (epi->event.events & EPOLLONESHOT)
  1431. epi->event.events &= EP_PRIVATE_BITS;
  1432. else if (!(epi->event.events & EPOLLET)) {
  1433. /*
  1434. * If this file has been added with Level
  1435. * Trigger mode, we need to insert back inside
  1436. * the ready list, so that the next call to
  1437. * epoll_wait() will check again the events
  1438. * availability. At this point, no one can insert
  1439. * into ep->rdllist besides us. The epoll_ctl()
  1440. * callers are locked out by
  1441. * ep_scan_ready_list() holding "mtx" and the
  1442. * poll callback will queue them in ep->ovflist.
  1443. */
  1444. list_add_tail(&epi->rdllink, &ep->rdllist);
  1445. ep_pm_stay_awake(epi);
  1446. }
  1447. }
  1448. }
  1449. return 0;
  1450. }
  1451. static int ep_send_events(struct eventpoll *ep,
  1452. struct epoll_event __user *events, int maxevents)
  1453. {
  1454. struct ep_send_events_data esed;
  1455. esed.maxevents = maxevents;
  1456. esed.events = events;
  1457. ep_scan_ready_list(ep, ep_send_events_proc, &esed, 0, false);
  1458. return esed.res;
  1459. }
  1460. static inline struct timespec64 ep_set_mstimeout(long ms)
  1461. {
  1462. struct timespec64 now, ts = {
  1463. .tv_sec = ms / MSEC_PER_SEC,
  1464. .tv_nsec = NSEC_PER_MSEC * (ms % MSEC_PER_SEC),
  1465. };
  1466. ktime_get_ts64(&now);
  1467. return timespec64_add_safe(now, ts);
  1468. }
  1469. /**
  1470. * ep_poll - Retrieves ready events, and delivers them to the caller supplied
  1471. * event buffer.
  1472. *
  1473. * @ep: Pointer to the eventpoll context.
  1474. * @events: Pointer to the userspace buffer where the ready events should be
  1475. * stored.
  1476. * @maxevents: Size (in terms of number of events) of the caller event buffer.
  1477. * @timeout: Maximum timeout for the ready events fetch operation, in
  1478. * milliseconds. If the @timeout is zero, the function will not block,
  1479. * while if the @timeout is less than zero, the function will block
  1480. * until at least one event has been retrieved (or an error
  1481. * occurred).
  1482. *
  1483. * Returns: Returns the number of ready events which have been fetched, or an
  1484. * error code, in case of error.
  1485. */
  1486. static int ep_poll(struct eventpoll *ep, struct epoll_event __user *events,
  1487. int maxevents, long timeout)
  1488. {
  1489. int res = 0, eavail, timed_out = 0;
  1490. unsigned long flags;
  1491. u64 slack = 0;
  1492. wait_queue_entry_t wait;
  1493. ktime_t expires, *to = NULL;
  1494. if (timeout > 0) {
  1495. struct timespec64 end_time = ep_set_mstimeout(timeout);
  1496. slack = select_estimate_accuracy(&end_time);
  1497. to = &expires;
  1498. *to = timespec64_to_ktime(end_time);
  1499. } else if (timeout == 0) {
  1500. /*
  1501. * Avoid the unnecessary trip to the wait queue loop, if the
  1502. * caller specified a non blocking operation.
  1503. */
  1504. timed_out = 1;
  1505. spin_lock_irqsave(&ep->lock, flags);
  1506. goto check_events;
  1507. }
  1508. fetch_events:
  1509. if (!ep_events_available(ep))
  1510. ep_busy_loop(ep, timed_out);
  1511. spin_lock_irqsave(&ep->lock, flags);
  1512. if (!ep_events_available(ep)) {
  1513. /*
  1514. * Busy poll timed out. Drop NAPI ID for now, we can add
  1515. * it back in when we have moved a socket with a valid NAPI
  1516. * ID onto the ready list.
  1517. */
  1518. ep_reset_busy_poll_napi_id(ep);
  1519. /*
  1520. * We don't have any available event to return to the caller.
  1521. * We need to sleep here, and we will be wake up by
  1522. * ep_poll_callback() when events will become available.
  1523. */
  1524. init_waitqueue_entry(&wait, current);
  1525. __add_wait_queue_exclusive(&ep->wq, &wait);
  1526. for (;;) {
  1527. /*
  1528. * We don't want to sleep if the ep_poll_callback() sends us
  1529. * a wakeup in between. That's why we set the task state
  1530. * to TASK_INTERRUPTIBLE before doing the checks.
  1531. */
  1532. set_current_state(TASK_INTERRUPTIBLE);
  1533. /*
  1534. * Always short-circuit for fatal signals to allow
  1535. * threads to make a timely exit without the chance of
  1536. * finding more events available and fetching
  1537. * repeatedly.
  1538. */
  1539. if (fatal_signal_pending(current)) {
  1540. res = -EINTR;
  1541. break;
  1542. }
  1543. if (ep_events_available(ep) || timed_out)
  1544. break;
  1545. if (signal_pending(current)) {
  1546. res = -EINTR;
  1547. break;
  1548. }
  1549. spin_unlock_irqrestore(&ep->lock, flags);
  1550. if (!schedule_hrtimeout_range(to, slack, HRTIMER_MODE_ABS))
  1551. timed_out = 1;
  1552. spin_lock_irqsave(&ep->lock, flags);
  1553. }
  1554. __remove_wait_queue(&ep->wq, &wait);
  1555. __set_current_state(TASK_RUNNING);
  1556. }
  1557. check_events:
  1558. /* Is it worth to try to dig for events ? */
  1559. eavail = ep_events_available(ep);
  1560. spin_unlock_irqrestore(&ep->lock, flags);
  1561. /*
  1562. * Try to transfer events to user space. In case we get 0 events and
  1563. * there's still timeout left over, we go trying again in search of
  1564. * more luck.
  1565. */
  1566. if (!res && eavail &&
  1567. !(res = ep_send_events(ep, events, maxevents)) && !timed_out)
  1568. goto fetch_events;
  1569. return res;
  1570. }
  1571. /**
  1572. * ep_loop_check_proc - Callback function to be passed to the @ep_call_nested()
  1573. * API, to verify that adding an epoll file inside another
  1574. * epoll structure, does not violate the constraints, in
  1575. * terms of closed loops, or too deep chains (which can
  1576. * result in excessive stack usage).
  1577. *
  1578. * @priv: Pointer to the epoll file to be currently checked.
  1579. * @cookie: Original cookie for this call. This is the top-of-the-chain epoll
  1580. * data structure pointer.
  1581. * @call_nests: Current dept of the @ep_call_nested() call stack.
  1582. *
  1583. * Returns: Returns zero if adding the epoll @file inside current epoll
  1584. * structure @ep does not violate the constraints, or -1 otherwise.
  1585. */
  1586. static int ep_loop_check_proc(void *priv, void *cookie, int call_nests)
  1587. {
  1588. int error = 0;
  1589. struct file *file = priv;
  1590. struct eventpoll *ep = file->private_data;
  1591. struct eventpoll *ep_tovisit;
  1592. struct rb_node *rbp;
  1593. struct epitem *epi;
  1594. mutex_lock_nested(&ep->mtx, call_nests + 1);
  1595. ep->visited = 1;
  1596. list_add(&ep->visited_list_link, &visited_list);
  1597. for (rbp = rb_first_cached(&ep->rbr); rbp; rbp = rb_next(rbp)) {
  1598. epi = rb_entry(rbp, struct epitem, rbn);
  1599. if (unlikely(is_file_epoll(epi->ffd.file))) {
  1600. ep_tovisit = epi->ffd.file->private_data;
  1601. if (ep_tovisit->visited)
  1602. continue;
  1603. error = ep_call_nested(&poll_loop_ncalls, EP_MAX_NESTS,
  1604. ep_loop_check_proc, epi->ffd.file,
  1605. ep_tovisit, current);
  1606. if (error != 0)
  1607. break;
  1608. } else {
  1609. /*
  1610. * If we've reached a file that is not associated with
  1611. * an ep, then we need to check if the newly added
  1612. * links are going to add too many wakeup paths. We do
  1613. * this by adding it to the tfile_check_list, if it's
  1614. * not already there, and calling reverse_path_check()
  1615. * during ep_insert().
  1616. */
  1617. if (list_empty(&epi->ffd.file->f_tfile_llink))
  1618. list_add(&epi->ffd.file->f_tfile_llink,
  1619. &tfile_check_list);
  1620. }
  1621. }
  1622. mutex_unlock(&ep->mtx);
  1623. return error;
  1624. }
  1625. /**
  1626. * ep_loop_check - Performs a check to verify that adding an epoll file (@file)
  1627. * another epoll file (represented by @ep) does not create
  1628. * closed loops or too deep chains.
  1629. *
  1630. * @ep: Pointer to the epoll private data structure.
  1631. * @file: Pointer to the epoll file to be checked.
  1632. *
  1633. * Returns: Returns zero if adding the epoll @file inside current epoll
  1634. * structure @ep does not violate the constraints, or -1 otherwise.
  1635. */
  1636. static int ep_loop_check(struct eventpoll *ep, struct file *file)
  1637. {
  1638. int ret;
  1639. struct eventpoll *ep_cur, *ep_next;
  1640. ret = ep_call_nested(&poll_loop_ncalls, EP_MAX_NESTS,
  1641. ep_loop_check_proc, file, ep, current);
  1642. /* clear visited list */
  1643. list_for_each_entry_safe(ep_cur, ep_next, &visited_list,
  1644. visited_list_link) {
  1645. ep_cur->visited = 0;
  1646. list_del(&ep_cur->visited_list_link);
  1647. }
  1648. return ret;
  1649. }
  1650. static void clear_tfile_check_list(void)
  1651. {
  1652. struct file *file;
  1653. /* first clear the tfile_check_list */
  1654. while (!list_empty(&tfile_check_list)) {
  1655. file = list_first_entry(&tfile_check_list, struct file,
  1656. f_tfile_llink);
  1657. list_del_init(&file->f_tfile_llink);
  1658. }
  1659. INIT_LIST_HEAD(&tfile_check_list);
  1660. }
  1661. /*
  1662. * Open an eventpoll file descriptor.
  1663. */
  1664. static int do_epoll_create(int flags)
  1665. {
  1666. int error, fd;
  1667. struct eventpoll *ep = NULL;
  1668. struct file *file;
  1669. /* Check the EPOLL_* constant for consistency. */
  1670. BUILD_BUG_ON(EPOLL_CLOEXEC != O_CLOEXEC);
  1671. if (flags & ~EPOLL_CLOEXEC)
  1672. return -EINVAL;
  1673. /*
  1674. * Create the internal data structure ("struct eventpoll").
  1675. */
  1676. error = ep_alloc(&ep);
  1677. if (error < 0)
  1678. return error;
  1679. /*
  1680. * Creates all the items needed to setup an eventpoll file. That is,
  1681. * a file structure and a free file descriptor.
  1682. */
  1683. fd = get_unused_fd_flags(O_RDWR | (flags & O_CLOEXEC));
  1684. if (fd < 0) {
  1685. error = fd;
  1686. goto out_free_ep;
  1687. }
  1688. file = anon_inode_getfile("[eventpoll]", &eventpoll_fops, ep,
  1689. O_RDWR | (flags & O_CLOEXEC));
  1690. if (IS_ERR(file)) {
  1691. error = PTR_ERR(file);
  1692. goto out_free_fd;
  1693. }
  1694. ep->file = file;
  1695. fd_install(fd, file);
  1696. return fd;
  1697. out_free_fd:
  1698. put_unused_fd(fd);
  1699. out_free_ep:
  1700. ep_free(ep);
  1701. return error;
  1702. }
  1703. SYSCALL_DEFINE1(epoll_create1, int, flags)
  1704. {
  1705. return do_epoll_create(flags);
  1706. }
  1707. SYSCALL_DEFINE1(epoll_create, int, size)
  1708. {
  1709. if (size <= 0)
  1710. return -EINVAL;
  1711. return do_epoll_create(0);
  1712. }
  1713. /*
  1714. * The following function implements the controller interface for
  1715. * the eventpoll file that enables the insertion/removal/change of
  1716. * file descriptors inside the interest set.
  1717. */
  1718. SYSCALL_DEFINE4(epoll_ctl, int, epfd, int, op, int, fd,
  1719. struct epoll_event __user *, event)
  1720. {
  1721. int error;
  1722. int full_check = 0;
  1723. struct fd f, tf;
  1724. struct eventpoll *ep;
  1725. struct epitem *epi;
  1726. struct epoll_event epds;
  1727. struct eventpoll *tep = NULL;
  1728. error = -EFAULT;
  1729. if (ep_op_has_event(op) &&
  1730. copy_from_user(&epds, event, sizeof(struct epoll_event)))
  1731. goto error_return;
  1732. error = -EBADF;
  1733. f = fdget(epfd);
  1734. if (!f.file)
  1735. goto error_return;
  1736. /* Get the "struct file *" for the target file */
  1737. tf = fdget(fd);
  1738. if (!tf.file)
  1739. goto error_fput;
  1740. /* The target file descriptor must support poll */
  1741. error = -EPERM;
  1742. if (!file_can_poll(tf.file))
  1743. goto error_tgt_fput;
  1744. /* Check if EPOLLWAKEUP is allowed */
  1745. if (ep_op_has_event(op))
  1746. ep_take_care_of_epollwakeup(&epds);
  1747. /*
  1748. * We have to check that the file structure underneath the file descriptor
  1749. * the user passed to us _is_ an eventpoll file. And also we do not permit
  1750. * adding an epoll file descriptor inside itself.
  1751. */
  1752. error = -EINVAL;
  1753. if (f.file == tf.file || !is_file_epoll(f.file))
  1754. goto error_tgt_fput;
  1755. /*
  1756. * epoll adds to the wakeup queue at EPOLL_CTL_ADD time only,
  1757. * so EPOLLEXCLUSIVE is not allowed for a EPOLL_CTL_MOD operation.
  1758. * Also, we do not currently supported nested exclusive wakeups.
  1759. */
  1760. if (ep_op_has_event(op) && (epds.events & EPOLLEXCLUSIVE)) {
  1761. if (op == EPOLL_CTL_MOD)
  1762. goto error_tgt_fput;
  1763. if (op == EPOLL_CTL_ADD && (is_file_epoll(tf.file) ||
  1764. (epds.events & ~EPOLLEXCLUSIVE_OK_BITS)))
  1765. goto error_tgt_fput;
  1766. }
  1767. /*
  1768. * At this point it is safe to assume that the "private_data" contains
  1769. * our own data structure.
  1770. */
  1771. ep = f.file->private_data;
  1772. /*
  1773. * When we insert an epoll file descriptor, inside another epoll file
  1774. * descriptor, there is the change of creating closed loops, which are
  1775. * better be handled here, than in more critical paths. While we are
  1776. * checking for loops we also determine the list of files reachable
  1777. * and hang them on the tfile_check_list, so we can check that we
  1778. * haven't created too many possible wakeup paths.
  1779. *
  1780. * We do not need to take the global 'epumutex' on EPOLL_CTL_ADD when
  1781. * the epoll file descriptor is attaching directly to a wakeup source,
  1782. * unless the epoll file descriptor is nested. The purpose of taking the
  1783. * 'epmutex' on add is to prevent complex toplogies such as loops and
  1784. * deep wakeup paths from forming in parallel through multiple
  1785. * EPOLL_CTL_ADD operations.
  1786. */
  1787. mutex_lock_nested(&ep->mtx, 0);
  1788. if (op == EPOLL_CTL_ADD) {
  1789. if (!list_empty(&f.file->f_ep_links) ||
  1790. is_file_epoll(tf.file)) {
  1791. full_check = 1;
  1792. mutex_unlock(&ep->mtx);
  1793. mutex_lock(&epmutex);
  1794. if (is_file_epoll(tf.file)) {
  1795. error = -ELOOP;
  1796. if (ep_loop_check(ep, tf.file) != 0) {
  1797. clear_tfile_check_list();
  1798. goto error_tgt_fput;
  1799. }
  1800. } else
  1801. list_add(&tf.file->f_tfile_llink,
  1802. &tfile_check_list);
  1803. mutex_lock_nested(&ep->mtx, 0);
  1804. if (is_file_epoll(tf.file)) {
  1805. tep = tf.file->private_data;
  1806. mutex_lock_nested(&tep->mtx, 1);
  1807. }
  1808. }
  1809. }
  1810. /*
  1811. * Try to lookup the file inside our RB tree, Since we grabbed "mtx"
  1812. * above, we can be sure to be able to use the item looked up by
  1813. * ep_find() till we release the mutex.
  1814. */
  1815. epi = ep_find(ep, tf.file, fd);
  1816. error = -EINVAL;
  1817. switch (op) {
  1818. case EPOLL_CTL_ADD:
  1819. if (!epi) {
  1820. epds.events |= EPOLLERR | EPOLLHUP;
  1821. error = ep_insert(ep, &epds, tf.file, fd, full_check);
  1822. } else
  1823. error = -EEXIST;
  1824. if (full_check)
  1825. clear_tfile_check_list();
  1826. break;
  1827. case EPOLL_CTL_DEL:
  1828. if (epi)
  1829. error = ep_remove(ep, epi);
  1830. else
  1831. error = -ENOENT;
  1832. break;
  1833. case EPOLL_CTL_MOD:
  1834. if (epi) {
  1835. if (!(epi->event.events & EPOLLEXCLUSIVE)) {
  1836. epds.events |= EPOLLERR | EPOLLHUP;
  1837. error = ep_modify(ep, epi, &epds);
  1838. }
  1839. } else
  1840. error = -ENOENT;
  1841. break;
  1842. }
  1843. if (tep != NULL)
  1844. mutex_unlock(&tep->mtx);
  1845. mutex_unlock(&ep->mtx);
  1846. error_tgt_fput:
  1847. if (full_check)
  1848. mutex_unlock(&epmutex);
  1849. fdput(tf);
  1850. error_fput:
  1851. fdput(f);
  1852. error_return:
  1853. return error;
  1854. }
  1855. /*
  1856. * Implement the event wait interface for the eventpoll file. It is the kernel
  1857. * part of the user space epoll_wait(2).
  1858. */
  1859. static int do_epoll_wait(int epfd, struct epoll_event __user *events,
  1860. int maxevents, int timeout)
  1861. {
  1862. int error;
  1863. struct fd f;
  1864. struct eventpoll *ep;
  1865. /* The maximum number of event must be greater than zero */
  1866. if (maxevents <= 0 || maxevents > EP_MAX_EVENTS)
  1867. return -EINVAL;
  1868. /* Verify that the area passed by the user is writeable */
  1869. if (!access_ok(VERIFY_WRITE, events, maxevents * sizeof(struct epoll_event)))
  1870. return -EFAULT;
  1871. /* Get the "struct file *" for the eventpoll file */
  1872. f = fdget(epfd);
  1873. if (!f.file)
  1874. return -EBADF;
  1875. /*
  1876. * We have to check that the file structure underneath the fd
  1877. * the user passed to us _is_ an eventpoll file.
  1878. */
  1879. error = -EINVAL;
  1880. if (!is_file_epoll(f.file))
  1881. goto error_fput;
  1882. /*
  1883. * At this point it is safe to assume that the "private_data" contains
  1884. * our own data structure.
  1885. */
  1886. ep = f.file->private_data;
  1887. /* Time to fish for events ... */
  1888. error = ep_poll(ep, events, maxevents, timeout);
  1889. error_fput:
  1890. fdput(f);
  1891. return error;
  1892. }
  1893. SYSCALL_DEFINE4(epoll_wait, int, epfd, struct epoll_event __user *, events,
  1894. int, maxevents, int, timeout)
  1895. {
  1896. return do_epoll_wait(epfd, events, maxevents, timeout);
  1897. }
  1898. /*
  1899. * Implement the event wait interface for the eventpoll file. It is the kernel
  1900. * part of the user space epoll_pwait(2).
  1901. */
  1902. SYSCALL_DEFINE6(epoll_pwait, int, epfd, struct epoll_event __user *, events,
  1903. int, maxevents, int, timeout, const sigset_t __user *, sigmask,
  1904. size_t, sigsetsize)
  1905. {
  1906. int error;
  1907. sigset_t ksigmask, sigsaved;
  1908. /*
  1909. * If the caller wants a certain signal mask to be set during the wait,
  1910. * we apply it here.
  1911. */
  1912. if (sigmask) {
  1913. if (sigsetsize != sizeof(sigset_t))
  1914. return -EINVAL;
  1915. if (copy_from_user(&ksigmask, sigmask, sizeof(ksigmask)))
  1916. return -EFAULT;
  1917. sigsaved = current->blocked;
  1918. set_current_blocked(&ksigmask);
  1919. }
  1920. error = do_epoll_wait(epfd, events, maxevents, timeout);
  1921. /*
  1922. * If we changed the signal mask, we need to restore the original one.
  1923. * In case we've got a signal while waiting, we do not restore the
  1924. * signal mask yet, and we allow do_signal() to deliver the signal on
  1925. * the way back to userspace, before the signal mask is restored.
  1926. */
  1927. if (sigmask) {
  1928. if (error == -EINTR) {
  1929. memcpy(&current->saved_sigmask, &sigsaved,
  1930. sizeof(sigsaved));
  1931. set_restore_sigmask();
  1932. } else
  1933. set_current_blocked(&sigsaved);
  1934. }
  1935. return error;
  1936. }
  1937. #ifdef CONFIG_COMPAT
  1938. COMPAT_SYSCALL_DEFINE6(epoll_pwait, int, epfd,
  1939. struct epoll_event __user *, events,
  1940. int, maxevents, int, timeout,
  1941. const compat_sigset_t __user *, sigmask,
  1942. compat_size_t, sigsetsize)
  1943. {
  1944. long err;
  1945. sigset_t ksigmask, sigsaved;
  1946. /*
  1947. * If the caller wants a certain signal mask to be set during the wait,
  1948. * we apply it here.
  1949. */
  1950. if (sigmask) {
  1951. if (sigsetsize != sizeof(compat_sigset_t))
  1952. return -EINVAL;
  1953. if (get_compat_sigset(&ksigmask, sigmask))
  1954. return -EFAULT;
  1955. sigsaved = current->blocked;
  1956. set_current_blocked(&ksigmask);
  1957. }
  1958. err = do_epoll_wait(epfd, events, maxevents, timeout);
  1959. /*
  1960. * If we changed the signal mask, we need to restore the original one.
  1961. * In case we've got a signal while waiting, we do not restore the
  1962. * signal mask yet, and we allow do_signal() to deliver the signal on
  1963. * the way back to userspace, before the signal mask is restored.
  1964. */
  1965. if (sigmask) {
  1966. if (err == -EINTR) {
  1967. memcpy(&current->saved_sigmask, &sigsaved,
  1968. sizeof(sigsaved));
  1969. set_restore_sigmask();
  1970. } else
  1971. set_current_blocked(&sigsaved);
  1972. }
  1973. return err;
  1974. }
  1975. #endif
  1976. static int __init eventpoll_init(void)
  1977. {
  1978. struct sysinfo si;
  1979. si_meminfo(&si);
  1980. /*
  1981. * Allows top 4% of lomem to be allocated for epoll watches (per user).
  1982. */
  1983. max_user_watches = (((si.totalram - si.totalhigh) / 25) << PAGE_SHIFT) /
  1984. EP_ITEM_COST;
  1985. BUG_ON(max_user_watches < 0);
  1986. /*
  1987. * Initialize the structure used to perform epoll file descriptor
  1988. * inclusion loops checks.
  1989. */
  1990. ep_nested_calls_init(&poll_loop_ncalls);
  1991. #ifdef CONFIG_DEBUG_LOCK_ALLOC
  1992. /* Initialize the structure used to perform safe poll wait head wake ups */
  1993. ep_nested_calls_init(&poll_safewake_ncalls);
  1994. #endif
  1995. /*
  1996. * We can have many thousands of epitems, so prevent this from
  1997. * using an extra cache line on 64-bit (and smaller) CPUs
  1998. */
  1999. BUILD_BUG_ON(sizeof(void *) <= 8 && sizeof(struct epitem) > 128);
  2000. /* Allocates slab cache used to allocate "struct epitem" items */
  2001. epi_cache = kmem_cache_create("eventpoll_epi", sizeof(struct epitem),
  2002. 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT, NULL);
  2003. /* Allocates slab cache used to allocate "struct eppoll_entry" */
  2004. pwq_cache = kmem_cache_create("eventpoll_pwq",
  2005. sizeof(struct eppoll_entry), 0, SLAB_PANIC|SLAB_ACCOUNT, NULL);
  2006. return 0;
  2007. }
  2008. fs_initcall(eventpoll_init);