|
root / base / usr / src / uts / common / os / netstack.c
netstack.c C 1457 lines 40.8 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
/*
 * 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 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 * Copyright (c) 2017, Joyent, Inc.  All rights reserved.
 */

#include <sys/param.h>
#include <sys/sysmacros.h>
#include <sys/vm.h>
#include <sys/proc.h>
#include <sys/tuneable.h>
#include <sys/systm.h>
#include <sys/cmn_err.h>
#include <sys/debug.h>
#include <sys/sdt.h>
#include <sys/mutex.h>
#include <sys/bitmap.h>
#include <sys/atomic.h>
#include <sys/sunddi.h>
#include <sys/kobj.h>
#include <sys/disp.h>
#include <vm/seg_kmem.h>
#include <sys/zone.h>
#include <sys/netstack.h>

/*
 * What we use so that the zones framework can tell us about new zones,
 * which we use to create new stacks.
 */
static zone_key_t netstack_zone_key;

static int	netstack_initialized = 0;

/*
 * Track the registered netstacks.
 * The global lock protects
 * - ns_reg
 * - the list starting at netstack_head and following the netstack_next
 *   pointers.
 */
static kmutex_t netstack_g_lock;

/*
 * Registry of netstacks with their create/shutdown/destory functions.
 */
static struct netstack_registry	ns_reg[NS_MAX];

/*
 * Global list of existing stacks.  We use this when a new zone with
 * an exclusive IP instance is created.
 *
 * Note that in some cases a netstack_t needs to stay around after the zone
 * has gone away. This is because there might be outstanding references
 * (from TCP TIME_WAIT connections, IPsec state, etc). The netstack_t data
 * structure and all the foo_stack_t's hanging off of it will be cleaned up
 * when the last reference to it is dropped.
 * However, the same zone might be rebooted. That is handled using the
 * assumption that the zones framework picks a new zoneid each time a zone
 * is (re)booted. We assert for that condition in netstack_zone_create().
 * Thus the old netstack_t can take its time for things to time out.
 */
static netstack_t *netstack_head;

/*
 * To support kstat_create_netstack() using kstat_zone_add we need
 * to track both
 *  - all zoneids that use the global/shared stack
 *  - all kstats that have been added for the shared stack
 */
struct shared_zone_list {
	struct shared_zone_list *sz_next;
	zoneid_t		sz_zoneid;
};

struct shared_kstat_list {
	struct shared_kstat_list *sk_next;
	kstat_t			 *sk_kstat;
};

static kmutex_t netstack_shared_lock;	/* protects the following two */
static struct shared_zone_list	*netstack_shared_zones;
static struct shared_kstat_list	*netstack_shared_kstats;

static void	*netstack_zone_create(zoneid_t zoneid);
static void	netstack_zone_shutdown(zoneid_t zoneid, void *arg);
static void	netstack_zone_destroy(zoneid_t zoneid, void *arg);

static void	netstack_shared_zone_add(zoneid_t zoneid);
static void	netstack_shared_zone_remove(zoneid_t zoneid);
static void	netstack_shared_kstat_add(kstat_t *ks);
static void	netstack_shared_kstat_remove(kstat_t *ks);

typedef boolean_t applyfn_t(kmutex_t *, netstack_t *, int);

static void	apply_all_netstacks(int, applyfn_t *);
static void	apply_all_modules(netstack_t *, applyfn_t *);
static void	apply_all_modules_reverse(netstack_t *, applyfn_t *);
static boolean_t netstack_apply_create(kmutex_t *, netstack_t *, int);
static boolean_t netstack_apply_shutdown(kmutex_t *, netstack_t *, int);
static boolean_t netstack_apply_destroy(kmutex_t *, netstack_t *, int);
static boolean_t wait_for_zone_creator(netstack_t *, kmutex_t *);
static boolean_t wait_for_nms_inprogress(netstack_t *, nm_state_t *,
    kmutex_t *);

static void netstack_hold_locked(netstack_t *);

static ksema_t netstack_reap_limiter;
/*
 * Hard-coded constant, but since this is not tunable in real-time, it seems
 * making it an /etc/system tunable is better than nothing.
 */
uint_t netstack_outstanding_reaps = 1024;

void
netstack_init(void)
{
	mutex_init(&netstack_g_lock, NULL, MUTEX_DEFAULT, NULL);
	mutex_init(&netstack_shared_lock, NULL, MUTEX_DEFAULT, NULL);

	sema_init(&netstack_reap_limiter, netstack_outstanding_reaps, NULL,
	    SEMA_DRIVER, NULL);

	netstack_initialized = 1;

	/*
	 * We want to be informed each time a zone is created or
	 * destroyed in the kernel, so we can maintain the
	 * stack instance information.
	 */
	zone_key_create(&netstack_zone_key, netstack_zone_create,
	    netstack_zone_shutdown, netstack_zone_destroy);
}

/*
 * Register a new module with the framework.
 * This registers interest in changes to the set of netstacks.
 * The createfn and destroyfn are required, but the shutdownfn can be
 * NULL.
 * Note that due to the current zsd implementation, when the create
 * function is called the zone isn't fully present, thus functions
 * like zone_find_by_* will fail, hence the create function can not
 * use many zones kernel functions including zcmn_err().
 */
void
netstack_register(int moduleid,
    void *(*module_create)(netstackid_t, netstack_t *),
    void (*module_shutdown)(netstackid_t, void *),
    void (*module_destroy)(netstackid_t, void *))
{
	netstack_t *ns;

	ASSERT(netstack_initialized);
	ASSERT(moduleid >= 0 && moduleid < NS_MAX);
	ASSERT(module_create != NULL);

	/*
	 * Make instances created after this point in time run the create
	 * callback.
	 */
	mutex_enter(&netstack_g_lock);
	ASSERT(ns_reg[moduleid].nr_create == NULL);
	ASSERT(ns_reg[moduleid].nr_flags == 0);
	ns_reg[moduleid].nr_create = module_create;
	ns_reg[moduleid].nr_shutdown = module_shutdown;
	ns_reg[moduleid].nr_destroy = module_destroy;
	ns_reg[moduleid].nr_flags = NRF_REGISTERED;

	/*
	 * Determine the set of stacks that exist before we drop the lock.
	 * Set NSS_CREATE_NEEDED for each of those.
	 * netstacks which have been deleted will have NSS_CREATE_COMPLETED
	 * set, but check NSF_CLOSING to be sure.
	 */
	for (ns = netstack_head; ns != NULL; ns = ns->netstack_next) {
		nm_state_t *nms = &ns->netstack_m_state[moduleid];

		mutex_enter(&ns->netstack_lock);
		if (!(ns->netstack_flags & NSF_CLOSING) &&
		    (nms->nms_flags & NSS_CREATE_ALL) == 0) {
			nms->nms_flags |= NSS_CREATE_NEEDED;
			DTRACE_PROBE2(netstack__create__needed,
			    netstack_t *, ns, int, moduleid);
		}
		mutex_exit(&ns->netstack_lock);
	}
	mutex_exit(&netstack_g_lock);

	/*
	 * At this point in time a new instance can be created or an instance
	 * can be destroyed, or some other module can register or unregister.
	 * Make sure we either run all the create functions for this moduleid
	 * or we wait for any other creators for this moduleid.
	 */
	apply_all_netstacks(moduleid, netstack_apply_create);
}

