libfs.c 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * fs/libfs.c
  4. * Library for filesystems writers.
  5. */
  6. #include <linux/blkdev.h>
  7. #include <linux/export.h>
  8. #include <linux/filelock.h>
  9. #include <linux/pagemap.h>
  10. #include <linux/slab.h>
  11. #include <linux/cred.h>
  12. #include <linux/mount.h>
  13. #include <linux/vfs.h>
  14. #include <linux/quotaops.h>
  15. #include <linux/mutex.h>
  16. #include <linux/namei.h>
  17. #include <linux/exportfs.h>
  18. #include <linux/iversion.h>
  19. #include <linux/writeback.h>
  20. #include <linux/buffer_head.h> /* sync_mapping_buffers */
  21. #include <linux/fs_context.h>
  22. #include <linux/pseudo_fs.h>
  23. #include <linux/fsnotify.h>
  24. #include <linux/unicode.h>
  25. #include <linux/fscrypt.h>
  26. #include <linux/pidfs.h>
  27. #include <linux/uaccess.h>
  28. #include "internal.h"
  29. int simple_getattr(struct mnt_idmap *idmap, const struct path *path,
  30. struct kstat *stat, u32 request_mask,
  31. unsigned int query_flags)
  32. {
  33. struct inode *inode = d_inode(path->dentry);
  34. generic_fillattr(&nop_mnt_idmap, request_mask, inode, stat);
  35. stat->blocks = inode->i_mapping->nrpages << (PAGE_SHIFT - 9);
  36. return 0;
  37. }
  38. EXPORT_SYMBOL(simple_getattr);
  39. int simple_statfs(struct dentry *dentry, struct kstatfs *buf)
  40. {
  41. u64 id = huge_encode_dev(dentry->d_sb->s_dev);
  42. buf->f_fsid = u64_to_fsid(id);
  43. buf->f_type = dentry->d_sb->s_magic;
  44. buf->f_bsize = PAGE_SIZE;
  45. buf->f_namelen = NAME_MAX;
  46. return 0;
  47. }
  48. EXPORT_SYMBOL(simple_statfs);
  49. /*
  50. * Retaining negative dentries for an in-memory filesystem just wastes
  51. * memory and lookup time: arrange for them to be deleted immediately.
  52. */
  53. int always_delete_dentry(const struct dentry *dentry)
  54. {
  55. return 1;
  56. }
  57. EXPORT_SYMBOL(always_delete_dentry);
  58. /*
  59. * Lookup the data. This is trivial - if the dentry didn't already
  60. * exist, we know it is negative. Set d_op to delete negative dentries.
  61. */
  62. struct dentry *simple_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
  63. {
  64. if (dentry->d_name.len > NAME_MAX)
  65. return ERR_PTR(-ENAMETOOLONG);
  66. if (!dentry->d_op && !(dentry->d_flags & DCACHE_DONTCACHE)) {
  67. spin_lock(&dentry->d_lock);
  68. dentry->d_flags |= DCACHE_DONTCACHE;
  69. spin_unlock(&dentry->d_lock);
  70. }
  71. if (IS_ENABLED(CONFIG_UNICODE) && IS_CASEFOLDED(dir))
  72. return NULL;
  73. d_add(dentry, NULL);
  74. return NULL;
  75. }
  76. EXPORT_SYMBOL(simple_lookup);
  77. int dcache_dir_open(struct inode *inode, struct file *file)
  78. {
  79. file->private_data = d_alloc_cursor(file->f_path.dentry);
  80. return file->private_data ? 0 : -ENOMEM;
  81. }
  82. EXPORT_SYMBOL(dcache_dir_open);
  83. int dcache_dir_close(struct inode *inode, struct file *file)
  84. {
  85. dput(file->private_data);
  86. return 0;
  87. }
  88. EXPORT_SYMBOL(dcache_dir_close);
  89. /* parent is locked at least shared */
  90. /*
  91. * Returns an element of siblings' list.
  92. * We are looking for <count>th positive after <p>; if
  93. * found, dentry is grabbed and returned to caller.
  94. * If no such element exists, NULL is returned.
  95. */
  96. static struct dentry *scan_positives(struct dentry *cursor,
  97. struct hlist_node **p,
  98. loff_t count,
  99. struct dentry *last)
  100. {
  101. struct dentry *dentry = cursor->d_parent, *found = NULL;
  102. spin_lock(&dentry->d_lock);
  103. while (*p) {
  104. struct dentry *d = hlist_entry(*p, struct dentry, d_sib);
  105. p = &d->d_sib.next;
  106. // we must at least skip cursors, to avoid livelocks
  107. if (d->d_flags & DCACHE_DENTRY_CURSOR)
  108. continue;
  109. if (simple_positive(d) && !--count) {
  110. spin_lock_nested(&d->d_lock, DENTRY_D_LOCK_NESTED);
  111. if (simple_positive(d))
  112. found = dget_dlock(d);
  113. spin_unlock(&d->d_lock);
  114. if (likely(found))
  115. break;
  116. count = 1;
  117. }
  118. if (need_resched()) {
  119. if (!hlist_unhashed(&cursor->d_sib))
  120. __hlist_del(&cursor->d_sib);
  121. hlist_add_behind(&cursor->d_sib, &d->d_sib);
  122. p = &cursor->d_sib.next;
  123. spin_unlock(&dentry->d_lock);
  124. cond_resched();
  125. spin_lock(&dentry->d_lock);
  126. }
  127. }
  128. spin_unlock(&dentry->d_lock);
  129. dput(last);
  130. return found;
  131. }
  132. loff_t dcache_dir_lseek(struct file *file, loff_t offset, int whence)
  133. {
  134. struct dentry *dentry = file->f_path.dentry;
  135. switch (whence) {
  136. case 1:
  137. offset += file->f_pos;
  138. fallthrough;
  139. case 0:
  140. if (offset >= 0)
  141. break;
  142. fallthrough;
  143. default:
  144. return -EINVAL;
  145. }
  146. if (offset != file->f_pos) {
  147. struct dentry *cursor = file->private_data;
  148. struct dentry *to = NULL;
  149. inode_lock_shared(dentry->d_inode);
  150. if (offset > 2)
  151. to = scan_positives(cursor, &dentry->d_children.first,
  152. offset - 2, NULL);
  153. spin_lock(&dentry->d_lock);
  154. hlist_del_init(&cursor->d_sib);
  155. if (to)
  156. hlist_add_behind(&cursor->d_sib, &to->d_sib);
  157. spin_unlock(&dentry->d_lock);
  158. dput(to);
  159. file->f_pos = offset;
  160. inode_unlock_shared(dentry->d_inode);
  161. }
  162. return offset;
  163. }
  164. EXPORT_SYMBOL(dcache_dir_lseek);
  165. /*
  166. * Directory is locked and all positive dentries in it are safe, since
  167. * for ramfs-type trees they can't go away without unlink() or rmdir(),
  168. * both impossible due to the lock on directory.
  169. */
  170. int dcache_readdir(struct file *file, struct dir_context *ctx)
  171. {
  172. struct dentry *dentry = file->f_path.dentry;
  173. struct dentry *cursor = file->private_data;
  174. struct dentry *next = NULL;
  175. struct hlist_node **p;
  176. if (!dir_emit_dots(file, ctx))
  177. return 0;
  178. if (ctx->pos == 2)
  179. p = &dentry->d_children.first;
  180. else
  181. p = &cursor->d_sib.next;
  182. while ((next = scan_positives(cursor, p, 1, next)) != NULL) {
  183. if (!dir_emit(ctx, next->d_name.name, next->d_name.len,
  184. d_inode(next)->i_ino,
  185. fs_umode_to_dtype(d_inode(next)->i_mode)))
  186. break;
  187. ctx->pos++;
  188. p = &next->d_sib.next;
  189. }
  190. spin_lock(&dentry->d_lock);
  191. hlist_del_init(&cursor->d_sib);
  192. if (next)
  193. hlist_add_before(&cursor->d_sib, &next->d_sib);
  194. spin_unlock(&dentry->d_lock);
  195. dput(next);
  196. return 0;
  197. }
  198. EXPORT_SYMBOL(dcache_readdir);
  199. ssize_t generic_read_dir(struct file *filp, char __user *buf, size_t siz, loff_t *ppos)
  200. {
  201. return -EISDIR;
  202. }
  203. EXPORT_SYMBOL(generic_read_dir);
  204. const struct file_operations simple_dir_operations = {
  205. .open = dcache_dir_open,
  206. .release = dcache_dir_close,
  207. .llseek = dcache_dir_lseek,
  208. .read = generic_read_dir,
  209. .iterate_shared = dcache_readdir,
  210. .fsync = noop_fsync,
  211. };
  212. EXPORT_SYMBOL(simple_dir_operations);
  213. const struct inode_operations simple_dir_inode_operations = {
  214. .lookup = simple_lookup,
  215. };
  216. EXPORT_SYMBOL(simple_dir_inode_operations);
  217. /* simple_offset_add() never assigns these to a dentry */
  218. enum {
  219. DIR_OFFSET_FIRST = 2, /* Find first real entry */
  220. DIR_OFFSET_EOD = S32_MAX,
  221. };
  222. /* simple_offset_add() allocation range */
  223. enum {
  224. DIR_OFFSET_MIN = DIR_OFFSET_FIRST + 1,
  225. DIR_OFFSET_MAX = DIR_OFFSET_EOD - 1,
  226. };
  227. static void offset_set(struct dentry *dentry, long offset)
  228. {
  229. dentry->d_fsdata = (void *)offset;
  230. }
  231. static long dentry2offset(struct dentry *dentry)
  232. {
  233. return (long)dentry->d_fsdata;
  234. }
  235. static struct lock_class_key simple_offset_lock_class;
  236. /**
  237. * simple_offset_init - initialize an offset_ctx
  238. * @octx: directory offset map to be initialized
  239. *
  240. */
  241. void simple_offset_init(struct offset_ctx *octx)
  242. {
  243. mt_init_flags(&octx->mt, MT_FLAGS_ALLOC_RANGE);
  244. lockdep_set_class(&octx->mt.ma_lock, &simple_offset_lock_class);
  245. octx->next_offset = DIR_OFFSET_MIN;
  246. }
  247. /**
  248. * simple_offset_add - Add an entry to a directory's offset map
  249. * @octx: directory offset ctx to be updated
  250. * @dentry: new dentry being added
  251. *
  252. * Returns zero on success. @octx and the dentry's offset are updated.
  253. * Otherwise, a negative errno value is returned.
  254. */
  255. int simple_offset_add(struct offset_ctx *octx, struct dentry *dentry)
  256. {
  257. unsigned long offset;
  258. int ret;
  259. if (dentry2offset(dentry) != 0)
  260. return -EBUSY;
  261. ret = mtree_alloc_cyclic(&octx->mt, &offset, dentry, DIR_OFFSET_MIN,
  262. DIR_OFFSET_MAX, &octx->next_offset,
  263. GFP_KERNEL);
  264. if (unlikely(ret < 0))
  265. return ret == -EBUSY ? -ENOSPC : ret;
  266. offset_set(dentry, offset);
  267. return 0;
  268. }
  269. static int simple_offset_replace(struct offset_ctx *octx, struct dentry *dentry,
  270. long offset)
  271. {
  272. int ret;
  273. ret = mtree_store(&octx->mt, offset, dentry, GFP_KERNEL);
  274. if (ret)
  275. return ret;
  276. offset_set(dentry, offset);
  277. return 0;
  278. }
  279. /**
  280. * simple_offset_remove - Remove an entry to a directory's offset map
  281. * @octx: directory offset ctx to be updated
  282. * @dentry: dentry being removed
  283. *
  284. */
  285. void simple_offset_remove(struct offset_ctx *octx, struct dentry *dentry)
  286. {
  287. long offset;
  288. offset = dentry2offset(dentry);
  289. if (offset == 0)
  290. return;
  291. mtree_erase(&octx->mt, offset);
  292. offset_set(dentry, 0);
  293. }
  294. /**
  295. * simple_offset_rename - handle directory offsets for rename
  296. * @old_dir: parent directory of source entry
  297. * @old_dentry: dentry of source entry
  298. * @new_dir: parent_directory of destination entry
  299. * @new_dentry: dentry of destination
  300. *
  301. * Caller provides appropriate serialization.
  302. *
  303. * User space expects the directory offset value of the replaced
  304. * (new) directory entry to be unchanged after a rename.
  305. *
  306. * Caller must have grabbed a slot for new_dentry in the maple_tree
  307. * associated with new_dir, even if dentry is negative.
  308. */
  309. void simple_offset_rename(struct inode *old_dir, struct dentry *old_dentry,
  310. struct inode *new_dir, struct dentry *new_dentry)
  311. {
  312. struct offset_ctx *old_ctx = old_dir->i_op->get_offset_ctx(old_dir);
  313. struct offset_ctx *new_ctx = new_dir->i_op->get_offset_ctx(new_dir);
  314. long new_offset = dentry2offset(new_dentry);
  315. if (WARN_ON(!new_offset))
  316. return;
  317. simple_offset_remove(old_ctx, old_dentry);
  318. offset_set(new_dentry, 0);
  319. WARN_ON(simple_offset_replace(new_ctx, old_dentry, new_offset));
  320. }
  321. /**
  322. * simple_offset_rename_exchange - exchange rename with directory offsets
  323. * @old_dir: parent of dentry being moved
  324. * @old_dentry: dentry being moved
  325. * @new_dir: destination parent
  326. * @new_dentry: destination dentry
  327. *
  328. * This API preserves the directory offset values. Caller provides
  329. * appropriate serialization.
  330. *
  331. * Returns zero on success. Otherwise a negative errno is returned and the
  332. * rename is rolled back.
  333. */
  334. int simple_offset_rename_exchange(struct inode *old_dir,
  335. struct dentry *old_dentry,
  336. struct inode *new_dir,
  337. struct dentry *new_dentry)
  338. {
  339. struct offset_ctx *old_ctx = old_dir->i_op->get_offset_ctx(old_dir);
  340. struct offset_ctx *new_ctx = new_dir->i_op->get_offset_ctx(new_dir);
  341. long old_index = dentry2offset(old_dentry);
  342. long new_index = dentry2offset(new_dentry);
  343. int ret;
  344. if (WARN_ON(!old_index || !new_index))
  345. return -EINVAL;
  346. ret = mtree_store(&new_ctx->mt, new_index, old_dentry, GFP_KERNEL);
  347. if (WARN_ON(ret))
  348. return ret;
  349. ret = mtree_store(&old_ctx->mt, old_index, new_dentry, GFP_KERNEL);
  350. if (WARN_ON(ret)) {
  351. mtree_store(&new_ctx->mt, new_index, new_dentry, GFP_KERNEL);
  352. return ret;
  353. }
  354. offset_set(old_dentry, new_index);
  355. offset_set(new_dentry, old_index);
  356. simple_rename_exchange(old_dir, old_dentry, new_dir, new_dentry);
  357. return 0;
  358. }
  359. /**
  360. * simple_offset_destroy - Release offset map
  361. * @octx: directory offset ctx that is about to be destroyed
  362. *
  363. * During fs teardown (eg. umount), a directory's offset map might still
  364. * contain entries. xa_destroy() cleans out anything that remains.
  365. */
  366. void simple_offset_destroy(struct offset_ctx *octx)
  367. {
  368. mtree_destroy(&octx->mt);
  369. }
  370. /**
  371. * offset_dir_llseek - Advance the read position of a directory descriptor
  372. * @file: an open directory whose position is to be updated
  373. * @offset: a byte offset
  374. * @whence: enumerator describing the starting position for this update
  375. *
  376. * SEEK_END, SEEK_DATA, and SEEK_HOLE are not supported for directories.
  377. *
  378. * Returns the updated read position if successful; otherwise a
  379. * negative errno is returned and the read position remains unchanged.
  380. */
  381. static loff_t offset_dir_llseek(struct file *file, loff_t offset, int whence)
  382. {
  383. switch (whence) {
  384. case SEEK_CUR:
  385. offset += file->f_pos;
  386. fallthrough;
  387. case SEEK_SET:
  388. if (offset >= 0)
  389. break;
  390. fallthrough;
  391. default:
  392. return -EINVAL;
  393. }
  394. return vfs_setpos(file, offset, LONG_MAX);
  395. }
  396. static struct dentry *find_positive_dentry(struct dentry *parent,
  397. struct dentry *dentry,
  398. bool next)
  399. {
  400. struct dentry *found = NULL;
  401. spin_lock(&parent->d_lock);
  402. if (next)
  403. dentry = d_next_sibling(dentry);
  404. else if (!dentry)
  405. dentry = d_first_child(parent);
  406. hlist_for_each_entry_from(dentry, d_sib) {
  407. if (!simple_positive(dentry))
  408. continue;
  409. spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
  410. if (simple_positive(dentry))
  411. found = dget_dlock(dentry);
  412. spin_unlock(&dentry->d_lock);
  413. if (likely(found))
  414. break;
  415. }
  416. spin_unlock(&parent->d_lock);
  417. return found;
  418. }
  419. static noinline_for_stack struct dentry *
  420. offset_dir_lookup(struct dentry *parent, loff_t offset)
  421. {
  422. struct inode *inode = d_inode(parent);
  423. struct offset_ctx *octx = inode->i_op->get_offset_ctx(inode);
  424. struct dentry *child, *found = NULL;
  425. MA_STATE(mas, &octx->mt, offset, offset);
  426. if (offset == DIR_OFFSET_FIRST)
  427. found = find_positive_dentry(parent, NULL, false);
  428. else {
  429. rcu_read_lock();
  430. child = mas_find_rev(&mas, DIR_OFFSET_MIN);
  431. found = find_positive_dentry(parent, child, false);
  432. rcu_read_unlock();
  433. }
  434. return found;
  435. }
  436. static bool offset_dir_emit(struct dir_context *ctx, struct dentry *dentry)
  437. {
  438. struct inode *inode = d_inode(dentry);
  439. return dir_emit(ctx, dentry->d_name.name, dentry->d_name.len,
  440. inode->i_ino, fs_umode_to_dtype(inode->i_mode));
  441. }
  442. static void offset_iterate_dir(struct file *file, struct dir_context *ctx)
  443. {
  444. struct dentry *dir = file->f_path.dentry;
  445. struct dentry *dentry;
  446. dentry = offset_dir_lookup(dir, ctx->pos);
  447. if (!dentry)
  448. goto out_eod;
  449. while (true) {
  450. struct dentry *next;
  451. ctx->pos = dentry2offset(dentry);
  452. if (!offset_dir_emit(ctx, dentry))
  453. break;
  454. next = find_positive_dentry(dir, dentry, true);
  455. dput(dentry);
  456. if (!next)
  457. goto out_eod;
  458. dentry = next;
  459. }
  460. dput(dentry);
  461. return;
  462. out_eod:
  463. ctx->pos = DIR_OFFSET_EOD;
  464. }
  465. /**
  466. * offset_readdir - Emit entries starting at offset @ctx->pos
  467. * @file: an open directory to iterate over
  468. * @ctx: directory iteration context
  469. *
  470. * Caller must hold @file's i_rwsem to prevent insertion or removal of
  471. * entries during this call.
  472. *
  473. * On entry, @ctx->pos contains an offset that represents the first entry
  474. * to be read from the directory.
  475. *
  476. * The operation continues until there are no more entries to read, or
  477. * until the ctx->actor indicates there is no more space in the caller's
  478. * output buffer.
  479. *
  480. * On return, @ctx->pos contains an offset that will read the next entry
  481. * in this directory when offset_readdir() is called again with @ctx.
  482. * Caller places this value in the d_off field of the last entry in the
  483. * user's buffer.
  484. *
  485. * Return values:
  486. * %0 - Complete
  487. */
  488. static int offset_readdir(struct file *file, struct dir_context *ctx)
  489. {
  490. struct dentry *dir = file->f_path.dentry;
  491. lockdep_assert_held(&d_inode(dir)->i_rwsem);
  492. if (!dir_emit_dots(file, ctx))
  493. return 0;
  494. if (ctx->pos != DIR_OFFSET_EOD)
  495. offset_iterate_dir(file, ctx);
  496. return 0;
  497. }
  498. const struct file_operations simple_offset_dir_operations = {
  499. .llseek = offset_dir_llseek,
  500. .iterate_shared = offset_readdir,
  501. .read = generic_read_dir,
  502. .fsync = noop_fsync,
  503. .setlease = generic_setlease,
  504. };
  505. struct dentry *find_next_child(struct dentry *parent, struct dentry *prev)
  506. {
  507. struct dentry *child = NULL, *d;
  508. spin_lock(&parent->d_lock);
  509. d = prev ? d_next_sibling(prev) : d_first_child(parent);
  510. hlist_for_each_entry_from(d, d_sib) {
  511. if (simple_positive(d)) {
  512. spin_lock_nested(&d->d_lock, DENTRY_D_LOCK_NESTED);
  513. if (simple_positive(d))
  514. child = dget_dlock(d);
  515. spin_unlock(&d->d_lock);
  516. if (likely(child))
  517. break;
  518. }
  519. }
  520. spin_unlock(&parent->d_lock);
  521. dput(prev);
  522. return child;
  523. }
  524. EXPORT_SYMBOL(find_next_child);
  525. static void __simple_recursive_removal(struct dentry *dentry,
  526. void (*callback)(struct dentry *),
  527. bool locked)
  528. {
  529. struct dentry *this = dget(dentry);
  530. while (true) {
  531. struct dentry *victim = NULL, *child;
  532. struct inode *inode = this->d_inode;
  533. inode_lock_nested(inode, I_MUTEX_CHILD);
  534. if (d_is_dir(this))
  535. inode->i_flags |= S_DEAD;
  536. while ((child = find_next_child(this, victim)) == NULL) {
  537. // kill and ascend
  538. // update metadata while it's still locked
  539. inode_set_ctime_current(inode);
  540. clear_nlink(inode);
  541. inode_unlock(inode);
  542. victim = this;
  543. this = this->d_parent;
  544. inode = this->d_inode;
  545. if (!locked || victim != dentry)
  546. inode_lock_nested(inode, I_MUTEX_CHILD);
  547. if (simple_positive(victim)) {
  548. d_invalidate(victim); // avoid lost mounts
  549. if (callback)
  550. callback(victim);
  551. fsnotify_delete(inode, d_inode(victim), victim);
  552. d_make_discardable(victim);
  553. }
  554. if (victim == dentry) {
  555. inode_set_mtime_to_ts(inode,
  556. inode_set_ctime_current(inode));
  557. if (d_is_dir(dentry))
  558. drop_nlink(inode);
  559. if (!locked)
  560. inode_unlock(inode);
  561. dput(dentry);
  562. return;
  563. }
  564. }
  565. inode_unlock(inode);
  566. this = child;
  567. }
  568. }
  569. void simple_recursive_removal(struct dentry *dentry,
  570. void (*callback)(struct dentry *))
  571. {
  572. return __simple_recursive_removal(dentry, callback, false);
  573. }
  574. EXPORT_SYMBOL(simple_recursive_removal);
  575. void simple_remove_by_name(struct dentry *parent, const char *name,
  576. void (*callback)(struct dentry *))
  577. {
  578. struct dentry *dentry;
  579. dentry = lookup_noperm_positive_unlocked(&QSTR(name), parent);
  580. if (!IS_ERR(dentry)) {
  581. simple_recursive_removal(dentry, callback);
  582. dput(dentry); // paired with lookup_noperm_positive_unlocked()
  583. }
  584. }
  585. EXPORT_SYMBOL(simple_remove_by_name);
  586. /* caller holds parent directory with I_MUTEX_PARENT */
  587. void locked_recursive_removal(struct dentry *dentry,
  588. void (*callback)(struct dentry *))
  589. {
  590. return __simple_recursive_removal(dentry, callback, true);
  591. }
  592. EXPORT_SYMBOL(locked_recursive_removal);
  593. static const struct super_operations simple_super_operations = {
  594. .statfs = simple_statfs,
  595. };
  596. static int pseudo_fs_fill_super(struct super_block *s, struct fs_context *fc)
  597. {
  598. struct pseudo_fs_context *ctx = fc->fs_private;
  599. struct inode *root;
  600. s->s_maxbytes = MAX_LFS_FILESIZE;
  601. s->s_blocksize = PAGE_SIZE;
  602. s->s_blocksize_bits = PAGE_SHIFT;
  603. s->s_magic = ctx->magic;
  604. s->s_op = ctx->ops ?: &simple_super_operations;
  605. s->s_export_op = ctx->eops;
  606. s->s_xattr = ctx->xattr;
  607. s->s_time_gran = 1;
  608. s->s_d_flags |= ctx->s_d_flags;
  609. root = new_inode(s);
  610. if (!root)
  611. return -ENOMEM;
  612. /*
  613. * since this is the first inode, make it number 1. New inodes created
  614. * after this must take care not to collide with it (by passing
  615. * max_reserved of 1 to iunique).
  616. */
  617. root->i_ino = 1;
  618. root->i_mode = S_IFDIR | S_IRUSR | S_IWUSR;
  619. simple_inode_init_ts(root);
  620. s->s_root = d_make_root(root);
  621. if (!s->s_root)
  622. return -ENOMEM;
  623. set_default_d_op(s, ctx->dops);
  624. return 0;
  625. }
  626. static int pseudo_fs_get_tree(struct fs_context *fc)
  627. {
  628. return get_tree_nodev(fc, pseudo_fs_fill_super);
  629. }
  630. static void pseudo_fs_free(struct fs_context *fc)
  631. {
  632. kfree(fc->fs_private);
  633. }
  634. static const struct fs_context_operations pseudo_fs_context_ops = {
  635. .free = pseudo_fs_free,
  636. .get_tree = pseudo_fs_get_tree,
  637. };
  638. /*
  639. * Common helper for pseudo-filesystems (sockfs, pipefs, bdev - stuff that
  640. * will never be mountable)
  641. */
  642. struct pseudo_fs_context *init_pseudo(struct fs_context *fc,
  643. unsigned long magic)
  644. {
  645. struct pseudo_fs_context *ctx;
  646. ctx = kzalloc_obj(struct pseudo_fs_context);
  647. if (likely(ctx)) {
  648. ctx->magic = magic;
  649. fc->fs_private = ctx;
  650. fc->ops = &pseudo_fs_context_ops;
  651. fc->sb_flags |= SB_NOUSER;
  652. fc->global = true;
  653. }
  654. return ctx;
  655. }
  656. EXPORT_SYMBOL(init_pseudo);
  657. int simple_open(struct inode *inode, struct file *file)
  658. {
  659. if (inode->i_private)
  660. file->private_data = inode->i_private;
  661. return 0;
  662. }
  663. EXPORT_SYMBOL(simple_open);
  664. int simple_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry)
  665. {
  666. struct inode *inode = d_inode(old_dentry);
  667. inode_set_mtime_to_ts(dir,
  668. inode_set_ctime_to_ts(dir, inode_set_ctime_current(inode)));
  669. inc_nlink(inode);
  670. ihold(inode);
  671. d_make_persistent(dentry, inode);
  672. return 0;
  673. }
  674. EXPORT_SYMBOL(simple_link);
  675. int simple_empty(struct dentry *dentry)
  676. {
  677. struct dentry *child;
  678. int ret = 0;
  679. spin_lock(&dentry->d_lock);
  680. hlist_for_each_entry(child, &dentry->d_children, d_sib) {
  681. spin_lock_nested(&child->d_lock, DENTRY_D_LOCK_NESTED);
  682. if (simple_positive(child)) {
  683. spin_unlock(&child->d_lock);
  684. goto out;
  685. }
  686. spin_unlock(&child->d_lock);
  687. }
  688. ret = 1;
  689. out:
  690. spin_unlock(&dentry->d_lock);
  691. return ret;
  692. }
  693. EXPORT_SYMBOL(simple_empty);
  694. void __simple_unlink(struct inode *dir, struct dentry *dentry)
  695. {
  696. struct inode *inode = d_inode(dentry);
  697. inode_set_mtime_to_ts(dir,
  698. inode_set_ctime_to_ts(dir, inode_set_ctime_current(inode)));
  699. drop_nlink(inode);
  700. }
  701. EXPORT_SYMBOL(__simple_unlink);
  702. void __simple_rmdir(struct inode *dir, struct dentry *dentry)
  703. {
  704. drop_nlink(d_inode(dentry));
  705. __simple_unlink(dir, dentry);
  706. drop_nlink(dir);
  707. }
  708. EXPORT_SYMBOL(__simple_rmdir);
  709. int simple_unlink(struct inode *dir, struct dentry *dentry)
  710. {
  711. __simple_unlink(dir, dentry);
  712. d_make_discardable(dentry);
  713. return 0;
  714. }
  715. EXPORT_SYMBOL(simple_unlink);
  716. int simple_rmdir(struct inode *dir, struct dentry *dentry)
  717. {
  718. if (!simple_empty(dentry))
  719. return -ENOTEMPTY;
  720. __simple_rmdir(dir, dentry);
  721. d_make_discardable(dentry);
  722. return 0;
  723. }
  724. EXPORT_SYMBOL(simple_rmdir);
  725. /**
  726. * simple_rename_timestamp - update the various inode timestamps for rename
  727. * @old_dir: old parent directory
  728. * @old_dentry: dentry that is being renamed
  729. * @new_dir: new parent directory
  730. * @new_dentry: target for rename
  731. *
  732. * POSIX mandates that the old and new parent directories have their ctime and
  733. * mtime updated, and that inodes of @old_dentry and @new_dentry (if any), have
  734. * their ctime updated.
  735. */
  736. void simple_rename_timestamp(struct inode *old_dir, struct dentry *old_dentry,
  737. struct inode *new_dir, struct dentry *new_dentry)
  738. {
  739. struct inode *newino = d_inode(new_dentry);
  740. inode_set_mtime_to_ts(old_dir, inode_set_ctime_current(old_dir));
  741. if (new_dir != old_dir)
  742. inode_set_mtime_to_ts(new_dir,
  743. inode_set_ctime_current(new_dir));
  744. inode_set_ctime_current(d_inode(old_dentry));
  745. if (newino)
  746. inode_set_ctime_current(newino);
  747. }
  748. EXPORT_SYMBOL_GPL(simple_rename_timestamp);
  749. int simple_rename_exchange(struct inode *old_dir, struct dentry *old_dentry,
  750. struct inode *new_dir, struct dentry *new_dentry)
  751. {
  752. bool old_is_dir = d_is_dir(old_dentry);
  753. bool new_is_dir = d_is_dir(new_dentry);
  754. if (old_dir != new_dir && old_is_dir != new_is_dir) {
  755. if (old_is_dir) {
  756. drop_nlink(old_dir);
  757. inc_nlink(new_dir);
  758. } else {
  759. drop_nlink(new_dir);
  760. inc_nlink(old_dir);
  761. }
  762. }
  763. simple_rename_timestamp(old_dir, old_dentry, new_dir, new_dentry);
  764. return 0;
  765. }
  766. EXPORT_SYMBOL_GPL(simple_rename_exchange);
  767. int simple_rename(struct mnt_idmap *idmap, struct inode *old_dir,
  768. struct dentry *old_dentry, struct inode *new_dir,
  769. struct dentry *new_dentry, unsigned int flags)
  770. {
  771. int they_are_dirs = d_is_dir(old_dentry);
  772. if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE))
  773. return -EINVAL;
  774. if (flags & RENAME_EXCHANGE)
  775. return simple_rename_exchange(old_dir, old_dentry, new_dir, new_dentry);
  776. if (!simple_empty(new_dentry))
  777. return -ENOTEMPTY;
  778. if (d_really_is_positive(new_dentry)) {
  779. simple_unlink(new_dir, new_dentry);
  780. if (they_are_dirs) {
  781. drop_nlink(d_inode(new_dentry));
  782. drop_nlink(old_dir);
  783. }
  784. } else if (they_are_dirs) {
  785. drop_nlink(old_dir);
  786. inc_nlink(new_dir);
  787. }
  788. simple_rename_timestamp(old_dir, old_dentry, new_dir, new_dentry);
  789. return 0;
  790. }
  791. EXPORT_SYMBOL(simple_rename);
  792. /**
  793. * simple_setattr - setattr for simple filesystem
  794. * @idmap: idmap of the target mount
  795. * @dentry: dentry
  796. * @iattr: iattr structure
  797. *
  798. * Returns 0 on success, -error on failure.
  799. *
  800. * simple_setattr is a simple ->setattr implementation without a proper
  801. * implementation of size changes.
  802. *
  803. * It can either be used for in-memory filesystems or special files
  804. * on simple regular filesystems. Anything that needs to change on-disk
  805. * or wire state on size changes needs its own setattr method.
  806. */
  807. int simple_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
  808. struct iattr *iattr)
  809. {
  810. struct inode *inode = d_inode(dentry);
  811. int error;
  812. error = setattr_prepare(idmap, dentry, iattr);
  813. if (error)
  814. return error;
  815. if (iattr->ia_valid & ATTR_SIZE)
  816. truncate_setsize(inode, iattr->ia_size);
  817. setattr_copy(idmap, inode, iattr);
  818. mark_inode_dirty(inode);
  819. return 0;
  820. }
  821. EXPORT_SYMBOL(simple_setattr);
  822. static int simple_read_folio(struct file *file, struct folio *folio)
  823. {
  824. folio_zero_range(folio, 0, folio_size(folio));
  825. flush_dcache_folio(folio);
  826. folio_mark_uptodate(folio);
  827. folio_unlock(folio);
  828. return 0;
  829. }
  830. int simple_write_begin(const struct kiocb *iocb, struct address_space *mapping,
  831. loff_t pos, unsigned len,
  832. struct folio **foliop, void **fsdata)
  833. {
  834. struct folio *folio;
  835. folio = __filemap_get_folio(mapping, pos / PAGE_SIZE, FGP_WRITEBEGIN,
  836. mapping_gfp_mask(mapping));
  837. if (IS_ERR(folio))
  838. return PTR_ERR(folio);
  839. *foliop = folio;
  840. if (!folio_test_uptodate(folio) && (len != folio_size(folio))) {
  841. size_t from = offset_in_folio(folio, pos);
  842. folio_zero_segments(folio, 0, from,
  843. from + len, folio_size(folio));
  844. }
  845. return 0;
  846. }
  847. EXPORT_SYMBOL(simple_write_begin);
  848. /**
  849. * simple_write_end - .write_end helper for non-block-device FSes
  850. * @iocb: kernel I/O control block
  851. * @mapping: "
  852. * @pos: "
  853. * @len: "
  854. * @copied: "
  855. * @folio: "
  856. * @fsdata: "
  857. *
  858. * simple_write_end does the minimum needed for updating a folio after
  859. * writing is done. It has the same API signature as the .write_end of
  860. * address_space_operations vector. So it can just be set onto .write_end for
  861. * FSes that don't need any other processing. i_rwsem is assumed to be held
  862. * exclusively.
  863. * Block based filesystems should use generic_write_end().
  864. * NOTE: Even though i_size might get updated by this function, mark_inode_dirty
  865. * is not called, so a filesystem that actually does store data in .write_inode
  866. * should extend on what's done here with a call to mark_inode_dirty() in the
  867. * case that i_size has changed.
  868. *
  869. * Use *ONLY* with simple_read_folio()
  870. */
  871. static int simple_write_end(const struct kiocb *iocb,
  872. struct address_space *mapping,
  873. loff_t pos, unsigned len, unsigned copied,
  874. struct folio *folio, void *fsdata)
  875. {
  876. struct inode *inode = folio->mapping->host;
  877. loff_t last_pos = pos + copied;
  878. /* zero the stale part of the folio if we did a short copy */
  879. if (!folio_test_uptodate(folio)) {
  880. if (copied < len) {
  881. size_t from = offset_in_folio(folio, pos);
  882. folio_zero_range(folio, from + copied, len - copied);
  883. }
  884. folio_mark_uptodate(folio);
  885. }
  886. /*
  887. * No need to use i_size_read() here, the i_size
  888. * cannot change under us because we hold the i_rwsem.
  889. */
  890. if (last_pos > inode->i_size)
  891. i_size_write(inode, last_pos);
  892. folio_mark_dirty(folio);
  893. folio_unlock(folio);
  894. folio_put(folio);
  895. return copied;
  896. }
  897. /*
  898. * Provides ramfs-style behavior: data in the pagecache, but no writeback.
  899. */
  900. const struct address_space_operations ram_aops = {
  901. .read_folio = simple_read_folio,
  902. .write_begin = simple_write_begin,
  903. .write_end = simple_write_end,
  904. .dirty_folio = noop_dirty_folio,
  905. };
  906. EXPORT_SYMBOL(ram_aops);
  907. /*
  908. * the inodes created here are not hashed. If you use iunique to generate
  909. * unique inode values later for this filesystem, then you must take care
  910. * to pass it an appropriate max_reserved value to avoid collisions.
  911. */
  912. int simple_fill_super(struct super_block *s, unsigned long magic,
  913. const struct tree_descr *files)
  914. {
  915. struct inode *inode;
  916. struct dentry *dentry;
  917. int i;
  918. s->s_blocksize = PAGE_SIZE;
  919. s->s_blocksize_bits = PAGE_SHIFT;
  920. s->s_magic = magic;
  921. s->s_op = &simple_super_operations;
  922. s->s_time_gran = 1;
  923. inode = new_inode(s);
  924. if (!inode)
  925. return -ENOMEM;
  926. /*
  927. * because the root inode is 1, the files array must not contain an
  928. * entry at index 1
  929. */
  930. inode->i_ino = 1;
  931. inode->i_mode = S_IFDIR | 0755;
  932. simple_inode_init_ts(inode);
  933. inode->i_op = &simple_dir_inode_operations;
  934. inode->i_fop = &simple_dir_operations;
  935. set_nlink(inode, 2);
  936. s->s_root = d_make_root(inode);
  937. if (!s->s_root)
  938. return -ENOMEM;
  939. for (i = 0; !files->name || files->name[0]; i++, files++) {
  940. if (!files->name)
  941. continue;
  942. /* warn if it tries to conflict with the root inode */
  943. if (unlikely(i == 1))
  944. printk(KERN_WARNING "%s: %s passed in a files array"
  945. "with an index of 1!\n", __func__,
  946. s->s_type->name);
  947. dentry = d_alloc_name(s->s_root, files->name);
  948. if (!dentry)
  949. return -ENOMEM;
  950. inode = new_inode(s);
  951. if (!inode) {
  952. dput(dentry);
  953. return -ENOMEM;
  954. }
  955. inode->i_mode = S_IFREG | files->mode;
  956. simple_inode_init_ts(inode);
  957. inode->i_fop = files->ops;
  958. inode->i_ino = i;
  959. d_make_persistent(dentry, inode);
  960. dput(dentry);
  961. }
  962. return 0;
  963. }
  964. EXPORT_SYMBOL(simple_fill_super);
  965. static DEFINE_SPINLOCK(pin_fs_lock);
  966. int simple_pin_fs(struct file_system_type *type, struct vfsmount **mount, int *count)
  967. {
  968. struct vfsmount *mnt = NULL;
  969. spin_lock(&pin_fs_lock);
  970. if (unlikely(!*mount)) {
  971. spin_unlock(&pin_fs_lock);
  972. mnt = vfs_kern_mount(type, SB_KERNMOUNT, type->name, NULL);
  973. if (IS_ERR(mnt))
  974. return PTR_ERR(mnt);
  975. spin_lock(&pin_fs_lock);
  976. if (!*mount)
  977. *mount = mnt;
  978. }
  979. mntget(*mount);
  980. ++*count;
  981. spin_unlock(&pin_fs_lock);
  982. mntput(mnt);
  983. return 0;
  984. }
  985. EXPORT_SYMBOL(simple_pin_fs);
  986. void simple_release_fs(struct vfsmount **mount, int *count)
  987. {
  988. struct vfsmount *mnt;
  989. spin_lock(&pin_fs_lock);
  990. mnt = *mount;
  991. if (!--*count)
  992. *mount = NULL;
  993. spin_unlock(&pin_fs_lock);
  994. mntput(mnt);
  995. }
  996. EXPORT_SYMBOL(simple_release_fs);
  997. /**
  998. * simple_read_from_buffer - copy data from the buffer to user space
  999. * @to: the user space buffer to read to
  1000. * @count: the maximum number of bytes to read
  1001. * @ppos: the current position in the buffer
  1002. * @from: the buffer to read from
  1003. * @available: the size of the buffer
  1004. *
  1005. * The simple_read_from_buffer() function reads up to @count bytes from the
  1006. * buffer @from at offset @ppos into the user space address starting at @to.
  1007. *
  1008. * On success, the number of bytes read is returned and the offset @ppos is
  1009. * advanced by this number, or negative value is returned on error.
  1010. **/
  1011. ssize_t simple_read_from_buffer(void __user *to, size_t count, loff_t *ppos,
  1012. const void *from, size_t available)
  1013. {
  1014. loff_t pos = *ppos;
  1015. size_t ret;
  1016. if (pos < 0)
  1017. return -EINVAL;
  1018. if (pos >= available || !count)
  1019. return 0;
  1020. if (count > available - pos)
  1021. count = available - pos;
  1022. ret = copy_to_user(to, from + pos, count);
  1023. if (ret == count)
  1024. return -EFAULT;
  1025. count -= ret;
  1026. *ppos = pos + count;
  1027. return count;
  1028. }
  1029. EXPORT_SYMBOL(simple_read_from_buffer);
  1030. /**
  1031. * simple_write_to_buffer - copy data from user space to the buffer
  1032. * @to: the buffer to write to
  1033. * @available: the size of the buffer
  1034. * @ppos: the current position in the buffer
  1035. * @from: the user space buffer to read from
  1036. * @count: the maximum number of bytes to read
  1037. *
  1038. * The simple_write_to_buffer() function reads up to @count bytes from the user
  1039. * space address starting at @from into the buffer @to at offset @ppos.
  1040. *
  1041. * On success, the number of bytes written is returned and the offset @ppos is
  1042. * advanced by this number, or negative value is returned on error.
  1043. **/
  1044. ssize_t simple_write_to_buffer(void *to, size_t available, loff_t *ppos,
  1045. const void __user *from, size_t count)
  1046. {
  1047. loff_t pos = *ppos;
  1048. size_t res;
  1049. if (pos < 0)
  1050. return -EINVAL;
  1051. if (pos >= available || !count)
  1052. return 0;
  1053. if (count > available - pos)
  1054. count = available - pos;
  1055. res = copy_from_user(to + pos, from, count);
  1056. if (res == count)
  1057. return -EFAULT;
  1058. count -= res;
  1059. *ppos = pos + count;
  1060. return count;
  1061. }
  1062. EXPORT_SYMBOL(simple_write_to_buffer);
  1063. /**
  1064. * memory_read_from_buffer - copy data from the buffer
  1065. * @to: the kernel space buffer to read to
  1066. * @count: the maximum number of bytes to read
  1067. * @ppos: the current position in the buffer
  1068. * @from: the buffer to read from
  1069. * @available: the size of the buffer
  1070. *
  1071. * The memory_read_from_buffer() function reads up to @count bytes from the
  1072. * buffer @from at offset @ppos into the kernel space address starting at @to.
  1073. *
  1074. * On success, the number of bytes read is returned and the offset @ppos is
  1075. * advanced by this number, or negative value is returned on error.
  1076. **/
  1077. ssize_t memory_read_from_buffer(void *to, size_t count, loff_t *ppos,
  1078. const void *from, size_t available)
  1079. {
  1080. loff_t pos = *ppos;
  1081. if (pos < 0)
  1082. return -EINVAL;
  1083. if (pos >= available)
  1084. return 0;
  1085. if (count > available - pos)
  1086. count = available - pos;
  1087. memcpy(to, from + pos, count);
  1088. *ppos = pos + count;
  1089. return count;
  1090. }
  1091. EXPORT_SYMBOL(memory_read_from_buffer);
  1092. /*
  1093. * Transaction based IO.
  1094. * The file expects a single write which triggers the transaction, and then
  1095. * possibly a read which collects the result - which is stored in a
  1096. * file-local buffer.
  1097. */
  1098. void simple_transaction_set(struct file *file, size_t n)
  1099. {
  1100. struct simple_transaction_argresp *ar = file->private_data;
  1101. BUG_ON(n > SIMPLE_TRANSACTION_LIMIT);
  1102. /*
  1103. * The barrier ensures that ar->size will really remain zero until
  1104. * ar->data is ready for reading.
  1105. */
  1106. smp_mb();
  1107. ar->size = n;
  1108. }
  1109. EXPORT_SYMBOL(simple_transaction_set);
  1110. char *simple_transaction_get(struct file *file, const char __user *buf, size_t size)
  1111. {
  1112. struct simple_transaction_argresp *ar;
  1113. static DEFINE_SPINLOCK(simple_transaction_lock);
  1114. if (size > SIMPLE_TRANSACTION_LIMIT - 1)
  1115. return ERR_PTR(-EFBIG);
  1116. ar = (struct simple_transaction_argresp *)get_zeroed_page(GFP_KERNEL);
  1117. if (!ar)
  1118. return ERR_PTR(-ENOMEM);
  1119. spin_lock(&simple_transaction_lock);
  1120. /* only one write allowed per open */
  1121. if (file->private_data) {
  1122. spin_unlock(&simple_transaction_lock);
  1123. free_page((unsigned long)ar);
  1124. return ERR_PTR(-EBUSY);
  1125. }
  1126. file->private_data = ar;
  1127. spin_unlock(&simple_transaction_lock);
  1128. if (copy_from_user(ar->data, buf, size))
  1129. return ERR_PTR(-EFAULT);
  1130. return ar->data;
  1131. }
  1132. EXPORT_SYMBOL(simple_transaction_get);
  1133. ssize_t simple_transaction_read(struct file *file, char __user *buf, size_t size, loff_t *pos)
  1134. {
  1135. struct simple_transaction_argresp *ar = file->private_data;
  1136. if (!ar)
  1137. return 0;
  1138. return simple_read_from_buffer(buf, size, pos, ar->data, ar->size);
  1139. }
  1140. EXPORT_SYMBOL(simple_transaction_read);
  1141. int simple_transaction_release(struct inode *inode, struct file *file)
  1142. {
  1143. free_page((unsigned long)file->private_data);
  1144. return 0;
  1145. }
  1146. EXPORT_SYMBOL(simple_transaction_release);
  1147. /* Simple attribute files */
  1148. struct simple_attr {
  1149. int (*get)(void *, u64 *);
  1150. int (*set)(void *, u64);
  1151. char get_buf[24]; /* enough to store a u64 and "\n\0" */
  1152. char set_buf[24];
  1153. void *data;
  1154. const char *fmt; /* format for read operation */
  1155. struct mutex mutex; /* protects access to these buffers */
  1156. };
  1157. /* simple_attr_open is called by an actual attribute open file operation
  1158. * to set the attribute specific access operations. */
  1159. int simple_attr_open(struct inode *inode, struct file *file,
  1160. int (*get)(void *, u64 *), int (*set)(void *, u64),
  1161. const char *fmt)
  1162. {
  1163. struct simple_attr *attr;
  1164. attr = kzalloc_obj(*attr);
  1165. if (!attr)
  1166. return -ENOMEM;
  1167. attr->get = get;
  1168. attr->set = set;
  1169. attr->data = inode->i_private;
  1170. attr->fmt = fmt;
  1171. mutex_init(&attr->mutex);
  1172. file->private_data = attr;
  1173. return nonseekable_open(inode, file);
  1174. }
  1175. EXPORT_SYMBOL_GPL(simple_attr_open);
  1176. int simple_attr_release(struct inode *inode, struct file *file)
  1177. {
  1178. kfree(file->private_data);
  1179. return 0;
  1180. }
  1181. EXPORT_SYMBOL_GPL(simple_attr_release); /* GPL-only? This? Really? */
  1182. /* read from the buffer that is filled with the get function */
  1183. ssize_t simple_attr_read(struct file *file, char __user *buf,
  1184. size_t len, loff_t *ppos)
  1185. {
  1186. struct simple_attr *attr;
  1187. size_t size;
  1188. ssize_t ret;
  1189. attr = file->private_data;
  1190. if (!attr->get)
  1191. return -EACCES;
  1192. ret = mutex_lock_interruptible(&attr->mutex);
  1193. if (ret)
  1194. return ret;
  1195. if (*ppos && attr->get_buf[0]) {
  1196. /* continued read */
  1197. size = strlen(attr->get_buf);
  1198. } else {
  1199. /* first read */
  1200. u64 val;
  1201. ret = attr->get(attr->data, &val);
  1202. if (ret)
  1203. goto out;
  1204. size = scnprintf(attr->get_buf, sizeof(attr->get_buf),
  1205. attr->fmt, (unsigned long long)val);
  1206. }
  1207. ret = simple_read_from_buffer(buf, len, ppos, attr->get_buf, size);
  1208. out:
  1209. mutex_unlock(&attr->mutex);
  1210. return ret;
  1211. }
  1212. EXPORT_SYMBOL_GPL(simple_attr_read);
  1213. /* interpret the buffer as a number to call the set function with */
  1214. static ssize_t simple_attr_write_xsigned(struct file *file, const char __user *buf,
  1215. size_t len, loff_t *ppos, bool is_signed)
  1216. {
  1217. struct simple_attr *attr;
  1218. unsigned long long val;
  1219. size_t size;
  1220. ssize_t ret;
  1221. attr = file->private_data;
  1222. if (!attr->set)
  1223. return -EACCES;
  1224. ret = mutex_lock_interruptible(&attr->mutex);
  1225. if (ret)
  1226. return ret;
  1227. ret = -EFAULT;
  1228. size = min(sizeof(attr->set_buf) - 1, len);
  1229. if (copy_from_user(attr->set_buf, buf, size))
  1230. goto out;
  1231. attr->set_buf[size] = '\0';
  1232. if (is_signed)
  1233. ret = kstrtoll(attr->set_buf, 0, &val);
  1234. else
  1235. ret = kstrtoull(attr->set_buf, 0, &val);
  1236. if (ret)
  1237. goto out;
  1238. ret = attr->set(attr->data, val);
  1239. if (ret == 0)
  1240. ret = len; /* on success, claim we got the whole input */
  1241. out:
  1242. mutex_unlock(&attr->mutex);
  1243. return ret;
  1244. }
  1245. ssize_t simple_attr_write(struct file *file, const char __user *buf,
  1246. size_t len, loff_t *ppos)
  1247. {
  1248. return simple_attr_write_xsigned(file, buf, len, ppos, false);
  1249. }
  1250. EXPORT_SYMBOL_GPL(simple_attr_write);
  1251. ssize_t simple_attr_write_signed(struct file *file, const char __user *buf,
  1252. size_t len, loff_t *ppos)
  1253. {
  1254. return simple_attr_write_xsigned(file, buf, len, ppos, true);
  1255. }
  1256. EXPORT_SYMBOL_GPL(simple_attr_write_signed);
  1257. /**
  1258. * generic_encode_ino32_fh - generic export_operations->encode_fh function
  1259. * @inode: the object to encode
  1260. * @fh: where to store the file handle fragment
  1261. * @max_len: maximum length to store there (in 4 byte units)
  1262. * @parent: parent directory inode, if wanted
  1263. *
  1264. * This generic encode_fh function assumes that the 32 inode number
  1265. * is suitable for locating an inode, and that the generation number
  1266. * can be used to check that it is still valid. It places them in the
  1267. * filehandle fragment where export_decode_fh expects to find them.
  1268. */
  1269. int generic_encode_ino32_fh(struct inode *inode, __u32 *fh, int *max_len,
  1270. struct inode *parent)
  1271. {
  1272. struct fid *fid = (void *)fh;
  1273. int len = *max_len;
  1274. int type = FILEID_INO32_GEN;
  1275. if (parent && (len < 4)) {
  1276. *max_len = 4;
  1277. return FILEID_INVALID;
  1278. } else if (len < 2) {
  1279. *max_len = 2;
  1280. return FILEID_INVALID;
  1281. }
  1282. len = 2;
  1283. fid->i32.ino = inode->i_ino;
  1284. fid->i32.gen = inode->i_generation;
  1285. if (parent) {
  1286. fid->i32.parent_ino = parent->i_ino;
  1287. fid->i32.parent_gen = parent->i_generation;
  1288. len = 4;
  1289. type = FILEID_INO32_GEN_PARENT;
  1290. }
  1291. *max_len = len;
  1292. return type;
  1293. }
  1294. EXPORT_SYMBOL_GPL(generic_encode_ino32_fh);
  1295. /**
  1296. * generic_fh_to_dentry - generic helper for the fh_to_dentry export operation
  1297. * @sb: filesystem to do the file handle conversion on
  1298. * @fid: file handle to convert
  1299. * @fh_len: length of the file handle in bytes
  1300. * @fh_type: type of file handle
  1301. * @get_inode: filesystem callback to retrieve inode
  1302. *
  1303. * This function decodes @fid as long as it has one of the well-known
  1304. * Linux filehandle types and calls @get_inode on it to retrieve the
  1305. * inode for the object specified in the file handle.
  1306. */
  1307. struct dentry *generic_fh_to_dentry(struct super_block *sb, struct fid *fid,
  1308. int fh_len, int fh_type, struct inode *(*get_inode)
  1309. (struct super_block *sb, u64 ino, u32 gen))
  1310. {
  1311. struct inode *inode = NULL;
  1312. if (fh_len < 2)
  1313. return NULL;
  1314. switch (fh_type) {
  1315. case FILEID_INO32_GEN:
  1316. case FILEID_INO32_GEN_PARENT:
  1317. inode = get_inode(sb, fid->i32.ino, fid->i32.gen);
  1318. break;
  1319. }
  1320. return d_obtain_alias(inode);
  1321. }
  1322. EXPORT_SYMBOL_GPL(generic_fh_to_dentry);
  1323. /**
  1324. * generic_fh_to_parent - generic helper for the fh_to_parent export operation
  1325. * @sb: filesystem to do the file handle conversion on
  1326. * @fid: file handle to convert
  1327. * @fh_len: length of the file handle in bytes
  1328. * @fh_type: type of file handle
  1329. * @get_inode: filesystem callback to retrieve inode
  1330. *
  1331. * This function decodes @fid as long as it has one of the well-known
  1332. * Linux filehandle types and calls @get_inode on it to retrieve the
  1333. * inode for the _parent_ object specified in the file handle if it
  1334. * is specified in the file handle, or NULL otherwise.
  1335. */
  1336. struct dentry *generic_fh_to_parent(struct super_block *sb, struct fid *fid,
  1337. int fh_len, int fh_type, struct inode *(*get_inode)
  1338. (struct super_block *sb, u64 ino, u32 gen))
  1339. {
  1340. struct inode *inode = NULL;
  1341. if (fh_len <= 2)
  1342. return NULL;
  1343. switch (fh_type) {
  1344. case FILEID_INO32_GEN_PARENT:
  1345. inode = get_inode(sb, fid->i32.parent_ino,
  1346. (fh_len > 3 ? fid->i32.parent_gen : 0));
  1347. break;
  1348. }
  1349. return d_obtain_alias(inode);
  1350. }
  1351. EXPORT_SYMBOL_GPL(generic_fh_to_parent);
  1352. /**
  1353. * __generic_file_fsync - generic fsync implementation for simple filesystems
  1354. *
  1355. * @file: file to synchronize
  1356. * @start: start offset in bytes
  1357. * @end: end offset in bytes (inclusive)
  1358. * @datasync: only synchronize essential metadata if true
  1359. *
  1360. * This is a generic implementation of the fsync method for simple
  1361. * filesystems which track all non-inode metadata in the buffers list
  1362. * hanging off the address_space structure.
  1363. */
  1364. int __generic_file_fsync(struct file *file, loff_t start, loff_t end,
  1365. int datasync)
  1366. {
  1367. struct inode *inode = file->f_mapping->host;
  1368. int err;
  1369. int ret;
  1370. err = file_write_and_wait_range(file, start, end);
  1371. if (err)
  1372. return err;
  1373. inode_lock(inode);
  1374. ret = sync_mapping_buffers(inode->i_mapping);
  1375. if (!(inode_state_read_once(inode) & I_DIRTY_ALL))
  1376. goto out;
  1377. if (datasync && !(inode_state_read_once(inode) & I_DIRTY_DATASYNC))
  1378. goto out;
  1379. err = sync_inode_metadata(inode, 1);
  1380. if (ret == 0)
  1381. ret = err;
  1382. out:
  1383. inode_unlock(inode);
  1384. /* check and advance again to catch errors after syncing out buffers */
  1385. err = file_check_and_advance_wb_err(file);
  1386. if (ret == 0)
  1387. ret = err;
  1388. return ret;
  1389. }
  1390. EXPORT_SYMBOL(__generic_file_fsync);
  1391. /**
  1392. * generic_file_fsync - generic fsync implementation for simple filesystems
  1393. * with flush
  1394. * @file: file to synchronize
  1395. * @start: start offset in bytes
  1396. * @end: end offset in bytes (inclusive)
  1397. * @datasync: only synchronize essential metadata if true
  1398. *
  1399. */
  1400. int generic_file_fsync(struct file *file, loff_t start, loff_t end,
  1401. int datasync)
  1402. {
  1403. struct inode *inode = file->f_mapping->host;
  1404. int err;
  1405. err = __generic_file_fsync(file, start, end, datasync);
  1406. if (err)
  1407. return err;
  1408. return blkdev_issue_flush(inode->i_sb->s_bdev);
  1409. }
  1410. EXPORT_SYMBOL(generic_file_fsync);
  1411. /**
  1412. * generic_check_addressable - Check addressability of file system
  1413. * @blocksize_bits: log of file system block size
  1414. * @num_blocks: number of blocks in file system
  1415. *
  1416. * Determine whether a file system with @num_blocks blocks (and a
  1417. * block size of 2**@blocksize_bits) is addressable by the sector_t
  1418. * and page cache of the system. Return 0 if so and -EFBIG otherwise.
  1419. */
  1420. int generic_check_addressable(unsigned blocksize_bits, u64 num_blocks)
  1421. {
  1422. u64 last_fs_block = num_blocks - 1;
  1423. u64 last_fs_page, max_bytes;
  1424. if (check_shl_overflow(num_blocks, blocksize_bits, &max_bytes))
  1425. return -EFBIG;
  1426. last_fs_page = (max_bytes >> PAGE_SHIFT) - 1;
  1427. if (unlikely(num_blocks == 0))
  1428. return 0;
  1429. if (blocksize_bits < 9)
  1430. return -EINVAL;
  1431. if ((last_fs_block > (sector_t)(~0ULL) >> (blocksize_bits - 9)) ||
  1432. (last_fs_page > (pgoff_t)(~0ULL))) {
  1433. return -EFBIG;
  1434. }
  1435. return 0;
  1436. }
  1437. EXPORT_SYMBOL(generic_check_addressable);
  1438. /*
  1439. * No-op implementation of ->fsync for in-memory filesystems.
  1440. */
  1441. int noop_fsync(struct file *file, loff_t start, loff_t end, int datasync)
  1442. {
  1443. return 0;
  1444. }
  1445. EXPORT_SYMBOL(noop_fsync);
  1446. ssize_t noop_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
  1447. {
  1448. /*
  1449. * iomap based filesystems support direct I/O without need for
  1450. * this callback. However, it still needs to be set in
  1451. * inode->a_ops so that open/fcntl know that direct I/O is
  1452. * generally supported.
  1453. */
  1454. return -EINVAL;
  1455. }
  1456. EXPORT_SYMBOL_GPL(noop_direct_IO);
  1457. /* Because kfree isn't assignment-compatible with void(void*) ;-/ */
  1458. void kfree_link(void *p)
  1459. {
  1460. kfree(p);
  1461. }
  1462. EXPORT_SYMBOL(kfree_link);
  1463. struct inode *alloc_anon_inode(struct super_block *s)
  1464. {
  1465. static const struct address_space_operations anon_aops = {
  1466. .dirty_folio = noop_dirty_folio,
  1467. };
  1468. struct inode *inode = new_inode_pseudo(s);
  1469. if (!inode)
  1470. return ERR_PTR(-ENOMEM);
  1471. inode->i_ino = get_next_ino();
  1472. inode->i_mapping->a_ops = &anon_aops;
  1473. /*
  1474. * Mark the inode dirty from the very beginning,
  1475. * that way it will never be moved to the dirty
  1476. * list because mark_inode_dirty() will think
  1477. * that it already _is_ on the dirty list.
  1478. */
  1479. inode_state_assign_raw(inode, I_DIRTY);
  1480. /*
  1481. * Historically anonymous inodes don't have a type at all and
  1482. * userspace has come to rely on this.
  1483. */
  1484. inode->i_mode = S_IRUSR | S_IWUSR;
  1485. inode->i_uid = current_fsuid();
  1486. inode->i_gid = current_fsgid();
  1487. inode->i_flags |= S_PRIVATE | S_ANON_INODE;
  1488. simple_inode_init_ts(inode);
  1489. return inode;
  1490. }
  1491. EXPORT_SYMBOL(alloc_anon_inode);
  1492. /**
  1493. * simple_get_link - generic helper to get the target of "fast" symlinks
  1494. * @dentry: not used here
  1495. * @inode: the symlink inode
  1496. * @done: not used here
  1497. *
  1498. * Generic helper for filesystems to use for symlink inodes where a pointer to
  1499. * the symlink target is stored in ->i_link. NOTE: this isn't normally called,
  1500. * since as an optimization the path lookup code uses any non-NULL ->i_link
  1501. * directly, without calling ->get_link(). But ->get_link() still must be set,
  1502. * to mark the inode_operations as being for a symlink.
  1503. *
  1504. * Return: the symlink target
  1505. */
  1506. const char *simple_get_link(struct dentry *dentry, struct inode *inode,
  1507. struct delayed_call *done)
  1508. {
  1509. return inode->i_link;
  1510. }
  1511. EXPORT_SYMBOL(simple_get_link);
  1512. const struct inode_operations simple_symlink_inode_operations = {
  1513. .get_link = simple_get_link,
  1514. };
  1515. EXPORT_SYMBOL(simple_symlink_inode_operations);
  1516. /*
  1517. * Operations for a permanently empty directory.
  1518. */
  1519. static struct dentry *empty_dir_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
  1520. {
  1521. return ERR_PTR(-ENOENT);
  1522. }
  1523. static int empty_dir_setattr(struct mnt_idmap *idmap,
  1524. struct dentry *dentry, struct iattr *attr)
  1525. {
  1526. return -EPERM;
  1527. }
  1528. static ssize_t empty_dir_listxattr(struct dentry *dentry, char *list, size_t size)
  1529. {
  1530. return -EOPNOTSUPP;
  1531. }
  1532. static const struct inode_operations empty_dir_inode_operations = {
  1533. .lookup = empty_dir_lookup,
  1534. .setattr = empty_dir_setattr,
  1535. .listxattr = empty_dir_listxattr,
  1536. };
  1537. static loff_t empty_dir_llseek(struct file *file, loff_t offset, int whence)
  1538. {
  1539. /* An empty directory has two entries . and .. at offsets 0 and 1 */
  1540. return generic_file_llseek_size(file, offset, whence, 2, 2);
  1541. }
  1542. static int empty_dir_readdir(struct file *file, struct dir_context *ctx)
  1543. {
  1544. dir_emit_dots(file, ctx);
  1545. return 0;
  1546. }
  1547. static const struct file_operations empty_dir_operations = {
  1548. .llseek = empty_dir_llseek,
  1549. .read = generic_read_dir,
  1550. .iterate_shared = empty_dir_readdir,
  1551. .fsync = noop_fsync,
  1552. };
  1553. void make_empty_dir_inode(struct inode *inode)
  1554. {
  1555. set_nlink(inode, 2);
  1556. inode->i_mode = S_IFDIR | S_IRUGO | S_IXUGO;
  1557. inode->i_uid = GLOBAL_ROOT_UID;
  1558. inode->i_gid = GLOBAL_ROOT_GID;
  1559. inode->i_rdev = 0;
  1560. inode->i_size = 0;
  1561. inode->i_blkbits = PAGE_SHIFT;
  1562. inode->i_blocks = 0;
  1563. inode->i_op = &empty_dir_inode_operations;
  1564. inode->i_opflags &= ~IOP_XATTR;
  1565. inode->i_fop = &empty_dir_operations;
  1566. }
  1567. bool is_empty_dir_inode(struct inode *inode)
  1568. {
  1569. return (inode->i_fop == &empty_dir_operations) &&
  1570. (inode->i_op == &empty_dir_inode_operations);
  1571. }
  1572. #if IS_ENABLED(CONFIG_UNICODE)
  1573. /**
  1574. * generic_ci_d_compare - generic d_compare implementation for casefolding filesystems
  1575. * @dentry: dentry whose name we are checking against
  1576. * @len: len of name of dentry
  1577. * @str: str pointer to name of dentry
  1578. * @name: Name to compare against
  1579. *
  1580. * Return: 0 if names match, 1 if mismatch, or -ERRNO
  1581. */
  1582. int generic_ci_d_compare(const struct dentry *dentry, unsigned int len,
  1583. const char *str, const struct qstr *name)
  1584. {
  1585. const struct dentry *parent;
  1586. const struct inode *dir;
  1587. union shortname_store strbuf;
  1588. struct qstr qstr;
  1589. /*
  1590. * Attempt a case-sensitive match first. It is cheaper and
  1591. * should cover most lookups, including all the sane
  1592. * applications that expect a case-sensitive filesystem.
  1593. *
  1594. * This comparison is safe under RCU because the caller
  1595. * guarantees the consistency between str and len. See
  1596. * __d_lookup_rcu_op_compare() for details.
  1597. */
  1598. if (len == name->len && !memcmp(str, name->name, len))
  1599. return 0;
  1600. parent = READ_ONCE(dentry->d_parent);
  1601. dir = READ_ONCE(parent->d_inode);
  1602. if (!dir || !IS_CASEFOLDED(dir))
  1603. return 1;
  1604. qstr.len = len;
  1605. qstr.name = str;
  1606. /*
  1607. * If the dentry name is stored in-line, then it may be concurrently
  1608. * modified by a rename. If this happens, the VFS will eventually retry
  1609. * the lookup, so it doesn't matter what ->d_compare() returns.
  1610. * However, it's unsafe to call utf8_strncasecmp() with an unstable
  1611. * string. Therefore, we have to copy the name into a temporary buffer.
  1612. * As above, len is guaranteed to match str, so the shortname case
  1613. * is exactly when str points to ->d_shortname.
  1614. */
  1615. if (qstr.name == dentry->d_shortname.string) {
  1616. strbuf = dentry->d_shortname; // NUL is guaranteed to be in there
  1617. qstr.name = strbuf.string;
  1618. /* prevent compiler from optimizing out the temporary buffer */
  1619. barrier();
  1620. }
  1621. return utf8_strncasecmp(dentry->d_sb->s_encoding, name, &qstr);
  1622. }
  1623. EXPORT_SYMBOL(generic_ci_d_compare);
  1624. /**
  1625. * generic_ci_d_hash - generic d_hash implementation for casefolding filesystems
  1626. * @dentry: dentry of the parent directory
  1627. * @str: qstr of name whose hash we should fill in
  1628. *
  1629. * Return: 0 if hash was successful or unchanged, and -EINVAL on error
  1630. */
  1631. int generic_ci_d_hash(const struct dentry *dentry, struct qstr *str)
  1632. {
  1633. const struct inode *dir = READ_ONCE(dentry->d_inode);
  1634. struct super_block *sb = dentry->d_sb;
  1635. const struct unicode_map *um = sb->s_encoding;
  1636. int ret;
  1637. if (!dir || !IS_CASEFOLDED(dir))
  1638. return 0;
  1639. ret = utf8_casefold_hash(um, dentry, str);
  1640. if (ret < 0 && sb_has_strict_encoding(sb))
  1641. return -EINVAL;
  1642. return 0;
  1643. }
  1644. EXPORT_SYMBOL(generic_ci_d_hash);
  1645. static const struct dentry_operations generic_ci_dentry_ops = {
  1646. .d_hash = generic_ci_d_hash,
  1647. .d_compare = generic_ci_d_compare,
  1648. #ifdef CONFIG_FS_ENCRYPTION
  1649. .d_revalidate = fscrypt_d_revalidate,
  1650. #endif
  1651. };
  1652. /**
  1653. * generic_ci_match() - Match a name (case-insensitively) with a dirent.
  1654. * This is a filesystem helper for comparison with directory entries.
  1655. * generic_ci_d_compare should be used in VFS' ->d_compare instead.
  1656. *
  1657. * @parent: Inode of the parent of the dirent under comparison
  1658. * @name: name under lookup.
  1659. * @folded_name: Optional pre-folded name under lookup
  1660. * @de_name: Dirent name.
  1661. * @de_name_len: dirent name length.
  1662. *
  1663. * Test whether a case-insensitive directory entry matches the filename
  1664. * being searched. If @folded_name is provided, it is used instead of
  1665. * recalculating the casefold of @name.
  1666. *
  1667. * Return: > 0 if the directory entry matches, 0 if it doesn't match, or
  1668. * < 0 on error.
  1669. */
  1670. int generic_ci_match(const struct inode *parent,
  1671. const struct qstr *name,
  1672. const struct qstr *folded_name,
  1673. const u8 *de_name, u32 de_name_len)
  1674. {
  1675. const struct super_block *sb = parent->i_sb;
  1676. const struct unicode_map *um = sb->s_encoding;
  1677. struct fscrypt_str decrypted_name = FSTR_INIT(NULL, de_name_len);
  1678. struct qstr dirent = QSTR_INIT(de_name, de_name_len);
  1679. int res = 0;
  1680. if (IS_ENCRYPTED(parent)) {
  1681. const struct fscrypt_str encrypted_name =
  1682. FSTR_INIT((u8 *) de_name, de_name_len);
  1683. if (WARN_ON_ONCE(!fscrypt_has_encryption_key(parent)))
  1684. return -EINVAL;
  1685. decrypted_name.name = kmalloc(de_name_len, GFP_KERNEL);
  1686. if (!decrypted_name.name)
  1687. return -ENOMEM;
  1688. res = fscrypt_fname_disk_to_usr(parent, 0, 0, &encrypted_name,
  1689. &decrypted_name);
  1690. if (res < 0) {
  1691. kfree(decrypted_name.name);
  1692. return res;
  1693. }
  1694. dirent.name = decrypted_name.name;
  1695. dirent.len = decrypted_name.len;
  1696. }
  1697. /*
  1698. * Attempt a case-sensitive match first. It is cheaper and
  1699. * should cover most lookups, including all the sane
  1700. * applications that expect a case-sensitive filesystem.
  1701. */
  1702. if (dirent.len == name->len &&
  1703. !memcmp(name->name, dirent.name, dirent.len))
  1704. goto out;
  1705. if (folded_name->name)
  1706. res = utf8_strncasecmp_folded(um, folded_name, &dirent);
  1707. else
  1708. res = utf8_strncasecmp(um, name, &dirent);
  1709. out:
  1710. kfree(decrypted_name.name);
  1711. if (res < 0 && sb_has_strict_encoding(sb)) {
  1712. pr_err_ratelimited("Directory contains filename that is invalid UTF-8");
  1713. return 0;
  1714. }
  1715. return !res;
  1716. }
  1717. EXPORT_SYMBOL(generic_ci_match);
  1718. #endif
  1719. #ifdef CONFIG_FS_ENCRYPTION
  1720. static const struct dentry_operations generic_encrypted_dentry_ops = {
  1721. .d_revalidate = fscrypt_d_revalidate,
  1722. };
  1723. #endif
  1724. /**
  1725. * generic_set_sb_d_ops - helper for choosing the set of
  1726. * filesystem-wide dentry operations for the enabled features
  1727. * @sb: superblock to be configured
  1728. *
  1729. * Filesystems supporting casefolding and/or fscrypt can call this
  1730. * helper at mount-time to configure default dentry_operations to the
  1731. * best set of dentry operations required for the enabled features.
  1732. * The helper must be called after these have been configured, but
  1733. * before the root dentry is created.
  1734. */
  1735. void generic_set_sb_d_ops(struct super_block *sb)
  1736. {
  1737. #if IS_ENABLED(CONFIG_UNICODE)
  1738. if (sb->s_encoding) {
  1739. set_default_d_op(sb, &generic_ci_dentry_ops);
  1740. return;
  1741. }
  1742. #endif
  1743. #ifdef CONFIG_FS_ENCRYPTION
  1744. if (sb->s_cop) {
  1745. set_default_d_op(sb, &generic_encrypted_dentry_ops);
  1746. return;
  1747. }
  1748. #endif
  1749. }
  1750. EXPORT_SYMBOL(generic_set_sb_d_ops);
  1751. /**
  1752. * inode_maybe_inc_iversion - increments i_version
  1753. * @inode: inode with the i_version that should be updated
  1754. * @force: increment the counter even if it's not necessary?
  1755. *
  1756. * Every time the inode is modified, the i_version field must be seen to have
  1757. * changed by any observer.
  1758. *
  1759. * If "force" is set or the QUERIED flag is set, then ensure that we increment
  1760. * the value, and clear the queried flag.
  1761. *
  1762. * In the common case where neither is set, then we can return "false" without
  1763. * updating i_version.
  1764. *
  1765. * If this function returns false, and no other metadata has changed, then we
  1766. * can avoid logging the metadata.
  1767. */
  1768. bool inode_maybe_inc_iversion(struct inode *inode, bool force)
  1769. {
  1770. u64 cur, new;
  1771. /*
  1772. * The i_version field is not strictly ordered with any other inode
  1773. * information, but the legacy inode_inc_iversion code used a spinlock
  1774. * to serialize increments.
  1775. *
  1776. * We add a full memory barrier to ensure that any de facto ordering
  1777. * with other state is preserved (either implicitly coming from cmpxchg
  1778. * or explicitly from smp_mb if we don't know upfront if we will execute
  1779. * the former).
  1780. *
  1781. * These barriers pair with inode_query_iversion().
  1782. */
  1783. cur = inode_peek_iversion_raw(inode);
  1784. if (!force && !(cur & I_VERSION_QUERIED)) {
  1785. smp_mb();
  1786. cur = inode_peek_iversion_raw(inode);
  1787. }
  1788. do {
  1789. /* If flag is clear then we needn't do anything */
  1790. if (!force && !(cur & I_VERSION_QUERIED))
  1791. return false;
  1792. /* Since lowest bit is flag, add 2 to avoid it */
  1793. new = (cur & ~I_VERSION_QUERIED) + I_VERSION_INCREMENT;
  1794. } while (!atomic64_try_cmpxchg(&inode->i_version, &cur, new));
  1795. return true;
  1796. }
  1797. EXPORT_SYMBOL(inode_maybe_inc_iversion);
  1798. /**
  1799. * inode_query_iversion - read i_version for later use
  1800. * @inode: inode from which i_version should be read
  1801. *
  1802. * Read the inode i_version counter. This should be used by callers that wish
  1803. * to store the returned i_version for later comparison. This will guarantee
  1804. * that a later query of the i_version will result in a different value if
  1805. * anything has changed.
  1806. *
  1807. * In this implementation, we fetch the current value, set the QUERIED flag and
  1808. * then try to swap it into place with a cmpxchg, if it wasn't already set. If
  1809. * that fails, we try again with the newly fetched value from the cmpxchg.
  1810. */
  1811. u64 inode_query_iversion(struct inode *inode)
  1812. {
  1813. u64 cur, new;
  1814. bool fenced = false;
  1815. /*
  1816. * Memory barriers (implicit in cmpxchg, explicit in smp_mb) pair with
  1817. * inode_maybe_inc_iversion(), see that routine for more details.
  1818. */
  1819. cur = inode_peek_iversion_raw(inode);
  1820. do {
  1821. /* If flag is already set, then no need to swap */
  1822. if (cur & I_VERSION_QUERIED) {
  1823. if (!fenced)
  1824. smp_mb();
  1825. break;
  1826. }
  1827. fenced = true;
  1828. new = cur | I_VERSION_QUERIED;
  1829. } while (!atomic64_try_cmpxchg(&inode->i_version, &cur, new));
  1830. return cur >> I_VERSION_QUERIED_SHIFT;
  1831. }
  1832. EXPORT_SYMBOL(inode_query_iversion);
  1833. ssize_t direct_write_fallback(struct kiocb *iocb, struct iov_iter *iter,
  1834. ssize_t direct_written, ssize_t buffered_written)
  1835. {
  1836. struct address_space *mapping = iocb->ki_filp->f_mapping;
  1837. loff_t pos = iocb->ki_pos - buffered_written;
  1838. loff_t end = iocb->ki_pos - 1;
  1839. int err;
  1840. /*
  1841. * If the buffered write fallback returned an error, we want to return
  1842. * the number of bytes which were written by direct I/O, or the error
  1843. * code if that was zero.
  1844. *
  1845. * Note that this differs from normal direct-io semantics, which will
  1846. * return -EFOO even if some bytes were written.
  1847. */
  1848. if (unlikely(buffered_written < 0)) {
  1849. if (direct_written)
  1850. return direct_written;
  1851. return buffered_written;
  1852. }
  1853. /*
  1854. * We need to ensure that the page cache pages are written to disk and
  1855. * invalidated to preserve the expected O_DIRECT semantics.
  1856. */
  1857. err = filemap_write_and_wait_range(mapping, pos, end);
  1858. if (err < 0) {
  1859. /*
  1860. * We don't know how much we wrote, so just return the number of
  1861. * bytes which were direct-written
  1862. */
  1863. iocb->ki_pos -= buffered_written;
  1864. if (direct_written)
  1865. return direct_written;
  1866. return err;
  1867. }
  1868. invalidate_mapping_pages(mapping, pos >> PAGE_SHIFT, end >> PAGE_SHIFT);
  1869. return direct_written + buffered_written;
  1870. }
  1871. EXPORT_SYMBOL_GPL(direct_write_fallback);
  1872. /**
  1873. * simple_inode_init_ts - initialize the timestamps for a new inode
  1874. * @inode: inode to be initialized
  1875. *
  1876. * When a new inode is created, most filesystems set the timestamps to the
  1877. * current time. Add a helper to do this.
  1878. */
  1879. struct timespec64 simple_inode_init_ts(struct inode *inode)
  1880. {
  1881. struct timespec64 ts = inode_set_ctime_current(inode);
  1882. inode_set_atime_to_ts(inode, ts);
  1883. inode_set_mtime_to_ts(inode, ts);
  1884. return ts;
  1885. }
  1886. EXPORT_SYMBOL(simple_inode_init_ts);
  1887. struct dentry *stashed_dentry_get(struct dentry **stashed)
  1888. {
  1889. struct dentry *dentry;
  1890. guard(rcu)();
  1891. dentry = rcu_dereference(*stashed);
  1892. if (!dentry)
  1893. return NULL;
  1894. if (IS_ERR(dentry))
  1895. return dentry;
  1896. if (!lockref_get_not_dead(&dentry->d_lockref))
  1897. return NULL;
  1898. return dentry;
  1899. }
  1900. static struct dentry *prepare_anon_dentry(struct dentry **stashed,
  1901. struct super_block *sb,
  1902. void *data)
  1903. {
  1904. struct dentry *dentry;
  1905. struct inode *inode;
  1906. const struct stashed_operations *sops = sb->s_fs_info;
  1907. int ret;
  1908. inode = new_inode_pseudo(sb);
  1909. if (!inode) {
  1910. sops->put_data(data);
  1911. return ERR_PTR(-ENOMEM);
  1912. }
  1913. inode->i_flags |= S_IMMUTABLE;
  1914. inode->i_mode = S_IFREG;
  1915. simple_inode_init_ts(inode);
  1916. ret = sops->init_inode(inode, data);
  1917. if (ret < 0) {
  1918. iput(inode);
  1919. return ERR_PTR(ret);
  1920. }
  1921. /* Notice when this is changed. */
  1922. WARN_ON_ONCE(!S_ISREG(inode->i_mode));
  1923. dentry = d_alloc_anon(sb);
  1924. if (!dentry) {
  1925. iput(inode);
  1926. return ERR_PTR(-ENOMEM);
  1927. }
  1928. /* Store address of location where dentry's supposed to be stashed. */
  1929. dentry->d_fsdata = stashed;
  1930. /* @data is now owned by the fs */
  1931. d_instantiate(dentry, inode);
  1932. return dentry;
  1933. }
  1934. struct dentry *stash_dentry(struct dentry **stashed, struct dentry *dentry)
  1935. {
  1936. guard(rcu)();
  1937. for (;;) {
  1938. struct dentry *old;
  1939. /* Assume any old dentry was cleared out. */
  1940. old = cmpxchg(stashed, NULL, dentry);
  1941. if (likely(!old))
  1942. return dentry;
  1943. /* Check if somebody else installed a reusable dentry. */
  1944. if (lockref_get_not_dead(&old->d_lockref))
  1945. return old;
  1946. /* There's an old dead dentry there, try to take it over. */
  1947. if (likely(try_cmpxchg(stashed, &old, dentry)))
  1948. return dentry;
  1949. }
  1950. }
  1951. /**
  1952. * path_from_stashed - create path from stashed or new dentry
  1953. * @stashed: where to retrieve or stash dentry
  1954. * @mnt: mnt of the filesystems to use
  1955. * @data: data to store in inode->i_private
  1956. * @path: path to create
  1957. *
  1958. * The function tries to retrieve a stashed dentry from @stashed. If the dentry
  1959. * is still valid then it will be reused. If the dentry isn't able the function
  1960. * will allocate a new dentry and inode. It will then check again whether it
  1961. * can reuse an existing dentry in case one has been added in the meantime or
  1962. * update @stashed with the newly added dentry.
  1963. *
  1964. * Special-purpose helper for nsfs and pidfs.
  1965. *
  1966. * Return: On success zero and on failure a negative error is returned.
  1967. */
  1968. int path_from_stashed(struct dentry **stashed, struct vfsmount *mnt, void *data,
  1969. struct path *path)
  1970. {
  1971. struct dentry *dentry, *res;
  1972. const struct stashed_operations *sops = mnt->mnt_sb->s_fs_info;
  1973. /* See if dentry can be reused. */
  1974. res = stashed_dentry_get(stashed);
  1975. if (IS_ERR(res))
  1976. return PTR_ERR(res);
  1977. if (res) {
  1978. sops->put_data(data);
  1979. goto make_path;
  1980. }
  1981. /* Allocate a new dentry. */
  1982. dentry = prepare_anon_dentry(stashed, mnt->mnt_sb, data);
  1983. if (IS_ERR(dentry))
  1984. return PTR_ERR(dentry);
  1985. /* Added a new dentry. @data is now owned by the filesystem. */
  1986. if (sops->stash_dentry)
  1987. res = sops->stash_dentry(stashed, dentry);
  1988. else
  1989. res = stash_dentry(stashed, dentry);
  1990. if (IS_ERR(res)) {
  1991. dput(dentry);
  1992. return PTR_ERR(res);
  1993. }
  1994. if (res != dentry)
  1995. dput(dentry);
  1996. make_path:
  1997. path->dentry = res;
  1998. path->mnt = mntget(mnt);
  1999. VFS_WARN_ON_ONCE(path->dentry->d_fsdata != stashed);
  2000. VFS_WARN_ON_ONCE(d_inode(path->dentry)->i_private != data);
  2001. return 0;
  2002. }
  2003. void stashed_dentry_prune(struct dentry *dentry)
  2004. {
  2005. struct dentry **stashed = dentry->d_fsdata;
  2006. struct inode *inode = d_inode(dentry);
  2007. if (WARN_ON_ONCE(!stashed))
  2008. return;
  2009. if (!inode)
  2010. return;
  2011. /*
  2012. * Only replace our own @dentry as someone else might've
  2013. * already cleared out @dentry and stashed their own
  2014. * dentry in there.
  2015. */
  2016. cmpxchg(stashed, dentry, NULL);
  2017. }
  2018. /**
  2019. * simple_start_creating - prepare to create a given name
  2020. * @parent: directory in which to prepare to create the name
  2021. * @name: the name to be created
  2022. *
  2023. * Required lock is taken and a lookup in performed prior to creating an
  2024. * object in a directory. No permission checking is performed.
  2025. *
  2026. * Returns: a negative dentry on which vfs_create() or similar may
  2027. * be attempted, or an error.
  2028. */
  2029. struct dentry *simple_start_creating(struct dentry *parent, const char *name)
  2030. {
  2031. struct qstr qname = QSTR(name);
  2032. int err;
  2033. err = lookup_noperm_common(&qname, parent);
  2034. if (err)
  2035. return ERR_PTR(err);
  2036. return start_dirop(parent, &qname, LOOKUP_CREATE | LOOKUP_EXCL);
  2037. }
  2038. EXPORT_SYMBOL(simple_start_creating);
  2039. /* parent must have been held exclusive since simple_start_creating() */
  2040. void simple_done_creating(struct dentry *child)
  2041. {
  2042. inode_unlock(child->d_parent->d_inode);
  2043. dput(child);
  2044. }
  2045. EXPORT_SYMBOL(simple_done_creating);