|
root / base / usr / src / uts / common / fs / nfs / nfs4_idmap.c
nfs4_idmap.c C 1703 lines 44.2 KB
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
 */


/*
 * There are well defined policies for mapping uid and gid values to and
 * from utf8 strings, as specified in RFC 7530. The protocol ops that are
 * most significantly affected by any changes in policy are GETATTR and
 * SETATTR, as these have different behavior depending on whether the id
 * mapping code is executing on the client or server. Thus, the following
 * rules represents the latest incantation of the id mapping policies.
 *
 * 1) For the case in which the nfsmapid(8) daemon has _never_ been
 *    started, the policy is to _always_ work with stringified uid's
 *    and gid's
 *
 * 2) For the case in which the nfsmapid(8) daemon _was_ started but
 *    has either died or become unresponsive, the mapping policies are
 *    as follows:
 *
 *                      Server                             Client
 *         .-------------------------------.---------------------------------.
 *         |                               |                                 |
 *         | . Respond to req by replying  | . If attr string does not have  |
 *         |   success and map the [u/g]id |   '@' sign, attempt to decode   |
 *         |   into its literal id string  |   a stringified id; map to      |
 *         |                               |   *ID_NOBODY if not an encoded  |
 *         |                               |   id.                           |
 *         |                               |                                 |
 * GETATTR |                               | . If attr string _does_ have    |
 *         |                               |   '@' sign			     |
 *         |                               |   Map to *ID_NOBODY on failure. |
 *         |                               |                                 |
 *         | nfs_idmap_*id_str             | nfs_idmap_str_*id               |
 *         +-------------------------------+---------------------------------+
 *         |                               |                                 |
 *         | . Respond to req by returning | . _Must_ map the user's passed  |
 *         |  ECOMM, which will be mapped  |  in [u/g]id into it's network   |
 *         |  to NFS4ERR_DELAY to clnt     |  attr string, so contact the    |
 *         |                               |  daemon, retrying forever if    |
 *         |   Server must not allow the   |  necessary, unless interrupted  |
 * SETATTR |   mapping to *ID_NOBODY upon  |                                 |
 *         |   lack of communication with  |   Client _should_ specify the   |
 *         |   the daemon, which could     |   correct attr string for a     |
 *         |   result in the file being    |   SETATTR operation, otherwise  |
 *         |   inadvertently given away !  |   it can also result in the     |
 *         |                               |   file being inadvertently      |
 *         |                               |   given away !                  |
 *         |                               |                                 |
 *         | nfs_idmap_str_*id             |   nfs_idmap_*id_str             |
 *         `-------------------------------'---------------------------------'
 *
 * 3) Lastly, in order to leverage better cache utilization whenever
 *    communication with nfsmapid(8) is currently hindered, cache
 *    entry eviction is throttled whenever nfsidmap_daemon_dh == NULL.
 *
 *
 *  Server-side behavior for upcall communication errors
 *  ====================================================
 *
 *   GETATTR - Server-side GETATTR *id to attr string conversion policies
 *             for unresponsive/dead nfsmapid(8) daemon
 *
 *	a) If the *id is *ID_NOBODY, the string "nobody" is returned
 *
 *	b) If the *id is not *ID_NOBODY _and_ the nfsmapid(8) daemon
 *	   _is_ operational, the daemon is contacted to convert the
 *	   [u/g]id into a string of type "[user/group]@domain"
 *
 *	c) If the nfsmapid(8) daemon has died or has become unresponsive,
 *	   the server returns status == NFS4_OK for the GETATTR operation,
 *	   and returns a strigified [u/g]id to let the client map it into
 *	   the appropriate value.
 *
 *   SETATTR - Server-side SETATTR attr string to *id conversion policies
 *             for unresponsive/dead nfsmapid(8) daemon
 *
 *	a) If the otw string is a stringified uid (ie. does _not_ contain
 *	   an '@' sign and is of the form "12345") then the literal uid is
 *	   decoded and it is used to perform the mapping.
 *
 *	b) If, on the other hand, the otw string _is_ of the form
 *	   "[user/group]@domain" and problems arise contacting nfsmapid(8),
 *	   the SETATTR operation _must_ fail w/NFS4ERR_DELAY, as the server
 *	   cannot default to *ID_NOBODY, which would allow a file to be
 *	   given away by setting it's owner or owner_group to "nobody".
 */
#include <sys/param.h>
#include <sys/errno.h>
#include <sys/disp.h>
#include <sys/vfs.h>
#include <sys/vnode.h>
#include <sys/cred.h>
#include <sys/cmn_err.h>
#include <sys/systm.h>
#include <sys/kmem.h>
#include <sys/pathname.h>
#include <sys/utsname.h>
#include <sys/debug.h>
#include <sys/sysmacros.h>
#include <sys/list.h>
#include <sys/sunddi.h>
#include <sys/dnlc.h>
#include <sys/sdt.h>
#include <sys/pkp_hash.h>
#include <nfs/nfs4.h>
#include <nfs/rnode4.h>
#include <nfs/nfsid_map.h>
#include <nfs/nfs4_idmap_impl.h>
#include <nfs/nfssys.h>

/*
 * Truly global modular globals
 */
zone_key_t			nfsidmap_zone_key;
static list_t			nfsidmap_globals_list;
static kmutex_t			nfsidmap_globals_lock;
static kmem_cache_t		*nfsidmap_cache;
static int			nfs4_idcache_tout;

/*
 * Some useful macros
 */
#define		MOD2(a, pow_of_2)	((a) & ((pow_of_2) - 1))
#define		_CACHE_TOUT		(60*60)		/* secs in 1 hour */
#define		TIMEOUT(x)		(gethrestime_sec() > \
					((x) + nfs4_idcache_tout))
/*
 * Max length of valid id string including the trailing null
 */
#define		_MAXIDSTRLEN		11

#define		ID_HASH(id, hash)					\
{									\
	(hash) = MOD2(((id) ^ NFSID_CACHE_ANCHORS), NFSID_CACHE_ANCHORS); \
}

/*
 * Prototypes
 */

static void	*nfs_idmap_init_zone(zoneid_t);
static void	 nfs_idmap_fini_zone(zoneid_t, void *);

static int	 is_stringified_id(utf8string *);
static void	 nfs_idmap_i2s_literal(uid_t, utf8string *);
static int	 nfs_idmap_s2i_literal(utf8string *, uid_t *, int);
static void	 nfs_idmap_reclaim(void *);
static void	 nfs_idmap_cache_reclaim(idmap_cache_info_t *);
static void	 nfs_idmap_cache_create(idmap_cache_info_t *, const char *);
static void	 nfs_idmap_cache_destroy(idmap_cache_info_t *);
static void	 nfs_idmap_cache_flush(idmap_cache_info_t *);

static uint_t	 nfs_idmap_cache_s2i_lkup(idmap_cache_info_t *, utf8string *,
			uint_t *, uid_t *);

static uint_t	 nfs_idmap_cache_i2s_lkup(idmap_cache_info_t *, uid_t,
			uint_t *, utf8string *);

