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 (const device of $$.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 (const device of $$.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.

Argument Type Description
bus string The device's bus (e.g. virtio, sata, etc.)
init object An optional object containing initialization options for the interface

Options for init parameter:

Property Type Description
read function Assigned to interface.onread
write function Assigned to interface.onwrite
formatInfo object Returned when the user tries to get interface.formatInfo
isOnline function Assigned to interface.ongetonline
const interface = 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.

const myU8 = new Uint8Array(512);
interface.read(3, myU8).then((u8) => {
  // the read has completed successfully
  // u8 is the same Uint8Array we passed in, which now contains the data
  myU8 === 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.

const myData = new Uint8Array(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) => new Promise((resolve, reject) => {
  // get the data from your disk
  // example:
  myDevice.get(sector, u8.length, (err, data) => {
    // was there an error?
    if (err) return reject(err);
    // assign the results to the Uint8Array you got:
    for (let i = 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) => new Promise((resolve, reject) => {
  // write the data to your disk
  // example:
  myDevice.set(sector, u8, (err) => {
    // was there an error?
    if (err) return reject(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:
  return myDevice.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 (const device of $$.block.devices) {
  console.log(device.name);
}
// возможный результат:
// virtio0
// hd0
// hd1
// и т.п.

block.buses

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

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

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

block.BlockDeviceInterface

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

constructor(bus, init)

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

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

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

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

Значение Тип Описание
read function Назначена на interface.onread
write function Назначена на interface.onwrite
formatInfo object Возвращён, когда пользователь пытаеться получить interface.formatInfo
isOnline function Назначен на interface.ongetonline
const interface = 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 или будет отклонён с ошибкой.

const myU8 = new Uint8Array(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.

const myData = new Uint8Array(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) => new Promise((resolve, reject) => {
  // get the data from your disk
  // example:
  myDevice.get(sector, u8.length, (err, data) => {
    // was there an error?
    if (err) return reject(err);
    // assign the results to the Uint8Array you got:
    for (let i = 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) => new Promise((resolve, reject) => {
  // write the data to your disk
  // example:
  myDevice.set(sector, u8, (err) => {
    // was there an error?
    if (err) return reject(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:
  return myDevice.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);