LDD3学习5--Scull代码流程

设备驱动简介 -- ldd3读书笔记 阅读详情

注:LDD3的整个第三章都在介绍这个程序。也可以看官方的,应该比我写的好。:)

 

1 代码基本结构

scull 使用一块虚拟内存作为模拟设备,并将这块内存划分成多个设备。例如,程序中可以定义 4 个 scull 设备,每个设备都有一个独立的内存区域。每个区域的大小是通过编译时参数或模块参数指定的。

内存分配: scull 的内存分配是通过一个链表实现的,每个链表节点保存了一块内存数据。链表中每个节点的大小是固定的,称为 quantum,多个 quantum 组成一个 qset。当数据超过当前节点的 quantum 大小时,scull 会自动分配新的节点并将其连接到链表中,形成一个灵活的内存管理机制。

核心结构

struct scull_dev

struct scull_dev {
    struct scull_qset *data;  /* Pointer to first quantum set */
    int quantum;              /* the current quantum size */
    int qset;                 /* the current array size */
    unsigned long size;       /* amount of data stored here */
    struct semaphore sem;     /* Mutual exclusion semaphore */
    struct cdev cdev;         /* Char device structure */
};

scull_qset 

struct scull_qset {
    void **data;
    struct scull_qset *next;
};

注册的字符驱动结构体

struct file_operations scull_fops = {
	.owner =    THIS_MODULE,
	.llseek =   scull_llseek,
	.read =     scull_read,
	.write =    scull_write,
	.unlocked_ioctl = scull_ioctl,
	.open =     scull_open,
	.release =  scull_release,
};

2 基本流程

scull_init_module

这个函数是初始化的函数,

int scull_init_module(void)
{
	int result, i;
	dev_t dev = 0;

	/*
	 * Get a range of minor numbers to work with, asking for a dynamic
	 * major unless directed otherwise at load time.
	 */
	if (scull_major) {
		dev = MKDEV(scull_major, scull_minor);
		result = register_chrdev_region(dev, scull_nr_devs, "scull");
	} else {
		result = alloc_chrdev_region(&dev, scull_minor, scull_nr_devs,
				"scull");
		scull_major = MAJOR(dev);
	}
	if (result < 0) {
		printk(KERN_WARNING "scull: can't get major %d\n", scull_major);
		return result;
	}

	/* 
	 * allocate the devices -- we can't have them static, as the number
	 * can be specified at load time
	 */
	scull_devices = kmalloc(scull_nr_devs * sizeof(struct scull_dev), GFP_KERNEL);
	if (!scull_devices) {
		result = -ENOMEM;
		goto fail;  /* Make this more graceful */
	}
	memset(scull_devices, 0, scull_nr_devs * sizeof(struct scull_dev));

        /* Initialize each device. */
	for (i = 0; i < scull_nr_devs; i++) {
		scull_devices[i].quantum = scull_quantum;
		scull_devices[i].qset = scull_qset;
		mutex_init(&scull_devices[i].lock);
		scull_setup_cdev(&scull_devices[i], i);
	}

        /* At this point call the init function for any friend device */
	dev = MKDEV(scull_major, scull_minor + scull_nr_devs);
	dev += scull_p_init(dev);
	dev += scull_access_init(dev);

#ifdef SCULL_DEBUG /* only when debugging */
	scull_create_proc();
#endif

	return 0; /* succeed */

  fail:
	scull_cleanup_module();
	return result;
}

可以看到,初始化的操作就是几个,alloc_chrdev_region,这个用来动态注册设备,kmalloc,这个给自己的主结构分配内存,然后初始化了四个次设备(TODO,这部分还要看看)。另外两个友设备这次就先不看了。。

scull_cleanup_module

这个是退出的清理函数

/*
 * The cleanup function is used to handle initialization failures as well.
 * Thefore, it must be careful to work correctly even if some of the items
 * have not been initialized
 */
