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