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