initial-freebsd-port-work-20010414
[openafs.git] / src / vol / partition.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 #ifndef lint
11 #endif
12 /*
13
14         System:         VICE-TWO
15         Module:         partition.c
16         Institution:    The Information Technology Center, Carnegie-Mellon University
17
18  */
19
20 #include <afs/param.h>
21 #include <ctype.h>
22 #ifdef AFS_NT40_ENV
23 #include <windows.h>
24 #include <winbase.h>
25 #include <winioctl.h>
26 #else
27 #include <sys/param.h>
28 #include <sys/types.h>
29  
30 #if AFS_HAVE_STATVFS
31 #include <sys/statvfs.h>
32 #endif /* AFS_HAVE_STATVFS */
33 #if defined(AFS_DARWIN_ENV) || defined(AFS_FBSD_ENV)
34 #include <sys/mount.h>
35 #endif
36
37 #if !defined(AFS_SGI_ENV)
38 #ifdef  AFS_OSF_ENV
39 #include <sys/mount.h>
40 #include <ufs/fs.h>
41 #else   /* AFS_OSF_ENV */
42 #ifdef AFS_VFSINCL_ENV
43 #define VFS
44 #ifdef  AFS_SUN5_ENV
45 #include <sys/fs/ufs_fs.h>
46 #else
47 #if defined(AFS_DARWIN_ENV) || defined(AFS_FBSD_ENV)
48 #include <ufs/ufs/dinode.h>
49 #include <ufs/ffs/fs.h>
50 #else
51 #include <ufs/fs.h>
52 #endif
53 #endif
54 #else /* AFS_VFSINCL_ENV */
55 #if !defined(AFS_AIX_ENV) && !defined(AFS_LINUX22_ENV) && !defined(AFS_DARWIN_ENV) && !defined(AFS_FBSD_ENV)
56 #include <sys/fs.h>
57 #endif
58 #endif /* AFS_VFSINCL_ENV */
59 #endif  /* AFS_OSF_ENV */
60 #include <sys/errno.h>
61 #include <sys/stat.h>
62 #include <stdio.h>
63 #include <sys/file.h>
64 #ifdef  AFS_AIX_ENV
65 #include <sys/vfs.h>
66 #include <sys/lockf.h>
67 #else
68 #ifdef  AFS_HPUX_ENV
69 #include <sys/vfs.h>
70 #include <unistd.h>
71 #include <fcntl.h>
72 #include <checklist.h>
73 #else
74 #if     defined(AFS_SUN_ENV)
75 #include <sys/vfs.h>
76 #endif
77 #ifdef AFS_SUN5_ENV
78 #include <unistd.h>
79 #include <sys/mnttab.h>
80 #include <sys/mntent.h>
81 #else
82 #ifdef AFS_LINUX22_ENV
83 #include <mntent.h>
84 #include <sys/statfs.h>
85 #else
86 #include <fstab.h>
87 #endif
88 #endif
89 #endif
90 #endif
91 #endif  /* AFS_SGI_ENV */
92 #endif /* AFS_NT40_ENV */
93 #if defined(AFS_SGI_ENV)
94 #include <sys/errno.h>
95 #include <sys/stat.h>
96 #include <stdio.h>
97 #include <sys/file.h>
98 #include <mntent.h>
99 #endif
100
101 #include <rx/xdr.h>
102 #include <afs/afsint.h>
103 #include "nfs.h"
104 #include <afs/errors.h>
105 #include "lock.h"
106 #include "lwp.h"
107 #include <afs/afssyscalls.h>
108 #include "ihandle.h"
109 #ifdef AFS_NAMEI_ENV
110 #ifdef AFS_NT40_ENV
111 #include "ntops.h"
112 #else
113 #include "namei_ops.h"
114 #if defined(AFS_SGI_ENV)
115 #include <sys/dir.h>
116 #else
117 #include <dirent.h>
118 #endif /* AFS_SGI_ENV */
119 #endif /* AFS_NT40_ENV */
120 #endif /* AFS_NAMEI_ENV */
121 #include "vnode.h"
122 #include "volume.h"
123 #include "partition.h"
124 #ifdef AFS_PTHREAD_ENV
125 #include <assert.h>
126 #else /* AFS_PTHREAD_ENV */
127 #include <afs/assert.h>
128 #endif /* AFS_PTHREAD_ENV */
129
130 #if defined(AFS_HPUX_ENV)
131 #include <sys/types.h>
132 #include <sys/privgrp.h>
133 #endif /* defined(AFS_HPUX_ENV) */
134
135 #ifdef AFS_AIX42_ENV
136 #include <jfs/filsys.h>
137 #endif
138
139 int aixlow_water = 8;   /* default 8% */
140 struct DiskPartition *DiskPartitionList;
141
142 #ifdef AFS_SGI_XFS_IOPS_ENV
143 /* Verify that the on disk XFS inodes on the partition are large enough to
144  * hold the AFS attribute. Returns -1 if the attribute can't be set or is
145  * too small to fit in the inode. Returns 0 if the attribute does fit in
146  * the XFS inode.
147  */
148 #include <afs/xfsattrs.h>
149 static int VerifyXFSInodeSize(char *part, char *fstype)
150 {
151     afs_xfs_attr_t junk;
152     int length = SIZEOF_XFS_ATTR_T;
153     int fd = 0;
154     int code = -1;
155     struct fsxattr fsx;
156
157     if (strcmp("xfs", fstype))
158         return 0;
159
160     if (attr_set(part, AFS_XFS_ATTR, &junk, length, ATTR_ROOT) == 0) {
161         if (((fd=open(part, O_RDONLY, 0)) != -1)
162             && (fcntl(fd, F_FSGETXATTRA, &fsx) == 0)) {
163         
164             if (fsx.fsx_nextents) {
165                 Log("Partition %s: XFS inodes too small, exiting.\n", part);
166                 Log("Run xfs_size_check utility and remake partitions.\n");
167             }
168             else
169                 code = 0;
170         }
171
172         if (fd > 0)
173             close(fd);
174         (void) attr_remove(part, AFS_XFS_ATTR, ATTR_ROOT);
175     }
176     return code;
177 }
178 #endif
179
180
181 static void VInitPartition_r(char *path, char *devname, Device dev)
182 {
183     struct DiskPartition *dp, *op;
184     dp = (struct DiskPartition *) malloc(sizeof (struct DiskPartition));
185     /* Add it to the end, to preserve order when we print statistics */
186     for (op = DiskPartitionList; op; op = op->next) {
187         if (!op->next)
188             break;
189     }
190     if (op)
191         op->next = dp;
192     else
193         DiskPartitionList = dp;
194     dp->next = 0;
195     strcpy(dp->name, path);
196 #if defined(AFS_NAMEI_ENV) && !defined(AFS_NT40_ENV)
197 #ifdef AFS_SUN5_ENV
198     strcpy(dp->devName, devname);
199 #else /* AFS_SUN5_ENV */
200     strcpy(dp->devName, path);
201 #endif
202     dp->device = volutil_GetPartitionID(path);
203 #else
204     strcpy(dp->devName, devname);
205     dp->device = dev;
206 #endif
207     dp->lock_fd = -1;
208     dp->flags = 0;
209     dp->f_files = 1;    /* just a default value */
210 #if defined(AFS_NAMEI_ENV) && !defined(AFS_NT40_ENV)
211     if (programType == fileServer)
212         (void) namei_ViceREADME(VPartitionPath(dp));
213 #endif
214     VSetPartitionDiskUsage_r(dp);
215 }
216
217 static void VInitPartition(char *path, char *devname, Device dev)
218 {
219     VOL_LOCK
220     VInitPartition_r(path, devname, dev);
221     VOL_UNLOCK
222 }
223
224 #ifndef AFS_NT40_ENV
225 /* VAttachPartitions() finds the vice partitions on this server. Calls
226  * VCheckPartition() to do some basic checks on the partition. If the partition
227  * is a valid vice partition, VCheckPartition will add it to the DiskPartition
228  * list.
229  * Returns the number of errors returned by VCheckPartition. An error in
230  * VCheckPartition means that partition is a valid vice partition but the
231  * fileserver should not start because of the error found on that partition.
232  *
233  * AFS_NAMEI_ENV
234  * No specific user space file system checks, since we don't know what
235  * is being used for vice partitions.
236  *
237  * Use partition name as devname.
238  */
239 int VCheckPartition(part, devname)
240      char *part;
241      char *devname;
242 {
243     struct stat status;
244 #if !defined(AFS_LINUX20_ENV) && !defined(AFS_NT40_ENV)
245     char AFSIDatPath[MAXPATHLEN];
246 #endif
247
248     /* Only keep track of "/vicepx" partitions since it can get hairy
249      * when NFS mounts are involved.. */
250     if (strncmp(part, VICE_PARTITION_PREFIX, VICE_PREFIX_SIZE)) {
251         return 0;
252     }
253     if (stat(part, &status) < 0) {
254         Log("VInitVnodes: Couldn't find file system %s; ignored\n", part);
255         return 0;
256     }
257     
258 #ifndef AFS_AIX32_ENV
259     if (programType == fileServer) {
260         char salvpath[MAXPATHLEN];
261         strcpy(salvpath, part);
262         strcat(salvpath, "/FORCESALVAGE");
263         if (stat(salvpath, &status) == 0) {
264             Log("VInitVnodes: Found %s; aborting\n", salvpath);
265             return -1;
266         }
267     }
268 #endif
269
270 #if !defined(AFS_LINUX20_ENV) && !defined(AFS_NT40_ENV)
271     strcpy(AFSIDatPath, part);
272     strcat(AFSIDatPath, "/AFSIDat");
273 #ifdef AFS_NAMEI_ENV
274     if (stat(AFSIDatPath, &status) < 0) {
275         DIR *dirp;
276         struct dirent *dp;
277
278         dirp = opendir(part);
279         assert(dirp);
280         while (dp = readdir(dirp)) {
281             if (dp->d_name[0] == 'V') {
282                 Log("This program is compiled with AFS_NAMEI_ENV, but partition %s seems to contain volumes which don't use the namei-interface; aborting\n", part);
283                 closedir(dirp);
284                 return -1;
285             }
286         }
287         closedir(dirp);
288     }
289 #else /* AFS_NAMEI_ENV */
290     if (stat(AFSIDatPath, &status) == 0) {
291         Log("This program is compiled without AFS_NAMEI_ENV, but partition %s seems to contain volumes which use the namei-interface; aborting\n", part);
292         return -1;
293     }
294 #endif /* AFS_NAMEI_ENV */f
295 #endif
296
297 #ifdef AFS_SGI_XFS_IOPS_ENV
298     if (VerifyXFSInodeSize(part, status.st_fstype) < 0)
299         return -1;
300 #endif
301
302 #ifdef AFS_DUX40_ENV
303     if (status.st_ino != ROOTINO) {
304         Log("%s is not a mounted file system; ignored.\n", part);
305         return 0;
306     }
307 #endif
308
309     VInitPartition(part, devname, status.st_dev);
310
311     return 0;
312 }
313 #endif /* AFS_NT40_ENV */
314
315 #ifdef AFS_SUN5_ENV
316 int VAttachPartitions(void)
317 {
318     int errors = 0;
319     struct mnttab mnt;
320     FILE *mntfile;
321
322     if (!(mntfile = fopen(MNTTAB, "r"))) {
323         Log("Can't open %s\n", MNTTAB);
324         perror(MNTTAB);
325         exit(-1);
326     }
327     while (!getmntent(mntfile, &mnt)) {
328         /* Ignore non ufs or non read/write partitions */
329         if ((strcmp(mnt.mnt_fstype, "ufs") !=0) ||
330             (strncmp(mnt.mnt_mntopts, "ro,ignore",9) ==0)) 
331             continue; 
332
333         if (VCheckPartition(mnt.mnt_mountp, mnt.mnt_special) < 0 )
334             errors ++;
335     }
336
337    (void) fclose(mntfile);
338
339     return errors ;
340 }
341
342 #endif /* AFS_SUN5_ENV */
343 #if defined(AFS_SGI_ENV) || (defined(AFS_SUN_ENV) && !defined(AFS_SUN5_ENV)) || defined(AFS_HPUX_ENV)
344 int VAttachPartitions(void)
345 {
346     int errors = 0;
347     FILE *mfd;
348     struct mntent *mntent;
349     
350     if ((mfd = setmntent(MOUNTED, "r")) == NULL) {
351         Log("Problems in getting mount entries(setmntent)\n");
352         exit(-1);
353     }
354     while (mntent = getmntent(mfd)) {
355         if (!hasmntopt(mntent, MNTOPT_RW)) continue;
356         
357         if (VCheckPartition(mntent->mnt_dir, mntent->mnt_fsname) < 0 )
358             errors ++;
359     }
360
361     endmntent(mfd);
362
363     return errors ;
364 }
365 #endif
366 #ifdef AFS_AIX_ENV
367 /*
368  * (This function was grabbed from df.c)
369  */
370 int
371 getmount(vmountpp)
372 register struct vmount  **vmountpp;     /* place to tell where buffer is */
373 {
374         int                     size;
375         register struct vmount  *vm;
376         int                     nmounts;
377
378         /* set initial size of mntctl buffer to a MAGIC NUMBER */
379         size = BUFSIZ;
380
381         /* try the operation until ok or a fatal error */
382         while (1) {
383                 if ((vm = (struct vmount *)malloc(size)) == NULL) {
384                         /* failed getting memory for mount status buf */
385                         perror("FATAL ERROR: get_stat malloc failed\n");
386                         exit(-1);
387                 }
388
389                 /*
390                  * perform the QUERY mntctl - if it returns > 0, that is the
391                  * number of vmount structures in the buffer.  If it returns
392                  * -1, an error occured.  If it returned 0, then look in
393                  * first word of buffer for needed size.
394                  */
395                 if ((nmounts = mntctl(MCTL_QUERY, size, (caddr_t)vm)) > 0) {
396                         /* OK, got it, now return */
397                         *vmountpp = vm;
398                         return(nmounts);
399
400                 } else if (nmounts == 0) {
401                         /* the buffer wasn't big enough .... */
402                         /* .... get required buffer size */
403                         size = *(int *)vm;
404                         free(vm);
405
406                 } else {
407                         /* some other kind of error occurred */
408                         free(vm);
409                         return(-1);
410                 }
411         }
412 }
413
414 int VAttachPartitions(void)
415 {
416     int errors = 0;
417     int nmounts;
418     struct vmount *vmountp;
419
420     if ((nmounts = getmount(&vmountp)) <= 0)    {   
421         Log("Problems in getting # of mount entries(getmount)\n");
422         exit(-1);
423     }
424     for (; nmounts; nmounts--,
425          vmountp = (struct vmount *)((int)vmountp + vmountp->vmt_length)) {
426         char *part = vmt2dataptr(vmountp, VMT_STUB);
427
428         if (vmountp->vmt_flags & (MNT_READONLY|MNT_REMOVABLE|MNT_REMOTE))
429             continue; /* Ignore any "special" partitions */
430
431 #ifdef AFS_AIX42_ENV
432         {
433             struct superblock fs;
434             /* The Log statements are non-sequiters in the SalvageLog and don't
435              * even appear in the VolserLog, so restrict them to the FileLog.
436              */
437             if (ReadSuper(&fs, vmt2dataptr(vmountp, VMT_OBJECT))<0) {
438                 if (programType == fileServer)
439                     Log("Can't read superblock for %s, ignoring it.\n", part);
440                 continue;
441             }
442             if (IsBigFilesFileSystem(&fs)) {
443                 if (programType == fileServer)
444                     Log("%s is a big files filesystem, ignoring it.\n", part);
445                 continue;
446             }
447         }
448 #endif
449
450         if (VCheckPartition(part, vmt2dataptr(vmountp, VMT_OBJECT)) < 0 )
451             errors ++;
452     }
453     return errors ;
454
455 }
456 #endif
457 #if defined(AFS_DUX40_ENV) || defined(AFS_DARWIN_ENV) || defined(AFS_FBSD_ENV)
458 int VAttachPartitions(void)
459 {
460     int errors = 0;
461     struct fstab *fsent;
462
463     if (setfsent() < 0) {
464         Log("Error listing filesystems.\n");
465         exit(-1);
466     }
467
468     while (fsent = getfsent()) {
469         if (strcmp(fsent->fs_type, "rw") != 0) continue;
470
471         if (VCheckPartition(fsent->fs_file, fsent->fs_spec) < 0 )
472             errors ++;
473     }
474     endfsent();
475     
476     return errors ;
477 }
478 #endif
479
480 #ifdef AFS_NT40_ENV
481 #include <string.h>
482 #include <sys/stat.h>
483 /* VValidVPTEntry
484  *
485  * validate names in vptab.
486  *
487  * Return value:
488  * 1 valid entry
489  * 0 invalid entry
490  */
491
492 int VValidVPTEntry(struct vptab *vpe)
493 {
494     int len = strlen(vpe->vp_name);
495     int i;
496
497     if (len < VICE_PREFIX_SIZE+1 || len > VICE_PREFIX_SIZE + 2)
498         return 0;
499     if (strncmp(vpe->vp_name, VICE_PARTITION_PREFIX, VICE_PREFIX_SIZE))
500         return 0;
501     
502     for (i=VICE_PREFIX_SIZE; i<len; i++) {
503         if (vpe->vp_name[i] < 'a' || vpe->vp_name[i] > 'z') {
504             Log("Invalid partition name %s in registry, ignoring it.\n",
505                 vpe->vp_name);
506             return 0;
507         }
508     }
509     if (len == VICE_PREFIX_SIZE + 2) {
510         i = (int)(vpe->vp_name[VICE_PREFIX_SIZE]-'a') * 26 +
511             (int)(vpe->vp_name[VICE_PREFIX_SIZE+1]-'a') ;
512         if (i>255) {
513             Log("Invalid partition name %s in registry, ignoring it.\n",
514                 vpe->vp_name);
515             return 0;
516         }
517     }
518
519     len = strlen(vpe->vp_dev);
520     if (len != 2 || vpe->vp_dev[1] != ':'  || vpe->vp_dev[0] < 'A' ||
521         vpe->vp_dev[0] > 'Z') {
522         Log("Invalid device name %s in registry, ignoring it.\n",
523             vpe->vp_dev);
524         return 0;
525     }
526
527     return 1;
528 }
529
530 int VCheckPartition(char *partName)
531 {
532     char volRoot[4];
533     char volFsType[64];
534     DWORD dwDummy;
535     int err;
536
537     /* partName is presumed to be of the form "X:" */
538     (void) sprintf(volRoot, "%c:\\", *partName);
539
540     if (!GetVolumeInformation(volRoot,    /* volume root directory */
541                               NULL,       /* volume name buffer */
542                               0,          /* volume name size */
543                               NULL,       /* volume serial number */
544                               &dwDummy,   /* max component length */
545                               &dwDummy,   /* file system flags */
546                               volFsType,  /* file system name */
547                               sizeof(volFsType))) {
548         err = GetLastError();
549         Log("VCheckPartition: Failed to get partition information for %s, ignoring it.\n",
550             partName);
551         return -1;
552     }
553
554     if (strcmp(volFsType, "NTFS")) {
555         Log("VCheckPartition: Partition %s is not an NTFS partition, ignoring it.\n", partName);
556         return -1;
557     }
558
559     return 0;
560 }
561
562
563 int VAttachPartitions(void)
564 {
565     struct DiskPartition *partP, *prevP, *nextP;
566     struct vpt_iter iter;
567     struct vptab entry;
568
569     if (vpt_Start(&iter)<0) {
570         Log("No partitions to attach.\n");
571         return 0;
572     }
573
574     while (0==vpt_NextEntry(&iter, &entry)) {
575         if (!VValidVPTEntry(&entry)) {
576             continue;
577         }
578
579         /* This test for duplicates relies on the fact that the method
580          * of storing the partition names in the NT registry means the same
581          * partition name will never appear twice in the list.
582          */
583         for (partP = DiskPartitionList; partP; partP = partP->next) {
584             if (*partP->devName == *entry.vp_dev) {
585                 Log("Same drive (%s) used for both partition %s and partition %s, ignoring both.\n", entry.vp_dev, partP->name, entry.vp_name);
586                 partP->flags = PART_DUPLICATE;
587                 break; /* Only one entry will ever be in this list. */
588             }
589         }
590         if (partP) continue; /* found a duplicate */
591
592         if (VCheckPartition(entry.vp_dev)<0)
593             continue;
594         /* This test allows for manually inserting the FORCESALVAGE flag
595          * and thereby invoking the salvager. scandisk obviously won't be
596          * doing this for us.
597          */
598         if (programType == fileServer) {
599             struct stat status;
600             char salvpath[MAXPATHLEN];
601             strcpy(salvpath, entry.vp_dev);
602             strcat(salvpath, "\\FORCESALVAGE");
603             if (stat(salvpath, &status) == 0) {
604                 Log("VAttachPartitions: Found %s; aborting\n", salvpath);
605                 exit(1);
606             }
607         }
608         VInitPartition(entry.vp_name, entry.vp_dev, *entry.vp_dev - 'A');
609     }
610     vpt_Finish(&iter);
611
612     /* Run through partition list and clear out the dupes. */
613     prevP = nextP = NULL;
614     for (partP = DiskPartitionList; partP; partP = nextP) {
615         nextP = partP->next;
616         if (partP->flags == PART_DUPLICATE) {
617             if (prevP)
618                 prevP->next = partP->next;
619             else
620                 DiskPartitionList = partP->next;
621             free(partP);
622         }
623         else
624             prevP = partP;
625     }
626
627     return 0;
628 }
629 #endif
630
631 #ifdef AFS_LINUX22_ENV
632 int VAttachPartitions(void)
633 {
634     int errors = 0;
635     FILE *mfd;
636     struct mntent *mntent;
637     
638     if ((mfd = setmntent("/proc/mounts", "r")) == NULL) {
639         if ((mfd = setmntent("/etc/mtab", "r")) == NULL) {
640             Log("Problems in getting mount entries(setmntent)\n");
641             exit(-1);
642         }
643     }
644     while (mntent = getmntent(mfd)) {
645         if (VCheckPartition(mntent->mnt_dir, mntent->mnt_fsname) < 0 )
646             errors ++;
647     }
648     endmntent(mfd);
649
650     return errors ;
651 }
652 #endif /* AFS_LINUX22_ENV */
653
654 /* This routine is to be called whenever the actual name of the partition
655  * is required. The canonical name is still in part->name.
656  */
657 char * VPartitionPath(struct DiskPartition *part)
658 {
659 #ifdef AFS_NT40_ENV
660     return part->devName;
661 #else
662     return part->name;
663 #endif    
664 }
665
666 /* get partition structure, abortp tells us if we should abort on failure */
667 struct DiskPartition *VGetPartition_r(char *name, int abortp)
668 {
669     register struct DiskPartition *dp;
670     for (dp = DiskPartitionList; dp; dp = dp->next) {
671         if (strcmp(dp->name, name) == 0)
672             break;
673     }
674     if (abortp)
675         assert(dp != NULL);
676     return dp;
677 }
678
679 struct DiskPartition *VGetPartition(char *name, int abortp)
680 {
681     struct DiskPartition *retVal;
682     VOL_LOCK
683     retVal = VGetPartition_r(name, abortp);
684     VOL_UNLOCK
685     return retVal;
686 }
687
688 #ifdef AFS_NT40_ENV
689 void VSetPartitionDiskUsage_r(register struct DiskPartition *dp)
690 {
691     ULARGE_INTEGER free_user, total, free_total;
692     int ufree, tot, tfree;
693     
694     if (!GetDiskFreeSpaceEx(VPartitionPath(dp), &free_user, &total,
695                             &free_total)) {
696         printf("Failed to get disk space info for %s, error = %d\n",
697                dp->name, GetLastError());
698         return;
699     }
700
701     /* Convert to 1K units. */
702     ufree = (int) Int64ShraMod32(free_user.QuadPart, 10);
703     tot = (int) Int64ShraMod32(total.QuadPart, 10);
704     tfree = (int) Int64ShraMod32(free_total.QuadPart, 10);
705
706     dp->minFree = tfree - ufree; /* only used in VPrintDiskStats_r */
707     dp->totalUsable = tot;
708     dp->free = tfree;
709 }
710
711 #else
712 void VSetPartitionDiskUsage_r(register struct DiskPartition *dp)
713 {
714     extern int errno;
715     int fd, totalblks, free, used, availblks, bsize, code;
716     int reserved;
717 #if AFS_HAVE_STATVFS
718     struct statvfs statbuf;
719 #else
720     struct statfs statbuf;
721 #endif
722
723     if (dp->flags & PART_DONTUPDATE)
724         return;
725     /* Note:  we don't bother syncing because it's only an estimate, update
726        is syncing every 30 seconds anyway, we only have to keep the disk
727        approximately 10% from full--you just can't get the stuff in from
728        the net fast enough to worry */
729 #if AFS_HAVE_STATVFS
730     code = statvfs(dp->name, &statbuf);
731 #else
732     code = statfs(dp->name, &statbuf);
733 #endif
734     if (code < 0) {
735         Log("statfs of %s failed in VSetPartitionDiskUsage (errno = %d)\n", dp->name, errno);
736         return;
737     }
738     if (statbuf.f_blocks == -1) {   /* Undefined; skip stats.. */   
739         Log("statfs of %s failed in VSetPartitionDiskUsage\n", dp->name);
740         return;
741     }
742     totalblks = statbuf.f_blocks;
743     free = statbuf.f_bfree;
744     reserved = free - statbuf.f_bavail;
745 #if AFS_HAVE_STATVFS
746     bsize = statbuf.f_frsize;
747 #else
748     bsize = statbuf.f_bsize;
749 #endif
750     availblks = totalblks - reserved;
751     dp->f_files = statbuf.f_files;      /* max # of files in partition */
752
753     /* Now free and totalblks are in fragment units, but we want them in
754      * 1K units.
755      */
756     if (bsize >= 1024) {
757         free *= (bsize/1024);
758         totalblks *= (bsize / 1024);
759         availblks *= (bsize / 1024 );
760         reserved *= (bsize / 1024 );
761     }
762     else {
763         free /= (1024/bsize);
764         totalblks /= (1024/bsize);
765         availblks /= (1024/bsize);
766         reserved /= (1024/bsize);
767     }
768     /* now compute remaining figures */
769     used = totalblks - free;
770
771     dp->minFree = reserved; /* only used in VPrintDiskStats_r */
772     dp->totalUsable = availblks;
773     dp->free = availblks - used; /* this is exactly f_bavail */
774 }
775 #endif /* AFS_NT40_ENV */
776
777 void VSetPartitionDiskUsage(register struct DiskPartition *dp)
778 {
779     VOL_LOCK
780     VSetPartitionDiskUsage_r(dp);
781     VOL_UNLOCK
782 }
783
784 void VResetDiskUsage_r(void)
785 {
786     struct DiskPartition *dp;
787     for (dp = DiskPartitionList; dp; dp = dp->next) {
788         VSetPartitionDiskUsage_r(dp);
789 #ifndef AFS_PTHREAD_ENV
790         IOMGR_Poll();
791 #endif /* !AFS_PTHREAD_ENV */
792     }
793 }
794
795 void VResetDiskUsage(void)
796 {
797     VOL_LOCK
798     VResetDiskUsage_r();
799     VOL_UNLOCK
800 }
801
802 void VAdjustDiskUsage_r(Error *ec, Volume *vp, afs_int32 blocks, afs_int32 checkBlocks)
803 {
804     afs_int32 rem, minavail;
805     *ec = 0;
806     /* why blocks instead of checkBlocks in the check below?  Otherwise, any check
807        for less than BlocksSpare would skip the error-checking path, and we
808        could grow existing files forever, not just for another BlocksSpare
809        blocks. */
810     if (blocks > 0) {
811 #ifdef  AFS_AIX32_ENV
812         if ((rem = vp->partition->free - checkBlocks) < 
813             (minavail = (vp->partition->totalUsable * aixlow_water) / 100))
814 #else
815         if (vp->partition->free - checkBlocks < 0)
816 #endif
817             *ec = VDISKFULL;
818         else if (V_maxquota(vp) && V_diskused(vp) + checkBlocks > V_maxquota(vp))
819             *ec = VOVERQUOTA;
820     }    
821     vp->partition->free -= blocks;
822     V_diskused(vp) += blocks;
823 }
824
825 void VAdjustDiskUsage(Error *ec, Volume *vp, afs_int32 blocks, afs_int32 checkBlocks)
826 {
827     VOL_LOCK
828     VAdjustDiskUsage_r(ec, vp, blocks, checkBlocks);
829     VOL_UNLOCK
830 }
831
832 int VDiskUsage_r(Volume *vp, afs_int32 blocks)
833 {
834     afs_int32 rem, minavail;
835     if (blocks > 0) {
836 #ifdef  AFS_AIX32_ENV
837         if ((rem = vp->partition->free - blocks) < 
838             (minavail = (vp->partition->totalUsable * aixlow_water) / 100))
839 #else
840         if (vp->partition->free - blocks < 0)
841 #endif
842             return(VDISKFULL);
843     }    
844     vp->partition->free -= blocks;
845     return 0;
846 }
847
848 int VDiskUsage(Volume *vp, afs_int32 blocks)
849 {
850     int retVal;
851     VOL_LOCK
852     retVal = VDiskUsage_r(vp, blocks);
853     VOL_UNLOCK
854     return retVal;
855 }
856
857 void VPrintDiskStats_r(void)
858 {
859     struct DiskPartition *dp;
860     for (dp = DiskPartitionList; dp; dp = dp->next) {
861         Log("Partition %s: %d available 1K blocks (minfree=%d), ",
862             dp->name, dp->totalUsable, dp->minFree);
863         if (dp->free < 0)
864             Log("overallocated by %d blocks\n", -dp->free);
865         else
866             Log("%d free blocks\n", dp->free);
867     }
868 }
869
870 void VPrintDiskStats(void)
871 {
872     VOL_LOCK
873     VPrintDiskStats_r();
874     VOL_UNLOCK
875 }
876
877 #ifdef AFS_NT40_ENV
878 /* Need a separate lock file on NT, since NT only has mandatory file locks. */
879 #define LOCKFILE "LOCKFILE"
880 void VLockPartition_r(char *name)
881 {
882     struct DiskPartition *dp = VGetPartition_r(name, 0);
883     OVERLAPPED lap;
884     
885     if (!dp) return;
886     if (dp->lock_fd == -1) {
887         char path[64];
888         int rc;
889         (void) sprintf(path, "%s\\%s", VPartitionPath(dp), LOCKFILE);
890         dp->lock_fd = (int)CreateFile(path, GENERIC_WRITE,
891                                  FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
892                                  CREATE_ALWAYS, FILE_ATTRIBUTE_HIDDEN, NULL);
893         assert (dp->lock_fd != (int)INVALID_HANDLE_VALUE);
894
895         memset((char*)&lap, 0, sizeof(lap));
896         rc = LockFileEx((HANDLE)dp->lock_fd, LOCKFILE_EXCLUSIVE_LOCK,
897                         0, 1, 0, &lap);
898         assert(rc);
899     }
900 }
901
902 void VUnlockPartition_r(char *name)
903 {
904     register struct DiskPartition *dp = VGetPartition_r(name, 0);
905     OVERLAPPED lap;
906
907     if (!dp) return;    /* no partition, will fail later */
908     memset((char*)&lap, 0, sizeof(lap));
909
910     UnlockFileEx((HANDLE)dp->lock_fd, 0, 1, 0, &lap);
911     CloseHandle((HANDLE)dp->lock_fd);
912     dp->lock_fd = -1;
913 }
914 #else /* AFS_NT40_ENV */
915
916 #if defined(AFS_HPUX_ENV)
917 #define BITS_PER_CHAR   (8)
918 #define BITS(type)      (sizeof(type) * BITS_PER_CHAR)
919
920 #define LOCKRDONLY_OFFSET       ((PRIV_LOCKRDONLY - 1) / BITS(int))
921 #endif /* defined(AFS_HPUX_ENV) */
922
923 void VLockPartition_r(char *name)
924 {
925     register struct DiskPartition *dp = VGetPartition_r(name, 0);
926     char *partitionName;
927     int retries, code;
928     struct timeval pausing;
929 #if defined(AFS_HPUX_ENV)
930     int                 lockfRtn;
931     struct privgrp_map  privGrpList[PRIV_MAXGRPS];
932     unsigned int        *globalMask;
933     int                 globalMaskIndex;
934 #endif /* defined(AFS_HPUX_ENV) */
935     
936     if (!dp) return;    /* no partition, will fail later */
937     if (dp->lock_fd != -1) return;
938
939 #if    defined(AFS_SUN5_ENV) || defined(AFS_AIX41_ENV)
940     partitionName = dp->devName;
941     code = O_RDWR;
942 #else
943     partitionName = dp->name;
944     code = O_RDONLY;
945 #endif
946
947     for (retries=25; retries; retries--) {
948         dp->lock_fd = open(partitionName, code);
949         if (dp->lock_fd != -1) break;
950         pausing.tv_sec = 0;
951         pausing.tv_usec = 500000;
952         select(0, NULL, NULL, NULL, &pausing);
953     }
954     assert(retries != 0);
955
956 #if defined (AFS_HPUX_ENV)
957
958         assert(getprivgrp(privGrpList) == 0);
959
960         /*
961          * In general, it will difficult and time-consuming ,if not impossible,
962          * to try to find the privgroup to which this process belongs that has the
963          * smallest membership, to minimise the security hole.  So, we use the privgrp
964          * to which everybody belongs.
965          */
966         /* first, we have to find the global mask */
967         for (globalMaskIndex = 0; globalMaskIndex < PRIV_MAXGRPS;
968              globalMaskIndex++) {
969           if (privGrpList[globalMaskIndex].priv_groupno == PRIV_GLOBAL) {
970             globalMask = &(privGrpList[globalMaskIndex].
971                            priv_mask[LOCKRDONLY_OFFSET]);
972             break;
973           }
974         }
975
976         if (((*globalMask) & privmask(PRIV_LOCKRDONLY)) == 0) {
977           /* allow everybody to set a lock on a read-only file descriptor */
978           (*globalMask) |= privmask(PRIV_LOCKRDONLY);
979           assert(setprivgrp(PRIV_GLOBAL,
980                             privGrpList[globalMaskIndex].priv_mask) == 0);
981
982           lockfRtn = lockf(dp->lock_fd, F_LOCK, 0);
983
984           /* remove the privilege granted to everybody to lock a read-only fd */
985           (*globalMask) &= ~(privmask(PRIV_LOCKRDONLY));
986           assert(setprivgrp(PRIV_GLOBAL,
987                             privGrpList[globalMaskIndex].priv_mask) == 0);
988         }
989         else {
990           /* in this case, we should be able to do this with impunity, anyway */
991           lockfRtn = lockf(dp->lock_fd, F_LOCK, 0);
992         }
993         
994         assert (lockfRtn != -1); 
995 #else
996 #if defined(AFS_AIX_ENV) || defined(AFS_SUN5_ENV)
997         assert (lockf(dp->lock_fd, F_LOCK, 0) != -1); 
998 #else
999         assert (flock(dp->lock_fd, LOCK_EX) == 0);
1000 #endif  /* defined(AFS_AIX_ENV) */
1001 #endif
1002 }
1003
1004 void VUnlockPartition_r(char *name)
1005 {
1006     register struct DiskPartition *dp = VGetPartition_r(name, 0);
1007     if (!dp) return;    /* no partition, will fail later */
1008     close(dp->lock_fd);
1009     dp->lock_fd = -1;
1010 }
1011
1012 #endif /* AFS_NT40_ENV */
1013
1014 void VLockPartition(char *name)
1015 {
1016     VOL_LOCK
1017     VLockPartition_r(name);
1018     VOL_UNLOCK
1019 }
1020
1021 void VUnlockPartition(char *name)
1022 {
1023     VOL_LOCK
1024     VUnlockPartition_r(name);
1025     VOL_UNLOCK
1026 }