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