summaryrefslogtreecommitdiff
path: root/common.rc
blob: ef41cbf68cd6b0987943a5da276a6409157fc81a (plain)
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
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
##/bin/bash
#-----------------------------------------------------------------------
#  Copyright (c) 2000-2006 Silicon Graphics, Inc.  All Rights Reserved.
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
#  USA
#
#  Contact information: Silicon Graphics, Inc., 1500 Crittenden Lane,
#  Mountain View, CA 94043, USA, or: http://www.sgi.com
#-----------------------------------------------------------------------

BC=$(which bc 2> /dev/null) || BC=

_require_math()
{
	if [ -z "$BC" ]; then
		_notrun "this test requires 'bc' tool for doing math operations"
	fi
}

_math()
{
	[ $# -le 0 ] && return
	if [ "$BC" ]; then
		result=$(LANG=C echo "scale=0; $@" | "$BC" -q 2> /dev/null)
	else
		_notrun "this test requires 'bc' tool for doing math operations"
	fi
	echo "$result"
}

dd()
{
   if [ "$HOSTOS" == "Linux" ]
   then	
	command dd --help | grep noxfer > /dev/null 2>&1
	
	if [ "$?" -eq 0 ]
	    then
		command dd status=noxfer $@
	    else
		command dd $@
    	fi
   else
	command dd $@
   fi
}

# ls -l w/ selinux sometimes puts a dot at the end:
# -rwxrw-r--. id1 id2 file1

_ls_l()
{
	ls -l $* | sed "s/\(^[-rwxdlbcpsStT]*\)\. /\1 /"
}

_mount_opts()
{
    # SELinux adds extra xattrs which can mess up our expected output.
    # So, mount with a context, and they won't be created
    # nfs_t is a "liberal" context so we can use it.
    if [ -x /usr/sbin/selinuxenabled ] && /usr/sbin/selinuxenabled; then
	SELINUX_MOUNT_OPTIONS="-o context=system_u:object_r:nfs_t:s0"
	export SELINUX_MOUNT_OPTIONS
    fi

    case $FSTYP in
    xfs)
	export MOUNT_OPTIONS=$XFS_MOUNT_OPTIONS
	;;
    udf)
	export MOUNT_OPTIONS=$UDF_MOUNT_OPTIONS
	;;
    nfs)
	export MOUNT_OPTIONS=$NFS_MOUNT_OPTIONS
	;;
    ext2|ext3|ext4|ext4dev)
	# acls & xattrs aren't turned on by default on ext$FOO
	export MOUNT_OPTIONS="-o acl,user_xattr $EXT_MOUNT_OPTIONS"
	;;
    reiserfs)
	# acls & xattrs aren't turned on by default on reiserfs
	export MOUNT_OPTIONS="-o acl,user_xattr $REISERFS_MOUNT_OPTIONS"
	;;
    gfs2)
	# acls aren't turned on by default on gfs2
	export MOUNT_OPTIONS="-o acl $GFS2_MOUNT_OPTIONS"
	;;
    *)
	;;
    esac
}

_mkfs_opts()
{
    case $FSTYP in
    xfs)
	export MKFS_OPTIONS=$XFS_MKFS_OPTIONS
	;;
    udf)
	[ ! -z "$udf_fsize" ] && \
	    UDF_MKFS_OPTIONS="$UDF_MKFS_OPTIONS -s $udf_fsize"
	export MKFS_OPTIONS=$UDF_MKFS_OPTIONS
	;;
    nfs)
	export MKFS_OPTIONS=$NFS_MKFS_OPTIONS
	;;
    reiserfs)
	export MKFS_OPTIONS="$REISERFS_MKFS_OPTIONS -q"
	;;
    gfs2)
	export MKFS_OPTIONS="$GFS2_MKFS_OPTIONS -O -p lock_nolock"
	;;
    jfs)
	export MKFS_OPTIONS="$JFS_MKFS_OPTIONS -q"
	;;
    *)
	;;
    esac
}

_fsck_opts()
{
    case $FSTYP in
    ext2|ext3|ext4|ext4dev)
	export FSCK_OPTIONS="-nf"
	;;
    reiserfs)
	export FSCK_OPTIONS="--yes"
	;;
    *)
	export FSCK_OPTIONS="-n"
	;;
    esac
}

[ -z "$FSTYP" ] && FSTYP=xfs
[ -z "$MOUNT_OPTIONS" ] && _mount_opts
[ -z "$MKFS_OPTIONS" ] && _mkfs_opts
[ -z "$FSCK_OPTIONS" ] && _fsck_opts


# we need common.config
if [ "$iam" != "check" ]
then
    if ! . ./common.config
        then
        echo "$iam: failed to source common.config"
        exit 1
    fi
fi

# make sure we have a standard umask
umask 022

_mount()
{
    $MOUNT_PROG `_mount_ops_filter $*`
}

_scratch_options()
{
    type=$1
    SCRATCH_OPTIONS=""

    if [ "$FSTYP" != "xfs" ]; then
        return
    fi

    case $type in
    mkfs)
	[ "$HOSTOS" != "IRIX" ] && SCRATCH_OPTIONS="$SCRATCH_OPTIONS -f"
	rt_opt="-r"
        log_opt="-l"
	;;
    mount)
	rt_opt="-o"
        log_opt="-o"
	;;
    esac
    [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_RTDEV" ] && \
	SCRATCH_OPTIONS="$SCRATCH_OPTIONS ${rt_opt}rtdev=$SCRATCH_RTDEV"
    [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
	SCRATCH_OPTIONS="$SCRATCH_OPTIONS ${log_opt}logdev=$SCRATCH_LOGDEV"
}

_test_options()
{
    type=$1
    TEST_OPTIONS=""

    if [ "$FSTYP" != "xfs" ]; then
        return
    fi

    case $type in
    mkfs)
	rt_opt="-r"
        log_opt="-l"
	;;
    mount)
	rt_opt="-o"
        log_opt="-o"
	;;
    esac
    [ "$USE_EXTERNAL" = yes -a ! -z "$TEST_RTDEV" ] && \
	TEST_OPTIONS="$TEST_OPTIONS ${rt_opt}rtdev=$TEST_RTDEV"
    [ "$USE_EXTERNAL" = yes -a ! -z "$TEST_LOGDEV" ] && \
	TEST_OPTIONS="$TEST_OPTIONS ${log_opt}logdev=$TEST_LOGDEV"
}

_mount_ops_filter()
{
    params="$*"
    
    #get mount point to handle dmapi mtpt option correctly
    let last_index=$#-1
    [ $last_index -gt 0 ] && shift $last_index
    FS_ESCAPED=$1
    
    # irix is fussy about how it is fed its mount options
    # - multiple -o's are not allowed
    # - no spaces between comma delimitered options
    # the sed script replaces all -o's (except the first) with a comma
    # not required for linux, but won't hurt
    
    echo $params | sed -e 's/[[:space:]]*-o[[:space:]]*/UnIqUe/1; s/[[:space:]]*-o[[:space:]]*/,/g; s/UnIqUe/ -o /1' \
        | sed -e 's/dmapi/dmi/' \
        | $PERL_PROG -ne "s#mtpt=[^,|^\n|^\s]*#mtpt=$FS_ESCAPED\1\2#; print;"

}