void
netstack_unregister(int moduleid)
{
	netstack_t *ns;

	ASSERT(moduleid >= 0 && moduleid < NS_MAX);

	ASSERT(ns_reg[moduleid].nr_create != NULL);
	ASSERT(ns_reg[moduleid].nr_flags & NRF_REGISTERED);

	mutex_enter(&netstack_g_lock);
	/*
	 * Determine the set of stacks that exist before we drop the lock.
	 * Set NSS_SHUTDOWN_NEEDED and NSS_DESTROY_NEEDED for each of those.
	 * That ensures that when we return all the callbacks for existing
	 * instances have completed. And since we set NRF_DYING no new
	 * instances can use this module.
	 */
	for (ns = netstack_head; ns != NULL; ns = ns->netstack_next) {
		boolean_t created = B_FALSE;
		nm_state_t *nms = &ns->netstack_m_state[moduleid];

		mutex_enter(&ns->netstack_lock);

		/*
		 * We need to be careful here. We could actually have a netstack
		 * being created as we speak waiting for us to let go of this
		 * lock to proceed. It may have set NSS_CREATE_NEEDED, but not
		 * have gotten to the point of completing it yet. If
		 * NSS_CREATE_NEEDED, we can safely just remove it here and
		 * never create the module. However, if NSS_CREATE_INPROGRESS is
		 * set, we need to still flag this module for shutdown and
		 * deletion, just as though it had reached NSS_CREATE_COMPLETED.
		 *
		 * It is safe to do that because of two different guarantees
		 * that exist in the system. The first is that before we do a
		 * create, shutdown, or destroy, we ensure that nothing else is
		 * in progress in the system for this netstack and wait for it
		 * to complete. Secondly, because the zone is being created, we
		 * know that the following call to apply_all_netstack will block
		 * on the zone finishing its initialization.
		 */
		if (nms->nms_flags & NSS_CREATE_NEEDED)
			nms->nms_flags &= ~NSS_CREATE_NEEDED;

		if (nms->nms_flags & NSS_CREATE_INPROGRESS ||
		    nms->nms_flags & NSS_CREATE_COMPLETED)
			created = B_TRUE;

		if (ns_reg[moduleid].nr_shutdown != NULL && created &&
		    (nms->nms_flags & NSS_CREATE_COMPLETED) &&
		    (nms->nms_flags & NSS_SHUTDOWN_ALL) == 0) {
			nms->nms_flags |= NSS_SHUTDOWN_NEEDED;
			DTRACE_PROBE2(netstack__shutdown__needed,
			    netstack_t *, ns, int, moduleid);
		}
		if ((ns_reg[moduleid].nr_flags & NRF_REGISTERED) &&
		    ns_reg[moduleid].nr_destroy != NULL && created &&
		    (nms->nms_flags & NSS_DESTROY_ALL) == 0) {
			nms->nms_flags |= NSS_DESTROY_NEEDED;
			DTRACE_PROBE2(netstack__destroy__needed,
			    netstack_t *, ns, int, moduleid);
		}
		mutex_exit(&ns->netstack_lock);
	}
	/*
	 * Prevent any new netstack from calling the registered create
	 * function, while keeping the function pointers in place until the
	 * shutdown and destroy callbacks are complete.
	 */
	ns_reg[moduleid].nr_flags |= NRF_DYING;
	mutex_exit(&netstack_g_lock);

	apply_all_netstacks(moduleid, netstack_apply_shutdown);
	apply_all_netstacks(moduleid, netstack_apply_destroy);

	/*
	 * Clear the nms_flags so that we can handle this module
	 * being loaded again.
	 * Also remove the registered functions.
	 */
	mutex_enter(&netstack_g_lock);
	ASSERT(ns_reg[moduleid].nr_flags & NRF_REGISTERED);
	ASSERT(ns_reg[moduleid].nr_flags & NRF_DYING);
	for (ns = netstack_head; ns != NULL; ns = ns->netstack_next) {
		nm_state_t *nms = &ns->netstack_m_state[moduleid];

		mutex_enter(&ns->netstack_lock);
		if (nms->nms_flags & NSS_DESTROY_COMPLETED) {
			nms->nms_flags = 0;
			DTRACE_PROBE2(netstack__destroy__done,
			    netstack_t *, ns, int, moduleid);
		}
		mutex_exit(&ns->netstack_lock);
	}

	ns_reg[moduleid].nr_create = NULL;
	ns_reg[moduleid].nr_shutdown = NULL;
	ns_reg[moduleid].nr_destroy = NULL;
	ns_reg[moduleid].nr_flags = 0;
	mutex_exit(&netstack_g_lock);
}

/*
 * Lookup and/or allocate a netstack for this zone.
 */
