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