file.c 36 KB

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