xref: /netbsd-src/sys/kern/vfs_wapbl.c (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /*	$NetBSD: vfs_wapbl.c,v 1.101 2017/12/02 17:29:55 jdolecek Exp $	*/
2 
3 /*-
4  * Copyright (c) 2003, 2008, 2009 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Wasabi Systems, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 /*
33  * This implements file system independent write ahead filesystem logging.
34  */
35 
36 #define WAPBL_INTERNAL
37 
38 #include <sys/cdefs.h>
39 __KERNEL_RCSID(0, "$NetBSD: vfs_wapbl.c,v 1.101 2017/12/02 17:29:55 jdolecek Exp $");
40 
41 #include <sys/param.h>
42 #include <sys/bitops.h>
43 #include <sys/time.h>
44 #include <sys/wapbl.h>
45 #include <sys/wapbl_replay.h>
46 
47 #ifdef _KERNEL
48 
49 #include <sys/atomic.h>
50 #include <sys/conf.h>
51 #include <sys/evcnt.h>
52 #include <sys/file.h>
53 #include <sys/kauth.h>
54 #include <sys/kernel.h>
55 #include <sys/module.h>
56 #include <sys/mount.h>
57 #include <sys/mutex.h>
58 #include <sys/namei.h>
59 #include <sys/proc.h>
60 #include <sys/resourcevar.h>
61 #include <sys/sysctl.h>
62 #include <sys/uio.h>
63 #include <sys/vnode.h>
64 
65 #include <miscfs/specfs/specdev.h>
66 
67 #define	wapbl_alloc(s) kmem_alloc((s), KM_SLEEP)
68 #define	wapbl_free(a, s) kmem_free((a), (s))
69 #define	wapbl_calloc(n, s) kmem_zalloc((n)*(s), KM_SLEEP)
70 
71 static struct sysctllog *wapbl_sysctl;
72 static int wapbl_flush_disk_cache = 1;
73 static int wapbl_verbose_commit = 0;
74 static int wapbl_allow_dpofua = 0; 	/* switched off by default for now */
75 static int wapbl_journal_iobufs = 4;
76 
77 static inline size_t wapbl_space_free(size_t, off_t, off_t);
78 
79 #else /* !_KERNEL */
80 
81 #include <assert.h>
82 #include <errno.h>
83 #include <stdbool.h>
84 #include <stdio.h>
85 #include <stdlib.h>
86 #include <string.h>
87 
88 #define	KDASSERT(x) assert(x)
89 #define	KASSERT(x) assert(x)
90 #define	wapbl_alloc(s) malloc(s)
91 #define	wapbl_free(a, s) free(a)
92 #define	wapbl_calloc(n, s) calloc((n), (s))
93 
94 #endif /* !_KERNEL */
95 
96 /*
97  * INTERNAL DATA STRUCTURES
98  */
99 
100 /*
101  * This structure holds per-mount log information.
102  *
103  * Legend:	a = atomic access only
104  *		r = read-only after init
105  *		l = rwlock held
106  *		m = mutex held
107  *		lm = rwlock held writing or mutex held
108  *		u = unlocked access ok
109  *		b = bufcache_lock held
110  */
111 LIST_HEAD(wapbl_ino_head, wapbl_ino);
112 struct wapbl {
113 	struct vnode *wl_logvp;	/* r:	log here */
114 	struct vnode *wl_devvp;	/* r:	log on this device */
115 	struct mount *wl_mount;	/* r:	mountpoint wl is associated with */
116 	daddr_t wl_logpbn;	/* r:	Physical block number of start of log */
117 	int wl_log_dev_bshift;	/* r:	logarithm of device block size of log
118 					device */
119 	int wl_fs_dev_bshift;	/* r:	logarithm of device block size of
120 					filesystem device */
121 
122 	unsigned wl_lock_count;	/* m:	Count of transactions in progress */
123 
124 	size_t wl_circ_size; 	/* r:	Number of bytes in buffer of log */
125 	size_t wl_circ_off;	/* r:	Number of bytes reserved at start */
126 
127 	size_t wl_bufcount_max;	/* r:	Number of buffers reserved for log */
128 	size_t wl_bufbytes_max;	/* r:	Number of buf bytes reserved for log */
129 
130 	off_t wl_head;		/* l:	Byte offset of log head */
131 	off_t wl_tail;		/* l:	Byte offset of log tail */
132 	/*
133 	 * WAPBL log layout, stored on wl_devvp at wl_logpbn:
134 	 *
135 	 *  ___________________ wl_circ_size __________________
136 	 * /                                                   \
137 	 * +---------+---------+-------+--------------+--------+
138 	 * [ commit0 | commit1 | CCWCW | EEEEEEEEEEEE | CCCWCW ]
139 	 * +---------+---------+-------+--------------+--------+
140 	 *       wl_circ_off --^       ^-- wl_head    ^-- wl_tail
141 	 *
142 	 * commit0 and commit1 are commit headers.  A commit header has
143 	 * a generation number, indicating which of the two headers is
144 	 * more recent, and an assignment of head and tail pointers.
145 	 * The rest is a circular queue of log records, starting at
146 	 * the byte offset wl_circ_off.
147 	 *
148 	 * E marks empty space for records.
149 	 * W marks records for block writes issued but waiting.
150 	 * C marks completed records.
151 	 *
152 	 * wapbl_flush writes new records to empty `E' spaces after
153 	 * wl_head from the current transaction in memory.
154 	 *
155 	 * wapbl_truncate advances wl_tail past any completed `C'
156 	 * records, freeing them up for use.
157 	 *
158 	 * head == tail == 0 means log is empty.
159 	 * head == tail != 0 means log is full.
160 	 *
161 	 * See assertions in wapbl_advance() for other boundary
162 	 * conditions.
163 	 *
164 	 * Only wapbl_flush moves the head, except when wapbl_truncate
165 	 * sets it to 0 to indicate that the log is empty.
166 	 *
167 	 * Only wapbl_truncate moves the tail, except when wapbl_flush
168 	 * sets it to wl_circ_off to indicate that the log is full.
169 	 */
170 
171 	struct wapbl_wc_header *wl_wc_header;	/* l	*/
172 	void *wl_wc_scratch;	/* l:	scratch space (XXX: por que?!?) */
173 
174 	kmutex_t wl_mtx;	/* u:	short-term lock */
175 	krwlock_t wl_rwlock;	/* u:	File system transaction lock */
176 
177 	/*
178 	 * Must be held while accessing
179 	 * wl_count or wl_bufs or head or tail
180 	 */
181 
182 #if _KERNEL
183 	/*
184 	 * Callback called from within the flush routine to flush any extra
185 	 * bits.  Note that flush may be skipped without calling this if
186 	 * there are no outstanding buffers in the transaction.
187 	 */
188 	wapbl_flush_fn_t wl_flush;	/* r	*/
189 	wapbl_flush_fn_t wl_flush_abort;/* r	*/
190 
191 	/* Event counters */
192 	char wl_ev_group[EVCNT_STRING_MAX];	/* r	*/
193 	struct evcnt wl_ev_commit;		/* l	*/
194 	struct evcnt wl_ev_journalwrite;	/* l	*/
195 	struct evcnt wl_ev_jbufs_bio_nowait;	/* l	*/
196 	struct evcnt wl_ev_metawrite;		/* lm	*/
197 	struct evcnt wl_ev_cacheflush;		/* l	*/
198 #endif
199 
200 	size_t wl_bufbytes;	/* m:	Byte count of pages in wl_bufs */
201 	size_t wl_bufcount;	/* m:	Count of buffers in wl_bufs */
202 	size_t wl_bcount;	/* m:	Total bcount of wl_bufs */
203 
204 	TAILQ_HEAD(, buf) wl_bufs; /* m: Buffers in current transaction */
205 
206 	kcondvar_t wl_reclaimable_cv;	/* m (obviously) */
207 	size_t wl_reclaimable_bytes; /* m:	Amount of space available for
208 						reclamation by truncate */
209 	int wl_error_count;	/* m:	# of wl_entries with errors */
210 	size_t wl_reserved_bytes; /* never truncate log smaller than this */
211 
212 #ifdef WAPBL_DEBUG_BUFBYTES
213 	size_t wl_unsynced_bufbytes; /* Byte count of unsynced buffers */
214 #endif
215 
216 #if _KERNEL
217 	int wl_brperjblock;	/* r Block records per journal block */
218 #endif
219 
220 	TAILQ_HEAD(, wapbl_dealloc) wl_dealloclist;	/* lm:	list head */
221 	int wl_dealloccnt;				/* lm:	total count */
222 	int wl_dealloclim;				/* r:	max count */
223 
224 	/* hashtable of inode numbers for allocated but unlinked inodes */
225 	/* synch ??? */
226 	struct wapbl_ino_head *wl_inohash;
227 	u_long wl_inohashmask;
228 	int wl_inohashcnt;
229 
230 	SIMPLEQ_HEAD(, wapbl_entry) wl_entries; /* On disk transaction
231 						   accounting */
232 
233 	/* buffers for wapbl_buffered_write() */
234 	TAILQ_HEAD(, buf) wl_iobufs;		/* l: Free or filling bufs */
235 	TAILQ_HEAD(, buf) wl_iobufs_busy;	/* l: In-transit bufs */
236 
237 	int wl_dkcache;		/* r: 	disk cache flags */
238 #define WAPBL_USE_FUA(wl)	\
239 		(wapbl_allow_dpofua && ISSET((wl)->wl_dkcache, DKCACHE_FUA))
240 #define WAPBL_JFLAGS(wl)	\
241 		(WAPBL_USE_FUA(wl) ? (wl)->wl_jwrite_flags : 0)
242 #define WAPBL_JDATA_FLAGS(wl)	\
243 		(WAPBL_JFLAGS(wl) & B_MEDIA_DPO)	/* only DPO */
244 	int wl_jwrite_flags;	/* r: 	journal write flags */
245 };
246 
247 #ifdef WAPBL_DEBUG_PRINT
248 int wapbl_debug_print = WAPBL_DEBUG_PRINT;
249 #endif
250 
251 /****************************************************************/
252 #ifdef _KERNEL
253 
254 #ifdef WAPBL_DEBUG
255 struct wapbl *wapbl_debug_wl;
256 #endif
257 
258 static int wapbl_write_commit(struct wapbl *wl, off_t head, off_t tail);
259 static int wapbl_write_blocks(struct wapbl *wl, off_t *offp);
260 static int wapbl_write_revocations(struct wapbl *wl, off_t *offp);
261 static int wapbl_write_inodes(struct wapbl *wl, off_t *offp);
262 #endif /* _KERNEL */
263 
264 static int wapbl_replay_process(struct wapbl_replay *wr, off_t, off_t);
265 
266 static inline size_t wapbl_space_used(size_t avail, off_t head,
267 	off_t tail);
268 
269 #ifdef _KERNEL
270 
271 static struct pool wapbl_entry_pool;
272 static struct pool wapbl_dealloc_pool;
273 
274 #define	WAPBL_INODETRK_SIZE 83
275 static int wapbl_ino_pool_refcount;
276 static struct pool wapbl_ino_pool;
277 struct wapbl_ino {
278 	LIST_ENTRY(wapbl_ino) wi_hash;
279 	ino_t wi_ino;
280 	mode_t wi_mode;
281 };
282 
283 static void wapbl_inodetrk_init(struct wapbl *wl, u_int size);
284 static void wapbl_inodetrk_free(struct wapbl *wl);
285 static struct wapbl_ino *wapbl_inodetrk_get(struct wapbl *wl, ino_t ino);
286 
287 static size_t wapbl_transaction_len(struct wapbl *wl);
288 static inline size_t wapbl_transaction_inodes_len(struct wapbl *wl);
289 
290 static void wapbl_deallocation_free(struct wapbl *, struct wapbl_dealloc *,
291 	bool);
292 
293 static void wapbl_evcnt_init(struct wapbl *);
294 static void wapbl_evcnt_free(struct wapbl *);
295 
296 static void wapbl_dkcache_init(struct wapbl *);
297 
298 #if 0
299 int wapbl_replay_verify(struct wapbl_replay *, struct vnode *);
300 #endif
301 
302 static int wapbl_replay_isopen1(struct wapbl_replay *);
303 
304 struct wapbl_ops wapbl_ops = {
305 	.wo_wapbl_discard	= wapbl_discard,
306 	.wo_wapbl_replay_isopen	= wapbl_replay_isopen1,
307 	.wo_wapbl_replay_can_read = wapbl_replay_can_read,
308 	.wo_wapbl_replay_read	= wapbl_replay_read,
309 	.wo_wapbl_add_buf	= wapbl_add_buf,
310 	.wo_wapbl_remove_buf	= wapbl_remove_buf,
311 	.wo_wapbl_resize_buf	= wapbl_resize_buf,
312 	.wo_wapbl_begin		= wapbl_begin,
313 	.wo_wapbl_end		= wapbl_end,
314 	.wo_wapbl_junlock_assert= wapbl_junlock_assert,
315 
316 	/* XXX: the following is only used to say "this is a wapbl buf" */
317 	.wo_wapbl_biodone	= wapbl_biodone,
318 };
319 
320 static int
321 wapbl_sysctl_init(void)
322 {
323 	int rv;
324 	const struct sysctlnode *rnode, *cnode;
325 
326 	wapbl_sysctl = NULL;
327 
328 	rv = sysctl_createv(&wapbl_sysctl, 0, NULL, &rnode,
329 		       CTLFLAG_PERMANENT,
330 		       CTLTYPE_NODE, "wapbl",
331 		       SYSCTL_DESCR("WAPBL journaling options"),
332 		       NULL, 0, NULL, 0,
333 		       CTL_VFS, CTL_CREATE, CTL_EOL);
334 	if (rv)
335 		return rv;
336 
337 	rv = sysctl_createv(&wapbl_sysctl, 0, &rnode, &cnode,
338 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
339 		       CTLTYPE_INT, "flush_disk_cache",
340 		       SYSCTL_DESCR("flush disk cache"),
341 		       NULL, 0, &wapbl_flush_disk_cache, 0,
342 		       CTL_CREATE, CTL_EOL);
343 	if (rv)
344 		return rv;
345 
346 	rv = sysctl_createv(&wapbl_sysctl, 0, &rnode, &cnode,
347 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
348 		       CTLTYPE_INT, "verbose_commit",
349 		       SYSCTL_DESCR("show time and size of wapbl log commits"),
350 		       NULL, 0, &wapbl_verbose_commit, 0,
351 		       CTL_CREATE, CTL_EOL);
352 	if (rv)
353 		return rv;
354 
355 	rv = sysctl_createv(&wapbl_sysctl, 0, &rnode, &cnode,
356 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
357 		       CTLTYPE_INT, "allow_dpofua",
358 		       SYSCTL_DESCR("allow use of FUA/DPO instead of cash flush if available"),
359 		       NULL, 0, &wapbl_allow_dpofua, 0,
360 		       CTL_CREATE, CTL_EOL);
361 	if (rv)
362 		return rv;
363 
364 	rv = sysctl_createv(&wapbl_sysctl, 0, &rnode, &cnode,
365 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
366 		       CTLTYPE_INT, "journal_iobufs",
367 		       SYSCTL_DESCR("count of bufs used for journal I/O (max async count)"),
368 		       NULL, 0, &wapbl_journal_iobufs, 0,
369 		       CTL_CREATE, CTL_EOL);
370 	if (rv)
371 		return rv;
372 
373 	return rv;
374 }
375 
376 static void
377 wapbl_init(void)
378 {
379 
380 	pool_init(&wapbl_entry_pool, sizeof(struct wapbl_entry), 0, 0, 0,
381 	    "wapblentrypl", &pool_allocator_kmem, IPL_VM);
382 	pool_init(&wapbl_dealloc_pool, sizeof(struct wapbl_dealloc), 0, 0, 0,
383 	    "wapbldealloc", &pool_allocator_nointr, IPL_NONE);
384 
385 	wapbl_sysctl_init();
386 }
387 
388 static int
389 wapbl_fini(void)
390 {
391 
392 	if (wapbl_sysctl != NULL)
393 		 sysctl_teardown(&wapbl_sysctl);
394 
395 	pool_destroy(&wapbl_dealloc_pool);
396 	pool_destroy(&wapbl_entry_pool);
397 
398 	return 0;
399 }
400 
401 static void
402 wapbl_evcnt_init(struct wapbl *wl)
403 {
404 	snprintf(wl->wl_ev_group, sizeof(wl->wl_ev_group),
405 	    "wapbl fsid 0x%x/0x%x",
406 	    wl->wl_mount->mnt_stat.f_fsidx.__fsid_val[0],
407 	    wl->wl_mount->mnt_stat.f_fsidx.__fsid_val[1]
408 	);
409 
410 	evcnt_attach_dynamic(&wl->wl_ev_commit, EVCNT_TYPE_MISC,
411 	    NULL, wl->wl_ev_group, "commit");
412 	evcnt_attach_dynamic(&wl->wl_ev_journalwrite, EVCNT_TYPE_MISC,
413 	    NULL, wl->wl_ev_group, "journal write total");
414 	evcnt_attach_dynamic(&wl->wl_ev_jbufs_bio_nowait, EVCNT_TYPE_MISC,
415 	    NULL, wl->wl_ev_group, "journal write finished async");
416 	evcnt_attach_dynamic(&wl->wl_ev_metawrite, EVCNT_TYPE_MISC,
417 	    NULL, wl->wl_ev_group, "metadata async write");
418 	evcnt_attach_dynamic(&wl->wl_ev_cacheflush, EVCNT_TYPE_MISC,
419 	    NULL, wl->wl_ev_group, "cache flush");
420 }
421 
422 static void
423 wapbl_evcnt_free(struct wapbl *wl)
424 {
425 	evcnt_detach(&wl->wl_ev_commit);
426 	evcnt_detach(&wl->wl_ev_journalwrite);
427 	evcnt_detach(&wl->wl_ev_jbufs_bio_nowait);
428 	evcnt_detach(&wl->wl_ev_metawrite);
429 	evcnt_detach(&wl->wl_ev_cacheflush);
430 }
431 
432 static void
433 wapbl_dkcache_init(struct wapbl *wl)
434 {
435 	int error;
436 
437 	/* Get disk cache flags */
438 	error = VOP_IOCTL(wl->wl_devvp, DIOCGCACHE, &wl->wl_dkcache,
439 	    FWRITE, FSCRED);
440 	if (error) {
441 		/* behave as if there was a write cache */
442 		wl->wl_dkcache = DKCACHE_WRITE;
443 	}
444 
445 	/* Use FUA instead of cache flush if available */
446 	if (ISSET(wl->wl_dkcache, DKCACHE_FUA))
447 		wl->wl_jwrite_flags |= B_MEDIA_FUA;
448 
449 	/* Use DPO for journal writes if available */
450 	if (ISSET(wl->wl_dkcache, DKCACHE_DPO))
451 		wl->wl_jwrite_flags |= B_MEDIA_DPO;
452 }
453 
454 static int
455 wapbl_start_flush_inodes(struct wapbl *wl, struct wapbl_replay *wr)
456 {
457 	int error, i;
458 
459 	WAPBL_PRINTF(WAPBL_PRINT_REPLAY,
460 	    ("wapbl_start: reusing log with %d inodes\n", wr->wr_inodescnt));
461 
462 	/*
463 	 * Its only valid to reuse the replay log if its
464 	 * the same as the new log we just opened.
465 	 */
466 	KDASSERT(!wapbl_replay_isopen(wr));
467 	KASSERT(wl->wl_devvp->v_type == VBLK);
468 	KASSERT(wr->wr_devvp->v_type == VBLK);
469 	KASSERT(wl->wl_devvp->v_rdev == wr->wr_devvp->v_rdev);
470 	KASSERT(wl->wl_logpbn == wr->wr_logpbn);
471 	KASSERT(wl->wl_circ_size == wr->wr_circ_size);
472 	KASSERT(wl->wl_circ_off == wr->wr_circ_off);
473 	KASSERT(wl->wl_log_dev_bshift == wr->wr_log_dev_bshift);
474 	KASSERT(wl->wl_fs_dev_bshift == wr->wr_fs_dev_bshift);
475 
476 	wl->wl_wc_header->wc_generation = wr->wr_generation + 1;
477 
478 	for (i = 0; i < wr->wr_inodescnt; i++)
479 		wapbl_register_inode(wl, wr->wr_inodes[i].wr_inumber,
480 		    wr->wr_inodes[i].wr_imode);
481 
482 	/* Make sure new transaction won't overwrite old inodes list */
483 	KDASSERT(wapbl_transaction_len(wl) <=
484 	    wapbl_space_free(wl->wl_circ_size, wr->wr_inodeshead,
485 	    wr->wr_inodestail));
486 
487 	wl->wl_head = wl->wl_tail = wr->wr_inodeshead;
488 	wl->wl_reclaimable_bytes = wl->wl_reserved_bytes =
489 	    wapbl_transaction_len(wl);
490 
491 	error = wapbl_write_inodes(wl, &wl->wl_head);
492 	if (error)
493 		return error;
494 
495 	KASSERT(wl->wl_head != wl->wl_tail);
496 	KASSERT(wl->wl_head != 0);
497 
498 	return 0;
499 }
500 
501 int
502 wapbl_start(struct wapbl ** wlp, struct mount *mp, struct vnode *vp,
503 	daddr_t off, size_t count, size_t blksize, struct wapbl_replay *wr,
504 	wapbl_flush_fn_t flushfn, wapbl_flush_fn_t flushabortfn)
505 {
506 	struct wapbl *wl;
507 	struct vnode *devvp;
508 	daddr_t logpbn;
509 	int error;
510 	int log_dev_bshift = ilog2(blksize);
511 	int fs_dev_bshift = log_dev_bshift;
512 	int run;
513 
514 	WAPBL_PRINTF(WAPBL_PRINT_OPEN, ("wapbl_start: vp=%p off=%" PRId64
515 	    " count=%zu blksize=%zu\n", vp, off, count, blksize));
516 
517 	if (log_dev_bshift > fs_dev_bshift) {
518 		WAPBL_PRINTF(WAPBL_PRINT_OPEN,
519 			("wapbl: log device's block size cannot be larger "
520 			 "than filesystem's\n"));
521 		/*
522 		 * Not currently implemented, although it could be if
523 		 * needed someday.
524 		 */
525 		return ENOSYS;
526 	}
527 
528 	if (off < 0)
529 		return EINVAL;
530 
531 	if (blksize < DEV_BSIZE)
532 		return EINVAL;
533 	if (blksize % DEV_BSIZE)
534 		return EINVAL;
535 
536 	/* XXXTODO: verify that the full load is writable */
537 
538 	/*
539 	 * XXX check for minimum log size
540 	 * minimum is governed by minimum amount of space
541 	 * to complete a transaction. (probably truncate)
542 	 */
543 	/* XXX for now pick something minimal */
544 	if ((count * blksize) < MAXPHYS) {
545 		return ENOSPC;
546 	}
547 
548 	if ((error = VOP_BMAP(vp, off, &devvp, &logpbn, &run)) != 0) {
549 		return error;
550 	}
551 
552 	wl = wapbl_calloc(1, sizeof(*wl));
553 	rw_init(&wl->wl_rwlock);
554 	mutex_init(&wl->wl_mtx, MUTEX_DEFAULT, IPL_NONE);
555 	cv_init(&wl->wl_reclaimable_cv, "wapblrec");
556 	TAILQ_INIT(&wl->wl_bufs);
557 	SIMPLEQ_INIT(&wl->wl_entries);
558 
559 	wl->wl_logvp = vp;
560 	wl->wl_devvp = devvp;
561 	wl->wl_mount = mp;
562 	wl->wl_logpbn = logpbn;
563 	wl->wl_log_dev_bshift = log_dev_bshift;
564 	wl->wl_fs_dev_bshift = fs_dev_bshift;
565 
566 	wl->wl_flush = flushfn;
567 	wl->wl_flush_abort = flushabortfn;
568 
569 	/* Reserve two log device blocks for the commit headers */
570 	wl->wl_circ_off = 2<<wl->wl_log_dev_bshift;
571 	wl->wl_circ_size = ((count * blksize) - wl->wl_circ_off);
572 	/* truncate the log usage to a multiple of log_dev_bshift */
573 	wl->wl_circ_size >>= wl->wl_log_dev_bshift;
574 	wl->wl_circ_size <<= wl->wl_log_dev_bshift;
575 
576 	/*
577 	 * wl_bufbytes_max limits the size of the in memory transaction space.
578 	 * - Since buffers are allocated and accounted for in units of
579 	 *   PAGE_SIZE it is required to be a multiple of PAGE_SIZE
580 	 *   (i.e. 1<<PAGE_SHIFT)
581 	 * - Since the log device has to be written in units of
582 	 *   1<<wl_log_dev_bshift it is required to be a mulitple of
583 	 *   1<<wl_log_dev_bshift.
584 	 * - Since filesystem will provide data in units of 1<<wl_fs_dev_bshift,
585 	 *   it is convenient to be a multiple of 1<<wl_fs_dev_bshift.
586 	 * Therefore it must be multiple of the least common multiple of those
587 	 * three quantities.  Fortunately, all of those quantities are
588 	 * guaranteed to be a power of two, and the least common multiple of
589 	 * a set of numbers which are all powers of two is simply the maximum
590 	 * of those numbers.  Finally, the maximum logarithm of a power of two
591 	 * is the same as the log of the maximum power of two.  So we can do
592 	 * the following operations to size wl_bufbytes_max:
593 	 */
594 
595 	/* XXX fix actual number of pages reserved per filesystem. */
596 	wl->wl_bufbytes_max = MIN(wl->wl_circ_size, buf_memcalc() / 2);
597 
598 	/* Round wl_bufbytes_max to the largest power of two constraint */
599 	wl->wl_bufbytes_max >>= PAGE_SHIFT;
600 	wl->wl_bufbytes_max <<= PAGE_SHIFT;
601 	wl->wl_bufbytes_max >>= wl->wl_log_dev_bshift;
602 	wl->wl_bufbytes_max <<= wl->wl_log_dev_bshift;
603 	wl->wl_bufbytes_max >>= wl->wl_fs_dev_bshift;
604 	wl->wl_bufbytes_max <<= wl->wl_fs_dev_bshift;
605 
606 	/* XXX maybe use filesystem fragment size instead of 1024 */
607 	/* XXX fix actual number of buffers reserved per filesystem. */
608 	wl->wl_bufcount_max = (buf_nbuf() / 2) * 1024;
609 
610 	wl->wl_brperjblock = ((1<<wl->wl_log_dev_bshift)
611 	    - offsetof(struct wapbl_wc_blocklist, wc_blocks)) /
612 	    sizeof(((struct wapbl_wc_blocklist *)0)->wc_blocks[0]);
613 	KASSERT(wl->wl_brperjblock > 0);
614 
615 	/* XXX tie this into resource estimation */
616 	wl->wl_dealloclim = wl->wl_bufbytes_max / mp->mnt_stat.f_bsize / 2;
617 	TAILQ_INIT(&wl->wl_dealloclist);
618 
619 	wapbl_inodetrk_init(wl, WAPBL_INODETRK_SIZE);
620 
621 	wapbl_evcnt_init(wl);
622 
623 	wapbl_dkcache_init(wl);
624 
625 	/* Initialize the commit header */
626 	{
627 		struct wapbl_wc_header *wc;
628 		size_t len = 1 << wl->wl_log_dev_bshift;
629 		wc = wapbl_calloc(1, len);
630 		wc->wc_type = WAPBL_WC_HEADER;
631 		wc->wc_len = len;
632 		wc->wc_circ_off = wl->wl_circ_off;
633 		wc->wc_circ_size = wl->wl_circ_size;
634 		/* XXX wc->wc_fsid */
635 		wc->wc_log_dev_bshift = wl->wl_log_dev_bshift;
636 		wc->wc_fs_dev_bshift = wl->wl_fs_dev_bshift;
637 		wl->wl_wc_header = wc;
638 		wl->wl_wc_scratch = wapbl_alloc(len);
639 	}
640 
641 	TAILQ_INIT(&wl->wl_iobufs);
642 	TAILQ_INIT(&wl->wl_iobufs_busy);
643 	for (int i = 0; i < wapbl_journal_iobufs; i++) {
644 		struct buf *bp;
645 
646 		if ((bp = geteblk(MAXPHYS)) == NULL)
647 			goto errout;
648 
649 		mutex_enter(&bufcache_lock);
650 		mutex_enter(devvp->v_interlock);
651 		bgetvp(devvp, bp);
652 		mutex_exit(devvp->v_interlock);
653 		mutex_exit(&bufcache_lock);
654 
655 		bp->b_dev = devvp->v_rdev;
656 
657 		TAILQ_INSERT_TAIL(&wl->wl_iobufs, bp, b_wapbllist);
658 	}
659 
660 	/*
661 	 * if there was an existing set of unlinked but
662 	 * allocated inodes, preserve it in the new
663 	 * log.
664 	 */
665 	if (wr && wr->wr_inodescnt) {
666 		error = wapbl_start_flush_inodes(wl, wr);
667 		if (error)
668 			goto errout;
669 	}
670 
671 	error = wapbl_write_commit(wl, wl->wl_head, wl->wl_tail);
672 	if (error) {
673 		goto errout;
674 	}
675 
676 	*wlp = wl;
677 #if defined(WAPBL_DEBUG)
678 	wapbl_debug_wl = wl;
679 #endif
680 
681 	return 0;
682  errout:
683 	wapbl_discard(wl);
684 	wapbl_free(wl->wl_wc_scratch, wl->wl_wc_header->wc_len);
685 	wapbl_free(wl->wl_wc_header, wl->wl_wc_header->wc_len);
686 	while (!TAILQ_EMPTY(&wl->wl_iobufs)) {
687 		struct buf *bp;
688 
689 		bp = TAILQ_FIRST(&wl->wl_iobufs);
690 		TAILQ_REMOVE(&wl->wl_iobufs, bp, b_wapbllist);
691 		brelse(bp, BC_INVAL);
692 	}
693 	wapbl_inodetrk_free(wl);
694 	wapbl_free(wl, sizeof(*wl));
695 
696 	return error;
697 }
698 
699 /*
700  * Like wapbl_flush, only discards the transaction
701  * completely
702  */
703 
704 void
705 wapbl_discard(struct wapbl *wl)
706 {
707 	struct wapbl_entry *we;
708 	struct wapbl_dealloc *wd;
709 	struct buf *bp;
710 	int i;
711 
712 	/*
713 	 * XXX we may consider using upgrade here
714 	 * if we want to call flush from inside a transaction
715 	 */
716 	rw_enter(&wl->wl_rwlock, RW_WRITER);
717 	wl->wl_flush(wl->wl_mount, TAILQ_FIRST(&wl->wl_dealloclist));
718 
719 #ifdef WAPBL_DEBUG_PRINT
720 	{
721 		pid_t pid = -1;
722 		lwpid_t lid = -1;
723 		if (curproc)
724 			pid = curproc->p_pid;
725 		if (curlwp)
726 			lid = curlwp->l_lid;
727 #ifdef WAPBL_DEBUG_BUFBYTES
728 		WAPBL_PRINTF(WAPBL_PRINT_DISCARD,
729 		    ("wapbl_discard: thread %d.%d discarding "
730 		    "transaction\n"
731 		    "\tbufcount=%zu bufbytes=%zu bcount=%zu "
732 		    "deallocs=%d inodes=%d\n"
733 		    "\terrcnt = %u, reclaimable=%zu reserved=%zu "
734 		    "unsynced=%zu\n",
735 		    pid, lid, wl->wl_bufcount, wl->wl_bufbytes,
736 		    wl->wl_bcount, wl->wl_dealloccnt,
737 		    wl->wl_inohashcnt, wl->wl_error_count,
738 		    wl->wl_reclaimable_bytes, wl->wl_reserved_bytes,
739 		    wl->wl_unsynced_bufbytes));
740 		SIMPLEQ_FOREACH(we, &wl->wl_entries, we_entries) {
741 			WAPBL_PRINTF(WAPBL_PRINT_DISCARD,
742 			    ("\tentry: bufcount = %zu, reclaimable = %zu, "
743 			     "error = %d, unsynced = %zu\n",
744 			     we->we_bufcount, we->we_reclaimable_bytes,
745 			     we->we_error, we->we_unsynced_bufbytes));
746 		}
747 #else /* !WAPBL_DEBUG_BUFBYTES */
748 		WAPBL_PRINTF(WAPBL_PRINT_DISCARD,
749 		    ("wapbl_discard: thread %d.%d discarding transaction\n"
750 		    "\tbufcount=%zu bufbytes=%zu bcount=%zu "
751 		    "deallocs=%d inodes=%d\n"
752 		    "\terrcnt = %u, reclaimable=%zu reserved=%zu\n",
753 		    pid, lid, wl->wl_bufcount, wl->wl_bufbytes,
754 		    wl->wl_bcount, wl->wl_dealloccnt,
755 		    wl->wl_inohashcnt, wl->wl_error_count,
756 		    wl->wl_reclaimable_bytes, wl->wl_reserved_bytes));
757 		SIMPLEQ_FOREACH(we, &wl->wl_entries, we_entries) {
758 			WAPBL_PRINTF(WAPBL_PRINT_DISCARD,
759 			    ("\tentry: bufcount = %zu, reclaimable = %zu, "
760 			     "error = %d\n",
761 			     we->we_bufcount, we->we_reclaimable_bytes,
762 			     we->we_error));
763 		}
764 #endif /* !WAPBL_DEBUG_BUFBYTES */
765 	}
766 #endif /* WAPBL_DEBUG_PRINT */
767 
768 	for (i = 0; i <= wl->wl_inohashmask; i++) {
769 		struct wapbl_ino_head *wih;
770 		struct wapbl_ino *wi;
771 
772 		wih = &wl->wl_inohash[i];
773 		while ((wi = LIST_FIRST(wih)) != NULL) {
774 			LIST_REMOVE(wi, wi_hash);
775 			pool_put(&wapbl_ino_pool, wi);
776 			KASSERT(wl->wl_inohashcnt > 0);
777 			wl->wl_inohashcnt--;
778 		}
779 	}
780 
781 	/*
782 	 * clean buffer list
783 	 */
784 	mutex_enter(&bufcache_lock);
785 	mutex_enter(&wl->wl_mtx);
786 	while ((bp = TAILQ_FIRST(&wl->wl_bufs)) != NULL) {
787 		if (bbusy(bp, 0, 0, &wl->wl_mtx) == 0) {
788 			/*
789 			 * The buffer will be unlocked and
790 			 * removed from the transaction in brelse
791 			 */
792 			mutex_exit(&wl->wl_mtx);
793 			brelsel(bp, 0);
794 			mutex_enter(&wl->wl_mtx);
795 		}
796 	}
797 	mutex_exit(&wl->wl_mtx);
798 	mutex_exit(&bufcache_lock);
799 
800 	/*
801 	 * Remove references to this wl from wl_entries, free any which
802 	 * no longer have buffers, others will be freed in wapbl_biodone
803 	 * when they no longer have any buffers.
804 	 */
805 	while ((we = SIMPLEQ_FIRST(&wl->wl_entries)) != NULL) {
806 		SIMPLEQ_REMOVE_HEAD(&wl->wl_entries, we_entries);
807 		/* XXX should we be accumulating wl_error_count
808 		 * and increasing reclaimable bytes ? */
809 		we->we_wapbl = NULL;
810 		if (we->we_bufcount == 0) {
811 #ifdef WAPBL_DEBUG_BUFBYTES
812 			KASSERT(we->we_unsynced_bufbytes == 0);
813 #endif
814 			pool_put(&wapbl_entry_pool, we);
815 		}
816 	}
817 
818 	/* Discard list of deallocs */
819 	while ((wd = TAILQ_FIRST(&wl->wl_dealloclist)) != NULL)
820 		wapbl_deallocation_free(wl, wd, true);
821 
822 	/* XXX should we clear wl_reserved_bytes? */
823 
824 	KASSERT(wl->wl_bufbytes == 0);
825 	KASSERT(wl->wl_bcount == 0);
826 	KASSERT(wl->wl_bufcount == 0);
827 	KASSERT(TAILQ_EMPTY(&wl->wl_bufs));
828 	KASSERT(SIMPLEQ_EMPTY(&wl->wl_entries));
829 	KASSERT(wl->wl_inohashcnt == 0);
830 	KASSERT(TAILQ_EMPTY(&wl->wl_dealloclist));
831 	KASSERT(wl->wl_dealloccnt == 0);
832 
833 	rw_exit(&wl->wl_rwlock);
834 }
835 
836 int
837 wapbl_stop(struct wapbl *wl, int force)
838 {
839 	int error;
840 
841 	WAPBL_PRINTF(WAPBL_PRINT_OPEN, ("wapbl_stop called\n"));
842 	error = wapbl_flush(wl, 1);
843 	if (error) {
844 		if (force)
845 			wapbl_discard(wl);
846 		else
847 			return error;
848 	}
849 
850 	/* Unlinked inodes persist after a flush */
851 	if (wl->wl_inohashcnt) {
852 		if (force) {
853 			wapbl_discard(wl);
854 		} else {
855 			return EBUSY;
856 		}
857 	}
858 
859 	KASSERT(wl->wl_bufbytes == 0);
860 	KASSERT(wl->wl_bcount == 0);
861 	KASSERT(wl->wl_bufcount == 0);
862 	KASSERT(TAILQ_EMPTY(&wl->wl_bufs));
863 	KASSERT(wl->wl_dealloccnt == 0);
864 	KASSERT(SIMPLEQ_EMPTY(&wl->wl_entries));
865 	KASSERT(wl->wl_inohashcnt == 0);
866 	KASSERT(TAILQ_EMPTY(&wl->wl_dealloclist));
867 	KASSERT(wl->wl_dealloccnt == 0);
868 	KASSERT(TAILQ_EMPTY(&wl->wl_iobufs_busy));
869 
870 	wapbl_free(wl->wl_wc_scratch, wl->wl_wc_header->wc_len);
871 	wapbl_free(wl->wl_wc_header, wl->wl_wc_header->wc_len);
872 	while (!TAILQ_EMPTY(&wl->wl_iobufs)) {
873 		struct buf *bp;
874 
875 		bp = TAILQ_FIRST(&wl->wl_iobufs);
876 		TAILQ_REMOVE(&wl->wl_iobufs, bp, b_wapbllist);
877 		brelse(bp, BC_INVAL);
878 	}
879 	wapbl_inodetrk_free(wl);
880 
881 	wapbl_evcnt_free(wl);
882 
883 	cv_destroy(&wl->wl_reclaimable_cv);
884 	mutex_destroy(&wl->wl_mtx);
885 	rw_destroy(&wl->wl_rwlock);
886 	wapbl_free(wl, sizeof(*wl));
887 
888 	return 0;
889 }
890 
891 /****************************************************************/
892 /*
893  * Unbuffered disk I/O
894  */
895 
896 static void
897 wapbl_doio_accounting(struct vnode *devvp, int flags)
898 {
899 	struct pstats *pstats = curlwp->l_proc->p_stats;
900 
901 	if ((flags & (B_WRITE | B_READ)) == B_WRITE) {
902 		mutex_enter(devvp->v_interlock);
903 		devvp->v_numoutput++;
904 		mutex_exit(devvp->v_interlock);
905 		pstats->p_ru.ru_oublock++;
906 	} else {
907 		pstats->p_ru.ru_inblock++;
908 	}
909 
910 }
911 
912 static int
913 wapbl_doio(void *data, size_t len, struct vnode *devvp, daddr_t pbn, int flags)
914 {
915 	struct buf *bp;
916 	int error;
917 
918 	KASSERT(devvp->v_type == VBLK);
919 
920 	wapbl_doio_accounting(devvp, flags);
921 
922 	bp = getiobuf(devvp, true);
923 	bp->b_flags = flags;
924 	bp->b_cflags = BC_BUSY;	/* mandatory, asserted by biowait() */
925 	bp->b_dev = devvp->v_rdev;
926 	bp->b_data = data;
927 	bp->b_bufsize = bp->b_resid = bp->b_bcount = len;
928 	bp->b_blkno = pbn;
929 	BIO_SETPRIO(bp, BPRIO_TIMECRITICAL);
930 
931 	WAPBL_PRINTF(WAPBL_PRINT_IO,
932 	    ("wapbl_doio: %s %d bytes at block %"PRId64" on dev 0x%"PRIx64"\n",
933 	    BUF_ISWRITE(bp) ? "write" : "read", bp->b_bcount,
934 	    bp->b_blkno, bp->b_dev));
935 
936 	VOP_STRATEGY(devvp, bp);
937 
938 	error = biowait(bp);
939 	putiobuf(bp);
940 
941 	if (error) {
942 		WAPBL_PRINTF(WAPBL_PRINT_ERROR,
943 		    ("wapbl_doio: %s %zu bytes at block %" PRId64
944 		    " on dev 0x%"PRIx64" failed with error %d\n",
945 		    (((flags & (B_WRITE | B_READ)) == B_WRITE) ?
946 		     "write" : "read"),
947 		    len, pbn, devvp->v_rdev, error));
948 	}
949 
950 	return error;
951 }
952 
953 /*
954  * wapbl_write(data, len, devvp, pbn)
955  *
956  *	Synchronously write len bytes from data to physical block pbn
957  *	on devvp.
958  */
959 int
960 wapbl_write(void *data, size_t len, struct vnode *devvp, daddr_t pbn)
961 {
962 
963 	return wapbl_doio(data, len, devvp, pbn, B_WRITE);
964 }
965 
966 /*
967  * wapbl_read(data, len, devvp, pbn)
968  *
969  *	Synchronously read len bytes into data from physical block pbn
970  *	on devvp.
971  */
972 int
973 wapbl_read(void *data, size_t len, struct vnode *devvp, daddr_t pbn)
974 {
975 
976 	return wapbl_doio(data, len, devvp, pbn, B_READ);
977 }
978 
979 /****************************************************************/
980 /*
981  * Buffered disk writes -- try to coalesce writes and emit
982  * MAXPHYS-aligned blocks.
983  */
984 
985 /*
986  * wapbl_buffered_write_async(wl, bp)
987  *
988  *	Send buffer for asynchronous write.
989  */
990 static void
991 wapbl_buffered_write_async(struct wapbl *wl, struct buf *bp)
992 {
993 	wapbl_doio_accounting(wl->wl_devvp, bp->b_flags);
994 
995 	KASSERT(TAILQ_FIRST(&wl->wl_iobufs) == bp);
996 	TAILQ_REMOVE(&wl->wl_iobufs, bp, b_wapbllist);
997 
998 	bp->b_flags |= B_WRITE;
999 	bp->b_cflags = BC_BUSY;	/* mandatory, asserted by biowait() */
1000 	bp->b_oflags = 0;
1001 	bp->b_bcount = bp->b_resid;
1002 	BIO_SETPRIO(bp, BPRIO_TIMECRITICAL);
1003 
1004 	VOP_STRATEGY(wl->wl_devvp, bp);
1005 
1006 	wl->wl_ev_journalwrite.ev_count++;
1007 
1008 	TAILQ_INSERT_TAIL(&wl->wl_iobufs_busy, bp, b_wapbllist);
1009 }
1010 
1011 /*
1012  * wapbl_buffered_flush(wl)
1013  *
1014  *	Flush any buffered writes from wapbl_buffered_write.
1015  */
1016 static int
1017 wapbl_buffered_flush(struct wapbl *wl, bool full)
1018 {
1019 	int error = 0;
1020 	struct buf *bp, *bnext;
1021 	bool only_done = true, found = false;
1022 
1023 	/* if there is outstanding buffered write, send it now */
1024 	if ((bp = TAILQ_FIRST(&wl->wl_iobufs)) && bp->b_resid > 0)
1025 		wapbl_buffered_write_async(wl, bp);
1026 
1027 	/* wait for I/O to complete */
1028 again:
1029 	TAILQ_FOREACH_SAFE(bp, &wl->wl_iobufs_busy, b_wapbllist, bnext) {
1030 		if (!full && only_done) {
1031 			/* skip unfinished */
1032 			if (!ISSET(bp->b_oflags, BO_DONE))
1033 				continue;
1034 		}
1035 
1036 		if (ISSET(bp->b_oflags, BO_DONE))
1037 			wl->wl_ev_jbufs_bio_nowait.ev_count++;
1038 
1039 		TAILQ_REMOVE(&wl->wl_iobufs_busy, bp, b_wapbllist);
1040 		error = biowait(bp);
1041 
1042 		/* reset for reuse */
1043 		bp->b_blkno = bp->b_resid = bp->b_flags = 0;
1044 		TAILQ_INSERT_TAIL(&wl->wl_iobufs, bp, b_wapbllist);
1045 		found = true;
1046 
1047 		if (!full)
1048 			break;
1049 	}
1050 
1051 	if (!found && only_done && !TAILQ_EMPTY(&wl->wl_iobufs_busy)) {
1052 		only_done = false;
1053 		goto again;
1054 	}
1055 
1056 	return error;
1057 }
1058 
1059 /*
1060  * wapbl_buffered_write(data, len, wl, pbn)
1061  *
1062  *	Write len bytes from data to physical block pbn on
1063  *	wl->wl_devvp.  The write may not complete until
1064  *	wapbl_buffered_flush.
1065  */
1066 static int
1067 wapbl_buffered_write(void *data, size_t len, struct wapbl *wl, daddr_t pbn,
1068     int bflags)
1069 {
1070 	size_t resid;
1071 	struct buf *bp;
1072 
1073 again:
1074 	bp = TAILQ_FIRST(&wl->wl_iobufs);
1075 
1076 	if (bp == NULL) {
1077 		/* No more buffers, wait for any previous I/O to finish. */
1078 		wapbl_buffered_flush(wl, false);
1079 
1080 		bp = TAILQ_FIRST(&wl->wl_iobufs);
1081 		KASSERT(bp != NULL);
1082 	}
1083 
1084 	/*
1085 	 * If not adjacent to buffered data flush first.  Disk block
1086 	 * address is always valid for non-empty buffer.
1087 	 */
1088 	if ((bp->b_resid > 0 && pbn != bp->b_blkno + btodb(bp->b_resid))) {
1089 		wapbl_buffered_write_async(wl, bp);
1090 		goto again;
1091 	}
1092 
1093 	/*
1094 	 * If this write goes to an empty buffer we have to
1095 	 * save the disk block address first.
1096 	 */
1097 	if (bp->b_blkno == 0) {
1098 		bp->b_blkno = pbn;
1099 		bp->b_flags |= bflags;
1100 	}
1101 
1102 	/*
1103 	 * Remaining space so this buffer ends on a buffer size boundary.
1104 	 *
1105 	 * Cannot become less or equal zero as the buffer would have been
1106 	 * flushed on the last call then.
1107 	 */
1108 	resid = bp->b_bufsize - dbtob(bp->b_blkno % btodb(bp->b_bufsize)) -
1109 	    bp->b_resid;
1110 	KASSERT(resid > 0);
1111 	KASSERT(dbtob(btodb(resid)) == resid);
1112 
1113 	if (len < resid)
1114 		resid = len;
1115 
1116 	memcpy((uint8_t *)bp->b_data + bp->b_resid, data, resid);
1117 	bp->b_resid += resid;
1118 
1119 	if (len >= resid) {
1120 		/* Just filled the buf, or data did not fit */
1121 		wapbl_buffered_write_async(wl, bp);
1122 
1123 		data = (uint8_t *)data + resid;
1124 		len -= resid;
1125 		pbn += btodb(resid);
1126 
1127 		if (len > 0)
1128 			goto again;
1129 	}
1130 
1131 	return 0;
1132 }
1133 
1134 /*
1135  * wapbl_circ_write(wl, data, len, offp)
1136  *
1137  *	Write len bytes from data to the circular queue of wl, starting
1138  *	at linear byte offset *offp, and returning the new linear byte
1139  *	offset in *offp.
1140  *
1141  *	If the starting linear byte offset precedes wl->wl_circ_off,
1142  *	the write instead begins at wl->wl_circ_off.  XXX WTF?  This
1143  *	should be a KASSERT, not a conditional.
1144  *
1145  *	The write is buffered in wl and must be flushed with
1146  *	wapbl_buffered_flush before it will be submitted to the disk.
1147  */
1148 static int
1149 wapbl_circ_write(struct wapbl *wl, void *data, size_t len, off_t *offp)
1150 {
1151 	size_t slen;
1152 	off_t off = *offp;
1153 	int error;
1154 	daddr_t pbn;
1155 
1156 	KDASSERT(((len >> wl->wl_log_dev_bshift) <<
1157 	    wl->wl_log_dev_bshift) == len);
1158 
1159 	if (off < wl->wl_circ_off)
1160 		off = wl->wl_circ_off;
1161 	slen = wl->wl_circ_off + wl->wl_circ_size - off;
1162 	if (slen < len) {
1163 		pbn = wl->wl_logpbn + (off >> wl->wl_log_dev_bshift);
1164 #ifdef _KERNEL
1165 		pbn = btodb(pbn << wl->wl_log_dev_bshift);
1166 #endif
1167 		error = wapbl_buffered_write(data, slen, wl, pbn,
1168 		    WAPBL_JDATA_FLAGS(wl));
1169 		if (error)
1170 			return error;
1171 		data = (uint8_t *)data + slen;
1172 		len -= slen;
1173 		off = wl->wl_circ_off;
1174 	}
1175 	pbn = wl->wl_logpbn + (off >> wl->wl_log_dev_bshift);
1176 #ifdef _KERNEL
1177 	pbn = btodb(pbn << wl->wl_log_dev_bshift);
1178 #endif
1179 	error = wapbl_buffered_write(data, len, wl, pbn,
1180 	    WAPBL_JDATA_FLAGS(wl));
1181 	if (error)
1182 		return error;
1183 	off += len;
1184 	if (off >= wl->wl_circ_off + wl->wl_circ_size)
1185 		off = wl->wl_circ_off;
1186 	*offp = off;
1187 	return 0;
1188 }
1189 
1190 /****************************************************************/
1191 /*
1192  * WAPBL transactions: entering, adding/removing bufs, and exiting
1193  */
1194 
1195 int
1196 wapbl_begin(struct wapbl *wl, const char *file, int line)
1197 {
1198 	int doflush;
1199 	unsigned lockcount;
1200 
1201 	KDASSERT(wl);
1202 
1203 	/*
1204 	 * XXX this needs to be made much more sophisticated.
1205 	 * perhaps each wapbl_begin could reserve a specified
1206 	 * number of buffers and bytes.
1207 	 */
1208 	mutex_enter(&wl->wl_mtx);
1209 	lockcount = wl->wl_lock_count;
1210 	doflush = ((wl->wl_bufbytes + (lockcount * MAXPHYS)) >
1211 		   wl->wl_bufbytes_max / 2) ||
1212 		  ((wl->wl_bufcount + (lockcount * 10)) >
1213 		   wl->wl_bufcount_max / 2) ||
1214 		  (wapbl_transaction_len(wl) > wl->wl_circ_size / 2) ||
1215 		  (wl->wl_dealloccnt >= (wl->wl_dealloclim / 2));
1216 	mutex_exit(&wl->wl_mtx);
1217 
1218 	if (doflush) {
1219 		WAPBL_PRINTF(WAPBL_PRINT_FLUSH,
1220 		    ("force flush lockcnt=%d bufbytes=%zu "
1221 		    "(max=%zu) bufcount=%zu (max=%zu) "
1222 		    "dealloccnt %d (lim=%d)\n",
1223 		    lockcount, wl->wl_bufbytes,
1224 		    wl->wl_bufbytes_max, wl->wl_bufcount,
1225 		    wl->wl_bufcount_max,
1226 		    wl->wl_dealloccnt, wl->wl_dealloclim));
1227 	}
1228 
1229 	if (doflush) {
1230 		int error = wapbl_flush(wl, 0);
1231 		if (error)
1232 			return error;
1233 	}
1234 
1235 	rw_enter(&wl->wl_rwlock, RW_READER);
1236 	mutex_enter(&wl->wl_mtx);
1237 	wl->wl_lock_count++;
1238 	mutex_exit(&wl->wl_mtx);
1239 
1240 #if defined(WAPBL_DEBUG_PRINT)
1241 	WAPBL_PRINTF(WAPBL_PRINT_TRANSACTION,
1242 	    ("wapbl_begin thread %d.%d with bufcount=%zu "
1243 	    "bufbytes=%zu bcount=%zu at %s:%d\n",
1244 	    curproc->p_pid, curlwp->l_lid, wl->wl_bufcount,
1245 	    wl->wl_bufbytes, wl->wl_bcount, file, line));
1246 #endif
1247 
1248 	return 0;
1249 }
1250 
1251 void
1252 wapbl_end(struct wapbl *wl)
1253 {
1254 
1255 #if defined(WAPBL_DEBUG_PRINT)
1256 	WAPBL_PRINTF(WAPBL_PRINT_TRANSACTION,
1257 	     ("wapbl_end thread %d.%d with bufcount=%zu "
1258 	      "bufbytes=%zu bcount=%zu\n",
1259 	      curproc->p_pid, curlwp->l_lid, wl->wl_bufcount,
1260 	      wl->wl_bufbytes, wl->wl_bcount));
1261 #endif
1262 
1263 	/*
1264 	 * XXX this could be handled more gracefully, perhaps place
1265 	 * only a partial transaction in the log and allow the
1266 	 * remaining to flush without the protection of the journal.
1267 	 */
1268 	KASSERTMSG((wapbl_transaction_len(wl) <=
1269 		(wl->wl_circ_size - wl->wl_reserved_bytes)),
1270 	    "wapbl_end: current transaction too big to flush");
1271 
1272 	mutex_enter(&wl->wl_mtx);
1273 	KASSERT(wl->wl_lock_count > 0);
1274 	wl->wl_lock_count--;
1275 	mutex_exit(&wl->wl_mtx);
1276 
1277 	rw_exit(&wl->wl_rwlock);
1278 }
1279 
1280 void
1281 wapbl_add_buf(struct wapbl *wl, struct buf * bp)
1282 {
1283 
1284 	KASSERT(bp->b_cflags & BC_BUSY);
1285 	KASSERT(bp->b_vp);
1286 
1287 	wapbl_jlock_assert(wl);
1288 
1289 #if 0
1290 	/*
1291 	 * XXX this might be an issue for swapfiles.
1292 	 * see uvm_swap.c:1702
1293 	 *
1294 	 * XXX2 why require it then?  leap of semantics?
1295 	 */
1296 	KASSERT((bp->b_cflags & BC_NOCACHE) == 0);
1297 #endif
1298 
1299 	mutex_enter(&wl->wl_mtx);
1300 	if (bp->b_flags & B_LOCKED) {
1301 		TAILQ_REMOVE(&wl->wl_bufs, bp, b_wapbllist);
1302 		WAPBL_PRINTF(WAPBL_PRINT_BUFFER2,
1303 		   ("wapbl_add_buf thread %d.%d re-adding buf %p "
1304 		    "with %d bytes %d bcount\n",
1305 		    curproc->p_pid, curlwp->l_lid, bp, bp->b_bufsize,
1306 		    bp->b_bcount));
1307 	} else {
1308 		/* unlocked by dirty buffers shouldn't exist */
1309 		KASSERT(!(bp->b_oflags & BO_DELWRI));
1310 		wl->wl_bufbytes += bp->b_bufsize;
1311 		wl->wl_bcount += bp->b_bcount;
1312 		wl->wl_bufcount++;
1313 		WAPBL_PRINTF(WAPBL_PRINT_BUFFER,
1314 		   ("wapbl_add_buf thread %d.%d adding buf %p "
1315 		    "with %d bytes %d bcount\n",
1316 		    curproc->p_pid, curlwp->l_lid, bp, bp->b_bufsize,
1317 		    bp->b_bcount));
1318 	}
1319 	TAILQ_INSERT_TAIL(&wl->wl_bufs, bp, b_wapbllist);
1320 	mutex_exit(&wl->wl_mtx);
1321 
1322 	bp->b_flags |= B_LOCKED;
1323 }
1324 
1325 static void
1326 wapbl_remove_buf_locked(struct wapbl * wl, struct buf *bp)
1327 {
1328 
1329 	KASSERT(mutex_owned(&wl->wl_mtx));
1330 	KASSERT(bp->b_cflags & BC_BUSY);
1331 	wapbl_jlock_assert(wl);
1332 
1333 #if 0
1334 	/*
1335 	 * XXX this might be an issue for swapfiles.
1336 	 * see uvm_swap.c:1725
1337 	 *
1338 	 * XXXdeux: see above
1339 	 */
1340 	KASSERT((bp->b_flags & BC_NOCACHE) == 0);
1341 #endif
1342 	KASSERT(bp->b_flags & B_LOCKED);
1343 
1344 	WAPBL_PRINTF(WAPBL_PRINT_BUFFER,
1345 	   ("wapbl_remove_buf thread %d.%d removing buf %p with "
1346 	    "%d bytes %d bcount\n",
1347 	    curproc->p_pid, curlwp->l_lid, bp, bp->b_bufsize, bp->b_bcount));
1348 
1349 	KASSERT(wl->wl_bufbytes >= bp->b_bufsize);
1350 	wl->wl_bufbytes -= bp->b_bufsize;
1351 	KASSERT(wl->wl_bcount >= bp->b_bcount);
1352 	wl->wl_bcount -= bp->b_bcount;
1353 	KASSERT(wl->wl_bufcount > 0);
1354 	wl->wl_bufcount--;
1355 	KASSERT((wl->wl_bufcount == 0) == (wl->wl_bufbytes == 0));
1356 	KASSERT((wl->wl_bufcount == 0) == (wl->wl_bcount == 0));
1357 	TAILQ_REMOVE(&wl->wl_bufs, bp, b_wapbllist);
1358 
1359 	bp->b_flags &= ~B_LOCKED;
1360 }
1361 
1362 /* called from brelsel() in vfs_bio among other places */
1363 void
1364 wapbl_remove_buf(struct wapbl * wl, struct buf *bp)
1365 {
1366 
1367 	mutex_enter(&wl->wl_mtx);
1368 	wapbl_remove_buf_locked(wl, bp);
1369 	mutex_exit(&wl->wl_mtx);
1370 }
1371 
1372 void
1373 wapbl_resize_buf(struct wapbl *wl, struct buf *bp, long oldsz, long oldcnt)
1374 {
1375 
1376 	KASSERT(bp->b_cflags & BC_BUSY);
1377 
1378 	/*
1379 	 * XXX: why does this depend on B_LOCKED?  otherwise the buf
1380 	 * is not for a transaction?  if so, why is this called in the
1381 	 * first place?
1382 	 */
1383 	if (bp->b_flags & B_LOCKED) {
1384 		mutex_enter(&wl->wl_mtx);
1385 		wl->wl_bufbytes += bp->b_bufsize - oldsz;
1386 		wl->wl_bcount += bp->b_bcount - oldcnt;
1387 		mutex_exit(&wl->wl_mtx);
1388 	}
1389 }
1390 
1391 #endif /* _KERNEL */
1392 
1393 /****************************************************************/
1394 /* Some utility inlines */
1395 
1396 /*
1397  * wapbl_space_used(avail, head, tail)
1398  *
1399  *	Number of bytes used in a circular queue of avail total bytes,
1400  *	from tail to head.
1401  */
1402 static inline size_t
1403 wapbl_space_used(size_t avail, off_t head, off_t tail)
1404 {
1405 
1406 	if (tail == 0) {
1407 		KASSERT(head == 0);
1408 		return 0;
1409 	}
1410 	return ((head + (avail - 1) - tail) % avail) + 1;
1411 }
1412 
1413 #ifdef _KERNEL
1414 /*
1415  * wapbl_advance(size, off, oldoff, delta)
1416  *
1417  *	Given a byte offset oldoff into a circular queue of size bytes
1418  *	starting at off, return a new byte offset oldoff + delta into
1419  *	the circular queue.
1420  */
1421 static inline off_t
1422 wapbl_advance(size_t size, size_t off, off_t oldoff, size_t delta)
1423 {
1424 	off_t newoff;
1425 
1426 	/* Define acceptable ranges for inputs. */
1427 	KASSERT(delta <= (size_t)size);
1428 	KASSERT((oldoff == 0) || ((size_t)oldoff >= off));
1429 	KASSERT(oldoff < (off_t)(size + off));
1430 
1431 	if ((oldoff == 0) && (delta != 0))
1432 		newoff = off + delta;
1433 	else if ((oldoff + delta) < (size + off))
1434 		newoff = oldoff + delta;
1435 	else
1436 		newoff = (oldoff + delta) - size;
1437 
1438 	/* Note some interesting axioms */
1439 	KASSERT((delta != 0) || (newoff == oldoff));
1440 	KASSERT((delta == 0) || (newoff != 0));
1441 	KASSERT((delta != (size)) || (newoff == oldoff));
1442 
1443 	/* Define acceptable ranges for output. */
1444 	KASSERT((newoff == 0) || ((size_t)newoff >= off));
1445 	KASSERT((size_t)newoff < (size + off));
1446 	return newoff;
1447 }
1448 
1449 /*
1450  * wapbl_space_free(avail, head, tail)
1451  *
1452  *	Number of bytes free in a circular queue of avail total bytes,
1453  *	in which everything from tail to head is used.
1454  */
1455 static inline size_t
1456 wapbl_space_free(size_t avail, off_t head, off_t tail)
1457 {
1458 
1459 	return avail - wapbl_space_used(avail, head, tail);
1460 }
1461 
1462 /*
1463  * wapbl_advance_head(size, off, delta, headp, tailp)
1464  *
1465  *	In a circular queue of size bytes starting at off, given the
1466  *	old head and tail offsets *headp and *tailp, store the new head
1467  *	and tail offsets in *headp and *tailp resulting from adding
1468  *	delta bytes of data to the head.
1469  */
1470 static inline void
1471 wapbl_advance_head(size_t size, size_t off, size_t delta, off_t *headp,
1472 		   off_t *tailp)
1473 {
1474 	off_t head = *headp;
1475 	off_t tail = *tailp;
1476 
1477 	KASSERT(delta <= wapbl_space_free(size, head, tail));
1478 	head = wapbl_advance(size, off, head, delta);
1479 	if ((tail == 0) && (head != 0))
1480 		tail = off;
1481 	*headp = head;
1482 	*tailp = tail;
1483 }
1484 
1485 /*
1486  * wapbl_advance_tail(size, off, delta, headp, tailp)
1487  *
1488  *	In a circular queue of size bytes starting at off, given the
1489  *	old head and tail offsets *headp and *tailp, store the new head
1490  *	and tail offsets in *headp and *tailp resulting from removing
1491  *	delta bytes of data from the tail.
1492  */
1493 static inline void
1494 wapbl_advance_tail(size_t size, size_t off, size_t delta, off_t *headp,
1495 		   off_t *tailp)
1496 {
1497 	off_t head = *headp;
1498 	off_t tail = *tailp;
1499 
1500 	KASSERT(delta <= wapbl_space_used(size, head, tail));
1501 	tail = wapbl_advance(size, off, tail, delta);
1502 	if (head == tail) {
1503 		head = tail = 0;
1504 	}
1505 	*headp = head;
1506 	*tailp = tail;
1507 }
1508 
1509 
1510 /****************************************************************/
1511 
1512 /*
1513  * wapbl_truncate(wl, minfree)
1514  *
1515  *	Wait until at least minfree bytes are available in the log.
1516  *
1517  *	If it was necessary to wait for writes to complete,
1518  *	advance the circular queue tail to reflect the new write
1519  *	completions and issue a write commit to the log.
1520  *
1521  *	=> Caller must hold wl->wl_rwlock writer lock.
1522  */
1523 static int
1524 wapbl_truncate(struct wapbl *wl, size_t minfree)
1525 {
1526 	size_t delta;
1527 	size_t avail;
1528 	off_t head;
1529 	off_t tail;
1530 	int error = 0;
1531 
1532 	KASSERT(minfree <= (wl->wl_circ_size - wl->wl_reserved_bytes));
1533 	KASSERT(rw_write_held(&wl->wl_rwlock));
1534 
1535 	mutex_enter(&wl->wl_mtx);
1536 
1537 	/*
1538 	 * First check to see if we have to do a commit
1539 	 * at all.
1540 	 */
1541 	avail = wapbl_space_free(wl->wl_circ_size, wl->wl_head, wl->wl_tail);
1542 	if (minfree < avail) {
1543 		mutex_exit(&wl->wl_mtx);
1544 		return 0;
1545 	}
1546 	minfree -= avail;
1547 	while ((wl->wl_error_count == 0) &&
1548 	    (wl->wl_reclaimable_bytes < minfree)) {
1549         	WAPBL_PRINTF(WAPBL_PRINT_TRUNCATE,
1550                    ("wapbl_truncate: sleeping on %p wl=%p bytes=%zd "
1551 		    "minfree=%zd\n",
1552                     &wl->wl_reclaimable_bytes, wl, wl->wl_reclaimable_bytes,
1553 		    minfree));
1554 
1555 		cv_wait(&wl->wl_reclaimable_cv, &wl->wl_mtx);
1556 	}
1557 	if (wl->wl_reclaimable_bytes < minfree) {
1558 		KASSERT(wl->wl_error_count);
1559 		/* XXX maybe get actual error from buffer instead someday? */
1560 		error = EIO;
1561 	}
1562 	head = wl->wl_head;
1563 	tail = wl->wl_tail;
1564 	delta = wl->wl_reclaimable_bytes;
1565 
1566 	/* If all of of the entries are flushed, then be sure to keep
1567 	 * the reserved bytes reserved.  Watch out for discarded transactions,
1568 	 * which could leave more bytes reserved than are reclaimable.
1569 	 */
1570 	if (SIMPLEQ_EMPTY(&wl->wl_entries) &&
1571 	    (delta >= wl->wl_reserved_bytes)) {
1572 		delta -= wl->wl_reserved_bytes;
1573 	}
1574 	wapbl_advance_tail(wl->wl_circ_size, wl->wl_circ_off, delta, &head,
1575 			   &tail);
1576 	KDASSERT(wl->wl_reserved_bytes <=
1577 		wapbl_space_used(wl->wl_circ_size, head, tail));
1578 	mutex_exit(&wl->wl_mtx);
1579 
1580 	if (error)
1581 		return error;
1582 
1583 	/*
1584 	 * This is where head, tail and delta are unprotected
1585 	 * from races against itself or flush.  This is ok since
1586 	 * we only call this routine from inside flush itself.
1587 	 *
1588 	 * XXX: how can it race against itself when accessed only
1589 	 * from behind the write-locked rwlock?
1590 	 */
1591 	error = wapbl_write_commit(wl, head, tail);
1592 	if (error)
1593 		return error;
1594 
1595 	wl->wl_head = head;
1596 	wl->wl_tail = tail;
1597 
1598 	mutex_enter(&wl->wl_mtx);
1599 	KASSERT(wl->wl_reclaimable_bytes >= delta);
1600 	wl->wl_reclaimable_bytes -= delta;
1601 	mutex_exit(&wl->wl_mtx);
1602 	WAPBL_PRINTF(WAPBL_PRINT_TRUNCATE,
1603 	    ("wapbl_truncate thread %d.%d truncating %zu bytes\n",
1604 	    curproc->p_pid, curlwp->l_lid, delta));
1605 
1606 	return 0;
1607 }
1608 
1609 /****************************************************************/
1610 
1611 void
1612 wapbl_biodone(struct buf *bp)
1613 {
1614 	struct wapbl_entry *we = bp->b_private;
1615 	struct wapbl *wl = we->we_wapbl;
1616 #ifdef WAPBL_DEBUG_BUFBYTES
1617 	const int bufsize = bp->b_bufsize;
1618 #endif
1619 
1620 	/*
1621 	 * Handle possible flushing of buffers after log has been
1622 	 * decomissioned.
1623 	 */
1624 	if (!wl) {
1625 		KASSERT(we->we_bufcount > 0);
1626 		we->we_bufcount--;
1627 #ifdef WAPBL_DEBUG_BUFBYTES
1628 		KASSERT(we->we_unsynced_bufbytes >= bufsize);
1629 		we->we_unsynced_bufbytes -= bufsize;
1630 #endif
1631 
1632 		if (we->we_bufcount == 0) {
1633 #ifdef WAPBL_DEBUG_BUFBYTES
1634 			KASSERT(we->we_unsynced_bufbytes == 0);
1635 #endif
1636 			pool_put(&wapbl_entry_pool, we);
1637 		}
1638 
1639 		brelse(bp, 0);
1640 		return;
1641 	}
1642 
1643 #ifdef ohbother
1644 	KDASSERT(bp->b_oflags & BO_DONE);
1645 	KDASSERT(!(bp->b_oflags & BO_DELWRI));
1646 	KDASSERT(bp->b_flags & B_ASYNC);
1647 	KDASSERT(bp->b_cflags & BC_BUSY);
1648 	KDASSERT(!(bp->b_flags & B_LOCKED));
1649 	KDASSERT(!(bp->b_flags & B_READ));
1650 	KDASSERT(!(bp->b_cflags & BC_INVAL));
1651 	KDASSERT(!(bp->b_cflags & BC_NOCACHE));
1652 #endif
1653 
1654 	if (bp->b_error) {
1655 		/*
1656 		 * If an error occurs, it would be nice to leave the buffer
1657 		 * as a delayed write on the LRU queue so that we can retry
1658 		 * it later. But buffercache(9) can't handle dirty buffer
1659 		 * reuse, so just mark the log permanently errored out.
1660 		 */
1661 		mutex_enter(&wl->wl_mtx);
1662 		if (wl->wl_error_count == 0) {
1663 			wl->wl_error_count++;
1664 			cv_broadcast(&wl->wl_reclaimable_cv);
1665 		}
1666 		mutex_exit(&wl->wl_mtx);
1667 	}
1668 
1669 	/*
1670 	 * Make sure that the buf doesn't retain the media flags, so that
1671 	 * e.g. wapbl_allow_fuadpo has immediate effect on any following I/O.
1672 	 * The flags will be set again if needed by another I/O.
1673 	 */
1674 	bp->b_flags &= ~B_MEDIA_FLAGS;
1675 
1676 	/*
1677 	 * Release the buffer here. wapbl_flush() may wait for the
1678 	 * log to become empty and we better unbusy the buffer before
1679 	 * wapbl_flush() returns.
1680 	 */
1681 	brelse(bp, 0);
1682 
1683 	mutex_enter(&wl->wl_mtx);
1684 
1685 	KASSERT(we->we_bufcount > 0);
1686 	we->we_bufcount--;
1687 #ifdef WAPBL_DEBUG_BUFBYTES
1688 	KASSERT(we->we_unsynced_bufbytes >= bufsize);
1689 	we->we_unsynced_bufbytes -= bufsize;
1690 	KASSERT(wl->wl_unsynced_bufbytes >= bufsize);
1691 	wl->wl_unsynced_bufbytes -= bufsize;
1692 #endif
1693 	wl->wl_ev_metawrite.ev_count++;
1694 
1695 	/*
1696 	 * If the current transaction can be reclaimed, start
1697 	 * at the beginning and reclaim any consecutive reclaimable
1698 	 * transactions.  If we successfully reclaim anything,
1699 	 * then wakeup anyone waiting for the reclaim.
1700 	 */
1701 	if (we->we_bufcount == 0) {
1702 		size_t delta = 0;
1703 		int errcnt = 0;
1704 #ifdef WAPBL_DEBUG_BUFBYTES
1705 		KDASSERT(we->we_unsynced_bufbytes == 0);
1706 #endif
1707 		/*
1708 		 * clear any posted error, since the buffer it came from
1709 		 * has successfully flushed by now
1710 		 */
1711 		while ((we = SIMPLEQ_FIRST(&wl->wl_entries)) &&
1712 		       (we->we_bufcount == 0)) {
1713 			delta += we->we_reclaimable_bytes;
1714 			if (we->we_error)
1715 				errcnt++;
1716 			SIMPLEQ_REMOVE_HEAD(&wl->wl_entries, we_entries);
1717 			pool_put(&wapbl_entry_pool, we);
1718 		}
1719 
1720 		if (delta) {
1721 			wl->wl_reclaimable_bytes += delta;
1722 			KASSERT(wl->wl_error_count >= errcnt);
1723 			wl->wl_error_count -= errcnt;
1724 			cv_broadcast(&wl->wl_reclaimable_cv);
1725 		}
1726 	}
1727 
1728 	mutex_exit(&wl->wl_mtx);
1729 }
1730 
1731 /*
1732  * wapbl_flush(wl, wait)
1733  *
1734  *	Flush pending block writes, deallocations, and inodes from
1735  *	the current transaction in memory to the log on disk:
1736  *
1737  *	1. Call the file system's wl_flush callback to flush any
1738  *	   per-file-system pending updates.
1739  *	2. Wait for enough space in the log for the current transaction.
1740  *	3. Synchronously write the new log records, advancing the
1741  *	   circular queue head.
1742  *	4. Issue the pending block writes asynchronously, now that they
1743  *	   are recorded in the log and can be replayed after crash.
1744  *	5. If wait is true, wait for all writes to complete and for the
1745  *	   log to become empty.
1746  *
1747  *	On failure, call the file system's wl_flush_abort callback.
1748  */
1749 int
1750 wapbl_flush(struct wapbl *wl, int waitfor)
1751 {
1752 	struct buf *bp;
1753 	struct wapbl_entry *we;
1754 	off_t off;
1755 	off_t head;
1756 	off_t tail;
1757 	size_t delta = 0;
1758 	size_t flushsize;
1759 	size_t reserved;
1760 	int error = 0;
1761 
1762 	/*
1763 	 * Do a quick check to see if a full flush can be skipped
1764 	 * This assumes that the flush callback does not need to be called
1765 	 * unless there are other outstanding bufs.
1766 	 */
1767 	if (!waitfor) {
1768 		size_t nbufs;
1769 		mutex_enter(&wl->wl_mtx);	/* XXX need mutex here to
1770 						   protect the KASSERTS */
1771 		nbufs = wl->wl_bufcount;
1772 		KASSERT((wl->wl_bufcount == 0) == (wl->wl_bufbytes == 0));
1773 		KASSERT((wl->wl_bufcount == 0) == (wl->wl_bcount == 0));
1774 		mutex_exit(&wl->wl_mtx);
1775 		if (nbufs == 0)
1776 			return 0;
1777 	}
1778 
1779 	/*
1780 	 * XXX we may consider using LK_UPGRADE here
1781 	 * if we want to call flush from inside a transaction
1782 	 */
1783 	rw_enter(&wl->wl_rwlock, RW_WRITER);
1784 	wl->wl_flush(wl->wl_mount, TAILQ_FIRST(&wl->wl_dealloclist));
1785 
1786 	/*
1787 	 * Now that we are exclusively locked and the file system has
1788 	 * issued any deferred block writes for this transaction, check
1789 	 * whether there are any blocks to write to the log.  If not,
1790 	 * skip waiting for space or writing any log entries.
1791 	 *
1792 	 * XXX Shouldn't this also check wl_dealloccnt and
1793 	 * wl_inohashcnt?  Perhaps wl_dealloccnt doesn't matter if the
1794 	 * file system didn't produce any blocks as a consequence of
1795 	 * it, but the same does not seem to be so of wl_inohashcnt.
1796 	 */
1797 	if (wl->wl_bufcount == 0) {
1798 		goto wait_out;
1799 	}
1800 
1801 #if 0
1802 	WAPBL_PRINTF(WAPBL_PRINT_FLUSH,
1803 		     ("wapbl_flush thread %d.%d flushing entries with "
1804 		      "bufcount=%zu bufbytes=%zu\n",
1805 		      curproc->p_pid, curlwp->l_lid, wl->wl_bufcount,
1806 		      wl->wl_bufbytes));
1807 #endif
1808 
1809 	/* Calculate amount of space needed to flush */
1810 	flushsize = wapbl_transaction_len(wl);
1811 	if (wapbl_verbose_commit) {
1812 		struct timespec ts;
1813 		getnanotime(&ts);
1814 		printf("%s: %lld.%09ld this transaction = %zu bytes\n",
1815 		    __func__, (long long)ts.tv_sec,
1816 		    (long)ts.tv_nsec, flushsize);
1817 	}
1818 
1819 	if (flushsize > (wl->wl_circ_size - wl->wl_reserved_bytes)) {
1820 		/*
1821 		 * XXX this could be handled more gracefully, perhaps place
1822 		 * only a partial transaction in the log and allow the
1823 		 * remaining to flush without the protection of the journal.
1824 		 */
1825 		panic("wapbl_flush: current transaction too big to flush");
1826 	}
1827 
1828 	error = wapbl_truncate(wl, flushsize);
1829 	if (error)
1830 		goto out;
1831 
1832 	off = wl->wl_head;
1833 	KASSERT((off == 0) || (off >= wl->wl_circ_off));
1834 	KASSERT((off == 0) || (off < wl->wl_circ_off + wl->wl_circ_size));
1835 	error = wapbl_write_blocks(wl, &off);
1836 	if (error)
1837 		goto out;
1838 	error = wapbl_write_revocations(wl, &off);
1839 	if (error)
1840 		goto out;
1841 	error = wapbl_write_inodes(wl, &off);
1842 	if (error)
1843 		goto out;
1844 
1845 	reserved = 0;
1846 	if (wl->wl_inohashcnt)
1847 		reserved = wapbl_transaction_inodes_len(wl);
1848 
1849 	head = wl->wl_head;
1850 	tail = wl->wl_tail;
1851 
1852 	wapbl_advance_head(wl->wl_circ_size, wl->wl_circ_off, flushsize,
1853 	    &head, &tail);
1854 
1855 	KASSERTMSG(head == off,
1856 	    "lost head! head=%"PRIdMAX" tail=%" PRIdMAX
1857 	    " off=%"PRIdMAX" flush=%zu",
1858 	    (intmax_t)head, (intmax_t)tail, (intmax_t)off,
1859 	    flushsize);
1860 
1861 	/* Opportunistically move the tail forward if we can */
1862 	mutex_enter(&wl->wl_mtx);
1863 	delta = wl->wl_reclaimable_bytes;
1864 	mutex_exit(&wl->wl_mtx);
1865 	wapbl_advance_tail(wl->wl_circ_size, wl->wl_circ_off, delta,
1866 	    &head, &tail);
1867 
1868 	error = wapbl_write_commit(wl, head, tail);
1869 	if (error)
1870 		goto out;
1871 
1872 	we = pool_get(&wapbl_entry_pool, PR_WAITOK);
1873 
1874 #ifdef WAPBL_DEBUG_BUFBYTES
1875 	WAPBL_PRINTF(WAPBL_PRINT_FLUSH,
1876 		("wapbl_flush: thread %d.%d head+=%zu tail+=%zu used=%zu"
1877 		 " unsynced=%zu"
1878 		 "\n\tbufcount=%zu bufbytes=%zu bcount=%zu deallocs=%d "
1879 		 "inodes=%d\n",
1880 		 curproc->p_pid, curlwp->l_lid, flushsize, delta,
1881 		 wapbl_space_used(wl->wl_circ_size, head, tail),
1882 		 wl->wl_unsynced_bufbytes, wl->wl_bufcount,
1883 		 wl->wl_bufbytes, wl->wl_bcount, wl->wl_dealloccnt,
1884 		 wl->wl_inohashcnt));
1885 #else
1886 	WAPBL_PRINTF(WAPBL_PRINT_FLUSH,
1887 		("wapbl_flush: thread %d.%d head+=%zu tail+=%zu used=%zu"
1888 		 "\n\tbufcount=%zu bufbytes=%zu bcount=%zu deallocs=%d "
1889 		 "inodes=%d\n",
1890 		 curproc->p_pid, curlwp->l_lid, flushsize, delta,
1891 		 wapbl_space_used(wl->wl_circ_size, head, tail),
1892 		 wl->wl_bufcount, wl->wl_bufbytes, wl->wl_bcount,
1893 		 wl->wl_dealloccnt, wl->wl_inohashcnt));
1894 #endif
1895 
1896 
1897 	mutex_enter(&bufcache_lock);
1898 	mutex_enter(&wl->wl_mtx);
1899 
1900 	wl->wl_reserved_bytes = reserved;
1901 	wl->wl_head = head;
1902 	wl->wl_tail = tail;
1903 	KASSERT(wl->wl_reclaimable_bytes >= delta);
1904 	wl->wl_reclaimable_bytes -= delta;
1905 	KDASSERT(wl->wl_dealloccnt == 0);
1906 #ifdef WAPBL_DEBUG_BUFBYTES
1907 	wl->wl_unsynced_bufbytes += wl->wl_bufbytes;
1908 #endif
1909 
1910 	we->we_wapbl = wl;
1911 	we->we_bufcount = wl->wl_bufcount;
1912 #ifdef WAPBL_DEBUG_BUFBYTES
1913 	we->we_unsynced_bufbytes = wl->wl_bufbytes;
1914 #endif
1915 	we->we_reclaimable_bytes = flushsize;
1916 	we->we_error = 0;
1917 	SIMPLEQ_INSERT_TAIL(&wl->wl_entries, we, we_entries);
1918 
1919 	/*
1920 	 * This flushes bufs in order than they were queued, so the LRU
1921 	 * order is preserved.
1922 	 */
1923 	while ((bp = TAILQ_FIRST(&wl->wl_bufs)) != NULL) {
1924 		if (bbusy(bp, 0, 0, &wl->wl_mtx)) {
1925 			continue;
1926 		}
1927 		bp->b_iodone = wapbl_biodone;
1928 		bp->b_private = we;
1929 
1930 		bremfree(bp);
1931 		wapbl_remove_buf_locked(wl, bp);
1932 		mutex_exit(&wl->wl_mtx);
1933 		mutex_exit(&bufcache_lock);
1934 		bawrite(bp);
1935 		mutex_enter(&bufcache_lock);
1936 		mutex_enter(&wl->wl_mtx);
1937 	}
1938 	mutex_exit(&wl->wl_mtx);
1939 	mutex_exit(&bufcache_lock);
1940 
1941 #if 0
1942 	WAPBL_PRINTF(WAPBL_PRINT_FLUSH,
1943 		     ("wapbl_flush thread %d.%d done flushing entries...\n",
1944 		     curproc->p_pid, curlwp->l_lid));
1945 #endif
1946 
1947  wait_out:
1948 
1949 	/*
1950 	 * If the waitfor flag is set, don't return until everything is
1951 	 * fully flushed and the on disk log is empty.
1952 	 */
1953 	if (waitfor) {
1954 		error = wapbl_truncate(wl, wl->wl_circ_size -
1955 			wl->wl_reserved_bytes);
1956 	}
1957 
1958  out:
1959 	if (error) {
1960 		wl->wl_flush_abort(wl->wl_mount,
1961 		    TAILQ_FIRST(&wl->wl_dealloclist));
1962 	}
1963 
1964 #ifdef WAPBL_DEBUG_PRINT
1965 	if (error) {
1966 		pid_t pid = -1;
1967 		lwpid_t lid = -1;
1968 		if (curproc)
1969 			pid = curproc->p_pid;
1970 		if (curlwp)
1971 			lid = curlwp->l_lid;
1972 		mutex_enter(&wl->wl_mtx);
1973 #ifdef WAPBL_DEBUG_BUFBYTES
1974 		WAPBL_PRINTF(WAPBL_PRINT_ERROR,
1975 		    ("wapbl_flush: thread %d.%d aborted flush: "
1976 		    "error = %d\n"
1977 		    "\tbufcount=%zu bufbytes=%zu bcount=%zu "
1978 		    "deallocs=%d inodes=%d\n"
1979 		    "\terrcnt = %d, reclaimable=%zu reserved=%zu "
1980 		    "unsynced=%zu\n",
1981 		    pid, lid, error, wl->wl_bufcount,
1982 		    wl->wl_bufbytes, wl->wl_bcount,
1983 		    wl->wl_dealloccnt, wl->wl_inohashcnt,
1984 		    wl->wl_error_count, wl->wl_reclaimable_bytes,
1985 		    wl->wl_reserved_bytes, wl->wl_unsynced_bufbytes));
1986 		SIMPLEQ_FOREACH(we, &wl->wl_entries, we_entries) {
1987 			WAPBL_PRINTF(WAPBL_PRINT_ERROR,
1988 			    ("\tentry: bufcount = %zu, reclaimable = %zu, "
1989 			     "error = %d, unsynced = %zu\n",
1990 			     we->we_bufcount, we->we_reclaimable_bytes,
1991 			     we->we_error, we->we_unsynced_bufbytes));
1992 		}
1993 #else
1994 		WAPBL_PRINTF(WAPBL_PRINT_ERROR,
1995 		    ("wapbl_flush: thread %d.%d aborted flush: "
1996 		     "error = %d\n"
1997 		     "\tbufcount=%zu bufbytes=%zu bcount=%zu "
1998 		     "deallocs=%d inodes=%d\n"
1999 		     "\terrcnt = %d, reclaimable=%zu reserved=%zu\n",
2000 		     pid, lid, error, wl->wl_bufcount,
2001 		     wl->wl_bufbytes, wl->wl_bcount,
2002 		     wl->wl_dealloccnt, wl->wl_inohashcnt,
2003 		     wl->wl_error_count, wl->wl_reclaimable_bytes,
2004 		     wl->wl_reserved_bytes));
2005 		SIMPLEQ_FOREACH(we, &wl->wl_entries, we_entries) {
2006 			WAPBL_PRINTF(WAPBL_PRINT_ERROR,
2007 			    ("\tentry: bufcount = %zu, reclaimable = %zu, "
2008 			     "error = %d\n", we->we_bufcount,
2009 			     we->we_reclaimable_bytes, we->we_error));
2010 		}
2011 #endif
2012 		mutex_exit(&wl->wl_mtx);
2013 	}
2014 #endif
2015 
2016 	rw_exit(&wl->wl_rwlock);
2017 	return error;
2018 }
2019 
2020 /****************************************************************/
2021 
2022 void
2023 wapbl_jlock_assert(struct wapbl *wl)
2024 {
2025 
2026 	KASSERT(rw_lock_held(&wl->wl_rwlock));
2027 }
2028 
2029 void
2030 wapbl_junlock_assert(struct wapbl *wl)
2031 {
2032 
2033 	KASSERT(!rw_write_held(&wl->wl_rwlock));
2034 }
2035 
2036 /****************************************************************/
2037 
2038 /* locks missing */
2039 void
2040 wapbl_print(struct wapbl *wl,
2041 		int full,
2042 		void (*pr)(const char *, ...))
2043 {
2044 	struct buf *bp;
2045 	struct wapbl_entry *we;
2046 	(*pr)("wapbl %p", wl);
2047 	(*pr)("\nlogvp = %p, devvp = %p, logpbn = %"PRId64"\n",
2048 	      wl->wl_logvp, wl->wl_devvp, wl->wl_logpbn);
2049 	(*pr)("circ = %zu, header = %zu, head = %"PRIdMAX" tail = %"PRIdMAX"\n",
2050 	      wl->wl_circ_size, wl->wl_circ_off,
2051 	      (intmax_t)wl->wl_head, (intmax_t)wl->wl_tail);
2052 	(*pr)("fs_dev_bshift = %d, log_dev_bshift = %d\n",
2053 	      wl->wl_log_dev_bshift, wl->wl_fs_dev_bshift);
2054 #ifdef WAPBL_DEBUG_BUFBYTES
2055 	(*pr)("bufcount = %zu, bufbytes = %zu bcount = %zu reclaimable = %zu "
2056 	      "reserved = %zu errcnt = %d unsynced = %zu\n",
2057 	      wl->wl_bufcount, wl->wl_bufbytes, wl->wl_bcount,
2058 	      wl->wl_reclaimable_bytes, wl->wl_reserved_bytes,
2059 				wl->wl_error_count, wl->wl_unsynced_bufbytes);
2060 #else
2061 	(*pr)("bufcount = %zu, bufbytes = %zu bcount = %zu reclaimable = %zu "
2062 	      "reserved = %zu errcnt = %d\n", wl->wl_bufcount, wl->wl_bufbytes,
2063 	      wl->wl_bcount, wl->wl_reclaimable_bytes, wl->wl_reserved_bytes,
2064 				wl->wl_error_count);
2065 #endif
2066 	(*pr)("\tdealloccnt = %d, dealloclim = %d\n",
2067 	      wl->wl_dealloccnt, wl->wl_dealloclim);
2068 	(*pr)("\tinohashcnt = %d, inohashmask = 0x%08x\n",
2069 	      wl->wl_inohashcnt, wl->wl_inohashmask);
2070 	(*pr)("entries:\n");
2071 	SIMPLEQ_FOREACH(we, &wl->wl_entries, we_entries) {
2072 #ifdef WAPBL_DEBUG_BUFBYTES
2073 		(*pr)("\tbufcount = %zu, reclaimable = %zu, error = %d, "
2074 		      "unsynced = %zu\n",
2075 		      we->we_bufcount, we->we_reclaimable_bytes,
2076 		      we->we_error, we->we_unsynced_bufbytes);
2077 #else
2078 		(*pr)("\tbufcount = %zu, reclaimable = %zu, error = %d\n",
2079 		      we->we_bufcount, we->we_reclaimable_bytes, we->we_error);
2080 #endif
2081 	}
2082 	if (full) {
2083 		int cnt = 0;
2084 		(*pr)("bufs =");
2085 		TAILQ_FOREACH(bp, &wl->wl_bufs, b_wapbllist) {
2086 			if (!TAILQ_NEXT(bp, b_wapbllist)) {
2087 				(*pr)(" %p", bp);
2088 			} else if ((++cnt % 6) == 0) {
2089 				(*pr)(" %p,\n\t", bp);
2090 			} else {
2091 				(*pr)(" %p,", bp);
2092 			}
2093 		}
2094 		(*pr)("\n");
2095 
2096 		(*pr)("dealloced blks = ");
2097 		{
2098 			struct wapbl_dealloc *wd;
2099 			cnt = 0;
2100 			TAILQ_FOREACH(wd, &wl->wl_dealloclist, wd_entries) {
2101 				(*pr)(" %"PRId64":%d,",
2102 				      wd->wd_blkno,
2103 				      wd->wd_len);
2104 				if ((++cnt % 4) == 0) {
2105 					(*pr)("\n\t");
2106 				}
2107 			}
2108 		}
2109 		(*pr)("\n");
2110 
2111 		(*pr)("registered inodes = ");
2112 		{
2113 			int i;
2114 			cnt = 0;
2115 			for (i = 0; i <= wl->wl_inohashmask; i++) {
2116 				struct wapbl_ino_head *wih;
2117 				struct wapbl_ino *wi;
2118 
2119 				wih = &wl->wl_inohash[i];
2120 				LIST_FOREACH(wi, wih, wi_hash) {
2121 					if (wi->wi_ino == 0)
2122 						continue;
2123 					(*pr)(" %"PRIu64"/0%06"PRIo32",",
2124 					    wi->wi_ino, wi->wi_mode);
2125 					if ((++cnt % 4) == 0) {
2126 						(*pr)("\n\t");
2127 					}
2128 				}
2129 			}
2130 			(*pr)("\n");
2131 		}
2132 
2133 		(*pr)("iobufs free =");
2134 		TAILQ_FOREACH(bp, &wl->wl_iobufs, b_wapbllist) {
2135 			if (!TAILQ_NEXT(bp, b_wapbllist)) {
2136 				(*pr)(" %p", bp);
2137 			} else if ((++cnt % 6) == 0) {
2138 				(*pr)(" %p,\n\t", bp);
2139 			} else {
2140 				(*pr)(" %p,", bp);
2141 			}
2142 		}
2143 		(*pr)("\n");
2144 
2145 		(*pr)("iobufs busy =");
2146 		TAILQ_FOREACH(bp, &wl->wl_iobufs_busy, b_wapbllist) {
2147 			if (!TAILQ_NEXT(bp, b_wapbllist)) {
2148 				(*pr)(" %p", bp);
2149 			} else if ((++cnt % 6) == 0) {
2150 				(*pr)(" %p,\n\t", bp);
2151 			} else {
2152 				(*pr)(" %p,", bp);
2153 			}
2154 		}
2155 		(*pr)("\n");
2156 	}
2157 }
2158 
2159 #if defined(WAPBL_DEBUG) || defined(DDB)
2160 void
2161 wapbl_dump(struct wapbl *wl)
2162 {
2163 #if defined(WAPBL_DEBUG)
2164 	if (!wl)
2165 		wl = wapbl_debug_wl;
2166 #endif
2167 	if (!wl)
2168 		return;
2169 	wapbl_print(wl, 1, printf);
2170 }
2171 #endif
2172 
2173 /****************************************************************/
2174 
2175 int
2176 wapbl_register_deallocation(struct wapbl *wl, daddr_t blk, int len, bool force,
2177     void **cookiep)
2178 {
2179 	struct wapbl_dealloc *wd;
2180 	int error = 0;
2181 
2182 	wapbl_jlock_assert(wl);
2183 
2184 	mutex_enter(&wl->wl_mtx);
2185 
2186 	if (__predict_false(wl->wl_dealloccnt >= wl->wl_dealloclim)) {
2187 		if (!force) {
2188 			error = EAGAIN;
2189 			goto out;
2190 		}
2191 
2192 		/*
2193 		 * Forced registration can only be used when:
2194 		 * 1) the caller can't cope with failure
2195 		 * 2) the path can be triggered only bounded, small
2196 		 *    times per transaction
2197 		 * If this is not fullfilled, and the path would be triggered
2198 		 * many times, this could overflow maximum transaction size
2199 		 * and panic later.
2200 		 */
2201 		printf("%s: forced dealloc registration over limit: %d >= %d\n",
2202 			wl->wl_mount->mnt_stat.f_mntonname,
2203 			wl->wl_dealloccnt, wl->wl_dealloclim);
2204 	}
2205 
2206 	wl->wl_dealloccnt++;
2207 	mutex_exit(&wl->wl_mtx);
2208 
2209 	wd = pool_get(&wapbl_dealloc_pool, PR_WAITOK);
2210 	wd->wd_blkno = blk;
2211 	wd->wd_len = len;
2212 
2213 	mutex_enter(&wl->wl_mtx);
2214 	TAILQ_INSERT_TAIL(&wl->wl_dealloclist, wd, wd_entries);
2215 
2216 	if (cookiep)
2217 		*cookiep = wd;
2218 
2219  out:
2220 	mutex_exit(&wl->wl_mtx);
2221 
2222 	WAPBL_PRINTF(WAPBL_PRINT_ALLOC,
2223 	    ("wapbl_register_deallocation: blk=%"PRId64" len=%d error=%d\n",
2224 	    blk, len, error));
2225 
2226 	return error;
2227 }
2228 
2229 static void
2230 wapbl_deallocation_free(struct wapbl *wl, struct wapbl_dealloc *wd,
2231 	bool locked)
2232 {
2233 	KASSERT(!locked
2234 	    || rw_lock_held(&wl->wl_rwlock) || mutex_owned(&wl->wl_mtx));
2235 
2236 	if (!locked)
2237 		mutex_enter(&wl->wl_mtx);
2238 
2239 	TAILQ_REMOVE(&wl->wl_dealloclist, wd, wd_entries);
2240 	wl->wl_dealloccnt--;
2241 
2242 	if (!locked)
2243 		mutex_exit(&wl->wl_mtx);
2244 
2245 	pool_put(&wapbl_dealloc_pool, wd);
2246 }
2247 
2248 void
2249 wapbl_unregister_deallocation(struct wapbl *wl, void *cookie)
2250 {
2251 	KASSERT(cookie != NULL);
2252 	wapbl_deallocation_free(wl, cookie, false);
2253 }
2254 
2255 /****************************************************************/
2256 
2257 static void
2258 wapbl_inodetrk_init(struct wapbl *wl, u_int size)
2259 {
2260 
2261 	wl->wl_inohash = hashinit(size, HASH_LIST, true, &wl->wl_inohashmask);
2262 	if (atomic_inc_uint_nv(&wapbl_ino_pool_refcount) == 1) {
2263 		pool_init(&wapbl_ino_pool, sizeof(struct wapbl_ino), 0, 0, 0,
2264 		    "wapblinopl", &pool_allocator_nointr, IPL_NONE);
2265 	}
2266 }
2267 
2268 static void
2269 wapbl_inodetrk_free(struct wapbl *wl)
2270 {
2271 
2272 	/* XXX this KASSERT needs locking/mutex analysis */
2273 	KASSERT(wl->wl_inohashcnt == 0);
2274 	hashdone(wl->wl_inohash, HASH_LIST, wl->wl_inohashmask);
2275 	if (atomic_dec_uint_nv(&wapbl_ino_pool_refcount) == 0) {
2276 		pool_destroy(&wapbl_ino_pool);
2277 	}
2278 }
2279 
2280 static struct wapbl_ino *
2281 wapbl_inodetrk_get(struct wapbl *wl, ino_t ino)
2282 {
2283 	struct wapbl_ino_head *wih;
2284 	struct wapbl_ino *wi;
2285 
2286 	KASSERT(mutex_owned(&wl->wl_mtx));
2287 
2288 	wih = &wl->wl_inohash[ino & wl->wl_inohashmask];
2289 	LIST_FOREACH(wi, wih, wi_hash) {
2290 		if (ino == wi->wi_ino)
2291 			return wi;
2292 	}
2293 	return 0;
2294 }
2295 
2296 void
2297 wapbl_register_inode(struct wapbl *wl, ino_t ino, mode_t mode)
2298 {
2299 	struct wapbl_ino_head *wih;
2300 	struct wapbl_ino *wi;
2301 
2302 	wi = pool_get(&wapbl_ino_pool, PR_WAITOK);
2303 
2304 	mutex_enter(&wl->wl_mtx);
2305 	if (wapbl_inodetrk_get(wl, ino) == NULL) {
2306 		wi->wi_ino = ino;
2307 		wi->wi_mode = mode;
2308 		wih = &wl->wl_inohash[ino & wl->wl_inohashmask];
2309 		LIST_INSERT_HEAD(wih, wi, wi_hash);
2310 		wl->wl_inohashcnt++;
2311 		WAPBL_PRINTF(WAPBL_PRINT_INODE,
2312 		    ("wapbl_register_inode: ino=%"PRId64"\n", ino));
2313 		mutex_exit(&wl->wl_mtx);
2314 	} else {
2315 		mutex_exit(&wl->wl_mtx);
2316 		pool_put(&wapbl_ino_pool, wi);
2317 	}
2318 }
2319 
2320 void
2321 wapbl_unregister_inode(struct wapbl *wl, ino_t ino, mode_t mode)
2322 {
2323 	struct wapbl_ino *wi;
2324 
2325 	mutex_enter(&wl->wl_mtx);
2326 	wi = wapbl_inodetrk_get(wl, ino);
2327 	if (wi) {
2328 		WAPBL_PRINTF(WAPBL_PRINT_INODE,
2329 		    ("wapbl_unregister_inode: ino=%"PRId64"\n", ino));
2330 		KASSERT(wl->wl_inohashcnt > 0);
2331 		wl->wl_inohashcnt--;
2332 		LIST_REMOVE(wi, wi_hash);
2333 		mutex_exit(&wl->wl_mtx);
2334 
2335 		pool_put(&wapbl_ino_pool, wi);
2336 	} else {
2337 		mutex_exit(&wl->wl_mtx);
2338 	}
2339 }
2340 
2341 /****************************************************************/
2342 
2343 /*
2344  * wapbl_transaction_inodes_len(wl)
2345  *
2346  *	Calculate the number of bytes required for inode registration
2347  *	log records in wl.
2348  */
2349 static inline size_t
2350 wapbl_transaction_inodes_len(struct wapbl *wl)
2351 {
2352 	int blocklen = 1<<wl->wl_log_dev_bshift;
2353 	int iph;
2354 
2355 	/* Calculate number of inodes described in a inodelist header */
2356 	iph = (blocklen - offsetof(struct wapbl_wc_inodelist, wc_inodes)) /
2357 	    sizeof(((struct wapbl_wc_inodelist *)0)->wc_inodes[0]);
2358 
2359 	KASSERT(iph > 0);
2360 
2361 	return MAX(1, howmany(wl->wl_inohashcnt, iph)) * blocklen;
2362 }
2363 
2364 
2365 /*
2366  * wapbl_transaction_len(wl)
2367  *
2368  *	Calculate number of bytes required for all log records in wl.
2369  */
2370 static size_t
2371 wapbl_transaction_len(struct wapbl *wl)
2372 {
2373 	int blocklen = 1<<wl->wl_log_dev_bshift;
2374 	size_t len;
2375 
2376 	/* Calculate number of blocks described in a blocklist header */
2377 	len = wl->wl_bcount;
2378 	len += howmany(wl->wl_bufcount, wl->wl_brperjblock) * blocklen;
2379 	len += howmany(wl->wl_dealloccnt, wl->wl_brperjblock) * blocklen;
2380 	len += wapbl_transaction_inodes_len(wl);
2381 
2382 	return len;
2383 }
2384 
2385 /*
2386  * wapbl_cache_sync(wl, msg)
2387  *
2388  *	Issue DIOCCACHESYNC to wl->wl_devvp.
2389  *
2390  *	If sysctl(vfs.wapbl.verbose_commit) >= 2, print a message
2391  *	including msg about the duration of the cache sync.
2392  */
2393 static int
2394 wapbl_cache_sync(struct wapbl *wl, const char *msg)
2395 {
2396 	const bool verbose = wapbl_verbose_commit >= 2;
2397 	struct bintime start_time;
2398 	int force = 1;
2399 	int error;
2400 
2401 	/* Skip full cache sync if disabled */
2402 	if (!wapbl_flush_disk_cache) {
2403 		return 0;
2404 	}
2405 	if (verbose) {
2406 		bintime(&start_time);
2407 	}
2408 	error = VOP_IOCTL(wl->wl_devvp, DIOCCACHESYNC, &force,
2409 	    FWRITE, FSCRED);
2410 	if (error) {
2411 		WAPBL_PRINTF(WAPBL_PRINT_ERROR,
2412 		    ("wapbl_cache_sync: DIOCCACHESYNC on dev 0x%jx "
2413 		    "returned %d\n", (uintmax_t)wl->wl_devvp->v_rdev, error));
2414 	}
2415 	if (verbose) {
2416 		struct bintime d;
2417 		struct timespec ts;
2418 
2419 		bintime(&d);
2420 		bintime_sub(&d, &start_time);
2421 		bintime2timespec(&d, &ts);
2422 		printf("wapbl_cache_sync: %s: dev 0x%jx %ju.%09lu\n",
2423 		    msg, (uintmax_t)wl->wl_devvp->v_rdev,
2424 		    (uintmax_t)ts.tv_sec, ts.tv_nsec);
2425 	}
2426 
2427 	wl->wl_ev_cacheflush.ev_count++;
2428 
2429 	return error;
2430 }
2431 
2432 /*
2433  * wapbl_write_commit(wl, head, tail)
2434  *
2435  *	Issue a disk cache sync to wait for all pending writes to the
2436  *	log to complete, and then synchronously commit the current
2437  *	circular queue head and tail to the log, in the next of two
2438  *	locations for commit headers on disk.
2439  *
2440  *	Increment the generation number.  If the generation number
2441  *	rolls over to zero, then a subsequent commit would appear to
2442  *	have an older generation than this one -- in that case, issue a
2443  *	duplicate commit to avoid this.
2444  *
2445  *	=> Caller must have exclusive access to wl, either by holding
2446  *	wl->wl_rwlock for writer or by being wapbl_start before anyone
2447  *	else has seen wl.
2448  */
2449 static int
2450 wapbl_write_commit(struct wapbl *wl, off_t head, off_t tail)
2451 {
2452 	struct wapbl_wc_header *wc = wl->wl_wc_header;
2453 	struct timespec ts;
2454 	int error;
2455 	daddr_t pbn;
2456 
2457 	error = wapbl_buffered_flush(wl, true);
2458 	if (error)
2459 		return error;
2460 	/*
2461 	 * Flush disk cache to ensure that blocks we've written are actually
2462 	 * written to the stable storage before the commit header.
2463 	 * This flushes to disk not only journal blocks, but also all
2464 	 * metadata blocks, written asynchronously since previous commit.
2465 	 *
2466 	 * XXX Calc checksum here, instead we do this for now
2467 	 */
2468 	wapbl_cache_sync(wl, "1");
2469 
2470 	wc->wc_head = head;
2471 	wc->wc_tail = tail;
2472 	wc->wc_checksum = 0;
2473 	wc->wc_version = 1;
2474 	getnanotime(&ts);
2475 	wc->wc_time = ts.tv_sec;
2476 	wc->wc_timensec = ts.tv_nsec;
2477 
2478 	WAPBL_PRINTF(WAPBL_PRINT_WRITE,
2479 	    ("wapbl_write_commit: head = %"PRIdMAX "tail = %"PRIdMAX"\n",
2480 	    (intmax_t)head, (intmax_t)tail));
2481 
2482 	/*
2483 	 * write the commit header.
2484 	 *
2485 	 * XXX if generation will rollover, then first zero
2486 	 * over second commit header before trying to write both headers.
2487 	 */
2488 
2489 	pbn = wl->wl_logpbn + (wc->wc_generation % 2);
2490 #ifdef _KERNEL
2491 	pbn = btodb(pbn << wc->wc_log_dev_bshift);
2492 #endif
2493 	error = wapbl_buffered_write(wc, wc->wc_len, wl, pbn, WAPBL_JFLAGS(wl));
2494 	if (error)
2495 		return error;
2496 	error = wapbl_buffered_flush(wl, true);
2497 	if (error)
2498 		return error;
2499 
2500 	/*
2501 	 * Flush disk cache to ensure that the commit header is actually
2502 	 * written before meta data blocks. Commit block is written using
2503 	 * FUA when enabled, in that case this flush is not needed.
2504 	 */
2505 	if (!WAPBL_USE_FUA(wl))
2506 		wapbl_cache_sync(wl, "2");
2507 
2508 	/*
2509 	 * If the generation number was zero, write it out a second time.
2510 	 * This handles initialization and generation number rollover
2511 	 */
2512 	if (wc->wc_generation++ == 0) {
2513 		error = wapbl_write_commit(wl, head, tail);
2514 		/*
2515 		 * This panic should be able to be removed if we do the
2516 		 * zero'ing mentioned above, and we are certain to roll
2517 		 * back generation number on failure.
2518 		 */
2519 		if (error)
2520 			panic("wapbl_write_commit: error writing duplicate "
2521 			      "log header: %d", error);
2522 	}
2523 
2524 	wl->wl_ev_commit.ev_count++;
2525 
2526 	return 0;
2527 }
2528 
2529 /*
2530  * wapbl_write_blocks(wl, offp)
2531  *
2532  *	Write all pending physical blocks in the current transaction
2533  *	from wapbl_add_buf to the log on disk, adding to the circular
2534  *	queue head at byte offset *offp, and returning the new head's
2535  *	byte offset in *offp.
2536  */
2537 static int
2538 wapbl_write_blocks(struct wapbl *wl, off_t *offp)
2539 {
2540 	struct wapbl_wc_blocklist *wc =
2541 	    (struct wapbl_wc_blocklist *)wl->wl_wc_scratch;
2542 	int blocklen = 1<<wl->wl_log_dev_bshift;
2543 	struct buf *bp;
2544 	off_t off = *offp;
2545 	int error;
2546 	size_t padding;
2547 
2548 	KASSERT(rw_write_held(&wl->wl_rwlock));
2549 
2550 	bp = TAILQ_FIRST(&wl->wl_bufs);
2551 
2552 	while (bp) {
2553 		int cnt;
2554 		struct buf *obp = bp;
2555 
2556 		KASSERT(bp->b_flags & B_LOCKED);
2557 
2558 		wc->wc_type = WAPBL_WC_BLOCKS;
2559 		wc->wc_len = blocklen;
2560 		wc->wc_blkcount = 0;
2561 		while (bp && (wc->wc_blkcount < wl->wl_brperjblock)) {
2562 			/*
2563 			 * Make sure all the physical block numbers are up to
2564 			 * date.  If this is not always true on a given
2565 			 * filesystem, then VOP_BMAP must be called.  We
2566 			 * could call VOP_BMAP here, or else in the filesystem
2567 			 * specific flush callback, although neither of those
2568 			 * solutions allow us to take the vnode lock.  If a
2569 			 * filesystem requires that we must take the vnode lock
2570 			 * to call VOP_BMAP, then we can probably do it in
2571 			 * bwrite when the vnode lock should already be held
2572 			 * by the invoking code.
2573 			 */
2574 			KASSERT((bp->b_vp->v_type == VBLK) ||
2575 				 (bp->b_blkno != bp->b_lblkno));
2576 			KASSERT(bp->b_blkno > 0);
2577 
2578 			wc->wc_blocks[wc->wc_blkcount].wc_daddr = bp->b_blkno;
2579 			wc->wc_blocks[wc->wc_blkcount].wc_dlen = bp->b_bcount;
2580 			wc->wc_len += bp->b_bcount;
2581 			wc->wc_blkcount++;
2582 			bp = TAILQ_NEXT(bp, b_wapbllist);
2583 		}
2584 		if (wc->wc_len % blocklen != 0) {
2585 			padding = blocklen - wc->wc_len % blocklen;
2586 			wc->wc_len += padding;
2587 		} else {
2588 			padding = 0;
2589 		}
2590 
2591 		WAPBL_PRINTF(WAPBL_PRINT_WRITE,
2592 		    ("wapbl_write_blocks: len = %u (padding %zu) off = %"PRIdMAX"\n",
2593 		    wc->wc_len, padding, (intmax_t)off));
2594 
2595 		error = wapbl_circ_write(wl, wc, blocklen, &off);
2596 		if (error)
2597 			return error;
2598 		bp = obp;
2599 		cnt = 0;
2600 		while (bp && (cnt++ < wl->wl_brperjblock)) {
2601 			error = wapbl_circ_write(wl, bp->b_data,
2602 			    bp->b_bcount, &off);
2603 			if (error)
2604 				return error;
2605 			bp = TAILQ_NEXT(bp, b_wapbllist);
2606 		}
2607 		if (padding) {
2608 			void *zero;
2609 
2610 			zero = wapbl_alloc(padding);
2611 			memset(zero, 0, padding);
2612 			error = wapbl_circ_write(wl, zero, padding, &off);
2613 			wapbl_free(zero, padding);
2614 			if (error)
2615 				return error;
2616 		}
2617 	}
2618 	*offp = off;
2619 	return 0;
2620 }
2621 
2622 /*
2623  * wapbl_write_revocations(wl, offp)
2624  *
2625  *	Write all pending deallocations in the current transaction from
2626  *	wapbl_register_deallocation to the log on disk, adding to the
2627  *	circular queue's head at byte offset *offp, and returning the
2628  *	new head's byte offset in *offp.
2629  */
2630 static int
2631 wapbl_write_revocations(struct wapbl *wl, off_t *offp)
2632 {
2633 	struct wapbl_wc_blocklist *wc =
2634 	    (struct wapbl_wc_blocklist *)wl->wl_wc_scratch;
2635 	struct wapbl_dealloc *wd, *lwd;
2636 	int blocklen = 1<<wl->wl_log_dev_bshift;
2637 	off_t off = *offp;
2638 	int error;
2639 
2640 	KASSERT(rw_write_held(&wl->wl_rwlock));
2641 
2642 	if (wl->wl_dealloccnt == 0)
2643 		return 0;
2644 
2645 	while ((wd = TAILQ_FIRST(&wl->wl_dealloclist)) != NULL) {
2646 		wc->wc_type = WAPBL_WC_REVOCATIONS;
2647 		wc->wc_len = blocklen;
2648 		wc->wc_blkcount = 0;
2649 		while (wd && (wc->wc_blkcount < wl->wl_brperjblock)) {
2650 			wc->wc_blocks[wc->wc_blkcount].wc_daddr =
2651 			    wd->wd_blkno;
2652 			wc->wc_blocks[wc->wc_blkcount].wc_dlen =
2653 			    wd->wd_len;
2654 			wc->wc_blkcount++;
2655 
2656 			wd = TAILQ_NEXT(wd, wd_entries);
2657 		}
2658 		WAPBL_PRINTF(WAPBL_PRINT_WRITE,
2659 		    ("wapbl_write_revocations: len = %u off = %"PRIdMAX"\n",
2660 		    wc->wc_len, (intmax_t)off));
2661 		error = wapbl_circ_write(wl, wc, blocklen, &off);
2662 		if (error)
2663 			return error;
2664 
2665 		/* free all successfully written deallocs */
2666 		lwd = wd;
2667 		while ((wd = TAILQ_FIRST(&wl->wl_dealloclist)) != NULL) {
2668 			if (wd == lwd)
2669 				break;
2670 			wapbl_deallocation_free(wl, wd, true);
2671 		}
2672 	}
2673 	*offp = off;
2674 	return 0;
2675 }
2676 
2677 /*
2678  * wapbl_write_inodes(wl, offp)
2679  *
2680  *	Write all pending inode allocations in the current transaction
2681  *	from wapbl_register_inode to the log on disk, adding to the
2682  *	circular queue's head at byte offset *offp and returning the
2683  *	new head's byte offset in *offp.
2684  */
2685 static int
2686 wapbl_write_inodes(struct wapbl *wl, off_t *offp)
2687 {
2688 	struct wapbl_wc_inodelist *wc =
2689 	    (struct wapbl_wc_inodelist *)wl->wl_wc_scratch;
2690 	int i;
2691 	int blocklen = 1 << wl->wl_log_dev_bshift;
2692 	off_t off = *offp;
2693 	int error;
2694 
2695 	struct wapbl_ino_head *wih;
2696 	struct wapbl_ino *wi;
2697 	int iph;
2698 
2699 	iph = (blocklen - offsetof(struct wapbl_wc_inodelist, wc_inodes)) /
2700 	    sizeof(((struct wapbl_wc_inodelist *)0)->wc_inodes[0]);
2701 
2702 	i = 0;
2703 	wih = &wl->wl_inohash[0];
2704 	wi = 0;
2705 	do {
2706 		wc->wc_type = WAPBL_WC_INODES;
2707 		wc->wc_len = blocklen;
2708 		wc->wc_inocnt = 0;
2709 		wc->wc_clear = (i == 0);
2710 		while ((i < wl->wl_inohashcnt) && (wc->wc_inocnt < iph)) {
2711 			while (!wi) {
2712 				KASSERT((wih - &wl->wl_inohash[0])
2713 				    <= wl->wl_inohashmask);
2714 				wi = LIST_FIRST(wih++);
2715 			}
2716 			wc->wc_inodes[wc->wc_inocnt].wc_inumber = wi->wi_ino;
2717 			wc->wc_inodes[wc->wc_inocnt].wc_imode = wi->wi_mode;
2718 			wc->wc_inocnt++;
2719 			i++;
2720 			wi = LIST_NEXT(wi, wi_hash);
2721 		}
2722 		WAPBL_PRINTF(WAPBL_PRINT_WRITE,
2723 		    ("wapbl_write_inodes: len = %u off = %"PRIdMAX"\n",
2724 		    wc->wc_len, (intmax_t)off));
2725 		error = wapbl_circ_write(wl, wc, blocklen, &off);
2726 		if (error)
2727 			return error;
2728 	} while (i < wl->wl_inohashcnt);
2729 
2730 	*offp = off;
2731 	return 0;
2732 }
2733 
2734 #endif /* _KERNEL */
2735 
2736 /****************************************************************/
2737 
2738 struct wapbl_blk {
2739 	LIST_ENTRY(wapbl_blk) wb_hash;
2740 	daddr_t wb_blk;
2741 	off_t wb_off; /* Offset of this block in the log */
2742 };
2743 #define	WAPBL_BLKPOOL_MIN 83
2744 
2745 static void
2746 wapbl_blkhash_init(struct wapbl_replay *wr, u_int size)
2747 {
2748 	if (size < WAPBL_BLKPOOL_MIN)
2749 		size = WAPBL_BLKPOOL_MIN;
2750 	KASSERT(wr->wr_blkhash == 0);
2751 #ifdef _KERNEL
2752 	wr->wr_blkhash = hashinit(size, HASH_LIST, true, &wr->wr_blkhashmask);
2753 #else /* ! _KERNEL */
2754 	/* Manually implement hashinit */
2755 	{
2756 		unsigned long i, hashsize;
2757 		for (hashsize = 1; hashsize < size; hashsize <<= 1)
2758 			continue;
2759 		wr->wr_blkhash = wapbl_alloc(hashsize * sizeof(*wr->wr_blkhash));
2760 		for (i = 0; i < hashsize; i++)
2761 			LIST_INIT(&wr->wr_blkhash[i]);
2762 		wr->wr_blkhashmask = hashsize - 1;
2763 	}
2764 #endif /* ! _KERNEL */
2765 }
2766 
2767 static void
2768 wapbl_blkhash_free(struct wapbl_replay *wr)
2769 {
2770 	KASSERT(wr->wr_blkhashcnt == 0);
2771 #ifdef _KERNEL
2772 	hashdone(wr->wr_blkhash, HASH_LIST, wr->wr_blkhashmask);
2773 #else /* ! _KERNEL */
2774 	wapbl_free(wr->wr_blkhash,
2775 	    (wr->wr_blkhashmask + 1) * sizeof(*wr->wr_blkhash));
2776 #endif /* ! _KERNEL */
2777 }
2778 
2779 static struct wapbl_blk *
2780 wapbl_blkhash_get(struct wapbl_replay *wr, daddr_t blk)
2781 {
2782 	struct wapbl_blk_head *wbh;
2783 	struct wapbl_blk *wb;
2784 	wbh = &wr->wr_blkhash[blk & wr->wr_blkhashmask];
2785 	LIST_FOREACH(wb, wbh, wb_hash) {
2786 		if (blk == wb->wb_blk)
2787 			return wb;
2788 	}
2789 	return 0;
2790 }
2791 
2792 static void
2793 wapbl_blkhash_ins(struct wapbl_replay *wr, daddr_t blk, off_t off)
2794 {
2795 	struct wapbl_blk_head *wbh;
2796 	struct wapbl_blk *wb;
2797 	wb = wapbl_blkhash_get(wr, blk);
2798 	if (wb) {
2799 		KASSERT(wb->wb_blk == blk);
2800 		wb->wb_off = off;
2801 	} else {
2802 		wb = wapbl_alloc(sizeof(*wb));
2803 		wb->wb_blk = blk;
2804 		wb->wb_off = off;
2805 		wbh = &wr->wr_blkhash[blk & wr->wr_blkhashmask];
2806 		LIST_INSERT_HEAD(wbh, wb, wb_hash);
2807 		wr->wr_blkhashcnt++;
2808 	}
2809 }
2810 
2811 static void
2812 wapbl_blkhash_rem(struct wapbl_replay *wr, daddr_t blk)
2813 {
2814 	struct wapbl_blk *wb = wapbl_blkhash_get(wr, blk);
2815 	if (wb) {
2816 		KASSERT(wr->wr_blkhashcnt > 0);
2817 		wr->wr_blkhashcnt--;
2818 		LIST_REMOVE(wb, wb_hash);
2819 		wapbl_free(wb, sizeof(*wb));
2820 	}
2821 }
2822 
2823 static void
2824 wapbl_blkhash_clear(struct wapbl_replay *wr)
2825 {
2826 	unsigned long i;
2827 	for (i = 0; i <= wr->wr_blkhashmask; i++) {
2828 		struct wapbl_blk *wb;
2829 
2830 		while ((wb = LIST_FIRST(&wr->wr_blkhash[i]))) {
2831 			KASSERT(wr->wr_blkhashcnt > 0);
2832 			wr->wr_blkhashcnt--;
2833 			LIST_REMOVE(wb, wb_hash);
2834 			wapbl_free(wb, sizeof(*wb));
2835 		}
2836 	}
2837 	KASSERT(wr->wr_blkhashcnt == 0);
2838 }
2839 
2840 /****************************************************************/
2841 
2842 /*
2843  * wapbl_circ_read(wr, data, len, offp)
2844  *
2845  *	Read len bytes into data from the circular queue of wr,
2846  *	starting at the linear byte offset *offp, and returning the new
2847  *	linear byte offset in *offp.
2848  *
2849  *	If the starting linear byte offset precedes wr->wr_circ_off,
2850  *	the read instead begins at wr->wr_circ_off.  XXX WTF?  This
2851  *	should be a KASSERT, not a conditional.
2852  */
2853 static int
2854 wapbl_circ_read(struct wapbl_replay *wr, void *data, size_t len, off_t *offp)
2855 {
2856 	size_t slen;
2857 	off_t off = *offp;
2858 	int error;
2859 	daddr_t pbn;
2860 
2861 	KASSERT(((len >> wr->wr_log_dev_bshift) <<
2862 	    wr->wr_log_dev_bshift) == len);
2863 
2864 	if (off < wr->wr_circ_off)
2865 		off = wr->wr_circ_off;
2866 	slen = wr->wr_circ_off + wr->wr_circ_size - off;
2867 	if (slen < len) {
2868 		pbn = wr->wr_logpbn + (off >> wr->wr_log_dev_bshift);
2869 #ifdef _KERNEL
2870 		pbn = btodb(pbn << wr->wr_log_dev_bshift);
2871 #endif
2872 		error = wapbl_read(data, slen, wr->wr_devvp, pbn);
2873 		if (error)
2874 			return error;
2875 		data = (uint8_t *)data + slen;
2876 		len -= slen;
2877 		off = wr->wr_circ_off;
2878 	}
2879 	pbn = wr->wr_logpbn + (off >> wr->wr_log_dev_bshift);
2880 #ifdef _KERNEL
2881 	pbn = btodb(pbn << wr->wr_log_dev_bshift);
2882 #endif
2883 	error = wapbl_read(data, len, wr->wr_devvp, pbn);
2884 	if (error)
2885 		return error;
2886 	off += len;
2887 	if (off >= wr->wr_circ_off + wr->wr_circ_size)
2888 		off = wr->wr_circ_off;
2889 	*offp = off;
2890 	return 0;
2891 }
2892 
2893 /*
2894  * wapbl_circ_advance(wr, len, offp)
2895  *
2896  *	Compute the linear byte offset of the circular queue of wr that
2897  *	is len bytes past *offp, and store it in *offp.
2898  *
2899  *	This is as if wapbl_circ_read, but without actually reading
2900  *	anything.
2901  *
2902  *	If the starting linear byte offset precedes wr->wr_circ_off, it
2903  *	is taken to be wr->wr_circ_off instead.  XXX WTF?  This should
2904  *	be a KASSERT, not a conditional.
2905  */
2906 static void
2907 wapbl_circ_advance(struct wapbl_replay *wr, size_t len, off_t *offp)
2908 {
2909 	size_t slen;
2910 	off_t off = *offp;
2911 
2912 	KASSERT(((len >> wr->wr_log_dev_bshift) <<
2913 	    wr->wr_log_dev_bshift) == len);
2914 
2915 	if (off < wr->wr_circ_off)
2916 		off = wr->wr_circ_off;
2917 	slen = wr->wr_circ_off + wr->wr_circ_size - off;
2918 	if (slen < len) {
2919 		len -= slen;
2920 		off = wr->wr_circ_off;
2921 	}
2922 	off += len;
2923 	if (off >= wr->wr_circ_off + wr->wr_circ_size)
2924 		off = wr->wr_circ_off;
2925 	*offp = off;
2926 }
2927 
2928 /****************************************************************/
2929 
2930 int
2931 wapbl_replay_start(struct wapbl_replay **wrp, struct vnode *vp,
2932 	daddr_t off, size_t count, size_t blksize)
2933 {
2934 	struct wapbl_replay *wr;
2935 	int error;
2936 	struct vnode *devvp;
2937 	daddr_t logpbn;
2938 	uint8_t *scratch;
2939 	struct wapbl_wc_header *wch;
2940 	struct wapbl_wc_header *wch2;
2941 	/* Use this until we read the actual log header */
2942 	int log_dev_bshift = ilog2(blksize);
2943 	size_t used;
2944 	daddr_t pbn;
2945 
2946 	WAPBL_PRINTF(WAPBL_PRINT_REPLAY,
2947 	    ("wapbl_replay_start: vp=%p off=%"PRId64 " count=%zu blksize=%zu\n",
2948 	    vp, off, count, blksize));
2949 
2950 	if (off < 0)
2951 		return EINVAL;
2952 
2953 	if (blksize < DEV_BSIZE)
2954 		return EINVAL;
2955 	if (blksize % DEV_BSIZE)
2956 		return EINVAL;
2957 
2958 #ifdef _KERNEL
2959 #if 0
2960 	/* XXX vp->v_size isn't reliably set for VBLK devices,
2961 	 * especially root.  However, we might still want to verify
2962 	 * that the full load is readable */
2963 	if ((off + count) * blksize > vp->v_size)
2964 		return EINVAL;
2965 #endif
2966 	if ((error = VOP_BMAP(vp, off, &devvp, &logpbn, 0)) != 0) {
2967 		return error;
2968 	}
2969 #else /* ! _KERNEL */
2970 	devvp = vp;
2971 	logpbn = off;
2972 #endif /* ! _KERNEL */
2973 
2974 	scratch = wapbl_alloc(MAXBSIZE);
2975 
2976 	pbn = logpbn;
2977 #ifdef _KERNEL
2978 	pbn = btodb(pbn << log_dev_bshift);
2979 #endif
2980 	error = wapbl_read(scratch, 2<<log_dev_bshift, devvp, pbn);
2981 	if (error)
2982 		goto errout;
2983 
2984 	wch = (struct wapbl_wc_header *)scratch;
2985 	wch2 =
2986 	    (struct wapbl_wc_header *)(scratch + (1<<log_dev_bshift));
2987 	/* XXX verify checksums and magic numbers */
2988 	if (wch->wc_type != WAPBL_WC_HEADER) {
2989 		printf("Unrecognized wapbl magic: 0x%08x\n", wch->wc_type);
2990 		error = EFTYPE;
2991 		goto errout;
2992 	}
2993 
2994 	if (wch2->wc_generation > wch->wc_generation)
2995 		wch = wch2;
2996 
2997 	wr = wapbl_calloc(1, sizeof(*wr));
2998 
2999 	wr->wr_logvp = vp;
3000 	wr->wr_devvp = devvp;
3001 	wr->wr_logpbn = logpbn;
3002 
3003 	wr->wr_scratch = scratch;
3004 
3005 	wr->wr_log_dev_bshift = wch->wc_log_dev_bshift;
3006 	wr->wr_fs_dev_bshift = wch->wc_fs_dev_bshift;
3007 	wr->wr_circ_off = wch->wc_circ_off;
3008 	wr->wr_circ_size = wch->wc_circ_size;
3009 	wr->wr_generation = wch->wc_generation;
3010 
3011 	used = wapbl_space_used(wch->wc_circ_size, wch->wc_head, wch->wc_tail);
3012 
3013 	WAPBL_PRINTF(WAPBL_PRINT_REPLAY,
3014 	    ("wapbl_replay: head=%"PRId64" tail=%"PRId64" off=%"PRId64
3015 	    " len=%"PRId64" used=%zu\n",
3016 	    wch->wc_head, wch->wc_tail, wch->wc_circ_off,
3017 	    wch->wc_circ_size, used));
3018 
3019 	wapbl_blkhash_init(wr, (used >> wch->wc_fs_dev_bshift));
3020 
3021 	error = wapbl_replay_process(wr, wch->wc_head, wch->wc_tail);
3022 	if (error) {
3023 		wapbl_replay_stop(wr);
3024 		wapbl_replay_free(wr);
3025 		return error;
3026 	}
3027 
3028 	*wrp = wr;
3029 	return 0;
3030 
3031  errout:
3032 	wapbl_free(scratch, MAXBSIZE);
3033 	return error;
3034 }
3035 
3036 void
3037 wapbl_replay_stop(struct wapbl_replay *wr)
3038 {
3039 
3040 	if (!wapbl_replay_isopen(wr))
3041 		return;
3042 
3043 	WAPBL_PRINTF(WAPBL_PRINT_REPLAY, ("wapbl_replay_stop called\n"));
3044 
3045 	wapbl_free(wr->wr_scratch, MAXBSIZE);
3046 	wr->wr_scratch = NULL;
3047 
3048 	wr->wr_logvp = NULL;
3049 
3050 	wapbl_blkhash_clear(wr);
3051 	wapbl_blkhash_free(wr);
3052 }
3053 
3054 void
3055 wapbl_replay_free(struct wapbl_replay *wr)
3056 {
3057 
3058 	KDASSERT(!wapbl_replay_isopen(wr));
3059 
3060 	if (wr->wr_inodes)
3061 		wapbl_free(wr->wr_inodes,
3062 		    wr->wr_inodescnt * sizeof(wr->wr_inodes[0]));
3063 	wapbl_free(wr, sizeof(*wr));
3064 }
3065 
3066 #ifdef _KERNEL
3067 int
3068 wapbl_replay_isopen1(struct wapbl_replay *wr)
3069 {
3070 
3071 	return wapbl_replay_isopen(wr);
3072 }
3073 #endif
3074 
3075 /*
3076  * calculate the disk address for the i'th block in the wc_blockblist
3077  * offset by j blocks of size blen.
3078  *
3079  * wc_daddr is always a kernel disk address in DEV_BSIZE units that
3080  * was written to the journal.
3081  *
3082  * The kernel needs that address plus the offset in DEV_BSIZE units.
3083  *
3084  * Userland needs that address plus the offset in blen units.
3085  *
3086  */
3087 static daddr_t
3088 wapbl_block_daddr(struct wapbl_wc_blocklist *wc, int i, int j, int blen)
3089 {
3090 	daddr_t pbn;
3091 
3092 #ifdef _KERNEL
3093 	pbn = wc->wc_blocks[i].wc_daddr + btodb(j * blen);
3094 #else
3095 	pbn = dbtob(wc->wc_blocks[i].wc_daddr) / blen + j;
3096 #endif
3097 
3098 	return pbn;
3099 }
3100 
3101 static void
3102 wapbl_replay_process_blocks(struct wapbl_replay *wr, off_t *offp)
3103 {
3104 	struct wapbl_wc_blocklist *wc =
3105 	    (struct wapbl_wc_blocklist *)wr->wr_scratch;
3106 	int fsblklen = 1 << wr->wr_fs_dev_bshift;
3107 	int i, j, n;
3108 
3109 	for (i = 0; i < wc->wc_blkcount; i++) {
3110 		/*
3111 		 * Enter each physical block into the hashtable independently.
3112 		 */
3113 		n = wc->wc_blocks[i].wc_dlen >> wr->wr_fs_dev_bshift;
3114 		for (j = 0; j < n; j++) {
3115 			wapbl_blkhash_ins(wr, wapbl_block_daddr(wc, i, j, fsblklen),
3116 			    *offp);
3117 			wapbl_circ_advance(wr, fsblklen, offp);
3118 		}
3119 	}
3120 }
3121 
3122 static void
3123 wapbl_replay_process_revocations(struct wapbl_replay *wr)
3124 {
3125 	struct wapbl_wc_blocklist *wc =
3126 	    (struct wapbl_wc_blocklist *)wr->wr_scratch;
3127 	int fsblklen = 1 << wr->wr_fs_dev_bshift;
3128 	int i, j, n;
3129 
3130 	for (i = 0; i < wc->wc_blkcount; i++) {
3131 		/*
3132 		 * Remove any blocks found from the hashtable.
3133 		 */
3134 		n = wc->wc_blocks[i].wc_dlen >> wr->wr_fs_dev_bshift;
3135 		for (j = 0; j < n; j++)
3136 			wapbl_blkhash_rem(wr, wapbl_block_daddr(wc, i, j, fsblklen));
3137 	}
3138 }
3139 
3140 static void
3141 wapbl_replay_process_inodes(struct wapbl_replay *wr, off_t oldoff, off_t newoff)
3142 {
3143 	struct wapbl_wc_inodelist *wc =
3144 	    (struct wapbl_wc_inodelist *)wr->wr_scratch;
3145 	void *new_inodes;
3146 	const size_t oldsize = wr->wr_inodescnt * sizeof(wr->wr_inodes[0]);
3147 
3148 	KASSERT(sizeof(wr->wr_inodes[0]) == sizeof(wc->wc_inodes[0]));
3149 
3150 	/*
3151 	 * Keep track of where we found this so location won't be
3152 	 * overwritten.
3153 	 */
3154 	if (wc->wc_clear) {
3155 		wr->wr_inodestail = oldoff;
3156 		wr->wr_inodescnt = 0;
3157 		if (wr->wr_inodes != NULL) {
3158 			wapbl_free(wr->wr_inodes, oldsize);
3159 			wr->wr_inodes = NULL;
3160 		}
3161 	}
3162 	wr->wr_inodeshead = newoff;
3163 	if (wc->wc_inocnt == 0)
3164 		return;
3165 
3166 	new_inodes = wapbl_alloc((wr->wr_inodescnt + wc->wc_inocnt) *
3167 	    sizeof(wr->wr_inodes[0]));
3168 	if (wr->wr_inodes != NULL) {
3169 		memcpy(new_inodes, wr->wr_inodes, oldsize);
3170 		wapbl_free(wr->wr_inodes, oldsize);
3171 	}
3172 	wr->wr_inodes = new_inodes;
3173 	memcpy(&wr->wr_inodes[wr->wr_inodescnt], wc->wc_inodes,
3174 	    wc->wc_inocnt * sizeof(wr->wr_inodes[0]));
3175 	wr->wr_inodescnt += wc->wc_inocnt;
3176 }
3177 
3178 static int
3179 wapbl_replay_process(struct wapbl_replay *wr, off_t head, off_t tail)
3180 {
3181 	off_t off;
3182 	int error;
3183 
3184 	int logblklen = 1 << wr->wr_log_dev_bshift;
3185 
3186 	wapbl_blkhash_clear(wr);
3187 
3188 	off = tail;
3189 	while (off != head) {
3190 		struct wapbl_wc_null *wcn;
3191 		off_t saveoff = off;
3192 		error = wapbl_circ_read(wr, wr->wr_scratch, logblklen, &off);
3193 		if (error)
3194 			goto errout;
3195 		wcn = (struct wapbl_wc_null *)wr->wr_scratch;
3196 		switch (wcn->wc_type) {
3197 		case WAPBL_WC_BLOCKS:
3198 			wapbl_replay_process_blocks(wr, &off);
3199 			break;
3200 
3201 		case WAPBL_WC_REVOCATIONS:
3202 			wapbl_replay_process_revocations(wr);
3203 			break;
3204 
3205 		case WAPBL_WC_INODES:
3206 			wapbl_replay_process_inodes(wr, saveoff, off);
3207 			break;
3208 
3209 		default:
3210 			printf("Unrecognized wapbl type: 0x%08x\n",
3211 			       wcn->wc_type);
3212  			error = EFTYPE;
3213 			goto errout;
3214 		}
3215 		wapbl_circ_advance(wr, wcn->wc_len, &saveoff);
3216 		if (off != saveoff) {
3217 			printf("wapbl_replay: corrupted records\n");
3218 			error = EFTYPE;
3219 			goto errout;
3220 		}
3221 	}
3222 	return 0;
3223 
3224  errout:
3225 	wapbl_blkhash_clear(wr);
3226 	return error;
3227 }
3228 
3229 #if 0
3230 int
3231 wapbl_replay_verify(struct wapbl_replay *wr, struct vnode *fsdevvp)
3232 {
3233 	off_t off;
3234 	int mismatchcnt = 0;
3235 	int logblklen = 1 << wr->wr_log_dev_bshift;
3236 	int fsblklen = 1 << wr->wr_fs_dev_bshift;
3237 	void *scratch1 = wapbl_alloc(MAXBSIZE);
3238 	void *scratch2 = wapbl_alloc(MAXBSIZE);
3239 	int error = 0;
3240 
3241 	KDASSERT(wapbl_replay_isopen(wr));
3242 
3243 	off = wch->wc_tail;
3244 	while (off != wch->wc_head) {
3245 		struct wapbl_wc_null *wcn;
3246 #ifdef DEBUG
3247 		off_t saveoff = off;
3248 #endif
3249 		error = wapbl_circ_read(wr, wr->wr_scratch, logblklen, &off);
3250 		if (error)
3251 			goto out;
3252 		wcn = (struct wapbl_wc_null *)wr->wr_scratch;
3253 		switch (wcn->wc_type) {
3254 		case WAPBL_WC_BLOCKS:
3255 			{
3256 				struct wapbl_wc_blocklist *wc =
3257 				    (struct wapbl_wc_blocklist *)wr->wr_scratch;
3258 				int i;
3259 				for (i = 0; i < wc->wc_blkcount; i++) {
3260 					int foundcnt = 0;
3261 					int dirtycnt = 0;
3262 					int j, n;
3263 					/*
3264 					 * Check each physical block into the
3265 					 * hashtable independently
3266 					 */
3267 					n = wc->wc_blocks[i].wc_dlen >>
3268 					    wch->wc_fs_dev_bshift;
3269 					for (j = 0; j < n; j++) {
3270 						struct wapbl_blk *wb =
3271 						   wapbl_blkhash_get(wr,
3272 						   wapbl_block_daddr(wc, i, j, fsblklen));
3273 						if (wb && (wb->wb_off == off)) {
3274 							foundcnt++;
3275 							error =
3276 							    wapbl_circ_read(wr,
3277 							    scratch1, fsblklen,
3278 							    &off);
3279 							if (error)
3280 								goto out;
3281 							error =
3282 							    wapbl_read(scratch2,
3283 							    fsblklen, fsdevvp,
3284 							    wb->wb_blk);
3285 							if (error)
3286 								goto out;
3287 							if (memcmp(scratch1,
3288 								   scratch2,
3289 								   fsblklen)) {
3290 								printf(
3291 		"wapbl_verify: mismatch block %"PRId64" at off %"PRIdMAX"\n",
3292 		wb->wb_blk, (intmax_t)off);
3293 								dirtycnt++;
3294 								mismatchcnt++;
3295 							}
3296 						} else {
3297 							wapbl_circ_advance(wr,
3298 							    fsblklen, &off);
3299 						}
3300 					}
3301 #if 0
3302 					/*
3303 					 * If all of the blocks in an entry
3304 					 * are clean, then remove all of its
3305 					 * blocks from the hashtable since they
3306 					 * never will need replay.
3307 					 */
3308 					if ((foundcnt != 0) &&
3309 					    (dirtycnt == 0)) {
3310 						off = saveoff;
3311 						wapbl_circ_advance(wr,
3312 						    logblklen, &off);
3313 						for (j = 0; j < n; j++) {
3314 							struct wapbl_blk *wb =
3315 							   wapbl_blkhash_get(wr,
3316 							   wapbl_block_daddr(wc, i, j, fsblklen));
3317 							if (wb &&
3318 							  (wb->wb_off == off)) {
3319 								wapbl_blkhash_rem(wr, wb->wb_blk);
3320 							}
3321 							wapbl_circ_advance(wr,
3322 							    fsblklen, &off);
3323 						}
3324 					}
3325 #endif
3326 				}
3327 			}
3328 			break;
3329 		case WAPBL_WC_REVOCATIONS:
3330 		case WAPBL_WC_INODES:
3331 			break;
3332 		default:
3333 			KASSERT(0);
3334 		}
3335 #ifdef DEBUG
3336 		wapbl_circ_advance(wr, wcn->wc_len, &saveoff);
3337 		KASSERT(off == saveoff);
3338 #endif
3339 	}
3340  out:
3341 	wapbl_free(scratch1, MAXBSIZE);
3342 	wapbl_free(scratch2, MAXBSIZE);
3343 	if (!error && mismatchcnt)
3344 		error = EFTYPE;
3345 	return error;
3346 }
3347 #endif
3348 
3349 int
3350 wapbl_replay_write(struct wapbl_replay *wr, struct vnode *fsdevvp)
3351 {
3352 	struct wapbl_blk *wb;
3353 	size_t i;
3354 	off_t off;
3355 	void *scratch;
3356 	int error = 0;
3357 	int fsblklen = 1 << wr->wr_fs_dev_bshift;
3358 
3359 	KDASSERT(wapbl_replay_isopen(wr));
3360 
3361 	scratch = wapbl_alloc(MAXBSIZE);
3362 
3363 	for (i = 0; i <= wr->wr_blkhashmask; ++i) {
3364 		LIST_FOREACH(wb, &wr->wr_blkhash[i], wb_hash) {
3365 			off = wb->wb_off;
3366 			error = wapbl_circ_read(wr, scratch, fsblklen, &off);
3367 			if (error)
3368 				break;
3369 			error = wapbl_write(scratch, fsblklen, fsdevvp,
3370 			    wb->wb_blk);
3371 			if (error)
3372 				break;
3373 		}
3374 	}
3375 
3376 	wapbl_free(scratch, MAXBSIZE);
3377 	return error;
3378 }
3379 
3380 int
3381 wapbl_replay_can_read(struct wapbl_replay *wr, daddr_t blk, long len)
3382 {
3383 	int fsblklen = 1 << wr->wr_fs_dev_bshift;
3384 
3385 	KDASSERT(wapbl_replay_isopen(wr));
3386 	KASSERT((len % fsblklen) == 0);
3387 
3388 	while (len != 0) {
3389 		struct wapbl_blk *wb = wapbl_blkhash_get(wr, blk);
3390 		if (wb)
3391 			return 1;
3392 		len -= fsblklen;
3393 	}
3394 	return 0;
3395 }
3396 
3397 int
3398 wapbl_replay_read(struct wapbl_replay *wr, void *data, daddr_t blk, long len)
3399 {
3400 	int fsblklen = 1 << wr->wr_fs_dev_bshift;
3401 
3402 	KDASSERT(wapbl_replay_isopen(wr));
3403 
3404 	KASSERT((len % fsblklen) == 0);
3405 
3406 	while (len != 0) {
3407 		struct wapbl_blk *wb = wapbl_blkhash_get(wr, blk);
3408 		if (wb) {
3409 			off_t off = wb->wb_off;
3410 			int error;
3411 			error = wapbl_circ_read(wr, data, fsblklen, &off);
3412 			if (error)
3413 				return error;
3414 		}
3415 		data = (uint8_t *)data + fsblklen;
3416 		len -= fsblklen;
3417 		blk++;
3418 	}
3419 	return 0;
3420 }
3421 
3422 #ifdef _KERNEL
3423 
3424 MODULE(MODULE_CLASS_VFS, wapbl, NULL);
3425 
3426 static int
3427 wapbl_modcmd(modcmd_t cmd, void *arg)
3428 {
3429 
3430 	switch (cmd) {
3431 	case MODULE_CMD_INIT:
3432 		wapbl_init();
3433 		return 0;
3434 	case MODULE_CMD_FINI:
3435 		return wapbl_fini();
3436 	default:
3437 		return ENOTTY;
3438 	}
3439 }
3440 #endif /* _KERNEL */
3441