xref: /freebsd/stand/lua/core.lua (revision 21795c374aceb685dbdb1bd18c7a5c41c3cf0baf)
1--
2-- SPDX-License-Identifier: BSD-2-Clause
3--
4-- Copyright (c) 2015 Pedro Souza <pedrosouza@freebsd.org>
5-- Copyright (c) 2018 Kyle Evans <kevans@FreeBSD.org>
6-- All rights reserved.
7--
8-- Redistribution and use in source and binary forms, with or without
9-- modification, are permitted provided that the following conditions
10-- are met:
11-- 1. Redistributions of source code must retain the above copyright
12--    notice, this list of conditions and the following disclaimer.
13-- 2. Redistributions in binary form must reproduce the above copyright
14--    notice, this list of conditions and the following disclaimer in the
15--    documentation and/or other materials provided with the distribution.
16--
17-- THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20-- ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23-- OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24-- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25-- LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26-- OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27-- SUCH DAMAGE.
28--
29
30local config = require("config")
31local hook = require("hook")
32
33local core = {}
34
35local default_acpi = false
36local default_safe_mode = false
37local default_single_user = false
38local default_verbose = false
39
40local bootenv_list = "bootenvs"
41
42local function composeLoaderCmd(cmd_name, argstr)
43	if argstr ~= nil then
44		cmd_name = cmd_name .. " " .. argstr
45	end
46	return cmd_name
47end
48
49local function recordDefaults()
50	local boot_single = loader.getenv("boot_single") or "no"
51	local boot_verbose = loader.getenv("boot_verbose") or "no"
52
53	default_acpi = core.getACPI()
54	default_single_user = boot_single:lower() ~= "no"
55	default_verbose = boot_verbose:lower() ~= "no"
56
57	core.setACPI(default_acpi)
58	core.setSingleUser(default_single_user)
59	core.setVerbose(default_verbose)
60end
61
62
63-- Globals
64-- try_include will return the loaded module on success, or false and the error
65-- message on failure.
66function try_include(module)
67	if module:sub(1, 1) ~= "/" then
68		local lua_path = loader.lua_path
69		-- XXX Temporary compat shim; this should be removed once the
70		-- loader.lua_path export has sufficiently spread.
71		if lua_path == nil then
72			lua_path = "/boot/lua"
73		end
74		module = lua_path .. "/" .. module
75		-- We only attempt to append an extension if an absolute path
76		-- wasn't specified.  This assumes that the caller either wants
77		-- to treat this like it would require() and specify just the
78		-- base filename, or they know what they're doing as they've
79		-- specified an absolute path and we shouldn't impede.
80		if module:match(".lua$") == nil then
81			module = module .. ".lua"
82		end
83	end
84	if lfs.attributes(module, "mode") ~= "file" then
85		return
86	end
87
88	return dofile(module)
89end
90
91-- Module exports
92-- Commonly appearing constants
93core.KEY_BACKSPACE	= 8
94core.KEY_ENTER		= 13
95core.KEY_DELETE		= 127
96
97-- Note that this is a decimal representation, despite the leading 0 that in
98-- other contexts (outside of Lua) may mean 'octal'
99core.KEYSTR_ESCAPE	= "\027"
100core.KEYSTR_CSI		= core.KEYSTR_ESCAPE .. "["
101core.KEYSTR_RESET	= core.KEYSTR_ESCAPE .. "c"
102
103core.MENU_RETURN	= "return"
104core.MENU_ENTRY		= "entry"
105core.MENU_SEPARATOR	= "separator"
106core.MENU_SUBMENU	= "submenu"
107core.MENU_CAROUSEL_ENTRY	= "carousel_entry"
108
109function core.setVerbose(verbose)
110	if verbose == nil then
111		verbose = not core.verbose
112	end
113
114	if verbose then
115		loader.setenv("boot_verbose", "YES")
116	else
117		loader.unsetenv("boot_verbose")
118	end
119	core.verbose = verbose
120end
121
122function core.setSingleUser(single_user)
123	if single_user == nil then
124		single_user = not core.su
125	end
126
127	if single_user then
128		loader.setenv("boot_single", "YES")
129	else
130		loader.unsetenv("boot_single")
131	end
132	core.su = single_user
133end
134
135function core.hasACPI()
136	return loader.getenv("acpi.rsdp") ~= nil
137end
138
139function core.isX86()
140	return loader.machine_arch == "i386" or loader.machine_arch == "amd64"
141end
142
143function core.getACPI()
144	if not core.hasACPI() then
145		-- x86 requires ACPI pretty much
146		return false or core.isX86()
147	end
148
149	-- Otherwise, respect disabled if it's set
150	local c = loader.getenv("hint.acpi.0.disabled")
151	return c == nil or tonumber(c) ~= 1
152end
153
154function core.setACPI(acpi)
155	if acpi == nil then
156		acpi = not core.acpi
157	end
158
159	if acpi then
160		loader.setenv("acpi_load", "YES")
161		loader.setenv("hint.acpi.0.disabled", "0")
162		loader.unsetenv("loader.acpi_disabled_by_user")
163	else
164		loader.unsetenv("acpi_load")
165		loader.setenv("hint.acpi.0.disabled", "1")
166		loader.setenv("loader.acpi_disabled_by_user", "1")
167	end
168	core.acpi = acpi
169end
170
171function core.setSafeMode(safe_mode)
172	if safe_mode == nil then
173		safe_mode = not core.sm
174	end
175	if safe_mode then
176		loader.setenv("kern.smp.disabled", "1")
177		loader.setenv("hw.ata.ata_dma", "0")
178		loader.setenv("hw.ata.atapi_dma", "0")
179		loader.setenv("hw.ata.wc", "0")
180		loader.setenv("kern.eventtimer.periodic", "1")
181		loader.setenv("kern.geom.part.check_integrity", "0")
182	else
183		loader.unsetenv("kern.smp.disabled")
184		loader.unsetenv("hw.ata.ata_dma")
185		loader.unsetenv("hw.ata.atapi_dma")
186		loader.unsetenv("hw.ata.wc")
187		loader.unsetenv("kern.eventtimer.periodic")
188		loader.unsetenv("kern.geom.part.check_integrity")
189	end
190	core.sm = safe_mode
191end
192
193function core.clearCachedKernels()
194	-- Clear the kernel cache on config changes, autodetect might have
195	-- changed or if we've switched boot environments then we could have
196	-- a new kernel set.
197	core.cached_kernels = nil
198end
199
200function core.kernelList()
201	if core.cached_kernels ~= nil then
202		return core.cached_kernels
203	end
204
205	local k = loader.getenv("kernel")
206	local v = loader.getenv("kernels")
207	local autodetect = loader.getenv("kernels_autodetect") or ""
208
209	local kernels = {}
210	local unique = {}
211	local i = 0
212	if k ~= nil then
213		i = i + 1
214		kernels[i] = k
215		unique[k] = true
216	end
217
218	if v ~= nil then
219		for n in v:gmatch("([^;, ]+)[;, ]?") do
220			if unique[n] == nil then
221				i = i + 1
222				kernels[i] = n
223				unique[n] = true
224			end
225		end
226	end
227
228	-- Do not attempt to autodetect if underlying filesystem
229	-- do not support directory listing (e.g. tftp, http)
230	if not lfs.attributes("/boot", "mode") then
231		autodetect = "no"
232		loader.setenv("kernels_autodetect", "NO")
233	end
234
235	-- Base whether we autodetect kernels or not on a loader.conf(5)
236	-- setting, kernels_autodetect. If it's set to 'yes', we'll add
237	-- any kernels we detect based on the criteria described.
238	if autodetect:lower() ~= "yes" then
239		core.cached_kernels = kernels
240		return core.cached_kernels
241	end
242
243	-- Automatically detect other bootable kernel directories using a
244	-- heuristic.  Any directory in /boot that contains an ordinary file
245	-- named "kernel" is considered eligible.
246	for file, ftype in lfs.dir("/boot") do
247		local fname = "/boot/" .. file
248
249		if file == "." or file == ".." then
250			goto continue
251		end
252
253		if ftype then
254			if ftype ~= lfs.DT_DIR then
255				goto continue
256			end
257		elseif lfs.attributes(fname, "mode") ~= "directory" then
258			goto continue
259		end
260
261		if lfs.attributes(fname .. "/kernel", "mode") ~= "file" then
262			goto continue
263		end
264
265		if unique[file] == nil then
266			i = i + 1
267			kernels[i] = file
268			unique[file] = true
269		end
270
271		::continue::
272	end
273	core.cached_kernels = kernels
274	return core.cached_kernels
275end
276
277function core.bootenvDefault()
278	return loader.getenv("zfs_be_active")
279end
280
281function core.bootenvList()
282	local bootenv_count = tonumber(loader.getenv(bootenv_list .. "_count"))
283	local bootenvs = {}
284	local curenv
285	local envcount = 0
286	local unique = {}
287
288	if bootenv_count == nil or bootenv_count <= 0 then
289		return bootenvs
290	end
291
292	-- Currently selected bootenv is always first/default
293	-- On the rewinded list the bootenv may not exists
294	if core.isRewinded() then
295		curenv = core.bootenvDefaultRewinded()
296	else
297		curenv = core.bootenvDefault()
298	end
299	if curenv ~= nil then
300		envcount = envcount + 1
301		bootenvs[envcount] = curenv
302		unique[curenv] = true
303	end
304
305	for curenv_idx = 0, bootenv_count - 1 do
306		curenv = loader.getenv(bootenv_list .. "[" .. curenv_idx .. "]")
307		if curenv ~= nil and unique[curenv] == nil then
308			envcount = envcount + 1
309			bootenvs[envcount] = curenv
310			unique[curenv] = true
311		end
312	end
313	return bootenvs
314end
315
316function core.isCheckpointed()
317	return loader.getenv("zpool_checkpoint") ~= nil
318end
319
320function core.bootenvDefaultRewinded()
321	local defname =  "zfs:!" .. string.sub(core.bootenvDefault(), 5)
322	local bootenv_count = tonumber("bootenvs_check_count")
323
324	if bootenv_count == nil or bootenv_count <= 0 then
325		return defname
326	end
327
328	for curenv_idx = 0, bootenv_count - 1 do
329		local curenv = loader.getenv("bootenvs_check[" .. curenv_idx .. "]")
330		if curenv == defname then
331			return defname
332		end
333	end
334
335	return loader.getenv("bootenvs_check[0]")
336end
337
338function core.isRewinded()
339	return bootenv_list == "bootenvs_check"
340end
341
342function core.changeRewindCheckpoint()
343	if core.isRewinded() then
344		bootenv_list = "bootenvs"
345	else
346		bootenv_list = "bootenvs_check"
347	end
348end
349
350function core.loadEntropy()
351	if core.isUEFIBoot() then
352		if (loader.getenv("entropy_efi_seed") or "no"):lower() == "yes" then
353			loader.perform("efi-seed-entropy")
354		end
355	end
356end
357
358function core.setDefaults()
359	core.setACPI(default_acpi)
360	core.setSafeMode(default_safe_mode)
361	core.setSingleUser(default_single_user)
362	core.setVerbose(default_verbose)
363end
364
365function core.autoboot(argstr)
366	-- loadelf() only if we've not already loaded a kernel
367	if loader.getenv("kernelname") == nil then
368		config.loadelf()
369	end
370	core.loadEntropy()
371	loader.perform(composeLoaderCmd("autoboot", argstr))
372end
373
374function core.boot(argstr)
375	-- loadelf() only if we've not already loaded a kernel
376	if loader.getenv("kernelname") == nil then
377		config.loadelf()
378	end
379	core.loadEntropy()
380	loader.perform(composeLoaderCmd("boot", argstr))
381end
382
383function core.isSingleUserBoot()
384	local single_user = loader.getenv("boot_single")
385	return single_user ~= nil and single_user:lower() == "yes"
386end
387
388function core.isUEFIBoot()
389	local efiver = loader.getenv("efi-version")
390
391	return efiver ~= nil
392end
393
394function core.isZFSBoot()
395	local c = loader.getenv("currdev")
396
397	if c ~= nil then
398		return c:match("^zfs:") ~= nil
399	end
400	return false
401end
402
403function core.isFramebufferConsole()
404	local c = loader.getenv("console")
405	if c ~= nil then
406		if c:find("efi") == nil and c:find("vidconsole") == nil then
407			return false
408		end
409		if loader.getenv("screen.depth") ~= nil then
410			return true
411		end
412	end
413	return false
414end
415
416function core.isSerialConsole()
417	local c = loader.getenv("console")
418	if c ~= nil then
419		-- serial console is comconsole, but also userboot.
420		-- userboot is there, because we have no way to know
421		-- if the user terminal can draw unicode box chars or not.
422		if c:find("comconsole") ~= nil or c:find("userboot") ~= nil then
423			return true
424		end
425	end
426	return false
427end
428
429function core.isSerialBoot()
430	local s = loader.getenv("boot_serial")
431	if s ~= nil then
432		return true
433	end
434
435	local m = loader.getenv("boot_multicons")
436	if m ~= nil then
437		return true
438	end
439	return false
440end
441
442-- Is the menu skipped in the environment in which we've booted?
443function core.isMenuSkipped()
444	return string.lower(loader.getenv("beastie_disable") or "") == "yes"
445end
446
447-- This may be a better candidate for a 'utility' module.
448function core.deepCopyTable(tbl)
449	local new_tbl = {}
450	for k, v in pairs(tbl) do
451		if type(v) == "table" then
452			new_tbl[k] = core.deepCopyTable(v)
453		else
454			new_tbl[k] = v
455		end
456	end
457	return new_tbl
458end
459
460-- XXX This should go away if we get the table lib into shape for importing.
461-- As of now, it requires some 'os' functions, so we'll implement this in lua
462-- for our uses
463function core.popFrontTable(tbl)
464	-- Shouldn't reasonably happen
465	if #tbl == 0 then
466		return nil, nil
467	elseif #tbl == 1 then
468		return tbl[1], {}
469	end
470
471	local first_value = tbl[1]
472	local new_tbl = {}
473	-- This is not a cheap operation
474	for k, v in ipairs(tbl) do
475		if k > 1 then
476			new_tbl[k - 1] = v
477		end
478	end
479
480	return first_value, new_tbl
481end
482
483function core.getConsoleName()
484	if loader.getenv("boot_multicons") ~= nil then
485		if loader.getenv("boot_serial") ~= nil then
486			return "Dual (Serial primary)"
487		else
488			return "Dual (Video primary)"
489		end
490	else
491		if loader.getenv("boot_serial") ~= nil then
492			return "Serial"
493		else
494			return "Video"
495		end
496	end
497end
498
499function core.nextConsoleChoice()
500	if loader.getenv("boot_multicons") ~= nil then
501		if loader.getenv("boot_serial") ~= nil then
502			loader.unsetenv("boot_serial")
503		else
504			loader.unsetenv("boot_multicons")
505			loader.setenv("boot_serial", "YES")
506		end
507	else
508		if loader.getenv("boot_serial") ~= nil then
509			loader.unsetenv("boot_serial")
510		else
511			loader.setenv("boot_multicons", "YES")
512			loader.setenv("boot_serial", "YES")
513		end
514	end
515end
516
517recordDefaults()
518hook.register("config.reloaded", core.clearCachedKernels)
519return core
520