eventpoll.c 63 KB

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