Merge branch 'vendor/SENDMAIL'
[dragonfly.git] / sys / vfs / hammer / hammer_inode.c
1 /*
2  * Copyright (c) 2007-2008 The DragonFly Project.  All rights reserved.
3  * 
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
6  * 
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  * 
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  * 
34  * $DragonFly: src/sys/vfs/hammer/hammer_inode.c,v 1.114 2008/09/24 00:53:51 dillon Exp $
35  */
36
37 #include "hammer.h"
38 #include <vm/vm_extern.h>
39
40 static int      hammer_unload_inode(struct hammer_inode *ip);
41 static void     hammer_free_inode(hammer_inode_t ip);
42 static void     hammer_flush_inode_core(hammer_inode_t ip,
43                                         hammer_flush_group_t flg, int flags);
44 static int      hammer_setup_child_callback(hammer_record_t rec, void *data);
45 #if 0
46 static int      hammer_syncgrp_child_callback(hammer_record_t rec, void *data);
47 #endif
48 static int      hammer_setup_parent_inodes(hammer_inode_t ip, int depth,
49                                         hammer_flush_group_t flg);
50 static int      hammer_setup_parent_inodes_helper(hammer_record_t record,
51                                         int depth, hammer_flush_group_t flg);
52 static void     hammer_inode_wakereclaims(hammer_inode_t ip);
53
54 #ifdef DEBUG_TRUNCATE
55 extern struct hammer_inode *HammerTruncIp;
56 #endif
57
58 /*
59  * RB-Tree support for inode structures
60  */
61 int
62 hammer_ino_rb_compare(hammer_inode_t ip1, hammer_inode_t ip2)
63 {
64         if (ip1->obj_localization < ip2->obj_localization)
65                 return(-1);
66         if (ip1->obj_localization > ip2->obj_localization)
67                 return(1);
68         if (ip1->obj_id < ip2->obj_id)
69                 return(-1);
70         if (ip1->obj_id > ip2->obj_id)
71                 return(1);
72         if (ip1->obj_asof < ip2->obj_asof)
73                 return(-1);
74         if (ip1->obj_asof > ip2->obj_asof)
75                 return(1);
76         return(0);
77 }
78
79 int
80 hammer_redo_rb_compare(hammer_inode_t ip1, hammer_inode_t ip2)
81 {
82         if (ip1->redo_fifo_start < ip2->redo_fifo_start)
83                 return(-1);
84         if (ip1->redo_fifo_start > ip2->redo_fifo_start)
85                 return(1);
86         return(0);
87 }
88
89 /*
90  * RB-Tree support for inode structures / special LOOKUP_INFO
91  */
92 static int
93 hammer_inode_info_cmp(hammer_inode_info_t info, hammer_inode_t ip)
94 {
95         if (info->obj_localization < ip->obj_localization)
96                 return(-1);
97         if (info->obj_localization > ip->obj_localization)
98                 return(1);
99         if (info->obj_id < ip->obj_id)
100                 return(-1);
101         if (info->obj_id > ip->obj_id)
102                 return(1);
103         if (info->obj_asof < ip->obj_asof)
104                 return(-1);
105         if (info->obj_asof > ip->obj_asof)
106                 return(1);
107         return(0);
108 }
109
110 /*
111  * Used by hammer_scan_inode_snapshots() to locate all of an object's
112  * snapshots.  Note that the asof field is not tested, which we can get
113  * away with because it is the lowest-priority field.
114  */
115 static int
116 hammer_inode_info_cmp_all_history(hammer_inode_t ip, void *data)
117 {
118         hammer_inode_info_t info = data;
119
120         if (ip->obj_localization > info->obj_localization)
121                 return(1);
122         if (ip->obj_localization < info->obj_localization)
123                 return(-1);
124         if (ip->obj_id > info->obj_id)
125                 return(1);
126         if (ip->obj_id < info->obj_id)
127                 return(-1);
128         return(0);
129 }
130
131 /*
132  * Used by hammer_unload_pseudofs() to locate all inodes associated with
133  * a particular PFS.
134  */
135 static int
136 hammer_inode_pfs_cmp(hammer_inode_t ip, void *data)
137 {
138         u_int32_t localization = *(u_int32_t *)data;
139         if (ip->obj_localization > localization)
140                 return(1);
141         if (ip->obj_localization < localization)
142                 return(-1);
143         return(0);
144 }
145
146 /*
147  * RB-Tree support for pseudofs structures
148  */
149 static int
150 hammer_pfs_rb_compare(hammer_pseudofs_inmem_t p1, hammer_pseudofs_inmem_t p2)
151 {
152         if (p1->localization < p2->localization)
153                 return(-1);
154         if (p1->localization > p2->localization)
155                 return(1);
156         return(0);
157 }
158
159
160 RB_GENERATE(hammer_ino_rb_tree, hammer_inode, rb_node, hammer_ino_rb_compare);
161 RB_GENERATE_XLOOKUP(hammer_ino_rb_tree, INFO, hammer_inode, rb_node,
162                 hammer_inode_info_cmp, hammer_inode_info_t);
163 RB_GENERATE2(hammer_pfs_rb_tree, hammer_pseudofs_inmem, rb_node,
164              hammer_pfs_rb_compare, u_int32_t, localization);
165
166 /*
167  * The kernel is not actively referencing this vnode but is still holding
168  * it cached.
169  *
170  * This is called from the frontend.
171  *
172  * MPALMOSTSAFE
173  */
174 int
175 hammer_vop_inactive(struct vop_inactive_args *ap)
176 {
177         struct hammer_inode *ip = VTOI(ap->a_vp);
178
179         /*
180          * Degenerate case
181          */
182         if (ip == NULL) {
183                 vrecycle(ap->a_vp);
184                 return(0);
185         }
186
187         /*
188          * If the inode no longer has visibility in the filesystem try to
189          * recycle it immediately, even if the inode is dirty.  Recycling
190          * it quickly allows the system to reclaim buffer cache and VM
191          * resources which can matter a lot in a heavily loaded system.
192          *
193          * This can deadlock in vfsync() if we aren't careful.
194          * 
195          * Do not queue the inode to the flusher if we still have visibility,
196          * otherwise namespace calls such as chmod will unnecessarily generate
197          * multiple inode updates.
198          */
199         if (ip->ino_data.nlinks == 0) {
200                 get_mplock();
201                 hammer_inode_unloadable_check(ip, 0);
202                 if (ip->flags & HAMMER_INODE_MODMASK)
203                         hammer_flush_inode(ip, 0);
204                 vrecycle(ap->a_vp);
205                 rel_mplock();
206         }
207         return(0);
208 }
209
210 /*
211  * Release the vnode association.  This is typically (but not always)
212  * the last reference on the inode.
213  *
214  * Once the association is lost we are on our own with regards to
215  * flushing the inode.
216  *
217  * We must interlock ip->vp so hammer_get_vnode() can avoid races.
218  */
219 int
220 hammer_vop_reclaim(struct vop_reclaim_args *ap)
221 {
222         struct hammer_inode *ip;
223         hammer_mount_t hmp;
224         struct vnode *vp;
225
226         vp = ap->a_vp;
227
228         if ((ip = vp->v_data) != NULL) {
229                 hmp = ip->hmp;
230                 hammer_lock_ex(&ip->lock);
231                 vp->v_data = NULL;
232                 ip->vp = NULL;
233
234                 if ((ip->flags & HAMMER_INODE_RECLAIM) == 0) {
235                         ++hammer_count_reclaiming;
236                         ++hmp->inode_reclaims;
237                         ip->flags |= HAMMER_INODE_RECLAIM;
238                 }
239                 hammer_unlock(&ip->lock);
240                 hammer_rel_inode(ip, 1);
241         }
242         return(0);
243 }
244
245 /*
246  * Return a locked vnode for the specified inode.  The inode must be
247  * referenced but NOT LOCKED on entry and will remain referenced on
248  * return.
249  *
250  * Called from the frontend.
251  */
252 int
253 hammer_get_vnode(struct hammer_inode *ip, struct vnode **vpp)
254 {
255         hammer_mount_t hmp;
256         struct vnode *vp;
257         int error = 0;
258         u_int8_t obj_type;
259
260         hmp = ip->hmp;
261
262         for (;;) {
263                 if ((vp = ip->vp) == NULL) {
264                         error = getnewvnode(VT_HAMMER, hmp->mp, vpp, 0, 0);
265                         if (error)
266                                 break;
267                         hammer_lock_ex(&ip->lock);
268                         if (ip->vp != NULL) {
269                                 hammer_unlock(&ip->lock);
270                                 vp = *vpp;
271                                 vp->v_type = VBAD;
272                                 vx_put(vp);
273                                 continue;
274                         }
275                         hammer_ref(&ip->lock);
276                         vp = *vpp;
277                         ip->vp = vp;
278
279                         obj_type = ip->ino_data.obj_type;
280                         vp->v_type = hammer_get_vnode_type(obj_type);
281
282                         hammer_inode_wakereclaims(ip);
283
284                         switch(ip->ino_data.obj_type) {
285                         case HAMMER_OBJTYPE_CDEV:
286                         case HAMMER_OBJTYPE_BDEV:
287                                 vp->v_ops = &hmp->mp->mnt_vn_spec_ops;
288                                 addaliasu(vp, ip->ino_data.rmajor,
289                                           ip->ino_data.rminor);
290                                 break;
291                         case HAMMER_OBJTYPE_FIFO:
292                                 vp->v_ops = &hmp->mp->mnt_vn_fifo_ops;
293                                 break;
294                         case HAMMER_OBJTYPE_REGFILE:
295                                 break;
296                         default:
297                                 break;
298                         }
299
300                         /*
301                          * Only mark as the root vnode if the ip is not
302                          * historical, otherwise the VFS cache will get
303                          * confused.  The other half of the special handling
304                          * is in hammer_vop_nlookupdotdot().
305                          *
306                          * Pseudo-filesystem roots can be accessed via
307                          * non-root filesystem paths and setting VROOT may
308                          * confuse the namecache.  Set VPFSROOT instead.
309                          */
310                         if (ip->obj_id == HAMMER_OBJID_ROOT &&
311                             ip->obj_asof == hmp->asof) {
312                                 if (ip->obj_localization == 0)
313                                         vsetflags(vp, VROOT);
314                                 else
315                                         vsetflags(vp, VPFSROOT);
316                         }
317
318                         vp->v_data = (void *)ip;
319                         /* vnode locked by getnewvnode() */
320                         /* make related vnode dirty if inode dirty? */
321                         hammer_unlock(&ip->lock);
322                         if (vp->v_type == VREG)
323                                 vinitvmio(vp, ip->ino_data.size);
324                         break;
325                 }
326
327                 /*
328                  * Interlock vnode clearing.  This does not prevent the
329                  * vnode from going into a reclaimed state but it does
330                  * prevent it from being destroyed or reused so the vget()
331                  * will properly fail.
332                  */
333                 hammer_lock_ex(&ip->lock);
334                 if ((vp = ip->vp) == NULL) {
335                         hammer_unlock(&ip->lock);
336                         continue;
337                 }
338                 vhold_interlocked(vp);
339                 hammer_unlock(&ip->lock);
340
341                 /*
342                  * loop if the vget fails (aka races), or if the vp
343                  * no longer matches ip->vp.
344                  */
345                 if (vget(vp, LK_EXCLUSIVE) == 0) {
346                         if (vp == ip->vp) {
347                                 vdrop(vp);
348                                 break;
349                         }
350                         vput(vp);
351                 }
352                 vdrop(vp);
353         }
354         *vpp = vp;
355         return(error);
356 }
357
358 /*
359  * Locate all copies of the inode for obj_id compatible with the specified
360  * asof, reference, and issue the related call-back.  This routine is used
361  * for direct-io invalidation and does not create any new inodes.
362  */
363 void
364 hammer_scan_inode_snapshots(hammer_mount_t hmp, hammer_inode_info_t iinfo,
365                             int (*callback)(hammer_inode_t ip, void *data),
366                             void *data)
367 {
368         hammer_ino_rb_tree_RB_SCAN(&hmp->rb_inos_root,
369                                    hammer_inode_info_cmp_all_history,
370                                    callback, iinfo);
371 }
372
373 /*
374  * Acquire a HAMMER inode.  The returned inode is not locked.  These functions
375  * do not attach or detach the related vnode (use hammer_get_vnode() for
376  * that).
377  *
378  * The flags argument is only applied for newly created inodes, and only
379  * certain flags are inherited.
380  *
381  * Called from the frontend.
382  */
383 struct hammer_inode *
384 hammer_get_inode(hammer_transaction_t trans, hammer_inode_t dip,
385                  int64_t obj_id, hammer_tid_t asof, u_int32_t localization,
386                  int flags, int *errorp)
387 {
388         hammer_mount_t hmp = trans->hmp;
389         struct hammer_node_cache *cachep;
390         struct hammer_inode_info iinfo;
391         struct hammer_cursor cursor;
392         struct hammer_inode *ip;
393
394
395         /*
396          * Determine if we already have an inode cached.  If we do then
397          * we are golden.
398          *
399          * If we find an inode with no vnode we have to mark the
400          * transaction such that hammer_inode_waitreclaims() is
401          * called later on to avoid building up an infinite number
402          * of inodes.  Otherwise we can continue to * add new inodes
403          * faster then they can be disposed of, even with the tsleep
404          * delay.
405          *
406          * If we find a dummy inode we return a failure so dounlink
407          * (which does another lookup) doesn't try to mess with the
408          * link count.  hammer_vop_nresolve() uses hammer_get_dummy_inode()
409          * to ref dummy inodes.
410          */
411         iinfo.obj_id = obj_id;
412         iinfo.obj_asof = asof;
413         iinfo.obj_localization = localization;
414 loop:
415         ip = hammer_ino_rb_tree_RB_LOOKUP_INFO(&hmp->rb_inos_root, &iinfo);
416         if (ip) {
417                 if (ip->flags & HAMMER_INODE_DUMMY) {
418                         *errorp = ENOENT;
419                         return(NULL);
420                 }
421                 hammer_ref(&ip->lock);
422                 *errorp = 0;
423                 return(ip);
424         }
425
426         /*
427          * Allocate a new inode structure and deal with races later.
428          */
429         ip = kmalloc(sizeof(*ip), hmp->m_inodes, M_WAITOK|M_ZERO);
430         ++hammer_count_inodes;
431         ++hmp->count_inodes;
432         ip->obj_id = obj_id;
433         ip->obj_asof = iinfo.obj_asof;
434         ip->obj_localization = localization;
435         ip->hmp = hmp;
436         ip->flags = flags & HAMMER_INODE_RO;
437         ip->cache[0].ip = ip;
438         ip->cache[1].ip = ip;
439         ip->cache[2].ip = ip;
440         ip->cache[3].ip = ip;
441         if (hmp->ronly)
442                 ip->flags |= HAMMER_INODE_RO;
443         ip->sync_trunc_off = ip->trunc_off = ip->save_trunc_off =
444                 0x7FFFFFFFFFFFFFFFLL;
445         RB_INIT(&ip->rec_tree);
446         TAILQ_INIT(&ip->target_list);
447         hammer_ref(&ip->lock);
448
449         /*
450          * Locate the on-disk inode.  If this is a PFS root we always
451          * access the current version of the root inode and (if it is not
452          * a master) always access information under it with a snapshot
453          * TID.
454          *
455          * We cache recent inode lookups in this directory in dip->cache[2].
456          * If we can't find it we assume the inode we are looking for is
457          * close to the directory inode.
458          */
459 retry:
460         cachep = NULL;
461         if (dip) {
462                 if (dip->cache[2].node)
463                         cachep = &dip->cache[2];
464                 else
465                         cachep = &dip->cache[0];
466         }
467         hammer_init_cursor(trans, &cursor, cachep, NULL);
468         cursor.key_beg.localization = localization + HAMMER_LOCALIZE_INODE;
469         cursor.key_beg.obj_id = ip->obj_id;
470         cursor.key_beg.key = 0;
471         cursor.key_beg.create_tid = 0;
472         cursor.key_beg.delete_tid = 0;
473         cursor.key_beg.rec_type = HAMMER_RECTYPE_INODE;
474         cursor.key_beg.obj_type = 0;
475
476         cursor.asof = iinfo.obj_asof;
477         cursor.flags = HAMMER_CURSOR_GET_LEAF | HAMMER_CURSOR_GET_DATA |
478                        HAMMER_CURSOR_ASOF;
479
480         *errorp = hammer_btree_lookup(&cursor);
481         if (*errorp == EDEADLK) {
482                 hammer_done_cursor(&cursor);
483                 goto retry;
484         }
485
486         /*
487          * On success the B-Tree lookup will hold the appropriate
488          * buffer cache buffers and provide a pointer to the requested
489          * information.  Copy the information to the in-memory inode
490          * and cache the B-Tree node to improve future operations.
491          */
492         if (*errorp == 0) {
493                 ip->ino_leaf = cursor.node->ondisk->elms[cursor.index].leaf;
494                 ip->ino_data = cursor.data->inode;
495
496                 /*
497                  * cache[0] tries to cache the location of the object inode.
498                  * The assumption is that it is near the directory inode.
499                  *
500                  * cache[1] tries to cache the location of the object data.
501                  * We might have something in the governing directory from
502                  * scan optimizations (see the strategy code in
503                  * hammer_vnops.c).
504                  *
505                  * We update dip->cache[2], if possible, with the location
506                  * of the object inode for future directory shortcuts.
507                  */
508                 hammer_cache_node(&ip->cache[0], cursor.node);
509                 if (dip) {
510                         if (dip->cache[3].node) {
511                                 hammer_cache_node(&ip->cache[1],
512                                                   dip->cache[3].node);
513                         }
514                         hammer_cache_node(&dip->cache[2], cursor.node);
515                 }
516
517                 /*
518                  * The file should not contain any data past the file size
519                  * stored in the inode.  Setting save_trunc_off to the
520                  * file size instead of max reduces B-Tree lookup overheads
521                  * on append by allowing the flusher to avoid checking for
522                  * record overwrites.
523                  */
524                 ip->save_trunc_off = ip->ino_data.size;
525
526                 /*
527                  * Locate and assign the pseudofs management structure to
528                  * the inode.
529                  */
530                 if (dip && dip->obj_localization == ip->obj_localization) {
531                         ip->pfsm = dip->pfsm;
532                         hammer_ref(&ip->pfsm->lock);
533                 } else {
534                         ip->pfsm = hammer_load_pseudofs(trans,
535                                                         ip->obj_localization,
536                                                         errorp);
537                         *errorp = 0;    /* ignore ENOENT */
538                 }
539         }
540
541         /*
542          * The inode is placed on the red-black tree and will be synced to
543          * the media when flushed or by the filesystem sync.  If this races
544          * another instantiation/lookup the insertion will fail.
545          */
546         if (*errorp == 0) {
547                 if (RB_INSERT(hammer_ino_rb_tree, &hmp->rb_inos_root, ip)) {
548                         hammer_free_inode(ip);
549                         hammer_done_cursor(&cursor);
550                         goto loop;
551                 }
552                 ip->flags |= HAMMER_INODE_ONDISK;
553         } else {
554                 if (ip->flags & HAMMER_INODE_RSV_INODES) {
555                         ip->flags &= ~HAMMER_INODE_RSV_INODES; /* sanity */
556                         --hmp->rsv_inodes;
557                 }
558
559                 hammer_free_inode(ip);
560                 ip = NULL;
561         }
562         hammer_done_cursor(&cursor);
563         trans->flags |= HAMMER_TRANSF_NEWINODE;
564         return (ip);
565 }
566
567 /*
568  * Get a dummy inode to placemark a broken directory entry.
569  */
570 struct hammer_inode *
571 hammer_get_dummy_inode(hammer_transaction_t trans, hammer_inode_t dip,
572                  int64_t obj_id, hammer_tid_t asof, u_int32_t localization,
573                  int flags, int *errorp)
574 {
575         hammer_mount_t hmp = trans->hmp;
576         struct hammer_inode_info iinfo;
577         struct hammer_inode *ip;
578
579         /*
580          * Determine if we already have an inode cached.  If we do then
581          * we are golden.
582          *
583          * If we find an inode with no vnode we have to mark the
584          * transaction such that hammer_inode_waitreclaims() is
585          * called later on to avoid building up an infinite number
586          * of inodes.  Otherwise we can continue to * add new inodes
587          * faster then they can be disposed of, even with the tsleep
588          * delay.
589          *
590          * If we find a non-fake inode we return an error.  Only fake
591          * inodes can be returned by this routine.
592          */
593         iinfo.obj_id = obj_id;
594         iinfo.obj_asof = asof;
595         iinfo.obj_localization = localization;
596 loop:
597         *errorp = 0;
598         ip = hammer_ino_rb_tree_RB_LOOKUP_INFO(&hmp->rb_inos_root, &iinfo);
599         if (ip) {
600                 if ((ip->flags & HAMMER_INODE_DUMMY) == 0) {
601                         *errorp = ENOENT;
602                         return(NULL);
603                 }
604                 hammer_ref(&ip->lock);
605                 return(ip);
606         }
607
608         /*
609          * Allocate a new inode structure and deal with races later.
610          */
611         ip = kmalloc(sizeof(*ip), hmp->m_inodes, M_WAITOK|M_ZERO);
612         ++hammer_count_inodes;
613         ++hmp->count_inodes;
614         ip->obj_id = obj_id;
615         ip->obj_asof = iinfo.obj_asof;
616         ip->obj_localization = localization;
617         ip->hmp = hmp;
618         ip->flags = flags | HAMMER_INODE_RO | HAMMER_INODE_DUMMY;
619         ip->cache[0].ip = ip;
620         ip->cache[1].ip = ip;
621         ip->cache[2].ip = ip;
622         ip->cache[3].ip = ip;
623         ip->sync_trunc_off = ip->trunc_off = ip->save_trunc_off =
624                 0x7FFFFFFFFFFFFFFFLL;
625         RB_INIT(&ip->rec_tree);
626         TAILQ_INIT(&ip->target_list);
627         hammer_ref(&ip->lock);
628
629         /*
630          * Populate the dummy inode.  Leave everything zero'd out.
631          *
632          * (ip->ino_leaf and ip->ino_data)
633          *
634          * Make the dummy inode a FIFO object which most copy programs
635          * will properly ignore.
636          */
637         ip->save_trunc_off = ip->ino_data.size;
638         ip->ino_data.obj_type = HAMMER_OBJTYPE_FIFO;
639
640         /*
641          * Locate and assign the pseudofs management structure to
642          * the inode.
643          */
644         if (dip && dip->obj_localization == ip->obj_localization) {
645                 ip->pfsm = dip->pfsm;
646                 hammer_ref(&ip->pfsm->lock);
647         } else {
648                 ip->pfsm = hammer_load_pseudofs(trans, ip->obj_localization,
649                                                 errorp);
650                 *errorp = 0;    /* ignore ENOENT */
651         }
652
653         /*
654          * The inode is placed on the red-black tree and will be synced to
655          * the media when flushed or by the filesystem sync.  If this races
656          * another instantiation/lookup the insertion will fail.
657          *
658          * NOTE: Do not set HAMMER_INODE_ONDISK.  The inode is a fake.
659          */
660         if (*errorp == 0) {
661                 if (RB_INSERT(hammer_ino_rb_tree, &hmp->rb_inos_root, ip)) {
662                         hammer_free_inode(ip);
663                         goto loop;
664                 }
665         } else {
666                 if (ip->flags & HAMMER_INODE_RSV_INODES) {
667                         ip->flags &= ~HAMMER_INODE_RSV_INODES; /* sanity */
668                         --hmp->rsv_inodes;
669                 }
670                 hammer_free_inode(ip);
671                 ip = NULL;
672         }
673         trans->flags |= HAMMER_TRANSF_NEWINODE;
674         return (ip);
675 }
676
677 /*
678  * Return a referenced inode only if it is in our inode cache.
679  *
680  * Dummy inodes do not count.
681  */
682 struct hammer_inode *
683 hammer_find_inode(hammer_transaction_t trans, int64_t obj_id,
684                   hammer_tid_t asof, u_int32_t localization)
685 {
686         hammer_mount_t hmp = trans->hmp;
687         struct hammer_inode_info iinfo;
688         struct hammer_inode *ip;
689
690         iinfo.obj_id = obj_id;
691         iinfo.obj_asof = asof;
692         iinfo.obj_localization = localization;
693
694         ip = hammer_ino_rb_tree_RB_LOOKUP_INFO(&hmp->rb_inos_root, &iinfo);
695         if (ip) {
696                 if (ip->flags & HAMMER_INODE_DUMMY)
697                         ip = NULL;
698                 else
699                         hammer_ref(&ip->lock);
700         }
701         return(ip);
702 }
703
704 /*
705  * Create a new filesystem object, returning the inode in *ipp.  The
706  * returned inode will be referenced.  The inode is created in-memory.
707  *
708  * If pfsm is non-NULL the caller wishes to create the root inode for
709  * a master PFS.
710  */
711 int
712 hammer_create_inode(hammer_transaction_t trans, struct vattr *vap,
713                     struct ucred *cred,
714                     hammer_inode_t dip, const char *name, int namelen,
715                     hammer_pseudofs_inmem_t pfsm, struct hammer_inode **ipp)
716 {
717         hammer_mount_t hmp;
718         hammer_inode_t ip;
719         uid_t xuid;
720         int error;
721         int64_t namekey;
722         u_int32_t dummy;
723
724         hmp = trans->hmp;
725
726         ip = kmalloc(sizeof(*ip), hmp->m_inodes, M_WAITOK|M_ZERO);
727         ++hammer_count_inodes;
728         ++hmp->count_inodes;
729         trans->flags |= HAMMER_TRANSF_NEWINODE;
730
731         if (pfsm) {
732                 KKASSERT(pfsm->localization != 0);
733                 ip->obj_id = HAMMER_OBJID_ROOT;
734                 ip->obj_localization = pfsm->localization;
735         } else {
736                 KKASSERT(dip != NULL);
737                 namekey = hammer_directory_namekey(dip, name, namelen, &dummy);
738                 ip->obj_id = hammer_alloc_objid(hmp, dip, namekey);
739                 ip->obj_localization = dip->obj_localization;
740         }
741
742         KKASSERT(ip->obj_id != 0);
743         ip->obj_asof = hmp->asof;
744         ip->hmp = hmp;
745         ip->flush_state = HAMMER_FST_IDLE;
746         ip->flags = HAMMER_INODE_DDIRTY |
747                     HAMMER_INODE_ATIME | HAMMER_INODE_MTIME;
748         ip->cache[0].ip = ip;
749         ip->cache[1].ip = ip;
750         ip->cache[2].ip = ip;
751         ip->cache[3].ip = ip;
752
753         ip->trunc_off = 0x7FFFFFFFFFFFFFFFLL;
754         /* ip->save_trunc_off = 0; (already zero) */
755         RB_INIT(&ip->rec_tree);
756         TAILQ_INIT(&ip->target_list);
757
758         ip->ino_data.atime = trans->time;
759         ip->ino_data.mtime = trans->time;
760         ip->ino_data.size = 0;
761         ip->ino_data.nlinks = 0;
762
763         /*
764          * A nohistory designator on the parent directory is inherited by
765          * the child.  We will do this even for pseudo-fs creation... the
766          * sysad can turn it off.
767          */
768         if (dip) {
769                 ip->ino_data.uflags = dip->ino_data.uflags &
770                                       (SF_NOHISTORY|UF_NOHISTORY|UF_NODUMP);
771         }
772
773         ip->ino_leaf.base.btype = HAMMER_BTREE_TYPE_RECORD;
774         ip->ino_leaf.base.localization = ip->obj_localization +
775                                          HAMMER_LOCALIZE_INODE;
776         ip->ino_leaf.base.obj_id = ip->obj_id;
777         ip->ino_leaf.base.key = 0;
778         ip->ino_leaf.base.create_tid = 0;
779         ip->ino_leaf.base.delete_tid = 0;
780         ip->ino_leaf.base.rec_type = HAMMER_RECTYPE_INODE;
781         ip->ino_leaf.base.obj_type = hammer_get_obj_type(vap->va_type);
782
783         ip->ino_data.obj_type = ip->ino_leaf.base.obj_type;
784         ip->ino_data.version = HAMMER_INODE_DATA_VERSION;
785         ip->ino_data.mode = vap->va_mode;
786         ip->ino_data.ctime = trans->time;
787
788         /*
789          * If we are running version 2 or greater directory entries are
790          * inode-localized instead of data-localized.
791          */
792         if (trans->hmp->version >= HAMMER_VOL_VERSION_TWO) {
793                 if (ip->ino_leaf.base.obj_type == HAMMER_OBJTYPE_DIRECTORY) {
794                         ip->ino_data.cap_flags |=
795                                 HAMMER_INODE_CAP_DIR_LOCAL_INO;
796                 }
797         }
798
799         /*
800          * Setup the ".." pointer.  This only needs to be done for directories
801          * but we do it for all objects as a recovery aid.
802          */
803         if (dip)
804                 ip->ino_data.parent_obj_id = dip->ino_leaf.base.obj_id;
805 #if 0
806         /*
807          * The parent_obj_localization field only applies to pseudo-fs roots.
808          * XXX this is no longer applicable, PFSs are no longer directly
809          * tied into the parent's directory structure.
810          */
811         if (ip->ino_data.obj_type == HAMMER_OBJTYPE_DIRECTORY &&
812             ip->obj_id == HAMMER_OBJID_ROOT) {
813                 ip->ino_data.ext.obj.parent_obj_localization = 
814                                                 dip->obj_localization;
815         }
816 #endif
817
818         switch(ip->ino_leaf.base.obj_type) {
819         case HAMMER_OBJTYPE_CDEV:
820         case HAMMER_OBJTYPE_BDEV:
821                 ip->ino_data.rmajor = vap->va_rmajor;
822                 ip->ino_data.rminor = vap->va_rminor;
823                 break;
824         default:
825                 break;
826         }
827
828         /*
829          * Calculate default uid/gid and overwrite with information from
830          * the vap.
831          */
832         if (dip) {
833                 xuid = hammer_to_unix_xid(&dip->ino_data.uid);
834                 xuid = vop_helper_create_uid(hmp->mp, dip->ino_data.mode,
835                                              xuid, cred, &vap->va_mode);
836         } else {
837                 xuid = 0;
838         }
839         ip->ino_data.mode = vap->va_mode;
840
841         if (vap->va_vaflags & VA_UID_UUID_VALID)
842                 ip->ino_data.uid = vap->va_uid_uuid;
843         else if (vap->va_uid != (uid_t)VNOVAL)
844                 hammer_guid_to_uuid(&ip->ino_data.uid, vap->va_uid);
845         else
846                 hammer_guid_to_uuid(&ip->ino_data.uid, xuid);
847
848         if (vap->va_vaflags & VA_GID_UUID_VALID)
849                 ip->ino_data.gid = vap->va_gid_uuid;
850         else if (vap->va_gid != (gid_t)VNOVAL)
851                 hammer_guid_to_uuid(&ip->ino_data.gid, vap->va_gid);
852         else if (dip)
853                 ip->ino_data.gid = dip->ino_data.gid;
854
855         hammer_ref(&ip->lock);
856
857         if (pfsm) {
858                 ip->pfsm = pfsm;
859                 hammer_ref(&pfsm->lock);
860                 error = 0;
861         } else if (dip->obj_localization == ip->obj_localization) {
862                 ip->pfsm = dip->pfsm;
863                 hammer_ref(&ip->pfsm->lock);
864                 error = 0;
865         } else {
866                 ip->pfsm = hammer_load_pseudofs(trans,
867                                                 ip->obj_localization,
868                                                 &error);
869                 error = 0;      /* ignore ENOENT */
870         }
871
872         if (error) {
873                 hammer_free_inode(ip);
874                 ip = NULL;
875         } else if (RB_INSERT(hammer_ino_rb_tree, &hmp->rb_inos_root, ip)) {
876                 panic("hammer_create_inode: duplicate obj_id %llx",
877                       (long long)ip->obj_id);
878                 /* not reached */
879                 hammer_free_inode(ip);
880         }
881         *ipp = ip;
882         return(error);
883 }
884
885 /*
886  * Final cleanup / freeing of an inode structure
887  */
888 static void
889 hammer_free_inode(hammer_inode_t ip)
890 {
891         struct hammer_mount *hmp;
892
893         hmp = ip->hmp;
894         KKASSERT(ip->lock.refs == 1);
895         hammer_uncache_node(&ip->cache[0]);
896         hammer_uncache_node(&ip->cache[1]);
897         hammer_uncache_node(&ip->cache[2]);
898         hammer_uncache_node(&ip->cache[3]);
899         hammer_inode_wakereclaims(ip);
900         if (ip->objid_cache)
901                 hammer_clear_objid(ip);
902         --hammer_count_inodes;
903         --hmp->count_inodes;
904         if (ip->pfsm) {
905                 hammer_rel_pseudofs(hmp, ip->pfsm);
906                 ip->pfsm = NULL;
907         }
908         kfree(ip, hmp->m_inodes);
909         ip = NULL;
910 }
911
912 /*
913  * Retrieve pseudo-fs data.  NULL will never be returned.
914  *
915  * If an error occurs *errorp will be set and a default template is returned,
916  * otherwise *errorp is set to 0.  Typically when an error occurs it will
917  * be ENOENT.
918  */
919 hammer_pseudofs_inmem_t
920 hammer_load_pseudofs(hammer_transaction_t trans,
921                      u_int32_t localization, int *errorp)
922 {
923         hammer_mount_t hmp = trans->hmp;
924         hammer_inode_t ip;
925         hammer_pseudofs_inmem_t pfsm;
926         struct hammer_cursor cursor;
927         int bytes;
928
929 retry:
930         pfsm = RB_LOOKUP(hammer_pfs_rb_tree, &hmp->rb_pfsm_root, localization);
931         if (pfsm) {
932                 hammer_ref(&pfsm->lock);
933                 *errorp = 0;
934                 return(pfsm);
935         }
936
937         /*
938          * PFS records are stored in the root inode (not the PFS root inode,
939          * but the real root).  Avoid an infinite recursion if loading
940          * the PFS for the real root.
941          */
942         if (localization) {
943                 ip = hammer_get_inode(trans, NULL, HAMMER_OBJID_ROOT,
944                                       HAMMER_MAX_TID,
945                                       HAMMER_DEF_LOCALIZATION, 0, errorp);
946         } else {
947                 ip = NULL;
948         }
949
950         pfsm = kmalloc(sizeof(*pfsm), hmp->m_misc, M_WAITOK | M_ZERO);
951         pfsm->localization = localization;
952         pfsm->pfsd.unique_uuid = trans->rootvol->ondisk->vol_fsid;
953         pfsm->pfsd.shared_uuid = pfsm->pfsd.unique_uuid;
954
955         hammer_init_cursor(trans, &cursor, (ip ? &ip->cache[1] : NULL), ip);
956         cursor.key_beg.localization = HAMMER_DEF_LOCALIZATION +
957                                       HAMMER_LOCALIZE_MISC;
958         cursor.key_beg.obj_id = HAMMER_OBJID_ROOT;
959         cursor.key_beg.create_tid = 0;
960         cursor.key_beg.delete_tid = 0;
961         cursor.key_beg.rec_type = HAMMER_RECTYPE_PFS;
962         cursor.key_beg.obj_type = 0;
963         cursor.key_beg.key = localization;
964         cursor.asof = HAMMER_MAX_TID;
965         cursor.flags |= HAMMER_CURSOR_ASOF;
966
967         if (ip)
968                 *errorp = hammer_ip_lookup(&cursor);
969         else
970                 *errorp = hammer_btree_lookup(&cursor);
971         if (*errorp == 0) {
972                 *errorp = hammer_ip_resolve_data(&cursor);
973                 if (*errorp == 0) {
974                         if (cursor.data->pfsd.mirror_flags &
975                             HAMMER_PFSD_DELETED) {
976                                 *errorp = ENOENT;
977                         } else {
978                                 bytes = cursor.leaf->data_len;
979                                 if (bytes > sizeof(pfsm->pfsd))
980                                         bytes = sizeof(pfsm->pfsd);
981                                 bcopy(cursor.data, &pfsm->pfsd, bytes);
982                         }
983                 }
984         }
985         hammer_done_cursor(&cursor);
986
987         pfsm->fsid_udev = hammer_fsid_to_udev(&pfsm->pfsd.shared_uuid);
988         hammer_ref(&pfsm->lock);
989         if (ip)
990                 hammer_rel_inode(ip, 0);
991         if (RB_INSERT(hammer_pfs_rb_tree, &hmp->rb_pfsm_root, pfsm)) {
992                 kfree(pfsm, hmp->m_misc);
993                 goto retry;
994         }
995         return(pfsm);
996 }
997
998 /*
999  * Store pseudo-fs data.  The backend will automatically delete any prior
1000  * on-disk pseudo-fs data but we have to delete in-memory versions.
1001  */
1002 int
1003 hammer_save_pseudofs(hammer_transaction_t trans, hammer_pseudofs_inmem_t pfsm)
1004 {
1005         struct hammer_cursor cursor;
1006         hammer_record_t record;
1007         hammer_inode_t ip;
1008         int error;
1009
1010         ip = hammer_get_inode(trans, NULL, HAMMER_OBJID_ROOT, HAMMER_MAX_TID,
1011                               HAMMER_DEF_LOCALIZATION, 0, &error);
1012 retry:
1013         pfsm->fsid_udev = hammer_fsid_to_udev(&pfsm->pfsd.shared_uuid);
1014         hammer_init_cursor(trans, &cursor, &ip->cache[1], ip);
1015         cursor.key_beg.localization = ip->obj_localization +
1016                                       HAMMER_LOCALIZE_MISC;
1017         cursor.key_beg.obj_id = HAMMER_OBJID_ROOT;
1018         cursor.key_beg.create_tid = 0;
1019         cursor.key_beg.delete_tid = 0;
1020         cursor.key_beg.rec_type = HAMMER_RECTYPE_PFS;
1021         cursor.key_beg.obj_type = 0;
1022         cursor.key_beg.key = pfsm->localization;
1023         cursor.asof = HAMMER_MAX_TID;
1024         cursor.flags |= HAMMER_CURSOR_ASOF;
1025
1026         /*
1027          * Replace any in-memory version of the record.
1028          */
1029         error = hammer_ip_lookup(&cursor);
1030         if (error == 0 && hammer_cursor_inmem(&cursor)) {
1031                 record = cursor.iprec;
1032                 if (record->flags & HAMMER_RECF_INTERLOCK_BE) {
1033                         KKASSERT(cursor.deadlk_rec == NULL);
1034                         hammer_ref(&record->lock);
1035                         cursor.deadlk_rec = record;
1036                         error = EDEADLK;
1037                 } else {
1038                         record->flags |= HAMMER_RECF_DELETED_FE;
1039                         error = 0;
1040                 }
1041         }
1042
1043         /*
1044          * Allocate replacement general record.  The backend flush will
1045          * delete any on-disk version of the record.
1046          */
1047         if (error == 0 || error == ENOENT) {
1048                 record = hammer_alloc_mem_record(ip, sizeof(pfsm->pfsd));
1049                 record->type = HAMMER_MEM_RECORD_GENERAL;
1050
1051                 record->leaf.base.localization = ip->obj_localization +
1052                                                  HAMMER_LOCALIZE_MISC;
1053                 record->leaf.base.rec_type = HAMMER_RECTYPE_PFS;
1054                 record->leaf.base.key = pfsm->localization;
1055                 record->leaf.data_len = sizeof(pfsm->pfsd);
1056                 bcopy(&pfsm->pfsd, record->data, sizeof(pfsm->pfsd));
1057                 error = hammer_ip_add_record(trans, record);
1058         }
1059         hammer_done_cursor(&cursor);
1060         if (error == EDEADLK)
1061                 goto retry;
1062         hammer_rel_inode(ip, 0);
1063         return(error);
1064 }
1065
1066 /*
1067  * Create a root directory for a PFS if one does not alredy exist.
1068  *
1069  * The PFS root stands alone so we must also bump the nlinks count
1070  * to prevent it from being destroyed on release.
1071  */
1072 int
1073 hammer_mkroot_pseudofs(hammer_transaction_t trans, struct ucred *cred,
1074                        hammer_pseudofs_inmem_t pfsm)
1075 {
1076         hammer_inode_t ip;
1077         struct vattr vap;
1078         int error;
1079
1080         ip = hammer_get_inode(trans, NULL, HAMMER_OBJID_ROOT, HAMMER_MAX_TID,
1081                               pfsm->localization, 0, &error);
1082         if (ip == NULL) {
1083                 vattr_null(&vap);
1084                 vap.va_mode = 0755;
1085                 vap.va_type = VDIR;
1086                 error = hammer_create_inode(trans, &vap, cred,
1087                                             NULL, NULL, 0,
1088                                             pfsm, &ip);
1089                 if (error == 0) {
1090                         ++ip->ino_data.nlinks;
1091                         hammer_modify_inode(ip, HAMMER_INODE_DDIRTY);
1092                 }
1093         }
1094         if (ip)
1095                 hammer_rel_inode(ip, 0);
1096         return(error);
1097 }
1098
1099 /*
1100  * Unload any vnodes & inodes associated with a PFS, return ENOTEMPTY
1101  * if we are unable to disassociate all the inodes.
1102  */
1103 static
1104 int
1105 hammer_unload_pseudofs_callback(hammer_inode_t ip, void *data)
1106 {
1107         int res;
1108
1109         hammer_ref(&ip->lock);
1110         if (ip->lock.refs == 2 && ip->vp)
1111                 vclean_unlocked(ip->vp);
1112         if (ip->lock.refs == 1 && ip->vp == NULL)
1113                 res = 0;
1114         else
1115                 res = -1;       /* stop, someone is using the inode */
1116         hammer_rel_inode(ip, 0);
1117         return(res);
1118 }
1119
1120 int
1121 hammer_unload_pseudofs(hammer_transaction_t trans, u_int32_t localization)
1122 {
1123         int res;
1124         int try;
1125
1126         for (try = res = 0; try < 4; ++try) {
1127                 res = hammer_ino_rb_tree_RB_SCAN(&trans->hmp->rb_inos_root,
1128                                            hammer_inode_pfs_cmp,
1129                                            hammer_unload_pseudofs_callback,
1130                                            &localization);
1131                 if (res == 0 && try > 1)
1132                         break;
1133                 hammer_flusher_sync(trans->hmp);
1134         }
1135         if (res != 0)
1136                 res = ENOTEMPTY;
1137         return(res);
1138 }
1139
1140
1141 /*
1142  * Release a reference on a PFS
1143  */
1144 void
1145 hammer_rel_pseudofs(hammer_mount_t hmp, hammer_pseudofs_inmem_t pfsm)
1146 {
1147         hammer_unref(&pfsm->lock);
1148         if (pfsm->lock.refs == 0) {
1149                 RB_REMOVE(hammer_pfs_rb_tree, &hmp->rb_pfsm_root, pfsm);
1150                 kfree(pfsm, hmp->m_misc);
1151         }
1152 }
1153
1154 /*
1155  * Called by hammer_sync_inode().
1156  */
1157 static int
1158 hammer_update_inode(hammer_cursor_t cursor, hammer_inode_t ip)
1159 {
1160         hammer_transaction_t trans = cursor->trans;
1161         hammer_record_t record;
1162         int error;
1163         int redirty;
1164
1165 retry:
1166         error = 0;
1167
1168         /*
1169          * If the inode has a presence on-disk then locate it and mark
1170          * it deleted, setting DELONDISK.
1171          *
1172          * The record may or may not be physically deleted, depending on
1173          * the retention policy.
1174          */
1175         if ((ip->flags & (HAMMER_INODE_ONDISK|HAMMER_INODE_DELONDISK)) ==
1176             HAMMER_INODE_ONDISK) {
1177                 hammer_normalize_cursor(cursor);
1178                 cursor->key_beg.localization = ip->obj_localization + 
1179                                                HAMMER_LOCALIZE_INODE;
1180                 cursor->key_beg.obj_id = ip->obj_id;
1181                 cursor->key_beg.key = 0;
1182                 cursor->key_beg.create_tid = 0;
1183                 cursor->key_beg.delete_tid = 0;
1184                 cursor->key_beg.rec_type = HAMMER_RECTYPE_INODE;
1185                 cursor->key_beg.obj_type = 0;
1186                 cursor->asof = ip->obj_asof;
1187                 cursor->flags &= ~HAMMER_CURSOR_INITMASK;
1188                 cursor->flags |= HAMMER_CURSOR_GET_LEAF | HAMMER_CURSOR_ASOF;
1189                 cursor->flags |= HAMMER_CURSOR_BACKEND;
1190
1191                 error = hammer_btree_lookup(cursor);
1192                 if (hammer_debug_inode)
1193                         kprintf("IPDEL %p %08x %d", ip, ip->flags, error);
1194
1195                 if (error == 0) {
1196                         error = hammer_ip_delete_record(cursor, ip, trans->tid);
1197                         if (hammer_debug_inode)
1198                                 kprintf(" error %d\n", error);
1199                         if (error == 0) {
1200                                 ip->flags |= HAMMER_INODE_DELONDISK;
1201                         }
1202                         if (cursor->node)
1203                                 hammer_cache_node(&ip->cache[0], cursor->node);
1204                 }
1205                 if (error == EDEADLK) {
1206                         hammer_done_cursor(cursor);
1207                         error = hammer_init_cursor(trans, cursor,
1208                                                    &ip->cache[0], ip);
1209                         if (hammer_debug_inode)
1210                                 kprintf("IPDED %p %d\n", ip, error);
1211                         if (error == 0)
1212                                 goto retry;
1213                 }
1214         }
1215
1216         /*
1217          * Ok, write out the initial record or a new record (after deleting
1218          * the old one), unless the DELETED flag is set.  This routine will
1219          * clear DELONDISK if it writes out a record.
1220          *
1221          * Update our inode statistics if this is the first application of
1222          * the inode on-disk.
1223          */
1224         if (error == 0 && (ip->flags & HAMMER_INODE_DELETED) == 0) {
1225                 /*
1226                  * Generate a record and write it to the media.  We clean-up
1227                  * the state before releasing so we do not have to set-up
1228                  * a flush_group.
1229                  */
1230                 record = hammer_alloc_mem_record(ip, 0);
1231                 record->type = HAMMER_MEM_RECORD_INODE;
1232                 record->flush_state = HAMMER_FST_FLUSH;
1233                 record->leaf = ip->sync_ino_leaf;
1234                 record->leaf.base.create_tid = trans->tid;
1235                 record->leaf.data_len = sizeof(ip->sync_ino_data);
1236                 record->leaf.create_ts = trans->time32;
1237                 record->data = (void *)&ip->sync_ino_data;
1238                 record->flags |= HAMMER_RECF_INTERLOCK_BE;
1239
1240                 /*
1241                  * If this flag is set we cannot sync the new file size
1242                  * because we haven't finished related truncations.  The
1243                  * inode will be flushed in another flush group to finish
1244                  * the job.
1245                  */
1246                 if ((ip->flags & HAMMER_INODE_WOULDBLOCK) &&
1247                     ip->sync_ino_data.size != ip->ino_data.size) {
1248                         redirty = 1;
1249                         ip->sync_ino_data.size = ip->ino_data.size;
1250                 } else {
1251                         redirty = 0;
1252                 }
1253
1254                 for (;;) {
1255                         error = hammer_ip_sync_record_cursor(cursor, record);
1256                         if (hammer_debug_inode)
1257                                 kprintf("GENREC %p rec %08x %d\n",      
1258                                         ip, record->flags, error);
1259                         if (error != EDEADLK)
1260                                 break;
1261                         hammer_done_cursor(cursor);
1262                         error = hammer_init_cursor(trans, cursor,
1263                                                    &ip->cache[0], ip);
1264                         if (hammer_debug_inode)
1265                                 kprintf("GENREC reinit %d\n", error);
1266                         if (error)
1267                                 break;
1268                 }
1269
1270                 /*
1271                  * Note:  The record was never on the inode's record tree
1272                  * so just wave our hands importantly and destroy it.
1273                  */
1274                 record->flags |= HAMMER_RECF_COMMITTED;
1275                 record->flags &= ~HAMMER_RECF_INTERLOCK_BE;
1276                 record->flush_state = HAMMER_FST_IDLE;
1277                 ++ip->rec_generation;
1278                 hammer_rel_mem_record(record);
1279
1280                 /*
1281                  * Finish up.
1282                  */
1283                 if (error == 0) {
1284                         if (hammer_debug_inode)
1285                                 kprintf("CLEANDELOND %p %08x\n", ip, ip->flags);
1286                         ip->sync_flags &= ~(HAMMER_INODE_DDIRTY |
1287                                             HAMMER_INODE_SDIRTY |
1288                                             HAMMER_INODE_ATIME |
1289                                             HAMMER_INODE_MTIME);
1290                         ip->flags &= ~HAMMER_INODE_DELONDISK;
1291                         if (redirty)
1292                                 ip->sync_flags |= HAMMER_INODE_DDIRTY;
1293
1294                         /*
1295                          * Root volume count of inodes
1296                          */
1297                         hammer_sync_lock_sh(trans);
1298                         if ((ip->flags & HAMMER_INODE_ONDISK) == 0) {
1299                                 hammer_modify_volume_field(trans,
1300                                                            trans->rootvol,
1301                                                            vol0_stat_inodes);
1302                                 ++ip->hmp->rootvol->ondisk->vol0_stat_inodes;
1303                                 hammer_modify_volume_done(trans->rootvol);
1304                                 ip->flags |= HAMMER_INODE_ONDISK;
1305                                 if (hammer_debug_inode)
1306                                         kprintf("NOWONDISK %p\n", ip);
1307                         }
1308                         hammer_sync_unlock(trans);
1309                 }
1310         }
1311
1312         /*
1313          * If the inode has been destroyed, clean out any left-over flags
1314          * that may have been set by the frontend.
1315          */
1316         if (error == 0 && (ip->flags & HAMMER_INODE_DELETED)) { 
1317                 ip->sync_flags &= ~(HAMMER_INODE_DDIRTY |
1318                                     HAMMER_INODE_SDIRTY |
1319                                     HAMMER_INODE_ATIME |
1320                                     HAMMER_INODE_MTIME);
1321         }
1322         return(error);
1323 }
1324
1325 /*
1326  * Update only the itimes fields.
1327  *
1328  * ATIME can be updated without generating any UNDO.  MTIME is updated
1329  * with UNDO so it is guaranteed to be synchronized properly in case of
1330  * a crash.
1331  *
1332  * Neither field is included in the B-Tree leaf element's CRC, which is how
1333  * we can get away with updating ATIME the way we do.
1334  */
1335 static int
1336 hammer_update_itimes(hammer_cursor_t cursor, hammer_inode_t ip)
1337 {
1338         hammer_transaction_t trans = cursor->trans;
1339         int error;
1340
1341 retry:
1342         if ((ip->flags & (HAMMER_INODE_ONDISK|HAMMER_INODE_DELONDISK)) !=
1343             HAMMER_INODE_ONDISK) {
1344                 return(0);
1345         }
1346
1347         hammer_normalize_cursor(cursor);
1348         cursor->key_beg.localization = ip->obj_localization + 
1349                                        HAMMER_LOCALIZE_INODE;
1350         cursor->key_beg.obj_id = ip->obj_id;
1351         cursor->key_beg.key = 0;
1352         cursor->key_beg.create_tid = 0;
1353         cursor->key_beg.delete_tid = 0;
1354         cursor->key_beg.rec_type = HAMMER_RECTYPE_INODE;
1355         cursor->key_beg.obj_type = 0;
1356         cursor->asof = ip->obj_asof;
1357         cursor->flags &= ~HAMMER_CURSOR_INITMASK;
1358         cursor->flags |= HAMMER_CURSOR_ASOF;
1359         cursor->flags |= HAMMER_CURSOR_GET_LEAF;
1360         cursor->flags |= HAMMER_CURSOR_GET_DATA;
1361         cursor->flags |= HAMMER_CURSOR_BACKEND;
1362
1363         error = hammer_btree_lookup(cursor);
1364         if (error == 0) {
1365                 hammer_cache_node(&ip->cache[0], cursor->node);
1366                 if (ip->sync_flags & HAMMER_INODE_MTIME) {
1367                         /*
1368                          * Updating MTIME requires an UNDO.  Just cover
1369                          * both atime and mtime.
1370                          */
1371                         hammer_sync_lock_sh(trans);
1372                         hammer_modify_buffer(trans, cursor->data_buffer,
1373                                      HAMMER_ITIMES_BASE(&cursor->data->inode),
1374                                      HAMMER_ITIMES_BYTES);
1375                         cursor->data->inode.atime = ip->sync_ino_data.atime;
1376                         cursor->data->inode.mtime = ip->sync_ino_data.mtime;
1377                         hammer_modify_buffer_done(cursor->data_buffer);
1378                         hammer_sync_unlock(trans);
1379                 } else if (ip->sync_flags & HAMMER_INODE_ATIME) {
1380                         /*
1381                          * Updating atime only can be done in-place with
1382                          * no UNDO.
1383                          */
1384                         hammer_sync_lock_sh(trans);
1385                         hammer_modify_buffer(trans, cursor->data_buffer,
1386                                              NULL, 0);
1387                         cursor->data->inode.atime = ip->sync_ino_data.atime;
1388                         hammer_modify_buffer_done(cursor->data_buffer);
1389                         hammer_sync_unlock(trans);
1390                 }
1391                 ip->sync_flags &= ~(HAMMER_INODE_ATIME | HAMMER_INODE_MTIME);
1392         }
1393         if (error == EDEADLK) {
1394                 hammer_done_cursor(cursor);
1395                 error = hammer_init_cursor(trans, cursor,
1396                                            &ip->cache[0], ip);
1397                 if (error == 0)
1398                         goto retry;
1399         }
1400         return(error);
1401 }
1402
1403 /*
1404  * Release a reference on an inode, flush as requested.
1405  *
1406  * On the last reference we queue the inode to the flusher for its final
1407  * disposition.
1408  */
1409 void
1410 hammer_rel_inode(struct hammer_inode *ip, int flush)
1411 {
1412         /*hammer_mount_t hmp = ip->hmp;*/
1413
1414         /*
1415          * Handle disposition when dropping the last ref.
1416          */
1417         for (;;) {
1418                 if (ip->lock.refs == 1) {
1419                         /*
1420                          * Determine whether on-disk action is needed for
1421                          * the inode's final disposition.
1422                          */
1423                         KKASSERT(ip->vp == NULL);
1424                         hammer_inode_unloadable_check(ip, 0);
1425                         if (ip->flags & HAMMER_INODE_MODMASK) {
1426                                 hammer_flush_inode(ip, 0);
1427                         } else if (ip->lock.refs == 1) {
1428                                 hammer_unload_inode(ip);
1429                                 break;
1430                         }
1431                 } else {
1432                         if (flush)
1433                                 hammer_flush_inode(ip, 0);
1434
1435                         /*
1436                          * The inode still has multiple refs, try to drop
1437                          * one ref.
1438                          */
1439                         KKASSERT(ip->lock.refs >= 1);
1440                         if (ip->lock.refs > 1) {
1441                                 hammer_unref(&ip->lock);
1442                                 break;
1443                         }
1444                 }
1445         }
1446 }
1447
1448 /*
1449  * Unload and destroy the specified inode.  Must be called with one remaining
1450  * reference.  The reference is disposed of.
1451  *
1452  * The inode must be completely clean.
1453  */
1454 static int
1455 hammer_unload_inode(struct hammer_inode *ip)
1456 {
1457         hammer_mount_t hmp = ip->hmp;
1458
1459         KASSERT(ip->lock.refs == 1,
1460                 ("hammer_unload_inode: %d refs\n", ip->lock.refs));
1461         KKASSERT(ip->vp == NULL);
1462         KKASSERT(ip->flush_state == HAMMER_FST_IDLE);
1463         KKASSERT(ip->cursor_ip_refs == 0);
1464         KKASSERT(hammer_notlocked(&ip->lock));
1465         KKASSERT((ip->flags & HAMMER_INODE_MODMASK) == 0);
1466
1467         KKASSERT(RB_EMPTY(&ip->rec_tree));
1468         KKASSERT(TAILQ_EMPTY(&ip->target_list));
1469
1470         if (ip->flags & HAMMER_INODE_RDIRTY) {
1471                 RB_REMOVE(hammer_redo_rb_tree, &hmp->rb_redo_root, ip);
1472                 ip->flags &= ~HAMMER_INODE_RDIRTY;
1473         }
1474         RB_REMOVE(hammer_ino_rb_tree, &hmp->rb_inos_root, ip);
1475
1476         hammer_free_inode(ip);
1477         return(0);
1478 }
1479
1480 /*
1481  * Called during unmounting if a critical error occured.  The in-memory
1482  * inode and all related structures are destroyed.
1483  *
1484  * If a critical error did not occur the unmount code calls the standard
1485  * release and asserts that the inode is gone.
1486  */
1487 int
1488 hammer_destroy_inode_callback(struct hammer_inode *ip, void *data __unused)
1489 {
1490         hammer_record_t rec;
1491
1492         /*
1493          * Get rid of the inodes in-memory records, regardless of their
1494          * state, and clear the mod-mask.
1495          */
1496         while ((rec = TAILQ_FIRST(&ip->target_list)) != NULL) {
1497                 TAILQ_REMOVE(&ip->target_list, rec, target_entry);
1498                 rec->target_ip = NULL;
1499                 if (rec->flush_state == HAMMER_FST_SETUP)
1500                         rec->flush_state = HAMMER_FST_IDLE;
1501         }
1502         while ((rec = RB_ROOT(&ip->rec_tree)) != NULL) {
1503                 if (rec->flush_state == HAMMER_FST_FLUSH)
1504                         --rec->flush_group->refs;
1505                 else
1506                         hammer_ref(&rec->lock);
1507                 KKASSERT(rec->lock.refs == 1);
1508                 rec->flush_state = HAMMER_FST_IDLE;
1509                 rec->flush_group = NULL;
1510                 rec->flags |= HAMMER_RECF_DELETED_FE; /* wave hands */
1511                 rec->flags |= HAMMER_RECF_DELETED_BE; /* wave hands */
1512                 ++ip->rec_generation;
1513                 hammer_rel_mem_record(rec);
1514         }
1515         ip->flags &= ~HAMMER_INODE_MODMASK;
1516         ip->sync_flags &= ~HAMMER_INODE_MODMASK;
1517         KKASSERT(ip->vp == NULL);
1518
1519         /*
1520          * Remove the inode from any flush group, force it idle.  FLUSH
1521          * and SETUP states have an inode ref.
1522          */
1523         switch(ip->flush_state) {
1524         case HAMMER_FST_FLUSH:
1525                 RB_REMOVE(hammer_fls_rb_tree, &ip->flush_group->flush_tree, ip);
1526                 --ip->flush_group->refs;
1527                 ip->flush_group = NULL;
1528                 /* fall through */
1529         case HAMMER_FST_SETUP:
1530                 hammer_unref(&ip->lock);
1531                 ip->flush_state = HAMMER_FST_IDLE;
1532                 /* fall through */
1533         case HAMMER_FST_IDLE:
1534                 break;
1535         }
1536
1537         /*
1538          * There shouldn't be any associated vnode.  The unload needs at
1539          * least one ref, if we do have a vp steal its ip ref.
1540          */
1541         if (ip->vp) {
1542                 kprintf("hammer_destroy_inode_callback: Unexpected "
1543                         "vnode association ip %p vp %p\n", ip, ip->vp);
1544                 ip->vp->v_data = NULL;
1545                 ip->vp = NULL;
1546         } else {
1547                 hammer_ref(&ip->lock);
1548         }
1549         hammer_unload_inode(ip);
1550         return(0);
1551 }
1552
1553 /*
1554  * Called on mount -u when switching from RW to RO or vise-versa.  Adjust
1555  * the read-only flag for cached inodes.
1556  *
1557  * This routine is called from a RB_SCAN().
1558  */
1559 int
1560 hammer_reload_inode(hammer_inode_t ip, void *arg __unused)
1561 {
1562         hammer_mount_t hmp = ip->hmp;
1563
1564         if (hmp->ronly || hmp->asof != HAMMER_MAX_TID)
1565                 ip->flags |= HAMMER_INODE_RO;
1566         else
1567                 ip->flags &= ~HAMMER_INODE_RO;
1568         return(0);
1569 }
1570
1571 /*
1572  * A transaction has modified an inode, requiring updates as specified by
1573  * the passed flags.
1574  *
1575  * HAMMER_INODE_DDIRTY: Inode data has been updated, not incl mtime/atime,
1576  *                      and not including size changes due to write-append
1577  *                      (but other size changes are included).
1578  * HAMMER_INODE_SDIRTY: Inode data has been updated, size changes due to
1579  *                      write-append.
1580  * HAMMER_INODE_XDIRTY: Dirty in-memory records
1581  * HAMMER_INODE_BUFS:   Dirty buffer cache buffers
1582  * HAMMER_INODE_DELETED: Inode record/data must be deleted
1583  * HAMMER_INODE_ATIME/MTIME: mtime/atime has been updated
1584  */
1585 void
1586 hammer_modify_inode(hammer_inode_t ip, int flags)
1587 {
1588         /* 
1589          * ronly of 0 or 2 does not trigger assertion.
1590          * 2 is a special error state 
1591          */
1592         KKASSERT(ip->hmp->ronly != 1 ||
1593                   (flags & (HAMMER_INODE_DDIRTY | HAMMER_INODE_XDIRTY | 
1594                             HAMMER_INODE_SDIRTY |
1595                             HAMMER_INODE_BUFS | HAMMER_INODE_DELETED |
1596                             HAMMER_INODE_ATIME | HAMMER_INODE_MTIME)) == 0);
1597         if ((ip->flags & HAMMER_INODE_RSV_INODES) == 0) {
1598                 ip->flags |= HAMMER_INODE_RSV_INODES;
1599                 ++ip->hmp->rsv_inodes;
1600         }
1601
1602         ip->flags |= flags;
1603 }
1604
1605 /*
1606  * Request that an inode be flushed.  This whole mess cannot block and may
1607  * recurse (if not synchronous).  Once requested HAMMER will attempt to
1608  * actively flush the inode until the flush can be done.
1609  *
1610  * The inode may already be flushing, or may be in a setup state.  We can
1611  * place the inode in a flushing state if it is currently idle and flag it
1612  * to reflush if it is currently flushing.
1613  *
1614  * Upon return if the inode could not be flushed due to a setup
1615  * dependancy, then it will be automatically flushed when the dependancy
1616  * is satisfied.
1617  */
1618 void
1619 hammer_flush_inode(hammer_inode_t ip, int flags)
1620 {
1621         hammer_mount_t hmp;
1622         hammer_flush_group_t flg;
1623         int good;
1624
1625         /*
1626          * next_flush_group is the first flush group we can place the inode
1627          * in.  It may be NULL.  If it becomes full we append a new flush
1628          * group and make that the next_flush_group.
1629          */
1630         hmp = ip->hmp;
1631         while ((flg = hmp->next_flush_group) != NULL) {
1632                 KKASSERT(flg->running == 0);
1633                 if (flg->total_count + flg->refs <= ip->hmp->undo_rec_limit)
1634                         break;
1635                 hmp->next_flush_group = TAILQ_NEXT(flg, flush_entry);
1636                 hammer_flusher_async(ip->hmp, flg);
1637         }
1638         if (flg == NULL) {
1639                 flg = kmalloc(sizeof(*flg), hmp->m_misc, M_WAITOK|M_ZERO);
1640                 hmp->next_flush_group = flg;
1641                 RB_INIT(&flg->flush_tree);
1642                 TAILQ_INSERT_TAIL(&hmp->flush_group_list, flg, flush_entry);
1643         }
1644
1645         /*
1646          * Trivial 'nothing to flush' case.  If the inode is in a SETUP
1647          * state we have to put it back into an IDLE state so we can
1648          * drop the extra ref.
1649          *
1650          * If we have a parent dependancy we must still fall through
1651          * so we can run it.
1652          */
1653         if ((ip->flags & HAMMER_INODE_MODMASK) == 0) {
1654                 if (ip->flush_state == HAMMER_FST_SETUP &&
1655                     TAILQ_EMPTY(&ip->target_list)) {
1656                         ip->flush_state = HAMMER_FST_IDLE;
1657                         hammer_rel_inode(ip, 0);
1658                 }
1659                 if (ip->flush_state == HAMMER_FST_IDLE)
1660                         return;
1661         }
1662
1663         /*
1664          * Our flush action will depend on the current state.
1665          */
1666         switch(ip->flush_state) {
1667         case HAMMER_FST_IDLE:
1668                 /*
1669                  * We have no dependancies and can flush immediately.  Some
1670                  * our children may not be flushable so we have to re-test
1671                  * with that additional knowledge.
1672                  */
1673                 hammer_flush_inode_core(ip, flg, flags);
1674                 break;
1675         case HAMMER_FST_SETUP:
1676                 /*
1677                  * Recurse upwards through dependancies via target_list
1678                  * and start their flusher actions going if possible.
1679                  *
1680                  * 'good' is our connectivity.  -1 means we have none and
1681                  * can't flush, 0 means there weren't any dependancies, and
1682                  * 1 means we have good connectivity.
1683                  */
1684                 good = hammer_setup_parent_inodes(ip, 0, flg);
1685
1686                 if (good >= 0) {
1687                         /*
1688                          * We can continue if good >= 0.  Determine how 
1689                          * many records under our inode can be flushed (and
1690                          * mark them).
1691                          */
1692                         hammer_flush_inode_core(ip, flg, flags);
1693                 } else {
1694                         /*
1695                          * Parent has no connectivity, tell it to flush
1696                          * us as soon as it does.
1697                          *
1698                          * The REFLUSH flag is also needed to trigger
1699                          * dependancy wakeups.
1700                          */
1701                         ip->flags |= HAMMER_INODE_CONN_DOWN |
1702                                      HAMMER_INODE_REFLUSH;
1703                         if (flags & HAMMER_FLUSH_SIGNAL) {
1704                                 ip->flags |= HAMMER_INODE_RESIGNAL;
1705                                 hammer_flusher_async(ip->hmp, flg);
1706                         }
1707                 }
1708                 break;
1709         case HAMMER_FST_FLUSH:
1710                 /*
1711                  * We are already flushing, flag the inode to reflush
1712                  * if needed after it completes its current flush.
1713                  *
1714                  * The REFLUSH flag is also needed to trigger
1715                  * dependancy wakeups.
1716                  */
1717                 if ((ip->flags & HAMMER_INODE_REFLUSH) == 0)
1718                         ip->flags |= HAMMER_INODE_REFLUSH;
1719                 if (flags & HAMMER_FLUSH_SIGNAL) {
1720                         ip->flags |= HAMMER_INODE_RESIGNAL;
1721                         hammer_flusher_async(ip->hmp, flg);
1722                 }
1723                 break;
1724         }
1725 }
1726
1727 /*
1728  * Scan ip->target_list, which is a list of records owned by PARENTS to our
1729  * ip which reference our ip.
1730  *
1731  * XXX This is a huge mess of recursive code, but not one bit of it blocks
1732  *     so for now do not ref/deref the structures.  Note that if we use the
1733  *     ref/rel code later, the rel CAN block.
1734  */
1735 static int
1736 hammer_setup_parent_inodes(hammer_inode_t ip, int depth,
1737                            hammer_flush_group_t flg)
1738 {
1739         hammer_record_t depend;
1740         int good;
1741         int r;
1742
1743         /*
1744          * If we hit our recursion limit and we have parent dependencies
1745          * We cannot continue.  Returning < 0 will cause us to be flagged
1746          * for reflush.  Returning -2 cuts off additional dependency checks
1747          * because they are likely to also hit the depth limit.
1748          *
1749          * We cannot return < 0 if there are no dependencies or there might
1750          * not be anything to wakeup (ip).
1751          */
1752         if (depth == 20 && TAILQ_FIRST(&ip->target_list)) {
1753                 kprintf("HAMMER Warning: depth limit reached on "
1754                         "setup recursion, inode %p %016llx\n",
1755                         ip, (long long)ip->obj_id);
1756                 return(-2);
1757         }
1758
1759         /*
1760          * Scan dependencies
1761          */
1762         good = 0;
1763         TAILQ_FOREACH(depend, &ip->target_list, target_entry) {
1764                 r = hammer_setup_parent_inodes_helper(depend, depth, flg);
1765                 KKASSERT(depend->target_ip == ip);
1766                 if (r < 0 && good == 0)
1767                         good = -1;
1768                 if (r > 0)
1769                         good = 1;
1770
1771                 /*
1772                  * If we failed due to the recursion depth limit then stop
1773                  * now.
1774                  */
1775                 if (r == -2)
1776                         break;
1777         }
1778         return(good);
1779 }
1780
1781 /*
1782  * This helper function takes a record representing the dependancy between
1783  * the parent inode and child inode.
1784  *
1785  * record->ip           = parent inode
1786  * record->target_ip    = child inode
1787  * 
1788  * We are asked to recurse upwards and convert the record from SETUP
1789  * to FLUSH if possible.
1790  *
1791  * Return 1 if the record gives us connectivity
1792  *
1793  * Return 0 if the record is not relevant 
1794  *
1795  * Return -1 if we can't resolve the dependancy and there is no connectivity.
1796  */
1797 static int
1798 hammer_setup_parent_inodes_helper(hammer_record_t record, int depth,
1799                                   hammer_flush_group_t flg)
1800 {
1801         hammer_mount_t hmp;
1802         hammer_inode_t pip;
1803         int good;
1804
1805         KKASSERT(record->flush_state != HAMMER_FST_IDLE);
1806         pip = record->ip;
1807         hmp = pip->hmp;
1808
1809         /*
1810          * If the record is already flushing, is it in our flush group?
1811          *
1812          * If it is in our flush group but it is a general record or a 
1813          * delete-on-disk, it does not improve our connectivity (return 0),
1814          * and if the target inode is not trying to destroy itself we can't
1815          * allow the operation yet anyway (the second return -1).
1816          */
1817         if (record->flush_state == HAMMER_FST_FLUSH) {
1818                 /*
1819                  * If not in our flush group ask the parent to reflush
1820                  * us as soon as possible.
1821                  */
1822                 if (record->flush_group != flg) {
1823                         pip->flags |= HAMMER_INODE_REFLUSH;
1824                         record->target_ip->flags |= HAMMER_INODE_CONN_DOWN;
1825                         return(-1);
1826                 }
1827
1828                 /*
1829                  * If in our flush group everything is already set up,
1830                  * just return whether the record will improve our
1831                  * visibility or not.
1832                  */
1833                 if (record->type == HAMMER_MEM_RECORD_ADD)
1834                         return(1);
1835                 return(0);
1836         }
1837
1838         /*
1839          * It must be a setup record.  Try to resolve the setup dependancies
1840          * by recursing upwards so we can place ip on the flush list.
1841          *
1842          * Limit ourselves to 20 levels of recursion to avoid blowing out
1843          * the kernel stack.  If we hit the recursion limit we can't flush
1844          * until the parent flushes.  The parent will flush independantly
1845          * on its own and ultimately a deep recursion will be resolved.
1846          */
1847         KKASSERT(record->flush_state == HAMMER_FST_SETUP);
1848
1849         good = hammer_setup_parent_inodes(pip, depth + 1, flg);
1850
1851         /*
1852          * If good < 0 the parent has no connectivity and we cannot safely
1853          * flush the directory entry, which also means we can't flush our
1854          * ip.  Flag us for downward recursion once the parent's
1855          * connectivity is resolved.  Flag the parent for [re]flush or it
1856          * may not check for downward recursions.
1857          */
1858         if (good < 0) {
1859                 pip->flags |= HAMMER_INODE_REFLUSH;
1860                 record->target_ip->flags |= HAMMER_INODE_CONN_DOWN;
1861                 return(good);
1862         }
1863
1864         /*
1865          * We are go, place the parent inode in a flushing state so we can
1866          * place its record in a flushing state.  Note that the parent
1867          * may already be flushing.  The record must be in the same flush
1868          * group as the parent.
1869          */
1870         if (pip->flush_state != HAMMER_FST_FLUSH)
1871                 hammer_flush_inode_core(pip, flg, HAMMER_FLUSH_RECURSION);
1872         KKASSERT(pip->flush_state == HAMMER_FST_FLUSH);
1873         KKASSERT(record->flush_state == HAMMER_FST_SETUP);
1874
1875 #if 0
1876         if (record->type == HAMMER_MEM_RECORD_DEL &&
1877             (record->target_ip->flags & (HAMMER_INODE_DELETED|HAMMER_INODE_DELONDISK)) == 0) {
1878                 /*
1879                  * Regardless of flushing state we cannot sync this path if the
1880                  * record represents a delete-on-disk but the target inode
1881                  * is not ready to sync its own deletion.
1882                  *
1883                  * XXX need to count effective nlinks to determine whether
1884                  * the flush is ok, otherwise removing a hardlink will
1885                  * just leave the DEL record to rot.
1886                  */
1887                 record->target_ip->flags |= HAMMER_INODE_REFLUSH;
1888                 return(-1);
1889         } else
1890 #endif
1891         if (pip->flush_group == flg) {
1892                 /*
1893                  * Because we have not calculated nlinks yet we can just
1894                  * set records to the flush state if the parent is in
1895                  * the same flush group as we are.
1896                  */
1897                 record->flush_state = HAMMER_FST_FLUSH;
1898                 record->flush_group = flg;
1899                 ++record->flush_group->refs;
1900                 hammer_ref(&record->lock);
1901
1902                 /*
1903                  * A general directory-add contributes to our visibility.
1904                  *
1905                  * Otherwise it is probably a directory-delete or 
1906                  * delete-on-disk record and does not contribute to our
1907                  * visbility (but we can still flush it).
1908                  */
1909                 if (record->type == HAMMER_MEM_RECORD_ADD)
1910                         return(1);
1911                 return(0);
1912         } else {
1913                 /*
1914                  * If the parent is not in our flush group we cannot
1915                  * flush this record yet, there is no visibility.
1916                  * We tell the parent to reflush and mark ourselves
1917                  * so the parent knows it should flush us too.
1918                  */
1919                 pip->flags |= HAMMER_INODE_REFLUSH;
1920                 record->target_ip->flags |= HAMMER_INODE_CONN_DOWN;
1921                 return(-1);
1922         }
1923 }
1924
1925 /*
1926  * This is the core routine placing an inode into the FST_FLUSH state.
1927  */
1928 static void
1929 hammer_flush_inode_core(hammer_inode_t ip, hammer_flush_group_t flg, int flags)
1930 {
1931         int go_count;
1932
1933         /*
1934          * Set flush state and prevent the flusher from cycling into
1935          * the next flush group.  Do not place the ip on the list yet.
1936          * Inodes not in the idle state get an extra reference.
1937          */
1938         KKASSERT(ip->flush_state != HAMMER_FST_FLUSH);
1939         if (ip->flush_state == HAMMER_FST_IDLE)
1940                 hammer_ref(&ip->lock);
1941         ip->flush_state = HAMMER_FST_FLUSH;
1942         ip->flush_group = flg;
1943         ++ip->hmp->flusher.group_lock;
1944         ++ip->hmp->count_iqueued;
1945         ++hammer_count_iqueued;
1946         ++flg->total_count;
1947         hammer_redo_fifo_start_flush(ip);
1948
1949         /*
1950          * If the flush group reaches the autoflush limit we want to signal
1951          * the flusher.  This is particularly important for remove()s.
1952          */
1953         if (flg->total_count == hammer_autoflush)
1954                 flags |= HAMMER_FLUSH_SIGNAL;
1955
1956 #if 0
1957         /*
1958          * We need to be able to vfsync/truncate from the backend.
1959          *
1960          * XXX Any truncation from the backend will acquire the vnode
1961          *     independently.
1962          */
1963         KKASSERT((ip->flags & HAMMER_INODE_VHELD) == 0);
1964         if (ip->vp && (ip->vp->v_flag & VINACTIVE) == 0) {
1965                 ip->flags |= HAMMER_INODE_VHELD;
1966                 vref(ip->vp);
1967         }
1968 #endif
1969
1970         /*
1971          * Figure out how many in-memory records we can actually flush
1972          * (not including inode meta-data, buffers, etc).
1973          */
1974         KKASSERT((ip->flags & HAMMER_INODE_WOULDBLOCK) == 0);
1975         if (flags & HAMMER_FLUSH_RECURSION) {
1976                 /*
1977                  * If this is a upwards recursion we do not want to
1978                  * recurse down again!
1979                  */
1980                 go_count = 1;
1981 #if 0
1982         } else if (ip->flags & HAMMER_INODE_WOULDBLOCK) {
1983                 /*
1984                  * No new records are added if we must complete a flush
1985                  * from a previous cycle, but we do have to move the records
1986                  * from the previous cycle to the current one.
1987                  */
1988 #if 0
1989                 go_count = RB_SCAN(hammer_rec_rb_tree, &ip->rec_tree, NULL,
1990                                    hammer_syncgrp_child_callback, NULL);
1991 #endif
1992                 go_count = 1;
1993 #endif
1994         } else {
1995                 /*
1996                  * Normal flush, scan records and bring them into the flush.
1997                  * Directory adds and deletes are usually skipped (they are
1998                  * grouped with the related inode rather then with the
1999                  * directory).
2000                  *
2001                  * go_count can be negative, which means the scan aborted
2002                  * due to the flush group being over-full and we should
2003                  * flush what we have.
2004                  */
2005                 go_count = RB_SCAN(hammer_rec_rb_tree, &ip->rec_tree, NULL,
2006                                    hammer_setup_child_callback, NULL);
2007         }
2008
2009         /*
2010          * This is a more involved test that includes go_count.  If we
2011          * can't flush, flag the inode and return.  If go_count is 0 we
2012          * were are unable to flush any records in our rec_tree and
2013          * must ignore the XDIRTY flag.
2014          */
2015         if (go_count == 0) {
2016                 if ((ip->flags & HAMMER_INODE_MODMASK_NOXDIRTY) == 0) {
2017                         --ip->hmp->count_iqueued;
2018                         --hammer_count_iqueued;
2019
2020                         --flg->total_count;
2021                         ip->flush_state = HAMMER_FST_SETUP;
2022                         ip->flush_group = NULL;
2023 #if 0
2024                         if (ip->flags & HAMMER_INODE_VHELD) {
2025                                 ip->flags &= ~HAMMER_INODE_VHELD;
2026                                 vrele(ip->vp);
2027                         }
2028 #endif
2029
2030                         /*
2031                          * REFLUSH is needed to trigger dependancy wakeups
2032                          * when an inode is in SETUP.
2033                          */
2034                         ip->flags |= HAMMER_INODE_REFLUSH;
2035                         if (flags & HAMMER_FLUSH_SIGNAL) {
2036                                 ip->flags |= HAMMER_INODE_RESIGNAL;
2037                                 hammer_flusher_async(ip->hmp, flg);
2038                         }
2039                         if (--ip->hmp->flusher.group_lock == 0)
2040                                 wakeup(&ip->hmp->flusher.group_lock);
2041                         return;
2042                 }
2043         }
2044
2045         /*
2046          * Snapshot the state of the inode for the backend flusher.
2047          *
2048          * We continue to retain save_trunc_off even when all truncations
2049          * have been resolved as an optimization to determine if we can
2050          * skip the B-Tree lookup for overwrite deletions.
2051          *
2052          * NOTE: The DELETING flag is a mod flag, but it is also sticky,
2053          * and stays in ip->flags.  Once set, it stays set until the
2054          * inode is destroyed.
2055          */
2056         if (ip->flags & HAMMER_INODE_TRUNCATED) {
2057                 KKASSERT((ip->sync_flags & HAMMER_INODE_TRUNCATED) == 0);
2058                 ip->sync_trunc_off = ip->trunc_off;
2059                 ip->trunc_off = 0x7FFFFFFFFFFFFFFFLL;
2060                 ip->flags &= ~HAMMER_INODE_TRUNCATED;
2061                 ip->sync_flags |= HAMMER_INODE_TRUNCATED;
2062
2063                 /*
2064                  * The save_trunc_off used to cache whether the B-Tree
2065                  * holds any records past that point is not used until
2066                  * after the truncation has succeeded, so we can safely
2067                  * set it now.
2068                  */
2069                 if (ip->save_trunc_off > ip->sync_trunc_off)
2070                         ip->save_trunc_off = ip->sync_trunc_off;
2071         }
2072         ip->sync_flags |= (ip->flags & HAMMER_INODE_MODMASK &
2073                            ~HAMMER_INODE_TRUNCATED);
2074         ip->sync_ino_leaf = ip->ino_leaf;
2075         ip->sync_ino_data = ip->ino_data;
2076         ip->flags &= ~HAMMER_INODE_MODMASK | HAMMER_INODE_TRUNCATED;
2077 #ifdef DEBUG_TRUNCATE
2078         if ((ip->sync_flags & HAMMER_INODE_TRUNCATED) && ip == HammerTruncIp)
2079                 kprintf("truncateS %016llx\n", ip->sync_trunc_off);
2080 #endif
2081
2082         /*
2083          * The flusher list inherits our inode and reference.
2084          */
2085         KKASSERT(flg->running == 0);
2086         RB_INSERT(hammer_fls_rb_tree, &flg->flush_tree, ip);
2087         if (--ip->hmp->flusher.group_lock == 0)
2088                 wakeup(&ip->hmp->flusher.group_lock);
2089
2090         if (flags & HAMMER_FLUSH_SIGNAL) {
2091                 hammer_flusher_async(ip->hmp, flg);
2092         }
2093 }
2094
2095 /*
2096  * Callback for scan of ip->rec_tree.  Try to include each record in our
2097  * flush.  ip->flush_group has been set but the inode has not yet been
2098  * moved into a flushing state.
2099  *
2100  * If we get stuck on a record we have to set HAMMER_INODE_REFLUSH on
2101  * both inodes.
2102  *
2103  * We return 1 for any record placed or found in FST_FLUSH, which prevents
2104  * the caller from shortcutting the flush.
2105  */
2106 static int
2107 hammer_setup_child_callback(hammer_record_t rec, void *data)
2108 {
2109         hammer_flush_group_t flg;
2110         hammer_inode_t target_ip;
2111         hammer_inode_t ip;
2112         int r;
2113
2114         /*
2115          * Records deleted or committed by the backend are ignored.
2116          * Note that the flush detects deleted frontend records at
2117          * multiple points to deal with races.  This is just the first
2118          * line of defense.  The only time HAMMER_RECF_DELETED_FE cannot
2119          * be set is when HAMMER_RECF_INTERLOCK_BE is set, because it
2120          * messes up link-count calculations.
2121          *
2122          * NOTE: Don't get confused between record deletion and, say,
2123          * directory entry deletion.  The deletion of a directory entry
2124          * which is on-media has nothing to do with the record deletion
2125          * flags.
2126          */
2127         if (rec->flags & (HAMMER_RECF_DELETED_FE | HAMMER_RECF_DELETED_BE |
2128                           HAMMER_RECF_COMMITTED)) {
2129                 if (rec->flush_state == HAMMER_FST_FLUSH) {
2130                         KKASSERT(rec->flush_group == rec->ip->flush_group);
2131                         r = 1;
2132                 } else {
2133                         r = 0;
2134                 }
2135                 return(r);
2136         }
2137
2138         /*
2139          * If the record is in an idle state it has no dependancies and
2140          * can be flushed.
2141          */
2142         ip = rec->ip;
2143         flg = ip->flush_group;
2144         r = 0;
2145
2146         switch(rec->flush_state) {
2147         case HAMMER_FST_IDLE:
2148                 /*
2149                  * The record has no setup dependancy, we can flush it.
2150                  */
2151                 KKASSERT(rec->target_ip == NULL);
2152                 rec->flush_state = HAMMER_FST_FLUSH;
2153                 rec->flush_group = flg;
2154                 ++flg->refs;
2155                 hammer_ref(&rec->lock);
2156                 r = 1;
2157                 break;
2158         case HAMMER_FST_SETUP:
2159                 /*
2160                  * The record has a setup dependancy.  These are typically
2161                  * directory entry adds and deletes.  Such entries will be
2162                  * flushed when their inodes are flushed so we do not
2163                  * usually have to add them to the flush here.  However,
2164                  * if the target_ip has set HAMMER_INODE_CONN_DOWN then
2165                  * it is asking us to flush this record (and it).
2166                  */
2167                 target_ip = rec->target_ip;
2168                 KKASSERT(target_ip != NULL);
2169                 KKASSERT(target_ip->flush_state != HAMMER_FST_IDLE);
2170
2171                 /*
2172                  * If the target IP is already flushing in our group
2173                  * we could associate the record, but target_ip has
2174                  * already synced ino_data to sync_ino_data and we
2175                  * would also have to adjust nlinks.   Plus there are
2176                  * ordering issues for adds and deletes.
2177                  *
2178                  * Reflush downward if this is an ADD, and upward if
2179                  * this is a DEL.
2180                  */
2181                 if (target_ip->flush_state == HAMMER_FST_FLUSH) {
2182                         if (rec->flush_state == HAMMER_MEM_RECORD_ADD)
2183                                 ip->flags |= HAMMER_INODE_REFLUSH;
2184                         else
2185                                 target_ip->flags |= HAMMER_INODE_REFLUSH;
2186                         break;
2187                 } 
2188
2189                 /*
2190                  * Target IP is not yet flushing.  This can get complex
2191                  * because we have to be careful about the recursion.
2192                  *
2193                  * Directories create an issue for us in that if a flush
2194                  * of a directory is requested the expectation is to flush
2195                  * any pending directory entries, but this will cause the
2196                  * related inodes to recursively flush as well.  We can't
2197                  * really defer the operation so just get as many as we
2198                  * can and
2199                  */
2200 #if 0
2201                 if ((target_ip->flags & HAMMER_INODE_RECLAIM) == 0 &&
2202                     (target_ip->flags & HAMMER_INODE_CONN_DOWN) == 0) {
2203                         /*
2204                          * We aren't reclaiming and the target ip was not
2205                          * previously prevented from flushing due to this
2206                          * record dependancy.  Do not flush this record.
2207                          */
2208                         /*r = 0;*/
2209                 } else
2210 #endif
2211                 if (flg->total_count + flg->refs >
2212                            ip->hmp->undo_rec_limit) {
2213                         /*
2214                          * Our flush group is over-full and we risk blowing
2215                          * out the UNDO FIFO.  Stop the scan, flush what we
2216                          * have, then reflush the directory.
2217                          *
2218                          * The directory may be forced through multiple
2219                          * flush groups before it can be completely
2220                          * flushed.
2221                          */
2222                         ip->flags |= HAMMER_INODE_RESIGNAL |
2223                                      HAMMER_INODE_REFLUSH;
2224                         r = -1;
2225                 } else if (rec->type == HAMMER_MEM_RECORD_ADD) {
2226                         /*
2227                          * If the target IP is not flushing we can force
2228                          * it to flush, even if it is unable to write out
2229                          * any of its own records we have at least one in
2230                          * hand that we CAN deal with.
2231                          */
2232                         rec->flush_state = HAMMER_FST_FLUSH;
2233                         rec->flush_group = flg;
2234                         ++flg->refs;
2235                         hammer_ref(&rec->lock);
2236                         hammer_flush_inode_core(target_ip, flg,
2237                                                 HAMMER_FLUSH_RECURSION);
2238                         r = 1;
2239                 } else {
2240                         /*
2241                          * General or delete-on-disk record.
2242                          *
2243                          * XXX this needs help.  If a delete-on-disk we could
2244                          * disconnect the target.  If the target has its own
2245                          * dependancies they really need to be flushed.
2246                          *
2247                          * XXX
2248                          */
2249                         rec->flush_state = HAMMER_FST_FLUSH;
2250                         rec->flush_group = flg;
2251                         ++flg->refs;
2252                         hammer_ref(&rec->lock);
2253                         hammer_flush_inode_core(target_ip, flg,
2254                                                 HAMMER_FLUSH_RECURSION);
2255                         r = 1;
2256                 }
2257                 break;
2258         case HAMMER_FST_FLUSH:
2259                 /* 
2260                  * The flush_group should already match.
2261                  */
2262                 KKASSERT(rec->flush_group == flg);
2263                 r = 1;
2264                 break;
2265         }
2266         return(r);
2267 }
2268
2269 #if 0
2270 /*
2271  * This version just moves records already in a flush state to the new
2272  * flush group and that is it.
2273  */
2274 static int
2275 hammer_syncgrp_child_callback(hammer_record_t rec, void *data)
2276 {
2277         hammer_inode_t ip = rec->ip;
2278
2279         switch(rec->flush_state) {
2280         case HAMMER_FST_FLUSH:
2281                 KKASSERT(rec->flush_group == ip->flush_group);
2282                 break;
2283         default:
2284                 break;
2285         }
2286         return(0);
2287 }
2288 #endif
2289
2290 /*
2291  * Wait for a previously queued flush to complete.
2292  *
2293  * If a critical error occured we don't try to wait.
2294  */
2295 void
2296 hammer_wait_inode(hammer_inode_t ip)
2297 {
2298         hammer_flush_group_t flg;
2299
2300         flg = NULL;
2301         if ((ip->hmp->flags & HAMMER_MOUNT_CRITICAL_ERROR) == 0) {
2302                 while (ip->flush_state != HAMMER_FST_IDLE &&
2303                        (ip->hmp->flags & HAMMER_MOUNT_CRITICAL_ERROR) == 0) {
2304                         if (ip->flush_state == HAMMER_FST_SETUP)
2305                                 hammer_flush_inode(ip, HAMMER_FLUSH_SIGNAL);
2306                         if (ip->flush_state != HAMMER_FST_IDLE) {
2307                                 ip->flags |= HAMMER_INODE_FLUSHW;
2308                                 tsleep(&ip->flags, 0, "hmrwin", 0);
2309                         }
2310                 }
2311         }
2312 }
2313
2314 /*
2315  * Called by the backend code when a flush has been completed.
2316  * The inode has already been removed from the flush list.
2317  *
2318  * A pipelined flush can occur, in which case we must re-enter the
2319  * inode on the list and re-copy its fields.
2320  */
2321 void
2322 hammer_flush_inode_done(hammer_inode_t ip, int error)
2323 {
2324         hammer_mount_t hmp;
2325         int dorel;
2326
2327         KKASSERT(ip->flush_state == HAMMER_FST_FLUSH);
2328
2329         hmp = ip->hmp;
2330
2331         /*
2332          * Auto-reflush if the backend could not completely flush
2333          * the inode.  This fixes a case where a deferred buffer flush
2334          * could cause fsync to return early.
2335          */
2336         if (ip->sync_flags & HAMMER_INODE_MODMASK)
2337                 ip->flags |= HAMMER_INODE_REFLUSH;
2338
2339         /*
2340          * Merge left-over flags back into the frontend and fix the state.
2341          * Incomplete truncations are retained by the backend.
2342          */
2343         ip->error = error;
2344         ip->flags |= ip->sync_flags & ~HAMMER_INODE_TRUNCATED;
2345         ip->sync_flags &= HAMMER_INODE_TRUNCATED;
2346
2347         /*
2348          * The backend may have adjusted nlinks, so if the adjusted nlinks
2349          * does not match the fronttend set the frontend's DDIRTY flag again.
2350          */
2351         if (ip->ino_data.nlinks != ip->sync_ino_data.nlinks)
2352                 ip->flags |= HAMMER_INODE_DDIRTY;
2353
2354         /*
2355          * Fix up the dirty buffer status.
2356          */
2357         if (ip->vp && RB_ROOT(&ip->vp->v_rbdirty_tree)) {
2358                 ip->flags |= HAMMER_INODE_BUFS;
2359         }
2360         hammer_redo_fifo_end_flush(ip);
2361
2362         /*
2363          * Re-set the XDIRTY flag if some of the inode's in-memory records
2364          * could not be flushed.
2365          */
2366         KKASSERT((RB_EMPTY(&ip->rec_tree) &&
2367                   (ip->flags & HAMMER_INODE_XDIRTY) == 0) ||
2368                  (!RB_EMPTY(&ip->rec_tree) &&
2369                   (ip->flags & HAMMER_INODE_XDIRTY) != 0));
2370
2371         /*
2372          * Do not lose track of inodes which no longer have vnode
2373          * assocations, otherwise they may never get flushed again.
2374          *
2375          * The reflush flag can be set superfluously, causing extra pain
2376          * for no reason.  If the inode is no longer modified it no longer
2377          * needs to be flushed.
2378          */
2379         if (ip->flags & HAMMER_INODE_MODMASK) {
2380                 if (ip->vp == NULL)
2381                         ip->flags |= HAMMER_INODE_REFLUSH;
2382         } else {
2383                 ip->flags &= ~HAMMER_INODE_REFLUSH;
2384         }
2385
2386         /*
2387          * Adjust the flush state.
2388          */
2389         if (ip->flags & HAMMER_INODE_WOULDBLOCK) {
2390                 /*
2391                  * We were unable to flush out all our records, leave the
2392                  * inode in a flush state and in the current flush group.
2393                  * The flush group will be re-run.
2394                  *
2395                  * This occurs if the UNDO block gets too full or there is
2396                  * too much dirty meta-data and allows the flusher to
2397                  * finalize the UNDO block and then re-flush.
2398                  */
2399                 ip->flags &= ~HAMMER_INODE_WOULDBLOCK;
2400                 dorel = 0;
2401         } else {
2402                 /*
2403                  * Remove from the flush_group
2404                  */
2405                 RB_REMOVE(hammer_fls_rb_tree, &ip->flush_group->flush_tree, ip);
2406                 ip->flush_group = NULL;
2407
2408 #if 0
2409                 /*
2410                  * Clean up the vnode ref and tracking counts.
2411                  */
2412                 if (ip->flags & HAMMER_INODE_VHELD) {
2413                         ip->flags &= ~HAMMER_INODE_VHELD;
2414                         vrele(ip->vp);
2415                 }
2416 #endif
2417                 --hmp->count_iqueued;
2418                 --hammer_count_iqueued;
2419
2420                 /*
2421                  * And adjust the state.
2422                  */
2423                 if (TAILQ_EMPTY(&ip->target_list) && RB_EMPTY(&ip->rec_tree)) {
2424                         ip->flush_state = HAMMER_FST_IDLE;
2425                         dorel = 1;
2426                 } else {
2427                         ip->flush_state = HAMMER_FST_SETUP;
2428                         dorel = 0;
2429                 }
2430
2431                 /*
2432                  * If the frontend is waiting for a flush to complete,
2433                  * wake it up.
2434                  */
2435                 if (ip->flags & HAMMER_INODE_FLUSHW) {
2436                         ip->flags &= ~HAMMER_INODE_FLUSHW;
2437                         wakeup(&ip->flags);
2438                 }
2439
2440                 /*
2441                  * If the frontend made more changes and requested another
2442                  * flush, then try to get it running.
2443                  *
2444                  * Reflushes are aborted when the inode is errored out.
2445                  */
2446                 if (ip->flags & HAMMER_INODE_REFLUSH) {
2447                         ip->flags &= ~HAMMER_INODE_REFLUSH;
2448                         if (ip->flags & HAMMER_INODE_RESIGNAL) {
2449                                 ip->flags &= ~HAMMER_INODE_RESIGNAL;
2450                                 hammer_flush_inode(ip, HAMMER_FLUSH_SIGNAL);
2451                         } else {
2452                                 hammer_flush_inode(ip, 0);
2453                         }
2454                 }
2455         }
2456
2457         /*
2458          * If we have no parent dependancies we can clear CONN_DOWN
2459          */
2460         if (TAILQ_EMPTY(&ip->target_list))
2461                 ip->flags &= ~HAMMER_INODE_CONN_DOWN;
2462
2463         /*
2464          * If the inode is now clean drop the space reservation.
2465          */
2466         if ((ip->flags & HAMMER_INODE_MODMASK) == 0 &&
2467             (ip->flags & HAMMER_INODE_RSV_INODES)) {
2468                 ip->flags &= ~HAMMER_INODE_RSV_INODES;
2469                 --hmp->rsv_inodes;
2470         }
2471
2472         if (dorel)
2473                 hammer_rel_inode(ip, 0);
2474 }
2475
2476 /*
2477  * Called from hammer_sync_inode() to synchronize in-memory records
2478  * to the media.
2479  */
2480 static int
2481 hammer_sync_record_callback(hammer_record_t record, void *data)
2482 {
2483         hammer_cursor_t cursor = data;
2484         hammer_transaction_t trans = cursor->trans;
2485         hammer_mount_t hmp = trans->hmp;
2486         int error;
2487
2488         /*
2489          * Skip records that do not belong to the current flush.
2490          */
2491         ++hammer_stats_record_iterations;
2492         if (record->flush_state != HAMMER_FST_FLUSH)
2493                 return(0);
2494
2495 #if 1
2496         if (record->flush_group != record->ip->flush_group) {
2497                 kprintf("sync_record %p ip %p bad flush group %p %p\n", record, record->ip, record->flush_group ,record->ip->flush_group);
2498                 if (hammer_debug_critical)
2499                         Debugger("blah2");
2500                 return(0);
2501         }
2502 #endif
2503         KKASSERT(record->flush_group == record->ip->flush_group);
2504
2505         /*
2506          * Interlock the record using the BE flag.  Once BE is set the
2507          * frontend cannot change the state of FE.
2508          *
2509          * NOTE: If FE is set prior to us setting BE we still sync the
2510          * record out, but the flush completion code converts it to 
2511          * a delete-on-disk record instead of destroying it.
2512          */
2513         KKASSERT((record->flags & HAMMER_RECF_INTERLOCK_BE) == 0);
2514         record->flags |= HAMMER_RECF_INTERLOCK_BE;
2515
2516         /*
2517          * The backend has already disposed of the record.
2518          */
2519         if (record->flags & (HAMMER_RECF_DELETED_BE | HAMMER_RECF_COMMITTED)) {
2520                 error = 0;
2521                 goto done;
2522         }
2523
2524         /*
2525          * If the whole inode is being deleting all on-disk records will
2526          * be deleted very soon, we can't sync any new records to disk
2527          * because they will be deleted in the same transaction they were
2528          * created in (delete_tid == create_tid), which will assert.
2529          *
2530          * XXX There may be a case with RECORD_ADD with DELETED_FE set
2531          * that we currently panic on.
2532          */
2533         if (record->ip->sync_flags & HAMMER_INODE_DELETING) {
2534                 switch(record->type) {
2535                 case HAMMER_MEM_RECORD_DATA:
2536                         /*
2537                          * We don't have to do anything, if the record was
2538                          * committed the space will have been accounted for
2539                          * in the blockmap.
2540                          */
2541                         /* fall through */
2542                 case HAMMER_MEM_RECORD_GENERAL:
2543                         /*
2544                          * Set deleted-by-backend flag.  Do not set the
2545                          * backend committed flag, because we are throwing
2546                          * the record away.
2547                          */
2548                         record->flags |= HAMMER_RECF_DELETED_BE;
2549                         ++record->ip->rec_generation;
2550                         error = 0;
2551                         goto done;
2552                 case HAMMER_MEM_RECORD_ADD:
2553                         panic("hammer_sync_record_callback: illegal add "
2554                               "during inode deletion record %p", record);
2555                         break; /* NOT REACHED */
2556                 case HAMMER_MEM_RECORD_INODE:
2557                         panic("hammer_sync_record_callback: attempt to "
2558                               "sync inode record %p?", record);
2559                         break; /* NOT REACHED */
2560                 case HAMMER_MEM_RECORD_DEL:
2561                         /* 
2562                          * Follow through and issue the on-disk deletion
2563                          */
2564                         break;
2565                 }
2566         }
2567
2568         /*
2569          * If DELETED_FE is set special handling is needed for directory
2570          * entries.  Dependant pieces related to the directory entry may
2571          * have already been synced to disk.  If this occurs we have to
2572          * sync the directory entry and then change the in-memory record
2573          * from an ADD to a DELETE to cover the fact that it's been
2574          * deleted by the frontend.
2575          *
2576          * A directory delete covering record (MEM_RECORD_DEL) can never
2577          * be deleted by the frontend.
2578          *
2579          * Any other record type (aka DATA) can be deleted by the frontend.
2580          * XXX At the moment the flusher must skip it because there may
2581          * be another data record in the flush group for the same block,
2582          * meaning that some frontend data changes can leak into the backend's
2583          * synchronization point.
2584          */
2585         if (record->flags & HAMMER_RECF_DELETED_FE) {
2586                 if (record->type == HAMMER_MEM_RECORD_ADD) {
2587                         /*
2588                          * Convert a front-end deleted directory-add to
2589                          * a directory-delete entry later.
2590                          */
2591                         record->flags |= HAMMER_RECF_CONVERT_DELETE;
2592                 } else {
2593                         /*
2594                          * Dispose of the record (race case).  Mark as
2595                          * deleted by backend (and not committed).
2596                          */
2597                         KKASSERT(record->type != HAMMER_MEM_RECORD_DEL);
2598                         record->flags |= HAMMER_RECF_DELETED_BE;
2599                         ++record->ip->rec_generation;
2600                         error = 0;
2601                         goto done;
2602                 }
2603         }
2604
2605         /*
2606          * Assign the create_tid for new records.  Deletions already
2607          * have the record's entire key properly set up.
2608          */
2609         if (record->type != HAMMER_MEM_RECORD_DEL) {
2610                 record->leaf.base.create_tid = trans->tid;
2611                 record->leaf.create_ts = trans->time32;
2612         }
2613
2614         /*
2615          * This actually moves the record to the on-media B-Tree.  We
2616          * must also generate REDO_TERM entries in the UNDO/REDO FIFO
2617          * indicating that the related REDO_WRITE(s) have been committed.
2618          *
2619          * During recovery any REDO_TERM's within the nominal recovery span
2620          * are ignored since the related meta-data is being undone, causing
2621          * any matching REDO_WRITEs to execute.  The REDO_TERMs outside
2622          * the nominal recovery span will match against REDO_WRITEs and
2623          * prevent them from being executed (because the meta-data has
2624          * already been synchronized).
2625          */
2626         if (record->flags & HAMMER_RECF_REDO) {
2627                 KKASSERT(record->type == HAMMER_MEM_RECORD_DATA);
2628                 hammer_generate_redo(trans, record->ip,
2629                                      record->leaf.base.key -
2630                                          record->leaf.data_len,
2631                                      HAMMER_REDO_TERM_WRITE,
2632                                      NULL,
2633                                      record->leaf.data_len);
2634         }
2635         for (;;) {
2636                 error = hammer_ip_sync_record_cursor(cursor, record);
2637                 if (error != EDEADLK)
2638                         break;
2639                 hammer_done_cursor(cursor);
2640                 error = hammer_init_cursor(trans, cursor, &record->ip->cache[0],
2641                                            record->ip);
2642                 if (error)
2643                         break;
2644         }
2645         record->flags &= ~HAMMER_RECF_CONVERT_DELETE;
2646
2647         if (error)
2648                 error = -error;
2649 done:
2650         hammer_flush_record_done(record, error);
2651
2652         /*
2653          * Do partial finalization if we have built up too many dirty
2654          * buffers.  Otherwise a buffer cache deadlock can occur when
2655          * doing things like creating tens of thousands of tiny files.
2656          *
2657          * We must release our cursor lock to avoid a 3-way deadlock
2658          * due to the exclusive sync lock the finalizer must get.
2659          *
2660          * WARNING: See warnings in hammer_unlock_cursor() function.
2661          */
2662         if (hammer_flusher_meta_limit(hmp)) {
2663                 hammer_unlock_cursor(cursor);
2664                 hammer_flusher_finalize(trans, 0);
2665                 hammer_lock_cursor(cursor);
2666         }
2667
2668         return(error);
2669 }
2670
2671 /*
2672  * Backend function called by the flusher to sync an inode to media.
2673  */
2674 int
2675 hammer_sync_inode(hammer_transaction_t trans, hammer_inode_t ip)
2676 {
2677         struct hammer_cursor cursor;
2678         hammer_node_t tmp_node;
2679         hammer_record_t depend;
2680         hammer_record_t next;
2681         int error, tmp_error;
2682         u_int64_t nlinks;
2683
2684         if ((ip->sync_flags & HAMMER_INODE_MODMASK) == 0)
2685                 return(0);
2686
2687         error = hammer_init_cursor(trans, &cursor, &ip->cache[1], ip);
2688         if (error)
2689                 goto done;
2690
2691         /*
2692          * Any directory records referencing this inode which are not in
2693          * our current flush group must adjust our nlink count for the
2694          * purposes of synchronizating to disk.
2695          *
2696          * Records which are in our flush group can be unlinked from our
2697          * inode now, potentially allowing the inode to be physically
2698          * deleted.
2699          *
2700          * This cannot block.
2701          */
2702         nlinks = ip->ino_data.nlinks;
2703         next = TAILQ_FIRST(&ip->target_list);
2704         while ((depend = next) != NULL) {
2705                 next = TAILQ_NEXT(depend, target_entry);
2706                 if (depend->flush_state == HAMMER_FST_FLUSH &&
2707                     depend->flush_group == ip->flush_group) {
2708                         /*
2709                          * If this is an ADD that was deleted by the frontend
2710                          * the frontend nlinks count will have already been
2711                          * decremented, but the backend is going to sync its
2712                          * directory entry and must account for it.  The
2713                          * record will be converted to a delete-on-disk when
2714                          * it gets synced.
2715                          *
2716                          * If the ADD was not deleted by the frontend we
2717                          * can remove the dependancy from our target_list.
2718                          */
2719                         if (depend->flags & HAMMER_RECF_DELETED_FE) {
2720                                 ++nlinks;
2721                         } else {
2722                                 TAILQ_REMOVE(&ip->target_list, depend,
2723                                              target_entry);
2724                                 depend->target_ip = NULL;
2725                         }
2726                 } else if ((depend->flags & HAMMER_RECF_DELETED_FE) == 0) {
2727                         /*
2728                          * Not part of our flush group and not deleted by
2729                          * the front-end, adjust the link count synced to
2730                          * the media (undo what the frontend did when it
2731                          * queued the record).
2732                          */
2733                         KKASSERT((depend->flags & HAMMER_RECF_DELETED_BE) == 0);
2734                         switch(depend->type) {
2735                         case HAMMER_MEM_RECORD_ADD:
2736                                 --nlinks;
2737                                 break;
2738                         case HAMMER_MEM_RECORD_DEL:
2739                                 ++nlinks;
2740                                 break;
2741                         default:
2742                                 break;
2743                         }
2744                 }
2745         }
2746
2747         /*
2748          * Set dirty if we had to modify the link count.
2749          */
2750         if (ip->sync_ino_data.nlinks != nlinks) {
2751                 KKASSERT((int64_t)nlinks >= 0);
2752                 ip->sync_ino_data.nlinks = nlinks;
2753                 ip->sync_flags |= HAMMER_INODE_DDIRTY;
2754         }
2755
2756         /*
2757          * If there is a trunction queued destroy any data past the (aligned)
2758          * truncation point.  Userland will have dealt with the buffer
2759          * containing the truncation point for us.
2760          *
2761          * We don't flush pending frontend data buffers until after we've
2762          * dealt with the truncation.
2763          */
2764         if (ip->sync_flags & HAMMER_INODE_TRUNCATED) {
2765                 /*
2766                  * Interlock trunc_off.  The VOP front-end may continue to
2767                  * make adjustments to it while we are blocked.
2768                  */
2769                 off_t trunc_off;
2770                 off_t aligned_trunc_off;
2771                 int blkmask;
2772
2773                 trunc_off = ip->sync_trunc_off;
2774                 blkmask = hammer_blocksize(trunc_off) - 1;
2775                 aligned_trunc_off = (trunc_off + blkmask) & ~(int64_t)blkmask;
2776
2777                 /*
2778                  * Delete any whole blocks on-media.  The front-end has
2779                  * already cleaned out any partial block and made it
2780                  * pending.  The front-end may have updated trunc_off
2781                  * while we were blocked so we only use sync_trunc_off.
2782                  *
2783                  * This operation can blow out the buffer cache, EWOULDBLOCK
2784                  * means we were unable to complete the deletion.  The
2785                  * deletion will update sync_trunc_off in that case.
2786                  */
2787                 error = hammer_ip_delete_range(&cursor, ip,
2788                                                 aligned_trunc_off,
2789                                                 0x7FFFFFFFFFFFFFFFLL, 2);
2790                 if (error == EWOULDBLOCK) {
2791                         ip->flags |= HAMMER_INODE_WOULDBLOCK;
2792                         error = 0;
2793                         goto defer_buffer_flush;
2794                 }
2795
2796                 if (error)
2797                         goto done;
2798
2799                 /*
2800                  * Generate a REDO_TERM_TRUNC entry in the UNDO/REDO FIFO.
2801                  *
2802                  * XXX we do this even if we did not previously generate
2803                  * a REDO_TRUNC record.  This operation may enclosed the
2804                  * range for multiple prior truncation entries in the REDO
2805                  * log.
2806                  */
2807                 if (trans->hmp->version >= HAMMER_VOL_VERSION_FOUR &&
2808                     (ip->flags & HAMMER_INODE_RDIRTY)) {
2809                         hammer_generate_redo(trans, ip, aligned_trunc_off,
2810                                              HAMMER_REDO_TERM_TRUNC,
2811                                              NULL, 0);
2812                 }
2813
2814                 /*
2815                  * Clear the truncation flag on the backend after we have
2816                  * completed the deletions.  Backend data is now good again
2817                  * (including new records we are about to sync, below).
2818                  *
2819                  * Leave sync_trunc_off intact.  As we write additional
2820                  * records the backend will update sync_trunc_off.  This
2821                  * tells the backend whether it can skip the overwrite
2822                  * test.  This should work properly even when the backend
2823                  * writes full blocks where the truncation point straddles
2824                  * the block because the comparison is against the base
2825                  * offset of the record.
2826                  */
2827                 ip->sync_flags &= ~HAMMER_INODE_TRUNCATED;
2828                 /* ip->sync_trunc_off = 0x7FFFFFFFFFFFFFFFLL; */
2829         } else {
2830                 error = 0;
2831         }
2832
2833         /*
2834          * Now sync related records.  These will typically be directory
2835          * entries, records tracking direct-writes, or delete-on-disk records.
2836          */
2837         if (error == 0) {
2838                 tmp_error = RB_SCAN(hammer_rec_rb_tree, &ip->rec_tree, NULL,
2839                                     hammer_sync_record_callback, &cursor);
2840                 if (tmp_error < 0)
2841                         tmp_error = -error;
2842                 if (tmp_error)
2843                         error = tmp_error;
2844         }
2845         hammer_cache_node(&ip->cache[1], cursor.node);
2846
2847         /*
2848          * Re-seek for inode update, assuming our cache hasn't been ripped
2849          * out from under us.
2850          */
2851         if (error == 0) {
2852                 tmp_node = hammer_ref_node_safe(trans, &ip->cache[0], &error);
2853                 if (tmp_node) {
2854                         hammer_cursor_downgrade(&cursor);
2855                         hammer_lock_sh(&tmp_node->lock);
2856                         if ((tmp_node->flags & HAMMER_NODE_DELETED) == 0)
2857                                 hammer_cursor_seek(&cursor, tmp_node, 0);
2858                         hammer_unlock(&tmp_node->lock);
2859                         hammer_rel_node(tmp_node);
2860                 }
2861                 error = 0;
2862         }
2863
2864         /*
2865          * If we are deleting the inode the frontend had better not have
2866          * any active references on elements making up the inode.
2867          *
2868          * The call to hammer_ip_delete_clean() cleans up auxillary records
2869          * but not DB or DATA records.  Those must have already been deleted
2870          * by the normal truncation mechanic.
2871          */
2872         if (error == 0 && ip->sync_ino_data.nlinks == 0 &&
2873                 RB_EMPTY(&ip->rec_tree)  &&
2874             (ip->sync_flags & HAMMER_INODE_DELETING) &&
2875             (ip->flags & HAMMER_INODE_DELETED) == 0) {
2876                 int count1 = 0;
2877
2878                 error = hammer_ip_delete_clean(&cursor, ip, &count1);
2879                 if (error == 0) {
2880                         ip->flags |= HAMMER_INODE_DELETED;
2881                         ip->sync_flags &= ~HAMMER_INODE_DELETING;
2882                         ip->sync_flags &= ~HAMMER_INODE_TRUNCATED;
2883                         KKASSERT(RB_EMPTY(&ip->rec_tree));
2884
2885                         /*
2886                          * Set delete_tid in both the frontend and backend
2887                          * copy of the inode record.  The DELETED flag handles
2888                          * this, do not set DDIRTY.
2889                          */
2890                         ip->ino_leaf.base.delete_tid = trans->tid;
2891                         ip->sync_ino_leaf.base.delete_tid = trans->tid;
2892                         ip->ino_leaf.delete_ts = trans->time32;
2893                         ip->sync_ino_leaf.delete_ts = trans->time32;
2894
2895
2896                         /*
2897                          * Adjust the inode count in the volume header
2898                          */
2899                         hammer_sync_lock_sh(trans);
2900                         if (ip->flags & HAMMER_INODE_ONDISK) {
2901                                 hammer_modify_volume_field(trans,
2902                                                            trans->rootvol,
2903                                                            vol0_stat_inodes);
2904                                 --ip->hmp->rootvol->ondisk->vol0_stat_inodes;
2905                                 hammer_modify_volume_done(trans->rootvol);
2906                         }
2907                         hammer_sync_unlock(trans);
2908                 }
2909         }
2910
2911         if (error)
2912                 goto done;
2913         ip->sync_flags &= ~HAMMER_INODE_BUFS;
2914
2915 defer_buffer_flush:
2916         /*
2917          * Now update the inode's on-disk inode-data and/or on-disk record.
2918          * DELETED and ONDISK are managed only in ip->flags.
2919          *
2920          * In the case of a defered buffer flush we still update the on-disk
2921          * inode to satisfy visibility requirements if there happen to be
2922          * directory dependancies.
2923          */
2924         switch(ip->flags & (HAMMER_INODE_DELETED | HAMMER_INODE_ONDISK)) {
2925         case HAMMER_INODE_DELETED|HAMMER_INODE_ONDISK:
2926                 /*
2927                  * If deleted and on-disk, don't set any additional flags.
2928                  * the delete flag takes care of things.
2929                  *
2930                  * Clear flags which may have been set by the frontend.
2931                  */
2932                 ip->sync_flags &= ~(HAMMER_INODE_DDIRTY | HAMMER_INODE_XDIRTY |
2933                                     HAMMER_INODE_SDIRTY |
2934                                     HAMMER_INODE_ATIME | HAMMER_INODE_MTIME |
2935                                     HAMMER_INODE_DELETING);
2936                 break;
2937         case HAMMER_INODE_DELETED:
2938                 /*
2939                  * Take care of the case where a deleted inode was never
2940                  * flushed to the disk in the first place.
2941                  *
2942                  * Clear flags which may have been set by the frontend.
2943                  */
2944                 ip->sync_flags &= ~(HAMMER_INODE_DDIRTY | HAMMER_INODE_XDIRTY |
2945                                     HAMMER_INODE_SDIRTY |
2946                                     HAMMER_INODE_ATIME | HAMMER_INODE_MTIME |
2947                                     HAMMER_INODE_DELETING);
2948                 while (RB_ROOT(&ip->rec_tree)) {
2949                         hammer_record_t record = RB_ROOT(&ip->rec_tree);
2950                         hammer_ref(&record->lock);
2951                         KKASSERT(record->lock.refs == 1);
2952                         record->flags |= HAMMER_RECF_DELETED_BE;
2953                         ++record->ip->rec_generation;
2954                         hammer_rel_mem_record(record);
2955                 }
2956                 break;
2957         case HAMMER_INODE_ONDISK:
2958                 /*
2959                  * If already on-disk, do not set any additional flags.
2960                  */
2961                 break;
2962         default:
2963                 /*
2964                  * If not on-disk and not deleted, set DDIRTY to force
2965                  * an initial record to be written.
2966                  *
2967                  * Also set the create_tid in both the frontend and backend
2968                  * copy of the inode record.
2969                  */
2970                 ip->ino_leaf.base.create_tid = trans->tid;
2971                 ip->ino_leaf.create_ts = trans->time32;
2972                 ip->sync_ino_leaf.base.create_tid = trans->tid;
2973                 ip->sync_ino_leaf.create_ts = trans->time32;
2974                 ip->sync_flags |= HAMMER_INODE_DDIRTY;
2975                 break;
2976         }
2977
2978         /*
2979          * If DDIRTY or SDIRTY is set, write out a new record.
2980          * If the inode is already on-disk the old record is marked as
2981          * deleted.
2982          *
2983          * If DELETED is set hammer_update_inode() will delete the existing
2984          * record without writing out a new one.
2985          *
2986          * If *ONLY* the ITIMES flag is set we can update the record in-place.
2987          */
2988         if (ip->flags & HAMMER_INODE_DELETED) {
2989                 error = hammer_update_inode(&cursor, ip);
2990         } else 
2991         if (!(ip->sync_flags & (HAMMER_INODE_DDIRTY | HAMMER_INODE_SDIRTY)) &&
2992             (ip->sync_flags & (HAMMER_INODE_ATIME | HAMMER_INODE_MTIME))) {
2993                 error = hammer_update_itimes(&cursor, ip);
2994         } else
2995         if (ip->sync_flags & (HAMMER_INODE_DDIRTY | HAMMER_INODE_SDIRTY |
2996                               HAMMER_INODE_ATIME | HAMMER_INODE_MTIME)) {
2997                 error = hammer_update_inode(&cursor, ip);
2998         }
2999 done:
3000         if (error) {
3001                 hammer_critical_error(ip->hmp, ip, error,
3002                                       "while syncing inode");
3003         }
3004         hammer_done_cursor(&cursor);
3005         return(error);
3006 }
3007
3008 /*
3009  * This routine is called when the OS is no longer actively referencing
3010  * the inode (but might still be keeping it cached), or when releasing
3011  * the last reference to an inode.
3012  *
3013  * At this point if the inode's nlinks count is zero we want to destroy
3014  * it, which may mean destroying it on-media too.
3015  */
3016 void
3017 hammer_inode_unloadable_check(hammer_inode_t ip, int getvp)
3018 {
3019         struct vnode *vp;
3020
3021         /*
3022          * Set the DELETING flag when the link count drops to 0 and the
3023          * OS no longer has any opens on the inode.
3024          *
3025          * The backend will clear DELETING (a mod flag) and set DELETED
3026          * (a state flag) when it is actually able to perform the
3027          * operation.
3028          *
3029          * Don't reflag the deletion if the flusher is currently syncing
3030          * one that was already flagged.  A previously set DELETING flag
3031          * may bounce around flags and sync_flags until the operation is
3032          * completely done.
3033          */
3034         if (ip->ino_data.nlinks == 0 &&
3035             ((ip->flags | ip->sync_flags) & (HAMMER_INODE_DELETING|HAMMER_INODE_DELETED)) == 0) {
3036                 ip->flags |= HAMMER_INODE_DELETING;
3037                 ip->flags |= HAMMER_INODE_TRUNCATED;
3038                 ip->trunc_off = 0;
3039                 vp = NULL;
3040                 if (getvp) {
3041                         if (hammer_get_vnode(ip, &vp) != 0)
3042                                 return;
3043                 }
3044
3045                 /*
3046                  * Final cleanup
3047                  */
3048                 if (ip->vp) {
3049                         vtruncbuf(ip->vp, 0, HAMMER_BUFSIZE);
3050                         vnode_pager_setsize(ip->vp, 0);
3051                 }
3052                 if (getvp) {
3053                         vput(vp);
3054                 }
3055         }
3056 }
3057
3058 /*
3059  * After potentially resolving a dependancy the inode is tested
3060  * to determine whether it needs to be reflushed.
3061  */
3062 void
3063 hammer_test_inode(hammer_inode_t ip)
3064 {
3065         if (ip->flags & HAMMER_INODE_REFLUSH) {
3066                 ip->flags &= ~HAMMER_INODE_REFLUSH;
3067                 hammer_ref(&ip->lock);
3068                 if (ip->flags & HAMMER_INODE_RESIGNAL) {
3069                         ip->flags &= ~HAMMER_INODE_RESIGNAL;
3070                         hammer_flush_inode(ip, HAMMER_FLUSH_SIGNAL);
3071                 } else {
3072                         hammer_flush_inode(ip, 0);
3073                 }
3074                 hammer_rel_inode(ip, 0);
3075         }
3076 }
3077
3078 /*
3079  * Clear the RECLAIM flag on an inode.  This occurs when the inode is
3080  * reassociated with a vp or just before it gets freed.
3081  *
3082  * Pipeline wakeups to threads blocked due to an excessive number of
3083  * detached inodes.  This typically occurs when atime updates accumulate
3084  * while scanning a directory tree.
3085  */
3086 static void
3087 hammer_inode_wakereclaims(hammer_inode_t ip)
3088 {
3089         struct hammer_reclaim *reclaim;
3090         hammer_mount_t hmp = ip->hmp;
3091
3092         if ((ip->flags & HAMMER_INODE_RECLAIM) == 0)
3093                 return;
3094
3095         --hammer_count_reclaiming;
3096         --hmp->inode_reclaims;
3097         ip->flags &= ~HAMMER_INODE_RECLAIM;
3098
3099         while ((reclaim = TAILQ_FIRST(&hmp->reclaim_list)) != NULL) {
3100                 if (reclaim->count > 0 && --reclaim->count == 0) {
3101                         TAILQ_REMOVE(&hmp->reclaim_list, reclaim, entry);
3102                         wakeup(reclaim);
3103                 }
3104                 if (hmp->inode_reclaims > hammer_limit_reclaim / 2)
3105                         break;
3106         }
3107 }
3108
3109 /*
3110  * Setup our reclaim pipeline.  We only let so many detached (and dirty)
3111  * inodes build up before we start blocking.  This routine is called
3112  * if a new inode is created or an inode is loaded from media.
3113  *
3114  * When we block we don't care *which* inode has finished reclaiming,
3115  * as lone as one does.
3116  */
3117 void
3118 hammer_inode_waitreclaims(hammer_mount_t hmp)
3119 {
3120         struct hammer_reclaim reclaim;
3121
3122         if (hmp->inode_reclaims < hammer_limit_reclaim)
3123                 return;
3124         reclaim.count = 1;
3125         TAILQ_INSERT_TAIL(&hmp->reclaim_list, &reclaim, entry);
3126         tsleep(&reclaim, 0, "hmrrcm", hz);
3127         if (reclaim.count > 0)
3128                 TAILQ_REMOVE(&hmp->reclaim_list, &reclaim, entry);
3129 }
3130
3131 #if 0
3132
3133 /*
3134  * XXX not used, doesn't work very well due to the large batching nature
3135  * of flushes.
3136  *
3137  * A larger then normal backlog of inodes is sitting in the flusher,
3138  * enforce a general slowdown to let it catch up.  This routine is only
3139  * called on completion of a non-flusher-related transaction which
3140  * performed B-Tree node I/O.
3141  *
3142  * It is possible for the flusher to stall in a continuous load.
3143  * blogbench -i1000 -o seems to do a good job generating this sort of load.
3144  * If the flusher is unable to catch up the inode count can bloat until
3145  * we run out of kvm.
3146  *
3147  * This is a bit of a hack.
3148  */
3149 void
3150 hammer_inode_waithard(hammer_mount_t hmp)
3151 {
3152         /*
3153          * Hysteresis.
3154          */
3155         if (hmp->flags & HAMMER_MOUNT_FLUSH_RECOVERY) {
3156                 if (hmp->inode_reclaims < hammer_limit_reclaim / 2 &&
3157                     hmp->count_iqueued < hmp->count_inodes / 20) {
3158                         hmp->flags &= ~HAMMER_MOUNT_FLUSH_RECOVERY;
3159                         return;
3160                 }
3161         } else {
3162                 if (hmp->inode_reclaims < hammer_limit_reclaim ||
3163                     hmp->count_iqueued < hmp->count_inodes / 10) {
3164                         return;
3165                 }
3166                 hmp->flags |= HAMMER_MOUNT_FLUSH_RECOVERY;
3167         }
3168
3169         /*
3170          * Block for one flush cycle.
3171          */
3172         hammer_flusher_wait_next(hmp);
3173 }
3174
3175 #endif