0795b2298702f680a9ccd2364faf80ce9dd71af8
[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.68 2008/06/14 01:42:13 dillon Exp $
35  */
36
37 #include "hammer.h"
38
39 static int hammer_mem_add(hammer_record_t record);
40 static int hammer_mem_lookup(hammer_cursor_t cursor);
41 static int hammer_mem_first(hammer_cursor_t cursor);
42 static int hammer_rec_trunc_callback(hammer_record_t record,
43                                 void *data __unused);
44
45 struct rec_trunc_info {
46         u_int16_t       rec_type;
47         int64_t         trunc_off;
48 };
49
50 /*
51  * Red-black tree support.  Comparison code for insertion.
52  */
53 static int
54 hammer_rec_rb_compare(hammer_record_t rec1, hammer_record_t rec2)
55 {
56         if (rec1->leaf.base.rec_type < rec2->leaf.base.rec_type)
57                 return(-1);
58         if (rec1->leaf.base.rec_type > rec2->leaf.base.rec_type)
59                 return(1);
60
61         if (rec1->leaf.base.key < rec2->leaf.base.key)
62                 return(-1);
63         if (rec1->leaf.base.key > rec2->leaf.base.key)
64                 return(1);
65
66         /*
67          * Never match against an item deleted by the front-end.
68          *
69          * rec1 is greater then rec2 if rec1 is marked deleted.
70          * rec1 is less then rec2 if rec2 is marked deleted.
71          *
72          * Multiple deleted records may be present, do not return 0
73          * if both are marked deleted.
74          */
75         if (rec1->flags & HAMMER_RECF_DELETED_FE)
76                 return(1);
77         if (rec2->flags & HAMMER_RECF_DELETED_FE)
78                 return(-1);
79
80         return(0);
81 }
82
83 /*
84  * Basic record comparison code similar to hammer_btree_cmp().
85  */
86 static int
87 hammer_rec_cmp(hammer_base_elm_t elm, hammer_record_t rec)
88 {
89         if (elm->rec_type < rec->leaf.base.rec_type)
90                 return(-3);
91         if (elm->rec_type > rec->leaf.base.rec_type)
92                 return(3);
93
94         if (elm->key < rec->leaf.base.key)
95                 return(-2);
96         if (elm->key > rec->leaf.base.key)
97                 return(2);
98
99         /*
100          * Never match against an item deleted by the front-end.
101          * elm is less then rec if rec is marked deleted.
102          */
103         if (rec->flags & HAMMER_RECF_DELETED_FE)
104                 return(-1);
105         return(0);
106 }
107
108 /*
109  * Special LOOKUP_INFO to locate an overlapping record.  This used by
110  * the reservation code to implement small-block records (whos keys will
111  * be different depending on data_len, when representing the same base
112  * offset).
113  *
114  * NOTE: The base file offset of a data record is (key - data_len), not (key).
115  */
116 static int
117 hammer_rec_overlap_compare(hammer_btree_leaf_elm_t leaf, hammer_record_t rec)
118 {
119         if (leaf->base.rec_type < rec->leaf.base.rec_type)
120                 return(-3);
121         if (leaf->base.rec_type > rec->leaf.base.rec_type)
122                 return(3);
123
124         if (leaf->base.rec_type == HAMMER_RECTYPE_DATA) {
125                 /* leaf_end <= rec_beg */
126                 if (leaf->base.key <= rec->leaf.base.key - rec->leaf.data_len)
127                         return(-2);
128                 /* leaf_beg >= rec_end */
129                 if (leaf->base.key - leaf->data_len >= rec->leaf.base.key)
130                         return(2);
131         } else {
132                 if (leaf->base.key < rec->leaf.base.key)
133                         return(-2);
134                 if (leaf->base.key > rec->leaf.base.key)
135                         return(2);
136         }
137
138         /*
139          * Never match against an item deleted by the front-end.
140          * leaf is less then rec if rec is marked deleted.
141          */
142         if (rec->flags & HAMMER_RECF_DELETED_FE)
143                 return(-1);
144         return(0);
145 }
146
147 /*
148  * RB_SCAN comparison code for hammer_mem_first().  The argument order
149  * is reversed so the comparison result has to be negated.  key_beg and
150  * key_end are both range-inclusive.
151  *
152  * Localized deletions are not cached in-memory.
153  */
154 static
155 int
156 hammer_rec_scan_cmp(hammer_record_t rec, void *data)
157 {
158         hammer_cursor_t cursor = data;
159         int r;
160
161         r = hammer_rec_cmp(&cursor->key_beg, rec);
162         if (r > 1)
163                 return(-1);
164         r = hammer_rec_cmp(&cursor->key_end, rec);
165         if (r < -1)
166                 return(1);
167         return(0);
168 }
169
170 /*
171  * This compare function is used when simply looking up key_beg.
172  */
173 static
174 int
175 hammer_rec_find_cmp(hammer_record_t rec, void *data)
176 {
177         hammer_cursor_t cursor = data;
178         int r;
179
180         r = hammer_rec_cmp(&cursor->key_beg, rec);
181         if (r > 1)
182                 return(-1);
183         if (r < -1)
184                 return(1);
185         return(0);
186 }
187
188 /*
189  * Locate blocks within the truncation range.  Partial blocks do not count.
190  */
191 static
192 int
193 hammer_rec_trunc_cmp(hammer_record_t rec, void *data)
194 {
195         struct rec_trunc_info *info = data;
196
197         if (rec->leaf.base.rec_type < info->rec_type)
198                 return(-1);
199         if (rec->leaf.base.rec_type > info->rec_type)
200                 return(1);
201
202         switch(rec->leaf.base.rec_type) {
203         case HAMMER_RECTYPE_DB:
204                 /*
205                  * DB record key is not beyond the truncation point, retain.
206                  */
207                 if (rec->leaf.base.key < info->trunc_off)
208                         return(-1);
209                 break;
210         case HAMMER_RECTYPE_DATA:
211                 /*
212                  * DATA record offset start is not beyond the truncation point,
213                  * retain.
214                  */
215                 if (rec->leaf.base.key - rec->leaf.data_len < info->trunc_off)
216                         return(-1);
217                 break;
218         default:
219                 panic("hammer_rec_trunc_cmp: unexpected record type");
220         }
221
222         /*
223          * The record start is >= the truncation point, return match,
224          * the record should be destroyed.
225          */
226         return(0);
227 }
228
229 RB_GENERATE(hammer_rec_rb_tree, hammer_record, rb_node, hammer_rec_rb_compare);
230 RB_GENERATE_XLOOKUP(hammer_rec_rb_tree, INFO, hammer_record, rb_node,
231                     hammer_rec_overlap_compare, hammer_btree_leaf_elm_t);
232
233 /*
234  * Allocate a record for the caller to finish filling in.  The record is
235  * returned referenced.
236  */
237 hammer_record_t
238 hammer_alloc_mem_record(hammer_inode_t ip, int data_len)
239 {
240         hammer_record_t record;
241
242         ++hammer_count_records;
243         record = kmalloc(sizeof(*record), M_HAMMER, M_WAITOK | M_ZERO);
244         record->flush_state = HAMMER_FST_IDLE;
245         record->ip = ip;
246         record->leaf.base.btype = HAMMER_BTREE_TYPE_RECORD;
247         record->leaf.data_len = data_len;
248         hammer_ref(&record->lock);
249
250         if (data_len) {
251                 record->data = kmalloc(data_len, M_HAMMER, M_WAITOK | M_ZERO);
252                 record->flags |= HAMMER_RECF_ALLOCDATA;
253                 ++hammer_count_record_datas;
254         }
255
256         return (record);
257 }
258
259 void
260 hammer_wait_mem_record_ident(hammer_record_t record, const char *ident)
261 {
262         while (record->flush_state == HAMMER_FST_FLUSH) {
263                 record->flags |= HAMMER_RECF_WANTED;
264                 tsleep(record, 0, ident, 0);
265         }
266 }
267
268 /*
269  * Called from the backend, hammer_inode.c, after a record has been
270  * flushed to disk.  The record has been exclusively locked by the
271  * caller and interlocked with BE.
272  *
273  * We clean up the state, unlock, and release the record (the record
274  * was referenced by the fact that it was in the HAMMER_FST_FLUSH state).
275  */
276 void
277 hammer_flush_record_done(hammer_record_t record, int error)
278 {
279         hammer_inode_t target_ip;
280
281         KKASSERT(record->flush_state == HAMMER_FST_FLUSH);
282         KKASSERT(record->flags & HAMMER_RECF_INTERLOCK_BE);
283
284         if (error) {
285                 /*
286                  * An error occured, the backend was unable to sync the
287                  * record to its media.  Leave the record intact.
288                  */
289                 Debugger("flush_record_done error");
290         }
291
292         if (record->flags & HAMMER_RECF_DELETED_BE) {
293                 if ((target_ip = record->target_ip) != NULL) {
294                         TAILQ_REMOVE(&target_ip->target_list, record,
295                                      target_entry);
296                         record->target_ip = NULL;
297                         hammer_test_inode(target_ip);
298                 }
299                 record->flush_state = HAMMER_FST_IDLE;
300         } else {
301                 if (record->target_ip) {
302                         record->flush_state = HAMMER_FST_SETUP;
303                         hammer_test_inode(record->ip);
304                         hammer_test_inode(record->target_ip);
305                 } else {
306                         record->flush_state = HAMMER_FST_IDLE;
307                 }
308         }
309         record->flags &= ~HAMMER_RECF_INTERLOCK_BE;
310         if (record->flags & HAMMER_RECF_WANTED) {
311                 record->flags &= ~HAMMER_RECF_WANTED;
312                 wakeup(record);
313         }
314         hammer_rel_mem_record(record);
315 }
316
317 /*
318  * Release a memory record.  Records marked for deletion are immediately
319  * removed from the RB-Tree but otherwise left intact until the last ref
320  * goes away.
321  */
322 void
323 hammer_rel_mem_record(struct hammer_record *record)
324 {
325         hammer_inode_t ip, target_ip;
326
327         hammer_unref(&record->lock);
328
329         if (record->lock.refs == 0) {
330                 /*
331                  * Upon release of the last reference wakeup any waiters.
332                  * The record structure may get destroyed so callers will
333                  * loop up and do a relookup.
334                  *
335                  * WARNING!  Record must be removed from RB-TREE before we
336                  * might possibly block.  hammer_test_inode() can block!
337                  */
338                 ip = record->ip;
339
340                 /*
341                  * Upon release of the last reference a record marked deleted
342                  * is destroyed.
343                  */
344                 if (record->flags & HAMMER_RECF_DELETED_FE) {
345                         KKASSERT(ip->lock.refs > 0);
346                         KKASSERT(record->flush_state != HAMMER_FST_FLUSH);
347
348                         /*
349                          * target_ip may have zero refs, we have to ref it
350                          * to prevent it from being ripped out from under
351                          * us.
352                          */
353                         if ((target_ip = record->target_ip) != NULL) {
354                                 TAILQ_REMOVE(&target_ip->target_list,
355                                              record, target_entry);
356                                 record->target_ip = NULL;
357                                 hammer_ref(&target_ip->lock);
358                         }
359
360                         if (record->flags & HAMMER_RECF_ONRBTREE) {
361                                 RB_REMOVE(hammer_rec_rb_tree,
362                                           &record->ip->rec_tree,
363                                           record);
364                                 KKASSERT(ip->rsv_recs > 0);
365                                 --ip->hmp->rsv_recs;
366                                 --ip->rsv_recs;
367                                 ip->hmp->rsv_databytes -= record->leaf.data_len;
368                                 record->flags &= ~HAMMER_RECF_ONRBTREE;
369
370                                 if ((ip->flags & HAMMER_INODE_PARTIALW) &&
371                                     ip->rsv_recs <= hammer_limit_irecs) {
372                                         ip->flags &= ~HAMMER_INODE_PARTIALW;
373                                         wakeup(&ip->flags);
374                                 }
375                                 if (RB_EMPTY(&record->ip->rec_tree)) {
376                                         record->ip->flags &= ~HAMMER_INODE_XDIRTY;
377                                         record->ip->sync_flags &= ~HAMMER_INODE_XDIRTY;
378                                         hammer_test_inode(record->ip);
379                                 }
380                         }
381
382                         /*
383                          * Do this test after removing record from the B-Tree.
384                          */
385                         if (target_ip) {
386                                 hammer_test_inode(target_ip);
387                                 hammer_rel_inode(target_ip, 0);
388                         }
389
390                         if (record->flags & HAMMER_RECF_ALLOCDATA) {
391                                 --hammer_count_record_datas;
392                                 kfree(record->data, M_HAMMER);
393                                 record->flags &= ~HAMMER_RECF_ALLOCDATA;
394                         }
395                         if (record->resv) {
396                                 hammer_blockmap_reserve_complete(ip->hmp,
397                                                                  record->resv);
398                                 record->resv = NULL;
399                         }
400                         record->data = NULL;
401                         --hammer_count_records;
402                         kfree(record, M_HAMMER);
403                 }
404         }
405 }
406
407 /*
408  * Record visibility depends on whether the record is being accessed by
409  * the backend or the frontend.
410  *
411  * Return non-zero if the record is visible, zero if it isn't or if it is
412  * deleted.
413  */
414 static __inline
415 int
416 hammer_ip_iterate_mem_good(hammer_cursor_t cursor, hammer_record_t record)
417 {
418         if (cursor->flags & HAMMER_CURSOR_BACKEND) {
419                 if (record->flags & HAMMER_RECF_DELETED_BE)
420                         return(0);
421         } else {
422                 if (record->flags & HAMMER_RECF_DELETED_FE)
423                         return(0);
424         }
425         return(1);
426 }
427
428 /*
429  * This callback is used as part of the RB_SCAN function for in-memory
430  * records.  We terminate it (return -1) as soon as we get a match.
431  *
432  * This routine is used by frontend code.
433  *
434  * The primary compare code does not account for ASOF lookups.  This
435  * code handles that case as well as a few others.
436  */
437 static
438 int
439 hammer_rec_scan_callback(hammer_record_t rec, void *data)
440 {
441         hammer_cursor_t cursor = data;
442
443         /*
444          * We terminate on success, so this should be NULL on entry.
445          */
446         KKASSERT(cursor->iprec == NULL);
447
448         /*
449          * Skip if the record was marked deleted.
450          */
451         if (hammer_ip_iterate_mem_good(cursor, rec) == 0)
452                 return(0);
453
454         /*
455          * Skip if not visible due to our as-of TID
456          */
457         if (cursor->flags & HAMMER_CURSOR_ASOF) {
458                 if (cursor->asof < rec->leaf.base.create_tid)
459                         return(0);
460                 if (rec->leaf.base.delete_tid &&
461                     cursor->asof >= rec->leaf.base.delete_tid) {
462                         return(0);
463                 }
464         }
465
466         /*
467          * If the record is queued to the flusher we have to block until
468          * it isn't.  Otherwise we may see duplication between our memory
469          * cache and the media.
470          */
471         hammer_ref(&rec->lock);
472
473 #warning "This deadlocks"
474 #if 0
475         if (rec->flush_state == HAMMER_FST_FLUSH)
476                 hammer_wait_mem_record(rec);
477 #endif
478
479         /*
480          * The record may have been deleted while we were blocked.
481          */
482         if (hammer_ip_iterate_mem_good(cursor, rec) == 0) {
483                 hammer_rel_mem_record(rec);
484                 return(0);
485         }
486
487         /*
488          * Set the matching record and stop the scan.
489          */
490         cursor->iprec = rec;
491         return(-1);
492 }
493
494
495 /*
496  * Lookup an in-memory record given the key specified in the cursor.  Works
497  * just like hammer_btree_lookup() but operates on an inode's in-memory
498  * record list.
499  *
500  * The lookup must fail if the record is marked for deferred deletion.
501  */
502 static
503 int
504 hammer_mem_lookup(hammer_cursor_t cursor)
505 {
506         int error;
507
508         KKASSERT(cursor->ip);
509         if (cursor->iprec) {
510                 hammer_rel_mem_record(cursor->iprec);
511                 cursor->iprec = NULL;
512         }
513         hammer_rec_rb_tree_RB_SCAN(&cursor->ip->rec_tree, hammer_rec_find_cmp,
514                                    hammer_rec_scan_callback, cursor);
515
516         if (cursor->iprec == NULL)
517                 error = ENOENT;
518         else
519                 error = 0;
520         return(error);
521 }
522
523 /*
524  * hammer_mem_first() - locate the first in-memory record matching the
525  * cursor within the bounds of the key range.
526  */
527 static
528 int
529 hammer_mem_first(hammer_cursor_t cursor)
530 {
531         hammer_inode_t ip;
532
533         ip = cursor->ip;
534         KKASSERT(ip != NULL);
535
536         if (cursor->iprec) {
537                 hammer_rel_mem_record(cursor->iprec);
538                 cursor->iprec = NULL;
539         }
540
541         hammer_rec_rb_tree_RB_SCAN(&ip->rec_tree, hammer_rec_scan_cmp,
542                                    hammer_rec_scan_callback, cursor);
543
544         /*
545          * Adjust scan.node and keep it linked into the RB-tree so we can
546          * hold the cursor through third party modifications of the RB-tree.
547          */
548         if (cursor->iprec)
549                 return(0);
550         return(ENOENT);
551 }
552
553 void
554 hammer_mem_done(hammer_cursor_t cursor)
555 {
556         if (cursor->iprec) {
557                 hammer_rel_mem_record(cursor->iprec);
558                 cursor->iprec = NULL;
559         }
560 }
561
562 /************************************************************************
563  *                   HAMMER IN-MEMORY RECORD FUNCTIONS                  *
564  ************************************************************************
565  *
566  * These functions manipulate in-memory records.  Such records typically
567  * exist prior to being committed to disk or indexed via the on-disk B-Tree.
568  */
569
570 /*
571  * Add a directory entry (dip,ncp) which references inode (ip).
572  *
573  * Note that the low 32 bits of the namekey are set temporarily to create
574  * a unique in-memory record, and may be modified a second time when the
575  * record is synchronized to disk.  In particular, the low 32 bits cannot be
576  * all 0's when synching to disk, which is not handled here.
577  */
578 int
579 hammer_ip_add_directory(struct hammer_transaction *trans,
580                      struct hammer_inode *dip, struct namecache *ncp,
581                      struct hammer_inode *ip)
582 {
583         hammer_record_t record;
584         int error;
585         int bytes;
586
587         bytes = ncp->nc_nlen;   /* NOTE: terminating \0 is NOT included */
588         record = hammer_alloc_mem_record(dip, HAMMER_ENTRY_SIZE(bytes));
589         if (++trans->hmp->namekey_iterator == 0)
590                 ++trans->hmp->namekey_iterator;
591
592         record->type = HAMMER_MEM_RECORD_ADD;
593         record->leaf.base.localization = HAMMER_LOCALIZE_MISC;
594         record->leaf.base.obj_id = dip->obj_id;
595         record->leaf.base.key = hammer_directory_namekey(ncp->nc_name, bytes);
596         record->leaf.base.key += trans->hmp->namekey_iterator;
597         record->leaf.base.rec_type = HAMMER_RECTYPE_DIRENTRY;
598         record->leaf.base.obj_type = ip->ino_leaf.base.obj_type;
599         record->data->entry.obj_id = ip->obj_id;
600         bcopy(ncp->nc_name, record->data->entry.name, bytes);
601
602         ++ip->ino_data.nlinks;
603         hammer_modify_inode(ip, HAMMER_INODE_DDIRTY);
604
605         /*
606          * The target inode and the directory entry are bound together.
607          */
608         record->target_ip = ip;
609         record->flush_state = HAMMER_FST_SETUP;
610         TAILQ_INSERT_TAIL(&ip->target_list, record, target_entry);
611
612         /*
613          * The inode now has a dependancy and must be taken out of the idle
614          * state.  An inode not in an idle state is given an extra reference.
615          */
616         if (ip->flush_state == HAMMER_FST_IDLE) {
617                 hammer_ref(&ip->lock);
618                 ip->flush_state = HAMMER_FST_SETUP;
619         }
620         error = hammer_mem_add(record);
621         return(error);
622 }
623
624 /*
625  * Delete the directory entry and update the inode link count.  The
626  * cursor must be seeked to the directory entry record being deleted.
627  *
628  * The related inode should be share-locked by the caller.  The caller is
629  * on the frontend.
630  *
631  * This function can return EDEADLK requiring the caller to terminate
632  * the cursor, any locks, wait on the returned record, and retry.
633  */
634 int
635 hammer_ip_del_directory(struct hammer_transaction *trans,
636                      hammer_cursor_t cursor, struct hammer_inode *dip,
637                      struct hammer_inode *ip)
638 {
639         hammer_record_t record;
640         int error;
641
642         if (hammer_cursor_inmem(cursor)) {
643                 /*
644                  * In-memory (unsynchronized) records can simply be freed.
645                  * Even though the HAMMER_RECF_DELETED_FE flag is ignored
646                  * by the backend, we must still avoid races against the
647                  * backend potentially syncing the record to the media. 
648                  *
649                  * We cannot call hammer_ip_delete_record(), that routine may
650                  * only be called from the backend.
651                  */
652                 record = cursor->iprec;
653                 if (record->flags & HAMMER_RECF_INTERLOCK_BE) {
654                         KKASSERT(cursor->deadlk_rec == NULL);
655                         hammer_ref(&record->lock);
656                         cursor->deadlk_rec = record;
657                         error = EDEADLK;
658                 } else {
659                         KKASSERT(record->type == HAMMER_MEM_RECORD_ADD);
660                         record->flags |= HAMMER_RECF_DELETED_FE;
661                         error = 0;
662                 }
663         } else {
664                 /*
665                  * If the record is on-disk we have to queue the deletion by
666                  * the record's key.  This also causes lookups to skip the
667                  * record.
668                  */
669                 KKASSERT(dip->flags &
670                          (HAMMER_INODE_ONDISK | HAMMER_INODE_DONDISK));
671                 record = hammer_alloc_mem_record(dip, 0);
672                 record->type = HAMMER_MEM_RECORD_DEL;
673                 record->leaf.base = cursor->leaf->base;
674
675                 record->target_ip = ip;
676                 record->flush_state = HAMMER_FST_SETUP;
677                 TAILQ_INSERT_TAIL(&ip->target_list, record, target_entry);
678
679                 /*
680                  * The inode now has a dependancy and must be taken out of
681                  * the idle state.  An inode not in an idle state is given
682                  * an extra reference.
683                  */
684                 if (ip->flush_state == HAMMER_FST_IDLE) {
685                         hammer_ref(&ip->lock);
686                         ip->flush_state = HAMMER_FST_SETUP;
687                 }
688
689                 error = hammer_mem_add(record);
690         }
691
692         /*
693          * One less link.  The file may still be open in the OS even after
694          * all links have gone away.
695          *
696          * We have to terminate the cursor before syncing the inode to
697          * avoid deadlocking against ourselves.  XXX this may no longer
698          * be true.
699          *
700          * If nlinks drops to zero and the vnode is inactive (or there is
701          * no vnode), call hammer_inode_unloadable_check() to zonk the
702          * inode.  If we don't do this here the inode will not be destroyed
703          * on-media until we unmount.
704          */
705         if (error == 0) {
706                 --ip->ino_data.nlinks;
707                 hammer_modify_inode(ip, HAMMER_INODE_DDIRTY);
708                 if (ip->ino_data.nlinks == 0 &&
709                     (ip->vp == NULL || (ip->vp->v_flag & VINACTIVE))) {
710                         hammer_done_cursor(cursor);
711                         hammer_inode_unloadable_check(ip, 1);
712                         hammer_flush_inode(ip, 0);
713                 }
714
715         }
716         return(error);
717 }
718
719 /*
720  * Add a record to an inode.
721  *
722  * The caller must allocate the record with hammer_alloc_mem_record(ip) and
723  * initialize the following additional fields:
724  *
725  * The related inode should be share-locked by the caller.  The caller is
726  * on the frontend.
727  *
728  * record->rec.entry.base.base.key
729  * record->rec.entry.base.base.rec_type
730  * record->rec.entry.base.base.data_len
731  * record->data         (a copy will be kmalloc'd if it cannot be embedded)
732  */
733 int
734 hammer_ip_add_record(struct hammer_transaction *trans, hammer_record_t record)
735 {
736         hammer_inode_t ip = record->ip;
737         int error;
738
739         KKASSERT(record->leaf.base.localization != 0);
740         record->leaf.base.obj_id = ip->obj_id;
741         record->leaf.base.obj_type = ip->ino_leaf.base.obj_type;
742         error = hammer_mem_add(record);
743         return(error);
744 }
745
746 /*
747  * Locate a bulk record in-memory.  Bulk records allow disk space to be
748  * reserved so the front-end can flush large data writes without having
749  * to queue the BIO to the flusher.  Only the related record gets queued
750  * to the flusher.
751  */
752 static hammer_record_t
753 hammer_ip_get_bulk(hammer_inode_t ip, off_t file_offset, int bytes)
754 {
755         hammer_record_t record;
756         struct hammer_btree_leaf_elm leaf;
757
758         bzero(&leaf, sizeof(leaf));
759         leaf.base.obj_id = ip->obj_id;
760         leaf.base.key = file_offset + bytes;
761         leaf.base.create_tid = 0;
762         leaf.base.delete_tid = 0;
763         leaf.base.rec_type = HAMMER_RECTYPE_DATA;
764         leaf.base.obj_type = 0;                 /* unused */
765         leaf.base.btype = HAMMER_BTREE_TYPE_RECORD;     /* unused */
766         leaf.base.localization = HAMMER_LOCALIZE_MISC;
767         leaf.data_len = bytes;
768
769         record = hammer_rec_rb_tree_RB_LOOKUP_INFO(&ip->rec_tree, &leaf);
770         if (record)
771                 hammer_ref(&record->lock);
772         return(record);
773 }
774
775 /*
776  * Reserve blockmap space placemarked with an in-memory record.  
777  *
778  * This routine is called by the front-end in order to be able to directly
779  * flush a buffer cache buffer.
780  */
781 hammer_record_t
782 hammer_ip_add_bulk(hammer_inode_t ip, off_t file_offset, void *data, int bytes,
783                    int *errorp)
784 {
785         hammer_record_t record;
786         hammer_record_t conflict;
787         int zone;
788         int flags;
789
790         /*
791          * Deal with conflicting in-memory records.  We cannot have multiple
792          * in-memory records for the same offset without seriously confusing
793          * the backend, including but not limited to the backend issuing
794          * delete-create-delete sequences and asserting on the delete_tid
795          * being the same as the create_tid.
796          *
797          * If we encounter a record with the backend interlock set we cannot
798          * immediately delete it without confusing the backend.
799          */
800         while ((conflict = hammer_ip_get_bulk(ip, file_offset, bytes)) !=NULL) {
801                 if (conflict->flags & HAMMER_RECF_INTERLOCK_BE) {
802                         conflict->flags |= HAMMER_RECF_WANTED;
803                         tsleep(conflict, 0, "hmrrc3", 0);
804                 } else {
805                         conflict->flags |= HAMMER_RECF_DELETED_FE;
806                 }
807                 hammer_rel_mem_record(conflict);
808         }
809
810         /*
811          * Create a record to cover the direct write.  This is called with
812          * the related BIO locked so there should be no possible conflict.
813          *
814          * The backend is responsible for finalizing the space reserved in
815          * this record.
816          *
817          * XXX bytes not aligned, depend on the reservation code to
818          * align the reservation.
819          */
820         record = hammer_alloc_mem_record(ip, 0);
821         zone = (bytes >= HAMMER_BUFSIZE) ? HAMMER_ZONE_LARGE_DATA_INDEX :
822                                            HAMMER_ZONE_SMALL_DATA_INDEX;
823         record->resv = hammer_blockmap_reserve(ip->hmp, zone, bytes,
824                                                &record->leaf.data_offset,
825                                                errorp);
826         if (record->resv == NULL) {
827                 kprintf("hammer_ip_add_bulk: reservation failed\n");
828                 hammer_rel_mem_record(record);
829                 return(NULL);
830         }
831         record->type = HAMMER_MEM_RECORD_DATA;
832         record->leaf.base.rec_type = HAMMER_RECTYPE_DATA;
833         record->leaf.base.obj_type = ip->ino_leaf.base.obj_type;
834         record->leaf.base.obj_id = ip->obj_id;
835         record->leaf.base.key = file_offset + bytes;
836         record->leaf.base.localization = HAMMER_LOCALIZE_MISC;
837         record->leaf.data_len = bytes;
838         record->leaf.data_crc = crc32(data, bytes);
839         flags = record->flags;
840
841         hammer_ref(&record->lock);      /* mem_add eats a reference */
842         *errorp = hammer_mem_add(record);
843         KKASSERT(*errorp == 0);
844
845         return (record);
846 }
847
848 /*
849  * Frontend truncation code.  Scan in-memory records only.  On-disk records
850  * and records in a flushing state are handled by the backend.  The vnops
851  * setattr code will handle the block containing the truncation point.
852  *
853  * Partial blocks are not deleted.
854  */
855 int
856 hammer_ip_frontend_trunc(struct hammer_inode *ip, off_t file_size)
857 {
858         struct rec_trunc_info info;
859
860         switch(ip->ino_data.obj_type) {
861         case HAMMER_OBJTYPE_REGFILE:
862                 info.rec_type = HAMMER_RECTYPE_DATA;
863                 break;
864         case HAMMER_OBJTYPE_DBFILE:
865                 info.rec_type = HAMMER_RECTYPE_DB;
866                 break;
867         default:
868                 return(EINVAL);
869         }
870         info.trunc_off = file_size;
871         hammer_rec_rb_tree_RB_SCAN(&ip->rec_tree, hammer_rec_trunc_cmp,
872                                    hammer_rec_trunc_callback, &info);
873         return(0);
874 }
875
876 static int
877 hammer_rec_trunc_callback(hammer_record_t record, void *data __unused)
878 {
879         if (record->flags & HAMMER_RECF_DELETED_FE)
880                 return(0);
881         if (record->flush_state == HAMMER_FST_FLUSH)
882                 return(0);
883         KKASSERT((record->flags & HAMMER_RECF_INTERLOCK_BE) == 0);
884         hammer_ref(&record->lock);
885         record->flags |= HAMMER_RECF_DELETED_FE;
886         hammer_rel_mem_record(record);
887         return(0);
888 }
889
890 /*
891  * Backend code.  Sync a record to the media.
892  */
893 int
894 hammer_ip_sync_record_cursor(hammer_cursor_t cursor, hammer_record_t record)
895 {
896         hammer_transaction_t trans = cursor->trans;
897         int64_t file_offset;
898         void *bdata;
899         int error;
900
901         KKASSERT(record->flush_state == HAMMER_FST_FLUSH);
902         KKASSERT(record->flags & HAMMER_RECF_INTERLOCK_BE);
903         KKASSERT(record->leaf.base.localization != 0);
904
905         /*
906          * If this is a bulk-data record placemarker there may be an existing
907          * record on-disk, indicating a data overwrite.  If there is the
908          * on-disk record must be deleted before we can insert our new record.
909          *
910          * We've synthesized this record and do not know what the create_tid
911          * on-disk is, nor how much data it represents.
912          *
913          * Keep in mind that (key) for data records is (base_offset + len),
914          * not (base_offset).  Also, we only want to get rid of on-disk
915          * records since we are trying to sync our in-memory record, call
916          * hammer_ip_delete_range() with truncating set to 1 to make sure
917          * it skips in-memory records.
918          *
919          * It is ok for the lookup to return ENOENT.
920          */
921         if (record->type == HAMMER_MEM_RECORD_DATA) {
922                 file_offset = record->leaf.base.key - record->leaf.data_len;
923                 KKASSERT((file_offset & HAMMER_BUFMASK) == 0);
924                 error = hammer_ip_delete_range(
925                                 cursor, record->ip,
926                                 file_offset, file_offset + HAMMER_BUFSIZE - 1,
927                                 1);
928                 if (error && error != ENOENT)
929                         goto done;
930         }
931
932         /*
933          * Setup the cursor.
934          */
935         hammer_normalize_cursor(cursor);
936         cursor->key_beg = record->leaf.base;
937         cursor->flags &= ~HAMMER_CURSOR_INITMASK;
938         cursor->flags |= HAMMER_CURSOR_BACKEND;
939         cursor->flags &= ~HAMMER_CURSOR_INSERT;
940
941         /*
942          * Records can wind up on-media before the inode itself is on-media.
943          * Flag the case.
944          */
945         record->ip->flags |= HAMMER_INODE_DONDISK;
946
947         /*
948          * If we are deleting a directory entry an exact match must be
949          * found on-disk.
950          */
951         if (record->type == HAMMER_MEM_RECORD_DEL) {
952                 error = hammer_btree_lookup(cursor);
953                 if (error == 0) {
954                         error = hammer_ip_delete_record(cursor, record->ip,
955                                                         trans->tid);
956                         if (error == 0) {
957                                 record->flags |= HAMMER_RECF_DELETED_FE;
958                                 record->flags |= HAMMER_RECF_DELETED_BE;
959                         }
960                 }
961                 goto done;
962         }
963
964         /*
965          * We are inserting.
966          *
967          * Issue a lookup to position the cursor and locate the cluster.  The
968          * target key should not exist.  If we are creating a directory entry
969          * we may have to iterate the low 32 bits of the key to find an unused
970          * key.
971          */
972         cursor->flags |= HAMMER_CURSOR_INSERT;
973
974         for (;;) {
975                 error = hammer_btree_lookup(cursor);
976                 if (hammer_debug_inode)
977                         kprintf("DOINSERT LOOKUP %d\n", error);
978                 if (error)
979                         break;
980                 if (record->leaf.base.rec_type != HAMMER_RECTYPE_DIRENTRY) {
981                         kprintf("hammer_ip_sync_record: duplicate rec "
982                                 "at (%016llx)\n", record->leaf.base.key);
983                         Debugger("duplicate record1");
984                         error = EIO;
985                         break;
986                 }
987                 if (++trans->hmp->namekey_iterator == 0)
988                         ++trans->hmp->namekey_iterator;
989                 record->leaf.base.key &= ~(0xFFFFFFFFLL);
990                 record->leaf.base.key |= trans->hmp->namekey_iterator;
991                 cursor->key_beg.key = record->leaf.base.key;
992         }
993 #if 0
994         if (record->type == HAMMER_MEM_RECORD_DATA)
995                 kprintf("sync_record  %016llx ---------------- %016llx %d\n",
996                         record->leaf.base.key - record->leaf.data_len,
997                         record->leaf.data_offset, error);
998 #endif
999                         
1000
1001         if (error != ENOENT)
1002                 goto done;
1003
1004         /*
1005          * Allocate the record and data.  The result buffers will be
1006          * marked as being modified and further calls to
1007          * hammer_modify_buffer() will result in unneeded UNDO records.
1008          *
1009          * Support zero-fill records (data == NULL and data_len != 0)
1010          */
1011         if (record->type == HAMMER_MEM_RECORD_DATA) {
1012                 /*
1013                  * The data portion of a bulk-data record has already been
1014                  * committed to disk, we need only adjust the layer2
1015                  * statistics in the same transaction as our B-Tree insert.
1016                  */
1017                 KKASSERT(record->leaf.data_offset != 0);
1018                 hammer_blockmap_free(trans, record->leaf.data_offset,
1019                                      -record->leaf.data_len);
1020                 error = 0;
1021         } else if (record->data && record->leaf.data_len) {
1022                 /*
1023                  * Wholely cached record, with data.  Allocate the data.
1024                  */
1025                 bdata = hammer_alloc_data(trans, record->leaf.data_len,
1026                                           record->leaf.base.rec_type,
1027                                           &record->leaf.data_offset,
1028                                           &cursor->data_buffer, &error);
1029                 if (bdata == NULL)
1030                         goto done;
1031                 record->leaf.data_crc = crc32(record->data,
1032                                               record->leaf.data_len);
1033                 hammer_modify_buffer(trans, cursor->data_buffer, NULL, 0);
1034                 bcopy(record->data, bdata, record->leaf.data_len);
1035                 hammer_modify_buffer_done(cursor->data_buffer);
1036         } else {
1037                 /*
1038                  * Wholely cached record, without data.
1039                  */
1040                 record->leaf.data_offset = 0;
1041                 record->leaf.data_crc = 0;
1042         }
1043
1044         error = hammer_btree_insert(cursor, &record->leaf);
1045         if (hammer_debug_inode && error)
1046                 kprintf("BTREE INSERT error %d @ %016llx:%d key %016llx\n", error, cursor->node->node_offset, cursor->index, record->leaf.base.key);
1047
1048         /*
1049          * Our record is on-disk, normally mark the in-memory version as
1050          * deleted.  If the record represented a directory deletion but
1051          * we had to sync a valid directory entry to disk we must convert
1052          * the record to a covering delete so the frontend does not have
1053          * visibility on the synced entry.
1054          */
1055         if (error == 0) {
1056                 if (record->flags & HAMMER_RECF_CONVERT_DELETE) {
1057                         KKASSERT(record->type == HAMMER_MEM_RECORD_ADD);
1058                         record->flags &= ~HAMMER_RECF_DELETED_FE;
1059                         record->type = HAMMER_MEM_RECORD_DEL;
1060                         KKASSERT(record->flush_state == HAMMER_FST_FLUSH);
1061                         record->flags &= ~HAMMER_RECF_CONVERT_DELETE;
1062                         /* hammer_flush_record_done takes care of the rest */
1063                 } else {
1064                         record->flags |= HAMMER_RECF_DELETED_FE;
1065                         record->flags |= HAMMER_RECF_DELETED_BE;
1066                 }
1067         } else {
1068                 if (record->leaf.data_offset) {
1069                         hammer_blockmap_free(trans, record->leaf.data_offset,
1070                                              record->leaf.data_len);
1071                 }
1072         }
1073
1074 done:
1075         return(error);
1076 }
1077
1078 /*
1079  * Add the record to the inode's rec_tree.  The low 32 bits of a directory
1080  * entry's key is used to deal with hash collisions in the upper 32 bits.
1081  * A unique 64 bit key is generated in-memory and may be regenerated a
1082  * second time when the directory record is flushed to the on-disk B-Tree.
1083  *
1084  * A referenced record is passed to this function.  This function
1085  * eats the reference.  If an error occurs the record will be deleted.
1086  *
1087  * A copy of the temporary record->data pointer provided by the caller
1088  * will be made.
1089  */
1090 static
1091 int
1092 hammer_mem_add(hammer_record_t record)
1093 {
1094         hammer_mount_t hmp = record->ip->hmp;
1095
1096         /*
1097          * Make a private copy of record->data
1098          */
1099         if (record->data)
1100                 KKASSERT(record->flags & HAMMER_RECF_ALLOCDATA);
1101
1102         /*
1103          * Insert into the RB tree, find an unused iterator if this is
1104          * a directory entry.
1105          */
1106         while (RB_INSERT(hammer_rec_rb_tree, &record->ip->rec_tree, record)) {
1107                 if (record->leaf.base.rec_type != HAMMER_RECTYPE_DIRENTRY){
1108                         record->flags |= HAMMER_RECF_DELETED_FE;
1109                         hammer_rel_mem_record(record);
1110                         return (EEXIST);
1111                 }
1112                 if (++hmp->namekey_iterator == 0)
1113                         ++hmp->namekey_iterator;
1114                 record->leaf.base.key &= ~(0xFFFFFFFFLL);
1115                 record->leaf.base.key |= hmp->namekey_iterator;
1116         }
1117         ++hmp->rsv_recs;
1118         ++record->ip->rsv_recs;
1119         record->ip->hmp->rsv_databytes += record->leaf.data_len;
1120         record->flags |= HAMMER_RECF_ONRBTREE;
1121         hammer_modify_inode(record->ip, HAMMER_INODE_XDIRTY);
1122         hammer_rel_mem_record(record);
1123         return(0);
1124 }
1125
1126 /************************************************************************
1127  *                   HAMMER INODE MERGED-RECORD FUNCTIONS               *
1128  ************************************************************************
1129  *
1130  * These functions augment the B-Tree scanning functions in hammer_btree.c
1131  * by merging in-memory records with on-disk records.
1132  */
1133
1134 /*
1135  * Locate a particular record either in-memory or on-disk.
1136  *
1137  * NOTE: This is basically a standalone routine, hammer_ip_next() may
1138  * NOT be called to iterate results.
1139  */
1140 int
1141 hammer_ip_lookup(hammer_cursor_t cursor)
1142 {
1143         int error;
1144
1145         /*
1146          * If the element is in-memory return it without searching the
1147          * on-disk B-Tree
1148          */
1149         KKASSERT(cursor->ip);
1150         error = hammer_mem_lookup(cursor);
1151         if (error == 0) {
1152                 cursor->leaf = &cursor->iprec->leaf;
1153                 return(error);
1154         }
1155         if (error != ENOENT)
1156                 return(error);
1157
1158         /*
1159          * If the inode has on-disk components search the on-disk B-Tree.
1160          */
1161         if ((cursor->ip->flags & (HAMMER_INODE_ONDISK|HAMMER_INODE_DONDISK)) == 0)
1162                 return(error);
1163         error = hammer_btree_lookup(cursor);
1164         if (error == 0)
1165                 error = hammer_btree_extract(cursor, HAMMER_CURSOR_GET_LEAF);
1166         return(error);
1167 }
1168
1169 /*
1170  * Locate the first record within the cursor's key_beg/key_end range,
1171  * restricted to a particular inode.  0 is returned on success, ENOENT
1172  * if no records matched the requested range, or some other error.
1173  *
1174  * When 0 is returned hammer_ip_next() may be used to iterate additional
1175  * records within the requested range.
1176  *
1177  * This function can return EDEADLK, requiring the caller to terminate
1178  * the cursor and try again.
1179  */
1180 int
1181 hammer_ip_first(hammer_cursor_t cursor)
1182 {
1183         hammer_inode_t ip = cursor->ip;
1184         int error;
1185
1186         KKASSERT(ip != NULL);
1187
1188         /*
1189          * Clean up fields and setup for merged scan
1190          */
1191         cursor->flags &= ~HAMMER_CURSOR_DELBTREE;
1192         cursor->flags |= HAMMER_CURSOR_ATEDISK | HAMMER_CURSOR_ATEMEM;
1193         cursor->flags |= HAMMER_CURSOR_DISKEOF | HAMMER_CURSOR_MEMEOF;
1194         if (cursor->iprec) {
1195                 hammer_rel_mem_record(cursor->iprec);
1196                 cursor->iprec = NULL;
1197         }
1198
1199         /*
1200          * Search the on-disk B-Tree.  hammer_btree_lookup() only does an
1201          * exact lookup so if we get ENOENT we have to call the iterate
1202          * function to validate the first record after the begin key.
1203          *
1204          * The ATEDISK flag is used by hammer_btree_iterate to determine
1205          * whether it must index forwards or not.  It is also used here
1206          * to select the next record from in-memory or on-disk.
1207          *
1208          * EDEADLK can only occur if the lookup hit an empty internal
1209          * element and couldn't delete it.  Since this could only occur
1210          * in-range, we can just iterate from the failure point.
1211          */
1212         if (ip->flags & (HAMMER_INODE_ONDISK|HAMMER_INODE_DONDISK)) {
1213                 error = hammer_btree_lookup(cursor);
1214                 if (error == ENOENT || error == EDEADLK) {
1215                         cursor->flags &= ~HAMMER_CURSOR_ATEDISK;
1216                         if (hammer_debug_general & 0x2000)
1217                                 kprintf("error %d node %p %016llx index %d\n", error, cursor->node, cursor->node->node_offset, cursor->index);
1218                         error = hammer_btree_iterate(cursor);
1219                 }
1220                 if (error && error != ENOENT) 
1221                         return(error);
1222                 if (error == 0) {
1223                         cursor->flags &= ~HAMMER_CURSOR_DISKEOF;
1224                         cursor->flags &= ~HAMMER_CURSOR_ATEDISK;
1225                 } else {
1226                         cursor->flags |= HAMMER_CURSOR_ATEDISK;
1227                 }
1228         }
1229
1230         /*
1231          * Search the in-memory record list (Red-Black tree).  Unlike the
1232          * B-Tree search, mem_first checks for records in the range.
1233          */
1234         error = hammer_mem_first(cursor);
1235         if (error && error != ENOENT)
1236                 return(error);
1237         if (error == 0) {
1238                 cursor->flags &= ~HAMMER_CURSOR_MEMEOF;
1239                 cursor->flags &= ~HAMMER_CURSOR_ATEMEM;
1240                 if (hammer_ip_iterate_mem_good(cursor, cursor->iprec) == 0)
1241                         cursor->flags |= HAMMER_CURSOR_ATEMEM;
1242         }
1243
1244         /*
1245          * This will return the first matching record.
1246          */
1247         return(hammer_ip_next(cursor));
1248 }
1249
1250 /*
1251  * Retrieve the next record in a merged iteration within the bounds of the
1252  * cursor.  This call may be made multiple times after the cursor has been
1253  * initially searched with hammer_ip_first().
1254  *
1255  * 0 is returned on success, ENOENT if no further records match the
1256  * requested range, or some other error code is returned.
1257  */
1258 int
1259 hammer_ip_next(hammer_cursor_t cursor)
1260 {
1261         hammer_btree_elm_t elm;
1262         hammer_record_t rec, save;
1263         int error;
1264         int r;
1265
1266 next_btree:
1267         /*
1268          * Load the current on-disk and in-memory record.  If we ate any
1269          * records we have to get the next one. 
1270          *
1271          * If we deleted the last on-disk record we had scanned ATEDISK will
1272          * be clear and DELBTREE will be set, forcing a call to iterate. The
1273          * fact that ATEDISK is clear causes iterate to re-test the 'current'
1274          * element.  If ATEDISK is set, iterate will skip the 'current'
1275          * element.
1276          *
1277          * Get the next on-disk record
1278          */
1279         if (cursor->flags & (HAMMER_CURSOR_ATEDISK|HAMMER_CURSOR_DELBTREE)) {
1280                 if ((cursor->flags & HAMMER_CURSOR_DISKEOF) == 0) {
1281                         error = hammer_btree_iterate(cursor);
1282                         cursor->flags &= ~HAMMER_CURSOR_DELBTREE;
1283                         if (error == 0)
1284                                 cursor->flags &= ~HAMMER_CURSOR_ATEDISK;
1285                         else
1286                                 cursor->flags |= HAMMER_CURSOR_DISKEOF |
1287                                                  HAMMER_CURSOR_ATEDISK;
1288                 }
1289         }
1290
1291 next_memory:
1292         /*
1293          * Get the next in-memory record.  The record can be ripped out
1294          * of the RB tree so we maintain a scan_info structure to track
1295          * the next node.
1296          *
1297          * hammer_rec_scan_cmp:  Is the record still in our general range,
1298          *                       (non-inclusive of snapshot exclusions)?
1299          * hammer_rec_scan_callback: Is the record in our snapshot?
1300          */
1301         if (cursor->flags & HAMMER_CURSOR_ATEMEM) {
1302                 if ((cursor->flags & HAMMER_CURSOR_MEMEOF) == 0) {
1303                         save = cursor->iprec;
1304                         cursor->iprec = NULL;
1305                         rec = save ? hammer_rec_rb_tree_RB_NEXT(save) : NULL;
1306                         while (rec) {
1307                                 if (hammer_rec_scan_cmp(rec, cursor) != 0)
1308                                         break;
1309                                 if (hammer_rec_scan_callback(rec, cursor) != 0)
1310                                         break;
1311                                 rec = hammer_rec_rb_tree_RB_NEXT(rec);
1312                         }
1313                         if (save)
1314                                 hammer_rel_mem_record(save);
1315                         if (cursor->iprec) {
1316                                 KKASSERT(cursor->iprec == rec);
1317                                 cursor->flags &= ~HAMMER_CURSOR_ATEMEM;
1318                         } else {
1319                                 cursor->flags |= HAMMER_CURSOR_MEMEOF;
1320                         }
1321                 }
1322         }
1323
1324         /*
1325          * The memory record may have become stale while being held in
1326          * cursor->iprec.  We are interlocked against the backend on 
1327          * with regards to B-Tree entries.
1328          */
1329         if ((cursor->flags & HAMMER_CURSOR_ATEMEM) == 0) {
1330                 if (hammer_ip_iterate_mem_good(cursor, cursor->iprec) == 0) {
1331                         cursor->flags |= HAMMER_CURSOR_ATEMEM;
1332                         goto next_memory;
1333                 }
1334         }
1335
1336         /*
1337          * Extract either the disk or memory record depending on their
1338          * relative position.
1339          */
1340         error = 0;
1341         switch(cursor->flags & (HAMMER_CURSOR_ATEDISK | HAMMER_CURSOR_ATEMEM)) {
1342         case 0:
1343                 /*
1344                  * Both entries valid.   Compare the entries and nominally
1345                  * return the first one in the sort order.  Numerous cases
1346                  * require special attention, however.
1347                  */
1348                 elm = &cursor->node->ondisk->elms[cursor->index];
1349                 r = hammer_btree_cmp(&elm->base, &cursor->iprec->leaf.base);
1350
1351                 /*
1352                  * If the two entries differ only by their key (-2/2) or
1353                  * create_tid (-1/1), and are DATA records, we may have a
1354                  * nominal match.  We have to calculate the base file
1355                  * offset of the data.
1356                  */
1357                 if (r <= 2 && r >= -2 && r != 0 &&
1358                     cursor->ip->ino_data.obj_type == HAMMER_OBJTYPE_REGFILE &&
1359                     cursor->iprec->type == HAMMER_MEM_RECORD_DATA) {
1360                         int64_t base1 = elm->leaf.base.key - elm->leaf.data_len;
1361                         int64_t base2 = cursor->iprec->leaf.base.key -
1362                                         cursor->iprec->leaf.data_len;
1363                         if (base1 == base2)
1364                                 r = 0;
1365                 }
1366
1367                 if (r < 0) {
1368                         error = hammer_btree_extract(cursor,
1369                                                      HAMMER_CURSOR_GET_LEAF);
1370                         cursor->flags |= HAMMER_CURSOR_ATEDISK;
1371                         break;
1372                 }
1373
1374                 /*
1375                  * If the entries match exactly the memory entry is either
1376                  * an on-disk directory entry deletion or a bulk data
1377                  * overwrite.  If it is a directory entry deletion we eat
1378                  * both entries.
1379                  *
1380                  * For the bulk-data overwrite case it is possible to have
1381                  * visibility into both, which simply means the syncer
1382                  * hasn't gotten around to doing the delete+insert sequence
1383                  * on the B-Tree.  Use the memory entry and throw away the
1384                  * on-disk entry.
1385                  *
1386                  * If the in-memory record is not either of these we
1387                  * probably caught the syncer while it was syncing it to
1388                  * the media.  Since we hold a shared lock on the cursor,
1389                  * the in-memory record had better be marked deleted at
1390                  * this point.
1391                  */
1392                 if (r == 0) {
1393                         if (cursor->iprec->type == HAMMER_MEM_RECORD_DEL) {
1394                                 if ((cursor->flags & HAMMER_CURSOR_DELETE_VISIBILITY) == 0) {
1395                                         cursor->flags |= HAMMER_CURSOR_ATEDISK;
1396                                         cursor->flags |= HAMMER_CURSOR_ATEMEM;
1397                                         goto next_btree;
1398                                 }
1399                         } else if (cursor->iprec->type == HAMMER_MEM_RECORD_DATA) {
1400                                 if ((cursor->flags & HAMMER_CURSOR_DELETE_VISIBILITY) == 0) {
1401                                         cursor->flags |= HAMMER_CURSOR_ATEDISK;
1402                                 }
1403                                 /* fall through to memory entry */
1404                         } else {
1405                                 panic("hammer_ip_next: duplicate mem/b-tree entry");
1406                                 cursor->flags |= HAMMER_CURSOR_ATEMEM;
1407                                 goto next_memory;
1408                         }
1409                 }
1410                 /* fall through to the memory entry */
1411         case HAMMER_CURSOR_ATEDISK:
1412                 /*
1413                  * Only the memory entry is valid.
1414                  */
1415                 cursor->leaf = &cursor->iprec->leaf;
1416                 cursor->flags |= HAMMER_CURSOR_ATEMEM;
1417
1418                 /*
1419                  * If the memory entry is an on-disk deletion we should have
1420                  * also had found a B-Tree record.  If the backend beat us
1421                  * to it it would have interlocked the cursor and we should
1422                  * have seen the in-memory record marked DELETED_FE.
1423                  */
1424                 if (cursor->iprec->type == HAMMER_MEM_RECORD_DEL &&
1425                     (cursor->flags & HAMMER_CURSOR_DELETE_VISIBILITY) == 0) {
1426                         panic("hammer_ip_next: del-on-disk with no b-tree entry");
1427                 }
1428                 break;
1429         case HAMMER_CURSOR_ATEMEM:
1430                 /*
1431                  * Only the disk entry is valid
1432                  */
1433                 error = hammer_btree_extract(cursor, HAMMER_CURSOR_GET_LEAF);
1434                 cursor->flags |= HAMMER_CURSOR_ATEDISK;
1435                 break;
1436         default:
1437                 /*
1438                  * Neither entry is valid
1439                  *
1440                  * XXX error not set properly
1441                  */
1442                 cursor->leaf = NULL;
1443                 error = ENOENT;
1444                 break;
1445         }
1446         return(error);
1447 }
1448
1449 /*
1450  * Resolve the cursor->data pointer for the current cursor position in
1451  * a merged iteration.
1452  */
1453 int
1454 hammer_ip_resolve_data(hammer_cursor_t cursor)
1455 {
1456         hammer_record_t record;
1457         int error;
1458
1459         if (hammer_cursor_inmem(cursor)) {
1460                 /*
1461                  * The data associated with an in-memory record is usually
1462                  * kmalloced, but reserve-ahead data records will have an
1463                  * on-disk reference.
1464                  *
1465                  * NOTE: Reserve-ahead data records must be handled in the
1466                  * context of the related high level buffer cache buffer
1467                  * to interlock against async writes.
1468                  */
1469                 record = cursor->iprec;
1470                 cursor->data = record->data;
1471                 error = 0;
1472                 if (cursor->data == NULL) {
1473                         KKASSERT(record->leaf.base.rec_type ==
1474                                  HAMMER_RECTYPE_DATA);
1475                         cursor->data = hammer_bread(cursor->trans->hmp,
1476                                                     record->leaf.data_offset,
1477                                                     &error,
1478                                                     &cursor->data_buffer);
1479                 }
1480         } else {
1481                 cursor->leaf = &cursor->node->ondisk->elms[cursor->index].leaf;
1482                 error = hammer_btree_extract(cursor, HAMMER_CURSOR_GET_DATA);
1483         }
1484         return(error);
1485 }
1486
1487 /*
1488  * Backend truncation / record replacement - delete records in range.
1489  *
1490  * Delete all records within the specified range for inode ip.  In-memory
1491  * records still associated with the frontend are ignored.
1492  *
1493  * NOTE: An unaligned range will cause new records to be added to cover
1494  * the edge cases. (XXX not implemented yet).
1495  *
1496  * NOTE: Replacement via reservations (see hammer_ip_sync_record_cursor())
1497  * also do not deal with unaligned ranges.
1498  *
1499  * NOTE: ran_end is inclusive (e.g. 0,1023 instead of 0,1024).
1500  *
1501  * NOTE: Record keys for regular file data have to be special-cased since
1502  * they indicate the end of the range (key = base + bytes).
1503  */
1504 int
1505 hammer_ip_delete_range(hammer_cursor_t cursor, hammer_inode_t ip,
1506                        int64_t ran_beg, int64_t ran_end, int truncating)
1507 {
1508         hammer_transaction_t trans = cursor->trans;
1509         hammer_btree_leaf_elm_t leaf;
1510         int error;
1511         int64_t off;
1512
1513 #if 0
1514         kprintf("delete_range %p %016llx-%016llx\n", ip, ran_beg, ran_end);
1515 #endif
1516
1517         KKASSERT(trans->type == HAMMER_TRANS_FLS);
1518 retry:
1519         hammer_normalize_cursor(cursor);
1520         cursor->key_beg.localization = HAMMER_LOCALIZE_MISC;
1521         cursor->key_beg.obj_id = ip->obj_id;
1522         cursor->key_beg.create_tid = 0;
1523         cursor->key_beg.delete_tid = 0;
1524         cursor->key_beg.obj_type = 0;
1525         cursor->asof = ip->obj_asof;
1526         cursor->flags &= ~HAMMER_CURSOR_INITMASK;
1527         cursor->flags |= HAMMER_CURSOR_ASOF;
1528         cursor->flags |= HAMMER_CURSOR_DELETE_VISIBILITY;
1529         cursor->flags |= HAMMER_CURSOR_BACKEND;
1530
1531         cursor->key_end = cursor->key_beg;
1532         if (ip->ino_data.obj_type == HAMMER_OBJTYPE_DBFILE) {
1533                 cursor->key_beg.key = ran_beg;
1534                 cursor->key_beg.rec_type = HAMMER_RECTYPE_DB;
1535                 cursor->key_end.rec_type = HAMMER_RECTYPE_DB;
1536                 cursor->key_end.key = ran_end;
1537         } else {
1538                 /*
1539                  * The key in the B-Tree is (base+bytes), so the first possible
1540                  * matching key is ran_beg + 1.
1541                  */
1542                 int64_t tmp64;
1543
1544                 cursor->key_beg.key = ran_beg + 1;
1545                 cursor->key_beg.rec_type = HAMMER_RECTYPE_DATA;
1546                 cursor->key_end.rec_type = HAMMER_RECTYPE_DATA;
1547
1548                 tmp64 = ran_end + MAXPHYS + 1;  /* work around GCC-4 bug */
1549                 if (tmp64 < ran_end)
1550                         cursor->key_end.key = 0x7FFFFFFFFFFFFFFFLL;
1551                 else
1552                         cursor->key_end.key = ran_end + MAXPHYS + 1;
1553         }
1554         cursor->flags |= HAMMER_CURSOR_END_INCLUSIVE;
1555
1556         error = hammer_ip_first(cursor);
1557
1558         /*
1559          * Iterate through matching records and mark them as deleted.
1560          */
1561         while (error == 0) {
1562                 leaf = cursor->leaf;
1563
1564                 KKASSERT(leaf->base.delete_tid == 0);
1565
1566                 /*
1567                  * There may be overlap cases for regular file data.  Also
1568                  * remember the key for a regular file record is (base + len),
1569                  * NOT (base).
1570                  */
1571                 if (leaf->base.rec_type == HAMMER_RECTYPE_DATA) {
1572                         off = leaf->base.key - leaf->data_len;
1573                         /*
1574                          * Check the left edge case.  We currently do not
1575                          * split existing records.
1576                          */
1577                         if (off < ran_beg) {
1578                                 panic("hammer left edge case %016llx %d\n",
1579                                         leaf->base.key, leaf->data_len);
1580                         }
1581
1582                         /*
1583                          * Check the right edge case.  Note that the
1584                          * record can be completely out of bounds, which
1585                          * terminates the search.
1586                          *
1587                          * base->key is exclusive of the right edge while
1588                          * ran_end is inclusive of the right edge.  The
1589                          * (key - data_len) left boundary is inclusive.
1590                          *
1591                          * XXX theory-check this test at some point, are
1592                          * we missing a + 1 somewhere?  Note that ran_end
1593                          * could overflow.
1594                          */
1595                         if (leaf->base.key - 1 > ran_end) {
1596                                 if (leaf->base.key - leaf->data_len > ran_end)
1597                                         break;
1598                                 panic("hammer right edge case\n");
1599                         }
1600                 }
1601
1602                 /*
1603                  * Delete the record.  When truncating we do not delete
1604                  * in-memory (data) records because they represent data
1605                  * written after the truncation.
1606                  *
1607                  * This will also physically destroy the B-Tree entry and
1608                  * data if the retention policy dictates.  The function
1609                  * will set HAMMER_CURSOR_DELBTREE which hammer_ip_next()
1610                  * uses to perform a fixup.
1611                  */
1612                 if (truncating == 0 || hammer_cursor_ondisk(cursor))
1613                         error = hammer_ip_delete_record(cursor, ip, trans->tid);
1614                 if (error)
1615                         break;
1616                 error = hammer_ip_next(cursor);
1617         }
1618         if (error == EDEADLK) {
1619                 hammer_done_cursor(cursor);
1620                 error = hammer_init_cursor(trans, cursor, &ip->cache[0], ip);
1621                 if (error == 0)
1622                         goto retry;
1623         }
1624         if (error == ENOENT)
1625                 error = 0;
1626         return(error);
1627 }
1628
1629 /*
1630  * Backend truncation - delete all records.
1631  *
1632  * Delete all user records associated with an inode except the inode record
1633  * itself.  Directory entries are not deleted (they must be properly disposed
1634  * of or nlinks would get upset).
1635  */
1636 int
1637 hammer_ip_delete_range_all(hammer_cursor_t cursor, hammer_inode_t ip,
1638                            int *countp)
1639 {
1640         hammer_transaction_t trans = cursor->trans;
1641         hammer_btree_leaf_elm_t leaf;
1642         int error;
1643
1644         KKASSERT(trans->type == HAMMER_TRANS_FLS);
1645 retry:
1646         hammer_normalize_cursor(cursor);
1647         cursor->key_beg.localization = HAMMER_LOCALIZE_MISC;
1648         cursor->key_beg.obj_id = ip->obj_id;
1649         cursor->key_beg.create_tid = 0;
1650         cursor->key_beg.delete_tid = 0;
1651         cursor->key_beg.obj_type = 0;
1652         cursor->key_beg.rec_type = HAMMER_RECTYPE_INODE + 1;
1653         cursor->key_beg.key = HAMMER_MIN_KEY;
1654
1655         cursor->key_end = cursor->key_beg;
1656         cursor->key_end.rec_type = 0xFFFF;
1657         cursor->key_end.key = HAMMER_MAX_KEY;
1658
1659         cursor->asof = ip->obj_asof;
1660         cursor->flags &= ~HAMMER_CURSOR_INITMASK;
1661         cursor->flags |= HAMMER_CURSOR_END_INCLUSIVE | HAMMER_CURSOR_ASOF;
1662         cursor->flags |= HAMMER_CURSOR_DELETE_VISIBILITY;
1663         cursor->flags |= HAMMER_CURSOR_BACKEND;
1664
1665         error = hammer_ip_first(cursor);
1666
1667         /*
1668          * Iterate through matching records and mark them as deleted.
1669          */
1670         while (error == 0) {
1671                 leaf = cursor->leaf;
1672
1673                 KKASSERT(leaf->base.delete_tid == 0);
1674
1675                 /*
1676                  * Mark the record and B-Tree entry as deleted.  This will
1677                  * also physically delete the B-Tree entry, record, and
1678                  * data if the retention policy dictates.  The function
1679                  * will set HAMMER_CURSOR_DELBTREE which hammer_ip_next()
1680                  * uses to perform a fixup.
1681                  *
1682                  * Directory entries (and delete-on-disk directory entries)
1683                  * must be synced and cannot be deleted.
1684                  */
1685                 if (leaf->base.rec_type != HAMMER_RECTYPE_DIRENTRY) {
1686                         error = hammer_ip_delete_record(cursor, ip, trans->tid);
1687                         ++*countp;
1688                 }
1689                 if (error)
1690                         break;
1691                 error = hammer_ip_next(cursor);
1692         }
1693         if (error == EDEADLK) {
1694                 hammer_done_cursor(cursor);
1695                 error = hammer_init_cursor(trans, cursor, &ip->cache[0], ip);
1696                 if (error == 0)
1697                         goto retry;
1698         }
1699         if (error == ENOENT)
1700                 error = 0;
1701         return(error);
1702 }
1703
1704 /*
1705  * Delete the record at the current cursor.  On success the cursor will
1706  * be positioned appropriately for an iteration but may no longer be at
1707  * a leaf node.
1708  *
1709  * This routine is only called from the backend.
1710  *
1711  * NOTE: This can return EDEADLK, requiring the caller to terminate the
1712  * cursor and retry.
1713  */
1714 int
1715 hammer_ip_delete_record(hammer_cursor_t cursor, hammer_inode_t ip,
1716                         hammer_tid_t tid)
1717 {
1718         hammer_btree_elm_t elm;
1719         hammer_mount_t hmp;
1720         int error;
1721         int dodelete;
1722
1723         KKASSERT(cursor->flags & HAMMER_CURSOR_BACKEND);
1724         KKASSERT(tid != 0);
1725
1726         /*
1727          * In-memory (unsynchronized) records can simply be freed.  This
1728          * only occurs in range iterations since all other records are
1729          * individually synchronized.  Thus there should be no confusion with
1730          * the interlock.
1731          */
1732         if (hammer_cursor_inmem(cursor)) {
1733                 KKASSERT((cursor->iprec->flags & HAMMER_RECF_INTERLOCK_BE) ==0);
1734                 cursor->iprec->flags |= HAMMER_RECF_DELETED_FE;
1735                 cursor->iprec->flags |= HAMMER_RECF_DELETED_BE;
1736                 return(0);
1737         }
1738
1739         /*
1740          * On-disk records are marked as deleted by updating their delete_tid.
1741          * This does not effect their position in the B-Tree (which is based
1742          * on their create_tid).
1743          */
1744         error = hammer_btree_extract(cursor, HAMMER_CURSOR_GET_LEAF);
1745         elm = NULL;
1746         hmp = cursor->node->hmp;
1747
1748         /*
1749          * If we were mounted with the nohistory option, we physically
1750          * delete the record.
1751          */
1752         dodelete = hammer_nohistory(ip);
1753
1754         if (error == 0) {
1755                 error = hammer_cursor_upgrade(cursor);
1756                 if (error == 0) {
1757                         elm = &cursor->node->ondisk->elms[cursor->index];
1758                         hammer_modify_node(cursor->trans, cursor->node,
1759                                            &elm->leaf.base.delete_tid,
1760                                            sizeof(elm->leaf.base.delete_tid));
1761                         elm->leaf.base.delete_tid = tid;
1762                         hammer_modify_node_done(cursor->node);
1763
1764                         /*
1765                          * An on-disk record cannot have the same delete_tid
1766                          * as its create_tid.  In a chain of record updates
1767                          * this could result in a duplicate record.
1768                          */
1769                         KKASSERT(elm->leaf.base.delete_tid != elm->leaf.base.create_tid);
1770                 }
1771         }
1772
1773         if (error == 0 && dodelete) {
1774                 error = hammer_delete_at_cursor(cursor, NULL);
1775                 if (error) {
1776                         panic("hammer_ip_delete_record: unable to physically delete the record!\n");
1777                         error = 0;
1778                 }
1779         }
1780         return(error);
1781 }
1782
1783 int
1784 hammer_delete_at_cursor(hammer_cursor_t cursor, int64_t *stat_bytes)
1785 {
1786         hammer_btree_elm_t elm;
1787         hammer_off_t data_offset;
1788         int32_t data_len;
1789         u_int16_t rec_type;
1790         int error;
1791
1792         elm = &cursor->node->ondisk->elms[cursor->index];
1793         KKASSERT(elm->base.btype == HAMMER_BTREE_TYPE_RECORD);
1794
1795         data_offset = elm->leaf.data_offset;
1796         data_len = elm->leaf.data_len;
1797         rec_type = elm->leaf.base.rec_type;
1798
1799         error = hammer_btree_delete(cursor);
1800         if (error == 0) {
1801                 /*
1802                  * This forces a fixup for the iteration because
1803                  * the cursor is now either sitting at the 'next'
1804                  * element or sitting at the end of a leaf.
1805                  */
1806                 if ((cursor->flags & HAMMER_CURSOR_DISKEOF) == 0) {
1807                         cursor->flags |= HAMMER_CURSOR_DELBTREE;
1808                         cursor->flags &= ~HAMMER_CURSOR_ATEDISK;
1809                 }
1810         }
1811         if (error == 0) {
1812                 switch(data_offset & HAMMER_OFF_ZONE_MASK) {
1813                 case HAMMER_ZONE_LARGE_DATA:
1814                 case HAMMER_ZONE_SMALL_DATA:
1815                 case HAMMER_ZONE_META:
1816                         hammer_blockmap_free(cursor->trans,
1817                                              data_offset, data_len);
1818                         break;
1819                 default:
1820                         break;
1821                 }
1822         }
1823         return (error);
1824 }
1825
1826 /*
1827  * Determine whether we can remove a directory.  This routine checks whether
1828  * a directory is empty or not and enforces flush connectivity.
1829  *
1830  * Flush connectivity requires that we block if the target directory is
1831  * currently flushing, otherwise it may not end up in the same flush group.
1832  *
1833  * Returns 0 on success, ENOTEMPTY or EDEADLK (or other errors) on failure.
1834  */
1835 int
1836 hammer_ip_check_directory_empty(hammer_transaction_t trans, hammer_inode_t ip)
1837 {
1838         struct hammer_cursor cursor;
1839         int error;
1840
1841         /*
1842          * Check directory empty
1843          */
1844         hammer_init_cursor(trans, &cursor, &ip->cache[0], ip);
1845
1846         cursor.key_beg.localization = HAMMER_LOCALIZE_MISC;
1847         cursor.key_beg.obj_id = ip->obj_id;
1848         cursor.key_beg.create_tid = 0;
1849         cursor.key_beg.delete_tid = 0;
1850         cursor.key_beg.obj_type = 0;
1851         cursor.key_beg.rec_type = HAMMER_RECTYPE_INODE + 1;
1852         cursor.key_beg.key = HAMMER_MIN_KEY;
1853
1854         cursor.key_end = cursor.key_beg;
1855         cursor.key_end.rec_type = 0xFFFF;
1856         cursor.key_end.key = HAMMER_MAX_KEY;
1857
1858         cursor.asof = ip->obj_asof;
1859         cursor.flags |= HAMMER_CURSOR_END_INCLUSIVE | HAMMER_CURSOR_ASOF;
1860
1861         error = hammer_ip_first(&cursor);
1862         if (error == ENOENT)
1863                 error = 0;
1864         else if (error == 0)
1865                 error = ENOTEMPTY;
1866         hammer_done_cursor(&cursor);
1867         return(error);
1868 }
1869