_scratch_mount_options()
{
    _scratch_options mount

    echo $SCRATCH_OPTIONS $MOUNT_OPTIONS $SELINUX_MOUNT_OPTIONS $* $SCRATCH_DEV $SCRATCH_MNT
}

_scratch_mount()
{
    _mount -t $FSTYP `_scratch_mount_options $*`
}

_scratch_unmount()
{
    $UMOUNT_PROG $SCRATCH_DEV
}

_scratch_remount()
{
    _scratch_unmount
    _scratch_mount
}

_test_mount()
{
    _test_options mount
    _mount -t $FSTYP $TEST_OPTIONS $TEST_FS_MOUNT_OPTS $SELINUX_MOUNT_OPTIONS $* $TEST_DEV $TEST_DIR
}

_scratch_mkfs_options()
{
    _scratch_options mkfs
    echo $SCRATCH_OPTIONS $MKFS_OPTIONS $* $SCRATCH_DEV
}

_scratch_mkfs_xfs()
{
    # extra mkfs options can be added by tests
    local extra_mkfs_options=$*

    local tmp_dir=/tmp/

    _scratch_options mkfs

    # save mkfs output in case conflict means we need to run again.
    # only the output for the mkfs that applies should be shown
    $MKFS_XFS_PROG $SCRATCH_OPTIONS $MKFS_OPTIONS $extra_mkfs_options $SCRATCH_DEV \
        2>$tmp_dir.mkfserr 1>$tmp_dir.mkfsstd
    local mkfs_status=$?

    # a mkfs failure may be caused by conflicts between
    # $MKFS_OPTIONS and $extra_mkfs_options

    if [ $mkfs_status -ne 0 -a ! -z "$extra_mkfs_options" ]; then
        echo "** mkfs failed with extra mkfs options added to \"$MKFS_OPTIONS\" by test $seq **" \
            >>$here/$seq.full
        echo "** attempting to mkfs using only test $seq options: $extra_mkfs_options **" \
            >>$here/$seq.full
        # running mkfs again. overwrite previous mkfs output files
        $MKFS_XFS_PROG $SCRATCH_OPTIONS $extra_mkfs_options $SCRATCH_DEV \
            2>$tmp_dir.mkfserr 1>$tmp_dir.mkfsstd
        mkfs_status=$?
    fi

    # output stored mkfs output
    cat $tmp_dir.mkfserr >&2
    cat $tmp_dir.mkfsstd
    rm -f $tmp_dir.mkfserr $tmp_dir.mkfsstd

    if [ "$USE_BIG_LOOPFS" = yes ]; then
        [ -z "$RETAIN_AG_BYTES" ] && RETAIN_AG_BYTES=0
        ./tools/ag-wipe -q -r $RETAIN_AG_BYTES $SCRATCH_DEV
    fi

    return $mkfs_status
}

_scratch_mkfs()
{
    case $FSTYP in
    xfs)
        _scratch_mkfs_xfs $*
	;;
    nfs*)
	# do nothing for nfs
	;;
    udf)
        $MKFS_UDF_PROG $MKFS_OPTIONS $* $SCRATCH_DEV > /dev/null
	;;
    btrfs)
        $MKFS_BTRFS_PROG $MKFS_OPTIONS $* $SCRATCH_DEV > /dev/null
	;;
    *)
	yes | $MKFS_PROG -t $FSTYP -- $MKFS_OPTIONS $* $SCRATCH_DEV
	;;
    esac
}

# Create fs of certain size on scratch device
# _scratch_mkfs_sized <size in bytes> [optional blocksize]
_scratch_mkfs_sized()
{
    fssize=$1
    blocksize=$2
    [ -z "$blocksize" ] && blocksize=4096
    blocks=`expr $fssize / $blocksize`

    if [ "$HOSTOS" == "Linux" ]; then
	devsize=`blockdev --getsize64 $SCRATCH_DEV`
	[ "$fssize" -gt "$devsize" ] && _notrun "Scratch device too small"
    fi

    case $FSTYP in
    xfs)
	_scratch_mkfs_xfs -d size=$fssize -b size=$blocksize
	;;
    ext2|ext3|ext4|ext4dev)
	yes | ${MKFS_PROG}.$FSTYP $MKFS_OPTIONS -b $blocksize $SCRATCH_DEV $blocks
	;;
    btrfs)
	$MKFS_BTRFS_PROG $MKFS_OPTIONS -b $fssize $SCRATCH_DEV
	;;
    *)
	_notrun "Filesystem $FSTYP not supported in _scratch_mkfs_sized"
	;;
    esac
}

# Emulate an N-data-disk stripe w/ various stripe units
# _scratch_mkfs_geom <sunit bytes> <swidth multiplier> [optional blocksize]
_scratch_mkfs_geom()
{
    sunit_bytes=$1
    swidth_mult=$2
    blocksize=$3
    [ -z "$blocksize" ] && blocksize=4096

    let sunit_blocks=$sunit_bytes/$blocksize
    let swidth_blocks=$sunit_blocks*$swidth_mult

    case $FSTYP in
    xfs)
	MKFS_OPTIONS+=" -b size=$blocksize, -d su=$sunit_bytes,sw=$swidth_mult"
	;;
    ext4|ext4dev)
	MKFS_OPTIONS+=" -b $blocksize -E stride=$sunit_blocks,stripe_width=$swidth_blocks"
	;;
    *)
	_notrun "can't mkfs $FSTYP with geometry"
	;;
    esac
    _scratch_mkfs
}

_scratch_resvblks()
{
	case $FSTYP in
	xfs)
		xfs_io -x -c "resblks $1" $SCRATCH_MNT
		;;
	*)
		;;
	esac
}