static void *
netstack_zone_create(zoneid_t zoneid)
{
	netstackid_t stackid;
	netstack_t *ns;
	netstack_t **nsp;
	zone_t	*zone;
	int i;

	ASSERT(netstack_initialized);

	zone = zone_find_by_id_nolock(zoneid);
	ASSERT(zone != NULL);

	if (zone->zone_flags & ZF_NET_EXCL) {
		stackid = zoneid;
	} else {
		/* Look for the stack instance for the global */
		stackid = GLOBAL_NETSTACKID;
	}

	/* Allocate even if it isn't needed; simplifies locking */
	ns = (netstack_t *)kmem_zalloc(sizeof (netstack_t), KM_SLEEP);

	/* Look if there is a matching stack instance */
	mutex_enter(&netstack_g_lock);
	for (nsp = &netstack_head; *nsp != NULL;
	    nsp = &((*nsp)->netstack_next)) {
		if ((*nsp)->netstack_stackid == stackid) {
			/*
			 * Should never find a pre-existing exclusive stack
			 */
			VERIFY(stackid == GLOBAL_NETSTACKID);
			kmem_free(ns, sizeof (netstack_t));
			ns = *nsp;
			mutex_enter(&ns->netstack_lock);
			ns->netstack_numzones++;
			mutex_exit(&ns->netstack_lock);
			mutex_exit(&netstack_g_lock);
			DTRACE_PROBE1(netstack__inc__numzones,
			    netstack_t *, ns);
			/* Record that we have a new shared stack zone */
			netstack_shared_zone_add(zoneid);
			zone->zone_netstack = ns;
			return (ns);
		}
	}
	/* Not found */
	mutex_init(&ns->netstack_lock, NULL, MUTEX_DEFAULT, NULL);
	cv_init(&ns->netstack_cv, NULL, CV_DEFAULT, NULL);
	ns->netstack_stackid = zoneid;
	ns->netstack_numzones = 1;
	ns->netstack_refcnt = 1; /* Decremented by netstack_zone_destroy */
	ns->netstack_flags = NSF_UNINIT;
	*nsp = ns;
	zone->zone_netstack = ns;

	mutex_enter(&ns->netstack_lock);
	/*
	 * Mark this netstack as having a CREATE running so
	 * any netstack_register/netstack_unregister waits for
	 * the existing create callbacks to complete in moduleid order
	 */
	ns->netstack_flags |= NSF_ZONE_CREATE;

	/*
	 * Determine the set of module create functions that need to be
	 * called before we drop the lock.
	 * Set NSS_CREATE_NEEDED for each of those.
	 * Skip any with NRF_DYING set, since those are in the process of
	 * going away, by checking for flags being exactly NRF_REGISTERED.
	 */
	for (i = 0; i < NS_MAX; i++) {
		nm_state_t *nms = &ns->netstack_m_state[i];

		cv_init(&nms->nms_cv, NULL, CV_DEFAULT, NULL);

		if ((ns_reg[i].nr_flags == NRF_REGISTERED) &&
		    (nms->nms_flags & NSS_CREATE_ALL) == 0) {
			nms->nms_flags |= NSS_CREATE_NEEDED;
			DTRACE_PROBE2(netstack__create__needed,
			    netstack_t *, ns, int, i);
		}
	}
	mutex_exit(&ns->netstack_lock);
	mutex_exit(&netstack_g_lock);

	apply_all_modules(ns, netstack_apply_create);

	/* Tell any waiting netstack_register/netstack_unregister to proceed */
	mutex_enter(&ns->netstack_lock);
	ns->netstack_flags &= ~NSF_UNINIT;
	ASSERT(ns->netstack_flags & NSF_ZONE_CREATE);
	ns->netstack_flags &= ~NSF_ZONE_CREATE;
	cv_broadcast(&ns->netstack_cv);
	mutex_exit(&ns->netstack_lock);

	return (ns);
}

/* ARGSUSED */
static void
netstack_zone_shutdown(zoneid_t zoneid, void *arg)
{
	netstack_t *ns = (netstack_t *)arg;
	int i;

	ASSERT(arg != NULL);

	mutex_enter(&ns->netstack_lock);
	ASSERT(ns->netstack_numzones > 0);
	if (ns->netstack_numzones != 1) {
		/* Stack instance being used by other zone */
		mutex_exit(&ns->netstack_lock);
		ASSERT(ns->netstack_stackid == GLOBAL_NETSTACKID);
		return;
	}
	mutex_exit(&ns->netstack_lock);

	mutex_enter(&netstack_g_lock);
	mutex_enter(&ns->netstack_lock);
	/*
	 * Mark this netstack as having a SHUTDOWN running so
	 * any netstack_register/netstack_unregister waits for
	 * the existing create callbacks to complete in moduleid order
	 */
	ASSERT(!(ns->netstack_flags & NSF_ZONE_INPROGRESS));
	ns->netstack_flags |= NSF_ZONE_SHUTDOWN;

	/*
	 * Determine the set of stacks that exist before we drop the lock.
	 * Set NSS_SHUTDOWN_NEEDED for each of those.
	 */
	for (i = 0; i < NS_MAX; i++) {
		nm_state_t *nms = &ns->netstack_m_state[i];

		if ((ns_reg[i].nr_flags & NRF_REGISTERED) &&
		    ns_reg[i].nr_shutdown != NULL &&
		    (nms->nms_flags & NSS_CREATE_COMPLETED) &&
		    (nms->nms_flags & NSS_SHUTDOWN_ALL) == 0) {
			nms->nms_flags |= NSS_SHUTDOWN_NEEDED;
			DTRACE_PROBE2(netstack__shutdown__needed,
			    netstack_t *, ns, int, i);
		}
	}
	mutex_exit(&ns->netstack_lock);
	mutex_exit(&netstack_g_lock);

	/*
	 * Call the shutdown function for all registered modules for this
	 * netstack.
	 */
	apply_all_modules_reverse(ns, netstack_apply_shutdown);

	/* Tell any waiting netstack_register/netstack_unregister to proceed */
	mutex_enter(&ns->netstack_lock);
	ASSERT(ns->netstack_flags & NSF_ZONE_SHUTDOWN);
	ns->netstack_flags &= ~NSF_ZONE_SHUTDOWN;
	cv_broadcast(&ns->netstack_cv);
	mutex_exit(&ns->netstack_lock);
}

/*
 * Common routine to release a zone.
 * If this was the last zone using the stack instance then prepare to
 * have the refcnt dropping to zero free the zone.
 */
/* ARGSUSED */
static void
netstack_zone_destroy(zoneid_t zoneid, void *arg)
{
	netstack_t *ns = (netstack_t *)arg;

	ASSERT(arg != NULL);

	mutex_enter(&ns->netstack_lock);
	ASSERT(ns->netstack_numzones > 0);
	ns->netstack_numzones--;
	if (ns->netstack_numzones != 0) {
		/* Stack instance being used by other zone */
		mutex_exit(&ns->netstack_lock);
		ASSERT(ns->netstack_stackid == GLOBAL_NETSTACKID);
		/* Record that we a shared stack zone has gone away */
		netstack_shared_zone_remove(zoneid);
		return;
	}
	/*
	 * Set CLOSING so that netstack_find_by will not find it.
	 */
	ns->netstack_flags |= NSF_CLOSING;
	mutex_exit(&ns->netstack_lock);
	DTRACE_PROBE1(netstack__dec__numzones, netstack_t *, ns);
	/* No other thread can call zone_destroy for this stack */

	/*
	 * Decrease refcnt to account for the one in netstack_zone_init()
	 */
	netstack_rele(ns);
}

