-
Notifications
You must be signed in to change notification settings - Fork 3
/
libtop.c
2591 lines (2171 loc) · 66.6 KB
/
libtop.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-2004, 2008, 2009, 2019 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* The contents of this file constitute Original Code as defined in and
* are subject to the Apple Public Source License Version 1.1 (the
* "License"). You may not use this file except in compliance with the
* License. Please obtain a copy of the License at
* http://www.apple.com/publicsource and read it before using this file.
*
* This 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 OR NON-INFRINGEMENT. Please see the
* License for the specific language governing rights and limitations
* under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#include <limits.h>
#include <mach/bootstrap.h>
#include <mach/host_priv.h>
#include <mach/mach_error.h>
#include <mach/mach_host.h>
#include <mach/mach_port.h>
#include <mach/mach_time.h>
#include <mach/mach_types.h>
#include <mach/mach_vm.h>
#include <mach/message.h>
#include <mach/processor_set.h>
#include <mach/shared_region.h>
#include <mach/task.h>
#include <mach/task_policy.h>
#include <mach/thread_act.h>
#include <mach/vm_map.h>
#include <mach/vm_page_size.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/kern_memorystatus.h>
#include <sys/types.h>
#define IOKIT 1 /* For io_name_t in device/device_types.h. */
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/storage/IOBlockStorageDriver.h>
#include <device/device_types.h>
#include <libproc.h>
#include <fcntl.h>
#include <nlist.h>
#include <pwd.h>
#include <sys/param.h>
#include <sys/sysctl.h>
#include <sys/resource.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/route.h>
#include <sys/socket.h>
#define LIBTOP_DBG
#ifndef LIBTOP_DBG
/* Disable assertions. */
#ifndef NDEBUG
#define NDEBUG
#endif
#endif
#include <assert.h>
#include "libtop.h"
#include "rb.h"
#define NS_TO_TIMEVAL(NS) \
(struct timeval) \
{ \
.tv_sec = (NS) / NSEC_PER_SEC, .tv_usec = ((NS) % NSEC_PER_SEC) / NSEC_PER_USEC, \
}
/*
* Process info.
*/
typedef struct libtop_pinfo_s libtop_pinfo_t;
struct libtop_pinfo_s {
/* Sample data that are exposed to the library user. */
libtop_psamp_t psamp;
/* Linkage for pid-ordered tree. */
rb_node(libtop_pinfo_t) pnode;
/* Linkage for sorted tree. */
rb_node(libtop_pinfo_t) snode;
int flag; /* Set, but not used. */
/* Manual override for memory region reporting. */
libtop_preg_t preg;
/* TRUE if the globally shared text and data segments are mapped in. */
boolean_t split;
};
/* Memory object info. */
typedef struct libtop_oinfo_s libtop_oinfo_t;
struct libtop_oinfo_s {
/*
* pinfo structure that was most recently used to access this
* structure.
*/
libtop_pinfo_t *pinfo;
/* Memory object ID. */
int obj_id;
/* Memory object size, in pages. */
int size;
/* SM_PRIVATE, SM_SHARED, SM_PRIVATE_ALIASED, SM_COW, ... */
int share_type;
/* Number of pages resident in memory. */
int resident_page_count;
/* Number of references to memory object. */
int ref_count;
/* Number of references to memory object that pinfo holds. */
int proc_ref_count;
/*
* Rollback fields. These are used to store old values that need to be
* rolled back to their previous values if an object is referenced more
* than once by a process.
*
* The reason rolling back is necessary has to do with the fact that
* memory usage statistics are tallied on the fly, but this can only be
* accurately done for each memory region a process refers to once all
* of the references have been encountered. Since the code
* optimistically updates the statistics, changes have to be backed out
* when another reference to the same memory region is encountered.
*/
int rb_share_type; /* SM_EMPTY == "no rollback" */
uint64_t rb_aliased;
uint64_t rb_vprvt;
uint64_t rb_rshrd;
};
static boolean_t ignore_PPP;
/* Sample data that are exposed to the library user. */
static libtop_tsamp_t tsamp;
/* Function pointer that points to an abstract printing function. */
static libtop_print_t *libtop_print;
static void *libtop_user_data;
/* Temporary storage for sorting function and opaque data pointer. */
static libtop_sort_t *libtop_sort;
static void *libtop_sort_data;
/* Mach port, used for various Mach calls. */
static mach_port_t libtop_port;
/* Buffer that is large enough to hold the entire argument area of a process. */
static char *libtop_arg;
static int libtop_argmax;
static mach_port_t libtop_master_port;
static uint32_t interval;
/*
* Memory object hash table and list. For each sample, a hash table of memory
* objects is created, and it is used to determine various per-process memory
* statistics, as well as the total number of memory objects. Rather than
* allocating and freeing oinfo structures for every sample, previously
* allocated structures are linked into a list, and objects in the list are used
* in preference to allocation.
*/
static CFMutableDictionaryRef libtop_oinfo_hash;
/* Tree of all pinfo's, always ordered by -pid. */
static rb_tree(libtop_pinfo_t) libtop_ptree;
/*
* Transient tree of all pinfo's, created for each sample according to a
* sorting function.
*/
static rb_tree(libtop_pinfo_t) libtop_stree;
/* TRUE if the most recent sample is sorted. */
static boolean_t libtop_sorted;
/* Pointer to the most recently seen pinfo structure in libtop_piterate(). */
static libtop_pinfo_t *libtop_piter;
/* Cache of uid->username translations. */
static CFMutableDictionaryRef libtop_uhash;
#define TIME_VALUE_TO_NS(a) \
(((uint64_t)((a)->seconds) * NSEC_PER_SEC) + ((uint64_t)((a)->microseconds) * NSEC_PER_USEC))
enum libtop_status {
LIBTOP_NO_ERR = 0,
LIBTOP_ERR_INVALID = 1, /* An invalid task. */
LIBTOP_ERR_ALLOC /* An allocation error. */
};
mach_timebase_info_data_t timebase_info;
typedef enum libtop_status libtop_status_t;
/* Function prototypes. */
static boolean_t libtop_p_print(void *user_data, const char *format, ...);
static int libtop_p_mach_state_order(int state, long sleep_time);
static int libtop_p_load_get(host_info_t r_load);
static int libtop_p_loadavg_update(void);
static bool in_shared_region(mach_vm_address_t addr, cpu_type_t type);
static void libtop_p_fw_scan(
task_read_t task, mach_vm_address_t region_base, mach_vm_size_t region_size);
static void libtop_p_fw_sample(boolean_t fw);
static int libtop_p_vm_sample(void);
static void libtop_p_networks_sample(void);
static int libtop_p_disks_sample(void);
static int libtop_p_proc_table_read(boolean_t reg);
static libtop_status_t libtop_p_cputype(pid_t pid, cpu_type_t *cputype);
static mach_vm_size_t libtop_p_shreg_size(cpu_type_t);
static libtop_status_t libtop_p_task_update(task_read_t task, boolean_t reg);
static libtop_status_t libtop_p_proc_command(libtop_pinfo_t *pinfo, struct kinfo_proc *kinfo);
static void libtop_p_pinsert(libtop_pinfo_t *pinfo);
static void libtop_p_premove(libtop_pinfo_t *pinfo);
static void libtop_p_destroy_pinfo(libtop_pinfo_t *pinfo);
static libtop_pinfo_t *libtop_p_psearch(pid_t pid);
static int libtop_p_pinfo_pid_comp(libtop_pinfo_t *a, libtop_pinfo_t *b);
static int libtop_p_pinfo_comp(libtop_pinfo_t *a, libtop_pinfo_t *b);
static libtop_oinfo_t *libtop_p_oinfo_insert(int obj_id, int share_type, int resident_page_count,
int ref_count, int size, libtop_pinfo_t *pinfo);
static int libtop_p_wq_update(libtop_pinfo_t *pinfo);
static void libtop_i64_test(void);
static void update_pages_stolen(libtop_tsamp_t *tsamp);
/* CFDictionary callbacks */
static void
simpleFree(CFAllocatorRef allocator, const void *value)
{
free((void *)value);
}
static const void *
stringRetain(CFAllocatorRef allocator, const void *value)
{
return strdup(value);
}
static Boolean
stringEqual(const void *value1, const void *value2)
{
return strcmp(value1, value2) == 0;
}
int
libtop_init(libtop_print_t *print, void *user_data)
{
// libtop_i64_test();
if (print != NULL) {
libtop_print = print;
libtop_user_data = user_data;
} else {
/* Use a noop printing function. */
libtop_print = libtop_p_print;
libtop_user_data = NULL;
}
tsamp.seq = 0;
interval = 1;
libtop_port = mach_host_self();
tsamp.pagesize = vm_kernel_page_size;
/* Get the physical memory size of the system. */
{
int mib[2];
size_t size;
mib[0] = CTL_HW;
mib[1] = HW_MEMSIZE;
size = sizeof(tsamp.memsize);
if (sysctl(mib, 2, &tsamp.memsize, &size, NULL, 0) == -1) {
libtop_print(
libtop_user_data, "%s(): Error in sysctl(): %s", __FUNCTION__, strerror(errno));
return -1;
}
}
update_pages_stolen(&tsamp);
/* Initialize the pinfo tree. */
rb_tree_new(&libtop_ptree, pnode);
/* Initialized the user hash. */
CFDictionaryValueCallBacks stringValueCallBacks
= { 0, stringRetain, simpleFree, NULL, stringEqual };
libtop_uhash = CFDictionaryCreateMutable(NULL, 0, NULL, &stringValueCallBacks);
/* Initialize the memory object hash table and spares ring. */
CFDictionaryValueCallBacks oinfoValueCallBacks = { 0, NULL, simpleFree, NULL, NULL };
libtop_oinfo_hash = CFDictionaryCreateMutable(NULL, 0, NULL, &oinfoValueCallBacks);
/*
* Allocate a buffer that is large enough to hold the maximum arguments
* to execve(). This is used when getting the arguments to programs.
*/
{
int mib[2];
size_t size;
mib[0] = CTL_KERN;
mib[1] = KERN_ARGMAX;
size = sizeof(libtop_argmax);
if (sysctl(mib, 2, &libtop_argmax, &size, NULL, 0) == -1) {
libtop_print(
libtop_user_data, "%s(): Error in sysctl(): %s", __FUNCTION__, strerror(errno));
return -1;
}
libtop_arg = (char *)malloc(libtop_argmax);
if (libtop_arg == NULL)
return -1;
}
/*
* Get ports and services for drive statistics.
*/
if (IOMasterPort(bootstrap_port, &libtop_master_port)) {
libtop_print(libtop_user_data, "Error in IOMasterPort()");
return -1;
}
/* Initialize the load statistics. */
if (libtop_p_load_get((host_info_t)&tsamp.b_cpu))
return -1;
tsamp.p_cpu = tsamp.b_cpu;
tsamp.cpu = tsamp.b_cpu;
/* Initialize the time. */
mach_timebase_info(&timebase_info);
tsamp.b_timens = tsamp.p_timens = tsamp.timens = clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW);
tsamp.b_time = tsamp.p_time = tsamp.time = NS_TO_TIMEVAL(tsamp.timens);
ignore_PPP = FALSE;
return 0;
}
void
libtop_fini(void)
{
libtop_pinfo_t *pinfo, *ppinfo;
/* Deallocate the arg string. */
free(libtop_arg);
/* Clean up the oinfo structures. */
CFRelease(libtop_oinfo_hash);
/* Clean up the pinfo structures. */
rb_first(&libtop_ptree, pnode, pinfo);
for (; pinfo != rb_tree_nil(&libtop_ptree); pinfo = ppinfo) {
rb_next(&libtop_ptree, pinfo, libtop_pinfo_t, pnode, ppinfo);
/* This removes the pinfo from the tree, and frees pinfo and its data. */
libtop_p_destroy_pinfo(pinfo);
}
/* Clean up the uid->username translation cache. */
CFRelease(libtop_uhash);
}
/*
* Set the interval between framework updates.
*/
int
libtop_set_interval(uint32_t ival)
{
/* Interval has to be above or equal one and less than max */
if ((ival == 0) || (ival > LIBTOP_MAX_INTERVAL)) {
return -1;
}
interval = ival;
return 0;
}
/* Take a sample. */
int
libtop_sample(boolean_t reg, boolean_t fw)
{
int res = 0;
/* Increment the sample sequence number. */
tsamp.seq++;
/*
* Make a note that the results haven't been sorted (reset by
* libtop_psort()).
*/
libtop_sorted = FALSE;
libtop_piter = NULL;
/* Clear state breakdown. */
memset(tsamp.state_breakdown, 0, sizeof(tsamp.state_breakdown));
/* Get time. */
if (tsamp.seq != 1) {
tsamp.p_timens = tsamp.timens;
tsamp.p_time = NS_TO_TIMEVAL(tsamp.timens);
tsamp.timens = clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW);
tsamp.time = NS_TO_TIMEVAL(tsamp.timens);
}
res = libtop_p_proc_table_read(reg);
if (res == 0)
res = libtop_p_loadavg_update();
/* Get CPU usage counters. */
tsamp.p_cpu = tsamp.cpu;
if (res == 0)
libtop_p_load_get((host_info_t)&tsamp.cpu);
if (res == 0)
libtop_p_fw_sample(fw);
if (res == 0)
libtop_p_vm_sample();
if (res == 0)
libtop_p_networks_sample();
if (res == 0)
libtop_p_disks_sample();
return res;
}
/* Return a pointer to the structure that contains libtop-wide data. */
const libtop_tsamp_t *
libtop_tsamp(void)
{
return &tsamp;
}
/*
* Given a tree of pinfo structures, create another tree that is sorted
* according to sort().
*/
void
libtop_psort(libtop_sort_t *sort, void *data)
{
libtop_pinfo_t *pinfo, *ppinfo;
assert(tsamp.seq != 0);
/* Reset the iteration pointer. */
libtop_piter = NULL;
/* Initialize the sorted tree. */
rb_tree_new(&libtop_stree, snode);
/* Note that the results are sorted. */
libtop_sorted = TRUE;
/*
* Set the sorting function and opaque data in preparation for building
* the sorted tree.
*/
libtop_sort = sort;
libtop_sort_data = data;
/*
* Iterate through ptree and insert the pinfo's into a sorted tree.
* At the same time, prune pinfo's that were associated with processes
* that were not found during the most recent sample.
*/
tsamp.nprocs = 0;
rb_first(&libtop_ptree, pnode, pinfo);
for (; pinfo != rb_tree_nil(&libtop_ptree); pinfo = ppinfo) {
/*
* Get the next pinfo before potentially removing this one from
* the tree.
*/
rb_next(&libtop_ptree, pinfo, libtop_pinfo_t, pnode, ppinfo);
if (pinfo->psamp.seq == tsamp.seq) {
/* Insert the pinfo into the sorted tree. */
rb_node_new(&libtop_stree, pinfo, snode);
rb_insert(&libtop_stree, pinfo, libtop_p_pinfo_comp, libtop_pinfo_t, snode);
tsamp.nprocs++;
} else {
/* The associated process has gone away. */
libtop_p_destroy_pinfo(pinfo);
}
}
}
/*
* Iteratively return a pointer to each process that was in the most recent
* sample. The order depends on if/how libtop_psort() was called.
*/
const libtop_psamp_t *
libtop_piterate(void)
{
assert(tsamp.seq != 0);
if (libtop_sorted) {
/* Use the order set by libtop_psort(). */
if (libtop_piter == NULL) {
rb_first(&libtop_stree, snode, libtop_piter);
} else {
rb_next(&libtop_stree, libtop_piter, libtop_pinfo_t, snode, libtop_piter);
}
if (libtop_piter == rb_tree_nil(&libtop_stree)) {
libtop_piter = NULL;
}
} else {
boolean_t dead;
/*
* Return results in ascending pid order. Since dead processes
* weren't cleaned out by libtop_psamp(), take care to do so
* here on the fly.
*/
if (libtop_piter == NULL) {
rb_first(&libtop_ptree, pnode, libtop_piter);
} else {
rb_next(&libtop_ptree, libtop_piter, libtop_pinfo_t, pnode, libtop_piter);
}
do {
dead = FALSE;
if (libtop_piter == rb_tree_nil(&libtop_ptree)) {
/* No more tree nodes. */
libtop_piter = NULL;
break;
}
if (libtop_piter->psamp.seq != tsamp.seq) {
libtop_pinfo_t *pinfo;
/*
* Dead process. Get the next pinfo tree node
* before removing this one.
*/
pinfo = libtop_piter;
rb_next(&libtop_ptree, libtop_piter, libtop_pinfo_t, pnode, libtop_piter);
libtop_p_destroy_pinfo(pinfo);
dead = TRUE;
}
} while (dead);
}
return &libtop_piter->psamp;
}
/*
* Set whether to collect memory region information for the process with pid
* pid.
*/
int
libtop_preg(pid_t pid, libtop_preg_t preg)
{
libtop_pinfo_t *pinfo;
pinfo = libtop_p_psearch(pid);
if (pinfo == NULL)
return -1;
pinfo->preg = preg;
return 0;
}
/* Return a pointer to the username string associated with uid. */
const char *
libtop_username(uid_t uid)
{
const void *k = (const void *)(uintptr_t)uid;
if (!CFDictionaryContainsKey(libtop_uhash, k)) {
struct passwd *pwd = getpwuid(uid);
if (pwd == NULL)
return NULL;
CFDictionarySetValue(libtop_uhash, k, pwd->pw_name);
}
return CFDictionaryGetValue(libtop_uhash, k);
}
/* Return a pointer to a string representation of a process state. */
const char *
libtop_state_str(uint32_t state)
{
const char *strings[] = { "zombie",
#define LIBTOP_STATE_ZOMBIE 0
"running",
#define LIBTOP_STATE_RUN 1
"stuck",
#define LIBTOP_STATE_STUCK 2
"sleeping",
#define LIBTOP_STATE_SLEEP 3
"idle",
#define LIBTOP_STATE_IDLE 4
"stopped",
#define LIBTOP_STATE_STOP 5
"halted",
#define LIBTOP_STATE_HALT 6
"unknown"
#define LIBTOP_STATE_UNKNOWN 7
};
assert(LIBTOP_NSTATES == sizeof(strings) / sizeof(char *));
assert(state <= LIBTOP_STATE_MAX);
assert(LIBTOP_STATE_MAXLEN >= 8); /* "sleeping" */
return strings[state];
}
/*
* Noop printing function, used when the user doesn't supply a printing
* function.
*/
static boolean_t
libtop_p_print(void *user_data, const char *format, ...)
{
/* Do nothing. */
return 0;
}
/* Translate a mach state to a state in the state breakdown array. */
static int
libtop_p_mach_state_order(int state, long sleeptime)
{
switch (state) {
case TH_STATE_RUNNING:
return LIBTOP_STATE_RUN;
case TH_STATE_UNINTERRUPTIBLE:
return LIBTOP_STATE_STUCK;
case TH_STATE_STOPPED:
return LIBTOP_STATE_STOP;
case TH_STATE_HALTED:
return LIBTOP_STATE_HALT;
case TH_STATE_WAITING:
return (sleeptime > 0) ? LIBTOP_STATE_IDLE : LIBTOP_STATE_SLEEP;
default:
return LIBTOP_STATE_UNKNOWN;
}
}
/* Get CPU load. */
static int
libtop_p_load_get(host_info_t r_load)
{
kern_return_t kr;
mach_msg_type_number_t count;
count = HOST_CPU_LOAD_INFO_COUNT;
kr = host_statistics(libtop_port, HOST_CPU_LOAD_INFO, r_load, &count);
if (kr != KERN_SUCCESS) {
libtop_print(libtop_user_data, "Error in host_statistics(): %s", mach_error_string(kr));
return -1;
}
return 0;
}
/* Update load averages. */
static int
libtop_p_loadavg_update(void)
{
double avg[3];
if (getloadavg(avg, sizeof(avg)) < 0) {
libtop_print(libtop_user_data, "Error in getloadavg(): %s", strerror(errno));
return -1;
}
tsamp.loadavg[0] = avg[0];
tsamp.loadavg[1] = avg[1];
tsamp.loadavg[2] = avg[2];
return 0;
}
/*
* Test whether the virtual address is within the architecture's shared region.
*/
static bool
in_shared_region(mach_vm_address_t addr, cpu_type_t type)
{
mach_vm_address_t base = 0, size = 0;
switch (type) {
case CPU_TYPE_ARM:
base = SHARED_REGION_BASE_ARM;
size = SHARED_REGION_SIZE_ARM;
break;
case CPU_TYPE_X86_64:
base = SHARED_REGION_BASE_X86_64;
size = SHARED_REGION_SIZE_X86_64;
break;
case CPU_TYPE_I386:
base = SHARED_REGION_BASE_I386;
size = SHARED_REGION_SIZE_I386;
break;
case CPU_TYPE_POWERPC:
base = SHARED_REGION_BASE_PPC;
size = SHARED_REGION_SIZE_PPC;
break;
case CPU_TYPE_POWERPC64:
base = SHARED_REGION_BASE_PPC64;
size = SHARED_REGION_SIZE_PPC64;
break;
default: {
int t = type;
fprintf(stderr, "unknown CPU type: 0x%x\n", t);
abort();
} break;
}
return (addr >= base && addr < (base + size));
}
/* Iterate through a given region of memory, adding up the various
submap regions found therein. Modifies tsamp. */
static void
libtop_p_fw_scan(task_read_t task, mach_vm_address_t region_base, mach_vm_size_t region_size)
{
mach_vm_size_t vsize = 0;
mach_vm_size_t code = 0;
mach_vm_size_t data = 0;
mach_vm_size_t linkedit = 0;
mach_vm_size_t pagesize = tsamp.pagesize;
mach_vm_size_t size;
for (mach_vm_address_t addr = region_base; addr < (region_base + region_size); addr += size) {
uint32_t depth = 1;
vm_region_submap_info_data_64_t sinfo;
mach_msg_type_number_t count = VM_REGION_SUBMAP_INFO_COUNT_64;
// Get the next submap in the specified region of memory
kern_return_t kr = mach_vm_region_recurse(
task, &addr, &size, &depth, (vm_region_recurse_info_t)&sinfo, &count);
if (kr != KERN_SUCCESS)
break;
/*
* There should be no reason to test if addr is in a shared
* region, because the for loop limits the region space to the
* passed SHARED_REGION_BASE and SHARED_REGION_SIZE.
*/
vsize += size;
switch (sinfo.share_mode) {
case SM_SHARED: /* FALLTHROUGH */
case SM_COW: /* FALLTHROUGH */
case SM_TRUESHARED:
if (sinfo.max_protection & VM_PROT_EXECUTE) {
// CODE
code += sinfo.pages_resident;
tsamp.fw_count++;
} else if (sinfo.max_protection & VM_PROT_WRITE) {
// DATA
data += sinfo.pages_resident;
} else {
// LINKEDIT
linkedit += sinfo.pages_resident;
}
break;
default:
break;
}
}
tsamp.fw_vsize += vsize;
tsamp.fw_code += code * pagesize;
tsamp.fw_data += data * pagesize;
tsamp.fw_linkedit += linkedit * pagesize;
}
/* Sample framework memory statistics (if fw is TRUE). */
static void
libtop_p_fw_sample(boolean_t fw)
{
if (!fw)
return;
if ((interval != 1) && ((tsamp.seq % interval) != 1))
return;
tsamp.fw_count = 0;
tsamp.fw_code = 0;
tsamp.fw_data = 0;
tsamp.fw_linkedit = 0;
tsamp.fw_vsize = 0;
tsamp.fw_private = 0;
#if defined(__arm__)
libtop_p_fw_scan(mach_task_self(), SHARED_REGION_BASE_ARM, SHARED_REGION_SIZE_ARM);
#elif defined(__arm64__)
libtop_p_fw_scan(mach_task_self(), SHARED_REGION_BASE_ARM64, SHARED_REGION_SIZE_ARM64);
#elif defined(__x86_64__) || defined(__i386__)
libtop_p_fw_scan(mach_task_self(), SHARED_REGION_BASE_I386, SHARED_REGION_BASE_I386);
libtop_p_fw_scan(mach_task_self(), SHARED_REGION_BASE_X86_64, SHARED_REGION_BASE_X86_64);
#else
#error "unsupported architecture"
#endif
// Iterate through all processes, collecting their individual fw stats
libtop_piter = NULL;
while (libtop_piterate()) {
tsamp.fw_private += libtop_piter->psamp.fw_private;
}
}
static int
libtop_tsamp_update_swap_usage(libtop_tsamp_t *tsamp)
{
int mib[2] = { CTL_VM, VM_SWAPUSAGE };
int miblen = 2;
size_t len = sizeof(tsamp->xsu);
int res = sysctl(mib, miblen, &tsamp->xsu, &len, NULL, 0);
tsamp->xsu_is_valid = (res == 0);
return res;
}
/* This is for <rdar://problem/6410098>. */
static uint64_t
round_down_wired(uint64_t value)
{
return (value & ~((128 * 1024 * 1024ULL) - 1));
}
/* This is for <rdar://problem/6410098>. */
static void
update_pages_stolen(libtop_tsamp_t *tsamp)
{
static int mib_reserved[CTL_MAXNAME];
static int mib_unusable[CTL_MAXNAME];
static int mib_other[CTL_MAXNAME];
static size_t mib_reserved_len = 0;
static size_t mib_unusable_len = 0;
static size_t mib_other_len = 0;
int r;
tsamp->pages_stolen = 0;
/* This can be used for testing: */
// tsamp->pages_stolen = (256 * 1024 * 1024ULL) / tsamp->pagesize;
if (0 == mib_reserved_len) {
mib_reserved_len = CTL_MAXNAME;
r = sysctlnametomib("machdep.memmap.Reserved", mib_reserved, &mib_reserved_len);
if (-1 == r) {
mib_reserved_len = 0;
return;
}
mib_unusable_len = CTL_MAXNAME;
r = sysctlnametomib("machdep.memmap.Unusable", mib_unusable, &mib_unusable_len);
if (-1 == r) {
mib_reserved_len = 0;
return;
}
mib_other_len = CTL_MAXNAME;
r = sysctlnametomib("machdep.memmap.Other", mib_other, &mib_other_len);
if (-1 == r) {
mib_reserved_len = 0;
return;
}
}
if (mib_reserved_len > 0 && mib_unusable_len > 0 && mib_other_len > 0) {
uint64_t reserved = 0, unusable = 0, other = 0;
size_t reserved_len;
size_t unusable_len;
size_t other_len;
reserved_len = sizeof(reserved);
unusable_len = sizeof(unusable);
other_len = sizeof(other);
/* These are all declared as QUAD/uint64_t sysctls in the kernel. */
if (-1 == sysctl(mib_reserved, mib_reserved_len, &reserved, &reserved_len, NULL, 0)) {
return;
}
if (-1 == sysctl(mib_unusable, mib_unusable_len, &unusable, &unusable_len, NULL, 0)) {
return;
}
if (-1 == sysctl(mib_other, mib_other_len, &other, &other_len, NULL, 0)) {
return;
}
if (reserved_len == sizeof(reserved) && unusable_len == sizeof(unusable)
&& other_len == sizeof(other)) {
uint64_t stolen = reserved + unusable + other;
uint64_t mb128 = 128 * 1024 * 1024ULL;
if (stolen >= mb128) {
tsamp->pages_stolen = round_down_wired(stolen) / tsamp->pagesize;
}
}
}
}
static int
libtop_tsamp_update_vm_stats(libtop_tsamp_t *tsamp)
{
kern_return_t kr;
tsamp->p_vm_stat = tsamp->vm_stat;
mach_msg_type_number_t count = sizeof(tsamp->vm_stat) / sizeof(natural_t);
kr = host_statistics64(libtop_port, HOST_VM_INFO64, (host_info64_t)&tsamp->vm_stat, &count);
if (kr != KERN_SUCCESS) {
return kr;
}
if (tsamp->pages_stolen > 0) {
tsamp->vm_stat.wire_count += tsamp->pages_stolen;
}
// Check whether we got purgeable memory statistics
tsamp->purgeable_is_valid = (count == (sizeof(tsamp->vm_stat) / sizeof(natural_t)));
if (!tsamp->purgeable_is_valid) {
tsamp->vm_stat.purgeable_count = 0;
tsamp->vm_stat.purges = 0;
}
if (tsamp->seq == 1) {
tsamp->p_vm_stat = tsamp->vm_stat;
tsamp->b_vm_stat = tsamp->vm_stat;
}
return kr;
}
static void
sum_rshrd(const void *key, const void *value, void *context)
{
libtop_oinfo_t *oinfo = (libtop_oinfo_t *)value;
mach_vm_size_t *rshrd = (mach_vm_size_t *)context;
switch (oinfo->share_type) {
case SM_SHARED:
case SM_COW:
*rshrd += oinfo->resident_page_count;
break;
}
}
/* Sample general VM statistics. */
static int
libtop_p_vm_sample(void)
{
/* Get VM statistics. */
libtop_tsamp_update_vm_stats(&tsamp);
/* Get swap usage */
libtop_tsamp_update_swap_usage(&tsamp);
/*
* Iterate through the oinfo hash table and add up the collective size
* of the shared objects.
*/
mach_vm_size_t reg = 0;
mach_vm_size_t rprvt = 0;
mach_vm_size_t rshrd = 0;
mach_vm_size_t vsize = 0;
CFDictionaryApplyFunction(libtop_oinfo_hash, sum_rshrd, &rshrd);