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