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