hammer2 - pfsmount -> clustermount separation part 1
[dragonfly.git] / sys / vfs / hammer2 / hammer2_inode.c
1 /*
2  * Copyright (c) 2011-2013 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@dragonflybsd.org>
6  * by Venkatesh Srinivas <vsrinivas@dragonflybsd.org>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  * 3. Neither the name of The DragonFly Project nor the names of its
19  *    contributors may be used to endorse or promote products derived
20  *    from this software without specific, prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
26  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
28  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
30  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 #include <sys/cdefs.h>
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/types.h>
39 #include <sys/lock.h>
40 #include <sys/uuid.h>
41
42 #include "hammer2.h"
43
44 RB_GENERATE2(hammer2_inode_tree, hammer2_inode, rbnode, hammer2_inode_cmp,
45              hammer2_tid_t, inum);
46
47 int
48 hammer2_inode_cmp(hammer2_inode_t *ip1, hammer2_inode_t *ip2)
49 {
50         if (ip1->inum < ip2->inum)
51                 return(-1);
52         if (ip1->inum > ip2->inum)
53                 return(1);
54         return(0);
55 }
56
57 /*
58  * HAMMER2 inode locks
59  *
60  * HAMMER2 offers shared locks and exclusive locks on inodes.
61  *
62  * An inode's ip->chain pointer is resolved and stable while an inode is
63  * locked, and can be cleaned out at any time (become NULL) when an inode
64  * is not locked.
65  *
66  * The underlying chain is also locked and returned.
67  *
68  * NOTE: We don't combine the inode/chain lock because putting away an
69  *       inode would otherwise confuse multiple lock holders of the inode.
70  */
71 hammer2_chain_t *
72 hammer2_inode_lock_ex(hammer2_inode_t *ip)
73 {
74         hammer2_chain_t *chain;
75
76         hammer2_inode_ref(ip);
77         ccms_thread_lock(&ip->topo_cst, CCMS_STATE_EXCLUSIVE);
78
79         /*
80          * ip->chain fixup.  Certain duplications used to move inodes
81          * into indirect blocks (for example) can cause ip->chain to
82          * become stale.
83          */
84 again:
85         chain = ip->chain;
86         if (hammer2_chain_refactor_test(chain, 1)) {
87                 spin_lock(&chain->core->cst.spin);
88                 while (hammer2_chain_refactor_test(chain, 1))
89                         chain = chain->next_parent;
90                 if (ip->chain != chain) {
91                         hammer2_chain_ref(chain);
92                         spin_unlock(&chain->core->cst.spin);
93                         hammer2_inode_repoint(ip, NULL, chain);
94                         hammer2_chain_drop(chain);
95                 } else {
96                         spin_unlock(&chain->core->cst.spin);
97                 }
98         }
99
100         KKASSERT(chain != NULL);        /* for now */
101         hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
102
103         /*
104          * Resolve duplication races
105          */
106         if (hammer2_chain_refactor_test(chain, 1)) {
107                 hammer2_chain_unlock(chain);
108                 goto again;
109         }
110         return (chain);
111 }
112
113 void
114 hammer2_inode_unlock_ex(hammer2_inode_t *ip, hammer2_chain_t *chain)
115 {
116         /*
117          * XXX this will catch parent directories too which we don't
118          *     really want.
119          */
120         if (chain)
121                 hammer2_chain_unlock(chain);
122         ccms_thread_unlock(&ip->topo_cst);
123         hammer2_inode_drop(ip);
124 }
125
126 /*
127  * NOTE: We don't combine the inode/chain lock because putting away an
128  *       inode would otherwise confuse multiple lock holders of the inode.
129  *
130  *       Shared locks are especially sensitive to having too many shared
131  *       lock counts (from the same thread) on certain paths which might
132  *       need to upgrade them.  Only one count of a shared lock can be
133  *       upgraded.
134  */
135 hammer2_chain_t *
136 hammer2_inode_lock_sh(hammer2_inode_t *ip)
137 {
138         hammer2_chain_t *chain;
139
140         hammer2_inode_ref(ip);
141 again:
142         ccms_thread_lock(&ip->topo_cst, CCMS_STATE_SHARED);
143
144         chain = ip->chain;
145         KKASSERT(chain != NULL);        /* for now */
146         hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS |
147                                   HAMMER2_RESOLVE_SHARED);
148
149         /*
150          * Resolve duplication races
151          */
152         if (hammer2_chain_refactor_test(chain, 1)) {
153                 hammer2_chain_unlock(chain);
154                 ccms_thread_unlock(&ip->topo_cst);
155                 chain = hammer2_inode_lock_ex(ip);
156                 hammer2_inode_unlock_ex(ip, chain);
157                 goto again;
158         }
159         return (chain);
160 }
161
162 void
163 hammer2_inode_unlock_sh(hammer2_inode_t *ip, hammer2_chain_t *chain)
164 {
165         if (chain)
166                 hammer2_chain_unlock(chain);
167         ccms_thread_unlock(&ip->topo_cst);
168         hammer2_inode_drop(ip);
169 }
170
171 ccms_state_t
172 hammer2_inode_lock_temp_release(hammer2_inode_t *ip)
173 {
174         return(ccms_thread_lock_temp_release(&ip->topo_cst));
175 }
176
177 void
178 hammer2_inode_lock_temp_restore(hammer2_inode_t *ip, ccms_state_t ostate)
179 {
180         ccms_thread_lock_temp_restore(&ip->topo_cst, ostate);
181 }
182
183 ccms_state_t
184 hammer2_inode_lock_upgrade(hammer2_inode_t *ip)
185 {
186         return(ccms_thread_lock_upgrade(&ip->topo_cst));
187 }
188
189 void
190 hammer2_inode_lock_downgrade(hammer2_inode_t *ip, ccms_state_t ostate)
191 {
192         ccms_thread_lock_downgrade(&ip->topo_cst, ostate);
193 }
194
195 /*
196  * Lookup an inode by inode number
197  */
198 hammer2_inode_t *
199 hammer2_inode_lookup(hammer2_pfsmount_t *pmp, hammer2_tid_t inum)
200 {
201         hammer2_inode_t *ip;
202
203         if (pmp) {
204                 spin_lock(&pmp->inum_spin);
205                 ip = RB_LOOKUP(hammer2_inode_tree, &pmp->inum_tree, inum);
206                 if (ip)
207                         hammer2_inode_ref(ip);
208                 spin_unlock(&pmp->inum_spin);
209         } else {
210                 ip = NULL;
211         }
212         return(ip);
213 }
214
215 /*
216  * Adding a ref to an inode is only legal if the inode already has at least
217  * one ref.
218  */
219 void
220 hammer2_inode_ref(hammer2_inode_t *ip)
221 {
222         atomic_add_int(&ip->refs, 1);
223 }
224
225 /*
226  * Drop an inode reference, freeing the inode when the last reference goes
227  * away.
228  */
229 void
230 hammer2_inode_drop(hammer2_inode_t *ip)
231 {
232         hammer2_mount_t *hmp;
233         hammer2_pfsmount_t *pmp;
234         hammer2_inode_t *pip;
235         u_int refs;
236
237         while (ip) {
238                 refs = ip->refs;
239                 cpu_ccfence();
240                 if (refs == 1) {
241                         /*
242                          * Transition to zero, must interlock with
243                          * the inode inumber lookup tree (if applicable).
244                          *
245                          * NOTE: The super-root inode has no pmp.
246                          */
247                         pmp = ip->pmp;
248                         if (pmp)
249                                 spin_lock(&pmp->inum_spin);
250
251                         if (atomic_cmpset_int(&ip->refs, 1, 0)) {
252                                 KKASSERT(ip->topo_cst.count == 0);
253                                 if (ip->flags & HAMMER2_INODE_ONRBTREE) {
254                                         atomic_clear_int(&ip->flags,
255                                                      HAMMER2_INODE_ONRBTREE);
256                                         RB_REMOVE(hammer2_inode_tree,
257                                                   &pmp->inum_tree, ip);
258                                 }
259                                 if (pmp)
260                                         spin_unlock(&pmp->inum_spin);
261
262                                 hmp = ip->hmp;
263                                 ip->hmp = NULL;
264                                 pip = ip->pip;
265                                 ip->pip = NULL;
266                                 ip->pmp = NULL;
267
268                                 /*
269                                  * Cleaning out ip->chain isn't entirely
270                                  * trivial.
271                                  */
272                                 hammer2_inode_repoint(ip, NULL, NULL);
273
274                                 /*
275                                  * We have to drop pip (if non-NULL) to
276                                  * dispose of our implied reference from
277                                  * ip->pip.  We can simply loop on it.
278                                  */
279                                 if (pmp) {
280                                         KKASSERT((ip->flags &
281                                                   HAMMER2_INODE_SROOT) == 0);
282                                         kfree(ip, pmp->minode);
283                                 } else {
284                                         KKASSERT(ip->flags &
285                                                  HAMMER2_INODE_SROOT);
286                                         kfree(ip, hmp->mchain);
287                                 }
288                                 ip = pip;
289                                 /* continue with pip (can be NULL) */
290                         } else {
291                                 if (pmp)
292                                         spin_unlock(&ip->pmp->inum_spin);
293                         }
294                 } else {
295                         /*
296                          * Non zero transition
297                          */
298                         if (atomic_cmpset_int(&ip->refs, refs, refs - 1))
299                                 break;
300                 }
301         }
302 }
303
304 /*
305  * Get the vnode associated with the given inode, allocating the vnode if
306  * necessary.  The vnode will be returned exclusively locked.
307  *
308  * The caller must lock the inode (shared or exclusive).
309  *
310  * Great care must be taken to avoid deadlocks and vnode acquisition/reclaim
311  * races.
312  */
313 struct vnode *
314 hammer2_igetv(hammer2_inode_t *ip, int *errorp)
315 {
316         hammer2_inode_data_t *ipdata;
317         hammer2_pfsmount_t *pmp;
318         struct vnode *vp;
319         ccms_state_t ostate;
320
321         pmp = ip->pmp;
322         KKASSERT(pmp != NULL);
323         *errorp = 0;
324         ipdata = &ip->chain->data->ipdata;
325
326         for (;;) {
327                 /*
328                  * Attempt to reuse an existing vnode assignment.  It is
329                  * possible to race a reclaim so the vget() may fail.  The
330                  * inode must be unlocked during the vget() to avoid a
331                  * deadlock against a reclaim.
332                  */
333                 vp = ip->vp;
334                 if (vp) {
335                         /*
336                          * Inode must be unlocked during the vget() to avoid
337                          * possible deadlocks, but leave the ip ref intact.
338                          *
339                          * vnode is held to prevent destruction during the
340                          * vget().  The vget() can still fail if we lost
341                          * a reclaim race on the vnode.
342                          */
343                         vhold_interlocked(vp);
344                         ostate = hammer2_inode_lock_temp_release(ip);
345                         if (vget(vp, LK_EXCLUSIVE)) {
346                                 vdrop(vp);
347                                 hammer2_inode_lock_temp_restore(ip, ostate);
348                                 continue;
349                         }
350                         hammer2_inode_lock_temp_restore(ip, ostate);
351                         vdrop(vp);
352                         /* vp still locked and ref from vget */
353                         if (ip->vp != vp) {
354                                 kprintf("hammer2: igetv race %p/%p\n",
355                                         ip->vp, vp);
356                                 vput(vp);
357                                 continue;
358                         }
359                         *errorp = 0;
360                         break;
361                 }
362
363                 /*
364                  * No vnode exists, allocate a new vnode.  Beware of
365                  * allocation races.  This function will return an
366                  * exclusively locked and referenced vnode.
367                  */
368                 *errorp = getnewvnode(VT_HAMMER2, pmp->mp, &vp, 0, 0);
369                 if (*errorp) {
370                         kprintf("hammer2: igetv getnewvnode failed %d\n",
371                                 *errorp);
372                         vp = NULL;
373                         break;
374                 }
375
376                 /*
377                  * Lock the inode and check for an allocation race.
378                  */
379                 ostate = hammer2_inode_lock_upgrade(ip);
380                 if (ip->vp != NULL) {
381                         vp->v_type = VBAD;
382                         vx_put(vp);
383                         hammer2_inode_lock_downgrade(ip, ostate);
384                         continue;
385                 }
386
387                 switch (ipdata->type) {
388                 case HAMMER2_OBJTYPE_DIRECTORY:
389                         vp->v_type = VDIR;
390                         break;
391                 case HAMMER2_OBJTYPE_REGFILE:
392                         vp->v_type = VREG;
393                         vinitvmio(vp, ipdata->size,
394                                   HAMMER2_LBUFSIZE,
395                                   (int)ipdata->size & HAMMER2_LBUFMASK);
396                         break;
397                 case HAMMER2_OBJTYPE_SOFTLINK:
398                         /*
399                          * XXX for now we are using the generic file_read
400                          * and file_write code so we need a buffer cache
401                          * association.
402                          */
403                         vp->v_type = VLNK;
404                         vinitvmio(vp, ipdata->size,
405                                   HAMMER2_LBUFSIZE,
406                                   (int)ipdata->size & HAMMER2_LBUFMASK);
407                         break;
408                 /* XXX FIFO */
409                 default:
410                         panic("hammer2: unhandled objtype %d", ipdata->type);
411                         break;
412                 }
413
414                 if (ip == pmp->iroot)
415                         vsetflags(vp, VROOT);
416
417                 vp->v_data = ip;
418                 ip->vp = vp;
419                 hammer2_inode_ref(ip);          /* vp association */
420                 hammer2_inode_lock_downgrade(ip, ostate);
421                 break;
422         }
423
424         /*
425          * Return non-NULL vp and *errorp == 0, or NULL vp and *errorp != 0.
426          */
427         if (hammer2_debug & 0x0002) {
428                 kprintf("igetv vp %p refs %d aux %d\n",
429                         vp, vp->v_sysref.refcnt, vp->v_auxrefs);
430         }
431         return (vp);
432 }
433
434 /*
435  * The passed-in chain must be locked and the returned inode will also be
436  * locked.  This routine typically locates or allocates the inode, assigns
437  * ip->chain (adding a ref to chain if necessary), and returns the inode.
438  *
439  * The hammer2_inode structure regulates the interface between the high level
440  * kernel VNOPS API and the filesystem backend (the chains).
441  *
442  * WARNING!  This routine sucks up the chain's lock (makes it part of the
443  *           inode lock from the point of view of the inode lock API),
444  *           so callers need to be careful.
445  *
446  * WARNING!  The mount code is allowed to pass dip == NULL for iroot and
447  *           is allowed to pass pmp == NULL and dip == NULL for sroot.
448  */
449 hammer2_inode_t *
450 hammer2_inode_get(hammer2_mount_t *hmp, hammer2_pfsmount_t *pmp,
451                   hammer2_inode_t *dip, hammer2_chain_t *chain)
452 {
453         hammer2_inode_t *nip;
454
455         KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_INODE);
456
457         /*
458          * Interlocked lookup/ref of the inode.  This code is only needed
459          * when looking up inodes with nlinks != 0 (TODO: optimize out
460          * otherwise and test for duplicates).
461          */
462 again:
463         for (;;) {
464                 nip = hammer2_inode_lookup(pmp, chain->data->ipdata.inum);
465                 if (nip == NULL)
466                         break;
467                 ccms_thread_lock(&nip->topo_cst, CCMS_STATE_EXCLUSIVE);
468                 if ((nip->flags & HAMMER2_INODE_ONRBTREE) == 0) { /* race */
469                         ccms_thread_unlock(&nip->topo_cst);
470                         hammer2_inode_drop(nip);
471                         continue;
472                 }
473                 if (nip->chain != chain)
474                         hammer2_inode_repoint(nip, NULL, chain);
475
476                 /*
477                  * Consolidated nip/nip->chain is locked (chain locked
478                  * by caller).
479                  */
480                 return nip;
481         }
482
483         /*
484          * We couldn't find the inode number, create a new inode.
485          */
486         if (pmp) {
487                 nip = kmalloc(sizeof(*nip), pmp->minode, M_WAITOK | M_ZERO);
488         } else {
489                 nip = kmalloc(sizeof(*nip), hmp->mchain, M_WAITOK | M_ZERO);
490                 nip->flags = HAMMER2_INODE_SROOT;
491         }
492         nip->inum = chain->data->ipdata.inum;
493         hammer2_inode_repoint(nip, NULL, chain);
494         nip->pip = dip;                         /* can be NULL */
495         if (dip)
496                 hammer2_inode_ref(dip); /* ref dip for nip->pip */
497
498         nip->pmp = pmp;
499         nip->hmp = hmp;
500
501         /*
502          * ref and lock on nip gives it state compatible to after a
503          * hammer2_inode_lock_ex() call.
504          */
505         nip->refs = 1;
506         ccms_cst_init(&nip->topo_cst, &nip->chain);
507         ccms_thread_lock(&nip->topo_cst, CCMS_STATE_EXCLUSIVE);
508         /* combination of thread lock and chain lock == inode lock */
509
510         /*
511          * Attempt to add the inode.  If it fails we raced another inode
512          * get.  Undo all the work and try again.
513          */
514         if (pmp) {
515                 spin_lock(&pmp->inum_spin);
516                 if (RB_INSERT(hammer2_inode_tree, &pmp->inum_tree, nip)) {
517                         spin_unlock(&pmp->inum_spin);
518                         ccms_thread_unlock(&nip->topo_cst);
519                         hammer2_inode_drop(nip);
520                         goto again;
521                 }
522                 atomic_set_int(&nip->flags, HAMMER2_INODE_ONRBTREE);
523                 spin_unlock(&pmp->inum_spin);
524         }
525
526         return (nip);
527 }
528
529 /*
530  * Create a new inode in the specified directory using the vattr to
531  * figure out the type of inode.
532  *
533  * If no error occurs the new inode with its chain locked is returned in
534  * *nipp, otherwise an error is returned and *nipp is set to NULL.
535  *
536  * If vap and/or cred are NULL the related fields are not set and the
537  * inode type defaults to a directory.  This is used when creating PFSs
538  * under the super-root, so the inode number is set to 1 in this case.
539  *
540  * dip is not locked on entry.
541  */
542 hammer2_inode_t *
543 hammer2_inode_create(hammer2_trans_t *trans, hammer2_inode_t *dip,
544                      struct vattr *vap, struct ucred *cred,
545                      const uint8_t *name, size_t name_len,
546                      hammer2_chain_t **chainp, int *errorp)
547 {
548         hammer2_inode_data_t *dipdata;
549         hammer2_inode_data_t *nipdata;
550         hammer2_mount_t *hmp;
551         hammer2_chain_t *chain;
552         hammer2_chain_t *parent;
553         hammer2_inode_t *nip;
554         hammer2_key_t lhc;
555         int error;
556         uid_t xuid;
557         uuid_t dip_uid;
558         uuid_t dip_gid;
559         uint32_t dip_mode;
560
561         hmp = dip->hmp;
562         lhc = hammer2_dirhash(name, name_len);
563         *errorp = 0;
564
565         /*
566          * Locate the inode or indirect block to create the new
567          * entry in.  At the same time check for key collisions
568          * and iterate until we don't get one.
569          *
570          * NOTE: hidden inodes do not have iterators.
571          */
572 retry:
573         parent = hammer2_inode_lock_ex(dip);
574         dipdata = &dip->chain->data->ipdata;
575         dip_uid = dipdata->uid;
576         dip_gid = dipdata->gid;
577         dip_mode = dipdata->mode;
578
579         error = 0;
580         while (error == 0) {
581                 chain = hammer2_chain_lookup(&parent, lhc, lhc, 0);
582                 if (chain == NULL)
583                         break;
584                 if ((lhc & HAMMER2_DIRHASH_VISIBLE) == 0)
585                         error = ENOSPC;
586                 if ((lhc & HAMMER2_DIRHASH_LOMASK) == HAMMER2_DIRHASH_LOMASK)
587                         error = ENOSPC;
588                 hammer2_chain_unlock(chain);
589                 chain = NULL;
590                 ++lhc;
591         }
592         if (error == 0) {
593                 error = hammer2_chain_create(trans, &parent, &chain,
594                                              lhc, 0,
595                                              HAMMER2_BREF_TYPE_INODE,
596                                              HAMMER2_INODE_BYTES);
597         }
598
599         /*
600          * Cleanup and handle retries.
601          */
602         if (error == EAGAIN) {
603                 hammer2_chain_ref(parent);
604                 hammer2_inode_unlock_ex(dip, parent);
605                 hammer2_chain_wait(parent);
606                 hammer2_chain_drop(parent);
607                 goto retry;
608         }
609         hammer2_inode_unlock_ex(dip, parent);
610
611         if (error) {
612                 KKASSERT(chain == NULL);
613                 *errorp = error;
614                 return (NULL);
615         }
616
617         /*
618          * Set up the new inode.
619          *
620          * NOTE: *_get() integrates chain's lock into the inode lock.
621          *
622          * NOTE: Only one new inode can currently be created per
623          *       transaction.  If the need arises we can adjust
624          *       hammer2_trans_init() to allow more.
625          */
626         chain->data->ipdata.inum = trans->sync_tid;
627         nip = hammer2_inode_get(dip->hmp, dip->pmp, dip, chain);
628         nipdata = &chain->data->ipdata;
629
630         if (vap) {
631                 KKASSERT(trans->inodes_created == 0);
632                 nipdata->type = hammer2_get_obj_type(vap->va_type);
633                 nipdata->inum = trans->sync_tid;
634                 ++trans->inodes_created;
635         } else {
636                 nipdata->type = HAMMER2_OBJTYPE_DIRECTORY;
637                 nipdata->inum = 1;
638         }
639         nipdata->version = HAMMER2_INODE_VERSION_ONE;
640         hammer2_update_time(&nipdata->ctime);
641         nipdata->mtime = nipdata->ctime;
642         if (vap)
643                 nipdata->mode = vap->va_mode;
644         nipdata->nlinks = 1;
645         if (vap) {
646                 if (dip) {
647                         xuid = hammer2_to_unix_xid(&dip_uid);
648                         xuid = vop_helper_create_uid(dip->pmp->mp,
649                                                      dip_mode,
650                                                      xuid,
651                                                      cred,
652                                                      &vap->va_mode);
653                 } else {
654                         xuid = 0;
655                 }
656                 if (vap->va_vaflags & VA_UID_UUID_VALID)
657                         nipdata->uid = vap->va_uid_uuid;
658                 else if (vap->va_uid != (uid_t)VNOVAL)
659                         hammer2_guid_to_uuid(&nipdata->uid, vap->va_uid);
660                 else
661                         hammer2_guid_to_uuid(&nipdata->uid, xuid);
662
663                 if (vap->va_vaflags & VA_GID_UUID_VALID)
664                         nipdata->gid = vap->va_gid_uuid;
665                 else if (vap->va_gid != (gid_t)VNOVAL)
666                         hammer2_guid_to_uuid(&nipdata->gid, vap->va_gid);
667                 else if (dip)
668                         nipdata->gid = dip_gid;
669         }
670
671         /*
672          * Regular files and softlinks allow a small amount of data to be
673          * directly embedded in the inode.  This flag will be cleared if
674          * the size is extended past the embedded limit.
675          */
676         if (nipdata->type == HAMMER2_OBJTYPE_REGFILE ||
677             nipdata->type == HAMMER2_OBJTYPE_SOFTLINK) {
678                 nipdata->op_flags |= HAMMER2_OPFLAG_DIRECTDATA;
679         }
680
681         KKASSERT(name_len < HAMMER2_INODE_MAXNAME);
682         bcopy(name, nipdata->filename, name_len);
683         nipdata->name_key = lhc;
684         nipdata->name_len = name_len;
685         *chainp = chain;
686
687         return (nip);
688 }
689
690 /*
691  * chain may have been moved around by the create.
692  */
693 static
694 void
695 hammer2_chain_refactor(hammer2_chain_t **chainp)
696 {
697         hammer2_chain_t *chain = *chainp;
698         hammer2_chain_core_t *core;
699
700         core = chain->core;
701         spin_lock(&core->cst.spin);
702         while (hammer2_chain_refactor_test(chain, 1)) {
703                 chain = chain->next_parent;
704                 while (hammer2_chain_refactor_test(chain, 1))
705                         chain = chain->next_parent;
706                 hammer2_chain_ref(chain);
707                 spin_unlock(&core->cst.spin);
708
709                 hammer2_chain_unlock(*chainp);
710                 hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS |
711                                           HAMMER2_RESOLVE_NOREF); /* eat ref */
712                 *chainp = chain;
713                 spin_lock(&core->cst.spin);
714         }
715         spin_unlock(&core->cst.spin);
716 }
717
718 /*
719  * ochain represents the target file inode.  We need to move it to the
720  * specified common parent directory (dip) and rename it to a special
721  * invisible "0xINODENUMBER" filename.
722  *
723  * We use chain_duplicate and duplicate ochain at the new location,
724  * renaming it appropriately.  We create a temporary chain and
725  * then delete it to placemark where the duplicate will go.  Both of
726  * these use the inode number for (lhc) (the key), generating the
727  * invisible filename.
728  */
729 static
730 hammer2_chain_t *
731 hammer2_hardlink_shiftup(hammer2_trans_t *trans, hammer2_chain_t **ochainp,
732                         hammer2_inode_t *dip, int *errorp)
733 {
734         hammer2_inode_data_t *nipdata;
735         hammer2_mount_t *hmp;
736         hammer2_chain_t *parent;
737         hammer2_chain_t *ochain;
738         hammer2_chain_t *nchain;
739         hammer2_chain_t *tmp;
740         hammer2_key_t lhc;
741         hammer2_blockref_t bref;
742
743         ochain = *ochainp;
744         *errorp = 0;
745         hmp = dip->hmp;
746         lhc = ochain->data->ipdata.inum;
747         KKASSERT((lhc & HAMMER2_DIRHASH_VISIBLE) == 0);
748
749         /*
750          * Locate the inode or indirect block to create the new
751          * entry in.  lhc represents the inode number so there is
752          * no collision iteration.
753          *
754          * There should be no key collisions with invisible inode keys.
755          */
756 retry:
757         parent = hammer2_chain_lookup_init(dip->chain, 0);
758         nchain = hammer2_chain_lookup(&parent, lhc, lhc, 0);
759         if (nchain) {
760                 kprintf("X3 chain %p parent %p dip %p dip->chain %p\n",
761                         nchain, parent, dip, dip->chain);
762                 hammer2_chain_unlock(nchain);
763                 nchain = NULL;
764                 *errorp = ENOSPC;
765 #if 1
766                 Debugger("X3");
767 #endif
768         }
769
770         /*
771          * Create entry in common parent directory using the seek position
772          * calculated above.
773          */
774         if (*errorp == 0) {
775                 KKASSERT(nchain == NULL);
776                 *errorp = hammer2_chain_create(trans, &parent, &nchain,
777                                                lhc, 0,
778                                                HAMMER2_BREF_TYPE_INODE,/* n/a */
779                                                HAMMER2_INODE_BYTES);   /* n/a */
780                 hammer2_chain_refactor(&ochain);
781                 *ochainp = ochain;
782         }
783
784         /*
785          * Cleanup and handle retries.
786          */
787         if (*errorp == EAGAIN) {
788                 hammer2_chain_ref(parent);
789                 hammer2_chain_lookup_done(parent);
790                 hammer2_chain_wait(parent);
791                 hammer2_chain_drop(parent);
792                 goto retry;
793         }
794
795         /*
796          * Handle the error case
797          */
798         if (*errorp) {
799                 KKASSERT(nchain == NULL);
800                 hammer2_chain_lookup_done(parent);
801                 return (NULL);
802         }
803
804         /*
805          * Use chain as a placeholder for (lhc), delete it and replace
806          * it with our duplication.
807          *
808          * Gain a second lock on ochain for the duplication function to
809          * unlock, maintain the caller's original lock across the call.
810          *
811          * This is a bit messy.
812          */
813         hammer2_chain_delete(trans, nchain);
814         hammer2_chain_lock(ochain, HAMMER2_RESOLVE_ALWAYS);
815         tmp = ochain;
816         bref = tmp->bref;
817         bref.key = lhc;                 /* invisible dir entry key */
818         bref.keybits = 0;
819         hammer2_chain_duplicate(trans, parent, nchain->index, &tmp, &bref);
820         hammer2_chain_lookup_done(parent);
821         hammer2_chain_unlock(nchain);   /* no longer needed */
822
823         /*
824          * Now set chain to our duplicate and modify it appropriately.
825          *
826          * Directory entries are inodes but this is a hidden hardlink
827          * target.  The name isn't used but to ease debugging give it
828          * a name after its inode number.
829          */
830         nchain = tmp;
831         tmp = NULL;     /* safety */
832
833         hammer2_chain_modify(trans, &nchain, HAMMER2_MODIFY_ASSERTNOCOPY);
834         nipdata = &nchain->data->ipdata;
835         ksnprintf(nipdata->filename, sizeof(nipdata->filename),
836                   "0x%016jx", (intmax_t)nipdata->inum);
837         nipdata->name_len = strlen(nipdata->filename);
838         nipdata->name_key = lhc;
839
840         return (nchain);
841 }
842
843 /*
844  * Connect the target inode represented by (*chainp) to the media topology
845  * at (dip, name, len).
846  *
847  * If hlink is TRUE this function creates an OBJTYPE_HARDLINK directory
848  * entry instead of connecting (*chainp).
849  *
850  * If hlink is FALSE this function uses chain_duplicate() to make a copy
851  * if (*chainp) in the directory entry.  (*chainp) is likely to be deleted
852  * by the caller in this case (e.g. rename).
853  */
854 int
855 hammer2_inode_connect(hammer2_trans_t *trans, int hlink,
856                       hammer2_inode_t *dip, hammer2_chain_t **chainp,
857                       const uint8_t *name, size_t name_len)
858 {
859         hammer2_inode_data_t *ipdata;
860         hammer2_mount_t *hmp;
861         hammer2_chain_t *nchain;
862         hammer2_chain_t *parent;
863         hammer2_chain_t *ochain;
864         hammer2_key_t lhc;
865         int error;
866
867         hmp = dip->hmp;
868
869         ochain = *chainp;
870
871         /*
872          * Since ochain is either disconnected from the topology or represents
873          * a hardlink terminus which is always a parent of or equal to dip,
874          * we should be able to safely lock dip->chain for our setup.
875          */
876         parent = hammer2_chain_lookup_init(dip->chain, 0);
877
878         lhc = hammer2_dirhash(name, name_len);
879
880         /*
881          * Locate the inode or indirect block to create the new
882          * entry in.  At the same time check for key collisions
883          * and iterate until we don't get one.
884          */
885         error = 0;
886         while (error == 0) {
887                 nchain = hammer2_chain_lookup(&parent, lhc, lhc, 0);
888                 if (nchain == NULL)
889                         break;
890                 if ((lhc & HAMMER2_DIRHASH_LOMASK) == HAMMER2_DIRHASH_LOMASK)
891                         error = ENOSPC;
892                 hammer2_chain_unlock(nchain);
893                 nchain = NULL;
894                 ++lhc;
895         }
896
897         if (error == 0) {
898                 if (hlink) {
899                         /*
900                          * Hardlink pointer needed, create totally fresh
901                          * directory entry.
902                          */
903                         KKASSERT(nchain == NULL);
904                         error = hammer2_chain_create(trans, &parent, &nchain,
905                                                      lhc, 0,
906                                                      HAMMER2_BREF_TYPE_INODE,
907                                                      HAMMER2_INODE_BYTES);
908                         hammer2_chain_refactor(&ochain);
909                 } else {
910                         /*
911                          * Reconnect the original chain and rename.  Use
912                          * chain_duplicate().  The caller will likely delete
913                          * or has already deleted the original chain in
914                          * this case.
915                          *
916                          * NOTE: chain_duplicate() generates a new chain
917                          *       with CHAIN_DELETED cleared (ochain typically
918                          *       has it set from the file unlink).
919                          */
920                         nchain = ochain;
921                         ochain = NULL;
922                         hammer2_chain_duplicate(trans, NULL, -1, &nchain, NULL);
923                         error = hammer2_chain_create(trans, &parent, &nchain,
924                                                      lhc, 0,
925                                                      HAMMER2_BREF_TYPE_INODE,
926                                                      HAMMER2_INODE_BYTES);
927                 }
928         }
929
930         /*
931          * Unlock stuff.
932          */
933         KKASSERT(error != EAGAIN);
934         hammer2_chain_lookup_done(parent);
935         parent = NULL;
936
937         /*
938          * nchain should be NULL on error, leave ochain (== *chainp) alone.
939          */
940         if (error) {
941                 KKASSERT(nchain == NULL);
942                 return (error);
943         }
944
945         /*
946          * Directory entries are inodes so if the name has changed we have
947          * to update the inode.
948          *
949          * When creating an OBJTYPE_HARDLINK entry remember to unlock the
950          * chain, the caller will access the hardlink via the actual hardlink
951          * target file and not the hardlink pointer entry, so we must still
952          * return ochain.
953          */
954         if (hlink && hammer2_hardlink_enable >= 0) {
955                 /*
956                  * Create the HARDLINK pointer.  oip represents the hardlink
957                  * target in this situation.
958                  *
959                  * We will return ochain (the hardlink target).
960                  */
961                 hammer2_chain_modify(trans, &nchain,
962                                      HAMMER2_MODIFY_ASSERTNOCOPY);
963                 KKASSERT(name_len < HAMMER2_INODE_MAXNAME);
964                 ipdata = &nchain->data->ipdata;
965                 bcopy(name, ipdata->filename, name_len);
966                 ipdata->name_key = lhc;
967                 ipdata->name_len = name_len;
968                 ipdata->target_type = ochain->data->ipdata.type;
969                 ipdata->type = HAMMER2_OBJTYPE_HARDLINK;
970                 ipdata->inum = ochain->data->ipdata.inum;
971                 ipdata->nlinks = 1;
972                 hammer2_chain_unlock(nchain);
973                 nchain = ochain;
974                 ochain = NULL;
975         } else if (hlink && hammer2_hardlink_enable < 0) {
976                 /*
977                  * Create a snapshot (hardlink fake mode for debugging).
978                  * (ochain already flushed above so we can just copy the
979                  * bref XXX).
980                  *
981                  * Since this is a snapshot we return nchain in the fake
982                  * hardlink case.
983                  */
984                 hammer2_chain_modify(trans, &nchain,
985                                      HAMMER2_MODIFY_ASSERTNOCOPY);
986                 KKASSERT(name_len < HAMMER2_INODE_MAXNAME);
987                 ipdata = &nchain->data->ipdata;
988                 *ipdata = ochain->data->ipdata;
989                 bcopy(name, ipdata->filename, name_len);
990                 ipdata->name_key = lhc;
991                 ipdata->name_len = name_len;
992                 kprintf("created fake hardlink %*.*s\n",
993                         (int)name_len, (int)name_len, name);
994         } else {
995                 /*
996                  * nchain is a duplicate of ochain at the new location.
997                  * We must fixup the name stored in oip.  The bref key
998                  * has already been set up.
999                  */
1000                 hammer2_chain_modify(trans, &nchain,
1001                                      HAMMER2_MODIFY_ASSERTNOCOPY);
1002                 ipdata = &nchain->data->ipdata;
1003
1004                 KKASSERT(name_len < HAMMER2_INODE_MAXNAME);
1005                 bcopy(name, ipdata->filename, name_len);
1006                 ipdata->name_key = lhc;
1007                 ipdata->name_len = name_len;
1008                 ipdata->nlinks = 1;
1009         }
1010
1011         /*
1012          * We are replacing ochain with nchain, unlock ochain.  In the
1013          * case where ochain is left unchanged the code above sets
1014          * nchain to ochain and ochain to NULL, resulting in a NOP here.
1015          */
1016         if (ochain)
1017                 hammer2_chain_unlock(ochain);
1018         *chainp = nchain;
1019
1020         return (0);
1021 }
1022
1023 /*
1024  * Repoint ip->chain to nchain.  Caller must hold the inode exclusively
1025  * locked.
1026  *
1027  * ip->chain is set to nchain.  The prior chain in ip->chain is dropped
1028  * and nchain is ref'd.
1029  */
1030 void
1031 hammer2_inode_repoint(hammer2_inode_t *ip, hammer2_inode_t *pip,
1032                       hammer2_chain_t *nchain)
1033 {
1034         hammer2_chain_t *ochain;
1035         hammer2_inode_t *opip;
1036
1037         /*
1038          * Repoint ip->chain if requested.
1039          */
1040         ochain = ip->chain;
1041         ip->chain = nchain;
1042         if (nchain)
1043                 hammer2_chain_ref(nchain);
1044         if (ochain)
1045                 hammer2_chain_drop(ochain);
1046
1047         /*
1048          * Repoint ip->pip if requested (non-NULL pip).
1049          */
1050         if (pip && ip->pip != pip) {
1051                 opip = ip->pip;
1052                 hammer2_inode_ref(pip);
1053                 ip->pip = pip;
1054                 if (opip)
1055                         hammer2_inode_drop(opip);
1056         }
1057 }
1058
1059 /*
1060  * Unlink the file from the specified directory inode.  The directory inode
1061  * does not need to be locked.
1062  *
1063  * isdir determines whether a directory/non-directory check should be made.
1064  * No check is made if isdir is set to -1.
1065  *
1066  * NOTE!  This function does not prevent the underlying file from still
1067  *        being used if it has other refs (such as from an inode, or if it's
1068  *        chain is manually held).  However, the caller is responsible for
1069  *        fixing up ip->chain if e.g. a rename occurs (see chain_duplicate()).
1070  */
1071 int
1072 hammer2_unlink_file(hammer2_trans_t *trans, hammer2_inode_t *dip,
1073                     const uint8_t *name, size_t name_len,
1074                     int isdir, int *hlinkp)
1075 {
1076         hammer2_inode_data_t *ipdata;
1077         hammer2_mount_t *hmp;
1078         hammer2_chain_t *parent;
1079         hammer2_chain_t *ochain;
1080         hammer2_chain_t *chain;
1081         hammer2_chain_t *dparent;
1082         hammer2_chain_t *dchain;
1083         hammer2_key_t lhc;
1084         int error;
1085         uint8_t type;
1086
1087         error = 0;
1088         ochain = NULL;
1089         hmp = dip->hmp;
1090         lhc = hammer2_dirhash(name, name_len);
1091
1092         /*
1093          * Search for the filename in the directory
1094          */
1095         if (hlinkp)
1096                 *hlinkp = 0;
1097         parent = hammer2_inode_lock_ex(dip);
1098         chain = hammer2_chain_lookup(&parent,
1099                                      lhc, lhc + HAMMER2_DIRHASH_LOMASK,
1100                                      0);
1101         while (chain) {
1102                 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
1103                     name_len == chain->data->ipdata.name_len &&
1104                     bcmp(name, chain->data->ipdata.filename, name_len) == 0) {
1105                         break;
1106                 }
1107                 chain = hammer2_chain_next(&parent, chain,
1108                                            lhc, lhc + HAMMER2_DIRHASH_LOMASK,
1109                                            0);
1110         }
1111         hammer2_inode_unlock_ex(dip, NULL);     /* retain parent */
1112
1113         /*
1114          * Not found or wrong type (isdir < 0 disables the type check).
1115          * If a hardlink pointer, type checks use the hardlink target.
1116          */
1117         if (chain == NULL) {
1118                 error = ENOENT;
1119                 goto done;
1120         }
1121         if ((type = chain->data->ipdata.type) == HAMMER2_OBJTYPE_HARDLINK) {
1122                 if (hlinkp)
1123                         *hlinkp = 1;
1124                 type = chain->data->ipdata.target_type;
1125         }
1126
1127         if (type == HAMMER2_OBJTYPE_DIRECTORY && isdir == 0) {
1128                 error = ENOTDIR;
1129                 goto done;
1130         }
1131         if (type != HAMMER2_OBJTYPE_DIRECTORY && isdir >= 1) {
1132                 error = EISDIR;
1133                 goto done;
1134         }
1135
1136         /*
1137          * Hardlink must be resolved.  We can't hold parent locked while we
1138          * do this or we could deadlock.
1139          *
1140          * On success chain will be adjusted to point at the hardlink target
1141          * and ochain will point to the hardlink pointer in the original
1142          * directory.  Otherwise chain remains pointing to the original.
1143          */
1144         if (chain->data->ipdata.type == HAMMER2_OBJTYPE_HARDLINK) {
1145                 hammer2_chain_unlock(parent);
1146                 parent = NULL;
1147                 error = hammer2_hardlink_find(dip, &chain, &ochain);
1148         }
1149
1150         /*
1151          * If this is a directory the directory must be empty.  However, if
1152          * isdir < 0 we are doing a rename and the directory does not have
1153          * to be empty, and if isdir > 1 we are deleting a PFS/snapshot
1154          * and the directory does not have to be empty.
1155          *
1156          * NOTE: We check the full key range here which covers both visible
1157          *       and invisible entries.  Theoretically there should be no
1158          *       invisible (hardlink target) entries if there are no visible
1159          *       entries.
1160          */
1161         if (type == HAMMER2_OBJTYPE_DIRECTORY && isdir == 1) {
1162                 dparent = hammer2_chain_lookup_init(chain, 0);
1163                 dchain = hammer2_chain_lookup(&dparent,
1164                                               0, (hammer2_key_t)-1,
1165                                               HAMMER2_LOOKUP_NODATA);
1166                 if (dchain) {
1167                         hammer2_chain_unlock(dchain);
1168                         hammer2_chain_lookup_done(dparent);
1169                         error = ENOTEMPTY;
1170                         goto done;
1171                 }
1172                 hammer2_chain_lookup_done(dparent);
1173                 dparent = NULL;
1174                 /* dchain NULL */
1175         }
1176
1177         /*
1178          * Ok, we can now unlink the chain.  We always decrement nlinks even
1179          * if the entry can be deleted in case someone has the file open and
1180          * does an fstat().
1181          *
1182          * The chain itself will no longer be in the on-media topology but
1183          * can still be flushed to the media (e.g. if an open descriptor
1184          * remains).  When the last vnode/ip ref goes away the chain will
1185          * be marked unmodified, avoiding any further (now unnecesary) I/O.
1186          *
1187          * A non-NULL ochain indicates a hardlink.
1188          */
1189         if (ochain) {
1190                 /*
1191                  * Delete the original hardlink pointer.
1192                  *
1193                  * NOTE: parent from above is NULL when ochain != NULL
1194                  *       so we can reuse it.
1195                  */
1196                 hammer2_chain_lock(ochain, HAMMER2_RESOLVE_ALWAYS);
1197                 hammer2_chain_delete(trans, ochain);
1198                 hammer2_chain_unlock(ochain);
1199
1200                 /*
1201                  * Then decrement nlinks on hardlink target, deleting
1202                  * the target when nlinks drops to 0.
1203                  */
1204                 hammer2_chain_modify(trans, &chain, 0);
1205                 --chain->data->ipdata.nlinks;
1206                 if (chain->data->ipdata.nlinks == 0)
1207                         hammer2_chain_delete(trans, chain);
1208         } else {
1209                 /*
1210                  * Otherwise this was not a hardlink and we can just
1211                  * remove the entry and decrement nlinks.
1212                  *
1213                  * NOTE: *_get() integrates chain's lock into the inode lock.
1214                  */
1215                 hammer2_chain_modify(trans, &chain, 0);
1216                 ipdata = &chain->data->ipdata;
1217                 --ipdata->nlinks;
1218                 hammer2_chain_delete(trans, chain);
1219         }
1220
1221         error = 0;
1222 done:
1223         if (chain)
1224                 hammer2_chain_unlock(chain);
1225         if (parent)
1226                 hammer2_chain_lookup_done(parent);
1227         if (ochain)
1228                 hammer2_chain_drop(ochain);
1229
1230         return error;
1231 }
1232
1233 /*
1234  * Given an exclusively locked inode we consolidate its chain for hardlink
1235  * creation, adding (nlinks) to the file's link count and potentially
1236  * relocating the inode to a directory common to ip->pip and tdip.
1237  *
1238  * Replaces (*chainp) if consolidation occurred, unlocking the old chain
1239  * and returning a new locked chain.
1240  *
1241  * NOTE!  This function will also replace ip->chain.
1242  */
1243 int
1244 hammer2_hardlink_consolidate(hammer2_trans_t *trans, hammer2_inode_t *ip,
1245                              hammer2_chain_t **chainp,
1246                              hammer2_inode_t *tdip, int nlinks)
1247 {
1248         hammer2_inode_data_t *ipdata;
1249         hammer2_mount_t *hmp;
1250         hammer2_inode_t *fdip;
1251         hammer2_inode_t *cdip;
1252         hammer2_chain_t *chain;
1253         hammer2_chain_t *nchain;
1254         int error;
1255
1256         hmp = tdip->hmp;
1257
1258         chain = *chainp;
1259         if (nlinks == 0 &&                      /* no hardlink needed */
1260             (chain->data->ipdata.name_key & HAMMER2_DIRHASH_VISIBLE)) {
1261                 return (0);
1262         }
1263         if (hammer2_hardlink_enable < 0) {      /* fake hardlinks */
1264                 return (0);
1265         }
1266
1267         if (hammer2_hardlink_enable == 0) {     /* disallow hardlinks */
1268                 hammer2_chain_unlock(chain);
1269                 *chainp = NULL;
1270                 return (ENOTSUP);
1271         }
1272
1273         /*
1274          * cdip will be returned with a ref, but not locked.
1275          */
1276         fdip = ip->pip;
1277         cdip = hammer2_inode_common_parent(fdip, tdip);
1278
1279         /*
1280          * If no change in the hardlink's target directory is required and
1281          * this is already a hardlink target, all we need to do is adjust
1282          * the link count.
1283          *
1284          * XXX The common parent is a big wiggly due to duplication from
1285          *     renames.  Compare the core (RBTREE) pointer instead of the
1286          *     ip's.
1287          */
1288         if (cdip == fdip &&
1289             (chain->data->ipdata.name_key & HAMMER2_DIRHASH_VISIBLE) == 0) {
1290                 if (nlinks) {
1291                         hammer2_chain_modify(trans, &chain, 0);
1292                         chain->data->ipdata.nlinks += nlinks;
1293                 }
1294                 error = 0;
1295                 goto done;
1296         }
1297
1298         /*
1299          * We either have to move an existing hardlink target or we have
1300          * to create a fresh hardlink target.
1301          *
1302          * Hardlink targets are hidden inodes in a parent directory common
1303          * to all directory entries referencing the hardlink.
1304          */
1305         nchain = hammer2_hardlink_shiftup(trans, &chain, cdip, &error);
1306
1307         if (error == 0) {
1308                 /*
1309                  * Bump nlinks on duplicated hidden inode, repoint
1310                  * ip->chain.
1311                  */
1312                 hammer2_chain_modify(trans, &nchain, 0);
1313                 nchain->data->ipdata.nlinks += nlinks;
1314                 hammer2_inode_repoint(ip, cdip, nchain);
1315
1316                 /*
1317                  * If the old chain is not a hardlink target then replace
1318                  * it with a OBJTYPE_HARDLINK pointer.
1319                  *
1320                  * If the old chain IS a hardlink target then delete it.
1321                  */
1322                 if (chain->data->ipdata.name_key & HAMMER2_DIRHASH_VISIBLE) {
1323                         /*
1324                          * Replace original non-hardlink that's been dup'd
1325                          * with a special hardlink directory entry.  We must
1326                          * set the DIRECTDATA flag to prevent sub-chains
1327                          * from trying to synchronize to the inode if the
1328                          * file is extended afterwords.
1329                          */
1330                         hammer2_chain_modify(trans, &chain, 0);
1331                         hammer2_chain_delete_duplicate(trans, &chain,
1332                                                        HAMMER2_DELDUP_RECORE);
1333                         ipdata = &chain->data->ipdata;
1334                         ipdata->target_type = ipdata->type;
1335                         ipdata->type = HAMMER2_OBJTYPE_HARDLINK;
1336                         ipdata->uflags = 0;
1337                         ipdata->rmajor = 0;
1338                         ipdata->rminor = 0;
1339                         ipdata->ctime = 0;
1340                         ipdata->mtime = 0;
1341                         ipdata->atime = 0;
1342                         ipdata->btime = 0;
1343                         bzero(&ipdata->uid, sizeof(ipdata->uid));
1344                         bzero(&ipdata->gid, sizeof(ipdata->gid));
1345                         ipdata->op_flags = HAMMER2_OPFLAG_DIRECTDATA;
1346                         ipdata->cap_flags = 0;
1347                         ipdata->mode = 0;
1348                         ipdata->size = 0;
1349                         ipdata->nlinks = 1;
1350                         ipdata->iparent = 0;    /* XXX */
1351                         ipdata->pfs_type = 0;
1352                         ipdata->pfs_inum = 0;
1353                         bzero(&ipdata->pfs_clid, sizeof(ipdata->pfs_clid));
1354                         bzero(&ipdata->pfs_fsid, sizeof(ipdata->pfs_fsid));
1355                         ipdata->data_quota = 0;
1356                         ipdata->data_count = 0;
1357                         ipdata->inode_quota = 0;
1358                         ipdata->inode_count = 0;
1359                         ipdata->attr_tid = 0;
1360                         ipdata->dirent_tid = 0;
1361                         bzero(&ipdata->u, sizeof(ipdata->u));
1362                         /* XXX transaction ids */
1363                 } else {
1364                         hammer2_chain_delete(trans, chain);
1365                 }
1366
1367                 /*
1368                  * Return the new chain.
1369                  */
1370                 hammer2_chain_unlock(chain);
1371                 chain = nchain;
1372         } else {
1373                 /*
1374                  * Return an error
1375                  */
1376                 hammer2_chain_unlock(chain);
1377                 chain = NULL;
1378         }
1379
1380         /*
1381          * Cleanup, chain/nchain already dealt with.
1382          */
1383 done:
1384         *chainp = chain;
1385         hammer2_inode_drop(cdip);
1386
1387         return (error);
1388 }
1389
1390 /*
1391  * If (*ochainp) is non-NULL it points to the forward OBJTYPE_HARDLINK
1392  * inode while (*chainp) points to the resolved (hidden hardlink
1393  * target) inode.  In this situation when nlinks is 1 we wish to
1394  * deconsolidate the hardlink, moving it back to the directory that now
1395  * represents the only remaining link.
1396  */
1397 int
1398 hammer2_hardlink_deconsolidate(hammer2_trans_t *trans,
1399                                hammer2_inode_t *dip,
1400                                hammer2_chain_t **chainp,
1401                                hammer2_chain_t **ochainp)
1402 {
1403         if (*ochainp == NULL)
1404                 return (0);
1405         /* XXX */
1406         return (0);
1407 }
1408
1409 /*
1410  * The caller presents a locked *chainp pointing to a HAMMER2_BREF_TYPE_INODE
1411  * with an obj_type of HAMMER2_OBJTYPE_HARDLINK.  This routine will gobble
1412  * the *chainp and return a new locked *chainp representing the file target
1413  * (the original *chainp will be unlocked).
1414  *
1415  * When a match is found the chain representing the original HARDLINK
1416  * will be returned in *ochainp with a ref, but not locked.
1417  *
1418  * When no match is found *chainp is set to NULL and EIO is returned.
1419  * (*ochainp) will still be set to the original chain with a ref but not
1420  * locked.
1421  */
1422 int
1423 hammer2_hardlink_find(hammer2_inode_t *dip, hammer2_chain_t **chainp,
1424                       hammer2_chain_t **ochainp)
1425 {
1426         hammer2_chain_t *chain = *chainp;
1427         hammer2_chain_t *parent;
1428         hammer2_inode_t *ip;
1429         hammer2_inode_t *pip;
1430         hammer2_key_t lhc;
1431
1432         pip = dip;
1433         hammer2_inode_ref(pip);         /* for loop */
1434         hammer2_chain_ref(chain);       /* for (*ochainp) */
1435         *ochainp = chain;
1436
1437         /*
1438          * Locate the hardlink.  pip is referenced and not locked,
1439          * ipp.
1440          *
1441          * chain is reused.
1442          */
1443         lhc = chain->data->ipdata.inum;
1444         hammer2_chain_unlock(chain);
1445         chain = NULL;
1446
1447         while ((ip = pip) != NULL) {
1448                 parent = hammer2_inode_lock_ex(ip);
1449                 hammer2_inode_drop(ip);                 /* loop */
1450                 KKASSERT(parent->bref.type == HAMMER2_BREF_TYPE_INODE);
1451                 chain = hammer2_chain_lookup(&parent, lhc, lhc, 0);
1452                 hammer2_chain_lookup_done(parent);      /* discard parent */
1453                 if (chain)
1454                         break;
1455                 pip = ip->pip;          /* safe, ip held locked */
1456                 if (pip)
1457                         hammer2_inode_ref(pip);         /* loop */
1458                 hammer2_inode_unlock_ex(ip, NULL);
1459         }
1460
1461         /*
1462          * chain is locked, ip is locked.  Unlock ip, return the locked
1463          * chain.  *ipp is already set w/a ref count and not locked.
1464          *
1465          * (parent is already unlocked).
1466          */
1467         if (ip)
1468                 hammer2_inode_unlock_ex(ip, NULL);
1469         *chainp = chain;
1470         if (chain) {
1471                 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_INODE);
1472                 /* already locked */
1473                 return (0);
1474         } else {
1475                 return (EIO);
1476         }
1477 }
1478
1479 /*
1480  * Find the directory common to both fdip and tdip, hold and return
1481  * its inode.
1482  */
1483 hammer2_inode_t *
1484 hammer2_inode_common_parent(hammer2_inode_t *fdip, hammer2_inode_t *tdip)
1485 {
1486         hammer2_inode_t *scan1;
1487         hammer2_inode_t *scan2;
1488
1489         /*
1490          * We used to have a depth field but it complicated matters too
1491          * much for directory renames.  So now its ugly.  Check for
1492          * simple cases before giving up and doing it the expensive way.
1493          *
1494          * XXX need a bottom-up topology stability lock
1495          */
1496         if (fdip == tdip || fdip == tdip->pip) {
1497                 hammer2_inode_ref(fdip);
1498                 return(fdip);
1499         }
1500         if (fdip->pip == tdip) {
1501                 hammer2_inode_ref(tdip);
1502                 return(tdip);
1503         }
1504
1505         /*
1506          * XXX not MPSAFE
1507          */
1508         for (scan1 = fdip; scan1->pmp == fdip->pmp; scan1 = scan1->pip) {
1509                 scan2 = tdip;
1510                 while (scan2->pmp == tdip->pmp) {
1511                         if (scan1 == scan2) {
1512                                 hammer2_inode_ref(scan1);
1513                                 return(scan1);
1514                         }
1515                         scan2 = scan2->pip;
1516                         if (scan2 == NULL)
1517                                 break;
1518                 }
1519         }
1520         panic("hammer2_inode_common_parent: no common parent %p %p\n",
1521               fdip, tdip);
1522         /* NOT REACHED */
1523         return(NULL);
1524 }