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