static void	 nfs_idmap_cache_s2i_insert(idmap_cache_info_t *, uid_t,
			utf8string *, hash_stat, uint_t);

static void	 nfs_idmap_cache_i2s_insert(idmap_cache_info_t *, uid_t,
			utf8string *, hash_stat, uint_t);

static void	 nfs_idmap_cache_rment(nfsidmap_t *);

/*
 * Initialization routine for NFSv4 id mapping
 */
void
nfs_idmap_init(void)
{
	/*
	 * Initialize the kmem cache
	 */
	nfsidmap_cache = kmem_cache_create("NFS_idmap_cache",
	    sizeof (nfsidmap_t), 0, NULL, NULL, nfs_idmap_reclaim, NULL,
	    NULL, 0);
	/*
	 * If not set in "/etc/system", set to default value
	 */
	if (!nfs4_idcache_tout)
		nfs4_idcache_tout = _CACHE_TOUT;
	/*
	 * Initialize the list of nfsidmap_globals
	 */
	mutex_init(&nfsidmap_globals_lock, NULL, MUTEX_DEFAULT, NULL);
	list_create(&nfsidmap_globals_list, sizeof (struct nfsidmap_globals),
	    offsetof(struct nfsidmap_globals, nig_link));
	/*
	 * Initialize the zone_key_t for per-zone idmaps
	 */
	zone_key_create(&nfsidmap_zone_key, nfs_idmap_init_zone, NULL,
	    nfs_idmap_fini_zone);
}

/*
 * Called only when module was not loaded properly
 */
void
nfs_idmap_fini(void)
{
	(void) zone_key_delete(nfsidmap_zone_key);
	list_destroy(&nfsidmap_globals_list);
	mutex_destroy(&nfsidmap_globals_lock);
	kmem_cache_destroy(nfsidmap_cache);
}

/*ARGSUSED*/
static void *
nfs_idmap_init_zone(zoneid_t zoneid)
{
	struct nfsidmap_globals *nig;

	nig = kmem_alloc(sizeof (*nig), KM_SLEEP);
	nig->nig_msg_done = 0;
	mutex_init(&nig->nfsidmap_daemon_lock, NULL, MUTEX_DEFAULT, NULL);

	/*
	 * nfsidmap certainly isn't running.
	 */
	nig->nfsidmap_pid = NOPID;
	nig->nfsidmap_daemon_dh = NULL;

	/*
	 * Create the idmap caches
	 */
	nfs_idmap_cache_create(&nig->u2s_ci, "u2s_cache");
	nig->u2s_ci.nfsidmap_daemon_dh = &nig->nfsidmap_daemon_dh;
	nfs_idmap_cache_create(&nig->s2u_ci, "s2u_cache");
	nig->s2u_ci.nfsidmap_daemon_dh = &nig->nfsidmap_daemon_dh;
	nfs_idmap_cache_create(&nig->g2s_ci, "g2s_cache");
	nig->g2s_ci.nfsidmap_daemon_dh = &nig->nfsidmap_daemon_dh;
	nfs_idmap_cache_create(&nig->s2g_ci, "s2g_cache");
	nig->s2g_ci.nfsidmap_daemon_dh = &nig->nfsidmap_daemon_dh;

	/*
	 * Add to global list.
	 */
	mutex_enter(&nfsidmap_globals_lock);
	list_insert_head(&nfsidmap_globals_list, nig);
	mutex_exit(&nfsidmap_globals_lock);

	return (nig);
}

/*ARGSUSED*/
static void
nfs_idmap_fini_zone(zoneid_t zoneid, void *arg)
{
	struct nfsidmap_globals *nig = arg;

	/*
	 * Remove from list.
	 */
	mutex_enter(&nfsidmap_globals_lock);
	list_remove(&nfsidmap_globals_list, nig);
	/*
	 * Destroy the idmap caches
	 */
	nfs_idmap_cache_destroy(&nig->u2s_ci);
	nfs_idmap_cache_destroy(&nig->s2u_ci);
	nfs_idmap_cache_destroy(&nig->g2s_ci);
	nfs_idmap_cache_destroy(&nig->s2g_ci);
	mutex_exit(&nfsidmap_globals_lock);
	/*
	 * Cleanup
	 */
	if (nig->nfsidmap_daemon_dh)
		door_ki_rele(nig->nfsidmap_daemon_dh);
	mutex_destroy(&nig->nfsidmap_daemon_lock);
	kmem_free(nig, sizeof (*nig));
}

/*
 * Convert a user utf-8 string identifier into its local uid.
 */
