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