_scratch_xfs_db_options()
{
    SCRATCH_OPTIONS=""
    [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
        SCRATCH_OPTIONS="-l$SCRATCH_LOGDEV"
    echo $SCRATCH_OPTIONS $* $SCRATCH_DEV
}

_scratch_xfs_logprint()
{
    SCRATCH_OPTIONS=""
    [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
        SCRATCH_OPTIONS="-l$SCRATCH_LOGDEV"
    $XFS_LOGPRINT_PROG $SCRATCH_OPTIONS $* $SCRATCH_DEV
}

_scratch_xfs_check()
{
    SCRATCH_OPTIONS=""
    [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
        SCRATCH_OPTIONS="-l $SCRATCH_LOGDEV"
    $XFS_CHECK_PROG $SCRATCH_OPTIONS $* $SCRATCH_DEV
}

_scratch_xfs_repair()
{
    SCRATCH_OPTIONS=""
    [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
        SCRATCH_OPTIONS="-l$SCRATCH_LOGDEV"
    [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_RTDEV" ] && \
        SCRATCH_OPTIONS=$SCRATCH_OPTIONS" -r$SCRATCH_RTDEV"
    [ "$USE_BIG_LOOPFS" = yes ] && SCRATCH_OPTIONS=$SCRATCH_OPTIONS" -t"
    $XFS_REPAIR_PROG $SCRATCH_OPTIONS $* $SCRATCH_DEV
}

_get_pids_by_name()
{
    if [ $# -ne 1 ]
    then
	echo "Usage: _get_pids_by_name process-name" 1>&2
	exit 1
    fi

    # Algorithm ... all ps(1) variants have a time of the form MM:SS or
    # HH:MM:SS before the psargs field, use this as the search anchor.
    #
    # Matches with $1 (process-name) occur if the first psarg is $1
    # or ends in /$1 ... the matching uses sed's regular expressions,
    # so passing a regex into $1 will work.

    ps $PS_ALL_FLAGS \
    | sed -n \
	-e 's/$/ /' \
	-e 's/[ 	][ 	]*/ /g' \
	-e 's/^ //' \
	-e 's/^[^ ]* //' \
	-e "/[0-9]:[0-9][0-9]  *[^ ]*\/$1 /s/ .*//p" \
	-e "/[0-9]:[0-9][0-9]  *$1 /s/ .*//p"
}

# fix malloc libs output
#
_fix_malloc()
{
    # filter out the Electric Fence notice
    $PERL_PROG -e '
        while (<>) {
            if (defined $o && /^\s+Electric Fence/) {
                chomp($o);
                print "$o";
                undef $o;
                next;
            }
            print $o if (defined $o);

            $o=$_;
        }
        print $o if (defined $o);
    '
}

# check if run as root
#
_need_to_be_root()
{
    id=`id | $SED_PROG -e 's/(.*//' -e 's/.*=//'`
    if [ "$id" -ne 0 ]
    then
	echo "Arrgh ... you need to be root (not uid=$id) to run this test"
	exit 1
    fi
}


#
# _df_device : get an IRIX style df line for a given device
#
#       - returns "" if not mounted
#       - returns fs type in field two (ala IRIX)
#       - joins line together if split by fancy df formatting
#       - strips header etc
#

_df_device()
{
    if [ $# -ne 1 ]
    then
	echo "Usage: _df_device device" 1>&2
	exit 1
    fi

    $DF_PROG 2>/dev/null | $AWK_PROG -v what=$1 '
        match($1,what) && NF==1 {
            v=$1
            getline
            print v, $0
            exit
        }
        match($1,what) {
            print
            exit
        }
    '
}

#
# _df_dir : get an IRIX style df line for device where a directory resides
#
#       - returns fs type in field two (ala IRIX)
#       - joins line together if split by fancy df formatting
#       - strips header etc
#

_df_dir()
{
    if [ $# -ne 1 ]
    then
	echo "Usage: _df_dir device" 1>&2
	exit 1
    fi

    $DF_PROG $1 2>/dev/null | $AWK_PROG -v what=$1 '
        NR == 2 && NF==1 {
            v=$1
            getline
            print v, $0;
            exit 0
        }
        NR == 2 {
            print;
            exit 0
        }
        {}
    '
    # otherwise, nada
}

# return percentage used disk space for mounted device

_used()
{
    if [ $# -ne 1 ]
    then
	echo "Usage: _used device" 1>&2
	exit 1
    fi

    _df_device $1 | $AWK_PROG '{ sub("%", "") ; print $6 }'
}

# return the FS type of a mounted device
#
_fs_type()
{
    if [ $# -ne 1 ]
    then
	echo "Usage: _fs_type device" 1>&2
	exit 1
    fi

    #
    # The Linux kernel shows NFSv4 filesystems in df output as
    # filesystem type nfs4, although we mounted it as nfs earlier.
    # Fix the filesystem type up here so that the callers don't
    # have to bother with this quirk.
    #
    _df_device $1 | $AWK_PROG '{ print $2 }' | sed -e 's/nfs4/nfs/'
}

# return the FS mount options of a mounted device
#
# should write a version which just parses the output of mount for IRIX
# compatibility, but since this isn't used at all, at the moment I'll leave
# this for now
#
_fs_options()
{
    if [ $# -ne 1 ]
    then
	echo "Usage: _fs_options device" 1>&2
	exit 1
    fi

    $AWK_PROG -v dev=$1 '
        match($1,dev) { print $4 }
    ' </proc/mounts
}

# returns device number if a file is a block device
#
_is_block_dev()
{
    if [ $# -ne 1 ]
    then
	echo "Usage: _is_block_dev dev" 1>&2
	exit 1
    fi

    _dev=$1
    if [ -L "${_dev}" ]; then
        _dev=`readlink -f ${_dev}`
    fi

    if [ -b "${_dev}" ]; then
        src/lstat64 ${_dev} | $AWK_PROG '/Device type:/ { print $9 }'
    fi
}

# Do a command, log it to $seq.full, optionally test return status
# and die if command fails. If called with one argument _do executes the
# command, logs it, and returns its exit status. With two arguments _do
# first prints the message passed in the first argument, and then "done"
# or "fail" depending on the return status of the command passed in the
# second argument. If the command fails and the variable _do_die_on_error
# is set to "always" or the two argument form is used and _do_die_on_error
# is set to "message_only" _do will print an error message to
# $seq.out and exit.

_do()
{
    if [ $# -eq 1 ]; then
	_cmd=$1
    elif [ $# -eq 2 ]; then
	_note=$1
	_cmd=$2
	echo -n "$_note... "
    else
	echo "Usage: _do [note] cmd" 1>&2
	status=1; exit
    fi

    (eval "echo '---' \"$_cmd\"") >>$here/$seq.full
    (eval "$_cmd") >$tmp._out 2>&1; ret=$?
    cat $tmp._out | _fix_malloc >>$here/$seq.full
    if [ $# -eq 2 ]; then
	if [ $ret -eq 0 ]; then
	    echo "done"
	else
	    echo "fail"
	fi
    fi
    if [ $ret -ne 0  ] \
	&& [ "$_do_die_on_error" = "always" \
	    -o \( $# -eq 2 -a "$_do_die_on_error" = "message_only" \) ]
    then
	[ $# -ne 2 ] && echo
	eval "echo \"$_cmd\" failed \(returned $ret\): see $seq.full"
	status=1; exit
    fi

    return $ret
}

# bail out, setting up .notrun file
#
_notrun()
{
    echo "$*" >$seq.notrun
    echo "$seq not run: $*"
    status=0
    exit
}

# just plain bail out
#
_fail()
{
    echo "$*" | tee -a $here/$seq.full
    echo "(see $seq.full for details)"
    status=1
    exit 1
}

# tests whether $FSTYP is one of the supported filesystems for a test
#
_supported_fs()
{
    for f
    do
	if [ "$f" = "$FSTYP" -o "$f" = "generic" ]
	then
	    return
	fi
    done

    _notrun "not suitable for this filesystem type: $FSTYP"
}

# tests whether $FSTYP is one of the supported OSes for a test
#
_supported_os()
{
    for h
    do
	if [ "$h" = "$HOSTOS" ]
	then
	    return
	fi
    done

    _notrun "not suitable for this OS: $HOSTOS"
}

# this test needs a scratch partition - check we're ok & unmount it
#
_require_scratch()
{
    case "$FSTYP" in
	nfs*)
		 echo $SCRATCH_DEV | grep -q ":" > /dev/null 2>&1
		 if [ -z "$SCRATCH_DEV" -o "$?" != "0" ]
		 then
		     _notrun "this test requires a valid \$SCRATCH_DEV"
		 fi
		 ;;
	*)
		 if [ -z "$SCRATCH_DEV" -o "`_is_block_dev $SCRATCH_DEV`" = "" ]
		 then
		     _notrun "this test requires a valid \$SCRATCH_DEV"
		 fi
		 if [ "`_is_block_dev $SCRATCH_DEV`" = "`_is_block_dev $TEST_DEV`" ]
		 then
		     _notrun "this test requires a valid \$SCRATCH_DEV"
		 fi
		if [ ! -d "$SCRATCH_MNT" ]
		then
		     _notrun "this test requires a valid \$SCRATCH_MNT"
		fi
		 ;;
    esac

    # mounted?
    if _mount | grep -q $SCRATCH_DEV
    then
        # if it's mounted, make sure its on $SCRATCH_MNT
        if ! _mount | grep $SCRATCH_DEV | grep -q $SCRATCH_MNT
        then
            echo "\$SCRATCH_DEV is mounted but not on \$SCRATCH_MNT - aborting"
            exit 1
        fi
        # and then unmount it
        if ! $UMOUNT_PROG $SCRATCH_DEV
        then
            echo "failed to unmount $SCRATCH_DEV"
            exit 1
        fi
    fi
}

# this test needs a logdev
#
_require_logdev()
{
    [ -z "$SCRATCH_LOGDEV" -o ! -b "$SCRATCH_LOGDEV" ] && \
        _notrun "This test requires a valid \$SCRATCH_LOGDEV"
    [ "$USE_EXTERNAL" != yes ] && \
        _notrun "This test requires USE_EXTERNAL to be enabled"

    # ensure its not mounted
    $UMOUNT_PROG $SCRATCH_LOGDEV 2>/dev/null
}

# this test requires loopback device support
#
_require_loop()
{
    if [ "$HOSTOS" != "Linux" ]
    then
	_notrun "This test requires linux for loopback device support"
    fi

    modprobe loop >/dev/null 2>&1
    if grep loop /proc/devices >/dev/null 2>&1
    then
	:
    else
	_notrun "This test requires loopback device support"
    fi
}

# this test requires ext2 filesystem support
#
_require_ext2()
{
    if [ "$HOSTOS" != "Linux" ]
    then
	_notrun "This test requires linux for ext2 filesystem support"
    fi

    modprobe ext2 >/dev/null 2>&1
    if grep ext2 /proc/filesystems >/dev/null 2>&1
    then
	:
    else
	_notrun "This test requires ext2 filesystem support"
    fi
}

# this test requires that (large) loopback device files are not in use
#
_require_nobigloopfs()
{
    [ "$USE_BIG_LOOPFS" = yes ] && \
	_notrun "Large filesystem testing in progress, skipped this test"
}

# this test requires that a realtime subvolume is in use, and
# that the kernel supports realtime as well.
#
_require_realtime()
{
    [ "$USE_EXTERNAL" = yes ] || \
	_notrun "External volumes not in use, skipped this test"
    [ "$SCRATCH_RTDEV" = "" ] && \
	_notrun "Realtime device required, skipped this test"
}

# this test requires that a specified command (executable) exists
# $1 - command, $2 - name for error message
#
_require_command()
{
    [ -n "$1" ] && _cmd="$1" || _cmd="$2"
    [ -n "$1" -a -x "$1" ] || _notrun "$_cmd utility required, skipped this test"
}

# this test requires the projid32bit feature to be available in
# mkfs.xfs
#
_require_projid32bit()
{
        _scratch_mkfs_xfs -f -i projid32bit=0 2>&1 >/dev/null \
	   || _notrun "mkfs.xfs doesn't have projid32bit feature"
}

# this test requires that external log/realtime devices are not in use
#
_require_nonexternal()
{
    [ "$USE_EXTERNAL" = yes ] && \
	_notrun "External device testing in progress, skipped this test"
}

# this test requires that a (specified) aio-dio executable exists
# $1 - command (optional)
#
_require_aiodio()
{
    if [ -z "$1" ]
    then
        AIO_TEST=src/aio-dio-regress/aiodio_sparse2
        [ -x $AIO_TEST ] || _notrun "aio-dio utilities required"
    else
        AIO_TEST=src/aio-dio-regress/$1
        [ -x $AIO_TEST ] || _notrun "$AIO_TEST not built"
    fi
}

# run an aio-dio program
# $1 - command
_run_aiodio()
{
    if [ -z "$1" ]
    then
        echo "usage: _run_aiodio command_name" 2>&1
        status=1; exit 1
    fi

    _require_aiodio $1

    local testtemp=$TEST_DIR/aio-testfile
    rm -f $testtemp
    $AIO_TEST $testtemp 2>&1
    status=$?
    rm -f $testtemp

    return $status
}

# indicate whether YP/NIS is active or not
#
_yp_active()
{
	local dn
	dn=$(domainname 2>/dev/null)
	test -n "${dn}" -a "${dn}" != "(none)"
	echo $?
}

# cat the password file
#
_cat_passwd()
{
	[ $(_yp_active) -eq 0 ] && ypcat passwd
	cat /etc/passwd
}

# cat the group file
#
_cat_group()
{
	[ $(_yp_active) -eq 0 ] && ypcat group
	cat /etc/group
}

# check for the fsgqa user on the machine
#
_require_user()
{
    qa_user=fsgqa
    _cat_passwd | grep -q $qa_user
    [ "$?" == "0" ] || _notrun "$qa_user user not defined."
    echo /bin/true | su $qa_user
    [ "$?" == "0" ] || _notrun "$qa_user cannot execute commands."
}

# check for the fsgqa group on the machine
#
_require_group()
{
    qa_group=fsgqa
    _cat_group | grep -q $qa_group
    [ "$?" == "0" ] || _notrun "$qa_group user not defined."
}

_filter_user_do()
{
        perl -ne "
s,.*Permission\sdenied.*,Permission denied,;
s,.*no\saccess\sto\stty.*,,;
s,.*no\sjob\scontrol\sin\sthis\sshell.*,,;
s,^\s*$,,;
        print;"
}

_user_do()
{
    if [ "$HOSTOS" == "IRIX" ]
	then
	echo $1 | /bin/bash "su $qa_user 2>&1" | _filter_user_do
    else
	echo $1 | su $qa_user 2>&1 | _filter_user_do
    fi
}

# check that xfs_io, kernel, and filesystem all support zero
_require_xfs_io_zero()
{
	testio=`$XFS_IO_PROG -c "zero help" 2>&1`
	echo $testio | grep -q 'command "zero" not found' && \
		_notrun "zero command not supported"
}

# check that xfs_io, glibc, kernel, and filesystem all (!) support
# fallocate
#
_require_xfs_io_falloc()
{
	testfile=$TEST_DIR/$$.falloc
	testio=`$XFS_IO_PROG -F -f -c "falloc 0 1m" $testfile 2>&1`
	rm -f $testfile 2>&1 > /dev/null
	echo $testio | grep -q "not found" && \
		_notrun "xfs_io fallocate support is missing"
	echo $testio | grep -q "Operation not supported" && \
		_notrun "xfs_io fallocate command failed (old kernel/wrong fs?)"
}

# check that xfs_io, kernel and filesystem all support fallocate with hole
# punching
_require_xfs_io_falloc_punch()
{
	testfile=$TEST_DIR/$$.falloc
	testio=`$XFS_IO_PROG -F -f -c "pwrite 0 20k" -c "fsync" \
		-c "fpunch 4k 8k" $testfile 2>&1`
	rm -f $testfile 2>&1 > /dev/null
	echo $testio | grep -q "not found" && \
		_notrun "xfs_io fallocate punch support is missing"
	echo $testio | grep -q "Operation not supported" && \
		_notrun "xfs_io fallocate punch command failed (no fs support?)"
}

# check that xfs_io, kernel and filesystem support fiemap
_require_xfs_io_fiemap()
{
	testfile=$TEST_DIR/$$.fiemap
	testio=`$XFS_IO_PROG -F -f -c "pwrite 0 20k" -c "fsync" \
		-c "fiemap -v" $testfile 2>&1`
	rm -f $testfile 2>&1 > /dev/null
	echo $testio | grep -q "not found" && \
		_notrun "xfs_io fiemap support is missing"
	echo $testio | grep -q "Operation not supported" && \
		_notrun "xfs_io fiemap command failed (no fs support?)"
}

# Check that a fs has enough free space (in 1024b blocks)
#
_require_fs_space()
{
	MNT=$1
	BLOCKS=$2	# in units of 1024
	let GB=$BLOCKS/1024/1024

	FREE_BLOCKS=`df -klP $MNT | grep -v Filesystem | awk '{print $4}'`
	[ $FREE_BLOCKS -lt $BLOCKS ] && \
		_notrun "This test requires at least ${GB}GB free on $MNT to run"
}

#
# Check if the filesystem supports sparse files.
#
# Unfortunately there is no better way to do this than a manual black list.
#
_require_sparse_files()
{
    case $FSTYP in
    hfsplus)
        _notrun "Sparse files not supported by this filesystem type: $FSTYP"
	;;
    *)
        ;;
    esac
}

_require_debugfs()
{
    #boot_params always present in debugfs
    [ -d "$DEBUGFS_MNT/boot_params" ] || _notrun "Debugfs not mounted"
}

_require_fail_make_request()
{
    [ -f "$DEBUGFS_MNT/fail_make_request/probability" ] \
	|| _notrun "$DEBUGFS_MNT/fail_make_request \
 not found. Seems that CONFIG_FAIL_MAKE_REQUEST kernel config option not enabled"
}

# check that a FS on a device is mounted
# if so, return mount point
#
_is_mounted()
{
    if [ $# -ne 1 ]
    then
	echo "Usage: _is_mounted device" 1>&2
	exit 1
    fi

    device=$1

    if _mount | grep "$device " | $AWK_PROG -v pattern="type $FSTYP" '
        pattern        { print $3 ; exit 0 }
        END            { exit 1 }
    '
    then
        echo "_is_mounted: $device is not a mounted $FSTYP FS"
        exit 1
    fi
}

# remount a FS to a new mode (ro or rw)
#
_remount()
{
    if [ $# -ne 2 ]
    then
	echo "Usage: _remount device ro/rw" 1>&2
	exit 1
    fi
    device=$1
    mode=$2

    if ! mount -o remount,$mode $device
    then
        echo "_remount: failed to remount filesystem on $device as $mode"
        exit 1
    fi
}

# Run the appropriate repair/check on a filesystem
#
# if the filesystem is mounted, it's either remounted ro before being
# checked or it's unmounted and then remounted
#

# If set, we remount ro instead of unmounting for fsck
USE_REMOUNT=0

_umount_or_remount_ro()
{
    if [ $# -ne 1 ]
    then
	echo "Usage: _umount_or_remount_ro <device>" 1>&2
	exit 1
    fi

    device=$1
    mountpoint=`_is_mounted $device`

    if [ $USE_REMOUNT -eq 0 ]; then
        $UMOUNT_PROG $device
    else
        _remount $device ro
    fi
    echo "$mountpoint"
}

_mount_or_remount_rw()
{
    if [ $# -ne 3 ]
    then
	echo "Usage: _mount_or_remount_rw <opts> <device> <mountpoint>" 1>&2
	exit 1
    fi
    mount_opts=$1
    device=$2
    mountpoint=$3

    if [ $USE_REMOUNT -eq 0 ]
    then
        if ! _mount -t $FSTYP $mount_opts $device $mountpoint
        then
            echo "!!! failed to remount $device on $mountpoint"
            return 0 # ok=0
        fi
    else
        _remount $device rw
    fi

    return 1 # ok=1
}

# Check a generic filesystem in no-op mode; this assumes that the
# underlying fsck program accepts "-n" for a no-op (check-only) run,
# and that it will still return an errno for corruption in this mode.
#
# Filesystems which don't support this will need to define their
# own check routine.
#
_check_generic_filesystem()
{
    device=$1

    # If type is set, we're mounted
    type=`_fs_type $device`
    ok=1

    if [ "$type" = "$FSTYP" ]
    then
        # mounted ...
        mountpoint=`_umount_or_remount_ro $device`
    fi

    fsck -t $FSTYP $FSCK_OPTIONS $device >$tmp.fsck 2>&1
    if [ $? -ne 0 ]
    then
        echo "_check_generic_filesystem: filesystem on $device is inconsistent (see $seq.full)"

        echo "_check_generic filesystem: filesystem on $device is inconsistent" >>$here/$seq.full
        echo "*** fsck.$FSTYP output ***"                     >>$here/$seq.full
        cat $tmp.fsck                                         >>$here/$seq.full
        echo "*** end fsck.$FSTYP output"                     >>$here/$seq.full

        ok=0
    fi
    rm -f $tmp.fsck

    if [ $ok -eq 0 ]
    then
        echo "*** mount output ***"                             >>$here/$seq.full
        _mount                                                  >>$here/$seq.full
        echo "*** end mount output"                             >>$here/$seq.full
    elif [ "$type" = "$FSTYP" ]
    then
	# was mounted ...
	_mount_or_remount_rw "$MOUNT_OPTIONS" $device $mountpoint
	ok=$?
    fi

    if [ $ok -eq 0 ]; then
	status=1
	exit 1
    fi

    return 0
}

# run xfs_check and friends on a FS.

_check_xfs_filesystem()
{
    if [ $# -ne 3 ]
    then
	echo "Usage: _check_xfs_filesystem device <logdev>|none <rtdev>|none" 1>&2
	exit 1
    fi

    extra_mount_options=""
    device=$1
    if [ "$2" != "none" ]; then
       	extra_log_options="-l$2"
        extra_mount_options="-ologdev=$2"
    fi

    if [ "$3" != "none" ]; then
       	extra_rt_options="-r$3"
        extra_mount_options=$extra_mount_options" -ortdev=$3"
    fi
    extra_mount_options=$extra_mount_options" $MOUNT_OPTIONS"

    [ "$FSTYP" != xfs ] && return 0
    testoption=""
    [ "$USE_BIG_LOOPFS" = yes ] && testoption=-t

    type=`_fs_type $device`
    ok=1

    if [ "$type" = "xfs" ]
    then
        # mounted ...
        mountpoint=`_umount_or_remount_ro $device`
    fi

    $XFS_LOGPRINT_PROG -t $extra_log_options $device 2>&1 \
                | tee $tmp.logprint | grep -q "<CLEAN>"
    if [ $? -ne 0 -a "$HOSTOS" = "Linux" ]
    then
        echo "_check_xfs_filesystem: filesystem on $device has dirty log (see $seq.full)"

        echo "_check_xfs_filesystem: filesystem on $device has dirty log"   >>$here/$seq.full
        echo "*** xfs_logprint -t output ***"                   >>$here/$seq.full
        cat $tmp.logprint                                       >>$here/$seq.full
        echo "*** end xfs_logprint output"                      >>$here/$seq.full

        ok=0
    fi

    $XFS_CHECK_PROG $testoption $extra_log_options $device 2>&1 |\
	 _fix_malloc >$tmp.fs_check
    if [ -s $tmp.fs_check ]
    then
        echo "_check_xfs_filesystem: filesystem on $device is inconsistent (c) (see $seq.full)"

        echo "_check_xfs_filesystem: filesystem on $device is inconsistent" >>$here/$seq.full
        echo "*** xfs_check output ***"                         >>$here/$seq.full
        cat $tmp.fs_check                                       >>$here/$seq.full
        echo "*** end xfs_check output"                         >>$here/$seq.full

        ok=0
    fi
    # repair doesn't scale massively at this stage, optionally skip it for now
    [ "$USE_BIG_LOOPFS" = yes ] || \
    $XFS_REPAIR_PROG -n $extra_log_options $extra_rt_options $device >$tmp.repair 2>&1
    if [ $? -ne 0 ]
    then
        echo "_check_xfs_filesystem: filesystem on $device is inconsistent (r) (see $seq.full)"

        echo "_check_xfs_filesystem: filesystem on $device is inconsistent" >>$here/$seq.full
        echo "*** xfs_repair -n output ***"                     >>$here/$seq.full
        cat $tmp.repair | _fix_malloc                           >>$here/$seq.full
        echo "*** end xfs_repair output"                        >>$here/$seq.full

        ok=0
    fi
    rm -f $tmp.fs_check $tmp.logprint $tmp.repair

    if [ $ok -eq 0 ]
    then
        echo "*** mount output ***"                             >>$here/$seq.full
        _mount                                                  >>$here/$seq.full
        echo "*** end mount output"                             >>$here/$seq.full
    elif [ "$type" = "xfs" ]
    then
	_mount_or_remount_rw "$extra_mount_options" $device $mountpoint
    fi

    if [ $ok -eq 0 ]; then
	status=1
	exit 1
    fi

    return 0
}

# Filter the knowen errors the UDF Verifier reports.
_udf_test_known_error_filter()
{
	egrep -v "PVD  60  Error: Interchange Level: 1, Maximum Interchange Level: 0|FSD  28  Error: Interchange Level: 1, Maximum Interchange Level: 1,|PVD  72  Warning: Volume Set Identifier: \"\*IRIX UDF\",|Warning: [0-9]+ unused blocks NOT marked as unallocated."

}

_check_udf_filesystem()
{
    [ "$DISABLE_UDF_TEST" == "1" ] && return

    if [ $# -ne 1 -a $# -ne 2 ]
    then
	echo "Usage: _check_udf_filesystem device [last_block]" 1>&2
	exit 1
    fi

    if [ ! -x $here/src/udf_test ]
    then
	echo "udf_test not installed, please download and build the Philips"
	echo "UDF Verification Software from http://www.extra.research.philips.com/udf/."
	echo "Then copy the udf_test binary to $here/src/."
	echo "If you do not wish to run udf_test then set environment variable DISABLE_UDF_TEST"
	echo "to 1."
	return
    fi

    device=$1
    if [ $# -eq 2 ];
    then
        LAST_BLOCK=`expr \( $2 - 1 \)`
        OPT_ARG="-lastvalidblock $LAST_BLOCK"
    fi

    rm -f $seq.checkfs
    sleep 1 # Due to a problem with time stamps in udf_test
    $here/src/udf_test $OPT_ARG $device | tee $here/$seq.checkfs | egrep "Error|Warning" | \
	_udf_test_known_error_filter | \
	egrep -iv "Error count:.*[0-9]+.*total occurrences:.*[0-9]+|Warning count:.*[0-9]+.*total occurrences:.*[0-9]+" | \
	sed "s/^.*$/Warning UDF Verifier reported errors see $seq.checkfs./g"

}

_check_xfs_test_fs()
{
    TEST_LOG="none"
    TEST_RT="none"
    [ "$USE_EXTERNAL" = yes -a ! -z "$TEST_LOGDEV" ] && \
        TEST_LOG="$TEST_LOGDEV"

    [ "$USE_EXTERNAL" = yes -a ! -z "$TEST_RTDEV" ] && \
        TEST_RT="$TEST_RTDEV"

    _check_xfs_filesystem $TEST_DEV $TEST_LOG $TEST_RT

    # check for ipath consistency
    if $XFS_GROWFS_PROG -n $TEST_DIR | grep -q 'inode-paths=1'; then
	# errors go to stderr
	xfs_check_ipaths $TEST_DIR >/dev/null
	xfs_repair_ipaths -n $TEST_DIR >/dev/null
    fi
}

_check_btrfs_filesystem()
{
    device=$1

    # If type is set, we're mounted
    type=`_fs_type $device`
    ok=1

    if [ "$type" = "$FSTYP" ]
    then
        # mounted ...
        mountpoint=`_umount_or_remount_ro $device`
    fi

    btrfsck $device >$tmp.fsck 2>&1
    if [ $? -ne 0 ]
    then
        echo "_check_btrfs_filesystem: filesystem on $device is inconsistent (see $seq.full)"

        echo "_check_btrfs_filesystem: filesystem on $device is inconsistent" >>$here/$seq.full
        echo "*** fsck.$FSTYP output ***"                     >>$here/$seq.full
        cat $tmp.fsck                                         >>$here/$seq.full
        echo "*** end fsck.$FSTYP output"                     >>$here/$seq.full

        ok=0
    fi
    rm -f $tmp.fsck

    if [ $ok -eq 0 ]
    then
        echo "*** mount output ***"                             >>$here/$seq.full
        _mount                                                  >>$here/$seq.full
        echo "*** end mount output"                             >>$here/$seq.full
    elif [ "$type" = "$FSTYP" ]
    then
	# was mounted ...
	_mount_or_remount_rw "$MOUNT_OPTIONS" $device $mountpoint
	ok=$?
    fi

    if [ $ok -eq 0 ]; then
	status=1
	exit 1
    fi

    return 0
}

_check_test_fs()
{
    case $FSTYP in
    xfs)
	_check_xfs_test_fs
	;;
    nfs)
	# no way to check consistency for nfs
	;;
    udf)
	# do nothing for now
	;;
    btrfs)
	_check_btrfs_filesystem $TEST_DEV
	;;
    *)
	_check_generic_filesystem $TEST_DEV
	;;
    esac
}

_check_scratch_fs()
{
    case $FSTYP in
    xfs)
	SCRATCH_LOG="none"
	SCRATCH_RT="none"
	[ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
	    SCRATCH_LOG="$SCRATCH_LOGDEV"

	[ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_RTDEV" ] && \
	    SCRATCH_RT="$SCRATCH_RTDEV"

	_check_xfs_filesystem $SCRATCH_DEV $SCRATCH_LOG $SCRATCH_RT
	;;
    udf)
	_check_udf_filesystem $SCRATCH_DEV $udf_fsize
	;;
    nfs*)
	# Don't know how to check an NFS filesystem, yet.
	;;
    btrfs)
	_check_btrfs_filesystem $SCRATCH_DEV
	;;
    *)
	_check_generic_filesystem $SCRATCH_DEV
	;;
    esac
}

_full_fstyp_details()
{
     [ -z "$FSTYP" ] && FSTYP=xfs
     if [ $FSTYP = xfs ]; then
	if [ -d /proc/fs/xfs ]; then
	    if grep -q 'debug 0' /proc/fs/xfs/stat; then
		FSTYP="$FSTYP (non-debug)"
	    elif grep -q 'debug 1' /proc/fs/xfs/stat; then
		FSTYP="$FSTYP (debug)"
	    fi
	else
	    if uname -a | grep -qi 'debug'; then
		FSTYP="$FSTYP (debug)"
	    else
		FSTYP="$FSTYP (non-debug)"
	    fi
	fi
     fi
     echo $FSTYP
}

_full_platform_details()
{
     os=`uname -s`
     host=`hostname -s`
     kernel=`uname -r`
     platform=`uname -m`
     echo "$os/$platform $host $kernel"
}

_setup_udf_scratchdir()
{
    [ "$FSTYP" != "udf" ] \
	&& _fail "setup_udf_testdir: \$FSTYP is not udf"
    [ -z "$SCRATCH_DEV" -o ! -b "$SCRATCH_DEV" ] \
	&& _notrun "this test requires a valid \$SCRATCH_DEV"
    [ -z "$SCRATCH_MNT" ] \
	&& _notrun "this test requires a valid \$SCRATCH_MNT"

    # mounted?
    if _mount | grep -q $SCRATCH_DEV
    then
        # if it's mounted, make sure its on $TEST_RW_DIR
        if ! _mount | grep $SCRATCH_DEV | grep -q $SCRATCH_MNT
        then
            _fail "\$SCRATCH_DEV is mounted but not on \$SCRATCH_MNT - aborting"
        fi
    	$UMOUNT_PROG $SCRATCH_DEV
    fi

    _scratch_mkfs
    _scratch_mount

    testdir=$SCRATCH_MNT
}

_setup_nfs_scratchdir()
{
    [ "$FSTYP" != "nfs" ] \
	&& _fail "setup_nfs_testdir: \$FSTYP is not nfs"
    [ -z "$SCRATCH_DEV" ] \
	&& _notrun "this test requires a valid host fs for \$SCRATCH_DEV"
    [ -z "$SCRATCH_MNT" ] \
	&& _notrun "this test requires a valid \$SCRATCH_MNT"

    # mounted?
    if _mount | grep -q $SCRATCH_DEV
    then
        # if it's mounted, make sure its on $SCRATCH_MNT
        if ! _mount | grep $SCRATCH_DEV | grep -q $SCRATCH_MNT
        then
            _fail "\$SCRATCH_DEV is mounted but not on \$SCRATCH_MNT - aborting"
        fi
    	$UMOUNT_PROG $SCRATCH_DEV
    fi

    _scratch_mkfs
    _scratch_mount

    testdir=$SCRATCH_MNT
}

#
# Warning for UDF and NFS:
# this function calls _setup_udf_scratchdir and _setup_udf_scratchdir
# which actually uses the scratch dir for the test dir.
#
# This was done because testdir was intended to be a persistent
# XFS only partition.  This should eventually change, and treat
# at least local filesystems all the same.
#
_setup_testdir()
{
    case $FSTYP in
    udf)
	_setup_udf_scratchdir
	;;
    nfs*)
	_setup_nfs_scratchdir
	;;
    *)
	testdir=$TEST_DIR
	;;
    esac
}

_cleanup_testdir()
{
    case $FSTYP in
    udf)
	# umount testdir as it is $SCRATCH_MNT which could be used by xfs next
	[ -n "$testdir" ] && $UMOUNT_PROG $testdir
	;;
    nfs*)
	# umount testdir as it is $SCRATCH_MNT which could be used by xfs next
	[ -n "$testdir" ] && $UMOUNT_PROG $testdir
	;;
    *)
	# do nothing, testdir is $TEST_DIR
	:
	;;
    esac
}

_link_out_file()
{
   if [ -z "$1" ]; then
      echo Error must pass \$seq.
      exit
   fi
   rm -f $1
   if [ "`uname`" == "IRIX64" ] || [ "`uname`" == "IRIX" ]; then
      ln -s $1.irix $1
   elif [ "`uname`" == "Linux" ]; then
      ln -s $1.linux $1
   else
      echo Error test $seq does not run on the operating system: `uname`
      exit
   fi
}

_die()
{
        echo $@
        exit 1
}

#takes files, randomdata
_nfiles()
{
        f=0
        while [ $f -lt $1 ]
        do
                file=f$f
                echo > $file
                if [ $size -gt 0 ]; then
                    if [ "$2" == "false" ]; then
                        dd if=/dev/zero of=$file bs=1024 count=$size 2>&1 | _filter_dd
                    else
                        dd if=/dev/urandom of=$file bs=1024 count=$size 2>&1 | _filter_dd
                    fi
                fi
		let f=$f+1
        done
}

# takes dirname, depth, randomdata
_descend()
{
        dirname=$1; depth=$2; randomdata=$3
        mkdir $dirname  || die "mkdir $dirname failed"
        cd $dirname

        _nfiles $files $randomdata          # files for this dir and data type

        [ $depth -eq 0 ] && return
	let deep=$depth-1 # go 1 down

        [ $verbose = true ] && echo "descending, depth from leaves = $deep"

        d=0
        while [ $d -lt $dirs ]
        do
                _descend d$d $deep &
		let d=$d+1
                wait
        done
}

# Populate a filesystem with inodes for performance experiments
#
# usage: populate [-v] [-n ndirs] [-f nfiles] [-d depth] [-r root] [-s size] [-x]
#
_populate_fs()
{
    here=`pwd`
    dirs=5          # ndirs in each subdir till leaves
    size=0          # sizeof files in K
    files=100       # num files in _each_ subdir
    depth=2         # depth of tree from root to leaves
    verbose=false
    root=root       # path of initial root of directory tree
    randomdata=false # -x data type urandom or zero

    OPTIND=1
    while getopts "d:f:n:r:s:v:x" c
    do
        case $c in
        d)      depth=$OPTARG;;
        n)      dirs=$OPTARG;;
        f)      files=$OPTARG;;
        s)      size=$OPTARG;;
        v)      verbose=true;;
        r)      root=$OPTARG;;
        x)      randomdata=true;;
        esac
    done

    _descend $root $depth $randomdata
    wait

    cd $here

    [ $verbose = true ] && echo done
}