int
nfs_idmap_str_uid(utf8string *u8s, uid_t *uid, bool_t isserver)
{
	int			error;
	uint_t			hashno = 0;
	const char		*whoami = "nfs_idmap_str_uid";
	struct nfsidmap_globals *nig;
	struct mapid_arg	*mapargp;
	struct mapid_res	mapres;
	struct mapid_res	*mapresp = &mapres;
	struct mapid_res	*resp = mapresp;
	door_arg_t		door_args;
	door_handle_t		dh;

	nig = zone_getspecific(nfsidmap_zone_key, nfs_zone());
	ASSERT(nig != NULL);

	if (!u8s || !u8s->utf8string_val || u8s->utf8string_len == 0 ||
	    (u8s->utf8string_val[0] == '\0')) {
		*uid = UID_NOBODY;
		return (isserver ? EINVAL : 0);
	}

	/*
	 * If "nobody", just short circuit and bail
	 */
	if (bcmp(u8s->utf8string_val, "nobody", 6) == 0) {
		*uid = UID_NOBODY;
		return (0);
	}

	/*
	 * Start-off with upcalls disabled, and once nfsmapid(8) is up and
	 * running, we'll leverage it's first flush to let the kernel know
	 * when it's up and available to perform mappings. Also, on client
	 * only, be smarter about when to issue upcalls by checking the
	 * string for existence of an '@' sign. If no '@' sign, then we just
	 * make our best effort to decode the string ourselves.
	 */
retry:
	mutex_enter(&nig->nfsidmap_daemon_lock);
	dh = nig->nfsidmap_daemon_dh;
	if (dh)
		door_ki_hold(dh);
	mutex_exit(&nig->nfsidmap_daemon_lock);

	if (dh == NULL || nig->nfsidmap_pid == curproc->p_pid ||
	    (!utf8_strchr(u8s, '@') && !isserver)) {
		if (dh)
			door_ki_rele(dh);
		error = nfs_idmap_s2i_literal(u8s, uid, isserver);
		/*
		 * If we get a numeric value, but we only do so because
		 * we are nfsmapid, return ENOTSUP to indicate a valid
		 * response, but not to cache it.
		 */
		if (!error && nig->nfsidmap_pid == curproc->p_pid)
			return (ENOTSUP);
		return (error);
	}

	/* cache hit */
	if (nfs_idmap_cache_s2i_lkup(&nig->s2u_ci, u8s, &hashno, uid)) {
		door_ki_rele(dh);
		return (0);
	}

	/* cache miss */
	mapargp = kmem_alloc(MAPID_ARG_LEN(u8s->utf8string_len), KM_SLEEP);
	mapargp->cmd = NFSMAPID_STR_UID;
	mapargp->u_arg.len = u8s->utf8string_len;
	(void) bcopy(u8s->utf8string_val, mapargp->str, mapargp->u_arg.len);
	mapargp->str[mapargp->u_arg.len] = '\0';

	door_args.data_ptr = (char *)mapargp;
	door_args.data_size = MAPID_ARG_LEN(mapargp->u_arg.len);
	door_args.desc_ptr = NULL;
	door_args.desc_num = 0;
	door_args.rbuf = (char *)mapresp;
	door_args.rsize = sizeof (struct mapid_res);

	error = door_ki_upcall_limited(dh, &door_args, NULL, SIZE_MAX, 0);
	if (!error) {
		resp = (struct mapid_res *)door_args.rbuf;

		/* Should never provide daemon with bad args */
		ASSERT(resp->status != NFSMAPID_INVALID);

		switch (resp->status) {
		case NFSMAPID_OK:
			/*
			 * Valid mapping. Cache it.
			 */
			*uid = resp->u_res.uid;
			nfs_idmap_cache_s2i_insert(&nig->s2u_ci, *uid,
			    u8s, HQ_HASH_HINT, hashno);
			break;

		case NFSMAPID_NUMSTR:
			/*
			 * string came in as stringified id. Don't cache !
			 *
			 * nfsmapid(8) semantics have changed in order to
			 * support diskless clients. Thus, for stringified
			 * id's that have passwd/group entries, we'll go
			 * ahead and map them, returning no error.
			 */
			*uid = resp->u_res.uid;
			break;

		case NFSMAPID_BADDOMAIN:
			/*
			 * Make the offending "user@domain" string readily
			 * available to D scripts that enable the probe.
			 */
			DTRACE_PROBE1(nfs4__str__uid, char *, mapargp->str);
			/* FALLTHROUGH */

		case NFSMAPID_INVALID:
		case NFSMAPID_UNMAPPABLE:
		case NFSMAPID_INTERNAL:
		case NFSMAPID_BADID:
		case NFSMAPID_NOTFOUND:
		default:
			/*
			 * For now, treat all of these errors as equal.
			 *
			 * Return error on the server side, then the
			 * server returns NFS4_BADOWNER to the client.
			 * On client side, just map to UID_NOBODY.
			 */
			if (isserver)
				error = EPERM;
			else
				*uid = UID_NOBODY;
			break;
		}
		kmem_free(mapargp, MAPID_ARG_LEN(u8s->utf8string_len));
		if (resp != mapresp)
			kmem_free(door_args.rbuf, door_args.rsize);
		door_ki_rele(dh);
		return (error);
	}

	kmem_free(mapargp, MAPID_ARG_LEN(u8s->utf8string_len));
	/*
	 * We got some door error
	 */
	switch (error) {
	case EINTR:
		/*
		 * If we took an interrupt we have to bail out.
		 */
		if (ttolwp(curthread) && ISSIG(curthread, JUSTLOOKING)) {
			door_ki_rele(dh);
			return (EINTR);
		}

		/*
		 * We may have gotten EINTR for other reasons like the
		 * door being revoked on us, instead of trying to
		 * extract this out of the door handle, sleep
		 * and try again, if still revoked we will get EBADF
		 * next time through.
		 */
		/* FALLTHROUGH */
	case EAGAIN:    /* process may be forking */
		door_ki_rele(dh);
		/*
		 * Back off for a bit
		 */
		delay(hz);
		goto retry;
	default:	/* Unknown must be fatal */
	case EBADF:	/* Invalid door */
	case EINVAL:	/* Not a door, wrong target */
		/*
		 * A fatal door error, if our failing door handle is the
		 * current door handle, clean up our state and
		 * mark the server dead.
		 */
		mutex_enter(&nig->nfsidmap_daemon_lock);
		if (dh == nig->nfsidmap_daemon_dh) {
			door_ki_rele(nig->nfsidmap_daemon_dh);
			nig->nfsidmap_daemon_dh = NULL;
		}
		mutex_exit(&nig->nfsidmap_daemon_lock);
		door_ki_rele(dh);

		if (isserver)
			return (ECOMM);

		/*
		 * Note: We've already done optimizations above to check
		 *	 for '@' sign, so if we can't comm w/nfsmapid, we
		 *	 _know_ this _can't_ be a stringified uid.
		 */
		if (!nig->nig_msg_done) {
			zcmn_err(getzoneid(), CE_WARN,
			    "!%s: Can't communicate with mapping daemon "
			    "nfsmapid", whoami);

			nig->nig_msg_done = 1;
		}
		*uid = UID_NOBODY;
		return (0);
	}
	/* NOTREACHED */
}

/*
 * Convert a uid into its utf-8 string representation.
 */