/*
 * Called when the reference count drops to zero.
 * Call the destroy functions for each registered module.
 */
static void
netstack_stack_inactive(netstack_t *ns)
{
	int i;

	mutex_enter(&netstack_g_lock);
	mutex_enter(&ns->netstack_lock);
	/*
	 * Mark this netstack as having a DESTROY running so
	 * any netstack_register/netstack_unregister waits for
	 * the existing destroy callbacks to complete in reverse moduleid order
	 */
	ASSERT(!(ns->netstack_flags & NSF_ZONE_INPROGRESS));
	ns->netstack_flags |= NSF_ZONE_DESTROY;
	/*
	 * If the shutdown callback wasn't called earlier (e.g., if this is
	 * a netstack shared between multiple zones), then we schedule it now.
	 *
	 * Determine the set of stacks that exist before we drop the lock.
	 * Set NSS_DESTROY_NEEDED for each of those. That
	 * ensures that when we return all the callbacks for existing
	 * instances have completed.
	 */
	for (i = 0; i < NS_MAX; i++) {
		nm_state_t *nms = &ns->netstack_m_state[i];

		if ((ns_reg[i].nr_flags & NRF_REGISTERED) &&
		    ns_reg[i].nr_shutdown != NULL &&
		    (nms->nms_flags & NSS_CREATE_COMPLETED) &&
		    (nms->nms_flags & NSS_SHUTDOWN_ALL) == 0) {
			nms->nms_flags |= NSS_SHUTDOWN_NEEDED;
			DTRACE_PROBE2(netstack__shutdown__needed,
			    netstack_t *, ns, int, i);
		}

		if ((ns_reg[i].nr_flags & NRF_REGISTERED) &&
		    ns_reg[i].nr_destroy != NULL &&
		    (nms->nms_flags & NSS_CREATE_COMPLETED) &&
		    (nms->nms_flags & NSS_DESTROY_ALL) == 0) {
			nms->nms_flags |= NSS_DESTROY_NEEDED;
			DTRACE_PROBE2(netstack__destroy__needed,
			    netstack_t *, ns, int, i);
		}
	}
	mutex_exit(&ns->netstack_lock);
	mutex_exit(&netstack_g_lock);

	/*
	 * Call the shutdown and destroy functions for all registered modules
	 * for this netstack.
	 *
	 * Since there are some ordering dependencies between the modules we
	 * tear them down in the reverse order of what was used to create them.
	 *
	 * Since a netstack_t is never reused (when a zone is rebooted it gets
	 * a new zoneid == netstackid i.e. a new netstack_t is allocated) we
	 * leave nms_flags the way it is i.e. with NSS_DESTROY_COMPLETED set.
	 * That is different than in the netstack_unregister() case.
	 */
	apply_all_modules_reverse(ns, netstack_apply_shutdown);
	apply_all_modules_reverse(ns, netstack_apply_destroy);

	/* Tell any waiting netstack_register/netstack_unregister to proceed */
	mutex_enter(&ns->netstack_lock);
	ASSERT(ns->netstack_flags & NSF_ZONE_DESTROY);
	ns->netstack_flags &= ~NSF_ZONE_DESTROY;
	cv_broadcast(&ns->netstack_cv);
	mutex_exit(&ns->netstack_lock);
}

/*
 * Apply a function to all netstacks for a particular moduleid.
 *
 * If there is any zone activity (due to a zone being created, shutdown,
 * or destroyed) we wait for that to complete before we proceed. This ensures
 * that the moduleids are processed in order when a zone is created or
 * destroyed.
 *
 * The applyfn has to drop netstack_g_lock if it does some work.
 * In that case we don't follow netstack_next,
 * even if it is possible to do so without any hazards. This is
 * because we want the design to allow for the list of netstacks threaded
 * by netstack_next to change in any arbitrary way during the time the
 * lock was dropped.
 *
 * It is safe to restart the loop at netstack_head since the applyfn
 * changes netstack_m_state as it processes things, so a subsequent
 * pass through will have no effect in applyfn, hence the loop will terminate
 * in at worst O(N^2).
 */
static void
apply_all_netstacks(int moduleid, applyfn_t *applyfn)
{
	netstack_t *ns;

	mutex_enter(&netstack_g_lock);
	ns = netstack_head;
	while (ns != NULL) {
		if (wait_for_zone_creator(ns, &netstack_g_lock)) {
			/* Lock dropped - restart at head */
			ns = netstack_head;
		} else if ((applyfn)(&netstack_g_lock, ns, moduleid)) {
			/* Lock dropped - restart at head */
			ns = netstack_head;
		} else {
			ns = ns->netstack_next;
		}
	}
	mutex_exit(&netstack_g_lock);
}

/*
 * Apply a function to all moduleids for a particular netstack.
 *
 * Since the netstack linkage doesn't matter in this case we can
 * ignore whether the function drops the lock.
 */
static void
apply_all_modules(netstack_t *ns, applyfn_t *applyfn)
{
	int i;

	mutex_enter(&netstack_g_lock);
	for (i = 0; i < NS_MAX; i++) {
		/*
		 * We don't care whether the lock was dropped
		 * since we are not iterating over netstack_head.
		 */
		(void) (applyfn)(&netstack_g_lock, ns, i);
	}
	mutex_exit(&netstack_g_lock);
}

/* Like the above but in reverse moduleid order */
static void
apply_all_modules_reverse(netstack_t *ns, applyfn_t *applyfn)
{
	int i;

	mutex_enter(&netstack_g_lock);
	for (i = NS_MAX-1; i >= 0; i--) {
		/*
		 * We don't care whether the lock was dropped
		 * since we are not iterating over netstack_head.
		 */
		(void) (applyfn)(&netstack_g_lock, ns, i);
	}
	mutex_exit(&netstack_g_lock);
}