# query whether the given file has the given inode flag set
#
_test_inode_flag()
{
    flag=$1
    file=$2

    if which $XFS_IO_PROG >/dev/null; then
        if $XFS_IO_PROG -r -c 'lsattr -v' "$file" | grep -q "$flag" ; then
	    return 0
        fi
    fi
    return 1
}

# query the given files extsize allocator hint in bytes (if any)
#
_test_inode_extsz()
{
    file=$1
    blocks=""

    if which $XFS_IO_PROG >/dev/null; then
	blocks=`$XFS_IO_PROG -r -c 'stat' "$file" | \
		awk '/^xattr.extsize =/ { print $3 }'`
    fi
    [ -z "$blocks" ] && blocks="0"
    echo $blocks
}

# scratch_dev_pool should contain the disks pool for the btrfs raid
_require_scratch_dev_pool()
{
	local i
	if [ -z "$SCRATCH_DEV_POOL" ]; then
		_notrun "this test requires a valid \$SCRATCH_DEV_POOL"
	fi

	# btrfs test case needs 2 or more scratch_dev_pool; other FS not sure
	# so fail it
	case $FSTYP in
	btrfs)
		if [ "`echo $SCRATCH_DEV_POOL|wc -w`" -lt 2 ]; then
			_notrun "btrfs and this test needs 2 or more disks in SCRATCH_DEV_POOL"
		fi
	;;
	*)
		_notrun "dev_pool is not supported by fstype \"$FSTYP\""
	;;
	esac

	for i in $SCRATCH_DEV_POOL; do
		if [ "`_is_block_dev $i`" = "" ]; then
			_notrun "this test requires valid block disk $i"
		fi
		if [ "`_is_block_dev $i`" = "`_is_block_dev $TEST_DEV`" ]; then
			_notrun "$i is part of TEST_DEV, this test requires unique disks"
		fi
		if _mount | grep -q $i; then
			if ! $UMOUNT_PROG $i; then
		            echo "failed to unmount $i - aborting"
		            exit 1
		        fi
		fi
		# to help better debug when something fails, we remove
		# traces of previous btrfs FS on the dev.
		dd if=/dev/zero of=$i bs=4096 count=100 > /dev/null 2>&1
	done
}

