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