HAMMER 56C/Many: Performance tuning - MEDIA STRUCTURES CHANGED!
[dragonfly.git] / sys / vfs / hammer / hammer_object.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_object.c,v 1.71 2008/06/20 05:38:26 dillon Exp $
35  */
36
37 #include "hammer.h"
38
39 static int hammer_mem_add(hammer_record_t record);
40 static int hammer_mem_lookup(hammer_cursor_t cursor);
41 static int hammer_mem_first(hammer_cursor_t cursor);
42 static int hammer_rec_trunc_callback(hammer_record_t record,
43                                 void *data __unused);
44 static int hammer_record_needs_overwrite_delete(hammer_record_t record);
45
46 struct rec_trunc_info {
47         u_int16_t       rec_type;
48         int64_t         trunc_off;
49 };
50
51 /*
52  * Red-black tree support.  Comparison code for insertion.
53  */
54 static int
55 hammer_rec_rb_compare(hammer_record_t rec1, hammer_record_t rec2)
56 {
57         if (rec1->leaf.base.rec_type < rec2->leaf.base.rec_type)
58                 return(-1);
59         if (rec1->leaf.base.rec_type > rec2->leaf.base.rec_type)
60                 return(1);
61
62         if (rec1->leaf.base.key < rec2->leaf.base.key)
63                 return(-1);
64         if (rec1->leaf.base.key > rec2->leaf.base.key)
65                 return(1);
66
67         /*
68          * Never match against an item deleted by the front-end.
69          *
70          * rec1 is greater then rec2 if rec1 is marked deleted.
71          * rec1 is less then rec2 if rec2 is marked deleted.
72          *
73          * Multiple deleted records may be present, do not return 0
74          * if both are marked deleted.
75          */
76         if (rec1->flags & HAMMER_RECF_DELETED_FE)
77                 return(1);
78         if (rec2->flags & HAMMER_RECF_DELETED_FE)
79                 return(-1);
80
81         return(0);
82 }
83
84 /*
85  * Basic record comparison code similar to hammer_btree_cmp().
86  */
87 static int
88 hammer_rec_cmp(hammer_base_elm_t elm, hammer_record_t rec)
89 {
90         if (elm->rec_type < rec->leaf.base.rec_type)
91                 return(-3);
92         if (elm->rec_type > rec->leaf.base.rec_type)
93                 return(3);
94
95         if (elm->key < rec->leaf.base.key)
96                 return(-2);
97         if (elm->key > rec->leaf.base.key)
98                 return(2);
99
100         /*
101          * Never match against an item deleted by the front-end.
102          * elm is less then rec if rec is marked deleted.
103          */
104         if (rec->flags & HAMMER_RECF_DELETED_FE)
105                 return(-1);
106         return(0);
107 }
108
109 /*
110  * Special LOOKUP_INFO to locate an overlapping record.  This used by
111  * the reservation code to implement small-block records (whos keys will
112  * be different depending on data_len, when representing the same base
113  * offset).
114  *
115  * NOTE: The base file offset of a data record is (key - data_len), not (key).
116  */
117 static int
118 hammer_rec_overlap_compare(hammer_btree_leaf_elm_t leaf, hammer_record_t rec)
119 {
120         if (leaf->base.rec_type < rec->leaf.base.rec_type)
121                 return(-3);
122         if (leaf->base.rec_type > rec->leaf.base.rec_type)
123                 return(3);
124
125         /*
126          * Overlap compare
127          */
128         if (leaf->base.rec_type == HAMMER_RECTYPE_DATA) {
129                 /* leaf_end <= rec_beg */
130                 if (leaf->base.key <= rec->leaf.base.key - rec->leaf.data_len)
131                         return(-2);
132                 /* leaf_beg >= rec_end */
133                 if (leaf->base.key - leaf->data_len >= rec->leaf.base.key)
134                         return(2);
135         } else {
136                 if (leaf->base.key < rec->leaf.base.key)
137                         return(-2);
138                 if (leaf->base.key > rec->leaf.base.key)
139                         return(2);
140         }
141
142         /*
143          * Never match against an item deleted by the front-end.
144          * leaf is less then rec if rec is marked deleted.
145          *
146          * We must still return the proper code for the scan to continue
147          * along the correct branches.
148          */
149         if (rec->flags & HAMMER_RECF_DELETED_FE) {
150                 if (leaf->base.key < rec->leaf.base.key)
151                         return(-2);
152                 if (leaf->base.key > rec->leaf.base.key)
153                         return(2);
154                 return(-1);
155         }
156         return(0);
157 }
158
159 /*
160  * RB_SCAN comparison code for hammer_mem_first().  The argument order
161  * is reversed so the comparison result has to be negated.  key_beg and
162  * key_end are both range-inclusive.
163  *
164  * Localized deletions are not cached in-memory.
165  */
166 static
167 int
168 hammer_rec_scan_cmp(hammer_record_t rec, void *data)
169 {
170         hammer_cursor_t cursor = data;
171         int r;
172
173         r = hammer_rec_cmp(&cursor->key_beg, rec);
174         if (r > 1)
175                 return(-1);
176         r = hammer_rec_cmp(&cursor->key_end, rec);
177         if (r < -1)
178                 return(1);
179         return(0);
180 }
181
182 /*
183  * This compare function is used when simply looking up key_beg.
184  */
185 static
186 int
187 hammer_rec_find_cmp(hammer_record_t rec, void *data)
188 {
189         hammer_cursor_t cursor = data;
190         int r;
191
192         r = hammer_rec_cmp(&cursor->key_beg, rec);
193         if (r > 1)
194                 return(-1);
195         if (r < -1)
196                 return(1);
197         return(0);
198 }
199
200 /*
201  * Locate blocks within the truncation range.  Partial blocks do not count.
202  */
203 static
204 int
205 hammer_rec_trunc_cmp(hammer_record_t rec, void *data)
206 {
207         struct rec_trunc_info *info = data;
208
209         if (rec->leaf.base.rec_type < info->rec_type)
210                 return(-1);
211         if (rec->leaf.base.rec_type > info->rec_type)
212                 return(1);
213
214         switch(rec->leaf.base.rec_type) {
215         case HAMMER_RECTYPE_DB:
216                 /*
217                  * DB record key is not beyond the truncation point, retain.
218                  */
219                 if (rec->leaf.base.key < info->trunc_off)
220                         return(-1);
221                 break;
222         case HAMMER_RECTYPE_DATA:
223                 /*
224                  * DATA record offset start is not beyond the truncation point,
225                  * retain.
226                  */
227                 if (rec->leaf.base.key - rec->leaf.data_len < info->trunc_off)
228                         return(-1);
229                 break;
230         default:
231                 panic("hammer_rec_trunc_cmp: unexpected record type");
232         }
233
234         /*
235          * The record start is >= the truncation point, return match,
236          * the record should be destroyed.
237          */
238         return(0);
239 }
240
241 RB_GENERATE(hammer_rec_rb_tree, hammer_record, rb_node, hammer_rec_rb_compare);
242 RB_GENERATE_XLOOKUP(hammer_rec_rb_tree, INFO, hammer_record, rb_node,
243                     hammer_rec_overlap_compare, hammer_btree_leaf_elm_t);
244
245 /*
246  * Allocate a record for the caller to finish filling in.  The record is
247  * returned referenced.
248  */
249 hammer_record_t
250 hammer_alloc_mem_record(hammer_inode_t ip, int data_len)
251 {
252         hammer_record_t record;
253
254         ++hammer_count_records;
255         record = kmalloc(sizeof(*record), M_HAMMER, M_WAITOK | M_ZERO);
256         record->flush_state = HAMMER_FST_IDLE;
257         record->ip = ip;
258         record->leaf.base.btype = HAMMER_BTREE_TYPE_RECORD;
259         record->leaf.data_len = data_len;
260         hammer_ref(&record->lock);
261
262         if (data_len) {
263                 record->data = kmalloc(data_len, M_HAMMER, M_WAITOK | M_ZERO);
264                 record->flags |= HAMMER_RECF_ALLOCDATA;
265                 ++hammer_count_record_datas;
266         }
267
268         return (record);
269 }
270
271 void
272 hammer_wait_mem_record_ident(hammer_record_t record, const char *ident)
273 {
274         while (record->flush_state == HAMMER_FST_FLUSH) {
275                 record->flags |= HAMMER_RECF_WANTED;
276                 tsleep(record, 0, ident, 0);
277         }
278 }
279
280 /*
281  * Called from the backend, hammer_inode.c, after a record has been
282  * flushed to disk.  The record has been exclusively locked by the
283  * caller and interlocked with BE.
284  *
285  * We clean up the state, unlock, and release the record (the record
286  * was referenced by the fact that it was in the HAMMER_FST_FLUSH state).
287  */
288 void
289 hammer_flush_record_done(hammer_record_t record, int error)
290 {
291         hammer_inode_t target_ip;
292
293         KKASSERT(record->flush_state == HAMMER_FST_FLUSH);
294         KKASSERT(record->flags & HAMMER_RECF_INTERLOCK_BE);
295
296         if (error) {
297                 /*
298                  * An error occured, the backend was unable to sync the
299                  * record to its media.  Leave the record intact.
300                  */
301                 Debugger("flush_record_done error");
302         }
303
304         if (record->flags & HAMMER_RECF_DELETED_BE) {
305                 if ((target_ip = record->target_ip) != NULL) {
306                         TAILQ_REMOVE(&target_ip->target_list, record,
307                                      target_entry);
308                         record->target_ip = NULL;
309                         hammer_test_inode(target_ip);
310                 }
311                 record->flush_state = HAMMER_FST_IDLE;
312         } else {
313                 if (record->target_ip) {
314                         record->flush_state = HAMMER_FST_SETUP;
315                         hammer_test_inode(record->ip);
316                         hammer_test_inode(record->target_ip);
317                 } else {
318                         record->flush_state = HAMMER_FST_IDLE;
319                 }
320         }
321         record->flags &= ~HAMMER_RECF_INTERLOCK_BE;
322         if (record->flags & HAMMER_RECF_WANTED) {
323                 record->flags &= ~HAMMER_RECF_WANTED;
324                 wakeup(record);
325         }
326         hammer_rel_mem_record(record);
327 }
328
329 /*
330  * Release a memory record.  Records marked for deletion are immediately
331  * removed from the RB-Tree but otherwise left intact until the last ref
332  * goes away.
333  */
334 void
335 hammer_rel_mem_record(struct hammer_record *record)
336 {
337         hammer_inode_t ip, target_ip;
338
339         hammer_unref(&record->lock);
340
341         if (record->lock.refs == 0) {
342                 /*
343                  * Upon release of the last reference wakeup any waiters.
344                  * The record structure may get destroyed so callers will
345                  * loop up and do a relookup.
346                  *
347                  * WARNING!  Record must be removed from RB-TREE before we
348                  * might possibly block.  hammer_test_inode() can block!
349                  */
350                 ip = record->ip;
351
352                 /*
353                  * Upon release of the last reference a record marked deleted
354                  * is destroyed.
355                  */
356                 if (record->flags & HAMMER_RECF_DELETED_FE) {
357                         KKASSERT(ip->lock.refs > 0);
358                         KKASSERT(record->flush_state != HAMMER_FST_FLUSH);
359
360                         /*
361                          * target_ip may have zero refs, we have to ref it
362                          * to prevent it from being ripped out from under
363                          * us.
364                          */
365                         if ((target_ip = record->target_ip) != NULL) {
366                                 TAILQ_REMOVE(&target_ip->target_list,
367                                              record, target_entry);
368                                 record->target_ip = NULL;
369                                 hammer_ref(&target_ip->lock);
370                         }
371
372                         if (record->flags & HAMMER_RECF_ONRBTREE) {
373                                 RB_REMOVE(hammer_rec_rb_tree,
374                                           &record->ip->rec_tree,
375                                           record);
376                                 KKASSERT(ip->rsv_recs > 0);
377                                 --ip->hmp->rsv_recs;
378                                 --ip->rsv_recs;
379                                 ip->hmp->rsv_databytes -= record->leaf.data_len;
380                                 record->flags &= ~HAMMER_RECF_ONRBTREE;
381
382                                 if (RB_EMPTY(&record->ip->rec_tree)) {
383                                         record->ip->flags &= ~HAMMER_INODE_XDIRTY;
384                                         record->ip->sync_flags &= ~HAMMER_INODE_XDIRTY;
385                                         hammer_test_inode(record->ip);
386                                 }
387                         }
388
389                         /*
390                          * Do this test after removing record from the B-Tree.
391                          */
392                         if (target_ip) {
393                                 hammer_test_inode(target_ip);
394                                 hammer_rel_inode(target_ip, 0);
395                         }
396
397                         if (record->flags & HAMMER_RECF_ALLOCDATA) {
398                                 --hammer_count_record_datas;
399                                 kfree(record->data, M_HAMMER);
400                                 record->flags &= ~HAMMER_RECF_ALLOCDATA;
401                         }
402                         if (record->resv) {
403                                 hammer_blockmap_reserve_complete(ip->hmp,
404                                                                  record->resv);
405                                 record->resv = NULL;
406                         }
407                         record->data = NULL;
408                         --hammer_count_records;
409                         kfree(record, M_HAMMER);
410                 }
411         }
412 }
413
414 /*
415  * Record visibility depends on whether the record is being accessed by
416  * the backend or the frontend.
417  *
418  * Return non-zero if the record is visible, zero if it isn't or if it is
419  * deleted.
420  */
421 static __inline
422 int
423 hammer_ip_iterate_mem_good(hammer_cursor_t cursor, hammer_record_t record)
424 {
425         if (cursor->flags & HAMMER_CURSOR_BACKEND) {
426                 if (record->flags & HAMMER_RECF_DELETED_BE)
427                         return(0);
428         } else {
429                 if (record->flags & HAMMER_RECF_DELETED_FE)
430                         return(0);
431         }
432         return(1);
433 }
434
435 /*
436  * This callback is used as part of the RB_SCAN function for in-memory
437  * records.  We terminate it (return -1) as soon as we get a match.
438  *
439  * This routine is used by frontend code.
440  *
441  * The primary compare code does not account for ASOF lookups.  This
442  * code handles that case as well as a few others.
443  */
444 static
445 int
446 hammer_rec_scan_callback(hammer_record_t rec, void *data)
447 {
448         hammer_cursor_t cursor = data;
449
450         /*
451          * We terminate on success, so this should be NULL on entry.
452          */
453         KKASSERT(cursor->iprec == NULL);
454
455         /*
456          * Skip if the record was marked deleted.
457          */
458         if (hammer_ip_iterate_mem_good(cursor, rec) == 0)
459                 return(0);
460
461         /*
462          * Skip if not visible due to our as-of TID
463          */
464         if (cursor->flags & HAMMER_CURSOR_ASOF) {
465                 if (cursor->asof < rec->leaf.base.create_tid)
466                         return(0);
467                 if (rec->leaf.base.delete_tid &&
468                     cursor->asof >= rec->leaf.base.delete_tid) {
469                         return(0);
470                 }
471         }
472
473         /*
474          * If the record is queued to the flusher we have to block until
475          * it isn't.  Otherwise we may see duplication between our memory
476          * cache and the media.
477          */
478         hammer_ref(&rec->lock);
479
480 #warning "This deadlocks"
481 #if 0
482         if (rec->flush_state == HAMMER_FST_FLUSH)
483                 hammer_wait_mem_record(rec);
484 #endif
485
486         /*
487          * The record may have been deleted while we were blocked.
488          */
489         if (hammer_ip_iterate_mem_good(cursor, rec) == 0) {
490                 hammer_rel_mem_record(rec);
491                 return(0);
492         }
493
494         /*
495          * Set the matching record and stop the scan.
496          */
497         cursor->iprec = rec;
498         return(-1);
499 }
500
501
502 /*
503  * Lookup an in-memory record given the key specified in the cursor.  Works
504  * just like hammer_btree_lookup() but operates on an inode's in-memory
505  * record list.
506  *
507  * The lookup must fail if the record is marked for deferred deletion.
508  */
509 static
510 int
511 hammer_mem_lookup(hammer_cursor_t cursor)
512 {
513         int error;
514
515         KKASSERT(cursor->ip);
516         if (cursor->iprec) {
517                 hammer_rel_mem_record(cursor->iprec);
518                 cursor->iprec = NULL;
519         }
520         hammer_rec_rb_tree_RB_SCAN(&cursor->ip->rec_tree, hammer_rec_find_cmp,
521                                    hammer_rec_scan_callback, cursor);
522
523         if (cursor->iprec == NULL)
524                 error = ENOENT;
525         else
526                 error = 0;
527         return(error);
528 }
529
530 /*
531  * hammer_mem_first() - locate the first in-memory record matching the
532  * cursor within the bounds of the key range.
533  */
534 static
535 int
536 hammer_mem_first(hammer_cursor_t cursor)
537 {
538         hammer_inode_t ip;
539
540         ip = cursor->ip;
541         KKASSERT(ip != NULL);
542
543         if (cursor->iprec) {
544                 hammer_rel_mem_record(cursor->iprec);
545                 cursor->iprec = NULL;
546         }
547
548         hammer_rec_rb_tree_RB_SCAN(&ip->rec_tree, hammer_rec_scan_cmp,
549                                    hammer_rec_scan_callback, cursor);
550
551         /*
552          * Adjust scan.node and keep it linked into the RB-tree so we can
553          * hold the cursor through third party modifications of the RB-tree.
554          */
555         if (cursor->iprec)
556                 return(0);
557         return(ENOENT);
558 }
559
560 void
561 hammer_mem_done(hammer_cursor_t cursor)
562 {
563         if (cursor->iprec) {
564                 hammer_rel_mem_record(cursor->iprec);
565                 cursor->iprec = NULL;
566         }
567 }
568
569 /************************************************************************
570  *                   HAMMER IN-MEMORY RECORD FUNCTIONS                  *
571  ************************************************************************
572  *
573  * These functions manipulate in-memory records.  Such records typically
574  * exist prior to being committed to disk or indexed via the on-disk B-Tree.
575  */
576
577 /*
578  * Add a directory entry (dip,ncp) which references inode (ip).
579  *
580  * Note that the low 32 bits of the namekey are set temporarily to create
581  * a unique in-memory record, and may be modified a second time when the
582  * record is synchronized to disk.  In particular, the low 32 bits cannot be
583  * all 0's when synching to disk, which is not handled here.
584  */
585 int
586 hammer_ip_add_directory(struct hammer_transaction *trans,
587                      struct hammer_inode *dip, struct namecache *ncp,
588                      struct hammer_inode *ip)
589 {
590         hammer_record_t record;
591         int error;
592         int bytes;
593
594         bytes = ncp->nc_nlen;   /* NOTE: terminating \0 is NOT included */
595         record = hammer_alloc_mem_record(dip, HAMMER_ENTRY_SIZE(bytes));
596         if (++trans->hmp->namekey_iterator == 0)
597                 ++trans->hmp->namekey_iterator;
598
599         record->type = HAMMER_MEM_RECORD_ADD;
600         record->leaf.base.localization = HAMMER_LOCALIZE_MISC;
601         record->leaf.base.obj_id = dip->obj_id;
602         record->leaf.base.key = hammer_directory_namekey(ncp->nc_name, bytes);
603         record->leaf.base.key += trans->hmp->namekey_iterator;
604         record->leaf.base.rec_type = HAMMER_RECTYPE_DIRENTRY;
605         record->leaf.base.obj_type = ip->ino_leaf.base.obj_type;
606         record->data->entry.obj_id = ip->obj_id;
607         bcopy(ncp->nc_name, record->data->entry.name, bytes);
608
609         ++ip->ino_data.nlinks;
610         hammer_modify_inode(ip, HAMMER_INODE_DDIRTY);
611
612         /*
613          * The target inode and the directory entry are bound together.
614          */
615         record->target_ip = ip;
616         record->flush_state = HAMMER_FST_SETUP;
617         TAILQ_INSERT_TAIL(&ip->target_list, record, target_entry);
618
619         /*
620          * The inode now has a dependancy and must be taken out of the idle
621          * state.  An inode not in an idle state is given an extra reference.
622          */
623         if (ip->flush_state == HAMMER_FST_IDLE) {
624                 hammer_ref(&ip->lock);
625                 ip->flush_state = HAMMER_FST_SETUP;
626         }
627         error = hammer_mem_add(record);
628         return(error);
629 }
630
631 /*
632  * Delete the directory entry and update the inode link count.  The
633  * cursor must be seeked to the directory entry record being deleted.
634  *
635  * The related inode should be share-locked by the caller.  The caller is
636  * on the frontend.
637  *
638  * This function can return EDEADLK requiring the caller to terminate
639  * the cursor, any locks, wait on the returned record, and retry.
640  */
641 int
642 hammer_ip_del_directory(struct hammer_transaction *trans,
643                      hammer_cursor_t cursor, struct hammer_inode *dip,
644                      struct hammer_inode *ip)
645 {
646         hammer_record_t record;
647         int error;
648
649         if (hammer_cursor_inmem(cursor)) {
650                 /*
651                  * In-memory (unsynchronized) records can simply be freed.
652                  * Even though the HAMMER_RECF_DELETED_FE flag is ignored
653                  * by the backend, we must still avoid races against the
654                  * backend potentially syncing the record to the media. 
655                  *
656                  * We cannot call hammer_ip_delete_record(), that routine may
657                  * only be called from the backend.
658                  */
659                 record = cursor->iprec;
660                 if (record->flags & HAMMER_RECF_INTERLOCK_BE) {
661                         KKASSERT(cursor->deadlk_rec == NULL);
662                         hammer_ref(&record->lock);
663                         cursor->deadlk_rec = record;
664                         error = EDEADLK;
665                 } else {
666                         KKASSERT(record->type == HAMMER_MEM_RECORD_ADD);
667                         record->flags |= HAMMER_RECF_DELETED_FE;
668                         error = 0;
669                 }
670         } else {
671                 /*
672                  * If the record is on-disk we have to queue the deletion by
673                  * the record's key.  This also causes lookups to skip the
674                  * record.
675                  */
676                 KKASSERT(dip->flags &
677                          (HAMMER_INODE_ONDISK | HAMMER_INODE_DONDISK));
678                 record = hammer_alloc_mem_record(dip, 0);
679                 record->type = HAMMER_MEM_RECORD_DEL;
680                 record->leaf.base = cursor->leaf->base;
681
682                 record->target_ip = ip;
683                 record->flush_state = HAMMER_FST_SETUP;
684                 TAILQ_INSERT_TAIL(&ip->target_list, record, target_entry);
685
686                 /*
687                  * The inode now has a dependancy and must be taken out of
688                  * the idle state.  An inode not in an idle state is given
689                  * an extra reference.
690                  */
691                 if (ip->flush_state == HAMMER_FST_IDLE) {
692                         hammer_ref(&ip->lock);
693                         ip->flush_state = HAMMER_FST_SETUP;
694                 }
695
696                 error = hammer_mem_add(record);
697         }
698
699         /*
700          * One less link.  The file may still be open in the OS even after
701          * all links have gone away.
702          *
703          * We have to terminate the cursor before syncing the inode to
704          * avoid deadlocking against ourselves.  XXX this may no longer
705          * be true.
706          *
707          * If nlinks drops to zero and the vnode is inactive (or there is
708          * no vnode), call hammer_inode_unloadable_check() to zonk the
709          * inode.  If we don't do this here the inode will not be destroyed
710          * on-media until we unmount.
711          */
712         if (error == 0) {
713                 --ip->ino_data.nlinks;
714                 hammer_modify_inode(ip, HAMMER_INODE_DDIRTY);
715                 if (ip->ino_data.nlinks == 0 &&
716                     (ip->vp == NULL || (ip->vp->v_flag & VINACTIVE))) {
717                         hammer_done_cursor(cursor);
718                         hammer_inode_unloadable_check(ip, 1);
719                         hammer_flush_inode(ip, 0);
720                 }
721
722         }
723         return(error);
724 }
725
726 /*
727  * Add a record to an inode.
728  *
729  * The caller must allocate the record with hammer_alloc_mem_record(ip) and
730  * initialize the following additional fields:
731  *
732  * The related inode should be share-locked by the caller.  The caller is
733  * on the frontend.
734  *
735  * record->rec.entry.base.base.key
736  * record->rec.entry.base.base.rec_type
737  * record->rec.entry.base.base.data_len
738  * record->data         (a copy will be kmalloc'd if it cannot be embedded)
739  */
740 int
741 hammer_ip_add_record(struct hammer_transaction *trans, hammer_record_t record)
742 {
743         hammer_inode_t ip = record->ip;
744         int error;
745
746         KKASSERT(record->leaf.base.localization != 0);
747         record->leaf.base.obj_id = ip->obj_id;
748         record->leaf.base.obj_type = ip->ino_leaf.base.obj_type;
749         error = hammer_mem_add(record);
750         return(error);
751 }
752
753 /*
754  * Locate a bulk record in-memory.  Bulk records allow disk space to be
755  * reserved so the front-end can flush large data writes without having
756  * to queue the BIO to the flusher.  Only the related record gets queued
757  * to the flusher.
758  */
759 static hammer_record_t
760 hammer_ip_get_bulk(hammer_inode_t ip, off_t file_offset, int bytes)
761 {
762         hammer_record_t record;
763         struct hammer_btree_leaf_elm leaf;
764
765         bzero(&leaf, sizeof(leaf));
766         leaf.base.obj_id = ip->obj_id;
767         leaf.base.key = file_offset + bytes;
768         leaf.base.create_tid = 0;
769         leaf.base.delete_tid = 0;
770         leaf.base.rec_type = HAMMER_RECTYPE_DATA;
771         leaf.base.obj_type = 0;                 /* unused */
772         leaf.base.btype = HAMMER_BTREE_TYPE_RECORD;     /* unused */
773         leaf.base.localization = HAMMER_LOCALIZE_MISC;
774         leaf.data_len = bytes;
775
776         record = hammer_rec_rb_tree_RB_LOOKUP_INFO(&ip->rec_tree, &leaf);
777         if (record)
778                 hammer_ref(&record->lock);
779         return(record);
780 }
781
782 /*
783  * Reserve blockmap space placemarked with an in-memory record.  
784  *
785  * This routine is called by the frontend in order to be able to directly
786  * flush a buffer cache buffer.  The frontend has locked the related buffer
787  * cache buffers and we should be able to manipulate any overlapping
788  * in-memory records.
789  */
790 hammer_record_t
791 hammer_ip_add_bulk(hammer_inode_t ip, off_t file_offset, void *data, int bytes,
792                    int *errorp)
793 {
794         hammer_record_t record;
795         hammer_record_t conflict;
796         int zone;
797         int flags;
798
799         /*
800          * Deal with conflicting in-memory records.  We cannot have multiple
801          * in-memory records for the same offset without seriously confusing
802          * the backend, including but not limited to the backend issuing
803          * delete-create-delete sequences and asserting on the delete_tid
804          * being the same as the create_tid.
805          *
806          * If we encounter a record with the backend interlock set we cannot
807          * immediately delete it without confusing the backend.
808          */
809         while ((conflict = hammer_ip_get_bulk(ip, file_offset, bytes)) !=NULL) {
810                 if (conflict->flags & HAMMER_RECF_INTERLOCK_BE) {
811                         conflict->flags |= HAMMER_RECF_WANTED;
812                         tsleep(conflict, 0, "hmrrc3", 0);
813                 } else {
814                         conflict->flags |= HAMMER_RECF_DELETED_FE;
815                 }
816                 hammer_rel_mem_record(conflict);
817         }
818
819         /*
820          * Create a record to cover the direct write.  This is called with
821          * the related BIO locked so there should be no possible conflict.
822          *
823          * The backend is responsible for finalizing the space reserved in
824          * this record.
825          *
826          * XXX bytes not aligned, depend on the reservation code to
827          * align the reservation.
828          */
829         record = hammer_alloc_mem_record(ip, 0);
830         zone = (bytes >= HAMMER_BUFSIZE) ? HAMMER_ZONE_LARGE_DATA_INDEX :
831                                            HAMMER_ZONE_SMALL_DATA_INDEX;
832         record->resv = hammer_blockmap_reserve(ip->hmp, zone, bytes,
833                                                &record->leaf.data_offset,
834                                                errorp);
835         if (record->resv == NULL) {
836                 kprintf("hammer_ip_add_bulk: reservation failed\n");
837                 hammer_rel_mem_record(record);
838                 return(NULL);
839         }
840         record->type = HAMMER_MEM_RECORD_DATA;
841         record->leaf.base.rec_type = HAMMER_RECTYPE_DATA;
842         record->leaf.base.obj_type = ip->ino_leaf.base.obj_type;
843         record->leaf.base.obj_id = ip->obj_id;
844         record->leaf.base.key = file_offset + bytes;
845         record->leaf.base.localization = HAMMER_LOCALIZE_MISC;
846         record->leaf.data_len = bytes;
847         record->leaf.data_crc = crc32(data, bytes);
848         flags = record->flags;
849
850         hammer_ref(&record->lock);      /* mem_add eats a reference */
851         *errorp = hammer_mem_add(record);
852         if (*errorp) {
853                 conflict = hammer_ip_get_bulk(ip, file_offset, bytes);
854                 kprintf("hammer_ip_add_bulk: error %d conflict %p file_offset %lld bytes %d\n",
855                         *errorp, conflict, file_offset, bytes);
856                 if (conflict)
857                         kprintf("conflict %lld %d\n", conflict->leaf.base.key, conflict->leaf.data_len);
858                 if (conflict)
859                         hammer_rel_mem_record(conflict);
860         }
861         KKASSERT(*errorp == 0);
862         conflict = hammer_ip_get_bulk(ip, file_offset, bytes);
863         if (conflict != record) {
864                 kprintf("conflict mismatch %p %p %08x\n", conflict, record, record->flags);
865                 if (conflict)
866                     kprintf("conflict mismatch %lld/%d %lld/%d\n", conflict->leaf.base.key, conflict->leaf.data_len, record->leaf.base.key, record->leaf.data_len);
867         }
868         KKASSERT(conflict == record);
869         hammer_rel_mem_record(conflict);
870
871         return (record);
872 }
873
874 /*
875  * Frontend truncation code.  Scan in-memory records only.  On-disk records
876  * and records in a flushing state are handled by the backend.  The vnops
877  * setattr code will handle the block containing the truncation point.
878  *
879  * Partial blocks are not deleted.
880  */
881 int
882 hammer_ip_frontend_trunc(struct hammer_inode *ip, off_t file_size)
883 {
884         struct rec_trunc_info info;
885
886         switch(ip->ino_data.obj_type) {
887         case HAMMER_OBJTYPE_REGFILE:
888                 info.rec_type = HAMMER_RECTYPE_DATA;
889                 break;
890         case HAMMER_OBJTYPE_DBFILE:
891                 info.rec_type = HAMMER_RECTYPE_DB;
892                 break;
893         default:
894                 return(EINVAL);
895         }
896         info.trunc_off = file_size;
897         hammer_rec_rb_tree_RB_SCAN(&ip->rec_tree, hammer_rec_trunc_cmp,
898                                    hammer_rec_trunc_callback, &info);
899         return(0);
900 }
901
902 static int
903 hammer_rec_trunc_callback(hammer_record_t record, void *data __unused)
904 {
905         if (record->flags & HAMMER_RECF_DELETED_FE)
906                 return(0);
907         if (record->flush_state == HAMMER_FST_FLUSH)
908                 return(0);
909         KKASSERT((record->flags & HAMMER_RECF_INTERLOCK_BE) == 0);
910         hammer_ref(&record->lock);
911         record->flags |= HAMMER_RECF_DELETED_FE;
912         hammer_rel_mem_record(record);
913         return(0);
914 }
915
916 /*
917  * Return 1 if the caller must check for and delete existing records
918  * before writing out a new data record.
919  *
920  * Return 0 if the caller can just insert the record into the B-Tree without
921  * checking.
922  */
923 static int
924 hammer_record_needs_overwrite_delete(hammer_record_t record)
925 {
926         hammer_inode_t ip = record->ip;
927         int64_t file_offset;
928         int r;
929
930         if (ip->ino_data.obj_type == HAMMER_OBJTYPE_DBFILE)
931                 file_offset = record->leaf.base.key;
932         else
933                 file_offset = record->leaf.base.key - record->leaf.data_len;
934         r = (file_offset < ip->sync_trunc_off);
935         if (ip->ino_data.obj_type == HAMMER_OBJTYPE_DBFILE) {
936                 if (ip->sync_trunc_off <= record->leaf.base.key)
937                         ip->sync_trunc_off = record->leaf.base.key + 1;
938         } else {
939                 if (ip->sync_trunc_off < record->leaf.base.key)
940                         ip->sync_trunc_off = record->leaf.base.key;
941         }
942         return(r);
943 }
944
945 /*
946  * Backend code.  Sync a record to the media.
947  */
948 int
949 hammer_ip_sync_record_cursor(hammer_cursor_t cursor, hammer_record_t record)
950 {
951         hammer_transaction_t trans = cursor->trans;
952         int64_t file_offset;
953         int bytes;
954         void *bdata;
955         int error;
956
957         KKASSERT(record->flush_state == HAMMER_FST_FLUSH);
958         KKASSERT(record->flags & HAMMER_RECF_INTERLOCK_BE);
959         KKASSERT(record->leaf.base.localization != 0);
960
961         /*
962          * If this is a bulk-data record placemarker there may be an existing
963          * record on-disk, indicating a data overwrite.  If there is the
964          * on-disk record must be deleted before we can insert our new record.
965          *
966          * We've synthesized this record and do not know what the create_tid
967          * on-disk is, nor how much data it represents.
968          *
969          * Keep in mind that (key) for data records is (base_offset + len),
970          * not (base_offset).  Also, we only want to get rid of on-disk
971          * records since we are trying to sync our in-memory record, call
972          * hammer_ip_delete_range() with truncating set to 1 to make sure
973          * it skips in-memory records.
974          *
975          * It is ok for the lookup to return ENOENT.
976          *
977          * NOTE OPTIMIZATION: sync_trunc_off is used to determine if we have
978          * to call hammer_ip_delete_range() or not.  This also means we must
979          * update sync_trunc_off() as we write.
980          */
981         if (record->type == HAMMER_MEM_RECORD_DATA &&
982             hammer_record_needs_overwrite_delete(record)) {
983                 file_offset = record->leaf.base.key - record->leaf.data_len;
984                 bytes = (record->leaf.data_len + HAMMER_BUFMASK) & 
985                         ~HAMMER_BUFMASK;
986                 KKASSERT((file_offset & HAMMER_BUFMASK) == 0);
987                 error = hammer_ip_delete_range(
988                                 cursor, record->ip,
989                                 file_offset, file_offset + bytes - 1,
990                                 1);
991                 if (error && error != ENOENT)
992                         goto done;
993         }
994
995         /*
996          * Setup the cursor.
997          */
998         hammer_normalize_cursor(cursor);
999         cursor->key_beg = record->leaf.base;
1000         cursor->flags &= ~HAMMER_CURSOR_INITMASK;
1001         cursor->flags |= HAMMER_CURSOR_BACKEND;
1002         cursor->flags &= ~HAMMER_CURSOR_INSERT;
1003
1004         /*
1005          * Records can wind up on-media before the inode itself is on-media.
1006          * Flag the case.
1007          */
1008         record->ip->flags |= HAMMER_INODE_DONDISK;
1009
1010         /*
1011          * If we are deleting a directory entry an exact match must be
1012          * found on-disk.
1013          */
1014         if (record->type == HAMMER_MEM_RECORD_DEL) {
1015                 error = hammer_btree_lookup(cursor);
1016                 if (error == 0) {
1017                         error = hammer_ip_delete_record(cursor, record->ip,
1018                                                         trans->tid);
1019                         if (error == 0) {
1020                                 record->flags |= HAMMER_RECF_DELETED_FE;
1021                                 record->flags |= HAMMER_RECF_DELETED_BE;
1022                         }
1023                 }
1024                 goto done;
1025         }
1026
1027         /*
1028          * We are inserting.
1029          *
1030          * Issue a lookup to position the cursor and locate the cluster.  The
1031          * target key should not exist.  If we are creating a directory entry
1032          * we may have to iterate the low 32 bits of the key to find an unused
1033          * key.
1034          */
1035         cursor->flags |= HAMMER_CURSOR_INSERT;
1036
1037         for (;;) {
1038                 error = hammer_btree_lookup(cursor);
1039                 if (hammer_debug_inode)
1040                         kprintf("DOINSERT LOOKUP %d\n", error);
1041                 if (error)
1042                         break;
1043                 if (record->leaf.base.rec_type != HAMMER_RECTYPE_DIRENTRY) {
1044                         kprintf("hammer_ip_sync_record: duplicate rec "
1045                                 "at (%016llx)\n", record->leaf.base.key);
1046                         Debugger("duplicate record1");
1047                         error = EIO;
1048                         break;
1049                 }
1050                 if (++trans->hmp->namekey_iterator == 0)
1051                         ++trans->hmp->namekey_iterator;
1052                 record->leaf.base.key &= ~(0xFFFFFFFFLL);
1053                 record->leaf.base.key |= trans->hmp->namekey_iterator;
1054                 cursor->key_beg.key = record->leaf.base.key;
1055         }
1056 #if 0
1057         if (record->type == HAMMER_MEM_RECORD_DATA)
1058                 kprintf("sync_record  %016llx ---------------- %016llx %d\n",
1059                         record->leaf.base.key - record->leaf.data_len,
1060                         record->leaf.data_offset, error);
1061 #endif
1062                         
1063
1064         if (error != ENOENT)
1065                 goto done;
1066
1067         /*
1068          * Allocate the record and data.  The result buffers will be
1069          * marked as being modified and further calls to
1070          * hammer_modify_buffer() will result in unneeded UNDO records.
1071          *
1072          * Support zero-fill records (data == NULL and data_len != 0)
1073          */
1074         if (record->type == HAMMER_MEM_RECORD_DATA) {
1075                 /*
1076                  * The data portion of a bulk-data record has already been
1077                  * committed to disk, we need only adjust the layer2
1078                  * statistics in the same transaction as our B-Tree insert.
1079                  */
1080                 KKASSERT(record->leaf.data_offset != 0);
1081                 hammer_blockmap_finalize(trans, record->leaf.data_offset,
1082                                          record->leaf.data_len);
1083                 error = 0;
1084         } else if (record->data && record->leaf.data_len) {
1085                 /*
1086                  * Wholely cached record, with data.  Allocate the data.
1087                  */
1088                 bdata = hammer_alloc_data(trans, record->leaf.data_len,
1089                                           record->leaf.base.rec_type,
1090                                           &record->leaf.data_offset,
1091                                           &cursor->data_buffer, &error);
1092                 if (bdata == NULL)
1093                         goto done;
1094                 record->leaf.data_crc = crc32(record->data,
1095                                               record->leaf.data_len);
1096                 hammer_modify_buffer(trans, cursor->data_buffer, NULL, 0);
1097                 bcopy(record->data, bdata, record->leaf.data_len);
1098                 hammer_modify_buffer_done(cursor->data_buffer);
1099         } else {
1100                 /*
1101                  * Wholely cached record, without data.
1102                  */
1103                 record->leaf.data_offset = 0;
1104                 record->leaf.data_crc = 0;
1105         }
1106
1107         error = hammer_btree_insert(cursor, &record->leaf);
1108         if (hammer_debug_inode && error)
1109                 kprintf("BTREE INSERT error %d @ %016llx:%d key %016llx\n", error, cursor->node->node_offset, cursor->index, record->leaf.base.key);
1110
1111         /*
1112          * Our record is on-disk, normally mark the in-memory version as
1113          * deleted.  If the record represented a directory deletion but
1114          * we had to sync a valid directory entry to disk we must convert
1115          * the record to a covering delete so the frontend does not have
1116          * visibility on the synced entry.
1117          */
1118         if (error == 0) {
1119                 if (record->flags & HAMMER_RECF_CONVERT_DELETE) {
1120                         KKASSERT(record->type == HAMMER_MEM_RECORD_ADD);
1121                         record->flags &= ~HAMMER_RECF_DELETED_FE;
1122                         record->type = HAMMER_MEM_RECORD_DEL;
1123                         KKASSERT(record->flush_state == HAMMER_FST_FLUSH);
1124                         record->flags &= ~HAMMER_RECF_CONVERT_DELETE;
1125                         /* hammer_flush_record_done takes care of the rest */
1126                 } else {
1127                         record->flags |= HAMMER_RECF_DELETED_FE;
1128                         record->flags |= HAMMER_RECF_DELETED_BE;
1129                 }
1130         } else {
1131                 if (record->leaf.data_offset) {
1132                         hammer_blockmap_free(trans, record->leaf.data_offset,
1133                                              record->leaf.data_len);
1134                 }
1135         }
1136
1137 done:
1138         return(error);
1139 }
1140
1141 /*
1142  * Add the record to the inode's rec_tree.  The low 32 bits of a directory
1143  * entry's key is used to deal with hash collisions in the upper 32 bits.
1144  * A unique 64 bit key is generated in-memory and may be regenerated a
1145  * second time when the directory record is flushed to the on-disk B-Tree.
1146  *
1147  * A referenced record is passed to this function.  This function
1148  * eats the reference.  If an error occurs the record will be deleted.
1149  *
1150  * A copy of the temporary record->data pointer provided by the caller
1151  * will be made.
1152  */
1153 static
1154 int
1155 hammer_mem_add(hammer_record_t record)
1156 {
1157         hammer_mount_t hmp = record->ip->hmp;
1158
1159         /*
1160          * Make a private copy of record->data
1161          */
1162         if (record->data)
1163                 KKASSERT(record->flags & HAMMER_RECF_ALLOCDATA);
1164
1165         /*
1166          * Insert into the RB tree, find an unused iterator if this is
1167          * a directory entry.
1168          */
1169         while (RB_INSERT(hammer_rec_rb_tree, &record->ip->rec_tree, record)) {
1170                 if (record->leaf.base.rec_type != HAMMER_RECTYPE_DIRENTRY){
1171                         record->flags |= HAMMER_RECF_DELETED_FE;
1172                         hammer_rel_mem_record(record);
1173                         return (EEXIST);
1174                 }
1175                 if (++hmp->namekey_iterator == 0)
1176                         ++hmp->namekey_iterator;
1177                 record->leaf.base.key &= ~(0xFFFFFFFFLL);
1178                 record->leaf.base.key |= hmp->namekey_iterator;
1179         }
1180         ++hmp->count_newrecords;
1181         ++hmp->rsv_recs;
1182         ++record->ip->rsv_recs;
1183         record->ip->hmp->rsv_databytes += record->leaf.data_len;
1184         record->flags |= HAMMER_RECF_ONRBTREE;
1185         hammer_modify_inode(record->ip, HAMMER_INODE_XDIRTY);
1186         hammer_rel_mem_record(record);
1187         return(0);
1188 }
1189
1190 /************************************************************************
1191  *                   HAMMER INODE MERGED-RECORD FUNCTIONS               *
1192  ************************************************************************
1193  *
1194  * These functions augment the B-Tree scanning functions in hammer_btree.c
1195  * by merging in-memory records with on-disk records.
1196  */
1197
1198 /*
1199  * Locate a particular record either in-memory or on-disk.
1200  *
1201  * NOTE: This is basically a standalone routine, hammer_ip_next() may
1202  * NOT be called to iterate results.
1203  */
1204 int
1205 hammer_ip_lookup(hammer_cursor_t cursor)
1206 {
1207         int error;
1208
1209         /*
1210          * If the element is in-memory return it without searching the
1211          * on-disk B-Tree
1212          */
1213         KKASSERT(cursor->ip);
1214         error = hammer_mem_lookup(cursor);
1215         if (error == 0) {
1216                 cursor->leaf = &cursor->iprec->leaf;
1217                 return(error);
1218         }
1219         if (error != ENOENT)
1220                 return(error);
1221
1222         /*
1223          * If the inode has on-disk components search the on-disk B-Tree.
1224          */
1225         if ((cursor->ip->flags & (HAMMER_INODE_ONDISK|HAMMER_INODE_DONDISK)) == 0)
1226                 return(error);
1227         error = hammer_btree_lookup(cursor);
1228         if (error == 0)
1229                 error = hammer_btree_extract(cursor, HAMMER_CURSOR_GET_LEAF);
1230         return(error);
1231 }
1232
1233 /*
1234  * Locate the first record within the cursor's key_beg/key_end range,
1235  * restricted to a particular inode.  0 is returned on success, ENOENT
1236  * if no records matched the requested range, or some other error.
1237  *
1238  * When 0 is returned hammer_ip_next() may be used to iterate additional
1239  * records within the requested range.
1240  *
1241  * This function can return EDEADLK, requiring the caller to terminate
1242  * the cursor and try again.
1243  */
1244 int
1245 hammer_ip_first(hammer_cursor_t cursor)
1246 {
1247         hammer_inode_t ip = cursor->ip;
1248         int error;
1249
1250         KKASSERT(ip != NULL);
1251
1252         /*
1253          * Clean up fields and setup for merged scan
1254          */
1255         cursor->flags &= ~HAMMER_CURSOR_DELBTREE;
1256         cursor->flags |= HAMMER_CURSOR_ATEDISK | HAMMER_CURSOR_ATEMEM;
1257         cursor->flags |= HAMMER_CURSOR_DISKEOF | HAMMER_CURSOR_MEMEOF;
1258         if (cursor->iprec) {
1259                 hammer_rel_mem_record(cursor->iprec);
1260                 cursor->iprec = NULL;
1261         }
1262
1263         /*
1264          * Search the on-disk B-Tree.  hammer_btree_lookup() only does an
1265          * exact lookup so if we get ENOENT we have to call the iterate
1266          * function to validate the first record after the begin key.
1267          *
1268          * The ATEDISK flag is used by hammer_btree_iterate to determine
1269          * whether it must index forwards or not.  It is also used here
1270          * to select the next record from in-memory or on-disk.
1271          *
1272          * EDEADLK can only occur if the lookup hit an empty internal
1273          * element and couldn't delete it.  Since this could only occur
1274          * in-range, we can just iterate from the failure point.
1275          */
1276         if (ip->flags & (HAMMER_INODE_ONDISK|HAMMER_INODE_DONDISK)) {
1277                 error = hammer_btree_lookup(cursor);
1278                 if (error == ENOENT || error == EDEADLK) {
1279                         cursor->flags &= ~HAMMER_CURSOR_ATEDISK;
1280                         if (hammer_debug_general & 0x2000)
1281                                 kprintf("error %d node %p %016llx index %d\n", error, cursor->node, cursor->node->node_offset, cursor->index);
1282                         error = hammer_btree_iterate(cursor);
1283                 }
1284                 if (error && error != ENOENT) 
1285                         return(error);
1286                 if (error == 0) {
1287                         cursor->flags &= ~HAMMER_CURSOR_DISKEOF;
1288                         cursor->flags &= ~HAMMER_CURSOR_ATEDISK;
1289                 } else {
1290                         cursor->flags |= HAMMER_CURSOR_ATEDISK;
1291                 }
1292         }
1293
1294         /*
1295          * Search the in-memory record list (Red-Black tree).  Unlike the
1296          * B-Tree search, mem_first checks for records in the range.
1297          */
1298         error = hammer_mem_first(cursor);
1299         if (error && error != ENOENT)
1300                 return(error);
1301         if (error == 0) {
1302                 cursor->flags &= ~HAMMER_CURSOR_MEMEOF;
1303                 cursor->flags &= ~HAMMER_CURSOR_ATEMEM;
1304                 if (hammer_ip_iterate_mem_good(cursor, cursor->iprec) == 0)
1305                         cursor->flags |= HAMMER_CURSOR_ATEMEM;
1306         }
1307
1308         /*
1309          * This will return the first matching record.
1310          */
1311         return(hammer_ip_next(cursor));
1312 }
1313
1314 /*
1315  * Retrieve the next record in a merged iteration within the bounds of the
1316  * cursor.  This call may be made multiple times after the cursor has been
1317  * initially searched with hammer_ip_first().
1318  *
1319  * 0 is returned on success, ENOENT if no further records match the
1320  * requested range, or some other error code is returned.
1321  */
1322 int
1323 hammer_ip_next(hammer_cursor_t cursor)
1324 {
1325         hammer_btree_elm_t elm;
1326         hammer_record_t rec, save;
1327         int error;
1328         int r;
1329
1330 next_btree:
1331         /*
1332          * Load the current on-disk and in-memory record.  If we ate any
1333          * records we have to get the next one. 
1334          *
1335          * If we deleted the last on-disk record we had scanned ATEDISK will
1336          * be clear and DELBTREE will be set, forcing a call to iterate. The
1337          * fact that ATEDISK is clear causes iterate to re-test the 'current'
1338          * element.  If ATEDISK is set, iterate will skip the 'current'
1339          * element.
1340          *
1341          * Get the next on-disk record
1342          */
1343         if (cursor->flags & (HAMMER_CURSOR_ATEDISK|HAMMER_CURSOR_DELBTREE)) {
1344                 if ((cursor->flags & HAMMER_CURSOR_DISKEOF) == 0) {
1345                         error = hammer_btree_iterate(cursor);
1346                         cursor->flags &= ~HAMMER_CURSOR_DELBTREE;
1347                         if (error == 0) {
1348                                 cursor->flags &= ~HAMMER_CURSOR_ATEDISK;
1349                                 hammer_cache_node(&cursor->ip->cache[1],
1350                                                   cursor->node);
1351                         } else {
1352                                 cursor->flags |= HAMMER_CURSOR_DISKEOF |
1353                                                  HAMMER_CURSOR_ATEDISK;
1354                         }
1355                 }
1356         }
1357
1358 next_memory:
1359         /*
1360          * Get the next in-memory record.  The record can be ripped out
1361          * of the RB tree so we maintain a scan_info structure to track
1362          * the next node.
1363          *
1364          * hammer_rec_scan_cmp:  Is the record still in our general range,
1365          *                       (non-inclusive of snapshot exclusions)?
1366          * hammer_rec_scan_callback: Is the record in our snapshot?
1367          */
1368         if (cursor->flags & HAMMER_CURSOR_ATEMEM) {
1369                 if ((cursor->flags & HAMMER_CURSOR_MEMEOF) == 0) {
1370                         save = cursor->iprec;
1371                         cursor->iprec = NULL;
1372                         rec = save ? hammer_rec_rb_tree_RB_NEXT(save) : NULL;
1373                         while (rec) {
1374                                 if (hammer_rec_scan_cmp(rec, cursor) != 0)
1375                                         break;
1376                                 if (hammer_rec_scan_callback(rec, cursor) != 0)
1377                                         break;
1378                                 rec = hammer_rec_rb_tree_RB_NEXT(rec);
1379                         }
1380                         if (save)
1381                                 hammer_rel_mem_record(save);
1382                         if (cursor->iprec) {
1383                                 KKASSERT(cursor->iprec == rec);
1384                                 cursor->flags &= ~HAMMER_CURSOR_ATEMEM;
1385                         } else {
1386                                 cursor->flags |= HAMMER_CURSOR_MEMEOF;
1387                         }
1388                 }
1389         }
1390
1391         /*
1392          * The memory record may have become stale while being held in
1393          * cursor->iprec.  We are interlocked against the backend on 
1394          * with regards to B-Tree entries.
1395          */
1396         if ((cursor->flags & HAMMER_CURSOR_ATEMEM) == 0) {
1397                 if (hammer_ip_iterate_mem_good(cursor, cursor->iprec) == 0) {
1398                         cursor->flags |= HAMMER_CURSOR_ATEMEM;
1399                         goto next_memory;
1400                 }
1401         }
1402
1403         /*
1404          * Extract either the disk or memory record depending on their
1405          * relative position.
1406          */
1407         error = 0;
1408         switch(cursor->flags & (HAMMER_CURSOR_ATEDISK | HAMMER_CURSOR_ATEMEM)) {
1409         case 0:
1410                 /*
1411                  * Both entries valid.   Compare the entries and nominally
1412                  * return the first one in the sort order.  Numerous cases
1413                  * require special attention, however.
1414                  */
1415                 elm = &cursor->node->ondisk->elms[cursor->index];
1416                 r = hammer_btree_cmp(&elm->base, &cursor->iprec->leaf.base);
1417
1418                 /*
1419                  * If the two entries differ only by their key (-2/2) or
1420                  * create_tid (-1/1), and are DATA records, we may have a
1421                  * nominal match.  We have to calculate the base file
1422                  * offset of the data.
1423                  */
1424                 if (r <= 2 && r >= -2 && r != 0 &&
1425                     cursor->ip->ino_data.obj_type == HAMMER_OBJTYPE_REGFILE &&
1426                     cursor->iprec->type == HAMMER_MEM_RECORD_DATA) {
1427                         int64_t base1 = elm->leaf.base.key - elm->leaf.data_len;
1428                         int64_t base2 = cursor->iprec->leaf.base.key -
1429                                         cursor->iprec->leaf.data_len;
1430                         if (base1 == base2)
1431                                 r = 0;
1432                 }
1433
1434                 if (r < 0) {
1435                         error = hammer_btree_extract(cursor,
1436                                                      HAMMER_CURSOR_GET_LEAF);
1437                         cursor->flags |= HAMMER_CURSOR_ATEDISK;
1438                         break;
1439                 }
1440
1441                 /*
1442                  * If the entries match exactly the memory entry is either
1443                  * an on-disk directory entry deletion or a bulk data
1444                  * overwrite.  If it is a directory entry deletion we eat
1445                  * both entries.
1446                  *
1447                  * For the bulk-data overwrite case it is possible to have
1448                  * visibility into both, which simply means the syncer
1449                  * hasn't gotten around to doing the delete+insert sequence
1450                  * on the B-Tree.  Use the memory entry and throw away the
1451                  * on-disk entry.
1452                  *
1453                  * If the in-memory record is not either of these we
1454                  * probably caught the syncer while it was syncing it to
1455                  * the media.  Since we hold a shared lock on the cursor,
1456                  * the in-memory record had better be marked deleted at
1457                  * this point.
1458                  */
1459                 if (r == 0) {
1460                         if (cursor->iprec->type == HAMMER_MEM_RECORD_DEL) {
1461                                 if ((cursor->flags & HAMMER_CURSOR_DELETE_VISIBILITY) == 0) {
1462                                         cursor->flags |= HAMMER_CURSOR_ATEDISK;
1463                                         cursor->flags |= HAMMER_CURSOR_ATEMEM;
1464                                         goto next_btree;
1465                                 }
1466                         } else if (cursor->iprec->type == HAMMER_MEM_RECORD_DATA) {
1467                                 if ((cursor->flags & HAMMER_CURSOR_DELETE_VISIBILITY) == 0) {
1468                                         cursor->flags |= HAMMER_CURSOR_ATEDISK;
1469                                 }
1470                                 /* fall through to memory entry */
1471                         } else {
1472                                 panic("hammer_ip_next: duplicate mem/b-tree entry");
1473                                 cursor->flags |= HAMMER_CURSOR_ATEMEM;
1474                                 goto next_memory;
1475                         }
1476                 }
1477                 /* fall through to the memory entry */
1478         case HAMMER_CURSOR_ATEDISK:
1479                 /*
1480                  * Only the memory entry is valid.
1481                  */
1482                 cursor->leaf = &cursor->iprec->leaf;
1483                 cursor->flags |= HAMMER_CURSOR_ATEMEM;
1484
1485                 /*
1486                  * If the memory entry is an on-disk deletion we should have
1487                  * also had found a B-Tree record.  If the backend beat us
1488                  * to it it would have interlocked the cursor and we should
1489                  * have seen the in-memory record marked DELETED_FE.
1490                  */
1491                 if (cursor->iprec->type == HAMMER_MEM_RECORD_DEL &&
1492                     (cursor->flags & HAMMER_CURSOR_DELETE_VISIBILITY) == 0) {
1493                         panic("hammer_ip_next: del-on-disk with no b-tree entry");
1494                 }
1495                 break;
1496         case HAMMER_CURSOR_ATEMEM:
1497                 /*
1498                  * Only the disk entry is valid
1499                  */
1500                 error = hammer_btree_extract(cursor, HAMMER_CURSOR_GET_LEAF);
1501                 cursor->flags |= HAMMER_CURSOR_ATEDISK;
1502                 break;
1503         default:
1504                 /*
1505                  * Neither entry is valid
1506                  *
1507                  * XXX error not set properly
1508                  */
1509                 cursor->leaf = NULL;
1510                 error = ENOENT;
1511                 break;
1512         }
1513         return(error);
1514 }
1515
1516 /*
1517  * Resolve the cursor->data pointer for the current cursor position in
1518  * a merged iteration.
1519  */
1520 int
1521 hammer_ip_resolve_data(hammer_cursor_t cursor)
1522 {
1523         hammer_record_t record;
1524         int error;
1525
1526         if (hammer_cursor_inmem(cursor)) {
1527                 /*
1528                  * The data associated with an in-memory record is usually
1529                  * kmalloced, but reserve-ahead data records will have an
1530                  * on-disk reference.
1531                  *
1532                  * NOTE: Reserve-ahead data records must be handled in the
1533                  * context of the related high level buffer cache buffer
1534                  * to interlock against async writes.
1535                  */
1536                 record = cursor->iprec;
1537                 cursor->data = record->data;
1538                 error = 0;
1539                 if (cursor->data == NULL) {
1540                         KKASSERT(record->leaf.base.rec_type ==
1541                                  HAMMER_RECTYPE_DATA);
1542                         cursor->data = hammer_bread_ext(cursor->trans->hmp,
1543                                                     record->leaf.data_offset,
1544                                                     record->leaf.data_len,
1545                                                     &error,
1546                                                     &cursor->data_buffer);
1547                 }
1548         } else {
1549                 cursor->leaf = &cursor->node->ondisk->elms[cursor->index].leaf;
1550                 error = hammer_btree_extract(cursor, HAMMER_CURSOR_GET_DATA);
1551         }
1552         return(error);
1553 }
1554
1555 /*
1556  * Backend truncation / record replacement - delete records in range.
1557  *
1558  * Delete all records within the specified range for inode ip.  In-memory
1559  * records still associated with the frontend are ignored.
1560  *
1561  * NOTE: An unaligned range will cause new records to be added to cover
1562  * the edge cases. (XXX not implemented yet).
1563  *
1564  * NOTE: Replacement via reservations (see hammer_ip_sync_record_cursor())
1565  * also do not deal with unaligned ranges.
1566  *
1567  * NOTE: ran_end is inclusive (e.g. 0,1023 instead of 0,1024).
1568  *
1569  * NOTE: Record keys for regular file data have to be special-cased since
1570  * they indicate the end of the range (key = base + bytes).
1571  */
1572 int
1573 hammer_ip_delete_range(hammer_cursor_t cursor, hammer_inode_t ip,
1574                        int64_t ran_beg, int64_t ran_end, int truncating)
1575 {
1576         hammer_transaction_t trans = cursor->trans;
1577         hammer_btree_leaf_elm_t leaf;
1578         int error;
1579         int64_t off;
1580
1581 #if 0
1582         kprintf("delete_range %p %016llx-%016llx\n", ip, ran_beg, ran_end);
1583 #endif
1584
1585         KKASSERT(trans->type == HAMMER_TRANS_FLS);
1586 retry:
1587         hammer_normalize_cursor(cursor);
1588         cursor->key_beg.localization = HAMMER_LOCALIZE_MISC;
1589         cursor->key_beg.obj_id = ip->obj_id;
1590         cursor->key_beg.create_tid = 0;
1591         cursor->key_beg.delete_tid = 0;
1592         cursor->key_beg.obj_type = 0;
1593         cursor->asof = ip->obj_asof;
1594         cursor->flags &= ~HAMMER_CURSOR_INITMASK;
1595         cursor->flags |= HAMMER_CURSOR_ASOF;
1596         cursor->flags |= HAMMER_CURSOR_DELETE_VISIBILITY;
1597         cursor->flags |= HAMMER_CURSOR_BACKEND;
1598
1599         cursor->key_end = cursor->key_beg;
1600         if (ip->ino_data.obj_type == HAMMER_OBJTYPE_DBFILE) {
1601                 cursor->key_beg.key = ran_beg;
1602                 cursor->key_beg.rec_type = HAMMER_RECTYPE_DB;
1603                 cursor->key_end.rec_type = HAMMER_RECTYPE_DB;
1604                 cursor->key_end.key = ran_end;
1605         } else {
1606                 /*
1607                  * The key in the B-Tree is (base+bytes), so the first possible
1608                  * matching key is ran_beg + 1.
1609                  */
1610                 int64_t tmp64;
1611
1612                 cursor->key_beg.key = ran_beg + 1;
1613                 cursor->key_beg.rec_type = HAMMER_RECTYPE_DATA;
1614                 cursor->key_end.rec_type = HAMMER_RECTYPE_DATA;
1615
1616                 tmp64 = ran_end + MAXPHYS + 1;  /* work around GCC-4 bug */
1617                 if (tmp64 < ran_end)
1618                         cursor->key_end.key = 0x7FFFFFFFFFFFFFFFLL;
1619                 else
1620                         cursor->key_end.key = ran_end + MAXPHYS + 1;
1621         }
1622         cursor->flags |= HAMMER_CURSOR_END_INCLUSIVE;
1623
1624         error = hammer_ip_first(cursor);
1625
1626         /*
1627          * Iterate through matching records and mark them as deleted.
1628          */
1629         while (error == 0) {
1630                 leaf = cursor->leaf;
1631
1632                 KKASSERT(leaf->base.delete_tid == 0);
1633
1634                 /*
1635                  * There may be overlap cases for regular file data.  Also
1636                  * remember the key for a regular file record is (base + len),
1637                  * NOT (base).
1638                  */
1639                 if (leaf->base.rec_type == HAMMER_RECTYPE_DATA) {
1640                         off = leaf->base.key - leaf->data_len;
1641                         /*
1642                          * Check the left edge case.  We currently do not
1643                          * split existing records.
1644                          */
1645                         if (off < ran_beg) {
1646                                 panic("hammer left edge case %016llx %d\n",
1647                                         leaf->base.key, leaf->data_len);
1648                         }
1649
1650                         /*
1651                          * Check the right edge case.  Note that the
1652                          * record can be completely out of bounds, which
1653                          * terminates the search.
1654                          *
1655                          * base->key is exclusive of the right edge while
1656                          * ran_end is inclusive of the right edge.  The
1657                          * (key - data_len) left boundary is inclusive.
1658                          *
1659                          * XXX theory-check this test at some point, are
1660                          * we missing a + 1 somewhere?  Note that ran_end
1661                          * could overflow.
1662                          */
1663                         if (leaf->base.key - 1 > ran_end) {
1664                                 if (leaf->base.key - leaf->data_len > ran_end)
1665                                         break;
1666                                 panic("hammer right edge case\n");
1667                         }
1668                 }
1669
1670                 /*
1671                  * Delete the record.  When truncating we do not delete
1672                  * in-memory (data) records because they represent data
1673                  * written after the truncation.
1674                  *
1675                  * This will also physically destroy the B-Tree entry and
1676                  * data if the retention policy dictates.  The function
1677                  * will set HAMMER_CURSOR_DELBTREE which hammer_ip_next()
1678                  * uses to perform a fixup.
1679                  */
1680                 if (truncating == 0 || hammer_cursor_ondisk(cursor))
1681                         error = hammer_ip_delete_record(cursor, ip, trans->tid);
1682                 if (error)
1683                         break;
1684                 error = hammer_ip_next(cursor);
1685         }
1686         if (cursor->node)
1687                 hammer_cache_node(&ip->cache[1], cursor->node);
1688
1689         if (error == EDEADLK) {
1690                 hammer_done_cursor(cursor);
1691                 error = hammer_init_cursor(trans, cursor, &ip->cache[1], ip);
1692                 if (error == 0)
1693                         goto retry;
1694         }
1695         if (error == ENOENT)
1696                 error = 0;
1697         return(error);
1698 }
1699
1700 /*
1701  * Backend truncation - delete all records.
1702  *
1703  * Delete all user records associated with an inode except the inode record
1704  * itself.  Directory entries are not deleted (they must be properly disposed
1705  * of or nlinks would get upset).
1706  */
1707 int
1708 hammer_ip_delete_range_all(hammer_cursor_t cursor, hammer_inode_t ip,
1709                            int *countp)
1710 {
1711         hammer_transaction_t trans = cursor->trans;
1712         hammer_btree_leaf_elm_t leaf;
1713         int error;
1714
1715         KKASSERT(trans->type == HAMMER_TRANS_FLS);
1716 retry:
1717         hammer_normalize_cursor(cursor);
1718         cursor->key_beg.localization = HAMMER_LOCALIZE_MISC;
1719         cursor->key_beg.obj_id = ip->obj_id;
1720         cursor->key_beg.create_tid = 0;
1721         cursor->key_beg.delete_tid = 0;
1722         cursor->key_beg.obj_type = 0;
1723         cursor->key_beg.rec_type = HAMMER_RECTYPE_INODE + 1;
1724         cursor->key_beg.key = HAMMER_MIN_KEY;
1725
1726         cursor->key_end = cursor->key_beg;
1727         cursor->key_end.rec_type = 0xFFFF;
1728         cursor->key_end.key = HAMMER_MAX_KEY;
1729
1730         cursor->asof = ip->obj_asof;
1731         cursor->flags &= ~HAMMER_CURSOR_INITMASK;
1732         cursor->flags |= HAMMER_CURSOR_END_INCLUSIVE | HAMMER_CURSOR_ASOF;
1733         cursor->flags |= HAMMER_CURSOR_DELETE_VISIBILITY;
1734         cursor->flags |= HAMMER_CURSOR_BACKEND;
1735
1736         error = hammer_ip_first(cursor);
1737
1738         /*
1739          * Iterate through matching records and mark them as deleted.
1740          */
1741         while (error == 0) {
1742                 leaf = cursor->leaf;
1743
1744                 KKASSERT(leaf->base.delete_tid == 0);
1745
1746                 /*
1747                  * Mark the record and B-Tree entry as deleted.  This will
1748                  * also physically delete the B-Tree entry, record, and
1749                  * data if the retention policy dictates.  The function
1750                  * will set HAMMER_CURSOR_DELBTREE which hammer_ip_next()
1751                  * uses to perform a fixup.
1752                  *
1753                  * Directory entries (and delete-on-disk directory entries)
1754                  * must be synced and cannot be deleted.
1755                  */
1756                 if (leaf->base.rec_type != HAMMER_RECTYPE_DIRENTRY) {
1757                         error = hammer_ip_delete_record(cursor, ip, trans->tid);
1758                         ++*countp;
1759                 }
1760                 if (error)
1761                         break;
1762                 error = hammer_ip_next(cursor);
1763         }
1764         if (cursor->node)
1765                 hammer_cache_node(&ip->cache[1], cursor->node);
1766         if (error == EDEADLK) {
1767                 hammer_done_cursor(cursor);
1768                 error = hammer_init_cursor(trans, cursor, &ip->cache[1], ip);
1769                 if (error == 0)
1770                         goto retry;
1771         }
1772         if (error == ENOENT)
1773                 error = 0;
1774         return(error);
1775 }
1776
1777 /*
1778  * Delete the record at the current cursor.  On success the cursor will
1779  * be positioned appropriately for an iteration but may no longer be at
1780  * a leaf node.
1781  *
1782  * This routine is only called from the backend.
1783  *
1784  * NOTE: This can return EDEADLK, requiring the caller to terminate the
1785  * cursor and retry.
1786  */
1787 int
1788 hammer_ip_delete_record(hammer_cursor_t cursor, hammer_inode_t ip,
1789                         hammer_tid_t tid)
1790 {
1791         hammer_off_t zone2_offset;
1792         hammer_record_t iprec;
1793         hammer_btree_elm_t elm;
1794         hammer_mount_t hmp;
1795         int error;
1796         int dodelete;
1797
1798         KKASSERT(cursor->flags & HAMMER_CURSOR_BACKEND);
1799         KKASSERT(tid != 0);
1800         hmp = cursor->node->hmp;
1801
1802         /*
1803          * In-memory (unsynchronized) records can simply be freed.  This
1804          * only occurs in range iterations since all other records are
1805          * individually synchronized.  Thus there should be no confusion with
1806          * the interlock.
1807          *
1808          * An in-memory record may be deleted before being committed to disk,
1809          * but could have been accessed in the mean time.  The backing store
1810          * may never been marked allocated and so hammer_blockmap_free() may
1811          * never get called on it.  Because of this we have to make sure that
1812          * we've gotten rid of any related hammer_buffer or buffer cache
1813          * buffer.
1814          */
1815         if (hammer_cursor_inmem(cursor)) {
1816                 iprec = cursor->iprec;
1817                 KKASSERT((iprec->flags & HAMMER_RECF_INTERLOCK_BE) ==0);
1818                 iprec->flags |= HAMMER_RECF_DELETED_FE;
1819                 iprec->flags |= HAMMER_RECF_DELETED_BE;
1820
1821                 if (iprec->leaf.data_offset && iprec->leaf.data_len) {
1822                         zone2_offset = hammer_blockmap_lookup(hmp, iprec->leaf.data_offset, &error);
1823                         KKASSERT(error == 0);
1824                         hammer_del_buffers(hmp,
1825                                            iprec->leaf.data_offset,
1826                                            zone2_offset,
1827                                            iprec->leaf.data_len);
1828                 }
1829                 return(0);
1830         }
1831
1832         /*
1833          * On-disk records are marked as deleted by updating their delete_tid.
1834          * This does not effect their position in the B-Tree (which is based
1835          * on their create_tid).
1836          */
1837         error = hammer_btree_extract(cursor, HAMMER_CURSOR_GET_LEAF);
1838         elm = NULL;
1839
1840         /*
1841          * If we were mounted with the nohistory option, we physically
1842          * delete the record.
1843          */
1844         dodelete = hammer_nohistory(ip);
1845
1846         if (error == 0) {
1847                 error = hammer_cursor_upgrade(cursor);
1848                 if (error == 0) {
1849                         elm = &cursor->node->ondisk->elms[cursor->index];
1850                         hammer_modify_node(cursor->trans, cursor->node,
1851                                            &elm->leaf.base.delete_tid,
1852                                            sizeof(elm->leaf.base.delete_tid));
1853                         elm->leaf.base.delete_tid = tid;
1854                         hammer_modify_node_done(cursor->node);
1855
1856                         /*
1857                          * An on-disk record cannot have the same delete_tid
1858                          * as its create_tid.  In a chain of record updates
1859                          * this could result in a duplicate record.
1860                          */
1861                         KKASSERT(elm->leaf.base.delete_tid != elm->leaf.base.create_tid);
1862                 }
1863         }
1864
1865         if (error == 0 && dodelete) {
1866                 error = hammer_delete_at_cursor(cursor, NULL);
1867                 if (error) {
1868                         panic("hammer_ip_delete_record: unable to physically delete the record!\n");
1869                         error = 0;
1870                 }
1871         }
1872         return(error);
1873 }
1874
1875 int
1876 hammer_delete_at_cursor(hammer_cursor_t cursor, int64_t *stat_bytes)
1877 {
1878         hammer_btree_elm_t elm;
1879         hammer_off_t data_offset;
1880         int32_t data_len;
1881         u_int16_t rec_type;
1882         int error;
1883
1884         elm = &cursor->node->ondisk->elms[cursor->index];
1885         KKASSERT(elm->base.btype == HAMMER_BTREE_TYPE_RECORD);
1886
1887         data_offset = elm->leaf.data_offset;
1888         data_len = elm->leaf.data_len;
1889         rec_type = elm->leaf.base.rec_type;
1890
1891         error = hammer_btree_delete(cursor);
1892         if (error == 0) {
1893                 /*
1894                  * This forces a fixup for the iteration because
1895                  * the cursor is now either sitting at the 'next'
1896                  * element or sitting at the end of a leaf.
1897                  */
1898                 if ((cursor->flags & HAMMER_CURSOR_DISKEOF) == 0) {
1899                         cursor->flags |= HAMMER_CURSOR_DELBTREE;
1900                         cursor->flags &= ~HAMMER_CURSOR_ATEDISK;
1901                 }
1902         }
1903         if (error == 0) {
1904                 switch(data_offset & HAMMER_OFF_ZONE_MASK) {
1905                 case HAMMER_ZONE_LARGE_DATA:
1906                 case HAMMER_ZONE_SMALL_DATA:
1907                 case HAMMER_ZONE_META:
1908                         hammer_blockmap_free(cursor->trans,
1909                                              data_offset, data_len);
1910                         break;
1911                 default:
1912                         break;
1913                 }
1914         }
1915         return (error);
1916 }
1917
1918 /*
1919  * Determine whether we can remove a directory.  This routine checks whether
1920  * a directory is empty or not and enforces flush connectivity.
1921  *
1922  * Flush connectivity requires that we block if the target directory is
1923  * currently flushing, otherwise it may not end up in the same flush group.
1924  *
1925  * Returns 0 on success, ENOTEMPTY or EDEADLK (or other errors) on failure.
1926  */
1927 int
1928 hammer_ip_check_directory_empty(hammer_transaction_t trans, hammer_inode_t ip)
1929 {
1930         struct hammer_cursor cursor;
1931         int error;
1932
1933         /*
1934          * Check directory empty
1935          */
1936         hammer_init_cursor(trans, &cursor, &ip->cache[1], ip);
1937
1938         cursor.key_beg.localization = HAMMER_LOCALIZE_MISC;
1939         cursor.key_beg.obj_id = ip->obj_id;
1940         cursor.key_beg.create_tid = 0;
1941         cursor.key_beg.delete_tid = 0;
1942         cursor.key_beg.obj_type = 0;
1943         cursor.key_beg.rec_type = HAMMER_RECTYPE_INODE + 1;
1944         cursor.key_beg.key = HAMMER_MIN_KEY;
1945
1946         cursor.key_end = cursor.key_beg;
1947         cursor.key_end.rec_type = 0xFFFF;
1948         cursor.key_end.key = HAMMER_MAX_KEY;
1949
1950         cursor.asof = ip->obj_asof;
1951         cursor.flags |= HAMMER_CURSOR_END_INCLUSIVE | HAMMER_CURSOR_ASOF;
1952
1953         error = hammer_ip_first(&cursor);
1954         if (error == ENOENT)
1955                 error = 0;
1956         else if (error == 0)
1957                 error = ENOTEMPTY;
1958         hammer_done_cursor(&cursor);
1959         return(error);
1960 }
1961