# We will check if the device is virtual (eg: loop device) since it does not
# have the delete entry-point. Otherwise SCSI and USB devices are fine. 
_require_deletable_scratch_dev_pool()
{
	local i
	local x
	for i in $SCRATCH_DEV_POOL; do
		x=`echo $i | cut -d"/" -f 3`
		ls -l /sys/class/block/${x} | grep -q "virtual" 
		if [ $? == "0" ]; then
			_notrun "$i is a virtual device which is not deletable"
		fi
	done
}

# We check for btrfs and (optionally) features of the btrfs command
_require_btrfs()
{
	cmd=$1
	_require_command $BTRFS_UTIL_PROG btrfs
	if [ -z "$1" ]; then
		return 1;
	fi
	$BTRFS_UTIL_PROG $cmd --help >/dev/null 2>&1
	[ $? -eq 0 ] || _notrun "$BTRFS_UTIL_PROG too old (must support $cmd)"
}

# Check that fio is present, and it is able to execute given jobfile
_require_fio()
{
	job=$1

	_require_command $FIO_PROG
	if [ -z "$1" ]; then
		return 1;
	fi

	$FIO_PROG --warnings-fatal --showcmd $job >/dev/null 2>&1
	[ $? -eq 0 ] || _notrun "$FIO_PROG too old"
}

