-
Notifications
You must be signed in to change notification settings - Fork 10
/
hfs_journal.c
4946 lines (4134 loc) · 152 KB
/
hfs_journal.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2002-2015 Apple Inc. All rights reserved.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. The rights granted to you under the License
* may not be used to create, or enable the creation or redistribution of,
* unlawful or unlicensed copies of an Apple operating system, or to
* circumvent, violate, or enable the circumvention or violation of, any
* terms of an Apple operating system software license agreement.
*
* Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_END@
*/
//
// This file implements a simple write-ahead journaling layer.
// In theory any file system can make use of it by calling these
// functions when the fs wants to modify meta-data blocks. See
// hfs_journal.h for a more detailed description of the api and
// data structures.
//
// Dominic Giampaolo (dbg@apple.com)
//
#ifdef KERNEL
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/stat.h>
#include <sys/namei.h>
#include <sys/ioctl.h>
#include <sys/ubc.h>
#include <sys/malloc.h>
#include <kern/task.h>
#include <kern/thread.h>
#include <sys/disk.h>
#include <sys/kdebug.h>
#include <sys/kpi_private.h>
#include <sys/sysctl.h>
#include <sys/systm.h>
#include <miscfs/specfs/specdev.h>
#include <libkern/OSAtomic.h> /* OSAddAtomic */
#include "hfs.h"
kern_return_t thread_terminate(thread_t);
/*
* Set sysctl vfs.generic.jnl.kdebug.trim=1 to enable KERNEL_DEBUG_CONSTANT
* logging of trim-related calls within the journal. (They're
* disabled by default because there can be a lot of these events,
* and we don't want to overwhelm the kernel debug buffer. If you
* want to watch these events in particular, just set the sysctl.)
*/
static int jnl_kdebug = 0;
HFS_SYSCTL(NODE, _vfs_generic_hfs, OID_AUTO, jnl, CTLFLAG_RW|CTLFLAG_LOCKED, 0, "Journal")
HFS_SYSCTL(NODE, _vfs_generic_hfs_jnl, OID_AUTO, kdebug, CTLFLAG_RW|CTLFLAG_LOCKED, 0, "Journal kdebug")
HFS_SYSCTL(INT, _vfs_generic_hfs_jnl_kdebug, OID_AUTO, trim, CTLFLAG_RW|CTLFLAG_LOCKED, &jnl_kdebug, 0, "Enable kdebug logging for journal TRIM")
#define DBG_JOURNAL_FLUSH FSDBG_CODE(DBG_JOURNAL, 1)
#define DBG_JOURNAL_TRIM_ADD FSDBG_CODE(DBG_JOURNAL, 2)
#define DBG_JOURNAL_TRIM_REMOVE FSDBG_CODE(DBG_JOURNAL, 3)
#define DBG_JOURNAL_TRIM_REMOVE_PENDING FSDBG_CODE(DBG_JOURNAL, 4)
#define DBG_JOURNAL_TRIM_REALLOC FSDBG_CODE(DBG_JOURNAL, 5)
#define DBG_JOURNAL_TRIM_FLUSH FSDBG_CODE(DBG_JOURNAL, 6)
#define DBG_JOURNAL_TRIM_UNMAP FSDBG_CODE(DBG_JOURNAL, 7)
/*
* Cap the journal max size to 2GB. On HFS, it will attempt to occupy
* a full allocation block if the current size is smaller than the allocation
* block on which it resides. Once we hit the exabyte filesystem range, then
* it will use 2GB allocation blocks. As a result, make the cap 2GB.
*/
#define MAX_JOURNAL_SIZE 0x80000000U
#include <mach/machine/sdt.h>
#else
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdarg.h>
#include <sys/types.h>
#include "compat.h"
#endif /* KERNEL */
#include "hfs_journal.h"
#include <sys/kdebug.h>
//
// By default, we grow the list of extents to trim by 4K at a time.
// We'll opt to flush a transaction if it contains at least
// JOURNAL_FLUSH_TRIM_EXTENTS extents to be trimmed (even if the number
// of modified blocks is small).
//
enum {
JOURNAL_DEFAULT_TRIM_BYTES = 4096,
JOURNAL_DEFAULT_TRIM_EXTENTS = JOURNAL_DEFAULT_TRIM_BYTES / sizeof(dk_extent_t),
JOURNAL_FLUSH_TRIM_EXTENTS = JOURNAL_DEFAULT_TRIM_EXTENTS * 15 / 16
};
unsigned int jnl_trim_flush_limit = JOURNAL_FLUSH_TRIM_EXTENTS;
HFS_SYSCTL(UINT, _vfs_generic_hfs_jnl, OID_AUTO, trim_flush, CTLFLAG_RW, &jnl_trim_flush_limit, 0, "number of trimmed extents to cause a journal flush")
// number of bytes to checksum in a block_list_header
// NOTE: this should be enough to clear out the header
// fields as well as the first entry of binfo[]
#define BLHDR_CHECKSUM_SIZE 32
static void lock_condition(journal *jnl, boolean_t *condition, const char *condition_name);
static void wait_condition(journal *jnl, boolean_t *condition, const char *condition_name);
static void unlock_condition(journal *jnl, boolean_t *condition);
static void finish_end_thread(transaction *tr);
static void write_header_thread(journal *jnl);
static int finish_end_transaction(transaction *tr, errno_t (*callback)(void*), void *callback_arg);
static int end_transaction(transaction *tr, int force_it, errno_t (*callback)(void*), void *callback_arg, boolean_t drop_lock, boolean_t must_wait);
static void abort_transaction(journal *jnl, transaction *tr);
static void dump_journal(journal *jnl);
static __inline__ void lock_oldstart(journal *jnl);
static __inline__ void unlock_oldstart(journal *jnl);
static __inline__ void lock_flush(journal *jnl);
static __inline__ void unlock_flush(journal *jnl);
//
// 3105942 - Coalesce writes to the same block on journal replay
//
typedef struct bucket {
off_t block_num;
uint32_t jnl_offset;
uint32_t block_size;
int32_t cksum;
} bucket;
#define STARTING_BUCKETS 256
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);
static int grow_table(struct bucket **buf_ptr, int num_buckets, int new_size);
static int lookup_bucket(struct bucket **buf_ptr, off_t block_num, int num_full);
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);
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);
#define CHECK_JOURNAL(jnl) \
do { \
if (jnl == NULL) { \
panic("%s:%d: null journal ptr?\n", __FILE__, __LINE__); \
} \
if (jnl->jdev == NULL) { \
panic("%s:%d: jdev is null!\n", __FILE__, __LINE__); \
} \
if (jnl->fsdev == NULL) { \
panic("%s:%d: fsdev is null!\n", __FILE__, __LINE__); \
} \
if (jnl->jhdr->magic != JOURNAL_HEADER_MAGIC) { \
panic("%s:%d: jhdr magic corrupted (0x%x != 0x%x)\n", \
__FILE__, __LINE__, jnl->jhdr->magic, JOURNAL_HEADER_MAGIC); \
} \
if ( jnl->jhdr->start <= 0 \
|| jnl->jhdr->start > jnl->jhdr->size) { \
panic("%s:%d: jhdr start looks bad (0x%llx max size 0x%llx)\n", \
__FILE__, __LINE__, jnl->jhdr->start, jnl->jhdr->size); \
} \
if ( jnl->jhdr->end <= 0 \
|| jnl->jhdr->end > jnl->jhdr->size) { \
panic("%s:%d: jhdr end looks bad (0x%llx max size 0x%llx)\n", \
__FILE__, __LINE__, jnl->jhdr->end, jnl->jhdr->size); \
} \
} while(0)
#define CHECK_TRANSACTION(tr) \
do { \
if (tr == NULL) { \
panic("%s:%d: null transaction ptr?\n", __FILE__, __LINE__); \
} \
if (tr->jnl == NULL) { \
panic("%s:%d: null tr->jnl ptr?\n", __FILE__, __LINE__); \
} \
if (tr->blhdr != (block_list_header *)tr->tbuffer) { \
panic("%s:%d: blhdr (%p) != tbuffer (%p)\n", __FILE__, __LINE__, tr->blhdr, tr->tbuffer); \
} \
if (tr->total_bytes < 0) { \
panic("%s:%d: tr total_bytes looks bad: %d\n", __FILE__, __LINE__, tr->total_bytes); \
} \
if (tr->journal_start < 0) { \
panic("%s:%d: tr journal start looks bad: 0x%llx\n", __FILE__, __LINE__, tr->journal_start); \
} \
if (tr->journal_end < 0) { \
panic("%s:%d: tr journal end looks bad: 0x%llx\n", __FILE__, __LINE__, tr->journal_end); \
} \
if (tr->blhdr && (tr->blhdr->max_blocks <= 0 || tr->blhdr->max_blocks > (tr->jnl->jhdr->size/tr->jnl->jhdr->jhdr_size))) { \
panic("%s:%d: tr blhdr max_blocks looks bad: %d\n", __FILE__, __LINE__, tr->blhdr->max_blocks); \
} \
} while(0)
#define BLHDR_TO_BLHDRIM(hdr) (block_list_header_in_memory *)((char *)(hdr) - offsetof(block_list_header_in_memory, blhdr))
//
// this isn't a great checksum routine but it will do for now.
// we use it to checksum the journal header and the block list
// headers that are at the start of each transaction.
//
static unsigned int
calc_checksum(const char *ptr, int len)
{
int i;
unsigned int cksum=0;
// this is a lame checksum but for now it'll do
for(i = 0; i < len; i++, ptr++) {
cksum = (cksum << 8) ^ (cksum + *(unsigned char *)ptr);
}
return (~cksum);
}
//
// Journal Locking
//
lck_grp_attr_t * jnl_group_attr;
lck_attr_t * jnl_lock_attr;
lck_grp_t * jnl_mutex_group;
void
journal_init(void)
{
jnl_lock_attr = lck_attr_alloc_init();
jnl_group_attr = lck_grp_attr_alloc_init();
jnl_mutex_group = lck_grp_alloc_init("jnl-mutex", jnl_group_attr);
}
__inline__ void
journal_lock(journal *jnl)
{
lck_mtx_lock(&jnl->jlock);
if (jnl->owner) {
panic ("jnl: owner is %p, expected NULL\n", jnl->owner);
}
jnl->owner = current_thread();
}
__inline__ void
journal_unlock(journal *jnl)
{
jnl->owner = NULL;
lck_mtx_unlock(&jnl->jlock);
}
static __inline__ void
lock_flush(journal *jnl)
{
lck_mtx_lock(&jnl->flock);
}
static __inline__ void
unlock_flush(journal *jnl)
{
lck_mtx_unlock(&jnl->flock);
}
static __inline__ void
lock_oldstart(journal *jnl)
{
lck_mtx_lock(&jnl->old_start_lock);
}
static __inline__ void
unlock_oldstart(journal *jnl)
{
lck_mtx_unlock(&jnl->old_start_lock);
}
#define JNL_WRITE 0x0001
#define JNL_READ 0x0002
#define JNL_HEADER 0x8000
//
// This function sets up a fake buf and passes it directly to the
// journal device strategy routine (so that it won't get cached in
// the block cache.
//
// It also handles range checking the i/o so that we don't write
// outside the journal boundaries and it will wrap the i/o back
// to the beginning if necessary (skipping over the journal header)
//
static size_t
do_journal_io(journal *jnl, off_t *offset, void *data, size_t len, int direction)
{
int err;
off_t curlen = len;
size_t io_sz = 0;
buf_t bp;
off_t max_iosize;
bufattr_t bap;
boolean_t was_vm_privileged = FALSE;
boolean_t need_vm_privilege = FALSE;
if (vfs_isswapmount(jnl->fsmount))
need_vm_privilege = TRUE;
if (*offset < 0 || *offset > jnl->jhdr->size) {
panic("jnl: do_jnl_io: bad offset 0x%llx (max 0x%llx)\n", *offset, jnl->jhdr->size);
}
if (direction & JNL_WRITE)
max_iosize = jnl->max_write_size;
else if (direction & JNL_READ)
max_iosize = jnl->max_read_size;
else
max_iosize = 128 * 1024;
again:
bp = buf_alloc(jnl->jdev);
if (*offset + curlen > jnl->jhdr->size && *offset != 0 && jnl->jhdr->size != 0) {
if (*offset == jnl->jhdr->size) {
*offset = jnl->jhdr->jhdr_size;
} else {
curlen = jnl->jhdr->size - *offset;
}
}
if (curlen > max_iosize) {
curlen = max_iosize;
}
if (curlen <= 0) {
panic("jnl: do_jnl_io: curlen == %lld, offset 0x%llx len %zd\n", curlen, *offset, len);
}
if (*offset == 0 && (direction & JNL_HEADER) == 0) {
panic("jnl: request for i/o to jnl-header without JNL_HEADER flag set! (len %lld, data %p)\n", curlen, data);
}
/*
* As alluded to in the block comment at the top of the function, we use a "fake" iobuf
* here and issue directly to the disk device that the journal protects since we don't
* want this to enter the block cache. As a result, we lose the ability to mark it
* as a metadata buf_t for the layers below us that may care. If we were to
* simply attach the B_META flag into the b_flags this may confuse things further
* since this is an iobuf, not a metadata buffer.
*
* To address this, we use the extended bufattr struct embedded in the bp.
* Explicitly mark the buf here as a metadata buffer in its bufattr flags.
*/
bap = buf_attr(bp);
bufattr_markmeta(bap);
if (direction & JNL_READ)
buf_setflags(bp, B_READ);
else {
/*
* don't have to set any flags
*/
vnode_startwrite(jnl->jdev);
}
buf_setsize(bp, curlen);
buf_setcount(bp, curlen);
buf_setdataptr(bp, (uintptr_t)data);
buf_setblkno(bp, (daddr64_t) ((jnl->jdev_offset + *offset) / (off_t)jnl->jhdr->jhdr_size));
buf_setlblkno(bp, (daddr64_t) ((jnl->jdev_offset + *offset) / (off_t)jnl->jhdr->jhdr_size));
if ((direction & JNL_WRITE) && (jnl->flags & JOURNAL_DO_FUA_WRITES)) {
buf_markfua(bp);
}
if (need_vm_privilege == TRUE) {
/*
* if we block waiting for memory, and there is enough pressure to
* cause us to try and create a new swap file, we may end up deadlocking
* due to waiting for the journal on the swap file creation path...
* by making ourselves vm_privileged, we give ourselves the best chance
* of not blocking
*/
was_vm_privileged = set_vm_privilege(TRUE);
}
DTRACE_IO1(journal__start, buf_t, bp);
err = VNOP_STRATEGY(bp);
if (!err) {
err = (int)buf_biowait(bp);
}
DTRACE_IO1(journal__done, buf_t, bp);
if (need_vm_privilege == TRUE && was_vm_privileged == FALSE)
set_vm_privilege(FALSE);
buf_free(bp);
if (err) {
printf("jnl: %s: do_jnl_io: strategy err 0x%x\n", jnl->jdev_name, err);
return 0;
}
*offset += curlen;
io_sz += curlen;
if (io_sz != len) {
// handle wrap-around
data = (char *)data + curlen;
curlen = len - io_sz;
if (*offset >= jnl->jhdr->size) {
*offset = jnl->jhdr->jhdr_size;
}
goto again;
}
return io_sz;
}
static size_t
read_journal_data(journal *jnl, off_t *offset, void *data, size_t len)
{
return do_journal_io(jnl, offset, data, len, JNL_READ);
}
static size_t
write_journal_data(journal *jnl, off_t *offset, void *data, size_t len)
{
return do_journal_io(jnl, offset, data, len, JNL_WRITE);
}
static size_t
read_journal_header(journal *jnl, void *data, size_t len)
{
off_t hdr_offset = 0;
return do_journal_io(jnl, &hdr_offset, data, len, JNL_READ|JNL_HEADER);
}
static int
write_journal_header(journal *jnl, int updating_start, uint32_t sequence_num)
{
static int num_err_prints = 0;
int ret=0;
off_t jhdr_offset = 0;
//
// Flush the track cache if we're not doing force-unit-access
// writes.
//
if (!updating_start && (jnl->flags & JOURNAL_DO_FUA_WRITES) == 0) {
dk_synchronize_t sync_request = {
.options = DK_SYNCHRONIZE_OPTION_BARRIER,
};
/*
* If device doesn't support barrier-only flush, or
* the journal is on a different device, use full flush.
*/
if (!(jnl->flags & JOURNAL_FEATURE_BARRIER) || (jnl->jdev != jnl->fsdev)) {
sync_request.options = 0;
jnl->flush_counter++;
}
ret = VNOP_IOCTL(jnl->jdev, DKIOCSYNCHRONIZE, (caddr_t)&sync_request, FWRITE, vfs_context_kernel());
}
if (ret != 0) {
//
// Only print this error if it's a different error than the
// previous one, or if it's the first time for this device
// or if the total number of printfs is less than 25. We
// allow for up to 25 printfs to insure that some make it
// into the on-disk syslog. Otherwise if we only printed
// one, it's possible it would never make it to the syslog
// for the root volume and that makes debugging hard.
//
if ( ret != jnl->last_flush_err
|| (jnl->flags & JOURNAL_FLUSHCACHE_ERR) == 0
|| num_err_prints++ < 25) {
printf("jnl: %s: flushing fs disk buffer returned 0x%x\n", jnl->jdev_name, ret);
jnl->flags |= JOURNAL_FLUSHCACHE_ERR;
jnl->last_flush_err = ret;
}
}
jnl->jhdr->sequence_num = sequence_num;
jnl->jhdr->checksum = 0;
jnl->jhdr->checksum = calc_checksum((char *)jnl->jhdr, JOURNAL_HEADER_CKSUM_SIZE);
if (do_journal_io(jnl, &jhdr_offset, jnl->header_buf, jnl->jhdr->jhdr_size, JNL_WRITE|JNL_HEADER) != (size_t)jnl->jhdr->jhdr_size) {
printf("jnl: %s: write_journal_header: error writing the journal header!\n", jnl->jdev_name);
jnl->flags |= JOURNAL_INVALID;
return -1;
}
// If we're not doing force-unit-access writes, then we
// have to flush after writing the journal header so that
// a future transaction doesn't sneak out to disk before
// the header does and thus overwrite data that the old
// journal header refers to. Saw this exact case happen
// on an IDE bus analyzer with Larry Barras so while it
// may seem obscure, it's not.
//
if (updating_start && (jnl->flags & JOURNAL_DO_FUA_WRITES) == 0) {
dk_synchronize_t sync_request = {
.options = DK_SYNCHRONIZE_OPTION_BARRIER,
};
/*
* If device doesn't support barrier-only flush, or
* the journal is on a different device, use full flush.
*/
if (!(jnl->flags & JOURNAL_FEATURE_BARRIER) || (jnl->jdev != jnl->fsdev)) {
sync_request.options = 0;
jnl->flush_counter++;
}
VNOP_IOCTL(jnl->jdev, DKIOCSYNCHRONIZE, (caddr_t)&sync_request, FWRITE, vfs_context_kernel());
}
return 0;
}
static inline int32_t
journal_max_blocks(journal *jnl)
{
return ((jnl->jhdr->blhdr_size / sizeof(block_info)) - 1);
}
//
// this is a work function used to free up transactions that
// completed. they can't be free'd from buffer_flushed_callback
// because it is called from deep with the disk driver stack
// and thus can't do something that would potentially cause
// paging. it gets called by each of the journal api entry
// points so stuff shouldn't hang around for too long.
//
static void
free_old_stuff(journal *jnl)
{
transaction *tr, *next;
block_list_header *blhdr=NULL, *next_blhdr=NULL;
if (jnl->tr_freeme == NULL)
return;
lock_oldstart(jnl);
tr = jnl->tr_freeme;
jnl->tr_freeme = NULL;
unlock_oldstart(jnl);
for(; tr; tr=next) {
for (blhdr = tr->blhdr; blhdr; blhdr = next_blhdr) {
next_blhdr = (block_list_header *)((long)blhdr->binfo[0].bnum);
blhdr->binfo[0].bnum = 0xdeadc0de;
// get block_list_header_in_memory pointer, since this is what we really allocated in memory
block_list_header_in_memory *blhdrim = BLHDR_TO_BLHDRIM(blhdr);
hfs_free_data(blhdrim->buffers, tr->tbuffer_size - jnl->jhdr->blhdr_size);
hfs_delete_with_hdr(blhdrim, block_list_header_in_memory, block_info, journal_max_blocks(jnl));
KERNEL_DEBUG(0xbbbbc01c, jnl, tr, tr->tbuffer_size, 0, 0);
}
next = tr->next;
hfs_free_type(tr, transaction);
}
}
//
// This is our callback that lets us know when a buffer has been
// flushed to disk. It's called from deep within the driver stack
// and thus is quite limited in what it can do. Notably, it can
// not initiate any new i/o's or allocate/free memory.
//
static void
buffer_flushed_callback(struct buf *bp, void *arg)
{
transaction *tr;
journal *jnl;
transaction *ctr, *prev=NULL, *next;
size_t i;
int bufsize, amt_flushed, total_bytes;
//printf("jnl: buf flush: bp @ 0x%x l/blkno %qd/%qd vp 0x%x tr @ 0x%x\n",
// bp, buf_lblkno(bp), buf_blkno(bp), buf_vnode(bp), arg);
// snarf out the bits we want
bufsize = buf_size(bp);
tr = (transaction *)arg;
// then we've already seen it
if (tr == NULL) {
return;
}
if (tr->total_bytes == (int)0xfbadc0de) {
// then someone beat us to it...
return;
}
CHECK_TRANSACTION(tr);
jnl = tr->jnl;
CHECK_JOURNAL(jnl);
amt_flushed = tr->num_killed;
total_bytes = tr->total_bytes;
// update the number of blocks that have been flushed.
// this buf may represent more than one block so take
// that into account.
//
// OSAddAtomic() returns the value of tr->num_flushed before the add
//
amt_flushed += OSAddAtomic(bufsize, &tr->num_flushed);
// if this transaction isn't done yet, just return as
// there is nothing to do.
//
// NOTE: we are careful to not reference anything through
// the tr pointer after doing the OSAddAtomic(). if
// this if statement fails then we are the last one
// and then it's ok to dereference "tr".
//
if ((amt_flushed + bufsize) < total_bytes) {
return;
}
// this will single thread checking the transaction
lock_oldstart(jnl);
// re-check this after acquiring the lock
if (tr->total_bytes == (int)0xfbadc0de) {
// then someone beat us to it...
unlock_oldstart(jnl);
return;
}
// mark this so that we're the owner of dealing with the
// cleanup for this transaction
tr->total_bytes = 0xfbadc0de;
if (jnl->flags & JOURNAL_INVALID)
goto transaction_done;
//printf("jnl: tr 0x%x (0x%llx 0x%llx) in jnl 0x%x completed.\n",
// tr, tr->journal_start, tr->journal_end, jnl);
// find this entry in the old_start[] index and mark it completed
for(i = 0; i < sizeof(jnl->old_start)/sizeof(jnl->old_start[0]); i++) {
if ((off_t)(jnl->old_start[i] & ~(0x8000000000000000ULL)) == tr->journal_start) {
jnl->old_start[i] &= ~(0x8000000000000000ULL);
break;
}
}
if (i >= sizeof(jnl->old_start)/sizeof(jnl->old_start[0])) {
panic("jnl: buffer_flushed: did not find tr w/start @ %lld (tr %p, jnl %p)\n",
tr->journal_start, tr, jnl);
}
// if we are here then we need to update the journal header
// to reflect that this transaction is complete
if (tr->journal_start == jnl->active_start) {
jnl->active_start = tr->journal_end;
tr->journal_start = tr->journal_end = (off_t)0;
}
// go through the completed_trs list and try to coalesce
// entries, restarting back at the beginning if we have to.
for (ctr = jnl->completed_trs; ctr; prev=ctr, ctr=next) {
if (ctr->journal_start == jnl->active_start) {
jnl->active_start = ctr->journal_end;
if (prev) {
prev->next = ctr->next;
}
if (ctr == jnl->completed_trs) {
jnl->completed_trs = ctr->next;
}
next = jnl->completed_trs; // this starts us over again
ctr->next = jnl->tr_freeme;
jnl->tr_freeme = ctr;
ctr = NULL;
} else if (tr->journal_end == ctr->journal_start) {
ctr->journal_start = tr->journal_start;
next = jnl->completed_trs; // this starts us over again
ctr = NULL;
tr->journal_start = tr->journal_end = (off_t)0;
} else if (tr->journal_start == ctr->journal_end) {
ctr->journal_end = tr->journal_end;
next = ctr->next;
tr->journal_start = tr->journal_end = (off_t)0;
} else if (ctr->next && ctr->journal_end == ctr->next->journal_start) {
// coalesce the next entry with this one and link the next
// entry in at the head of the tr_freeme list
next = ctr->next; // temporarily use the "next" variable
ctr->journal_end = next->journal_end;
ctr->next = next->next;
next->next = jnl->tr_freeme; // link in the next guy at the head of the tr_freeme list
jnl->tr_freeme = next;
next = jnl->completed_trs; // this starts us over again
ctr = NULL;
} else {
next = ctr->next;
}
}
// if this is true then we didn't merge with anyone
// so link ourselves in at the head of the completed
// transaction list.
if (tr->journal_start != 0) {
// put this entry into the correct sorted place
// in the list instead of just at the head.
//
prev = NULL;
for (ctr = jnl->completed_trs; ctr && tr->journal_start > ctr->journal_start; prev=ctr, ctr=ctr->next) {
// just keep looping
}
if (ctr == NULL && prev == NULL) {
jnl->completed_trs = tr;
tr->next = NULL;
} else if (ctr == jnl->completed_trs) {
tr->next = jnl->completed_trs;
jnl->completed_trs = tr;
} else {
tr->next = prev->next;
prev->next = tr;
}
} else {
// if we're here this tr got merged with someone else so
// put it on the list to be free'd
tr->next = jnl->tr_freeme;
jnl->tr_freeme = tr;
}
transaction_done:
unlock_oldstart(jnl);
unlock_condition(jnl, &jnl->asyncIO);
}
#include <libkern/OSByteOrder.h>
#define SWAP16(x) OSSwapInt16(x)
#define SWAP32(x) OSSwapInt32(x)
#define SWAP64(x) OSSwapInt64(x)
static void
swap_journal_header(journal *jnl)
{
jnl->jhdr->magic = SWAP32(jnl->jhdr->magic);
jnl->jhdr->endian = SWAP32(jnl->jhdr->endian);
jnl->jhdr->start = SWAP64(jnl->jhdr->start);
jnl->jhdr->end = SWAP64(jnl->jhdr->end);
jnl->jhdr->size = SWAP64(jnl->jhdr->size);
jnl->jhdr->blhdr_size = SWAP32(jnl->jhdr->blhdr_size);
jnl->jhdr->checksum = SWAP32(jnl->jhdr->checksum);
jnl->jhdr->jhdr_size = SWAP32(jnl->jhdr->jhdr_size);
jnl->jhdr->sequence_num = SWAP32(jnl->jhdr->sequence_num);
}
static void
swap_block_list_header(journal *jnl, block_list_header *blhdr)
{
int i;
blhdr->max_blocks = SWAP16(blhdr->max_blocks);
blhdr->num_blocks = SWAP16(blhdr->num_blocks);
blhdr->bytes_used = SWAP32(blhdr->bytes_used);
blhdr->checksum = SWAP32(blhdr->checksum);
blhdr->flags = SWAP32(blhdr->flags);
if (blhdr->num_blocks >= journal_max_blocks(jnl)) {
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);
return;
}
for(i = 0; i < blhdr->num_blocks; i++) {
blhdr->binfo[i].bnum = SWAP64(blhdr->binfo[i].bnum);
blhdr->binfo[i].u.bi.bsize = SWAP32(blhdr->binfo[i].u.bi.bsize);
blhdr->binfo[i].u.bi.b.cksum = SWAP32(blhdr->binfo[i].u.bi.b.cksum);
}
}
static int
update_fs_block(journal *jnl, void *block_ptr, off_t fs_block, size_t bsize)
{
int ret;
struct buf *oblock_bp=NULL;
boolean_t was_vm_privileged = FALSE;
// first read the block we want.
ret = buf_meta_bread(jnl->fsdev, (daddr64_t)fs_block, bsize, NOCRED, &oblock_bp);
if (ret != 0) {
printf("jnl: %s: update_fs_block: error reading fs block # %lld! (ret %d)\n", jnl->jdev_name, fs_block, ret);
if (oblock_bp) {
buf_brelse(oblock_bp);
oblock_bp = NULL;
}
// let's try to be aggressive here and just re-write the block
oblock_bp = buf_getblk(jnl->fsdev, (daddr64_t)fs_block, bsize, 0, 0, BLK_META);
if (oblock_bp == NULL) {
printf("jnl: %s: update_fs_block: buf_getblk() for %lld failed! failing update.\n", jnl->jdev_name, fs_block);
return -1;
}
}
// make sure it's the correct size.
if (buf_size(oblock_bp) != bsize) {
buf_brelse(oblock_bp);
return -1;
}
// copy the journal data over top of it
memcpy((char *)buf_dataptr(oblock_bp), block_ptr, bsize);
if (vfs_isswapmount(jnl->fsmount)) {
/*
* if we block waiting for memory, and there is enough pressure to
* cause us to try and create a new swap file, we may end up deadlocking
* due to waiting for the journal on the swap file creation path...
* by making ourselves vm_privileged, we give ourselves the best chance
* of not blocking
*/
was_vm_privileged = set_vm_privilege(TRUE);
}
ret = VNOP_BWRITE(oblock_bp);
if (vfs_isswapmount(jnl->fsmount) && (was_vm_privileged == FALSE))
set_vm_privilege(FALSE);
if (ret != 0) {
printf("jnl: %s: update_fs_block: failed to update block %lld (ret %d)\n", jnl->jdev_name, fs_block,ret);
return ret;
}
// and now invalidate it so that if someone else wants to read
// it in a different size they'll be able to do it.
ret = buf_meta_bread(jnl->fsdev, (daddr64_t)fs_block, bsize, NOCRED, &oblock_bp);
if (oblock_bp) {
buf_markinvalid(oblock_bp);
buf_brelse(oblock_bp);
}
return 0;
}
static int
grow_table(struct bucket **buf_ptr, int num_buckets, int new_size)
{
struct bucket *newBuf;
int current_size = num_buckets, i;
// return if newsize is less than the current size
if (new_size < num_buckets) {
return current_size;
}
newBuf = hfs_new_data(struct bucket, new_size);
// printf("jnl: lookup_bucket: expanded co_buf to %d elems\n", new_size);
// copy existing elements
bcopy(*buf_ptr, newBuf, num_buckets*sizeof(struct bucket));
// initialize the new ones
for(i = num_buckets; i < new_size; i++) {
newBuf[i].block_num = (off_t)-1;
}
// free the old container
hfs_delete_data(*buf_ptr, struct bucket, num_buckets);
// reset the buf_ptr
*buf_ptr = newBuf;
return new_size;
}
static int
lookup_bucket(struct bucket **buf_ptr, off_t block_num, int num_full)
{
int lo, hi, index, matches, i;
if (num_full == 0) {
return 0; // table is empty, so insert at index=0
}
lo = 0;
hi = num_full - 1;
index = -1;
// perform binary search for block_num
do {
int mid = (hi - lo)/2 + lo;
off_t this_num = (*buf_ptr)[mid].block_num;
if (block_num == this_num) {
index = mid;
break;
}
if (block_num < this_num) {
hi = mid;
continue;
}
if (block_num > this_num) {
lo = mid + 1;
continue;
}
} while (lo < hi);
// check if lo and hi converged on the match
if (block_num == (*buf_ptr)[hi].block_num) {
index = hi;
}
// if no existing entry found, find index for new one
if (index == -1) {
index = (block_num < (*buf_ptr)[hi].block_num) ? hi : hi + 1;
} else {
// make sure that we return the right-most index in the case of multiple matches
matches = 0;
i = index + 1;
while (i < num_full && block_num == (*buf_ptr)[i].block_num) {
matches++;
i++;
}
index += matches;
}
return index;
}
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)
{
if (!overwriting) {
// grow the table if we're out of space - we may index the table
// with *num_full_ptr (lookup_bucket() can return a maximum value ==
// *num_full_ptr), so we need to grow when we hit (*num_buckets_ptr - 1)
// to prevent out-of-bounds indexing
if (*num_full_ptr >= (*num_buckets_ptr - 1)) {
int new_size = *num_buckets_ptr * 2;
int grow_size = grow_table(buf_ptr, *num_buckets_ptr, new_size);
if (grow_size < new_size) {
printf("jnl: %s: add_block: grow_table returned an error!\n", jnl->jdev_name);
return -1;
}
*num_buckets_ptr = grow_size; //update num_buckets to reflect the new size
}
// if we're not inserting at the end, we need to bcopy
if (blk_index != *num_full_ptr) {
bcopy( (*buf_ptr)+(blk_index), (*buf_ptr)+(blk_index+1), (*num_full_ptr-blk_index)*sizeof(struct bucket) );
}
(*num_full_ptr)++; // increment only if we're not overwriting
}
// sanity check the values we're about to add
if ((off_t)offset >= jnl->jhdr->size) {