dir.c 43 KB

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