# Does freeze work on this fs?
_require_freeze()
{
	xfs_freeze -f "$TEST_DIR" >/dev/null 2>&1
	result=$? 
	xfs_freeze -u "$TEST_DIR" >/dev/null 2>&1
	[ $result -eq 0 ] || _notrun "$FSTYP does not support freezing"
}

# arg 1 is dev to remove and is output of the below eg.
# ls -l /sys/class/block/sdd | rev | cut -d "/" -f 3 | rev
_devmgt_remove()
{
	echo 1 > /sys/class/scsi_device/${1}/device/delete || _fail "Remove disk failed"
}

# arg 1 is dev to add and is output of the below eg.
# ls -l /sys/class/block/sdd | rev | cut -d "/" -f 3 | rev
_devmgt_add()
{
	local h
	local tdl
	# arg 1 will be in h:t:d:l format now in the h and "t d l" format
	h=`echo ${1} | cut -d":" -f 1`
	tdl=`echo ${1} | cut -d":" -f 2-|sed 's/:/ /g'`

	echo ${tdl} >  /sys/class/scsi_host/host${h}/scan || _fail "Add disk failed"
}

_require_fstrim()
{
	if [ -z "$FSTRIM_PROG" ]; then
		_notrun "This test requires fstrim utility."
	fi
}