int
nfs_idmap_uid_str(uid_t uid, utf8string *u8s, bool_t isserver)
{
	int			error;
	uint_t			hashno = 0;
	const char		*whoami = "nfs_idmap_uid_str";
	struct nfsidmap_globals	*nig;
	struct mapid_arg	maparg;
	struct mapid_res	mapres;
	struct mapid_res	*mapresp = &mapres;
	struct mapid_res	*resp = mapresp;
	door_arg_t		door_args;
	door_handle_t		dh;

	nig = zone_getspecific(nfsidmap_zone_key, nfs_zone());
	ASSERT(nig != NULL);

	/*
	 * If the supplied uid is "nobody", then we don't look at the
	 * cache, since we DON'T cache it in the u2s_cache. We cannot
	 * tell two strings apart from caching the same uid.
	 */
	if (uid == UID_NOBODY) {
		(void) str_to_utf8("nobody", u8s);
		return (0);
	}

	/*
	 * Start-off with upcalls disabled, and once nfsmapid(8) is
	 * up and running, we'll leverage it's first flush to let the
	 * kernel know when it's up and available to perform mappings.
	 * We fall back to answering with stringified uid's.
	 */
retry:
	mutex_enter(&nig->nfsidmap_daemon_lock);
	dh = nig->nfsidmap_daemon_dh;
	if (dh)
		door_ki_hold(dh);
	mutex_exit(&nig->nfsidmap_daemon_lock);

	if (dh == NULL || nig->nfsidmap_pid == curproc->p_pid) {
		if (dh)
			door_ki_rele(dh);
		nfs_idmap_i2s_literal(uid, u8s);
		return (0);
	}

	/* cache hit */
	if (nfs_idmap_cache_i2s_lkup(&nig->u2s_ci, uid, &hashno, u8s)) {
		door_ki_rele(dh);
		return (0);
	}

	/* cache miss */
	maparg.cmd = NFSMAPID_UID_STR;
	maparg.u_arg.uid = uid;

	door_args.data_ptr = (char *)&maparg;
	door_args.data_size = sizeof (struct mapid_arg);
	door_args.desc_ptr = NULL;
	door_args.desc_num = 0;
	door_args.rbuf = (char *)mapresp;
	door_args.rsize = sizeof (struct mapid_res);

	error = door_ki_upcall_limited(dh, &door_args, NULL, SIZE_MAX, 0);
	if (!error) {
		resp = (struct mapid_res *)door_args.rbuf;

		/* Should never provide daemon with bad args */
		ASSERT(resp->status != NFSMAPID_INVALID);

		switch (resp->status) {
		case NFSMAPID_OK:
			/*
			 * We now have a valid result from the
			 * user-land daemon, so cache the result (if need be).
			 * Load return value first then do the caches.
			 */
			(void) str_to_utf8(resp->str, u8s);
			nfs_idmap_cache_i2s_insert(&nig->u2s_ci, uid,
			    u8s, HQ_HASH_HINT, hashno);
			break;

		case NFSMAPID_INVALID:
		case NFSMAPID_UNMAPPABLE:
		case NFSMAPID_INTERNAL:
		case NFSMAPID_BADDOMAIN:
		case NFSMAPID_BADID:
		case NFSMAPID_NOTFOUND:
		default:
			/*
			 * For now, treat all of these errors as equal.
			 */
			error = EPERM;
			break;
		}

		if (resp != mapresp)
			kmem_free(door_args.rbuf, door_args.rsize);
		door_ki_rele(dh);
		return (error);
	}

	/*
	 * We got some door error
	 */
	switch (error) {
	case EINTR:
		/*
		 * If we took an interrupt we have to bail out.
		 */
		if (ttolwp(curthread) && ISSIG(curthread, JUSTLOOKING)) {
			door_ki_rele(dh);
			return (EINTR);
		}

		/*
		 * We may have gotten EINTR for other reasons like the
		 * door being revoked on us, instead of trying to
		 * extract this out of the door handle, sleep
		 * and try again, if still revoked we will get EBADF
		 * next time through.
		 */
		/* FALLTHROUGH */
	case EAGAIN:    /* process may be forking */
		door_ki_rele(dh);
		/*
		 * Back off for a bit
		 */
		delay(hz);
		goto retry;
	default:	/* Unknown must be fatal */
	case EBADF:	/* Invalid door */
	case EINVAL:	/* Not a door, wrong target */
		/*
		 * A fatal door error, if our failing door handle is the
		 * current door handle, clean up our state and
		 * mark the server dead.
		 */
		mutex_enter(&nig->nfsidmap_daemon_lock);
		if (dh == nig->nfsidmap_daemon_dh) {
			door_ki_rele(nig->nfsidmap_daemon_dh);
			nig->nfsidmap_daemon_dh = NULL;
		}
		mutex_exit(&nig->nfsidmap_daemon_lock);
		door_ki_rele(dh);

		/*
		 * Log error on client-side only
		 */
		if (!nig->nig_msg_done && !isserver) {
			zcmn_err(getzoneid(), CE_WARN,
			    "!%s: Can't communicate with mapping daemon "
			    "nfsmapid", whoami);

			nig->nig_msg_done = 1;
		}
		nfs_idmap_i2s_literal(uid, u8s);
		return (0);
	}
	/* NOTREACHED */
}

/*
 * Convert a group utf-8 string identifier into its local gid.
 */
int
nfs_idmap_str_gid(utf8string *u8s, gid_t *gid, bool_t isserver)
{
	int			error;
	uint_t			hashno = 0;
	const char		*whoami = "nfs_idmap_str_gid";
	struct nfsidmap_globals *nig;
	struct mapid_arg	*mapargp;
	struct mapid_res	mapres;
	struct mapid_res	*mapresp = &mapres;
	struct mapid_res	*resp = mapresp;
	door_arg_t		door_args;
	door_handle_t		dh;

	nig = zone_getspecific(nfsidmap_zone_key, nfs_zone());
	ASSERT(nig != NULL);

	if (!u8s || !u8s->utf8string_val || u8s->utf8string_len == 0 ||
	    (u8s->utf8string_val[0] == '\0')) {
		*gid = GID_NOBODY;
		return (isserver ? EINVAL : 0);
	}

	/*
	 * If "nobody", just short circuit and bail
	 */
	if (bcmp(u8s->utf8string_val, "nobody", 6) == 0) {
		*gid = GID_NOBODY;
		return (0);
	}

	/*
	 * Start-off with upcalls disabled, and once nfsmapid(8) is up and
	 * running, we'll leverage it's first flush to let the kernel know
	 * when it's up and available to perform mappings. Also, on client
	 * only, be smarter about when to issue upcalls by checking the
	 * string for existence of an '@' sign. If no '@' sign, then we just
	 * make our best effort to decode the string ourselves.
	 */
retry:
	mutex_enter(&nig->nfsidmap_daemon_lock);
	dh = nig->nfsidmap_daemon_dh;
	if (dh)
		door_ki_hold(dh);
	mutex_exit(&nig->nfsidmap_daemon_lock);

	if (dh == NULL || nig->nfsidmap_pid == curproc->p_pid ||
	    (!utf8_strchr(u8s, '@') && !isserver)) {
		if (dh)
			door_ki_rele(dh);
		error = nfs_idmap_s2i_literal(u8s, gid, isserver);
		/*
		 * If we get a numeric value, but we only do so because
		 * we are nfsmapid, return ENOTSUP to indicate a valid
		 * response, but not to cache it.
		 */
		if (!error && nig->nfsidmap_pid == curproc->p_pid)
			return (ENOTSUP);
		return (error);
	}

	/* cache hit */
	if (nfs_idmap_cache_s2i_lkup(&nig->s2g_ci, u8s, &hashno, gid)) {
		door_ki_rele(dh);
		return (0);
	}

	/* cache miss */
	mapargp = kmem_alloc(MAPID_ARG_LEN(u8s->utf8string_len), KM_SLEEP);
	mapargp->cmd = NFSMAPID_STR_GID;
	mapargp->u_arg.len = u8s->utf8string_len;
	(void) bcopy(u8s->utf8string_val, mapargp->str, mapargp->u_arg.len);
	mapargp->str[mapargp->u_arg.len] = '\0';

	door_args.data_ptr = (char *)mapargp;
	door_args.data_size = MAPID_ARG_LEN(mapargp->u_arg.len);
	door_args.desc_ptr = NULL;
	door_args.desc_num = 0;
	door_args.rbuf = (char *)mapresp;
	door_args.rsize = sizeof (struct mapid_res);

	error = door_ki_upcall_limited(dh, &door_args, NULL, SIZE_MAX, 0);
	if (!error) {
		resp = (struct mapid_res *)door_args.rbuf;

		/* Should never provide daemon with bad args */
		ASSERT(resp->status != NFSMAPID_INVALID);

		switch (resp->status) {
		case NFSMAPID_OK:
			/*
			 * Valid mapping. Cache it.
			 */
			*gid = resp->u_res.gid;
			error = 0;
			nfs_idmap_cache_s2i_insert(&nig->s2g_ci, *gid,
			    u8s, HQ_HASH_HINT, hashno);
			break;

		case NFSMAPID_NUMSTR:
			/*
			 * string came in as stringified id. Don't cache !
			 *
			 * nfsmapid(8) semantics have changed in order to
			 * support diskless clients. Thus, for stringified
			 * id's that have passwd/group entries, we'll go
			 * ahead and map them, returning no error.
			 */
			*gid = resp->u_res.gid;
			break;

		case NFSMAPID_BADDOMAIN:
			/*
			 * Make the offending "group@domain" string readily
			 * available to D scripts that enable the probe.
			 */
			DTRACE_PROBE1(nfs4__str__gid, char *, mapargp->str);
			/* FALLTHROUGH */

		case NFSMAPID_INVALID:
		case NFSMAPID_UNMAPPABLE:
		case NFSMAPID_INTERNAL:
		case NFSMAPID_BADID:
		case NFSMAPID_NOTFOUND:
		default:
			/*
			 * For now, treat all of these errors as equal.
			 *
			 * Return error on the server side, then the
			 * server returns NFS4_BADOWNER to the client.
			 * On client side, just map to GID_NOBODY.
			 */
			if (isserver)
				error = EPERM;
			else
				*gid = GID_NOBODY;
			break;
		}
		kmem_free(mapargp, MAPID_ARG_LEN(u8s->utf8string_len));
		if (resp != mapresp)
			kmem_free(door_args.rbuf, door_args.rsize);
		door_ki_rele(dh);
		return (error);
	}

	kmem_free(mapargp, MAPID_ARG_LEN(u8s->utf8string_len));
	/*
	 * We got some door error
	 */
	switch (error) {
	case EINTR:
		/*
		 * If we took an interrupt we have to bail out.
		 */
		if (ttolwp(curthread) && ISSIG(curthread, JUSTLOOKING)) {
			door_ki_rele(dh);
			return (EINTR);
		}

		/*
		 * We may have gotten EINTR for other reasons like the
		 * door being revoked on us, instead of trying to
		 * extract this out of the door handle, sleep
		 * and try again, if still revoked we will get EBADF
		 * next time through.
		 */
		/* FALLTHROUGH */
	case EAGAIN:    /* process may be forking */
		door_ki_rele(dh);
		/*
		 * Back off for a bit
		 */
		delay(hz);
		goto retry;
	default:	/* Unknown must be fatal */
	case EBADF:	/* Invalid door */
	case EINVAL:	/* Not a door, wrong target */
		/*
		 * A fatal door error, clean up our state and
		 * mark the server dead.
		 */

		mutex_enter(&nig->nfsidmap_daemon_lock);
		if (dh == nig->nfsidmap_daemon_dh) {
			door_ki_rele(nig->nfsidmap_daemon_dh);
			nig->nfsidmap_daemon_dh = NULL;
		}
		mutex_exit(&nig->nfsidmap_daemon_lock);
		door_ki_rele(dh);

		if (isserver)
			return (ECOMM);

		/*
		 * Note: We've already done optimizations above to check
		 *	 for '@' sign, so if we can't comm w/nfsmapid, we
		 *	 _know_ this _can't_ be a stringified gid.
		 */
		if (!nig->nig_msg_done) {
			zcmn_err(getzoneid(), CE_WARN,
			    "!%s: Can't communicate with mapping daemon "
			    "nfsmapid", whoami);

			nig->nig_msg_done = 1;
		}
		*gid = GID_NOBODY;
		return (0);
	}
	/* NOTREACHED */
}

