Loading...
   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
/*
 * Copyright (c) 1998-2000 Apple Computer, Inc. All rights reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 * 
 * The contents of this file constitute Original Code as defined in and
 * are subject to the Apple Public Source License Version 1.1 (the
 * "License").  You may not use this file except in compliance with the
 * License.  Please obtain a copy of the License at
 * http://www.apple.com/publicsource and read it before using this file.
 * 
 * This Original Code and all software distributed under the License are
 * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT.  Please see the
 * License for the specific language governing rights and limitations
 * under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */
/*
 * Copyright (c) 1999 Apple Computer, Inc.  All rights reserved. 
 *
 * IONetworkStack.cpp - An IOKit proxy for the BSD network stack.
 *
 * HISTORY
 *
 * IONetworkStack abstracts essential network stack services. These
 * include registering/unregistering network interfaces, and interface
 * name space management.
 *
 * Only a single IONetworkStack object is instantiated. This object will
 * register to receive a notification when a network interface object is
 * first published. The notification handler is responsible for attaching
 * the network stack object to the interface object as a client. When the
 * interface is terminated, this linkage is severed.
 *
 * This object does not participate in the data/packet flow. The interface
 * object will interact directly with DLIL to send and to receive packets.
 */

#include <IOKit/assert.h>
#include <IOKit/IOLib.h>
#include <IOKit/IOBSD.h>
#include <IOKit/IOMessage.h>
#include <IOKit/IOKitKeys.h>
#include <IOKit/network/IONetworkInterface.h>
#include <IOKit/network/IONetworkStack.h>
#include <libkern/c++/OSDictionary.h>

extern "C" {
#include <sys/param.h>
#include <sys/mbuf.h>
#include <sys/socket.h>
#include <net/bpf.h>
#include <net/if.h>
#include <netinet/if_ether.h>
#include <net/dlil.h>
#include <sys/sockio.h>
void ether_ifattach(struct ifnet * ifp);   // FIXME
}

#define super IOService
OSDefineMetaClassAndStructors( IONetworkStack, IOService )
OSMetaClassDefineReservedUnused( IONetworkStack,  0);
OSMetaClassDefineReservedUnused( IONetworkStack,  1);
OSMetaClassDefineReservedUnused( IONetworkStack,  2);
OSMetaClassDefineReservedUnused( IONetworkStack,  3);

#ifdef  DEBUG_XXX
#define __LOG(class, fn, fmt, args...)   IOLog(class "::%s " fmt, fn, ## args)
#define DLOG(fmt, args...) __LOG("IONetworkStack", __FUNCTION__, fmt, ## args)
#else
#define DLOG(fmt, args...)
#endif

#define NETIF_FLAGS(n)           ((n)->_clientVar[0])
#define SET_NETIF_FLAGS(n, x)    (NETIF_FLAGS(n) |= (x))
#define CLR_NETIF_FLAGS(n, x)    (NETIF_FLAGS(n) &= ~(x))

static IONetworkStack * gIONetworkStack = 0;

// Flags encoded on the interface object.
//
enum {
    kInterfaceFlagActive      = 0x01,  // Interface is awaiting registration
    kInterfaceFlagRegistered  = 0x02,  // Interface has registered with DLIL
    kInterfaceFlagRegistering = 0x04   // Interface is registering with DLIL
};

// IONetworkStackUserClient definition.
//
#include <IOKit/IOUserClient.h>

class IONetworkStackUserClient : public IOUserClient
{
    OSDeclareDefaultStructors( IONetworkStackUserClient )

protected:
    IONetworkStack * _provider;

public:
    static  IONetworkStackUserClient * withTask( task_t owningTask );
    virtual bool start( IOService * provider );
    virtual IOReturn clientClose();
    virtual IOReturn clientDied();
    virtual IOReturn setProperties( OSObject * properties );
};

//---------------------------------------------------------------------------
// Initialize the IONetworkStack object.

bool IONetworkStack::init( OSDictionary * properties )
{
    // Init our superclass first.

    if ( super::init(properties) == false )
        return false;

    return true;
}

//---------------------------------------------------------------------------
// IONetworkStack was matched to its provider (IOResources), now start it up.