/*
 * Call the create function for the ns and moduleid if CREATE_NEEDED
 * is set.
 * If some other thread gets here first and sets *_INPROGRESS, then
 * we wait for that thread to complete so that we can ensure that
 * all the callbacks are done when we've looped over all netstacks/moduleids.
 *
 * When we call the create function, we temporarily drop the netstack_lock
 * held by the caller, and return true to tell the caller it needs to
 * re-evalute the state.
 */
static boolean_t
netstack_apply_create(kmutex_t *lockp, netstack_t *ns, int moduleid)
{
	void *result;
	netstackid_t stackid;
	nm_state_t *nms = &ns->netstack_m_state[moduleid];
	boolean_t dropped = B_FALSE;

	ASSERT(MUTEX_HELD(lockp));
	mutex_enter(&ns->netstack_lock);

	if (wait_for_nms_inprogress(ns, nms, lockp))
		dropped = B_TRUE;

	if (nms->nms_flags & NSS_CREATE_NEEDED) {
		nms->nms_flags &= ~NSS_CREATE_NEEDED;
		nms->nms_flags |= NSS_CREATE_INPROGRESS;
		DTRACE_PROBE2(netstack__create__inprogress,
		    netstack_t *, ns, int, moduleid);
		mutex_exit(&ns->netstack_lock);
		mutex_exit(lockp);
		dropped = B_TRUE;

		ASSERT(ns_reg[moduleid].nr_create != NULL);
		stackid = ns->netstack_stackid;
		DTRACE_PROBE2(netstack__create__start,
		    netstackid_t, stackid,
		    netstack_t *, ns);
		result = (ns_reg[moduleid].nr_create)(stackid, ns);
		DTRACE_PROBE2(netstack__create__end,
		    void *, result, netstack_t *, ns);

		ASSERT(result != NULL);
		mutex_enter(lockp);
		mutex_enter(&ns->netstack_lock);
		ns->netstack_modules[moduleid] = result;
		nms->nms_flags &= ~NSS_CREATE_INPROGRESS;
		nms->nms_flags |= NSS_CREATE_COMPLETED;
		cv_broadcast(&nms->nms_cv);
		DTRACE_PROBE2(netstack__create__completed,
		    netstack_t *, ns, int, moduleid);
		mutex_exit(&ns->netstack_lock);
		return (dropped);
	} else {
		mutex_exit(&ns->netstack_lock);
		return (dropped);
	}
}

/*
 * Call the shutdown function for the ns and moduleid if SHUTDOWN_NEEDED
 * is set.
 * If some other thread gets here first and sets *_INPROGRESS, then
 * we wait for that thread to complete so that we can ensure that
 * all the callbacks are done when we've looped over all netstacks/moduleids.
 *
 * When we call the shutdown function, we temporarily drop the netstack_lock
 * held by the caller, and return true to tell the caller it needs to
 * re-evalute the state.
 */
static boolean_t
netstack_apply_shutdown(kmutex_t *lockp, netstack_t *ns, int moduleid)
{
	netstackid_t stackid;
	void * netstack_module;
	nm_state_t *nms = &ns->netstack_m_state[moduleid];
	boolean_t dropped = B_FALSE;

	ASSERT(MUTEX_HELD(lockp));
	mutex_enter(&ns->netstack_lock);

	if (wait_for_nms_inprogress(ns, nms, lockp))
		dropped = B_TRUE;

	if (nms->nms_flags & NSS_SHUTDOWN_NEEDED) {
		nms->nms_flags &= ~NSS_SHUTDOWN_NEEDED;
		nms->nms_flags |= NSS_SHUTDOWN_INPROGRESS;
		DTRACE_PROBE2(netstack__shutdown__inprogress,
		    netstack_t *, ns, int, moduleid);
		mutex_exit(&ns->netstack_lock);
		mutex_exit(lockp);
		dropped = B_TRUE;

		ASSERT(ns_reg[moduleid].nr_shutdown != NULL);
		stackid = ns->netstack_stackid;
		netstack_module = ns->netstack_modules[moduleid];
		DTRACE_PROBE2(netstack__shutdown__start,
		    netstackid_t, stackid,
		    void *, netstack_module);
		(ns_reg[moduleid].nr_shutdown)(stackid, netstack_module);
		DTRACE_PROBE1(netstack__shutdown__end,
		    netstack_t *, ns);

		mutex_enter(lockp);
		mutex_enter(&ns->netstack_lock);
		nms->nms_flags &= ~NSS_SHUTDOWN_INPROGRESS;
		nms->nms_flags |= NSS_SHUTDOWN_COMPLETED;
		cv_broadcast(&nms->nms_cv);
		DTRACE_PROBE2(netstack__shutdown__completed,
		    netstack_t *, ns, int, moduleid);
		mutex_exit(&ns->netstack_lock);
		return (dropped);
	} else {
		mutex_exit(&ns->netstack_lock);
		return (dropped);
	}
}

/*
 * Call the destroy function for the ns and moduleid if DESTROY_NEEDED
 * is set.
 * If some other thread gets here first and sets *_INPROGRESS, then
 * we wait for that thread to complete so that we can ensure that
 * all the callbacks are done when we've looped over all netstacks/moduleids.
 *
 * When we call the destroy function, we temporarily drop the netstack_lock
 * held by the caller, and return true to tell the caller it needs to
 * re-evalute the state.
 */
static boolean_t
netstack_apply_destroy(kmutex_t *lockp, netstack_t *ns, int moduleid)
{
	netstackid_t stackid;
	void * netstack_module;
	nm_state_t *nms = &ns->netstack_m_state[moduleid];
	boolean_t dropped = B_FALSE;

	ASSERT(MUTEX_HELD(lockp));
	mutex_enter(&ns->netstack_lock);

	if (wait_for_nms_inprogress(ns, nms, lockp))
		dropped = B_TRUE;

	if (nms->nms_flags & NSS_DESTROY_NEEDED) {
		nms->nms_flags &= ~NSS_DESTROY_NEEDED;
		nms->nms_flags |= NSS_DESTROY_INPROGRESS;
		DTRACE_PROBE2(netstack__destroy__inprogress,
		    netstack_t *, ns, int, moduleid);
		mutex_exit(&ns->netstack_lock);
		mutex_exit(lockp);
		dropped = B_TRUE;

		ASSERT(ns_reg[moduleid].nr_destroy != NULL);
		stackid = ns->netstack_stackid;
		netstack_module = ns->netstack_modules[moduleid];
		DTRACE_PROBE2(netstack__destroy__start,
		    netstackid_t, stackid,
		    void *, netstack_module);
		(ns_reg[moduleid].nr_destroy)(stackid, netstack_module);
		DTRACE_PROBE1(netstack__destroy__end,
		    netstack_t *, ns);

		mutex_enter(lockp);
		mutex_enter(&ns->netstack_lock);
		ns->netstack_modules[moduleid] = NULL;
		nms->nms_flags &= ~NSS_DESTROY_INPROGRESS;
		nms->nms_flags |= NSS_DESTROY_COMPLETED;
		cv_broadcast(&nms->nms_cv);
		DTRACE_PROBE2(netstack__destroy__completed,
		    netstack_t *, ns, int, moduleid);
		mutex_exit(&ns->netstack_lock);
		return (dropped);
	} else {
		mutex_exit(&ns->netstack_lock);
		return (dropped);
	}
}

