优化一下下面这个函数 static u64 read_one_extent(struct zram *zram, u32 eid, u16 gid) { struct erdio *erdio = NULL; u32 ext_size = 0; int ret; struct erdio_priv *priv = NULL; priv = kmalloc(sizeof(struct erdio_priv), GFP_NOIO); if (!priv) goto err; priv->gid = gid; priv->zram = zram; erdio = extramdisk_io_get(eid, GFP_NOIO, REQ_OP_READ); if (!erdio) goto err; ext_size = extramdisk_extent_size(eid); ret = extramdisk_read_async(erdio, read_endio, priv); if (ret) goto err; return ext_size; err: extramdisk_io_put(erdio); kfree(priv); return 0; }
时间: 2024-02-03 10:03:25 浏览: 144
可以尝试以下优化:
1. 将 kmalloc() 和 kfree() 改为使用栈分配和动态分配:
```
static u64 read_one_extent(struct zram *zram, u32 eid, u16 gid) {
struct erdio *erdio = NULL;
u32 ext_size = 0;
int ret;
struct erdio_priv priv = {
.gid = gid,
.zram = zram,
};
erdio = extramdisk_io_get(eid, GFP_NOIO, REQ_OP_READ);
if (!erdio)
return 0;
ext_size = extramdisk_extent_size(eid);
ret = extramdisk_read_async(erdio, read_endio, &priv);
if (ret) {
extramdisk_io_put(erdio);
return 0;
}
extramdisk_io_put(erdio);
return ext_size;
}
```
2. 可以考虑使用 static inline 函数,这样可以避免函数调用的开销:
```
static inline struct erdio_priv *allocate_erdio_priv(u16 gid, struct zram *zram) {
struct erdio_priv *priv = kmalloc(sizeof(struct erdio_priv), GFP_NOIO);
if (!priv)
return NULL;
priv->gid = gid;
priv->zram = zram;
return priv;
}
static u64 read_one_extent(struct zram *zram, u32 eid, u16 gid) {
struct erdio *erdio = NULL;
u32 ext_size = 0;
int ret;
struct erdio_priv *priv = allocate_erdio_priv(gid, zram);
if (!priv)
return 0;
erdio = extramdisk_io_get(eid, GFP_NOIO, REQ_OP_READ);
if (!erdio) {
kfree(priv);
return 0;
}
ext_size = extramdisk_extent_size(eid);
ret = extramdisk_read_async(erdio, read_endio, priv);
if (ret) {
extramdisk_io_put(erdio);
kfree(priv);
return 0;
}
extramdisk_io_put(erdio);
return ext_size;
}
```
3. 可以考虑使用 GOTO 语句的替代方案,例如使用 if-else:
```
static inline struct erdio_priv *allocate_erdio_priv(u16 gid, struct zram *zram) {
struct erdio_priv *priv = kmalloc(sizeof(struct erdio_priv), GFP_NOIO);
if (!priv)
return NULL;
priv->gid = gid;
priv->zram = zram;
return priv;
}
static u64 read_one_extent(struct zram *zram, u32 eid, u16 gid) {
struct erdio *erdio = NULL;
u32 ext_size = 0;
int ret;
struct erdio_priv *priv = allocate_erdio_priv(gid, zram);
if (!priv)
return 0;
erdio = extramdisk_io_get(eid, GFP_NOIO, REQ_OP_READ);
if (erdio) {
ext_size = extramdisk_extent_size(eid);
ret = extramdisk_read_async(erdio, read_endio, priv);
if (!ret) {
extramdisk_io_put(erdio);
return ext_size;
}
extramdisk_io_put(erdio);
}
kfree(priv);
return 0;
}
```
阅读全文