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