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