/*
 * Convert a gid into its utf-8 string representation.
 */
int
nfs_idmap_gid_str(gid_t gid, utf8string *u8s, bool_t isserver)
{
	int			error;
	uint_t			hashno = 0;
	const char		*whoami = "nfs_idmap_gid_str";
	struct nfsidmap_globals	*nig;
	struct mapid_arg	maparg;
	struct mapid_res	mapres;
	struct mapid_res	*mapresp = &mapres;
	struct mapid_res	*resp = mapresp;
	door_arg_t		door_args;
	door_handle_t		dh;

	nig = zone_getspecific(nfsidmap_zone_key, nfs_zone());
	ASSERT(nig != NULL);

	/*
	 * If the supplied gid is "nobody", then we don't look at the
	 * cache, since we DON'T cache it in the u2s_cache. We cannot
	 * tell two strings apart from caching the same gid.
	 */
	if (gid == GID_NOBODY) {
		(void) str_to_utf8("nobody", u8s);
		return (0);
	}

	/*
	 * Start-off with upcalls disabled, and once nfsmapid(8) is
	 * up and running, we'll leverage it's first flush to let the
	 * kernel know when it's up and available to perform mappings.
	 * We fall back to answering with stringified gid's.
	 */
retry:
	mutex_enter(&nig->nfsidmap_daemon_lock);
	dh = nig->nfsidmap_daemon_dh;
	if (dh)
		door_ki_hold(dh);
	mutex_exit(&nig->nfsidmap_daemon_lock);

	if (dh == NULL || nig->nfsidmap_pid == curproc->p_pid) {
		if (dh)
			door_ki_rele(dh);
		nfs_idmap_i2s_literal(gid, u8s);
		return (0);
	}

	/* cache hit */
	if (nfs_idmap_cache_i2s_lkup(&nig->g2s_ci, gid, &hashno, u8s)) {
		door_ki_rele(dh);
		return (0);
	}

	/* cache miss */
	maparg.cmd = NFSMAPID_GID_STR;
	maparg.u_arg.gid = gid;

	door_args.data_ptr = (char *)&maparg;
	door_args.data_size = sizeof (struct mapid_arg);
	door_args.desc_ptr = NULL;
	door_args.desc_num = 0;
	door_args.rbuf = (char *)mapresp;
	door_args.rsize = sizeof (struct mapid_res);

	error = door_ki_upcall_limited(dh, &door_args, NULL, SIZE_MAX, 0);
	if (!error) {
		resp = (struct mapid_res *)door_args.rbuf;

		/* Should never provide daemon with bad args */
		ASSERT(resp->status != NFSMAPID_INVALID);

		switch (resp->status) {
		case NFSMAPID_OK:
			/*
			 * We now have a valid result from the
			 * user-land daemon, so cache the result (if need be).
			 * Load return value first then do the caches.
			 */
			(void) str_to_utf8(resp->str, u8s);
			nfs_idmap_cache_i2s_insert(&nig->g2s_ci, gid,
			    u8s, HQ_HASH_HINT, hashno);
			break;

		case NFSMAPID_INVALID:
		case NFSMAPID_UNMAPPABLE:
		case NFSMAPID_INTERNAL:
		case NFSMAPID_BADDOMAIN:
		case NFSMAPID_BADID:
		case NFSMAPID_NOTFOUND:
		default:
			/*
			 * For now, treat all of these errors as equal.
			 */
			error = EPERM;
			break;
		}

		if (resp != mapresp)
			kmem_free(door_args.rbuf, door_args.rsize);
		door_ki_rele(dh);
		return (error);
	}

	/*
	 * We got some door error
	 */
	switch (error) {
	case EINTR:
		/*
		 * If we took an interrupt we have to bail out.
		 */
		if (ttolwp(curthread) && ISSIG(curthread, JUSTLOOKING)) {
			door_ki_rele(dh);
			return (EINTR);
		}

		/*
		 * We may have gotten EINTR for other reasons like the
		 * door being revoked on us, instead of trying to
		 * extract this out of the door handle, sleep
		 * and try again, if still revoked we will get EBADF
		 * next time through.
		 */
		/* FALLTHROUGH */
	case EAGAIN:    /* process may be forking */
		door_ki_rele(dh);
		/*
		 * Back off for a bit
		 */
		delay(hz);
		goto retry;
	default:	/* Unknown must be fatal */
	case EBADF:	/* Invalid door */
	case EINVAL:	/* Not a door, wrong target */
		/*
		 * A fatal door error, if our failing door handle is the
		 * current door handle, clean up our state and
		 * mark the server dead.
		 */
		mutex_enter(&nig->nfsidmap_daemon_lock);
		if (dh == nig->nfsidmap_daemon_dh) {
			door_ki_rele(nig->nfsidmap_daemon_dh);
			nig->nfsidmap_daemon_dh = NULL;
		}
		door_ki_rele(dh);
		mutex_exit(&nig->nfsidmap_daemon_lock);

		/*
		 * Log error on client-side only
		 */
		if (!nig->nig_msg_done && !isserver) {
			zcmn_err(getzoneid(), CE_WARN,
			    "!%s: Can't communicate with mapping daemon "
			    "nfsmapid", whoami);

			nig->nig_msg_done = 1;
		}
		nfs_idmap_i2s_literal(gid, u8s);
		return (0);
	}
	/* NOTREACHED */
}

