0cdeebcbb4339c956b4aa61af0daa1566b9e7892
[dragonfly.git] / sys / vfs / nfs / nfs_subs.c
1 /*
2  * Copyright (c) 1989, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Rick Macklem at The University of Guelph.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by the University of
19  *      California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *      @(#)nfs_subs.c  8.8 (Berkeley) 5/22/95
37  * $FreeBSD: /repoman/r/ncvs/src/sys/nfsclient/nfs_subs.c,v 1.128 2004/04/14 23:23:55 peadar Exp $
38  * $DragonFly: src/sys/vfs/nfs/nfs_subs.c,v 1.48 2008/09/17 21:44:24 dillon Exp $
39  */
40
41 /*
42  * These functions support the macros and help fiddle mbuf chains for
43  * the nfs op functions. They do things like create the rpc header and
44  * copy data between mbuf chains and uio lists.
45  */
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/kernel.h>
49 #include <sys/buf.h>
50 #include <sys/proc.h>
51 #include <sys/mount.h>
52 #include <sys/vnode.h>
53 #include <sys/nlookup.h>
54 #include <sys/namei.h>
55 #include <sys/mbuf.h>
56 #include <sys/socket.h>
57 #include <sys/stat.h>
58 #include <sys/malloc.h>
59 #include <sys/sysent.h>
60 #include <sys/syscall.h>
61 #include <sys/conf.h>
62 #include <sys/objcache.h>
63
64 #include <vm/vm.h>
65 #include <vm/vm_object.h>
66 #include <vm/vm_extern.h>
67 #include <vm/vm_zone.h>
68
69 #include <sys/buf2.h>
70
71 #include "rpcv2.h"
72 #include "nfsproto.h"
73 #include "nfs.h"
74 #include "nfsmount.h"
75 #include "nfsnode.h"
76 #include "xdr_subs.h"
77 #include "nfsm_subs.h"
78 #include "nfsrtt.h"
79
80 #include <netinet/in.h>
81
82 /*
83  * Data items converted to xdr at startup, since they are constant
84  * This is kinda hokey, but may save a little time doing byte swaps
85  */
86 u_int32_t nfs_xdrneg1;
87 u_int32_t rpc_reply, rpc_msgdenied, rpc_mismatch, rpc_vers;
88 u_int32_t rpc_auth_unix, rpc_msgaccepted, rpc_call, rpc_autherr;
89 u_int32_t rpc_auth_kerb;
90 u_int32_t nfs_prog, nfs_true, nfs_false;
91
92 /* And other global data */
93 static enum vtype nv2tov_type[8]= {
94         VNON, VREG, VDIR, VBLK, VCHR, VLNK, VNON,  VNON 
95 };
96 enum vtype nv3tov_type[8]= {
97         VNON, VREG, VDIR, VBLK, VCHR, VLNK, VSOCK, VFIFO
98 };
99
100 int nfs_ticks;
101
102 static int nfs_pbuf_freecnt = -1;       /* start out unlimited */
103
104 struct nfsmount_head nfs_mountq = TAILQ_HEAD_INITIALIZER(nfs_mountq);
105 struct nfssvc_sockhead nfssvc_sockhead;
106 int nfssvc_sockhead_flag;
107 struct nfsd_head nfsd_head;
108 int nfsd_head_flag;
109 struct nfs_bufq nfs_bufq;
110 struct nqfhhashhead *nqfhhashtbl;
111 u_long nqfhhash;
112
113 static int nfs_prev_nfssvc_sy_narg;
114 static sy_call_t *nfs_prev_nfssvc_sy_call;
115
116 #ifndef NFS_NOSERVER
117
118 /*
119  * Mapping of old NFS Version 2 RPC numbers to generic numbers.
120  */
121 int nfsv3_procid[NFS_NPROCS] = {
122         NFSPROC_NULL,
123         NFSPROC_GETATTR,
124         NFSPROC_SETATTR,
125         NFSPROC_NOOP,
126         NFSPROC_LOOKUP,
127         NFSPROC_READLINK,
128         NFSPROC_READ,
129         NFSPROC_NOOP,
130         NFSPROC_WRITE,
131         NFSPROC_CREATE,
132         NFSPROC_REMOVE,
133         NFSPROC_RENAME,
134         NFSPROC_LINK,
135         NFSPROC_SYMLINK,
136         NFSPROC_MKDIR,
137         NFSPROC_RMDIR,
138         NFSPROC_READDIR,
139         NFSPROC_FSSTAT,
140         NFSPROC_NOOP,
141         NFSPROC_NOOP,
142         NFSPROC_NOOP,
143         NFSPROC_NOOP,
144         NFSPROC_NOOP,
145         NFSPROC_NOOP,
146         NFSPROC_NOOP,
147         NFSPROC_NOOP
148 };
149
150 #endif /* NFS_NOSERVER */
151 /*
152  * and the reverse mapping from generic to Version 2 procedure numbers
153  */
154 int nfsv2_procid[NFS_NPROCS] = {
155         NFSV2PROC_NULL,
156         NFSV2PROC_GETATTR,
157         NFSV2PROC_SETATTR,
158         NFSV2PROC_LOOKUP,
159         NFSV2PROC_NOOP,
160         NFSV2PROC_READLINK,
161         NFSV2PROC_READ,
162         NFSV2PROC_WRITE,
163         NFSV2PROC_CREATE,
164         NFSV2PROC_MKDIR,
165         NFSV2PROC_SYMLINK,
166         NFSV2PROC_CREATE,
167         NFSV2PROC_REMOVE,
168         NFSV2PROC_RMDIR,
169         NFSV2PROC_RENAME,
170         NFSV2PROC_LINK,
171         NFSV2PROC_READDIR,
172         NFSV2PROC_NOOP,
173         NFSV2PROC_STATFS,
174         NFSV2PROC_NOOP,
175         NFSV2PROC_NOOP,
176         NFSV2PROC_NOOP,
177         NFSV2PROC_NOOP,
178         NFSV2PROC_NOOP,
179         NFSV2PROC_NOOP,
180         NFSV2PROC_NOOP,
181 };
182
183 #ifndef NFS_NOSERVER
184 /*
185  * Maps errno values to nfs error numbers.
186  * Use NFSERR_IO as the catch all for ones not specifically defined in
187  * RFC 1094.
188  */
189 static u_char nfsrv_v2errmap[ELAST] = {
190   NFSERR_PERM,  NFSERR_NOENT,   NFSERR_IO,      NFSERR_IO,      NFSERR_IO,
191   NFSERR_NXIO,  NFSERR_IO,      NFSERR_IO,      NFSERR_IO,      NFSERR_IO,
192   NFSERR_IO,    NFSERR_IO,      NFSERR_ACCES,   NFSERR_IO,      NFSERR_IO,
193   NFSERR_IO,    NFSERR_EXIST,   NFSERR_IO,      NFSERR_NODEV,   NFSERR_NOTDIR,
194   NFSERR_ISDIR, NFSERR_IO,      NFSERR_IO,      NFSERR_IO,      NFSERR_IO,
195   NFSERR_IO,    NFSERR_FBIG,    NFSERR_NOSPC,   NFSERR_IO,      NFSERR_ROFS,
196   NFSERR_IO,    NFSERR_IO,      NFSERR_IO,      NFSERR_IO,      NFSERR_IO,
197   NFSERR_IO,    NFSERR_IO,      NFSERR_IO,      NFSERR_IO,      NFSERR_IO,
198   NFSERR_IO,    NFSERR_IO,      NFSERR_IO,      NFSERR_IO,      NFSERR_IO,
199   NFSERR_IO,    NFSERR_IO,      NFSERR_IO,      NFSERR_IO,      NFSERR_IO,
200   NFSERR_IO,    NFSERR_IO,      NFSERR_IO,      NFSERR_IO,      NFSERR_IO,
201   NFSERR_IO,    NFSERR_IO,      NFSERR_IO,      NFSERR_IO,      NFSERR_IO,
202   NFSERR_IO,    NFSERR_IO,      NFSERR_NAMETOL, NFSERR_IO,      NFSERR_IO,
203   NFSERR_NOTEMPTY, NFSERR_IO,   NFSERR_IO,      NFSERR_DQUOT,   NFSERR_STALE,
204   NFSERR_IO,    NFSERR_IO,      NFSERR_IO,      NFSERR_IO,      NFSERR_IO,
205   NFSERR_IO,    NFSERR_IO,      NFSERR_IO,      NFSERR_IO,      NFSERR_IO,
206   NFSERR_IO,    NFSERR_IO,      NFSERR_IO,      NFSERR_IO,      NFSERR_IO,
207   NFSERR_IO /* << Last is 86 */
208 };
209
210 /*
211  * Maps errno values to nfs error numbers.
212  * Although it is not obvious whether or not NFS clients really care if
213  * a returned error value is in the specified list for the procedure, the
214  * safest thing to do is filter them appropriately. For Version 2, the
215  * X/Open XNFS document is the only specification that defines error values
216  * for each RPC (The RFC simply lists all possible error values for all RPCs),
217  * so I have decided to not do this for Version 2.
218  * The first entry is the default error return and the rest are the valid
219  * errors for that RPC in increasing numeric order.
220  */
221 static short nfsv3err_null[] = {
222         0,
223         0,
224 };
225
226 static short nfsv3err_getattr[] = {
227         NFSERR_IO,
228         NFSERR_IO,
229         NFSERR_STALE,
230         NFSERR_BADHANDLE,
231         NFSERR_SERVERFAULT,
232         0,
233 };
234
235 static short nfsv3err_setattr[] = {
236         NFSERR_IO,
237         NFSERR_PERM,
238         NFSERR_IO,
239         NFSERR_ACCES,
240         NFSERR_INVAL,
241         NFSERR_NOSPC,
242         NFSERR_ROFS,
243         NFSERR_DQUOT,
244         NFSERR_STALE,
245         NFSERR_BADHANDLE,
246         NFSERR_NOT_SYNC,
247         NFSERR_SERVERFAULT,
248         0,
249 };
250
251 static short nfsv3err_lookup[] = {
252         NFSERR_IO,
253         NFSERR_NOENT,
254         NFSERR_IO,
255         NFSERR_ACCES,
256         NFSERR_NOTDIR,
257         NFSERR_NAMETOL,
258         NFSERR_STALE,
259         NFSERR_BADHANDLE,
260         NFSERR_SERVERFAULT,
261         0,
262 };
263
264 static short nfsv3err_access[] = {
265         NFSERR_IO,
266         NFSERR_IO,
267         NFSERR_STALE,
268         NFSERR_BADHANDLE,
269         NFSERR_SERVERFAULT,
270         0,
271 };
272
273 static short nfsv3err_readlink[] = {
274         NFSERR_IO,
275         NFSERR_IO,
276         NFSERR_ACCES,
277         NFSERR_INVAL,
278         NFSERR_STALE,
279         NFSERR_BADHANDLE,
280         NFSERR_NOTSUPP,
281         NFSERR_SERVERFAULT,
282         0,
283 };
284
285 static short nfsv3err_read[] = {
286         NFSERR_IO,
287         NFSERR_IO,
288         NFSERR_NXIO,
289         NFSERR_ACCES,
290         NFSERR_INVAL,
291         NFSERR_STALE,
292         NFSERR_BADHANDLE,
293         NFSERR_SERVERFAULT,
294         0,
295 };
296
297 static short nfsv3err_write[] = {
298         NFSERR_IO,
299         NFSERR_IO,
300         NFSERR_ACCES,
301         NFSERR_INVAL,
302         NFSERR_FBIG,
303         NFSERR_NOSPC,
304         NFSERR_ROFS,
305         NFSERR_DQUOT,
306         NFSERR_STALE,
307         NFSERR_BADHANDLE,
308         NFSERR_SERVERFAULT,
309         0,
310 };
311
312 static short nfsv3err_create[] = {
313         NFSERR_IO,
314         NFSERR_IO,
315         NFSERR_ACCES,
316         NFSERR_EXIST,
317         NFSERR_NOTDIR,
318         NFSERR_NOSPC,
319         NFSERR_ROFS,
320         NFSERR_NAMETOL,
321         NFSERR_DQUOT,
322         NFSERR_STALE,
323         NFSERR_BADHANDLE,
324         NFSERR_NOTSUPP,
325         NFSERR_SERVERFAULT,
326         0,
327 };
328
329 static short nfsv3err_mkdir[] = {
330         NFSERR_IO,
331         NFSERR_IO,
332         NFSERR_ACCES,
333         NFSERR_EXIST,
334         NFSERR_NOTDIR,
335         NFSERR_NOSPC,
336         NFSERR_ROFS,
337         NFSERR_NAMETOL,
338         NFSERR_DQUOT,
339         NFSERR_STALE,
340         NFSERR_BADHANDLE,
341         NFSERR_NOTSUPP,
342         NFSERR_SERVERFAULT,
343         0,
344 };
345
346 static short nfsv3err_symlink[] = {
347         NFSERR_IO,
348         NFSERR_IO,
349         NFSERR_ACCES,
350         NFSERR_EXIST,
351         NFSERR_NOTDIR,
352         NFSERR_NOSPC,
353         NFSERR_ROFS,
354         NFSERR_NAMETOL,
355         NFSERR_DQUOT,
356         NFSERR_STALE,
357         NFSERR_BADHANDLE,
358         NFSERR_NOTSUPP,
359         NFSERR_SERVERFAULT,
360         0,
361 };
362
363 static short nfsv3err_mknod[] = {
364         NFSERR_IO,
365         NFSERR_IO,
366         NFSERR_ACCES,
367         NFSERR_EXIST,
368         NFSERR_NOTDIR,
369         NFSERR_NOSPC,
370         NFSERR_ROFS,
371         NFSERR_NAMETOL,
372         NFSERR_DQUOT,
373         NFSERR_STALE,
374         NFSERR_BADHANDLE,
375         NFSERR_NOTSUPP,
376         NFSERR_SERVERFAULT,
377         NFSERR_BADTYPE,
378         0,
379 };
380
381 static short nfsv3err_remove[] = {
382         NFSERR_IO,
383         NFSERR_NOENT,
384         NFSERR_IO,
385         NFSERR_ACCES,
386         NFSERR_NOTDIR,
387         NFSERR_ROFS,
388         NFSERR_NAMETOL,
389         NFSERR_STALE,
390         NFSERR_BADHANDLE,
391         NFSERR_SERVERFAULT,
392         0,
393 };
394
395 static short nfsv3err_rmdir[] = {
396         NFSERR_IO,
397         NFSERR_NOENT,
398         NFSERR_IO,
399         NFSERR_ACCES,
400         NFSERR_EXIST,
401         NFSERR_NOTDIR,
402         NFSERR_INVAL,
403         NFSERR_ROFS,
404         NFSERR_NAMETOL,
405         NFSERR_NOTEMPTY,
406         NFSERR_STALE,
407         NFSERR_BADHANDLE,
408         NFSERR_NOTSUPP,
409         NFSERR_SERVERFAULT,
410         0,
411 };
412
413 static short nfsv3err_rename[] = {
414         NFSERR_IO,
415         NFSERR_NOENT,
416         NFSERR_IO,
417         NFSERR_ACCES,
418         NFSERR_EXIST,
419         NFSERR_XDEV,
420         NFSERR_NOTDIR,
421         NFSERR_ISDIR,
422         NFSERR_INVAL,
423         NFSERR_NOSPC,
424         NFSERR_ROFS,
425         NFSERR_MLINK,
426         NFSERR_NAMETOL,
427         NFSERR_NOTEMPTY,
428         NFSERR_DQUOT,
429         NFSERR_STALE,
430         NFSERR_BADHANDLE,
431         NFSERR_NOTSUPP,
432         NFSERR_SERVERFAULT,
433         0,
434 };
435
436 static short nfsv3err_link[] = {
437         NFSERR_IO,
438         NFSERR_IO,
439         NFSERR_ACCES,
440         NFSERR_EXIST,
441         NFSERR_XDEV,
442         NFSERR_NOTDIR,
443         NFSERR_INVAL,
444         NFSERR_NOSPC,
445         NFSERR_ROFS,
446         NFSERR_MLINK,
447         NFSERR_NAMETOL,
448         NFSERR_DQUOT,
449         NFSERR_STALE,
450         NFSERR_BADHANDLE,
451         NFSERR_NOTSUPP,
452         NFSERR_SERVERFAULT,
453         0,
454 };
455
456 static short nfsv3err_readdir[] = {
457         NFSERR_IO,
458         NFSERR_IO,
459         NFSERR_ACCES,
460         NFSERR_NOTDIR,
461         NFSERR_STALE,
462         NFSERR_BADHANDLE,
463         NFSERR_BAD_COOKIE,
464         NFSERR_TOOSMALL,
465         NFSERR_SERVERFAULT,
466         0,
467 };
468
469 static short nfsv3err_readdirplus[] = {
470         NFSERR_IO,
471         NFSERR_IO,
472         NFSERR_ACCES,
473         NFSERR_NOTDIR,
474         NFSERR_STALE,
475         NFSERR_BADHANDLE,
476         NFSERR_BAD_COOKIE,
477         NFSERR_NOTSUPP,
478         NFSERR_TOOSMALL,
479         NFSERR_SERVERFAULT,
480         0,
481 };
482
483 static short nfsv3err_fsstat[] = {
484         NFSERR_IO,
485         NFSERR_IO,
486         NFSERR_STALE,
487         NFSERR_BADHANDLE,
488         NFSERR_SERVERFAULT,
489         0,
490 };
491
492 static short nfsv3err_fsinfo[] = {
493         NFSERR_STALE,
494         NFSERR_STALE,
495         NFSERR_BADHANDLE,
496         NFSERR_SERVERFAULT,
497         0,
498 };
499
500 static short nfsv3err_pathconf[] = {
501         NFSERR_STALE,
502         NFSERR_STALE,
503         NFSERR_BADHANDLE,
504         NFSERR_SERVERFAULT,
505         0,
506 };
507
508 static short nfsv3err_commit[] = {
509         NFSERR_IO,
510         NFSERR_IO,
511         NFSERR_STALE,
512         NFSERR_BADHANDLE,
513         NFSERR_SERVERFAULT,
514         0,
515 };
516
517 static short *nfsrv_v3errmap[] = {
518         nfsv3err_null,
519         nfsv3err_getattr,
520         nfsv3err_setattr,
521         nfsv3err_lookup,
522         nfsv3err_access,
523         nfsv3err_readlink,
524         nfsv3err_read,
525         nfsv3err_write,
526         nfsv3err_create,
527         nfsv3err_mkdir,
528         nfsv3err_symlink,
529         nfsv3err_mknod,
530         nfsv3err_remove,
531         nfsv3err_rmdir,
532         nfsv3err_rename,
533         nfsv3err_link,
534         nfsv3err_readdir,
535         nfsv3err_readdirplus,
536         nfsv3err_fsstat,
537         nfsv3err_fsinfo,
538         nfsv3err_pathconf,
539         nfsv3err_commit,
540 };
541
542 #endif /* NFS_NOSERVER */
543
544 struct nfssvc_args;
545 extern int sys_nfssvc(struct proc *, struct nfssvc_args *, int *);
546
547 /*
548  * This needs to return a monotonically increasing or close to monotonically
549  * increasing result, otherwise the write gathering queues won't work 
550  * properly.
551  */
552 u_quad_t
553 nfs_curusec(void) 
554 {
555         struct timeval tv;
556         
557         getmicrouptime(&tv);
558         return ((u_quad_t)tv.tv_sec * 1000000 + (u_quad_t)tv.tv_usec);
559 }
560
561 /*
562  * Called once to initialize data structures...
563  */
564 int
565 nfs_init(struct vfsconf *vfsp)
566 {
567         callout_init(&nfs_timer_handle);
568         nfsmount_zone = zinit("NFSMOUNT", sizeof(struct nfsmount), 0, 0, 1);
569
570         nfs_mount_type = vfsp->vfc_typenum;
571         nfsrtt.pos = 0;
572         rpc_vers = txdr_unsigned(RPC_VER2);
573         rpc_call = txdr_unsigned(RPC_CALL);
574         rpc_reply = txdr_unsigned(RPC_REPLY);
575         rpc_msgdenied = txdr_unsigned(RPC_MSGDENIED);
576         rpc_msgaccepted = txdr_unsigned(RPC_MSGACCEPTED);
577         rpc_mismatch = txdr_unsigned(RPC_MISMATCH);
578         rpc_autherr = txdr_unsigned(RPC_AUTHERR);
579         rpc_auth_unix = txdr_unsigned(RPCAUTH_UNIX);
580         rpc_auth_kerb = txdr_unsigned(RPCAUTH_KERB4);
581         nfs_prog = txdr_unsigned(NFS_PROG);
582         nfs_true = txdr_unsigned(TRUE);
583         nfs_false = txdr_unsigned(FALSE);
584         nfs_xdrneg1 = txdr_unsigned(-1);
585         nfs_ticks = (hz * NFS_TICKINTVL + 500) / 1000;
586         if (nfs_ticks < 1)
587                 nfs_ticks = 1;
588         nfs_nhinit();                   /* Init the nfsnode table */
589 #ifndef NFS_NOSERVER
590         nfsrv_init(0);                  /* Init server data structures */
591         nfsrv_initcache();              /* Init the server request cache */
592 #endif
593
594         /*
595          * Mainly for vkernel operation.  If memory is severely limited
596          */
597         if (nfs_maxasyncbio > nmbclusters * MCLBYTES / NFS_MAXDATA / 3)
598                 nfs_maxasyncbio = nmbclusters * MCLBYTES / NFS_MAXDATA / 3;
599         if (nfs_maxasyncbio < 4)
600                 nfs_maxasyncbio = 4;
601
602         /*
603          * Initialize reply list and start timer
604          */
605         nfs_timer(0);
606
607         nfs_prev_nfssvc_sy_narg = sysent[SYS_nfssvc].sy_narg;
608         sysent[SYS_nfssvc].sy_narg = 2;
609         nfs_prev_nfssvc_sy_call = sysent[SYS_nfssvc].sy_call;
610         sysent[SYS_nfssvc].sy_call = (sy_call_t *)sys_nfssvc;
611
612         nfs_pbuf_freecnt = nswbuf / 2 + 1;
613
614         return (0);
615 }
616
617 int
618 nfs_uninit(struct vfsconf *vfsp)
619 {
620         callout_stop(&nfs_timer_handle);
621         nfs_mount_type = -1;
622         sysent[SYS_nfssvc].sy_narg = nfs_prev_nfssvc_sy_narg;
623         sysent[SYS_nfssvc].sy_call = nfs_prev_nfssvc_sy_call;
624         return (0);
625 }
626
627 /*
628  * Attribute cache routines.
629  * nfs_loadattrcache() - loads or updates the cache contents from attributes
630  *      that are on the mbuf list
631  * nfs_getattrcache() - returns valid attributes if found in cache, returns
632  *      error otherwise
633  */
634
635 /*
636  * Load the attribute cache (that lives in the nfsnode entry) with
637  * the values on the mbuf list.  Load *vaper with the attributes.  vaper
638  * may be NULL.
639  *
640  * As a side effect n_mtime, which we use to determine if the file was
641  * modified by some other host, is set to the attribute timestamp and
642  * NRMODIFIED is set if the two values differ.
643  *
644  * WARNING: the mtime loaded into vaper does not necessarily represent
645  * n_mtime or n_attr.mtime due to NACC and NUPD.
646  */
647 int
648 nfs_loadattrcache(struct vnode *vp, struct mbuf **mdp, caddr_t *dposp,
649                   struct vattr *vaper, int lattr_flags)
650 {
651         struct vattr *vap;
652         struct nfs_fattr *fp;
653         struct nfsnode *np;
654         int32_t t1;
655         caddr_t cp2;
656         int error = 0;
657         int rmajor, rminor;
658         udev_t rdev;
659         struct mbuf *md;
660         enum vtype vtyp;
661         u_short vmode;
662         struct timespec mtime;
663         int v3 = NFS_ISV3(vp);
664
665         md = *mdp;
666         t1 = (mtod(md, caddr_t) + md->m_len) - *dposp;
667         if ((error = nfsm_disct(mdp, dposp, NFSX_FATTR(v3), t1, &cp2)) != 0)
668                 return (error);
669         fp = (struct nfs_fattr *)cp2;
670         if (v3) {
671                 vtyp = nfsv3tov_type(fp->fa_type);
672                 vmode = fxdr_unsigned(u_short, fp->fa_mode);
673                 rmajor = (int)fxdr_unsigned(int, fp->fa3_rdev.specdata1);
674                 rminor = (int)fxdr_unsigned(int, fp->fa3_rdev.specdata2);
675                 fxdr_nfsv3time(&fp->fa3_mtime, &mtime);
676         } else {
677                 vtyp = nfsv2tov_type(fp->fa_type);
678                 vmode = fxdr_unsigned(u_short, fp->fa_mode);
679                 /*
680                  * XXX
681                  *
682                  * The duplicate information returned in fa_type and fa_mode
683                  * is an ambiguity in the NFS version 2 protocol.
684                  *
685                  * VREG should be taken literally as a regular file.  If a
686                  * server intents to return some type information differently
687                  * in the upper bits of the mode field (e.g. for sockets, or
688                  * FIFOs), NFSv2 mandates fa_type to be VNON.  Anyway, we
689                  * leave the examination of the mode bits even in the VREG
690                  * case to avoid breakage for bogus servers, but we make sure
691                  * that there are actually type bits set in the upper part of
692                  * fa_mode (and failing that, trust the va_type field).
693                  *
694                  * NFSv3 cleared the issue, and requires fa_mode to not
695                  * contain any type information (while also introduing sockets
696                  * and FIFOs for fa_type).
697                  */
698                 if (vtyp == VNON || (vtyp == VREG && (vmode & S_IFMT) != 0))
699                         vtyp = IFTOVT(vmode);
700                 rdev = fxdr_unsigned(int32_t, fp->fa2_rdev);
701                 rmajor = umajor(rdev);
702                 rminor = uminor(rdev);
703                 fxdr_nfsv2time(&fp->fa2_mtime, &mtime);
704
705                 /*
706                  * Really ugly NFSv2 kludge.
707                  */
708                 if (vtyp == VCHR && rdev == (udev_t)0xffffffff)
709                         vtyp = VFIFO;
710         }
711
712         /*
713          * If v_type == VNON it is a new node, so fill in the v_type,
714          * n_mtime fields. Check to see if it represents a special
715          * device, and if so, check for a possible alias. Once the
716          * correct vnode has been obtained, fill in the rest of the
717          * information.
718          */
719         np = VTONFS(vp);
720         if (vp->v_type != vtyp) {
721                 nfs_setvtype(vp, vtyp);
722                 if (vp->v_type == VFIFO) {
723                         vp->v_ops = &vp->v_mount->mnt_vn_fifo_ops;
724                 } else if (vp->v_type == VCHR || vp->v_type == VBLK) {
725                         vp->v_ops = &vp->v_mount->mnt_vn_spec_ops;
726                         addaliasu(vp, rmajor, rminor);
727                 } else {
728                         vp->v_ops = &vp->v_mount->mnt_vn_use_ops;
729                 }
730                 np->n_mtime = mtime.tv_sec;
731         } else if (np->n_mtime != mtime.tv_sec) {
732                 /*
733                  * If we haven't modified the file locally and the server
734                  * timestamp does not match, then the server probably
735                  * modified the file.  We must flag this condition so
736                  * the proper syncnronization can be done.  We do not
737                  * try to synchronize the state here because that
738                  * could lead to an endless recursion.
739                  *
740                  * XXX loadattrcache can be set during the reply to a write,
741                  * before the write timestamp is properly processed.  To
742                  * avoid unconditionally setting the rmodified bit (which
743                  * has the effect of flushing the cache), we only do this
744                  * check if the lmodified bit is not set.
745                  */
746                 np->n_mtime = mtime.tv_sec;
747                 if ((lattr_flags & NFS_LATTR_NOMTIMECHECK) == 0)
748                         np->n_flag |= NRMODIFIED;
749         }
750         vap = &np->n_vattr;
751         vap->va_type = vtyp;
752         vap->va_mode = (vmode & 07777);
753         vap->va_rmajor = rmajor;
754         vap->va_rminor = rminor;
755         vap->va_mtime = mtime;
756         vap->va_fsid = vp->v_mount->mnt_stat.f_fsid.val[0];
757         if (v3) {
758                 vap->va_nlink = fxdr_unsigned(u_short, fp->fa_nlink);
759                 vap->va_uid = fxdr_unsigned(uid_t, fp->fa_uid);
760                 vap->va_gid = fxdr_unsigned(gid_t, fp->fa_gid);
761                 vap->va_size = fxdr_hyper(&fp->fa3_size);
762                 vap->va_blocksize = NFS_FABLKSIZE;
763                 vap->va_bytes = fxdr_hyper(&fp->fa3_used);
764                 vap->va_fileid = fxdr_hyper(&fp->fa3_fileid);
765                 fxdr_nfsv3time(&fp->fa3_atime, &vap->va_atime);
766                 fxdr_nfsv3time(&fp->fa3_ctime, &vap->va_ctime);
767                 vap->va_flags = 0;
768                 vap->va_filerev = 0;
769         } else {
770                 vap->va_nlink = fxdr_unsigned(u_short, fp->fa_nlink);
771                 vap->va_uid = fxdr_unsigned(uid_t, fp->fa_uid);
772                 vap->va_gid = fxdr_unsigned(gid_t, fp->fa_gid);
773                 vap->va_size = fxdr_unsigned(u_int32_t, fp->fa2_size);
774                 vap->va_blocksize = fxdr_unsigned(int32_t, fp->fa2_blocksize);
775                 vap->va_bytes = (u_quad_t)fxdr_unsigned(int32_t, fp->fa2_blocks)
776                     * NFS_FABLKSIZE;
777                 vap->va_fileid = fxdr_unsigned(int32_t, fp->fa2_fileid);
778                 fxdr_nfsv2time(&fp->fa2_atime, &vap->va_atime);
779                 vap->va_flags = 0;
780                 vap->va_ctime.tv_sec = fxdr_unsigned(u_int32_t,
781                     fp->fa2_ctime.nfsv2_sec);
782                 vap->va_ctime.tv_nsec = 0;
783                 vap->va_gen = fxdr_unsigned(u_int32_t,fp->fa2_ctime.nfsv2_usec);
784                 vap->va_filerev = 0;
785         }
786         np->n_attrstamp = time_second;
787         if (vap->va_size != np->n_size) {
788                 if (vap->va_type == VREG) {
789                         /*
790                          * Get rid of all the junk we had before and just
791                          * set NRMODIFIED if NLMODIFIED is 0.  Depend on
792                          * occassionally flushing our dirty buffers to
793                          * clear both the NLMODIFIED and NRMODIFIED flags.
794                          */
795                         if ((np->n_flag & NLMODIFIED) == 0)
796                                 np->n_flag |= NRMODIFIED;
797 #if 0
798                         if ((lattr_flags & NFS_LATTR_NOSHRINK) && 
799                             vap->va_size < np->n_size) {
800                                 /*
801                                  * We've been told not to shrink the file;
802                                  * zero np->n_attrstamp to indicate that
803                                  * the attributes are stale.
804                                  *
805                                  * This occurs primarily due to recursive
806                                  * NFS ops that are executed during periods
807                                  * where we cannot safely reduce the size of
808                                  * the file.
809                                  *
810                                  * Additionally, write rpcs are broken down
811                                  * into buffers and np->n_size is 
812                                  * pre-extended.  Setting NRMODIFIED here
813                                  * can result in n_size getting reset to a
814                                  * lower value, which is NOT what we want.
815                                  * XXX this needs to be cleaned up a lot 
816                                  * more.
817                                  */
818                                 vap->va_size = np->n_size;
819                                 np->n_attrstamp = 0;
820                                 if ((np->n_flag & NLMODIFIED) == 0)
821                                         np->n_flag |= NRMODIFIED;
822                         } else if (np->n_flag & NLMODIFIED) {
823                                 /*
824                                  * We've modified the file: Use the larger
825                                  * of our size, and the server's size.  At
826                                  * this point the cache coherency is all
827                                  * shot to hell.  To try to handle multiple
828                                  * clients appending to the file at the same
829                                  * time mark that the server has changed
830                                  * the file if the server's notion of the
831                                  * file size is larger then our notion.
832                                  *
833                                  * XXX this needs work.
834                                  */
835                                 if (vap->va_size < np->n_size) {
836                                         vap->va_size = np->n_size;
837                                 } else {
838                                         np->n_size = vap->va_size;
839                                         np->n_flag |= NRMODIFIED;
840                                 }
841                         } else {
842                                 /*
843                                  * Someone changed the file's size on the
844                                  * server and there are no local changes
845                                  * to get in the way, set the size and mark
846                                  * it.
847                                  */
848                                 np->n_size = vap->va_size;
849                                 np->n_flag |= NRMODIFIED;
850                         }
851                         nvnode_pager_setsize(vp, np->n_size, XXX);
852 #endif
853                 } else {
854                         np->n_size = vap->va_size;
855                 }
856         }
857         if (vaper != NULL) {
858                 bcopy((caddr_t)vap, (caddr_t)vaper, sizeof(*vap));
859                 if (np->n_flag & NCHG) {
860                         if (np->n_flag & NACC)
861                                 vaper->va_atime = np->n_atim;
862                         if (np->n_flag & NUPD)
863                                 vaper->va_mtime = np->n_mtim;
864                 }
865         }
866         return (0);
867 }
868
869 #ifdef NFS_ACDEBUG
870 #include <sys/sysctl.h>
871 SYSCTL_DECL(_vfs_nfs);
872 static int nfs_acdebug;
873 SYSCTL_INT(_vfs_nfs, OID_AUTO, acdebug, CTLFLAG_RW, &nfs_acdebug, 0, "");
874 #endif
875
876 /*
877  * Check the time stamp
878  * If the cache is valid, copy contents to *vap and return 0
879  * otherwise return an error
880  */
881 int
882 nfs_getattrcache(struct vnode *vp, struct vattr *vaper)
883 {
884         struct nfsnode *np;
885         struct vattr *vap;
886         struct nfsmount *nmp;
887         int timeo;
888
889         np = VTONFS(vp);
890         vap = &np->n_vattr;
891         nmp = VFSTONFS(vp->v_mount);
892
893         /*
894          * Dynamic timeout based on how recently the file was modified.
895          * n_mtime is always valid.
896          */
897         timeo = (get_approximate_time_t() - np->n_mtime) / 60;
898
899 #ifdef NFS_ACDEBUG
900         if (nfs_acdebug>1)
901                 kprintf("nfs_getattrcache: initial timeo = %d\n", timeo);
902 #endif
903
904         if (vap->va_type == VDIR) {
905                 if ((np->n_flag & NLMODIFIED) || timeo < nmp->nm_acdirmin)
906                         timeo = nmp->nm_acdirmin;
907                 else if (timeo > nmp->nm_acdirmax)
908                         timeo = nmp->nm_acdirmax;
909         } else {
910                 if ((np->n_flag & NLMODIFIED) || timeo < nmp->nm_acregmin)
911                         timeo = nmp->nm_acregmin;
912                 else if (timeo > nmp->nm_acregmax)
913                         timeo = nmp->nm_acregmax;
914         }
915
916 #ifdef NFS_ACDEBUG
917         if (nfs_acdebug > 2)
918                 kprintf("acregmin %d; acregmax %d; acdirmin %d; acdirmax %d\n",
919                         nmp->nm_acregmin, nmp->nm_acregmax,
920                         nmp->nm_acdirmin, nmp->nm_acdirmax);
921
922         if (nfs_acdebug)
923                 kprintf("nfs_getattrcache: age = %d; final timeo = %d\n",
924                         (int)(time_second - np->n_attrstamp), timeo);
925 #endif
926
927         if (np->n_attrstamp == 0 || (time_second - np->n_attrstamp) >= timeo) {
928                 nfsstats.attrcache_misses++;
929                 return (ENOENT);
930         }
931         nfsstats.attrcache_hits++;
932
933         /*
934          * Our attribute cache can be stale due to modifications made on
935          * this host.  XXX this is a bad hack.  We need a more deterministic
936          * means of finding out which np fields are valid verses attr cache
937          * fields.  We really should update the vattr info on the fly when
938          * making local changes.
939          */
940         if (vap->va_size != np->n_size) {
941                 if (vap->va_type == VREG) {
942                         if (np->n_flag & NLMODIFIED)
943                                 vap->va_size = np->n_size;
944                         nfs_meta_setsize(vp, curthread, vap->va_size, 0);
945                 } else {
946                         np->n_size = vap->va_size;
947                 }
948         }
949         bcopy((caddr_t)vap, (caddr_t)vaper, sizeof(struct vattr));
950         if (np->n_flag & NCHG) {
951                 if (np->n_flag & NACC)
952                         vaper->va_atime = np->n_atim;
953                 if (np->n_flag & NUPD)
954                         vaper->va_mtime = np->n_mtim;
955         }
956         return (0);
957 }
958
959 #ifndef NFS_NOSERVER
960
961 /*
962  * Set up nameidata for a lookup() call and do it.
963  *
964  * If pubflag is set, this call is done for a lookup operation on the
965  * public filehandle. In that case we allow crossing mountpoints and
966  * absolute pathnames. However, the caller is expected to check that
967  * the lookup result is within the public fs, and deny access if
968  * it is not.
969  *
970  * dirp may be set whether an error is returned or not, and must be 
971  * released by the caller.
972  *
973  * On return nd->nl_nch usually points to the target ncp, which may represent
974  * a negative hit.
975  *
976  * NOTE: the caller must call nlookup_done(nd) unconditionally on return
977  * to cleanup.
978  */
979 int
980 nfs_namei(struct nlookupdata *nd, struct ucred *cred, int nflags,
981         struct vnode **dvpp, struct vnode **vpp,
982         fhandle_t *fhp, int len,
983         struct nfssvc_sock *slp, struct sockaddr *nam, struct mbuf **mdp,
984         caddr_t *dposp, struct vnode **dirpp, struct thread *td,
985         int kerbflag, int pubflag)
986 {
987         int i, rem;
988         struct mbuf *md;
989         char *fromcp, *tocp, *cp;
990         char *namebuf;
991         struct nchandle nch;
992         struct vnode *dp;
993         struct mount *mp;
994         int error, rdonly;
995
996         namebuf = objcache_get(namei_oc, M_WAITOK);
997         *dirpp = NULL;
998
999         /*
1000          * Copy the name from the mbuf list to namebuf.
1001          */
1002         fromcp = *dposp;
1003         tocp = namebuf;
1004         md = *mdp;
1005         rem = mtod(md, caddr_t) + md->m_len - fromcp;
1006         for (i = 0; i < len; i++) {
1007                 while (rem == 0) {
1008                         md = md->m_next;
1009                         if (md == NULL) {
1010                                 error = EBADRPC;
1011                                 goto out;
1012                         }
1013                         fromcp = mtod(md, caddr_t);
1014                         rem = md->m_len;
1015                 }
1016                 if (*fromcp == '\0' || (!pubflag && *fromcp == '/')) {
1017                         error = EACCES;
1018                         goto out;
1019                 }
1020                 *tocp++ = *fromcp++;
1021                 rem--;
1022         }
1023         *tocp = '\0';
1024         *mdp = md;
1025         *dposp = fromcp;
1026         len = nfsm_rndup(len)-len;
1027         if (len > 0) {
1028                 if (rem >= len)
1029                         *dposp += len;
1030                 else if ((error = nfs_adv(mdp, dposp, len, rem)) != 0)
1031                         goto out;
1032         }
1033
1034         /*
1035          * Extract and set starting directory.  The returned dp is refd
1036          * but not locked.
1037          */
1038         error = nfsrv_fhtovp(fhp, FALSE, &mp, &dp, cred, slp,
1039                                 nam, &rdonly, kerbflag, pubflag);
1040         if (error)
1041                 goto out;
1042         if (dp->v_type != VDIR) {
1043                 vrele(dp);
1044                 error = ENOTDIR;
1045                 goto out;
1046         }
1047
1048         /*
1049          * Set return directory.  Reference to dp is implicitly transfered 
1050          * to the returned pointer.  This must be set before we potentially
1051          * goto out below.
1052          */
1053         *dirpp = dp;
1054
1055         /*
1056          * read-only - NLC_DELETE, NLC_RENAME_DST are disallowed.  NLC_CREATE
1057          *             is passed through to nlookup() and will be disallowed
1058          *             if the file does not already exist.
1059          */
1060         if (rdonly) {
1061                 nflags |= NLC_NFS_RDONLY;
1062                 if (nflags & (NLC_DELETE | NLC_RENAME_DST)) {
1063                         error = EROFS;
1064                         goto out;
1065                 }
1066         }
1067
1068         /*
1069          * Oh joy. For WebNFS, handle those pesky '%' escapes,
1070          * and the 'native path' indicator.
1071          */
1072         if (pubflag) {
1073                 cp = objcache_get(namei_oc, M_WAITOK);
1074                 fromcp = namebuf;
1075                 tocp = cp;
1076                 if ((unsigned char)*fromcp >= WEBNFS_SPECCHAR_START) {
1077                         switch ((unsigned char)*fromcp) {
1078                         case WEBNFS_NATIVE_CHAR:
1079                                 /*
1080                                  * 'Native' path for us is the same
1081                                  * as a path according to the NFS spec,
1082                                  * just skip the escape char.
1083                                  */
1084                                 fromcp++;
1085                                 break;
1086                         /*
1087                          * More may be added in the future, range 0x80-0xff
1088                          */
1089                         default:
1090                                 error = EIO;
1091                                 objcache_put(namei_oc, cp);
1092                                 goto out;
1093                         }
1094                 }
1095                 /*
1096                  * Translate the '%' escapes, URL-style.
1097                  */
1098                 while (*fromcp != '\0') {
1099                         if (*fromcp == WEBNFS_ESC_CHAR) {
1100                                 if (fromcp[1] != '\0' && fromcp[2] != '\0') {
1101                                         fromcp++;
1102                                         *tocp++ = HEXSTRTOI(fromcp);
1103                                         fromcp += 2;
1104                                         continue;
1105                                 } else {
1106                                         error = ENOENT;
1107                                         objcache_put(namei_oc, cp);
1108                                         goto out;
1109                                 }
1110                         } else
1111                                 *tocp++ = *fromcp++;
1112                 }
1113                 *tocp = '\0';
1114                 objcache_put(namei_oc, namebuf);
1115                 namebuf = cp;
1116         }
1117
1118         /*
1119          * Setup for search.  We need to get a start directory from dp.  Note
1120          * that dp is ref'd, but we no longer 'own' the ref (*dirpp owns it).
1121          */
1122         if (pubflag == 0) {
1123                 nflags |= NLC_NFS_NOSOFTLINKTRAV;
1124                 nflags |= NLC_NOCROSSMOUNT;
1125         }
1126
1127         /*
1128          * We need a starting ncp from the directory vnode dp.  dp must not
1129          * be locked.  The returned ncp will be refd but not locked. 
1130          *
1131          * If no suitable ncp is found we instruct cache_fromdvp() to create
1132          * one.  If this fails the directory has probably been removed while
1133          * the target was chdir'd into it and any further lookup will fail.
1134          */
1135         if ((error = cache_fromdvp(dp, cred, 1, &nch)) != 0)
1136                 goto out;
1137         nlookup_init_raw(nd, namebuf, UIO_SYSSPACE, nflags, cred, &nch);
1138         cache_drop(&nch);
1139
1140         /*
1141          * Ok, do the lookup.
1142          */
1143         error = nlookup(nd);
1144
1145         /*
1146          * If no error occured return the requested dvpp and vpp.  If
1147          * NLC_CREATE was specified nd->nl_nch may represent a negative
1148          * cache hit in which case we do not attempt to obtain the vp.
1149          */
1150         if (error == 0) {
1151                 if (dvpp) {
1152                         if (nd->nl_nch.ncp->nc_parent) {
1153                                 nch = nd->nl_nch;
1154                                 nch.ncp = nch.ncp->nc_parent;
1155                                 cache_hold(&nch);
1156                                 cache_lock(&nch);
1157                                 error = cache_vget(&nch, nd->nl_cred,
1158                                                    LK_EXCLUSIVE, dvpp);
1159                                 cache_put(&nch);
1160                         } else {
1161                                 error = ENXIO;
1162                         }
1163                 }
1164                 if (vpp && nd->nl_nch.ncp->nc_vp) {
1165                         error = cache_vget(&nd->nl_nch, nd->nl_cred, LK_EXCLUSIVE, vpp);
1166                 }
1167                 if (error) {
1168                         if (dvpp && *dvpp) {
1169                                 vput(*dvpp);
1170                                 *dvpp = NULL;
1171                         }
1172                         if (vpp && *vpp) {
1173                                 vput(*vpp);
1174                                 *vpp = NULL;
1175                         }
1176                 }
1177         }
1178
1179         /*
1180          * Finish up.
1181          */
1182 out:
1183         objcache_put(namei_oc, namebuf);
1184         return (error);
1185 }
1186
1187 /*
1188  * nfsrv_fhtovp() - convert a fh to a vnode ptr (optionally locked)
1189  *      - look up fsid in mount list (if not found ret error)
1190  *      - get vp and export rights by calling VFS_FHTOVP()
1191  *      - if cred->cr_uid == 0 or MNT_EXPORTANON set it to credanon
1192  *      - if not lockflag unlock it with vn_unlock()
1193  */
1194 int
1195 nfsrv_fhtovp(fhandle_t *fhp, int lockflag,
1196              struct mount **mpp, struct vnode **vpp,
1197              struct ucred *cred, struct nfssvc_sock *slp, struct sockaddr *nam,
1198              int *rdonlyp, int kerbflag, int pubflag)
1199 {
1200         struct mount *mp;
1201         int i;
1202         struct ucred *credanon;
1203         int error, exflags;
1204 #ifdef MNT_EXNORESPORT          /* XXX needs mountd and /etc/exports help yet */
1205         struct sockaddr_int *saddr;
1206 #endif
1207
1208         *vpp = NULL;
1209         *mpp = NULL;
1210
1211         if (nfs_ispublicfh(fhp)) {
1212                 if (!pubflag || !nfs_pub.np_valid)
1213                         return (ESTALE);
1214                 fhp = &nfs_pub.np_handle;
1215         }
1216
1217         mp = *mpp = vfs_getvfs(&fhp->fh_fsid);
1218         if (mp == NULL)
1219                 return (ESTALE);
1220         error = VFS_CHECKEXP(mp, nam, &exflags, &credanon);
1221         if (error)
1222                 return (error); 
1223         error = VFS_FHTOVP(mp, NULL, &fhp->fh_fid, vpp);
1224         if (error)
1225                 return (error);
1226 #ifdef MNT_EXNORESPORT
1227         if (!(exflags & (MNT_EXNORESPORT|MNT_EXPUBLIC))) {
1228                 saddr = (struct sockaddr_in *)nam;
1229                 if (saddr->sin_family == AF_INET &&
1230                     ntohs(saddr->sin_port) >= IPPORT_RESERVED) {
1231                         vput(*vpp);
1232                         *vpp = NULL;
1233                         return (NFSERR_AUTHERR | AUTH_TOOWEAK);
1234                 }
1235         }
1236 #endif
1237         /*
1238          * Check/setup credentials.
1239          */
1240         if (exflags & MNT_EXKERB) {
1241                 if (!kerbflag) {
1242                         vput(*vpp);
1243                         *vpp = NULL;
1244                         return (NFSERR_AUTHERR | AUTH_TOOWEAK);
1245                 }
1246         } else if (kerbflag) {
1247                 vput(*vpp);
1248                 *vpp = NULL;
1249                 return (NFSERR_AUTHERR | AUTH_TOOWEAK);
1250         } else if (cred->cr_uid == 0 || (exflags & MNT_EXPORTANON)) {
1251                 cred->cr_uid = credanon->cr_uid;
1252                 for (i = 0; i < credanon->cr_ngroups && i < NGROUPS; i++)
1253                         cred->cr_groups[i] = credanon->cr_groups[i];
1254                 cred->cr_ngroups = i;
1255         }
1256         if (exflags & MNT_EXRDONLY)
1257                 *rdonlyp = 1;
1258         else
1259                 *rdonlyp = 0;
1260
1261         if (!lockflag)
1262                 vn_unlock(*vpp);
1263         return (0);
1264 }
1265
1266 /*
1267  * WebNFS: check if a filehandle is a public filehandle. For v3, this
1268  * means a length of 0, for v2 it means all zeroes. nfsm_srvmtofh has
1269  * transformed this to all zeroes in both cases, so check for it.
1270  */
1271 int
1272 nfs_ispublicfh(fhandle_t *fhp)
1273 {
1274         char *cp = (char *)fhp;
1275         int i;
1276
1277         for (i = 0; i < NFSX_V3FH; i++)
1278                 if (*cp++ != 0)
1279                         return (FALSE);
1280         return (TRUE);
1281 }
1282   
1283 #endif /* NFS_NOSERVER */
1284 /*
1285  * This function compares two net addresses by family and returns TRUE
1286  * if they are the same host.
1287  * If there is any doubt, return FALSE.
1288  * The AF_INET family is handled as a special case so that address mbufs
1289  * don't need to be saved to store "struct in_addr", which is only 4 bytes.
1290  */
1291 int
1292 netaddr_match(int family, union nethostaddr *haddr, struct sockaddr *nam)
1293 {
1294         struct sockaddr_in *inetaddr;
1295
1296         switch (family) {
1297         case AF_INET:
1298                 inetaddr = (struct sockaddr_in *)nam;
1299                 if (inetaddr->sin_family == AF_INET &&
1300                     inetaddr->sin_addr.s_addr == haddr->had_inetaddr)
1301                         return (1);
1302                 break;
1303         default:
1304                 break;
1305         };
1306         return (0);
1307 }
1308
1309 static nfsuint64 nfs_nullcookie = { { 0, 0 } };
1310 /*
1311  * This function finds the directory cookie that corresponds to the
1312  * logical byte offset given.
1313  */
1314 nfsuint64 *
1315 nfs_getcookie(struct nfsnode *np, off_t off, int add)
1316 {
1317         struct nfsdmap *dp, *dp2;
1318         int pos;
1319
1320         pos = (uoff_t)off / NFS_DIRBLKSIZ;
1321         if (pos == 0 || off < 0) {
1322 #ifdef DIAGNOSTIC
1323                 if (add)
1324                         panic("nfs getcookie add at <= 0");
1325 #endif
1326                 return (&nfs_nullcookie);
1327         }
1328         pos--;
1329         dp = np->n_cookies.lh_first;
1330         if (!dp) {
1331                 if (add) {
1332                         MALLOC(dp, struct nfsdmap *, sizeof (struct nfsdmap),
1333                                 M_NFSDIROFF, M_WAITOK);
1334                         dp->ndm_eocookie = 0;
1335                         LIST_INSERT_HEAD(&np->n_cookies, dp, ndm_list);
1336                 } else
1337                         return (NULL);
1338         }
1339         while (pos >= NFSNUMCOOKIES) {
1340                 pos -= NFSNUMCOOKIES;
1341                 if (dp->ndm_list.le_next) {
1342                         if (!add && dp->ndm_eocookie < NFSNUMCOOKIES &&
1343                                 pos >= dp->ndm_eocookie)
1344                                 return (NULL);
1345                         dp = dp->ndm_list.le_next;
1346                 } else if (add) {
1347                         MALLOC(dp2, struct nfsdmap *, sizeof (struct nfsdmap),
1348                                 M_NFSDIROFF, M_WAITOK);
1349                         dp2->ndm_eocookie = 0;
1350                         LIST_INSERT_AFTER(dp, dp2, ndm_list);
1351                         dp = dp2;
1352                 } else
1353                         return (NULL);
1354         }
1355         if (pos >= dp->ndm_eocookie) {
1356                 if (add)
1357                         dp->ndm_eocookie = pos + 1;
1358                 else
1359                         return (NULL);
1360         }
1361         return (&dp->ndm_cookies[pos]);
1362 }
1363
1364 /*
1365  * Invalidate cached directory information, except for the actual directory
1366  * blocks (which are invalidated separately).
1367  * Done mainly to avoid the use of stale offset cookies.
1368  */
1369 void
1370 nfs_invaldir(struct vnode *vp)
1371 {
1372         struct nfsnode *np = VTONFS(vp);
1373
1374 #ifdef DIAGNOSTIC
1375         if (vp->v_type != VDIR)
1376                 panic("nfs: invaldir not dir");
1377 #endif
1378         np->n_direofoffset = 0;
1379         np->n_cookieverf.nfsuquad[0] = 0;
1380         np->n_cookieverf.nfsuquad[1] = 0;
1381         if (np->n_cookies.lh_first)
1382                 np->n_cookies.lh_first->ndm_eocookie = 0;
1383 }
1384
1385 /*
1386  * Set the v_type field for an NFS client's vnode and initialize for
1387  * buffer cache operations if necessary.
1388  */
1389 void
1390 nfs_setvtype(struct vnode *vp, enum vtype vtyp)
1391 {
1392         vp->v_type = vtyp;
1393
1394         switch(vtyp) {
1395         case VREG:
1396         case VDIR:
1397         case VLNK:
1398                 /*
1399                  * Needs VMIO, size not yet known, and blocksize
1400                  * is not really relevant if we are passing a
1401                  * filesize of 0.
1402                  */
1403                 vinitvmio(vp, 0, PAGE_SIZE, -1);
1404                 break;
1405         default:
1406                 break;
1407         }
1408 }
1409
1410 /*
1411  * The write verifier has changed (probably due to a server reboot), so all
1412  * B_NEEDCOMMIT blocks will have to be written again. Since they are on the
1413  * dirty block list as B_DELWRI, all this takes is clearing the B_NEEDCOMMIT
1414  * and B_CLUSTEROK flags.  Once done the new write verifier can be set for the
1415  * mount point.
1416  *
1417  * B_CLUSTEROK must be cleared along with B_NEEDCOMMIT because stage 1 data 
1418  * writes are not clusterable.
1419  */
1420
1421 static int nfs_clearcommit_bp(struct buf *bp, void *data __unused);
1422 static int nfs_clearcommit_callback(struct mount *mp, struct vnode *vp,
1423                                     void *data __unused);
1424
1425 void
1426 nfs_clearcommit(struct mount *mp)
1427 {
1428         vmntvnodescan(mp, VMSC_NOWAIT, nfs_clearcommit_callback, NULL, NULL);
1429 }
1430
1431 static int
1432 nfs_clearcommit_callback(struct mount *mp, struct vnode *vp,
1433                          void *data __unused)
1434 {
1435         vhold(vp);
1436         lwkt_gettoken(&vp->v_token);
1437         RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
1438                 nfs_clearcommit_bp, NULL);
1439         lwkt_reltoken(&vp->v_token);
1440         vdrop(vp);
1441         return(0);
1442 }
1443
1444 static int
1445 nfs_clearcommit_bp(struct buf *bp, void *data __unused)
1446 {
1447         if (BUF_REFCNT(bp) == 0 &&
1448             (bp->b_flags & (B_DELWRI | B_NEEDCOMMIT))
1449              == (B_DELWRI | B_NEEDCOMMIT)) {
1450                 bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1451         }
1452         return(0);
1453 }
1454
1455 #ifndef NFS_NOSERVER
1456 /*
1457  * Map errnos to NFS error numbers. For Version 3 also filter out error
1458  * numbers not specified for the associated procedure.
1459  */
1460 int
1461 nfsrv_errmap(struct nfsrv_descript *nd, int err)
1462 {
1463         short *defaulterrp, *errp;
1464
1465         if (nd->nd_flag & ND_NFSV3) {
1466             if (nd->nd_procnum <= NFSPROC_COMMIT) {
1467                 errp = defaulterrp = nfsrv_v3errmap[nd->nd_procnum];
1468                 while (*++errp) {
1469                         if (*errp == err)
1470                                 return (err);
1471                         else if (*errp > err)
1472                                 break;
1473                 }
1474                 return ((int)*defaulterrp);
1475             } else
1476                 return (err & 0xffff);
1477         }
1478         if (err <= ELAST)
1479                 return ((int)nfsrv_v2errmap[err - 1]);
1480         return (NFSERR_IO);
1481 }
1482
1483 /*
1484  * Sort the group list in increasing numerical order.
1485  * (Insertion sort by Chris Torek, who was grossed out by the bubble sort
1486  *  that used to be here.)
1487  */
1488 void
1489 nfsrvw_sort(gid_t *list, int num)
1490 {
1491         int i, j;
1492         gid_t v;
1493
1494         /* Insertion sort. */
1495         for (i = 1; i < num; i++) {
1496                 v = list[i];
1497                 /* find correct slot for value v, moving others up */
1498                 for (j = i; --j >= 0 && v < list[j];)
1499                         list[j + 1] = list[j];
1500                 list[j + 1] = v;
1501         }
1502 }
1503
1504 /*
1505  * copy credentials making sure that the result can be compared with bcmp().
1506  */
1507 void
1508 nfsrv_setcred(struct ucred *incred, struct ucred *outcred)
1509 {
1510         int i;
1511
1512         bzero((caddr_t)outcred, sizeof (struct ucred));
1513         outcred->cr_ref = 1;
1514         outcred->cr_uid = incred->cr_uid;
1515         outcred->cr_ngroups = incred->cr_ngroups;
1516         for (i = 0; i < incred->cr_ngroups; i++)
1517                 outcred->cr_groups[i] = incred->cr_groups[i];
1518         nfsrvw_sort(outcred->cr_groups, outcred->cr_ngroups);
1519 }
1520 #endif /* NFS_NOSERVER */