File: nfstest_alloc

package info (click to toggle)
nfstest 3.2-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,580 kB
  • sloc: python: 24,102; makefile: 3
file content (1281 lines) | stat: -rwxr-xr-x 56,074 bytes parent folder | download
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
#!/usr/bin/env python3
#===============================================================================
# Copyright 2015 NetApp, Inc. All Rights Reserved,
# contribution by Jorge Mora <mora@netapp.com>
#
# 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.
#===============================================================================
import os
import time
import errno
import ctypes
import struct
import formatstr
import traceback
import nfstest_config as c
from nfstest.utils import *
from packet.nfs.nfs4_const import *
from nfstest.test_util import TestUtil
from fcntl import fcntl,F_WRLCK,F_SETLK

# Module constants
__author__    = "Jorge Mora (%s)" % c.NFSTEST_AUTHOR_EMAIL
__copyright__ = "Copyright (C) 2015 NetApp, Inc."
__license__   = "GPL v2"
__version__   = "1.3"

USAGE = """%prog --server <server> [options]

Space reservation tests
=======================
Verify correct functionality of space reservations so applications are
able to reserve or unreserve space for a file. The system call fallocate
is used to manipulate the allocated disk space for a file, either to
preallocate or deallocate it. For filesystems which support the fallocate
system call, preallocation is done quickly by allocating blocks and
marking them as uninitialized, requiring no I/O to the data blocks.
This is much faster than creating a file and filling it with zeros.

Basic allocate tests verify the disk space is actually preallocated or
reserved for the given range by filling up the device after the allocation
and make sure data can be written to the allocated range without any
problems. Also, any data written outside the allocated range will fail
with NFS4ERR_NOSPC when there is no more space left on the device.
On the other hand, deallocating space will give the disk space back
so it can be used by either the same file on regions not already
preallocated or by different files without the risk of getting
a no space error.

Performance testing using ALLOCATE versus initializing a file to all
zeros is also included. The performance comparison is done with different
file sizes.

Some tests include testing at the protocol level by taking a packet trace
and inspecting the actual packets sent to the server or servers.

Negative testing is included whenever possible since some testing cannot
be done at the protocol level because the fallocate system call does some
error checking of its own and the NFS client won't even send an ALLOCATE
or DEALLOCATE operation to the server letting the server deal with the
error. Negative tests include trying to allocate an invalid range, having
an invalid value for either the offset or the length, trying to allocate
or deallocate a region on a file opened as read only or the file is a
non-regular file type.

Examples:
    The only required option is --server
    $ %prog --server 192.168.0.11

Notes:
    The user id in the local host must have access to run commands as root
    using the 'sudo' command without the need for a password.

    Tests which require filling up all the disk space on the mounted device
    should have exclusive access to the device.

    Valid only for NFS version 4.2 and above."""

# Test script ID
SCRIPT_ID = "ALLOC"

ALLOC_TESTS = [
    "alloc01",
    "alloc02",
    "alloc03",
    "alloc04",
    "alloc05",
    "alloc06",
]
DEALLOC_TESTS = [
    "dealloc01",
    "dealloc02",
    "dealloc03",
    "dealloc04",
    "dealloc05",
    "dealloc06",
]
PERF_TESTS = [
    "perf01",
]

# Include the test groups in the list of test names
# so they are displayed in the help
TESTNAMES = ["alloc"] + ALLOC_TESTS + ["dealloc"] + DEALLOC_TESTS + PERF_TESTS

TESTGROUPS = {
    "alloc": {
         "tests": ALLOC_TESTS,
         "desc": "Run all ALLOCATE tests: ",
    },
    "dealloc": {
         "tests": DEALLOC_TESTS,
         "desc": "Run all DEALLOCATE tests: ",
    },
}

def getlock(fd, lock_type, offset=0, length=0):
    """Get byte range lock on file given by file descriptor"""
    lockdata = struct.pack('hhllhh', lock_type, 0, offset, length, 0, 0)
    out = fcntl(fd, F_SETLK, lockdata)
    return struct.unpack('hhllhh', out)

