phy.rs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  1. // SPDX-License-Identifier: GPL-2.0
  2. // Copyright (C) 2023 FUJITA Tomonori <fujita.tomonori@gmail.com>
  3. //! Network PHY device.
  4. //!
  5. //! C headers: [`include/linux/phy.h`](srctree/include/linux/phy.h).
  6. use crate::{error::*, prelude::*, types::Opaque};
  7. use core::{marker::PhantomData, ptr::addr_of_mut};
  8. pub mod reg;
  9. /// PHY state machine states.
  10. ///
  11. /// Corresponds to the kernel's [`enum phy_state`].
  12. ///
  13. /// Some of PHY drivers access to the state of PHY's software state machine.
  14. ///
  15. /// [`enum phy_state`]: srctree/include/linux/phy.h
  16. #[derive(PartialEq, Eq)]
  17. pub enum DeviceState {
  18. /// PHY device and driver are not ready for anything.
  19. Down,
  20. /// PHY is ready to send and receive packets.
  21. Ready,
  22. /// PHY is up, but no polling or interrupts are done.
  23. Halted,
  24. /// PHY is up, but is in an error state.
  25. Error,
  26. /// PHY and attached device are ready to do work.
  27. Up,
  28. /// PHY is currently running.
  29. Running,
  30. /// PHY is up, but not currently plugged in.
  31. NoLink,
  32. /// PHY is performing a cable test.
  33. CableTest,
  34. }
  35. /// A mode of Ethernet communication.
  36. ///
  37. /// PHY drivers get duplex information from hardware and update the current state.
  38. pub enum DuplexMode {
  39. /// PHY is in full-duplex mode.
  40. Full,
  41. /// PHY is in half-duplex mode.
  42. Half,
  43. /// PHY is in unknown duplex mode.
  44. Unknown,
  45. }
  46. /// An instance of a PHY device.
  47. ///
  48. /// Wraps the kernel's [`struct phy_device`].
  49. ///
  50. /// A [`Device`] instance is created when a callback in [`Driver`] is executed. A PHY driver
  51. /// executes [`Driver`]'s methods during the callback.
  52. ///
  53. /// # Invariants
  54. ///
  55. /// - Referencing a `phy_device` using this struct asserts that you are in
  56. /// a context where all methods defined on this struct are safe to call.
  57. /// - This struct always has a valid `self.0.mdio.dev`.
  58. ///
  59. /// [`struct phy_device`]: srctree/include/linux/phy.h
  60. // During the calls to most functions in [`Driver`], the C side (`PHYLIB`) holds a lock that is
  61. // unique for every instance of [`Device`]. `PHYLIB` uses a different serialization technique for
  62. // [`Driver::resume`] and [`Driver::suspend`]: `PHYLIB` updates `phy_device`'s state with
  63. // the lock held, thus guaranteeing that [`Driver::resume`] has exclusive access to the instance.
  64. // [`Driver::resume`] and [`Driver::suspend`] also are called where only one thread can access
  65. // to the instance.
  66. #[repr(transparent)]
  67. pub struct Device(Opaque<bindings::phy_device>);
  68. impl Device {
  69. /// Creates a new [`Device`] instance from a raw pointer.
  70. ///
  71. /// # Safety
  72. ///
  73. /// For the duration of `'a`,
  74. /// - the pointer must point at a valid `phy_device`, and the caller
  75. /// must be in a context where all methods defined on this struct
  76. /// are safe to call.
  77. /// - `(*ptr).mdio.dev` must be a valid.
  78. unsafe fn from_raw<'a>(ptr: *mut bindings::phy_device) -> &'a mut Self {
  79. // CAST: `Self` is a `repr(transparent)` wrapper around `bindings::phy_device`.
  80. let ptr = ptr.cast::<Self>();
  81. // SAFETY: by the function requirements the pointer is valid and we have unique access for
  82. // the duration of `'a`.
  83. unsafe { &mut *ptr }
  84. }
  85. /// Gets the id of the PHY.
  86. pub fn phy_id(&self) -> u32 {
  87. let phydev = self.0.get();
  88. // SAFETY: The struct invariant ensures that we may access
  89. // this field without additional synchronization.
  90. unsafe { (*phydev).phy_id }
  91. }
  92. /// Gets the state of PHY state machine states.
  93. pub fn state(&self) -> DeviceState {
  94. let phydev = self.0.get();
  95. // SAFETY: The struct invariant ensures that we may access
  96. // this field without additional synchronization.
  97. let state = unsafe { (*phydev).state };
  98. // TODO: this conversion code will be replaced with automatically generated code by bindgen
  99. // when it becomes possible.
  100. match state {
  101. bindings::phy_state_PHY_DOWN => DeviceState::Down,
  102. bindings::phy_state_PHY_READY => DeviceState::Ready,
  103. bindings::phy_state_PHY_HALTED => DeviceState::Halted,
  104. bindings::phy_state_PHY_ERROR => DeviceState::Error,
  105. bindings::phy_state_PHY_UP => DeviceState::Up,
  106. bindings::phy_state_PHY_RUNNING => DeviceState::Running,
  107. bindings::phy_state_PHY_NOLINK => DeviceState::NoLink,
  108. bindings::phy_state_PHY_CABLETEST => DeviceState::CableTest,
  109. _ => DeviceState::Error,
  110. }
  111. }
  112. /// Gets the current link state.
  113. ///
  114. /// It returns true if the link is up.
  115. pub fn is_link_up(&self) -> bool {
  116. const LINK_IS_UP: u64 = 1;
  117. // TODO: the code to access to the bit field will be replaced with automatically
  118. // generated code by bindgen when it becomes possible.
  119. // SAFETY: The struct invariant ensures that we may access
  120. // this field without additional synchronization.
  121. let bit_field = unsafe { &(*self.0.get())._bitfield_1 };
  122. bit_field.get(14, 1) == LINK_IS_UP
  123. }
  124. /// Gets the current auto-negotiation configuration.
  125. ///
  126. /// It returns true if auto-negotiation is enabled.
  127. pub fn is_autoneg_enabled(&self) -> bool {
  128. // TODO: the code to access to the bit field will be replaced with automatically
  129. // generated code by bindgen when it becomes possible.
  130. // SAFETY: The struct invariant ensures that we may access
  131. // this field without additional synchronization.
  132. let bit_field = unsafe { &(*self.0.get())._bitfield_1 };
  133. bit_field.get(13, 1) == bindings::AUTONEG_ENABLE as u64
  134. }
  135. /// Gets the current auto-negotiation state.
  136. ///
  137. /// It returns true if auto-negotiation is completed.
  138. pub fn is_autoneg_completed(&self) -> bool {
  139. const AUTONEG_COMPLETED: u64 = 1;
  140. // TODO: the code to access to the bit field will be replaced with automatically
  141. // generated code by bindgen when it becomes possible.
  142. // SAFETY: The struct invariant ensures that we may access
  143. // this field without additional synchronization.
  144. let bit_field = unsafe { &(*self.0.get())._bitfield_1 };
  145. bit_field.get(15, 1) == AUTONEG_COMPLETED
  146. }
  147. /// Sets the speed of the PHY.
  148. pub fn set_speed(&mut self, speed: u32) {
  149. let phydev = self.0.get();
  150. // SAFETY: The struct invariant ensures that we may access
  151. // this field without additional synchronization.
  152. unsafe { (*phydev).speed = speed as i32 };
  153. }
  154. /// Sets duplex mode.
  155. pub fn set_duplex(&mut self, mode: DuplexMode) {
  156. let phydev = self.0.get();
  157. let v = match mode {
  158. DuplexMode::Full => bindings::DUPLEX_FULL as i32,
  159. DuplexMode::Half => bindings::DUPLEX_HALF as i32,
  160. DuplexMode::Unknown => bindings::DUPLEX_UNKNOWN as i32,
  161. };
  162. // SAFETY: The struct invariant ensures that we may access
  163. // this field without additional synchronization.
  164. unsafe { (*phydev).duplex = v };
  165. }
  166. /// Reads a PHY register.
  167. // This function reads a hardware register and updates the stats so takes `&mut self`.
  168. pub fn read<R: reg::Register>(&mut self, reg: R) -> Result<u16> {
  169. reg.read(self)
  170. }
  171. /// Writes a PHY register.
  172. pub fn write<R: reg::Register>(&mut self, reg: R, val: u16) -> Result {
  173. reg.write(self, val)
  174. }
  175. /// Reads a paged register.
  176. pub fn read_paged(&mut self, page: u16, regnum: u16) -> Result<u16> {
  177. let phydev = self.0.get();
  178. // SAFETY: `phydev` is pointing to a valid object by the type invariant of `Self`.
  179. // So it's just an FFI call.
  180. let ret = unsafe { bindings::phy_read_paged(phydev, page.into(), regnum.into()) };
  181. if ret < 0 {
  182. Err(Error::from_errno(ret))
  183. } else {
  184. Ok(ret as u16)
  185. }
  186. }
  187. /// Resolves the advertisements into PHY settings.
  188. pub fn resolve_aneg_linkmode(&mut self) {
  189. let phydev = self.0.get();
  190. // SAFETY: `phydev` is pointing to a valid object by the type invariant of `Self`.
  191. // So it's just an FFI call.
  192. unsafe { bindings::phy_resolve_aneg_linkmode(phydev) };
  193. }
  194. /// Executes software reset the PHY via `BMCR_RESET` bit.
  195. pub fn genphy_soft_reset(&mut self) -> Result {
  196. let phydev = self.0.get();
  197. // SAFETY: `phydev` is pointing to a valid object by the type invariant of `Self`.
  198. // So it's just an FFI call.
  199. to_result(unsafe { bindings::genphy_soft_reset(phydev) })
  200. }
  201. /// Initializes the PHY.
  202. pub fn init_hw(&mut self) -> Result {
  203. let phydev = self.0.get();
  204. // SAFETY: `phydev` is pointing to a valid object by the type invariant of `Self`.
  205. // So it's just an FFI call.
  206. to_result(unsafe { bindings::phy_init_hw(phydev) })
  207. }
  208. /// Starts auto-negotiation.
  209. pub fn start_aneg(&mut self) -> Result {
  210. let phydev = self.0.get();
  211. // SAFETY: `phydev` is pointing to a valid object by the type invariant of `Self`.
  212. // So it's just an FFI call.
  213. to_result(unsafe { bindings::_phy_start_aneg(phydev) })
  214. }
  215. /// Resumes the PHY via `BMCR_PDOWN` bit.
  216. pub fn genphy_resume(&mut self) -> Result {
  217. let phydev = self.0.get();
  218. // SAFETY: `phydev` is pointing to a valid object by the type invariant of `Self`.
  219. // So it's just an FFI call.
  220. to_result(unsafe { bindings::genphy_resume(phydev) })
  221. }
  222. /// Suspends the PHY via `BMCR_PDOWN` bit.
  223. pub fn genphy_suspend(&mut self) -> Result {
  224. let phydev = self.0.get();
  225. // SAFETY: `phydev` is pointing to a valid object by the type invariant of `Self`.
  226. // So it's just an FFI call.
  227. to_result(unsafe { bindings::genphy_suspend(phydev) })
  228. }
  229. /// Checks the link status and updates current link state.
  230. pub fn genphy_read_status<R: reg::Register>(&mut self) -> Result<u16> {
  231. R::read_status(self)
  232. }
  233. /// Updates the link status.
  234. pub fn genphy_update_link(&mut self) -> Result {
  235. let phydev = self.0.get();
  236. // SAFETY: `phydev` is pointing to a valid object by the type invariant of `Self`.
  237. // So it's just an FFI call.
  238. to_result(unsafe { bindings::genphy_update_link(phydev) })
  239. }
  240. /// Reads link partner ability.
  241. pub fn genphy_read_lpa(&mut self) -> Result {
  242. let phydev = self.0.get();
  243. // SAFETY: `phydev` is pointing to a valid object by the type invariant of `Self`.
  244. // So it's just an FFI call.
  245. to_result(unsafe { bindings::genphy_read_lpa(phydev) })
  246. }
  247. /// Reads PHY abilities.
  248. pub fn genphy_read_abilities(&mut self) -> Result {
  249. let phydev = self.0.get();
  250. // SAFETY: `phydev` is pointing to a valid object by the type invariant of `Self`.
  251. // So it's just an FFI call.
  252. to_result(unsafe { bindings::genphy_read_abilities(phydev) })
  253. }
  254. }
  255. impl AsRef<kernel::device::Device> for Device {
  256. fn as_ref(&self) -> &kernel::device::Device {
  257. let phydev = self.0.get();
  258. // SAFETY: The struct invariant ensures that `mdio.dev` is valid.
  259. unsafe { kernel::device::Device::as_ref(addr_of_mut!((*phydev).mdio.dev)) }
  260. }
  261. }
  262. /// Defines certain other features this PHY supports (like interrupts).
  263. ///
  264. /// These flag values are used in [`Driver::FLAGS`].
  265. pub mod flags {
  266. /// PHY is internal.
  267. pub const IS_INTERNAL: u32 = bindings::PHY_IS_INTERNAL;
  268. /// PHY needs to be reset after the refclk is enabled.
  269. pub const RST_AFTER_CLK_EN: u32 = bindings::PHY_RST_AFTER_CLK_EN;
  270. /// Polling is used to detect PHY status changes.
  271. pub const POLL_CABLE_TEST: u32 = bindings::PHY_POLL_CABLE_TEST;
  272. /// Don't suspend.
  273. pub const ALWAYS_CALL_SUSPEND: u32 = bindings::PHY_ALWAYS_CALL_SUSPEND;
  274. }
  275. /// An adapter for the registration of a PHY driver.
  276. struct Adapter<T: Driver> {
  277. _p: PhantomData<T>,
  278. }
  279. impl<T: Driver> Adapter<T> {
  280. /// # Safety
  281. ///
  282. /// `phydev` must be passed by the corresponding callback in `phy_driver`.
  283. unsafe extern "C" fn soft_reset_callback(
  284. phydev: *mut bindings::phy_device,
  285. ) -> crate::ffi::c_int {
  286. from_result(|| {
  287. // SAFETY: This callback is called only in contexts
  288. // where we hold `phy_device->lock`, so the accessors on
  289. // `Device` are okay to call.
  290. let dev = unsafe { Device::from_raw(phydev) };
  291. T::soft_reset(dev)?;
  292. Ok(0)
  293. })
  294. }
  295. /// # Safety
  296. ///
  297. /// `phydev` must be passed by the corresponding callback in `phy_driver`.
  298. unsafe extern "C" fn probe_callback(phydev: *mut bindings::phy_device) -> crate::ffi::c_int {
  299. from_result(|| {
  300. // SAFETY: This callback is called only in contexts
  301. // where we can exclusively access `phy_device` because
  302. // it's not published yet, so the accessors on `Device` are okay
  303. // to call.
  304. let dev = unsafe { Device::from_raw(phydev) };
  305. T::probe(dev)?;
  306. Ok(0)
  307. })
  308. }
  309. /// # Safety
  310. ///
  311. /// `phydev` must be passed by the corresponding callback in `phy_driver`.
  312. unsafe extern "C" fn get_features_callback(
  313. phydev: *mut bindings::phy_device,
  314. ) -> crate::ffi::c_int {
  315. from_result(|| {
  316. // SAFETY: This callback is called only in contexts
  317. // where we hold `phy_device->lock`, so the accessors on
  318. // `Device` are okay to call.
  319. let dev = unsafe { Device::from_raw(phydev) };
  320. T::get_features(dev)?;
  321. Ok(0)
  322. })
  323. }
  324. /// # Safety
  325. ///
  326. /// `phydev` must be passed by the corresponding callback in `phy_driver`.
  327. unsafe extern "C" fn suspend_callback(phydev: *mut bindings::phy_device) -> crate::ffi::c_int {
  328. from_result(|| {
  329. // SAFETY: The C core code ensures that the accessors on
  330. // `Device` are okay to call even though `phy_device->lock`
  331. // might not be held.
  332. let dev = unsafe { Device::from_raw(phydev) };
  333. T::suspend(dev)?;
  334. Ok(0)
  335. })
  336. }
  337. /// # Safety
  338. ///
  339. /// `phydev` must be passed by the corresponding callback in `phy_driver`.
  340. unsafe extern "C" fn resume_callback(phydev: *mut bindings::phy_device) -> crate::ffi::c_int {
  341. from_result(|| {
  342. // SAFETY: The C core code ensures that the accessors on
  343. // `Device` are okay to call even though `phy_device->lock`
  344. // might not be held.
  345. let dev = unsafe { Device::from_raw(phydev) };
  346. T::resume(dev)?;
  347. Ok(0)
  348. })
  349. }
  350. /// # Safety
  351. ///
  352. /// `phydev` must be passed by the corresponding callback in `phy_driver`.
  353. unsafe extern "C" fn config_aneg_callback(
  354. phydev: *mut bindings::phy_device,
  355. ) -> crate::ffi::c_int {
  356. from_result(|| {
  357. // SAFETY: This callback is called only in contexts
  358. // where we hold `phy_device->lock`, so the accessors on
  359. // `Device` are okay to call.
  360. let dev = unsafe { Device::from_raw(phydev) };
  361. T::config_aneg(dev)?;
  362. Ok(0)
  363. })
  364. }
  365. /// # Safety
  366. ///
  367. /// `phydev` must be passed by the corresponding callback in `phy_driver`.
  368. unsafe extern "C" fn read_status_callback(
  369. phydev: *mut bindings::phy_device,
  370. ) -> crate::ffi::c_int {
  371. from_result(|| {
  372. // SAFETY: This callback is called only in contexts
  373. // where we hold `phy_device->lock`, so the accessors on
  374. // `Device` are okay to call.
  375. let dev = unsafe { Device::from_raw(phydev) };
  376. T::read_status(dev)?;
  377. Ok(0)
  378. })
  379. }
  380. /// # Safety
  381. ///
  382. /// `phydev` must be passed by the corresponding callback in `phy_driver`.
  383. unsafe extern "C" fn match_phy_device_callback(
  384. phydev: *mut bindings::phy_device,
  385. ) -> crate::ffi::c_int {
  386. // SAFETY: This callback is called only in contexts
  387. // where we hold `phy_device->lock`, so the accessors on
  388. // `Device` are okay to call.
  389. let dev = unsafe { Device::from_raw(phydev) };
  390. T::match_phy_device(dev) as i32
  391. }
  392. /// # Safety
  393. ///
  394. /// `phydev` must be passed by the corresponding callback in `phy_driver`.
  395. unsafe extern "C" fn read_mmd_callback(
  396. phydev: *mut bindings::phy_device,
  397. devnum: i32,
  398. regnum: u16,
  399. ) -> i32 {
  400. from_result(|| {
  401. // SAFETY: This callback is called only in contexts
  402. // where we hold `phy_device->lock`, so the accessors on
  403. // `Device` are okay to call.
  404. let dev = unsafe { Device::from_raw(phydev) };
  405. // CAST: the C side verifies devnum < 32.
  406. let ret = T::read_mmd(dev, devnum as u8, regnum)?;
  407. Ok(ret.into())
  408. })
  409. }
  410. /// # Safety
  411. ///
  412. /// `phydev` must be passed by the corresponding callback in `phy_driver`.
  413. unsafe extern "C" fn write_mmd_callback(
  414. phydev: *mut bindings::phy_device,
  415. devnum: i32,
  416. regnum: u16,
  417. val: u16,
  418. ) -> i32 {
  419. from_result(|| {
  420. // SAFETY: This callback is called only in contexts
  421. // where we hold `phy_device->lock`, so the accessors on
  422. // `Device` are okay to call.
  423. let dev = unsafe { Device::from_raw(phydev) };
  424. T::write_mmd(dev, devnum as u8, regnum, val)?;
  425. Ok(0)
  426. })
  427. }
  428. /// # Safety
  429. ///
  430. /// `phydev` must be passed by the corresponding callback in `phy_driver`.
  431. unsafe extern "C" fn link_change_notify_callback(phydev: *mut bindings::phy_device) {
  432. // SAFETY: This callback is called only in contexts
  433. // where we hold `phy_device->lock`, so the accessors on
  434. // `Device` are okay to call.
  435. let dev = unsafe { Device::from_raw(phydev) };
  436. T::link_change_notify(dev);
  437. }
  438. }
  439. /// Driver structure for a particular PHY type.
  440. ///
  441. /// Wraps the kernel's [`struct phy_driver`].
  442. /// This is used to register a driver for a particular PHY type with the kernel.
  443. ///
  444. /// # Invariants
  445. ///
  446. /// `self.0` is always in a valid state.
  447. ///
  448. /// [`struct phy_driver`]: srctree/include/linux/phy.h
  449. #[repr(transparent)]
  450. pub struct DriverVTable(Opaque<bindings::phy_driver>);
  451. // SAFETY: `DriverVTable` doesn't expose any &self method to access internal data, so it's safe to
  452. // share `&DriverVTable` across execution context boundaries.
  453. unsafe impl Sync for DriverVTable {}
  454. /// Creates a [`DriverVTable`] instance from [`Driver`].
  455. ///
  456. /// This is used by [`module_phy_driver`] macro to create a static array of `phy_driver`.
  457. ///
  458. /// [`module_phy_driver`]: crate::module_phy_driver
  459. pub const fn create_phy_driver<T: Driver>() -> DriverVTable {
  460. // INVARIANT: All the fields of `struct phy_driver` are initialized properly.
  461. DriverVTable(Opaque::new(bindings::phy_driver {
  462. name: T::NAME.as_char_ptr().cast_mut(),
  463. flags: T::FLAGS,
  464. phy_id: T::PHY_DEVICE_ID.id,
  465. phy_id_mask: T::PHY_DEVICE_ID.mask_as_int(),
  466. soft_reset: if T::HAS_SOFT_RESET {
  467. Some(Adapter::<T>::soft_reset_callback)
  468. } else {
  469. None
  470. },
  471. probe: if T::HAS_PROBE {
  472. Some(Adapter::<T>::probe_callback)
  473. } else {
  474. None
  475. },
  476. get_features: if T::HAS_GET_FEATURES {
  477. Some(Adapter::<T>::get_features_callback)
  478. } else {
  479. None
  480. },
  481. match_phy_device: if T::HAS_MATCH_PHY_DEVICE {
  482. Some(Adapter::<T>::match_phy_device_callback)
  483. } else {
  484. None
  485. },
  486. suspend: if T::HAS_SUSPEND {
  487. Some(Adapter::<T>::suspend_callback)
  488. } else {
  489. None
  490. },
  491. resume: if T::HAS_RESUME {
  492. Some(Adapter::<T>::resume_callback)
  493. } else {
  494. None
  495. },
  496. config_aneg: if T::HAS_CONFIG_ANEG {
  497. Some(Adapter::<T>::config_aneg_callback)
  498. } else {
  499. None
  500. },
  501. read_status: if T::HAS_READ_STATUS {
  502. Some(Adapter::<T>::read_status_callback)
  503. } else {
  504. None
  505. },
  506. read_mmd: if T::HAS_READ_MMD {
  507. Some(Adapter::<T>::read_mmd_callback)
  508. } else {
  509. None
  510. },
  511. write_mmd: if T::HAS_WRITE_MMD {
  512. Some(Adapter::<T>::write_mmd_callback)
  513. } else {
  514. None
  515. },
  516. link_change_notify: if T::HAS_LINK_CHANGE_NOTIFY {
  517. Some(Adapter::<T>::link_change_notify_callback)
  518. } else {
  519. None
  520. },
  521. // SAFETY: The rest is zeroed out to initialize `struct phy_driver`,
  522. // sets `Option<&F>` to be `None`.
  523. ..unsafe { core::mem::MaybeUninit::<bindings::phy_driver>::zeroed().assume_init() }
  524. }))
  525. }
  526. /// Driver implementation for a particular PHY type.
  527. ///
  528. /// This trait is used to create a [`DriverVTable`].
  529. #[vtable]
  530. pub trait Driver {
  531. /// Defines certain other features this PHY supports.
  532. /// It is a combination of the flags in the [`flags`] module.
  533. const FLAGS: u32 = 0;
  534. /// The friendly name of this PHY type.
  535. const NAME: &'static CStr;
  536. /// This driver only works for PHYs with IDs which match this field.
  537. /// The default id and mask are zero.
  538. const PHY_DEVICE_ID: DeviceId = DeviceId::new_with_custom_mask(0, 0);
  539. /// Issues a PHY software reset.
  540. fn soft_reset(_dev: &mut Device) -> Result {
  541. kernel::build_error(VTABLE_DEFAULT_ERROR)
  542. }
  543. /// Sets up device-specific structures during discovery.
  544. fn probe(_dev: &mut Device) -> Result {
  545. kernel::build_error(VTABLE_DEFAULT_ERROR)
  546. }
  547. /// Probes the hardware to determine what abilities it has.
  548. fn get_features(_dev: &mut Device) -> Result {
  549. kernel::build_error(VTABLE_DEFAULT_ERROR)
  550. }
  551. /// Returns true if this is a suitable driver for the given phydev.
  552. /// If not implemented, matching is based on [`Driver::PHY_DEVICE_ID`].
  553. fn match_phy_device(_dev: &Device) -> bool {
  554. false
  555. }
  556. /// Configures the advertisement and resets auto-negotiation
  557. /// if auto-negotiation is enabled.
  558. fn config_aneg(_dev: &mut Device) -> Result {
  559. kernel::build_error(VTABLE_DEFAULT_ERROR)
  560. }
  561. /// Determines the negotiated speed and duplex.
  562. fn read_status(_dev: &mut Device) -> Result<u16> {
  563. kernel::build_error(VTABLE_DEFAULT_ERROR)
  564. }
  565. /// Suspends the hardware, saving state if needed.
  566. fn suspend(_dev: &mut Device) -> Result {
  567. kernel::build_error(VTABLE_DEFAULT_ERROR)
  568. }
  569. /// Resumes the hardware, restoring state if needed.
  570. fn resume(_dev: &mut Device) -> Result {
  571. kernel::build_error(VTABLE_DEFAULT_ERROR)
  572. }
  573. /// Overrides the default MMD read function for reading a MMD register.
  574. fn read_mmd(_dev: &mut Device, _devnum: u8, _regnum: u16) -> Result<u16> {
  575. kernel::build_error(VTABLE_DEFAULT_ERROR)
  576. }
  577. /// Overrides the default MMD write function for writing a MMD register.
  578. fn write_mmd(_dev: &mut Device, _devnum: u8, _regnum: u16, _val: u16) -> Result {
  579. kernel::build_error(VTABLE_DEFAULT_ERROR)
  580. }
  581. /// Callback for notification of link change.
  582. fn link_change_notify(_dev: &mut Device) {}
  583. }
  584. /// Registration structure for PHY drivers.
  585. ///
  586. /// Registers [`DriverVTable`] instances with the kernel. They will be unregistered when dropped.
  587. ///
  588. /// # Invariants
  589. ///
  590. /// The `drivers` slice are currently registered to the kernel via `phy_drivers_register`.
  591. pub struct Registration {
  592. drivers: Pin<&'static mut [DriverVTable]>,
  593. }
  594. // SAFETY: The only action allowed in a `Registration` instance is dropping it, which is safe to do
  595. // from any thread because `phy_drivers_unregister` can be called from any thread context.
  596. unsafe impl Send for Registration {}
  597. impl Registration {
  598. /// Registers a PHY driver.
  599. pub fn register(
  600. module: &'static crate::ThisModule,
  601. drivers: Pin<&'static mut [DriverVTable]>,
  602. ) -> Result<Self> {
  603. if drivers.is_empty() {
  604. return Err(code::EINVAL);
  605. }
  606. // SAFETY: The type invariants of [`DriverVTable`] ensure that all elements of
  607. // the `drivers` slice are initialized properly. `drivers` will not be moved.
  608. // So it's just an FFI call.
  609. to_result(unsafe {
  610. bindings::phy_drivers_register(drivers[0].0.get(), drivers.len().try_into()?, module.0)
  611. })?;
  612. // INVARIANT: The `drivers` slice is successfully registered to the kernel via `phy_drivers_register`.
  613. Ok(Registration { drivers })
  614. }
  615. }
  616. impl Drop for Registration {
  617. fn drop(&mut self) {
  618. // SAFETY: The type invariants guarantee that `self.drivers` is valid.
  619. // So it's just an FFI call.
  620. unsafe {
  621. bindings::phy_drivers_unregister(self.drivers[0].0.get(), self.drivers.len() as i32)
  622. };
  623. }
  624. }
  625. /// An identifier for PHY devices on an MDIO/MII bus.
  626. ///
  627. /// Represents the kernel's `struct mdio_device_id`. This is used to find an appropriate
  628. /// PHY driver.
  629. pub struct DeviceId {
  630. id: u32,
  631. mask: DeviceMask,
  632. }
  633. impl DeviceId {
  634. /// Creates a new instance with the exact match mask.
  635. pub const fn new_with_exact_mask(id: u32) -> Self {
  636. DeviceId {
  637. id,
  638. mask: DeviceMask::Exact,
  639. }
  640. }
  641. /// Creates a new instance with the model match mask.
  642. pub const fn new_with_model_mask(id: u32) -> Self {
  643. DeviceId {
  644. id,
  645. mask: DeviceMask::Model,
  646. }
  647. }
  648. /// Creates a new instance with the vendor match mask.
  649. pub const fn new_with_vendor_mask(id: u32) -> Self {
  650. DeviceId {
  651. id,
  652. mask: DeviceMask::Vendor,
  653. }
  654. }
  655. /// Creates a new instance with a custom match mask.
  656. pub const fn new_with_custom_mask(id: u32, mask: u32) -> Self {
  657. DeviceId {
  658. id,
  659. mask: DeviceMask::Custom(mask),
  660. }
  661. }
  662. /// Creates a new instance from [`Driver`].
  663. pub const fn new_with_driver<T: Driver>() -> Self {
  664. T::PHY_DEVICE_ID
  665. }
  666. /// Get a `mask` as u32.
  667. pub const fn mask_as_int(&self) -> u32 {
  668. self.mask.as_int()
  669. }
  670. // macro use only
  671. #[doc(hidden)]
  672. pub const fn mdio_device_id(&self) -> bindings::mdio_device_id {
  673. bindings::mdio_device_id {
  674. phy_id: self.id,
  675. phy_id_mask: self.mask.as_int(),
  676. }
  677. }
  678. }
  679. enum DeviceMask {
  680. Exact,
  681. Model,
  682. Vendor,
  683. Custom(u32),
  684. }
  685. impl DeviceMask {
  686. const MASK_EXACT: u32 = !0;
  687. const MASK_MODEL: u32 = !0 << 4;
  688. const MASK_VENDOR: u32 = !0 << 10;
  689. const fn as_int(&self) -> u32 {
  690. match self {
  691. DeviceMask::Exact => Self::MASK_EXACT,
  692. DeviceMask::Model => Self::MASK_MODEL,
  693. DeviceMask::Vendor => Self::MASK_VENDOR,
  694. DeviceMask::Custom(mask) => *mask,
  695. }
  696. }
  697. }
  698. /// Declares a kernel module for PHYs drivers.
  699. ///
  700. /// This creates a static array of kernel's `struct phy_driver` and registers it.
  701. /// This also corresponds to the kernel's `MODULE_DEVICE_TABLE` macro, which embeds the information
  702. /// for module loading into the module binary file. Every driver needs an entry in `device_table`.
  703. ///
  704. /// # Examples
  705. ///
  706. /// ```
  707. /// # mod module_phy_driver_sample {
  708. /// use kernel::c_str;
  709. /// use kernel::net::phy::{self, DeviceId};
  710. /// use kernel::prelude::*;
  711. ///
  712. /// kernel::module_phy_driver! {
  713. /// drivers: [PhySample],
  714. /// device_table: [
  715. /// DeviceId::new_with_driver::<PhySample>()
  716. /// ],
  717. /// name: "rust_sample_phy",
  718. /// author: "Rust for Linux Contributors",
  719. /// description: "Rust sample PHYs driver",
  720. /// license: "GPL",
  721. /// }
  722. ///
  723. /// struct PhySample;
  724. ///
  725. /// #[vtable]
  726. /// impl phy::Driver for PhySample {
  727. /// const NAME: &'static CStr = c_str!("PhySample");
  728. /// const PHY_DEVICE_ID: phy::DeviceId = phy::DeviceId::new_with_exact_mask(0x00000001);
  729. /// }
  730. /// # }
  731. /// ```
  732. ///
  733. /// This expands to the following code:
  734. ///
  735. /// ```ignore
  736. /// use kernel::c_str;
  737. /// use kernel::net::phy::{self, DeviceId};
  738. /// use kernel::prelude::*;
  739. ///
  740. /// struct Module {
  741. /// _reg: ::kernel::net::phy::Registration,
  742. /// }
  743. ///
  744. /// module! {
  745. /// type: Module,
  746. /// name: "rust_sample_phy",
  747. /// author: "Rust for Linux Contributors",
  748. /// description: "Rust sample PHYs driver",
  749. /// license: "GPL",
  750. /// }
  751. ///
  752. /// struct PhySample;
  753. ///
  754. /// #[vtable]
  755. /// impl phy::Driver for PhySample {
  756. /// const NAME: &'static CStr = c_str!("PhySample");
  757. /// const PHY_DEVICE_ID: phy::DeviceId = phy::DeviceId::new_with_exact_mask(0x00000001);
  758. /// }
  759. ///
  760. /// const _: () = {
  761. /// static mut DRIVERS: [::kernel::net::phy::DriverVTable; 1] =
  762. /// [::kernel::net::phy::create_phy_driver::<PhySample>()];
  763. ///
  764. /// impl ::kernel::Module for Module {
  765. /// fn init(module: &'static ThisModule) -> Result<Self> {
  766. /// let drivers = unsafe { &mut DRIVERS };
  767. /// let mut reg = ::kernel::net::phy::Registration::register(
  768. /// module,
  769. /// ::core::pin::Pin::static_mut(drivers),
  770. /// )?;
  771. /// Ok(Module { _reg: reg })
  772. /// }
  773. /// }
  774. /// };
  775. ///
  776. /// #[cfg(MODULE)]
  777. /// #[no_mangle]
  778. /// static __mod_mdio__phydev_device_table: [::kernel::bindings::mdio_device_id; 2] = [
  779. /// ::kernel::bindings::mdio_device_id {
  780. /// phy_id: 0x00000001,
  781. /// phy_id_mask: 0xffffffff,
  782. /// },
  783. /// ::kernel::bindings::mdio_device_id {
  784. /// phy_id: 0,
  785. /// phy_id_mask: 0,
  786. /// },
  787. /// ];
  788. /// ```
  789. #[macro_export]
  790. macro_rules! module_phy_driver {
  791. (@replace_expr $_t:tt $sub:expr) => {$sub};
  792. (@count_devices $($x:expr),*) => {
  793. 0usize $(+ $crate::module_phy_driver!(@replace_expr $x 1usize))*
  794. };
  795. (@device_table [$($dev:expr),+]) => {
  796. // SAFETY: C will not read off the end of this constant since the last element is zero.
  797. #[cfg(MODULE)]
  798. #[no_mangle]
  799. static __mod_mdio__phydev_device_table: [$crate::bindings::mdio_device_id;
  800. $crate::module_phy_driver!(@count_devices $($dev),+) + 1] = [
  801. $($dev.mdio_device_id()),+,
  802. $crate::bindings::mdio_device_id {
  803. phy_id: 0,
  804. phy_id_mask: 0
  805. }
  806. ];
  807. };
  808. (drivers: [$($driver:ident),+ $(,)?], device_table: [$($dev:expr),+ $(,)?], $($f:tt)*) => {
  809. struct Module {
  810. _reg: $crate::net::phy::Registration,
  811. }
  812. $crate::prelude::module! {
  813. type: Module,
  814. $($f)*
  815. }
  816. const _: () = {
  817. static mut DRIVERS: [$crate::net::phy::DriverVTable;
  818. $crate::module_phy_driver!(@count_devices $($driver),+)] =
  819. [$($crate::net::phy::create_phy_driver::<$driver>()),+];
  820. impl $crate::Module for Module {
  821. fn init(module: &'static ThisModule) -> Result<Self> {
  822. // SAFETY: The anonymous constant guarantees that nobody else can access
  823. // the `DRIVERS` static. The array is used only in the C side.
  824. let drivers = unsafe { &mut DRIVERS };
  825. let mut reg = $crate::net::phy::Registration::register(
  826. module,
  827. ::core::pin::Pin::static_mut(drivers),
  828. )?;
  829. Ok(Module { _reg: reg })
  830. }
  831. }
  832. };
  833. $crate::module_phy_driver!(@device_table [$($dev),+]);
  834. }
  835. }