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