Skip to content

Commit

Permalink
trasnlating....
Browse files Browse the repository at this point in the history
  • Loading branch information
rafaelcorsi committed Jun 14, 2023
1 parent b8dc782 commit c70f916
Show file tree
Hide file tree
Showing 12 changed files with 465 additions and 456 deletions.
1 change: 0 additions & 1 deletion 2020-Alunos/cripto
Submodule cripto deleted from db15d6
2 changes: 1 addition & 1 deletion docs-src/Entrega-2.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# 👁 Entrega 2
# 🔔 Entrega 2

O que deve ser entregue?

Expand Down
2 changes: 1 addition & 1 deletion docs-src/Entrega-4.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# 🪙 Delivery 1
# 🔔 Assigment 1

The objective of this delivery is to automate the compilation and deployment of new programs to the `target`. For this, we will have to create a Makefile that should be able to compile and deploy a program. For this, we have several options, some of them being:

Expand Down
33 changes: 16 additions & 17 deletions docs-src/Entrega-5.md
Original file line number Diff line number Diff line change
@@ -1,34 +1,33 @@
# 👁 Entrega 2
# 🔔 Assignment 2

Vocês devem criar uma sistema embarcado que possui um webserver e uma página web que permita sensoriar e controlar o hardware por uma interface simples.
You must create an embedded system that includes a web server and a webpage that allows you to monitor and control the hardware through a simple interface.

A página deve permitir:
The webpage should allow:

1. Controlar o LED da placa
1. Fazer a leitura do botão da placa
1. Control of the board's LED
1. Reading the status of the board's button

Dica: Vocês vai precisar ter um servidor (por exemplo em python) que vai precisar comunicar com um software em C (para controle dos pinos), uma sugesão é a de utilizar um socket para a comunicação entre os dois programas. Aqui tem um exemplo de como fazer isso:
Hint: You will need to have a server (for example in Python) that will need to communicate with a C software (for control of the pins), one suggestion is to use a socket for communication between the two programs. Here is an example of how to do this:

- https://github.com/Insper/Embarcados-Avancados/tree/master/Entrega-5

## Rubrica:
## Rubric

### A

Alguma das opções a seguir:
Any of the following options:

- Leitura e exibição da IMU da placa (dica: usar código exemplo ([hps_gsensor](https://github.com/Insper/DE10-Standard-v.1.3.0-SystemCD/tree/master/Demonstration/SoC/hps_gsensor)))
- Escrever no LCD da placa (dica: usar código exemplo [hps_lcd](https://github.com/Insper/DE10-Standard-v.1.3.0-SystemCD/tree/master/Demonstration/SoC/hps_lcd))
- Ou outra ideia legal (validar com o professor)
- Reading and displaying the board's IMU (hint: use example code ([hps_gsensor](https://github.com/Insper/DE10-Standard-v.1.3.0-SystemCD/tree/master/Demonstration/SoC/hps_gsensor)))
- Writing on the board's LCD (hint: use example code [hps_lcd](https://github.com/Insper/DE10-Standard-v.1.3.0-SystemCD/tree/master/Demonstration/SoC/hps_lcd))
- Or another cool idea (to be validated with the professor)

### B

- O deploy e configuração do webserver deve ser feito via um makefile
- O sistema deve ser inicializado automaticamente

- The web server deployment and configuration should be done via a makefile
- The system should start automatically

### C

- webserver que permite:
- controlar via botão (web) o LED da placa
- leitura da chave da placa (status)
- A web server that allows:
- control of the board's LED via a web button
- reading of the board's switch status
306 changes: 151 additions & 155 deletions docs-src/Tutorial-HPS-Buildroot.md

Large diffs are not rendered by default.

292 changes: 133 additions & 159 deletions docs-src/Tutorial-HPS-DeviceDriver1.md

Large diffs are not rendered by default.

128 changes: 52 additions & 76 deletions docs-src/Tutorial-HPS-kernel-chardriver.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
# Char device driver
# Char Device Driver

Agora iremos criar um driver do tipo char, este módulo irá aparecer como um dispositivo no `/dev/`, suportando que um programa no userspace interaja com ele.
Now we will create a character device driver. This module will appear as a device in `/dev/`, allowing a program in the userspace to interact with it.

## Syscall

Lembre que no linux tudo é um arquivo, inclusive um driver. Para ele se comportar como um arquivo devemos implementar no mínimo as as seguintes chamadas de sistema: `open`, `close/release`, `read` e `write`. Com isso, um programa no userspace poderá interagir com o nosso driver.
Remember that in Linux, everything is a file, including a driver. In order for it to behave like a file, we must implement at least the following system calls: `open`, `close/release`, `read`, and `write`. With this, a program in the userspace will be able to interact with our driver.

!!! info "chamada de sistemas"
Um módulo do tipo char pode implementar outras chamadas de sistema, como definido no arquivo
`fs.h` no repositório do kernel:
!!! info "system calls"
A character device module can implement other system calls as well, as defined in the `fs.h` file in the kernel repository.

```c
struct file_operations {
Expand Down Expand Up @@ -45,40 +44,17 @@ Lembre que no linux tudo é um arquivo, inclusive um driver. Para ele se comport
#endif
};
```

The following code implements a very simple character device driver. This driver has the operations listed in the `fops` struct.

## ebbchar

O código a seguir implementa um driver muito simples do tipo char, esse driver possui as operações listadas no struct `fops`.
This driver does the following: It prints everything that is written to it in the system log and returns the same string for reading. This is done by saving the message in a memory region called `message` (created in the module's init function using `kmalloc`). Every time the driver is opened by a program, it increments a global counter and prints that value in the system log.

Esse driver faz o seguinte: Ele imprime no log do sistema tudo o que for escrito nele e retornar para leitura a mesma string que foi escrito, isso é feito salvando a mensagem na região de memória chamada de `message` (criada no init do módulo com `kmalloc`). Toda vez que o driver for aberto por um programa ele incrementa um contador global e imprime no log do sistema esse valor.

```
+-------+
<------| |----------------<
| | | |
| +-------+ test.c |
| | users space
-v--------------------------------^----------------------
| | kernel space
| |
| +------------------+ |
| write| kmalloc |read |
|----->-\ ------- /-->----
| \ | | / |
| \->|message|-> |
| ---|--- |
+---------|--------+
| ebbchar.c
v
demesg
```
![](figs/kernel-chardriver.svg)

!!! tip
Não copie apenas, leia e entenda. Os códigos fornecidos estão são bem comentandos.

Don't just copy, read and understand. The provided code has detailed comments.

Crie e inicialize com os códigos a seguir, resultando em três arquivos: `ebbchar.c`, `test.c` e `Makefile`
Create and initialize the following files: `ebbchar.c`, `test.c`, and `Makefile`.

=== "Makefile"
```c
Expand Down Expand Up @@ -338,24 +314,24 @@ Crie e inicialize com os códigos a seguir, resultando em três arquivos: `ebbch
}
```

Vamos analisar algumas partes desse código:
Let's analyze some parts of this code:

- `ebbchar_iniat`: é chamado sempre que o driver for inserido no kernel (`insmod`) e faz o registro do módulo coamo device no `/dev/eebchar`. Nessa etapa o driver aloca uma memória para uso interno pelo comando [`kmalloc`](https://www.kernel.org/doc/htmldocs/kernel-hacking/routines-kmalloc.html)
- `ebbchar_init`: It is called whenever the driver is inserted into the kernel (`insmod`) and registers the device module as `/dev/ebbchar`. In this step, the driver allocates memory for internal use using the `kmalloc` command.

``` c
// alocate mem
```c
// allocate memory
message = kmalloc(32, GFP_KERNEL);
if (IS_ERR(message)){
printk(KERN_INFO "Failed to allocate mem \n");
printk(KERN_INFO "Failed to allocate memory\n");
return PTR_ERR(message);
}
```
- `ebbchar_exit`: é chamada quando o driver for removido do kernel (`rmmod`), e remove o device do `/dev/ebbchar`, libera a memória que foi alocada anteriormente (`kfree`).
- `ebbchar_exit`: It is called when the driver is removed from the kernel (`rmmod`), and it removes the device from `/dev/ebbchar` and frees the previously allocated memory using `kfree`.
- A função `dev_open` é chamada sempre que um programa abrir o device como um arquivo, sempre que isso acontece uma variável global (`numberOpens`) é incrementada e um log `KERN_INFO` gerado.
- The `dev_open` function is called whenever a program opens the device as a file. Whenever this happens, a global variable (`numberOpens`) is incremented, and a `KERN_INFO` log is generated.
- `dev_write`: é chamado sempre que acontece uma escrita no driver, quando isso acontece a mensagem que foi passada no comando de write no programa do userspace é copiada para a região de memória `message`:
- `dev_write`: It is called whenever a write operation occurs on the driver. When this happens, the message passed in the write command from the userspace program is copied to the `message` memory region:
```c
static ssize_t dev_write(struct file *filep, const char *buffer,
Expand All @@ -364,50 +340,50 @@ static ssize_t dev_write(struct file *filep, const char *buffer,
...
```

- `dev_read`: é chamada quando acontece uma operação de leitura no driver, o módulo retorna a mensagem salva no buffer `message`:
- `dev_read`: It is called when a read operation occurs on the driver. The module returns the message saved in the `message` buffer:

```c
static ssize_t dev_read(struct file *filep, char *buffer,
size_t len, loff_t *offset){
int error_count = 0;
// copy_to_user has the format ( * to, *from, size) and returns 0 on success
// copy_to_user has the format ( *to, *from, size) and returns 0 on success
error_count = copy_to_user(buffer, message, size_of_message);
...
```
### Testando
### Testing
Para testar basta compilar o módulo e o programa de teste com o comando `make`, uma vez compilado você deve carregar o módulo (verificar se ele inicializou corretamente) e então executar o programa de teste.
To test, simply compile the module and the test program using the `make` command. Once compiled, you should load the module (and check if it initialized correctly) and then run the test program.
1. Em um terminal execute o comando `dmesg -wH`.
1. Em outro terminal execute: `make`
1. `sudo insmod ebbchar.ko`
1. Você deve obter o log a seguir no terminal do dmesg:
```
[12944.610531] EBBChar: Initializing the EBBChar LKM
[12944.610537] EBBChar: registered correctly with major number 236
[12944.610577] EBBChar: device class registered correctly
[12944.613972] EBBChar: device class created correctly
```
1. verificando se device foi inserido corretamente: `ls /dev/ebbchar` (deve ter esse arquivo)
1. agora vamos inicializar o programa `sudo ./test`
1. note que o dmesg indicou que alguém abriu o nosso driver:
1. In one terminal, execute the command `dmesg -wH`.
2. In another terminal, execute: `make`.
3. `sudo insmod ebbchar.ko`.
4. You should see the following log in the `dmesg` terminal:
```
[nov 3 13:07] EBBChar: Device has been opened 1 time(s)
[12944.610531] EBBChar: Initializing the EBBChar LKM
[12944.610537] EBBChar: registered correctly with major number 236
[12944.610577] EBBChar: device class registered correctly
[12944.613972] EBBChar: device class created correctly
```
1. agora no terminal que executou o programa test, escreva alguma coisa, você irá notar que a mesma informação será imprimida de volta:
```
Type in a short string to send to the kernel module:
123
Writing message to the device [123].
Reading from the device...
The received message is: [123]
```
1. No dmesg aparece a informação de quantos bytes o usuário digitou.
!!! info
1. Experimente você escrever uma mensagem grande no terminal do programa test, o que acontece?
1. Porque isso acontece?
5. Verify if the device was inserted correctly: `ls /dev/ebbchar` (you should see this file).
6. Now let's initialize the program: `sudo ./test`.
7. Note that `dmesg` indicates that someone has opened our driver:
```
[Nov 3 13:07] EBBChar: Device has been opened 1 time(s)
```
8. Now, in the terminal where you ran the test program, type something, and you will notice that the same information is printed back:
```
Type in a short string to send to the kernel module:
123
Writing message to the device [123].
Reading from the device...
The received message is: [123]
```
9. In `dmesg`, you can see the information about how many bytes the user entered.
!!! info
1. Try entering a large message in the test program's terminal. What happens?
2. Why do you think this happens?
3. Propose a solution!
Pronto! acabamos de criar nosso primeiro device driver, ele ainda não controla nenhum hardware, mas já implementamos a interface com o sistema operacional. Agora vem a parte que mais dominamos, controlar hardware (criar ponteiro, configurar e escrever).
There you go! We have just created our first device driver. It doesn't control any hardware yet, but we have implemented the interface with the operating system. Now comes the part we are most familiar with, controlling hardware (creating pointers, configuring, and writing).
49 changes: 26 additions & 23 deletions docs-src/Tutorial-HPS-kernel-module.md
Original file line number Diff line number Diff line change
@@ -1,20 +1,17 @@
# Kernel module
# Kernel Module

Nesse tutorial iremos trabalhar com o básico do desenvolvimento de módulos para o kernel do linux.
In this tutorial, we will work with the basics of developing modules for the Linux kernel. We will develop a kernel driver for our computer, since its easy and fast to develop and test.

## Simple module
## Simple Module

!!! tip
Antes de começar instale:
!!! exercise
Before starting, install:

```
apt-get install build-essential linux-headers-`uname -r`
```

!!! note
Trabalhe dentro de uma pasta chamada `simple_module`.

Crie um arquivo `simple.c` e inicialize com o código a seguir:
We will create a very simple driver that print "HELLO, WORLD" when initialized and "GOODBYE, WORLD" when removed from the kernel. The fallowing `.c` code does this:

```c
// simple.c
Expand All @@ -40,9 +37,12 @@ module_init(simple_init);
module_exit(simple_exit);
```
Pronto! Este é um módulo que pode ser lincado no kernel do Linux em tempo de execução e altera o seu funcionamento (na verdade não faz nada). Vamos entender algumas coisas:
!!! exercise
Create the file `simple_module/simple.c` with the previous content.
There you have it! This is a module that can be linked into the Linux kernel at runtime and alters its operation (actually does nothing). Let's understand a few things:
- Todo módulo deve ter uma função de inicialização e saída, essas funções podem ter qualquer nome, mas devem ser informadas ao kernel pelas macros `module_init()` e `module_exit()`.
- Every module should have an initialization and exit function, these functions can have any name, but must be informed to the kernel by the `module_init()` and `module_exit()` macros.
!!! info "kernel doc"
`__initcall()/module_init() include/linux/init.h`
Expand All @@ -55,14 +55,14 @@ Pronto! Este é um módulo que pode ser lincado no kernel do Linux em tempo de e
> ref: https://www.kernel.org/doc/htmldocs/kernel-hacking/routines-init-again.html
- `printk`: É uma das funções mais conhecidas no kernel do Linux, usada para criar logs e rastrear bugs. A saída desse print não é no terminal como o printf, mas sim no `demesg`.
- `printk`: It is one of the most well-known functions in the Linux kernel, used to create logs and track bugs. The output of this print is not on the terminal like printf, but in `dmesg`.
!!! info "kernel doc"
Para mais informações acesse:
For more information, visit:
- https://www.kernel.org/doc/html/latest/core-api/printk-basics.html
Agora precisamos compilar esse módulo para um `.ko`, para isso crie um arquivo `Makefile`:
Now we need to compile this module into a `.ko`, to do this we will use this `Makefile`:
```make
// Makefile
Expand All @@ -75,33 +75,36 @@ clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
```

### compilando e testando
!!! exercise
Create a `Makefile` with the previous content.

Agora você pode compilar o módulo com o comando `make`, uma vez feito isso o arquivo `simple.ko` deve ter sido gerado na pasta do projeto. Esse arquivo é o módulo compilado e que iremos linkar no kernel do linux usando o comando:
### Compiling and Testing

```bash
$ sudo insmod simple.ko
```
Now you can compile the module with the `make` command, once done, the `simple.ko` file should have been generated in the project folder. This file is the compiled module and we will link into the Linux kernel with `insmd`.

Isso fará com que o módulo faça parte do kernel, para verificarmos se funcionou podemos listar os módulos em execução com o comando `lsmod`:
!!! exercise
1. Compile with: `make`
2. Insert in kernel: `sudo insmod simple.ko`

This will make the module part of the kernel, to verify if it worked we can list the running modules with the `lsmod` command:

```bash
$ lsmod | grep simple
```

Para termos acesso ao log (mensagem de HELLO), basta acessarmos o `dmesg`:
To access the log (HELLO message), just access `dmesg`:

```bash
$ dmesg | tail
```

Para remover o módulo usamos o comando `rmmod`:
To remove the module we use the `rmmod` command:

```bash
$ sudo rmmod simple
```

Então devemos ver a mensagem de Goodbye no `demesg`:
Then we should see the Goodbye message in `dmesg`:

```bash
$ dmesg | tail
Expand Down
Loading

0 comments on commit c70f916

Please sign in to comment.