hammer: Change u_int{8,16,32,64}_t to uint{8,16,32,64}_t
[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
35 #include "hammer.h"
36
37 static int hammer_mem_lookup(hammer_cursor_t cursor);
38 static int hammer_mem_first(hammer_cursor_t cursor);
39 static int hammer_frontend_trunc_callback(hammer_record_t record,
40                                 void *data __unused);
41 static int hammer_bulk_scan_callback(hammer_record_t record, void *data);
42 static int hammer_record_needs_overwrite_delete(hammer_record_t record);
43 static int hammer_delete_general(hammer_cursor_t cursor, hammer_inode_t ip,
44                                 hammer_btree_leaf_elm_t leaf);
45 static int hammer_cursor_localize_data(hammer_data_ondisk_t data,
46                                 hammer_btree_leaf_elm_t leaf);
47
48 struct rec_trunc_info {
49         uint16_t        rec_type;
50         int64_t         trunc_off;
51 };
52
53 struct hammer_bulk_info {
54         hammer_record_t record;
55         hammer_record_t conflict;
56 };
57
58 /*
59  * Red-black tree support.  Comparison code for insertion.
60  */
61 static int
62 hammer_rec_rb_compare(hammer_record_t rec1, hammer_record_t rec2)
63 {
64         if (rec1->leaf.base.rec_type < rec2->leaf.base.rec_type)
65                 return(-1);
66         if (rec1->leaf.base.rec_type > rec2->leaf.base.rec_type)
67                 return(1);
68
69         if (rec1->leaf.base.key < rec2->leaf.base.key)
70                 return(-1);
71         if (rec1->leaf.base.key > rec2->leaf.base.key)
72                 return(1);
73
74         /*
75          * For search & insertion purposes records deleted by the
76          * frontend or deleted/committed by the backend are silently
77          * ignored.  Otherwise pipelined insertions will get messed
78          * up.
79          *
80          * rec1 is greater then rec2 if rec1 is marked deleted.
81          * rec1 is less then rec2 if rec2 is marked deleted.
82          *
83          * Multiple deleted records may be present, do not return 0
84          * if both are marked deleted.
85          */
86         if (rec1->flags & (HAMMER_RECF_DELETED_FE | HAMMER_RECF_DELETED_BE |
87                            HAMMER_RECF_COMMITTED)) {
88                 return(1);
89         }
90         if (rec2->flags & (HAMMER_RECF_DELETED_FE | HAMMER_RECF_DELETED_BE |
91                            HAMMER_RECF_COMMITTED)) {
92                 return(-1);
93         }
94
95         return(0);
96 }
97
98 /*
99  * Basic record comparison code similar to hammer_btree_cmp().
100  *
101  * obj_id is not compared and may not yet be assigned in the record.
102  */
103 static int
104 hammer_rec_cmp(hammer_base_elm_t elm, hammer_record_t rec)
105 {
106         if (elm->rec_type < rec->leaf.base.rec_type)
107                 return(-3);
108         if (elm->rec_type > rec->leaf.base.rec_type)
109                 return(3);
110
111         if (elm->key < rec->leaf.base.key)
112                 return(-2);
113         if (elm->key > rec->leaf.base.key)
114                 return(2);
115
116         /*
117          * Never match against an item deleted by the frontend
118          * or backend, or committed by the backend.
119          *
120          * elm is less then rec if rec is marked deleted.
121          */
122         if (rec->flags & (HAMMER_RECF_DELETED_FE | HAMMER_RECF_DELETED_BE |
123                           HAMMER_RECF_COMMITTED)) {
124                 return(-1);
125         }
126         return(0);
127 }
128
129 /*
130  * Ranged scan to locate overlapping record(s).  This is used by
131  * hammer_ip_get_bulk() to locate an overlapping record.  We have
132  * to use a ranged scan because the keys for data records with the
133  * same file base offset can be different due to differing data_len's.
134  *
135  * NOTE: The base file offset of a data record is (key - data_len), not (key).
136  */
137 static int
138 hammer_rec_overlap_cmp(hammer_record_t rec, void *data)
139 {
140         struct hammer_bulk_info *info = data;
141         hammer_btree_leaf_elm_t leaf = &info->record->leaf;
142
143         if (rec->leaf.base.rec_type < leaf->base.rec_type)
144                 return(-3);
145         if (rec->leaf.base.rec_type > leaf->base.rec_type)
146                 return(3);
147
148         /*
149          * Overlap compare
150          */
151         if (leaf->base.rec_type == HAMMER_RECTYPE_DATA) {
152                 /* rec_beg >= leaf_end */
153                 if (rec->leaf.base.key - rec->leaf.data_len >= leaf->base.key)
154                         return(2);
155                 /* rec_end <= leaf_beg */
156                 if (rec->leaf.base.key <= leaf->base.key - leaf->data_len)
157                         return(-2);
158         } else {
159                 if (rec->leaf.base.key < leaf->base.key)
160                         return(-2);
161                 if (rec->leaf.base.key > leaf->base.key)
162                         return(2);
163         }
164
165         /*
166          * We have to return 0 at this point, even if DELETED_FE is set,
167          * because returning anything else will cause the scan to ignore
168          * one of the branches when we really want it to check both.
169          */
170         return(0);
171 }
172
173 /*
174  * RB_SCAN comparison code for hammer_mem_first().  The argument order
175  * is reversed so the comparison result has to be negated.  key_beg and
176  * key_end are both range-inclusive.
177  *
178  * Localized deletions are not cached in-memory.
179  */
180 static
181 int
182 hammer_rec_scan_cmp(hammer_record_t rec, void *data)
183 {
184         hammer_cursor_t cursor = data;
185         int r;
186
187         r = hammer_rec_cmp(&cursor->key_beg, rec);
188         if (r > 1)
189                 return(-1);
190         r = hammer_rec_cmp(&cursor->key_end, rec);
191         if (r < -1)
192                 return(1);
193         return(0);
194 }
195
196 /*
197  * This compare function is used when simply looking up key_beg.
198  */
199 static
200 int
201 hammer_rec_find_cmp(hammer_record_t rec, void *data)
202 {
203         hammer_cursor_t cursor = data;
204         int r;
205
206         r = hammer_rec_cmp(&cursor->key_beg, rec);
207         if (r > 1)
208                 return(-1);
209         if (r < -1)
210                 return(1);
211         return(0);
212 }
213
214 /*
215  * Locate blocks within the truncation range.  Partial blocks do not count.
216  */
217 static
218 int
219 hammer_rec_trunc_cmp(hammer_record_t rec, void *data)
220 {
221         struct rec_trunc_info *info = data;
222
223         if (rec->leaf.base.rec_type < info->rec_type)
224                 return(-1);
225         if (rec->leaf.base.rec_type > info->rec_type)
226                 return(1);
227
228         switch(rec->leaf.base.rec_type) {
229         case HAMMER_RECTYPE_DB:
230                 /*
231                  * DB record key is not beyond the truncation point, retain.
232                  */
233                 if (rec->leaf.base.key < info->trunc_off)
234                         return(-1);
235                 break;
236         case HAMMER_RECTYPE_DATA:
237                 /*
238                  * DATA record offset start is not beyond the truncation point,
239                  * retain.
240                  */
241                 if (rec->leaf.base.key - rec->leaf.data_len < info->trunc_off)
242                         return(-1);
243                 break;
244         default:
245                 hpanic("unexpected record type");
246         }
247
248         /*
249          * The record start is >= the truncation point, return match,
250          * the record should be destroyed.
251          */
252         return(0);
253 }
254
255 RB_GENERATE(hammer_rec_rb_tree, hammer_record, rb_node, hammer_rec_rb_compare);
256
257 /*
258  * Allocate a record for the caller to finish filling in.  The record is
259  * returned referenced.  In order to manually set data call this function
260  * with data_len=0 and then manually set record->leaf.data_len and
261  * record->data later.
262  */
263 hammer_record_t
264 hammer_alloc_mem_record(hammer_inode_t ip, int data_len)
265 {
266         hammer_record_t record;
267         hammer_mount_t hmp;
268
269         hmp = ip->hmp;
270         ++hammer_count_records;
271         record = kmalloc(sizeof(*record), hmp->m_misc,
272                          M_WAITOK | M_ZERO | M_USE_RESERVE);
273         record->flush_state = HAMMER_FST_IDLE;
274         record->ip = ip;
275         record->leaf.base.btype = HAMMER_BTREE_TYPE_RECORD;
276         record->leaf.data_len = data_len;
277         hammer_ref(&record->lock);
278
279         if (data_len) {
280                 record->data = kmalloc(data_len, hmp->m_misc, M_WAITOK | M_ZERO);
281                 record->flags |= HAMMER_RECF_ALLOCDATA;
282                 ++hammer_count_record_datas;
283         }
284
285         return (record);
286 }
287
288 void
289 hammer_wait_mem_record_ident(hammer_record_t record, const char *ident)
290 {
291         while (record->flush_state == HAMMER_FST_FLUSH) {
292                 record->flags |= HAMMER_RECF_WANTED;
293                 tsleep(record, 0, ident, 0);
294         }
295 }
296
297 /*
298  * Called from the backend, hammer_inode.c, after a record has been
299  * flushed to disk.  The record has been exclusively locked by the
300  * caller and interlocked with BE.
301  *
302  * We clean up the state, unlock, and release the record (the record
303  * was referenced by the fact that it was in the HAMMER_FST_FLUSH state).
304  */
305 void
306 hammer_flush_record_done(hammer_record_t record, int error)
307 {
308         hammer_inode_t target_ip;
309
310         KKASSERT(record->flush_state == HAMMER_FST_FLUSH);
311         KKASSERT(record->flags & HAMMER_RECF_INTERLOCK_BE);
312
313         /*
314          * If an error occured, the backend was unable to sync the
315          * record to its media.  Leave the record intact.
316          */
317         if (error) {
318                 hammer_critical_error(record->ip->hmp, record->ip, error,
319                                       "while flushing record");
320         }
321
322         --record->flush_group->refs;
323         record->flush_group = NULL;
324
325         /*
326          * Adjust the flush state and dependancy based on success or
327          * failure.
328          */
329         if (record->flags & (HAMMER_RECF_DELETED_BE | HAMMER_RECF_COMMITTED)) {
330                 if ((target_ip = record->target_ip) != NULL) {
331                         TAILQ_REMOVE(&target_ip->target_list, record,
332                                      target_entry);
333                         record->target_ip = NULL;
334                         hammer_test_inode(target_ip);
335                 }
336                 record->flush_state = HAMMER_FST_IDLE;
337         } else {
338                 if (record->target_ip) {
339                         record->flush_state = HAMMER_FST_SETUP;
340                         hammer_test_inode(record->ip);
341                         hammer_test_inode(record->target_ip);
342                 } else {
343                         record->flush_state = HAMMER_FST_IDLE;
344                 }
345         }
346         record->flags &= ~HAMMER_RECF_INTERLOCK_BE;
347
348         /*
349          * Cleanup
350          */
351         if (record->flags & HAMMER_RECF_WANTED) {
352                 record->flags &= ~HAMMER_RECF_WANTED;
353                 wakeup(record);
354         }
355         hammer_rel_mem_record(record);
356 }
357
358 /*
359  * Release a memory record.  Records marked for deletion are immediately
360  * removed from the RB-Tree but otherwise left intact until the last ref
361  * goes away.
362  */
363 void
364 hammer_rel_mem_record(struct hammer_record *record)
365 {
366         hammer_mount_t hmp;
367         hammer_reserve_t resv;
368         hammer_inode_t ip;
369         hammer_inode_t target_ip;
370         int diddrop;
371
372         hammer_rel(&record->lock);
373
374         if (hammer_norefs(&record->lock)) {
375                 /*
376                  * Upon release of the last reference wakeup any waiters.
377                  * The record structure may get destroyed so callers will
378                  * loop up and do a relookup.
379                  *
380                  * WARNING!  Record must be removed from RB-TREE before we
381                  * might possibly block.  hammer_test_inode() can block!
382                  */
383                 ip = record->ip;
384                 hmp = ip->hmp;
385
386                 /*
387                  * Upon release of the last reference a record marked deleted
388                  * by the front or backend, or committed by the backend,
389                  * is destroyed.
390                  */
391                 if (record->flags & (HAMMER_RECF_DELETED_FE |
392                                      HAMMER_RECF_DELETED_BE |
393                                      HAMMER_RECF_COMMITTED)) {
394                         KKASSERT(hammer_isactive(&ip->lock) > 0);
395                         KKASSERT(record->flush_state != HAMMER_FST_FLUSH);
396
397                         /*
398                          * target_ip may have zero refs, we have to ref it
399                          * to prevent it from being ripped out from under
400                          * us.
401                          */
402                         if ((target_ip = record->target_ip) != NULL) {
403                                 TAILQ_REMOVE(&target_ip->target_list,
404                                              record, target_entry);
405                                 record->target_ip = NULL;
406                                 hammer_ref(&target_ip->lock);
407                         }
408
409                         /*
410                          * Remove the record from the RB-Tree
411                          */
412                         if (record->flags & HAMMER_RECF_ONRBTREE) {
413                                 RB_REMOVE(hammer_rec_rb_tree,
414                                           &ip->rec_tree,
415                                           record);
416                                 record->flags &= ~HAMMER_RECF_ONRBTREE;
417                                 KKASSERT(ip->rsv_recs > 0);
418                                 if (RB_EMPTY(&ip->rec_tree)) {
419                                         ip->flags &= ~HAMMER_INODE_XDIRTY;
420                                         ip->sync_flags &= ~HAMMER_INODE_XDIRTY;
421                                 }
422                                 diddrop = 1;
423                         } else {
424                                 diddrop = 0;
425                         }
426
427                         /*
428                          * We must wait for any direct-IO to complete before
429                          * we can destroy the record because the bio may
430                          * have a reference to it.
431                          */
432                         if (record->gflags &
433                            (HAMMER_RECG_DIRECT_IO | HAMMER_RECG_DIRECT_INVAL)) {
434                                 hammer_io_direct_wait(record);
435                         }
436
437                         /*
438                          * Account for the completion after the direct IO
439                          * has completed.
440                          */
441                         if (diddrop) {
442                                 --hmp->rsv_recs;
443                                 --ip->rsv_recs;
444                                 hmp->rsv_databytes -= record->leaf.data_len;
445
446                                 if (RB_EMPTY(&ip->rec_tree))
447                                         hammer_test_inode(ip);
448                                 if ((ip->flags & HAMMER_INODE_RECSW) &&
449                                     ip->rsv_recs <= hammer_limit_inode_recs/2) {
450                                         ip->flags &= ~HAMMER_INODE_RECSW;
451                                         wakeup(&ip->rsv_recs);
452                                 }
453                         }
454
455                         /*
456                          * Do this test after removing record from the RB-Tree.
457                          */
458                         if (target_ip) {
459                                 hammer_test_inode(target_ip);
460                                 hammer_rel_inode(target_ip, 0);
461                         }
462
463                         if (record->flags & HAMMER_RECF_ALLOCDATA) {
464                                 --hammer_count_record_datas;
465                                 kfree(record->data, hmp->m_misc);
466                                 record->flags &= ~HAMMER_RECF_ALLOCDATA;
467                         }
468
469                         /*
470                          * Release the reservation.
471                          *
472                          * If the record was not committed we can theoretically
473                          * undo the reservation.  However, doing so might
474                          * create weird edge cases with the ordering of
475                          * direct writes because the related buffer cache
476                          * elements are per-vnode.  So we don't try.
477                          */
478                         if ((resv = record->resv) != NULL) {
479                                 /* XXX undo leaf.data_offset,leaf.data_len */
480                                 hammer_blockmap_reserve_complete(hmp, resv);
481                                 record->resv = NULL;
482                         }
483                         record->data = NULL;
484                         --hammer_count_records;
485                         kfree(record, hmp->m_misc);
486                 }
487         }
488 }
489
490 /*
491  * Record visibility depends on whether the record is being accessed by
492  * the backend or the frontend.  Backend tests ignore the frontend delete
493  * flag.  Frontend tests do NOT ignore the backend delete/commit flags and
494  * must also check for commit races.
495  *
496  * Return non-zero if the record is visible, zero if it isn't or if it is
497  * deleted.  Returns 0 if the record has been comitted (unless the special
498  * delete-visibility flag is set).  A committed record must be located
499  * via the media B-Tree.  Returns non-zero if the record is good.
500  *
501  * If HAMMER_CURSOR_DELETE_VISIBILITY is set we allow deleted memory
502  * records to be returned.  This is so pending deletions are detected
503  * when using an iterator to locate an unused hash key, or when we need
504  * to locate historical records on-disk to destroy.
505  */
506 static __inline
507 int
508 hammer_ip_iterate_mem_good(hammer_cursor_t cursor, hammer_record_t record)
509 {
510         if (cursor->flags & HAMMER_CURSOR_DELETE_VISIBILITY)
511                 return(1);
512         if (cursor->flags & HAMMER_CURSOR_BACKEND) {
513                 if (record->flags & (HAMMER_RECF_DELETED_BE |
514                                      HAMMER_RECF_COMMITTED)) {
515                         return(0);
516                 }
517         } else {
518                 if (record->flags & (HAMMER_RECF_DELETED_FE |
519                                      HAMMER_RECF_DELETED_BE |
520                                      HAMMER_RECF_COMMITTED)) {
521                         return(0);
522                 }
523         }
524         return(1);
525 }
526
527 /*
528  * This callback is used as part of the RB_SCAN function for in-memory
529  * records.  We terminate it (return -1) as soon as we get a match.
530  *
531  * This routine is used by frontend code.
532  *
533  * The primary compare code does not account for ASOF lookups.  This
534  * code handles that case as well as a few others.
535  */
536 static
537 int
538 hammer_rec_scan_callback(hammer_record_t rec, void *data)
539 {
540         hammer_cursor_t cursor = data;
541
542         /*
543          * We terminate on success, so this should be NULL on entry.
544          */
545         KKASSERT(cursor->iprec == NULL);
546
547         /*
548          * Skip if the record was marked deleted or committed.
549          */
550         if (hammer_ip_iterate_mem_good(cursor, rec) == 0)
551                 return(0);
552
553         /*
554          * Skip if not visible due to our as-of TID
555          */
556         if (cursor->flags & HAMMER_CURSOR_ASOF) {
557                 if (cursor->asof < rec->leaf.base.create_tid)
558                         return(0);
559                 if (rec->leaf.base.delete_tid &&
560                     cursor->asof >= rec->leaf.base.delete_tid) {
561                         return(0);
562                 }
563         }
564
565         /*
566          * ref the record.  The record is protected from backend B-Tree
567          * interactions by virtue of the cursor's IP lock.
568          */
569         hammer_ref(&rec->lock);
570
571         /*
572          * The record may have been deleted or committed while we
573          * were blocked.  XXX remove?
574          */
575         if (hammer_ip_iterate_mem_good(cursor, rec) == 0) {
576                 hammer_rel_mem_record(rec);
577                 return(0);
578         }
579
580         /*
581          * Set the matching record and stop the scan.
582          */
583         cursor->iprec = rec;
584         return(-1);
585 }
586
587
588 /*
589  * Lookup an in-memory record given the key specified in the cursor.  Works
590  * just like hammer_btree_lookup() but operates on an inode's in-memory
591  * record list.
592  *
593  * The lookup must fail if the record is marked for deferred deletion.
594  *
595  * The API for mem/btree_lookup() does not mess with the ATE/EOF bits.
596  */
597 static
598 int
599 hammer_mem_lookup(hammer_cursor_t cursor)
600 {
601         KKASSERT(cursor->ip != NULL);
602         if (cursor->iprec) {
603                 hammer_rel_mem_record(cursor->iprec);
604                 cursor->iprec = NULL;
605         }
606         hammer_rec_rb_tree_RB_SCAN(&cursor->ip->rec_tree, hammer_rec_find_cmp,
607                                    hammer_rec_scan_callback, cursor);
608
609         return (cursor->iprec ? 0 : ENOENT);
610 }
611
612 /*
613  * hammer_mem_first() - locate the first in-memory record matching the
614  * cursor within the bounds of the key range.
615  *
616  * WARNING!  API is slightly different from btree_first().  hammer_mem_first()
617  * will set ATEMEM the same as MEMEOF, and does not return any error.
618  */
619 static
620 int
621 hammer_mem_first(hammer_cursor_t cursor)
622 {
623         KKASSERT(cursor->ip != NULL);
624         if (cursor->iprec) {
625                 hammer_rel_mem_record(cursor->iprec);
626                 cursor->iprec = NULL;
627         }
628         hammer_rec_rb_tree_RB_SCAN(&cursor->ip->rec_tree, hammer_rec_scan_cmp,
629                                    hammer_rec_scan_callback, cursor);
630
631         if (cursor->iprec)
632                 cursor->flags &= ~(HAMMER_CURSOR_MEMEOF | HAMMER_CURSOR_ATEMEM);
633         else
634                 cursor->flags |= HAMMER_CURSOR_MEMEOF | HAMMER_CURSOR_ATEMEM;
635
636         return (cursor->iprec ? 0 : ENOENT);
637 }
638
639 /************************************************************************
640  *                   HAMMER IN-MEMORY RECORD FUNCTIONS                  *
641  ************************************************************************
642  *
643  * These functions manipulate in-memory records.  Such records typically
644  * exist prior to being committed to disk or indexed via the on-disk B-Tree.
645  */
646
647 /*
648  * Add a directory entry (dip,ncp) which references inode (ip).
649  *
650  * Note that the low 32 bits of the namekey are set temporarily to create
651  * a unique in-memory record, and may be modified a second time when the
652  * record is synchronized to disk.  In particular, the low 32 bits cannot be
653  * all 0's when synching to disk, which is not handled here.
654  *
655  * NOTE: bytes does not include any terminating \0 on name, and name might
656  * not be terminated.
657  */
658 int
659 hammer_ip_add_directory(struct hammer_transaction *trans,
660                      struct hammer_inode *dip, const char *name, int bytes,
661                      struct hammer_inode *ip)
662 {
663         struct hammer_cursor cursor;
664         hammer_record_t record;
665         int error;
666         uint32_t max_iterations;
667
668         KKASSERT(dip->ino_data.obj_type == HAMMER_OBJTYPE_DIRECTORY);
669
670         record = hammer_alloc_mem_record(dip, HAMMER_ENTRY_SIZE(bytes));
671
672         record->type = HAMMER_MEM_RECORD_ADD;
673         record->leaf.base.localization = dip->obj_localization +
674                                          hammer_dir_localization(dip);
675         record->leaf.base.obj_id = dip->obj_id;
676         record->leaf.base.key = hammer_directory_namekey(dip, name, bytes,
677                                                          &max_iterations);
678         record->leaf.base.rec_type = HAMMER_RECTYPE_DIRENTRY;
679         record->leaf.base.obj_type = ip->ino_leaf.base.obj_type;
680         record->data->entry.obj_id = ip->obj_id;
681         record->data->entry.localization = ip->obj_localization;
682         bcopy(name, record->data->entry.name, bytes);
683
684         ++ip->ino_data.nlinks;
685         ip->ino_data.ctime = trans->time;
686         hammer_modify_inode(trans, ip, HAMMER_INODE_DDIRTY);
687
688         /*
689          * Find an unused namekey.  Both the in-memory record tree and
690          * the B-Tree are checked.  We do not want historically deleted
691          * names to create a collision as our iteration space may be limited,
692          * and since create_tid wouldn't match anyway an ASOF search
693          * must be used to locate collisions.
694          *
695          * delete-visibility is set so pending deletions do not give us
696          * a false-negative on our ability to use an iterator.
697          *
698          * The iterator must not rollover the key.  Directory keys only
699          * use the positive key space.
700          */
701         hammer_init_cursor(trans, &cursor, &dip->cache[1], dip);
702         cursor.key_beg = record->leaf.base;
703         cursor.flags |= HAMMER_CURSOR_ASOF;
704         cursor.flags |= HAMMER_CURSOR_DELETE_VISIBILITY;
705         cursor.asof = ip->obj_asof;
706
707         while (hammer_ip_lookup(&cursor) == 0) {
708                 ++record->leaf.base.key;
709                 KKASSERT(record->leaf.base.key > 0);
710                 cursor.key_beg.key = record->leaf.base.key;
711                 if (--max_iterations == 0) {
712                         hammer_rel_mem_record(record);
713                         error = ENOSPC;
714                         goto failed;
715                 }
716         }
717
718         /*
719          * The target inode and the directory entry are bound together.
720          */
721         record->target_ip = ip;
722         record->flush_state = HAMMER_FST_SETUP;
723         TAILQ_INSERT_TAIL(&ip->target_list, record, target_entry);
724
725         /*
726          * The inode now has a dependancy and must be taken out of the idle
727          * state.  An inode not in an idle state is given an extra reference.
728          *
729          * When transitioning to a SETUP state flag for an automatic reflush
730          * when the dependancies are disposed of if someone is waiting on
731          * the inode.
732          */
733         if (ip->flush_state == HAMMER_FST_IDLE) {
734                 hammer_ref(&ip->lock);
735                 ip->flush_state = HAMMER_FST_SETUP;
736                 if (ip->flags & HAMMER_INODE_FLUSHW)
737                         ip->flags |= HAMMER_INODE_REFLUSH;
738         }
739         error = hammer_mem_add(record);
740         if (error == 0) {
741                 dip->ino_data.mtime = trans->time;
742                 hammer_modify_inode(trans, dip, HAMMER_INODE_MTIME);
743         }
744 failed:
745         hammer_done_cursor(&cursor);
746         return(error);
747 }
748
749 /*
750  * Delete the directory entry and update the inode link count.  The
751  * cursor must be seeked to the directory entry record being deleted.
752  *
753  * The related inode should be share-locked by the caller.  The caller is
754  * on the frontend.  It could also be NULL indicating that the directory
755  * entry being removed has no related inode.
756  *
757  * This function can return EDEADLK requiring the caller to terminate
758  * the cursor, any locks, wait on the returned record, and retry.
759  */
760 int
761 hammer_ip_del_directory(struct hammer_transaction *trans,
762                      hammer_cursor_t cursor, struct hammer_inode *dip,
763                      struct hammer_inode *ip)
764 {
765         hammer_record_t record;
766         int error;
767
768         if (hammer_cursor_inmem(cursor)) {
769                 /*
770                  * In-memory (unsynchronized) records can simply be freed.
771                  *
772                  * Even though the HAMMER_RECF_DELETED_FE flag is ignored
773                  * by the backend, we must still avoid races against the
774                  * backend potentially syncing the record to the media.
775                  *
776                  * We cannot call hammer_ip_delete_record(), that routine may
777                  * only be called from the backend.
778                  */
779                 record = cursor->iprec;
780                 if (record->flags & (HAMMER_RECF_INTERLOCK_BE |
781                                      HAMMER_RECF_DELETED_BE |
782                                      HAMMER_RECF_COMMITTED)) {
783                         KKASSERT(cursor->deadlk_rec == NULL);
784                         hammer_ref(&record->lock);
785                         cursor->deadlk_rec = record;
786                         error = EDEADLK;
787                 } else {
788                         KKASSERT(record->type == HAMMER_MEM_RECORD_ADD);
789                         record->flags |= HAMMER_RECF_DELETED_FE;
790                         error = 0;
791                 }
792         } else {
793                 /*
794                  * If the record is on-disk we have to queue the deletion by
795                  * the record's key.  This also causes lookups to skip the
796                  * record (lookups for the purposes of finding an unused
797                  * directory key do not skip the record).
798                  */
799                 KKASSERT(dip->flags &
800                          (HAMMER_INODE_ONDISK | HAMMER_INODE_DONDISK));
801                 record = hammer_alloc_mem_record(dip, 0);
802                 record->type = HAMMER_MEM_RECORD_DEL;
803                 record->leaf.base = cursor->leaf->base;
804                 KKASSERT(dip->obj_id == record->leaf.base.obj_id);
805
806                 /*
807                  * ip may be NULL, indicating the deletion of a directory
808                  * entry which has no related inode.
809                  */
810                 record->target_ip = ip;
811                 if (ip) {
812                         record->flush_state = HAMMER_FST_SETUP;
813                         TAILQ_INSERT_TAIL(&ip->target_list, record,
814                                           target_entry);
815                 } else {
816                         record->flush_state = HAMMER_FST_IDLE;
817                 }
818
819                 /*
820                  * The inode now has a dependancy and must be taken out of
821                  * the idle state.  An inode not in an idle state is given
822                  * an extra reference.
823                  *
824                  * When transitioning to a SETUP state flag for an automatic
825                  * reflush when the dependancies are disposed of if someone
826                  * is waiting on the inode.
827                  */
828                 if (ip && ip->flush_state == HAMMER_FST_IDLE) {
829                         hammer_ref(&ip->lock);
830                         ip->flush_state = HAMMER_FST_SETUP;
831                         if (ip->flags & HAMMER_INODE_FLUSHW)
832                                 ip->flags |= HAMMER_INODE_REFLUSH;
833                 }
834
835                 error = hammer_mem_add(record);
836         }
837
838         /*
839          * One less link.  The file may still be open in the OS even after
840          * all links have gone away.
841          *
842          * We have to terminate the cursor before syncing the inode to
843          * avoid deadlocking against ourselves.  XXX this may no longer
844          * be true.
845          *
846          * If nlinks drops to zero and the vnode is inactive (or there is
847          * no vnode), call hammer_inode_unloadable_check() to zonk the
848          * inode.  If we don't do this here the inode will not be destroyed
849          * on-media until we unmount.
850          */
851         if (error == 0) {
852                 if (ip) {
853                         --ip->ino_data.nlinks;  /* do before we might block */
854                         ip->ino_data.ctime = trans->time;
855                 }
856                 dip->ino_data.mtime = trans->time;
857                 hammer_modify_inode(trans, dip, HAMMER_INODE_MTIME);
858                 if (ip) {
859                         hammer_modify_inode(trans, ip, HAMMER_INODE_DDIRTY);
860                         if (ip->ino_data.nlinks == 0 &&
861                             (ip->vp == NULL || (ip->vp->v_flag & VINACTIVE))) {
862                                 hammer_done_cursor(cursor);
863                                 hammer_inode_unloadable_check(ip, 1);
864                                 hammer_flush_inode(ip, 0);
865                         }
866                 }
867
868         }
869         return(error);
870 }
871
872 /*
873  * Add a record to an inode.
874  *
875  * The caller must allocate the record with hammer_alloc_mem_record(ip,len) and
876  * initialize the following additional fields that are not initialized by these
877  * functions.
878  *
879  * The related inode should be share-locked by the caller.  The caller is
880  * on the frontend.
881  *
882  * record->leaf.base.key
883  * record->leaf.base.rec_type
884  * record->leaf.base.localization
885  */
886 int
887 hammer_ip_add_record(struct hammer_transaction *trans, hammer_record_t record)
888 {
889         hammer_inode_t ip = record->ip;
890         int error;
891
892         KKASSERT(record->leaf.base.localization != 0);
893         record->leaf.base.obj_id = ip->obj_id;
894         record->leaf.base.obj_type = ip->ino_leaf.base.obj_type;
895         error = hammer_mem_add(record);
896         return(error);
897 }
898
899 /*
900  * Locate a pre-existing bulk record in memory.  The caller wishes to
901  * replace the record with a new one.  The existing record may have a
902  * different length (and thus a different key) so we have to use an
903  * overlap check function.
904  */
905 static hammer_record_t
906 hammer_ip_get_bulk(hammer_record_t record)
907 {
908         struct hammer_bulk_info info;
909         hammer_inode_t ip = record->ip;
910
911         info.record = record;
912         info.conflict = NULL;
913         hammer_rec_rb_tree_RB_SCAN(&ip->rec_tree, hammer_rec_overlap_cmp,
914                                    hammer_bulk_scan_callback, &info);
915
916         return(info.conflict);  /* may be NULL */
917 }
918
919 /*
920  * Take records vetted by overlap_cmp.  The first non-deleted record
921  * (if any) stops the scan.
922  */
923 static int
924 hammer_bulk_scan_callback(hammer_record_t record, void *data)
925 {
926         struct hammer_bulk_info *info = data;
927
928         if (record->flags & (HAMMER_RECF_DELETED_FE | HAMMER_RECF_DELETED_BE |
929                              HAMMER_RECF_COMMITTED)) {
930                 return(0);
931         }
932         hammer_ref(&record->lock);
933         info->conflict = record;
934         return(-1);                     /* stop scan */
935 }
936
937 /*
938  * Reserve blockmap space placemarked with an in-memory record.
939  *
940  * This routine is called by the frontend in order to be able to directly
941  * flush a buffer cache buffer.  The frontend has locked the related buffer
942  * cache buffers and we should be able to manipulate any overlapping
943  * in-memory records.
944  *
945  * The caller is responsible for adding the returned record and deleting
946  * the returned conflicting record (if any), typically by calling
947  * hammer_ip_replace_bulk() (via hammer_io_direct_write()).
948  */
949 hammer_record_t
950 hammer_ip_add_bulk(hammer_inode_t ip, off_t file_offset, void *data, int bytes,
951                    int *errorp)
952 {
953         hammer_record_t record;
954         hammer_dedup_cache_t dcp;
955         hammer_crc_t crc;
956         int zone;
957
958         /*
959          * Create a record to cover the direct write.  The record cannot
960          * be added to the in-memory RB tree here as it might conflict
961          * with an existing memory record.  See hammer_io_direct_write().
962          *
963          * The backend is responsible for finalizing the space reserved in
964          * this record.
965          *
966          * XXX bytes not aligned, depend on the reservation code to
967          * align the reservation.
968          */
969         record = hammer_alloc_mem_record(ip, 0);
970         zone = hammer_data_zone_index(bytes);
971         if (bytes == 0)
972                 crc = 0;
973         else
974                 crc = crc32(data, bytes);
975
976         if (hammer_live_dedup == 0)
977                 goto nodedup;
978         if ((dcp = hammer_dedup_cache_lookup(ip->hmp, crc)) != NULL) {
979                 struct hammer_dedup_cache tmp = *dcp;
980
981                 record->resv = hammer_blockmap_reserve_dedup(ip->hmp, zone,
982                         bytes, tmp.data_offset, errorp);
983                 if (record->resv == NULL)
984                         goto nodedup;
985
986                 if (!hammer_dedup_validate(&tmp, zone, bytes, data)) {
987                         hammer_blockmap_reserve_complete(ip->hmp, record->resv);
988                         goto nodedup;
989                 }
990
991                 record->leaf.data_offset = tmp.data_offset;
992                 record->flags |= HAMMER_RECF_DEDUPED;
993         } else {
994 nodedup:
995                 record->resv = hammer_blockmap_reserve(ip->hmp, zone, bytes,
996                        &record->leaf.data_offset, errorp);
997                 if (record->resv == NULL) {
998                         hdkprintf("reservation failed\n");
999                         hammer_rel_mem_record(record);
1000                         return(NULL);
1001                 }
1002         }
1003
1004         record->type = HAMMER_MEM_RECORD_DATA;
1005         record->leaf.base.rec_type = HAMMER_RECTYPE_DATA;
1006         record->leaf.base.obj_type = ip->ino_leaf.base.obj_type;
1007         record->leaf.base.obj_id = ip->obj_id;
1008         record->leaf.base.key = file_offset + bytes;
1009         record->leaf.base.localization = ip->obj_localization +
1010                                          HAMMER_LOCALIZE_MISC;
1011         record->leaf.data_len = bytes;
1012         record->leaf.data_crc = crc;
1013         KKASSERT(*errorp == 0);
1014
1015         return(record);
1016 }
1017
1018 /*
1019  * Called by hammer_io_direct_write() prior to any possible completion
1020  * of the BIO to emplace the memory record associated with the I/O and
1021  * to replace any prior memory record which might still be active.
1022  *
1023  * Setting the FE deleted flag on the old record (if any) avoids any RB
1024  * tree insertion conflict, amoung other things.
1025  *
1026  * This has to be done prior to the caller completing any related buffer
1027  * cache I/O or a reinstantiation of the buffer may load data from the
1028  * old media location instead of the new media location.  The holding
1029  * of the locked buffer cache buffer serves to interlock the record
1030  * replacement operation.
1031  */
1032 void
1033 hammer_ip_replace_bulk(hammer_mount_t hmp, hammer_record_t record)
1034 {
1035         hammer_record_t conflict;
1036         int error __debugvar;
1037
1038         while ((conflict = hammer_ip_get_bulk(record)) != NULL) {
1039                 if ((conflict->flags & HAMMER_RECF_INTERLOCK_BE) == 0) {
1040                         conflict->flags |= HAMMER_RECF_DELETED_FE;
1041                         break;
1042                 }
1043                 conflict->flags |= HAMMER_RECF_WANTED;
1044                 tsleep(conflict, 0, "hmrrc3", 0);
1045                 hammer_rel_mem_record(conflict);
1046         }
1047         error = hammer_mem_add(record);
1048         if (conflict)
1049                 hammer_rel_mem_record(conflict);
1050         KKASSERT(error == 0);
1051 }
1052
1053 /*
1054  * Frontend truncation code.  Scan in-memory records only.  On-disk records
1055  * and records in a flushing state are handled by the backend.  The vnops
1056  * setattr code will handle the block containing the truncation point.
1057  *
1058  * Partial blocks are not deleted.
1059  *
1060  * This code is only called on regular files.
1061  */
1062 int
1063 hammer_ip_frontend_trunc(struct hammer_inode *ip, off_t file_size)
1064 {
1065         struct rec_trunc_info info;
1066
1067         switch(ip->ino_data.obj_type) {
1068         case HAMMER_OBJTYPE_REGFILE:
1069                 info.rec_type = HAMMER_RECTYPE_DATA;
1070                 break;
1071         case HAMMER_OBJTYPE_DBFILE:
1072                 info.rec_type = HAMMER_RECTYPE_DB;
1073                 break;
1074         default:
1075                 return(EINVAL);
1076         }
1077         info.trunc_off = file_size;
1078         hammer_rec_rb_tree_RB_SCAN(&ip->rec_tree, hammer_rec_trunc_cmp,
1079                                    hammer_frontend_trunc_callback, &info);
1080         return(0);
1081 }
1082
1083 /*
1084  * Scan callback for frontend records to destroy during a truncation.
1085  * We must ensure that DELETED_FE is set on the record or the frontend
1086  * will get confused in future read() calls.
1087  *
1088  * NOTE: DELETED_FE cannot be set while the record interlock (BE) is held.
1089  *       In this rare case we must wait for the interlock to be cleared.
1090  *
1091  * NOTE: This function is only called on regular files.  There are further
1092  *       restrictions to the setting of DELETED_FE on directory records
1093  *       undergoing a flush due to sensitive inode link count calculations.
1094  */
1095 static int
1096 hammer_frontend_trunc_callback(hammer_record_t record, void *data __unused)
1097 {
1098         if (record->flags & HAMMER_RECF_DELETED_FE)
1099                 return(0);
1100 #if 0
1101         if (record->flush_state == HAMMER_FST_FLUSH)
1102                 return(0);
1103 #endif
1104         hammer_ref(&record->lock);
1105         while (record->flags & HAMMER_RECF_INTERLOCK_BE)
1106                 hammer_wait_mem_record_ident(record, "hmmtrr");
1107         record->flags |= HAMMER_RECF_DELETED_FE;
1108         hammer_rel_mem_record(record);
1109         return(0);
1110 }
1111
1112 /*
1113  * Return 1 if the caller must check for and delete existing records
1114  * before writing out a new data record.
1115  *
1116  * Return 0 if the caller can just insert the record into the B-Tree without
1117  * checking.
1118  */
1119 static int
1120 hammer_record_needs_overwrite_delete(hammer_record_t record)
1121 {
1122         hammer_inode_t ip = record->ip;
1123         int64_t file_offset;
1124         int r;
1125
1126         if (ip->ino_data.obj_type == HAMMER_OBJTYPE_DBFILE)
1127                 file_offset = record->leaf.base.key;
1128         else
1129                 file_offset = record->leaf.base.key - record->leaf.data_len;
1130         r = (file_offset < ip->save_trunc_off);
1131         if (ip->ino_data.obj_type == HAMMER_OBJTYPE_DBFILE) {
1132                 if (ip->save_trunc_off <= record->leaf.base.key)
1133                         ip->save_trunc_off = record->leaf.base.key + 1;
1134         } else {
1135                 if (ip->save_trunc_off < record->leaf.base.key)
1136                         ip->save_trunc_off = record->leaf.base.key;
1137         }
1138         return(r);
1139 }
1140
1141 /*
1142  * Backend code.  Sync a record to the media.
1143  */
1144 int
1145 hammer_ip_sync_record_cursor(hammer_cursor_t cursor, hammer_record_t record)
1146 {
1147         hammer_transaction_t trans = cursor->trans;
1148         int64_t file_offset;
1149         int bytes;
1150         void *bdata;
1151         int error;
1152         int doprop;
1153
1154         KKASSERT(record->flush_state == HAMMER_FST_FLUSH);
1155         KKASSERT(record->flags & HAMMER_RECF_INTERLOCK_BE);
1156         KKASSERT(record->leaf.base.localization != 0);
1157
1158         /*
1159          * Any direct-write related to the record must complete before we
1160          * can sync the record to the on-disk media.
1161          */
1162         if (record->gflags & (HAMMER_RECG_DIRECT_IO | HAMMER_RECG_DIRECT_INVAL))
1163                 hammer_io_direct_wait(record);
1164
1165         /*
1166          * If this is a bulk-data record placemarker there may be an existing
1167          * record on-disk, indicating a data overwrite.  If there is the
1168          * on-disk record must be deleted before we can insert our new record.
1169          *
1170          * We've synthesized this record and do not know what the create_tid
1171          * on-disk is, nor how much data it represents.
1172          *
1173          * Keep in mind that (key) for data records is (base_offset + len),
1174          * not (base_offset).  Also, we only want to get rid of on-disk
1175          * records since we are trying to sync our in-memory record, call
1176          * hammer_ip_delete_range() with truncating set to 1 to make sure
1177          * it skips in-memory records.
1178          *
1179          * It is ok for the lookup to return ENOENT.
1180          *
1181          * NOTE OPTIMIZATION: sync_trunc_off is used to determine if we have
1182          * to call hammer_ip_delete_range() or not.  This also means we must
1183          * update sync_trunc_off() as we write.
1184          */
1185         if (record->type == HAMMER_MEM_RECORD_DATA &&
1186             hammer_record_needs_overwrite_delete(record)) {
1187                 file_offset = record->leaf.base.key - record->leaf.data_len;
1188                 bytes = (record->leaf.data_len + HAMMER_BUFMASK) &
1189                         ~HAMMER_BUFMASK;
1190                 KKASSERT((file_offset & HAMMER_BUFMASK) == 0);
1191                 error = hammer_ip_delete_range(
1192                                 cursor, record->ip,
1193                                 file_offset, file_offset + bytes - 1,
1194                                 1);
1195                 if (error && error != ENOENT)
1196                         goto done;
1197         }
1198
1199         /*
1200          * If this is a general record there may be an on-disk version
1201          * that must be deleted before we can insert the new record.
1202          */
1203         if (record->type == HAMMER_MEM_RECORD_GENERAL) {
1204                 error = hammer_delete_general(cursor, record->ip, &record->leaf);
1205                 if (error && error != ENOENT)
1206                         goto done;
1207         }
1208
1209         /*
1210          * Setup the cursor.
1211          */
1212         hammer_normalize_cursor(cursor);
1213         cursor->key_beg = record->leaf.base;
1214         cursor->flags &= ~HAMMER_CURSOR_INITMASK;
1215         cursor->flags |= HAMMER_CURSOR_BACKEND;
1216         cursor->flags &= ~HAMMER_CURSOR_INSERT;
1217
1218         /*
1219          * Records can wind up on-media before the inode itself is on-media.
1220          * Flag the case.
1221          */
1222         record->ip->flags |= HAMMER_INODE_DONDISK;
1223
1224         /*
1225          * If we are deleting a directory entry an exact match must be
1226          * found on-disk.
1227          */
1228         if (record->type == HAMMER_MEM_RECORD_DEL) {
1229                 error = hammer_btree_lookup(cursor);
1230                 if (error == 0) {
1231                         KKASSERT(cursor->iprec == NULL);
1232                         error = hammer_ip_delete_record(cursor, record->ip,
1233                                                         trans->tid);
1234                         if (error == 0) {
1235                                 record->flags |= HAMMER_RECF_DELETED_BE |
1236                                                  HAMMER_RECF_COMMITTED;
1237                                 ++record->ip->rec_generation;
1238                         }
1239                 }
1240                 goto done;
1241         }
1242
1243         /*
1244          * We are inserting.
1245          *
1246          * Issue a lookup to position the cursor and locate the insertion
1247          * point.  The target key should not exist.  If we are creating a
1248          * directory entry we may have to iterate the low 32 bits of the
1249          * key to find an unused key.
1250          */
1251         hammer_sync_lock_sh(trans);
1252         cursor->flags |= HAMMER_CURSOR_INSERT;
1253         error = hammer_btree_lookup(cursor);
1254         if (hammer_debug_inode)
1255                 hdkprintf("DOINSERT LOOKUP %d\n", error);
1256         if (error == 0) {
1257                 hdkprintf("duplicate rec at (%016llx)\n",
1258                         (long long)record->leaf.base.key);
1259                 if (hammer_debug_critical)
1260                         Debugger("duplicate record1");
1261                 error = EIO;
1262         }
1263 #if 0
1264         if (record->type == HAMMER_MEM_RECORD_DATA)
1265                 hdkprintf("%016llx ---------------- %016llx %d\n",
1266                         record->leaf.base.key - record->leaf.data_len,
1267                         record->leaf.data_offset, error);
1268 #endif
1269
1270         if (error != ENOENT)
1271                 goto done_unlock;
1272
1273         /*
1274          * Allocate the record and data.  The result buffers will be
1275          * marked as being modified and further calls to
1276          * hammer_modify_buffer() will result in unneeded UNDO records.
1277          *
1278          * Support zero-fill records (data == NULL and data_len != 0)
1279          */
1280         if (record->type == HAMMER_MEM_RECORD_DATA) {
1281                 /*
1282                  * The data portion of a bulk-data record has already been
1283                  * committed to disk, we need only adjust the layer2
1284                  * statistics in the same transaction as our B-Tree insert.
1285                  */
1286                 KKASSERT(record->leaf.data_offset != 0);
1287                 error = hammer_blockmap_finalize(trans,
1288                                                  record->resv,
1289                                                  record->leaf.data_offset,
1290                                                  record->leaf.data_len);
1291
1292                 if (hammer_live_dedup == 2 &&
1293                     (record->flags & HAMMER_RECF_DEDUPED) == 0) {
1294                         hammer_dedup_cache_add(record->ip, &record->leaf);
1295                 }
1296         } else if (record->data && record->leaf.data_len) {
1297                 /*
1298                  * Wholely cached record, with data.  Allocate the data.
1299                  */
1300                 bdata = hammer_alloc_data(trans, record->leaf.data_len,
1301                                           record->leaf.base.rec_type,
1302                                           &record->leaf.data_offset,
1303                                           &cursor->data_buffer,
1304                                           0, &error);
1305                 if (bdata == NULL)
1306                         goto done_unlock;
1307                 hammer_crc_set_leaf(record->data, &record->leaf);
1308                 hammer_modify_buffer_noundo(trans, cursor->data_buffer);
1309                 bcopy(record->data, bdata, record->leaf.data_len);
1310                 hammer_modify_buffer_done(cursor->data_buffer);
1311         } else {
1312                 /*
1313                  * Wholely cached record, without data.
1314                  */
1315                 record->leaf.data_offset = 0;
1316                 record->leaf.data_crc = 0;
1317         }
1318
1319         error = hammer_btree_insert(cursor, &record->leaf, &doprop);
1320         if (hammer_debug_inode && error) {
1321                 hdkprintf("BTREE INSERT error %d @ %016llx:%d key %016llx\n",
1322                         error,
1323                         (long long)cursor->node->node_offset,
1324                         cursor->index,
1325                         (long long)record->leaf.base.key);
1326         }
1327
1328         /*
1329          * Our record is on-disk and we normally mark the in-memory version
1330          * as having been committed (and not BE-deleted).
1331          *
1332          * If the record represented a directory deletion but we had to
1333          * sync a valid directory entry to disk due to dependancies,
1334          * we must convert the record to a covering delete so the
1335          * frontend does not have visibility on the synced entry.
1336          *
1337          * WARNING: cursor's leaf pointer may have changed after do_propagation
1338          *          returns!
1339          */
1340         if (error == 0) {
1341                 if (doprop) {
1342                         hammer_btree_do_propagation(cursor,
1343                                                     record->ip->pfsm,
1344                                                     &record->leaf);
1345                 }
1346                 if (record->flags & HAMMER_RECF_CONVERT_DELETE) {
1347                         /*
1348                          * Must convert deleted directory entry add
1349                          * to a directory entry delete.
1350                          */
1351                         KKASSERT(record->type == HAMMER_MEM_RECORD_ADD);
1352                         record->flags &= ~HAMMER_RECF_DELETED_FE;
1353                         record->type = HAMMER_MEM_RECORD_DEL;
1354                         KKASSERT(record->ip->obj_id == record->leaf.base.obj_id);
1355                         KKASSERT(record->flush_state == HAMMER_FST_FLUSH);
1356                         record->flags &= ~HAMMER_RECF_CONVERT_DELETE;
1357                         KKASSERT((record->flags & (HAMMER_RECF_COMMITTED |
1358                                                  HAMMER_RECF_DELETED_BE)) == 0);
1359                         /* converted record is not yet committed */
1360                         /* hammer_flush_record_done takes care of the rest */
1361                 } else {
1362                         /*
1363                          * Everything went fine and we are now done with
1364                          * this record.
1365                          */
1366                         record->flags |= HAMMER_RECF_COMMITTED;
1367                         ++record->ip->rec_generation;
1368                 }
1369         } else {
1370                 if (record->leaf.data_offset) {
1371                         hammer_blockmap_free(trans, record->leaf.data_offset,
1372                                              record->leaf.data_len);
1373                 }
1374         }
1375 done_unlock:
1376         hammer_sync_unlock(trans);
1377 done:
1378         return(error);
1379 }
1380
1381 /*
1382  * Add the record to the inode's rec_tree.  The low 32 bits of a directory
1383  * entry's key is used to deal with hash collisions in the upper 32 bits.
1384  * A unique 64 bit key is generated in-memory and may be regenerated a
1385  * second time when the directory record is flushed to the on-disk B-Tree.
1386  *
1387  * A referenced record is passed to this function.  This function
1388  * eats the reference.  If an error occurs the record will be deleted.
1389  *
1390  * A copy of the temporary record->data pointer provided by the caller
1391  * will be made.
1392  */
1393 int
1394 hammer_mem_add(hammer_record_t record)
1395 {
1396         hammer_mount_t hmp = record->ip->hmp;
1397
1398         /*
1399          * Make a private copy of record->data
1400          */
1401         if (record->data)
1402                 KKASSERT(record->flags & HAMMER_RECF_ALLOCDATA);
1403
1404         /*
1405          * Insert into the RB tree.  A unique key should have already
1406          * been selected if this is a directory entry.
1407          */
1408         if (RB_INSERT(hammer_rec_rb_tree, &record->ip->rec_tree, record)) {
1409                 record->flags |= HAMMER_RECF_DELETED_FE;
1410                 hammer_rel_mem_record(record);
1411                 return (EEXIST);
1412         }
1413         ++hmp->rsv_recs;
1414         ++record->ip->rsv_recs;
1415         record->ip->hmp->rsv_databytes += record->leaf.data_len;
1416         record->flags |= HAMMER_RECF_ONRBTREE;
1417         hammer_modify_inode(NULL, record->ip, HAMMER_INODE_XDIRTY);
1418         hammer_rel_mem_record(record);
1419         return(0);
1420 }
1421
1422 /************************************************************************
1423  *                   HAMMER INODE MERGED-RECORD FUNCTIONS               *
1424  ************************************************************************
1425  *
1426  * These functions augment the B-Tree scanning functions in hammer_btree.c
1427  * by merging in-memory records with on-disk records.
1428  */
1429
1430 /*
1431  * Locate a particular record either in-memory or on-disk.
1432  *
1433  * NOTE: This is basically a standalone routine, hammer_ip_next() may
1434  * NOT be called to iterate results.
1435  */
1436 int
1437 hammer_ip_lookup(hammer_cursor_t cursor)
1438 {
1439         int error;
1440
1441         /*
1442          * If the element is in-memory return it without searching the
1443          * on-disk B-Tree
1444          */
1445         KKASSERT(cursor->ip);
1446         error = hammer_mem_lookup(cursor);
1447         if (error == 0) {
1448                 cursor->leaf = &cursor->iprec->leaf;
1449                 return(error);
1450         }
1451         if (error != ENOENT)
1452                 return(error);
1453
1454         /*
1455          * If the inode has on-disk components search the on-disk B-Tree.
1456          */
1457         if ((cursor->ip->flags & (HAMMER_INODE_ONDISK|HAMMER_INODE_DONDISK)) == 0)
1458                 return(error);
1459         error = hammer_btree_lookup(cursor);
1460         if (error == 0)
1461                 error = hammer_btree_extract(cursor, HAMMER_CURSOR_GET_LEAF);
1462         return(error);
1463 }
1464
1465 /*
1466  * Helper for hammer_ip_first()/hammer_ip_next()
1467  *
1468  * NOTE: Both ATEDISK and DISKEOF will be set the same.  This sets up
1469  * hammer_ip_first() for calling hammer_ip_next(), and sets up the re-seek
1470  * state if hammer_ip_next() needs to re-seek.
1471  */
1472 static __inline
1473 int
1474 _hammer_ip_seek_btree(hammer_cursor_t cursor)
1475 {
1476         hammer_inode_t ip = cursor->ip;
1477         int error;
1478
1479         if (ip->flags & (HAMMER_INODE_ONDISK|HAMMER_INODE_DONDISK)) {
1480                 error = hammer_btree_lookup(cursor);
1481                 if (error == ENOENT || error == EDEADLK) {
1482                         if (hammer_debug_general & 0x2000) {
1483                                 hdkprintf("error %d node %p %016llx index %d\n",
1484                                         error, cursor->node,
1485                                         (long long)cursor->node->node_offset,
1486                                         cursor->index);
1487                         }
1488                         cursor->flags &= ~HAMMER_CURSOR_ATEDISK;
1489                         error = hammer_btree_iterate(cursor);
1490                 }
1491                 if (error == 0) {
1492                         cursor->flags &= ~(HAMMER_CURSOR_DISKEOF |
1493                                            HAMMER_CURSOR_ATEDISK);
1494                 } else {
1495                         cursor->flags |= HAMMER_CURSOR_DISKEOF |
1496                                          HAMMER_CURSOR_ATEDISK;
1497                         if (error == ENOENT)
1498                                 error = 0;
1499                 }
1500         } else {
1501                 cursor->flags |= HAMMER_CURSOR_DISKEOF | HAMMER_CURSOR_ATEDISK;
1502                 error = 0;
1503         }
1504         return(error);
1505 }
1506
1507 /*
1508  * Helper for hammer_ip_next()
1509  *
1510  * The caller has determined that the media cursor is further along than the
1511  * memory cursor and must be reseeked after a generation number change.
1512  */
1513 static
1514 int
1515 _hammer_ip_reseek(hammer_cursor_t cursor)
1516 {
1517         struct hammer_base_elm save;
1518         hammer_btree_elm_t elm;
1519         int error __debugvar;
1520         int r;
1521         int again = 0;
1522
1523         /*
1524          * Do the re-seek.
1525          */
1526         hkprintf("Debug: re-seeked during scan @ino=%016llx\n",
1527                 (long long)cursor->ip->obj_id);
1528         save = cursor->key_beg;
1529         cursor->key_beg = cursor->iprec->leaf.base;
1530         error = _hammer_ip_seek_btree(cursor);
1531         KKASSERT(error == 0);
1532         cursor->key_beg = save;
1533
1534         /*
1535          * If the memory record was previous returned to
1536          * the caller and the media record matches
1537          * (-1/+1: only create_tid differs), then iterate
1538          * the media record to avoid a double result.
1539          */
1540         if ((cursor->flags & HAMMER_CURSOR_ATEDISK) == 0 &&
1541             (cursor->flags & HAMMER_CURSOR_LASTWASMEM)) {
1542                 elm = &cursor->node->ondisk->elms[cursor->index];
1543                 r = hammer_btree_cmp(&elm->base, &cursor->iprec->leaf.base);
1544                 if (cursor->flags & HAMMER_CURSOR_ASOF) {
1545                         if (r >= -1 && r <= 1) {
1546                                 hkprintf("Debug: iterated after "
1547                                         "re-seek (asof r=%d)\n", r);
1548                                 cursor->flags |= HAMMER_CURSOR_ATEDISK;
1549                                 again = 1;
1550                         }
1551                 } else {
1552                         if (r == 0) {
1553                                 hkprintf("Debug: iterated after "
1554                                         "re-seek\n");
1555                                 cursor->flags |= HAMMER_CURSOR_ATEDISK;
1556                                 again = 1;
1557                         }
1558                 }
1559         }
1560         return(again);
1561 }
1562
1563 /*
1564  * Locate the first record within the cursor's key_beg/key_end range,
1565  * restricted to a particular inode.  0 is returned on success, ENOENT
1566  * if no records matched the requested range, or some other error.
1567  *
1568  * When 0 is returned hammer_ip_next() may be used to iterate additional
1569  * records within the requested range.
1570  *
1571  * This function can return EDEADLK, requiring the caller to terminate
1572  * the cursor and try again.
1573  */
1574
1575 int
1576 hammer_ip_first(hammer_cursor_t cursor)
1577 {
1578         hammer_inode_t ip __debugvar = cursor->ip;
1579         int error;
1580
1581         KKASSERT(ip != NULL);
1582
1583         /*
1584          * Clean up fields and setup for merged scan
1585          */
1586         cursor->flags &= ~HAMMER_CURSOR_RETEST;
1587
1588         /*
1589          * Search the in-memory record list (Red-Black tree).  Unlike the
1590          * B-Tree search, mem_first checks for records in the range.
1591          *
1592          * This function will setup both ATEMEM and MEMEOF properly for
1593          * the ip iteration.  ATEMEM will be set if MEMEOF is set.
1594          */
1595         hammer_mem_first(cursor);
1596
1597         /*
1598          * Detect generation changes during blockages, including
1599          * blockages which occur on the initial btree search.
1600          */
1601         cursor->rec_generation = cursor->ip->rec_generation;
1602
1603         /*
1604          * Initial search and result
1605          */
1606         error = _hammer_ip_seek_btree(cursor);
1607         if (error == 0)
1608                 error = hammer_ip_next(cursor);
1609
1610         return (error);
1611 }
1612
1613 /*
1614  * Retrieve the next record in a merged iteration within the bounds of the
1615  * cursor.  This call may be made multiple times after the cursor has been
1616  * initially searched with hammer_ip_first().
1617  *
1618  * There are numerous special cases in this code to deal with races between
1619  * in-memory records and on-media records.
1620  *
1621  * 0 is returned on success, ENOENT if no further records match the
1622  * requested range, or some other error code is returned.
1623  */
1624 int
1625 hammer_ip_next(hammer_cursor_t cursor)
1626 {
1627         hammer_btree_elm_t elm;
1628         hammer_record_t rec;
1629         hammer_record_t tmprec;
1630         int error;
1631         int r;
1632
1633 again:
1634         /*
1635          * Get the next on-disk record
1636          *
1637          * NOTE: If we deleted the last on-disk record we had scanned
1638          *       ATEDISK will be clear and RETEST will be set, forcing
1639          *       a call to iterate.  The fact that ATEDISK is clear causes
1640          *       iterate to re-test the 'current' element.  If ATEDISK is
1641          *       set, iterate will skip the 'current' element.
1642          */
1643         error = 0;
1644         if ((cursor->flags & HAMMER_CURSOR_DISKEOF) == 0) {
1645                 if (cursor->flags & (HAMMER_CURSOR_ATEDISK |
1646                                      HAMMER_CURSOR_RETEST)) {
1647                         error = hammer_btree_iterate(cursor);
1648                         cursor->flags &= ~HAMMER_CURSOR_RETEST;
1649                         if (error == 0) {
1650                                 cursor->flags &= ~HAMMER_CURSOR_ATEDISK;
1651                                 hammer_cache_node(&cursor->ip->cache[1],
1652                                                   cursor->node);
1653                         } else if (error == ENOENT) {
1654                                 cursor->flags |= HAMMER_CURSOR_DISKEOF |
1655                                                  HAMMER_CURSOR_ATEDISK;
1656                                 error = 0;
1657                         }
1658                 }
1659         }
1660
1661         /*
1662          * If the generation changed the backend has deleted or committed
1663          * one or more memory records since our last check.
1664          *
1665          * When this case occurs if the disk cursor is > current memory record
1666          * or the disk cursor is at EOF, we must re-seek the disk-cursor.
1667          * Since the cursor is ahead it must have not yet been eaten (if
1668          * not at eof anyway). (XXX data offset case?)
1669          *
1670          * NOTE: we are not doing a full check here.  That will be handled
1671          * later on.
1672          *
1673          * If we have exhausted all memory records we do not have to do any
1674          * further seeks.
1675          */
1676         while (cursor->rec_generation != cursor->ip->rec_generation &&
1677                error == 0) {
1678                 hkprintf("Debug: generation changed during scan @ino=%016llx\n",
1679                         (long long)cursor->ip->obj_id);
1680                 cursor->rec_generation = cursor->ip->rec_generation;
1681                 if (cursor->flags & HAMMER_CURSOR_MEMEOF)
1682                         break;
1683                 if (cursor->flags & HAMMER_CURSOR_DISKEOF) {
1684                         r = 1;
1685                 } else {
1686                         KKASSERT((cursor->flags & HAMMER_CURSOR_ATEDISK) == 0);
1687                         elm = &cursor->node->ondisk->elms[cursor->index];
1688                         r = hammer_btree_cmp(&elm->base,
1689                                              &cursor->iprec->leaf.base);
1690                 }
1691
1692                 /*
1693                  * Do we re-seek the media cursor?
1694                  */
1695                 if (r > 0) {
1696                         if (_hammer_ip_reseek(cursor))
1697                                 goto again;
1698                 }
1699         }
1700
1701         /*
1702          * We can now safely get the next in-memory record.  We cannot
1703          * block here.
1704          *
1705          * hammer_rec_scan_cmp:  Is the record still in our general range,
1706          *                       (non-inclusive of snapshot exclusions)?
1707          * hammer_rec_scan_callback: Is the record in our snapshot?
1708          */
1709         tmprec = NULL;
1710         if ((cursor->flags & HAMMER_CURSOR_MEMEOF) == 0) {
1711                 /*
1712                  * If the current memory record was eaten then get the next
1713                  * one.  Stale records are skipped.
1714                  */
1715                 if (cursor->flags & HAMMER_CURSOR_ATEMEM) {
1716                         tmprec = cursor->iprec;
1717                         cursor->iprec = NULL;
1718                         rec = hammer_rec_rb_tree_RB_NEXT(tmprec);
1719                         while (rec) {
1720                                 if (hammer_rec_scan_cmp(rec, cursor) != 0)
1721                                         break;
1722                                 if (hammer_rec_scan_callback(rec, cursor) != 0)
1723                                         break;
1724                                 rec = hammer_rec_rb_tree_RB_NEXT(rec);
1725                         }
1726                         if (cursor->iprec) {
1727                                 KKASSERT(cursor->iprec == rec);
1728                                 cursor->flags &= ~HAMMER_CURSOR_ATEMEM;
1729                         } else {
1730                                 cursor->flags |= HAMMER_CURSOR_MEMEOF;
1731                         }
1732                         cursor->flags &= ~HAMMER_CURSOR_LASTWASMEM;
1733                 }
1734         }
1735
1736         /*
1737          * MEMORY RECORD VALIDITY TEST
1738          *
1739          * (We still can't block, which is why tmprec is being held so
1740          * long).
1741          *
1742          * If the memory record is no longer valid we skip it.  It may
1743          * have been deleted by the frontend.  If it was deleted or
1744          * committed by the backend the generation change re-seeked the
1745          * disk cursor and the record will be present there.
1746          */
1747         if (error == 0 && (cursor->flags & HAMMER_CURSOR_MEMEOF) == 0) {
1748                 KKASSERT(cursor->iprec);
1749                 KKASSERT((cursor->flags & HAMMER_CURSOR_ATEMEM) == 0);
1750                 if (!hammer_ip_iterate_mem_good(cursor, cursor->iprec)) {
1751                         cursor->flags |= HAMMER_CURSOR_ATEMEM;
1752                         if (tmprec)
1753                                 hammer_rel_mem_record(tmprec);
1754                         goto again;
1755                 }
1756         }
1757         if (tmprec)
1758                 hammer_rel_mem_record(tmprec);
1759
1760         /*
1761          * Extract either the disk or memory record depending on their
1762          * relative position.
1763          */
1764         error = 0;
1765         switch(cursor->flags & (HAMMER_CURSOR_ATEDISK | HAMMER_CURSOR_ATEMEM)) {
1766         case 0:
1767                 /*
1768                  * Both entries valid.   Compare the entries and nominally
1769                  * return the first one in the sort order.  Numerous cases
1770                  * require special attention, however.
1771                  */
1772                 elm = &cursor->node->ondisk->elms[cursor->index];
1773                 r = hammer_btree_cmp(&elm->base, &cursor->iprec->leaf.base);
1774
1775                 /*
1776                  * If the two entries differ only by their key (-2/2) or
1777                  * create_tid (-1/1), and are DATA records, we may have a
1778                  * nominal match.  We have to calculate the base file
1779                  * offset of the data.
1780                  */
1781                 if (r <= 2 && r >= -2 && r != 0 &&
1782                     cursor->ip->ino_data.obj_type == HAMMER_OBJTYPE_REGFILE &&
1783                     cursor->iprec->type == HAMMER_MEM_RECORD_DATA) {
1784                         int64_t base1 = elm->leaf.base.key - elm->leaf.data_len;
1785                         int64_t base2 = cursor->iprec->leaf.base.key -
1786                                         cursor->iprec->leaf.data_len;
1787                         if (base1 == base2)
1788                                 r = 0;
1789                 }
1790
1791                 if (r < 0) {
1792                         error = hammer_btree_extract(cursor,
1793                                                      HAMMER_CURSOR_GET_LEAF);
1794                         cursor->flags |= HAMMER_CURSOR_ATEDISK;
1795                         cursor->flags &= ~HAMMER_CURSOR_LASTWASMEM;
1796                         break;
1797                 }
1798
1799                 /*
1800                  * If the entries match exactly the memory entry is either
1801                  * an on-disk directory entry deletion or a bulk data
1802                  * overwrite.  If it is a directory entry deletion we eat
1803                  * both entries.
1804                  *
1805                  * For the bulk-data overwrite case it is possible to have
1806                  * visibility into both, which simply means the syncer
1807                  * hasn't gotten around to doing the delete+insert sequence
1808                  * on the B-Tree.  Use the memory entry and throw away the
1809                  * on-disk entry.
1810                  *
1811                  * If the in-memory record is not either of these we
1812                  * probably caught the syncer while it was syncing it to
1813                  * the media.  Since we hold a shared lock on the cursor,
1814                  * the in-memory record had better be marked deleted at
1815                  * this point.
1816                  */
1817                 if (r == 0) {
1818                         if (cursor->iprec->type == HAMMER_MEM_RECORD_DEL) {
1819                                 if ((cursor->flags & HAMMER_CURSOR_DELETE_VISIBILITY) == 0) {
1820                                         cursor->flags |= HAMMER_CURSOR_ATEDISK;
1821                                         cursor->flags |= HAMMER_CURSOR_ATEMEM;
1822                                         goto again;
1823                                 }
1824                         } else if (cursor->iprec->type == HAMMER_MEM_RECORD_DATA) {
1825                                 if ((cursor->flags & HAMMER_CURSOR_DELETE_VISIBILITY) == 0) {
1826                                         cursor->flags |= HAMMER_CURSOR_ATEDISK;
1827                                 }
1828                                 /* fall through to memory entry */
1829                         } else {
1830                                 hpanic("duplicate mem/B-Tree entry %p %d %08x",
1831                                         cursor->iprec,
1832                                         cursor->iprec->type,
1833                                         cursor->iprec->flags);
1834                                 cursor->flags |= HAMMER_CURSOR_ATEMEM;
1835                                 goto again;
1836                         }
1837                 }
1838                 /* fall through to the memory entry */
1839         case HAMMER_CURSOR_ATEDISK:
1840                 /*
1841                  * Only the memory entry is valid.
1842                  */
1843                 cursor->leaf = &cursor->iprec->leaf;
1844                 cursor->flags |= HAMMER_CURSOR_ATEMEM;
1845                 cursor->flags |= HAMMER_CURSOR_LASTWASMEM;
1846
1847                 /*
1848                  * If the memory entry is an on-disk deletion we should have
1849                  * also had found a B-Tree record.  If the backend beat us
1850                  * to it it would have interlocked the cursor and we should
1851                  * have seen the in-memory record marked DELETED_FE.
1852                  */
1853                 if (cursor->iprec->type == HAMMER_MEM_RECORD_DEL &&
1854                     (cursor->flags & HAMMER_CURSOR_DELETE_VISIBILITY) == 0) {
1855                         hpanic("del-on-disk with no B-Tree entry iprec %p flags %08x",
1856                                 cursor->iprec,
1857                                 cursor->iprec->flags);
1858                 }
1859                 break;
1860         case HAMMER_CURSOR_ATEMEM:
1861                 /*
1862                  * Only the disk entry is valid
1863                  */
1864                 error = hammer_btree_extract(cursor, HAMMER_CURSOR_GET_LEAF);
1865                 cursor->flags |= HAMMER_CURSOR_ATEDISK;
1866                 cursor->flags &= ~HAMMER_CURSOR_LASTWASMEM;
1867                 break;
1868         default:
1869                 /*
1870                  * Neither entry is valid
1871                  *
1872                  * XXX error not set properly
1873                  */
1874                 cursor->flags &= ~HAMMER_CURSOR_LASTWASMEM;
1875                 cursor->leaf = NULL;
1876                 error = ENOENT;
1877                 break;
1878         }
1879         return(error);
1880 }
1881
1882 /*
1883  * Resolve the cursor->data pointer for the current cursor position in
1884  * a merged iteration.
1885  */
1886 int
1887 hammer_ip_resolve_data(hammer_cursor_t cursor)
1888 {
1889         hammer_record_t record;
1890         int error;
1891
1892         if (hammer_cursor_inmem(cursor)) {
1893                 /*
1894                  * The data associated with an in-memory record is usually
1895                  * kmalloced, but reserve-ahead data records will have an
1896                  * on-disk reference.
1897                  *
1898                  * NOTE: Reserve-ahead data records must be handled in the
1899                  * context of the related high level buffer cache buffer
1900                  * to interlock against async writes.
1901                  */
1902                 record = cursor->iprec;
1903                 cursor->data = record->data;
1904                 error = 0;
1905                 if (cursor->data == NULL) {
1906                         KKASSERT(record->leaf.base.rec_type ==
1907                                  HAMMER_RECTYPE_DATA);
1908                         cursor->data = hammer_bread_ext(cursor->trans->hmp,
1909                                                     record->leaf.data_offset,
1910                                                     record->leaf.data_len,
1911                                                     &error,
1912                                                     &cursor->data_buffer);
1913                 }
1914         } else {
1915                 cursor->leaf = &cursor->node->ondisk->elms[cursor->index].leaf;
1916                 error = hammer_btree_extract(cursor, HAMMER_CURSOR_GET_DATA);
1917         }
1918         return(error);
1919 }
1920
1921 /*
1922  * Backend truncation / record replacement - delete records in range.
1923  *
1924  * Delete all records within the specified range for inode ip.  In-memory
1925  * records still associated with the frontend are ignored.
1926  *
1927  * If truncating is non-zero in-memory records associated with the back-end
1928  * are ignored.  If truncating is > 1 we can return EWOULDBLOCK.
1929  *
1930  * NOTES:
1931  *
1932  *      * An unaligned range will cause new records to be added to cover
1933  *        the edge cases. (XXX not implemented yet).
1934  *
1935  *      * Replacement via reservations (see hammer_ip_sync_record_cursor())
1936  *        also do not deal with unaligned ranges.
1937  *
1938  *      * ran_end is inclusive (e.g. 0,1023 instead of 0,1024).
1939  *
1940  *      * Record keys for regular file data have to be special-cased since
1941  *        they indicate the end of the range (key = base + bytes).
1942  *
1943  *      * This function may be asked to delete ridiculously huge ranges, for
1944  *        example if someone truncates or removes a 1TB regular file.  We
1945  *        must be very careful on restarts and we may have to stop w/
1946  *        EWOULDBLOCK to avoid blowing out the buffer cache.
1947  */
1948 int
1949 hammer_ip_delete_range(hammer_cursor_t cursor, hammer_inode_t ip,
1950                        int64_t ran_beg, int64_t ran_end, int truncating)
1951 {
1952         hammer_transaction_t trans = cursor->trans;
1953         hammer_btree_leaf_elm_t leaf;
1954         int error;
1955         int64_t off;
1956         int64_t tmp64;
1957
1958 #if 0
1959         hdkprintf("%p %016llx-%016llx\n", ip, ran_beg, ran_end);
1960 #endif
1961
1962         KKASSERT(trans->type == HAMMER_TRANS_FLS);
1963 retry:
1964         hammer_normalize_cursor(cursor);
1965         cursor->key_beg.localization = ip->obj_localization +
1966                                        HAMMER_LOCALIZE_MISC;
1967         cursor->key_beg.obj_id = ip->obj_id;
1968         cursor->key_beg.create_tid = 0;
1969         cursor->key_beg.delete_tid = 0;
1970         cursor->key_beg.obj_type = 0;
1971
1972         if (ip->ino_data.obj_type == HAMMER_OBJTYPE_DBFILE) {
1973                 cursor->key_beg.key = ran_beg;
1974                 cursor->key_beg.rec_type = HAMMER_RECTYPE_DB;
1975         } else {
1976                 /*
1977                  * The key in the B-Tree is (base+bytes), so the first possible
1978                  * matching key is ran_beg + 1.
1979                  */
1980                 cursor->key_beg.key = ran_beg + 1;
1981                 cursor->key_beg.rec_type = HAMMER_RECTYPE_DATA;
1982         }
1983
1984         cursor->key_end = cursor->key_beg;
1985         if (ip->ino_data.obj_type == HAMMER_OBJTYPE_DBFILE) {
1986                 cursor->key_end.key = ran_end;
1987         } else {
1988                 tmp64 = ran_end + MAXPHYS + 1;  /* work around GCC-4 bug */
1989                 if (tmp64 < ran_end)
1990                         cursor->key_end.key = 0x7FFFFFFFFFFFFFFFLL;
1991                 else
1992                         cursor->key_end.key = ran_end + MAXPHYS + 1;
1993         }
1994
1995         cursor->asof = ip->obj_asof;
1996         cursor->flags &= ~HAMMER_CURSOR_INITMASK;
1997         cursor->flags |= HAMMER_CURSOR_ASOF;
1998         cursor->flags |= HAMMER_CURSOR_DELETE_VISIBILITY;
1999         cursor->flags |= HAMMER_CURSOR_BACKEND;
2000         cursor->flags |= HAMMER_CURSOR_END_INCLUSIVE;
2001
2002         error = hammer_ip_first(cursor);
2003
2004         /*
2005          * Iterate through matching records and mark them as deleted.
2006          */
2007         while (error == 0) {
2008                 leaf = cursor->leaf;
2009
2010                 KKASSERT(leaf->base.delete_tid == 0);
2011                 KKASSERT(leaf->base.obj_id == ip->obj_id);
2012
2013                 /*
2014                  * There may be overlap cases for regular file data.  Also
2015                  * remember the key for a regular file record is (base + len),
2016                  * NOT (base).
2017                  *
2018                  * Note that due to duplicates (mem & media) allowed by
2019                  * DELETE_VISIBILITY, off can wind up less then ran_beg.
2020                  */
2021                 if (leaf->base.rec_type == HAMMER_RECTYPE_DATA) {
2022                         off = leaf->base.key - leaf->data_len;
2023                         /*
2024                          * Check the left edge case.  We currently do not
2025                          * split existing records.
2026                          */
2027                         if (off < ran_beg && leaf->base.key > ran_beg) {
2028                                 hpanic("hammer left edge case %016llx %d",
2029                                         (long long)leaf->base.key,
2030                                         leaf->data_len);
2031                         }
2032
2033                         /*
2034                          * Check the right edge case.  Note that the
2035                          * record can be completely out of bounds, which
2036                          * terminates the search.
2037                          *
2038                          * base->key is exclusive of the right edge while
2039                          * ran_end is inclusive of the right edge.  The
2040                          * (key - data_len) left boundary is inclusive.
2041                          *
2042                          * XXX theory-check this test at some point, are
2043                          * we missing a + 1 somewhere?  Note that ran_end
2044                          * could overflow.
2045                          */
2046                         if (leaf->base.key - 1 > ran_end) {
2047                                 if (leaf->base.key - leaf->data_len > ran_end)
2048                                         break;
2049                                 hpanic("hammer right edge case");
2050                         }
2051                 } else {
2052                         off = leaf->base.key;
2053                 }
2054
2055                 /*
2056                  * Delete the record.  When truncating we do not delete
2057                  * in-memory (data) records because they represent data
2058                  * written after the truncation.
2059                  *
2060                  * This will also physically destroy the B-Tree entry and
2061                  * data if the retention policy dictates.  The function
2062                  * will set HAMMER_CURSOR_RETEST to cause hammer_ip_next()
2063                  * to retest the new 'current' element.
2064                  */
2065                 if (truncating == 0 || hammer_cursor_ondisk(cursor)) {
2066                         error = hammer_ip_delete_record(cursor, ip, trans->tid);
2067                         /*
2068                          * If we have built up too many meta-buffers we risk
2069                          * deadlocking the kernel and must stop.  This can
2070                          * occur when deleting ridiculously huge files.
2071                          * sync_trunc_off is updated so the next cycle does
2072                          * not re-iterate records we have already deleted.
2073                          *
2074                          * This is only done with formal truncations.
2075                          */
2076                         if (truncating > 1 && error == 0 &&
2077                             hammer_flusher_meta_limit(ip->hmp)) {
2078                                 ip->sync_trunc_off = off;
2079                                 error = EWOULDBLOCK;
2080                         }
2081                 }
2082                 if (error)
2083                         break;
2084                 ran_beg = off;  /* for restart */
2085                 error = hammer_ip_next(cursor);
2086         }
2087         if (cursor->node)
2088                 hammer_cache_node(&ip->cache[1], cursor->node);
2089
2090         if (error == EDEADLK) {
2091                 hammer_done_cursor(cursor);
2092                 error = hammer_init_cursor(trans, cursor, &ip->cache[1], ip);
2093                 if (error == 0)
2094                         goto retry;
2095         }
2096         if (error == ENOENT)
2097                 error = 0;
2098         return(error);
2099 }
2100
2101 /*
2102  * This backend function deletes the specified record on-disk, similar to
2103  * delete_range but for a specific record.  Unlike the exact deletions
2104  * used when deleting a directory entry this function uses an ASOF search
2105  * like delete_range.
2106  *
2107  * This function may be called with ip->obj_asof set for a slave snapshot,
2108  * so don't use it.  We always delete non-historical records only.
2109  */
2110 static int
2111 hammer_delete_general(hammer_cursor_t cursor, hammer_inode_t ip,
2112                       hammer_btree_leaf_elm_t leaf)
2113 {
2114         hammer_transaction_t trans = cursor->trans;
2115         int error;
2116
2117         KKASSERT(trans->type == HAMMER_TRANS_FLS);
2118 retry:
2119         hammer_normalize_cursor(cursor);
2120         cursor->key_beg = leaf->base;
2121         cursor->asof = HAMMER_MAX_TID;
2122         cursor->flags &= ~HAMMER_CURSOR_INITMASK;
2123         cursor->flags |= HAMMER_CURSOR_ASOF;
2124         cursor->flags |= HAMMER_CURSOR_BACKEND;
2125         cursor->flags &= ~HAMMER_CURSOR_INSERT;
2126
2127         error = hammer_btree_lookup(cursor);
2128         if (error == 0) {
2129                 error = hammer_ip_delete_record(cursor, ip, trans->tid);
2130         }
2131         if (error == EDEADLK) {
2132                 hammer_done_cursor(cursor);
2133                 error = hammer_init_cursor(trans, cursor, &ip->cache[1], ip);
2134                 if (error == 0)
2135                         goto retry;
2136         }
2137         return(error);
2138 }
2139
2140 /*
2141  * This function deletes remaining auxillary records when an inode is
2142  * being deleted.  This function explicitly does not delete the
2143  * inode record, directory entry, data, or db records.  Those must be
2144  * properly disposed of prior to this call.
2145  */
2146 int
2147 hammer_ip_delete_clean(hammer_cursor_t cursor, hammer_inode_t ip, int *countp)
2148 {
2149         hammer_transaction_t trans = cursor->trans;
2150         hammer_btree_leaf_elm_t leaf __debugvar;
2151         int error;
2152
2153         KKASSERT(trans->type == HAMMER_TRANS_FLS);
2154 retry:
2155         hammer_normalize_cursor(cursor);
2156         cursor->key_beg.localization = ip->obj_localization +
2157                                        HAMMER_LOCALIZE_MISC;
2158         cursor->key_beg.obj_id = ip->obj_id;
2159         cursor->key_beg.create_tid = 0;
2160         cursor->key_beg.delete_tid = 0;
2161         cursor->key_beg.obj_type = 0;
2162         cursor->key_beg.rec_type = HAMMER_RECTYPE_CLEAN_START;
2163         cursor->key_beg.key = HAMMER_MIN_KEY;
2164
2165         cursor->key_end = cursor->key_beg;
2166         cursor->key_end.rec_type = HAMMER_RECTYPE_MAX;
2167         cursor->key_end.key = HAMMER_MAX_KEY;
2168
2169         cursor->asof = ip->obj_asof;
2170         cursor->flags &= ~HAMMER_CURSOR_INITMASK;
2171         cursor->flags |= HAMMER_CURSOR_END_INCLUSIVE | HAMMER_CURSOR_ASOF;
2172         cursor->flags |= HAMMER_CURSOR_DELETE_VISIBILITY;
2173         cursor->flags |= HAMMER_CURSOR_BACKEND;
2174
2175         error = hammer_ip_first(cursor);
2176
2177         /*
2178          * Iterate through matching records and mark them as deleted.
2179          */
2180         while (error == 0) {
2181                 leaf = cursor->leaf;
2182
2183                 KKASSERT(leaf->base.delete_tid == 0);
2184
2185                 /*
2186                  * Mark the record and B-Tree entry as deleted.  This will
2187                  * also physically delete the B-Tree entry, record, and
2188                  * data if the retention policy dictates.  The function
2189                  * will set HAMMER_CURSOR_RETEST to cause hammer_ip_next()
2190                  * to retest the new 'current' element.
2191                  *
2192                  * Directory entries (and delete-on-disk directory entries)
2193                  * must be synced and cannot be deleted.
2194                  */
2195                 error = hammer_ip_delete_record(cursor, ip, trans->tid);
2196                 ++*countp;
2197                 if (error)
2198                         break;
2199                 error = hammer_ip_next(cursor);
2200         }
2201         if (cursor->node)
2202                 hammer_cache_node(&ip->cache[1], cursor->node);
2203         if (error == EDEADLK) {
2204                 hammer_done_cursor(cursor);
2205                 error = hammer_init_cursor(trans, cursor, &ip->cache[1], ip);
2206                 if (error == 0)
2207                         goto retry;
2208         }
2209         if (error == ENOENT)
2210                 error = 0;
2211         return(error);
2212 }
2213
2214 /*
2215  * Delete the record at the current cursor.  On success the cursor will
2216  * be positioned appropriately for an iteration but may no longer be at
2217  * a leaf node.
2218  *
2219  * This routine is only called from the backend.
2220  *
2221  * NOTE: This can return EDEADLK, requiring the caller to terminate the
2222  * cursor and retry.
2223  */
2224 int
2225 hammer_ip_delete_record(hammer_cursor_t cursor, hammer_inode_t ip,
2226                         hammer_tid_t tid)
2227 {
2228         hammer_record_t iprec;
2229         int error;
2230
2231         KKASSERT(cursor->flags & HAMMER_CURSOR_BACKEND);
2232         KKASSERT(tid != 0);
2233
2234         /*
2235          * In-memory (unsynchronized) records can simply be freed.  This
2236          * only occurs in range iterations since all other records are
2237          * individually synchronized.  Thus there should be no confusion with
2238          * the interlock.
2239          *
2240          * An in-memory record may be deleted before being committed to disk,
2241          * but could have been accessed in the mean time.  The reservation
2242          * code will deal with the case.
2243          */
2244         if (hammer_cursor_inmem(cursor)) {
2245                 iprec = cursor->iprec;
2246                 KKASSERT((iprec->flags & HAMMER_RECF_INTERLOCK_BE) ==0);
2247                 iprec->flags |= HAMMER_RECF_DELETED_FE;
2248                 iprec->flags |= HAMMER_RECF_DELETED_BE;
2249                 KKASSERT(iprec->ip == ip);
2250                 ++ip->rec_generation;
2251                 return(0);
2252         }
2253
2254         /*
2255          * On-disk records are marked as deleted by updating their delete_tid.
2256          * This does not effect their position in the B-Tree (which is based
2257          * on their create_tid).
2258          *
2259          * Frontend B-Tree operations track inodes so we tell
2260          * hammer_delete_at_cursor() not to.
2261          */
2262         error = hammer_btree_extract(cursor, HAMMER_CURSOR_GET_LEAF);
2263
2264         if (error == 0) {
2265                 error = hammer_delete_at_cursor(
2266                                 cursor,
2267                                 HAMMER_DELETE_ADJUST | hammer_nohistory(ip),
2268                                 cursor->trans->tid,
2269                                 cursor->trans->time32,
2270                                 0, NULL);
2271         }
2272         return(error);
2273 }
2274
2275 /*
2276  * Used to write a generic record w/optional data to the media b-tree
2277  * when no inode context is available.  Used by the mirroring and
2278  * snapshot code.
2279  *
2280  * Caller must set cursor->key_beg to leaf->base.  The cursor must be
2281  * flagged for backend operation and not flagged ASOF (since we are
2282  * doing an insertion).
2283  *
2284  * This function will acquire the appropriate sync lock and will set
2285  * the cursor insertion flag for the operation, do the btree lookup,
2286  * and the insertion, and clear the insertion flag and sync lock before
2287  * returning.  The cursor state will be such that the caller can continue
2288  * scanning (used by the mirroring code).
2289  *
2290  * mode: HAMMER_CREATE_MODE_UMIRROR     copyin data, check crc
2291  *       HAMMER_CREATE_MODE_SYS         bcopy data, generate crc
2292  *
2293  * NOTE: EDEADLK can be returned.  The caller must do deadlock handling and
2294  *                retry.
2295  *
2296  *       EALREADY can be returned if the record already exists (WARNING,
2297  *                because ASOF cannot be used no check is made for illegal
2298  *                duplicates).
2299  *
2300  * NOTE: Do not use the function for normal inode-related records as this
2301  *       functions goes directly to the media and is not integrated with
2302  *       in-memory records.
2303  */
2304 int
2305 hammer_create_at_cursor(hammer_cursor_t cursor, hammer_btree_leaf_elm_t leaf,
2306                         void *udata, int mode)
2307 {
2308         hammer_transaction_t trans;
2309         hammer_buffer_t data_buffer;
2310         hammer_off_t ndata_offset;
2311         hammer_tid_t high_tid;
2312         void *ndata;
2313         int error;
2314         int doprop;
2315
2316         trans = cursor->trans;
2317         data_buffer = NULL;
2318         ndata_offset = 0;
2319         doprop = 0;
2320
2321         KKASSERT((cursor->flags &
2322                   (HAMMER_CURSOR_BACKEND | HAMMER_CURSOR_ASOF)) ==
2323                   (HAMMER_CURSOR_BACKEND));
2324
2325         hammer_sync_lock_sh(trans);
2326
2327         if (leaf->data_len) {
2328                 ndata = hammer_alloc_data(trans, leaf->data_len,
2329                                           leaf->base.rec_type,
2330                                           &ndata_offset, &data_buffer,
2331                                           0, &error);
2332                 if (ndata == NULL) {
2333                         hammer_sync_unlock(trans);
2334                         return (error);
2335                 }
2336                 leaf->data_offset = ndata_offset;
2337                 hammer_modify_buffer_noundo(trans, data_buffer);
2338
2339                 switch(mode) {
2340                 case HAMMER_CREATE_MODE_UMIRROR:
2341                         error = copyin(udata, ndata, leaf->data_len);
2342                         if (error == 0) {
2343                                 if (hammer_crc_test_leaf(ndata, leaf) == 0) {
2344                                         hdkprintf("CRC DATA @ %016llx/%d MISMATCH ON PIPE\n",
2345                                                 (long long)ndata_offset,
2346                                                 leaf->data_len);
2347                                         error = EINVAL;
2348                                 } else {
2349                                         error = hammer_cursor_localize_data(
2350                                                         ndata, leaf);
2351                                 }
2352                         }
2353                         break;
2354                 case HAMMER_CREATE_MODE_SYS:
2355                         bcopy(udata, ndata, leaf->data_len);
2356                         error = 0;
2357                         hammer_crc_set_leaf(ndata, leaf);
2358                         break;
2359                 default:
2360                         hpanic("bad mode %d", mode);
2361                         break; /* NOT REACHED */
2362                 }
2363                 hammer_modify_buffer_done(data_buffer);
2364         } else {
2365                 leaf->data_offset = 0;
2366                 error = 0;
2367                 ndata = NULL;
2368         }
2369         if (error)
2370                 goto failed;
2371
2372         /*
2373          * Do the insertion.  This can fail with a EDEADLK or EALREADY
2374          */
2375         cursor->flags |= HAMMER_CURSOR_INSERT;
2376         error = hammer_btree_lookup(cursor);
2377         if (error != ENOENT) {
2378                 if (error == 0)
2379                         error = EALREADY;
2380                 goto failed;
2381         }
2382         error = hammer_btree_insert(cursor, leaf, &doprop);
2383
2384         /*
2385          * Cursor is left on current element, we want to skip it now.
2386          * (in case the caller is scanning)
2387          */
2388         cursor->flags |= HAMMER_CURSOR_ATEDISK;
2389         cursor->flags &= ~HAMMER_CURSOR_INSERT;
2390
2391         /*
2392          * If the insertion happens to be creating (and not just replacing)
2393          * an inode we have to track it.
2394          */
2395         if (error == 0 &&
2396             leaf->base.rec_type == HAMMER_RECTYPE_INODE &&
2397             leaf->base.delete_tid == 0) {
2398                 hammer_modify_volume_field(trans, trans->rootvol,
2399                                            vol0_stat_inodes);
2400                 ++trans->hmp->rootvol->ondisk->vol0_stat_inodes;
2401                 hammer_modify_volume_done(trans->rootvol);
2402         }
2403
2404         /*
2405          * vol0_next_tid must track the highest TID stored in the filesystem.
2406          * We do not need to generate undo for this update.
2407          */
2408         high_tid = leaf->base.create_tid;
2409         if (high_tid < leaf->base.delete_tid)
2410                 high_tid = leaf->base.delete_tid;
2411         if (trans->rootvol->ondisk->vol0_next_tid < high_tid) {
2412                 hammer_modify_volume_noundo(trans, trans->rootvol);
2413                 trans->rootvol->ondisk->vol0_next_tid = high_tid;
2414                 hammer_modify_volume_done(trans->rootvol);
2415         }
2416
2417         /*
2418          * WARNING!  cursor's leaf pointer may have changed after
2419          *           do_propagation returns.
2420          */
2421         if (error == 0 && doprop)
2422                 hammer_btree_do_propagation(cursor, NULL, leaf);
2423
2424 failed:
2425         /*
2426          * Cleanup
2427          */
2428         if (error && leaf->data_offset) {
2429                 hammer_blockmap_free(trans, leaf->data_offset, leaf->data_len);
2430
2431         }
2432         hammer_sync_unlock(trans);
2433         if (data_buffer)
2434                 hammer_rel_buffer(data_buffer, 0);
2435         return (error);
2436 }
2437
2438 /*
2439  * Delete the B-Tree element at the current cursor and do any necessary
2440  * mirror propagation.
2441  *
2442  * The cursor must be properly positioned for an iteration on return but
2443  * may be pointing at an internal element.
2444  *
2445  * An element can be un-deleted by passing a delete_tid of 0 with
2446  * HAMMER_DELETE_ADJUST.
2447  *
2448  * This function will store the number of bytes deleted in *stat_bytes
2449  * if stat_bytes is not NULL.
2450  */
2451 int
2452 hammer_delete_at_cursor(hammer_cursor_t cursor, int delete_flags,
2453                         hammer_tid_t delete_tid, uint32_t delete_ts,
2454                         int track, int64_t *stat_bytes)
2455 {
2456         struct hammer_btree_leaf_elm save_leaf;
2457         hammer_transaction_t trans;
2458         hammer_btree_leaf_elm_t leaf;
2459         hammer_node_t node;
2460         hammer_btree_elm_t elm;
2461         hammer_off_t data_offset;
2462         int32_t data_len;
2463         int64_t bytes;
2464         int ndelete;
2465         int error;
2466         int icount;
2467         int doprop;
2468
2469         error = hammer_cursor_upgrade(cursor);
2470         if (error)
2471                 return(error);
2472
2473         trans = cursor->trans;
2474         node = cursor->node;
2475         elm = &node->ondisk->elms[cursor->index];
2476         leaf = &elm->leaf;
2477         KKASSERT(elm->base.btype == HAMMER_BTREE_TYPE_RECORD);
2478
2479         hammer_sync_lock_sh(trans);
2480         bytes = 0;
2481         doprop = 0;
2482         icount = 0;
2483
2484         /*
2485          * Adjust the delete_tid.  Update the mirror_tid propagation field
2486          * as well.  delete_tid can be 0 (undelete -- used by mirroring).
2487          */
2488         if (delete_flags & HAMMER_DELETE_ADJUST) {
2489                 if (elm->base.rec_type == HAMMER_RECTYPE_INODE) {
2490                         if (elm->leaf.base.delete_tid == 0 && delete_tid)
2491                                 icount = -1;
2492                         if (elm->leaf.base.delete_tid && delete_tid == 0)
2493                                 icount = 1;
2494                 }
2495
2496                 hammer_modify_node(trans, node, elm, sizeof(*elm));
2497                 elm->leaf.base.delete_tid = delete_tid;
2498                 elm->leaf.delete_ts = delete_ts;
2499                 hammer_modify_node_done(node);
2500
2501                 if (elm->leaf.base.delete_tid > node->ondisk->mirror_tid) {
2502                         hammer_modify_node_field(trans, node, mirror_tid);
2503                         node->ondisk->mirror_tid = elm->leaf.base.delete_tid;
2504                         hammer_modify_node_done(node);
2505                         doprop = 1;
2506                         if (hammer_debug_general & 0x0002) {
2507                                 hdkprintf("propagate %016llx @%016llx\n",
2508                                         (long long)elm->leaf.base.delete_tid,
2509                                         (long long)node->node_offset);
2510                         }
2511                 }
2512
2513                 /*
2514                  * Adjust for the iteration.  We have deleted the current
2515                  * element and want to clear ATEDISK so the iteration does
2516                  * not skip the element after, which now becomes the current
2517                  * element.  This element must be re-tested if doing an
2518                  * iteration, which is handled by the RETEST flag.
2519                  */
2520                 if ((cursor->flags & HAMMER_CURSOR_DISKEOF) == 0) {
2521                         cursor->flags |= HAMMER_CURSOR_RETEST;
2522                         cursor->flags &= ~HAMMER_CURSOR_ATEDISK;
2523                 }
2524
2525                 /*
2526                  * An on-disk record cannot have the same delete_tid
2527                  * as its create_tid.  In a chain of record updates
2528                  * this could result in a duplicate record.
2529                  */
2530                 KKASSERT(elm->leaf.base.delete_tid !=
2531                          elm->leaf.base.create_tid);
2532         }
2533
2534         /*
2535          * Destroy the B-Tree element if asked (typically if a nohistory
2536          * file or mount, or when called by the pruning code).
2537          *
2538          * Adjust the ATEDISK flag to properly support iterations.
2539          */
2540         if (delete_flags & HAMMER_DELETE_DESTROY) {
2541                 data_offset = elm->leaf.data_offset;
2542                 data_len = elm->leaf.data_len;
2543                 if (doprop) {
2544                         save_leaf = elm->leaf;
2545                         leaf = &save_leaf;
2546                 }
2547                 if (elm->base.rec_type == HAMMER_RECTYPE_INODE &&
2548                     elm->leaf.base.delete_tid == 0) {
2549                         icount = -1;
2550                 }
2551
2552                 error = hammer_btree_delete(cursor, &ndelete);
2553                 if (error == 0) {
2554                         /*
2555                          * The deletion moves the next element (if any) to
2556                          * the current element position.  We must clear
2557                          * ATEDISK so this element is not skipped and we
2558                          * must set RETEST to force any iteration to re-test
2559                          * the element.
2560                          */
2561                         if ((cursor->flags & HAMMER_CURSOR_DISKEOF) == 0) {
2562                                 cursor->flags |= HAMMER_CURSOR_RETEST;
2563                                 cursor->flags &= ~HAMMER_CURSOR_ATEDISK;
2564                         }
2565                         bytes += (ndelete * sizeof(struct hammer_node_ondisk));
2566
2567                         switch(data_offset & HAMMER_OFF_ZONE_MASK) {
2568                         case HAMMER_ZONE_LARGE_DATA:
2569                         case HAMMER_ZONE_SMALL_DATA:
2570                         case HAMMER_ZONE_META:
2571                                 hammer_blockmap_free(trans,
2572                                                      data_offset, data_len);
2573                                 bytes += data_len;
2574                                 break;
2575                         default:
2576                                 break;
2577                         }
2578                 }
2579         }
2580
2581         /*
2582          * Track inode count and next_tid.  This is used by the mirroring
2583          * and PFS code.  icount can be negative, zero, or positive.
2584          */
2585         if (error == 0 && track) {
2586                 if (icount) {
2587                         hammer_modify_volume_field(trans, trans->rootvol,
2588                                                    vol0_stat_inodes);
2589                         trans->rootvol->ondisk->vol0_stat_inodes += icount;
2590                         hammer_modify_volume_done(trans->rootvol);
2591                 }
2592                 if (trans->rootvol->ondisk->vol0_next_tid < delete_tid) {
2593                         hammer_modify_volume_noundo(trans, trans->rootvol);
2594                         trans->rootvol->ondisk->vol0_next_tid = delete_tid;
2595                         hammer_modify_volume_done(trans->rootvol);
2596                 }
2597         }
2598
2599         /*
2600          * mirror_tid propagation occurs if the node's mirror_tid had to be
2601          * updated while adjusting the delete_tid.
2602          *
2603          * This occurs when deleting even in nohistory mode, but does not
2604          * occur when pruning an already-deleted node.
2605          *
2606          * cursor->ip is NULL when called from the pruning, mirroring,
2607          * and pfs code.  If non-NULL propagation will be conditionalized
2608          * on whether the PFS is in no-history mode or not.
2609          *
2610          * WARNING: cursor's leaf pointer may have changed after do_propagation
2611          *          returns!
2612          */
2613         if (doprop) {
2614                 if (cursor->ip)
2615                         hammer_btree_do_propagation(cursor, cursor->ip->pfsm, leaf);
2616                 else
2617                         hammer_btree_do_propagation(cursor, NULL, leaf);
2618         }
2619         if (stat_bytes)
2620                 *stat_bytes = bytes;
2621         hammer_sync_unlock(trans);
2622         return (error);
2623 }
2624
2625 /*
2626  * Determine whether we can remove a directory.  This routine checks whether
2627  * a directory is empty or not and enforces flush connectivity.
2628  *
2629  * Flush connectivity requires that we block if the target directory is
2630  * currently flushing, otherwise it may not end up in the same flush group.
2631  *
2632  * Returns 0 on success, ENOTEMPTY or EDEADLK (or other errors) on failure.
2633  */
2634 int
2635 hammer_ip_check_directory_empty(hammer_transaction_t trans, hammer_inode_t ip)
2636 {
2637         struct hammer_cursor cursor;
2638         int error;
2639
2640         /*
2641          * Check directory empty
2642          */
2643         hammer_init_cursor(trans, &cursor, &ip->cache[1], ip);
2644
2645         cursor.key_beg.localization = ip->obj_localization +
2646                                       hammer_dir_localization(ip);
2647         cursor.key_beg.obj_id = ip->obj_id;
2648         cursor.key_beg.create_tid = 0;
2649         cursor.key_beg.delete_tid = 0;
2650         cursor.key_beg.obj_type = 0;
2651         cursor.key_beg.rec_type = HAMMER_RECTYPE_ENTRY_START;
2652         cursor.key_beg.key = HAMMER_MIN_KEY;
2653
2654         cursor.key_end = cursor.key_beg;
2655         cursor.key_end.rec_type = HAMMER_RECTYPE_MAX;
2656         cursor.key_end.key = HAMMER_MAX_KEY;
2657
2658         cursor.asof = ip->obj_asof;
2659         cursor.flags |= HAMMER_CURSOR_END_INCLUSIVE | HAMMER_CURSOR_ASOF;
2660
2661         error = hammer_ip_first(&cursor);
2662         if (error == ENOENT)
2663                 error = 0;
2664         else if (error == 0)
2665                 error = ENOTEMPTY;
2666         hammer_done_cursor(&cursor);
2667         return(error);
2668 }
2669
2670 /*
2671  * Localize the data payload.  Directory entries may need their
2672  * localization adjusted.
2673  */
2674 static
2675 int
2676 hammer_cursor_localize_data(hammer_data_ondisk_t data,
2677                             hammer_btree_leaf_elm_t leaf)
2678 {
2679         uint32_t localization;
2680
2681         if (leaf->base.rec_type == HAMMER_RECTYPE_DIRENTRY) {
2682                 localization = leaf->base.localization &
2683                                HAMMER_LOCALIZE_PSEUDOFS_MASK;
2684                 if (data->entry.localization != localization) {
2685                         data->entry.localization = localization;
2686                         hammer_crc_set_leaf(data, leaf);
2687                 }
2688         }
2689         return(0);
2690 }