/*
 * If somebody  is creating the netstack (due to a new zone being created)
 * then we wait for them to complete. This ensures that any additional
 * netstack_register() doesn't cause the create functions to run out of
 * order.
 * Note that we do not need such a global wait in the case of the shutdown
 * and destroy callbacks, since in that case it is sufficient for both
 * threads to set NEEDED and wait for INPROGRESS to ensure ordering.
 * Returns true if lockp was temporarily dropped while waiting.
 */
static boolean_t
wait_for_zone_creator(netstack_t *ns, kmutex_t *lockp)
{
	boolean_t dropped = B_FALSE;

	mutex_enter(&ns->netstack_lock);
	while (ns->netstack_flags & NSF_ZONE_CREATE) {
		DTRACE_PROBE1(netstack__wait__zone__inprogress,
		    netstack_t *, ns);
		if (lockp != NULL) {
			dropped = B_TRUE;
			mutex_exit(lockp);
		}
		cv_wait(&ns->netstack_cv, &ns->netstack_lock);
		if (lockp != NULL) {
			/* First drop netstack_lock to preserve order */
			mutex_exit(&ns->netstack_lock);
			mutex_enter(lockp);
			mutex_enter(&ns->netstack_lock);
		}
	}
	mutex_exit(&ns->netstack_lock);
	return (dropped);
}

/*
 * Wait for any INPROGRESS flag to be cleared for the netstack/moduleid
 * combination.
 * Returns true if lockp was temporarily dropped while waiting.
 */
static boolean_t
wait_for_nms_inprogress(netstack_t *ns, nm_state_t *nms, kmutex_t *lockp)
{
	boolean_t dropped = B_FALSE;

	while (nms->nms_flags & NSS_ALL_INPROGRESS) {
		DTRACE_PROBE2(netstack__wait__nms__inprogress,
		    netstack_t *, ns, nm_state_t *, nms);
		if (lockp != NULL) {
			dropped = B_TRUE;
			mutex_exit(lockp);
		}
		cv_wait(&nms->nms_cv, &ns->netstack_lock);
		if (lockp != NULL) {
			/* First drop netstack_lock to preserve order */
			mutex_exit(&ns->netstack_lock);
			mutex_enter(lockp);
			mutex_enter(&ns->netstack_lock);
		}
	}
	return (dropped);
}

/*
 * Get the stack instance used in caller's zone.
 * Increases the reference count, caller must do a netstack_rele.
 * It can't be called after zone_destroy() has started.
 */
netstack_t *
netstack_get_current(void)
{
	netstack_t *ns;

	ns = curproc->p_zone->zone_netstack;
	ASSERT(ns != NULL);
	return (netstack_hold_if_active(ns));
}

/*
 * Find a stack instance given the cred.
 * This is used by the modules to potentially allow for a future when
 * something other than the zoneid is used to determine the stack.
 */
netstack_t *
netstack_find_by_cred(const cred_t *cr)
{
	zoneid_t zoneid = crgetzoneid(cr);

	/* Handle the case when cr_zone is NULL */
	if (zoneid == (zoneid_t)-1)
		zoneid = GLOBAL_ZONEID;

	/* For performance ... */
	if (curproc->p_zone->zone_id == zoneid)
		return (netstack_get_current());
	else
		return (netstack_find_by_zoneid(zoneid));
}

/*
 * Find a stack instance given the zoneid.
 * Increases the reference count if found; caller must do a
 * netstack_rele().
 *
 * If there is no exact match then assume the shared stack instance
 * matches.
 *
 * Skip the uninitialized and closing ones.
 */
netstack_t *
netstack_find_by_zoneid(zoneid_t zoneid)
{
	netstack_t *ns;
	zone_t *zone;

	zone = zone_find_by_id(zoneid);

	if (zone == NULL)
		return (NULL);

	ASSERT(zone->zone_netstack != NULL);
	ns = netstack_hold_if_active(zone->zone_netstack);

	zone_rele(zone);
	return (ns);
}

/*
 * Find a stack instance given the zoneid. Can only be called from
 * the create callback. See the comments in zone_find_by_id_nolock why
 * that limitation exists.
 *
 * Increases the reference count if found; caller must do a
 * netstack_rele().
 *
 * If there is no exact match then assume the shared stack instance
 * matches.
 *
 * Skip the unitialized ones.
 */
netstack_t *
netstack_find_by_zoneid_nolock(zoneid_t zoneid)
{
	zone_t *zone;

	zone = zone_find_by_id_nolock(zoneid);

	if (zone == NULL)
		return (NULL);

	ASSERT(zone->zone_netstack != NULL);
	/* zone_find_by_id_nolock does not have a hold on the zone */
	return (netstack_hold_if_active(zone->zone_netstack));
}

/*
 * Find a stack instance given the stackid with exact match?
 * Increases the reference count if found; caller must do a
 * netstack_rele().
 *
 * Skip the unitialized ones.
 */
netstack_t *
netstack_find_by_stackid(netstackid_t stackid)
{
	netstack_t *ns;

	mutex_enter(&netstack_g_lock);
	for (ns = netstack_head; ns != NULL; ns = ns->netstack_next) {
		/* Can't use hold_if_active because of stackid check. */
		mutex_enter(&ns->netstack_lock);
		if (ns->netstack_stackid == stackid &&
		    !(ns->netstack_flags & (NSF_UNINIT|NSF_CLOSING))) {
			netstack_hold_locked(ns);
			mutex_exit(&ns->netstack_lock);
			mutex_exit(&netstack_g_lock);
			return (ns);
		}
		mutex_exit(&ns->netstack_lock);
	}
	mutex_exit(&netstack_g_lock);
	return (NULL);
}