void scull_cleanup_module(void)
{
	int i;
	dev_t devno = MKDEV(scull_major, scull_minor);

	/* Get rid of our char dev entries */
	if (scull_devices) {
		for (i = 0; i < scull_nr_devs; i++) {
			scull_trim(scull_devices + i);
			cdev_del(&scull_devices[i].cdev);
		}
		kfree(scull_devices);
	}

#ifdef SCULL_DEBUG /* use proc only if debugging */
	scull_remove_proc();
#endif

	/* cleanup_module is never called if registering failed */
	unregister_chrdev_region(devno, scull_nr_devs);

	/* and call the cleanup functions for friend devices */
	scull_p_cleanup();
	scull_access_cleanup();

}

然后就是注册回调:

struct file_operations scull_fops = {
	.owner =    THIS_MODULE,
	.llseek =   scull_llseek,
	.read =     scull_read,
	.write =    scull_write,
	.unlocked_ioctl = scull_ioctl,
	.open =     scull_open,
	.release =  scull_release,
};

scull_trim():

会在scull_cleanup_module,open的时候如果是只读模式也会调用,这个函数会遍历链表并释放所有分配的内存。

scull_open():

打开设备。 在设备文件被打开时调用,增加设备的引用计数,并进行必要的初始化。

scull_release():

释放设备。 当设备文件被关闭时调用,减少引用计数,如果没有进程再使用该设备,则释放其资源。

scull_read():

从设备读取数据。 将内存中的数据拷贝到用户空间。

scull_write():

向设备写入数据。 将用户空间的数据拷贝到设备的内存中,必要时扩展内存区域。

scull_follow():

返回指定的链表位置指针,同时如果不够,会分配新的链表空间。

试了一下对ko进行echo和cat,有一点小发现。不管是echo还是cat,都调用了一串注册的回调。

ubuntu@VM-8-10-ubuntu:~/ldd3/scull$ echo "Hello, SCULL!" > /dev/scull0
ubuntu@VM-8-10-ubuntu:~/ldd3/scull$ dmesg | tail -n 10
[1522160.238474] scull: get major 0 0
[1522160.239150] scull: get result 241
[1522160.239687] scullsingle registered at f100008
[1522160.239688] sculluid registered at f100009
[1522160.239689] scullwuid registered at f10000a
[1522160.239689] scullpriv registered at f10000b
[1522182.942577] scull_open:
[1522182.943011] scull_trim:
[1522182.943345] scull_write:
[1522182.943672] scull_follow:
ubuntu@VM-8-10-ubuntu:~/ldd3/scull$ cat /dev/scull0
Hello, SCULL!
ubuntu@VM-8-10-ubuntu:~/ldd3/scull$ dmesg | tail -n 10
[1522160.239689] scullwuid registered at f10000a
[1522160.239689] scullpriv registered at f10000b
[1522182.942577] scull_open:
[1522182.943011] scull_trim:
[1522182.943345] scull_write:
[1522182.943672] scull_follow:
[1522205.620598] scull_open:
[1522205.621056] scull_read:
[1522205.621383] scull_follow:
[1522205.621738] scull_read:

按照规范来说,open的时候才会打开scull_open,那么对于echo和cat,详细要看看这两个命令的代码才行。估计这个本身就是执行的一串操作。这里follow和trim是自定义操作。所以

命令行echo输入:open->write

命令行cat输出:open->read

3 重点函数

然后重点看一下write和read两个函数:

scull_write

