2 * Copyright (c) 2004-2006 The DragonFly Project. All rights reserved.
4 * This code is derived from software contributed to The DragonFly Project
5 * by Matthew Dillon <dillon@backplane.com>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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
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.
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
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.
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.
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.
61 #include <sys/param.h>
62 #include <sys/systm.h>
65 #include <sys/kernel.h>
66 #include <sys/queue.h>
68 #include <sys/malloc.h>
69 #include <sys/mount.h>
70 #include <sys/unistd.h>
71 #include <sys/vnode.h>
73 #include <sys/mountctl.h>
74 #include <sys/journal.h>
78 #include <sys/socket.h>
79 #include <sys/socketvar.h>
81 #include <machine/limits.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>
89 #include <sys/file2.h>
90 #include <sys/mplock2.h>
91 #include <sys/spinlock2.h>
93 static void journal_wthread(void *info);
94 static void journal_rthread(void *info);
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);
111 MALLOC_DEFINE(M_JOURNAL, "journal", "Journaling structures");
112 MALLOC_DEFINE(M_JFIFO, "journal-fifo", "Journal FIFO");
115 journal_create_threads(struct journal *jo)
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,
121 "journal w:%.*s", JIDMAX, jo->id);
122 lwkt_setpri(&jo->wthread, TDPRI_KERN_DAEMON);
123 lwkt_schedule(&jo->wthread);
125 if (jo->flags & MC_JOURNAL_WANT_FULLDUPLEX) {
126 jo->flags |= MC_JOURNAL_RACTIVE;
127 lwkt_create(journal_rthread, jo, NULL, &jo->rthread,
129 "journal r:%.*s", JIDMAX, jo->id);
130 lwkt_setpri(&jo->rthread, TDPRI_KERN_DAEMON);
131 lwkt_schedule(&jo->rthread);
136 journal_destroy_threads(struct journal *jo, int flags)
140 jo->flags |= MC_JOURNAL_STOP_REQ | (flags & MC_JOURNAL_STOP_IMM);
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",
152 * XXX SMP - threads should move to cpu requesting the restart or
153 * termination before finishing up to properly interlock.
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);
162 * The per-journal worker thread is responsible for writing out the
163 * journal's FIFO to the target stream.
166 journal_wthread(void *info)
168 struct journal *jo = info;
169 struct journal_rawrecbeg *rawp;
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.
184 bytes = jo->fifo.windex - jo->fifo.rindex;
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.
192 if (jo->flags & MC_JOURNAL_STOP_REQ)
194 tsleep(&jo->fifo, 0, "jfifo", hz);
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
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);
210 * Skip any pad records. We do not write out pad records if we can
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;
220 jo->fifo.rindex += (rawp->recsize + 15) & ~15;
221 jo->total_acked += bytes;
222 KKASSERT(jo->fifo.windex - jo->fifo.rindex >= 0);
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
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;
239 KKASSERT(res == avail);
242 rawp = (void *)((char *)rawp + ((rawp->recsize + 15) & ~15));
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.
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.
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
261 jo->fifo.rindex += bytes;
262 error = fp_write(jo->fp,
264 ((jo->fifo.rindex - bytes) & jo->fifo.mask),
265 bytes, &res, UIO_SYSSPACE);
267 kprintf("journal_thread(%s) write, error %d\n", jo->id, error);
270 KKASSERT(res == bytes);
274 * Advance rindex. If the journal stream is not full duplex we also
275 * advance xindex, otherwise the rjournal thread is responsible for
278 if ((jo->flags & MC_JOURNAL_WANT_FULLDUPLEX) == 0) {
279 jo->fifo.xindex += bytes;
280 jo->total_acked += bytes;
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);
290 fp_shutdown(jo->fp, SHUT_WR);
291 jo->flags &= ~MC_JOURNAL_WACTIVE;
293 wakeup(&jo->fifo.windex);
298 * A second per-journal worker thread is created for two-way journaling
299 * streams to deal with the return acknowledgement stream.
302 journal_rthread(void *info)
304 struct journal_rawrecbeg *rawp;
305 struct journal_ackrecord ack;
306 struct journal *jo = info;
320 * We have been asked to stop
322 if (jo->flags & MC_JOURNAL_STOP_REQ)
326 * If we have no active transaction id, get one from the return
330 error = fp_read(jo->fp, &ack, sizeof(ack), &count,
333 kprintf("fp_read ack error %d count %d\n", error, count);
335 if (error || count != sizeof(ack))
338 kprintf("read error %d on receive stream\n", error);
341 if (ack.rbeg.begmagic != JREC_BEGMAGIC ||
342 ack.rend.endmagic != JREC_ENDMAGIC
344 kprintf("bad begmagic or endmagic on receive stream\n");
347 transid = ack.rbeg.transid;
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.
356 bytes = jo->fifo.rindex - jo->fifo.xindex;
359 kprintf("warning: unsent data acknowledged transid %08llx\n",
361 tsleep(&jo->fifo.xindex, 0, "jrseq", hz);
367 * Since rindex has advanced, the record pointed to by xindex
368 * must be a valid record.
370 rawp = (void *)(jo->fifo.membase + (jo->fifo.xindex & jo->fifo.mask));
371 KKASSERT(rawp->begmagic == JREC_BEGMAGIC);
372 KKASSERT(rawp->recsize <= bytes);
375 * The target can acknowledge several records at once.
377 if (rawp->transid < transid) {
379 kprintf("ackskip %08llx/%08llx\n",
380 (long long)rawp->transid,
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);
391 if (rawp->transid == transid) {
393 kprintf("ackskip %08llx/%08llx\n",
394 (long long)rawp->transid,
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);
406 kprintf("warning: unsent data(2) acknowledged transid %08llx\n",
410 jo->flags &= ~MC_JOURNAL_RACTIVE;
412 wakeup(&jo->fifo.windex);
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.
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.
426 journal_build_pad(struct journal_rawrecbeg *rawp, int recsize, int64_t transid)
428 struct journal_rawrecend *rendp;
430 KKASSERT((recsize & 15) == 0 && recsize >= 16);
432 rawp->streamid = JREC_STREAMID_PAD;
433 rawp->recsize = recsize; /* must be 16-byte aligned */
434 rawp->transid = transid;
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.
440 rendp = (void *)((char *)rawp + rawp->recsize - sizeof(*rendp));
441 rendp->endmagic = JREC_ENDMAGIC;
443 rendp->recsize = rawp->recsize;
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.
451 rawp->begmagic = JREC_BEGMAGIC;
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.
462 journal_commit_wakeup(struct journal *jo)
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))
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.
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
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.
498 journal_reserve(struct journal *jo, struct journal_rawrecbeg **rawpp,
499 int16_t streamid, int bytes)
501 struct journal_rawrecbeg *rawp;
507 * Add header and trailer overheads to the passed payload. Note that
508 * the passed payload size need not be aligned in any way.
510 bytes += sizeof(struct journal_rawrecbeg);
511 bytes += sizeof(struct journal_rawrecend);
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.
520 * Neither 'bytes' or 'req' are aligned.
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.
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 */
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.
540 avail = jo->fifo.size - (jo->fifo.windex - jo->fifo.xindex);
541 KKASSERT(avail >= 0 && (avail & 15) == 0);
544 /* XXX MC_JOURNAL_STOP_IMM */
545 jo->flags |= MC_JOURNAL_WWAIT;
547 tsleep(&jo->fifo.windex, 0, "jwrite", 0);
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.
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.
562 * The transaction id must accomodate real and potential pad creation.
564 rawp = (void *)(jo->fifo.membase + (jo->fifo.windex & jo->fifo.mask));
566 journal_build_pad(rawp, availtoend, jo->transid);
568 rawp = (void *)jo->fifo.membase;
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;
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.
582 * Note that stream records are always 16-byte aligned.
585 jo->fifo.windex += (req + 15) & ~15;
595 * Attempt to extend the stream record by <bytes> worth of payload space.
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.
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.
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.
611 journal_extend(struct journal *jo, struct journal_rawrecbeg **rawpp,
612 int truncbytes, int bytes, int *newstreamrecp)
614 struct journal_rawrecbeg *rawp;
625 osize = (rawp->recsize + 15) & ~15;
626 nsize = (rawp->recsize + bytes + 15) & ~15;
627 wbase = (char *)rawp - jo->fifo.membase;
630 * If the aligned record size does not change we can trivially adjust
633 if (nsize == osize) {
634 rawp->recsize += bytes;
635 return((char *)(rawp + 1) + truncbytes);
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.
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);
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).
661 streamid = rawp->streamid & JREC_STREAMID_MASK;
662 journal_commit(jo, rawpp, truncbytes, 0);
663 rptr = journal_reserve(jo, rawpp, streamid, bytes);
665 rawp->streamid &= ~JREC_STREAMCTL_BEGIN;
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.
675 * Otherwise we set the JREC_STREAMCTL_ABORTED bit and commit the record
676 * with the payload truncated to 0 bytes.
679 journal_abort(struct journal *jo, struct journal_rawrecbeg **rawpp)
681 struct journal_rawrecbeg *rawp;
685 osize = (rawp->recsize + 15) & ~15;
687 if ((rawp->streamid & JREC_STREAMCTL_BEGIN) &&
688 (jo->fifo.windex & jo->fifo.mask) ==
689 (char *)rawp - jo->fifo.membase + osize)
691 jo->fifo.windex -= osize;
694 rawp->streamid |= JREC_STREAMCTL_ABORTED;
695 journal_commit(jo, rawpp, 0, 1);
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.
706 * The logical stream is terminated by this function.
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.
713 journal_commit(struct journal *jo, struct journal_rawrecbeg **rawpp,
714 int bytes, int closeout)
716 struct journal_rawrecbeg *rawp;
717 struct journal_rawrecend *rendp;
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);
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.
733 * We calculate osize which is the 16-byte-aligned original recsize.
734 * We calculate nsize which is the 16-byte-aligned new recsize.
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.
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) {
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;
753 /* we cannot backindex the fifo, emplace a pad in the dead space */
754 journal_build_pad((void *)((char *)rawp + nsize), osize - nsize,
760 * Fill in the trailer. Note that unlike pad records, the trailer will
761 * never overlap the header.
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 */
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.
775 rawp->streamid |= JREC_STREAMCTL_END;
776 cpu_sfence(); /* memory and compiler barrier */
777 rawp->begmagic = JREC_BEGMAGIC;
779 journal_commit_wakeup(jo);
782 /************************************************************************
783 * TRANSACTION SUPPORT ROUTINES *
784 ************************************************************************
786 * JRECORD_*() - routines to create subrecord transactions and embed them
787 * in the logical streams managed by the journal_*() routines.
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.
795 jrecord_init(struct journal *jo, struct jrecord *jrec, int16_t streamid)
797 bzero(jrec, sizeof(*jrec));
799 jrec->streamid = streamid;
800 jrec->stream_residual = JREC_DEFAULTSIZE;
801 jrec->stream_reserved = jrec->stream_residual;
803 journal_reserve(jo, &jrec->rawp, streamid, jrec->stream_reserved);
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.
814 struct journal_subrecord *
815 jrecord_push(struct jrecord *jrec, int16_t rectype)
817 struct journal_subrecord *save;
820 jrec->parent = jrecord_write(jrec, rectype|JMASK_NESTED, 0);
822 KKASSERT(jrec->parent != NULL);
824 ++jrec->pushptrgood; /* cleared on flush */
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.
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.
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
844 jrecord_pop(struct jrecord *jrec, struct journal_subrecord *save)
846 struct journal_subrecord *last;
848 KKASSERT(jrec->pushcount > 0);
849 KKASSERT(jrec->residual == 0);
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
857 if ((last = jrec->last) == NULL) {
858 jrecord_write(jrec, JLEAF_PAD|JMASK_LAST, 0);
859 last = jrec->last; /* reload after possible flush */
861 last->rectype |= JMASK_LAST;
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.
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.
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.
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
894 * This pop sets the new 'last' record to parentB, the pointer
895 * to which may or may not still be accessible.
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.
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
904 * This pop sets the new 'last' record to parentA, the pointer
905 * to which may or may not still be accessible.
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
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.
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).
921 jrec->last = jrec->parent;
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 */
928 KKASSERT(save != NULL);
929 jrec->parent = save; /* 'save' must not be NULL */
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).
938 jrec->last->recsize = (char *)last + last->recsize - (char *)jrec->last;
941 KKASSERT(jrec->last == NULL);
946 * Write out a leaf record, including associated data.
949 jrecord_leaf(struct jrecord *jrec, int16_t rectype, void *ptr, int bytes)
951 jrecord_write(jrec, rectype, bytes);
952 jrecord_data(jrec, ptr, bytes, JDATA_KERN);
956 jrecord_leaf_uio(struct jrecord *jrec, int16_t rectype,
962 for (i = 0; i < uio->uio_iovcnt; ++i) {
963 iov = &uio->uio_iov[i];
964 if (iov->iov_len == 0)
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);
977 jrecord_leaf_xio(struct jrecord *jrec, int16_t rectype, xio_t xio)
979 int bytes = xio->xio_npages * PAGE_SIZE;
981 jrecord_write(jrec, rectype, bytes);
982 jrecord_data(jrec, xio, bytes, JDATA_XIO);
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
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.
995 struct journal_subrecord *
996 jrecord_write(struct jrecord *jrec, int16_t rectype, int bytes)
998 struct journal_subrecord *last;
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).
1006 KKASSERT(bytes == 0 || (rectype & JMASK_NESTED) == 0);
1007 KKASSERT(jrec->residual == 0);
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
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
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);
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.
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 */
1034 * If no pushout occured the stream record is NOT truncated and
1037 jrec->stream_reserved += JREC_DEFAULTSIZE;
1038 jrec->stream_residual += JREC_DEFAULTSIZE;
1041 last = (void *)jrec->stream_ptr;
1042 last->rectype = rectype;
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.
1050 if ((rectype & JMASK_NESTED) && bytes == 0)
1053 last->recsize = sizeof(struct journal_subrecord) + bytes;
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 */
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().
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.
1072 jrecord_data(struct jrecord *jrec, void *buf, int bytes, int dtype)
1078 KKASSERT(bytes >= 0 && bytes <= jrec->residual);
1081 * Push out stream records as long as there is insufficient room to hold
1082 * the remaining data.
1084 while (jrec->stream_residual < bytes) {
1086 * Fill in any remaining space in the current stream record.
1090 bcopy(buf, jrec->stream_ptr, jrec->stream_residual);
1093 copyin(buf, jrec->stream_ptr, jrec->stream_residual);
1096 xio_copy_xtok((xio_t)buf, xio_offset, jrec->stream_ptr,
1097 jrec->stream_residual);
1098 xio_offset += jrec->stream_residual;
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;
1109 * Try to extend the current stream record, but no more then 1/4
1110 * the size of the FIFO.
1112 extsize = jrec->jo->fifo.size >> 2;
1113 if (extsize > bytes)
1114 extsize = (bytes + 15) & ~15;
1116 jrec->stream_ptr = journal_extend(jrec->jo, &jrec->rawp,
1117 jrec->stream_reserved - jrec->stream_residual,
1118 extsize, &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 */
1126 jrec->stream_reserved += extsize;
1127 jrec->stream_residual += extsize;
1132 * Push out any remaining bytes into the current stream record.
1137 bcopy(buf, jrec->stream_ptr, bytes);
1140 copyin(buf, jrec->stream_ptr, bytes);
1143 xio_copy_xtok((xio_t)buf, xio_offset, jrec->stream_ptr, bytes);
1146 jrec->stream_ptr += bytes;
1147 jrec->stream_residual -= bytes;
1148 jrec->residual -= bytes;
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.
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;
1166 * We are finished with the transaction. This closes the transaction created
1167 * by jrecord_init().
1169 * NOTE: If abortit is not set then we must be at the top level with no
1170 * residual subrecord data left to output.
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.
1177 * The stream record will be committed or aborted as specified and jrecord
1178 * resources will be cleaned up.
1181 jrecord_done(struct jrecord *jrec, int abortit)
1183 KKASSERT(jrec->rawp != NULL);
1186 journal_abort(jrec->jo, &jrec->rawp);
1188 KKASSERT(jrec->pushcount == 0 && jrec->residual == 0);
1189 journal_commit(jrec->jo, &jrec->rawp,
1190 jrec->stream_reserved - jrec->stream_residual, 1);
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.
1197 * Note that jrec->rawp is NULLd out by journal_abort/journal_commit.
1200 jrec->stream_ptr = NULL;
1203 /************************************************************************
1204 * LOW LEVEL RECORD SUPPORT ROUTINES *
1205 ************************************************************************
1207 * These routine create low level recursive and leaf subrecords representing
1208 * common filesystem structures.
1212 * Write out a filename path relative to the base of the mount point.
1213 * rectype is typically JLEAF_PATH{1,2,3,4}.
1216 jrecord_write_path(struct jrecord *jrec, int16_t rectype, struct namecache *ncp)
1218 char buf[64]; /* local buffer if it fits, else malloced */
1222 struct namecache *scan;
1225 * Pass 1 - figure out the number of bytes required. Include terminating
1226 * \0 on last element and '/' separator on other elements.
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).
1234 for (scan = ncp; scan; scan = scan->nc_parent) {
1235 if (scan->nc_nlen > 0)
1236 pathlen += scan->nc_nlen + 1;
1239 if (pathlen <= sizeof(buf))
1242 base = kmalloc(pathlen, M_TEMP, M_INTWAIT);
1245 * Pass 2 - generate the path buffer
1248 for (scan = ncp; scan; scan = scan->nc_parent) {
1249 if (scan->nc_nlen == 0)
1251 if (scan->nc_nlen >= index) {
1253 kfree(base, M_TEMP);
1256 if (index == pathlen)
1259 base[--index] = '/';
1260 index -= scan->nc_nlen;
1261 bcopy(scan->nc_name, base + index, scan->nc_nlen);
1263 jrecord_leaf(jrec, rectype, base + index, pathlen - index);
1265 kfree(base, M_TEMP);
1269 * Write out a file attribute structure. While somewhat inefficient, using
1270 * a recursive data structure is the most portable and extensible way.
1273 jrecord_write_vattr(struct jrecord *jrec, struct vattr *vat)
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 dev_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));
1311 if (vat->va_filerev != VNOVAL)
1312 jrecord_leaf(jrec, JLEAF_FILEREV, &vat->va_filerev, sizeof(vat->va_filerev));
1314 jrecord_pop(jrec, save);
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
1322 * XXX additional tracking info
1326 jrecord_write_cred(struct jrecord *jrec, struct thread *td, struct ucred *cred)
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));
1338 jrecord_pop(jrec, save);
1342 * Write out information required to identify a vnode
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.
1349 jrecord_write_vnode_ref(struct jrecord *jrec, struct vnode *vp)
1351 struct nchandle nch;
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)
1361 spin_unlock(&vp->v_spin);
1362 jrecord_write_path(jrec, JLEAF_PATH_REF, nch.ncp);
1365 spin_unlock(&vp->v_spin);
1370 jrecord_write_vnode_link(struct jrecord *jrec, struct vnode *vp,
1371 struct namecache *notncp)
1373 struct nchandle nch;
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)
1380 if ((nch.ncp->nc_flag & (NCF_UNRESOLVED|NCF_DESTROYED)) == 0)
1385 spin_unlock(&vp->v_spin);
1386 jrecord_write_path(jrec, JLEAF_PATH_REF, nch.ncp);
1389 spin_unlock(&vp->v_spin);
1394 * Write out the data represented by a pagelist
1397 jrecord_write_pagelist(struct jrecord *jrec, int16_t rectype,
1398 struct vm_page **pglist, int *rtvals, int pgcount,
1408 while (i < pgcount) {
1410 * Find the next valid section. Skip any invalid elements
1412 if (rtvals[i] != VM_PAGER_OK) {
1414 offset += PAGE_SIZE;
1419 * Figure out how big the valid section is, capping I/O at what the
1420 * MSFBUF can represent.
1423 while (i < pgcount && i - b != XIO_INTERNAL_PAGES &&
1424 rtvals[i] == VM_PAGER_OK
1433 error = xio_init_pages(&xio, pglist + b, i - b, XIOF_READ);
1435 jrecord_leaf(jrec, JLEAF_SEEKPOS, &offset, sizeof(offset));
1436 jrecord_leaf_xio(jrec, rectype, &xio);
1438 kprintf("jrecord_write_pagelist: xio init failure\n");
1441 offset += (off_t)(i - b) << PAGE_SHIFT;
1447 * Write out the data represented by a UIO.
1450 jrecord_write_uio(struct jrecord *jrec, int16_t rectype, struct uio *uio)
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);
1460 jrecord_file_data(struct jrecord *jrec, struct vnode *vp,
1461 off_t off, off_t bytes)
1463 const int bufsize = 8192;
1468 buf = kmalloc(bufsize, M_JOURNAL, M_WAITOK);
1469 jrecord_leaf(jrec, JLEAF_SEEKPOS, &off, sizeof(off));
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);
1475 jrecord_leaf(jrec, JLEAF_ERROR, &error, sizeof(error));
1478 jrecord_leaf(jrec, JLEAF_FILEDATA, buf, n);
1482 kfree(buf, M_JOURNAL);