Skip to content
PROPHESSOR edited this page May 1, 2018 · 4 revisions

English

Block Devices

Accessed through: $$.block

=============

block.devices

For use of: Device users

Provides access to block devices in an Array format. Contains instances of BlockDeviceInterfaces.

for(constdeviceof$$.block.devices){console.log(device.name);}// might print:// virtio0// hd0// hd1// etc.

block.buses

For use of: Device users

Provides access to block devices in an Object format. Each property is an Array with all the devices registered on that type of bus.

// might have properties like:$$.block.buses.virtio$$.block.buses.hd// etc.// each with their respective devices:for(constdeviceof$$.block.buses.virtio){console.log(device.name);}// might print// virtio0

block.BlockDeviceInterface

Provides an interface for block devices drivers so they can be accessed by the user (after registering them with registerDisk).

constructor(bus, init)

For use of: Device driver implementors

Construct a new block device interface.

ArgumentTypeDescription
busstringThe device's bus (e.g. virtio, sata, etc.)
initobjectAn optional object containing initialization options for the interface

Options for init parameter:

PropertyTypeDescription
readfunctionAssigned to interface.onread
writefunctionAssigned to interface.onwrite
formatInfoobjectReturned when the user tries to get interface.formatInfo
isOnlinefunctionAssigned to interface.ongetonline
constinterface=new$$.block.BlockDeviceInterface('virtio',{read(sector,u8){// my implementation...},write(sector,u8){// my implementation...},formatInfo: {sectorSize: 512,// other info about block device...},isOnline(){// my implementation...}});

formatInfo

For use of: Device users

An Object containing format information (sector size, number of sectors, etc.) about the device. Returns an empty object if it was not initialized in the constructor.

interface.formatInfo;// might contain:interface.formatInfo.sectorSize;interface.formatInfo.totalSectorCount;// etc.

read(sector, u8)

For use of: Device users

Reads data from the device starting from the given sector, filling the given Uint8Array. Returns a Promise that is resolved with the same Uint8Array given or rejected with an Error.

constmyU8=newUint8Array(512);interface.read(3,myU8).then((u8)=>{// the read has completed successfully// u8 is the same Uint8Array we passed in, which now contains the datamyU8===u8;// true}).catch((err)=>{// something went wrong while reading});

write(sector, u8)

For use of: Device users

Writes data to the device starting from the given sector. Returns a Promise that is resolved with nothing or rejected with an Error.

constmyData=newUint8Array(512);// set some data...// then write it:interface.write(3,myData).then(()=>{// the write has completed successfully}).catch((err)=>{// something went wrong while writing});

isOnline

For use of: Device users

Checks whether the disk is online and returns a Boolean indicating whether it's online or not. Note the lack of parentheses, this is a getter property.

interface.isOnline;// may return true or false

name

For use of: Device users

Returns a String with the name of the device.

interface.name;// could return 'virtio0', 'sata0', 'sata1', etc.

bus

For use of: Device users

Returns a String with the bus of the device.

interface.bus;// could return 'virtio', 'sata', etc.

onread = function (sector, u8)

For use of: Device driver implementors

Called when the user wants to read from a sector. The results should be assigned to the given Uint8Array (i.e. it should be modified in place instead of creating a new array). Should return a Promise that's resolved with the Uint8Array passed in or rejected with an error.

interface.onread=(sector,u8)=>newPromise((resolve,reject)=>{// get the data from your disk// example:myDevice.get(sector,u8.length,(err,data)=>{// was there an error?if(err)returnreject(err);// assign the results to the Uint8Array you got:for(leti=0,len=u8.length;i<len;i++){u8[i]=data[i];}// then resolve with the Uint8Array you got:resolve(u8);});});

onwrite = function (sector, u8)

For use of: Device driver implementors

Called when the user wants to write to a sector. Should return a Promise that's resolved with nothing or rejected with an error.

interface.onwrite=(sector,u8)=>newPromise((resolve,reject)=>{// write the data to your disk// example:myDevice.set(sector,u8,(err)=>{// was there an error?if(err)returnreject(err);// then resolve with nothing:resolve();});});

ongetonline = function ()

For use of: Device driver implementors

Called when the user wants to know whether the block device is online. Should return a Boolean indicating whether the device is online.

interface.ongetonline=()=>{// do some checking to see whether the device is online// example:returnmyDevice.checkIsOnline();}

block.registerDisk

For use of: Device driver implementors

Registers a BlockDeviceInterface so it can be accessed through block.devices or block.buses.

$$.block.registerDisk(myInterface);

Russian

Блочные устройства

Доступ через: $$.block

=============

block.devices

Для использования: Пользователями устройства

Даёт доступ к блочным устройствам в формате массива Содержит BlockDeviceInterface.

for(constdeviceof$$.block.devices){console.log(device.name);}// возможный результат:// virtio0// hd0// hd1// и т.п.

block.buses

Для использования: Пользователями устройства

Даёт доступ к блочным устройствам в формате объекта. Каждое значение в массиве со всеми устройствами, которые зарегистрированы на данном типе шины.

// возможные значения:$$.block.buses.virtio$$.block.buses.hd// и т.д.// каждый со своим устройством:for(constdeviceof$$.block.buses.virtio){console.log(device.name);}// возможный результат// virtio0

block.BlockDeviceInterface

Даёт интерфейс к драйверу блочного устройства, чтобы пользователь получил к ним доступ (после регистрации с помощью registerDisk).

constructor(bus, init)

Для использования: Реализация драйвера устройства

Построить новый интерфейс блочного устройства

АргументТипОписание
busstringШина устройства (virtio, sata и т.д)
initobjectОпциональный объект, который содержит в себе параметры инициализации

Значения для параметра init:

ЗначениеТипОписание
readfunctionНазначена на interface.onread
writefunctionНазначена на interface.onwrite
formatInfoobjectВозвращён, когда пользователь пытаеться получить interface.formatInfo
isOnlinefunctionНазначен на interface.ongetonline
constinterface=new$$.block.BlockDeviceInterface('virtio',{read(sector,u8){// my implementation...},write(sector,u8){// my implementation...},formatInfo: {sectorSize: 512,// информация о блочном устройстве},isOnline(){// my implementation...}});

formatInfo

Для использования: Пользователем устройства

Объект, который содержит в себе информацию (размер сектора, количество секторов и т.п.) об устройстве. Вернёт пустой объект, если не был инициализирован в конструкторе.

interface.formatInfo;// вероятный результат:interface.formatInfo.sectorSize;interface.formatInfo.totalSectorCount;// и т.д.

read(sector, u8)

Для использования: Пользователями устройства

Читает значение с устройства начиная с заданого сектора, заполняя Uint8Array. Вернёт Promise с таким же Uint8Array или будет отклонён с ошибкой.

constmyU8=newUint8Array(512);interface.read(3,myU8).then((u8)=>{// чтение завершено// u8 это тот же Uint8Array, который содержит в себе информациюmyU8===u8;// true}).catch((err)=>{// что-то пошло не так});

//TODO: Translate to Russian

write(sector, u8)

For use of: Device users

Writes data to the device starting from the given sector. Returns a Promise that is resolved with nothing or rejected with an Error.

constmyData=newUint8Array(512);// set some data...// then write it:interface.write(3,myData).then(()=>{// the write has completed successfully}).catch((err)=>{// something went wrong while writing});

isOnline

For use of: Device users

Checks whether the disk is online and returns a Boolean indicating whether it's online or not. Note the lack of parentheses, this is a getter property.

interface.isOnline;// may return true or false

name

For use of: Device users

Returns a String with the name of the device.

interface.name;// could return 'virtio0', 'sata0', 'sata1', etc.

bus

For use of: Device users

Returns a String with the bus of the device.

interface.bus;// could return 'virtio', 'sata', etc.

onread = function (sector, u8)

For use of: Device driver implementors

Called when the user wants to read from a sector. The results should be assigned to the given Uint8Array (i.e. it should be modified in place instead of creating a new array). Should return a Promise that's resolved with the Uint8Array passed in or rejected with an error.

interface.onread=(sector,u8)=>newPromise((resolve,reject)=>{// get the data from your disk// example:myDevice.get(sector,u8.length,(err,data)=>{// was there an error?if(err)returnreject(err);// assign the results to the Uint8Array you got:for(leti=0,len=u8.length;i<len;i++){u8[i]=data[i];}// then resolve with the Uint8Array you got:resolve(u8);});});

onwrite = function (sector, u8)

For use of: Device driver implementors

Called when the user wants to write to a sector. Should return a Promise that's resolved with nothing or rejected with an error.

interface.onwrite=(sector,u8)=>newPromise((resolve,reject)=>{// write the data to your disk// example:myDevice.set(sector,u8,(err)=>{// was there an error?if(err)returnreject(err);// then resolve with nothing:resolve();});});

ongetonline = function ()

For use of: Device driver implementors

Called when the user wants to know whether the block device is online. Should return a Boolean indicating whether the device is online.

interface.ongetonline=()=>{// do some checking to see whether the device is online// example:returnmyDevice.checkIsOnline();}

block.registerDisk

For use of: Device driver implementors

Registers a BlockDeviceInterface so it can be accessed through block.devices or block.buses.

$$.block.registerDisk(myInterface);