-
Notifications
You must be signed in to change notification settings - Fork 140
Expand file tree
/
Copy pathfdtable.c
More file actions
2386 lines (2069 loc) · 71.4 KB
/
fdtable.c
File metadata and controls
2386 lines (2069 loc) · 71.4 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
/* SPDX-License-Identifier: GPL-2.0 */
/* X-SPDX-Copyright-Text: (c) Copyright 2003-2020 Xilinx, Inc. */
/**************************************************************************\
*//*! \file
** <L5_PRIVATE L5_SOURCE>
** \author djr/ctk
** \brief Table mapping [fd]s to userlevel state.
** \date 2003/01/08
** \cop (c) Level 5 Networks Limited.
** </L5_PRIVATE>
*//*
\**************************************************************************/
/*! \cidoxg_lib_transport_unix */
#include "internal.h"
#include <fcntl.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/vfs.h>
#include <onload/ul.h>
#include <onload/dup2_lock.h>
#include <onload/ul/tcp_helper.h>
#include <onload/version.h>
#include <dlfcn.h>
#include "ul_pipe.h"
#include "ul_poll.h"
#include "ul_epoll.h"
#include <ci/internal/syscall.h>
#include <ci/internal/banner.h>
/* FIXME Yes, it is ugly. But we do not have any appropriate header */
#define CI_ID_POOL_ID_NONE ((unsigned)(-1))
#define DEBUGPREINIT(x)
citp_fdtable_globals citp_fdtable;
/* Initial seqno should differ from the seqno in special fdi, such as
* citp_the_closed_fd */
ci_uint64 fdtable_seq_no = 1;
static void dup2_complete(citp_fdinfo* prev_newfdi,
citp_fdinfo_p prev_newfdip, int fdt_locked);
static void exit_with_status(int status)
{
/* oo_exit_hook() takes too long, we should exit ungraciously */
if( WIFEXITED(status) )
ci_sys__exit(WEXITSTATUS(status));
else if( WIFSIGNALED(status) )
ci_sys_syscall(__NR_tgkill, getpid(), ci_sys_syscall(__NR_gettid),
WTERMSIG(status));
return;
}
void oo_signal_terminate(int signum)
{
struct sigaction act = { };
Log_CALL(ci_log("%s(%d)", __func__, signum));
/* Set SIGDFL for this signal, so that we do what the user expects next
* time
*/
oo_syscall_sigaction(signum, &act, NULL);
oo_exit_hook(signum);
exit_with_status(signum);
}
static void sighandler_sigonload(int sig, siginfo_t* info, void* context)
{
/* This signal is raised by dup2()/dup3() to interrupt blocking operations
* such as recv(). It comes from pthread_kill(), via the tgkill() syscall,
* which uses the SI_TKILL code. The assertion can catch some unexpected
* uses of the signal.
*/
ci_assert_equal(info->si_code, SI_TKILL);
/* Ensure that blocking operations are not restarted */
ci_atomic32_or(&citp_signal_get_specific_inited()->c.aflags,
OO_SIGNAL_FLAG_HAVE_PENDING);
ci_atomic32_and(&citp_signal_get_specific_inited()->c.aflags,
~OO_SIGNAL_FLAG_NEED_RESTART);
}
/* Hook to be called at gracious exit */
void oo_exit_hook(int status)
{
citp_lib_context_t lib_context;
/* exit status as in waitpid:
* (exit_status << 8) | exit_sig
* combined with OO_EXIT_STATUS_SET when really exiting.
* exit_fn() exits with status=0, so we have to mark it somehow.
*/
#define OO_EXIT_STATUS_SET 0x10000
static ci_uint32 exit_status;
ci_uint32 old_status;
Log_CALL(ci_log("%s(0x%x)", __func__, status));
do {
old_status = exit_status;
} while( ci_cas32u_fail(&exit_status, old_status,
status | OO_EXIT_STATUS_SET) );
if( old_status != 0 ) {
if( status != 0 ) {
/* We have been already exiting, and now we see emergency exit via
* _exit() or via signal. Do the emergency thing.
*/
exit_with_status(status);
return;
}
else {
/* This hook have already been called, from either _exit() or signal.
* Now we are in exit_fn(): return.
*/
return;
}
}
if( ! have_active_netifs() )
return;
citp_enter_lib(&lib_context);
CITP_FDTABLE_LOCK_RD();
#if CI_CFG_FD_CACHING
uncache_active_netifs();
#endif
exit_lock_all_stacks();
CITP_FDTABLE_UNLOCK_RD();
citp_exit_lib(&lib_context, 1);
}
/*! Block until fdtable entry is neither closing nor busy, and return the
** new (non-closing-or-busy) fdip. */
static citp_fdinfo_p citp_fdtable_closing_wait(unsigned fd, int fdt_locked);
#ifdef __x86_64__
#if __GNUC__ >= 6
__attribute__((force_align_arg_pointer))
static long oo_close_nocancel_entry(long fd)
#else
extern long oo_close_nocancel_entry(long fd);
__asm__(
".globl oo_close_nocancel_entry;"
"oo_close_nocancel_entry:"
"push %rbp;"
"mov %rsp,%rbp;"
"and $0xfffffffffffffff0,%rsp;"
"call close_nocancel_entry_fixed;"
"mov %rbp,%rsp;"
"pop %rbp;"
"ret;"
);
__attribute__((used))
static long close_nocancel_entry_fixed(long fd)
#endif
#else
static long oo_close_nocancel_entry(long fd)
#endif
{
int rc;
citp_lib_context_t lib_context;
if( fd < 0 || fd >= citp_fdtable.inited_count ||
fdip_is_unknown(citp_fdtable.table[fd].fdip) ) {
/* Don't enter lib when we're not going to affect anything. This avoids
* cases of infinite recursion, most notably when grabbing the TLS entry
* requires doing TLS init (which might require initialising malloc too,
* which might call close()) */
return ci_tcp_helper_close_no_trampoline(fd);
}
Log_CALL(ci_log("%s: close_nocancel(%ld)", __func__, fd));
citp_enter_lib(&lib_context);
rc = citp_ep_close((int)fd);
citp_exit_lib(&lib_context, false);
Log_CALL_RESULT(rc);
return rc;
}
#ifdef __aarch64__
static void aarch64_write_ptr_insns(void* dst, const void* value)
{
unsigned* u = dst;
uintptr_t v = (uintptr_t)value;
u[0] |= ((v >> 0) & 0xffff) << 5;
u[1] |= ((v >> 16) & 0xffff) << 5;
u[2] |= ((v >> 32) & 0xffff) << 5;
u[3] |= ((v >> 48) & 0xffff) << 5;
}
#endif
static int modify_glibc_code(void* dst, const void* src, size_t n)
{
int rc;
void* patch_page_start;
size_t patch_page_size;
/* This patching is thread-unsafe, but happens at process startup when
* there's only one thread */
patch_page_start = CI_PTR_ALIGN_BACK(dst, CI_PAGE_SIZE);
patch_page_size = (char*)CI_PTR_ALIGN_FWD((char*)dst + n, CI_PAGE_SIZE) -
(char*)patch_page_start;
rc = mprotect(patch_page_start, patch_page_size, PROT_READ | PROT_WRITE);
if( rc != 0 ) {
rc = -errno;
LOG_S(ci_log("ERROR: mprotect(glibc write) = %d", errno));
return rc;
}
memcpy(dst, src, n);
rc = mprotect(patch_page_start, patch_page_size, PROT_READ | PROT_EXEC);
if( rc != 0 ) {
/* Normally, ci_log() would be used here to log the error however if
* SELinux is running on RHEL9/glibc 2.34 then the call to ci_log() will
* cause a seg fault before writing anything. To ensure that the error
* message is printed the write() syscall is used directly.
*
* The crash has been observed on entry to __fcntl64_nocancel_adjusted(),
* In the failing version of libc __fcntl64_nocancel comes immediately
* after __close_nocancel. So I think that the code for fcntl64 is no
* longer marked as executable causing the crash. */
char err_msg[256];
snprintf(err_msg, sizeof(err_msg),
"CRITICAL: mprotect(glibc exec) = %d\n"
"If you have SELinux enabled either disable it or give permission"
" for your application to execmod lib_t files\n"
"Process will likely crash now\n", errno);
ci_sys_write(STDERR_FILENO, err_msg, strlen(err_msg));
rc = -errno;
return rc;
}
return 0;
}
#ifdef __x86_64__
static const unsigned char x64_endbr[] = {0xf3, 0x0f, 0x1e, 0xfa};
static const unsigned char x64_nop[] = {0x90};
/* Returns the length of the given instruction, if it's one of the
* instructions that we expect to find in the implementation of libc's
* _IO_file_close. Currently this is just some movs */
static int is_io_file_close_insn(const unsigned char* insn)
{
if( insn[0] == 0x8b ) { /* mov r,r/m */
bool has_sib = (insn[1] & 7) == 4 && insn[1] < 0xc0;
bool has_disp8 = (insn[1] >> 6) == 1;
bool has_disp32 = (insn[1] >> 6) == 2 || (insn[1] & 0xc7) == 0x04;
return 2 + has_sib + has_disp8 + has_disp32 * 4;
}
return 0;
}
#endif
static void* find_close_nocancel(void)
{
void* close_nocancel = dlsym(NULL, "__close_nocancel");
if( close_nocancel )
return close_nocancel;
#ifdef __x86_64__
{
/* Only newish versions of glibc (e.g. RHEL8) export __close_nocancel.
* Prior versions (before glibc 329ea513b4) had it inline in close().
* That's still hard to find, however, since other components of glibc
* also export a close/__close, e.g. libpthread.so.
* Instead we start at _IO_file_close, which is a moderately simple
* wrapper of __close_nocancel, i.e. it ends with a jmp to it. */
int n;
unsigned char* io_file_close;
io_file_close = dlsym(RTLD_NEXT, "_IO_file_close");
if( ! io_file_close )
return NULL;
if( ! memcmp(io_file_close, x64_endbr, sizeof(x64_endbr)) )
io_file_close += sizeof(x64_endbr);
/* Needed for SLES15 sp4 with GNU libc 2.31 */
while( ! memcmp(io_file_close, x64_nop, sizeof(x64_nop)) )
io_file_close += sizeof(x64_nop);
while( (n = is_io_file_close_insn(io_file_close)) != 0 )
io_file_close += n;
if( *io_file_close != 0xe9 ) /* jmp rel32 */
return NULL;
return io_file_close + 5 + *(uint32_t*)(io_file_close + 1);
}
#else
/* We do not do extra searching on aarch64, since we don't support old glibc
* there */
return NULL;
#endif
}
static int patch_libc_close_nocancel(void)
{
unsigned char* close_nocancel = find_close_nocancel();
if( ! close_nocancel ) {
LOG_S(ci_log("libc __close_nocancel not found: not running glibc?"));
return -ENOENT;
}
#ifdef __x86_64__
{
static const unsigned char sysclose[] = {
0xb8, 0x03, 0x00, 0x00, 0x00, /* mov $3, %eax */
0x0f, 0x05 /* syscall */
};
static const unsigned char call_rax[] = {
0xff, 0xd0 /* call *%rax */
};
static const unsigned char trampo_code[] = {
0xf3, 0x0f, 0x1e, 0xfa, /* endbr64 */
0x48, 0xb8, 0xef, 0xcd, 0xab, 0x89, 0x67,
0x45, 0x23, 0x01, /* movabs $0x123456789abcdef,%rax */
0xff, 0xe0, /* jmpq *%rax */
};
unsigned char new_glibc_bytes[6];
unsigned char* trampoline;
long (*target)(long) = &oo_close_nocancel_entry;
int rc;
/* One x86-64 we somehow have to replace the 7 bytes "mov $3,eax;syscall"
* with a call to an 8-byte absolute address. The fundamental insight here
* is to use mmap(MAP_32BIT) to get ourselves a 32-bit address and put an
* intermediate trampoline there. That allows us to replace those 7 bytes
* with a call to a 4-byte absolute address. Doable. */
if( ! memcmp(close_nocancel, x64_endbr, sizeof(x64_endbr)) )
close_nocancel += sizeof(x64_endbr);
/* Needed for SLES15 sp4 with GNU libc 2.31 */
while( ! memcmp(close_nocancel, x64_nop, sizeof(x64_nop)) )
close_nocancel += sizeof(x64_nop);
if( memcmp(close_nocancel, sysclose, sizeof(sysclose)) ) {
LOG_S(ci_log("Mismatching syscall implementation in __close_nocancel"));
return -ESRCH;
}
trampoline = mmap(NULL, sizeof(trampo_code), PROT_READ | PROT_WRITE,
MAP_32BIT | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if( trampoline == MAP_FAILED ) {
rc = -errno;
LOG_S(ci_log("__close_nocancel mmap failed: %d", errno));
return rc;
}
ci_assert_le((uintptr_t)trampoline, 0xffffffff);
memcpy(trampoline, trampo_code, sizeof(trampo_code));
memcpy(trampoline + 6, &target, sizeof(void*));
rc = mprotect(trampoline, CI_PAGE_SIZE, PROT_READ | PROT_EXEC);
if( rc != 0 ) {
char err_msg[64];
snprintf(err_msg, sizeof(err_msg),
"CRITICAL: mprotect(trampoline) = %d\n", errno);
ci_sys_write(STDERR_FILENO, err_msg, strlen(err_msg));
rc = -errno;
return rc;
}
memcpy(new_glibc_bytes, &trampoline, 4);
memcpy(new_glibc_bytes + 4, call_rax, sizeof(call_rax));
return modify_glibc_code(close_nocancel + 1, new_glibc_bytes,
sizeof(new_glibc_bytes));
}
#elif defined __aarch64__
{
static const unsigned expected[] = {
0x93407c00, /* sxtw x0, w0 */
0xd2800728, /* mov x8, #57 */
0xd4000001, /* svc #0 */
};
unsigned replacement[] = {
0xd2a00008, /* mov x8, #0xnnnn0000 */
0xf2c00008, /* movk x8, #0xnnnn, lsl #32 */
0xd61f0100, /* br x8 */
};
static const unsigned trampo_code[] = {
0xa9bf7bfd, /* stp x29, x30, [sp, #-16]! */
0x910003fd, /* mov x29, sp */
0xd2800008, /* mov x8, #0xnnnn */
0xf2a00008, /* movk x8, #0xnnnn, lsl #16 */
0xf2c00008, /* movk x8, #0xnnnn, lsl #32 */
0xf2e00008, /* movk x8, #0xnnnn, lsl #48 */
0xd63f0100, /* blr x8 */
0xa8c17bfd, /* ldp x29, x30, [sp], #16 */
0xd2800008, /* mov x8, #0xnnnn */
0xf2a00008, /* movk x8, #0xnnnn, lsl #16 */
0xf2c00008, /* movk x8, #0xnnnn, lsl #32 */
0xf2e00008, /* movk x8, #0xnnnn, lsl #48 */
0xd61f0100, /* br x8 */
};
void* trampo_area;
unsigned* trampoline;
int rc;
if( memcmp(close_nocancel, expected, sizeof(expected)) ) {
LOG_S(ci_log("Mismatching syscall implementation in __close_nocancel"));
return -ESRCH;
}
/* In order to fit the replacement into the requisite 3 instructions we
* need a 64KB-aligned address to jump to. Allocate 64KB of address space
* and map only the useful page. AArch64 has only a 48-bit virtual address
* space, so we get a pointer we can fit in to two mov instructions. */
trampo_area = mmap(NULL, 65536, PROT_NONE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
if( trampo_area == MAP_FAILED ) {
rc = -errno;
LOG_S(ci_log("__close_nocancel reservation failed: %d", errno));
return rc;
}
trampoline = (unsigned*)CI_PTR_ALIGN_FWD(trampo_area, 65536);
if( mmap(trampoline, CI_PAGE_SIZE, PROT_READ | PROT_WRITE,
MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0) != trampoline ) {
rc = -errno;
LOG_S(ci_log("__close_nocancel mmap failed: %d", errno));
return rc;
}
memcpy(trampoline, trampo_code, sizeof(trampo_code));
aarch64_write_ptr_insns(trampoline + 2, oo_close_nocancel_entry);
aarch64_write_ptr_insns(trampoline + 8, (unsigned*)close_nocancel + 3);
rc = mprotect(trampoline, CI_PAGE_SIZE, PROT_READ | PROT_EXEC);
if( rc != 0 ) {
char err_msg[64];
snprintf(err_msg, sizeof(err_msg),
"CRITICAL: mprotect(trampoline) = %d\n", errno);
ci_sys_write(STDERR_FILENO, err_msg, strlen(err_msg));
rc = -errno;
return rc;
}
ci_assert_equal((uintptr_t)trampoline & 0xffff, 0);
ci_assert_equal((uintptr_t)trampoline >> 48, 0);
replacement[0] |= (((uintptr_t)trampoline >> 16) & 0xffff) << 5;
replacement[1] |= (((uintptr_t)trampoline >> 32) & 0xffff) << 5;
return modify_glibc_code(close_nocancel, replacement, sizeof(replacement));
}
#else
/* x86 plan:
* The syscall instruction is 65 ff 15 10 00 00 00 call *%gs:0x10, so we
* can just overwrite the whole thing with
* "push %ebx;call close_nocancel_entry;pop %ebx"
*/
LOG_S(ci_log("Unsupported architecture for patching libc close"));
return -EOPNOTSUPP;
#endif
}
int citp_fdtable_ctor()
{
struct rlimit rlim;
int rc;
Log_S(log("%s:", __FUNCTION__));
/* How big should our fdtable be by default? It's pretty arbitrary, but we have
* seen a few apps that use setrlimit to set the fdtable to 4096 entries on
* start-up (see bugs 3253 and 3373), so we choose that. (Note: we can't grow
* the table if the app later does setrlimit, and unused entries consume virtual
* space only, so it's worth allocating a table of reasonable sized.)
*/
citp_fdtable.size = 4096;
if( getrlimit(RLIMIT_NOFILE, &rlim) == 0 ) {
citp_fdtable.size = rlim.rlim_max;
if( CITP_OPTS.fdtable_size != 0 &&
CITP_OPTS.fdtable_size != rlim.rlim_max ) {
Log_S(ci_log("Set the limits for the number of opened files "
"to EF_FDTABLE_SIZE=%u value.",
CITP_OPTS.fdtable_size));
rlim.rlim_max = CITP_OPTS.fdtable_size;
if( rlim.rlim_cur > rlim.rlim_max )
rlim.rlim_cur = rlim.rlim_max;
if( ci_sys_setrlimit(RLIMIT_NOFILE, &rlim) == 0 )
citp_fdtable.size = rlim.rlim_max;
else {
/* Most probably, we've got EPERM */
ci_assert_lt(citp_fdtable.size, CITP_OPTS.fdtable_size);
ci_log("Can't set EF_FDTABLE_SIZE=%u; using %u",
CITP_OPTS.fdtable_size, citp_fdtable.size);
rlim.rlim_max = rlim.rlim_cur = citp_fdtable.size;
CI_TRY(ci_sys_setrlimit(RLIMIT_NOFILE, &rlim));
}
}
}
else
Log_S(ci_log("Assume EF_FDTABLE_SIZE=%u", citp_fdtable.size));
citp_fdtable.inited_count = 0;
citp_fdtable.table = malloc(sizeof (citp_fdtable_entry) *
citp_fdtable.size);
if( ! citp_fdtable.table ) {
Log_U(log("%s: failed to allocate fdtable (0x%x)", __FUNCTION__,
citp_fdtable.size));
return -1;
}
/* The whole table is not initialised at start-of-day, but is initialised
** on demand. citp_fdtable.inited_count counts the number of initialised
** entries.
*/
if( (rc = oo_rwlock_ctor(&citp_ul_lock)) != 0 ) {
Log_E(log("%s: oo_rwlock_ctor(ul_lock) %d", __FUNCTION__, rc));
return -1;
}
if( (rc = oo_rwlock_ctor(&citp_dup2_lock)) != 0 ) {
Log_E(log("%s: oo_rwlock_ctor(dup2_lock) %d", __FUNCTION__, rc));
return -1;
}
rc = patch_libc_close_nocancel();
if( rc < 0 ) {
Log_E(log("%s: Didn't intercept libc internal close %d", __FUNCTION__, rc));
/* Which is bad, but not fatal */
}
/* Install SIGONLOAD handler */
rc = oo_sigonload_init(sighandler_sigonload);
if( rc < 0 )
return rc;
return 0;
}
#if !defined (NDEBUG) || CI_CFG_FDTABLE_CHECKS
/* This function does some simple tests to ensure that the fdtable makes sense.
* There are many more tests we could do; feel free to add them at your
* leisure!
*/
void
citp_fdtable_assert_valid(void)
{
int i;
if( ! citp_fdtable.table ) return;
CITP_FDTABLE_LOCK_RD();
for( i = 0; i < citp_fdtable.inited_count; i++ ) {
citp_fdinfo_p fdip = citp_fdtable.table[i].fdip;
if( fdip_is_normal(fdip) ) {
citp_fdinfo * fdi = fdip_to_fdi(fdip);
ci_assert(fdi);
ci_assert(fdi->protocol);
if( ( fdi->protocol->type == CITP_TCP_SOCKET ||
fdi->protocol->type == CITP_UDP_SOCKET )
&& fdi_to_socket(fdi)->s )
ci_assert(! (fdi_to_socket(fdi)->s->b.sb_aflags & CI_SB_AFLAG_ORPHAN));
if (!fdi->is_special) {
/* Ensure the "back pointer" makes sense */
ci_assert (fdi->fd == i);
/* Ensure that the reference count is in a vaguely sensible range */
ci_assert ((oo_atomic_read (&fdi->ref_count) > 0) &&
(oo_atomic_read (&fdi->ref_count) < 10000));
/* 10,000 threads is a bit mad, warn if more than 20 */
if (oo_atomic_read (&fdi->ref_count) > 20) {
Log_U (log ("Warning: fd %d's ref-count suspiciously large (%d)\n",
i, oo_atomic_read (&fdi->ref_count)));
}
}
}
}
CITP_FDTABLE_UNLOCK_RD();
}
#endif
static void fdtable_swap(unsigned fd, citp_fdinfo_p from,
citp_fdinfo_p to, int fdt_locked)
{
volatile citp_fdinfo_p* p_fdip;
citp_fdinfo_p fdip;
p_fdip = &citp_fdtable.table[fd].fdip;
again:
fdip = *p_fdip;
if( fdip_is_busy(fdip) ) fdip = citp_fdtable_busy_wait(fd, fdt_locked);
ci_assert_equal(fdip, from);
if( fdip_cas_fail(p_fdip, from, to) ) goto again;
}
/* If this is called with OO_IOC_TCP_HANDOVER the stack lock must be held */
static int fdtable_fd_move(ci_fd_t sock_fd, int op)
{
ci_uint32 io_fd = sock_fd;
int rc;
oo_rwlock_lock_read(&citp_dup2_lock);
rc = oo_resource_op(sock_fd, op, &io_fd);
if( rc != 0 || io_fd == sock_fd ) {
oo_rwlock_unlock_read(&citp_dup2_lock);
return rc;
}
/* Kernel failed to hand over, but there is no epoll here - let's dup */
rc = ci_sys_dup2(io_fd, sock_fd);
ci_tcp_helper_close_no_trampoline(io_fd);
oo_rwlock_unlock_read(&citp_dup2_lock);
if( rc == sock_fd )
return 0;
else if( rc >= 0 )
return -EINVAL;
return rc;
}
static int
citp_fdtable_probe_restore(int fd, ci_ep_info_t * info, int print_banner,
citp_fdinfo_p* fdip_out)
{
citp_protocol_impl* proto = 0;
citp_fdinfo* fdi = 0;
ci_netif* ni;
int rc = 0;
int c_sock_fdi = 1;
/* Must be holding the FD table writer lock */
CITP_FDTABLE_ASSERT_LOCKED(1);
ci_assert_nequal(info->resource_id, CI_ID_POOL_ID_NONE);
/* Will need to review this function if the following assert fires */
switch( info->fd_flags & OO_FDFLAG_EP_MASK ) {
case OO_FDFLAG_EP_TCP: proto = &citp_tcp_protocol_impl; break;
case OO_FDFLAG_EP_UDP: proto = &citp_udp_protocol_impl; break;
case OO_FDFLAG_EP_PASSTHROUGH:
proto = &citp_passthrough_protocol_impl;
c_sock_fdi = 0;
break;
case OO_FDFLAG_EP_ALIEN:
proto = NULL;
c_sock_fdi = 0;
break;
case OO_FDFLAG_EP_PIPE_READ:
proto = &citp_pipe_read_protocol_impl;
c_sock_fdi = 0;
break;
case OO_FDFLAG_EP_PIPE_WRITE:
proto = &citp_pipe_write_protocol_impl;
c_sock_fdi = 0;
break;
default: ci_assert(0);
}
/* Attempt to find the user-level netif for this endpoint */
ni = citp_find_ul_netif(info->resource_id, 1);
if( ! ni ) {
ef_driver_handle netif_fd;
/* Not found, rebuild/restore the netif for this endpoint */
rc = citp_netif_recreate_probed(fd, &netif_fd, &ni);
if ( rc < 0 ) {
Log_E(log("%s: citp_netif_recreate_probed failed! (%d)",
__FUNCTION__, rc));
goto fail;
}
if( print_banner ) {
ci_netif_log_startup_banner(ni, "Importing");
}
}
else
citp_netif_add_ref(ni);
/* There is a race condition where the fd can have been created, but it has
* not yet been initialised, as we can't put a busy marker in the right place
* in the fdtable until we know what the fd is. In this case we don't want
* to probe this new info, so return the closed fd.
*/
if( SP_TO_WAITABLE(ni, info->sock_id)->sb_aflags & CI_SB_AFLAG_NOT_READY ) {
citp_fdtable_busy_clear(fd, fdip_unknown, 1);
fdi = &citp_the_closed_fd;
citp_fdinfo_ref(fdi);
*fdip_out = fdi_to_fdip(fdi);
return rc;
}
if (c_sock_fdi) {
citp_sock_fdi* sock_fdi;
sock_fdi = CI_ALLOC_OBJ(citp_sock_fdi);
if( ! sock_fdi ) {
Log_E(log("%s: out of memory (sock_fdi)", __FUNCTION__));
rc = -ENOMEM;
goto fail;
}
fdi = &sock_fdi->fdinfo;
sock_fdi->sock.s = SP_TO_SOCK_CMN(ni, info->sock_id);
sock_fdi->sock.netif = ni;
}
else if( info->fd_flags & OO_FDFLAG_EP_PASSTHROUGH ) {
citp_waitable* w = SP_TO_WAITABLE(ni, info->sock_id);
citp_alien_fdi* alien_fdi;
if( ~w->sb_aflags & CI_SB_AFLAG_MOVED_AWAY_IN_EPOLL &&
fdtable_fd_move(fd, OO_IOC_FILE_MOVED) == 0 ) {
citp_netif_release_ref(ni, 1);
*fdip_out = fdip_passthru;
return rc;
}
alien_fdi = CI_ALLOC_OBJ(citp_alien_fdi);
if( ! alien_fdi ) {
Log_E(log("%s: out of memory (alien_fdi)", __FUNCTION__));
rc = -ENOMEM;
goto fail;
}
fdi = &alien_fdi->fdinfo;
alien_fdi->netif = ni;
alien_fdi->ep = SP_TO_WAITABLE(ni, info->sock_id);
citp_passthrough_init(alien_fdi);
}
#if CI_CFG_ENDPOINT_MOVE
else if( info->fd_flags & OO_FDFLAG_EP_ALIEN ) {
citp_waitable* w = SP_TO_WAITABLE(ni, info->sock_id);
citp_sock_fdi* sock_fdi;
ci_netif* alien_ni;
sock_fdi = CI_ALLOC_OBJ(citp_sock_fdi);
if( ! sock_fdi ) {
Log_E(log("%s: out of memory (alien sock_fdi)", __FUNCTION__));
rc = -ENOMEM;
goto fail;
}
fdi = &sock_fdi->fdinfo;
rc = citp_netif_by_id(w->moved_to_stack_id, &alien_ni, 1);
if( rc != 0 ) {
goto fail;
}
sock_fdi->sock.s = SP_TO_SOCK_CMN(alien_ni, w->moved_to_sock_id);
sock_fdi->sock.netif = alien_ni;
citp_netif_release_ref(ni, 1);
/* Replace the file under this fd if possible */
if( ~w->sb_aflags & CI_SB_AFLAG_MOVED_AWAY_IN_EPOLL )
fdtable_fd_move(fd, OO_IOC_FILE_MOVED);
if( sock_fdi->sock.s->b.state & CI_TCP_STATE_TCP )
proto = &citp_tcp_protocol_impl;
else if( sock_fdi->sock.s->b.state == CI_TCP_STATE_UDP )
proto = &citp_udp_protocol_impl;
else {
CI_TEST(0);
}
}
#endif
else {
citp_pipe_fdi* pipe_fdi;
pipe_fdi = CI_ALLOC_OBJ(citp_pipe_fdi);
if( ! pipe_fdi ) {
Log_E(log("%s: out of memory (pipe_fdi)", __FUNCTION__));
rc = -ENOMEM;
goto fail;
}
fdi = &pipe_fdi->fdinfo;
pipe_fdi->pipe = SP_TO_PIPE(ni, info->sock_id);
pipe_fdi->ni = ni;
}
citp_fdinfo_init(fdi, proto);
/* We're returning a reference to the caller. */
citp_fdinfo_ref(fdi);
citp_fdtable_insert(fdi, fd, 1);
*fdip_out = fdi_to_fdip(fdi);
return rc;
fail:
if( ni ) citp_netif_release_ref(ni, 1);
*fdip_out = fdip_unknown;
return rc;
}
/* Find out what sort of thing [fd] is, and if it is a user-level socket
* then map in the user-level state.
*/
static int
citp_fdtable_probe_locked(unsigned fd, int print_banner,
int fdip_is_already_busy, citp_fdinfo** fdi_out)
{
citp_fdinfo* fdi = NULL;
struct stat64 st;
ci_ep_info_t info;
int rc = 0;
if( ! fdip_is_already_busy ) {
volatile citp_fdinfo_p* p_fdip;
citp_fdinfo_p fdip;
/* ?? We're repeating some effort already expended in lookup() here, but
** this keeps it cleaner. May optimise down the line when I understand
** what other code needs to call this.
*/
p_fdip = &citp_fdtable.table[fd].fdip;
again:
fdip = *p_fdip;
if( fdip_is_busy(fdip) ) fdip = citp_fdtable_busy_wait(fd, 1);
if( ! fdip_is_unknown(fdip) && ! fdip_is_normal(fdip) ) goto exit;
if( fdip_cas_fail(p_fdip, fdip, fdip_busy) ) goto again;
if( fdip_is_normal(fdip) ) {
fdi = fdip_to_fdi(fdip);
citp_fdinfo_ref(fdi);
citp_fdtable_busy_clear(fd, fdip, 1);
goto exit;
}
}
if( ci_sys_fstat64(fd, &st) != 0 ) {
/* fstat() failed. Must be a bad (closed) file descriptor, so
** leave this entry as unknown. Return citp_the_closed_fd to avoid the
** caller passing through to an fd that is created asynchronously.
*/
citp_fdtable_busy_clear(fd, fdip_unknown, 1);
fdi = &citp_the_closed_fd;
citp_fdinfo_ref(fdi);
goto exit;
}
/* oo_get_st_rdev() and oo_onloadfs_dev_t() open-and-close fd, so
* fdtable should be locked if strict mode requested. */
if( fdtable_strict() ) { CITP_FDTABLE_ASSERT_LOCKED(1); }
if( st.st_dev == oo_onloadfs_dev_t() ) {
/* Retrieve user-level endpoint info */
if( oo_ep_info(fd, &info) < 0 ) {
Log_V(log("%s: fd=%d unknown type "OO_FDFLAG_FMT,
__FUNCTION__, fd, OO_FDFLAG_ARG(info.fd_flags)));
citp_fdtable_busy_clear(fd, fdip_passthru, 1);
goto exit;
}
switch( info.fd_flags & (OO_FDFLAG_EP_MASK | OO_FDFLAG_STACK) ) {
case OO_FDFLAG_EP_TCP:
case OO_FDFLAG_EP_UDP:
case OO_FDFLAG_EP_PASSTHROUGH:
case OO_FDFLAG_EP_ALIEN:
case OO_FDFLAG_EP_PIPE_READ:
case OO_FDFLAG_EP_PIPE_WRITE:
{
citp_fdinfo_p fdip;
Log_V(log("%s: fd=%d restore type "OO_FDFLAG_FMT, __FUNCTION__, fd,
OO_FDFLAG_ARG(info.fd_flags)));
rc = citp_fdtable_probe_restore(fd, &info, print_banner, &fdip);
if( fdip_is_normal(fdip) )
fdi = fdip_to_fdi(fdip);
else
citp_fdtable_busy_clear(fd, fdip, 1);
goto exit;
}
case OO_FDFLAG_STACK:
/* This should never happen, because netif fds are close-on-exec.
** But let's leave this code here just in case my reasoning is bad.
*/
Log_U(log("%s: fd=%d NETIF reserved", __FUNCTION__, fd));
citp_fdtable_busy_clear(fd, fdip_reserved, 1);
fdi = &citp_the_reserved_fd;
citp_fdinfo_ref(fdi);
goto exit;
default:
/* This happens if a thread gets at an onload driver fd that has just
* been created, but not yet specialised. On Linux I think this
* means it will shortly be a new netif internal fd. (fds associated
* with sockets and pipes are never unspecialised).
*/
Log_V(log("%s: fd=%d TYPE_NONE", __FUNCTION__, fd));
citp_fdtable_busy_clear(fd, fdip_passthru, 1);
goto exit;
}
}
#if CI_CFG_EPOLL2
else if( ci_major(st.st_rdev) == ci_major(oo_get_st_rdev(OO_EPOLL_DEV)) ) {
citp_epollb_fdi *epi = CI_ALLOC_OBJ(citp_epollb_fdi);
if( ! epi ) {
Log_E(log("%s: out of memory (epoll_fdi)", __FUNCTION__));
citp_fdtable_busy_clear(fd, fdip_passthru, 1);
goto exit;
}
oo_epollb_ctor(epi);
fdi = &epi->fdinfo;
citp_fdinfo_init(fdi, &citp_epollb_protocol_impl);
citp_fdinfo_ref(fdi);
citp_fdtable_insert(fdi, fd, 1);
goto exit;
}
#endif
#ifndef NDEBUG
/* /dev/onload may be netif or log_fd or onload_fd;
* they are closed on fork or exec */
if( ci_major(st.st_rdev) == ci_major(oo_get_st_rdev(OO_STACK_DEV)) )
Log_U(log("%s: %d is /dev/onload", __FUNCTION__, fd));
#endif
/* Not one of ours, so pass-through. */
Log_V(log("%s: fd=%u non-efab", __FUNCTION__, fd));
citp_fdtable_busy_clear(fd, fdip_passthru, 1);
exit:
*fdi_out = fdi;
return rc;
}
static citp_fdinfo *
citp_fdtable_probe(unsigned fd)
{
citp_fdinfo* fdi;
int saved_errno;
ci_assert(fd < citp_fdtable.size);
if( ! CITP_OPTS.probe || oo_per_thread_get()->in_vfork_child )
return NULL;
saved_errno = errno;
CITP_FDTABLE_LOCK();
__citp_fdtable_extend(fd);
citp_fdtable_probe_locked(fd, CI_FALSE, CI_FALSE, &fdi);
CITP_FDTABLE_UNLOCK();
errno = saved_errno;
return fdi;
}
static int
citp_fdinfo_is_consistent(citp_fdinfo* fdi)
{
switch( fdi->protocol->type ) {
case CITP_TCP_SOCKET:
case CITP_UDP_SOCKET:
return ~fdi_to_sock_fdi(fdi)->sock.s->b.sb_aflags & CI_SB_AFLAG_MOVED_AWAY;
}
return CI_TRUE;
}
citp_fdinfo *
citp_fdtable_lookup(unsigned fd)
{
/* Note that if we haven't yet initialised this module, then
** [inited_count] will be zero, and the following test will fail. So the
** test for initialisation is done further down...
**
** This is highly performance critial. DO NOT add any code between here
** and the first [return] statement.
*/
citp_fdinfo* fdi;
/* In some cases, we'll lock fdtable. Assert that it is possible: */
ci_assert(oo_per_thread_get()->sig.c.inside_lib);
if( fd < citp_fdtable.inited_count ) {
volatile citp_fdinfo_p* p_fdip = &citp_fdtable.table[fd].fdip;
citp_fdinfo_p fdip;
again:
/* Swap in the busy marker. */
fdip = *p_fdip;
if( fdip_is_normal(fdip) ) {
if( citp_fdtable_not_mt_safe() ) {
if( fdip_cas_succeed(p_fdip, fdip, fdip_busy) ) {
fdi = fdip_to_fdi(fdip);
ci_assert(fdi);
ci_assert_gt(oo_atomic_read(&fdi->ref_count), 0);
ci_assert(fdip_is_closing(fdip) || fdip_is_reserved(fdip) ||
fdi->fd == fd);
/* Bump the reference count. */
citp_fdinfo_ref(fdi);
if( ! citp_fdinfo_is_consistent(fdi) ) {
/* Something is wrong. Re-probe. */
fdi = citp_reprobe_moved(fdi, CI_FALSE, CI_TRUE);
}