Linux内核读取spi-nor flash sn

设备量产时,需要自动设置一个mac地址和sn,如果使用随机数生成的话,可能会有重复的,这里读取spi-nor的sn,参考sn来生成设备的mac和sn;

添加如下部分:
在这里插入图片描述
代码如下:

#include <linux/proc_fs.h>
static ssize_t unique_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
{
	struct spi_nor *nor = PDE_DATA(file_inode(file));
	u8			unique[12];
	u64         unique_id = 0;
	int			i, tmp;

	tmp = nor->read_reg(nor, 0x4b, unique, 12);
	if (tmp < 0) {
		dev_dbg(nor->dev, " error %d reading unique ID\n", tmp);
		return 0;
	}

	for (i=4; i<11; i++) {
		unique_id |= unique[i];
		unique_id = unique_id << 8;
	}
	unique_id |= unique[i];

	return sprintf(buf, "%llx\n", unique_id);
}

static const struct file_operations spi_nor_proc_fops = {
	.read   = unique_read,
	.llseek = default_llseek,
};


static const struct spi_device_id *spi_nor_read_id(struct spi_nor *nor)
{
	int			tmp;
	u8			id[5];
	u32			jedec;
	u16                     ext_jedec;
	struct flash_info	*info;

	//调用
	proc_create_data("unique_id", 0666, NULL, &spi_nor_proc_fops, nor);


	tmp = nor->read_reg(nor, SPINOR_OP_RDID, id, 5);
	if (tmp < 0) {
		dev_dbg(nor->dev, " error %d reading JEDEC ID\n", tmp);
		return ERR_PTR(tmp);
	}
	jedec = id[0];
	jedec = jedec << 8;
	jedec |= id[1];
	jedec = jedec << 8;
	jedec |= id[2];

	ext_jedec = id[3] << 8 | id[4];

	for (tmp = 0; tmp < ARRAY_SIZE(spi_nor_ids) - 1; tmp++) {
		info = (void *)spi_nor_ids[tmp].driver_data;
		if (info->jedec_id == jedec) {
			if (info->ext_id == 0 || info->ext_id == ext_jedec)
				return &spi_nor_ids[tmp];
		}
	}
	dev_err(nor->dev, "unrecognized JEDEC id %06x\n", jedec);
	return ERR_PTR(-ENODEV);
}

然后应用层读取/proc/unique_id即可,应用层读取示例:

#include <stdint.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>

#include <algorithm>
#include <string>

using namespace std;

int main(void)
{
    
    
    int fd;
    
    char  uid[32] = {
    
    0};
    int size;

	fd = open("/proc/unique_id", O_RDONLY);
	if (fd < 0)
		return 1;

	size = read(fd, uid, sizeof(uid));
	close(fd);
	
	uid[strlen(uid)-1] = '\0';
	
	//转为大写
	std::string str = uid;
	std::transform(str.begin(), str.end(),str.begin(), ::toupper);
	printf("%s", str.c_str());

	return 0;
}

猜你喜欢

转载自blog.csdn.net/wuquan_1230/article/details/126262133