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