ssize_t scull_write(struct file *filp, const char __user *buf, size_t count,
                loff_t *f_pos)
{
	struct scull_dev *dev = filp->private_data;
	struct scull_qset *dptr;
	int quantum = dev->quantum, qset = dev->qset;
	int itemsize = quantum * qset;
	int item, s_pos, q_pos, rest;
	ssize_t retval = -ENOMEM; /* value used in "goto out" statements */

	if (mutex_lock_interruptible(&dev->lock))
		return -ERESTARTSYS;

	/* find listitem, qset index and offset in the quantum */
	item = (long)*f_pos / itemsize;
	rest = (long)*f_pos % itemsize;
	s_pos = rest / quantum; q_pos = rest % quantum;

	/* follow the list up to the right position */
	dptr = scull_follow(dev, item);
	if (dptr == NULL)
		goto out;
	if (!dptr->data) {
		dptr->data = kmalloc(qset * sizeof(char *), GFP_KERNEL);
		if (!dptr->data)
			goto out;
		memset(dptr->data, 0, qset * sizeof(char *));
	}
	if (!dptr->data[s_pos]) {
		dptr->data[s_pos] = kmalloc(quantum, GFP_KERNEL);
		if (!dptr->data[s_pos])
			goto out;
	}
	/* write only up to the end of this quantum */
	if (count > quantum - q_pos)
		count = quantum - q_pos;

	if (copy_from_user(dptr->data[s_pos]+q_pos, buf, count)) {
		retval = -EFAULT;
		goto out;
	}
	*f_pos += count;
	retval = count;

        /* update the size */
	if (dev->size < *f_pos)
		dev->size = *f_pos;

  out:
	mutex_unlock(&dev->lock);
	return retval;
}

在这里也可以看到内存的分配,大概是一个1000*4000的矩阵。有1000条,每条是4K。每次的4K是动态分配的。整个4000K也就是4M作为一个item,也就是数据结构中的链表长度。

...4000
...1000

完成之后,将数据的长度写回给驱动中的size。没写完会继续调用scull_write。

这里的锁保护是进来的时候会mutex_lock_interruptible(&dev->lock),结束的时候mutex_unlock(&dev->lock);

scull_read

ssize_t scull_read(struct file *filp, char __user *buf, size_t count,
                loff_t *f_pos)
{
	struct scull_dev *dev = filp->private_data; 
	struct scull_qset *dptr;	/* the first listitem */
	int quantum = dev->quantum, qset = dev->qset;
	int itemsize = quantum * qset; /* how many bytes in the listitem */
	int item, s_pos, q_pos, rest;
	ssize_t retval = 0;

	if (mutex_lock_interruptible(&dev->lock))
		return -ERESTARTSYS;
	if (*f_pos >= dev->size)
		goto out;
	if (*f_pos + count > dev->size)
		count = dev->size - *f_pos;

	/* find listitem, qset index, and offset in the quantum */
	item = (long)*f_pos / itemsize;
	rest = (long)*f_pos % itemsize;
	s_pos = rest / quantum; q_pos = rest % quantum;

	/* follow the list up to the right position (defined elsewhere) */
	dptr = scull_follow(dev, item);

	if (dptr == NULL || !dptr->data || ! dptr->data[s_pos])
		goto out; /* don't fill holes */

	/* read only up to the end of this quantum */
	if (count > quantum - q_pos)
		count = quantum - q_pos;

	if (copy_to_user(buf, dptr->data[s_pos] + q_pos, count)) {
		retval = -EFAULT;
		goto out;
	}
	*f_pos += count;
	retval = count;

  out:
	mutex_unlock(&dev->lock);
	return retval;
}

Read的流程基本就是write的反操作。可以再说一下寻址:

	/* find listitem, qset index, and offset in the quantum */
	item = (long)*f_pos / itemsize;
	rest = (long)*f_pos % itemsize;
	s_pos = rest / quantum; q_pos = rest % quantum;

就是通过这个来查找两级的地址,第一级是item,第二级就是里面的数组。之后就是根据偏移找到正确的数据,并拷贝到用户空间。锁的操作和write一样。

最后就是scull_ioctl。

命令的定义如下:

#define SCULL_IOCRESET    _IO(SCULL_IOC_MAGIC, 0)

/*
 * S means "Set" through a ptr,
 * T means "Tell" directly with the argument value
 * G means "Get": reply by setting through a pointer
 * Q means "Query": response is on the return value
 * X means "eXchange": switch G and S atomically
 * H means "sHift": switch T and Q atomically
 */
