g_journal.c revision 241896
1296417Sdim/*-
2254721Semaste * Copyright (c) 2005-2006 Pawel Jakub Dawidek <pjd@FreeBSD.org>
3353358Sdim * All rights reserved.
4353358Sdim *
5353358Sdim * Redistribution and use in source and binary forms, with or without
6254721Semaste * modification, are permitted provided that the following conditions
7254721Semaste * are met:
8254721Semaste * 1. Redistributions of source code must retain the above copyright
9254721Semaste *    notice, this list of conditions and the following disclaimer.
10254721Semaste * 2. Redistributions in binary form must reproduce the above copyright
11254721Semaste *    notice, this list of conditions and the following disclaimer in the
12254721Semaste *    documentation and/or other materials provided with the distribution.
13254721Semaste *
14254721Semaste * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
15254721Semaste * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16314564Sdim * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17353358Sdim * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
18321369Sdim * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19321369Sdim * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20254721Semaste * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21254721Semaste * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22254721Semaste * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23254721Semaste * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24254721Semaste * SUCH DAMAGE.
25254721Semaste */
26254721Semaste
27254721Semaste#include <sys/cdefs.h>
28254721Semaste__FBSDID("$FreeBSD: head/sys/geom/journal/g_journal.c 241896 2012-10-22 17:50:54Z kib $");
29254721Semaste
30296417Sdim#include <sys/param.h>
31254721Semaste#include <sys/systm.h>
32314564Sdim#include <sys/kernel.h>
33254721Semaste#include <sys/module.h>
34254721Semaste#include <sys/limits.h>
35254721Semaste#include <sys/lock.h>
36254721Semaste#include <sys/mutex.h>
37353358Sdim#include <sys/bio.h>
38353358Sdim#include <sys/sysctl.h>
39254721Semaste#include <sys/malloc.h>
40254721Semaste#include <sys/mount.h>
41254721Semaste#include <sys/eventhandler.h>
42360784Sdim#include <sys/proc.h>
43360784Sdim#include <sys/kthread.h>
44314564Sdim#include <sys/sched.h>
45341825Sdim#include <sys/taskqueue.h>
46360784Sdim#include <sys/vnode.h>
47254721Semaste#include <sys/sbuf.h>
48254721Semaste#ifdef GJ_MEMDEBUG
49314564Sdim#include <sys/stack.h>
50314564Sdim#include <sys/kdb.h>
51314564Sdim#endif
52314564Sdim#include <vm/vm.h>
53254721Semaste#include <vm/vm_kern.h>
54314564Sdim#include <geom/geom.h>
55254721Semaste
56314564Sdim#include <geom/journal/g_journal.h>
57314564Sdim
58314564SdimFEATURE(geom_journal, "GEOM journaling support");
59276479Sdim
60314564Sdim/*
61314564Sdim * On-disk journal format:
62314564Sdim *
63276479Sdim * JH - Journal header
64314564Sdim * RH - Record header
65360784Sdim *
66360784Sdim * %%%%%% ****** +------+ +------+     ****** +------+     %%%%%%
67360784Sdim * % JH % * RH * | Data | | Data | ... * RH * | Data | ... % JH % ...
68360784Sdim * %%%%%% ****** +------+ +------+     ****** +------+     %%%%%%
69360784Sdim *
70254721Semaste */
71314564Sdim
72314564SdimCTASSERT(sizeof(struct g_journal_header) <= 512);
73314564SdimCTASSERT(sizeof(struct g_journal_record_header) <= 512);
74314564Sdim
75314564Sdimstatic MALLOC_DEFINE(M_JOURNAL, "journal_data", "GEOM_JOURNAL Data");
76314564Sdimstatic struct mtx g_journal_cache_mtx;
77276479SdimMTX_SYSINIT(g_journal_cache, &g_journal_cache_mtx, "cache usage", MTX_DEF);
78314564Sdim
79314564Sdimconst struct g_journal_desc *g_journal_filesystems[] = {
80314564Sdim	&g_journal_ufs,
81341825Sdim	NULL
82341825Sdim};
83276479Sdim
84314564SdimSYSCTL_DECL(_kern_geom);
85314564Sdim
86314564Sdimint g_journal_debug = 0;
87314564SdimTUNABLE_INT("kern.geom.journal.debug", &g_journal_debug);
88314564Sdimstatic u_int g_journal_switch_time = 10;
89344779Sdimstatic u_int g_journal_force_switch = 70;
90314564Sdimstatic u_int g_journal_parallel_flushes = 16;
91314564Sdimstatic u_int g_journal_parallel_copies = 16;
92344779Sdimstatic u_int g_journal_accept_immediately = 64;
93314564Sdimstatic u_int g_journal_record_entries = GJ_RECORD_HEADER_NENTRIES;
94276479Sdimstatic u_int g_journal_do_optimize = 1;
95314564Sdim
96314564Sdimstatic SYSCTL_NODE(_kern_geom, OID_AUTO, journal, CTLFLAG_RW, 0,
97314564Sdim    "GEOM_JOURNAL stuff");
98276479SdimSYSCTL_INT(_kern_geom_journal, OID_AUTO, debug, CTLFLAG_RW, &g_journal_debug, 0,
99314564Sdim    "Debug level");
100341825SdimSYSCTL_UINT(_kern_geom_journal, OID_AUTO, switch_time, CTLFLAG_RW,
101341825Sdim    &g_journal_switch_time, 0, "Switch journals every N seconds");
102341825SdimSYSCTL_UINT(_kern_geom_journal, OID_AUTO, force_switch, CTLFLAG_RW,
103314564Sdim    &g_journal_force_switch, 0, "Force switch when journal is N% full");
104314564SdimSYSCTL_UINT(_kern_geom_journal, OID_AUTO, parallel_flushes, CTLFLAG_RW,
105314564Sdim    &g_journal_parallel_flushes, 0,
106314564Sdim    "Number of flush I/O requests to send in parallel");
107314564SdimSYSCTL_UINT(_kern_geom_journal, OID_AUTO, accept_immediately, CTLFLAG_RW,
108276479Sdim    &g_journal_accept_immediately, 0,
109314564Sdim    "Number of I/O requests accepted immediately");
110314564SdimSYSCTL_UINT(_kern_geom_journal, OID_AUTO, parallel_copies, CTLFLAG_RW,
111314564Sdim    &g_journal_parallel_copies, 0,
112314564Sdim    "Number of copy I/O requests to send in parallel");
113314564Sdimstatic int
114314564Sdimg_journal_record_entries_sysctl(SYSCTL_HANDLER_ARGS)
115314564Sdim{
116314564Sdim	u_int entries;
117314564Sdim	int error;
118314564Sdim
119314564Sdim	entries = g_journal_record_entries;
120314564Sdim	error = sysctl_handle_int(oidp, &entries, 0, req);
121314564Sdim	if (error != 0 || req->newptr == NULL)
122314564Sdim		return (error);
123276479Sdim	if (entries < 1 || entries > GJ_RECORD_HEADER_NENTRIES)
124314564Sdim		return (EINVAL);
125341825Sdim	g_journal_record_entries = entries;
126341825Sdim	return (0);
127341825Sdim}
128341825SdimSYSCTL_PROC(_kern_geom_journal, OID_AUTO, record_entries,
129341825Sdim    CTLTYPE_UINT | CTLFLAG_RW, NULL, 0, g_journal_record_entries_sysctl, "I",
130341825Sdim    "Maximum number of entires in one journal record");
131341825SdimSYSCTL_UINT(_kern_geom_journal, OID_AUTO, optimize, CTLFLAG_RW,
132314564Sdim    &g_journal_do_optimize, 0, "Try to combine bios on flush and copy");
133314564Sdim
134314564Sdimstatic u_int g_journal_cache_used = 0;
135314564Sdimstatic u_int g_journal_cache_limit = 64 * 1024 * 1024;
136314564SdimTUNABLE_INT("kern.geom.journal.cache.limit", &g_journal_cache_limit);
137276479Sdimstatic u_int g_journal_cache_divisor = 2;
138341825SdimTUNABLE_INT("kern.geom.journal.cache.divisor", &g_journal_cache_divisor);
139341825Sdimstatic u_int g_journal_cache_switch = 90;
140314564Sdimstatic u_int g_journal_cache_misses = 0;
141314564Sdimstatic u_int g_journal_cache_alloc_failures = 0;
142314564Sdimstatic u_int g_journal_cache_low = 0;
143314564Sdim
144314564Sdimstatic SYSCTL_NODE(_kern_geom_journal, OID_AUTO, cache, CTLFLAG_RW, 0,
145314564Sdim    "GEOM_JOURNAL cache");
146314564SdimSYSCTL_UINT(_kern_geom_journal_cache, OID_AUTO, used, CTLFLAG_RD,
147314564Sdim    &g_journal_cache_used, 0, "Number of allocated bytes");
148314564Sdimstatic int
149314564Sdimg_journal_cache_limit_sysctl(SYSCTL_HANDLER_ARGS)
150314564Sdim{
151314564Sdim	u_int limit;
152314564Sdim	int error;
153254721Semaste
154314564Sdim	limit = g_journal_cache_limit;
155314564Sdim	error = sysctl_handle_int(oidp, &limit, 0, req);
156314564Sdim	if (error != 0 || req->newptr == NULL)
157314564Sdim		return (error);
158276479Sdim	g_journal_cache_limit = limit;
159314564Sdim	g_journal_cache_low = (limit / 100) * g_journal_cache_switch;
160314564Sdim	return (0);
161314564Sdim}
162254721SemasteSYSCTL_PROC(_kern_geom_journal_cache, OID_AUTO, limit,
163314564Sdim    CTLTYPE_UINT | CTLFLAG_RW, NULL, 0, g_journal_cache_limit_sysctl, "I",
164314564Sdim    "Maximum number of allocated bytes");
165254721SemasteSYSCTL_UINT(_kern_geom_journal_cache, OID_AUTO, divisor, CTLFLAG_RDTUN,
166254721Semaste    &g_journal_cache_divisor, 0,
167314564Sdim    "(kmem_size / kern.geom.journal.cache.divisor) == cache size");
168254721Semastestatic int
169314564Sdimg_journal_cache_switch_sysctl(SYSCTL_HANDLER_ARGS)
170314564Sdim{
171314564Sdim	u_int cswitch;
172314564Sdim	int error;
173314564Sdim
174314564Sdim	cswitch = g_journal_cache_switch;
175254721Semaste	error = sysctl_handle_int(oidp, &cswitch, 0, req);
176314564Sdim	if (error != 0 || req->newptr == NULL)
177254721Semaste		return (error);
178360784Sdim	if (cswitch < 0 || cswitch > 100)
179360784Sdim		return (EINVAL);
180360784Sdim	g_journal_cache_switch = cswitch;
181314564Sdim	g_journal_cache_low = (g_journal_cache_limit / 100) * cswitch;
182353358Sdim	return (0);
183360784Sdim}
184254721SemasteSYSCTL_PROC(_kern_geom_journal_cache, OID_AUTO, switch,
185314564Sdim    CTLTYPE_UINT | CTLFLAG_RW, NULL, 0, g_journal_cache_switch_sysctl, "I",
186314564Sdim    "Force switch when we hit this percent of cache use");
187314564SdimSYSCTL_UINT(_kern_geom_journal_cache, OID_AUTO, misses, CTLFLAG_RW,
188314564Sdim    &g_journal_cache_misses, 0, "Number of cache misses");
189314564SdimSYSCTL_UINT(_kern_geom_journal_cache, OID_AUTO, alloc_failures, CTLFLAG_RW,
190314564Sdim    &g_journal_cache_alloc_failures, 0, "Memory allocation failures");
191360784Sdim
192360784Sdimstatic u_long g_journal_stats_bytes_skipped = 0;
193341825Sdimstatic u_long g_journal_stats_combined_ios = 0;
194341825Sdimstatic u_long g_journal_stats_switches = 0;
195341825Sdimstatic u_long g_journal_stats_wait_for_copy = 0;
196314564Sdimstatic u_long g_journal_stats_journal_full = 0;
197360784Sdimstatic u_long g_journal_stats_low_mem = 0;
198254721Semaste
199314564Sdimstatic SYSCTL_NODE(_kern_geom_journal, OID_AUTO, stats, CTLFLAG_RW, 0,
200353358Sdim    "GEOM_JOURNAL statistics");
201314564SdimSYSCTL_ULONG(_kern_geom_journal_stats, OID_AUTO, skipped_bytes, CTLFLAG_RW,
202314564Sdim    &g_journal_stats_bytes_skipped, 0, "Number of skipped bytes");
203360784SdimSYSCTL_ULONG(_kern_geom_journal_stats, OID_AUTO, combined_ios, CTLFLAG_RW,
204314564Sdim    &g_journal_stats_combined_ios, 0, "Number of combined I/O requests");
205360784SdimSYSCTL_ULONG(_kern_geom_journal_stats, OID_AUTO, switches, CTLFLAG_RW,
206314564Sdim    &g_journal_stats_switches, 0, "Number of journal switches");
207314564SdimSYSCTL_ULONG(_kern_geom_journal_stats, OID_AUTO, wait_for_copy, CTLFLAG_RW,
208314564Sdim    &g_journal_stats_wait_for_copy, 0, "Wait for journal copy on switch");
209314564SdimSYSCTL_ULONG(_kern_geom_journal_stats, OID_AUTO, journal_full, CTLFLAG_RW,
210314564Sdim    &g_journal_stats_journal_full, 0,
211314564Sdim    "Number of times journal was almost full.");
212360784SdimSYSCTL_ULONG(_kern_geom_journal_stats, OID_AUTO, low_mem, CTLFLAG_RW,
213254721Semaste    &g_journal_stats_low_mem, 0, "Number of times low_mem hook was called.");
214314564Sdim
215254721Semastestatic g_taste_t g_journal_taste;
216353358Sdimstatic g_ctl_req_t g_journal_config;
217314564Sdimstatic g_dumpconf_t g_journal_dumpconf;
218254721Semastestatic g_init_t g_journal_init;
219254721Semastestatic g_fini_t g_journal_fini;
220314564Sdim
221314564Sdimstruct g_class g_journal_class = {
222254721Semaste	.name = G_JOURNAL_CLASS_NAME,
223254721Semaste	.version = G_VERSION,
224314564Sdim	.taste = g_journal_taste,
225314564Sdim	.ctlreq = g_journal_config,
226314564Sdim	.dumpconf = g_journal_dumpconf,
227254721Semaste	.init = g_journal_init,
228254721Semaste	.fini = g_journal_fini
229314564Sdim};
230314564Sdim
231254721Semastestatic int g_journal_destroy(struct g_journal_softc *sc);
232254721Semastestatic void g_journal_metadata_update(struct g_journal_softc *sc);
233314564Sdimstatic void g_journal_switch_wait(struct g_journal_softc *sc);
234314564Sdim
235314564Sdim#define	GJ_SWITCHER_WORKING	0
236254721Semaste#define	GJ_SWITCHER_DIE		1
237254721Semaste#define	GJ_SWITCHER_DIED	2
238314564Sdimstatic int g_journal_switcher_state = GJ_SWITCHER_WORKING;
239314564Sdimstatic int g_journal_switcher_wokenup = 0;
240254721Semastestatic int g_journal_sync_requested = 0;
241254721Semaste
242360784Sdim#ifdef GJ_MEMDEBUG
243360784Sdimstruct meminfo {
244254721Semaste	size_t		mi_size;
245254721Semaste	struct stack	mi_stack;
246360784Sdim};
247360784Sdim#endif
248360784Sdim
249314564Sdim/*
250254721Semaste * We use our own malloc/realloc/free funtions, so we can collect statistics
251314564Sdim * and force journal switch when we're running out of cache.
252254721Semaste */
253314564Sdimstatic void *
254254721Semastegj_malloc(size_t size, int flags)
255314564Sdim{
256314564Sdim	void *p;
257314564Sdim#ifdef GJ_MEMDEBUG
258254721Semaste	struct meminfo *mi;
259314564Sdim#endif
260254721Semaste
261314564Sdim	mtx_lock(&g_journal_cache_mtx);
262314564Sdim	if (g_journal_cache_limit > 0 && !g_journal_switcher_wokenup &&
263360784Sdim	    g_journal_cache_used + size > g_journal_cache_low) {
264314564Sdim		GJ_DEBUG(1, "No cache, waking up the switcher.");
265254721Semaste		g_journal_switcher_wokenup = 1;
266314564Sdim		wakeup(&g_journal_switcher_state);
267314564Sdim	}
268360784Sdim	if ((flags & M_NOWAIT) && g_journal_cache_limit > 0 &&
269314564Sdim	    g_journal_cache_used + size > g_journal_cache_limit) {
270314564Sdim		mtx_unlock(&g_journal_cache_mtx);
271314564Sdim		g_journal_cache_alloc_failures++;
272314564Sdim		return (NULL);
273314564Sdim	}
274314564Sdim	g_journal_cache_used += size;
275314564Sdim	mtx_unlock(&g_journal_cache_mtx);
276314564Sdim	flags &= ~M_NOWAIT;
277254721Semaste#ifndef GJ_MEMDEBUG
278314564Sdim	p = malloc(size, M_JOURNAL, flags | M_WAITOK);
279314564Sdim#else
280314564Sdim	mi = malloc(sizeof(*mi) + size, M_JOURNAL, flags | M_WAITOK);
281314564Sdim	p = (u_char *)mi + sizeof(*mi);
282314564Sdim	mi->mi_size = size;
283254721Semaste	stack_save(&mi->mi_stack);
284314564Sdim#endif
285314564Sdim	return (p);
286341825Sdim}
287341825Sdim
288254721Semastestatic void
289360784Sdimgj_free(void *p, size_t size)
290314564Sdim{
291314564Sdim#ifdef GJ_MEMDEBUG
292254721Semaste	struct meminfo *mi;
293314564Sdim#endif
294314564Sdim
295314564Sdim	KASSERT(p != NULL, ("p=NULL"));
296314564Sdim	KASSERT(size > 0, ("size=0"));
297341825Sdim	mtx_lock(&g_journal_cache_mtx);
298341825Sdim	KASSERT(g_journal_cache_used >= size, ("Freeing too much?"));
299341825Sdim	g_journal_cache_used -= size;
300341825Sdim	mtx_unlock(&g_journal_cache_mtx);
301314564Sdim#ifdef GJ_MEMDEBUG
302254721Semaste	mi = p = (void *)((u_char *)p - sizeof(*mi));
303314564Sdim	if (mi->mi_size != size) {
304314564Sdim		printf("GJOURNAL: Size mismatch! %zu != %zu\n", size,
305314564Sdim		    mi->mi_size);
306254721Semaste		printf("GJOURNAL: Alloc backtrace:\n");
307314564Sdim		stack_print(&mi->mi_stack);
308314564Sdim		printf("GJOURNAL: Free backtrace:\n");
309314564Sdim		kdb_backtrace();
310314564Sdim	}
311314564Sdim#endif
312314564Sdim	free(p, M_JOURNAL);
313314564Sdim}
314314564Sdim
315314564Sdimstatic void *
316314564Sdimgj_realloc(void *p, size_t size, size_t oldsize)
317314564Sdim{
318314564Sdim	void *np;
319314564Sdim
320314564Sdim#ifndef GJ_MEMDEBUG
321314564Sdim	mtx_lock(&g_journal_cache_mtx);
322314564Sdim	g_journal_cache_used -= oldsize;
323314564Sdim	g_journal_cache_used += size;
324314564Sdim	mtx_unlock(&g_journal_cache_mtx);
325314564Sdim	np = realloc(p, size, M_JOURNAL, M_WAITOK);
326314564Sdim#else
327314564Sdim	np = gj_malloc(size, M_WAITOK);
328314564Sdim	bcopy(p, np, MIN(oldsize, size));
329314564Sdim	gj_free(p, oldsize);
330314564Sdim#endif
331314564Sdim	return (np);
332314564Sdim}
333314564Sdim
334314564Sdimstatic void
335314564Sdimg_journal_check_overflow(struct g_journal_softc *sc)
336314564Sdim{
337314564Sdim	off_t length, used;
338314564Sdim
339314564Sdim	if ((sc->sc_active.jj_offset < sc->sc_inactive.jj_offset &&
340314564Sdim	     sc->sc_journal_offset >= sc->sc_inactive.jj_offset) ||
341314564Sdim	    (sc->sc_active.jj_offset > sc->sc_inactive.jj_offset &&
342314564Sdim	     sc->sc_journal_offset >= sc->sc_inactive.jj_offset &&
343314564Sdim	     sc->sc_journal_offset < sc->sc_active.jj_offset)) {
344314564Sdim		panic("Journal overflow (joffset=%jd active=%jd inactive=%jd)",
345314564Sdim		    (intmax_t)sc->sc_journal_offset,
346314564Sdim		    (intmax_t)sc->sc_active.jj_offset,
347344779Sdim		    (intmax_t)sc->sc_inactive.jj_offset);
348314564Sdim	}
349314564Sdim	if (sc->sc_active.jj_offset < sc->sc_inactive.jj_offset) {
350314564Sdim		length = sc->sc_inactive.jj_offset - sc->sc_active.jj_offset;
351314564Sdim		used = sc->sc_journal_offset - sc->sc_active.jj_offset;
352314564Sdim	} else {
353314564Sdim		length = sc->sc_jend - sc->sc_active.jj_offset;
354314564Sdim		length += sc->sc_inactive.jj_offset - sc->sc_jstart;
355360784Sdim		if (sc->sc_journal_offset >= sc->sc_active.jj_offset)
356314564Sdim			used = sc->sc_journal_offset - sc->sc_active.jj_offset;
357314564Sdim		else {
358314564Sdim			used = sc->sc_jend - sc->sc_active.jj_offset;
359314564Sdim			used += sc->sc_journal_offset - sc->sc_jstart;
360314564Sdim		}
361314564Sdim	}
362314564Sdim	/* Already woken up? */
363314564Sdim	if (g_journal_switcher_wokenup)
364314564Sdim		return;
365314564Sdim	/*
366360784Sdim	 * If the active journal takes more than g_journal_force_switch precent
367360784Sdim	 * of free journal space, we force journal switch.
368314564Sdim	 */
369314564Sdim	KASSERT(length > 0,
370353358Sdim	    ("length=%jd used=%jd active=%jd inactive=%jd joffset=%jd",
371360784Sdim	    (intmax_t)length, (intmax_t)used,
372314564Sdim	    (intmax_t)sc->sc_active.jj_offset,
373314564Sdim	    (intmax_t)sc->sc_inactive.jj_offset,
374314564Sdim	    (intmax_t)sc->sc_journal_offset));
375353358Sdim	if ((used * 100) / length > g_journal_force_switch) {
376360784Sdim		g_journal_stats_journal_full++;
377314564Sdim		GJ_DEBUG(1, "Journal %s %jd%% full, forcing journal switch.",
378314564Sdim		    sc->sc_name, (used * 100) / length);
379314564Sdim		mtx_lock(&g_journal_cache_mtx);
380314564Sdim		g_journal_switcher_wokenup = 1;
381360784Sdim		wakeup(&g_journal_switcher_state);
382314564Sdim		mtx_unlock(&g_journal_cache_mtx);
383314564Sdim	}
384314564Sdim}
385314564Sdim
386360784Sdimstatic void
387314564Sdimg_journal_orphan(struct g_consumer *cp)
388314564Sdim{
389314564Sdim	struct g_journal_softc *sc;
390254721Semaste	char name[256];
391314564Sdim	int error;
392254721Semaste
393314564Sdim	g_topology_assert();
394254721Semaste	sc = cp->geom->softc;
395254721Semaste	strlcpy(name, cp->provider->name, sizeof(name));
396314564Sdim	GJ_DEBUG(0, "Lost provider %s.", name);
397314564Sdim	if (sc == NULL)
398314564Sdim		return;
399314564Sdim	error = g_journal_destroy(sc);
400353358Sdim	if (error == 0)
401254721Semaste		GJ_DEBUG(0, "Journal %s destroyed.", name);
402254721Semaste	else {
403314564Sdim		GJ_DEBUG(0, "Cannot destroy journal %s (error=%d). "
404314564Sdim		    "Destroy it manually after last close.", sc->sc_name,
405314564Sdim		    error);
406341825Sdim	}
407341825Sdim}
408314564Sdim
409314564Sdimstatic int
410314564Sdimg_journal_access(struct g_provider *pp, int acr, int acw, int ace)
411314564Sdim{
412353358Sdim	struct g_journal_softc *sc;
413341825Sdim	int dcr, dcw, dce;
414341825Sdim
415314564Sdim	g_topology_assert();
416344779Sdim	GJ_DEBUG(2, "Access request for %s: r%dw%de%d.", pp->name,
417314564Sdim	    acr, acw, ace);
418344779Sdim
419344779Sdim	dcr = pp->acr + acr;
420344779Sdim	dcw = pp->acw + acw;
421344779Sdim	dce = pp->ace + ace;
422344779Sdim
423360784Sdim	sc = pp->geom->softc;
424360784Sdim	if (sc == NULL || (sc->sc_flags & GJF_DEVICE_DESTROY)) {
425360784Sdim		if (acr <= 0 && acw <= 0 && ace <= 0)
426360784Sdim			return (0);
427360784Sdim		else
428314564Sdim			return (ENXIO);
429314564Sdim	}
430314564Sdim	if (pp->acw == 0 && dcw > 0) {
431314564Sdim		GJ_DEBUG(1, "Marking %s as dirty.", sc->sc_name);
432314564Sdim		sc->sc_flags &= ~GJF_DEVICE_CLEAN;
433314564Sdim		g_topology_unlock();
434353358Sdim		g_journal_metadata_update(sc);
435254721Semaste		g_topology_lock();
436254721Semaste	} /* else if (pp->acw == 0 && dcw > 0 && JEMPTY(sc)) {
437314564Sdim		GJ_DEBUG(1, "Marking %s as clean.", sc->sc_name);
438314564Sdim		sc->sc_flags |= GJF_DEVICE_CLEAN;
439254721Semaste		g_topology_unlock();
440314564Sdim		g_journal_metadata_update(sc);
441314564Sdim		g_topology_lock();
442353358Sdim	} */
443254721Semaste	return (0);
444314564Sdim}
445341825Sdim
446341825Sdimstatic void
447341825Sdimg_journal_header_encode(struct g_journal_header *hdr, u_char *data)
448341825Sdim{
449314564Sdim
450314564Sdim	bcopy(GJ_HEADER_MAGIC, data, sizeof(GJ_HEADER_MAGIC));
451341825Sdim	data += sizeof(GJ_HEADER_MAGIC);
452341825Sdim	le32enc(data, hdr->jh_journal_id);
453341825Sdim	data += 4;
454360784Sdim	le32enc(data, hdr->jh_journal_next_id);
455314564Sdim}
456314564Sdim
457314564Sdimstatic int
458314564Sdimg_journal_header_decode(const u_char *data, struct g_journal_header *hdr)
459314564Sdim{
460353358Sdim
461314564Sdim	bcopy(data, hdr->jh_magic, sizeof(hdr->jh_magic));
462353358Sdim	data += sizeof(hdr->jh_magic);
463353358Sdim	if (bcmp(hdr->jh_magic, GJ_HEADER_MAGIC, sizeof(GJ_HEADER_MAGIC)) != 0)
464254721Semaste		return (EINVAL);
465314564Sdim	hdr->jh_journal_id = le32dec(data);
466314564Sdim	data += 4;
467314564Sdim	hdr->jh_journal_next_id = le32dec(data);
468353358Sdim	return (0);
469254721Semaste}
470254721Semaste
471314564Sdimstatic void
472314564Sdimg_journal_flush_cache(struct g_journal_softc *sc)
473314564Sdim{
474314564Sdim	struct bintime bt;
475314564Sdim	int error;
476314564Sdim
477254721Semaste	if (sc->sc_bio_flush == 0)
478314564Sdim		return;
479314564Sdim	GJ_TIMER_START(1, &bt);
480254721Semaste	if (sc->sc_bio_flush & GJ_FLUSH_JOURNAL) {
481254721Semaste		error = g_io_flush(sc->sc_jconsumer);
482314564Sdim		GJ_DEBUG(error == 0 ? 2 : 0, "Flush cache of %s: error=%d.",
483314564Sdim		    sc->sc_jconsumer->provider->name, error);
484314564Sdim	}
485314564Sdim	if (sc->sc_bio_flush & GJ_FLUSH_DATA) {
486353358Sdim		/*
487254721Semaste		 * TODO: This could be called in parallel with the
488254721Semaste		 *       previous call.
489254721Semaste		 */
490314564Sdim		error = g_io_flush(sc->sc_dconsumer);
491344779Sdim		GJ_DEBUG(error == 0 ? 2 : 0, "Flush cache of %s: error=%d.",
492344779Sdim		    sc->sc_dconsumer->provider->name, error);
493344779Sdim	}
494344779Sdim	GJ_TIMER_STOP(1, &bt, "Cache flush time");
495344779Sdim}
496344779Sdim
497314564Sdimstatic int
498314564Sdimg_journal_write_header(struct g_journal_softc *sc)
499353358Sdim{
500254721Semaste	struct g_journal_header hdr;
501254721Semaste	struct g_consumer *cp;
502314564Sdim	u_char *buf;
503314564Sdim	int error;
504314564Sdim
505314564Sdim	cp = sc->sc_jconsumer;
506314564Sdim	buf = gj_malloc(cp->provider->sectorsize, M_WAITOK);
507353358Sdim
508254721Semaste	strlcpy(hdr.jh_magic, GJ_HEADER_MAGIC, sizeof(hdr.jh_magic));
509254721Semaste	hdr.jh_journal_id = sc->sc_journal_id;
510314564Sdim	hdr.jh_journal_next_id = sc->sc_journal_next_id;
511314564Sdim	g_journal_header_encode(&hdr, buf);
512314564Sdim	error = g_write_data(cp, sc->sc_journal_offset, buf,
513314564Sdim	    cp->provider->sectorsize);
514314564Sdim	/* if (error == 0) */
515314564Sdim	sc->sc_journal_offset += cp->provider->sectorsize;
516314564Sdim
517314564Sdim	gj_free(buf, cp->provider->sectorsize);
518314564Sdim	return (error);
519314564Sdim}
520254721Semaste
521254721Semaste/*
522254721Semaste * Every journal record has a header and data following it.
523314564Sdim * Functions below are used to decode the header before storing it to
524344779Sdim * little endian and to encode it after reading to system endianess.
525344779Sdim */
526314564Sdimstatic void
527353358Sdimg_journal_record_header_encode(struct g_journal_record_header *hdr,
528254721Semaste    u_char *data)
529254721Semaste{
530254721Semaste	struct g_journal_entry *ent;
531314564Sdim	u_int i;
532314564Sdim
533314564Sdim	bcopy(GJ_RECORD_HEADER_MAGIC, data, sizeof(GJ_RECORD_HEADER_MAGIC));
534314564Sdim	data += sizeof(GJ_RECORD_HEADER_MAGIC);
535353358Sdim	le32enc(data, hdr->jrh_journal_id);
536254721Semaste	data += 8;
537254721Semaste	le16enc(data, hdr->jrh_nentries);
538314564Sdim	data += 2;
539314564Sdim	bcopy(hdr->jrh_sum, data, sizeof(hdr->jrh_sum));
540360784Sdim	data += 8;
541360784Sdim	for (i = 0; i < hdr->jrh_nentries; i++) {
542353358Sdim		ent = &hdr->jrh_entries[i];
543254721Semaste		le64enc(data, ent->je_joffset);
544254721Semaste		data += 8;
545314564Sdim		le64enc(data, ent->je_offset);
546314564Sdim		data += 8;
547314564Sdim		le64enc(data, ent->je_length);
548341825Sdim		data += 8;
549341825Sdim	}
550254721Semaste}
551314564Sdim
552314564Sdimstatic int
553314564Sdimg_journal_record_header_decode(const u_char *data,
554314564Sdim    struct g_journal_record_header *hdr)
555314564Sdim{
556314564Sdim	struct g_journal_entry *ent;
557314564Sdim	u_int i;
558314564Sdim
559254721Semaste	bcopy(data, hdr->jrh_magic, sizeof(hdr->jrh_magic));
560314564Sdim	data += sizeof(hdr->jrh_magic);
561314564Sdim	if (strcmp(hdr->jrh_magic, GJ_RECORD_HEADER_MAGIC) != 0)
562254721Semaste		return (EINVAL);
563254721Semaste	hdr->jrh_journal_id = le32dec(data);
564360784Sdim	data += 8;
565314564Sdim	hdr->jrh_nentries = le16dec(data);
566314564Sdim	data += 2;
567254721Semaste	if (hdr->jrh_nentries > GJ_RECORD_HEADER_NENTRIES)
568254721Semaste		return (EINVAL);
569314564Sdim	bcopy(data, hdr->jrh_sum, sizeof(hdr->jrh_sum));
570314564Sdim	data += 8;
571314564Sdim	for (i = 0; i < hdr->jrh_nentries; i++) {
572254721Semaste		ent = &hdr->jrh_entries[i];
573314564Sdim		ent->je_joffset = le64dec(data);
574314564Sdim		data += 8;
575314564Sdim		ent->je_offset = le64dec(data);
576314564Sdim		data += 8;
577314564Sdim		ent->je_length = le64dec(data);
578341825Sdim		data += 8;
579341825Sdim	}
580314564Sdim	return (0);
581353358Sdim}
582353358Sdim
583360784Sdim/*
584353358Sdim * Function reads metadata from a provider (via the given consumer), decodes
585309124Sdim * it to system endianess and verifies its correctness.
586314564Sdim */
587360784Sdimstatic int
588360784Sdimg_journal_metadata_read(struct g_consumer *cp, struct g_journal_metadata *md)
589254721Semaste{
590314564Sdim	struct g_provider *pp;
591254721Semaste	u_char *buf;
592314564Sdim	int error;
593314564Sdim
594254721Semaste	g_topology_assert();
595314564Sdim
596254721Semaste	error = g_access(cp, 1, 0, 0);
597254721Semaste	if (error != 0)
598254721Semaste		return (error);
599314564Sdim	pp = cp->provider;
600344779Sdim	g_topology_unlock();
601344779Sdim	/* Metadata is stored in last sector. */
602344779Sdim	buf = g_read_data(cp, pp->mediasize - pp->sectorsize, pp->sectorsize,
603344779Sdim	    &error);
604344779Sdim	g_topology_lock();
605314564Sdim	g_access(cp, -1, 0, 0);
606314564Sdim	if (buf == NULL) {
607360784Sdim		GJ_DEBUG(1, "Cannot read metadata from %s (error=%d).",
608314564Sdim		    cp->provider->name, error);
609314564Sdim		return (error);
610353358Sdim	}
611254721Semaste
612254721Semaste	/* Decode metadata. */
613314564Sdim	error = journal_metadata_decode(buf, md);
614314564Sdim	g_free(buf);
615314564Sdim	/* Is this is gjournal provider at all? */
616314564Sdim	if (strcmp(md->md_magic, G_JOURNAL_MAGIC) != 0)
617314564Sdim		return (EINVAL);
618314564Sdim	/*
619314564Sdim	 * Are we able to handle this version of metadata?
620314564Sdim	 * We only maintain backward compatibility.
621314564Sdim	 */
622254721Semaste	if (md->md_version > G_JOURNAL_VERSION) {
623254721Semaste		GJ_DEBUG(0,
624254721Semaste		    "Kernel module is too old to handle metadata from %s.",
625344779Sdim		    cp->provider->name);
626360784Sdim		return (EINVAL);
627344779Sdim	}
628314564Sdim	/* Is checksum correct? */
629344779Sdim	if (error != 0) {
630314564Sdim		GJ_DEBUG(0, "MD5 metadata hash mismatch for provider %s.",
631254721Semaste		    cp->provider->name);
632254721Semaste		return (error);
633344779Sdim	}
634360784Sdim	return (0);
635344779Sdim}
636314564Sdim
637344779Sdim/*
638314564Sdim * Two functions below are responsible for updating metadata.
639254721Semaste * Only metadata on the data provider is updated (we need to update
640254721Semaste * information about active journal in there).
641344779Sdim */
642360784Sdimstatic void
643344779Sdimg_journal_metadata_done(struct bio *bp)
644314564Sdim{
645344779Sdim
646314564Sdim	/*
647254721Semaste	 * There is not much we can do on error except informing about it.
648254721Semaste	 */
649344779Sdim	if (bp->bio_error != 0) {
650360784Sdim		GJ_LOGREQ(0, bp, "Cannot update metadata (error=%d).",
651344779Sdim		    bp->bio_error);
652314564Sdim	} else {
653344779Sdim		GJ_LOGREQ(2, bp, "Metadata updated.");
654314564Sdim	}
655296417Sdim	gj_free(bp->bio_data, bp->bio_length);
656296417Sdim	g_destroy_bio(bp);
657360784Sdim}
658360784Sdim
659360784Sdimstatic void
660360784Sdimg_journal_metadata_update(struct g_journal_softc *sc)
661360784Sdim{
662360784Sdim	struct g_journal_metadata md;
663360784Sdim	struct g_consumer *cp;
664360784Sdim	struct bio *bp;
665360784Sdim	u_char *sector;
666360784Sdim
667360784Sdim	cp = sc->sc_dconsumer;
668344779Sdim	sector = gj_malloc(cp->provider->sectorsize, M_WAITOK);
669344779Sdim	strlcpy(md.md_magic, G_JOURNAL_MAGIC, sizeof(md.md_magic));
670360784Sdim	md.md_version = G_JOURNAL_VERSION;
671344779Sdim	md.md_id = sc->sc_id;
672314564Sdim	md.md_type = sc->sc_orig_type;
673344779Sdim	md.md_jstart = sc->sc_jstart;
674314564Sdim	md.md_jend = sc->sc_jend;
675254721Semaste	md.md_joffset = sc->sc_inactive.jj_offset;
676254721Semaste	md.md_jid = sc->sc_journal_previous_id;
677344779Sdim	md.md_flags = 0;
678360784Sdim	if (sc->sc_flags & GJF_DEVICE_CLEAN)
679344779Sdim		md.md_flags |= GJ_FLAG_CLEAN;
680314564Sdim
681344779Sdim	if (sc->sc_flags & GJF_DEVICE_HARDCODED)
682314564Sdim		strlcpy(md.md_provider, sc->sc_name, sizeof(md.md_provider));
683309124Sdim	else
684309124Sdim		bzero(md.md_provider, sizeof(md.md_provider));
685314564Sdim	md.md_provsize = cp->provider->mediasize;
686353358Sdim	journal_metadata_encode(&md, sector);
687360784Sdim
688314564Sdim	/*
689314564Sdim	 * Flush the cache, so we know all data are on disk.
690314564Sdim	 * We write here informations like "journal is consistent", so we need
691314564Sdim	 * to be sure it is. Without BIO_FLUSH here, we can end up in situation
692288943Sdim	 * where metadata is stored on disk, but not all data.
693254721Semaste	 */
694344779Sdim	g_journal_flush_cache(sc);
695360784Sdim
696344779Sdim	bp = g_alloc_bio();
697344779Sdim	bp->bio_offset = cp->provider->mediasize - cp->provider->sectorsize;
698344779Sdim	bp->bio_length = cp->provider->sectorsize;
699344779Sdim	bp->bio_data = sector;
700344779Sdim	bp->bio_cmd = BIO_WRITE;
701314564Sdim	if (!(sc->sc_flags & GJF_DEVICE_DESTROY)) {
702344779Sdim		bp->bio_done = g_journal_metadata_done;
703314564Sdim		g_io_request(bp, cp);
704254721Semaste	} else {
705254721Semaste		bp->bio_done = NULL;
706344779Sdim		g_io_request(bp, cp);
707360784Sdim		biowait(bp, "gjmdu");
708344779Sdim		g_journal_metadata_done(bp);
709314564Sdim	}
710344779Sdim
711314564Sdim	/*
712254721Semaste	 * Be sure metadata reached the disk.
713254721Semaste	 */
714254721Semaste	g_journal_flush_cache(sc);
715314564Sdim}
716360784Sdim
717314564Sdim/*
718314564Sdim * This is where the I/O request comes from the GEOM.
719314564Sdim */
720314564Sdimstatic void
721254721Semasteg_journal_start(struct bio *bp)
722254721Semaste{
723314564Sdim	struct g_journal_softc *sc;
724360784Sdim
725314564Sdim	sc = bp->bio_to->geom->softc;
726314564Sdim	GJ_LOGREQ(3, bp, "Request received.");
727314564Sdim
728314564Sdim	switch (bp->bio_cmd) {
729353358Sdim	case BIO_READ:
730254721Semaste	case BIO_WRITE:
731254721Semaste		mtx_lock(&sc->sc_mtx);
732344779Sdim		bioq_insert_tail(&sc->sc_regular_queue, bp);
733344779Sdim		wakeup(sc);
734344779Sdim		mtx_unlock(&sc->sc_mtx);
735344779Sdim		return;
736344779Sdim	case BIO_GETATTR:
737344779Sdim		if (strcmp(bp->bio_attribute, "GJOURNAL::provider") == 0) {
738344779Sdim			strlcpy(bp->bio_data, bp->bio_to->name, bp->bio_length);
739344779Sdim			bp->bio_completed = strlen(bp->bio_to->name) + 1;
740344779Sdim			g_io_deliver(bp, 0);
741344779Sdim			return;
742314564Sdim		}
743314564Sdim		/* FALLTHROUGH */
744314564Sdim	case BIO_DELETE:
745314564Sdim	default:
746314564Sdim		g_io_deliver(bp, EOPNOTSUPP);
747314564Sdim		return;
748314564Sdim	}
749314564Sdim}
750314564Sdim
751314564Sdimstatic void
752314564Sdimg_journal_std_done(struct bio *bp)
753314564Sdim{
754314564Sdim	struct g_journal_softc *sc;
755254721Semaste
756254721Semaste	sc = bp->bio_from->geom->softc;
757344779Sdim	mtx_lock(&sc->sc_mtx);
758344779Sdim	bioq_insert_tail(&sc->sc_back_queue, bp);
759344779Sdim	wakeup(sc);
760344779Sdim	mtx_unlock(&sc->sc_mtx);
761360784Sdim}
762314564Sdim
763360784Sdimstatic struct bio *
764314564Sdimg_journal_new_bio(off_t start, off_t end, off_t joffset, u_char *data,
765314564Sdim    int flags)
766254721Semaste{
767314564Sdim	struct bio *bp;
768314564Sdim
769314564Sdim	bp = g_alloc_bio();
770254721Semaste	bp->bio_offset = start;
771314564Sdim	bp->bio_joffset = joffset;
772314564Sdim	bp->bio_length = end - start;
773254721Semaste	bp->bio_cmd = BIO_WRITE;
774353358Sdim	bp->bio_done = g_journal_std_done;
775314564Sdim	if (data == NULL)
776254721Semaste		bp->bio_data = NULL;
777314564Sdim	else {
778314564Sdim		bp->bio_data = gj_malloc(bp->bio_length, flags);
779314564Sdim		if (bp->bio_data != NULL)
780314564Sdim			bcopy(data, bp->bio_data, bp->bio_length);
781314564Sdim	}
782314564Sdim	return (bp);
783314564Sdim}
784314564Sdim
785314564Sdim#define	g_journal_insert_bio(head, bp, flags)				\
786314564Sdim	g_journal_insert((head), (bp)->bio_offset,			\
787314564Sdim		(bp)->bio_offset + (bp)->bio_length, (bp)->bio_joffset,	\
788314564Sdim		(bp)->bio_data, flags)
789314564Sdim/*
790360784Sdim * The function below does a lot more than just inserting bio to the queue.
791314564Sdim * It keeps the queue sorted by offset and ensures that there are no doubled
792254721Semaste * data (it combines bios where ranges overlap).
793314564Sdim *
794254721Semaste * The function returns the number of bios inserted (as bio can be splitted).
795314564Sdim */
796254721Semastestatic int
797314564Sdimg_journal_insert(struct bio **head, off_t nstart, off_t nend, off_t joffset,
798314564Sdim    u_char *data, int flags)
799254721Semaste{
800254721Semaste	struct bio *nbp, *cbp, *pbp;
801314564Sdim	off_t cstart, cend;
802314564Sdim	u_char *tmpdata;
803344779Sdim	int n;
804360784Sdim
805314564Sdim	GJ_DEBUG(3, "INSERT(%p): (%jd, %jd, %jd)", *head, nstart, nend,
806314564Sdim	    joffset);
807254721Semaste	n = 0;
808314564Sdim	pbp = NULL;
809341825Sdim	GJQ_FOREACH(*head, cbp) {
810341825Sdim		cstart = cbp->bio_offset;
811314564Sdim		cend = cbp->bio_offset + cbp->bio_length;
812314564Sdim
813314564Sdim		if (nstart >= cend) {
814314564Sdim			/*
815360784Sdim			 *  +-------------+
816360784Sdim			 *  |             |
817254721Semaste			 *  |   current   |  +-------------+
818314564Sdim			 *  |     bio     |  |             |
819314564Sdim			 *  |             |  |     new     |
820314564Sdim			 *  +-------------+  |     bio     |
821314564Sdim			 *                   |             |
822314564Sdim			 *                   +-------------+
823314564Sdim			 */
824314564Sdim			GJ_DEBUG(3, "INSERT(%p): 1", *head);
825314564Sdim		} else if (nend <= cstart) {
826254721Semaste			/*
827254721Semaste			 *                   +-------------+
828360784Sdim			 *                   |             |
829353358Sdim			 *  +-------------+  |   current   |
830314564Sdim			 *  |             |  |     bio     |
831314564Sdim			 *  |     new     |  |             |
832344779Sdim			 *  |     bio     |  +-------------+
833314564Sdim			 *  |             |
834314564Sdim			 *  +-------------+
835314564Sdim			 */
836314564Sdim			nbp = g_journal_new_bio(nstart, nend, joffset, data,
837314564Sdim			    flags);
838314564Sdim			if (pbp == NULL)
839314564Sdim				*head = nbp;
840314564Sdim			else
841360784Sdim				pbp->bio_next = nbp;
842360784Sdim			nbp->bio_next = cbp;
843360784Sdim			n++;
844360784Sdim			GJ_DEBUG(3, "INSERT(%p): 2 (nbp=%p pbp=%p)", *head, nbp,
845314564Sdim			    pbp);
846254721Semaste			goto end;
847314564Sdim		} else if (nstart <= cstart && nend >= cend) {
848254721Semaste			/*
849254721Semaste			 *      +-------------+      +-------------+
850360784Sdim			 *      | current bio |      | current bio |
851353358Sdim			 *  +---+-------------+---+  +-------------+---+
852341825Sdim			 *  |   |             |   |  |             |   |
853360784Sdim			 *  |   |             |   |  |             |   |
854314564Sdim			 *  |   +-------------+   |  +-------------+   |
855288943Sdim			 *  |       new bio       |  |     new bio     |
856314564Sdim			 *  +---------------------+  +-----------------+
857360784Sdim			 *
858360784Sdim			 *      +-------------+  +-------------+
859360784Sdim			 *      | current bio |  | current bio |
860360784Sdim			 *  +---+-------------+  +-------------+
861314564Sdim			 *  |   |             |  |             |
862314564Sdim			 *  |   |             |  |             |
863314564Sdim			 *  |   +-------------+  +-------------+
864314564Sdim			 *  |     new bio     |  |   new bio   |
865314564Sdim			 *  +-----------------+  +-------------+
866314564Sdim			 */
867314564Sdim			g_journal_stats_bytes_skipped += cbp->bio_length;
868314564Sdim			cbp->bio_offset = nstart;
869314564Sdim			cbp->bio_joffset = joffset;
870314564Sdim			cbp->bio_length = cend - nstart;
871314564Sdim			if (cbp->bio_data != NULL) {
872341825Sdim				gj_free(cbp->bio_data, cend - cstart);
873341825Sdim				cbp->bio_data = NULL;
874314564Sdim			}
875314564Sdim			if (data != NULL) {
876314564Sdim				cbp->bio_data = gj_malloc(cbp->bio_length,
877314564Sdim				    flags);
878314564Sdim				if (cbp->bio_data != NULL) {
879254721Semaste					bcopy(data, cbp->bio_data,
880254721Semaste					    cbp->bio_length);
881360784Sdim				}
882360784Sdim				data += cend - nstart;
883360784Sdim			}
884360784Sdim			joffset += cend - nstart;
885314564Sdim			nstart = cend;
886314564Sdim			GJ_DEBUG(3, "INSERT(%p): 3 (cbp=%p)", *head, cbp);
887360784Sdim		} else if (nstart > cstart && nend >= cend) {
888360784Sdim			/*
889360784Sdim			 *  +-----------------+  +-------------+
890360784Sdim			 *  |   current bio   |  | current bio |
891314564Sdim			 *  |   +-------------+  |   +---------+---+
892314564Sdim			 *  |   |             |  |   |         |   |
893254721Semaste			 *  |   |             |  |   |         |   |
894314564Sdim			 *  +---+-------------+  +---+---------+   |
895314564Sdim			 *      |   new bio   |      |   new bio   |
896314564Sdim			 *      +-------------+      +-------------+
897254721Semaste			 */
898314564Sdim			g_journal_stats_bytes_skipped += cend - nstart;
899314564Sdim			nbp = g_journal_new_bio(nstart, cend, joffset, data,
900314564Sdim			    flags);
901254721Semaste			nbp->bio_next = cbp->bio_next;
902341825Sdim			cbp->bio_next = nbp;
903341825Sdim			cbp->bio_length = nstart - cstart;
904314564Sdim			if (cbp->bio_data != NULL) {
905314564Sdim				cbp->bio_data = gj_realloc(cbp->bio_data,
906314564Sdim				    cbp->bio_length, cend - cstart);
907314564Sdim			}
908314564Sdim			if (data != NULL)
909254721Semaste				data += cend - nstart;
910254721Semaste			joffset += cend - nstart;
911314564Sdim			nstart = cend;
912314564Sdim			n++;
913314564Sdim			GJ_DEBUG(3, "INSERT(%p): 4 (cbp=%p)", *head, cbp);
914254721Semaste		} else if (nstart > cstart && nend < cend) {
915314564Sdim			/*
916314564Sdim			 *  +---------------------+
917254721Semaste			 *  |     current bio     |
918314564Sdim			 *  |   +-------------+   |
919314564Sdim			 *  |   |             |   |
920254721Semaste			 *  |   |             |   |
921314564Sdim			 *  +---+-------------+---+
922254721Semaste			 *      |   new bio   |
923254721Semaste			 *      +-------------+
924314564Sdim			 */
925314564Sdim			g_journal_stats_bytes_skipped += nend - nstart;
926314564Sdim			nbp = g_journal_new_bio(nstart, nend, joffset, data,
927254721Semaste			    flags);
928314564Sdim			nbp->bio_next = cbp->bio_next;
929314564Sdim			cbp->bio_next = nbp;
930254721Semaste			if (cbp->bio_data == NULL)
931314564Sdim				tmpdata = NULL;
932314564Sdim			else
933254721Semaste				tmpdata = cbp->bio_data + nend - cstart;
934314564Sdim			nbp = g_journal_new_bio(nend, cend,
935254721Semaste			    cbp->bio_joffset + nend - cstart, tmpdata, flags);
936254721Semaste			nbp->bio_next = ((struct bio *)cbp->bio_next)->bio_next;
937314564Sdim			((struct bio *)cbp->bio_next)->bio_next = nbp;
938314564Sdim			cbp->bio_length = nstart - cstart;
939314564Sdim			if (cbp->bio_data != NULL) {
940314564Sdim				cbp->bio_data = gj_realloc(cbp->bio_data,
941353358Sdim				    cbp->bio_length, cend - cstart);
942314564Sdim			}
943314564Sdim			n += 2;
944314564Sdim			GJ_DEBUG(3, "INSERT(%p): 5 (cbp=%p)", *head, cbp);
945314564Sdim			goto end;
946314564Sdim		} else if (nstart <= cstart && nend < cend) {
947314564Sdim			/*
948254721Semaste			 *  +-----------------+      +-------------+
949314564Sdim			 *  |   current bio   |      | current bio |
950353358Sdim			 *  +-------------+   |  +---+---------+   |
951314564Sdim			 *  |             |   |  |   |         |   |
952314564Sdim			 *  |             |   |  |   |         |   |
953314564Sdim			 *  +-------------+---+  |   +---------+---+
954314564Sdim			 *  |   new bio   |      |   new bio   |
955314564Sdim			 *  +-------------+      +-------------+
956254721Semaste			 */
957254721Semaste			g_journal_stats_bytes_skipped += nend - nstart;
958314564Sdim			nbp = g_journal_new_bio(nstart, nend, joffset, data,
959314564Sdim			    flags);
960314564Sdim			if (pbp == NULL)
961314564Sdim				*head = nbp;
962353358Sdim			else
963314564Sdim				pbp->bio_next = nbp;
964314564Sdim			nbp->bio_next = cbp;
965314564Sdim			cbp->bio_offset = nend;
966314564Sdim			cbp->bio_length = cend - nend;
967314564Sdim			cbp->bio_joffset += nend - cstart;
968314564Sdim			tmpdata = cbp->bio_data;
969254721Semaste			if (tmpdata != NULL) {
970314564Sdim				cbp->bio_data = gj_malloc(cbp->bio_length,
971353358Sdim				    flags);
972314564Sdim				if (cbp->bio_data != NULL) {
973314564Sdim					bcopy(tmpdata + nend - cstart,
974314564Sdim					    cbp->bio_data, cbp->bio_length);
975314564Sdim				}
976314564Sdim				gj_free(tmpdata, cend - cstart);
977254721Semaste			}
978254721Semaste			n++;
979314564Sdim			GJ_DEBUG(3, "INSERT(%p): 6 (cbp=%p)", *head, cbp);
980314564Sdim			goto end;
981314564Sdim		}
982341825Sdim		if (nstart == nend)
983341825Sdim			goto end;
984341825Sdim		pbp = cbp;
985341825Sdim	}
986341825Sdim	nbp = g_journal_new_bio(nstart, nend, joffset, data, flags);
987341825Sdim	if (pbp == NULL)
988314564Sdim		*head = nbp;
989314564Sdim	else
990314564Sdim		pbp->bio_next = nbp;
991314564Sdim	nbp->bio_next = NULL;
992314564Sdim	n++;
993314564Sdim	GJ_DEBUG(3, "INSERT(%p): 8 (nbp=%p pbp=%p)", *head, nbp, pbp);
994314564Sdimend:
995314564Sdim	if (g_journal_debug >= 3) {
996314564Sdim		GJQ_FOREACH(*head, cbp) {
997314564Sdim			GJ_DEBUG(3, "ELEMENT: %p (%jd, %jd, %jd, %p)", cbp,
998314564Sdim			    (intmax_t)cbp->bio_offset,
999254721Semaste			    (intmax_t)cbp->bio_length,
1000314564Sdim			    (intmax_t)cbp->bio_joffset, cbp->bio_data);
1001314564Sdim		}
1002254721Semaste		GJ_DEBUG(3, "INSERT(%p): DONE %d", *head, n);
1003254721Semaste	}
1004360784Sdim	return (n);
1005353358Sdim}
1006360784Sdim
1007314564Sdim/*
1008360784Sdim * The function combines neighbour bios trying to squeeze as much data as
1009321369Sdim * possible into one bio.
1010321369Sdim *
1011314564Sdim * The function returns the number of bios combined (negative value).
1012314564Sdim */
1013254721Semastestatic int
1014314564Sdimg_journal_optimize(struct bio *head)
1015314564Sdim{
1016360784Sdim	struct bio *cbp, *pbp;
1017360784Sdim	int n;
1018360784Sdim
1019360784Sdim	n = 0;
1020314564Sdim	pbp = NULL;
1021314564Sdim	GJQ_FOREACH(head, cbp) {
1022314564Sdim		/* Skip bios which has to be read first. */
1023314564Sdim		if (cbp->bio_data == NULL) {
1024254721Semaste			pbp = NULL;
1025254721Semaste			continue;
1026360784Sdim		}
1027360784Sdim		/* There is no previous bio yet. */
1028360784Sdim		if (pbp == NULL) {
1029360784Sdim			pbp = cbp;
1030321369Sdim			continue;
1031321369Sdim		}
1032314564Sdim		/* Is this a neighbour bio? */
1033314564Sdim		if (pbp->bio_offset + pbp->bio_length != cbp->bio_offset) {
1034254721Semaste			/* Be sure that bios queue is sorted. */
1035314564Sdim			KASSERT(pbp->bio_offset + pbp->bio_length < cbp->bio_offset,
1036314564Sdim			    ("poffset=%jd plength=%jd coffset=%jd",
1037254721Semaste			    (intmax_t)pbp->bio_offset,
1038360784Sdim			    (intmax_t)pbp->bio_length,
1039360784Sdim			    (intmax_t)cbp->bio_offset));
1040360784Sdim			pbp = cbp;
1041314564Sdim			continue;
1042314564Sdim		}
1043314564Sdim		/* Be sure we don't end up with too big bio. */
1044314564Sdim		if (pbp->bio_length + cbp->bio_length > MAXPHYS) {
1045254721Semaste			pbp = cbp;
1046254721Semaste			continue;
1047360784Sdim		}
1048360784Sdim		/* Ok, we can join bios. */
1049360784Sdim		GJ_LOGREQ(4, pbp, "Join: ");
1050360784Sdim		GJ_LOGREQ(4, cbp, "and: ");
1051321369Sdim		pbp->bio_data = gj_realloc(pbp->bio_data,
1052321369Sdim		    pbp->bio_length + cbp->bio_length, pbp->bio_length);
1053314564Sdim		bcopy(cbp->bio_data, pbp->bio_data + pbp->bio_length,
1054314564Sdim		    cbp->bio_length);
1055296417Sdim		gj_free(cbp->bio_data, cbp->bio_length);
1056353358Sdim		pbp->bio_length += cbp->bio_length;
1057314564Sdim		pbp->bio_next = cbp->bio_next;
1058314564Sdim		g_destroy_bio(cbp);
1059314564Sdim		cbp = pbp;
1060314564Sdim		g_journal_stats_combined_ios++;
1061314564Sdim		n--;
1062314564Sdim		GJ_LOGREQ(4, pbp, "Got: ");
1063314564Sdim	}
1064314564Sdim	return (n);
1065314564Sdim}
1066254721Semaste
1067314564Sdim/*
1068314564Sdim * TODO: Update comment.
1069314564Sdim * These are functions responsible for copying one portion of data from journal
1070314564Sdim * to the destination provider.
1071314564Sdim * The order goes like this:
1072314564Sdim * 1. Read the header, which contains informations about data blocks
1073254721Semaste *    following it.
1074254721Semaste * 2. Read the data blocks from the journal.
1075360784Sdim * 3. Write the data blocks on the data provider.
1076344779Sdim *
1077344779Sdim * g_journal_copy_start()
1078344779Sdim * g_journal_copy_done() - got finished write request, logs potential errors.
1079344779Sdim */
1080344779Sdim
1081344779Sdim/*
1082344779Sdim * When there is no data in cache, this function is used to read it.
1083344779Sdim */
1084314564Sdimstatic void
1085314564Sdimg_journal_read_first(struct g_journal_softc *sc, struct bio *bp)
1086314564Sdim{
1087314564Sdim	struct bio *cbp;
1088314564Sdim
1089314564Sdim	/*
1090314564Sdim	 * We were short in memory, so data was freed.
1091314564Sdim	 * In that case we need to read it back from journal.
1092314564Sdim	 */
1093314564Sdim	cbp = g_alloc_bio();
1094314564Sdim	cbp->bio_cflags = bp->bio_cflags;
1095314564Sdim	cbp->bio_parent = bp;
1096314564Sdim	cbp->bio_offset = bp->bio_joffset;
1097314564Sdim	cbp->bio_length = bp->bio_length;
1098288943Sdim	cbp->bio_data = gj_malloc(bp->bio_length, M_WAITOK);
1099314564Sdim	cbp->bio_cmd = BIO_READ;
1100353358Sdim	cbp->bio_done = g_journal_std_done;
1101314564Sdim	GJ_LOGREQ(4, cbp, "READ FIRST");
1102314564Sdim	g_io_request(cbp, sc->sc_jconsumer);
1103314564Sdim	g_journal_cache_misses++;
1104314564Sdim}
1105288943Sdim
1106314564Sdimstatic void
1107314564Sdimg_journal_copy_send(struct g_journal_softc *sc)
1108254721Semaste{
1109254721Semaste	struct bio *bioq, *bp, *lbp;
1110314564Sdim
1111353358Sdim	bioq = lbp = NULL;
1112314564Sdim	mtx_lock(&sc->sc_mtx);
1113341825Sdim	for (; sc->sc_copy_in_progress < g_journal_parallel_copies;) {
1114314564Sdim		bp = GJQ_FIRST(sc->sc_inactive.jj_queue);
1115314564Sdim		if (bp == NULL)
1116314564Sdim			break;
1117341825Sdim		GJQ_REMOVE(sc->sc_inactive.jj_queue, bp);
1118341825Sdim		sc->sc_copy_in_progress++;
1119353358Sdim		GJQ_INSERT_AFTER(bioq, bp, lbp);
1120314564Sdim		lbp = bp;
1121360784Sdim	}
1122314564Sdim	mtx_unlock(&sc->sc_mtx);
1123314564Sdim	if (g_journal_do_optimize)
1124314564Sdim		sc->sc_copy_in_progress += g_journal_optimize(bioq);
1125314564Sdim	while ((bp = GJQ_FIRST(bioq)) != NULL) {
1126314564Sdim		GJQ_REMOVE(bioq, bp);
1127314564Sdim		GJQ_INSERT_HEAD(sc->sc_copy_queue, bp);
1128314564Sdim		bp->bio_cflags = GJ_BIO_COPY;
1129314564Sdim		if (bp->bio_data == NULL)
1130341825Sdim			g_journal_read_first(sc, bp);
1131314564Sdim		else {
1132254721Semaste			bp->bio_joffset = 0;
1133314564Sdim			GJ_LOGREQ(4, bp, "SEND");
1134314564Sdim			g_io_request(bp, sc->sc_dconsumer);
1135314564Sdim		}
1136314564Sdim	}
1137314564Sdim}
1138314564Sdim
1139314564Sdimstatic void
1140353358Sdimg_journal_copy_start(struct g_journal_softc *sc)
1141314564Sdim{
1142314564Sdim
1143314564Sdim	/*
1144314564Sdim	 * Remember in metadata that we're starting to copy journaled data
1145314564Sdim	 * to the data provider.
1146314564Sdim	 * In case of power failure, we will copy these data once again on boot.
1147314564Sdim	 */
1148288943Sdim	if (!sc->sc_journal_copying) {
1149314564Sdim		sc->sc_journal_copying = 1;
1150288943Sdim		GJ_DEBUG(1, "Starting copy of journal.");
1151314564Sdim		g_journal_metadata_update(sc);
1152288943Sdim	}
1153314564Sdim	g_journal_copy_send(sc);
1154254721Semaste}
1155314564Sdim
1156288943Sdim/*
1157314564Sdim * Data block has been read from the journal provider.
1158341825Sdim */
1159341825Sdimstatic int
1160344779Sdimg_journal_copy_read_done(struct bio *bp)
1161314564Sdim{
1162314564Sdim	struct g_journal_softc *sc;
1163314564Sdim	struct g_consumer *cp;
1164314564Sdim	struct bio *pbp;
1165314564Sdim
1166314564Sdim	KASSERT(bp->bio_cflags == GJ_BIO_COPY,
1167314564Sdim	    ("Invalid bio (%d != %d).", bp->bio_cflags, GJ_BIO_COPY));
1168314564Sdim
1169314564Sdim	sc = bp->bio_from->geom->softc;
1170314564Sdim	pbp = bp->bio_parent;
1171314564Sdim
1172254721Semaste	if (bp->bio_error != 0) {
1173254721Semaste		GJ_DEBUG(0, "Error while reading data from %s (error=%d).",
1174360784Sdim		    bp->bio_to->name, bp->bio_error);
1175353358Sdim		/*
1176360784Sdim		 * We will not be able to deliver WRITE request as well.
1177309124Sdim		 */
1178314564Sdim		gj_free(bp->bio_data, bp->bio_length);
1179360784Sdim		g_destroy_bio(pbp);
1180344779Sdim		g_destroy_bio(bp);
1181360784Sdim		sc->sc_copy_in_progress--;
1182344779Sdim		return (1);
1183344779Sdim	}
1184344779Sdim	pbp->bio_data = bp->bio_data;
1185360784Sdim	cp = sc->sc_dconsumer;
1186254721Semaste	g_io_request(pbp, cp);
1187360784Sdim	GJ_LOGREQ(4, bp, "READ DONE");
1188360784Sdim	g_destroy_bio(bp);
1189360784Sdim	return (0);
1190360784Sdim}
1191360784Sdim
1192360784Sdim/*
1193360784Sdim * Data block has been written to the data provider.
1194360784Sdim */
1195254721Semastestatic void
1196254721Semasteg_journal_copy_write_done(struct bio *bp)
1197254721Semaste{
1198314564Sdim	struct g_journal_softc *sc;
1199314564Sdim
1200314564Sdim	KASSERT(bp->bio_cflags == GJ_BIO_COPY,
1201314564Sdim	    ("Invalid bio (%d != %d).", bp->bio_cflags, GJ_BIO_COPY));
1202254721Semaste
1203254721Semaste	sc = bp->bio_from->geom->softc;
1204254721Semaste	sc->sc_copy_in_progress--;
1205314564Sdim
1206314564Sdim	if (bp->bio_error != 0) {
1207254721Semaste		GJ_LOGREQ(0, bp, "[copy] Error while writing data (error=%d)",
1208254721Semaste		    bp->bio_error);
1209254721Semaste	}
1210314564Sdim	GJQ_REMOVE(sc->sc_copy_queue, bp);
1211353358Sdim	gj_free(bp->bio_data, bp->bio_length);
1212314564Sdim	GJ_LOGREQ(4, bp, "DONE");
1213360784Sdim	g_destroy_bio(bp);
1214314564Sdim
1215254721Semaste	if (sc->sc_copy_in_progress == 0) {
1216344779Sdim		/*
1217344779Sdim		 * This was the last write request for this journal.
1218254721Semaste		 */
1219344779Sdim		GJ_DEBUG(1, "Data has been copied.");
1220344779Sdim		sc->sc_journal_copying = 0;
1221254721Semaste	}
1222314564Sdim}
1223254721Semaste
1224254721Semastestatic void g_journal_flush_done(struct bio *bp);
1225344779Sdim
1226344779Sdim/*
1227344779Sdim * Flush one record onto active journal provider.
1228344779Sdim */
1229344779Sdimstatic void
1230344779Sdimg_journal_flush(struct g_journal_softc *sc)
1231344779Sdim{
1232254721Semaste	struct g_journal_record_header hdr;
1233314564Sdim	struct g_journal_entry *ent;
1234314564Sdim	struct g_provider *pp;
1235254721Semaste	struct bio **bioq;
1236254721Semaste	struct bio *bp, *fbp, *pbp;
1237314564Sdim	off_t joffset, size;
1238254721Semaste	u_char *data, hash[16];
1239254721Semaste	MD5_CTX ctx;
1240314564Sdim	u_int i;
1241314564Sdim
1242314564Sdim	if (sc->sc_current_count == 0)
1243314564Sdim		return;
1244314564Sdim
1245314564Sdim	size = 0;
1246314564Sdim	pp = sc->sc_jprovider;
1247314564Sdim	GJ_VALIDATE_OFFSET(sc->sc_journal_offset, sc);
1248314564Sdim	joffset = sc->sc_journal_offset;
1249314564Sdim
1250254721Semaste	GJ_DEBUG(2, "Storing %d journal entries on %s at %jd.",
1251314564Sdim	    sc->sc_current_count, pp->name, (intmax_t)joffset);
1252314564Sdim
1253254721Semaste	/*
1254314564Sdim	 * Store 'journal id', so we know to which journal this record belongs.
1255314564Sdim	 */
1256254721Semaste	hdr.jrh_journal_id = sc->sc_journal_id;
1257254721Semaste	/* Could be less than g_journal_record_entries if called due timeout. */
1258254721Semaste	hdr.jrh_nentries = MIN(sc->sc_current_count, g_journal_record_entries);
1259314564Sdim	strlcpy(hdr.jrh_magic, GJ_RECORD_HEADER_MAGIC, sizeof(hdr.jrh_magic));
1260314564Sdim
1261314564Sdim	bioq = &sc->sc_active.jj_queue;
1262314564Sdim	pbp = sc->sc_flush_queue;
1263314564Sdim
1264314564Sdim	fbp = g_alloc_bio();
1265314564Sdim	fbp->bio_parent = NULL;
1266314564Sdim	fbp->bio_cflags = GJ_BIO_JOURNAL;
1267314564Sdim	fbp->bio_offset = -1;
1268254721Semaste	fbp->bio_joffset = joffset;
1269314564Sdim	fbp->bio_length = pp->sectorsize;
1270353358Sdim	fbp->bio_cmd = BIO_WRITE;
1271254721Semaste	fbp->bio_done = g_journal_std_done;
1272254721Semaste	GJQ_INSERT_AFTER(sc->sc_flush_queue, fbp, pbp);
1273314564Sdim	pbp = fbp;
1274314564Sdim	fbp->bio_to = pp;
1275314564Sdim	GJ_LOGREQ(4, fbp, "FLUSH_OUT");
1276314564Sdim	joffset += pp->sectorsize;
1277314564Sdim	sc->sc_flush_count++;
1278314564Sdim	if (sc->sc_flags & GJF_DEVICE_CHECKSUM)
1279314564Sdim		MD5Init(&ctx);
1280314564Sdim
1281314564Sdim	for (i = 0; i < hdr.jrh_nentries; i++) {
1282314564Sdim		bp = sc->sc_current_queue;
1283314564Sdim		KASSERT(bp != NULL, ("NULL bp"));
1284314564Sdim		bp->bio_to = pp;
1285314564Sdim		GJ_LOGREQ(4, bp, "FLUSHED");
1286360784Sdim		sc->sc_current_queue = bp->bio_next;
1287254721Semaste		bp->bio_next = NULL;
1288314564Sdim		sc->sc_current_count--;
1289254721Semaste
1290314564Sdim		/* Add to the header. */
1291254721Semaste		ent = &hdr.jrh_entries[i];
1292254721Semaste		ent->je_offset = bp->bio_offset;
1293296417Sdim		ent->je_joffset = joffset;
1294314564Sdim		ent->je_length = bp->bio_length;
1295314564Sdim		size += ent->je_length;
1296314564Sdim
1297314564Sdim		data = bp->bio_data;
1298314564Sdim		if (sc->sc_flags & GJF_DEVICE_CHECKSUM)
1299314564Sdim			MD5Update(&ctx, data, ent->je_length);
1300254721Semaste		bzero(bp, sizeof(*bp));
1301254721Semaste		bp->bio_cflags = GJ_BIO_JOURNAL;
1302296417Sdim		bp->bio_offset = ent->je_offset;
1303314564Sdim		bp->bio_joffset = ent->je_joffset;
1304314564Sdim		bp->bio_length = ent->je_length;
1305314564Sdim		bp->bio_data = data;
1306314564Sdim		bp->bio_cmd = BIO_WRITE;
1307314564Sdim		bp->bio_done = g_journal_std_done;
1308314564Sdim		GJQ_INSERT_AFTER(sc->sc_flush_queue, bp, pbp);
1309254721Semaste		pbp = bp;
1310254721Semaste		bp->bio_to = pp;
1311314564Sdim		GJ_LOGREQ(4, bp, "FLUSH_OUT");
1312314564Sdim		joffset += bp->bio_length;
1313314564Sdim		sc->sc_flush_count++;
1314314564Sdim
1315314564Sdim		/*
1316314564Sdim		 * Add request to the active sc_journal_queue queue.
1317296417Sdim		 * This is our cache. After journal switch we don't have to
1318296417Sdim		 * read the data from the inactive journal, because we keep
1319314564Sdim		 * it in memory.
1320314564Sdim		 */
1321314564Sdim		g_journal_insert(bioq, ent->je_offset,
1322314564Sdim		    ent->je_offset + ent->je_length, ent->je_joffset, data,
1323314564Sdim		    M_NOWAIT);
1324314564Sdim	}
1325314564Sdim
1326314564Sdim	/*
1327314564Sdim	 * After all requests, store valid header.
1328314564Sdim	 */
1329314564Sdim	data = gj_malloc(pp->sectorsize, M_WAITOK);
1330314564Sdim	if (sc->sc_flags & GJF_DEVICE_CHECKSUM) {
1331314564Sdim		MD5Final(hash, &ctx);
1332314564Sdim		bcopy(hash, hdr.jrh_sum, sizeof(hdr.jrh_sum));
1333314564Sdim	}
1334314564Sdim	g_journal_record_header_encode(&hdr, data);
1335254721Semaste	fbp->bio_data = data;
1336314564Sdim
1337314564Sdim	sc->sc_journal_offset = joffset;
1338314564Sdim
1339314564Sdim	g_journal_check_overflow(sc);
1340314564Sdim}
1341254721Semaste
1342254721Semaste/*
1343314564Sdim * Flush request finished.
1344314564Sdim */
1345254721Semastestatic void
1346314564Sdimg_journal_flush_done(struct bio *bp)
1347314564Sdim{
1348314564Sdim	struct g_journal_softc *sc;
1349314564Sdim	struct g_consumer *cp;
1350314564Sdim
1351314564Sdim	KASSERT((bp->bio_cflags & GJ_BIO_MASK) == GJ_BIO_JOURNAL,
1352314564Sdim	    ("Invalid bio (%d != %d).", bp->bio_cflags, GJ_BIO_JOURNAL));
1353314564Sdim
1354314564Sdim	cp = bp->bio_from;
1355314564Sdim	sc = cp->geom->softc;
1356314564Sdim	sc->sc_flush_in_progress--;
1357254721Semaste
1358254721Semaste	if (bp->bio_error != 0) {
1359254721Semaste		GJ_LOGREQ(0, bp, "[flush] Error while writing data (error=%d)",
1360254721Semaste		    bp->bio_error);
1361314564Sdim	}
1362314564Sdim	gj_free(bp->bio_data, bp->bio_length);
1363314564Sdim	GJ_LOGREQ(4, bp, "DONE");
1364314564Sdim	g_destroy_bio(bp);
1365314564Sdim}
1366314564Sdim
1367314564Sdimstatic void g_journal_release_delayed(struct g_journal_softc *sc);
1368314564Sdim
1369314564Sdimstatic void
1370314564Sdimg_journal_flush_send(struct g_journal_softc *sc)
1371314564Sdim{
1372314564Sdim	struct g_consumer *cp;
1373314564Sdim	struct bio *bioq, *bp, *lbp;
1374314564Sdim
1375314564Sdim	cp = sc->sc_jconsumer;
1376314564Sdim	bioq = lbp = NULL;
1377254721Semaste	while (sc->sc_flush_in_progress < g_journal_parallel_flushes) {
1378314564Sdim		/* Send one flush requests to the active journal. */
1379314564Sdim		bp = GJQ_FIRST(sc->sc_flush_queue);
1380254721Semaste		if (bp != NULL) {
1381254721Semaste			GJQ_REMOVE(sc->sc_flush_queue, bp);
1382314564Sdim			sc->sc_flush_count--;
1383314564Sdim			bp->bio_offset = bp->bio_joffset;
1384314564Sdim			bp->bio_joffset = 0;
1385314564Sdim			sc->sc_flush_in_progress++;
1386314564Sdim			GJQ_INSERT_AFTER(bioq, bp, lbp);
1387314564Sdim			lbp = bp;
1388254721Semaste		}
1389360784Sdim		/* Try to release delayed requests. */
1390360784Sdim		g_journal_release_delayed(sc);
1391314564Sdim		/* If there are no requests to flush, leave. */
1392314564Sdim		if (GJQ_FIRST(sc->sc_flush_queue) == NULL)
1393314564Sdim			break;
1394314564Sdim	}
1395314564Sdim	if (g_journal_do_optimize)
1396314564Sdim		sc->sc_flush_in_progress += g_journal_optimize(bioq);
1397314564Sdim	while ((bp = GJQ_FIRST(bioq)) != NULL) {
1398314564Sdim		GJQ_REMOVE(bioq, bp);
1399314564Sdim		GJ_LOGREQ(3, bp, "Flush request send");
1400314564Sdim		g_io_request(bp, cp);
1401314564Sdim	}
1402314564Sdim}
1403314564Sdim
1404314564Sdimstatic void
1405254721Semasteg_journal_add_current(struct g_journal_softc *sc, struct bio *bp)
1406314564Sdim{
1407314564Sdim	int n;
1408254721Semaste
1409254721Semaste	GJ_LOGREQ(4, bp, "CURRENT %d", sc->sc_current_count);
1410314564Sdim	n = g_journal_insert_bio(&sc->sc_current_queue, bp, M_WAITOK);
1411314564Sdim	sc->sc_current_count += n;
1412314564Sdim	n = g_journal_optimize(sc->sc_current_queue);
1413314564Sdim	sc->sc_current_count += n;
1414314564Sdim	/*
1415353358Sdim	 * For requests which are added to the current queue we deliver
1416254721Semaste	 * response immediately.
1417254721Semaste	 */
1418254721Semaste	bp->bio_completed = bp->bio_length;
1419314564Sdim	g_io_deliver(bp, 0);
1420314564Sdim	if (sc->sc_current_count >= g_journal_record_entries) {
1421314564Sdim		/*
1422314564Sdim		 * Let's flush one record onto active journal provider.
1423314564Sdim		 */
1424314564Sdim		g_journal_flush(sc);
1425314564Sdim	}
1426314564Sdim}
1427314564Sdim
1428314564Sdimstatic void
1429314564Sdimg_journal_release_delayed(struct g_journal_softc *sc)
1430314564Sdim{
1431314564Sdim	struct bio *bp;
1432314564Sdim
1433254721Semaste	for (;;) {
1434314564Sdim		/* The flush queue is full, exit. */
1435254721Semaste		if (sc->sc_flush_count >= g_journal_accept_immediately)
1436314564Sdim			return;
1437314564Sdim		bp = bioq_takefirst(&sc->sc_delayed_queue);
1438254721Semaste		if (bp == NULL)
1439			return;
1440		sc->sc_delayed_count--;
1441		g_journal_add_current(sc, bp);
1442	}
1443}
1444
1445/*
1446 * Add I/O request to the current queue. If we have enough requests for one
1447 * journal record we flush them onto active journal provider.
1448 */
1449static void
1450g_journal_add_request(struct g_journal_softc *sc, struct bio *bp)
1451{
1452
1453	/*
1454	 * The flush queue is full, we need to delay the request.
1455	 */
1456	if (sc->sc_delayed_count > 0 ||
1457	    sc->sc_flush_count >= g_journal_accept_immediately) {
1458		GJ_LOGREQ(4, bp, "DELAYED");
1459		bioq_insert_tail(&sc->sc_delayed_queue, bp);
1460		sc->sc_delayed_count++;
1461		return;
1462	}
1463
1464	KASSERT(TAILQ_EMPTY(&sc->sc_delayed_queue.queue),
1465	    ("DELAYED queue not empty."));
1466	g_journal_add_current(sc, bp);
1467}
1468
1469static void g_journal_read_done(struct bio *bp);
1470
1471/*
1472 * Try to find requested data in cache.
1473 */
1474static struct bio *
1475g_journal_read_find(struct bio *head, int sorted, struct bio *pbp, off_t ostart,
1476    off_t oend)
1477{
1478	off_t cstart, cend;
1479	struct bio *bp;
1480
1481	GJQ_FOREACH(head, bp) {
1482		if (bp->bio_offset == -1)
1483			continue;
1484		cstart = MAX(ostart, bp->bio_offset);
1485		cend = MIN(oend, bp->bio_offset + bp->bio_length);
1486		if (cend <= ostart)
1487			continue;
1488		else if (cstart >= oend) {
1489			if (!sorted)
1490				continue;
1491			else {
1492				bp = NULL;
1493				break;
1494			}
1495		}
1496		if (bp->bio_data == NULL)
1497			break;
1498		GJ_DEBUG(3, "READ(%p): (%jd, %jd) (bp=%p)", head, cstart, cend,
1499		    bp);
1500		bcopy(bp->bio_data + cstart - bp->bio_offset,
1501		    pbp->bio_data + cstart - pbp->bio_offset, cend - cstart);
1502		pbp->bio_completed += cend - cstart;
1503		if (pbp->bio_completed == pbp->bio_length) {
1504			/*
1505			 * Cool, the whole request was in cache, deliver happy
1506			 * message.
1507			 */
1508			g_io_deliver(pbp, 0);
1509			return (pbp);
1510		}
1511		break;
1512	}
1513	return (bp);
1514}
1515
1516/*
1517 * Try to find requested data in cache.
1518 */
1519static struct bio *
1520g_journal_read_queue_find(struct bio_queue *head, struct bio *pbp, off_t ostart,
1521    off_t oend)
1522{
1523	off_t cstart, cend;
1524	struct bio *bp;
1525
1526	TAILQ_FOREACH(bp, head, bio_queue) {
1527		cstart = MAX(ostart, bp->bio_offset);
1528		cend = MIN(oend, bp->bio_offset + bp->bio_length);
1529		if (cend <= ostart)
1530			continue;
1531		else if (cstart >= oend)
1532			continue;
1533		KASSERT(bp->bio_data != NULL,
1534		    ("%s: bio_data == NULL", __func__));
1535		GJ_DEBUG(3, "READ(%p): (%jd, %jd) (bp=%p)", head, cstart, cend,
1536		    bp);
1537		bcopy(bp->bio_data + cstart - bp->bio_offset,
1538		    pbp->bio_data + cstart - pbp->bio_offset, cend - cstart);
1539		pbp->bio_completed += cend - cstart;
1540		if (pbp->bio_completed == pbp->bio_length) {
1541			/*
1542			 * Cool, the whole request was in cache, deliver happy
1543			 * message.
1544			 */
1545			g_io_deliver(pbp, 0);
1546			return (pbp);
1547		}
1548		break;
1549	}
1550	return (bp);
1551}
1552
1553/*
1554 * This function is used for colecting data on read.
1555 * The complexity is because parts of the data can be stored in four different
1556 * places:
1557 * - in delayed requests
1558 * - in memory - the data not yet send to the active journal provider
1559 * - in requests which are going to be sent to the active journal
1560 * - in the active journal
1561 * - in the inactive journal
1562 * - in the data provider
1563 */
1564static void
1565g_journal_read(struct g_journal_softc *sc, struct bio *pbp, off_t ostart,
1566    off_t oend)
1567{
1568	struct bio *bp, *nbp, *head;
1569	off_t cstart, cend;
1570	u_int i, sorted = 0;
1571
1572	GJ_DEBUG(3, "READ: (%jd, %jd)", ostart, oend);
1573
1574	cstart = cend = -1;
1575	bp = NULL;
1576	head = NULL;
1577	for (i = 0; i <= 5; i++) {
1578		switch (i) {
1579		case 0:	/* Delayed requests. */
1580			head = NULL;
1581			sorted = 0;
1582			break;
1583		case 1:	/* Not-yet-send data. */
1584			head = sc->sc_current_queue;
1585			sorted = 1;
1586			break;
1587		case 2:	/* In-flight to the active journal. */
1588			head = sc->sc_flush_queue;
1589			sorted = 0;
1590			break;
1591		case 3:	/* Active journal. */
1592			head = sc->sc_active.jj_queue;
1593			sorted = 1;
1594			break;
1595		case 4:	/* Inactive journal. */
1596			/*
1597			 * XXX: Here could be a race with g_journal_lowmem().
1598			 */
1599			head = sc->sc_inactive.jj_queue;
1600			sorted = 1;
1601			break;
1602		case 5:	/* In-flight to the data provider. */
1603			head = sc->sc_copy_queue;
1604			sorted = 0;
1605			break;
1606		default:
1607			panic("gjournal %s: i=%d", __func__, i);
1608		}
1609		if (i == 0)
1610			bp = g_journal_read_queue_find(&sc->sc_delayed_queue.queue, pbp, ostart, oend);
1611		else
1612			bp = g_journal_read_find(head, sorted, pbp, ostart, oend);
1613		if (bp == pbp) { /* Got the whole request. */
1614			GJ_DEBUG(2, "Got the whole request from %u.", i);
1615			return;
1616		} else if (bp != NULL) {
1617			cstart = MAX(ostart, bp->bio_offset);
1618			cend = MIN(oend, bp->bio_offset + bp->bio_length);
1619			GJ_DEBUG(2, "Got part of the request from %u (%jd-%jd).",
1620			    i, (intmax_t)cstart, (intmax_t)cend);
1621			break;
1622		}
1623	}
1624	if (bp != NULL) {
1625		if (bp->bio_data == NULL) {
1626			nbp = g_duplicate_bio(pbp);
1627			nbp->bio_cflags = GJ_BIO_READ;
1628			nbp->bio_data =
1629			    pbp->bio_data + cstart - pbp->bio_offset;
1630			nbp->bio_offset =
1631			    bp->bio_joffset + cstart - bp->bio_offset;
1632			nbp->bio_length = cend - cstart;
1633			nbp->bio_done = g_journal_read_done;
1634			g_io_request(nbp, sc->sc_jconsumer);
1635		}
1636		/*
1637		 * If we don't have the whole request yet, call g_journal_read()
1638		 * recursively.
1639		 */
1640		if (ostart < cstart)
1641			g_journal_read(sc, pbp, ostart, cstart);
1642		if (oend > cend)
1643			g_journal_read(sc, pbp, cend, oend);
1644	} else {
1645		/*
1646		 * No data in memory, no data in journal.
1647		 * Its time for asking data provider.
1648		 */
1649		GJ_DEBUG(3, "READ(data): (%jd, %jd)", ostart, oend);
1650		nbp = g_duplicate_bio(pbp);
1651		nbp->bio_cflags = GJ_BIO_READ;
1652		nbp->bio_data = pbp->bio_data + ostart - pbp->bio_offset;
1653		nbp->bio_offset = ostart;
1654		nbp->bio_length = oend - ostart;
1655		nbp->bio_done = g_journal_read_done;
1656		g_io_request(nbp, sc->sc_dconsumer);
1657		/* We have the whole request, return here. */
1658		return;
1659	}
1660}
1661
1662/*
1663 * Function responsible for handling finished READ requests.
1664 * Actually, g_std_done() could be used here, the only difference is that we
1665 * log error.
1666 */
1667static void
1668g_journal_read_done(struct bio *bp)
1669{
1670	struct bio *pbp;
1671
1672	KASSERT(bp->bio_cflags == GJ_BIO_READ,
1673	    ("Invalid bio (%d != %d).", bp->bio_cflags, GJ_BIO_READ));
1674
1675	pbp = bp->bio_parent;
1676	pbp->bio_inbed++;
1677	pbp->bio_completed += bp->bio_length;
1678
1679	if (bp->bio_error != 0) {
1680		if (pbp->bio_error == 0)
1681			pbp->bio_error = bp->bio_error;
1682		GJ_DEBUG(0, "Error while reading data from %s (error=%d).",
1683		    bp->bio_to->name, bp->bio_error);
1684	}
1685	g_destroy_bio(bp);
1686	if (pbp->bio_children == pbp->bio_inbed &&
1687	    pbp->bio_completed == pbp->bio_length) {
1688		/* We're done. */
1689		g_io_deliver(pbp, 0);
1690	}
1691}
1692
1693/*
1694 * Deactive current journal and active next one.
1695 */
1696static void
1697g_journal_switch(struct g_journal_softc *sc)
1698{
1699	struct g_provider *pp;
1700
1701	if (JEMPTY(sc)) {
1702		GJ_DEBUG(3, "No need for %s switch.", sc->sc_name);
1703		pp = LIST_FIRST(&sc->sc_geom->provider);
1704		if (!(sc->sc_flags & GJF_DEVICE_CLEAN) && pp->acw == 0) {
1705			sc->sc_flags |= GJF_DEVICE_CLEAN;
1706			GJ_DEBUG(1, "Marking %s as clean.", sc->sc_name);
1707			g_journal_metadata_update(sc);
1708		}
1709	} else {
1710		GJ_DEBUG(3, "Switching journal %s.", sc->sc_geom->name);
1711
1712		pp = sc->sc_jprovider;
1713
1714		sc->sc_journal_previous_id = sc->sc_journal_id;
1715
1716		sc->sc_journal_id = sc->sc_journal_next_id;
1717		sc->sc_journal_next_id = arc4random();
1718
1719		GJ_VALIDATE_OFFSET(sc->sc_journal_offset, sc);
1720
1721		g_journal_write_header(sc);
1722
1723		sc->sc_inactive.jj_offset = sc->sc_active.jj_offset;
1724		sc->sc_inactive.jj_queue = sc->sc_active.jj_queue;
1725
1726		sc->sc_active.jj_offset =
1727		    sc->sc_journal_offset - pp->sectorsize;
1728		sc->sc_active.jj_queue = NULL;
1729
1730		/*
1731		 * Switch is done, start copying data from the (now) inactive
1732		 * journal to the data provider.
1733		 */
1734		g_journal_copy_start(sc);
1735	}
1736	mtx_lock(&sc->sc_mtx);
1737	sc->sc_flags &= ~GJF_DEVICE_SWITCH;
1738	mtx_unlock(&sc->sc_mtx);
1739}
1740
1741static void
1742g_journal_initialize(struct g_journal_softc *sc)
1743{
1744
1745	sc->sc_journal_id = arc4random();
1746	sc->sc_journal_next_id = arc4random();
1747	sc->sc_journal_previous_id = sc->sc_journal_id;
1748	sc->sc_journal_offset = sc->sc_jstart;
1749	sc->sc_inactive.jj_offset = sc->sc_jstart;
1750	g_journal_write_header(sc);
1751	sc->sc_active.jj_offset = sc->sc_jstart;
1752}
1753
1754static void
1755g_journal_mark_as_dirty(struct g_journal_softc *sc)
1756{
1757	const struct g_journal_desc *desc;
1758	int i;
1759
1760	GJ_DEBUG(1, "Marking file system %s as dirty.", sc->sc_name);
1761	for (i = 0; (desc = g_journal_filesystems[i]) != NULL; i++)
1762		desc->jd_dirty(sc->sc_dconsumer);
1763}
1764
1765/*
1766 * Function read record header from the given journal.
1767 * It is very simlar to g_read_data(9), but it doesn't allocate memory for bio
1768 * and data on every call.
1769 */
1770static int
1771g_journal_sync_read(struct g_consumer *cp, struct bio *bp, off_t offset,
1772    void *data)
1773{
1774	int error;
1775
1776	bzero(bp, sizeof(*bp));
1777	bp->bio_cmd = BIO_READ;
1778	bp->bio_done = NULL;
1779	bp->bio_offset = offset;
1780	bp->bio_length = cp->provider->sectorsize;
1781	bp->bio_data = data;
1782	g_io_request(bp, cp);
1783	error = biowait(bp, "gjs_read");
1784	return (error);
1785}
1786
1787#if 0
1788/*
1789 * Function is called when we start the journal device and we detect that
1790 * one of the journals was not fully copied.
1791 * The purpose of this function is to read all records headers from journal
1792 * and placed them in the inactive queue, so we can start journal
1793 * synchronization process and the journal provider itself.
1794 * Design decision was taken to not synchronize the whole journal here as it
1795 * can take too much time. Reading headers only and delaying synchronization
1796 * process until after journal provider is started should be the best choice.
1797 */
1798#endif
1799
1800static void
1801g_journal_sync(struct g_journal_softc *sc)
1802{
1803	struct g_journal_record_header rhdr;
1804	struct g_journal_entry *ent;
1805	struct g_journal_header jhdr;
1806	struct g_consumer *cp;
1807	struct bio *bp, *fbp, *tbp;
1808	off_t joffset, offset;
1809	u_char *buf, sum[16];
1810	uint64_t id;
1811	MD5_CTX ctx;
1812	int error, found, i;
1813
1814	found = 0;
1815	fbp = NULL;
1816	cp = sc->sc_jconsumer;
1817	bp = g_alloc_bio();
1818	buf = gj_malloc(cp->provider->sectorsize, M_WAITOK);
1819	offset = joffset = sc->sc_inactive.jj_offset = sc->sc_journal_offset;
1820
1821	GJ_DEBUG(2, "Looking for termination at %jd.", (intmax_t)joffset);
1822
1823	/*
1824	 * Read and decode first journal header.
1825	 */
1826	error = g_journal_sync_read(cp, bp, offset, buf);
1827	if (error != 0) {
1828		GJ_DEBUG(0, "Error while reading journal header from %s.",
1829		    cp->provider->name);
1830		goto end;
1831	}
1832	error = g_journal_header_decode(buf, &jhdr);
1833	if (error != 0) {
1834		GJ_DEBUG(0, "Cannot decode journal header from %s.",
1835		    cp->provider->name);
1836		goto end;
1837	}
1838	id = sc->sc_journal_id;
1839	if (jhdr.jh_journal_id != sc->sc_journal_id) {
1840		GJ_DEBUG(1, "Journal ID mismatch at %jd (0x%08x != 0x%08x).",
1841		    (intmax_t)offset, (u_int)jhdr.jh_journal_id, (u_int)id);
1842		goto end;
1843	}
1844	offset += cp->provider->sectorsize;
1845	id = sc->sc_journal_next_id = jhdr.jh_journal_next_id;
1846
1847	for (;;) {
1848		/*
1849		 * If the biggest record won't fit, look for a record header or
1850		 * journal header from the begining.
1851		 */
1852		GJ_VALIDATE_OFFSET(offset, sc);
1853		error = g_journal_sync_read(cp, bp, offset, buf);
1854		if (error != 0) {
1855			/*
1856			 * Not good. Having an error while reading header
1857			 * means, that we cannot read next headers and in
1858			 * consequence we cannot find termination.
1859			 */
1860			GJ_DEBUG(0,
1861			    "Error while reading record header from %s.",
1862			    cp->provider->name);
1863			break;
1864		}
1865
1866		error = g_journal_record_header_decode(buf, &rhdr);
1867		if (error != 0) {
1868			GJ_DEBUG(2, "Not a record header at %jd (error=%d).",
1869			    (intmax_t)offset, error);
1870			/*
1871			 * This is not a record header.
1872			 * If we are lucky, this is next journal header.
1873			 */
1874			error = g_journal_header_decode(buf, &jhdr);
1875			if (error != 0) {
1876				GJ_DEBUG(1, "Not a journal header at %jd (error=%d).",
1877				    (intmax_t)offset, error);
1878				/*
1879				 * Nope, this is not journal header, which
1880				 * bascially means that journal is not
1881				 * terminated properly.
1882				 */
1883				error = ENOENT;
1884				break;
1885			}
1886			/*
1887			 * Ok. This is header of _some_ journal. Now we need to
1888			 * verify if this is header of the _next_ journal.
1889			 */
1890			if (jhdr.jh_journal_id != id) {
1891				GJ_DEBUG(1, "Journal ID mismatch at %jd "
1892				    "(0x%08x != 0x%08x).", (intmax_t)offset,
1893				    (u_int)jhdr.jh_journal_id, (u_int)id);
1894				error = ENOENT;
1895				break;
1896			}
1897
1898			/* Found termination. */
1899			found++;
1900			GJ_DEBUG(1, "Found termination at %jd (id=0x%08x).",
1901			    (intmax_t)offset, (u_int)id);
1902			sc->sc_active.jj_offset = offset;
1903			sc->sc_journal_offset =
1904			    offset + cp->provider->sectorsize;
1905			sc->sc_journal_id = id;
1906			id = sc->sc_journal_next_id = jhdr.jh_journal_next_id;
1907
1908			while ((tbp = fbp) != NULL) {
1909				fbp = tbp->bio_next;
1910				GJ_LOGREQ(3, tbp, "Adding request.");
1911				g_journal_insert_bio(&sc->sc_inactive.jj_queue,
1912				    tbp, M_WAITOK);
1913			}
1914
1915			/* Skip journal's header. */
1916			offset += cp->provider->sectorsize;
1917			continue;
1918		}
1919
1920		/* Skip record's header. */
1921		offset += cp->provider->sectorsize;
1922
1923		/*
1924		 * Add information about every record entry to the inactive
1925		 * queue.
1926		 */
1927		if (sc->sc_flags & GJF_DEVICE_CHECKSUM)
1928			MD5Init(&ctx);
1929		for (i = 0; i < rhdr.jrh_nentries; i++) {
1930			ent = &rhdr.jrh_entries[i];
1931			GJ_DEBUG(3, "Insert entry: %jd %jd.",
1932			    (intmax_t)ent->je_offset, (intmax_t)ent->je_length);
1933			g_journal_insert(&fbp, ent->je_offset,
1934			    ent->je_offset + ent->je_length, ent->je_joffset,
1935			    NULL, M_WAITOK);
1936			if (sc->sc_flags & GJF_DEVICE_CHECKSUM) {
1937				u_char *buf2;
1938
1939				/*
1940				 * TODO: Should use faster function (like
1941				 *       g_journal_sync_read()).
1942				 */
1943				buf2 = g_read_data(cp, offset, ent->je_length,
1944				    NULL);
1945				if (buf2 == NULL)
1946					GJ_DEBUG(0, "Cannot read data at %jd.",
1947					    (intmax_t)offset);
1948				else {
1949					MD5Update(&ctx, buf2, ent->je_length);
1950					g_free(buf2);
1951				}
1952			}
1953			/* Skip entry's data. */
1954			offset += ent->je_length;
1955		}
1956		if (sc->sc_flags & GJF_DEVICE_CHECKSUM) {
1957			MD5Final(sum, &ctx);
1958			if (bcmp(sum, rhdr.jrh_sum, sizeof(rhdr.jrh_sum)) != 0) {
1959				GJ_DEBUG(0, "MD5 hash mismatch at %jd!",
1960				    (intmax_t)offset);
1961			}
1962		}
1963	}
1964end:
1965	gj_free(bp->bio_data, cp->provider->sectorsize);
1966	g_destroy_bio(bp);
1967
1968	/* Remove bios from unterminated journal. */
1969	while ((tbp = fbp) != NULL) {
1970		fbp = tbp->bio_next;
1971		g_destroy_bio(tbp);
1972	}
1973
1974	if (found < 1 && joffset > 0) {
1975		GJ_DEBUG(0, "Journal on %s is broken/corrupted. Initializing.",
1976		    sc->sc_name);
1977		while ((tbp = sc->sc_inactive.jj_queue) != NULL) {
1978			sc->sc_inactive.jj_queue = tbp->bio_next;
1979			g_destroy_bio(tbp);
1980		}
1981		g_journal_initialize(sc);
1982		g_journal_mark_as_dirty(sc);
1983	} else {
1984		GJ_DEBUG(0, "Journal %s consistent.", sc->sc_name);
1985		g_journal_copy_start(sc);
1986	}
1987}
1988
1989/*
1990 * Wait for requests.
1991 * If we have requests in the current queue, flush them after 3 seconds from the
1992 * last flush. In this way we don't wait forever (or for journal switch) with
1993 * storing not full records on journal.
1994 */
1995static void
1996g_journal_wait(struct g_journal_softc *sc, time_t last_write)
1997{
1998	int error, timeout;
1999
2000	GJ_DEBUG(3, "%s: enter", __func__);
2001	if (sc->sc_current_count == 0) {
2002		if (g_journal_debug < 2)
2003			msleep(sc, &sc->sc_mtx, PRIBIO | PDROP, "gj:work", 0);
2004		else {
2005			/*
2006			 * If we have debug turned on, show number of elements
2007			 * in various queues.
2008			 */
2009			for (;;) {
2010				error = msleep(sc, &sc->sc_mtx, PRIBIO,
2011				    "gj:work", hz * 3);
2012				if (error == 0) {
2013					mtx_unlock(&sc->sc_mtx);
2014					break;
2015				}
2016				GJ_DEBUG(3, "Report: current count=%d",
2017				    sc->sc_current_count);
2018				GJ_DEBUG(3, "Report: flush count=%d",
2019				    sc->sc_flush_count);
2020				GJ_DEBUG(3, "Report: flush in progress=%d",
2021				    sc->sc_flush_in_progress);
2022				GJ_DEBUG(3, "Report: copy in progress=%d",
2023				    sc->sc_copy_in_progress);
2024				GJ_DEBUG(3, "Report: delayed=%d",
2025				    sc->sc_delayed_count);
2026			}
2027		}
2028		GJ_DEBUG(3, "%s: exit 1", __func__);
2029		return;
2030	}
2031
2032	/*
2033	 * Flush even not full records every 3 seconds.
2034	 */
2035	timeout = (last_write + 3 - time_second) * hz;
2036	if (timeout <= 0) {
2037		mtx_unlock(&sc->sc_mtx);
2038		g_journal_flush(sc);
2039		g_journal_flush_send(sc);
2040		GJ_DEBUG(3, "%s: exit 2", __func__);
2041		return;
2042	}
2043	error = msleep(sc, &sc->sc_mtx, PRIBIO | PDROP, "gj:work", timeout);
2044	if (error == EWOULDBLOCK)
2045		g_journal_flush_send(sc);
2046	GJ_DEBUG(3, "%s: exit 3", __func__);
2047}
2048
2049/*
2050 * Worker thread.
2051 */
2052static void
2053g_journal_worker(void *arg)
2054{
2055	struct g_journal_softc *sc;
2056	struct g_geom *gp;
2057	struct g_provider *pp;
2058	struct bio *bp;
2059	time_t last_write;
2060	int type;
2061
2062	thread_lock(curthread);
2063	sched_prio(curthread, PRIBIO);
2064	thread_unlock(curthread);
2065
2066	sc = arg;
2067	type = 0;	/* gcc */
2068
2069	if (sc->sc_flags & GJF_DEVICE_CLEAN) {
2070		GJ_DEBUG(0, "Journal %s clean.", sc->sc_name);
2071		g_journal_initialize(sc);
2072	} else {
2073		g_journal_sync(sc);
2074	}
2075	/*
2076	 * Check if we can use BIO_FLUSH.
2077	 */
2078	sc->sc_bio_flush = 0;
2079	if (g_io_flush(sc->sc_jconsumer) == 0) {
2080		sc->sc_bio_flush |= GJ_FLUSH_JOURNAL;
2081		GJ_DEBUG(1, "BIO_FLUSH supported by %s.",
2082		    sc->sc_jconsumer->provider->name);
2083	} else {
2084		GJ_DEBUG(0, "BIO_FLUSH not supported by %s.",
2085		    sc->sc_jconsumer->provider->name);
2086	}
2087	if (sc->sc_jconsumer != sc->sc_dconsumer) {
2088		if (g_io_flush(sc->sc_dconsumer) == 0) {
2089			sc->sc_bio_flush |= GJ_FLUSH_DATA;
2090			GJ_DEBUG(1, "BIO_FLUSH supported by %s.",
2091			    sc->sc_dconsumer->provider->name);
2092		} else {
2093			GJ_DEBUG(0, "BIO_FLUSH not supported by %s.",
2094			    sc->sc_dconsumer->provider->name);
2095		}
2096	}
2097
2098	gp = sc->sc_geom;
2099	g_topology_lock();
2100	pp = g_new_providerf(gp, "%s.journal", sc->sc_name);
2101	pp->mediasize = sc->sc_mediasize;
2102	/*
2103	 * There could be a problem when data provider and journal providers
2104	 * have different sectorsize, but such scenario is prevented on journal
2105	 * creation.
2106	 */
2107	pp->sectorsize = sc->sc_sectorsize;
2108	g_error_provider(pp, 0);
2109	g_topology_unlock();
2110	last_write = time_second;
2111
2112	if (sc->sc_rootmount != NULL) {
2113		GJ_DEBUG(1, "root_mount_rel %p", sc->sc_rootmount);
2114		root_mount_rel(sc->sc_rootmount);
2115		sc->sc_rootmount = NULL;
2116	}
2117
2118	for (;;) {
2119		/* Get first request from the queue. */
2120		mtx_lock(&sc->sc_mtx);
2121		bp = bioq_first(&sc->sc_back_queue);
2122		if (bp != NULL)
2123			type = (bp->bio_cflags & GJ_BIO_MASK);
2124		if (bp == NULL) {
2125			bp = bioq_first(&sc->sc_regular_queue);
2126			if (bp != NULL)
2127				type = GJ_BIO_REGULAR;
2128		}
2129		if (bp == NULL) {
2130try_switch:
2131			if ((sc->sc_flags & GJF_DEVICE_SWITCH) ||
2132			    (sc->sc_flags & GJF_DEVICE_DESTROY)) {
2133				if (sc->sc_current_count > 0) {
2134					mtx_unlock(&sc->sc_mtx);
2135					g_journal_flush(sc);
2136					g_journal_flush_send(sc);
2137					continue;
2138				}
2139				if (sc->sc_flush_in_progress > 0)
2140					goto sleep;
2141				if (sc->sc_copy_in_progress > 0)
2142					goto sleep;
2143			}
2144			if (sc->sc_flags & GJF_DEVICE_SWITCH) {
2145				mtx_unlock(&sc->sc_mtx);
2146				g_journal_switch(sc);
2147				wakeup(&sc->sc_journal_copying);
2148				continue;
2149			}
2150			if (sc->sc_flags & GJF_DEVICE_DESTROY) {
2151				GJ_DEBUG(1, "Shutting down worker "
2152				    "thread for %s.", gp->name);
2153				sc->sc_worker = NULL;
2154				wakeup(&sc->sc_worker);
2155				mtx_unlock(&sc->sc_mtx);
2156				kproc_exit(0);
2157			}
2158sleep:
2159			g_journal_wait(sc, last_write);
2160			continue;
2161		}
2162		/*
2163		 * If we're in switch process, we need to delay all new
2164		 * write requests until its done.
2165		 */
2166		if ((sc->sc_flags & GJF_DEVICE_SWITCH) &&
2167		    type == GJ_BIO_REGULAR && bp->bio_cmd == BIO_WRITE) {
2168			GJ_LOGREQ(2, bp, "WRITE on SWITCH");
2169			goto try_switch;
2170		}
2171		if (type == GJ_BIO_REGULAR)
2172			bioq_remove(&sc->sc_regular_queue, bp);
2173		else
2174			bioq_remove(&sc->sc_back_queue, bp);
2175		mtx_unlock(&sc->sc_mtx);
2176		switch (type) {
2177		case GJ_BIO_REGULAR:
2178			/* Regular request. */
2179			switch (bp->bio_cmd) {
2180			case BIO_READ:
2181				g_journal_read(sc, bp, bp->bio_offset,
2182				    bp->bio_offset + bp->bio_length);
2183				break;
2184			case BIO_WRITE:
2185				last_write = time_second;
2186				g_journal_add_request(sc, bp);
2187				g_journal_flush_send(sc);
2188				break;
2189			default:
2190				panic("Invalid bio_cmd (%d).", bp->bio_cmd);
2191			}
2192			break;
2193		case GJ_BIO_COPY:
2194			switch (bp->bio_cmd) {
2195			case BIO_READ:
2196				if (g_journal_copy_read_done(bp))
2197					g_journal_copy_send(sc);
2198				break;
2199			case BIO_WRITE:
2200				g_journal_copy_write_done(bp);
2201				g_journal_copy_send(sc);
2202				break;
2203			default:
2204				panic("Invalid bio_cmd (%d).", bp->bio_cmd);
2205			}
2206			break;
2207		case GJ_BIO_JOURNAL:
2208			g_journal_flush_done(bp);
2209			g_journal_flush_send(sc);
2210			break;
2211		case GJ_BIO_READ:
2212		default:
2213			panic("Invalid bio (%d).", type);
2214		}
2215	}
2216}
2217
2218static void
2219g_journal_destroy_event(void *arg, int flags __unused)
2220{
2221	struct g_journal_softc *sc;
2222
2223	g_topology_assert();
2224	sc = arg;
2225	g_journal_destroy(sc);
2226}
2227
2228static void
2229g_journal_timeout(void *arg)
2230{
2231	struct g_journal_softc *sc;
2232
2233	sc = arg;
2234	GJ_DEBUG(0, "Timeout. Journal %s cannot be completed.",
2235	    sc->sc_geom->name);
2236	g_post_event(g_journal_destroy_event, sc, M_NOWAIT, NULL);
2237}
2238
2239static struct g_geom *
2240g_journal_create(struct g_class *mp, struct g_provider *pp,
2241    const struct g_journal_metadata *md)
2242{
2243	struct g_journal_softc *sc;
2244	struct g_geom *gp;
2245	struct g_consumer *cp;
2246	int error;
2247
2248	sc = NULL;	/* gcc */
2249
2250	g_topology_assert();
2251	/*
2252	 * There are two possibilities:
2253	 * 1. Data and both journals are on the same provider.
2254	 * 2. Data and journals are all on separated providers.
2255	 */
2256	/* Look for journal device with the same ID. */
2257	LIST_FOREACH(gp, &mp->geom, geom) {
2258		sc = gp->softc;
2259		if (sc == NULL)
2260			continue;
2261		if (sc->sc_id == md->md_id)
2262			break;
2263	}
2264	if (gp == NULL)
2265		sc = NULL;
2266	else if (sc != NULL && (sc->sc_type & md->md_type) != 0) {
2267		GJ_DEBUG(1, "Journal device %u already configured.", sc->sc_id);
2268		return (NULL);
2269	}
2270	if (md->md_type == 0 || (md->md_type & ~GJ_TYPE_COMPLETE) != 0) {
2271		GJ_DEBUG(0, "Invalid type on %s.", pp->name);
2272		return (NULL);
2273	}
2274	if (md->md_type & GJ_TYPE_DATA) {
2275		GJ_DEBUG(0, "Journal %u: %s contains data.", md->md_id,
2276		    pp->name);
2277	}
2278	if (md->md_type & GJ_TYPE_JOURNAL) {
2279		GJ_DEBUG(0, "Journal %u: %s contains journal.", md->md_id,
2280		    pp->name);
2281	}
2282
2283	if (sc == NULL) {
2284		/* Action geom. */
2285		sc = malloc(sizeof(*sc), M_JOURNAL, M_WAITOK | M_ZERO);
2286		sc->sc_id = md->md_id;
2287		sc->sc_type = 0;
2288		sc->sc_flags = 0;
2289		sc->sc_worker = NULL;
2290
2291		gp = g_new_geomf(mp, "gjournal %u", sc->sc_id);
2292		gp->start = g_journal_start;
2293		gp->orphan = g_journal_orphan;
2294		gp->access = g_journal_access;
2295		gp->softc = sc;
2296		gp->flags |= G_GEOM_VOLATILE_BIO;
2297		sc->sc_geom = gp;
2298
2299		mtx_init(&sc->sc_mtx, "gjournal", NULL, MTX_DEF);
2300
2301		bioq_init(&sc->sc_back_queue);
2302		bioq_init(&sc->sc_regular_queue);
2303		bioq_init(&sc->sc_delayed_queue);
2304		sc->sc_delayed_count = 0;
2305		sc->sc_current_queue = NULL;
2306		sc->sc_current_count = 0;
2307		sc->sc_flush_queue = NULL;
2308		sc->sc_flush_count = 0;
2309		sc->sc_flush_in_progress = 0;
2310		sc->sc_copy_queue = NULL;
2311		sc->sc_copy_in_progress = 0;
2312		sc->sc_inactive.jj_queue = NULL;
2313		sc->sc_active.jj_queue = NULL;
2314
2315		sc->sc_rootmount = root_mount_hold("GJOURNAL");
2316		GJ_DEBUG(1, "root_mount_hold %p", sc->sc_rootmount);
2317
2318		callout_init(&sc->sc_callout, CALLOUT_MPSAFE);
2319		if (md->md_type != GJ_TYPE_COMPLETE) {
2320			/*
2321			 * Journal and data are on separate providers.
2322			 * At this point we have only one of them.
2323			 * We setup a timeout in case the other part will not
2324			 * appear, so we won't wait forever.
2325			 */
2326			callout_reset(&sc->sc_callout, 5 * hz,
2327			    g_journal_timeout, sc);
2328		}
2329	}
2330
2331	/* Remember type of the data provider. */
2332	if (md->md_type & GJ_TYPE_DATA)
2333		sc->sc_orig_type = md->md_type;
2334	sc->sc_type |= md->md_type;
2335	cp = NULL;
2336
2337	if (md->md_type & GJ_TYPE_DATA) {
2338		if (md->md_flags & GJ_FLAG_CLEAN)
2339			sc->sc_flags |= GJF_DEVICE_CLEAN;
2340		if (md->md_flags & GJ_FLAG_CHECKSUM)
2341			sc->sc_flags |= GJF_DEVICE_CHECKSUM;
2342		cp = g_new_consumer(gp);
2343		error = g_attach(cp, pp);
2344		KASSERT(error == 0, ("Cannot attach to %s (error=%d).",
2345		    pp->name, error));
2346		error = g_access(cp, 1, 1, 1);
2347		if (error != 0) {
2348			GJ_DEBUG(0, "Cannot access %s (error=%d).", pp->name,
2349			    error);
2350			g_journal_destroy(sc);
2351			return (NULL);
2352		}
2353		sc->sc_dconsumer = cp;
2354		sc->sc_mediasize = pp->mediasize - pp->sectorsize;
2355		sc->sc_sectorsize = pp->sectorsize;
2356		sc->sc_jstart = md->md_jstart;
2357		sc->sc_jend = md->md_jend;
2358		if (md->md_provider[0] != '\0')
2359			sc->sc_flags |= GJF_DEVICE_HARDCODED;
2360		sc->sc_journal_offset = md->md_joffset;
2361		sc->sc_journal_id = md->md_jid;
2362		sc->sc_journal_previous_id = md->md_jid;
2363	}
2364	if (md->md_type & GJ_TYPE_JOURNAL) {
2365		if (cp == NULL) {
2366			cp = g_new_consumer(gp);
2367			error = g_attach(cp, pp);
2368			KASSERT(error == 0, ("Cannot attach to %s (error=%d).",
2369			    pp->name, error));
2370			error = g_access(cp, 1, 1, 1);
2371			if (error != 0) {
2372				GJ_DEBUG(0, "Cannot access %s (error=%d).",
2373				    pp->name, error);
2374				g_journal_destroy(sc);
2375				return (NULL);
2376			}
2377		} else {
2378			/*
2379			 * Journal is on the same provider as data, which means
2380			 * that data provider ends where journal starts.
2381			 */
2382			sc->sc_mediasize = md->md_jstart;
2383		}
2384		sc->sc_jconsumer = cp;
2385	}
2386
2387	if ((sc->sc_type & GJ_TYPE_COMPLETE) != GJ_TYPE_COMPLETE) {
2388		/* Journal is not complete yet. */
2389		return (gp);
2390	} else {
2391		/* Journal complete, cancel timeout. */
2392		callout_drain(&sc->sc_callout);
2393	}
2394
2395	error = kproc_create(g_journal_worker, sc, &sc->sc_worker, 0, 0,
2396	    "g_journal %s", sc->sc_name);
2397	if (error != 0) {
2398		GJ_DEBUG(0, "Cannot create worker thread for %s.journal.",
2399		    sc->sc_name);
2400		g_journal_destroy(sc);
2401		return (NULL);
2402	}
2403
2404	return (gp);
2405}
2406
2407static void
2408g_journal_destroy_consumer(void *arg, int flags __unused)
2409{
2410	struct g_consumer *cp;
2411
2412	g_topology_assert();
2413	cp = arg;
2414	g_detach(cp);
2415	g_destroy_consumer(cp);
2416}
2417
2418static int
2419g_journal_destroy(struct g_journal_softc *sc)
2420{
2421	struct g_geom *gp;
2422	struct g_provider *pp;
2423	struct g_consumer *cp;
2424
2425	g_topology_assert();
2426
2427	if (sc == NULL)
2428		return (ENXIO);
2429
2430	gp = sc->sc_geom;
2431	pp = LIST_FIRST(&gp->provider);
2432	if (pp != NULL) {
2433		if (pp->acr != 0 || pp->acw != 0 || pp->ace != 0) {
2434			GJ_DEBUG(1, "Device %s is still open (r%dw%de%d).",
2435			    pp->name, pp->acr, pp->acw, pp->ace);
2436			return (EBUSY);
2437		}
2438		g_error_provider(pp, ENXIO);
2439
2440		g_journal_flush(sc);
2441		g_journal_flush_send(sc);
2442		g_journal_switch(sc);
2443	}
2444
2445	sc->sc_flags |= (GJF_DEVICE_DESTROY | GJF_DEVICE_CLEAN);
2446
2447	g_topology_unlock();
2448
2449	if (sc->sc_rootmount != NULL) {
2450		GJ_DEBUG(1, "root_mount_rel %p", sc->sc_rootmount);
2451		root_mount_rel(sc->sc_rootmount);
2452		sc->sc_rootmount = NULL;
2453	}
2454
2455	callout_drain(&sc->sc_callout);
2456	mtx_lock(&sc->sc_mtx);
2457	wakeup(sc);
2458	while (sc->sc_worker != NULL)
2459		msleep(&sc->sc_worker, &sc->sc_mtx, PRIBIO, "gj:destroy", 0);
2460	mtx_unlock(&sc->sc_mtx);
2461
2462	if (pp != NULL) {
2463		GJ_DEBUG(1, "Marking %s as clean.", sc->sc_name);
2464		g_journal_metadata_update(sc);
2465		g_topology_lock();
2466		pp->flags |= G_PF_WITHER;
2467		g_orphan_provider(pp, ENXIO);
2468	} else {
2469		g_topology_lock();
2470	}
2471	mtx_destroy(&sc->sc_mtx);
2472
2473	if (sc->sc_current_count != 0) {
2474		GJ_DEBUG(0, "Warning! Number of current requests %d.",
2475		    sc->sc_current_count);
2476	}
2477
2478	LIST_FOREACH(cp, &gp->consumer, consumer) {
2479		if (cp->acr + cp->acw + cp->ace > 0)
2480			g_access(cp, -1, -1, -1);
2481		/*
2482		 * We keep all consumers open for writting, so if I'll detach
2483		 * and destroy consumer here, I'll get providers for taste, so
2484		 * journal will be started again.
2485		 * Sending an event here, prevents this from happening.
2486		 */
2487		g_post_event(g_journal_destroy_consumer, cp, M_WAITOK, NULL);
2488	}
2489	gp->softc = NULL;
2490	g_wither_geom(gp, ENXIO);
2491	free(sc, M_JOURNAL);
2492	return (0);
2493}
2494
2495static void
2496g_journal_taste_orphan(struct g_consumer *cp)
2497{
2498
2499	KASSERT(1 == 0, ("%s called while tasting %s.", __func__,
2500	    cp->provider->name));
2501}
2502
2503static struct g_geom *
2504g_journal_taste(struct g_class *mp, struct g_provider *pp, int flags __unused)
2505{
2506	struct g_journal_metadata md;
2507	struct g_consumer *cp;
2508	struct g_geom *gp;
2509	int error;
2510
2511	g_topology_assert();
2512	g_trace(G_T_TOPOLOGY, "%s(%s, %s)", __func__, mp->name, pp->name);
2513	GJ_DEBUG(2, "Tasting %s.", pp->name);
2514	if (pp->geom->class == mp)
2515		return (NULL);
2516
2517	gp = g_new_geomf(mp, "journal:taste");
2518	/* This orphan function should be never called. */
2519	gp->orphan = g_journal_taste_orphan;
2520	cp = g_new_consumer(gp);
2521	g_attach(cp, pp);
2522	error = g_journal_metadata_read(cp, &md);
2523	g_detach(cp);
2524	g_destroy_consumer(cp);
2525	g_destroy_geom(gp);
2526	if (error != 0)
2527		return (NULL);
2528	gp = NULL;
2529
2530	if (md.md_provider[0] != '\0' &&
2531	    !g_compare_names(md.md_provider, pp->name))
2532		return (NULL);
2533	if (md.md_provsize != 0 && md.md_provsize != pp->mediasize)
2534		return (NULL);
2535	if (g_journal_debug >= 2)
2536		journal_metadata_dump(&md);
2537
2538	gp = g_journal_create(mp, pp, &md);
2539	return (gp);
2540}
2541
2542static struct g_journal_softc *
2543g_journal_find_device(struct g_class *mp, const char *name)
2544{
2545	struct g_journal_softc *sc;
2546	struct g_geom *gp;
2547	struct g_provider *pp;
2548
2549	if (strncmp(name, "/dev/", 5) == 0)
2550		name += 5;
2551	LIST_FOREACH(gp, &mp->geom, geom) {
2552		sc = gp->softc;
2553		if (sc == NULL)
2554			continue;
2555		if (sc->sc_flags & GJF_DEVICE_DESTROY)
2556			continue;
2557		if ((sc->sc_type & GJ_TYPE_COMPLETE) != GJ_TYPE_COMPLETE)
2558			continue;
2559		pp = LIST_FIRST(&gp->provider);
2560		if (strcmp(sc->sc_name, name) == 0)
2561			return (sc);
2562		if (pp != NULL && strcmp(pp->name, name) == 0)
2563			return (sc);
2564	}
2565	return (NULL);
2566}
2567
2568static void
2569g_journal_ctl_destroy(struct gctl_req *req, struct g_class *mp)
2570{
2571	struct g_journal_softc *sc;
2572	const char *name;
2573	char param[16];
2574	int *nargs;
2575	int error, i;
2576
2577	g_topology_assert();
2578
2579	nargs = gctl_get_paraml(req, "nargs", sizeof(*nargs));
2580	if (nargs == NULL) {
2581		gctl_error(req, "No '%s' argument.", "nargs");
2582		return;
2583	}
2584	if (*nargs <= 0) {
2585		gctl_error(req, "Missing device(s).");
2586		return;
2587	}
2588
2589	for (i = 0; i < *nargs; i++) {
2590		snprintf(param, sizeof(param), "arg%d", i);
2591		name = gctl_get_asciiparam(req, param);
2592		if (name == NULL) {
2593			gctl_error(req, "No 'arg%d' argument.", i);
2594			return;
2595		}
2596		sc = g_journal_find_device(mp, name);
2597		if (sc == NULL) {
2598			gctl_error(req, "No such device: %s.", name);
2599			return;
2600		}
2601		error = g_journal_destroy(sc);
2602		if (error != 0) {
2603			gctl_error(req, "Cannot destroy device %s (error=%d).",
2604			    LIST_FIRST(&sc->sc_geom->provider)->name, error);
2605			return;
2606		}
2607	}
2608}
2609
2610static void
2611g_journal_ctl_sync(struct gctl_req *req __unused, struct g_class *mp __unused)
2612{
2613
2614	g_topology_assert();
2615	g_topology_unlock();
2616	g_journal_sync_requested++;
2617	wakeup(&g_journal_switcher_state);
2618	while (g_journal_sync_requested > 0)
2619		tsleep(&g_journal_sync_requested, PRIBIO, "j:sreq", hz / 2);
2620	g_topology_lock();
2621}
2622
2623static void
2624g_journal_config(struct gctl_req *req, struct g_class *mp, const char *verb)
2625{
2626	uint32_t *version;
2627
2628	g_topology_assert();
2629
2630	version = gctl_get_paraml(req, "version", sizeof(*version));
2631	if (version == NULL) {
2632		gctl_error(req, "No '%s' argument.", "version");
2633		return;
2634	}
2635	if (*version != G_JOURNAL_VERSION) {
2636		gctl_error(req, "Userland and kernel parts are out of sync.");
2637		return;
2638	}
2639
2640	if (strcmp(verb, "destroy") == 0 || strcmp(verb, "stop") == 0) {
2641		g_journal_ctl_destroy(req, mp);
2642		return;
2643	} else if (strcmp(verb, "sync") == 0) {
2644		g_journal_ctl_sync(req, mp);
2645		return;
2646	}
2647
2648	gctl_error(req, "Unknown verb.");
2649}
2650
2651static void
2652g_journal_dumpconf(struct sbuf *sb, const char *indent, struct g_geom *gp,
2653    struct g_consumer *cp, struct g_provider *pp)
2654{
2655	struct g_journal_softc *sc;
2656
2657	g_topology_assert();
2658
2659	sc = gp->softc;
2660	if (sc == NULL)
2661		return;
2662	if (pp != NULL) {
2663		/* Nothing here. */
2664	} else if (cp != NULL) {
2665		int first = 1;
2666
2667		sbuf_printf(sb, "%s<Role>", indent);
2668		if (cp == sc->sc_dconsumer) {
2669			sbuf_printf(sb, "Data");
2670			first = 0;
2671		}
2672		if (cp == sc->sc_jconsumer) {
2673			if (!first)
2674				sbuf_printf(sb, ",");
2675			sbuf_printf(sb, "Journal");
2676		}
2677		sbuf_printf(sb, "</Role>\n");
2678		if (cp == sc->sc_jconsumer) {
2679			sbuf_printf(sb, "<Jstart>%jd</Jstart>\n",
2680			    (intmax_t)sc->sc_jstart);
2681			sbuf_printf(sb, "<Jend>%jd</Jend>\n",
2682			    (intmax_t)sc->sc_jend);
2683		}
2684	} else {
2685		sbuf_printf(sb, "%s<ID>%u</ID>\n", indent, (u_int)sc->sc_id);
2686	}
2687}
2688
2689static eventhandler_tag g_journal_event_shutdown = NULL;
2690static eventhandler_tag g_journal_event_lowmem = NULL;
2691
2692static void
2693g_journal_shutdown(void *arg, int howto __unused)
2694{
2695	struct g_class *mp;
2696	struct g_geom *gp, *gp2;
2697
2698	if (panicstr != NULL)
2699		return;
2700	mp = arg;
2701	DROP_GIANT();
2702	g_topology_lock();
2703	LIST_FOREACH_SAFE(gp, &mp->geom, geom, gp2) {
2704		if (gp->softc == NULL)
2705			continue;
2706		GJ_DEBUG(0, "Shutting down geom %s.", gp->name);
2707		g_journal_destroy(gp->softc);
2708	}
2709	g_topology_unlock();
2710	PICKUP_GIANT();
2711}
2712
2713/*
2714 * Free cached requests from inactive queue in case of low memory.
2715 * We free GJ_FREE_AT_ONCE elements at once.
2716 */
2717#define	GJ_FREE_AT_ONCE	4
2718static void
2719g_journal_lowmem(void *arg, int howto __unused)
2720{
2721	struct g_journal_softc *sc;
2722	struct g_class *mp;
2723	struct g_geom *gp;
2724	struct bio *bp;
2725	u_int nfree = GJ_FREE_AT_ONCE;
2726
2727	g_journal_stats_low_mem++;
2728	mp = arg;
2729	DROP_GIANT();
2730	g_topology_lock();
2731	LIST_FOREACH(gp, &mp->geom, geom) {
2732		sc = gp->softc;
2733		if (sc == NULL || (sc->sc_flags & GJF_DEVICE_DESTROY))
2734			continue;
2735		mtx_lock(&sc->sc_mtx);
2736		for (bp = sc->sc_inactive.jj_queue; nfree > 0 && bp != NULL;
2737		    nfree--, bp = bp->bio_next) {
2738			/*
2739			 * This is safe to free the bio_data, because:
2740			 * 1. If bio_data is NULL it will be read from the
2741			 *    inactive journal.
2742			 * 2. If bp is sent down, it is first removed from the
2743			 *    inactive queue, so it's impossible to free the
2744			 *    data from under in-flight bio.
2745			 * On the other hand, freeing elements from the active
2746			 * queue, is not safe.
2747			 */
2748			if (bp->bio_data != NULL) {
2749				GJ_DEBUG(2, "Freeing data from %s.",
2750				    sc->sc_name);
2751				gj_free(bp->bio_data, bp->bio_length);
2752				bp->bio_data = NULL;
2753			}
2754		}
2755		mtx_unlock(&sc->sc_mtx);
2756		if (nfree == 0)
2757			break;
2758	}
2759	g_topology_unlock();
2760	PICKUP_GIANT();
2761}
2762
2763static void g_journal_switcher(void *arg);
2764
2765static void
2766g_journal_init(struct g_class *mp)
2767{
2768	int error;
2769
2770	/* Pick a conservative value if provided value sucks. */
2771	if (g_journal_cache_divisor <= 0 ||
2772	    (vm_kmem_size / g_journal_cache_divisor == 0)) {
2773		g_journal_cache_divisor = 5;
2774	}
2775	if (g_journal_cache_limit > 0) {
2776		g_journal_cache_limit = vm_kmem_size / g_journal_cache_divisor;
2777		g_journal_cache_low =
2778		    (g_journal_cache_limit / 100) * g_journal_cache_switch;
2779	}
2780	g_journal_event_shutdown = EVENTHANDLER_REGISTER(shutdown_post_sync,
2781	    g_journal_shutdown, mp, EVENTHANDLER_PRI_FIRST);
2782	if (g_journal_event_shutdown == NULL)
2783		GJ_DEBUG(0, "Warning! Cannot register shutdown event.");
2784	g_journal_event_lowmem = EVENTHANDLER_REGISTER(vm_lowmem,
2785	    g_journal_lowmem, mp, EVENTHANDLER_PRI_FIRST);
2786	if (g_journal_event_lowmem == NULL)
2787		GJ_DEBUG(0, "Warning! Cannot register lowmem event.");
2788	error = kproc_create(g_journal_switcher, mp, NULL, 0, 0,
2789	    "g_journal switcher");
2790	KASSERT(error == 0, ("Cannot create switcher thread."));
2791}
2792
2793static void
2794g_journal_fini(struct g_class *mp)
2795{
2796
2797	if (g_journal_event_shutdown != NULL) {
2798		EVENTHANDLER_DEREGISTER(shutdown_post_sync,
2799		    g_journal_event_shutdown);
2800	}
2801	if (g_journal_event_lowmem != NULL)
2802		EVENTHANDLER_DEREGISTER(vm_lowmem, g_journal_event_lowmem);
2803	g_journal_switcher_state = GJ_SWITCHER_DIE;
2804	wakeup(&g_journal_switcher_state);
2805	while (g_journal_switcher_state != GJ_SWITCHER_DIED)
2806		tsleep(&g_journal_switcher_state, PRIBIO, "jfini:wait", hz / 5);
2807	GJ_DEBUG(1, "Switcher died.");
2808}
2809
2810DECLARE_GEOM_CLASS(g_journal_class, g_journal);
2811
2812static const struct g_journal_desc *
2813g_journal_find_desc(const char *fstype)
2814{
2815	const struct g_journal_desc *desc;
2816	int i;
2817
2818	for (desc = g_journal_filesystems[i = 0]; desc != NULL;
2819	     desc = g_journal_filesystems[++i]) {
2820		if (strcmp(desc->jd_fstype, fstype) == 0)
2821			break;
2822	}
2823	return (desc);
2824}
2825
2826static void
2827g_journal_switch_wait(struct g_journal_softc *sc)
2828{
2829	struct bintime bt;
2830
2831	mtx_assert(&sc->sc_mtx, MA_OWNED);
2832	if (g_journal_debug >= 2) {
2833		if (sc->sc_flush_in_progress > 0) {
2834			GJ_DEBUG(2, "%d requests flushing.",
2835			    sc->sc_flush_in_progress);
2836		}
2837		if (sc->sc_copy_in_progress > 0) {
2838			GJ_DEBUG(2, "%d requests copying.",
2839			    sc->sc_copy_in_progress);
2840		}
2841		if (sc->sc_flush_count > 0) {
2842			GJ_DEBUG(2, "%d requests to flush.",
2843			    sc->sc_flush_count);
2844		}
2845		if (sc->sc_delayed_count > 0) {
2846			GJ_DEBUG(2, "%d requests delayed.",
2847			    sc->sc_delayed_count);
2848		}
2849	}
2850	g_journal_stats_switches++;
2851	if (sc->sc_copy_in_progress > 0)
2852		g_journal_stats_wait_for_copy++;
2853	GJ_TIMER_START(1, &bt);
2854	sc->sc_flags &= ~GJF_DEVICE_BEFORE_SWITCH;
2855	sc->sc_flags |= GJF_DEVICE_SWITCH;
2856	wakeup(sc);
2857	while (sc->sc_flags & GJF_DEVICE_SWITCH) {
2858		msleep(&sc->sc_journal_copying, &sc->sc_mtx, PRIBIO,
2859		    "gj:switch", 0);
2860	}
2861	GJ_TIMER_STOP(1, &bt, "Switch time of %s", sc->sc_name);
2862}
2863
2864static void
2865g_journal_do_switch(struct g_class *classp)
2866{
2867	struct g_journal_softc *sc;
2868	const struct g_journal_desc *desc;
2869	struct g_geom *gp;
2870	struct mount *mp;
2871	struct bintime bt;
2872	char *mountpoint;
2873	int error, save;
2874
2875	DROP_GIANT();
2876	g_topology_lock();
2877	LIST_FOREACH(gp, &classp->geom, geom) {
2878		sc = gp->softc;
2879		if (sc == NULL)
2880			continue;
2881		if (sc->sc_flags & GJF_DEVICE_DESTROY)
2882			continue;
2883		if ((sc->sc_type & GJ_TYPE_COMPLETE) != GJ_TYPE_COMPLETE)
2884			continue;
2885		mtx_lock(&sc->sc_mtx);
2886		sc->sc_flags |= GJF_DEVICE_BEFORE_SWITCH;
2887		mtx_unlock(&sc->sc_mtx);
2888	}
2889	g_topology_unlock();
2890	PICKUP_GIANT();
2891
2892	mtx_lock(&mountlist_mtx);
2893	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
2894		if (mp->mnt_gjprovider == NULL)
2895			continue;
2896		if (mp->mnt_flag & MNT_RDONLY)
2897			continue;
2898		desc = g_journal_find_desc(mp->mnt_stat.f_fstypename);
2899		if (desc == NULL)
2900			continue;
2901		if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
2902			continue;
2903		/* mtx_unlock(&mountlist_mtx) was done inside vfs_busy() */
2904
2905		DROP_GIANT();
2906		g_topology_lock();
2907		sc = g_journal_find_device(classp, mp->mnt_gjprovider);
2908		g_topology_unlock();
2909		PICKUP_GIANT();
2910
2911		if (sc == NULL) {
2912			GJ_DEBUG(0, "Cannot find journal geom for %s.",
2913			    mp->mnt_gjprovider);
2914			goto next;
2915		} else if (JEMPTY(sc)) {
2916			mtx_lock(&sc->sc_mtx);
2917			sc->sc_flags &= ~GJF_DEVICE_BEFORE_SWITCH;
2918			mtx_unlock(&sc->sc_mtx);
2919			GJ_DEBUG(3, "No need for %s switch.", sc->sc_name);
2920			goto next;
2921		}
2922
2923		mountpoint = mp->mnt_stat.f_mntonname;
2924
2925		error = vn_start_write(NULL, &mp, V_WAIT);
2926		if (error != 0) {
2927			GJ_DEBUG(0, "vn_start_write(%s) failed (error=%d).",
2928			    mountpoint, error);
2929			goto next;
2930		}
2931
2932		save = curthread_pflags_set(TDP_SYNCIO);
2933
2934		GJ_TIMER_START(1, &bt);
2935		vfs_msync(mp, MNT_NOWAIT);
2936		GJ_TIMER_STOP(1, &bt, "Msync time of %s", mountpoint);
2937
2938		GJ_TIMER_START(1, &bt);
2939		error = VFS_SYNC(mp, MNT_NOWAIT);
2940		if (error == 0)
2941			GJ_TIMER_STOP(1, &bt, "Sync time of %s", mountpoint);
2942		else {
2943			GJ_DEBUG(0, "Cannot sync file system %s (error=%d).",
2944			    mountpoint, error);
2945		}
2946
2947		curthread_pflags_restore(save);
2948
2949		vn_finished_write(mp);
2950
2951		if (error != 0)
2952			goto next;
2953
2954		/*
2955		 * Send BIO_FLUSH before freezing the file system, so it can be
2956		 * faster after the freeze.
2957		 */
2958		GJ_TIMER_START(1, &bt);
2959		g_journal_flush_cache(sc);
2960		GJ_TIMER_STOP(1, &bt, "BIO_FLUSH time of %s", sc->sc_name);
2961
2962		GJ_TIMER_START(1, &bt);
2963		error = vfs_write_suspend(mp);
2964		GJ_TIMER_STOP(1, &bt, "Suspend time of %s", mountpoint);
2965		if (error != 0) {
2966			GJ_DEBUG(0, "Cannot suspend file system %s (error=%d).",
2967			    mountpoint, error);
2968			goto next;
2969		}
2970
2971		error = desc->jd_clean(mp);
2972		if (error != 0)
2973			goto next;
2974
2975		mtx_lock(&sc->sc_mtx);
2976		g_journal_switch_wait(sc);
2977		mtx_unlock(&sc->sc_mtx);
2978
2979		vfs_write_resume(mp);
2980next:
2981		mtx_lock(&mountlist_mtx);
2982		vfs_unbusy(mp);
2983	}
2984	mtx_unlock(&mountlist_mtx);
2985
2986	sc = NULL;
2987	for (;;) {
2988		DROP_GIANT();
2989		g_topology_lock();
2990		LIST_FOREACH(gp, &g_journal_class.geom, geom) {
2991			sc = gp->softc;
2992			if (sc == NULL)
2993				continue;
2994			mtx_lock(&sc->sc_mtx);
2995			if ((sc->sc_type & GJ_TYPE_COMPLETE) == GJ_TYPE_COMPLETE &&
2996			    !(sc->sc_flags & GJF_DEVICE_DESTROY) &&
2997			    (sc->sc_flags & GJF_DEVICE_BEFORE_SWITCH)) {
2998				break;
2999			}
3000			mtx_unlock(&sc->sc_mtx);
3001			sc = NULL;
3002		}
3003		g_topology_unlock();
3004		PICKUP_GIANT();
3005		if (sc == NULL)
3006			break;
3007		mtx_assert(&sc->sc_mtx, MA_OWNED);
3008		g_journal_switch_wait(sc);
3009		mtx_unlock(&sc->sc_mtx);
3010	}
3011}
3012
3013/*
3014 * TODO: Switcher thread should be started on first geom creation and killed on
3015 * last geom destruction.
3016 */
3017static void
3018g_journal_switcher(void *arg)
3019{
3020	struct g_class *mp;
3021	struct bintime bt;
3022	int error;
3023
3024	mp = arg;
3025	curthread->td_pflags |= TDP_NORUNNINGBUF;
3026	for (;;) {
3027		g_journal_switcher_wokenup = 0;
3028		error = tsleep(&g_journal_switcher_state, PRIBIO, "jsw:wait",
3029		    g_journal_switch_time * hz);
3030		if (g_journal_switcher_state == GJ_SWITCHER_DIE) {
3031			g_journal_switcher_state = GJ_SWITCHER_DIED;
3032			GJ_DEBUG(1, "Switcher exiting.");
3033			wakeup(&g_journal_switcher_state);
3034			kproc_exit(0);
3035		}
3036		if (error == 0 && g_journal_sync_requested == 0) {
3037			GJ_DEBUG(1, "Out of cache, force switch (used=%u "
3038			    "limit=%u).", g_journal_cache_used,
3039			    g_journal_cache_limit);
3040		}
3041		GJ_TIMER_START(1, &bt);
3042		g_journal_do_switch(mp);
3043		GJ_TIMER_STOP(1, &bt, "Entire switch time");
3044		if (g_journal_sync_requested > 0) {
3045			g_journal_sync_requested = 0;
3046			wakeup(&g_journal_sync_requested);
3047		}
3048	}
3049}
3050