/* -- idmap cache management -- */

/*
 * Cache creation and initialization routine
 */
static void
nfs_idmap_cache_create(idmap_cache_info_t *cip, const char *name)
{
	int		 i;
	nfsidhq_t	*hq = NULL;

	cip->table = kmem_alloc((NFSID_CACHE_ANCHORS * sizeof (nfsidhq_t)),
	    KM_SLEEP);

	for (i = 0, hq = cip->table; i < NFSID_CACHE_ANCHORS; i++, hq++) {
		hq->hq_que_forw = hq;
		hq->hq_que_back = hq;
		mutex_init(&(hq->hq_lock), NULL, MUTEX_DEFAULT, NULL);
	}
	cip->name = name;
}

/*
 * Cache destruction routine
 *
 * Ops per hash queue
 *
 * - dequeue cache entries
 * - release string storage per entry
 * - release cache entry storage
 * - destroy HQ lock when HQ is empty
 * - once all HQ's empty, release HQ storage
 */
static void
nfs_idmap_cache_destroy(idmap_cache_info_t *cip)
{
	int		 i;
	nfsidhq_t	*hq;

	ASSERT(MUTEX_HELD(&nfsidmap_globals_lock));
	nfs_idmap_cache_flush(cip);
	/*
	 * We can safely destroy per-queue locks since the only
	 * other entity that could be mucking with this table is the
	 * kmem reaper thread which does everything under
	 * nfsidmap_globals_lock (which we're holding).
	 */
	for (i = 0, hq = cip->table; i < NFSID_CACHE_ANCHORS; i++, hq++)
		mutex_destroy(&(hq->hq_lock));
	kmem_free(cip->table, NFSID_CACHE_ANCHORS * sizeof (nfsidhq_t));
}

void
nfs_idmap_args(struct nfsidmap_args *idmp)
{
	struct nfsidmap_globals *nig;

	nig = zone_getspecific(nfsidmap_zone_key, nfs_zone());
	ASSERT(nig != NULL);

	nfs_idmap_cache_flush(&nig->u2s_ci);
	nfs_idmap_cache_flush(&nig->s2u_ci);
	nfs_idmap_cache_flush(&nig->g2s_ci);
	nfs_idmap_cache_flush(&nig->s2g_ci);

	/*
	 * nfsmapid(8) up and running; enable upcalls
	 * State:
	 *	0	Just flush caches
	 *	1	Re-establish door knob
	 */
	if (idmp->state) {
		/*
		 * When reestablishing the nfsmapid we need to
		 * not only purge the idmap cache but also
		 * the dnlc as it will have cached uid/gid's.
		 * While heavyweight, this should almost never happen
		 */
		dnlc_purge();

		/*
		 * Invalidate the attrs of all rnodes to force new uid and gids
		 */
		nfs4_rnode_invalidate(NULL);

		mutex_enter(&nig->nfsidmap_daemon_lock);
		if (nig->nfsidmap_daemon_dh)
			door_ki_rele(nig->nfsidmap_daemon_dh);
		nig->nfsidmap_daemon_dh = door_ki_lookup(idmp->did);
		nig->nfsidmap_pid = curproc->p_pid;
		nig->nig_msg_done = 0;
		mutex_exit(&nig->nfsidmap_daemon_lock);
	}
}

/*
 * Cache flush routine
 *
 *	The only serialization required it to hold the hash chain lock
 *	when destroying cache entries.  There is no need to prevent access
 *	to all hash chains while flushing.  It is possible that (valid)
 *	entries could be cached in later hash chains after we start flushing.
 *	It is unfortunate that the entry will be instantly destroyed, but
 *	it isn't a major concern.  This is only a cache.  It'll be repopulated.
 *
 * Ops per hash queue
 *
 * - dequeue cache entries
 * - release string storage per entry
 * - release cache entry storage
 */
static void
nfs_idmap_cache_flush(idmap_cache_info_t *cip)
{
	int		 i;
	nfsidmap_t	*p, *next;
	nfsidhq_t	*hq;

	for (i = 0, hq = cip->table; i < NFSID_CACHE_ANCHORS; i++, hq++) {

		mutex_enter(&(hq->hq_lock));

		/*
		 * remove list from hash header so we can release
		 * the lock early.
		 */
		p = hq->hq_lru_forw;
		hq->hq_que_forw = hq;
		hq->hq_que_back = hq;

		mutex_exit(&(hq->hq_lock));

		/*
		 * Iterate over the orphan'd list and free all elements.
		 * There's no need to bother with remque since we're
		 * freeing the entire list.
		 */
		while (p != (nfsidmap_t *)hq) {
			next = p->id_forw;
			if (p->id_val != 0)
				kmem_free(p->id_val, p->id_len);
			kmem_cache_free(nfsidmap_cache, p);
			p = next;
		}

	}
}

static void
nfs_idmap_cache_reclaim(idmap_cache_info_t *cip)
{
	nfsidhq_t		*hq;
	nfsidmap_t		*pprev = NULL;
	int			 i;
	nfsidmap_t		*p;

	ASSERT(cip != NULL && cip->table != NULL);

	/*
	 * If the daemon is down, do not flush anything
	 */
	if ((*cip->nfsidmap_daemon_dh) == NULL)
		return;

	for (i = 0, hq = cip->table; i < NFSID_CACHE_ANCHORS; i++, hq++) {
		if (!mutex_tryenter(&(hq->hq_lock)))
			continue;

		/*
		 * Start at end of list and work backwards since LRU
		 */
		for (p = hq->hq_lru_back; p != (nfsidmap_t *)hq; p = pprev) {
			pprev = p->id_back;

			/*
			 * List is LRU. If trailing end does not
			 * contain stale entries, then no need to
			 * continue.
			 */
			if (!TIMEOUT(p->id_time))
				break;

			nfs_idmap_cache_rment(p);
		}
		mutex_exit(&(hq->hq_lock));
	}
}

