Repository navigation
Expand file tree
/
Copy pathcontrol.c
More file actions
1867 lines (1574 loc) · 52.2 KB
/
Copy pathcontrol.c
File metadata and controls
1867 lines (1574 loc) · 52.2 KB
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
/*
* Block device "smart readahead" cache control utility.
*
* Provides the user-space interface to the BootCache cache;
* loading the playlist, reading and presorting the history list
* into a new playlist, gathering performance statistics.
*
*/
#include <sys/param.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/attr.h>
#include <sys/syscall.h>
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOKitLib.h>
#include <dirent.h>
#include <sys/xattr.h>
#include <sys/mount.h>
#include <libkern/OSAtomic.h>
#include <os/assumes.h>
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <notify.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <mach/mach_time.h>
#include <sys/kdebug_private.h>
#include "BootCache_private.h"
// --- For fusion disk checking
#include <IOKit/storage/CoreStorage/CoreStorageUserLib.h>
#include <IOKit/storage/IOMedia.h>
#include <APFS/APFSConstants.h>
static int usage(const char *reason);
static int do_boot_cache(void);
static int start_cache(const char *pfname);
static int stop_cache(const char *pfname, int debugging);
static int jettison_cache(void);
static int merge_playlists(const char *pfname, int argc, char *argv[], int* pbatch);
static int print_statistics(struct BC_statistics *ss);
static int print_debug_buffer(void);
static void print_history(struct BC_history *he);
static int print_playlist_on_disk(const char *pfname);
static int unprint_playlist(const char *pfname);
static int generalize_playlist(const char *pfname);
static int truncate_playlist(const char *pfname, char *larg);
static int trim_playlist_to_max_size(struct BC_playlist* pc);
static void max_playlist_size(uint64_t* max_high_priority_size_out, uint64_t* max_total_size_out);
static int add_file(struct BC_playlist *pc, const char *fname, const int batch, const bool low_priority);
static int add_directory(struct BC_playlist *pc, const char *fname, const int batch);
static int add_fseventsd_files(struct BC_playlist *pc, const int batch);
static int add_playlist_for_preheated_user(struct BC_playlist *pc, bool isFusion);
static int add_logical_playlist(const char *playlist, struct BC_playlist *pc, int batch);
static int add_native_shared_cache(struct BC_playlist *pc, int batch, bool low_priority);
static CFStringRef _bootcachectl_copy_root_volume_uuid(bool *is_apfs_out, bool* is_fusion_out);
static CFStringRef _bootcachectl_copy_uuid_for_bsd_device(const char* bsd_name, bool *is_apfs_out, bool *is_fusion_out);
static int verbose;
static char *myname;
static FILE *outstream;
#define LOG(fmt, args...) fprintf(outstream, fmt"\n", ##args)
#define LOG_ERRNO(fmt, args...) LOG(fmt": %d %s", ## args, errno, strerror(errno))
#ifdef DEBUG
#define DLOG(fmt, args...) LOG(fmt, ##args)
#else
#define DLOG(fmt, args...)
#endif
int
main(int argc, char *argv[])
{
int ch, batch;
int* pbatch;
char *pfname;
outstream = stdout;
bc_log_stream = stdout;
myname = argv[0];
pfname = NULL;
pbatch = NULL;
while ((ch = getopt(argc, argv, "b:cvf:t:")) != -1) {
switch(ch) {
case 'b':
usage("blocksize is no longer required, ignoring");
case 'c':
// no longer used
break;
case 'v':
verbose++;
break;
case 'f':
pfname = optarg;
break;
case 't':
if ((sscanf(optarg, "%d", &batch)) != 1)
usage("bad batch number");
else
pbatch = &batch;
break;
case '?':
default:
return(usage(NULL));
break;
}
}
argc -= optind;
argv += optind;
if (argc < 1)
return(usage("missing command"));
/* documented interface */
if (!strcmp(argv[0], "start")) {
if (pfname)
return(start_cache(pfname));
else
return(do_boot_cache());
}
if (!strcmp(argv[0], "stop"))
return(stop_cache(pfname, 0));
if (!strcmp(argv[0], "mount"))
return(BC_notify_mount());
if (!strcmp(argv[0], "jettison"))
return(jettison_cache());
if (!strcmp(argv[0], "tag"))
return(BC_tag_history());
if (!strcmp(argv[0], "statistics"))
return(print_statistics(NULL));
if (!strcmp(argv[0], "debugbuffer"))
return(print_debug_buffer());
if (!strcmp(argv[0], "merge"))
return(merge_playlists(pfname, argc - 1, argv + 1, pbatch));
if (!strcmp(argv[0], "print"))
return(print_playlist_on_disk(pfname));
if (!strcmp(argv[0], "unprint"))
return(unprint_playlist(pfname));
if (!strcmp(argv[0], "generalize"))
return(generalize_playlist(pfname));
if (!strcmp(argv[0], "generate")) {
LOG("generate is no longer supported");
return(1);
}
if (!strcmp(argv[0], "truncate")) {
if (argc < 2)
return(usage("missing truncate length"));
return(truncate_playlist(pfname, argv[1]));
}
if (!strcmp(argv[0], "unload")) {
if (BC_unload()) {
LOG("could not unload cache");
return(1);
} else {
return(0);
}
}
return(usage("invalid command"));
}
/*
* Suggest better usage habits.
*/
static int
usage(const char *reason)
{
if (reason != NULL)
LOG("%s", reason);
LOG("Usage: %s [-vvv] [-f <playlistfile>] start", myname);
LOG(" Start recording history and play back <playlistfile>.");
LOG(" %s [-vvv] [-f <playlistfile>] stop", myname);
LOG(" Stop recording history and write the playlist to <playlistfile>.");
LOG(" %s mount", myname);
LOG(" Notify the boot cache of a new mount.");
LOG(" %s [-vvv] jettison", myname);
LOG(" Jettison the cache.");
LOG(" %s statistics", myname);
LOG(" Print statistics for the currently-active cache.");
LOG(" %s debugbuffer", myname);
LOG(" Print the debug buffer, if available.");
LOG(" %s tag", myname);
LOG(" Insert the end-prefetch tag.");
LOG(" %s [-vvv] [-t batchnum] -f <playlistfile> merge <playlistfile1> [<playlistfile2>...]", myname);
LOG(" Merge <playlistfile1>... into <playlistfile>.");
LOG(" Playlist files after the first will be offset <batchnum> batches, if provided");
LOG(" %s -f <playlistfile> print", myname);
LOG(" Print the contents of <playlistfile>.");
LOG(" %s -f <playlistfile> unprint", myname);
LOG(" Read a playlist from standard input and write to <playlistfile>.");
LOG(" %s -f <playlistfile> truncate <count>", myname);
LOG(" Truncate <playlistfile> to <count> entries.");
LOG(" %s -f <playlistfile> generalize", myname);
LOG(" Modify <playlistfile> to apply to any root volume.");
return(1);
}
/*
* Return a user-readable string for a given uuid
*
* Returns a pointer to a static buffer, which is
* racy, so this should only be used for debugging purposes
*/
static inline const char* uuid_string(const uuid_t uuid)
{
static uuid_string_t string[4];
static int index = 0;
int i = OSAtomicIncrement32(&index) % 4;
uuid_unparse(uuid, string[i]);
return string[i];
}
static int add_logical_playlist(const char *playlist, struct BC_playlist *pc, int batch)
{
char filename[MAXPATHLEN];
FILE *lpl = fopen(playlist, "r");
if (lpl == NULL){
if (errno != ENOENT && errno != EINVAL) {
LOG_ERRNO("Could not read playlist %s", playlist);
}
return -1;
}
while (fgets(filename, sizeof filename, lpl)){
size_t len = strlen(filename);
if (len < 3)
continue;
if (filename[len - 1] == '\n')
filename[len - 1] = '\0';
if (filename[len - 2] == '/'){
filename[len - 2] = '\0';
int error;
if ((error = add_directory(pc, filename, batch))
&& error != ENOENT && error != EINVAL)
LOG_ERRNO("Error adding files in directory %s", filename);
} else {
add_file(pc, filename, batch, false);
}
}
fclose(lpl);
return 0;
}
/*
* Kick off the boot cache.
*/
static int
do_boot_cache(void)
{
struct BC_userspace_timestamps userspace_timestamps = {0};
userspace_timestamps.ssup_launch_timestamp = mach_absolute_time();
#ifdef DEBUG
outstream = fopen("/var/log/BootCacheControl.log", "a");
err_set_file(outstream);
bc_log_stream = outstream;
struct tm tm;
time_t seconds = time(NULL);
localtime_r(&seconds, &tm);
char date[32];
size_t ret = strftime(date, sizeof(date), "%Y-%m-%d %T", &tm);
if (ret != 0) {
LOG("Launched at %s", date);
} else {
LOG("Launched");
}
#endif
struct BC_playlist *pc;
int error;
const char* pfname = BC_ROOT_PLAYLIST;
if ((error = BC_test()) != 0) {
return error;
}
bool isFusion = false;
bool isAPFS = false;
CFStringRef uuid = _bootcachectl_copy_root_volume_uuid(&isAPFS, &isFusion);
if (!uuid) {
isFusion = false;
isAPFS = false;
} else {
CFRelease(uuid);
}
/* set up to start recording with no playback */
pc = NULL;
/*
* If we have a playlist, open it and prepare to load it.
*/
error = BC_read_playlist(pfname, &pc);
/*
* If the playlist is missing or invalid, ignore it. We'll
* overwrite it later.
*/
if ((error != 0) && (error != EINVAL) && (error != ENOENT)) {
errno = error;
LOG_ERRNO("could not read playlist %s", pfname);
}
/*
* Remove the consumed playlist: it'll be replaced once BootCache
* completes successfully.
*/
#ifdef DEBUG
char prev_path[MAXPATHLEN];
snprintf(prev_path, sizeof(prev_path), "%s.previous", pfname);
error = rename(pfname, prev_path); // for debugging
if (error != 0 && errno != ENOENT) {
LOG_ERRNO("could not rename bootcache playlist %s", pfname);
}
#else
error = unlink(pfname);
if (error != 0 && errno != ENOENT) {
LOG_ERRNO("could not unlink bootcache playlist %s", pfname);
}
#endif
int last_shutdown_was_clean = 0;
size_t wasCleanSz = sizeof(wasCleanSz);
error = sysctlbyname("vfs.generic.root_unmounted_cleanly", &last_shutdown_was_clean, &wasCleanSz, NULL, 0);
if (error != 0) {
LOG_ERRNO("Unable to check for hard shutdown");
}
if (pc) {
if (! last_shutdown_was_clean) {
struct timeval start_time = {0,0}, end_time = {0,0};
(void)gettimeofday(&start_time, NULL); // can't fail
// Make sure the unlink(pfname) above hits disk in case we panic rdar://8947415
int fd = open("/var/db/", O_RDONLY);
if (fd != -1) {
if (-1 != fcntl(fd, F_FULLFSYNC)) {
LOG("Synced /var/db/");
} else {
LOG_ERRNO("Unable to sync /var/db/");
}
close(fd);
} else {
LOG_ERRNO("Unable to open /var/db/");
}
(void)gettimeofday(&end_time, NULL); // can't fail
timersub(&end_time, &start_time, &end_time);
// LOG("Took %dus to sync /var/db/", end_time.tv_usec);
}
if (!isFusion) {
// rdar://9424845 Add any files we know are read in every boot, but change every boot
add_fseventsd_files(pc, 0);
add_logical_playlist(BC_ROOT_EXTRA_LOGICAL_PLAYLIST, pc, 0);
add_logical_playlist(BC_LOGIN_EXTRA_LOGICAL_PLAYLIST, pc, 2);
}
} else {
if (last_shutdown_was_clean) {
pc = BC_allocate_playlist(0, 0, 0);
// No Root playlist: we're during an install so use our premade logical playlists
if (!isFusion) {
add_logical_playlist(BC_ROOT_LOGICAL_PLAYLIST, pc, 0);
add_logical_playlist(BC_LOGIN_LOGICAL_PLAYLIST, pc, 2);
}
}
}
// If we don't have a playlist here, we don't want to play back anything
if (pc) {
if (!isAPFS || !isFusion) {
// Add the login playlist of user we expect to log in to the boot playlist
add_playlist_for_preheated_user(pc, isFusion);
// rdar://9021675 Always warm the shared cache
DLOG("Adding shared cache");
add_native_shared_cache(pc, -1, false);
}
error = trim_playlist_to_max_size(pc);
if (error != 0) {
errno = error;
LOG_ERRNO("cache trim failed");
PC_FREE_ZERO(pc);
}
}
userspace_timestamps.ssup_oid_timestamp = mach_absolute_time();
BC_set_userspace_timestamps(&userspace_timestamps);
error = BC_start(pc);
if (error != 0) {
errno = error;
LOG_ERRNO("could not start cache");
}
PC_FREE_ZERO(pc);
#ifdef DEBUG
fflush(outstream);
#endif
return(error);
}
/*
* Fetch or create a login playlist for the given user and add it to the provided playlist in subsequent batches
*/
static int
add_playlist_for_preheated_user(struct BC_playlist *pc, bool isFusion) {
if (!pc) return 1;
// These defines match those in warmd
#define PLAYLIST_DIR "/var/db/BootCaches/"
#define MERGED_PLAYLIST "Merged.playlist"
#define LOGIN_PLAYLIST "Login.playlist"
#define DEFAULT_USER_DIR PLAYLIST_DIR"PreheatedUser/"
#define APP_CACHE_PLAYLIST_PREFIX "app."
#define PLAYLIST_SUFFIX ".playlist"
#define RUNNING_XATTR_NAME "BC_RUNNING"
#define MAX_PLAYLIST_PATH_LENGTH 256
#define TAL_LOGIN_FOREGROUND_APP_BATCH_NUM 0
#define TAL_LOGIN_BACKGROUND_APP_BATCH_NUM (TAL_LOGIN_FOREGROUND_APP_BATCH_NUM + 1)
#define TAL_LOGIN_LOWPRI_DATA_BATCH_NUM (TAL_LOGIN_BACKGROUND_APP_BATCH_NUM + 1)
int error = 0, i;
size_t playlist_path_end_idx = 0;
char playlist_path[MAX_PLAYLIST_PATH_LENGTH] = DEFAULT_USER_DIR;
struct BC_playlist* user_playlist = NULL;
//rdar://8830944&9209576 Detect FDE user
io_registry_entry_t service = IORegistryEntryFromPath(kIOMainPortDefault, "IODeviceTree:/chosen");
if (service != MACH_PORT_NULL) {
CFDataRef fde_login_user = IORegistryEntryCreateCFProperty(service, CFSTR(kCSFDEEFILoginUnlockIdentID),
kCFAllocatorDefault, kNilOptions);
IOObjectRelease(service);
if (fde_login_user != NULL) {
char fde_login_user_str[128] = {0};
CFDataGetBytes(fde_login_user, CFRangeMake(0, sizeof(fde_login_user_str)), (UInt8*)fde_login_user_str);
CFRelease(fde_login_user);
snprintf(playlist_path, sizeof(playlist_path), "%s%s/", PLAYLIST_DIR, fde_login_user_str);
struct stat statbuf;
if (0 == stat(playlist_path, &statbuf)) {
DLOG("Using FDE user %s", fde_login_user_str);
} else {
LOG("No such FDE user %s, using Preheated User", fde_login_user_str);
snprintf(playlist_path, sizeof(playlist_path), "%s", DEFAULT_USER_DIR);
}
}
}
playlist_path_end_idx = strlen(playlist_path);
// DLOG("Reading user playlists from user dir %s", playlist_path);
// Check for the merged playlist warmd has left
strlcpy(playlist_path + playlist_path_end_idx, MERGED_PLAYLIST, sizeof(playlist_path) - playlist_path_end_idx);
error = BC_read_playlist(playlist_path, &user_playlist);
if (ENOENT == error) {
// No merged playlist for the preheated user. Try to create one from its login and app playlists
strlcpy(playlist_path + playlist_path_end_idx, LOGIN_PLAYLIST, sizeof(playlist_path) - playlist_path_end_idx);
error = BC_read_playlist(playlist_path, &user_playlist);
if (0 == error) {
struct BC_playlist *app_playlist = NULL;
struct dirent* direntry;
int suffix_length = strlen(PLAYLIST_SUFFIX);
int app_prefix_length = strlen(APP_CACHE_PLAYLIST_PREFIX);
playlist_path[playlist_path_end_idx] = '\0';
DIR* dir = opendir(playlist_path);
// Iterate over the app playlists twice:
// The first iteration to add the running apps to the playlist.
// The second iteration to add the non-running apps to the low-priority playlist
int iteration;
for (iteration = 0; iteration < 2; iteration++) {
int batch_offset = 0;
int flags = 0x0;
if (iteration == 0) {
// We can't tell the order between apps, so just put them all background to give the login playlist priority
batch_offset = TAL_LOGIN_BACKGROUND_APP_BATCH_NUM;
if (isFusion) {
//rdar://11294417 All user data is low priority on CoreStorage Fusion
flags |= BC_PE_LOWPRIORITY;
}
} else {
// Non-running apps are low-priority
batch_offset = TAL_LOGIN_LOWPRI_DATA_BATCH_NUM;
flags |= BC_PE_LOWPRIORITY;
}
while ((direntry = readdir(dir)) != NULL) {
if (direntry->d_namlen > suffix_length && 0 == strncmp(direntry->d_name + direntry->d_namlen - suffix_length, PLAYLIST_SUFFIX, suffix_length)) {
if (0 == strncmp(direntry->d_name, APP_CACHE_PLAYLIST_PREFIX, app_prefix_length)) {
snprintf(playlist_path + playlist_path_end_idx, sizeof(playlist_path) - playlist_path_end_idx, "/%s", direntry->d_name);
bool is_running = (-1 != getxattr(playlist_path, RUNNING_XATTR_NAME, NULL, 0, 0, 0x0));
if ((iteration == 0) == is_running) { // First iteration we're looking for running apps; second, for non-running
if (0 == BC_read_playlist(playlist_path, &app_playlist)) {
// Adjust the flags and batch for this playlist as necessary
for (i = 0; i < app_playlist->p_nentries; i++) {
app_playlist->p_entries[i].pe_flags |= flags;
app_playlist->p_entries[i].pe_batch += batch_offset;
}
for (i = 0; i < app_playlist->p_nomaps; i++) {
app_playlist->p_omaps[i].po_omap.otr_batch += batch_offset;
}
if (0 != (error = BC_merge_playlists(user_playlist, app_playlist))) {
PC_FREE_ZERO(app_playlist);
goto out;
}
PC_FREE_ZERO(app_playlist);
#ifdef DEBUG
DLOG("Merged playlist for app %s into user playlist:", playlist_path);
BC_print_playlist(user_playlist, false);
#endif
}
}
}
} else {
playlist_path[playlist_path_end_idx] = '\0';
// DLOG("Unknown file in user playlist directory %s: %s", playlist_path, direntry->d_name);
}
}
if (iteration == 0) {
rewinddir(dir);
}
}
closedir(dir);
dir = NULL;
}
}
if (error != 0) {
goto out;
}
if (!isFusion) {
// Add any files we know are read in every login, but change every login
// --- none yet, use add_file ---
}
// Slide the user playlist by the number of batches we have in the boot playlist
int batch_max = 0;
for (i = 0; i < pc->p_nentries; i++) {
if (pc->p_entries[i].pe_batch > batch_max) {
batch_max = pc->p_entries[i].pe_batch;
}
}
batch_max ++;
for (i = 0; i < user_playlist->p_nentries; i++) {
user_playlist->p_entries[i].pe_batch += batch_max;
}
for (i = 0; i < user_playlist->p_nomaps; i++) {
user_playlist->p_omaps[i].po_omap.otr_batch += batch_max;
}
error = BC_merge_playlists(pc, user_playlist);
if (error != 0) {
BC_reset_playlist(pc);
} else {
#ifdef DEBUG
DLOG("Merged preheated user playlist into root playlist:");
BC_print_playlist(pc, false);
#endif
}
out:
PC_FREE_ZERO(user_playlist);
return (error);
}
/*
* Upon return:
* *max_high_priority_size_out is the the maximum size of the high priority batches, in bytes
* *max_total_size_out is the maximum size of the cache when also including low priority
* (to limit memory impact of the low priority batch).
* I.E. if (high priority size) < (max_total_size), then the maximum amount of low priority
* bytes is (max_total_size) - (high priority size). Otherwise, no low priority bytes are allowed
*
* (max_total_size may be larger or smaller than max_high_priority_size)
*/
static void
max_playlist_size(uint64_t* max_high_priority_size_out, uint64_t* max_total_size_out)
{
static dispatch_once_t onceToken;
static uint64_t max_high_priority_size = 0;
static uint64_t max_total_size = 0;
dispatch_once(&onceToken, ^{
uint64_t memsize = 0;
size_t len = sizeof(memsize);
int error = sysctlbyname("hw.memsize", &memsize, &len, NULL, 0);
if(error != 0) {
memsize = (4ull * 1024 * 1024 * 1024);
LOG_ERRNO("sysctlbyname(\"hw.memsize\") failed. Assuming 4GB");
} else {
// Subtract any memory that is allocated by boot kernel tracing
char bootargs[PAGE_SIZE];
bootargs[0] = '\0';
size_t s = sizeof(bootargs);
if (0 != sysctlbyname("kern.bootargs", &(bootargs[0]), &s, NULL, 0)) {
LOG_ERRNO("Unable to get kern.bootargs");
} else {
char* trace_str = strnstr(bootargs, "trace=", sizeof(bootargs));
if (trace_str) {
uint64_t trace_count;
if (sscanf(trace_str, "trace=%lli", &trace_count) == 1) {
uint64_t trace_size = trace_count * sizeof(kd_buf);
if (memsize > trace_size) {
memsize -= trace_size;
}
}
}
}
}
#define BC_RESERVE_MEM_SIZE_FOR_HIGH_PRIORITY_PLAYLIST (1ull * 1024 * 1024 * 1024) // Make sure we leave 1GB free if the cache is completely wrong
#define BC_MIN_MEM_SIZE_FOR_HIGH_PRIORITY_PLAYLIST (1ull * 1024 * 1024 * 1024) // But don't force the BootCache size to less than 1GB
#define BC_RESERVE_MEM_SIZE_FOR_LOW_PRIORITY_PLAYLIST (3ull * 1024 * 1024 * 1024) // Maks sure we leave 3GB of memory free since the low priority playlist isn't expected to be used (and its mainly read in after boot has completed)
#define BC_MIN_MEM_SIZE_FOR_LOW_PRIORITY_PLAYLIST (0) // If we're low on memory, don't do any low priority playback
// max high priority playlist size is memory size minus 1GB
// (pages will be pulled from the cache as boot progresses, so its never all resident at once)
if (memsize >= BC_RESERVE_MEM_SIZE_FOR_HIGH_PRIORITY_PLAYLIST + BC_MIN_MEM_SIZE_FOR_HIGH_PRIORITY_PLAYLIST) {
// machine has >=2GB of memory, use default sizing
max_high_priority_size = memsize - BC_RESERVE_MEM_SIZE_FOR_HIGH_PRIORITY_PLAYLIST;
} else if (memsize >= BC_MIN_MEM_SIZE_FOR_HIGH_PRIORITY_PLAYLIST) {
// 1-2GB in the machine, use 1GB
max_high_priority_size = BC_MIN_MEM_SIZE_FOR_HIGH_PRIORITY_PLAYLIST;
} else {
// <1GB of memory, use memsize
max_high_priority_size = memsize;
}
// max size that low priority entires can make a playlist to be is memory size minus 3GB
// (low priority entries are not expected to be used, so will cause memory pressure if we pull in too much)
// rdar://53720350 (BootCache causing memory pressure after login for 4GB machines)
if (memsize >= BC_RESERVE_MEM_SIZE_FOR_LOW_PRIORITY_PLAYLIST + BC_MIN_MEM_SIZE_FOR_LOW_PRIORITY_PLAYLIST) {
// machine has >=3GB of memory, use default sizing
max_total_size = memsize - BC_RESERVE_MEM_SIZE_FOR_LOW_PRIORITY_PLAYLIST;
} else if (memsize >= BC_MIN_MEM_SIZE_FOR_LOW_PRIORITY_PLAYLIST) {
// <3GB in the machine, no low priority bytes allowed
max_total_size = BC_MIN_MEM_SIZE_FOR_LOW_PRIORITY_PLAYLIST;
} else {
// Unused (would be used if we have a min for low priority playlist)
max_total_size = memsize;
}
});
*max_high_priority_size_out = max_high_priority_size;
*max_total_size_out = max_total_size;
}
/*
* Trim the lowest priority extents until the playlist
* is under the provided size
*/
static int
trim_playlist_to_size(struct BC_playlist* pc, uint64_t max_high_priority_size, uint64_t max_total_size)
{
struct BC_userspace_oversize oversize = {
.ssup_highpri_bytes_trimmed = 0,
.ssup_lowpri_bytes_trimmed = 0,
};
uint64_t playlist_low_priority_size = 0;
uint64_t playlist_high_priority_size = 0;
int max_batch = 0;
for (int entry_idx = 0; entry_idx < pc->p_nentries; entry_idx++) {
struct BC_playlist_entry* pe = pc->p_entries + entry_idx;
if (pe->pe_flags & BC_PE_LOWPRIORITY) {
playlist_low_priority_size += pe->pe_length;
} else {
playlist_high_priority_size += pe->pe_length;
if (max_batch < pe->pe_batch) {
max_batch = pe->pe_batch;
}
}
}
if (playlist_high_priority_size > max_high_priority_size) {
// High priority part of the playlist is too large,
// trim off entries in last-to-first batch order
// Also, iterate in reverse block address order
// (because lower extents tend to be grouped tighter in my experience)
uint64_t playlist_high_priority_size_orig = playlist_high_priority_size;
for (int batch = max_batch; batch >= 0; batch--) {
for (int entry_idx = pc->p_nentries - 1; entry_idx >= 0; entry_idx--) {
struct BC_playlist_entry* pe = pc->p_entries + entry_idx;
if ((pe->pe_batch == batch) && !(pe->pe_flags & BC_PE_LOWPRIORITY)) {
if (pe->pe_length > playlist_high_priority_size - max_high_priority_size) {
pe->pe_length -= (playlist_high_priority_size - max_high_priority_size);
playlist_high_priority_size = max_high_priority_size;
} else {
playlist_high_priority_size -= pe->pe_length;
pe->pe_length = 0;
}
}
if (playlist_high_priority_size <= max_high_priority_size) {
break;
}
}
if (playlist_high_priority_size <= max_high_priority_size) {
break;
}
}
LOG("Trimmed %llu high priority bytes due to oversize (%llu > %llu)", playlist_high_priority_size_orig - playlist_high_priority_size, playlist_high_priority_size_orig, max_high_priority_size);
oversize.ssup_highpri_bytes_trimmed = playlist_high_priority_size_orig - playlist_high_priority_size;
}
if (playlist_high_priority_size + playlist_low_priority_size > max_total_size) {
// Low priority part of the playlist is too large trim off entries
uint64_t playlist_low_priority_size_orig = playlist_low_priority_size;
for (int entry_idx = pc->p_nentries - 1; entry_idx >= 0; entry_idx--) {
struct BC_playlist_entry* pe = pc->p_entries + entry_idx;
if (pe->pe_flags & BC_PE_LOWPRIORITY) {
if (pe->pe_length > playlist_high_priority_size + playlist_low_priority_size - max_total_size) {
pe->pe_length -= (playlist_high_priority_size + playlist_low_priority_size - max_total_size);
playlist_low_priority_size = max_total_size - playlist_high_priority_size;
} else {
playlist_low_priority_size -= pe->pe_length;
pe->pe_length = 0;
}
}
if (playlist_high_priority_size + playlist_low_priority_size <= max_total_size) {
break;
}
}
LOG("Trimmed %llu low priority bytes due to oversize (%llu > %llu)", playlist_low_priority_size_orig - playlist_low_priority_size, playlist_high_priority_size + playlist_low_priority_size_orig, max_total_size);
oversize.ssup_lowpri_bytes_trimmed = playlist_low_priority_size_orig - playlist_low_priority_size;
}
int err = BC_sort_and_coalesce_playlist(pc);
if (err == 0) {
BC_set_userspace_oversize(&oversize);
}
return err;
}
/*
* Trim the lowest priority extents until the playlist
* is under the maximum size
*/
static int
trim_playlist_to_max_size(struct BC_playlist* pc)
{
uint64_t max_high_priority_size = 0;
uint64_t max_total_size = 0;
max_playlist_size(&max_high_priority_size, &max_total_size);
return trim_playlist_to_size(pc, max_high_priority_size, max_total_size);
}
/*
* Add contents of the file to the bootcache
*/
static int
merge_into_batch(struct BC_playlist *dest, const struct BC_playlist *source, const int batch, const bool low_priority)
{
if (low_priority) {
for (int i = 0; i < source->p_nentries; i++) {
source->p_entries[i].pe_flags |= BC_PE_LOWPRIORITY;
}
} else {
if(batch > 0){
int i;
for (i = 0; i < source->p_nentries; i++) {
source->p_entries[i].pe_batch += batch;
}
for (i = 0; i < source->p_nomaps; i++) {
source->p_omaps[i].po_omap.otr_batch += batch;
}
} else if (batch < 0) {
int i;
int inverse_batch = 0 - batch;
for (i = 0; i < dest->p_nentries; i++) {
dest->p_entries[i].pe_batch += inverse_batch;
}
for (i = 0; i < dest->p_nomaps; i++) {
dest->p_omaps[i].po_omap.otr_batch += inverse_batch;
}
}
}
int error = BC_merge_playlists(dest, source);
if (error != 0) {
BC_reset_playlist(dest);
}
return error;
}
/*
* Add contents of the file to the bootcache
*/
static int
add_file(struct BC_playlist *pc, const char *fname, const int batch, const bool low_priority)
{
#define MAX_FILESIZE (10ll * 1024 * 1024) // 10MB
int error;
int fd = open(fname, O_RDONLY);
if (fd == -1) {
if (errno != ENOENT && errno != EINVAL) {
LOG_ERRNO("Unable to open %s to add it to the boot cache", fname);
}
return errno;
}
off_t maxsize = MAX_FILESIZE;
struct BC_playlist *playlist = NULL;
error = BC_playlist_for_filename(fd, fname, maxsize, &playlist);
close(fd);
if (playlist == NULL) {
if (error != ENOENT && error != EINVAL) {
LOG_ERRNO("Unable to create playlist for %s", fname);
}
return error;
}
error = merge_into_batch(pc, playlist, batch, low_priority);
PC_FREE_ZERO(playlist);
#ifdef DEBUG
if (!error) {
DLOG("Merged playlist for file %s into playlist:", fname);
BC_print_playlist(pc, false);
}
#endif
return error;
}
/*
* Add contents of a directory to the bootcache. Does not operate recursively.
*/
static int
add_directory(struct BC_playlist *pc, const char *dname, const int batch)
{
#define MAX_FILES_PER_DIR 10
DIR *dirp = opendir(dname);
if (!dirp)
return errno;
int count = 0;
struct dirent *dp;
while ((dp = readdir(dirp)) != NULL){
if (dp->d_type != DT_REG)
continue;
char fname[MAXPATHLEN];
int ret = snprintf(fname, MAXPATHLEN, "%s/%s", dname, dp->d_name);
if (ret < 0 || ret >= MAXPATHLEN)
continue;
add_file(pc, fname, batch, false);
if (++count >= MAX_FILES_PER_DIR) break;
}
closedir(dirp);
return 0;
}
/*
* Add fseventsd-related files to the bootcache.
*
* We add the 10 newest files of the fsventsd folder to the boot cache
*/
static int
add_fseventsd_files(struct BC_playlist *pc, const int batch)
{
#define FSEVENTSD_DIR "/.fseventsd"
#define MAX_NAME_LENGTH 64
#define NUM_FILES_TO_WARM 10
DIR *dirp = opendir(FSEVENTSD_DIR);
if (!dirp)
return errno;
char newest_files[NUM_FILES_TO_WARM][MAX_NAME_LENGTH];
int i;
for (i = 0; i < NUM_FILES_TO_WARM; i++) {
newest_files[i][0] = '\0';
}
// Copy the first 10 files into our array
struct dirent *dp;
for (i = 0; i < NUM_FILES_TO_WARM && (dp = readdir(dirp)) != NULL; i++) {
if (dp->d_type != DT_REG)
continue;
strlcpy(newest_files[i], dp->d_name, MAX_NAME_LENGTH);
}
// Check if we ran out of directory entries
if (dp) {
//Find the oldest file of the first 10
char* oldest_new_file = newest_files[0];
for (i = 1; i < NUM_FILES_TO_WARM; i++) {
if (strncmp(newest_files[i], oldest_new_file, MAX_NAME_LENGTH) < 0) {
oldest_new_file = newest_files[i];
}
}
// Find any files that are newer than the first 10
while ((dp = readdir(dirp)) != NULL){
if (dp->d_type != DT_REG)
continue;
// We want the last 10 files, and they're ordered alphabetically
if (strncmp(oldest_new_file, dp->d_name, MAX_NAME_LENGTH) < 0) {
strlcpy(oldest_new_file, dp->d_name, MAX_NAME_LENGTH);
// We replaced the oldest file, find the oldest of the 10 newest again
for (i = 0; i < NUM_FILES_TO_WARM; i++) {
if (strncmp(newest_files[i], oldest_new_file, MAX_NAME_LENGTH) < 0) {
oldest_new_file = newest_files[i];
}
}
}
}
}
closedir(dirp);
for (i = 0; i < NUM_FILES_TO_WARM; i++) {
if (newest_files[i][0] != '\0') {
char fname[128];
int ret = snprintf(fname, 128, "%s/%s", FSEVENTSD_DIR, newest_files[i]);
if (ret < 0 || ret >= 128)
continue;
add_file(pc, fname, batch, false);
}
}
return 0;
}
/*
* Add the native shared cache to the bootcache.
*/
static int