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