xref: /titanic_50/usr/src/uts/common/fs/nfs/nfs4_subr.c (revision 108322fb1c3ed341aba9c80c9774df0ed9e35768)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  *  	Copyright (c) 1983,1984,1985,1986,1987,1988,1989  AT&T.
29  *	All Rights Reserved
30  */
31 
32 #pragma ident	"%Z%%M%	%I%	%E% SMI"
33 
34 #include <sys/param.h>
35 #include <sys/types.h>
36 #include <sys/systm.h>
37 #include <sys/cmn_err.h>
38 #include <sys/vtrace.h>
39 #include <sys/session.h>
40 #include <sys/thread.h>
41 #include <sys/dnlc.h>
42 #include <sys/cred.h>
43 #include <sys/list.h>
44 #include <sys/sdt.h>
45 
46 #include <rpc/types.h>
47 #include <rpc/xdr.h>
48 
49 #include <nfs/nfs.h>
50 
51 #include <nfs/nfs_clnt.h>
52 
53 #include <nfs/nfs4.h>
54 #include <nfs/rnode4.h>
55 #include <nfs/nfs4_clnt.h>
56 
57 /*
58  * client side statistics
59  */
60 static const struct clstat4 clstat4_tmpl = {
61 	{ "calls",	KSTAT_DATA_UINT64 },
62 	{ "badcalls",	KSTAT_DATA_UINT64 },
63 	{ "clgets",	KSTAT_DATA_UINT64 },
64 	{ "cltoomany",	KSTAT_DATA_UINT64 },
65 #ifdef DEBUG
66 	{ "clalloc",	KSTAT_DATA_UINT64 },
67 	{ "noresponse",	KSTAT_DATA_UINT64 },
68 	{ "failover",	KSTAT_DATA_UINT64 },
69 	{ "remap",	KSTAT_DATA_UINT64 },
70 #endif
71 };
72 
73 #ifdef DEBUG
74 struct clstat4_debug clstat4_debug = {
75 	{ "nrnode",	KSTAT_DATA_UINT64 },
76 	{ "access",	KSTAT_DATA_UINT64 },
77 	{ "dirent",	KSTAT_DATA_UINT64 },
78 	{ "dirents",	KSTAT_DATA_UINT64 },
79 	{ "reclaim",	KSTAT_DATA_UINT64 },
80 	{ "clreclaim",	KSTAT_DATA_UINT64 },
81 	{ "f_reclaim",	KSTAT_DATA_UINT64 },
82 	{ "a_reclaim",	KSTAT_DATA_UINT64 },
83 	{ "r_reclaim",	KSTAT_DATA_UINT64 },
84 	{ "r_path",	KSTAT_DATA_UINT64 },
85 };
86 #endif
87 
88 /*
89  * We keep a global list of per-zone client data, so we can clean up all zones
90  * if we get low on memory.
91  */
92 static list_t nfs4_clnt_list;
93 static kmutex_t nfs4_clnt_list_lock;
94 static zone_key_t nfs4clnt_zone_key;
95 
96 static struct kmem_cache *chtab4_cache;
97 
98 #ifdef DEBUG
99 static int nfs4_rfscall_debug;
100 static int nfs4_try_failover_any;
101 int nfs4_utf8_debug = 0;
102 #endif
103 
104 /*
105  * NFSv4 readdir cache implementation
106  */
107 typedef struct rddir4_cache_impl {
108 	rddir4_cache	rc;		/* readdir cache element */
109 	kmutex_t	lock;		/* lock protects count */
110 	uint_t		count;		/* reference count */
111 	avl_node_t	tree;		/* AVL tree link */
112 } rddir4_cache_impl;
113 
114 static int rddir4_cache_compar(const void *, const void *);
115 static void rddir4_cache_free(rddir4_cache_impl *);
116 static rddir4_cache *rddir4_cache_alloc(int);
117 static void rddir4_cache_hold(rddir4_cache *);
118 static int try_failover(enum clnt_stat);
119 
120 static int nfs4_readdir_cache_hits = 0;
121 static int nfs4_readdir_cache_waits = 0;
122 static int nfs4_readdir_cache_misses = 0;
123 
124 /*
125  * Shared nfs4 functions
126  */
127 
128 /*
129  * Copy an nfs_fh4.  The destination storage (to->nfs_fh4_val) must already
130  * be allocated.
131  */
132 
133 void
134 nfs_fh4_copy(nfs_fh4 *from, nfs_fh4 *to)
135 {
136 	to->nfs_fh4_len = from->nfs_fh4_len;
137 	bcopy(from->nfs_fh4_val, to->nfs_fh4_val, to->nfs_fh4_len);
138 }
139 
140 /*
141  * nfs4cmpfh - compare 2 filehandles.
142  * Returns 0 if the two nfsv4 filehandles are the same, -1 if the first is
143  * "less" than the second, +1 if the first is "greater" than the second.
144  */
145 
146 int
147 nfs4cmpfh(const nfs_fh4 *fh4p1, const nfs_fh4 *fh4p2)
148 {
149 	const char *c1, *c2;
150 
151 	if (fh4p1->nfs_fh4_len < fh4p2->nfs_fh4_len)
152 		return (-1);
153 	if (fh4p1->nfs_fh4_len > fh4p2->nfs_fh4_len)
154 		return (1);
155 	for (c1 = fh4p1->nfs_fh4_val, c2 = fh4p2->nfs_fh4_val;
156 	    c1 < fh4p1->nfs_fh4_val + fh4p1->nfs_fh4_len;
157 	    c1++, c2++) {
158 		if (*c1 < *c2)
159 			return (-1);
160 		if (*c1 > *c2)
161 			return (1);
162 	}
163 
164 	return (0);
165 }
166 
167 /*
168  * Compare two v4 filehandles.  Return zero if they're the same, non-zero
169  * if they're not.  Like nfs4cmpfh(), but different filehandle
170  * representation, and doesn't provide information about greater than or
171  * less than.
172  */
173 
174 int
175 nfs4cmpfhandle(nfs4_fhandle_t *fh1, nfs4_fhandle_t *fh2)
176 {
177 	if (fh1->fh_len == fh2->fh_len)
178 		return (bcmp(fh1->fh_buf, fh2->fh_buf, fh1->fh_len));
179 
180 	return (1);
181 }
182 
183 int
184 stateid4_cmp(stateid4 *s1, stateid4 *s2)
185 {
186 	if (bcmp(s1, s2, sizeof (stateid4)) == 0)
187 		return (1);
188 	else
189 		return (0);
190 }
191 
192 nfsstat4
193 puterrno4(int error)
194 {
195 	switch (error) {
196 	case 0:
197 		return (NFS4_OK);
198 	case EPERM:
199 		return (NFS4ERR_PERM);
200 	case ENOENT:
201 		return (NFS4ERR_NOENT);
202 	case EINTR:
203 		return (NFS4ERR_IO);
204 	case EIO:
205 		return (NFS4ERR_IO);
206 	case ENXIO:
207 		return (NFS4ERR_NXIO);
208 	case ENOMEM:
209 		return (NFS4ERR_RESOURCE);
210 	case EACCES:
211 		return (NFS4ERR_ACCESS);
212 	case EBUSY:
213 		return (NFS4ERR_IO);
214 	case EEXIST:
215 		return (NFS4ERR_EXIST);
216 	case EXDEV:
217 		return (NFS4ERR_XDEV);
218 	case ENODEV:
219 		return (NFS4ERR_IO);
220 	case ENOTDIR:
221 		return (NFS4ERR_NOTDIR);
222 	case EISDIR:
223 		return (NFS4ERR_ISDIR);
224 	case EINVAL:
225 		return (NFS4ERR_INVAL);
226 	case EMFILE:
227 		return (NFS4ERR_RESOURCE);
228 	case EFBIG:
229 		return (NFS4ERR_FBIG);
230 	case ENOSPC:
231 		return (NFS4ERR_NOSPC);
232 	case EROFS:
233 		return (NFS4ERR_ROFS);
234 	case EMLINK:
235 		return (NFS4ERR_MLINK);
236 	case EDEADLK:
237 		return (NFS4ERR_DEADLOCK);
238 	case ENOLCK:
239 		return (NFS4ERR_DENIED);
240 	case EREMOTE:
241 		return (NFS4ERR_SERVERFAULT);
242 	case ENOTSUP:
243 		return (NFS4ERR_NOTSUPP);
244 	case EDQUOT:
245 		return (NFS4ERR_DQUOT);
246 	case ENAMETOOLONG:
247 		return (NFS4ERR_NAMETOOLONG);
248 	case EOVERFLOW:
249 		return (NFS4ERR_INVAL);
250 	case ENOSYS:
251 		return (NFS4ERR_NOTSUPP);
252 	case ENOTEMPTY:
253 		return (NFS4ERR_NOTEMPTY);
254 	case EOPNOTSUPP:
255 		return (NFS4ERR_NOTSUPP);
256 	case ESTALE:
257 		return (NFS4ERR_STALE);
258 	case EAGAIN:
259 		if (curthread->t_flag & T_WOULDBLOCK) {
260 			curthread->t_flag &= ~T_WOULDBLOCK;
261 			return (NFS4ERR_DELAY);
262 		}
263 		return (NFS4ERR_LOCKED);
264 	default:
265 		return ((enum nfsstat4)error);
266 	}
267 }
268 
269 int
270 geterrno4(enum nfsstat4 status)
271 {
272 	switch (status) {
273 	case NFS4_OK:
274 		return (0);
275 	case NFS4ERR_PERM:
276 		return (EPERM);
277 	case NFS4ERR_NOENT:
278 		return (ENOENT);
279 	case NFS4ERR_IO:
280 		return (EIO);
281 	case NFS4ERR_NXIO:
282 		return (ENXIO);
283 	case NFS4ERR_ACCESS:
284 		return (EACCES);
285 	case NFS4ERR_EXIST:
286 		return (EEXIST);
287 	case NFS4ERR_XDEV:
288 		return (EXDEV);
289 	case NFS4ERR_NOTDIR:
290 		return (ENOTDIR);
291 	case NFS4ERR_ISDIR:
292 		return (EISDIR);
293 	case NFS4ERR_INVAL:
294 		return (EINVAL);
295 	case NFS4ERR_FBIG:
296 		return (EFBIG);
297 	case NFS4ERR_NOSPC:
298 		return (ENOSPC);
299 	case NFS4ERR_ROFS:
300 		return (EROFS);
301 	case NFS4ERR_MLINK:
302 		return (EMLINK);
303 	case NFS4ERR_NAMETOOLONG:
304 		return (ENAMETOOLONG);
305 	case NFS4ERR_NOTEMPTY:
306 		return (ENOTEMPTY);
307 	case NFS4ERR_DQUOT:
308 		return (EDQUOT);
309 	case NFS4ERR_STALE:
310 		return (ESTALE);
311 	case NFS4ERR_BADHANDLE:
312 		return (ESTALE);
313 	case NFS4ERR_BAD_COOKIE:
314 		return (EINVAL);
315 	case NFS4ERR_NOTSUPP:
316 		return (EOPNOTSUPP);
317 	case NFS4ERR_TOOSMALL:
318 		return (EINVAL);
319 	case NFS4ERR_SERVERFAULT:
320 		return (EIO);
321 	case NFS4ERR_BADTYPE:
322 		return (EINVAL);
323 	case NFS4ERR_DELAY:
324 		return (ENXIO);
325 	case NFS4ERR_SAME:
326 		return (EPROTO);
327 	case NFS4ERR_DENIED:
328 		return (ENOLCK);
329 	case NFS4ERR_EXPIRED:
330 		return (EPROTO);
331 	case NFS4ERR_LOCKED:
332 		return (EACCES);
333 	case NFS4ERR_GRACE:
334 		return (EAGAIN);
335 	case NFS4ERR_FHEXPIRED:	/* if got here, failed to get a new fh */
336 		return (ESTALE);
337 	case NFS4ERR_SHARE_DENIED:
338 		return (EACCES);
339 	case NFS4ERR_WRONGSEC:
340 		return (EPERM);
341 	case NFS4ERR_CLID_INUSE:
342 		return (EAGAIN);
343 	case NFS4ERR_RESOURCE:
344 		return (EAGAIN);
345 	case NFS4ERR_MOVED:
346 		return (EPROTO);
347 	case NFS4ERR_NOFILEHANDLE:
348 		return (EIO);
349 	case NFS4ERR_MINOR_VERS_MISMATCH:
350 		return (ENOTSUP);
351 	case NFS4ERR_STALE_CLIENTID:
352 		return (EIO);
353 	case NFS4ERR_STALE_STATEID:
354 		return (EIO);
355 	case NFS4ERR_OLD_STATEID:
356 		return (EIO);
357 	case NFS4ERR_BAD_STATEID:
358 		return (EIO);
359 	case NFS4ERR_BAD_SEQID:
360 		return (EIO);
361 	case NFS4ERR_NOT_SAME:
362 		return (EPROTO);
363 	case NFS4ERR_LOCK_RANGE:
364 		return (EPROTO);
365 	case NFS4ERR_SYMLINK:
366 		return (EPROTO);
367 	case NFS4ERR_RESTOREFH:
368 		return (EPROTO);
369 	case NFS4ERR_LEASE_MOVED:
370 		return (EPROTO);
371 	case NFS4ERR_ATTRNOTSUPP:
372 		return (ENOTSUP);
373 	case NFS4ERR_NO_GRACE:
374 		return (EPROTO);
375 	case NFS4ERR_RECLAIM_BAD:
376 		return (EPROTO);
377 	case NFS4ERR_RECLAIM_CONFLICT:
378 		return (EPROTO);
379 	case NFS4ERR_BADXDR:
380 		return (EINVAL);
381 	case NFS4ERR_LOCKS_HELD:
382 		return (EIO);
383 	case NFS4ERR_OPENMODE:
384 		return (EACCES);
385 	case NFS4ERR_BADOWNER:
386 		/*
387 		 * Client and server are in different DNS domains
388 		 * and the NFSMAPID_DOMAIN in /etc/default/nfs
389 		 * doesn't match.  No good answer here.  Return
390 		 * EACCESS, which translates to "permission denied".
391 		 */
392 		return (EACCES);
393 	case NFS4ERR_BADCHAR:
394 		return (EINVAL);
395 	case NFS4ERR_BADNAME:
396 		return (EINVAL);
397 	case NFS4ERR_BAD_RANGE:
398 		return (EIO);
399 	case NFS4ERR_LOCK_NOTSUPP:
400 		return (ENOTSUP);
401 	case NFS4ERR_OP_ILLEGAL:
402 		return (EINVAL);
403 	case NFS4ERR_DEADLOCK:
404 		return (EDEADLK);
405 	case NFS4ERR_FILE_OPEN:
406 		return (EACCES);
407 	case NFS4ERR_ADMIN_REVOKED:
408 		return (EPROTO);
409 	case NFS4ERR_CB_PATH_DOWN:
410 		return (EPROTO);
411 	default:
412 #ifdef DEBUG
413 		zcmn_err(getzoneid(), CE_WARN, "geterrno4: got status %d",
414 		    status);
415 #endif
416 		return ((int)status);
417 	}
418 }
419 
420 void
421 nfs4_log_badowner(mntinfo4_t *mi, nfs_opnum4 op)
422 {
423 	nfs4_server_t *server;
424 
425 	/*
426 	 * Return if already printed/queued a msg
427 	 * for this mount point.
428 	 */
429 	if (mi->mi_flags & MI4_BADOWNER_DEBUG)
430 		return;
431 	/*
432 	 * Happens once per client <-> server pair.
433 	 */
434 	if (nfs_rw_enter_sig(&mi->mi_recovlock, RW_READER,
435 		mi->mi_flags & MI4_INT))
436 		return;
437 
438 	server = find_nfs4_server(mi);
439 	if (server == NULL) {
440 		nfs_rw_exit(&mi->mi_recovlock);
441 		return;
442 	}
443 
444 	if (!(server->s_flags & N4S_BADOWNER_DEBUG)) {
445 		zcmn_err(mi->mi_zone->zone_id, CE_WARN,
446 		    "!NFSMAPID_DOMAIN does not match"
447 		    " the server: %s domain.\n"
448 		    "Please check configuration",
449 		    mi->mi_curr_serv->sv_hostname);
450 		server->s_flags |= N4S_BADOWNER_DEBUG;
451 	}
452 	mutex_exit(&server->s_lock);
453 	nfs4_server_rele(server);
454 	nfs_rw_exit(&mi->mi_recovlock);
455 
456 	/*
457 	 * Happens once per mntinfo4_t.
458 	 * This error is deemed as one of the recovery facts "RF_BADOWNER",
459 	 * queue this in the mesg queue for this mount_info. This message
460 	 * is not printed, meaning its absent from id_to_dump_solo_fact()
461 	 * but its there for inspection if the queue is ever dumped/inspected.
462 	 */
463 	mutex_enter(&mi->mi_lock);
464 	if (!(mi->mi_flags & MI4_BADOWNER_DEBUG)) {
465 		nfs4_queue_fact(RF_BADOWNER, mi, NFS4ERR_BADOWNER, 0, op,
466 		    FALSE, NULL, 0, NULL);
467 		mi->mi_flags |= MI4_BADOWNER_DEBUG;
468 	}
469 	mutex_exit(&mi->mi_lock);
470 }
471 
472 
473 
474 int
475 nfs4_time_ntov(nfstime4 *ntime, timestruc_t *vatime)
476 {
477 	int64_t sec;
478 	int32_t nsec;
479 
480 	/*
481 	 * Here check that the nfsv4 time is valid for the system.
482 	 * nfsv4 time value is a signed 64-bit, and the system time
483 	 * may be either int64_t or int32_t (depends on the kernel),
484 	 * so if the kernel is 32-bit, the nfsv4 time value may not fit.
485 	 */
486 #ifndef _LP64
487 	if (! NFS4_TIME_OK(ntime->seconds)) {
488 		return (EOVERFLOW);
489 	}
490 #endif
491 
492 	/* Invalid to specify 1 billion (or more) nsecs */
493 	if (ntime->nseconds >= 1000000000)
494 		return (EINVAL);
495 
496 	if (ntime->seconds < 0) {
497 		sec = ntime->seconds + 1;
498 		nsec = -1000000000 + ntime->nseconds;
499 	} else {
500 		sec = ntime->seconds;
501 		nsec = ntime->nseconds;
502 	}
503 
504 	vatime->tv_sec = sec;
505 	vatime->tv_nsec = nsec;
506 
507 	return (0);
508 }
509 
510 int
511 nfs4_time_vton(timestruc_t *vatime, nfstime4 *ntime)
512 {
513 	int64_t sec;
514 	uint32_t nsec;
515 
516 	/*
517 	 * nfsv4 time value is a signed 64-bit, and the system time
518 	 * may be either int64_t or int32_t (depends on the kernel),
519 	 * so all system time values will fit.
520 	 */
521 	if (vatime->tv_nsec >= 0) {
522 		sec = vatime->tv_sec;
523 		nsec = vatime->tv_nsec;
524 	} else {
525 		sec = vatime->tv_sec - 1;
526 		nsec = 1000000000 + vatime->tv_nsec;
527 	}
528 	ntime->seconds = sec;
529 	ntime->nseconds = nsec;
530 
531 	return (0);
532 }
533 
534 /*
535  * Converts a utf8 string to a valid null terminated filename string.
536  *
537  * XXX - Not actually translating the UTF-8 string as per RFC 2279.
538  *	 For now, just validate that the UTF-8 string off the wire
539  *	 does not have characters that will freak out UFS, and leave
540  *	 it at that.
541  */
542 char *
543 utf8_to_fn(utf8string *u8s, uint_t *lenp, char *s)
544 {
545 	ASSERT(lenp != NULL);
546 
547 	if (u8s == NULL || u8s->utf8string_len <= 0 ||
548 					u8s->utf8string_val == NULL)
549 		return (NULL);
550 
551 	/*
552 	 * Check for obvious illegal filename chars
553 	 */
554 	if (utf8_strchr(u8s, '/') != NULL) {
555 #ifdef DEBUG
556 		if (nfs4_utf8_debug) {
557 			char *path;
558 			int len = u8s->utf8string_len;
559 
560 			path = kmem_alloc(len + 1, KM_SLEEP);
561 			bcopy(u8s->utf8string_val, path, len);
562 			path[len] = '\0';
563 
564 			zcmn_err(getzoneid(), CE_WARN,
565 			    "Invalid UTF-8 filename: %s", path);
566 
567 			kmem_free(path, len + 1);
568 		}
569 #endif
570 		return (NULL);
571 	}
572 
573 	return (utf8_to_str(u8s, lenp, s));
574 }
575 
576 /*
577  * Converts a utf8 string to a C string.
578  * kmem_allocs a new string if not supplied
579  */
580 char *
581 utf8_to_str(utf8string *str, uint_t *lenp, char *s)
582 {
583 	char	*sp;
584 	char	*u8p;
585 	int	len;
586 	int	 i;
587 
588 	ASSERT(lenp != NULL);
589 
590 	if (str == NULL)
591 		return (NULL);
592 
593 	u8p = str->utf8string_val;
594 	len = str->utf8string_len;
595 	if (len <= 0 || u8p == NULL) {
596 		if (s)
597 			*s = '\0';
598 		return (NULL);
599 	}
600 
601 	sp = s;
602 	if (sp == NULL)
603 		sp = kmem_alloc(len + 1, KM_SLEEP);
604 
605 	/*
606 	 * At least check for embedded nulls
607 	 */
608 	for (i = 0; i < len; i++) {
609 		sp[i] = u8p[i];
610 		if (u8p[i] == '\0') {
611 #ifdef	DEBUG
612 			zcmn_err(getzoneid(), CE_WARN,
613 			    "Embedded NULL in UTF-8 string");
614 #endif
615 			if (s == NULL)
616 				kmem_free(sp, len + 1);
617 			return (NULL);
618 		}
619 	}
620 	sp[len] = '\0';
621 	*lenp = len + 1;
622 
623 	return (sp);
624 }
625 
626 /*
627  * str_to_utf8 - converts a null-terminated C string to a utf8 string
628  */
629 utf8string *
630 str_to_utf8(char *nm, utf8string *str)
631 {
632 	int len;
633 
634 	if (str == NULL)
635 		return (NULL);
636 
637 	if (nm == NULL || *nm == '\0') {
638 		str->utf8string_len = 0;
639 		str->utf8string_val = NULL;
640 	}
641 
642 	len = strlen(nm);
643 
644 	str->utf8string_val = kmem_alloc(len, KM_SLEEP);
645 	str->utf8string_len = len;
646 	bcopy(nm, str->utf8string_val, len);
647 
648 	return (str);
649 }
650 
651 utf8string *
652 utf8_copy(utf8string *src, utf8string *dest)
653 {
654 	if (src == NULL)
655 		return (NULL);
656 	if (dest == NULL)
657 		return (NULL);
658 
659 	if (src->utf8string_len > 0) {
660 		dest->utf8string_val = kmem_alloc(src->utf8string_len,
661 			KM_SLEEP);
662 		bcopy(src->utf8string_val, dest->utf8string_val,
663 			src->utf8string_len);
664 		dest->utf8string_len = src->utf8string_len;
665 	} else {
666 		dest->utf8string_val = NULL;
667 		dest->utf8string_len = 0;
668 	}
669 
670 	return (dest);
671 }
672 
673 int
674 utf8_compare(const utf8string *a, const utf8string *b)
675 {
676 	int mlen, cmp;
677 	int alen, blen;
678 	char *aval, *bval;
679 
680 	if ((a == NULL) && (b == NULL))
681 		return (0);
682 	else if (a == NULL)
683 		return (-1);
684 	else if (b == NULL)
685 		return (1);
686 
687 	alen = a->utf8string_len;
688 	blen = b->utf8string_len;
689 	aval = a->utf8string_val;
690 	bval = b->utf8string_val;
691 
692 	if (((alen == 0) || (aval == NULL)) &&
693 	    ((blen == 0) || (bval == NULL)))
694 		return (0);
695 	else if ((alen == 0) || (aval == NULL))
696 		return (-1);
697 	else if ((blen == 0) || (bval == NULL))
698 		return (1);
699 
700 	mlen = MIN(alen, blen);
701 	cmp = strncmp(aval, bval, mlen);
702 
703 	if ((cmp == 0) && (alen == blen))
704 		return (0);
705 	else if ((cmp == 0) && (alen < blen))
706 		return (-1);
707 	else if (cmp == 0)
708 		return (1);
709 	else if (cmp < 0)
710 		return (-1);
711 	return (1);
712 }
713 
714 /*
715  * utf8_dir_verify - checks that the utf8 string is valid
716  */
717 int
718 utf8_dir_verify(utf8string *str)
719 {
720 	char *nm;
721 	int len;
722 
723 	if (str == NULL)
724 		return (0);
725 
726 	nm = str->utf8string_val;
727 	len = str->utf8string_len;
728 	if (nm == NULL || len == 0) {
729 		return (0);
730 	}
731 
732 	if (len == 1 && nm[0] == '.')
733 		return (0);
734 	if (len == 2 && nm[0] == '.' && nm[1] == '.')
735 		return (0);
736 
737 	if (utf8_strchr(str, '/') != NULL)
738 		return (0);
739 
740 	if (utf8_strchr(str, '\0') != NULL)
741 		return (0);
742 
743 	return (1);
744 }
745 
746 /*
747  * from rpcsec module (common/rpcsec)
748  */
749 extern int sec_clnt_geth(CLIENT *, struct sec_data *, cred_t *, AUTH **);
750 extern void sec_clnt_freeh(AUTH *);
751 extern void sec_clnt_freeinfo(struct sec_data *);
752 
753 /*
754  * authget() gets an auth handle based on the security
755  * information from the servinfo in mountinfo.
756  * The auth handle is stored in ch_client->cl_auth.
757  *
758  * First security flavor of choice is to use sv_secdata
759  * which is initiated by the client. If that fails, get
760  * secinfo from the server and then select one from the
761  * server secinfo list .
762  *
763  * For RPCSEC_GSS flavor, upon success, a secure context is
764  * established between client and server.
765  */
766 int
767 authget(servinfo4_t *svp, CLIENT *ch_client, cred_t *cr)
768 {
769 	int error, i;
770 
771 	/*
772 	 * SV4_TRYSECINFO indicates to try the secinfo list from
773 	 * sv_secinfo until a successful one is reached. Point
774 	 * sv_currsec to the selected security mechanism for
775 	 * later sessions.
776 	 */
777 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_WRITER, 0);
778 	if ((svp->sv_flags & SV4_TRYSECINFO) && svp->sv_secinfo) {
779 		for (i = svp->sv_secinfo->index; i < svp->sv_secinfo->count;
780 								i++) {
781 			if (!(error = sec_clnt_geth(ch_client,
782 				&svp->sv_secinfo->sdata[i],
783 				cr, &ch_client->cl_auth))) {
784 
785 				svp->sv_currsec = &svp->sv_secinfo->sdata[i];
786 				svp->sv_secinfo->index = i;
787 				/* done */
788 				svp->sv_flags &= ~SV4_TRYSECINFO;
789 				break;
790 			}
791 
792 			/*
793 			 * Allow the caller retry with the security flavor
794 			 * pointed by svp->sv_secinfo->index when
795 			 * ETIMEDOUT/ECONNRESET occurs.
796 			 */
797 			if (error == ETIMEDOUT || error == ECONNRESET) {
798 				svp->sv_secinfo->index = i;
799 				break;
800 			}
801 		}
802 	} else {
803 		/* sv_currsec points to one of the entries in sv_secinfo */
804 		if (svp->sv_currsec) {
805 			error = sec_clnt_geth(ch_client, svp->sv_currsec, cr,
806 				&ch_client->cl_auth);
807 		} else {
808 			/* If it's null, use sv_secdata. */
809 			error = sec_clnt_geth(ch_client, svp->sv_secdata, cr,
810 				&ch_client->cl_auth);
811 		}
812 	}
813 	nfs_rw_exit(&svp->sv_lock);
814 
815 	return (error);
816 }
817 
818 /*
819  * Common handle get program for NFS, NFS ACL, and NFS AUTH client.
820  */
821 int
822 clget4(clinfo_t *ci, servinfo4_t *svp, cred_t *cr, CLIENT **newcl,
823     struct chtab **chp, struct nfs4_clnt *nfscl)
824 {
825 	struct chhead *ch, *newch;
826 	struct chhead **plistp;
827 	struct chtab *cp;
828 	int error;
829 	k_sigset_t smask;
830 
831 	if (newcl == NULL || chp == NULL || ci == NULL)
832 		return (EINVAL);
833 
834 	*newcl = NULL;
835 	*chp = NULL;
836 
837 	/*
838 	 * Find an unused handle or create one
839 	 */
840 	newch = NULL;
841 	nfscl->nfscl_stat.clgets.value.ui64++;
842 top:
843 	/*
844 	 * Find the correct entry in the cache to check for free
845 	 * client handles.  The search is based on the RPC program
846 	 * number, program version number, dev_t for the transport
847 	 * device, and the protocol family.
848 	 */
849 	mutex_enter(&nfscl->nfscl_chtable4_lock);
850 	plistp = &nfscl->nfscl_chtable4;
851 	for (ch = nfscl->nfscl_chtable4; ch != NULL; ch = ch->ch_next) {
852 		if (ch->ch_prog == ci->cl_prog &&
853 		    ch->ch_vers == ci->cl_vers &&
854 		    ch->ch_dev == svp->sv_knconf->knc_rdev &&
855 		    (strcmp(ch->ch_protofmly,
856 			svp->sv_knconf->knc_protofmly) == 0))
857 			break;
858 		plistp = &ch->ch_next;
859 	}
860 
861 	/*
862 	 * If we didn't find a cache entry for this quadruple, then
863 	 * create one.  If we don't have one already preallocated,
864 	 * then drop the cache lock, create one, and then start over.
865 	 * If we did have a preallocated entry, then just add it to
866 	 * the front of the list.
867 	 */
868 	if (ch == NULL) {
869 		if (newch == NULL) {
870 			mutex_exit(&nfscl->nfscl_chtable4_lock);
871 			newch = kmem_alloc(sizeof (*newch), KM_SLEEP);
872 			newch->ch_timesused = 0;
873 			newch->ch_prog = ci->cl_prog;
874 			newch->ch_vers = ci->cl_vers;
875 			newch->ch_dev = svp->sv_knconf->knc_rdev;
876 			newch->ch_protofmly = kmem_alloc(
877 			    strlen(svp->sv_knconf->knc_protofmly) + 1,
878 			    KM_SLEEP);
879 			(void) strcpy(newch->ch_protofmly,
880 			    svp->sv_knconf->knc_protofmly);
881 			newch->ch_list = NULL;
882 			goto top;
883 		}
884 		ch = newch;
885 		newch = NULL;
886 		ch->ch_next = nfscl->nfscl_chtable4;
887 		nfscl->nfscl_chtable4 = ch;
888 	/*
889 	 * We found a cache entry, but if it isn't on the front of the
890 	 * list, then move it to the front of the list to try to take
891 	 * advantage of locality of operations.
892 	 */
893 	} else if (ch != nfscl->nfscl_chtable4) {
894 		*plistp = ch->ch_next;
895 		ch->ch_next = nfscl->nfscl_chtable4;
896 		nfscl->nfscl_chtable4 = ch;
897 	}
898 
899 	/*
900 	 * If there was a free client handle cached, then remove it
901 	 * from the list, init it, and use it.
902 	 */
903 	if (ch->ch_list != NULL) {
904 		cp = ch->ch_list;
905 		ch->ch_list = cp->ch_list;
906 		mutex_exit(&nfscl->nfscl_chtable4_lock);
907 		if (newch != NULL) {
908 			kmem_free(newch->ch_protofmly,
909 			    strlen(newch->ch_protofmly) + 1);
910 			kmem_free(newch, sizeof (*newch));
911 		}
912 		(void) clnt_tli_kinit(cp->ch_client, svp->sv_knconf,
913 		    &svp->sv_addr, ci->cl_readsize, ci->cl_retrans, cr);
914 
915 		/*
916 		 * Get an auth handle.
917 		 */
918 		error = authget(svp, cp->ch_client, cr);
919 		if (error || cp->ch_client->cl_auth == NULL) {
920 			CLNT_DESTROY(cp->ch_client);
921 			kmem_cache_free(chtab4_cache, cp);
922 			return ((error != 0) ? error : EINTR);
923 		}
924 		ch->ch_timesused++;
925 		*newcl = cp->ch_client;
926 		*chp = cp;
927 		return (0);
928 	}
929 
930 	/*
931 	 * There weren't any free client handles which fit, so allocate
932 	 * a new one and use that.
933 	 */
934 #ifdef DEBUG
935 	atomic_add_64(&nfscl->nfscl_stat.clalloc.value.ui64, 1);
936 #endif
937 	mutex_exit(&nfscl->nfscl_chtable4_lock);
938 
939 	nfscl->nfscl_stat.cltoomany.value.ui64++;
940 	if (newch != NULL) {
941 		kmem_free(newch->ch_protofmly, strlen(newch->ch_protofmly) + 1);
942 		kmem_free(newch, sizeof (*newch));
943 	}
944 
945 	cp = kmem_cache_alloc(chtab4_cache, KM_SLEEP);
946 	cp->ch_head = ch;
947 
948 	sigintr(&smask, (int)ci->cl_flags & MI4_INT);
949 	error = clnt_tli_kcreate(svp->sv_knconf, &svp->sv_addr, ci->cl_prog,
950 	    ci->cl_vers, ci->cl_readsize, ci->cl_retrans, cr, &cp->ch_client);
951 	sigunintr(&smask);
952 
953 	if (error != 0) {
954 		kmem_cache_free(chtab4_cache, cp);
955 #ifdef DEBUG
956 		atomic_add_64(&nfscl->nfscl_stat.clalloc.value.ui64, -1);
957 #endif
958 		/*
959 		 * Warning is unnecessary if error is EINTR.
960 		 */
961 		if (error != EINTR) {
962 			nfs_cmn_err(error, CE_WARN,
963 			    "clget: couldn't create handle: %m\n");
964 		}
965 		return (error);
966 	}
967 	(void) CLNT_CONTROL(cp->ch_client, CLSET_PROGRESS, NULL);
968 	auth_destroy(cp->ch_client->cl_auth);
969 
970 	/*
971 	 * Get an auth handle.
972 	 */
973 	error = authget(svp, cp->ch_client, cr);
974 	if (error || cp->ch_client->cl_auth == NULL) {
975 		CLNT_DESTROY(cp->ch_client);
976 		kmem_cache_free(chtab4_cache, cp);
977 #ifdef DEBUG
978 		atomic_add_64(&nfscl->nfscl_stat.clalloc.value.ui64, -1);
979 #endif
980 		return ((error != 0) ? error : EINTR);
981 	}
982 	ch->ch_timesused++;
983 	*newcl = cp->ch_client;
984 	ASSERT(cp->ch_client->cl_nosignal == FALSE);
985 	*chp = cp;
986 	return (0);
987 }
988 
989 static int
990 nfs_clget4(mntinfo4_t *mi, servinfo4_t *svp, cred_t *cr, CLIENT **newcl,
991     struct chtab **chp, struct nfs4_clnt *nfscl)
992 {
993 	clinfo_t ci;
994 	bool_t is_recov;
995 	int firstcall, error = 0;
996 
997 	/*
998 	 * Set read buffer size to rsize
999 	 * and add room for RPC headers.
1000 	 */
1001 	ci.cl_readsize = mi->mi_tsize;
1002 	if (ci.cl_readsize != 0)
1003 		ci.cl_readsize += (RPC_MAXDATASIZE - NFS_MAXDATA);
1004 
1005 	/*
1006 	 * If soft mount and server is down just try once.
1007 	 * meaning: do not retransmit.
1008 	 */
1009 	if (!(mi->mi_flags & MI4_HARD) && (mi->mi_flags & MI4_DOWN))
1010 		ci.cl_retrans = 0;
1011 	else
1012 		ci.cl_retrans = mi->mi_retrans;
1013 
1014 	ci.cl_prog = mi->mi_prog;
1015 	ci.cl_vers = mi->mi_vers;
1016 	ci.cl_flags = mi->mi_flags;
1017 
1018 	/*
1019 	 * clget4 calls authget() to get an auth handle. For RPCSEC_GSS
1020 	 * security flavor, the client tries to establish a security context
1021 	 * by contacting the server. If the connection is timed out or reset,
1022 	 * e.g. server reboot, we will try again.
1023 	 */
1024 	is_recov = (curthread == mi->mi_recovthread);
1025 	firstcall = 1;
1026 
1027 	do {
1028 		error = clget4(&ci, svp, cr, newcl, chp, nfscl);
1029 
1030 		if (error == 0)
1031 			break;
1032 
1033 		/*
1034 		 * For forced unmount and zone shutdown, bail out but
1035 		 * let the recovery thread do one more transmission.
1036 		 */
1037 		if ((FS_OR_ZONE_GONE4(mi->mi_vfsp)) &&
1038 		    (!is_recov || !firstcall)) {
1039 			error = EIO;
1040 			break;
1041 		}
1042 
1043 		/* do not retry for soft mount */
1044 		if (!(mi->mi_flags & MI4_HARD))
1045 			break;
1046 
1047 		/* let the caller deal with the failover case */
1048 		if (FAILOVER_MOUNT4(mi))
1049 			break;
1050 
1051 		firstcall = 0;
1052 
1053 	} while (error == ETIMEDOUT || error == ECONNRESET);
1054 
1055 	return (error);
1056 }
1057 
1058 void
1059 clfree4(CLIENT *cl, struct chtab *cp, struct nfs4_clnt *nfscl)
1060 {
1061 	if (cl->cl_auth != NULL) {
1062 		sec_clnt_freeh(cl->cl_auth);
1063 		cl->cl_auth = NULL;
1064 	}
1065 
1066 	/*
1067 	 * Timestamp this cache entry so that we know when it was last
1068 	 * used.
1069 	 */
1070 	cp->ch_freed = gethrestime_sec();
1071 
1072 	/*
1073 	 * Add the free client handle to the front of the list.
1074 	 * This way, the list will be sorted in youngest to oldest
1075 	 * order.
1076 	 */
1077 	mutex_enter(&nfscl->nfscl_chtable4_lock);
1078 	cp->ch_list = cp->ch_head->ch_list;
1079 	cp->ch_head->ch_list = cp;
1080 	mutex_exit(&nfscl->nfscl_chtable4_lock);
1081 }
1082 
1083 #define	CL_HOLDTIME	60	/* time to hold client handles */
1084 
1085 static void
1086 clreclaim4_zone(struct nfs4_clnt *nfscl, uint_t cl_holdtime)
1087 {
1088 	struct chhead *ch;
1089 	struct chtab *cp;	/* list of objects that can be reclaimed */
1090 	struct chtab *cpe;
1091 	struct chtab *cpl;
1092 	struct chtab **cpp;
1093 #ifdef DEBUG
1094 	int n = 0;
1095 	clstat4_debug.clreclaim.value.ui64++;
1096 #endif
1097 
1098 	/*
1099 	 * Need to reclaim some memory, so step through the cache
1100 	 * looking through the lists for entries which can be freed.
1101 	 */
1102 	cp = NULL;
1103 
1104 	mutex_enter(&nfscl->nfscl_chtable4_lock);
1105 
1106 	/*
1107 	 * Here we step through each non-NULL quadruple and start to
1108 	 * construct the reclaim list pointed to by cp.  Note that
1109 	 * cp will contain all eligible chtab entries.  When this traversal
1110 	 * completes, chtab entries from the last quadruple will be at the
1111 	 * front of cp and entries from previously inspected quadruples have
1112 	 * been appended to the rear of cp.
1113 	 */
1114 	for (ch = nfscl->nfscl_chtable4; ch != NULL; ch = ch->ch_next) {
1115 		if (ch->ch_list == NULL)
1116 			continue;
1117 		/*
1118 		 * Search each list for entries older then
1119 		 * cl_holdtime seconds.  The lists are maintained
1120 		 * in youngest to oldest order so that when the
1121 		 * first entry is found which is old enough, then
1122 		 * all of the rest of the entries on the list will
1123 		 * be old enough as well.
1124 		 */
1125 		cpl = ch->ch_list;
1126 		cpp = &ch->ch_list;
1127 		while (cpl != NULL &&
1128 			cpl->ch_freed + cl_holdtime > gethrestime_sec()) {
1129 			cpp = &cpl->ch_list;
1130 			cpl = cpl->ch_list;
1131 		}
1132 		if (cpl != NULL) {
1133 			*cpp = NULL;
1134 			if (cp != NULL) {
1135 				cpe = cpl;
1136 				while (cpe->ch_list != NULL)
1137 					cpe = cpe->ch_list;
1138 				cpe->ch_list = cp;
1139 			}
1140 			cp = cpl;
1141 		}
1142 	}
1143 
1144 	mutex_exit(&nfscl->nfscl_chtable4_lock);
1145 
1146 	/*
1147 	 * If cp is empty, then there is nothing to reclaim here.
1148 	 */
1149 	if (cp == NULL)
1150 		return;
1151 
1152 	/*
1153 	 * Step through the list of entries to free, destroying each client
1154 	 * handle and kmem_free'ing the memory for each entry.
1155 	 */
1156 	while (cp != NULL) {
1157 #ifdef DEBUG
1158 		n++;
1159 #endif
1160 		CLNT_DESTROY(cp->ch_client);
1161 		cpl = cp->ch_list;
1162 		kmem_cache_free(chtab4_cache, cp);
1163 		cp = cpl;
1164 	}
1165 
1166 #ifdef DEBUG
1167 	/*
1168 	 * Update clalloc so that nfsstat shows the current number
1169 	 * of allocated client handles.
1170 	 */
1171 	atomic_add_64(&nfscl->nfscl_stat.clalloc.value.ui64, -n);
1172 #endif
1173 }
1174 
1175 /* ARGSUSED */
1176 static void
1177 clreclaim4(void *all)
1178 {
1179 	struct nfs4_clnt *nfscl;
1180 
1181 	/*
1182 	 * The system is low on memory; go through and try to reclaim some from
1183 	 * every zone on the system.
1184 	 */
1185 	mutex_enter(&nfs4_clnt_list_lock);
1186 	nfscl = list_head(&nfs4_clnt_list);
1187 	for (; nfscl != NULL; nfscl = list_next(&nfs4_clnt_list, nfscl))
1188 		clreclaim4_zone(nfscl, CL_HOLDTIME);
1189 	mutex_exit(&nfs4_clnt_list_lock);
1190 }
1191 
1192 /*
1193  * Minimum time-out values indexed by call type
1194  * These units are in "eights" of a second to avoid multiplies
1195  */
1196 static unsigned int minimum_timeo[] = {
1197 	6, 7, 10
1198 };
1199 
1200 #define	SHORTWAIT	(NFS_COTS_TIMEO / 10)
1201 
1202 /*
1203  * Back off for retransmission timeout, MAXTIMO is in hz of a sec
1204  */
1205 #define	MAXTIMO	(20*hz)
1206 #define	backoff(tim)	(((tim) < MAXTIMO) ? dobackoff(tim) : (tim))
1207 #define	dobackoff(tim)	((((tim) << 1) > MAXTIMO) ? MAXTIMO : ((tim) << 1))
1208 
1209 static int
1210 nfs4_rfscall(mntinfo4_t *mi, rpcproc_t which, xdrproc_t xdrargs, caddr_t argsp,
1211     xdrproc_t xdrres, caddr_t resp, cred_t *cr, int *doqueue,
1212     enum clnt_stat *rpc_statusp, int flags, struct nfs4_clnt *nfscl)
1213 {
1214 	CLIENT *client;
1215 	struct chtab *ch;
1216 	struct rpc_err rpcerr;
1217 	enum clnt_stat status;
1218 	int error;
1219 	struct timeval wait;
1220 	int timeo;		/* in units of hz */
1221 	bool_t tryagain, is_recov;
1222 	k_sigset_t smask;
1223 	servinfo4_t *svp;
1224 #ifdef DEBUG
1225 	char *bufp;
1226 #endif
1227 	int firstcall;
1228 
1229 	rpcerr.re_status = RPC_SUCCESS;
1230 
1231 	/*
1232 	 * If we know that we are rebooting then let's
1233 	 * not bother with doing any over the wireness.
1234 	 */
1235 	mutex_enter(&mi->mi_lock);
1236 	if (mi->mi_flags & MI4_SHUTDOWN) {
1237 		mutex_exit(&mi->mi_lock);
1238 		return (EIO);
1239 	}
1240 	mutex_exit(&mi->mi_lock);
1241 
1242 	/*
1243 	 * clget() calls clnt_tli_kinit() which clears the xid, so we
1244 	 * are guaranteed to reprocess the retry as a new request.
1245 	 */
1246 	svp = mi->mi_curr_serv;
1247 	rpcerr.re_errno = nfs_clget4(mi, svp, cr, &client, &ch, nfscl);
1248 	if (rpcerr.re_errno != 0)
1249 		return (rpcerr.re_errno);
1250 
1251 	timeo = (mi->mi_timeo * hz) / 10;
1252 
1253 	/*
1254 	 * If hard mounted fs, retry call forever unless hard error
1255 	 * occurs.
1256 	 *
1257 	 * For forced unmount, let the recovery thread through but return
1258 	 * an error for all others.  This is so that user processes can
1259 	 * exit quickly.  The recovery thread bails out after one
1260 	 * transmission so that it can tell if it needs to continue.
1261 	 *
1262 	 * For zone shutdown, behave as above to encourage quick
1263 	 * process exit, but also fail quickly when servers have
1264 	 * timed out before and reduce the timeouts.
1265 	 */
1266 	is_recov = (curthread == mi->mi_recovthread);
1267 	firstcall = 1;
1268 	do {
1269 		tryagain = FALSE;
1270 
1271 		NFS4_DEBUG(nfs4_rfscall_debug, (CE_NOTE,
1272 			"nfs4_rfscall: vfs_flag=0x%x, %s",
1273 			mi->mi_vfsp->vfs_flag,
1274 			is_recov ? "recov thread" : "not recov thread"));
1275 
1276 		/*
1277 		 * It's possible while we're retrying the admin
1278 		 * decided to reboot.
1279 		 */
1280 		mutex_enter(&mi->mi_lock);
1281 		if (mi->mi_flags & MI4_SHUTDOWN) {
1282 			mutex_exit(&mi->mi_lock);
1283 			clfree4(client, ch, nfscl);
1284 			return (EIO);
1285 		}
1286 		mutex_exit(&mi->mi_lock);
1287 
1288 		if ((mi->mi_vfsp->vfs_flag & VFS_UNMOUNTED) &&
1289 		    (!is_recov || !firstcall)) {
1290 			clfree4(client, ch, nfscl);
1291 			return (EIO);
1292 		}
1293 
1294 		if (zone_status_get(curproc->p_zone) >= ZONE_IS_SHUTTING_DOWN) {
1295 			mutex_enter(&mi->mi_lock);
1296 			if ((mi->mi_flags & MI4_TIMEDOUT) ||
1297 			    !is_recov || !firstcall) {
1298 				mutex_exit(&mi->mi_lock);
1299 				clfree4(client, ch, nfscl);
1300 				return (EIO);
1301 			}
1302 			mutex_exit(&mi->mi_lock);
1303 			timeo = (MIN(mi->mi_timeo, SHORTWAIT) * hz) / 10;
1304 		}
1305 
1306 		firstcall = 0;
1307 		TICK_TO_TIMEVAL(timeo, &wait);
1308 
1309 		/*
1310 		 * Mask out all signals except SIGHUP, SIGINT, SIGQUIT
1311 		 * and SIGTERM. (Preserving the existing masks).
1312 		 * Mask out SIGINT if mount option nointr is specified.
1313 		 */
1314 		sigintr(&smask, (int)mi->mi_flags & MI4_INT);
1315 		if (!(mi->mi_flags & MI4_INT))
1316 			client->cl_nosignal = TRUE;
1317 
1318 		/*
1319 		 * If there is a current signal, then don't bother
1320 		 * even trying to send out the request because we
1321 		 * won't be able to block waiting for the response.
1322 		 * Simply assume RPC_INTR and get on with it.
1323 		 */
1324 		if (ttolwp(curthread) != NULL && ISSIG(curthread, JUSTLOOKING))
1325 			status = RPC_INTR;
1326 		else {
1327 			status = CLNT_CALL(client, which, xdrargs, argsp,
1328 			    xdrres, resp, wait);
1329 		}
1330 
1331 		if (!(mi->mi_flags & MI4_INT))
1332 			client->cl_nosignal = FALSE;
1333 		/*
1334 		 * restore original signal mask
1335 		 */
1336 		sigunintr(&smask);
1337 
1338 		switch (status) {
1339 		case RPC_SUCCESS:
1340 			break;
1341 
1342 		case RPC_INTR:
1343 			/*
1344 			 * There is no way to recover from this error,
1345 			 * even if mount option nointr is specified.
1346 			 * SIGKILL, for example, cannot be blocked.
1347 			 */
1348 			rpcerr.re_status = RPC_INTR;
1349 			rpcerr.re_errno = EINTR;
1350 			break;
1351 
1352 		case RPC_UDERROR:
1353 			/*
1354 			 * If the NFS server is local (vold) and
1355 			 * it goes away then we get RPC_UDERROR.
1356 			 * This is a retryable error, so we would
1357 			 * loop, so check to see if the specific
1358 			 * error was ECONNRESET, indicating that
1359 			 * target did not exist at all.  If so,
1360 			 * return with RPC_PROGUNAVAIL and
1361 			 * ECONNRESET to indicate why.
1362 			 */
1363 			CLNT_GETERR(client, &rpcerr);
1364 			if (rpcerr.re_errno == ECONNRESET) {
1365 				rpcerr.re_status = RPC_PROGUNAVAIL;
1366 				rpcerr.re_errno = ECONNRESET;
1367 				break;
1368 			}
1369 			/*FALLTHROUGH*/
1370 
1371 		default:		/* probably RPC_TIMEDOUT */
1372 
1373 			if (IS_UNRECOVERABLE_RPC(status))
1374 				break;
1375 
1376 			/*
1377 			 * increment server not responding count
1378 			 */
1379 			mutex_enter(&mi->mi_lock);
1380 			mi->mi_noresponse++;
1381 			mutex_exit(&mi->mi_lock);
1382 #ifdef DEBUG
1383 			nfscl->nfscl_stat.noresponse.value.ui64++;
1384 #endif
1385 			/*
1386 			 * On zone shutdown, mark server dead and move on.
1387 			 */
1388 			if (zone_status_get(curproc->p_zone) >=
1389 			    ZONE_IS_SHUTTING_DOWN) {
1390 				mutex_enter(&mi->mi_lock);
1391 				mi->mi_flags |= MI4_TIMEDOUT;
1392 				mutex_exit(&mi->mi_lock);
1393 				clfree4(client, ch, nfscl);
1394 				return (EIO);
1395 			}
1396 
1397 			/*
1398 			 * NFS client failover support:
1399 			 * return and let the caller take care of
1400 			 * failover.  We only return for failover mounts
1401 			 * because otherwise we want the "not responding"
1402 			 * message, the timer updates, etc.
1403 			 */
1404 			if (mi->mi_vers == 4 && FAILOVER_MOUNT4(mi) &&
1405 			    (error = try_failover(status)) != 0) {
1406 				clfree4(client, ch, nfscl);
1407 				*rpc_statusp = status;
1408 				return (error);
1409 			}
1410 
1411 			if (flags & RFSCALL_SOFT)
1412 				break;
1413 
1414 			tryagain = TRUE;
1415 
1416 			/*
1417 			 * The call is in progress (over COTS).
1418 			 * Try the CLNT_CALL again, but don't
1419 			 * print a noisy error message.
1420 			 */
1421 			if (status == RPC_INPROGRESS)
1422 				break;
1423 
1424 			timeo = backoff(timeo);
1425 			mutex_enter(&mi->mi_lock);
1426 			if (!(mi->mi_flags & MI4_PRINTED)) {
1427 				mi->mi_flags |= MI4_PRINTED;
1428 				mutex_exit(&mi->mi_lock);
1429 				nfs4_queue_fact(RF_SRV_NOT_RESPOND, mi, 0, 0, 0,
1430 				    FALSE, NULL, 0, NULL);
1431 			} else
1432 				mutex_exit(&mi->mi_lock);
1433 
1434 			if (*doqueue && curproc->p_sessp->s_vp != NULL) {
1435 				*doqueue = 0;
1436 				if (!(mi->mi_flags & MI4_NOPRINT))
1437 					nfs4_queue_fact(RF_SRV_NOT_RESPOND, mi,
1438 					    0, 0, 0, FALSE, NULL, 0, NULL);
1439 			}
1440 		}
1441 	} while (tryagain);
1442 
1443 	DTRACE_PROBE2(nfs4__rfscall_debug, enum clnt_stat, status,
1444 			int, rpcerr.re_errno);
1445 
1446 	if (status != RPC_SUCCESS) {
1447 		zoneid_t zoneid = mi->mi_zone->zone_id;
1448 
1449 		/*
1450 		 * Let soft mounts use the timed out message.
1451 		 */
1452 		if (status == RPC_INPROGRESS)
1453 			status = RPC_TIMEDOUT;
1454 		nfscl->nfscl_stat.badcalls.value.ui64++;
1455 		if (status != RPC_INTR) {
1456 			mutex_enter(&mi->mi_lock);
1457 			mi->mi_flags |= MI4_DOWN;
1458 			mutex_exit(&mi->mi_lock);
1459 			CLNT_GETERR(client, &rpcerr);
1460 #ifdef DEBUG
1461 			bufp = clnt_sperror(client, svp->sv_hostname);
1462 			zprintf(zoneid, "NFS%d %s failed for %s\n",
1463 			    mi->mi_vers, mi->mi_rfsnames[which], bufp);
1464 			if (curproc->p_sessp->s_vp != NULL) {
1465 				if (!(mi->mi_flags & MI4_NOPRINT)) {
1466 					uprintf("NFS%d %s failed for %s\n",
1467 					    mi->mi_vers, mi->mi_rfsnames[which],
1468 					    bufp);
1469 				}
1470 			}
1471 			kmem_free(bufp, MAXPATHLEN);
1472 #else
1473 			zprintf(zoneid,
1474 			    "NFS %s failed for server %s: error %d (%s)\n",
1475 			    mi->mi_rfsnames[which], svp->sv_hostname,
1476 			    status, clnt_sperrno(status));
1477 			if (curproc->p_sessp->s_vp != NULL) {
1478 				if (!(mi->mi_flags & MI4_NOPRINT)) {
1479 					uprintf(
1480 				"NFS %s failed for server %s: error %d (%s)\n",
1481 					    mi->mi_rfsnames[which],
1482 					    svp->sv_hostname, status,
1483 					    clnt_sperrno(status));
1484 				}
1485 			}
1486 #endif
1487 			/*
1488 			 * when CLNT_CALL() fails with RPC_AUTHERROR,
1489 			 * re_errno is set appropriately depending on
1490 			 * the authentication error
1491 			 */
1492 			if (status == RPC_VERSMISMATCH ||
1493 			    status == RPC_PROGVERSMISMATCH)
1494 				rpcerr.re_errno = EIO;
1495 		}
1496 	} else {
1497 		/*
1498 		 * Test the value of mi_down and mi_printed without
1499 		 * holding the mi_lock mutex.  If they are both zero,
1500 		 * then it is okay to skip the down and printed
1501 		 * processing.  This saves on a mutex_enter and
1502 		 * mutex_exit pair for a normal, successful RPC.
1503 		 * This was just complete overhead.
1504 		 */
1505 		if (mi->mi_flags & (MI4_DOWN | MI4_PRINTED)) {
1506 			mutex_enter(&mi->mi_lock);
1507 			mi->mi_flags &= ~MI4_DOWN;
1508 			if (mi->mi_flags & MI4_PRINTED) {
1509 				mi->mi_flags &= ~MI4_PRINTED;
1510 				mutex_exit(&mi->mi_lock);
1511 				if (!(mi->mi_vfsp->vfs_flag & VFS_UNMOUNTED))
1512 					nfs4_queue_fact(RF_SRV_OK, mi, 0, 0,
1513 					    0, FALSE, NULL, 0, NULL);
1514 			} else
1515 				mutex_exit(&mi->mi_lock);
1516 		}
1517 
1518 		if (*doqueue == 0) {
1519 			if (!(mi->mi_flags & MI4_NOPRINT) &&
1520 			    !(mi->mi_vfsp->vfs_flag & VFS_UNMOUNTED))
1521 				nfs4_queue_fact(RF_SRV_OK, mi, 0, 0, 0,
1522 				    FALSE, NULL, 0, NULL);
1523 
1524 			*doqueue = 1;
1525 		}
1526 	}
1527 
1528 	clfree4(client, ch, nfscl);
1529 
1530 	ASSERT(rpcerr.re_status == RPC_SUCCESS || rpcerr.re_errno != 0);
1531 
1532 	TRACE_1(TR_FAC_NFS, TR_RFSCALL_END, "nfs4_rfscall_end:errno %d",
1533 	    rpcerr.re_errno);
1534 
1535 	*rpc_statusp = status;
1536 	return (rpcerr.re_errno);
1537 }
1538 
1539 /*
1540  * rfs4call - general wrapper for RPC calls initiated by the client
1541  */
1542 void
1543 rfs4call(mntinfo4_t *mi, COMPOUND4args_clnt *argsp, COMPOUND4res_clnt *resp,
1544 	cred_t *cr, int *doqueue, int flags, nfs4_error_t *ep)
1545 {
1546 	int i, error;
1547 	enum clnt_stat rpc_status = NFS4_OK;
1548 	int num_resops;
1549 	struct nfs4_clnt *nfscl;
1550 
1551 	ASSERT(nfs_zone() == mi->mi_zone);
1552 	nfscl = zone_getspecific(nfs4clnt_zone_key, nfs_zone());
1553 	ASSERT(nfscl != NULL);
1554 
1555 	nfscl->nfscl_stat.calls.value.ui64++;
1556 	mi->mi_reqs[NFSPROC4_COMPOUND].value.ui64++;
1557 
1558 	/* Set up the results struct for XDR usage */
1559 	resp->argsp = argsp;
1560 	resp->array = NULL;
1561 	resp->status = 0;
1562 	resp->decode_len = 0;
1563 
1564 	error = nfs4_rfscall(mi, NFSPROC4_COMPOUND,
1565 		xdr_COMPOUND4args_clnt, (caddr_t)argsp,
1566 		xdr_COMPOUND4res_clnt, (caddr_t)resp, cr,
1567 		doqueue, &rpc_status, flags, nfscl);
1568 
1569 	/* Return now if it was an RPC error */
1570 	if (error) {
1571 		ep->error = error;
1572 		ep->stat = resp->status;
1573 		ep->rpc_status = rpc_status;
1574 		return;
1575 	}
1576 
1577 	/* else we'll count the processed operations */
1578 	num_resops = resp->decode_len;
1579 	for (i = 0; i < num_resops; i++) {
1580 		/*
1581 		 * Count the individual operations
1582 		 * processed by the server.
1583 		 */
1584 		if (resp->array[i].resop >= NFSPROC4_NULL &&
1585 		    resp->array[i].resop <= OP_WRITE)
1586 			mi->mi_reqs[resp->array[i].resop].value.ui64++;
1587 	}
1588 
1589 	ep->error = 0;
1590 	ep->stat = resp->status;
1591 	ep->rpc_status = rpc_status;
1592 }
1593 
1594 /*
1595  * nfs4rename_update - updates stored state after a rename.  Currently this
1596  * is the path of the object and anything under it, and the filehandle of
1597  * the renamed object.
1598  */
1599 void
1600 nfs4rename_update(vnode_t *renvp, vnode_t *ndvp, nfs_fh4 *nfh4p, char *nnm)
1601 {
1602 	sfh4_update(VTOR4(renvp)->r_fh, nfh4p);
1603 	fn_move(VTOSV(renvp)->sv_name, VTOSV(ndvp)->sv_name, nnm);
1604 }
1605 
1606 /*
1607  * Routine to look up the filehandle for the given path and rootvp.
1608  *
1609  * Return values:
1610  * - success: returns zero and *statp is set to NFS4_OK, and *fhp is
1611  *   updated.
1612  * - error: return value (errno value) and/or *statp is set appropriately.
1613  */
1614 #define	RML_ORDINARY	1
1615 #define	RML_NAMED_ATTR	2
1616 #define	RML_ATTRDIR	3
1617 
1618 static void
1619 remap_lookup(nfs4_fname_t *fname, vnode_t *rootvp,
1620 	int filetype, cred_t *cr,
1621 	nfs_fh4 *fhp, nfs4_ga_res_t *garp,	/* fh, attrs for object */
1622 	nfs_fh4 *pfhp, nfs4_ga_res_t *pgarp,	/* fh, attrs for parent */
1623 	nfs4_error_t *ep)
1624 {
1625 	COMPOUND4args_clnt args;
1626 	COMPOUND4res_clnt res;
1627 	nfs_argop4 *argop;
1628 	nfs_resop4 *resop;
1629 	int num_argops;
1630 	lookup4_param_t lookuparg;
1631 	nfs_fh4 *tmpfhp;
1632 	int doqueue = 1;
1633 	char *path;
1634 	mntinfo4_t *mi;
1635 
1636 	ASSERT(fname != NULL);
1637 	ASSERT(rootvp->v_type == VDIR);
1638 
1639 	mi = VTOMI4(rootvp);
1640 	path = fn_path(fname);
1641 	switch (filetype) {
1642 	case RML_NAMED_ATTR:
1643 		lookuparg.l4_getattrs = LKP4_LAST_NAMED_ATTR;
1644 		args.ctag = TAG_REMAP_LOOKUP_NA;
1645 		break;
1646 	case RML_ATTRDIR:
1647 		lookuparg.l4_getattrs = LKP4_LAST_ATTRDIR;
1648 		args.ctag = TAG_REMAP_LOOKUP_AD;
1649 		break;
1650 	case RML_ORDINARY:
1651 		lookuparg.l4_getattrs = LKP4_ALL_ATTRIBUTES;
1652 		args.ctag = TAG_REMAP_LOOKUP;
1653 		break;
1654 	default:
1655 		ep->error = EINVAL;
1656 		return;
1657 	}
1658 	lookuparg.argsp = &args;
1659 	lookuparg.resp = &res;
1660 	lookuparg.header_len = 1;	/* Putfh */
1661 	lookuparg.trailer_len = 0;
1662 	lookuparg.ga_bits = NFS4_VATTR_MASK;
1663 	lookuparg.mi = VTOMI4(rootvp);
1664 
1665 	(void) nfs4lookup_setup(path, &lookuparg, 1);
1666 
1667 	/* 0: putfh directory */
1668 	argop = args.array;
1669 	argop[0].argop = OP_CPUTFH;
1670 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(rootvp)->r_fh;
1671 
1672 	num_argops = args.array_len;
1673 
1674 	rfs4call(mi, &args, &res, cr, &doqueue, RFSCALL_SOFT, ep);
1675 
1676 	if (ep->error || res.status != NFS4_OK)
1677 		goto exit;
1678 
1679 	/* get the object filehandle */
1680 	resop = &res.array[res.array_len - 2];
1681 	if (resop->resop != OP_GETFH) {
1682 		nfs4_queue_event(RE_FAIL_REMAP_OP, mi, NULL,
1683 		    0, NULL, NULL, 0, NULL, 0, TAG_NONE, TAG_NONE, 0, 0);
1684 		ep->stat = NFS4ERR_SERVERFAULT;
1685 		goto exit;
1686 	}
1687 	tmpfhp = &resop->nfs_resop4_u.opgetfh.object;
1688 	if (tmpfhp->nfs_fh4_len > NFS4_FHSIZE) {
1689 		nfs4_queue_event(RE_FAIL_REMAP_LEN, mi, NULL,
1690 		    tmpfhp->nfs_fh4_len, NULL, NULL, 0, NULL, 0, TAG_NONE,
1691 		    TAG_NONE, 0, 0);
1692 		ep->stat = NFS4ERR_SERVERFAULT;
1693 		goto exit;
1694 	}
1695 	fhp->nfs_fh4_val = kmem_alloc(tmpfhp->nfs_fh4_len, KM_SLEEP);
1696 	nfs_fh4_copy(tmpfhp, fhp);
1697 
1698 	/* get the object attributes */
1699 	resop = &res.array[res.array_len - 1];
1700 	if (garp && resop->resop == OP_GETATTR)
1701 		*garp = resop->nfs_resop4_u.opgetattr.ga_res;
1702 
1703 	/* See if there are enough fields in the response for parent info */
1704 	if ((int)res.array_len - 5 <= 0)
1705 		goto exit;
1706 
1707 	/* get the parent filehandle */
1708 	resop = &res.array[res.array_len - 5];
1709 	if (resop->resop != OP_GETFH) {
1710 		nfs4_queue_event(RE_FAIL_REMAP_OP, mi, NULL,
1711 		    0, NULL, NULL, 0, NULL, 0, TAG_NONE, TAG_NONE, 0, 0);
1712 		ep->stat = NFS4ERR_SERVERFAULT;
1713 		goto exit;
1714 	}
1715 	tmpfhp = &resop->nfs_resop4_u.opgetfh.object;
1716 	if (tmpfhp->nfs_fh4_len > NFS4_FHSIZE) {
1717 		nfs4_queue_event(RE_FAIL_REMAP_LEN, mi, NULL,
1718 		    tmpfhp->nfs_fh4_len, NULL, NULL, 0, NULL, 0, TAG_NONE,
1719 		    TAG_NONE, 0, 0);
1720 		ep->stat = NFS4ERR_SERVERFAULT;
1721 		goto exit;
1722 	}
1723 	pfhp->nfs_fh4_val = kmem_alloc(tmpfhp->nfs_fh4_len, KM_SLEEP);
1724 	nfs_fh4_copy(tmpfhp, pfhp);
1725 
1726 	/* get the parent attributes */
1727 	resop = &res.array[res.array_len - 4];
1728 	if (pgarp && resop->resop == OP_GETATTR)
1729 		*pgarp = resop->nfs_resop4_u.opgetattr.ga_res;
1730 
1731 exit:
1732 	/*
1733 	 * It is too hard to remember where all the OP_LOOKUPs are
1734 	 */
1735 	nfs4args_lookup_free(argop, num_argops);
1736 	kmem_free(argop, lookuparg.arglen * sizeof (nfs_argop4));
1737 
1738 	if (!ep->error)
1739 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1740 	kmem_free(path, strlen(path)+1);
1741 }
1742 
1743 /*
1744  * NFS client failover / volatile filehandle support
1745  *
1746  * Recover the filehandle for the given rnode.
1747  *
1748  * Errors are returned via the nfs4_error_t parameter.
1749  */
1750 
1751 void
1752 nfs4_remap_file(mntinfo4_t *mi, vnode_t *vp, int flags, nfs4_error_t *ep)
1753 {
1754 	rnode4_t *rp = VTOR4(vp);
1755 	vnode_t *rootvp = NULL;
1756 	vnode_t *dvp = NULL;
1757 	cred_t *cr, *cred_otw;
1758 	nfs4_ga_res_t gar, pgar;
1759 	nfs_fh4 newfh = {0, NULL}, newpfh = {0, NULL};
1760 	int filetype = RML_ORDINARY;
1761 	nfs4_recov_state_t recov = {NULL, 0, 0};
1762 	int badfhcount = 0;
1763 	nfs4_open_stream_t *osp = NULL;
1764 	bool_t first_time = TRUE;	/* first time getting OTW cred */
1765 	bool_t last_time = FALSE;	/* last time getting OTW cred */
1766 
1767 	NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
1768 	    "nfs4_remap_file: remapping %s", rnode4info(rp)));
1769 	ASSERT(nfs4_consistent_type(vp));
1770 
1771 	if (vp->v_flag & VROOT) {
1772 		nfs4_remap_root(mi, ep, flags);
1773 		return;
1774 	}
1775 
1776 	/*
1777 	 * Given the root fh, use the path stored in
1778 	 * the rnode to find the fh for the new server.
1779 	 */
1780 	ep->error = VFS_ROOT(mi->mi_vfsp, &rootvp);
1781 	if (ep->error != 0)
1782 		return;
1783 
1784 	cr = curthread->t_cred;
1785 	ASSERT(cr != NULL);
1786 get_remap_cred:
1787 	/*
1788 	 * Releases the osp, if it is provided.
1789 	 * Puts a hold on the cred_otw and the new osp (if found).
1790 	 */
1791 	cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
1792 		&first_time, &last_time);
1793 	ASSERT(cred_otw != NULL);
1794 
1795 	if (rp->r_flags & R4ISXATTR) {
1796 		filetype = RML_NAMED_ATTR;
1797 		(void) vtodv(vp, &dvp, cred_otw, FALSE);
1798 	}
1799 
1800 	if (vp->v_flag & V_XATTRDIR) {
1801 		filetype = RML_ATTRDIR;
1802 	}
1803 
1804 	if (filetype == RML_ORDINARY && rootvp->v_type == VREG) {
1805 		/* file mount, doesn't need a remap */
1806 		goto done;
1807 	}
1808 
1809 again:
1810 	remap_lookup(rp->r_svnode.sv_name, rootvp, filetype, cred_otw,
1811 			&newfh, &gar, &newpfh, &pgar, ep);
1812 
1813 	NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
1814 	    "nfs4_remap_file: remap_lookup returned %d/%d",
1815 	    ep->error, ep->stat));
1816 
1817 	if (last_time == FALSE && ep->error == EACCES) {
1818 		crfree(cred_otw);
1819 		if (dvp != NULL)
1820 			VN_RELE(dvp);
1821 		goto get_remap_cred;
1822 	}
1823 	if (ep->error != 0)
1824 		goto done;
1825 
1826 	switch (ep->stat) {
1827 	case NFS4_OK:
1828 		badfhcount = 0;
1829 		if (recov.rs_flags & NFS4_RS_DELAY_MSG) {
1830 			mutex_enter(&rp->r_statelock);
1831 			rp->r_delay_interval = 0;
1832 			mutex_exit(&rp->r_statelock);
1833 			uprintf("NFS File Available..\n");
1834 		}
1835 		break;
1836 	case NFS4ERR_FHEXPIRED:
1837 	case NFS4ERR_BADHANDLE:
1838 		/*
1839 		 * If we ran into filehandle problems, we should try to
1840 		 * remap the root vnode first and hope life gets better.
1841 		 * But we need to avoid loops.
1842 		 */
1843 		if (badfhcount++ > 0)
1844 			goto done;
1845 		if (newfh.nfs_fh4_len != 0) {
1846 			kmem_free(newfh.nfs_fh4_val, newfh.nfs_fh4_len);
1847 			newfh.nfs_fh4_len = 0;
1848 		}
1849 		if (newpfh.nfs_fh4_len != 0) {
1850 			kmem_free(newpfh.nfs_fh4_val, newpfh.nfs_fh4_len);
1851 			newpfh.nfs_fh4_len = 0;
1852 		}
1853 		/* relative path - remap rootvp then retry */
1854 		VN_RELE(rootvp);
1855 		rootvp = NULL;
1856 		nfs4_remap_root(mi, ep, flags);
1857 		if (ep->error != 0 || ep->stat != NFS4_OK)
1858 			goto done;
1859 		ep->error = VFS_ROOT(mi->mi_vfsp, &rootvp);
1860 		if (ep->error != 0)
1861 			goto done;
1862 		goto again;
1863 	case NFS4ERR_DELAY:
1864 		badfhcount = 0;
1865 		nfs4_set_delay_wait(vp);
1866 		ep->error = nfs4_wait_for_delay(vp, &recov);
1867 		if (ep->error != 0)
1868 			goto done;
1869 		goto again;
1870 	case NFS4ERR_ACCESS:
1871 		/* get new cred, try again */
1872 		if (last_time == TRUE)
1873 			goto done;
1874 		if (dvp != NULL)
1875 			VN_RELE(dvp);
1876 		crfree(cred_otw);
1877 		goto get_remap_cred;
1878 	default:
1879 		goto done;
1880 	}
1881 
1882 	/*
1883 	 * Check on the new and old rnodes before updating;
1884 	 * if the vnode type or size changes, issue a warning
1885 	 * and mark the file dead.
1886 	 */
1887 	mutex_enter(&rp->r_statelock);
1888 	if (flags & NFS4_REMAP_CKATTRS) {
1889 		if (vp->v_type != gar.n4g_va.va_type ||
1890 			(vp->v_type != VDIR &&
1891 			rp->r_size != gar.n4g_va.va_size)) {
1892 			NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
1893 			    "nfs4_remap_file: size %d vs. %d, type %d vs. %d",
1894 			    (int)rp->r_size, (int)gar.n4g_va.va_size,
1895 			    vp->v_type, gar.n4g_va.va_type));
1896 			mutex_exit(&rp->r_statelock);
1897 			nfs4_queue_event(RE_FILE_DIFF, mi,
1898 			    rp->r_server->sv_hostname, 0, vp, NULL, 0, NULL, 0,
1899 			    TAG_NONE, TAG_NONE, 0, 0);
1900 			nfs4_fail_recov(vp, NULL, 0, NFS4_OK);
1901 			goto done;
1902 		}
1903 	}
1904 	ASSERT(gar.n4g_va.va_type != VNON);
1905 	rp->r_server = mi->mi_curr_serv;
1906 
1907 	if (gar.n4g_fsid_valid) {
1908 		(void) nfs_rw_enter_sig(&rp->r_server->sv_lock, RW_READER, 0);
1909 		rp->r_srv_fsid = gar.n4g_fsid;
1910 		if (FATTR4_FSID_EQ(&gar.n4g_fsid, &rp->r_server->sv_fsid))
1911 			rp->r_flags &= ~R4SRVSTUB;
1912 		else
1913 			rp->r_flags |= R4SRVSTUB;
1914 		nfs_rw_exit(&rp->r_server->sv_lock);
1915 #ifdef DEBUG
1916 	} else {
1917 		NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
1918 			"remap_file: fsid attr not provided by server.  rp=%p",
1919 			(void *)rp));
1920 #endif
1921 	}
1922 	mutex_exit(&rp->r_statelock);
1923 	nfs4_attrcache_noinval(vp, &gar, gethrtime()); /* force update */
1924 	sfh4_update(rp->r_fh, &newfh);
1925 	ASSERT(nfs4_consistent_type(vp));
1926 
1927 	/*
1928 	 * If we got parent info, use it to update the parent
1929 	 */
1930 	if (newpfh.nfs_fh4_len != 0) {
1931 		if (rp->r_svnode.sv_dfh != NULL)
1932 			sfh4_update(rp->r_svnode.sv_dfh, &newpfh);
1933 		if (dvp != NULL) {
1934 			/* force update of attrs */
1935 			nfs4_attrcache_noinval(dvp, &pgar, gethrtime());
1936 		}
1937 	}
1938 done:
1939 	if (newfh.nfs_fh4_len != 0)
1940 		kmem_free(newfh.nfs_fh4_val, newfh.nfs_fh4_len);
1941 	if (newpfh.nfs_fh4_len != 0)
1942 		kmem_free(newpfh.nfs_fh4_val, newpfh.nfs_fh4_len);
1943 	if (cred_otw != NULL)
1944 		crfree(cred_otw);
1945 	if (rootvp != NULL)
1946 		VN_RELE(rootvp);
1947 	if (dvp != NULL)
1948 		VN_RELE(dvp);
1949 	if (osp != NULL)
1950 		open_stream_rele(osp, rp);
1951 }
1952 
1953 /*
1954  * Client-side failover support: remap the filehandle for vp if it appears
1955  * necessary.  errors are returned via the nfs4_error_t parameter; though,
1956  * if there is a problem, we will just try again later.
1957  */
1958 
1959 void
1960 nfs4_check_remap(mntinfo4_t *mi, vnode_t *vp, int flags, nfs4_error_t *ep)
1961 {
1962 	if (vp == NULL)
1963 		return;
1964 
1965 	if (!(vp->v_vfsp->vfs_flag & VFS_RDONLY))
1966 		return;
1967 
1968 	if (VTOR4(vp)->r_server == mi->mi_curr_serv)
1969 		return;
1970 
1971 	nfs4_remap_file(mi, vp, flags, ep);
1972 }
1973 
1974 /*
1975  * nfs4_make_dotdot() - find or create a parent vnode of a non-root node.
1976  *
1977  * Our caller has a filehandle for ".." relative to a particular
1978  * directory object.  We want to find or create a parent vnode
1979  * with that filehandle and return it.  We can of course create
1980  * a vnode from this filehandle, but we need to also make sure
1981  * that if ".." is a regular file (i.e. dvp is a V_XATTRDIR)
1982  * that we have a parent FH for future reopens as well.  If
1983  * we have a remap failure, we won't be able to reopen this
1984  * file, but we won't treat that as fatal because a reopen
1985  * is at least unlikely.  Someday nfs4_reopen() should look
1986  * for a missing parent FH and try a remap to recover from it.
1987  *
1988  * need_start_op argument indicates whether this function should
1989  * do a start_op before calling remap_lookup().  This should
1990  * be FALSE, if you are the recovery thread or in an op; otherwise,
1991  * set it to TRUE.
1992  */
1993 int
1994 nfs4_make_dotdot(nfs4_sharedfh_t *fhp, hrtime_t t, vnode_t *dvp,
1995     cred_t *cr, vnode_t **vpp, int need_start_op)
1996 {
1997 	mntinfo4_t *mi = VTOMI4(dvp);
1998 	nfs4_fname_t *np = NULL, *pnp = NULL;
1999 	vnode_t *vp = NULL, *rootvp = NULL;
2000 	rnode4_t *rp;
2001 	nfs_fh4 newfh = {0, NULL}, newpfh = {0, NULL};
2002 	nfs4_ga_res_t gar, pgar;
2003 	vattr_t va, pva;
2004 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
2005 	nfs4_sharedfh_t *sfh = NULL, *psfh = NULL;
2006 	nfs4_recov_state_t recov_state;
2007 
2008 #ifdef DEBUG
2009 	/*
2010 	 * ensure need_start_op is correct
2011 	 */
2012 	{
2013 		int no_need_start_op = (tsd_get(nfs4_tsd_key) ||
2014 		    (curthread == mi->mi_recovthread));
2015 		/* C needs a ^^ operator! */
2016 		ASSERT(((need_start_op) && (!no_need_start_op)) ||
2017 		    ((! need_start_op) && (no_need_start_op)));
2018 	}
2019 #endif
2020 	ASSERT(VTOMI4(dvp)->mi_zone == nfs_zone());
2021 
2022 	NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE,
2023 	    "nfs4_make_dotdot: called with fhp %p, dvp %s", (void *)fhp,
2024 	    rnode4info(VTOR4(dvp))));
2025 
2026 	/*
2027 	 * rootvp might be needed eventually. Holding it now will
2028 	 * ensure that r4find_unlocked() will find it, if ".." is the root.
2029 	 */
2030 	e.error = VFS_ROOT(mi->mi_vfsp, &rootvp);
2031 	if (e.error != 0)
2032 		goto out;
2033 	rp = r4find_unlocked(fhp, mi->mi_vfsp);
2034 	if (rp != NULL) {
2035 		*vpp = RTOV4(rp);
2036 		VN_RELE(rootvp);
2037 		return (0);
2038 	}
2039 
2040 	/*
2041 	 * Since we don't have the rnode, we have to go over the wire.
2042 	 * remap_lookup() can get all of the filehandles and attributes
2043 	 * we need in one operation.
2044 	 */
2045 	np = fn_parent(VTOSV(dvp)->sv_name);
2046 	ASSERT(np != NULL);
2047 
2048 	recov_state.rs_flags = 0;
2049 	recov_state.rs_num_retry_despite_err = 0;
2050 recov_retry:
2051 	if (need_start_op) {
2052 		e.error = nfs4_start_fop(mi, rootvp, NULL, OH_LOOKUP,
2053 		    &recov_state, NULL);
2054 		if (e.error != 0) {
2055 			goto out;
2056 		}
2057 	}
2058 	va.va_type = VNON;
2059 	pva.va_type = VNON;
2060 	remap_lookup(np, rootvp, RML_ORDINARY, cr,
2061 	    &newfh, &gar, &newpfh, &pgar, &e);
2062 	if (nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp)) {
2063 		if (need_start_op) {
2064 			bool_t abort;
2065 
2066 			abort = nfs4_start_recovery(&e, mi,
2067 			    rootvp, NULL, NULL, NULL, OP_LOOKUP, NULL);
2068 			if (abort) {
2069 				nfs4_end_fop(mi, rootvp, NULL, OH_LOOKUP,
2070 				    &recov_state, FALSE);
2071 				if (e.error == 0)
2072 					e.error = EIO;
2073 				goto out;
2074 			}
2075 			nfs4_end_fop(mi, rootvp, NULL, OH_LOOKUP,
2076 			    &recov_state, TRUE);
2077 			goto recov_retry;
2078 		}
2079 		if (e.error == 0)
2080 			e.error = EIO;
2081 		goto out;
2082 	}
2083 
2084 	if (!e.error) {
2085 		va = gar.n4g_va;
2086 		pva = pgar.n4g_va;
2087 	}
2088 
2089 	if ((e.error != 0) ||
2090 	    (va.va_type != VDIR)) {
2091 		if (e.error == 0)
2092 			e.error = EIO;
2093 		goto out;
2094 	}
2095 
2096 	if (e.stat != NFS4_OK) {
2097 		e.error = EIO;
2098 		goto out;
2099 	}
2100 
2101 	/*
2102 	 * It is possible for remap_lookup() to return with no error,
2103 	 * but without providing the parent filehandle and attrs.
2104 	 */
2105 	if (pva.va_type != VDIR) {
2106 		/*
2107 		 * Call remap_lookup() again, this time with the
2108 		 * newpfh and pgar args in the first position.
2109 		 */
2110 		pnp = fn_parent(np);
2111 		if (pnp != NULL) {
2112 			remap_lookup(pnp, rootvp, RML_ORDINARY, cr,
2113 			    &newpfh, &pgar, NULL, NULL, &e);
2114 			if (nfs4_needs_recovery(&e, FALSE,
2115 			    mi->mi_vfsp)) {
2116 				if (need_start_op) {
2117 					bool_t abort;
2118 
2119 					abort = nfs4_start_recovery(&e, mi,
2120 					    rootvp, NULL, NULL, NULL,
2121 					    OP_LOOKUP, NULL);
2122 					if (abort) {
2123 						nfs4_end_fop(mi, rootvp, NULL,
2124 						    OH_LOOKUP, &recov_state,
2125 						    FALSE);
2126 						if (e.error == 0)
2127 							e.error = EIO;
2128 						goto out;
2129 					}
2130 					nfs4_end_fop(mi, rootvp, NULL,
2131 					    OH_LOOKUP, &recov_state, TRUE);
2132 					goto recov_retry;
2133 				}
2134 				if (e.error == 0)
2135 					e.error = EIO;
2136 				goto out;
2137 			}
2138 
2139 			if (e.stat != NFS4_OK) {
2140 				e.error = EIO;
2141 				goto out;
2142 			}
2143 		}
2144 		if ((pnp == NULL) ||
2145 		    (e.error != 0) ||
2146 		    (pva.va_type == VNON)) {
2147 			if (need_start_op)
2148 				nfs4_end_fop(mi, rootvp, NULL, OH_LOOKUP,
2149 				    &recov_state, FALSE);
2150 			if (e.error == 0)
2151 				e.error = EIO;
2152 			goto out;
2153 		}
2154 	}
2155 	ASSERT(newpfh.nfs_fh4_len != 0);
2156 	if (need_start_op)
2157 		nfs4_end_fop(mi, rootvp, NULL, OH_LOOKUP, &recov_state, FALSE);
2158 	psfh = sfh4_get(&newpfh, mi);
2159 
2160 	sfh = sfh4_get(&newfh, mi);
2161 	vp = makenfs4node_by_fh(sfh, psfh, &np, &gar, mi, cr, t);
2162 
2163 out:
2164 	if (np != NULL)
2165 		fn_rele(&np);
2166 	if (pnp != NULL)
2167 		fn_rele(&pnp);
2168 	if (newfh.nfs_fh4_len != 0)
2169 		kmem_free(newfh.nfs_fh4_val, newfh.nfs_fh4_len);
2170 	if (newpfh.nfs_fh4_len != 0)
2171 		kmem_free(newpfh.nfs_fh4_val, newpfh.nfs_fh4_len);
2172 	if (sfh != NULL)
2173 		sfh4_rele(&sfh);
2174 	if (psfh != NULL)
2175 		sfh4_rele(&psfh);
2176 	if (rootvp != NULL)
2177 		VN_RELE(rootvp);
2178 	*vpp = vp;
2179 	return (e.error);
2180 }
2181 
2182 #ifdef DEBUG
2183 size_t r_path_memuse = 0;
2184 #endif
2185 
2186 /*
2187  * NFS client failover support
2188  *
2189  * sv4_free() frees the malloc'd portion of a "servinfo_t".
2190  */
2191 void
2192 sv4_free(servinfo4_t *svp)
2193 {
2194 	servinfo4_t *next;
2195 	struct knetconfig *knconf;
2196 
2197 	while (svp != NULL) {
2198 		next = svp->sv_next;
2199 		if (svp->sv_dhsec)
2200 			sec_clnt_freeinfo(svp->sv_dhsec);
2201 		if (svp->sv_secdata)
2202 			sec_clnt_freeinfo(svp->sv_secdata);
2203 		if (svp->sv_save_secinfo &&
2204 				svp->sv_save_secinfo != svp->sv_secinfo)
2205 			secinfo_free(svp->sv_save_secinfo);
2206 		if (svp->sv_secinfo)
2207 			secinfo_free(svp->sv_secinfo);
2208 		if (svp->sv_hostname && svp->sv_hostnamelen > 0)
2209 			kmem_free(svp->sv_hostname, svp->sv_hostnamelen);
2210 		knconf = svp->sv_knconf;
2211 		if (knconf != NULL) {
2212 			if (knconf->knc_protofmly != NULL)
2213 				kmem_free(knconf->knc_protofmly, KNC_STRSIZE);
2214 			if (knconf->knc_proto != NULL)
2215 				kmem_free(knconf->knc_proto, KNC_STRSIZE);
2216 			kmem_free(knconf, sizeof (*knconf));
2217 		}
2218 		knconf = svp->sv_origknconf;
2219 		if (knconf != NULL) {
2220 			if (knconf->knc_protofmly != NULL)
2221 				kmem_free(knconf->knc_protofmly, KNC_STRSIZE);
2222 			if (knconf->knc_proto != NULL)
2223 				kmem_free(knconf->knc_proto, KNC_STRSIZE);
2224 			kmem_free(knconf, sizeof (*knconf));
2225 		}
2226 		if (svp->sv_addr.buf != NULL && svp->sv_addr.maxlen != 0)
2227 			kmem_free(svp->sv_addr.buf, svp->sv_addr.maxlen);
2228 		if (svp->sv_path != NULL) {
2229 			kmem_free(svp->sv_path, svp->sv_pathlen);
2230 		}
2231 		nfs_rw_destroy(&svp->sv_lock);
2232 		kmem_free(svp, sizeof (*svp));
2233 		svp = next;
2234 	}
2235 }
2236 
2237 void
2238 nfs4_printfhandle(nfs4_fhandle_t *fhp)
2239 {
2240 	int *ip;
2241 	char *buf;
2242 	size_t bufsize;
2243 	char *cp;
2244 
2245 	/*
2246 	 * 13 == "(file handle:"
2247 	 * maximum of NFS_FHANDLE / sizeof (*ip) elements in fh_buf times
2248 	 *	1 == ' '
2249 	 *	8 == maximum strlen of "%x"
2250 	 * 3 == ")\n\0"
2251 	 */
2252 	bufsize = 13 + ((NFS_FHANDLE_LEN / sizeof (*ip)) * (1 + 8)) + 3;
2253 	buf = kmem_alloc(bufsize, KM_NOSLEEP);
2254 	if (buf == NULL)
2255 		return;
2256 
2257 	cp = buf;
2258 	(void) strcpy(cp, "(file handle:");
2259 	while (*cp != '\0')
2260 		cp++;
2261 	for (ip = (int *)fhp->fh_buf;
2262 	    ip < (int *)&fhp->fh_buf[fhp->fh_len];
2263 	    ip++) {
2264 		(void) sprintf(cp, " %x", *ip);
2265 		while (*cp != '\0')
2266 			cp++;
2267 	}
2268 	(void) strcpy(cp, ")\n");
2269 
2270 	zcmn_err(getzoneid(), CE_CONT, "%s", buf);
2271 
2272 	kmem_free(buf, bufsize);
2273 }
2274 
2275 /*
2276  * The NFSv4 readdir cache subsystem.
2277  *
2278  * We provide a set of interfaces to allow the rest of the system to utilize
2279  * a caching mechanism while encapsulating the details of the actual
2280  * implementation.  This should allow for better maintainability and
2281  * extensibilty by consolidating the implementation details in one location.
2282  */
2283 
2284 /*
2285  * Comparator used by AVL routines.
2286  */
2287 static int
2288 rddir4_cache_compar(const void *x, const void *y)
2289 {
2290 	rddir4_cache_impl *ai = (rddir4_cache_impl *)x;
2291 	rddir4_cache_impl *bi = (rddir4_cache_impl *)y;
2292 	rddir4_cache *a = &ai->rc;
2293 	rddir4_cache *b = &bi->rc;
2294 
2295 	if (a->nfs4_cookie == b->nfs4_cookie) {
2296 		if (a->buflen == b->buflen)
2297 			return (0);
2298 		if (a->buflen < b->buflen)
2299 			return (-1);
2300 		return (1);
2301 	}
2302 
2303 	if (a->nfs4_cookie < b->nfs4_cookie)
2304 			return (-1);
2305 
2306 	return (1);
2307 }
2308 
2309 /*
2310  * Allocate an opaque handle for the readdir cache.
2311  */
2312 void
2313 rddir4_cache_create(rnode4_t *rp)
2314 {
2315 	ASSERT(rp->r_dir == NULL);
2316 
2317 	rp->r_dir = kmem_alloc(sizeof (avl_tree_t), KM_SLEEP);
2318 
2319 	avl_create(rp->r_dir, rddir4_cache_compar, sizeof (rddir4_cache_impl),
2320 			offsetof(rddir4_cache_impl, tree));
2321 }
2322 
2323 /*
2324  *  Purge the cache of all cached readdir responses.
2325  */
2326 void
2327 rddir4_cache_purge(rnode4_t *rp)
2328 {
2329 	rddir4_cache_impl	*rdip;
2330 	rddir4_cache_impl	*nrdip;
2331 
2332 	ASSERT(MUTEX_HELD(&rp->r_statelock));
2333 
2334 	if (rp->r_dir == NULL)
2335 		return;
2336 
2337 	rdip = avl_first(rp->r_dir);
2338 
2339 	while (rdip != NULL) {
2340 		nrdip = AVL_NEXT(rp->r_dir, rdip);
2341 		avl_remove(rp->r_dir, rdip);
2342 		rdip->rc.flags &= ~RDDIRCACHED;
2343 		rddir4_cache_rele(rp, &rdip->rc);
2344 		rdip = nrdip;
2345 	}
2346 	ASSERT(avl_numnodes(rp->r_dir) == 0);
2347 }
2348 
2349 /*
2350  * Destroy the readdir cache.
2351  */
2352 void
2353 rddir4_cache_destroy(rnode4_t *rp)
2354 {
2355 	ASSERT(MUTEX_HELD(&rp->r_statelock));
2356 	if (rp->r_dir == NULL)
2357 		return;
2358 
2359 	rddir4_cache_purge(rp);
2360 	avl_destroy(rp->r_dir);
2361 	kmem_free(rp->r_dir, sizeof (avl_tree_t));
2362 	rp->r_dir = NULL;
2363 }
2364 
2365 /*
2366  * Locate a readdir response from the readdir cache.
2367  *
2368  * Return values:
2369  *
2370  * NULL - If there is an unrecoverable situation like the operation may have
2371  *	  been interrupted.
2372  *
2373  * rddir4_cache * - A pointer to a rddir4_cache is returned to the caller.
2374  *		    The flags are set approprately, such that the caller knows
2375  *		    what state the entry is in.
2376  */
2377 rddir4_cache *
2378 rddir4_cache_lookup(rnode4_t *rp, offset_t cookie, int count)
2379 {
2380 	rddir4_cache_impl	*rdip = NULL;
2381 	rddir4_cache_impl	srdip;
2382 	rddir4_cache		*srdc;
2383 	rddir4_cache		*rdc = NULL;
2384 	rddir4_cache		*nrdc = NULL;
2385 	avl_index_t		where;
2386 
2387 top:
2388 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
2389 	ASSERT(MUTEX_HELD(&rp->r_statelock));
2390 	/*
2391 	 * Check to see if the readdir cache has been disabled.  If so, then
2392 	 * simply allocate an rddir4_cache entry and return it, since caching
2393 	 * operations do not apply.
2394 	 */
2395 	if (rp->r_dir == NULL) {
2396 		if (nrdc == NULL) {
2397 			/*
2398 			 * Drop the lock because we are doing a sleeping
2399 			 * allocation.
2400 			 */
2401 			mutex_exit(&rp->r_statelock);
2402 			rdc = rddir4_cache_alloc(KM_SLEEP);
2403 			rdc->nfs4_cookie = cookie;
2404 			rdc->buflen = count;
2405 			mutex_enter(&rp->r_statelock);
2406 			return (rdc);
2407 		}
2408 		return (nrdc);
2409 	}
2410 
2411 	srdc = &srdip.rc;
2412 	srdc->nfs4_cookie = cookie;
2413 	srdc->buflen = count;
2414 
2415 	rdip = avl_find(rp->r_dir, &srdip, &where);
2416 
2417 	/*
2418 	 * If we didn't find an entry then create one and insert it
2419 	 * into the cache.
2420 	 */
2421 	if (rdip == NULL) {
2422 		/*
2423 		 * Check for the case where we have made a second pass through
2424 		 * the cache due to a lockless allocation.  If we find that no
2425 		 * thread has already inserted this entry, do the insert now
2426 		 * and return.
2427 		 */
2428 		if (nrdc != NULL) {
2429 			avl_insert(rp->r_dir, nrdc->data, where);
2430 			nrdc->flags |= RDDIRCACHED;
2431 			rddir4_cache_hold(nrdc);
2432 			return (nrdc);
2433 		}
2434 
2435 #ifdef DEBUG
2436 		nfs4_readdir_cache_misses++;
2437 #endif
2438 		/*
2439 		 * First, try to allocate an entry without sleeping.  If that
2440 		 * fails then drop the lock and do a sleeping allocation.
2441 		 */
2442 		nrdc = rddir4_cache_alloc(KM_NOSLEEP);
2443 		if (nrdc != NULL) {
2444 			nrdc->nfs4_cookie = cookie;
2445 			nrdc->buflen = count;
2446 			avl_insert(rp->r_dir, nrdc->data, where);
2447 			nrdc->flags |= RDDIRCACHED;
2448 			rddir4_cache_hold(nrdc);
2449 			return (nrdc);
2450 		}
2451 
2452 		/*
2453 		 * Drop the lock and do a sleeping allocation.	We incur
2454 		 * additional overhead by having to search the cache again,
2455 		 * but this case should be rare.
2456 		 */
2457 		mutex_exit(&rp->r_statelock);
2458 		nrdc = rddir4_cache_alloc(KM_SLEEP);
2459 		nrdc->nfs4_cookie = cookie;
2460 		nrdc->buflen = count;
2461 		mutex_enter(&rp->r_statelock);
2462 		/*
2463 		 * We need to take another pass through the cache
2464 		 * since we dropped our lock to perform the alloc.
2465 		 * Another thread may have come by and inserted the
2466 		 * entry we are interested in.
2467 		 */
2468 		goto top;
2469 	}
2470 
2471 	/*
2472 	 * Check to see if we need to free our entry.  This can happen if
2473 	 * another thread came along beat us to the insert.  We can
2474 	 * safely call rddir4_cache_free directly because no other thread
2475 	 * would have a reference to this entry.
2476 	 */
2477 	if (nrdc != NULL)
2478 		rddir4_cache_free((rddir4_cache_impl *)nrdc->data);
2479 
2480 #ifdef DEBUG
2481 	nfs4_readdir_cache_hits++;
2482 #endif
2483 	/*
2484 	 * Found something.  Make sure it's ready to return.
2485 	 */
2486 	rdc = &rdip->rc;
2487 	rddir4_cache_hold(rdc);
2488 	/*
2489 	 * If the cache entry is in the process of being filled in, wait
2490 	 * until this completes.  The RDDIRWAIT bit is set to indicate that
2491 	 * someone is waiting and when the thread currently filling the entry
2492 	 * is done, it should do a cv_broadcast to wakeup all of the threads
2493 	 * waiting for it to finish. If the thread wakes up to find that
2494 	 * someone new is now trying to complete the the entry, go back
2495 	 * to sleep.
2496 	 */
2497 	while (rdc->flags & RDDIR) {
2498 		/*
2499 		 * The entry is not complete.
2500 		 */
2501 		nfs_rw_exit(&rp->r_rwlock);
2502 		rdc->flags |= RDDIRWAIT;
2503 #ifdef DEBUG
2504 		nfs4_readdir_cache_waits++;
2505 #endif
2506 		while (rdc->flags & RDDIRWAIT) {
2507 			if (!cv_wait_sig(&rdc->cv, &rp->r_statelock)) {
2508 				/*
2509 				 * We got interrupted, probably the user
2510 				 * typed ^C or an alarm fired.  We free the
2511 				 * new entry if we allocated one.
2512 				 */
2513 				rddir4_cache_rele(rp, rdc);
2514 				mutex_exit(&rp->r_statelock);
2515 				(void) nfs_rw_enter_sig(&rp->r_rwlock,
2516 					RW_READER, FALSE);
2517 				mutex_enter(&rp->r_statelock);
2518 				return (NULL);
2519 			}
2520 		}
2521 		mutex_exit(&rp->r_statelock);
2522 		(void) nfs_rw_enter_sig(&rp->r_rwlock,
2523 			RW_READER, FALSE);
2524 		mutex_enter(&rp->r_statelock);
2525 	}
2526 
2527 	/*
2528 	 * The entry we were waiting on may have been purged from
2529 	 * the cache and should no longer be used, release it and
2530 	 * start over.
2531 	 */
2532 	if (!(rdc->flags & RDDIRCACHED)) {
2533 		rddir4_cache_rele(rp, rdc);
2534 		goto top;
2535 	}
2536 
2537 	/*
2538 	 * The entry is completed.  Return it.
2539 	 */
2540 	return (rdc);
2541 }
2542 
2543 /*
2544  * Allocate a cache element and return it.  Can return NULL if memory is
2545  * low.
2546  */
2547 static rddir4_cache *
2548 rddir4_cache_alloc(int flags)
2549 {
2550 	rddir4_cache_impl	*rdip = NULL;
2551 	rddir4_cache		*rc = NULL;
2552 
2553 	rdip = kmem_alloc(sizeof (rddir4_cache_impl), flags);
2554 
2555 	if (rdip != NULL) {
2556 		rc = &rdip->rc;
2557 		rc->data = (void *)rdip;
2558 		rc->nfs4_cookie = 0;
2559 		rc->nfs4_ncookie = 0;
2560 		rc->entries = NULL;
2561 		rc->eof = 0;
2562 		rc->entlen = 0;
2563 		rc->buflen = 0;
2564 		rc->actlen = 0;
2565 		/*
2566 		 * A readdir is required so set the flag.
2567 		 */
2568 		rc->flags = RDDIRREQ;
2569 		cv_init(&rc->cv, NULL, CV_DEFAULT, NULL);
2570 		rc->error = 0;
2571 		mutex_init(&rdip->lock, NULL, MUTEX_DEFAULT, NULL);
2572 		rdip->count = 1;
2573 #ifdef DEBUG
2574 		atomic_add_64(&clstat4_debug.dirent.value.ui64, 1);
2575 #endif
2576 	}
2577 	return (rc);
2578 }
2579 
2580 /*
2581  * Increment the reference count to this cache element.
2582  */
2583 static void
2584 rddir4_cache_hold(rddir4_cache *rc)
2585 {
2586 	rddir4_cache_impl *rdip = (rddir4_cache_impl *)rc->data;
2587 
2588 	mutex_enter(&rdip->lock);
2589 	rdip->count++;
2590 	mutex_exit(&rdip->lock);
2591 }
2592 
2593 /*
2594  * Release a reference to this cache element.  If the count is zero then
2595  * free the element.
2596  */
2597 void
2598 rddir4_cache_rele(rnode4_t *rp, rddir4_cache *rdc)
2599 {
2600 	rddir4_cache_impl *rdip = (rddir4_cache_impl *)rdc->data;
2601 
2602 	ASSERT(MUTEX_HELD(&rp->r_statelock));
2603 
2604 	/*
2605 	 * Check to see if we have any waiters.  If so, we can wake them
2606 	 * so that they can proceed.
2607 	 */
2608 	if (rdc->flags & RDDIRWAIT) {
2609 		rdc->flags &= ~RDDIRWAIT;
2610 		cv_broadcast(&rdc->cv);
2611 	}
2612 
2613 	mutex_enter(&rdip->lock);
2614 	ASSERT(rdip->count > 0);
2615 	if (--rdip->count == 0) {
2616 		mutex_exit(&rdip->lock);
2617 		rddir4_cache_free(rdip);
2618 	} else
2619 		mutex_exit(&rdip->lock);
2620 }
2621 
2622 /*
2623  * Free a cache element.
2624  */
2625 static void
2626 rddir4_cache_free(rddir4_cache_impl *rdip)
2627 {
2628 	rddir4_cache *rc = &rdip->rc;
2629 
2630 #ifdef DEBUG
2631 	atomic_add_64(&clstat4_debug.dirent.value.ui64, -1);
2632 #endif
2633 	if (rc->entries != NULL)
2634 		kmem_free(rc->entries, rc->buflen);
2635 	cv_destroy(&rc->cv);
2636 	mutex_destroy(&rdip->lock);
2637 	kmem_free(rdip, sizeof (*rdip));
2638 }
2639 
2640 /*
2641  * Snapshot callback for nfs:0:nfs4_client as registered with the kstat
2642  * framework.
2643  */
2644 static int
2645 cl4_snapshot(kstat_t *ksp, void *buf, int rw)
2646 {
2647 	ksp->ks_snaptime = gethrtime();
2648 	if (rw == KSTAT_WRITE) {
2649 		bcopy(buf, ksp->ks_private, sizeof (clstat4_tmpl));
2650 #ifdef DEBUG
2651 		/*
2652 		 * Currently only the global zone can write to kstats, but we
2653 		 * add the check just for paranoia.
2654 		 */
2655 		if (INGLOBALZONE(curproc))
2656 		    bcopy((char *)buf + sizeof (clstat4_tmpl), &clstat4_debug,
2657 			    sizeof (clstat4_debug));
2658 #endif
2659 	} else {
2660 		bcopy(ksp->ks_private, buf, sizeof (clstat4_tmpl));
2661 #ifdef DEBUG
2662 		/*
2663 		 * If we're displaying the "global" debug kstat values, we
2664 		 * display them as-is to all zones since in fact they apply to
2665 		 * the system as a whole.
2666 		 */
2667 		bcopy(&clstat4_debug, (char *)buf + sizeof (clstat4_tmpl),
2668 		    sizeof (clstat4_debug));
2669 #endif
2670 	}
2671 	return (0);
2672 }
2673 
2674 
2675 
2676 /*
2677  * Zone support
2678  */
2679 static void *
2680 clinit4_zone(zoneid_t zoneid)
2681 {
2682 	kstat_t *nfs4_client_kstat;
2683 	struct nfs4_clnt *nfscl;
2684 	uint_t ndata;
2685 
2686 	nfscl = kmem_alloc(sizeof (*nfscl), KM_SLEEP);
2687 	mutex_init(&nfscl->nfscl_chtable4_lock, NULL, MUTEX_DEFAULT, NULL);
2688 	nfscl->nfscl_chtable4 = NULL;
2689 	nfscl->nfscl_zoneid = zoneid;
2690 
2691 	bcopy(&clstat4_tmpl, &nfscl->nfscl_stat, sizeof (clstat4_tmpl));
2692 	ndata = sizeof (clstat4_tmpl) / sizeof (kstat_named_t);
2693 #ifdef DEBUG
2694 	ndata += sizeof (clstat4_debug) / sizeof (kstat_named_t);
2695 #endif
2696 	if ((nfs4_client_kstat = kstat_create_zone("nfs", 0, "nfs4_client",
2697 	    "misc", KSTAT_TYPE_NAMED, ndata,
2698 	    KSTAT_FLAG_VIRTUAL | KSTAT_FLAG_WRITABLE, zoneid)) != NULL) {
2699 		nfs4_client_kstat->ks_private = &nfscl->nfscl_stat;
2700 		nfs4_client_kstat->ks_snapshot = cl4_snapshot;
2701 		kstat_install(nfs4_client_kstat);
2702 	}
2703 	mutex_enter(&nfs4_clnt_list_lock);
2704 	list_insert_head(&nfs4_clnt_list, nfscl);
2705 	mutex_exit(&nfs4_clnt_list_lock);
2706 	return (nfscl);
2707 }
2708 
2709 /*ARGSUSED*/
2710 static void
2711 clfini4_zone(zoneid_t zoneid, void *arg)
2712 {
2713 	struct nfs4_clnt *nfscl = arg;
2714 	chhead_t *chp, *next;
2715 
2716 	if (nfscl == NULL)
2717 		return;
2718 	mutex_enter(&nfs4_clnt_list_lock);
2719 	list_remove(&nfs4_clnt_list, nfscl);
2720 	mutex_exit(&nfs4_clnt_list_lock);
2721 	clreclaim4_zone(nfscl, 0);
2722 	for (chp = nfscl->nfscl_chtable4; chp != NULL; chp = next) {
2723 		ASSERT(chp->ch_list == NULL);
2724 		kmem_free(chp->ch_protofmly, strlen(chp->ch_protofmly) + 1);
2725 		next = chp->ch_next;
2726 		kmem_free(chp, sizeof (*chp));
2727 	}
2728 	kstat_delete_byname_zone("nfs", 0, "nfs4_client", zoneid);
2729 	mutex_destroy(&nfscl->nfscl_chtable4_lock);
2730 	kmem_free(nfscl, sizeof (*nfscl));
2731 }
2732 
2733 /*
2734  * Called by endpnt_destructor to make sure the client handles are
2735  * cleaned up before the RPC endpoints.  This becomes a no-op if
2736  * clfini_zone (above) is called first.  This function is needed
2737  * (rather than relying on clfini_zone to clean up) because the ZSD
2738  * callbacks have no ordering mechanism, so we have no way to ensure
2739  * that clfini_zone is called before endpnt_destructor.
2740  */
2741 void
2742 clcleanup4_zone(zoneid_t zoneid)
2743 {
2744 	struct nfs4_clnt *nfscl;
2745 
2746 	mutex_enter(&nfs4_clnt_list_lock);
2747 	nfscl = list_head(&nfs4_clnt_list);
2748 	for (; nfscl != NULL; nfscl = list_next(&nfs4_clnt_list, nfscl)) {
2749 		if (nfscl->nfscl_zoneid == zoneid) {
2750 			clreclaim4_zone(nfscl, 0);
2751 			break;
2752 		}
2753 	}
2754 	mutex_exit(&nfs4_clnt_list_lock);
2755 }
2756 
2757 int
2758 nfs4_subr_init(void)
2759 {
2760 	/*
2761 	 * Allocate and initialize the client handle cache
2762 	 */
2763 	chtab4_cache = kmem_cache_create("client_handle4_cache",
2764 		sizeof (struct chtab), 0, NULL, NULL, clreclaim4, NULL,
2765 		NULL, 0);
2766 
2767 	/*
2768 	 * Initialize the list of per-zone client handles (and associated data).
2769 	 * This needs to be done before we call zone_key_create().
2770 	 */
2771 	list_create(&nfs4_clnt_list, sizeof (struct nfs4_clnt),
2772 	    offsetof(struct nfs4_clnt, nfscl_node));
2773 
2774 	/*
2775 	 * Initialize the zone_key for per-zone client handle lists.
2776 	 */
2777 	zone_key_create(&nfs4clnt_zone_key, clinit4_zone, NULL, clfini4_zone);
2778 
2779 	if (nfs4err_delay_time == 0)
2780 		nfs4err_delay_time = NFS4ERR_DELAY_TIME;
2781 
2782 	return (0);
2783 }
2784 
2785 int
2786 nfs4_subr_fini(void)
2787 {
2788 	/*
2789 	 * Deallocate the client handle cache
2790 	 */
2791 	kmem_cache_destroy(chtab4_cache);
2792 
2793 	/*
2794 	 * Destroy the zone_key
2795 	 */
2796 	(void) zone_key_delete(nfs4clnt_zone_key);
2797 
2798 	return (0);
2799 }
2800 /*
2801  * Set or Clear direct I/O flag
2802  * VOP_RWLOCK() is held for write access to prevent a race condition
2803  * which would occur if a process is in the middle of a write when
2804  * directio flag gets set. It is possible that all pages may not get flushed.
2805  *
2806  * This is a copy of nfs_directio, changes here may need to be made
2807  * there and vice versa.
2808  */
2809 
2810 int
2811 nfs4_directio(vnode_t *vp, int cmd, cred_t *cr)
2812 {
2813 	int	error = 0;
2814 	rnode4_t *rp;
2815 
2816 	rp = VTOR4(vp);
2817 
2818 	if (cmd == DIRECTIO_ON) {
2819 
2820 		if (rp->r_flags & R4DIRECTIO)
2821 			return (0);
2822 
2823 		/*
2824 		 * Flush the page cache.
2825 		 */
2826 
2827 		(void) VOP_RWLOCK(vp, V_WRITELOCK_TRUE, NULL);
2828 
2829 		if (rp->r_flags & R4DIRECTIO) {
2830 			VOP_RWUNLOCK(vp, V_WRITELOCK_TRUE, NULL);
2831 			return (0);
2832 		}
2833 
2834 		if (nfs4_has_pages(vp) &&
2835 		    ((rp->r_flags & R4DIRTY) || rp->r_awcount > 0)) {
2836 			error = VOP_PUTPAGE(vp, (offset_t)0, (uint_t)0,
2837 			    B_INVAL, cr);
2838 			if (error) {
2839 				if (error == ENOSPC || error == EDQUOT) {
2840 					mutex_enter(&rp->r_statelock);
2841 					if (!rp->r_error)
2842 						rp->r_error = error;
2843 					mutex_exit(&rp->r_statelock);
2844 				}
2845 				VOP_RWUNLOCK(vp, V_WRITELOCK_TRUE, NULL);
2846 				return (error);
2847 			}
2848 		}
2849 
2850 		mutex_enter(&rp->r_statelock);
2851 		rp->r_flags |= R4DIRECTIO;
2852 		mutex_exit(&rp->r_statelock);
2853 		VOP_RWUNLOCK(vp, V_WRITELOCK_TRUE, NULL);
2854 		return (0);
2855 	}
2856 
2857 	if (cmd == DIRECTIO_OFF) {
2858 		mutex_enter(&rp->r_statelock);
2859 		rp->r_flags &= ~R4DIRECTIO;	/* disable direct mode */
2860 		mutex_exit(&rp->r_statelock);
2861 		return (0);
2862 	}
2863 
2864 	return (EINVAL);
2865 }
2866 
2867 /*
2868  * Return TRUE if the file has any pages.  Always go back to
2869  * the master vnode to check v_pages since none of the shadows
2870  * can have pages.
2871  */
2872 
2873 bool_t
2874 nfs4_has_pages(vnode_t *vp)
2875 {
2876 	rnode4_t *rp;
2877 
2878 	rp = VTOR4(vp);
2879 	if (IS_SHADOW(vp, rp))
2880 		vp = RTOV4(rp);	/* RTOV4 always gives the master */
2881 
2882 	return (vn_has_cached_data(vp));
2883 }
2884 
2885 /*
2886  * This table is used to determine whether the client should attempt
2887  * failover based on the clnt_stat value returned by CLNT_CALL.  The
2888  * clnt_stat is used as an index into the table.  If
2889  * the error value that corresponds to the clnt_stat value in the
2890  * table is non-zero, then that is the error to be returned AND
2891  * that signals that failover should be attempted.
2892  *
2893  * Special note: If the RPC_ values change, then direct indexing of the
2894  * table is no longer valid, but having the RPC_ values in the table
2895  * allow the functions to detect the change and issue a warning.
2896  * In this case, the code will always attempt failover as a defensive
2897  * measure.
2898  */
2899 
2900 static struct try_failover_tab {
2901 	enum clnt_stat	cstat;
2902 	int		error;
2903 } try_failover_table [] = {
2904 
2905 	RPC_SUCCESS,		0,
2906 	RPC_CANTENCODEARGS,	0,
2907 	RPC_CANTDECODERES,	0,
2908 	RPC_CANTSEND,		ECOMM,
2909 	RPC_CANTRECV,		ECOMM,
2910 	RPC_TIMEDOUT,		ETIMEDOUT,
2911 	RPC_VERSMISMATCH,	0,
2912 	RPC_AUTHERROR,		0,
2913 	RPC_PROGUNAVAIL,	0,
2914 	RPC_PROGVERSMISMATCH,	0,
2915 	RPC_PROCUNAVAIL,	0,
2916 	RPC_CANTDECODEARGS,	0,
2917 	RPC_SYSTEMERROR,	ENOSR,
2918 	RPC_UNKNOWNHOST,	EHOSTUNREACH,
2919 	RPC_RPCBFAILURE,	ENETUNREACH,
2920 	RPC_PROGNOTREGISTERED,	ECONNREFUSED,
2921 	RPC_FAILED,		ETIMEDOUT,
2922 	RPC_UNKNOWNPROTO,	EHOSTUNREACH,
2923 	RPC_INTR,		0,
2924 	RPC_UNKNOWNADDR,	EHOSTUNREACH,
2925 	RPC_TLIERROR,		0,
2926 	RPC_NOBROADCAST,	EHOSTUNREACH,
2927 	RPC_N2AXLATEFAILURE,	ECONNREFUSED,
2928 	RPC_UDERROR,		0,
2929 	RPC_INPROGRESS,		0,
2930 	RPC_STALERACHANDLE,	EINVAL,
2931 	RPC_CANTCONNECT,	ECONNREFUSED,
2932 	RPC_XPRTFAILED,		ECONNABORTED,
2933 	RPC_CANTCREATESTREAM,	ECONNREFUSED,
2934 	RPC_CANTSTORE,		ENOBUFS
2935 };
2936 
2937 /*
2938  * nfs4_try_failover - determine whether the client should
2939  * attempt failover based on the values stored in the nfs4_error_t.
2940  */
2941 int
2942 nfs4_try_failover(nfs4_error_t *ep)
2943 {
2944 	if (ep->error == ETIMEDOUT || ep->stat == NFS4ERR_RESOURCE)
2945 		return (TRUE);
2946 
2947 	if (ep->error && ep->rpc_status != RPC_SUCCESS)
2948 		return (try_failover(ep->rpc_status) != 0 ? TRUE : FALSE);
2949 
2950 	return (FALSE);
2951 }
2952 
2953 /*
2954  * try_failover - internal version of nfs4_try_failover, called
2955  * only by rfscall and aclcall.  Determine if failover is warranted
2956  * based on the clnt_stat and return the error number if it is.
2957  */
2958 static int
2959 try_failover(enum clnt_stat rpc_status)
2960 {
2961 	int err = 0;
2962 
2963 	if (rpc_status == RPC_SUCCESS)
2964 		return (0);
2965 
2966 #ifdef	DEBUG
2967 	if (rpc_status != 0 && nfs4_try_failover_any) {
2968 		err = ETIMEDOUT;
2969 		goto done;
2970 	}
2971 #endif
2972 	/*
2973 	 * The rpc status is used as an index into the table.
2974 	 * If the rpc status is outside of the range of the
2975 	 * table or if the rpc error numbers have been changed
2976 	 * since the table was constructed, then print a warning
2977 	 * (DEBUG only) and try failover anyway.  Otherwise, just
2978 	 * grab the resulting error number out of the table.
2979 	 */
2980 	if (rpc_status < RPC_SUCCESS || rpc_status >=
2981 	    sizeof (try_failover_table)/sizeof (try_failover_table[0]) ||
2982 	    try_failover_table[rpc_status].cstat != rpc_status) {
2983 
2984 		err = ETIMEDOUT;
2985 #ifdef	DEBUG
2986 		cmn_err(CE_NOTE, "try_failover: unexpected rpc error %d",
2987 			rpc_status);
2988 #endif
2989 	} else
2990 		err = try_failover_table[rpc_status].error;
2991 
2992 done:
2993 	if (rpc_status)
2994 		NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
2995 			"nfs4_try_failover: %strying failover on error %d",
2996 			err ? "" : "NOT ", rpc_status));
2997 
2998 	return (err);
2999 }
3000 
3001 void
3002 nfs4_error_zinit(nfs4_error_t *ep)
3003 {
3004 	ep->error = 0;
3005 	ep->stat = NFS4_OK;
3006 	ep->rpc_status = RPC_SUCCESS;
3007 }
3008 
3009 void
3010 nfs4_error_init(nfs4_error_t *ep, int error)
3011 {
3012 	ep->error = error;
3013 	ep->stat = NFS4_OK;
3014 	ep->rpc_status = RPC_SUCCESS;
3015 }
3016 
3017 
3018 #ifdef DEBUG
3019 
3020 /*
3021  * Return a 16-bit hash for filehandle, stateid, clientid, owner.
3022  * use the same algorithm as for NFS v3.
3023  *
3024  */
3025 int
3026 hash16(void *p, int len)
3027 {
3028 	int i, rem;
3029 	uint_t *wp;
3030 	uint_t key = 0;
3031 
3032 	/* protect against non word aligned */
3033 	if ((rem = len & 3) != 0)
3034 		len &= ~3;
3035 
3036 	for (i = 0, wp = (uint_t *)p; i < len; i += 4, wp++) {
3037 		key ^= (*wp >> 16) ^ *wp;
3038 	}
3039 
3040 	/* hash left-over bytes */
3041 	for (i = 0; i < rem; i++)
3042 		key ^= *((uchar_t *)p + i);
3043 
3044 	return (key & 0xffff);
3045 }
3046 
3047 /*
3048  * rnode4info - return filehandle and path information for an rnode.
3049  * XXX MT issues: uses a single static buffer, no locking of path.
3050  */
3051 char *
3052 rnode4info(rnode4_t *rp)
3053 {
3054 	static char buf[80];
3055 	nfs4_fhandle_t fhandle;
3056 	char *path;
3057 	char *type;
3058 
3059 	if (rp == NULL)
3060 		return ("null");
3061 	if (rp->r_flags & R4ISXATTR)
3062 		type = "attr";
3063 	else if (RTOV4(rp)->v_flag & V_XATTRDIR)
3064 		type = "attrdir";
3065 	else if (RTOV4(rp)->v_flag & VROOT)
3066 		type = "root";
3067 	else if (RTOV4(rp)->v_type == VDIR)
3068 		type = "dir";
3069 	else if (RTOV4(rp)->v_type == VREG)
3070 		type = "file";
3071 	else
3072 		type = "other";
3073 	sfh4_copyval(rp->r_fh, &fhandle);
3074 	path = fn_path(rp->r_svnode.sv_name);
3075 	(void) snprintf(buf, 80, "$%p[%s], type=%s, flags=%04X, FH=%04X\n",
3076 	    (void *)rp, path, type, rp->r_flags,
3077 	    hash16((void *)&fhandle.fh_buf, fhandle.fh_len));
3078 	kmem_free(path, strlen(path)+1);
3079 	return (buf);
3080 }
3081 #endif
3082