_test_batched_discard()
{
	if [ $# -ne 1 ]; then
		echo "Usage: _test_batched_discard mnt_point" 1>&2
		exit 1
	fi
	_require_fstrim
	$FSTRIM_PROG ${1} &>/dev/null
}

_require_dumpe2fs()
{
	if [ -z "$DUMPE2FS_PROG" ]; then
		_notrun "This test requires dumpe2fs utility."
	fi
}

_create_loop_device()
{
	file=$1
	dev=`losetup -f --show $file` || _fail "Cannot assign $file to a loop device"
	echo $dev
}

_destroy_loop_device()
{
	dev=$1
	losetup -d $dev || _fail "Cannot destroy loop device $dev"
}

_scale_fsstress_args()
{
    args=""
    while [ $# -gt 0 ]; do
        case "$1" in
            -n) args="$args $1 $(($2 * $TIME_FACTOR))"; shift ;;
            -p) args="$args $1 $(($2 * $LOAD_FACTOR))"; shift ;;
            *) args="$args $1" ;;
        esac
        shift
    done
    echo $args
}

run_check()
{
	echo "# $@" >> $seq.full 2>&1
	"$@" >> $seq.full 2>&1 || _fail "failed: '$@'"
}

################################################################################

if [ "$iam" != new -a "$iam" != bench ]
then
    # make some further configuration checks here

    if [ "$TEST_DEV" = ""  ]
    then
        echo "common.rc: Error: \$TEST_DEV is not set"
        exit 1
    fi

    # if $TEST_DEV is not mounted, mount it now as XFS
    if [ -z "`_fs_type $TEST_DEV`" ]
    then
        # $TEST_DEV is not mounted
        if ! _test_mount
        then
            echo "common.rc: retrying test device mount with external set"
            [ "$USE_EXTERNAL" != "yes" ] && export USE_EXTERNAL=yes
            if ! _test_mount
            then
                echo "common.rc: could not mount $TEST_DEV on $TEST_DIR"
                exit 1
            fi
        fi
    fi

    if [ "`_fs_type $TEST_DEV`" != "$FSTYP" ]
    then
        echo "common.rc: Error: \$TEST_DEV ($TEST_DEV) is not a MOUNTED $FSTYP filesystem"
        $DF_PROG $TEST_DEV
        exit 1
    fi
fi

# make sure this script returns success
/bin/true