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