1 use core::intrinsics::unlikely; 2 3 use alloc::{string::ToString, sync::Arc}; 4 use intertrait::cast::CastArc; 5 6 use crate::{ 7 driver::base::kobject::KObject, 8 filesystem::{ 9 sysfs::{ 10 file::sysfs_emit_str, sysfs_instance, Attribute, SysFSOpsSupport, SYSFS_ATTR_MODE_WO, 11 }, 12 vfs::syscall::ModeType, 13 }, 14 libs::wait_queue::WaitQueue, 15 }; 16 use system_error::SystemError; 17 18 use super::{ 19 bus::BusNotifyEvent, 20 device_manager, 21 driver::{driver_manager, Driver, DriverManager}, 22 Device, DeviceManager, 23 }; 24 25 static PROBE_WAIT_QUEUE: WaitQueue = WaitQueue::default(); 26 27 impl DeviceManager { 28 /// 尝试把一个设备与一个驱动匹配 29 /// 30 /// 当前函数会遍历整个bus的驱动列表,并且尝试把设备与每一个驱动进行匹配。 31 /// 一旦有一个驱动匹配成功,就会返回。 32 /// 33 /// ## 参数 34 /// 35 /// - `dev`: 设备 36 /// 37 /// ## 返回 38 /// 39 /// - Ok(true): 匹配成功 40 /// - Ok(false): 没有匹配成功 41 /// - Err(SystemError::ENODEV): 设备还没被注册 42 /// 43 /// ## 参考 44 /// 45 /// https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/dd.c#1049 46 pub fn device_attach(&self, dev: &Arc<dyn Device>) -> Result<bool, SystemError> { 47 return self.do_device_attach(dev, false); 48 } 49 50 pub fn device_initial_probe(&self, dev: &Arc<dyn Device>) -> Result<bool, SystemError> { 51 return self.do_device_attach(dev, true); 52 } 53 54 /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/dd.c#978 55 fn do_device_attach( 56 &self, 57 dev: &Arc<dyn Device>, 58 allow_async: bool, 59 ) -> Result<bool, SystemError> { 60 if unlikely(allow_async) { 61 // todo!("do_device_attach: allow_async") 62 kwarn!("do_device_attach: allow_async is true, but currently not supported"); 63 } 64 if dev.is_dead() { 65 return Ok(false); 66 } 67 68 kwarn!("do_device_attach: dev: '{}'", dev.name()); 69 70 let mut do_async = false; 71 let mut r = Ok(false); 72 73 if dev.driver().is_some() { 74 if self.device_is_bound(dev) { 75 return Ok(true); 76 } 77 78 if self.device_bind_driver(dev).is_ok() { 79 return Ok(true); 80 } else { 81 dev.set_driver(None); 82 return Ok(false); 83 } 84 } else { 85 let bus = dev 86 .bus() 87 .and_then(|bus| bus.upgrade()) 88 .ok_or(SystemError::EINVAL)?; 89 let mut data = DeviceAttachData::new(dev.clone(), allow_async, false); 90 let mut flag = false; 91 for driver in bus.subsystem().drivers().iter() { 92 let r = self.do_device_attach_driver(driver, &mut data); 93 if unlikely(r.is_err()) { 94 flag = false; 95 break; 96 } else if r.unwrap() { 97 flag = true; 98 break; 99 } 100 } 101 102 if flag { 103 r = Ok(true); 104 } 105 106 if !flag && allow_async && data.have_async { 107 // If we could not find appropriate driver 108 // synchronously and we are allowed to do 109 // async probes and there are drivers that 110 // want to probe asynchronously, we'll 111 // try them. 112 113 do_async = true; 114 kdebug!( 115 "do_device_attach: try scheduling asynchronous probe for device: {}", 116 dev.name() 117 ); 118 } 119 } 120 121 if do_async { 122 todo!("do_device_attach: do_async") 123 } 124 return r; 125 } 126 127 /// 匹配设备和驱动 128 /// 129 /// ## 参数 130 /// 131 /// - `driver`: 驱动 132 /// - `data`: 匹配数据 133 /// 134 /// ## 返回 135 /// 136 /// - Ok(true): 匹配成功 137 /// - Ok(false): 没有匹配成功 138 /// - Err(SystemError): 匹配过程中出现意外错误,没有匹配成功 139 /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/dd.c#899 140 fn do_device_attach_driver( 141 &self, 142 driver: &Arc<dyn Driver>, 143 data: &mut DeviceAttachData, 144 ) -> Result<bool, SystemError> { 145 if let Some(bus) = driver.bus().and_then(|bus| bus.upgrade()) { 146 let r = bus.match_device(&data.dev, driver); 147 148 if let Err(e) = r { 149 // 如果不是ENOSYS,则总线出错 150 if e != SystemError::ENOSYS { 151 kdebug!( 152 "do_device_attach_driver: bus.match_device() failed, dev: '{}', err: {:?}", 153 data.dev.name(), 154 e 155 ); 156 return Err(e); 157 } 158 } else if !r.unwrap() { 159 return Ok(false); 160 } 161 } 162 163 let async_allowed = driver.allows_async_probing(); 164 if data.check_async && async_allowed != data.want_async { 165 return Ok(false); 166 } 167 168 return driver_manager() 169 .probe_device(driver, &data.dev) 170 .map(|_| true); 171 } 172 173 /// 检查设备是否绑定到驱动程序 174 /// 175 /// ## 参数 176 /// 177 /// - `dev`: 设备 178 /// 179 /// ## 返回 180 /// 181 /// 如果传递的设备已成功完成对驱动程序的探测,则返回true,否则返回false。 182 pub fn device_is_bound(&self, dev: &Arc<dyn Device>) -> bool { 183 return dev.driver().is_some(); 184 } 185 186 /// 把一个驱动绑定到设备上 187 /// 188 /// 允许手动绑定驱动到设备上。调用者需要设置好dev.driver(),保证其不为None 189 /// 190 /// ## 参数 191 /// 192 /// - `dev`: 设备 193 /// 194 /// ## 建议 195 /// 196 /// 使用device_manager().driver_attach()会更好 197 /// 198 /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/dd.c#496 199 pub fn device_bind_driver(&self, dev: &Arc<dyn Device>) -> Result<(), SystemError> { 200 let r = driver_manager().driver_sysfs_add(dev); 201 if let Err(e) = r { 202 self.device_links_force_bind(dev); 203 driver_manager().driver_bound(dev); 204 return Err(e); 205 } else if let Some(bus) = dev.bus().and_then(|bus| bus.upgrade()) { 206 bus.subsystem().bus_notifier().call_chain( 207 BusNotifyEvent::DriverNotBound, 208 Some(dev), 209 None, 210 ); 211 } 212 return r; 213 } 214 215 /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/dd.c?fi=driver_attach#528 216 fn unbind_cleanup(&self, dev: &Arc<dyn Device>) { 217 dev.set_driver(None); 218 // todo: 添加更多操作,清理数据 219 } 220 } 221 222 /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/dd.c#866 223 #[derive(Debug)] 224 #[allow(dead_code)] 225 struct DeviceAttachData { 226 dev: Arc<dyn Device>, 227 228 /// Indicates whether we are considering asynchronous probing or 229 /// not. Only initial binding after device or driver registration 230 /// (including deferral processing) may be done asynchronously, the 231 /// rest is always synchronous, as we expect it is being done by 232 /// request from userspace. 233 check_async: bool, 234 235 /// Indicates if we are binding synchronous or asynchronous drivers. 236 /// When asynchronous probing is enabled we'll execute 2 passes 237 /// over drivers: first pass doing synchronous probing and second 238 /// doing asynchronous probing (if synchronous did not succeed - 239 /// most likely because there was no driver requiring synchronous 240 /// probing - and we found asynchronous driver during first pass). 241 /// The 2 passes are done because we can't shoot asynchronous 242 /// probe for given device and driver from bus_for_each_drv() since 243 /// driver pointer is not guaranteed to stay valid once 244 /// bus_for_each_drv() iterates to the next driver on the bus. 245 want_async: bool, 246 247 /// We'll set have_async to 'true' if, while scanning for matching 248 /// driver, we'll encounter one that requests asynchronous probing. 249 have_async: bool, 250 } 251 252 impl DeviceAttachData { 253 pub fn new(dev: Arc<dyn Device>, check_async: bool, want_async: bool) -> Self { 254 Self { 255 dev, 256 check_async, 257 want_async, 258 have_async: false, 259 } 260 } 261 262 #[allow(dead_code)] 263 #[inline(always)] 264 fn set_have_async(&mut self) { 265 self.have_async = true; 266 } 267 } 268 269 impl DriverManager { 270 /// 尝试把驱动绑定到现有的设备上 271 /// 272 /// 这个函数会遍历驱动现有的全部设备,然后尝试把他们匹配。 273 /// 一旦有一个设备匹配成功,就会返回,并且设备的driver字段会被设置。 274 pub fn driver_attach(&self, driver: &Arc<dyn Driver>) -> Result<(), SystemError> { 275 let bus = driver 276 .bus() 277 .and_then(|bus| bus.upgrade()) 278 .ok_or(SystemError::EINVAL)?; 279 for dev in bus.subsystem().devices().iter() { 280 if self.do_driver_attach(dev, driver) { 281 // 匹配成功 282 return Ok(()); 283 } 284 } 285 286 return Ok(()); 287 } 288 289 /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/dd.c?fi=driver_attach#1134 290 fn do_driver_attach(&self, device: &Arc<dyn Device>, driver: &Arc<dyn Driver>) -> bool { 291 let r = self.match_device(driver, device).unwrap_or(false); 292 if !r { 293 // 不匹配 294 return false; 295 } 296 297 if driver.allows_async_probing() { 298 unimplemented!( 299 "do_driver_attach: probe driver '{}' asynchronously", 300 driver.name() 301 ); 302 } 303 304 if self.probe_device(driver, device).is_err() { 305 return false; 306 } 307 308 return true; 309 } 310 311 #[inline(always)] 312 pub fn match_device( 313 &self, 314 driver: &Arc<dyn Driver>, 315 device: &Arc<dyn Device>, 316 ) -> Result<bool, SystemError> { 317 return driver 318 .bus() 319 .and_then(|bus| bus.upgrade()) 320 .unwrap() 321 .match_device(device, driver); 322 } 323 324 /// 尝试把设备和驱动绑定在一起 325 /// 326 /// 327 /// ## 返回 328 /// 329 /// - Ok(): 绑定成功 330 /// - Err(ENODEV): 设备未注册 331 /// - Err(EBUSY): 设备已经绑定到驱动上 332 /// 333 /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/dd.c?fi=driver_attach#802 334 fn probe_device( 335 &self, 336 driver: &Arc<dyn Driver>, 337 device: &Arc<dyn Device>, 338 ) -> Result<(), SystemError> { 339 let r = self.do_probe_device(driver, device); 340 PROBE_WAIT_QUEUE.wakeup_all(None); 341 return r; 342 } 343 344 fn do_probe_device( 345 &self, 346 driver: &Arc<dyn Driver>, 347 device: &Arc<dyn Device>, 348 ) -> Result<(), SystemError> { 349 if device.is_dead() || (!device.is_registered()) { 350 return Err(SystemError::ENODEV); 351 } 352 if device.driver().is_some() { 353 return Err(SystemError::EBUSY); 354 } 355 356 device.set_can_match(true); 357 358 self.really_probe(driver, device)?; 359 360 return Ok(()); 361 } 362 363 /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/dd.c?fi=driver_attach#584 364 fn really_probe( 365 &self, 366 driver: &Arc<dyn Driver>, 367 device: &Arc<dyn Device>, 368 ) -> Result<(), SystemError> { 369 let bind_failed = || { 370 device_manager().unbind_cleanup(device); 371 }; 372 373 let sysfs_failed = || { 374 if let Some(bus) = device.bus().and_then(|bus| bus.upgrade()) { 375 bus.subsystem().bus_notifier().call_chain( 376 BusNotifyEvent::DriverNotBound, 377 Some(device), 378 None, 379 ); 380 } 381 }; 382 383 let probe_failed = || { 384 self.remove_from_sysfs(device); 385 }; 386 387 let dev_groups_failed = || { 388 device_manager().remove(device); 389 }; 390 391 device.set_driver(Some(Arc::downgrade(driver))); 392 393 self.add_to_sysfs(device).map_err(|e| { 394 kerror!( 395 "really_probe: add_to_sysfs failed, dev: '{}', err: {:?}", 396 device.name(), 397 e 398 ); 399 sysfs_failed(); 400 bind_failed(); 401 e 402 })?; 403 404 self.call_driver_probe(device, driver).map_err(|e| { 405 kerror!( 406 "really_probe: call_driver_probe failed, dev: '{}', err: {:?}", 407 device.name(), 408 e 409 ); 410 411 probe_failed(); 412 sysfs_failed(); 413 bind_failed(); 414 e 415 })?; 416 417 device_manager() 418 .add_groups(device, driver.dev_groups()) 419 .map_err(|e| { 420 kerror!( 421 "really_probe: add_groups failed, dev: '{}', err: {:?}", 422 device.name(), 423 e 424 ); 425 dev_groups_failed(); 426 probe_failed(); 427 sysfs_failed(); 428 bind_failed(); 429 e 430 })?; 431 432 // 我们假设所有的设备都有 sync_state 这个属性。如果没有的话,也创建属性文件。 433 device_manager() 434 .create_file(device, &DeviceAttrStateSynced) 435 .map_err(|e| { 436 kerror!( 437 "really_probe: create_file failed, dev: '{}', err: {:?}", 438 device.name(), 439 e 440 ); 441 dev_groups_failed(); 442 probe_failed(); 443 sysfs_failed(); 444 bind_failed(); 445 e 446 })?; 447 448 self.driver_bound(device); 449 450 return Ok(()); 451 } 452 453 /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/dd.c?fi=driver_attach#434 454 fn add_to_sysfs(&self, device: &Arc<dyn Device>) -> Result<(), SystemError> { 455 let driver = device.driver().ok_or(SystemError::EINVAL)?; 456 457 if let Some(bus) = device.bus().and_then(|bus| bus.upgrade()) { 458 bus.subsystem().bus_notifier().call_chain( 459 BusNotifyEvent::BindDriver, 460 Some(device), 461 None, 462 ); 463 } 464 465 let driver_kobj = driver.clone() as Arc<dyn KObject>; 466 let device_kobj = device.clone() as Arc<dyn KObject>; 467 468 sysfs_instance().create_link(Some(&driver_kobj), &device_kobj, device.name())?; 469 470 let fail_rm_dev_link = || { 471 sysfs_instance().remove_link(&driver_kobj, device.name()); 472 }; 473 474 sysfs_instance() 475 .create_link(Some(&device_kobj), &driver_kobj, "driver".to_string()) 476 .map_err(|e| { 477 fail_rm_dev_link(); 478 e 479 })?; 480 481 device_manager() 482 .create_file(device, &DeviceAttrCoredump) 483 .map_err(|e| { 484 sysfs_instance().remove_link(&device_kobj, "driver".to_string()); 485 fail_rm_dev_link(); 486 e 487 })?; 488 489 return Ok(()); 490 } 491 492 /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/dd.c?fi=driver_attach#469 493 fn remove_from_sysfs(&self, _device: &Arc<dyn Device>) { 494 todo!("remove_from_sysfs") 495 } 496 497 fn call_driver_probe( 498 &self, 499 device: &Arc<dyn Device>, 500 driver: &Arc<dyn Driver>, 501 ) -> Result<(), SystemError> { 502 let bus = device 503 .bus() 504 .and_then(|bus| bus.upgrade()) 505 .ok_or(SystemError::EINVAL)?; 506 let r = bus.probe(device); 507 if r == Err(SystemError::EOPNOTSUPP_OR_ENOTSUP) { 508 kerror!( 509 "call_driver_probe: bus.probe() failed, dev: '{}', err: {:?}", 510 device.name(), 511 r 512 ); 513 return r; 514 } 515 516 if r.is_ok() { 517 return Ok(()); 518 } 519 520 let err = r.unwrap_err(); 521 match err { 522 SystemError::ENODEV | SystemError::ENXIO => { 523 kdebug!( 524 "driver'{}': probe of {} rejects match {:?}", 525 driver.name(), 526 device.name(), 527 err 528 ); 529 } 530 531 _ => { 532 kwarn!( 533 "driver'{}': probe of {} failed with error {:?}", 534 driver.name(), 535 device.name(), 536 err 537 ); 538 } 539 } 540 541 return Err(err); 542 } 543 544 /// 当设备被成功探测,进行了'设备->驱动'绑定后,调用这个函数,完成'驱动->设备'的绑定 545 /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/dd.c#393 546 fn driver_bound(&self, device: &Arc<dyn Device>) { 547 if self.driver_is_bound(device) { 548 kwarn!("driver_bound: device '{}' is already bound.", device.name()); 549 return; 550 } 551 552 let driver = device.driver().unwrap(); 553 driver.add_device(device.clone()); 554 555 if let Some(bus) = device.bus().and_then(|bus| bus.upgrade()) { 556 bus.subsystem().bus_notifier().call_chain( 557 BusNotifyEvent::BoundDriver, 558 Some(device), 559 None, 560 ); 561 } 562 563 // todo: 发送kobj bind的uevent 564 } 565 566 fn driver_is_bound(&self, device: &Arc<dyn Device>) -> bool { 567 if let Some(driver) = device.driver() { 568 if driver.find_device_by_name(&device.name()).is_some() { 569 return true; 570 } 571 } 572 573 return false; 574 } 575 } 576 577 /// 设备文件夹下的`dev`文件的属性 578 #[derive(Debug, Clone, Copy)] 579 pub struct DeviceAttrStateSynced; 580 581 impl Attribute for DeviceAttrStateSynced { 582 fn mode(&self) -> ModeType { 583 // 0o444 584 return ModeType::S_IRUGO; 585 } 586 587 fn name(&self) -> &str { 588 "state_synced" 589 } 590 591 fn show(&self, kobj: Arc<dyn KObject>, buf: &mut [u8]) -> Result<usize, SystemError> { 592 let dev = kobj.cast::<dyn Device>().map_err(|kobj| { 593 kerror!( 594 "Intertrait casting not implemented for kobj: {}", 595 kobj.name() 596 ); 597 SystemError::EOPNOTSUPP_OR_ENOTSUP 598 })?; 599 600 let val = dev.state_synced(); 601 let val = if val { 1 } else { 0 }; 602 return sysfs_emit_str(buf, format!("{}\n", val).as_str()); 603 } 604 605 fn support(&self) -> SysFSOpsSupport { 606 SysFSOpsSupport::ATTR_SHOW 607 } 608 } 609 610 #[derive(Debug)] 611 struct DeviceAttrCoredump; 612 613 impl Attribute for DeviceAttrCoredump { 614 fn name(&self) -> &str { 615 "coredump" 616 } 617 618 fn mode(&self) -> ModeType { 619 SYSFS_ATTR_MODE_WO 620 } 621 622 fn support(&self) -> SysFSOpsSupport { 623 SysFSOpsSupport::ATTR_STORE 624 } 625 626 fn store(&self, kobj: Arc<dyn KObject>, buf: &[u8]) -> Result<usize, SystemError> { 627 let dev = kobj.cast::<dyn Device>().map_err(|kobj| { 628 kerror!( 629 "Intertrait casting not implemented for kobj: {}", 630 kobj.name() 631 ); 632 SystemError::EOPNOTSUPP_OR_ENOTSUP 633 })?; 634 635 let drv = dev.driver().ok_or(SystemError::EINVAL)?; 636 drv.coredump(&dev)?; 637 638 return Ok(buf.len()); 639 } 640 } 641