boolean_t
netstack_inuse_by_stackid(netstackid_t stackid)
{
	netstack_t *ns;
	boolean_t rval = B_FALSE;

	mutex_enter(&netstack_g_lock);

	for (ns = netstack_head; ns != NULL; ns = ns->netstack_next) {
		if (ns->netstack_stackid == stackid) {
			rval = B_TRUE;
			break;
		}
	}

	mutex_exit(&netstack_g_lock);

	return (rval);
}


static void
netstack_reap(void *arg)
{
	netstack_t **nsp, *ns = (netstack_t *)arg;
	boolean_t found;
	int i;

	/*
	 * Time to call the destroy functions and free up
	 * the structure
	 */
	netstack_stack_inactive(ns);

	/* Make sure nothing increased the references */
	ASSERT(ns->netstack_refcnt == 0);
	ASSERT(ns->netstack_numzones == 0);

	/* Finally remove from list of netstacks */
	mutex_enter(&netstack_g_lock);
	found = B_FALSE;
	for (nsp = &netstack_head; *nsp != NULL;
	    nsp = &(*nsp)->netstack_next) {
		if (*nsp == ns) {
			*nsp = ns->netstack_next;
			ns->netstack_next = NULL;
			found = B_TRUE;
			break;
		}
	}
	ASSERT(found);
	mutex_exit(&netstack_g_lock);

	/* Make sure nothing increased the references */
	ASSERT(ns->netstack_refcnt == 0);
	ASSERT(ns->netstack_numzones == 0);

	ASSERT(ns->netstack_flags & NSF_CLOSING);

	for (i = 0; i < NS_MAX; i++) {
		nm_state_t *nms = &ns->netstack_m_state[i];

		cv_destroy(&nms->nms_cv);
	}
	mutex_destroy(&ns->netstack_lock);
	cv_destroy(&ns->netstack_cv);
	kmem_free(ns, sizeof (*ns));
	/* Allow another reap to be scheduled. */
	sema_v(&netstack_reap_limiter);
}

void
netstack_rele(netstack_t *ns)
{
	int refcnt, numzones;

	mutex_enter(&ns->netstack_lock);
	ASSERT(ns->netstack_refcnt > 0);
	ns->netstack_refcnt--;
	/*
	 * As we drop the lock additional netstack_rele()s can come in
	 * and decrement the refcnt to zero and free the netstack_t.
	 * Store pointers in local variables and if we were not the last
	 * then don't reference the netstack_t after that.
	 */
	refcnt = ns->netstack_refcnt;
	numzones = ns->netstack_numzones;
	DTRACE_PROBE1(netstack__dec__ref, netstack_t *, ns);
	mutex_exit(&ns->netstack_lock);

	if (refcnt == 0 && numzones == 0) {
		/*
		 * Because there are possibilities of re-entrancy in various
		 * netstack structures by callers, which might cause a lock up
		 * due to odd reference models, or other factors, we choose to
		 * schedule the actual deletion of this netstack as a deferred
		 * task on the system taskq.  This way, any such reference
		 * models won't trip over themselves.
		 *
		 * Assume we aren't in a high-priority interrupt context, so
		 * we can use KM_SLEEP and semaphores.
		 */
		if (sema_tryp(&netstack_reap_limiter) == 0) {
			/*
			 * Indicate we're slamming against a limit.
			 */
			hrtime_t measurement = gethrtime();

			sema_p(&netstack_reap_limiter);
			/* Capture delay in ns. */
			DTRACE_PROBE1(netstack__reap__rate__limited,
			    hrtime_t, gethrtime() - measurement);
		}

		/* TQ_SLEEP should prevent taskq_dispatch() from failing. */
		(void) taskq_dispatch(system_taskq, netstack_reap, ns,
		    TQ_SLEEP);
	}
}

static void
netstack_hold_locked(netstack_t *ns)
{
	ASSERT(MUTEX_HELD(&ns->netstack_lock));
	ns->netstack_refcnt++;
	ASSERT(ns->netstack_refcnt > 0);
	DTRACE_PROBE1(netstack__inc__ref, netstack_t *, ns);
}

/*
 * If the passed-in netstack isn't active (i.e. it's uninitialized or closing),
 * return NULL, otherwise return it with its reference held.  Common code
 * for many netstack_find*() functions.
 */
netstack_t *
netstack_hold_if_active(netstack_t *ns)
{
	netstack_t *retval;

	mutex_enter(&ns->netstack_lock);
	if (ns->netstack_flags & (NSF_UNINIT | NSF_CLOSING)) {
		retval = NULL;
	} else {
		netstack_hold_locked(ns);
		retval = ns;
	}
	mutex_exit(&ns->netstack_lock);

	return (retval);
}

void
netstack_hold(netstack_t *ns)
{
	mutex_enter(&ns->netstack_lock);
	netstack_hold_locked(ns);
	mutex_exit(&ns->netstack_lock);
}

/*
 * To support kstat_create_netstack() using kstat_zone_add we need
 * to track both
 *  - all zoneids that use the global/shared stack
 *  - all kstats that have been added for the shared stack
 */
kstat_t *
kstat_create_netstack(char *ks_module, int ks_instance, char *ks_name,
    char *ks_class, uchar_t ks_type, uint_t ks_ndata, uchar_t ks_flags,
    netstackid_t ks_netstackid)
{
	kstat_t *ks;

	if (ks_netstackid == GLOBAL_NETSTACKID) {
		ks = kstat_create_zone(ks_module, ks_instance, ks_name,
		    ks_class, ks_type, ks_ndata, ks_flags, GLOBAL_ZONEID);
		if (ks != NULL)
			netstack_shared_kstat_add(ks);
		return (ks);
	} else {
		zoneid_t zoneid = ks_netstackid;

		return (kstat_create_zone(ks_module, ks_instance, ks_name,
		    ks_class, ks_type, ks_ndata, ks_flags, zoneid));
	}
}

void
kstat_delete_netstack(kstat_t *ks, netstackid_t ks_netstackid)
{
	if (ks_netstackid == GLOBAL_NETSTACKID) {
		netstack_shared_kstat_remove(ks);
	}
	kstat_delete(ks);
}

