-
Notifications
You must be signed in to change notification settings - Fork 1
/
libtmstat.c
5075 lines (4745 loc) · 147 KB
/
libtmstat.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) 2013, F5 Networks, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of F5 Networks, Inc.
*
* Statistics publishing and subscription facilities.
*
*/
#define _GNU_SOURCE
#include <sys/mman.h>
#include <sys/procfs.h>
#include <sys/queue.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/user.h>
#include <assert.h>
#include <ctype.h>
#include <dirent.h>
#include <elf.h>
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <libgen.h>
#include "tmstat.h"
#define HUGE_PAGE_SIZE (2 * 1024 * 1024)
#define ROUND_UP(n, m) (((n) + ((m) - 1)) & -(m))
#define ROW_ALIGN 8
#define TMSTAT_MIN(a, b) \
({ typeof(a) _a = (a); \
typeof(b) _b = (b); \
_a < _b ? _a : _b; })
#define TMSTAT_MAX(a, b) \
({ typeof(a) _a = (a); \
typeof(b) _b = (b); \
_a > _b ? _a : _b; })
#define TM_SLAB_MAGIC (*(uint32_t *)"TMSS") //!< Slab magic.
#define TM_SZ_LINE 64 //!< Slab line size.
#define TM_ID_TABLE 0 //!< Table descriptor id.
#define TM_ID_COLUMN 1 //!< Column descriptor id.
#define TM_ID_INODE 2 //!< Inode id.
#define TM_ID_LABEL 3 //!< Inode id.
#define TM_ID_USER 4 //!< First user id.
#define TM_SZ_TMSS 256 //!< Initial tmss table size.
#define TM_MAX_NAME TMSTAT_MAX_NAME //!< Max col/tbl name length.
/**
* Forward declaration.
*/
static void _tmstat_dealloc(TMSTAT stat);
/**
* Column descriptor.
*/
struct tmstat_column {
char name[TM_MAX_NAME+1];//!< Column name.
uint16_t tableid; //!< Associated table.
uint16_t offset; //!< Column offset.
uint16_t size; //!< Column size.
uint8_t type; //!< Data type.
uint8_t rule; //!< Merge rule.
} __attribute__((packed));
/**
* Index container--a dynamically-sized array of pointers.
* Order is not preserved across item removals.
*/
struct tmidx {
unsigned n; //!< Total entries.
unsigned c; //!< Used entries.
void **a; //!< Entry array.
};
/**
* Index node.
*
* These are always the same size as a line.
*
* TM_SZ_INODE is the number of entries in an inode.
*/
#define TM_SZ_INODE (((TM_SZ_LINE) / sizeof(uint32_t)) - 1)
struct tmstat_inode {
uint32_t child[TM_SZ_INODE]; //!< Child list.
uint32_t next; //!< Next node.
};
/**
* Inode child components.
*
* Inode numbers are 32 bits. The upper 24 bits contain a 0-based
* slab offset into the segment. The lower 8 bits contain a 0-based
* row index. Note that the row index skips first line in the slab
* used to hold the tmstat_slab structure and also that it cannot be
* used to determine the starting address of the row without the
* tmstat_slab structure's lines_per_row member.
*
* The value TM_INODE_LEAF is used in the low-order bits of inode
* numbers to mark objects in the index structure that have no
* children.
*/
#define TM_INODE_LEAF 0xff //!< Leaf marker.
#define TM_INODE_ROW(n) ((n) & 0xff) //!< Inode row index.
#define TM_INODE_SLAB(n) ((n) >> 8) //!< Inode slab index.
#define TM_INODE(s, i) (((s) << 8) | i) //!< Calculate inode value.
/**
* Label descriptor.
*/
struct tmstat_label {
char tree[8]; //!< ASCII art.
char name[TM_MAX_NAME+1]; //!< Label name.
char ctime[26]; //!< Creation time string.
time_t time; //!< Creation time in secs.
} __attribute__((packed));
/**
* Slab line.
*/
struct tmstat_line {
uint8_t data[TM_SZ_LINE]; //!< Line data.
};
/**
* Row slab.
*
* The bitmap member tracks row allocation, not line allocation.
*/
struct tmstat_slab {
uint32_t magic; //!< TM_SLAB_MAGIC.
uint16_t tableid; //!< Associated table Id.
uint16_t lines_per_row; //!< Lines per row.
uint64_t bitmap; //!< Allocation bitmap.
uint32_t inode; //!< Slab inode address.
uint32_t parent; //!< Parent inode (if any).
uint32_t statid; //!< Owning stat context.
uint8_t pad[TM_SZ_LINE-28]; //!< Pad to TM_SZ_LINE.
struct tmstat_line line[]; //!< Slab lines (containing rows).
} __attribute__((packed));
/**
* Table descriptor. These objects exist in the .table table and
* must not be more than one line long.
*/
struct tmstat_table {
char name[TM_MAX_NAME+1];//!< Table name.
uint32_t inode; //!< Root inode.
uint32_t rows; //!< Total rows (informational).
uint16_t rowsz; //!< Row size (bytes).
uint16_t cols; //!< Total columns (informational).
uint8_t is_sorted; //!< If sorted use fast query
uint16_t tableid; //!< Id of this table.
} __attribute__((packed));
/**
* Modes for allocating pages from the system for slabs.
*/
enum alloc_policy {
PREALLOCATE, //<! Pre-allocate pages to reduce number of mmap calls.
AS_NEEDED, //<! Allocate pages only when they're needed.
};
/**
* Methods by which a stat handle can be created.
*/
enum origin {
INVALID_ORIGIN,
CREATE,
SUBSCRIBE,
SUBSCRIBE_FILE,
READ,
UNION,
};
/**
* A record of an allocation of slab pages.
*/
struct alloc {
char *base; //<! Beginning of region.
char *limit; //<! First address after region.
struct alloc *prev; //<! Previous allocation.
};
/**
* Statistics segment handle.
*/
struct TMSTAT {
char name[32]; //!< Segment name.
char directory[32]; //!< Segment directory name.
uint32_t statid; //!< Process-unique ID
signed fd; //!< File descriptor.
enum alloc_policy alloc_policy; //!< How to map pages for slabs.
enum origin origin; //!< How this segment was created.
size_t slab_size; //!< Slab size.
struct tmidx slab_idx; //!< Slab index.
struct tmidx table_idx; //!< Table index.
struct tmidx child_idx; //!< Child segment index.
char *next_page; //!< Next free page in curr. alloc.
struct alloc *allocs; //!< Allocations for slabs.
struct timespec ctime; //!< Ctime of dir when last read.
};
/**
* Statistics table handle.
*/
struct TMTABLE {
TMSTAT stat; //!< Parent segment.
uint16_t tableid; //!< Table Id.
size_t rowsz; //!< Row size (in bytes).
uint32_t *inode; //!< Root inode pointer.
struct tmstat_table *td; //!< Table descriptor.
struct tmidx avail_idx; //!< Partially-allocated slab index.
TMCOL col; //!< All Column metadata.
unsigned col_count; //!< Total number of columns.
TMCOL key_col; //!< Key column metadata (duped).
unsigned key_col_count; //!< Number of Key columns.
bool want_merge : 1; //!< Table needs row merge pass.
LIST_HEAD(, TMROW) row_list; //!< Row handles.
};
/**
* Row handle.
*/
struct TMROW {
LIST_ENTRY(TMROW) entry; //!< Row list linkage.
signed ref_count; //!< Total references.
uint8_t *data; //!< Start of row data.
uint32_t inode_addr; //!< Row address.
TMTABLE table; //!< Parent table.
bool own_row : 1; //!< This handle owns this row.
};
/**
* Calculate the number of entries in a static array.
*/
#define array_size(a) (sizeof(a) / sizeof((a)[0]))
/**
* Calculate the number of objects a slab can store.
*
* @param[in] stat The slab's owning stat.
* @param[in] stat The relevant slab.
* @return The number of objects the slab can store.
*/
#define slab_max(stat, slab) \
((((stat)->slab_size / TM_SZ_LINE) - 1) / (slab)->lines_per_row)
/**
* Iterate over entries in an index.
*
* @param[in] t The tmidx.
* @param[in] p Iterator variable.
*/
#define TMIDX_FOREACH(t, p) \
for (unsigned tmidxforeachi = 0; \
(tmidxforeachi < (t)->c) && (p = (t)->a[tmidxforeachi]); \
tmidxforeachi++)
/**
* Retrieve a specific row from an index.
*
* @param[in] t The tmidx.
* @param[in] i The index of the desired row.
* @return The value at index i or NULL if there is no such entry.
*/
#define TMIDX_ROW(t, i) \
((i < (t)->c) ? (t)->a[i] : NULL)
/**
* Iterate over allocated rows in a slab.
*
* @param[in] st The stat owning the slabs.
* @param[in] sl The slab over whose lines to iterate.
* @param[in] r Row number iterator, an integer.
* @param[in] p A pointer, assigned the address of each row.
*/
#define TMSTAT_SLAB_FOREACH(st, sl, r, p) \
for (r = 0; (sl)->bitmap >> r; r++) \
if (((sl)->bitmap & (1ULL << r)) && \
((p) = (void *)&(sl)->line[r * (sl)->lines_per_row]) && \
((char *)(p) < ((char *)sl) + st->slab_size))
/**
* Calculate the number of lines in a slab, which depends upon the
* segment.
*
* @param[in] stat The segment in whose slabs you are interested.
* @return The number of lines in a slab in this segment.
*/
#define TM_LINES_PER_SLAB(stat) ((stat)->slab_size / TM_SZ_LINE)
/**
* Return a pointer to the first row in a slab or NULL if no rows are
* allocated.
*
* @param[in] stat The stat owning the slab.
* @param[in] s The slab from which to return a row.
* @param[out] rowno If non-null, assigned the index of the first row.
* @return The address of the first allocated row.
*/
static void *
tmstat_slab_first(TMSTAT stat, struct tmstat_slab *s, uint32_t *rowno)
{
uint32_t r;
void *p = NULL;
const uint32_t limit = TM_LINES_PER_SLAB(stat) / s->lines_per_row;
for (r = 0; (s->bitmap >> r) && (r < limit); ++r) {
if (s->bitmap & (1ULL << r)) {
p = (void *)&s->line[r * (s)->lines_per_row];
break;
}
}
*rowno = r;
return p;
}
#define TMSTAT_SEGMENT_DAMAGED(stat) \
tmstat_segment_damaged(__func__, __LINE__, stat)
static void
tmstat_segment_damaged(const char *func, unsigned line, TMSTAT stat)
{
warnx("%s(%d): tmstat segment %s/%s appears to be damaged",
func, line, stat->directory, stat->name);
errno = EINVAL;
}
static bool
tmstat_is_internal_name(const char *name)
{
for (unsigned i = 0; (name[i] != '\0') && (i < TM_MAX_NAME); ++i) {
if (name[i] == '/') {
return true;
}
}
return false;
}
static char *
tmstat_name_copy(const char *name)
{
char *copy;
copy = malloc(TM_MAX_NAME + 1);
if (copy != NULL) {
memset(copy, 0, TM_MAX_NAME + 1);
strncpy(copy, name, TM_MAX_NAME);
}
return copy;
}
/**
* Return a pointer to the last row in a slab or NULL if no rows are
* allocated.
*
* @param[in] stat The stat owning the slab.
* @param[in] s The slab from which to return a row.
* @param[out] rowno If non-null, assigned the index of the last row.
* @return The address of the last allocated row.
*/
static void *
tmstat_slab_last(TMSTAT stat, struct tmstat_slab *s, uint32_t *rowno)
{
uint32_t r;
void *p = NULL;
const uint32_t limit = TM_LINES_PER_SLAB(stat) / s->lines_per_row;
for (r = limit - 1; r != (uint32_t)-1; --r) {
if (s->bitmap & (1ULL << r)) {
p = (void *)&s->line[r * (s)->lines_per_row];
break;
}
}
*rowno = r;
return p;
}
/**
* Table-descriptor (struct tmstat_table) descriptor.
*
* Each row in this table describes a table in the segment.
*/
static THREAD struct TMCOL tm_cols_table[] = {
TMCOL_TEXT(struct tmstat_table, name),
TMCOL_UINT(struct tmstat_table, rows, .rule = TMSTAT_R_SUM),
TMCOL_UINT(struct tmstat_table, rowsz, .rule = TMSTAT_R_MAX),
TMCOL_UINT(struct tmstat_table, cols, .rule = TMSTAT_R_MAX),
TMCOL_UINT(struct tmstat_table, is_sorted, .rule = TMSTAT_R_MIN),
};
/**
* Label (struct tmstat_label) descriptor.
*
* Each row in this table describes a source for the segment.
*/
static THREAD struct TMCOL tm_cols_label[] = {
TMCOL_TEXT(struct tmstat_label, tree, .rule = TMSTAT_R_MIN),
TMCOL_TEXT(struct tmstat_label, name),
TMCOL_TEXT(struct tmstat_label, ctime),
TMCOL_INT(struct tmstat_label, time, .rule = TMSTAT_R_MAX),
};
/**
* Segment base path.
*/
THREAD char *tmstat_path = TMSTAT_PATH;
/**
* Segment id
*/
static GLOBALSET uint32_t tmstat_nextid = 1;
/**
* Header of the base.
*/
#define TMSTAT_BASE_HEADER "+- "
/**
* Header of the segment.
*/
#define TMSTAT_SEGMENT_HEADER "| +- "
/*
* The red-black tree implementation herein was adapted from the
* (public domain) code found at
* http://eternallyconfuzzled.com/tuts/datastructures/jsw_tut_rbtree.aspx
* There is a delete routine to be found there; it is not present here
* because we never delete from our trees. Note that this
* implementation is incapable of supporting iteration but is snappy
* due to the absence of parent pointers.
*/
/**
* Red-black search tree node.
*/
struct tmrbt_node {
int red; /* Node color. 0 = black, 1 = red. */
TMROW key; /* The node's key. */
struct tmrbt_node *link[2]; /* Children. 0 = left, 1 = right. */
};
typedef struct tmrbt_node *tmrbt_node;
/**
* A block of nodes allocated by a tmrbt. This is like a slab in
* allocator parlance but we don't want to confuse our terminology.
*/
#define TMRBT_SZ_POOL 62
struct tmrbt_pool {
struct tmrbt_node node[TMRBT_SZ_POOL]; /* The goodies. */
unsigned c; /* Index of next free node. */
struct tmrbt_pool *next; /* The next pool or NULL. */
};
typedef struct tmrbt_pool *tmrbt_pool;
/**
* Red-black search tree.
*/
struct tmrbt {
tmrbt_node root; /* Tree's root node. */
tmrbt_pool pool; /* Our memory allocations. */
};
typedef struct tmrbt *tmrbt;
TMTABLE tmstat_table(TMSTAT, char *);
/**
* Resize index.
*
* @param[in] idx Index to resize.
* @param[in] n Entries to preallocate.
*/
static signed
tmidx_resize(struct tmidx *idx, unsigned n)
{
void **a = (void **)realloc(idx->a, n * sizeof(void *));
assert(n >= idx->c);
if (a == NULL) {
/* Allocation failure; realloc sets errno. */
return -1;
}
memset(&a[idx->n], 0, (n - idx->n) * sizeof(void *));
idx->a = a;
idx->n = n;
return 0;
}
/**
* Initialize index.
*
* @param[in] idx Index to initialize.
*/
static inline void
tmidx_init(struct tmidx *idx)
{
memset(idx, 0, sizeof(struct tmidx));
}
/**
* Free index.
*
* @param[in] idx Index to free.
*/
static inline void
tmidx_free(struct tmidx *idx)
{
free(idx->a);
}
/**
* Add entry to idx.
*
* @param[in] idx Associated index.
* @param[in] p Entry to add.
* @return index on success, -1 on error.
*/
static signed
tmidx_add(struct tmidx *idx, void *p)
{
assert(p != NULL);
if (idx->c == idx->n) {
/* Extend idx. */
signed ret = tmidx_resize(idx, (idx->n > 0) ? idx->n * 2 : 1);
if (ret != 0) {
/* Allocation failure; tmidx_resize sets errno. */
return -1;
}
}
/* Add entry. */
idx->a[idx->c] = p;
return idx->c++;
}
/**
* Remove entry from index.
*
* @param[in] idx Associated index.
* @param[in] i Index of entry to remove.
*/
static inline void
tmidx_remove(struct tmidx *idx, unsigned i)
{
assert(i < idx->c);
idx->c--;
idx->a[i] = idx->a[idx->c];
idx->a[idx->c] = NULL;
}
/**
* Fetch entry from index.
*
* @param[in] idx Associated index.
* @param[in] i Index of entry to fetch.
* @return pointer to entry.
*/
static inline void *
tmidx_entry(struct tmidx *idx, unsigned i)
{
return (i < idx->c) ? idx->a[i] : NULL;
}
/**
* Return total used entries.
*
* @param[in] idx Associated index.
* @return count of used entries.
*/
static inline unsigned
tmidx_count(struct tmidx *idx)
{
return idx->c;
}
static int64_t tmstat_row_cmp(TMROW r1, TMROW r2);
int tmstat_pseudo_row_create(TMTABLE table, TMROW *row);
int tmstat_alloc_weak_ref_row(TMTABLE table, struct tmidx *rows, uint8_t *row,
struct tmstat_slab *slab, unsigned line);
/**
* Allocate a red-black tree node. We use pools of nodes not to
* reduce the number of calls to malloc but to make freeing the tree
* easier; this way, we don't have to walk the tree to free it. A
* non-recursive free would be very challenging without an
* auxiliary data structure because the nodes do not contain parent
* pointers.
*/
static tmrbt_node
tmrbt_node_alloc(tmrbt tree, TMROW key)
{
tmrbt_node node;
if (tree->pool->c == TMRBT_SZ_POOL) {
tmrbt_pool next = tree->pool;
tree->pool = (tmrbt_pool)malloc(sizeof(*tree->pool));
if (tree->pool == NULL) {
tree->pool = next;
return NULL;
}
tree->pool->next = next;
tree->pool->c = 0;
}
node = &tree->pool->node[tree->pool->c++];
node->red = 1;
node->key = key;
node->link[0] = NULL;
node->link[1] = NULL;
return node;
}
static inline int
tmrbt_is_red(tmrbt_node node)
{
return (node != NULL) && (node->red == 1);
}
static tmrbt_node
tmrbt_rot_single(tmrbt_node root, int dir)
{
tmrbt_node save = root->link[!dir];
root->link[!dir] = save->link[dir];
save->link[dir] = root;
root->red = 1;
save->red = 0;
return save;
}
static tmrbt_node
tmrbt_rot_double(tmrbt_node root, int dir)
{
root->link[!dir] = tmrbt_rot_single(root->link[!dir], !dir);
return tmrbt_rot_single(root, dir);
}
static tmrbt
tmrbt_alloc()
{
tmrbt tree;
tree = (tmrbt)malloc(sizeof(*tree));
if (tree == NULL) {
return NULL;
}
tree->root = NULL;
tree->pool = (tmrbt_pool)malloc(sizeof(*tree->pool));
if (tree->pool == NULL) {
free(tree);
return NULL;
}
tree->pool->c = 0;
tree->pool->next = NULL;
return tree;
}
static void
tmrbt_free(tmrbt tree)
{
if (tree == NULL) return;
tmrbt_pool pool = tree->pool;
while (pool) {
tmrbt_pool next = pool->next;
free(pool);
pool = next;
}
free(tree);
}
static TMROW
tmrbt_find(tmrbt tree, TMROW key)
{
tmrbt_node node = tree->root;
while (node) {
int64_t cmp = tmstat_row_cmp(node->key, key);
if (cmp == 0) {
return node->key;
}
node = node->link[cmp < 0];
}
return NULL;
}
/**
* Red-black search tree insertion.
*
* Warning! On failure, the tree will no longer maintain the
* red-black properties.
*
* @param[in] tree Tree to modify.
* @param[in] key Element to insert.
* @return 0 on success, -1 on failure.
*/
static int
tmrbt_insert(tmrbt tree, TMROW key)
{
int ret = 0;
if (tree->root == NULL) {
/* Empty tree case. */
tree->root = tmrbt_node_alloc(tree, key);
if (tree->root == NULL) {
/* Memory exhausted. */
ret = -1;
goto out;
}
} else {
struct tmrbt_node head = { 0 }; /* False tree root. */
tmrbt_node g, t; /* Grandparent & parent. */
tmrbt_node p, q; /* Iterator & parent. */
int dir = 0, last;
int64_t cmp;
/* Set up helpers. */
t = &head;
g = p = NULL;
q = t->link[1] = tree->root;
/* Search down the tree. */
for (;;) {
if (q == NULL) {
/* Insert new node at the bottom. */
q = tmrbt_node_alloc(tree, key);
if (q == NULL) {
/* Memory exhausted. */
ret = -1;
goto out;
}
p->link[dir] = q;
}
else if (tmrbt_is_red(q->link[0]) && tmrbt_is_red(q->link[1])) {
/* Color flip. */
q->red = 1;
q->link[0]->red = 0;
q->link[1]->red = 0;
}
/* Fix red violation. */
if (tmrbt_is_red(q) && tmrbt_is_red(p)) {
int dir2 = t->link[1] == g;
if (q == p->link[last])
t->link[dir2] = tmrbt_rot_single(g, !last);
else
t->link[dir2] = tmrbt_rot_double(g, !last);
}
/* Stop if found. */
cmp = tmstat_row_cmp(q->key, key);
if (cmp == 0) {
break;
}
last = dir;
dir = cmp < 0;
/* Update helpers. */
if (g != NULL)
t = g;
g = p, p = q;
q = q->link[dir];
}
/* Update root. */
tree->root = head.link[1];
}
/* Make root black. */
tree->root->red = 0;
out:
return ret;
}
/**
* Map a portion of a file.
*
* @param[in] stat Segment whose file we're mapping.
* @param[in] size Length of mapping (in slabs).
* @param[in] perm Permissions, passed to mmap.
* @param[in] offset Offset in file of mapping (in slabs).
* @return 0 on success, -1 on failure.
*/
#define tmstat_mmap(a, b, c, d) (tmstat_mmap)((a), (b), (c), (d), __func__)
static int (
tmstat_mmap)(TMSTAT stat, size_t size, int perm, size_t offset,
const char *func)
{
char *p;
struct alloc *a;
/*
* If we're mmaping more of the file, either we should have
* already made slabs out of everything we had already mmaped or this
* should be the first mmap.
*/
assert((stat->next_page == NULL) ||
(stat->next_page == stat->allocs->limit));
a = calloc(1, sizeof(struct alloc));
if (a == NULL) {
warn("%s: calloc", func);
return -1;
}
size = size * stat->slab_size;
offset = offset * stat->slab_size;
if (stat->fd != -1) {
p = mmap(NULL, size, perm, MAP_SHARED, stat->fd, offset);
if (p == MAP_FAILED) {
warn("%s: mmap", func);
p = NULL;
}
} else {
p = calloc(1, size);
if (p == NULL) {
warn("%s: calloc", func);
}
}
if (p != NULL) {
a->prev = stat->allocs;
a->base = p;
a->limit = p + size;
stat->next_page = p;
stat->allocs = a;
return 0;
} else {
free(a);
return -1;
}
}
/**
* Unmap mappings for this file.
*
* @param[in] stat Segment whose mappings we're releasing.
*/
static void
tmstat_munmap(TMSTAT stat)
{
struct alloc *a, *prev;
int ret;
for (a = stat->allocs; a != NULL; a = prev) {
if (stat->fd != -1) {
ret = munmap(a->base, a->limit - a->base);
if (ret != 0) {
warn("%s: munmap", __func__);
}
} else {
free(a->base);
}
prev = a->prev;
free(a);
}
stat->allocs = NULL;
stat->next_page = NULL;
}
/**
* Obtain slab for inode address.
*
* @param[in] stat Parent segment.
* @param[in] inode_addr Inode address.
* @return slab pointer or NULL upon error.
*/
static struct tmstat_slab *
tmstat_slab(TMSTAT stat, uint32_t inode_address)
{
struct tmstat_slab *slab;
slab = (struct tmstat_slab *)
tmidx_entry(&stat->slab_idx, TM_INODE_SLAB(inode_address));
if ((slab == NULL) && stat->origin != CREATE) {
struct stat stat_buf;
unsigned slab_count, new_count;
signed ret;
char *p;
/*
* Publisher extended segment since we subscribed; extend our map.
*/
ret = fstat(stat->fd, &stat_buf);
if (ret != 0) {
/* Filesystem failure; fstat sets errno. */
goto out;
}
if ((stat_buf.st_size % stat->slab_size) != 0) {
warnx("segment is not an even number of slabs: %u %% %u = %u",
stat_buf.st_size, stat->slab_size,
(stat_buf.st_size % stat->slab_size));
goto out;
}
slab_count = stat_buf.st_size / stat->slab_size;
if (slab_count <= tmidx_count(&stat->slab_idx)) {
/* File was not extended. This is a bogus request. */
goto out;
}
new_count = slab_count - tmidx_count(&stat->slab_idx);
/* Map new slabs. */
ret = tmstat_mmap(stat, new_count, PROT_READ,
tmidx_count(&stat->slab_idx));
if (ret == -1) {
/* Mapping failure; tmstat_mmap sets errno. */
goto out;
}
p = stat->next_page;
/* Insert slab index entries. */
for (unsigned i = 0; i < new_count; i++) {
ret = tmidx_add(&stat->slab_idx, p);
if (ret == -1) {
/* Insertion failure; tmidx_add sets errno. */
goto out;
}
p += stat->slab_size;
}
stat->next_page = p;
/* Use the new index. */
slab = (struct tmstat_slab *)
tmidx_entry(&stat->slab_idx, TM_INODE_SLAB(inode_address));
}
out:
return slab;
}
/*
* Obtain inode from address.
*/
static inline struct tmstat_inode *
tmstat_inode(TMSTAT stat, uint32_t addr)
{
struct tmstat_slab *slab;
struct tmstat_inode *inode = NULL;
struct tmstat_inode *limit;
slab = tmstat_slab(stat, addr);
if (slab != NULL) {
limit = (struct tmstat_inode *)((char *)slab + stat->slab_size);
inode = (struct tmstat_inode *)
&slab->line[TM_INODE_ROW(addr) * slab->lines_per_row];
if (inode >= limit) {
inode = NULL;
}
}
return inode;
}
/**
* Allocate slab for table.
*
* @param[in] tms Parent segment.
* @param[in] tableid Table Id.
* @param[in] rowsz Row size (in bytes).
* @param[out] new_slab New slab.
* @return 0 on success, -1 on error.
*/
static int
tmstat_slab_alloc(TMSTAT stat, uint16_t tableid, uint16_t rowsz,
struct tmstat_slab **new_slab)
{
struct tmstat_slab *slab = NULL;
unsigned i = tmidx_count(&stat->slab_idx);
signed ret;
unsigned c;