bool IONetworkStack::start( IOService * provider )
{
    DLOG("%p\n", provider);

    if ( super::start(provider) == false )
        return false;

    // Only a single IONetworkStack object is created, and a reference
    // to this object is stored in a global variable.

    // When the boot process is VERY VERY slow for some unknown reason
    // we get two instances of IONetworkStack and theassert below fires.
    // so I am commenting the assert and replacing it with an if statement.
    // assert( gIONetworkStack == 0 );

    if ( gIONetworkStack != 0 )
        return false;

    gIONetworkStack = this;

    // Create containers to store interface objects.

    _ifSet = OSOrderedSet::withCapacity(10);
    if ( _ifSet == 0 )
        return false;

    _ifDict = OSDictionary::withCapacity(4);
    if ( _ifDict == 0 )
        return false;

    // Create a notification object to call a 'C' function, every time an
    // interface object is first published.

    _interfaceNotifier = addNotification(
                         /* type   */    gIOFirstPublishNotification,
                         /* match  */    serviceMatching("IONetworkInterface"),
                         /* action */    interfacePublished,
                         /* param  */    this );

    if ( _interfaceNotifier == 0 ) return false;

    // Register the IONetworkStack object.

    registerService();

    // Success.

    DLOG("success\n");

    return true;
}

//---------------------------------------------------------------------------
// Stop is called by a terminated provider, after being closed, but before
// this client object is detached from it.

void IONetworkStack::stop( IOService * provider )
{
    DLOG("%p\n", provider);
    super::stop(provider);
}

//---------------------------------------------------------------------------
// Release allocated resources.

void IONetworkStack::free()
{
    DLOG("\n");

    // IONotifier::remove() will remove the notification request
    // and release the object.

    if ( _interfaceNotifier )
    {
        _interfaceNotifier->remove();
        _interfaceNotifier = 0;
    }

    // Free interface containers.

    if ( _ifDict )
    {
        _ifDict->release();
        _ifDict = 0;
    }

    if ( _ifSet )
    {
        _ifSet->release();
        _ifSet = 0;
    }

    gIONetworkStack = 0;

    // Propagate the free to superclass.

    super::free();
}

//---------------------------------------------------------------------------
// A static method to get the global network stack object.

IONetworkStack * IONetworkStack::getNetworkStack()
{
    return (IONetworkStack *) IOService::waitForService(
                              IOService::serviceMatching("IONetworkStack") );
}


//===========================================================================
//
// Interface object container helpers.
//
//===========================================================================

//---------------------------------------------------------------------------
// Add the new interface object to an OSOrderedSet.

bool IONetworkStack::addInterface( IONetworkInterface * netif )
{
    return _ifSet->setObject(netif);
}

//---------------------------------------------------------------------------
// Remove an interface object from an OSOrderedSet.

void IONetworkStack::removeInterface( IONetworkInterface * netif )
{
    _ifSet->removeObject(netif);
    DLOG("count = %d\n", _ifSet->getCount());
}

//---------------------------------------------------------------------------
// Get an interface object at a given index.

IONetworkInterface * IONetworkStack::getInterface( UInt32 index )
{
    return (IONetworkInterface *) _ifSet->getObject(index);
}

//---------------------------------------------------------------------------
// Query whether the specified interface object is a member of the Set.

bool IONetworkStack::containsInterface( IONetworkInterface * netif )
{
    return _ifSet->containsObject(netif);
}

//---------------------------------------------------------------------------
// Add an interface object to the set of registered interfaces.

bool IONetworkStack::addRegisteredInterface( IONetworkInterface * netif )
{
    bool           success = true;
    OSOrderedSet * set;
    const char *   prefix = netif->getNamePrefix();

    if (prefix == 0) return false;

    // Look for a Set object in the dictionary.

    set = (OSOrderedSet *) _ifDict->getObject(prefix);

    // If not found, then create one and add it to the dictionary.

    if ( (set == 0) &&
         ((set = OSOrderedSet::withCapacity(10, orderRegisteredInterfaces))) )
    {
        success = _ifDict->setObject(prefix, set);
        set->release();
    }

    // Add the interface object to its corresponding set.
    // All objects in a set will have the same name prefix.

    success = (set && success) ? set->setObject(netif) : false;

    return success;
}

