Skip to content

Instantly share code, notes, and snippets.

@NanXiao
Created August 2, 2016 02:01
Show Gist options
  • Save NanXiao/b448b3796a44e1d74a8faba00db68b72 to your computer and use it in GitHub Desktop.
Save NanXiao/b448b3796a44e1d74a8faba00db68b72 to your computer and use it in GitHub Desktop.
#include <sys/types.h>
#include <sys/param.h>
#include <sys/kernel.h>
#include <sys/module.h>
#include <sys/errno.h>
#include <sys/systm.h>
#include <sys/conf.h>
#include <sys/uio.h>
static d_open_t hello_open;
static d_close_t hello_close;
static d_read_t hello_read;
static d_write_t hello_write;
static struct make_dev_args args;
static struct cdevsw hello_cdevsw = {
.d_version = D_VERSION,
.d_open = hello_open,
.d_read = hello_read,
.d_write = hello_write,
.d_close = hello_close,
.d_name = "hello"
};
static struct cdev *hello_dev = NULL;
static char buffer[1024];
static int hello_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
{
uprintf("Open hello device\n");
return 0;
}
static int hello_read(struct cdev *dev, struct uio *uio, int ioflag)
{
int error = 0;
uprintf("Read: %p,%p,%d,%ld,%zd,%d,%d,%p\n", uio, uio->uio_iov, uio->uio_iovcnt, uio->uio_offset, uio->uio_resid, uio->uio_segflg, uio->uio_rw, uio->uio_td);
uiomove("Hello", strlen("Hello") + 1, uio);
uprintf("Read: %p,%p,%d,%ld,%zd,%d,%d,%p\n", uio, uio->uio_iov, uio->uio_iovcnt, uio->uio_offset, uio->uio_resid, uio->uio_segflg, uio->uio_rw, uio->uio_td);
return error;
}
static int hello_write(struct cdev *dev, struct uio *uio, int ioflag)
{
int error = 0;
uprintf("Write: %p,%p,%d,%ld,%zd,%d,%d,%p\n", uio, uio->uio_iov, uio->uio_iovcnt, uio->uio_offset, uio->uio_resid, uio->uio_segflg, uio->uio_rw, uio->uio_td);
error = copyin(uio->uio_iov->iov_base, buffer, MIN(sizeof(buffer) - 1, uio->uio_iov->iov_len));
if (error != 0)
{
uprintf("Write to hello device failed, error code is %d\n", error);
}
else
{
buffer[MIN(sizeof(buffer) - 1, uio->uio_iov->iov_len)] = 0;
uprintf("Write to hello device successfully, string is %s\n", buffer);
}
return error;
}
static int hello_close(struct cdev *dev, int fflag, int devtype, struct thread *td)
{
uprintf("Close hello device\n");
return 0;
}
static int hello_modevent(module_t mod __unused, int /* modeventtype_t */ event, void *arg __unused)
{
int error = 0;
switch (event)
{
case MOD_LOAD:
{
make_dev_args_init(&args);
args.mda_devsw = &hello_cdevsw;
args.mda_uid = UID_ROOT;
args.mda_gid = GID_WHEEL;
args.mda_mode = 0600;
uprintf("Hello is loaded:%d\n", make_dev_s(&args, &hello_dev, "%s", hello_cdevsw.d_name));
break;
}
case MOD_UNLOAD:
{
destroy_dev(hello_dev);
uprintf("Hello is unloaded\n");
break;
}
default:
{
error = EOPNOTSUPP;
break;
}
}
return error;
}
static moduledata_t hello_mod =
{
"hello",
hello_modevent,
NULL
};
DECLARE_MODULE(hello, hello_mod, SI_SUB_DRIVERS, SI_ORDER_ANY);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment