]> git.saurik.com Git - apple/xnu.git/blob - bsd/vfs/vfs_journal.c
3864ff34c2b805092352f92a433461b707827ffe
[apple/xnu.git] / bsd / vfs / vfs_journal.c
1 /*
2 * Copyright (c) 2002-2012 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 //
29 // This file implements a simple write-ahead journaling layer.
30 // In theory any file system can make use of it by calling these
31 // functions when the fs wants to modify meta-data blocks. See
32 // vfs_journal.h for a more detailed description of the api and
33 // data structures.
34 //
35 // Dominic Giampaolo (dbg@apple.com)
36 //
37
38 #ifdef KERNEL
39
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/kernel.h>
43 #include <sys/file_internal.h>
44 #include <sys/stat.h>
45 #include <sys/buf_internal.h>
46 #include <sys/proc_internal.h>
47 #include <sys/mount_internal.h>
48 #include <sys/namei.h>
49 #include <sys/vnode_internal.h>
50 #include <sys/ioctl.h>
51 #include <sys/tty.h>
52 #include <sys/ubc.h>
53 #include <sys/malloc.h>
54 #include <kern/task.h>
55 #include <kern/thread.h>
56 #include <kern/kalloc.h>
57 #include <sys/disk.h>
58 #include <sys/kdebug.h>
59 #include <miscfs/specfs/specdev.h>
60 #include <libkern/OSAtomic.h> /* OSAddAtomic */
61
62 kern_return_t thread_terminate(thread_t);
63
64 /*
65 * Set sysctl vfs.generic.jnl.kdebug.trim=1 to enable KERNEL_DEBUG_CONSTANT
66 * logging of trim-related calls within the journal. (They're
67 * disabled by default because there can be a lot of these events,
68 * and we don't want to overwhelm the kernel debug buffer. If you
69 * want to watch these events in particular, just set the sysctl.)
70 */
71 static int jnl_kdebug = 0;
72 SYSCTL_DECL(_vfs_generic);
73 SYSCTL_NODE(_vfs_generic, OID_AUTO, jnl, CTLFLAG_RW|CTLFLAG_LOCKED, 0, "Journal");
74 SYSCTL_NODE(_vfs_generic_jnl, OID_AUTO, kdebug, CTLFLAG_RW|CTLFLAG_LOCKED, 0, "Journal kdebug");
75 SYSCTL_INT(_vfs_generic_jnl_kdebug, OID_AUTO, trim, CTLFLAG_RW|CTLFLAG_LOCKED, &jnl_kdebug, 0, "Enable kdebug logging for journal TRIM");
76
77 #define DBG_JOURNAL_FLUSH FSDBG_CODE(DBG_JOURNAL, 1)
78 #define DBG_JOURNAL_TRIM_ADD FSDBG_CODE(DBG_JOURNAL, 2)
79 #define DBG_JOURNAL_TRIM_REMOVE FSDBG_CODE(DBG_JOURNAL, 3)
80 #define DBG_JOURNAL_TRIM_REMOVE_PENDING FSDBG_CODE(DBG_JOURNAL, 4)
81 #define DBG_JOURNAL_TRIM_REALLOC FSDBG_CODE(DBG_JOURNAL, 5)
82 #define DBG_JOURNAL_TRIM_FLUSH FSDBG_CODE(DBG_JOURNAL, 6)
83 #define DBG_JOURNAL_TRIM_UNMAP FSDBG_CODE(DBG_JOURNAL, 7)
84
85 /*
86 * Cap the journal max size to 2GB. On HFS, it will attempt to occupy
87 * a full allocation block if the current size is smaller than the allocation
88 * block on which it resides. Once we hit the exabyte filesystem range, then
89 * it will use 2GB allocation blocks. As a result, make the cap 2GB.
90 */
91 #define MAX_JOURNAL_SIZE 0x80000000U
92
93 #include <sys/sdt.h> /* DTRACE_IO1 */
94 #else
95
96 #include <stdio.h>
97 #include <stdlib.h>
98 #include <string.h>
99 #include <limits.h>
100 #include <errno.h>
101 #include <fcntl.h>
102 #include <unistd.h>
103 #include <stdarg.h>
104 #include <sys/types.h>
105 #include "compat.h"
106
107 #endif /* KERNEL */
108
109 #include "vfs_journal.h"
110
111 #include <sys/kdebug.h>
112
113 #if 0
114 #undef KERNEL_DEBUG
115 #define KERNEL_DEBUG KERNEL_DEBUG_CONSTANT
116 #endif
117
118
119 #ifndef CONFIG_HFS_TRIM
120 #define CONFIG_HFS_TRIM 0
121 #endif
122
123
124 #if JOURNALING
125
126 //
127 // By default, we grow the list of extents to trim by one page at a time.
128 // We'll opt to flush a transaction if it contains at least
129 // JOURNAL_FLUSH_TRIM_EXTENTS extents to be trimmed (even if the number
130 // of modified blocks is small).
131 //
132 enum {
133 JOURNAL_DEFAULT_TRIM_BYTES = PAGE_SIZE,
134 JOURNAL_DEFAULT_TRIM_EXTENTS = JOURNAL_DEFAULT_TRIM_BYTES / sizeof(dk_extent_t),
135 JOURNAL_FLUSH_TRIM_EXTENTS = JOURNAL_DEFAULT_TRIM_EXTENTS * 15 / 16
136 };
137
138 unsigned int jnl_trim_flush_limit = JOURNAL_FLUSH_TRIM_EXTENTS;
139 SYSCTL_UINT (_kern, OID_AUTO, jnl_trim_flush, CTLFLAG_RW, &jnl_trim_flush_limit, 0, "number of trimmed extents to cause a journal flush");
140
141 /* XXX next prototype should be from libsa/stdlib.h> but conflicts libkern */
142 __private_extern__ void qsort(
143 void * array,
144 size_t nmembers,
145 size_t member_size,
146 int (*)(const void *, const void *));
147
148
149
150 // number of bytes to checksum in a block_list_header
151 // NOTE: this should be enough to clear out the header
152 // fields as well as the first entry of binfo[]
153 #define BLHDR_CHECKSUM_SIZE 32
154
155 static void lock_condition(journal *jnl, boolean_t *condition, const char *condition_name);
156 static void wait_condition(journal *jnl, boolean_t *condition, const char *condition_name);
157 static void unlock_condition(journal *jnl, boolean_t *condition);
158 static void finish_end_thread(transaction *tr);
159 static void write_header_thread(journal *jnl);
160 static int finish_end_transaction(transaction *tr, errno_t (*callback)(void*), void *callback_arg);
161 static int end_transaction(transaction *tr, int force_it, errno_t (*callback)(void*), void *callback_arg, boolean_t drop_lock, boolean_t must_wait);
162 static void abort_transaction(journal *jnl, transaction *tr);
163 static void dump_journal(journal *jnl);
164
165 static __inline__ void lock_journal(journal *jnl);
166 static __inline__ void unlock_journal(journal *jnl);
167 static __inline__ void lock_oldstart(journal *jnl);
168 static __inline__ void unlock_oldstart(journal *jnl);
169 static __inline__ void lock_flush(journal *jnl);
170 static __inline__ void unlock_flush(journal *jnl);
171
172
173 //
174 // 3105942 - Coalesce writes to the same block on journal replay
175 //
176
177 typedef struct bucket {
178 off_t block_num;
179 uint32_t jnl_offset;
180 uint32_t block_size;
181 int32_t cksum;
182 } bucket;
183
184 #define STARTING_BUCKETS 256
185
186 static int add_block(journal *jnl, struct bucket **buf_ptr, off_t block_num, size_t size, size_t offset, int32_t cksum, int *num_buckets_ptr, int *num_full_ptr);
187 static int grow_table(struct bucket **buf_ptr, int num_buckets, int new_size);
188 static int lookup_bucket(struct bucket **buf_ptr, off_t block_num, int num_full);
189 static int do_overlap(journal *jnl, struct bucket **buf_ptr, int blk_index, off_t block_num, size_t size, size_t offset, int32_t cksum, int *num_buckets_ptr, int *num_full_ptr);
190 static int insert_block(journal *jnl, struct bucket **buf_ptr, int blk_index, off_t num, size_t size, size_t offset, int32_t cksum, int *num_buckets_ptr, int *num_full_ptr, int overwriting);
191
192 #define CHECK_JOURNAL(jnl) \
193 do { \
194 if (jnl == NULL) { \
195 panic("%s:%d: null journal ptr?\n", __FILE__, __LINE__); \
196 } \
197 if (jnl->jdev == NULL) { \
198 panic("%s:%d: jdev is null!\n", __FILE__, __LINE__); \
199 } \
200 if (jnl->fsdev == NULL) { \
201 panic("%s:%d: fsdev is null!\n", __FILE__, __LINE__); \
202 } \
203 if (jnl->jhdr->magic != JOURNAL_HEADER_MAGIC) { \
204 panic("%s:%d: jhdr magic corrupted (0x%x != 0x%x)\n", \
205 __FILE__, __LINE__, jnl->jhdr->magic, JOURNAL_HEADER_MAGIC); \
206 } \
207 if ( jnl->jhdr->start <= 0 \
208 || jnl->jhdr->start > jnl->jhdr->size) { \
209 panic("%s:%d: jhdr start looks bad (0x%llx max size 0x%llx)\n", \
210 __FILE__, __LINE__, jnl->jhdr->start, jnl->jhdr->size); \
211 } \
212 if ( jnl->jhdr->end <= 0 \
213 || jnl->jhdr->end > jnl->jhdr->size) { \
214 panic("%s:%d: jhdr end looks bad (0x%llx max size 0x%llx)\n", \
215 __FILE__, __LINE__, jnl->jhdr->end, jnl->jhdr->size); \
216 } \
217 } while(0)
218
219 #define CHECK_TRANSACTION(tr) \
220 do { \
221 if (tr == NULL) { \
222 panic("%s:%d: null transaction ptr?\n", __FILE__, __LINE__); \
223 } \
224 if (tr->jnl == NULL) { \
225 panic("%s:%d: null tr->jnl ptr?\n", __FILE__, __LINE__); \
226 } \
227 if (tr->blhdr != (block_list_header *)tr->tbuffer) { \
228 panic("%s:%d: blhdr (%p) != tbuffer (%p)\n", __FILE__, __LINE__, tr->blhdr, tr->tbuffer); \
229 } \
230 if (tr->total_bytes < 0) { \
231 panic("%s:%d: tr total_bytes looks bad: %d\n", __FILE__, __LINE__, tr->total_bytes); \
232 } \
233 if (tr->journal_start < 0) { \
234 panic("%s:%d: tr journal start looks bad: 0x%llx\n", __FILE__, __LINE__, tr->journal_start); \
235 } \
236 if (tr->journal_end < 0) { \
237 panic("%s:%d: tr journal end looks bad: 0x%llx\n", __FILE__, __LINE__, tr->journal_end); \
238 } \
239 if (tr->blhdr && (tr->blhdr->max_blocks <= 0 || tr->blhdr->max_blocks > (tr->jnl->jhdr->size/tr->jnl->jhdr->jhdr_size))) { \
240 panic("%s:%d: tr blhdr max_blocks looks bad: %d\n", __FILE__, __LINE__, tr->blhdr->max_blocks); \
241 } \
242 } while(0)
243
244
245
246 //
247 // this isn't a great checksum routine but it will do for now.
248 // we use it to checksum the journal header and the block list
249 // headers that are at the start of each transaction.
250 //
251 static int
252 calc_checksum(char *ptr, int len)
253 {
254 int i, cksum=0;
255
256 // this is a lame checksum but for now it'll do
257 for(i = 0; i < len; i++, ptr++) {
258 cksum = (cksum << 8) ^ (cksum + *(unsigned char *)ptr);
259 }
260
261 return (~cksum);
262 }
263
264 //
265 // Journal Locking
266 //
267 lck_grp_attr_t * jnl_group_attr;
268 lck_attr_t * jnl_lock_attr;
269 lck_grp_t * jnl_mutex_group;
270
271 void
272 journal_init(void)
273 {
274 jnl_lock_attr = lck_attr_alloc_init();
275 jnl_group_attr = lck_grp_attr_alloc_init();
276 jnl_mutex_group = lck_grp_alloc_init("jnl-mutex", jnl_group_attr);
277 }
278
279 static __inline__ void
280 lock_journal(journal *jnl)
281 {
282 lck_mtx_lock(&jnl->jlock);
283 }
284
285 static __inline__ void
286 unlock_journal(journal *jnl)
287 {
288 lck_mtx_unlock(&jnl->jlock);
289 }
290
291 static __inline__ void
292 lock_flush(journal *jnl)
293 {
294 lck_mtx_lock(&jnl->flock);
295 }
296
297 static __inline__ void
298 unlock_flush(journal *jnl)
299 {
300 lck_mtx_unlock(&jnl->flock);
301 }
302
303 static __inline__ void
304 lock_oldstart(journal *jnl)
305 {
306 lck_mtx_lock(&jnl->old_start_lock);
307 }
308
309 static __inline__ void
310 unlock_oldstart(journal *jnl)
311 {
312 lck_mtx_unlock(&jnl->old_start_lock);
313 }
314
315
316
317 #define JNL_WRITE 0x0001
318 #define JNL_READ 0x0002
319 #define JNL_HEADER 0x8000
320
321 //
322 // This function sets up a fake buf and passes it directly to the
323 // journal device strategy routine (so that it won't get cached in
324 // the block cache.
325 //
326 // It also handles range checking the i/o so that we don't write
327 // outside the journal boundaries and it will wrap the i/o back
328 // to the beginning if necessary (skipping over the journal header)
329 //
330 static size_t
331 do_journal_io(journal *jnl, off_t *offset, void *data, size_t len, int direction)
332 {
333 int err, curlen=len;
334 size_t io_sz = 0;
335 buf_t bp;
336 off_t max_iosize;
337
338 if (*offset < 0 || *offset > jnl->jhdr->size) {
339 panic("jnl: do_jnl_io: bad offset 0x%llx (max 0x%llx)\n", *offset, jnl->jhdr->size);
340 }
341
342 if (direction & JNL_WRITE)
343 max_iosize = jnl->max_write_size;
344 else if (direction & JNL_READ)
345 max_iosize = jnl->max_read_size;
346 else
347 max_iosize = 128 * 1024;
348
349 again:
350 bp = alloc_io_buf(jnl->jdev, 1);
351
352 if (*offset + (off_t)curlen > jnl->jhdr->size && *offset != 0 && jnl->jhdr->size != 0) {
353 if (*offset == jnl->jhdr->size) {
354 *offset = jnl->jhdr->jhdr_size;
355 } else {
356 curlen = (off_t)jnl->jhdr->size - *offset;
357 }
358 }
359
360 if (curlen > max_iosize) {
361 curlen = max_iosize;
362 }
363
364 if (curlen <= 0) {
365 panic("jnl: do_jnl_io: curlen == %d, offset 0x%llx len %zd\n", curlen, *offset, len);
366 }
367
368 if (*offset == 0 && (direction & JNL_HEADER) == 0) {
369 panic("jnl: request for i/o to jnl-header without JNL_HEADER flag set! (len %d, data %p)\n", curlen, data);
370 }
371
372 if (direction & JNL_READ)
373 buf_setflags(bp, B_READ);
374 else {
375 /*
376 * don't have to set any flags
377 */
378 vnode_startwrite(jnl->jdev);
379 }
380 buf_setsize(bp, curlen);
381 buf_setcount(bp, curlen);
382 buf_setdataptr(bp, (uintptr_t)data);
383 buf_setblkno(bp, (daddr64_t) ((jnl->jdev_offset + *offset) / (off_t)jnl->jhdr->jhdr_size));
384 buf_setlblkno(bp, (daddr64_t) ((jnl->jdev_offset + *offset) / (off_t)jnl->jhdr->jhdr_size));
385
386 if ((direction & JNL_WRITE) && (jnl->flags & JOURNAL_DO_FUA_WRITES)) {
387 buf_markfua(bp);
388 }
389
390 DTRACE_IO1(journal__start, buf_t, bp);
391 err = VNOP_STRATEGY(bp);
392 if (!err) {
393 err = (int)buf_biowait(bp);
394 }
395 DTRACE_IO1(journal__done, buf_t, bp);
396 free_io_buf(bp);
397
398 if (err) {
399 printf("jnl: %s: do_jnl_io: strategy err 0x%x\n", jnl->jdev_name, err);
400 return 0;
401 }
402
403 *offset += curlen;
404 io_sz += curlen;
405
406 if (io_sz != len) {
407 // handle wrap-around
408 data = (char *)data + curlen;
409 curlen = len - io_sz;
410 if (*offset >= jnl->jhdr->size) {
411 *offset = jnl->jhdr->jhdr_size;
412 }
413 goto again;
414 }
415
416 return io_sz;
417 }
418
419 static size_t
420 read_journal_data(journal *jnl, off_t *offset, void *data, size_t len)
421 {
422 return do_journal_io(jnl, offset, data, len, JNL_READ);
423 }
424
425 static size_t
426 write_journal_data(journal *jnl, off_t *offset, void *data, size_t len)
427 {
428 return do_journal_io(jnl, offset, data, len, JNL_WRITE);
429 }
430
431
432 static size_t
433 read_journal_header(journal *jnl, void *data, size_t len)
434 {
435 off_t hdr_offset = 0;
436
437 return do_journal_io(jnl, &hdr_offset, data, len, JNL_READ|JNL_HEADER);
438 }
439
440 static int
441 write_journal_header(journal *jnl, int updating_start, uint32_t sequence_num)
442 {
443 static int num_err_prints = 0;
444 int ret=0;
445 off_t jhdr_offset = 0;
446 struct vfs_context context;
447
448 context.vc_thread = current_thread();
449 context.vc_ucred = NOCRED;
450 //
451 // Flush the track cache if we're not doing force-unit-access
452 // writes.
453 //
454 if (!updating_start && (jnl->flags & JOURNAL_DO_FUA_WRITES) == 0) {
455 ret = VNOP_IOCTL(jnl->jdev, DKIOCSYNCHRONIZECACHE, NULL, FWRITE, &context);
456 }
457 if (ret != 0) {
458 //
459 // Only print this error if it's a different error than the
460 // previous one, or if it's the first time for this device
461 // or if the total number of printfs is less than 25. We
462 // allow for up to 25 printfs to insure that some make it
463 // into the on-disk syslog. Otherwise if we only printed
464 // one, it's possible it would never make it to the syslog
465 // for the root volume and that makes debugging hard.
466 //
467 if ( ret != jnl->last_flush_err
468 || (jnl->flags & JOURNAL_FLUSHCACHE_ERR) == 0
469 || num_err_prints++ < 25) {
470
471 printf("jnl: %s: flushing fs disk buffer returned 0x%x\n", jnl->jdev_name, ret);
472
473 jnl->flags |= JOURNAL_FLUSHCACHE_ERR;
474 jnl->last_flush_err = ret;
475 }
476 }
477
478 jnl->jhdr->sequence_num = sequence_num;
479 jnl->jhdr->checksum = 0;
480 jnl->jhdr->checksum = calc_checksum((char *)jnl->jhdr, JOURNAL_HEADER_CKSUM_SIZE);
481
482 if (do_journal_io(jnl, &jhdr_offset, jnl->header_buf, jnl->jhdr->jhdr_size, JNL_WRITE|JNL_HEADER) != (size_t)jnl->jhdr->jhdr_size) {
483 printf("jnl: %s: write_journal_header: error writing the journal header!\n", jnl->jdev_name);
484 jnl->flags |= JOURNAL_INVALID;
485 return -1;
486 }
487
488 // If we're not doing force-unit-access writes, then we
489 // have to flush after writing the journal header so that
490 // a future transaction doesn't sneak out to disk before
491 // the header does and thus overwrite data that the old
492 // journal header refers to. Saw this exact case happen
493 // on an IDE bus analyzer with Larry Barras so while it
494 // may seem obscure, it's not.
495 //
496 if (updating_start && (jnl->flags & JOURNAL_DO_FUA_WRITES) == 0) {
497 VNOP_IOCTL(jnl->jdev, DKIOCSYNCHRONIZECACHE, NULL, FWRITE, &context);
498 }
499
500 return 0;
501 }
502
503
504
505 //
506 // this is a work function used to free up transactions that
507 // completed. they can't be free'd from buffer_flushed_callback
508 // because it is called from deep with the disk driver stack
509 // and thus can't do something that would potentially cause
510 // paging. it gets called by each of the journal api entry
511 // points so stuff shouldn't hang around for too long.
512 //
513 static void
514 free_old_stuff(journal *jnl)
515 {
516 transaction *tr, *next;
517 block_list_header *blhdr=NULL, *next_blhdr=NULL;
518
519 if (jnl->tr_freeme == NULL)
520 return;
521
522 lock_oldstart(jnl);
523 tr = jnl->tr_freeme;
524 jnl->tr_freeme = NULL;
525 unlock_oldstart(jnl);
526
527 for(; tr; tr=next) {
528 for (blhdr = tr->blhdr; blhdr; blhdr = next_blhdr) {
529 next_blhdr = (block_list_header *)((long)blhdr->binfo[0].bnum);
530 blhdr->binfo[0].bnum = 0xdeadc0de;
531
532 kmem_free(kernel_map, (vm_offset_t)blhdr, tr->tbuffer_size);
533
534 KERNEL_DEBUG(0xbbbbc01c, jnl, tr, tr->tbuffer_size, 0, 0);
535 }
536 next = tr->next;
537 FREE_ZONE(tr, sizeof(transaction), M_JNL_TR);
538 }
539 }
540
541
542
543 //
544 // This is our callback that lets us know when a buffer has been
545 // flushed to disk. It's called from deep within the driver stack
546 // and thus is quite limited in what it can do. Notably, it can
547 // not initiate any new i/o's or allocate/free memory.
548 //
549 static void
550 buffer_flushed_callback(struct buf *bp, void *arg)
551 {
552 transaction *tr;
553 journal *jnl;
554 transaction *ctr, *prev=NULL, *next;
555 size_t i;
556 int bufsize, amt_flushed, total_bytes;
557
558
559 //printf("jnl: buf flush: bp @ 0x%x l/blkno %qd/%qd vp 0x%x tr @ 0x%x\n",
560 // bp, buf_lblkno(bp), buf_blkno(bp), buf_vnode(bp), arg);
561
562 // snarf out the bits we want
563 bufsize = buf_size(bp);
564 tr = (transaction *)arg;
565
566 // then we've already seen it
567 if (tr == NULL) {
568 return;
569 }
570
571 CHECK_TRANSACTION(tr);
572
573 jnl = tr->jnl;
574 if (jnl->flags & JOURNAL_INVALID) {
575 return;
576 }
577
578 CHECK_JOURNAL(jnl);
579
580 amt_flushed = tr->num_killed;
581 total_bytes = tr->total_bytes;
582
583 // update the number of blocks that have been flushed.
584 // this buf may represent more than one block so take
585 // that into account.
586 //
587 // OSAddAtomic() returns the value of tr->num_flushed before the add
588 //
589 amt_flushed += OSAddAtomic(bufsize, &tr->num_flushed);
590
591
592 // if this transaction isn't done yet, just return as
593 // there is nothing to do.
594 //
595 // NOTE: we are careful to not reference anything through
596 // the tr pointer after doing the OSAddAtomic(). if
597 // this if statement fails then we are the last one
598 // and then it's ok to dereference "tr".
599 //
600 if ((amt_flushed + bufsize) < total_bytes) {
601 return;
602 }
603
604 // this will single thread checking the transaction
605 lock_oldstart(jnl);
606
607 if (tr->total_bytes == (int)0xfbadc0de) {
608 // then someone beat us to it...
609 unlock_oldstart(jnl);
610 return;
611 }
612
613 // mark this so that we're the owner of dealing with the
614 // cleanup for this transaction
615 tr->total_bytes = 0xfbadc0de;
616
617 //printf("jnl: tr 0x%x (0x%llx 0x%llx) in jnl 0x%x completed.\n",
618 // tr, tr->journal_start, tr->journal_end, jnl);
619
620 // find this entry in the old_start[] index and mark it completed
621 for(i = 0; i < sizeof(jnl->old_start)/sizeof(jnl->old_start[0]); i++) {
622
623 if ((off_t)(jnl->old_start[i] & ~(0x8000000000000000ULL)) == tr->journal_start) {
624 jnl->old_start[i] &= ~(0x8000000000000000ULL);
625 break;
626 }
627 }
628
629 if (i >= sizeof(jnl->old_start)/sizeof(jnl->old_start[0])) {
630 panic("jnl: buffer_flushed: did not find tr w/start @ %lld (tr %p, jnl %p)\n",
631 tr->journal_start, tr, jnl);
632 }
633
634
635 // if we are here then we need to update the journal header
636 // to reflect that this transaction is complete
637 if (tr->journal_start == jnl->active_start) {
638 jnl->active_start = tr->journal_end;
639 tr->journal_start = tr->journal_end = (off_t)0;
640 }
641
642 // go through the completed_trs list and try to coalesce
643 // entries, restarting back at the beginning if we have to.
644 for (ctr = jnl->completed_trs; ctr; prev=ctr, ctr=next) {
645 if (ctr->journal_start == jnl->active_start) {
646 jnl->active_start = ctr->journal_end;
647 if (prev) {
648 prev->next = ctr->next;
649 }
650 if (ctr == jnl->completed_trs) {
651 jnl->completed_trs = ctr->next;
652 }
653
654 next = jnl->completed_trs; // this starts us over again
655 ctr->next = jnl->tr_freeme;
656 jnl->tr_freeme = ctr;
657 ctr = NULL;
658 } else if (tr->journal_end == ctr->journal_start) {
659 ctr->journal_start = tr->journal_start;
660 next = jnl->completed_trs; // this starts us over again
661 ctr = NULL;
662 tr->journal_start = tr->journal_end = (off_t)0;
663 } else if (tr->journal_start == ctr->journal_end) {
664 ctr->journal_end = tr->journal_end;
665 next = ctr->next;
666 tr->journal_start = tr->journal_end = (off_t)0;
667 } else if (ctr->next && ctr->journal_end == ctr->next->journal_start) {
668 // coalesce the next entry with this one and link the next
669 // entry in at the head of the tr_freeme list
670 next = ctr->next; // temporarily use the "next" variable
671 ctr->journal_end = next->journal_end;
672 ctr->next = next->next;
673 next->next = jnl->tr_freeme; // link in the next guy at the head of the tr_freeme list
674 jnl->tr_freeme = next;
675
676 next = jnl->completed_trs; // this starts us over again
677 ctr = NULL;
678 } else {
679 next = ctr->next;
680 }
681 }
682
683 // if this is true then we didn't merge with anyone
684 // so link ourselves in at the head of the completed
685 // transaction list.
686 if (tr->journal_start != 0) {
687 // put this entry into the correct sorted place
688 // in the list instead of just at the head.
689 //
690
691 prev = NULL;
692 for (ctr = jnl->completed_trs; ctr && tr->journal_start > ctr->journal_start; prev=ctr, ctr=ctr->next) {
693 // just keep looping
694 }
695
696 if (ctr == NULL && prev == NULL) {
697 jnl->completed_trs = tr;
698 tr->next = NULL;
699 } else if (ctr == jnl->completed_trs) {
700 tr->next = jnl->completed_trs;
701 jnl->completed_trs = tr;
702 } else {
703 tr->next = prev->next;
704 prev->next = tr;
705 }
706 } else {
707 // if we're here this tr got merged with someone else so
708 // put it on the list to be free'd
709 tr->next = jnl->tr_freeme;
710 jnl->tr_freeme = tr;
711 }
712 unlock_oldstart(jnl);
713
714 unlock_condition(jnl, &jnl->asyncIO);
715 }
716
717
718 #include <libkern/OSByteOrder.h>
719
720 #define SWAP16(x) OSSwapInt16(x)
721 #define SWAP32(x) OSSwapInt32(x)
722 #define SWAP64(x) OSSwapInt64(x)
723
724
725 static void
726 swap_journal_header(journal *jnl)
727 {
728 jnl->jhdr->magic = SWAP32(jnl->jhdr->magic);
729 jnl->jhdr->endian = SWAP32(jnl->jhdr->endian);
730 jnl->jhdr->start = SWAP64(jnl->jhdr->start);
731 jnl->jhdr->end = SWAP64(jnl->jhdr->end);
732 jnl->jhdr->size = SWAP64(jnl->jhdr->size);
733 jnl->jhdr->blhdr_size = SWAP32(jnl->jhdr->blhdr_size);
734 jnl->jhdr->checksum = SWAP32(jnl->jhdr->checksum);
735 jnl->jhdr->jhdr_size = SWAP32(jnl->jhdr->jhdr_size);
736 jnl->jhdr->sequence_num = SWAP32(jnl->jhdr->sequence_num);
737 }
738
739 static void
740 swap_block_list_header(journal *jnl, block_list_header *blhdr)
741 {
742 int i;
743
744 blhdr->max_blocks = SWAP16(blhdr->max_blocks);
745 blhdr->num_blocks = SWAP16(blhdr->num_blocks);
746 blhdr->bytes_used = SWAP32(blhdr->bytes_used);
747 blhdr->checksum = SWAP32(blhdr->checksum);
748 blhdr->flags = SWAP32(blhdr->flags);
749
750 if (blhdr->num_blocks >= ((jnl->jhdr->blhdr_size / sizeof(block_info)) - 1)) {
751 printf("jnl: %s: blhdr num blocks looks suspicious (%d / blhdr size %d). not swapping.\n", jnl->jdev_name, blhdr->num_blocks, jnl->jhdr->blhdr_size);
752 return;
753 }
754
755 for(i = 0; i < blhdr->num_blocks; i++) {
756 blhdr->binfo[i].bnum = SWAP64(blhdr->binfo[i].bnum);
757 blhdr->binfo[i].u.bi.bsize = SWAP32(blhdr->binfo[i].u.bi.bsize);
758 blhdr->binfo[i].u.bi.b.cksum = SWAP32(blhdr->binfo[i].u.bi.b.cksum);
759 }
760 }
761
762
763 static int
764 update_fs_block(journal *jnl, void *block_ptr, off_t fs_block, size_t bsize)
765 {
766 int ret;
767 struct buf *oblock_bp=NULL;
768
769 // first read the block we want.
770 ret = buf_meta_bread(jnl->fsdev, (daddr64_t)fs_block, bsize, NOCRED, &oblock_bp);
771 if (ret != 0) {
772 printf("jnl: %s: update_fs_block: error reading fs block # %lld! (ret %d)\n", jnl->jdev_name, fs_block, ret);
773
774 if (oblock_bp) {
775 buf_brelse(oblock_bp);
776 oblock_bp = NULL;
777 }
778
779 // let's try to be aggressive here and just re-write the block
780 oblock_bp = buf_getblk(jnl->fsdev, (daddr64_t)fs_block, bsize, 0, 0, BLK_META);
781 if (oblock_bp == NULL) {
782 printf("jnl: %s: update_fs_block: buf_getblk() for %lld failed! failing update.\n", jnl->jdev_name, fs_block);
783 return -1;
784 }
785 }
786
787 // make sure it's the correct size.
788 if (buf_size(oblock_bp) != bsize) {
789 buf_brelse(oblock_bp);
790 return -1;
791 }
792
793 // copy the journal data over top of it
794 memcpy((char *)buf_dataptr(oblock_bp), block_ptr, bsize);
795
796 if ((ret = VNOP_BWRITE(oblock_bp)) != 0) {
797 printf("jnl: %s: update_fs_block: failed to update block %lld (ret %d)\n", jnl->jdev_name, fs_block,ret);
798 return ret;
799 }
800
801 // and now invalidate it so that if someone else wants to read
802 // it in a different size they'll be able to do it.
803 ret = buf_meta_bread(jnl->fsdev, (daddr64_t)fs_block, bsize, NOCRED, &oblock_bp);
804 if (oblock_bp) {
805 buf_markinvalid(oblock_bp);
806 buf_brelse(oblock_bp);
807 }
808
809 return 0;
810 }
811
812 static int
813 grow_table(struct bucket **buf_ptr, int num_buckets, int new_size)
814 {
815 struct bucket *newBuf;
816 int current_size = num_buckets, i;
817
818 // return if newsize is less than the current size
819 if (new_size < num_buckets) {
820 return current_size;
821 }
822
823 if ((MALLOC(newBuf, struct bucket *, new_size*sizeof(struct bucket), M_TEMP, M_WAITOK)) == NULL) {
824 printf("jnl: grow_table: no memory to expand coalesce buffer!\n");
825 return -1;
826 }
827
828 // printf("jnl: lookup_bucket: expanded co_buf to %d elems\n", new_size);
829
830 // copy existing elements
831 bcopy(*buf_ptr, newBuf, num_buckets*sizeof(struct bucket));
832
833 // initialize the new ones
834 for(i = num_buckets; i < new_size; i++) {
835 newBuf[i].block_num = (off_t)-1;
836 }
837
838 // free the old container
839 FREE(*buf_ptr, M_TEMP);
840
841 // reset the buf_ptr
842 *buf_ptr = newBuf;
843
844 return new_size;
845 }
846
847 static int
848 lookup_bucket(struct bucket **buf_ptr, off_t block_num, int num_full)
849 {
850 int lo, hi, index, matches, i;
851
852 if (num_full == 0) {
853 return 0; // table is empty, so insert at index=0
854 }
855
856 lo = 0;
857 hi = num_full - 1;
858 index = -1;
859
860 // perform binary search for block_num
861 do {
862 int mid = (hi - lo)/2 + lo;
863 off_t this_num = (*buf_ptr)[mid].block_num;
864
865 if (block_num == this_num) {
866 index = mid;
867 break;
868 }
869
870 if (block_num < this_num) {
871 hi = mid;
872 continue;
873 }
874
875 if (block_num > this_num) {
876 lo = mid + 1;
877 continue;
878 }
879 } while (lo < hi);
880
881 // check if lo and hi converged on the match
882 if (block_num == (*buf_ptr)[hi].block_num) {
883 index = hi;
884 }
885
886 // if no existing entry found, find index for new one
887 if (index == -1) {
888 index = (block_num < (*buf_ptr)[hi].block_num) ? hi : hi + 1;
889 } else {
890 // make sure that we return the right-most index in the case of multiple matches
891 matches = 0;
892 i = index + 1;
893 while (i < num_full && block_num == (*buf_ptr)[i].block_num) {
894 matches++;
895 i++;
896 }
897
898 index += matches;
899 }
900
901 return index;
902 }
903
904 static int
905 insert_block(journal *jnl, struct bucket **buf_ptr, int blk_index, off_t num, size_t size, size_t offset, int32_t cksum, int *num_buckets_ptr, int *num_full_ptr, int overwriting)
906 {
907 if (!overwriting) {
908 // grow the table if we're out of space
909 if (*num_full_ptr >= *num_buckets_ptr) {
910 int new_size = *num_buckets_ptr * 2;
911 int grow_size = grow_table(buf_ptr, *num_buckets_ptr, new_size);
912
913 if (grow_size < new_size) {
914 printf("jnl: %s: add_block: grow_table returned an error!\n", jnl->jdev_name);
915 return -1;
916 }
917
918 *num_buckets_ptr = grow_size; //update num_buckets to reflect the new size
919 }
920
921 // if we're not inserting at the end, we need to bcopy
922 if (blk_index != *num_full_ptr) {
923 bcopy( (*buf_ptr)+(blk_index), (*buf_ptr)+(blk_index+1), (*num_full_ptr-blk_index)*sizeof(struct bucket) );
924 }
925
926 (*num_full_ptr)++; // increment only if we're not overwriting
927 }
928
929 // sanity check the values we're about to add
930 if ((off_t)offset >= jnl->jhdr->size) {
931 offset = jnl->jhdr->jhdr_size + (offset - jnl->jhdr->size);
932 }
933 if (size <= 0) {
934 panic("jnl: insert_block: bad size in insert_block (%zd)\n", size);
935 }
936
937 (*buf_ptr)[blk_index].block_num = num;
938 (*buf_ptr)[blk_index].block_size = size;
939 (*buf_ptr)[blk_index].jnl_offset = offset;
940 (*buf_ptr)[blk_index].cksum = cksum;
941
942 return blk_index;
943 }
944
945 static int
946 do_overlap(journal *jnl, struct bucket **buf_ptr, int blk_index, off_t block_num, size_t size, __unused size_t offset, int32_t cksum, int *num_buckets_ptr, int *num_full_ptr)
947 {
948 int num_to_remove, index, i, overwrite, err;
949 size_t jhdr_size = jnl->jhdr->jhdr_size, new_offset;
950 off_t overlap, block_start, block_end;
951
952 block_start = block_num*jhdr_size;
953 block_end = block_start + size;
954 overwrite = (block_num == (*buf_ptr)[blk_index].block_num && size >= (*buf_ptr)[blk_index].block_size);
955
956 // first, eliminate any overlap with the previous entry
957 if (blk_index != 0 && !overwrite) {
958 off_t prev_block_start = (*buf_ptr)[blk_index-1].block_num*jhdr_size;
959 off_t prev_block_end = prev_block_start + (*buf_ptr)[blk_index-1].block_size;
960 overlap = prev_block_end - block_start;
961 if (overlap > 0) {
962 if (overlap % jhdr_size != 0) {
963 panic("jnl: do_overlap: overlap with previous entry not a multiple of %zd\n", jhdr_size);
964 }
965
966 // if the previous entry completely overlaps this one, we need to break it into two pieces.
967 if (prev_block_end > block_end) {
968 off_t new_num = block_end / jhdr_size;
969 size_t new_size = prev_block_end - block_end;
970
971 new_offset = (*buf_ptr)[blk_index-1].jnl_offset + (block_end - prev_block_start);
972
973 err = insert_block(jnl, buf_ptr, blk_index, new_num, new_size, new_offset, cksum, num_buckets_ptr, num_full_ptr, 0);
974 if (err < 0) {
975 panic("jnl: do_overlap: error inserting during pre-overlap\n");
976 }
977 }
978
979 // Regardless, we need to truncate the previous entry to the beginning of the overlap
980 (*buf_ptr)[blk_index-1].block_size = block_start - prev_block_start;
981 (*buf_ptr)[blk_index-1].cksum = 0; // have to blow it away because there's no way to check it
982 }
983 }
984
985 // then, bail out fast if there's no overlap with the entries that follow
986 if (!overwrite && block_end <= (off_t)((*buf_ptr)[blk_index].block_num*jhdr_size)) {
987 return 0; // no overlap, no overwrite
988 } else if (overwrite && (blk_index + 1 >= *num_full_ptr || block_end <= (off_t)((*buf_ptr)[blk_index+1].block_num*jhdr_size))) {
989
990 (*buf_ptr)[blk_index].cksum = cksum; // update this
991 return 1; // simple overwrite
992 }
993
994 // Otherwise, find all cases of total and partial overlap. We use the special
995 // block_num of -2 to designate entries that are completely overlapped and must
996 // be eliminated. The block_num, size, and jnl_offset of partially overlapped
997 // entries must be adjusted to keep the array consistent.
998 index = blk_index;
999 num_to_remove = 0;
1000 while (index < *num_full_ptr && block_end > (off_t)((*buf_ptr)[index].block_num*jhdr_size)) {
1001 if (block_end >= (off_t)(((*buf_ptr)[index].block_num*jhdr_size + (*buf_ptr)[index].block_size))) {
1002 (*buf_ptr)[index].block_num = -2; // mark this for deletion
1003 num_to_remove++;
1004 } else {
1005 overlap = block_end - (*buf_ptr)[index].block_num*jhdr_size;
1006 if (overlap > 0) {
1007 if (overlap % jhdr_size != 0) {
1008 panic("jnl: do_overlap: overlap of %lld is not multiple of %zd\n", overlap, jhdr_size);
1009 }
1010
1011 // if we partially overlap this entry, adjust its block number, jnl offset, and size
1012 (*buf_ptr)[index].block_num += (overlap / jhdr_size); // make sure overlap is multiple of jhdr_size, or round up
1013 (*buf_ptr)[index].cksum = 0;
1014
1015 new_offset = (*buf_ptr)[index].jnl_offset + overlap; // check for wrap-around
1016 if ((off_t)new_offset >= jnl->jhdr->size) {
1017 new_offset = jhdr_size + (new_offset - jnl->jhdr->size);
1018 }
1019 (*buf_ptr)[index].jnl_offset = new_offset;
1020
1021 (*buf_ptr)[index].block_size -= overlap; // sanity check for negative value
1022 if ((*buf_ptr)[index].block_size <= 0) {
1023 panic("jnl: do_overlap: after overlap, new block size is invalid (%u)\n", (*buf_ptr)[index].block_size);
1024 // return -1; // if above panic is removed, return -1 for error
1025 }
1026 }
1027
1028 }
1029
1030 index++;
1031 }
1032
1033 // bcopy over any completely overlapped entries, starting at the right (where the above loop broke out)
1034 index--; // start with the last index used within the above loop
1035 while (index >= blk_index) {
1036 if ((*buf_ptr)[index].block_num == -2) {
1037 if (index == *num_full_ptr-1) {
1038 (*buf_ptr)[index].block_num = -1; // it's the last item in the table... just mark as free
1039 } else {
1040 bcopy( (*buf_ptr)+(index+1), (*buf_ptr)+(index), (*num_full_ptr - (index + 1)) * sizeof(struct bucket) );
1041 }
1042 (*num_full_ptr)--;
1043 }
1044 index--;
1045 }
1046
1047 // eliminate any stale entries at the end of the table
1048 for(i = *num_full_ptr; i < (*num_full_ptr + num_to_remove); i++) {
1049 (*buf_ptr)[i].block_num = -1;
1050 }
1051
1052 return 0; // if we got this far, we need to insert the entry into the table (rather than overwrite)
1053 }
1054
1055 // PR-3105942: Coalesce writes to the same block in journal replay
1056 // We coalesce writes by maintaining a dynamic sorted array of physical disk blocks
1057 // to be replayed and the corresponding location in the journal which contains
1058 // the most recent data for those blocks. The array is "played" once the all the
1059 // blocks in the journal have been coalesced. The code for the case of conflicting/
1060 // overlapping writes to a single block is the most dense. Because coalescing can
1061 // disrupt the existing time-ordering of blocks in the journal playback, care
1062 // is taken to catch any overlaps and keep the array consistent.
1063 static int
1064 add_block(journal *jnl, struct bucket **buf_ptr, off_t block_num, size_t size, __unused size_t offset, int32_t cksum, int *num_buckets_ptr, int *num_full_ptr)
1065 {
1066 int blk_index, overwriting;
1067
1068 // on return from lookup_bucket(), blk_index is the index into the table where block_num should be
1069 // inserted (or the index of the elem to overwrite).
1070 blk_index = lookup_bucket( buf_ptr, block_num, *num_full_ptr);
1071
1072 // check if the index is within bounds (if we're adding this block to the end of
1073 // the table, blk_index will be equal to num_full)
1074 if (blk_index < 0 || blk_index > *num_full_ptr) {
1075 //printf("jnl: add_block: trouble adding block to co_buf\n");
1076 return -1;
1077 } // else printf("jnl: add_block: adding block 0x%llx at i=%d\n", block_num, blk_index);
1078
1079 // Determine whether we're overwriting an existing entry by checking for overlap
1080 overwriting = do_overlap(jnl, buf_ptr, blk_index, block_num, size, offset, cksum, num_buckets_ptr, num_full_ptr);
1081 if (overwriting < 0) {
1082 return -1; // if we got an error, pass it along
1083 }
1084
1085 // returns the index, or -1 on error
1086 blk_index = insert_block(jnl, buf_ptr, blk_index, block_num, size, offset, cksum, num_buckets_ptr, num_full_ptr, overwriting);
1087
1088 return blk_index;
1089 }
1090
1091 static int
1092 replay_journal(journal *jnl)
1093 {
1094 int i, orig_checksum, checksum, check_block_checksums=0, bad_blocks=0;
1095 size_t ret;
1096 size_t max_bsize = 0; /* protected by block_ptr */
1097 block_list_header *blhdr;
1098 off_t offset, txn_start_offset=0, blhdr_offset, orig_jnl_start;
1099 char *buff, *block_ptr=NULL;
1100 struct bucket *co_buf;
1101 int num_buckets = STARTING_BUCKETS, num_full, check_past_jnl_end = 1, in_uncharted_territory=0;
1102 uint32_t last_sequence_num = 0;
1103 int replay_retry_count = 0;
1104
1105 // wrap the start ptr if it points to the very end of the journal
1106 if (jnl->jhdr->start == jnl->jhdr->size) {
1107 jnl->jhdr->start = jnl->jhdr->jhdr_size;
1108 }
1109 if (jnl->jhdr->end == jnl->jhdr->size) {
1110 jnl->jhdr->end = jnl->jhdr->jhdr_size;
1111 }
1112
1113 if (jnl->jhdr->start == jnl->jhdr->end) {
1114 return 0;
1115 }
1116
1117 orig_jnl_start = jnl->jhdr->start;
1118
1119 // allocate memory for the header_block. we'll read each blhdr into this
1120 if (kmem_alloc_kobject(kernel_map, (vm_offset_t *)&buff, jnl->jhdr->blhdr_size)) {
1121 printf("jnl: %s: replay_journal: no memory for block buffer! (%d bytes)\n",
1122 jnl->jdev_name, jnl->jhdr->blhdr_size);
1123 return -1;
1124 }
1125
1126 // allocate memory for the coalesce buffer
1127 if ((MALLOC(co_buf, struct bucket *, num_buckets*sizeof(struct bucket), M_TEMP, M_WAITOK)) == NULL) {
1128 printf("jnl: %s: replay_journal: no memory for coalesce buffer!\n", jnl->jdev_name);
1129 return -1;
1130 }
1131
1132 restart_replay:
1133
1134 // initialize entries
1135 for(i = 0; i < num_buckets; i++) {
1136 co_buf[i].block_num = -1;
1137 }
1138 num_full = 0; // empty at first
1139
1140
1141 printf("jnl: %s: replay_journal: from: %lld to: %lld (joffset 0x%llx)\n",
1142 jnl->jdev_name, jnl->jhdr->start, jnl->jhdr->end, jnl->jdev_offset);
1143
1144 while (check_past_jnl_end || jnl->jhdr->start != jnl->jhdr->end) {
1145 offset = blhdr_offset = jnl->jhdr->start;
1146 ret = read_journal_data(jnl, &offset, buff, jnl->jhdr->blhdr_size);
1147 if (ret != (size_t)jnl->jhdr->blhdr_size) {
1148 printf("jnl: %s: replay_journal: Could not read block list header block @ 0x%llx!\n", jnl->jdev_name, offset);
1149 bad_blocks = 1;
1150 goto bad_txn_handling;
1151 }
1152
1153 blhdr = (block_list_header *)buff;
1154
1155 orig_checksum = blhdr->checksum;
1156 blhdr->checksum = 0;
1157 if (jnl->flags & JOURNAL_NEED_SWAP) {
1158 // calculate the checksum based on the unswapped data
1159 // because it is done byte-at-a-time.
1160 orig_checksum = SWAP32(orig_checksum);
1161 checksum = calc_checksum((char *)blhdr, BLHDR_CHECKSUM_SIZE);
1162 swap_block_list_header(jnl, blhdr);
1163 } else {
1164 checksum = calc_checksum((char *)blhdr, BLHDR_CHECKSUM_SIZE);
1165 }
1166
1167
1168 //
1169 // XXXdbg - if these checks fail, we should replay as much
1170 // we can in the hopes that it will still leave the
1171 // drive in a better state than if we didn't replay
1172 // anything
1173 //
1174 if (checksum != orig_checksum) {
1175 if (check_past_jnl_end && in_uncharted_territory) {
1176
1177 if (blhdr_offset != jnl->jhdr->end) {
1178 printf("jnl: %s: Extra txn replay stopped @ %lld / 0x%llx\n", jnl->jdev_name, blhdr_offset, blhdr_offset);
1179 }
1180
1181 check_past_jnl_end = 0;
1182 jnl->jhdr->end = blhdr_offset;
1183 continue;
1184 }
1185
1186 printf("jnl: %s: replay_journal: bad block list header @ 0x%llx (checksum 0x%x != 0x%x)\n",
1187 jnl->jdev_name, blhdr_offset, orig_checksum, checksum);
1188
1189 if (blhdr_offset == orig_jnl_start) {
1190 // if there's nothing in the journal at all, just bail out altogether.
1191 goto bad_replay;
1192 }
1193
1194 bad_blocks = 1;
1195 goto bad_txn_handling;
1196 }
1197
1198 if ( (last_sequence_num != 0)
1199 && (blhdr->binfo[0].u.bi.b.sequence_num != 0)
1200 && (blhdr->binfo[0].u.bi.b.sequence_num != last_sequence_num)
1201 && (blhdr->binfo[0].u.bi.b.sequence_num != last_sequence_num+1)) {
1202
1203 txn_start_offset = jnl->jhdr->end = blhdr_offset;
1204
1205 if (check_past_jnl_end) {
1206 check_past_jnl_end = 0;
1207 printf("jnl: %s: 2: extra replay stopped @ %lld / 0x%llx (seq %d < %d)\n",
1208 jnl->jdev_name, blhdr_offset, blhdr_offset, blhdr->binfo[0].u.bi.b.sequence_num, last_sequence_num);
1209 continue;
1210 }
1211
1212 printf("jnl: %s: txn sequence numbers out of order in txn @ %lld / %llx! (%d < %d)\n",
1213 jnl->jdev_name, blhdr_offset, blhdr_offset, blhdr->binfo[0].u.bi.b.sequence_num, last_sequence_num);
1214 bad_blocks = 1;
1215 goto bad_txn_handling;
1216 }
1217 last_sequence_num = blhdr->binfo[0].u.bi.b.sequence_num;
1218
1219 if (blhdr_offset >= jnl->jhdr->end && jnl->jhdr->start <= jnl->jhdr->end) {
1220 if (last_sequence_num == 0) {
1221 check_past_jnl_end = 0;
1222 printf("jnl: %s: pre-sequence-num-enabled txn's - can not go further than end (%lld %lld).\n",
1223 jnl->jdev_name, jnl->jhdr->start, jnl->jhdr->end);
1224 if (jnl->jhdr->start != jnl->jhdr->end) {
1225 jnl->jhdr->start = jnl->jhdr->end;
1226 }
1227 continue;
1228 }
1229 printf("jnl: %s: examining extra transactions starting @ %lld / 0x%llx\n", jnl->jdev_name, blhdr_offset, blhdr_offset);
1230 }
1231
1232 if ( blhdr->max_blocks <= 0 || blhdr->max_blocks > (jnl->jhdr->size/jnl->jhdr->jhdr_size)
1233 || blhdr->num_blocks <= 0 || blhdr->num_blocks > blhdr->max_blocks) {
1234 printf("jnl: %s: replay_journal: bad looking journal entry: max: %d num: %d\n",
1235 jnl->jdev_name, blhdr->max_blocks, blhdr->num_blocks);
1236 bad_blocks = 1;
1237 goto bad_txn_handling;
1238 }
1239
1240 max_bsize = 0;
1241 for (i = 1; i < blhdr->num_blocks; i++) {
1242 if (blhdr->binfo[i].bnum < 0 && blhdr->binfo[i].bnum != (off_t)-1) {
1243 printf("jnl: %s: replay_journal: bogus block number 0x%llx\n", jnl->jdev_name, blhdr->binfo[i].bnum);
1244 bad_blocks = 1;
1245 goto bad_txn_handling;
1246 }
1247
1248 if ((size_t)blhdr->binfo[i].u.bi.bsize > max_bsize) {
1249 max_bsize = blhdr->binfo[i].u.bi.bsize;
1250 }
1251 }
1252
1253 if (blhdr->flags & BLHDR_CHECK_CHECKSUMS) {
1254 check_block_checksums = 1;
1255 if (kmem_alloc(kernel_map, (vm_offset_t *)&block_ptr, max_bsize)) {
1256 goto bad_replay;
1257 }
1258 } else {
1259 block_ptr = NULL;
1260 }
1261
1262 if (blhdr->flags & BLHDR_FIRST_HEADER) {
1263 txn_start_offset = blhdr_offset;
1264 }
1265
1266 //printf("jnl: replay_journal: adding %d blocks in journal entry @ 0x%llx to co_buf\n",
1267 // blhdr->num_blocks-1, jnl->jhdr->start);
1268 bad_blocks = 0;
1269 for (i = 1; i < blhdr->num_blocks; i++) {
1270 int size, ret_val;
1271 off_t number;
1272
1273 size = blhdr->binfo[i].u.bi.bsize;
1274 number = blhdr->binfo[i].bnum;
1275
1276 // don't add "killed" blocks
1277 if (number == (off_t)-1) {
1278 //printf("jnl: replay_journal: skipping killed fs block (index %d)\n", i);
1279 } else {
1280
1281 if (check_block_checksums) {
1282 int32_t disk_cksum;
1283 off_t block_offset;
1284
1285 block_offset = offset;
1286
1287 // read the block so we can check the checksum
1288 ret = read_journal_data(jnl, &block_offset, block_ptr, size);
1289 if (ret != (size_t)size) {
1290 printf("jnl: %s: replay_journal: Could not read journal entry data @ offset 0x%llx!\n", jnl->jdev_name, offset);
1291 bad_blocks = 1;
1292 goto bad_txn_handling;
1293 }
1294
1295 disk_cksum = calc_checksum(block_ptr, size);
1296
1297 // there is no need to swap the checksum from disk because
1298 // it got swapped when the blhdr was read in.
1299 if (blhdr->binfo[i].u.bi.b.cksum != 0 && disk_cksum != blhdr->binfo[i].u.bi.b.cksum) {
1300 printf("jnl: %s: txn starting at %lld (%lld) @ index %3d bnum %lld (%d) with disk cksum != blhdr cksum (0x%.8x 0x%.8x)\n",
1301 jnl->jdev_name, txn_start_offset, blhdr_offset, i, number, size, disk_cksum, blhdr->binfo[i].u.bi.b.cksum);
1302 printf("jnl: 0x%.8x 0x%.8x 0x%.8x 0x%.8x 0x%.8x 0x%.8x 0x%.8x 0x%.8x\n",
1303 *(int *)&block_ptr[0*sizeof(int)], *(int *)&block_ptr[1*sizeof(int)], *(int *)&block_ptr[2*sizeof(int)], *(int *)&block_ptr[3*sizeof(int)],
1304 *(int *)&block_ptr[4*sizeof(int)], *(int *)&block_ptr[5*sizeof(int)], *(int *)&block_ptr[6*sizeof(int)], *(int *)&block_ptr[7*sizeof(int)]);
1305
1306 bad_blocks = 1;
1307 goto bad_txn_handling;
1308 }
1309 }
1310
1311
1312 // add this bucket to co_buf, coalescing where possible
1313 // printf("jnl: replay_journal: adding block 0x%llx\n", number);
1314 ret_val = add_block(jnl, &co_buf, number, size, (size_t) offset, blhdr->binfo[i].u.bi.b.cksum, &num_buckets, &num_full);
1315
1316 if (ret_val == -1) {
1317 printf("jnl: %s: replay_journal: trouble adding block to co_buf\n", jnl->jdev_name);
1318 goto bad_replay;
1319 } // else printf("jnl: replay_journal: added block 0x%llx at i=%d\n", number);
1320 }
1321
1322 // increment offset
1323 offset += size;
1324
1325 // check if the last block added puts us off the end of the jnl.
1326 // if so, we need to wrap to the beginning and take any remainder
1327 // into account
1328 //
1329 if (offset >= jnl->jhdr->size) {
1330 offset = jnl->jhdr->jhdr_size + (offset - jnl->jhdr->size);
1331 }
1332 }
1333
1334 if (block_ptr) {
1335 kmem_free(kernel_map, (vm_offset_t)block_ptr, max_bsize);
1336 block_ptr = NULL;
1337 }
1338
1339 bad_txn_handling:
1340 if (bad_blocks) {
1341 /* Journal replay got error before it found any valid
1342 * transations, abort replay */
1343 if (txn_start_offset == 0) {
1344 printf("jnl: %s: no known good txn start offset! aborting journal replay.\n", jnl->jdev_name);
1345 goto bad_replay;
1346 }
1347
1348 /* Repeated error during journal replay, abort replay */
1349 if (replay_retry_count == 3) {
1350 printf("jnl: %s: repeated errors replaying journal! aborting journal replay.\n", jnl->jdev_name);
1351 goto bad_replay;
1352 }
1353 replay_retry_count++;
1354
1355 /* There was an error replaying the journal (possibly
1356 * EIO/ENXIO from the device). So retry replaying all
1357 * the good transactions that we found before getting
1358 * the error.
1359 */
1360 jnl->jhdr->start = orig_jnl_start;
1361 jnl->jhdr->end = txn_start_offset;
1362 check_past_jnl_end = 0;
1363 last_sequence_num = 0;
1364 printf("jnl: %s: restarting journal replay (%lld - %lld)!\n", jnl->jdev_name, jnl->jhdr->start, jnl->jhdr->end);
1365 goto restart_replay;
1366 }
1367
1368 jnl->jhdr->start += blhdr->bytes_used;
1369 if (jnl->jhdr->start >= jnl->jhdr->size) {
1370 // wrap around and skip the journal header block
1371 jnl->jhdr->start = (jnl->jhdr->start % jnl->jhdr->size) + jnl->jhdr->jhdr_size;
1372 }
1373
1374 if (jnl->jhdr->start == jnl->jhdr->end) {
1375 in_uncharted_territory = 1;
1376 }
1377 }
1378
1379 if (jnl->jhdr->start != jnl->jhdr->end) {
1380 printf("jnl: %s: start %lld != end %lld. resetting end.\n", jnl->jdev_name, jnl->jhdr->start, jnl->jhdr->end);
1381 jnl->jhdr->end = jnl->jhdr->start;
1382 }
1383
1384 //printf("jnl: replay_journal: replaying %d blocks\n", num_full);
1385
1386 /*
1387 * make sure it's at least one page in size, so
1388 * start max_bsize at PAGE_SIZE
1389 */
1390 for (i = 0, max_bsize = PAGE_SIZE; i < num_full; i++) {
1391
1392 if (co_buf[i].block_num == (off_t)-1)
1393 continue;
1394
1395 if (co_buf[i].block_size > max_bsize)
1396 max_bsize = co_buf[i].block_size;
1397 }
1398 /*
1399 * round max_bsize up to the nearest PAGE_SIZE multiple
1400 */
1401 if (max_bsize & (PAGE_SIZE - 1)) {
1402 max_bsize = (max_bsize + PAGE_SIZE) & ~(PAGE_SIZE - 1);
1403 }
1404
1405 if (kmem_alloc(kernel_map, (vm_offset_t *)&block_ptr, max_bsize)) {
1406 goto bad_replay;
1407 }
1408
1409 // Replay the coalesced entries in the co-buf
1410 for(i = 0; i < num_full; i++) {
1411 size_t size = co_buf[i].block_size;
1412 off_t jnl_offset = (off_t) co_buf[i].jnl_offset;
1413 off_t number = co_buf[i].block_num;
1414
1415
1416 // printf("replaying co_buf[%d]: block 0x%llx, size 0x%x, jnl_offset 0x%llx\n", i, co_buf[i].block_num,
1417 // co_buf[i].block_size, co_buf[i].jnl_offset);
1418
1419 if (number == (off_t)-1) {
1420 // printf("jnl: replay_journal: skipping killed fs block\n");
1421 } else {
1422
1423 // do journal read, and set the phys. block
1424 ret = read_journal_data(jnl, &jnl_offset, block_ptr, size);
1425 if (ret != size) {
1426 printf("jnl: %s: replay_journal: Could not read journal entry data @ offset 0x%llx!\n", jnl->jdev_name, offset);
1427 goto bad_replay;
1428 }
1429
1430 if (update_fs_block(jnl, block_ptr, number, size) != 0) {
1431 goto bad_replay;
1432 }
1433 }
1434 }
1435
1436
1437 // done replaying; update jnl header
1438 if (write_journal_header(jnl, 1, jnl->jhdr->sequence_num) != 0) {
1439 goto bad_replay;
1440 }
1441
1442 printf("jnl: %s: journal replay done.\n", jnl->jdev_name);
1443
1444 // free block_ptr
1445 if (block_ptr) {
1446 kmem_free(kernel_map, (vm_offset_t)block_ptr, max_bsize);
1447 block_ptr = NULL;
1448 }
1449
1450 // free the coalesce buffer
1451 FREE(co_buf, M_TEMP);
1452 co_buf = NULL;
1453
1454 kmem_free(kernel_map, (vm_offset_t)buff, jnl->jhdr->blhdr_size);
1455 return 0;
1456
1457 bad_replay:
1458 if (block_ptr) {
1459 kmem_free(kernel_map, (vm_offset_t)block_ptr, max_bsize);
1460 }
1461 if (co_buf) {
1462 FREE(co_buf, M_TEMP);
1463 }
1464 kmem_free(kernel_map, (vm_offset_t)buff, jnl->jhdr->blhdr_size);
1465
1466 return -1;
1467 }
1468
1469
1470 #define DEFAULT_TRANSACTION_BUFFER_SIZE (128*1024)
1471 #define MAX_TRANSACTION_BUFFER_SIZE (2048*1024)
1472
1473 // XXXdbg - so I can change it in the debugger
1474 int def_tbuffer_size = 0;
1475
1476
1477 //
1478 // This function sets the size of the tbuffer and the
1479 // size of the blhdr. It assumes that jnl->jhdr->size
1480 // and jnl->jhdr->jhdr_size are already valid.
1481 //
1482 static void
1483 size_up_tbuffer(journal *jnl, int tbuffer_size, int phys_blksz)
1484 {
1485 //
1486 // one-time initialization based on how much memory
1487 // there is in the machine.
1488 //
1489 if (def_tbuffer_size == 0) {
1490 if (mem_size < (256*1024*1024)) {
1491 def_tbuffer_size = DEFAULT_TRANSACTION_BUFFER_SIZE;
1492 } else if (mem_size < (512*1024*1024)) {
1493 def_tbuffer_size = DEFAULT_TRANSACTION_BUFFER_SIZE * 2;
1494 } else if (mem_size < (1024*1024*1024)) {
1495 def_tbuffer_size = DEFAULT_TRANSACTION_BUFFER_SIZE * 3;
1496 } else {
1497 def_tbuffer_size = DEFAULT_TRANSACTION_BUFFER_SIZE * (mem_size / (256*1024*1024));
1498 }
1499 }
1500
1501 // size up the transaction buffer... can't be larger than the number
1502 // of blocks that can fit in a block_list_header block.
1503 if (tbuffer_size == 0) {
1504 jnl->tbuffer_size = def_tbuffer_size;
1505 } else {
1506 // make sure that the specified tbuffer_size isn't too small
1507 if (tbuffer_size < jnl->jhdr->blhdr_size * 2) {
1508 tbuffer_size = jnl->jhdr->blhdr_size * 2;
1509 }
1510 // and make sure it's an even multiple of the block size
1511 if ((tbuffer_size % jnl->jhdr->jhdr_size) != 0) {
1512 tbuffer_size -= (tbuffer_size % jnl->jhdr->jhdr_size);
1513 }
1514
1515 jnl->tbuffer_size = tbuffer_size;
1516 }
1517
1518 if (jnl->tbuffer_size > (jnl->jhdr->size / 2)) {
1519 jnl->tbuffer_size = (jnl->jhdr->size / 2);
1520 }
1521
1522 if (jnl->tbuffer_size > MAX_TRANSACTION_BUFFER_SIZE) {
1523 jnl->tbuffer_size = MAX_TRANSACTION_BUFFER_SIZE;
1524 }
1525
1526 jnl->jhdr->blhdr_size = (jnl->tbuffer_size / jnl->jhdr->jhdr_size) * sizeof(block_info);
1527 if (jnl->jhdr->blhdr_size < phys_blksz) {
1528 jnl->jhdr->blhdr_size = phys_blksz;
1529 } else if ((jnl->jhdr->blhdr_size % phys_blksz) != 0) {
1530 // have to round up so we're an even multiple of the physical block size
1531 jnl->jhdr->blhdr_size = (jnl->jhdr->blhdr_size + (phys_blksz - 1)) & ~(phys_blksz - 1);
1532 }
1533 }
1534
1535
1536
1537 static void
1538 get_io_info(struct vnode *devvp, size_t phys_blksz, journal *jnl, struct vfs_context *context)
1539 {
1540 off_t readblockcnt;
1541 off_t writeblockcnt;
1542 off_t readmaxcnt=0, tmp_readmaxcnt;
1543 off_t writemaxcnt=0, tmp_writemaxcnt;
1544 off_t readsegcnt, writesegcnt;
1545 int32_t features;
1546
1547 if (VNOP_IOCTL(devvp, DKIOCGETFEATURES, (caddr_t)&features, 0, context) == 0) {
1548 if (features & DK_FEATURE_FORCE_UNIT_ACCESS) {
1549 const char *name = vnode_name(devvp);
1550 jnl->flags |= JOURNAL_DO_FUA_WRITES;
1551 printf("jnl: %s: enabling FUA writes (features 0x%x)\n", name ? name : "no-name-dev", features);
1552 }
1553 if (features & DK_FEATURE_UNMAP) {
1554 jnl->flags |= JOURNAL_USE_UNMAP;
1555 }
1556 }
1557
1558 //
1559 // First check the max read size via several different mechanisms...
1560 //
1561 VNOP_IOCTL(devvp, DKIOCGETMAXBYTECOUNTREAD, (caddr_t)&readmaxcnt, 0, context);
1562
1563 if (VNOP_IOCTL(devvp, DKIOCGETMAXBLOCKCOUNTREAD, (caddr_t)&readblockcnt, 0, context) == 0) {
1564 tmp_readmaxcnt = readblockcnt * phys_blksz;
1565 if (readmaxcnt == 0 || (readblockcnt > 0 && tmp_readmaxcnt < readmaxcnt)) {
1566 readmaxcnt = tmp_readmaxcnt;
1567 }
1568 }
1569
1570 if (VNOP_IOCTL(devvp, DKIOCGETMAXSEGMENTCOUNTREAD, (caddr_t)&readsegcnt, 0, context)) {
1571 readsegcnt = 0;
1572 }
1573
1574 if (readsegcnt > 0 && (readsegcnt * PAGE_SIZE) < readmaxcnt) {
1575 readmaxcnt = readsegcnt * PAGE_SIZE;
1576 }
1577
1578 if (readmaxcnt == 0) {
1579 readmaxcnt = 128 * 1024;
1580 } else if (readmaxcnt > UINT32_MAX) {
1581 readmaxcnt = UINT32_MAX;
1582 }
1583
1584
1585 //
1586 // Now check the max writes size via several different mechanisms...
1587 //
1588 VNOP_IOCTL(devvp, DKIOCGETMAXBYTECOUNTWRITE, (caddr_t)&writemaxcnt, 0, context);
1589
1590 if (VNOP_IOCTL(devvp, DKIOCGETMAXBLOCKCOUNTWRITE, (caddr_t)&writeblockcnt, 0, context) == 0) {
1591 tmp_writemaxcnt = writeblockcnt * phys_blksz;
1592 if (writemaxcnt == 0 || (writeblockcnt > 0 && tmp_writemaxcnt < writemaxcnt)) {
1593 writemaxcnt = tmp_writemaxcnt;
1594 }
1595 }
1596
1597 if (VNOP_IOCTL(devvp, DKIOCGETMAXSEGMENTCOUNTWRITE, (caddr_t)&writesegcnt, 0, context)) {
1598 writesegcnt = 0;
1599 }
1600
1601 if (writesegcnt > 0 && (writesegcnt * PAGE_SIZE) < writemaxcnt) {
1602 writemaxcnt = writesegcnt * PAGE_SIZE;
1603 }
1604
1605 if (writemaxcnt == 0) {
1606 writemaxcnt = 128 * 1024;
1607 } else if (writemaxcnt > UINT32_MAX) {
1608 writemaxcnt = UINT32_MAX;
1609 }
1610
1611 jnl->max_read_size = readmaxcnt;
1612 jnl->max_write_size = writemaxcnt;
1613 // printf("jnl: %s: max read/write: %lld k / %lld k\n",
1614 // jnl->jdev_name ? jnl->jdev_name : "unknown",
1615 // jnl->max_read_size/1024, jnl->max_write_size/1024);
1616 }
1617
1618
1619 static const char *
1620 get_jdev_name(struct vnode *jvp)
1621 {
1622 const char *jdev_name;
1623
1624 jdev_name = vnode_name(jvp);
1625 if (jdev_name == NULL) {
1626 jdev_name = vfs_addname("unknown-dev", strlen("unknown-dev"), 0, 0);
1627 } else {
1628 // this just bumps the refcount on the name so we have our own copy
1629 jdev_name = vfs_addname(jdev_name, strlen(jdev_name), 0, 0);
1630 }
1631
1632 return jdev_name;
1633 }
1634
1635
1636 journal *
1637 journal_create(struct vnode *jvp,
1638 off_t offset,
1639 off_t journal_size,
1640 struct vnode *fsvp,
1641 size_t min_fs_blksz,
1642 int32_t flags,
1643 int32_t tbuffer_size,
1644 void (*flush)(void *arg),
1645 void *arg)
1646 {
1647 journal *jnl;
1648 uint32_t phys_blksz, new_txn_base;
1649 u_int32_t min_size;
1650 struct vfs_context context;
1651 const char *jdev_name;
1652 /*
1653 * Cap the journal max size to 2GB. On HFS, it will attempt to occupy
1654 * a full allocation block if the current size is smaller than the allocation
1655 * block on which it resides. Once we hit the exabyte filesystem range, then
1656 * it will use 2GB allocation blocks. As a result, make the cap 2GB.
1657 */
1658 context.vc_thread = current_thread();
1659 context.vc_ucred = FSCRED;
1660
1661 jdev_name = get_jdev_name(jvp);
1662
1663 /* Get the real physical block size. */
1664 if (VNOP_IOCTL(jvp, DKIOCGETBLOCKSIZE, (caddr_t)&phys_blksz, 0, &context)) {
1665 return NULL;
1666 }
1667
1668 if (journal_size < (256*1024) || journal_size > (MAX_JOURNAL_SIZE)) {
1669 printf("jnl: create: journal size %lld looks bogus.\n", journal_size);
1670 return NULL;
1671 }
1672
1673 min_size = phys_blksz * (phys_blksz / sizeof(block_info));
1674 /* Reject journals that are too small given the sector size of the device */
1675 if (journal_size < min_size) {
1676 printf("jnl: create: journal size (%lld) too small given sector size of (%u)\n",
1677 journal_size, phys_blksz);
1678 return NULL;
1679 }
1680
1681 if (phys_blksz > min_fs_blksz) {
1682 printf("jnl: %s: create: error: phys blksize %u bigger than min fs blksize %zd\n",
1683 jdev_name, phys_blksz, min_fs_blksz);
1684 return NULL;
1685 }
1686
1687 if ((journal_size % phys_blksz) != 0) {
1688 printf("jnl: %s: create: journal size 0x%llx is not an even multiple of block size 0x%ux\n",
1689 jdev_name, journal_size, phys_blksz);
1690 return NULL;
1691 }
1692
1693
1694 MALLOC_ZONE(jnl, struct journal *, sizeof(struct journal), M_JNL_JNL, M_WAITOK);
1695 memset(jnl, 0, sizeof(*jnl));
1696
1697 jnl->jdev = jvp;
1698 jnl->jdev_offset = offset;
1699 jnl->fsdev = fsvp;
1700 jnl->flush = flush;
1701 jnl->flush_arg = arg;
1702 jnl->flags = (flags & JOURNAL_OPTION_FLAGS_MASK);
1703 jnl->jdev_name = jdev_name;
1704 lck_mtx_init(&jnl->old_start_lock, jnl_mutex_group, jnl_lock_attr);
1705
1706 get_io_info(jvp, phys_blksz, jnl, &context);
1707
1708 if (kmem_alloc_kobject(kernel_map, (vm_offset_t *)&jnl->header_buf, phys_blksz)) {
1709 printf("jnl: %s: create: could not allocate space for header buffer (%u bytes)\n", jdev_name, phys_blksz);
1710 goto bad_kmem_alloc;
1711 }
1712 jnl->header_buf_size = phys_blksz;
1713
1714 jnl->jhdr = (journal_header *)jnl->header_buf;
1715 memset(jnl->jhdr, 0, sizeof(journal_header));
1716
1717 // we have to set this up here so that do_journal_io() will work
1718 jnl->jhdr->jhdr_size = phys_blksz;
1719
1720 //
1721 // We try and read the journal header to see if there is already one
1722 // out there. If there is, it's possible that it has transactions
1723 // in it that we might replay if we happen to pick a sequence number
1724 // that is a little less than the old one, there is a crash and the
1725 // last txn written ends right at the start of a txn from the previous
1726 // incarnation of this file system. If all that happens we would
1727 // replay the transactions from the old file system and that would
1728 // destroy your disk. Although it is extremely unlikely for all those
1729 // conditions to happen, the probability is non-zero and the result is
1730 // severe - you lose your file system. Therefore if we find a valid
1731 // journal header and the sequence number is non-zero we write junk
1732 // over the entire journal so that there is no way we will encounter
1733 // any old transactions. This is slow but should be a rare event
1734 // since most tools erase the journal.
1735 //
1736 if ( read_journal_header(jnl, jnl->jhdr, phys_blksz) == phys_blksz
1737 && jnl->jhdr->magic == JOURNAL_HEADER_MAGIC
1738 && jnl->jhdr->sequence_num != 0) {
1739
1740 new_txn_base = (jnl->jhdr->sequence_num + (journal_size / phys_blksz) + (random() % 16384)) & 0x00ffffff;
1741 printf("jnl: create: avoiding old sequence number 0x%x (0x%x)\n", jnl->jhdr->sequence_num, new_txn_base);
1742
1743 #if 0
1744 int i;
1745 off_t pos=0;
1746
1747 for(i = 1; i < journal_size / phys_blksz; i++) {
1748 pos = i*phys_blksz;
1749
1750 // we don't really care what data we write just so long
1751 // as it's not a valid transaction header. since we have
1752 // the header_buf sitting around we'll use that.
1753 write_journal_data(jnl, &pos, jnl->header_buf, phys_blksz);
1754 }
1755 printf("jnl: create: done clearing journal (i=%d)\n", i);
1756 #endif
1757 } else {
1758 new_txn_base = random() & 0x00ffffff;
1759 }
1760
1761 memset(jnl->header_buf, 0, phys_blksz);
1762
1763 jnl->jhdr->magic = JOURNAL_HEADER_MAGIC;
1764 jnl->jhdr->endian = ENDIAN_MAGIC;
1765 jnl->jhdr->start = phys_blksz; // start at block #1, block #0 is for the jhdr itself
1766 jnl->jhdr->end = phys_blksz;
1767 jnl->jhdr->size = journal_size;
1768 jnl->jhdr->jhdr_size = phys_blksz;
1769 size_up_tbuffer(jnl, tbuffer_size, phys_blksz);
1770
1771 jnl->active_start = jnl->jhdr->start;
1772
1773 // XXXdbg - for testing you can force the journal to wrap around
1774 // jnl->jhdr->start = jnl->jhdr->size - (phys_blksz*3);
1775 // jnl->jhdr->end = jnl->jhdr->size - (phys_blksz*3);
1776
1777 jnl->jhdr->sequence_num = new_txn_base;
1778
1779 lck_mtx_init(&jnl->jlock, jnl_mutex_group, jnl_lock_attr);
1780 lck_mtx_init(&jnl->flock, jnl_mutex_group, jnl_lock_attr);
1781 lck_rw_init(&jnl->trim_lock, jnl_mutex_group, jnl_lock_attr);
1782
1783
1784 jnl->flushing = FALSE;
1785 jnl->asyncIO = FALSE;
1786 jnl->flush_aborted = FALSE;
1787 jnl->writing_header = FALSE;
1788 jnl->async_trim = NULL;
1789 jnl->sequence_num = jnl->jhdr->sequence_num;
1790
1791 if (write_journal_header(jnl, 1, jnl->jhdr->sequence_num) != 0) {
1792 printf("jnl: %s: journal_create: failed to write journal header.\n", jdev_name);
1793 goto bad_write;
1794 }
1795
1796 return jnl;
1797
1798
1799 bad_write:
1800 kmem_free(kernel_map, (vm_offset_t)jnl->header_buf, phys_blksz);
1801 bad_kmem_alloc:
1802 if (jdev_name) {
1803 vfs_removename(jdev_name);
1804 }
1805 jnl->jhdr = NULL;
1806 FREE_ZONE(jnl, sizeof(struct journal), M_JNL_JNL);
1807
1808 return NULL;
1809 }
1810
1811
1812 journal *
1813 journal_open(struct vnode *jvp,
1814 off_t offset,
1815 off_t journal_size,
1816 struct vnode *fsvp,
1817 size_t min_fs_blksz,
1818 int32_t flags,
1819 int32_t tbuffer_size,
1820 void (*flush)(void *arg),
1821 void *arg)
1822 {
1823 journal *jnl;
1824 uint32_t orig_blksz=0;
1825 uint32_t phys_blksz;
1826 u_int32_t min_size = 0;
1827 int orig_checksum, checksum;
1828 struct vfs_context context;
1829 const char *jdev_name = get_jdev_name(jvp);
1830
1831 context.vc_thread = current_thread();
1832 context.vc_ucred = FSCRED;
1833
1834 /* Get the real physical block size. */
1835 if (VNOP_IOCTL(jvp, DKIOCGETBLOCKSIZE, (caddr_t)&phys_blksz, 0, &context)) {
1836 return NULL;
1837 }
1838
1839 if (phys_blksz > min_fs_blksz) {
1840 printf("jnl: %s: open: error: phys blksize %u bigger than min fs blksize %zd\n",
1841 jdev_name, phys_blksz, min_fs_blksz);
1842 return NULL;
1843 }
1844
1845 if (journal_size < (256*1024) || journal_size > (1024*1024*1024)) {
1846 printf("jnl: open: journal size %lld looks bogus.\n", journal_size);
1847 return NULL;
1848 }
1849
1850 min_size = phys_blksz * (phys_blksz / sizeof(block_info));
1851 /* Reject journals that are too small given the sector size of the device */
1852 if (journal_size < min_size) {
1853 printf("jnl: open: journal size (%lld) too small given sector size of (%u)\n",
1854 journal_size, phys_blksz);
1855 return NULL;
1856 }
1857
1858 if ((journal_size % phys_blksz) != 0) {
1859 printf("jnl: %s: open: journal size 0x%llx is not an even multiple of block size 0x%x\n",
1860 jdev_name, journal_size, phys_blksz);
1861 return NULL;
1862 }
1863
1864 MALLOC_ZONE(jnl, struct journal *, sizeof(struct journal), M_JNL_JNL, M_WAITOK);
1865 memset(jnl, 0, sizeof(*jnl));
1866
1867 jnl->jdev = jvp;
1868 jnl->jdev_offset = offset;
1869 jnl->fsdev = fsvp;
1870 jnl->flush = flush;
1871 jnl->flush_arg = arg;
1872 jnl->flags = (flags & JOURNAL_OPTION_FLAGS_MASK);
1873 jnl->jdev_name = jdev_name;
1874 lck_mtx_init(&jnl->old_start_lock, jnl_mutex_group, jnl_lock_attr);
1875
1876 get_io_info(jvp, phys_blksz, jnl, &context);
1877
1878 if (kmem_alloc_kobject(kernel_map, (vm_offset_t *)&jnl->header_buf, phys_blksz)) {
1879 printf("jnl: %s: create: could not allocate space for header buffer (%u bytes)\n", jdev_name, phys_blksz);
1880 goto bad_kmem_alloc;
1881 }
1882 jnl->header_buf_size = phys_blksz;
1883
1884 jnl->jhdr = (journal_header *)jnl->header_buf;
1885 memset(jnl->jhdr, 0, sizeof(journal_header));
1886
1887 // we have to set this up here so that do_journal_io() will work
1888 jnl->jhdr->jhdr_size = phys_blksz;
1889
1890 if (read_journal_header(jnl, jnl->jhdr, phys_blksz) != phys_blksz) {
1891 printf("jnl: %s: open: could not read %u bytes for the journal header.\n",
1892 jdev_name, phys_blksz);
1893 goto bad_journal;
1894 }
1895
1896 orig_checksum = jnl->jhdr->checksum;
1897 jnl->jhdr->checksum = 0;
1898
1899 if (jnl->jhdr->magic == SWAP32(JOURNAL_HEADER_MAGIC)) {
1900 // do this before the swap since it's done byte-at-a-time
1901 orig_checksum = SWAP32(orig_checksum);
1902 checksum = calc_checksum((char *)jnl->jhdr, JOURNAL_HEADER_CKSUM_SIZE);
1903 swap_journal_header(jnl);
1904 jnl->flags |= JOURNAL_NEED_SWAP;
1905 } else {
1906 checksum = calc_checksum((char *)jnl->jhdr, JOURNAL_HEADER_CKSUM_SIZE);
1907 }
1908
1909 if (jnl->jhdr->magic != JOURNAL_HEADER_MAGIC && jnl->jhdr->magic != OLD_JOURNAL_HEADER_MAGIC) {
1910 printf("jnl: %s: open: journal magic is bad (0x%x != 0x%x)\n",
1911 jnl->jdev_name, jnl->jhdr->magic, JOURNAL_HEADER_MAGIC);
1912 goto bad_journal;
1913 }
1914
1915 // only check if we're the current journal header magic value
1916 if (jnl->jhdr->magic == JOURNAL_HEADER_MAGIC) {
1917
1918 if (orig_checksum != checksum) {
1919 printf("jnl: %s: open: journal checksum is bad (0x%x != 0x%x)\n",
1920 jdev_name, orig_checksum, checksum);
1921
1922 //goto bad_journal;
1923 }
1924 }
1925
1926 // XXXdbg - convert old style magic numbers to the new one
1927 if (jnl->jhdr->magic == OLD_JOURNAL_HEADER_MAGIC) {
1928 jnl->jhdr->magic = JOURNAL_HEADER_MAGIC;
1929 }
1930
1931 if (phys_blksz != (size_t)jnl->jhdr->jhdr_size && jnl->jhdr->jhdr_size != 0) {
1932 /*
1933 * The volume has probably been resized (such that we had to adjust the
1934 * logical sector size), or copied to media with a different logical
1935 * sector size.
1936 *
1937 * Temporarily change the device's logical block size to match the
1938 * journal's header size. This will allow us to replay the journal
1939 * safely. If the replay succeeds, we will update the journal's header
1940 * size (later in this function).
1941 */
1942 orig_blksz = phys_blksz;
1943 phys_blksz = jnl->jhdr->jhdr_size;
1944 VNOP_IOCTL(jvp, DKIOCSETBLOCKSIZE, (caddr_t)&phys_blksz, FWRITE, &context);
1945 printf("jnl: %s: open: temporarily switched block size from %u to %u\n",
1946 jdev_name, orig_blksz, phys_blksz);
1947 }
1948
1949 if ( jnl->jhdr->start <= 0
1950 || jnl->jhdr->start > jnl->jhdr->size
1951 || jnl->jhdr->start > 1024*1024*1024) {
1952 printf("jnl: %s: open: jhdr start looks bad (0x%llx max size 0x%llx)\n",
1953 jdev_name, jnl->jhdr->start, jnl->jhdr->size);
1954 goto bad_journal;
1955 }
1956
1957 if ( jnl->jhdr->end <= 0
1958 || jnl->jhdr->end > jnl->jhdr->size
1959 || jnl->jhdr->end > 1024*1024*1024) {
1960 printf("jnl: %s: open: jhdr end looks bad (0x%llx max size 0x%llx)\n",
1961 jdev_name, jnl->jhdr->end, jnl->jhdr->size);
1962 goto bad_journal;
1963 }
1964
1965 if (jnl->jhdr->size < (256*1024) || jnl->jhdr->size > 1024*1024*1024) {
1966 printf("jnl: %s: open: jhdr size looks bad (0x%llx)\n", jdev_name, jnl->jhdr->size);
1967 goto bad_journal;
1968 }
1969
1970 // XXXdbg - can't do these checks because hfs writes all kinds of
1971 // non-uniform sized blocks even on devices that have a block size
1972 // that is larger than 512 bytes (i.e. optical media w/2k blocks).
1973 // therefore these checks will fail and so we just have to punt and
1974 // do more relaxed checking...
1975 // XXXdbg if ((jnl->jhdr->start % jnl->jhdr->jhdr_size) != 0) {
1976 if ((jnl->jhdr->start % 512) != 0) {
1977 printf("jnl: %s: open: journal start (0x%llx) not a multiple of 512?\n",
1978 jdev_name, jnl->jhdr->start);
1979 goto bad_journal;
1980 }
1981
1982 //XXXdbg if ((jnl->jhdr->end % jnl->jhdr->jhdr_size) != 0) {
1983 if ((jnl->jhdr->end % 512) != 0) {
1984 printf("jnl: %s: open: journal end (0x%llx) not a multiple of block size (0x%x)?\n",
1985 jdev_name, jnl->jhdr->end, jnl->jhdr->jhdr_size);
1986 goto bad_journal;
1987 }
1988
1989 // take care of replaying the journal if necessary
1990 if (flags & JOURNAL_RESET) {
1991 printf("jnl: %s: journal start/end pointers reset! (jnl %p; s 0x%llx e 0x%llx)\n",
1992 jdev_name, jnl, jnl->jhdr->start, jnl->jhdr->end);
1993 jnl->jhdr->start = jnl->jhdr->end;
1994 } else if (replay_journal(jnl) != 0) {
1995 printf("jnl: %s: journal_open: Error replaying the journal!\n", jdev_name);
1996 goto bad_journal;
1997 }
1998
1999 /*
2000 * When we get here, we know that the journal is empty (jnl->jhdr->start ==
2001 * jnl->jhdr->end). If the device's logical block size was different from
2002 * the journal's header size, then we can now restore the device's logical
2003 * block size and update the journal's header size to match.
2004 *
2005 * Note that we also adjust the journal's start and end so that they will
2006 * be aligned on the new block size. We pick a new sequence number to
2007 * avoid any problems if a replay found previous transactions using the old
2008 * journal header size. (See the comments in journal_create(), above.)
2009 */
2010
2011 if (orig_blksz != 0) {
2012 VNOP_IOCTL(jvp, DKIOCSETBLOCKSIZE, (caddr_t)&orig_blksz, FWRITE, &context);
2013 phys_blksz = orig_blksz;
2014
2015 orig_blksz = 0;
2016
2017 jnl->jhdr->jhdr_size = phys_blksz;
2018 jnl->jhdr->start = phys_blksz;
2019 jnl->jhdr->end = phys_blksz;
2020 jnl->jhdr->sequence_num = (jnl->jhdr->sequence_num +
2021 (journal_size / phys_blksz) +
2022 (random() % 16384)) & 0x00ffffff;
2023
2024 if (write_journal_header(jnl, 1, jnl->jhdr->sequence_num)) {
2025 printf("jnl: %s: open: failed to update journal header size\n", jdev_name);
2026 goto bad_journal;
2027 }
2028 }
2029
2030 // make sure this is in sync!
2031 jnl->active_start = jnl->jhdr->start;
2032 jnl->sequence_num = jnl->jhdr->sequence_num;
2033
2034 // set this now, after we've replayed the journal
2035 size_up_tbuffer(jnl, tbuffer_size, phys_blksz);
2036
2037 // TODO: Does this need to change if the device's logical block size changed?
2038 if ((off_t)(jnl->jhdr->blhdr_size/sizeof(block_info)-1) > (jnl->jhdr->size/jnl->jhdr->jhdr_size)) {
2039 printf("jnl: %s: open: jhdr size and blhdr size are not compatible (0x%llx, %d, %d)\n", jdev_name, jnl->jhdr->size,
2040 jnl->jhdr->blhdr_size, jnl->jhdr->jhdr_size);
2041 goto bad_journal;
2042 }
2043
2044 lck_mtx_init(&jnl->jlock, jnl_mutex_group, jnl_lock_attr);
2045 lck_mtx_init(&jnl->flock, jnl_mutex_group, jnl_lock_attr);
2046 lck_rw_init(&jnl->trim_lock, jnl_mutex_group, jnl_lock_attr);
2047
2048 return jnl;
2049
2050 bad_journal:
2051 if (orig_blksz != 0) {
2052 phys_blksz = orig_blksz;
2053 VNOP_IOCTL(jvp, DKIOCSETBLOCKSIZE, (caddr_t)&orig_blksz, FWRITE, &context);
2054 printf("jnl: %s: open: restored block size after error\n", jdev_name);
2055 }
2056 kmem_free(kernel_map, (vm_offset_t)jnl->header_buf, phys_blksz);
2057 bad_kmem_alloc:
2058 if (jdev_name) {
2059 vfs_removename(jdev_name);
2060 }
2061 FREE_ZONE(jnl, sizeof(struct journal), M_JNL_JNL);
2062 return NULL;
2063 }
2064
2065
2066 int
2067 journal_is_clean(struct vnode *jvp,
2068 off_t offset,
2069 off_t journal_size,
2070 struct vnode *fsvp,
2071 size_t min_fs_block_size)
2072 {
2073 journal jnl;
2074 uint32_t phys_blksz;
2075 int ret;
2076 int orig_checksum, checksum;
2077 struct vfs_context context;
2078 const char *jdev_name = get_jdev_name(jvp);
2079
2080 context.vc_thread = current_thread();
2081 context.vc_ucred = FSCRED;
2082
2083 /* Get the real physical block size. */
2084 if (VNOP_IOCTL(jvp, DKIOCGETBLOCKSIZE, (caddr_t)&phys_blksz, 0, &context)) {
2085 printf("jnl: %s: is_clean: failed to get device block size.\n", jdev_name);
2086 return EINVAL;
2087 }
2088
2089 if (phys_blksz > (uint32_t)min_fs_block_size) {
2090 printf("jnl: %s: is_clean: error: phys blksize %d bigger than min fs blksize %zd\n",
2091 jdev_name, phys_blksz, min_fs_block_size);
2092 return EINVAL;
2093 }
2094
2095 if (journal_size < (256*1024) || journal_size > (MAX_JOURNAL_SIZE)) {
2096 printf("jnl: is_clean: journal size %lld looks bogus.\n", journal_size);
2097 return EINVAL;
2098 }
2099
2100 if ((journal_size % phys_blksz) != 0) {
2101 printf("jnl: %s: is_clean: journal size 0x%llx is not an even multiple of block size 0x%x\n",
2102 jdev_name, journal_size, phys_blksz);
2103 return EINVAL;
2104 }
2105
2106 memset(&jnl, 0, sizeof(jnl));
2107
2108 if (kmem_alloc_kobject(kernel_map, (vm_offset_t *)&jnl.header_buf, phys_blksz)) {
2109 printf("jnl: %s: is_clean: could not allocate space for header buffer (%d bytes)\n", jdev_name, phys_blksz);
2110 return ENOMEM;
2111 }
2112 jnl.header_buf_size = phys_blksz;
2113
2114 get_io_info(jvp, phys_blksz, &jnl, &context);
2115
2116 jnl.jhdr = (journal_header *)jnl.header_buf;
2117 memset(jnl.jhdr, 0, sizeof(journal_header));
2118
2119 jnl.jdev = jvp;
2120 jnl.jdev_offset = offset;
2121 jnl.fsdev = fsvp;
2122
2123 // we have to set this up here so that do_journal_io() will work
2124 jnl.jhdr->jhdr_size = phys_blksz;
2125
2126 if (read_journal_header(&jnl, jnl.jhdr, phys_blksz) != (unsigned)phys_blksz) {
2127 printf("jnl: %s: is_clean: could not read %d bytes for the journal header.\n",
2128 jdev_name, phys_blksz);
2129 ret = EINVAL;
2130 goto get_out;
2131 }
2132
2133 orig_checksum = jnl.jhdr->checksum;
2134 jnl.jhdr->checksum = 0;
2135
2136 if (jnl.jhdr->magic == SWAP32(JOURNAL_HEADER_MAGIC)) {
2137 // do this before the swap since it's done byte-at-a-time
2138 orig_checksum = SWAP32(orig_checksum);
2139 checksum = calc_checksum((char *)jnl.jhdr, JOURNAL_HEADER_CKSUM_SIZE);
2140 swap_journal_header(&jnl);
2141 jnl.flags |= JOURNAL_NEED_SWAP;
2142 } else {
2143 checksum = calc_checksum((char *)jnl.jhdr, JOURNAL_HEADER_CKSUM_SIZE);
2144 }
2145
2146 if (jnl.jhdr->magic != JOURNAL_HEADER_MAGIC && jnl.jhdr->magic != OLD_JOURNAL_HEADER_MAGIC) {
2147 printf("jnl: %s: is_clean: journal magic is bad (0x%x != 0x%x)\n",
2148 jdev_name, jnl.jhdr->magic, JOURNAL_HEADER_MAGIC);
2149 ret = EINVAL;
2150 goto get_out;
2151 }
2152
2153 if (orig_checksum != checksum) {
2154 printf("jnl: %s: is_clean: journal checksum is bad (0x%x != 0x%x)\n", jdev_name, orig_checksum, checksum);
2155 ret = EINVAL;
2156 goto get_out;
2157 }
2158
2159 //
2160 // if the start and end are equal then the journal is clean.
2161 // otherwise it's not clean and therefore an error.
2162 //
2163 if (jnl.jhdr->start == jnl.jhdr->end) {
2164 ret = 0;
2165 } else {
2166 ret = EBUSY; // so the caller can differentiate an invalid journal from a "busy" one
2167 }
2168
2169 get_out:
2170 kmem_free(kernel_map, (vm_offset_t)jnl.header_buf, phys_blksz);
2171 if (jdev_name) {
2172 vfs_removename(jdev_name);
2173 }
2174
2175 return ret;
2176
2177 }
2178
2179
2180 void
2181 journal_close(journal *jnl)
2182 {
2183 volatile off_t *start, *end;
2184 int counter=0;
2185
2186 CHECK_JOURNAL(jnl);
2187
2188 // set this before doing anything that would block so that
2189 // we start tearing things down properly.
2190 //
2191 jnl->flags |= JOURNAL_CLOSE_PENDING;
2192
2193 if (jnl->owner != current_thread()) {
2194 lock_journal(jnl);
2195 }
2196
2197 wait_condition(jnl, &jnl->flushing, "journal_close");
2198
2199 //
2200 // only write stuff to disk if the journal is still valid
2201 //
2202 if ((jnl->flags & JOURNAL_INVALID) == 0) {
2203
2204 if (jnl->active_tr) {
2205 /*
2206 * "journal_end_transaction" will fire the flush asynchronously
2207 */
2208 journal_end_transaction(jnl);
2209 }
2210
2211 // flush any buffered transactions
2212 if (jnl->cur_tr) {
2213 transaction *tr = jnl->cur_tr;
2214
2215 jnl->cur_tr = NULL;
2216 /*
2217 * "end_transaction" will wait for any in-progress flush to complete
2218 * before flushing "cur_tr" synchronously("must_wait" == TRUE)
2219 */
2220 end_transaction(tr, 1, NULL, NULL, FALSE, TRUE);
2221 }
2222 /*
2223 * if there was an "active_tr", make sure we wait for
2224 * it to flush if there was no "cur_tr" to process
2225 */
2226 wait_condition(jnl, &jnl->flushing, "journal_close");
2227
2228 //start = &jnl->jhdr->start;
2229 start = &jnl->active_start;
2230 end = &jnl->jhdr->end;
2231
2232 while (*start != *end && counter++ < 5000) {
2233 //printf("jnl: close: flushing the buffer cache (start 0x%llx end 0x%llx)\n", *start, *end);
2234 if (jnl->flush) {
2235 jnl->flush(jnl->flush_arg);
2236 }
2237 tsleep((caddr_t)jnl, PRIBIO, "jnl_close", 2);
2238 }
2239
2240 if (*start != *end) {
2241 printf("jnl: %s: close: buffer flushing didn't seem to flush out all the transactions! (0x%llx - 0x%llx)\n",
2242 jnl->jdev_name, *start, *end);
2243 }
2244
2245 // make sure this is in sync when we close the journal
2246 jnl->jhdr->start = jnl->active_start;
2247
2248 // if this fails there's not much we can do at this point...
2249 write_journal_header(jnl, 1, jnl->sequence_num);
2250 } else {
2251 // if we're here the journal isn't valid any more.
2252 // so make sure we don't leave any locked blocks lying around
2253 printf("jnl: %s: close: journal %p, is invalid. aborting outstanding transactions\n", jnl->jdev_name, jnl);
2254
2255 if (jnl->active_tr || jnl->cur_tr) {
2256 transaction *tr;
2257
2258 if (jnl->active_tr) {
2259 tr = jnl->active_tr;
2260 jnl->active_tr = NULL;
2261 } else {
2262 tr = jnl->cur_tr;
2263 jnl->cur_tr = NULL;
2264 }
2265 abort_transaction(jnl, tr);
2266
2267 if (jnl->active_tr || jnl->cur_tr) {
2268 panic("jnl: %s: close: jnl @ %p had both an active and cur tr\n", jnl->jdev_name, jnl);
2269 }
2270 }
2271 }
2272
2273 free_old_stuff(jnl);
2274
2275 kmem_free(kernel_map, (vm_offset_t)jnl->header_buf, jnl->header_buf_size);
2276 jnl->jhdr = (void *)0xbeefbabe;
2277
2278 if (jnl->jdev_name) {
2279 vfs_removename(jnl->jdev_name);
2280 }
2281
2282 FREE_ZONE(jnl, sizeof(struct journal), M_JNL_JNL);
2283 }
2284
2285 static void
2286 dump_journal(journal *jnl)
2287 {
2288 transaction *ctr;
2289
2290 printf("journal for dev %s:", jnl->jdev_name);
2291 printf(" jdev_offset %.8llx\n", jnl->jdev_offset);
2292 printf(" magic: 0x%.8x\n", jnl->jhdr->magic);
2293 printf(" start: 0x%.8llx\n", jnl->jhdr->start);
2294 printf(" end: 0x%.8llx\n", jnl->jhdr->end);
2295 printf(" size: 0x%.8llx\n", jnl->jhdr->size);
2296 printf(" blhdr size: %d\n", jnl->jhdr->blhdr_size);
2297 printf(" jhdr size: %d\n", jnl->jhdr->jhdr_size);
2298 printf(" chksum: 0x%.8x\n", jnl->jhdr->checksum);
2299
2300 printf(" completed transactions:\n");
2301 for (ctr = jnl->completed_trs; ctr; ctr = ctr->next) {
2302 printf(" 0x%.8llx - 0x%.8llx\n", ctr->journal_start, ctr->journal_end);
2303 }
2304 }
2305
2306
2307
2308 static off_t
2309 free_space(journal *jnl)
2310 {
2311 off_t free_space_offset;
2312
2313 if (jnl->jhdr->start < jnl->jhdr->end) {
2314 free_space_offset = jnl->jhdr->size - (jnl->jhdr->end - jnl->jhdr->start) - jnl->jhdr->jhdr_size;
2315 } else if (jnl->jhdr->start > jnl->jhdr->end) {
2316 free_space_offset = jnl->jhdr->start - jnl->jhdr->end;
2317 } else {
2318 // journal is completely empty
2319 free_space_offset = jnl->jhdr->size - jnl->jhdr->jhdr_size;
2320 }
2321
2322 return free_space_offset;
2323 }
2324
2325
2326 //
2327 // The journal must be locked on entry to this function.
2328 // The "desired_size" is in bytes.
2329 //
2330 static int
2331 check_free_space(journal *jnl, int desired_size, boolean_t *delayed_header_write, uint32_t sequence_num)
2332 {
2333 size_t i;
2334 int counter=0;
2335
2336 //printf("jnl: check free space (desired 0x%x, avail 0x%Lx)\n",
2337 // desired_size, free_space(jnl));
2338
2339 if (delayed_header_write)
2340 *delayed_header_write = FALSE;
2341
2342 while (1) {
2343 int old_start_empty;
2344
2345 // make sure there's space in the journal to hold this transaction
2346 if (free_space(jnl) > desired_size && jnl->old_start[0] == 0) {
2347 break;
2348 }
2349 if (counter++ == 5000) {
2350 dump_journal(jnl);
2351 panic("jnl: check_free_space: buffer flushing isn't working "
2352 "(jnl @ %p s %lld e %lld f %lld [active start %lld]).\n", jnl,
2353 jnl->jhdr->start, jnl->jhdr->end, free_space(jnl), jnl->active_start);
2354 }
2355 if (counter > 7500) {
2356 printf("jnl: %s: check_free_space: giving up waiting for free space.\n", jnl->jdev_name);
2357 return ENOSPC;
2358 }
2359
2360 //
2361 // here's where we lazily bump up jnl->jhdr->start. we'll consume
2362 // entries until there is enough space for the next transaction.
2363 //
2364 old_start_empty = 1;
2365 lock_oldstart(jnl);
2366
2367 for (i = 0; i < sizeof(jnl->old_start)/sizeof(jnl->old_start[0]); i++) {
2368 int lcl_counter;
2369
2370 lcl_counter = 0;
2371 while (jnl->old_start[i] & 0x8000000000000000LL) {
2372 if (lcl_counter++ > 10000) {
2373 panic("jnl: check_free_space: tr starting @ 0x%llx not flushing (jnl %p).\n",
2374 jnl->old_start[i], jnl);
2375 }
2376
2377 unlock_oldstart(jnl);
2378 if (jnl->flush) {
2379 jnl->flush(jnl->flush_arg);
2380 }
2381 tsleep((caddr_t)jnl, PRIBIO, "check_free_space1", 1);
2382 lock_oldstart(jnl);
2383 }
2384
2385 if (jnl->old_start[i] == 0) {
2386 continue;
2387 }
2388
2389 old_start_empty = 0;
2390 jnl->jhdr->start = jnl->old_start[i];
2391 jnl->old_start[i] = 0;
2392
2393 if (free_space(jnl) > desired_size) {
2394
2395 if (delayed_header_write)
2396 *delayed_header_write = TRUE;
2397 else {
2398 unlock_oldstart(jnl);
2399 write_journal_header(jnl, 1, sequence_num);
2400 lock_oldstart(jnl);
2401 }
2402 break;
2403 }
2404 }
2405 unlock_oldstart(jnl);
2406
2407 // if we bumped the start, loop and try again
2408 if (i < sizeof(jnl->old_start)/sizeof(jnl->old_start[0])) {
2409 continue;
2410 } else if (old_start_empty) {
2411 //
2412 // if there is nothing in old_start anymore then we can
2413 // bump the jhdr->start to be the same as active_start
2414 // since it is possible there was only one very large
2415 // transaction in the old_start array. if we didn't do
2416 // this then jhdr->start would never get updated and we
2417 // would wind up looping until we hit the panic at the
2418 // start of the loop.
2419 //
2420 jnl->jhdr->start = jnl->active_start;
2421
2422 if (delayed_header_write)
2423 *delayed_header_write = TRUE;
2424 else
2425 write_journal_header(jnl, 1, sequence_num);
2426 continue;
2427 }
2428
2429
2430 // if the file system gave us a flush function, call it to so that
2431 // it can flush some blocks which hopefully will cause some transactions
2432 // to complete and thus free up space in the journal.
2433 if (jnl->flush) {
2434 jnl->flush(jnl->flush_arg);
2435 }
2436
2437 // wait for a while to avoid being cpu-bound (this will
2438 // put us to sleep for 10 milliseconds)
2439 tsleep((caddr_t)jnl, PRIBIO, "check_free_space2", 1);
2440 }
2441
2442 return 0;
2443 }
2444
2445 /*
2446 * Allocate a new active transaction.
2447 */
2448 static errno_t
2449 journal_allocate_transaction(journal *jnl)
2450 {
2451 transaction *tr;
2452
2453 MALLOC_ZONE(tr, transaction *, sizeof(transaction), M_JNL_TR, M_WAITOK);
2454 memset(tr, 0, sizeof(transaction));
2455
2456 tr->tbuffer_size = jnl->tbuffer_size;
2457
2458 if (kmem_alloc_kobject(kernel_map, (vm_offset_t *)&tr->tbuffer, tr->tbuffer_size)) {
2459 FREE_ZONE(tr, sizeof(transaction), M_JNL_TR);
2460 jnl->active_tr = NULL;
2461 return ENOMEM;
2462 }
2463
2464 // journal replay code checksum check depends on this.
2465 memset(tr->tbuffer, 0, BLHDR_CHECKSUM_SIZE);
2466 // Fill up the rest of the block with unimportant bytes (0x5a 'Z' chosen for visibility)
2467 memset(tr->tbuffer + BLHDR_CHECKSUM_SIZE, 0x5a, jnl->jhdr->blhdr_size - BLHDR_CHECKSUM_SIZE);
2468
2469 tr->blhdr = (block_list_header *)tr->tbuffer;
2470 tr->blhdr->max_blocks = (jnl->jhdr->blhdr_size / sizeof(block_info)) - 1;
2471 tr->blhdr->num_blocks = 1; // accounts for this header block
2472 tr->blhdr->bytes_used = jnl->jhdr->blhdr_size;
2473 tr->blhdr->flags = BLHDR_CHECK_CHECKSUMS | BLHDR_FIRST_HEADER;
2474
2475 tr->sequence_num = ++jnl->sequence_num;
2476 tr->num_blhdrs = 1;
2477 tr->total_bytes = jnl->jhdr->blhdr_size;
2478 tr->jnl = jnl;
2479
2480 jnl->active_tr = tr;
2481
2482 return 0;
2483 }
2484
2485 int
2486 journal_start_transaction(journal *jnl)
2487 {
2488 int ret;
2489
2490 CHECK_JOURNAL(jnl);
2491
2492 free_old_stuff(jnl);
2493
2494 if (jnl->flags & JOURNAL_INVALID) {
2495 return EINVAL;
2496 }
2497 if (jnl->owner == current_thread()) {
2498 if (jnl->active_tr == NULL) {
2499 panic("jnl: start_tr: active_tr is NULL (jnl @ %p, owner %p, current_thread %p\n",
2500 jnl, jnl->owner, current_thread());
2501 }
2502 jnl->nested_count++;
2503 return 0;
2504 }
2505 lock_journal(jnl);
2506
2507 if (jnl->owner != NULL || jnl->nested_count != 0 || jnl->active_tr != NULL) {
2508 panic("jnl: start_tr: owner %p, nested count %d, active_tr %p jnl @ %p\n",
2509 jnl->owner, jnl->nested_count, jnl->active_tr, jnl);
2510 }
2511
2512 jnl->owner = current_thread();
2513 jnl->nested_count = 1;
2514
2515 #if JOE
2516 // make sure there's room in the journal
2517 if (free_space(jnl) < jnl->tbuffer_size) {
2518
2519 KERNEL_DEBUG(0xbbbbc030 | DBG_FUNC_START, jnl, 0, 0, 0, 0);
2520
2521 // this is the call that really waits for space to free up
2522 // as well as updating jnl->jhdr->start
2523 if (check_free_space(jnl, jnl->tbuffer_size, NULL, jnl->sequence_num) != 0) {
2524 printf("jnl: %s: start transaction failed: no space\n", jnl->jdev_name);
2525 ret = ENOSPC;
2526 goto bad_start;
2527 }
2528 KERNEL_DEBUG(0xbbbbc030 | DBG_FUNC_END, jnl, 0, 0, 0, 0);
2529 }
2530 #endif
2531
2532 // if there's a buffered transaction, use it.
2533 if (jnl->cur_tr) {
2534 jnl->active_tr = jnl->cur_tr;
2535 jnl->cur_tr = NULL;
2536
2537 return 0;
2538 }
2539
2540 ret = journal_allocate_transaction(jnl);
2541 if (ret) {
2542 goto bad_start;
2543 }
2544
2545 // printf("jnl: start_tr: owner 0x%x new tr @ 0x%x\n", jnl->owner, jnl->active_tr);
2546
2547 return 0;
2548
2549 bad_start:
2550 jnl->owner = NULL;
2551 jnl->nested_count = 0;
2552 unlock_journal(jnl);
2553
2554 return ret;
2555 }
2556
2557
2558 int
2559 journal_modify_block_start(journal *jnl, struct buf *bp)
2560 {
2561 transaction *tr;
2562
2563 CHECK_JOURNAL(jnl);
2564
2565
2566 free_old_stuff(jnl);
2567
2568 if (jnl->flags & JOURNAL_INVALID) {
2569 return EINVAL;
2570 }
2571
2572 // XXXdbg - for debugging I want this to be true. later it may
2573 // not be necessary.
2574 if ((buf_flags(bp) & B_META) == 0) {
2575 panic("jnl: modify_block_start: bp @ %p is not a meta-data block! (jnl %p)\n", bp, jnl);
2576 }
2577
2578 tr = jnl->active_tr;
2579 CHECK_TRANSACTION(tr);
2580
2581 if (jnl->owner != current_thread()) {
2582 panic("jnl: modify_block_start: called w/out a transaction! jnl %p, owner %p, curact %p\n",
2583 jnl, jnl->owner, current_thread());
2584 }
2585
2586 //printf("jnl: mod block start (bp 0x%x vp 0x%x l/blkno %qd/%qd bsz %d; total bytes %d)\n",
2587 // bp, buf_vnode(bp), buf_lblkno(bp), buf_blkno(bp), buf_size(bp), tr->total_bytes);
2588
2589 // can't allow blocks that aren't an even multiple of the
2590 // underlying block size.
2591 if ((buf_size(bp) % jnl->jhdr->jhdr_size) != 0) {
2592 uint32_t phys_blksz, bad=0;
2593
2594 if (VNOP_IOCTL(jnl->jdev, DKIOCGETBLOCKSIZE, (caddr_t)&phys_blksz, 0, vfs_context_kernel())) {
2595 bad = 1;
2596 } else if (phys_blksz != (uint32_t)jnl->jhdr->jhdr_size) {
2597 if (phys_blksz < 512) {
2598 panic("jnl: mod block start: phys blksz %d is too small (%d, %d)\n",
2599 phys_blksz, buf_size(bp), jnl->jhdr->jhdr_size);
2600 }
2601
2602 if ((buf_size(bp) % phys_blksz) != 0) {
2603 bad = 1;
2604 } else if (phys_blksz < (uint32_t)jnl->jhdr->jhdr_size) {
2605 jnl->jhdr->jhdr_size = phys_blksz;
2606 } else {
2607 // the phys_blksz is now larger... need to realloc the jhdr
2608 char *new_header_buf;
2609
2610 printf("jnl: %s: phys blksz got bigger (was: %d/%d now %d)\n",
2611 jnl->jdev_name, jnl->header_buf_size, jnl->jhdr->jhdr_size, phys_blksz);
2612 if (kmem_alloc_kobject(kernel_map, (vm_offset_t *)&new_header_buf, phys_blksz)) {
2613 printf("jnl: modify_block_start: %s: create: phys blksz change (was %d, now %d) but could not allocate space for new header\n",
2614 jnl->jdev_name, jnl->jhdr->jhdr_size, phys_blksz);
2615 bad = 1;
2616 } else {
2617 memcpy(new_header_buf, jnl->header_buf, jnl->header_buf_size);
2618 memset(&new_header_buf[jnl->header_buf_size], 0x18, (phys_blksz - jnl->header_buf_size));
2619 kmem_free(kernel_map, (vm_offset_t)jnl->header_buf, jnl->header_buf_size);
2620 jnl->header_buf = new_header_buf;
2621 jnl->header_buf_size = phys_blksz;
2622
2623 jnl->jhdr = (journal_header *)jnl->header_buf;
2624 jnl->jhdr->jhdr_size = phys_blksz;
2625 }
2626 }
2627 } else {
2628 bad = 1;
2629 }
2630
2631 if (bad) {
2632 panic("jnl: mod block start: bufsize %d not a multiple of block size %d\n",
2633 buf_size(bp), jnl->jhdr->jhdr_size);
2634 return -1;
2635 }
2636 }
2637
2638 // make sure that this transaction isn't bigger than the whole journal
2639 if (tr->total_bytes+buf_size(bp) >= (jnl->jhdr->size - jnl->jhdr->jhdr_size)) {
2640 panic("jnl: transaction too big (%d >= %lld bytes, bufsize %d, tr %p bp %p)\n",
2641 tr->total_bytes, (tr->jnl->jhdr->size - jnl->jhdr->jhdr_size), buf_size(bp), tr, bp);
2642 return -1;
2643 }
2644
2645 // if the block is dirty and not already locked we have to write
2646 // it out before we muck with it because it has data that belongs
2647 // (presumably) to another transaction.
2648 //
2649 if ((buf_flags(bp) & (B_DELWRI | B_LOCKED)) == B_DELWRI) {
2650
2651 if (buf_flags(bp) & B_ASYNC) {
2652 panic("modify_block_start: bp @ %p has async flag set!\n", bp);
2653 }
2654 if (bp->b_shadow_ref)
2655 panic("modify_block_start: dirty bp @ %p has shadows!\n", bp);
2656
2657 // this will cause it to not be buf_brelse()'d
2658 buf_setflags(bp, B_NORELSE);
2659 VNOP_BWRITE(bp);
2660 }
2661 buf_setflags(bp, B_LOCKED);
2662
2663 return 0;
2664 }
2665
2666 int
2667 journal_modify_block_abort(journal *jnl, struct buf *bp)
2668 {
2669 transaction *tr;
2670 block_list_header *blhdr;
2671 int i;
2672
2673 CHECK_JOURNAL(jnl);
2674
2675 free_old_stuff(jnl);
2676
2677 tr = jnl->active_tr;
2678
2679 //
2680 // if there's no active transaction then we just want to
2681 // call buf_brelse() and return since this is just a block
2682 // that happened to be modified as part of another tr.
2683 //
2684 if (tr == NULL) {
2685 buf_brelse(bp);
2686 return 0;
2687 }
2688
2689 if (jnl->flags & JOURNAL_INVALID) {
2690 /* Still need to buf_brelse(). Callers assume we consume the bp. */
2691 buf_brelse(bp);
2692 return EINVAL;
2693 }
2694
2695 CHECK_TRANSACTION(tr);
2696
2697 if (jnl->owner != current_thread()) {
2698 panic("jnl: modify_block_abort: called w/out a transaction! jnl %p, owner %p, curact %p\n",
2699 jnl, jnl->owner, current_thread());
2700 }
2701
2702 // printf("jnl: modify_block_abort: tr 0x%x bp 0x%x\n", jnl->active_tr, bp);
2703
2704 // first check if it's already part of this transaction
2705 for (blhdr = tr->blhdr; blhdr; blhdr = (block_list_header *)((long)blhdr->binfo[0].bnum)) {
2706 for (i = 1; i < blhdr->num_blocks; i++) {
2707 if (bp == blhdr->binfo[i].u.bp) {
2708 break;
2709 }
2710 }
2711
2712 if (i < blhdr->num_blocks) {
2713 break;
2714 }
2715 }
2716
2717 //
2718 // if blhdr is null, then this block has only had modify_block_start
2719 // called on it as part of the current transaction. that means that
2720 // it is ok to clear the LOCKED bit since it hasn't actually been
2721 // modified. if blhdr is non-null then modify_block_end was called
2722 // on it and so we need to keep it locked in memory.
2723 //
2724 if (blhdr == NULL) {
2725 buf_clearflags(bp, B_LOCKED);
2726 }
2727
2728 buf_brelse(bp);
2729 return 0;
2730 }
2731
2732
2733 int
2734 journal_modify_block_end(journal *jnl, struct buf *bp, void (*func)(buf_t bp, void *arg), void *arg)
2735 {
2736 int i = 1;
2737 int tbuffer_offset=0;
2738 block_list_header *blhdr, *prev=NULL;
2739 transaction *tr;
2740
2741 CHECK_JOURNAL(jnl);
2742
2743 free_old_stuff(jnl);
2744
2745 if (jnl->flags & JOURNAL_INVALID) {
2746 /* Still need to buf_brelse(). Callers assume we consume the bp. */
2747 buf_brelse(bp);
2748 return EINVAL;
2749 }
2750
2751 tr = jnl->active_tr;
2752 CHECK_TRANSACTION(tr);
2753
2754 if (jnl->owner != current_thread()) {
2755 panic("jnl: modify_block_end: called w/out a transaction! jnl %p, owner %p, curact %p\n",
2756 jnl, jnl->owner, current_thread());
2757 }
2758
2759 //printf("jnl: mod block end: (bp 0x%x vp 0x%x l/blkno %qd/%qd bsz %d, total bytes %d)\n",
2760 // bp, buf_vnode(bp), buf_lblkno(bp), buf_blkno(bp), buf_size(bp), tr->total_bytes);
2761
2762 if ((buf_flags(bp) & B_LOCKED) == 0) {
2763 panic("jnl: modify_block_end: bp %p not locked! jnl @ %p\n", bp, jnl);
2764 }
2765
2766 // first check if it's already part of this transaction
2767 for (blhdr = tr->blhdr; blhdr; prev = blhdr, blhdr = (block_list_header *)((long)blhdr->binfo[0].bnum)) {
2768 tbuffer_offset = jnl->jhdr->blhdr_size;
2769
2770 for (i = 1; i < blhdr->num_blocks; i++) {
2771 if (bp == blhdr->binfo[i].u.bp) {
2772 break;
2773 }
2774 if (blhdr->binfo[i].bnum != (off_t)-1) {
2775 tbuffer_offset += buf_size(blhdr->binfo[i].u.bp);
2776 } else {
2777 tbuffer_offset += blhdr->binfo[i].u.bi.bsize;
2778 }
2779 }
2780
2781 if (i < blhdr->num_blocks) {
2782 break;
2783 }
2784 }
2785
2786 if (blhdr == NULL
2787 && prev
2788 && (prev->num_blocks+1) <= prev->max_blocks
2789 && (prev->bytes_used+buf_size(bp)) <= (uint32_t)tr->tbuffer_size) {
2790 blhdr = prev;
2791
2792 } else if (blhdr == NULL) {
2793 block_list_header *nblhdr;
2794 if (prev == NULL) {
2795 panic("jnl: modify block end: no way man, prev == NULL?!?, jnl %p, bp %p\n", jnl, bp);
2796 }
2797
2798 // we got to the end of the list, didn't find the block and there's
2799 // no room in the block_list_header pointed to by prev
2800
2801 // we allocate another tbuffer and link it in at the end of the list
2802 // through prev->binfo[0].bnum. that's a skanky way to do things but
2803 // avoids having yet another linked list of small data structures to manage.
2804
2805 if (kmem_alloc_kobject(kernel_map, (vm_offset_t *)&nblhdr, tr->tbuffer_size)) {
2806 panic("jnl: end_tr: no space for new block tr @ %p (total bytes: %d)!\n",
2807 tr, tr->total_bytes);
2808 }
2809
2810 // journal replay code checksum check depends on this.
2811 memset(nblhdr, 0, BLHDR_CHECKSUM_SIZE);
2812 // Fill up the rest of the block with unimportant bytes
2813 memset(nblhdr + BLHDR_CHECKSUM_SIZE, 0x5a, jnl->jhdr->blhdr_size - BLHDR_CHECKSUM_SIZE);
2814
2815 // initialize the new guy
2816 nblhdr->max_blocks = (jnl->jhdr->blhdr_size / sizeof(block_info)) - 1;
2817 nblhdr->num_blocks = 1; // accounts for this header block
2818 nblhdr->bytes_used = jnl->jhdr->blhdr_size;
2819 nblhdr->flags = BLHDR_CHECK_CHECKSUMS;
2820
2821 tr->num_blhdrs++;
2822 tr->total_bytes += jnl->jhdr->blhdr_size;
2823
2824 // then link him in at the end
2825 prev->binfo[0].bnum = (off_t)((long)nblhdr);
2826
2827 // and finally switch to using the new guy
2828 blhdr = nblhdr;
2829 tbuffer_offset = jnl->jhdr->blhdr_size;
2830 i = 1;
2831 }
2832
2833
2834 if ((i+1) > blhdr->max_blocks) {
2835 panic("jnl: modify_block_end: i = %d, max_blocks %d\n", i, blhdr->max_blocks);
2836 }
2837
2838 // if this is true then this is a new block we haven't seen
2839 if (i >= blhdr->num_blocks) {
2840 int bsize;
2841 vnode_t vp;
2842
2843 vp = buf_vnode(bp);
2844 vnode_ref(vp);
2845 bsize = buf_size(bp);
2846
2847 blhdr->binfo[i].bnum = (off_t)(buf_blkno(bp));
2848 blhdr->binfo[i].u.bp = bp;
2849
2850 if (func) {
2851 void (*old_func)(buf_t, void *)=NULL, *old_arg=NULL;
2852
2853 buf_setfilter(bp, func, arg, &old_func, &old_arg);
2854 if (old_func != NULL && old_func != func) {
2855 panic("jnl: modify_block_end: old func %p / arg %p (func %p)", old_func, old_arg, func);
2856 }
2857 }
2858
2859 blhdr->bytes_used += bsize;
2860 tr->total_bytes += bsize;
2861
2862 blhdr->num_blocks++;
2863 }
2864 buf_bdwrite(bp);
2865
2866 return 0;
2867 }
2868
2869 int
2870 journal_kill_block(journal *jnl, struct buf *bp)
2871 {
2872 int i;
2873 int bflags;
2874 block_list_header *blhdr;
2875 transaction *tr;
2876
2877 CHECK_JOURNAL(jnl);
2878
2879 free_old_stuff(jnl);
2880
2881 if (jnl->flags & JOURNAL_INVALID) {
2882 return EINVAL;
2883 }
2884
2885 tr = jnl->active_tr;
2886 CHECK_TRANSACTION(tr);
2887
2888 if (jnl->owner != current_thread()) {
2889 panic("jnl: modify_block_end: called w/out a transaction! jnl %p, owner %p, curact %p\n",
2890 jnl, jnl->owner, current_thread());
2891 }
2892
2893 bflags = buf_flags(bp);
2894
2895 if ( !(bflags & B_LOCKED))
2896 panic("jnl: modify_block_end: called with bp not B_LOCKED");
2897
2898 /*
2899 * bp must be BL_BUSY and B_LOCKED
2900 * first check if it's already part of this transaction
2901 */
2902 for (blhdr = tr->blhdr; blhdr; blhdr = (block_list_header *)((long)blhdr->binfo[0].bnum)) {
2903
2904 for (i = 1; i < blhdr->num_blocks; i++) {
2905 if (bp == blhdr->binfo[i].u.bp) {
2906 vnode_t vp;
2907
2908 buf_clearflags(bp, B_LOCKED);
2909
2910 // this undoes the vnode_ref() in journal_modify_block_end()
2911 vp = buf_vnode(bp);
2912 vnode_rele_ext(vp, 0, 1);
2913
2914 // if the block has the DELWRI and FILTER bits sets, then
2915 // things are seriously weird. if it was part of another
2916 // transaction then journal_modify_block_start() should
2917 // have force it to be written.
2918 //
2919 //if ((bflags & B_DELWRI) && (bflags & B_FILTER)) {
2920 // panic("jnl: kill block: this defies all logic! bp 0x%x\n", bp);
2921 //} else {
2922 tr->num_killed += buf_size(bp);
2923 //}
2924 blhdr->binfo[i].bnum = (off_t)-1;
2925 blhdr->binfo[i].u.bp = NULL;
2926 blhdr->binfo[i].u.bi.bsize = buf_size(bp);
2927
2928 buf_markinvalid(bp);
2929 buf_brelse(bp);
2930
2931 break;
2932 }
2933 }
2934
2935 if (i < blhdr->num_blocks) {
2936 break;
2937 }
2938 }
2939
2940 return 0;
2941 }
2942
2943 /*
2944 ;________________________________________________________________________________
2945 ;
2946 ; Routine: journal_trim_set_callback
2947 ;
2948 ; Function: Provide the journal with a routine to be called back when a
2949 ; TRIM has (or would have) been issued to the device. That
2950 ; is, the transaction has been flushed to the device, and the
2951 ; blocks freed by the transaction are now safe for reuse.
2952 ;
2953 ; CAUTION: If the journal becomes invalid (eg., due to an I/O
2954 ; error when trying to write to the journal), this callback
2955 ; will stop getting called, even if extents got freed before
2956 ; the journal became invalid!
2957 ;
2958 ; Input Arguments:
2959 ; jnl - The journal structure for the filesystem.
2960 ; callback - The function to call when the TRIM is complete.
2961 ; arg - An argument to be passed to callback.
2962 ;________________________________________________________________________________
2963 */
2964 __private_extern__ void
2965 journal_trim_set_callback(journal *jnl, jnl_trim_callback_t callback, void *arg)
2966 {
2967 jnl->trim_callback = callback;
2968 jnl->trim_callback_arg = arg;
2969 }
2970
2971
2972 /*
2973 ;________________________________________________________________________________
2974 ;
2975 ; Routine: journal_trim_realloc
2976 ;
2977 ; Function: Increase the amount of memory allocated for the list of extents
2978 ; to be unmapped (trimmed). This routine will be called when
2979 ; adding an extent to the list, and the list already occupies
2980 ; all of the space allocated to it. This routine returns ENOMEM
2981 ; if unable to allocate more space, or 0 if the extent list was
2982 ; grown successfully.
2983 ;
2984 ; Input Arguments:
2985 ; trim - The trim list to be resized.
2986 ;
2987 ; Output:
2988 ; (result) - ENOMEM or 0.
2989 ;
2990 ; Side effects:
2991 ; The allocated_count and extents fields of tr->trim are updated
2992 ; if the function returned 0.
2993 ;________________________________________________________________________________
2994 */
2995 static int
2996 trim_realloc(struct jnl_trim_list *trim)
2997 {
2998 void *new_extents;
2999 uint32_t new_allocated_count;
3000
3001 if (jnl_kdebug)
3002 KERNEL_DEBUG_CONSTANT(DBG_JOURNAL_TRIM_REALLOC | DBG_FUNC_START, trim, 0, trim->allocated_count, trim->extent_count, 0);
3003
3004 new_allocated_count = trim->allocated_count + JOURNAL_DEFAULT_TRIM_EXTENTS;
3005 new_extents = kalloc(new_allocated_count * sizeof(dk_extent_t));
3006 if (new_extents == NULL) {
3007 printf("jnl: trim_realloc: unable to grow extent list!\n");
3008 /*
3009 * Since we could be called when allocating space previously marked
3010 * to be trimmed, we need to empty out the list to be safe.
3011 */
3012 trim->extent_count = 0;
3013 if (jnl_kdebug)
3014 KERNEL_DEBUG_CONSTANT(DBG_JOURNAL_TRIM_REALLOC | DBG_FUNC_END, ENOMEM, 0, trim->allocated_count, 0, 0);
3015 return ENOMEM;
3016 }
3017
3018 /* Copy the old extent list to the newly allocated list. */
3019 if (trim->extents != NULL) {
3020 memmove(new_extents,
3021 trim->extents,
3022 trim->allocated_count * sizeof(dk_extent_t));
3023 kfree(trim->extents,
3024 trim->allocated_count * sizeof(dk_extent_t));
3025 }
3026
3027 trim->allocated_count = new_allocated_count;
3028 trim->extents = new_extents;
3029
3030 if (jnl_kdebug)
3031 KERNEL_DEBUG_CONSTANT(DBG_JOURNAL_TRIM_REALLOC | DBG_FUNC_END, 0, 0, new_allocated_count, trim->extent_count, 0);
3032
3033 return 0;
3034 }
3035
3036 /*
3037 ;________________________________________________________________________________
3038 ;
3039 ; Routine: trim_search_extent
3040 ;
3041 ; Function: Search the given extent list to see if any of its extents
3042 ; overlap the given extent.
3043 ;
3044 ; Input Arguments:
3045 ; trim - The trim list to be searched.
3046 ; offset - The first byte of the range to be searched for.
3047 ; length - The number of bytes of the extent being searched for.
3048 ;
3049 ; Output:
3050 ; (result) - TRUE if one or more extents overlap, FALSE otherwise.
3051 ;________________________________________________________________________________
3052 */
3053 static int
3054 trim_search_extent(struct jnl_trim_list *trim, uint64_t offset, uint64_t length)
3055 {
3056 uint64_t end = offset + length;
3057 uint32_t lower = 0; /* Lowest index to search */
3058 uint32_t upper = trim->extent_count; /* Highest index to search + 1 */
3059 uint32_t middle;
3060
3061 /* A binary search over the extent list. */
3062 while (lower < upper) {
3063 middle = (lower + upper) / 2;
3064
3065 if (trim->extents[middle].offset >= end)
3066 upper = middle;
3067 else if (trim->extents[middle].offset + trim->extents[middle].length <= offset)
3068 lower = middle + 1;
3069 else
3070 return TRUE;
3071 }
3072
3073 return FALSE;
3074 }
3075
3076
3077 /*
3078 ;________________________________________________________________________________
3079 ;
3080 ; Routine: journal_trim_add_extent
3081 ;
3082 ; Function: Keep track of extents that have been freed as part of this
3083 ; transaction. If the underlying device supports TRIM (UNMAP),
3084 ; then those extents will be trimmed/unmapped once the
3085 ; transaction has been written to the journal. (For example,
3086 ; SSDs can support trim/unmap and avoid having to recopy those
3087 ; blocks when doing wear leveling, and may reuse the same
3088 ; phsyical blocks for different logical blocks.)
3089 ;
3090 ; HFS also uses this, in combination with journal_trim_set_callback,
3091 ; to add recently freed extents to its free extent cache, but
3092 ; only after the transaction that freed them is committed to
3093 ; disk. (This reduces the chance of overwriting live data in
3094 ; a way that causes data loss if a transaction never gets
3095 ; written to the journal.)
3096 ;
3097 ; Input Arguments:
3098 ; jnl - The journal for the volume containing the byte range.
3099 ; offset - The first byte of the range to be trimmed.
3100 ; length - The number of bytes of the extent being trimmed.
3101 ;________________________________________________________________________________
3102 */
3103 __private_extern__ int
3104 journal_trim_add_extent(journal *jnl, uint64_t offset, uint64_t length)
3105 {
3106 uint64_t end;
3107 transaction *tr;
3108 dk_extent_t *extent;
3109 uint32_t insert_index;
3110 uint32_t replace_count;
3111
3112 CHECK_JOURNAL(jnl);
3113
3114 /* TODO: Is it OK to manipulate the trim list even if JOURNAL_INVALID is set? I think so... */
3115 if (jnl->flags & JOURNAL_INVALID) {
3116 return EINVAL;
3117 }
3118
3119 tr = jnl->active_tr;
3120 CHECK_TRANSACTION(tr);
3121
3122 if (jnl_kdebug)
3123 KERNEL_DEBUG_CONSTANT(DBG_JOURNAL_TRIM_ADD | DBG_FUNC_START, jnl, offset, length, tr->trim.extent_count, 0);
3124
3125 if (jnl->owner != current_thread()) {
3126 panic("jnl: trim_add_extent: called w/out a transaction! jnl %p, owner %p, curact %p\n",
3127 jnl, jnl->owner, current_thread());
3128 }
3129
3130 free_old_stuff(jnl);
3131
3132 end = offset + length;
3133
3134 /*
3135 * Find the range of existing extents that can be combined with the
3136 * input extent. We start by counting the number of extents that end
3137 * strictly before the input extent, then count the number of extents
3138 * that overlap or are contiguous with the input extent.
3139 */
3140 extent = tr->trim.extents;
3141 insert_index = 0;
3142 while (insert_index < tr->trim.extent_count && extent->offset + extent->length < offset) {
3143 ++insert_index;
3144 ++extent;
3145 }
3146 replace_count = 0;
3147 while (insert_index + replace_count < tr->trim.extent_count && extent->offset <= end) {
3148 ++replace_count;
3149 ++extent;
3150 }
3151
3152 /*
3153 * If none of the existing extents can be combined with the input extent,
3154 * then just insert it in the list (before item number insert_index).
3155 */
3156 if (replace_count == 0) {
3157 /* If the list was already full, we need to grow it. */
3158 if (tr->trim.extent_count == tr->trim.allocated_count) {
3159 if (trim_realloc(&tr->trim) != 0) {
3160 printf("jnl: trim_add_extent: out of memory!");
3161 if (jnl_kdebug)
3162 KERNEL_DEBUG_CONSTANT(DBG_JOURNAL_TRIM_ADD | DBG_FUNC_END, ENOMEM, 0, 0, tr->trim.extent_count, 0);
3163 return ENOMEM;
3164 }
3165 }
3166
3167 /* Shift any existing extents with larger offsets. */
3168 if (insert_index < tr->trim.extent_count) {
3169 memmove(&tr->trim.extents[insert_index+1],
3170 &tr->trim.extents[insert_index],
3171 (tr->trim.extent_count - insert_index) * sizeof(dk_extent_t));
3172 }
3173 tr->trim.extent_count++;
3174
3175 /* Store the new extent in the list. */
3176 tr->trim.extents[insert_index].offset = offset;
3177 tr->trim.extents[insert_index].length = length;
3178
3179 /* We're done. */
3180 if (jnl_kdebug)
3181 KERNEL_DEBUG_CONSTANT(DBG_JOURNAL_TRIM_ADD | DBG_FUNC_END, 0, 0, 0, tr->trim.extent_count, 0);
3182 return 0;
3183 }
3184
3185 /*
3186 * Update extent number insert_index to be the union of the input extent
3187 * and all of the replaced extents.
3188 */
3189 if (tr->trim.extents[insert_index].offset < offset)
3190 offset = tr->trim.extents[insert_index].offset;
3191 extent = &tr->trim.extents[insert_index + replace_count - 1];
3192 if (extent->offset + extent->length > end)
3193 end = extent->offset + extent->length;
3194 tr->trim.extents[insert_index].offset = offset;
3195 tr->trim.extents[insert_index].length = end - offset;
3196
3197 /*
3198 * If we were replacing more than one existing extent, then shift any
3199 * extents with larger offsets, and update the count of extents.
3200 *
3201 * We're going to leave extent #insert_index alone since it was just updated, above.
3202 * We need to move extents from index (insert_index + replace_count) through the end of
3203 * the list by (replace_count - 1) positions so that they overwrite extent #(insert_index + 1).
3204 */
3205 if (replace_count > 1 && (insert_index + replace_count) < tr->trim.extent_count) {
3206 memmove(&tr->trim.extents[insert_index + 1],
3207 &tr->trim.extents[insert_index + replace_count],
3208 (tr->trim.extent_count - insert_index - replace_count) * sizeof(dk_extent_t));
3209 }
3210 tr->trim.extent_count -= replace_count - 1;
3211
3212 if (jnl_kdebug)
3213 KERNEL_DEBUG_CONSTANT(DBG_JOURNAL_TRIM_ADD | DBG_FUNC_END, 0, 0, 0, tr->trim.extent_count, 0);
3214 return 0;
3215 }
3216
3217
3218 /*
3219 ;________________________________________________________________________________
3220 ;
3221 ; Routine: trim_remove_extent
3222 ;
3223 ; Function: Indicate that a range of bytes, some of which may have previously
3224 ; been passed to journal_trim_add_extent, is now allocated.
3225 ; Any overlapping ranges currently in the journal's trim list will
3226 ; be removed. If the underlying device supports TRIM (UNMAP), then
3227 ; these extents will not be trimmed/unmapped when the transaction
3228 ; is written to the journal.
3229 ;
3230 ; HFS also uses this to prevent newly allocated space from being
3231 ; added to its free extent cache (if some portion of the newly
3232 ; allocated space was recently freed).
3233 ;
3234 ; Input Arguments:
3235 ; trim - The trim list to update.
3236 ; offset - The first byte of the range to be trimmed.
3237 ; length - The number of bytes of the extent being trimmed.
3238 ;________________________________________________________________________________
3239 */
3240 static int
3241 trim_remove_extent(struct jnl_trim_list *trim, uint64_t offset, uint64_t length)
3242 {
3243 u_int64_t end;
3244 dk_extent_t *extent;
3245 u_int32_t keep_before;
3246 u_int32_t keep_after;
3247
3248 end = offset + length;
3249
3250 /*
3251 * Find any existing extents that start before or end after the input
3252 * extent. These extents will be modified if they overlap the input
3253 * extent. Other extents between them will be deleted.
3254 */
3255 extent = trim->extents;
3256 keep_before = 0;
3257 while (keep_before < trim->extent_count && extent->offset < offset) {
3258 ++keep_before;
3259 ++extent;
3260 }
3261 keep_after = keep_before;
3262 if (keep_after > 0) {
3263 /* See if previous extent extends beyond both ends of input extent. */
3264 --keep_after;
3265 --extent;
3266 }
3267 while (keep_after < trim->extent_count && (extent->offset + extent->length) <= end) {
3268 ++keep_after;
3269 ++extent;
3270 }
3271
3272 /*
3273 * When we get here, the first keep_before extents (0 .. keep_before-1)
3274 * start before the input extent, and extents (keep_after .. extent_count-1)
3275 * end after the input extent. We'll need to keep, all of those extents,
3276 * but possibly modify #(keep_before-1) and #keep_after to remove the portion
3277 * that overlaps with the input extent.
3278 */
3279
3280 /*
3281 * Does the input extent start after and end before the same existing
3282 * extent? If so, we have to "punch a hole" in that extent and convert
3283 * it to two separate extents.
3284 */
3285 if (keep_before > keep_after) {
3286 /* If the list was already full, we need to grow it. */
3287 if (trim->extent_count == trim->allocated_count) {
3288 if (trim_realloc(trim) != 0) {
3289 printf("jnl: trim_remove_extent: out of memory!");
3290 return ENOMEM;
3291 }
3292 }
3293
3294 /*
3295 * Make room for a new extent by shifting extents #keep_after and later
3296 * down by one extent. When we're done, extents #keep_before and
3297 * #keep_after will be identical, and we can fall through to removing
3298 * the portion that overlaps the input extent.
3299 */
3300 memmove(&trim->extents[keep_before],
3301 &trim->extents[keep_after],
3302 (trim->extent_count - keep_after) * sizeof(dk_extent_t));
3303 ++trim->extent_count;
3304 ++keep_after;
3305
3306 /*
3307 * Fall through. We now have the case where the length of extent
3308 * #(keep_before - 1) needs to be updated, and the start of extent
3309 * #(keep_after) needs to be updated.
3310 */
3311 }
3312
3313 /*
3314 * May need to truncate the end of extent #(keep_before - 1) if it overlaps
3315 * the input extent.
3316 */
3317 if (keep_before > 0) {
3318 extent = &trim->extents[keep_before - 1];
3319 if (extent->offset + extent->length > offset) {
3320 extent->length = offset - extent->offset;
3321 }
3322 }
3323
3324 /*
3325 * May need to update the start of extent #(keep_after) if it overlaps the
3326 * input extent.
3327 */
3328 if (keep_after < trim->extent_count) {
3329 extent = &trim->extents[keep_after];
3330 if (extent->offset < end) {
3331 extent->length = extent->offset + extent->length - end;
3332 extent->offset = end;
3333 }
3334 }
3335
3336 /*
3337 * If there were whole extents that overlapped the input extent, get rid
3338 * of them by shifting any following extents, and updating the count.
3339 */
3340 if (keep_after > keep_before && keep_after < trim->extent_count) {
3341 memmove(&trim->extents[keep_before],
3342 &trim->extents[keep_after],
3343 (trim->extent_count - keep_after) * sizeof(dk_extent_t));
3344 }
3345 trim->extent_count -= keep_after - keep_before;
3346
3347 return 0;
3348 }
3349
3350 /*
3351 ;________________________________________________________________________________
3352 ;
3353 ; Routine: journal_trim_remove_extent
3354 ;
3355 ; Function: Make note of a range of bytes, some of which may have previously
3356 ; been passed to journal_trim_add_extent, is now in use on the
3357 ; volume. The given bytes will be not be trimmed as part of
3358 ; this transaction, or a pending trim of a transaction being
3359 ; asynchronously flushed.
3360 ;
3361 ; Input Arguments:
3362 ; jnl - The journal for the volume containing the byte range.
3363 ; offset - The first byte of the range to be trimmed.
3364 ; length - The number of bytes of the extent being trimmed.
3365 ;________________________________________________________________________________
3366 */
3367 __private_extern__ int
3368 journal_trim_remove_extent(journal *jnl, uint64_t offset, uint64_t length)
3369 {
3370 int error = 0;
3371 transaction *tr;
3372
3373 CHECK_JOURNAL(jnl);
3374
3375 /* TODO: Is it OK to manipulate the trim list even if JOURNAL_INVALID is set? I think so... */
3376 if (jnl->flags & JOURNAL_INVALID) {
3377 return EINVAL;
3378 }
3379
3380 tr = jnl->active_tr;
3381 CHECK_TRANSACTION(tr);
3382
3383 if (jnl_kdebug)
3384 KERNEL_DEBUG_CONSTANT(DBG_JOURNAL_TRIM_REMOVE | DBG_FUNC_START, jnl, offset, length, tr->trim.extent_count, 0);
3385
3386 if (jnl->owner != current_thread()) {
3387 panic("jnl: trim_remove_extent: called w/out a transaction! jnl %p, owner %p, curact %p\n",
3388 jnl, jnl->owner, current_thread());
3389 }
3390
3391 free_old_stuff(jnl);
3392
3393 error = trim_remove_extent(&tr->trim, offset, length);
3394 if (error == 0) {
3395 int found = FALSE;
3396
3397 /*
3398 * See if a pending trim has any extents that overlap with the
3399 * one we were given.
3400 */
3401 lck_rw_lock_shared(&jnl->trim_lock);
3402 if (jnl->async_trim != NULL)
3403 found = trim_search_extent(jnl->async_trim, offset, length);
3404 lck_rw_unlock_shared(&jnl->trim_lock);
3405
3406 if (found) {
3407 /*
3408 * There was an overlap, so avoid trimming the extent we
3409 * just allocated. (Otherwise, it might get trimmed after
3410 * we've written to it, which will cause that data to be
3411 * corrupted.)
3412 */
3413 uint32_t async_extent_count = 0;
3414
3415 if (jnl_kdebug)
3416 KERNEL_DEBUG_CONSTANT(DBG_JOURNAL_TRIM_REMOVE_PENDING | DBG_FUNC_START, jnl, offset, length, 0, 0);
3417 lck_rw_lock_exclusive(&jnl->trim_lock);
3418 if (jnl->async_trim != NULL) {
3419 error = trim_remove_extent(jnl->async_trim, offset, length);
3420 async_extent_count = jnl->async_trim->extent_count;
3421 }
3422 lck_rw_unlock_exclusive(&jnl->trim_lock);
3423 if (jnl_kdebug)
3424 KERNEL_DEBUG_CONSTANT(DBG_JOURNAL_TRIM_REMOVE_PENDING | DBG_FUNC_END, error, 0, 0, async_extent_count, 0);
3425 }
3426 }
3427
3428 if (jnl_kdebug)
3429 KERNEL_DEBUG_CONSTANT(DBG_JOURNAL_TRIM_REMOVE | DBG_FUNC_END, error, 0, 0, tr->trim.extent_count, 0);
3430 return error;
3431 }
3432
3433
3434 static int
3435 journal_trim_flush(journal *jnl, transaction *tr)
3436 {
3437 int errno = 0;
3438
3439 if (jnl_kdebug)
3440 KERNEL_DEBUG_CONSTANT(DBG_JOURNAL_TRIM_FLUSH | DBG_FUNC_START, jnl, tr, 0, tr->trim.extent_count, 0);
3441
3442 lck_rw_lock_shared(&jnl->trim_lock);
3443 if (tr->trim.extent_count > 0) {
3444 dk_unmap_t unmap;
3445
3446 bzero(&unmap, sizeof(unmap));
3447 if (CONFIG_HFS_TRIM && (jnl->flags & JOURNAL_USE_UNMAP)) {
3448 unmap.extents = tr->trim.extents;
3449 unmap.extentsCount = tr->trim.extent_count;
3450 if (jnl_kdebug)
3451 KERNEL_DEBUG_CONSTANT(DBG_JOURNAL_TRIM_UNMAP | DBG_FUNC_START, jnl, tr, 0, tr->trim.extent_count, 0);
3452 errno = VNOP_IOCTL(jnl->fsdev, DKIOCUNMAP, (caddr_t)&unmap, FWRITE, vfs_context_kernel());
3453 if (jnl_kdebug)
3454 KERNEL_DEBUG_CONSTANT(DBG_JOURNAL_TRIM_UNMAP | DBG_FUNC_END, errno, 0, 0, 0, 0);
3455 if (errno) {
3456 printf("jnl: error %d from DKIOCUNMAP (extents=%lx, count=%u); disabling trim for %s\n",
3457 errno, (unsigned long) (unmap.extents), unmap.extentsCount,
3458 jnl->jdev_name);
3459 jnl->flags &= ~JOURNAL_USE_UNMAP;
3460 }
3461 }
3462
3463 /*
3464 * Call back into the file system to tell them that we have
3465 * trimmed some extents and that they can now be reused.
3466 *
3467 * CAUTION: If the journal becomes invalid (eg., due to an I/O
3468 * error when trying to write to the journal), this callback
3469 * will stop getting called, even if extents got freed before
3470 * the journal became invalid!
3471 */
3472 if (jnl->trim_callback)
3473 jnl->trim_callback(jnl->trim_callback_arg, tr->trim.extent_count, tr->trim.extents);
3474 }
3475 lck_rw_unlock_shared(&jnl->trim_lock);
3476
3477 /*
3478 * If the transaction we're flushing was the async transaction, then
3479 * tell the current transaction that there is no pending trim
3480 * any more.
3481 *
3482 * NOTE: Since we released the lock, another thread could have
3483 * removed one or more extents from our list. That's not a
3484 * problem since any writes to the re-allocated blocks
3485 * would get sent to the device after the DKIOCUNMAP.
3486 */
3487 lck_rw_lock_exclusive(&jnl->trim_lock);
3488 if (jnl->async_trim == &tr->trim)
3489 jnl->async_trim = NULL;
3490 lck_rw_unlock_exclusive(&jnl->trim_lock);
3491
3492 /*
3493 * By the time we get here, no other thread can discover the address
3494 * of "tr", so it is safe for us to manipulate tr->trim without
3495 * holding any locks.
3496 */
3497 if (tr->trim.extents) {
3498 kfree(tr->trim.extents, tr->trim.allocated_count * sizeof(dk_extent_t));
3499 tr->trim.allocated_count = 0;
3500 tr->trim.extent_count = 0;
3501 tr->trim.extents = NULL;
3502 }
3503
3504 if (jnl_kdebug)
3505 KERNEL_DEBUG_CONSTANT(DBG_JOURNAL_TRIM_FLUSH | DBG_FUNC_END, errno, 0, 0, 0, 0);
3506
3507 return errno;
3508 }
3509
3510 static int
3511 journal_binfo_cmp(const void *a, const void *b)
3512 {
3513 const block_info *bi_a = (const struct block_info *)a;
3514 const block_info *bi_b = (const struct block_info *)b;
3515 daddr64_t res;
3516
3517 if (bi_a->bnum == (off_t)-1) {
3518 return 1;
3519 }
3520 if (bi_b->bnum == (off_t)-1) {
3521 return -1;
3522 }
3523
3524 // don't have to worry about negative block
3525 // numbers so this is ok to do.
3526 //
3527 res = (buf_blkno(bi_a->u.bp) - buf_blkno(bi_b->u.bp));
3528
3529 return (int)res;
3530 }
3531
3532
3533 /*
3534 * End a transaction. If the transaction is small enough, and we're not forcing
3535 * a write to disk, the "active" transaction becomes the "current" transaction,
3536 * and will be reused for the next transaction that is started (group commit).
3537 *
3538 * If the transaction gets written to disk (because force_it is true, or no
3539 * group commit, or the transaction is sufficiently full), the blocks get
3540 * written into the journal first, then the are written asynchronously. When
3541 * those async writes complete, the transaction can be freed and removed from
3542 * the journal.
3543 *
3544 * An optional callback can be supplied. If given, it is called after the
3545 * the blocks have been written to the journal, but before the async writes
3546 * of those blocks to their normal on-disk locations. This is used by
3547 * journal_relocate so that the location of the journal can be changed and
3548 * flushed to disk before the blocks get written to their normal locations.
3549 * Note that the callback is only called if the transaction gets written to
3550 * the journal during this end_transaction call; you probably want to set the
3551 * force_it flag.
3552 *
3553 * Inputs:
3554 * tr Transaction to add to the journal
3555 * force_it If true, force this transaction to the on-disk journal immediately.
3556 * callback See description above. Pass NULL for no callback.
3557 * callback_arg Argument passed to callback routine.
3558 *
3559 * Result
3560 * 0 No errors
3561 * -1 An error occurred. The journal is marked invalid.
3562 */
3563 static int
3564 end_transaction(transaction *tr, int force_it, errno_t (*callback)(void*), void *callback_arg, boolean_t drop_lock, boolean_t must_wait)
3565 {
3566 block_list_header *blhdr=NULL, *next=NULL;
3567 int i, ret_val = 0;
3568 errno_t errno;
3569 journal *jnl = tr->jnl;
3570 struct buf *bp;
3571 size_t tbuffer_offset;
3572 boolean_t drop_lock_early;
3573
3574 if (jnl->cur_tr) {
3575 panic("jnl: jnl @ %p already has cur_tr %p, new tr: %p\n",
3576 jnl, jnl->cur_tr, tr);
3577 }
3578
3579 // if there weren't any modified blocks in the transaction
3580 // just save off the transaction pointer and return.
3581 if (tr->total_bytes == jnl->jhdr->blhdr_size) {
3582 jnl->cur_tr = tr;
3583 goto done;
3584 }
3585
3586 // if our transaction buffer isn't very full, just hang
3587 // on to it and don't actually flush anything. this is
3588 // what is known as "group commit". we will flush the
3589 // transaction buffer if it's full or if we have more than
3590 // one of them so we don't start hogging too much memory.
3591 //
3592 // We also check the device supports UNMAP/TRIM, and if so,
3593 // the number of extents waiting to be trimmed. If it is
3594 // small enough, then keep accumulating more (so we can
3595 // reduce the overhead of trimming). If there was a prior
3596 // trim error, then we stop issuing trims for this
3597 // volume, so we can also coalesce transactions.
3598 //
3599 if ( force_it == 0
3600 && (jnl->flags & JOURNAL_NO_GROUP_COMMIT) == 0
3601 && tr->num_blhdrs < 3
3602 && (tr->total_bytes <= ((tr->tbuffer_size*tr->num_blhdrs) - tr->tbuffer_size/8))
3603 && (!(jnl->flags & JOURNAL_USE_UNMAP) || (tr->trim.extent_count < jnl_trim_flush_limit))) {
3604
3605 jnl->cur_tr = tr;
3606 goto done;
3607 }
3608
3609 KERNEL_DEBUG(0xbbbbc018|DBG_FUNC_START, jnl, tr, drop_lock, must_wait, 0);
3610
3611 lock_condition(jnl, &jnl->flushing, "end_transaction");
3612
3613 /*
3614 * if the previous 'finish_end_transaction' was being run
3615 * asynchronously, it could have encountered a condition
3616 * that caused it to mark the journal invalid... if that
3617 * occurred while we were waiting for it to finish, we
3618 * need to notice and abort the current transaction
3619 */
3620 if ((jnl->flags & JOURNAL_INVALID) || jnl->flush_aborted == TRUE) {
3621 unlock_condition(jnl, &jnl->flushing);
3622
3623 abort_transaction(jnl, tr);
3624 ret_val = -1;
3625 KERNEL_DEBUG(0xbbbbc018|DBG_FUNC_END, jnl, tr, ret_val, 0, 0);
3626 goto done;
3627 }
3628
3629 /*
3630 * Store a pointer to this transaction's trim list so that
3631 * future transactions can find it.
3632 *
3633 * Note: if there are no extents in the trim list, then don't
3634 * bother saving the pointer since nothing can add new extents
3635 * to the list (and other threads/transactions only care if
3636 * there is a trim pending).
3637 */
3638 lck_rw_lock_exclusive(&jnl->trim_lock);
3639 if (jnl->async_trim != NULL)
3640 panic("jnl: end_transaction: async_trim already non-NULL!");
3641 if (tr->trim.extent_count > 0)
3642 jnl->async_trim = &tr->trim;
3643 lck_rw_unlock_exclusive(&jnl->trim_lock);
3644
3645 /*
3646 * snapshot the transaction sequence number while we are still behind
3647 * the journal lock since it will be bumped upon the start of the
3648 * next transaction group which may overlap the current journal flush...
3649 * we pass the snapshot into write_journal_header during the journal
3650 * flush so that it can write the correct version in the header...
3651 * because we hold the 'flushing' condition variable for the duration
3652 * of the journal flush, 'saved_sequence_num' remains stable
3653 */
3654 jnl->saved_sequence_num = jnl->sequence_num;
3655
3656 /*
3657 * if we're here we're going to flush the transaction buffer to disk.
3658 * 'check_free_space' will not return untl there is enough free
3659 * space for this transaction in the journal and jnl->old_start[0]
3660 * is avaiable for use
3661 */
3662 KERNEL_DEBUG(0xbbbbc030 | DBG_FUNC_START, jnl, 0, 0, 0, 0);
3663
3664 check_free_space(jnl, tr->total_bytes, &tr->delayed_header_write, jnl->saved_sequence_num);
3665
3666 KERNEL_DEBUG(0xbbbbc030 | DBG_FUNC_END, jnl, tr->delayed_header_write, 0, 0, 0);
3667
3668 // range check the end index
3669 if (jnl->jhdr->end <= 0 || jnl->jhdr->end > jnl->jhdr->size) {
3670 panic("jnl: end_transaction: end is bogus 0x%llx (sz 0x%llx)\n",
3671 jnl->jhdr->end, jnl->jhdr->size);
3672 }
3673 if (tr->delayed_header_write == TRUE) {
3674 thread_t thread = THREAD_NULL;
3675
3676 lock_condition(jnl, &jnl->writing_header, "end_transaction");
3677 /*
3678 * fire up a thread to write the journal header
3679 * asynchronously... when it finishes, it will call
3680 * unlock_condition... we can overlap the preparation of
3681 * the log and buffers during this time
3682 */
3683 kernel_thread_start((thread_continue_t)write_header_thread, jnl, &thread);
3684 } else
3685 jnl->write_header_failed = FALSE;
3686
3687
3688 // this transaction starts where the current journal ends
3689 tr->journal_start = jnl->jhdr->end;
3690
3691 lock_oldstart(jnl);
3692 /*
3693 * Because old_start is locked above, we can cast away the volatile qualifier before passing it to memcpy.
3694 * slide everyone else down and put our latest guy in the last
3695 * entry in the old_start array
3696 */
3697 memcpy(__CAST_AWAY_QUALIFIER(&jnl->old_start[0], volatile, void *), __CAST_AWAY_QUALIFIER(&jnl->old_start[1], volatile, void *), sizeof(jnl->old_start)-sizeof(jnl->old_start[0]));
3698 jnl->old_start[sizeof(jnl->old_start)/sizeof(jnl->old_start[0]) - 1] = tr->journal_start | 0x8000000000000000LL;
3699
3700 unlock_oldstart(jnl);
3701
3702
3703 for (blhdr = tr->blhdr; blhdr; blhdr = next) {
3704 char *blkptr;
3705 buf_t sbp;
3706 int32_t bsize;
3707
3708 tbuffer_offset = jnl->jhdr->blhdr_size;
3709
3710 for (i = 1; i < blhdr->num_blocks; i++) {
3711
3712 if (blhdr->binfo[i].bnum != (off_t)-1) {
3713 void (*func)(buf_t, void *);
3714 void *arg;
3715
3716 bp = blhdr->binfo[i].u.bp;
3717
3718 if (bp == NULL) {
3719 panic("jnl: inconsistent binfo (NULL bp w/bnum %lld; jnl @ %p, tr %p)\n",
3720 blhdr->binfo[i].bnum, jnl, tr);
3721 }
3722 /*
3723 * acquire the bp here so that we can safely
3724 * mess around with its data. buf_acquire()
3725 * will return EAGAIN if the buffer was busy,
3726 * so loop trying again.
3727 */
3728 do {
3729 errno = buf_acquire(bp, BAC_REMOVE, 0, 0);
3730 } while (errno == EAGAIN);
3731
3732 if (errno)
3733 panic("could not acquire bp %p (err %d)\n", bp, errno);
3734
3735 if ((buf_flags(bp) & (B_LOCKED|B_DELWRI)) != (B_LOCKED|B_DELWRI)) {
3736 if (jnl->flags & JOURNAL_CLOSE_PENDING) {
3737 buf_clearflags(bp, B_LOCKED);
3738 buf_brelse(bp);
3739
3740 /*
3741 * this is an odd case that appears to happen occasionally
3742 * make sure we mark this block as no longer valid
3743 * so that we don't process it in "finish_end_transaction" since
3744 * the bp that is recorded in our array no longer belongs
3745 * to us (normally we substitute a shadow bp to be processed
3746 * issuing a 'buf_bawrite' on a stale buf_t pointer leads
3747 * to all kinds of problems.
3748 */
3749 blhdr->binfo[i].bnum = (off_t)-1;
3750 continue;
3751 } else {
3752 panic("jnl: end_tr: !!!DANGER!!! bp %p flags (0x%x) not LOCKED & DELWRI\n", bp, buf_flags(bp));
3753 }
3754 }
3755 bsize = buf_size(bp);
3756
3757 buf_setfilter(bp, NULL, NULL, &func, &arg);
3758
3759 blkptr = (char *)&((char *)blhdr)[tbuffer_offset];
3760
3761 sbp = buf_create_shadow_priv(bp, FALSE, (uintptr_t)blkptr, 0, 0);
3762
3763 if (sbp == NULL)
3764 panic("jnl: buf_create_shadow returned NULL");
3765
3766 /*
3767 * copy the data into the transaction buffer...
3768 */
3769 memcpy(blkptr, (char *)buf_dataptr(bp), bsize);
3770
3771 buf_clearflags(bp, B_LOCKED);
3772 buf_markclean(bp);
3773 buf_drop(bp);
3774
3775 /*
3776 * adopt the shadow buffer for this block
3777 */
3778 if (func) {
3779 /*
3780 * transfer FS hook function to the
3781 * shadow buffer... it will get called
3782 * in finish_end_transaction
3783 */
3784 buf_setfilter(sbp, func, arg, NULL, NULL);
3785 }
3786 blhdr->binfo[i].u.bp = sbp;
3787
3788 } else {
3789 // bnum == -1, only true if a block was "killed"
3790 bsize = blhdr->binfo[i].u.bi.bsize;
3791 }
3792 tbuffer_offset += bsize;
3793 }
3794 next = (block_list_header *)((long)blhdr->binfo[0].bnum);
3795 }
3796 /*
3797 * if callback != NULL, we don't want to drop the journal
3798 * lock, or complete end_transaction asynchronously, since
3799 * the caller is expecting the callback to run in the calling
3800 * context
3801 *
3802 * if drop_lock == FALSE, we can't complete end_transaction
3803 * asynchronously
3804 */
3805 if (callback)
3806 drop_lock_early = FALSE;
3807 else
3808 drop_lock_early = drop_lock;
3809
3810 if (drop_lock_early == FALSE)
3811 must_wait = TRUE;
3812
3813 if (drop_lock_early == TRUE) {
3814 jnl->owner = NULL;
3815 unlock_journal(jnl);
3816 drop_lock = FALSE;
3817 }
3818 if (must_wait == TRUE)
3819 ret_val = finish_end_transaction(tr, callback, callback_arg);
3820 else {
3821 thread_t thread = THREAD_NULL;
3822
3823 /*
3824 * fire up a thread to complete processing this transaction
3825 * asynchronously... when it finishes, it will call
3826 * unlock_condition
3827 */
3828 kernel_thread_start((thread_continue_t)finish_end_thread, tr, &thread);
3829 }
3830 KERNEL_DEBUG(0xbbbbc018|DBG_FUNC_END, jnl, tr, ret_val, 0, 0);
3831 done:
3832 if (drop_lock == TRUE) {
3833 jnl->owner = NULL;
3834 unlock_journal(jnl);
3835 }
3836 return (ret_val);
3837 }
3838
3839
3840 static void
3841 finish_end_thread(transaction *tr)
3842 {
3843 proc_apply_thread_selfdiskacc(IOPOL_PASSIVE);
3844 finish_end_transaction(tr, NULL, NULL);
3845
3846 thread_deallocate(current_thread());
3847 thread_terminate(current_thread());
3848 }
3849
3850 static void
3851 write_header_thread(journal *jnl)
3852 {
3853 proc_apply_thread_selfdiskacc(IOPOL_PASSIVE);
3854
3855 if (write_journal_header(jnl, 1, jnl->saved_sequence_num))
3856 jnl->write_header_failed = TRUE;
3857 else
3858 jnl->write_header_failed = FALSE;
3859 unlock_condition(jnl, &jnl->writing_header);
3860
3861 thread_deallocate(current_thread());
3862 thread_terminate(current_thread());
3863 }
3864
3865 static int
3866 finish_end_transaction(transaction *tr, errno_t (*callback)(void*), void *callback_arg)
3867 {
3868 int i, amt;
3869 int ret = 0;
3870 off_t end;
3871 journal *jnl = tr->jnl;
3872 buf_t bp, *bparray;
3873 vnode_t vp;
3874 block_list_header *blhdr=NULL, *next=NULL;
3875 size_t tbuffer_offset;
3876 int bufs_written = 0;
3877 int ret_val = 0;
3878
3879 KERNEL_DEBUG(0xbbbbc028|DBG_FUNC_START, jnl, tr, 0, 0, 0);
3880
3881 end = jnl->jhdr->end;
3882
3883 for (blhdr = tr->blhdr; blhdr; blhdr = (block_list_header *)((long)blhdr->binfo[0].bnum)) {
3884
3885 amt = blhdr->bytes_used;
3886
3887 blhdr->binfo[0].u.bi.b.sequence_num = tr->sequence_num;
3888
3889 blhdr->checksum = 0;
3890 blhdr->checksum = calc_checksum((char *)blhdr, BLHDR_CHECKSUM_SIZE);
3891
3892 if (kmem_alloc(kernel_map, (vm_offset_t *)&bparray, blhdr->num_blocks * sizeof(struct buf *))) {
3893 panic("can't allocate %zd bytes for bparray\n", blhdr->num_blocks * sizeof(struct buf *));
3894 }
3895 tbuffer_offset = jnl->jhdr->blhdr_size;
3896
3897 for (i = 1; i < blhdr->num_blocks; i++) {
3898 void (*func)(buf_t, void *);
3899 void *arg;
3900 int32_t bsize;
3901
3902 /*
3903 * finish preparing the shadow buf_t before
3904 * calculating the individual block checksums
3905 */
3906 if (blhdr->binfo[i].bnum != (off_t)-1) {
3907 daddr64_t blkno;
3908 daddr64_t lblkno;
3909
3910 bp = blhdr->binfo[i].u.bp;
3911
3912 vp = buf_vnode(bp);
3913 blkno = buf_blkno(bp);
3914 lblkno = buf_lblkno(bp);
3915
3916 if (vp == NULL && lblkno == blkno) {
3917 printf("jnl: %s: end_tr: bad news! bp @ %p w/null vp and l/blkno = %qd/%qd. aborting the transaction (tr %p jnl %p).\n",
3918 jnl->jdev_name, bp, lblkno, blkno, tr, jnl);
3919 ret_val = -1;
3920 goto bad_journal;
3921 }
3922
3923 // if the lblkno is the same as blkno and this bp isn't
3924 // associated with the underlying file system device then
3925 // we need to call bmap() to get the actual physical block.
3926 //
3927 if ((lblkno == blkno) && (vp != jnl->fsdev)) {
3928 off_t f_offset;
3929 size_t contig_bytes;
3930
3931 if (VNOP_BLKTOOFF(vp, lblkno, &f_offset)) {
3932 printf("jnl: %s: end_tr: vnop_blktooff failed @ %p, jnl %p\n", jnl->jdev_name, bp, jnl);
3933 ret_val = -1;
3934 goto bad_journal;
3935 }
3936 if (VNOP_BLOCKMAP(vp, f_offset, buf_count(bp), &blkno, &contig_bytes, NULL, 0, NULL)) {
3937 printf("jnl: %s: end_tr: can't blockmap the bp @ %p, jnl %p\n", jnl->jdev_name, bp, jnl);
3938 ret_val = -1;
3939 goto bad_journal;
3940 }
3941 if ((uint32_t)contig_bytes < buf_count(bp)) {
3942 printf("jnl: %s: end_tr: blk not physically contiguous on disk@ %p, jnl %p\n", jnl->jdev_name, bp, jnl);
3943 ret_val = -1;
3944 goto bad_journal;
3945 }
3946 buf_setblkno(bp, blkno);
3947 }
3948 // update this so we write out the correct physical block number!
3949 blhdr->binfo[i].bnum = (off_t)(blkno);
3950
3951 /*
3952 * pick up the FS hook function (if any) and prepare
3953 * to fire this buffer off in the next pass
3954 */
3955 buf_setfilter(bp, buffer_flushed_callback, tr, &func, &arg);
3956
3957 if (func) {
3958 /*
3959 * call the hook function supplied by the filesystem...
3960 * this needs to happen BEFORE cacl_checksum in case
3961 * the FS morphs the data in the buffer
3962 */
3963 func(bp, arg);
3964 }
3965 bparray[i] = bp;
3966 bsize = buf_size(bp);
3967 blhdr->binfo[i].u.bi.bsize = bsize;
3968 blhdr->binfo[i].u.bi.b.cksum = calc_checksum(&((char *)blhdr)[tbuffer_offset], bsize);
3969 } else {
3970 bparray[i] = NULL;
3971 bsize = blhdr->binfo[i].u.bi.bsize;
3972 blhdr->binfo[i].u.bi.b.cksum = 0;
3973 }
3974 tbuffer_offset += bsize;
3975 }
3976 /*
3977 * if we fired off the journal_write_header asynchronously in
3978 * 'end_transaction', we need to wait for its completion
3979 * before writing the actual journal data
3980 */
3981 wait_condition(jnl, &jnl->writing_header, "finish_end_transaction");
3982
3983 if (jnl->write_header_failed == FALSE)
3984 ret = write_journal_data(jnl, &end, blhdr, amt);
3985 else
3986 ret_val = -1;
3987 /*
3988 * put the bp pointers back so that we can
3989 * make the final pass on them
3990 */
3991 for (i = 1; i < blhdr->num_blocks; i++)
3992 blhdr->binfo[i].u.bp = bparray[i];
3993
3994 kmem_free(kernel_map, (vm_offset_t)bparray, blhdr->num_blocks * sizeof(struct buf *));
3995
3996 if (ret_val == -1)
3997 goto bad_journal;
3998
3999 if (ret != amt) {
4000 printf("jnl: %s: end_transaction: only wrote %d of %d bytes to the journal!\n",
4001 jnl->jdev_name, ret, amt);
4002
4003 ret_val = -1;
4004 goto bad_journal;
4005 }
4006 }
4007 jnl->jhdr->end = end; // update where the journal now ends
4008 tr->journal_end = end; // the transaction ends here too
4009
4010 if (tr->journal_start == 0 || tr->journal_end == 0) {
4011 panic("jnl: end_transaction: bad tr journal start/end: 0x%llx 0x%llx\n",
4012 tr->journal_start, tr->journal_end);
4013 }
4014
4015 if (write_journal_header(jnl, 0, jnl->saved_sequence_num) != 0) {
4016 ret_val = -1;
4017 goto bad_journal;
4018 }
4019 /*
4020 * If the caller supplied a callback, call it now that the blocks have been
4021 * written to the journal. This is used by journal_relocate so, for example,
4022 * the file system can change its pointer to the new journal.
4023 */
4024 if (callback != NULL && callback(callback_arg) != 0) {
4025 ret_val = -1;
4026 goto bad_journal;
4027 }
4028
4029 //
4030 // Send a DKIOCUNMAP for the extents trimmed by this transaction, and
4031 // free up the extent list.
4032 //
4033 journal_trim_flush(jnl, tr);
4034
4035 // the buffer_flushed_callback will only be called for the
4036 // real blocks that get flushed so we have to account for
4037 // the block_list_headers here.
4038 //
4039 tr->num_flushed = tr->num_blhdrs * jnl->jhdr->blhdr_size;
4040
4041 lock_condition(jnl, &jnl->asyncIO, "finish_end_transaction");
4042
4043 //
4044 // setup for looping through all the blhdr's.
4045 //
4046 for (blhdr = tr->blhdr; blhdr; blhdr = next) {
4047 uint16_t num_blocks;
4048
4049 /*
4050 * grab this info ahead of issuing the buf_bawrites...
4051 * once the last one goes out, its possible for blhdr
4052 * to be freed (especially if we get preempted) before
4053 * we do the last check of num_blocks or
4054 * grab the next blhdr pointer...
4055 */
4056 next = (block_list_header *)((long)blhdr->binfo[0].bnum);
4057 num_blocks = blhdr->num_blocks;
4058
4059 /*
4060 * we can re-order the buf ptrs because everything is written out already
4061 */
4062 qsort(&blhdr->binfo[1], num_blocks-1, sizeof(block_info), journal_binfo_cmp);
4063
4064 /*
4065 * need to make sure that the loop issuing the buf_bawrite's
4066 * does not touch blhdr once the last buf_bawrite has been
4067 * issued... at that point, we no longer have a legitmate
4068 * reference on the associated storage since it will be
4069 * released upon the completion of that last buf_bawrite
4070 */
4071 for (i = num_blocks-1; i >= 1; i--) {
4072 if (blhdr->binfo[i].bnum != (off_t)-1)
4073 break;
4074 num_blocks--;
4075 }
4076 for (i = 1; i < num_blocks; i++) {
4077
4078 if ((bp = blhdr->binfo[i].u.bp)) {
4079 vp = buf_vnode(bp);
4080
4081 buf_bawrite(bp);
4082
4083 // this undoes the vnode_ref() in journal_modify_block_end()
4084 vnode_rele_ext(vp, 0, 1);
4085
4086 bufs_written++;
4087 }
4088 }
4089 }
4090 if (bufs_written == 0) {
4091 /*
4092 * since we didn't issue any buf_bawrite's, there is no
4093 * async trigger to cause the memory associated with this
4094 * transaction to be freed... so, move it to the garbage
4095 * list now
4096 */
4097 lock_oldstart(jnl);
4098
4099 tr->next = jnl->tr_freeme;
4100 jnl->tr_freeme = tr;
4101
4102 unlock_oldstart(jnl);
4103
4104 unlock_condition(jnl, &jnl->asyncIO);
4105 }
4106
4107 //printf("jnl: end_tr: tr @ 0x%x, jnl-blocks: 0x%llx - 0x%llx. exit!\n",
4108 // tr, tr->journal_start, tr->journal_end);
4109
4110 bad_journal:
4111 if (ret_val == -1) {
4112 /*
4113 * 'flush_aborted' is protected by the flushing condition... we need to
4114 * set it before dropping the condition so that it will be
4115 * noticed in 'end_transaction'... we add this additional
4116 * aborted condition so that we can drop the 'flushing' condition
4117 * before grabbing the journal lock... this avoids a deadlock
4118 * in 'end_transaction' which is holding the journal lock while
4119 * waiting for the 'flushing' condition to clear...
4120 * everyone else will notice the JOURNAL_INVALID flag
4121 */
4122 jnl->flush_aborted = TRUE;
4123
4124 unlock_condition(jnl, &jnl->flushing);
4125 lock_journal(jnl);
4126
4127 jnl->flags |= JOURNAL_INVALID;
4128 jnl->old_start[sizeof(jnl->old_start)/sizeof(jnl->old_start[0]) - 1] &= ~0x8000000000000000LL;
4129 abort_transaction(jnl, tr); // cleans up list of extents to be trimmed
4130
4131 unlock_journal(jnl);
4132 } else
4133 unlock_condition(jnl, &jnl->flushing);
4134
4135 KERNEL_DEBUG(0xbbbbc028|DBG_FUNC_END, jnl, tr, bufs_written, ret_val, 0);
4136
4137 return (ret_val);
4138 }
4139
4140
4141 static void
4142 lock_condition(journal *jnl, boolean_t *condition, const char *condition_name)
4143 {
4144
4145 KERNEL_DEBUG(0xbbbbc020|DBG_FUNC_START, jnl, condition, 0, 0, 0);
4146
4147 lock_flush(jnl);
4148
4149 while (*condition == TRUE)
4150 msleep(condition, &jnl->flock, PRIBIO, condition_name, NULL);
4151
4152 *condition = TRUE;
4153 unlock_flush(jnl);
4154
4155 KERNEL_DEBUG(0xbbbbc020|DBG_FUNC_END, jnl, condition, 0, 0, 0);
4156 }
4157
4158 static void
4159 wait_condition(journal *jnl, boolean_t *condition, const char *condition_name)
4160 {
4161
4162 if (*condition == FALSE)
4163 return;
4164
4165 KERNEL_DEBUG(0xbbbbc02c|DBG_FUNC_START, jnl, condition, 0, 0, 0);
4166
4167 lock_flush(jnl);
4168
4169 while (*condition == TRUE)
4170 msleep(condition, &jnl->flock, PRIBIO, condition_name, NULL);
4171
4172 unlock_flush(jnl);
4173
4174 KERNEL_DEBUG(0xbbbbc02c|DBG_FUNC_END, jnl, condition, 0, 0, 0);
4175 }
4176
4177 static void
4178 unlock_condition(journal *jnl, boolean_t *condition)
4179 {
4180 lock_flush(jnl);
4181
4182 *condition = FALSE;
4183 wakeup(condition);
4184
4185 unlock_flush(jnl);
4186 }
4187
4188 static void
4189 abort_transaction(journal *jnl, transaction *tr)
4190 {
4191 block_list_header *blhdr, *next;
4192
4193 // for each block list header, iterate over the blocks then
4194 // free up the memory associated with the block list.
4195 //
4196 // find each of the primary blocks (i.e. the list could
4197 // contain a mix of shadowed and real buf_t's depending
4198 // on when the abort condition was detected) and mark them
4199 // clean and locked in the cache... this at least allows
4200 // the FS a consistent view between it's incore data structures
4201 // and the meta-data held in the cache
4202 //
4203 KERNEL_DEBUG(0xbbbbc034|DBG_FUNC_START, jnl, tr, 0, 0, 0);
4204
4205 for (blhdr = tr->blhdr; blhdr; blhdr = next) {
4206 int i;
4207
4208 for (i = 1; i < blhdr->num_blocks; i++) {
4209 buf_t bp, tbp, sbp;
4210 vnode_t bp_vp;
4211 errno_t errno;
4212
4213 if (blhdr->binfo[i].bnum == (off_t)-1)
4214 continue;
4215
4216 tbp = blhdr->binfo[i].u.bp;
4217
4218 bp_vp = buf_vnode(tbp);
4219
4220 buf_setfilter(tbp, NULL, NULL, NULL, NULL);
4221
4222 if (buf_shadow(tbp))
4223 sbp = tbp;
4224 else
4225 sbp = NULL;
4226
4227 if (bp_vp) {
4228 errno = buf_meta_bread(bp_vp,
4229 buf_lblkno(tbp),
4230 buf_size(tbp),
4231 NOCRED,
4232 &bp);
4233 if (errno == 0) {
4234 if (sbp == NULL && bp != tbp && (buf_flags(tbp) & B_LOCKED)) {
4235 panic("jnl: abort_tr: got back a different bp! (bp %p should be %p, jnl %p\n",
4236 bp, tbp, jnl);
4237 }
4238 /*
4239 * once the journal has been marked INVALID and aborted,
4240 * NO meta data can be written back to the disk, so
4241 * mark the buf_t clean and make sure it's locked in the cache
4242 * note: if we found a shadow, the real buf_t needs to be relocked
4243 */
4244 buf_setflags(bp, B_LOCKED);
4245 buf_markclean(bp);
4246 buf_brelse(bp);
4247
4248 KERNEL_DEBUG(0xbbbbc034|DBG_FUNC_NONE, jnl, tr, bp, 0, 0);
4249
4250 /*
4251 * this undoes the vnode_ref() in journal_modify_block_end()
4252 */
4253 vnode_rele_ext(bp_vp, 0, 1);
4254 } else {
4255 printf("jnl: %s: abort_tr: could not find block %lld vp %p!\n",
4256 jnl->jdev_name, blhdr->binfo[i].bnum, tbp);
4257 if (bp) {
4258 buf_brelse(bp);
4259 }
4260 }
4261 }
4262 if (sbp)
4263 buf_brelse(sbp);
4264 }
4265 next = (block_list_header *)((long)blhdr->binfo[0].bnum);
4266
4267 // we can free blhdr here since we won't need it any more
4268 blhdr->binfo[0].bnum = 0xdeadc0de;
4269 kmem_free(kernel_map, (vm_offset_t)blhdr, tr->tbuffer_size);
4270 }
4271
4272 /*
4273 * If the transaction we're aborting was the async transaction, then
4274 * tell the current transaction that there is no pending trim
4275 * any more.
4276 */
4277 lck_rw_lock_exclusive(&jnl->trim_lock);
4278 if (jnl->async_trim == &tr->trim)
4279 jnl->async_trim = NULL;
4280 lck_rw_unlock_exclusive(&jnl->trim_lock);
4281
4282
4283 if (tr->trim.extents) {
4284 kfree(tr->trim.extents, tr->trim.allocated_count * sizeof(dk_extent_t));
4285 }
4286 tr->trim.allocated_count = 0;
4287 tr->trim.extent_count = 0;
4288 tr->trim.extents = NULL;
4289 tr->tbuffer = NULL;
4290 tr->blhdr = NULL;
4291 tr->total_bytes = 0xdbadc0de;
4292 FREE_ZONE(tr, sizeof(transaction), M_JNL_TR);
4293
4294 KERNEL_DEBUG(0xbbbbc034|DBG_FUNC_END, jnl, tr, 0, 0, 0);
4295 }
4296
4297
4298 int
4299 journal_end_transaction(journal *jnl)
4300 {
4301 int ret;
4302 transaction *tr;
4303
4304 CHECK_JOURNAL(jnl);
4305
4306 free_old_stuff(jnl);
4307
4308 if ((jnl->flags & JOURNAL_INVALID) && jnl->owner == NULL) {
4309 return 0;
4310 }
4311
4312 if (jnl->owner != current_thread()) {
4313 panic("jnl: end_tr: I'm not the owner! jnl %p, owner %p, curact %p\n",
4314 jnl, jnl->owner, current_thread());
4315 }
4316 jnl->nested_count--;
4317
4318 if (jnl->nested_count > 0) {
4319 return 0;
4320 } else if (jnl->nested_count < 0) {
4321 panic("jnl: jnl @ %p has negative nested count (%d). bad boy.\n", jnl, jnl->nested_count);
4322 }
4323
4324 if (jnl->flags & JOURNAL_INVALID) {
4325 if (jnl->active_tr) {
4326 if (jnl->cur_tr != NULL) {
4327 panic("jnl: journal @ %p has active tr (%p) and cur tr (%p)\n",
4328 jnl, jnl->active_tr, jnl->cur_tr);
4329 }
4330 tr = jnl->active_tr;
4331 jnl->active_tr = NULL;
4332
4333 abort_transaction(jnl, tr);
4334 }
4335 jnl->owner = NULL;
4336 unlock_journal(jnl);
4337
4338 return EINVAL;
4339 }
4340
4341 tr = jnl->active_tr;
4342 CHECK_TRANSACTION(tr);
4343
4344 // clear this out here so that when check_free_space() calls
4345 // the FS flush function, we don't panic in journal_flush()
4346 // if the FS were to call that. note: check_free_space() is
4347 // called from end_transaction().
4348 //
4349 jnl->active_tr = NULL;
4350 ret = end_transaction(tr, 0, NULL, NULL, TRUE, FALSE);
4351
4352 return ret;
4353 }
4354
4355
4356 /*
4357 * Flush the contents of the journal to the disk.
4358 *
4359 * Input:
4360 * wait_for_IO -
4361 * If TRUE, wait to write in-memory journal to the disk
4362 * consistently, and also wait to write all asynchronous
4363 * metadata blocks to its corresponding locations
4364 * consistently on the disk. This means that the journal
4365 * is empty at this point and does not contain any
4366 * transactions. This is overkill in normal scenarios
4367 * but is useful whenever the metadata blocks are required
4368 * to be consistent on-disk instead of just the journal
4369 * being consistent; like before live verification
4370 * and live volume resizing.
4371 *
4372 * If FALSE, only wait to write in-memory journal to the
4373 * disk consistently. This means that the journal still
4374 * contains uncommitted transactions and the file system
4375 * metadata blocks in the journal transactions might be
4376 * written asynchronously to the disk. But there is no
4377 * guarantee that they are written to the disk before
4378 * returning to the caller. Note that this option is
4379 * sufficient for file system data integrity as it
4380 * guarantees consistent journal content on the disk.
4381 */
4382 int
4383 journal_flush(journal *jnl, boolean_t wait_for_IO)
4384 {
4385 boolean_t drop_lock = FALSE;
4386
4387 CHECK_JOURNAL(jnl);
4388
4389 free_old_stuff(jnl);
4390
4391 if (jnl->flags & JOURNAL_INVALID) {
4392 return -1;
4393 }
4394
4395 KERNEL_DEBUG(DBG_JOURNAL_FLUSH | DBG_FUNC_START, jnl, 0, 0, 0, 0);
4396
4397 if (jnl->owner != current_thread()) {
4398 lock_journal(jnl);
4399 drop_lock = TRUE;
4400 }
4401
4402 // if we're not active, flush any buffered transactions
4403 if (jnl->active_tr == NULL && jnl->cur_tr) {
4404 transaction *tr = jnl->cur_tr;
4405
4406 jnl->cur_tr = NULL;
4407
4408 if (wait_for_IO) {
4409 wait_condition(jnl, &jnl->flushing, "journal_flush");
4410 wait_condition(jnl, &jnl->asyncIO, "journal_flush");
4411 }
4412 /*
4413 * "end_transction" will wait for any current async flush
4414 * to complete, before flushing "cur_tr"... because we've
4415 * specified the 'must_wait' arg as TRUE, it will then
4416 * synchronously flush the "cur_tr"
4417 */
4418 end_transaction(tr, 1, NULL, NULL, drop_lock, TRUE); // force it to get flushed
4419
4420 } else {
4421 if (drop_lock == TRUE) {
4422 unlock_journal(jnl);
4423 }
4424
4425 /* Because of pipelined journal, the journal transactions
4426 * might be in process of being flushed on another thread.
4427 * If there is nothing to flush currently, we should
4428 * synchronize ourselves with the pipelined journal thread
4429 * to ensure that all inflight transactions, if any, are
4430 * flushed before we return success to caller.
4431 */
4432 wait_condition(jnl, &jnl->flushing, "journal_flush");
4433 }
4434 if (wait_for_IO) {
4435 wait_condition(jnl, &jnl->asyncIO, "journal_flush");
4436 }
4437
4438 KERNEL_DEBUG(DBG_JOURNAL_FLUSH | DBG_FUNC_END, jnl, 0, 0, 0, 0);
4439
4440 return 0;
4441 }
4442
4443 int
4444 journal_active(journal *jnl)
4445 {
4446 if (jnl->flags & JOURNAL_INVALID) {
4447 return -1;
4448 }
4449
4450 return (jnl->active_tr == NULL) ? 0 : 1;
4451 }
4452
4453 void *
4454 journal_owner(journal *jnl)
4455 {
4456 return jnl->owner;
4457 }
4458
4459 int journal_uses_fua(journal *jnl)
4460 {
4461 if (jnl->flags & JOURNAL_DO_FUA_WRITES)
4462 return 1;
4463 return 0;
4464 }
4465
4466 /*
4467 * Relocate the journal.
4468 *
4469 * You provide the new starting offset and size for the journal. You may
4470 * optionally provide a new tbuffer_size; passing zero defaults to not
4471 * changing the tbuffer size except as needed to fit within the new journal
4472 * size.
4473 *
4474 * You must have already started a transaction. The transaction may contain
4475 * modified blocks (such as those needed to deallocate the old journal,
4476 * allocate the new journal, and update the location and size of the journal
4477 * in filesystem-private structures). Any transactions prior to the active
4478 * transaction will be flushed to the old journal. The new journal will be
4479 * initialized, and the blocks from the active transaction will be written to
4480 * the new journal.
4481 *
4482 * The caller will need to update the structures that identify the location
4483 * and size of the journal. These updates should be made in the supplied
4484 * callback routine. These updates must NOT go into a transaction. You should
4485 * force these updates to the media before returning from the callback. In the
4486 * even of a crash, either the old journal will be found, with an empty journal,
4487 * or the new journal will be found with the contents of the active transaction.
4488 *
4489 * Upon return from the callback, the blocks from the active transaction are
4490 * written to their normal locations on disk.
4491 *
4492 * (Remember that we have to ensure that blocks get committed to the journal
4493 * before being committed to their normal locations. But the blocks don't count
4494 * as committed until the new journal is pointed at.)
4495 *
4496 * Upon return, there is still an active transaction: newly allocated, and
4497 * with no modified blocks. Call journal_end_transaction as normal. You may
4498 * modifiy additional blocks before calling journal_end_transaction, and those
4499 * blocks will (eventually) go to the relocated journal.
4500 *
4501 * Inputs:
4502 * jnl The (opened) journal to relocate.
4503 * offset The new journal byte offset (from start of the journal device).
4504 * journal_size The size, in bytes, of the new journal.
4505 * tbuffer_size The new desired transaction buffer size. Pass zero to keep
4506 * the same size as the current journal. The size will be
4507 * modified as needed to fit the new journal.
4508 * callback Routine called after the new journal has been initialized,
4509 * and the active transaction written to the new journal, but
4510 * before the blocks are written to their normal locations.
4511 * Pass NULL for no callback.
4512 * callback_arg An argument passed to the callback routine.
4513 *
4514 * Result:
4515 * 0 No errors
4516 * EINVAL The offset is not block aligned
4517 * EINVAL The journal_size is not a multiple of the block size
4518 * EINVAL The journal is invalid
4519 * (any) An error returned by journal_flush.
4520 *
4521 */
4522 int journal_relocate(journal *jnl, off_t offset, off_t journal_size, int32_t tbuffer_size,
4523 errno_t (*callback)(void *), void *callback_arg)
4524 {
4525 int ret;
4526 transaction *tr;
4527 size_t i = 0;
4528
4529 /*
4530 * Sanity check inputs, and adjust the size of the transaction buffer.
4531 */
4532 if ((offset % jnl->jhdr->jhdr_size) != 0) {
4533 printf("jnl: %s: relocate: offset 0x%llx is not an even multiple of block size 0x%x\n",
4534 jnl->jdev_name, offset, jnl->jhdr->jhdr_size);
4535 return EINVAL;
4536 }
4537 if ((journal_size % jnl->jhdr->jhdr_size) != 0) {
4538 printf("jnl: %s: relocate: journal size 0x%llx is not an even multiple of block size 0x%x\n",
4539 jnl->jdev_name, journal_size, jnl->jhdr->jhdr_size);
4540 return EINVAL;
4541 }
4542
4543 CHECK_JOURNAL(jnl);
4544
4545 /* Guarantee we own the active transaction. */
4546 if (jnl->flags & JOURNAL_INVALID) {
4547 return EINVAL;
4548 }
4549 if (jnl->owner != current_thread()) {
4550 panic("jnl: relocate: Not the owner! jnl %p, owner %p, curact %p\n",
4551 jnl, jnl->owner, current_thread());
4552 }
4553
4554 if (tbuffer_size == 0)
4555 tbuffer_size = jnl->tbuffer_size;
4556 size_up_tbuffer(jnl, tbuffer_size, jnl->jhdr->jhdr_size);
4557
4558 /*
4559 * Flush any non-active transactions. We have to temporarily hide the
4560 * active transaction to make journal_flush flush out non-active but
4561 * current (unwritten) transactions.
4562 */
4563 tr = jnl->active_tr;
4564 CHECK_TRANSACTION(tr);
4565 jnl->active_tr = NULL;
4566 ret = journal_flush(jnl, TRUE);
4567 jnl->active_tr = tr;
4568
4569 if (ret) {
4570 return ret;
4571 }
4572 wait_condition(jnl, &jnl->flushing, "end_transaction");
4573
4574 /*
4575 * At this point, we have completely flushed the contents of the current
4576 * journal to disk (and have asynchronously written all of the txns to
4577 * their actual desired locations). As a result, we can (and must) clear
4578 * out the old_start array. If we do not, then if the last written transaction
4579 * started at the beginning of the journal (starting 1 block into the
4580 * journal file) it could confuse the buffer_flushed callback. This is
4581 * because we're about to reset the start/end pointers of the journal header
4582 * below.
4583 */
4584 lock_oldstart(jnl);
4585 for (i = 0; i < sizeof (jnl->old_start) / sizeof(jnl->old_start[0]); i++) {
4586 jnl->old_start[i] = 0;
4587 }
4588 unlock_oldstart(jnl);
4589
4590 /* Update the journal's offset and size in memory. */
4591 jnl->jdev_offset = offset;
4592 jnl->jhdr->start = jnl->jhdr->end = jnl->jhdr->jhdr_size;
4593 jnl->jhdr->size = journal_size;
4594 jnl->active_start = jnl->jhdr->start;
4595
4596 /*
4597 * Force the active transaction to be written to the new journal. Call the
4598 * supplied callback after the blocks have been written to the journal, but
4599 * before they get written to their normal on-disk locations.
4600 */
4601 jnl->active_tr = NULL;
4602 ret = end_transaction(tr, 1, callback, callback_arg, FALSE, TRUE);
4603 if (ret) {
4604 printf("jnl: %s: relocate: end_transaction failed (%d)\n", jnl->jdev_name, ret);
4605 goto bad_journal;
4606 }
4607
4608 /*
4609 * Create a new, empty transaction to be the active transaction. This way
4610 * our caller can use journal_end_transaction as usual.
4611 */
4612 ret = journal_allocate_transaction(jnl);
4613 if (ret) {
4614 printf("jnl: %s: relocate: could not allocate new transaction (%d)\n", jnl->jdev_name, ret);
4615 goto bad_journal;
4616 }
4617
4618 return 0;
4619
4620 bad_journal:
4621 jnl->flags |= JOURNAL_INVALID;
4622 abort_transaction(jnl, tr);
4623 return ret;
4624 }
4625
4626
4627 #else // !JOURNALING - so provide stub functions
4628
4629 int journal_uses_fua(__unused journal *jnl)
4630 {
4631 return 0;
4632 }
4633
4634 journal *
4635 journal_create(__unused struct vnode *jvp,
4636 __unused off_t offset,
4637 __unused off_t journal_size,
4638 __unused struct vnode *fsvp,
4639 __unused size_t min_fs_blksz,
4640 __unused int32_t flags,
4641 __unused int32_t tbuffer_size,
4642 __unused void (*flush)(void *arg),
4643 __unused void *arg)
4644 {
4645 return NULL;
4646 }
4647
4648 journal *
4649 journal_open(__unused struct vnode *jvp,
4650 __unused off_t offset,
4651 __unused off_t journal_size,
4652 __unused struct vnode *fsvp,
4653 __unused size_t min_fs_blksz,
4654 __unused int32_t flags,
4655 __unused int32_t tbuffer_size,
4656 __unused void (*flush)(void *arg),
4657 __unused void *arg)
4658 {
4659 return NULL;
4660 }
4661
4662
4663 int
4664 journal_modify_block_start(__unused journal *jnl, __unused struct buf *bp)
4665 {
4666 return EINVAL;
4667 }
4668
4669 int
4670 journal_modify_block_end(__unused journal *jnl,
4671 __unused struct buf *bp,
4672 __unused void (*func)(struct buf *bp, void *arg),
4673 __unused void *arg)
4674 {
4675 return EINVAL;
4676 }
4677
4678 int
4679 journal_kill_block(__unused journal *jnl, __unused struct buf *bp)
4680 {
4681 return EINVAL;
4682 }
4683
4684 int journal_relocate(__unused journal *jnl,
4685 __unused off_t offset,
4686 __unused off_t journal_size,
4687 __unused int32_t tbuffer_size,
4688 __unused errno_t (*callback)(void *),
4689 __unused void *callback_arg)
4690 {
4691 return EINVAL;
4692 }
4693
4694 void
4695 journal_close(__unused journal *jnl)
4696 {
4697 }
4698
4699 int
4700 journal_start_transaction(__unused journal *jnl)
4701 {
4702 return EINVAL;
4703 }
4704
4705 int
4706 journal_end_transaction(__unused journal *jnl)
4707 {
4708 return EINVAL;
4709 }
4710
4711 int
4712 journal_flush(__unused journal *jnl, __unused boolean_t wait_for_IO)
4713 {
4714 return EINVAL;
4715 }
4716
4717 int
4718 journal_is_clean(__unused struct vnode *jvp,
4719 __unused off_t offset,
4720 __unused off_t journal_size,
4721 __unused struct vnode *fsvp,
4722 __unused size_t min_fs_block_size)
4723 {
4724 return 0;
4725 }
4726
4727
4728 void *
4729 journal_owner(__unused journal *jnl)
4730 {
4731 return NULL;
4732 }
4733 #endif // !JOURNALING