#define SCULL_IOCSQUANTUM _IOW(SCULL_IOC_MAGIC,  1, int)
#define SCULL_IOCSQSET    _IOW(SCULL_IOC_MAGIC,  2, int)
#define SCULL_IOCTQUANTUM _IO(SCULL_IOC_MAGIC,   3)
#define SCULL_IOCTQSET    _IO(SCULL_IOC_MAGIC,   4)
#define SCULL_IOCGQUANTUM _IOR(SCULL_IOC_MAGIC,  5, int)
#define SCULL_IOCGQSET    _IOR(SCULL_IOC_MAGIC,  6, int)
#define SCULL_IOCQQUANTUM _IO(SCULL_IOC_MAGIC,   7)
#define SCULL_IOCQQSET    _IO(SCULL_IOC_MAGIC,   8)
#define SCULL_IOCXQUANTUM _IOWR(SCULL_IOC_MAGIC, 9, int)
#define SCULL_IOCXQSET    _IOWR(SCULL_IOC_MAGIC,10, int)
#define SCULL_IOCHQUANTUM _IO(SCULL_IOC_MAGIC,  11)
#define SCULL_IOCHQSET    _IO(SCULL_IOC_MAGIC,  12)

比较特别的是,设置代码中会判断是否是admin,也就是要sudo才能设置。

		if (! capable (CAP_SYS_ADMIN))
			return -EPERM;

这部分的代码主要还是设置之前说的scull_quantum和scull_qset。这里用了好几种方法,直接返回,或者用指针参数返回,还有就是设置并返回旧值。大概就是这几种。。。

最后一个就是proc的调试,打开SCULL_DEBUG调试宏。在proc下面会创建两个节点,scullmem,scullseq。

ubuntu@VM-8-10-ubuntu:~/ldd3/scull$ ls /proc/scull*
/proc/scullmem  /proc/scullpipe  /proc/scullseq

这里是通过scull_read_procmem和scull_seq_show来返回的。如下:

ubuntu@VM-8-10-ubuntu:~/ldd3/scull$ cat /proc/scullmem

Device 0: qset 1000, q 10, sz 14
  item at 00000000dd711a31, qset at 0000000002f9ee99
       0: aa623c79
       1: 601ed2c8

Device 1: qset 1000, q 10, sz 0

Device 2: qset 1000, q 10, sz 0

Device 3: qset 1000, q 10, sz 0
ubuntu@VM-8-10-ubuntu:~/ldd3/scull$ cat /proc/scullseq

Device 0: qset 1000, q 10, sz 14
  item at 00000000dd711a31, qset at 0000000002f9ee99
       0: aa623c79
       1: 601ed2c8

Device 1: qset 1000, q 10, sz 0

Device 2: qset 1000, q 10, sz 0

Device 3: qset 1000, q 10, sz 0

一个是扫内存,一个是把链表打印一圈。结果看起来都差不多。。

4 小结

大部分代码都是八股文。其中一些细节还是挺周到的,比如权限,多种IOCTL。此外对于内存的管理比较花心思,看来这部分是重点了。。。

最后说一下LDD这本书,当然,不否认这个是经典,但是我觉得编排上真不如Beginning Linux Programming,Linux程序设计那本。那本书浅显易懂,循序渐进。我以前就是学了那本书,一直吃了10年老本。。比起来LDD就逊色不少。

ldd3学习笔记--环境搭建(构建linux2.6.10源码树) ldd3《Linux设备驱动程序(第三版)》使用的内核是linux-2.6.10,所以想要搭建一个该版本的内核,方便学习。 //************************************************************************************************* 环境:虚拟机中运行Fedora Core 3 下载地址: Fedora 阅读详情

相关推荐

【原创】【专栏】《Linux设备驱动程序》--- LDD3源码目录结构和源码分析经典链接

