kernel - Add callout debugging
[dragonfly.git] / sys / kern / vfs_journal.c
1 /*
2  * Copyright (c) 2004-2006 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 /*
35  * The journaling protocol is intended to evolve into a two-way stream
36  * whereby transaction IDs can be acknowledged by the journaling target
37  * when the data has been committed to hard storage.  Both implicit and
38  * explicit acknowledgement schemes will be supported, depending on the
39  * sophistication of the journaling stream, plus resynchronization and
40  * restart when a journaling stream is interrupted.  This information will
41  * also be made available to journaling-aware filesystems to allow better
42  * management of their own physical storage synchronization mechanisms as
43  * well as to allow such filesystems to take direct advantage of the kernel's
44  * journaling layer so they don't have to roll their own.
45  *
46  * In addition, the worker thread will have access to much larger 
47  * spooling areas then the memory buffer is able to provide by e.g. 
48  * reserving swap space, in order to absorb potentially long interruptions
49  * of off-site journaling streams, and to prevent 'slow' off-site linkages
50  * from radically slowing down local filesystem operations.  
51  *
52  * Because of the non-trivial algorithms the journaling system will be
53  * required to support, use of a worker thread is mandatory.  Efficiencies
54  * are maintained by utilitizing the memory FIFO to batch transactions when
55  * possible, reducing the number of gratuitous thread switches and taking
56  * advantage of cpu caches through the use of shorter batched code paths
57  * rather then trying to do everything in the context of the process
58  * originating the filesystem op.  In the future the memory FIFO can be
59  * made per-cpu to remove BGL or other locking requirements.
60  */
61 #include <sys/param.h>
62 #include <sys/systm.h>
63 #include <sys/buf.h>
64 #include <sys/conf.h>
65 #include <sys/kernel.h>
66 #include <sys/queue.h>
67 #include <sys/lock.h>
68 #include <sys/malloc.h>
69 #include <sys/mount.h>
70 #include <sys/unistd.h>
71 #include <sys/vnode.h>
72 #include <sys/poll.h>
73 #include <sys/mountctl.h>
74 #include <sys/journal.h>
75 #include <sys/file.h>
76 #include <sys/proc.h>
77 #include <sys/xio.h>
78 #include <sys/socket.h>
79 #include <sys/socketvar.h>
80
81 #include <machine/limits.h>
82
83 #include <vm/vm.h>
84 #include <vm/vm_object.h>
85 #include <vm/vm_page.h>
86 #include <vm/vm_pager.h>
87 #include <vm/vnode_pager.h>
88
89 #include <sys/file2.h>
90 #include <sys/mplock2.h>
91 #include <sys/spinlock2.h>
92
93 static void journal_wthread(void *info);
94 static void journal_rthread(void *info);
95
96 static void *journal_reserve(struct journal *jo,
97                         struct journal_rawrecbeg **rawpp,
98                         int16_t streamid, int bytes);
99 static void *journal_extend(struct journal *jo,
100                         struct journal_rawrecbeg **rawpp,
101                         int truncbytes, int bytes, int *newstreamrecp);
102 static void journal_abort(struct journal *jo,
103                         struct journal_rawrecbeg **rawpp);
104 static void journal_commit(struct journal *jo,
105                         struct journal_rawrecbeg **rawpp,
106                         int bytes, int closeout);
107 static void jrecord_data(struct jrecord *jrec,
108                         void *buf, int bytes, int dtype);
109
110
111 MALLOC_DEFINE(M_JOURNAL, "journal", "Journaling structures");
112 MALLOC_DEFINE(M_JFIFO, "journal-fifo", "Journal FIFO");
113
114 void
115 journal_create_threads(struct journal *jo)
116 {
117         jo->flags &= ~(MC_JOURNAL_STOP_REQ | MC_JOURNAL_STOP_IMM);
118         jo->flags |= MC_JOURNAL_WACTIVE;
119         lwkt_create(journal_wthread, jo, NULL, &jo->wthread,
120                     TDF_NOSTART, -1,
121                     "journal w:%.*s", JIDMAX, jo->id);
122         lwkt_setpri(&jo->wthread, TDPRI_KERN_DAEMON);
123         lwkt_schedule(&jo->wthread);
124
125         if (jo->flags & MC_JOURNAL_WANT_FULLDUPLEX) {
126             jo->flags |= MC_JOURNAL_RACTIVE;
127             lwkt_create(journal_rthread, jo, NULL, &jo->rthread,
128                         TDF_NOSTART, -1,
129                         "journal r:%.*s", JIDMAX, jo->id);
130             lwkt_setpri(&jo->rthread, TDPRI_KERN_DAEMON);
131             lwkt_schedule(&jo->rthread);
132         }
133 }
134
135 void
136 journal_destroy_threads(struct journal *jo, int flags)
137 {
138     int wcount;
139
140     jo->flags |= MC_JOURNAL_STOP_REQ | (flags & MC_JOURNAL_STOP_IMM);
141     wakeup(&jo->fifo);
142     wcount = 0;
143     while (jo->flags & (MC_JOURNAL_WACTIVE | MC_JOURNAL_RACTIVE)) {
144         tsleep(jo, 0, "jwait", hz);
145         if (++wcount % 10 == 0) {
146             kprintf("Warning: journal %s waiting for descriptors to close\n",
147                 jo->id);
148         }
149     }
150
151     /*
152      * XXX SMP - threads should move to cpu requesting the restart or
153      * termination before finishing up to properly interlock.
154      */
155     tsleep(jo, 0, "jwait", hz);
156     lwkt_free_thread(&jo->wthread);
157     if (jo->flags & MC_JOURNAL_WANT_FULLDUPLEX)
158         lwkt_free_thread(&jo->rthread);
159 }
160
161 /*
162  * The per-journal worker thread is responsible for writing out the
163  * journal's FIFO to the target stream.
164  */
165 static void
166 journal_wthread(void *info)
167 {
168     struct journal *jo = info;
169     struct journal_rawrecbeg *rawp;
170     int error;
171     size_t avail;
172     size_t bytes;
173     size_t res;
174
175     /* not MPSAFE yet */
176     get_mplock();
177
178     for (;;) {
179         /*
180          * Calculate the number of bytes available to write.  This buffer
181          * area may contain reserved records so we can't just write it out
182          * without further checks.
183          */
184         bytes = jo->fifo.windex - jo->fifo.rindex;
185
186         /*
187          * sleep if no bytes are available or if an incomplete record is
188          * encountered (it needs to be filled in before we can write it
189          * out), and skip any pad records that we encounter.
190          */
191         if (bytes == 0) {
192             if (jo->flags & MC_JOURNAL_STOP_REQ)
193                 break;
194             tsleep(&jo->fifo, 0, "jfifo", hz);
195             continue;
196         }
197
198         /*
199          * Sleep if we can not go any further due to hitting an incomplete
200          * record.  This case should occur rarely but may have to be better
201          * optimized XXX.
202          */
203         rawp = (void *)(jo->fifo.membase + (jo->fifo.rindex & jo->fifo.mask));
204         if (rawp->begmagic == JREC_INCOMPLETEMAGIC) {
205             tsleep(&jo->fifo, 0, "jpad", hz);
206             continue;
207         }
208
209         /*
210          * Skip any pad records.  We do not write out pad records if we can
211          * help it. 
212          */
213         if (rawp->streamid == JREC_STREAMID_PAD) {
214             if ((jo->flags & MC_JOURNAL_WANT_FULLDUPLEX) == 0) {
215                 if (jo->fifo.rindex == jo->fifo.xindex) {
216                     jo->fifo.xindex += (rawp->recsize + 15) & ~15;
217                     jo->total_acked += (rawp->recsize + 15) & ~15;
218                 }
219             }
220             jo->fifo.rindex += (rawp->recsize + 15) & ~15;
221             jo->total_acked += bytes;
222             KKASSERT(jo->fifo.windex - jo->fifo.rindex >= 0);
223             continue;
224         }
225
226         /*
227          * 'bytes' is the amount of data that can potentially be written out.  
228          * Calculate 'res', the amount of data that can actually be written
229          * out.  res is bounded either by hitting the end of the physical
230          * memory buffer or by hitting an incomplete record.  Incomplete
231          * records often occur due to the way the space reservation model
232          * works.
233          */
234         res = 0;
235         avail = jo->fifo.size - (jo->fifo.rindex & jo->fifo.mask);
236         while (res < bytes && rawp->begmagic == JREC_BEGMAGIC) {
237             res += (rawp->recsize + 15) & ~15;
238             if (res >= avail) {
239                 KKASSERT(res == avail);
240                 break;
241             }
242             rawp = (void *)((char *)rawp + ((rawp->recsize + 15) & ~15));
243         }
244
245         /*
246          * Issue the write and deal with any errors or other conditions.
247          * For now assume blocking I/O.  Since we are record-aware the
248          * code cannot yet handle partial writes.
249          *
250          * We bump rindex prior to issuing the write to avoid racing
251          * the acknowledgement coming back (which could prevent the ack
252          * from bumping xindex).  Restarts are always based on xindex so
253          * we do not try to undo the rindex if an error occurs.
254          *
255          * XXX EWOULDBLOCK/NBIO
256          * XXX notification on failure
257          * XXX permanent verses temporary failures
258          * XXX two-way acknowledgement stream in the return direction / xindex
259          */
260         bytes = res;
261         jo->fifo.rindex += bytes;
262         error = fp_write(jo->fp, 
263                         jo->fifo.membase +
264                          ((jo->fifo.rindex - bytes) & jo->fifo.mask),
265                         bytes, &res, UIO_SYSSPACE);
266         if (error) {
267             kprintf("journal_thread(%s) write, error %d\n", jo->id, error);
268             /* XXX */
269         } else {
270             KKASSERT(res == bytes);
271         }
272
273         /*
274          * Advance rindex.  If the journal stream is not full duplex we also
275          * advance xindex, otherwise the rjournal thread is responsible for
276          * advancing xindex.
277          */
278         if ((jo->flags & MC_JOURNAL_WANT_FULLDUPLEX) == 0) {
279             jo->fifo.xindex += bytes;
280             jo->total_acked += bytes;
281         }
282         KKASSERT(jo->fifo.windex - jo->fifo.rindex >= 0);
283         if ((jo->flags & MC_JOURNAL_WANT_FULLDUPLEX) == 0) {
284             if (jo->flags & MC_JOURNAL_WWAIT) {
285                 jo->flags &= ~MC_JOURNAL_WWAIT; /* XXX hysteresis */
286                 wakeup(&jo->fifo.windex);
287             }
288         }
289     }
290     fp_shutdown(jo->fp, SHUT_WR);
291     jo->flags &= ~MC_JOURNAL_WACTIVE;
292     wakeup(jo);
293     wakeup(&jo->fifo.windex);
294     rel_mplock();
295 }
296
297 /*
298  * A second per-journal worker thread is created for two-way journaling
299  * streams to deal with the return acknowledgement stream.
300  */
301 static void
302 journal_rthread(void *info)
303 {
304     struct journal_rawrecbeg *rawp;
305     struct journal_ackrecord ack;
306     struct journal *jo = info;
307     int64_t transid;
308     int error;
309     size_t count;
310     size_t bytes;
311
312     transid = 0;
313     error = 0;
314
315     /* not MPSAFE yet */
316     get_mplock();
317
318     for (;;) {
319         /*
320          * We have been asked to stop
321          */
322         if (jo->flags & MC_JOURNAL_STOP_REQ)
323                 break;
324
325         /*
326          * If we have no active transaction id, get one from the return
327          * stream.
328          */
329         if (transid == 0) {
330             error = fp_read(jo->fp, &ack, sizeof(ack), &count, 
331                             1, UIO_SYSSPACE);
332 #if 0
333             kprintf("fp_read ack error %d count %d\n", error, count);
334 #endif
335             if (error || count != sizeof(ack))
336                 break;
337             if (error) {
338                 kprintf("read error %d on receive stream\n", error);
339                 break;
340             }
341             if (ack.rbeg.begmagic != JREC_BEGMAGIC ||
342                 ack.rend.endmagic != JREC_ENDMAGIC
343             ) {
344                 kprintf("bad begmagic or endmagic on receive stream\n");
345                 break;
346             }
347             transid = ack.rbeg.transid;
348         }
349
350         /*
351          * Calculate the number of unacknowledged bytes.  If there are no
352          * unacknowledged bytes then unsent data was acknowledged, report,
353          * sleep a bit, and loop in that case.  This should not happen 
354          * normally.  The ack record is thrown away.
355          */
356         bytes = jo->fifo.rindex - jo->fifo.xindex;
357
358         if (bytes == 0) {
359             kprintf("warning: unsent data acknowledged transid %08llx\n",
360                     (long long)transid);
361             tsleep(&jo->fifo.xindex, 0, "jrseq", hz);
362             transid = 0;
363             continue;
364         }
365
366         /*
367          * Since rindex has advanced, the record pointed to by xindex
368          * must be a valid record.
369          */
370         rawp = (void *)(jo->fifo.membase + (jo->fifo.xindex & jo->fifo.mask));
371         KKASSERT(rawp->begmagic == JREC_BEGMAGIC);
372         KKASSERT(rawp->recsize <= bytes);
373
374         /*
375          * The target can acknowledge several records at once.
376          */
377         if (rawp->transid < transid) {
378 #if 1
379             kprintf("ackskip %08llx/%08llx\n",
380                     (long long)rawp->transid,
381                     (long long)transid);
382 #endif
383             jo->fifo.xindex += (rawp->recsize + 15) & ~15;
384             jo->total_acked += (rawp->recsize + 15) & ~15;
385             if (jo->flags & MC_JOURNAL_WWAIT) {
386                 jo->flags &= ~MC_JOURNAL_WWAIT; /* XXX hysteresis */
387                 wakeup(&jo->fifo.windex);
388             }
389             continue;
390         }
391         if (rawp->transid == transid) {
392 #if 1
393             kprintf("ackskip %08llx/%08llx\n",
394                     (long long)rawp->transid,
395                     (long long)transid);
396 #endif
397             jo->fifo.xindex += (rawp->recsize + 15) & ~15;
398             jo->total_acked += (rawp->recsize + 15) & ~15;
399             if (jo->flags & MC_JOURNAL_WWAIT) {
400                 jo->flags &= ~MC_JOURNAL_WWAIT; /* XXX hysteresis */
401                 wakeup(&jo->fifo.windex);
402             }
403             transid = 0;
404             continue;
405         }
406         kprintf("warning: unsent data(2) acknowledged transid %08llx\n",
407                 (long long)transid);
408         transid = 0;
409     }
410     jo->flags &= ~MC_JOURNAL_RACTIVE;
411     wakeup(jo);
412     wakeup(&jo->fifo.windex);
413     rel_mplock();
414 }
415
416 /*
417  * This builds a pad record which the journaling thread will skip over.  Pad
418  * records are required when we are unable to reserve sufficient stream space
419  * due to insufficient space at the end of the physical memory fifo.
420  *
421  * Even though the record is not transmitted, a normal transid must be 
422  * assigned to it so link recovery operations after a failure work properly.
423  */
424 static
425 void
426 journal_build_pad(struct journal_rawrecbeg *rawp, int recsize, int64_t transid)
427 {
428     struct journal_rawrecend *rendp;
429     
430     KKASSERT((recsize & 15) == 0 && recsize >= 16);
431
432     rawp->streamid = JREC_STREAMID_PAD;
433     rawp->recsize = recsize;    /* must be 16-byte aligned */
434     rawp->transid = transid;
435     /*
436      * WARNING, rendp may overlap rawp->transid.  This is necessary to
437      * allow PAD records to fit in 16 bytes.  Use cpu_ccfence() to
438      * hopefully cause the compiler to not make any assumptions.
439      */
440     rendp = (void *)((char *)rawp + rawp->recsize - sizeof(*rendp));
441     rendp->endmagic = JREC_ENDMAGIC;
442     rendp->check = 0;
443     rendp->recsize = rawp->recsize;
444
445     /*
446      * Set the begin magic last.  This is what will allow the journal
447      * thread to write the record out.  Use a store fence to prevent
448      * compiler and cpu reordering of the writes.
449      */
450     cpu_sfence();
451     rawp->begmagic = JREC_BEGMAGIC;
452 }
453
454 /*
455  * Wake up the worker thread if the FIFO is more then half full or if
456  * someone is waiting for space to be freed up.  Otherwise let the 
457  * heartbeat deal with it.  Being able to avoid waking up the worker
458  * is the key to the journal's cpu performance.
459  */
460 static __inline
461 void
462 journal_commit_wakeup(struct journal *jo)
463 {
464     int avail;
465
466     avail = jo->fifo.size - (jo->fifo.windex - jo->fifo.xindex);
467     KKASSERT(avail >= 0);
468     if ((avail < (jo->fifo.size >> 1)) || (jo->flags & MC_JOURNAL_WWAIT))
469         wakeup(&jo->fifo);
470 }
471
472 /*
473  * Create a new BEGIN stream record with the specified streamid and the
474  * specified amount of payload space.  *rawpp will be set to point to the
475  * base of the new stream record and a pointer to the base of the payload
476  * space will be returned.  *rawpp does not need to be pre-NULLd prior to
477  * making this call.  The raw record header will be partially initialized.
478  *
479  * A stream can be extended, aborted, or committed by other API calls
480  * below.  This may result in a sequence of potentially disconnected
481  * stream records to be output to the journaling target.  The first record
482  * (the one created by this function) will be marked JREC_STREAMCTL_BEGIN,
483  * while the last record on commit or abort will be marked JREC_STREAMCTL_END
484  * (and possibly also JREC_STREAMCTL_ABORTED).  The last record could wind
485  * up being the same as the first, in which case the bits are all set in
486  * the first record.
487  *
488  * The stream record is created in an incomplete state by setting the begin
489  * magic to JREC_INCOMPLETEMAGIC.  This prevents the worker thread from
490  * flushing the fifo past our record until we have finished populating it.
491  * Other threads can reserve and operate on their own space without stalling
492  * but the stream output will stall until we have completed operations.  The
493  * memory FIFO is intended to be large enough to absorb such situations
494  * without stalling out other threads.
495  */
496 static
497 void *
498 journal_reserve(struct journal *jo, struct journal_rawrecbeg **rawpp,
499                 int16_t streamid, int bytes)
500 {
501     struct journal_rawrecbeg *rawp;
502     int avail;
503     int availtoend;
504     int req;
505
506     /*
507      * Add header and trailer overheads to the passed payload.  Note that
508      * the passed payload size need not be aligned in any way.
509      */
510     bytes += sizeof(struct journal_rawrecbeg);
511     bytes += sizeof(struct journal_rawrecend);
512
513     for (;;) {
514         /*
515          * First, check boundary conditions.  If the request would wrap around
516          * we have to skip past the ending block and return to the beginning
517          * of the FIFO's buffer.  Calculate 'req' which is the actual number
518          * of bytes being reserved, including wrap-around dead space.
519          *
520          * Neither 'bytes' or 'req' are aligned.
521          *
522          * Note that availtoend is not truncated to avail and so cannot be
523          * used to determine whether the reservation is possible by itself.
524          * Also, since all fifo ops are 16-byte aligned, we can check
525          * the size before calculating the aligned size.
526          */
527         availtoend = jo->fifo.size - (jo->fifo.windex & jo->fifo.mask);
528         KKASSERT((availtoend & 15) == 0);
529         if (bytes > availtoend) 
530             req = bytes + availtoend;   /* add pad to end */
531         else
532             req = bytes;
533
534         /*
535          * Next calculate the total available space and see if it is
536          * sufficient.  We cannot overwrite previously buffered data
537          * past xindex because otherwise we would not be able to restart
538          * a broken link at the target's last point of commit.
539          */
540         avail = jo->fifo.size - (jo->fifo.windex - jo->fifo.xindex);
541         KKASSERT(avail >= 0 && (avail & 15) == 0);
542
543         if (avail < req) {
544             /* XXX MC_JOURNAL_STOP_IMM */
545             jo->flags |= MC_JOURNAL_WWAIT;
546             ++jo->fifostalls;
547             tsleep(&jo->fifo.windex, 0, "jwrite", 0);
548             continue;
549         }
550
551         /*
552          * Create a pad record for any dead space and create an incomplete
553          * record for the live space, then return a pointer to the
554          * contiguous buffer space that was requested.
555          *
556          * NOTE: The worker thread will not flush past an incomplete
557          * record, so the reserved space can be filled in at-will.  The
558          * journaling code must also be aware the reserved sections occuring
559          * after this one will also not be written out even if completed
560          * until this one is completed.
561          *
562          * The transaction id must accomodate real and potential pad creation.
563          */
564         rawp = (void *)(jo->fifo.membase + (jo->fifo.windex & jo->fifo.mask));
565         if (req != bytes) {
566             journal_build_pad(rawp, availtoend, jo->transid);
567             ++jo->transid;
568             rawp = (void *)jo->fifo.membase;
569         }
570         rawp->begmagic = JREC_INCOMPLETEMAGIC;  /* updated by abort/commit */
571         rawp->recsize = bytes;                  /* (unaligned size) */
572         rawp->streamid = streamid | JREC_STREAMCTL_BEGIN;
573         rawp->transid = jo->transid;
574         jo->transid += 2;
575
576         /*
577          * Issue a memory barrier to guarentee that the record data has been
578          * properly initialized before we advance the write index and return
579          * a pointer to the reserved record.  Otherwise the worker thread
580          * could accidently run past us.
581          *
582          * Note that stream records are always 16-byte aligned.
583          */
584         cpu_sfence();
585         jo->fifo.windex += (req + 15) & ~15;
586         *rawpp = rawp;
587         return(rawp + 1);
588     }
589     /* not reached */
590     *rawpp = NULL;
591     return(NULL);
592 }
593
594 /*
595  * Attempt to extend the stream record by <bytes> worth of payload space.
596  *
597  * If it is possible to extend the existing stream record no truncation
598  * occurs and the record is extended as specified.  A pointer to the 
599  * truncation offset within the payload space is returned.
600  *
601  * If it is not possible to do this the existing stream record is truncated
602  * and committed, and a new stream record of size <bytes> is created.  A
603  * pointer to the base of the new stream record's payload space is returned.
604  *
605  * *rawpp is set to the new reservation in the case of a new record but
606  * the caller cannot depend on a comparison with the old rawp to determine if
607  * this case occurs because we could end up using the same memory FIFO
608  * offset for the new stream record.  Use *newstreamrecp instead.
609  */
610 static void *
611 journal_extend(struct journal *jo, struct journal_rawrecbeg **rawpp, 
612                 int truncbytes, int bytes, int *newstreamrecp)
613 {
614     struct journal_rawrecbeg *rawp;
615     int16_t streamid;
616     int availtoend;
617     int avail;
618     int osize;
619     int nsize;
620     int wbase;
621     void *rptr;
622
623     *newstreamrecp = 0;
624     rawp = *rawpp;
625     osize = (rawp->recsize + 15) & ~15;
626     nsize = (rawp->recsize + bytes + 15) & ~15;
627     wbase = (char *)rawp - jo->fifo.membase;
628
629     /*
630      * If the aligned record size does not change we can trivially adjust
631      * the record size.
632      */
633     if (nsize == osize) {
634         rawp->recsize += bytes;
635         return((char *)(rawp + 1) + truncbytes);
636     }
637
638     /*
639      * If the fifo's write index hasn't been modified since we made the
640      * reservation and we do not hit any boundary conditions, we can 
641      * trivially make the record smaller or larger.
642      */
643     if ((jo->fifo.windex & jo->fifo.mask) == wbase + osize) {
644         availtoend = jo->fifo.size - wbase;
645         avail = jo->fifo.size - (jo->fifo.windex - jo->fifo.xindex) + osize;
646         KKASSERT((availtoend & 15) == 0);
647         KKASSERT((avail & 15) == 0);
648         if (nsize <= avail && nsize <= availtoend) {
649             jo->fifo.windex += nsize - osize;
650             rawp->recsize += bytes;
651             return((char *)(rawp + 1) + truncbytes);
652         }
653     }
654
655     /*
656      * It was not possible to extend the buffer.  Commit the current
657      * buffer and create a new one.  We manually clear the BEGIN mark that
658      * journal_reserve() creates (because this is a continuing record, not
659      * the start of a new stream).
660      */
661     streamid = rawp->streamid & JREC_STREAMID_MASK;
662     journal_commit(jo, rawpp, truncbytes, 0);
663     rptr = journal_reserve(jo, rawpp, streamid, bytes);
664     rawp = *rawpp;
665     rawp->streamid &= ~JREC_STREAMCTL_BEGIN;
666     *newstreamrecp = 1;
667     return(rptr);
668 }
669
670 /*
671  * Abort a journal record.  If the transaction record represents a stream
672  * BEGIN and we can reverse the fifo's write index we can simply reverse
673  * index the entire record, as if it were never reserved in the first place.
674  *
675  * Otherwise we set the JREC_STREAMCTL_ABORTED bit and commit the record
676  * with the payload truncated to 0 bytes.
677  */
678 static void
679 journal_abort(struct journal *jo, struct journal_rawrecbeg **rawpp)
680 {
681     struct journal_rawrecbeg *rawp;
682     int osize;
683
684     rawp = *rawpp;
685     osize = (rawp->recsize + 15) & ~15;
686
687     if ((rawp->streamid & JREC_STREAMCTL_BEGIN) &&
688         (jo->fifo.windex & jo->fifo.mask) == 
689          (char *)rawp - jo->fifo.membase + osize)
690     {
691         jo->fifo.windex -= osize;
692         *rawpp = NULL;
693     } else {
694         rawp->streamid |= JREC_STREAMCTL_ABORTED;
695         journal_commit(jo, rawpp, 0, 1);
696     }
697 }
698
699 /*
700  * Commit a journal record and potentially truncate it to the specified
701  * number of payload bytes.  If you do not want to truncate the record,
702  * simply pass -1 for the bytes parameter.  Do not pass rawp->recsize, that
703  * field includes header and trailer and will not be correct.  Note that
704  * passing 0 will truncate the entire data payload of the record.
705  *
706  * The logical stream is terminated by this function.
707  *
708  * If truncation occurs, and it is not possible to physically optimize the
709  * memory FIFO due to other threads having reserved space after ours,
710  * the remaining reserved space will be covered by a pad record.
711  */
712 static void
713 journal_commit(struct journal *jo, struct journal_rawrecbeg **rawpp,
714                 int bytes, int closeout)
715 {
716     struct journal_rawrecbeg *rawp;
717     struct journal_rawrecend *rendp;
718     int osize;
719     int nsize;
720
721     rawp = *rawpp;
722     *rawpp = NULL;
723
724     KKASSERT((char *)rawp >= jo->fifo.membase &&
725              (char *)rawp + rawp->recsize <= jo->fifo.membase + jo->fifo.size);
726     KKASSERT(((intptr_t)rawp & 15) == 0);
727
728     /*
729      * Truncate the record if necessary.  If the FIFO write index as still
730      * at the end of our record we can optimally backindex it.  Otherwise
731      * we have to insert a pad record to cover the dead space.
732      *
733      * We calculate osize which is the 16-byte-aligned original recsize.
734      * We calculate nsize which is the 16-byte-aligned new recsize.
735      *
736      * Due to alignment issues or in case the passed truncation bytes is
737      * the same as the original payload, nsize may be equal to osize even
738      * if the committed bytes is less then the originally reserved bytes.
739      */
740     if (bytes >= 0) {
741         KKASSERT(bytes >= 0 && bytes <= rawp->recsize - sizeof(struct journal_rawrecbeg) - sizeof(struct journal_rawrecend));
742         osize = (rawp->recsize + 15) & ~15;
743         rawp->recsize = bytes + sizeof(struct journal_rawrecbeg) +
744                         sizeof(struct journal_rawrecend);
745         nsize = (rawp->recsize + 15) & ~15;
746         KKASSERT(nsize <= osize);
747         if (osize == nsize) {
748             /* do nothing */
749         } else if ((jo->fifo.windex & jo->fifo.mask) == (char *)rawp - jo->fifo.membase + osize) {
750             /* we are able to backindex the fifo */
751             jo->fifo.windex -= osize - nsize;
752         } else {
753             /* we cannot backindex the fifo, emplace a pad in the dead space */
754             journal_build_pad((void *)((char *)rawp + nsize), osize - nsize,
755                                 rawp->transid + 1);
756         }
757     }
758
759     /*
760      * Fill in the trailer.  Note that unlike pad records, the trailer will
761      * never overlap the header.
762      */
763     rendp = (void *)((char *)rawp + 
764             ((rawp->recsize + 15) & ~15) - sizeof(*rendp));
765     rendp->endmagic = JREC_ENDMAGIC;
766     rendp->recsize = rawp->recsize;
767     rendp->check = 0;           /* XXX check word, disabled for now */
768
769     /*
770      * Fill in begmagic last.  This will allow the worker thread to proceed.
771      * Use a memory barrier to guarentee write ordering.  Mark the stream
772      * as terminated if closeout is set.  This is the typical case.
773      */
774     if (closeout)
775         rawp->streamid |= JREC_STREAMCTL_END;
776     cpu_sfence();               /* memory and compiler barrier */
777     rawp->begmagic = JREC_BEGMAGIC;
778
779     journal_commit_wakeup(jo);
780 }
781
782 /************************************************************************
783  *                      TRANSACTION SUPPORT ROUTINES                    *
784  ************************************************************************
785  *
786  * JRECORD_*() - routines to create subrecord transactions and embed them
787  *               in the logical streams managed by the journal_*() routines.
788  */
789
790 /*
791  * Initialize the passed jrecord structure and start a new stream transaction
792  * by reserving an initial build space in the journal's memory FIFO.
793  */
794 void
795 jrecord_init(struct journal *jo, struct jrecord *jrec, int16_t streamid)
796 {
797     bzero(jrec, sizeof(*jrec));
798     jrec->jo = jo;
799     jrec->streamid = streamid;
800     jrec->stream_residual = JREC_DEFAULTSIZE;
801     jrec->stream_reserved = jrec->stream_residual;
802     jrec->stream_ptr = 
803         journal_reserve(jo, &jrec->rawp, streamid, jrec->stream_reserved);
804 }
805
806 /*
807  * Push a recursive record type.  All pushes should have matching pops.
808  * The old parent is returned and the newly pushed record becomes the
809  * new parent.  Note that the old parent's pointer may already be invalid
810  * or may become invalid if jrecord_write() had to build a new stream
811  * record, so the caller should not mess with the returned pointer in
812  * any way other then to save it.
813  */
814 struct journal_subrecord *
815 jrecord_push(struct jrecord *jrec, int16_t rectype)
816 {
817     struct journal_subrecord *save;
818
819     save = jrec->parent;
820     jrec->parent = jrecord_write(jrec, rectype|JMASK_NESTED, 0);
821     jrec->last = NULL;
822     KKASSERT(jrec->parent != NULL);
823     ++jrec->pushcount;
824     ++jrec->pushptrgood;        /* cleared on flush */
825     return(save);
826 }
827
828 /*
829  * Pop a previously pushed sub-transaction.  We must set JMASK_LAST
830  * on the last record written within the subtransaction.  If the last 
831  * record written is not accessible or if the subtransaction is empty,
832  * we must write out a pad record with JMASK_LAST set before popping.
833  *
834  * When popping a subtransaction the parent record's recsize field
835  * will be properly set.  If the parent pointer is no longer valid
836  * (which can occur if the data has already been flushed out to the
837  * stream), the protocol spec allows us to leave it 0.
838  *
839  * The saved parent pointer which we restore may or may not be valid,
840  * and if not valid may or may not be NULL, depending on the value
841  * of pushptrgood.
842  */
843 void
844 jrecord_pop(struct jrecord *jrec, struct journal_subrecord *save)
845 {
846     struct journal_subrecord *last;
847
848     KKASSERT(jrec->pushcount > 0);
849     KKASSERT(jrec->residual == 0);
850
851     /*
852      * Set JMASK_LAST on the last record we wrote at the current
853      * level.  If last is NULL we either no longer have access to the
854      * record or the subtransaction was empty and we must write out a pad
855      * record.
856      */
857     if ((last = jrec->last) == NULL) {
858         jrecord_write(jrec, JLEAF_PAD|JMASK_LAST, 0);
859         last = jrec->last;      /* reload after possible flush */
860     } else {
861         last->rectype |= JMASK_LAST;
862     }
863
864     /*
865      * pushptrgood tells us how many levels of parent record pointers
866      * are valid.  The jrec only stores the current parent record pointer
867      * (and it is only valid if pushptrgood != 0).  The higher level parent
868      * record pointers are saved by the routines calling jrecord_push() and
869      * jrecord_pop().  These pointers may become stale and we determine
870      * that fact by tracking the count of valid parent pointers with 
871      * pushptrgood.  Pointers become invalid when their related stream
872      * record gets pushed out.
873      *
874      * If no pointer is available (the data has already been pushed out),
875      * then no fixup of e.g. the length field is possible for non-leaf
876      * nodes.  The protocol allows for this situation by placing a larger
877      * burden on the program scanning the stream on the other end.
878      *
879      * [parentA]
880      *    [node X]
881      *    [parentB]
882      *       [node Y]
883      *       [node Z]
884      *    (pop B)       see NOTE B
885      * (pop A)          see NOTE A
886      *
887      * NOTE B:  This pop sets LAST in node Z if the node is still accessible,
888      *          else a PAD record is appended and LAST is set in that.
889      *
890      *          This pop sets the record size in parentB if parentB is still
891      *          accessible, else the record size is left 0 (the scanner must
892      *          deal with that).
893      *
894      *          This pop sets the new 'last' record to parentB, the pointer
895      *          to which may or may not still be accessible.
896      *
897      * NOTE A:  This pop sets LAST in parentB if the node is still accessible,
898      *          else a PAD record is appended and LAST is set in that.
899      *
900      *          This pop sets the record size in parentA if parentA is still
901      *          accessible, else the record size is left 0 (the scanner must
902      *          deal with that).
903      *
904      *          This pop sets the new 'last' record to parentA, the pointer
905      *          to which may or may not still be accessible.
906      *
907      * Also note that the last record in the stream transaction, which in
908      * the above example is parentA, does not currently have the LAST bit
909      * set.
910      *
911      * The current parent becomes the last record relative to the
912      * saved parent passed into us.  It's validity is based on 
913      * whether pushptrgood is non-zero prior to decrementing.  The saved
914      * parent becomes the new parent, and its validity is based on whether
915      * pushptrgood is non-zero after decrementing.
916      *
917      * The old jrec->parent may be NULL if it is no longer accessible.
918      * If pushptrgood is non-zero, however, it is guarenteed to not
919      * be NULL (since no flush occured).
920      */
921     jrec->last = jrec->parent;
922     --jrec->pushcount;
923     if (jrec->pushptrgood) {
924         KKASSERT(jrec->last != NULL && last != NULL);
925         if (--jrec->pushptrgood == 0) {
926             jrec->parent = NULL;        /* 'save' contains garbage or NULL */
927         } else {
928             KKASSERT(save != NULL);
929             jrec->parent = save;        /* 'save' must not be NULL */
930         }
931
932         /*
933          * Set the record size in the old parent.  'last' still points to
934          * the original last record in the subtransaction being popped,
935          * jrec->last points to the old parent (which became the last
936          * record relative to the new parent being popped into).
937          */
938         jrec->last->recsize = (char *)last + last->recsize - (char *)jrec->last;
939     } else {
940         jrec->parent = NULL;
941         KKASSERT(jrec->last == NULL);
942     }
943 }
944
945 /*
946  * Write out a leaf record, including associated data.
947  */
948 void
949 jrecord_leaf(struct jrecord *jrec, int16_t rectype, void *ptr, int bytes)
950 {
951     jrecord_write(jrec, rectype, bytes);
952     jrecord_data(jrec, ptr, bytes, JDATA_KERN);
953 }
954
955 void
956 jrecord_leaf_uio(struct jrecord *jrec, int16_t rectype,
957                  struct uio *uio)
958 {
959     struct iovec *iov;
960     int i;
961
962     for (i = 0; i < uio->uio_iovcnt; ++i) {
963         iov = &uio->uio_iov[i];
964         if (iov->iov_len == 0)
965             continue;
966         if (uio->uio_segflg == UIO_SYSSPACE) {
967             jrecord_write(jrec, rectype, iov->iov_len);
968             jrecord_data(jrec, iov->iov_base, iov->iov_len, JDATA_KERN);
969         } else { /* UIO_USERSPACE */
970             jrecord_write(jrec, rectype, iov->iov_len);
971             jrecord_data(jrec, iov->iov_base, iov->iov_len, JDATA_USER);
972         }
973     }
974 }
975
976 void
977 jrecord_leaf_xio(struct jrecord *jrec, int16_t rectype, xio_t xio)
978 {
979     int bytes = xio->xio_npages * PAGE_SIZE;
980
981     jrecord_write(jrec, rectype, bytes);
982     jrecord_data(jrec, xio, bytes, JDATA_XIO);
983 }
984
985 /*
986  * Write a leaf record out and return a pointer to its base.  The leaf
987  * record may contain potentially megabytes of data which is supplied
988  * in jrecord_data() calls.  The exact amount must be specified in this
989  * call.
990  *
991  * THE RETURNED SUBRECORD POINTER IS ONLY VALID IMMEDIATELY AFTER THE
992  * CALL AND MAY BECOME INVALID AT ANY TIME.  ONLY THE PUSH/POP CODE SHOULD
993  * USE THE RETURN VALUE.
994  */
995 struct journal_subrecord *
996 jrecord_write(struct jrecord *jrec, int16_t rectype, int bytes)
997 {
998     struct journal_subrecord *last;
999     int pusheditout;
1000
1001     /*
1002      * Try to catch some obvious errors.  Nesting records must specify a
1003      * size of 0, and there should be no left-overs from previous operations
1004      * (such as incomplete data writeouts).
1005      */
1006     KKASSERT(bytes == 0 || (rectype & JMASK_NESTED) == 0);
1007     KKASSERT(jrec->residual == 0);
1008
1009     /*
1010      * Check to see if the current stream record has enough room for
1011      * the new subrecord header.  If it doesn't we extend the current
1012      * stream record.
1013      *
1014      * This may have the side effect of pushing out the current stream record
1015      * and creating a new one.  We must adjust our stream tracking fields
1016      * accordingly.
1017      */
1018     if (jrec->stream_residual < sizeof(struct journal_subrecord)) {
1019         jrec->stream_ptr = journal_extend(jrec->jo, &jrec->rawp,
1020                                 jrec->stream_reserved - jrec->stream_residual,
1021                                 JREC_DEFAULTSIZE, &pusheditout);
1022         if (pusheditout) {
1023             /*
1024              * If a pushout occured, the pushed out stream record was
1025              * truncated as specified and the new record is exactly the
1026              * extension size specified.
1027              */
1028             jrec->stream_reserved = JREC_DEFAULTSIZE;
1029             jrec->stream_residual = JREC_DEFAULTSIZE;
1030             jrec->parent = NULL;        /* no longer accessible */
1031             jrec->pushptrgood = 0;      /* restored parents in pops no good */
1032         } else {
1033             /*
1034              * If no pushout occured the stream record is NOT truncated and
1035              * IS extended.
1036              */
1037             jrec->stream_reserved += JREC_DEFAULTSIZE;
1038             jrec->stream_residual += JREC_DEFAULTSIZE;
1039         }
1040     }
1041     last = (void *)jrec->stream_ptr;
1042     last->rectype = rectype;
1043     last->reserved = 0;
1044
1045     /*
1046      * We may not know the record size for recursive records and the 
1047      * header may become unavailable due to limited FIFO space.  Write
1048      * -1 to indicate this special case.
1049      */
1050     if ((rectype & JMASK_NESTED) && bytes == 0)
1051         last->recsize = -1;
1052     else
1053         last->recsize = sizeof(struct journal_subrecord) + bytes;
1054     jrec->last = last;
1055     jrec->residual = bytes;             /* remaining data to be posted */
1056     jrec->residual_align = -bytes & 7;  /* post-data alignment required */
1057     jrec->stream_ptr += sizeof(*last);  /* current write pointer */
1058     jrec->stream_residual -= sizeof(*last); /* space remaining in stream */
1059     return(last);
1060 }
1061
1062 /*
1063  * Write out the data associated with a leaf record.  Any number of calls
1064  * to this routine may be made as long as the byte count adds up to the
1065  * amount originally specified in jrecord_write().
1066  *
1067  * The act of writing out the leaf data may result in numerous stream records
1068  * being pushed out.   Callers should be aware that even the associated
1069  * subrecord header may become inaccessible due to stream record pushouts.
1070  */
1071 static void
1072 jrecord_data(struct jrecord *jrec, void *buf, int bytes, int dtype)
1073 {
1074     int pusheditout;
1075     int extsize;
1076     int xio_offset = 0;
1077
1078     KKASSERT(bytes >= 0 && bytes <= jrec->residual);
1079
1080     /*
1081      * Push out stream records as long as there is insufficient room to hold
1082      * the remaining data.
1083      */
1084     while (jrec->stream_residual < bytes) {
1085         /*
1086          * Fill in any remaining space in the current stream record.
1087          */
1088         switch (dtype) {
1089         case JDATA_KERN:
1090             bcopy(buf, jrec->stream_ptr, jrec->stream_residual);
1091             break;
1092         case JDATA_USER:
1093             copyin(buf, jrec->stream_ptr, jrec->stream_residual);
1094             break;
1095         case JDATA_XIO:
1096             xio_copy_xtok((xio_t)buf, xio_offset, jrec->stream_ptr,
1097                           jrec->stream_residual);
1098             xio_offset += jrec->stream_residual;
1099             break;
1100         }
1101         if (dtype != JDATA_XIO)
1102             buf = (char *)buf + jrec->stream_residual;
1103         bytes -= jrec->stream_residual;
1104         /*jrec->stream_ptr += jrec->stream_residual;*/
1105         jrec->residual -= jrec->stream_residual;
1106         jrec->stream_residual = 0;
1107
1108         /*
1109          * Try to extend the current stream record, but no more then 1/4
1110          * the size of the FIFO.
1111          */
1112         extsize = jrec->jo->fifo.size >> 2;
1113         if (extsize > bytes)
1114             extsize = (bytes + 15) & ~15;
1115
1116         jrec->stream_ptr = journal_extend(jrec->jo, &jrec->rawp,
1117                                 jrec->stream_reserved - jrec->stream_residual,
1118                                 extsize, &pusheditout);
1119         if (pusheditout) {
1120             jrec->stream_reserved = extsize;
1121             jrec->stream_residual = extsize;
1122             jrec->parent = NULL;        /* no longer accessible */
1123             jrec->last = NULL;          /* no longer accessible */
1124             jrec->pushptrgood = 0;      /* restored parents in pops no good */
1125         } else {
1126             jrec->stream_reserved += extsize;
1127             jrec->stream_residual += extsize;
1128         }
1129     }
1130
1131     /*
1132      * Push out any remaining bytes into the current stream record.
1133      */
1134     if (bytes) {
1135         switch (dtype) {
1136         case JDATA_KERN:
1137             bcopy(buf, jrec->stream_ptr, bytes);
1138             break;
1139         case JDATA_USER:
1140             copyin(buf, jrec->stream_ptr, bytes);
1141             break;
1142         case JDATA_XIO:
1143             xio_copy_xtok((xio_t)buf, xio_offset, jrec->stream_ptr, bytes);
1144             break;
1145         }
1146         jrec->stream_ptr += bytes;
1147         jrec->stream_residual -= bytes;
1148         jrec->residual -= bytes;
1149     }
1150
1151     /*
1152      * Handle data alignment requirements for the subrecord.  Because the
1153      * stream record's data space is more strictly aligned, it must already
1154      * have sufficient space to hold any subrecord alignment slop.
1155      */
1156     if (jrec->residual == 0 && jrec->residual_align) {
1157         KKASSERT(jrec->residual_align <= jrec->stream_residual);
1158         bzero(jrec->stream_ptr, jrec->residual_align);
1159         jrec->stream_ptr += jrec->residual_align;
1160         jrec->stream_residual -= jrec->residual_align;
1161         jrec->residual_align = 0;
1162     }
1163 }
1164
1165 /*
1166  * We are finished with the transaction.  This closes the transaction created
1167  * by jrecord_init().
1168  *
1169  * NOTE: If abortit is not set then we must be at the top level with no
1170  *       residual subrecord data left to output.
1171  *
1172  *       If abortit is set then we can be in any state, all pushes will be 
1173  *       popped and it is ok for there to be residual data.  This works 
1174  *       because the virtual stream itself is truncated.  Scanners must deal
1175  *       with this situation.
1176  *
1177  * The stream record will be committed or aborted as specified and jrecord
1178  * resources will be cleaned up.
1179  */
1180 void
1181 jrecord_done(struct jrecord *jrec, int abortit)
1182 {
1183     KKASSERT(jrec->rawp != NULL);
1184
1185     if (abortit) {
1186         journal_abort(jrec->jo, &jrec->rawp);
1187     } else {
1188         KKASSERT(jrec->pushcount == 0 && jrec->residual == 0);
1189         journal_commit(jrec->jo, &jrec->rawp, 
1190                         jrec->stream_reserved - jrec->stream_residual, 1);
1191     }
1192
1193     /*
1194      * jrec should not be used beyond this point without another init,
1195      * but clean up some fields to ensure that we panic if it is.
1196      *
1197      * Note that jrec->rawp is NULLd out by journal_abort/journal_commit.
1198      */
1199     jrec->jo = NULL;
1200     jrec->stream_ptr = NULL;
1201 }
1202
1203 /************************************************************************
1204  *                      LOW LEVEL RECORD SUPPORT ROUTINES               *
1205  ************************************************************************
1206  *
1207  * These routine create low level recursive and leaf subrecords representing
1208  * common filesystem structures.
1209  */
1210
1211 /*
1212  * Write out a filename path relative to the base of the mount point.
1213  * rectype is typically JLEAF_PATH{1,2,3,4}.
1214  */
1215 void
1216 jrecord_write_path(struct jrecord *jrec, int16_t rectype, struct namecache *ncp)
1217 {
1218     char buf[64];       /* local buffer if it fits, else malloced */
1219     char *base;
1220     int pathlen;
1221     int index;
1222     struct namecache *scan;
1223
1224     /*
1225      * Pass 1 - figure out the number of bytes required.  Include terminating
1226      *         \0 on last element and '/' separator on other elements.
1227      *
1228      * The namecache topology terminates at the root of the filesystem
1229      * (the normal lookup code would then continue by using the mount
1230      * structure to figure out what it was mounted on).
1231      */
1232 again:
1233     pathlen = 0;
1234     for (scan = ncp; scan; scan = scan->nc_parent) {
1235         if (scan->nc_nlen > 0)
1236             pathlen += scan->nc_nlen + 1;
1237     }
1238
1239     if (pathlen <= sizeof(buf))
1240         base = buf;
1241     else
1242         base = kmalloc(pathlen, M_TEMP, M_INTWAIT);
1243
1244     /*
1245      * Pass 2 - generate the path buffer
1246      */
1247     index = pathlen;
1248     for (scan = ncp; scan; scan = scan->nc_parent) {
1249         if (scan->nc_nlen == 0)
1250             continue;
1251         if (scan->nc_nlen >= index) {
1252             if (base != buf)
1253                 kfree(base, M_TEMP);
1254             goto again;
1255         }
1256         if (index == pathlen)
1257             base[--index] = 0;
1258         else
1259             base[--index] = '/';
1260         index -= scan->nc_nlen;
1261         bcopy(scan->nc_name, base + index, scan->nc_nlen);
1262     }
1263     jrecord_leaf(jrec, rectype, base + index, pathlen - index);
1264     if (base != buf)
1265         kfree(base, M_TEMP);
1266 }
1267
1268 /*
1269  * Write out a file attribute structure.  While somewhat inefficient, using
1270  * a recursive data structure is the most portable and extensible way.
1271  */
1272 void
1273 jrecord_write_vattr(struct jrecord *jrec, struct vattr *vat)
1274 {
1275     void *save;
1276
1277     save = jrecord_push(jrec, JTYPE_VATTR);
1278     if (vat->va_type != VNON)
1279         jrecord_leaf(jrec, JLEAF_VTYPE, &vat->va_type, sizeof(vat->va_type));
1280     if (vat->va_mode != (mode_t)VNOVAL)
1281         jrecord_leaf(jrec, JLEAF_MODES, &vat->va_mode, sizeof(vat->va_mode));
1282     if (vat->va_nlink != VNOVAL)
1283         jrecord_leaf(jrec, JLEAF_NLINK, &vat->va_nlink, sizeof(vat->va_nlink));
1284     if (vat->va_uid != VNOVAL)
1285         jrecord_leaf(jrec, JLEAF_UID, &vat->va_uid, sizeof(vat->va_uid));
1286     if (vat->va_gid != VNOVAL)
1287         jrecord_leaf(jrec, JLEAF_GID, &vat->va_gid, sizeof(vat->va_gid));
1288     if (vat->va_fsid != VNOVAL)
1289         jrecord_leaf(jrec, JLEAF_FSID, &vat->va_fsid, sizeof(vat->va_fsid));
1290     if (vat->va_fileid != VNOVAL)
1291         jrecord_leaf(jrec, JLEAF_INUM, &vat->va_fileid, sizeof(vat->va_fileid));
1292     if (vat->va_size != VNOVAL)
1293         jrecord_leaf(jrec, JLEAF_SIZE, &vat->va_size, sizeof(vat->va_size));
1294     if (vat->va_atime.tv_sec != VNOVAL)
1295         jrecord_leaf(jrec, JLEAF_ATIME, &vat->va_atime, sizeof(vat->va_atime));
1296     if (vat->va_mtime.tv_sec != VNOVAL)
1297         jrecord_leaf(jrec, JLEAF_MTIME, &vat->va_mtime, sizeof(vat->va_mtime));
1298     if (vat->va_ctime.tv_sec != VNOVAL)
1299         jrecord_leaf(jrec, JLEAF_CTIME, &vat->va_ctime, sizeof(vat->va_ctime));
1300     if (vat->va_gen != VNOVAL)
1301         jrecord_leaf(jrec, JLEAF_GEN, &vat->va_gen, sizeof(vat->va_gen));
1302     if (vat->va_flags != VNOVAL)
1303         jrecord_leaf(jrec, JLEAF_FLAGS, &vat->va_flags, sizeof(vat->va_flags));
1304     if (vat->va_rmajor != VNOVAL) {
1305         udev_t rdev = makeudev(vat->va_rmajor, vat->va_rminor);
1306         jrecord_leaf(jrec, JLEAF_UDEV, &rdev, sizeof(rdev));
1307         jrecord_leaf(jrec, JLEAF_UMAJOR, &vat->va_rmajor, sizeof(vat->va_rmajor));
1308         jrecord_leaf(jrec, JLEAF_UMINOR, &vat->va_rminor, sizeof(vat->va_rminor));
1309     }
1310 #if 0
1311     if (vat->va_filerev != VNOVAL)
1312         jrecord_leaf(jrec, JLEAF_FILEREV, &vat->va_filerev, sizeof(vat->va_filerev));
1313 #endif
1314     jrecord_pop(jrec, save);
1315 }
1316
1317 /*
1318  * Write out the creds used to issue a file operation.  If a process is
1319  * available write out additional tracking information related to the 
1320  * process.
1321  *
1322  * XXX additional tracking info
1323  * XXX tty line info
1324  */
1325 void
1326 jrecord_write_cred(struct jrecord *jrec, struct thread *td, struct ucred *cred)
1327 {
1328     void *save;
1329     struct proc *p;
1330
1331     save = jrecord_push(jrec, JTYPE_CRED);
1332     jrecord_leaf(jrec, JLEAF_UID, &cred->cr_uid, sizeof(cred->cr_uid));
1333     jrecord_leaf(jrec, JLEAF_GID, &cred->cr_gid, sizeof(cred->cr_gid));
1334     if (td && (p = td->td_proc) != NULL) {
1335         jrecord_leaf(jrec, JLEAF_PID, &p->p_pid, sizeof(p->p_pid));
1336         jrecord_leaf(jrec, JLEAF_COMM, p->p_comm, sizeof(p->p_comm));
1337     }
1338     jrecord_pop(jrec, save);
1339 }
1340
1341 /*
1342  * Write out information required to identify a vnode
1343  *
1344  * XXX this needs work.  We should write out the inode number as well,
1345  * and in fact avoid writing out the file path for seqential writes
1346  * occuring within e.g. a certain period of time.
1347  */
1348 void
1349 jrecord_write_vnode_ref(struct jrecord *jrec, struct vnode *vp)
1350 {
1351     struct nchandle nch;
1352
1353     nch.mount = vp->v_mount;
1354     spin_lock(&vp->v_spin);
1355     TAILQ_FOREACH(nch.ncp, &vp->v_namecache, nc_vnode) {
1356         if ((nch.ncp->nc_flag & (NCF_UNRESOLVED|NCF_DESTROYED)) == 0)
1357             break;
1358     }
1359     if (nch.ncp) {
1360         cache_hold(&nch);
1361         spin_unlock(&vp->v_spin);
1362         jrecord_write_path(jrec, JLEAF_PATH_REF, nch.ncp);
1363         cache_drop(&nch);
1364     } else {
1365         spin_unlock(&vp->v_spin);
1366     }
1367 }
1368
1369 void
1370 jrecord_write_vnode_link(struct jrecord *jrec, struct vnode *vp, 
1371                          struct namecache *notncp)
1372 {
1373     struct nchandle nch;
1374
1375     nch.mount = vp->v_mount;
1376     spin_lock(&vp->v_spin);
1377     TAILQ_FOREACH(nch.ncp, &vp->v_namecache, nc_vnode) {
1378         if (nch.ncp == notncp)
1379             continue;
1380         if ((nch.ncp->nc_flag & (NCF_UNRESOLVED|NCF_DESTROYED)) == 0)
1381             break;
1382     }
1383     if (nch.ncp) {
1384         cache_hold(&nch);
1385         spin_unlock(&vp->v_spin);
1386         jrecord_write_path(jrec, JLEAF_PATH_REF, nch.ncp);
1387         cache_drop(&nch);
1388     } else {
1389         spin_unlock(&vp->v_spin);
1390     }
1391 }
1392
1393 /*
1394  * Write out the data represented by a pagelist
1395  */
1396 void
1397 jrecord_write_pagelist(struct jrecord *jrec, int16_t rectype,
1398                         struct vm_page **pglist, int *rtvals, int pgcount,
1399                         off_t offset)
1400 {
1401     struct xio xio;
1402     int error;
1403     int b;
1404     int i;
1405
1406     i = 0;
1407     xio_init(&xio);
1408     while (i < pgcount) {
1409         /*
1410          * Find the next valid section.  Skip any invalid elements
1411          */
1412         if (rtvals[i] != VM_PAGER_OK) {
1413             ++i;
1414             offset += PAGE_SIZE;
1415             continue;
1416         }
1417
1418         /*
1419          * Figure out how big the valid section is, capping I/O at what the
1420          * MSFBUF can represent.
1421          */
1422         b = i;
1423         while (i < pgcount && i - b != XIO_INTERNAL_PAGES && 
1424                rtvals[i] == VM_PAGER_OK
1425         ) {
1426             ++i;
1427         }
1428
1429         /*
1430          * And write it out.
1431          */
1432         if (i - b) {
1433             error = xio_init_pages(&xio, pglist + b, i - b, XIOF_READ);
1434             if (error == 0) {
1435                 jrecord_leaf(jrec, JLEAF_SEEKPOS, &offset, sizeof(offset));
1436                 jrecord_leaf_xio(jrec, rectype, &xio);
1437             } else {
1438                 kprintf("jrecord_write_pagelist: xio init failure\n");
1439             }
1440             xio_release(&xio);
1441             offset += (off_t)(i - b) << PAGE_SHIFT;
1442         }
1443     }
1444 }
1445
1446 /*
1447  * Write out the data represented by a UIO.
1448  */
1449 void
1450 jrecord_write_uio(struct jrecord *jrec, int16_t rectype, struct uio *uio)
1451 {
1452     if (uio->uio_segflg != UIO_NOCOPY) {
1453         jrecord_leaf(jrec, JLEAF_SEEKPOS, &uio->uio_offset, 
1454                      sizeof(uio->uio_offset));
1455         jrecord_leaf_uio(jrec, rectype, uio);
1456     }
1457 }
1458
1459 void
1460 jrecord_file_data(struct jrecord *jrec, struct vnode *vp, 
1461                   off_t off, off_t bytes)
1462 {
1463     const int bufsize = 8192;
1464     char *buf;
1465     int error;
1466     int n;
1467
1468     buf = kmalloc(bufsize, M_JOURNAL, M_WAITOK);
1469     jrecord_leaf(jrec, JLEAF_SEEKPOS, &off, sizeof(off));
1470     while (bytes) {
1471         n = (bytes > bufsize) ? bufsize : (int)bytes;
1472         error = vn_rdwr(UIO_READ, vp, buf, n, off, UIO_SYSSPACE, IO_NODELOCKED,
1473                         proc0.p_ucred, NULL);
1474         if (error) {
1475             jrecord_leaf(jrec, JLEAF_ERROR, &error, sizeof(error));
1476             break;
1477         }
1478         jrecord_leaf(jrec, JLEAF_FILEDATA, buf, n);
1479         bytes -= n;
1480         off += n;
1481     }
1482     kfree(buf, M_JOURNAL);
1483 }
1484