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