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