//---------------------------------------------------------------------------
// Remove an interface object from the set of registered interfaces.

void IONetworkStack::removeRegisteredInterface( IONetworkInterface * netif )
{
    OSOrderedSet * set;
    const char *   prefix = netif->getNamePrefix();

    if ( prefix )
    {
        set = (OSOrderedSet *) _ifDict->getObject(prefix);

        if ( set )
        {
            // Remove interface from set.

            set->removeObject(netif);
            DLOG("set:%s count = %d\n", prefix, set->getCount());

            // Remove (also release) the set from the dictionary.

            if ( set->getCount() == 0 ) _ifDict->removeObject(prefix);
        }
    }
}

//---------------------------------------------------------------------------
// Get an registered interface with the given prefix and unit number.

IONetworkInterface *
IONetworkStack::getRegisteredInterface( const char * prefix,
                                        UInt32       unit )
{
    OSOrderedSet *       set;
    IONetworkInterface * netif = 0;

    set = (OSOrderedSet *) _ifDict->getObject(prefix);

    for ( UInt32 index = 0;
          ( set && (netif = (IONetworkInterface *) set->getObject(index)) );
          index++ )
    {
        if ( netif->getUnitNumber() == unit )
            break;
    }

    return netif;
}

//---------------------------------------------------------------------------
// Get the last object (with largest index) in the set of registered
// interfaces with the specified prefix.

IONetworkInterface *
IONetworkStack::getLastRegisteredInterface( const char * prefix )
{
    OSOrderedSet * set;

    set = (OSOrderedSet *) _ifDict->getObject(prefix);

    return ( set ) ? (IONetworkInterface *) set->getLastObject() : 0;
}

//---------------------------------------------------------------------------
// Get the next available unit number in the set of registered interfaces
// with the specified prefix.

UInt32
IONetworkStack::getNextAvailableUnitNumber( const char * prefix,
                                            UInt32       startingUnit )
{
    IONetworkInterface * netif = getLastRegisteredInterface(prefix);

    if ( ( netif == 0 ) || ( netif->getUnitNumber() < startingUnit ) )
    {
        // The unit number provided is acceptable.
    }
    else if ( netif->getUnitNumber() == startingUnit )
    {
        // Conflict, bump proposed unit number by one.
        startingUnit++;
    }
    else
    {
        OSOrderedSet * set = (OSOrderedSet *) _ifDict->getObject(prefix);

        for ( UInt32 index = 0; set; index++ )
        {
            netif = (IONetworkInterface *) set->getObject(index);

            if ( ( netif == 0 ) ||
                 ( netif->getUnitNumber() > startingUnit ) )
                break;
            else if ( netif->getUnitNumber() < startingUnit )
                continue;
            else
                startingUnit = netif->getUnitNumber() + 1;
        }
    }

    return startingUnit;
}


//===========================================================================
//
// Interface Management.
//
//===========================================================================


//---------------------------------------------------------------------------
// A static member function that is called by a notification object when an 
// interface is published. This function is called with arbitration lock of
// the interface object held.

bool IONetworkStack::interfacePublished( void *      /* target */,
                                         void *      /* param  */,
                                         IOService * service )
{
    IONetworkInterface * netif   = OSDynamicCast(IONetworkInterface, service);
    bool                 success = false;

    DLOG("%p\n", netif);

    if ( gIONetworkStack == 0 )
        return false;

    gIONetworkStack->lockForArbitration();

    do {
        if ( netif == 0 ) break;

        // Early exit from redundant notifications.

        if ( gIONetworkStack->containsInterface(netif) == true )
        {
            success = true;
            break;
        }

        // Add the interface to a collection.

        if ( gIONetworkStack->addInterface(netif) == false )
            break;

        // Attach the stack object to the interface object as its client.

        if ( gIONetworkStack->attach(netif) == false )
            break;

        // Initialize the interface flags. These flags are used only
        // by IONetworkStack.

        NETIF_FLAGS(netif) = kInterfaceFlagActive;

        // No outside intervention is required for the primary interface
        // to be registered at unit 0. This is to assure that we have 'en0'
        // even if something is really fouled up. Ideally, this should be
        // removed in the future and have a single entity manage the
        // naming responsibility. And on Intel, there is no concept of a
        // "built-in" interface, so this will do nothing for Intel.

        if ( gIONetworkStack->_registerPrimaryInterface &&
             netif->isPrimaryInterface() )
        {
            const char * prefix = netif->getNamePrefix();
            const UInt32 unit   = 0;

            // If another interface already took unit 0, do nothing.

            if ( gIONetworkStack->getRegisteredInterface(prefix, unit) == 0 )
            {
                OSArray * array = OSArray::withCapacity(1);
                if ( array )
                {
                    gIONetworkStack->preRegisterInterface( netif,
                                                           prefix,
                                                           unit,
                                                           array );

                    completeRegistration( array, false );   // Async
                }
            }
        }

        success = true;
    }
    while ( false );

    // Remove interface on failure.

    if (success == false) gIONetworkStack->removeInterface(netif);

    gIONetworkStack->unlockForArbitration();

    return success;
}

