e1000e.rs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  1. // 参考手册: PCIe* GbE Controllers Open Source Software Developer’s Manual
  2. // Refernce: PCIe* GbE Controllers Open Source Software Developer’s Manual
  3. use alloc::vec::Vec;
  4. use core::intrinsics::unlikely;
  5. use core::mem::size_of;
  6. use core::ptr::NonNull;
  7. use core::slice::{from_raw_parts, from_raw_parts_mut};
  8. use core::sync::atomic::{compiler_fence, Ordering};
  9. use super::e1000e_driver::e1000e_driver_init;
  10. use crate::driver::net::dma::{dma_alloc, dma_dealloc};
  11. use crate::driver::pci::pci::{
  12. get_pci_device_structure_mut, PciDeviceStructure, PciDeviceStructureGeneralDevice, PciError,
  13. PCI_DEVICE_LINKEDLIST,
  14. };
  15. use crate::driver::pci::pci_irq::{IrqCommonMsg, IrqMsg, IrqSpecificMsg, PciInterrupt, IRQ};
  16. use crate::include::bindings::bindings::pt_regs;
  17. use crate::libs::volatile::{ReadOnly, Volatile, WriteOnly};
  18. use crate::net::net_core::poll_ifaces_try_lock_onetime;
  19. use crate::{kdebug, kinfo};
  20. const PAGE_SIZE: usize = 4096;
  21. const NETWORK_CLASS: u8 = 0x2;
  22. const ETHERNET_SUBCLASS: u8 = 0x0;
  23. // e1000e系列网卡的device id列表,来源:https://admin.pci-ids.ucw.cz/read/PC/8086
  24. const E1000E_DEVICE_ID: [u16; 14] = [
  25. 0x10d3, // 8574L, qemu default
  26. 0x10cc, // 82567LM-2
  27. 0x10cd, // 82567LF-2
  28. 0x105f, // 82571EB
  29. 0x1060, // 82571EB
  30. 0x107f, // 82572EI
  31. 0x109a, // 82573L
  32. 0x10ea, // 82577LM
  33. 0x10eb, // 82577LC
  34. 0x10ef, // 82578DM
  35. 0x10f0, // 82578DC
  36. 0x1502, // 82579LM
  37. 0x1503, // 82579V
  38. 0x150c, // 82583V
  39. ];
  40. // e1000e网卡与BAR有关的常量
  41. // BAR0空间大小(128KB)
  42. const E1000E_BAR_REG_SIZE: u32 = 128 * 1024;
  43. // BAR0空间对齐(64bit)
  44. #[allow(dead_code)]
  45. const E1000E_BAR_REG_ALIGN: u8 = 64;
  46. // 单个寄存器大小(32bit, 4字节)
  47. #[allow(dead_code)]
  48. const E1000E_REG_SIZE: u8 = 4;
  49. // TxBuffer和RxBuffer的大小(DMA页)
  50. const E1000E_DMA_PAGES: usize = 1;
  51. // 中断相关
  52. const E1000E_RECV_VECTOR: u16 = 57;
  53. // napi队列中暂时存储的buffer个数
  54. const E1000E_RECV_NAPI: usize = 1024;
  55. // 收/发包的描述符结构 pp.24 Table 3-1
  56. #[repr(C)]
  57. #[derive(Copy, Clone, Debug)]
  58. struct E1000ETransDesc {
  59. addr: u64,
  60. len: u16,
  61. cso: u8,
  62. cmd: u8,
  63. status: u8,
  64. css: u8,
  65. special: u8,
  66. }
  67. // pp.54 Table 3-12
  68. #[repr(C)]
  69. #[derive(Copy, Clone, Debug)]
  70. struct E1000ERecvDesc {
  71. addr: u64,
  72. len: u16,
  73. chksum: u16,
  74. status: u16,
  75. error: u8,
  76. special: u8,
  77. }
  78. #[derive(Copy, Clone)]
  79. // Buffer的Copy只是指针操作,不涉及实际数据的复制,因此要小心使用,确保不同的buffer不会使用同一块内存
  80. pub struct E1000EBuffer {
  81. buffer: NonNull<u8>,
  82. paddr: usize,
  83. // length字段为0则表示这个buffer是一个占位符,不指向实际内存
  84. // the buffer is empty and no page is allocated if length field is set 0
  85. length: usize,
  86. }
  87. impl E1000EBuffer {
  88. pub fn new(length: usize) -> Self {
  89. assert!(length <= PAGE_SIZE);
  90. if unlikely(length == 0) {
  91. // 在某些情况下,我们并不需要实际分配buffer,只需要提供一个占位符即可
  92. // we dont need to allocate dma pages for buffer in some cases
  93. E1000EBuffer {
  94. buffer: NonNull::dangling(),
  95. paddr: 0,
  96. length: 0,
  97. }
  98. } else {
  99. let (paddr, vaddr) = dma_alloc(E1000E_DMA_PAGES);
  100. E1000EBuffer {
  101. buffer: vaddr,
  102. paddr,
  103. length,
  104. }
  105. }
  106. }
  107. #[allow(dead_code)]
  108. pub fn as_addr(&self) -> NonNull<u8> {
  109. assert!(self.length != 0);
  110. return self.buffer;
  111. }
  112. #[allow(dead_code)]
  113. pub fn as_addr_u64(&self) -> u64 {
  114. assert!(self.length != 0);
  115. return self.buffer.as_ptr() as u64;
  116. }
  117. pub fn as_paddr(&self) -> usize {
  118. assert!(self.length != 0);
  119. return self.paddr;
  120. }
  121. #[allow(dead_code)]
  122. pub fn as_slice(&self) -> &[u8] {
  123. assert!(self.length != 0);
  124. return unsafe { from_raw_parts(self.buffer.as_ptr(), self.length) };
  125. }
  126. pub fn as_mut_slice(&mut self) -> &mut [u8] {
  127. assert!(self.length != 0);
  128. return unsafe { from_raw_parts_mut(self.buffer.as_ptr(), self.length) };
  129. }
  130. pub fn set_length(&mut self, length: usize) {
  131. self.length = length;
  132. }
  133. pub fn len(&self) -> usize {
  134. return self.length;
  135. }
  136. // 释放buffer内部的dma_pages,需要小心使用
  137. pub fn free_buffer(self) -> () {
  138. if self.length != 0 {
  139. unsafe { dma_dealloc(self.paddr, self.buffer, E1000E_DMA_PAGES) };
  140. }
  141. }
  142. }
  143. // 中断处理函数, 调用协议栈的poll函数,未来可能会用napi来替换这里
  144. // Interrupt handler
  145. unsafe extern "C" fn e1000e_irq_handler(_irq_num: u64, _irq_paramer: u64, _regs: *mut pt_regs) {
  146. poll_ifaces_try_lock_onetime().ok();
  147. }
  148. #[allow(dead_code)]
  149. pub struct E1000EDevice {
  150. // 设备寄存器
  151. // device registers
  152. general_regs: NonNull<GeneralRegs>,
  153. interrupt_regs: NonNull<InterruptRegs>,
  154. rctl_regs: NonNull<ReceiveCtrlRegs>,
  155. receive_regs: NonNull<ReceiveRegs>,
  156. tctl_regs: NonNull<TransmitCtrlRegs>,
  157. transimit_regs: NonNull<TransimitRegs>,
  158. pcie_regs: NonNull<PCIeRegs>,
  159. // descriptor环形队列,在操作系统与设备之间共享
  160. // descriptor rings are shared between os and device
  161. recv_desc_ring: &'static mut [E1000ERecvDesc],
  162. trans_desc_ring: &'static mut [E1000ETransDesc],
  163. recv_ring_pa: usize,
  164. trans_ring_pa: usize,
  165. // 设备收/发包缓冲区数组
  166. // buffers of receive/transmit packets
  167. recv_buffers: Vec<E1000EBuffer>,
  168. trans_buffers: Vec<E1000EBuffer>,
  169. mac: [u8; 6],
  170. first_trans: bool,
  171. // napi队列,用于存放在中断关闭期间通过轮询收取的buffer
  172. // the napi queue is designed to save buffer/packet when the interrupt is close
  173. // NOTE: this feature is not completely implemented and not used in the current version
  174. napi_buffers: Vec<E1000EBuffer>,
  175. napi_buffer_head: usize,
  176. napi_buffer_tail: usize,
  177. napi_buffer_empty: bool,
  178. }
  179. impl E1000EDevice {
  180. // 从PCI标准设备进行驱动初始化
  181. // init the device for PCI standard device struct
  182. #[allow(unused_assignments)]
  183. pub fn new(device: &mut PciDeviceStructureGeneralDevice) -> Result<Self, E1000EPciError> {
  184. // 从BAR0获取我们需要的寄存器
  185. // Build registers sturcts from BAR0
  186. device.bar_ioremap().unwrap()?;
  187. device.enable_master();
  188. let bar = device.bar().ok_or(E1000EPciError::BarGetFailed)?;
  189. let bar0 = bar.get_bar(0)?;
  190. let (address, size) = bar0
  191. .memory_address_size()
  192. .ok_or(E1000EPciError::UnexpectedBarType)?;
  193. if address == 0 {
  194. return Err(E1000EPciError::BarNotAllocated);
  195. }
  196. if size != E1000E_BAR_REG_SIZE {
  197. return Err(E1000EPciError::UnexpectedBarSize);
  198. }
  199. let vaddress = bar0
  200. .virtual_address()
  201. .ok_or(E1000EPciError::BarGetVaddrFailed)?
  202. .data() as u64;
  203. // 初始化msi中断
  204. // initialize msi interupt
  205. let irq_vector = device.irq_vector_mut().unwrap();
  206. irq_vector.push(E1000E_RECV_VECTOR);
  207. device.irq_init(IRQ::PCI_IRQ_MSI).expect("IRQ Init Failed");
  208. let msg = IrqMsg {
  209. irq_common_message: IrqCommonMsg::init_from(
  210. 0,
  211. "E1000E_RECV_IRQ",
  212. 0,
  213. e1000e_irq_handler,
  214. None,
  215. ),
  216. irq_specific_message: IrqSpecificMsg::msi_default(),
  217. };
  218. device.irq_install(msg)?;
  219. device.irq_enable(true)?;
  220. let general_regs: NonNull<GeneralRegs> =
  221. get_register_ptr(vaddress, E1000E_GENERAL_REGS_OFFSET);
  222. let interrupt_regs: NonNull<InterruptRegs> =
  223. get_register_ptr(vaddress, E1000E_INTERRRUPT_REGS_OFFSET);
  224. let rctl_regs: NonNull<ReceiveCtrlRegs> =
  225. get_register_ptr(vaddress, E1000E_RECEIVE_CTRL_REG_OFFSET);
  226. let receive_regs: NonNull<ReceiveRegs> =
  227. get_register_ptr(vaddress, E1000E_RECEIVE_REGS_OFFSET);
  228. let tctl_regs: NonNull<TransmitCtrlRegs> =
  229. get_register_ptr(vaddress, E1000E_TRANSMIT_CTRL_REG_OFFSET);
  230. let transimit_regs: NonNull<TransimitRegs> =
  231. get_register_ptr(vaddress, E1000E_TRANSMIT_REGS_OFFSET);
  232. let pcie_regs: NonNull<PCIeRegs> = get_register_ptr(vaddress, E1000E_PCIE_REGS_OFFSET);
  233. let ra_regs: NonNull<ReceiveAddressRegs> =
  234. get_register_ptr(vaddress, E1000E_RECEIVE_ADDRESS_REGS_OFFSET);
  235. // 开始设备初始化 14.3
  236. // Initialization Sequence
  237. unsafe {
  238. let mut ctrl = volread!(general_regs, ctrl);
  239. // 关闭中断
  240. // close the interrupt
  241. volwrite!(interrupt_regs, imc, E1000E_IMC_CLEAR);
  242. //SW RESET
  243. volwrite!(general_regs, ctrl, ctrl | E1000E_CTRL_RST);
  244. compiler_fence(Ordering::AcqRel);
  245. // PHY RESET
  246. ctrl = volread!(general_regs, ctrl);
  247. volwrite!(general_regs, ctrl, ctrl | E1000E_CTRL_PHY_RST);
  248. volwrite!(general_regs, ctrl, ctrl);
  249. // 关闭中断
  250. // close the interrupt
  251. volwrite!(interrupt_regs, imc, E1000E_IMC_CLEAR);
  252. let mut gcr = volread!(pcie_regs, gcr);
  253. gcr = gcr | (1 << 22);
  254. volwrite!(pcie_regs, gcr, gcr);
  255. compiler_fence(Ordering::AcqRel);
  256. // PHY Initialization 14.8.1
  257. // MAC/PHY Link Setup 14.8.2
  258. ctrl = volread!(general_regs, ctrl);
  259. ctrl &= !(E1000E_CTRL_FRCSPD | E1000E_CTRL_FRCDPLX);
  260. volwrite!(general_regs, ctrl, ctrl | E1000E_CTRL_SLU);
  261. }
  262. let status = unsafe { volread!(general_regs, status) };
  263. kdebug!("Status: {status:#X}");
  264. // 读取设备的mac地址
  265. // Read mac address
  266. let ral = unsafe { volread!(ra_regs, ral0) };
  267. let rah = unsafe { volread!(ra_regs, rah0) };
  268. let mac: [u8; 6] = [
  269. ((ral >> 0) & 0xFF) as u8,
  270. ((ral >> 8) & 0xFF) as u8,
  271. ((ral >> 16) & 0xFF) as u8,
  272. ((ral >> 24) & 0xFF) as u8,
  273. ((rah >> 0) & 0xFF) as u8,
  274. ((rah >> 8) & 0xFF) as u8,
  275. ];
  276. // 初始化receive和transimit descriptor环形队列
  277. // initialize receive and transimit desciptor ring
  278. let (recv_ring_pa, recv_ring_va) = dma_alloc(E1000E_DMA_PAGES);
  279. let (trans_ring_pa, trans_ring_va) = dma_alloc(E1000E_DMA_PAGES);
  280. let recv_ring_length = PAGE_SIZE / size_of::<E1000ERecvDesc>();
  281. let trans_ring_length = PAGE_SIZE / size_of::<E1000ETransDesc>();
  282. let recv_desc_ring = unsafe {
  283. from_raw_parts_mut::<E1000ERecvDesc>(recv_ring_va.as_ptr().cast(), recv_ring_length)
  284. };
  285. let trans_desc_ring = unsafe {
  286. from_raw_parts_mut::<E1000ETransDesc>(trans_ring_va.as_ptr().cast(), trans_ring_length)
  287. };
  288. // 初始化receive和transmit packet的缓冲区
  289. // initialzie receive and transmit buffers
  290. let mut recv_buffers: Vec<E1000EBuffer> = Vec::with_capacity(recv_ring_length);
  291. let mut trans_buffers: Vec<E1000EBuffer> = Vec::with_capacity(trans_ring_length);
  292. // 初始化缓冲区与descriptor,descriptor 中的addr字典应当指向buffer的物理地址
  293. // Receive buffers of appropriate size should be allocated and pointers to these buffers should be stored in the descriptor ring.
  294. for i in 0..recv_ring_length {
  295. let buffer = E1000EBuffer::new(PAGE_SIZE);
  296. recv_desc_ring[i].addr = buffer.as_paddr() as u64;
  297. recv_desc_ring[i].status = 0;
  298. recv_buffers.push(buffer);
  299. }
  300. // Same as receive buffers
  301. for i in 0..trans_ring_length {
  302. let buffer = E1000EBuffer::new(PAGE_SIZE);
  303. trans_desc_ring[i].addr = buffer.as_paddr() as u64;
  304. trans_desc_ring[i].status = 1;
  305. trans_buffers.push(buffer);
  306. }
  307. // Receive Initialization 14.6
  308. // Initialzie mutlicast table array to 0b
  309. // 初始化MTA,遍历0x05200-0x053FC中每个寄存器,写入0b,一共128个寄存器
  310. let mut mta_adress = vaddress + E1000E_MTA_REGS_START_OFFSET;
  311. while mta_adress != vaddress + E1000E_MTA_REGS_END_OFFSET {
  312. let mta: NonNull<MTARegs> = get_register_ptr(mta_adress, 0);
  313. unsafe { volwrite!(mta, mta, 0) };
  314. mta_adress = mta_adress + 4;
  315. }
  316. // 连续的寄存器读-写操作,放在同一个unsafe块中
  317. unsafe {
  318. // 设置descriptor环形队列的基地址
  319. // Program the descriptor base address with the address of the region.
  320. volwrite!(receive_regs, rdbal0, (recv_ring_pa) as u32);
  321. volwrite!(receive_regs, rdbah0, (recv_ring_pa >> 32) as u32);
  322. // 设置descriptor环形队列的长度
  323. // Set the length register to the size of the descriptor ring.
  324. volwrite!(receive_regs, rdlen0, PAGE_SIZE as u32);
  325. // 设置队列的首尾指针
  326. // Program the head and tail registers
  327. volwrite!(receive_regs, rdh0, 0);
  328. volwrite!(receive_regs, rdt0, (recv_ring_length - 1) as u32);
  329. // 设置控制寄存器的相关功能 14.6.1
  330. // Set the receive control register
  331. volwrite!(
  332. rctl_regs,
  333. rctl,
  334. E1000E_RCTL_EN
  335. | E1000E_RCTL_BAM
  336. | E1000E_RCTL_BSIZE_4K
  337. | E1000E_RCTL_BSEX
  338. | E1000E_RCTL_SECRC
  339. );
  340. // Transmit Initialization 14.7
  341. // 开启发包descriptor的回写功能
  342. // Program the TXDCTL register with the desired TX descriptor write-back policy
  343. volwrite!(
  344. transimit_regs,
  345. txdctl,
  346. E1000E_TXDCTL_WTHRESH | E1000E_TXDCTL_GRAN
  347. );
  348. // 设置descriptor环形队列的基地址,长度与首尾指针
  349. // Program the descriptor base address with the address of the region
  350. volwrite!(transimit_regs, tdbal0, trans_ring_pa as u32);
  351. volwrite!(transimit_regs, tdbah0, (trans_ring_pa >> 32) as u32);
  352. // Set the length register to the size of the descriptor ring.
  353. volwrite!(transimit_regs, tdlen0, PAGE_SIZE as u32);
  354. // Program the head and tail registerss
  355. volwrite!(transimit_regs, tdh0, 0);
  356. volwrite!(transimit_regs, tdt0, 0);
  357. // Program the TIPG register
  358. volwrite!(
  359. tctl_regs,
  360. tipg,
  361. E1000E_TIPG_IPGT | E1000E_TIPG_IPGR1 | E1000E_TIPG_IPGR2
  362. );
  363. // Program the TCTL register.
  364. volwrite!(
  365. tctl_regs,
  366. tctl,
  367. E1000E_TCTL_EN | E1000E_TCTL_PSP | E1000E_TCTL_CT_VAL | E1000E_TCTL_COLD_VAL
  368. );
  369. let icr = volread!(interrupt_regs, icr);
  370. volwrite!(interrupt_regs, icr, icr);
  371. // 开启收包相关的中断
  372. // Enable receive interrupts
  373. let mut ims = volread!(interrupt_regs, ims);
  374. ims = E1000E_IMS_LSC | E1000E_IMS_RXT0 | E1000E_IMS_RXDMT0 | E1000E_IMS_OTHER;
  375. volwrite!(interrupt_regs, ims, ims);
  376. }
  377. return Ok(E1000EDevice {
  378. general_regs,
  379. interrupt_regs,
  380. rctl_regs,
  381. receive_regs,
  382. tctl_regs,
  383. transimit_regs,
  384. pcie_regs,
  385. recv_desc_ring,
  386. trans_desc_ring,
  387. recv_ring_pa,
  388. trans_ring_pa,
  389. recv_buffers,
  390. trans_buffers,
  391. mac,
  392. first_trans: true,
  393. napi_buffers: vec![E1000EBuffer::new(0); E1000E_RECV_NAPI],
  394. napi_buffer_head: 0,
  395. napi_buffer_tail: 0,
  396. napi_buffer_empty: true,
  397. });
  398. }
  399. pub fn e1000e_receive(&mut self) -> Option<E1000EBuffer> {
  400. self.e1000e_intr();
  401. let mut rdt = unsafe { volread!(self.receive_regs, rdt0) } as usize;
  402. let index = (rdt + 1) % self.recv_desc_ring.len();
  403. let desc = &mut self.recv_desc_ring[index];
  404. if (desc.status & E1000E_RXD_STATUS_DD) == 0 {
  405. return None;
  406. }
  407. let mut buffer = self.recv_buffers[index];
  408. let new_buffer = E1000EBuffer::new(PAGE_SIZE);
  409. self.recv_buffers[index] = new_buffer;
  410. desc.addr = new_buffer.as_paddr() as u64;
  411. buffer.set_length(desc.len as usize);
  412. rdt = index;
  413. unsafe { volwrite!(self.receive_regs, rdt0, rdt as u32) };
  414. // kdebug!("e1000e: receive packet");
  415. return Some(buffer);
  416. }
  417. pub fn e1000e_can_transmit(&self) -> bool {
  418. let tdt = unsafe { volread!(self.transimit_regs, tdt0) } as usize;
  419. let index = tdt % self.trans_desc_ring.len();
  420. let desc = &self.trans_desc_ring[index];
  421. if (desc.status & E1000E_TXD_STATUS_DD) == 0 {
  422. return false;
  423. }
  424. true
  425. }
  426. pub fn e1000e_transmit(&mut self, packet: E1000EBuffer) {
  427. let mut tdt = unsafe { volread!(self.transimit_regs, tdt0) } as usize;
  428. let index = tdt % self.trans_desc_ring.len();
  429. let desc = &mut self.trans_desc_ring[index];
  430. let buffer = self.trans_buffers[index];
  431. self.trans_buffers[index] = packet;
  432. // recycle unused transmit buffer
  433. buffer.free_buffer();
  434. // Set the transmit descriptor
  435. desc.addr = packet.as_paddr() as u64;
  436. desc.len = packet.len() as u16;
  437. desc.status = 0;
  438. desc.cmd = E1000E_TXD_CMD_EOP | E1000E_TXD_CMD_RS | E1000E_TXD_CMD_IFCS;
  439. tdt = (tdt + 1) % self.trans_desc_ring.len();
  440. unsafe { volwrite!(self.transimit_regs, tdt0, tdt as u32) };
  441. self.first_trans = false;
  442. }
  443. pub fn mac_address(&self) -> [u8; 6] {
  444. return self.mac;
  445. }
  446. // 向ICR寄存器中的某一bit写入1b表示该中断已经被接收,同时会清空该位
  447. // we need to clear ICR to tell e1000e we have read the interrupt
  448. pub fn e1000e_intr(&mut self) {
  449. let icr = unsafe { volread!(self.interrupt_regs, icr) };
  450. // write 1b to any bit in ICR will clear the bit
  451. unsafe { volwrite!(self.interrupt_regs, icr, icr) };
  452. }
  453. // 切换是否接受分组到达的中断
  454. // change whether the receive timer interrupt is enabled
  455. // Note: this method is not completely implemented and not used in the current version
  456. #[allow(dead_code)]
  457. pub fn e1000e_intr_set(&mut self, state: bool) {
  458. let mut ims = unsafe { volread!(self.interrupt_regs, ims) };
  459. match state {
  460. true => ims = ims | E1000E_IMS_RXT0,
  461. false => ims = ims & !E1000E_IMS_RXT0,
  462. }
  463. unsafe { volwrite!(self.interrupt_regs, ims, ims) };
  464. }
  465. // 实现了一部分napi机制的收包函数, 现在还没有投入使用
  466. // This method is a partial implementation of napi (New API) techniques
  467. // Note: this method is not completely implemented and not used in the current version
  468. #[allow(dead_code)]
  469. pub fn e1000e_receive2(&mut self) -> Option<E1000EBuffer> {
  470. // 向设备表明我们已经接受到了之前的中断
  471. // Tell e1000e we have received the interrupt
  472. self.e1000e_intr();
  473. // 如果napi队列不存在已经收到的分组...
  474. // if napi queue is empty...
  475. if self.napi_buffer_empty {
  476. // 暂时关闭设备中断
  477. // close interrupt
  478. self.e1000e_intr_set(false);
  479. loop {
  480. if self.napi_buffer_tail == self.napi_buffer_head && self.napi_buffer_empty == false
  481. {
  482. // napi缓冲队列已满,停止收包
  483. // napi queue is full, stop
  484. break;
  485. }
  486. match self.e1000e_receive() {
  487. Some(buffer) => {
  488. self.napi_buffers[self.napi_buffer_tail] = buffer;
  489. self.napi_buffer_tail = (self.napi_buffer_tail + 1) % E1000E_RECV_NAPI;
  490. self.napi_buffer_empty = false;
  491. }
  492. None => {
  493. // 设备队列中没有剩余的已到达的数据包
  494. // no packet remains in the device buffer
  495. break;
  496. }
  497. };
  498. }
  499. // 重新打开设备中断
  500. // open the interrupt
  501. self.e1000e_intr_set(true);
  502. }
  503. let result = self.napi_buffers[self.napi_buffer_head];
  504. match result.len() {
  505. 0 => {
  506. // napi队列和网卡队列中都不存在数据包
  507. // both napi queue and device buffer is empty, no packet will receive
  508. return None;
  509. }
  510. _ => {
  511. // 有剩余的已到达的数据包
  512. // there is packet in napi queue
  513. self.napi_buffer_head = (self.napi_buffer_head + 1) % E1000E_RECV_NAPI;
  514. if self.napi_buffer_head == self.napi_buffer_tail {
  515. self.napi_buffer_empty = true;
  516. }
  517. return Some(result);
  518. }
  519. }
  520. }
  521. }
  522. impl Drop for E1000EDevice {
  523. fn drop(&mut self) {
  524. // 释放已分配的所有dma页
  525. // free all dma pages we have allocated
  526. kdebug!("droping...");
  527. let recv_ring_length = PAGE_SIZE / size_of::<E1000ERecvDesc>();
  528. let trans_ring_length = PAGE_SIZE / size_of::<E1000ETransDesc>();
  529. unsafe {
  530. // 释放所有buffer中的dma页
  531. // free all dma pages in buffers
  532. for i in 0..recv_ring_length {
  533. self.recv_buffers[i].free_buffer();
  534. }
  535. for i in 0..trans_ring_length {
  536. self.trans_buffers[i].free_buffer();
  537. }
  538. // 释放descriptor ring
  539. // free descriptor ring
  540. dma_dealloc(
  541. self.recv_ring_pa,
  542. NonNull::new(self.recv_desc_ring).unwrap().cast(),
  543. E1000E_DMA_PAGES,
  544. );
  545. dma_dealloc(
  546. self.trans_ring_pa,
  547. NonNull::new(self.trans_desc_ring).unwrap().cast(),
  548. E1000E_DMA_PAGES,
  549. );
  550. }
  551. }
  552. }
  553. #[no_mangle]
  554. pub extern "C" fn rs_e1000e_init() {
  555. e1000e_init();
  556. }
  557. pub fn e1000e_init() -> () {
  558. match e1000e_probe() {
  559. Ok(_code) => kinfo!("Successfully init e1000e device!"),
  560. Err(_error) => kinfo!("Error occurred!"),
  561. }
  562. }
  563. pub fn e1000e_probe() -> Result<u64, E1000EPciError> {
  564. let mut list = PCI_DEVICE_LINKEDLIST.write();
  565. let result = get_pci_device_structure_mut(&mut list, NETWORK_CLASS, ETHERNET_SUBCLASS);
  566. if result.is_empty() {
  567. return Ok(0);
  568. }
  569. for device in result {
  570. let standard_device = device.as_standard_device_mut().unwrap();
  571. let header = &standard_device.common_header;
  572. if header.vendor_id == 0x8086 {
  573. // intel
  574. if E1000E_DEVICE_ID.contains(&header.device_id) {
  575. kdebug!(
  576. "Detected e1000e PCI device with device id {:#x}",
  577. header.device_id
  578. );
  579. let e1000e = E1000EDevice::new(standard_device)?;
  580. e1000e_driver_init(e1000e);
  581. }
  582. }
  583. }
  584. return Ok(1);
  585. }
  586. // 用到的e1000e寄存器结构体
  587. // pp.275, Table 13-3
  588. // 设备通用寄存器
  589. #[allow(dead_code)]
  590. struct GeneralRegs {
  591. ctrl: Volatile<u32>, //0x00000
  592. ctrl_alias: Volatile<u32>, //0x00004
  593. status: ReadOnly<u32>, //0x00008
  594. status_align: ReadOnly<u32>, //0x0000c
  595. eec: Volatile<u32>, //0x00010
  596. eerd: Volatile<u32>, //0x00014
  597. ctrl_ext: Volatile<u32>, //0x00018
  598. fla: Volatile<u32>, //0x0001c
  599. mdic: Volatile<u32>, //0x00020
  600. }
  601. // 中断控制
  602. #[allow(dead_code)]
  603. struct InterruptRegs {
  604. icr: Volatile<u32>, //0x000c0 ICR寄存器应当为只读寄存器,但我们需要向其中写入来清除对应位
  605. itr: Volatile<u32>, //0x000c4
  606. ics: WriteOnly<u32>, //0x000c8
  607. ics_align: ReadOnly<u32>, //0x000cc
  608. ims: Volatile<u32>, //0x000d0
  609. ims_align: ReadOnly<u32>, //0x000d4
  610. imc: WriteOnly<u32>, //0x000d8
  611. }
  612. // 收包功能控制
  613. struct ReceiveCtrlRegs {
  614. rctl: Volatile<u32>, //0x00100
  615. }
  616. // 发包功能控制
  617. #[allow(dead_code)]
  618. struct TransmitCtrlRegs {
  619. tctl: Volatile<u32>, //0x00400
  620. tctl_ext: Volatile<u32>, //0x00404
  621. unused_1: ReadOnly<u32>, //0x00408
  622. unused_2: ReadOnly<u32>, //0x0040c
  623. tipg: Volatile<u32>, //0x00410
  624. }
  625. // 收包功能相关
  626. #[allow(dead_code)]
  627. struct ReceiveRegs {
  628. rdbal0: Volatile<u32>, //0x02800
  629. rdbah0: Volatile<u32>, //0x02804
  630. rdlen0: Volatile<u32>, //0x02808
  631. rdl_align: ReadOnly<u32>, //0x0280c
  632. rdh0: Volatile<u32>, //0x02810
  633. rdh_align: ReadOnly<u32>, //0x02814
  634. rdt0: Volatile<u32>, //0x02818
  635. rdt_align: ReadOnly<u32>, //0x281c
  636. rdtr: Volatile<u32>, //0x2820
  637. rdtr_align: ReadOnly<u32>, //0x2824
  638. rxdctl: Volatile<u32>, //0x2828
  639. }
  640. // 发包功能相关
  641. #[allow(dead_code)]
  642. struct TransimitRegs {
  643. tdbal0: Volatile<u32>, //0x03800
  644. tdbah0: Volatile<u32>, //0x03804
  645. tdlen0: Volatile<u32>, //0x03808
  646. tdlen_algin: ReadOnly<u32>, //0x0380c
  647. tdh0: Volatile<u32>, //0x03810
  648. tdh_align: ReadOnly<u32>, //0x03814
  649. tdt0: Volatile<u32>, //0x03818
  650. tdt_align: ReadOnly<u32>, //0x0381c
  651. tidv: Volatile<u32>, //0x03820
  652. tidv_align: ReadOnly<u32>, //0x03824
  653. txdctl: Volatile<u32>, //0x03828
  654. tadv: Volatile<u32>, //0x0382c
  655. }
  656. // mac地址
  657. struct ReceiveAddressRegs {
  658. ral0: Volatile<u32>, //0x05400
  659. rah0: Volatile<u32>, //0x05404
  660. }
  661. // PCIe 通用控制
  662. struct PCIeRegs {
  663. gcr: Volatile<u32>, //0x05b00
  664. }
  665. #[allow(dead_code)]
  666. struct StatisticsRegs {}
  667. // 0x05200-0x053fc
  668. // 在Receive Initialization 中按照每次一个32bit寄存器的方式来遍历
  669. // Multicast Table Array Registers will be written per 32bit
  670. struct MTARegs {
  671. mta: Volatile<u32>,
  672. }
  673. const E1000E_GENERAL_REGS_OFFSET: u64 = 0x00000;
  674. const E1000E_INTERRRUPT_REGS_OFFSET: u64 = 0x000c0;
  675. const E1000E_RECEIVE_CTRL_REG_OFFSET: u64 = 0x00100;
  676. const E1000E_RECEIVE_REGS_OFFSET: u64 = 0x02800;
  677. const E1000E_TRANSMIT_CTRL_REG_OFFSET: u64 = 0x00400;
  678. const E1000E_TRANSMIT_REGS_OFFSET: u64 = 0x03800;
  679. const E1000E_RECEIVE_ADDRESS_REGS_OFFSET: u64 = 0x05400;
  680. const E1000E_PCIE_REGS_OFFSET: u64 = 0x05b00;
  681. const E1000E_MTA_REGS_START_OFFSET: u64 = 0x05200;
  682. const E1000E_MTA_REGS_END_OFFSET: u64 = 0x053fc;
  683. // 寄存器的特定位
  684. //CTRL
  685. const E1000E_CTRL_SLU: u32 = 1 << 6;
  686. const E1000E_CTRL_FRCSPD: u32 = 1 << 11;
  687. const E1000E_CTRL_FRCDPLX: u32 = 1 << 12;
  688. const E1000E_CTRL_RST: u32 = 1 << 26;
  689. #[allow(dead_code)]
  690. const E1000E_CTRL_RFCE: u32 = 1 << 27;
  691. #[allow(dead_code)]
  692. const E1000E_CTRL_TFCE: u32 = 1 << 28;
  693. const E1000E_CTRL_PHY_RST: u32 = 1 << 31;
  694. // IMS
  695. const E1000E_IMS_LSC: u32 = 1 << 2;
  696. const E1000E_IMS_RXDMT0: u32 = 1 << 4;
  697. #[allow(dead_code)]
  698. const E1000E_IMS_RXO: u32 = 1 << 6;
  699. const E1000E_IMS_RXT0: u32 = 1 << 7;
  700. #[allow(dead_code)]
  701. const E1000E_IMS_RXQ0: u32 = 1 << 20;
  702. const E1000E_IMS_OTHER: u32 = 1 << 24; // qemu use this bit to set msi-x interrupt
  703. // IMC
  704. const E1000E_IMC_CLEAR: u32 = 0xffffffff;
  705. // RCTL
  706. const E1000E_RCTL_EN: u32 = 1 << 1;
  707. const E1000E_RCTL_BAM: u32 = 1 << 15;
  708. const E1000E_RCTL_BSIZE_4K: u32 = 3 << 16;
  709. const E1000E_RCTL_BSEX: u32 = 1 << 25;
  710. const E1000E_RCTL_SECRC: u32 = 1 << 26;
  711. // TCTL
  712. const E1000E_TCTL_EN: u32 = 1 << 1;
  713. const E1000E_TCTL_PSP: u32 = 1 << 3;
  714. const E1000E_TCTL_CT_VAL: u32 = 0x0f << 4; // suggested 16d collision, 手册建议值:16d
  715. const E1000E_TCTL_COLD_VAL: u32 = 0x03f << 12; // suggested 64 byte time for Full-Duplex, 手册建议值:64
  716. // TXDCTL
  717. const E1000E_TXDCTL_WTHRESH: u32 = 1 << 16;
  718. const E1000E_TXDCTL_GRAN: u32 = 1 << 24;
  719. // TIPG
  720. const E1000E_TIPG_IPGT: u32 = 8;
  721. const E1000E_TIPG_IPGR1: u32 = 2 << 10;
  722. const E1000E_TIPG_IPGR2: u32 = 10 << 20;
  723. // RxDescriptorStatus
  724. const E1000E_RXD_STATUS_DD: u16 = 1 << 0;
  725. // TxDescriptorStatus
  726. const E1000E_TXD_STATUS_DD: u8 = 1 << 0;
  727. const E1000E_TXD_CMD_EOP: u8 = 1 << 0;
  728. const E1000E_TXD_CMD_IFCS: u8 = 1 << 1;
  729. const E1000E_TXD_CMD_RS: u8 = 1 << 3;
  730. // E1000E驱动初始化过程中可能的错误
  731. pub enum E1000EPciError {
  732. // 获取到错误类型的BAR(IO BAR)
  733. // An IO BAR was provided rather than a memory BAR.
  734. UnexpectedBarType,
  735. // 获取的BAR没有被分配到某个地址(address == 0)
  736. // A BAR which we need was not allocated an address(address == 0).
  737. BarNotAllocated,
  738. //获取虚拟地址失败
  739. BarGetVaddrFailed,
  740. // 没有对应的BAR或者获取BAR失败
  741. BarGetFailed,
  742. // BAR的大小与预期不符(128KB)
  743. // Size of BAR is not 128KB
  744. UnexpectedBarSize,
  745. Pci(PciError),
  746. }
  747. /// PCI error到VirtioPciError的转换,层层上报
  748. impl From<PciError> for E1000EPciError {
  749. fn from(error: PciError) -> Self {
  750. Self::Pci(error)
  751. }
  752. }
  753. /**
  754. * @brief 获取基地址的某个偏移量的指针,用于在mmio bar中构造寄存器结构体
  755. * @brief used for build register struct in mmio bar
  756. * @param vaddr: base address (in virtual memory)
  757. * @param offset: offset
  758. */
  759. fn get_register_ptr<T>(vaddr: u64, offset: u64) -> NonNull<T> {
  760. NonNull::new((vaddr + offset) as *mut T).unwrap()
  761. }