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