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