file.c 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * linux/fs/file.c
  4. *
  5. * Copyright (C) 1998-1999, Stephen Tweedie and Bill Hawes
  6. *
  7. * Manage the dynamic fd arrays in the process files_struct.
  8. */
  9. #include <linux/syscalls.h>
  10. #include <linux/export.h>
  11. #include <linux/fs.h>
  12. #include <linux/kernel.h>
  13. #include <linux/mm.h>
  14. #include <linux/sched/signal.h>
  15. #include <linux/slab.h>
  16. #include <linux/file.h>
  17. #include <linux/fdtable.h>
  18. #include <linux/bitops.h>
  19. #include <linux/spinlock.h>
  20. #include <linux/rcupdate.h>
  21. #include <linux/close_range.h>
  22. #include <linux/file_ref.h>
  23. #include <net/sock.h>
  24. #include <linux/init_task.h>
  25. #include "internal.h"
  26. static noinline bool __file_ref_put_badval(file_ref_t *ref, unsigned long cnt)
  27. {
  28. /*
  29. * If the reference count was already in the dead zone, then this
  30. * put() operation is imbalanced. Warn, put the reference count back to
  31. * DEAD and tell the caller to not deconstruct the object.
  32. */
  33. if (WARN_ONCE(cnt >= FILE_REF_RELEASED, "imbalanced put on file reference count")) {
  34. atomic_long_set(&ref->refcnt, FILE_REF_DEAD);
  35. return false;
  36. }
  37. /*
  38. * This is a put() operation on a saturated refcount. Restore the
  39. * mean saturation value and tell the caller to not deconstruct the
  40. * object.
  41. */
  42. if (cnt > FILE_REF_MAXREF)
  43. atomic_long_set(&ref->refcnt, FILE_REF_SATURATED);
  44. return false;
  45. }
  46. /**
  47. * __file_ref_put - Slowpath of file_ref_put()
  48. * @ref: Pointer to the reference count
  49. * @cnt: Current reference count
  50. *
  51. * Invoked when the reference count is outside of the valid zone.
  52. *
  53. * Return:
  54. * True if this was the last reference with no future references
  55. * possible. This signals the caller that it can safely schedule the
  56. * object, which is protected by the reference counter, for
  57. * deconstruction.
  58. *
  59. * False if there are still active references or the put() raced
  60. * with a concurrent get()/put() pair. Caller is not allowed to
  61. * deconstruct the protected object.
  62. */
  63. bool __file_ref_put(file_ref_t *ref, unsigned long cnt)
  64. {
  65. /* Did this drop the last reference? */
  66. if (likely(cnt == FILE_REF_NOREF)) {
  67. /*
  68. * Carefully try to set the reference count to FILE_REF_DEAD.
  69. *
  70. * This can fail if a concurrent get() operation has
  71. * elevated it again or the corresponding put() even marked
  72. * it dead already. Both are valid situations and do not
  73. * require a retry. If this fails the caller is not
  74. * allowed to deconstruct the object.
  75. */
  76. if (!atomic_long_try_cmpxchg_release(&ref->refcnt, &cnt, FILE_REF_DEAD))
  77. return false;
  78. /*
  79. * The caller can safely schedule the object for
  80. * deconstruction. Provide acquire ordering.
  81. */
  82. smp_acquire__after_ctrl_dep();
  83. return true;
  84. }
  85. return __file_ref_put_badval(ref, cnt);
  86. }
  87. EXPORT_SYMBOL_GPL(__file_ref_put);
  88. unsigned int sysctl_nr_open __read_mostly = 1024*1024;
  89. unsigned int sysctl_nr_open_min = BITS_PER_LONG;
  90. /* our min() is unusable in constant expressions ;-/ */
  91. #define __const_min(x, y) ((x) < (y) ? (x) : (y))
  92. unsigned int sysctl_nr_open_max =
  93. __const_min(INT_MAX, ~(size_t)0/sizeof(void *)) & -BITS_PER_LONG;
  94. static void __free_fdtable(struct fdtable *fdt)
  95. {
  96. kvfree(fdt->fd);
  97. kvfree(fdt->open_fds);
  98. kfree(fdt);
  99. }
  100. static void free_fdtable_rcu(struct rcu_head *rcu)
  101. {
  102. __free_fdtable(container_of(rcu, struct fdtable, rcu));
  103. }
  104. #define BITBIT_NR(nr) BITS_TO_LONGS(BITS_TO_LONGS(nr))
  105. #define BITBIT_SIZE(nr) (BITBIT_NR(nr) * sizeof(long))
  106. #define fdt_words(fdt) ((fdt)->max_fds / BITS_PER_LONG) // words in ->open_fds
  107. /*
  108. * Copy 'count' fd bits from the old table to the new table and clear the extra
  109. * space if any. This does not copy the file pointers. Called with the files
  110. * spinlock held for write.
  111. */
  112. static inline void copy_fd_bitmaps(struct fdtable *nfdt, struct fdtable *ofdt,
  113. unsigned int copy_words)
  114. {
  115. unsigned int nwords = fdt_words(nfdt);
  116. bitmap_copy_and_extend(nfdt->open_fds, ofdt->open_fds,
  117. copy_words * BITS_PER_LONG, nwords * BITS_PER_LONG);
  118. bitmap_copy_and_extend(nfdt->close_on_exec, ofdt->close_on_exec,
  119. copy_words * BITS_PER_LONG, nwords * BITS_PER_LONG);
  120. bitmap_copy_and_extend(nfdt->full_fds_bits, ofdt->full_fds_bits,
  121. copy_words, nwords);
  122. }
  123. /*
  124. * Copy all file descriptors from the old table to the new, expanded table and
  125. * clear the extra space. Called with the files spinlock held for write.
  126. */
  127. static void copy_fdtable(struct fdtable *nfdt, struct fdtable *ofdt)
  128. {
  129. size_t cpy, set;
  130. BUG_ON(nfdt->max_fds < ofdt->max_fds);
  131. cpy = ofdt->max_fds * sizeof(struct file *);
  132. set = (nfdt->max_fds - ofdt->max_fds) * sizeof(struct file *);
  133. memcpy(nfdt->fd, ofdt->fd, cpy);
  134. memset((char *)nfdt->fd + cpy, 0, set);
  135. copy_fd_bitmaps(nfdt, ofdt, fdt_words(ofdt));
  136. }
  137. /*
  138. * Note how the fdtable bitmap allocations very much have to be a multiple of
  139. * BITS_PER_LONG. This is not only because we walk those things in chunks of
  140. * 'unsigned long' in some places, but simply because that is how the Linux
  141. * kernel bitmaps are defined to work: they are not "bits in an array of bytes",
  142. * they are very much "bits in an array of unsigned long".
  143. */
  144. static struct fdtable *alloc_fdtable(unsigned int slots_wanted)
  145. {
  146. struct fdtable *fdt;
  147. unsigned int nr;
  148. void *data;
  149. /*
  150. * Figure out how many fds we actually want to support in this fdtable.
  151. * Allocation steps are keyed to the size of the fdarray, since it
  152. * grows far faster than any of the other dynamic data. We try to fit
  153. * the fdarray into comfortable page-tuned chunks: starting at 1024B
  154. * and growing in powers of two from there on. Since we called only
  155. * with slots_wanted > BITS_PER_LONG (embedded instance in files->fdtab
  156. * already gives BITS_PER_LONG slots), the above boils down to
  157. * 1. use the smallest power of two large enough to give us that many
  158. * slots.
  159. * 2. on 32bit skip 64 and 128 - the minimal capacity we want there is
  160. * 256 slots (i.e. 1Kb fd array).
  161. * 3. on 64bit don't skip anything, 1Kb fd array means 128 slots there
  162. * and we are never going to be asked for 64 or less.
  163. */
  164. if (IS_ENABLED(CONFIG_32BIT) && slots_wanted < 256)
  165. nr = 256;
  166. else
  167. nr = roundup_pow_of_two(slots_wanted);
  168. /*
  169. * Note that this can drive nr *below* what we had passed if sysctl_nr_open
  170. * had been set lower between the check in expand_files() and here.
  171. *
  172. * We make sure that nr remains a multiple of BITS_PER_LONG - otherwise
  173. * bitmaps handling below becomes unpleasant, to put it mildly...
  174. */
  175. if (unlikely(nr > sysctl_nr_open)) {
  176. nr = round_down(sysctl_nr_open, BITS_PER_LONG);
  177. if (nr < slots_wanted)
  178. return ERR_PTR(-EMFILE);
  179. }
  180. /*
  181. * Check if the allocation size would exceed INT_MAX. kvmalloc_array()
  182. * and kvmalloc() will warn if the allocation size is greater than
  183. * INT_MAX, as filp_cachep objects are not __GFP_NOWARN.
  184. *
  185. * This can happen when sysctl_nr_open is set to a very high value and
  186. * a process tries to use a file descriptor near that limit. For example,
  187. * if sysctl_nr_open is set to 1073741816 (0x3ffffff8) - which is what
  188. * systemd typically sets it to - then trying to use a file descriptor
  189. * close to that value will require allocating a file descriptor table
  190. * that exceeds 8GB in size.
  191. */
  192. if (unlikely(nr > INT_MAX / sizeof(struct file *)))
  193. return ERR_PTR(-EMFILE);
  194. fdt = kmalloc_obj(struct fdtable, GFP_KERNEL_ACCOUNT);
  195. if (!fdt)
  196. goto out;
  197. fdt->max_fds = nr;
  198. data = kvmalloc_objs(struct file *, nr, GFP_KERNEL_ACCOUNT);
  199. if (!data)
  200. goto out_fdt;
  201. fdt->fd = data;
  202. data = kvmalloc(max_t(size_t,
  203. 2 * nr / BITS_PER_BYTE + BITBIT_SIZE(nr), L1_CACHE_BYTES),
  204. GFP_KERNEL_ACCOUNT);
  205. if (!data)
  206. goto out_arr;
  207. fdt->open_fds = data;
  208. data += nr / BITS_PER_BYTE;
  209. fdt->close_on_exec = data;
  210. data += nr / BITS_PER_BYTE;
  211. fdt->full_fds_bits = data;
  212. return fdt;
  213. out_arr:
  214. kvfree(fdt->fd);
  215. out_fdt:
  216. kfree(fdt);
  217. out:
  218. return ERR_PTR(-ENOMEM);
  219. }
  220. /*
  221. * Expand the file descriptor table.
  222. * This function will allocate a new fdtable and both fd array and fdset, of
  223. * the given size.
  224. * Return <0 error code on error; 0 on successful completion.
  225. * The files->file_lock should be held on entry, and will be held on exit.
  226. */
  227. static int expand_fdtable(struct files_struct *files, unsigned int nr)
  228. __releases(files->file_lock)
  229. __acquires(files->file_lock)
  230. {
  231. struct fdtable *new_fdt, *cur_fdt;
  232. spin_unlock(&files->file_lock);
  233. new_fdt = alloc_fdtable(nr + 1);
  234. /* make sure all fd_install() have seen resize_in_progress
  235. * or have finished their rcu_read_lock_sched() section.
  236. */
  237. if (atomic_read(&files->count) > 1)
  238. synchronize_rcu();
  239. spin_lock(&files->file_lock);
  240. if (IS_ERR(new_fdt))
  241. return PTR_ERR(new_fdt);
  242. cur_fdt = files_fdtable(files);
  243. BUG_ON(nr < cur_fdt->max_fds);
  244. copy_fdtable(new_fdt, cur_fdt);
  245. rcu_assign_pointer(files->fdt, new_fdt);
  246. if (cur_fdt != &files->fdtab)
  247. call_rcu(&cur_fdt->rcu, free_fdtable_rcu);
  248. /* coupled with smp_rmb() in fd_install() */
  249. smp_wmb();
  250. return 0;
  251. }
  252. /*
  253. * Expand files.
  254. * This function will expand the file structures, if the requested size exceeds
  255. * the current capacity and there is room for expansion.
  256. * Return <0 error code on error; 0 on success.
  257. * The files->file_lock should be held on entry, and will be held on exit.
  258. */
  259. static int expand_files(struct files_struct *files, unsigned int nr)
  260. __releases(files->file_lock)
  261. __acquires(files->file_lock)
  262. {
  263. struct fdtable *fdt;
  264. int error;
  265. repeat:
  266. fdt = files_fdtable(files);
  267. /* Do we need to expand? */
  268. if (nr < fdt->max_fds)
  269. return 0;
  270. if (unlikely(files->resize_in_progress)) {
  271. spin_unlock(&files->file_lock);
  272. wait_event(files->resize_wait, !files->resize_in_progress);
  273. spin_lock(&files->file_lock);
  274. goto repeat;
  275. }
  276. /* Can we expand? */
  277. if (unlikely(nr >= sysctl_nr_open))
  278. return -EMFILE;
  279. /* All good, so we try */
  280. files->resize_in_progress = true;
  281. error = expand_fdtable(files, nr);
  282. files->resize_in_progress = false;
  283. wake_up_all(&files->resize_wait);
  284. return error;
  285. }
  286. static inline void __set_close_on_exec(unsigned int fd, struct fdtable *fdt,
  287. bool set)
  288. {
  289. if (set) {
  290. __set_bit(fd, fdt->close_on_exec);
  291. } else {
  292. if (test_bit(fd, fdt->close_on_exec))
  293. __clear_bit(fd, fdt->close_on_exec);
  294. }
  295. }
  296. static inline void __set_open_fd(unsigned int fd, struct fdtable *fdt, bool set)
  297. {
  298. __set_bit(fd, fdt->open_fds);
  299. __set_close_on_exec(fd, fdt, set);
  300. fd /= BITS_PER_LONG;
  301. if (!~fdt->open_fds[fd])
  302. __set_bit(fd, fdt->full_fds_bits);
  303. }
  304. static inline void __clear_open_fd(unsigned int fd, struct fdtable *fdt)
  305. {
  306. __clear_bit(fd, fdt->open_fds);
  307. fd /= BITS_PER_LONG;
  308. if (test_bit(fd, fdt->full_fds_bits))
  309. __clear_bit(fd, fdt->full_fds_bits);
  310. }
  311. static inline bool fd_is_open(unsigned int fd, const struct fdtable *fdt)
  312. {
  313. return test_bit(fd, fdt->open_fds);
  314. }
  315. /*
  316. * Note that a sane fdtable size always has to be a multiple of
  317. * BITS_PER_LONG, since we have bitmaps that are sized by this.
  318. *
  319. * punch_hole is optional - when close_range() is asked to unshare
  320. * and close, we don't need to copy descriptors in that range, so
  321. * a smaller cloned descriptor table might suffice if the last
  322. * currently opened descriptor falls into that range.
  323. */
  324. static unsigned int sane_fdtable_size(struct fdtable *fdt, struct fd_range *punch_hole)
  325. {
  326. unsigned int last = find_last_bit(fdt->open_fds, fdt->max_fds);
  327. if (last == fdt->max_fds)
  328. return NR_OPEN_DEFAULT;
  329. if (punch_hole && punch_hole->to >= last && punch_hole->from <= last) {
  330. last = find_last_bit(fdt->open_fds, punch_hole->from);
  331. if (last == punch_hole->from)
  332. return NR_OPEN_DEFAULT;
  333. }
  334. return ALIGN(last + 1, BITS_PER_LONG);
  335. }
  336. /*
  337. * Allocate a new descriptor table and copy contents from the passed in
  338. * instance. Returns a pointer to cloned table on success, ERR_PTR()
  339. * on failure. For 'punch_hole' see sane_fdtable_size().
  340. */
  341. struct files_struct *dup_fd(struct files_struct *oldf, struct fd_range *punch_hole)
  342. {
  343. struct files_struct *newf;
  344. struct file **old_fds, **new_fds;
  345. unsigned int open_files, i;
  346. struct fdtable *old_fdt, *new_fdt;
  347. newf = kmem_cache_alloc(files_cachep, GFP_KERNEL);
  348. if (!newf)
  349. return ERR_PTR(-ENOMEM);
  350. atomic_set(&newf->count, 1);
  351. spin_lock_init(&newf->file_lock);
  352. newf->resize_in_progress = false;
  353. init_waitqueue_head(&newf->resize_wait);
  354. newf->next_fd = 0;
  355. new_fdt = &newf->fdtab;
  356. new_fdt->max_fds = NR_OPEN_DEFAULT;
  357. new_fdt->close_on_exec = newf->close_on_exec_init;
  358. new_fdt->open_fds = newf->open_fds_init;
  359. new_fdt->full_fds_bits = newf->full_fds_bits_init;
  360. new_fdt->fd = &newf->fd_array[0];
  361. spin_lock(&oldf->file_lock);
  362. old_fdt = files_fdtable(oldf);
  363. open_files = sane_fdtable_size(old_fdt, punch_hole);
  364. /*
  365. * Check whether we need to allocate a larger fd array and fd set.
  366. */
  367. while (unlikely(open_files > new_fdt->max_fds)) {
  368. spin_unlock(&oldf->file_lock);
  369. if (new_fdt != &newf->fdtab)
  370. __free_fdtable(new_fdt);
  371. new_fdt = alloc_fdtable(open_files);
  372. if (IS_ERR(new_fdt)) {
  373. kmem_cache_free(files_cachep, newf);
  374. return ERR_CAST(new_fdt);
  375. }
  376. /*
  377. * Reacquire the oldf lock and a pointer to its fd table
  378. * who knows it may have a new bigger fd table. We need
  379. * the latest pointer.
  380. */
  381. spin_lock(&oldf->file_lock);
  382. old_fdt = files_fdtable(oldf);
  383. open_files = sane_fdtable_size(old_fdt, punch_hole);
  384. }
  385. copy_fd_bitmaps(new_fdt, old_fdt, open_files / BITS_PER_LONG);
  386. old_fds = old_fdt->fd;
  387. new_fds = new_fdt->fd;
  388. /*
  389. * We may be racing against fd allocation from other threads using this
  390. * files_struct, despite holding ->file_lock.
  391. *
  392. * alloc_fd() might have already claimed a slot, while fd_install()
  393. * did not populate it yet. Note the latter operates locklessly, so
  394. * the file can show up as we are walking the array below.
  395. *
  396. * At the same time we know no files will disappear as all other
  397. * operations take the lock.
  398. *
  399. * Instead of trying to placate userspace racing with itself, we
  400. * ref the file if we see it and mark the fd slot as unused otherwise.
  401. */
  402. for (i = open_files; i != 0; i--) {
  403. struct file *f = rcu_dereference_raw(*old_fds++);
  404. if (f) {
  405. get_file(f);
  406. } else {
  407. __clear_open_fd(open_files - i, new_fdt);
  408. }
  409. rcu_assign_pointer(*new_fds++, f);
  410. }
  411. spin_unlock(&oldf->file_lock);
  412. /* clear the remainder */
  413. memset(new_fds, 0, (new_fdt->max_fds - open_files) * sizeof(struct file *));
  414. rcu_assign_pointer(newf->fdt, new_fdt);
  415. return newf;
  416. }
  417. static struct fdtable *close_files(struct files_struct * files)
  418. {
  419. /*
  420. * It is safe to dereference the fd table without RCU or
  421. * ->file_lock because this is the last reference to the
  422. * files structure.
  423. */
  424. struct fdtable *fdt = rcu_dereference_raw(files->fdt);
  425. unsigned int i, j = 0;
  426. for (;;) {
  427. unsigned long set;
  428. i = j * BITS_PER_LONG;
  429. if (i >= fdt->max_fds)
  430. break;
  431. set = fdt->open_fds[j++];
  432. while (set) {
  433. if (set & 1) {
  434. struct file *file = fdt->fd[i];
  435. if (file) {
  436. filp_close(file, files);
  437. cond_resched();
  438. }
  439. }
  440. i++;
  441. set >>= 1;
  442. }
  443. }
  444. return fdt;
  445. }
  446. void put_files_struct(struct files_struct *files)
  447. {
  448. if (atomic_dec_and_test(&files->count)) {
  449. struct fdtable *fdt = close_files(files);
  450. /* free the arrays if they are not embedded */
  451. if (fdt != &files->fdtab)
  452. __free_fdtable(fdt);
  453. kmem_cache_free(files_cachep, files);
  454. }
  455. }
  456. void exit_files(struct task_struct *tsk)
  457. {
  458. struct files_struct * files = tsk->files;
  459. if (files) {
  460. task_lock(tsk);
  461. tsk->files = NULL;
  462. task_unlock(tsk);
  463. put_files_struct(files);
  464. }
  465. }
  466. struct files_struct init_files = {
  467. .count = ATOMIC_INIT(1),
  468. .fdt = &init_files.fdtab,
  469. .fdtab = {
  470. .max_fds = NR_OPEN_DEFAULT,
  471. .fd = &init_files.fd_array[0],
  472. .close_on_exec = init_files.close_on_exec_init,
  473. .open_fds = init_files.open_fds_init,
  474. .full_fds_bits = init_files.full_fds_bits_init,
  475. },
  476. .file_lock = __SPIN_LOCK_UNLOCKED(init_files.file_lock),
  477. .resize_wait = __WAIT_QUEUE_HEAD_INITIALIZER(init_files.resize_wait),
  478. };
  479. static unsigned int find_next_fd(struct fdtable *fdt, unsigned int start)
  480. {
  481. unsigned int maxfd = fdt->max_fds; /* always multiple of BITS_PER_LONG */
  482. unsigned int maxbit = maxfd / BITS_PER_LONG;
  483. unsigned int bitbit = start / BITS_PER_LONG;
  484. unsigned int bit;
  485. /*
  486. * Try to avoid looking at the second level bitmap
  487. */
  488. bit = find_next_zero_bit(&fdt->open_fds[bitbit], BITS_PER_LONG,
  489. start & (BITS_PER_LONG - 1));
  490. if (bit < BITS_PER_LONG)
  491. return bit + bitbit * BITS_PER_LONG;
  492. bitbit = find_next_zero_bit(fdt->full_fds_bits, maxbit, bitbit) * BITS_PER_LONG;
  493. if (bitbit >= maxfd)
  494. return maxfd;
  495. if (bitbit > start)
  496. start = bitbit;
  497. return find_next_zero_bit(fdt->open_fds, maxfd, start);
  498. }
  499. /*
  500. * allocate a file descriptor, mark it busy.
  501. */
  502. static int alloc_fd(unsigned start, unsigned end, unsigned flags)
  503. {
  504. struct files_struct *files = current->files;
  505. unsigned int fd;
  506. int error;
  507. struct fdtable *fdt;
  508. spin_lock(&files->file_lock);
  509. repeat:
  510. fdt = files_fdtable(files);
  511. fd = start;
  512. if (fd < files->next_fd)
  513. fd = files->next_fd;
  514. if (likely(fd < fdt->max_fds))
  515. fd = find_next_fd(fdt, fd);
  516. /*
  517. * N.B. For clone tasks sharing a files structure, this test
  518. * will limit the total number of files that can be opened.
  519. */
  520. error = -EMFILE;
  521. if (unlikely(fd >= end))
  522. goto out;
  523. if (unlikely(fd >= fdt->max_fds)) {
  524. error = expand_files(files, fd);
  525. if (error < 0)
  526. goto out;
  527. goto repeat;
  528. }
  529. if (start <= files->next_fd)
  530. files->next_fd = fd + 1;
  531. __set_open_fd(fd, fdt, flags & O_CLOEXEC);
  532. error = fd;
  533. VFS_BUG_ON(rcu_access_pointer(fdt->fd[fd]) != NULL);
  534. out:
  535. spin_unlock(&files->file_lock);
  536. return error;
  537. }
  538. int __get_unused_fd_flags(unsigned flags, unsigned long nofile)
  539. {
  540. return alloc_fd(0, nofile, flags);
  541. }
  542. int get_unused_fd_flags(unsigned flags)
  543. {
  544. return __get_unused_fd_flags(flags, rlimit(RLIMIT_NOFILE));
  545. }
  546. EXPORT_SYMBOL(get_unused_fd_flags);
  547. static void __put_unused_fd(struct files_struct *files, unsigned int fd)
  548. {
  549. struct fdtable *fdt = files_fdtable(files);
  550. __clear_open_fd(fd, fdt);
  551. if (fd < files->next_fd)
  552. files->next_fd = fd;
  553. }
  554. void put_unused_fd(unsigned int fd)
  555. {
  556. struct files_struct *files = current->files;
  557. spin_lock(&files->file_lock);
  558. __put_unused_fd(files, fd);
  559. spin_unlock(&files->file_lock);
  560. }
  561. EXPORT_SYMBOL(put_unused_fd);
  562. /*
  563. * Install a file pointer in the fd array while it is being resized.
  564. *
  565. * We need to make sure our update to the array does not get lost as the resizing
  566. * thread can be copying the content as we modify it.
  567. *
  568. * We have two ways to do it:
  569. * - go off CPU waiting for resize_in_progress to clear
  570. * - take the spin lock
  571. *
  572. * The latter is trivial to implement and saves us from having to might_sleep()
  573. * for debugging purposes.
  574. *
  575. * This is moved out of line from fd_install() to convince gcc to optimize that
  576. * routine better.
  577. */
  578. static void noinline fd_install_slowpath(unsigned int fd, struct file *file)
  579. {
  580. struct files_struct *files = current->files;
  581. struct fdtable *fdt;
  582. spin_lock(&files->file_lock);
  583. fdt = files_fdtable(files);
  584. VFS_BUG_ON(rcu_access_pointer(fdt->fd[fd]) != NULL);
  585. rcu_assign_pointer(fdt->fd[fd], file);
  586. spin_unlock(&files->file_lock);
  587. }
  588. /**
  589. * fd_install - install a file pointer in the fd array
  590. * @fd: file descriptor to install the file in
  591. * @file: the file to install
  592. *
  593. * This consumes the "file" refcount, so callers should treat it
  594. * as if they had called fput(file).
  595. */
  596. void fd_install(unsigned int fd, struct file *file)
  597. {
  598. struct files_struct *files = current->files;
  599. struct fdtable *fdt;
  600. if (WARN_ON_ONCE(unlikely(file->f_mode & FMODE_BACKING)))
  601. return;
  602. rcu_read_lock_sched();
  603. if (unlikely(files->resize_in_progress)) {
  604. rcu_read_unlock_sched();
  605. fd_install_slowpath(fd, file);
  606. return;
  607. }
  608. /* coupled with smp_wmb() in expand_fdtable() */
  609. smp_rmb();
  610. fdt = rcu_dereference_sched(files->fdt);
  611. VFS_BUG_ON(rcu_access_pointer(fdt->fd[fd]) != NULL);
  612. rcu_assign_pointer(fdt->fd[fd], file);
  613. rcu_read_unlock_sched();
  614. }
  615. EXPORT_SYMBOL(fd_install);
  616. /**
  617. * file_close_fd_locked - return file associated with fd
  618. * @files: file struct to retrieve file from
  619. * @fd: file descriptor to retrieve file for
  620. *
  621. * Doesn't take a separate reference count.
  622. *
  623. * Context: files_lock must be held.
  624. *
  625. * Returns: The file associated with @fd (NULL if @fd is not open)
  626. */
  627. struct file *file_close_fd_locked(struct files_struct *files, unsigned fd)
  628. {
  629. struct fdtable *fdt = files_fdtable(files);
  630. struct file *file;
  631. lockdep_assert_held(&files->file_lock);
  632. if (fd >= fdt->max_fds)
  633. return NULL;
  634. fd = array_index_nospec(fd, fdt->max_fds);
  635. file = rcu_dereference_raw(fdt->fd[fd]);
  636. if (file) {
  637. rcu_assign_pointer(fdt->fd[fd], NULL);
  638. __put_unused_fd(files, fd);
  639. }
  640. return file;
  641. }
  642. int close_fd(unsigned fd)
  643. {
  644. struct files_struct *files = current->files;
  645. struct file *file;
  646. spin_lock(&files->file_lock);
  647. file = file_close_fd_locked(files, fd);
  648. spin_unlock(&files->file_lock);
  649. if (!file)
  650. return -EBADF;
  651. return filp_close(file, files);
  652. }
  653. EXPORT_SYMBOL(close_fd);
  654. /**
  655. * last_fd - return last valid index into fd table
  656. * @fdt: File descriptor table.
  657. *
  658. * Context: Either rcu read lock or files_lock must be held.
  659. *
  660. * Returns: Last valid index into fdtable.
  661. */
  662. static inline unsigned last_fd(struct fdtable *fdt)
  663. {
  664. return fdt->max_fds - 1;
  665. }
  666. static inline void __range_cloexec(struct files_struct *cur_fds,
  667. unsigned int fd, unsigned int max_fd)
  668. {
  669. struct fdtable *fdt;
  670. /* make sure we're using the correct maximum value */
  671. spin_lock(&cur_fds->file_lock);
  672. fdt = files_fdtable(cur_fds);
  673. max_fd = min(last_fd(fdt), max_fd);
  674. if (fd <= max_fd)
  675. bitmap_set(fdt->close_on_exec, fd, max_fd - fd + 1);
  676. spin_unlock(&cur_fds->file_lock);
  677. }
  678. static inline void __range_close(struct files_struct *files, unsigned int fd,
  679. unsigned int max_fd)
  680. {
  681. struct file *file;
  682. struct fdtable *fdt;
  683. unsigned n;
  684. spin_lock(&files->file_lock);
  685. fdt = files_fdtable(files);
  686. n = last_fd(fdt);
  687. max_fd = min(max_fd, n);
  688. for (fd = find_next_bit(fdt->open_fds, max_fd + 1, fd);
  689. fd <= max_fd;
  690. fd = find_next_bit(fdt->open_fds, max_fd + 1, fd + 1)) {
  691. file = file_close_fd_locked(files, fd);
  692. if (file) {
  693. spin_unlock(&files->file_lock);
  694. filp_close(file, files);
  695. cond_resched();
  696. spin_lock(&files->file_lock);
  697. fdt = files_fdtable(files);
  698. } else if (need_resched()) {
  699. spin_unlock(&files->file_lock);
  700. cond_resched();
  701. spin_lock(&files->file_lock);
  702. fdt = files_fdtable(files);
  703. }
  704. }
  705. spin_unlock(&files->file_lock);
  706. }
  707. /**
  708. * sys_close_range() - Close all file descriptors in a given range.
  709. *
  710. * @fd: starting file descriptor to close
  711. * @max_fd: last file descriptor to close
  712. * @flags: CLOSE_RANGE flags.
  713. *
  714. * This closes a range of file descriptors. All file descriptors
  715. * from @fd up to and including @max_fd are closed.
  716. * Currently, errors to close a given file descriptor are ignored.
  717. */
  718. SYSCALL_DEFINE3(close_range, unsigned int, fd, unsigned int, max_fd,
  719. unsigned int, flags)
  720. {
  721. struct task_struct *me = current;
  722. struct files_struct *cur_fds = me->files, *fds = NULL;
  723. if (flags & ~(CLOSE_RANGE_UNSHARE | CLOSE_RANGE_CLOEXEC))
  724. return -EINVAL;
  725. if (fd > max_fd)
  726. return -EINVAL;
  727. if ((flags & CLOSE_RANGE_UNSHARE) && atomic_read(&cur_fds->count) > 1) {
  728. struct fd_range range = {fd, max_fd}, *punch_hole = &range;
  729. /*
  730. * If the caller requested all fds to be made cloexec we always
  731. * copy all of the file descriptors since they still want to
  732. * use them.
  733. */
  734. if (flags & CLOSE_RANGE_CLOEXEC)
  735. punch_hole = NULL;
  736. fds = dup_fd(cur_fds, punch_hole);
  737. if (IS_ERR(fds))
  738. return PTR_ERR(fds);
  739. /*
  740. * We used to share our file descriptor table, and have now
  741. * created a private one, make sure we're using it below.
  742. */
  743. swap(cur_fds, fds);
  744. }
  745. if (flags & CLOSE_RANGE_CLOEXEC)
  746. __range_cloexec(cur_fds, fd, max_fd);
  747. else
  748. __range_close(cur_fds, fd, max_fd);
  749. if (fds) {
  750. /*
  751. * We're done closing the files we were supposed to. Time to install
  752. * the new file descriptor table and drop the old one.
  753. */
  754. task_lock(me);
  755. me->files = cur_fds;
  756. task_unlock(me);
  757. put_files_struct(fds);
  758. }
  759. return 0;
  760. }
  761. /**
  762. * file_close_fd - return file associated with fd
  763. * @fd: file descriptor to retrieve file for
  764. *
  765. * Doesn't take a separate reference count.
  766. *
  767. * Returns: The file associated with @fd (NULL if @fd is not open)
  768. */
  769. struct file *file_close_fd(unsigned int fd)
  770. {
  771. struct files_struct *files = current->files;
  772. struct file *file;
  773. spin_lock(&files->file_lock);
  774. file = file_close_fd_locked(files, fd);
  775. spin_unlock(&files->file_lock);
  776. return file;
  777. }
  778. void do_close_on_exec(struct files_struct *files)
  779. {
  780. unsigned i;
  781. struct fdtable *fdt;
  782. /* exec unshares first */
  783. spin_lock(&files->file_lock);
  784. for (i = 0; ; i++) {
  785. unsigned long set;
  786. unsigned fd = i * BITS_PER_LONG;
  787. fdt = files_fdtable(files);
  788. if (fd >= fdt->max_fds)
  789. break;
  790. set = fdt->close_on_exec[i];
  791. if (!set)
  792. continue;
  793. fdt->close_on_exec[i] = 0;
  794. for ( ; set ; fd++, set >>= 1) {
  795. struct file *file;
  796. if (!(set & 1))
  797. continue;
  798. file = fdt->fd[fd];
  799. if (!file)
  800. continue;
  801. rcu_assign_pointer(fdt->fd[fd], NULL);
  802. __put_unused_fd(files, fd);
  803. spin_unlock(&files->file_lock);
  804. filp_close(file, files);
  805. cond_resched();
  806. spin_lock(&files->file_lock);
  807. }
  808. }
  809. spin_unlock(&files->file_lock);
  810. }
  811. static struct file *__get_file_rcu(struct file __rcu **f)
  812. {
  813. struct file __rcu *file;
  814. struct file __rcu *file_reloaded;
  815. struct file __rcu *file_reloaded_cmp;
  816. file = rcu_dereference_raw(*f);
  817. if (!file)
  818. return NULL;
  819. if (unlikely(!file_ref_get(&file->f_ref)))
  820. return ERR_PTR(-EAGAIN);
  821. file_reloaded = rcu_dereference_raw(*f);
  822. /*
  823. * Ensure that all accesses have a dependency on the load from
  824. * rcu_dereference_raw() above so we get correct ordering
  825. * between reuse/allocation and the pointer check below.
  826. */
  827. file_reloaded_cmp = file_reloaded;
  828. OPTIMIZER_HIDE_VAR(file_reloaded_cmp);
  829. /*
  830. * file_ref_get() above provided a full memory barrier when we
  831. * acquired a reference.
  832. *
  833. * This is paired with the write barrier from assigning to the
  834. * __rcu protected file pointer so that if that pointer still
  835. * matches the current file, we know we have successfully
  836. * acquired a reference to the right file.
  837. *
  838. * If the pointers don't match the file has been reallocated by
  839. * SLAB_TYPESAFE_BY_RCU.
  840. */
  841. if (file == file_reloaded_cmp)
  842. return file_reloaded;
  843. fput(file);
  844. return ERR_PTR(-EAGAIN);
  845. }
  846. /**
  847. * get_file_rcu - try go get a reference to a file under rcu
  848. * @f: the file to get a reference on
  849. *
  850. * This function tries to get a reference on @f carefully verifying that
  851. * @f hasn't been reused.
  852. *
  853. * This function should rarely have to be used and only by users who
  854. * understand the implications of SLAB_TYPESAFE_BY_RCU. Try to avoid it.
  855. *
  856. * Return: Returns @f with the reference count increased or NULL.
  857. */
  858. struct file *get_file_rcu(struct file __rcu **f)
  859. {
  860. for (;;) {
  861. struct file __rcu *file;
  862. file = __get_file_rcu(f);
  863. if (!IS_ERR(file))
  864. return file;
  865. }
  866. }
  867. EXPORT_SYMBOL_GPL(get_file_rcu);
  868. /**
  869. * get_file_active - try go get a reference to a file
  870. * @f: the file to get a reference on
  871. *
  872. * In contast to get_file_rcu() the pointer itself isn't part of the
  873. * reference counting.
  874. *
  875. * This function should rarely have to be used and only by users who
  876. * understand the implications of SLAB_TYPESAFE_BY_RCU. Try to avoid it.
  877. *
  878. * Return: Returns @f with the reference count increased or NULL.
  879. */
  880. struct file *get_file_active(struct file **f)
  881. {
  882. struct file __rcu *file;
  883. rcu_read_lock();
  884. file = __get_file_rcu(f);
  885. rcu_read_unlock();
  886. if (IS_ERR(file))
  887. file = NULL;
  888. return file;
  889. }
  890. EXPORT_SYMBOL_GPL(get_file_active);
  891. static inline struct file *__fget_files_rcu(struct files_struct *files,
  892. unsigned int fd, fmode_t mask)
  893. {
  894. for (;;) {
  895. struct file *file;
  896. struct fdtable *fdt = rcu_dereference_raw(files->fdt);
  897. struct file __rcu **fdentry;
  898. unsigned long nospec_mask;
  899. /* Mask is a 0 for invalid fd's, ~0 for valid ones */
  900. nospec_mask = array_index_mask_nospec(fd, fdt->max_fds);
  901. /*
  902. * fdentry points to the 'fd' offset, or fdt->fd[0].
  903. * Loading from fdt->fd[0] is always safe, because the
  904. * array always exists.
  905. */
  906. fdentry = fdt->fd + (fd & nospec_mask);
  907. /* Do the load, then mask any invalid result */
  908. file = rcu_dereference_raw(*fdentry);
  909. file = (void *)(nospec_mask & (unsigned long)file);
  910. if (unlikely(!file))
  911. return NULL;
  912. /*
  913. * Ok, we have a file pointer that was valid at
  914. * some point, but it might have become stale since.
  915. *
  916. * We need to confirm it by incrementing the refcount
  917. * and then check the lookup again.
  918. *
  919. * file_ref_get() gives us a full memory barrier. We
  920. * only really need an 'acquire' one to protect the
  921. * loads below, but we don't have that.
  922. */
  923. if (unlikely(!file_ref_get(&file->f_ref)))
  924. continue;
  925. /*
  926. * Such a race can take two forms:
  927. *
  928. * (a) the file ref already went down to zero and the
  929. * file hasn't been reused yet or the file count
  930. * isn't zero but the file has already been reused.
  931. *
  932. * (b) the file table entry has changed under us.
  933. * Note that we don't need to re-check the 'fdt->fd'
  934. * pointer having changed, because it always goes
  935. * hand-in-hand with 'fdt'.
  936. *
  937. * If so, we need to put our ref and try again.
  938. */
  939. if (unlikely(file != rcu_dereference_raw(*fdentry)) ||
  940. unlikely(rcu_dereference_raw(files->fdt) != fdt)) {
  941. fput(file);
  942. continue;
  943. }
  944. /*
  945. * This isn't the file we're looking for or we're not
  946. * allowed to get a reference to it.
  947. */
  948. if (unlikely(file->f_mode & mask)) {
  949. fput(file);
  950. return NULL;
  951. }
  952. /*
  953. * Ok, we have a ref to the file, and checked that it
  954. * still exists.
  955. */
  956. return file;
  957. }
  958. }
  959. static struct file *__fget_files(struct files_struct *files, unsigned int fd,
  960. fmode_t mask)
  961. {
  962. struct file *file;
  963. rcu_read_lock();
  964. file = __fget_files_rcu(files, fd, mask);
  965. rcu_read_unlock();
  966. return file;
  967. }
  968. static inline struct file *__fget(unsigned int fd, fmode_t mask)
  969. {
  970. return __fget_files(current->files, fd, mask);
  971. }
  972. struct file *fget(unsigned int fd)
  973. {
  974. return __fget(fd, FMODE_PATH);
  975. }
  976. EXPORT_SYMBOL(fget);
  977. struct file *fget_raw(unsigned int fd)
  978. {
  979. return __fget(fd, 0);
  980. }
  981. EXPORT_SYMBOL(fget_raw);
  982. struct file *fget_task(struct task_struct *task, unsigned int fd)
  983. {
  984. struct file *file = NULL;
  985. task_lock(task);
  986. if (task->files)
  987. file = __fget_files(task->files, fd, 0);
  988. task_unlock(task);
  989. return file;
  990. }
  991. struct file *fget_task_next(struct task_struct *task, unsigned int *ret_fd)
  992. {
  993. /* Must be called with rcu_read_lock held */
  994. struct files_struct *files;
  995. unsigned int fd = *ret_fd;
  996. struct file *file = NULL;
  997. task_lock(task);
  998. files = task->files;
  999. if (files) {
  1000. rcu_read_lock();
  1001. for (; fd < files_fdtable(files)->max_fds; fd++) {
  1002. file = __fget_files_rcu(files, fd, 0);
  1003. if (file)
  1004. break;
  1005. }
  1006. rcu_read_unlock();
  1007. }
  1008. task_unlock(task);
  1009. *ret_fd = fd;
  1010. return file;
  1011. }
  1012. EXPORT_SYMBOL(fget_task_next);
  1013. /*
  1014. * Lightweight file lookup - no refcnt increment if fd table isn't shared.
  1015. *
  1016. * You can use this instead of fget if you satisfy all of the following
  1017. * conditions:
  1018. * 1) You must call fput_light before exiting the syscall and returning control
  1019. * to userspace (i.e. you cannot remember the returned struct file * after
  1020. * returning to userspace).
  1021. * 2) You must not call filp_close on the returned struct file * in between
  1022. * calls to fget_light and fput_light.
  1023. * 3) You must not clone the current task in between the calls to fget_light
  1024. * and fput_light.
  1025. *
  1026. * The fput_needed flag returned by fget_light should be passed to the
  1027. * corresponding fput_light.
  1028. *
  1029. * (As an exception to rule 2, you can call filp_close between fget_light and
  1030. * fput_light provided that you capture a real refcount with get_file before
  1031. * the call to filp_close, and ensure that this real refcount is fput *after*
  1032. * the fput_light call.)
  1033. *
  1034. * See also the documentation in rust/kernel/file.rs.
  1035. */
  1036. static inline struct fd __fget_light(unsigned int fd, fmode_t mask)
  1037. {
  1038. struct files_struct *files = current->files;
  1039. struct file *file;
  1040. /*
  1041. * If another thread is concurrently calling close_fd() followed
  1042. * by put_files_struct(), we must not observe the old table
  1043. * entry combined with the new refcount - otherwise we could
  1044. * return a file that is concurrently being freed.
  1045. *
  1046. * atomic_read_acquire() pairs with atomic_dec_and_test() in
  1047. * put_files_struct().
  1048. */
  1049. if (likely(atomic_read_acquire(&files->count) == 1)) {
  1050. file = files_lookup_fd_raw(files, fd);
  1051. if (!file || unlikely(file->f_mode & mask))
  1052. return EMPTY_FD;
  1053. return BORROWED_FD(file);
  1054. } else {
  1055. file = __fget_files(files, fd, mask);
  1056. if (!file)
  1057. return EMPTY_FD;
  1058. return CLONED_FD(file);
  1059. }
  1060. }
  1061. struct fd fdget(unsigned int fd)
  1062. {
  1063. return __fget_light(fd, FMODE_PATH);
  1064. }
  1065. EXPORT_SYMBOL(fdget);
  1066. struct fd fdget_raw(unsigned int fd)
  1067. {
  1068. return __fget_light(fd, 0);
  1069. }
  1070. /*
  1071. * Try to avoid f_pos locking. We only need it if the
  1072. * file is marked for FMODE_ATOMIC_POS, and it can be
  1073. * accessed multiple ways.
  1074. *
  1075. * Always do it for directories, because pidfd_getfd()
  1076. * can make a file accessible even if it otherwise would
  1077. * not be, and for directories this is a correctness
  1078. * issue, not a "POSIX requirement".
  1079. */
  1080. static inline bool file_needs_f_pos_lock(struct file *file)
  1081. {
  1082. if (!(file->f_mode & FMODE_ATOMIC_POS))
  1083. return false;
  1084. if (__file_ref_read_raw(&file->f_ref) != FILE_REF_ONEREF)
  1085. return true;
  1086. if (file->f_op->iterate_shared)
  1087. return true;
  1088. return false;
  1089. }
  1090. bool file_seek_cur_needs_f_lock(struct file *file)
  1091. {
  1092. if (!(file->f_mode & FMODE_ATOMIC_POS) && !file->f_op->iterate_shared)
  1093. return false;
  1094. /*
  1095. * Note that we are not guaranteed to be called after fdget_pos() on
  1096. * this file obj, in which case the caller is expected to provide the
  1097. * appropriate locking.
  1098. */
  1099. return true;
  1100. }
  1101. struct fd fdget_pos(unsigned int fd)
  1102. {
  1103. struct fd f = fdget(fd);
  1104. struct file *file = fd_file(f);
  1105. if (likely(file) && file_needs_f_pos_lock(file)) {
  1106. f.word |= FDPUT_POS_UNLOCK;
  1107. mutex_lock(&file->f_pos_lock);
  1108. }
  1109. return f;
  1110. }
  1111. void __f_unlock_pos(struct file *f)
  1112. {
  1113. mutex_unlock(&f->f_pos_lock);
  1114. }
  1115. /*
  1116. * We only lock f_pos if we have threads or if the file might be
  1117. * shared with another process. In both cases we'll have an elevated
  1118. * file count (done either by fdget() or by fork()).
  1119. */
  1120. void set_close_on_exec(unsigned int fd, int flag)
  1121. {
  1122. struct files_struct *files = current->files;
  1123. spin_lock(&files->file_lock);
  1124. __set_close_on_exec(fd, files_fdtable(files), flag);
  1125. spin_unlock(&files->file_lock);
  1126. }
  1127. bool get_close_on_exec(unsigned int fd)
  1128. {
  1129. bool res;
  1130. rcu_read_lock();
  1131. res = close_on_exec(fd, current->files);
  1132. rcu_read_unlock();
  1133. return res;
  1134. }
  1135. static int do_dup2(struct files_struct *files,
  1136. struct file *file, unsigned fd, unsigned flags)
  1137. __releases(&files->file_lock)
  1138. {
  1139. struct file *tofree;
  1140. struct fdtable *fdt;
  1141. /*
  1142. * dup2() is expected to close the file installed in the target fd slot
  1143. * (if any). However, userspace hand-picking a fd may be racing against
  1144. * its own threads which happened to allocate it in open() et al but did
  1145. * not populate it yet.
  1146. *
  1147. * Broadly speaking we may be racing against the following:
  1148. * fd = get_unused_fd_flags(); // fd slot reserved, ->fd[fd] == NULL
  1149. * file = hard_work_goes_here();
  1150. * fd_install(fd, file); // only now ->fd[fd] == file
  1151. *
  1152. * It is an invariant that a successfully allocated fd has a NULL entry
  1153. * in the array until the matching fd_install().
  1154. *
  1155. * If we fit the window, we have the fd to populate, yet no target file
  1156. * to close. Trying to ignore it and install our new file would violate
  1157. * the invariant and make fd_install() overwrite our file.
  1158. *
  1159. * Things can be done(tm) to handle this. However, the issue does not
  1160. * concern legitimate programs and we only need to make sure the kernel
  1161. * does not trip over it.
  1162. *
  1163. * The simplest way out is to return an error if we find ourselves here.
  1164. *
  1165. * POSIX is silent on the issue, we return -EBUSY.
  1166. */
  1167. fdt = files_fdtable(files);
  1168. fd = array_index_nospec(fd, fdt->max_fds);
  1169. tofree = rcu_dereference_raw(fdt->fd[fd]);
  1170. if (!tofree && fd_is_open(fd, fdt))
  1171. goto Ebusy;
  1172. get_file(file);
  1173. rcu_assign_pointer(fdt->fd[fd], file);
  1174. __set_open_fd(fd, fdt, flags & O_CLOEXEC);
  1175. spin_unlock(&files->file_lock);
  1176. if (tofree)
  1177. filp_close(tofree, files);
  1178. return fd;
  1179. Ebusy:
  1180. spin_unlock(&files->file_lock);
  1181. return -EBUSY;
  1182. }
  1183. int replace_fd(unsigned fd, struct file *file, unsigned flags)
  1184. {
  1185. int err;
  1186. struct files_struct *files = current->files;
  1187. if (!file)
  1188. return close_fd(fd);
  1189. if (fd >= rlimit(RLIMIT_NOFILE))
  1190. return -EBADF;
  1191. spin_lock(&files->file_lock);
  1192. err = expand_files(files, fd);
  1193. if (unlikely(err < 0))
  1194. goto out_unlock;
  1195. err = do_dup2(files, file, fd, flags);
  1196. if (err < 0)
  1197. return err;
  1198. return 0;
  1199. out_unlock:
  1200. spin_unlock(&files->file_lock);
  1201. return err;
  1202. }
  1203. /**
  1204. * receive_fd() - Install received file into file descriptor table
  1205. * @file: struct file that was received from another process
  1206. * @ufd: __user pointer to write new fd number to
  1207. * @o_flags: the O_* flags to apply to the new fd entry
  1208. *
  1209. * Installs a received file into the file descriptor table, with appropriate
  1210. * checks and count updates. Optionally writes the fd number to userspace, if
  1211. * @ufd is non-NULL.
  1212. *
  1213. * This helper handles its own reference counting of the incoming
  1214. * struct file.
  1215. *
  1216. * Returns newly install fd or -ve on error.
  1217. */
  1218. int receive_fd(struct file *file, int __user *ufd, unsigned int o_flags)
  1219. {
  1220. int error;
  1221. error = security_file_receive(file);
  1222. if (error)
  1223. return error;
  1224. FD_PREPARE(fdf, o_flags, file);
  1225. if (fdf.err)
  1226. return fdf.err;
  1227. get_file(file);
  1228. if (ufd) {
  1229. error = put_user(fd_prepare_fd(fdf), ufd);
  1230. if (error)
  1231. return error;
  1232. }
  1233. __receive_sock(fd_prepare_file(fdf));
  1234. return fd_publish(fdf);
  1235. }
  1236. EXPORT_SYMBOL_GPL(receive_fd);
  1237. int receive_fd_replace(int new_fd, struct file *file, unsigned int o_flags)
  1238. {
  1239. int error;
  1240. error = security_file_receive(file);
  1241. if (error)
  1242. return error;
  1243. error = replace_fd(new_fd, file, o_flags);
  1244. if (error)
  1245. return error;
  1246. __receive_sock(file);
  1247. return new_fd;
  1248. }
  1249. static int ksys_dup3(unsigned int oldfd, unsigned int newfd, int flags)
  1250. {
  1251. int err = -EBADF;
  1252. struct file *file;
  1253. struct files_struct *files = current->files;
  1254. if ((flags & ~O_CLOEXEC) != 0)
  1255. return -EINVAL;
  1256. if (unlikely(oldfd == newfd))
  1257. return -EINVAL;
  1258. if (newfd >= rlimit(RLIMIT_NOFILE))
  1259. return -EBADF;
  1260. spin_lock(&files->file_lock);
  1261. err = expand_files(files, newfd);
  1262. file = files_lookup_fd_locked(files, oldfd);
  1263. if (unlikely(!file))
  1264. goto Ebadf;
  1265. if (unlikely(err < 0)) {
  1266. if (err == -EMFILE)
  1267. goto Ebadf;
  1268. goto out_unlock;
  1269. }
  1270. return do_dup2(files, file, newfd, flags);
  1271. Ebadf:
  1272. err = -EBADF;
  1273. out_unlock:
  1274. spin_unlock(&files->file_lock);
  1275. return err;
  1276. }
  1277. SYSCALL_DEFINE3(dup3, unsigned int, oldfd, unsigned int, newfd, int, flags)
  1278. {
  1279. return ksys_dup3(oldfd, newfd, flags);
  1280. }
  1281. SYSCALL_DEFINE2(dup2, unsigned int, oldfd, unsigned int, newfd)
  1282. {
  1283. if (unlikely(newfd == oldfd)) { /* corner case */
  1284. struct files_struct *files = current->files;
  1285. struct file *f;
  1286. int retval = oldfd;
  1287. rcu_read_lock();
  1288. f = __fget_files_rcu(files, oldfd, 0);
  1289. if (!f)
  1290. retval = -EBADF;
  1291. rcu_read_unlock();
  1292. if (f)
  1293. fput(f);
  1294. return retval;
  1295. }
  1296. return ksys_dup3(oldfd, newfd, 0);
  1297. }
  1298. SYSCALL_DEFINE1(dup, unsigned int, fildes)
  1299. {
  1300. int ret = -EBADF;
  1301. struct file *file = fget_raw(fildes);
  1302. if (file) {
  1303. ret = get_unused_fd_flags(0);
  1304. if (ret >= 0)
  1305. fd_install(ret, file);
  1306. else
  1307. fput(file);
  1308. }
  1309. return ret;
  1310. }
  1311. int f_dupfd(unsigned int from, struct file *file, unsigned flags)
  1312. {
  1313. unsigned long nofile = rlimit(RLIMIT_NOFILE);
  1314. int err;
  1315. if (from >= nofile)
  1316. return -EINVAL;
  1317. err = alloc_fd(from, nofile, flags);
  1318. if (err >= 0) {
  1319. get_file(file);
  1320. fd_install(err, file);
  1321. }
  1322. return err;
  1323. }
  1324. int iterate_fd(struct files_struct *files, unsigned n,
  1325. int (*f)(const void *, struct file *, unsigned),
  1326. const void *p)
  1327. {
  1328. struct fdtable *fdt;
  1329. int res = 0;
  1330. if (!files)
  1331. return 0;
  1332. spin_lock(&files->file_lock);
  1333. for (fdt = files_fdtable(files); n < fdt->max_fds; n++) {
  1334. struct file *file;
  1335. file = rcu_dereference_check_fdtable(files, fdt->fd[n]);
  1336. if (!file)
  1337. continue;
  1338. res = f(p, file, n);
  1339. if (res)
  1340. break;
  1341. }
  1342. spin_unlock(&files->file_lock);
  1343. return res;
  1344. }
  1345. EXPORT_SYMBOL(iterate_fd);