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