【原创】LDD3源码目录结构和源码分析经典链接 http://blog.chinaunix.net/uid-25194149-id-3361623.html http://blog.csdn.net/column/details/ldd3.html

GengLUT 4289

探秘LDD3:一个互动的Linux设备驱动程序开发指南

是一个开源项目,基于经典的《Linux Device Drivers, Third Edition》(简称LDD3)书籍,提供了一种交互式的方式来学习和实践Linux设备驱动程序开发。本文将从技术角度深入解析该项目,并阐述其用途与特点,邀请更多的开发者加入其中。 ## 项目简介 LDD3项目是一个在线版本的Linux设备驱动教程,由Javier Martinez提供了一个可执行的环境,让你能够...

gitblog_00079的博客 779

LDD3(第三版).PDF

由于对Linux设备驱动程序设计的需求,所以前段时间在网上下载了LDD3的HTML格式文档,在看的时候感觉不太好看,同时为了打印方便,把它转化为PDF格式,所以在此与大家一起分享。 由于本资料不是本人自创,也是来自于网络,所以不要求资源分,但是,请不要用于任何商业行办,如果对此书真的感兴趣,请购买正版。 同时,由于本人的时间有限,没有对所有的章节进行重新排版,所以,请原谅!!!!

LDD3笔记基础知识

http://zzzppp.cublog.cn/ 去年(2005)9月2号就买了Linux Device Drivers第三版,但一直没仔细拜读.最近决定仔细研读它以学习Linux设备驱动程序. 在这里归纳学习笔记. 不知道自己有没有恒心把它看完,总之better later than never. 就让这一系列的笔记伴随我学习ldd3的漫漫长路吧 ldd3介绍的是2.6.10版的内核

smile_cc的专栏 1328

【华为鸿蒙3.0/荣耀安卓12使用VMOS Pro的激活方式】

解压激活工具 →连接数据线 轻松搞定激活!

Amy_mumu的博客 142万+

EPLAN二次开发入门:Visual Studio 2019环境配置与插件调试实战

本文详细介绍了EPLAN二次开发入门的关键步骤,重点讲解如何在Visual Studio 2019中配置开发环境并进行插件调试。通过创建符合命名规范的项目、引用核心API库、实现插件接口以及使用附加进程调试等实战技巧,帮助电气工程师快速掌握EPLAN插件开发,提升自动化设计效率。

h6i7j8的博客 765

LDD3学习6--Scull的变种

里面的行,也就是quantum,使用kmem_cache_alloc来获得。kmem_cache_alloc主要用于从特定的高速缓存(cache)中分配内存对象。这些高速缓存是通过kmem_cache_create函数预先创建的。最后一个区别就是在scullc_trim清理的时候,用的kmem_cache_free。分配默认4000byte的空间的时候,使用__get_free_pages来获取。在scullc_init的时候,创建了cache。在scullp_init的时候,和基本版没有区别。

fanged的专栏 825

DBeaver 实战:手动配置 PostgreSQL JDBC 驱动的高级技巧

本文详细介绍了在DBeaver中手动配置PostgreSQL JDBC驱动的高级技巧。针对企业内网、多版本数据库兼容等场景,从获取官方驱动文件、创建自定义驱动配置,到使用Maven坐标管理、连接参数调优及解决常见连接问题,提供了完整的实战指南,帮助开发者实现对数据库连接环境的精准掌控。

apple5的专栏 841

LDD学习2--Scull基本介绍

