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 (the "License").
   6  * You may not use this file except in compliance with the License.
   7  *
   8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
   9  * or http://www.opensolaris.org/os/licensing.
  10  * See the License for the specific language governing permissions
  11  * and limitations under the License.
  12  *
  13  * When distributing Covered Code, include this CDDL HEADER in each
  14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
  15  * If applicable, add the following below this CDDL HEADER, with the
  16  * fields enclosed by brackets "[]" replaced with your own identifying
  17  * information: Portions Copyright [yyyy] [name of copyright owner]
  18  *
  19  * CDDL HEADER END
  20  */
  21 
  22 /*
  23  * Copyright (c) 1995, 2010, Oracle and/or its affiliates. All rights reserved.
  24  * Copyright (c) 2015 by Delphix. All rights reserved.
  25  * Copyright 2018 Nexenta Systems, Inc. All rights reserved.
  26  */
  27 
  28 #include <sys/param.h>
  29 #include <sys/errno.h>
  30 #include <sys/vfs.h>
  31 #include <sys/vnode.h>
  32 #include <sys/cred.h>
  33 #include <sys/cmn_err.h>
  34 #include <sys/systm.h>
  35 #include <sys/kmem.h>
  36 #include <sys/pathname.h>
  37 #include <sys/utsname.h>
  38 #include <sys/debug.h>
  39 #include <sys/door.h>
  40 #include <sys/sdt.h>
  41 #include <sys/thread.h>
  42 #include <sys/avl.h>
  43 
  44 #include <rpc/types.h>
  45 #include <rpc/auth.h>
  46 #include <rpc/clnt.h>
  47 
  48 #include <nfs/nfs.h>
  49 #include <nfs/export.h>
  50 #include <nfs/nfs_clnt.h>
  51 #include <nfs/auth.h>
  52 
  53 static struct kmem_cache *exi_cache_handle;
  54 static void exi_cache_reclaim(void *);
  55 static void exi_cache_trim(struct exportinfo *exi);
  56 static void *nfsauth_zone_init(zoneid_t);
  57 static void nfsauth_zone_shutdown(zoneid_t zoneid, void *data);
  58 static void nfsauth_zone_fini(zoneid_t, void *);
  59 
  60 extern pri_t minclsyspri;
  61 
  62 /* NFS auth cache statistics */
  63 volatile uint_t nfsauth_cache_hit;
  64 volatile uint_t nfsauth_cache_miss;
  65 volatile uint_t nfsauth_cache_refresh;
  66 volatile uint_t nfsauth_cache_reclaim;
  67 volatile uint_t exi_cache_auth_reclaim_failed;
  68 volatile uint_t exi_cache_clnt_reclaim_failed;
  69 
  70 /*
  71  * The lifetime of an auth cache entry:
  72  * ------------------------------------
  73  *
  74  * An auth cache entry is created with both the auth_time
  75  * and auth_freshness times set to the current time.
  76  *
  77  * Upon every client access which results in a hit, the
  78  * auth_time will be updated.
  79  *
  80  * If a client access determines that the auth_freshness
  81  * indicates that the entry is STALE, then it will be
  82  * refreshed. Note that this will explicitly reset
  83  * auth_time.
  84  *
  85  * When the REFRESH successfully occurs, then the
  86  * auth_freshness is updated.
  87  *
  88  * There are two ways for an entry to leave the cache:
  89  *
  90  * 1) Purged by an action on the export (remove or changed)
  91  * 2) Memory backpressure from the kernel (check against NFSAUTH_CACHE_TRIM)
  92  *
  93  * For 2) we check the timeout value against auth_time.
  94  */
  95 
  96 /*
  97  * Number of seconds until we mark for refresh an auth cache entry.
  98  */
  99 #define NFSAUTH_CACHE_REFRESH 600
 100 
 101 /*
 102  * Number of idle seconds until we yield to backpressure
 103  * to trim a cache entry.
 104  */
 105 #define NFSAUTH_CACHE_TRIM 3600
 106 
 107 /*
 108  * While we could encapuslate the exi_list inside the
 109  * exi structure, we can't do that for the auth_list.
 110  * So, to keep things looking clean, we keep them both
 111  * in these external lists.
 112  */
 113 typedef struct refreshq_exi_node {
 114         struct exportinfo       *ren_exi;
 115         list_t                  ren_authlist;
 116         list_node_t             ren_node;
 117 } refreshq_exi_node_t;
 118 
 119 typedef struct refreshq_auth_node {
 120         struct auth_cache       *ran_auth;
 121         char                    *ran_netid;
 122         list_node_t             ran_node;
 123 } refreshq_auth_node_t;
 124 
 125 /*
 126  * Used to manipulate things on the refreshq_queue.  Note that the refresh
 127  * thread will effectively pop a node off of the queue, at which point it
 128  * will no longer need to hold the mutex.
 129  */
 130 static kmutex_t refreshq_lock;
 131 static list_t refreshq_queue;
 132 static kcondvar_t refreshq_cv;
 133 
 134 /*
 135  * If there is ever a problem with loading the module, then nfsauth_fini()
 136  * needs to be called to remove state.  In that event, since the refreshq
 137  * thread has been started, they need to work together to get rid of state.
 138  */
 139 typedef enum nfsauth_refreshq_thread_state {
 140         REFRESHQ_THREAD_RUNNING,
 141         REFRESHQ_THREAD_FINI_REQ,
 142         REFRESHQ_THREAD_HALTED,
 143         REFRESHQ_THREAD_NEED_CREATE
 144 } nfsauth_refreshq_thread_state_t;
 145 
 146 typedef struct nfsauth_globals {
 147         kmutex_t        mountd_lock;
 148         door_handle_t   mountd_dh;
 149 
 150         /*
 151          * Used to manipulate things on the refreshq_queue.  Note that the
 152          * refresh thread will effectively pop a node off of the queue,
 153          * at which point it will no longer need to hold the mutex.
 154          */
 155         kmutex_t        refreshq_lock;
 156         list_t          refreshq_queue;
 157         kcondvar_t      refreshq_cv;
 158 
 159         /*
 160          * A list_t would be overkill.  These are auth_cache entries which are
 161          * no longer linked to an exi.  It should be the case that all of their
 162          * states are NFS_AUTH_INVALID, i.e., the only way to be put on this
 163          * list is iff their state indicated that they had been placed on the
 164          * refreshq_queue.
 165          *
 166          * Note that while there is no link from the exi or back to the exi,
 167          * the exi can not go away until these entries are harvested.
 168          */
 169         struct auth_cache               *refreshq_dead_entries;
 170         nfsauth_refreshq_thread_state_t refreshq_thread_state;
 171 
 172 } nfsauth_globals_t;
 173 
 174 static void nfsauth_free_node(struct auth_cache *);
 175 static void nfsauth_refresh_thread(nfsauth_globals_t *);
 176 
 177 static int nfsauth_cache_compar(const void *, const void *);
 178 
 179 static zone_key_t       nfsauth_zone_key;
 180 
 181 void
 182 mountd_args(uint_t did)
 183 {
 184         nfsauth_globals_t *nag;
 185 
 186         nag = zone_getspecific(nfsauth_zone_key, curzone);
 187         mutex_enter(&nag->mountd_lock);
 188         if (nag->mountd_dh != NULL)
 189                 door_ki_rele(nag->mountd_dh);
 190         nag->mountd_dh = door_ki_lookup(did);
 191         mutex_exit(&nag->mountd_lock);
 192 }
 193 
 194 void
 195 nfsauth_init(void)
 196 {
 197         zone_key_create(&nfsauth_zone_key, nfsauth_zone_init,
 198             nfsauth_zone_shutdown, nfsauth_zone_fini);
 199 
 200         exi_cache_handle = kmem_cache_create("exi_cache_handle",
 201             sizeof (struct auth_cache), 0, NULL, NULL,
 202             exi_cache_reclaim, NULL, NULL, 0);
 203 }
 204 
 205 void
 206 nfsauth_fini(void)
 207 {
 208         kmem_cache_destroy(exi_cache_handle);
 209 }
 210 
 211 /*ARGSUSED*/
 212 static void *
 213 nfsauth_zone_init(zoneid_t zoneid)
 214 {
 215         nfsauth_globals_t *nag;
 216 
 217         nag = kmem_zalloc(sizeof (*nag), KM_SLEEP);
 218 
 219         /*
 220          * mountd can be restarted by smf(5).  We need to make sure
 221          * the updated door handle will safely make it to mountd_dh.
 222          */
 223         mutex_init(&nag->mountd_lock, NULL, MUTEX_DEFAULT, NULL);
 224         mutex_init(&nag->refreshq_lock, NULL, MUTEX_DEFAULT, NULL);
 225         list_create(&nag->refreshq_queue, sizeof (refreshq_exi_node_t),
 226             offsetof(refreshq_exi_node_t, ren_node));
 227         cv_init(&nag->refreshq_cv, NULL, CV_DEFAULT, NULL);
 228         nag->refreshq_thread_state = REFRESHQ_THREAD_NEED_CREATE;
 229 
 230         return (nag);
 231 }
 232 
 233 /*ARGSUSED*/
 234 static void
 235 nfsauth_zone_shutdown(zoneid_t zoneid, void *data)
 236 {
 237         refreshq_exi_node_t     *ren;
 238         nfsauth_globals_t       *nag = data;
 239 
 240         /* Prevent the nfsauth_refresh_thread from getting new work */
 241         mutex_enter(&nag->refreshq_lock);
 242         if (nag->refreshq_thread_state == REFRESHQ_THREAD_RUNNING) {
 243                 nag->refreshq_thread_state = REFRESHQ_THREAD_FINI_REQ;
 244                 cv_broadcast(&nag->refreshq_cv);
 245 
 246                 /* Wait for nfsauth_refresh_thread() to exit */
 247                 while (nag->refreshq_thread_state != REFRESHQ_THREAD_HALTED)
 248                         cv_wait(&nag->refreshq_cv, &nag->refreshq_lock);
 249         }
 250         mutex_exit(&nag->refreshq_lock);
 251 
 252         /*
 253          * Walk the exi_list and in turn, walk the auth_lists and free all
 254          * lists.  In addition, free INVALID auth_cache entries.
 255          */
 256         while ((ren = list_remove_head(&nag->refreshq_queue))) {
 257                 refreshq_auth_node_t *ran;
 258 
 259                 while ((ran = list_remove_head(&ren->ren_authlist)) != NULL) {
 260                         struct auth_cache *p = ran->ran_auth;
 261                         if (p->auth_state == NFS_AUTH_INVALID)
 262                                 nfsauth_free_node(p);
 263                         strfree(ran->ran_netid);
 264                         kmem_free(ran, sizeof (*ran));
 265                 }
 266 
 267                 list_destroy(&ren->ren_authlist);
 268                 exi_rele(ren->ren_exi);
 269                 kmem_free(ren, sizeof (*ren));
 270         }
 271 }
 272 
 273 /*ARGSUSED*/
 274 static void
 275 nfsauth_zone_fini(zoneid_t zoneid, void *data)
 276 {
 277         nfsauth_globals_t *nag = data;
 278 
 279         list_destroy(&nag->refreshq_queue);
 280         cv_destroy(&nag->refreshq_cv);
 281         mutex_destroy(&nag->refreshq_lock);
 282         mutex_destroy(&nag->mountd_lock);
 283         kmem_free(nag, sizeof (*nag));
 284 }
 285 
 286 /*
 287  * Convert the address in a netbuf to
 288  * a hash index for the auth_cache table.
 289  */
 290 static int
 291 hash(struct netbuf *a)
 292 {
 293         int i, h = 0;
 294 
 295         for (i = 0; i < a->len; i++)
 296                 h ^= a->buf[i];
 297 
 298         return (h & (AUTH_TABLESIZE - 1));
 299 }
 300 
 301 /*
 302  * Mask out the components of an
 303  * address that do not identify
 304  * a host. For socket addresses the
 305  * masking gets rid of the port number.
 306  */
 307 static void
 308 addrmask(struct netbuf *addr, struct netbuf *mask)
 309 {
 310         int i;
 311 
 312         for (i = 0; i < addr->len; i++)
 313                 addr->buf[i] &= mask->buf[i];
 314 }
 315 
 316 /*
 317  * nfsauth4_access is used for NFS V4 auth checking. Besides doing
 318  * the common nfsauth_access(), it will check if the client can
 319  * have a limited access to this vnode even if the security flavor
 320  * used does not meet the policy.
 321  */
 322 int
 323 nfsauth4_access(struct exportinfo *exi, vnode_t *vp, struct svc_req *req,
 324     cred_t *cr, uid_t *uid, gid_t *gid, uint_t *ngids, gid_t **gids)
 325 {
 326         int access;
 327 
 328         access = nfsauth_access(exi, req, cr, uid, gid, ngids, gids);
 329 
 330         /*
 331          * There are cases that the server needs to allow the client
 332          * to have a limited view.
 333          *
 334          * e.g.
 335          * /export is shared as "sec=sys,rw=dfs-test-4,sec=krb5,rw"
 336          * /export/home is shared as "sec=sys,rw"
 337          *
 338          * When the client mounts /export with sec=sys, the client
 339          * would get a limited view with RO access on /export to see
 340          * "home" only because the client is allowed to access
 341          * /export/home with auth_sys.
 342          */
 343         if (access & NFSAUTH_DENIED || access & NFSAUTH_WRONGSEC) {
 344                 /*
 345                  * Allow ro permission with LIMITED view if there is a
 346                  * sub-dir exported under vp.
 347                  */
 348                 if (has_visible(exi, vp))
 349                         return (NFSAUTH_LIMITED);
 350         }
 351 
 352         return (access);
 353 }
 354 
 355 static void
 356 sys_log(const char *msg)
 357 {
 358         static time_t   tstamp = 0;
 359         time_t          now;
 360 
 361         /*
 362          * msg is shown (at most) once per minute
 363          */
 364         now = gethrestime_sec();
 365         if ((tstamp + 60) < now) {
 366                 tstamp = now;
 367                 cmn_err(CE_WARN, msg);
 368         }
 369 }
 370 
 371 /*
 372  * Callup to the mountd to get access information in the kernel.
 373  */
 374 static bool_t
 375 nfsauth_retrieve(nfsauth_globals_t *nag, struct exportinfo *exi,
 376     char *req_netid, int flavor, struct netbuf *addr, int *access,
 377     cred_t *clnt_cred, uid_t *srv_uid, gid_t *srv_gid, uint_t *srv_gids_cnt,
 378     gid_t **srv_gids)
 379 {
 380         varg_t                    varg = {0};
 381         nfsauth_res_t             res = {0};
 382         XDR                       xdrs;
 383         size_t                    absz;
 384         caddr_t                   abuf;
 385         int                       last = 0;
 386         door_arg_t                da;
 387         door_info_t               di;
 388         door_handle_t             dh;
 389         uint_t                    ntries = 0;
 390 
 391         /*
 392          * No entry in the cache for this client/flavor
 393          * so we need to call the nfsauth service in the
 394          * mount daemon.
 395          */
 396 
 397         varg.vers = V_PROTO;
 398         varg.arg_u.arg.cmd = NFSAUTH_ACCESS;
 399         varg.arg_u.arg.areq.req_client.n_len = addr->len;
 400         varg.arg_u.arg.areq.req_client.n_bytes = addr->buf;
 401         varg.arg_u.arg.areq.req_netid = req_netid;
 402         varg.arg_u.arg.areq.req_path = exi->exi_export.ex_path;
 403         varg.arg_u.arg.areq.req_flavor = flavor;
 404         varg.arg_u.arg.areq.req_clnt_uid = crgetuid(clnt_cred);
 405         varg.arg_u.arg.areq.req_clnt_gid = crgetgid(clnt_cred);
 406         varg.arg_u.arg.areq.req_clnt_gids.len = crgetngroups(clnt_cred);
 407         varg.arg_u.arg.areq.req_clnt_gids.val = (gid_t *)crgetgroups(clnt_cred);
 408 
 409         DTRACE_PROBE1(nfsserv__func__nfsauth__varg, varg_t *, &varg);
 410 
 411         /*
 412          * Setup the XDR stream for encoding the arguments. Notice that
 413          * in addition to the args having variable fields (req_netid and
 414          * req_path), the argument data structure is itself versioned,
 415          * so we need to make sure we can size the arguments buffer
 416          * appropriately to encode all the args. If we can't get sizing
 417          * info _or_ properly encode the arguments, there's really no
 418          * point in continuting, so we fail the request.
 419          */
 420         if ((absz = xdr_sizeof(xdr_varg, &varg)) == 0) {
 421                 *access = NFSAUTH_DENIED;
 422                 return (FALSE);
 423         }
 424 
 425         abuf = (caddr_t)kmem_alloc(absz, KM_SLEEP);
 426         xdrmem_create(&xdrs, abuf, absz, XDR_ENCODE);
 427         if (!xdr_varg(&xdrs, &varg)) {
 428                 XDR_DESTROY(&xdrs);
 429                 goto fail;
 430         }
 431         XDR_DESTROY(&xdrs);
 432 
 433         /*
 434          * Prepare the door arguments
 435          *
 436          * We don't know the size of the message the daemon
 437          * will pass back to us.  By setting rbuf to NULL,
 438          * we force the door code to allocate a buf of the
 439          * appropriate size.  We must set rsize > 0, however,
 440          * else the door code acts as if no response was
 441          * expected and doesn't pass the data to us.
 442          */
 443         da.data_ptr = (char *)abuf;
 444         da.data_size = absz;
 445         da.desc_ptr = NULL;
 446         da.desc_num = 0;
 447         da.rbuf = NULL;
 448         da.rsize = 1;
 449 
 450 retry:
 451         mutex_enter(&nag->mountd_lock);
 452         dh = nag->mountd_dh;
 453         if (dh != NULL)
 454                 door_ki_hold(dh);
 455         mutex_exit(&nag->mountd_lock);
 456 
 457         if (dh == NULL) {
 458                 /*
 459                  * The rendezvous point has not been established yet!
 460                  * This could mean that either mountd(1m) has not yet
 461                  * been started or that _this_ routine nuked the door
 462                  * handle after receiving an EINTR for a REVOKED door.
 463                  *
 464                  * Returning NFSAUTH_DROP will cause the NFS client
 465                  * to retransmit the request, so let's try to be more
 466                  * rescillient and attempt for ntries before we bail.
 467                  */
 468                 if (++ntries % NFSAUTH_DR_TRYCNT) {
 469                         delay(hz);
 470                         goto retry;
 471                 }
 472 
 473                 kmem_free(abuf, absz);
 474 
 475                 sys_log("nfsauth: mountd has not established door");
 476                 *access = NFSAUTH_DROP;
 477                 return (FALSE);
 478         }
 479 
 480         ntries = 0;
 481 
 482         /*
 483          * Now that we've got what we need, place the call.
 484          */
 485         switch (door_ki_upcall_limited(dh, &da, NULL, SIZE_MAX, 0)) {
 486         case 0:                         /* Success */
 487                 door_ki_rele(dh);
 488 
 489                 if (da.data_ptr == NULL && da.data_size == 0) {
 490                         /*
 491                          * The door_return that contained the data
 492                          * failed! We're here because of the 2nd
 493                          * door_return (w/o data) such that we can
 494                          * get control of the thread (and exit
 495                          * gracefully).
 496                          */
 497                         DTRACE_PROBE1(nfsserv__func__nfsauth__door__nil,
 498                             door_arg_t *, &da);
 499                         goto fail;
 500                 }
 501 
 502                 break;
 503 
 504         case EAGAIN:
 505                 /*
 506                  * Server out of resources; back off for a bit
 507                  */
 508                 door_ki_rele(dh);
 509                 delay(hz);
 510                 goto retry;
 511                 /* NOTREACHED */
 512 
 513         case EINTR:
 514                 if (!door_ki_info(dh, &di)) {
 515                         door_ki_rele(dh);
 516 
 517                         if (di.di_attributes & DOOR_REVOKED) {
 518                                 /*
 519                                  * The server barfed and revoked
 520                                  * the (existing) door on us; we
 521                                  * want to wait to give smf(5) a
 522                                  * chance to restart mountd(1m)
 523                                  * and establish a new door handle.
 524                                  */
 525                                 mutex_enter(&nag->mountd_lock);
 526                                 if (dh == nag->mountd_dh) {
 527                                         door_ki_rele(nag->mountd_dh);
 528                                         nag->mountd_dh = NULL;
 529                                 }
 530                                 mutex_exit(&nag->mountd_lock);
 531                                 delay(hz);
 532                                 goto retry;
 533                         }
 534                         /*
 535                          * If the door was _not_ revoked on us,
 536                          * then more than likely we took an INTR,
 537                          * so we need to fail the operation.
 538                          */
 539                         goto fail;
 540                 }
 541                 /*
 542                  * The only failure that can occur from getting
 543                  * the door info is EINVAL, so we let the code
 544                  * below handle it.
 545                  */
 546                 /* FALLTHROUGH */
 547 
 548         case EBADF:
 549         case EINVAL:
 550         default:
 551                 /*
 552                  * If we have a stale door handle, give smf a last
 553                  * chance to start it by sleeping for a little bit.
 554                  * If we're still hosed, we'll fail the call.
 555                  *
 556                  * Since we're going to reacquire the door handle
 557                  * upon the retry, we opt to sleep for a bit and
 558                  * _not_ to clear mountd_dh. If mountd restarted
 559                  * and was able to set mountd_dh, we should see
 560                  * the new instance; if not, we won't get caught
 561                  * up in the retry/DELAY loop.
 562                  */
 563                 door_ki_rele(dh);
 564                 if (!last) {
 565                         delay(hz);
 566                         last++;
 567                         goto retry;
 568                 }
 569                 sys_log("nfsauth: stale mountd door handle");
 570                 goto fail;
 571         }
 572 
 573         ASSERT(da.rbuf != NULL);
 574 
 575         /*
 576          * No door errors encountered; setup the XDR stream for decoding
 577          * the results. If we fail to decode the results, we've got no
 578          * other recourse than to fail the request.
 579          */
 580         xdrmem_create(&xdrs, da.rbuf, da.rsize, XDR_DECODE);
 581         if (!xdr_nfsauth_res(&xdrs, &res)) {
 582                 xdr_free(xdr_nfsauth_res, (char *)&res);
 583                 XDR_DESTROY(&xdrs);
 584                 kmem_free(da.rbuf, da.rsize);
 585                 goto fail;
 586         }
 587         XDR_DESTROY(&xdrs);
 588         kmem_free(da.rbuf, da.rsize);
 589 
 590         DTRACE_PROBE1(nfsserv__func__nfsauth__results, nfsauth_res_t *, &res);
 591         switch (res.stat) {
 592                 case NFSAUTH_DR_OKAY:
 593                         *access = res.ares.auth_perm;
 594                         *srv_uid = res.ares.auth_srv_uid;
 595                         *srv_gid = res.ares.auth_srv_gid;
 596                         *srv_gids_cnt = res.ares.auth_srv_gids.len;
 597                         *srv_gids = kmem_alloc(*srv_gids_cnt * sizeof (gid_t),
 598                             KM_SLEEP);
 599                         bcopy(res.ares.auth_srv_gids.val, *srv_gids,
 600                             *srv_gids_cnt * sizeof (gid_t));
 601                         break;
 602 
 603                 case NFSAUTH_DR_EFAIL:
 604                 case NFSAUTH_DR_DECERR:
 605                 case NFSAUTH_DR_BADCMD:
 606                 default:
 607                         xdr_free(xdr_nfsauth_res, (char *)&res);
 608 fail:
 609                         *access = NFSAUTH_DENIED;
 610                         kmem_free(abuf, absz);
 611                         return (FALSE);
 612                         /* NOTREACHED */
 613         }
 614 
 615         xdr_free(xdr_nfsauth_res, (char *)&res);
 616         kmem_free(abuf, absz);
 617 
 618         return (TRUE);
 619 }
 620 
 621 static void
 622 nfsauth_refresh_thread(nfsauth_globals_t *nag)
 623 {
 624         refreshq_exi_node_t     *ren;
 625         refreshq_auth_node_t    *ran;
 626 
 627         struct exportinfo       *exi;
 628 
 629         int                     access;
 630         bool_t                  retrieval;
 631 
 632         callb_cpr_t             cprinfo;
 633 
 634         CALLB_CPR_INIT(&cprinfo, &nag->refreshq_lock, callb_generic_cpr,
 635             "nfsauth_refresh");
 636 
 637         for (;;) {
 638                 mutex_enter(&nag->refreshq_lock);
 639                 if (nag->refreshq_thread_state != REFRESHQ_THREAD_RUNNING) {
 640                         /* Keep the hold on the lock! */
 641                         break;
 642                 }
 643 
 644                 ren = list_remove_head(&nag->refreshq_queue);
 645                 if (ren == NULL) {
 646                         CALLB_CPR_SAFE_BEGIN(&cprinfo);
 647                         cv_wait(&nag->refreshq_cv, &nag->refreshq_lock);
 648                         CALLB_CPR_SAFE_END(&cprinfo, &nag->refreshq_lock);
 649                         mutex_exit(&nag->refreshq_lock);
 650                         continue;
 651                 }
 652                 mutex_exit(&nag->refreshq_lock);
 653 
 654                 exi = ren->ren_exi;
 655                 ASSERT(exi != NULL);
 656 
 657                 /*
 658                  * Since the ren was removed from the refreshq_queue above,
 659                  * this is the only thread aware about the ren existence, so we
 660                  * have the exclusive ownership of it and we do not need to
 661                  * protect it by any lock.
 662                  */
 663                 while ((ran = list_remove_head(&ren->ren_authlist))) {
 664                         uid_t uid;
 665                         gid_t gid;
 666                         uint_t ngids;
 667                         gid_t *gids;
 668                         struct auth_cache *p = ran->ran_auth;
 669                         char *netid = ran->ran_netid;
 670 
 671                         ASSERT(p != NULL);
 672                         ASSERT(netid != NULL);
 673 
 674                         kmem_free(ran, sizeof (refreshq_auth_node_t));
 675 
 676                         mutex_enter(&p->auth_lock);
 677 
 678                         /*
 679                          * Once the entry goes INVALID, it can not change
 680                          * state.
 681                          *
 682                          * No need to refresh entries also in a case we are
 683                          * just shutting down.
 684                          *
 685                          * In general, there is no need to hold the
 686                          * refreshq_lock to test the refreshq_thread_state.  We
 687                          * do hold it at other places because there is some
 688                          * related thread synchronization (or some other tasks)
 689                          * close to the refreshq_thread_state check.
 690                          *
 691                          * The check for the refreshq_thread_state value here
 692                          * is purely advisory to allow the faster
 693                          * nfsauth_refresh_thread() shutdown.  In a case we
 694                          * will miss such advisory, nothing catastrophic
 695                          * happens: we will just spin longer here before the
 696                          * shutdown.
 697                          */
 698                         if (p->auth_state == NFS_AUTH_INVALID ||
 699                             nag->refreshq_thread_state !=
 700                             REFRESHQ_THREAD_RUNNING) {
 701                                 mutex_exit(&p->auth_lock);
 702 
 703                                 if (p->auth_state == NFS_AUTH_INVALID)
 704                                         nfsauth_free_node(p);
 705 
 706                                 strfree(netid);
 707 
 708                                 continue;
 709                         }
 710 
 711                         /*
 712                          * Make sure the state is valid.  Note that once we
 713                          * change the state to NFS_AUTH_REFRESHING, no other
 714                          * thread will be able to work on this entry.
 715                          */
 716                         ASSERT(p->auth_state == NFS_AUTH_STALE);
 717 
 718                         p->auth_state = NFS_AUTH_REFRESHING;
 719                         mutex_exit(&p->auth_lock);
 720 
 721                         DTRACE_PROBE2(nfsauth__debug__cache__refresh,
 722                             struct exportinfo *, exi,
 723                             struct auth_cache *, p);
 724 
 725                         /*
 726                          * The first caching of the access rights
 727                          * is done with the netid pulled out of the
 728                          * request from the client. All subsequent
 729                          * users of the cache may or may not have
 730                          * the same netid. It doesn't matter. So
 731                          * when we refresh, we simply use the netid
 732                          * of the request which triggered the
 733                          * refresh attempt.
 734                          */
 735                         retrieval = nfsauth_retrieve(nag, exi, netid,
 736                             p->auth_flavor, &p->auth_clnt->authc_addr, &access,
 737                             p->auth_clnt_cred, &uid, &gid, &ngids, &gids);
 738 
 739                         /*
 740                          * This can only be set in one other place
 741                          * and the state has to be NFS_AUTH_FRESH.
 742                          */
 743                         strfree(netid);
 744 
 745                         mutex_enter(&p->auth_lock);
 746                         if (p->auth_state == NFS_AUTH_INVALID) {
 747                                 mutex_exit(&p->auth_lock);
 748                                 nfsauth_free_node(p);
 749                                 if (retrieval == TRUE)
 750                                         kmem_free(gids, ngids * sizeof (gid_t));
 751                         } else {
 752                                 /*
 753                                  * If we got an error, do not reset the
 754                                  * time. This will cause the next access
 755                                  * check for the client to reschedule this
 756                                  * node.
 757                                  */
 758                                 if (retrieval == TRUE) {
 759                                         p->auth_access = access;
 760 
 761                                         p->auth_srv_uid = uid;
 762                                         p->auth_srv_gid = gid;
 763                                         kmem_free(p->auth_srv_gids,
 764                                             p->auth_srv_ngids * sizeof (gid_t));
 765                                         p->auth_srv_ngids = ngids;
 766                                         p->auth_srv_gids = gids;
 767 
 768                                         p->auth_freshness = gethrestime_sec();
 769                                 }
 770                                 p->auth_state = NFS_AUTH_FRESH;
 771 
 772                                 cv_broadcast(&p->auth_cv);
 773                                 mutex_exit(&p->auth_lock);
 774                         }
 775                 }
 776 
 777                 list_destroy(&ren->ren_authlist);
 778                 exi_rele(ren->ren_exi);
 779                 kmem_free(ren, sizeof (refreshq_exi_node_t));
 780         }
 781 
 782         nag->refreshq_thread_state = REFRESHQ_THREAD_HALTED;
 783         cv_broadcast(&nag->refreshq_cv);
 784         CALLB_CPR_EXIT(&cprinfo);
 785         DTRACE_PROBE(nfsauth__nfsauth__refresh__thread__exit);
 786         zthread_exit();
 787 }
 788 
 789 int
 790 nfsauth_cache_clnt_compar(const void *v1, const void *v2)
 791 {
 792         int c;
 793 
 794         const struct auth_cache_clnt *a1 = (const struct auth_cache_clnt *)v1;
 795         const struct auth_cache_clnt *a2 = (const struct auth_cache_clnt *)v2;
 796 
 797         if (a1->authc_addr.len < a2->authc_addr.len)
 798                 return (-1);
 799         if (a1->authc_addr.len > a2->authc_addr.len)
 800                 return (1);
 801 
 802         c = memcmp(a1->authc_addr.buf, a2->authc_addr.buf, a1->authc_addr.len);
 803         if (c < 0)
 804                 return (-1);
 805         if (c > 0)
 806                 return (1);
 807 
 808         return (0);
 809 }
 810 
 811 static int
 812 nfsauth_cache_compar(const void *v1, const void *v2)
 813 {
 814         int c;
 815 
 816         const struct auth_cache *a1 = (const struct auth_cache *)v1;
 817         const struct auth_cache *a2 = (const struct auth_cache *)v2;
 818 
 819         if (a1->auth_flavor < a2->auth_flavor)
 820                 return (-1);
 821         if (a1->auth_flavor > a2->auth_flavor)
 822                 return (1);
 823 
 824         if (crgetuid(a1->auth_clnt_cred) < crgetuid(a2->auth_clnt_cred))
 825                 return (-1);
 826         if (crgetuid(a1->auth_clnt_cred) > crgetuid(a2->auth_clnt_cred))
 827                 return (1);
 828 
 829         if (crgetgid(a1->auth_clnt_cred) < crgetgid(a2->auth_clnt_cred))
 830                 return (-1);
 831         if (crgetgid(a1->auth_clnt_cred) > crgetgid(a2->auth_clnt_cred))
 832                 return (1);
 833 
 834         if (crgetngroups(a1->auth_clnt_cred) < crgetngroups(a2->auth_clnt_cred))
 835                 return (-1);
 836         if (crgetngroups(a1->auth_clnt_cred) > crgetngroups(a2->auth_clnt_cred))
 837                 return (1);
 838 
 839         c = memcmp(crgetgroups(a1->auth_clnt_cred),
 840             crgetgroups(a2->auth_clnt_cred), crgetngroups(a1->auth_clnt_cred));
 841         if (c < 0)
 842                 return (-1);
 843         if (c > 0)
 844                 return (1);
 845 
 846         return (0);
 847 }
 848 
 849 /*
 850  * Get the access information from the cache or callup to the mountd
 851  * to get and cache the access information in the kernel.
 852  */
 853 static int
 854 nfsauth_cache_get(struct exportinfo *exi, struct svc_req *req, int flavor,
 855     cred_t *cr, uid_t *uid, gid_t *gid, uint_t *ngids, gid_t **gids)
 856 {
 857         nfsauth_globals_t       *nag;
 858         struct netbuf           *taddrmask;
 859         struct netbuf           addr;   /* temporary copy of client's address */
 860         const struct netbuf     *claddr;
 861         avl_tree_t              *tree;
 862         struct auth_cache       ac;     /* used as a template for avl_find() */
 863         struct auth_cache_clnt  *c;
 864         struct auth_cache_clnt  acc;    /* used as a template for avl_find() */
 865         struct auth_cache       *p = NULL;
 866         int                     access;
 867 
 868         uid_t                   tmpuid;
 869         gid_t                   tmpgid;
 870         uint_t                  tmpngids;
 871         gid_t                   *tmpgids;
 872 
 873         avl_index_t             where;  /* used for avl_find()/avl_insert() */
 874 
 875         ASSERT(cr != NULL);
 876 
 877         ASSERT3P(curzone, ==, exi->exi_zone);
 878         nag = zone_getspecific(nfsauth_zone_key, curzone);
 879 
 880         /*
 881          * Now check whether this client already
 882          * has an entry for this flavor in the cache
 883          * for this export.
 884          * Get the caller's address, mask off the
 885          * parts of the address that do not identify
 886          * the host (port number, etc), and then hash
 887          * it to find the chain of cache entries.
 888          */
 889 
 890         claddr = svc_getrpccaller(req->rq_xprt);
 891         addr = *claddr;
 892         addr.buf = kmem_alloc(addr.maxlen, KM_SLEEP);
 893         bcopy(claddr->buf, addr.buf, claddr->len);
 894 
 895         SVC_GETADDRMASK(req->rq_xprt, SVC_TATTR_ADDRMASK, (void **)&taddrmask);
 896         ASSERT(taddrmask != NULL);
 897         addrmask(&addr, taddrmask);
 898 
 899         ac.auth_flavor = flavor;
 900         ac.auth_clnt_cred = crdup(cr);
 901 
 902         acc.authc_addr = addr;
 903 
 904         tree = exi->exi_cache[hash(&addr)];
 905 
 906         rw_enter(&exi->exi_cache_lock, RW_READER);
 907         c = (struct auth_cache_clnt *)avl_find(tree, &acc, NULL);
 908 
 909         if (c == NULL) {
 910                 struct auth_cache_clnt *nc;
 911 
 912                 rw_exit(&exi->exi_cache_lock);
 913 
 914                 nc = kmem_alloc(sizeof (*nc), KM_NOSLEEP | KM_NORMALPRI);
 915                 if (nc == NULL)
 916                         goto retrieve;
 917 
 918                 /*
 919                  * Initialize the new auth_cache_clnt
 920                  */
 921                 nc->authc_addr = addr;
 922                 nc->authc_addr.buf = kmem_alloc(addr.maxlen,
 923                     KM_NOSLEEP | KM_NORMALPRI);
 924                 if (addr.maxlen != 0 && nc->authc_addr.buf == NULL) {
 925                         kmem_free(nc, sizeof (*nc));
 926                         goto retrieve;
 927                 }
 928                 bcopy(addr.buf, nc->authc_addr.buf, addr.len);
 929                 rw_init(&nc->authc_lock, NULL, RW_DEFAULT, NULL);
 930                 avl_create(&nc->authc_tree, nfsauth_cache_compar,
 931                     sizeof (struct auth_cache),
 932                     offsetof(struct auth_cache, auth_link));
 933 
 934                 rw_enter(&exi->exi_cache_lock, RW_WRITER);
 935                 c = (struct auth_cache_clnt *)avl_find(tree, &acc, &where);
 936                 if (c == NULL) {
 937                         avl_insert(tree, nc, where);
 938                         rw_downgrade(&exi->exi_cache_lock);
 939                         c = nc;
 940                 } else {
 941                         rw_downgrade(&exi->exi_cache_lock);
 942 
 943                         avl_destroy(&nc->authc_tree);
 944                         rw_destroy(&nc->authc_lock);
 945                         kmem_free(nc->authc_addr.buf, nc->authc_addr.maxlen);
 946                         kmem_free(nc, sizeof (*nc));
 947                 }
 948         }
 949 
 950         ASSERT(c != NULL);
 951 
 952         rw_enter(&c->authc_lock, RW_READER);
 953         p = (struct auth_cache *)avl_find(&c->authc_tree, &ac, NULL);
 954 
 955         if (p == NULL) {
 956                 struct auth_cache *np;
 957 
 958                 rw_exit(&c->authc_lock);
 959 
 960                 np = kmem_cache_alloc(exi_cache_handle,
 961                     KM_NOSLEEP | KM_NORMALPRI);
 962                 if (np == NULL) {
 963                         rw_exit(&exi->exi_cache_lock);
 964                         goto retrieve;
 965                 }
 966 
 967                 /*
 968                  * Initialize the new auth_cache
 969                  */
 970                 np->auth_clnt = c;
 971                 np->auth_flavor = flavor;
 972                 np->auth_clnt_cred = ac.auth_clnt_cred;
 973                 np->auth_srv_ngids = 0;
 974                 np->auth_srv_gids = NULL;
 975                 np->auth_time = np->auth_freshness = gethrestime_sec();
 976                 np->auth_state = NFS_AUTH_NEW;
 977                 mutex_init(&np->auth_lock, NULL, MUTEX_DEFAULT, NULL);
 978                 cv_init(&np->auth_cv, NULL, CV_DEFAULT, NULL);
 979 
 980                 rw_enter(&c->authc_lock, RW_WRITER);
 981                 rw_exit(&exi->exi_cache_lock);
 982 
 983                 p = (struct auth_cache *)avl_find(&c->authc_tree, &ac, &where);
 984                 if (p == NULL) {
 985                         avl_insert(&c->authc_tree, np, where);
 986                         rw_downgrade(&c->authc_lock);
 987                         p = np;
 988                 } else {
 989                         rw_downgrade(&c->authc_lock);
 990 
 991                         cv_destroy(&np->auth_cv);
 992                         mutex_destroy(&np->auth_lock);
 993                         crfree(ac.auth_clnt_cred);
 994                         kmem_cache_free(exi_cache_handle, np);
 995                 }
 996         } else {
 997                 rw_exit(&exi->exi_cache_lock);
 998                 crfree(ac.auth_clnt_cred);
 999         }
1000 
1001         mutex_enter(&p->auth_lock);
1002         rw_exit(&c->authc_lock);
1003 
1004         /*
1005          * If the entry is in the WAITING state then some other thread is just
1006          * retrieving the required info.  The entry was either NEW, or the list
1007          * of client's supplemental groups is going to be changed (either by
1008          * this thread, or by some other thread).  We need to wait until the
1009          * nfsauth_retrieve() is done.
1010          */
1011         while (p->auth_state == NFS_AUTH_WAITING)
1012                 cv_wait(&p->auth_cv, &p->auth_lock);
1013 
1014         /*
1015          * Here the entry cannot be in WAITING or INVALID state.
1016          */
1017         ASSERT(p->auth_state != NFS_AUTH_WAITING);
1018         ASSERT(p->auth_state != NFS_AUTH_INVALID);
1019 
1020         /*
1021          * If the cache entry is not valid yet, we need to retrieve the
1022          * info ourselves.
1023          */
1024         if (p->auth_state == NFS_AUTH_NEW) {
1025                 bool_t res;
1026                 /*
1027                  * NFS_AUTH_NEW is the default output auth_state value in a
1028                  * case we failed somewhere below.
1029                  */
1030                 auth_state_t state = NFS_AUTH_NEW;
1031 
1032                 p->auth_state = NFS_AUTH_WAITING;
1033                 mutex_exit(&p->auth_lock);
1034                 kmem_free(addr.buf, addr.maxlen);
1035                 addr = p->auth_clnt->authc_addr;
1036 
1037                 atomic_inc_uint(&nfsauth_cache_miss);
1038 
1039                 res = nfsauth_retrieve(nag, exi, svc_getnetid(req->rq_xprt),
1040                     flavor, &addr, &access, cr, &tmpuid, &tmpgid, &tmpngids,
1041                     &tmpgids);
1042 
1043                 p->auth_access = access;
1044                 p->auth_time = p->auth_freshness = gethrestime_sec();
1045 
1046                 if (res == TRUE) {
1047                         if (uid != NULL)
1048                                 *uid = tmpuid;
1049                         if (gid != NULL)
1050                                 *gid = tmpgid;
1051                         if (ngids != NULL && gids != NULL) {
1052                                 *ngids = tmpngids;
1053                                 *gids = tmpgids;
1054 
1055                                 /*
1056                                  * We need a copy of gids for the
1057                                  * auth_cache entry
1058                                  */
1059                                 tmpgids = kmem_alloc(tmpngids * sizeof (gid_t),
1060                                     KM_NOSLEEP | KM_NORMALPRI);
1061                                 if (tmpgids != NULL)
1062                                         bcopy(*gids, tmpgids,
1063                                             tmpngids * sizeof (gid_t));
1064                         }
1065 
1066                         if (tmpgids != NULL || tmpngids == 0) {
1067                                 p->auth_srv_uid = tmpuid;
1068                                 p->auth_srv_gid = tmpgid;
1069                                 p->auth_srv_ngids = tmpngids;
1070                                 p->auth_srv_gids = tmpgids;
1071 
1072                                 state = NFS_AUTH_FRESH;
1073                         }
1074                 }
1075 
1076                 /*
1077                  * Set the auth_state and notify waiters.
1078                  */
1079                 mutex_enter(&p->auth_lock);
1080                 p->auth_state = state;
1081                 cv_broadcast(&p->auth_cv);
1082                 mutex_exit(&p->auth_lock);
1083         } else {
1084                 uint_t nach;
1085                 time_t refresh;
1086 
1087                 refresh = gethrestime_sec() - p->auth_freshness;
1088 
1089                 p->auth_time = gethrestime_sec();
1090 
1091                 if (uid != NULL)
1092                         *uid = p->auth_srv_uid;
1093                 if (gid != NULL)
1094                         *gid = p->auth_srv_gid;
1095                 if (ngids != NULL && gids != NULL) {
1096                         *ngids = p->auth_srv_ngids;
1097                         *gids = kmem_alloc(*ngids * sizeof (gid_t), KM_SLEEP);
1098                         bcopy(p->auth_srv_gids, *gids, *ngids * sizeof (gid_t));
1099                 }
1100 
1101                 access = p->auth_access;
1102 
1103                 if ((refresh > NFSAUTH_CACHE_REFRESH) &&
1104                     p->auth_state == NFS_AUTH_FRESH) {
1105                         refreshq_auth_node_t *ran;
1106                         uint_t nacr;
1107 
1108                         p->auth_state = NFS_AUTH_STALE;
1109                         mutex_exit(&p->auth_lock);
1110 
1111                         nacr = atomic_inc_uint_nv(&nfsauth_cache_refresh);
1112                         DTRACE_PROBE3(nfsauth__debug__cache__stale,
1113                             struct exportinfo *, exi,
1114                             struct auth_cache *, p,
1115                             uint_t, nacr);
1116 
1117                         ran = kmem_alloc(sizeof (refreshq_auth_node_t),
1118                             KM_SLEEP);
1119                         ran->ran_auth = p;
1120                         ran->ran_netid = strdup(svc_getnetid(req->rq_xprt));
1121 
1122                         mutex_enter(&nag->refreshq_lock);
1123 
1124                         if (nag->refreshq_thread_state ==
1125                             REFRESHQ_THREAD_NEED_CREATE) {
1126                                 /* Launch nfsauth refresh thread */
1127                                 nag->refreshq_thread_state =
1128                                     REFRESHQ_THREAD_RUNNING;
1129                                 (void) zthread_create(NULL, 0,
1130                                     nfsauth_refresh_thread, nag, 0,
1131                                     minclsyspri);
1132                         }
1133 
1134                         /*
1135                          * We should not add a work queue item if the thread
1136                          * is not accepting them.
1137                          */
1138                         if (nag->refreshq_thread_state ==
1139                             REFRESHQ_THREAD_RUNNING) {
1140                                 refreshq_exi_node_t *ren;
1141 
1142                                 /*
1143                                  * Is there an existing exi_list?
1144                                  */
1145                                 for (ren = list_head(&nag->refreshq_queue);
1146                                     ren != NULL;
1147                                     ren = list_next(&nag->refreshq_queue,
1148                                     ren)) {
1149                                         if (ren->ren_exi == exi) {
1150                                                 list_insert_tail(
1151                                                     &ren->ren_authlist, ran);
1152                                                 break;
1153                                         }
1154                                 }
1155 
1156                                 if (ren == NULL) {
1157                                         ren = kmem_alloc(
1158                                             sizeof (refreshq_exi_node_t),
1159                                             KM_SLEEP);
1160 
1161                                         exi_hold(exi);
1162                                         ren->ren_exi = exi;
1163 
1164                                         list_create(&ren->ren_authlist,
1165                                             sizeof (refreshq_auth_node_t),
1166                                             offsetof(refreshq_auth_node_t,
1167                                             ran_node));
1168 
1169                                         list_insert_tail(&ren->ren_authlist,
1170                                             ran);
1171                                         list_insert_tail(&nag->refreshq_queue,
1172                                             ren);
1173                                 }
1174 
1175                                 cv_broadcast(&nag->refreshq_cv);
1176                         } else {
1177                                 strfree(ran->ran_netid);
1178                                 kmem_free(ran, sizeof (refreshq_auth_node_t));
1179                         }
1180 
1181                         mutex_exit(&nag->refreshq_lock);
1182                 } else {
1183                         mutex_exit(&p->auth_lock);
1184                 }
1185 
1186                 nach = atomic_inc_uint_nv(&nfsauth_cache_hit);
1187                 DTRACE_PROBE2(nfsauth__debug__cache__hit,
1188                     uint_t, nach,
1189                     time_t, refresh);
1190 
1191                 kmem_free(addr.buf, addr.maxlen);
1192         }
1193 
1194         return (access);
1195 
1196 retrieve:
1197         crfree(ac.auth_clnt_cred);
1198 
1199         /*
1200          * Retrieve the required data without caching.
1201          */
1202 
1203         ASSERT(p == NULL);
1204 
1205         atomic_inc_uint(&nfsauth_cache_miss);
1206 
1207         if (nfsauth_retrieve(nag, exi, svc_getnetid(req->rq_xprt), flavor,
1208             &addr, &access, cr, &tmpuid, &tmpgid, &tmpngids, &tmpgids)) {
1209                 if (uid != NULL)
1210                         *uid = tmpuid;
1211                 if (gid != NULL)
1212                         *gid = tmpgid;
1213                 if (ngids != NULL && gids != NULL) {
1214                         *ngids = tmpngids;
1215                         *gids = tmpgids;
1216                 } else {
1217                         kmem_free(tmpgids, tmpngids * sizeof (gid_t));
1218                 }
1219         }
1220 
1221         kmem_free(addr.buf, addr.maxlen);
1222 
1223         return (access);
1224 }
1225 
1226 /*
1227  * Check if the requesting client has access to the filesystem with
1228  * a given nfs flavor number which is an explicitly shared flavor.
1229  */
1230 int
1231 nfsauth4_secinfo_access(struct exportinfo *exi, struct svc_req *req,
1232     int flavor, int perm, cred_t *cr)
1233 {
1234         int access;
1235 
1236         if (! (perm & M_4SEC_EXPORTED)) {
1237                 return (NFSAUTH_DENIED);
1238         }
1239 
1240         /*
1241          * Optimize if there are no lists
1242          */
1243         if ((perm & (M_ROOT | M_NONE | M_MAP)) == 0) {
1244                 perm &= ~M_4SEC_EXPORTED;
1245                 if (perm == M_RO)
1246                         return (NFSAUTH_RO);
1247                 if (perm == M_RW)
1248                         return (NFSAUTH_RW);
1249         }
1250 
1251         access = nfsauth_cache_get(exi, req, flavor, cr, NULL, NULL, NULL,
1252             NULL);
1253 
1254         return (access);
1255 }
1256 
1257 int
1258 nfsauth_access(struct exportinfo *exi, struct svc_req *req, cred_t *cr,
1259     uid_t *uid, gid_t *gid, uint_t *ngids, gid_t **gids)
1260 {
1261         int access, mapaccess;
1262         struct secinfo *sp;
1263         int i, flavor, perm;
1264         int authnone_entry = -1;
1265 
1266         /*
1267          * By default root is mapped to anonymous user.
1268          * This might get overriden later in nfsauth_cache_get().
1269          */
1270         if (crgetuid(cr) == 0) {
1271                 if (uid != NULL)
1272                         *uid = exi->exi_export.ex_anon;
1273                 if (gid != NULL)
1274                         *gid = exi->exi_export.ex_anon;
1275         } else {
1276                 if (uid != NULL)
1277                         *uid = crgetuid(cr);
1278                 if (gid != NULL)
1279                         *gid = crgetgid(cr);
1280         }
1281 
1282         if (ngids != NULL)
1283                 *ngids = 0;
1284         if (gids != NULL)
1285                 *gids = NULL;
1286 
1287         /*
1288          *  Get the nfs flavor number from xprt.
1289          */
1290         flavor = (int)(uintptr_t)req->rq_xprt->xp_cookie;
1291 
1292         /*
1293          * First check the access restrictions on the filesystem.  If
1294          * there are no lists associated with this flavor then there's no
1295          * need to make an expensive call to the nfsauth service or to
1296          * cache anything.
1297          */
1298 
1299         sp = exi->exi_export.ex_secinfo;
1300         for (i = 0; i < exi->exi_export.ex_seccnt; i++) {
1301                 if (flavor != sp[i].s_secinfo.sc_nfsnum) {
1302                         if (sp[i].s_secinfo.sc_nfsnum == AUTH_NONE)
1303                                 authnone_entry = i;
1304                         continue;
1305                 }
1306                 break;
1307         }
1308 
1309         mapaccess = 0;
1310 
1311         if (i >= exi->exi_export.ex_seccnt) {
1312                 /*
1313                  * Flavor not found, but use AUTH_NONE if it exists
1314                  */
1315                 if (authnone_entry == -1)
1316                         return (NFSAUTH_DENIED);
1317                 flavor = AUTH_NONE;
1318                 mapaccess = NFSAUTH_MAPNONE;
1319                 i = authnone_entry;
1320         }
1321 
1322         /*
1323          * If the flavor is in the ex_secinfo list, but not an explicitly
1324          * shared flavor by the user, it is a result of the nfsv4 server
1325          * namespace setup. We will grant an RO permission similar for
1326          * a pseudo node except that this node is a shared one.
1327          *
1328          * e.g. flavor in (flavor) indicates that it is not explictly
1329          *      shared by the user:
1330          *
1331          *              /       (sys, krb5)
1332          *              |
1333          *              export  #share -o sec=sys (krb5)
1334          *              |
1335          *              secure  #share -o sec=krb5
1336          *
1337          *      In this case, when a krb5 request coming in to access
1338          *      /export, RO permission is granted.
1339          */
1340         if (!(sp[i].s_flags & M_4SEC_EXPORTED))
1341                 return (mapaccess | NFSAUTH_RO);
1342 
1343         /*
1344          * Optimize if there are no lists.
1345          * We cannot optimize for AUTH_SYS with NGRPS (16) supplemental groups.
1346          */
1347         perm = sp[i].s_flags;
1348         if ((perm & (M_ROOT | M_NONE | M_MAP)) == 0 && (ngroups_max <= NGRPS ||
1349             flavor != AUTH_SYS || crgetngroups(cr) < NGRPS)) {
1350                 perm &= ~M_4SEC_EXPORTED;
1351                 if (perm == M_RO)
1352                         return (mapaccess | NFSAUTH_RO);
1353                 if (perm == M_RW)
1354                         return (mapaccess | NFSAUTH_RW);
1355         }
1356 
1357         access = nfsauth_cache_get(exi, req, flavor, cr, uid, gid, ngids, gids);
1358 
1359         /*
1360          * For both NFSAUTH_DENIED and NFSAUTH_WRONGSEC we do not care about
1361          * the supplemental groups.
1362          */
1363         if (access & NFSAUTH_DENIED || access & NFSAUTH_WRONGSEC) {
1364                 if (ngids != NULL && gids != NULL) {
1365                         kmem_free(*gids, *ngids * sizeof (gid_t));
1366                         *ngids = 0;
1367                         *gids = NULL;
1368                 }
1369         }
1370 
1371         /*
1372          * Client's security flavor doesn't match with "ro" or
1373          * "rw" list. Try again using AUTH_NONE if present.
1374          */
1375         if ((access & NFSAUTH_WRONGSEC) && (flavor != AUTH_NONE)) {
1376                 /*
1377                  * Have we already encountered AUTH_NONE ?
1378                  */
1379                 if (authnone_entry != -1) {
1380                         mapaccess = NFSAUTH_MAPNONE;
1381                         access = nfsauth_cache_get(exi, req, AUTH_NONE, cr,
1382                             NULL, NULL, NULL, NULL);
1383                 } else {
1384                         /*
1385                          * Check for AUTH_NONE presence.
1386                          */
1387                         for (; i < exi->exi_export.ex_seccnt; i++) {
1388                                 if (sp[i].s_secinfo.sc_nfsnum == AUTH_NONE) {
1389                                         mapaccess = NFSAUTH_MAPNONE;
1390                                         access = nfsauth_cache_get(exi, req,
1391                                             AUTH_NONE, cr, NULL, NULL, NULL,
1392                                             NULL);
1393                                         break;
1394                                 }
1395                         }
1396                 }
1397         }
1398 
1399         if (access & NFSAUTH_DENIED)
1400                 access = NFSAUTH_DENIED;
1401 
1402         return (access | mapaccess);
1403 }
1404 
1405 static void
1406 nfsauth_free_clnt_node(struct auth_cache_clnt *p)
1407 {
1408         void *cookie = NULL;
1409         struct auth_cache *node;
1410 
1411         while ((node = avl_destroy_nodes(&p->authc_tree, &cookie)) != NULL)
1412                 nfsauth_free_node(node);
1413         avl_destroy(&p->authc_tree);
1414 
1415         kmem_free(p->authc_addr.buf, p->authc_addr.maxlen);
1416         rw_destroy(&p->authc_lock);
1417 
1418         kmem_free(p, sizeof (*p));
1419 }
1420 
1421 static void
1422 nfsauth_free_node(struct auth_cache *p)
1423 {
1424         crfree(p->auth_clnt_cred);
1425         kmem_free(p->auth_srv_gids, p->auth_srv_ngids * sizeof (gid_t));
1426         mutex_destroy(&p->auth_lock);
1427         cv_destroy(&p->auth_cv);
1428         kmem_cache_free(exi_cache_handle, p);
1429 }
1430 
1431 /*
1432  * Free the nfsauth cache for a given export
1433  */
1434 void
1435 nfsauth_cache_free(struct exportinfo *exi)
1436 {
1437         int i;
1438 
1439         /*
1440          * The only way we got here was with an exi_rele, which means that no
1441          * auth cache entry is being refreshed.
1442          */
1443 
1444         for (i = 0; i < AUTH_TABLESIZE; i++) {
1445                 avl_tree_t *tree = exi->exi_cache[i];
1446                 void *cookie = NULL;
1447                 struct auth_cache_clnt *node;
1448 
1449                 while ((node = avl_destroy_nodes(tree, &cookie)) != NULL)
1450                         nfsauth_free_clnt_node(node);
1451         }
1452 }
1453 
1454 /*
1455  * Called by the kernel memory allocator when
1456  * memory is low. Free unused cache entries.
1457  * If that's not enough, the VM system will
1458  * call again for some more.
1459  */
1460 /*ARGSUSED*/
1461 void
1462 exi_cache_reclaim(void *cdrarg)
1463 {
1464         int i;
1465         struct exportinfo *exi;
1466         nfs_export_t *ne = nfs_get_export();
1467 
1468         rw_enter(&ne->exported_lock, RW_READER);
1469 
1470         for (i = 0; i < EXPTABLESIZE; i++) {
1471                 for (exi = ne->exptable[i]; exi; exi = exi->fid_hash.next)
1472                         exi_cache_trim(exi);
1473         }
1474 
1475         rw_exit(&ne->exported_lock);
1476 
1477         atomic_inc_uint(&nfsauth_cache_reclaim);
1478 }
1479 
1480 void
1481 exi_cache_trim(struct exportinfo *exi)
1482 {
1483         struct auth_cache_clnt *c;
1484         struct auth_cache_clnt *nextc;
1485         struct auth_cache *p;
1486         struct auth_cache *next;
1487         int i;
1488         time_t stale_time;
1489         avl_tree_t *tree;
1490 
1491         for (i = 0; i < AUTH_TABLESIZE; i++) {
1492                 tree = exi->exi_cache[i];
1493                 stale_time = gethrestime_sec() - NFSAUTH_CACHE_TRIM;
1494                 rw_enter(&exi->exi_cache_lock, RW_READER);
1495 
1496                 /*
1497                  * Free entries that have not been
1498                  * used for NFSAUTH_CACHE_TRIM seconds.
1499                  */
1500                 for (c = avl_first(tree); c != NULL; c = AVL_NEXT(tree, c)) {
1501                         /*
1502                          * We are being called by the kmem subsystem to reclaim
1503                          * memory so don't block if we can't get the lock.
1504                          */
1505                         if (rw_tryenter(&c->authc_lock, RW_WRITER) == 0) {
1506                                 exi_cache_auth_reclaim_failed++;
1507                                 rw_exit(&exi->exi_cache_lock);
1508                                 return;
1509                         }
1510 
1511                         for (p = avl_first(&c->authc_tree); p != NULL;
1512                             p = next) {
1513                                 next = AVL_NEXT(&c->authc_tree, p);
1514 
1515                                 ASSERT(p->auth_state != NFS_AUTH_INVALID);
1516 
1517                                 mutex_enter(&p->auth_lock);
1518 
1519                                 /*
1520                                  * We won't trim recently used and/or WAITING
1521                                  * entries.
1522                                  */
1523                                 if (p->auth_time > stale_time ||
1524                                     p->auth_state == NFS_AUTH_WAITING) {
1525                                         mutex_exit(&p->auth_lock);
1526                                         continue;
1527                                 }
1528 
1529                                 DTRACE_PROBE1(nfsauth__debug__trim__state,
1530                                     auth_state_t, p->auth_state);
1531 
1532                                 /*
1533                                  * STALE and REFRESHING entries needs to be
1534                                  * marked INVALID only because they are
1535                                  * referenced by some other structures or
1536                                  * threads.  They will be freed later.
1537                                  */
1538                                 if (p->auth_state == NFS_AUTH_STALE ||
1539                                     p->auth_state == NFS_AUTH_REFRESHING) {
1540                                         p->auth_state = NFS_AUTH_INVALID;
1541                                         mutex_exit(&p->auth_lock);
1542 
1543                                         avl_remove(&c->authc_tree, p);
1544                                 } else {
1545                                         mutex_exit(&p->auth_lock);
1546 
1547                                         avl_remove(&c->authc_tree, p);
1548                                         nfsauth_free_node(p);
1549                                 }
1550                         }
1551                         rw_exit(&c->authc_lock);
1552                 }
1553 
1554                 if (rw_tryupgrade(&exi->exi_cache_lock) == 0) {
1555                         rw_exit(&exi->exi_cache_lock);
1556                         exi_cache_clnt_reclaim_failed++;
1557                         continue;
1558                 }
1559 
1560                 for (c = avl_first(tree); c != NULL; c = nextc) {
1561                         nextc = AVL_NEXT(tree, c);
1562 
1563                         if (avl_is_empty(&c->authc_tree) == B_FALSE)
1564                                 continue;
1565 
1566                         avl_remove(tree, c);
1567 
1568                         nfsauth_free_clnt_node(c);
1569                 }
1570 
1571                 rw_exit(&exi->exi_cache_lock);
1572         }
1573 }