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