scull` 实现了 `file_operations` 结构体中的关键函数,注册到内核中,用户程序通过 `open`, `read`, `write`, `close` 等系统调用与设备交互。这些操作由 `scull_open`, `scull_release`, `scull_read`, `scull_write` 函数实现。`scull` 模块创建了一个虚拟的字符设备,它并不和真实的硬件设备交互,而是将分配的内存空间作为设备存储,这样开发者可以在内存中操作数据,模拟实际的字符设备工作流程。

fanged的专栏 601

华南理工大学电子与信息学院23年预推免复试面试经验贴

华南理工大学电子与信息学院23年预推免复试面试经验贴

Scut_Ty的博客 3311

245. 项目195:简易文字冒险游戏——《跟老吕学Python·新手》

如果您在学习本专栏教程时遇到任何问题,或有任何技术交流的意愿,欢迎在文章评论区留言,或通过CSDN私信与老吕取得联系。老吕将及时回复您的留言,并与您共同探讨,以期为大家提供更为精准和有效的帮助。老吕珍视每一位读者的反馈和支持,期待与您共同学习、共同进步,共同创造美好的未来!我们的目标是不仅教会您Python语言,更是培养您解决问题的思维方式。请随意翻阅,按照自己的节奏学习,让这本专栏成为您编程旅程中的可靠伙伴。开发一个简易的文字冒险游戏,通过文本描述场景和事件,让玩家通过选择不同的选项来推动故事发展。

Python老吕的博客 716

LDD3 /scull 驱动实例在linux3.2.0编译实现

由于LDD3的驱动实例都是在linux2.6.10中实现,在后期linux内核版本中有些改动,导致有些实例编译不通过。 环境:ubuntu12.04   内核版本:linux3.2.0  实例:LDD3中驱动实例 SCULL 排除错误 1、scripts/Makefile.build:49: *** CFLAGS was changed in "/usr/src/linux-source

rig622的专栏 7116

【数字IC设计】芯片设计中的RDC

在芯片设计中,RDC是的缩写,类似于CDC(clock domain crossing),由于现在SOC芯片是有很多ECUs组成,为了使整个系统能够快速从复位中恢复, 用户希望SOC里面每个ECU模块都可以有自己独立的异步复位信号,这样可以在出问题的时候只复位有错误逻辑的模块,而使其它模块保持正常工作。

qq_40268672的博客 2205

运行LDD3的例程scull中的scull_load时,出现了很多错误

运行LDD3的例程scull中的scull_load时,出现了很多错误: awk: 0: unexpected character ‘\’ awk: line 1: syntax error at or near == mknod: missing operand after 0' Trymknod –help’ for more information. mknod:

JassionJohn的专栏 1591

「UG/NX」多功能dll集成一个dll的三种方法

C++多功能集成一个dll的三种方法。

何曾参静谧的博客 1394

YOLOv11训练:Roboflow免费数据集获取与格式转换超详细教程

公共数据集库:包含超过20,000个开源数据集数据标注工具:支持在线标注和团队协作数据预处理:自动增强、扩充和格式化版本控制:像管理代码一样管理数据集版本多格式导出:支持所有主流目标检测格式import cv2# 加载图像# 加载标注# 数据增强# 调整尺寸# 调整标注坐标# 转换为Tensor# 实现保持长宽比的resize逻辑pass# 坐标转换逻辑pass# 数据增强实现pass数据集选择优先选择Roboflow上标注质量高的官方数据集。

weixin_39818775的博客 2369

LDD3示例代码Scull编译问题

在运行《Linux设备驱动程序》第三版书中的示例代码时出现了很多编译错误 ,主要原因是我的系统内核版本为 2.6.39,而示例代码运行的内核版本为 2.6.10。以下是我遇到的问题以及解决方案:

liuuq的博客 509

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

LDD3源码学习笔记之scull_pipe转

/*pipe.c*//*=========================================*//*驱动功能分析*/本驱动使用环形缓冲作为scull设备的的具体实现,类似于pipe.其中实现了阻塞的I/O读写和非同步通知./*=========================================*//*主函数流程分析*/1.定义scull_pipe设备机构体(){/*由于

weixiuc的专栏 825

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

linux内核驱动ldd3_《Linux设备驱动程序》编译LDD3的scull驱动问题总结***

Makefile文件分析# disable/enable debugging#DEBUG=y# 当DEBUG变量等于y时。两个比较变量用括号括起来,逗号分隔。ifeq和括号中间有一个空格。ifeq ($(DEBUG), y)#+= 追加变量值。如果该变量之前没有被定义过,+=就自动变成=,变量被定义成递归展开式的变量;如果之前已经定义过,就遵循之前的风格。#=递归展开式变量:在定义时,变量中对其它...

weixin_32265069的博客 406

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain&#39;s apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath(&#39;DeepLearnToolbox&#39;));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand(&#39;state&#39;,0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = &#39;sigm&#39;;%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, &#39;Too big error&#39;);```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, &#39;Too big error&#39;);```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Linux设备驱动程序(LDD) 第三章:Scull设备