/*
 * Callback reclaim function for VM.  We reap timed-out entries from all hash
 * tables in all zones.
 */
/* ARGSUSED */
void
nfs_idmap_reclaim(void *arg)
{
	struct nfsidmap_globals *nig;

	mutex_enter(&nfsidmap_globals_lock);
	for (nig = list_head(&nfsidmap_globals_list); nig != NULL;
	    nig = list_next(&nfsidmap_globals_list, nig)) {
		nfs_idmap_cache_reclaim(&nig->u2s_ci);
		nfs_idmap_cache_reclaim(&nig->s2u_ci);
		nfs_idmap_cache_reclaim(&nig->g2s_ci);
		nfs_idmap_cache_reclaim(&nig->s2g_ci);
	}
	mutex_exit(&nfsidmap_globals_lock);
}

/*
 * Search the specified cache for the existence of the specified utf-8
 * string. If found, the corresponding mapping is returned in id_buf and
 * the cache entry is updated to the head of the LRU list. The computed
 * hash queue number, is returned in hashno.
 *
 * cip    - cache info ptr
 * u8s    - utf8 string to resolve
 * hashno - hash number, retval
 * id_buf - if found, id for u8s
 */
static uint_t
nfs_idmap_cache_s2i_lkup(idmap_cache_info_t *cip, utf8string *u8s,
    uint_t *hashno, uid_t *id_buf)
{
	nfsidmap_t	*p;
	nfsidmap_t	*pnext;
	nfsidhq_t	*hq;
	char		*rqst_c_str;
	uint_t		 rqst_len;
	uint_t		 found_stat = 0;

	if ((rqst_c_str = utf8_to_str(u8s, &rqst_len, NULL)) == NULL) {
		/*
		 * Illegal string, return not found.
		 */
		return (0);
	}

	/*
	 * Compute hash queue
	 */
	*hashno = pkp_tab_hash(rqst_c_str, rqst_len - 1);
	hq = &cip->table[*hashno];

	/*
	 * Look for the entry in the HQ
	 */
	mutex_enter(&(hq->hq_lock));
	for (p = hq->hq_lru_forw; p != (nfsidmap_t *)hq; p = pnext) {

		pnext = p->id_forw;

		/*
		 * Check entry for staleness first, as user's id
		 * may have changed and may need to be remapped.
		 * Note that we don't evict entries from the cache
		 * if we're having trouble contacting nfsmapid(8)
		 */
		if (TIMEOUT(p->id_time) && (*cip->nfsidmap_daemon_dh) != NULL) {
			nfs_idmap_cache_rment(p);
			continue;
		}

		/*
		 * Compare equal length strings
		 */
		if (p->id_len == (rqst_len - 1)) {
			if (bcmp(p->id_val, rqst_c_str, (rqst_len - 1)) == 0) {
				/*
				 * Found it. Update it and load return value.
				 */
				*id_buf = p->id_no;
				remque(p);
				insque(p, hq);
				p->id_time = gethrestime_sec();

				found_stat = 1;
				break;
			}
		}
	}
	mutex_exit(&(hq->hq_lock));

	if (rqst_c_str != NULL)
		kmem_free(rqst_c_str, rqst_len);

	return (found_stat);
}

/*
 * Search the specified cache for the existence of the specified utf8
 * string, as it may have been inserted before this instance got a chance
 * to do it. If NOT found, then a new entry is allocated for the specified
 * cache, and inserted. The hash queue number is obtained from hash_number
 * if the behavior is HQ_HASH_HINT, or computed otherwise.
 *
 * cip         - cache info ptr
 * id          - id result from upcall
 * u8s         - utf8 string to resolve
 * behavior    - hash algorithm behavior
 * hash_number - hash number iff hint
 */
static void
nfs_idmap_cache_s2i_insert(idmap_cache_info_t *cip, uid_t id, utf8string *u8s,
    hash_stat behavior, uint_t hash_number)
{
	uint_t			 hashno;
	char			*c_str;
	nfsidhq_t		*hq;
	nfsidmap_t		*newp;
	nfsidmap_t		*p;
	nfsidmap_t		*pnext;
	uint_t			 c_len;

	/*
	 * This shouldn't fail, since already successful at lkup.
	 * So, if it does happen, just drop the request-to-insert
	 * on the floor.
	 */
	if ((c_str = utf8_to_str(u8s, &c_len, NULL)) == NULL)
		return;

	/*
	 * Obtain correct hash queue to insert new entry in
	 */
	switch (behavior) {
		case HQ_HASH_HINT:
			hashno = hash_number;
			break;

		case HQ_HASH_FIND:
		default:
			hashno = pkp_tab_hash(c_str, c_len - 1);
			break;
	}
	hq = &cip->table[hashno];


	/*
	 * Look for an existing entry in the cache. If one exists
	 * update it, and return. Otherwise, allocate a new cache
	 * entry, initialize it and insert it.
	 */
	mutex_enter(&(hq->hq_lock));
	for (p = hq->hq_lru_forw; p != (nfsidmap_t *)hq; p = pnext) {

		pnext = p->id_forw;

		/*
		 * Check entry for staleness first, as user's id
		 * may have changed and may need to be remapped.
		 * Note that we don't evict entries from the cache
		 * if we're having trouble contacting nfsmapid(8)
		 */
		if (TIMEOUT(p->id_time) && (*cip->nfsidmap_daemon_dh) != NULL) {
			nfs_idmap_cache_rment(p);
			continue;
		}

		/*
		 * Compare equal length strings
		 */
		if (p->id_len == (c_len - 1)) {
			if (bcmp(p->id_val, c_str, (c_len - 1)) == 0) {
				/*
				 * Move to front, and update time.
				 */
				remque(p);
				insque(p, hq);
				p->id_time = gethrestime_sec();

				mutex_exit(&(hq->hq_lock));
				kmem_free(c_str, c_len);
				return;
			}
		}
	}

	/*
	 * Not found ! Alloc, init and insert new entry
	 */
	newp = kmem_cache_alloc(nfsidmap_cache, KM_SLEEP);
	newp->id_len = u8s->utf8string_len;
	newp->id_val = kmem_alloc(u8s->utf8string_len, KM_SLEEP);
	bcopy(u8s->utf8string_val, newp->id_val, u8s->utf8string_len);
	newp->id_no = id;
	newp->id_time = gethrestime_sec();
	insque(newp, hq);

	mutex_exit(&(hq->hq_lock));
	kmem_free(c_str, c_len);
}

/*
 * Search the specified cache for the existence of the specified id.
 * If found, the corresponding mapping is returned in u8s and the
 * cache entry is updated to the head of the LRU list. The computed
 * hash queue number, is returned in hashno.
 *
 * cip    - cache info ptr
 * id     - id to resolve
 * hashno - hash number, retval
 * u8s    - if found, utf8 str for id
 */
