blob: 3054d2b432c9f999b4af4ad6ead812deeb0c662c [file] [log] [blame]
Steve Muckle18b981e2019-04-15 17:43:02 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <modprobe/modprobe.h>
18
19#include <fnmatch.h>
20#include <sys/stat.h>
21#include <sys/syscall.h>
22
23#include <algorithm>
Chungkaic60300a2021-02-03 20:30:07 -080024#include <map>
Steve Muckle18b981e2019-04-15 17:43:02 -070025#include <set>
26#include <string>
Chungkaic60300a2021-02-03 20:30:07 -080027#include <thread>
Steve Muckle18b981e2019-04-15 17:43:02 -070028#include <vector>
29
30#include <android-base/chrono_utils.h>
31#include <android-base/file.h>
32#include <android-base/logging.h>
33#include <android-base/strings.h>
34#include <android-base/unique_fd.h>
35
36std::string Modprobe::MakeCanonical(const std::string& module_path) {
37 auto start = module_path.find_last_of('/');
38 if (start == std::string::npos) {
39 start = 0;
40 } else {
41 start += 1;
42 }
43 auto end = module_path.size();
44 if (android::base::EndsWith(module_path, ".ko")) {
45 end -= 3;
46 }
47 if ((end - start) <= 1) {
48 LOG(ERROR) << "malformed module name: " << module_path;
49 return "";
50 }
51 std::string module_name = module_path.substr(start, end - start);
52 // module names can have '-', but their file names will have '_'
53 std::replace(module_name.begin(), module_name.end(), '-', '_');
54 return module_name;
55}
56
57bool Modprobe::ParseDepCallback(const std::string& base_path,
58 const std::vector<std::string>& args) {
59 std::vector<std::string> deps;
60 std::string prefix = "";
61
62 // Set first item as our modules path
63 std::string::size_type pos = args[0].find(':');
64 if (args[0][0] != '/') {
65 prefix = base_path + "/";
66 }
67 if (pos != std::string::npos) {
68 deps.emplace_back(prefix + args[0].substr(0, pos));
69 } else {
70 LOG(ERROR) << "dependency lines must start with name followed by ':'";
Andrew Scullfb18f6e2020-10-18 17:37:27 +010071 return false;
Steve Muckle18b981e2019-04-15 17:43:02 -070072 }
73
74 // Remaining items are dependencies of our module
75 for (auto arg = args.begin() + 1; arg != args.end(); ++arg) {
76 if ((*arg)[0] != '/') {
77 prefix = base_path + "/";
78 } else {
79 prefix = "";
80 }
81 deps.push_back(prefix + *arg);
82 }
83
84 std::string canonical_name = MakeCanonical(args[0].substr(0, pos));
85 if (canonical_name.empty()) {
86 return false;
87 }
88 this->module_deps_[canonical_name] = deps;
89
90 return true;
91}
92
93bool Modprobe::ParseAliasCallback(const std::vector<std::string>& args) {
94 auto it = args.begin();
95 const std::string& type = *it++;
96
97 if (type != "alias") {
98 LOG(ERROR) << "non-alias line encountered in modules.alias, found " << type;
99 return false;
100 }
101
102 if (args.size() != 3) {
103 LOG(ERROR) << "alias lines in modules.alias must have 3 entries, not " << args.size();
104 return false;
105 }
106
107 const std::string& alias = *it++;
108 const std::string& module_name = *it++;
109 this->module_aliases_.emplace_back(alias, module_name);
110
111 return true;
112}
113
114bool Modprobe::ParseSoftdepCallback(const std::vector<std::string>& args) {
115 auto it = args.begin();
116 const std::string& type = *it++;
117 std::string state = "";
118
119 if (type != "softdep") {
120 LOG(ERROR) << "non-softdep line encountered in modules.softdep, found " << type;
121 return false;
122 }
123
124 if (args.size() < 4) {
125 LOG(ERROR) << "softdep lines in modules.softdep must have at least 4 entries";
126 return false;
127 }
128
129 const std::string& module = *it++;
130 while (it != args.end()) {
131 const std::string& token = *it++;
132 if (token == "pre:" || token == "post:") {
133 state = token;
134 continue;
135 }
136 if (state == "") {
137 LOG(ERROR) << "malformed modules.softdep at token " << token;
138 return false;
139 }
140 if (state == "pre:") {
141 this->module_pre_softdep_.emplace_back(module, token);
142 } else {
143 this->module_post_softdep_.emplace_back(module, token);
144 }
145 }
146
147 return true;
148}
149
150bool Modprobe::ParseLoadCallback(const std::vector<std::string>& args) {
151 auto it = args.begin();
152 const std::string& module = *it++;
153
154 const std::string& canonical_name = MakeCanonical(module);
155 if (canonical_name.empty()) {
156 return false;
157 }
158 this->module_load_.emplace_back(canonical_name);
159
160 return true;
161}
162
163bool Modprobe::ParseOptionsCallback(const std::vector<std::string>& args) {
164 auto it = args.begin();
165 const std::string& type = *it++;
166
167 if (type != "options") {
168 LOG(ERROR) << "non-options line encountered in modules.options";
169 return false;
170 }
171
172 if (args.size() < 2) {
173 LOG(ERROR) << "lines in modules.options must have at least 2 entries, not " << args.size();
174 return false;
175 }
176
177 const std::string& module = *it++;
178 std::string options = "";
179
180 const std::string& canonical_name = MakeCanonical(module);
181 if (canonical_name.empty()) {
182 return false;
183 }
184
185 while (it != args.end()) {
186 options += *it++;
187 if (it != args.end()) {
188 options += " ";
189 }
190 }
191
192 auto [unused, inserted] = this->module_options_.emplace(canonical_name, options);
193 if (!inserted) {
194 LOG(ERROR) << "multiple options lines present for module " << module;
195 return false;
196 }
197 return true;
198}
199
Mark Salyzyn703fb742020-06-15 11:51:59 -0700200bool Modprobe::ParseBlocklistCallback(const std::vector<std::string>& args) {
Steve Mucklee31f8402019-07-31 14:34:52 -0700201 auto it = args.begin();
202 const std::string& type = *it++;
203
Mark Salyzyn9debda12020-06-16 05:14:06 -0700204 if (type != "blocklist") {
Mark Salyzyn703fb742020-06-15 11:51:59 -0700205 LOG(ERROR) << "non-blocklist line encountered in modules.blocklist";
Steve Mucklee31f8402019-07-31 14:34:52 -0700206 return false;
207 }
208
209 if (args.size() != 2) {
Mark Salyzyn703fb742020-06-15 11:51:59 -0700210 LOG(ERROR) << "lines in modules.blocklist must have exactly 2 entries, not " << args.size();
Steve Mucklee31f8402019-07-31 14:34:52 -0700211 return false;
212 }
213
214 const std::string& module = *it++;
215
216 const std::string& canonical_name = MakeCanonical(module);
217 if (canonical_name.empty()) {
218 return false;
219 }
Mark Salyzyn703fb742020-06-15 11:51:59 -0700220 this->module_blocklist_.emplace(canonical_name);
Steve Mucklee31f8402019-07-31 14:34:52 -0700221
222 return true;
223}
224
Steve Muckle18b981e2019-04-15 17:43:02 -0700225void Modprobe::ParseCfg(const std::string& cfg,
226 std::function<bool(const std::vector<std::string>&)> f) {
227 std::string cfg_contents;
228 if (!android::base::ReadFileToString(cfg, &cfg_contents, false)) {
229 return;
230 }
231
232 std::vector<std::string> lines = android::base::Split(cfg_contents, "\n");
233 for (const std::string line : lines) {
234 if (line.empty() || line[0] == '#') {
235 continue;
236 }
237 const std::vector<std::string> args = android::base::Split(line, " ");
238 if (args.empty()) continue;
239 f(args);
240 }
241 return;
242}
243
Steve Muckle373a3ca2019-12-06 17:08:09 -0800244void Modprobe::AddOption(const std::string& module_name, const std::string& option_name,
245 const std::string& value) {
246 auto canonical_name = MakeCanonical(module_name);
247 auto options_iter = module_options_.find(canonical_name);
248 auto option_str = option_name + "=" + value;
249 if (options_iter != module_options_.end()) {
250 options_iter->second = options_iter->second + " " + option_str;
251 } else {
252 module_options_.emplace(canonical_name, option_str);
253 }
254}
255
256void Modprobe::ParseKernelCmdlineOptions(void) {
257 std::string cmdline = GetKernelCmdline();
258 std::string module_name = "";
259 std::string option_name = "";
260 std::string value = "";
261 bool in_module = true;
262 bool in_option = false;
263 bool in_value = false;
264 bool in_quotes = false;
265 int start = 0;
266
267 for (int i = 0; i < cmdline.size(); i++) {
268 if (cmdline[i] == '"') {
269 in_quotes = !in_quotes;
270 }
271
272 if (in_quotes) continue;
273
274 if (cmdline[i] == ' ') {
275 if (in_value) {
276 value = cmdline.substr(start, i - start);
277 if (!module_name.empty() && !option_name.empty()) {
278 AddOption(module_name, option_name, value);
279 }
280 }
281 module_name = "";
282 option_name = "";
283 value = "";
284 in_value = false;
285 start = i + 1;
286 in_module = true;
287 continue;
288 }
289
290 if (cmdline[i] == '.') {
291 if (in_module) {
292 module_name = cmdline.substr(start, i - start);
293 start = i + 1;
294 in_module = false;
295 }
296 in_option = true;
297 continue;
298 }
299
300 if (cmdline[i] == '=') {
301 if (in_option) {
302 option_name = cmdline.substr(start, i - start);
303 start = i + 1;
304 in_option = false;
305 }
306 in_value = true;
307 continue;
308 }
309 }
310 if (in_value && !in_quotes) {
311 value = cmdline.substr(start, cmdline.size() - start);
312 if (!module_name.empty() && !option_name.empty()) {
313 AddOption(module_name, option_name, value);
314 }
315 }
316}
317
Will McVicker87b2ef02021-03-12 11:11:37 -0800318Modprobe::Modprobe(const std::vector<std::string>& base_paths, const std::string load_file,
319 bool use_blocklist)
320 : blocklist_enabled(use_blocklist) {
Steve Muckle18b981e2019-04-15 17:43:02 -0700321 using namespace std::placeholders;
322
323 for (const auto& base_path : base_paths) {
324 auto alias_callback = std::bind(&Modprobe::ParseAliasCallback, this, _1);
325 ParseCfg(base_path + "/modules.alias", alias_callback);
326
327 auto dep_callback = std::bind(&Modprobe::ParseDepCallback, this, base_path, _1);
328 ParseCfg(base_path + "/modules.dep", dep_callback);
329
330 auto softdep_callback = std::bind(&Modprobe::ParseSoftdepCallback, this, _1);
331 ParseCfg(base_path + "/modules.softdep", softdep_callback);
332
333 auto load_callback = std::bind(&Modprobe::ParseLoadCallback, this, _1);
Steve Muckle4c593232020-04-03 17:47:10 -0700334 ParseCfg(base_path + "/" + load_file, load_callback);
Steve Muckle18b981e2019-04-15 17:43:02 -0700335
336 auto options_callback = std::bind(&Modprobe::ParseOptionsCallback, this, _1);
337 ParseCfg(base_path + "/modules.options", options_callback);
Steve Mucklee31f8402019-07-31 14:34:52 -0700338
Mark Salyzyn703fb742020-06-15 11:51:59 -0700339 auto blocklist_callback = std::bind(&Modprobe::ParseBlocklistCallback, this, _1);
340 ParseCfg(base_path + "/modules.blocklist", blocklist_callback);
Steve Muckle18b981e2019-04-15 17:43:02 -0700341 }
Steve Muckleded44c02019-08-01 16:03:02 -0700342
Steve Muckle373a3ca2019-12-06 17:08:09 -0800343 ParseKernelCmdlineOptions();
Steve Muckle18b981e2019-04-15 17:43:02 -0700344}
345
346std::vector<std::string> Modprobe::GetDependencies(const std::string& module) {
347 auto it = module_deps_.find(module);
348 if (it == module_deps_.end()) {
349 return {};
350 }
351 return it->second;
352}
353
Steve Muckle13700a62019-07-31 09:59:48 -0700354bool Modprobe::InsmodWithDeps(const std::string& module_name, const std::string& parameters) {
Steve Muckle18b981e2019-04-15 17:43:02 -0700355 if (module_name.empty()) {
356 LOG(ERROR) << "Need valid module name, given: " << module_name;
357 return false;
358 }
359
360 auto dependencies = GetDependencies(module_name);
361 if (dependencies.empty()) {
362 LOG(ERROR) << "Module " << module_name << " not in dependency file";
363 return false;
364 }
365
366 // load module dependencies in reverse order
367 for (auto dep = dependencies.rbegin(); dep != dependencies.rend() - 1; ++dep) {
Steve Muckleded44c02019-08-01 16:03:02 -0700368 LOG(VERBOSE) << "Loading hard dep for '" << module_name << "': " << *dep;
Steve Muckle73b29282019-07-30 16:03:44 -0700369 if (!LoadWithAliases(*dep, true)) {
Steve Muckle18b981e2019-04-15 17:43:02 -0700370 return false;
371 }
372 }
373
374 // try to load soft pre-dependencies
375 for (const auto& [module, softdep] : module_pre_softdep_) {
376 if (module_name == module) {
Steve Muckleded44c02019-08-01 16:03:02 -0700377 LOG(VERBOSE) << "Loading soft pre-dep for '" << module << "': " << softdep;
Steve Muckle18b981e2019-04-15 17:43:02 -0700378 LoadWithAliases(softdep, false);
379 }
380 }
381
382 // load target module itself with args
Steve Muckle13700a62019-07-31 09:59:48 -0700383 if (!Insmod(dependencies[0], parameters)) {
Steve Muckle18b981e2019-04-15 17:43:02 -0700384 return false;
385 }
386
387 // try to load soft post-dependencies
388 for (const auto& [module, softdep] : module_post_softdep_) {
389 if (module_name == module) {
Steve Muckleded44c02019-08-01 16:03:02 -0700390 LOG(VERBOSE) << "Loading soft post-dep for '" << module << "': " << softdep;
Steve Muckle18b981e2019-04-15 17:43:02 -0700391 LoadWithAliases(softdep, false);
392 }
393 }
394
395 return true;
396}
397
Steve Muckle13700a62019-07-31 09:59:48 -0700398bool Modprobe::LoadWithAliases(const std::string& module_name, bool strict,
399 const std::string& parameters) {
Mark Salyzyn8c105192019-10-29 08:38:55 -0700400 auto canonical_name = MakeCanonical(module_name);
401 if (module_loaded_.count(canonical_name)) {
402 return true;
403 }
404
405 std::set<std::string> modules_to_load = {canonical_name};
Steve Muckle18b981e2019-04-15 17:43:02 -0700406 bool module_loaded = false;
407
408 // use aliases to expand list of modules to load (multiple modules
409 // may alias themselves to the requested name)
410 for (const auto& [alias, aliased_module] : module_aliases_) {
411 if (fnmatch(alias.c_str(), module_name.c_str(), 0) != 0) continue;
Steve Muckleded44c02019-08-01 16:03:02 -0700412 LOG(VERBOSE) << "Found alias for '" << module_name << "': '" << aliased_module;
Mark Salyzyn8c105192019-10-29 08:38:55 -0700413 if (module_loaded_.count(MakeCanonical(aliased_module))) continue;
Steve Muckle18b981e2019-04-15 17:43:02 -0700414 modules_to_load.emplace(aliased_module);
415 }
416
417 // attempt to load all modules aliased to this name
418 for (const auto& module : modules_to_load) {
419 if (!ModuleExists(module)) continue;
Steve Muckle13700a62019-07-31 09:59:48 -0700420 if (InsmodWithDeps(module, parameters)) module_loaded = true;
Steve Muckle18b981e2019-04-15 17:43:02 -0700421 }
422
423 if (strict && !module_loaded) {
Steve Muckleded44c02019-08-01 16:03:02 -0700424 LOG(ERROR) << "LoadWithAliases was unable to load " << module_name;
Steve Muckle18b981e2019-04-15 17:43:02 -0700425 return false;
426 }
427 return true;
428}
429
Will McVicker87b2ef02021-03-12 11:11:37 -0800430bool Modprobe::IsBlocklisted(const std::string& module_name) {
431 if (!blocklist_enabled) return false;
432
433 auto canonical_name = MakeCanonical(module_name);
434 auto dependencies = GetDependencies(canonical_name);
435 for (auto dep = dependencies.begin(); dep != dependencies.end(); ++dep) {
436 if (module_blocklist_.count(MakeCanonical(*dep))) return true;
437 }
438
439 return module_blocklist_.count(canonical_name) > 0;
440}
441
Chungkaic60300a2021-02-03 20:30:07 -0800442// Another option to load kernel modules. load in independent modules in parallel
443// and then load modules which only have soft dependency, third update dependency list of other
444// remaining modules, repeat these steps until all modules are loaded.
445bool Modprobe::LoadModulesParallel(int num_threads) {
446 bool ret = true;
447 std::map<std::string, std::set<std::string>> mod_with_deps;
448 std::map<std::string, std::set<std::string>> mod_with_softdeps;
449
450 // Get dependencies
451 for (const auto& module : module_load_) {
452 auto dependencies = GetDependencies(MakeCanonical(module));
453
454 for (auto dep = dependencies.rbegin(); dep != dependencies.rend(); dep++) {
455 mod_with_deps[module].emplace(*dep);
456 }
457 }
458
459 // Get soft dependencies
460 for (const auto& [it_mod, it_softdep] : module_pre_softdep_) {
461 mod_with_softdeps[MakeCanonical(it_mod)].emplace(it_softdep);
462 }
463
464 // Get soft post dependencies
465 for (const auto& [it_mod, it_softdep] : module_post_softdep_) {
466 mod_with_softdeps[MakeCanonical(it_mod)].emplace(it_softdep);
467 }
468
469 while (!mod_with_deps.empty()) {
470 std::vector<std::thread> threads;
471 std::vector<std::string> mods_path_to_load;
472 std::vector<std::string> mods_with_softdep_to_load;
473 std::mutex vector_lock;
474
475 // Find independent modules and modules only having soft dependencies
476 for (const auto& [it_mod, it_dep] : mod_with_deps) {
477 if (it_dep.size() == 1 && mod_with_softdeps[it_mod].empty()) {
478 mods_path_to_load.emplace_back(*(it_dep.begin()));
479 } else if (it_dep.size() == 1) {
480 mods_with_softdep_to_load.emplace_back(it_mod);
481 }
482 }
483
484 // Load independent modules in parallel
485 auto thread_function = [&] {
486 std::unique_lock lk(vector_lock);
487 while (!mods_path_to_load.empty()) {
488 auto mod_path_to_load = std::move(mods_path_to_load.back());
489 mods_path_to_load.pop_back();
490
491 lk.unlock();
492 ret &= Insmod(mod_path_to_load, "");
493 lk.lock();
494 }
495 };
496
497 std::generate_n(std::back_inserter(threads), num_threads,
498 [&] { return std::thread(thread_function); });
499
500 // Wait for the threads.
501 for (auto& thread : threads) {
502 thread.join();
503 }
504
505 // Since we cannot assure if these soft dependencies tree are overlap,
506 // we loaded these modules one by one.
507 for (auto dep = mods_with_softdep_to_load.rbegin(); dep != mods_with_softdep_to_load.rend();
508 dep++) {
509 ret &= LoadWithAliases(*dep, true);
510 }
511
512 std::lock_guard guard(module_loaded_lock_);
513 // Remove loaded module form mod_with_deps and soft dependencies of other modules
514 for (const auto& module_loaded : module_loaded_) {
515 mod_with_deps.erase(module_loaded);
516
517 for (auto& [mod, softdeps] : mod_with_softdeps) {
518 softdeps.erase(module_loaded);
519 }
520 }
521
522 // Remove loaded module form dependencies of other modules which are not loaded yet
523 for (const auto& module_loaded_path : module_loaded_paths_) {
524 for (auto& [mod, deps] : mod_with_deps) {
525 deps.erase(module_loaded_path);
526 }
527 }
528 }
529
530 return ret;
531}
532
Mark Salyzynd4782712019-10-29 09:32:09 -0700533bool Modprobe::LoadListedModules(bool strict) {
534 auto ret = true;
Steve Muckle18b981e2019-04-15 17:43:02 -0700535 for (const auto& module : module_load_) {
536 if (!LoadWithAliases(module, true)) {
Will McVicker87b2ef02021-03-12 11:11:37 -0800537 if (IsBlocklisted(module)) continue;
Mark Salyzynd4782712019-10-29 09:32:09 -0700538 ret = false;
539 if (strict) break;
Steve Muckle18b981e2019-04-15 17:43:02 -0700540 }
541 }
Mark Salyzynd4782712019-10-29 09:32:09 -0700542 return ret;
Steve Muckle18b981e2019-04-15 17:43:02 -0700543}
Steve Mucklebb58b012019-07-30 11:58:11 -0700544
545bool Modprobe::Remove(const std::string& module_name) {
546 auto dependencies = GetDependencies(MakeCanonical(module_name));
Will McVicker87b2ef02021-03-12 11:11:37 -0800547 for (auto dep = dependencies.begin(); dep != dependencies.end(); ++dep) {
Steve Mucklebb58b012019-07-30 11:58:11 -0700548 Rmmod(*dep);
549 }
Will McVicker87b2ef02021-03-12 11:11:37 -0800550 Rmmod(module_name);
Steve Mucklebb58b012019-07-30 11:58:11 -0700551 return true;
552}
Steve Muckle012cfa12019-07-31 15:55:00 -0700553
554std::vector<std::string> Modprobe::ListModules(const std::string& pattern) {
555 std::vector<std::string> rv;
556 for (const auto& [module, deps] : module_deps_) {
557 // Attempt to match both the canonical module name and the module filename.
558 if (!fnmatch(pattern.c_str(), module.c_str(), 0)) {
559 rv.emplace_back(module);
560 } else if (!fnmatch(pattern.c_str(), basename(deps[0].c_str()), 0)) {
561 rv.emplace_back(deps[0]);
562 }
563 }
564 return rv;
565}
Steve Muckle781aa782019-08-01 14:55:07 -0700566
567bool Modprobe::GetAllDependencies(const std::string& module,
568 std::vector<std::string>* pre_dependencies,
569 std::vector<std::string>* dependencies,
570 std::vector<std::string>* post_dependencies) {
571 std::string canonical_name = MakeCanonical(module);
572 if (pre_dependencies) {
573 pre_dependencies->clear();
574 for (const auto& [it_module, it_softdep] : module_pre_softdep_) {
575 if (canonical_name == it_module) {
576 pre_dependencies->emplace_back(it_softdep);
577 }
578 }
579 }
580 if (dependencies) {
581 dependencies->clear();
582 auto hard_deps = GetDependencies(canonical_name);
583 if (hard_deps.empty()) {
584 return false;
585 }
586 for (auto dep = hard_deps.rbegin(); dep != hard_deps.rend(); dep++) {
587 dependencies->emplace_back(*dep);
588 }
589 }
590 if (post_dependencies) {
591 for (const auto& [it_module, it_softdep] : module_post_softdep_) {
592 if (canonical_name == it_module) {
593 post_dependencies->emplace_back(it_softdep);
594 }
595 }
596 }
597 return true;
598}