xref: /freebsd/stand/lua/core.lua (revision c2ba66d4d01f23303352bfe3cbd50ff5d9a05947)
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	-- We can't trust acpi.rsdp to be set if the loader binary doesn't do
137	-- ACPI detection early enough.  UEFI loader historically didn't, so
138	-- we'll fallback to assuming ACPI is enabled if this binary does not
139	-- declare that it probes for ACPI early enough
140	if loader.getenv("acpi.rsdp") ~= nil then
141		return true
142	end
143
144	return not core.hasFeature("EARLY_ACPI")
145end
146
147function core.getACPI()
148	if not core.hasACPI() then
149		return false
150	end
151
152	-- Otherwise, respect disabled if it's set
153	local c = loader.getenv("hint.acpi.0.disabled")
154	return c == nil or tonumber(c) ~= 1
155end
156
157function core.setACPI(acpi)
158	if acpi == nil then
159		acpi = not core.acpi
160	end
161
162	if acpi then
163		config.enableModule("acpi")
164		loader.setenv("hint.acpi.0.disabled", "0")
165	else
166		config.disableModule("acpi")
167		loader.setenv("hint.acpi.0.disabled", "1")
168	end
169	core.acpi = acpi
170end
171
172function core.setSafeMode(safe_mode)
173	if safe_mode == nil then
174		safe_mode = not core.sm
175	end
176	if safe_mode then
177		loader.setenv("kern.smp.disabled", "1")
178		loader.setenv("hw.ata.ata_dma", "0")
179		loader.setenv("hw.ata.atapi_dma", "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("kern.eventtimer.periodic")
187		loader.unsetenv("kern.geom.part.check_integrity")
188	end
189	core.sm = safe_mode
190end
191
192function core.clearCachedKernels()
193	-- Clear the kernel cache on config changes, autodetect might have
194	-- changed or if we've switched boot environments then we could have
195	-- a new kernel set.
196	core.cached_kernels = nil
197end
198
199function core.kernelList()
200	if core.cached_kernels ~= nil then
201		return core.cached_kernels
202	end
203
204	local default_kernel = loader.getenv("kernel")
205	local v = loader.getenv("kernels")
206	local autodetect = loader.getenv("kernels_autodetect") or ""
207
208	local kernels = {}
209	local unique = {}
210	local i = 0
211
212	if default_kernel then
213		i = i + 1
214		kernels[i] = default_kernel
215		unique[default_kernel] = 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	local present = {}
244
245	-- Automatically detect other bootable kernel directories using a
246	-- heuristic.  Any directory in /boot that contains an ordinary file
247	-- named "kernel" is considered eligible.
248	for file, ftype in lfs.dir("/boot") do
249		local fname = "/boot/" .. file
250
251		if file == "." or file == ".." then
252			goto continue
253		end
254
255		if ftype then
256			if ftype ~= lfs.DT_DIR then
257				goto continue
258			end
259		elseif lfs.attributes(fname, "mode") ~= "directory" then
260			goto continue
261		end
262
263		if lfs.attributes(fname .. "/kernel", "mode") ~= "file" then
264			goto continue
265		end
266
267		if unique[file] == nil then
268			i = i + 1
269			kernels[i] = file
270			unique[file] = true
271		end
272
273		present[file] = true
274
275		::continue::
276	end
277
278	-- If we found more than one kernel, prune the "kernel" specified kernel
279	-- off of the list if it wasn't found during traversal.  If we didn't
280	-- actually find any kernels, we just assume that they know what they're
281	-- doing and leave it alone.
282	if default_kernel and not present[default_kernel] and #kernels > 1 then
283		for i = 1, #kernels do
284			if i == #kernels then
285				kernels[i] = nil
286			else
287				kernels[i] = kernels[i + 1]
288			end
289		end
290	end
291
292	core.cached_kernels = kernels
293	return core.cached_kernels
294end
295
296function core.bootenvDefault()
297	return loader.getenv("zfs_be_active")
298end
299
300function core.bootenvList()
301	local bootenv_count = tonumber(loader.getenv(bootenv_list .. "_count"))
302	local bootenvs = {}
303	local curenv
304	local envcount = 0
305	local unique = {}
306
307	if bootenv_count == nil or bootenv_count <= 0 then
308		return bootenvs
309	end
310
311	-- Currently selected bootenv is always first/default
312	-- On the rewinded list the bootenv may not exists
313	if core.isRewinded() then
314		curenv = core.bootenvDefaultRewinded()
315	else
316		curenv = core.bootenvDefault()
317	end
318	if curenv ~= nil then
319		envcount = envcount + 1
320		bootenvs[envcount] = curenv
321		unique[curenv] = true
322	end
323
324	for curenv_idx = 0, bootenv_count - 1 do
325		curenv = loader.getenv(bootenv_list .. "[" .. curenv_idx .. "]")
326		if curenv ~= nil and unique[curenv] == nil then
327			envcount = envcount + 1
328			bootenvs[envcount] = curenv
329			unique[curenv] = true
330		end
331	end
332	return bootenvs
333end
334
335function core.isCheckpointed()
336	return loader.getenv("zpool_checkpoint") ~= nil
337end
338
339function core.bootenvDefaultRewinded()
340	local defname =  "zfs:!" .. string.sub(core.bootenvDefault(), 5)
341	local bootenv_count = tonumber("bootenvs_check_count")
342
343	if bootenv_count == nil or bootenv_count <= 0 then
344		return defname
345	end
346
347	for curenv_idx = 0, bootenv_count - 1 do
348		local curenv = loader.getenv("bootenvs_check[" .. curenv_idx .. "]")
349		if curenv == defname then
350			return defname
351		end
352	end
353
354	return loader.getenv("bootenvs_check[0]")
355end
356
357function core.isRewinded()
358	return bootenv_list == "bootenvs_check"
359end
360
361function core.changeRewindCheckpoint()
362	if core.isRewinded() then
363		bootenv_list = "bootenvs"
364	else
365		bootenv_list = "bootenvs_check"
366	end
367end
368
369function core.loadEntropy()
370	if core.isUEFIBoot() then
371		if (loader.getenv("entropy_efi_seed") or "no"):lower() == "yes" then
372			local seedsize = loader.getenv("entropy_efi_seed_size") or "2048"
373			loader.perform("efi-seed-entropy " .. seedsize)
374		end
375	end
376end
377
378function core.setDefaults()
379	core.setACPI(default_acpi)
380	core.setSafeMode(default_safe_mode)
381	core.setSingleUser(default_single_user)
382	core.setVerbose(default_verbose)
383end
384
385function core.autoboot(argstr)
386	-- loadelf() only if we've not already loaded a kernel
387	if loader.getenv("kernelname") == nil then
388		config.loadelf()
389	end
390	core.loadEntropy()
391	loader.perform(composeLoaderCmd("autoboot", argstr))
392end
393
394function core.boot(argstr)
395	-- loadelf() only if we've not already loaded a kernel
396	if loader.getenv("kernelname") == nil then
397		config.loadelf()
398	end
399	core.loadEntropy()
400	loader.perform(composeLoaderCmd("boot", argstr))
401end
402
403function core.hasFeature(name)
404	if not loader.has_feature then
405		-- Loader too old, no feature support
406		return nil, "No feature support in loaded loader"
407	end
408
409	return loader.has_feature(name)
410end
411
412function core.isSingleUserBoot()
413	local single_user = loader.getenv("boot_single")
414	return single_user ~= nil and single_user:lower() == "yes"
415end
416
417function core.isUEFIBoot()
418	local efiver = loader.getenv("efi-version")
419
420	return efiver ~= nil
421end
422
423function core.isZFSBoot()
424	local c = loader.getenv("currdev")
425
426	if c ~= nil then
427		return c:match("^zfs:") ~= nil
428	end
429	return false
430end
431
432function core.isFramebufferConsole()
433	local c = loader.getenv("console")
434	if c ~= nil then
435		if c:find("efi") == nil and c:find("vidconsole") == nil then
436			return false
437		end
438		if loader.getenv("screen.depth") ~= nil then
439			return true
440		end
441	end
442	return false
443end
444
445function core.isSerialConsole()
446	local c = loader.getenv("console")
447	if c ~= nil then
448		-- serial console is comconsole, but also userboot.
449		-- userboot is there, because we have no way to know
450		-- if the user terminal can draw unicode box chars or not.
451		if c:find("comconsole") ~= nil or c:find("userboot") ~= nil then
452			return true
453		end
454	end
455	return false
456end
457
458function core.isSerialBoot()
459	local s = loader.getenv("boot_serial")
460	if s ~= nil then
461		return true
462	end
463
464	local m = loader.getenv("boot_multicons")
465	if m ~= nil then
466		return true
467	end
468	return false
469end
470
471-- Is the menu skipped in the environment in which we've booted?
472function core.isMenuSkipped()
473	return string.lower(loader.getenv("beastie_disable") or "") == "yes"
474end
475
476-- This may be a better candidate for a 'utility' module.
477function core.deepCopyTable(tbl)
478	local new_tbl = {}
479	for k, v in pairs(tbl) do
480		if type(v) == "table" then
481			new_tbl[k] = core.deepCopyTable(v)
482		else
483			new_tbl[k] = v
484		end
485	end
486	return new_tbl
487end
488
489-- XXX This should go away if we get the table lib into shape for importing.
490-- As of now, it requires some 'os' functions, so we'll implement this in lua
491-- for our uses
492function core.popFrontTable(tbl)
493	-- Shouldn't reasonably happen
494	if #tbl == 0 then
495		return nil, nil
496	elseif #tbl == 1 then
497		return tbl[1], {}
498	end
499
500	local first_value = tbl[1]
501	local new_tbl = {}
502	-- This is not a cheap operation
503	for k, v in ipairs(tbl) do
504		if k > 1 then
505			new_tbl[k - 1] = v
506		end
507	end
508
509	return first_value, new_tbl
510end
511
512function core.getConsoleName()
513	if loader.getenv("boot_multicons") ~= nil then
514		if loader.getenv("boot_serial") ~= nil then
515			return "Dual (Serial primary)"
516		else
517			return "Dual (Video primary)"
518		end
519	else
520		if loader.getenv("boot_serial") ~= nil then
521			return "Serial"
522		else
523			return "Video"
524		end
525	end
526end
527
528function core.nextConsoleChoice()
529	if loader.getenv("boot_multicons") ~= nil then
530		if loader.getenv("boot_serial") ~= nil then
531			loader.unsetenv("boot_serial")
532		else
533			loader.unsetenv("boot_multicons")
534			loader.setenv("boot_serial", "YES")
535		end
536	else
537		if loader.getenv("boot_serial") ~= nil then
538			loader.unsetenv("boot_serial")
539		else
540			loader.setenv("boot_multicons", "YES")
541			loader.setenv("boot_serial", "YES")
542		end
543	end
544end
545
546-- The graphical-enabled loaders have unicode drawing character support. The
547-- text-only ones do not. We check the old and new bindings for term_drawrect as
548-- a proxy for unicode support, which will work on older boot loaders as well
549-- as be future proof for when we remove the old binding. This also abstracts
550-- out the test to one spot in case we start to export this notion more directly.
551function core.hasUnicode()
552	 return gfx.term_drawrect ~= nil or loader.term_drawrect ~= nil
553end
554
555-- Sanity check the boot loader revision
556-- Loaders with version 3.0 have everything that we need without backwards
557-- compatible hacks. Warn users that still have old versions to upgrade so
558-- that we can remove the backwards compatible hacks in the future since
559-- they have been there a long time.
560local loader_major = 3
561
562function core.loaderTooOld()
563	return loader.version == nil or loader.version < loader_major * 1000
564end
565
566if core.loaderTooOld() then
567	print("**********************************************************************")
568	print("**********************************************************************")
569	print("*****                                                            *****")
570	print("*****           BOOT LOADER IS TOO OLD. PLEASE UPGRADE.          *****")
571	print("*****                                                            *****")
572	print("**********************************************************************")
573	print("**********************************************************************")
574end
575
576recordDefaults()
577hook.register("config.reloaded", core.clearCachedKernels)
578return core
579