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