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