static void
netstack_shared_zone_add(zoneid_t zoneid)
{
	struct shared_zone_list *sz;
	struct shared_kstat_list *sk;

	sz = (struct shared_zone_list *)kmem_zalloc(sizeof (*sz), KM_SLEEP);
	sz->sz_zoneid = zoneid;

	/* Insert in list */
	mutex_enter(&netstack_shared_lock);
	sz->sz_next = netstack_shared_zones;
	netstack_shared_zones = sz;

	/*
	 * Perform kstat_zone_add for each existing shared stack kstat.
	 * Note: Holds netstack_shared_lock lock across kstat_zone_add.
	 */
	for (sk = netstack_shared_kstats; sk != NULL; sk = sk->sk_next) {
		kstat_zone_add(sk->sk_kstat, zoneid);
	}
	mutex_exit(&netstack_shared_lock);
}

static void
netstack_shared_zone_remove(zoneid_t zoneid)
{
	struct shared_zone_list **szp, *sz;
	struct shared_kstat_list *sk;

	/* Find in list */
	mutex_enter(&netstack_shared_lock);
	sz = NULL;
	for (szp = &netstack_shared_zones; *szp != NULL;
	    szp = &((*szp)->sz_next)) {
		if ((*szp)->sz_zoneid == zoneid) {
			sz = *szp;
			break;
		}
	}
	/* We must find it */
	ASSERT(sz != NULL);
	*szp = sz->sz_next;
	sz->sz_next = NULL;

	/*
	 * Perform kstat_zone_remove for each existing shared stack kstat.
	 * Note: Holds netstack_shared_lock lock across kstat_zone_remove.
	 */
	for (sk = netstack_shared_kstats; sk != NULL; sk = sk->sk_next) {
		kstat_zone_remove(sk->sk_kstat, zoneid);
	}
	mutex_exit(&netstack_shared_lock);

	kmem_free(sz, sizeof (*sz));
}

static void
netstack_shared_kstat_add(kstat_t *ks)
{
	struct shared_zone_list *sz;
	struct shared_kstat_list *sk;

	sk = (struct shared_kstat_list *)kmem_zalloc(sizeof (*sk), KM_SLEEP);
	sk->sk_kstat = ks;

	/* Insert in list */
	mutex_enter(&netstack_shared_lock);
	sk->sk_next = netstack_shared_kstats;
	netstack_shared_kstats = sk;

	/*
	 * Perform kstat_zone_add for each existing shared stack zone.
	 * Note: Holds netstack_shared_lock lock across kstat_zone_add.
	 */
	for (sz = netstack_shared_zones; sz != NULL; sz = sz->sz_next) {
		kstat_zone_add(ks, sz->sz_zoneid);
	}
	mutex_exit(&netstack_shared_lock);
}

static void
netstack_shared_kstat_remove(kstat_t *ks)
{
	struct shared_zone_list *sz;
	struct shared_kstat_list **skp, *sk;

	/* Find in list */
	mutex_enter(&netstack_shared_lock);
	sk = NULL;
	for (skp = &netstack_shared_kstats; *skp != NULL;
	    skp = &((*skp)->sk_next)) {
		if ((*skp)->sk_kstat == ks) {
			sk = *skp;
			break;
		}
	}
	/* Must find it */
	ASSERT(sk != NULL);
	*skp = sk->sk_next;
	sk->sk_next = NULL;

	/*
	 * Perform kstat_zone_remove for each existing shared stack kstat.
	 * Note: Holds netstack_shared_lock lock across kstat_zone_remove.
	 */
	for (sz = netstack_shared_zones; sz != NULL; sz = sz->sz_next) {
		kstat_zone_remove(ks, sz->sz_zoneid);
	}
	mutex_exit(&netstack_shared_lock);
	kmem_free(sk, sizeof (*sk));
}

/*
 * If a zoneid is part of the shared zone, return true
 */
static boolean_t
netstack_find_shared_zoneid(zoneid_t zoneid)
{
	struct shared_zone_list *sz;

	mutex_enter(&netstack_shared_lock);
	for (sz = netstack_shared_zones; sz != NULL; sz = sz->sz_next) {
		if (sz->sz_zoneid == zoneid) {
			mutex_exit(&netstack_shared_lock);
			return (B_TRUE);
		}
	}
	mutex_exit(&netstack_shared_lock);
	return (B_FALSE);
}

/*
 * Hide the fact that zoneids and netstackids are allocated from
 * the same space in the current implementation.
 * We currently do not check that the stackid/zoneids are valid, since there
 * is no need for that. But this should only be done for ids that are
 * valid.
 */
zoneid_t
netstackid_to_zoneid(netstackid_t stackid)
{
	return (stackid);
}

netstackid_t
zoneid_to_netstackid(zoneid_t zoneid)
{
	if (netstack_find_shared_zoneid(zoneid))
		return (GLOBAL_ZONEID);
	else
		return (zoneid);
}

zoneid_t
netstack_get_zoneid(netstack_t *ns)
{
	return (netstackid_to_zoneid(ns->netstack_stackid));
}

/*
 * Simplistic support for walking all the handles.
 * Example usage:
 *	netstack_handle_t nh;
 *	netstack_t *ns;
 *
 *	netstack_next_init(&nh);
 *	while ((ns = netstack_next(&nh)) != NULL) {
 *		do something;
 *		netstack_rele(ns);
 *	}
 *	netstack_next_fini(&nh);
 */
void
netstack_next_init(netstack_handle_t *handle)
{
	*handle = 0;
}

/* ARGSUSED */
void
netstack_next_fini(netstack_handle_t *handle)
{
}

netstack_t *
netstack_next(netstack_handle_t *handle)
{
	netstack_t *ns;
	int i, end;

	end = *handle;
	/* Walk skipping *handle number of instances */

	/* Look if there is a matching stack instance */
	mutex_enter(&netstack_g_lock);
	ns = netstack_head;
	for (i = 0; i < end; i++) {
		if (ns == NULL)
			break;
		ns = ns->netstack_next;
	}
	/*
	 * Skip those that aren't really here (uninitialized or closing).
	 * Can't use hold_if_active because of "end" tracking.
	 */
	while (ns != NULL) {
		mutex_enter(&ns->netstack_lock);
		if ((ns->netstack_flags & (NSF_UNINIT|NSF_CLOSING)) == 0) {
			*handle = end + 1;
			netstack_hold_locked(ns);
			mutex_exit(&ns->netstack_lock);
			break;
		}
		mutex_exit(&ns->netstack_lock);
		end++;
		ns = ns->netstack_next;
	}
	mutex_exit(&netstack_g_lock);
	return (ns);
}