HAMMER 60I/Many: Mirroring
[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.96 2008/07/09 10:29:20 dillon Exp $
35  */
36
37 #include "hammer.h"
38 #include <vm/vm_extern.h>
39 #include <sys/buf.h>
40 #include <sys/buf2.h>
41
42 static int      hammer_unload_inode(struct hammer_inode *ip);
43 static void     hammer_free_inode(hammer_inode_t ip);
44 static void     hammer_flush_inode_core(hammer_inode_t ip, int flags);
45 static int      hammer_setup_child_callback(hammer_record_t rec, void *data);
46 static int      hammer_syncgrp_child_callback(hammer_record_t rec, void *data);
47 static int      hammer_setup_parent_inodes(hammer_inode_t ip);
48 static int      hammer_setup_parent_inodes_helper(hammer_record_t record);
49 static void     hammer_inode_wakereclaims(hammer_inode_t ip);
50
51 #ifdef DEBUG_TRUNCATE
52 extern struct hammer_inode *HammerTruncIp;
53 #endif
54
55 /*
56  * RB-Tree support for inode structures
57  */
58 int
59 hammer_ino_rb_compare(hammer_inode_t ip1, hammer_inode_t ip2)
60 {
61         if (ip1->obj_localization < ip2->obj_localization)
62                 return(-1);
63         if (ip1->obj_localization > ip2->obj_localization)
64                 return(1);
65         if (ip1->obj_id < ip2->obj_id)
66                 return(-1);
67         if (ip1->obj_id > ip2->obj_id)
68                 return(1);
69         if (ip1->obj_asof < ip2->obj_asof)
70                 return(-1);
71         if (ip1->obj_asof > ip2->obj_asof)
72                 return(1);
73         return(0);
74 }
75
76 /*
77  * RB-Tree support for inode structures / special LOOKUP_INFO
78  */
79 static int
80 hammer_inode_info_cmp(hammer_inode_info_t info, hammer_inode_t ip)
81 {
82         if (info->obj_localization < ip->obj_localization)
83                 return(-1);
84         if (info->obj_localization > ip->obj_localization)
85                 return(1);
86         if (info->obj_id < ip->obj_id)
87                 return(-1);
88         if (info->obj_id > ip->obj_id)
89                 return(1);
90         if (info->obj_asof < ip->obj_asof)
91                 return(-1);
92         if (info->obj_asof > ip->obj_asof)
93                 return(1);
94         return(0);
95 }
96
97 /*
98  * Used by hammer_scan_inode_snapshots() to locate all of an object's
99  * snapshots.  Note that the asof field is not tested, which we can get
100  * away with because it is the lowest-priority field.
101  */
102 static int
103 hammer_inode_info_cmp_all_history(hammer_inode_t ip, void *data)
104 {
105         hammer_inode_info_t info = data;
106
107         if (ip->obj_localization > info->obj_localization)
108                 return(1);
109         if (ip->obj_localization < info->obj_localization)
110                 return(-1);
111         if (ip->obj_id > info->obj_id)
112                 return(1);
113         if (ip->obj_id < info->obj_id)
114                 return(-1);
115         return(0);
116 }
117
118 /*
119  * RB-Tree support for pseudofs structures
120  */
121 static int
122 hammer_pfs_rb_compare(hammer_pseudofs_inmem_t p1, hammer_pseudofs_inmem_t p2)
123 {
124         if (p1->localization < p2->localization)
125                 return(-1);
126         if (p1->localization > p2->localization)
127                 return(1);
128         return(0);
129 }
130
131
132 RB_GENERATE(hammer_ino_rb_tree, hammer_inode, rb_node, hammer_ino_rb_compare);
133 RB_GENERATE_XLOOKUP(hammer_ino_rb_tree, INFO, hammer_inode, rb_node,
134                 hammer_inode_info_cmp, hammer_inode_info_t);
135 RB_GENERATE2(hammer_pfs_rb_tree, hammer_pseudofs_inmem, rb_node,
136              hammer_pfs_rb_compare, u_int32_t, localization);
137
138 /*
139  * The kernel is not actively referencing this vnode but is still holding
140  * it cached.
141  *
142  * This is called from the frontend.
143  */
144 int
145 hammer_vop_inactive(struct vop_inactive_args *ap)
146 {
147         struct hammer_inode *ip = VTOI(ap->a_vp);
148
149         /*
150          * Degenerate case
151          */
152         if (ip == NULL) {
153                 vrecycle(ap->a_vp);
154                 return(0);
155         }
156
157         /*
158          * If the inode no longer has visibility in the filesystem try to
159          * recycle it immediately, even if the inode is dirty.  Recycling
160          * it quickly allows the system to reclaim buffer cache and VM
161          * resources which can matter a lot in a heavily loaded system.
162          *
163          * This can deadlock in vfsync() if we aren't careful.
164          * 
165          * Do not queue the inode to the flusher if we still have visibility,
166          * otherwise namespace calls such as chmod will unnecessarily generate
167          * multiple inode updates.
168          */
169         hammer_inode_unloadable_check(ip, 0);
170         if (ip->ino_data.nlinks == 0) {
171                 if (ip->flags & HAMMER_INODE_MODMASK)
172                         hammer_flush_inode(ip, 0);
173                 vrecycle(ap->a_vp);
174         }
175         return(0);
176 }
177
178 /*
179  * Release the vnode association.  This is typically (but not always)
180  * the last reference on the inode.
181  *
182  * Once the association is lost we are on our own with regards to
183  * flushing the inode.
184  */
185 int
186 hammer_vop_reclaim(struct vop_reclaim_args *ap)
187 {
188         struct hammer_inode *ip;
189         hammer_mount_t hmp;
190         struct vnode *vp;
191
192         vp = ap->a_vp;
193
194         if ((ip = vp->v_data) != NULL) {
195                 hmp = ip->hmp;
196                 vp->v_data = NULL;
197                 ip->vp = NULL;
198
199                 if ((ip->flags & HAMMER_INODE_RECLAIM) == 0) {
200                         ++hammer_count_reclaiming;
201                         ++hmp->inode_reclaims;
202                         ip->flags |= HAMMER_INODE_RECLAIM;
203                         if (hmp->inode_reclaims > HAMMER_RECLAIM_FLUSH &&
204                             (hmp->inode_reclaims & 255) == 0) {
205                                 hammer_flusher_async(hmp);
206                         }
207                 }
208                 hammer_rel_inode(ip, 1);
209         }
210         return(0);
211 }
212
213 /*
214  * Return a locked vnode for the specified inode.  The inode must be
215  * referenced but NOT LOCKED on entry and will remain referenced on
216  * return.
217  *
218  * Called from the frontend.
219  */
220 int
221 hammer_get_vnode(struct hammer_inode *ip, struct vnode **vpp)
222 {
223         hammer_mount_t hmp;
224         struct vnode *vp;
225         int error = 0;
226         u_int8_t obj_type;
227
228         hmp = ip->hmp;
229
230         for (;;) {
231                 if ((vp = ip->vp) == NULL) {
232                         error = getnewvnode(VT_HAMMER, hmp->mp, vpp, 0, 0);
233                         if (error)
234                                 break;
235                         hammer_lock_ex(&ip->lock);
236                         if (ip->vp != NULL) {
237                                 hammer_unlock(&ip->lock);
238                                 vp->v_type = VBAD;
239                                 vx_put(vp);
240                                 continue;
241                         }
242                         hammer_ref(&ip->lock);
243                         vp = *vpp;
244                         ip->vp = vp;
245
246                         obj_type = ip->ino_data.obj_type;
247                         vp->v_type = hammer_get_vnode_type(obj_type);
248
249                         hammer_inode_wakereclaims(ip);
250
251                         switch(ip->ino_data.obj_type) {
252                         case HAMMER_OBJTYPE_CDEV:
253                         case HAMMER_OBJTYPE_BDEV:
254                                 vp->v_ops = &hmp->mp->mnt_vn_spec_ops;
255                                 addaliasu(vp, ip->ino_data.rmajor,
256                                           ip->ino_data.rminor);
257                                 break;
258                         case HAMMER_OBJTYPE_FIFO:
259                                 vp->v_ops = &hmp->mp->mnt_vn_fifo_ops;
260                                 break;
261                         default:
262                                 break;
263                         }
264
265                         /*
266                          * Only mark as the root vnode if the ip is not
267                          * historical, otherwise the VFS cache will get
268                          * confused.  The other half of the special handling
269                          * is in hammer_vop_nlookupdotdot().
270                          *
271                          * Pseudo-filesystem roots also do not count.
272                          */
273                         if (ip->obj_id == HAMMER_OBJID_ROOT &&
274                             ip->obj_asof == hmp->asof &&
275                             ip->obj_localization == 0) {
276                                 vp->v_flag |= VROOT;
277                         }
278
279                         vp->v_data = (void *)ip;
280                         /* vnode locked by getnewvnode() */
281                         /* make related vnode dirty if inode dirty? */
282                         hammer_unlock(&ip->lock);
283                         if (vp->v_type == VREG)
284                                 vinitvmio(vp, ip->ino_data.size);
285                         break;
286                 }
287
288                 /*
289                  * loop if the vget fails (aka races), or if the vp
290                  * no longer matches ip->vp.
291                  */
292                 if (vget(vp, LK_EXCLUSIVE) == 0) {
293                         if (vp == ip->vp)
294                                 break;
295                         vput(vp);
296                 }
297         }
298         *vpp = vp;
299         return(error);
300 }
301
302 /*
303  * Locate all copies of the inode for obj_id compatible with the specified
304  * asof, reference, and issue the related call-back.  This routine is used
305  * for direct-io invalidation and does not create any new inodes.
306  */
307 void
308 hammer_scan_inode_snapshots(hammer_mount_t hmp, hammer_inode_info_t iinfo,
309                             int (*callback)(hammer_inode_t ip, void *data),
310                             void *data)
311 {
312         hammer_ino_rb_tree_RB_SCAN(&hmp->rb_inos_root,
313                                    hammer_inode_info_cmp_all_history,
314                                    callback, iinfo);
315 }
316
317 /*
318  * Acquire a HAMMER inode.  The returned inode is not locked.  These functions
319  * do not attach or detach the related vnode (use hammer_get_vnode() for
320  * that).
321  *
322  * The flags argument is only applied for newly created inodes, and only
323  * certain flags are inherited.
324  *
325  * Called from the frontend.
326  */
327 struct hammer_inode *
328 hammer_get_inode(hammer_transaction_t trans, hammer_inode_t dip,
329                  int64_t obj_id, hammer_tid_t asof, u_int32_t localization,
330                  int flags, int *errorp)
331 {
332         hammer_mount_t hmp = trans->hmp;
333         struct hammer_inode_info iinfo;
334         struct hammer_cursor cursor;
335         struct hammer_inode *ip;
336
337
338         /*
339          * Determine if we already have an inode cached.  If we do then
340          * we are golden.
341          */
342         iinfo.obj_id = obj_id;
343         iinfo.obj_asof = asof;
344         iinfo.obj_localization = localization;
345 loop:
346         ip = hammer_ino_rb_tree_RB_LOOKUP_INFO(&hmp->rb_inos_root, &iinfo);
347         if (ip) {
348                 hammer_ref(&ip->lock);
349                 *errorp = 0;
350                 return(ip);
351         }
352
353         /*
354          * Allocate a new inode structure and deal with races later.
355          */
356         ip = kmalloc(sizeof(*ip), M_HAMMER, M_WAITOK|M_ZERO);
357         ++hammer_count_inodes;
358         ++hmp->count_inodes;
359         ip->obj_id = obj_id;
360         ip->obj_asof = iinfo.obj_asof;
361         ip->obj_localization = localization;
362         ip->hmp = hmp;
363         ip->flags = flags & HAMMER_INODE_RO;
364         ip->cache[0].ip = ip;
365         ip->cache[1].ip = ip;
366         if (hmp->ronly)
367                 ip->flags |= HAMMER_INODE_RO;
368         ip->sync_trunc_off = ip->trunc_off = ip->save_trunc_off =
369                 0x7FFFFFFFFFFFFFFFLL;
370         RB_INIT(&ip->rec_tree);
371         TAILQ_INIT(&ip->target_list);
372         hammer_ref(&ip->lock);
373
374         /*
375          * Locate the on-disk inode.  If this is a PFS root we always
376          * access the current version of the root inode and (if it is not
377          * a master) always access information under it with a snapshot
378          * TID.
379          */
380 retry:
381         hammer_init_cursor(trans, &cursor, (dip ? &dip->cache[0] : NULL), NULL);
382         cursor.key_beg.localization = localization + HAMMER_LOCALIZE_INODE;
383         cursor.key_beg.obj_id = ip->obj_id;
384         cursor.key_beg.key = 0;
385         cursor.key_beg.create_tid = 0;
386         cursor.key_beg.delete_tid = 0;
387         cursor.key_beg.rec_type = HAMMER_RECTYPE_INODE;
388         cursor.key_beg.obj_type = 0;
389
390         cursor.asof = iinfo.obj_asof;
391         cursor.flags = HAMMER_CURSOR_GET_LEAF | HAMMER_CURSOR_GET_DATA |
392                        HAMMER_CURSOR_ASOF;
393
394         *errorp = hammer_btree_lookup(&cursor);
395         if (*errorp == EDEADLK) {
396                 hammer_done_cursor(&cursor);
397                 goto retry;
398         }
399
400         /*
401          * On success the B-Tree lookup will hold the appropriate
402          * buffer cache buffers and provide a pointer to the requested
403          * information.  Copy the information to the in-memory inode
404          * and cache the B-Tree node to improve future operations.
405          */
406         if (*errorp == 0) {
407                 ip->ino_leaf = cursor.node->ondisk->elms[cursor.index].leaf;
408                 ip->ino_data = cursor.data->inode;
409
410                 /*
411                  * cache[0] tries to cache the location of the object inode.
412                  * The assumption is that it is near the directory inode.
413                  *
414                  * cache[1] tries to cache the location of the object data.
415                  * The assumption is that it is near the directory data.
416                  */
417                 hammer_cache_node(&ip->cache[0], cursor.node);
418                 if (dip && dip->cache[1].node)
419                         hammer_cache_node(&ip->cache[1], dip->cache[1].node);
420
421                 /*
422                  * The file should not contain any data past the file size
423                  * stored in the inode.  Setting save_trunc_off to the
424                  * file size instead of max reduces B-Tree lookup overheads
425                  * on append by allowing the flusher to avoid checking for
426                  * record overwrites.
427                  */
428                 ip->save_trunc_off = ip->ino_data.size;
429
430                 /*
431                  * Locate and assign the pseudofs management structure to
432                  * the inode.
433                  */
434                 if (dip && dip->obj_localization == ip->obj_localization) {
435                         ip->pfsm = dip->pfsm;
436                         hammer_ref(&ip->pfsm->lock);
437                 } else {
438                         ip->pfsm = hammer_load_pseudofs(trans,
439                                                         ip->obj_localization,
440                                                         errorp);
441                         *errorp = 0;    /* ignore ENOENT */
442                 }
443         }
444
445         /*
446          * The inode is placed on the red-black tree and will be synced to
447          * the media when flushed or by the filesystem sync.  If this races
448          * another instantiation/lookup the insertion will fail.
449          */
450         if (*errorp == 0) {
451                 if (RB_INSERT(hammer_ino_rb_tree, &hmp->rb_inos_root, ip)) {
452                         hammer_free_inode(ip);
453                         hammer_done_cursor(&cursor);
454                         goto loop;
455                 }
456                 ip->flags |= HAMMER_INODE_ONDISK;
457         } else {
458                 if (ip->flags & HAMMER_INODE_RSV_INODES) {
459                         ip->flags &= ~HAMMER_INODE_RSV_INODES; /* sanity */
460                         --hmp->rsv_inodes;
461                 }
462
463                 hammer_free_inode(ip);
464                 ip = NULL;
465         }
466         hammer_done_cursor(&cursor);
467         return (ip);
468 }
469
470 /*
471  * Create a new filesystem object, returning the inode in *ipp.  The
472  * returned inode will be referenced.  The inode is created in-memory.
473  *
474  * If pfsm is non-NULL the caller wishes to create the root inode for
475  * a master PFS.
476  */
477 int
478 hammer_create_inode(hammer_transaction_t trans, struct vattr *vap,
479                     struct ucred *cred, hammer_inode_t dip,
480                     hammer_pseudofs_inmem_t pfsm, struct hammer_inode **ipp)
481 {
482         hammer_mount_t hmp;
483         hammer_inode_t ip;
484         uid_t xuid;
485         int error;
486
487         hmp = trans->hmp;
488
489         ip = kmalloc(sizeof(*ip), M_HAMMER, M_WAITOK|M_ZERO);
490         ++hammer_count_inodes;
491         ++hmp->count_inodes;
492
493         if (pfsm) {
494                 KKASSERT(pfsm->localization != 0);
495                 ip->obj_id = HAMMER_OBJID_ROOT;
496                 ip->obj_localization = pfsm->localization;
497         } else {
498                 KKASSERT(dip != NULL);
499                 ip->obj_id = hammer_alloc_objid(hmp, dip);
500                 ip->obj_localization = dip->obj_localization;
501         }
502
503         KKASSERT(ip->obj_id != 0);
504         ip->obj_asof = hmp->asof;
505         ip->hmp = hmp;
506         ip->flush_state = HAMMER_FST_IDLE;
507         ip->flags = HAMMER_INODE_DDIRTY |
508                     HAMMER_INODE_ATIME | HAMMER_INODE_MTIME;
509         ip->cache[0].ip = ip;
510         ip->cache[1].ip = ip;
511
512         ip->trunc_off = 0x7FFFFFFFFFFFFFFFLL;
513         /* ip->save_trunc_off = 0; (already zero) */
514         RB_INIT(&ip->rec_tree);
515         TAILQ_INIT(&ip->target_list);
516
517         ip->ino_data.atime = trans->time;
518         ip->ino_data.mtime = trans->time;
519         ip->ino_data.size = 0;
520         ip->ino_data.nlinks = 0;
521
522         /*
523          * A nohistory designator on the parent directory is inherited by
524          * the child.  We will do this even for pseudo-fs creation... the
525          * sysad can turn it off.
526          */
527         if (dip) {
528                 ip->ino_data.uflags = dip->ino_data.uflags &
529                                       (SF_NOHISTORY|UF_NOHISTORY|UF_NODUMP);
530         }
531
532         ip->ino_leaf.base.btype = HAMMER_BTREE_TYPE_RECORD;
533         ip->ino_leaf.base.localization = ip->obj_localization +
534                                          HAMMER_LOCALIZE_INODE;
535         ip->ino_leaf.base.obj_id = ip->obj_id;
536         ip->ino_leaf.base.key = 0;
537         ip->ino_leaf.base.create_tid = 0;
538         ip->ino_leaf.base.delete_tid = 0;
539         ip->ino_leaf.base.rec_type = HAMMER_RECTYPE_INODE;
540         ip->ino_leaf.base.obj_type = hammer_get_obj_type(vap->va_type);
541
542         ip->ino_data.obj_type = ip->ino_leaf.base.obj_type;
543         ip->ino_data.version = HAMMER_INODE_DATA_VERSION;
544         ip->ino_data.mode = vap->va_mode;
545         ip->ino_data.ctime = trans->time;
546
547         /*
548          * Setup the ".." pointer.  This only needs to be done for directories
549          * but we do it for all objects as a recovery aid.
550          */
551         if (dip)
552                 ip->ino_data.parent_obj_id = dip->ino_leaf.base.obj_id;
553 #if 0
554         /*
555          * The parent_obj_localization field only applies to pseudo-fs roots.
556          * XXX this is no longer applicable, PFSs are no longer directly
557          * tied into the parent's directory structure.
558          */
559         if (ip->ino_data.obj_type == HAMMER_OBJTYPE_DIRECTORY &&
560             ip->obj_id == HAMMER_OBJID_ROOT) {
561                 ip->ino_data.ext.obj.parent_obj_localization = 
562                                                 dip->obj_localization;
563         }
564 #endif
565
566         switch(ip->ino_leaf.base.obj_type) {
567         case HAMMER_OBJTYPE_CDEV:
568         case HAMMER_OBJTYPE_BDEV:
569                 ip->ino_data.rmajor = vap->va_rmajor;
570                 ip->ino_data.rminor = vap->va_rminor;
571                 break;
572         default:
573                 break;
574         }
575
576         /*
577          * Calculate default uid/gid and overwrite with information from
578          * the vap.
579          */
580         if (dip) {
581                 xuid = hammer_to_unix_xid(&dip->ino_data.uid);
582                 xuid = vop_helper_create_uid(hmp->mp, dip->ino_data.mode,
583                                              xuid, cred, &vap->va_mode);
584         } else {
585                 xuid = 0;
586         }
587         ip->ino_data.mode = vap->va_mode;
588
589         if (vap->va_vaflags & VA_UID_UUID_VALID)
590                 ip->ino_data.uid = vap->va_uid_uuid;
591         else if (vap->va_uid != (uid_t)VNOVAL)
592                 hammer_guid_to_uuid(&ip->ino_data.uid, vap->va_uid);
593         else
594                 hammer_guid_to_uuid(&ip->ino_data.uid, xuid);
595
596         if (vap->va_vaflags & VA_GID_UUID_VALID)
597                 ip->ino_data.gid = vap->va_gid_uuid;
598         else if (vap->va_gid != (gid_t)VNOVAL)
599                 hammer_guid_to_uuid(&ip->ino_data.gid, vap->va_gid);
600         else if (dip)
601                 ip->ino_data.gid = dip->ino_data.gid;
602
603         hammer_ref(&ip->lock);
604
605         if (pfsm) {
606                 ip->pfsm = pfsm;
607                 hammer_ref(&pfsm->lock);
608                 error = 0;
609         } else if (dip->obj_localization == ip->obj_localization) {
610                 ip->pfsm = dip->pfsm;
611                 hammer_ref(&ip->pfsm->lock);
612                 error = 0;
613         } else {
614                 ip->pfsm = hammer_load_pseudofs(trans,
615                                                 ip->obj_localization,
616                                                 &error);
617                 error = 0;      /* ignore ENOENT */
618         }
619
620         if (error) {
621                 hammer_free_inode(ip);
622                 ip = NULL;
623         } else if (RB_INSERT(hammer_ino_rb_tree, &hmp->rb_inos_root, ip)) {
624                 panic("hammer_create_inode: duplicate obj_id %llx", ip->obj_id);
625                 /* not reached */
626                 hammer_free_inode(ip);
627         }
628         *ipp = ip;
629         return(error);
630 }
631
632 /*
633  * Final cleanup / freeing of an inode structure
634  */
635 static void
636 hammer_free_inode(hammer_inode_t ip)
637 {
638         KKASSERT(ip->lock.refs == 1);
639         hammer_uncache_node(&ip->cache[0]);
640         hammer_uncache_node(&ip->cache[1]);
641         hammer_inode_wakereclaims(ip);
642         if (ip->objid_cache)
643                 hammer_clear_objid(ip);
644         --hammer_count_inodes;
645         --ip->hmp->count_inodes;
646         if (ip->pfsm) {
647                 hammer_rel_pseudofs(ip->hmp, ip->pfsm);
648                 ip->pfsm = NULL;
649         }
650         kfree(ip, M_HAMMER);
651         ip = NULL;
652 }
653
654 /*
655  * Retrieve pseudo-fs data.  NULL will never be returned.
656  *
657  * If an error occurs *errorp will be set and a default template is returned,
658  * otherwise *errorp is set to 0.  Typically when an error occurs it will
659  * be ENOENT.
660  */
661 hammer_pseudofs_inmem_t
662 hammer_load_pseudofs(hammer_transaction_t trans,
663                      u_int32_t localization, int *errorp)
664 {
665         hammer_mount_t hmp = trans->hmp;
666         hammer_inode_t ip;
667         hammer_pseudofs_inmem_t pfsm;
668         struct hammer_cursor cursor;
669         int bytes;
670
671 retry:
672         pfsm = RB_LOOKUP(hammer_pfs_rb_tree, &hmp->rb_pfsm_root, localization);
673         if (pfsm) {
674                 hammer_ref(&pfsm->lock);
675                 *errorp = 0;
676                 return(pfsm);
677         }
678
679         /*
680          * PFS records are stored in the root inode (not the PFS root inode,
681          * but the real root).  Avoid an infinite recursion if loading
682          * the PFS for the real root.
683          */
684         if (localization) {
685                 ip = hammer_get_inode(trans, NULL, HAMMER_OBJID_ROOT,
686                                       HAMMER_MAX_TID,
687                                       HAMMER_DEF_LOCALIZATION, 0, errorp);
688         } else {
689                 ip = NULL;
690         }
691
692         pfsm = kmalloc(sizeof(*pfsm), M_HAMMER, M_WAITOK | M_ZERO);
693         pfsm->localization = localization;
694         pfsm->pfsd.unique_uuid = trans->rootvol->ondisk->vol_fsid;
695         pfsm->pfsd.shared_uuid = pfsm->pfsd.unique_uuid;
696
697         hammer_init_cursor(trans, &cursor, (ip ? &ip->cache[1] : NULL), ip);
698         cursor.key_beg.localization = HAMMER_DEF_LOCALIZATION +
699                                       HAMMER_LOCALIZE_MISC;
700         cursor.key_beg.obj_id = HAMMER_OBJID_ROOT;
701         cursor.key_beg.create_tid = 0;
702         cursor.key_beg.delete_tid = 0;
703         cursor.key_beg.rec_type = HAMMER_RECTYPE_PFS;
704         cursor.key_beg.obj_type = 0;
705         cursor.key_beg.key = localization;
706         cursor.asof = HAMMER_MAX_TID;
707         cursor.flags |= HAMMER_CURSOR_ASOF;
708
709         if (ip)
710                 *errorp = hammer_ip_lookup(&cursor);
711         else
712                 *errorp = hammer_btree_lookup(&cursor);
713         if (*errorp == 0) {
714                 *errorp = hammer_ip_resolve_data(&cursor);
715                 if (*errorp == 0) {
716                         bytes = cursor.leaf->data_len;
717                         if (bytes > sizeof(pfsm->pfsd))
718                                 bytes = sizeof(pfsm->pfsd);
719                         bcopy(cursor.data, &pfsm->pfsd, bytes);
720                 }
721         }
722         hammer_done_cursor(&cursor);
723
724         pfsm->fsid_udev = hammer_fsid_to_udev(&pfsm->pfsd.shared_uuid);
725         hammer_ref(&pfsm->lock);
726         if (ip)
727                 hammer_rel_inode(ip, 0);
728         if (RB_INSERT(hammer_pfs_rb_tree, &hmp->rb_pfsm_root, pfsm)) {
729                 kfree(pfsm, M_HAMMER);
730                 goto retry;
731         }
732         return(pfsm);
733 }
734
735 /*
736  * Store pseudo-fs data.  The backend will automatically delete any prior
737  * on-disk pseudo-fs data but we have to delete in-memory versions.
738  */
739 int
740 hammer_save_pseudofs(hammer_transaction_t trans, hammer_pseudofs_inmem_t pfsm)
741 {
742         struct hammer_cursor cursor;
743         hammer_record_t record;
744         hammer_inode_t ip;
745         int error;
746
747         ip = hammer_get_inode(trans, NULL, HAMMER_OBJID_ROOT, HAMMER_MAX_TID,
748                               HAMMER_DEF_LOCALIZATION, 0, &error);
749 retry:
750         pfsm->fsid_udev = hammer_fsid_to_udev(&pfsm->pfsd.shared_uuid);
751         hammer_init_cursor(trans, &cursor, &ip->cache[1], ip);
752         cursor.key_beg.localization = ip->obj_localization +
753                                       HAMMER_LOCALIZE_MISC;
754         cursor.key_beg.obj_id = HAMMER_OBJID_ROOT;
755         cursor.key_beg.create_tid = 0;
756         cursor.key_beg.delete_tid = 0;
757         cursor.key_beg.rec_type = HAMMER_RECTYPE_PFS;
758         cursor.key_beg.obj_type = 0;
759         cursor.key_beg.key = pfsm->localization;
760         cursor.asof = HAMMER_MAX_TID;
761         cursor.flags |= HAMMER_CURSOR_ASOF;
762
763         error = hammer_ip_lookup(&cursor);
764         if (error == 0 && hammer_cursor_inmem(&cursor)) {
765                 record = cursor.iprec;
766                 if (record->flags & HAMMER_RECF_INTERLOCK_BE) {
767                         KKASSERT(cursor.deadlk_rec == NULL);
768                         hammer_ref(&record->lock);
769                         cursor.deadlk_rec = record;
770                         error = EDEADLK;
771                 } else {
772                         record->flags |= HAMMER_RECF_DELETED_FE;
773                         error = 0;
774                 }
775         }
776         if (error == 0 || error == ENOENT) {
777                 record = hammer_alloc_mem_record(ip, sizeof(pfsm->pfsd));
778                 record->type = HAMMER_MEM_RECORD_GENERAL;
779
780                 record->leaf.base.localization = ip->obj_localization +
781                                                  HAMMER_LOCALIZE_MISC;
782                 record->leaf.base.rec_type = HAMMER_RECTYPE_PFS;
783                 record->leaf.base.key = pfsm->localization;
784                 record->leaf.data_len = sizeof(pfsm->pfsd);
785                 bcopy(&pfsm->pfsd, record->data, sizeof(pfsm->pfsd));
786                 error = hammer_ip_add_record(trans, record);
787         }
788         hammer_done_cursor(&cursor);
789         if (error == EDEADLK)
790                 goto retry;
791         hammer_rel_inode(ip, 0);
792         return(error);
793 }
794
795 /*
796  * Create a root directory for a PFS if one does not alredy exist.
797  */
798 int
799 hammer_mkroot_pseudofs(hammer_transaction_t trans, struct ucred *cred,
800                        hammer_pseudofs_inmem_t pfsm)
801 {
802         hammer_inode_t ip;
803         struct vattr vap;
804         int error;
805
806         ip = hammer_get_inode(trans, NULL, HAMMER_OBJID_ROOT, HAMMER_MAX_TID,
807                               pfsm->localization, 0, &error);
808         if (ip == NULL) {
809                 vattr_null(&vap);
810                 vap.va_mode = 0755;
811                 vap.va_type = VDIR;
812                 error = hammer_create_inode(trans, &vap, cred, NULL, pfsm, &ip);
813         }
814         if (ip)
815                 hammer_rel_inode(ip, 0);
816         return(error);
817 }
818
819 /*
820  * Release a reference on a PFS
821  */
822 void
823 hammer_rel_pseudofs(hammer_mount_t hmp, hammer_pseudofs_inmem_t pfsm)
824 {
825         hammer_unref(&pfsm->lock);
826         if (pfsm->lock.refs == 0) {
827                 RB_REMOVE(hammer_pfs_rb_tree, &hmp->rb_pfsm_root, pfsm);
828                 kfree(pfsm, M_HAMMER);
829         }
830 }
831
832 /*
833  * Called by hammer_sync_inode().
834  */
835 static int
836 hammer_update_inode(hammer_cursor_t cursor, hammer_inode_t ip)
837 {
838         hammer_transaction_t trans = cursor->trans;
839         hammer_record_t record;
840         int error;
841         int redirty;
842
843 retry:
844         error = 0;
845
846         /*
847          * If the inode has a presence on-disk then locate it and mark
848          * it deleted, setting DELONDISK.
849          *
850          * The record may or may not be physically deleted, depending on
851          * the retention policy.
852          */
853         if ((ip->flags & (HAMMER_INODE_ONDISK|HAMMER_INODE_DELONDISK)) ==
854             HAMMER_INODE_ONDISK) {
855                 hammer_normalize_cursor(cursor);
856                 cursor->key_beg.localization = ip->obj_localization + 
857                                                HAMMER_LOCALIZE_INODE;
858                 cursor->key_beg.obj_id = ip->obj_id;
859                 cursor->key_beg.key = 0;
860                 cursor->key_beg.create_tid = 0;
861                 cursor->key_beg.delete_tid = 0;
862                 cursor->key_beg.rec_type = HAMMER_RECTYPE_INODE;
863                 cursor->key_beg.obj_type = 0;
864                 cursor->asof = ip->obj_asof;
865                 cursor->flags &= ~HAMMER_CURSOR_INITMASK;
866                 cursor->flags |= HAMMER_CURSOR_GET_LEAF | HAMMER_CURSOR_ASOF;
867                 cursor->flags |= HAMMER_CURSOR_BACKEND;
868
869                 error = hammer_btree_lookup(cursor);
870                 if (hammer_debug_inode)
871                         kprintf("IPDEL %p %08x %d", ip, ip->flags, error);
872                 if (error) {
873                         kprintf("error %d\n", error);
874                         Debugger("hammer_update_inode");
875                 }
876
877                 if (error == 0) {
878                         error = hammer_ip_delete_record(cursor, ip, trans->tid);
879                         if (hammer_debug_inode)
880                                 kprintf(" error %d\n", error);
881                         if (error && error != EDEADLK) {
882                                 kprintf("error %d\n", error);
883                                 Debugger("hammer_update_inode2");
884                         }
885                         if (error == 0) {
886                                 ip->flags |= HAMMER_INODE_DELONDISK;
887                         }
888                         if (cursor->node)
889                                 hammer_cache_node(&ip->cache[0], cursor->node);
890                 }
891                 if (error == EDEADLK) {
892                         hammer_done_cursor(cursor);
893                         error = hammer_init_cursor(trans, cursor,
894                                                    &ip->cache[0], ip);
895                         if (hammer_debug_inode)
896                                 kprintf("IPDED %p %d\n", ip, error);
897                         if (error == 0)
898                                 goto retry;
899                 }
900         }
901
902         /*
903          * Ok, write out the initial record or a new record (after deleting
904          * the old one), unless the DELETED flag is set.  This routine will
905          * clear DELONDISK if it writes out a record.
906          *
907          * Update our inode statistics if this is the first application of
908          * the inode on-disk.
909          */
910         if (error == 0 && (ip->flags & HAMMER_INODE_DELETED) == 0) {
911                 /*
912                  * Generate a record and write it to the media
913                  */
914                 record = hammer_alloc_mem_record(ip, 0);
915                 record->type = HAMMER_MEM_RECORD_INODE;
916                 record->flush_state = HAMMER_FST_FLUSH;
917                 record->leaf = ip->sync_ino_leaf;
918                 record->leaf.base.create_tid = trans->tid;
919                 record->leaf.data_len = sizeof(ip->sync_ino_data);
920                 record->leaf.create_ts = trans->time32;
921                 record->data = (void *)&ip->sync_ino_data;
922                 record->flags |= HAMMER_RECF_INTERLOCK_BE;
923
924                 /*
925                  * If this flag is set we cannot sync the new file size
926                  * because we haven't finished related truncations.  The
927                  * inode will be flushed in another flush group to finish
928                  * the job.
929                  */
930                 if ((ip->flags & HAMMER_INODE_WOULDBLOCK) &&
931                     ip->sync_ino_data.size != ip->ino_data.size) {
932                         redirty = 1;
933                         ip->sync_ino_data.size = ip->ino_data.size;
934                 } else {
935                         redirty = 0;
936                 }
937
938                 for (;;) {
939                         error = hammer_ip_sync_record_cursor(cursor, record);
940                         if (hammer_debug_inode)
941                                 kprintf("GENREC %p rec %08x %d\n",      
942                                         ip, record->flags, error);
943                         if (error != EDEADLK)
944                                 break;
945                         hammer_done_cursor(cursor);
946                         error = hammer_init_cursor(trans, cursor,
947                                                    &ip->cache[0], ip);
948                         if (hammer_debug_inode)
949                                 kprintf("GENREC reinit %d\n", error);
950                         if (error)
951                                 break;
952                 }
953                 if (error) {
954                         kprintf("error %d\n", error);
955                         Debugger("hammer_update_inode3");
956                 }
957
958                 /*
959                  * The record isn't managed by the inode's record tree,
960                  * destroy it whether we succeed or fail.
961                  */
962                 record->flags &= ~HAMMER_RECF_INTERLOCK_BE;
963                 record->flags |= HAMMER_RECF_DELETED_FE;
964                 record->flush_state = HAMMER_FST_IDLE;
965                 hammer_rel_mem_record(record);
966
967                 /*
968                  * Finish up.
969                  */
970                 if (error == 0) {
971                         if (hammer_debug_inode)
972                                 kprintf("CLEANDELOND %p %08x\n", ip, ip->flags);
973                         ip->sync_flags &= ~(HAMMER_INODE_DDIRTY |
974                                             HAMMER_INODE_ATIME |
975                                             HAMMER_INODE_MTIME);
976                         ip->flags &= ~HAMMER_INODE_DELONDISK;
977                         if (redirty)
978                                 ip->sync_flags |= HAMMER_INODE_DDIRTY;
979
980                         /*
981                          * Root volume count of inodes
982                          */
983                         if ((ip->flags & HAMMER_INODE_ONDISK) == 0) {
984                                 hammer_modify_volume_field(trans,
985                                                            trans->rootvol,
986                                                            vol0_stat_inodes);
987                                 ++ip->hmp->rootvol->ondisk->vol0_stat_inodes;
988                                 hammer_modify_volume_done(trans->rootvol);
989                                 ip->flags |= HAMMER_INODE_ONDISK;
990                                 if (hammer_debug_inode)
991                                         kprintf("NOWONDISK %p\n", ip);
992                         }
993                 }
994         }
995
996         /*
997          * If the inode has been destroyed, clean out any left-over flags
998          * that may have been set by the frontend.
999          */
1000         if (error == 0 && (ip->flags & HAMMER_INODE_DELETED)) { 
1001                 ip->sync_flags &= ~(HAMMER_INODE_DDIRTY |
1002                                     HAMMER_INODE_ATIME |
1003                                     HAMMER_INODE_MTIME);
1004         }
1005         return(error);
1006 }
1007
1008 /*
1009  * Update only the itimes fields.
1010  *
1011  * ATIME can be updated without generating any UNDO.  MTIME is updated
1012  * with UNDO so it is guaranteed to be synchronized properly in case of
1013  * a crash.
1014  *
1015  * Neither field is included in the B-Tree leaf element's CRC, which is how
1016  * we can get away with updating ATIME the way we do.
1017  */
1018 static int
1019 hammer_update_itimes(hammer_cursor_t cursor, hammer_inode_t ip)
1020 {
1021         hammer_transaction_t trans = cursor->trans;
1022         int error;
1023
1024 retry:
1025         if ((ip->flags & (HAMMER_INODE_ONDISK|HAMMER_INODE_DELONDISK)) !=
1026             HAMMER_INODE_ONDISK) {
1027                 return(0);
1028         }
1029
1030         hammer_normalize_cursor(cursor);
1031         cursor->key_beg.localization = ip->obj_localization + 
1032                                        HAMMER_LOCALIZE_INODE;
1033         cursor->key_beg.obj_id = ip->obj_id;
1034         cursor->key_beg.key = 0;
1035         cursor->key_beg.create_tid = 0;
1036         cursor->key_beg.delete_tid = 0;
1037         cursor->key_beg.rec_type = HAMMER_RECTYPE_INODE;
1038         cursor->key_beg.obj_type = 0;
1039         cursor->asof = ip->obj_asof;
1040         cursor->flags &= ~HAMMER_CURSOR_INITMASK;
1041         cursor->flags |= HAMMER_CURSOR_ASOF;
1042         cursor->flags |= HAMMER_CURSOR_GET_LEAF;
1043         cursor->flags |= HAMMER_CURSOR_GET_DATA;
1044         cursor->flags |= HAMMER_CURSOR_BACKEND;
1045
1046         error = hammer_btree_lookup(cursor);
1047         if (error) {
1048                 kprintf("error %d\n", error);
1049                 Debugger("hammer_update_itimes1");
1050         }
1051         if (error == 0) {
1052                 hammer_cache_node(&ip->cache[0], cursor->node);
1053                 if (ip->sync_flags & HAMMER_INODE_MTIME) {
1054                         /*
1055                          * Updating MTIME requires an UNDO.  Just cover
1056                          * both atime and mtime.
1057                          */
1058                         hammer_modify_buffer(trans, cursor->data_buffer,
1059                                      HAMMER_ITIMES_BASE(&cursor->data->inode),
1060                                      HAMMER_ITIMES_BYTES);
1061                         cursor->data->inode.atime = ip->sync_ino_data.atime;
1062                         cursor->data->inode.mtime = ip->sync_ino_data.mtime;
1063                         hammer_modify_buffer_done(cursor->data_buffer);
1064                 } else if (ip->sync_flags & HAMMER_INODE_ATIME) {
1065                         /*
1066                          * Updating atime only can be done in-place with
1067                          * no UNDO.
1068                          */
1069                         hammer_modify_buffer(trans, cursor->data_buffer,
1070                                              NULL, 0);
1071                         cursor->data->inode.atime = ip->sync_ino_data.atime;
1072                         hammer_modify_buffer_done(cursor->data_buffer);
1073                 }
1074                 ip->sync_flags &= ~(HAMMER_INODE_ATIME | HAMMER_INODE_MTIME);
1075         }
1076         if (error == EDEADLK) {
1077                 hammer_done_cursor(cursor);
1078                 error = hammer_init_cursor(trans, cursor,
1079                                            &ip->cache[0], ip);
1080                 if (error == 0)
1081                         goto retry;
1082         }
1083         return(error);
1084 }
1085
1086 /*
1087  * Release a reference on an inode, flush as requested.
1088  *
1089  * On the last reference we queue the inode to the flusher for its final
1090  * disposition.
1091  */
1092 void
1093 hammer_rel_inode(struct hammer_inode *ip, int flush)
1094 {
1095         hammer_mount_t hmp = ip->hmp;
1096
1097         /*
1098          * Handle disposition when dropping the last ref.
1099          */
1100         for (;;) {
1101                 if (ip->lock.refs == 1) {
1102                         /*
1103                          * Determine whether on-disk action is needed for
1104                          * the inode's final disposition.
1105                          */
1106                         KKASSERT(ip->vp == NULL);
1107                         hammer_inode_unloadable_check(ip, 0);
1108                         if (ip->flags & HAMMER_INODE_MODMASK) {
1109                                 if (hmp->rsv_inodes > desiredvnodes) {
1110                                         hammer_flush_inode(ip,
1111                                                            HAMMER_FLUSH_SIGNAL);
1112                                 } else {
1113                                         hammer_flush_inode(ip, 0);
1114                                 }
1115                         } else if (ip->lock.refs == 1) {
1116                                 hammer_unload_inode(ip);
1117                                 break;
1118                         }
1119                 } else {
1120                         if (flush)
1121                                 hammer_flush_inode(ip, 0);
1122
1123                         /*
1124                          * The inode still has multiple refs, try to drop
1125                          * one ref.
1126                          */
1127                         KKASSERT(ip->lock.refs >= 1);
1128                         if (ip->lock.refs > 1) {
1129                                 hammer_unref(&ip->lock);
1130                                 break;
1131                         }
1132                 }
1133         }
1134 }
1135
1136 /*
1137  * Unload and destroy the specified inode.  Must be called with one remaining
1138  * reference.  The reference is disposed of.
1139  *
1140  * This can only be called in the context of the flusher.
1141  */
1142 static int
1143 hammer_unload_inode(struct hammer_inode *ip)
1144 {
1145         hammer_mount_t hmp = ip->hmp;
1146
1147         KASSERT(ip->lock.refs == 1,
1148                 ("hammer_unload_inode: %d refs\n", ip->lock.refs));
1149         KKASSERT(ip->vp == NULL);
1150         KKASSERT(ip->flush_state == HAMMER_FST_IDLE);
1151         KKASSERT(ip->cursor_ip_refs == 0);
1152         KKASSERT(ip->lock.lockcount == 0);
1153         KKASSERT((ip->flags & HAMMER_INODE_MODMASK) == 0);
1154
1155         KKASSERT(RB_EMPTY(&ip->rec_tree));
1156         KKASSERT(TAILQ_EMPTY(&ip->target_list));
1157
1158         RB_REMOVE(hammer_ino_rb_tree, &hmp->rb_inos_root, ip);
1159
1160         hammer_free_inode(ip);
1161         return(0);
1162 }
1163
1164 /*
1165  * Called on mount -u when switching from RW to RO or vise-versa.  Adjust
1166  * the read-only flag for cached inodes.
1167  *
1168  * This routine is called from a RB_SCAN().
1169  */
1170 int
1171 hammer_reload_inode(hammer_inode_t ip, void *arg __unused)
1172 {
1173         hammer_mount_t hmp = ip->hmp;
1174
1175         if (hmp->ronly || hmp->asof != HAMMER_MAX_TID)
1176                 ip->flags |= HAMMER_INODE_RO;
1177         else
1178                 ip->flags &= ~HAMMER_INODE_RO;
1179         return(0);
1180 }
1181
1182 /*
1183  * A transaction has modified an inode, requiring updates as specified by
1184  * the passed flags.
1185  *
1186  * HAMMER_INODE_DDIRTY: Inode data has been updated
1187  * HAMMER_INODE_XDIRTY: Dirty in-memory records
1188  * HAMMER_INODE_BUFS:   Dirty buffer cache buffers
1189  * HAMMER_INODE_DELETED: Inode record/data must be deleted
1190  * HAMMER_INODE_ATIME/MTIME: mtime/atime has been updated
1191  */
1192 void
1193 hammer_modify_inode(hammer_inode_t ip, int flags)
1194 {
1195         KKASSERT(ip->hmp->ronly == 0 ||
1196                   (flags & (HAMMER_INODE_DDIRTY | HAMMER_INODE_XDIRTY | 
1197                             HAMMER_INODE_BUFS | HAMMER_INODE_DELETED |
1198                             HAMMER_INODE_ATIME | HAMMER_INODE_MTIME)) == 0);
1199         if ((ip->flags & HAMMER_INODE_RSV_INODES) == 0) {
1200                 ip->flags |= HAMMER_INODE_RSV_INODES;
1201                 ++ip->hmp->rsv_inodes;
1202         }
1203
1204         ip->flags |= flags;
1205 }
1206
1207 /*
1208  * Request that an inode be flushed.  This whole mess cannot block and may
1209  * recurse (if not synchronous).  Once requested HAMMER will attempt to
1210  * actively flush the inode until the flush can be done.
1211  *
1212  * The inode may already be flushing, or may be in a setup state.  We can
1213  * place the inode in a flushing state if it is currently idle and flag it
1214  * to reflush if it is currently flushing.
1215  *
1216  * If the HAMMER_FLUSH_SYNCHRONOUS flag is specified we will attempt to
1217  * flush the indoe synchronously using the caller's context.
1218  */
1219 void
1220 hammer_flush_inode(hammer_inode_t ip, int flags)
1221 {
1222         int good;
1223
1224         /*
1225          * Trivial 'nothing to flush' case.  If the inode is ina SETUP
1226          * state we have to put it back into an IDLE state so we can
1227          * drop the extra ref.
1228          */
1229         if ((ip->flags & HAMMER_INODE_MODMASK) == 0) {
1230                 if (ip->flush_state == HAMMER_FST_SETUP) {
1231                         ip->flush_state = HAMMER_FST_IDLE;
1232                         hammer_rel_inode(ip, 0);
1233                 }
1234                 return;
1235         }
1236
1237         /*
1238          * Our flush action will depend on the current state.
1239          */
1240         switch(ip->flush_state) {
1241         case HAMMER_FST_IDLE:
1242                 /*
1243                  * We have no dependancies and can flush immediately.  Some
1244                  * our children may not be flushable so we have to re-test
1245                  * with that additional knowledge.
1246                  */
1247                 hammer_flush_inode_core(ip, flags);
1248                 break;
1249         case HAMMER_FST_SETUP:
1250                 /*
1251                  * Recurse upwards through dependancies via target_list
1252                  * and start their flusher actions going if possible.
1253                  *
1254                  * 'good' is our connectivity.  -1 means we have none and
1255                  * can't flush, 0 means there weren't any dependancies, and
1256                  * 1 means we have good connectivity.
1257                  */
1258                 good = hammer_setup_parent_inodes(ip);
1259
1260                 /*
1261                  * We can continue if good >= 0.  Determine how many records
1262                  * under our inode can be flushed (and mark them).
1263                  */
1264                 if (good >= 0) {
1265                         hammer_flush_inode_core(ip, flags);
1266                 } else {
1267                         ip->flags |= HAMMER_INODE_REFLUSH;
1268                         if (flags & HAMMER_FLUSH_SIGNAL) {
1269                                 ip->flags |= HAMMER_INODE_RESIGNAL;
1270                                 hammer_flusher_async(ip->hmp);
1271                         }
1272                 }
1273                 break;
1274         default:
1275                 /*
1276                  * We are already flushing, flag the inode to reflush
1277                  * if needed after it completes its current flush.
1278                  */
1279                 if ((ip->flags & HAMMER_INODE_REFLUSH) == 0)
1280                         ip->flags |= HAMMER_INODE_REFLUSH;
1281                 if (flags & HAMMER_FLUSH_SIGNAL) {
1282                         ip->flags |= HAMMER_INODE_RESIGNAL;
1283                         hammer_flusher_async(ip->hmp);
1284                 }
1285                 break;
1286         }
1287 }
1288
1289 /*
1290  * Scan ip->target_list, which is a list of records owned by PARENTS to our
1291  * ip which reference our ip.
1292  *
1293  * XXX This is a huge mess of recursive code, but not one bit of it blocks
1294  *     so for now do not ref/deref the structures.  Note that if we use the
1295  *     ref/rel code later, the rel CAN block.
1296  */
1297 static int
1298 hammer_setup_parent_inodes(hammer_inode_t ip)
1299 {
1300         hammer_record_t depend;
1301 #if 0
1302         hammer_record_t next;
1303         hammer_inode_t  pip;
1304 #endif
1305         int good;
1306         int r;
1307
1308         good = 0;
1309         TAILQ_FOREACH(depend, &ip->target_list, target_entry) {
1310                 r = hammer_setup_parent_inodes_helper(depend);
1311                 KKASSERT(depend->target_ip == ip);
1312                 if (r < 0 && good == 0)
1313                         good = -1;
1314                 if (r > 0)
1315                         good = 1;
1316         }
1317         return(good);
1318
1319 #if 0
1320 retry:
1321         good = 0;
1322         next = TAILQ_FIRST(&ip->target_list);
1323         if (next) {
1324                 hammer_ref(&next->lock);
1325                 hammer_ref(&next->ip->lock);
1326         }
1327         while ((depend = next) != NULL) {
1328                 if (depend->target_ip == NULL) {
1329                         pip = depend->ip;
1330                         hammer_rel_mem_record(depend);
1331                         hammer_rel_inode(pip, 0);
1332                         goto retry;
1333                 }
1334                 KKASSERT(depend->target_ip == ip);
1335                 next = TAILQ_NEXT(depend, target_entry);
1336                 if (next) {
1337                         hammer_ref(&next->lock);
1338                         hammer_ref(&next->ip->lock);
1339                 }
1340                 r = hammer_setup_parent_inodes_helper(depend);
1341                 if (r < 0 && good == 0)
1342                         good = -1;
1343                 if (r > 0)
1344                         good = 1;
1345                 pip = depend->ip;
1346                 hammer_rel_mem_record(depend);
1347                 hammer_rel_inode(pip, 0);
1348         }
1349         return(good);
1350 #endif
1351 }
1352
1353 /*
1354  * This helper function takes a record representing the dependancy between
1355  * the parent inode and child inode.
1356  *
1357  * record->ip           = parent inode
1358  * record->target_ip    = child inode
1359  * 
1360  * We are asked to recurse upwards and convert the record from SETUP
1361  * to FLUSH if possible.
1362  *
1363  * Return 1 if the record gives us connectivity
1364  *
1365  * Return 0 if the record is not relevant 
1366  *
1367  * Return -1 if we can't resolve the dependancy and there is no connectivity.
1368  */
1369 static int
1370 hammer_setup_parent_inodes_helper(hammer_record_t record)
1371 {
1372         hammer_mount_t hmp;
1373         hammer_inode_t pip;
1374         int good;
1375
1376         KKASSERT(record->flush_state != HAMMER_FST_IDLE);
1377         pip = record->ip;
1378         hmp = pip->hmp;
1379
1380         /*
1381          * If the record is already flushing, is it in our flush group?
1382          *
1383          * If it is in our flush group but it is a general record or a 
1384          * delete-on-disk, it does not improve our connectivity (return 0),
1385          * and if the target inode is not trying to destroy itself we can't
1386          * allow the operation yet anyway (the second return -1).
1387          */
1388         if (record->flush_state == HAMMER_FST_FLUSH) {
1389                 if (record->flush_group != hmp->flusher.next) {
1390                         pip->flags |= HAMMER_INODE_REFLUSH;
1391                         return(-1);
1392                 }
1393                 if (record->type == HAMMER_MEM_RECORD_ADD)
1394                         return(1);
1395                 /* GENERAL or DEL */
1396                 return(0);
1397         }
1398
1399         /*
1400          * It must be a setup record.  Try to resolve the setup dependancies
1401          * by recursing upwards so we can place ip on the flush list.
1402          */
1403         KKASSERT(record->flush_state == HAMMER_FST_SETUP);
1404
1405         good = hammer_setup_parent_inodes(pip);
1406
1407         /*
1408          * We can't flush ip because it has no connectivity (XXX also check
1409          * nlinks for pre-existing connectivity!).  Flag it so any resolution
1410          * recurses back down.
1411          */
1412         if (good < 0) {
1413                 pip->flags |= HAMMER_INODE_REFLUSH;
1414                 return(good);
1415         }
1416
1417         /*
1418          * We are go, place the parent inode in a flushing state so we can
1419          * place its record in a flushing state.  Note that the parent
1420          * may already be flushing.  The record must be in the same flush
1421          * group as the parent.
1422          */
1423         if (pip->flush_state != HAMMER_FST_FLUSH)
1424                 hammer_flush_inode_core(pip, HAMMER_FLUSH_RECURSION);
1425         KKASSERT(pip->flush_state == HAMMER_FST_FLUSH);
1426         KKASSERT(record->flush_state == HAMMER_FST_SETUP);
1427
1428 #if 0
1429         if (record->type == HAMMER_MEM_RECORD_DEL &&
1430             (record->target_ip->flags & (HAMMER_INODE_DELETED|HAMMER_INODE_DELONDISK)) == 0) {
1431                 /*
1432                  * Regardless of flushing state we cannot sync this path if the
1433                  * record represents a delete-on-disk but the target inode
1434                  * is not ready to sync its own deletion.
1435                  *
1436                  * XXX need to count effective nlinks to determine whether
1437                  * the flush is ok, otherwise removing a hardlink will
1438                  * just leave the DEL record to rot.
1439                  */
1440                 record->target_ip->flags |= HAMMER_INODE_REFLUSH;
1441                 return(-1);
1442         } else
1443 #endif
1444         if (pip->flush_group == pip->hmp->flusher.next) {
1445                 /*
1446                  * This is the record we wanted to synchronize.  If the
1447                  * record went into a flush state while we blocked it 
1448                  * had better be in the correct flush group.
1449                  */
1450                 if (record->flush_state != HAMMER_FST_FLUSH) {
1451                         record->flush_state = HAMMER_FST_FLUSH;
1452                         record->flush_group = pip->flush_group;
1453                         hammer_ref(&record->lock);
1454                 } else {
1455                         KKASSERT(record->flush_group == pip->flush_group);
1456                 }
1457                 if (record->type == HAMMER_MEM_RECORD_ADD)
1458                         return(1);
1459
1460                 /*
1461                  * A general or delete-on-disk record does not contribute
1462                  * to our visibility.  We can still flush it, however.
1463                  */
1464                 return(0);
1465         } else {
1466                 /*
1467                  * We couldn't resolve the dependancies, request that the
1468                  * inode be flushed when the dependancies can be resolved.
1469                  */
1470                 pip->flags |= HAMMER_INODE_REFLUSH;
1471                 return(-1);
1472         }
1473 }
1474
1475 /*
1476  * This is the core routine placing an inode into the FST_FLUSH state.
1477  */
1478 static void
1479 hammer_flush_inode_core(hammer_inode_t ip, int flags)
1480 {
1481         int go_count;
1482
1483         /*
1484          * Set flush state and prevent the flusher from cycling into
1485          * the next flush group.  Do not place the ip on the list yet.
1486          * Inodes not in the idle state get an extra reference.
1487          */
1488         KKASSERT(ip->flush_state != HAMMER_FST_FLUSH);
1489         if (ip->flush_state == HAMMER_FST_IDLE)
1490                 hammer_ref(&ip->lock);
1491         ip->flush_state = HAMMER_FST_FLUSH;
1492         ip->flush_group = ip->hmp->flusher.next;
1493         ++ip->hmp->flusher.group_lock;
1494         ++ip->hmp->count_iqueued;
1495         ++hammer_count_iqueued;
1496
1497         /*
1498          * We need to be able to vfsync/truncate from the backend.
1499          */
1500         KKASSERT((ip->flags & HAMMER_INODE_VHELD) == 0);
1501         if (ip->vp && (ip->vp->v_flag & VINACTIVE) == 0) {
1502                 ip->flags |= HAMMER_INODE_VHELD;
1503                 vref(ip->vp);
1504         }
1505
1506         /*
1507          * Figure out how many in-memory records we can actually flush
1508          * (not including inode meta-data, buffers, etc).
1509          *
1510          * Do not add new records to the flush if this is a recursion or
1511          * if we must still complete a flush from the previous flush cycle.
1512          */
1513         if (flags & HAMMER_FLUSH_RECURSION) {
1514                 go_count = 1;
1515         } else if (ip->flags & HAMMER_INODE_WOULDBLOCK) {
1516                 go_count = RB_SCAN(hammer_rec_rb_tree, &ip->rec_tree, NULL,
1517                                    hammer_syncgrp_child_callback, NULL);
1518                 go_count = 1;
1519         } else {
1520                 go_count = RB_SCAN(hammer_rec_rb_tree, &ip->rec_tree, NULL,
1521                                    hammer_setup_child_callback, NULL);
1522         }
1523
1524         /*
1525          * This is a more involved test that includes go_count.  If we
1526          * can't flush, flag the inode and return.  If go_count is 0 we
1527          * were are unable to flush any records in our rec_tree and
1528          * must ignore the XDIRTY flag.
1529          */
1530         if (go_count == 0) {
1531                 if ((ip->flags & HAMMER_INODE_MODMASK_NOXDIRTY) == 0) {
1532                         ip->flags |= HAMMER_INODE_REFLUSH;
1533
1534                         --ip->hmp->count_iqueued;
1535                         --hammer_count_iqueued;
1536
1537                         ip->flush_state = HAMMER_FST_SETUP;
1538                         if (ip->flags & HAMMER_INODE_VHELD) {
1539                                 ip->flags &= ~HAMMER_INODE_VHELD;
1540                                 vrele(ip->vp);
1541                         }
1542                         if (flags & HAMMER_FLUSH_SIGNAL) {
1543                                 ip->flags |= HAMMER_INODE_RESIGNAL;
1544                                 hammer_flusher_async(ip->hmp);
1545                         }
1546                         if (--ip->hmp->flusher.group_lock == 0)
1547                                 wakeup(&ip->hmp->flusher.group_lock);
1548                         return;
1549                 }
1550         }
1551
1552         /*
1553          * Snapshot the state of the inode for the backend flusher.
1554          *
1555          * We continue to retain save_trunc_off even when all truncations
1556          * have been resolved as an optimization to determine if we can
1557          * skip the B-Tree lookup for overwrite deletions.
1558          *
1559          * NOTE: The DELETING flag is a mod flag, but it is also sticky,
1560          * and stays in ip->flags.  Once set, it stays set until the
1561          * inode is destroyed.
1562          *
1563          * NOTE: If a truncation from a previous flush cycle had to be
1564          * continued into this one, the TRUNCATED flag will still be
1565          * set in sync_flags as will WOULDBLOCK.  When this occurs
1566          * we CANNOT safely integrate a new truncation from the front-end
1567          * because there may be data records in-memory assigned a flush
1568          * state from the previous cycle that are supposed to be flushed
1569          * before the next frontend truncation.
1570          */
1571         if ((ip->flags & (HAMMER_INODE_TRUNCATED | HAMMER_INODE_WOULDBLOCK)) ==
1572             HAMMER_INODE_TRUNCATED) {
1573                 KKASSERT((ip->sync_flags & HAMMER_INODE_TRUNCATED) == 0);
1574                 ip->sync_trunc_off = ip->trunc_off;
1575                 ip->trunc_off = 0x7FFFFFFFFFFFFFFFLL;
1576                 ip->flags &= ~HAMMER_INODE_TRUNCATED;
1577                 ip->sync_flags |= HAMMER_INODE_TRUNCATED;
1578
1579                 /*
1580                  * The save_trunc_off used to cache whether the B-Tree
1581                  * holds any records past that point is not used until
1582                  * after the truncation has succeeded, so we can safely
1583                  * set it now.
1584                  */
1585                 if (ip->save_trunc_off > ip->sync_trunc_off)
1586                         ip->save_trunc_off = ip->sync_trunc_off;
1587         }
1588         ip->sync_flags |= (ip->flags & HAMMER_INODE_MODMASK &
1589                            ~HAMMER_INODE_TRUNCATED);
1590         ip->sync_ino_leaf = ip->ino_leaf;
1591         ip->sync_ino_data = ip->ino_data;
1592         ip->flags &= ~HAMMER_INODE_MODMASK | HAMMER_INODE_TRUNCATED;
1593 #ifdef DEBUG_TRUNCATE
1594         if ((ip->sync_flags & HAMMER_INODE_TRUNCATED) && ip == HammerTruncIp)
1595                 kprintf("truncateS %016llx\n", ip->sync_trunc_off);
1596 #endif
1597
1598         /*
1599          * The flusher list inherits our inode and reference.
1600          */
1601         TAILQ_INSERT_TAIL(&ip->hmp->flush_list, ip, flush_entry);
1602         if (--ip->hmp->flusher.group_lock == 0)
1603                 wakeup(&ip->hmp->flusher.group_lock);
1604
1605         if (flags & HAMMER_FLUSH_SIGNAL) {
1606                 hammer_flusher_async(ip->hmp);
1607         }
1608 }
1609
1610 /*
1611  * Callback for scan of ip->rec_tree.  Try to include each record in our
1612  * flush.  ip->flush_group has been set but the inode has not yet been
1613  * moved into a flushing state.
1614  *
1615  * If we get stuck on a record we have to set HAMMER_INODE_REFLUSH on
1616  * both inodes.
1617  *
1618  * We return 1 for any record placed or found in FST_FLUSH, which prevents
1619  * the caller from shortcutting the flush.
1620  */
1621 static int
1622 hammer_setup_child_callback(hammer_record_t rec, void *data)
1623 {
1624         hammer_inode_t target_ip;
1625         hammer_inode_t ip;
1626         int r;
1627
1628         /*
1629          * Deleted records are ignored.  Note that the flush detects deleted
1630          * front-end records at multiple points to deal with races.  This is
1631          * just the first line of defense.  The only time DELETED_FE cannot
1632          * be set is when HAMMER_RECF_INTERLOCK_BE is set. 
1633          *
1634          * Don't get confused between record deletion and, say, directory
1635          * entry deletion.  The deletion of a directory entry that is on
1636          * the media has nothing to do with the record deletion flags.
1637          *
1638          * The flush_group for a record already in a flush state must
1639          * be updated.  This case can only occur if the inode deleting
1640          * too many records had to be moved to the next flush group.
1641          */
1642         if (rec->flags & (HAMMER_RECF_DELETED_FE|HAMMER_RECF_DELETED_BE)) {
1643                 if (rec->flush_state == HAMMER_FST_FLUSH) {
1644                         KKASSERT(rec->ip->flags & HAMMER_INODE_WOULDBLOCK);
1645                         rec->flush_group = rec->ip->flush_group;
1646                         r = 1;
1647                 } else {
1648                         r = 0;
1649                 }
1650                 return(r);
1651         }
1652
1653         /*
1654          * If the record is in an idle state it has no dependancies and
1655          * can be flushed.
1656          */
1657         ip = rec->ip;
1658         r = 0;
1659
1660         switch(rec->flush_state) {
1661         case HAMMER_FST_IDLE:
1662                 /*
1663                  * Record has no setup dependancy, we can flush it.
1664                  */
1665                 KKASSERT(rec->target_ip == NULL);
1666                 rec->flush_state = HAMMER_FST_FLUSH;
1667                 rec->flush_group = ip->flush_group;
1668                 hammer_ref(&rec->lock);
1669                 r = 1;
1670                 break;
1671         case HAMMER_FST_SETUP:
1672                 /*
1673                  * Record has a setup dependancy.  Try to include the
1674                  * target ip in the flush. 
1675                  *
1676                  * We have to be careful here, if we do not do the right
1677                  * thing we can lose track of dirty inodes and the system
1678                  * will lockup trying to allocate buffers.
1679                  */
1680                 target_ip = rec->target_ip;
1681                 KKASSERT(target_ip != NULL);
1682                 KKASSERT(target_ip->flush_state != HAMMER_FST_IDLE);
1683                 if (target_ip->flush_state == HAMMER_FST_FLUSH) {
1684                         /*
1685                          * If the target IP is already flushing in our group
1686                          * we are golden, otherwise make sure the target
1687                          * reflushes.
1688                          */
1689                         if (target_ip->flush_group == ip->flush_group) {
1690                                 rec->flush_state = HAMMER_FST_FLUSH;
1691                                 rec->flush_group = ip->flush_group;
1692                                 hammer_ref(&rec->lock);
1693                                 r = 1;
1694                         } else {
1695                                 target_ip->flags |= HAMMER_INODE_REFLUSH;
1696                         }
1697                 } else if (rec->type == HAMMER_MEM_RECORD_ADD) {
1698                         /*
1699                          * If the target IP is not flushing we can force
1700                          * it to flush, even if it is unable to write out
1701                          * any of its own records we have at least one in
1702                          * hand that we CAN deal with.
1703                          */
1704                         rec->flush_state = HAMMER_FST_FLUSH;
1705                         rec->flush_group = ip->flush_group;
1706                         hammer_ref(&rec->lock);
1707                         hammer_flush_inode_core(target_ip,
1708                                                 HAMMER_FLUSH_RECURSION);
1709                         r = 1;
1710                 } else {
1711                         /*
1712                          * General or delete-on-disk record.
1713                          *
1714                          * XXX this needs help.  If a delete-on-disk we could
1715                          * disconnect the target.  If the target has its own
1716                          * dependancies they really need to be flushed.
1717                          *
1718                          * XXX
1719                          */
1720                         rec->flush_state = HAMMER_FST_FLUSH;
1721                         rec->flush_group = ip->flush_group;
1722                         hammer_ref(&rec->lock);
1723                         hammer_flush_inode_core(target_ip,
1724                                                 HAMMER_FLUSH_RECURSION);
1725                         r = 1;
1726                 }
1727                 break;
1728         case HAMMER_FST_FLUSH:
1729                 /* 
1730                  * If the WOULDBLOCK flag is set records may have been left
1731                  * over from a previous flush attempt and should be moved
1732                  * to the current flush group.  If it is not set then all
1733                  * such records had better have been flushed already or
1734                  * already associated with the current flush group.
1735                  */
1736                 if (ip->flags & HAMMER_INODE_WOULDBLOCK) {
1737                         rec->flush_group = ip->flush_group;
1738                 } else {
1739                         KKASSERT(rec->flush_group == ip->flush_group);
1740                 }
1741                 r = 1;
1742                 break;
1743         }
1744         return(r);
1745 }
1746
1747 /*
1748  * This version just moves records already in a flush state to the new
1749  * flush group and that is it.
1750  */
1751 static int
1752 hammer_syncgrp_child_callback(hammer_record_t rec, void *data)
1753 {
1754         hammer_inode_t ip = rec->ip;
1755
1756         switch(rec->flush_state) {
1757         case HAMMER_FST_FLUSH:
1758                 if (ip->flags & HAMMER_INODE_WOULDBLOCK) {
1759                         rec->flush_group = ip->flush_group;
1760                 } else {
1761                         KKASSERT(rec->flush_group == ip->flush_group);
1762                 }
1763                 break;
1764         default:
1765                 break;
1766         }
1767         return(0);
1768 }
1769
1770 /*
1771  * Wait for a previously queued flush to complete.  Not only do we need to
1772  * wait for the inode to sync out, we also may have to run the flusher again
1773  * to get it past the UNDO position pertaining to the flush so a crash does
1774  * not 'undo' our flush.
1775  */
1776 void
1777 hammer_wait_inode(hammer_inode_t ip)
1778 {
1779         hammer_mount_t hmp = ip->hmp;
1780         int sync_group;
1781         int waitcount;
1782
1783         sync_group = ip->flush_group;
1784         waitcount = (ip->flags & HAMMER_INODE_REFLUSH) ? 2 : 1;
1785
1786         if (ip->flush_state == HAMMER_FST_SETUP) {
1787                 hammer_flush_inode(ip, HAMMER_FLUSH_SIGNAL);
1788         }
1789         /* XXX can we make this != FST_IDLE ? check SETUP depends */
1790         while (ip->flush_state == HAMMER_FST_FLUSH &&
1791                (ip->flush_group - sync_group) < waitcount) {
1792                 ip->flags |= HAMMER_INODE_FLUSHW;
1793                 tsleep(&ip->flags, 0, "hmrwin", 0);
1794         }
1795         while (hmp->flusher.done - sync_group < waitcount) {
1796                 kprintf("Y");
1797                 hammer_flusher_sync(hmp);
1798         }
1799 }
1800
1801 /*
1802  * Called by the backend code when a flush has been completed.
1803  * The inode has already been removed from the flush list.
1804  *
1805  * A pipelined flush can occur, in which case we must re-enter the
1806  * inode on the list and re-copy its fields.
1807  */
1808 void
1809 hammer_flush_inode_done(hammer_inode_t ip)
1810 {
1811         hammer_mount_t hmp;
1812         int dorel;
1813
1814         KKASSERT(ip->flush_state == HAMMER_FST_FLUSH);
1815
1816         hmp = ip->hmp;
1817
1818         /*
1819          * Merge left-over flags back into the frontend and fix the state.
1820          * Incomplete truncations are retained by the backend.
1821          */
1822         ip->flags |= ip->sync_flags & ~HAMMER_INODE_TRUNCATED;
1823         ip->sync_flags &= HAMMER_INODE_TRUNCATED;
1824
1825         /*
1826          * The backend may have adjusted nlinks, so if the adjusted nlinks
1827          * does not match the fronttend set the frontend's RDIRTY flag again.
1828          */
1829         if (ip->ino_data.nlinks != ip->sync_ino_data.nlinks)
1830                 ip->flags |= HAMMER_INODE_DDIRTY;
1831
1832         /*
1833          * Fix up the dirty buffer status.
1834          */
1835         if (ip->vp && RB_ROOT(&ip->vp->v_rbdirty_tree)) {
1836                 ip->flags |= HAMMER_INODE_BUFS;
1837         }
1838
1839         /*
1840          * Re-set the XDIRTY flag if some of the inode's in-memory records
1841          * could not be flushed.
1842          */
1843         KKASSERT((RB_EMPTY(&ip->rec_tree) &&
1844                   (ip->flags & HAMMER_INODE_XDIRTY) == 0) ||
1845                  (!RB_EMPTY(&ip->rec_tree) &&
1846                   (ip->flags & HAMMER_INODE_XDIRTY) != 0));
1847
1848         /*
1849          * Do not lose track of inodes which no longer have vnode
1850          * assocations, otherwise they may never get flushed again.
1851          */
1852         if ((ip->flags & HAMMER_INODE_MODMASK) && ip->vp == NULL)
1853                 ip->flags |= HAMMER_INODE_REFLUSH;
1854
1855         /*
1856          * Clean up the vnode ref
1857          */
1858         if (ip->flags & HAMMER_INODE_VHELD) {
1859                 ip->flags &= ~HAMMER_INODE_VHELD;
1860                 vrele(ip->vp);
1861         }
1862
1863         /*
1864          * Adjust flush_state.  The target state (idle or setup) shouldn't
1865          * be terribly important since we will reflush if we really need
1866          * to do anything.
1867          *
1868          * If the WOULDBLOCK flag is set we must re-flush immediately
1869          * to continue a potentially large deletion.  The flag also causes
1870          * the hammer_setup_child_callback() to move records in the old
1871          * flush group to the new one.
1872          */
1873         if (ip->flags & HAMMER_INODE_WOULDBLOCK) {
1874                 ip->flush_state = HAMMER_FST_IDLE;
1875                 hammer_flush_inode_core(ip, HAMMER_FLUSH_SIGNAL);
1876                 ip->flags &= ~HAMMER_INODE_WOULDBLOCK;
1877                 dorel = 1;
1878         } else if (TAILQ_EMPTY(&ip->target_list) && RB_EMPTY(&ip->rec_tree)) {
1879                 ip->flush_state = HAMMER_FST_IDLE;
1880                 dorel = 1;
1881         } else {
1882                 ip->flush_state = HAMMER_FST_SETUP;
1883                 dorel = 0;
1884         }
1885
1886         --hmp->count_iqueued;
1887         --hammer_count_iqueued;
1888
1889         /*
1890          * If the frontend made more changes and requested another flush,
1891          * then try to get it running.
1892          */
1893         if (ip->flags & HAMMER_INODE_REFLUSH) {
1894                 ip->flags &= ~HAMMER_INODE_REFLUSH;
1895                 if (ip->flags & HAMMER_INODE_RESIGNAL) {
1896                         ip->flags &= ~HAMMER_INODE_RESIGNAL;
1897                         hammer_flush_inode(ip, HAMMER_FLUSH_SIGNAL);
1898                 } else {
1899                         hammer_flush_inode(ip, 0);
1900                 }
1901         }
1902
1903         /*
1904          * If the inode is now clean drop the space reservation.
1905          */
1906         if ((ip->flags & HAMMER_INODE_MODMASK) == 0 &&
1907             (ip->flags & HAMMER_INODE_RSV_INODES)) {
1908                 ip->flags &= ~HAMMER_INODE_RSV_INODES;
1909                 --hmp->rsv_inodes;
1910         }
1911
1912         /*
1913          * Finally, if the frontend is waiting for a flush to complete,
1914          * wake it up.
1915          */
1916         if (ip->flush_state != HAMMER_FST_FLUSH) {
1917                 if (ip->flags & HAMMER_INODE_FLUSHW) {
1918                         ip->flags &= ~HAMMER_INODE_FLUSHW;
1919                         wakeup(&ip->flags);
1920                 }
1921         }
1922         if (dorel)
1923                 hammer_rel_inode(ip, 0);
1924 }
1925
1926 /*
1927  * Called from hammer_sync_inode() to synchronize in-memory records
1928  * to the media.
1929  */
1930 static int
1931 hammer_sync_record_callback(hammer_record_t record, void *data)
1932 {
1933         hammer_cursor_t cursor = data;
1934         hammer_transaction_t trans = cursor->trans;
1935         int error;
1936
1937         /*
1938          * Skip records that do not belong to the current flush.
1939          */
1940         ++hammer_stats_record_iterations;
1941         if (record->flush_state != HAMMER_FST_FLUSH)
1942                 return(0);
1943
1944 #if 1
1945         if (record->flush_group != record->ip->flush_group) {
1946                 kprintf("sync_record %p ip %p bad flush group %d %d\n", record, record->ip, record->flush_group ,record->ip->flush_group);
1947                 Debugger("blah2");
1948                 return(0);
1949         }
1950 #endif
1951         KKASSERT(record->flush_group == record->ip->flush_group);
1952
1953         /*
1954          * Interlock the record using the BE flag.  Once BE is set the
1955          * frontend cannot change the state of FE.
1956          *
1957          * NOTE: If FE is set prior to us setting BE we still sync the
1958          * record out, but the flush completion code converts it to 
1959          * a delete-on-disk record instead of destroying it.
1960          */
1961         KKASSERT((record->flags & HAMMER_RECF_INTERLOCK_BE) == 0);
1962         record->flags |= HAMMER_RECF_INTERLOCK_BE;
1963
1964         /*
1965          * The backend may have already disposed of the record.
1966          */
1967         if (record->flags & HAMMER_RECF_DELETED_BE) {
1968                 error = 0;
1969                 goto done;
1970         }
1971
1972         /*
1973          * If the whole inode is being deleting all on-disk records will
1974          * be deleted very soon, we can't sync any new records to disk
1975          * because they will be deleted in the same transaction they were
1976          * created in (delete_tid == create_tid), which will assert.
1977          *
1978          * XXX There may be a case with RECORD_ADD with DELETED_FE set
1979          * that we currently panic on.
1980          */
1981         if (record->ip->sync_flags & HAMMER_INODE_DELETING) {
1982                 switch(record->type) {
1983                 case HAMMER_MEM_RECORD_DATA:
1984                         /*
1985                          * We don't have to do anything, if the record was
1986                          * committed the space will have been accounted for
1987                          * in the blockmap.
1988                          */
1989                         /* fall through */
1990                 case HAMMER_MEM_RECORD_GENERAL:
1991                         record->flags |= HAMMER_RECF_DELETED_FE;
1992                         record->flags |= HAMMER_RECF_DELETED_BE;
1993                         error = 0;
1994                         goto done;
1995                 case HAMMER_MEM_RECORD_ADD:
1996                         panic("hammer_sync_record_callback: illegal add "
1997                               "during inode deletion record %p", record);
1998                         break; /* NOT REACHED */
1999                 case HAMMER_MEM_RECORD_INODE:
2000                         panic("hammer_sync_record_callback: attempt to "
2001                               "sync inode record %p?", record);
2002                         break; /* NOT REACHED */
2003                 case HAMMER_MEM_RECORD_DEL:
2004                         /* 
2005                          * Follow through and issue the on-disk deletion
2006                          */
2007                         break;
2008                 }
2009         }
2010
2011         /*
2012          * If DELETED_FE is set special handling is needed for directory
2013          * entries.  Dependant pieces related to the directory entry may
2014          * have already been synced to disk.  If this occurs we have to
2015          * sync the directory entry and then change the in-memory record
2016          * from an ADD to a DELETE to cover the fact that it's been
2017          * deleted by the frontend.
2018          *
2019          * A directory delete covering record (MEM_RECORD_DEL) can never
2020          * be deleted by the frontend.
2021          *
2022          * Any other record type (aka DATA) can be deleted by the frontend.
2023          * XXX At the moment the flusher must skip it because there may
2024          * be another data record in the flush group for the same block,
2025          * meaning that some frontend data changes can leak into the backend's
2026          * synchronization point.
2027          */
2028         if (record->flags & HAMMER_RECF_DELETED_FE) {
2029                 if (record->type == HAMMER_MEM_RECORD_ADD) {
2030                         record->flags |= HAMMER_RECF_CONVERT_DELETE;
2031                 } else {
2032                         KKASSERT(record->type != HAMMER_MEM_RECORD_DEL);
2033                         record->flags |= HAMMER_RECF_DELETED_BE;
2034                         error = 0;
2035                         goto done;
2036                 }
2037         }
2038
2039         /*
2040          * Assign the create_tid for new records.  Deletions already
2041          * have the record's entire key properly set up.
2042          */
2043         if (record->type != HAMMER_MEM_RECORD_DEL)
2044                 record->leaf.base.create_tid = trans->tid;
2045                 record->leaf.create_ts = trans->time32;
2046         for (;;) {
2047                 error = hammer_ip_sync_record_cursor(cursor, record);
2048                 if (error != EDEADLK)
2049                         break;
2050                 hammer_done_cursor(cursor);
2051                 error = hammer_init_cursor(trans, cursor, &record->ip->cache[0],
2052                                            record->ip);
2053                 if (error)
2054                         break;
2055         }
2056         record->flags &= ~HAMMER_RECF_CONVERT_DELETE;
2057
2058         if (error) {
2059                 error = -error;
2060                 if (error != -ENOSPC) {
2061                         kprintf("hammer_sync_record_callback: sync failed rec "
2062                                 "%p, error %d\n", record, error);
2063                         Debugger("sync failed rec");
2064                 }
2065         }
2066 done:
2067         hammer_flush_record_done(record, error);
2068         return(error);
2069 }
2070
2071 /*
2072  * XXX error handling
2073  */
2074 int
2075 hammer_sync_inode(hammer_inode_t ip)
2076 {
2077         struct hammer_transaction trans;
2078         struct hammer_cursor cursor;
2079         hammer_node_t tmp_node;
2080         hammer_record_t depend;
2081         hammer_record_t next;
2082         int error, tmp_error;
2083         u_int64_t nlinks;
2084
2085         if ((ip->sync_flags & HAMMER_INODE_MODMASK) == 0)
2086                 return(0);
2087
2088         hammer_start_transaction_fls(&trans, ip->hmp);
2089         error = hammer_init_cursor(&trans, &cursor, &ip->cache[1], ip);
2090         if (error)
2091                 goto done;
2092
2093         /*
2094          * Any directory records referencing this inode which are not in
2095          * our current flush group must adjust our nlink count for the
2096          * purposes of synchronization to disk.
2097          *
2098          * Records which are in our flush group can be unlinked from our
2099          * inode now, potentially allowing the inode to be physically
2100          * deleted.
2101          *
2102          * This cannot block.
2103          */
2104         nlinks = ip->ino_data.nlinks;
2105         next = TAILQ_FIRST(&ip->target_list);
2106         while ((depend = next) != NULL) {
2107                 next = TAILQ_NEXT(depend, target_entry);
2108                 if (depend->flush_state == HAMMER_FST_FLUSH &&
2109                     depend->flush_group == ip->hmp->flusher.act) {
2110                         /*
2111                          * If this is an ADD that was deleted by the frontend
2112                          * the frontend nlinks count will have already been
2113                          * decremented, but the backend is going to sync its
2114                          * directory entry and must account for it.  The
2115                          * record will be converted to a delete-on-disk when
2116                          * it gets synced.
2117                          *
2118                          * If the ADD was not deleted by the frontend we
2119                          * can remove the dependancy from our target_list.
2120                          */
2121                         if (depend->flags & HAMMER_RECF_DELETED_FE) {
2122                                 ++nlinks;
2123                         } else {
2124                                 TAILQ_REMOVE(&ip->target_list, depend,
2125                                              target_entry);
2126                                 depend->target_ip = NULL;
2127                         }
2128                 } else if ((depend->flags & HAMMER_RECF_DELETED_FE) == 0) {
2129                         /*
2130                          * Not part of our flush group
2131                          */
2132                         KKASSERT((depend->flags & HAMMER_RECF_DELETED_BE) == 0);
2133                         switch(depend->type) {
2134                         case HAMMER_MEM_RECORD_ADD:
2135                                 --nlinks;
2136                                 break;
2137                         case HAMMER_MEM_RECORD_DEL:
2138                                 ++nlinks;
2139                                 break;
2140                         default:
2141                                 break;
2142                         }
2143                 }
2144         }
2145
2146         /*
2147          * Set dirty if we had to modify the link count.
2148          */
2149         if (ip->sync_ino_data.nlinks != nlinks) {
2150                 KKASSERT((int64_t)nlinks >= 0);
2151                 ip->sync_ino_data.nlinks = nlinks;
2152                 ip->sync_flags |= HAMMER_INODE_DDIRTY;
2153         }
2154
2155         /*
2156          * If there is a trunction queued destroy any data past the (aligned)
2157          * truncation point.  Userland will have dealt with the buffer
2158          * containing the truncation point for us.
2159          *
2160          * We don't flush pending frontend data buffers until after we've
2161          * dealt with the truncation.
2162          */
2163         if (ip->sync_flags & HAMMER_INODE_TRUNCATED) {
2164                 /*
2165                  * Interlock trunc_off.  The VOP front-end may continue to
2166                  * make adjustments to it while we are blocked.
2167                  */
2168                 off_t trunc_off;
2169                 off_t aligned_trunc_off;
2170                 int blkmask;
2171
2172                 trunc_off = ip->sync_trunc_off;
2173                 blkmask = hammer_blocksize(trunc_off) - 1;
2174                 aligned_trunc_off = (trunc_off + blkmask) & ~(int64_t)blkmask;
2175
2176                 /*
2177                  * Delete any whole blocks on-media.  The front-end has
2178                  * already cleaned out any partial block and made it
2179                  * pending.  The front-end may have updated trunc_off
2180                  * while we were blocked so we only use sync_trunc_off.
2181                  *
2182                  * This operation can blow out the buffer cache, EWOULDBLOCK
2183                  * means we were unable to complete the deletion.  The
2184                  * deletion will update sync_trunc_off in that case.
2185                  */
2186                 error = hammer_ip_delete_range(&cursor, ip,
2187                                                 aligned_trunc_off,
2188                                                 0x7FFFFFFFFFFFFFFFLL, 2);
2189                 if (error == EWOULDBLOCK) {
2190                         ip->flags |= HAMMER_INODE_WOULDBLOCK;
2191                         error = 0;
2192                         goto defer_buffer_flush;
2193                 }
2194
2195                 if (error)
2196                         Debugger("hammer_ip_delete_range errored");
2197
2198                 /*
2199                  * Clear the truncation flag on the backend after we have
2200                  * complete the deletions.  Backend data is now good again
2201                  * (including new records we are about to sync, below).
2202                  *
2203                  * Leave sync_trunc_off intact.  As we write additional
2204                  * records the backend will update sync_trunc_off.  This
2205                  * tells the backend whether it can skip the overwrite
2206                  * test.  This should work properly even when the backend
2207                  * writes full blocks where the truncation point straddles
2208                  * the block because the comparison is against the base
2209                  * offset of the record.
2210                  */
2211                 ip->sync_flags &= ~HAMMER_INODE_TRUNCATED;
2212                 /* ip->sync_trunc_off = 0x7FFFFFFFFFFFFFFFLL; */
2213         } else {
2214                 error = 0;
2215         }
2216
2217         /*
2218          * Now sync related records.  These will typically be directory
2219          * entries or delete-on-disk records.
2220          *
2221          * Not all records will be flushed, but clear XDIRTY anyway.  We
2222          * will set it again in the frontend hammer_flush_inode_done() 
2223          * if records remain.
2224          */
2225         if (error == 0) {
2226                 tmp_error = RB_SCAN(hammer_rec_rb_tree, &ip->rec_tree, NULL,
2227                                     hammer_sync_record_callback, &cursor);
2228                 if (tmp_error < 0)
2229                         tmp_error = -error;
2230                 if (tmp_error)
2231                         error = tmp_error;
2232         }
2233         hammer_cache_node(&ip->cache[1], cursor.node);
2234
2235         /*
2236          * Re-seek for inode update, assuming our cache hasn't been ripped
2237          * out from under us.
2238          */
2239         if (error == 0) {
2240                 tmp_node = hammer_ref_node_safe(ip->hmp, &ip->cache[0], &error);
2241                 if (tmp_node) {
2242                         hammer_cursor_downgrade(&cursor);
2243                         hammer_lock_sh(&tmp_node->lock);
2244                         if ((tmp_node->flags & HAMMER_NODE_DELETED) == 0)
2245                                 hammer_cursor_seek(&cursor, tmp_node, 0);
2246                         hammer_unlock(&tmp_node->lock);
2247                         hammer_rel_node(tmp_node);
2248                 }
2249                 error = 0;
2250         }
2251
2252         /*
2253          * If we are deleting the inode the frontend had better not have
2254          * any active references on elements making up the inode.
2255          *
2256          * The call to hammer_ip_delete_clean() cleans up auxillary records
2257          * but not DB or DATA records.  Those must have already been deleted
2258          * by the normal truncation mechanic.
2259          */
2260         if (error == 0 && ip->sync_ino_data.nlinks == 0 &&
2261                 RB_EMPTY(&ip->rec_tree)  &&
2262             (ip->sync_flags & HAMMER_INODE_DELETING) &&
2263             (ip->flags & HAMMER_INODE_DELETED) == 0) {
2264                 int count1 = 0;
2265
2266                 error = hammer_ip_delete_clean(&cursor, ip, &count1);
2267                 if (error == 0) {
2268                         ip->flags |= HAMMER_INODE_DELETED;
2269                         ip->sync_flags &= ~HAMMER_INODE_DELETING;
2270                         ip->sync_flags &= ~HAMMER_INODE_TRUNCATED;
2271                         KKASSERT(RB_EMPTY(&ip->rec_tree));
2272
2273                         /*
2274                          * Set delete_tid in both the frontend and backend
2275                          * copy of the inode record.  The DELETED flag handles
2276                          * this, do not set RDIRTY.
2277                          */
2278                         ip->ino_leaf.base.delete_tid = trans.tid;
2279                         ip->sync_ino_leaf.base.delete_tid = trans.tid;
2280                         ip->ino_leaf.delete_ts = trans.time32;
2281                         ip->sync_ino_leaf.delete_ts = trans.time32;
2282
2283
2284                         /*
2285                          * Adjust the inode count in the volume header
2286                          */
2287                         if (ip->flags & HAMMER_INODE_ONDISK) {
2288                                 hammer_modify_volume_field(&trans,
2289                                                            trans.rootvol,
2290                                                            vol0_stat_inodes);
2291                                 --ip->hmp->rootvol->ondisk->vol0_stat_inodes;
2292                                 hammer_modify_volume_done(trans.rootvol);
2293                         }
2294                 } else {
2295                         Debugger("hammer_ip_delete_clean errored");
2296                 }
2297         }
2298
2299         ip->sync_flags &= ~HAMMER_INODE_BUFS;
2300
2301         if (error)
2302                 Debugger("RB_SCAN errored");
2303
2304 defer_buffer_flush:
2305         /*
2306          * Now update the inode's on-disk inode-data and/or on-disk record.
2307          * DELETED and ONDISK are managed only in ip->flags.
2308          *
2309          * In the case of a defered buffer flush we still update the on-disk
2310          * inode to satisfy visibility requirements if there happen to be
2311          * directory dependancies.
2312          */
2313         switch(ip->flags & (HAMMER_INODE_DELETED | HAMMER_INODE_ONDISK)) {
2314         case HAMMER_INODE_DELETED|HAMMER_INODE_ONDISK:
2315                 /*
2316                  * If deleted and on-disk, don't set any additional flags.
2317                  * the delete flag takes care of things.
2318                  *
2319                  * Clear flags which may have been set by the frontend.
2320                  */
2321                 ip->sync_flags &= ~(HAMMER_INODE_DDIRTY | HAMMER_INODE_XDIRTY |
2322                                     HAMMER_INODE_ATIME | HAMMER_INODE_MTIME |
2323                                     HAMMER_INODE_DELETING);
2324                 break;
2325         case HAMMER_INODE_DELETED:
2326                 /*
2327                  * Take care of the case where a deleted inode was never
2328                  * flushed to the disk in the first place.
2329                  *
2330                  * Clear flags which may have been set by the frontend.
2331                  */
2332                 ip->sync_flags &= ~(HAMMER_INODE_DDIRTY | HAMMER_INODE_XDIRTY |
2333                                     HAMMER_INODE_ATIME | HAMMER_INODE_MTIME |
2334                                     HAMMER_INODE_DELETING);
2335                 while (RB_ROOT(&ip->rec_tree)) {
2336                         hammer_record_t record = RB_ROOT(&ip->rec_tree);
2337                         hammer_ref(&record->lock);
2338                         KKASSERT(record->lock.refs == 1);
2339                         record->flags |= HAMMER_RECF_DELETED_FE;
2340                         record->flags |= HAMMER_RECF_DELETED_BE;
2341                         hammer_rel_mem_record(record);
2342                 }
2343                 break;
2344         case HAMMER_INODE_ONDISK:
2345                 /*
2346                  * If already on-disk, do not set any additional flags.
2347                  */
2348                 break;
2349         default:
2350                 /*
2351                  * If not on-disk and not deleted, set DDIRTY to force
2352                  * an initial record to be written.
2353                  *
2354                  * Also set the create_tid in both the frontend and backend
2355                  * copy of the inode record.
2356                  */
2357                 ip->ino_leaf.base.create_tid = trans.tid;
2358                 ip->ino_leaf.create_ts = trans.time32;
2359                 ip->sync_ino_leaf.base.create_tid = trans.tid;
2360                 ip->sync_ino_leaf.create_ts = trans.time32;
2361                 ip->sync_flags |= HAMMER_INODE_DDIRTY;
2362                 break;
2363         }
2364
2365         /*
2366          * If RDIRTY or DDIRTY is set, write out a new record.  If the inode
2367          * is already on-disk the old record is marked as deleted.
2368          *
2369          * If DELETED is set hammer_update_inode() will delete the existing
2370          * record without writing out a new one.
2371          *
2372          * If *ONLY* the ITIMES flag is set we can update the record in-place.
2373          */
2374         if (ip->flags & HAMMER_INODE_DELETED) {
2375                 error = hammer_update_inode(&cursor, ip);
2376         } else 
2377         if ((ip->sync_flags & HAMMER_INODE_DDIRTY) == 0 &&
2378             (ip->sync_flags & (HAMMER_INODE_ATIME | HAMMER_INODE_MTIME))) {
2379                 error = hammer_update_itimes(&cursor, ip);
2380         } else
2381         if (ip->sync_flags & (HAMMER_INODE_DDIRTY | HAMMER_INODE_ATIME | HAMMER_INODE_MTIME)) {
2382                 error = hammer_update_inode(&cursor, ip);
2383         }
2384         if (error)
2385                 Debugger("hammer_update_itimes/inode errored");
2386 done:
2387         /*
2388          * Save the TID we used to sync the inode with to make sure we
2389          * do not improperly reuse it.
2390          */
2391         hammer_done_cursor(&cursor);
2392         hammer_done_transaction(&trans);
2393         return(error);
2394 }
2395
2396 /*
2397  * This routine is called when the OS is no longer actively referencing
2398  * the inode (but might still be keeping it cached), or when releasing
2399  * the last reference to an inode.
2400  *
2401  * At this point if the inode's nlinks count is zero we want to destroy
2402  * it, which may mean destroying it on-media too.
2403  */
2404 void
2405 hammer_inode_unloadable_check(hammer_inode_t ip, int getvp)
2406 {
2407         struct vnode *vp;
2408
2409         /*
2410          * Set the DELETING flag when the link count drops to 0 and the
2411          * OS no longer has any opens on the inode.
2412          *
2413          * The backend will clear DELETING (a mod flag) and set DELETED
2414          * (a state flag) when it is actually able to perform the
2415          * operation.
2416          */
2417         if (ip->ino_data.nlinks == 0 &&
2418             (ip->flags & (HAMMER_INODE_DELETING|HAMMER_INODE_DELETED)) == 0) {
2419                 ip->flags |= HAMMER_INODE_DELETING;
2420                 ip->flags |= HAMMER_INODE_TRUNCATED;
2421                 ip->trunc_off = 0;
2422                 vp = NULL;
2423                 if (getvp) {
2424                         if (hammer_get_vnode(ip, &vp) != 0)
2425                                 return;
2426                 }
2427
2428                 /*
2429                  * Final cleanup
2430                  */
2431                 if (ip->vp) {
2432                         vtruncbuf(ip->vp, 0, HAMMER_BUFSIZE);
2433                         vnode_pager_setsize(ip->vp, 0);
2434                 }
2435                 if (getvp) {
2436                         vput(vp);
2437                 }
2438         }
2439 }
2440
2441 /*
2442  * Re-test an inode when a dependancy had gone away to see if we
2443  * can chain flush it.
2444  */
2445 void
2446 hammer_test_inode(hammer_inode_t ip)
2447 {
2448         if (ip->flags & HAMMER_INODE_REFLUSH) {
2449                 ip->flags &= ~HAMMER_INODE_REFLUSH;
2450                 hammer_ref(&ip->lock);
2451                 if (ip->flags & HAMMER_INODE_RESIGNAL) {
2452                         ip->flags &= ~HAMMER_INODE_RESIGNAL;
2453                         hammer_flush_inode(ip, HAMMER_FLUSH_SIGNAL);
2454                 } else {
2455                         hammer_flush_inode(ip, 0);
2456                 }
2457                 hammer_rel_inode(ip, 0);
2458         }
2459 }
2460
2461 /*
2462  * Clear the RECLAIM flag on an inode.  This occurs when the inode is
2463  * reassociated with a vp or just before it gets freed.
2464  *
2465  * Wakeup one thread blocked waiting on reclaims to complete.  Note that
2466  * the inode the thread is waiting on behalf of is a different inode then
2467  * the inode we are called with.  This is to create a pipeline.
2468  */
2469 static void
2470 hammer_inode_wakereclaims(hammer_inode_t ip)
2471 {
2472         struct hammer_reclaim *reclaim;
2473         hammer_mount_t hmp = ip->hmp;
2474
2475         if ((ip->flags & HAMMER_INODE_RECLAIM) == 0)
2476                 return;
2477
2478         --hammer_count_reclaiming;
2479         --hmp->inode_reclaims;
2480         ip->flags &= ~HAMMER_INODE_RECLAIM;
2481
2482         if ((reclaim = TAILQ_FIRST(&hmp->reclaim_list)) != NULL) {
2483                 TAILQ_REMOVE(&hmp->reclaim_list, reclaim, entry);
2484                 reclaim->okydoky = 1;
2485                 wakeup(reclaim);
2486         }
2487 }
2488
2489 /*
2490  * Setup our reclaim pipeline.  We only let so many detached (and dirty)
2491  * inodes build up before we start blocking.
2492  *
2493  * When we block we don't care *which* inode has finished reclaiming,
2494  * as lone as one does.  This is somewhat heuristical... we also put a
2495  * cap on how long we are willing to wait.
2496  */
2497 void
2498 hammer_inode_waitreclaims(hammer_mount_t hmp)
2499 {
2500         struct hammer_reclaim reclaim;
2501         int delay;
2502
2503         if (hmp->inode_reclaims > HAMMER_RECLAIM_WAIT) {
2504                 reclaim.okydoky = 0;
2505                 TAILQ_INSERT_TAIL(&hmp->reclaim_list,
2506                                   &reclaim, entry);
2507         } else {
2508                 reclaim.okydoky = 1;
2509         }
2510
2511         if (reclaim.okydoky == 0) {
2512                 delay = (hmp->inode_reclaims - HAMMER_RECLAIM_WAIT) * hz /
2513                         HAMMER_RECLAIM_WAIT;
2514                 if (delay >= 0)
2515                         tsleep(&reclaim, 0, "hmrrcm", delay + 1);
2516                 if (reclaim.okydoky == 0)
2517                         TAILQ_REMOVE(&hmp->reclaim_list, &reclaim, entry);
2518         }
2519 }
2520