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