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