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