-
Notifications
You must be signed in to change notification settings - Fork 12
Block Devices API
Accessed through: $$.block
=============
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.
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
Provides an interface for block devices drivers so they can be accessed by the user (after registering them with registerDisk).
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...
}
});
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.
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
});
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
});
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
For use of: Device users
Returns a String with the name of the device.
interface.name; // could return 'virtio0', 'sata0', 'sata1', etc.
For use of: Device users
Returns a String with the bus of the device.
interface.bus; // could return 'virtio', 'sata', etc.
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);
});
});
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();
});
});
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();
}
For use of: Device driver implementors
Registers a BlockDeviceInterface so it can be accessed through block.devices or block.buses.
$$.block.registerDisk(myInterface);
Доступ через: $$.block
=============
Для использования: Пользователями устройства
Даёт доступ к блочным устройствам в формате массива Содержит BlockDeviceInterface.
for (const device of $$.block.devices) {
console.log(device.name);
}
// возможный результат:
// virtio0
// hd0
// hd1
// и т.п.
Для использования: Пользователями устройства
Даёт доступ к блочным устройствам в формате объекта. Каждое значение в массиве со всеми устройствами, которые зарегистрированы на данном типе шины.
// возможные значения:
$$.block.buses.virtio
$$.block.buses.hd
// и т.д.
// каждый со своим устройством:
for (const device of $$.block.buses.virtio) {
console.log(device.name);
}
// возможный результат
// virtio0
Даёт интерфейс к драйверу блочного устройства, чтобы пользователь получил к ним доступ (после регистрации с помощью registerDisk).
Для использования: Реализация драйвера устройства
Построить новый интерфейс блочного устройства
Аргумент | Тип | Описание |
---|---|---|
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...
}
});
Для использования: Пользователем устройства
Объект, который содержит в себе информацию (размер сектора, количество секторов и т.п.) об устройстве. Вернёт пустой объект, если не был инициализирован в конструкторе.
interface.formatInfo;
// вероятный результат:
interface.formatInfo.sectorSize;
interface.formatInfo.totalSectorCount;
// и т.д.
Для использования: Пользователями устройства
Читает значение с устройства начиная с заданого сектора, заполняя Uint8Array. Вернёт Promise с таким же Uint8Array или будет отклонён с ошибкой.
const myU8 = new Uint8Array(512);
interface.read(3, myU8).then((u8) => {
// чтение завершено
// u8 это тот же Uint8Array, который содержит в себе информацию
myU8 === u8; // true
}).catch((err) => {
// что-то пошло не так
});
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
});
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
For use of: Device users
Returns a String with the name of the device.
interface.name; // could return 'virtio0', 'sata0', 'sata1', etc.
For use of: Device users
Returns a String with the bus of the device.
interface.bus; // could return 'virtio', 'sata', etc.
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);
});
});
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();
});
});
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();
}
For use of: Device driver implementors
Registers a BlockDeviceInterface so it can be accessed through block.devices or block.buses.
$$.block.registerDisk(myInterface);