Apple's open-source XNU kernel on Android phones: its own loader and drivers, Metal on the Adreno. Runs from RAM; a reboot gives the phone back to Android.
C
APFS: back to reading a file's data a block at a time through the cache
vcvkkcde2b0611e08
diff --git a/README.md b/README.mdindex f1323bf..f8d08a4 100644--- a/README.md+++ b/README.md@@ -735,10 +735,40 @@ python3 tools/apfs/verify.py sum /куда/rootfs.apfs # с чем срав- средний столбец веры не заслуживает: его 17 330 → 29 456 → 17 140 по крупным чтениям не может быть следствиемдобавления кеша, тот прогон делил машину с чужой работой.-Куда уходит время на дороге отображения — не измерено. Наиболее вероятное: `apfs_read_stream` берёт данные файла-блоками через кеш блоков, то есть по 4096 байт на запрос virtio, а у virtio-blk в полёте один запрос. Чтение-целого экстента одним запросом сократило бы их число до шестнадцати раз — это следующее, что стоит попробовать,-и мерить так же до и после.+#### Чтение целым экстентом: пробовали, стало медленнее++Казалось, что время уходит на запросы к устройству: `apfs_read_stream` берёт данные файла блоками через кеш+блоков, то есть по 4096 байт на запрос virtio, а у virtio-blk в полёте один запрос. Это проверено —+`struct apfs_dev` получила `read_bulk`, драйвер делал на запрос один `VNOP_STRATEGY` со своим буфером, мимо+кеша и прямо в память вызывающего, а `read_stream` звала её для целых блоков в середине запроса, оставляя кешу+только невыровненные концы.++Число запросов и правда упало: по всему тому на хосте блоков метаданных прочитано 1 441 810 → 238 864, а+4 776 120 320 байт данных файлов пришли 128 588 запросами — по 37 КБ вместо 4 КБ, примерно в девять раз меньше.+Но быстрее не стало:++| дорога | блоками через кеш | целым экстентом |+|---|---|---|+| отображение (`vnop_pagein`) | 24 530 / 23 151 мс | 30 614 / 32 080 мс |+| `read(2)` по 4096 байт | 35 254 / 38 206 мс | 36 007 / 32 551 мс |+| `read(2)` по 65 536 байт | 17 140 / 15 947 мс | 23 288 / 17 922 мс |+| обход всего тома в ядре | 415 903 мс | 449 860 мс |++При разбросе одного и того же ядра около ±8 % дорога отображения медленнее на 30 % в обоих прогонах — это вне+разброса; дороги `read(2)` перекрываются и не говорят ничего; обход всего тома медленнее на 8 %, то есть на+границе. Читалось при этом всё верно: суммы хешей совпадают во всех прогонах, обход тома по-прежнему даёт+318 098 записей, 8 285 771 220 байт содержимого и сумму `ceb8a53c349a011f` при 0 ошибок.++Почему проиграло: почти всё на этом томе лежит сжатым, то есть с устройства читаются куски ресурсной вилки — по+десятку-другому килобайт, по смещениям, не выровненным на блок, и подряд друг за другом. Кеш блоков эти блоки+держал, поэтому соседний кусок и общий последний блок с предыдущим куском доставались без обращения к+устройству. Чтение середины запроса мимо кеша эту локальность выбрасывает, и сэкономленные запросы стоят меньше,+чем потерянная локальность. На томе из больших несжатых файлов, читаемых подряд, вышло бы, скорее всего,+наоборот — но этот том не такой, и корневая файловая система телефона тоже не такая.++Поэтому изменение откачено (в истории оставлено: коммит «read a file's data a whole extent at a time», чтобы к+нему можно было вернуться для устройства, где запрос стоит заметно дороже). Куда на самом деле уходит время на+дороге отображения — по-прежнему не измерено.На телефоне не пробовалось вообще.diff --git a/tools/apfs/apfs-tool.c b/tools/apfs/apfs-tool.cindex 6f18667..f95ad03 100644--- a/tools/apfs/apfs-tool.c+++ b/tools/apfs/apfs-tool.c@@ -80,8 +80,6 @@ open_image(const char *path, struct apfs_nx *nx, struct apfs_vol *vol)dev.ctx = (void *)(intptr_t)fd;dev.size = (uint64_t)lseek(fd, 0, SEEK_END);dev.read = file_read;- /* pread already fetches a whole run in one call */- dev.read_bulk = file_read;error = apfs_nx_open(nx, &dev);if (error) {@@ -137,8 +135,6 @@ cmd_info(const char *path)v.tree.key_count, v.tree.node_count, v.tree.flags);}printf(" blocks read %" PRIu64 ", cache hits %" PRIu64 "\n", nx.reads, nx.hits);- printf(" file-data requests %" PRIu64 ", bytes %" PRIu64 "\n", nx.bulk_calls,- nx.bulk_bytes);apfs_nx_close(&nx);return 0;}@@ -484,8 +480,7 @@ cmd_census(const char *path, const char *where)return 1;}fprintf(stderr, "apfs-tool: %ld entries, %" PRIu64 " blocks read, %" PRIu64- " cache hits, %" PRIu64 " file-data requests for %" PRIu64 " bytes\n",- cs.seen, nx.reads, nx.hits, nx.bulk_calls, nx.bulk_bytes);+ " cache hits\n", cs.seen, nx.reads, nx.hits);free(cs.path);free(cs.buf);apfs_nx_close(&nx);diff --git a/xnu/files/bsd/miscfs/apfs/apfs_lib.c b/xnu/files/bsd/miscfs/apfs/apfs_lib.cindex c38dc1b..63daed6 100644--- a/xnu/files/bsd/miscfs/apfs/apfs_lib.c+++ b/xnu/files/bsd/miscfs/apfs/apfs_lib.c@@ -161,35 +161,6 @@ nx_block(struct apfs_nx *nx, uint64_t addr, const uint8_t **out, bool verify)return 0;}-/*- * A run of whole blocks of file data, straight into the caller's buffer. Nothing is- * cached: see the note on read_bulk in struct apfs_dev.- */-static int-nx_bulk(struct apfs_nx *nx, uint64_t off, void *buf, size_t len)-{- int error;-- if (len == 0) {- return 0;- }- if ((off % nx->block_size) != 0 || (len % nx->block_size) != 0) {- return EIO;- }- if (off / nx->block_size >= nx->block_count ||- len / nx->block_size > nx->block_count - off / nx->block_size) {- return EIO;- }- error = (nx->dev.read_bulk != NULL)- ? nx->dev.read_bulk(nx->dev.ctx, off, buf, len)- : nx->dev.read(nx->dev.ctx, off, buf, len);- if (error == 0) {- nx->bulk_calls++;- nx->bulk_bytes += len;- }- return error;-}-static uint32_tobj_type(const uint8_t *blk){@@ -1492,50 +1463,28 @@ apfs_read_stream(struct apfs_vol *vol, uint64_t stream_id, uint64_t stream_size,{uint64_t from = logical > off ? logical : off;uint64_t to = (logical + length) < end ? (logical + length) : end;- uint64_t dev_off = phys * (uint64_t)bs + (from - logical);+ uint64_t inner = from - logical;uint64_t nbytes = to - from;- uint8_t *dp = dst + (from - off);- const uint8_t *blk;-- /*- * The whole blocks in the middle go to the device in one request and land- * in the caller's buffer directly. Only the ends, where the request does- * not line up with a block, go through the block cache -- one block each.- * File data has no object header, so none of it is checksummed.- */- if ((dev_off % bs) != 0) {- uint64_t skew = dev_off % bs;+ uint64_t addr = phys + inner / bs;+ uint64_t skew = inner % bs;++ while (nbytes > 0) {+ const uint8_t *blk;uint64_t n = bs - skew;if (n > nbytes) {n = nbytes;}- error = nx_block(vol->nx, dev_off / bs, &blk, false);- if (error) {- return error;- }- memcpy(dp, blk + skew, (size_t)n);- dp += n;- dev_off += n;- nbytes -= n;- }- if (nbytes >= bs) {- uint64_t n = (nbytes / bs) * bs;-- error = nx_bulk(vol->nx, dev_off, dp, (size_t)n);+ /* file data has no object header and so no checksum */+ error = nx_block(vol->nx, addr, &blk, false);if (error) {return error;}- dp += n;- dev_off += n;+ memcpy(dst + (from - off), blk + skew, (size_t)n);+ from += n;nbytes -= n;- }- if (nbytes > 0) {- error = nx_block(vol->nx, dev_off / bs, &blk, false);- if (error) {- return error;- }- memcpy(dp, blk, (size_t)nbytes);+ addr++;+ skew = 0;}}}diff --git a/xnu/files/bsd/miscfs/apfs/apfs_lib.h b/xnu/files/bsd/miscfs/apfs/apfs_lib.hindex da10dea..5d29e00 100644--- a/xnu/files/bsd/miscfs/apfs/apfs_lib.h+++ b/xnu/files/bsd/miscfs/apfs/apfs_lib.h@@ -60,15 +60,6 @@ struct apfs_dev {void *ctx;uint64_t size; /* bytes, 0 if not known */int (*read)(void *ctx, uint64_t off, void *buf, size_t len);- /*- * The same, for a file's contents rather than metadata: a whole run of blocks- * straight into the caller's buffer, in as few requests to the device as it can- * manage, and not through any cache. Metadata is read over and over and is worth- * caching; a file's bytes are usually wanted once, and putting them through the- * cache a block at a time cost one request to the device per 4096 bytes and pushed- * the metadata out of it. May be NULL, and then read() is used instead.- */- int (*read_bulk)(void *ctx, uint64_t off, void *buf, size_t len);};/* One cached block of metadata. */@@ -113,8 +104,6 @@ struct apfs_nx {uint32_t clock;uint64_t reads;uint64_t hits;- uint64_t bulk_calls; /* requests for file data, outside the cache */- uint64_t bulk_bytes;};/* A volume inside the container. */diff --git a/xnu/files/bsd/miscfs/apfs/apfs_vfsops.c b/xnu/files/bsd/miscfs/apfs/apfs_vfsops.cindex fa09b3c..1975c12 100644--- a/xnu/files/bsd/miscfs/apfs/apfs_vfsops.c+++ b/xnu/files/bsd/miscfs/apfs/apfs_vfsops.c@@ -70,51 +70,6 @@ apfs_dev_read(void *ctx, uint64_t off, void *buf, size_t len)return 0;}-/*- * A file's contents, straight into the caller's buffer. One buffer of our own per- * request, outside the buffer cache: these bytes are usually wanted once, and putting a- * 64 KB read through the cache a block at a time meant sixteen requests to the device and- * sixteen cached blocks nobody would ask for again.- */-#define APFS_BULK_MAX (64 * 1024)--static int-apfs_dev_read_bulk(void *ctx, uint64_t off, void *buf, size_t len)-{- struct apfs_devctx *dc = ctx;- char *out = buf;-- if ((off % dc->dc_devblock) != 0 || (len % dc->dc_devblock) != 0) {- return EINVAL;- }- while (len > 0) {- size_t n = len < APFS_BULK_MAX ? len : APFS_BULK_MAX;- buf_t bp = buf_alloc(dc->dc_devvp);- int error;-- if (bp == NULL) {- return ENOMEM;- }- buf_reset(bp, B_READ);- buf_setblkno(bp, (daddr64_t)(off / dc->dc_devblock));- buf_setlblkno(bp, (daddr64_t)(off / dc->dc_devblock));- buf_setcount(bp, (uint32_t)n);- buf_setdataptr(bp, (uintptr_t)out);- error = VNOP_STRATEGY(bp);- if (error == 0) {- error = (int)buf_biowait(bp);- }- buf_free(bp);- if (error) {- return error;- }- out += n;- off += n;- len -= n;- }- return 0;-}-/* ------------------------------------------------------------------ vnodes */static uint32_t@@ -290,7 +245,6 @@ apfs_mount_common(mount_t mp, vnode_t devvp, vfs_context_t ctx)dev.ctx = dc;dev.size = devblocks * (uint64_t)devblock;dev.read = apfs_dev_read;- dev.read_bulk = apfs_dev_read_bulk;error = apfs_nx_open(&am->am_nx, &dev);if (error) {@@ -440,11 +394,6 @@ apfs_unmount(mount_t mp, int mntflags, vfs_context_t ctx)if (error) {return error;}- printf("apfs: %llu blocks read for metadata (%llu cache hits), %llu requests for "- "file data carrying %llu bytes\n",- (unsigned long long)am->am_nx.reads, (unsigned long long)am->am_nx.hits,- (unsigned long long)am->am_nx.bulk_calls,- (unsigned long long)am->am_nx.bulk_bytes);vfs_setfsprivate(mp, NULL);if (am->am_owns_devvp && am->am_devvp != NULLVP) {(void)VNOP_CLOSE(am->am_devvp, FREAD, ctx);