IOAGPDevice.h



© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOAGPDevice

IOAGPDevice



Member Functions

commitAGPMemory

Abstract: Makes memory addressable by AGP transactions.
public:

virtual IOReturn commitAGPMemory( IOMemoryDescriptor * memory, IOByteCount agpOffset, IOOptionBits options = 0 );

Makes the memory described by the IOMemoryDescriptor object addressable by AGP by entering its pages into the GART array, given an offset into AGP space supplied by the caller (usually allocated by the AGP range allocator). It is the callers responsibility to prepare non-kernel pageable memory before calling this method, with IOMemoryDescriptor::prepare.

Parameters

NameDescription
memoryA IOMemoryDescriptor object describing the memory to add to the GART.
agpOffsetAn offset into AGP space that the caller has allocated - usually allocated by the AGP range allocator.
optionsNone currently defined - pass zero.
Result: An IOReturn code indicating success or failure.

createAGPSpace

Abstract: Allocates the AGP space, and enables AGP transactions on the master and slave.
public:

virtual IOReturn createAGPSpace( IOOptionBits options, IOPhysicalAddress * address, IOPhysicalLength * length );

This method should be called by the driver for the AGP master device to set the size of the space and enable AGP transactions. It will destroy any AGP space currently allocated.

Parameters

NameDescription
optionsNo options are currently defined, pass zero.
addressThe physical range allocated for the AGP space is passed back to the caller.
lengthAn in/out parameter - the caller sets the devices maximum AGP addressing and the actual size created is passed back.
Result: An IOReturn code indicating success or failure.

destroyAGPSpace

Abstract: Destroys the AGP space, and disables AGP transactions on the master and slave.
public:

virtual IOReturn destroyAGPSpace( void );

This method should be called by the driver to shutdown AGP transactions and release resources.


getAGPRangeAllocator

Abstract: Accessor to obtain the AGP range allocator.
public:

virtual IORangeAllocator * getAGPRangeAllocator( void );

To allocate ranges in AGP space, obtain a range allocator for the space with this method. It is retained while the space is created (until destroyAGPSpace is called) and should not be released by the caller.

Result: A pointer to the range allocator for the AGP space.

getAGPStatus

Abstract: Returns the current state of the AGP bus.
public:

virtual IOOptionBits getAGPStatus( IOOptionBits which = kIOAGPDefaultStatus );

Returns state bits for the AGP bus. Only one type of status is currently defined.

Parameters

NameDescription
whichType of status - only kIOAGPDefaultStatus is currently valid.
Result: Mask of status bits for the AGP bus.

releaseAGPMemory

Abstract: Releases memory addressable by AGP transactions.
public:

virtual IOReturn releaseAGPMemory( IOMemoryDescriptor * memory, IOByteCount agpOffset );

Makes the memory described by the IOMemoryDescriptor object unaddressable by AGP by removing its pages from the GART array, given an offset into AGP space supplied by the caller (usually allocated by the AGP range allocator). It is the callers responsibility to complete non-kernel pageable memory before calling this method, with IOMemoryDescriptor::complete.

Parameters

NameDescription
memoryA IOMemoryDescriptor object describing the memory to remove from the GART.
agpOffsetAn offset into AGP space that the caller has allocated - usually allocated by the AGP range allocator.
Result: An IOReturn code indicating success or failure.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOBasicSCSI.h

IOBasicSCSI.h



Typedefs

statevalue

typedef  enum  stateValues  stateValue;

const  bool  kSync  =  true;  /*  type  info  for  requests  awaiting  power  */
const  bool  kAsync  =  false;

};

Shorthand for enum StateValues.


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOBasicSCSI

IOBasicSCSI



Member Functions

RWCompletion

Abstract: Asynchronous read/write completion routine.
protected:

virtual void RWCompletion(struct context *cx) = 0;

A subclass must implement the read-write completion, called upon completion of an IO started by doAsyncReadWrite.

Parameters

NameDescription
cxA pointer to the context structure for the completing command.

allocateContext

Abstract: Allocate a context structure for use with the current IO operation.
protected:

virtual struct context * allocateContext(void);


allocateInquiryBuffer

Abstract: Allocate an inquiry buffer.
protected:

virtual IOReturn allocateInquiryBuffer(UInt8 **buf,UInt32 size);

Parameters

NameDescription
bufA pointer for the returned buffer pointer.
sizeThe requested size of the buffer, in bytes.

allocateReadCapacityBuffer

Abstract: Allocate a buffer for Read-Capacity data.
protected:

virtual IOReturn allocateReadCapacityBuffer(UInt8 **buf,UInt8 size);

Parameters

NameDescription
bufA pointer for the returned buffer pointer.
sizeThe requested size of the buffer, in bytes.

allocateTempBuffer

Abstract: Allocate a buffer for temporary use.
protected:

virtual IOReturn allocateTempBuffer(UInt8 **buf,UInt32 size);

Parameters

NameDescription
bufA pointer for the returned buffer pointer.
sizeThe requested size of the buffer, in bytes.

createReadCdb

Abstract: Create a SCSI CDB for a read operation.
protected:

virtual UInt32 createReadCdb( UInt8 *cdb, /* in */ UInt32 *cdbLength, /* out */ UInt32 block, /* in */ UInt32 nblks, /* in */ UInt32 *maxAutoSenseLength, /* out */ UInt32 *timeoutSeconds); /* out */

Override this to control the cdb created for a read operation. The default implementation creates a 10-byte read command with disconnect allowed, 8-byte autosense, and a 2-second timeout.

Parameters

NameDescription
cdbA pointer to the CDB bytes.
cdbLengthThe length of the CDB in bytes.
blockThe device block to be read.
nblksThe number of blocks to be transferred.
maxAutoSenseLengthThe maximum size of the autosense data, in bytes. A value of zero will disable autosense.
timeoutSecondsThe command timeout in seconds.
Result: The IOSCSICommandOptions returned will be used to issue the command.

createWriteCdb

Abstract: Create a SCSI CDB for a write operation.
protected:

virtual UInt32 createWriteCdb( UInt8 *cdb, /* in */ UInt32 *cdbLength, /* out */ UInt32 block, /* in */ UInt32 nblks, /* in */ UInt32 *maxAutoSenseLength, /* out */ UInt32 *timeoutSeconds); /* out */

Override this to control the cdb created for a write operation. The default implementation creates a 10-byte write command with disconnect allowed, 8-byte autosense, and a 2-second timeout.

Parameters

NameDescription
cdbA pointer to the CDB bytes.
cdbLengthThe length of the CDB in bytes.
blockThe device block to be written.
nblksThe number of blocks to be transferred.
maxAutoSenseLengthThe maximum size of the autosense data, in bytes. A value of zero will disable autosense.
timeoutSecondsThe command timeout in seconds.
Result: The IOSCSICommandOptions returned will be used to issue the command.

deleteContext

Abstract: Delete a context structure.
protected:

virtual void deleteContext(struct context *cx);

This method also issues a "release" for the IO buffer and/or lock, if any.

Parameters

NameDescription
cxA pointer to the context structure to be deleted.

deleteInquiryBuffer

Abstract: Delete an inquiry data buffer.
protected:

virtual void deleteInquiryBuffer(UInt8 *buf,UInt32 size);

Parameters

NameDescription
bufA pointer to the buffer.
sizeThe requested size of the buffer, in bytes.

deleteReadCapacityBuffer

Abstract: Delete a Read-Capacity data buffer.
protected:

virtual void deleteReadCapacityBuffer(UInt8 *buf,UInt32 len);

Parameters

NameDescription
bufA pointer to the buffer.
lenThe requested size of the buffer, in bytes.

deleteTempBuffer

Abstract: Delete a temporary data buffer.
protected:

virtual void deleteTempBuffer(UInt8 *buf,UInt32 len);

Parameters

NameDescription
bufA pointer to the buffer.
lenThe requested size of the buffer, in bytes.

dequeueCommands

Abstract: Dequeue commands previously enqueued awaiting the proper device power level.
protected:

virtual void dequeueCommands(void);

This method is called when a command is queued (from queueCommand), when a call completes (from RWCompletion), and when the device power level changes. All commands for which the device power level is proper are immediately dequeued.

Queued synchronous commands are simply "awakened" by unlocking a lock. The originating thread then continues and issues the command. Asynchronous commands are immediately dispatched via a call to standardAsyncReadWriteExecute.


deviceTypeMatches

Abstract: Determine if device type matches expected type.
public:

virtual bool deviceTypeMatches(UInt8 inqBuf[],UInt32 inqLen) = 0;

This method must be implemented by a device-specific subclass.

Parameters

NameDescription
inqBufA pointer to the SCSI inquiry data for the device.
inqLenThe size of the data in the inquiry buffer.
Result: True indicates a match; False indicates a failure.

doInquiry

Abstract: Obtain SCSI Inquiry data from the device.
protected:

virtual IOReturn doInquiry(UInt8 *inqBuf,UInt32 maxLen,UInt32 *actualLen);

This method issues a SCSI Inquiry command to the device, to obtain the result in the supplied buffer. The method first issues an inquiry with a 5-byte length, to obtain the full length of the devices inquiry data. The second Inquiry command is issued to get the full inquiry data (limited to maxLen, of course).

Parameters

NameDescription
inqBufA pointer to the buffer.
maxLenThe maximum number of bytes the buffer can contain.
actualLenA pointer to the returned byte count actually transferred.

doReadCapacity

protected:

virtual IOReturn doReadCapacity(UInt64 *blockSize,UInt64 *maxBlock);

The default implementation of this method issues a standard SCSI Read Capacity command. The block size and maximum valid block are extracted from the returned data in an endian-neutral way.

Parameters

NameDescription
blockSizeA pointer to the returned block size value.
maxBlockA pointer to the returned maximum block number.

executeCdb

public:

virtual IOReturn executeCdb(struct cdbParams *params);

This method is provided to allow developers to issue arbitrary commands to the device (via the Transport Driver). Expected uses might include vendor-specific commands to support device-based password-protection, or for other vendor features.

This method may not be supported by all Transport Drivers. For example, ATA devices do not have a CDB concept; those Transport Drivers will return kIOReturnUnsupported.

Parameters

NameDescription
paramsSee IOHDTypes.h for the layout of this data structure.

genericCompletion

Abstract: Generic IO completion function.
public:

virtual void genericCompletion(struct context *cx);

This method handles completion of a SCSI command. It implements a simple state machine to handle a Unit Attention condition on a command.

This method must be public so we can reach it from the C-language callback "glue" routine. It should not be called from outside this class. *

* If a Unit Attention condition occurs, we set the state to kHandlingUnitAttention and call handleUnitAttention to do whatever is necessary to clear the condition. Eventually, handleUnitAttention resets the state to kDoneHandlingUnitAttention, which will allow the state machine to reissue the original command.

If we are already processing a Unit Attention, then genericCompletion increments a step counter and calls handleUnitAttention. The step counter allows handleUnitAttention to issue multiple SCSI commands to clear the condition. The handleUnitAttention method is called repeatedly, until the state is set to kDoneHandlingUnitAttention.

If this operation is a normal asynchronous read or write (usually started by standardAsyncReadWrite, though this is not required), then a call is made to RWCompletion, followed by deletion of the context structure for the command. RWCompletion is implemented by the subclass of IOBasicSCSI, for example in IOSCSIHDDrive.

Parameters

NameDescription
cxA pointer to the context structure for the command.

getAdditionalDeviceInfoString

Abstract: Return additional informational string for the device.
public:

virtual char * getAdditionalDeviceInfoString(void);

Result: A pointer to a static character string. The default implementation returns "[SCSI]" .

getBlockSize

Abstract: Return the device block size.
protected:

virtual UInt64 getBlockSize(void);

This method obtains the block size from the Read-Capacity data. If RC data is not yet cached, a call is made to doReadCapacity to obtain the data.


getExecuteCDBPowerState

Abstract: Return the required device power level to execute a client CDB.
protected:

virtual UInt32 getExecuteCDBPowerState(void) = 0;


getInquiryPowerState

Abstract: Return the required device power level to issue an Inquiry command.
protected:

virtual UInt32 getInquiryPowerState(void) = 0;


getProductString

Abstract: Return Product Name string for the device.
public:

virtual char * getProductString(void);

Result: A pointer to a static character string, copied from the inquiry data.

getReadCapacityPowerState

Abstract: Return the required device power level to issue a Read Capacity command.
protected:

virtual UInt32 getReadCapacityPowerState(void) = 0;


getReadWritePowerState

Abstract: Return the required device power level to issue a data read or write.
protected:

virtual UInt32 getReadWritePowerState(void) = 0;


getReportWriteProtectionPowerState

Abstract: Return the required device power level to determine media write protection.
protected:

virtual UInt32 getReportWriteProtectionPowerState(void) = 0;


getRevisionString

Abstract: Return Product Revision string for the device.
public:

virtual char * getRevisionString(void);

Result: A pointer to a static character string, copied from the inquiry data.

getVendorString

Abstract: Return Vendor Name string
public:

virtual char * getVendorString(void);

Result: A pointer to a static character string, copied from the inquiry data.

handleUnitAttention

protected:

virtual void handleUnitAttention(struct context *cx);

Override this to perform any special processing required when a Unit-Attention condition is detected. The cx->step value starts at 1 and is incremented as each subsequent command is executed. HandleUnitAttention is then called again duirng the command completion, until cx->state is changed to kDoneHandlingUnitAttention. This repeated calling behavior allows handleUnitAttention to issue several commands to the device to recover from the Unit-Attention condition. Note that since handleUnitAttention is called on the SCSI completion thread, it must not issue blocking operations, but should instead call simpleAsyncIO.

The default implementation merely sets the state to kDoneHandlingUnitAttention, to allow the original command to be reissued.

Parameters

NameDescription
cxPointer to context for the current command.

powerTickle

Abstract: Check for the device power state currently being in the desired state.
protected:

virtual bool powerTickle(UInt32 desiredState) = 0;

A subclass must implement powerTickle, which is called when we desire power to execute a command. PowerTickle may handle generic or a subclass-expanded set of power states. The implementation will usually relay the call to the Power Management subsystem function activityTickle. For a device without power management capability, the implementation should always return True.

Parameters

NameDescription
desiredStateThe desired device power level.
Result: True if power is in the desired state (or better); False if the caller must wait until power is available.

probe

Abstract: Determine if device matches expected type.
public:

virtual IOService * probe(IOService * provider,SInt32 * score);

This method is responsible for matching the device type. It calls doInquiry to issue a SCSI Inquiry command to the device, then calls deviceTypeMatches to ensure that the device type matches the expected type. If the device type matches, then the Vendor, Product, and Revision strings are copied from the inquiry data, and "this" is returned. If the device type does not match, NULL is returned.

The default implementation ignores the score parameter, though that parameter is passed to the superclass probe method.


queueCommand

Abstract: Queue commands awaiting the proper device power level.
protected:

virtual void queueCommand(struct context *cx,bool isSync,UInt32 desiredPower);

This method is called prior to issuing any IO command, so that each command can be enqueued awaiting its desired device power level. After queuing the command, a call is made to dequeueCommands to attempt to dequeue any available command that can be executed (including the one just queued). Putting commands into the queue ensures that the proper sequence is maintained.

Parameters

NameDescription
cxThe context for the command being queued.
isSyncTrue if the command is synchronous; False if the command is asynchronous.
desiredPowerThe device power level needed before the command can execute.

reportBlockSize

Abstract: Report the block size for the device, in bytes.
public:

virtual IOReturn reportBlockSize(UInt64 *blockSize);

This method returns the block size for the media. The default implementation obtains the block size from the SCSI Read Capacity command. Since the result of the Read Capacity is used by this method and reportMaxValidBlock, this method either returns a cached value or calls doReadCapacity to issue the command and cache both values.

Parameters

NameDescription
blockSizePointer to returned block size value.

reportEjectability

Abstract: Report if the media is ejectable under software control.
public:

virtual IOReturn reportEjectability(bool *isEjectable);

This method reports whether the media is ejectable under software control. The default implementation always reports that removable media is ejectable.

This method should only be called if the media is known to be removable.

Parameters

NameDescription
isEjectablePointer to returned result. True indicates the media is ejectable, False indicates the media cannot be ejected under software control.

reportLockability

Abstract: Report if the media is lockable under software control.
public:

virtual IOReturn reportLockability(bool *isLockable);

This method reports whether the media can be locked under software control, to prevent the user from removing the media manually, e.g. by pressing a button on the drive. This method is only called by the generic driver when the media is known to be removable. The default implementation always returns true.

This method should only be called if the media is known to be removable.

Parameters

NameDescription
isLockablePointer to returned result. True indicates the media can be locked in place; False indicates the media cannot be locked by software.

reportMaxReadTransfer

Abstract: Report the maximum allowed byte transfer for read operations.
public:

virtual IOReturn reportMaxReadTransfer(UInt64 blocksize,UInt64 *max);

Some devices impose a maximum data transfer size. Because this limit may be determined by the size of a block-count field in a command, the limit may depend on the block size of the transfer. The default implementation reports blocksize * 65536, which is the maximum number of bytes that can be transferred in a SCSI command with a standard 16-bit block count field.

Parameters

NameDescription
blockSizeThe block size desired for the transfer.
maxPointer to returned result.

reportMaxValidBlock

Abstract: Report the highest valid block for the device.
public:

virtual IOReturn reportMaxValidBlock(UInt64 *maxBlock);

This method reports the maximum allowable block number. The default implementation obtains the block number from the SCSI Read Capacity command. Since the result of the Read Capacity is used by this method and reportBlockSize, this method either returns a cached value or calls doReadCapacity to issue the command and cache both values.

Parameters

NameDescription
maxBlockPointer to returned result

reportMaxWriteTransfer

Abstract: Report the maximum allowed byte transfer for write operations.
public:

virtual IOReturn reportMaxWriteTransfer(UInt64 blocksize,UInt64 *max);

Some devices impose a maximum data transfer size. Because this limit may be determined by the size of a block-count field in a command, the limit may depend on the block size of the transfer. The default implementation reports blocksize * 65536, which is the maximum number of bytes that can be transferred in a SCSI command with a standard 16-bit block count field.

Parameters

NameDescription
blockSizeThe block size desired for the transfer.
maxPointer to returned result.

reportPollRequirements

Abstract: Report if it's necessary to poll for media insertion, and if polling is expensive.
public:

virtual IOReturn reportPollRequirements(bool *pollRequired,bool *pollIsExpensive);

This method reports whether the device must be polled to detect media insertion, and whether a poll is expensive to perform.

The term "expensive" typically implies a device that must be spun-up to detect media, as on a PC floppy. Most devices can detect media inexpensively.

The default implementation of this method always reports an inexpensive poll (pollIsExpensive = false), and that all removable media must be polled.

Parameters

NameDescription
pollRequiredPointer to returned result. True indicates that polling is required; False indicates that polling is not required to detect media.
pollIsExpensivePointer to returned result. True indicates that the polling operation is expensive; False indicates that the polling operation is cheap.

reportRemovability

Abstract: Report whether the media is removable or not.
public:

virtual IOReturn reportRemovability(bool *isRemovable);

This method reports whether the media is removable, but it does not provide detailed information regarding software eject or lock/unlock capability.

The default implementation of this method examines the cached Inquiry data to determine if media is removable. If the RMB bit (0x80 of Inquiry data byte 1) is set, the media is removable. If there is no Inquiry data, the media is reported to be nonremovable.

This method also sets the instance variable _removable.

Parameters

NameDescription
isRemovablePointer to returned result. True indicates that the media is removable; False indicates the media is not removable.

reportWriteProtection

Abstract: Report whether the media is write-protected or not.
public:

virtual IOReturn reportWriteProtection(bool *isWriteProtected);

The default implementation of this method issues a SCSI Mode Sense command to test the WP bit( 0x80 of byte 2 of the Mode Sense Header data). A request is made for Mode Sense Page 1, though any valid page will return a header. If the bit is set, the media is considered write-protected.

Parameters

NameDescription
isWriteProtectedPointer to returned result. True indicates that the media is write-protected (it cannot be written); False indicates that the media is not write-protected (it is permissible to write).

simpleSynchIO

Abstract: Issue a simple synchronous SCSI command.
protected:

virtual IOReturn simpleSynchIO(struct context *cx);

This method issues a single SCSI command and waits for the command to complete. The SCSI command must already be set up in the context structure.

Parameters

NameDescription
cxA pointer to the context structure for the command.

standardAsyncReadWrite

Abstract: Start an asynchronous read or write operation.
protected:

virtual IOReturn standardAsyncReadWrite(IOMemoryDescriptor *buffer, UInt32 block,UInt32 nblks, gdCompletionFunction action, IOService *target,void *param);

This method starts an asynchronous read or write operation. No incoming parameters are validated. The default implementation calls createReadCdb or createWriteCdb, then issues a SCSI command to IOSCSIDevice. If the command is accepted, then the completion will be called at some future time.

Parameters

NameDescription
bufferAn IOMemoryDescriptor describing the data-transfer buffer. The data direction is contained in the IOMemoryDescriptor. Responsiblity for releasing the descriptor rests with the caller.
blockThe starting block number of the data transfer.
nblksThe integral number of blocks to be transferred.
actionThe C function called upon completion of the data transfer.
targetThe C++ class "this" pointer, passed as an argument to "action."
paramThis value is passed as an argument to "action." It is not validated or modified.
Result: The only possible returns from this method are:

kIOReturnSuccess, meaning that the IO was accepted by the transport drivers provider (e.g. IOSCSIDevice), and that the completion function will be called when the IO completes, i.e. target->action(param).

kIOReturnNoMemory, meaning that memory allocation failed.

Other kIOReturn codes from the provider which occurred because the IO was not accepted in that provider's queue. This might indicate a full queue or bad parameter.

standardAsyncReadWriteExecute

Abstract: Issue an asynchronous read/write operation after dequeuing.
protected:

virtual IOReturn standardAsyncReadWriteExecute(struct context *cx);

Parameters

NameDescription
cxA pointer to the context structure for the command.

standardSyncReadWrite

protected:

virtual IOReturn standardSyncReadWrite(IOMemoryDescriptor *buffer,UInt32 block,UInt32 nblks);

Perform a synchronous read or write operation.

Parameters

NameDescription
bufferAn IOMemoryDescriptor describing the data-transfer buffer. The data direction is contained in the IOMemoryDescriptor. Responsiblity for releasing the descriptor rests with the caller.
blockThe starting block number of the data transfer.
nblksThe integral number of blocks to be transferred.

stringFromState

Abstract: Return a string description of a state value.
protected:

virtual char * stringFromState(stateValue state);

Used for debugging.

Parameters

NameDescription
stateThe state to be converted to a string description.

Member Data

_inqBuf

protected:
 UInt8 * _inqBuf; /* the Inquiry data buffer */

 /*!
 * @var _inqBufSize
 * The size of the inquiry data buffer, in bytes.
 */
 UInt32 _inqBufSize; /* size of the buffer */

 /*!
 * @var _inqLen
 * The number of valid bytes of inquiry data.
 */
 UInt32 _inqLen; /* valid bytes in buffer */
 
 /*!
 * @var _vendor
 * The Vendor Name string from the inquiry data, null-terminated.
 */
 char _vendor[9]; /* info from Inquiry data */

 /*!
 * @var _product
 * The Product Name string from the inquiry data, null-terminated.
 */
 char _product[17];

 /*!
 * @var _rev
 * The Product Revision string from the inquiry data, null-terminated.
 */
 char _rev[5];

 /* Since we get both of these items from the same command, we
 * just cache both values if we get either call, so we only
 * have to issue the command once.
 */

 /*!
 * @var _readCapDone
 * True if we have issued a Read-Capacity command to obtain the
 * values for _maxBlock and _blockSize.
 */
 bool _readCapDone;

 /*!
 * @var _removable
 * True if the media is removable; False if the media is fixed.
 */
 bool _removable;

 /*!
 * @var _maxBlock
 * The highest valid block on the media, relative to zero.
 */
 UInt64 _maxBlock;

 /*!
 * @var _blockSize
 * The block size of the media in bytes.
 */
 UInt64 _blockSize;

 /* The queue of pending requests awaiting power: */

 /*!
 * @struct queue
 * @discussion
 * A data structure for a queue.
 * @field head
 * A pointer to the head item.
 * @field tail
 * A pointer to the tail item.
 * @field lock
 * A lock used to protect the queue during changes.
 */
 /*!
 * @var _powerQueue
 * A queue structure containing operations queued awaiting power level.
 */
 struct queue {
 struct context * head;
 struct context * tail;
 IOLock * lock;
 } _powerQueue;
 
};

A pointer to the allocate Inquiry Data buffer.


_provider

protected:
 IOSCSIDevice * _provider;

A pointer to our provider.


completion

public:
  *  @struct  context
  *  @discussion
  *  The  context  structure  contains  all  persistent  information  needed  for  a
  *  synchronous  or  asynchronous  IO  operation.
  *  @field  completion
  *  The  completion  information  for  an  asynchronous  read  or  write  operation.
  *  @field  state
  *  The  current  state  of  the  operation.
  *  @field  step
  *  The  current  step  value,  if  we  are  handling  a  Unit  Attention.
  *  @field  originalContext
  *  A  pointer  to  the  context  for  the  command  that  caused  the  Unit  Attention
  *  condition.
  *  @field  scsireq
  *  A  pointer  to  the  IOSCSIRequest  object.
  *  @field  memory
  *  The  data  buffer  for  the  operation.  A  pointer  to  an  IOMemoryDescriptor.
  *  @field  scsiresult
  *  A  pointer  to  the  IOSCSIResult  object.
  *  @field  desiredPower
  *  The  desired  power  level  for  the  operation  to  execute.
  *  @field  isSync
  *  True  if  synchronous;  False  if  asynchronous.
  *  @field  next
  *  A  pointer  to  a  context  structure,  used  as  a  queue  forward-link.
  *  @field  sync
  *  A  syncer  used  to  block  a  thread  awaiting  a  power  level,  or  for  completion
  *  of  a  synchronous  operation.
  */
  struct  context  {

  /*  Completion  information  for  our  client,  used  only  for  async  operations.
  *  Typically  this  information  will  only  be  used  by  subclasses.
  */

  struct  {
  gdCompletionFunction  action;  /*  function  to  call  */
  IOService  *target;  /*  client  object  ("this")  */
  void  *param;  /*  client's  parameter  */
  }  completion;

Fields

NameDescription
actionThe C function called upon completion of the operation.
targetThe C++ class pointer, passed to tha action function.
paramA value passed to the action function. This value is not touched.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOCommandGate.h

IOCommandGate.h



© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOCommandGate

IOCommandGate



Member Functions

checkForWork

Abstract: Not used, $link IOEventSource::checkForWork().
protected:

virtual bool checkForWork();


commandGate

Abstract: Factory method to create and initialise an IOCommandGate, See $link init.
public:

static IOCommandGate *commandGate(OSObject *owner, Action action = 0);

Result: Returns a pointer to the new command gate if sucessful, 0 otherwise.

init

Abstract: Class initialiser.
public:

virtual bool init(OSObject *owner, Action action = 0);

Initialiser for IOCommandGate operates only on newly 'newed' objects. Shouldn't be used to re-init an existing instance.

Parameters

NameDescription
ownerOwner of this, newly created, instance of the IOCommandGate. This argument will be used as the first parameter in the action callout.
actionPointer to a C function that is called whenever a client of the IOCommandGate calls runCommand. NB Can be a C++ member function but caller must cast the member function to $link IOCommandGate::Action and they will get a compiler warning. Defaults to zero, see $link IOEventSource::setAction.
Result: True if inherited classes initialise successfully.

runAction

Abstract: Single thread a call to an action with the target work-loop.
public:

virtual IOReturn runAction(Action action, void *arg0 = 0, void *arg1 = 0, void *arg2 = 0, void *arg3 = 0);

Client function that causes the given action to be called in a single threaded manner. Beware the work-loop's gate is recursive and command gates can cause direct or indirect re-entrancy. When the executing on a client's thread runCommand will sleep until the work-loop's gate opens for execution of client actions, the action is single threaded against all other work-loop event sources.

Parameters

NameDescription
actionPointer to function to be executed in work-loop context.
arg0Parameter for action of command gate, defaults to 0.
arg1Parameter for action of command gate, defaults to 0.
arg2Parameter for action of command gate, defaults to 0.
arg3Parameter for action of command gate, defaults to 0.
Result: kIOReturnSuccess if successful. kIOReturnBadArgument if action is not defined, kIOReturnNoResources if no action available.

runCommand

Abstract: Single thread a command with the target work-loop.
public:

virtual IOReturn runCommand(void *arg0 = 0, void *arg1 = 0, void *arg2 = 0, void *arg3 = 0);

Client function that causes the current action to be called in a single threaded manner. Beware the work-loop's gate is recursive and command gates can cause direct or indirect re-entrancy. When the executing on a client's thread runCommand will sleep until the work-loop's gate opens for execution of client actions, the action is single threaded against all other work-loop event sources.

Parameters

NameDescription
arg0Parameter for action of command gate, defaults to 0.
arg1Parameter for action of command gate, defaults to 0.
arg2Parameter for action of command gate, defaults to 0.
arg3Parameter for action of command gate, defaults to 0.
Result: kIOReturnSuccess if successful. kIOReturnNotPermitted if this event source is currently disabled, kIOReturnNoResources if no action available.

Member Data

Action

public:typedef IOReturn (*Action)(OSObject *owner, void *arg0, void *arg1, void *arg2, void *arg3);

Type and arguments of callout C function that is used when a runCommand is executed by a client. Cast to this type when you want a C++ member function to be used. Note the arg1 - arg3 parameters are straight pass through from the runCommand to the action callout.

Parameters

NameDescription
ownerTarget of the function, can be used as a refcon. The owner is set during initialisation of the IOCommandGate instance. Note if a C++ function was specified this parameter is implicitly the first paramter in the target member function's parameter list.
arg0Argument to action from run operation.
arg1Argument to action from run operation.
arg2Argument to action from run operation.
arg3Argument to action from run operation.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IODeviceMemory.h

IODeviceMemory.h



© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IODeviceMemory

IODeviceMemory



Member Functions

arrayFromList

Abstract: Constructs an OSArray of IODeviceMemory instances, each describing one physical range, and a tag value.
public:

static OSArray * arrayFromList( InitElement list[], IOItemCount count );

This method creates IODeviceMemory instances for each physical range passed in a IODeviceMemory::InitElement array. Each element consists of a physical address, length and tag value for the IODeviceMemory. The instances are returned as a created OSArray.

Parameters

NameDescription
listAn array of IODeviceMemory::InitElement structures.
countThe number of elements in the list.
Result: A created OSArray of IODeviceMemory objects, to be released by the caller, or zero on failure.

withRange

Abstract: Constructs an IODeviceMemory instance, describing one physical range.
public:

static IODeviceMemory * withRange( IOPhysicalAddress start, IOPhysicalLength length );

This method creates IODeviceMemory instance for one physical range passed as a physical address and length. It just calls IOMemoryDescriptor::withPhysicalAddress.

Parameters

NameDescription
addressThe physical address of the first byte in the memory.
withLengthThe length of memory.
Result: The created IODeviceMemory on success, to be released by the caller, or zero on failure.

withRange

Abstract: Constructs an IODeviceMemory instance, describing a subset of an existing IODeviceMemory range.
public:

static IODeviceMemory * withSubRange( IODeviceMemory * of, IOPhysicalAddress offset, IOPhysicalLength length );

This method creates IODeviceMemory instance for a subset of an existing IODeviceMemory range, passed as a physical address offset and length. It just calls IOMemoryDescriptor::withSubRange.

Parameters

NameDescription
ofThe parent IODeviceMemory of which a subrange is to be used for the new descriptor, which will be retained by the subrange IODeviceMemory.
offsetA byte offset into the parent's memory.
lengthThe length of the subrange.
Result: The created IODeviceMemory on success, to be released by the caller, or zero on failure.

Member Data

InitElement

public:
  struct  InitElement  {
  IOPhysicalAddress  start;
  IOPhysicalLength  length;
  IOOptionBits  tag;
  };

Fields

NameDescription
startFirst physical address in the range.
lengthLength of the range.
tag32-bit value not interpreted by IODeviceMemory or IOMemoryDescriptor, for use by the bus family.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IODrive.h

IODrive.h



#defines

kIODriveStatistics

kIODriveStatistics is a property of IODrive objects. It is an OSDictionary.

#define kIODriveStatistics "Statistics"

The kIODirectionStatistics property contains a table of statistics describing drive operations. All the different statistics are grouped under this table.


kIODriveStatisticsBytesRead

kIODriveStatisticsBytesRead is one of the statistic entries listed under the kIODriveStatistics property of IODrive objects. It is an OSNumber.

#define kIODriveStatisticsBytesRead "Bytes (Read)"

The kIODriveStatisticsBytesRead property describes the number of bytes read since the drive object was instantiated.


kIODriveStatisticsBytesWritten

kIODriveStatisticsBytesWritten is one of the statistic entries listed under the kIODriveStatistics property of IODrive objects. It is an OSNumber.

#define kIODriveStatisticsBytesWritten "Bytes (Write)"

The kIODriveStatisticsBytesWritten property describes the number of bytes written since the drive object was instantiated.


kIODriveStatisticsLatentReadTime

kIODriveStatisticsLatentReadTime is one of the statistic entries listed under the kIODriveStatistics property of IODrive objects. It is an OSNumber.

#define kIODriveStatisticsLatentReadTime "Latency Time (Read)"

The kIODriveStatisticsLatentReadTime property describes the number of nanoseconds of latency during reads since the drive object was instantiated.


kIODriveStatisticsLatentWriteTime

kIODriveStatisticsLatentWriteTime is one of the statistic entries listed under the kIODriveStatistics property of IODrive objects. It is an OSNumber.

#define kIODriveStatisticsLatentWriteTime "Latency Time (Write)"

The kIODriveStatisticsLatentWriteTime property describes the number of nanoseconds of latency during writes since the drive object was instantiated.


kIODriveStatisticsReadErrors

kIODriveStatisticsReadErrors is one of the statistic entries listed under the kIODriveStatistics property of IODrive objects. It is an OSNumber.

#define kIODriveStatisticsReadErrors "Errors (Read)"

The kIODriveStatisticsReadErrors property describes the number of read errors encountered since the drive object was instantiated.


kIODriveStatisticsReadRetries

kIODriveStatisticsReadRetries is one of the statistic entries listed under the kIODriveStatistics property of IODrive objects. It is an OSNumber.

#define kIODriveStatisticsReadRetries "Retries (Read)"

The kIODriveStatisticsReadRetries property describes the number of read retries required since the drive object was instantiated.


kIODriveStatisticsReads

kIODriveStatisticsReads is one of the statistic entries listed under the kIODriveStatistics property of IODrive objects. It is an OSNumber.

#define kIODriveStatisticsReads "Operations (Read)"

The kIODriveStatisticsReads property describes the number of read operations processed since the drive object was instantiated.


kIODriveStatisticsTotalReadTime

kIODriveStatisticsTotalReadTime is one of the statistic entries listed under the kIODriveStatistics property of IODrive objects. It is an OSNumber.

#define kIODriveStatisticsTotalReadTime "Total Time (Read)"

The kIODriveStatisticsTotalReadTime property describes the number of nanoseconds spent performing reads since the drive object was instantiated.


kIODriveStatisticsTotalWriteTime

kIODriveStatisticsTotalWriteTime is one of the statistic entries listed under the kIODriveStatistics property of IODrive objects. It is an OSNumber.

#define kIODriveStatisticsTotalWriteTime "Total Time (Write)"

The kIODriveStatisticsTotalWriteTime property describes the number of nanoseconds spent performing writes since the drive object was instantiated.


kIODriveStatisticsWriteErrors

kIODriveStatisticsWriteErrors is one of the statistic entries listed under the kIODriveStatistics property of IODrive objects. It is an OSNumber.

#define kIODriveStatisticsWriteErrors "Errors (Write)"

The kIODriveStatisticsWriteErrors property describes the number of write errors encountered since the drive object was instantiated.


kIODriveStatisticsWriteRetries

kIODriveStatisticsWriteRetries is one of the statistic entries listed under the kIODriveStatistics property of IODrive objects. It is an OSNumber.

#define kIODriveStatisticsWriteRetries "Retries (Write)"

The kIODriveStatisticsWriteRetries property describes the number of write retries required since the drive object was instantiated.


kIODriveStatisticsWrites

kIODriveStatisticsWrites is one of the statistic entries listed under the kIODriveStatistics property of IODrive objects. It is an OSNumber.

#define kIODriveStatisticsWrites "Operations (Write)"

The kIODriveStatisticsWrites property describes the number of write operations processed since the drive object was instantiated.


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IODrive

IODrive



Member Functions

addToBytesTransferred

protected:

virtual void addToBytesTransferred(UInt64 bytesTransferred, UInt64 totalTime, UInt64 latentTime, bool isWrite);

Update the total number of bytes transferred, the total transfer time, and the total latency time for this drive -- used for statistics. * This method's implementation is not typically overidden.

Parameters

NameDescription
bytesTransferredNumber of bytes transferred in this operation.
totalTimeNanoseconds spent performing this operation.
latentTimeNanoseconds of latency during this operation.
isWriteIndicates whether this operation was a write, otherwise is was a read.

deblockRequest

protected:

virtual void deblockRequest(UInt64 byteStart, IOMemoryDescriptor * buffer, IOStorageCompletion completion);

The deblockRequest method checks to see if the incoming request rests on the media's block boundaries, and if not, deblocks it. Deblocking involves breaking up the request into sub-requests that rest on block boundaries, and performing the appropriate unaligned byte copies from the scratch buffer into into the client's request buffer. * This method is part of a sequence of methods that are called for each read or write request. The first is deblockRequest, which aligns the request at the media's block boundaries; the second is prepareRequest, which prepares the memory involved in the transfer; and the third is executeRequest, which implements the actual transfer from the drive. * This method's implementation is not typically overidden.

Parameters

NameDescription
byteStartStarting byte offset for the data transfer.
bufferBuffer for the data transfer. The size of the buffer implies the size of the data transfer.
completionCompletion routine to call once the data transfer is complete.

ejectMedia

public:

virtual IOReturn ejectMedia() = 0;

Eject the media from the drive. The drive object is responsible for tearing down the child storage objects it created before proceeding with the eject. If the teardown fails, an error should be returned.

Result: An IOReturn code.

executeRequest

protected:

virtual void executeRequest(UInt64 byteStart, IOMemoryDescriptor * buffer, IOStorageCompletion completion) = 0;

Execute the specified storage request. The request is guaranteed to be block-aligned, and to have a memory buffer that is wired, mapped, and is constrained according to the controller's and drive's limits. * This method is part of a sequence of methods that are called for each read or write request. The first is deblockRequest, which aligns the request at the media's block boundaries; the second is prepareRequest, which prepares the buffer involved in the transfer; and the third is executeRequest, which implements the actual transfer from the drive. * When implementing this abstract method, it is important to remember that the buffer must be retained while the asynchronous operation is being processed, as per regular I/O Kit object-passing semantics.

Parameters

NameDescription
byteStartStarting byte offset for the data transfer.
bufferBuffer for the data transfer. The size of the buffer implies the size of the data transfer.
completionCompletion routine to call once the data transfer is complete.

formatMedia

public:

virtual IOReturn formatMedia(UInt64 byteCapacity) = 0;

Format the media in the drive with the specified byte capacity. The drive object is responsible for tearing down the child storage objects and recreating them, if applicable.

Parameters

NameDescription
byteCapacityNumber of bytes to format media to.
Result: An IOReturn code.

getFormatCapacities

public:

virtual UInt32 getFormatCapacities(UInt64 * capacities, UInt32 capacitiesMaxCount) const = 0;

Ask the drive to report the feasible formatting capacities for the inserted media (in bytes). This routine fills the caller's buffer, up to the maximum count specified if the real number of capacities would overflow the buffer. The return value indicates the actual number of capacities copied to the buffer. * If the capacities buffer is not supplied or if the maximum count is zero, the routine returns the proposed count of capacities instead.

Parameters

NameDescription
capacitiesBuffer that will receive the UInt64 capacity values.
capacitiesMaxCountMaximum number of capacity values that can be held in the buffer.
Result: Actual number of capacity values copied to the buffer, or if no buffer is given, the total number of capacity values available.

getMediaBlockSize

protected:

virtual inline UInt64 getMediaBlockSize() const = 0;

Ask the drive about the media's actual block size.

Result: Natural block size, in bytes.

getMediaState

public:

virtual IOMediaState getMediaState() const = 0;

Ask the drive about the media's current state.

Result: An IOMediaState value.

getStatistic

public:

virtual UInt64 getStatistic(Statistics statistic) const;

Ask the drive to report one of its operating statistics.

Parameters

NameDescription
statisticStatistic index (an IODrive::Statistics index).
Result: Statistic value.

getStatistics

public:

virtual UInt32 getStatistics(UInt64 * statistics, UInt32 statisticsMaxCount) const;

Ask the drive to report its operating statistics. The statistics are described by the IODrive::Statistics indices. This routine fills the caller's buffer, up to the maximum count specified if the real number of statistics would overflow the buffer. The return value indicates the actual number of statistics copied to the buffer. * If the statistics buffer is not supplied or if the maximum count is zero, the routine returns the proposed count of statistics instead.

Parameters

NameDescription
statisticsBuffer that will receive the UInt64 statistic values.
statisticsMaxCountMaximum number of statistic values that can be held in the buffer.
Result: Actual number of statistic values copied to the buffer, or if no buffer is given, the total number of statistic values available.

handleClose

protected:

virtual void handleClose(IOService * client, IOOptionBits options);

The handleClose method closes the client's access to this object. * This implementation replaces the IOService definition of handleIsOpen().

Parameters

NameDescription
clientClient requesting the close.
optionsOptions for the close. Set to zero.

handleIsOpen

protected:

virtual bool handleIsOpen(const IOService * client) const;

The handleIsOpen method determines whether the specified client, or any client if none is specificed, presently has an open on this object. * This implementation replaces the IOService definition of handleIsOpen().

Parameters

NameDescription
clientClient to check the open state of. Set to zero to check the open state of all clients.
Result: Returns true if the client was (or clients were) open, false otherwise.

handleOpen

protected:

virtual bool handleOpen(IOService * client, IOOptionBits options, void * access);

The handleOpen method grants or denies permission to access this object to an interested client. The argument is an IOStorageAccess value that specifies the level of access desired -- reader or reader-writer. * This method can be invoked to upgrade or downgrade the access level for an existing client as well. The previous access level will prevail for upgrades that fail, of course. A downgrade should never fail. If the new access level should be the same as the old for a given client, this method will do nothing and return success. In all cases, one, singular close-per-client is expected for all opens-per-client received. * This implementation replaces the IOService definition of handleIsOpen().

Parameters

NameDescription
clientClient requesting the open.
optionsOptions for the open. Set to zero.
accessAccess level for the open. Set to kAccessReader or kAccessReaderWriter.
Result: Returns true if the open was successful, false otherwise.

handleStart

protected:

virtual bool handleStart(IOService * provider) = 0;

Prepare the drive for operation. * This is where a media object needs to be created for fixed media, and optionally for removable media. For removable media, the poller will issue handlePoll() once a second, so the creation of the media object could be delayed until then if you wish. * Note that this method is called from the superclass' start() routine; if this method returns successfully, it should be prepared to accept any of IODrive's abstract methods.

Parameters

NameDescription
providerThis object's provider.
Result: Returns true on success, false otherwise.

handleStop

protected:

virtual void handleStop(IOService * provider) = 0;

Stop the drive. * This is where the driver should clean up its state in preparation for removal from the system. * Note that this method is called from the superclass' stop() routine.

Parameters

NameDescription
providerThis object's provider.

incrementErrors

protected:

virtual void incrementErrors(bool isWrite);

Update the total error count -- used for statistics. * This method's implementation is not typically overidden.

Parameters

NameDescription
isWriteIndicates whether this operation was a write, otherwise is was a read.

incrementRetries

protected:

virtual void incrementRetries(bool isWrite);

Update the total retry count -- used for statistics. * This method's implementation is not typically overidden.

Parameters

NameDescription
isWriteIndicates whether this operation was a write, otherwise is was a read.

isMediaEjectable

public:

virtual bool isMediaEjectable() const = 0;

Ask the drive whether it contains ejectable media.

Result: Returns true if the media is ejectable, false otherwise.

isMediaPollExpensive

public:

virtual bool isMediaPollExpensive() const = 0;

Ask the drive whether it a pollMedia would be an expensive operation, that is, one that requires the drive to spin up or delay for a while.

Result: Returns true if polling the media is expensive, false otherwise.

isMediaPollRequired

public:

virtual bool isMediaPollRequired() const = 0;

Ask the drive whether it requires polling, which is typically required for drives with ejectable media without the ability to asynchronously detect the arrival or departure of the media.

Result: Returns true if polling the media is required, false otherwise.

lockMedia

public:

virtual IOReturn lockMedia(bool lock) = 0;

Lock or unlock the ejectable media in the drive, that is, prevent it from manual ejection or allow its manual ejection.

Parameters

NameDescription
lockPass true to lock the media, otherwise pass false to unlock the media.
Result: An IOReturn code.

pollMedia

public:

virtual IOReturn pollMedia() = 0;

Poll for the presence of media in the drive. The drive object is responsible for tearing down the child storage objects it created should the media have been removed since the last poll, and vice- versa, creating the child storage objects should new media have arrived since the last poll.

Result: An IOReturn code.

prepareRequest

protected:

virtual void prepareRequest(UInt64 byteStart, IOMemoryDescriptor * buffer, IOStorageCompletion completion);

The prepareRequest method prepares the memory involved in the transfer. The memory will be wired down, physically mapped, and broken up based on the controller's and drive's constraints. * This method is part of a sequence of methods that are called for each read or write request. The first is deblockRequest, which aligns the request at the media's block boundaries; the second is prepareRequest, which prepares the buffer involved in the transfer; and the third is executeRequest, which implements the actual transfer from the drive. * This method's implementation is not typically overidden.

Parameters

NameDescription
byteStartStarting byte offset for the data transfer.
bufferBuffer for the data transfer. The size of the buffer implies the size of the data transfer.
completionCompletion routine to call once the data transfer is complete.

read

public:

virtual void read(IOService * client, UInt64 byteStart, IOMemoryDescriptor * buffer, IOStorageCompletion completion);

The read method is the receiving end for all read requests from the storage framework, that is, the child storage objects of this drive. * This method kicks off a sequence of methods which are called for each read or write request. The first is deblockRequest, which aligns the request at the media's block boundaries; the second is prepareRequest, which prepares the buffer involved in the transfer; and the third is executeRequest, which implements the actual transfer from the drive. * This method's implementation is not typically overidden.

Parameters

NameDescription
clientClient requesting the read.
byteStartStarting byte offset for the data transfer.
bufferBuffer for the data transfer. The size of the buffer implies the size of the data transfer.
completionCompletion routine to call once the data transfer is complete.

write

public:

virtual void write(IOService * client, UInt64 byteStart, IOMemoryDescriptor * buffer, IOStorageCompletion completion);

The write method is the receiving end for all write requests from the storage framework, that is, the child storage objects of this drive. * This method kicks off a sequence of methods which are called for each read or write request. The first is deblockRequest, which aligns the request at the media's block boundaries; the second is prepareRequest, which prepares the buffer involved in the transfer; and the third is executeRequest, which implements the actual transfer from the drive. * This method's implementation is not typically overidden.

Parameters

NameDescription
clientClient requesting the write.
byteStartStarting byte offset for the data transfer.
bufferBuffer for the data transfer. The size of the buffer implies the size of the data transfer.
completionCompletion routine to call once the data transfer is complete.

Member Data

IOMediaState

public:
  enum  IOMediaState
  {
  kMediaOffline,
  kMediaOnline,
  kMediaBusy
  };

The different states that getMediaState() can report.

Constants

NameDescription
kMediaOfflineMedia is not available.
kMediaOnlineMedia is available and ready for operations.
kMediaBusyMedia is available, but not ready for operations.

Statistics

public:
  enum  Statistics
  {
  kStatisticsReads,
  kStatisticsSingleBlockReads,
  kStatisticsBytesRead,
  kStatisticsTotalReadTime,
  kStatisticsLatentReadTime,
  kStatisticsReadRetries,
  kStatisticsReadErrors,

  kStatisticsWrites,
  kStatisticsSingleBlockWrites,
  kStatisticsBytesWritten,
  kStatisticsTotalWriteTime,
  kStatisticsLatentWriteTime,
  kStatisticsWriteRetries,
  kStatisticsWriteErrors
  };

Indices for the different statistics that getStatistics() can report.

Constants

NameDescription
kStatisticsReadsNumber of read operations thus far.
kStatisticsSingleBlockReadsNumber of read operations for a single block thus far.
kStatisticsBytesReadNumber of bytes read thus far.
kStatisticsTotalReadTimeNanoseconds spent performing reads thus far.
kStatisticsLatentReadTimeNanoseconds of latency during reads thus far.
kStatisticsReadRetriesNumber of read retries thus far.
kStatisticsReadErrorsNumber of read errors thus far.
kStatisticsWritesNumber of write operations thus far.
kStatisticsSingleBlockWritesNumber of write operations for a single block thus far.
kStatisticsBytesWrittenNumber of bytes written thus far.
kStatisticsTotalWriteTimeNanoseconds spent performing writes thus far.
kStatisticsLatentWriteTimeNanoseconds of latency during writes thus far.
kStatisticsWriteRetriesNumber of write retries thus far.
kStatisticsWriteErrorsNumber of write errors thus far.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOEthernetController.h

IOEthernetController.h



© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOEthernetController

IOEthernetController



Member Functions

allocateNetworkInterface

protected:

virtual IONetworkInterface * allocateNetworkInterface();

Allocates and returns a new IOEthernetInterface instance. The controller class from each family must implement this method inherited from IONetworkController to return the corresponding interface object when attachNetworkInterface() is called. Subclasses of IOEthernetController (Ethernet drivers) would have little need to override this implementation.

Result: A newly allocated and initialized IONetworkInterface instance.

enablePacketFilters

protected:

virtual IOReturn enablePacketFilters(UInt32 filters, UInt32 * activeFiltersP);

Called by interface object to change the set of packet filters that should be enabled by the controller. The implementation in IOEthernetController will trap any changes to multicast or promiscuous filters and convert the changes into a filter mode for setMulticastMode() and setPromiscuousMode() methods. This is done strictly as a convenience for drivers, which may choose to override this method to handle the filter changes directly. Unicast and Broadcast filters are assumed to be always enabled, and no driver intervention is required.

Parameters

NameDescription
filtersEach bit set indicates a particular filter that should be enabled. Filter bits that are not turned on must be disabled.
activeFiltersPUpdated by this method to reflect the real set of active filters. Ideally, it should be the same as the set specified by the first argument.
Result: kIOReturnSuccess on success, otherwise an error code is returned.

free

protected:

virtual void free();

Frees the IOEthernetController instance.


getFamilyFeatureSet

public:

virtual UInt32 getFamilyFeatureSet() const;

Get the Ethernet feature sets supported by the controller. Ethernet controller drivers may override this method and return a mask of supported feature sets.

Result: IOEthernetController will always return 0.

getHardwareAddress

protected:

virtual IOReturn getHardwareAddress(enet_addr_t * addr) = 0;

Get the controller's hardware address. Ethernet drivers must implement this method, by reading the address from hardware and writing it to the buffer provided.

Parameters

NameDescription
addrPointer to a enet_addr_t where the hardware address should be written to.
Result: Drivers should return kIOReturnSuccess upon success, or an error code otherwise.

getPacketFilters

protected:

virtual IOReturn getPacketFilters(UInt32 * filtersP);

Returns all the packet filters supported by the controller. See IONetworkController for the list of packet filters. This method will perform a bitwise OR of kIOPacketFilterUnicast, kIOPacketFilterBroadcast, kIOPacketFilterMulticast, kIOPacketFilterPromiscuous, and write the result using the provided pointer. Drivers that support a different set of filters should override this method.

Parameters

NameDescription
filtersPPointer to an integer that shall be updated by this method to contain the set of supported filters.
Result: kIOReturnSuccess. Drivers that override this method must return an appropriate return code.

init

public:

virtual bool init(OSDictionary * properties);

Initialize an IOEthernetController instance.

Parameters

NameDescription
propertiesA property dictionary.
Result: true if initialized successfully, false otherwise.

publishCapabilities

protected:

virtual bool publishCapabilities();

Publish Ethernet specific properties to the property table. For instance, getHardwareAddress() is called to fetch the hardware address. This method is called by the superclass and should not be called by drivers.

Result: true if all required properties were discovered and published without errors, false otherwise.

requestHandler

public:

virtual IOReturn requestHandler(OSObject * sender, UInt32 request, void * arg0 = 0, void * arg1 = 0, void * arg2 = 0, void * arg3 = 0);

Overrides the requestHandler() inherited from IONetworkController to handle Ethernet specific requests sent from our clients. Requests not handled are passed to the superclass.

Parameters

NameDescription
senderThe sender of the request.
requestThe request type.
arg0Request argument.
arg1Request argument.
arg2Request argument.
arg3Request argument.
Result: kIOReturnSuccess if the request was handled successfully, otherwise a error code is returned.

setHardwareAddress

protected:

virtual IOReturn setHardwareAddress(const enet_addr_t * addr);

Called when a client wishes to change the station address used by the controller's hardware filter. Implementation of this method is optional.

Parameters

NameDescription
addrPointer to a enet_addr_t containing the new Ethernet address.
Result: kIOReturnUnsupported. Drivers that implement this method must return an appropriate return code.

setMulticastList

protected:

virtual IOReturn setMulticastList(enet_addr_t * addrs, UInt count);

Called when the list of multicast addresses in the interface object attached to the controller is changed. Drivers that supports multicasting should override this method and update the hardware filter using the provided address list. A count of the number of addresses in the list is also provided. This count will be zero when the list becomes empty. Perfect multicast filtering is preferred if supported by the hardware. If the number of multicast addresses in the list exceed the limit imposed by the hardware, or if perfect filtering is not supported, then ideally the hardware should be programmed to perform imperfect filtering, perhaps through a hash table built by the driver. This method may be called only if getPacketFilters() reports that kIOPacketFilterMulticast is supported.

Parameters

NameDescription
addrsPointer to a list of multicast addresses.
countThe number of multicast addresses in the list. May be zero if the list becomes empty.
Result: kIOReturnUnsupported. Drivers that override this method must return an appropriate return code.

setMulticastMode

protected:

virtual IOReturn setMulticastMode(IOEnetMulticastMode mode);

Called by enablePacketFilters() when the controller's multicast filter mode should be changed. See IOEnetMulticastMode for the list of defined modes.

Parameters

NameDescription
modeThe multicast filter should be programmed to the mode specified.
Result: kIOReturnUnsupported. Drivers that override this method must return an appropriate return code.

setPromiscuousMode

protected:

virtual IOReturn setPromiscuousMode(IOEnetPromiscuousMode mode);

Called by enablePacketFilters() when the controller's promiscuous filter mode should be changed. See IOEnetPromiscuousMode for the list of defined modes.

Parameters

NameDescription
modeThe promiscuous filter should be programmed to the mode specified.
Result: kIOReturnUnsupported. Drivers that override this method must return an appropriate return code.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOEthernetInterface.h

IOEthernetInterface.h



© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOEthernetInterface

IOEthernetInterface



Member Functions

controllerDidOpen

protected:

virtual bool controllerDidOpen(IONetworkController * controller);

This method will be called by our superclass after a network controller has accepted an open from this interface. IOEthernetInterface uses this method to qualify the controller and to cache certain controller properties, such as its hardware address, and its set of supported packet filters.

Parameters

NameDescription
controllerThe controller object.
Result: true if the controller was accepted, false otherwise (which will cause the controller to be closed).

controllerWillClose

protected:

virtual void controllerWillClose(IONetworkController * controller);

When the last close from our client is received, the interface object will close its controller. But before the controller is closed, this method will be called by our superclass to perform any necessary cleanup. IOEthernetInterface will ensure that the controller is disabled before it is closed.

Parameters

NameDescription
controllerThe currently opened controller object.

free

protected:

virtual void free();

Frees the IOEthernetInterface instance. The memory allocated for the arpcom structure is released.


getIfnet

protected:

virtual struct ifnet * getIfnet() const;

This method returns a pointer to an ifnet structure maintained by the family specific interface. IOEthernetInterface allocates an arpcom structure during initialization, and returns a pointer to this structure when this method is called.

Result: Pointer to an ifnet structure.

getNamePrefix

public:

virtual const char * getNamePrefix() const;

The name of the interface advertised to the network layer is generated by concatenating the string returned by this method, and an integer unit number assigned by an external entity.

Result: A pointer to a constant string "en". Thus the network layer will see Ethernet interfaces named as en0, en1, etc.

init

public:

virtual bool init(OSDictionary * properties = 0);

Initialize an IOEthernetInterface instance.

Parameters

NameDescription
propertiesA property dictionary.
Result: true if initialized successfully, false otherwise.

initIfnet

protected:

virtual bool initIfnet(struct ifnet * ifp);

Initialize the ifnet structure. The argument specified is a pointer to an ifnet structure obtained through getIfnet(). IOEthernetInterface will initialize this structure in a manner that is appropriate for Ethernet interfaces, then call super::initIfnet() to allow the superclass to perform family independent initialization.

Parameters

NameDescription
ifpPointer to the ifnet structure to be initialized.
Result: true if successful, false otherwise.

performCommand

protected:

virtual SInt performCommand(IONetworkController * controller, UInt32 cmd, void * arg0, void * arg1);

The handler for ioctl commands sent from the network stack. Commands not handled by this method are passed to our superclass. The ioctl commands handled are SIOCSIFADDR, SIOCSIFFLAGS, SIOCADDMULTI, and SIOCDELMULTI.

Parameters

NameDescription
controllerOur controller object.
cmdThe command code.
arg0Command argument.
arg1Command argument.
Result: An error code defined in errno.h (BSD).

publishParameters

public:

virtual void publishParameters(OSDictionary * dict) const;

Add Ethernet specific IONetworkParameter objects to the dictionary provided.

Parameters

NameDescription
dictA dictionary containing IONetworkParameter objects.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOEthernetStats.h

IOEthernetStats.h



Typedefs

IODot3CollEntry

typedef  struct  {
  UInt32  collFrequencies[16];
}  IODot3CollEntry;

Collision statistics structure.

Fields

NameDescription
collFrequenciesdot3StatsCollFrequencies.

IODot3RxExtraEntry

typedef  struct  {
  UInt32  overruns;
  UInt32  watchdogTimeouts;
  UInt32  frameTooShorts;
  UInt32  collisionErrors;
  UInt32  phyErrors;
  UInt32  timeouts;
  UInt32  interrupts;
  UInt32  resets;
  UInt32  resourceErrors;
}  IODot3RxExtraEntry;

Extra receiver statistics not defined by RFC1650.

Fields

NameDescription
overrunsreceiver overruns.
watchdogTimeoutswatchdog timer expirations.
frameTooShortsrunt frames.
collisionErrorsframes damages by late collision.
phyErrorsPHY receive errors.
timeoutsreceiver timeouts.
interruptsreceiver interrupts.
resetsreceiver resets.
resourceErrorsreceiver resource shortages.

IODot3RxExtraEntry

typedef  struct  {
  UInt32  underruns;
  UInt32  jabbers;
  UInt32  phyErrors;
  UInt32  timeouts;
  UInt32  interrupts;
  UInt32  resets;
  UInt32  resourceErrors;
}  IODot3TxExtraEntry;

Extra transmitter statistics not defined by RFC1650.

Fields

NameDescription
underrunstransmit underruns.
jabbersjabber events.
phyErrorsPHY transmit errors.
timeoutstransmitter timeouts.
interruptstransmitter interrupts.
resetstransmitter resets.
resourceErrorstransmitter resource shortages.

IODot3StatsEntry

typedef  struct  {
  UInt32  alignmentErrors;
  UInt32  fcsErrors;
  UInt32  singleCollisionFrames;
  UInt32  multipleCollisionFrames;
  UInt32  sqeTestErrors;
  UInt32  deferredTransmissions;
  UInt32  lateCollisions;
  UInt32  excessiveCollisions;
  UInt32  internalMacTransmitErrors;
  UInt32  carrierSenseErrors;
  UInt32  frameTooLongs;
  UInt32  internalMacReceiveErrors;
  UInt32  etherChipSet;
  UInt32  missedFrames;
}  IODot3StatsEntry;

Ethernet MIB statistics structure.

Fields

NameDescription
alignmentErrorsdot3StatsAlignmentErrors.
fcsErrorsdot3StatsFCSErrors.
singleCollisionFramesdot3StatsSingleCollisionFrames.
multipleCollisionFramesdot3StatsMultipleCollisionFrames.
sqeTestErrorsdot3StatsSQETestErrors.
deferredTransmissionsdot3StatsDeferredTransmissions.
lateCollisionsdot3StatsLateCollisions.
excessiveCollisionsdot3StatsExcessiveCollisions.
internalMacTransmitErrorsdot3StatsInternalMacTransmitErrors.
carrierSenseErrorsdot3StatsCarrierSenseErrors.
frameTooLongsdot3StatsFrameTooLongs.
internalMacReceiveErrorsdot3StatsInternalMacReceiveErrors.
etherChipSetdot3StatsEtherChipSet.
missedFramesdot3StatsMissedFrames (not in RFC1650).

IOEthernetStats

typedef  struct  {
  IODot3StatsEntry  dot3StatsEntry;
  IODot3CollEntry  dot3CollEntry;
  IODot3RxExtraEntry  dot3RxExtraEntry;
  IODot3TxExtraEntry  dot3TxExtraEntry;  
}  IOEthernetStats;

Aggregate Ethernet statistics structure.

Fields

NameDescription
dot3StatsEntryIODot3StatsEntry statistics group.
dot3CollEntryIODot3CollEntry statistics group.
dot3RxExtraEntryIODot3RxExtraEntry statistics group.
dot3TxExtraEntryIODot3TxExtraEntry statistics group.

#defines

kIOEthernetStatsKey

#define kIOEthernetStatsKey "IOEthernetStatsKey"

Defines the name of an IONetworkParameter that contains an IOEthernetStats.


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOEventSource.h

IOEventSource.h



© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOEventSource

IOEventSource



Member Functions

checkForWork

Abstract: Pure Virtual member function used by IOWorkLoop for work scheduling.
protected:

virtual bool checkForWork() = 0;

This function will be called to request a subclass to check it's internal state for any work to do and then to call out the owner/action.

Result: Return true if this function needs to be called again before all its outstanding events have been processed.

disable

Abstract: Disable event source.
public:

virtual void disable();

A subclass implementation is expected to respect the enabled state when checkForWork is called.


enable

Abstract: Enable event source.
public:

virtual void enable();

A subclass implementation is expected to respect the enabled state when checkForWork is called. Calling this function will cause the work-loop to be signalled so that a checkForWork is performed.


getAction

Abstract: Get'ter for $link action variable.
public:

virtual IOEventSource::Action getAction() const;

Result: value of action.

getNext

Abstract: Get'ter for $link eventChainNext variable.
protected:

virtual IOEventSource *getNext() const;

Result: value of eventChainNext.

getWorkLoop

Abstract: Get'ter for $link workLoop variable.
public:

virtual IOWorkLoop *getWorkLoop() const;

Result: value of workLoop.

init

Abstract: Primary initialiser for the IOEventSource class.
protected:

virtual bool init(OSObject *owner, IOEventSource::Action action = 0);

Parameters

NameDescription
ownerOwner of this instance of an event source. Used as the first parameter of the action callout. Owner will generally be an OSObject it doesn't have to be as no member functions will be called directly in it. It can just be a refcon for a client routine.
actionPointer to C call out function. Action is a pointer to a C function that gets called when this event source has outstanding work. It will usually be called by the checkForWork member function. The first parameter of the action call out will always be the owner, this allows C++ member functions to be used as actions. Defaults to 0.
Result: true if the inherited classes and this instance initialise successfully.

isEnabled

Abstract: Get'ter for $link enable variable.
public:

virtual bool isEnabled() const;

Result: true if enabled.

onThread

Abstract: Convenience function for workLoop->onThread.
public:

virtual bool onThread() const;

Result: true if called on the work-loop thread.

setAction

Abstract: Set'ter for $link action variable.
public:

virtual void setAction(IOEventSource::Action action);

Parameters

NameDescription
actionPointer to a C function of type IOEventSource::Action.

setNext

Abstract: Set'ter for $link eventChainNext variable.
protected:

virtual void setNext(IOEventSource *next);

Parameters

NameDescription
nextPointer to another IOEventSource instance.

setWorkLoop

Abstract: Set'ter for $link workLoop variable.
protected:

virtual void setWorkLoop(IOWorkLoop *workLoop);

Parameters

NameDescription
workLoopTarget work-loop of this event source instance. A subclass of IOWorkLoop that at least reacts to signalWorkAvailable() and onThread functions.

Member Data

Action

public:typedef void (*Action)(OSObject *owner, ...);

Placeholder type for C++ function overloading discrimination. As the all event sources require an action and it has to be stored somewhere and be of some type, this is that type.

Parameters

NameDescription
ownerTarget of the function, can be used as a refcon. The owner is set during initialisation. Note if a C++ function was specified this parameter is implicitly the first paramter in the target member function's parameter list.

action

protected:
 Action action;

The action method called when an event has been delivered


enabled

protected:
 bool enabled;

Is this event source enabled to deliver requests to the work-loop.


eventChainNext

protected:
 IOEventSource *eventChainNext;

The next event source in the event chain. nil at end of chain.


owner

protected:
 OSObject *owner;

The owner object called when an event has been delivered.


refcon

protected:
 void *refcon;

What ever the client wants to do, see $link setRefcon.


workLoop

protected:
 IOWorkLoop *workLoop;

What is the work-loop for this event source.


#defines

IOEventSourceAction

#define IOEventSourceAction IOEventSource::Action

Backward compatibilty define for the old non-class scoped type definition. See $link IOEventSource::Action


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOFilterInterruptEventSource.h

IOFilterInterruptEventSource.h



© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOFilterInterruptEventSource

IOFilterInterruptEventSource



Member Functions

disableInterruptOccurred

Abstract: Override $link IOInterruptEventSource::disableInterruptOccurred to make a filter callout.
public:

virtual void disableInterruptOccurred(void *self, IOService *prov, int ind);


filterInterruptEventSource

Abstract: Factor method to create and initialise an IOFilterInterruptEventSource. See $link init.
public:

static IOFilterInterruptEventSource * filterInterruptEventSource(OSObject *owner, IOInterruptEventSource::Action action, Filter filter, IOService *provider, int intIndex = 0);

Parameters

NameDescription
ownerOwner/client of this event source.
action'C' Function to call when something happens.
filter'C' Function to call when interrupt occurs.
providerService that provides interrupts.
intIndexDefaults to 0.
Result: a new event source if succesful, 0 otherwise.

getFilterAction

Abstract: Get'ter for filterAction variable.
public:

virtual Filter getFilterAction() const;

Result: value of filterAction.

init

Abstract: Primary initialiser for the IOFilterInterruptEventSource class.
public:

virtual bool init(OSObject *owner, IOInterruptEventSource::Action action, Filter filter, IOService *provider, int intIndex = 0);

Parameters

NameDescription
ownerOwner/client of this event source.
action'C' Function to call when something happens.
filter'C' Function to call in primary interrupt context.
providerService that provides interrupts.
intIndexInterrupt source within provider. Defaults to 0.
Result: true if the inherited classes and this instance initialise successfully.

normalInterruptOccurred

Abstract: Override $link IOInterruptEventSource::normalInterruptOccured to make a filter callout.
public:

virtual void normalInterruptOccurred(void *self, IOService *prov, int ind);


Member Data

Filter

public:typedef bool (*Filter)(OSObject *, IOFilterInterruptEventSource *);

C Function pointer to a routine to call when an interrupt occurs.

Parameters

NameDescription
ownerPointer to the owning/client instance.
senderWhere is the interrupt comming from.

filterAction

protected:
 Filter filterAction;

Filter callout


#defines

IOFilterInterruptAction

#define IOFilterInterruptAction IOFilterInterruptEventSource::Filter

Backward compatibilty define for the old non-class scoped type definition. See $link IOFilterInterruptSource::Filter


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOHDDrive.h

IOHDDrive.h



© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOHDDrive

IOHDDrive



Member Functions

RWCompletion

Abstract: Handle a C callback for an IO completion.
public:

virtual void RWCompletion(struct IOHDDrive::context *cx);

This method must be public so we can reach it from the C-language callback "glue" routine. It should not be called from outside this class.


acceptNewMedia

Abstract: React to new media insertion.
protected:

virtual IOReturn acceptNewMedia(void);

This method logs the media block size and block count, then calls instantiateMediaObject to get a media object instantiated. The media object is then attached above us and registered.

This method can be overridden to control what happens when new media is inserted. The default implementation deals with one IOMedia object.


allocateContext

Abstract: Allocate a context structure for use with the current async operation.
protected:

virtual struct IOHDDrive::context *allocateContext(void);

A context structure is only needed for asynchronous read or write operations, to contain information used to complete the request with the client.


checkForMedia

Abstract: Check if media has newly arrived or disappeared.
protected:

virtual IOReturn checkForMedia(void);

This method does most of the work in polling for media, first calling the Transport Driver's reportMediaState method. If reportMediaState reports no change in the media state, kIOReturnSuccess is returned. If media has just become available, calls are made to recordMediaParameters and acceptNewMedia. If media has just gone away, a call is made to decommissionMedia, with the forcible parameter set to true. The forcible teardown is needed to enforce the disappearance of media, regardless of interested clients.


constrainByteCount

Abstract: Constrain the byte count for this IO to device limits.
public:

virtual UInt64 constrainByteCount(UInt64 requestedCount,bool isWrite);

This function should be called prior to each read or write operation, so that the driver can constrain the requested byte count, as necessary, to meet current device limits. Such limits could be imposed by the device depending on operating modes, media types, or transport prototol (e.g. ATA, SCSI).

At present, this method is not used.

Parameters

NameDescription
requestedCountThe requested byte count for the next read or write operation.
isWriteTrue if the operation will be a write; False if the operation will be a read.

constructMediaProperties

Abstract: Create properties related to the media.
protected:

virtual OSDictionary *constructMediaProperties(void);

This function creates a set of properties to express media properties.

This function is presently called by recordMediaParameters, but it does nothing.


decommissionMedia

Abstract: Decommission an existing piece of media that has gone away.
protected:

virtual IOReturn decommissionMedia(bool forcible);

This method wraps a call to tearDown, to tear down the stack and the IOMedia object for the media. If "forcible" is true, the media object will be forgotten, and initMediaStates will be called. A forcible decommission would occur when an unrecoverable error happens during teardown (e.g. perhaps a client is still open), but we must still forget about the media.

Parameters

NameDescription
forcibleTrue to force forgetting of the media object even if tearDown reports that there was an active client.

deleteContext

Abstract: Delete a context structure.
protected:

virtual void deleteContext(struct IOHDDrive::context *cx);

This method also issues a "release" for the IO buffer, if any.

Parameters

NameDescription
cxA pointer to the context structure to be deleted.

ejectMedia

Abstract: Eject the media.
public:

virtual IOReturn ejectMedia(void);


executeRequest

Abstract: Start an asynchronous read or write operation.
protected:

virtual void executeRequest(UInt64 byteStart, IOMemoryDescriptor * buffer, IOStorageCompletion completion);

This method is the main entry to start an asynchronous read or write operation. All IO operations must be block aligned and a multiple of the device block size. After some validations, the request is passed to the Transport Driver's doAsyncReadWrite method. The completion from the operation is set to call RWCompletion, by way of the gc_glue C function.

Parameters

NameDescription
byteStartThe starting byte offset of the data transfer.
bufferThe data buffer for the operation. A pointer to an IOMemoryDescriptor.
completionThe completion information for an asynchronous read or write operation.

formatMedia

Abstract: Format the media to the specified byte capacity.
public:

virtual IOReturn formatMedia(UInt64 byteCapacity);

Parameters

NameDescription
byteCapacityThe requested final byte capacity for the formatted media.

getDeviceTypeName

Abstract: Return the desired device name.
protected:

virtual const char * getDeviceTypeName(void);

This method returns a string, used to compare the kDeviceTypeProperty of our provider. This method is called from probe.

The default implementation of this method returns kDeviceTypeHardDisk.


getFormatCapacities

Abstract: Return the allowable formatting byte capacities.
public:

virtual UInt32 getFormatCapacities(UInt64 * capacities, UInt32 capacitiesMaxCount) const;

This function returns the supported byte capacities for the device.

Parameters

NameDescription
capacitiesPointer for returning the list of capacities.
capacitiesMaxCountThe number of capacity values returned in "capacities."

getMediaBlockSize

Abstract: Return the block size for the device, in bytes.
public:

virtual UInt64 getMediaBlockSize(void) const;


getMediaState

Abstract: Return the state of media in the device.
public:

virtual IODrive::IOMediaState getMediaState(void) const;


handleStart

Abstract: Handle startup functionality after superclass is ready.
public:

virtual bool handleStart(IOService * provider);

This function obtains device description strings (e.g. Vendor name), prints a message describing the device, and then obtains all removable-media information (if the device is removable.) Finally, a check for media is performed.

Parameters

NameDescription
providerA pointer to our provider.

handleStop

Abstract: Handle clean up functionality before driver is unloaded.
public:

virtual void handleStop(IOService * provider);

If the media is writable, this method issues a Synchronize Cache operation. Then the media is ejected.

Parameters

NameDescription
providerA pointer to our provider.

initMediaStates

Abstract: Initialize media-related instance variables.
protected:

virtual void initMediaStates(void);

Called when media is not present, this method marks the drive state as not having media present, not spun up, and write-enabled.


instantiateDesiredMediaObject

Abstract: Create an IOMedia object for media.
protected:

virtual IOMedia * instantiateDesiredMediaObject(void);

This method creates the exact type of IOMedia object desired. It is called by instantiateMediaObject. A subclass may override this one-line method to change the type of media object actually instantiated.


instantiateMediaObject

Abstract: Create an IOMedia object for media.
protected:

virtual IOReturn instantiateMediaObject(IOMedia **media,UInt64 base,UInt64 byteSize,UInt32 blockSize, bool isWholeMedia,char *mediaName);

This method creates an IOMedia object from the supplied parameters. It is a convenience method to wrap the handful of steps to do the job.

Parameters

NameDescription
mediaA pointer to the created IOMedia object.
baseByte number of beginning of active data area of the media. Usually zero.
byteSizeSize of the data area of the media, in bytes.
blockSizeBlock size of the media, in bytes.
isWholeMediaTrue indicates the IOMedia object represents the entire media; False indicates the IOMedia object represents a portion of the entire media.
mediaNameName of the IOMedia object.

isMediaEjectable

Abstract: Report whether the media is removable or not.
public:

virtual bool isMediaEjectable(void) const;

Result: True indicates the media can be ejected by software; False indicates it cannot.

isMediaPollExpensive

Abstract: Report whether polling for media is expensive.
public:

virtual bool isMediaPollExpensive(void) const;

Result: True indicates the media poll is expensive; False indicates polling is cheap.

isMediaPollRequired

Abstract: Report whether device must be polled to determine media state.
public:

virtual bool isMediaPollRequired(void) const;

Result: True indicates that polling is required; False indicates that no polling is needed.

lockMedia

Abstract: Lock or unlock the media in the device.
public:

virtual IOReturn lockMedia(bool lock);

This method may be used to lock the media in the device, thus preventing the user from removing the media manually.

This method only makes sense if it is known that the device supports locking.

Parameters

NameDescription
lockTrue indicates the media should be locked in the device; False indicates the media should be unlocked.

pollMedia

Abstract: Poll for media insertion/removal.
public:

virtual IOReturn pollMedia(void);

This method is called periodically by the superclass, if isMediaPollRequired has previously reported True. We are responsible for reacting to new media insertion, or to existing media being removed.


probe

Abstract: Probe for proper client Transport Driver.
public:

virtual IOService * probe(IOService * provider,SInt32 * score);

This method first verifies that our provider is of class IOHDDriveNub, then checks that the provider's property "kDeviceTypeProperty" matches what we expect. Failure of either test causes a return of NULL.


recordAdditionalMediaParameters

Abstract: Record any additional media parameters as necessary.
protected:

virtual IOReturn recordAdditionalMediaParameters(void);

This method is called by recordMediaParameters() when media is detected. The default implementation does nothing and returns kIOReturnSuccess. A subclass may override this method to record additional parameters.


recordMediaParameters

Abstract: Obtain media-related parameters on media insertion.
protected:

virtual IOReturn recordMediaParameters(void);

This method obtains media-related parameters via calls to the Transport Driver's reportBlockSize, reportMaxValidBlock, reportMaxReadTransfer, reportMaxWriteTransfer, and reportWriteProtection methods.


rejectMedia

Abstract: Reject new media.
protected:

virtual void rejectMedia(void); /* default ejects */

This method will be called if validateNewMedia returns False (thus rejecting the new media. A vendor may choose to override this method to control behavior when media is rejected.

The default implementation simply calls ejectMedia.


setProvider

Abstract: Store the provider pointer.
protected:

virtual bool setProvider(IOService * provider);

This method uses IODynamicCast to verify that the provider is of the proper class type. The default implementation checks for a nub of type IOHDDriveNub.

This method would be overridden for a new generic driver subclass. For example, a generic CD driver would need to accept a different provider class (e.g. IOCDDriveNub instead of IOHDDriveNub).

Parameters

NameDescription
providerA pointer to our provider.

showStats

Abstract: Print debugging statistics.
protected:

virtual bool showStats(void);

This method prints debugging statistics maintained by the class.

Present statistics include counts of up and down calls.

Result: True indicates statistics should be printed; False indicates no printing desired.

tearDown

Abstract: Tear down the stack above this object when media goes away.
protected:

virtual IOReturn tearDown(IOService *media);

This method calls media->terminate, and if that succeeds, issues a release on the media object, followed by a call to initMediaStates.

Parameters

NameDescription
mediaA pointer to the IOMedia object from which to initiate teardown.

validateNewMedia

Abstract: Verify that new media is acceptable.
protected:

virtual bool validateNewMedia(void);

This method will be called whenever new media is detected. Return true to accept the media, or false to reject it (andcall rejectMedia). Vendors might override this method to handle password-protection for new media.

The default implementation always returns True, indicating media is accepted.


Member Data

_ejectable

protected:
 bool _ejectable; /* software-ejectable */

 /*!
 * @var _lockable
 * True if the media can be locked in the device under software control.
 */
 bool _lockable; /* software lockable in drive */
 /*!
 * @var _pollIsRequired
 * True if we must poll to detect media insertion or removal.
 */
 bool _pollIsRequired;
 /*!
 * @var _pollIsExpensive
 * True if polling is expensive; False if not.
 */
 bool _pollIsExpensive;

 /* Async IO statistics, usually only useful for debugging. These counters show
 * outstanding IO operations and completions.
 */

 /*!
 * @struct stats
 * A data structure to contain debugging statistics. Each field is a count.
 * @field clientReceived
 * Requests received from our client.
 * @field providerSent
 * Requests sent to our provider.
 * @field providerReject
 * Client requests we rejected without sending to our provider.
 * @field providerCompletionsRcvd
 * Completion calls that have arrived from our provider. 
 * @field clientCompletionsSent
 * Completion calls that have been made to our client.
 * @field clientCompletionsDone
 * Completion calls to the client that have come back to us.
 * This count MUST match clientCompletionsSent!
 */
 /*!
 * @var stats
 * The stats structure.
 */
 struct stats { /* executeRequest & completion counts */
 int clientReceived; /* requests received from client */
 int providerSent; /* requests sent to provider */
 int providerReject; /* provider requests rejected */
 int providerCompletionsRcvd; /* completions received from provider */
 int clientCompletionsSent; /* completions sent to client */
 int clientCompletionsDone; /* client completions made it back to us */
 } _stats;
 
 /* Media info and states: */

 /*!
 * @var _mediaObject
 * A pointer to the media object we have instantiated (if any).
 */
 IOMedia * _mediaObject;
 /*!
 * @var _mediaPresent
 * True if media is present in the device; False if not.
 */
 bool _mediaPresent; /* media is present and ready */
 /*!
 * @var _writeProtected
 * True if the media is write-protected; False if not.
 */
 bool _writeProtected;
 
 /*!
 * @var _mediaStateLock
 * A lock used to protect during media checks.
 */
 IOLock * _mediaStateLock;

 /*!
 * @var _mediaBlockSize
 * The block size of the media, in bytes.
 */
 UInt64 _mediaBlockSize;
 /*!
 * @var _maxBlockNumber
 * The maximum allowable block number for the media, zero-based.
 */
 UInt64 _maxBlockNumber;

 /*!
 * @var _maxReadByteTransfer
 * The maximum byte transfer allowed for read operations.
 */
 UInt64 _maxReadByteTransfer;

 /*!
 * @var _maxWriteByteTransfer
 * The maximum byte transfer allowed for write operations.
 */
 UInt64 _maxWriteByteTransfer;
};

True if the media is ejectable under software control.


_provider

protected:
 IOHDDriveNub * _provider;

A pointer to our provider.


_removable

protected:
 bool _removable;

True if the media is removable; False if it is fixed (not removable).


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOHDDriveNub.h

IOHDDriveNub.h



#defines

kDeviceTypeHardDisk A character string used for nub matching.


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOHDDriveNub

IOHDDriveNub



Member Functions

doAsyncReadWrite

Abstract: Start an asynchronous read or write operation.
public:

virtual IOReturn doAsyncReadWrite(IOMemoryDescriptor *buffer, UInt32 block,UInt32 nblks, gdCompletionFunction action, IOService *target,void *param) = 0;

Parameters

NameDescription
bufferAn IOMemoryDescriptor describing the data-transfer buffer. The data direction is contained in the IOMemoryDescriptor. Responsiblity for releasing the descriptor rests with the caller.
blockThe starting block number of the data transfer.
nblksThe integral number of blocks to be transferred.
actionThe C function called upon completion of the data transfer.
targetThe C++ class "this" pointer, passed as an argument to "action."
paramThis value is passed as an argument to "action." It is not validated or modified.

doEjectMedia

Abstract: Eject the media.
public:

virtual IOReturn doEjectMedia(void) = 0;


doFormatMedia

Abstract: Format the media to the specified byte capacity.
public:

virtual IOReturn doFormatMedia(UInt64 byteCapacity) = 0;

The specified byte capacity must be one supported by the device. Supported capacities can be obtained by calling doGetFormatCapacities.

Parameters

NameDescription
byteCapacityThe byte capacity to which the device is to be formatted, if possible.

doGetFormatCapacities

Abstract: Return the allowable formatting byte capacities.
public:

virtual UInt32 doGetFormatCapacities(UInt64 * capacities, UInt32 capacitiesMaxCount) const = 0;

This function returns the supported byte capacities for the device.

Parameters

NameDescription
capacitiesPointer for returning the list of capacities.
capacitiesMaxCountThe number of capacity values returned in "capacities."

doLockUnlockMedia

Abstract: Lock or unlock the (removable) media in the drive.
public:

virtual IOReturn doLockUnlockMedia(bool doLock) = 0;

This method should only be called if the media is known to be removable.

Parameters

NameDescription
doLockTrue to lock the media, False to unlock.

doSyncReadWrite

Abstract: Perform a synchronous read or write operation.
public:

virtual IOReturn doSyncReadWrite(IOMemoryDescriptor *buffer, UInt32 block,UInt32 nblks) = 0;

Parameters

NameDescription
bufferAn IOMemoryDescriptor describing the data-transfer buffer. The data direction is contained in the IOMemoryDescriptor. Responsiblity for releasing the descriptor rests with the caller.
blockThe starting block number of the data transfer.
nblksThe integral number of blocks to be transferred.

doSynchronizeCache

Abstract: Force data blocks in the drive's buffer to be flushed to the media.
public:

virtual IOReturn doSynchronizeCache(void) = 0;

This method should only be called if the media is writable.


executeCdb

Abstract: Issue the client's cdb as a pass-through.
public:

virtual IOReturn executeCdb(struct cdbParams *params) = 0;

This method is provided to allow developers to issue arbitrary commands to the device (via the Transport Driver). Expected uses would include vendor-specific commands to effect password-protection, or for other vendor features.

This method may not be supported by all Transport Drivers. For example, ATA devices do not have a CDB concept; those Transport Drivers will return kIOReturnUnsupported.

Parameters

NameDescription
paramsSee IOHDTypes.h for the layout of this data structure.

getAdditionalDeviceInfoString

Abstract: Return additional informational string for the device.
public:

virtual char * getAdditionalDeviceInfoString(void) = 0;

Result: A pointer to a static character string.

getProductString

Abstract: Return Product Name string for the device.
public:

virtual char * getProductString(void) = 0;

Result: A pointer to a static character string.

getRevisionString

Abstract: Return Product Revision string for the device.
public:

virtual char * getRevisionString(void) = 0;

Result: A pointer to a static character string.

getVendorString

Abstract: Return Vendor Name string for the device.
public:

virtual char * getVendorString(void) = 0;

Result: A pointer to a static character string.

init

public:

virtual bool init(OSDictionary * properties);

This function is overridden so that IOHDDriveNub can set a property, used by IOHDDrive for matching. Since the concrete subclass of IOHDDriveNub can be of any class type, the property is used for matching.

This function is usually not overridden by developers.


reportBlockSize

Abstract: Report the block size for the device, in bytes.
public:

virtual IOReturn reportBlockSize(UInt64 *blockSize) = 0;

Parameters

NameDescription
blockSizePointer to returned block size value.

reportEjectability

Abstract: Report if the media is ejectable under software control.
public:

virtual IOReturn reportEjectability(bool *isEjectable) = 0;

This method should only be called if the media is known to be removable.

Parameters

NameDescription
isEjectablePointer to returned result. True indicates the media is ejectable, False indicates the media cannot be ejected under software control.

reportLockability

Abstract: Report if the media is lockable under software control.
public:

virtual IOReturn reportLockability(bool *isLockable) = 0;

This method should only be called if the media is known to be removable.

Parameters

NameDescription
isLockablePointer to returned result. True indicates the media can be locked in place; False indicates the media cannot be locked by software.

reportMaxReadTransfer

Abstract: Report the maximum allowed byte transfer for read operations.
public:

virtual IOReturn reportMaxReadTransfer(UInt64 blockSize,UInt64 *max) = 0;

Some devices impose a maximum data transfer size. Because this limit may be determined by the size of a block-count field in a command, the limit may depend on the block size of the transfer.

Parameters

NameDescription
blockSizeThe block size desired for the transfer.
maxPointer to returned result.

reportMaxValidBlock

Abstract: Report the highest valid block for the device.
public:

virtual IOReturn reportMaxValidBlock(UInt64 *maxBlock) = 0;

Parameters

NameDescription
maxBlockPointer to returned result

reportMaxWriteTransfer

Abstract: Report the maximum allowed byte transfer for write operations.
public:

virtual IOReturn reportMaxWriteTransfer(UInt64 blockSize,UInt64 *max) = 0;

Some devices impose a maximum data transfer size. Because this limit may be determined by the size of a block-count field in a command, the limit may depend on the block size of the transfer.

Parameters

NameDescription
blockSizeThe block size desired for the transfer.
maxPointer to returned result.

reportMediaState

Abstract: Report the device's media state.
public:

virtual IOReturn reportMediaState(bool *mediaPresent,bool *changedState) = 0;

This method reports whether we have media in the drive or not, and whether the state has changed from the previously reported state.

A result of kIOReturnSuccess is always returned if the test for media is successful, regardless of media presence. The mediaPresent result should be used to determine whether media is present or not. A return other than kIOReturnSuccess indicates that the Transport Driver was unable to interrogate the device. In this error case, the outputs mediaState and changedState will *not* be stored.

Parameters

NameDescription
mediaPresentPointer to returned media state. True indicates media is present in the device; False indicates no media is present.
changedStatePointer to returned result. True indicates a change of state since prior calls, False indicates that the state has not changed.

reportPollRequirements

Abstract: Report if it's necessary to poll for media insertion, and if polling is expensive.
public:

virtual IOReturn reportPollRequirements(bool *pollRequired, bool *pollIsExpensive) = 0;

This method reports whether the device must be polled to detect media insertion, and whether a poll is expensive to perform.

The term "expensive" typically implies a device that must be spun-up to detect media, as on a PC floppy. Most devices can detect media inexpensively.

Parameters

NameDescription
pollRequiredPointer to returned result. True indicates that polling is required; False indicates that polling is not required to detect media.
pollIsExpensivePointer to returned result. True indicates that the polling operation is expensive; False indicates that the polling operation is cheap.

reportRemovability

Abstract: Report whether the media is removable or not.
public:

virtual IOReturn reportRemovability(bool *isRemovable) = 0;

This method reports whether the media is removable, but it does not provide detailed information regarding software eject or lock/unlock capability.

Parameters

NameDescription
isRemovablePointer to returned result. True indicates that the media is removable; False indicates the media is not removable.

reportWriteProtection

Abstract: Report whether the media is write-protected or not.
public:

virtual IOReturn reportWriteProtection(bool *isWriteProtected) = 0;

Parameters

NameDescription
isWriteProtectedPointer to returned result. True indicates that the media is write-protected (it cannot be written); False indicates that the media is not write-protected (it is permissible to write).

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOHDTypes.h

IOHDTypes.h



Typedefs

gdCompletionFunction

typedef void (*gdCompletionFunction)( 
            IOService	*target,
            void	*param,
            UInt64	actualByteCount,
            IOReturn	result);

Type and arguments of callout C function that is used to complete an asynchronous IO operation.

Parameters

NameDescription
targetThe target C function to be called.
paramA parameter passed to the target C function. It is not validated or changed.
actualByteCountThe actual byte count transferred in the operation.
resultThe kIOReturn value from the operation

Structs

cdbParams

struct  cdbParams  {
  UInt32  cdbLength;
  UInt8  cdb[16];
  UInt32  senseLength;
  UInt32  actualSenseLength;
  IOMemoryDescriptor  *  senseBuffer;
  UInt32  timeoutSeconds;
  UInt32  dataLength;
  UInt32  actualDataLength;
  IOMemoryDescriptor  *  dataBuffer;
  UInt8  status;
};

Data provided by a client to an executeCDB operation.

Fields

NameDescription
cdbLengthThe length of the command bytes (cdb), in bytes.
cdbThe actual command bytes to be sent to the device. These are not checked by the driver.
senseLengthThe requested maximum sense length, in bytes.
actualSenseLengthThe actual number of sense bytes transferred. If the driver does not support autosense, this field will always return zero.
senseBufferThe buffer for the sense data. This buffer must have already been prepared for IO by the caller. The buffer must contain the data direction.
timeoutSecondsThe timeout for the command, in seconds.
dataLengthThe requested number of data bytes to transfer with the command, or zero if no data is to be transferred.
actualDataLengthThe actual number of data bytes transferred.
dataBufferThe buffer for the data. This buffer must have already been prepared for IO by the caller. The buffer must contain the data direction.
statusThe status reported by the device at command completion. The contents of thisfield will depend on the type of transport (e.g. SCSI, ATAPI, etc). Some drivers may not support the return of status information and will zero this field.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOHIDDescriptorParser.h

IOHIDDescriptorParser.h



Functions

HIDCloseReportDescriptor

Abstract: Disposes of the memory the parser allocated for the HIDOpenReportDescriptor function.
extern OSStatus HIDCloseReportDescriptor(HIDPreparsedDataRef preparsedDataRef);

Parameters

NameDescription
hidReportDescriptorContains a pointer to the actual HID report descriptor from the USB device's firmware
preparsedDataRefPreparsed data reference for the report that is returned by the HIDOpenReportDescriptor function. After making a call to the HIDCloseReportDescriptor function, the preparsedDataRef is invalid and should not be used.
Result: OSStatus Returns an error code if an error was encountered or noErr on success.

HIDGetButtonCaps

Abstract: Returns the button capabilities structures for a HID device based on the given preparsed data.
extern OSStatus HIDGetButtonCaps(HIDReportType reportType,
 HIDButtonCapsPtr buttonCaps,
 UInt32 * buttonCapsSize,
 HIDPreparsedDataRef preparsedDataRef);

Parameters

NameDescription
reportTypeSpecifies the type of report for which to retrieve the scaled value. This parameter must be one of the following: kHIDInputReport, kHIDOutputReport, or kHIDFeatureReport
buttonCapsPoints to a caller-allocated buffer that will contain, on return, an array of HIDButtonCaps structures. The structures contain information for all buttons that meet the search criteria
buttonCapsSizeContains the size of the buttonCaps array passed in to the function and is set to the number of elements actually placed in the array after the call completes.
preparsedDataRefPreparsed data reference for the report that is retuned by the HIDOpenReportDescriptor function
Result: OSStatus Returns an error code if an error was encountered or noErr on success.

HIDGetButtons

Abstract: The HIDGetButtons function takes a report from a HID device and gets the current state of the buttons in that report.
extern OSStatus HIDGetButtons(HIDReportType reportType,
 UInt32 collection,
 HIDUsageAndPagePtr usageList,
 UInt32 * usageListSize,
 HIDPreparsedDataRef preparsedDataRef,
 void * report,
 ByteCount reportLength);

Parameters

NameDescription
reportTypeSpecifies the type of report, provided in the report parameter, from which to retrieve the buttons. This parameter must be one of the following: kHIDInputReport, kHIDOutputReport or kHIDFeatureReport
collectionOptionally specifies the link collection identifier used to retrieve only specific button states. If this value is non-zero, only the buttons that are part of the given collection are returned.
usageListOn return, points to a caller-allocated buffer that contains the usages of all the buttons that are pressed.
usageListSizeIs the size, in array elements, of the buffer provided in the usageList parameter. On return, this parameter contains the number of button states that were set by this routine. If the error kHIDBufferToSmallErr was returned, this parameter contains the number of array elements required to hold all button data requested. The maximum number of buttons that can ever be returned for a given type of report can be obtained by calling the HIDMaxUsageListLength function.
preparsedDataRefPreparsed data reference for the report that is retuned by the HIDOpenReportDescriptor function
reportPoints to the caller-allocated buffer that contains the device report data.
reportLengthSpecifies the length, in bytes, of the report data provided in the report parameter.
Result: OSStatus Returns an error code if an error was encountered or noErr on success.

HIDGetButtonsOnPage

Abstract: Retrieves the button stat information for buttons on a specified usage page.
extern OSStatus HIDGetButtonsOnPage(HIDReportType reportType,
 HIDUsage usagePage,
 UInt32 collection,
 HIDUsage * usageList,
 UInt32 * usageListSize,
 HIDPreparsedDataRef preparsedDataRef,
 void * report,
 ByteCount reportLength);

Parameters

NameDescription
reportTypeSpecifies the type of report, provided in the report parameter, from which to retrieve the buttons. This parameter must be one of the following: kHIDInputReport, kHIDOutputReport or kHIDFeatureReport.
usagePageSpecifies the usage page of the buttons for which to retrieve the current state.
collectionOptionally specifies the link collection identifier used to retrieve only specific button states. If this value is non-zero, only the buttons that are part of the given collection are returned.
usageListOn return, points to a caller-allocated buffer that contains the usages of all the buttons that are perssed and belong to the usage page specified in the usagePage parameter.
usageListSizeIs the size, in array elements, of the buffer provided in the usageList parameter. On return, this parameter contains the number of button states that were set by this routine. If the error kHIDBufferTooSmallErr was returned, this parameter contains the number of array elements required to hold all button data requested. The maximum number of buttons that can ever be returned for a given type of report can be obtained by calling the HIDMaxUsageListLength function.
preparsedDataRefPreparsed data reference for the report that is retuned by the HIDOpenReportDescriptor function
reportPoints to the caller-allocated buffer that contains the device report data
reportLengthSpecifies the size, in bytes, of the report data provided in the report parameter
Result: OSStatus Returns an error code if an error was encountered or noErr on success.

HIDGetCaps

Abstract: Returns the capabilities of a HID device based on the given preparsed data.
extern OSStatus HIDGetCaps(HIDPreparsedDataRef preparsedDataRef,
 HIDCapsPtr capabilities);

Parameters

NameDescription
preparsedDataRefPreparsed data reference for the report that is retuned by the HIDOpenReportDescriptor function
capabilitiesPoints to a caller allocated buffer, that upon return contains the parsed capability information for this HID device.
Result: OSStatus Returns an error code if an error was encountered or noErr on success.

HIDGetCollectionNodes

Abstract: Returns an array of HIDCollectionNode structures that describe the relationships and layout of the link collections within this top level collection.
extern OSStatus HIDGetCollectionNodes(HIDCollectionNodePtr collectionNodes,
 UInt32 * collectionNodesSize,
 HIDPreparsedDataRef preparsedDataRef);

The length of the buffer required, in array elements, for an entire collection node array is found in the HIDCaps structure member numberCollectionNodes. You obtain the HIDCaps information by calling the HIDGetCaps function. For information on the relationships of link collections described by the data returned from this routine, see the descripton of the HIDCollectionNode structure.

Parameters

NameDescription
collectionNodesPoints to a caller-allocated array of HIDCollectionNode structures in which this routine returns an entry for each collection within the top level collection. A collection is a group of corresponding HID descriptors containing input, output, and feature items that have some common relationship to one another. For example, a pointer collection contains items for x and y position data, and button data.
collectionNodesSizeOn input, specifies the length in array elements of the buffer provided at collectionNodes. On output, this parameter is set to the number of entries in the collectionNodes array that were initialized.
preparsedDataRefPreparsed data reference for the report that is retuned by the HIDOpenReportDescriptor function
Result: OSStatus Returns an error code if an error was encountered or noErr on success.

HIDGetScaledUsageValue

Abstract: The HIDGetScaledUsageValue function returns the capabilities for all buttons for a given top level collection.
extern OSStatus HIDGetScaledUsageValue(HIDReportType reportType,
 HIDUsage usagePage,
 UInt32 collection,
 HIDUsage usage,
 SInt32 * usageValue,
 HIDPreparsedDataRef preparsedDataRef,
 void * report,
 ByteCount reportLength);

Clients who which to obtain all capabilities for a usage that contains multiple data items for a single usage that corresponds to a HID byte array, must call the HIDGetUsageValueArray function.

Parameters

NameDescription
reportTypeSpecifies the type of report for which to retrieve the scaled value. This parameter must be one of the following: kHIDInputReport, kHIDOutputReport, or kHIDFeatureReport.
usagePageSpecifies the usage page of the value to be retrieved.
collectionOptionally specifies the link collection identifier of the value to be retrieved.
usageSpecifies the usage of the scaled value to be retrieved.
usageValuePoints to a variable, that on return from this routine holds the scaled value retrieved from the device report.
preparsedDataRefPreparsed data reference for the report that is retuned by the HIDOpenReportDescriptor function
reportPoints to the caller-allocated buffer that contains the device report data
reportLengthSpecifies the length, in bytes, of the report data provided at report
Result: OSStatus Returns an error code if an error was encountered or noErr on success.

HIDGetSpecificButtonCaps

Abstract: Retrieves the capabilities for all buttons in a specific type of report that meet the search criteria.
extern OSStatus HIDGetSpecificButtonCaps(HIDReportType reportType,
 HIDUsage usagePage,
 UInt32 collection,
 HIDUsage usage,
 HIDButtonCapsPtr buttonCaps,
 UInt32 * buttonCapsSize,
 HIDPreparsedDataRef preparsedDataRef);

The HIDGetSpecificButtonCaps function retrieves capability data for buttons that meet a given search criteria, as opposed to the HIDGetButtonCaps function which returns the capability data for all buttons on the device. Calling this routine specifying zero for usagePage, usage and collection is equivalent to calling the HIDGetButtonCaps function.

Parameters

NameDescription
reportTypeSpecifies the type of report for which to retrieve the button capabilities. This parameter must be one of the following: kHIDInputReport, kHIDOutputReport, or kHIDFeatureReport.
usagePageSpecifies a usage page identifier to use as a search criteria. If this parameter is non-zero, then only buttons that specify this usage page will be retrieved.
collectionSpecifies a link collection identifier to use as a search criteria. If this parameter is non-zero, then only buttons that are part of the specified link collection are retrieved.
usageSpecifies a usage identifier to use as a search criteria. If this parameter is non-zero, then only buttons that match the value specified are retrieved.
buttonCapsPoints to a caller-allocated buffer that will contain, on return, an array of HIDButtonCaps structures. The structures contain information for all buttons that meet the search criteria.
buttonCapsLengthOn input, specifies the length, in array elements, of the buffer provided in the buttonCaps parameter. On output, this parameter is set to the actual number of elements that were returned by the function call, in the buffer provided in the buttonCaps parameter, if the routine completed without error. The correct length necessary to retrieve the button capabilities can be found in the capability data returned for the device by the HIDGetCaps function.
preparsedDataRefPreparsed data reference for the report that is retuned by the HIDOpenReportDescriptor function
Result: OSStatus Returns an error code if an error was encountered or noErr on success.

HIDGetSpecificValueCaps

Abstract: Retrieves the capabilities for all values in a specific type of report that meet the search criteria.
extern OSStatus HIDGetSpecificValueCaps(HIDReportType reportType,
 HIDUsage usagePage,
 UInt32 collection,
 HIDUsage usage,
 HIDValueCapsPtr valueCaps,
 UInt32 * valueCapsSize,
 HIDPreparsedDataRef preparsedDataRef);

The HIDGetSpecificValueCaps function retrieves capability data for values that meet given search criteria, as opposed to the HIDGetValueCaps function, which returns the capability data for all values on the device. Calling this routine with a value of zero for usagePage, usage and collection parameters is equivalent to calling the HIDGetValueCaps function.

Parameters

NameDescription
reportTypeSpecifies the type of report for which to retrieve the value capabilities. This parameter must be one of the following: kHIDInputReport, kHIDOutputReport or kHIDFeatureReport.
usagePageSpecifies a usage page identifier to use as a search criteria. If this parameter is non-zero, then only values that specify this usage page will be retrieved.
collectionSpecifies a link collection identifier to use as a search criteria. If this parameter is non-zero, then only values that are part of this link collection will be retrieved.
usageSpecifies a usage identifier to use as a search criteria. If this parameter is non-zero, then only values that specify this usage will be retrieved.
valueCapsPoints to a caller-allocated buffer that will contain, on return, an array of HIDValueCaps structures that contain information for all values that meet the search criteria.
valueCapsLengthSpecifies the length on input, in array elements, of the buffer provided in the valueCaps parameter. On output, this parameter is set to the actual number of elements that were returned by this function call, in the buffer provided in the valueCaps parameter, if the routine completed without error. The correct length necessary to retrieve the value capabilities can be found in the capability data returned for the device from the HIDGetCaps function.
preparsedDataRefPreparsed data reference for the report that is retuned by the HIDOpenReportDescriptor function
Result: OSStatus Returns an error code if an error was encountered or noErr on success.

HIDGetUsageValue

Abstract: The HIDGetUsageValue function returns a value from a device data report given a selected search criteria.
extern OSStatus HIDGetUsageValue(HIDReportType reportType,
 HIDUsage usagePage,
 UInt32 collection,
 HIDUsage usage,
 SInt32 * usageValue,
 HIDPreparsedDataRef preparsedDataRef,
 void * report,
 ByteCount reportLength);

The HIDGetUsageValue function does not sign the value. To have the sign bit automatically applied, use the HIDGetScaledUsageValue function instead. For manually assigning the sign bit, the position of the sign bit can be found in the HIDValueCaps structure for this value. Clients who wish to obtain all data for a usage that contains multiple data items for a single usage, corresponding to a HID byte array, must call the HIDGetUsageValueArray function instead.

Parameters

NameDescription
reportTypeSpecifies the type of report, provided in report, from which to retrieve the value. This parameter must be one of the following: kHIDInputReport, kHIDOutputReport, or kHIDFeatureReport.
usagePageSpecifies the usage page of the value to retrieve.
collectionOptionally specifies the link collection identifier of the value to be retrieved.
usageSpecifies the usage of the value to be retrieved.
usageValuePoints to a variable, that on return from this routine holds the value retrieved from the device report.
preparsedDataRefPreparsed data reference for the report that is retuned by the HIDOpenReportDescriptor function
reportPoints to the caller-allocated buffer that contains the device report data.
reportLengthSpecifies the size, in bytes, of the report data provided in the report parameter.
Result: OSStatus Returns an error code if an error was encountered or noErr on success.

HIDGetUsageValueArray

Abstract: The HIDGetUsageValueArray function returns a value from a device data report given a selected search criteria.
extern OSStatus HIDGetUsageValueArray(HIDReportType reportType,
 HIDUsage usagePage,
 UInt32 collection,
 HIDUsage usage,
 Byte * usageValueBuffer,
 ByteCount usageValueBufferSize,
 HIDPreparsedDataRef preparsedDataRef,
 void * report,
 ByteCount reportLength);

When the HIDGetUsageValueArray function retrieves the data, it fills in the buffer in little-endian order beginning with the least significant bit of the data for this usage. The data is filled in without regard to byte alignment and is shifted such that the least significant bit is placed as the 1st bit of the given buffer.

Parameters

NameDescription
reportTypeSpecifies the type of report, provided in report, from which to retrieve the value. This parameter must be one of the following: kHIDInputReport, kHIDOutputReport, or kHIDFeatureReport.
usagePageSpecifies the usage page of the data to be retrieved.
collectionOptionally specifies the link collection identifier of the data to be retrieved.
usageSpecifies the usage identifier of the value to be retrieved.
usageValueBufferPoints to a caller-allocated buffer that contains, on output, the data from the device. The correct length for this buffer can be found by multiplying the reportCount and bitSize fields of the HIDValueCaps structure for the value and rounding the resulting value up to the nearest byte.
usageValueBufferSizeSpecifies the size, in bytes, of the buffer in the usageValueBuffer parameter.
preparsedDataRefPreparsed data reference for the report that is retuned by the HIDOpenReportDescriptor function
reportPoints to the caller-allocated buffer that contains the device report data.
reportLengthSpecifies the size, in bytes, of the report data provided in report.
Result: OSStatus Returns an error code if an error was encountered or noErr on success.

HIDGetValueCaps

Abstract: The HIDGetValueCaps function retrieves the capabilities for all values for a specified top level collection.
extern OSStatus HIDGetValueCaps(HIDReportType reportType,
 HIDValueCapsPtr valueCaps,
 UInt32 * valueCapsSize,
 HIDPreparsedDataRef preparsedDataRef);

The HIDGetValueCaps function retrieves the capability data for all values in a top level collection without regard for the usage, usage page or collection of the value. To retrieve value capabilities for a specific usage, usage page or collection, use the HIDGetSpecificValueCaps function.

Parameters

NameDescription
reportTypeSpecifies the type of report for which to retrieve the value capabilities. This parameter must be one of the following: kHIDInputReport, kHIDOutputReport, or kHIDFeatureReport.
valueCapsOn return, points to a caller-allocated buffer that contains an array of HIDValueCaps structures containing information for all values in the top level collection.
valueCapsSizeOn input, specifies the size in array elements of the buffer provided in the valueCaps parameter. On output, this parameter is set to the actual number of elements that were returned in the buffer provided in the valueCaps parameter, if the function completed without error. The correct length necessary to retrieve the value capabilities can be found in the capability data returned for the device by the HIDGetCaps function.
preparsedDataRefPreparsed data reference for the report that is retuned by the HIDOpenReportDescriptor function
Result: OSStatus Returns an error code if an error was encountered or noErr on success.

HIDMaxUsageListLength

Abstract: The HIDMaxUsageListLength function returns the maximum number of buttons that can be returned from a given report type for the top level collection.
extern UInt32 HIDMaxUsageListLength(HIDReportType reportType,
 HIDUsage usagePage,
 HIDPreparsedDataRef preparsedDataRef);

Parameters

NameDescription
reportTypeSpecifies the type of report for which to get a maximum usage count. This parameter must be one of the following: kHIDInputReport, kHIDOutputReport, or kHIDFeatureReport.
usagePageOptionally specifies the usage page identifier to use as a search criteria. If this parameter is zero, the function returns the number of buttons for the entire top-level collection regardless of the actual value of the usage page.
preparsedDataRefPreparsed data reference for the report that is retuned by the HIDOpenReportDescriptor function
Result: OSStatus Returns an error code if an error was encountered or noErr on success.

HIDOpenReportDescriptor

Abstract: The HIDOpenReportDescriptor function allocates the memory the parser needs to handle the given report descriptor, and then parses the report descriptor.
extern OSStatus HIDOpenReportDescriptor(void * hidReportDescriptor,
 ByteCount descriptorLength,
 HIDPreparsedDataRef * preparsedDataRef,
 UInt32 flags);

When the parsed information is no longer needed, clients should call the HIDCloseReportDescriptor function.

Parameters

NameDescription
hidReportDescriptorContains a pointer to the actual HID report descriptor from the USB device's firmware
descriptorLengthThe length of the HID report descriptor
preparsedDataRefPreparsed data reference to be used for subsequent function calls
flagsFlags for this runction are kHIDFlag_StrictErrorChecking = 0x00000001
Result: OSStatus Returns an error code if an error was encountered or noErr on success.

HIDSetButton

Abstract: The HIDSetButton function takes a report from a HID device and sets the current state of the specified button in that report.
extern OSStatus HIDSetButton(HIDReportType reportType,
 HIDUsage usagePage,
 UInt32 collection,
 HIDUsage usage,
 HIDPreparsedDataRef preparsedDataRef,
 void * report,
 ByteCount reportLength);

Parameters

NameDescription
reportTypeSpecifies the type of report. This parameter must be one of the following: kHIDInputReport, kHIDOutputReport, or kHIDFeatureReport.
usagePageSpecifies the usage page identifier of the value to be set in the report.
collectionOptionally specifies the link collection identifier to distinguish between buttons. If this parameter is zero, it is ignored.
usagePoints to a caller-allocated buffer that contains the button data to be set in the report in the report parameter.
preparsedDataRefPreparsed data reference for the report that is retuned by the HIDOpenReportDescriptor function
reportPoints to the caller-allocated buffer that contains the device report data.
reportLengthSpecifies the size, in bytes, of the report data provided in the report parameter.
Result: OSStatus Returns an error code if an error was encountered or noErr on success.

HIDSetButtons

Abstract: The HIDSetButtons function takes a report from a HID device and returns the current state of the buttons in that report.
extern OSStatus HIDSetButtons(HIDReportType reportType,
 HIDUsage usagePage,
 UInt32 collection,
 HIDUsage * usageList,
 UInt32 * usageListSize,
 HIDPreparsedDataRef preparsedDataRef,
 void * report,
 ByteCount reportLength);

Parameters

NameDescription
reportTypeSpecifies the type of repor. This parameter must be one of the following: kHIDInputReport, kHIDOutputReport, or kHIDFeatureReport.
usagePageSpecifies the usage page identifier of the value to be set in the report.
collectionOptionally specifies the link collection identifier to distinguish between buttons. If this parameter is zero, it is ignored.
usageListPoints to a caller-allocated buffer that contains an array of button data to be set in the report in the report parameter.
usageListSizeSpecifies the size, in array elements, of the buffer provided in the usageList parameter. If an error is returned by a call to this function, the usageListLength parameter contains the location in the array provided in the usageList parameter where the error was encountered. All array entries encountered prior to the error location were successfully set in the report provided in the report parameter.
preparsedDataRefPreparsed data reference for the report that is retuned by the HIDOpenReportDescriptor function
reportPoints to the caller-allocated buffer that contains the device report data.
reportLengthSpecifies the size, in bytes, of the report data provided in the report parameter.
Result: OSStatus Returns an error code if an error was encountered or noErr on success.

HIDSetScaledUsageValue

Abstract: The HIDSetScaledUsageValue function takes a signed physical (scaled) number and converts it to the logical, or device representation and inserts it in a given report.
extern OSStatus HIDSetScaledUsageValue(HIDReportType reportType,
 HIDUsage usagePage,
 UInt32 collection,
 HIDUsage usage,
 SInt32 usageValue,
 HIDPreparsedDataRef preparsedDataRef,
 void * report,
 ByteCount reportLength);

The HIDSetScaledUsageValue function automatically handles the setting of the signed bit in the data to be sent to the device.

Parameters

NameDescription
reportTypeSpecifies the type of report. This parameter must be one of the following: kHIDInputReport, kHIDOutputReport, or kHIDFeatureReport.
usagePageSpecifies the usage page identifier of the value to be set in the report.
collectionOptionally specifies the link collection identifier to distinguish between values that have the same usage page and usage identifiers. If this parameter is zero, it will be ignored.
usageSpecifies the usage identifier of the value to be set in the report.
usageValueSpecifies the physical, or scaled, value to be set in the value for the given report.
preparsedDataRefPreparsed data reference for the report that is retuned by the HIDOpenReportDescriptor function
reportPoints to the caller-allocated buffer that contains the device report data.
Specifiesthe length, in bytes of the report data specified in the report parameter.
Result: OSStatus Returns an error code if an error was encountered or noErr on success.

HIDSetUsageValue

Abstract: The HIDSetUsageValue function sets a value in a give report.
extern OSStatus HIDSetUsageValue(HIDReportType reportType,
 HIDUsage usagePage,
 UInt32 collection,
 HIDUsage usage,
 SInt32 usageValue,
 HIDPreparsedDataRef preparsedDataRef,
 void * report,
 ByteCount reportLength);

The HIDSetUsageVlaue function does not automatically handle the sign bit. Clients must either manually set the sign bit, at the position provided in the HIDValueCaps structure for this value, or call the HIDSetScaledUsageValue function.

Parameters

NameDescription
reportTypeSpecifies the type of report. This parameter must be one of the following: kHIDInputReport, kHIDOutputReport, or kHIDFeatureReport.
usagePageSpecifies the usage page identifier of the value to be set in the report.
collectionOptionally specifies the link collection identifier to distinguish between values that have the same usage page and usage identifiers. If this parameter is zero, it is ignored.
usageSpecifies the usage identifier of the value to be set in the report.
usageValueSpecifies the data that is to be set in the value for the given report.
preparsedDataRefPreparsed data reference for the report that is retuned by the HIDOpenReportDescriptor function
reportPoints to the caller-allocated buffer that contains the device report data.
reportLengthSpecifies the size, in bytes, of the report data provided in the report parameter.
Result: OSStatus Returns an error code if an error was encountered or noErr on success.

HIDSetUsageValueArray

Abstract: The HIDSetUsageValueArray function sets an array of values in a given report.
extern OSStatus HIDSetUsageValueArray(HIDReportType reportType,
 HIDUsage usagePage,
 UInt32 collection,
 HIDUsage usage,
 Byte * usageValueBuffer,
 ByteCount usageValueBufferLength,
 HIDPreparsedDataRef preparsedDataRef,
 void * report,
 ByteCount reportLength);

The HIDSetUsageValue function does not automatically handle the sign bit. Clients must either manually set the sign bit, at the position provided in the HIDValueCaps structure for this value, or call the HIDSetScaledUsageValue function.

Parameters

NameDescription
reportTypeSpecifies the type of report. This parameter must be one of the following: kHIDInputReport, kHIDOutputReport, or kHIDFeatureReport.
usagePageSpecifies the usage page identifier of the value to be set in the report.
collectionOptionally specifies the link collection identifier to distinguish between values that have the same usage page and usage identifiers. If this parameter is zero, it is ignored.
usageSpecifies the usage identifier of the value to be set in the report.
usageValueBufferPoints to a caller-allocated buffer that contains, on output, the data from the device. The correct length for this buffer can be found by multiplying the reportCount and bitSize fields of the HIDValueCaps structure for this value and rounding the resulting value up to the nearest byte.
usageValueBufferLengthSpecifies the size, in bytes, of the buffer in the usageValueBuffer parameter.
preparsedDataRefPreparsed data reference for the report that is retuned by the HIDOpenReportDescriptor function
reportPoints to the caller-allocated buffer that contains the device report data.
reportLengthSpecifies the size, in bytes, of the report data provided in the report parameter.
Result: OSStatus Returns an error code if an error was encountered or noErr on success.

HIDUsageListDifference

Abstract: The HIDUsageListDifference function compares and provides the differences between two lists of buttons.
extern OSStatus HIDUsageListDifference(HIDUsage * previousUsageList,
 HIDUsage * currentUsageList,
 HIDUsage * breakUsageList,
 HIDUsage * makeUsageList,
 UInt32 usageListsSize);

Parameters

NameDescription
previousUsageListPoints to the older button list to be used for comparison.
currentUsageListPoints to the newer button list to be used for comparison.
breakUsageListOn return, points to a caller-allocated buffer that contains the buttons set in the older list, specified in the previousUsageList parameter, but not set in the new list, specified in the currentUsageList parameter.
makeUsageListOn return, points to a caller-allocated buffer that contains the buttons set in the new list, specified in the currentUsageList parameter, but not set in the old list, specified in the previousUsageList parameter.
usageListsLengthSpecifies the length, in array elements, of the buffers provided in the currentUsageList and previousUssageList parameters.
Result: OSStatus Returns an error code if an error was encountered or noErr on success.

Typedefs

HIDCaps

struct  HIDCaps
{
  HIDUsage  usage;
  HIDUsage  usagePage;
  ByteCount  inputReportByteLength;
  ByteCount  outputReportByteLength;
  ByteCount  featureReportByteLength;
  UInt32  numberCollectionNodes;
  UInt32  numberInputButtonCaps;
  UInt32  numberInputValueCaps;
  UInt32  numberOutputButtonCaps;
  UInt32  numberOutputValueCaps;
  UInt32  numberFeatureButtonCaps;
  UInt32  numberFeatureValueCaps;
};
typedef  struct  HIDCaps  HIDCaps,  *  HIDCapsPtr;

This structure holds the parsed capabilities and data maximums returned for a device by the HIDGetCaps function.

Fields

NameDescription
usageSpecifies the specific class of functionality that this device provides. This value is dependent and specific to the value provided in the usagePage field. For example, a keyboard could have a usagePage of kHIDUsagePage_Generic and a usage of kHIDUsage_Generic_Keyboard.
usagePageSpecifies the usage page identifier for this top level collection.
inputReportByteLengthSpecifies the maximum length, in bytes, of an input report for this device, including the report ID which is unilaterally prepended to the device data.
outputReportByteLengthSpecifies the maximum length, in bytes, of an output report for this device, including the report ID which is unilaterally prepended to the device data.
featureReportByteLengthSpecifies the maximum length, in bytes, of a feature report for this device, including the report ID which is unilaterally prepended to the device data.
numberCollectionNodesSpecifies the number of HIDCollectionNode structures that are returned for this top level collection by the HIDGetConnectionNodes function.
numberInputButtonCapsSpecifies the number of input buttons.
numberInputValueCapsSpecifies the number of input values.
numberOutputButtonCapsSpecifies the number of output buttons.
numberOutputValueCapsSpecifies the number of output values
numberFeatureButtonCapsSpecifies the number of feature buttons.
numberFeatureValueCapsSpecifies the number of feature values.

HIDUsageAndPage

struct  HIDUsageAndPage
{
  HIDUsage  usage;
  HIDUsage  usagePage;
};
typedef  struct  HIDUsageAndPage  HIDUsageAndPage,  *HIDUsageAndPagePtr;

Clients use the HIDUSageAndPage structure with the HIDGetButtonsEx function to obtain both the usage page and usage identifiers of each button that is down.

Fields

NameDescription
usageSpecifies the usage identifier within the usage page specified by usagePage of a button that is down.
usagePageSpecifies the usage page identifier of a button that is down.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOInterruptEventSource.h

IOInterruptEventSource.h



© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOInterruptEventSource

IOInterruptEventSource



Member Functions

checkForWork

Abstract: Pure Virtual member function used by IOWorkLoop for issueing a client calls.
protected:

virtual bool checkForWork();

This function called when the work-loop is ready to check for any work to do and then to call out the owner/action.

Result: Return true if this function needs to be called again before all its outstanding events have been processed.

disable

Abstract: Disable event source.
public:

virtual void disable();

A subclass implementation is expected to respect the enabled state when checkForWork is called.


disableInterruptOccurred

Abstract: Functions that get called by the interrupt controller.See $link IOService::registerInterrupt
public:

virtual void disableInterruptOccurred(void *, IOService *nub, int ind);

Parameters

NameDescription
nubWhere did the interrupt originate from
indWhat is this interrupts index within 'nub'.

enable

Abstract: Enable event source.
public:

virtual void enable();

A subclass implementation is expected to respect the enabled state when checkForWork is called. Calling this function will cause the work-loop to be signalled so that a checkForWork is performed.


free

Abstract: Sub-class implementation of free method, disconnects from the interrupt source.
protected:

virtual void free();


getAutoDisable

Abstract: Get'ter for $link autoDisable variable.
public:

virtual bool getAutoDisable() const;

Result: value of autoDisable.

getIntIndex

Abstract: Get'ter for $link intIndex interrupt index variable.
public:

virtual int getIntIndex() const;

Result: value of intIndex.

getProvider

Abstract: Get'ter for $link provider variable.
public:

virtual const IOService *getProvider() const;

Result: value of provider.

init

Abstract: Primary initialiser for the IOInterruptEventSource class.
public:

virtual bool init(OSObject *owner, Action action, IOService *provider = 0, int intIndex = 0);

Parameters

NameDescription
ownerOwning client of the new event source.
action'C' Function to call when something happens.
providerIOService that represents the interrupt source. Defaults to 0. When no provider is defined the event source assumes that the client will in some manner call the interruptOccured method explicitly. This will start the ball rolling for safe delivery of asynchronous event's into the driver.
intIndexThe index of the interrupt within the provider's interrupt sources. Defaults to 0, i.e. the first interrupt in the provider.
Result: true if the inherited classes and this instance initialise successfully.

interruptEventSource

Abstract: Factory function for IOInterruptEventSources creation and initialisation.
public:

static IOInterruptEventSource * interruptEventSource(OSObject *owner, Action action, IOService *provider = 0, int intIndex = 0);

Parameters

NameDescription
ownerOwning client of the new event source.
action'C' Function to call when something happens.
providerIOService that represents the interrupt source. Defaults to 0. When no provider is defined the event source assumes that the client will in some manner call the interruptOccured method explicitly. This will start the ball rolling for safe delivery of asynchronous event's into the driver.
intIndexThe index of the interrupt within the provider's interrupt sources. Defaults to 0, i.e. the first interrupt in the provider.
Result: A new interrupt event source if successfully created and initialised, 0 otherwise.

interruptOccurred

Abstract: Functions that get called by the interrupt controller. See $link IOService::registerInterrupt
public:

virtual void interruptOccurred(void *, IOService *nub, int ind);

Parameters

NameDescription
nubWhere did the interrupt originate from
indWhat is this interrupts index within 'nub'.

normalInterruptOccurred

Abstract: Functions that get called by the interrupt controller.See $link IOService::registerInterrupt
public:

virtual void normalInterruptOccurred(void *, IOService *nub, int ind);

Parameters

NameDescription
nubWhere did the interrupt originate from
indWhat is this interrupts index within 'nub'.

Member Data

Action

public:typedef void (*Action)(OSObject *, IOInterruptEventSource *, int count);

'C' pointer prototype of functions that are called in a single threaded context when an interrupt occurs.

Parameters

NameDescription
ownerPointer to client instance.
senderPointer to generation interrupt event source.
countNumber of interrupts seen before delivery.

autoDisable

protected:
 bool autoDisable;

Do we need to automatically disable the interrupt source when we take an interrupt, i.e. we are level triggered.


consumerCount

protected:
 unsigned int consumerCount;

Current count of produced interrupts that the owner has been informed of.


explicitDisable

protected:
 bool explicitDisable;

Has the user expicitly disabled this event source, if so then do not overide their request when returning from the callout


intIndex

protected:
 int intIndex;


producerCount

protected:
 volatile unsigned int producerCount;

Current count of produced interrupts that have been received.


provider

protected:
 IOService *provider;

IOService that provides interrupts for delivery.


#defines

IOInterruptEventAction

#define IOInterruptEventAction IOInterruptEventSource::Action

Backward compatibilty define for the old non-class scoped type definition. See $link IOInterruptEventSource::Action


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOLib.h

IOLib.h



Functions

Debugger

Abstract: Enter the kernel debugger.
void Debugger(const char * reason);

This function freezes the kernel and enters the builtin debugger. It may not be possible to exit the debugger without a second machine.

Parameters

NameDescription
reasonA C-string to describe why the debugger is being entered.

IOCreateThread

Abstract: Create a kernel thread.
IOThread IOCreateThread(IOThreadFunc function, void *argument);

This function creates a kernel thread, and passes the caller supplied argument to the new thread.

Parameters

NameDescription
functionA C-function pointer where the thread will begin execution.
argumentCaller specified data to be passed to the new thread.
Result: An IOThread identifier for the new thread, equivalent to an osfmk thread_t.

IODelay

Abstract: Spin delay for a number of microseconds.
void IODelay(unsigned microseconds);

This function spins to delay for at least the number of specified microseconds. Since the CPU is busy spinning no time is made available to other processes; this method of delay should be used only for short periods. Also, the AbsoluteTime based APIs of kern/clock.h provide finer grained and lower cost delays.

Parameters

NameDescription
microsecondsThe integer number of microseconds to spin wait.

IOExitThread

Abstract: Terminate exceution of current thread.
volatile void IOExitThread();

This function destroys the currently running thread, and does not return.


IOFlushProcessorCache

Abstract: Flushes the processor cache for mapped memory.
IOReturn IOFlushProcessorCache( task_t task, IOVirtualAddress address,
 IOByteCount length );

This function flushes the processor cache of an already mapped memory range. Note in most cases it is preferable to use IOMemoryDescriptor::prepare and complete to manage cache coherency since they are aware of the architecture's requirements. Flushing the processor cache is not required for coherency in most situations.

Parameters

NameDescription
taskTask the memory is mapped into.
addressVirtual address of the memory.
lengthLength of the range to set.
Result: An IOReturn code.

IOFree

Abstract: Frees memory allocated with IOMalloc.
void IOFree(void * address, vm_size_t size);

This function frees memory allocated with IOMalloc, it may block and so should not be called from interrupt level or while a simple lock is held.

Parameters

NameDescription
addressPointer to the allocated memory.
sizeSize of the memory allocated.

IOFreeAligned

Abstract: Frees memory allocated with IOMallocAligned.
void IOFreeAligned(void * address, vm_size_t size);

This function frees memory allocated with IOMallocAligned, it may block and so should not be called from interrupt level or while a simple lock is held.

Parameters

NameDescription
addressPointer to the allocated memory.
sizeSize of the memory allocated.

IOFreeContiguous

Abstract: Frees memory allocated with IOMallocContiguous.
void IOFreeContiguous(void * address, vm_size_t size);

This function frees memory allocated with IOMallocContiguous, it may block and so should not be called from interrupt level or while a simple lock is held.

Parameters

NameDescription
addressVirtual address of the allocated memory.
sizeSize of the memory allocated.

IOLog

Abstract: Log a message to console in text mode, and /var/log/system.log.
void IOLog(const char *format, ...)
__attribute__((format(printf, 1, 2)));

This function allows a driver to log diagnostic information to the screen during verbose boots, and to a log file found at /var/log/system.log. IOLog should not be called from interrupt context.

Parameters

NameDescription
formatA printf() style format string (see printf() documentation).
otherarguments described by the format string.

IOMalloc

Abstract: Allocates general purpose, wired memory in the kernel map.
void * IOMalloc(vm_size_t size);

This is a general purpose utility to allocate memory in the kernel. There are no alignment guarantees given on the returned memory, and alignment may vary depending on the kernel configuration. This function may block and so should not be called from interrupt level or while a simple lock is held.

Parameters

NameDescription
sizeSize of the memory requested.
Result: Pointer to the allocated memory, or zero on failure.

IOMallocAligned

Abstract: Allocates wired memory in the kernel map, with an alignment restriction.
void * IOMallocAligned(vm_size_t size, vm_offset_t alignment);

This is a utility to allocate memory in the kernel, with an alignment restriction which is specified as a byte count. This function may block and so should not be called from interrupt level or while a simple lock is held.

Parameters

NameDescription
sizeSize of the memory requested.
alignmentByte count of the alignment for the memory. For example, pass 256 to get memory allocated at an address with bit 0-7 zero.
Result: Pointer to the allocated memory, or zero on failure.

IOMallocContiguous

Abstract: Allocates wired memory in the kernel map, with an alignment restriction and physically contiguous.
void * IOMallocContiguous(vm_size_t size, vm_size_t alignment,
 IOPhysicalAddress * physicalAddress);

This is a utility to allocate memory in the kernel, with an alignment restriction which is specified as a byte count, and will allocate only physically contiguous memory. The request may fail if memory is fragmented, and may cause large amounts of paging activity. This function may block and so should not be called from interrupt level or while a simple lock is held.

Parameters

NameDescription
sizeSize of the memory requested.
alignmentByte count of the alignment for the memory. For example, pass 256 to get memory allocated at an address with bits 0-7 zero.
physicalAddressIOMallocContiguous returns the physical address of the allocated memory here, if physicalAddress is a non-zero pointer.
Result: Virtual address of the allocated memory, or zero on failure.

IOSetProcessorCacheMode

Abstract: Sets the processor cache mode for mapped memory.
IOReturn IOSetProcessorCacheMode( task_t task, IOVirtualAddress address,
 IOByteCount length, IOOptionBits cacheMode );

This function sets the cache mode of an already mapped & wired memory range. Note this may not be supported on I/O mappings or shared memory - it is far preferable to set the cache mode as mappings are created with the IOMemoryDescriptor::map method.

Parameters

NameDescription
taskTask the memory is mapped into.
addressVirtual address of the memory.
lengthLength of the range to set.
cacheModeA constant from IOTypes.h,
kIOMapDefaultCache to inhibit the cache in I/O areas, kIOMapCopybackCache in general purpose RAM.
kIOMapInhibitCache, kIOMapWriteThruCache, kIOMapCopybackCache to set the appropriate caching.
Result: An IOReturn code.

IOSleep

Abstract: Sleep the calling thread for a number of milliseconds.
void IOSleep(unsigned milliseconds);

This function blocks the calling thread for at least the number of specified milliseconds, giving time to other processes.

Parameters

NameDescription
millisecondsThe integer number of milliseconds to wait.

IOThreadSelf

Abstract: Returns the osfmk identifier for the currently running thread.

This function returns the current thread (a pointer to the currently active osfmk thread_shuttle).


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOLocks.h

IOLocks.h



Functions

IOLockAlloc

Abstract: Allocates and initializes an osfmk mutex.
IOLock * IOLockAlloc( void );

Allocates an osfmk mutex in general purpose memory, and initilizes it. Mutexes are general purpose blocking mutual exclusion locks, supplied by osfmk/kern/lock.h. This function may block and so should not be called from interrupt level or while a simple lock is held.

Result: Pointer to the allocated lock, or zero on failure.

IOLockFree

Abstract: Frees an osfmk mutex.
void IOLockFree( IOLock * lock);

Frees a lock allocated with IOLockAlloc. Any blocked waiters will not be woken.

Parameters

NameDescription
lockPointer to the allocated lock.

IOLockLock

Abstract: Lock an osfmk mutex.
static __inline__ void IOLockLock( IOLock * lock)
{
 _mutex_lock(lock);

Lock the mutex. If the lock is held by any thread, block waiting for its unlock. This function may block and so should not be called from interrupt level or while a simple lock is held. Locking the mutex recursively from one thread will result in deadlock.

Parameters

NameDescription
lockPointer to the allocated lock.

IOLockTryLock

Abstract: Attempt to lock an osfmk mutex.
static __inline__ boolean_t IOLockTryLock( IOLock * lock)
{
 return(_mutex_try(lock));

Lock the mutex if it is currently unlocked, and return true. If the lock is held by any thread, return false.

Parameters

NameDescription
lockPointer to the allocated lock.
Result: True if the mutex was unlocked and is now locked by the caller, otherwise false.

IOLockUnlock

Abstract: Unlock an osfmk mutex.
static __inline__ void IOLockUnlock( IOLock * lock)
{
 mutex_unlock(lock);

Unlock the mutex and wake any blocked waiters. Results are undefined if the caller has not locked the mutex. This function may block and so should not be called from interrupt level or while a simple lock is held.

Parameters

NameDescription
lockPointer to the allocated lock.

IORWLockAlloc

Abstract: Allocates and initializes an osfmk general (read/write) lock.
IORWLock * IORWLockAlloc( void );

Allocates an initializes an osfmk lock_t in general purpose memory, and initilizes it. Read/write locks provide for multiple readers, one exclusive writer, and are supplied by osfmk/kern/lock.h. This function may block and so should not be called from interrupt level or while a simple lock is held.

Result: Pointer to the allocated lock, or zero on failure.

IORWLockFree

Abstract: Frees an osfmk general (read/write) lock.
void IORWLockFree( IORWLock * lock);

Frees a lock allocated with IORWLockAlloc. Any blocked waiters will not be woken.

Parameters

NameDescription
lockPointer to the allocated lock.

IORWLockRead

Abstract: Lock an osfmk lock for read.
static __inline__ void IORWLockRead( IORWLock * lock)
{
 lock_read( lock);

Lock the lock for read, allowing multiple readers when there are no writers. If the lock is held for write, block waiting for its unlock. This function may block and so should not be called from interrupt level or while a simple lock is held. Locking the lock recursively from one thread, for read or write, can result in deadlock.

Parameters

NameDescription
lockPointer to the allocated lock.

IORWLockUnlock

Abstract: Unlock an osfmk lock.
static __inline__ void IORWLockUnlock( IORWLock * lock)
{
 lock_done( lock);

Undo one call to IORWLockRead or IORWLockWrite. Results are undefined if the caller has not locked the lock. This function may block and so should not be called from interrupt level or while a simple lock is held.

Parameters

NameDescription
lockPointer to the allocated lock.

IORWLockWrite

Abstract: Lock an osfmk lock for write.
static __inline__ void IORWLockWrite( IORWLock * lock)
{
 lock_write( lock);

Lock the lock for write, allowing one writer exlusive access. If the lock is held for read or write, block waiting for its unlock. This function may block and so should not be called from interrupt level or while a simple lock is held. Locking the lock recursively from one thread, for read or write, can result in deadlock.

Parameters

NameDescription
lockPointer to the allocated lock.

IORecursiveLockAlloc

Abstract: Allocates and initializes an recursive lock.
IORecursiveLock * IORecursiveLockAlloc( void );

Allocates a recursive lock in general purpose memory, and initilizes it. Recursive locks function identically to osfmk mutexes but allow one thread to lock more than once, with balanced unlocks.

Result: Pointer to the allocated lock, or zero on failure.

IORecursiveLockFree

Abstract: Frees a recursive lock.
void IORecursiveLockFree( IORecursiveLock * lock);

Frees a lock allocated with IORecursiveLockAlloc. Any blocked waiters will not be woken.

Parameters

NameDescription
lockPointer to the allocated lock.

IORecursiveLockHaveLock

Abstract: Check if a recursive lock is held by the calling thread.
boolean_t IORecursiveLockHaveLock( const IORecursiveLock * lock);

If the lock is held by the calling thread, return true, otherwise the lock is unlocked, or held by another thread and false is returned.

Parameters

NameDescription
lockPointer to the allocated lock.
Result: True if the calling thread holds the lock otherwise false.

IORecursiveLockLock

Abstract: Lock a recursive lock.
void IORecursiveLockLock( IORecursiveLock * lock);

Lock the recursive lock. If the lock is held by another thread, block waiting for its unlock. This function may block and so should not be called from interrupt level or while a simple lock is held. The lock may be taken recursively by the same thread, with a balanced number of calls to IORecursiveLockUnlock.

Parameters

NameDescription
lockPointer to the allocated lock.

IORecursiveLockTryLock

Abstract: Attempt to lock a recursive lock.
boolean_t IORecursiveLockTryLock( IORecursiveLock * lock);

Lock the lock if it is currently unlocked, or held by the calling thread, and return true. If the lock is held by another thread, return false. Successful calls to IORecursiveLockTryLock should be balanced with calls to IORecursiveLockUnlock.

Parameters

NameDescription
lockPointer to the allocated lock.
Result: True if the lock is now locked by the caller, otherwise false.

IORecursiveLockUnlock

Abstract: Unlock a recursive lock.
void IORecursiveLockUnlock( IORecursiveLock * lock);

Undo one call to IORecursiveLockLock, if the lock is now unlocked wake any blocked waiters. Results are undefined if the caller does not balance calls to IORecursiveLockLock with IORecursiveLockUnlock. This function may block and so should not be called from interrupt level or while a simple lock is held.

Parameters

NameDescription
lockPointer to the allocated lock.

IOSimpleLockAlloc

Abstract: Allocates and initializes an osfmk simple (spin) lock.
IOSimpleLock * IOSimpleLockAlloc( void );

Allocates an initializes an osfmk simple lock in general purpose memory, and initilizes it. Simple locks provide non-blocking mutual exclusion for synchronization between thread context and interrupt context, or for multiprocessor synchronization, and are supplied by osfmk/kern/simple_lock.h. This function may block and so should not be called from interrupt level or while a simple lock is held.

Result: Pointer to the allocated lock, or zero on failure.

IOSimpleLockFree

Abstract: Frees an osfmk simple (spin) lock.
void IOSimpleLockFree( IOSimpleLock * lock );

Frees a lock allocated with IOSimpleLockAlloc.

Parameters

NameDescription
lockPointer to the lock.

IOSimpleLockInit

Abstract: Initialize an osfmk simple (spin) lock.
void IOSimpleLockInit( IOSimpleLock * lock );

Initialize an embedded osfmk simple lock, to the unlocked state.

Parameters

NameDescription
lockPointer to the lock.

IOSimpleLockLock

Abstract: Lock an osfmk simple lock.
static __inline__ void IOSimpleLockLock( IOSimpleLock * lock )
{
 simple_lock( lock );

Lock the simple lock. If the lock is held, spin waiting for its unlock. Simple locks disable preemption, cannot be held across any blocking operation, and should be held for very short periods. When used to synchronize between interrupt context and thread context they should be locked with interrupts disabled - IOSimpleLockLockDisableInterrupt() will do both. Locking the lock recursively from one thread will result in deadlock.

Parameters

NameDescription
lockPointer to the lock.

IOSimpleLockLockDisableInterrupt

Abstract: Lock an osfmk simple lock.
static __inline__ IOInterruptState IOSimpleLockLockDisableInterrupt( IOSimpleLock * lock )
{
 IOInterruptState state = ml_set_interrupts_enabled( false );

Lock the simple lock. If the lock is held, spin waiting for its unlock. Simple locks disable preemption, cannot be held across any blocking operation, and should be held for very short periods. When used to synchronize between interrupt context and thread context they should be locked with interrupts disabled - IOSimpleLockLockDisableInterrupt() will do both. Locking the lock recursively from one thread will result in deadlock.

Parameters

NameDescription
lockPointer to the lock.

IOSimpleLockTryLock

Abstract: Attempt to lock an osfmk simple lock.
static __inline__ boolean_t IOSimpleLockTryLock( IOSimpleLock * lock )
{
 return( simple_lock_try( lock ) );

Lock the simple lock if it is currently unlocked, and return true. If the lock is held, return false. Successful calls to IOSimpleLockTryLock should be balanced with calls to IOSimpleLockUnlock.

Parameters

NameDescription
lockPointer to the lock.
Result: True if the lock was unlocked and is now locked by the caller, otherwise false.

IOSimpleLockUnlock

Abstract: Unlock an osfmk simple lock.
static __inline__ void IOSimpleLockUnlock( IOSimpleLock * lock )
{
 simple_unlock( lock );

Unlock the lock, and restore preemption. Results are undefined if the caller has not locked the lock.

Parameters

NameDescription
lockPointer to the lock.

IOSimpleLockUnlockEnableInterrupt

Abstract: Unlock an osfmk simple lock, and restore interrupt state.
static __inline__ void IOSimpleLockUnlockEnableInterrupt( IOSimpleLock * lock,
 IOInterruptState state )
{
 simple_unlock( lock );

Unlock the lock, and restore preemption and interrupts to the state as they were when the lock was taken. Results are undefined if the caller has not locked the lock.

Parameters

NameDescription
lockPointer to the lock.
stateThe interrupt state returned by IOSimpleLockLockDisableInterrupt()

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOMBufMemoryCursor.h

IOMBufMemoryCursor.h



© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOMBufBigMemoryCursor

IOMBufBigMemoryCursor



Member Functions

getPhysicalSegments

Abstract: Generate a big endian physical scatter/gather list from a given mbuf.
public:

UInt getPhysicalSegments(struct mbuf * packet, struct IOPhysicalSegment * vector, UInt numVectorSegments = 0);

Parameters

NameDescription
packetThe mbuf packet.
vectorPointer to an array of IOPhysicalSegments for the output physical scatter/gather list.
numVectorSegmentsMaximum number of IOPhysicalSegments accepted.
Result: The number of segments that were filled in is returned, or 0 if an error occurred.

getPhysicalSegmentsWithCoalesce

Abstract: Generate a big endian physical scatter/gather list from a given mbuf.
public:

UInt getPhysicalSegmentsWithCoalesce(struct mbuf * packet, struct IOPhysicalSegment * vector, UInt numVectorSegments = 0);

Generate a big endian physical scatter/gather list from a given mbuf. Coalesce mbuf chain when the number of segments in the scatter/gather list exceeds numVectorSegments.

Parameters

NameDescription
packetThe mbuf packet.
vectorPointer to an array of IOPhysicalSegments for the output physical scatter/gather list.
numVectorSegmentsMaximum number of IOPhysicalSegments accepted.
Result: The number of segments that were filled in is returned, or 0 if an error occurred.

withSpecification

Abstract: Factory function to create and initialize an IOMBufBigMemoryCursor in one operation, see IOMBufMemoryCursor::initWithSpecification.
public:

static IOMBufBigMemoryCursor * withSpecification(UInt maxSegmentSize, UInt maxNumSegments);

Parameters

NameDescription
maxSegmentSizeMaximum allowable size for one segment.
maxNumSegmentsMaximum number of segments.
Result: A new mbuf cursor if successfully created and initialized, 0 otherwise.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOMBufDBDMAMemoryCursor

IOMBufDBDMAMemoryCursor



Member Functions

getPhysicalSegments

Abstract: Generate a DBDMA descriptor list from a given mbuf.
public:

UInt getPhysicalSegments(struct mbuf * packet, struct IODBDMADescriptor *vector, UInt numVectorSegments = 0);

Parameters

NameDescription
packetThe mbuf packet.
vectorPointer to an array of IODBDMADescriptor for the output list.
numVectorSegmentsMaximum number of IODBDMADescriptors accepted.
Result: The number of segments that were filled in is returned, or 0 if an error occurred.

getPhysicalSegmentsWithCoalesce

Abstract: Generate a DBDMA descriptor list from a given mbuf.
public:

UInt getPhysicalSegmentsWithCoalesce(struct mbuf * packet, struct IODBDMADescriptor * vector, UInt numVectorSegments = 0);

Generate a DBDMA descriptor list from a given mbuf. Coalesce mbuf chain when the number of elements in the list exceeds numVectorSegments.

Parameters

NameDescription
packetThe mbuf packet.
vectorPointer to an array of IODBDMADescriptor for the output list.
numVectorSegmentsMaximum number of IODBDMADescriptors accepted.
Result: The number of segments that were filled in is returned, or 0 if an error occurred.

withSpecification

Abstract: Factory function to create and initialize an IOMBufDBDMAMemoryCursor in one operation, see IOMBufMemoryCursor::initWithSpecification.
public:

static IOMBufDBDMAMemoryCursor * withSpecification(UInt maxSegmentSize, UInt maxNumSegments);

Parameters

NameDescription
maxSegmentSizeMaximum allowable size for one segment.
maxNumSegmentsMaximum number of segments.
Result: A new mbuf cursor if successfully created and initialized, 0 otherwise.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOMBufLittleMemoryCursor

IOMBufLittleMemoryCursor



Member Functions

getPhysicalSegments

Abstract: Generate a little endian physical scatter/gather list from a given mbuf.
public:

UInt getPhysicalSegments(struct mbuf * packet, struct IOPhysicalSegment * vector, UInt numVectorSegments = 0);

Parameters

NameDescription
packetThe mbuf packet.
vectorPointer to an array of IOPhysicalSegments for the output physical scatter/gather list.
numVectorSegmentsMaximum number of IOPhysicalSegments accepted.
Result: The number of segments that were filled in is returned, or 0 if an error occurred.

getPhysicalSegmentsWithCoalesce

Abstract: Generate a little endian physical scatter/gather list from a given mbuf.
public:

UInt getPhysicalSegmentsWithCoalesce(struct mbuf * packet, struct IOPhysicalSegment * vector, UInt numVectorSegments = 0);

Generate a little endian physical scatter/gather list from a given mbuf. Coalesce mbuf chain when the number of segments in the scatter/gather list exceeds numVectorSegments.

Parameters

NameDescription
packetThe mbuf packet.
vectorPointer to an array of IOPhysicalSegments for the output physical scatter/gather list.
numVectorSegmentsMaximum number of IOPhysicalSegments accepted.
Result: The number of segments that were filled in is returned, or 0 if an error occurred.

withSpecification

Abstract: Factory function to create and initialize an IOMBufLittleMemoryCursor in one operation, see IOMBufMemoryCursor::initWithSpecification.
public:

static IOMBufLittleMemoryCursor * withSpecification(UInt maxSegmentSize, UInt maxNumSegments);

Parameters

NameDescription
maxSegmentSizeMaximum allowable size for one segment.
maxNumSegmentsMaximum number of segments.
Result: A new mbuf cursor if successfully created and initialized, 0 otherwise.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOMBufMemoryCursor

IOMBufMemoryCursor



Member Functions

genPhysicalSegments

Abstract: Generate a physical scatter/gather list given a mbuf packet.
protected:

virtual UInt genPhysicalSegments(struct mbuf * packet, void * vector, UInt maxSegs, bool doCoalesce);

Generates a list of physical segments from the given mbuf.

Parameters

NameDescription
packetThe mbuf packet.
vectorVoid pointer to base of output physical scatter/gather list. Always passed directly onto the OutputSegmentFunc without interpretation by the cursor.
maxSegsMaximum number of segments that can be written to segments array.
doCoalesceSet to true to perform coalescing when the required number of segments exceeds the specified limit, otherwise abort and return 0.
Result: The number of segments that were filled in is returned, or 0 if an error occurred.

genPhysicalSegments

Abstract: Returns a count of the total number of mbuf chains coalesced by genPhysicalSegments(). The counter is then reset to 0.
public:

UInt getAndResetCoalesceCount();

Result: The coalesce count.

initWithSpecification

Abstract: Primary initializer for the IOMBufMemoryCursor class.
protected:

virtual bool initWithSpecification(OutputSegmentFunc outSeg, UInt maxSegmentSize, UInt maxNumSegments);

Parameters

NameDescription
outSegFunction to call to output one physical segment.
maxSegmentSizeMaximum allowable size for one segment.
maxNumSegmentsMaximum number of segments.
Result: true if the inherited classes and this instance initialized successfully.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOMBufNaturalMemoryCursor

IOMBufNaturalMemoryCursor



Member Functions

getPhysicalSegments

Abstract: Generate a cpu natural physical scatter/gather list from a given mbuf.
public:

UInt getPhysicalSegments(struct mbuf * packet, struct IOPhysicalSegment * vector, UInt numVectorSegments = 0);

Parameters

NameDescription
packetThe mbuf packet.
vectorPointer to an array of IOPhysicalSegments for the output physical scatter/gather list.
numVectorSegmentsMaximum number of IOPhysicalSegments accepted.
Result: The number of segments that were filled in is returned, or 0 if an error occurred.

getPhysicalSegmentsWithCoalesce

Abstract: Generate a cpu natural physical scatter/gather list from a given mbuf.
public:

UInt getPhysicalSegmentsWithCoalesce(struct mbuf * packet, struct IOPhysicalSegment * vector, UInt numVectorSegments = 0);

Generate a cpu natural physical scatter/gather list from a given mbuf. Coalesce mbuf chain when the number of segments in the scatter/gather list exceeds numVectorSegments.

Parameters

NameDescription
packetThe mbuf packet.
vectorPointer to an array of IOPhysicalSegments for the output physical scatter/gather list.
numVectorSegmentsMaximum number of IOPhysicalSegments accepted.
Result: The number of segments that were filled in is returned, or 0 if an error occurred.

withSpecification

Abstract: Factory function to create and initialize an IOMBufNaturalMemoryCursor in one operation, see IOMBufMemoryCursor::initWithSpecification.
public:

static IOMBufNaturalMemoryCursor * withSpecification(UInt maxSegmentSize, UInt maxNumSegments);

Parameters

NameDescription
maxSegmentSizeMaximum allowable size for one segment.
maxNumSegmentsMaximum number of segments.
Result: A new mbuf cursor if successfully created and initialized, 0 otherwise.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOMedia.h

IOMedia.h



#defines

kIOMediaContent

kIOMediaContent is a property of IOMedia objects. It is an OSString.

#define kIOMediaContent "Content"

The kIOMediaContent property contains a description of the media's contents. The description is the same as the hint at the time of the object's creation, but it is possible that the description be overrided by a client (which has probed the media and identified the content correctly) of the media object. It is more accurate than the hint for this reason. The string is formed in the likeness of Apple's "Apple_HFS" strings.


kIOMediaContentHint

kIOMediaContentHint is a property of IOMedia objects. It is an OSString.

#define kIOMediaContentHint "Content Hint"

The kIOMediaContentHint property contains a hint of the media's contents. The hint is set at the time of the object's creation, should the creator have a clue as to what it may contain. The hint string does not change for the lifetime of the object and is formed in the likeness of Apple's "Apple_HFS" strings.


kIOMediaContentMask

kIOMediaContentMask is a property of IOMedia clients. It is an OSString.

#define kIOMediaContentMask "Content Mask"

The kIOMediaContentMask property must exist in all IOMedia clients that drive new content (that is, produce new media objects). When the client matches on the provider media, the value of the client's kIOMediaContentMask property is used to replace the provider's kIOMediaContent property.


kIOMediaEjectable

kIOMediaEjectable is a property of IOMedia objects. It is an OSBoolean.

#define kIOMediaEjectable "Ejectable"

The kIOMediaEjectable property describes whether the media is ejectable.


kIOMediaLeaf

kIOMediaLeaf is a property of IOMedia objects. It is an OSBoolean.

#define kIOMediaLeaf "Leaf"

The kIOMediaLeaf property describes whether the media is a leaf, that is, it is the deepest media object in this branch of the I/O Kit registry.


kIOMediaSize

kIOMediaSize is a property of IOMedia objects. It is an OSNumber.

#define kIOMediaSize "Size"

The kIOMediaSize property describes the total length of the media in bytes.


kIOMediaWhole

kIOMediaWhole is a property of IOMedia objects. Is it an OSBoolean.

#define kIOMediaWhole "Whole"

The kIOMediaWhole property describes whether the media is whole, that is, it represents the whole disk (the physical disk, or a virtual replica thereof).


kIOMediaWritable

kIOMediaWritable is a property of IOMedia objects. It is an OSBoolean.

#define kIOMediaWritable "Writable"

The kIOMediaWritable property describes whether the media is writable.


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOMedia

IOMedia



Member Functions

getBase

public:

virtual UInt64 getBase() const;

Ask the media object for its byte offset relative to its provider media object below it in the storage hierarchy. Media offset, in bytes.


getContent

public:

virtual const char * getContent() const;

Ask the media object for a description of its contents. The description is the same as the hint at the time of the object's creation, but it is possible that the description be overrided by a client (which has probed the media and identified the content correctly) of the media object. It is more accurate than the hint for this reason. The string is formed in the likeness of Apple's "Apple_HFS" strings. * The content description can be overrided by any client that matches onto this media object with a match category of kIOStorageCategory. The media object checks for a kIOMediaContentMask property in the client, and if it finds one, it copies it into kIOMediaContent property.

Result: Description of media's contents.

getContentHint

public:

virtual const char * getContentHint() const;

Ask the media object for a hint of its contents. The hint is set at the time of the object's creation, should the creator have a clue as to what it may contain. The hint string does not change for the lifetime of the object and is also formed in the likeness of Apple's "Apple_HFS" strings.

Result: Hint of media's contents.

getPreferredBlockSize

public:

virtual UInt64 getPreferredBlockSize() const;

Ask the media object for its natural block size. This information is useful to clients that want to optimize access to the media.

Result: Natural block size, in bytes.

getSize

public:

virtual UInt64 getSize() const;

Ask the media object for its total length in bytes.

Result: Media size, in bytes.

handleClose

protected:

virtual void handleClose(IOService * client, IOOptionBits options);

The handleClose method closes the client's access to this object. * This implementation replaces the IOService definition of handleClose().

Parameters

NameDescription
clientClient requesting the close.
optionsOptions for the close. Set to zero.

handleIsOpen

protected:

virtual bool handleIsOpen(const IOService * client) const;

The handleIsOpen method determines whether the specified client, or any client if none is specificed, presently has an open on this object. * This implementation replaces the IOService definition of handleIsOpen().

Parameters

NameDescription
clientClient to check the open state of. Set to zero to check the open state of all clients.
Result: Returns true if the client was (or clients were) open, false otherwise.

handleOpen

protected:

virtual bool handleOpen(IOService * client, IOOptionBits options, void * access);

The handleOpen method grants or denies permission to access this object to an interested client. The argument is an IOStorageAccess value that specifies the level of access desired -- reader or reader-writer. * This method can be invoked to upgrade or downgrade the access level for an existing client as well. The previous access level will prevail for upgrades that fail, of course. A downgrade should never fail. If the new access level should be the same as the old for a given client, this method will do nothing and return success. In all cases, one, singular close-per-client is expected for all opens-per-client received. * This implementation replaces the IOService definition of handleOpen().

Parameters

NameDescription
clientClient requesting the open.
optionsOptions for the open. Set to zero.
accessAccess level for the open. Set to kAccessReader or kAccessReaderWriter.
Result: Returns true if the open was successful, false otherwise.

init

public:

virtual bool init(UInt64 base, UInt64 size, UInt64 preferredBlockSize, bool isEjectable, bool isWhole, bool isWritable, const char * contentHint = 0, OSDictionary * properties = 0);

Initialize this object's minimal state.

Parameters

NameDescription
baseMedia offset, in bytes.
sizeMedia size, in bytes.
preferredBlockSizeNatural block size, in bytes.
isEjectableIndicates whether the media is ejectable.
isWholeIndicated whether the media represents the whole disk.
isWritableIndicates whether the media is writable.
contentHintHint of media's contents (optional). See getContentHint().
propertiesSubstitute property table for this object (optional).
Result: Returns true on success, false otherwise.

isEjectable

public:

virtual bool isEjectable() const;

Ask the media object whether it is ejectable.

Result: Returns true if the media is ejectable, false otherwise.

isFormatted

public:

virtual bool isFormatted() const;

Ask the media object whether it is formatted.

Result: Returns true if the media is formatted, false otherwise.

isWhole

public:

virtual bool isWhole() const;

Ask the media object whether it represents the whole disk.

Result: Returns true if the media represents the whole disk, false otherwise.

isWritable

public:

virtual bool isWritable() const;

Ask the media object whether it is writable.

Result: Returns true if the media is writable, false otherwise.

read

public:

virtual void read(IOService * client, UInt64 byteStart, IOMemoryDescriptor * buffer, IOStorageCompletion completion);

Read data from the storage object at the specified byte offset into the specified buffer, asynchronously. When the read completes, the caller will be notified via the specified completion action. * The buffer will be retained for the duration of the read.

Parameters

NameDescription
clientClient requesting the read.
byteStartStarting byte offset for the data transfer.
bufferBuffer for the data transfer. The size of the buffer implies the size of the data transfer.
completionCompletion routine to call once the data transfer is complete.

write

public:

virtual void write(IOService * client, UInt64 byteStart, IOMemoryDescriptor * buffer, IOStorageCompletion completion);

Write data into the storage object at the specified byte offset from the specified buffer, asynchronously. When the write completes, the caller will be notified via the specified completion action. * The buffer will be retained for the duration of the write.

Parameters

NameDescription
clientClient requesting the write.
byteStartStarting byte offset for the data transfer.
bufferBuffer for the data transfer. The size of the buffer implies the size of the data transfer.
completionCompletion routine to call once the data transfer is complete.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOMemoryCursor.h

IOMemoryCursor.h



© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOBigMemoryCursor

IOBigMemoryCursor



Member Functions

getPhysicalSegments

Abstract: Generate a big endian physical scatter/gather list given a memory descriptor.
public:

virtual UInt32 getPhysicalSegments(IOMemoryDescriptor * descriptor, IOByteCount fromPosition, PhysicalSegment * segments, UInt32 maxSegments, UInt32 maxTransferSize = 0, IOByteCount * transferSize = 0) { return genPhysicalSegments(descriptor, fromPosition, segments, maxSegments, maxTransferSize, transferSize);

Generates a list of physical segments from the given memory descriptor, relative to the current position of the descriptor. Wraps $link IOMemoryCursor::genPhysicalSegments.

Parameters

NameDescription
descriptorIOMemoryDescriptor that describes the data associated with an I/O request.
fromPositionStarting location of the I/O within a memory descriptor.
segmentsPointer to an array of $link IOMemoryCursor::PhysicalSegments for the output physical scatter/gather list.
maxSegmentsMaximum number of segments that can be written to segments array.
maxTransferSizeMaximum transfer size is limited to that many bytes, otherwise it defaults to the maximum transfer size specified when the memory cursor was initialized.
transferSizePointer to a IOByteCount variable that can contain the total size of the transfer being described. Default to 0 indicating that no transfer size need be returned.
Result: If the descriptor is exhausted of memory, a zero is returned, otherwise the number of segments that were filled in is returned.

initWithSpecification

Abstract: Primary initialiser for the IOBigMemoryCursor class.
public:

virtual bool initWithSpecification(IOPhysicalLength maxSegmentSize, IOPhysicalLength maxTransferSize, IOPhysicalLength alignment = 1);

Parameters

NameDescription
maxSegmentSizeMaximum allowable size for one segment. Defaults to 0.
maxTransferSizeMaximum size of an entire transfer. Default to 0 indicating no maximum.
alignmentAlligment restrictions on output physical addresses. Not currently implemented. Defaults to single byte alignment.
Result: true if the inherited classes and this instance initialise successfully.

withSpecification

Abstract: Factory function to create and initialise an IOBigMemoryCursor in one operation, see $link IOBigMemoryCursor::initWithSpecification.
public:

static IOBigMemoryCursor * withSpecification(IOPhysicalLength maxSegmentSize, IOPhysicalLength maxTransferSize, IOPhysicalLength alignment = 1);

Parameters

NameDescription
maxSegmentSizeMaximum allowable size for one segment. Defaults to 0.
maxTransferSizeMaximum size of an entire transfer. Default to 0 indicating no maximum.
alignmentAlligment restrictions on output physical addresses. Not currently implemented. Defaults to single byte alignment.
Result: A new memory cursor if successfully created and initialised, 0 otherwise.

#defines

bigOutputSegment

#define bigOutputSegment IOBigMemoryCursor::outputSegment

Backward compatibilty define for the old global function definition. See $link IOBigMemoryCursor::outputSegment


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IODBDMAMemoryCursor

IODBDMAMemoryCursor



Member Functions

getPhysicalSegments

Abstract: Generate a DBDMA physical scatter/gather list given a memory descriptor.
public:

virtual UInt32 getPhysicalSegments(IOMemoryDescriptor * descriptor, IOByteCount fromPosition, IODBDMADescriptor * segments, UInt32 maxSegments, UInt32 maxTransferSize = 0, IOByteCount * transferSize = 0) { return genPhysicalSegments(descriptor, fromPosition, segments, maxSegments, maxTransferSize, transferSize);

Generates a list of DBDMA descriptors where the address and length fields are filled in appropriately. But the client is expected to fill in the rest of teh DBDMA descriptor as is appropriate for their particular hardware. Wraps $link IOMemoryCursor::genPhysicalSegments.

Parameters

NameDescription
descriptorIOMemoryDescriptor that describes the data associated with an I/O request.
fromPositionStarting location of the I/O within a memory descriptor.
segmentsPointer to an array of DBDMA descriptors for the output physical scatter/gather list. Be warned no room is left for a preamble in the output array. 'segments' should point to the first memory description slot in a DBDMA command.
maxSegmentsMaximum number of segments that can be written to the dbdma descriptor table.
maxTransferSizeMaximum transfer size is limited to that many bytes, otherwise it defaults to the maximum transfer size specified when the memory cursor was initialized.
transferSizePointer to a IOByteCount variable that can contain the total size of the transfer being described. Default to 0 indicating that no transfer size need be returned.
Result: If the descriptor is exhausted of memory, a zero is returned, otherwise the number of segments that were filled in is returned.

initWithSpecification

Abstract: Primary initialiser for the IODBDMAMemoryCursor class.
public:

virtual bool initWithSpecification(IOPhysicalLength maxSegmentSize, IOPhysicalLength maxTransferSize, IOPhysicalLength alignment = 1);

Parameters

NameDescription
maxSegmentSizeMaximum allowable size for one segment. Defaults to 0.
maxTransferSizeMaximum size of an entire transfer. Default to 0 indicating no maximum.
alignmentAlligment restrictions on output physical addresses. Not currently implemented. Defaults to single byte alignment.
Result: true if the inherited classes and this instance initialise successfully.

withSpecification

Abstract: Factory function to create and initialise an IODBDMAMemoryCursor in one operation, see $link IODBDMAMemoryCursor::initWithSpecification.
public:

static IODBDMAMemoryCursor * withSpecification(IOPhysicalLength maxSegmentSize, IOPhysicalLength maxTransferSize, IOPhysicalLength alignment = 1);

Parameters

NameDescription
maxSegmentSizeMaximum allowable size for one segment. Defaults to 0.
maxTransferSizeMaximum size of an entire transfer. Default to 0 indicating no maximum.
alignmentAlligment restrictions on output physical addresses. Not currently implemented. Defaults to single byte alignment.
Result: A new memory cursor if successfully created and initialised, 0 otherwise.

#defines

dbdmaOutputSegment

#define dbdmaOutputSegment IODBDMAMemoryCursor::outputSegment

Backward compatibilty define for the old global function definition. See $link IODBDMAMemoryCursor::outputSegment


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOLittleMemoryCursor

IOLittleMemoryCursor



Member Functions

getPhysicalSegments

Abstract: Generate a little endian physical scatter/gather list given a memory descriptor.
public:

virtual UInt32 getPhysicalSegments(IOMemoryDescriptor * descriptor, IOByteCount fromPosition, PhysicalSegment * segments, UInt32 maxSegments, UInt32 maxTransferSize = 0, IOByteCount * transferSize = 0) { return genPhysicalSegments(descriptor, fromPosition, segments, maxSegments, maxTransferSize, transferSize);

Generates a list of physical segments from the given memory descriptor, relative to the current position of the descriptor. Wraps $link IOMemoryCursor::genPhysicalSegments.

Parameters

NameDescription
descriptorIOMemoryDescriptor that describes the data associated with an I/O request.
fromPositionStarting location of the I/O within a memory descriptor.
segmentsPointer to an array of $link IOMemoryCursor::PhysicalSegments for the output physical scatter/gather list.
maxSegmentsMaximum number of segments that can be written to segments array.
maxTransferSizeMaximum transfer size is limited to that many bytes, otherwise it defaults to the maximum transfer size specified when the memory cursor was initialized.
transferSizePointer to a IOByteCount variable that can contain the total size of the transfer being described. Default to 0 indicating that no transfer size need be returned.
Result: If the descriptor is exhausted of memory, a zero is returned, otherwise the number of segments that were filled in is returned.

initWithSpecification

Abstract: Primary initialiser for the IOLittleMemoryCursor class.
public:

virtual bool initWithSpecification(IOPhysicalLength maxSegmentSize, IOPhysicalLength maxTransferSize, IOPhysicalLength alignment = 1);

Parameters

NameDescription
maxSegmentSizeMaximum allowable size for one segment. Defaults to 0.
maxTransferSizeMaximum size of an entire transfer. Default to 0 indicating no maximum.
alignmentAlligment restrictions on output physical addresses. Not currently implemented. Defaults to single byte alignment.
Result: true if the inherited classes and this instance initialise successfully.

withSpecification

Abstract: Factory function to create and initialise an IOLittleMemoryCursor in one operation, see $link IOLittleMemoryCursor::initWithSpecification.
public:

static IOLittleMemoryCursor * withSpecification(IOPhysicalLength maxSegmentSize, IOPhysicalLength maxTransferSize, IOPhysicalLength alignment = 1);

Parameters

NameDescription
maxSegmentSizeMaximum allowable size for one segment. Defaults to 0.
maxTransferSizeMaximum size of an entire transfer. Default to 0 indicating no maximum.
alignmentAlligment restrictions on output physical addresses. Not currently implemented. Defaults to single byte alignment.
Result: A new memory cursor if successfully created and initialised, 0 otherwise.

#defines

littleOutputSegment

#define littleOutputSegment IOLittleMemoryCursor::outputSegment

Backward compatibilty define for the old global function definition. See $link IOLittleMemoryCursor::outputSegment


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOMemoryCursor

IOMemoryCursor



Member Functions

genPhysicalSegments

Abstract: Generate a physical scatter/gather list given a memory descriptor.
public:

virtual UInt32 genPhysicalSegments( IOMemoryDescriptor *descriptor, IOByteCount fromPosition, void * segments, UInt32 maxSegments, UInt32 maxTransferSize = 0, IOByteCount *transferSize = 0);

Generates a list of physical segments from the given memory descriptor, relative to the current position of the descriptor.

Parameters

NameDescription
descriptorIOMemoryDescriptor that describes the data associated with an I/O request.
fromPositionStarting location of the I/O within a memory descriptor.
segmentsVoid pointer to base of output physical scatter/gather list. Always passed directly onto the SegmentFunction without interpretation by the cursor.
maxSegmentsMaximum number of segments that can be written to segments array.
maxTransferSizeMaximum transfer size is limited to that many bytes, otherwise it defaults to the maximum transfer size specified when the memory cursor was initialized.
transferSizePointer to a IOByteCount variable that can contain the total size of the transfer being described. Default to 0 indicating that no transfer size need be returned.
Result: If the descriptor is exhausted of memory, a zero is returned, otherwise the number of segments that were filled in is returned.

initWithSpecification

Abstract: Primary initialiser for the IOMemoryCursor class.
public:

virtual bool initWithSpecification(SegmentFunction outSegFunc, IOPhysicalLength maxSegmentSize = 0, IOPhysicalLength maxTransferSize = 0, IOPhysicalLength alignment = 1);

Parameters

NameDescription
outSegFuncSegmentFunction to call to output one physical segment.
maxSegmentSizeMaximum allowable size for one segment. Defaults to 0.
maxTransferSizeMaximum size of an entire transfer. Default to 0 indicating no maximum.
alignmentAlligment restrictions on output physical addresses. Not currently implemented. Defaults to single byte alignment.
Result: true if the inherited classes and this instance initialise successfully.

withSpecification

Abstract: Factory function to create and initialise an IOMemoryCursor in one operation, see $link IOMemoryCursor::initWithSpecification.
public:

static IOMemoryCursor * withSpecification(SegmentFunction outSegFunc, IOPhysicalLength maxSegmentSize = 0, IOPhysicalLength maxTransferSize = 0, IOPhysicalLength alignment = 1);

Parameters

NameDescription
outSegFuncSegmentFunction to call to output one physical segment.
maxSegmentSizeMaximum allowable size for one segment. Defaults to 0.
maxTransferSizeMaximum size of an entire transfer. Default to 0 indicating no maximum.
alignmentAlligment restrictions on output physical addresses. Not currently implemented. Defaults to single byte alignment.
Result: A new memory cursor if successfully created and initialised, 0 otherwise.

Member Data

PhysicalSegment

public:
  struct  PhysicalSegment
  {
  IOPhysicalAddress  location;
  IOPhysicalLength  length;
  };

/*!  @defined  IOPhysicalSegment
  @discussion  Backward  compatibilty  define  for  the  old  non-class  scoped  type  definition.  See  $link  IOMemoryCursor::PhysicalSegment  */
#define  IOPhysicalSegment  IOMemoryCursor::PhysicalSegment

/*!
  @typedef  SegmentFunction

A physical address/length pair.


alignMask

protected:
 IOPhysicalLength alignMask;

Currently unused. Reserved for automated aligment restriction code.


maxSegmentSize

protected:
 IOPhysicalLength maxSegmentSize;

Maximum size of one segment in a scatter/gather list


maxTransferSize

protected:
 IOPhysicalLength maxTransferSize;

Maximum size of a transfer that this memory cursor is allowed to generate


outSeg

protected:
 SegmentFunction outSeg;

The action method called when an event has been delivered


#defines

OutputSegmentFunc

#define OutputSegmentFunc IOMemoryCursor::SegmentFunction

Backward compatibilty define for the old non-class scoped type definition. See $link IOMemoryCursor::SegmentFunction


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IONaturalMemoryCursor

IONaturalMemoryCursor



Member Functions

getPhysicalSegments

Abstract: Generate a cpu natural physical scatter/gather list given a memory descriptor.
public:

virtual UInt32 getPhysicalSegments(IOMemoryDescriptor *descriptor, IOByteCount fromPosition, PhysicalSegment *segments, UInt32 maxSegments, UInt32 maxTransferSize = 0, IOByteCount *transferSize = 0) { return genPhysicalSegments(descriptor, fromPosition, segments, maxSegments, maxTransferSize, transferSize);

Generates a list of physical segments from the given memory descriptor, relative to the current position of the descriptor. Wraps $link IOMemoryCursor::genPhysicalSegments.

Parameters

NameDescription
descriptorIOMemoryDescriptor that describes the data associated with an I/O request.
fromPositionStarting location of the I/O within a memory descriptor.
segmentsPointer to an array of $link IOMemoryCursor::PhysicalSegments for the output physical scatter/gather list.
maxSegmentsMaximum number of segments that can be written to segments array.
maxTransferSizeMaximum transfer size is limited to that many bytes, otherwise it defaults to the maximum transfer size specified when the memory cursor was initialized.
transferSizePointer to a IOByteCount variable that can contain the total size of the transfer being described. Default to 0 indicating that no transfer size need be returned.
Result: If the descriptor is exhausted of memory, a zero is returned, otherwise the number of segments that were filled in is returned.

initWithSpecification

Abstract: Primary initialiser for the IONaturalMemoryCursor class.
public:

virtual bool initWithSpecification(IOPhysicalLength maxSegmentSize, IOPhysicalLength maxTransferSize, IOPhysicalLength alignment = 1);

Parameters

NameDescription
maxSegmentSizeMaximum allowable size for one segment. Defaults to 0.
maxTransferSizeMaximum size of an entire transfer. Default to 0 indicating no maximum.
alignmentAlligment restrictions on output physical addresses. Not currently implemented. Defaults to single byte alignment.
Result: true if the inherited classes and this instance initialise successfully.

withSpecification

Abstract: Factory function to create and initialise an IONaturalMemoryCursor in one operation, see $link IONaturalMemoryCursor::initWithSpecification.
public:

static IONaturalMemoryCursor * withSpecification(IOPhysicalLength maxSegmentSize, IOPhysicalLength maxTransferSize, IOPhysicalLength alignment = 1);

Parameters

NameDescription
maxSegmentSizeMaximum allowable size for one segment. Defaults to 0.
maxTransferSizeMaximum size of an entire transfer. Default to 0 indicating no maximum.
alignmentAlligment restrictions on output physical addresses. Not currently implemented. Defaults to single byte alignment.
Result: A new memory cursor if successfully created and initialised, 0 otherwise.

#defines

naturalOutputSegment

#define naturalOutputSegment IONaturalMemoryCursor::outputSegment

Backward compatibilty define for the old global function definition. See $link IONaturalMemoryCursor::outputSegment


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOMemoryDescriptor.h

IOMemoryDescriptor.h



© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOMemoryDescriptor

IOMemoryDescriptor



Member Functions

complete

Abstract: Complete processing of the memory after an I/O transfer finishes.
public:

virtual IOReturn complete(IODirection forDirection = kIODirectionNone) = 0;

This method should not be called unless a prepare was previously issued; the prepare() and complete() must occur in pairs, before and after an I/O transfer involving pageable memory.

Parameters

NameDescription
forDirectionThe direction of the I/O just completed, or kIODirectionNone for the direction specified by the memory descriptor.
Result: An IOReturn code.

getDirection

Abstract: Accessor to get the direction the memory descriptor was created with.
public:

virtual IODirection getDirection() const;

This method returns the direction the memory descriptor was created with.

Result: The direction.

getLength

Abstract: Accessor to get the length of the memory descriptor (over all its ranges).
public:

virtual IOByteCount getLength() const;

This method returns the total length of the memory described by the descriptor, ie. the sum of its ranges' lengths.

Result: The byte count.

getPhysicalAddress

Abstract: Return the physical address of the first byte in the memory.
public:

inline IOPhysicalAddress getPhysicalAddress() { return( getPhysicalSegment( 0, 0 )); }

This method returns the physical address of the first byte in the memory. It is most useful on memory known to be physically contiguous.

Result: A physical address.

getPhysicalSegment

Abstract: Break a memory descriptor into its physically contiguous segments.
public:

virtual IOPhysicalAddress getPhysicalSegment(IOByteCount offset, IOByteCount * length) = 0;

This method returns the physical address of the byte at the given offset into the memory, and optionally the length of the physically contiguous segment from that offset.

Parameters

NameDescription
offsetA byte offset into the memory whose physical address to return.
lengthIf non-zero, getPhysicalSegment will store here the length of the physically contiguous segement at the given offset.
Result: A physical address, or zero if the offset is beyond the length of the memory.

getTag

Abstract: Accessor to the retrieve the tag for the memory descriptor.
public:

virtual IOOptionBits getTag( void );

This method returns the tag for the memory descriptor. Tag bits are not interpreted by IOMemoryDescriptor.

Result: The tag.

initWithAddress

Abstract: Initialize or reinitialize an IOMemoryDescriptor to describe one virtual range of the kernel task.
public:

virtual bool initWithAddress(void * address, IOByteCount withLength, IODirection withDirection) = 0;

This method initializes an IOMemoryDescriptor for memory consisting of a single virtual memory range mapped into the kernel map. An IOMemoryDescriptor can be re-used by calling initWithAddress or initWithRanges again on an existing instance -- note this behavior is not commonly supported in other IOKit classes, although it is supported here.

Parameters

NameDescription
addressThe virtual address of the first byte in the memory.
withLengthThe length of memory.
withDirectionAn I/O direction to be associated with the descriptor, which may affect the operation of the prepare and complete methods on some architectures.
Result: true on success, false on failure.

initWithAddress

Abstract: Initialize or reinitialize an IOMemoryDescriptor to describe one virtual range of the specified map.
public:

virtual bool initWithAddress(vm_address_t address, IOByteCount withLength, IODirection withDirection, task_t withTask) = 0;

This method initializes an IOMemoryDescriptor for memory consisting of a single virtual memory range mapped into the specified map. An IOMemoryDescriptor can be re-used by calling initWithAddress or initWithRanges again on an existing instance -- note this behavior is not commonly supported in other IOKit classes, although it is supported here.

Parameters

NameDescription
addressThe virtual address of the first byte in the memory.
withLengthThe length of memory.
withDirectionAn I/O direction to be associated with the descriptor, which may affect the operation of the prepare and complete methods on some architectures.
withTaskThe task the virtual ranges are mapped into.
Result: true on success, false on failure.

initWithPhysicalAddress

Abstract: Initialize or reinitialize an IOMemoryDescriptor to describe one physical range.
public:

virtual bool initWithPhysicalAddress( IOPhysicalAddress address, IOByteCount withLength, IODirection withDirection ) = 0;

This method initializes an IOMemoryDescriptor for memory consisting of a single physical memory range. An IOMemoryDescriptor can be re-used by calling initWithAddress or initWithRanges again on an existing instance -- note this behavior is not commonly supported in other IOKit classes, although it is supported here.

Parameters

NameDescription
addressThe physical address of the first byte in the memory.
withLengthThe length of memory.
withDirectionAn I/O direction to be associated with the descriptor, which may affect the operation of the prepare and complete methods on some architectures.
Result: true on success, false on failure.

initWithPhysicalRanges

Abstract: Initialize or reinitialize an IOMemoryDescriptor to describe one or more physical ranges.
public:

virtual bool initWithPhysicalRanges(IOPhysicalRange * ranges, UInt32 withCount, IODirection withDirection, bool asReference = false) = 0;

This method initializes an IOMemoryDescriptor for memory consisting of an array of physical memory ranges. An IOMemoryDescriptor can be re-used by calling initWithAddress or initWithRanges again on an existing instance -- note this behavior is not commonly supported in other IOKit classes, although it is supported here.

Parameters

NameDescription
rangesAn array of IOPhysicalRange structures which specify the physical ranges which make up the memory to be described.
withCountThe member count of the ranges array.
withDirectionAn I/O direction to be associated with the descriptor, which may affect the operation of the prepare and complete methods on some architectures.
asReferenceIf false, the IOMemoryDescriptor object will make a copy of the ranges array, otherwise, the array will be used in situ, avoiding an extra allocation.
Result: true on success, false on failure.

initWithRanges

Abstract: Initialize or reinitialize an IOMemoryDescriptor to describe one or more virtual ranges.
public:

virtual bool initWithRanges( IOVirtualRange * ranges, UInt32 withCount, IODirection withDirection, task_t withTask, bool asReference = false) = 0;

This method initializes an IOMemoryDescriptor for memory consisting of an array of virtual memory ranges each mapped into a specified source task. An IOMemoryDescriptor can be re-used by calling initWithAddress or initWithRanges again on an existing instance -- note this behavior is not commonly supported in other IOKit classes, although it is supported here.

Parameters

NameDescription
rangesAn array of IOVirtualRange structures which specify the virtual ranges in the specified map which make up the memory to be described.
withCountThe member count of the ranges array.
withDirectionAn I/O direction to be associated with the descriptor, which may affect the operation of the prepare and complete methods on some architectures.
withTaskThe task each of the virtual ranges are mapped into.
asReferenceIf false, the IOMemoryDescriptor object will make a copy of the ranges array, otherwise, the array will be used in situ, avoiding an extra allocation.
Result: true on success, false on failure.

map

Abstract: Maps a IOMemoryDescriptor into the kernel map.
public:

virtual IOMemoryMap * map( IOOptionBits options = 0 );

This is a shortcut method to map all the memory described by a memory descriptor into the kernel map at any available address. See the full version of the map method for further details.

Parameters

NameDescription
optionsMapping options as in the full version of the map method, with kIOMapAnywhere assumed.
Result: See the full version of the map method.

map

Abstract: Maps a IOMemoryDescriptor into a task.
public:

virtual IOMemoryMap * map( task_t intoTask, IOVirtualAddress atAddress, IOOptionBits options, IOByteCount offset = 0, IOByteCount length = 0 );

This is the general purpose method to map all or part of the memory described by a memory descriptor into a task at any available address, or at a fixed address if possible. Caching & read-only options may be set for the mapping. The mapping is represented as a returned reference to a IOMemoryMap object, which may be shared if the mapping is compatible with an existing mapping of the IOMemoryDescriptor. The IOMemoryMap object returned should be released only when the caller has finished accessing the mapping, as freeing the object destroys the mapping.

Parameters

NameDescription
intoTaskSets the target task for the mapping. Pass kernel_task for the kernel address space.
atAddressIf a placed mapping is requested, atAddress specifies its address, and the kIOMapAnywhere should not be set. Otherwise, atAddress is ignored.
optionsMapping options are defined in IOTypes.h,
kIOMapAnywhere should be passed if the mapping can be created anywhere. If not set, the atAddress parameter sets the location of the mapping, if it is available in the target map.
kIOMapDefaultCache to inhibit the cache in I/O areas, kIOMapCopybackCache in general purpose RAM.
kIOMapInhibitCache, kIOMapWriteThruCache, kIOMapCopybackCache to set the appropriate caching.
kIOMapReadOnly to allow only read only accesses to the memory - writes will cause and access fault.
kIOMapReference will only succeed if the mapping already exists, and the IOMemoryMap object is just an extra reference, ie. no new mapping will be created.
offsetIs a beginning offset into the IOMemoryDescriptor's memory where the mapping starts. Zero is the default to map all the memory.
lengthIs the length of the mapping requested for a subset of the IOMemoryDescriptor. Zero is the default to map all the memory.
Result: A reference to an IOMemoryMap object representing the mapping, which can supply the virtual address of the mapping and other information. The mapping may be shared with multiple callers - multiple maps are avoided if a compatible one exists. The IOMemoryMap object returned should be released only when the caller has finished accessing the mapping, as freeing the object destroys the mapping. The IOMemoryMap instance also retains the IOMemoryDescriptor it maps while it exists.

prepare

Abstract: Prepare the memory for an I/O transfer.
public:

virtual IOReturn prepare(IODirection forDirection = kIODirectionNone) = 0;

This involves paging in the memory, if necessary, and wiring it down for the duration of the transfer. The complete() method completes the processing of the memory after the I/O transfer finishes. This method needn't called for non-pageable memory.

Parameters

NameDescription
forDirectionThe direction of the I/O just completed, or kIODirectionNone for the direction specified by the memory descriptor.
Result: An IOReturn code.

readBytes

Abstract: Copy data from the memory descriptor's buffer to the specified buffer.
public:

virtual IOByteCount readBytes(IOByteCount offset, void * bytes, IOByteCount withLength) = 0;

This method copies data from the memory descriptor's memory at the given offset, to the caller's buffer.

Parameters

NameDescription
offsetA byte offset into the memory descriptor's memory.
bytesThe caller supplied buffer to copy the data to.
withLengthThe length of the data to copy.
Result: The number of bytes copied, zero will be returned if the specified offset is beyond the length of the descriptor.

setMapping

Abstract: Establishes an already existing mapping.
public:

virtual IOMemoryMap * setMapping( task_t task, IOVirtualAddress mapAddress, IOOptionBits options = 0 );

This method tells the IOMemoryDescriptor about a mapping that exists, but was created elsewhere. It allows later callers of the map method to share this externally created mapping. The IOMemoryMap object returned is created to represent it. This method is not commonly needed.

Parameters

NameDescription
taskAddress space in which the mapping exists.
mapAddressVirtual address of the mapping.
optionsCaching and read-only attributes of the mapping.
Result: A IOMemoryMap object created to represent the mapping.

setTag

Abstract: Set the tag for the memory descriptor.
public:

virtual void setTag( IOOptionBits tag );

This method sets the tag for the memory descriptor. Tag bits are not interpreted by IOMemoryDescriptor.

Parameters

NameDescription
tagThe tag.

withAddress

Abstract: Create an IOMemoryDescriptor to describe one virtual range of the specified map.
public:

static IOMemoryDescriptor * withAddress(vm_address_t address, IOByteCount withLength, IODirection withDirection, task_t withTask);

This method creates and initializes an IOMemoryDescriptor for memory consisting of a single virtual memory range mapped into the specified map.

Parameters

NameDescription
addressThe virtual address of the first byte in the memory.
withLengthThe length of memory.
withDirectionAn I/O direction to be associated with the descriptor, which may affect the operation of the prepare and complete methods on some architectures.
withTaskThe task the virtual ranges are mapped into.
Result: The created IOMemoryDescriptor on success, to be released by the caller, or zero on failure.

withAddress

Abstract: Create an IOMemoryDescriptor to describe one virtual range of the kernel task.
public:

static IOMemoryDescriptor * withAddress(void * address, IOByteCount withLength, IODirection withDirection);

This method creates and initializes an IOMemoryDescriptor for memory consisting of a single virtual memory range mapped into the kernel map.

Parameters

NameDescription
addressThe virtual address of the first byte in the memory.
withLengthThe length of memory.
withDirectionAn I/O direction to be associated with the descriptor, which may affect the operation of the prepare and complete methods on some architectures.
Result: The created IOMemoryDescriptor on success, to be released by the caller, or zero on failure.

withPhysicalAddress

Abstract: Create an IOMemoryDescriptor to describe one physical range.
public:

static IOMemoryDescriptor * withPhysicalAddress( IOPhysicalAddress address, IOByteCount withLength, IODirection withDirection );

This method creates and initializes an IOMemoryDescriptor for memory consisting of a single physical memory range.

Parameters

NameDescription
addressThe physical address of the first byte in the memory.
withLengthThe length of memory.
withDirectionAn I/O direction to be associated with the descriptor, which may affect the operation of the prepare and complete methods on some architectures.
Result: The created IOMemoryDescriptor on success, to be released by the caller, or zero on failure.

withPhysicalRanges

Abstract: Create an IOMemoryDescriptor to describe one or more physical ranges.
public:

static IOMemoryDescriptor * withPhysicalRanges( IOPhysicalRange * ranges, UInt32 withCount, IODirection withDirection, bool asReference = false);

This method creates and initializes an IOMemoryDescriptor for memory consisting of an array of physical memory ranges.

Parameters

NameDescription
rangesAn array of IOPhysicalRange structures which specify the physical ranges which make up the memory to be described.
withCountThe member count of the ranges array.
withDirectionAn I/O direction to be associated with the descriptor, which may affect the operation of the prepare and complete methods on some architectures.
asReferenceIf false, the IOMemoryDescriptor object will make a copy of the ranges array, otherwise, the array will be used in situ, avoiding an extra allocation.
Result: The created IOMemoryDescriptor on success, to be released by the caller, or zero on failure.

withRanges

Abstract: Create an IOMemoryDescriptor to describe one or more virtual ranges.
public:

static IOMemoryDescriptor * withRanges(IOVirtualRange * ranges, UInt32 withCount, IODirection withDirection, task_t withTask, bool asReference = false);

This method creates and initializes an IOMemoryDescriptor for memory consisting of an array of virtual memory ranges each mapped into a specified source task.

Parameters

NameDescription
rangesAn array of IOVirtualRange structures which specify the virtual ranges in the specified map which make up the memory to be described.
withCountThe member count of the ranges array.
withDirectionAn I/O direction to be associated with the descriptor, which may affect the operation of the prepare and complete methods on some architectures.
withTaskThe task each of the virtual ranges are mapped into.
asReferenceIf false, the IOMemoryDescriptor object will make a copy of the ranges array, otherwise, the array will be used in situ, avoiding an extra allocation.
Result: The created IOMemoryDescriptor on success, to be released by the caller, or zero on failure.

withSubRange

Abstract: Create an IOMemoryDescriptor to describe a subrange of an existing descriptor.
public:

static IOMemoryDescriptor * withSubRange(IOMemoryDescriptor * of, IOByteCount offset, IOByteCount length, IODirection withDirection);

This method creates and initializes an IOMemoryDescriptor for memory consisting of a subrange of the specified memory descriptor. The parent memory descriptor is retained by the new descriptor.

Parameters

NameDescription
ofThe parent IOMemoryDescriptor of which a subrange is to be used for the new descriptor, which will be retained by the subrange IOMemoryDescriptor.
offsetA byte offset into the parent memory descriptor's memory.
lengthThe length of the subrange.
withDirectionAn I/O direction to be associated with the descriptor, which may affect the operation of the prepare and complete methods on some architectures. This is used over the direction of the parent descriptor.
Result: The created IOMemoryDescriptor on success, to be released by the caller, or zero on failure.

writeBytes

Abstract: Copy data to the memory descriptor's buffer from the specified buffer.
public:

virtual IOByteCount writeBytes(IOByteCount offset, const void * bytes, IOByteCount withLength) = 0;

This method copies data to the memory descriptor's memory at the given offset, from the caller's buffer.

Parameters

NameDescription
offsetA byte offset into the memory descriptor's memory.
bytesThe caller supplied buffer to copy the data from.
withLengthThe length of the data to copy.
Result: The number of bytes copied, zero will be returned if the specified offset is beyond the length of the descriptor.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOMemoryMap

IOMemoryMap



Member Functions

getAddressTask

Abstract: Accessor to the task of the mapping.
public:

virtual task_t getAddressTask() = 0;

This method returns the mach task the mapping exists in.

Result: A mach task_t.

getLength

Abstract: Accessor to the length of the mapping.
public:

virtual IOByteCount getLength() = 0;

This method returns the length of the mapping.

Result: A byte count.

getMapOptions

Abstract: Accessor to the options the mapping was created with.
public:

virtual IOOptionBits getMapOptions() = 0;

This method returns the options to IOMemoryDescriptor::map the mapping was created with.

Result: Options for the mapping, including cache settings.

getMemoryDescriptor

Abstract: Accessor to the IOMemoryDescriptor the mapping was created from.
public:

virtual IOMemoryDescriptor * getMemoryDescriptor() = 0;

This method returns the IOMemoryDescriptor the mapping was created from.

Result: An IOMemoryDescriptor reference, which is valid while the IOMemoryMap object is retained. It should not be released by the caller.

getPhysicalAddress

Abstract: Return the physical address of the first byte in the mapping.
public:

inline IOPhysicalAddress getPhysicalAddress() { return( getPhysicalSegment( 0, 0 )); }

This method returns the physical address of the first byte in the mapping. It is most useful on mappings known to be physically contiguous.

Result: A physical address.

getPhysicalSegment

Abstract: Break a mapping into its physically contiguous segments.
public:

virtual IOPhysicalAddress getPhysicalSegment(IOByteCount offset, IOByteCount * length) = 0;

This method returns the physical address of the byte at the given offset into the mapping, and optionally the length of the physically contiguous segment from that offset. It functions similarly to IOMemoryDescriptor::getPhysicalSegment.

Parameters

NameDescription
offsetA byte offset into the mapping whose physical address to return.
lengthIf non-zero, getPhysicalSegment will store here the length of the physically contiguous segement at the given offset.
Result: A physical address, or zero if the offset is beyond the length of the mapping.

getVirtualAddress

Abstract: Accessor to the virtual address of the first byte in the mapping.
public:

virtual IOVirtualAddress getVirtualAddress() = 0;

This method returns the virtual address of the first byte in the mapping.

Result: A virtual address.

unmap

Abstract: Force the IOMemoryMap to unmap, without destroying the object.
public:

virtual IOReturn unmap() = 0;

IOMemoryMap instances will unmap themselves upon free, ie. when the last client with a reference calls release. This method forces the IOMemoryMap to destroy the mapping it represents, regardless of the number of clients. It is not generally used.

Result: An IOReturn code.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IONetworkController.h

IONetworkController.h



Typedefs

IONetworkAction

typedef UInt32 (OSObject::*IONetworkAction)(void * arg0,
                                            void * arg1,
                                            void * arg2,
                                            void * arg3);

Prototype for an action passed to syncRequest().

Parameters

NameDescription
arg0Action argument.
arg1Action argument.
arg2Action argument.
arg3Action argument.

IOPacketBufferConstraints

typedef  struct  {
  UInt32  alignStart;
  UInt32  alignLength;
  UInt32  maxLength;
}  IOPacketBufferConstraints;

Constraint parameters used by allocatePacket() to align the memory buffer associated with a mbuf.

Fields

NameDescription
alignStartAlignment for the buffer's starting address.
alignLengthBuffer length alignment.
maxLengthMaximum buffer size (not implemented).

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IONetworkController

IONetworkController



Member Functions

allocateNetworkInterface

protected:

virtual IONetworkInterface * allocateNetworkInterface() = 0;

Allocate and return a new IONetworkInterface. This method is called by attachNetworkInterface() to perform the allocation of a new interface client object. A family specific subclass of IONetworkController must implement this method and return a matching interface instance. For example, IOEthernetController implements this method and returns an IOEthernetInterface when called.

Result: The allocated interface object.

allocateOutputQueue

protected:

virtual IOOutputQueue * allocateOutputQueue();

Called by start() to allocate an IOOutputQueue instance. The default implementation will always return 0, hence no output queue will be created. A driver may override this method and return a subclass of IOOutputQueue. IONetworkController will keep a reference to the queue created, and will also release the object when IONetworkController is freed. Also see getOutputQueue().

Result: A newly allocated and initialized IOOutputQueue instance.

allocatePacket

protected:

virtual struct mbuf * allocatePacket(UInt size);

Allocate a mbuf packet with the given size. This method will always return a single mbuf unless the size requested (plus the alignment padding) is greater than MCLBYTES. The mbuf (or a mbuf chain) returned is aligned according to the constraints obtained through getPacketBufferConstraints().

The m_len and pkthdr.len fields in the mbuf is updated by this function, thus allowing the packet to be directly passed to an IOMbufMemoryCursor object.

Parameters

NameDescription
sizeThe size of the mbuf packet.
Result: The allocated mbuf packet, or 0 if allocation failed.

attachNetworkInterface

protected:

virtual bool attachNetworkInterface(IONetworkInterface ** interface, bool doRegister = true);

Allocate a new interface object and attach it to the controller as a client. The allocateNetworkInterface() method is called to allocate the new interface instance, followed by a call to configureNetworkInterface() to configure the interface. Both of these methods can be overridden by subclasses to change the type of interface client attached. Drivers must call this from its start() method, after it is ready to service requests from its soon to be attached interface client.

Parameters

NameDescription
interfaceIf successful (return value is true), then the interface object will be written to the handle provided by the caller.
doRegisterIf the doRegister argument is true, then the interface's registerService() is called to register the object, which will trigger the matching process, and cause client object to attach to the interface. For drivers that wish to delay the registration, and hold off the interface clients, set doRegister to false and call registerService() when both the controller and interface object are ready to handle client requests.
Result: true on success, false otherwise.

broadcastEvent

protected:

virtual bool broadcastEvent(UInt32 type, void * arg = 0);

Broadcast an event to all attached interface objects. This is equivalent to calling the IONetworkInterface::inputEvent() method for all interfaces. This method may block.

IONetworkController uses this method to broadcast link and media events. Drivers will usually call the inputEvent() method directly since it is more efficient, and most drivers will only attach a single interface.

Parameters

NameDescription
typeEvent type. See IONetworkInterface.
argEvent argument. See IONetworkInterface.
Result: true if the event was delivered, false if an error occurred (unable to allocate memory to create objects) and the event was not delivered.

configureNetworkInterface

protected:

virtual bool configureNetworkInterface(IONetworkInterface * netif);

Configure a network interface allocated through allocateNetworkInterface(). IONetworkController will register the output handler with the interface object provided. Subclasses may override this method to customize the interface object. Once the interface is registered and opened by a client, it will refuse changes to its properties. But since this method is called before the interface has been registered, this is an opportunity for the controller to configure the interface.

Parameters

NameDescription
netifThe interface object to be configured.
Result: true if configuration was successful, false otherwise.

copyPacket

protected:

virtual struct mbuf * copyPacket(const struct mbuf * m, UInt size = 0);

Make a copy of a mbuf, and return the copy. The source mbuf is not modified.

Parameters

NameDescription
mThe source mbuf.
sizeThe number of bytes to copy. If set to 0, then the entire source mbuf is copied.
Result: A new mbuf created from the source packet.

detachNetworkInterface

protected:

virtual void detachNetworkInterface(IONetworkInterface * interface);

Detach the interface object asynchronously. This method will check that the object provided is indeed an IONetworkInterface, and if so its terminate() method is called. The interface object will close and detach from its controller only after the network layer has removed all references to the registered interface.

Parameters

NameDescription
interfaceAn interface object to be detached.

disable

protected:

virtual IOReturn disable(IOService * client);

Handle a disable request from a client. The client is typecasted using OSDynamicCast(), and depending on the type, an disable(IONetworkInterface *) is called for an interface client, a handleDebuggerClose(IOKernelDebugger *) is called for a debugger client, or an kIOReturnBadArgument is returned for any other type.

Parameters

NameDescription
clientThe client object that requested the disable.
Result: The return from the dispatched methods, or kIOReturnBadArgument if the client's type is unknown.

disable

protected:

virtual IOReturn disable(IONetworkInterface * netif);

Called by the interface object to disable the controller. Drivers must override this method and shutdown the hardware and disable interrupt sources. Any resources allocated in enable() should also be deallocated.

Parameters

NameDescription
netifThe interface object that requested the disable.
Result: kIOReturnUnsupported. Driver may override this method and return kIOReturnSuccess upon success, or an error code otherwise.

disableSyncRequest

protected:

virtual bool disableSyncRequest();

Prevent syncRequest() from handling synchronous requests.

Result: The previous state.

enable

protected:

virtual IOReturn enable(IONetworkInterface * netif);

Called by the interface object to enable the controller. Drivers must override this method and prepare the hardware and interrupt sources to allow packet transmission and reception. The driver should delay the allocation of most runtime resources until this method is called to conserve system resources.

Parameters

NameDescription
netifThe interface object that requested the enable.
Result: kIOReturnUnsupported. Driver may override this method and return kIOReturnSuccess upon success, or an error code otherwise.

enable

protected:

virtual IOReturn enable(IOService * client);

Handle an enable request from a client. The client is typecasted using OSDynamicCast(), and depending on the type, an enable(IONetworkInterface *) is called for an interface client, a handleDebuggerOpen(IOKernelDebugger *) is called for a debugger client, or an kIOReturnBadArgument is returned for any other type.

Parameters

NameDescription
clientThe client object that requested the enable.
Result: The return from the dispatched methods, or kIOReturnBadArgument if the client's type is unknown.

enablePacketFilters

protected:

virtual IOReturn enablePacketFilters(UInt32 filters, UInt32 * activeFiltersP) = 0;

After calling getPacketFilters() to gather the set of supported packet filters. A client may issue a request to enable a group of filters from the supported set.

Parameters

NameDescription
filtersEach bit set indicates a particular filter that should be enabled. Filter bits that are not turned on must be disabled.
activeFiltersPUpdated by this method to reflect the real set of active filters. Ideally, it should be the same as the set specified by the first argument.
Result: kIOReturnSuccess on success, otherwise an error code is returned. If *activeFiltersP != filters, then an error must be retuned.

enableSyncRequest

protected:

virtual bool enableSyncRequest();

Enable syncRequest() to handle synchronous requests. By default, syncRequest() is always enabled unless a call is made to disableSyncRequest().

Result: The previous state.

flushOutputQueue

protected:

virtual IOReturn flushOutputQueue(UInt32 * flushCountP);

A client request to flush all packets currently held by the queue, and return the number of packets discarded. If an IOOutputQueue was allocated, and this method does not return kIOReturnSuccess, then this request will be handled by the queue object.

Parameters

NameDescription
flushCountPPointer to an integer where the number of packets discarded should be written to.
Result: kIOReturnUnsupported. Drivers may override this method and return kIOReturnSuccess.

free

protected:

virtual void free();

Free the IONetworkController instance and all allocated resources, then call super::free().


freePacket

protected:

virtual void freePacket(struct mbuf * m);

Release the mbuf back to the free pool.

Parameters

NameDescription
mThe mbuf to be freed.

getCommandGate

protected:

virtual IOCommandGate * getCommandGate() const;

An IOCommandGate is created and attached to an IOWorkLoop during start(). This IOCommandGate object is used to handle client commands issued through the syncRequest() method. Subclasses that need a IOCommandGate should use the object returned by this method, rather than creating a new instance.

Result: The internal IOCommandGate object.

getControllerIndex

protected:

virtual IOReturn getControllerIndex(UInt32 * indexP) const;

Return an ordinal for multiport network adapters. The implementation in IONetworkController will work for PCI controllers behind a PCI-PCI bridge. This method exists solely to support the current interface naming scheme, and is likely to undergo changes or may disappear in the future.

Parameters

NameDescription
indexPUpdate the ordinal via this pointer.
Result: kIOReturnSuccess.

getCurrentMedium

public:

virtual const IONetworkMedium * getCurrentMedium() const;

Return the current medium property. If the driver has yet to assign an entry in its medium dictionary as the current medium. Then the driver's property table is consulted and a default medium property, which can be set by the user, is looked up and returned as the current medium. Thus drivers can call getCurrentMedium() after publishing a medium dictionary to get the default medium selected by the user. However, if the medium selected by the user does not match any entries found in the dictionary, then 0 is returned.

Result: An entry in the medium dictionary that is the current medium.

getFamilyFeatureSet

public:

virtual UInt32 getFamilyFeatureSet() const = 0;

Report family specific features supported by the controller.

Result: Drivers may override this method and return a mask of all supported family defined feature sets.

getFeatureSet

public:

virtual UInt32 getFeatureSet() const;

Report features supported by the controller.

Result: Returns 0. Drivers may override this method and return a mask of all supported feature sets.

getInfoString

public:

virtual const char * getInfoString() const;

Result: Return a string containing any additional information about the controller and/or driver.

getMediumDictionary

public:

virtual const OSDictionary * getMediumDictionary() const;

Return the medium dictionary from the property table. See mediumDictionary() to obtain a copy of the dictionary instead.

Result: The medium dictionary, or 0 if the driver never published a medium dictionary through setMediumDictionary().

getModelString

public:

virtual const char * getModelString() const = 0;

Result: Return a string describing the model of the network controller. i.e. "BMac"

getOutputHandler

public:

void getOutputHandler(IOOutputHandler * handlerP) const;

Given a pointer to an IOOutputHandler structure provided by the caller, this method will initialize the structure, and thus exposing the controller method responsible for handling the output packets (outputPacket), and also the method responsible for handling interface requests (requestHandler).

Parameters

NameDescription
handlerPPointer to an IOOutputHandler structure. See IONetworkInterface.

getOutputQueue

protected:

virtual IOOutputQueue * getOutputQueue() const;

Result: Return the output queue allocated though allocateOutputQueue().

getOutputQueueCapacity

protected:

virtual IOReturn getOutputQueueCapacity(UInt32 * capacityP) const;

A client request to fetch the capacity of the output queue. If an IOOutputQueue was allocated, and this method does not return kIOReturnSuccess, then this request will be handled by the queue object.

Parameters

NameDescription
capacityPPointer to an integer where the current capacity should be written to.
Result: kIOReturnUnsupported. Drivers may override this method and return kIOReturnSuccess.

getOutputQueueSize

protected:

virtual IOReturn getOutputQueueSize(UInt32 * size) const;

A client request to fetch the number of packets currently held by the queue. If an IOOutputQueue was allocated, and this method does not return kIOReturnSuccess, then this request will be handled by the queue object.

Parameters

NameDescription
sizePPointer to an integer where the size should be written to.
Result: kIOReturnUnsupported. Drivers may override this method and return kIOReturnSuccess.

getPacketBufferConstraints

protected:

virtual void getPacketBufferConstraints( IOPacketBufferConstraints * constraintsP) const;

Called by start() to obtain the constraints on the memory buffer associated with each mbuf allocated through allocatePacket(). Drivers can override this method to specify their buffer constraints that are usually imposed by their bus master hardware. Note that outbound packets, originating from the network stack, are not subject to the constraints reported here.

Parameters

NameDescription
constraintsPA pointer to an IOPacketBufferConstraints structure allocated by the caller that the receiver is expected to initialize. See IOPacketBufferConstraints structure definition for additional information.

getPacketFilters

protected:

virtual IOReturn getPacketFilters(UInt32 * filtersP) = 0;

Obtain the set of packet filters supported by the controller. See IOPacketFilter enum for the list of defined packet filters. A subclass must implement this method and write its set of supported filters, formed by OR'ing the defined filter constants.

Parameters

NameDescription
filtersPPointer to an integer that the filter set should be written to.
Result: kIOReturnSuccess on success, or an error code to indicate failure to discover the available filters.

getRevisionString

public:

virtual const char * getRevisionString() const;

Result: Return a string describing the revision level of the network controller.

getSyncRequestSender

protected:

virtual OSObject * getSyncRequestSender() const;

For methods that are called by syncRequest(), return the sender of the request.

Result: The caller of the request is returned.

getVendorString

public:

virtual const char * getVendorString() const = 0;

Result: Return a vendor string. i.e. "Apple"

getWorkLoop

protected:

virtual IOWorkLoop * getWorkLoop() const;

An IOWorkLoop object is created by the start() method. Drivers can use this method to obtain a reference to the IOWorkLoop object created and attach their event sources, such as IOTimerEventSource or IOInterruptEventSource. See IOWorkLoop documentation.

Result: The internal IOWorkLoop object.

handleClose

protected:

virtual void handleClose(IOService * client, IOOptionBits options);

Handle a close from one of our client objects. IOService calls this method with the arbitration lock held. Subclasses should not override this method.

Parameters

NameDescription
clientThe client that has closed the controller.
optionsSee IOService.

handleIsOpen

protected:

virtual bool handleIsOpen(const IOService * client) const;

This method is always called by IOService with the arbitration lock held. Subclasses should not override this method.

Result: true if the specified client, or any client if none is specified, presently has an open on this object.

handleOpen

protected:

virtual bool handleOpen(IOService * client, IOOptionBits options, void * argument);

Handle a client open on the controller object. IOService calls this method with the arbitration lock held. Subclasses should not override this method.

Parameters

NameDescription
clientThe client that is trying to open the controller.
optionsSee IOService.
argumentSee IOService.
Result: true to accept the client open, false to refuse the open.

init

public:

virtual bool init(OSDictionary * properties);

Initialize the IONetworkController instance. Instance variables are initialized to their default values, and the init() method in superclass is called.

Parameters

NameDescription
propertiesA property table.
Result: true on success, false otherwise.

initialize

public:

static void initialize();

Class initializer for IONetworkController. Create OSSymbol objects ahead of time that are used as keys. This method is called explicitly by a line in IOStartIOKit.cpp and not by the OSDefineMetaClassAndInit() mechanism, since the OSSymbol class is not guaranteed to be initialized first, thus its OSSymbol pool may not be setup.


mediumDictionary

public:

virtual OSDictionary * mediumDictionary() const;

Return a.copy of the medium dictionary published by the driver. The caller is responsible for releasing the dictionary object returned.

Result: A copy of the medium dictionary, or 0 if the driver never published a medium dictionary through setMediumDictionary().

outputPacket

public:

virtual UInt32 outputPacket(struct mbuf * m);

Transmit the given packet mbuf. If an IOOutputQueue was allocated and returned in allocateOutputQueue(), then this method will be called by a queue object. Otherwise, an interface object will call this method directly upon receiving an output packet from the network layer. When a queue is not present, the controller driver must assume that several threads may call this method simultaneously, thus it must implement some form of locking to enforce serialization.

There is no upper limit on the length of the mbuf chain provided. Drivers must be able to handle cases when the chain exceeds the limit dictated by their DMA engines, and perform coalescing to copy the various memory fragments into a smaller number of fragments. All this complexity can be hidden when an IOMBufMemoryCursor is used, which will convert a mbuf chain into a scatter-gather list that is guaranteed never to exceed a given size.

Packets may also be chained to form a packet chain. Although the interface object (network layer) will currently only send a single packet to the controller for each outputPacket() call, it is possible for this to change. When a queue object is used, the queue will absorb the packet or packet chain, but it will always send a single packet to the controller. When a queue is not used, drivers should take this into consideration.

The implementation in IONetworkController performs no useful action and will drop all packets. Subclasses are expected to override this method.

Parameters

NameDescription
mThe packet mbuf.
Result: A return code defined by the caller.

performDiagnostics

protected:

virtual IOReturn performDiagnostics(UInt32 * failureCode);

Called by clients to request the hardware to perform diagnostics and return the test result.

Parameters

NameDescription
failureCodeIn addition to the return code, drivers may return a hardware specific failure code via the pointer provided.
Result: kIOReturnSuccess if hardware passed all test, otherwise an appropriate error code should be returned.

publishCapabilities

protected:

virtual bool publishCapabilities();

Discover and publish controller capabilities and publish them to the property table.

Result: true if all capabilities were discovered and published successfully, false otherwise.

publishParameters

public:

virtual void publishParameters(OSDictionary * paramDict);

Controller drivers can publish custom network parameters by adding their IONetworkParameter object(s) to the dictionary provided. The interface object will call this method after publishing its own parameters. The implementation in IONetworkController does nothing.

Parameters

NameDescription
paramDictDictionary provided by the interface object.

ready

protected:

virtual bool ready(IOService * provider);

This method is called the first time that a controller driver calls attachNetworkInterface(), which is an indication that the driver has been started and is ready to service client requests. IONetworkController uses this method to complete its initialization before providing services to client objects. This method will always run on the workloop thread.

Parameters

NameDescription
providerThe controller's provider object.
Result: true on success, false otherwise.

replaceOrCopyPacket

protected:

virtual struct mbuf * replaceOrCopyPacket(struct mbuf ** mp, UInt rcvlen, bool * replacedP);

Either replace or copy the source mbuf given depending on the amount of data in the source mbuf. This method will either perform a copy or replace the source mbuf, whichever is more time efficient. If replaced, then the original mbuf is returned, and a new mbuf is allocated to take its place. If copied, the source mbuf is left intact, while a copy is returned that is just big enough to hold the data from the source mbuf.

Parameters

NameDescription
mpA pointer to the source mbuf that may be updated by this method to point to the new mbuf if replaced.
rcvlenThe number of data bytes in the source mbuf.
replacedPPointer to a bool that is set by this method to true if the source mbuf was replaced, false if the source mbuf was copied.
Result: A replacement or a copy of the source mbuf, 0 if mbuf allocation failed.

replacePacket

protected:

virtual struct mbuf * replacePacket(struct mbuf ** mp, UInt size = 0);

Replace the mbuf pointed by the pointer provided with another mbuf. Drivers can call this method to replace a mbuf before passing the original mbuf, which contains a received frame, to the network layer.

Parameters

NameDescription
mpA pointer to the original mbuf that shall be updated by this method to point to the new mbuf.
sizeIf size is 0, then the new mbuf shall have the same size as the original mbuf that is being replaced. Otherwise, the new mbuf shall have the size specified.
Result: If mbuf allocation was successful, then the replacement will take place and the original mbuf will be returned. Otherwise, a NULL is returned.

requestHandler

public:

virtual IOReturn requestHandler(OSObject * sender, UInt32 request, void * arg0 = 0, void * arg1 = 0, void * arg2 = 0, void * arg3 = 0);

Handles client requests. Most requests will require participation by the hardware, and thus will cause driver methods to be called via the syncRequest() method, to ensure single threaded access to the hardware.

Parameters

NameDescription
senderThe sender of the request.
requestThe request type.
arg0Request argument.
arg1Request argument.
arg2Request argument.
arg3Request argument.
Result: kIOReturnSuccess if the request was handled successfully, otherwise an error code is returned.

setCurrentMedium

protected:

virtual bool setCurrentMedium(const IONetworkMedium * medium);

From the set of medium objects in the medium dictionary published by the driver (through setMediumDictionary), one can be assigned as the "current" medium, to designate it as the currently selected medium. Drivers should call this method whenever the driver changes its media selection.

An media change event will be broadcasted to interface clients when the current medium property changes.

Parameters

NameDescription
mediumA medium object to promote as the current medium.
Result: true if the medium dictionary exists, the medium object provided is the same as an entry in the dictionary, and the update was successful, false otherwise.

setLinkStatus

protected:

virtual bool setLinkStatus(UInt32 status, UInt64 speed, const IONetworkMedium * activeMedium, OSData * data = 0);

Update the link status parameters published by the controller. Drivers should call this method whenever the link status changes. Never call this method from the interrupt context since this method may block. An event will be sent to all attached interface objects when a change is detected.

Parameters

NameDescription
statusSee IONetworkMedium.h for defined link status bits.
speedLink speed in units of bits per second.
activeMediumThe medium where the link is established. This may not be the same as the current medium.
dataAn arbitrary OSData object containing additional information about the link status.
Result: true if all link properties were successfully updated, false otherwise.

setMaxTransferUnit

protected:

virtual IOReturn setMaxTransferUnit(UInt32 mtu);

A client request for the controller to switch to a new MTU size. This method is called only if the current MTU size advertised by the interface does not match the new size requested.

Parameters

NameDescription
mtuThe new MTU size requested.
Result: kIOReturnUnsupported. Drivers that override this method should return kIOReturnSuccess to indicate that the new MTU size was accepted and is in effect.

setMedium

protected:

virtual IOReturn setMedium(const IONetworkMedium * medium);

A client request for the controller to change the medium currently used. Drivers may override this method and provide an implementation appropriate for its hardware, then call setCurrentMedium() to update the current medium property.

Parameters

NameDescription
mediumA medium object in the published medium dictionary.
Result: kIOReturnUnsupported. Drivers may override this method and return kIOReturnSuccess if the change was performed successfully.

setMediumDictionary

protected:

virtual bool setMediumDictionary(const OSDictionary * mediumDict);

This method is called by drivers to publish a dictionary containing IONetworkMedium objects. Each entry in this dictionary corresponds to a medium supported by the controller. The dictionary is added to the property table, and the caller can release the dictionary after this method returns. It is permissible to call this method multiple times, in case the hardware's media capability changes dynamically. Otherwise, drivers should call this method only once in its start() implementation.

Several methods depends on the presence of a medium dictionary. Those methods are: setMedium() setCurrentMedium() getCurrentMedium() getMediumDictionary() mediumDictionary()

This method will broadcast a media change event to all attached interface clients.

Parameters

NameDescription
mediumDictDictionary provided by the caller that has been populated with IONetworkMedium objects.
Result: true if the dictionary and its entries are valid, and the dictionary was added to the property table, false otherwise.

setOutputQueueCapacity

protected:

virtual IOReturn setOutputQueueCapacity(UInt32 capacity);

A client request to adjust the capacity of the driver's output queue (number of packets the queue can hold). If an IOOutputQueue was allocated, and this method does not return kIOReturnSuccess, then this request will be handled by the queue object.

Parameters

NameDescription
capacityThe new capacity of the output queue.
Result: kIOReturnUnsupported. Drivers may override this method and return kIOReturnSuccess if the new capacity was accepted.

start

public:

virtual bool start(IOService * provider);

Called when the controller was matched to a provider and has been selected to begin running. IONetworkController will allocate resources and call several methods to gather the controller's characteristics. None of those calls should generate any I/O. Subclasses must override this method and call super::start() at the beginning of its implementation.

Parameters

NameDescription
providerThe provider that the controller was matched (and attached) to.
Result: true on success, false otherwise.

stop

public:

void stop(IOService * provider);

The opposite of start(). The controller has been instructed to stop running. This method should release resources and undo actions performed by start(). Subclasses must override this method and call super::stop() at the end of its implementation.

Parameters

NameDescription
providerThe provider that the controller was matched (and attached) to.

syncRequest

public:

virtual IOReturn syncRequest(OSObject * sender, OSObject * target, IONetworkAction action, UInt32 * ret = 0, void * arg0 = 0, void * arg1 = 0, void * arg2 = 0, void * arg3 = 0);

Instruct the internal IOCommandGate object to call the member function provided. The function called by the IOCommandGate and any other actions called by event source attached to the same workloop will run in a mutually exclusive fashion.

Parameters

NameDescription
senderThe sender of the synchronous request.
targetThe target object that implements the action.
actionThe action to perform.
retThe return value from the action.
arg0Action argument.
arg1Action argument.
arg2Action argument.
arg3Action argument.
Result: kIOReturnSuccess on success, kIOReturnNotReady if syncRequest() was refused to handle the request.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IONetworkInterface.h

IONetworkInterface.h



Typedefs

BPF_FUNC

typedef  int  (*BPF_FUNC)(struct  ifnet  *,  struct  mbuf  *);

Prototype of the BPF tap handler. This will disappear when the appropriate DLIL header file is included.


IOOutputAction

typedef UInt32 (OSObject::*IOOutputAction)(struct mbuf * m);

Prototype for an output packet handler that will receive all outbound packets sent to the interface from the network layer. This handler is registered by calling registerOutputHandler().

Parameters

NameDescription
mA packet mbuf.

IOOutputHandler

typedef  struct
{
  OSObject  *  target;
  IOOutputAction  output;
  IORequestAction  request;
}  IOOutputHandler;

A structure that encapsulates information about a target and its output packet and request handlers.

Fields

NameDescription
targetThe target object that implements the handlers.
outputAn IOOutputAction handler.
outputAn IORequestAction handler.

IORequestAction

typedef IOReturn (OSObject::*IORequestAction)(OSObject * sender,
                                              UInt32     type,
                                              void *     arg0,
                                              void *     arg1,
                                              void *     arg2,
                                              void *     arg3);

Prototype for a request handler that will handle all requests originated from the interface.

Parameters

NameDescription
senderThe sender of the request. This is usually the interface object that called the handler.
typeRequest type.
arg0Request argument.
arg1Request argument.
arg2Request argument.
arg3Request argument.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IONetworkInterface

IONetworkInterface



Member Functions

attachToParent

protected:

virtual bool attachToParent(IORegistryEntry * parent, const IORegistryPlane * plane);

Called by IOService::attach() when the interface is attached to a controller. This method checks that the parent object that the interface is attached to is a type of IONetworkController.

Parameters

NameDescription
parentThe registry entry to attach to.
planeThe plane object.
Result: true on success, false otherwise.

clearInputQueue

public:

virtual UInt32 clearInputQueue();

Remove all packets in the interface's input queue and release them back to the free buffer pool. The packets are not submitted to the network layer. Also see flushInputQueue().

Result: The number of packets released.

controllerDidOpen

protected:

virtual bool controllerDidOpen(IONetworkController * controller);

Called by handleOpen() to configure the controller after it has just been opened. The open on the controller occurs after the interface receives the initial open request from a client. Subclasses can override this method and setup the controller before allowing the client open. The implementation in the subclass must call the method in super and check the return value.

Parameters

NameDescription
controllerThe controller that was opened.
Result: This method must return true in order for handleOpen() to accept the client open. If the return is false, then the controller will be closed and the client open will be rejected.

controllerWillClose

protected:

virtual void controllerWillClose(IONetworkController * controller);

Called by handleClose() after receiving a close from the last client, and before the controller is closed. Subclasses can override this method to perform any cleanup action before the controller is closed.

Parameters

NameDescription
controllerThe controller that will be closed.

feedInputFilterTap

public:

virtual void feedInputFilterTap(struct mbuf * pkt);

Feed a packet to the input filter tap. This method should not be called if the input filter tap mode is set to kIOFilterTapModeInternal, since the tap would automatically receive every input packet that flows through the interface. A call to feedInputFilterTap() under this condition would cause the tap to incorrectly receive the same packet twice.

Parameters

NameDescription
pktThe packet mbuf to pass to the input tap. The rcvif field in the mbuf is modified by this method.

feedOutputFilterTap

public:

virtual void feedOutputFilterTap(struct mbuf * pkt);

Feed a packet to the output filter tap. This method should not be called if the output filter tap mode is set to kIOFilterTapModeInternal, since the tap would automatically receive every output packet that flows through the interface. A call to feedOutputFilterTap() under this condition would cause the tap to incorrectly receive the same packet twice.

Parameters

NameDescription
pktThe packet mbuf to pass to the output tap.

flushInputQueue

public:

virtual UInt32 flushInputQueue();

Remove all packets in the interface's input queue and submit them to the network layer by calling dlil_input(). This method should be used in connection with the inputPacket() method, in order to flush the input queue after inputPacket() has queued all received packets. Also see inputPacket() and clearInputQueue().

Result: The number of packets submitted to the network layer. May be zero if the queue is empty.

free

protected:

virtual void free();

Free the IONetworkInterface instance and release allocated resources.


getExtraFlags

public:

virtual UInt32 getExtraFlags() const;

Result: The if_eflags field in the ifnet structure associated with the interface.

getFlags

public:

virtual UInt16 getFlags() const;

Result: The if_flags field in the ifnet structure associated with the interface.

getIfnet

protected:

virtual struct ifnet * getIfnet() const = 0;

Request an interface to reveal its ifnet structure. A concrete subclass must allocate an ifnet structure when the object is initialized, and return a pointer to the ifnet structure when this method is called.

Result: Pointer to an ifnet structure allocated by a concrete subclass.

getInputFilterTapMode

public:

virtual IOFilterTapMode getInputFilterTapMode() const;

Result: Returns the current mode of the input packet tap.

getInterfaceName

public:

virtual const char * getInterfaceName() const;

Result: The if_name field in the ifnet structure associated with the interface.

getInterfaceState

public:

virtual UInt32 getInterfaceState() const;

Result: Returns the current state of the interface.

getInterfaceType

public:

virtual UInt8 getInterfaceType() const;

Result: The assigned interface type that matches one of the types defined in bsd/net/if_types.h.

getMaxTransferUnit

public:

virtual UInt32 getMaxTransferUnit() const;

Result: The interface MTU size.

getMediaAddressLength

public:

virtual UInt8 getMediaAddressLength() const;

Result: The if_data.ifi_addrlen field in the ifnet structure associated with the interface.

getMediaHeaderLength

public:

virtual UInt8 getMediaHeaderLength() const;

Result: The if_data.ifi_hdrlen field in the ifnet structure associated with the interface.

getNamePrefix

public:

virtual const char * getNamePrefix() const = 0;

The name of the interface advertised to the network layer is generated by concatenating the string returned by this method, and an integer unit number assigned by an external entity. This method must be implemented by a family specific subclass.

Result: A pointer to a constant string.

getOutputFilterTapMode

public:

virtual IOFilterTapMode getOutputFilterTapMode() const;

Result: Returns the current mode of the input packet tap.

getParameter

public:

virtual IONetworkParameter * getParameter(const OSSymbol * key) const;

Search of the parameter dictionary populated through publishParameters(), and return an entry that matches the specified OSSymbol key.

Parameters

NameDescription
keySearch for an entry with this OSSymbol key.
Result: The matching entry, or 0 if no match was found.

getParameter

public:

virtual IONetworkParameter * getParameter(const char * key) const;

Perform a lookup of the parameter dictionary populated through publishParameters(), and return the entry that matches the specified string key.

Parameters

NameDescription
keySearch for an entry with this string key.
Result: The matching entry, or 0 if no match was found.

getUnitNumber

public:

virtual UInt16 getUnitNumber() const;

Result: The assigned interface unit number.

handleClientClose

protected:

virtual void handleClientClose(IONetworkController * controller, IOService * client);

Called by handleOpen() to notify that a client object has closed the interface.

Parameters

NameDescription
controllerThe controller object (provider).
clientThe client object.

handleClientOpen

protected:

virtual bool handleClientOpen(IONetworkController * controller, IOService * client);

Called by handleOpen() to qualify a client object that is attempting to open the interface.

Parameters

NameDescription
controllerThe controller object (provider).
clientThe client object.
Result: true to accept the client open, false to refuse the open.

handleClose

protected:

virtual void handleClose(IOService * client, IOOptionBits options);

Handle a close by one of our clients. The close() method in IOService calls this method with the arbitration lock held. This method will in turn call handleClientClose() and controllerWillClose(). Subclasses must not override this method.

Parameters

NameDescription
clientThe client object that requested the close.
optionsNot used. See IOService.

handleIsOpen

protected:

virtual bool handleIsOpen(const IOService * client) const;

This method is always called by IOService with the arbitration lock held. Subclasses must not override this method.

Result: true if the specified client, or any client if none is specified, presently has an open on this object.

handleOpen

protected:

virtual bool handleOpen(IOService * client, IOOptionBits options, void * argument);

Handle a client open on this object. The open() method in IOService calls this method with the arbitration lock held, and this method must return true to accept the client open. This method will in turn call handleClientOpen() and controllerDidOpen(). Subclasses must not override this method.

Parameters

NameDescription
clientThe client object that requested the open.
optionsNot used. See IOService.
argumentNot used. See IOService.
Result: true to accept the client open, false otherwise.

init

public:

virtual bool init(OSDictionary * properties = 0);

Initialize an IONetworkInterface instance.

Parameters

NameDescription
propertiesA property dictionary.
Result: true if initialized successfully, false otherwise.

initIfnet

protected:

virtual bool initIfnet(struct ifnet * ifp);

Initialize the ifnet structure. Subclasses must override this method and initialize the ifnet structure given in a family specific manner. Subclasses may use the "setter" methods such as setFlags() to initialize the ifnet fields. The implementation in the subclass must call the version in super before it returns, and allow IONetworkInterface to complete the initialization.

Parameters

NameDescription
ifpPointer to an ifnet structure obtained earlier through the getIfnet() call.
Result: true on success, false otherwise.

inputEvent

public:

virtual void inputEvent(UInt32 eventType, void * arg);

Called by the controller driver to send a defined event to the network layer. Possible applications include: media changed events, power management events, controller state change events.

Parameters

NameDescription
eventTypeThe event type.
argAn argument associated with the event type.

inputPacket

public:

virtual UInt32 inputPacket(struct mbuf * m, UInt32 length = 0, bool queuePkt = false);

Called by the controller to pass a received packet to the network layer. If the length specified is not zero, then the packet will be truncated to the given length. Packets received by this method can also be placed on a queue local to the interface, that the controller can use to delay the packet handoff to the network layer until all received packets have been transferred to the queue. A flushInputQueue(), or a inputPacket() call with 'queuePkt' argument set to false will cause any queued packets (may be a single packet) to be submitted to the network layer, by calling dlil_input() (defined by DLIL) only once. Additional methods that manipulates the input queue are flushInputQueue() and clearInputQueue(). The input queue is not protected by a lock since the controller is expected to call all methods that touches the queue from a single thread.

Parameters

NameDescription
mThe packet mbuf containing the received frame.
lengthIf non zero, the mbuf given will be truncated to the length given. If zero, then no truncation will take place.
queuePktIf true, the only action performed is to queue the input packet. Otherwise, the dlil_input() function is also called to submit any queued packets.
Result: The number of packets submitted to the network layer.

issueRequest

public:

virtual IOReturn issueRequest(OSObject * sender, UInt32 request, void * arg0 = 0, void * arg1 = 0, void * arg2 = 0, void * arg3 = 0);

Issue a request to the network controller by calling its requestHandler() method.

Parameters

NameDescription
senderThis sender of the request, usually set to 'this'.
requestThe request type.
arg0Request argument.
arg1Request argument.
arg2Request argument.
arg3Request argument.
Result: kIOReturnSuccess if the request was issued and handled successfully.

issueRequest

public:

virtual IOReturn issueRequest(UInt32 request, void * arg0 = 0, void * arg1 = 0, void * arg2 = 0, void * arg3 = 0);

Issue a request to the network controller by calling its requestHandler() method. The sender of the request is set to 'this'.

Parameters

NameDescription
requestThe request type.
arg0Request argument.
arg1Request argument.
arg2Request argument.
arg3Request argument.
Result: kIOReturnSuccess if the request was issued and handled successfully.

lock

protected:

virtual void lock();

Take the recursive lock that protects the interface data and state.


newUserClient

protected:

virtual IOReturn newUserClient(task_t owningTask, void * security_id, UInt32 type, IOUserClient ** handler);

Create a new IOUserClient to handle userspace client requests. The default implementation will create an IONetworkUserClient instance if the type given is kIONUCType.

Parameters

NameDescription
owningTaskSee IOService.
security_idSee IOService.
typeSee IOService.
handlerSee IOService.
Result: kIOReturnSuccess if an IONetworkUserClient was created.

performCommand

protected:

virtual SInt performCommand(IONetworkController * controller, UInt32 cmd, void * arg0, void * arg1);

Handles generic socket ioctl commands. IONetworkInterface handles commands that are common to all network families. A family specific subclass of IONetworkInterface may override this function in order to handle commands specific to its family. Any commands not handled in the subclass should be forwarded to its superclass. The ioctl commands handled by IONetworkInterface are SIOCGIFMTU (Get interface MTU size), SIOCSIFMTU (Set interface MTU size), SIOCSIFMEDIA (Set media), and SIOCGIFMEDIA (Get media and link status).

Parameters

NameDescription
controllerThe controller object.
cmdThe command code.
arg0Command argument.
arg1Command argument.
Result: A BSD error code defined in bsd/sys/errno.h.

publishParameters

public:

virtual void publishParameters(OSDictionary * array) const;

A dictionary is created to store IONetworkParameter objects created by IONetworkInterface and also by its subclasses. This method is called to collect those parameters, by passing the dictionary object, and allowing the receiver to add its parameter objects to the dictionary. Subclasses can override this method, but it must also call the method in super.

Parameters

NameDescription
dictThe dictionary that the receiver may use to add its IONetworkParameter objects.

registerOutputHandler

public:

virtual bool registerOutputHandler(const IOOutputHandler * handler);

Register the output handler.

Parameters

NameDescription
handlerPointer to an IOOutputHandler structure provided by the caller.
Result: true if the handler provided was accepted, false otherwise.

setExtraFlags

public:

virtual bool setExtraFlags(UInt32 flags, UInt32 clear = 0);

Perform a read-modify-write operation on the if_eflags field in the ifnet structure associated with the interface.

Parameters

NameDescription
flagsThe flags that should be set.
clearThe flags that should be cleared. If this value is 0, then no flags are cleared and the result is formed by OR'ing the original flags with the new flags.
Result: true if the current state is kStateUnregistered and the update was successful, false otherwise.

setExtraFlagsInt

protected:

virtual bool setExtraFlagsInt(UInt32 flags, UInt32 clear = 0);

Perform a read-modify-write operation on the if_eflags field in the ifnet structure associated with the interface.

Parameters

NameDescription
flagsThe flags that should be set.
clearThe flags that should be cleared. If this value is 0, then no flags are cleared and the result is formed by OR'ing the original flags with the new flags.
Result: true if the update was successful, false otherwise.

setFlags

public:

virtual bool setFlags(UInt16 flags, UInt16 clear = 0);

Performs a read-modify-write operation on the if_flags field in the ifnet structure associated with the interface.

Parameters

NameDescription
flagsThe flags that should be set.
clearThe flags that should be cleared. If this value is 0, then no flags are cleared and the result is formed by OR'ing the original flags with the new flags.
Result: true if the current state is kStateUnregistered and the update was successful, false otherwise.

setFlagsInt

protected:

virtual bool setFlagsInt(UInt16 flags, UInt16 clear = 0);

Performs a read-modify-write operation on the if_flags field in the ifnet structure associated with the interface.

Parameters

NameDescription
flagsThe flags that should be set.
clearThe flags that should be cleared. If this value is 0, then no flags are cleared and the result is formed by OR'ing the original flags with the new flags.
Result: true if the update was successful, false otherwise.

setInputFilterTapMode

public:

virtual bool setInputFilterTapMode(IOFilterTapMode mode);

Set the mode of the input packet tap, to specify how the tap will connect to the input packet flow once the tap becomes enabled. See IOFilterTapMode enumeration.

Parameters

NameDescription
Thenew mode.
Result: true if the new mode was accepted, false otherwise.

setInterfaceName

public:

virtual bool setInterfaceName(const char * name);

Parameters

NameDescription
nameThe new value for the if_name field in the ifnet structure associated with the interface.
Result: true if the current state is kStateUnregistered and the update was successful, false otherwise.

setInterfaceNameInt

protected:

virtual bool setInterfaceNameInt(const char * name);

Parameters

NameDescription
nameThe new value for the if_name field in the ifnet structure associated with the interface.
Result: true if the update was successful, false otherwise.

setInterfaceType

public:

virtual bool setInterfaceType(UInt8 type);

Parameters

NameDescription
typeThe type of the interface. See bsd/net/if_types.h for the defined types.
Result: true if the current state is kStateUnregistered and the update was successful, false otherwise.

setInterfaceTypeInt

protected:

virtual bool setInterfaceTypeInt(UInt8 type);

Parameters

NameDescription
typeThe type of the interface. See bsd/net/if_types.h for defined types.
Result: true if the update was successful, false otherwise.

setMaxTransferUnit

public:

virtual bool setMaxTransferUnit(UInt32 mtu);

Parameters

NameDescription
mtuThe new interface MTU size.
Result: true if the current state is kStateUnregistered and the update was successful, false otherwise.

setMaxTransferUnitInt

protected:

virtual bool setMaxTransferUnitInt(UInt32 mtu);

Parameters

NameDescription
mtuThe new interface MTU size.
Result: true if the update was successful, false otherwise.

setMediaAddressLength

public:

virtual bool setMediaAddressLength(UInt8 length);

Parameters

NameDescription
lengthThe new value for the if_data.ifi_addrlen field in the ifnet structure associated with the interface.
Result: true if the current state is kStateUnregistered and the update was successful, false otherwise.

setMediaAddressLengthInt

protected:

virtual bool setMediaAddressLengthInt(UInt8 length);

Parameters

NameDescription
lengthThe new value for the if_data.ifi_addrlen field in the ifnet structure associated with the interface.
Result: true if the field was updated, false otherwise.

setMediaHeaderLength

public:

virtual bool setMediaHeaderLength(UInt8 length);

Parameters

NameDescription
lengthThe new value for the if_data.ifi_hdrlen field in the ifnet structure associated with the interface.
Result: true if the current state is kStateUnregistered and the update was successful, false otherwise.

setMediaHeaderLengthInt

protected:

virtual bool setMediaHeaderLengthInt(UInt8 length);

Parameters

NameDescription
lengthThe new value for the if_data.ifi_hdrlen field in the ifnet structure associated with the interface.
Result: true if the update was successful, false otherwise.

setOutputFilterTapMode

public:

virtual bool setOutputFilterTapMode(IOFilterTapMode mode);

Set the mode of the output packet tap, to specify how the tap will connect to the output packet flow once the tap becomes enabled. See IOFilterTapMode enumeration.

Parameters

NameDescription
Thenew mode.
Result: true if the new mode was accepted, false otherwise.

setUnitNumber

public:

virtual bool setUnitNumber(UInt16 unit);

Parameters

NameDescription
unitThe unit number to assign to this interface.
Result: true if the current state is kStateUnregistered and the unit number was accepted, false otherwise.

setUnitNumberInt

protected:

virtual bool setUnitNumberInt(UInt16 unit);

Parameters

NameDescription
unitThe unit number to assign to this interface.
Result: true if the unit number was accepted, false otherwise.

unlock

protected:

virtual void unlock();

Release the recursive lock that protects the interface data and state.


Member Data

State

public:
  enum  {
  kStateUnregistered,
  kStateRegistered
  };

The state of the interface returned by getInterfaceState().

Constants

NameDescription
kStateUnregisteredThe interface has no client (IOUserClient excluded), hence the interface is not registered with the network layer.
kStateRegisteredA client has opened the interface, and the interface is registered with the network layer.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IONetworkMedium.h

IONetworkMedium.h



Typedefs

IOMediumDescriptor

typedef  struct  {
  IOMediumType  type;
  UInt32  flags;
  UInt64  speed;
  UInt32  data;
  UInt32  rsvd[2];
}  IOMediumDescriptor;

A structure which describes the properties of an IONetworkMedium object.

Fields

NameDescription
typeSee init().
flagsSee init().
speedSee init().
dataSee init().

IOMediumType

typedef  UInt32  IOMediumType;

A 32-bit value divided into fields describing the medium type. See IONetworkMedium.h for defined bits.


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IONetworkMedium

IONetworkMedium



Member Functions

addMedium

public:

static bool addMedium(OSDictionary * dict, const IONetworkMedium * medium);

A helper function to add an IONetworkMedium object to a given dictionary. The name of the medium is used as the key for the new dictionary entry.

Parameters

NameDescription
dictAn OSDictionary object where the medium object should be added.
mediumThe IONetworkMedium object to be added to the dictionary.
Result: true on success, false otherwise.

free

protected:

virtual void free();

Free the IONetworkMedium instance.


getData

public:

virtual UInt32 getData() const;

Result: The assigned token.

getDescriptor

public:

virtual void getDescriptor(IOMediumDescriptor * descP) const;

Parameters

NameDescription
descPThe IOMediumDescriptor structure associated with the instance is copied to a structure provided by the caller.

getFlags

public:

virtual UInt32 getFlags() const;

Result: The medium flags.

getKey

public:

virtual const OSSymbol * getKey() const;

Result: The key for this instance. Same as getName().

getMedium

public:

static IONetworkMedium * getMedium(OSDictionary * dict, IOMediumDescriptor * match, IOMediumDescriptor * mask);

Iterate through a dictionary and return an IONetworkMedium entry that satisfies the matching criteria. Returns 0 if there is no match. Also see getMediumWithType() and getMediumWithData() that are built on top of this method.

Parameters

NameDescription
dictThe dictionary to look for a match.
matchAn IOMediumDescriptor structure containing the matching fields.
maskAn IOMediumDescriptor structure containing the matching mask. Bits set are used for matching, while cleared bits are don't care bits.
Result: The matching IONetworkMedium entry, 0 if no match was found.

getMediumWithData

public:

static IONetworkMedium * getMediumWithData(OSDictionary * dict, UInt32 data, UInt32 mask = 0);

Iterate through a dictionary and return an IONetworkMedium entry with the given data. A optional mask supplies the don't care bits.

Parameters

NameDescription
dictThe dictionary to look for a match.
typeThe medium data to search for.
maskThe don't care bits in data. Defaults to 0, which means all bits must match.
Result: The matching IONetworkMedium entry, 0 if no match was found.

getMediumWithType

public:

static IONetworkMedium * getMediumWithType(OSDictionary * dict, IOMediumType type, IOMediumType mask = 0);

Iterate through a dictionary and return an IONetworkMedium entry with the given type. A optional mask supplies the don't care bits.

Parameters

NameDescription
dictThe dictionary to look for a match.
typeThe medium type to search for.
maskThe don't care bits in IOMediumType. Defaults to 0, which means all bits must match.
Result: The matching IONetworkMedium entry, 0 if no match was found.

getName

public:

virtual const OSSymbol * getName() const;

Result: The name for this instance.

getSpeed

public:

virtual UInt64 getSpeed() const;

Result: The maximum medium speed.

getType

public:

virtual IOMediumType getType() const;

Result: The assigned medium type.

init

public:

virtual bool init(IOMediumType type, UInt64 speed, UInt32 flags = 0, UInt32 data = 0, const char * name = 0);

Initialize the IONetworkMedium instance.

Parameters

NameDescription
typeThe medium type, the fields are encoded with bits defined in IONetworkMedium.h.
speedThe maximum link speed supported over this medium in units of bits per second.
flagsAn optional flag for the medium object. No flags are currently defined.
dataAn arbitrary 32-bit token assigned by the caller.
nameAn optional name assigned to this medium object. If 0, then a name will be created based on the medium type given.
Result: true on success, false otherwise.

isEqualTo

public:

virtual bool isEqualTo(const IONetworkMedium * medium) const;

Parameters

NameDescription
mediumAn IONetworkMedium to test against the receiver of this method. Two IONetworkMedium objects are considered equal if they have the same name.
Result: true if equal, false otherwise.

isEqualTo

public:

virtual bool isEqualTo(const OSObject * obj) const;

Parameters

NameDescription
objAn OSObject to test against the receiver of this method. The object is considered equal if it is an IONetworkMedium, and it has the same name as the receiver.
Result: true if equal, false otherwise.

medium

public:

static IONetworkMedium * medium(IOMediumType type, UInt64 speed, UInt32 flags = 0, UInt32 data = 0, const char * name = 0);

Factory method that will construct and initialize an IONetworkMedium instance.

Parameters

NameDescription
typeSee init().
speedSee init().
flagsSee init().
dataSee init().
nameSee init().
Result: An IONetworkMedium instance on success, or 0 otherwise.

nameForType

public:

static const OSSymbol * nameForType(IOMediumType type);

Given a medium type, create an unique OSymbol name for the medium. The caller is responsible for releasing the OSSymbol instance returned.

Parameters

NameDescription
typeA medium type.
Result: An OSSymbol created from the type provided.

removeMedium

public:

static void removeMedium(OSDictionary * dict, const IONetworkMedium * medium);

A helper function to remove an entry in a dictionary with a key which matches the name of the IONetworkMedium object provided.

Parameters

NameDescription
dictAn OSDictionary object where the medium object should be removed from.
mediumThe name of this medium object is used as the removal key.

serialize

public:

virtual bool serialize(OSSerialize * s) const;

Create an OSData containing an IOMediumDescriptor structure (not copied), and ask the OSData to serialize.

Parameters

NameDescription
sAn OSSerialize object to handle the serialization.
Result: true on success, false otherwise.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IONetworkParameter.h

IONetworkParameter.h



Typedefs

IONPAction

typedef IOReturn (OSObject::*IONPAction)(IONetworkParameter * param,
                                         UInt32               accessType,
                                         void *               arg);

Implemented by the registered access notification target..

Parameters

NameDescription
paramThe IONetworkParameter object that has received a request, and is also the sender of the notification.
accessThe type of access requested. The possible values are, kIONPAccessRead, kIONPAccessWrite, or kIONPAccessReset.
argAn argument set when the notification handler was registered.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IONetworkParameter

IONetworkParameter



Member Functions

clearBytes

public:

virtual bool clearBytes();

Clear the entire data buffer by calling bzero().

Result: true if the buffer was cleared, false otherwise.

copyBytes

public:

virtual bool copyBytes(void * bytes, UInt * inOutLength) const;

Copy the data buffer to a destination buffer provided by the caller.

Parameters

NameDescription
bytesPointer to a destination buffer.
inOutLengthThe caller must initialize the integer value pointed by inOutLength with the size of the destination buffer, and this method will overwrite it with the number of bytes copied.
Result: true if the destination buffer is larger or equal to the length of the parameter, false otherwise.

free

protected:

virtual void free();

Frees the IONetworkParameter instance.


getAccessTypes

public:

virtual UInt32 getAccessTypes() const;

Result: The access types supported by this instance.

getAction

public:

virtual IONPAction getAction() const;

Result: The notification action.

getArgument

public:

virtual void * getArgument() const;

Result: The notification argument.

getBuffer

public:

virtual const void * getBuffer() const;

Result: A pointer to the data buffer.

getCapacity

public:

virtual UInt getCapacity() const;

Override the getCapacity() method inherited from OSData.

Result: The capacity of the data buffer in bytes.

getDescriptor

public:

virtual void getDescriptor(IONPDescriptor * descP) const;

Updates the IONPDescriptor structure provided by the caller.

Parameters

NameDescription
Pointerto an IONPDescriptor structure allocated by the caller.

getKey

public:

virtual const OSSymbol * getKey() const;

During initialization, IONetworkParameter will create an OSSymbol key based on its assigned name. This key can be used when adding this object to a dictionary.

Result: An OSSymbol key based on the parameter's assigned name.

getTarget

public:

virtual OSObject * getTarget() const;

Result: The notification target.

init

public:

virtual bool initWithName(const char * name, void * buffer, UInt32 size, UInt32 accessTypes = kIONPAccessRead, OSObject * target = 0, IONPAction action = 0, void * arg = 0);

Initialize an IONetworkParameter instance. A target/action may be assigned to receive notifications when the read(), write(), or reset() methods are called. See those methods for additional information.

Parameters

NameDescription
nameA name assigned to the parameter.
bufferPoints to an external data buffer. If set to kIONPInternalBuffer, then internal buffer storage shall be allocated.
sizeSize of the data buffer in bytes. Both the capacity and the length are intialized to the size given.
accessTypesThe types of access allowed. Can be later changed by calling setAccessTypes().
targetNotification target.
actionNotification action.
argNotification argument.
Result: true if initialized successfully, false otherwise.

initialize

protected:

static void initialize();

Class initializer which allocates a global mutex lock (gIONPLock).


read

public:

virtual IOReturn read(void * inBuffer, UInt * inOutSize);

Handle a request to read from the data buffer and copy it to the destination buffer provided. If notification is enabled, then the notification handler is called with the access argument set to kIONPAccessRead before the data buffer is copied to the destination buffer. The notification handler may take this opportunity to update the contents of the data buffer.

Parameters

NameDescription
inBufferPointer to the destination buffer.
inOutSizePoints to the size of the destination buffer before the call. This method will change it to contain the actual number of bytes written to the destination buffer.
Result: kIOReturnSuccess if success, kIOReturnBadArgument if any argument is invalid, kIOReturnNoSpace if the destination buffer is too small, kIOReturnNotReadable if read access is not permitted, or some other error code from the notification handler if called.

reset

public:

virtual IOReturn reset();

Handle a request to reset the parameter. If notication is enabled, then the notification handler is called with the access argument set to kIONPAccessReset, after the data buffer is cleared.

Result: kIOReturnNotWritable if reset access is not allowed, or kIOReturnSuccess otherwise. If a notification handler is called, then the return value from the handler is returned.

serialize

public:

virtual bool serialize(OSSerialize * s) const;

Serialize the parameter object. If notification is enabled, then the notification target is called as though a read() access has occurred.

Parameters

NameDescription
sAn OSSerialize object.

setAccessTypes

public:

virtual void setAccessTypes(UInt32 accessTypes);

Sets the types of external access allowed. For instance, if access is set to kIONPAccessRead, then only read() will return success. Calls to write() or reset() will return kIOReturnNotWritable. To change this and allow writes, access must be set to (kIONPAccessRead | kIONPAccessWrite). Note that other methods in IONetworkParameter do not check the access types.

Parameters

NameDescription
accessTypesAll supported access types.

setBytes

public:

virtual bool setBytes(const void * bytes, UInt inLength);

Replace the data buffer contents from a source buffer provided by the caller.

Parameters

NameDescription
bytesPointer to a source buffer provided by the caller.
inLengthLength of the source buffer. The length provided must be smaller or equal to the capacity of the parameter object.
Result: true if the length of the source buffer is valid, and the source buffer was copied, false otherwise.

setLength

public:

virtual bool setLength(UInt inLength);

Set a new data buffer length.

Parameters

NameDescription
inLengthLength of the data buffer in bytes. The length provided must be smaller or equal to the capacity of the parameter object.
Result: true if the length provided was accepted.

setNotificationTarget

public:

virtual void setNotificationTarget(OSObject * target, IONPAction action, void * arg = 0);

Set a target/action to receive external access notifications.

Parameters

NameDescription
targetThe target object. If set to 0, then notification will be disabled.
actionThe notification action or handler. If set to 0, then notification will be disabled.
argAn optional argument that will be passed to the notification handler.

withTarget

public:

static IONetworkParameter * withName( const char * name, void * buffer, UInt32 size, UInt32 accessTypes = kIONPAccessRead, OSObject * target = 0, IONPAction action = 0, void * arg = 0);

Factory method that will construct and initialize an IONetworkParameter instance.

Parameters

NameDescription
nameSame as init().
bufferSame as init().
sizeSame as init().
accessTypesSame as init().
targetSame as init().
actionSame as init().
argSame as init().
Result: An IONetworkParameter instance upon success, or 0 otherwise.

write

public:

virtual IOReturn write(void * inBuffer, UInt size);

Handle a request to write to the data buffer from a source buffer provided. If notification is enabled, then the notification handler is called with the access argument set to kIONPAccessWrite after the source buffer has been copied to the data buffer.

Parameters

NameDescription
inBufferPointer to the source buffer.
sizeSize of the source buffer in bytes.
Result: kIOReturnSuccess if success, kIOReturnBadArgument if any argument is invalid, kIOReturnNoSpace if the source buffer is too big, kIOReturnNotWritable if write access is not permitted, or some other error code from the notification handler if called.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IONetworkStats.h

IONetworkStats.h



Typedefs

IONetworkStats

typedef  struct  {
  UInt32  inputPackets;
  UInt32  inputErrors;
  UInt32  outputPackets;
  UInt32  outputErrors;
  UInt32  collisions;
}  IONetworkStats;

Generic network statistics structure.

Fields

NameDescription
inputPacketscount input packets.
inputErrorscount input errors.
outputPacketscount output packets.
outputErrorscount output errors.
collisionscount collisions on CDMA networks.

IOOutputQueueStats

typedef  struct  {
  UInt32  capacity;
  UInt32  size;
  UInt32  peakSize;
  UInt32  dropCount;
  UInt32  outputCount;
  UInt32  retryCount;
  UInt32  stallCount;
  UInt32  reserved[4];
}  IOOutputQueueStats;

Statistics recorded by IOOutputQueue objects.

Fields

NameDescription
capacityqueue capacity.
sizecurrent size of the queue.
peakSizepeak size of the queue.
dropCountnumber of packets dropped.
outputCountnumber of output packets.
retryCountnumber of retries.
stallCountnumber of queue stalls.

#defines

kIONetworkStatsKey

#define kIONetworkStatsKey "IONetworkStatsKey"

Defines the name of an IONetworkParameter that contains an IONetworkStats.


kIOOutputQueueStatsKey

#define kIOOutputQueueStatsKey "IOOutputQueueStatsKey"

Defines the name of an IONetworkParameter that contains an IOOutputQueueStats.


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IONotifier.h

IONotifier.h



© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IONotifier

IONotifier



Member Functions

disable

Abstract: Disables the notification request.
public:

virtual bool disable() = 0;

Disables the notification request. This method is synchronous with any handler invocations, so when this method returns its guaranteed the handler will not be in entered.

Result: Returns the previous enable state of the IONotifier.

enable

Abstract: Sets the enable state of the notification request.
public:

virtual void enable( bool was ) = 0;

Restores the enable state of the notification request, given the previous state passed in.

Parameters

NameDescription
wasThe enable state of the notifier to restore.

remove

Abstract: Removes the notification request and releases it.
public:

virtual void remove() = 0;

Removes the notification request and release it. Since creating an IONotifier instance will leave it with a retain count of one, creating an IONotifier and then removing it will destroy it. This method is synchronous with any handler invocations, so when this method returns its guaranteed the handler will not be in entered.


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOOQGateFIFOQueue.h

IOOQGateFIFOQueue.h



© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOOQGateFIFOQueue

IOOQGateFIFOQueue



Member Functions

dequeue

protected:

virtual void dequeue();

Responsible for removing all packets from the queue and calling the target's output handler. This method returns when the queue becomes empty or if the queue's state is no longer kIOOQStateRunning. The target's output handler is called for every packet removed from the queue. Only a single packet is sent to the target for every call, the packets are never chained. An IOCommandGate attached to an workloop provided by the target ensures mutual exclusion between the dequeueing action (and calls to the target's output handler), and any other action performed by the workloop's thread.


enqueue

public:

virtual UInt32 enqueue(struct mbuf * m);

Handles packet (or a packet chain) sent to the queue. This method can handle calls from multiple simultaneous client threads. A client thread that calls enqueue() will call dequeue() with the command gate closed if it detects that no other thread is actively dequeueing packets from the queue. The dequeue() method will return when the queue becomes empty, or if the target stalls the queue. This method may block its caller.

Parameters

NameDescription
Thepacket (or a packet chain) to be queued for transmission.
Result: The number of dropped packets.

free

protected:

virtual void free();

Frees the IOOQGateFIFOQueue instance.


gatedDequeue

protected:

virtual void gatedDequeue();

The naked dequeue() method not protected by the IOCommandGate. dequeue() method will call gatedDequeue() with the command gate closed.


gatedStop

protected:

virtual void gatedStop();

The naked stop() method not protected by the IOCommandGate. stop() method will call gatedStop() with the command gate closed.


init

public:

virtual bool init(OSObject * target, IOWorkLoop * workloop, UInt32 capacity = 0);

Initialize an IOOQGateFIFOQueue instance.

Parameters

NameDescription
targetThe object that shall receive packets from the queue, and is usually a subclass of IONetworkController. If the target is not an IONetworkController instance, then the target must immediately call registerOutputHandler() after initializing the queue.
workloopA workloop object provided by the target that the queue will use to add an internal IOCommandGate as an event source.
capacityThe initial capacity of the output queue, defined as the number of packets that the queue can hold without dropping.
Result: true if initialized successfully, false otherwise.

service

public:

virtual bool service(bool sync = true);

If the queue becomes stalled, then service() must be called to restart the queue when the target is ready to accept more packets. If the queue is not empty, this method will also call dequeue(). Note that if the target never sends a kIOOQReturnActionStall action code to the queue, then the queue will never stall on its own accord. Calling this method on a running queue that is not stalled is harmless.

Parameters

NameDescription
syncTrue if the service action should be performed synchronously, false to perform the action asynchronously without blocking the caller, but with a much higher latency cost.
Result: true if the queue needed servicing, false otherwise.

serviceThread

protected:

virtual void serviceThread();

Provide an implementation for the interface defined in IOOutputQueue. This method is called by a callout thread when service() is performed asynchronously.


start

public:

virtual bool start();

This method is called by the target to start the queue. Once started, the queue will be allowed to call the target's output handler. Before that, with the queue stopped, the queue will absorb incoming packets sent to the enqueue() method, but no packets will be dequeued, and the target's output handler will not be called.

Result: true if the queue was successfully started, false otherwise.

stop

public:

virtual void stop();

Stops the queue to prevent it from calling the target's output handler. This call is synchronous the caller may block. The target's output handler must never call this method, or any other queue methods.


withTarget

public:

static IOOQGateFIFOQueue * withTarget(OSObject * target, IOWorkLoop * workloop, UInt32 capacity = 0);

Factory method that will construct and initialize an IOOQGateFIFOQueue instance.

Parameters

NameDescription
targetSame as init().
workloopSame as init().
capacitySame as init().
Result: An IOOQGateFIFOQueue instance upon success, or 0 otherwise.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOOQLockFIFOQueue.h

IOOQLockFIFOQueue.h



© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOOQLockFIFOQueue

IOOQLockFIFOQueue



Member Functions

dequeue

protected:

virtual void dequeue();

Responsible for removing all packets from the queue and calling the target's output handler. This method returns when the queue becomes empty or if the queue's state is no longer kIOOQStateRunning. The target's output handler is called for every packet removed from the queue. Only a single packet is sent to the target for every call, the packets are never chained. A mutex lock enforces single threaded access to the target's output handler.


enqueue

public:

virtual UInt32 enqueue(struct mbuf * m);

Handles packet (or a packet chain) sent to the queue. This method can handle calls from multiple simultaneous client threads. A client thread that calls enqueue() will acquire a mutex lock and call dequeue() if it detects that no other thread is actively dequeueing packets from the queue. The dequeue() method will return when the queue becomes empty, or if the target stalls the queue. This method may block its caller.

Parameters

NameDescription
mThe packet (or a packet chain) to be queued for transmission.
Result: The number of dropped packets.

free

protected:

virtual void free();

Frees the IOOQLockFIFOQueue instance.


init

public:

virtual bool init(OSObject * target, UInt32 capacity = 0);

Initialize an IOOQLockFIFOQueue instance.

Parameters

NameDescription
targetThe object that shall receive packets from the queue, and is usually a subclass of IONetworkController. If the target is not an IONetworkController instance, then the target must immediately call registerOutputHandler() after initializing the queue.
capacityThe initial capacity of the output queue, defined as the number of packets that the queue can hold without dropping.
Result: true if initialized successfully, false otherwise.

service

public:

virtual bool service(bool sync = true);

If the queue becomes stalled, then service() must be called to restart the queue when the target is ready to accept more packets. If the queue is not empty, this method will also call dequeue(). Note that if the target never sends a kIOOQReturnActionStall action code to the queue, then the queue will never stall on its own accord. Calling this method on a running queue that is not stalled is harmless.

Parameters

NameDescription
syncTrue if the service action should be performed synchronously, false to perform the action asynchronously without blocking the caller, but with a much higher latency cost.
Result: true if the queue needed servicing, false otherwise.

serviceThread

protected:

virtual void serviceThread();

Provide an implementation for the interface defined in IOOutputQueue. This method is called by a callout thread when service() is performed asynchronously.


start

public:

virtual bool start();

This method is called by the target to start the queue. Once started, the queue will be allowed to call the target's output handler. Before that, with the queue stopped, the queue will absorb incoming packets sent to the enqueue() method, but no packets will be dequeued, and the target's output handler will not be called.

Result: true if the queue was successfully started, false otherwise.

stop

public:

virtual void stop();

Stops the queue to prevent it from calling the target's output handler. This call is synchronous the caller may block. The target's output handler must never call this method, or any other queue methods.


withTarget

public:

static IOOQLockFIFOQueue * withTarget(OSObject * target, UInt32 capacity = 0);

Factory method that will construct and initialize an IOOQLockFIFOQueue instance.

Parameters

NameDescription
targetSame as init().
capacitySame as init().
Result: An IOOQLockFIFOQueue instance upon success, or 0 otherwise.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOOutputQueue.h

IOOutputQueue.h



Constants

kIOOQReturnDropped

Same as (kIOOQReturnStatusDropped | kIOOQReturnActionNone). Packet was dropped.


kIOOQReturnStall

Same as (kIOOQReturnStatusRetry | kIOOQReturnActionStall). Stall the queue and retry the same packet when the queue is restarted.


kIOOQReturnSuccess

Same as (kIOOQReturnStatusSuccess | kIOOQReturnActionNone). Packet was accepted.


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOOutputQueue

IOOutputQueue



Member Functions

cancelServiceThread

protected:

virtual bool cancelServiceThread();

Cancel the service thread callout. Subclasses should not override this method.

Result: true if a previously scheduled thread callout was canceled, false otherwise.

createPacketQueue

protected:

virtual IOPacketQueue * createPacketQueue(UInt32 capacity) const;

Allows subclasses to override the default action, which is to allocate and return an IOPacketQueue instance. The returned object is used to implement the queueing behavior of the IOOutputQueue.

Parameters

NameDescription
capacityThe initial capacity of the queue.
Result: A newly allocated and initialized IOPacketQueue instance.

enqueue

public:

virtual UInt32 enqueue(struct mbuf * m) = 0;

Handles packet (or a packet chain) sent to the queue. This method can handle calls from multiple simultaneous client threads. A pointer to this function is written to the "output" field in the IOOutputHandler structure by getOutputHandler(), thus allowing client objects to call this method in order to process the output packet.

Parameters

NameDescription
mThe packet (or a packet chain) to be queued for transmission.
Result: The number of dropped packets.

flush

public:

virtual UInt32 flush();

Release all packets held in the queue. The size of the queue is reset to zero. The drop packet counter is incremented by the number of packets freed. See getDropCount().

Result: The number of packets freed.

free

protected:

virtual void free();

Frees the IOOutputQueue instance.


getCapacity

public:

virtual UInt32 getCapacity() const;

Result: The current queue capacity.

getDropCount

public:

virtual UInt32 getDropCount(bool reset = false);

This method returns the number of times that a kIOOQReturnStatusDropped status code is received from the target's output handler, indicating that the packet given was dropped. This count is also incremented when the queue drops a packet due to overcapacity, or by an explicit flush() call.

Parameters

NameDescription
resetResets the counter if true.
Result: The number of dropped packets.

getOutputCount

public:

virtual UInt32 getOutputCount(bool reset = false);

This method returns the number of times that a kIOOQReturnStatusSuccess status code is received from the target's output handler, indicating that the packet given was accepted, and is ready to be (or already has been) transmitted.

Parameters

NameDescription
resetResets the counter if true.
Result: The number of packets accepted by our target.

getOutputHandler

public:

void getOutputHandler(IOOutputHandler * handler) const;

This method will write to the fields in the IOOutputHandler structure allocated by the caller. This method is called to discover the methods implemented by this object used to handle outbound packets and requests.

Parameters

NameDescription
handlerPointer to an IOOutputHandler structure passed in by the caller.

getPeakSize

public:

virtual UInt32 getPeakSize(bool reset = false);

Parameters

NameDescription
resetResets the counter if true.
Result: The peak queue size.

getRetryCount

public:

virtual UInt32 getRetryCount(bool reset = false);

This method returns the number of times that a kIOOQReturnStatusRetry status code is received from the target's output handler, indicating that the target is temporarily unable to handle the packet given, and the queue should try to resend the same packet at some later time.

Parameters

NameDescription
resetResets the counter if true.
Result: The number of retries issued by the target.

getSize

public:

virtual UInt32 getSize() const;

Result: The current queue size.

getStallCount

public:

virtual UInt32 getStallCount(bool reset = false);

Each time the queue is stalled, when a kIOOQReturnActionStall action code is received from the target's output handler, a counter is incremented. This method returns the value stored in this counter.

Parameters

NameDescription
resetResets the counter if true.
Result: The number of times that the queue was stalled.

getState

public:

virtual IOOQState getState() const;

Result: The current state of the queue object. See IOOQState enumeration.

init

protected:

virtual bool init(OSObject * target, UInt32 capacity);

Initialize an IOOutputQueue instance.

Parameters

NameDescription
targetThe object that shall receive packets from the queue, and is usually a subclass of IONetworkController. If the target is not an IONetworkController instance, then the target must immediately call registerOutputHandler() after initializing the queue.
capacityThe initial capacity of the output queue, defined as the number of packets that the queue can hold without dropping.
Result: true if initialized successfully, false otherwise.

publishParameters

protected:

virtual void publishParameters(OSDictionary * paramDict);

Called by an interface object to collect IONetworkParameter objects. IOOutputQueue will add a parameter, containing an IOOutputQueueStats structure, to the dictionary provided. This dictionary and the objects (and data) contained within can be serialized to user-space, allowing the queue statistics to be visible outside of the kernel.

Parameters

NameDescription
Adictionary provided by the interface object that is used as a parameter container.

registerOutputHandler

public:

bool registerOutputHandler(const IOOutputHandler * handler);

Register the target object, and methods to call needed for the queue to send packets and requests downstream. The caller must provide a pointer to an IOOutputHandler structure that has been initialized.

Parameters

NameDescription
handlerPointer to an initialized IOOutputHandler structure passed in by the caller.
Result: true if the structure given was accepted, otherwise return false.

requestHandler

public:

IOReturn requestHandler(OSObject * sender, UInt32 request, void * arg0 = 0, void * arg1 = 0, void * arg2 = 0, void * arg3 = 0);

Handle a request sent from the interface object.

Parameters

NameDescription
senderThe sender of the request.
requestThe request type. The types handled by this class are kRequestSetOutputQueueCapacity, kRequestGetOutputQueueCapacity, kRequestGetOutputQueueSize, kRequestFlushOutputQueue, and kRequestPublishParameters.
arg0Request argument.
arg1Request argument.
arg2Request argument.
arg3Request argument.
Result: kIOReturnSuccess if the request was successfully handled, otherwise an appropriate error code is returned.

runServiceThread

protected:

static void runServiceThread(IOOutputQueue * self, thread_call_param_t);

A glue function that is registered as the service thread callout handler. This function in turn will call the serviceThread() method.

Parameters

NameDescription
selfAn argument previously registered with the callout to identify the IOOutputQueue instance associated with the callout.

scheduleServiceThread

protected:

virtual bool scheduleServiceThread();

Schedule a service thread callout, which will then execute the serviceThread() method. Subclasses should not override this method.

Result: true if scheduling the thread callout was successful, false otherwise.

service

public:

virtual bool service(bool sync = true) = 0;

If the queue becomes stalled, then service() must be called to restart the queue when the target is ready to accept more packets. Note that if the target never sends a kIOOQReturnActionStall action code to the queue, then the queue will never stall on its own accord. Calling this method on a running queue that is not stalled is harmless.

Parameters

NameDescription
syncTrue if the service action should be performed synchronously, false to perform the action asynchronously without blocking the caller, but with a much higher latency cost.
Result: true if the queue needed servicing, false otherwise.

serviceThread

protected:

virtual void serviceThread();

Must be implemented by subclasses that calls scheduleServiceThread(). The default implementation is a placeholder and performs no useful action.


setCapacity

public:

virtual bool setCapacity(UInt32 capacity);

Parameters

NameDescription
capacityThe new capacity of the queue.
Result: true if the new capacity was accepted, false otherwise.

start

public:

virtual bool start() = 0;

This method is called by the target to start the queue. Once started, the queue will be allowed to call the target's output handler. Before that, with the queue stopped, the queue will absorb incoming packets sent to the enqueue() method, but no packets will be dequeued, and the target's output handler will not be called.

Result: true if the queue was successfully started, false otherwise.

stop

public:

virtual void stop() = 0;

Stops the queue to prevent it from calling the target's output handler. This call is synchronous the caller may block. The target's output handler must never call this method, or any other queue methods.


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOPCIDevice.h

IOPCIDevice.h



© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOPCIDevice

IOPCIDevice



Member Functions

configRead32

Abstract: Reads a 32-bit value from the PCI device's configuration space.
public:

virtual UInt32 configRead32( UInt8 offset );

This method reads a 32-bit configuration space register on the device and returns its value.

Parameters

NameDescription
offsetAn 8-bit offset into configuration space, of which bits 0-1 are ignored.
Result: An 32-bit value in host byte order (big endian on PPC).

configWrite32

Abstract: Writes a 32-bit value to the PCI device's configuration space.
public:

virtual void configWrite32( UInt8 offset, UInt32 data );

This method write a 32-bit value to a configuration space register on the device.

Parameters

NameDescription
offsetAn 8-bit offset into configuration space, of which bits 0-1 are ignored.
dataAn 32-bit value to be written in host byte order (big endian on PPC).

findPCICapability

Abstract: Search configuration space for a PCI capability register.
public:

virtual UInt32 findPCICapability( UInt8 capabilityID );

This method searchs the device's config space for a PCI capability register matching the passed capability ID, if the device supports PCI capabilities.

Parameters

NameDescription
capabilityIDAn 8-bit PCI capability ID.
Result: The 32-bit value of the capability register if one was found, zero otherwise.

getBusNumber

Abstract: Accessor to return the PCI device's assigned bus number.
public:

virtual UInt8 getBusNumber( void );

This method is an accessor to return the PCI device's assigned bus number.

Result: The 8-bit value of device's PCI bus number.

getDeviceMemoryWithRegister

Abstract: Returns an instance of IODeviceMemory representing one of the device's memory mapped ranges.
public:

virtual IODeviceMemory * getDeviceMemoryWithRegister( UInt8 reg );

This method will return a pointer to an instance of IODeviceMemory for the physical memory range that was assigned to the configuration space base address register passed in. It is analogous to IOService::getDeviceMemoryWithIndex.

Parameters

NameDescription
regThe 8-bit configuration space register that is the base address register for the desired range.
Result: A pointer to an instance of IODeviceMemory, or zero no such range was found. The IODeviceMemory is retained by the provider, so is valid while attached, or while any mappings to it exist. It should not be released by the caller.

getDeviceNumber

Abstract: Accessor to return the PCI device's device number.
public:

virtual UInt8 getDeviceNumber( void );

This method is an accessor to return the PCI device's device number.

Result: The 5-bit value of device's device number.

getFunctionNumber

Abstract: Accessor to return the PCI device's function number.
public:

virtual UInt8 getFunctionNumber( void );

This method is an accessor to return the PCI device's function number.

Result: The 3-bit value of device's function number.

ioDeviceMemory

Abstract: Accessor to the I/O space aperture for the bus.
public:

virtual IODeviceMemory * ioDeviceMemory( void );

This method will return a reference to the IODeviceMemory for the I/O aperture of the bus the device is on.

Result: A pointer to an IODeviceMemory object for the I/O aperture. The IODeviceMemory is retained by the provider, so is valid while attached, or while any mappings to it exist. It should not be released by the caller.

ioRead16

Abstract: Reads a 16-bit value from an I/O space aperture.
public:

virtual UInt16 ioRead16( UInt16 offset, IOMemoryMap * map = 0 );

This method will read a 16-bit value from a 2 byte aligned offset in an I/O space aperture. If a map object is passed in, the value is read relative to it, otherwise to the value is read relative to the I/O space aperture for the bus. This function encapsulates the differences between architectures in generating I/O space operations. An eieio instruction is included on PPC.

Parameters

NameDescription
offsetAn offset into a bus or device's I/O space aperture.
mapIf the offset is relative to the beginning of a device's aperture, an IOMemoryMap object for that object should be passed in. Otherwise, passing zero will write the value relative to the beginning of the bus' I/O space.
Result: The value read in host byte order (big endian on PPC).

ioRead32

Abstract: Reads a 32-bit value from an I/O space aperture.
public:

virtual UInt32 ioRead32( UInt16 offset, IOMemoryMap * map = 0 );

This method will read a 32-bit value from a 4 byte aligned offset in an I/O space aperture. If a map object is passed in, the value is read relative to it, otherwise to the value is read relative to the I/O space aperture for the bus. This function encapsulates the differences between architectures in generating I/O space operations. An eieio instruction is included on PPC.

Parameters

NameDescription
offsetAn offset into a bus or device's I/O space aperture.
mapIf the offset is relative to the beginning of a device's aperture, an IOMemoryMap object for that object should be passed in. Otherwise, passing zero will write the value relative to the beginning of the bus' I/O space.
Result: The value read in host byte order (big endian on PPC).

ioRead8

Abstract: Reads a 8-bit value from an I/O space aperture.
public:

virtual UInt8 ioRead8( UInt16 offset, IOMemoryMap * map = 0 );

This method will read a 8-bit value from an offset in an I/O space aperture. If a map object is passed in, the value is read relative to it, otherwise to the value is read relative to the I/O space aperture for the bus. This function encapsulates the differences between architectures in generating I/O space operations. An eieio instruction is included on PPC.

Parameters

NameDescription
offsetAn offset into a bus or device's I/O space aperture.
mapIf the offset is relative to the beginning of a device's aperture, an IOMemoryMap object for that object should be passed in. Otherwise, passing zero will write the value relative to the beginning of the bus' I/O space.
Result: The value read.

ioWrite16

Abstract: Writes a 16-bit value to an I/O space aperture.
public:

virtual void ioWrite16( UInt16 offset, UInt16 value, IOMemoryMap * map = 0 );

This method will write a 16-bit value to a 2 byte aligned offset in an I/O space aperture. If a map object is passed in, the value is written relative to it, otherwise to the value is written relative to the I/O space aperture for the bus. This function encapsulates the differences between architectures in generating I/O space operations. An eieio instruction is included on PPC.

Parameters

NameDescription
offsetAn offset into a bus or device's I/O space aperture.
valueThe value to be written in host byte order (big endian on PPC).
mapIf the offset is relative to the beginning of a device's aperture, an IOMemoryMap object for that object should be passed in. Otherwise, passing zero will write the value relative to the beginning of the bus' I/O space.

ioWrite32

Abstract: Writes a 32-bit value to an I/O space aperture.
public:

virtual void ioWrite32( UInt16 offset, UInt32 value, IOMemoryMap * map = 0 );

This method will write a 32-bit value to a 4 byte aligned offset in an I/O space aperture. If a map object is passed in, the value is written relative to it, otherwise to the value is written relative to the I/O space aperture for the bus. This function encapsulates the differences between architectures in generating I/O space operations. An eieio instruction is included on PPC.

Parameters

NameDescription
offsetAn offset into a bus or device's I/O space aperture.
valueThe value to be written in host byte order (big endian on PPC).
mapIf the offset is relative to the beginning of a device's aperture, an IOMemoryMap object for that object should be passed in. Otherwise, passing zero will write the value relative to the beginning of the bus' I/O space.

ioWrite8

Abstract: Writes a 8-bit value to an I/O space aperture.
public:

virtual void ioWrite8( UInt16 offset, UInt8 value, IOMemoryMap * map = 0 );

This method will write a 8-bit value to an offset in an I/O space aperture. If a map object is passed in, the value is written relative to it, otherwise to the value is written relative to the I/O space aperture for the bus. This function encapsulates the differences between architectures in generating I/O space operations. An eieio instruction is included on PPC.

Parameters

NameDescription
offsetAn offset into a bus or device's I/O space aperture.
valueThe value to be written in host byte order (big endian on PPC).
mapIf the offset is relative to the beginning of a device's aperture, an IOMemoryMap object for that object should be passed in. Otherwise, passing zero will write the value relative to the beginning of the bus' I/O space.

mapDeviceMemoryWithRegister

Abstract: Maps a physical range of the device.
public:

virtual IOMemoryMap * mapDeviceMemoryWithRegister( UInt8 reg, IOOptionBits options = 0 );

This method will create a mapping for the IODeviceMemory for the physical memory range that was assigned to the configuration space base address register passed in, with IODeviceMemory::map(options). The mapping is represented by the returned instance of IOMemoryMap, which should not be released until the mapping is no longer required. This method is analogous to IOService::mapDeviceMemoryWithIndex.

Parameters

NameDescription
indexAn index into the array of ranges assigned to the device.
Result: An instance of IOMemoryMap, or zero if the index is beyond the count available. The mapping should be released only when access to it is no longer required.

setBusMasterEnable

Abstract: Sets the device's bus master enable.
public:

virtual bool setBusMasterEnable( bool enable );

This method sets the bus master enable bit in the device's command config space register to the passed value, and returns the previous state of the enable.

Parameters

NameDescription
enableTrue or false to enable or disable bus mastering.
Result: True if bus mastering was previously enabled, false otherwise.

setConfigBits

Abstract: Sets masked bits in a configuration space register.
public:

virtual UInt32 setConfigBits( UInt8 offset, UInt32 mask, UInt32 value );

This method sets masked bits in a configuration space register on the device by reading and writing the register. The value of the masked bits before the write is returned.

Parameters

NameDescription
offsetAn 8-bit offset into configuration space, of which bits 0-1 are ignored.
maskAn 32-bit mask indicating which bits in the value parameter are valid.
dataAn 32-bit value to be written in host byte order (big endian on PPC).
Result: The value of the register masked with the mask before the write.

setIOEnable

Abstract: Sets the device's I/O space response.
public:

virtual bool setIOEnable( bool enable, bool exclusive = false );

This method sets the I/O space response bit in the device's command config space register to the passed value, and returns the previous state of the enable. The exclusive option allows only one exclusive device on the bus to be enabled concurrently, this should be only for temporary access.

Parameters

NameDescription
enableTrue or false to enable or disable the I/O space response.
exclusiveIf true, only one setIOEnable with the exclusive flag set will be allowed at a time on the bus, this should be only for temporary access.
Result: True if the I/O space response was previously enabled, false otherwise.

setMemoryEnable

Abstract: Sets the device's memory space response.
public:

virtual bool setMemoryEnable( bool enable );

This method sets the memory space response bit in the device's command config space register to the passed value, and returns the previous state of the enable.

Parameters

NameDescription
enableTrue or false to enable or disable the memory space response.
Result: True if the memory space response was previously enabled, false otherwise.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOPacketQueue.h

IOPacketQueue.h



© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOPacketQueue

IOPacketQueue



Member Functions

dequeue

public:

struct mbuf * dequeue();

Remove a single packet from the head of the queue.

Result: The dequeued packet. A NULL is returned if the queue is empty.

dequeueAll

public:

struct mbuf * dequeueAll();

Removes all packets from the queue and return the head of the packet chain.

Result: The head of the dequeued packet chain.

enqueue

public:

UInt32 enqueue(struct mbuf * m);

Add a packet (or a packet chain) to the tail of the queue.

Parameters

NameDescription
mA single packet, or a packet chain, to be added to the tail of the queue.
Result: The number of packets dropped due to over-capacity.

flush

public:

UInt32 flush();

Removes all packets from the queue and put them back to the free buffer pool. The size of the queue becomes zero after the call.

Result: The number of packets freed.

free

private:

virtual void free();

Frees the IOPacketQueue instance. All packets in the queue are released back to the free buffer pool.


freePacketChain

public:

static UInt32 freePacketChain(struct mbuf * m);

This method frees a mbuf chain linked through the mbuf's nextpkt pointers.

Parameters

NameDescription
mThe mbuf at the start of the mbuf chain.
Result: The number of mbufs freed.

getCapacity

public:

UInt32 getCapacity() const;

Get the capacity of the queue.

Result: The current queue capacity.

getPeakSize

public:

UInt32 getPeakSize(bool reset = false);

The queue contains a counter that registers the peak size of the queue. This method returns the value in the counter, and optionally resets the counter to zero.

Parameters

NameDescription
resetReset the peak size counter to zero if true.
Result: The peak size count.

getSize

public:

UInt32 getSize() const;

Get the size of the queue.

Result: The number of packets currently held in the queue.

initWithCapacity

public:

virtual bool initWithCapacity(UInt32 capacity = IOPQDefaultCapacity);

Initialize an IOPacketQueue instance.

Parameters

NameDescription
capacityThe initial capacity of the queue.
Result: true if initialized successfully, false otherwise.

lockDequeue

public:

struct mbuf * lockDequeue();

Same as dequeue(). A spinlock lock is held while the queue is being accessed.

Result: See dequeue().

lockDequeueAll

public:

struct mbuf * lockDequeueAll();

Same as dequeueAll(). A spinlock lock is held while the queue is being accessed.

Result: See dequeueAll().

lockEnqueue

public:

UInt32 lockEnqueue(struct mbuf * m);

Same as enqueue(). A spinlock lock is held while the queue is being accessed.

Parameters

NameDescription
Seeenqueue().
Result: See enqueue().

lockFlush

public:

UInt32 lockFlush();

Same as flush(). A spinlock lock is held while the queue is being accessed.

Result: See flush().

lockPrepend

public:

void lockPrepend(struct mbuf * m);

Same as prepend(). A spinlock lock is held while the queue is being accessed.

Parameters

NameDescription
Seeprepend().

peek

public:

const struct mbuf * peek() const;

Peek at the head of the queue without dequeueing the packet. Subsequent calls to peek() or dequeue() will return the same packet. The caller must not modify the packet.

Result: The packet at the head of the queue.

prepend

public:

void prepend(struct mbuf * m);

Add a packet (or a packet chain) to the head of the queue. Unlike enqueue(), the capacity is not checked, and the input packet is never dropped.

Parameters

NameDescription
mA single packet, or packet chain, to be added to the head of the queue.

setCapacity

public:

bool setCapacity(UInt32 capacity);

Adjust the capacity of the queue. If the capacity is set to a value that is smaller than its current size, then the queue will drop incoming packets, but existing packets in the queue will remain intact.

Parameters

NameDescription
capacityThe new capacity.
Result: true if the new capacity was accepted, false otherwise.

withCapacity

public:

static IOPacketQueue * withCapacity(UInt32 capacity = IOPQDefaultCapacity);

Factory method that will construct and initialize an IOPacketQueue instance.

Parameters

NameDescription
capacityThe initial capacity of the queue.
Result: An IOPacketQueue instance upon success, or 0 otherwise.

Member Data

IOPQDefaultCapacity

private:
 static const UInt32 IOPQDefaultCapacity = 100;

Specifies the default capacity of the queue (number of packets that the queue can hold). Once the size of the queue grows to its capacity, the queue will begin to drop incoming packets. This capacity can be overridden by specifying the desired capacity when the queue is initialized, or the setCapacity() method can be called to adjust the queue's capacity.


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOPartitionScheme.h

IOPartitionScheme.h



#defines

kIOMediaPartitionID

kIOMediaPartitionID is property of IOMedia objects. It is an OSNumber.

#define kIOMediaPartitionID "Partition ID"

The kIOMediaPartitionID property is placed into each IOMedia instance created via the partition scheme. It is an ID that differentiates one partition from the other (within a given scheme). It is typically an index into the on-disk partition table.


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOPartitionScheme

IOPartitionScheme



Member Functions

handleClose

protected:

virtual void handleClose(IOService * client, IOOptionBits options);

The handleClose method closes the client's access to this object. * This implementation replaces the IOService definition of handleClose().

Parameters

NameDescription
clientClient requesting the close.
optionsOptions for the close. Set to zero.

handleIsOpen

protected:

virtual bool handleIsOpen(const IOService * client) const;

The handleIsOpen method determines whether the specified client, or any client if none is specificed, presently has an open on this object. * This implementation replaces the IOService definition of handleIsOpen().

Parameters

NameDescription
clientClient to check the open state of. Set to zero to check the open state of all clients.
Result: Returns true if the client was (or clients were) open, false otherwise.

handleOpen

protected:

virtual bool handleOpen(IOService * client, IOOptionBits options, void * access);

The handleOpen method grants or denies permission to access this object to an interested client. The argument is an IOStorageAccess value that specifies the level of access desired -- reader or reader-writer. * This method can be invoked to upgrade or downgrade the access level for an existing client as well. The previous access level will prevail for upgrades that fail, of course. A downgrade should never fail. If the new access level should be the same as the old for a given client, this method will do nothing and return success. In all cases, one, singular close-per-client is expected for all opens-per-client received. * This implementation replaces the IOService definition of handleOpen().

Parameters

NameDescription
clientClient requesting the open.
optionsOptions for the open. Set to zero.
accessAccess level for the open. Set to kAccessReader or kAccessReaderWriter.
Result: Returns true if the open was successful, false otherwise.

read

public:

virtual void read(IOService * client, UInt64 byteStart, IOMemoryDescriptor * buffer, IOStorageCompletion completion);

Read data from the storage object at the specified byte offset into the specified buffer, asynchronously. When the read completes, the caller will be notified via the specified completion action. * The buffer will be retained for the duration of the read. * For simple partition schemes, the default behavior is to simply pass the read through to the provider media. More complex partition schemes such as RAID will need to do extra processing here.

Parameters

NameDescription
clientClient requesting the read.
byteStartStarting byte offset for the data transfer.
bufferBuffer for the data transfer. The size of the buffer implies the size of the data transfer.
completionCompletion routine to call once the data transfer is complete.

write

public:

virtual void write(IOService * client, UInt64 byteStart, IOMemoryDescriptor * buffer, IOStorageCompletion completion);

Write data into the storage object at the specified byte offset from the specified buffer, asynchronously. When the write completes, the caller will be notified via the specified completion action. * The buffer will be retained for the duration of the write. * For simple partition schemes, the default behavior is to simply pass the write through to the provider media. More complex partition schemes such as RAID will need to do extra processing here.

Parameters

NameDescription
clientClient requesting the write.
byteStartStarting byte offset for the data transfer.
bufferBuffer for the data transfer. The size of the buffer implies the size of the data transfer.
completionCompletion routine to call once the data transfer is complete.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IORangeAllocator.h

IORangeAllocator.h



© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IORangeAllocator

IORangeAllocator



Member Functions

allocate

Abstract: Allocate from the free list, at any offset.
public:

virtual bool allocate( IORangeScalar size, IORangeScalar * result, IORangeScalar alignment = 0 );

This method allocates a range from the free list. The alignment will default to the alignment set when the allocator was created or may be set here.

Parameters

NameDescription
sizeThe size of the range requested.
resultThe beginning of the range allocated is returned here on success.
alignmentIf zero is passed, default to the allocators alignment, otherwise pass an alignment required for the allocation, for example 4096 to page align.
Result: True if the allocation was successful, else false.

allocateRange

Abstract: Allocate from the free list, at a set offset.
public:

virtual bool allocateRange( IORangeScalar start, IORangeScalar size );

This method allocates a range from the free list, given a set offset passed in.

Parameters

NameDescription
startThe beginning of the range requested.
sizeThe size of the range requested.
Result: True if the allocation was successful, else false.

deallocate

Abstract: Deallocate a range to the free list.
public:

virtual void deallocate( IORangeScalar start, IORangeScalar size );

This method deallocates a range to the free list, given a the start offset and length passed in.

Parameters

NameDescription
startThe beginning of the range requested.
sizeThe size of the range requested.

getFragmentCapacity

Abstract: Accessor to return the number of free fragments in the range.
public:

virtual UInt32 getFragmentCapacity( void );

This method returns the current capacity of the free fragment list.

Result: The current capacity of free fragment list.

getFragmentCount

Abstract: Accessor to return the number of free fragments in the range.
public:

virtual UInt32 getFragmentCount( void );

This method returns a count of free fragments. Each fragment describes a non-contiguous free range - deallocations will merge contiguous fragments together.

Result: The count of free fragments.

getFreeCount

Abstract: Totals the sizes of the free fragments.
public:

virtual IORangeScalar getFreeCount( void );

This method returns the total of the sizes of the fragments on the free list.

Result: The total of the free fragments sizes.

init

Abstract: Standard initializer for IORangeAllocator.
public:

virtual bool init( IORangeScalar endOfRange, IORangeScalar defaultAlignment, UInt32 capacity, IOOptionBits options );

This method initializes an IORangeAllocator and optionally sets the free list to contain one fragment, from zero to an endOfRange parameter. The capacity in terms of free fragments and locking options are set for the instance.

Parameters

NameDescription
endOfRangeIf the free list is to contain an initial fragment, set endOfRange to the last offset in the range, ie. size - 1, to create a free fragment for the range zero to endOfRange inclusive. If zero is passed the free list will be initialized empty, and can be populated with calls to the deallocate method.
defaultAlignmentIf this parameter is non-zero it specifies a required alignment for all allocations, for example pass 256 to align allocations on 256 byte boundaries. Zero or one specify unaligned allocations.
capacitySets the initial size of the free list in number of non-contiguous fragments. This value is also used for the capacityIncrement.
optionsPass kLocking if the instance can be used by multiple threads.
Result: Returns true if the instance is successfully initialize, false on failure.

setFragmentCapacityIncrement

Abstract: Sets the count of fragments the free list will increase by when full.
public:

virtual void setFragmentCapacityIncrement( UInt32 count );

This method sets the number of extra fragments the free list will expand to when full. It defaults to the initial capacity.

Parameters

NameDescription
countThe number of fragments to increment the capacity by when the free list is full.

withRange

Abstract: Standard factory method for IORangeAllocator.
public:

static IORangeAllocator * withRange( IORangeScalar endOfRange, IORangeScalar defaultAlignment = 0, UInt32 capacity = 0, IOOptionBits options = 0 );

This method allocates and initializes an IORangeAllocator and optionally sets the free list to contain one fragment, from zero to an endOfRange parameter. The capacity in terms of free fragments and locking options are set for the instance.

Parameters

NameDescription
endOfRangeIf the free list is to contain an initial fragment, set endOfRange to the last offset in the range, ie. size - 1, to create a free fragment for the range zero to endOfRange inclusive. If zero is passed the free list will be initialized empty, and can be populated with calls to the deallocate method.
defaultAlignmentIf this parameter is non-zero it specifies a required alignment for all allocations, for example pass 256 to align allocations on 256 byte boundaries. Zero or one specify unaligned allocations.
capacitySets the initial size of the free list in number of non-contiguous fragments. This value is also used for the capacityIncrement.
optionsPass kLocking if the instance can be used by multiple threads.
Result: Returns the new IORangeAllocator instance, to be released by the caller, or zero on failure.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IORegistryEntry.h

IORegistryEntry.h



© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IORegistryEntry

IORegistryEntry



Member Functions

attachToChild

Abstract: Method called in the parent entry when a child attaches.
public:

virtual bool attachToChild( IORegistryEntry * child, const IORegistryPlane * plane );

This method is called in the parent entry when a child attaches, to make overrides possible. This method will also call attachToParent in the child entry if it is not being called from attachToParent. It is a no-op and success if the entry is already a child. Attaching the entry into the registry retains both the child and parent while they are attached.

Parameters

NameDescription
childThe registry entry being attached.
planeThe plane object.
Result: true on success, or false on a resource failure, or if the parent is the same as the child.

attachToParent

Abstract: Attaches a entry to a parent entry in a plane.
public:

virtual bool attachToParent( IORegistryEntry * parent, const IORegistryPlane * plane );

This is the usual method of entering an entry into the registry. It is a no-op and success if the entry is already attached to the parent. Attaching the entry into the registry retains both the child and parent while they are attached. This method will call attachToChild in the parent entry if it is not being called from attachToChild.

Parameters

NameDescription
parentThe registry entry to attach to.
planeThe plane object.
Result: true on success, or false on a resource failure, or if the parent is the same as the child.

compareName

Abstract: Compares the name of the entry with one name, and optionally returns the matching name.
public:

virtual bool compareName( OSString * name, OSString ** matched = 0 ) const;

This method is called during IOService name matching and elsewhere from the compareNames method. It should be overridden to provide non-standard name matching.

Parameters

NameDescription
nameThe name to compare with as an OSString.
matchedIf the caller wants the successfully matched name returned, pass a non-zero pointer for the matched parameter and an OSString will be returned here. It should be released by the caller. Generally, this will be the same as the name parameter, but may not be if wildcards are used.
Result: True if the name compared true with the entry's global name.

compareNames

Abstract: Compares the name of the entry with one or more names, and optionally returns the matching name.
public:

virtual bool compareNames( OSObject * name, OSString ** matched = 0 ) const;

This method is called during IOService name matching and elsewhere to compare the entry's global name with a list of names, or a single name. A list of names may be passed as any OSCollection of OSStrings, while a single name may be passed an OSString, in the name parameter. compareNames will call the compareName method for each name, for overrides.

Parameters

NameDescription
nameThe name or names to compare with as any OSCollection (eg. OSArray, OSSet, OSDictionary) of OSStrings, or a single name may be passed an OSString.
matchedIf the caller wants the successfully matched name returned, pass a non-zero pointer for the matched parameter and an OSString will be returned here. It should be released by the caller.
Result: True if one of the names compared true with the entry's global name.

copyLocation

Abstract: Returns the location string assigned to the registry entry as an OSSymbol.
public:

virtual const OSSymbol * copyLocation( const IORegistryPlane * plane = 0 ) const;

Entries can given a location string in a particular plane, or globally. If the entry has had a location set in a plane and the plane is specified that location string will be returned, otherwise the global location string is returned. If no global location string has been set, zero is returned.

Parameters

NameDescription
planeThe plane object, or zero for the global name.
Result: A reference to an OSSymbol for the location if one exists, which should be released by the caller, or zero.

copyName

Abstract: Returns the name assigned to the registry entry as an OSSymbol.
public:

virtual const OSSymbol * copyName( const IORegistryPlane * plane = 0 ) const;

Entries can be named in a particular plane, or globally. If the entry is named in plane and the plane is specified that name will be returned, otherwise the global name is returned. The global name defaults to the entry's meta class name if it has not been named.

Parameters

NameDescription
planeThe plane object, or zero for the global name.
Result: A reference to an OSSymbol for the name, which should be released by the caller.

dealiasPath

Abstract: Strips any aliases from the head of path returns the full path.
public:

static const char * dealiasPath( const char ** opath, const IORegistryPlane * plane );

If the path specified begins with an alias found in the /aliases entry, the value of the alias is returned, and a pointer into the passed in path after the alias is passed back to the caller. If an alias is not found, zero is returned and the path parameter is unchanged.

Parameters

NameDescription
opathAn in/out paramter - the caller passes in a pointer to a C-string pointer to a path. If an alias is found, dealiasPath returns a pointer into the path just beyond the end of the alias.
planeA plane object must be specified.
Result: A C-string pointer to the value of the alias if one is found, or zero if not.

detachAbove

Abstract: Detaches an entry from all its parent entries in a plane.
public:

virtual void detachAbove( const IORegistryPlane * plane );

This method calls detachFromParent in the entry for each of its parent entries in the plane.

Parameters

NameDescription
planeThe plane object.

detachAll

Abstract: Detaches an entry and all its children recursively in a plane.
public:

virtual void detachAll( const IORegistryPlane * plane );

This method breaks the registry connections for a subtree. detachAbove is called in the entry, and all child entries and their children in the plane.

Parameters

NameDescription
planeThe plane object.

detachFromChild

Abstract: Detaches a child entry from its parent in a plane.
public:

virtual void detachFromChild( IORegistryEntry * child, const IORegistryPlane * plane );

This method is called in the parent entry when a child detaches, to make overrides possible. It is a no-op if the entry is not a child of the parent. Detaching the entry will release both the child and parent. This method will call detachFromParent in the child entry if it is not being called from detachFromParent.

Parameters

NameDescription
parentThe registry entry to detach.
planeThe plane object.

detachFromParent

Abstract: Detaches an entry from a parent entry in a plane.
public:

virtual void detachFromParent( IORegistryEntry * parent, const IORegistryPlane * plane );

This is the usual method of removing an entry from the registry. It is a no-op if the entry is not attached to the parent. Detaching the entry will release both the child and parent. This method will call detachFromChild in the parent entry if it is not being called from detachFromChild.

Parameters

NameDescription
parentThe registry entry to detach from.
planeThe plane object.

dictionaryWithProperties

Abstract: Synchronized method to obtain copy a registry entry's property table.
public:

virtual OSDictionary * dictionaryWithProperties( void ) const;

This method will copy a registry entry's property table, using the OSDictionary::withDictionary semantics. This method is synchronized with other IORegistryEntry accesses to the property table. Since OSDictionary will only copy property values by reference, synchronization is not guaranteed to any collection values.

Result: The created dictionary, or zero on a resource value. It should be released by the caller.

free

Abstract: Standard free method for all IORegistryEntry subclasses.
public:

virtual void free( void );

This method will release any resources of the entry, in particular its property table. Note that the registry entry must always be detached from the registry before free may be called, and subclasses (namely IOService) will have additional protocols for removing registry entries. free should never need be called directly.


fromPath

Abstract: Looks up a registry entry by relative path.
public:

virtual IORegistryEntry * childFromPath( const char * path, const IORegistryPlane * plane = 0, char * residualPath = 0, int * residualLength = 0 );

This function looks up a entry below the called entry by a relative path. It is just a convenience that calls IORegistryEntry::fromPath with this as the fromEntry parameter.

Parameters

NameDescription
pathSee IORegistryEntry::fromPath.
planeSee IORegistryEntry::fromPath.
residualPathSee IORegistryEntry::fromPath.
residualLengthSee IORegistryEntry::fromPath.
Result: See IORegistryEntry::fromPath.

fromPath

Abstract: Looks up a registry entry by path.
public:

static IORegistryEntry * fromPath( const char * path, const IORegistryPlane * plane = 0, char * residualPath = 0, int * residualLength = 0, IORegistryEntry * fromEntry = 0 );

This function parses paths to lookup registry entries. The path may begin with the : created by getPath, or the plane may be set by the caller. If there are characters remaining unparsed after an entry has been looked up, this may be considered an invalid lookup, or those characters may be passed back to the caller and the lookup successful.

Parameters

NameDescription
pathA C-string path.
planeThe plane to lookup up the path, or zero, in which case the path must begin with the plane name.
residualPathIf the path may contain residual characters after the last path component, the residual will be copied back to the caller's residualPath buffer. If there are residual characters and no residual buffer is specified, fromPath will fail.
residualLengthAn in/out parameter - the caller sets the length of the residual buffer available, and fromPath returns the total length of the residual path copied to the buffer. If there is no residualBuffer (residualPath = 0) then residualLength may be zero also.
fromEntryThe lookup will proceed rooted at this entry if non-zero, otherwise it proceeds from the root of the plane.
Result: A retained registry entry is returned on success, or zero on failure. The caller should release the entry.

getChildEntry

Abstract: Returns an registry entry's first child entry in a plane.
public:

virtual IORegistryEntry * getChildEntry( const IORegistryPlane * plane ) const;

This function will return the child which first attached to a registry entry.

Parameters

NameDescription
planeThe plane object.
Result: Returns the first child of the registry entry, or zero if the entry is not attached into the registry in that plane. The child is retained while the entry is attached, and should not be released by the caller.

getChildIterator

Abstract: Returns an iterator over an registry entry's child entries in a plane.
public:

virtual OSIterator * getChildIterator( const IORegistryPlane * plane ) const;

This method creates an iterator which will return each of a registry entry's child entries in a specified plane.

Parameters

NameDescription
planeThe plane object.
Result: Returns an iterator over the children of the entry, or zero if there is a resource failure. The iterator must be released when the iteration is finished. All objects returned by the iteration are retained while the iterator is valid, though they may no longer be attached during the iteration.

getDepth

Abstract: Counts the maximum number of entries between an entry and the registry root, in a plane.
public:

virtual unsigned int getDepth( const IORegistryPlane * plane ) const;

This method counts the number of entries between and entry and the registry root, in a plane, for each parent of the entry and returns the maximum value.

Parameters

NameDescription
planeThe plane object.
Result: The maximum number of entries between the entry and the root. Zero is returned if the entry is not attached in the plane.

getGenerationCount

Abstract: Returns an generation count for all registry changing operations.
public:

static SInt32 getGenerationCount( void );

This method provides an accessor to the current generation count (or seed) of the registry which changes when any topology change occurs in the registry - this does not include property table changes. It may be used to invalidate any caching of the results from IORegistryEntry methods.

Result: An integer generation count.

getLocation

Abstract: Returns the location string assigned to the registry entry as a C-string.
public:

virtual const char * getLocation( const IORegistryPlane * plane = 0 ) const;

Entries can given a location string in a particular plane, or globally. If the entry has had a location set in a plane and the plane is specified that location string will be returned, otherwise the global location string is returned. If no global location string has been set, zero is returned.

Parameters

NameDescription
planeThe plane object, or zero for the global name.
Result: A C-string location string, valid while the entry is retained, or zero.

getName

Abstract: Returns the name assigned to the registry entry as a C-string.
public:

virtual const char * getName( const IORegistryPlane * plane = 0 ) const;

Entries can be named in a particular plane, or globally. If the entry is named in plane and the plane is specified that name will be returned, otherwise the global name is returned. The global name defaults to the entry's meta class name if it has not been named.

Parameters

NameDescription
planeThe plane object, or zero for the global name.
Result: A C-string name, valid while the entry is retained.

getParentEntry

Abstract: Returns an registry entry's first parent entry in a plane.
public:

virtual IORegistryEntry * getParentEntry( const IORegistryPlane * plane ) const;

This function will return the parent to which a registry entry was first attached. Since the majority of registry entrys have only one provider, this is a useful simplification.

Parameters

NameDescription
planeThe plane object.
Result: Returns the first parent of the registry entry, or zero if the entry is not attached into the registry in that plane. The parent is retained while the entry is attached, and should not be released by the caller.

getParentIterator

Abstract: Returns an iterator over an registry entry's parent entries in a specified plane.
public:

virtual OSIterator * getParentIterator( const IORegistryPlane * plane ) const;

Parameters

NameDescription
planeThe plane object.
Result: Returns an iterator over the parents of the registry entry, or zero if there is a resource failure. The iterator must be released when the iteration is finished. All objects returned by the iteration are retained while the iterator is valid, though they may no longer be attached during the iteration.

getPath

Abstract: Create a path for a registry entry.
public:

virtual bool getPath( char * path, int * length, const IORegistryPlane * plane) const;

The path for a registry entry is copied to the caller's buffer. The path describes the entry's attachment in a particular plane, which must be specified. The path begins with the plane name followed by a colon, and then followed by '/' separated path components for each of the entries between the root and the registry entry. Each component is constructed with the getPathComponent method called in each entry. An alias may also exist for the entry, which are described as properties in a registry entry found at /aliases in the plane. If a property value interpreted as a path in a call to IORegistryEntry::fromPath yields the entry, then the property name is used as the entry's path.

Parameters

NameDescription
pathA char buffer allocated by the caller.
lengthAn in/out parameter - the caller sets the length of the buffer available, and getPath returns the total length of the path copied to the buffer.
planeThe plane object.
Result: getPath will fail if the entry is not attached in the plane, or if the buffer is not large enough to contain the path.

getPathComponent

Abstract: Create a path component for a registry entry.
public:

virtual bool getPathComponent( char * path, int * length, const IORegistryPlane * plane ) const;

Each component of a path created with getPath is created with getPathComponent. The default implementation concatenates the entry's name in the the plane, with the "at" symbol and the location string of the entry in the plane if it has been set.

Parameters

NameDescription
pathA char buffer allocated by the caller.
lengthAn in/out parameter - the caller sets the length of the buffer available, and getPathComponent returns the total length of the path component copied to the buffer.
planeThe plane object.
Result: true if the path fits into the supplied buffer or false on a overflow.

getPlane

Abstract: Looks up the plane object by a C-string name.
public:

static const IORegistryPlane * getPlane( const char * name );

Planes are usually provided as globals by the creator, eg. gIOServicePlane, gIODeviceTreePlane, or gIOAudioPlane, however they may also be looked up by name with this method.

Result: A pointer to the plane object, or zero if no such plane exists. The returned plane should not be released.

getProperty

Abstract: Synchronized method to obtain a property from a registry entry's property table.
public:

virtual OSObject * getProperty( const OSSymbol * aKey) const;

This method will lookup a property in a registry entry's property table, using the OSDictionary::getObject semantics. This method is synchronized with other IORegistryEntry accesses to the property table.

Parameters

NameDescription
aKeyThe property's name as a OSymbol.
Result: The property value found, or zero.

getProperty

Abstract: Synchronized method to obtain a property from a registry entry's property table.
public:

virtual OSObject * getProperty( const OSString * aKey) const;

This method will lookup a property in a registry entry's property table, using the OSDictionary::getObject semantics. This method is synchronized with other IORegistryEntry accesses to the property table.

Parameters

NameDescription
aKeyThe property's name as anOSString.
Result: The property value found, or zero.

getProperty

Abstract: Synchronized method to obtain a property from a registry entry's property table.
public:

virtual OSObject * getProperty( const char * aKey) const;

This method will lookup a property in a registry entry's property table, using the OSDictionary::getObject semantics. This method is synchronized with other IORegistryEntry accesses to the property table.

Parameters

NameDescription
aKeyThe property's name as a C-string.
Result: The property value found, or zero.

getPropertyTable

Abstract: Unsynchronized accessor to a registry entry's property table.
public:

inline OSDictionary * getPropertyTable( void ) const { return(fPropertyTable); }

This method will return a pointer to the live property table as an OSDictionery. Its use is not recommended in most cases, instead use the synchronized accessors and helper functions of IORegistryEntry to access properties. It can only safely be used by one thread, which usually means it can only be used before a registry entry is entered into the registry.

Result: A pointer to the property table as an OSDictionary. The pointer is valid while the registry entry is retained, and should not be released by the caller.

getRegistryRoot

Abstract: Returns a pointer to the root instance of the registry.
public:

static IORegistryEntry * getRegistryRoot( void );

This method provides an accessor to the root of the registry for the machine. The root may be passed to a registry iterator when iterating a plane, and contains properties that describe the available planes, and diagnostic information for IOKit. Keys for these properties are in IOKitKeys.h.

Result: A pointer to the IORegistryEntry root instance. It should not be released by the caller.

inPlane

Abstract: Determines whether a registry entry is attached in a plane.
public:

virtual bool inPlane( const IORegistryPlane * plane ) const;

This method determines if the entry is attached in a plane to any other entry.

Parameters

NameDescription
planeThe plane object.
Result: If the entry has a parent in the plane, true is returned, otherwise false is returned.

init

Abstract: Standard init method for all IORegistryEntry subclasses.
public:

virtual bool init( OSDictionary * dictionary = 0 );

A registry entry must be initialized with this method before it can be used. A property dictionary may passed and will be retained by this method for use as the registry entry's property table, or an empty one will be created.

Parameters

NameDescription
Adictionary that will become the registry entry's property table (retaining it), or zero which will cause an empty property table to be created.
Result: true on success, or false on a resource failure.

isChild

Abstract: Determines whether a registry entry is the child of another in a plane.
public:

virtual bool isChild( IORegistryEntry * child, const IORegistryPlane * plane, bool onlyChild = false ) const;

This method called in the parent entry determines if the specified entry is a child, in a plane. Additionally, it can check if the child is the only child of the parent entry.

Parameters

NameDescription
childThe possible child registry entry.
planeThe plane object.
onlyChildIf true, check also if the child is the only child.
Result: If the child argument is not a child of the registry entry, false is returned. If onlyChild is true and the child is not the only child of the entry, false is returned, otherwise true is returned.

isParent

Abstract: Determines whether a registry entry is the parent of another in a plane.
public:

virtual bool isParent( IORegistryEntry * parent, const IORegistryPlane * plane, bool onlyParent = false ) const;

This method called in the child entry determines if the specified entry is a parent, in a plane. Additionally, it can check if the parent is the only parent of the child entry.

Parameters

NameDescription
parentThe possible parent registry entry.
planeThe plane object.
onlyParentIf true, check also if the parent is the only parent.
Result: If the parent argument is not a parent of the registry entry, false is returned. If onlyParent is true and the parent is not the only parent of the entry, false is returned, otherwise true is returned.

removeProperty

Abstract: Synchronized method to remove a property from a registry entry's property table.
public:

virtual void removeProperty( const char * aKey);

This method will remove a property from a registry entry's property table, using the OSDictionary::removeObject semantics. This method is synchronized with other IORegistryEntry accesses to the property table.

Parameters

NameDescription
aKeyThe property's name as a C-string.

removeProperty

Abstract: Synchronized method to remove a property from a registry entry's property table.
public:

virtual void removeProperty( const OSSymbol * aKey);

This method will remove a property from a registry entry's property table, using the OSDictionary::removeObject semantics. This method is synchronized with other IORegistryEntry accesses to the property table.

Parameters

NameDescription
aKeyThe property's name as an OSSymbol.

removeProperty

Abstract: Synchronized method to remove a property from a registry entry's property table.
public:

virtual void removeProperty( const OSString * aKey);

This method will remove a property from a registry entry's property table, using the OSDictionary::removeObject semantics. This method is synchronized with other IORegistryEntry accesses to the property table.

Parameters

NameDescription
aKeyThe property's name as an OSString.

serializeProperties

Abstract: Synchronized method to serialize a registry entry's property table.
public:

virtual bool serializeProperties( OSSerialize * serialize ) const;

This method will serialize a registry entry's property table, using the OSDictionary::serialize semantics. This method is synchronized with other IORegistryEntry accesses to the property table. Many non-kernel clients of IOKit read information from the registry via properties, and will invoke this method in a registry entry to create a serialization of all the entry's properties, which is then reconstructed in the client's task as a CFDictionary. This method may be intercepted by subclasses to update their properties or implement a different serialization method, though it is usually better to implement such functionality by creating objects in the property table and implementing their serialize methods, avoiding any need to implement serializeProperties.

Parameters

NameDescription
serializeThe OSSerialize instance representing the serialization request.
Result: True on success, false otherwise.

setLocation

Abstract: Sets a location string for the registry entry, in a particular plane, or globally.
public:

virtual void setLocation( const OSSymbol * location, const IORegistryPlane * plane = 0 );

Entries can be given a location string in a particular plane, or globally. If the plane is specified the location applies only to that plane, otherwise the global location is set. The location string may be used during path lookups of registry entries, to distinguish between sibling entries with the same name. The default IORegistryEntry parsing of location strings expects a list of hex numbers separated by commas, though subclasses of IORegistryEntry might do their own parsing.

Parameters

NameDescription
locationA C-string location string which will be copied, or an OSSymbol which will be retained.
planeThe plane object, or zero to set the global location string.

setName

Abstract: Sets a name for the registry entry, in a particular plane, or globally.
public:

virtual void setName( const OSSymbol * name, const IORegistryPlane * plane = 0 );

Entries can be named in a particular plane, or globally. If the plane is specified the name applies only to that plane, otherwise the global name is set. The global name defaults to the entry's meta class name if it has not been named.

Parameters

NameDescription
nameAn OSSymbol which will be retained.
planeThe plane object, or zero to set the global name.

setName

Abstract: Sets a name for the registry entry, in a particular plane, or globally.
public:

virtual void setName( const char * name, const IORegistryPlane * plane = 0 );

Entries can be named in a particular plane, or globally. If the plane is specified the name applies only to that plane, otherwise the global name is set. The global name defaults to the entry's meta class name if it has not been named.

Parameters

NameDescription
nameA const C-string name which will be copied.
planeThe plane object, or zero to set the global name.

setProperties

Abstract: Optionally supported external method to set properties in a registry entry.
public:

virtual IOReturn setProperties( OSObject * properties );

This method is not implemented by IORegistryEntry, but is available to kernel and non-kernel clients to set properties in a registry entry. IOUserClient provides connection based, more controlled access to this functionality and may be more appropriate for many uses, since there is no differentiation between clients available to this method.

Parameters

NameDescription
propertiesAny OSObject subclass, to be interpreted by the implementing method - for example an OSDictionary, OSData etc. may all be appropriate.
Result: An IOReturn code to be returned to the caller.

setProperty

Abstract: Synchronized method to construct and add an OSBoolean property to a registry entry's property table.
public:

virtual bool setProperty(const char * aKey, bool aBoolean);

This method will add or replace a property in a registry entry's property table, using the OSDictionary::setObject semantics. This method is synchronized with other IORegistryEntry accesses to the property table. The property is created as an OSBoolean from the supplied value, set in the property table with the given name, and released.

Parameters

NameDescription
aKeyThe property's name as a C-string.
aBooleanThe property's boolean value.
Result: true on success or false on a resource failure.

setProperty

Abstract: Synchronized method to add a property to a registry entry's property table.
public:

virtual bool setProperty(const char * aKey, OSObject * anObject);

This method will add or replace a property in a registry entry's property table, using the OSDictionary::setObject semantics. This method is synchronized with other IORegistryEntry accesses to the property table.

Parameters

NameDescription
aKeyThe property's name as a C-string.
anObjectThe property value.
Result: true on success or false on a resource failure.

setProperty

Abstract: Synchronized method to construct and add a OSString property to a registry entry's property table.
public:

virtual bool setProperty(const char * aKey, const char * aString);

This method will add or replace a property in a registry entry's property table, using the OSDictionary::setObject semantics. This method is synchronized with other IORegistryEntry accesses to the property table. The property is created as an OSString from the supplied C-string, set in the property table with the given name, and released.

Parameters

NameDescription
aKeyThe property's name as a C-string.
aStringThe property value as a C-string.
Result: true on success or false on a resource failure.

setProperty

Abstract: Synchronized method to add a property to a registry entry's property table.
public:

virtual bool setProperty(const OSString * aKey, OSObject * anObject);

This method will add or replace a property in a registry entry's property table, using the OSDictionary::setObject semantics. This method is synchronized with other IORegistryEntry accesses to the property table.

Parameters

NameDescription
aKeyThe property's name as an OSString.
anObjectThe property value.
Result: true on success or false on a resource failure.

setProperty

Abstract: Synchronized method to add a property to a registry entry's property table.
public:

virtual bool setProperty(const OSSymbol * aKey, OSObject * anObject);

This method will add or replace a property in a registry entry's property table, using the OSDictionary::setObject semantics. This method is synchronized with other IORegistryEntry accesses to the property table.

Parameters

NameDescription
aKeyThe properties name as an OSSymbol.
anObjectThe property value.
Result: true on success or false on a resource failure.

setProperty

Abstract: Synchronized method to construct and add an OSData property to a registry entry's property table.
public:

virtual bool setProperty( const char * aKey, void * bytes, unsigned int length);

This method will add or replace a property in a registry entry's property table, using the OSDictionary::setObject semantics. This method is synchronized with other IORegistryEntry accesses to the property table. The property is created as an OSData copied from the supplied date and length, set in the property table with the given name, and released.

Parameters

NameDescription
aKeyThe property's name as a C-string.
bytesThe property's value as a pointer. OSData will copy this data.
lengthThe property's size in bytes, for OSData.
Result: true on success or false on a resource failure.

setProperty

Abstract: Synchronized method to construct and add an OSNumber property to a registry entry's property table.
public:

virtual bool setProperty( const char * aKey, unsigned long long aValue, unsigned int aNumberOfBits);

This method will add or replace a property in a registry entry's property table, using the OSDictionary::setObject semantics. This method is synchronized with other IORegistryEntry accesses to the property table. The property is created as an OSNumber from the supplied value and size, set in the property table with the given name, and released.

Parameters

NameDescription
aKeyThe property's name as a C-string.
aValueThe property's numeric value.
aNumberOfBitsThe property's size in bits, for OSNumber.
Result: true on success or false on a resource failure.

setPropertyTable

Abstract: Replace a registry entry's property table.
public:

virtual void setPropertyTable( OSDictionary * dict );

This method will release the current property table of a the entry and replace it with another, retaining the new property table.

Parameters

NameDescription
dictThe new dictionary to be used as the entry's property table.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IORegistryIterator

IORegistryIterator



Member Functions

enterEntry

Abstract: Recurse into the current entry in the registry iteration.
public:

virtual void enterEntry( const IORegistryPlane * plane );

This method recurses into an entry as with enterEntry, but also switches from the current plane to a new one set by the caller.

Parameters

NameDescription
planeThe new plane to switch into.

enterEntry

Abstract: Recurse into the current entry in the registry iteration.
public:

virtual void enterEntry( void );

This method makes the current entry, ie. the last entry returned by getNextObject et al., the root in a new level of recursion.


exitEntry

Abstract: Exits a level of recursion, restoring the current entry.
public:

virtual bool exitEntry( void );

This method undoes an enterEntry, restoring the current entry. If there are no more levels of recursion to exit false is returned, otherwise true is returned.

Result: true if a level of recursion was undone, false if no recursive levels are left in the iteration.

getCurrentEntry

Abstract: Return the current entry in the registry iteration.
public:

virtual IORegistryEntry * getCurrentEntry( void );

This method returns the current entry, last returned by getNextObject et al. The object returned is retained while the iterator is pointing at it (its the current entry), or recursing into it. The caller should not release it. If the iteration is no longer valid (see isValid), the current entry is zero.

Result: The current registry entry in the iteration, or zero if the last iteration returned zero, or the iteration is invalid (see isValid). The entry returned is retained while the iterator is pointing at it (its the current entry), or recursing into it. The caller should not release it.

getNextObject

Abstract: Return the next object in the registry iteration.
public:

virtual IORegistryEntry * getNextObject( void );

This method calls either getNextObjectFlat or getNextObjectRecursive depending on the options the iterator was created with. This implements the OSIterator defined getNextObject method. The object returned is retained while the iterator is pointing at it (its the current entry), or recursing into it. The caller should not release it.

Parameters

NameDescription
planeA plane object must be specified.
Result: The next registry entry in the iteration (the current entry), or zero if the iteration has finished at this level of recursion. The entry returned is retained while the iterator is pointing at it (its the current entry), or recursing into it. The caller should not release it.

getNextObjectFlat

Abstract: Return the next object in the registry iteration, ignoring the kIORegistryIterateRecursively option.
public:

virtual IORegistryEntry * getNextObjectFlat( void );

This method returns the next child, or parent if the kIORegistryIterateParents option was used to create the iterator, of the current root entry. The object returned is retained while the iterator is pointing at it (its the current entry), or recursing into it. The caller should not release it.

Parameters

NameDescription
planeA plane object must be specified.
Result: The next registry entry in the iteration (the current entry), or zero if the iteration has finished at this level of recursion, or the iteration is invalid (see isValid). The entry returned is retained while the iterator is pointing at it (its the current entry), or recursing into it. The caller should not release it.

getNextObjectRecursive

Abstract: Return the next object in the registry iteration, and enter it.
public:

virtual IORegistryEntry * getNextObjectRecursive( void );

If the iterator has a current entry, and the iterator has not already entered previously, enterEntry is called to recurse into it, ie. make it the new root, and the next child, or parent if the kIORegistryIterateParents option was used to create the iterator, at this new level of recursion is returned. If there is no current entry at this level of recursion, exitEntry is called and the process repeats, until the iteration returns to the entry the iterator was created with and zero is returned. The object returned is retained while the iterator is pointing at it (its the current entry), or recursing into it. The caller should not release it.

Parameters

NameDescription
planeA plane object must be specified.
Result: The next registry entry in the iteration (the current entry), or zero if its finished, or the iteration is invalid (see isValid). The entry returned is retained while the iterator is pointing at it (its the current entry), or recursing into it. The caller should not release it.

isValid

Abstract: Checks that no registry changes have invalidated the iteration.
public:

virtual bool isValid( void );

If a registry iteration is invalidated by changes to the registry, it will be made invalid, the currentEntry will be considered zero, and further calls to getNextObject et al. will return zero. The iterator should be reset to restart the iteration when this happens.

Result: false if the iterator has been invalidated by changes to the registry, true otherwise.

iterateAll

Abstract: Iterates all entries (with getNextObject) and returns a set of all returned entries.
public:

virtual OSOrderedSet * iterateAll( void );

This method will reset, then iterate all entries in the iteration (with getNextObject) until successful (ie. the iterator is valid at the end of the iteration).

Result: A set of entries returned by the iteration. The caller should release the set when it has finished with it. Zero is returned on a resource failure.

iterateOver

Abstract: Create an iterator rooted at a given registry entry.
public:

static IORegistryIterator * iterateOver( IORegistryEntry * start, const IORegistryPlane * plane, IOOptionBits options = 0 );

This method creates an IORegistryIterator that is set up with options to iterate children or parents of a root entry, and to recurse automatically into entries as they are returned, or only when instructed. The iterator object keeps track of entries that have been recursed into previously to avoid loops.

Parameters

NameDescription
startThe root entry to begin the iteration at.
planeA plane object must be specified.
optionskIORegistryIterateRecursively may be set to recurse automatically into each entry as it is returned. This option affects the behaviour of the getNextObject method, which is defined in the OSIterator superclass. Other methods will override this behaviour. kIORegistryIterateParents may be set to iterate the parents of each entry, by default the children are iterated.
Result: A created IORegistryIterator instance, to be released by the caller when it has finished with it.

iterateOver

Abstract: Create an iterator rooted at the registry root.
public:

static IORegistryIterator * iterateOver( const IORegistryPlane * plane, IOOptionBits options = 0 );

This method creates an IORegistryIterator that is set up with options to iterate children of the registry root entry, and to recurse automatically into entries as they are returned, or only when instructed. The iterator object keeps track of entries that have been recursed into previously to avoid loops.

Parameters

NameDescription
planeA plane object must be specified.
optionskIORegistryIterateRecursively may be set to recurse automatically into each entry as it is returned. This option affects the behaviour of the getNextObject method, which is defined in the OSIterator superclass. Other methods will override this behaviour. kIORegistryIterateParents may be set to iterate the parents of each entry, by default the children are iterated.
Result: A created IORegistryIterator instance, to be released by the caller when it has finished with it.

reset

Abstract: Exits all levels of recursion, restoring the iterator to its state at creation.
public:

virtual void reset( void );

This method exits all levels of recursion, and restores the iterator to its state at creation.


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOSCSICDDrive.h

IOSCSICDDrive.h



© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOSCSICDDrive

IOSCSICDDrive



Member Functions

audioPause

Abstract: Pause or resume the audio playback.
public:

virtual IOReturn audioPause(bool pause);

Parameters

NameDescription
pauseTrue to pause playback; False to resume.

audioPlay

Abstract: Play audio.
public:

virtual IOReturn audioPlay(positioningType addressType,cdAddress address, audioPlayMode mode);

Parameters

NameDescription
addressTypeThe type of positioning address. See positioningType for details.
addressThe position from which to begin.
modeThe mode for playing the audio. See audioPlayMode for details.

audioScan

Abstract: Perform a fast-forward or fast-backward operation.
public:

virtual IOReturn audioScan(positioningType addressType,cdAddress address,bool reverse);

Parameters

NameDescription
addressTypeThe type of positioning address. See positioningType for details.
addressThe position from which to begin.
reverseTrue to go backward; False to go forward.

audioTrackSearch

Abstract: Position the optical pick-up at the specified audio address.
public:

virtual IOReturn audioTrackSearch(positioningType addressType,cdAddress address, bool startPlay,audioPlayMode mode);

Parameters

NameDescription
addressTypeThe type of positioning address. See positioningType for details.
addressThe position from which to begin.
startPlayTrue to begin playing audio after positioning; False to enter the pause state.
modeThe mode for playing the audio. See audioPlayMode for details.

convertMSFToLba

Abstract: Convert an MM:SS:FF value to a Logical Block Address
protected:

virtual IOReturn convertMSFToLba(UInt32 *lba,cdAddress address);

Parameters

NameDescription
lbaA pointer to the returned LBA.
addressThe address to convert from MM:SS:FF format.

deviceTypeMatches

Abstract: Determine if the device type matches that which we expect.
public:

virtual bool deviceTypeMatches(UInt8 inqBuf[],UInt32 inqLen);

This override allows us to check for the SCSI CD-ROM device type instead of hard disk. See IOBasicSCSI for details.


doAudioPlayCommand

Abstract: Issue an audio play command to the device.
protected:

virtual IOReturn doAudioPlayCommand(positioningType startType,cdAddress startAddress, positioningType endType,cdAddress endAddress);

Parameters

NameDescription
startTypeThe type of positioning address. See positioningType for details.
startAddressThe position from which to begin.
endTypeThe type of positioning address. See positioningType for details.
endAddressThe position at which to end.

getAudioStatus

Abstract: Return the current audio play status information.
public:

virtual IOReturn getAudioStatus(struct audioStatus *status);

Parameters

NameDescription
statusThe buffer for the returned information.

getDeviceTypeName

Abstract: Return a character string for the device type.
public:

virtual const char * getDeviceTypeName(void);

This override returns kDeviceTypeCDROM.


initAudioModes

Abstract: Initialize audio modes for the device when media is changed.
protected:

virtual void initAudioModes(void);


instantiateNub

Abstract: Create the device nub.
public:

virtual IOService * instantiateNub(void);

This override instantiates an IOSCSICDDriveNub instead of an IOSCSIHDDriveNub.


mediaGone

Abstract: React to media going away.
protected:

virtual void mediaGone(void);


playModeToDriveBits

Abstract: Convert an audioPlayMode value to the format used by the device.
protected:

virtual UInt8 playModeToDriveBits(audioPlayMode mode,channel chan);

Parameters

NameDescription
modeThe audioPlayMode value to be converted.
chanThe desired audio channel.

readAudioData

Abstract: Read audio data blocks.
public:

virtual IOReturn readAudioData(positioningType addressType,cdAddress address, UInt8 blockCount,UInt8 *buffer);

Parameters

NameDescription
addressTypeThe type of positioning address. See positioningType for details.
addressThe position from which to begin.
blockCountThe number of blocks to read.
bufferThe buffer for the data.

readAudioSubcodes

Abstract: Read audio subcodes only.
public:

virtual IOReturn readAudioSubcodes(positioningType addressType,cdAddress address, UInt8 blockCount,UInt8 *buffer);

Parameters

NameDescription
addressTypeThe type of positioning address. See positioningType for details.
addressThe position from which to begin.
blockCountThe number of blocks to read.
bufferThe buffer for the data.

readAudioVolume

Abstract: Read the current audio volume.
public:

virtual IOReturn readAudioVolume(UInt8 *leftVolume,UInt8 *rightVolume);

Parameters

NameDescription
leftVolumeA pointer to the returned left-channel volume.
rightVolumeA pointer to the returned right-channel volume.

readAudioWithAllSubcodes

Abstract: Read audio data along with all subcodes.
public:

virtual IOReturn readAudioWithAllSubcodes(positioningType addressType,cdAddress address, UInt8 blockCount,UInt8 *buffer);

Parameters

NameDescription
addressTypeThe type of positioning address. See positioningType for details.
addressThe position from which to begin.
blockCountThe number of blocks to read.
bufferThe buffer for the data.

readAudioWithQSubcode

Abstract: Read audio blocks along with the Q subcode.
public:

virtual IOReturn readAudioWithQSubcode(positioningType addressType,cdAddress address, UInt8 blockCount,UInt8 *buffer);

Parameters

NameDescription
addressTypeThe type of positioning address. See positioningType for details.
addressThe position from which to begin.
blockCountThe number of blocks to read.
bufferThe buffer for the data.

readHeader

Abstract: Read the header for the specified logical block.
public:

virtual IOReturn readHeader(UInt32 blockAddress,struct headerInfo *buffer);

Parameters

NameDescription
addressThe logical block from which to read the header data.
bufferThe buffer for the header data.

readISRC

Abstract: Read the ISRC data for the disc.
public:

virtual IOReturn readISRC(UInt32 track,UInt8 *buffer,bool *found);

Parameters

NameDescription
trackThe track number from which to read the ISRC.
bufferThe buffer for the ISRC data.
foundA pointer to the result: True if the ISRC was found, else False.

readISRCMCN

Abstract: Perform the command necessary to read ISRC or MCN data.
protected:

virtual IOReturn readISRCMCN(UInt8 dataformat,UInt32 track,UInt8 *buffer,bool *found);

Parameters

NameDescription
dataformatThe desired data format: ISRC or MCN.
trackThe desired track from which to read the data
bufferThe buffer for the data.
foundA pointer to the result: True if the item was found; false if not.

readMCN

Abstract: Read the MCN (Media Catalog Number) for the disc.
public:

virtual IOReturn readMCN(UInt8 *buffer,bool *found);

Parameters

NameDescription
bufferThe buffer for the MCN data.
foundA pointer to the result: True if the ISRC was found, else False.

readQSubcodes

Abstract: Read the Q subcode entries in the lead-in areas of the disc.
public:

virtual IOReturn readQSubcodes(struct qSubcodeTocInfo *buffer,UInt32 bufSize);

Parameters

NameDescription
bufferThe buffer for the returned data
bufSizeThe size of the buffer in bytes.

readSubchannel

Abstract: Issue the command necessary to read subchannel data.
protected:

virtual IOReturn readSubchannel(UInt8 *buffer,UInt32 length,UInt8 track,UInt8 dataFormat);

Parameters

NameDescription
bufferThe buffer for the data.
lengthThe maximum data length desired.
trackThe desired track from which to read the data
dataFormatThe subchannel data desired.

readSubcodeBuffer

Abstract: Read the device subcode buffer while audio is playing.
public:

virtual IOReturn readSubcodeBuffer(UInt8 *buffer,bool purge,UInt32 entryCount);

Parameters

NameDescription
bufferThe buffer for the returned data
purgeTrue if the buffer should be purged before doing the read.
entryCountThe number of consecutive subcode blocks (96 bytes each) to return.

readTOC

Abstract: Read the entire Table Of Contents (TOC) for the disc.
public:

virtual IOReturn readTOC(struct rawToc *buffer,UInt32 length,tocFormat format);

Parameters

NameDescription
bufferThe buffer for the returned data
lengthThe maximum length of the buffer.
formatThe desired TOC format desired. See tocFormat for details.

readTheQSubcode

Abstract: Read the Q-subcode information for the current track.
public:

virtual IOReturn readTheQSubcode(struct qSubcode *buffer);

Parameters

NameDescription
bufferThe buffer for the returned data

reportMediaState

Abstract: Report the device's media state.
public:

virtual IOReturn reportMediaState(bool *mediaPresent,bool *changed);

This override allows us to reset device settings when media changes.


seek

Abstract: Issue the command necessary to position the device at the specified LBA.
protected:

virtual IOReturn seek(UInt32 lba);

Parameters

NameDescription
lbaThe desired Logical Block Address at which to position the device.

setAudioStopAddress

Abstract: Set the address at which the device is to stop playing audio.
public:

virtual IOReturn setAudioStopAddress(positioningType addressType,cdAddress address);

Parameters

NameDescription
addressTypeThe type of positioning address. See positioningType for details.
addressThe position from which to begin.

setDefaultAudioModes

Abstract: Set the device audio modes to the default.
protected:

virtual IOReturn setDefaultAudioModes(void);

This method calls initAudioModes and then sets volume to the max.


setVolume

Abstract: Set the audio volume.
public:

virtual IOReturn setVolume(UInt8 leftVolume,UInt8 rightVolume);

Parameters

NameDescription
leftVolumeThe desired left-channel volume.
rightVolumeThe desired right-channel volume.

Member Data

_audioPlayMode

protected:
 audioPlayMode _audioPlayMode;

The current audio play mode for the device.


_leftPortChannel

protected:
 UInt8 _leftPortChannel; /* matches IOCDTypes consts */

 /*!
 * @var _rightPortChannel
 * The current signal-routing assignment of the right-channel audio signal.
 */
 UInt8 _rightPortChannel; /* matches IOCDTypes consts */

 struct qualifiedCDAddress _audioStopAddress;
};

The current signal-routing assignment of the left-channel audio signal.


_leftVolume

protected:
 UInt8 _leftVolume;

The current volume of the left channel.


_rightVolume

protected:
 UInt8 _rightVolume;

The current volume of the right channel.


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOSCSICommand_Reference.h

IOSCSICommand_Reference.h



Typedefs

SCSICDBInfo

typedef  struct  SCSICDBInfo  {

  UInt32  cdbFlags;

  UInt32  cdbTagMsg;
  UInt32  cdbTag;

  UInt32  cdbAbortMsg;

  UInt32  cdbLength;
  UInt8  cdb[16];
  
  UInt32  reserved[16];
}  SCSICDBInfo;

Fields specified here are set by IOSCSIDevice client, while others are set by the IOSCSIController class for use by the host adapter driver. The client should zero all fields of the structure prior to use.

Fields

NameDescription
cdbFlagsSee enum SCSICDBFlags for flag definitions.
cdbTagMsgThis field should be set to zero by the IOSCSIDevice client. If the SCSI device supports tag queuing then the IOSCSIController class will set this field to select simple (unordered) tags.
cdbTagThis field is set by the IOSCSIController class to tell the host adapter driver the SCSI tag value to assign to this IOSCSICommand.
cdbLengthSet by the IOSCSIDevice client to the length of the Command Descriptor Block (CDB).
cdbSet by the IOSCSIDevice client to command descriptor block the client wishes the target to execute.

SCSIResults

typedef  struct  SCSIResults  {
  IOReturn  returnCode;
  
  UInt32  bytesTransferred;

  UInt32  adapterStatus;  
  UInt8  scsiStatus;
  
  bool  requestSenseDone;
  UInt32  requestSenseLength;
}  SCSIResults;

Fields

NameDescription
returnCodeThe overall return code for the command. See iokit/iokit/IOReturn.h. This value is also returned as the getResults() return value.

Note: The exact subset of return codes a SCSI command will return is currently under review.
bytesTransferredThe total number of bytes transferred to/from the target device.
adapterStatusThis field provides additional adapter reported error information. The SCSI Family uses this information to determine whether the target rejected a negotiation attempt (either/or) wide or synchronous.
scsiStatusThe SCSI Status byte returned from the target device.
requestSenseDoneA boolean indicating whether sense data was obtained from the target device.
requestSenseLengthThe number of sense data bytes returned from the target device.

Structs

SCSITargetLun

typedef  struct  SCSITargetLun  {
  UInt8  target;
  UInt8  lun;
  UInt8  reserved[2];
}  SCSITargetLun;

Fields

NameDescription
targetThe SCSI Id for the SCSI device being selected.
lunThe SCSI Lun for the SCSI device being selected.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOSCSICommand

IOSCSICommand



Member Functions

abort

Abstract: Aborts an executing SCSI Command.
public:

void abort( UInt32 sequenceNumber );

The client may invoke the abort() method to force the completion of an executing SCSI Command. The client must pass the sequence number provided when the execute() function was invoked.

Note: The abort function provides no status on whether or not a command has been successfully aborted. The client should wait for the command to actually complete to determine whether the abort completed successfully.

Parameters

NameDescription
sequenceNumberThe client must pass the sequence number assigned to the command when the client called the execute() function.

complete

Abstract: Indicates the IOSCSIController subclass (host adapter driver) has completed a SCSI command.
public:

void complete();

Once the complete() function is called, the controller subclass should make no further accesses to the IOSCSICommand being completed.

A IOSCSIDevice client would not normally call this function.


execute

Abstract: Submits a SCSI command to be executed.
public:

bool execute( UInt32 *sequenceNumber = 0 );

Once the execute() function is called, the client should not invoke any further functions on the SCSI Command with the exception of abort().

The execute() function optionally returns sets a unique sequence number token for the command. If the client intends to use the abort() method they must retain this sequence number token.

Parameters

NameDescription
sequenceNumberPointer to field (UInt32) to receive the sequence number assigned to the SCSI Command.

getCDB

Abstract: Gets the CDB component of a SCSI Command.
public:

void getCDB( SCSICDBInfo *scsiCmd );

Parameters

NameDescription
scsiCDBPointer to a SCSICDBInfo structure to receive the SCSI Command's cdb information.

getClientData

Abstract: Returns a pointer to the SCSI Command's client data area.
public:

void *getClientData();

The client may allocate storage in the SCSI Command for its own use. See IOSCSIDevice::allocateCmd().


getCmdType

Abstract: Obtains the underlying 'intent' of a SCSI Command.
public:

UInt32 getCmdType();

This function provides information on the intent of a SCSI Command. For example, since Aborts, Request Sense and normal Execute commands are all sent to the executeCommand() function, invoking getCmdType() will indicate whether a Request Sense, Abort or Normal I/O request is being processed.

It this information is not normally meaningful to IOSCSIDevice clients.


getDevice

Abstract: Returns the IOSCSIDevice this command is targeted to.
public:

IOSCSIDevice *getDevice( IOSCSIDevice *deviceType );

In some cases a IOSCSICommand is not associated with a specific target/lun. This would be the case for a SCSI Bus Reset. In this case getDevice() returns 0.

Parameters

NameDescription
deviceTypeThe caller should use value kIOSCSIDeviceType.

getOriginalCmd

Abstract: Obtains a 'related' SCSI Command.
public:

IOSCSICommand *getOriginalCmd();

In cases where a SCSI command is related to a previous command, this function will return the original command. For example, if a Request Sense command (CmdType = kSCSICommandReqSense)is processed, then this function can be used to obtain the original command that caused the check condition. If an Abort command (CmdType = kSCSICommandAbort) then this function can be used to obtain the original command the abort was issued against.


It this information is not normally meaningful to IOSCSIDevice clients.


getPointers

Abstract: Gets the data buffer component of a SCSI Command.
public:

void getPointers( IOMemoryDescriptor **desc, UInt32 *transferCount, bool *isWrite, bool isSense = false );

The client provides a set of pointers to fields to receive the IOSCSICommand's data/request sense buffer pointers.

Parameters

NameDescription
descPointer to a field (IOMemoryDescriptor *) to receive the IOSCSICommand's IOMemoryDescriptor pointer.
transferCountPointer to a field (UInt32) to receive the IOSCSICommand's maximum transfer count.
isWritePointer to a field (bool) to receive the IOSCSICommand's transfer direction.
isSenseIf isSense is set to true, the IOSCSICommand's data buffer information is returned. Otherwise, the IOSCSICommand's request sense buffer information is returned.

getQueueInfo

Abstract: Gets queuing information for the SCSI Command.
public:

void getQueueInfo( UInt32 *queueType, UInt32 *queuePosition = 0 );

Parameters

NameDescription
queueTypePointer to a field (UInt32) to receive the queue type previously set for this SCSI Command.
queuePositionPointer to a field (UInt32) to receive the queue position previously set for this SCSI Command.

getResults

Abstract: Gets results from a completed SCSI Command.
public:

IOReturn getResults( SCSIResults *results );

The getResults() function returns the value of the returnCode field of the command results. If the client is only interested in a pass/fail indication for the command, the client can pass (SCSIResult *)0 as a parameter.

Parameters

NameDescription
resultsPointer to a SCSIResults structure to receive the SCSI Commands completion information.

getSequenceNumber

Abstract: Returns the sequence number assigned to an executing command.
public:

UInt32 getSequenceNumber();

The caller should check the sequence number for 0. This indicates that the command has completed or has not been processed to the point where a sequence number has been assigned.


getTargetLun

Abstract: Returns the target/lun for the IOSCSIDevice this command is associated with.
public:

void getTargetLun( SCSITargetLun *targetLun );

Parameters

NameDescription
targetLunPointer to a SCSITargetLun structure to receive the target/lun information.

getTimeout

Abstract: Gets the timeout for the command in milliseconds.
public:

UInt32 getTimeout();

This function returns the command timeout previously set by setTimeout().

Parameters

NameDescription
timeoutCommand timeout in milliseconds.

setCDB

Abstract: Sets the CDB component of a SCSI Command.
public:

void setCDB( SCSICDBInfo *scsiCmd );

Parameters

NameDescription
scsiCDBPointer to a SCSICDBInfo structure.

setCallback

Abstract: Sets the callback routine to be invoked when the SCSI Command completes.
public:

void setCallback( void *target = 0, CallbackFn callback = 0, void *refcon = 0 );

Parameters

NameDescription
targetPointer to the object to be passed to the callback routine. This would usually be the client's (this) pointer.
callbackPointer to the client's function to process the completed command
refconPointer to the information required by the client's callback routine to process the completed command.

setPointers

Abstract: Sets the data buffer component of a SCSI Command.
public:

void setPointers( IOMemoryDescriptor *desc, UInt32 transferCount, bool isWrite, bool isSense=false );

The client provides an IOMemoryDescriptor object to corresponding to the client's data or request sense buffer, the maximum data transfer count and data transfer direction.

Parameters

NameDescription
descPointer to a IOMemoryDescriptor describing the client's I/O buffer.
transferCountMaximum data transfer count in bytes.
isWriteData transfer direction. (Defined with respect to the device, i.e. isWrite = true indicates the host is writing to the device.
isSenseIf isSense is set to true, the IOSCSICommand's data buffer information is set. Otherwise, the IOSCSICommand's request sense buffer information is set

setQueueInfo

Abstract: Sets queuing information for the SCSI Command.
public:

void setQueueInfo( UInt32 queueType = kQTypeNormalQ, UInt32 queuePosition = kQPositionTail );

Each IOSCSIDevice has two queues, a normal Q and a bypass Q. The treatment of the queues is esentially identical except that the bypass Q is given preference whenever it has commands available.

Usually, the client will use the normal Q for regular I/O commands and the bypass Q to send error recovery commands to the device.

Parameters

NameDescription
queueTypeSet to kQTypeNormalQ or kQTypeBypassQ to indicate which IOSCSIDevice queue the SCSI Command should be routed to.
queuePositionSet to kQPositionTail or kQPositionHead to indicate whether the SCSI Command should be added to the head to tail for the selected IOSCSIDevice queue.

setResults

Abstract: Sets the results component of a SCSI Command.
public:

void setResults( SCSIResults *results );

The setResults() function is used by the IOSCSIController subclass (host adapter driver) return results for a SCSI Command about to be completed.

Parameters

NameDescription
scsiResultsPointer to a SCSIResults structure containing completion information for the SCSI Command.

Completion information is copied into the command, so the caller may release the SCSIResults structure provided when this function returns.

setTimeout

Abstract: Sets the timeout for the command in milliseconds.
public:

void setTimeout( UInt32 timeoutmS );

The IOSCSIController class will abort a command which does not complete with in the time interval specified. The client should set the timeout parameter to zero if they want to suppress timing.

Parameters

NameDescription
timeoutCommand timeout in milliseconds.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOSCSIController_Reference.h

IOSCSIController_Reference.h



Typedefs

SCSIControllerInfo

typedef  struct  SCSIControllerInfo  {
  UInt32  initiatorId;

  UInt32  maxTargetsSupported;
  UInt32  maxLunsSupported;

  UInt32  minTransferPeriodpS;
  UInt32  maxTransferOffset;
  UInt32  maxTransferWidth;  
  
  UInt32  maxCommandsPerController;
  UInt32  maxCommandsPerTarget;
  UInt32  maxCommandsPerLun;

  UInt32  tagAllocationMethod;
  UInt32  maxTags;

  UInt32  targetPrivateDataSize;
  UInt32  lunPrivateDataSize;
  UInt32  commandPrivateDataSize;

  bool  disableCancelCommands;

  UInt32  reserved[64];

}  SCSIControllerInfo;

Parameter structure passed for configure() function.

Fields

NameDescription
initiatorIdThe SCSI address of your host adapter. Usually 7 (decimal).
maxTargetsSupportedThe number of targets you controller supports. Typically 8 or 16.
maxLunsSupportedThe number of logical units per target your controller supports. Typically 8.
minTransferPeriodpSThe minimum synchronous data transfer period in picoseconds your controller supports.
maxTransferOffsetThe maximum synchronous data offset your controller supports in bytes.
maxTransferWidthThe maximum data SCSI bus width your controller supports in bytes. Must be a power of 2.
maxCommandsPerControllerThe maximum number of outstanding commands your controller supports across all targets and luns. Set to 0 if there is no controller limit in this category.
maxCommandsPerTargetThe maximum number of outstanding commands your controller supports on a given target. Set to 0 if there is no controller limit in this category.
maxCommandsPerLunThe maximum number of outstanding commands your controller supports on a given lun. Set to 0 if there is no controller limit in this category.
tagAllocationMethodControls whether tags are allocated on a per Lun, per Target or per Controller basis. See enum SCSITagAllocation.
maxTagsThe maximum number of tags allocated to each Lun, Target or Controller depending on the tagAllocationMethod setting.
targetPrivateDataSizeIOSCSIController will optionally allocate per-target storage for your driver based on the setting of this field. The amount of storage needed is specified in bytes.
lunPrivateDataSizeIOSCSIController will optionally allocate per-lun storage for your driver based on the setting of this field. The amount of storage needed is specified in bytes.
commandPrivateDataSizeIOSCSIController will optionally allocate per-command storage for your driver based on the setting of this field. The amount of storage needed is specified in bytes.

Note: The amount of per-command storage allowed is under review. We anticipate that typical SCSI controllers will need not more than 1024 bytes per command.
disableCancelCommandsSubclasses of IOSCSIController which do their own management of aborts/resets can set this field to true to avoid receiving cancelCommand() requests.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOSCSIController

IOSCSIController



Member Functions

allocateLun

Abstract: Notifies driver of allocation of per-Lun resources.
public:

bool allocateLun( SCSITargetLun targetLun );

Your driver will be called at its allocateLun() function when a Lun is about to be probed. The your driver should initialize its per-lun data at this time. If the subclass wishes to prevent probing of this lun, it should return false as the result of this function call.

This is an optional function. Your driver is not required to implement it.

Parameters

NameDescription
targetLunSCSITargetLun structure containing the SCSI Id of the target/lun that is about to be allocated.

allocateTarget

Abstract: Notifies driver of allocation of per-Target resources.
public:

bool allocateTarget( SCSITargetLun targetLun );

Your driver will be called at its allocateTarget() function when a target is about to be probed. The your driver should initialize its per-target data at this time. If the subclass wishes to prevent probing of this target, it should return false as the result of this function call.

This is an optional function. Your driver is not required to implement it.

Parameters

NameDescription
targetLunSCSITargetLun structure containing the SCSI Id of the target that is about to be allocated.

cancelCommand

Abstract: Cancels a IOSCSICommand previously submitted to the driver.
public:

void cancelCommand( IOSCSICommand *scsiCommand );

The cancelCommand() function is called to inform your subclass to force completion of a SCSI command.

Your subclass should call the getOriginalCmd() to determine the command to complete.

After calling complete() on the original command, you should complete the IOSCSICommand passed to the cancelCommand() function

Note: When a cancelCommand is issued, your subclass may presume that any activity to remove an active command from the SCSI Target, i.e. (abort tag/abort) has already occurred.

Parameters

NameDescription
scsiCommandPointer to a IOSCSICommand. See IOSCSICommand for more information.

configure

Abstract: Driver configuration/initialization request.
public:

bool configure( IOService *provider, SCSIControllerInfo *controllerInfo );

The configure() member function is the first call your subclass will receive. You should provide the information requested in the SCSIControllerInfo structure and enable your hardware for operation. If your driver initialized successfully, you should return true, otherwise, your driver should return false.

Parameters

NameDescription
providerPointer to an object (usually IOPCIDevice) which represents the bus of your device is attached to . Typically your driver will use functions supplied by this object to access PCI space on your hardware. See IOPCIDevice for a description of PCI services.
controllerInfoPointer to a SCSIControllerInfo structure. Your driver should provide the information requested in this structure prior to returning from the configure() call.

deallocateLun

Abstract: Notifies driver of deallocation of per-Lun resources.
public:

bool allocateLun( SCSITargetLun targetLun );

Your driver will be called at its deallocateLun() function when a Lun is about deallocated. The your driver must insure that there will be no further access to the per-lun data allocated to this lun.

This is an optional function. Your driver is not required to implement it.

Parameters

NameDescription
targetLunSCSITargetLun structure containing the SCSI Id of the target/lun that is about to be deallocated.

deallocateTarget

Abstract: Notifies driver that target resources will be deallocated.
public:

bool deallocateTarget( SCSITargetLun targetLun );

Your driver will be called at its deallocateTarget() function when a target is about deallocated. The your driver must insure that there will be no further access to the per-target data allocated to this target.

This is an optional function. Your driver is not required to implement it.

Parameters

NameDescription
targetLunSCSITargetLun structure containing the SCSI Id of the target that is about to be deallocated.

disableCommands

Abstract: Suspend sending I/O commands to your driver.
public:

void disableCommands( UInt32 timeoutmS );

In cases where your executeCommand() member function cannot accept commands, you may disable further calls by invoking disableCommands(). Use enableCommands() to resume receiving commands.

Note: The resetCommand() and cancelCommands() entry points are not affected by the use of this function.

Note: The default timeout for disableCommands() is 5s. If this timeout is exceeded the IOSCSIController class will call your driver's disableTimeoutOccurred() function. The default action of this function is to issue a SCSI Bus Reset by calling your driver's resetCommand() function.

Parameters

NameDescription
timeoutmSYour driver may override the default timeout by specifying a timeout value in milliseconds.

disableTimeoutOccurred

Abstract: Indicates your driver has suspended commands too long.
public:

void disableTimeoutOccurred();

The IOSCSIController superclass will timeout disableCommand() requests to preclude the possibility of a hung SCSI bus. If a timeout occurs, then disableTimeoutOccurred() will be called. The default action of this routine is to do a SCSI Bus Reset by calling resetCommand(). Your subclass may choose to modify the default behavior of this routine to do additional adapter specific error recovery.


enableCommands

Abstract: Resume sending I/O commands to your driver.
public:

void enableCommands();

Resumes sending I/O commands to your driver that were previously suspended by calling disableCommands().


executeCommand

Abstract: Execute a IOSCSICommand.
public:

void executeCommand( IOSCSICommand *scsiCommand );

The executeCommand() function is called for all 'routine' I/O requests including abort requests. The driver is passed a pointer to an IOSCSICommand object. The driver obtains information about the I/O request by using function calls provided by the IOSCSICommand class.

Parameters

NameDescription
scsiCommandPointer to a IOSCSICommand. See IOSCSICommand for more information.

findCommandWithNexus

Abstract: Locate an active IOSCSICommand using target/lun/tag values.
public:

IOSCSICommand *findCommandWithNexus( SCSITargetLun targetLun, UInt32 tagValue = (UInt32) -1 );

Your subclass can use this function to search for an active IOSCSICommand by providing the target/lun/tag values for the command. In the case of a non-tagged command the second parameter must either be omitted or set to -1.

An unsuccessful search will return 0.

Parameters

NameDescription
targetLunStructure of type SCSITargetLun, initialized to the target/lun value you wish to search for.
tagValueOptional tag value you wish to search for.

getLunData

Abstract: Obtains a pointer to per-Lun data allocated by IOSCSIController.
public:

void *getLunData( SCSITargetLun targetLun );

This function returns a pointer to per-Lun workarea allocated for your driver's use. The size of this area must be specified during the configure() function. See struct SCSIControllerInfo, field lunDataSize.


getTargetData

Abstract: Obtains a pointer to per-Target data allocated by IOSCSIController.
public:

void *getTargetData( SCSITargetLun targetLun );

This function returns a pointer to per-Target workarea allocated for your driver's use. The size of this area must be specified in the during the configure() function. See struct SCSIControllerInfo, field targetDataSize.

Parameters

NameDescription
targetLunSCSITargetLun structure containing the SCSI Id of the target who's workarea you are requesting a pointer to.

getWorkLoop

Abstract: Returns the IOWorkLoop object that services your driver.
public:

IOWorkloop *getWorkLoop();


rescheduleCommand

Abstract: Return a IOSCSICommand for rescheduling.
public:

void rescheduleCommand( IOSCSICommand *scsiCommand );

If your subclass function cannot start processing an otherwise acceptable IOSCSICommand due to resource constraints, i.e. MailBox full, lost SCSI Bus arbitration, you may have the IOSCSICommand rescheduled by calling rescheduleCommand(). A IOSCSICommand passed to this function should be treated as 'complete', i.e. you should make no further accesses to it.

Note: If you cannot process further commands, you should call the disableCommands() function to prevent receiving additional commands until you are ready to accept them.

Parameters

NameDescription
scsiCommandPointer to IOSCSICommand your driver needs to reschedule.

resetCommand

Abstract: Request the driver issue a SCSI Bus reset.
public:

void resetCommand( IOSCSICommand *scsiCommand );

The resetCommand() function indicates you should do a SCSI Bus Reset. After issuing the reset you should complete to IOSCSICommand passed.

Note: After you report the IOSCSICommand Reset complete, you will receive cancelCommand() requests for all outstanding commands.

Parameters

NameDescription
scsiCommandPointer to a IOSCSICommand. See IOSCSICommand for more information.

resetOccurred

Abstract: Inform the IOSCSIController class of an unsolicited SCSI Bus reset.
public:

void resetOccurred();

Your subclass should call this function if you detect a target initiated bus reset, or need to do an unplanned SCSI Bus Reset as part of adapter error recovery.

Note: After you call the resetOccurred() function, you will receive cancelCommand() requests for all outstanding IOSCSICommand(s).


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOSCSIDevice_Reference.h

IOSCSIDevice_Reference.h



Typedefs

SCSILunParms

typedef  struct  SCSILunParms  {
  bool  disableDisconnect;
  
  UInt32  reserved[16];

}  SCSILunParms;

Parameter structure for get/setLunParms

Fields

NameDescription
disableDisconnectSetting disableDisconnect to true disables SCSI disconnect for SCSI Commands issued to the target/lun pair.

SCSITargetParms

typedef  struct  SCSITargetParms  {
  UInt32  transferPeriodpS;
  UInt32  transferOffset;
  UInt32  transferWidth;
  
  bool  enableTagQueuing;
  bool  disableParity;
  
  UInt32  reserved[16];

}  SCSITargetParms;

Parameter structure for get/setTargetParms

Fields

NameDescription
transferPeriodpSMinimum SCSI synchronous transfer period allowed for this target in picoseconds (10E-12). For asynchronous data transfer, set this field to 0.
transferOffsetMaximum SCSI synchronous transfer offset allowed for this target in bytes. For asynchronous data transfer, set this field to 0.
transferWidthMaximum SCSI bus width in bytes. Note: must be a power of 2.
enableTagQueuingSetting enableTagQueuing to true enables tag queuing for SCSI Commands issued to the target.
disableParitySet to (true) to disable parity checking on the SCSI bus for this target.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOSCSIDevice

IOSCSIDevice



Member Functions

abort

Abstract: Aborts all outstanding requests for the target/lun pair.
public:

void abort();

If any I/O requests are currently active for the target/lun, an abort command is sent to the device and any active requests are completed.

Prior to abort processing beginning, the client will be notified via:

message( kClientMsgDeviceAbort );

When abort processing is completed, the client will be notified via:

message( kClientMsgDeviceAbort | kClientMsgDone );

The client is responsible for managing the pending work queue for the device when an abort request occurs. See holdQueue(), flushQueue(), notifyIdle() functions.


allocCommand

Abstract: Allocates a IOSCSICommand object for this device.
public:

IOSCSICommand *allocCommand( IOSCSIDevice *scsiDevice, UInt32 clientDataSize = 0 );

The client uses the allocCommand() member function to allocate IOSCSICommand(s) for a IOSCSIDevice. The client then uses the member functions of the IOSCSICommand to initialize it and send it to the device. A completed IOSCSICommand may be reused for subsequent I/O requests or returned to the SCSI Family.

Parameters

NameDescription
scsiDeviceAlways specify kIOSCSIDevice.
clientDataSizeThe client may indicate the size of a per-command data area for its own use.

Note: The amount of per-command storage allowed is under review. We anticipate that typical SCSI clients will need not more than 1024 bytes per command.

close

Abstract: IOService close function
public:

void close( IOService *client, IOOptionBits options = 0 );

A client must close a IOSCSIDevice if the client plans no further accesses to it.

Parameters

NameDescription
clientPointer to the IOSCSI device the client is closing.
optionsThere are currently no options defined by the SCSI Family.

flushQueue

Abstract: Returns any commands on the IOSCSIDevice's pending work queue.
public:

void flushQueue( UInt32 queueType, IOReturn rc );

flushQueue() may only be called from the IOSCSIDevice workloop. This is guaranteed to be the case after a IOSCSICommand completion of after a message() notification.

All pending command are completed prior to flushQueue() returning to the caller.

flushQueue() has no effect on commands already passed to the host adapter. One or more commands may complete after the queue is flushed. See notifyIdle().

Parameters

NameDescription
queueTypePerform action on the indicated queue. See enum SCSIQueueType in IOSCSICommand.
rcThe return code of any flushed commands is set to (rc).

getInquiryData

Abstract: Returns SCSI Inquiry data for the IOSCSIDevice.
public:

void getInquiryData( void *inquiryBuffer, UInt32 inquiryBufSize, UInt32 *inquiryDataSize );

Inquiry data returned is from the results of the last SCSI bus probe.

Parameters

NameDescription
inquiryBufferPointer to a buffer to receive the Inquiry data.
inquiryBufSizeSize of the buffer supplied.
inquiryDataSizePointer to a UInt32 to receive the size of the Inquiry data actually returned.

getLunParms

Abstract: Gets the current logical unit parameters.
public:

void getLunParms( SCSILunParms *lunParms );

Returns the parameters currently in effect for the SCSI target/lun.

Parameters

NameDescription
lunParmsPointer to structure of type SCSITargetParms

getTargetParms

Abstract: Gets the current target parameters.
public:

void getTargetParms( SCSITargetParms *targetParms );

Returns the parameters currently in effect for the SCSI target. See setTargetParms().

Parameters

NameDescription
targetParmsPointer to structure of type SCSITargetParms.

getWorkLoop

Abstract: Returns the IOWorkLoop object that services this IOSCSIDevice.
public:

IOWorkloop *getWorkLoop();


holdQueue

Abstract: Suspends sending additional IOSCSICommands to the target/lun.
public:

holdQueue( UInt32 queueType );

holdQueue() may only be called from the IOSCSIDevice workloop. The client is guaranteed to be running in this context during a message() notification.

holdQueue() has no effect on commands already passed to the host adapter. One or more commands may complete after the queue is held. See notifyIdle()

Parameters

NameDescription
queueTypePerform action on the indicated queue. See enum SCSIQueueType in IOSCSICommand.

message

Abstract: IOService message function.
public:

IOReturn message( UInt32 type, IOService * provider, void * argument = 0 );

IOSCSIDevice notifies its client of significant 'events' by the IOService::message() api. When possible the client is notified of the event prior to any action taken. The client is responsible for managing the device queue for the IOSCSIDevice via the holdQueue(), releaseQueue(), flushQueue() and notifyIdle() api's.

Any return codes provided by the client are ignored.

Parameters

NameDescription
idMessage id's for IOSCSIDevice are defined by enum SCSIClientMessage
providerPointer to the IOSCSIDevice reporting the event.
argumentUnused.

notifyIdle

Abstract: Notifies the client when all active commands on a SCSI device have completed.
public:

void notifyIdle( void *target, Callback callback, void *refcon );

notifyIdle() may only be called from the IOSCSIDevice workloop. This is guaranteed to be the case after a IOSCSICommand completion of after a message() notification.

Only one notifyIdle() call may be active. Any outstanding notifyIdle() calls may be cancelled by calling notifyIdle() with no parameters.

Parameters

NameDescription
targetObject to receive the notification. Normally the client's (this) pointer.
callbackPointer to a callback routine of type CallbackFn.
refconPointer to client's private data.

open

Abstract: IOService open function
public:

bool open( IOService *client, IOOptionBits options = 0, void *arg = 0 );

A client should open a IOSCSIDevice prior to accessing it. Only one open is allowed per device.

Parameters

NameDescription
clientPointer to the IOSCSI device the client is opening.
optionsThere are currently no options defined by the SCSI Family.
argUnused. Omit or specify 0.

releaseQueue

Abstract: Resumes sending IOSCSICommands to the IOSCSIDevice.
public:

void releaseQueue( UInt32 queueType );

If the device queue was not held, releaseQueue() has no effect.

releaseQueue() may only be called from the IOSCSIDevice workloop. This is guaranteed to be the case after a IOSCSICommand completion of after a message() notification.

Parameters

NameDescription
queueTypePerform action on the indicated queue. See enum SCSIQueueType in IOSCSICommand.

reset

Abstract: Resets the SCSI target.
public:

void reset();

Since a SCSI target may have multiple logical units (lun(s)) the reset() function may affect multiple IOSCSIDevice instances. Processing for each lun is similar.

Prior to reset processing beginning, the client will be notified via:

message( kClientMsgDeviceReset );

When reset processing is completed, the client will be notified via:

message( kClientMsgDeviceReset | kClientMsgDone );

The client is responsible for managing the pending work queue for the device when an abort request occurs. See holdQueue(), flushQueue(), notifyIdle() functions.


setLunParms

Abstract: Sets the logical unit parameters for this device.
public:

bool setLunParms( SCSILunParms *lunParms );

This function will block until we attempt to set the requested parameters. It may not be called from the device's workloop context.

The SCSI Family will serialize accesses to the SCSI target/lun so as not to disrupt commands in progress prior to processing a change of lun parameters.

Parameters

NameDescription
lunParmsPointer to structure of type SCSILunParms

setTargetParms

Abstract: Sets SCSI parameters that apply to all luns on a SCSI target device.
public:

bool setTargetParms( SCSITargetParms *targetParms );

This function will block until we attempt to set the requested parameters. It may not be called from the device's workloop context.

The SCSI Family will serialize accesses to the SCSI target so as not to disrupt commands in progress prior to processing a change of target parameters.

Parameters

NameDescription
targetParmsPointer to structure of type SCSITargetParms.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOSCSIHDDrive.h

IOSCSIHDDrive.h



© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOSCSIHDDrive

IOSCSIHDDrive



Member Functions

RWCompletion

Abstract: Asynchronous read/write completion routine.
public:

virtual void RWCompletion(struct context *cx);

We implement this function in this class. It is called from the base class when an IO operation completes.


allocateFormatBuffer

Abstract: Create a data buffer to be used for formatting the media.
protected:

virtual IOReturn allocateFormatBuffer(UInt8 **buf,UInt32 *buflen);

If a format buffer is to be used, then "allocateFormatBuffer" and deleteFormatBuffer" must be overridden to manage the buffer. The buffer must be prepared for IO upon return from allocateFormatBuffer. The default implementations of these methods don't allocate a buffer.

Parameters

NameDescription
bufA pointer for the returned buffer pointer.
buflenThe desired length of the buffer, in bytes.

composeFormatBuffer

Abstract: Compose the data in the buffer used for the format command.
protected:

virtual UInt8 composeFormatBuffer(UInt8 *buf,UInt32 buflen);

This method will be called to compose the data in the format buffer.

The default implementation of this method does nothing.

Parameters

NameDescription
bufA pointer to the format data buffer.
buflenThe size of the format data buffer, in bytes.
Result: The return value should be the desired values for the "CmpLst" and Defect List Format bits in the CDB. The default implementation returns zero.

constructDeviceProperties

Abstract: Construct a set of properties about the device.
public:

virtual OSDictionary *constructDeviceProperties(void);

This function creates a set of properties reflecting information about the device.

This function is presently not used.

Result: A pointer to an OSDictionary containing the properties. The caller is responsible for releasing the OSDictionary.

createFormatCdb

Abstract: Create a SCSI CDB for a format operation.
protected:

virtual UInt32 createFormatCdb( UInt64 byteCapacity, /* in */ UInt8 *cdb, /* in */ UInt32 *cdbLength, /* out */ UInt8 buf[], /* in */ UInt32 bufLen, /* in */ UInt32 *maxAutoSenseLength, /* out */ UInt32 *timeoutSeconds); /* out */

Override this to control the cdb created for a format operation. The default implementation creates a 6-byte format command with no data buffer, disconnect allowed, 8-byte autosense, and a 15-minute timeout.

See also: allocateFormatBuffer, deleteFormatBuffer, composeFormatBuffer.

Parameters

NameDescription
byteCapacityThe requested byte capacity to which the media should be formatted. This value should have been previously validated, otherwise the device may return an error.
cdbA pointer to the CDB bytes.
cdbLengthThe length of the CDB in bytes.
blockThe device block to be written.
nblksThe number of blocks to be transferred.
maxAutoSenseLengthThe maximum size of the autosense data, in bytes. A value of zero will disable autosense.
timeoutSecondsThe command timeout in seconds.
Result: The IOSCSICommandOptions returned will be used to issue the command.

createNub

Abstract: Create, init, attach, and register the device nub.
protected:

virtual IOService * createNub(void);

This method calls instantiateNub, then init, attach, and register.

Result: A pointer to the nub or NULL if something failed.

deleteFormatBuffer

Abstract: Delete the data buffer to be used for formatting the media.
protected:

virtual void deleteFormatBuffer(UInt8 *buf,UInt32 buflen);

If a format buffer is to be used, then "allocateFormatBuffer" and deleteFormatBuffer" must be overridden to manage the buffer. The default implementation of this method does nothing.

Parameters

NameDescription
bufA pointer to the buffer to delete.
buflenThe size of the buffer, in bytes.

deviceTypeMatches

Abstract: Determine if device type matches expected type.
public:

virtual bool deviceTypeMatches(UInt8 inqBuf[],UInt32 inqLen);

We implement this function so we can return a match on the hard disk device type.


doAsyncReadWrite

Abstract: Start an asynchronous read or write operation.
public:

virtual IOReturn doAsyncReadWrite(IOMemoryDescriptor *buffer, UInt32 block,UInt32 nblks, gdCompletionFunction action, IOService *target,void *param);

See IOHDDriveNub for details.


doEjectMedia

Abstract: Eject the media.
public:

virtual IOReturn doEjectMedia(void);

See IOHDDriveNub for details.


doFormatMedia

Abstract: Format the media to the specified byte capacity.
public:

virtual IOReturn doFormatMedia(UInt64 byteCapacity);

The default implementation ignores the byteCapacity parameter. See IOHDDriveNub for details.


doGetFormatCapacities

Abstract: Return the allowable formatting byte capacities.
public:

virtual UInt32 doGetFormatCapacities(UInt64 * capacities, UInt32 capacitiesMaxCount) const;

The default implementation of this method returns a value of block size * max block, and a capacities count of 1. See IOHDDriveNub for details.


doLockUnlockMedia

Abstract: Lock or unlock the (removable) media in the drive.
public:

virtual IOReturn doLockUnlockMedia(bool doLock);

This method issues a standard SCSI Prevent/Allow command to lock or unlock the media in the drive. See IOHDDriveNub for details.


doStart

Abstract: Start (spin up) the media.
protected:

virtual IOReturn doStart(void);

This method calls doStartStop.


doStartStop

Abstract: Perform the actual spin up/down command.
protected:

virtual IOReturn doStartStop(bool start,bool loadEject,UInt8 powerCondition);

This method issues a SCSI Start Stop Unit command to start or stop the device. Because the powerCondition value is only for use with SCSI-3 devices, the current implementation ignores powerCondition.

Parameters

NameDescription
startTrue to start (spin-up) the media; False to stop (spin-down) the media.
loadEjectTrue to eject; False to not eject. This parameter is applicable only to a stop operation.
powerConditionThe power condition to which the drive should transition. This is a SCSI-3 capability; it is presently unused.

doStop

Abstract: Stop (spin down) the media.
protected:

virtual IOReturn doStop(void);

This method calls doStartStop.


doSyncReadWrite

Abstract: Perform a synchronous read or write operation.
public:

virtual IOReturn doSyncReadWrite(IOMemoryDescriptor *buffer,UInt32 block,UInt32 nblks);

See IOHDDriveNub for details.


doSynchronizeCache

Abstract: Force data blocks in the drive's buffer to be flushed to the media.
public:

virtual IOReturn doSynchronizeCache(void);

This method issues a SCSI Synchronize Cache command, to ensure that all blocks in the device cache are written to the media. See IOHDDriveNub for details.


getDeviceTypeName

Abstract: Return a character string for the device type.
protected:

virtual const char * getDeviceTypeName(void);

The default implementation of this method returns kDeviceTypeHardDisk.


getEjectPowerState

Abstract: Return the required device power level to determine eject the media.
protected:

virtual UInt32 getEjectPowerState(void); /* default = kElectronicsOn */

The default implementation of this method returns kElectronicsOn.

Result: The return value must be a valid power state value.

getExecuteCDBPowerState

protected:

virtual UInt32 getExecuteCDBPowerState(void); /* default = kAllOn */

Result: The return value must be a valid power state value.

getFormatMediaPowerState

Abstract: Return the required device power level to execute a client CDB.
protected:

virtual UInt32 getFormatMediaPowerState(void); /* default = kAllOn */

The default implementation of this method returns kAllOn.

Result: The return value must be a valid power state value.

getInitialPowerState

Abstract: Report the initial power state of the device.
protected:

virtual unsigned long getInitialPowerState(void); /* default = kAllOn */

The default implementation of this method returns kAllOn, assuming that the drive spindle spins up initially.

Result: The return value must be a valid power state value.

getInquiryPowerState

Abstract: Return the required device power level to execute an Inquiry command.
protected:

virtual UInt32 getInquiryPowerState(void); /* default = kElectronicsOn */

The default implementation of this method returns kElectronicsOn.

Result: The return value must be a valid power state value.

getLockUnlockMediaPowerState

Abstract: Return the required device power level to lock or unlock the media.
protected:

virtual UInt32 getLockUnlockMediaPowerState(void); /* default = kElectronicsOn */

The default implementation of this method returns kElectronicsOn.

Result: The return value must be a valid power state value.

getReadCapacityPowerState

Abstract: Return the required device power level to execute a Read-Capacity command.
protected:

virtual UInt32 getReadCapacityPowerState(void); /* default = kElectronicsOn */

The default implementation of this method returns kElectronicsOn.

Result: The return value must be a valid power state value.

getReadWritePowerState

Abstract: Return the required device power level to execute a Read or Write command.
protected:

virtual UInt32 getReadWritePowerState(void); /* default = kAllOn */

The default implementation of this method returns kAllOn.

Result: The return value must be a valid power state value.

getReportWriteProtectionPowerState

Abstract: Return the required device power level to report media write protection.
protected:

virtual UInt32 getReportWriteProtectionPowerState(void); /* default = kElectronicsOn */

The default implementation of this method returns kElectronicsOn.

Result: The return value must be a valid power state value.

getStartPowerState

Abstract: Return the required device power level to start (spin up) the media.
protected:

virtual UInt32 getStartPowerState(void); /* default = kElectronicsOn */

The default implementation of this method returns kElectronicsOn.

Result: The return value must be a valid power state value.

getStopPowerState

Abstract: Return the required device power level to stop (spin down) the media.
protected:

virtual UInt32 getStopPowerState(void); /* default = kAllOn */

The default implementation of this method returns kAllOn.

Result: The return value must be a valid power state value.

getSynchronizeCachePowerState

Abstract: Return the required device power level to issue a Synchronize-Cache command.
protected:

virtual UInt32 getSynchronizeCachePowerState(void); /* default = kAllOn */

The default implementation of this method returns kAllOn.

Result: The return value must be a valid power state value.

getTestUnitReadyPowerState

Abstract: Return the required device power level to issue a Test Unit Ready command.
protected:

virtual UInt32 getTestUnitReadyPowerState(void); /* default = kElectronicsOn */

The default implementation of this method returns kElectronicsOn.

Result: The return value must be a valid power state value.

initialPowerStateForDomainState

Abstract: Return the initial power state for the device.
protected:

virtual unsigned long initialPowerStateForDomainState( IOPMPowerFlags domainState );

This method is called to obtain the initial power state for the device, by calling getInitialPowerState.

Parameters

NameDescription
domainStatePower domain state flags.
Result: The return value must be a valid power state value.

instantiateNub

Abstract: Create the device nub.
protected:

virtual IOService * instantiateNub(void);

A subclass will override this method to change the type of nub created. A CD driver, for example, will instantiate an IOSCSICDDriveNub instead of the default implementation's IOSCSIHDDriveNub.


maxCapabilityForDomainState

Abstract: Return the maximum power level obtainable for the given state.
protected:

virtual unsigned long maxCapabilityForDomainState( IOPMPowerFlags domainState );

This method is called to obtain the maximum power level obtainable for the given state.

Parameters

NameDescription
domainStatePower domain state flags.
Result: The return value must be a valid power state value.

powerStateDidChangeTo

Abstract: React to a change in power state.
protected:

virtual IOReturn powerStateDidChangeTo( unsigned long, unsigned long stateOrdinal, IOService* );

This method is called when the power state changes. We call restoreElectronicsState if necessary, then call dequeueCommands if we have changed to a state that has power.

Parameters

NameDescription
stateOrdinalThe power level to which we have changed.

powerStateForDomainState

protected:

virtual unsigned long powerStateForDomainState( IOPMPowerFlags domainState );

This method is called to obtain the maximum power level obtainable for the given state.

Parameters

NameDescription
domainStatePower domain state flags.
Result: The return value must be a valid power state value.

powerStateWillChangeTo

Abstract: Prepare for a power state change.
protected:

virtual IOReturn powerStateWillChangeTo( unsigned long, unsigned long stateOrdinal, IOService* );

This method is called when the power state will change. If we are powering-up from kAllOff, we schedule a call to restoreElectronicsState. If, instead, we are powering-down from an "on" state, we schedule a call to saveElectronicsState.

Parameters

NameDescription
stateOrdinalThe power level to which we will change.

powerTickle

protected:

virtual bool powerTickle(UInt32 desiredState);

This method simply "tickles" the Power Management subsystem to ensure that the device transitions to the desired state if necessary.


reportMediaState

Abstract: Report the device's media state.
public:

virtual IOReturn reportMediaState(bool *mediaPresent,bool *changed);

This method reports whether media is present or not, and also whether the media state has changed since the last call to reportMediaState. The default implementation issues a SCSI Test Unit Ready command: depending on the result of that command, the following cases are reported:

1. TUR status == good completion: we report media present and return kIOReturnSuccess.

2. TUR status != good completion, but good autosense returned:

2a: sense key says not ready: we report media not present and return kIOReturnSuccess.

2b: sense key is anything else: we report media not present and return kIOReturnIOError.

3. TUR status != good completion, and no autosense data: we do not set mediaPresent or changedState, and we return whatever result came back from the SCSI operation.


restoreElectronicsState

Abstract: Restore the state of the device electronics when powering-up.
protected:

virtual IOReturn restoreElectronicsState(void);

This method is called just after the device transitions from a powered-off state.

The default implementation of this method does nothing and returns kIOReturnSuccess.


saveElectronicsState

Abstract: Save the state of the device electronics when powering-down.
protected:

virtual IOReturn saveElectronicsState(void);

This method is called just before the device transitions to a powered-off state.

The default implementation of this method does nothing and returns kIOReturnSuccess.


setPowerState

Abstract: Set the power state to the specified state.
protected:

virtual IOReturn setPowerState( unsigned long powerStateOrdinal, IOService* );

This method is called to cause a change in power state. We handle changes to and from kAllOn and kElectronicsOn, which are done by spinning up and down the media.

Parameters

NameDescription
powerStateOrdinalThe power level to which we must change.

start

Abstract: Start the driver.
public:

virtual bool start(IOService * provider);

We override IOBasicSCSI::start so we can initialize Power Management, then we call createNub to create an IOSCSIHDDriveNub.


Member Data

_mediaPresent

protected:
 bool _mediaPresent;

True if media is present; False if media is not present.


_restoreState

protected:
 bool _restoreState; /* true if we must restore after power-up */ };

True if we must restore the device electronics state after a power-up.


_startStopDisabled

protected:
 bool _startStopDisabled;

True if the start/stop commands are disabled due to an error.


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOService.h

IOService.h



Typedefs

IOServiceNotificationHandler

typedef bool (*IOServiceNotificationHandler)( OSObject * self, void * ref,
                    IOService * newService );

Parameters

NameDescription
selfOSObject reference supplied when the notification was registered.
refReference constant supplied when the notification was registered.
newServiceThe IOService object the notification is delivering. It is retained for the duration of the handler's invocation and doesn't need to be released by the handler.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOService

IOService



Member Functions

PMinit

public:

void PMinit(void );

A power managment policy-maker for a device calls itself here to initialize its power management. PMinit allocates and initializes the power management instance variables, and it should be called before any access to those variables or the power management methods.


PMstop

public:

void PMstop( void );

A power managment policy-maker for a device calls itself here when it resigns its responsibilities as policy-maker. This typically happens when it is handing off the responsibility to another policy-maker, or when the device is removed from the system. The power managment variables don't exist after this call, and the power managment methods in the caller shouldn't be accessed.


acknowledgePowerChange

public:

IOReturn acknowledgePowerChange( IOService * whichDriver );

When a device is changing power state, its policy-maker informs interested parties before and after the change. Interested parties are those which have registered as interested drivers and also children of the policy-maker in the case that it is a power domain. When an object is so informed, it can return an indication that it is prepared for the change, or it can return an indication that it needs some time to prepare. In this case it will call this method in the policy-maker when it has prepared.

Parameters

NameDescription
theDriverThis points to the calling driver. The policy-maker uses it to know if all interested parties have acknowledged the power state change.
Result: IOPMNoErr is returned.

acknowledgeSetPowerState

public:

IOReturn acknowledgeSetPowerState( void );

When a policy-maker instructs its controlling driver to switch the state of the device, the driver can return an indication that the change is complete, or it can return an indication that it needs some time to make the change. In this case it will call this method in the policy-maker when it has made the power state change.

Result: IOPMNoErr is returned.

activityTickle

public:

virtual bool activityTickle( unsigned long type, unsigned long stateNumber=0 );

A principal function of a policy-maker is deciding when the device is idle and can be powered down. To do this it needs to know when the device is being used. In some cases it is in the data path to the device so it knows when it is being used. In others it is not and must be told. The activityTickle method is provided for objects in the system to tell a policy-maker that its device is being used.

If the policy-maker is managing the idleness determination totally on its own, the paramter should be kIOPMSubclassPolicy, and the policy-maker should intercept the activityTickle call, because the superclass will do nothing with it.

The IOService superclass can manage idleness determination, too, with the simple mechanism of an idle timer and this activityTickle call. To start this up, the policy- maker calls its superclass at setIdleTimerPeriod. This starts a timer for the time interval specified in the call. When the timer expires, the superclass checks to see if there has been any activity since the last timer expiration. (It checks to see if activityTickle has been called). If there has been activity, it restarts the timer, and this process continues. When the timer expires, and there has been no device activity, the superclass lowers the device power state to the next lower state. This can continue until the device is in state zero.

After the device has been powered down by at least one power state, a call to activityTickle will cause the device to be switched to a higher state required for the activity.

activityTickle in the IOService superclass is meant to be called by sub-classed policy-makers, because only they understand the paramters. They may implement an activityTickle for their clients and then call this activityTickle in the superclass.

Parameters

NameDescription
typeactivityTickle with parameter kIOPMSubclassPolicy is not handled in IOService and should be intercepted by the subclass policy-maker. activityTickle with parameter kIOPMSuperclassPolicy1 causes an activity flag to be set, and the device state checked. If the device has been powered down, it is powered up again.
stateNumberWhen the type parameter is kIOPMSuperclassPolicy1, the stateNumber contains the desired power state ordinal for the activity. If the device is in a lower state, the superclass will switch it to this state. This is for devices which can handle some accesses in lower power states than others; the device is powered up only as far as it needs to be for the activity.
Result: When the type parameter is kIOPMSuperclassPolicy1, the superclass returns true if the device is currently in the state specified by stateNumber. If it is in a lower state and must be brought up, it returns false. In this case the superclass will cause the device to be brought up.

addChild

public:

virtual IOReturn addChild( IOService * theChild );

The Platform Expert or some other IOService calls a power domain policy-maker here to introduce it to a child of it, a member of the domain.

Parameters

NameDescription
theChildThis is a pointer to the child IOService, which is another power domain policy-maker or a device policy-maker.

addLocation

Abstract: Add a location matching property to an existing dictionary.
public:

static OSDictionary * addLocation( OSDictionary * table );

This function creates matching properties that specify the location of a IOService, as an embedded matching dictionary. This matching will be successful on an IOService which attached to an IOService which matches this location matching dictionary.

Parameters

NameDescription
tableThe matching properties are added to the specified dictionary, which must be non-zero.
Result: The location matching dictionary created is returned on success, or zero on failure.

addNotification

Abstract: Add a persistant notification handler to be notified of IOService events.
public:

static IONotifier * addNotification( const OSSymbol * type, OSDictionary * matching, IOServiceNotificationHandler handler, OSObject * self, void * ref = 0, SInt32 priority = 0 );

IOService will deliver notifications of changes in state of an IOService to registered clients. The type of notification is specified by a symbol, for example gIOMatchedNotification or gIOTerminatedNotification, and notifications will only include IOService's that match the supplied matching dictionary. Notifications are ordered by a priority set with addNotification. When the notification is installed, its handler will be called with each of any currently existing IOService's that are in the correct state (eg. registered) and match the supplied matching dictionary, avoiding races between finding preexisting and new IOService events. The notification request is identified by an instance of an IONotifier object, through which it can be enabled, disabled or removed. addNotification will consume a retain count on the matching dictionary when the notification is removed.

Parameters

NameDescription
typeAn OSSymbol identifying the type of notification and IOService state:
gIOPublishNotification Delivered when an IOService is registered.
gIOFirstPublishNotification Delivered when an IOService is registered, but only once per IOService instance. Some IOService's may be reregistered when their state is changed.
gIOMatchedNotification Delivered when an IOService has been matched with all client drivers, and they have been probed and started.
gIOFirstMatchNotification Delivered when an IOService has been matched with all client drivers, but only once per IOService instance. Some IOService's may be reregistered when their state is changed.
gIOTerminatedNotification Delivered after an IOService has been terminated, during its finalize stage.
matchingA matching dictionary to restrict notifications to only matching IOServices. The dictionary will be released when the notification is removed - consuming the passed in reference.
handlerA C-function callback to deliver notifications.
selfAn instance reference for the callbacks use.
refA reference constant for the callbacks use
priorityA constant ordering all notifications of a each type.
Result: Returns an instance of an IONotifier object that can be used to control or destroy the notification request.

adjustBusy

Abstract: Adjusts the busyState of an IOService.
public:

virtual void adjustBusy( SInt32 delta );

Applies a delta to an IOService's busyState. A change in the busyState to or from zero will changes the IOService's provider's busyState by one (in the same direction).

Parameters

NameDescription
deltaThe delta to be applied to the IOService busy state.

attach

Abstract: Attaches an IOService client to a provider in the registry.
public:

virtual bool attach( IOService * provider );

This function called in an IOService client enters the client into the registry as a child of the provider in the service plane. The provider must be active or the attach will fail. Multiple attach calls to the same provider are no-ops and return success. A client may be attached to multiple providers. Entering an object into the registry will retain both the client and provider until they are detached.

Parameters

NameDescription
providerThe IOService object which will serve as this objects provider.
Result: false if the provider is inactive or on a resource failure, otherwise true.

causeInterrupt

Abstract: Cause a device interrupt to occur.
public:

virtual IOReturn causeInterrupt(int source);

Emulate a hardware interrupt, to be called from task level.

Parameters

NameDescription
sourceThe index of the interrupt source in the device.
Result: An IOReturn code.
kIOReturnNoInterrupt is returned if the source is not valid.

changeStateTo

public:

IOReturn changeStateTo( unsigned long ordinal );

The power-controlling driver calls the policy-maker here when it wants the device switched to a different power state. This is mildly ironic in that it is the controlling driver which does the switching, but it must do it this way so that the policy-maker can make sure the power domain is correct and to notify interested parties pre-change. When appropriate, the policy-maker will call the controlling driver and have it switch the device to the requested state in the usual way. This request by the controlling driver is sticky in that the policy-maker will not switch the device lower than this request, so if the driver needs power raised for some reason and then gets it and does what it needs, it should then rescind the request by requesting state zero. This will allow the policy-maker to control the device as usual.

Parameters

NameDescription
ordinalThis is the number, in the power state array, of the desired power state.
Result: The return code reflects the state of the policy-maker's internal queue of power changes and can be ignored by the caller.

changeStateToPriv

    protected:

IOReturn changeStateToPriv( unsigned long ordinal );

A policy-maker calls its superclass here to change the power state of the device. The superclass takes care of making sure the power domain state is appropriate and informing interested parties. It calls the controlling driver to make the change.

Parameters

NameDescription
ordinalThis is the number, in the power state array, of the desired power state.
Result: The return code reflects the state of the policy-maker's internal queue of power changes and can be ignored by the caller.

close

Abstract: Release active access to a provider.
public:

virtual void close( IOService * forClient, IOOptionBits options = 0 );

IOService provides generic open and close semantics to track clients of a provider that have established an active datapath. The use of open & close, and rules regarding ownership are family defined, and defined by the handleOpen / handleClose methods in the provider.

Parameters

NameDescription
forClientDesignates the client of the provider requesting the close.
optionsOptions available for the close. The provider family may implement options for close; IOService defines none.
argFamily specific arguments, ignored by IOService.

compareProperties

Abstract: Utility to compare a set of properties in a matching dictionary with an IOService's property table.
public:

virtual bool compareProperties( OSDictionary * matching, OSCollection * keys );

This is a helper function to aid in implementing matchPropertyTable. A collection of dictionary keys specifies properties in a matching dictionary to be compared, with compareProperty, with an IOService property table, if compareProperty returns true for each key, success is return else failure.

Parameters

NameDescription
matchingThe matching dictionary, which must be non-zero.
keysA collection (eg. OSSet, OSArray, OSDictionary) which should contain OSStrings (or OSSymbols) that specify the property keys to be compared.
Result: if compareProperty returns true for each key in the collection, success is return else failure.

compareProperty

Abstract: Utility to compare a property in a matching dictionary with an IOService's property table.
public:

virtual bool compareProperty( OSDictionary * matching, const OSString * key );

This is a helper function to aid in implementing matchPropertyTable. If the property specified by key exists in the matching dictionary, it is compared with a property of the same name in the IOService's property table. The comparison is performed with the isEqualTo method. If the property does not exist in the matching table, success is returned. If the property exists in the matching dictionary but not the IOService property table, failure is returned.

Parameters

NameDescription
matchingThe matching dictionary, which must be non-zero.
keyThe dictionary key specifying the property to be compared, as an OSString (which includes OSSymbol).
Result: If the property does not exist in the matching table, true is returned. If the property exists in the matching dictionary but not the IOService property table, failure is returned. Otherwise the result of calling the property from the matching dictionary's isEqualTo method with the IOService property as an argument is returned.

compareProperty

Abstract: Utility to compare a property in a matching dictionary with an IOService's property table.
public:

virtual bool compareProperty( OSDictionary * matching, const char * key );

This is a helper function to aid in implementing matchPropertyTable. If the property specified by key exists in the matching dictionary, it is compared with a property of the same name in the IOService's property table. The comparison is performed with the isEqualTo method. If the property does not exist in the matching table, success is returned. If the property exists in the matching dictionary but not the IOService property table, failure is returned.

Parameters

NameDescription
matchingThe matching dictionary, which must be non-zero.
keyThe dictionary key specifying the property to be compared, as a C-string.
Result: If the property does not exist in the matching table, true is returned. If the property exists in the matching dictionary but not the IOService property table, failure is returned. Otherwise the result of calling the property from the matching dictionary's isEqualTo method with the IOService property as an argument is returned.

currentCapability

public:

virtual IOPMPowerFlags currentCapability( void );

Some object calls a policy-maker here to find out the current capability of a device. The policy-maker returns a copy of the capabilityFlags field for the current power state in the power state array.


currentPowerConsumption

public:

virtual unsigned long currentPowerConsumption( void );

Some object calls a policy-maker here to find out the current power consumption of a device. The policy-maker returns a copy of the staticPower field for the current power state in the power state array.


deRegisterInterestedDriver

public:

IOReturn deRegisterInterestedDriver( IOService * theDriver );

An IOService which has previously registered with a policy-maker as an interested driver calls the policy-maker here to withdraw its interest. The policy-maker removes it from its list of interested drivers.

Result: These bits describe the capability of the device in its current power state. They are not understood by the policy-maker; they come from the capabilityFlags field of the current power state in the power state array.

detach

Abstract: Detaches an IOService client from a provider in the registry.
public:

virtual void detach( IOService * provider );

This function called in an IOService client removes the client as a child of the provider in the service plane of the registry. If the provider is not a parent of the client this is a no-op, otherwise the registry will release both the client and provider.

Parameters

NameDescription
providerThe IOService object to detach from.

disableInterrupt

Abstract: Disable a device interrupt.
public:

virtual IOReturn disableInterrupt(int source);

Disable a device interrupt. It is the callers responsiblity to keep track of the enable state of the interrupt source.

Parameters

NameDescription
sourceThe index of the interrupt source in the device.
Result: An IOReturn code.
kIOReturnNoInterrupt is returned if the source is not valid.

enableInterrupt

Abstract: Enable a device interrupt.
public:

virtual IOReturn enableInterrupt(int source);

Enable a device interrupt. It is the callers responsiblity to keep track of the enable state of the interrupt source.

Parameters

NameDescription
sourceThe index of the interrupt source in the device.
Result: An IOReturn code.
kIOReturnNoInterrupt is returned if the source is not valid.

errnoFromReturn

Abstract: A utility to translate an IOReturn code to a BSD errno.
public:

virtual int errnoFromReturn( IOReturn rtn );

BSD defines its own return codes for its functions in sys/errno.h, and IOKit families may need to supply compliant results in BSD shims. Results are available for the standard return codes in IOReturn.h in IOService, while subclasses may implement this method to interpret family dependent return codes.

Parameters

NameDescription
rtnThe IOReturn code.
Result: The BSD errno or EIO if unknown.

finalize

Abstract: The last stage in an IOService destruction.
public:

virtual bool finalize( IOOptionBits options );

The finalize method is called in an inactive (ie. terminated) IOService after the last client has detached. IOService's implementation will call stop, close, and detach on each provider. When finalize returns, the object's retain count will have no references generated by IOService's registration process.

Parameters

NameDescription
optionsThe options passed to the terminate method of the IOService are passed on to finalize.
Result: Returns true.

getBusyState

Abstract: Returns the busyState of an IOService.
public:

virtual UInt32 getBusyState( void );

Many activities in IOService are asynchronous. When registration, matching, or termination is in progress on an IOService, its busyState is increased by one. Change in busyState to or from zero also changes the IOService's provider's busyState by one, which means that an IOService is marked busy when any of the above activities is ocurring on it or any of its clients.

Result: The busyState.

getClient

Abstract: Returns an IOService's primary client.
public:

virtual IOService * getClient( void ) const;

This function called in an IOService provider will return the first client to attach to it. For IOService objects which have only only one client, this may be a useful simplification.

Result: Returns the first client of the provider, or zero if the IOService is not attached into the registry. The client is retained while it is attached, and should not be released by the caller.

getClientIterator

Abstract: Returns an iterator over an IOService's clients.
public:

virtual OSIterator * getClientIterator( void ) const;

For IOService objects that may have multiple clients, this method supplies an iterator over a provider's clients.

Result: Returns an iterator over the clients of the provider, or zero if there is a resource failure. The iterator must be released when the iteration is finished. All objects returned by the iteration are retained while the iterator is valid, though they may no longer be attached during the iteration.

getDeviceMemory

Abstract: Returns the array of IODeviceMemory objects representing a device's memory mapped ranges.
public:

virtual OSArray * getDeviceMemory( void );

This method will return an array of IODeviceMemory objects representing the physical memory ranges allocated to a memory mapped device.

Result: An OSArray of IODeviceMemory objects, or zero if none are available. The array is retained by the provider, so is valid while attached.

getDeviceMemoryCount

Abstract: Returns a count of the physical memory ranges available for a device.
public:

virtual IOItemCount getDeviceMemoryCount( void );

This method will return the count of physical memory ranges, each represented by an IODeviceMemory instance, that have been allocated for a memory mapped device.

Result: An integer count of the number of ranges available.

getDeviceMemoryWithIndex

Abstract: Returns an instance of IODeviceMemory representing one of a device's memory mapped ranges.
public:

virtual IODeviceMemory * getDeviceMemoryWithIndex( unsigned int index );

This method will return a pointer to an instance of IODeviceMemory for the physical memory range at the given index for a memory mapped device.

Parameters

NameDescription
indexAn index into the array of ranges assigned to the device.
Result: A pointer to an instance of IODeviceMemory, or zero if the index is beyond the count available. The IODeviceMemory is retained by the provider, so is valid while attached, or while any mappings to it exist. It should not be released by the caller. See also mapDeviceMemory() which will create a device memory mapping.

getInterruptType

Abstract: Return the type of interrupt used for a device supplying hardware interrupts.
public:

virtual IOReturn getInterruptType(int source, int *interruptType);

This method will return the type of interrupt used by the device.

Parameters

NameDescription
sourceThe index of the interrupt source in the device.
interruptTypeThe interrupt type for the interrupt source will be stored here by getInterruptType.
kIOInterruptTypeEdge will be returned for edge trigggered sources.
kIOInterruptTypeLevel will be returned for level trigggered sources.
Result: An IOReturn code.
kIOReturnNoInterrupt is returned if the source is not valid.

getMatchingServices

Abstract: Finds the set of current published IOServices matching a matching dictionary.
public:

static OSIterator * getMatchingServices( OSDictionary * matching );

Provides a method of finding the current set of published IOServices matching the supplied matching dictionary.

Parameters

NameDescription
matchingThe matching dictionary describing the desired IOServices.
Result: An instance of an iterator over a set of IOServices. To be released by the caller.

getOpenClientIterator

Abstract: Returns an iterator over an provider's clients that currently have opened the provider.
public:

virtual OSIterator * getOpenClientIterator( void ) const;

For IOService objects that may have multiple clients, this method supplies an iterator over a provider's clients, locking each in turn with lockForArbitration and returning those that have opened the provider.

Result: Returns an iterator over the clients which the provider open, or zero if there is a resource failure. The iterator must be released when the iteration is finished. All objects returned by the iteration are retained while the iterator is valid, and the current entry in the iteration is locked with lockForArbitration, protecting it from state changes.

getOpenProviderIterator

Abstract: Returns an iterator over an client's providers that are currently opened by the client.
public:

virtual OSIterator * getOpenProviderIterator( void ) const;

For those few IOService objects that obtain service from multiple providers, this method supplies an iterator over a client's providers, locking each in turn with lockForArbitration and returning those that have been opened by the client.

Result: Returns an iterator over the providers the client has open, or zero if there is a resource failure. The iterator must be released when the iteration is finished. All objects returned by the iteration are retained while the iterator is valid, and the current entry in the iteration is locked with lockForArbitration, protecting it from state changes.

getPMworkloop

public:

virtual IOWorkLoop *getPMworkloop( void );


getPlatform

Abstract: Returns a pointer to the platform expert instance for the machine.
public:

static IOPlatformExpert * getPlatform( void );

This method provides an accessor to the platform expert instance for the machine.

Result: A pointer to the IOPlatformExport instance. It should not be released by the caller.

getProvider

Abstract: Returns an IOService's primary provider.
public:

virtual IOService * getProvider( void ) const;

This function called in an IOService client will return the provider to which it was first attached. Since the majority of IOService objects have only one provider, this is a useful simplification and also supports caching of the provider when the registry is unchanged.

Result: Returns the first provider of the client, or zero if the IOService is not attached into the registry. The provider is retained while the client is attached, and should not be released by the caller.

getProviderIterator

Abstract: Returns an iterator over an IOService's providers.
public:

virtual OSIterator * getProviderIterator( void ) const;

For those few IOService objects that obtain service from multiple providers, this method supplies an iterator over a client's providers.

Result: Returns an iterator over the providers of the client, or zero if there is a resource failure. The iterator must be released when the iteration is finished. All objects returned by the iteration are retained while the iterator is valid, though they may no longer be attached during the iteration.

getResources

Abstract: Allocate any needed resources for a published IOService before clients attach.
public:

virtual IOReturn getResources( void );

This method is called during the registration process for an IOService object if there are success driver matches, before any clients attach. It allows for lazy allocation of resources to an IOService when a matching driver is found.

Result: Return an IOReturn code, kIOReturnSuccess is necessary for the IOService to be successfully used, otherwise the registration process for the object is halted.

getServiceRoot

Abstract: Returns a pointer to the root of the service plane.
public:

static IOService * getServiceRoot( void );

This method provides an accessor to the root of the service plane for the machine.

Result: A pointer to the IOService instance at the root of the service plane. It should not be released by the caller.

getState

Abstract: Accessor for IOService state bits, not normally needed or used outside IOService.
public:

virtual IOOptionBits getState( void ) const;

Result: State bits for the IOService, eg. kIOServiceInactiveState, kIOServiceRegisteredState.

getWorkLoop

Abstract: Returns the current work loop or provider->getWorkLoop().
public:

virtual IOWorkLoop * getWorkLoop() const;

This function returns a valid work loop that a client can use to add an IOCommandGate to. The intention is that an IOService client has data that needs to be protected but doesn't want to pay the cost of an entire dedicated thread. This data has to be accessed from a providers call out context as well. So to achieve both of these goals the client creates an IOCommandGate to lock access to his data but he registers it with the providers work loop, i.e. the work loop which will make the completion call outs. In one fell swoop we avoid a potentially nasty deadlock 'cause a work loop's gate is recursive.

Result: Always returns a work loop, either the current work loop or it walks up the $link getProvider() chain calling getWorkLoop. Eventually it will reach a valid work loop based driver or the root of the io tree where it will return a system wide work loop. Returns 0 if it fails to find (or create)

handleClose

Abstract: Overrideable method to control the open / close behaviour of an IOService.
public:

virtual void handleClose( IOService * forClient, IOOptionBits options );

IOService calls this method in its subclasses in response to the close method, so the subclass may implement the request. The default implementation provides single owner access to an IOService via open. The object is locked via lockForArbitration before handleClose is called.

Parameters

NameDescription
forClientDesignates the client of the provider requesting the close.
optionsOptions for the close, may be interpreted by the implementor of handleOpen.

handleIsOpen

Abstract: Overrideable method to control the open / close behaviour of an IOService.
public:

virtual bool handleIsOpen( const IOService * forClient ) const;

IOService calls this method in its subclasses in response to the open method, so the subclass may implement the request. The default implementation provides single owner access to an IOService via open. The object is locked via lockForArbitration before handleIsOpen is called.

Parameters

NameDescription
forClientIf non-zero, isOpen returns the open state for that client. If zero is passed, isOpen returns the open state for all clients.
Result: Returns true if the specific, or any, client has the IOService open.

handleOpen

Abstract: Overrideable method to control the open / close behaviour of an IOService.
public:

virtual bool handleOpen( IOService * forClient, IOOptionBits options, void * arg );

IOService calls this method in its subclasses in response to the open method, so the subclass may implement the request. The default implementation provides single owner access to an IOService via open. The object is locked via lockForArbitration before handleOpen is called.

Parameters

NameDescription
forClientDesignates the client of the provider requesting the open.
optionsOptions for the open, may be interpreted by the implementor of handleOpen.
Result: Return true if the open was successful, false otherwise.

initialPowerStateForDomainState

public:

virtual unsigned long initialPowerStateForDomainState( IOPMPowerFlags );

A policy-maker (usually its superclass) calls its controlling driver here to find out which power state the device is in, given the current power domain state. This happens once, when the policy-maker is initializing, and the controlling driver can use this to know what state the device is in initially.

Parameters

NameDescription
domainStateThese flags describe the character of domain power in the current state of the power domain. The flags are not understood by the calling policy-maker; they were passed to it by its power domain parent. They come from the outputPowerCharacter field of the current power state in the power domain's power state array.

This method is implemented in a simple way in IOService. It scans the power state array looking for the highest state whose inputPowerRequirement field exactly matches the parameter. If more intelligent determination is required, the power-controlling driver should implement the method and override the superclass.
Result: A state number is returned.

installNotification

Abstract: Add a persistant notification handler to be notified of IOService events.
public:

static IONotifier * installNotification( const OSSymbol * type, OSDictionary * matching, IOServiceNotificationHandler handler, OSObject * self, void * ref, SInt32 priority, OSIterator ** existing );

A lower level interface to addNotification that will install a handler and return the current set of IOServices that are in the specified state and match the matching dictionary.

Parameters

NameDescription
typeSee addNotification.
matchingSee addNotification.
handlerSee addNotification.
selfSee addNotification.
refSee addNotification.
prioritySee addNotification.
existingReturns an iterator over the set of IOServices that are currently in the specified state and match the matching dictionary.
Result: See addNotification.

instanceMatching

Abstract: Create a matching dictionary, or add matching properties to an existing dictionary, that specify a service instance match.
public:

static OSDictionary * instanceMatching( IOService * instance, OSDictionary * table = 0 );

This function creates matching properties that will match only the specified IOService instance.

Parameters

NameDescription
instanceThe IOService instance for which matching will be successful.
tableIf zero, instanceMatching will create a matching dictionary and return a reference to it, otherwise the matching properties are added to the specified dictionary.
Result: The matching dictionary created, or passed in, is returned on success, or zero on failure.

isInactive

Abstract: Check the IOService has been terminated, and is in the process of being destroyed.
public:

inline bool isInactive( void ) const { return( 0 != (kIOServiceInactiveState & getState())); }

When an IOService is successfully terminated, it is immediately made inactive, which blocks further attach()es, matching or notifications occuring on the object. It remains inactive until the last client closes, and is then finalized and destroyed.

Result: Returns true if the IOService has been terminated.

isOpen

Abstract: Determine whether a specific, or any, client has an IOService open.
public:

virtual bool isOpen( const IOService * forClient = 0 ) const;

Returns the open state of an IOService with respect to the specified client, or when it is open by any client.

Parameters

NameDescription
forClientIf non-zero, isOpen returns the open state for that client. If zero is passed, isOpen returns the open state for all clients.
Result: Returns true if the specific, or any, client has the IOService open.

joinPMtree

public:

virtual void joinPMtree( IOService * driver );

A policy-maker calls its nub here when initializing, to be attached into the power management hierarchy. The default function is to call the platform expert, which knows how to do it. This method is overridden by a nub subclass which may either know how to do it, or may need to take other action.

This may be the only "power management" method used in a nub, meaning it may be called even if the nub is not initialized for power management.

Before the nub returns from this method, the caller will probably be called at "setParent" and "setAggressiveness" and possibly at "addChild" as it is added to me hierarchy.


lockForArbitration

Abstract: Locks an IOService against changes in state or ownership.
public:

virtual bool lockForArbitration( bool isSuccessRequired = true );

The registration, termination and open / close functions of IOService use lockForArbtration to single thread access to an IOService. lockForArbitration will grant recursive access to the same thread.

Parameters

NameDescription
isSuccessRequiredIf a request for access to an IOService should be denied if it is terminated, isSuccessRequired should passed as false, otherwise pass true.

makeUsable

public:

IOReturn makeUsable( void );

Some client of a device is asking that it become usable. Although this has not come from the policy-maker for the device, treat it exactly as if it had. In this way, subsequent requests for lower power from the policy-maker will pre-empt this request. We treat this as policy-maker request to switch to the highest power state.

Result: The return code reflects the state of the policy-maker's internal queue of power changes and can be ignored by the caller.

mapDeviceMemoryWithIndex

Abstract: Maps a physical range of a device.
public:

virtual IOMemoryMap * mapDeviceMemoryWithIndex( unsigned int index, IOOptionBits options = 0 );

This method will create a mapping for the IODeviceMemory at the given index, with IODeviceMemory::map(options). The mapping is represented by the returned instance of IOMemoryMap, which should not be released until the mapping is no longer required.

Parameters

NameDescription
indexAn index into the array of ranges assigned to the device.
Result: An instance of IOMemoryMap, or zero if the index is beyond the count available. The mapping should be released only when access to it is no longer required.

matchLocation

Abstract: Allows a registered IOService to direct location matching.
public:

virtual IOService * matchLocation( IOService * client );

By default, a location matching property will be applied to an IOService's provider. This method allows that behaviour to be overridden by families.

Parameters

NameDescription
clientThe IOService at which matching is taking place.
Result: Returns the IOService instance to be used for location matching.

matchPropertyTable

Abstract: Allows a registered IOService to implement family specific matching.
public:

virtual bool matchPropertyTable( OSDictionary * table );

All matching on an IOService will call this method to allow a family writer to implement matching in addition to the generic methods provided by IOService. The implementor should examine the matching dictionary passed to see if it contains properties the family understands for matching, and use them to match with the IOService if so. Note that since matching is also carried out by other parts of IOKit, the matching dictionary may contain properties the family does not understand - these should not be considered matching failures.

Parameters

NameDescription
tableThe dictionary of properties to be matched against.
Result: Returns false if the family considers the matching dictionary does not match in properties it understands, true otherwise.

maxCapabilityForDomainState

public:

virtual unsigned long maxCapabilityForDomainState( IOPMPowerFlags domainState );

A policy-maker (usually its superclass) calls its controlling driver here to find out the highest power state possible for a given power domain state. This happens when the power domain is changing state and the policy-maker wants to find out what states the device is capable of in the new domain state.

Parameters

NameDescription
domainStateThese flags describe the character of domain power in some domain power state. The flags are not understood by the calling policy-maker; they were passed to it by its power domain parent. They come from the outputPowerCharacter field of a state in the power domain's power state array.

This method is implemented in a simple way in IOService. It scans the power state array looking for the highest state whose inputPowerRequirement field exactly matches the parameter. If more intelligent determination is required, the power-controlling driver should implement the method and override the superclass.
Result: A state number is returned.

message

Abstract: Receive a generic message delivered from an attached provider.
public:

virtual IOReturn message( UInt32 type, IOService * provider, void * argument = 0 );

A provider may deliver messages via the message method to its clients informing them of state changes, for example kIOMessageServiceIsTerminated or kIOMessageServiceIsSuspended. Certain messages are defined by IOKit in IOMessage.h while others may family dependent. This method is implemented in the client to receive messages.

Parameters

NameDescription
typeA type defined in IOMessage.h or defined by the provider family.
providerThe provider from which the message originates.
argumentAn argument defined by the provider family, not used by IOService.
Result: An IOReturn code defined by the message type.

messageClient

Abstract: Send a generic message to an attached client.
public:

virtual IOReturn messageClient( UInt32 type, IOService * client, void * argument );

A provider may deliver messages via the message method to its clients informing them of state changes, for example kIOMessageServiceIsTerminated or kIOMessageServiceIsSuspended. Certain messages are defined by IOKit in IOMessage.h while others may family dependent. This method may be called in the provider to send a message to the specified client, which may be useful for overrides.

Parameters

NameDescription
typeA type defined in IOMessage.h or defined by the provider family.
clientA client of the IOService to send the message.
argumentAn argument defined by the provider family, not used by IOService.
Result: The return code from the client message call.

messageClients

Abstract: Send a generic message to all attached clients.
public:

virtual IOReturn messageClients( UInt32 type, void * argument = 0 );

A provider may deliver messages via the message method to its clients informing them of state changes, for example kIOMessageServiceIsTerminated or kIOMessageServiceIsSuspended. Certain messages are defined by IOKit in IOMessage.h while others may family dependent. This method may be called in the provider to send a message to all the attached clients, via the messageClient method.

Parameters

NameDescription
typeA type defined in IOMessage.h or defined by the provider family.
argumentAn argument defined by the provider family, not used by IOService.
Result: Any non-kIOReturnSuccess return codes returned by the clients, or kIOReturnSuccess if all return kIOReturnSuccess.

nameMatching

Abstract: Create a matching dictionary, or add matching properties to an existing dictionary, that specify an IOService name match.
public:

static OSDictionary * nameMatching( const OSString* name, OSDictionary * table = 0 );

A very common matching criteria for IOService is based on its name. nameMatching will create a matching dictionary that specifies any IOService which respond sucessfully to the IORegistryEntry method compareName. An existing dictionary may be passed in, in which case the matching properties will be added to that dictionary rather than creating a new one.

Parameters

NameDescription
nameThe service's name, as an OSString (which includes OSSymbol). Name matching is successful on IOService's which respond sucessfully to the IORegistryEntry method compareName.
tableIf zero, nameMatching will create a matching dictionary and return a reference to it, otherwise the matching properties are added to the specified dictionary.
Result: The matching dictionary created, or passed in, is returned on success, or zero on failure.

nameMatching

Abstract: Create a matching dictionary, or add matching properties to an existing dictionary, that specify an IOService name match.
public:

static OSDictionary * nameMatching( const char * name, OSDictionary * table = 0 );

A very common matching criteria for IOService is based on its name. nameMatching will create a matching dictionary that specifies any IOService which respond sucessfully to the IORegistryEntry method compareName. An existing dictionary may be passed in, in which case the matching properties will be added to that dictionary rather than creating a new one.

Parameters

NameDescription
nameThe service's name, as a const C-string. Name matching is successful on IOService's which respond sucessfully to the IORegistryEntry method compareName.
tableIf zero, nameMatching will create a matching dictionary and return a reference to it, otherwise the matching properties are added to the specified dictionary.
Result: The matching dictionary created, or passed in, is returned on success, or zero on failure.

newTemperature

public:

virtual IOReturn newTemperature( long currentTemp, IOService * whichZone );

A thermal-zone driver calls its policy-maker here to tell it that the temperature in the zone has changed. The thermal-zone policy-maker uses this information to manage its thermal zone.

Parameters

NameDescription
currentTempThis is the new temperature in the thermal zone.
whichZoneThis is a pointer to the controlling driver.

newUserClient

Abstract: A request to create a connection for a non kernel client.
public:

virtual IOReturn newUserClient( task_t owningTask, void * security_id, UInt32 type, IOUserClient ** handler );

A non kernel client may request a connection be opened via the IOServiceOpen() library function, which will call this method in an IOService. The rules & capabilities of user level clients are family dependent, and use the functions of the IOUserClient class for support. IOService's implementation returns kIOReturnUnsupported, so any family supporting user clients must implement this method.

Parameters

NameDescription
owningTaskThe mach task requesting the connection.
security_idA token representing the access level for the task.
typeA constant specifying the type of connection to be created, specified by the caller of IOServiceOpen and interpreted only by the family.
handlerAn instance of an IOUserClient object to represent the connection, which will be released when the connection is closed, or zero if the connection was not opened.
Result: A return code to be passed back to the caller of IOServiceOpen.

open

Abstract: Request active access to a provider.
public:

virtual bool open( IOService * forClient, IOOptionBits options = 0, void * arg = 0 );

IOService provides generic open and close semantics to track clients of a provider that have established an active datapath. The use of open & close, and rules regarding ownership are family defined, and defined by the handleOpen / handleClose methods in the provider. Some families will limit access to a provider based on its open state.

Parameters

NameDescription
forClientDesignates the client of the provider requesting the open.
optionsOptions for the open. The provider family may implement options for open; IOService defines only kIOServiceSeize to request the device be withdrawn from its current owner.
Result: Return true if the open was successful, false otherwise.

overrideOffPriv

    protected:

IOReturn overrideOffPriv( void );

When a policy-maker has enabled the override, it can disable it again by calling this method in its superclass. This will allow the superclass to keep the device at the highest state required by itself, its power-controlling driver, and its children (when the power domain state allows). Turning off the override will initiate a power change if the policy-maker's desired power state is different from the maximum of the controlling driver's desire and the children's desires.

Result: The return code reflects the state of the policy-maker's internal queue of power changes and can be ignored by the caller.

overrideOnPriv

    protected:

IOReturn overrideOnPriv( void );

A policy-maker normally keeps its device at the highest state required by itself, its power-controlling driver, and its children (when the power domain state allows). There may be times, however, when a policy-maker needs the power state lower than its driver or its children desire, and when this is the case, it calls overrideOnPriv in its superclass to enable this override. When the override is on, the superclass keeps the device in the state desired by the policy-maker (requested via changeStateToPriv), regardless of the children's or driver's desire. Turning on the override will initiate a power change if the policy-maker's desired power state is different from the maximum of the controlling driver's desire and the children's desires.

Result: The return code reflects the state of the policy-maker's internal queue of power changes and can be ignored by the caller.

powerDomainDidChangeTo

public:

IOReturn powerDomainDidChangeTo( IOPMPowerFlags newPowerStateFlags );

When a power domain changes state, it notifies its children, which are policy-makers, by calling them at this method. It calls here after the changed power of the power domain has settled at the new level. A called policy-maker can return IOPMAckImplied to indicate that it is prepared for the change, or it can return a non-zero number to indicate that it is not prepared but will prepare and then call the parent at acknowledgePowerChange.

To prepare for a lowered power domain, the policy-maker informs all its interested parties of the new power state of its device. If any do not acknowledge immediately, then the policy-maker also will not.

To prepare for a raised power domain, the policy-maker calls its controlling driver to switch the device to the appropriate power state for the new domain state. When that is accomplished, the policy-maker informs all its interested parties of the new power state. If any interested driver or the controlling driver does not acknowledge immediately, then the policy-maker also will not.

Parameters

NameDescription
newPowerStateFlagsThese flags describe the character of power in the new domain state. They are not understood by the policy-maker. It asks the controlling driver to translate them into a state number within the power state array. (The policy-maker for the domain also doesn't understand the bits; they come from a outputPowerCharacter field of the power state array for the power domain.)

powerDomainWillChangeTo

public:

IOReturn powerDomainWillChangeTo( IOPMPowerFlags newPowerStateFlags );

When a power domain changes state, it notifies its children, which are policy-makers, by calling them at this method. It calls here before it makes the change, and a called policy-maker can return IOPMAckImplied to indicate that it is prepared for the change, or it can return a non-zero number to indicate that it is not prepared but will prepare and then call the parent at acknowledgePowerChange.

To prepare for a lowering of the power domain, the policy-maker informs all its interested parties of any resulting change in its device, and when they have all acknowledged, it calls its controlling driver to switch the device to an appropriate power state for the imminent domain state. If any interested driver or the controlling driver does not acknowledge immediately, then the policy-maker also will not.

To prepare for a raising of the power domain, the policy-maker informs all its interested parties of any resulting change in its device. If any do not acknowledge immediately, then the policy-maker also will not.

Parameters

NameDescription
newPowerStateFlagsThese flags describe the character of power in the imminent domain state. They are not understood by the policy-maker. It asks the controlling driver to translate them into a state number within the power state array. (The policy-maker for the domain also doesn't understand the bits; they come from a outputPowerCharacter field of the power state array for the power domain.)

powerStateDidChangeTo

public:

virtual IOReturn powerStateDidChangeTo( IOPMPowerFlags, unsigned long, IOService* );

A policy-maker informs interested parties that its device has changed to a different power state. Interested parties are those that have registered for this notification via registerInterestedDriver and also the power-controlling driver which is registered as an interested driver automatically when it registers as the controlling driver.

Parameters

NameDescription
capabilitiesThese flags describe the capability of the device in the new power state. They are not understood by the policy-maker; they come from the capabilityFlags field of the new state in the power state array.
stateNumberThis is the number of the state in the state array that the device has switched to.
whatDeviceThis points to the policy-maker, and it is used by a driver which is receiving power state change notifications for multiple devices.
Result: The driver returns IOPMAckImplied if it has prepared for the power change when it returns. If it has started preparing but not finished, it should return a number of microseconds which is an upper limit of the time it will need to finish preparing. Then, when it has completed its preparations, it should call acknowledgePowerChange in the policy-maker.

powerStateForDomainState

public:

virtual unsigned long powerStateForDomainState( IOPMPowerFlags domainState );

A policy-maker (usually its superclass) calls its controlling driver here to find out what power state the device would be in for a given power domain state. This happens when the power domain is changing state and the policy-maker wants to find out the effect of the change.

Parameters

NameDescription
domainStateThese flags describe the character of domain power in some domain power state. The flags are not understood by the calling policy-maker; they were passed to it by its power domain parent. They come from the outputPowerCharacter field of a state in the power domain's power state array.

This method is implemented in a simple way in IOService. It scans the power state array looking for the highest state whose inputPowerRequirement field exactly matches the parameter. If more intelligent determination is required, the power-controlling driver should implement the method and override the superclass.
Result: A state number is returned.

powerStateWillChangeTo

public:

virtual IOReturn powerStateWillChangeTo( IOPMPowerFlags, unsigned long, IOService* );

A policy-maker informs interested parties that its device is about to change to a different power state. Interested parties are those that have registered for this notification via registerInterestedDriver and also the power-controlling driver which is registered as an interested driver automatically when it registers as the controlling driver.

Parameters

NameDescription
capabilitiesThese flags describe the capability of the device in the new power state. They are not understood by the policy-maker; they come from the capabilityFlags field of the new state in the power state array.
stateNumberThis is the number of the state in the state array that the device is switching to.
whatDeviceThis points to the policy-maker, and it is used by a driver which is receiving power state change notifications for multiple devices.
Result: The driver returns IOPMAckImplied if it has prepared for the power change when it returns. If it has started preparing but not finished, it should return a number of microseconds which is an upper limit of the time it will need to finish preparing. Then, when it has completed its preparations, it should call acknowledgePowerChange in the policy-maker.

probe

Abstract: During an IOService instantiation probe a matched service to see if it can be used.
public:

virtual IOService * probe( IOService * provider, SInt32 * score );

The registration process for an IOService (the provider) includes instantiating possible driver clients. The probe method is called in the client instance to check the matched service can be used before the driver is considered to be started. Since matching screens many possible providers, in many cases the probe method can be left unimplemented by IOService subclasses. The client is already attached to the provider when probe is called.

Parameters

NameDescription
providerThe registered IOService which matches a driver personality's matching dictionary.
scorePointer to the current driver's probe score, which is used to order multiple matching drivers in the same match category. It defaults to the value of the Probe Score property in the drivers property table, or kIODefaultProbeScore if none is specified. The probe method may alter the score to affect start order.
Result: Returns an IOService instance or zero when the probe is unsuccessful. In almost all cases the value of this is returned on success. If another IOService object is returned, the probed instance is detached and freed, and the returned instance is used in its stead for start.

publishResource

Abstract: Use the resource service to publish a property.
public:

static void publishResource( const char * key, OSObject * value = 0 );

The resource service uses IOService's matching and notification to allow objects to be published and found by any IOKit client by a global name. publishResource makes an object available to anyone waiting for it or looking for it in the future.

Parameters

NameDescription
keyA C-string key that globally identifies the object.
Theobject to be published.

publishResource

Abstract: Use the resource service to publish a property.
public:

static void publishResource( const OSSymbol * key, OSObject * value = 0 );

The resource service uses IOService's matching and notification to allow objects to be published and found by any IOKit client by a global name. publishResource makes an object available to anyone waiting for it or looking for it in the future.

Parameters

NameDescription
keyAn OSSymbol key that globally identifies the object.
Theobject to be published.

registerControllingDriver

public:

IOReturn registerControllingDriver( IOService* controllingDriver, IOPMPowerState* powerStates, unsigned long numberOfStates );

A driver calls a policy-maker here to volunteer to control power to the device. If the policy-maker accepts the volunteer, it adds the volunteer to its list of interested drivers, and it will call the volunteer at appropriate times to switch the power state of the device.

Parameters

NameDescription
controllingDriverThis points to the calling driver.
powerStatesThis is an array of power states which the driver can deal with. If this array is no less rich than one supplied by an earlier volunteer, then the policy-maker uses the calling driver as its power-controlling driver.
numberOfStatesThe number of power states in the array. Power states are defined in pwr_mgt/IOPMpowerState.h.
Result: IOPMNoErr is returned. There are various error conditions possible which prevent the policy-maker from accepting the new power state array. These conditions are logged in the power managment event log, but not returned to the caller.

registerInterestedDriver

public:

IOPMPowerFlags registerInterestedDriver( IOService* theDriver );

Some IOService calls a policy-maker here to register interest in the changing power state of its device.

Parameters

NameDescription
theDriverThe policy-maker adds this pointer to the calling IOService to its list of interested drivers. It informs drivers on this list pre- and post-power change.
Result: The policy-maker returns flags describing the capability of the device in its current power state. The policy-maker does not interpret these flags or understand them; they come from the power state array, and are understood only by interested drivers and perhaps the power-controlling driver. If the current power state is not yet defined, zero is returned. This is the case when the policy-maker is not yet in the power domain hierarchy or when it doesn't have a power-controlling driver yet.

registerInterrupt

Abstract: Register a C-function interrupt handler for a device supplying interrupts.
public:

virtual IOReturn registerInterrupt(int source, OSObject *target, IOInterruptAction handler, void *refCon = 0);

This method will install a C-function interrupt handler to be called at primary interrupt time for a device's interrupt. Only one handler may be installed per interrupt source. IOInterruptEventSource provides an IOWorkLoop based abstraction for interrupt delivery that may be more appropriate for work loop based drivers.

Parameters

NameDescription
sourceThe index of the interrupt source in the device.
targetAn object instance to be passed to the interrupt handler.
handlerThe C-function to be to be called at primary interrupt time when the interrupt occurs. The handler should process the interrupt by clearing the interrupt, or by disabling the source.
refConA reference constant for the handler's use.
Result: An IOReturn code.
kIOReturnNoInterrupt is returned if the source is not valid.
kIOReturnNoResources is returned if the interrupt already has an installed handler.

registerService

Abstract: Start the registration process for a newly discovered IOService.
public:

virtual void registerService( IOOptionBits options = 0 );

This function allows an IOService subclass to be published and made available to possible clients, by starting the registration process and delivering notifications to registered clients. The object should be completely setup and ready to field requests from clients before registerService is called.

Parameters

NameDescription
optionsThe default zero options mask is recommended & should be used in most cases. The registration process is usually asynchronous, with possible driver probing & notification occurring some time later. kIOServiceSynchronous may be passed to carry out the matching and notification process for currently registered clients before returning to the caller.

removeChild

public:

virtual IOReturn removeChild( IOService * theChild );

A power domain policy-maker is called here to tell it that one of its enclosed members is disappearing. This happens when a device policy-maker hands off its responsibility to another policy-maker or when its device disappears.


requestDomainState

public:

IOReturn requestDomainState( IOPMPowerFlags desiredState, IOService* whichChild, unsigned long specificationFlags );

The child of a power domain calls it parent here to request power of a certain character. It does this after lowering power in its own device which allows it to tolerate lower power in the domain, and it does this if it needs more power for its device than is currently available in the domain.

Parameters

NameDescription
desiredStateThese flags describe the power required for some state of the caller's device. They are not understood by either the child or the parent. They come from the power state array of the child (in the inputPowerRequirement field), and the parent compares them to bits in the outputPowerCharacter fields of its power state array.
whichChildThis points to the caller, so the power domain can know which child is requesting.
specificationFlagsThis value modifies the parent's choice of power state. If the parameter is IOPMNextHigherState, the parent will choose the lowest state which matches desiredState and which is higher than the current state. If the parameter is IOPMHighestState , the parent will choose the highest state which matches desiredState. If the parameter is IOPMNextLowerState, the parent will choose the highest state which matches desiredState and which is lower than the current state. If the parameter is IOPMLowestState, the parent will choose the lowest state which matches desiredState. A state matches desiredState if all the bits set in desiredState are also set in the outputPowerCharacter field of that state in the parent's power state array.
Result: The power domain parent returns IOPMBadSpecification if specificationFlags not wellformed. It returns IOPMNoSuchState if no state in its array satisfies the callers specification. It returns IOPMNotYetInitialized if it has not power state array yet to compare with. Otherwise it returns IOPMNoErr. In the last case it will initiate its change to the new state if it has a parent in the hierarchy (or is the root power domain.)

requestProbe

Abstract: An external request that hardware be re-scanned for devices.
public:

virtual IOReturn requestProbe( IOOptionBits options );

For bus families that do not usually detect device addition or removal, this method represents an external request (eg. from a utility application) to rescan and publish or remove found devices.

Parameters

NameDescription
optionsFamily defined options, not interpreted by IOService.
Result: An IOReturn code.
kIOReturnNoInterrupt is returned if the source is not valid.

resourceMatching

Abstract: Create a matching dictionary, or add matching properties to an existing dictionary, that specify a resource service match.
public:

static OSDictionary * resourceMatching( const OSString * name, OSDictionary * table = 0 );

IOService maintains a resource service IOResources that allows objects to be published and found globally in IOKit based on a name, using the standard IOService matching and notification calls.

Parameters

NameDescription
nameThe resource name, as an OSString (which includes OSSymbol). Resource matching is successful when an object by that name has been published with the publishResource method.
tableIf zero, resourceMatching will create a matching dictionary and return a reference to it, otherwise the matching properties are added to the specified dictionary.
Result: The matching dictionary created, or passed in, is returned on success, or zero on failure.

resourceMatching

Abstract: Create a matching dictionary, or add matching properties to an existing dictionary, that specify a resource service match.
public:

static OSDictionary * resourceMatching( const char * name, OSDictionary * table = 0 );

IOService maintains a resource service IOResources that allows objects to be published and found globally in IOKit based on a name, using the standard IOService matching and notification calls.

Parameters

NameDescription
nameThe resource name, as a const C-string. Resource matching is successful when an object by that name has been published with the publishResource method.
tableIf zero, resourceMatching will create a matching dictionary and return a reference to it, otherwise the matching properties are added to the specified dictionary.
Result: The matching dictionary created, or passed in, is returned on success, or zero on failure.

serviceMatching

Abstract: Create a matching dictionary, or add matching properties to an existing dictionary, that specify an IOService class match.
public:

static OSDictionary * serviceMatching( const OSString * className, OSDictionary * table = 0 );

A very common matching criteria for IOService is based on its class. serviceMatching will create a matching dictionary that specifies any IOService of a class, or its subclasses. The class is specified by name, and an existing dictionary may be passed in, in which case the matching properties will be added to that dictionary rather than creating a new one.

Parameters

NameDescription
classNameThe class name, as an OSString (which includes OSSymbol). Class matching is successful on IOService's of this class or any subclass.
tableIf zero, serviceMatching will create a matching dictionary and return a reference to it, otherwise the matching properties are added to the specified dictionary.
Result: The matching dictionary created, or passed in, is returned on success, or zero on failure.

serviceMatching

Abstract: Create a matching dictionary, or add matching properties to an existing dictionary, that specify an IOService class match.
public:

static OSDictionary * serviceMatching( const char * className, OSDictionary * table = 0 );

A very common matching criteria for IOService is based on its class. serviceMatching will create a matching dictionary that specifies any IOService of a class, or its subclasses. The class is specified by name, and an existing dictionary may be passed in, in which case the matching properties will be added to that dictionary rather than creating a new one.

Parameters

NameDescription
classNameThe class name, as a const C-string. Class matching is successful on IOService's of this class or any subclass.
tableIf zero, serviceMatching will create a matching dictionary and return a reference to it, otherwise the matching properties are added to the specified dictionary.
Result: The matching dictionary created, or passed in, is returned on success, or zero on failure.

setAggressiveness

public:

virtual IOReturn setAggressiveness( unsigned long, unsigned long newLevel );

The parent of a policy-maker calls it here while broadcasting an aggressiveness factor around the power management hierarchy.

A policy-maker may want to intercept this call if it needs to do something with the new factor, like change its idle timeout, for example. A policy-maker which does intercept should call setAggressiveness in its superclass, though.

Parameters

NameDescription
typeThere are several aggressiveness factors which can be broadcast. One is a general aggressiveness factor, and the others are specific to parts of the system, like the hard drive or the display. A policy-maker takes action only on a factor that applies to its policy. These factor types (e.g. kPMSetGeneralAggressiveness) are defined in pwr_mgt/IOPM.h.
newLevelThis is the aggressiveness factor's new value.
Result: setAggressiveness returns IOPMNoErr.

setDeviceMemory

Abstract: Sets the array of IODeviceMemory objects representing a device's memory mapped ranges.
public:

virtual void setDeviceMemory( OSArray * array );

This method will set an array of IODeviceMemory objects representing the physical memory ranges allocated to a memory mapped device.

Parameters

NameDescription
arrayAn OSArray of IODeviceMemory objects, or zero if none are available. The array will be retained by the object.

setIdleTimerPeriod

public:

virtual IOReturn setIdleTimerPeriod( unsigned long );

A policy-maker which uses the type 1 idleness determination provided by IOService calls its superclass here to set or change the idle timer period.

See activityTickle for a description of this idleness determination.

Parameters

NameDescription
periodThis is the desired idle timer period in seconds.
Result: The normal return is IOPMNoErr, but it is possible to return kIOReturnError if there was difficulty creating the timer event or the command queue, for example (which is done only on the first call.)

setParent

public:

virtual IOReturn setParent( IOService * theParent, IOPMPowerFlags currentState );

The Platform Expert or some other IOService calls a policy-maker here to inform it who its parent is in the power management hierarchy. This is part of the process of attaching a policy-maker into the hierarchy.

Parameters

NameDescription
theParentThis is a pointer to the parent IOService power domain.
currentStateThese flags describe the character of power in the power domain. If the policy-maker has a controlling driver, the policy-maker asks the driver, given this power domain state, what state it would be in, and then it tells the driver to assume that state.

setPowerState

public:

virtual IOReturn setPowerState( unsigned long powerStateOrdinal, IOService* whatDevice );

A policy-maker (usually its superclass) calls its controlling driver here to change the power state of its device.

Parameters

NameDescription
powerStateOrdinalThis is the number in the power state array of the state the driver is being instructed to switch to.
whatDeviceThis is a pointer to the policy-maker. It is useful when a single power-controlling driver controls multiple devices and needs to know for which device it is being called.
Result: The driver returns IOPMAckImplied if it has complied with the request when it returns. If it has started the process of changing power state but not finished it, it should return a number of microseconds which is an upper limit of the time it will need to finish. Then, when it has completed the power switch, it should call acknowledgeSetPowerState in the policy-maker.

start

Abstract: During an IOService instantiation, the start method is called when the IOService has been selected to run on the provider.
public:

virtual bool start( IOService * provider );

The registration process for an IOService (the provider) includes instantiating possible driver clients. The start method is called in the client instance when it has been selected (by its probe score and match category) to be the winning client. The client is already attached to the provider when start is called.

Result: Return true if the start was successful, false otherwise (which will cause the instance to be detached and usually freed).

stop

Abstract: During an IOService termination, the stop method is called in its clients before they are detached & it is destroyed.
public:

virtual void stop( IOService * provider );

The termination process for an IOService (the provider) will call stop in each of its clients, after they have closed the provider if they had it open, or immediately on termination.


stringFromReturn

Abstract: A utility to supply a programmer friendly string from an IOReturn code.
public:

virtual const char * stringFromReturn( IOReturn rtn );

Strings are available for the standard return codes in IOReturn.h in IOService, while subclasses may implement this method to interpret family dependent return codes.

Parameters

NameDescription
rtnThe IOReturn code.
Result: A pointer to a constant string, or zero if the return code is unknown.

temperatureCriticalForZone

public:

virtual IOReturn temperatureCriticalForZone( IOService * whichZone );

A policy-maker calls its parent power domain to alert it to critical temperature in some thermal zone.

Parameters

NameDescription
whichZoneThis is a pointer to the IOService policy-maker for the thermal zone which has reported critical temperature.
Result: temperatureCriticalForZone returns IOPMNoErr.

terminate

Abstract: Make an IOService inactive and begin its destruction.
public:

virtual bool terminate( IOOptionBits options = 0 );

Registering an IOService informs possible clients of its existance and instantiates drivers that may be used with it; terminate involves the opposite process of informing clients that an IOService is no longer able to be used and will be destroyed. By default, if any client has the service open, terminate fails. If the kIOServiceRequired flag is passed however, terminate will be sucessful though further progress in the destruction of the IOService will not proceed until the last client has closed it. The service will be made inactive immediately upon successful termination, and all its clients will be notified via their message method with a message of type kIOMessageServiceIsTerminated. Both these actions take place on the callers thread. After the IOService is made inactive, further matching or attach calls will fail on it. Each client has its stop method called upon their close of an inactive IOService, or on its termination if they do not have it open. After stop, detach is called in each client. When all clients have been detached, the finalize method is called in the inactive service. The terminate process is inherently asynchronous since it will be deferred until all clients have chosen to close.

Parameters

NameDescription
optionsIn most cases no options are needed. kIOServiceSynchronous may be passed to cause terminate to not return until the service is finalized.

terminateClient

Abstract: Passes a termination up the stack.
public:

virtual bool terminateClient( IOService * client, IOOptionBits options );

When an IOService is made inactive the default behaviour is to also make any of its clients that have it has their only provider also inactive, in this way recursing the termination up the driver stack. This method allows a terminated IOService to override this behaviour. Note the client may also override this behaviour by overriding its terminate method.

Parameters

NameDescription
clientThe client of the of the terminated provider.
optionsOptions originally passed to terminate, plus kIOServiceRecursing.
Result: result of the terminate request on the client.

unlockForArbitration

Abstract: Unlocks an IOService after a successful lockForArbitration.
public:

virtual void unlockForArbitration( void );

A thread granted exclusive access to an IOService should release it with unlockForArbitration.


unregisterInterrupt

Abstract: Remove a C-function interrupt handler for a device supplying hardware interrupts.
public:

virtual IOReturn unregisterInterrupt(int source);

This method will remove a C-function interrupt handler previously installed with registerInterrupt.

Parameters

NameDescription
sourceThe index of the interrupt source in the device.
Result: An IOReturn code.
kIOReturnNoInterrupt is returned if the source is not valid.

waitForService

Abstract: Wait for a matching to service to be published.
public:

static IOService * waitForService( OSDictionary * matching, mach_timespec_t * timeout = 0);

Provides a method of waiting for an IOService matching the supplied matching dictionary to be registered and fully matched.

Parameters

NameDescription
matchingThe matching dictionary describing the desired IOService.
timeoutThe maximum time to wait.
Result: A published IOService matching the supplied dictionary.

waitQuiet

Abstract: Wait for an IOService's busyState to be zero.
public:

virtual IOReturn waitQuiet( mach_timespec_t * timeout = 0 );

Blocks the caller until an IOService is non busy.

Parameters

NameDescription
timeoutSpecifies a maximum time to wait.
Result: Returns an error code if mach synchronization primitives fail, kIOReturnTimeout, or kIOReturnSuccess.

youAreRoot

public:

IOReturn youAreRoot( void );

The Platform Expert instantiates the root power domain IOService and calls it here to inform it that it is the root power domain. (The only difference between the root domain and any other power domain is that the root has no parent and therefore never calls it.


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOServicePM.h

IOServicePM.h



#defines

ACK_TIMER_PERIOD

#define ACK_TIMER_PERIOD 1000000

When an IOService is waiting for acknowledgement to a power state change notification from an interested driver or the controlling driver its ack timer is ticking every millisecond. (1000000 nanoseconds are one millisecond).


State machine states

#define IOPMour_prechange_1 1
#define IOPMour_prechange_2 2
#define IOPMour_prechange_3 3
#define IOPMour_prechange_4 4
#define IOPMparent_prechange_down_3 5
#define IOPMparent_prechange_down_4 6
#define IOPMparent_prechange_down_5 7
#define IOPMparent_postchange_down_1 8
#define IOPMparent_postchange_down_2 9
#define IOPMparent_prechange_up_1 10
#define IOPMparent_postchange_up_1 11
#define IOPMparent_postchange_up_4 12
#define IOPMparent_postchange_up_5 13
#define IOPMparent_postchange_up_6 14
#define IOPMparent_postchange_null 15
#define IOPMfinished 16

The current change note is processed by a state machine. Inputs are acks from interested parties, ack from the controlling driver, ack timeouts, settle timeout, and powerStateDidChange from the parent.


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOPMpriv

IOPMpriv



Member Functions

serialize

    public:

virtual bool serialize(OSSerialize *s) const;

Serialize private instance variables for debug output (IORegistryDumper).


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOPMprot

IOPMprot



Member Functions

serialize

    public:

virtual bool serialize(OSSerialize *s) const;

Serialize protected instance variables for debug output (IORegistryDumper).


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOStorage.h

IOStorage.h



Typedefs

IOStorageCompletionAction

typedef void (*IOStorageCompletionAction)(void *   target,
                                          void *   parameter,
                                          IOReturn status,
                                          UInt64   actualByteCount);

The IOStorageCompletionAction declaration describes the C (or C++) completion routine that is called once an asynchronous storage operation completes.

Parameters

NameDescription
targetOpaque client-supplied pointer (or an instance pointer for a C++ callback).
parameterOpaque client-supplied pointer.
statusStatus of the data transfer.
actualByteCountActual number of bytes transferred in the data transfer.

Structs

IOStorageCompletion

struct  IOStorageCompletion
{
  void  *  target;
  IOStorageCompletionAction  action;
  void  *  parameter;
};

The IOStorageCompletion structure describes the C (or C++) completion routine that is called once an asynchronous storage operation completes. The values passed for the target and parameter fields will be passed to the routine when it is called.

Fields

NameDescription
targetOpaque client-supplied pointer (or an instance pointer for a C++ callback).
actionCompletion routine to call on completion of the data transfer.
parameterOpaque client-supplied pointer.

#defines

kIOStorageCategory

kIOStorageCategory is a value for IOService's kIOMatchCategoryKey property.

#define kIOStorageCategory "IOStorage" /* (as IOMatchCategory) */

The kIOStorageCategory value is the standard value for the IOService property kIOMatchCategoryKey ("IOMatchCategory") for all storage drivers. All storage objects that expect to drive new content (that is, produce new media objects) are expected to compete within the kIOStorageCategory namespace. * See the IOService documentation for more information on match categories.


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOStorage

IOStorage



Member Functions

complete

protected:

inline void complete(IOStorageCompletion completion, IOReturn status, UInt64 actualByteCount = 0);

Invokes the specified completion action of the read/write request. If the completion action is unspecified, no action is taken. This method serves simply as a convenience to storage subclass developers.

Parameters

NameDescription
completionCompletion information for the data transfer.
statusStatus of the data transfer.
actualByteCountActual number of bytes transferred in the data transfer.

handleClose

protected:

virtual void handleClose(IOService * client, IOOptionBits options) = 0;

The handleClose method closes the client's access to this object.

Parameters

NameDescription
clientClient requesting the close.
optionsOptions for the close. Set to zero.

handleIsOpen

protected:

virtual bool handleIsOpen(const IOService * client) const = 0;

The handleIsOpen method determines whether the specified client, or any client if none is specificed, presently has an open on this object.

Parameters

NameDescription
clientClient to check the open state of. Set to zero to check the open state of all clients.
Result: Returns true if the client was (or clients were) open, false otherwise.

handleOpen

protected:

virtual bool handleOpen(IOService * client, IOOptionBits options, void * access) = 0;

The handleOpen method grants or denies permission to access this object to an interested client. The argument is an IOStorageAccess value that specifies the level of access desired -- reader or reader-writer. * This method can be invoked to upgrade or downgrade the access level for an existing client as well. The previous access level will prevail for upgrades that fail, of course. A downgrade should never fail. If the new access level should be the same as the old for a given client, this method will do nothing and return success. In all cases, one, singular close-per-client is expected for all opens-per-client received.

Parameters

NameDescription
clientClient requesting the open.
optionsOptions for the open. Set to zero.
accessAccess level for the open. Set to kAccessReader or kAccessReaderWriter.
Result: Returns true if the open was successful, false otherwise.

open

public:

inline bool open(IOService * client, IOOptionBits options, IOStorageAccess access);

Ask the storage object for permission to access its contents; the method is equivalent to IOService::open(), but with the correct parameter types. * This method may also be invoked to upgrade or downgrade the access of an existing open (if it fails, the existing open prevails).

Parameters

NameDescription
clientClient requesting the open.
optionsOptions for the open. Set to zero.
accessAccess level for the open. Set to kAccessReader or kAccessReaderWriter.
Result: Returns true if the open was successful, false otherwise.

read

public:

virtual void read(IOService * client, UInt64 byteStart, IOMemoryDescriptor * buffer, IOStorageCompletion completion) = 0;

Read data from the storage object at the specified byte offset into the specified buffer, asynchronously. When the read completes, the caller will be notified via the specified completion action. * The buffer will be retained for the duration of the read.

Parameters

NameDescription
clientClient requesting the read.
byteStartStarting byte offset for the data transfer.
bufferBuffer for the data transfer. The size of the buffer implies the size of the data transfer.
completionCompletion routine to call once the data transfer is complete.

read

public:

virtual IOReturn read(IOService * client, UInt64 byteStart, IOMemoryDescriptor * buffer, UInt64 * actualByteCount = 0);

Read data from the storage object at the specified byte offset into the specified buffer, synchronously. When the read completes, this method will return to the caller. The actual byte count field is optional.

Parameters

NameDescription
clientClient requesting the read.
byteStartStarting byte offset for the data transfer.
bufferBuffer for the data transfer. The size of the buffer implies the size of the data transfer.
actualByteCountReturns the actual number of bytes transferred in the data transfer.
Result: Returns the status of the data transfer.

write

public:

virtual void write(IOService * client, UInt64 byteStart, IOMemoryDescriptor * buffer, IOStorageCompletion completion) = 0;

Write data into the storage object at the specified byte offset from the specified buffer, asynchronously. When the write completes, the caller will be notified via the specified completion action. * The buffer will be retained for the duration of the write.

Parameters

NameDescription
clientClient requesting the write.
byteStartStarting byte offset for the data transfer.
bufferBuffer for the data transfer. The size of the buffer implies the size of the data transfer.
completionCompletion routine to call once the data transfer is complete.

write

public:

virtual IOReturn write(IOService * client, UInt64 byteStart, IOMemoryDescriptor * buffer, UInt64 * actualByteCount = 0);

Write data into the storage object at the specified byte offset from the specified buffer, synchronously. When the write completes, this method will return to the caller. The actual byte count field is optional.

Parameters

NameDescription
clientClient requesting the write.
byteStartStarting byte offset for the data transfer.
bufferBuffer for the data transfer. The size of the buffer implies the size of the data transfer.
actualByteCountReturns the actual number of bytes transferred in the data transfer.
Result: Returns the status of the data transfer.

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOTimerEventSource.h

IOTimerEventSource.h



© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOTimerEventSource

IOTimerEventSource



Member Functions

cancelTimeout

Abstract: Disable any outstanding calls to this event source.
public:

virtual void cancelTimeout();

Clear down any oustanding calls. By the time this function completes it is guaranteed that the action will not be called again.


checkForWork

Abstract: Have to implement it is mandatory in $link IOEventSource, but IOTimerEventSources don't actually use this work-loop mechanism.
protected:

virtual bool checkForWork();


disable

Abstract: Disable a timed callout.
public:

virtual void disable();

When disable returns the action will not be called until the next time enable(qv) is called.


enable

Abstract: Enables a call to the action.
public:

virtual void enable();

Allows the action function to be called. If the timer event source was disabled while a call was outstanding and the call wasn't cancelled then it will be rescheduled. So a disable/enable pair will disable calls from this event source.


free

Abstract: Sub-class implementation of free method, frees calloutEntry
protected:

virtual void free();


init

Abstract: Initializes the timer with an owner, and a handler to call when the timeout expires.
public:

virtual bool init(OSObject *owner, Action action = 0);


setTimeout

Abstract: Setup a callback at after the delay in decrementer ticks. See wakeAtTime(AbsoluteTime).
public:

virtual IOReturn setTimeout(AbsoluteTime interval);

Parameters

NameDescription
intervalDelay from now to wake up in decrementer ticks.
Result: kIOReturnSuccess if everything is fine, kIOReturnNoResources if action hasn't been declared.

setTimeout

Abstract: Setup a callback at after the delay in decrementer ticks. See wakeAtTime(AbsoluteTime).
public:

virtual IOReturn setTimeout(mach_timespec_t interval);

Parameters

NameDescription
intervalDelay from now to wake up.
Result: kIOReturnSuccess if everything is fine, kIOReturnNoResources if action hasn't been declared.

setTimeout

Abstract: Setup a callback at after the delay in some unit. See wakeAtTime(AbsoluteTime).
public:

virtual IOReturn setTimeout(UInt32 interval, UInt32 scale_factor = kNanosecondScale);

Parameters

NameDescription
intervalDelay from now to wake up in some defined unit.
scale_factorDefine the unit of interval, default to nanoseconds.
Result: kIOReturnSuccess if everything is fine, kIOReturnNoResources if action hasn't been declared.

setTimeoutFunc

Abstract: Set's timeout as the function of calloutEntry.
protected:

virtual void setTimeoutFunc();

IOTimerEventSource is based upon the kern/thread_call.h APIs currently. This function allocates the calloutEntry member variable by using thread_call_allocate(timeout, this). If you need to write your own subclass of IOTimerEventSource you probably should override this method to allocate an entry that points to your own timeout routine.


setTimeoutMS

Abstract: Setup a callback at after the delay in milliseconds. See wakeAtTime(AbsoluteTime).
public:

virtual IOReturn setTimeoutMS(UInt32 ms);

Parameters

NameDescription
intervalDelay from now to wake up, time in milliseconds.
Result: kIOReturnSuccess if everything is fine, kIOReturnNoResources if action hasn't been declared.

setTimeoutTicks

Abstract: Setup a callback at after the delay in scheduler ticks. See wakeAtTime(AbsoluteTime).
public:

virtual IOReturn setTimeoutTicks(UInt32 ticks);

Parameters

NameDescription
intervalDelay from now to wake up, in scheduler ticks, whatever that may be.
Result: kIOReturnSuccess if everything is fine, kIOReturnNoResources if action hasn't been declared.

setTimeoutUS

Abstract: Setup a callback at after the delay in microseconds. See wakeAtTime(AbsoluteTime).
public:

virtual IOReturn setTimeoutUS(UInt32 us);

Parameters

NameDescription
intervalDelay from now to wake up, time in microseconds.
Result: kIOReturnSuccess if everything is fine, kIOReturnNoResources if action hasn't been declared.

timeout

Abstract: Function that routes the call from the OS' timeout mechanism into a work-loop context.
protected:

static void timeout(void *self);

timeout will normally not be called nor overridden by a subclass. If the event source is enabled then close the work-loop's gate and call the action routine.

Parameters

NameDescription
selfThis argument will be cast to an IOTimerEventSource.

timerEventSource

Abstract: Allocates and returns an initialized timer instance.
public:

static IOTimerEventSource * timerEventSource(OSObject *owner, Action action = 0);


wakeAtTime

Abstract: Setup a callback at this absolute time. See wakeAtTime(AbsoluteTime).
public:

virtual IOReturn wakeAtTime(mach_timespec_t abstime);

Parameters

NameDescription
abstimemach_timespec_t of the desired callout time.
Result: kIOReturnSuccess if everything is fine, kIOReturnNoResources if action hasn't been declared.

wakeAtTime

Abstract: Setup a callback at this absolute time.
public:

virtual IOReturn wakeAtTime(AbsoluteTime abstime);

Starts the timer, which will expire at abstime. After it expires, the timer will call the 'action' registered in the init() function. This timer is not periodic, a further call is needed to reset and restart the timer after it expires.

Parameters

NameDescription
abstimeAbsolute Time when to wake up, counted in 'decrementer' units and starts at zero when system boots.
Result: kIOReturnSuccess if everything is fine, kIOReturnNoResources if action hasn't been declared by init or IOEventSource::setAction (qqv).

wakeAtTime

Abstract: Setup a callback at this absolute time. See wakeAtTime(AbsoluteTime).
public:

virtual IOReturn wakeAtTime(UInt32 abstime, UInt32 scale_factor = kNanosecondScale);

Parameters

NameDescription
abstimeTime to wake up in some unit.
scale_factorDefine the unit of abstime, default to nanoseconds.
Result: kIOReturnSuccess if everything is fine, kIOReturnNoResources if action hasn't been declared.

wakeAtTimeMS

Abstract: Setup a callback at this absolute time. See wakeAtTime(AbsoluteTime).
public:

virtual IOReturn wakeAtTimeMS(UInt32 ms);

Parameters

NameDescription
abstimeTime to wake up in milliseconds.
Result: kIOReturnSuccess if everything is fine, kIOReturnNoResources if action hasn't been declared.

wakeAtTimeTicks

Abstract: Setup a callback at this absolute time. See wakeAtTime(AbsoluteTime).
public:

virtual IOReturn wakeAtTimeTicks(UInt32 ticks);

Parameters

NameDescription
abstimeTime to wake up in scheduler quantums, whatever that is?
Result: kIOReturnSuccess if everything is fine, kIOReturnNoResources if action hasn't been declared.

wakeAtTimeUS

Abstract: Setup a callback at this absolute time. See wakeAtTime(AbsoluteTime).
public:

virtual IOReturn wakeAtTimeUS(UInt32 us);

Parameters

NameDescription
abstimeTime to wake up in microseconds.
Result: kIOReturnSuccess if everything is fine, kIOReturnNoResources if action hasn't been declared.

Member Data

Action

public:typedef void (*Action)(OSObject *owner, IOTimerEventSource *sender);

'C' Function pointer defining the callout routine of this event source.

Parameters

NameDescription
ownerOwning target object. Note by a startling coincidence the first parameter in a C callout is currently used to define the target of a C++ member function.
senderThe object that timed out.

Scale

public:
  enum  {
  kNanosecondScale  =  1,
  kMicrosecondScale  =  1000,
  kMillisecondScale  =  1000  *  1000
  };

Used when a scale_factor parameter is required to define a unit of time.

Constants

NameDescription
kNanosecondScaleScale factor for nanosecond based times.
kMicrosecondScaleScale factor for microsecond based times.
kMillisecondScaleScale factor for millisecond based times.

abstime

protected:
 AbsoluteTime abstime;

time to wake up next, see enable.


calloutEntry

protected:
 void *calloutEntry;

thread_call entry for preregistered thread callouts


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOTypes.h

IOTypes.h



© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOUSBController.h

IOUSBController.h



© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOUSBController

IOUSBController



Member Functions

AcquireDeviceZero

public:

virtual IOReturn AcquireDeviceZero();

Get the device zero lock - call this before resetting a device, to ensure there's only one device with address 0


ConfigureDeviceZero

public:

IOReturn ConfigureDeviceZero(UInt8 maxPacketSize, UInt8 speed);

create a pipe to the default pipe for the device at address 0

Parameters

NameDescription
maxPacketSizemax packet size for the pipe
speedDevice speed

GetBandwidthAvailable

public:

virtual UInt32 GetBandwidthAvailable() = 0;

Returns the available bandwidth (in bytes) per frame for isochronous transfers.

Result: maximum number of bytes that a new iso pipe could transfer per frame given current allocations.

GetDeviceZeroDescriptor

public:

IOReturn GetDeviceZeroDescriptor(IOUSBDeviceDescriptor *desc);

read the device descriptor of the device at address 0

Parameters

NameDescription
descpointer to descriptor

GetFrameNumber

public:

virtual UInt64 GetFrameNumber() = 0;

Returns the full current frame number.

Result: The frame number.

GetFrameNumber32

public:

virtual UInt32 GetFrameNumber32() = 0;

Returns the least significant 32 bits of the frame number.

Result: The lsb 32 bits of the frame number.

MakeDevice

public:

IOUSBDevice *MakeDevice(IOUSBDeviceDescriptor *desc, UInt8 speed, UInt32 power);

Create a new device object for the device currently at address 0. This routine calls SetDeviceZeroAddress() with a new, unique, address for the device and adds the device into the registry.

Parameters

NameDescription
descDevice descriptor of the device
speedDevice speed
powerBus power available to the device
Result: Pointer to the newly-created device, 0 if the object coudn't be created.

ReleaseDeviceZero

public:

virtual void ReleaseDeviceZero(void);

Release the device zero lock - call this to release the device zero lock, when there is no longer a device at address 0


SetDeviceZeroAddress

public:

IOReturn SetDeviceZeroAddress(USBDeviceAddress address, UInt8 maxPacketSize, UInt8 speed);

Set the device address of the device currently at address 0. When this routine returns, it's safe to release the device zero lock.

Parameters

NameDescription
addressNew address for the device
maxPacketSizemaximum packet size for the default pipe
speedspeed of the device

WaitForReleaseDeviceZero

public:

void WaitForReleaseDeviceZero();

Block until the device zero lock is released


abortPipe

public:

virtual IOReturn abortPipe(USBDeviceAddress address, Endpoint * endpoint);

Abort pending I/O to/from the specified endpoint, causing them to complete with return code kIOReturnAborted

Parameters

NameDescription
addressAddress of the device on the USB bus
endpointdescription of endpoint

clearPipeStall

public:

virtual IOReturn clearPipeStall(USBDeviceAddress address, Endpoint * endpoint);

Clear a pipe stall.

Parameters

NameDescription
addressAddress of the device on the USB bus
endpointdescription of endpoint

closePipe

public:

virtual IOReturn closePipe(USBDeviceAddress address, Endpoint * endpoint);

Close a pipe to the specified device endpoint

Parameters

NameDescription
addressAddress of the device on the USB bus
endpointdescription of endpoint

deviceRequest

public:

virtual IOReturn deviceRequest(IOUSBDevRequest * request, IOUSBCompletion * completion, USBDeviceAddress address, UInt8 epNum);

Make a control request to the specified endpoint There are two versions of this method, one uses a simple void * to point to the data portion of the transfer, the other uses an IOMemoryDescriptor to point to the data.

Parameters

NameDescription
requestparameter block for the control request
completiondescribes action to take when the request has been executed
addressAddress of the device on the USB bus
epNumendpoint number

isocIO

public:

virtual IOReturn isocIO(IOMemoryDescriptor * buffer, UInt64 frameStart, UInt32 numFrames, IOUSBIsocFrame *frameList, USBDeviceAddress address, Endpoint * endpoint, IOUSBIsocCompletion * completion);

Read from or write to an isochronous endpoint

Parameters

NameDescription
bufferplace to put the transferred data
frameStartUSB frame number of the frame to start transfer
numFramesNumber of frames to transfer
frameListBytes to transfer and result for each frame
addressAddress of the device on the USB bus
endpointdescription of endpoint
completiondescribes action to take when buffer has been filled

openPipe

public:

virtual IOReturn openPipe(USBDeviceAddress address, UInt8 speed, Endpoint *endpoint);

Open a pipe to the specified device endpoint

Parameters

NameDescription
addressAddress of the device on the USB bus
speedof the device: kUSBHighSpeed or kUSBLowSpeed
endpointdescription of endpoint to connect to

read

public:

virtual IOReturn read(IOMemoryDescriptor * buffer, USBDeviceAddress address, Endpoint * endpoint, IOUSBCompletion * completion);

Read from an interrupt or bulk endpoint

Parameters

NameDescription
bufferplace to put the transferred data
addressAddress of the device on the USB bus
endpointdescription of endpoint
completiondescribes action to take when buffer has been filled

resetPipe

public:

virtual IOReturn resetPipe(USBDeviceAddress address, Endpoint * endpoint);

Abort pending I/O and clear stalled state - this method is a combination of abortPipe and clearPipeStall

Parameters

NameDescription
addressAddress of the device on the USB bus
endpointdescription of endpoint

write

public:

virtual IOReturn write(IOMemoryDescriptor * buffer, USBDeviceAddress address, Endpoint * endpoint, IOUSBCompletion * completion);

Write to an interrupt or bulk endpoint

Parameters

NameDescription
bufferplace to get the transferred data
addressAddress of the device on the USB bus
endpointdescription of endpoint
completiondescribes action to take when buffer has been emptied

Member Data

Endpoint

public:
  struct  Endpoint  {
  IOUSBEndpointDescriptor  *descriptor;
  UInt8  number;
  UInt8  direction;  //  in,  out
  UInt8  transferType;  //  cntrl,  bulk,  isoc,  int
  UInt16  maxPacketSize;
  UInt8  interval;
  };

Describes an endpoint of a device. Simply an easier to use version of the endpoint descriptor.

Fields

NameDescription
descriptorThe raw endpoint descriptor.
numberEndpoint number
directionEndpoint direction: kUSBOut, kUSBIn, kUSBAnyDirn
transferTypeType of endpoint: kUSBControl, kUSBIsoc, kUSBBulk, kUSBInterrupt
maxPacketSizeMaximum packet size for endpoint
intervalPolling interval in milliseconds (only relevent for Interrupt endpoints)

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOUSBDevice.h

IOUSBDevice.h



© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOUSBDevice

IOUSBDevice



Member Functions

findNextInterface

public:

virtual IOUSBInterface *findNextInterface(IOUSBInterface *current, FindInterfaceRequest *request);

return an interface satisfying the requirements specified in request, or NULL if there aren't any. request is updated with the properties of the returned interface.

Parameters

NameDescription
currentinterface to start searching from, NULL to start at the beginning of the device's interface list.
requestspecifies what properties an interface must have to match.
Result: Pointer to a matching interface, or NULL if none match

getConfigurationDescriptor

public:

virtual IOReturn getConfigurationDescriptor(UInt8 configValue, void *data, UInt32 len);

Copy the specified amount of data for a configuration into the suppled buffer.

Parameters

NameDescription
configValueThe configuration value
dataBuffer to copy data into
lennumber of bytes to copy

getFullConfigurationDescriptor

public:

virtual const IOUSBConfigurationDescriptor *getFullConfigurationDescriptor(UInt8 configIndex);

return a pointer to all the descriptors for the requested configuration.

Parameters

NameDescription
configIndexThe configuration index (not the configuration value)
Result: Pointer to the descriptors, which are cached in the device object.

resetDevice

public:

virtual IOReturn resetDevice();

Reset the device, returning it to the addressed, unconfigured state. This is useful if a device has got badly confused


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOUSBInterface.h

IOUSBInterface.h



© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOUSBInterface

IOUSBInterface



Member Functions

device

public:

IOUSBDevice * device();

returns the device the interface is part of.

Result: Pointer to the device.

findNextAltInterface

public:

virtual const IOUSBInterfaceDescriptor *findNextAltInterface(const IOUSBInterfaceDescriptor *current, FindInterfaceRequest *request);

return alternate interface descriptor satisfying the requirements specified in request, or NULL if there aren't any. request is updated with the properties of the returned interface.

Parameters

NameDescription
currentinterface descriptor to start searching from, NULL to start at alternate interface 0.
requestspecifies what properties an interface must have to match.
Result: Pointer to a matching interface descriptor, or NULL if none match.

findNextAssociatedDescriptor

public:

virtual const IOUSBDescriptorHeader * findNextAssociatedDescriptor(const void *current, UInt8 type);

Find the next descriptor of the requested type associated with the interface.

Parameters

NameDescription
currentDescriptor to start searching from, NULL to start from beginning of list.
typeDescriptor type to search for, or kUSBAnyDesc to return any descriptor type.
Result: Pointer to the descriptor, or NULL if no matching descriptors found.

findNextPipe

public:

virtual IOUSBPipe *findNextPipe(IOUSBPipe *current, IOUSBFindEndpointRequest *request);

Find a pipe of the interface that matches the requirements, either starting from the beginning of the interface's pipe list or from a specified pipe.

Parameters

NameDescription
currentPipe to start searching from, NULL to start from beginning of list.
requestRequirements for pipe to match, updated with the found pipe's properties.
Result: Pointer to the pipe, or NULL if no pipe matches the request.

getConfigValue

public:

UInt8 getConfigValue();

returns the device configuration value for the interface

Result: The device configuration value.

interfaceDescriptor

public:

const IOUSBInterfaceDescriptor * interfaceDescriptor();

returns the interface descriptor for the interface

Result: Pointer to the interface descriptor.

setAlternateInterface

public:

virtual IOReturn setAlternateInterface(UInt8 alternateSetting);

Select the specified alternate interface.

Parameters

NameDescription
alternateSettingAlternate setting (from the alternate interface's interface descriptor).

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOUSBNub.h

IOUSBNub.h



Structs

IOUSBDevRequest

typedef  struct  {
  UInt8  rqDirection:1;  //  bmRequestType:7
  UInt8  rqType:2;  //  bmRequestType:6..5
  UInt8  rqRecipient:5;  //  bmRequestType:4..0
  UInt8  bRequest;
  USBWord  wValue;
  USBWord  wIndex;
  USBWord  wLength;
  void  *  pData;  //  data  pointer
  UInt32  wLenDone;  //  #  bytes  transferred
}  IOUSBDevRequest;

parameter block for control requests, using a simple pointer for the data to be transferred.

Fields

NameDescription
rdDirectionDirection of data part of request: kUSBIn or kUSBOut
rqTypeRequest type: kUSBStandard, kUSBClass or kUSBVendor
rqRecipientTarget of the request: kUSBDevice, kUSBInterface, kUSBEndpoint or kUSBOther
bRequestRequest code
wValue16 bit parameter for request, low byte first
wIndex16 bit parameter for request, low byte first
wLengthLength of data part of request, 16 bits, low byte first
pDataPointer to data for request
wLenDoneSet by standard completion routine to number of data bytes actually transferred

IOUSBDevRequestDesc

typedef  struct  {
  UInt8  rqDirection:1;  //  bmRequestType:7
  UInt8  rqType:2;  //  bmRequestType:6..5
  UInt8  rqRecipient:5;  //  bmRequestType:4..0
  UInt8  bRequest;
  USBWord  wValue;
  USBWord  wIndex;
  USBWord  wLength;
  IOMemoryDescriptor  *pData;  //  data  pointer
  UInt32  wLenDone;  //  #  bytes  transferred
}  IOUSBDevRequestDesc;

parameter block for control requests, using a memory descriptor for the data to be transferred

Fields

NameDescription
rdDirectionDirection of data part of request: kUSBIn or kUSBOut
rqTypeRequest type: kUSBStandard, kUSBClass or kUSBVendor
rqRecipientTarget of the request: kUSBDevice, kUSBInterface, kUSBEndpoint or kUSBOther
bRequestRequest code
wValue16 bit parameter for request, low byte first
wIndex16 bit parameter for request, low byte first
wLengthLength of data part of request, 16 bits, low byte first
pDataPointer to memory descriptor for data for request
wLenDoneSet by standard completion routine to number of data bytes actually transferred

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOUSBNub

IOUSBNub



Member Functions

GetBandwidthAvailable

public:

virtual UInt32 GetBandwidthAvailable();

Returns the available bandwidth (in bytes) per frame for isochronous transfers.

Result: maximum number of bytes that a new iso pipe could transfer per frame given current allocations.

GetConfiguration

public:

virtual IOReturn GetConfiguration(UInt8 *configNumber);

Gets the current configuration from the device

Parameters

NameDescription
configNumPointer to place to store configuration value

GetConfiguration

public:

virtual IOReturn GetDeviceStatus(USBStatus *status);

Gets the current configuration from the device

Parameters

NameDescription
configNumPointer to place to store configuration value

GetFrameNumber

public:

virtual UInt64 GetFrameNumber();

Returns the full current frame number of the bus the device is attached to

Result: The frame number.

GetStringDescriptor

public:

virtual IOReturn GetStringDescriptor(UInt8 index, char *buf, int maxLen, UInt16 lang=0x409);

Get a string descriptor as ASCII, in the specified language (default is US English)

Parameters

NameDescription
indexIndex of the string descriptor to get.
bufPointer to place to store ASCII string
maxLenSize of buffer pointed to by buf
langLanguage to get string in (default is US English)

address

public:

virtual USBDeviceAddress address(void);

returns the bus address of the device


bus

public:

virtual IOUSBController * bus(void);

returns a pointer to the bus object for the device


busPowerAvailable

public:

virtual UInt32 busPowerAvailable( void );

returns the power available to the device, in units of 2mA


deviceDescriptor

public:

virtual const IOUSBDeviceDescriptor *deviceDescriptor(void);

returns a pointer to the device descriptor


deviceRequest

Abstract: execute a device request
public:

virtual IOReturn deviceRequest(IOUSBDevRequest *request, IOUSBCompletion *completion = 0);

Parameters

NameDescription
requestThe parameter block to send to the device

findNextDescriptor

Abstract: find next descriptor in configuration list of given type (kUSBAnyDesc matches any type).
public:

static const IOUSBDescriptorHeader *findNextDescriptor(const void *cur, UInt8 descType);

call this function with a pointer to a descriptor in a descriptor list, for example the descriptor list returned by IOUSBDevice::getFullConfigurationDescriptor(). Returns NULL if no more descriptors match descType.

Parameters

NameDescription
curcurrent descriptor in list
descTypedescriptor type to return (kUSBAnyDesc to match any type)
Result: Pointer to the next matching descriptor, or NULL if no more match.

pipeZero

public:

virtual IOUSBPipe * pipeZero();

returns a pointer to the device's default pipe


Member Data

FindInterfaceRequest

public:
  struct  FindInterfaceRequest  {
  UInt8  theClass;  //  requested  class,  0  =  don't  care
  UInt8  subClass;  //  requested  subclass;  0  =  don't  care
  UInt8  protocol;  //  requested  protocol;  0  =  don't  care
  UInt8  maxPower;  //  max  power  in  2ma  increments;  0  =  don't  care
  UInt8  busPowered:2;  //  1  =  not  bus  powered,  2  =  bus  powered,
  UInt8  selfPowered:2;  //  1  =  not  self  powered,  2  =  self  powered,
  UInt8  remoteWakeup:2;  //  1  =  doesn't  support  remote  wakeup;  2  =  does
  UInt8  reserved:2;
  };

Parameter block for finding interfaces in a device. Initialize each field to the desired value before calling findNextInterface, set a field to 0 if any value is OK.

Fields

NameDescription
theClassRequested class
subClassRequested subclass
protocolRequested protocol
maxPowermax power consumption in 2mA units
busPowered1 = not bus powered, 2 = bus powered
selfPowered1 = not self powered, 2 = self powered
remoteWakeup1 = doesn't support remote wakeup, 2 = does

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOUSBPipe.h

IOUSBPipe.h



© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOUSBPipe

IOUSBPipe



Member Functions

GetBandwidthAvailable

public:

virtual UInt32 GetBandwidthAvailable();

Returns the available bandwidth (in bytes) per frame for isochronous transfers.

Result: maximum number of bytes that a new iso pipe could transfer per frame given current allocations.

GetFrameNumber

public:

virtual UInt64 GetFrameNumber();

Returns the full current frame number of the bus the device is attached to

Result: The frame number.

abort

public:

virtual IOReturn abort(void);

abort a pipe, causing all outstanding I/O to complete with return code kIOReturnAborted


address

public:

virtual USBDeviceAddress address(void);

returns the bus address of the pipe's device


clearStall

public:

virtual IOReturn clearStall(void);

clear any stall.


controlRequest

public:

// Do a control request over a Control pipe, using a memory descriptor virtual IOReturn controlRequest(IOUSBDevRequestDesc *request, IOUSBCompletion *completion = 0);

Make a control request There are two versions of this method, one uses a simple void * to point to the data portion of the transfer, the other uses an IOMemoryDescriptor to point to the data.

Parameters

NameDescription
requestparameter block for the control request
completiondescribes action to take when the request has been executed

direction

public:

UInt8 direction();

returns the direction of the pipe:kUSBOut/kUSBIn for a bulk or interrupt pipe, kUSBAnyDirn for a control pipe.


endpoint

public:

const IOUSBController::Endpoint * endpoint();

returns a pointer to the Endpoint structure for the pipe.


endpointDescriptor

public:

const IOUSBEndpointDescriptor * endpointDescriptor();

returns the endpoint descriptor for the pipe.


endpointNumber

public:

UInt8 endpointNumber();

returns the endpoint number in the device that the pipe is connected to.


findNextAssociatedDescriptor

public:

virtual const IOUSBDescriptorHeader * findNextAssociatedDescriptor(const void *current, UInt8 type);

Find the next descriptor of the requested type associated with the endpoint.

Parameters

NameDescription
currentDescriptor to start searching from, NULL to start from beginning of list.
typeDescriptor type to search for, or kUSBAnyDesc to return any descriptor type.

read

public:

virtual IOReturn read(IOMemoryDescriptor * buffer, UInt64 frameStart, UInt32 numFrames, IOUSBIsocFrame *frameList, IOUSBIsocCompletion * completion = 0);

Read from an isochronous endpoint

Parameters

NameDescription
bufferplace to put the transferred data
frameStartUSB frame number of the frame to start transfer
numFramesNumber of frames to transfer
frameListBytes to transfer and result for each frame
completiondescribes action to take when buffer has been filled

read

public:

virtual IOReturn read(IOMemoryDescriptor * buffer, IOUSBCompletion * completion = 0, IOByteCount * bytesRead = 0);

Read from an interrupt or bulk endpoint

Parameters

NameDescription
bufferplace to put the transferred data
completiondescribes action to take when buffer has been filled
bytesReadreturns total bytes read for synchronous reads

reset

public:

virtual IOReturn reset(void);

reset a pipe, causing all outstanding I/O to complete with return code kIOReturnAborted, and clear any stall.


status

public:

virtual UInt8 status(void);

Get the current state of the pipe (kIOUSBPipeStalled if stalled or 0 if active). We clear a pipe stall as soon as it is detected, so in practice this routine always returns zero


type

public:

UInt8 type();

returns the pipe type: kUSBControl, kUSBBulk or kUSBInterrupt.


write

public:

virtual IOReturn write(IOMemoryDescriptor * buffer, UInt64 frameStart, UInt32 numFrames, IOUSBIsocFrame *frameList, IOUSBIsocCompletion * completion = 0);

Write to an interrupt or bulk endpoint

Parameters

NameDescription
bufferplace to get the transferred data
frameStartUSB frame number of the frame to start transfer
numFramesNumber of frames to transfer
frameListBytes to transfer and result for each frame
completiondescribes action to take when buffer has been emptied

write

public:

virtual IOReturn write(IOMemoryDescriptor * buffer, IOUSBCompletion * completion = 0);

Write to an interrupt or bulk endpoint

Parameters

NameDescription
bufferplace to get the transferred data
completiondescribes action to take when buffer has been emptied

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOWorkLoop.h

IOWorkLoop.h



© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

IOWorkLoop

IOWorkLoop



Member Functions

_maintRequest

Abstract: Synchrounous implementation of $link addEventSource & $link removeEventSource functions.
protected:

virtual IOReturn _maintRequest(void *command, void *data, void *, void *);


addEventSource

public:

virtual IOReturn addEventSource(IOEventSource *newEvent);

Add an event source to be monitored by the work loop. This function does not return until the work loop has acknowledged the arrival of the new event source. When a new event has been added the threadMain will always restart it's loop and check all outstanding events. The event source is retained by the work loop

Parameters

NameDescription
newEventPointer to $link IOEventSource subclass to add.
Result: Always returns kIOReturnSuccess.

closeGate

Abstract: Close the single-threading gate
public:

virtual void closeGate();


disableAllEventSources

Abstract: Call disable() in all event sources
public:

virtual void disableAllEventSources() const;

For all event sources in $link eventChain call disable() function. See $link IOEventSource::disable()


disableAllInterrupts

Abstract: Call disable() in all interrupt event sources
public:

virtual void disableAllInterrupts() const;

For all event sources, ES, for which IODynamicCast(IOInterruptEventSource, ES) is valid, in $link eventChain call disable() function. See $link IOEventSource::disable()


enableAllEventSources

Abstract: Call enable() in all event sources
public:

virtual void enableAllEventSources() const;

For all event sources in $link eventChain call enable() function. See $link IOEventSource::enable()


enableAllInterrupts

Abstract: Call enable() in all interrupt event sources
public:

virtual void enableAllInterrupts() const;

For all event sources, ES, for which IODynamicCast(IOInterruptEventSource, ES) is valid, in $link eventChain call enable() function. See $link IOEventSource::enable()


free

protected:

virtual void free();

Mandatory free of the object independent of the current retain count. If the work loop is running this method will not return until the thread has succefully terminated. Each event source in the chain will be released and the working semaphore will be destroyed.

If the client has some outstanding requests on an event they will never be informed of completion. If an external thread is blocked on any of the event sources they will be awoken with a KERN_INTERUPTED status.


free

Abstract: Sub-class implementation of free method, frees calloutEntry
public:

virtual void signalWorkAvailable();


getThread

Abstract: Get'ter for $link workThread.
public:

virtual IOThread getThread() const;

Result: Returns workThread

inGate

Abstract: Is the current execution context holding the work-loop's gate?
public:

virtual bool inGate() const;

Result: Returns true if IOThreadSelf() is gate holder.

init

public:

virtual bool init();

Result: true if initialised successfully, false otherwise.

launchThreadMain

Abstract: Static function that just calls the $link threadMain function.
private:

static void launchThreadMain(void *self);


onThread

Abstract: Is the current execution context on the work thread?
public:

virtual bool onThread() const;

Result: Returns true if IOThreadSelf() == workThread.

openGate

Abstract: Open the single-threading gate
public:

virtual void openGate();


removeEventSource

public:

virtual IOReturn removeEventSource(IOEventSource *toRemove);

Remove an event source from the work loop. This function does not return until the work loop has acknowledged the removal of the event source. When an event has been removed the threadMain will always restart it's loop and check all outstanding events. The event source will be released before return.

Parameters

NameDescription
toRemovePointer to $link IOEventSource subclass to remove.
Result: kIOReturnSuccess if successful, kIOReturnBadArgument if toRemove couldn't be found.

threadMain

protected:

virtual void threadMain();

Work loop threads main function. This function consists of 3 loops: the outermost loop is the semaphore clear and wait loop, the middle loop terminates when there is no more work and the inside loop walks the event list calling the $link checkForWork method in each event source. If an event source has more work to do then it can set the more flag and the middle loop will repeat. When no more work is outstanding the outermost will sleep until and event is signaled or the least wakeupTime whichever occurs first. If the event source does not require the semaphore wait to time out it must set the provided wakeupTime parameter to zero.


workLoop

Abstract: Factory member function to constuct and intialise a work loop.
public:

static IOWorkLoop *workLoop();

Result: workLoop instance if constructed successfully, 0 otherwise.

Member Data

controlG

protected:
 IOCommandGate *controlG;

Internal control gate to maintain event system.


eventChain

protected:
 IOEventSource *eventChain;

Pointer to first Event Source in linked list.


gateLock

protected:
 IORecursiveLock *gateLock;

Mutual exlusion lock that used by close and open Gate functions.


loopRestart

protected:
 bool loopRestart;

If event chain has been changed and the system has to be rechecked from start this flag is set. (Internal use only)


maintCommandEnum

protected:
  typedef  enum  {  mAddEvent,  mRemoveEvent  }  maintCommandEnum;

Enumeration of commands that $link _maintCommand can deal with.


workSemaphore

protected:
 semaphore_port_t workSemaphore;

The semaphore that is used to signal the work loop when some event has been 'produced'.


workThread

protected:
 IOThread workThread;

Work loop thread.


© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)

USB.h

USB.h



Typedefs

IOUSBCompletion

typedef struct IOUSBCompletion { void * target; IOUSBCompletionAction action; void * parameter; } IOUSBCompletion;();

Struct spefifying action to perform when a USB I/O completes

Parameters

NameDescription
targetThe target to pass to the action function.
actionThe function to call.
parameterThe parameter to pass to the action function.
bufferSizeRemainingbytes left to be transferred

IOUSBCompletionAction

typedef void (*IOUSBCompletionAction)(
                void *			target,
                void *			parameter,
                IOReturn		status,
                UInt32			bufferSizeRemaining);

Function called when USB I/O completes

Parameters

NameDescription
targetThe target specified in the IOUSBCompletion struct.
parameterThe parameter specified in the IOUSBCompletion struct.
statusCompletion status
bufferSizeRemainingbytes left to be transferred

IOUSBFindEndpointRequest

typedef  struct  {
  UInt8  type;  //  kUSBAnyType  =  don't  care
  UInt8  direction;  //  kUSBAnyDirn  =  don't  care
  UInt16  maxPacketSize;
  UInt8  interval;
}  IOUSBFindEndpointRequest;

Struct used to find endpoints of an interface type and direction are used to match endpoints, type, direction, maxPacketSize and interval are updated with the properties of the found endpoint.

Fields

NameDescription
typeType of endpoint: kUSBControl, kUSBIsoc, kUSBBulk, kUSBInterrupt, kUSBAnyType
directionDirection of endpoint: kUSBOut, kUSBIn, kUSBAnyDirn
maxPacketSizemaximum packet size of endpoint.
intervalPolling interval in mSec for endpoint.

USBWord

typedef  struct  USBWord  {
  UInt8  loByte;
  UInt8  hiByte;
}  USBWord;

A 16 bit value in little-endian format, best accessed using the OSRead/WriteLittleInt16 functions

Fields

NameDescription
loByteleast significant byte
hiBytemost significant byte

© 2000 Apple Computer, Inc. — (Last Updated 2/23/2000)