2 * Copyright (c) 2004 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_jops.c,v 1.4 2004/12/30 21:41:04 dillon Exp $
37 * Each mount point may have zero or more independantly configured journals
38 * attached to it. Each journal is represented by a memory FIFO and worker
39 * thread. Journal events are streamed through the FIFO to the thread,
40 * batched up (typically on one-second intervals), and written out by the
43 * Journal vnode ops are executed instead of mnt_vn_norm_ops when one or
44 * more journals have been installed on a mount point. It becomes the
45 * responsibility of the journal op to call the underlying normal op as
48 * The journaling protocol is intended to evolve into a two-way stream
49 * whereby transaction IDs can be acknowledged by the journaling target
50 * when the data has been committed to hard storage. Both implicit and
51 * explicit acknowledgement schemes will be supported, depending on the
52 * sophistication of the journaling stream, plus resynchronization and
53 * restart when a journaling stream is interrupted. This information will
54 * also be made available to journaling-aware filesystems to allow better
55 * management of their own physical storage synchronization mechanisms as
56 * well as to allow such filesystems to take direct advantage of the kernel's
57 * journaling layer so they don't have to roll their own.
59 * In addition, the worker thread will have access to much larger
60 * spooling areas then the memory buffer is able to provide by e.g.
61 * reserving swap space, in order to absorb potentially long interruptions
62 * of off-site journaling streams, and to prevent 'slow' off-site linkages
63 * from radically slowing down local filesystem operations.
65 * Because of the non-trivial algorithms the journaling system will be
66 * required to support, use of a worker thread is mandatory. Efficiencies
67 * are maintained by utilitizing the memory FIFO to batch transactions when
68 * possible, reducing the number of gratuitous thread switches and taking
69 * advantage of cpu caches through the use of shorter batched code paths
70 * rather then trying to do everything in the context of the process
71 * originating the filesystem op. In the future the memory FIFO can be
72 * made per-cpu to remove BGL or other locking requirements.
74 #include <sys/param.h>
75 #include <sys/systm.h>
78 #include <sys/kernel.h>
79 #include <sys/queue.h>
81 #include <sys/malloc.h>
82 #include <sys/mount.h>
83 #include <sys/unistd.h>
84 #include <sys/vnode.h>
86 #include <sys/mountctl.h>
89 #include <machine/limits.h>
92 #include <vm/vm_object.h>
93 #include <vm/vm_page.h>
94 #include <vm/vm_pager.h>
95 #include <vm/vnode_pager.h>
97 #include <sys/file2.h>
98 #include <sys/thread2.h>
100 static int journal_attach(struct mount *mp);
101 static void journal_detach(struct mount *mp);
102 static int journal_install_vfs_journal(struct mount *mp, struct file *fp,
103 const struct mountctl_install_journal *info);
104 static int journal_remove_vfs_journal(struct mount *mp,
105 const struct mountctl_remove_journal *info);
106 static int journal_resync_vfs_journal(struct mount *mp, const void *ctl);
107 static void journal_thread(void *info);
109 static void *journal_reserve(struct journal *jo,
110 struct journal_rawrecbeg **rawpp,
111 int16_t streamid, int bytes);
112 static void *journal_extend(struct journal *jo,
113 struct journal_rawrecbeg **rawpp,
114 int truncbytes, int bytes, int *newstreamrecp);
115 static void journal_abort(struct journal *jo,
116 struct journal_rawrecbeg **rawpp);
117 static void journal_commit(struct journal *jo,
118 struct journal_rawrecbeg **rawpp,
119 int bytes, int closeout);
121 static void jrecord_init(struct journal *jo,
122 struct jrecord *jrec, int16_t streamid);
123 static struct journal_subrecord *jrecord_push(
124 struct jrecord *jrec, int16_t rectype);
125 static void jrecord_pop(struct jrecord *jrec, struct journal_subrecord *parent);
126 static struct journal_subrecord *jrecord_write(struct jrecord *jrec,
127 int16_t rectype, int bytes);
128 static void jrecord_data(struct jrecord *jrec, const void *buf, int bytes);
129 static void jrecord_done(struct jrecord *jrec, int abortit);
131 static void jrecord_write_path(struct jrecord *jrec,
132 int16_t rectype, struct namecache *ncp);
133 static void jrecord_write_vattr(struct jrecord *jrec, struct vattr *vat);
136 static int journal_nmkdir(struct vop_nmkdir_args *ap);
138 static struct vnodeopv_entry_desc journal_vnodeop_entries[] = {
139 { &vop_default_desc, vop_journal_operate_ap },
140 { &vop_mountctl_desc, (void *)journal_mountctl },
141 { &vop_nmkdir_desc, (void *)journal_nmkdir },
145 static MALLOC_DEFINE(M_JOURNAL, "journal", "Journaling structures");
146 static MALLOC_DEFINE(M_JFIFO, "journal-fifo", "Journal FIFO");
149 journal_mountctl(struct vop_mountctl_args *ap)
154 mp = ap->a_head.a_ops->vv_mount;
157 if (mp->mnt_vn_journal_ops == NULL) {
159 case MOUNTCTL_INSTALL_VFS_JOURNAL:
160 error = journal_attach(mp);
161 if (error == 0 && ap->a_ctllen != sizeof(struct mountctl_install_journal))
163 if (error == 0 && ap->a_fp == NULL)
166 error = journal_install_vfs_journal(mp, ap->a_fp, ap->a_ctl);
167 if (TAILQ_EMPTY(&mp->mnt_jlist))
170 case MOUNTCTL_REMOVE_VFS_JOURNAL:
171 case MOUNTCTL_RESYNC_VFS_JOURNAL:
180 case MOUNTCTL_INSTALL_VFS_JOURNAL:
181 if (ap->a_ctllen != sizeof(struct mountctl_install_journal))
183 if (error == 0 && ap->a_fp == NULL)
186 error = journal_install_vfs_journal(mp, ap->a_fp, ap->a_ctl);
188 case MOUNTCTL_REMOVE_VFS_JOURNAL:
189 if (ap->a_ctllen != sizeof(struct mountctl_remove_journal))
192 error = journal_remove_vfs_journal(mp, ap->a_ctl);
193 if (TAILQ_EMPTY(&mp->mnt_jlist))
196 case MOUNTCTL_RESYNC_VFS_JOURNAL:
197 if (ap->a_ctllen != 0)
199 error = journal_resync_vfs_journal(mp, ap->a_ctl);
210 * High level mount point setup. When a
213 journal_attach(struct mount *mp)
215 vfs_add_vnodeops(mp, &mp->mnt_vn_journal_ops, journal_vnodeop_entries);
220 journal_detach(struct mount *mp)
222 if (mp->mnt_vn_journal_ops)
223 vfs_rm_vnodeops(&mp->mnt_vn_journal_ops);
227 * Install a journal on a mount point. Each journal has an associated worker
228 * thread which is responsible for buffering and spooling the data to the
229 * target. A mount point may have multiple journals attached to it. An
230 * initial start record is generated when the journal is associated.
233 journal_install_vfs_journal(struct mount *mp, struct file *fp,
234 const struct mountctl_install_journal *info)
241 jo = malloc(sizeof(struct journal), M_JOURNAL, M_WAITOK|M_ZERO);
242 bcopy(info->id, jo->id, sizeof(jo->id));
243 jo->flags = info->flags & ~(MC_JOURNAL_ACTIVE | MC_JOURNAL_STOP_REQ);
246 * Memory FIFO size, round to nearest power of 2
248 if (info->membufsize) {
249 if (info->membufsize < 65536)
251 else if (info->membufsize > 128 * 1024 * 1024)
252 size = 128 * 1024 * 1024;
254 size = (int)info->membufsize;
259 while (jo->fifo.size < size)
263 * Other parameters. If not specified the starting transaction id
264 * will be the current date.
267 jo->transid = info->transid;
271 jo->transid = ((int64_t)ts.tv_sec << 30) | ts.tv_nsec;
277 * Allocate the memory FIFO
279 jo->fifo.mask = jo->fifo.size - 1;
280 jo->fifo.membase = malloc(jo->fifo.size, M_JFIFO, M_WAITOK|M_ZERO|M_NULLOK);
281 if (jo->fifo.membase == NULL)
285 * Create the worker thread and generate the association record.
291 jo->flags |= MC_JOURNAL_ACTIVE;
292 lwkt_create(journal_thread, jo, NULL, &jo->thread,
293 TDF_STOPREQ, -1, "journal %.*s", JIDMAX, jo->id);
294 lwkt_setpri(&jo->thread, TDPRI_KERN_DAEMON);
295 lwkt_schedule(&jo->thread);
297 jrecord_init(jo, &jrec, JREC_STREAMID_DISCONT);
298 jrecord_write(&jrec, JTYPE_ASSOCIATE, 0);
299 jrecord_done(&jrec, 0);
300 TAILQ_INSERT_TAIL(&mp->mnt_jlist, jo, jentry);
306 * Disassociate a journal from a mount point and terminate its worker thread.
307 * A final termination record is written out before the file pointer is
311 journal_remove_vfs_journal(struct mount *mp,
312 const struct mountctl_remove_journal *info)
318 TAILQ_FOREACH(jo, &mp->mnt_jlist, jentry) {
319 if (bcmp(jo->id, info->id, sizeof(jo->id)) == 0)
324 TAILQ_REMOVE(&mp->mnt_jlist, jo, jentry);
326 jrecord_init(jo, &jrec, JREC_STREAMID_DISCONT);
327 jrecord_write(&jrec, JTYPE_DISASSOCIATE, 0);
328 jrecord_done(&jrec, 0);
330 jo->flags |= MC_JOURNAL_STOP_REQ | (info->flags & MC_JOURNAL_STOP_IMM);
332 while (jo->flags & MC_JOURNAL_ACTIVE) {
333 tsleep(jo, 0, "jwait", 0);
335 lwkt_free_thread(&jo->thread); /* XXX SMP */
337 fdrop(jo->fp, curthread);
338 if (jo->fifo.membase)
339 free(jo->fifo.membase, M_JFIFO);
348 journal_resync_vfs_journal(struct mount *mp, const void *ctl)
354 * The per-journal worker thread is responsible for writing out the
355 * journal's FIFO to the target stream.
358 journal_thread(void *info)
360 struct journal *jo = info;
361 struct journal_rawrecbeg *rawp;
369 * Calculate the number of bytes available to write. This buffer
370 * area may contain reserved records so we can't just write it out
371 * without further checks.
373 bytes = jo->fifo.windex - jo->fifo.rindex;
376 * sleep if no bytes are available or if an incomplete record is
377 * encountered (it needs to be filled in before we can write it
378 * out), and skip any pad records that we encounter.
381 if (jo->flags & MC_JOURNAL_STOP_REQ)
383 tsleep(&jo->fifo, 0, "jfifo", hz);
386 rawp = (void *)(jo->fifo.membase + (jo->fifo.rindex & jo->fifo.mask));
387 if (rawp->begmagic == JREC_INCOMPLETEMAGIC) {
388 tsleep(&jo->fifo, 0, "jpad", hz);
391 if (rawp->streamid == JREC_STREAMID_PAD) {
392 jo->fifo.rindex += (rawp->recsize + 15) & ~15;
393 KKASSERT(jo->fifo.windex - jo->fifo.rindex > 0);
398 * Figure out how much we can write out, beware the buffer wrap
402 avail = jo->fifo.size - (jo->fifo.rindex & jo->fifo.mask);
403 while (res < bytes && rawp->begmagic == JREC_BEGMAGIC) {
404 res += (rawp->recsize + 15) & ~15;
406 KKASSERT(res == avail);
412 * Issue the write and deal with any errors or other conditions.
413 * For now assume blocking I/O. Since we are record-aware the
414 * code cannot yet handle partial writes.
416 * XXX EWOULDBLOCK/NBIO
417 * XXX notification on failure
418 * XXX two-way acknowledgement stream in the return direction / xindex
421 error = fp_write(jo->fp,
422 jo->fifo.membase + (jo->fifo.rindex & jo->fifo.mask),
425 printf("journal_thread(%s) write, error %d\n", jo->id, error);
428 KKASSERT(res == bytes);
429 printf("journal_thread(%s) write %d\n", jo->id, res);
433 * Advance rindex. XXX for now also advance xindex, which will
434 * eventually be advanced when the target acknowledges the sequence
437 jo->fifo.rindex += bytes;
438 jo->fifo.xindex += bytes;
439 if (jo->flags & MC_JOURNAL_WWAIT) {
440 jo->flags &= ~MC_JOURNAL_WWAIT; /* XXX hysteresis */
441 wakeup(&jo->fifo.windex);
444 jo->flags &= ~MC_JOURNAL_ACTIVE;
446 wakeup(&jo->fifo.windex);
451 journal_build_pad(struct journal_rawrecbeg *rawp, int recsize)
453 struct journal_rawrecend *rendp;
455 KKASSERT((recsize & 15) == 0 && recsize >= 16);
457 rawp->begmagic = JREC_BEGMAGIC;
458 rawp->streamid = JREC_STREAMID_PAD;
459 rawp->recsize = recsize; /* must be 16-byte aligned */
462 * WARNING, rendp may overlap rawp->seqno. This is necessary to
463 * allow PAD records to fit in 16 bytes. Use cpu_mb1() to
464 * hopefully cause the compiler to not make any assumptions.
467 rendp = (void *)((char *)rawp + rawp->recsize - sizeof(*rendp));
468 rendp->endmagic = JREC_ENDMAGIC;
470 rendp->recsize = rawp->recsize;
474 * Wake up the worker thread if the FIFO is more then half full or if
475 * someone is waiting for space to be freed up. Otherwise let the
476 * heartbeat deal with it. Being able to avoid waking up the worker
477 * is the key to the journal's cpu efficiency.
481 journal_commit_wakeup(struct journal *jo)
485 avail = jo->fifo.size - (jo->fifo.windex - jo->fifo.xindex);
486 KKASSERT(avail >= 0);
487 if ((avail < (jo->fifo.size >> 1)) || (jo->flags & MC_JOURNAL_WWAIT))
492 * Create a new BEGIN stream record with the specified streamid and the
493 * specified amount of payload space. *rawpp will be set to point to the
494 * base of the new stream record and a pointer to the base of the payload
495 * space will be returned. *rawpp does not need to be pre-NULLd prior to
498 * A stream can be extended, aborted, or committed by other API calls
499 * below. This may result in a sequence of potentially disconnected
500 * stream records to be output to the journaling target. The first record
501 * (the one created by this function) will be marked JREC_STREAMCTL_BEGIN,
502 * while the last record on commit or abort will be marked JREC_STREAMCTL_END
503 * (and possibly also JREC_STREAMCTL_ABORTED). The last record could wind
504 * up being the same as the first, in which case the bits are all set in
507 * The stream record is created in an incomplete state by setting the begin
508 * magic to JREC_INCOMPLETEMAGIC. This prevents the worker thread from
509 * flushing the fifo past our record until we have finished populating it.
510 * Other threads can reserve and operate on their own space without stalling
511 * but the stream output will stall until we have completed operations. The
512 * memory FIFO is intended to be large enough to absorb such situations
513 * without stalling out other threads.
517 journal_reserve(struct journal *jo, struct journal_rawrecbeg **rawpp,
518 int16_t streamid, int bytes)
520 struct journal_rawrecbeg *rawp;
526 * Add header and trailer overheads to the passed payload. Note that
527 * the passed payload size need not be aligned in any way.
529 bytes += sizeof(struct journal_rawrecbeg);
530 bytes += sizeof(struct journal_rawrecend);
534 * First, check boundary conditions. If the request would wrap around
535 * we have to skip past the ending block and return to the beginning
536 * of the FIFO's buffer. Calculate 'req' which is the actual number
537 * of bytes being reserved, including wrap-around dead space.
539 * Note that availtoend is not truncated to avail and so cannot be
540 * used to determine whether the reservation is possible by itself.
541 * Also, since all fifo ops are 16-byte aligned, we can check
542 * the size before calculating the aligned size.
544 availtoend = jo->fifo.size - (jo->fifo.windex & jo->fifo.mask);
545 if (bytes > availtoend)
546 req = bytes + availtoend; /* add pad to end */
551 * Next calculate the total available space and see if it is
552 * sufficient. We cannot overwrite previously buffered data
553 * past xindex because otherwise we would not be able to restart
554 * a broken link at the target's last point of commit.
556 avail = jo->fifo.size - (jo->fifo.windex - jo->fifo.xindex);
557 KKASSERT(avail >= 0 && (avail & 15) == 0);
560 /* XXX MC_JOURNAL_STOP_IMM */
561 jo->flags |= MC_JOURNAL_WWAIT;
562 tsleep(&jo->fifo.windex, 0, "jwrite", 0);
567 * Create a pad record for any dead space and create an incomplete
568 * record for the live space, then return a pointer to the
569 * contiguous buffer space that was requested.
571 * NOTE: The worker thread will not flush past an incomplete
572 * record, so the reserved space can be filled in at-will. The
573 * journaling code must also be aware the reserved sections occuring
574 * after this one will also not be written out even if completed
575 * until this one is completed.
577 rawp = (void *)(jo->fifo.membase + (jo->fifo.windex & jo->fifo.mask));
579 journal_build_pad(rawp, req - bytes);
580 rawp = (void *)jo->fifo.membase;
582 rawp->begmagic = JREC_INCOMPLETEMAGIC; /* updated by abort/commit */
583 rawp->recsize = bytes; /* (unaligned size) */
584 rawp->streamid = streamid | JREC_STREAMCTL_BEGIN;
585 rawp->seqno = 0; /* set by caller */
588 * Issue a memory barrier to guarentee that the record data has been
589 * properly initialized before we advance the write index and return
590 * a pointer to the reserved record. Otherwise the worker thread
591 * could accidently run past us.
593 * Note that stream records are always 16-byte aligned.
596 jo->fifo.windex += (req + 15) & ~15;
606 * Extend a previous reservation by the specified number of payload bytes.
607 * If it is not possible to extend the existing reservation due to either
608 * another thread having reserved space after us or due to a boundary
609 * condition, the current reservation will be committed and possibly
610 * truncated and a new reservation with the specified payload size will
611 * be created. *rawpp is set to the new reservation in this case but the
612 * caller cannot depend on a comparison with the old rawp to determine if
613 * this case occurs because we could end up using the same memory FIFO
614 * offset for the new stream record.
616 * In either case this function will return a pointer to the base of the
617 * extended payload space.
619 * If a new stream block is created the caller needs to recalculate payload
620 * byte counts, if the same stream block is used the caller needs to extend
621 * its current notion of the payload byte count.
624 journal_extend(struct journal *jo, struct journal_rawrecbeg **rawpp,
625 int truncbytes, int bytes, int *newstreamrecp)
627 struct journal_rawrecbeg *rawp;
638 osize = (rawp->recsize + 15) & ~15;
639 nsize = (rawp->recsize + bytes + 15) & ~15;
640 wbase = (char *)rawp - jo->fifo.membase;
643 * If the aligned record size does not change we can trivially extend
646 if (nsize == osize) {
647 rawp->recsize += bytes;
648 return((char *)rawp + rawp->recsize - bytes);
652 * If the fifo's write index hasn't been modified since we made the
653 * reservation and we do not hit any boundary conditions, we can
654 * trivially extend the record.
656 if ((jo->fifo.windex & jo->fifo.mask) == wbase + osize) {
657 availtoend = jo->fifo.size - wbase;
658 avail = jo->fifo.size - (jo->fifo.windex - jo->fifo.xindex) + osize;
659 KKASSERT((availtoend & 15) == 0);
660 KKASSERT((avail & 15) == 0);
661 if (nsize <= avail && nsize <= availtoend) {
662 jo->fifo.windex += nsize - osize;
663 rawp->recsize += bytes;
664 return((char *)rawp + rawp->recsize - bytes);
669 * It was not possible to extend the buffer. Commit the current
670 * buffer and create a new one. We manually clear the BEGIN mark that
671 * journal_reserve() creates (because this is a continuing record, not
672 * the start of a new stream).
674 streamid = rawp->streamid & JREC_STREAMID_MASK;
675 journal_commit(jo, rawpp, truncbytes, 0);
676 rptr = journal_reserve(jo, rawpp, streamid, bytes);
678 rawp->streamid &= ~JREC_STREAMCTL_BEGIN;
684 * Abort a journal record. If the transaction record represents a stream
685 * BEGIN and we can reverse the fifo's write index we can simply reverse
686 * index the entire record, as if it were never reserved in the first place.
688 * Otherwise we set the JREC_STREAMCTL_ABORTED bit and commit the record
689 * with the payload truncated to 0 bytes.
692 journal_abort(struct journal *jo, struct journal_rawrecbeg **rawpp)
694 struct journal_rawrecbeg *rawp;
698 osize = (rawp->recsize + 15) & ~15;
700 if ((rawp->streamid & JREC_STREAMCTL_BEGIN) &&
701 (jo->fifo.windex & jo->fifo.mask) ==
702 (char *)rawp - jo->fifo.membase + osize)
704 jo->fifo.windex -= osize;
707 rawp->streamid |= JREC_STREAMCTL_ABORTED;
708 journal_commit(jo, rawpp, 0, 1);
713 * Commit a journal record and potentially truncate it to the specified
714 * number of payload bytes. If you do not want to truncate the record,
715 * simply pass -1 for the bytes parameter. Do not pass rawp->recsize, that
716 * field includes header and trailer and will not be correct. Note that
717 * passing 0 will truncate the entire data payload of the record.
719 * The logical stream is terminated by this function.
721 * If truncation occurs, and it is not possible to physically optimize the
722 * memory FIFO due to other threads having reserved space after ours,
723 * the remaining reserved space will be covered by a pad record.
726 journal_commit(struct journal *jo, struct journal_rawrecbeg **rawpp,
727 int bytes, int closeout)
729 struct journal_rawrecbeg *rawp;
730 struct journal_rawrecend *rendp;
737 KKASSERT((char *)rawp >= jo->fifo.membase &&
738 (char *)rawp + rawp->recsize <= jo->fifo.membase + jo->fifo.size);
739 KKASSERT(((intptr_t)rawp & 15) == 0);
742 * Truncate the record if requested. If the FIFO write index as still
743 * at the end of our record we can optimally backindex it. Otherwise
744 * we have to insert a pad record.
746 * We calculate osize which is the 16-byte-aligned original recsize.
747 * We calculate nsize which is the 16-byte-aligned new recsize.
749 * Due to alignment issues or in case the passed truncation bytes is
750 * the same as the original payload, windex will be equal to nindex.
753 KKASSERT(bytes >= 0 && bytes <= rawp->recsize - sizeof(struct journal_rawrecbeg) - sizeof(struct journal_rawrecend));
754 osize = (rawp->recsize + 15) & ~15;
755 rawp->recsize = bytes + sizeof(struct journal_rawrecbeg) +
756 sizeof(struct journal_rawrecend);
757 nsize = (rawp->recsize + 15) & ~15;
758 if (osize == nsize) {
760 } else if ((jo->fifo.windex & jo->fifo.mask) == (char *)rawp - jo->fifo.membase + osize) {
761 /* we are able to backindex the fifo */
762 jo->fifo.windex -= osize - nsize;
764 /* we cannot backindex the fifo, emplace a pad in the dead space */
765 journal_build_pad((void *)((char *)rawp + osize), osize - nsize);
770 * Fill in the trailer. Note that unlike pad records, the trailer will
771 * never overlap the header.
773 rendp = (void *)((char *)rawp +
774 ((rawp->recsize + 15) & ~15) - sizeof(*rendp));
775 rendp->endmagic = JREC_ENDMAGIC;
776 rendp->recsize = rawp->recsize;
777 rendp->check = 0; /* XXX check word, disabled for now */
780 * Fill in begmagic last. This will allow the worker thread to proceed.
781 * Use a memory barrier to guarentee write ordering. Mark the stream
782 * as terminated if closeout is set. This is the typical case.
785 rawp->streamid |= JREC_STREAMCTL_END;
786 cpu_mb1(); /* memory barrier */
787 rawp->begmagic = JREC_BEGMAGIC;
789 journal_commit_wakeup(jo);
792 /************************************************************************
793 * TRANSACTION SUPPORT ROUTINES *
794 ************************************************************************
796 * JRECORD_*() - routines to create subrecord transactions and embed them
797 * in the logical streams managed by the journal_*() routines.
800 static int16_t sid = JREC_STREAMID_JMIN;
803 * Initialize the passed jrecord structure and start a new stream transaction
804 * by reserving an initial build space in the journal's memory FIFO.
807 jrecord_init(struct journal *jo, struct jrecord *jrec, int16_t streamid)
809 bzero(jrec, sizeof(*jrec));
812 streamid = sid++; /* XXX need to track stream ids! */
813 if (sid == JREC_STREAMID_JMAX)
814 sid = JREC_STREAMID_JMIN;
816 jrec->streamid = streamid;
817 jrec->stream_residual = JREC_DEFAULTSIZE;
818 jrec->stream_reserved = jrec->stream_residual;
820 journal_reserve(jo, &jrec->rawp, streamid, jrec->stream_reserved);
824 * Push a recursive record type. All pushes should have matching pops.
825 * The old parent is returned and the newly pushed record becomes the
826 * new parent. Note that the old parent's pointer may already be invalid
827 * or may become invalid if jrecord_write() had to build a new stream
828 * record, so the caller should not mess with the returned pointer in
829 * any way other then to save it.
832 struct journal_subrecord *
833 jrecord_push(struct jrecord *jrec, int16_t rectype)
835 struct journal_subrecord *save;
838 jrec->parent = jrecord_write(jrec, rectype|JMASK_NESTED, 0);
840 KKASSERT(jrec->parent != NULL);
842 ++jrec->pushptrgood; /* cleared on flush */
847 * Pop a previously pushed sub-transaction. We must set JMASK_LAST
848 * on the last record written within the subtransaction. If the last
849 * record written is not accessible or if the subtransaction is empty,
850 * we must write out a pad record with JMASK_LAST set before popping.
852 * When popping a subtransaction the parent record's recsize field
853 * will be properly set. If the parent pointer is no longer valid
854 * (which can occur if the data has already been flushed out to the
855 * stream), the protocol spec allows us to leave it 0.
857 * The saved parent pointer which we restore may or may not be valid,
858 * and if not valid may or may not be NULL, depending on the value
862 jrecord_pop(struct jrecord *jrec, struct journal_subrecord *save)
864 struct journal_subrecord *last;
866 KKASSERT(jrec->pushcount > 0);
867 KKASSERT(jrec->residual == 0);
870 * Set JMASK_LAST on the last record we wrote at the current
871 * level. If last is NULL we either no longer have access to the
872 * record or the subtransaction was empty and we must write out a pad
875 if ((last = jrec->last) == NULL) {
876 jrecord_write(jrec, JLEAF_PAD|JMASK_LAST, 0);
877 last = jrec->last; /* reload after possible flush */
879 last->rectype |= JMASK_LAST;
883 * pushptrgood tells us how many levels of parent record pointers
884 * are valid. The jrec only stores the current parent record pointer
885 * (and it is only valid if pushptrgood != 0). The higher level parent
886 * record pointers are saved by the routines calling jrecord_push() and
887 * jrecord_pop(). These pointers may become stale and we determine
888 * that fact by tracking the count of valid parent pointers with
889 * pushptrgood. Pointers become invalid when their related stream
890 * record gets pushed out.
900 * NOTE B: This pop sets LAST in node Z if the node is still accessible,
901 * else a PAD record is appended and LAST is set in that.
903 * This pop sets the record size in parentB if parentB is still
904 * accessible, else the record size is left 0 (the scanner must
907 * This pop sets the new 'last' record to parentB, the pointer
908 * to which may or may not still be accessible.
910 * NOTE A: This pop sets LAST in parentB if the node is still accessible,
911 * else a PAD record is appended and LAST is set in that.
913 * This pop sets the record size in parentA if parentA is still
914 * accessible, else the record size is left 0 (the scanner must
917 * This pop sets the new 'last' record to parentA, the pointer
918 * to which may or may not still be accessible.
920 * Also note that the last record in the stream transaction, which in
921 * the above example is parentA, does not currently have the LAST bit
924 * The current parent becomes the last record relative to the
925 * saved parent passed into us. It's validity is based on
926 * whether pushptrgood is non-zero prior to decrementing. The saved
927 * parent becomes the new parent, and its validity is based on whether
928 * pushptrgood is non-zero after decrementing.
930 * The old jrec->parent may be NULL if it is no longer accessible.
931 * If pushptrgood is non-zero, however, it is guarenteed to not
932 * be NULL (since no flush occured).
934 jrec->last = jrec->parent;
936 if (jrec->pushptrgood) {
937 KKASSERT(jrec->last != NULL && last != NULL);
938 if (--jrec->pushptrgood == 0) {
939 jrec->parent = NULL; /* 'save' contains garbage or NULL */
941 KKASSERT(save != NULL);
942 jrec->parent = save; /* 'save' must not be NULL */
946 * Set the record size in the old parent. 'last' still points to
947 * the original last record in the subtransaction being popped,
948 * jrec->last points to the old parent (which became the last
949 * record relative to the new parent being popped into).
951 jrec->last->recsize = (char *)last + last->recsize - (char *)jrec->last;
954 KKASSERT(jrec->last == NULL);
959 * Write a leaf record out and return a pointer to its base. The leaf
960 * record may contain potentially megabytes of data which is supplied
961 * in jrecord_data() calls. The exact amount must be specified in this
965 struct journal_subrecord *
966 jrecord_write(struct jrecord *jrec, int16_t rectype, int bytes)
968 struct journal_subrecord *last;
972 * Try to catch some obvious errors. Nesting records must specify a
973 * size of 0, and there should be no left-overs from previous operations
974 * (such as incomplete data writeouts).
976 KKASSERT(bytes == 0 || (rectype & JMASK_NESTED) == 0);
977 KKASSERT(jrec->residual == 0);
980 * Check to see if the current stream record has enough room for
981 * the new subrecord header. If it doesn't we extend the current
984 * This may have the side effect of pushing out the current stream record
985 * and creating a new one. We must adjust our stream tracking fields
988 if (jrec->stream_residual < sizeof(struct journal_subrecord)) {
989 jrec->stream_ptr = journal_extend(jrec->jo, &jrec->rawp,
990 jrec->stream_reserved - jrec->stream_residual,
991 JREC_DEFAULTSIZE, &pusheditout);
993 jrec->stream_reserved = JREC_DEFAULTSIZE;
994 jrec->stream_residual = JREC_DEFAULTSIZE;
995 jrec->parent = NULL; /* no longer accessible */
996 jrec->pushptrgood = 0; /* restored parents in pops no good */
998 jrec->stream_reserved += JREC_DEFAULTSIZE;
999 jrec->stream_residual += JREC_DEFAULTSIZE;
1002 last = (void *)jrec->stream_ptr;
1003 last->rectype = rectype;
1005 last->recsize = sizeof(struct journal_subrecord) + bytes;
1007 jrec->residual = bytes; /* remaining data to be posted */
1008 jrec->residual_align = -bytes & 7; /* post-data alignment required */
1013 * Write out the data associated with a leaf record. Any number of calls
1014 * to this routine may be made as long as the byte count adds up to the
1015 * amount originally specified in jrecord_write().
1017 * The act of writing out the leaf data may result in numerous stream records
1018 * being pushed out. Callers should be aware that even the associated
1019 * subrecord header may become inaccessible due to stream record pushouts.
1022 jrecord_data(struct jrecord *jrec, const void *buf, int bytes)
1027 KKASSERT(bytes >= 0 && bytes <= jrec->residual);
1030 * Push out stream records as long as there is insufficient room to hold
1031 * the remaining data.
1033 while (jrec->stream_residual < bytes) {
1035 * Fill in any remaining space in the current stream record.
1037 bcopy(buf, jrec->stream_ptr, jrec->stream_residual);
1038 buf = (const char *)buf + jrec->stream_residual;
1039 bytes -= jrec->stream_residual;
1040 /*jrec->stream_ptr += jrec->stream_residual;*/
1041 jrec->stream_residual = 0;
1042 jrec->residual -= jrec->stream_residual;
1045 * Try to extend the current stream record, but no more then 1/4
1046 * the size of the FIFO.
1048 extsize = jrec->jo->fifo.size >> 2;
1049 if (extsize > bytes)
1050 extsize = (bytes + 15) & ~15;
1052 jrec->stream_ptr = journal_extend(jrec->jo, &jrec->rawp,
1053 jrec->stream_reserved - jrec->stream_residual,
1054 extsize, &pusheditout);
1056 jrec->stream_reserved = extsize;
1057 jrec->stream_residual = extsize;
1058 jrec->parent = NULL; /* no longer accessible */
1059 jrec->last = NULL; /* no longer accessible */
1060 jrec->pushptrgood = 0; /* restored parents in pops no good */
1062 jrec->stream_reserved += extsize;
1063 jrec->stream_residual += extsize;
1068 * Push out any remaining bytes into the current stream record.
1071 bcopy(buf, jrec->stream_ptr, bytes);
1072 jrec->stream_ptr += bytes;
1073 jrec->stream_residual -= bytes;
1074 jrec->residual -= bytes;
1078 * Handle data alignment requirements for the subrecord. Because the
1079 * stream record's data space is more strictly aligned, it must already
1080 * have sufficient space to hold any subrecord alignment slop.
1082 if (jrec->residual == 0 && jrec->residual_align) {
1083 KKASSERT(jrec->residual_align <= jrec->stream_residual);
1084 bzero(jrec->stream_ptr, jrec->residual_align);
1085 jrec->stream_ptr += jrec->residual_align;
1086 jrec->stream_residual -= jrec->residual_align;
1087 jrec->residual_align = 0;
1092 * We are finished with a transaction. If abortit is not set then we must
1093 * be at the top level with no residual subrecord data left to output.
1094 * If abortit is set then we can be in any state.
1096 * The stream record will be committed or aborted as specified and jrecord
1097 * resources will be cleaned up.
1100 jrecord_done(struct jrecord *jrec, int abortit)
1102 KKASSERT(jrec->rawp != NULL);
1105 journal_abort(jrec->jo, &jrec->rawp);
1107 KKASSERT(jrec->pushcount == 0 && jrec->residual == 0);
1108 journal_commit(jrec->jo, &jrec->rawp,
1109 jrec->stream_reserved - jrec->stream_residual, 1);
1113 * jrec should not be used beyond this point without another init,
1114 * but clean up some fields to ensure that we panic if it is.
1116 * Note that jrec->rawp is NULLd out by journal_abort/journal_commit.
1119 jrec->stream_ptr = NULL;
1122 /************************************************************************
1123 * LEAF RECORD SUPPORT ROUTINES *
1124 ************************************************************************
1126 * These routine create leaf subrecords representing common filesystem
1131 jrecord_write_path(struct jrecord *jrec, int16_t rectype, struct namecache *ncp)
1136 jrecord_write_vattr(struct jrecord *jrec, struct vattr *vat)
1140 /************************************************************************
1142 ************************************************************************/
1146 journal_nmkdir(struct vop_nmkdir_args *ap)
1150 struct jrecord jrec;
1151 void *save; /* warning, save pointers do not always remain valid */
1154 error = vop_journal_operate_ap(&ap->a_head);
1155 mp = ap->a_head.a_ops->vv_mount;
1157 TAILQ_FOREACH(jo, &mp->mnt_jlist, jentry) {
1158 jrecord_init(jo, &jrec, -1);
1159 if (jo->flags & MC_JOURNAL_WANT_REVERSABLE) {
1160 save = jrecord_push(&jrec, JTYPE_UNDO);
1161 /* XXX undo operations */
1162 jrecord_pop(&jrec, save);
1165 if (jo->flags & MC_JOURNAL_WANT_AUDIT) {
1166 jrecord_write_audit(&jrec);
1169 save = jrecord_push(&jrec, JTYPE_MKDIR);
1170 jrecord_write_path(&jrec, JLEAF_PATH1, ap->a_ncp);
1171 jrecord_write_vattr(&jrec, ap->a_vap);
1172 jrecord_pop(&jrec, save);
1173 jrecord_done(&jrec, 0);