//---------------------------------------------------------------------------
// Handle termination messages sent from the interface object (provider).

IOReturn IONetworkStack::message( UInt32      type,
                                  IOService * provider,
                                  void *      /* argument */ )
{
    IONetworkInterface * netif = (IONetworkInterface *) provider;
    IOReturn             ret   = kIOReturnBadArgument;

    DLOG("%lx %p\n", type, provider);

    if ( type == kIOMessageServiceIsTerminated )
    {
        lockForArbitration();

        do {
            // Verify that the provider object given is known.

            if ( containsInterface(netif) == false )
                break;

            ret = kIOReturnSuccess;

            // Interface has become inactive, it is no longer possible
            // to open or to attach to the interface object.
            // Mark the interface as Inactive.

            CLR_NETIF_FLAGS( netif, kInterfaceFlagActive );

            // Interface is registering with DLIL. Postpone termination until
            // the interface has completed the registration.

            if ( NETIF_FLAGS(netif) & kInterfaceFlagRegistering )
                break;

            // Remove the interface object. Don't worry, it is still retained.

            removeInterface(netif);

            // If interface was never registered with BSD, no additional
            // action is required.

            if ( (NETIF_FLAGS(netif) & kInterfaceFlagRegistered) == 0 )
                break;

            // Need to unregister the interface. Do this asynchronously.
            // The interface will be waiting for a close before advancing
            // to the next stage in the termination process.

            thread_call_func( (thread_call_func_t) unregisterBSDInterface,
                              netif,
                              TRUE );  /* unique call desired */
        }
        while ( false );

        unlockForArbitration();
    }

    return ret;
}

//---------------------------------------------------------------------------
// Detach an inactive interface that is currently registered with BSD.

void IONetworkStack::unregisterBSDInterface( IONetworkInterface * netif ) 
{
    assert( netif );

    // If dlil_if_detach() returns DLIL_WAIT_FOR_FREE, then we
    // must not close the interface until we receive a callback
    // from DLIL. Otherwise, proceed with the close.

    DLOG("%p\n", netif);

    if ( dlil_if_detach(netif->getIfnet()) != DLIL_WAIT_FOR_FREE )
    {
        bsdInterfaceWasUnregistered( netif->getIfnet() );
    }
}

//---------------------------------------------------------------------------
// Handle a callback from DLIL to signal that an interface can now be safely
// destroyed. DLIL will issue this call only if the dlil_if_detach() function
// returned DLIL_WAIT_FOR_FREE.

int IONetworkStack::bsdInterfaceWasUnregistered( struct ifnet * ifp )
{
    IONetworkInterface * netif;

    assert( ifp );

    netif = (IONetworkInterface *) ifp->if_private;
    DLOG("%p\n", netif);

    assert( netif && gIONetworkStack );

    // An interface was detached from DLIL. It is now safe to close the 
    // interface object.

    gIONetworkStack->lockForArbitration();

    assert( NETIF_FLAGS(netif) == kInterfaceFlagRegistered );

    // Update state.

    CLR_NETIF_FLAGS( netif, kInterfaceFlagRegistered );

    // Drop interface from list of registered interfaces,
    // and decrement interface retain count.

    gIONetworkStack->removeRegisteredInterface(netif);

    gIONetworkStack->unlockForArbitration();

    // Make sure the interface is brought down before it is closed.

    netif->setFlags( 0, IFF_UP );  // clear IFF_UP flag.
    (*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, 0);

    // Close interface and allow it to proceed with termination.

    netif->close(gIONetworkStack);

    return 0;
}