class AllocTest(TestUtil):
    """AllocTest object

       AllocTest() -> New test object

       Usage:
           x = AllocTest(testnames=['alloc01', 'alloc02', 'alloc03', ...])

           # Run all the tests
           x.run_tests()
           x.exit()
    """
    def __init__(self, **kwargs):
        """Constructor

           Initialize object's private data.
        """
        TestUtil.__init__(self, **kwargs)
        self.opts.version = "%prog " + __version__

        # Set default script options
        # Tests are valid for NFSv4.2 and beyond
        self.opts.set_defaults(nfsversion=4.2)

        # Options specific for this test script
        # Option self.free_blocks
        hmsg = "Number of free blocks to use when trying to allocate all " + \
               "available space [default: %default]"
        self.test_opgroup.add_option("--free-blocks", type="int", default=64, help=hmsg)
        # Option self.perf_fsize
        hmsg = "Starting file size for the perf01 test [default: %default]"
        self.test_opgroup.add_option("--perf-fsize", default="1MB", help=hmsg)
        # Option self.perf_mult
        hmsg = "File size multiplier for the perf01 test, the tests are " + \
               "performed for a file size which is a multiple of the " + \
               "previous test file size [default: %default]"
        self.test_opgroup.add_option("--perf-mult", type="int", default=4, help=hmsg)
        # Option self.perf_time
        hmsg = "Run the performance test perf01 until the sub-test for " + \
               "the current file size executes for more than this time " + \
               "[default: %default]"
        self.test_opgroup.add_option("--perf-time", type="int", default=15, help=hmsg)
        self.scan_options()

        # Convert units
        self.perf_fsize = formatstr.int_units(self.perf_fsize)

        # Disable createtraces option but save it first for tests that do not
        # check the NFS packets to verify the assertion
        self._createtraces = self.createtraces
        self.createtraces = False

    def setup(self, **kwargs):
        """Setup test environment"""
        self.umount()
        self.mount()
        # Get block size for mounted volume
        self.statvfs = os.statvfs(self.mtdir)
        super(AllocTest, self).setup(**kwargs)
        self.umount()

    def dprint_freebytes(self):
        """Display available disk space"""
        self.dprint('DBG4', "Available disk space %s" % formatstr.str_units(self.get_freebytes()))

    def verify_fallocate(self, fd, offset, size, **kwargs):
        """Verify fallocate works as expected

           fd:
               Allocate/deallocate disk space for the file referred
               to by this file handle
           offset:
               Starting offset where the allocation or deallocation
               takes place
           size:
               Length of region in file to allocate or deallocate
           msg:
               Message appended to assertion [default: ""]
           smsg:
               Message appended to file size assertion [default: ""]
           dmsg:
               Debug message to display [default: None]
           absfile:
               File name to display in default debug message
               [default: self.absfile]
           ftype:
               File type [default: "file"]
           error:
               Expected error [default: None]
           dealloc:
               Verify deallocate when set to True [default: False]
        """
        msg     = kwargs.pop("msg", "")
        smsg    = kwargs.pop("smsg", "")
        dmsg    = kwargs.pop("dmsg", None)
        absfile = kwargs.pop("absfile", self.absfile)
        ftype   = kwargs.pop("ftype", "file")
        error   = kwargs.pop("error", None)
        dealloc = kwargs.pop("dealloc", False)
        err = 0
        fmsg = ""

        if dealloc:
            mode  = SR_DEALLOCATE
            opstr = "Deallocate"
        else:
            mode  = SR_ALLOCATE
            opstr = "Allocate"

        s_msg = opstr.lower() + smsg
        if dmsg is None:
            dmsg = "%s %s %s starting at offset %d with length %d" % (opstr, ftype, absfile, offset, size)

        # Get the size of file
        fstat = os.fstat(fd)
        esize = fstat.st_size

        self.dprint('DBG3', dmsg)
        out = self.libc.fallocate(fd, mode, offset, size)
        if out == -1:
            err = ctypes.get_errno()
            errstr = errno.errorcode.get(err,err)
            fmsg = ", got error [%s] %s" % (errstr, os.strerror(err))
        elif error:
            fmsg = ", but it succeeded"

        if error is None:
            # Expecting fallocate to succeed
            self.test(out == 0, "%s should succeed %s" % (opstr, msg), failmsg=fmsg)
            if dealloc:
                tmsg = "File size should not change after %s" % s_msg
            else:
                esize = max(esize, offset+size)
                tmsg = "File size should be correct after %s" % s_msg
        else:
            # Expecting fallocate to fail
            tmsg = "File size should not change after a failed %s" % s_msg
            errorstr = errno.errorcode.get(error,error)
            self.test(out == -1 and err == error, "%s should fail with %s %s" % (opstr, errorstr, msg), failmsg=fmsg)

        if ftype == "file":
            fstat = os.fstat(fd)
            tfmsg = ", expecting file size %d and got %d" % (esize, fstat.st_size)
            self.test(esize == fstat.st_size, tmsg, failmsg=tfmsg)

        return out

    def verify_allocate(self, offset, size, **kwargs):
        """Verify client sends ALLOCATE/DEALLOCATE with correct arguments

           offset:
               Starting offset of allocation or deallocation
           size:
               Length of region in file to allocate or deallocate
           stateid:
               Expected stateid in call [default: self.stateid]
           status:
               Expected status in reply [default: NFS4_OK]
           dealloc:
               Verify DEALLOCATE when set to True [default: False]
        """
        status  = kwargs.pop("status",  NFS4_OK)
        stateid = kwargs.pop("stateid", self.stateid)
        dealloc = kwargs.pop("dealloc", False)
        mstatus = nfsstat4.get(status, status)

        nfsop = OP_DEALLOCATE if dealloc else OP_ALLOCATE
        opstr = "DEALLOCATE"  if dealloc else "ALLOCATE"

        # Find next ALLOCATE/DEALLOCATE call and reply
        (pktcall, pktreply) = self.find_nfs_op(nfsop, status=None)
        self.dprint('DBG7', str(pktcall))
        self.dprint('DBG7', str(pktreply))

        self.test(pktcall, "%s should be sent to the server" % opstr)
        if pktcall is None:
            return

        allocobj = pktcall.NFSop

        fmsg = ", expecting 0x%08x but got 0x%08x" % (formatstr.crc32(stateid), formatstr.crc32(allocobj.stateid.other))
        self.test(allocobj.stateid == stateid, "%s should be sent with correct stateid" % opstr, failmsg=fmsg)
        fmsg = ", expecting %d but got %d" % (offset, allocobj.offset)
        self.test(allocobj.offset == offset, "%s should be sent with correct offset" % opstr, failmsg=fmsg)
        fmsg = ", expecting %d but got %d" % (size, allocobj.length)
        self.test(allocobj.length == size, "%s should be sent with correct length" % opstr, failmsg=fmsg)

        if status == NFS4_OK:
            msg = "%s should return NFS4_OK" % opstr
        else:
            msg = "%s should fail with %s when whole range cannot be guaranteed" % (opstr, mstatus)

        if pktreply:
            rstatus = pktreply.nfs.status
            fmsg = ", expecting %s but got %s" % (mstatus, nfsstat4.get(rstatus, rstatus))
        else:
            rstatus = None
            fmsg = ""
        self.test(pktreply and rstatus == status, msg, failmsg=fmsg)

    def alloc01(self, open_mode, offset=0, size=None, msg="", lock=False, dealloc=False):
        """Main test to verify ALLOCATE/DEALLOCATE succeeds on files opened as
           write only or read and write.

           open_mode:
               Open mode, either O_WRONLY or O_RDWR
           offset:
               Starting offset where the allocation or deallocation will take
               place [default: 0]
           size:
               Length of region in file to allocate or deallocate.
               [default: --filesize option]
           msg:
               String to identify the specific test running and it is appended
               to the main assertion message [default: ""]
           lock:
               Lock file before doing the allocate/deallocate [default: False]
           dealloc:
               Run the DEALLOCATE test when set to True [default: False]
        """
        try:
            fd = None
            if size is None:
                # Default size to allocate or deallocate
                size = self.filesize

            self.test_info("====  %s test %02d%s" % (self.testname, self.testidx, msg))
            self.testidx += 1
            self.umount()

            if open_mode == os.O_RDWR or dealloc:
                # Mount device to create a new file, this file should already
                # exist for the test
                self.mount()

            if open_mode == os.O_WRONLY:
                open_str = "writing"
                o_str = "write only"
                if dealloc:
                    # Create a new file for deallocate tests
                    self.create_file()
                else:
                    # Get a new file name
                    self.get_filename()
                drange = [0, 0]
                zrange = [offset, size]
            else:
                open_str = "read and write"
                o_str = open_str
                # Create a new file to have an existing file for the test
                self.create_file()
                # No change on current data should be expected on allocate
                drange = [0, self.filesize]
                if offset+size > self.filesize:
                    # Allocate range is beyond the end of the file so zero data
                    # should be expected beyond the end of the current file size
                    zrange = [self.filesize, offset+size-self.filesize]
                else:
                    # Allocate range is fully inside the current file size thus
                    # all data should remained intact -- no zeros
                    zrange = [0, 0]

            if dealloc:
                nfsop = OP_DEALLOCATE
                opstr = "Deallocate"

                if offset >= self.filesize:
                    # Deallocate range is fully outside the current file size
                    # so all data should remained intact -- no zeros
                    drange = [0, self.filesize]
                    zrange = [0, 0]
                elif offset+size > self.filesize:
                    # Deallocate range is partially outside the current file
                    # size thus data should remain intact from the start of
                    # the file to the start of the deallocated range and
                    # zero data should be expected starting from offset to
                    # the end of the file -- file size should not change
                    drange = [0, offset]
                    zrange = [offset, self.filesize-offset]
                else:
                    # Deallocate range is fully inside the current file size
                    # thus zero data should be expected on the entire
                    # deallocated range and all data outside this range should
                    # be left intact
                    drange = [0, offset]
                    if offset+size < self.filesize:
                        drange += [offset+size, self.filesize-offset-size]
                    zrange = [offset, size]
            else:
                nfsop = OP_ALLOCATE
                opstr = "Allocate"

            self.umount()
            self.trace_start()
            self.mount()

            self.dprint('DBG2', "Open file %s for %s" % (self.absfile, open_str))
            fd = os.open(self.absfile, open_mode|os.O_CREAT)

            if lock:
                self.dprint('DBG3', "Lock file %s starting at offset %d with length %d" % (self.absfile, offset, size))
                getlock(fd, F_WRLCK, offset, size)

            # Allocate or deallocate test range
            tmsg = "when the file is opened as %s" % o_str
            self.verify_fallocate(fd, offset, size, msg=tmsg, smsg=msg, dealloc=dealloc)
            os.close(fd)
            fd = None

            # Verify the contents of the file are correct, data and zero regions
            self.dprint('DBG2', "Open file %s for reading" % self.absfile)
            fd = os.open(self.absfile, os.O_RDONLY)

            if drange[1] > 0:
                # Read from range where previous file data is expected
                self.dprint('DBG3', "Read file %s %d @ %d" % (self.absfile, drange[1], drange[0]))
                os.lseek(fd, drange[0], 0)
                rdata = os.read(fd, drange[1])
                wdata = self.data_pattern(drange[0], drange[1])
                if dealloc:
                    tmsg = "Read from file before deallocated range should return the file data"
                else:
                    tmsg = "Read from allocated range within the previous file size should return the file data"
                self.test(rdata == wdata, tmsg)
            if len(drange) > 2 and drange[3] > 0:
                # Read from second range where previous file data is expected
                self.dprint('DBG3', "Read file %s %d @ %d" % (self.absfile, drange[3], drange[2]))
                os.lseek(fd, drange[2], 0)
                rdata = os.read(fd, drange[3])
                wdata = self.data_pattern(drange[2], drange[3])
                self.test(rdata == wdata, "Read from file after deallocated range should return the file data")

            if zrange[1] > 0:
                # Read from range where zero data is expected
                self.dprint('DBG3', "Read file %s %d @ %d" % (self.absfile, zrange[1], zrange[0]))
                os.lseek(fd, zrange[0], 0)
                rdata = os.read(fd, zrange[1])
                wdata = bytes(zrange[1])
                if dealloc:
                    tmsg = "Read from deallocated range inside the previous file size should return zeros"
                else:
                    tmsg = "Read from allocated range outside the previous file size should return zeros"
                self.test(rdata == wdata, tmsg)
        except Exception:
            self.test(False, traceback.format_exc())
        finally:
            if fd:
                os.close(fd)
            self.umount()
            self.trace_stop()

        try:
            # Process the packet trace to inspect the NFS packets
            self.trace_open()
            self.set_pktlist()
            # Get the correct state id for the ALLOCATE/DEALLOCATE operation
            self.get_stateid(self.filename, write=True)

            # Verify ALLOCATE/DEALLOCATE packet call and reply
            self.verify_allocate(offset, size, dealloc=dealloc)
        except Exception:
            self.test(False, traceback.format_exc())
        finally:
            self.pktt.close()

    def alloc01_test(self):
        """Verify ALLOCATE succeeds on files opened as write only"""
        self.test_group("Verify ALLOCATE succeeds on files opened as write only")
        blocksize = self.statvfs.f_bsize
        bsize = int(blocksize/2)
        self.testidx = 1

        self.alloc01(os.O_WRONLY)
        msg1 = " for a range not starting at the beginning of the file"
        self.alloc01(os.O_WRONLY, offset=blocksize, size=self.filesize, msg=msg1)
        msg2 = " for a range starting at a non-aligned block size boundary"
        self.alloc01(os.O_WRONLY, offset=bsize, size=blocksize+bsize, msg=msg2)
        msg3 = " for a range ending at a non-aligned block size boundary"
        self.alloc01(os.O_WRONLY, offset=0, size=blocksize+bsize, msg=msg3)
        msg4 = " for a range starting and ending at a non-aligned block size boundary"
        self.alloc01(os.O_WRONLY, offset=bsize, size=blocksize, msg=msg4)

        if hasattr(self, "deleg_stateid") and self.deleg_stateid is None:
            # Run tests with byte range locking
            msg = " (locking file)"
            self.alloc01(os.O_WRONLY, msg=msg, lock=True)
            self.alloc01(os.O_WRONLY, offset=blocksize, size=self.filesize, msg=msg1+msg, lock=True)
            self.alloc01(os.O_WRONLY, offset=bsize, size=blocksize+bsize, msg=msg2+msg, lock=True)
            self.alloc01(os.O_WRONLY, offset=0, size=blocksize+bsize, msg=msg3+msg, lock=True)
            self.alloc01(os.O_WRONLY, offset=bsize, size=blocksize, msg=msg4+msg, lock=True)

    def alloc02_test(self):
        """Verify ALLOCATE succeeds on files opened as read and write"""
        self.test_group("Verify ALLOCATE succeeds on files opened as read and write")
        blocksize = self.statvfs.f_bsize
        bsize = int(blocksize/2)
        self.testidx = 1

        self.alloc01(os.O_RDWR)
        msg1 = " for a range not starting at the beginning of the file"
        self.alloc01(os.O_RDWR, offset=blocksize, size=self.filesize, msg=msg1)
        msg2 = " for a range starting at a non-aligned block size boundary"
        self.alloc01(os.O_RDWR, offset=bsize, size=blocksize+bsize, msg=msg2)
        msg3 = " for a range ending at a non-aligned block size boundary"
        self.alloc01(os.O_RDWR, offset=0, size=blocksize+bsize, msg=msg3)
        msg4 = " for a range starting and ending at a non-aligned block size boundary"
        self.alloc01(os.O_RDWR, offset=bsize, size=blocksize, msg=msg4)
        msg5 = " when range is fully inside the current file size"
        self.alloc01(os.O_RDWR, offset=int(self.filesize/4), size=int(self.filesize/2), msg=msg5)
        msg6 = " when range is partially outside the current file size"
        self.alloc01(os.O_RDWR, offset=int(self.filesize/2), size=self.filesize, msg=msg6)
        msg7 = " when range is fully outside the current file size"
        self.alloc01(os.O_RDWR, offset=self.filesize, size=self.filesize, msg=msg7)

        if hasattr(self, "deleg_stateid") and self.deleg_stateid is None:
            # Run tests with byte range locking
            msg = " (locking file)"
            self.alloc01(os.O_RDWR, msg=msg, lock=True)
            self.alloc01(os.O_RDWR, offset=blocksize, size=self.filesize, msg=msg1+msg, lock=True)
            self.alloc01(os.O_RDWR, offset=bsize, size=blocksize+bsize, msg=msg2+msg, lock=True)
            self.alloc01(os.O_RDWR, offset=0, size=blocksize+bsize, msg=msg3+msg, lock=True)
            self.alloc01(os.O_RDWR, offset=bsize, size=blocksize, msg=msg4+msg, lock=True)
            self.alloc01(os.O_RDWR, offset=int(self.filesize/4), size=int(self.filesize/2), msg=msg5+msg, lock=True)
            self.alloc01(os.O_RDWR, offset=int(self.filesize/2), size=self.filesize, msg=msg6+msg, lock=True)
            self.alloc01(os.O_RDWR, offset=self.filesize, size=self.filesize, msg=msg7+msg, lock=True)

    def alloc03(self, dealloc=False):
        """Main test to verify ALLOCATE/DEALLOCATE fails on files opened
           as read only

           dealloc:
               Run the DEALLOCATE test when set to True [default: False]
        """
        try:
            fd = None
            self.umount()
            if self._createtraces:
                # Just capture the packet trace when --createtraces is set
                self.trace_start()
            self.mount()

            # Use an existing file
            absfile = self.abspath(self.files[0])
            self.dprint('DBG2', "Open file %s for reading" % absfile)
            fd = os.open(absfile, os.O_RDONLY)

            # Allocate or deallocate test range
            tmsg = "when the file is opened as read only"
            self.verify_fallocate(fd, 0, self.filesize, absfile=absfile, msg=tmsg, error=errno.EBADF, dealloc=dealloc)
        except Exception:
            self.test(False, traceback.format_exc())
        finally:
            if fd:
                os.close(fd)
            self.umount()
            self.trace_stop()
            self.trace_open()
            self.pktt.close()

    def alloc03_test(self):
        """Verify ALLOCATE fails on files opened as read only"""
        self.test_group("Verify ALLOCATE fails on files opened as read only")
        self.alloc03()

    def alloc04(self, dealloc=False):
        """Verify DE/ALLOCATE fails with EINVAL for invalid offset or length

           dealloc:
               Run the DEALLOCATE test when set to True [default: False]
        """
        try:
            fd = None
            self.umount()
            if self._createtraces:
                # Just capture the packet trace when --createtraces is set
                self.trace_start()
            self.mount()

            if dealloc:
                # Create a new file
                self.create_file()
            else:
                # Get a new file name
                self.get_filename()

            self.dprint('DBG2', "Open file %s for writing" % self.absfile)
            fd = os.open(self.absfile, os.O_WRONLY|os.O_CREAT)

            # Use an invalid offset
            tmsg = "when the offset is invalid"
            self.verify_fallocate(fd, -1, self.filesize, msg=tmsg, error=errno.EINVAL, dealloc=dealloc)

            # Use an invalid length
            tmsg = "when the length is invalid"
            self.verify_fallocate(fd, 0, 0, msg=tmsg, error=errno.EINVAL, dealloc=dealloc)
        except Exception:
            self.test(False, traceback.format_exc())
        finally:
            if fd:
                os.close(fd)
            self.umount()
            self.trace_stop()
            self.trace_open()
            self.pktt.close()

    def alloc04_test(self):
        """Verify ALLOCATE fails with EINVAL for invalid offset or length"""
        self.test_group("Verify ALLOCATE fails EINVAL for invalid offset or length")
        self.alloc04()

    def alloc05(self, dealloc=False):
        """Verify DE/ALLOCATE fails with ESPIPE when using a named pipe file handle

           dealloc:
               Run the DEALLOCATE test when set to True [default: False]
        """
        try:
            fd = None
            pid = None
            self.umount()
            if self._createtraces:
                # Just capture the packet trace when --createtraces is set
                self.trace_start()
            self.mount()
            # Get a new file name
            self.get_filename()

            self.dprint('DBG3', "Create named pipe %s" % self.absfile)
            os.mkfifo(self.absfile)

            # Create another process for reading the named pipe
            pid = os.fork()
            if pid == 0:
                try:
                    fd = os.open(self.absfile, os.O_RDONLY)
                    os.read(fd)
                    os.close(fd)
                finally:
                    os._exit(0)

            self.dprint('DBG2', "Open named pipe %s for writing" % self.absfile)
            fd = os.open(self.absfile, os.O_WRONLY)

            tmsg = "when using a named pipe file handle"
            self.verify_fallocate(fd, 0, self.filesize, ftype="named pipe", msg=tmsg, error=errno.ESPIPE, dealloc=dealloc)

            os.close(fd)
            fd = None
        except Exception:
            self.test(False, traceback.format_exc())
        finally:
            if pid is not None:
                # Reap the background reading process
                (pid, out) = os.waitpid(pid, 0)
            if fd:
                os.close(fd)
            self.umount()
            self.trace_stop()
            self.trace_open()
            self.pktt.close()

    def alloc05_test(self):
        """Verify ALLOCATE fails with ESPIPE when using a named pipe file handle"""
        self.test_group("Verify ALLOCATE fails ESPIPE when using a named pipe file handle")
        self.alloc05()

    def alloc06(self, msg="", lock=False):
        """Verify ALLOCATE reserves the disk space

           msg:
               String to identify the specific test running and it is appended
               to the main assertion message [default: ""]
           lock:
               Lock file before doing the allocate/deallocate [default: False]
        """
        try:
            fd = None
            fd1 = None
            rmfile = None
            otherfile = None
            offset = 0
            size = 4*self.filesize
            free_space = self.free_blocks * self.statvfs.f_bsize

            self.test_info("====  %s test %02d%s" % (self.testname, self.testidx, msg))
            self.testidx += 1

            self.umount()
            self.trace_start()
            self.mount()

            # Get a new file name
            self.get_filename()
            filename = self.filename
            testfile = self.absfile
            self.dprint('DBG2', "Open file %s for writing" % testfile)
            fd = os.open(testfile, os.O_WRONLY|os.O_CREAT)

            if lock:
                self.dprint('DBG3', "Lock file %s starting at offset %d with length %d" % (testfile, offset, size))
                out = getlock(fd, F_WRLCK, offset, size)

            tmsg = "when the file is opened as write only"
            self.verify_fallocate(fd, offset, size, absfile=testfile, msg=tmsg)
            self.dprint_freebytes()

            # Get a new file name
            self.get_filename()
            maxfile = self.filename
            rmfile  = self.absfile
            self.dprint('DBG2', "Open file %s for writing" % rmfile)
            fd1 = os.open(rmfile, os.O_WRONLY|os.O_CREAT)

            maxsize = self.get_freebytes() - free_space
            tmsg = "when allocating the maximum number of blocks left on the device"
            dmsg = "Allocate file %s with length of %s (available disk space minus %s) " % \
                   (rmfile, formatstr.str_units(maxsize), formatstr.str_units(free_space))
            out = self.verify_fallocate(fd1, 0, maxsize, msg=tmsg, dmsg=dmsg)
            if out == -1: return
            self.dprint_freebytes()

            # Check if space was actually allocated
            if self.get_freebytes() > free_space:
                self.test(False, "Space was not actually allocated -- skipping rest of the test")
                return

            # Use the rest of the remaining space and a little bit more
            filesize = self.get_freebytes() + self.filesize

            try:
                fmsg = ", expecting ENOSPC but it succeeded"
                werrno = 0
                self.create_file(size=filesize)
            except OSError as werror:
                werrno = werror.errno
                fmsg = ", expecting ENOSPC but got %s" % errno.errorcode.get(werrno, werrno)
            expr = werrno == errno.ENOSPC
            self.test(expr, "Write to a different file should fail with ENOSPC when no space is left on the device", failmsg=fmsg)
            otherfile = self.filename
            self.dprint_freebytes()

            tmsg = "when whole range cannot be guaranteed"
            self.verify_fallocate(fd, offset+size, filesize, absfile=testfile, msg=tmsg, error=errno.ENOSPC)
            self.dprint_freebytes()

            try:
                fmsg = ", expecting ENOSPC but it succeeded"
                werrno = 0
                os.lseek(fd, offset+size, 0)
                data = self.data_pattern(offset+size, filesize)
                self.dprint('DBG3', "Write file %s %d@%d" % (testfile, len(data), offset+size))
                count = os.write(fd, data)
                os.fsync(fd)
            except OSError as werror:
                werrno = werror.errno
                fmsg = ", expecting ENOSPC but got %s" % errno.errorcode.get(werrno, werrno)
            expr = werrno == errno.ENOSPC
            self.test(expr, "Write outside the allocated region should fail with ENOSPC when no space is left on the device", failmsg=fmsg)
            self.dprint_freebytes()

            os.lseek(fd, offset, 0)
            data = self.data_pattern(offset, size, pattern=b"\x55\xaa")
            self.dprint('DBG3', "Write file %s %d@%d" % (testfile, len(data), offset))
            count = os.write(fd, data)
            os.fsync(fd)
            self.test(count > 0, "Write within the allocated region should succeed when no space is left on the device"+msg)
            self.dprint_freebytes()
        except Exception:
            self.test(False, traceback.format_exc())
        finally:
            if fd:
                try:
                    os.close(fd)
                except:
                    pass
            if fd1:
                os.close(fd1)
            if rmfile:
                os.unlink(rmfile)
            self.umount()
            self.trace_stop()

        try:
            self.set_nfserr_list(nfs4list=[NFS4ERR_NOENT, NFS4ERR_NOSPC])
            self.trace_open()
            self.set_pktlist()

            # Find OPEN and correct stateid to use for the other file
            self.get_stateid(maxfile)
            other_stateid = self.stateid

            # Find OPEN and correct stateid to use
            self.pktt.rewind(0)
            self.get_stateid(filename, noreset=True)
            save_index = self.pktt.get_index()

            # Verify ALLOCATE packet call and reply
            self.verify_allocate(offset, size)

            # Verify ALLOCATE which allocates the rest of the disk space
            self.verify_allocate(0, maxsize, stateid=other_stateid)

            # Verify second ALLOCATE for file
            self.verify_allocate(offset+size, filesize, status=NFS4ERR_NOSPC)

            # Rewind packet trace to search for WRITEs
            in_alloc  = True
            out_alloc = False
            non_alloc = False
            in_alloc_cnt  = 0
            out_alloc_cnt = 0
            non_alloc_cnt = 0
            while True:
                self.pktt.rewind(save_index)
                (pktcall, pktreply) = self.find_nfs_op(OP_WRITE, status=None)
                if not pktcall:
                    break
                save_index = pktcall.record.index + 1
                writeobj = pktcall.NFSop
                if writeobj.stateid == self.stateid:
                    # WRITE sent to allocated file
                    if writeobj.offset < offset+size:
                        # WRITE sent to allocated region
                        in_alloc_cnt += 1
                        if pktreply.nfs.status != NFS4_OK:
                            in_alloc = False
                    else:
                        # WRITE sent to non-allocated region
                        out_alloc_cnt += 1
                        if pktreply.nfs.status == NFS4ERR_NOSPC:
                            out_alloc = True
                else:
                    # WRITE sent to non-allocated file
                    non_alloc_cnt += 1
                    if pktreply.nfs.status == NFS4ERR_NOSPC:
                        non_alloc = True
            if in_alloc_cnt > 0:
                self.test(in_alloc, "WRITE within the allocated region should succeed when no space is left on the device")
            else:
                self.test(False, "WRITE within the allocated region should be sent")
            if out_alloc_cnt > 0:
                self.test(out_alloc, "WRITE outside the allocated region should fail with NFS4ERR_NOSPC when no space is left on the device")
            else:
                self.test(False, "WRITE outside the allocated region should be sent")
            if non_alloc_cnt > 0:
                self.test(non_alloc, "WRITE sent to non-allocated file should return NFS4ERR_NOSPC when no space is left on the device")
            else:
                # No writes found for other file, look for OPEN to check if
                # it failed on open instead
                self.pktt.rewind(0)
                file_str = "NFS.claim.name == '%s'" % otherfile
                (pktcall, pktreply) = self.find_nfs_op(OP_OPEN, match=file_str, status=None)
                if pktreply is None:
                    # Could not find OPEN, fail with the write error below
                    status = NFS4_OK
                else:
                    status = pktreply.NFSop.status
                if status != NFS4_OK:
                    fmsg = ", expecting NFS4ERR_NOSPC but got %s" % nfsstat4.get(status, status)
                    self.test(status == NFS4ERR_NOSPC, "OPEN sent to non-allocated file should return NFS4ERR_NOSPC", failmsg=fmsg)
                else:
                    self.test(False, "WRITE to non-allocated file should be sent")
        except Exception:
            self.test(False, traceback.format_exc())
        finally:
            self.pktt.close()

    def alloc06_test(self):
        """Verify ALLOCATE reserves the disk space"""
        self.test_group("Verify ALLOCATE reserves the disk space")
        self.testidx = 1
        self.alloc06()

        if hasattr(self, "deleg_stateid") and self.deleg_stateid is None:
            # Run tests with byte range locking
            msg = " (locking file)"
            self.alloc06(msg=msg, lock=True)

    def dealloc01_test(self):
        """Verify DEALLOCATE succeeds on files opened as write only"""
        self.test_group("Verify DEALLOCATE succeeds on files opened as write only")
        blocksize = self.statvfs.f_bsize
        bsize = int(blocksize/2)
        self.testidx = 1

        self.alloc01(os.O_WRONLY, dealloc=True)
        msg1 = " for a range not starting at the beginning of the file"
        self.alloc01(os.O_WRONLY, offset=blocksize, size=self.filesize, msg=msg1, dealloc=True)
        msg2 = " for a range starting at a non-aligned block size boundary"
        self.alloc01(os.O_WRONLY, offset=bsize, size=blocksize+bsize, msg=msg2, dealloc=True)
        msg3 = " for a range ending at a non-aligned block size boundary"
        self.alloc01(os.O_WRONLY, offset=0, size=blocksize+bsize, msg=msg3, dealloc=True)
        msg4 = " for a range starting and ending at a non-aligned block size boundary"
        self.alloc01(os.O_WRONLY, offset=bsize, size=blocksize, msg=msg4, dealloc=True)
        msg5 = " when range is fully inside the current file size"
        self.alloc01(os.O_WRONLY, offset=int(self.filesize/4), size=int(self.filesize/2), msg=msg5, dealloc=True)
        msg6 = " when range is partially outside the current file size"
        self.alloc01(os.O_WRONLY, offset=int(self.filesize/2), size=self.filesize, msg=msg6, dealloc=True)
        msg7 = " when range is fully outside the current file size"
        self.alloc01(os.O_WRONLY, offset=self.filesize, size=self.filesize, msg=msg7, dealloc=True)

        if hasattr(self, "deleg_stateid") and self.deleg_stateid is None:
            # Run tests with byte range locking
            msg = " (locking file)"
            self.alloc01(os.O_WRONLY, msg=msg, lock=True, dealloc=True)
            self.alloc01(os.O_WRONLY, offset=blocksize, size=self.filesize, msg=msg1+msg, lock=True, dealloc=True)
            self.alloc01(os.O_WRONLY, offset=bsize, size=blocksize+bsize, msg=msg2+msg, lock=True, dealloc=True)
            self.alloc01(os.O_WRONLY, offset=0, size=blocksize+bsize, msg=msg3+msg, lock=True, dealloc=True)
            self.alloc01(os.O_WRONLY, offset=bsize, size=blocksize, msg=msg4+msg, lock=True, dealloc=True)
            self.alloc01(os.O_WRONLY, offset=int(self.filesize/4), size=int(self.filesize/2), msg=msg5+msg, lock=True, dealloc=True)
            self.alloc01(os.O_WRONLY, offset=int(self.filesize/2), size=self.filesize, msg=msg6+msg, lock=True, dealloc=True)
            self.alloc01(os.O_WRONLY, offset=self.filesize, size=self.filesize, msg=msg7+msg, lock=True, dealloc=True)

    def dealloc02_test(self):
        """Verify DEALLOCATE succeeds on files opened as read and write"""
        self.test_group("Verify DEALLOCATE succeeds on files opened as read and write")
        blocksize = self.statvfs.f_bsize
        bsize = int(blocksize/2)
        self.testidx = 1

        self.alloc01(os.O_RDWR, dealloc=True)
        msg1 = " for a range not starting at the beginning of the file"
        self.alloc01(os.O_RDWR, offset=blocksize, size=self.filesize, msg=msg1, dealloc=True)
        msg2 = " for a range starting at a non-aligned block size boundary"
        self.alloc01(os.O_RDWR, offset=bsize, size=blocksize+bsize, msg=msg2, dealloc=True)
        msg3 = " for a range ending at a non-aligned block size boundary"
        self.alloc01(os.O_RDWR, offset=0, size=blocksize+bsize, msg=msg3, dealloc=True)
        msg4 = " for a range starting and ending at a non-aligned block size boundary"
        self.alloc01(os.O_RDWR, offset=bsize, size=blocksize, msg=msg4, dealloc=True)
        msg5 = " when range is fully inside the current file size"
        self.alloc01(os.O_RDWR, offset=int(self.filesize/4), size=int(self.filesize/2), msg=msg5, dealloc=True)
        msg6 = " when range is partially outside the current file size"
        self.alloc01(os.O_RDWR, offset=int(self.filesize/2), size=self.filesize, msg=msg6, dealloc=True)
        msg7 = " when range is fully outside the current file size"
        self.alloc01(os.O_RDWR, offset=self.filesize, size=self.filesize, msg=msg7, dealloc=True)

        if hasattr(self, "deleg_stateid") and self.deleg_stateid is None:
            # Run tests with byte range locking
            msg = " (locking file)"
            self.alloc01(os.O_RDWR, msg=msg, lock=True, dealloc=True)
            self.alloc01(os.O_RDWR, offset=blocksize, size=self.filesize, msg=msg1+msg, lock=True, dealloc=True)
            self.alloc01(os.O_RDWR, offset=bsize, size=blocksize+bsize, msg=msg2+msg, lock=True, dealloc=True)
            self.alloc01(os.O_RDWR, offset=0, size=blocksize+bsize, msg=msg3+msg, lock=True, dealloc=True)
            self.alloc01(os.O_RDWR, offset=bsize, size=blocksize, msg=msg4+msg, lock=True, dealloc=True)
            self.alloc01(os.O_RDWR, offset=int(self.filesize/4), size=int(self.filesize/2), msg=msg5+msg, lock=True, dealloc=True)
            self.alloc01(os.O_RDWR, offset=int(self.filesize/2), size=self.filesize, msg=msg6+msg, lock=True, dealloc=True)
            self.alloc01(os.O_RDWR, offset=self.filesize, size=self.filesize, msg=msg7+msg, lock=True, dealloc=True)

    def dealloc03_test(self):
        """Verify DEALLOCATE fails on files opened as read only"""
        self.test_group("Verify DEALLOCATE fails on files opened as read only")
        self.alloc03(dealloc=True)

    def dealloc04_test(self):
        """Verify DEALLOCATE fails with EINVAL for invalid offset or length"""
        self.test_group("Verify DEALLOCATE fails EINVAL for invalid offset or length")
        self.alloc04(dealloc=True)

    def dealloc05_test(self):
        """Verify DEALLOCATE fails with ESPIPE when using a named pipe file handle"""
        self.test_group("Verify DEALLOCATE fails ESPIPE when using a named pipe file handle")
        self.alloc05(dealloc=True)

    def dealloc06(self, msg="", lock=False):
        """Verify DEALLOCATE unreserves the disk space

           msg:
               String to identify the specific test running and it is appended
               to the main assertion message [default: ""]
           lock:
               Lock file before doing the allocate/deallocate [default: False]
        """
        try:
            fd = None
            testfile = None
            free_space = self.free_blocks * self.statvfs.f_bsize

            self.test_info("====  %s test %02d%s" % (self.testname, self.testidx, msg))
            self.testidx += 1

            self.umount()
            self.trace_start()
            self.mount()
            self.dprint_freebytes()

            # Get a new file name
            self.get_filename()
            filename = self.filename
            testfile = self.absfile
            self.dprint('DBG2', "Open file %s for writing" % testfile)
            fd = os.open(testfile, os.O_WRONLY|os.O_CREAT)

            maxsize = self.get_freebytes() - free_space
            tmsg = "when allocating the maximum number of blocks left on the device"
            dmsg = "Allocate file %s with length of %s (available disk space minus %s) " % \
                   (testfile, formatstr.str_units(maxsize), formatstr.str_units(free_space))
            out = self.verify_fallocate(fd, 0, maxsize, absfile=testfile, msg=tmsg, dmsg=dmsg)
            if out == -1: return
            self.dprint_freebytes()

            # Check if space was actually allocated
            if self.get_freebytes() > free_space:
                self.test(False, "Space was not actually allocated -- skipping rest of the test")
                return

            # Use the rest of the remaining space and a little bit more
            filesize = 2*self.get_freebytes() + self.filesize

            # Try creating a file to make sure there is no more disk space
            try:
                fmsg = ", expecting ENOSPC but it succeeded"
                werrno = 0
                self.create_file(size=filesize)
            except OSError as werror:
                werrno = werror.errno
                fmsg = ", expecting ENOSPC but got %s" % errno.errorcode.get(werrno, werrno)
            expr = werrno == errno.ENOSPC
            self.test(expr, "Write to a different file should fail with ENOSPC when no space is left on the device", failmsg=fmsg)
            self.dprint_freebytes()

            offset = 0
            size = 4*self.filesize
            # Free space after deallocate
            free_space = size - offset
            strsize = formatstr.str_units(size)

            if lock:
                self.dprint('DBG3', "Lock file %s starting at offset %d with length %d" % (testfile, offset, size))
                out = getlock(fd, F_WRLCK, offset, size)

            tmsg = "when no space is left on the device"
            self.verify_fallocate(fd, offset, size, absfile=testfile, msg=tmsg, dealloc=True)
            self.dprint_freebytes()

            try:
                fmsg = ""
                werrno = 0
                os.lseek(fd, offset, 0)
                data = self.data_pattern(offset, self.filesize)
                self.dprint('DBG3', "Write file %s %d@%d" % (testfile, len(data), offset))
                count = os.write(fd, data)
                os.fsync(fd)
            except OSError as werror:
                werrno = werror.errno
                fmsg = ", got error [%s] %s" % (errno.errorcode.get(werrno, werrno), os.strerror(werrno))
            self.test(werrno == 0, "Write within the deallocated region should succeed", failmsg=fmsg)
            self.dprint_freebytes()

            try:
                fmsg = ""
                werrno = 0
                self.create_file()
            except OSError as werror:
                werrno = werror.errno
                fmsg = ", got error [%s] %s" % (errno.errorcode.get(werrno, werrno), os.strerror(werrno))
            self.test(werrno == 0, "Write to another file should succeed when no space is left on the device after a successful DEALLOCATE"+msg, failmsg=fmsg)
            self.dprint_freebytes()

            try:
                fmsg = ", expecting ENOSPC but it succeeded"
                werrno = 0
                os.lseek(fd, offset+self.filesize, 0)
                data = self.data_pattern(offset+self.filesize, size)
                self.dprint('DBG3', "Write file %s %d@%d" % (testfile, len(data), offset+self.filesize))
                count = os.write(fd, data)
                os.fsync(fd)
            except OSError as werror:
                werrno = werror.errno
                fmsg = ", expecting ENOSPC but got %s" % errno.errorcode.get(werrno, werrno)
            expr = werrno == errno.ENOSPC
            self.test(expr, "Write within the deallocated region should fail with ENOSPC when no space is left on the device", failmsg=fmsg)
            self.dprint_freebytes()
        except Exception:
            self.test(False, traceback.format_exc())
        finally:
            if fd:
                try:
                    os.close(fd)
                except:
                    pass
            if testfile:
                os.unlink(testfile)
            self.umount()
            self.trace_stop()

        try:
            self.set_nfserr_list(nfs4list=[NFS4ERR_NOENT, NFS4ERR_NOSPC])
            self.trace_open()
            self.set_pktlist()
            # Find OPEN and correct stateid to use
            self.get_stateid(filename)
            stateid = self.open_stateid if self.deleg_stateid is None else self.deleg_stateid

            # Verify ALLOCATE which allocates the rest of the disk space
            self.verify_allocate(0, maxsize, stateid=stateid)

            # Verify DEALLOCATE for file
            self.verify_allocate(offset, size, dealloc=True)

            in_dealloc  = True
            out_dealloc = False
            non_dealloc = False
            in_dealloc_cnt  = 0
            out_dealloc_cnt = 0
            non_dealloc_cnt = 0
            save_index = self.pktt.get_index()
            while True:
                self.pktt.rewind(save_index)
                (pktcall, pktreply) = self.find_nfs_op(OP_WRITE, status=None)
                if not pktcall:
                    break
                save_index = pktcall.record.index + 1
                writeobj = pktcall.NFSop
                free_space -= writeobj.count
                if writeobj.stateid == self.stateid:
                    # WRITE sent to deallocated file
                    if writeobj.offset < offset+self.filesize:
                        # WRITE sent to deallocated region when space is available
                        in_dealloc_cnt += 1
                        if pktreply.nfs.status != NFS4_OK:
                            in_dealloc = False
                    else:
                        # WRITE sent to deallocated region when space is no longer available
                        out_dealloc_cnt += 1
                        if pktreply.nfs.status == NFS4ERR_NOSPC:
                            out_dealloc = True
                else:
                    # WRITE sent to different file
                    non_dealloc_cnt += 1
                    if pktreply.nfs.status == NFS4_OK:
                        non_dealloc = True
            if in_dealloc_cnt > 0:
                self.test(in_dealloc, "WRITE within the deallocated region should succeed")
            else:
                self.test(False, "WRITE within the deallocated region should be sent")
            if non_dealloc_cnt > 0:
                self.test(non_dealloc, "WRITE sent to another file should succeed when no space is left on the device after a successful DEALLOCATE")
            else:
                self.test(False, "WRITE should be sent to another file when no space is left on the device after a successful DEALLOCATE")
            if out_dealloc_cnt > 0:
                self.test(out_dealloc, "WRITE within the deallocated region should fail with NFS4ERR_NOSPC when no space is left on the device")
            else:
                self.test(False, "WRITE within the deallocated region should be sent")
        except Exception:
            self.test(False, traceback.format_exc())
        finally:
            self.pktt.close()

    def dealloc06_test(self):
        """Verify DEALLOCATE unreserves the disk space"""
        self.test_group("Verify DEALLOCATE unreserves the disk space")
        self.testidx = 1
        self.dealloc06()

        if hasattr(self, "deleg_stateid") and self.deleg_stateid is None:
            # Run tests with byte range locking
            msg = " (locking file)"
            self.dealloc06(msg=msg, lock=True)

    def perftest(self, filesize):
        try:
            fd = None
            block_size = 16 * self.statvfs.f_bsize
            strsize = formatstr.str_units(filesize)
            filelist = []

            # Get a new file name
            self.get_filename()
            filelist.append(self.absfile)
            self.dprint('DBG2', "Open file %s for writing" % self.absfile)
            fd = os.open(self.absfile, os.O_WRONLY|os.O_CREAT)

            tstart = time.time()
            tmsg = "when the file is opened as write only"
            out = self.verify_fallocate(fd, 0, filesize, msg=tmsg)
            os.close(fd)
            fd = None
            t1delta = time.time() - tstart
            self.dprint('INFO', "ALLOCATE took %f seconds" % t1delta)

            # Get a new file name
            self.get_filename()
            filelist.append(self.absfile)
            self.dprint('DBG2', "Open file %s for writing" % self.absfile)
            fd = os.open(self.absfile, os.O_WRONLY|os.O_CREAT)
            self.dprint('DBG3', "Initialize file %s with zeros" % self.absfile)
            size = filesize
            data = bytes(block_size)
            tstart = time.time()
            while size > 0:
                if block_size > size:
                    data = data[:size]
                count = os.write(fd, data)
                size -= count
            os.close(fd)
            fd = None
            t2delta = time.time() - tstart
            fstat = os.stat(self.absfile)
            self.test(fstat.st_size == filesize, "File size should be correct after initialization")
            self.dprint('INFO', "Initialization took %f seconds" % t2delta)
            if t1delta > 0:
                perf = int(100.0*(t2delta-t1delta) / t1delta)
                msg = ", performance improvement for a %s file: %s%%" % (strsize, "{:,}".format(perf))
            else:
                msg = ""
            self.test(t1delta < t2delta, "ALLOCATE should outperform initializing the file to all zeros" + msg)

        except Exception:
            self.test(False, traceback.format_exc())
        finally:
            if fd:
                os.close(fd)
            for absfile in filelist:
                try:
                    if os.path.exists(absfile):
                        self.dprint('DBG5', "Removing file %s" % absfile)
                        os.unlink(absfile)
                except:
                    pass

    def perf01_test(self):
        """Verify ALLOCATE outperforms initializing the file to all zeros"""
        self.test_group("Verify ALLOCATE outperforms initializing the file to all zeros")
        # Starting file size
        filesize = self.perf_fsize
        self.umount()
        self.mount()
        self.testidx = 1
        while True:
            self.test_info("====  %s test %02d" % (self.testname, self.testidx))
            self.testidx += 1
            tstart = time.time()
            self.perftest(filesize)
            tdelta = time.time() - tstart
            if tdelta > self.perf_time:
                break
            filesize = self.perf_mult*filesize
        self.umount()

################################################################################
# Entry point
x = AllocTest(usage=USAGE, testnames=TESTNAMES, testgroups=TESTGROUPS, sid=SCRIPT_ID)

try:
    x.setup(nfiles=1)

    # Run all the tests
    x.run_tests()
except Exception:
    x.test(False, traceback.format_exc())
finally:
    x.cleanup()
    x.exit()