static uint_t
nfs_idmap_cache_i2s_lkup(idmap_cache_info_t *cip, uid_t id, uint_t *hashno,
    utf8string *u8s)
{
	uint_t			 found_stat = 0;
	nfsidmap_t		*p;
	nfsidmap_t		*pnext;
	nfsidhq_t		*hq;
	uint_t			 hash;

	/*
	 * Compute hash queue
	 */
	ID_HASH(id, hash);
	*hashno = hash;
	hq = &cip->table[hash];

	/*
	 * Look for the entry in the HQ
	 */
	mutex_enter(&(hq->hq_lock));
	for (p = hq->hq_lru_forw; p != (nfsidmap_t *)hq; p = pnext) {

		pnext = p->id_forw;

		/*
		 * Check entry for staleness first, as user's id
		 * may have changed and may need to be remapped.
		 * Note that we don't evict entries from the cache
		 * if we're having trouble contacting nfsmapid(8)
		 */
		if (TIMEOUT(p->id_time) && (*cip->nfsidmap_daemon_dh) != NULL) {
			nfs_idmap_cache_rment(p);
			continue;
		}

		if (p->id_no == id) {

			/*
			 * Found it. Load return value and move to head
			 */
			ASSERT(u8s->utf8string_val == NULL);
			u8s->utf8string_len = p->id_len;
			u8s->utf8string_val = kmem_alloc(p->id_len, KM_SLEEP);
			bcopy(p->id_val, u8s->utf8string_val, p->id_len);

			remque(p);
			insque(p, hq);
			p->id_time = gethrestime_sec();

			found_stat = 1;
			break;
		}
	}
	mutex_exit(&(hq->hq_lock));

	return (found_stat);
}

/*
 * Search the specified cache for the existence of the specified id,
 * as it may have been inserted before this instance got a chance to
 * do it. If NOT found, then a new entry is allocated for the specified
 * cache, and inserted. The hash queue number is obtained from hash_number
 * if the behavior is HQ_HASH_HINT, or computed otherwise.
 *
 * cip         - cache info ptr
 * id          - id to resolve
 * u8s         - utf8 result from upcall
 * behavior    - has algorithm behavior
 * hash_number - hash number iff hint
 */
static void
nfs_idmap_cache_i2s_insert(idmap_cache_info_t *cip, uid_t id, utf8string *u8s,
    hash_stat behavior, uint_t hash_number)
{
	uint_t		 hashno;
	nfsidhq_t	*hq;
	nfsidmap_t	*newp;
	nfsidmap_t	*pnext;
	nfsidmap_t	*p;


	/*
	 * Obtain correct hash queue to insert new entry in
	 */
	switch (behavior) {
		case HQ_HASH_HINT:
			hashno = hash_number;
			break;

		case HQ_HASH_FIND:
		default:
			ID_HASH(id, hashno);
			break;
	}
	hq = &cip->table[hashno];


	/*
	 * Look for an existing entry in the cache. If one exists
	 * update it, and return. Otherwise, allocate a new cache
	 * entry, initialize and insert it.
	 */
	mutex_enter(&(hq->hq_lock));
	for (p = hq->hq_lru_forw; p != (nfsidmap_t *)hq; p = pnext) {

		pnext = p->id_forw;

		/*
		 * Check entry for staleness first, as user's id
		 * may have changed and may need to be remapped.
		 * Note that we don't evict entries from the cache
		 * if we're having trouble contacting nfsmapid(8)
		 */
		if (TIMEOUT(p->id_time) && (*cip->nfsidmap_daemon_dh) != NULL) {
			nfs_idmap_cache_rment(p);
			continue;
		}


		if ((p->id_no == id) && (p->id_len == u8s->utf8string_len)) {
			/*
			 * Found It ! Move to front, and update time.
			 */
			remque(p);
			insque(p, hq);
			p->id_time = gethrestime_sec();

			mutex_exit(&(hq->hq_lock));
			return;
		}
	}

	/*
	 * Not found ! Alloc, init and insert new entry
	 */
	newp = kmem_cache_alloc(nfsidmap_cache, KM_SLEEP);
	newp->id_len = u8s->utf8string_len;
	newp->id_val = kmem_alloc(u8s->utf8string_len, KM_SLEEP);
	bcopy(u8s->utf8string_val, newp->id_val, u8s->utf8string_len);
	newp->id_no = id;
	newp->id_time = gethrestime_sec();
	insque(newp, hq);

	mutex_exit(&(hq->hq_lock));
}

/*
 * Remove and free one cache entry
 */
static void
nfs_idmap_cache_rment(nfsidmap_t *p)
{
	remque(p);
	if (p->id_val != 0)
		kmem_free(p->id_val, p->id_len);
	kmem_cache_free(nfsidmap_cache, p);
}

#ifndef		UID_MAX
#define		UID_MAX		2147483647		/* see limits.h */
#endif

#ifndef		isdigit
#define		isdigit(c)	((c) >= '0' && (c) <= '9')
#endif

static int
is_stringified_id(utf8string *u8s)
{
	int	i;

	for (i = 0; i < u8s->utf8string_len; i++)
		if (!isdigit(u8s->utf8string_val[i]))
			return (0);
	return (1);
}

int
nfs_idmap_s2i_literal(utf8string *u8s, uid_t *id, int isserver)
{
	long	tmp;
	int	convd;
	char	ids[_MAXIDSTRLEN];

	/*
	 * "nobody" unless we can actually decode it.
	 */
	*id = UID_NOBODY;

	/*
	 * We're here because it has already been determined that the
	 * string contains no '@' _or_ the nfsmapid daemon has yet to
	 * be started.
	 */
	if (!is_stringified_id(u8s))
		return (0);

	/*
	 * If utf8string_len is greater than _MAXIDSTRLEN-1, then the id
	 * is going to be greater than UID_MAX. Return id of "nobody"
	 * right away.
	 */
	if (u8s->utf8string_len >= _MAXIDSTRLEN)
		return (isserver ? EPERM : 0);

	/*
	 * Make sure we pass a NULL terminated 'C' string to ddi_strtol
	 */
	bcopy(u8s->utf8string_val, ids, u8s->utf8string_len);
	ids[u8s->utf8string_len] = '\0';
	convd = ddi_strtol(ids, NULL, 10, &tmp);
	if (convd == 0 && tmp >= 0 && tmp <= UID_MAX) {
		*id = tmp;
		return (0);
	}
	return (isserver ? EPERM : 0);
}

static void
nfs_idmap_i2s_literal(uid_t id, utf8string *u8s)
{
	char	ids[_MAXIDSTRLEN];

	(void) snprintf(ids, _MAXIDSTRLEN, "%d", id);
	(void) str_to_utf8(ids, u8s);
}

/* -- Utility functions -- */

char *
utf8_strchr(utf8string *u8s, const char c)
{
	int	i;
	char	*u8p = u8s->utf8string_val;
	int	len = u8s->utf8string_len;

	for (i = 0; i < len; i++)
		if (u8p[i] == c)
			return (&u8p[i]);
	return (NULL);
}