简介 SCULL是LDD为字符型设备驱动程序创建的一个示例。其作用是在内存中开辟一段缓冲区,这部分缓冲区可以写入数据,也可以读出数据。 编译环境 编译环境使用Ubuntu 10.04,内核版本2.6.35.14 LDD的源码包:http://pan.baidu.com/s/1kUU5cVl 将源码包解压之后,进入scull目录下执行make指令编译,通常情况下编译是会报错的。这是因为源码包

御风牧云的代码笔记 1084

Linux驱动开发之LDD3中第三章scull注释详解【转】

1 #include <linux/module.h> 2 #include <linux/moduleparam.h> 3 #include <linux/init.h> 4 #include <linux/kernel.h> /* printk() */ 5 #include &l...

199

关于ldd3中的ioctl的调用

这几天终于把scull程序弄好了,重点是知道ioctl怎么用了,主要是要自己写一个头文件定义一些操作,这个应该是 和scull.h中定义的一模一样的。然后再在自己的应用程序中包含这个头文件,我的头文件名字为sculltest.h。具体的,我的应用程序编写如下: #include   #include   #include   #include   #include   #include   #in

Kevin1217的专栏 823

LDD3源码分析之调试技术

版权声明:本文为博主原创文章,未经博主允许不得转载。 作者:刘昊昱  博客:http://blog.csdn.net/liuhaoyutz 编译环境:Ubuntu 10.10 内核版本:2.6.32-38-generic-pae LDD3源码路径:examples/scull/main.c   本文分析LDD3第四章相关代码,主要是使用/proc文件系统(包括seq_f

zjy900507的博客 369

第三章 scull的内存使用 read write函数

在设备驱动简介时,就提到过要编写特定硬件的设备,首先要相当的了解这个设备。scull的设备就是一片内存,了解scull的设备就得知道scull的内存使用了。 如图所示: 事实上,可以把scull的内存直接理解为一个3维数组了(类似)。第一维的单元是Scull_device结构,Scull_device结构的代码如下: 1 struct ...

dianliang2986的博客 263

终极指南:如何从零构建嵌入式Linux驱动系统——基于LDD-LinuxDeviceDrivers项目实战

LDD-LinuxDeviceDrivers是一个专注于Linux内核与设备驱动程序学习的开源项目,提供了从基础模块到高级驱动的完整实战案例。本文将带你快速掌握嵌入式驱动开发的核心技能,通过项目中的实例代码和调试工具,轻松入门Linux设备驱动开发。 ## 为什么选择LDD-LinuxDeviceDrivers? 对于嵌入式开发者而言,掌握Linux设备驱动开发是提升竞争力的关键。LDD-Li

gitblog_00596的博客 561

ldd3 5 继续学习ldd3

LDD3源码分析之并发与竞态 2012-07-05 11:46:32 分类: LINUX 作者:刘昊昱  博客:http://blog.csdn.net/liuhaoyutz 编译环境:Ubuntu 10.10 内核版本:2.6.32-38-generic-pae LDD3源码路径:examples/scull/main.c  exa

jerry_zhang99的专栏 596
上一篇: Android学习19 -- NDK4--共享内存(TODO)
下一篇: Linux内核学习8--VSCode调试Linux内核
fanged
博客等级 码龄24年 1151粉丝 599原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值