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