//---------------------------------------------------------------------------
// Pre-register a network interface. This function assumes that the
// caller is holding the arbitration lock.

bool IONetworkStack::preRegisterInterface( IONetworkInterface * netif,
                                           const char *         prefix,
                                           UInt32               unit,
                                           OSArray *            array )
{
    bool success = false;

    DLOG("%p %s %d\n", netif, prefix ? prefix : "", unit);

    assert( netif && array );

    do {
        if ( prefix == 0 ) break;

        // Verify that the interface object given is known.

        if ( containsInterface(netif) == false )
            break;

        // Interface must be in Active state.

        if ( NETIF_FLAGS(netif) != kInterfaceFlagActive )
        {
            break;
        }

        // The unit argument provided is a hint to indicate the lowest unit
        // number that can be assigned to the interface. We are allowed to
        // increment the unit number provided if the number is already
        // taken.

        unit = getNextAvailableUnitNumber(prefix, unit);

        // Open the interface object. This will fail if the interface
        // object has become inactive. Beware of reverse lock acquisition
        // sequence, which is interface then stack arbitration lock.
        // Must avoid taking locks in that order to avoid deadlocks.
        // The only exception is when handling the "First Publish"
        // notification, which is safe since the stack object does not
        // yet have a reference to the new interface.

        if ( netif->open(this) == false )
        {
            break;
        }

        // Update interface name properties and add the interface object
        // to a collection of registered interfaces. The chosen name will
        // be reserved until the interface is removed from the collection
        // of registered interfaces.

        if ( ( netif->setUnitNumber(unit) == false    ) ||
             ( addRegisteredInterface(netif) == false ) )
        {
            netif->close(this);
            break;
        }

        success = true;
    }
    while ( false );

    if ( success )
    {
        // Mark the interface as in the process of registering.

        SET_NETIF_FLAGS( netif, kInterfaceFlagRegistering );

        // Add interface to pre-registration array.
        // We assume the array has enough storage space for the new entry.

        success = array->setObject( netif );
        assert( success );
    }

    return success;
}

//---------------------------------------------------------------------------
// Complete the registration of interface objects stored in the array provided.
// The arbitration lock should not be held when the 'isSync' flag is true.

void
IONetworkStack::completeRegistration( OSArray * array, bool isSync )
{
    if ( isSync )
    {
        completeRegistrationUsingArray( array );
    }
    else
    {
        thread_call_func( (thread_call_func_t) completeRegistrationUsingArray,
                          array,
                          TRUE );  /* unique call desired */
    }
}

void
IONetworkStack::completeRegistrationUsingArray( OSArray * array )
{
    IONetworkInterface * netif;

    assert( array );

    for ( UInt32 i = 0; i < array->getCount(); i++ )
    {
        netif = (IONetworkInterface *) array->getObject(i);
        assert( netif );

        registerBSDInterface( netif );
    }

    array->release();   // consumes a ref count
}

//---------------------------------------------------------------------------
// Call DLIL functions to register the BSD interface.

void IONetworkStack::registerBSDInterface( IONetworkInterface * netif )
{
    char  ifname[20];
    bool  doTermination = false;

    assert( netif );

    // Attach the interface to DLIL.

    bpfattach( netif->getIfnet(), DLT_EN10MB, sizeof(struct ether_header) );
    ether_ifattach( netif->getIfnet() );

    // Add a kIOBSDNameKey property to the interface AFTER the interface
    // has registered with DLIL. The order is very important to avoid
    // rooting from an interface which is not yet known by BSD.

    sprintf(ifname, "%s%d", netif->getNamePrefix(), netif->getUnitNumber());
    netif->setProperty(kIOBSDNameKey, ifname);

    // Update state bits and detect for untimely interface termination.

    gIONetworkStack->lockForArbitration();

    assert( ( NETIF_FLAGS(netif) &
            ( kInterfaceFlagRegistering | kInterfaceFlagRegistered ) ) ==
              kInterfaceFlagRegistering );

    CLR_NETIF_FLAGS( netif, kInterfaceFlagRegistering );
    SET_NETIF_FLAGS( netif, kInterfaceFlagRegistered  );

    if ( ( NETIF_FLAGS(netif) & kInterfaceFlagActive ) == 0 )
    {
        doTermination = true;
    }
    else
    {
        // Re-register interface after the interface has registered with BSD.
        // Is there a danger in calling registerService while holding the
        // gIONetworkStack's arbitration lock?

        netif->registerService();
    }

    gIONetworkStack->unlockForArbitration();

    // In the unlikely event that an interface was terminated before
    // being registered, re-issue the termination message and tear it
    // all down.

    if ( doTermination )
    {
        gIONetworkStack->message(kIOMessageServiceIsTerminated, netif);
    }
}

