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