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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
//! pNFS I/O: parallel reads and writes to data servers (RFC 5661 ยง12-13).
//!
//! This module adds pNFS layout-aware I/O methods to `Mount41`. When a file
//! has a granted layout, reads and writes are striped across data servers in
//! parallel. If pNFS is unavailable or fails, callers fall back to MDS I/O.
use std::collections::HashSet;
use std::future::Future;
use std::net::SocketAddr;
use bytes::{Buf, Bytes, BytesMut};
use tracing::{debug, info};
use super::Nfs4ErrorCode;
use super::compound::CompoundResponse;
use super::fastxdr::nfsstat4;
#[cfg(test)]
use super::layout::LayoutManager;
use super::layout::{IoMode, Layout, LayoutContent, LayoutSegment};
use super::mount::Mount41;
use super::state::{AccessMode, StateId};
use crate::error::{
NfsError, OperationClass, OperationOutcome, OperationOutcomeError, RecoveryAction,
RequestContext, Result,
};
/// Whether pNFS WRITE transmitted a DS mutation.
///
/// Only `NotAttempted` permits the caller to fall back to an MDS WRITE. Once a
/// DS batch starts, every result remains on the `Attempted` path so an
/// ambiguous mutation can never be silently overwritten through the MDS.
pub(crate) enum PnfsWriteOutcome {
NotAttempted,
Attempted(Result<u32>),
}
struct PlannedDsWrite {
stripe_index: usize,
ds_fh: Bytes,
ds_addr: SocketAddr,
ds_offset: u64,
data: Bytes,
}
struct DsWriteCompletion<T> {
stripe_index: usize,
ds_addr: SocketAddr,
result: Result<T>,
}
fn ds_batch_diagnostic<T>(completions: &[DsWriteCompletion<T>]) -> String {
completions
.iter()
.map(|completion| match &completion.result {
Ok(_) => format!(
"stripe={} ds={} attempted=true outcome=success",
completion.stripe_index, completion.ds_addr
),
Err(error) => format!(
"stripe={} ds={} attempted=true outcome=error error={error}",
completion.stripe_index, completion.ds_addr
),
})
.collect::<Vec<_>>()
.join("; ")
}
fn uncertain_pnfs_write(context: RequestContext, source: NfsError) -> NfsError {
NfsError::OperationOutcome(Box::new(OperationOutcomeError::new(
OperationOutcome::Uncertain,
OperationClass::ReplaySensitive,
RecoveryAction::VerifyThenResume,
context,
source,
)))
}
/// Wait for every request in an already-issued DS batch before reporting its
/// aggregate result. Unlike `try_join_all`, an early error cannot cancel a
/// sibling WRITE whose request may already be on the wire. Errors are selected
/// in plan order, so diagnostics do not depend on network completion order.
async fn settle_ds_batch<T, F>(futures: Vec<(usize, SocketAddr, F)>) -> Vec<DsWriteCompletion<T>>
where
F: Future<Output = Result<T>>,
{
futures::future::join_all(futures.into_iter().map(
|(stripe_index, ds_addr, future)| async move {
DsWriteCompletion {
stripe_index,
ds_addr,
result: future.await,
}
},
))
.await
}
#[cfg(test)]
async fn invalidate_layout_after_ds_error(
layout_manager: &LayoutManager,
fh: &Bytes,
error: &NfsError,
) {
if matches!(error, NfsError::Nfs4(Nfs4ErrorCode::NFS4ERR_STALE)) {
layout_manager.remove_layout(fh).await;
layout_manager.invalidate_dirty(fh).await;
}
}
/// Find the layout segment covering a given file offset.
fn find_covering_segment(layout: &Layout, offset: u64) -> Option<&LayoutSegment> {
layout
.segments
.iter()
.find(|segment| segment.covers(offset))
}
impl Mount41 {
async fn preflight_write_data_servers(
&self,
writes: &[PlannedDsWrite],
generation: u64,
) -> Result<()> {
let addresses = writes
.iter()
.map(|write| write.ds_addr)
.filter(|address| *address != self.server_addr)
.collect::<HashSet<_>>();
futures::future::try_join_all(addresses.into_iter().map(|address| async move {
self.layout_manager
.get_data_server(address, &self.auth, &self.client_identity, generation)
.await
.map(|_| ())
}))
.await?;
Ok(())
}
/// Get layout for a file, fetching from MDS if not cached.
/// Returns None if pNFS layouts are unavailable (caller should fall back to MDS I/O).
pub(crate) async fn get_or_fetch_layout(
&self,
fh: &Bytes,
iomode: IoMode,
offset: u64,
) -> Option<Layout> {
self.fetch_layout(fh, iomode, offset, false).await
}
async fn fetch_layout(
&self,
fh: &Bytes,
iomode: IoMode,
offset: u64,
force_update: bool,
) -> Option<Layout> {
// RFC 5661 ยง18.35.3๏ผserver ๆชๅจ EXCHANGE_ID ไธญๅฃฐๆ USE_PNFS_MDS๏ผ
// ๆดไธช mount ็ฆ็จ pNFS๏ผ่ทณ่ฟ LAYOUTGET๏ผ็ๆฏๆไปถไธๆฌกๆณจๅฎๅคฑ่ดฅ็ RTT๏ผ
if !self.session_holder.get().await.pnfs_mds() {
return None;
}
// 1. Check cache
if !force_update
&& let Some(layout) = self.layout_manager.get_layout_covering(fh, offset).await
{
return Some(layout);
}
// 2. LAYOUTGET to MDS: COMPOUND(SEQUENCE, PUTFH, LAYOUTGET)
// iomode 1=READ, 2=RW โ use matching access mode to avoid NFS4ERR_OPENMODE.
let access = match iomode {
IoMode::Read => AccessMode::Read,
IoMode::ReadWrite => AccessMode::Write,
};
let cached = self.layout_manager.get_layout(fh).await;
let sid = self
.state
.has_open(fh, access)
.await
.unwrap_or_else(StateId::anonymous);
let request_stateid = cached
.as_ref()
.map(|layout| layout.stateid)
.unwrap_or(sid.raw);
let result = self
.compound("layoutget", |b| {
b.require_generation(sid.generation).putfh(fh).layoutget(
false, // signal_layout_avail
1, // LAYOUT4_NFSV4_1_FILES
iomode as u32,
offset,
u64::MAX - offset,
0, // min_length
&request_stateid,
1024 * 1024, // max_count (1 MiB)
)
})
.await;
match result {
Ok(resp) => {
// LAYOUTGET result is after SEQUENCE=0, PUTFH=1 โ index 2
let op = resp.op_ok(2).ok()?;
let mut data = op.data.clone();
let mut layout = super::layout::decode_layoutget_response(&mut data).ok()?;
layout.generation = resp.session_generation;
let accepted = if cached.is_some() {
self.layout_manager.merge_layout(fh, layout.clone()).await;
self.layout_manager.get_layout(fh).await.is_some()
} else {
self.layout_manager
.store_layout_at(fh, resp.session_generation, layout.clone())
.await
};
if accepted {
// Only an accepted layout may populate generation-owned caches.
self.fetch_devices_for_layout(&layout).await;
self.layout_manager.get_layout(fh).await
} else {
debug!(
response_generation = resp.session_generation,
active_generation = self.layout_manager.generation(),
"discarding stale LAYOUTGET response"
);
None
}
}
Err(e) => {
debug!(error = %e, "LAYOUTGET failed, falling back to MDS I/O");
None
}
}
}
/// ่ฏฅๆไปถ็ pNFS ่ฎพๅคๆฏๅฆ้ๅ๏ผๆๆ DS ๅฐๅ้ฝ็ญไบ MDS๏ผใ
///
/// ้ๅๆถ DS I/O ไธ MDS I/O ็ฝ็ป่ทฏๅพๅฎๅ
จ็ญไปท๏ผ่ตฐ pNFS ๅชๅคไป
/// LAYOUTCOMMIT ็ญ็ฎก็ๅผ้๏ผI/O ่ทฏๅพๅบๅ้ MDSใๅคๅฎๆ device
/// ่้ mount ็บงโโFlexGroup ็ญๅค device ๆๆไธ๏ผไธๅๆไปถๅฏ่ฝ
/// ่ฝๅจไธๅ่็น๏ผๅ
ถไธญ้จๅ device ้ๅใ้จๅไธ้ๅใ
fn device_degenerate(&self, device: &super::layout::DeviceInfo) -> bool {
let degenerate = super::layout::is_degenerate_device(device, &self.server_addr);
if degenerate && self.layout_manager.should_log_degenerate() {
info!(
"pNFS degenerate device: data servers resolve to the MDS, using MDS I/O for affected files"
);
}
degenerate
}
/// ่ฏฅ่ฎพๅคๅผ็จ็ไปปไธ้ MDS ็ DS ้ฆ้ๅฐๅๅทฒ่ขซๆ ่ฎฐไธๅฏ่พพๆถ่ฟๅ true๏ผ
/// ่ฐ็จๆน็ดๆฅๅ้ MDS I/O๏ผlayout ไฟ็็ผๅญ๏ผ้ฟๅ
ๅๅค LAYOUTGET๏ผใ
async fn device_ds_unreachable(&self, device: &super::layout::DeviceInfo) -> bool {
for paths in &device.ds_addrs {
if let Some(addr) = paths.first()
&& *addr != self.server_addr
&& self.layout_manager.is_ds_unreachable(addr).await
{
return true;
}
}
false
}
/// Fetch GETDEVICEINFO for each unique device_id referenced by a layout.
async fn fetch_devices_for_layout(&self, layout: &Layout) {
let mut seen = HashSet::new();
for seg in &layout.segments {
if let LayoutContent::FilesLayout { device_id, .. } = &seg.content {
if !seen.insert(*device_id) {
continue;
}
if self.layout_manager.get_device(device_id).await.is_some() {
continue;
}
// GETDEVICEINFO: COMPOUND(SEQUENCE, PUTROOTFH, GETDEVICEINFO)
match self
.compound("getdeviceinfo", |b| {
b.require_generation(layout.generation)
.putrootfh()
.getdeviceinfo(device_id, 1, 1024 * 1024)
})
.await
{
Ok(resp) => {
// GETDEVICEINFO is after SEQUENCE=0, PUTROOTFH=1 โ index 2
if let Ok(op) = resp.op_ok(2) {
let mut data = op.data.clone();
if let Ok(mut info) =
super::layout::decode_getdeviceinfo_response(&mut data)
{
// multipath ๅฐๅๆไธ MDS ็็ฝ็ปๆฅ่ฟๅบฆๆๅบๅๅ็ผๅญ๏ผ
// ้ฟๅ
DS I/O ้ๅฐๅฎขๆท็ซฏไธๅฏ่พพ็ฝๆฎต็ LIF
super::layout::sort_multipath_by_affinity(
&mut info,
&self.server_addr,
);
if !self
.layout_manager
.store_device_at(*device_id, layout.generation, info)
.await
{
debug!(
layout_generation = layout.generation,
"discarding stale GETDEVICEINFO response"
);
}
}
}
}
Err(e) => {
debug!(error = %e, "GETDEVICEINFO failed");
}
}
}
}
}
// โโโ DS chunk I/O โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
/// ๅฏนๅไธช stripe chunk ๅ DS READ๏ผCOMPOUND: SEQUENCE, PUTFH, READ๏ผใ
/// MDS ๅณ DS ๆถๅค็จไธป session๏ผ้ฟๅ
ๅฏนๅไธ server ้ๅคๅปบ client-id๏ผ๏ผ
/// ๅฆๅ่ตฐ DS ่ชๅทฑ็ session๏ผNFS4ERR_BADSESSION/DEADSESSION ๆถ้ๅปบไธๆฌกใ
async fn ds_read_chunk(
&self,
ds_addr: SocketAddr,
ds_fh: &Bytes,
stateid: &[u8; 16],
generation: u64,
offset: u64,
count: u32,
) -> Result<CompoundResponse> {
if ds_addr == self.server_addr {
return self
.compound_data("ds-read-mds", count as usize, |b| {
b.require_generation(generation)
.putfh(ds_fh)
.read(stateid, offset, count)
})
.await;
}
let ds = self
.layout_manager
.get_data_server(ds_addr, &self.auth, &self.client_identity, generation)
.await?;
let result = Mount41::compound_ds(&ds, &self.auth, "ds-read", count as usize, |b| {
b.putfh(ds_fh).read(stateid, offset, count)
})
.await;
match result {
Err(NfsError::Nfs4(nfsstat4::NFS4ERR_BADSESSION | nfsstat4::NFS4ERR_DEADSESSION)) => {
// DS session ๅคฑๆ๏ผๅฆ้ฟๆถ้ด็ฉบ้ฒๅ่ฟๆ๏ผ๏ผ้ๅปบไธๆฌกๅ่ฏ
self.layout_manager.remove_data_server(ds_addr).await;
let ds = self
.layout_manager
.get_data_server(ds_addr, &self.auth, &self.client_identity, generation)
.await?;
Mount41::compound_ds(&ds, &self.auth, "ds-read", count as usize, |b| {
b.putfh(ds_fh).read(stateid, offset, count)
})
.await
}
other => other,
}
}
/// ๅฏนๅไธช stripe chunk ๅ DS WRITE๏ผCOMPOUND: SEQUENCE, PUTFH, WRITE๏ผ๏ผ
/// ่ทฏ็ฑไธ session ๅคฑๆๅค็ๅ [`Self::ds_read_chunk`]ใ
async fn ds_write_chunk(
&self,
ds_addr: SocketAddr,
ds_fh: &Bytes,
stateid: &[u8; 16],
generation: u64,
ds_off: u64,
data: Bytes,
) -> Result<CompoundResponse> {
let len = data.len() as u32;
if ds_addr == self.server_addr {
return self
.compound_write("ds-write-mds", data, |b| {
b.require_generation(generation)
.putfh(ds_fh)
.write_header(stateid, ds_off, 2 /* FILE_SYNC4 */, len)
})
.await;
}
let ds = self
.layout_manager
.get_data_server(ds_addr, &self.auth, &self.client_identity, generation)
.await?;
let result = Mount41::compound_ds_write(&ds, &self.auth, "ds-write", data.clone(), |b| {
b.putfh(ds_fh)
.write_header(stateid, ds_off, 2 /* FILE_SYNC4 */, len)
})
.await;
match result {
Err(NfsError::Nfs4(nfsstat4::NFS4ERR_BADSESSION | nfsstat4::NFS4ERR_DEADSESSION)) => {
self.layout_manager.remove_data_server(ds_addr).await;
let ds = self
.layout_manager
.get_data_server(ds_addr, &self.auth, &self.client_identity, generation)
.await?;
Mount41::compound_ds_write(&ds, &self.auth, "ds-write", data, |b| {
b.putfh(ds_fh)
.write_header(stateid, ds_off, 2 /* FILE_SYNC4 */, len)
})
.await
}
other => other,
}
}
// โโโ pNFS Read โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
/// Attempt a pNFS parallel read.
/// Returns `None` if layout is unavailable (caller should fall back to MDS).
/// Returns `Some(Ok(data))` on success, `Some(Err(e))` is never returned โ
/// on DS error the layout is evicted and `None` is returned for MDS fallback.
pub(crate) async fn pnfs_read(
&self,
fh: &Bytes,
offset: u64,
count: u32,
) -> Option<Result<Bytes>> {
let layout = self.get_or_fetch_layout(fh, IoMode::Read, offset).await?;
let seg = find_covering_segment(&layout, offset)?;
let (device_id, stripe_unit, is_dense, first_stripe_index, pattern_offset, fh_list) =
match &seg.content {
LayoutContent::FilesLayout {
device_id,
stripe_unit,
is_dense,
first_stripe_index,
pattern_offset,
fh_list,
..
} => (
*device_id,
*stripe_unit,
*is_dense,
*first_stripe_index,
*pattern_offset,
fh_list,
),
_ => return None,
};
if stripe_unit == 0 || fh_list.is_empty() {
return None;
}
let device = self.layout_manager.get_device(&device_id).await?;
if device.ds_addrs.len() < fh_list.len() {
return None;
}
// ้ๅ่ฎพๅค๏ผDS == MDS๏ผ๏ผDS ่ทฏๅพๆ ๆถ็๏ผๅ้ MDS I/O
if self.device_degenerate(&device) {
return None;
}
// DS ๅทฒ็ฅไธๅฏ่พพ๏ผๅ้ MDS I/O๏ผlayout ไฟ็๏ผไธๅๅๅคๅฐ่ฏ๏ผ
if self.device_ds_unreachable(&device).await {
return None;
}
// RFC 8881 ยง13.9.1๏ผDS ไธ็ READ ไฝฟ็จ open/delegation stateid๏ผ
// ่้ layout stateid๏ผlayout stateid ไป
็จไบ LAYOUTCOMMIT/LAYOUTRETURN๏ผ
let io_stateid = self
.state
.has_open(fh, AccessMode::Read)
.await
.unwrap_or_else(StateId::anonymous)
.raw;
let num_ds = fh_list.len() as u32;
let chunks = super::layout::split_into_stripes(
offset,
count,
stripe_unit,
is_dense,
first_stripe_index,
num_ds,
pattern_offset,
);
// Issue parallel reads to data servers
let futures: Vec<_> = chunks
.iter()
.map(|chunk| {
// fh_list is indexed by stripe position (ds_index)
// ds_addrs is indexed by physical DS (needs stripe_indices indirection)
let ds_fh_res = fh_list
.get(chunk.ds_index as usize)
.cloned()
.ok_or_else(|| {
NfsError::Rpc(format!("fh_list index {} out of range", chunk.ds_index))
});
let ds_phys_idx = device
.stripe_indices
.get(chunk.ds_index as usize)
.copied()
.unwrap_or(chunk.ds_index) as usize;
let ds_addr_res = device
.ds_addrs
.get(ds_phys_idx)
.and_then(|a| a.first())
.copied()
.ok_or_else(|| NfsError::Rpc(format!("DS index {} out of range", ds_phys_idx)));
let chunk_len = chunk.length;
let chunk_ds_offset = chunk.ds_offset;
async move {
let ds_fh = ds_fh_res?;
let ds_addr = ds_addr_res?;
let resp = self
.ds_read_chunk(
ds_addr,
&ds_fh,
&io_stateid,
layout.generation,
chunk_ds_offset,
chunk_len,
)
.await?;
// ไธป session ๅค็จไธ็ฌ็ซ DS session ไธคๆก่ทฏๅพ็ op ๅธๅฑไธ่ด๏ผ
// SEQUENCE=0, PUTFH=1, READ=2
resp.op_ok(1)?; // PUTFH
let read_op = resp.op_ok(2)?; // READ
let mut data = read_op.data.clone();
// READ4resok: eof(4) + data<>
if data.remaining() < 4 {
return Err(NfsError::Xdr("DS READ result too short".to_string()));
}
let _eof = data.get_u32();
if data.remaining() < 4 {
return Err(NfsError::Xdr("DS READ data length missing".to_string()));
}
let data_len = data.get_u32() as usize;
if data.remaining() < data_len {
return Err(NfsError::Xdr("DS READ data truncated".to_string()));
}
Ok::<Bytes, NfsError>(data.slice(..data_len))
}
})
.collect();
match futures::future::try_join_all(futures).await {
Ok(results) => {
if layout.generation != self.layout_manager.generation() {
return Some(Err(NfsError::Rpc(
"discarding pNFS READ result from stale session generation".to_string(),
)));
}
if results.len() == 1 {
Some(Ok(results.into_iter().next().unwrap_or_default()))
} else {
// Concatenate stripe results in order
let total_len: usize = results.iter().map(|b| b.len()).sum();
let mut combined = BytesMut::with_capacity(total_len);
for chunk_data in results {
combined.extend_from_slice(&chunk_data);
}
Some(Ok(combined.freeze()))
}
}
Err(e) => {
// On DS error, evict layout and return None to fall back to MDS
self.layout_manager.remove_layout(fh).await;
debug!(error = %e, "pNFS read failed, falling back to MDS");
None
}
}
}
// โโโ pNFS Write โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
/// Attempt a pNFS parallel write.
/// Returns `NotAttempted` only while MDS fallback is provably safe. After
/// any DS batch starts, failures are returned as an uncertain attempted
/// mutation and must be verified by the migration consumer.
pub(crate) async fn pnfs_write(
&self,
fh: &Bytes,
offset: u64,
data: Bytes,
) -> PnfsWriteOutcome {
let Some(layout) = self
.get_or_fetch_layout(fh, IoMode::ReadWrite, offset)
.await
else {
return PnfsWriteOutcome::NotAttempted;
};
let Some(seg) = find_covering_segment(&layout, offset) else {
return PnfsWriteOutcome::NotAttempted;
};
let (device_id, stripe_unit, is_dense, first_stripe_index, pattern_offset, fh_list) =
match &seg.content {
LayoutContent::FilesLayout {
device_id,
stripe_unit,
is_dense,
first_stripe_index,
pattern_offset,
fh_list,
..
} => (
*device_id,
*stripe_unit,
*is_dense,
*first_stripe_index,
*pattern_offset,
fh_list,
),
_ => return PnfsWriteOutcome::NotAttempted,
};
if stripe_unit == 0 || fh_list.is_empty() {
return PnfsWriteOutcome::NotAttempted;
}
let Some(device) = self.layout_manager.get_device(&device_id).await else {
return PnfsWriteOutcome::NotAttempted;
};
if device.ds_addrs.len() < fh_list.len() {
return PnfsWriteOutcome::NotAttempted;
}
// ้ๅ่ฎพๅค๏ผDS == MDS๏ผ๏ผDS ่ทฏๅพๆ ๆถ็๏ผๅ้ MDS I/O
if self.device_degenerate(&device) {
return PnfsWriteOutcome::NotAttempted;
}
// DS ๅทฒ็ฅไธๅฏ่พพ๏ผๅ้ MDS I/O๏ผlayout ไฟ็๏ผไธๅๅๅคๅฐ่ฏ๏ผ
if self.device_ds_unreachable(&device).await {
return PnfsWriteOutcome::NotAttempted;
}
// RFC 8881 ยง13.9.1๏ผDS ไธ็ WRITE ไฝฟ็จ open/delegation stateid๏ผ
// ่้ layout stateid๏ผlayout stateid ไป
็จไบ LAYOUTCOMMIT/LAYOUTRETURN๏ผ
let io_stateid = self
.state
.has_open(fh, AccessMode::Write)
.await
.unwrap_or_else(StateId::anonymous)
.raw;
let num_ds = fh_list.len() as u32;
let data_len = data.len();
let chunks = super::layout::split_into_stripes(
offset,
data_len as u32,
stripe_unit,
is_dense,
first_stripe_index,
num_ds,
pattern_offset,
);
// Resolve the complete write plan before any DS mutation. Bytes::slice
// keeps stripe payloads zero-copy.
let writes = match chunks
.iter()
.enumerate()
.map(|(stripe_index, chunk)| {
// fh_list is indexed by stripe position (ds_index)
// ds_addrs is indexed by physical DS (needs stripe_indices indirection)
let ds_fh_res = fh_list
.get(chunk.ds_index as usize)
.cloned()
.ok_or_else(|| {
NfsError::Rpc(format!("fh_list index {} out of range", chunk.ds_index))
});
let ds_phys_idx = device
.stripe_indices
.get(chunk.ds_index as usize)
.copied()
.unwrap_or(chunk.ds_index) as usize;
let ds_addr_res = device
.ds_addrs
.get(ds_phys_idx)
.and_then(|a| a.first())
.copied()
.ok_or_else(|| NfsError::Rpc(format!("DS index {} out of range", ds_phys_idx)));
// Zero-copy slice of the write data for this stripe chunk
let chunk_start = (chunk.file_offset - offset) as usize;
let chunk_data = data.slice(chunk_start..chunk_start + chunk.length as usize);
Ok::<PlannedDsWrite, NfsError>(PlannedDsWrite {
stripe_index,
ds_fh: ds_fh_res?,
ds_addr: ds_addr_res?,
ds_offset: chunk.ds_offset,
data: chunk_data,
})
})
.collect::<Result<Vec<_>>>()
{
Ok(writes) => writes,
Err(error) => {
debug!(error = %error, "pNFS WRITE plan invalid before send; using MDS");
return PnfsWriteOutcome::NotAttempted;
}
};
// Phase 1: establish every required DS session before transmitting any
// WRITE. A failure here proves that this logical write made no DS
// mutation, so MDS fallback is safe.
if let Err(error) = self
.preflight_write_data_servers(&writes, layout.generation)
.await
{
debug!(error = %error, "pNFS DS preflight failed before send; using MDS");
return PnfsWriteOutcome::NotAttempted;
}
// Phase 2: after this boundary, any error is potentially post-send and
// must remain uncertain rather than falling back to MDS.
let futures: Vec<_> = writes
.into_iter()
.map(|write| {
let stripe_index = write.stripe_index;
let ds_addr = write.ds_addr;
let future = async move {
let resp = self
.ds_write_chunk(
write.ds_addr,
&write.ds_fh,
&io_stateid,
layout.generation,
write.ds_offset,
write.data,
)
.await?;
// SEQUENCE=0, PUTFH=1, WRITE=2๏ผไธคๆก่ทฏๅพๅธๅฑไธ่ด๏ผ
resp.op_ok(1)?; // PUTFH
let write_op = resp.op_ok(2)?; // WRITE
let mut d = write_op.data.clone();
if d.remaining() < 16 {
return Err(NfsError::Xdr("DS WRITE result too short".to_string()));
}
let written = d.get_u32();
let committed = d.get_u32();
// writeverf: 8 bytes
d.advance(8);
// needs_commit=true if DS downgraded write stability
Ok::<(u32, bool), NfsError>((written, committed != 2 /* FILE_SYNC4 */))
};
(stripe_index, ds_addr, future)
})
.collect();
let completions = settle_ds_batch(futures).await;
if completions
.iter()
.all(|completion| completion.result.is_ok())
{
let results: Vec<_> = completions
.into_iter()
.filter_map(|completion| completion.result.ok())
.collect();
if layout.generation != self.layout_manager.generation() {
// This is aggregate pNFS batch context, so slot/sequence are
// intentionally zero rather than claiming one DS request.
let active_session = self.session_holder.get().await;
let context = RequestContext {
operation: "pnfs_write".to_string(),
session_id: *active_session.id(),
slot_id: 0,
sequence_id: 0,
};
return PnfsWriteOutcome::Attempted(Err(uncertain_pnfs_write(
context,
NfsError::Rpc(
"pNFS WRITE outcome crossed a session generation boundary".to_string(),
),
)));
}
let total: u32 = results.iter().map(|(n, _)| n).sum();
let needs_commit = results.iter().any(|(_, c)| *c);
// RFC 5661 ยง18.42.3๏ผLAYOUTCOMMIT ไธๅฟ
ๆฏๆฌก WRITE ๅๅ๏ผๅช้ๅจ
// LAYOUTRETURN/CLOSE ๅๆไบคใ่ฟ้ไป
็ดฏ็งฏ dirty ่ๅด๏ผ็ฑ
// flush_layoutcommit ๅจ close/layoutreturn ๆถไธๆฌกๆงๅ้๏ผ
// ้ฟๅ
ๆฏไธช wsize ๅไธๆฌกไธฒ่ก MDS RTTใ
if data_len > 0 {
self.layout_manager
.mark_dirty_at(fh, layout.generation, offset, offset + data_len as u64)
.await;
}
// RFC 5661 ยง18.32.3: if any DS downgraded write stability, COMMIT to MDS.
if needs_commit {
let _ = self.commit(fh.clone(), offset, total).await;
}
PnfsWriteOutcome::Attempted(Ok(total))
} else {
if data_len > 0 {
self.layout_manager
.mark_dirty_at(fh, layout.generation, offset, offset + data_len as u64)
.await;
}
if completions.iter().any(|completion| {
matches!(
completion.result,
Err(NfsError::Nfs4(Nfs4ErrorCode::NFS4ERR_STALE))
)
}) {
self.layout_manager.remove_layout(fh).await;
self.layout_manager.invalidate_dirty(fh).await;
}
let diagnostic = ds_batch_diagnostic(&completions);
// Preserve hot-path performance: aggregate diagnostic context
// is only materialized when the DS batch actually fails.
let active_session = self.session_holder.get().await;
let context = RequestContext {
operation: "pnfs_write".to_string(),
session_id: *active_session.id(),
slot_id: 0,
sequence_id: 0,
};
debug!(
diagnostic,
"pNFS write result is uncertain; refusing MDS fallback"
);
PnfsWriteOutcome::Attempted(Err(uncertain_pnfs_write(
context,
NfsError::Rpc(format!("pNFS DS WRITE results: {diagnostic}")),
)))
}
}
// โโโ pNFS Layout Commit โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
/// Commit a versioned snapshot of the accumulated dirty range. The range
/// remains pending across transport errors, operation errors, and task
/// cancellation, and is acknowledged only after authoritative success.
pub(crate) async fn flush_layoutcommit(&self, fh: &Bytes) -> Result<()> {
let Some(dirty) = self.layout_manager.snapshot_dirty(fh).await else {
return Ok(());
};
let Some(layout) = self.layout_manager.get_layout(fh).await else {
return Err(NfsError::Rpc(
"cannot LAYOUTCOMMIT dirty range without an active layout".to_string(),
));
};
let response = self
.compound("layoutcommit", |b| {
b.putfh(fh).layoutcommit(
dirty.start,
dirty.end - dirty.start,
false,
&layout.stateid,
Some(dirty.end - 1),
1, // LAYOUT4_NFSV4_1_FILES
)
})
.await?;
response.op_ok(1)?; // PUTFH
response.op_ok(2)?; // LAYOUTCOMMIT
if !self.layout_manager.acknowledge_dirty(fh, dirty).await {
return Err(NfsError::Rpc(
"pNFS dirty range changed during LAYOUTCOMMIT; retry before CLOSE".to_string(),
));
}
Ok(())
}
// โโโ pNFS Layout Return โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
/// Return a layout to the metadata server (LAYOUTRETURN4_FILE).
/// Removes the layout from the local cache and notifies the server.
/// A failed commit/return is propagated so CLOSE cannot release state while
/// layout changes are still pending.
pub(crate) async fn layoutreturn_file(&self, fh: &Bytes) -> Result<()> {
// RFC 5661 ยง18.42.3๏ผLAYOUTCOMMIT ๅฟ
้กปๅจ LAYOUTRETURN ไนๅ
self.flush_layoutcommit(fh).await?;
let layout = match self.layout_manager.get_layout(fh).await {
Some(l) => l,
None => return Ok(()),
};
// Use the first segment's iomode; for whole-file layouts this is correct.
// If multiple iomodes exist, IOMODE_ANY (3) tells the server to return all.
let iomode = if layout.segments.len() == 1 {
layout.segments[0].iomode as u32
} else {
3 // LAYOUTIOMODE4_ANY
};
let result = self
.compound("layoutreturn", |b| {
b.putfh(fh).layoutreturn(
false, // reclaim
1, // LAYOUT4_NFSV4_1_FILES
iomode as u32,
1, // LAYOUTRETURN4_FILE
0, // offset = whole file
0xFFFF_FFFF_FFFF_FFFF, // length = whole file
&layout.stateid,
)
})
.await;
match result {
Ok(resp) => {
resp.op_ok(1)?;
resp.op_ok(2)?;
}
Err(e) => return Err(e),
}
self.layout_manager.remove_layout(fh).await;
Ok(())
}
pub(crate) async fn refresh_layout_for_write(&self, fh: &Bytes, offset: u64) -> Result<()> {
if self.layout_manager.get_layout(fh).await.is_none()
|| !self.layout_manager.layout_refresh_due(fh, offset).await
{
return Ok(());
}
let _io_guard = self.layout_manager.write_file_io(fh).await;
if self.layout_manager.get_layout(fh).await.is_some()
&& self.layout_manager.layout_refresh_due(fh, offset).await
{
self.flush_layoutcommit(fh).await?;
if self
.fetch_layout(fh, IoMode::ReadWrite, offset, true)
.await
.is_some()
{
self.layout_manager.record_layout_refresh(fh, offset).await;
}
}
Ok(())
}
/// Return all cached layouts to the server (used during umount).
pub(crate) async fn layoutreturn_all(&self) -> Result<()> {
let layouts = self.layout_manager.all_layouts().await;
for (fh, _) in layouts {
let _io_guard = self.layout_manager.write_file_io(&fh).await;
self.layoutreturn_file(&fh).await?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::nfs41::layout::{IoMode, Layout, LayoutContent, LayoutSegment, LayoutType};
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
type TestDsFuture = Pin<Box<dyn Future<Output = Result<u32>> + Send>>;
#[test]
fn find_covering_segment_whole_file() {
let layout = Layout {
generation: 1,
stateid: [0u8; 16],
return_on_close: false,
segments: vec![LayoutSegment {
offset: 0,
length: 0xFFFF_FFFF_FFFF_FFFF,
iomode: IoMode::Read,
layout_type: LayoutType::NfsV41Files,
content: LayoutContent::Opaque(Bytes::new()),
}],
};
assert!(find_covering_segment(&layout, 0).is_some());
assert!(find_covering_segment(&layout, 1_000_000).is_some());
}
#[test]
fn find_covering_segment_bounded() {
let layout = Layout {
generation: 1,
stateid: [0u8; 16],
return_on_close: false,
segments: vec![LayoutSegment {
offset: 100,
length: 500,
iomode: IoMode::Read,
layout_type: LayoutType::NfsV41Files,
content: LayoutContent::Opaque(Bytes::new()),
}],
};
assert!(find_covering_segment(&layout, 99).is_none());
assert!(find_covering_segment(&layout, 100).is_some());
assert!(find_covering_segment(&layout, 599).is_some());
assert!(find_covering_segment(&layout, 600).is_none());
}
#[test]
fn find_covering_segment_handles_a_range_ending_past_u64_max() {
let layout = Layout {
generation: 1,
stateid: [0; 16],
return_on_close: false,
segments: vec![LayoutSegment {
offset: u64::MAX - 10,
length: 20,
iomode: IoMode::ReadWrite,
layout_type: LayoutType::NfsV41Files,
content: LayoutContent::Opaque(Bytes::new()),
}],
};
assert!(find_covering_segment(&layout, u64::MAX).is_some());
}
#[test]
fn find_covering_segment_empty() {
let layout = Layout {
generation: 1,
stateid: [0u8; 16],
return_on_close: false,
segments: vec![],
};
assert!(find_covering_segment(&layout, 0).is_none());
}
#[test]
fn find_covering_segment_multiple() {
let layout = Layout {
generation: 1,
stateid: [0u8; 16],
return_on_close: false,
segments: vec![
LayoutSegment {
offset: 0,
length: 1000,
iomode: IoMode::Read,
layout_type: LayoutType::NfsV41Files,
content: LayoutContent::Opaque(Bytes::new()),
},
LayoutSegment {
offset: 1000,
length: 1000,
iomode: IoMode::Read,
layout_type: LayoutType::NfsV41Files,
content: LayoutContent::Opaque(Bytes::new()),
},
],
};
let seg = find_covering_segment(&layout, 500);
assert!(seg.is_some());
assert_eq!(seg.map(|s| s.offset), Some(0));
let seg2 = find_covering_segment(&layout, 1500);
assert!(seg2.is_some());
assert_eq!(seg2.map(|s| s.offset), Some(1000));
}
#[test]
fn attempted_ds_error_is_uncertain_and_requires_verification() {
let context = RequestContext {
operation: "pnfs_write".to_string(),
session_id: [7; 16],
slot_id: 0,
sequence_id: 0,
};
let error = uncertain_pnfs_write(
context,
NfsError::Rpc("DS connection reset after send".to_string()),
);
let outcome = error
.operation_outcome()
.expect("attempted pNFS WRITE must have structured guidance");
assert_eq!(outcome.outcome, OperationOutcome::Uncertain);
assert_eq!(outcome.operation_class, OperationClass::ReplaySensitive);
assert_eq!(outcome.recovery, RecoveryAction::VerifyThenResume);
assert_eq!(outcome.context().operation, "pnfs_write");
}
#[tokio::test]
async fn stale_ds_write_evicts_layout_and_invalidates_old_dirty_range() {
let manager = LayoutManager::new(true);
let fh = Bytes::from_static(b"multipart-file");
let layout = Layout {
generation: manager.generation(),
stateid: [7; 16],
return_on_close: false,
segments: vec![],
};
manager.store_layout(&fh, layout).await;
manager.mark_dirty(&fh, 0, 4096).await;
invalidate_layout_after_ds_error(
&manager,
&fh,
&NfsError::Nfs4(Nfs4ErrorCode::NFS4ERR_STALE),
)
.await;
assert!(manager.get_layout(&fh).await.is_none());
assert_eq!(manager.take_dirty(&fh).await, None);
}
#[tokio::test]
async fn transport_ds_write_error_retains_layout_for_verification() {
let manager = LayoutManager::new(true);
let fh = Bytes::from_static(b"ordinary-file");
let layout = Layout {
generation: manager.generation(),
stateid: [8; 16],
return_on_close: false,
segments: vec![],
};
manager.store_layout(&fh, layout).await;
invalidate_layout_after_ds_error(
&manager,
&fh,
&NfsError::Rpc("connection reset after send".to_string()),
)
.await;
assert!(manager.get_layout(&fh).await.is_some());
}
#[tokio::test]
async fn ds_batch_waits_for_success_when_failure_completes_first() {
let (failure_seen_tx, failure_seen_rx) = tokio::sync::oneshot::channel();
let (release_success_tx, release_success_rx) = tokio::sync::oneshot::channel();
let success_count = Arc::new(AtomicUsize::new(0));
let success_count_task = Arc::clone(&success_count);
let futures: Vec<(usize, SocketAddr, TestDsFuture)> = vec![
(
0,
"192.0.2.10:2049".parse().unwrap(),
Box::pin(async move {
let _ = failure_seen_tx.send(());
Err(NfsError::Rpc("DS 0 failed".to_string()))
}),
),
(
1,
"192.0.2.11:2049".parse().unwrap(),
Box::pin(async move {
let _ = release_success_rx.await;
success_count_task.fetch_add(1, Ordering::SeqCst);
Ok(17)
}),
),
];
let batch = tokio::spawn(settle_ds_batch(futures));
assert!(failure_seen_rx.await.is_ok());
tokio::task::yield_now().await;
assert!(
!batch.is_finished(),
"early DS failure cancelled a sibling WRITE"
);
assert_eq!(success_count.load(Ordering::SeqCst), 0);
assert!(release_success_tx.send(()).is_ok());
let completions = batch.await.unwrap();
assert!(
matches!(completions[0].result, Err(NfsError::Rpc(ref message)) if message == "DS 0 failed")
);
assert!(matches!(completions[1].result, Ok(17)));
let diagnostic = ds_batch_diagnostic(&completions);
assert_eq!(
diagnostic,
"stripe=0 ds=192.0.2.10:2049 attempted=true outcome=error error=RPC error: DS 0 failed; stripe=1 ds=192.0.2.11:2049 attempted=true outcome=success"
);
assert!(!diagnostic.contains("file-handle"));
assert!(!diagnostic.contains("payload"));
assert_eq!(success_count.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn ds_batch_waits_for_failure_when_success_completes_first() {
let (success_seen_tx, success_seen_rx) = tokio::sync::oneshot::channel();
let (release_failure_tx, release_failure_rx) = tokio::sync::oneshot::channel();
let futures: Vec<(usize, SocketAddr, TestDsFuture)> = vec![
(
0,
"192.0.2.10:2049".parse().unwrap(),
Box::pin(async move {
let _ = success_seen_tx.send(());
Ok(23)
}),
),
(
1,
"192.0.2.11:2049".parse().unwrap(),
Box::pin(async move {
let _ = release_failure_rx.await;
Err(NfsError::Rpc("DS 1 failed".to_string()))
}),
),
];
let batch = tokio::spawn(settle_ds_batch(futures));
assert!(success_seen_rx.await.is_ok());
tokio::task::yield_now().await;
assert!(
!batch.is_finished(),
"successful stripe hid a pending DS WRITE"
);
assert!(release_failure_tx.send(()).is_ok());
let completions = batch.await.unwrap();
assert!(matches!(completions[0].result, Ok(23)));
assert!(
matches!(completions[1].result, Err(NfsError::Rpc(ref message)) if message == "DS 1 failed")
);
}
#[tokio::test]
async fn cancelling_ds_batch_drops_every_pending_write() {
struct DropCount(Arc<AtomicUsize>);
impl Drop for DropCount {
fn drop(&mut self) {
self.0.fetch_add(1, Ordering::SeqCst);
}
}
let started = Arc::new(AtomicUsize::new(0));
let dropped = Arc::new(AtomicUsize::new(0));
let futures: Vec<(usize, SocketAddr, TestDsFuture)> = (0..2)
.map(|stripe_index| {
let started = Arc::clone(&started);
let guard = DropCount(Arc::clone(&dropped));
let future = Box::pin(async move {
let _guard = guard;
started.fetch_add(1, Ordering::SeqCst);
std::future::pending::<Result<u32>>().await
}) as TestDsFuture;
(stripe_index, "192.0.2.10:2049".parse().unwrap(), future)
})
.collect();
let batch = tokio::spawn(settle_ds_batch(futures));
while started.load(Ordering::SeqCst) != 2 {
tokio::task::yield_now().await;
}
batch.abort();
let _ = batch.await;
assert_eq!(dropped.load(Ordering::SeqCst), 2);
}
}