//---------------------------------------------------------------------------
// External/Public API - Register all interfaces.

IOReturn
IONetworkStack::registerAllInterfaces()
{
    IONetworkInterface * netif;
    const UInt32         unit = 0;
    OSArray *            array;

    lockForArbitration();

    // Allocate array to hold pre-registered interface objects.

    array = OSArray::withCapacity( _ifSet->getCount() );
    if ( array == 0 )
    {
        unlockForArbitration();
        return kIOReturnNoMemory;
    }

    // Iterate through all interface objects.

    for ( UInt32 index = 0; ( netif = getInterface(index) ); index++ )
    {
        // Interface must be Active and not yet registered.

        if ( NETIF_FLAGS(netif) != kInterfaceFlagActive )
        {
            continue;
        }

        // Pre-register the interface.

        preRegisterInterface( netif,
                              netif->getNamePrefix(),
                              unit,
                              array );
    }

    unlockForArbitration();

    // Complete registration without holding the arbitration lock.

    completeRegistration( array, true );

    return kIOReturnSuccess;
}

//---------------------------------------------------------------------------
// External/Public API - Register primary interface.

IOReturn IONetworkStack::registerPrimaryInterface( bool enable )
{
    IONetworkInterface * netif;
    const UInt32         unit = 0;
    OSArray *            array;

    lockForArbitration();

    _registerPrimaryInterface = enable;

    if ( _registerPrimaryInterface == false )
    {
        unlockForArbitration();
        return kIOReturnSuccess;
    }

    // Allocate array to hold pre-registered interface objects.

    array = OSArray::withCapacity( _ifSet->getCount() );
    if ( array == 0 )
    {
        unlockForArbitration();
        return kIOReturnNoMemory;
    }

    // Iterate through all interface objects.

    for ( UInt32 index = 0; ( netif = getInterface(index) ); index++ )
    {
        const char * prefix = netif->getNamePrefix();
    
        // Interface must be Active and not yet registered.

        if ( NETIF_FLAGS(netif) != kInterfaceFlagActive )
        {
            continue;
        }

        // Primary only.

        if ( netif->isPrimaryInterface() != true )
        {
            continue;
        }

        // If the unit slot is already taken, forget it.

        if ( getRegisteredInterface( prefix, unit ) )
        {
            continue;
        }

        // Pre-register the interface.

        preRegisterInterface( netif, prefix, unit, array );
    }

    unlockForArbitration();

    // Complete registration without holding the arbitration lock.

    completeRegistration( array, true );

    return kIOReturnSuccess;
}

//---------------------------------------------------------------------------
// External/Public API - Register a single interface.

IOReturn IONetworkStack::registerInterface( IONetworkInterface * netif,
                                            const char *         prefix,
                                            UInt32               unit,
                                            bool                 isSync )
{
    bool       ret;
    OSArray *  array;

    // Create pre-registration array.

    array = OSArray::withCapacity( 1 );
    if ( array == 0 )
    {
        return kIOReturnNoMemory;
    }

    // Pre-registration has to be serialized, but the registration can
    // (and should) be completed without holding a lock. If the interface
    // has already been registered, or cannot be registered, then the
    // return value will be false.

    lockForArbitration();
    ret = preRegisterInterface( netif, prefix, unit, array );
    unlockForArbitration();

    // Complete the registration synchronously or asynchronously.
    // If synchronous, then this call will return after the interface
    // object in the array has registered with DLIL.

    completeRegistration( array, isSync );

    return ret ? kIOReturnSuccess : kIOReturnError;
}

