g_journal.c revision 163912
1/*-
2 * Copyright (c) 2005-2006 Pawel Jakub Dawidek <pjd@FreeBSD.org>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
25 */
26
27#include <sys/cdefs.h>
28__FBSDID("$FreeBSD: head/sys/geom/journal/g_journal.c 163912 2006-11-02 16:24:18Z pjd $");
29
30#include <sys/param.h>
31#include <sys/systm.h>
32#include <sys/kernel.h>
33#include <sys/module.h>
34#include <sys/limits.h>
35#include <sys/lock.h>
36#include <sys/mutex.h>
37#include <sys/bio.h>
38#include <sys/sysctl.h>
39#include <sys/malloc.h>
40#include <sys/mount.h>
41#include <sys/eventhandler.h>
42#include <sys/proc.h>
43#include <sys/kthread.h>
44#include <sys/sched.h>
45#include <sys/taskqueue.h>
46#include <sys/vnode.h>
47#include <sys/sbuf.h>
48#ifdef GJ_MEMDEBUG
49#include <sys/stack.h>
50#include <sys/kdb.h>
51#endif
52#include <vm/vm.h>
53#include <vm/vm_kern.h>
54#include <geom/geom.h>
55
56#include <geom/journal/g_journal.h>
57
58
59/*
60 * On-disk journal format:
61 *
62 * JH - Journal header
63 * RH - Record header
64 *
65 * %%%%%% ****** +------+ +------+     ****** +------+     %%%%%%
66 * % JH % * RH * | Data | | Data | ... * RH * | Data | ... % JH % ...
67 * %%%%%% ****** +------+ +------+     ****** +------+     %%%%%%
68 *
69 */
70
71CTASSERT(sizeof(struct g_journal_header) <= 512);
72CTASSERT(sizeof(struct g_journal_record_header) <= 512);
73
74static MALLOC_DEFINE(M_JOURNAL, "journal_data", "GEOM_JOURNAL Data");
75static struct mtx g_journal_cache_mtx;
76MTX_SYSINIT(g_journal_cache, &g_journal_cache_mtx, "cache usage", MTX_DEF);
77
78const struct g_journal_desc *g_journal_filesystems[] = {
79	&g_journal_ufs,
80	NULL
81};
82
83SYSCTL_DECL(_kern_geom);
84
85int g_journal_debug = 0;
86TUNABLE_INT("kern.geom.journal.debug", &g_journal_debug);
87static u_int g_journal_switch_time = 10;
88static u_int g_journal_force_switch = 70;
89static u_int g_journal_parallel_flushes = 16;
90static u_int g_journal_parallel_copies = 16;
91static u_int g_journal_accept_immediately = 64;
92static u_int g_journal_record_entries = GJ_RECORD_HEADER_NENTRIES;
93static u_int g_journal_do_optimize = 1;
94
95SYSCTL_NODE(_kern_geom, OID_AUTO, journal, CTLFLAG_RW, 0, "GEOM_JOURNAL stuff");
96SYSCTL_INT(_kern_geom_journal, OID_AUTO, debug, CTLFLAG_RW, &g_journal_debug, 0,
97    "Debug level");
98SYSCTL_UINT(_kern_geom_journal, OID_AUTO, switch_time, CTLFLAG_RW,
99    &g_journal_switch_time, 0, "Switch journals every N seconds");
100SYSCTL_UINT(_kern_geom_journal, OID_AUTO, force_switch, CTLFLAG_RW,
101    &g_journal_force_switch, 0, "Force switch when journal is N%% full");
102SYSCTL_UINT(_kern_geom_journal, OID_AUTO, parallel_flushes, CTLFLAG_RW,
103    &g_journal_parallel_flushes, 0,
104    "Number of flush I/O requests send in parallel");
105SYSCTL_UINT(_kern_geom_journal, OID_AUTO, accept_immediately, CTLFLAG_RW,
106    &g_journal_accept_immediately, 0,
107    "Number of I/O requests accepted immediatelly");
108SYSCTL_UINT(_kern_geom_journal, OID_AUTO, parallel_copies, CTLFLAG_RW,
109    &g_journal_parallel_copies, 0,
110    "Number of copy I/O requests send in parallel");
111static int
112g_journal_record_entries_sysctl(SYSCTL_HANDLER_ARGS)
113{
114	u_int entries;
115	int error;
116
117	entries = g_journal_record_entries;
118	error = sysctl_handle_int(oidp, &entries, sizeof(entries), req);
119	if (error != 0 || req->newptr == NULL)
120		return (error);
121	if (entries < 1 || entries > GJ_RECORD_HEADER_NENTRIES)
122		return (EINVAL);
123	g_journal_record_entries = entries;
124	return (0);
125}
126SYSCTL_PROC(_kern_geom_journal, OID_AUTO, record_entries,
127    CTLTYPE_UINT | CTLFLAG_RW, NULL, 0, g_journal_record_entries_sysctl, "I",
128    "Maximum number of entires in one journal record");
129SYSCTL_UINT(_kern_geom_journal, OID_AUTO, optimize, CTLFLAG_RW,
130    &g_journal_do_optimize, 0, "Try to combine bios on flush and copy");
131
132static u_int g_journal_cache_used = 0;
133static u_int g_journal_cache_limit = 64 * 1024 * 1024;
134TUNABLE_INT("kern.geom.journal.cache.limit", &g_journal_cache_limit);
135static u_int g_journal_cache_divisor = 2;
136TUNABLE_INT("kern.geom.journal.cache.divisor", &g_journal_cache_divisor);
137static u_int g_journal_cache_switch = 90;
138static u_int g_journal_cache_misses = 0;
139static u_int g_journal_cache_alloc_failures = 0;
140static u_int g_journal_cache_low = 0;
141
142SYSCTL_NODE(_kern_geom_journal, OID_AUTO, cache, CTLFLAG_RW, 0,
143    "GEOM_JOURNAL cache");
144SYSCTL_UINT(_kern_geom_journal_cache, OID_AUTO, used, CTLFLAG_RD,
145    &g_journal_cache_used, 0, "Number of allocated bytes");
146static int
147g_journal_cache_limit_sysctl(SYSCTL_HANDLER_ARGS)
148{
149	u_int limit;
150	int error;
151
152	limit = g_journal_cache_limit;
153	error = sysctl_handle_int(oidp, &limit, sizeof(limit), req);
154	if (error != 0 || req->newptr == NULL)
155		return (error);
156	g_journal_cache_limit = limit;
157	g_journal_cache_low = (limit / 100) * g_journal_cache_switch;
158	return (0);
159}
160SYSCTL_PROC(_kern_geom_journal_cache, OID_AUTO, limit,
161    CTLTYPE_UINT | CTLFLAG_RW, NULL, 0, g_journal_cache_limit_sysctl, "I",
162    "Maximum number of allocated bytes");
163SYSCTL_UINT(_kern_geom_journal_cache, OID_AUTO, divisor, CTLFLAG_RDTUN,
164    &g_journal_cache_divisor, 0,
165    "(kmem_size / kern.geom.journal.cache.divisor) == cache size");
166static int
167g_journal_cache_switch_sysctl(SYSCTL_HANDLER_ARGS)
168{
169	u_int cswitch;
170	int error;
171
172	cswitch = g_journal_cache_switch;
173	error = sysctl_handle_int(oidp, &cswitch, sizeof(cswitch), req);
174	if (error != 0 || req->newptr == NULL)
175		return (error);
176	if (cswitch < 0 || cswitch > 100)
177		return (EINVAL);
178	g_journal_cache_switch = cswitch;
179	g_journal_cache_low = (g_journal_cache_limit / 100) * cswitch;
180	return (0);
181}
182SYSCTL_PROC(_kern_geom_journal_cache, OID_AUTO, switch,
183    CTLTYPE_UINT | CTLFLAG_RW, NULL, 0, g_journal_cache_switch_sysctl, "I",
184    "Force switch when we hit this percent of cache use");
185SYSCTL_UINT(_kern_geom_journal_cache, OID_AUTO, misses, CTLFLAG_RW,
186    &g_journal_cache_misses, 0, "Number of cache misses");
187SYSCTL_UINT(_kern_geom_journal_cache, OID_AUTO, alloc_failures, CTLFLAG_RW,
188    &g_journal_cache_alloc_failures, 0, "Memory allocation failures");
189
190static u_long g_journal_stats_bytes_skipped = 0;
191static u_long g_journal_stats_combined_ios = 0;
192static u_long g_journal_stats_switches = 0;
193static u_long g_journal_stats_wait_for_copy = 0;
194static u_long g_journal_stats_journal_full = 0;
195static u_long g_journal_stats_low_mem = 0;
196
197SYSCTL_NODE(_kern_geom_journal, OID_AUTO, stats, CTLFLAG_RW, 0,
198    "GEOM_JOURNAL statistics");
199SYSCTL_ULONG(_kern_geom_journal_stats, OID_AUTO, skipped_bytes, CTLFLAG_RW,
200    &g_journal_stats_bytes_skipped, 0, "Number of skipped bytes");
201SYSCTL_ULONG(_kern_geom_journal_stats, OID_AUTO, combined_ios, CTLFLAG_RW,
202    &g_journal_stats_combined_ios, 0, "Number of combined I/O requests");
203SYSCTL_ULONG(_kern_geom_journal_stats, OID_AUTO, switches, CTLFLAG_RW,
204    &g_journal_stats_switches, 0, "Number of journal switches");
205SYSCTL_ULONG(_kern_geom_journal_stats, OID_AUTO, wait_for_copy, CTLFLAG_RW,
206    &g_journal_stats_wait_for_copy, 0, "Wait for journal copy on switch");
207SYSCTL_ULONG(_kern_geom_journal_stats, OID_AUTO, journal_full, CTLFLAG_RW,
208    &g_journal_stats_journal_full, 0,
209    "Number of times journal was almost full.");
210SYSCTL_ULONG(_kern_geom_journal_stats, OID_AUTO, low_mem, CTLFLAG_RW,
211    &g_journal_stats_low_mem, 0, "Number of times low_mem hook was called.");
212
213static g_taste_t g_journal_taste;
214static g_ctl_req_t g_journal_config;
215static g_dumpconf_t g_journal_dumpconf;
216static g_init_t g_journal_init;
217static g_fini_t g_journal_fini;
218
219struct g_class g_journal_class = {
220	.name = G_JOURNAL_CLASS_NAME,
221	.version = G_VERSION,
222	.taste = g_journal_taste,
223	.ctlreq = g_journal_config,
224	.dumpconf = g_journal_dumpconf,
225	.init = g_journal_init,
226	.fini = g_journal_fini
227};
228
229static int g_journal_destroy(struct g_journal_softc *sc);
230static void g_journal_metadata_update(struct g_journal_softc *sc);
231static void g_journal_switch_wait(struct g_journal_softc *sc);
232
233#define	GJ_SWITCHER_WORKING	0
234#define	GJ_SWITCHER_DIE		1
235#define	GJ_SWITCHER_DIED	2
236static int g_journal_switcher_state = GJ_SWITCHER_WORKING;
237static int g_journal_switcher_wokenup = 0;
238static int g_journal_sync_requested = 0;
239
240#ifdef GJ_MEMDEBUG
241struct meminfo {
242	size_t		mi_size;
243	struct stack	mi_stack;
244};
245#endif
246
247/*
248 * We use our own malloc/realloc/free funtions, so we can collect statistics
249 * and force journal switch when we're running out of cache.
250 */
251static void *
252gj_malloc(size_t size, int flags)
253{
254	void *p;
255#ifdef GJ_MEMDEBUG
256	struct meminfo *mi;
257#endif
258
259	mtx_lock(&g_journal_cache_mtx);
260	if (g_journal_cache_limit > 0 && !g_journal_switcher_wokenup &&
261	    g_journal_cache_used + size > g_journal_cache_low) {
262		GJ_DEBUG(1, "No cache, waking up the switcher.");
263		g_journal_switcher_wokenup = 1;
264		wakeup(&g_journal_switcher_state);
265	}
266	if ((flags & M_NOWAIT) && g_journal_cache_limit > 0 &&
267	    g_journal_cache_used + size > g_journal_cache_limit) {
268		mtx_unlock(&g_journal_cache_mtx);
269		g_journal_cache_alloc_failures++;
270		return (NULL);
271	}
272	g_journal_cache_used += size;
273	mtx_unlock(&g_journal_cache_mtx);
274	flags &= ~M_NOWAIT;
275#ifndef GJ_MEMDEBUG
276	p = malloc(size, M_JOURNAL, flags | M_WAITOK);
277#else
278	mi = malloc(sizeof(*mi) + size, M_JOURNAL, flags | M_WAITOK);
279	p = (u_char *)mi + sizeof(*mi);
280	mi->mi_size = size;
281	stack_save(&mi->mi_stack);
282#endif
283	return (p);
284}
285
286static void
287gj_free(void *p, size_t size)
288{
289#ifdef GJ_MEMDEBUG
290	struct meminfo *mi;
291#endif
292
293	KASSERT(p != NULL, ("p=NULL"));
294	KASSERT(size > 0, ("size=0"));
295	mtx_lock(&g_journal_cache_mtx);
296	KASSERT(g_journal_cache_used >= size, ("Freeing too much?"));
297	g_journal_cache_used -= size;
298	mtx_unlock(&g_journal_cache_mtx);
299#ifdef GJ_MEMDEBUG
300	mi = p = (void *)((u_char *)p - sizeof(*mi));
301	if (mi->mi_size != size) {
302		printf("GJOURNAL: Size mismatch! %zu != %zu\n", size,
303		    mi->mi_size);
304		printf("GJOURNAL: Alloc backtrace:\n");
305		stack_print(&mi->mi_stack);
306		printf("GJOURNAL: Free backtrace:\n");
307		kdb_backtrace();
308	}
309#endif
310	free(p, M_JOURNAL);
311}
312
313static void *
314gj_realloc(void *p, size_t size, size_t oldsize)
315{
316	void *np;
317
318#ifndef GJ_MEMDEBUG
319	mtx_lock(&g_journal_cache_mtx);
320	g_journal_cache_used -= oldsize;
321	g_journal_cache_used += size;
322	mtx_unlock(&g_journal_cache_mtx);
323	np = realloc(p, size, M_JOURNAL, M_WAITOK);
324#else
325	np = gj_malloc(size, M_WAITOK);
326	bcopy(p, np, MIN(oldsize, size));
327	gj_free(p, oldsize);
328#endif
329	return (np);
330}
331
332static void
333g_journal_check_overflow(struct g_journal_softc *sc)
334{
335	off_t length, used;
336
337	if ((sc->sc_active.jj_offset < sc->sc_inactive.jj_offset &&
338	     sc->sc_journal_offset >= sc->sc_inactive.jj_offset) ||
339	    (sc->sc_active.jj_offset > sc->sc_inactive.jj_offset &&
340	     sc->sc_journal_offset >= sc->sc_inactive.jj_offset &&
341	     sc->sc_journal_offset < sc->sc_active.jj_offset)) {
342		panic("Journal overflow (joffset=%jd active=%jd inactive=%jd)",
343		    (intmax_t)sc->sc_journal_offset,
344		    (intmax_t)sc->sc_active.jj_offset,
345		    (intmax_t)sc->sc_inactive.jj_offset);
346	}
347	if (sc->sc_active.jj_offset < sc->sc_inactive.jj_offset) {
348		length = sc->sc_inactive.jj_offset - sc->sc_active.jj_offset;
349		used = sc->sc_journal_offset - sc->sc_active.jj_offset;
350	} else {
351		length = sc->sc_jend - sc->sc_active.jj_offset;
352		length += sc->sc_inactive.jj_offset - sc->sc_jstart;
353		if (sc->sc_journal_offset >= sc->sc_active.jj_offset)
354			used = sc->sc_journal_offset - sc->sc_active.jj_offset;
355		else {
356			used = sc->sc_jend - sc->sc_active.jj_offset;
357			used += sc->sc_journal_offset - sc->sc_jstart;
358		}
359	}
360	/* Already woken up? */
361	if (g_journal_switcher_wokenup)
362		return;
363	/*
364	 * If the active journal takes more than g_journal_force_switch precent
365	 * of free journal space, we force journal switch.
366	 */
367	KASSERT(length > 0,
368	    ("length=%jd used=%jd active=%jd inactive=%jd joffset=%jd",
369	    (intmax_t)length, (intmax_t)used,
370	    (intmax_t)sc->sc_active.jj_offset,
371	    (intmax_t)sc->sc_inactive.jj_offset,
372	    (intmax_t)sc->sc_journal_offset));
373	if ((used * 100) / length > g_journal_force_switch) {
374		g_journal_stats_journal_full++;
375		GJ_DEBUG(1, "Journal %s %jd%% full, forcing journal switch.",
376		    sc->sc_name, (used * 100) / length);
377		mtx_lock(&g_journal_cache_mtx);
378		g_journal_switcher_wokenup = 1;
379		wakeup(&g_journal_switcher_state);
380		mtx_unlock(&g_journal_cache_mtx);
381	}
382}
383
384static void
385g_journal_orphan(struct g_consumer *cp)
386{
387	struct g_journal_softc *sc;
388	char name[256];
389	int error;
390
391	g_topology_assert();
392	sc = cp->geom->softc;
393	GJ_DEBUG(0, "Lost provider %s (journal=%s).", cp->provider->name,
394	    sc->sc_name);
395	strlcpy(name, sc->sc_name, sizeof(name));
396	error = g_journal_destroy(sc);
397	if (error == 0)
398		GJ_DEBUG(0, "Journal %s destroyed.", name);
399	else {
400		GJ_DEBUG(0, "Cannot destroy journal %s (error=%d). "
401		    "Destroy it manually after last close.", sc->sc_name,
402		    error);
403	}
404}
405
406static int
407g_journal_access(struct g_provider *pp, int acr, int acw, int ace)
408{
409	struct g_journal_softc *sc;
410	int dcr, dcw, dce;
411
412	g_topology_assert();
413	GJ_DEBUG(2, "Access request for %s: r%dw%de%d.", pp->name,
414	    acr, acw, ace);
415
416	dcr = pp->acr + acr;
417	dcw = pp->acw + acw;
418	dce = pp->ace + ace;
419
420	sc = pp->geom->softc;
421	if (sc == NULL || (sc->sc_flags & GJF_DEVICE_DESTROY)) {
422		if (acr <= 0 && acw <= 0 && ace <= 0)
423			return (0);
424		else
425			return (ENXIO);
426	}
427	if (pp->acw == 0 && dcw > 0) {
428		GJ_DEBUG(1, "Marking %s as dirty.", sc->sc_name);
429		sc->sc_flags &= ~GJF_DEVICE_CLEAN;
430		g_topology_unlock();
431		g_journal_metadata_update(sc);
432		g_topology_lock();
433	} /* else if (pp->acw == 0 && dcw > 0 && JEMPTY(sc)) {
434		GJ_DEBUG(1, "Marking %s as clean.", sc->sc_name);
435		sc->sc_flags |= GJF_DEVICE_CLEAN;
436		g_topology_unlock();
437		g_journal_metadata_update(sc);
438		g_topology_lock();
439	} */
440	return (0);
441}
442
443static void
444g_journal_header_encode(struct g_journal_header *hdr, u_char *data)
445{
446
447	bcopy(GJ_HEADER_MAGIC, data, sizeof(GJ_HEADER_MAGIC));
448	data += sizeof(GJ_HEADER_MAGIC);
449	le32enc(data, hdr->jh_journal_id);
450	data += 4;
451	le32enc(data, hdr->jh_journal_next_id);
452}
453
454static int
455g_journal_header_decode(const u_char *data, struct g_journal_header *hdr)
456{
457
458	bcopy(data, hdr->jh_magic, sizeof(hdr->jh_magic));
459	data += sizeof(hdr->jh_magic);
460	if (bcmp(hdr->jh_magic, GJ_HEADER_MAGIC, sizeof(GJ_HEADER_MAGIC)) != 0)
461		return (EINVAL);
462	hdr->jh_journal_id = le32dec(data);
463	data += 4;
464	hdr->jh_journal_next_id = le32dec(data);
465	return (0);
466}
467
468static void
469g_journal_flush_cache(struct g_journal_softc *sc)
470{
471	struct bintime bt;
472	int error;
473
474	if (sc->sc_bio_flush == 0)
475		return;
476	GJ_TIMER_START(1, &bt);
477	if (sc->sc_bio_flush & GJ_FLUSH_JOURNAL) {
478		error = g_io_flush(sc->sc_jconsumer);
479		GJ_DEBUG(error == 0 ? 2 : 0, "Flush cache of %s: error=%d.",
480		    sc->sc_jconsumer->provider->name, error);
481	}
482	if (sc->sc_bio_flush & GJ_FLUSH_DATA) {
483		/*
484		 * TODO: This could be called in parallel with the
485		 *       previous call.
486		 */
487		error = g_io_flush(sc->sc_dconsumer);
488		GJ_DEBUG(error == 0 ? 2 : 0, "Flush cache of %s: error=%d.",
489		    sc->sc_dconsumer->provider->name, error);
490	}
491	GJ_TIMER_STOP(1, &bt, "Cache flush time");
492}
493
494static int
495g_journal_write_header(struct g_journal_softc *sc)
496{
497	struct g_journal_header hdr;
498	struct g_consumer *cp;
499	u_char *buf;
500	int error;
501
502	cp = sc->sc_jconsumer;
503	buf = gj_malloc(cp->provider->sectorsize, M_WAITOK);
504
505	strlcpy(hdr.jh_magic, GJ_HEADER_MAGIC, sizeof(hdr.jh_magic));
506	hdr.jh_journal_id = sc->sc_journal_id;
507	hdr.jh_journal_next_id = sc->sc_journal_next_id;
508	g_journal_header_encode(&hdr, buf);
509	error = g_write_data(cp, sc->sc_journal_offset, buf,
510	    cp->provider->sectorsize);
511	/* if (error == 0) */
512	sc->sc_journal_offset += cp->provider->sectorsize;
513
514	gj_free(buf, cp->provider->sectorsize);
515	return (error);
516}
517
518/*
519 * Every journal record has a header and data following it.
520 * Functions below are used to decode the header before storing it to
521 * little endian and to encode it after reading to system endianess.
522 */
523static void
524g_journal_record_header_encode(struct g_journal_record_header *hdr,
525    u_char *data)
526{
527	struct g_journal_entry *ent;
528	u_int i;
529
530	bcopy(GJ_RECORD_HEADER_MAGIC, data, sizeof(GJ_RECORD_HEADER_MAGIC));
531	data += sizeof(GJ_RECORD_HEADER_MAGIC);
532	le32enc(data, hdr->jrh_journal_id);
533	data += 8;
534	le16enc(data, hdr->jrh_nentries);
535	data += 2;
536	bcopy(hdr->jrh_sum, data, sizeof(hdr->jrh_sum));
537	data += 8;
538	for (i = 0; i < hdr->jrh_nentries; i++) {
539		ent = &hdr->jrh_entries[i];
540		le64enc(data, ent->je_joffset);
541		data += 8;
542		le64enc(data, ent->je_offset);
543		data += 8;
544		le64enc(data, ent->je_length);
545		data += 8;
546	}
547}
548
549static int
550g_journal_record_header_decode(const u_char *data,
551    struct g_journal_record_header *hdr)
552{
553	struct g_journal_entry *ent;
554	u_int i;
555
556	bcopy(data, hdr->jrh_magic, sizeof(hdr->jrh_magic));
557	data += sizeof(hdr->jrh_magic);
558	if (strcmp(hdr->jrh_magic, GJ_RECORD_HEADER_MAGIC) != 0)
559		return (EINVAL);
560	hdr->jrh_journal_id = le32dec(data);
561	data += 8;
562	hdr->jrh_nentries = le16dec(data);
563	data += 2;
564	if (hdr->jrh_nentries > GJ_RECORD_HEADER_NENTRIES)
565		return (EINVAL);
566	bcopy(data, hdr->jrh_sum, sizeof(hdr->jrh_sum));
567	data += 8;
568	for (i = 0; i < hdr->jrh_nentries; i++) {
569		ent = &hdr->jrh_entries[i];
570		ent->je_joffset = le64dec(data);
571		data += 8;
572		ent->je_offset = le64dec(data);
573		data += 8;
574		ent->je_length = le64dec(data);
575		data += 8;
576	}
577	return (0);
578}
579
580/*
581 * Function reads metadata from a provider (via the given consumer), decodes
582 * it to system endianess and verifies its correctness.
583 */
584static int
585g_journal_metadata_read(struct g_consumer *cp, struct g_journal_metadata *md)
586{
587	struct g_provider *pp;
588	u_char *buf;
589	int error;
590
591	g_topology_assert();
592
593	error = g_access(cp, 1, 0, 0);
594	if (error != 0)
595		return (error);
596	pp = cp->provider;
597	g_topology_unlock();
598	/* Metadata is stored in last sector. */
599	buf = g_read_data(cp, pp->mediasize - pp->sectorsize, pp->sectorsize,
600	    &error);
601	g_topology_lock();
602	g_access(cp, -1, 0, 0);
603	if (buf == NULL) {
604		GJ_DEBUG(1, "Cannot read metadata from %s (error=%d).",
605		    cp->provider->name, error);
606		return (error);
607	}
608
609	/* Decode metadata. */
610	error = journal_metadata_decode(buf, md);
611	g_free(buf);
612	/* Is this is gjournal provider at all? */
613	if (strcmp(md->md_magic, G_JOURNAL_MAGIC) != 0)
614		return (EINVAL);
615	/*
616	 * Are we able to handle this version of metadata?
617	 * We only maintain backward compatibility.
618	 */
619	if (md->md_version > G_JOURNAL_VERSION) {
620		GJ_DEBUG(0,
621		    "Kernel module is too old to handle metadata from %s.",
622		    cp->provider->name);
623		return (EINVAL);
624	}
625	/* Is checksum correct? */
626	if (error != 0) {
627		GJ_DEBUG(0, "MD5 metadata hash mismatch for provider %s.",
628		    cp->provider->name);
629		return (error);
630	}
631	return (0);
632}
633
634/*
635 * Two functions below are responsible for updating metadata.
636 * Only metadata on the data provider is updated (we need to update
637 * information about active journal in there).
638 */
639static void
640g_journal_metadata_done(struct bio *bp)
641{
642
643	/*
644	 * There is not much we can do on error except informing about it.
645	 */
646	if (bp->bio_error != 0) {
647		GJ_LOGREQ(0, bp, "Cannot update metadata (error=%d).",
648		    bp->bio_error);
649	} else {
650		GJ_LOGREQ(2, bp, "Metadata updated.");
651	}
652	gj_free(bp->bio_data, bp->bio_length);
653	g_destroy_bio(bp);
654}
655
656static void
657g_journal_metadata_update(struct g_journal_softc *sc)
658{
659	struct g_journal_metadata md;
660	struct g_consumer *cp;
661	struct bio *bp;
662	u_char *sector;
663
664	cp = sc->sc_dconsumer;
665	sector = gj_malloc(cp->provider->sectorsize, M_WAITOK);
666	strlcpy(md.md_magic, G_JOURNAL_MAGIC, sizeof(md.md_magic));
667	md.md_version = G_JOURNAL_VERSION;
668	md.md_id = sc->sc_id;
669	md.md_type = sc->sc_orig_type;
670	md.md_jstart = sc->sc_jstart;
671	md.md_jend = sc->sc_jend;
672	md.md_joffset = sc->sc_inactive.jj_offset;
673	md.md_jid = sc->sc_journal_previous_id;
674	md.md_flags = 0;
675	if (sc->sc_flags & GJF_DEVICE_CLEAN)
676		md.md_flags |= GJ_FLAG_CLEAN;
677
678	if (sc->sc_flags & GJF_DEVICE_HARDCODED)
679		strlcpy(md.md_provider, sc->sc_name, sizeof(md.md_provider));
680	else
681		bzero(md.md_provider, sizeof(md.md_provider));
682	md.md_provsize = cp->provider->mediasize;
683	journal_metadata_encode(&md, sector);
684
685	/*
686	 * Flush the cache, so we know all data are on disk.
687	 * We write here informations like "journal is consistent", so we need
688	 * to be sure it is. Without BIO_FLUSH here, we can end up in situation
689	 * where metadata is stored on disk, but not all data.
690	 */
691	g_journal_flush_cache(sc);
692
693	bp = g_alloc_bio();
694	bp->bio_offset = cp->provider->mediasize - cp->provider->sectorsize;
695	bp->bio_length = cp->provider->sectorsize;
696	bp->bio_data = sector;
697	bp->bio_cmd = BIO_WRITE;
698	if (!(sc->sc_flags & GJF_DEVICE_DESTROY)) {
699		bp->bio_done = g_journal_metadata_done;
700		g_io_request(bp, cp);
701	} else {
702		bp->bio_done = NULL;
703		g_io_request(bp, cp);
704		biowait(bp, "gjmdu");
705		g_journal_metadata_done(bp);
706	}
707
708	/*
709	 * Be sure metadata reached the disk.
710	 */
711	g_journal_flush_cache(sc);
712}
713
714/*
715 * This is where the I/O request comes from the GEOM.
716 */
717static void
718g_journal_start(struct bio *bp)
719{
720	struct g_journal_softc *sc;
721
722	sc = bp->bio_to->geom->softc;
723	GJ_LOGREQ(3, bp, "Request received.");
724
725	switch (bp->bio_cmd) {
726	case BIO_READ:
727	case BIO_WRITE:
728		mtx_lock(&sc->sc_mtx);
729		bioq_insert_tail(&sc->sc_regular_queue, bp);
730		wakeup(sc);
731		mtx_unlock(&sc->sc_mtx);
732		return;
733	case BIO_GETATTR:
734		if (strcmp(bp->bio_attribute, "GJOURNAL::provider") == 0) {
735			strlcpy(bp->bio_data, bp->bio_to->name, bp->bio_length);
736			bp->bio_completed = strlen(bp->bio_to->name) + 1;
737			g_io_deliver(bp, 0);
738			return;
739		}
740		/* FALLTHROUGH */
741	case BIO_DELETE:
742	default:
743		g_io_deliver(bp, EOPNOTSUPP);
744		return;
745	}
746}
747
748static void
749g_journal_std_done(struct bio *bp)
750{
751	struct g_journal_softc *sc;
752
753	sc = bp->bio_from->geom->softc;
754	mtx_lock(&sc->sc_mtx);
755	bioq_insert_tail(&sc->sc_back_queue, bp);
756	wakeup(sc);
757	mtx_unlock(&sc->sc_mtx);
758}
759
760static struct bio *
761g_journal_new_bio(off_t start, off_t end, off_t joffset, u_char *data,
762    int flags)
763{
764	struct bio *bp;
765
766	bp = g_alloc_bio();
767	bp->bio_offset = start;
768	bp->bio_joffset = joffset;
769	bp->bio_length = end - start;
770	bp->bio_cmd = BIO_WRITE;
771	bp->bio_done = g_journal_std_done;
772	if (data == NULL)
773		bp->bio_data = NULL;
774	else {
775		bp->bio_data = gj_malloc(bp->bio_length, flags);
776		if (bp->bio_data != NULL)
777			bcopy(data, bp->bio_data, bp->bio_length);
778	}
779	return (bp);
780}
781
782#define	g_journal_insert_bio(head, bp, flags)				\
783	g_journal_insert((head), (bp)->bio_offset,			\
784		(bp)->bio_offset + (bp)->bio_length, (bp)->bio_joffset,	\
785		(bp)->bio_data, flags)
786/*
787 * The function below does a lot more than just inserting bio to the queue.
788 * It keeps the queue sorted by offset and ensures that there are no doubled
789 * data (it combines bios where ranges overlap).
790 *
791 * The function returns the number of bios inserted (as bio can be splitted).
792 */
793static int
794g_journal_insert(struct bio **head, off_t nstart, off_t nend, off_t joffset,
795    u_char *data, int flags)
796{
797	struct bio *nbp, *cbp, *pbp;
798	off_t cstart, cend;
799	u_char *tmpdata;
800	int n;
801
802	GJ_DEBUG(3, "INSERT(%p): (%jd, %jd, %jd)", *head, nstart, nend,
803	    joffset);
804	n = 0;
805	pbp = NULL;
806	GJQ_FOREACH(*head, cbp) {
807		cstart = cbp->bio_offset;
808		cend = cbp->bio_offset + cbp->bio_length;
809
810		if (nstart >= cend) {
811			/*
812			 *  +-------------+
813			 *  |             |
814			 *  |   current   |  +-------------+
815			 *  |     bio     |  |             |
816			 *  |             |  |     new     |
817			 *  +-------------+  |     bio     |
818			 *                   |             |
819			 *                   +-------------+
820			 */
821			GJ_DEBUG(3, "INSERT(%p): 1", *head);
822		} else if (nend <= cstart) {
823			/*
824			 *                   +-------------+
825			 *                   |             |
826			 *  +-------------+  |   current   |
827			 *  |             |  |     bio     |
828			 *  |     new     |  |             |
829			 *  |     bio     |  +-------------+
830			 *  |             |
831			 *  +-------------+
832			 */
833			nbp = g_journal_new_bio(nstart, nend, joffset, data,
834			    flags);
835			if (pbp == NULL)
836				*head = nbp;
837			else
838				pbp->bio_next = nbp;
839			nbp->bio_next = cbp;
840			n++;
841			GJ_DEBUG(3, "INSERT(%p): 2 (nbp=%p pbp=%p)", *head, nbp,
842			    pbp);
843			goto end;
844		} else if (nstart <= cstart && nend >= cend) {
845			/*
846			 *      +-------------+      +-------------+
847			 *      | current bio |      | current bio |
848			 *  +---+-------------+---+  +-------------+---+
849			 *  |   |             |   |  |             |   |
850			 *  |   |             |   |  |             |   |
851			 *  |   +-------------+   |  +-------------+   |
852			 *  |       new bio       |  |     new bio     |
853			 *  +---------------------+  +-----------------+
854			 *
855			 *      +-------------+  +-------------+
856			 *      | current bio |  | current bio |
857			 *  +---+-------------+  +-------------+
858			 *  |   |             |  |             |
859			 *  |   |             |  |             |
860			 *  |   +-------------+  +-------------+
861			 *  |     new bio     |  |   new bio   |
862			 *  +-----------------+  +-------------+
863			 */
864			g_journal_stats_bytes_skipped += cbp->bio_length;
865			cbp->bio_offset = nstart;
866			cbp->bio_joffset = joffset;
867			cbp->bio_length = cend - nstart;
868			if (cbp->bio_data != NULL) {
869				gj_free(cbp->bio_data, cend - cstart);
870				cbp->bio_data = NULL;
871			}
872			if (data != NULL) {
873				cbp->bio_data = gj_malloc(cbp->bio_length,
874				    flags);
875				if (cbp->bio_data != NULL) {
876					bcopy(data, cbp->bio_data,
877					    cbp->bio_length);
878				}
879				data += cend - nstart;
880			}
881			joffset += cend - nstart;
882			nstart = cend;
883			GJ_DEBUG(3, "INSERT(%p): 3 (cbp=%p)", *head, cbp);
884		} else if (nstart > cstart && nend >= cend) {
885			/*
886			 *  +-----------------+  +-------------+
887			 *  |   current bio   |  | current bio |
888			 *  |   +-------------+  |   +---------+---+
889			 *  |   |             |  |   |         |   |
890			 *  |   |             |  |   |         |   |
891			 *  +---+-------------+  +---+---------+   |
892			 *      |   new bio   |      |   new bio   |
893			 *      +-------------+      +-------------+
894			 */
895			g_journal_stats_bytes_skipped += cend - nstart;
896			nbp = g_journal_new_bio(nstart, cend, joffset, data,
897			    flags);
898			nbp->bio_next = cbp->bio_next;
899			cbp->bio_next = nbp;
900			cbp->bio_length = nstart - cstart;
901			if (cbp->bio_data != NULL) {
902				cbp->bio_data = gj_realloc(cbp->bio_data,
903				    cbp->bio_length, cend - cstart);
904			}
905			if (data != NULL)
906				data += cend - nstart;
907			joffset += cend - nstart;
908			nstart = cend;
909			n++;
910			GJ_DEBUG(3, "INSERT(%p): 4 (cbp=%p)", *head, cbp);
911		} else if (nstart > cstart && nend < cend) {
912			/*
913			 *  +---------------------+
914			 *  |     current bio     |
915			 *  |   +-------------+   |
916			 *  |   |             |   |
917			 *  |   |             |   |
918			 *  +---+-------------+---+
919			 *      |   new bio   |
920			 *      +-------------+
921			 */
922			g_journal_stats_bytes_skipped += nend - nstart;
923			nbp = g_journal_new_bio(nstart, nend, joffset, data,
924			    flags);
925			nbp->bio_next = cbp->bio_next;
926			cbp->bio_next = nbp;
927			if (cbp->bio_data == NULL)
928				tmpdata = NULL;
929			else
930				tmpdata = cbp->bio_data + nend - cstart;
931			nbp = g_journal_new_bio(nend, cend,
932			    cbp->bio_joffset + nend - cstart, tmpdata, flags);
933			nbp->bio_next = ((struct bio *)cbp->bio_next)->bio_next;
934			((struct bio *)cbp->bio_next)->bio_next = nbp;
935			cbp->bio_length = nstart - cstart;
936			if (cbp->bio_data != NULL) {
937				cbp->bio_data = gj_realloc(cbp->bio_data,
938				    cbp->bio_length, cend - cstart);
939			}
940			n += 2;
941			GJ_DEBUG(3, "INSERT(%p): 5 (cbp=%p)", *head, cbp);
942			goto end;
943		} else if (nstart <= cstart && nend < cend) {
944			/*
945			 *  +-----------------+      +-------------+
946			 *  |   current bio   |      | current bio |
947			 *  +-------------+   |  +---+---------+   |
948			 *  |             |   |  |   |         |   |
949			 *  |             |   |  |   |         |   |
950			 *  +-------------+---+  |   +---------+---+
951			 *  |   new bio   |      |   new bio   |
952			 *  +-------------+      +-------------+
953			 */
954			g_journal_stats_bytes_skipped += nend - nstart;
955			nbp = g_journal_new_bio(nstart, nend, joffset, data,
956			    flags);
957			if (pbp == NULL)
958				*head = nbp;
959			else
960				pbp->bio_next = nbp;
961			nbp->bio_next = cbp;
962			cbp->bio_offset = nend;
963			cbp->bio_length = cend - nend;
964			cbp->bio_joffset += nend - cstart;
965			tmpdata = cbp->bio_data;
966			if (tmpdata != NULL) {
967				cbp->bio_data = gj_malloc(cbp->bio_length,
968				    flags);
969				if (cbp->bio_data != NULL) {
970					bcopy(tmpdata + nend - cstart,
971					    cbp->bio_data, cbp->bio_length);
972				}
973				gj_free(tmpdata, cend - cstart);
974			}
975			n++;
976			GJ_DEBUG(3, "INSERT(%p): 6 (cbp=%p)", *head, cbp);
977			goto end;
978		}
979		if (nstart == nend)
980			goto end;
981		pbp = cbp;
982	}
983	nbp = g_journal_new_bio(nstart, nend, joffset, data, flags);
984	if (pbp == NULL)
985		*head = nbp;
986	else
987		pbp->bio_next = nbp;
988	nbp->bio_next = NULL;
989	n++;
990	GJ_DEBUG(3, "INSERT(%p): 8 (nbp=%p pbp=%p)", *head, nbp, pbp);
991end:
992	if (g_journal_debug >= 3) {
993		GJQ_FOREACH(*head, cbp) {
994			GJ_DEBUG(3, "ELEMENT: %p (%jd, %jd, %jd, %p)", cbp,
995			    (intmax_t)cbp->bio_offset,
996			    (intmax_t)cbp->bio_length,
997			    (intmax_t)cbp->bio_joffset, cbp->bio_data);
998		}
999		GJ_DEBUG(3, "INSERT(%p): DONE %d", *head, n);
1000	}
1001	return (n);
1002}
1003
1004/*
1005 * The function combines neighbour bios trying to squeeze as much data as
1006 * possible into one bio.
1007 *
1008 * The function returns the number of bios combined (negative value).
1009 */
1010static int
1011g_journal_optimize(struct bio *head)
1012{
1013	struct bio *cbp, *pbp;
1014	int n;
1015
1016	n = 0;
1017	pbp = NULL;
1018	GJQ_FOREACH(head, cbp) {
1019		/* Skip bios which has to be read first. */
1020		if (cbp->bio_data == NULL) {
1021			pbp = NULL;
1022			continue;
1023		}
1024		/* There is no previous bio yet. */
1025		if (pbp == NULL) {
1026			pbp = cbp;
1027			continue;
1028		}
1029		/* Is this a neighbour bio? */
1030		if (pbp->bio_offset + pbp->bio_length != cbp->bio_offset) {
1031			/* Be sure that bios queue is sorted. */
1032			KASSERT(pbp->bio_offset + pbp->bio_length < cbp->bio_offset,
1033			    ("poffset=%jd plength=%jd coffset=%jd",
1034			    (intmax_t)pbp->bio_offset,
1035			    (intmax_t)pbp->bio_length,
1036			    (intmax_t)cbp->bio_offset));
1037			pbp = cbp;
1038			continue;
1039		}
1040		/* Be sure we don't end up with too big bio. */
1041		if (pbp->bio_length + cbp->bio_length > MAXPHYS) {
1042			pbp = cbp;
1043			continue;
1044		}
1045		/* Ok, we can join bios. */
1046		GJ_LOGREQ(4, pbp, "Join: ");
1047		GJ_LOGREQ(4, cbp, "and: ");
1048		pbp->bio_data = gj_realloc(pbp->bio_data,
1049		    pbp->bio_length + cbp->bio_length, pbp->bio_length);
1050		bcopy(cbp->bio_data, pbp->bio_data + pbp->bio_length,
1051		    cbp->bio_length);
1052		gj_free(cbp->bio_data, cbp->bio_length);
1053		pbp->bio_length += cbp->bio_length;
1054		pbp->bio_next = cbp->bio_next;
1055		g_destroy_bio(cbp);
1056		cbp = pbp;
1057		g_journal_stats_combined_ios++;
1058		n--;
1059		GJ_LOGREQ(4, pbp, "Got: ");
1060	}
1061	return (n);
1062}
1063
1064/*
1065 * TODO: Update comment.
1066 * These are functions responsible for copying one portion of data from journal
1067 * to the destination provider.
1068 * The order goes like this:
1069 * 1. Read the header, which contains informations about data blocks
1070 *    following it.
1071 * 2. Read the data blocks from the journal.
1072 * 3. Write the data blocks on the data provider.
1073 *
1074 * g_journal_copy_start()
1075 * g_journal_copy_done() - got finished write request, logs potential errors.
1076 */
1077
1078/*
1079 * When there is no data in cache, this function is used to read it.
1080 */
1081static void
1082g_journal_read_first(struct g_journal_softc *sc, struct bio *bp)
1083{
1084	struct bio *cbp;
1085
1086	/*
1087	 * We were short in memory, so data was freed.
1088	 * In that case we need to read it back from journal.
1089	 */
1090	cbp = g_alloc_bio();
1091	cbp->bio_cflags = bp->bio_cflags;
1092	cbp->bio_parent = bp;
1093	cbp->bio_offset = bp->bio_joffset;
1094	cbp->bio_length = bp->bio_length;
1095	cbp->bio_data = gj_malloc(bp->bio_length, M_WAITOK);
1096	cbp->bio_cmd = BIO_READ;
1097	cbp->bio_done = g_journal_std_done;
1098	GJ_LOGREQ(4, cbp, "READ FIRST");
1099	g_io_request(cbp, sc->sc_jconsumer);
1100	g_journal_cache_misses++;
1101}
1102
1103static void
1104g_journal_copy_send(struct g_journal_softc *sc)
1105{
1106	struct bio *bioq, *bp, *lbp;
1107
1108	bioq = lbp = NULL;
1109	mtx_lock(&sc->sc_mtx);
1110	for (; sc->sc_copy_in_progress < g_journal_parallel_copies;) {
1111		bp = GJQ_FIRST(sc->sc_inactive.jj_queue);
1112		if (bp == NULL)
1113			break;
1114		GJQ_REMOVE(sc->sc_inactive.jj_queue, bp);
1115		sc->sc_copy_in_progress++;
1116		GJQ_INSERT_AFTER(bioq, bp, lbp);
1117		lbp = bp;
1118	}
1119	mtx_unlock(&sc->sc_mtx);
1120	if (g_journal_do_optimize)
1121		sc->sc_copy_in_progress += g_journal_optimize(bioq);
1122	while ((bp = GJQ_FIRST(bioq)) != NULL) {
1123		GJQ_REMOVE(bioq, bp);
1124		GJQ_INSERT_HEAD(sc->sc_copy_queue, bp);
1125		bp->bio_cflags = GJ_BIO_COPY;
1126		if (bp->bio_data == NULL)
1127			g_journal_read_first(sc, bp);
1128		else {
1129			bp->bio_joffset = 0;
1130			GJ_LOGREQ(4, bp, "SEND");
1131			g_io_request(bp, sc->sc_dconsumer);
1132		}
1133	}
1134}
1135
1136static void
1137g_journal_copy_start(struct g_journal_softc *sc)
1138{
1139
1140	/*
1141	 * Remember in metadata that we're starting to copy journaled data
1142	 * to the data provider.
1143	 * In case of power failure, we will copy these data once again on boot.
1144	 */
1145	if (!sc->sc_journal_copying) {
1146		sc->sc_journal_copying = 1;
1147		GJ_DEBUG(1, "Starting copy of journal.");
1148		g_journal_metadata_update(sc);
1149	}
1150	g_journal_copy_send(sc);
1151}
1152
1153/*
1154 * Data block has been read from the journal provider.
1155 */
1156static int
1157g_journal_copy_read_done(struct bio *bp)
1158{
1159	struct g_journal_softc *sc;
1160	struct g_consumer *cp;
1161	struct bio *pbp;
1162
1163	KASSERT(bp->bio_cflags == GJ_BIO_COPY,
1164	    ("Invalid bio (%d != %d).", bp->bio_cflags, GJ_BIO_COPY));
1165
1166	sc = bp->bio_from->geom->softc;
1167	pbp = bp->bio_parent;
1168
1169	if (bp->bio_error != 0) {
1170		GJ_DEBUG(0, "Error while reading data from %s (error=%d).",
1171		    bp->bio_to->name, bp->bio_error);
1172		/*
1173		 * We will not be able to deliver WRITE request as well.
1174		 */
1175		gj_free(bp->bio_data, bp->bio_length);
1176		g_destroy_bio(pbp);
1177		g_destroy_bio(bp);
1178		sc->sc_copy_in_progress--;
1179		return (1);
1180	}
1181	pbp->bio_data = bp->bio_data;
1182	cp = sc->sc_dconsumer;
1183	g_io_request(pbp, cp);
1184	GJ_LOGREQ(4, bp, "READ DONE");
1185	g_destroy_bio(bp);
1186	return (0);
1187}
1188
1189/*
1190 * Data block has been written to the data provider.
1191 */
1192static void
1193g_journal_copy_write_done(struct bio *bp)
1194{
1195	struct g_journal_softc *sc;
1196
1197	KASSERT(bp->bio_cflags == GJ_BIO_COPY,
1198	    ("Invalid bio (%d != %d).", bp->bio_cflags, GJ_BIO_COPY));
1199
1200	sc = bp->bio_from->geom->softc;
1201	sc->sc_copy_in_progress--;
1202
1203	if (bp->bio_error != 0) {
1204		GJ_LOGREQ(0, bp, "[copy] Error while writting data (error=%d)",
1205		    bp->bio_error);
1206	}
1207	GJQ_REMOVE(sc->sc_copy_queue, bp);
1208	gj_free(bp->bio_data, bp->bio_length);
1209	GJ_LOGREQ(4, bp, "DONE");
1210	g_destroy_bio(bp);
1211
1212	if (sc->sc_copy_in_progress == 0) {
1213		/*
1214		 * This was the last write request for this journal.
1215		 */
1216		GJ_DEBUG(1, "Data has been copied.");
1217		sc->sc_journal_copying = 0;
1218	}
1219}
1220
1221static void g_journal_flush_done(struct bio *bp);
1222
1223/*
1224 * Flush one record onto active journal provider.
1225 */
1226static void
1227g_journal_flush(struct g_journal_softc *sc)
1228{
1229	struct g_journal_record_header hdr;
1230	struct g_journal_entry *ent;
1231	struct g_provider *pp;
1232	struct bio **bioq;
1233	struct bio *bp, *fbp, *pbp;
1234	off_t joffset, size;
1235	u_char *data, hash[16];
1236	MD5_CTX ctx;
1237	u_int i;
1238
1239	if (sc->sc_current_count == 0)
1240		return;
1241
1242	size = 0;
1243	pp = sc->sc_jprovider;
1244	GJ_VALIDATE_OFFSET(sc->sc_journal_offset, sc);
1245	joffset = sc->sc_journal_offset;
1246
1247	GJ_DEBUG(2, "Storing %d journal entries on %s at %jd.",
1248	    sc->sc_current_count, pp->name, (intmax_t)joffset);
1249
1250	/*
1251	 * Store 'journal id', so we know to which journal this record belongs.
1252	 */
1253	hdr.jrh_journal_id = sc->sc_journal_id;
1254	/* Could be less than g_journal_record_entries if called due timeout. */
1255	hdr.jrh_nentries = MIN(sc->sc_current_count, g_journal_record_entries);
1256	strlcpy(hdr.jrh_magic, GJ_RECORD_HEADER_MAGIC, sizeof(hdr.jrh_magic));
1257
1258	bioq = &sc->sc_active.jj_queue;
1259	pbp = sc->sc_flush_queue;
1260
1261	fbp = g_alloc_bio();
1262	fbp->bio_parent = NULL;
1263	fbp->bio_cflags = GJ_BIO_JOURNAL;
1264	fbp->bio_offset = -1;
1265	fbp->bio_joffset = joffset;
1266	fbp->bio_length = pp->sectorsize;
1267	fbp->bio_cmd = BIO_WRITE;
1268	fbp->bio_done = g_journal_std_done;
1269	GJQ_INSERT_AFTER(sc->sc_flush_queue, fbp, pbp);
1270	pbp = fbp;
1271	fbp->bio_to = pp;
1272	GJ_LOGREQ(4, fbp, "FLUSH_OUT");
1273	joffset += pp->sectorsize;
1274	sc->sc_flush_count++;
1275	if (sc->sc_flags & GJF_DEVICE_CHECKSUM)
1276		MD5Init(&ctx);
1277
1278	for (i = 0; i < hdr.jrh_nentries; i++) {
1279		bp = sc->sc_current_queue;
1280		KASSERT(bp != NULL, ("NULL bp"));
1281		bp->bio_to = pp;
1282		GJ_LOGREQ(4, bp, "FLUSHED");
1283		sc->sc_current_queue = bp->bio_next;
1284		bp->bio_next = NULL;
1285		sc->sc_current_count--;
1286
1287		/* Add to the header. */
1288		ent = &hdr.jrh_entries[i];
1289		ent->je_offset = bp->bio_offset;
1290		ent->je_joffset = joffset;
1291		ent->je_length = bp->bio_length;
1292		size += ent->je_length;
1293
1294		data = bp->bio_data;
1295		if (sc->sc_flags & GJF_DEVICE_CHECKSUM)
1296			MD5Update(&ctx, data, ent->je_length);
1297		bzero(bp, sizeof(*bp));
1298		bp->bio_cflags = GJ_BIO_JOURNAL;
1299		bp->bio_offset = ent->je_offset;
1300		bp->bio_joffset = ent->je_joffset;
1301		bp->bio_length = ent->je_length;
1302		bp->bio_data = data;
1303		bp->bio_cmd = BIO_WRITE;
1304		bp->bio_done = g_journal_std_done;
1305		GJQ_INSERT_AFTER(sc->sc_flush_queue, bp, pbp);
1306		pbp = bp;
1307		bp->bio_to = pp;
1308		GJ_LOGREQ(4, bp, "FLUSH_OUT");
1309		joffset += bp->bio_length;
1310		sc->sc_flush_count++;
1311
1312		/*
1313		 * Add request to the active sc_journal_queue queue.
1314		 * This is our cache. After journal switch we don't have to
1315		 * read the data from the inactive journal, because we keep
1316		 * it in memory.
1317		 */
1318		g_journal_insert(bioq, ent->je_offset,
1319		    ent->je_offset + ent->je_length, ent->je_joffset, data,
1320		    M_NOWAIT);
1321	}
1322
1323	/*
1324	 * After all requests, store valid header.
1325	 */
1326	data = gj_malloc(pp->sectorsize, M_WAITOK);
1327	if (sc->sc_flags & GJF_DEVICE_CHECKSUM) {
1328		MD5Final(hash, &ctx);
1329		bcopy(hash, hdr.jrh_sum, sizeof(hdr.jrh_sum));
1330	}
1331	g_journal_record_header_encode(&hdr, data);
1332	fbp->bio_data = data;
1333
1334	sc->sc_journal_offset = joffset;
1335
1336	g_journal_check_overflow(sc);
1337}
1338
1339/*
1340 * Flush request finished.
1341 */
1342static void
1343g_journal_flush_done(struct bio *bp)
1344{
1345	struct g_journal_softc *sc;
1346	struct g_consumer *cp;
1347
1348	KASSERT((bp->bio_cflags & GJ_BIO_MASK) == GJ_BIO_JOURNAL,
1349	    ("Invalid bio (%d != %d).", bp->bio_cflags, GJ_BIO_JOURNAL));
1350
1351	cp = bp->bio_from;
1352	sc = cp->geom->softc;
1353	sc->sc_flush_in_progress--;
1354
1355	if (bp->bio_error != 0) {
1356		GJ_LOGREQ(0, bp, "[flush] Error while writting data (error=%d)",
1357		    bp->bio_error);
1358	}
1359	gj_free(bp->bio_data, bp->bio_length);
1360	GJ_LOGREQ(4, bp, "DONE");
1361	g_destroy_bio(bp);
1362}
1363
1364static void g_journal_release_delayed(struct g_journal_softc *sc);
1365
1366static void
1367g_journal_flush_send(struct g_journal_softc *sc)
1368{
1369	struct g_consumer *cp;
1370	struct bio *bioq, *bp, *lbp;
1371
1372	cp = sc->sc_jconsumer;
1373	bioq = lbp = NULL;
1374	while (sc->sc_flush_in_progress < g_journal_parallel_flushes) {
1375		/* Send one flush requests to the active journal. */
1376		bp = GJQ_FIRST(sc->sc_flush_queue);
1377		if (bp != NULL) {
1378			GJQ_REMOVE(sc->sc_flush_queue, bp);
1379			sc->sc_flush_count--;
1380			bp->bio_offset = bp->bio_joffset;
1381			bp->bio_joffset = 0;
1382			sc->sc_flush_in_progress++;
1383			GJQ_INSERT_AFTER(bioq, bp, lbp);
1384			lbp = bp;
1385		}
1386		/* Try to release delayed requests. */
1387		g_journal_release_delayed(sc);
1388		/* If there are no requests to flush, leave. */
1389		if (GJQ_FIRST(sc->sc_flush_queue) == NULL)
1390			break;
1391	}
1392	if (g_journal_do_optimize)
1393		sc->sc_flush_in_progress += g_journal_optimize(bioq);
1394	while ((bp = GJQ_FIRST(bioq)) != NULL) {
1395		GJQ_REMOVE(bioq, bp);
1396		GJ_LOGREQ(3, bp, "Flush request send");
1397		g_io_request(bp, cp);
1398	}
1399}
1400
1401static void
1402g_journal_add_current(struct g_journal_softc *sc, struct bio *bp)
1403{
1404	int n;
1405
1406	GJ_LOGREQ(4, bp, "CURRENT %d", sc->sc_current_count);
1407	n = g_journal_insert_bio(&sc->sc_current_queue, bp, M_WAITOK);
1408	sc->sc_current_count += n;
1409	n = g_journal_optimize(sc->sc_current_queue);
1410	sc->sc_current_count += n;
1411	/*
1412	 * For requests which are added to the current queue we deliver
1413	 * response immediately.
1414	 */
1415	bp->bio_completed = bp->bio_length;
1416	g_io_deliver(bp, 0);
1417	if (sc->sc_current_count >= g_journal_record_entries) {
1418		/*
1419		 * Let's flush one record onto active journal provider.
1420		 */
1421		g_journal_flush(sc);
1422	}
1423}
1424
1425static void
1426g_journal_release_delayed(struct g_journal_softc *sc)
1427{
1428	struct bio *bp;
1429
1430	for (;;) {
1431		/* The flush queue is full, exit. */
1432		if (sc->sc_flush_count >= g_journal_accept_immediately)
1433			return;
1434		bp = bioq_takefirst(&sc->sc_delayed_queue);
1435		if (bp == NULL)
1436			return;
1437		sc->sc_delayed_count--;
1438		g_journal_add_current(sc, bp);
1439	}
1440}
1441
1442/*
1443 * Add I/O request to the current queue. If we have enough requests for one
1444 * journal record we flush them onto active journal provider.
1445 */
1446static void
1447g_journal_add_request(struct g_journal_softc *sc, struct bio *bp)
1448{
1449
1450	/*
1451	 * The flush queue is full, we need to delay the request.
1452	 */
1453	if (sc->sc_delayed_count > 0 ||
1454	    sc->sc_flush_count >= g_journal_accept_immediately) {
1455		GJ_LOGREQ(4, bp, "DELAYED");
1456		bioq_insert_tail(&sc->sc_delayed_queue, bp);
1457		sc->sc_delayed_count++;
1458		return;
1459	}
1460
1461	KASSERT(TAILQ_EMPTY(&sc->sc_delayed_queue.queue),
1462	    ("DELAYED queue not empty."));
1463	g_journal_add_current(sc, bp);
1464}
1465
1466static void g_journal_read_done(struct bio *bp);
1467
1468/*
1469 * Try to find requested data in cache.
1470 */
1471static struct bio *
1472g_journal_read_find(struct bio *head, int sorted, struct bio *pbp, off_t ostart,
1473    off_t oend)
1474{
1475	off_t cstart, cend;
1476	struct bio *bp;
1477
1478	GJQ_FOREACH(head, bp) {
1479		if (bp->bio_offset == -1)
1480			continue;
1481		cstart = MAX(ostart, bp->bio_offset);
1482		cend = MIN(oend, bp->bio_offset + bp->bio_length);
1483		if (cend <= ostart)
1484			continue;
1485		else if (cstart >= oend) {
1486			if (!sorted)
1487				continue;
1488			else {
1489				bp = NULL;
1490				break;
1491			}
1492		}
1493		if (bp->bio_data == NULL)
1494			break;
1495		GJ_DEBUG(3, "READ(%p): (%jd, %jd) (bp=%p)", head, cstart, cend,
1496		    bp);
1497		bcopy(bp->bio_data + cstart - bp->bio_offset,
1498		    pbp->bio_data + cstart - pbp->bio_offset, cend - cstart);
1499		pbp->bio_completed += cend - cstart;
1500		if (pbp->bio_completed == pbp->bio_length) {
1501			/*
1502			 * Cool, the whole request was in cache, deliver happy
1503			 * message.
1504			 */
1505			g_io_deliver(pbp, 0);
1506			return (pbp);
1507		}
1508		break;
1509	}
1510	return (bp);
1511}
1512
1513/*
1514 * Try to find requested data in cache.
1515 */
1516static struct bio *
1517g_journal_read_queue_find(struct bio_queue *head, struct bio *pbp, off_t ostart,
1518    off_t oend)
1519{
1520	off_t cstart, cend;
1521	struct bio *bp;
1522
1523	TAILQ_FOREACH(bp, head, bio_queue) {
1524		cstart = MAX(ostart, bp->bio_offset);
1525		cend = MIN(oend, bp->bio_offset + bp->bio_length);
1526		if (cend <= ostart)
1527			continue;
1528		else if (cstart >= oend)
1529			continue;
1530		KASSERT(bp->bio_data != NULL,
1531		    ("%s: bio_data == NULL", __func__));
1532		GJ_DEBUG(3, "READ(%p): (%jd, %jd) (bp=%p)", head, cstart, cend,
1533		    bp);
1534		bcopy(bp->bio_data + cstart - bp->bio_offset,
1535		    pbp->bio_data + cstart - pbp->bio_offset, cend - cstart);
1536		pbp->bio_completed += cend - cstart;
1537		if (pbp->bio_completed == pbp->bio_length) {
1538			/*
1539			 * Cool, the whole request was in cache, deliver happy
1540			 * message.
1541			 */
1542			g_io_deliver(pbp, 0);
1543			return (pbp);
1544		}
1545		break;
1546	}
1547	return (bp);
1548}
1549
1550/*
1551 * This function is used for colecting data on read.
1552 * The complexity is because parts of the data can be stored in four different
1553 * places:
1554 * - in delayed requests
1555 * - in memory - the data not yet send to the active journal provider
1556 * - in requests which are going to be sent to the active journal
1557 * - in the active journal
1558 * - in the inactive journal
1559 * - in the data provider
1560 */
1561static void
1562g_journal_read(struct g_journal_softc *sc, struct bio *pbp, off_t ostart,
1563    off_t oend)
1564{
1565	struct bio *bp, *nbp, *head;
1566	off_t cstart, cend;
1567	u_int i, sorted = 0;
1568
1569	GJ_DEBUG(3, "READ: (%jd, %jd)", ostart, oend);
1570
1571	cstart = cend = -1;
1572	bp = NULL;
1573	head = NULL;
1574	for (i = 0; i <= 5; i++) {
1575		switch (i) {
1576		case 0:	/* Delayed requests. */
1577			head = NULL;
1578			sorted = 0;
1579			break;
1580		case 1:	/* Not-yet-send data. */
1581			head = sc->sc_current_queue;
1582			sorted = 1;
1583			break;
1584		case 2:	/* In-flight to the active journal. */
1585			head = sc->sc_flush_queue;
1586			sorted = 0;
1587			break;
1588		case 3:	/* Active journal. */
1589			head = sc->sc_active.jj_queue;
1590			sorted = 1;
1591			break;
1592		case 4:	/* Inactive journal. */
1593			/*
1594			 * XXX: Here could be a race with g_journal_lowmem().
1595			 */
1596			head = sc->sc_inactive.jj_queue;
1597			sorted = 1;
1598			break;
1599		case 5:	/* In-flight to the data provider. */
1600			head = sc->sc_copy_queue;
1601			sorted = 0;
1602			break;
1603		default:
1604			panic("gjournal %s: i=%d", __func__, i);
1605		}
1606		if (i == 0)
1607			bp = g_journal_read_queue_find(&sc->sc_delayed_queue.queue, pbp, ostart, oend);
1608		else
1609			bp = g_journal_read_find(head, sorted, pbp, ostart, oend);
1610		if (bp == pbp) { /* Got the whole request. */
1611			GJ_DEBUG(2, "Got the whole request from %u.", i);
1612			return;
1613		} else if (bp != NULL) {
1614			cstart = MAX(ostart, bp->bio_offset);
1615			cend = MIN(oend, bp->bio_offset + bp->bio_length);
1616			GJ_DEBUG(2, "Got part of the request from %u (%jd-%jd).",
1617			    i, (intmax_t)cstart, (intmax_t)cend);
1618			break;
1619		}
1620	}
1621	if (bp != NULL) {
1622		if (bp->bio_data == NULL) {
1623			nbp = g_duplicate_bio(pbp);
1624			nbp->bio_cflags = GJ_BIO_READ;
1625			nbp->bio_data =
1626			    pbp->bio_data + cstart - pbp->bio_offset;
1627			nbp->bio_offset =
1628			    bp->bio_joffset + cstart - bp->bio_offset;
1629			nbp->bio_length = cend - cstart;
1630			nbp->bio_done = g_journal_read_done;
1631			g_io_request(nbp, sc->sc_jconsumer);
1632		}
1633		/*
1634		 * If we don't have the whole request yet, call g_journal_read()
1635		 * recursively.
1636		 */
1637		if (ostart < cstart)
1638			g_journal_read(sc, pbp, ostart, cstart);
1639		if (oend > cend)
1640			g_journal_read(sc, pbp, cend, oend);
1641	} else {
1642		/*
1643		 * No data in memory, no data in journal.
1644		 * Its time for asking data provider.
1645		 */
1646		GJ_DEBUG(3, "READ(data): (%jd, %jd)", ostart, oend);
1647		nbp = g_duplicate_bio(pbp);
1648		nbp->bio_cflags = GJ_BIO_READ;
1649		nbp->bio_data = pbp->bio_data + ostart - pbp->bio_offset;
1650		nbp->bio_offset = ostart;
1651		nbp->bio_length = oend - ostart;
1652		nbp->bio_done = g_journal_read_done;
1653		g_io_request(nbp, sc->sc_dconsumer);
1654		/* We have the whole request, return here. */
1655		return;
1656	}
1657}
1658
1659/*
1660 * Function responsible for handling finished READ requests.
1661 * Actually, g_std_done() could be used here, the only difference is that we
1662 * log error.
1663 */
1664static void
1665g_journal_read_done(struct bio *bp)
1666{
1667	struct bio *pbp;
1668
1669	KASSERT(bp->bio_cflags == GJ_BIO_READ,
1670	    ("Invalid bio (%d != %d).", bp->bio_cflags, GJ_BIO_READ));
1671
1672	pbp = bp->bio_parent;
1673	pbp->bio_inbed++;
1674	pbp->bio_completed += bp->bio_length;
1675
1676	if (bp->bio_error != 0) {
1677		if (pbp->bio_error == 0)
1678			pbp->bio_error = bp->bio_error;
1679		GJ_DEBUG(0, "Error while reading data from %s (error=%d).",
1680		    bp->bio_to->name, bp->bio_error);
1681	}
1682	g_destroy_bio(bp);
1683	if (pbp->bio_children == pbp->bio_inbed &&
1684	    pbp->bio_completed == pbp->bio_length) {
1685		/* We're done. */
1686		g_io_deliver(pbp, 0);
1687	}
1688}
1689
1690/*
1691 * Deactive current journal and active next one.
1692 */
1693static void
1694g_journal_switch(struct g_journal_softc *sc)
1695{
1696	struct g_provider *pp;
1697
1698	if (JEMPTY(sc)) {
1699		GJ_DEBUG(3, "No need for %s switch.", sc->sc_name);
1700		pp = LIST_FIRST(&sc->sc_geom->provider);
1701		if (!(sc->sc_flags & GJF_DEVICE_CLEAN) && pp->acw == 0) {
1702			sc->sc_flags |= GJF_DEVICE_CLEAN;
1703			GJ_DEBUG(1, "Marking %s as clean.", sc->sc_name);
1704			g_journal_metadata_update(sc);
1705		}
1706	} else {
1707		GJ_DEBUG(3, "Switching journal %s.", sc->sc_geom->name);
1708
1709		pp = sc->sc_jprovider;
1710
1711		sc->sc_journal_previous_id = sc->sc_journal_id;
1712
1713		sc->sc_journal_id = sc->sc_journal_next_id;
1714		sc->sc_journal_next_id = arc4random();
1715
1716		GJ_VALIDATE_OFFSET(sc->sc_journal_offset, sc);
1717
1718		g_journal_write_header(sc);
1719
1720		sc->sc_inactive.jj_offset = sc->sc_active.jj_offset;
1721		sc->sc_inactive.jj_queue = sc->sc_active.jj_queue;
1722
1723		sc->sc_active.jj_offset =
1724		    sc->sc_journal_offset - pp->sectorsize;
1725		sc->sc_active.jj_queue = NULL;
1726
1727		/*
1728		 * Switch is done, start copying data from the (now) inactive
1729		 * journal to the data provider.
1730		 */
1731		g_journal_copy_start(sc);
1732	}
1733	mtx_lock(&sc->sc_mtx);
1734	sc->sc_flags &= ~GJF_DEVICE_SWITCH;
1735	mtx_unlock(&sc->sc_mtx);
1736}
1737
1738static void
1739g_journal_initialize(struct g_journal_softc *sc)
1740{
1741
1742	sc->sc_journal_id = arc4random();
1743	sc->sc_journal_next_id = arc4random();
1744	sc->sc_journal_previous_id = sc->sc_journal_id;
1745	sc->sc_journal_offset = sc->sc_jstart;
1746	sc->sc_inactive.jj_offset = sc->sc_jstart;
1747	g_journal_write_header(sc);
1748	sc->sc_active.jj_offset = sc->sc_jstart;
1749}
1750
1751static void
1752g_journal_mark_as_dirty(struct g_journal_softc *sc)
1753{
1754	const struct g_journal_desc *desc;
1755	int i;
1756
1757	GJ_DEBUG(1, "Marking file system %s as dirty.", sc->sc_name);
1758	for (i = 0; (desc = g_journal_filesystems[i]) != NULL; i++)
1759		desc->jd_dirty(sc->sc_dconsumer);
1760}
1761
1762/*
1763 * Function read record header from the given journal.
1764 * It is very simlar to g_read_data(9), but it doesn't allocate memory for bio
1765 * and data on every call.
1766 */
1767static int
1768g_journal_sync_read(struct g_consumer *cp, struct bio *bp, off_t offset,
1769    void *data)
1770{
1771	int error;
1772
1773	bzero(bp, sizeof(*bp));
1774	bp->bio_cmd = BIO_READ;
1775	bp->bio_done = NULL;
1776	bp->bio_offset = offset;
1777	bp->bio_length = cp->provider->sectorsize;
1778	bp->bio_data = data;
1779	g_io_request(bp, cp);
1780	error = biowait(bp, "gjs_read");
1781	return (error);
1782}
1783
1784#if 0
1785/*
1786 * Function is called when we start the journal device and we detect that
1787 * one of the journals was not fully copied.
1788 * The purpose of this function is to read all records headers from journal
1789 * and placed them in the inactive queue, so we can start journal
1790 * synchronization process and the journal provider itself.
1791 * Design decision was taken to not synchronize the whole journal here as it
1792 * can take too much time. Reading headers only and delaying synchronization
1793 * process until after journal provider is started should be the best choice.
1794 */
1795#endif
1796
1797static void
1798g_journal_sync(struct g_journal_softc *sc)
1799{
1800	struct g_journal_record_header rhdr;
1801	struct g_journal_entry *ent;
1802	struct g_journal_header jhdr;
1803	struct g_consumer *cp;
1804	struct bio *bp, *fbp, *tbp;
1805	off_t joffset, offset;
1806	u_char *buf, sum[16];
1807	uint64_t id;
1808	MD5_CTX ctx;
1809	int error, found, i;
1810
1811	found = 0;
1812	fbp = NULL;
1813	cp = sc->sc_jconsumer;
1814	bp = g_alloc_bio();
1815	buf = gj_malloc(cp->provider->sectorsize, M_WAITOK);
1816	offset = joffset = sc->sc_inactive.jj_offset = sc->sc_journal_offset;
1817
1818	GJ_DEBUG(2, "Looking for termination at %jd.", (intmax_t)joffset);
1819
1820	/*
1821	 * Read and decode first journal header.
1822	 */
1823	error = g_journal_sync_read(cp, bp, offset, buf);
1824	if (error != 0) {
1825		GJ_DEBUG(0, "Error while reading journal header from %s.",
1826		    cp->provider->name);
1827		goto end;
1828	}
1829	error = g_journal_header_decode(buf, &jhdr);
1830	if (error != 0) {
1831		GJ_DEBUG(0, "Cannot decode journal header from %s.",
1832		    cp->provider->name);
1833		goto end;
1834	}
1835	id = sc->sc_journal_id;
1836	if (jhdr.jh_journal_id != sc->sc_journal_id) {
1837		GJ_DEBUG(1, "Journal ID mismatch at %jd (0x%08x != 0x%08x).",
1838		    (intmax_t)offset, (u_int)jhdr.jh_journal_id, (u_int)id);
1839		goto end;
1840	}
1841	offset += cp->provider->sectorsize;
1842	id = sc->sc_journal_next_id = jhdr.jh_journal_next_id;
1843
1844	for (;;) {
1845		/*
1846		 * If the biggest record won't fit, look for a record header or
1847		 * journal header from the begining.
1848		 */
1849		GJ_VALIDATE_OFFSET(offset, sc);
1850		error = g_journal_sync_read(cp, bp, offset, buf);
1851		if (error != 0) {
1852			/*
1853			 * Not good. Having an error while reading header
1854			 * means, that we cannot read next headers and in
1855			 * consequence we cannot find termination.
1856			 */
1857			GJ_DEBUG(0,
1858			    "Error while reading record header from %s.",
1859			    cp->provider->name);
1860			break;
1861		}
1862
1863		error = g_journal_record_header_decode(buf, &rhdr);
1864		if (error != 0) {
1865			GJ_DEBUG(2, "Not a record header at %jd (error=%d).",
1866			    (intmax_t)offset, error);
1867			/*
1868			 * This is not a record header.
1869			 * If we are lucky, this is next journal header.
1870			 */
1871			error = g_journal_header_decode(buf, &jhdr);
1872			if (error != 0) {
1873				GJ_DEBUG(1, "Not a journal header at %jd (error=%d).",
1874				    (intmax_t)offset, error);
1875				/*
1876				 * Nope, this is not journal header, which
1877				 * bascially means that journal is not
1878				 * terminated properly.
1879				 */
1880				error = ENOENT;
1881				break;
1882			}
1883			/*
1884			 * Ok. This is header of _some_ journal. Now we need to
1885			 * verify if this is header of the _next_ journal.
1886			 */
1887			if (jhdr.jh_journal_id != id) {
1888				GJ_DEBUG(1, "Journal ID mismatch at %jd "
1889				    "(0x%08x != 0x%08x).", (intmax_t)offset,
1890				    (u_int)jhdr.jh_journal_id, (u_int)id);
1891				error = ENOENT;
1892				break;
1893			}
1894
1895			/* Found termination. */
1896			found++;
1897			GJ_DEBUG(1, "Found termination at %jd (id=0x%08x).",
1898			    (intmax_t)offset, (u_int)id);
1899			sc->sc_active.jj_offset = offset;
1900			sc->sc_journal_offset =
1901			    offset + cp->provider->sectorsize;
1902			sc->sc_journal_id = id;
1903			id = sc->sc_journal_next_id = jhdr.jh_journal_next_id;
1904
1905			while ((tbp = fbp) != NULL) {
1906				fbp = tbp->bio_next;
1907				GJ_LOGREQ(3, tbp, "Adding request.");
1908				g_journal_insert_bio(&sc->sc_inactive.jj_queue,
1909				    tbp, M_WAITOK);
1910			}
1911
1912			/* Skip journal's header. */
1913			offset += cp->provider->sectorsize;
1914			continue;
1915		}
1916
1917		/* Skip record's header. */
1918		offset += cp->provider->sectorsize;
1919
1920		/*
1921		 * Add information about every record entry to the inactive
1922		 * queue.
1923		 */
1924		if (sc->sc_flags & GJF_DEVICE_CHECKSUM)
1925			MD5Init(&ctx);
1926		for (i = 0; i < rhdr.jrh_nentries; i++) {
1927			ent = &rhdr.jrh_entries[i];
1928			GJ_DEBUG(3, "Insert entry: %jd %jd.",
1929			    (intmax_t)ent->je_offset, (intmax_t)ent->je_length);
1930			g_journal_insert(&fbp, ent->je_offset,
1931			    ent->je_offset + ent->je_length, ent->je_joffset,
1932			    NULL, M_WAITOK);
1933			if (sc->sc_flags & GJF_DEVICE_CHECKSUM) {
1934				u_char *buf2;
1935
1936				/*
1937				 * TODO: Should use faster function (like
1938				 *       g_journal_sync_read()).
1939				 */
1940				buf2 = g_read_data(cp, offset, ent->je_length,
1941				    NULL);
1942				if (buf2 == NULL)
1943					GJ_DEBUG(0, "Cannot read data at %jd.",
1944					    (intmax_t)offset);
1945				else {
1946					MD5Update(&ctx, buf2, ent->je_length);
1947					g_free(buf2);
1948				}
1949			}
1950			/* Skip entry's data. */
1951			offset += ent->je_length;
1952		}
1953		if (sc->sc_flags & GJF_DEVICE_CHECKSUM) {
1954			MD5Final(sum, &ctx);
1955			if (bcmp(sum, rhdr.jrh_sum, sizeof(rhdr.jrh_sum)) != 0) {
1956				GJ_DEBUG(0, "MD5 hash mismatch at %jd!",
1957				    (intmax_t)offset);
1958			}
1959		}
1960	}
1961end:
1962	gj_free(bp->bio_data, cp->provider->sectorsize);
1963	g_destroy_bio(bp);
1964
1965	/* Remove bios from unterminated journal. */
1966	while ((tbp = fbp) != NULL) {
1967		fbp = tbp->bio_next;
1968		g_destroy_bio(tbp);
1969	}
1970
1971	if (found < 1 && joffset > 0) {
1972		GJ_DEBUG(0, "Journal on %s is broken/corrupted. Initializing.",
1973		    sc->sc_name);
1974		while ((tbp = sc->sc_inactive.jj_queue) != NULL) {
1975			sc->sc_inactive.jj_queue = tbp->bio_next;
1976			g_destroy_bio(tbp);
1977		}
1978		g_journal_initialize(sc);
1979		g_journal_mark_as_dirty(sc);
1980	} else {
1981		GJ_DEBUG(0, "Journal %s consistent.", sc->sc_name);
1982		g_journal_copy_start(sc);
1983	}
1984}
1985
1986/*
1987 * Wait for requests.
1988 * If we have requests in the current queue, flush them after 3 seconds from the
1989 * last flush. In this way we don't wait forever (or for journal switch) with
1990 * storing not full records on journal.
1991 */
1992static void
1993g_journal_wait(struct g_journal_softc *sc, time_t last_write)
1994{
1995	int error, timeout;
1996
1997	GJ_DEBUG(3, "%s: enter", __func__);
1998	if (sc->sc_current_count == 0) {
1999		if (g_journal_debug < 2)
2000			msleep(sc, &sc->sc_mtx, PRIBIO | PDROP, "gj:work", 0);
2001		else {
2002			/*
2003			 * If we have debug turned on, show number of elements
2004			 * in various queues.
2005			 */
2006			for (;;) {
2007				error = msleep(sc, &sc->sc_mtx, PRIBIO,
2008				    "gj:work", hz * 3);
2009				if (error == 0) {
2010					mtx_unlock(&sc->sc_mtx);
2011					break;
2012				}
2013				GJ_DEBUG(3, "Report: current count=%d",
2014				    sc->sc_current_count);
2015				GJ_DEBUG(3, "Report: flush count=%d",
2016				    sc->sc_flush_count);
2017				GJ_DEBUG(3, "Report: flush in progress=%d",
2018				    sc->sc_flush_in_progress);
2019				GJ_DEBUG(3, "Report: copy in progress=%d",
2020				    sc->sc_copy_in_progress);
2021				GJ_DEBUG(3, "Report: delayed=%d",
2022				    sc->sc_delayed_count);
2023			}
2024		}
2025		GJ_DEBUG(3, "%s: exit 1", __func__);
2026		return;
2027	}
2028
2029	/*
2030	 * Flush even not full records every 3 seconds.
2031	 */
2032	timeout = (last_write + 3 - time_second) * hz;
2033	if (timeout <= 0) {
2034		mtx_unlock(&sc->sc_mtx);
2035		g_journal_flush(sc);
2036		g_journal_flush_send(sc);
2037		GJ_DEBUG(3, "%s: exit 2", __func__);
2038		return;
2039	}
2040	error = msleep(sc, &sc->sc_mtx, PRIBIO | PDROP, "gj:work", timeout);
2041	if (error == EWOULDBLOCK)
2042		g_journal_flush_send(sc);
2043	GJ_DEBUG(3, "%s: exit 3", __func__);
2044}
2045
2046/*
2047 * Worker thread.
2048 */
2049static void
2050g_journal_worker(void *arg)
2051{
2052	struct g_journal_softc *sc;
2053	struct g_geom *gp;
2054	struct g_provider *pp;
2055	struct bio *bp;
2056	time_t last_write;
2057	int type;
2058
2059	mtx_lock_spin(&sched_lock);
2060	sched_prio(curthread, PRIBIO);
2061	mtx_unlock_spin(&sched_lock);
2062
2063	sc = arg;
2064	type = 0;	/* gcc */
2065
2066	if (sc->sc_flags & GJF_DEVICE_CLEAN) {
2067		GJ_DEBUG(0, "Journal %s clean.", sc->sc_name);
2068		g_journal_initialize(sc);
2069	} else {
2070		g_journal_sync(sc);
2071	}
2072	/*
2073	 * Check if we can use BIO_FLUSH.
2074	 */
2075	sc->sc_bio_flush = 0;
2076	if (g_io_flush(sc->sc_jconsumer) == 0) {
2077		sc->sc_bio_flush |= GJ_FLUSH_JOURNAL;
2078		GJ_DEBUG(1, "BIO_FLUSH supported by %s.",
2079		    sc->sc_jconsumer->provider->name);
2080	} else {
2081		GJ_DEBUG(0, "BIO_FLUSH not supported by %s.",
2082		    sc->sc_jconsumer->provider->name);
2083	}
2084	if (sc->sc_jconsumer != sc->sc_dconsumer) {
2085		if (g_io_flush(sc->sc_dconsumer) == 0) {
2086			sc->sc_bio_flush |= GJ_FLUSH_DATA;
2087			GJ_DEBUG(1, "BIO_FLUSH supported by %s.",
2088			    sc->sc_dconsumer->provider->name);
2089		} else {
2090			GJ_DEBUG(0, "BIO_FLUSH not supported by %s.",
2091			    sc->sc_dconsumer->provider->name);
2092		}
2093	}
2094
2095	gp = sc->sc_geom;
2096	g_topology_lock();
2097	pp = g_new_providerf(gp, "%s.journal", sc->sc_name);
2098	KASSERT(pp != NULL, ("Cannot create %s.journal.", sc->sc_name));
2099	pp->mediasize = sc->sc_mediasize;
2100	/*
2101	 * There could be a problem when data provider and journal providers
2102	 * have different sectorsize, but such scenario is prevented on journal
2103	 * creation.
2104	 */
2105	pp->sectorsize = sc->sc_sectorsize;
2106	g_error_provider(pp, 0);
2107	g_topology_unlock();
2108	last_write = time_second;
2109
2110	for (;;) {
2111		/* Get first request from the queue. */
2112		mtx_lock(&sc->sc_mtx);
2113		bp = bioq_first(&sc->sc_back_queue);
2114		if (bp != NULL)
2115			type = (bp->bio_cflags & GJ_BIO_MASK);
2116		if (bp == NULL) {
2117			bp = bioq_first(&sc->sc_regular_queue);
2118			if (bp != NULL)
2119				type = GJ_BIO_REGULAR;
2120		}
2121		if (bp == NULL) {
2122try_switch:
2123			if ((sc->sc_flags & GJF_DEVICE_SWITCH) ||
2124			    (sc->sc_flags & GJF_DEVICE_DESTROY)) {
2125				if (sc->sc_current_count > 0) {
2126					mtx_unlock(&sc->sc_mtx);
2127					g_journal_flush(sc);
2128					g_journal_flush_send(sc);
2129					continue;
2130				}
2131				if (sc->sc_flush_in_progress > 0)
2132					goto sleep;
2133				if (sc->sc_copy_in_progress > 0)
2134					goto sleep;
2135			}
2136			if (sc->sc_flags & GJF_DEVICE_SWITCH) {
2137				mtx_unlock(&sc->sc_mtx);
2138				g_journal_switch(sc);
2139				wakeup(&sc->sc_journal_copying);
2140				continue;
2141			}
2142			if (sc->sc_flags & GJF_DEVICE_DESTROY) {
2143				GJ_DEBUG(1, "Shutting down worker "
2144				    "thread for %s.", gp->name);
2145				sc->sc_worker = NULL;
2146				wakeup(&sc->sc_worker);
2147				mtx_unlock(&sc->sc_mtx);
2148				kthread_exit(0);
2149			}
2150sleep:
2151			g_journal_wait(sc, last_write);
2152			continue;
2153		}
2154		/*
2155		 * If we're in switch process, we need to delay all new
2156		 * write requests until its done.
2157		 */
2158		if ((sc->sc_flags & GJF_DEVICE_SWITCH) &&
2159		    type == GJ_BIO_REGULAR && bp->bio_cmd == BIO_WRITE) {
2160			GJ_LOGREQ(2, bp, "WRITE on SWITCH");
2161			goto try_switch;
2162		}
2163		if (type == GJ_BIO_REGULAR)
2164			bioq_remove(&sc->sc_regular_queue, bp);
2165		else
2166			bioq_remove(&sc->sc_back_queue, bp);
2167		mtx_unlock(&sc->sc_mtx);
2168		switch (type) {
2169		case GJ_BIO_REGULAR:
2170			/* Regular request. */
2171			switch (bp->bio_cmd) {
2172			case BIO_READ:
2173				g_journal_read(sc, bp, bp->bio_offset,
2174				    bp->bio_offset + bp->bio_length);
2175				break;
2176			case BIO_WRITE:
2177				last_write = time_second;
2178				g_journal_add_request(sc, bp);
2179				g_journal_flush_send(sc);
2180				break;
2181			default:
2182				panic("Invalid bio_cmd (%d).", bp->bio_cmd);
2183			}
2184			break;
2185		case GJ_BIO_COPY:
2186			switch (bp->bio_cmd) {
2187			case BIO_READ:
2188				if (g_journal_copy_read_done(bp))
2189					g_journal_copy_send(sc);
2190				break;
2191			case BIO_WRITE:
2192				g_journal_copy_write_done(bp);
2193				g_journal_copy_send(sc);
2194				break;
2195			default:
2196				panic("Invalid bio_cmd (%d).", bp->bio_cmd);
2197			}
2198			break;
2199		case GJ_BIO_JOURNAL:
2200			g_journal_flush_done(bp);
2201			g_journal_flush_send(sc);
2202			break;
2203		case GJ_BIO_READ:
2204		default:
2205			panic("Invalid bio (%d).", type);
2206		}
2207	}
2208}
2209
2210static void
2211g_journal_destroy_event(void *arg, int flags __unused)
2212{
2213	struct g_journal_softc *sc;
2214
2215	g_topology_assert();
2216	sc = arg;
2217	g_journal_destroy(sc);
2218}
2219
2220static void
2221g_journal_timeout(void *arg)
2222{
2223	struct g_journal_softc *sc;
2224
2225	sc = arg;
2226	GJ_DEBUG(0, "Timeout. Journal %s cannot be completed.",
2227	    sc->sc_geom->name);
2228	g_post_event(g_journal_destroy_event, sc, M_NOWAIT, NULL);
2229}
2230
2231static struct g_geom *
2232g_journal_create(struct g_class *mp, struct g_provider *pp,
2233    const struct g_journal_metadata *md)
2234{
2235	struct g_journal_softc *sc;
2236	struct g_geom *gp;
2237	struct g_consumer *cp;
2238	int error;
2239
2240	sc = NULL;	/* gcc */
2241
2242	g_topology_assert();
2243	/*
2244	 * There are two possibilities:
2245	 * 1. Data and both journals are on the same provider.
2246	 * 2. Data and journals are all on separated providers.
2247	 */
2248	/* Look for journal device with the same ID. */
2249	LIST_FOREACH(gp, &mp->geom, geom) {
2250		sc = gp->softc;
2251		if (sc == NULL)
2252			continue;
2253		if (sc->sc_id == md->md_id)
2254			break;
2255	}
2256	if (gp == NULL)
2257		sc = NULL;
2258	else if (sc != NULL && (sc->sc_type & md->md_type) != 0) {
2259		GJ_DEBUG(1, "Journal device %u already configured.", sc->sc_id);
2260		return (NULL);
2261	}
2262	if (md->md_type == 0 || (md->md_type & ~GJ_TYPE_COMPLETE) != 0) {
2263		GJ_DEBUG(0, "Invalid type on %s.", pp->name);
2264		return (NULL);
2265	}
2266	if (md->md_type & GJ_TYPE_DATA) {
2267		GJ_DEBUG(0, "Journal %u: %s contains data.", md->md_id,
2268		    pp->name);
2269	}
2270	if (md->md_type & GJ_TYPE_JOURNAL) {
2271		GJ_DEBUG(0, "Journal %u: %s contains journal.", md->md_id,
2272		    pp->name);
2273	}
2274
2275	if (sc == NULL) {
2276		/* Action geom. */
2277		sc = malloc(sizeof(*sc), M_JOURNAL, M_WAITOK | M_ZERO);
2278		sc->sc_id = md->md_id;
2279		sc->sc_type = 0;
2280		sc->sc_flags = 0;
2281		sc->sc_worker = NULL;
2282
2283		gp = g_new_geomf(mp, "gjournal %u", sc->sc_id);
2284		gp->start = g_journal_start;
2285		gp->orphan = g_journal_orphan;
2286		gp->access = g_journal_access;
2287		gp->softc = sc;
2288		sc->sc_geom = gp;
2289
2290		mtx_init(&sc->sc_mtx, "gjournal", NULL, MTX_DEF);
2291
2292		bioq_init(&sc->sc_back_queue);
2293		bioq_init(&sc->sc_regular_queue);
2294		bioq_init(&sc->sc_delayed_queue);
2295		sc->sc_delayed_count = 0;
2296		sc->sc_current_queue = NULL;
2297		sc->sc_current_count = 0;
2298		sc->sc_flush_queue = NULL;
2299		sc->sc_flush_count = 0;
2300		sc->sc_flush_in_progress = 0;
2301		sc->sc_copy_queue = NULL;
2302		sc->sc_copy_in_progress = 0;
2303		sc->sc_inactive.jj_queue = NULL;
2304		sc->sc_active.jj_queue = NULL;
2305
2306		callout_init(&sc->sc_callout, CALLOUT_MPSAFE);
2307		if (md->md_type != GJ_TYPE_COMPLETE) {
2308			/*
2309			 * Journal and data are on separate providers.
2310			 * At this point we have only one of them.
2311			 * We setup a timeout in case the other part will not
2312			 * appear, so we won't wait forever.
2313			 */
2314			callout_reset(&sc->sc_callout, 5 * hz,
2315			    g_journal_timeout, sc);
2316		}
2317	}
2318
2319	/* Remember type of the data provider. */
2320	if (md->md_type & GJ_TYPE_DATA)
2321		sc->sc_orig_type = md->md_type;
2322	sc->sc_type |= md->md_type;
2323	cp = NULL;
2324
2325	if (md->md_type & GJ_TYPE_DATA) {
2326		if (md->md_flags & GJ_FLAG_CLEAN)
2327			sc->sc_flags |= GJF_DEVICE_CLEAN;
2328		if (md->md_flags & GJ_FLAG_CHECKSUM)
2329			sc->sc_flags |= GJF_DEVICE_CHECKSUM;
2330		cp = g_new_consumer(gp);
2331		error = g_attach(cp, pp);
2332		KASSERT(error == 0, ("Cannot attach to %s (error=%d).",
2333		    pp->name, error));
2334		error = g_access(cp, 1, 1, 1);
2335		if (error != 0) {
2336			GJ_DEBUG(0, "Cannot access %s (error=%d).", pp->name,
2337			    error);
2338			g_journal_destroy(sc);
2339			return (NULL);
2340		}
2341		sc->sc_dconsumer = cp;
2342		sc->sc_mediasize = pp->mediasize - pp->sectorsize;
2343		sc->sc_sectorsize = pp->sectorsize;
2344		sc->sc_jstart = md->md_jstart;
2345		sc->sc_jend = md->md_jend;
2346		if (md->md_provider[0] != '\0')
2347			sc->sc_flags |= GJF_DEVICE_HARDCODED;
2348		sc->sc_journal_offset = md->md_joffset;
2349		sc->sc_journal_id = md->md_jid;
2350		sc->sc_journal_previous_id = md->md_jid;
2351	}
2352	if (md->md_type & GJ_TYPE_JOURNAL) {
2353		if (cp == NULL) {
2354			cp = g_new_consumer(gp);
2355			error = g_attach(cp, pp);
2356			KASSERT(error == 0, ("Cannot attach to %s (error=%d).",
2357			    pp->name, error));
2358			error = g_access(cp, 1, 1, 1);
2359			if (error != 0) {
2360				GJ_DEBUG(0, "Cannot access %s (error=%d).",
2361				    pp->name, error);
2362				g_journal_destroy(sc);
2363				return (NULL);
2364			}
2365		} else {
2366			/*
2367			 * Journal is on the same provider as data, which means
2368			 * that data provider ends where journal starts.
2369			 */
2370			sc->sc_mediasize = md->md_jstart;
2371		}
2372		sc->sc_jconsumer = cp;
2373	}
2374
2375	if ((sc->sc_type & GJ_TYPE_COMPLETE) != GJ_TYPE_COMPLETE) {
2376		/* Journal is not complete yet. */
2377		return (gp);
2378	} else {
2379		/* Journal complete, cancel timeout. */
2380		callout_drain(&sc->sc_callout);
2381	}
2382
2383	error = kthread_create(g_journal_worker, sc, &sc->sc_worker, 0, 0,
2384	    "g_journal %s", sc->sc_name);
2385	if (error != 0) {
2386		GJ_DEBUG(0, "Cannot create worker thread for %s.journal.",
2387		    sc->sc_name);
2388		g_journal_destroy(sc);
2389		return (NULL);
2390	}
2391
2392	return (gp);
2393}
2394
2395static void
2396g_journal_destroy_consumer(void *arg, int flags __unused)
2397{
2398	struct g_consumer *cp;
2399
2400	g_topology_assert();
2401	cp = arg;
2402	g_detach(cp);
2403	g_destroy_consumer(cp);
2404}
2405
2406static int
2407g_journal_destroy(struct g_journal_softc *sc)
2408{
2409	struct g_geom *gp;
2410	struct g_provider *pp;
2411	struct g_consumer *cp;
2412
2413	g_topology_assert();
2414
2415	if (sc == NULL)
2416		return (ENXIO);
2417
2418	gp = sc->sc_geom;
2419	pp = LIST_FIRST(&gp->provider);
2420	if (pp != NULL) {
2421		if (pp->acr != 0 || pp->acw != 0 || pp->ace != 0) {
2422			GJ_DEBUG(1, "Device %s is still open (r%dw%de%d).",
2423			    pp->name, pp->acr, pp->acw, pp->ace);
2424			return (EBUSY);
2425		}
2426		g_error_provider(pp, ENXIO);
2427
2428		g_journal_flush(sc);
2429		g_journal_flush_send(sc);
2430		g_journal_switch(sc);
2431	}
2432
2433	sc->sc_flags |= (GJF_DEVICE_DESTROY | GJF_DEVICE_CLEAN);
2434
2435	g_topology_unlock();
2436	callout_drain(&sc->sc_callout);
2437	mtx_lock(&sc->sc_mtx);
2438	wakeup(sc);
2439	while (sc->sc_worker != NULL)
2440		msleep(&sc->sc_worker, &sc->sc_mtx, PRIBIO, "gj:destroy", 0);
2441	mtx_unlock(&sc->sc_mtx);
2442
2443	if (pp != NULL) {
2444		GJ_DEBUG(1, "Marking %s as clean.", sc->sc_name);
2445		g_journal_metadata_update(sc);
2446		g_topology_lock();
2447		pp->flags |= G_PF_WITHER;
2448		g_orphan_provider(pp, ENXIO);
2449	} else {
2450		g_topology_lock();
2451	}
2452	mtx_destroy(&sc->sc_mtx);
2453
2454	if (sc->sc_current_count != 0) {
2455		GJ_DEBUG(0, "Warning! Number of current requests %d.",
2456		    sc->sc_current_count);
2457	}
2458
2459	LIST_FOREACH(cp, &gp->consumer, consumer) {
2460		if (cp->acr + cp->acw + cp->ace > 0)
2461			g_access(cp, -1, -1, -1);
2462		/*
2463		 * We keep all consumers open for writting, so if I'll detach
2464		 * and destroy consumer here, I'll get providers for taste, so
2465		 * journal will be started again.
2466		 * Sending an event here, prevents this from happening.
2467		 */
2468		g_post_event(g_journal_destroy_consumer, cp, M_WAITOK, NULL);
2469	}
2470	gp->softc = NULL;
2471	g_wither_geom(gp, ENXIO);
2472	free(sc, M_JOURNAL);
2473	return (0);
2474}
2475
2476static void
2477g_journal_taste_orphan(struct g_consumer *cp)
2478{
2479
2480	KASSERT(1 == 0, ("%s called while tasting %s.", __func__,
2481	    cp->provider->name));
2482}
2483
2484static struct g_geom *
2485g_journal_taste(struct g_class *mp, struct g_provider *pp, int flags __unused)
2486{
2487	struct g_journal_metadata md;
2488	struct g_consumer *cp;
2489	struct g_geom *gp;
2490	int error;
2491
2492	g_topology_assert();
2493	g_trace(G_T_TOPOLOGY, "%s(%s, %s)", __func__, mp->name, pp->name);
2494	GJ_DEBUG(2, "Tasting %s.", pp->name);
2495	if (pp->geom->class == mp)
2496		return (NULL);
2497
2498	gp = g_new_geomf(mp, "journal:taste");
2499	/* This orphan function should be never called. */
2500	gp->orphan = g_journal_taste_orphan;
2501	cp = g_new_consumer(gp);
2502	g_attach(cp, pp);
2503	error = g_journal_metadata_read(cp, &md);
2504	g_detach(cp);
2505	g_destroy_consumer(cp);
2506	g_destroy_geom(gp);
2507	if (error != 0)
2508		return (NULL);
2509	gp = NULL;
2510
2511	if (md.md_provider[0] != '\0' && strcmp(md.md_provider, pp->name) != 0)
2512		return (NULL);
2513	if (md.md_provsize != 0 && md.md_provsize != pp->mediasize)
2514		return (NULL);
2515	if (g_journal_debug >= 2)
2516		journal_metadata_dump(&md);
2517
2518	gp = g_journal_create(mp, pp, &md);
2519	return (gp);
2520}
2521
2522static struct g_journal_softc *
2523g_journal_find_device(struct g_class *mp, const char *name)
2524{
2525	struct g_journal_softc *sc;
2526	struct g_geom *gp;
2527	struct g_provider *pp;
2528
2529	if (strncmp(name, "/dev/", 5) == 0)
2530		name += 5;
2531	LIST_FOREACH(gp, &mp->geom, geom) {
2532		sc = gp->softc;
2533		if (sc == NULL)
2534			continue;
2535		if (sc->sc_flags & GJF_DEVICE_DESTROY)
2536			continue;
2537		if ((sc->sc_type & GJ_TYPE_COMPLETE) != GJ_TYPE_COMPLETE)
2538			continue;
2539		pp = LIST_FIRST(&gp->provider);
2540		if (strcmp(sc->sc_name, name) == 0)
2541			return (sc);
2542		if (pp != NULL && strcmp(pp->name, name) == 0)
2543			return (sc);
2544	}
2545	return (NULL);
2546}
2547
2548static void
2549g_journal_ctl_destroy(struct gctl_req *req, struct g_class *mp)
2550{
2551	struct g_journal_softc *sc;
2552	const char *name;
2553	char param[16];
2554	int *nargs;
2555	int error, i;
2556
2557	g_topology_assert();
2558
2559	nargs = gctl_get_paraml(req, "nargs", sizeof(*nargs));
2560	if (nargs == NULL) {
2561		gctl_error(req, "No '%s' argument.", "nargs");
2562		return;
2563	}
2564	if (*nargs <= 0) {
2565		gctl_error(req, "Missing device(s).");
2566		return;
2567	}
2568
2569	for (i = 0; i < *nargs; i++) {
2570		snprintf(param, sizeof(param), "arg%d", i);
2571		name = gctl_get_asciiparam(req, param);
2572		if (name == NULL) {
2573			gctl_error(req, "No 'arg%d' argument.", i);
2574			return;
2575		}
2576		sc = g_journal_find_device(mp, name);
2577		if (sc == NULL) {
2578			gctl_error(req, "No such device: %s.", name);
2579			return;
2580		}
2581		error = g_journal_destroy(sc);
2582		if (error != 0) {
2583			gctl_error(req, "Cannot destroy device %s (error=%d).",
2584			    LIST_FIRST(&sc->sc_geom->provider)->name, error);
2585			return;
2586		}
2587	}
2588}
2589
2590static void
2591g_journal_ctl_sync(struct gctl_req *req __unused, struct g_class *mp __unused)
2592{
2593
2594	g_topology_assert();
2595	g_topology_unlock();
2596	g_journal_sync_requested++;
2597	wakeup(&g_journal_switcher_state);
2598	while (g_journal_sync_requested > 0)
2599		tsleep(&g_journal_sync_requested, PRIBIO, "j:sreq", hz / 2);
2600	g_topology_lock();
2601}
2602
2603static void
2604g_journal_config(struct gctl_req *req, struct g_class *mp, const char *verb)
2605{
2606	uint32_t *version;
2607
2608	g_topology_assert();
2609
2610	version = gctl_get_paraml(req, "version", sizeof(*version));
2611	if (version == NULL) {
2612		gctl_error(req, "No '%s' argument.", "version");
2613		return;
2614	}
2615	if (*version != G_JOURNAL_VERSION) {
2616		gctl_error(req, "Userland and kernel parts are out of sync.");
2617		return;
2618	}
2619
2620	if (strcmp(verb, "destroy") == 0 || strcmp(verb, "stop") == 0) {
2621		g_journal_ctl_destroy(req, mp);
2622		return;
2623	} else if (strcmp(verb, "sync") == 0) {
2624		g_journal_ctl_sync(req, mp);
2625		return;
2626	}
2627
2628	gctl_error(req, "Unknown verb.");
2629}
2630
2631static void
2632g_journal_dumpconf(struct sbuf *sb, const char *indent, struct g_geom *gp,
2633    struct g_consumer *cp, struct g_provider *pp)
2634{
2635	struct g_journal_softc *sc;
2636
2637	g_topology_assert();
2638
2639	sc = gp->softc;
2640	if (sc == NULL)
2641		return;
2642	if (pp != NULL) {
2643		/* Nothing here. */
2644	} else if (cp != NULL) {
2645		int first = 1;
2646
2647		sbuf_printf(sb, "%s<Role>", indent);
2648		if (cp == sc->sc_dconsumer) {
2649			sbuf_printf(sb, "Data");
2650			first = 0;
2651		}
2652		if (cp == sc->sc_jconsumer) {
2653			if (!first)
2654				sbuf_printf(sb, ",");
2655			sbuf_printf(sb, "Journal");
2656		}
2657		sbuf_printf(sb, "</Role>\n");
2658		if (cp == sc->sc_jconsumer) {
2659			sbuf_printf(sb, "<Jstart>%jd</Jstart>",
2660			    (intmax_t)sc->sc_jstart);
2661			sbuf_printf(sb, "<Jend>%jd</Jend>",
2662			    (intmax_t)sc->sc_jend);
2663		}
2664	} else {
2665		sbuf_printf(sb, "%s<ID>%u</ID>\n", indent, (u_int)sc->sc_id);
2666	}
2667}
2668
2669static eventhandler_tag g_journal_event_shutdown = NULL;
2670static eventhandler_tag g_journal_event_lowmem = NULL;
2671
2672static void
2673g_journal_shutdown(void *arg, int howto __unused)
2674{
2675	struct g_class *mp;
2676	struct g_geom *gp, *gp2;
2677
2678	if (panicstr != NULL)
2679		return;
2680	mp = arg;
2681	DROP_GIANT();
2682	g_topology_lock();
2683	LIST_FOREACH_SAFE(gp, &mp->geom, geom, gp2) {
2684		if (gp->softc == NULL)
2685			continue;
2686		GJ_DEBUG(0, "Shutting down geom %s.", gp->name);
2687		g_journal_destroy(gp->softc);
2688	}
2689	g_topology_unlock();
2690	PICKUP_GIANT();
2691}
2692
2693/*
2694 * Free cached requests from inactive queue in case of low memory.
2695 * We free GJ_FREE_AT_ONCE elements at once.
2696 */
2697#define	GJ_FREE_AT_ONCE	4
2698static void
2699g_journal_lowmem(void *arg, int howto __unused)
2700{
2701	struct g_journal_softc *sc;
2702	struct g_class *mp;
2703	struct g_geom *gp;
2704	struct bio *bp;
2705	u_int nfree = GJ_FREE_AT_ONCE;
2706
2707	g_journal_stats_low_mem++;
2708	mp = arg;
2709	DROP_GIANT();
2710	g_topology_lock();
2711	LIST_FOREACH(gp, &mp->geom, geom) {
2712		sc = gp->softc;
2713		if (sc == NULL || (sc->sc_flags & GJF_DEVICE_DESTROY))
2714			continue;
2715		mtx_lock(&sc->sc_mtx);
2716		for (bp = sc->sc_inactive.jj_queue; nfree > 0 && bp != NULL;
2717		    nfree--, bp = bp->bio_next) {
2718			/*
2719			 * This is safe to free the bio_data, because:
2720			 * 1. If bio_data is NULL it will be read from the
2721			 *    inactive journal.
2722			 * 2. If bp is sent down, it is first removed from the
2723			 *    inactive queue, so it's impossible to free the
2724			 *    data from under in-flight bio.
2725			 * On the other hand, freeing elements from the active
2726			 * queue, is not safe.
2727			 */
2728			if (bp->bio_data != NULL) {
2729				GJ_DEBUG(2, "Freeing data from %s.",
2730				    sc->sc_name);
2731				gj_free(bp->bio_data, bp->bio_length);
2732				bp->bio_data = NULL;
2733			}
2734		}
2735		mtx_unlock(&sc->sc_mtx);
2736		if (nfree == 0)
2737			break;
2738	}
2739	g_topology_unlock();
2740	PICKUP_GIANT();
2741}
2742
2743static void g_journal_switcher(void *arg);
2744
2745static void
2746g_journal_init(struct g_class *mp)
2747{
2748	int error;
2749
2750	/* Pick a conservative value if provided value sucks. */
2751	if (g_journal_cache_divisor <= 0 ||
2752	    (vm_kmem_size / g_journal_cache_divisor == 0)) {
2753		g_journal_cache_divisor = 5;
2754	}
2755	if (g_journal_cache_limit > 0) {
2756		g_journal_cache_limit = vm_kmem_size / g_journal_cache_divisor;
2757		g_journal_cache_low =
2758		    (g_journal_cache_limit / 100) * g_journal_cache_switch;
2759	}
2760	g_journal_event_shutdown = EVENTHANDLER_REGISTER(shutdown_post_sync,
2761	    g_journal_shutdown, mp, EVENTHANDLER_PRI_FIRST);
2762	if (g_journal_event_shutdown == NULL)
2763		GJ_DEBUG(0, "Warning! Cannot register shutdown event.");
2764	g_journal_event_lowmem = EVENTHANDLER_REGISTER(vm_lowmem,
2765	    g_journal_lowmem, mp, EVENTHANDLER_PRI_FIRST);
2766	if (g_journal_event_lowmem == NULL)
2767		GJ_DEBUG(0, "Warning! Cannot register lowmem event.");
2768	error = kthread_create(g_journal_switcher, mp, NULL, 0, 0,
2769	    "g_journal switcher");
2770	KASSERT(error == 0, ("Cannot create switcher thread."));
2771}
2772
2773static void
2774g_journal_fini(struct g_class *mp)
2775{
2776
2777	if (g_journal_event_shutdown != NULL) {
2778		EVENTHANDLER_DEREGISTER(shutdown_post_sync,
2779		    g_journal_event_shutdown);
2780	}
2781	if (g_journal_event_lowmem != NULL)
2782		EVENTHANDLER_DEREGISTER(vm_lowmem, g_journal_event_lowmem);
2783	g_journal_switcher_state = GJ_SWITCHER_DIE;
2784	wakeup(&g_journal_switcher_state);
2785	while (g_journal_switcher_state != GJ_SWITCHER_DIED)
2786		tsleep(&g_journal_switcher_state, PRIBIO, "jfini:wait", hz / 5);
2787	GJ_DEBUG(1, "Switcher died.");
2788}
2789
2790DECLARE_GEOM_CLASS(g_journal_class, g_journal);
2791
2792static const struct g_journal_desc *
2793g_journal_find_desc(const char *fstype)
2794{
2795	const struct g_journal_desc *desc;
2796	int i;
2797
2798	for (desc = g_journal_filesystems[i = 0]; desc != NULL;
2799	     desc = g_journal_filesystems[++i]) {
2800		if (strcmp(desc->jd_fstype, fstype) == 0)
2801			break;
2802	}
2803	return (desc);
2804}
2805
2806static void
2807g_journal_switch_wait(struct g_journal_softc *sc)
2808{
2809	struct bintime bt;
2810
2811	mtx_assert(&sc->sc_mtx, MA_OWNED);
2812	if (g_journal_debug >= 2) {
2813		if (sc->sc_flush_in_progress > 0) {
2814			GJ_DEBUG(2, "%d requests flushing.",
2815			    sc->sc_flush_in_progress);
2816		}
2817		if (sc->sc_copy_in_progress > 0) {
2818			GJ_DEBUG(2, "%d requests copying.",
2819			    sc->sc_copy_in_progress);
2820		}
2821		if (sc->sc_flush_count > 0) {
2822			GJ_DEBUG(2, "%d requests to flush.",
2823			    sc->sc_flush_count);
2824		}
2825		if (sc->sc_delayed_count > 0) {
2826			GJ_DEBUG(2, "%d requests delayed.",
2827			    sc->sc_delayed_count);
2828		}
2829	}
2830	g_journal_stats_switches++;
2831	if (sc->sc_copy_in_progress > 0)
2832		g_journal_stats_wait_for_copy++;
2833	GJ_TIMER_START(1, &bt);
2834	sc->sc_flags &= ~GJF_DEVICE_BEFORE_SWITCH;
2835	sc->sc_flags |= GJF_DEVICE_SWITCH;
2836	wakeup(sc);
2837	while (sc->sc_flags & GJF_DEVICE_SWITCH) {
2838		msleep(&sc->sc_journal_copying, &sc->sc_mtx, PRIBIO,
2839		    "gj:switch", 0);
2840	}
2841	GJ_TIMER_STOP(1, &bt, "Switch time of %s", sc->sc_name);
2842}
2843
2844static void
2845g_journal_do_switch(struct g_class *classp, struct thread *td)
2846{
2847	struct g_journal_softc *sc;
2848	const struct g_journal_desc *desc;
2849	struct g_geom *gp;
2850	struct mount *mp;
2851	struct bintime bt;
2852	char *mountpoint;
2853	int error, vfslocked;
2854
2855	DROP_GIANT();
2856	g_topology_lock();
2857	LIST_FOREACH(gp, &classp->geom, geom) {
2858		sc = gp->softc;
2859		if (sc == NULL)
2860			continue;
2861		if (sc->sc_flags & GJF_DEVICE_DESTROY)
2862			continue;
2863		if ((sc->sc_type & GJ_TYPE_COMPLETE) != GJ_TYPE_COMPLETE)
2864			continue;
2865		mtx_lock(&sc->sc_mtx);
2866		sc->sc_flags |= GJF_DEVICE_BEFORE_SWITCH;
2867		mtx_unlock(&sc->sc_mtx);
2868	}
2869	g_topology_unlock();
2870	PICKUP_GIANT();
2871
2872	mtx_lock(&mountlist_mtx);
2873	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
2874		if (mp->mnt_gjprovider == NULL)
2875			continue;
2876		if (mp->mnt_flag & MNT_RDONLY)
2877			continue;
2878		desc = g_journal_find_desc(mp->mnt_stat.f_fstypename);
2879		if (desc == NULL)
2880			continue;
2881		if (vfs_busy(mp, LK_NOWAIT, &mountlist_mtx, td))
2882			continue;
2883		/* mtx_unlock(&mountlist_mtx) was done inside vfs_busy() */
2884
2885		DROP_GIANT();
2886		g_topology_lock();
2887		sc = g_journal_find_device(classp, mp->mnt_gjprovider);
2888		g_topology_unlock();
2889		PICKUP_GIANT();
2890
2891		if (sc == NULL) {
2892			GJ_DEBUG(0, "Cannot find journal geom for %s.",
2893			    mp->mnt_gjprovider);
2894			goto next;
2895		} else if (JEMPTY(sc)) {
2896			mtx_lock(&sc->sc_mtx);
2897			sc->sc_flags &= ~GJF_DEVICE_BEFORE_SWITCH;
2898			mtx_unlock(&sc->sc_mtx);
2899			GJ_DEBUG(3, "No need for %s switch.", sc->sc_name);
2900			goto next;
2901		}
2902
2903		mountpoint = mp->mnt_stat.f_mntonname;
2904
2905		vfslocked = VFS_LOCK_GIANT(mp);
2906
2907		error = vn_start_write(NULL, &mp, V_WAIT);
2908		if (error != 0) {
2909			VFS_UNLOCK_GIANT(vfslocked);
2910			GJ_DEBUG(0, "vn_start_write(%s) failed (error=%d).",
2911			    mountpoint, error);
2912			goto next;
2913		}
2914
2915		MNT_ILOCK(mp);
2916		mp->mnt_noasync++;
2917		mp->mnt_kern_flag &= ~MNTK_ASYNC;
2918		MNT_IUNLOCK(mp);
2919
2920		GJ_TIMER_START(1, &bt);
2921		vfs_msync(mp, MNT_NOWAIT);
2922		GJ_TIMER_STOP(1, &bt, "Msync time of %s", mountpoint);
2923
2924		GJ_TIMER_START(1, &bt);
2925		error = VFS_SYNC(mp, MNT_NOWAIT, curthread);
2926		if (error == 0)
2927			GJ_TIMER_STOP(1, &bt, "Sync time of %s", mountpoint);
2928		else {
2929			GJ_DEBUG(0, "Cannot sync file system %s (error=%d).",
2930			    mountpoint, error);
2931		}
2932
2933		MNT_ILOCK(mp);
2934		mp->mnt_noasync--;
2935		if ((mp->mnt_flag & MNT_ASYNC) != 0 && mp->mnt_noasync == 0)
2936			mp->mnt_kern_flag |= MNTK_ASYNC;
2937		MNT_IUNLOCK(mp);
2938
2939		vn_finished_write(mp);
2940
2941		if (error != 0) {
2942			VFS_UNLOCK_GIANT(vfslocked);
2943			goto next;
2944		}
2945
2946		/*
2947		 * Send BIO_FLUSH before freezing the file system, so it can be
2948		 * faster after the freeze.
2949		 */
2950		GJ_TIMER_START(1, &bt);
2951		g_journal_flush_cache(sc);
2952		GJ_TIMER_STOP(1, &bt, "BIO_FLUSH time of %s", sc->sc_name);
2953
2954		GJ_TIMER_START(1, &bt);
2955		error = vfs_write_suspend(mp);
2956		VFS_UNLOCK_GIANT(vfslocked);
2957		GJ_TIMER_STOP(1, &bt, "Suspend time of %s", mountpoint);
2958		if (error != 0) {
2959			GJ_DEBUG(0, "Cannot suspend file system %s (error=%d).",
2960			    mountpoint, error);
2961			goto next;
2962		}
2963
2964		error = desc->jd_clean(mp);
2965		if (error != 0)
2966			goto next;
2967
2968		mtx_lock(&sc->sc_mtx);
2969		g_journal_switch_wait(sc);
2970		mtx_unlock(&sc->sc_mtx);
2971
2972		vfs_write_resume(mp);
2973next:
2974		mtx_lock(&mountlist_mtx);
2975		vfs_unbusy(mp, td);
2976	}
2977	mtx_unlock(&mountlist_mtx);
2978
2979	sc = NULL;
2980	for (;;) {
2981		DROP_GIANT();
2982		g_topology_lock();
2983		LIST_FOREACH(gp, &g_journal_class.geom, geom) {
2984			sc = gp->softc;
2985			if (sc == NULL)
2986				continue;
2987			mtx_lock(&sc->sc_mtx);
2988			if ((sc->sc_type & GJ_TYPE_COMPLETE) == GJ_TYPE_COMPLETE &&
2989			    !(sc->sc_flags & GJF_DEVICE_DESTROY) &&
2990			    (sc->sc_flags & GJF_DEVICE_BEFORE_SWITCH)) {
2991				break;
2992			}
2993			mtx_unlock(&sc->sc_mtx);
2994			sc = NULL;
2995		}
2996		g_topology_unlock();
2997		PICKUP_GIANT();
2998		if (sc == NULL)
2999			break;
3000		mtx_assert(&sc->sc_mtx, MA_OWNED);
3001		g_journal_switch_wait(sc);
3002		mtx_unlock(&sc->sc_mtx);
3003	}
3004}
3005
3006/*
3007 * TODO: Switcher thread should be started on first geom creation and killed on
3008 * last geom destruction.
3009 */
3010static void
3011g_journal_switcher(void *arg)
3012{
3013	struct thread *td = curthread;
3014	struct g_class *mp;
3015	struct bintime bt;
3016	int error;
3017
3018	mp = arg;
3019	for (;;) {
3020		g_journal_switcher_wokenup = 0;
3021		error = tsleep(&g_journal_switcher_state, PRIBIO, "jsw:wait",
3022		    g_journal_switch_time * hz);
3023		if (g_journal_switcher_state == GJ_SWITCHER_DIE) {
3024			g_journal_switcher_state = GJ_SWITCHER_DIED;
3025			GJ_DEBUG(1, "Switcher exiting.");
3026			wakeup(&g_journal_switcher_state);
3027			kthread_exit(0);
3028		}
3029		if (error == 0 && g_journal_sync_requested == 0) {
3030			GJ_DEBUG(1, "Out of cache, force switch (used=%u "
3031			    "limit=%u).", g_journal_cache_used,
3032			    g_journal_cache_limit);
3033		}
3034		GJ_TIMER_START(1, &bt);
3035		g_journal_do_switch(mp, td);
3036		GJ_TIMER_STOP(1, &bt, "Entire switch time");
3037		if (g_journal_sync_requested > 0) {
3038			g_journal_sync_requested = 0;
3039			wakeup(&g_journal_sync_requested);
3040		}
3041	}
3042}
3043