pull-prototypes-to-head-20020821
[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 #ifdef HAVE_STRING_H
104 #include <string.h>
105 #else
106 #ifdef HAVE_STRINGS_H
107 #include <strings.h>
108 #endif
109 #endif
110
111
112 #include <rx/xdr.h>
113 #include <afs/afsint.h>
114 #include "nfs.h"
115 #include <afs/errors.h>
116 #include "lock.h"
117 #include "lwp.h"
118 #include <afs/afssyscalls.h>
119 #include "ihandle.h"
120 #ifdef AFS_NAMEI_ENV
121 #ifdef AFS_NT40_ENV
122 #include "ntops.h"
123 #else
124 #include "namei_ops.h"
125 #include <dirent.h>
126 #endif /* AFS_NT40_ENV */
127 #endif /* AFS_NAMEI_ENV */
128 #include "vnode.h"
129 #include "volume.h"
130 #include "partition.h"
131 #ifdef AFS_PTHREAD_ENV
132 #include <assert.h>
133 #else /* AFS_PTHREAD_ENV */
134 #include <afs/assert.h>
135 #endif /* AFS_PTHREAD_ENV */
136
137 #if defined(AFS_HPUX_ENV)
138 #include <sys/types.h>
139 #include <sys/privgrp.h>
140 #endif /* defined(AFS_HPUX_ENV) */
141
142 #ifdef AFS_AIX42_ENV
143 #include <jfs/filsys.h>
144 #endif
145
146 int aixlow_water = 8;   /* default 8% */
147 struct DiskPartition *DiskPartitionList;
148
149 #ifdef AFS_SGI_XFS_IOPS_ENV
150 /* Verify that the on disk XFS inodes on the partition are large enough to
151  * hold the AFS attribute. Returns -1 if the attribute can't be set or is
152  * too small to fit in the inode. Returns 0 if the attribute does fit in
153  * the XFS inode.
154  */
155 #include <afs/xfsattrs.h>
156 static int VerifyXFSInodeSize(char *part, char *fstype)
157 {
158     afs_xfs_attr_t junk;
159     int length = SIZEOF_XFS_ATTR_T;
160     int fd = 0;
161     int code = -1;
162     struct fsxattr fsx;
163
164     if (strcmp("xfs", fstype))
165         return 0;
166
167     if (attr_set(part, AFS_XFS_ATTR, &junk, length, ATTR_ROOT) == 0) {
168         if (((fd=open(part, O_RDONLY, 0)) != -1)
169             && (fcntl(fd, F_FSGETXATTRA, &fsx) == 0)) {
170         
171             if (fsx.fsx_nextents) {
172                 Log("Partition %s: XFS inodes too small, exiting.\n", part);
173                 Log("Run xfs_size_check utility and remake partitions.\n");
174             }
175             else
176                 code = 0;
177         }
178
179         if (fd > 0)
180             close(fd);
181         (void) attr_remove(part, AFS_XFS_ATTR, ATTR_ROOT);
182     }
183     return code;
184 }
185 #endif
186
187
188 static void VInitPartition_r(char *path, char *devname, Device dev)
189 {
190     struct DiskPartition *dp, *op;
191     dp = (struct DiskPartition *) malloc(sizeof (struct DiskPartition));
192     /* Add it to the end, to preserve order when we print statistics */
193     for (op = DiskPartitionList; op; op = op->next) {
194         if (!op->next)
195             break;
196     }
197     if (op)
198         op->next = dp;
199     else
200         DiskPartitionList = dp;
201     dp->next = 0;
202     dp->name = (char *)malloc(strlen(path) + 1);
203     strncpy(dp->name, path, strlen(path) + 1);
204 #if defined(AFS_NAMEI_ENV) && !defined(AFS_NT40_ENV)
205     /* Create a lockfile for the partition, of the form /vicepa/Lock/vicepa */
206     dp->devName = (char *)malloc(2 * strlen(path) + 6);
207     strcpy(dp->devName, path);
208     strcat(dp->devName, "/");
209     strcat(dp->devName, "Lock");
210     mkdir(dp->devName, 0700);
211     strcat(dp->devName, path);
212     close(open(dp->devName, O_RDWR | O_CREAT, 0600));
213     dp->device = volutil_GetPartitionID(path);
214 #else
215     dp->devName = (char *)malloc(strlen(devname) + 1);
216     strncpy(dp->devName, devname, strlen(devname) + 1);
217     dp->device = dev;
218 #endif
219     dp->lock_fd = -1;
220     dp->flags = 0;
221     dp->f_files = 1;    /* just a default value */
222 #if defined(AFS_NAMEI_ENV) && !defined(AFS_NT40_ENV)
223     if (programType == fileServer)
224         (void) namei_ViceREADME(VPartitionPath(dp));
225 #endif
226     VSetPartitionDiskUsage_r(dp);
227 }
228
229 static void VInitPartition(char *path, char *devname, Device dev)
230 {
231     VOL_LOCK
232     VInitPartition_r(path, devname, dev);
233     VOL_UNLOCK
234 }
235
236 #ifndef AFS_NT40_ENV
237 /* VAttachPartitions() finds the vice partitions on this server. Calls
238  * VCheckPartition() to do some basic checks on the partition. If the partition
239  * is a valid vice partition, VCheckPartition will add it to the DiskPartition
240  * list.
241  * Returns the number of errors returned by VCheckPartition. An error in
242  * VCheckPartition means that partition is a valid vice partition but the
243  * fileserver should not start because of the error found on that partition.
244  *
245  * AFS_NAMEI_ENV
246  * No specific user space file system checks, since we don't know what
247  * is being used for vice partitions.
248  *
249  * Use partition name as devname.
250  */
251 int VCheckPartition(part, devname)
252      char *part;
253      char *devname;
254 {
255     struct stat status;
256 #if !defined(AFS_LINUX20_ENV) && !defined(AFS_NT40_ENV)
257     char AFSIDatPath[MAXPATHLEN];
258 #endif
259
260     /* Only keep track of "/vicepx" partitions since it can get hairy
261      * when NFS mounts are involved.. */
262     if (strncmp(part, VICE_PARTITION_PREFIX, VICE_PREFIX_SIZE)) {
263         return 0;
264     }
265     if (stat(part, &status) < 0) {
266         Log("VInitVnodes: Couldn't find file system %s; ignored\n", part);
267         return 0;
268     }
269     
270 #ifndef AFS_AIX32_ENV
271     if (programType == fileServer) {
272         char salvpath[MAXPATHLEN];
273         strcpy(salvpath, part);
274         strcat(salvpath, "/FORCESALVAGE");
275         if (stat(salvpath, &status) == 0) {
276             Log("VInitVnodes: Found %s; aborting\n", salvpath);
277             return -1;
278         }
279     }
280 #endif
281
282 #if !defined(AFS_LINUX20_ENV) && !defined(AFS_NT40_ENV)
283     strcpy(AFSIDatPath, part);
284     strcat(AFSIDatPath, "/AFSIDat");
285 #ifdef AFS_NAMEI_ENV
286     if (stat(AFSIDatPath, &status) < 0) {
287         DIR *dirp;
288         struct dirent *dp;
289
290         dirp = opendir(part);
291         assert(dirp);
292         while (dp = readdir(dirp)) {
293             if (dp->d_name[0] == 'V') {
294                 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);
295                 closedir(dirp);
296                 return -1;
297             }
298         }
299         closedir(dirp);
300     }
301 #else /* AFS_NAMEI_ENV */
302     if (stat(AFSIDatPath, &status) == 0) {
303         Log("This program is compiled without AFS_NAMEI_ENV, but partition %s seems to contain volumes which use the namei-interface; aborting\n", part);
304         return -1;
305     }
306 #endif /* AFS_NAMEI_ENV */
307 #endif
308
309 #ifdef AFS_SGI_XFS_IOPS_ENV
310     if (VerifyXFSInodeSize(part, status.st_fstype) < 0)
311         return -1;
312 #endif
313
314 #if defined(AFS_DUX40_ENV) && !defined(AFS_NAMEI_ENV)
315     if (status.st_ino != ROOTINO) {
316         Log("%s is not a mounted file system; ignored.\n", part);
317         return 0;
318     }
319 #endif
320
321     VInitPartition(part, devname, status.st_dev);
322
323     return 0;
324 }
325
326 /* VIsAlwaysAttach() checks whether a /vicepX directory should always be
327  * attached (return value 1), or only attached when it is a separately
328  * mounted partition (return value 0).  For non-NAMEI environments, it
329  * always returns 0.
330  */
331 static int VIsAlwaysAttach(part)
332     char *part;
333 {
334 #ifdef AFS_NAMEI_ENV
335     struct stat st;
336     char checkfile[256];
337     int ret;
338
339     if (strncmp(part, VICE_PARTITION_PREFIX, VICE_PREFIX_SIZE))
340         return 0;
341
342     strncpy(checkfile, part, 100);
343     strcat(checkfile, "/");
344     strcat(checkfile, VICE_ALWAYSATTACH_FILE);
345
346     ret = stat(checkfile, &st);
347     return (ret < 0) ? 0 : 1;
348 #else  /* AFS_NAMEI_ENV */
349     return 0;
350 #endif /* AFS_NAMEI_ENV */
351 }
352
353 /* VAttachPartitions2() looks for and attaches /vicepX partitions
354  * where a special file (VICE_ALWAYSATTACH_FILE) exists.  This is
355  * used to attach /vicepX directories which aren't on dedicated
356  * partitions, in the NAMEI fileserver.
357  */
358 void VAttachPartitions2() {
359 #ifdef AFS_NAMEI_ENV
360     DIR *dirp;
361     struct dirent *de;
362     char pname[32];
363
364     dirp = opendir("/");
365     while ((de = readdir(dirp))) {
366         strcpy(pname, "/");
367         strncat(pname, de->d_name, 20);
368         pname[sizeof(pname)-1] = '\0';
369
370         /* Only keep track of "/vicepx" partitions since automounter
371            may hose us */
372         if (VIsAlwaysAttach(pname))
373             VCheckPartition(pname, "");
374     }
375     closedir(dirp);
376 #endif /* AFS_NAMEI_ENV */
377 }
378 #endif /* AFS_NT40_ENV */
379
380 #ifdef AFS_SUN5_ENV
381 int VAttachPartitions(void)
382 {
383     int errors = 0;
384     struct mnttab mnt;
385     FILE *mntfile;
386
387     if (!(mntfile = fopen(MNTTAB, "r"))) {
388         Log("Can't open %s\n", MNTTAB);
389         perror(MNTTAB);
390         exit(-1);
391     }
392     while (!getmntent(mntfile, &mnt)) {
393         /* Ignore non ufs or non read/write partitions */
394         if ((strcmp(mnt.mnt_fstype, "ufs") !=0) ||
395             (strncmp(mnt.mnt_mntopts, "ro,ignore",9) ==0)) 
396             continue; 
397
398         /* If we're going to always attach this partition, do it later. */
399         if (VIsAlwaysAttach(mnt.mnt_mountp))
400             continue;
401
402         if (VCheckPartition(mnt.mnt_mountp, mnt.mnt_special) < 0 )
403             errors ++;
404     }
405
406     (void) fclose(mntfile);
407
408     /* Process the always-attach partitions, if any. */
409     VAttachPartitions2();
410
411     return errors ;
412 }
413
414 #endif /* AFS_SUN5_ENV */
415 #if defined(AFS_SGI_ENV) || (defined(AFS_SUN_ENV) && !defined(AFS_SUN5_ENV)) || defined(AFS_HPUX_ENV)
416 int VAttachPartitions(void)
417 {
418     int errors = 0;
419     FILE *mfd;
420     struct mntent *mntent;
421     
422     if ((mfd = setmntent(MOUNTED, "r")) == NULL) {
423         Log("Problems in getting mount entries(setmntent)\n");
424         exit(-1);
425     }
426     while (mntent = getmntent(mfd)) {
427         if (!hasmntopt(mntent, MNTOPT_RW)) continue;
428         
429         /* If we're going to always attach this partition, do it later. */
430         if (VIsAlwaysAttach(mntent->mnt_dir))
431             continue;
432
433         if (VCheckPartition(mntent->mnt_dir, mntent->mnt_fsname) < 0 )
434             errors ++;
435     }
436
437     endmntent(mfd);
438
439     /* Process the always-attach partitions, if any. */
440     VAttachPartitions2();
441
442     return errors ;
443 }
444 #endif
445 #ifdef AFS_AIX_ENV
446 /*
447  * (This function was grabbed from df.c)
448  */
449 int
450 getmount(vmountpp)
451 register struct vmount  **vmountpp;     /* place to tell where buffer is */
452 {
453         int                     size;
454         register struct vmount  *vm;
455         int                     nmounts;
456
457         /* set initial size of mntctl buffer to a MAGIC NUMBER */
458         size = BUFSIZ;
459
460         /* try the operation until ok or a fatal error */
461         while (1) {
462                 if ((vm = (struct vmount *)malloc(size)) == NULL) {
463                         /* failed getting memory for mount status buf */
464                         perror("FATAL ERROR: get_stat malloc failed\n");
465                         exit(-1);
466                 }
467
468                 /*
469                  * perform the QUERY mntctl - if it returns > 0, that is the
470                  * number of vmount structures in the buffer.  If it returns
471                  * -1, an error occured.  If it returned 0, then look in
472                  * first word of buffer for needed size.
473                  */
474                 if ((nmounts = mntctl(MCTL_QUERY, size, (caddr_t)vm)) > 0) {
475                         /* OK, got it, now return */
476                         *vmountpp = vm;
477                         return(nmounts);
478
479                 } else if (nmounts == 0) {
480                         /* the buffer wasn't big enough .... */
481                         /* .... get required buffer size */
482                         size = *(int *)vm;
483                         free(vm);
484
485                 } else {
486                         /* some other kind of error occurred */
487                         free(vm);
488                         return(-1);
489                 }
490         }
491 }
492
493 int VAttachPartitions(void)
494 {
495     int errors = 0;
496     int nmounts;
497     struct vmount *vmountp;
498
499     if ((nmounts = getmount(&vmountp)) <= 0)    {   
500         Log("Problems in getting # of mount entries(getmount)\n");
501         exit(-1);
502     }
503     for (; nmounts; nmounts--,
504          vmountp = (struct vmount *)((int)vmountp + vmountp->vmt_length)) {
505         char *part = vmt2dataptr(vmountp, VMT_STUB);
506
507         if (vmountp->vmt_flags & (MNT_READONLY|MNT_REMOVABLE|MNT_REMOTE))
508             continue; /* Ignore any "special" partitions */
509
510 #ifdef AFS_AIX42_ENV
511 #ifndef AFS_NAMEI_ENV
512         {
513             struct superblock fs;
514             /* The Log statements are non-sequiters in the SalvageLog and don't
515              * even appear in the VolserLog, so restrict them to the FileLog.
516              */
517             if (ReadSuper(&fs, vmt2dataptr(vmountp, VMT_OBJECT))<0) {
518                 if (programType == fileServer)
519                     Log("Can't read superblock for %s, ignoring it.\n", part);
520                 continue;
521             }
522             if (IsBigFilesFileSystem(&fs)) {
523                 if (programType == fileServer)
524                     Log("%s is a big files filesystem, ignoring it.\n", part);
525                 continue;
526             }
527         }
528 #endif
529 #endif
530
531         /* If we're going to always attach this partition, do it later. */
532         if (VIsAlwaysAttach(part))
533             continue;
534
535         if (VCheckPartition(part, vmt2dataptr(vmountp, VMT_OBJECT)) < 0 )
536             errors ++;
537     }
538
539     /* Process the always-attach partitions, if any. */
540     VAttachPartitions2();
541
542     return errors ;
543 }
544 #endif
545 #if defined(AFS_DUX40_ENV) || defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
546 int VAttachPartitions(void)
547 {
548     int errors = 0;
549     struct fstab *fsent;
550
551     if (setfsent() < 0) {
552         Log("Error listing filesystems.\n");
553         exit(-1);
554     }
555
556     while (fsent = getfsent()) {
557         if (strcmp(fsent->fs_type, "rw") != 0) continue;
558
559         /* If we're going to always attach this partition, do it later. */
560         if (VIsAlwaysAttach(fsent->fs_file))
561             continue;
562
563         if (VCheckPartition(fsent->fs_file, fsent->fs_spec) < 0 )
564             errors ++;
565     }
566     endfsent();
567     
568     /* Process the always-attach partitions, if any. */
569     VAttachPartitions2();
570
571     return errors ;
572 }
573 #endif
574
575 #ifdef AFS_NT40_ENV
576 #include <string.h>
577 #include <sys/stat.h>
578 /* VValidVPTEntry
579  *
580  * validate names in vptab.
581  *
582  * Return value:
583  * 1 valid entry
584  * 0 invalid entry
585  */
586
587 int VValidVPTEntry(struct vptab *vpe)
588 {
589     int len = strlen(vpe->vp_name);
590     int i;
591
592     if (len < VICE_PREFIX_SIZE+1 || len > VICE_PREFIX_SIZE + 2)
593         return 0;
594     if (strncmp(vpe->vp_name, VICE_PARTITION_PREFIX, VICE_PREFIX_SIZE))
595         return 0;
596     
597     for (i=VICE_PREFIX_SIZE; i<len; i++) {
598         if (vpe->vp_name[i] < 'a' || vpe->vp_name[i] > 'z') {
599             Log("Invalid partition name %s in registry, ignoring it.\n",
600                 vpe->vp_name);
601             return 0;
602         }
603     }
604     if (len == VICE_PREFIX_SIZE + 2) {
605         i = (int)(vpe->vp_name[VICE_PREFIX_SIZE]-'a') * 26 +
606             (int)(vpe->vp_name[VICE_PREFIX_SIZE+1]-'a') ;
607         if (i>255) {
608             Log("Invalid partition name %s in registry, ignoring it.\n",
609                 vpe->vp_name);
610             return 0;
611         }
612     }
613
614     len = strlen(vpe->vp_dev);
615     if (len != 2 || vpe->vp_dev[1] != ':'  || vpe->vp_dev[0] < 'A' ||
616         vpe->vp_dev[0] > 'Z') {
617         Log("Invalid device name %s in registry, ignoring it.\n",
618             vpe->vp_dev);
619         return 0;
620     }
621
622     return 1;
623 }
624
625 int VCheckPartition(char *partName)
626 {
627     char volRoot[4];
628     char volFsType[64];
629     DWORD dwDummy;
630     int err;
631
632     /* partName is presumed to be of the form "X:" */
633     (void) sprintf(volRoot, "%c:\\", *partName);
634
635     if (!GetVolumeInformation(volRoot,    /* volume root directory */
636                               NULL,       /* volume name buffer */
637                               0,          /* volume name size */
638                               NULL,       /* volume serial number */
639                               &dwDummy,   /* max component length */
640                               &dwDummy,   /* file system flags */
641                               volFsType,  /* file system name */
642                               sizeof(volFsType))) {
643         err = GetLastError();
644         Log("VCheckPartition: Failed to get partition information for %s, ignoring it.\n",
645             partName);
646         return -1;
647     }
648
649     if (strcmp(volFsType, "NTFS")) {
650         Log("VCheckPartition: Partition %s is not an NTFS partition, ignoring it.\n", partName);
651         return -1;
652     }
653
654     return 0;
655 }
656
657
658 int VAttachPartitions(void)
659 {
660     struct DiskPartition *partP, *prevP, *nextP;
661     struct vpt_iter iter;
662     struct vptab entry;
663
664     if (vpt_Start(&iter)<0) {
665         Log("No partitions to attach.\n");
666         return 0;
667     }
668
669     while (0==vpt_NextEntry(&iter, &entry)) {
670         if (!VValidVPTEntry(&entry)) {
671             continue;
672         }
673
674         /* This test for duplicates relies on the fact that the method
675          * of storing the partition names in the NT registry means the same
676          * partition name will never appear twice in the list.
677          */
678         for (partP = DiskPartitionList; partP; partP = partP->next) {
679             if (*partP->devName == *entry.vp_dev) {
680                 Log("Same drive (%s) used for both partition %s and partition %s, ignoring both.\n", entry.vp_dev, partP->name, entry.vp_name);
681                 partP->flags = PART_DUPLICATE;
682                 break; /* Only one entry will ever be in this list. */
683             }
684         }
685         if (partP) continue; /* found a duplicate */
686
687         if (VCheckPartition(entry.vp_dev)<0)
688             continue;
689         /* This test allows for manually inserting the FORCESALVAGE flag
690          * and thereby invoking the salvager. scandisk obviously won't be
691          * doing this for us.
692          */
693         if (programType == fileServer) {
694             struct stat status;
695             char salvpath[MAXPATHLEN];
696             strcpy(salvpath, entry.vp_dev);
697             strcat(salvpath, "\\FORCESALVAGE");
698             if (stat(salvpath, &status) == 0) {
699                 Log("VAttachPartitions: Found %s; aborting\n", salvpath);
700                 exit(1);
701             }
702         }
703         VInitPartition(entry.vp_name, entry.vp_dev, *entry.vp_dev - 'A');
704     }
705     vpt_Finish(&iter);
706
707     /* Run through partition list and clear out the dupes. */
708     prevP = nextP = NULL;
709     for (partP = DiskPartitionList; partP; partP = nextP) {
710         nextP = partP->next;
711         if (partP->flags == PART_DUPLICATE) {
712             if (prevP)
713                 prevP->next = partP->next;
714             else
715                 DiskPartitionList = partP->next;
716             free(partP);
717         }
718         else
719             prevP = partP;
720     }
721
722     return 0;
723 }
724 #endif
725
726 #ifdef AFS_LINUX22_ENV
727 int VAttachPartitions(void)
728 {
729     int errors = 0;
730     FILE *mfd;
731     struct mntent *mntent;
732     
733     if ((mfd = setmntent("/proc/mounts", "r")) == NULL) {
734         if ((mfd = setmntent("/etc/mtab", "r")) == NULL) {
735             Log("Problems in getting mount entries(setmntent)\n");
736             exit(-1);
737         }
738     }
739     while ((mntent = getmntent(mfd))) {
740         /* If we're going to always attach this partition, do it later. */
741         if (VIsAlwaysAttach(mntent->mnt_dir))
742             continue;
743
744         if (VCheckPartition(mntent->mnt_dir, mntent->mnt_fsname) < 0 )
745             errors ++;
746     }
747     endmntent(mfd);
748
749     /* Process the always-attach partitions, if any. */
750     VAttachPartitions2();
751
752     return errors ;
753 }
754 #endif /* AFS_LINUX22_ENV */
755
756 /* This routine is to be called whenever the actual name of the partition
757  * is required. The canonical name is still in part->name.
758  */
759 char * VPartitionPath(struct DiskPartition *part)
760 {
761 #ifdef AFS_NT40_ENV
762     return part->devName;
763 #else
764     return part->name;
765 #endif    
766 }
767
768 /* get partition structure, abortp tells us if we should abort on failure */
769 struct DiskPartition *VGetPartition_r(char *name, int abortp)
770 {
771     register struct DiskPartition *dp;
772     for (dp = DiskPartitionList; dp; dp = dp->next) {
773         if (strcmp(dp->name, name) == 0)
774             break;
775     }
776     if (abortp)
777         assert(dp != NULL);
778     return dp;
779 }
780
781 struct DiskPartition *VGetPartition(char *name, int abortp)
782 {
783     struct DiskPartition *retVal;
784     VOL_LOCK
785     retVal = VGetPartition_r(name, abortp);
786     VOL_UNLOCK
787     return retVal;
788 }
789
790 #ifdef AFS_NT40_ENV
791 void VSetPartitionDiskUsage_r(register struct DiskPartition *dp)
792 {
793     ULARGE_INTEGER free_user, total, free_total;
794     int ufree, tot, tfree;
795     
796     if (!GetDiskFreeSpaceEx(VPartitionPath(dp), &free_user, &total,
797                             &free_total)) {
798         printf("Failed to get disk space info for %s, error = %d\n",
799                dp->name, GetLastError());
800         return;
801     }
802
803     /* Convert to 1K units. */
804     ufree = (int) Int64ShraMod32(free_user.QuadPart, 10);
805     tot = (int) Int64ShraMod32(total.QuadPart, 10);
806     tfree = (int) Int64ShraMod32(free_total.QuadPart, 10);
807
808     dp->minFree = tfree - ufree; /* only used in VPrintDiskStats_r */
809     dp->totalUsable = tot;
810     dp->free = tfree;
811 }
812
813 #else
814 void VSetPartitionDiskUsage_r(register struct DiskPartition *dp)
815 {
816     extern int errno;
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 }