dir.c 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * fs/kernfs/dir.c - kernfs directory implementation
  4. *
  5. * Copyright (c) 2001-3 Patrick Mochel
  6. * Copyright (c) 2007 SUSE Linux Products GmbH
  7. * Copyright (c) 2007, 2013 Tejun Heo <tj@kernel.org>
  8. */
  9. #include <linux/sched.h>
  10. #include <linux/fs.h>
  11. #include <linux/namei.h>
  12. #include <linux/idr.h>
  13. #include <linux/slab.h>
  14. #include <linux/security.h>
  15. #include <linux/hash.h>
  16. #include "kernfs-internal.h"
  17. static DEFINE_RWLOCK(kernfs_rename_lock); /* kn->parent and ->name */
  18. /*
  19. * Don't use rename_lock to piggy back on pr_cont_buf. We don't want to
  20. * call pr_cont() while holding rename_lock. Because sometimes pr_cont()
  21. * will perform wakeups when releasing console_sem. Holding rename_lock
  22. * will introduce deadlock if the scheduler reads the kernfs_name in the
  23. * wakeup path.
  24. */
  25. static DEFINE_SPINLOCK(kernfs_pr_cont_lock);
  26. static char kernfs_pr_cont_buf[PATH_MAX]; /* protected by pr_cont_lock */
  27. static DEFINE_SPINLOCK(kernfs_idr_lock); /* root->ino_idr */
  28. #define rb_to_kn(X) rb_entry((X), struct kernfs_node, rb)
  29. static bool __kernfs_active(struct kernfs_node *kn)
  30. {
  31. return atomic_read(&kn->active) >= 0;
  32. }
  33. static bool kernfs_active(struct kernfs_node *kn)
  34. {
  35. lockdep_assert_held(&kernfs_root(kn)->kernfs_rwsem);
  36. return __kernfs_active(kn);
  37. }
  38. static bool kernfs_lockdep(struct kernfs_node *kn)
  39. {
  40. #ifdef CONFIG_DEBUG_LOCK_ALLOC
  41. return kn->flags & KERNFS_LOCKDEP;
  42. #else
  43. return false;
  44. #endif
  45. }
  46. static int kernfs_name_locked(struct kernfs_node *kn, char *buf, size_t buflen)
  47. {
  48. if (!kn)
  49. return strscpy(buf, "(null)", buflen);
  50. return strscpy(buf, kn->parent ? kn->name : "/", buflen);
  51. }
  52. /* kernfs_node_depth - compute depth from @from to @to */
  53. static size_t kernfs_depth(struct kernfs_node *from, struct kernfs_node *to)
  54. {
  55. size_t depth = 0;
  56. while (to->parent && to != from) {
  57. depth++;
  58. to = to->parent;
  59. }
  60. return depth;
  61. }
  62. static struct kernfs_node *kernfs_common_ancestor(struct kernfs_node *a,
  63. struct kernfs_node *b)
  64. {
  65. size_t da, db;
  66. struct kernfs_root *ra = kernfs_root(a), *rb = kernfs_root(b);
  67. if (ra != rb)
  68. return NULL;
  69. da = kernfs_depth(ra->kn, a);
  70. db = kernfs_depth(rb->kn, b);
  71. while (da > db) {
  72. a = a->parent;
  73. da--;
  74. }
  75. while (db > da) {
  76. b = b->parent;
  77. db--;
  78. }
  79. /* worst case b and a will be the same at root */
  80. while (b != a) {
  81. b = b->parent;
  82. a = a->parent;
  83. }
  84. return a;
  85. }
  86. /**
  87. * kernfs_path_from_node_locked - find a pseudo-absolute path to @kn_to,
  88. * where kn_from is treated as root of the path.
  89. * @kn_from: kernfs node which should be treated as root for the path
  90. * @kn_to: kernfs node to which path is needed
  91. * @buf: buffer to copy the path into
  92. * @buflen: size of @buf
  93. *
  94. * We need to handle couple of scenarios here:
  95. * [1] when @kn_from is an ancestor of @kn_to at some level
  96. * kn_from: /n1/n2/n3
  97. * kn_to: /n1/n2/n3/n4/n5
  98. * result: /n4/n5
  99. *
  100. * [2] when @kn_from is on a different hierarchy and we need to find common
  101. * ancestor between @kn_from and @kn_to.
  102. * kn_from: /n1/n2/n3/n4
  103. * kn_to: /n1/n2/n5
  104. * result: /../../n5
  105. * OR
  106. * kn_from: /n1/n2/n3/n4/n5 [depth=5]
  107. * kn_to: /n1/n2/n3 [depth=3]
  108. * result: /../..
  109. *
  110. * [3] when @kn_to is %NULL result will be "(null)"
  111. *
  112. * Return: the length of the constructed path. If the path would have been
  113. * greater than @buflen, @buf contains the truncated path with the trailing
  114. * '\0'. On error, -errno is returned.
  115. */
  116. static int kernfs_path_from_node_locked(struct kernfs_node *kn_to,
  117. struct kernfs_node *kn_from,
  118. char *buf, size_t buflen)
  119. {
  120. struct kernfs_node *kn, *common;
  121. const char parent_str[] = "/..";
  122. size_t depth_from, depth_to, len = 0;
  123. ssize_t copied;
  124. int i, j;
  125. if (!kn_to)
  126. return strscpy(buf, "(null)", buflen);
  127. if (!kn_from)
  128. kn_from = kernfs_root(kn_to)->kn;
  129. if (kn_from == kn_to)
  130. return strscpy(buf, "/", buflen);
  131. common = kernfs_common_ancestor(kn_from, kn_to);
  132. if (WARN_ON(!common))
  133. return -EINVAL;
  134. depth_to = kernfs_depth(common, kn_to);
  135. depth_from = kernfs_depth(common, kn_from);
  136. buf[0] = '\0';
  137. for (i = 0; i < depth_from; i++) {
  138. copied = strscpy(buf + len, parent_str, buflen - len);
  139. if (copied < 0)
  140. return copied;
  141. len += copied;
  142. }
  143. /* Calculate how many bytes we need for the rest */
  144. for (i = depth_to - 1; i >= 0; i--) {
  145. for (kn = kn_to, j = 0; j < i; j++)
  146. kn = kn->parent;
  147. len += scnprintf(buf + len, buflen - len, "/%s", kn->name);
  148. }
  149. return len;
  150. }
  151. /**
  152. * kernfs_name - obtain the name of a given node
  153. * @kn: kernfs_node of interest
  154. * @buf: buffer to copy @kn's name into
  155. * @buflen: size of @buf
  156. *
  157. * Copies the name of @kn into @buf of @buflen bytes. The behavior is
  158. * similar to strscpy().
  159. *
  160. * Fills buffer with "(null)" if @kn is %NULL.
  161. *
  162. * Return: the resulting length of @buf. If @buf isn't long enough,
  163. * it's filled up to @buflen-1 and nul terminated, and returns -E2BIG.
  164. *
  165. * This function can be called from any context.
  166. */
  167. int kernfs_name(struct kernfs_node *kn, char *buf, size_t buflen)
  168. {
  169. unsigned long flags;
  170. int ret;
  171. read_lock_irqsave(&kernfs_rename_lock, flags);
  172. ret = kernfs_name_locked(kn, buf, buflen);
  173. read_unlock_irqrestore(&kernfs_rename_lock, flags);
  174. return ret;
  175. }
  176. /**
  177. * kernfs_path_from_node - build path of node @to relative to @from.
  178. * @from: parent kernfs_node relative to which we need to build the path
  179. * @to: kernfs_node of interest
  180. * @buf: buffer to copy @to's path into
  181. * @buflen: size of @buf
  182. *
  183. * Builds @to's path relative to @from in @buf. @from and @to must
  184. * be on the same kernfs-root. If @from is not parent of @to, then a relative
  185. * path (which includes '..'s) as needed to reach from @from to @to is
  186. * returned.
  187. *
  188. * Return: the length of the constructed path. If the path would have been
  189. * greater than @buflen, @buf contains the truncated path with the trailing
  190. * '\0'. On error, -errno is returned.
  191. */
  192. int kernfs_path_from_node(struct kernfs_node *to, struct kernfs_node *from,
  193. char *buf, size_t buflen)
  194. {
  195. unsigned long flags;
  196. int ret;
  197. read_lock_irqsave(&kernfs_rename_lock, flags);
  198. ret = kernfs_path_from_node_locked(to, from, buf, buflen);
  199. read_unlock_irqrestore(&kernfs_rename_lock, flags);
  200. return ret;
  201. }
  202. EXPORT_SYMBOL_GPL(kernfs_path_from_node);
  203. /**
  204. * pr_cont_kernfs_name - pr_cont name of a kernfs_node
  205. * @kn: kernfs_node of interest
  206. *
  207. * This function can be called from any context.
  208. */
  209. void pr_cont_kernfs_name(struct kernfs_node *kn)
  210. {
  211. unsigned long flags;
  212. spin_lock_irqsave(&kernfs_pr_cont_lock, flags);
  213. kernfs_name(kn, kernfs_pr_cont_buf, sizeof(kernfs_pr_cont_buf));
  214. pr_cont("%s", kernfs_pr_cont_buf);
  215. spin_unlock_irqrestore(&kernfs_pr_cont_lock, flags);
  216. }
  217. /**
  218. * pr_cont_kernfs_path - pr_cont path of a kernfs_node
  219. * @kn: kernfs_node of interest
  220. *
  221. * This function can be called from any context.
  222. */
  223. void pr_cont_kernfs_path(struct kernfs_node *kn)
  224. {
  225. unsigned long flags;
  226. int sz;
  227. spin_lock_irqsave(&kernfs_pr_cont_lock, flags);
  228. sz = kernfs_path_from_node(kn, NULL, kernfs_pr_cont_buf,
  229. sizeof(kernfs_pr_cont_buf));
  230. if (sz < 0) {
  231. if (sz == -E2BIG)
  232. pr_cont("(name too long)");
  233. else
  234. pr_cont("(error)");
  235. goto out;
  236. }
  237. pr_cont("%s", kernfs_pr_cont_buf);
  238. out:
  239. spin_unlock_irqrestore(&kernfs_pr_cont_lock, flags);
  240. }
  241. /**
  242. * kernfs_get_parent - determine the parent node and pin it
  243. * @kn: kernfs_node of interest
  244. *
  245. * Determines @kn's parent, pins and returns it. This function can be
  246. * called from any context.
  247. *
  248. * Return: parent node of @kn
  249. */
  250. struct kernfs_node *kernfs_get_parent(struct kernfs_node *kn)
  251. {
  252. struct kernfs_node *parent;
  253. unsigned long flags;
  254. read_lock_irqsave(&kernfs_rename_lock, flags);
  255. parent = kn->parent;
  256. kernfs_get(parent);
  257. read_unlock_irqrestore(&kernfs_rename_lock, flags);
  258. return parent;
  259. }
  260. /**
  261. * kernfs_name_hash - calculate hash of @ns + @name
  262. * @name: Null terminated string to hash
  263. * @ns: Namespace tag to hash
  264. *
  265. * Return: 31-bit hash of ns + name (so it fits in an off_t)
  266. */
  267. static unsigned int kernfs_name_hash(const char *name, const void *ns)
  268. {
  269. unsigned long hash = init_name_hash(ns);
  270. unsigned int len = strlen(name);
  271. while (len--)
  272. hash = partial_name_hash(*name++, hash);
  273. hash = end_name_hash(hash);
  274. hash &= 0x7fffffffU;
  275. /* Reserve hash numbers 0, 1 and INT_MAX for magic directory entries */
  276. if (hash < 2)
  277. hash += 2;
  278. if (hash >= INT_MAX)
  279. hash = INT_MAX - 1;
  280. return hash;
  281. }
  282. static int kernfs_name_compare(unsigned int hash, const char *name,
  283. const void *ns, const struct kernfs_node *kn)
  284. {
  285. if (hash < kn->hash)
  286. return -1;
  287. if (hash > kn->hash)
  288. return 1;
  289. if (ns < kn->ns)
  290. return -1;
  291. if (ns > kn->ns)
  292. return 1;
  293. return strcmp(name, kn->name);
  294. }
  295. static int kernfs_sd_compare(const struct kernfs_node *left,
  296. const struct kernfs_node *right)
  297. {
  298. return kernfs_name_compare(left->hash, left->name, left->ns, right);
  299. }
  300. /**
  301. * kernfs_link_sibling - link kernfs_node into sibling rbtree
  302. * @kn: kernfs_node of interest
  303. *
  304. * Link @kn into its sibling rbtree which starts from
  305. * @kn->parent->dir.children.
  306. *
  307. * Locking:
  308. * kernfs_rwsem held exclusive
  309. *
  310. * Return:
  311. * %0 on success, -EEXIST on failure.
  312. */
  313. static int kernfs_link_sibling(struct kernfs_node *kn)
  314. {
  315. struct rb_node **node = &kn->parent->dir.children.rb_node;
  316. struct rb_node *parent = NULL;
  317. while (*node) {
  318. struct kernfs_node *pos;
  319. int result;
  320. pos = rb_to_kn(*node);
  321. parent = *node;
  322. result = kernfs_sd_compare(kn, pos);
  323. if (result < 0)
  324. node = &pos->rb.rb_left;
  325. else if (result > 0)
  326. node = &pos->rb.rb_right;
  327. else
  328. return -EEXIST;
  329. }
  330. /* add new node and rebalance the tree */
  331. rb_link_node(&kn->rb, parent, node);
  332. rb_insert_color(&kn->rb, &kn->parent->dir.children);
  333. /* successfully added, account subdir number */
  334. down_write(&kernfs_root(kn)->kernfs_iattr_rwsem);
  335. if (kernfs_type(kn) == KERNFS_DIR)
  336. kn->parent->dir.subdirs++;
  337. kernfs_inc_rev(kn->parent);
  338. up_write(&kernfs_root(kn)->kernfs_iattr_rwsem);
  339. return 0;
  340. }
  341. /**
  342. * kernfs_unlink_sibling - unlink kernfs_node from sibling rbtree
  343. * @kn: kernfs_node of interest
  344. *
  345. * Try to unlink @kn from its sibling rbtree which starts from
  346. * kn->parent->dir.children.
  347. *
  348. * Return: %true if @kn was actually removed,
  349. * %false if @kn wasn't on the rbtree.
  350. *
  351. * Locking:
  352. * kernfs_rwsem held exclusive
  353. */
  354. static bool kernfs_unlink_sibling(struct kernfs_node *kn)
  355. {
  356. if (RB_EMPTY_NODE(&kn->rb))
  357. return false;
  358. down_write(&kernfs_root(kn)->kernfs_iattr_rwsem);
  359. if (kernfs_type(kn) == KERNFS_DIR)
  360. kn->parent->dir.subdirs--;
  361. kernfs_inc_rev(kn->parent);
  362. up_write(&kernfs_root(kn)->kernfs_iattr_rwsem);
  363. rb_erase(&kn->rb, &kn->parent->dir.children);
  364. RB_CLEAR_NODE(&kn->rb);
  365. return true;
  366. }
  367. /**
  368. * kernfs_get_active - get an active reference to kernfs_node
  369. * @kn: kernfs_node to get an active reference to
  370. *
  371. * Get an active reference of @kn. This function is noop if @kn
  372. * is %NULL.
  373. *
  374. * Return:
  375. * Pointer to @kn on success, %NULL on failure.
  376. */
  377. struct kernfs_node *kernfs_get_active(struct kernfs_node *kn)
  378. {
  379. if (unlikely(!kn))
  380. return NULL;
  381. if (!atomic_inc_unless_negative(&kn->active))
  382. return NULL;
  383. if (kernfs_lockdep(kn))
  384. rwsem_acquire_read(&kn->dep_map, 0, 1, _RET_IP_);
  385. return kn;
  386. }
  387. /**
  388. * kernfs_put_active - put an active reference to kernfs_node
  389. * @kn: kernfs_node to put an active reference to
  390. *
  391. * Put an active reference to @kn. This function is noop if @kn
  392. * is %NULL.
  393. */
  394. void kernfs_put_active(struct kernfs_node *kn)
  395. {
  396. int v;
  397. if (unlikely(!kn))
  398. return;
  399. if (kernfs_lockdep(kn))
  400. rwsem_release(&kn->dep_map, _RET_IP_);
  401. v = atomic_dec_return(&kn->active);
  402. if (likely(v != KN_DEACTIVATED_BIAS))
  403. return;
  404. wake_up_all(&kernfs_root(kn)->deactivate_waitq);
  405. }
  406. /**
  407. * kernfs_drain - drain kernfs_node
  408. * @kn: kernfs_node to drain
  409. *
  410. * Drain existing usages and nuke all existing mmaps of @kn. Multiple
  411. * removers may invoke this function concurrently on @kn and all will
  412. * return after draining is complete.
  413. */
  414. static void kernfs_drain(struct kernfs_node *kn)
  415. __releases(&kernfs_root(kn)->kernfs_rwsem)
  416. __acquires(&kernfs_root(kn)->kernfs_rwsem)
  417. {
  418. struct kernfs_root *root = kernfs_root(kn);
  419. lockdep_assert_held_write(&root->kernfs_rwsem);
  420. WARN_ON_ONCE(kernfs_active(kn));
  421. /*
  422. * Skip draining if already fully drained. This avoids draining and its
  423. * lockdep annotations for nodes which have never been activated
  424. * allowing embedding kernfs_remove() in create error paths without
  425. * worrying about draining.
  426. */
  427. if (atomic_read(&kn->active) == KN_DEACTIVATED_BIAS &&
  428. !kernfs_should_drain_open_files(kn))
  429. return;
  430. up_write(&root->kernfs_rwsem);
  431. if (kernfs_lockdep(kn)) {
  432. rwsem_acquire(&kn->dep_map, 0, 0, _RET_IP_);
  433. if (atomic_read(&kn->active) != KN_DEACTIVATED_BIAS)
  434. lock_contended(&kn->dep_map, _RET_IP_);
  435. }
  436. wait_event(root->deactivate_waitq,
  437. atomic_read(&kn->active) == KN_DEACTIVATED_BIAS);
  438. if (kernfs_lockdep(kn)) {
  439. lock_acquired(&kn->dep_map, _RET_IP_);
  440. rwsem_release(&kn->dep_map, _RET_IP_);
  441. }
  442. if (kernfs_should_drain_open_files(kn))
  443. kernfs_drain_open_files(kn);
  444. down_write(&root->kernfs_rwsem);
  445. }
  446. /**
  447. * kernfs_get - get a reference count on a kernfs_node
  448. * @kn: the target kernfs_node
  449. */
  450. void kernfs_get(struct kernfs_node *kn)
  451. {
  452. if (kn) {
  453. WARN_ON(!atomic_read(&kn->count));
  454. atomic_inc(&kn->count);
  455. }
  456. }
  457. EXPORT_SYMBOL_GPL(kernfs_get);
  458. static void kernfs_free_rcu(struct rcu_head *rcu)
  459. {
  460. struct kernfs_node *kn = container_of(rcu, struct kernfs_node, rcu);
  461. kfree_const(kn->name);
  462. if (kn->iattr) {
  463. simple_xattrs_free(&kn->iattr->xattrs, NULL);
  464. kmem_cache_free(kernfs_iattrs_cache, kn->iattr);
  465. }
  466. kmem_cache_free(kernfs_node_cache, kn);
  467. }
  468. /**
  469. * kernfs_put - put a reference count on a kernfs_node
  470. * @kn: the target kernfs_node
  471. *
  472. * Put a reference count of @kn and destroy it if it reached zero.
  473. */
  474. void kernfs_put(struct kernfs_node *kn)
  475. {
  476. struct kernfs_node *parent;
  477. struct kernfs_root *root;
  478. if (!kn || !atomic_dec_and_test(&kn->count))
  479. return;
  480. root = kernfs_root(kn);
  481. repeat:
  482. /*
  483. * Moving/renaming is always done while holding reference.
  484. * kn->parent won't change beneath us.
  485. */
  486. parent = kn->parent;
  487. WARN_ONCE(atomic_read(&kn->active) != KN_DEACTIVATED_BIAS,
  488. "kernfs_put: %s/%s: released with incorrect active_ref %d\n",
  489. parent ? parent->name : "", kn->name, atomic_read(&kn->active));
  490. if (kernfs_type(kn) == KERNFS_LINK)
  491. kernfs_put(kn->symlink.target_kn);
  492. spin_lock(&kernfs_idr_lock);
  493. idr_remove(&root->ino_idr, (u32)kernfs_ino(kn));
  494. spin_unlock(&kernfs_idr_lock);
  495. call_rcu(&kn->rcu, kernfs_free_rcu);
  496. kn = parent;
  497. if (kn) {
  498. if (atomic_dec_and_test(&kn->count))
  499. goto repeat;
  500. } else {
  501. /* just released the root kn, free @root too */
  502. idr_destroy(&root->ino_idr);
  503. kfree_rcu(root, rcu);
  504. }
  505. }
  506. EXPORT_SYMBOL_GPL(kernfs_put);
  507. /**
  508. * kernfs_node_from_dentry - determine kernfs_node associated with a dentry
  509. * @dentry: the dentry in question
  510. *
  511. * Return: the kernfs_node associated with @dentry. If @dentry is not a
  512. * kernfs one, %NULL is returned.
  513. *
  514. * While the returned kernfs_node will stay accessible as long as @dentry
  515. * is accessible, the returned node can be in any state and the caller is
  516. * fully responsible for determining what's accessible.
  517. */
  518. struct kernfs_node *kernfs_node_from_dentry(struct dentry *dentry)
  519. {
  520. if (dentry->d_sb->s_op == &kernfs_sops)
  521. return kernfs_dentry_node(dentry);
  522. return NULL;
  523. }
  524. static struct kernfs_node *__kernfs_new_node(struct kernfs_root *root,
  525. struct kernfs_node *parent,
  526. const char *name, umode_t mode,
  527. kuid_t uid, kgid_t gid,
  528. unsigned flags)
  529. {
  530. struct kernfs_node *kn;
  531. u32 id_highbits;
  532. int ret;
  533. name = kstrdup_const(name, GFP_KERNEL);
  534. if (!name)
  535. return NULL;
  536. kn = kmem_cache_zalloc(kernfs_node_cache, GFP_KERNEL);
  537. if (!kn)
  538. goto err_out1;
  539. idr_preload(GFP_KERNEL);
  540. spin_lock(&kernfs_idr_lock);
  541. ret = idr_alloc_cyclic(&root->ino_idr, kn, 1, 0, GFP_ATOMIC);
  542. if (ret >= 0 && ret < root->last_id_lowbits)
  543. root->id_highbits++;
  544. id_highbits = root->id_highbits;
  545. root->last_id_lowbits = ret;
  546. spin_unlock(&kernfs_idr_lock);
  547. idr_preload_end();
  548. if (ret < 0)
  549. goto err_out2;
  550. kn->id = (u64)id_highbits << 32 | ret;
  551. atomic_set(&kn->count, 1);
  552. atomic_set(&kn->active, KN_DEACTIVATED_BIAS);
  553. RB_CLEAR_NODE(&kn->rb);
  554. kn->name = name;
  555. kn->mode = mode;
  556. kn->flags = flags;
  557. if (!uid_eq(uid, GLOBAL_ROOT_UID) || !gid_eq(gid, GLOBAL_ROOT_GID)) {
  558. struct iattr iattr = {
  559. .ia_valid = ATTR_UID | ATTR_GID,
  560. .ia_uid = uid,
  561. .ia_gid = gid,
  562. };
  563. ret = __kernfs_setattr(kn, &iattr);
  564. if (ret < 0)
  565. goto err_out3;
  566. }
  567. if (parent) {
  568. ret = security_kernfs_init_security(parent, kn);
  569. if (ret)
  570. goto err_out3;
  571. }
  572. return kn;
  573. err_out3:
  574. spin_lock(&kernfs_idr_lock);
  575. idr_remove(&root->ino_idr, (u32)kernfs_ino(kn));
  576. spin_unlock(&kernfs_idr_lock);
  577. err_out2:
  578. kmem_cache_free(kernfs_node_cache, kn);
  579. err_out1:
  580. kfree_const(name);
  581. return NULL;
  582. }
  583. struct kernfs_node *kernfs_new_node(struct kernfs_node *parent,
  584. const char *name, umode_t mode,
  585. kuid_t uid, kgid_t gid,
  586. unsigned flags)
  587. {
  588. struct kernfs_node *kn;
  589. if (parent->mode & S_ISGID) {
  590. /* this code block imitates inode_init_owner() for
  591. * kernfs
  592. */
  593. if (parent->iattr)
  594. gid = parent->iattr->ia_gid;
  595. if (flags & KERNFS_DIR)
  596. mode |= S_ISGID;
  597. }
  598. kn = __kernfs_new_node(kernfs_root(parent), parent,
  599. name, mode, uid, gid, flags);
  600. if (kn) {
  601. kernfs_get(parent);
  602. kn->parent = parent;
  603. }
  604. return kn;
  605. }
  606. /*
  607. * kernfs_find_and_get_node_by_id - get kernfs_node from node id
  608. * @root: the kernfs root
  609. * @id: the target node id
  610. *
  611. * @id's lower 32bits encode ino and upper gen. If the gen portion is
  612. * zero, all generations are matched.
  613. *
  614. * Return: %NULL on failure,
  615. * otherwise a kernfs node with reference counter incremented.
  616. */
  617. struct kernfs_node *kernfs_find_and_get_node_by_id(struct kernfs_root *root,
  618. u64 id)
  619. {
  620. struct kernfs_node *kn;
  621. ino_t ino = kernfs_id_ino(id);
  622. u32 gen = kernfs_id_gen(id);
  623. rcu_read_lock();
  624. kn = idr_find(&root->ino_idr, (u32)ino);
  625. if (!kn)
  626. goto err_unlock;
  627. if (sizeof(ino_t) >= sizeof(u64)) {
  628. /* we looked up with the low 32bits, compare the whole */
  629. if (kernfs_ino(kn) != ino)
  630. goto err_unlock;
  631. } else {
  632. /* 0 matches all generations */
  633. if (unlikely(gen && kernfs_gen(kn) != gen))
  634. goto err_unlock;
  635. }
  636. /*
  637. * We should fail if @kn has never been activated and guarantee success
  638. * if the caller knows that @kn is active. Both can be achieved by
  639. * __kernfs_active() which tests @kn->active without kernfs_rwsem.
  640. */
  641. if (unlikely(!__kernfs_active(kn) || !atomic_inc_not_zero(&kn->count)))
  642. goto err_unlock;
  643. rcu_read_unlock();
  644. return kn;
  645. err_unlock:
  646. rcu_read_unlock();
  647. return NULL;
  648. }
  649. /**
  650. * kernfs_add_one - add kernfs_node to parent without warning
  651. * @kn: kernfs_node to be added
  652. *
  653. * The caller must already have initialized @kn->parent. This
  654. * function increments nlink of the parent's inode if @kn is a
  655. * directory and link into the children list of the parent.
  656. *
  657. * Return:
  658. * %0 on success, -EEXIST if entry with the given name already
  659. * exists.
  660. */
  661. int kernfs_add_one(struct kernfs_node *kn)
  662. {
  663. struct kernfs_node *parent = kn->parent;
  664. struct kernfs_root *root = kernfs_root(parent);
  665. struct kernfs_iattrs *ps_iattr;
  666. bool has_ns;
  667. int ret;
  668. down_write(&root->kernfs_rwsem);
  669. ret = -EINVAL;
  670. has_ns = kernfs_ns_enabled(parent);
  671. if (WARN(has_ns != (bool)kn->ns, KERN_WARNING "kernfs: ns %s in '%s' for '%s'\n",
  672. has_ns ? "required" : "invalid", parent->name, kn->name))
  673. goto out_unlock;
  674. if (kernfs_type(parent) != KERNFS_DIR)
  675. goto out_unlock;
  676. ret = -ENOENT;
  677. if (parent->flags & (KERNFS_REMOVING | KERNFS_EMPTY_DIR))
  678. goto out_unlock;
  679. kn->hash = kernfs_name_hash(kn->name, kn->ns);
  680. ret = kernfs_link_sibling(kn);
  681. if (ret)
  682. goto out_unlock;
  683. /* Update timestamps on the parent */
  684. down_write(&root->kernfs_iattr_rwsem);
  685. ps_iattr = parent->iattr;
  686. if (ps_iattr) {
  687. ktime_get_real_ts64(&ps_iattr->ia_ctime);
  688. ps_iattr->ia_mtime = ps_iattr->ia_ctime;
  689. }
  690. up_write(&root->kernfs_iattr_rwsem);
  691. up_write(&root->kernfs_rwsem);
  692. /*
  693. * Activate the new node unless CREATE_DEACTIVATED is requested.
  694. * If not activated here, the kernfs user is responsible for
  695. * activating the node with kernfs_activate(). A node which hasn't
  696. * been activated is not visible to userland and its removal won't
  697. * trigger deactivation.
  698. */
  699. if (!(kernfs_root(kn)->flags & KERNFS_ROOT_CREATE_DEACTIVATED))
  700. kernfs_activate(kn);
  701. return 0;
  702. out_unlock:
  703. up_write(&root->kernfs_rwsem);
  704. return ret;
  705. }
  706. /**
  707. * kernfs_find_ns - find kernfs_node with the given name
  708. * @parent: kernfs_node to search under
  709. * @name: name to look for
  710. * @ns: the namespace tag to use
  711. *
  712. * Look for kernfs_node with name @name under @parent.
  713. *
  714. * Return: pointer to the found kernfs_node on success, %NULL on failure.
  715. */
  716. static struct kernfs_node *kernfs_find_ns(struct kernfs_node *parent,
  717. const unsigned char *name,
  718. const void *ns)
  719. {
  720. struct rb_node *node = parent->dir.children.rb_node;
  721. bool has_ns = kernfs_ns_enabled(parent);
  722. unsigned int hash;
  723. lockdep_assert_held(&kernfs_root(parent)->kernfs_rwsem);
  724. if (has_ns != (bool)ns) {
  725. WARN(1, KERN_WARNING "kernfs: ns %s in '%s' for '%s'\n",
  726. has_ns ? "required" : "invalid", parent->name, name);
  727. return NULL;
  728. }
  729. hash = kernfs_name_hash(name, ns);
  730. while (node) {
  731. struct kernfs_node *kn;
  732. int result;
  733. kn = rb_to_kn(node);
  734. result = kernfs_name_compare(hash, name, ns, kn);
  735. if (result < 0)
  736. node = node->rb_left;
  737. else if (result > 0)
  738. node = node->rb_right;
  739. else
  740. return kn;
  741. }
  742. return NULL;
  743. }
  744. static struct kernfs_node *kernfs_walk_ns(struct kernfs_node *parent,
  745. const unsigned char *path,
  746. const void *ns)
  747. {
  748. ssize_t len;
  749. char *p, *name;
  750. lockdep_assert_held_read(&kernfs_root(parent)->kernfs_rwsem);
  751. spin_lock_irq(&kernfs_pr_cont_lock);
  752. len = strscpy(kernfs_pr_cont_buf, path, sizeof(kernfs_pr_cont_buf));
  753. if (len < 0) {
  754. spin_unlock_irq(&kernfs_pr_cont_lock);
  755. return NULL;
  756. }
  757. p = kernfs_pr_cont_buf;
  758. while ((name = strsep(&p, "/")) && parent) {
  759. if (*name == '\0')
  760. continue;
  761. parent = kernfs_find_ns(parent, name, ns);
  762. }
  763. spin_unlock_irq(&kernfs_pr_cont_lock);
  764. return parent;
  765. }
  766. /**
  767. * kernfs_find_and_get_ns - find and get kernfs_node with the given name
  768. * @parent: kernfs_node to search under
  769. * @name: name to look for
  770. * @ns: the namespace tag to use
  771. *
  772. * Look for kernfs_node with name @name under @parent and get a reference
  773. * if found. This function may sleep.
  774. *
  775. * Return: pointer to the found kernfs_node on success, %NULL on failure.
  776. */
  777. struct kernfs_node *kernfs_find_and_get_ns(struct kernfs_node *parent,
  778. const char *name, const void *ns)
  779. {
  780. struct kernfs_node *kn;
  781. struct kernfs_root *root = kernfs_root(parent);
  782. down_read(&root->kernfs_rwsem);
  783. kn = kernfs_find_ns(parent, name, ns);
  784. kernfs_get(kn);
  785. up_read(&root->kernfs_rwsem);
  786. return kn;
  787. }
  788. EXPORT_SYMBOL_GPL(kernfs_find_and_get_ns);
  789. /**
  790. * kernfs_walk_and_get_ns - find and get kernfs_node with the given path
  791. * @parent: kernfs_node to search under
  792. * @path: path to look for
  793. * @ns: the namespace tag to use
  794. *
  795. * Look for kernfs_node with path @path under @parent and get a reference
  796. * if found. This function may sleep.
  797. *
  798. * Return: pointer to the found kernfs_node on success, %NULL on failure.
  799. */
  800. struct kernfs_node *kernfs_walk_and_get_ns(struct kernfs_node *parent,
  801. const char *path, const void *ns)
  802. {
  803. struct kernfs_node *kn;
  804. struct kernfs_root *root = kernfs_root(parent);
  805. down_read(&root->kernfs_rwsem);
  806. kn = kernfs_walk_ns(parent, path, ns);
  807. kernfs_get(kn);
  808. up_read(&root->kernfs_rwsem);
  809. return kn;
  810. }
  811. /**
  812. * kernfs_create_root - create a new kernfs hierarchy
  813. * @scops: optional syscall operations for the hierarchy
  814. * @flags: KERNFS_ROOT_* flags
  815. * @priv: opaque data associated with the new directory
  816. *
  817. * Return: the root of the new hierarchy on success, ERR_PTR() value on
  818. * failure.
  819. */
  820. struct kernfs_root *kernfs_create_root(struct kernfs_syscall_ops *scops,
  821. unsigned int flags, void *priv)
  822. {
  823. struct kernfs_root *root;
  824. struct kernfs_node *kn;
  825. root = kzalloc(sizeof(*root), GFP_KERNEL);
  826. if (!root)
  827. return ERR_PTR(-ENOMEM);
  828. idr_init(&root->ino_idr);
  829. init_rwsem(&root->kernfs_rwsem);
  830. init_rwsem(&root->kernfs_iattr_rwsem);
  831. init_rwsem(&root->kernfs_supers_rwsem);
  832. INIT_LIST_HEAD(&root->supers);
  833. /*
  834. * On 64bit ino setups, id is ino. On 32bit, low 32bits are ino.
  835. * High bits generation. The starting value for both ino and
  836. * genenration is 1. Initialize upper 32bit allocation
  837. * accordingly.
  838. */
  839. if (sizeof(ino_t) >= sizeof(u64))
  840. root->id_highbits = 0;
  841. else
  842. root->id_highbits = 1;
  843. kn = __kernfs_new_node(root, NULL, "", S_IFDIR | S_IRUGO | S_IXUGO,
  844. GLOBAL_ROOT_UID, GLOBAL_ROOT_GID,
  845. KERNFS_DIR);
  846. if (!kn) {
  847. idr_destroy(&root->ino_idr);
  848. kfree(root);
  849. return ERR_PTR(-ENOMEM);
  850. }
  851. kn->priv = priv;
  852. kn->dir.root = root;
  853. root->syscall_ops = scops;
  854. root->flags = flags;
  855. root->kn = kn;
  856. init_waitqueue_head(&root->deactivate_waitq);
  857. if (!(root->flags & KERNFS_ROOT_CREATE_DEACTIVATED))
  858. kernfs_activate(kn);
  859. return root;
  860. }
  861. /**
  862. * kernfs_destroy_root - destroy a kernfs hierarchy
  863. * @root: root of the hierarchy to destroy
  864. *
  865. * Destroy the hierarchy anchored at @root by removing all existing
  866. * directories and destroying @root.
  867. */
  868. void kernfs_destroy_root(struct kernfs_root *root)
  869. {
  870. /*
  871. * kernfs_remove holds kernfs_rwsem from the root so the root
  872. * shouldn't be freed during the operation.
  873. */
  874. kernfs_get(root->kn);
  875. kernfs_remove(root->kn);
  876. kernfs_put(root->kn); /* will also free @root */
  877. }
  878. /**
  879. * kernfs_root_to_node - return the kernfs_node associated with a kernfs_root
  880. * @root: root to use to lookup
  881. *
  882. * Return: @root's kernfs_node
  883. */
  884. struct kernfs_node *kernfs_root_to_node(struct kernfs_root *root)
  885. {
  886. return root->kn;
  887. }
  888. /**
  889. * kernfs_create_dir_ns - create a directory
  890. * @parent: parent in which to create a new directory
  891. * @name: name of the new directory
  892. * @mode: mode of the new directory
  893. * @uid: uid of the new directory
  894. * @gid: gid of the new directory
  895. * @priv: opaque data associated with the new directory
  896. * @ns: optional namespace tag of the directory
  897. *
  898. * Return: the created node on success, ERR_PTR() value on failure.
  899. */
  900. struct kernfs_node *kernfs_create_dir_ns(struct kernfs_node *parent,
  901. const char *name, umode_t mode,
  902. kuid_t uid, kgid_t gid,
  903. void *priv, const void *ns)
  904. {
  905. struct kernfs_node *kn;
  906. int rc;
  907. /* allocate */
  908. kn = kernfs_new_node(parent, name, mode | S_IFDIR,
  909. uid, gid, KERNFS_DIR);
  910. if (!kn)
  911. return ERR_PTR(-ENOMEM);
  912. kn->dir.root = parent->dir.root;
  913. kn->ns = ns;
  914. kn->priv = priv;
  915. /* link in */
  916. rc = kernfs_add_one(kn);
  917. if (!rc)
  918. return kn;
  919. kernfs_put(kn);
  920. return ERR_PTR(rc);
  921. }
  922. /**
  923. * kernfs_create_empty_dir - create an always empty directory
  924. * @parent: parent in which to create a new directory
  925. * @name: name of the new directory
  926. *
  927. * Return: the created node on success, ERR_PTR() value on failure.
  928. */
  929. struct kernfs_node *kernfs_create_empty_dir(struct kernfs_node *parent,
  930. const char *name)
  931. {
  932. struct kernfs_node *kn;
  933. int rc;
  934. /* allocate */
  935. kn = kernfs_new_node(parent, name, S_IRUGO|S_IXUGO|S_IFDIR,
  936. GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, KERNFS_DIR);
  937. if (!kn)
  938. return ERR_PTR(-ENOMEM);
  939. kn->flags |= KERNFS_EMPTY_DIR;
  940. kn->dir.root = parent->dir.root;
  941. kn->ns = NULL;
  942. kn->priv = NULL;
  943. /* link in */
  944. rc = kernfs_add_one(kn);
  945. if (!rc)
  946. return kn;
  947. kernfs_put(kn);
  948. return ERR_PTR(rc);
  949. }
  950. static int kernfs_dop_revalidate(struct dentry *dentry, unsigned int flags)
  951. {
  952. struct kernfs_node *kn;
  953. struct kernfs_root *root;
  954. if (flags & LOOKUP_RCU)
  955. return -ECHILD;
  956. /* Negative hashed dentry? */
  957. if (d_really_is_negative(dentry)) {
  958. struct kernfs_node *parent;
  959. /* If the kernfs parent node has changed discard and
  960. * proceed to ->lookup.
  961. *
  962. * There's nothing special needed here when getting the
  963. * dentry parent, even if a concurrent rename is in
  964. * progress. That's because the dentry is negative so
  965. * it can only be the target of the rename and it will
  966. * be doing a d_move() not a replace. Consequently the
  967. * dentry d_parent won't change over the d_move().
  968. *
  969. * Also kernfs negative dentries transitioning from
  970. * negative to positive during revalidate won't happen
  971. * because they are invalidated on containing directory
  972. * changes and the lookup re-done so that a new positive
  973. * dentry can be properly created.
  974. */
  975. root = kernfs_root_from_sb(dentry->d_sb);
  976. down_read(&root->kernfs_rwsem);
  977. parent = kernfs_dentry_node(dentry->d_parent);
  978. if (parent) {
  979. if (kernfs_dir_changed(parent, dentry)) {
  980. up_read(&root->kernfs_rwsem);
  981. return 0;
  982. }
  983. }
  984. up_read(&root->kernfs_rwsem);
  985. /* The kernfs parent node hasn't changed, leave the
  986. * dentry negative and return success.
  987. */
  988. return 1;
  989. }
  990. kn = kernfs_dentry_node(dentry);
  991. root = kernfs_root(kn);
  992. down_read(&root->kernfs_rwsem);
  993. /* The kernfs node has been deactivated */
  994. if (!kernfs_active(kn))
  995. goto out_bad;
  996. /* The kernfs node has been moved? */
  997. if (kernfs_dentry_node(dentry->d_parent) != kn->parent)
  998. goto out_bad;
  999. /* The kernfs node has been renamed */
  1000. if (strcmp(dentry->d_name.name, kn->name) != 0)
  1001. goto out_bad;
  1002. /* The kernfs node has been moved to a different namespace */
  1003. if (kn->parent && kernfs_ns_enabled(kn->parent) &&
  1004. kernfs_info(dentry->d_sb)->ns != kn->ns)
  1005. goto out_bad;
  1006. up_read(&root->kernfs_rwsem);
  1007. return 1;
  1008. out_bad:
  1009. up_read(&root->kernfs_rwsem);
  1010. return 0;
  1011. }
  1012. const struct dentry_operations kernfs_dops = {
  1013. .d_revalidate = kernfs_dop_revalidate,
  1014. };
  1015. static struct dentry *kernfs_iop_lookup(struct inode *dir,
  1016. struct dentry *dentry,
  1017. unsigned int flags)
  1018. {
  1019. struct kernfs_node *parent = dir->i_private;
  1020. struct kernfs_node *kn;
  1021. struct kernfs_root *root;
  1022. struct inode *inode = NULL;
  1023. const void *ns = NULL;
  1024. root = kernfs_root(parent);
  1025. down_read(&root->kernfs_rwsem);
  1026. if (kernfs_ns_enabled(parent))
  1027. ns = kernfs_info(dir->i_sb)->ns;
  1028. kn = kernfs_find_ns(parent, dentry->d_name.name, ns);
  1029. /* attach dentry and inode */
  1030. if (kn) {
  1031. /* Inactive nodes are invisible to the VFS so don't
  1032. * create a negative.
  1033. */
  1034. if (!kernfs_active(kn)) {
  1035. up_read(&root->kernfs_rwsem);
  1036. return NULL;
  1037. }
  1038. inode = kernfs_get_inode(dir->i_sb, kn);
  1039. if (!inode)
  1040. inode = ERR_PTR(-ENOMEM);
  1041. }
  1042. /*
  1043. * Needed for negative dentry validation.
  1044. * The negative dentry can be created in kernfs_iop_lookup()
  1045. * or transforms from positive dentry in dentry_unlink_inode()
  1046. * called from vfs_rmdir().
  1047. */
  1048. if (!IS_ERR(inode))
  1049. kernfs_set_rev(parent, dentry);
  1050. up_read(&root->kernfs_rwsem);
  1051. /* instantiate and hash (possibly negative) dentry */
  1052. return d_splice_alias(inode, dentry);
  1053. }
  1054. static int kernfs_iop_mkdir(struct mnt_idmap *idmap,
  1055. struct inode *dir, struct dentry *dentry,
  1056. umode_t mode)
  1057. {
  1058. struct kernfs_node *parent = dir->i_private;
  1059. struct kernfs_syscall_ops *scops = kernfs_root(parent)->syscall_ops;
  1060. int ret;
  1061. if (!scops || !scops->mkdir)
  1062. return -EPERM;
  1063. if (!kernfs_get_active(parent))
  1064. return -ENODEV;
  1065. ret = scops->mkdir(parent, dentry->d_name.name, mode);
  1066. kernfs_put_active(parent);
  1067. return ret;
  1068. }
  1069. static int kernfs_iop_rmdir(struct inode *dir, struct dentry *dentry)
  1070. {
  1071. struct kernfs_node *kn = kernfs_dentry_node(dentry);
  1072. struct kernfs_syscall_ops *scops = kernfs_root(kn)->syscall_ops;
  1073. int ret;
  1074. if (!scops || !scops->rmdir)
  1075. return -EPERM;
  1076. if (!kernfs_get_active(kn))
  1077. return -ENODEV;
  1078. ret = scops->rmdir(kn);
  1079. kernfs_put_active(kn);
  1080. return ret;
  1081. }
  1082. static int kernfs_iop_rename(struct mnt_idmap *idmap,
  1083. struct inode *old_dir, struct dentry *old_dentry,
  1084. struct inode *new_dir, struct dentry *new_dentry,
  1085. unsigned int flags)
  1086. {
  1087. struct kernfs_node *kn = kernfs_dentry_node(old_dentry);
  1088. struct kernfs_node *new_parent = new_dir->i_private;
  1089. struct kernfs_syscall_ops *scops = kernfs_root(kn)->syscall_ops;
  1090. int ret;
  1091. if (flags)
  1092. return -EINVAL;
  1093. if (!scops || !scops->rename)
  1094. return -EPERM;
  1095. if (!kernfs_get_active(kn))
  1096. return -ENODEV;
  1097. if (!kernfs_get_active(new_parent)) {
  1098. kernfs_put_active(kn);
  1099. return -ENODEV;
  1100. }
  1101. ret = scops->rename(kn, new_parent, new_dentry->d_name.name);
  1102. kernfs_put_active(new_parent);
  1103. kernfs_put_active(kn);
  1104. return ret;
  1105. }
  1106. const struct inode_operations kernfs_dir_iops = {
  1107. .lookup = kernfs_iop_lookup,
  1108. .permission = kernfs_iop_permission,
  1109. .setattr = kernfs_iop_setattr,
  1110. .getattr = kernfs_iop_getattr,
  1111. .listxattr = kernfs_iop_listxattr,
  1112. .mkdir = kernfs_iop_mkdir,
  1113. .rmdir = kernfs_iop_rmdir,
  1114. .rename = kernfs_iop_rename,
  1115. };
  1116. static struct kernfs_node *kernfs_leftmost_descendant(struct kernfs_node *pos)
  1117. {
  1118. struct kernfs_node *last;
  1119. while (true) {
  1120. struct rb_node *rbn;
  1121. last = pos;
  1122. if (kernfs_type(pos) != KERNFS_DIR)
  1123. break;
  1124. rbn = rb_first(&pos->dir.children);
  1125. if (!rbn)
  1126. break;
  1127. pos = rb_to_kn(rbn);
  1128. }
  1129. return last;
  1130. }
  1131. /**
  1132. * kernfs_next_descendant_post - find the next descendant for post-order walk
  1133. * @pos: the current position (%NULL to initiate traversal)
  1134. * @root: kernfs_node whose descendants to walk
  1135. *
  1136. * Find the next descendant to visit for post-order traversal of @root's
  1137. * descendants. @root is included in the iteration and the last node to be
  1138. * visited.
  1139. *
  1140. * Return: the next descendant to visit or %NULL when done.
  1141. */
  1142. static struct kernfs_node *kernfs_next_descendant_post(struct kernfs_node *pos,
  1143. struct kernfs_node *root)
  1144. {
  1145. struct rb_node *rbn;
  1146. lockdep_assert_held_write(&kernfs_root(root)->kernfs_rwsem);
  1147. /* if first iteration, visit leftmost descendant which may be root */
  1148. if (!pos)
  1149. return kernfs_leftmost_descendant(root);
  1150. /* if we visited @root, we're done */
  1151. if (pos == root)
  1152. return NULL;
  1153. /* if there's an unvisited sibling, visit its leftmost descendant */
  1154. rbn = rb_next(&pos->rb);
  1155. if (rbn)
  1156. return kernfs_leftmost_descendant(rb_to_kn(rbn));
  1157. /* no sibling left, visit parent */
  1158. return pos->parent;
  1159. }
  1160. static void kernfs_activate_one(struct kernfs_node *kn)
  1161. {
  1162. lockdep_assert_held_write(&kernfs_root(kn)->kernfs_rwsem);
  1163. kn->flags |= KERNFS_ACTIVATED;
  1164. if (kernfs_active(kn) || (kn->flags & (KERNFS_HIDDEN | KERNFS_REMOVING)))
  1165. return;
  1166. WARN_ON_ONCE(kn->parent && RB_EMPTY_NODE(&kn->rb));
  1167. WARN_ON_ONCE(atomic_read(&kn->active) != KN_DEACTIVATED_BIAS);
  1168. atomic_sub(KN_DEACTIVATED_BIAS, &kn->active);
  1169. }
  1170. /**
  1171. * kernfs_activate - activate a node which started deactivated
  1172. * @kn: kernfs_node whose subtree is to be activated
  1173. *
  1174. * If the root has KERNFS_ROOT_CREATE_DEACTIVATED set, a newly created node
  1175. * needs to be explicitly activated. A node which hasn't been activated
  1176. * isn't visible to userland and deactivation is skipped during its
  1177. * removal. This is useful to construct atomic init sequences where
  1178. * creation of multiple nodes should either succeed or fail atomically.
  1179. *
  1180. * The caller is responsible for ensuring that this function is not called
  1181. * after kernfs_remove*() is invoked on @kn.
  1182. */
  1183. void kernfs_activate(struct kernfs_node *kn)
  1184. {
  1185. struct kernfs_node *pos;
  1186. struct kernfs_root *root = kernfs_root(kn);
  1187. down_write(&root->kernfs_rwsem);
  1188. pos = NULL;
  1189. while ((pos = kernfs_next_descendant_post(pos, kn)))
  1190. kernfs_activate_one(pos);
  1191. up_write(&root->kernfs_rwsem);
  1192. }
  1193. /**
  1194. * kernfs_show - show or hide a node
  1195. * @kn: kernfs_node to show or hide
  1196. * @show: whether to show or hide
  1197. *
  1198. * If @show is %false, @kn is marked hidden and deactivated. A hidden node is
  1199. * ignored in future activaitons. If %true, the mark is removed and activation
  1200. * state is restored. This function won't implicitly activate a new node in a
  1201. * %KERNFS_ROOT_CREATE_DEACTIVATED root which hasn't been activated yet.
  1202. *
  1203. * To avoid recursion complexities, directories aren't supported for now.
  1204. */
  1205. void kernfs_show(struct kernfs_node *kn, bool show)
  1206. {
  1207. struct kernfs_root *root = kernfs_root(kn);
  1208. if (WARN_ON_ONCE(kernfs_type(kn) == KERNFS_DIR))
  1209. return;
  1210. down_write(&root->kernfs_rwsem);
  1211. if (show) {
  1212. kn->flags &= ~KERNFS_HIDDEN;
  1213. if (kn->flags & KERNFS_ACTIVATED)
  1214. kernfs_activate_one(kn);
  1215. } else {
  1216. kn->flags |= KERNFS_HIDDEN;
  1217. if (kernfs_active(kn))
  1218. atomic_add(KN_DEACTIVATED_BIAS, &kn->active);
  1219. kernfs_drain(kn);
  1220. }
  1221. up_write(&root->kernfs_rwsem);
  1222. }
  1223. static void __kernfs_remove(struct kernfs_node *kn)
  1224. {
  1225. struct kernfs_node *pos;
  1226. /* Short-circuit if non-root @kn has already finished removal. */
  1227. if (!kn)
  1228. return;
  1229. lockdep_assert_held_write(&kernfs_root(kn)->kernfs_rwsem);
  1230. /*
  1231. * This is for kernfs_remove_self() which plays with active ref
  1232. * after removal.
  1233. */
  1234. if (kn->parent && RB_EMPTY_NODE(&kn->rb))
  1235. return;
  1236. pr_debug("kernfs %s: removing\n", kn->name);
  1237. /* prevent new usage by marking all nodes removing and deactivating */
  1238. pos = NULL;
  1239. while ((pos = kernfs_next_descendant_post(pos, kn))) {
  1240. pos->flags |= KERNFS_REMOVING;
  1241. if (kernfs_active(pos))
  1242. atomic_add(KN_DEACTIVATED_BIAS, &pos->active);
  1243. }
  1244. /* deactivate and unlink the subtree node-by-node */
  1245. do {
  1246. pos = kernfs_leftmost_descendant(kn);
  1247. /*
  1248. * kernfs_drain() may drop kernfs_rwsem temporarily and @pos's
  1249. * base ref could have been put by someone else by the time
  1250. * the function returns. Make sure it doesn't go away
  1251. * underneath us.
  1252. */
  1253. kernfs_get(pos);
  1254. kernfs_drain(pos);
  1255. /*
  1256. * kernfs_unlink_sibling() succeeds once per node. Use it
  1257. * to decide who's responsible for cleanups.
  1258. */
  1259. if (!pos->parent || kernfs_unlink_sibling(pos)) {
  1260. struct kernfs_iattrs *ps_iattr =
  1261. pos->parent ? pos->parent->iattr : NULL;
  1262. /* update timestamps on the parent */
  1263. down_write(&kernfs_root(kn)->kernfs_iattr_rwsem);
  1264. if (ps_iattr) {
  1265. ktime_get_real_ts64(&ps_iattr->ia_ctime);
  1266. ps_iattr->ia_mtime = ps_iattr->ia_ctime;
  1267. }
  1268. up_write(&kernfs_root(kn)->kernfs_iattr_rwsem);
  1269. kernfs_put(pos);
  1270. }
  1271. kernfs_put(pos);
  1272. } while (pos != kn);
  1273. }
  1274. /**
  1275. * kernfs_remove - remove a kernfs_node recursively
  1276. * @kn: the kernfs_node to remove
  1277. *
  1278. * Remove @kn along with all its subdirectories and files.
  1279. */
  1280. void kernfs_remove(struct kernfs_node *kn)
  1281. {
  1282. struct kernfs_root *root;
  1283. if (!kn)
  1284. return;
  1285. root = kernfs_root(kn);
  1286. down_write(&root->kernfs_rwsem);
  1287. __kernfs_remove(kn);
  1288. up_write(&root->kernfs_rwsem);
  1289. }
  1290. /**
  1291. * kernfs_break_active_protection - break out of active protection
  1292. * @kn: the self kernfs_node
  1293. *
  1294. * The caller must be running off of a kernfs operation which is invoked
  1295. * with an active reference - e.g. one of kernfs_ops. Each invocation of
  1296. * this function must also be matched with an invocation of
  1297. * kernfs_unbreak_active_protection().
  1298. *
  1299. * This function releases the active reference of @kn the caller is
  1300. * holding. Once this function is called, @kn may be removed at any point
  1301. * and the caller is solely responsible for ensuring that the objects it
  1302. * dereferences are accessible.
  1303. */
  1304. void kernfs_break_active_protection(struct kernfs_node *kn)
  1305. {
  1306. /*
  1307. * Take out ourself out of the active ref dependency chain. If
  1308. * we're called without an active ref, lockdep will complain.
  1309. */
  1310. kernfs_put_active(kn);
  1311. }
  1312. /**
  1313. * kernfs_unbreak_active_protection - undo kernfs_break_active_protection()
  1314. * @kn: the self kernfs_node
  1315. *
  1316. * If kernfs_break_active_protection() was called, this function must be
  1317. * invoked before finishing the kernfs operation. Note that while this
  1318. * function restores the active reference, it doesn't and can't actually
  1319. * restore the active protection - @kn may already or be in the process of
  1320. * being drained and removed. Once kernfs_break_active_protection() is
  1321. * invoked, that protection is irreversibly gone for the kernfs operation
  1322. * instance.
  1323. *
  1324. * While this function may be called at any point after
  1325. * kernfs_break_active_protection() is invoked, its most useful location
  1326. * would be right before the enclosing kernfs operation returns.
  1327. */
  1328. void kernfs_unbreak_active_protection(struct kernfs_node *kn)
  1329. {
  1330. /*
  1331. * @kn->active could be in any state; however, the increment we do
  1332. * here will be undone as soon as the enclosing kernfs operation
  1333. * finishes and this temporary bump can't break anything. If @kn
  1334. * is alive, nothing changes. If @kn is being deactivated, the
  1335. * soon-to-follow put will either finish deactivation or restore
  1336. * deactivated state. If @kn is already removed, the temporary
  1337. * bump is guaranteed to be gone before @kn is released.
  1338. */
  1339. atomic_inc(&kn->active);
  1340. if (kernfs_lockdep(kn))
  1341. rwsem_acquire(&kn->dep_map, 0, 1, _RET_IP_);
  1342. }
  1343. /**
  1344. * kernfs_remove_self - remove a kernfs_node from its own method
  1345. * @kn: the self kernfs_node to remove
  1346. *
  1347. * The caller must be running off of a kernfs operation which is invoked
  1348. * with an active reference - e.g. one of kernfs_ops. This can be used to
  1349. * implement a file operation which deletes itself.
  1350. *
  1351. * For example, the "delete" file for a sysfs device directory can be
  1352. * implemented by invoking kernfs_remove_self() on the "delete" file
  1353. * itself. This function breaks the circular dependency of trying to
  1354. * deactivate self while holding an active ref itself. It isn't necessary
  1355. * to modify the usual removal path to use kernfs_remove_self(). The
  1356. * "delete" implementation can simply invoke kernfs_remove_self() on self
  1357. * before proceeding with the usual removal path. kernfs will ignore later
  1358. * kernfs_remove() on self.
  1359. *
  1360. * kernfs_remove_self() can be called multiple times concurrently on the
  1361. * same kernfs_node. Only the first one actually performs removal and
  1362. * returns %true. All others will wait until the kernfs operation which
  1363. * won self-removal finishes and return %false. Note that the losers wait
  1364. * for the completion of not only the winning kernfs_remove_self() but also
  1365. * the whole kernfs_ops which won the arbitration. This can be used to
  1366. * guarantee, for example, all concurrent writes to a "delete" file to
  1367. * finish only after the whole operation is complete.
  1368. *
  1369. * Return: %true if @kn is removed by this call, otherwise %false.
  1370. */
  1371. bool kernfs_remove_self(struct kernfs_node *kn)
  1372. {
  1373. bool ret;
  1374. struct kernfs_root *root = kernfs_root(kn);
  1375. down_write(&root->kernfs_rwsem);
  1376. kernfs_break_active_protection(kn);
  1377. /*
  1378. * SUICIDAL is used to arbitrate among competing invocations. Only
  1379. * the first one will actually perform removal. When the removal
  1380. * is complete, SUICIDED is set and the active ref is restored
  1381. * while kernfs_rwsem for held exclusive. The ones which lost
  1382. * arbitration waits for SUICIDED && drained which can happen only
  1383. * after the enclosing kernfs operation which executed the winning
  1384. * instance of kernfs_remove_self() finished.
  1385. */
  1386. if (!(kn->flags & KERNFS_SUICIDAL)) {
  1387. kn->flags |= KERNFS_SUICIDAL;
  1388. __kernfs_remove(kn);
  1389. kn->flags |= KERNFS_SUICIDED;
  1390. ret = true;
  1391. } else {
  1392. wait_queue_head_t *waitq = &kernfs_root(kn)->deactivate_waitq;
  1393. DEFINE_WAIT(wait);
  1394. while (true) {
  1395. prepare_to_wait(waitq, &wait, TASK_UNINTERRUPTIBLE);
  1396. if ((kn->flags & KERNFS_SUICIDED) &&
  1397. atomic_read(&kn->active) == KN_DEACTIVATED_BIAS)
  1398. break;
  1399. up_write(&root->kernfs_rwsem);
  1400. schedule();
  1401. down_write(&root->kernfs_rwsem);
  1402. }
  1403. finish_wait(waitq, &wait);
  1404. WARN_ON_ONCE(!RB_EMPTY_NODE(&kn->rb));
  1405. ret = false;
  1406. }
  1407. /*
  1408. * This must be done while kernfs_rwsem held exclusive; otherwise,
  1409. * waiting for SUICIDED && deactivated could finish prematurely.
  1410. */
  1411. kernfs_unbreak_active_protection(kn);
  1412. up_write(&root->kernfs_rwsem);
  1413. return ret;
  1414. }
  1415. /**
  1416. * kernfs_remove_by_name_ns - find a kernfs_node by name and remove it
  1417. * @parent: parent of the target
  1418. * @name: name of the kernfs_node to remove
  1419. * @ns: namespace tag of the kernfs_node to remove
  1420. *
  1421. * Look for the kernfs_node with @name and @ns under @parent and remove it.
  1422. *
  1423. * Return: %0 on success, -ENOENT if such entry doesn't exist.
  1424. */
  1425. int kernfs_remove_by_name_ns(struct kernfs_node *parent, const char *name,
  1426. const void *ns)
  1427. {
  1428. struct kernfs_node *kn;
  1429. struct kernfs_root *root;
  1430. if (!parent) {
  1431. WARN(1, KERN_WARNING "kernfs: can not remove '%s', no directory\n",
  1432. name);
  1433. return -ENOENT;
  1434. }
  1435. root = kernfs_root(parent);
  1436. down_write(&root->kernfs_rwsem);
  1437. kn = kernfs_find_ns(parent, name, ns);
  1438. if (kn) {
  1439. kernfs_get(kn);
  1440. __kernfs_remove(kn);
  1441. kernfs_put(kn);
  1442. }
  1443. up_write(&root->kernfs_rwsem);
  1444. if (kn)
  1445. return 0;
  1446. else
  1447. return -ENOENT;
  1448. }
  1449. /**
  1450. * kernfs_rename_ns - move and rename a kernfs_node
  1451. * @kn: target node
  1452. * @new_parent: new parent to put @sd under
  1453. * @new_name: new name
  1454. * @new_ns: new namespace tag
  1455. *
  1456. * Return: %0 on success, -errno on failure.
  1457. */
  1458. int kernfs_rename_ns(struct kernfs_node *kn, struct kernfs_node *new_parent,
  1459. const char *new_name, const void *new_ns)
  1460. {
  1461. struct kernfs_node *old_parent;
  1462. struct kernfs_root *root;
  1463. const char *old_name = NULL;
  1464. int error;
  1465. /* can't move or rename root */
  1466. if (!kn->parent)
  1467. return -EINVAL;
  1468. root = kernfs_root(kn);
  1469. down_write(&root->kernfs_rwsem);
  1470. error = -ENOENT;
  1471. if (!kernfs_active(kn) || !kernfs_active(new_parent) ||
  1472. (new_parent->flags & KERNFS_EMPTY_DIR))
  1473. goto out;
  1474. error = 0;
  1475. if ((kn->parent == new_parent) && (kn->ns == new_ns) &&
  1476. (strcmp(kn->name, new_name) == 0))
  1477. goto out; /* nothing to rename */
  1478. error = -EEXIST;
  1479. if (kernfs_find_ns(new_parent, new_name, new_ns))
  1480. goto out;
  1481. /* rename kernfs_node */
  1482. if (strcmp(kn->name, new_name) != 0) {
  1483. error = -ENOMEM;
  1484. new_name = kstrdup_const(new_name, GFP_KERNEL);
  1485. if (!new_name)
  1486. goto out;
  1487. } else {
  1488. new_name = NULL;
  1489. }
  1490. /*
  1491. * Move to the appropriate place in the appropriate directories rbtree.
  1492. */
  1493. kernfs_unlink_sibling(kn);
  1494. kernfs_get(new_parent);
  1495. /* rename_lock protects ->parent and ->name accessors */
  1496. write_lock_irq(&kernfs_rename_lock);
  1497. old_parent = kn->parent;
  1498. kn->parent = new_parent;
  1499. kn->ns = new_ns;
  1500. if (new_name) {
  1501. old_name = kn->name;
  1502. kn->name = new_name;
  1503. }
  1504. write_unlock_irq(&kernfs_rename_lock);
  1505. kn->hash = kernfs_name_hash(kn->name, kn->ns);
  1506. kernfs_link_sibling(kn);
  1507. kernfs_put(old_parent);
  1508. kfree_const(old_name);
  1509. error = 0;
  1510. out:
  1511. up_write(&root->kernfs_rwsem);
  1512. return error;
  1513. }
  1514. static int kernfs_dir_fop_release(struct inode *inode, struct file *filp)
  1515. {
  1516. kernfs_put(filp->private_data);
  1517. return 0;
  1518. }
  1519. static struct kernfs_node *kernfs_dir_pos(const void *ns,
  1520. struct kernfs_node *parent, loff_t hash, struct kernfs_node *pos)
  1521. {
  1522. if (pos) {
  1523. int valid = kernfs_active(pos) &&
  1524. pos->parent == parent && hash == pos->hash;
  1525. kernfs_put(pos);
  1526. if (!valid)
  1527. pos = NULL;
  1528. }
  1529. if (!pos && (hash > 1) && (hash < INT_MAX)) {
  1530. struct rb_node *node = parent->dir.children.rb_node;
  1531. while (node) {
  1532. pos = rb_to_kn(node);
  1533. if (hash < pos->hash)
  1534. node = node->rb_left;
  1535. else if (hash > pos->hash)
  1536. node = node->rb_right;
  1537. else
  1538. break;
  1539. }
  1540. }
  1541. /* Skip over entries which are dying/dead or in the wrong namespace */
  1542. while (pos && (!kernfs_active(pos) || pos->ns != ns)) {
  1543. struct rb_node *node = rb_next(&pos->rb);
  1544. if (!node)
  1545. pos = NULL;
  1546. else
  1547. pos = rb_to_kn(node);
  1548. }
  1549. return pos;
  1550. }
  1551. static struct kernfs_node *kernfs_dir_next_pos(const void *ns,
  1552. struct kernfs_node *parent, ino_t ino, struct kernfs_node *pos)
  1553. {
  1554. pos = kernfs_dir_pos(ns, parent, ino, pos);
  1555. if (pos) {
  1556. do {
  1557. struct rb_node *node = rb_next(&pos->rb);
  1558. if (!node)
  1559. pos = NULL;
  1560. else
  1561. pos = rb_to_kn(node);
  1562. } while (pos && (!kernfs_active(pos) || pos->ns != ns));
  1563. }
  1564. return pos;
  1565. }
  1566. static int kernfs_fop_readdir(struct file *file, struct dir_context *ctx)
  1567. {
  1568. struct dentry *dentry = file->f_path.dentry;
  1569. struct kernfs_node *parent = kernfs_dentry_node(dentry);
  1570. struct kernfs_node *pos = file->private_data;
  1571. struct kernfs_root *root;
  1572. const void *ns = NULL;
  1573. if (!dir_emit_dots(file, ctx))
  1574. return 0;
  1575. root = kernfs_root(parent);
  1576. down_read(&root->kernfs_rwsem);
  1577. if (kernfs_ns_enabled(parent))
  1578. ns = kernfs_info(dentry->d_sb)->ns;
  1579. for (pos = kernfs_dir_pos(ns, parent, ctx->pos, pos);
  1580. pos;
  1581. pos = kernfs_dir_next_pos(ns, parent, ctx->pos, pos)) {
  1582. const char *name = pos->name;
  1583. unsigned int type = fs_umode_to_dtype(pos->mode);
  1584. int len = strlen(name);
  1585. ino_t ino = kernfs_ino(pos);
  1586. ctx->pos = pos->hash;
  1587. file->private_data = pos;
  1588. kernfs_get(pos);
  1589. up_read(&root->kernfs_rwsem);
  1590. if (!dir_emit(ctx, name, len, ino, type))
  1591. return 0;
  1592. down_read(&root->kernfs_rwsem);
  1593. }
  1594. up_read(&root->kernfs_rwsem);
  1595. file->private_data = NULL;
  1596. ctx->pos = INT_MAX;
  1597. return 0;
  1598. }
  1599. const struct file_operations kernfs_dir_fops = {
  1600. .read = generic_read_dir,
  1601. .iterate_shared = kernfs_fop_readdir,
  1602. .release = kernfs_dir_fop_release,
  1603. .llseek = generic_file_llseek,
  1604. };