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
34 * $DragonFly: src/sys/kern/vfs_journal.c,v 1.30 2006/12/23 00:35:04 swildner Exp $
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.
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.
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.
63 #include <sys/param.h>
64 #include <sys/systm.h>
67 #include <sys/kernel.h>
68 #include <sys/queue.h>
70 #include <sys/malloc.h>
71 #include <sys/mount.h>
72 #include <sys/unistd.h>
73 #include <sys/vnode.h>
75 #include <sys/mountctl.h>
76 #include <sys/journal.h>
79 #include <sys/msfbuf.h>
80 #include <sys/socket.h>
81 #include <sys/socketvar.h>
83 #include <machine/limits.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>
91 #include <sys/file2.h>
92 #include <sys/thread2.h>
94 static void journal_wthread(void *info);
95 static void journal_rthread(void *info);
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);
110 MALLOC_DEFINE(M_JOURNAL, "journal", "Journaling structures");
111 MALLOC_DEFINE(M_JFIFO, "journal-fifo", "Journal FIFO");
114 journal_create_threads(struct journal *jo)
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);
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);
133 journal_destroy_threads(struct journal *jo, int flags)
137 jo->flags |= MC_JOURNAL_STOP_REQ | (flags & MC_JOURNAL_STOP_IMM);
140 while (jo->flags & (MC_JOURNAL_WACTIVE | MC_JOURNAL_RACTIVE)) {
141 tsleep(jo, 0, "jwait", hz);
142 if (++wcount % 10 == 0) {
143 kprintf("Warning: journal %s waiting for descriptors to close\n",
149 * XXX SMP - threads should move to cpu requesting the restart or
150 * termination before finishing up to properly interlock.
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);
159 * The per-journal worker thread is responsible for writing out the
160 * journal's FIFO to the target stream.
163 journal_wthread(void *info)
165 struct journal *jo = info;
166 struct journal_rawrecbeg *rawp;
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.
178 bytes = jo->fifo.windex - jo->fifo.rindex;
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.
186 if (jo->flags & MC_JOURNAL_STOP_REQ)
188 tsleep(&jo->fifo, 0, "jfifo", hz);
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
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);
204 * Skip any pad records. We do not write out pad records if we can
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;
214 jo->fifo.rindex += (rawp->recsize + 15) & ~15;
215 jo->total_acked += bytes;
216 KKASSERT(jo->fifo.windex - jo->fifo.rindex >= 0);
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
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;
233 KKASSERT(res == avail);
236 rawp = (void *)((char *)rawp + ((rawp->recsize + 15) & ~15));
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.
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.
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
255 jo->fifo.rindex += bytes;
256 error = fp_write(jo->fp,
257 jo->fifo.membase + ((jo->fifo.rindex - bytes) & jo->fifo.mask),
260 kprintf("journal_thread(%s) write, error %d\n", jo->id, error);
263 KKASSERT(res == bytes);
267 * Advance rindex. If the journal stream is not full duplex we also
268 * advance xindex, otherwise the rjournal thread is responsible for
271 if ((jo->flags & MC_JOURNAL_WANT_FULLDUPLEX) == 0) {
272 jo->fifo.xindex += bytes;
273 jo->total_acked += bytes;
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);
283 fp_shutdown(jo->fp, SHUT_WR);
284 jo->flags &= ~MC_JOURNAL_WACTIVE;
286 wakeup(&jo->fifo.windex);
290 * A second per-journal worker thread is created for two-way journaling
291 * streams to deal with the return acknowledgement stream.
294 journal_rthread(void *info)
296 struct journal_rawrecbeg *rawp;
297 struct journal_ackrecord ack;
298 struct journal *jo = info;
309 * We have been asked to stop
311 if (jo->flags & MC_JOURNAL_STOP_REQ)
315 * If we have no active transaction id, get one from the return
319 error = fp_read(jo->fp, &ack, sizeof(ack), &count, 1);
321 kprintf("fp_read ack error %d count %d\n", error, count);
323 if (error || count != sizeof(ack))
326 kprintf("read error %d on receive stream\n", error);
329 if (ack.rbeg.begmagic != JREC_BEGMAGIC ||
330 ack.rend.endmagic != JREC_ENDMAGIC
332 kprintf("bad begmagic or endmagic on receive stream\n");
335 transid = ack.rbeg.transid;
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.
344 bytes = jo->fifo.rindex - jo->fifo.xindex;
347 kprintf("warning: unsent data acknowledged transid %08llx\n", transid);
348 tsleep(&jo->fifo.xindex, 0, "jrseq", hz);
354 * Since rindex has advanced, the record pointed to by xindex
355 * must be a valid record.
357 rawp = (void *)(jo->fifo.membase + (jo->fifo.xindex & jo->fifo.mask));
358 KKASSERT(rawp->begmagic == JREC_BEGMAGIC);
359 KKASSERT(rawp->recsize <= bytes);
362 * The target can acknowledge several records at once.
364 if (rawp->transid < transid) {
366 kprintf("ackskip %08llx/%08llx\n", rawp->transid, transid);
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);
376 if (rawp->transid == transid) {
378 kprintf("ackskip %08llx/%08llx\n", rawp->transid, transid);
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);
389 kprintf("warning: unsent data(2) acknowledged transid %08llx\n", transid);
392 jo->flags &= ~MC_JOURNAL_RACTIVE;
394 wakeup(&jo->fifo.windex);
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.
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.
407 journal_build_pad(struct journal_rawrecbeg *rawp, int recsize, int64_t transid)
409 struct journal_rawrecend *rendp;
411 KKASSERT((recsize & 15) == 0 && recsize >= 16);
413 rawp->streamid = JREC_STREAMID_PAD;
414 rawp->recsize = recsize; /* must be 16-byte aligned */
415 rawp->transid = transid;
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.
421 rendp = (void *)((char *)rawp + rawp->recsize - sizeof(*rendp));
422 rendp->endmagic = JREC_ENDMAGIC;
424 rendp->recsize = rawp->recsize;
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.
432 rawp->begmagic = JREC_BEGMAGIC;
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.
443 journal_commit_wakeup(struct journal *jo)
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))
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.
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
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.
479 journal_reserve(struct journal *jo, struct journal_rawrecbeg **rawpp,
480 int16_t streamid, int bytes)
482 struct journal_rawrecbeg *rawp;
488 * Add header and trailer overheads to the passed payload. Note that
489 * the passed payload size need not be aligned in any way.
491 bytes += sizeof(struct journal_rawrecbeg);
492 bytes += sizeof(struct journal_rawrecend);
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.
501 * Neither 'bytes' or 'req' are aligned.
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.
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 */
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.
521 avail = jo->fifo.size - (jo->fifo.windex - jo->fifo.xindex);
522 KKASSERT(avail >= 0 && (avail & 15) == 0);
525 /* XXX MC_JOURNAL_STOP_IMM */
526 jo->flags |= MC_JOURNAL_WWAIT;
528 tsleep(&jo->fifo.windex, 0, "jwrite", 0);
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.
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.
543 * The transaction id must accomodate real and potential pad creation.
545 rawp = (void *)(jo->fifo.membase + (jo->fifo.windex & jo->fifo.mask));
547 journal_build_pad(rawp, availtoend, jo->transid);
549 rawp = (void *)jo->fifo.membase;
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;
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.
563 * Note that stream records are always 16-byte aligned.
566 jo->fifo.windex += (req + 15) & ~15;
576 * Attempt to extend the stream record by <bytes> worth of payload space.
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.
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.
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.
592 journal_extend(struct journal *jo, struct journal_rawrecbeg **rawpp,
593 int truncbytes, int bytes, int *newstreamrecp)
595 struct journal_rawrecbeg *rawp;
606 osize = (rawp->recsize + 15) & ~15;
607 nsize = (rawp->recsize + bytes + 15) & ~15;
608 wbase = (char *)rawp - jo->fifo.membase;
611 * If the aligned record size does not change we can trivially adjust
614 if (nsize == osize) {
615 rawp->recsize += bytes;
616 return((char *)(rawp + 1) + truncbytes);
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.
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);
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).
642 streamid = rawp->streamid & JREC_STREAMID_MASK;
643 journal_commit(jo, rawpp, truncbytes, 0);
644 rptr = journal_reserve(jo, rawpp, streamid, bytes);
646 rawp->streamid &= ~JREC_STREAMCTL_BEGIN;
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.
656 * Otherwise we set the JREC_STREAMCTL_ABORTED bit and commit the record
657 * with the payload truncated to 0 bytes.
660 journal_abort(struct journal *jo, struct journal_rawrecbeg **rawpp)
662 struct journal_rawrecbeg *rawp;
666 osize = (rawp->recsize + 15) & ~15;
668 if ((rawp->streamid & JREC_STREAMCTL_BEGIN) &&
669 (jo->fifo.windex & jo->fifo.mask) ==
670 (char *)rawp - jo->fifo.membase + osize)
672 jo->fifo.windex -= osize;
675 rawp->streamid |= JREC_STREAMCTL_ABORTED;
676 journal_commit(jo, rawpp, 0, 1);
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.
687 * The logical stream is terminated by this function.
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.
694 journal_commit(struct journal *jo, struct journal_rawrecbeg **rawpp,
695 int bytes, int closeout)
697 struct journal_rawrecbeg *rawp;
698 struct journal_rawrecend *rendp;
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);
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.
714 * We calculate osize which is the 16-byte-aligned original recsize.
715 * We calculate nsize which is the 16-byte-aligned new recsize.
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.
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) {
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;
734 /* we cannot backindex the fifo, emplace a pad in the dead space */
735 journal_build_pad((void *)((char *)rawp + nsize), osize - nsize,
741 * Fill in the trailer. Note that unlike pad records, the trailer will
742 * never overlap the header.
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 */
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.
756 rawp->streamid |= JREC_STREAMCTL_END;
757 cpu_sfence(); /* memory and compiler barrier */
758 rawp->begmagic = JREC_BEGMAGIC;
760 journal_commit_wakeup(jo);
763 /************************************************************************
764 * TRANSACTION SUPPORT ROUTINES *
765 ************************************************************************
767 * JRECORD_*() - routines to create subrecord transactions and embed them
768 * in the logical streams managed by the journal_*() routines.
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.
776 jrecord_init(struct journal *jo, struct jrecord *jrec, int16_t streamid)
778 bzero(jrec, sizeof(*jrec));
780 jrec->streamid = streamid;
781 jrec->stream_residual = JREC_DEFAULTSIZE;
782 jrec->stream_reserved = jrec->stream_residual;
784 journal_reserve(jo, &jrec->rawp, streamid, jrec->stream_reserved);
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.
795 struct journal_subrecord *
796 jrecord_push(struct jrecord *jrec, int16_t rectype)
798 struct journal_subrecord *save;
801 jrec->parent = jrecord_write(jrec, rectype|JMASK_NESTED, 0);
803 KKASSERT(jrec->parent != NULL);
805 ++jrec->pushptrgood; /* cleared on flush */
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.
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.
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
825 jrecord_pop(struct jrecord *jrec, struct journal_subrecord *save)
827 struct journal_subrecord *last;
829 KKASSERT(jrec->pushcount > 0);
830 KKASSERT(jrec->residual == 0);
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
838 if ((last = jrec->last) == NULL) {
839 jrecord_write(jrec, JLEAF_PAD|JMASK_LAST, 0);
840 last = jrec->last; /* reload after possible flush */
842 last->rectype |= JMASK_LAST;
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.
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.
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.
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
875 * This pop sets the new 'last' record to parentB, the pointer
876 * to which may or may not still be accessible.
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.
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
885 * This pop sets the new 'last' record to parentA, the pointer
886 * to which may or may not still be accessible.
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
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.
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).
902 jrec->last = jrec->parent;
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 */
909 KKASSERT(save != NULL);
910 jrec->parent = save; /* 'save' must not be NULL */
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).
919 jrec->last->recsize = (char *)last + last->recsize - (char *)jrec->last;
922 KKASSERT(jrec->last == NULL);
927 * Write out a leaf record, including associated data.
930 jrecord_leaf(struct jrecord *jrec, int16_t rectype, void *ptr, int bytes)
932 jrecord_write(jrec, rectype, bytes);
933 jrecord_data(jrec, ptr, bytes);
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
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.
946 struct journal_subrecord *
947 jrecord_write(struct jrecord *jrec, int16_t rectype, int bytes)
949 struct journal_subrecord *last;
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).
957 KKASSERT(bytes == 0 || (rectype & JMASK_NESTED) == 0);
958 KKASSERT(jrec->residual == 0);
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
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
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);
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.
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 */
985 * If no pushout occured the stream record is NOT truncated and
988 jrec->stream_reserved += JREC_DEFAULTSIZE;
989 jrec->stream_residual += JREC_DEFAULTSIZE;
992 last = (void *)jrec->stream_ptr;
993 last->rectype = rectype;
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.
1001 if ((rectype & JMASK_NESTED) && bytes == 0)
1004 last->recsize = sizeof(struct journal_subrecord) + bytes;
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 */
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().
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.
1023 jrecord_data(struct jrecord *jrec, const void *buf, int bytes)
1028 KKASSERT(bytes >= 0 && bytes <= jrec->residual);
1031 * Push out stream records as long as there is insufficient room to hold
1032 * the remaining data.
1034 while (jrec->stream_residual < bytes) {
1036 * Fill in any remaining space in the current stream record.
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;
1046 * Try to extend the current stream record, but no more then 1/4
1047 * the size of the FIFO.
1049 extsize = jrec->jo->fifo.size >> 2;
1050 if (extsize > bytes)
1051 extsize = (bytes + 15) & ~15;
1053 jrec->stream_ptr = journal_extend(jrec->jo, &jrec->rawp,
1054 jrec->stream_reserved - jrec->stream_residual,
1055 extsize, &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 */
1063 jrec->stream_reserved += extsize;
1064 jrec->stream_residual += extsize;
1069 * Push out any remaining bytes into the current stream record.
1072 bcopy(buf, jrec->stream_ptr, bytes);
1073 jrec->stream_ptr += bytes;
1074 jrec->stream_residual -= bytes;
1075 jrec->residual -= bytes;
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.
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;
1093 * We are finished with the transaction. This closes the transaction created
1094 * by jrecord_init().
1096 * NOTE: If abortit is not set then we must be at the top level with no
1097 * residual subrecord data left to output.
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.
1104 * The stream record will be committed or aborted as specified and jrecord
1105 * resources will be cleaned up.
1108 jrecord_done(struct jrecord *jrec, int abortit)
1110 KKASSERT(jrec->rawp != NULL);
1113 journal_abort(jrec->jo, &jrec->rawp);
1115 KKASSERT(jrec->pushcount == 0 && jrec->residual == 0);
1116 journal_commit(jrec->jo, &jrec->rawp,
1117 jrec->stream_reserved - jrec->stream_residual, 1);
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.
1124 * Note that jrec->rawp is NULLd out by journal_abort/journal_commit.
1127 jrec->stream_ptr = NULL;
1130 /************************************************************************
1131 * LOW LEVEL RECORD SUPPORT ROUTINES *
1132 ************************************************************************
1134 * These routine create low level recursive and leaf subrecords representing
1135 * common filesystem structures.
1139 * Write out a filename path relative to the base of the mount point.
1140 * rectype is typically JLEAF_PATH{1,2,3,4}.
1143 jrecord_write_path(struct jrecord *jrec, int16_t rectype, struct namecache *ncp)
1145 char buf[64]; /* local buffer if it fits, else malloced */
1149 struct namecache *scan;
1152 * Pass 1 - figure out the number of bytes required. Include terminating
1153 * \0 on last element and '/' separator on other elements.
1155 * The namecache topology terminates at the root of the filesystem
1156 * (the normal lookup code would then continue by using the mount
1157 * structure to figure out what it was mounted on).
1161 for (scan = ncp; scan; scan = scan->nc_parent) {
1162 pathlen += scan->nc_nlen + 1;
1165 if (pathlen <= sizeof(buf))
1168 base = kmalloc(pathlen, M_TEMP, M_INTWAIT);
1171 * Pass 2 - generate the path buffer
1174 for (scan = ncp; scan; scan = scan->nc_parent) {
1175 if (scan->nc_nlen >= index) {
1177 kfree(base, M_TEMP);
1180 if (index == pathlen)
1183 base[--index] = '/';
1184 index -= scan->nc_nlen;
1185 bcopy(scan->nc_name, base + index, scan->nc_nlen);
1187 jrecord_leaf(jrec, rectype, base + index, pathlen - index);
1189 kfree(base, M_TEMP);
1193 * Write out a file attribute structure. While somewhat inefficient, using
1194 * a recursive data structure is the most portable and extensible way.
1197 jrecord_write_vattr(struct jrecord *jrec, struct vattr *vat)
1201 save = jrecord_push(jrec, JTYPE_VATTR);
1202 if (vat->va_type != VNON)
1203 jrecord_leaf(jrec, JLEAF_VTYPE, &vat->va_type, sizeof(vat->va_type));
1204 if (vat->va_mode != (mode_t)VNOVAL)
1205 jrecord_leaf(jrec, JLEAF_MODES, &vat->va_mode, sizeof(vat->va_mode));
1206 if (vat->va_nlink != VNOVAL)
1207 jrecord_leaf(jrec, JLEAF_NLINK, &vat->va_nlink, sizeof(vat->va_nlink));
1208 if (vat->va_uid != VNOVAL)
1209 jrecord_leaf(jrec, JLEAF_UID, &vat->va_uid, sizeof(vat->va_uid));
1210 if (vat->va_gid != VNOVAL)
1211 jrecord_leaf(jrec, JLEAF_GID, &vat->va_gid, sizeof(vat->va_gid));
1212 if (vat->va_fsid != VNOVAL)
1213 jrecord_leaf(jrec, JLEAF_FSID, &vat->va_fsid, sizeof(vat->va_fsid));
1214 if (vat->va_fileid != VNOVAL)
1215 jrecord_leaf(jrec, JLEAF_INUM, &vat->va_fileid, sizeof(vat->va_fileid));
1216 if (vat->va_size != VNOVAL)
1217 jrecord_leaf(jrec, JLEAF_SIZE, &vat->va_size, sizeof(vat->va_size));
1218 if (vat->va_atime.tv_sec != VNOVAL)
1219 jrecord_leaf(jrec, JLEAF_ATIME, &vat->va_atime, sizeof(vat->va_atime));
1220 if (vat->va_mtime.tv_sec != VNOVAL)
1221 jrecord_leaf(jrec, JLEAF_MTIME, &vat->va_mtime, sizeof(vat->va_mtime));
1222 if (vat->va_ctime.tv_sec != VNOVAL)
1223 jrecord_leaf(jrec, JLEAF_CTIME, &vat->va_ctime, sizeof(vat->va_ctime));
1224 if (vat->va_gen != VNOVAL)
1225 jrecord_leaf(jrec, JLEAF_GEN, &vat->va_gen, sizeof(vat->va_gen));
1226 if (vat->va_flags != VNOVAL)
1227 jrecord_leaf(jrec, JLEAF_FLAGS, &vat->va_flags, sizeof(vat->va_flags));
1228 if (vat->va_rdev != VNOVAL)
1229 jrecord_leaf(jrec, JLEAF_UDEV, &vat->va_rdev, sizeof(vat->va_rdev));
1231 if (vat->va_filerev != VNOVAL)
1232 jrecord_leaf(jrec, JLEAF_FILEREV, &vat->va_filerev, sizeof(vat->va_filerev));
1234 jrecord_pop(jrec, save);
1238 * Write out the creds used to issue a file operation. If a process is
1239 * available write out additional tracking information related to the
1242 * XXX additional tracking info
1246 jrecord_write_cred(struct jrecord *jrec, struct thread *td, struct ucred *cred)
1251 save = jrecord_push(jrec, JTYPE_CRED);
1252 jrecord_leaf(jrec, JLEAF_UID, &cred->cr_uid, sizeof(cred->cr_uid));
1253 jrecord_leaf(jrec, JLEAF_GID, &cred->cr_gid, sizeof(cred->cr_gid));
1254 if (td && (p = td->td_proc) != NULL) {
1255 jrecord_leaf(jrec, JLEAF_PID, &p->p_pid, sizeof(p->p_pid));
1256 jrecord_leaf(jrec, JLEAF_COMM, p->p_comm, sizeof(p->p_comm));
1258 jrecord_pop(jrec, save);
1262 * Write out information required to identify a vnode
1264 * XXX this needs work. We should write out the inode number as well,
1265 * and in fact avoid writing out the file path for seqential writes
1266 * occuring within e.g. a certain period of time.
1269 jrecord_write_vnode_ref(struct jrecord *jrec, struct vnode *vp)
1271 struct namecache *ncp;
1273 TAILQ_FOREACH(ncp, &vp->v_namecache, nc_vnode) {
1274 if ((ncp->nc_flag & (NCF_UNRESOLVED|NCF_DESTROYED)) == 0)
1278 jrecord_write_path(jrec, JLEAF_PATH_REF, ncp);
1282 jrecord_write_vnode_link(struct jrecord *jrec, struct vnode *vp,
1283 struct namecache *notncp)
1285 struct namecache *ncp;
1287 TAILQ_FOREACH(ncp, &vp->v_namecache, nc_vnode) {
1290 if ((ncp->nc_flag & (NCF_UNRESOLVED|NCF_DESTROYED)) == 0)
1294 jrecord_write_path(jrec, JLEAF_PATH_REF, ncp);
1298 * Write out the data represented by a pagelist
1301 jrecord_write_pagelist(struct jrecord *jrec, int16_t rectype,
1302 struct vm_page **pglist, int *rtvals, int pgcount,
1305 struct msf_buf *msf;
1311 while (i < pgcount) {
1313 * Find the next valid section. Skip any invalid elements
1315 if (rtvals[i] != VM_PAGER_OK) {
1317 offset += PAGE_SIZE;
1322 * Figure out how big the valid section is, capping I/O at what the
1323 * MSFBUF can represent.
1326 while (i < pgcount && i - b != XIO_INTERNAL_PAGES &&
1327 rtvals[i] == VM_PAGER_OK
1336 error = msf_map_pagelist(&msf, pglist + b, i - b, 0);
1338 kprintf("RECORD PUTPAGES %d\n", msf_buf_bytes(msf));
1339 jrecord_leaf(jrec, JLEAF_SEEKPOS, &offset, sizeof(offset));
1340 jrecord_leaf(jrec, rectype,
1341 msf_buf_kva(msf), msf_buf_bytes(msf));
1344 kprintf("jrecord_write_pagelist: mapping failure\n");
1346 offset += (off_t)(i - b) << PAGE_SHIFT;
1352 * Write out the data represented by a UIO.
1355 struct jrecord *jrec;
1359 static int jrecord_write_uio_callback(void *info, char *buf, int bytes);
1362 jrecord_write_uio(struct jrecord *jrec, int16_t rectype, struct uio *uio)
1364 struct jwuio_info info = { jrec, rectype };
1367 if (uio->uio_segflg != UIO_NOCOPY) {
1368 jrecord_leaf(jrec, JLEAF_SEEKPOS, &uio->uio_offset,
1369 sizeof(uio->uio_offset));
1370 error = msf_uio_iterate(uio, jrecord_write_uio_callback, &info);
1372 kprintf("XXX warning uio iterate failed %d\n", error);
1377 jrecord_write_uio_callback(void *info_arg, char *buf, int bytes)
1379 struct jwuio_info *info = info_arg;
1381 jrecord_leaf(info->jrec, info->rectype, buf, bytes);
1386 jrecord_file_data(struct jrecord *jrec, struct vnode *vp,
1387 off_t off, off_t bytes)
1389 const int bufsize = 8192;
1394 buf = kmalloc(bufsize, M_JOURNAL, M_WAITOK);
1395 jrecord_leaf(jrec, JLEAF_SEEKPOS, &off, sizeof(off));
1397 n = (bytes > bufsize) ? bufsize : (int)bytes;
1398 error = vn_rdwr(UIO_READ, vp, buf, n, off, UIO_SYSSPACE, IO_NODELOCKED,
1399 proc0.p_ucred, NULL);
1401 jrecord_leaf(jrec, JLEAF_ERROR, &error, sizeof(error));
1404 jrecord_leaf(jrec, JLEAF_FILEDATA, buf, n);
1408 kfree(buf, M_JOURNAL);