//---------------------------------------------------------------------------
// Registered interfaces are ordered by their assigned unit number. Those with
// larger unit numbers will be placed behind those with smaller unit numbers.
// This ordering makes it easier to hunt for an available unit number slot for
// a new interface.

SInt32 IONetworkStack::
orderRegisteredInterfaces( const OSMetaClassBase * obj1,
                           const OSMetaClassBase * obj2,
                           void *     ref )
{
    const IONetworkInterface * netif1 = (const IONetworkInterface *) obj1;
    const IONetworkInterface * netif2 = (const IONetworkInterface *) obj2;

    assert( netif1 && netif2 );

    return ( netif2->getUnitNumber() - netif1->getUnitNumber() );
}

//---------------------------------------------------------------------------
// Create a user-client object to manage user space access.

IOReturn IONetworkStack::newUserClient( task_t           owningTask,
                                        void *           /* security_id */,
                                        UInt32           /* type */,
                                        IOUserClient **  handler )
{
    IOReturn       err = kIOReturnSuccess;
    IOUserClient * client;

    client = IONetworkStackUserClient::withTask(owningTask);

    if (!client || !client->attach(this) || !client->start(this))
    {
        if (client)
        {
            client->detach(this);
            client->release();
            client = 0;
            err = kIOReturnExclusiveAccess;
        }
        else
        {
            err = kIOReturnNoMemory;
        }
    }

    *handler = client;

    return err;
}

//---------------------------------------------------------------------------
// IONetworkStackUserClient implementation.

#undef  super
#define super IOUserClient
OSDefineMetaClassAndStructors( IONetworkStackUserClient, IOUserClient )

IONetworkStackUserClient * IONetworkStackUserClient::withTask( task_t task )
{
    IONetworkStackUserClient * me = new IONetworkStackUserClient;

    if ( me && me->init() == false )
    {
        me->release();
        return 0;
    }
    return me;
}

bool IONetworkStackUserClient::start( IOService * provider )
{
    if ( super::start(provider) == false )
        return false;

    if ( provider->open(this) == false )
        return false;

    _provider = (IONetworkStack *) provider;

    return true;
}

IOReturn IONetworkStackUserClient::clientClose()
{
    if (_provider)
    {
        _provider->close(this);
        detach(_provider);
    }
    return kIOReturnSuccess;
}

IOReturn IONetworkStackUserClient::clientDied()
{
    return clientClose();
}

IOReturn IONetworkStackUserClient::setProperties( OSObject * properties )
{
    IONetworkInterface * netif;
    OSDictionary *       dict = OSDynamicCast(OSDictionary, properties);
    IOReturn             ret  = kIOReturnBadArgument;
    OSString *           path = 0;
    OSNumber *           unit;
    OSNumber *           cmd;

    do {
        // Sanity check.

        if ( (_provider == 0) || (dict == 0) )
            break;

        // Switch on the specified user command.

        cmd = OSDynamicCast( OSNumber,
                             dict->getObject( kIONetworkStackUserCommand ) );
        if ( cmd == 0 )
            break;

        switch ( cmd->unsigned32BitValue() )
        {
        	// Register one interface.

            case kIORegisterOne:
            	path = OSDynamicCast( OSString,
            	                      dict->getObject( kIOPathMatchKey ));
                unit = OSDynamicCast( OSNumber,
                                      dict->getObject( kIOInterfaceUnit ));
                
                if ( (path == 0) || (unit == 0) )
            	{
                	break;
            	}
                
                netif = OSDynamicCast( IONetworkInterface,
                        IORegistryEntry::fromPath( path->getCStringNoCopy()) );
                        
                if ( netif == 0 ) break;

                ret = _provider->registerInterface( netif,
                                         netif->getNamePrefix(),
                                         unit->unsigned32BitValue() );

                netif->release();   // offset the retain by fromPath().

            	break;

            // Register all interfaces.

            case kIORegisterAll:
                ret = _provider->registerAllInterfaces();
                break;
        }
    }
    while ( false );

    return ret;
}