// Copyright 1997-2000 Omni Development, Inc.  All rights reserved.
//
// This software may only be used and reproduced according to the
// terms in the file OmniSourceLicense.html, which should be
// distributed with this project and can also be found at
// http://www.omnigroup.com/DeveloperResources/OmniSourceLicense.html.

#import <OmniFoundation/OFMach.h>

#import <mach/mach.h>
#import <mach/mach_error.h>
#import <mach/bootstrap.h>

#import <OmniBase/OmniBase.h>
#import <stdio.h>

RCS_ID("$Header: /Network/Source/CVS/OmniGroup/Frameworks/OmniFoundation/OFMach.m,v 1.1 2000/09/14 04:27:42 bungi Exp $")

static BOOL         _OFMachInitialized = NO;
static host_priv_t  _OFHostPort = PORT_NULL;
static unsigned int _OFNumberOfProcessors = 0;

static void _OFInitHost()
{
    kern_return_t krc;
    processor_array_t processors;
    mach_port_t dummy_port_1, dummy_port_2, dummy_port_3, dummy_port_4;

    if (_OFMachInitialized)
        return;
    
    _OFMachInitialized = YES;
    
    krc = bootstrap_ports(mach_task_self(),
                          &_OFHostPort,
                          &dummy_port_1, &dummy_port_2,
                          &dummy_port_3, &dummy_port_4);
    if (krc != KERN_SUCCESS) {
        fprintf(stderr, "_OFInitHost: bootstrap_ports -- %s\n", mach_error_string(krc));
        return;
    }
    
    krc = host_processors(_OFHostPort, &processors, &_OFNumberOfProcessors);
    if (krc != KERN_SUCCESS) {
        fprintf(stderr, "_OFInitHost: host_processors -- %s\n", mach_error_string(krc));
        return;
    }
    
    // We don't actually need the list of processors...
    krc = vm_deallocate(mach_task_self(), (vm_address_t)processors, sizeof(*processors) * _OFNumberOfProcessors);
    if (krc != KERN_SUCCESS) {
        fprintf(stderr, "_OFInitHost: vm_deallocate -- %s\n", mach_error_string(krc));
        return;
    }
}

unsigned int OFNumberOfProcessors()
{
    if (!_OFMachInitialized)
        _OFInitHost();
    return _OFNumberOfProcessors;
}
