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