core.lua revision 352349
1--
2-- SPDX-License-Identifier: BSD-2-Clause-FreeBSD
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-- $FreeBSD: stable/11/stand/lua/core.lua 352349 2019-09-15 02:48:15Z kevans $
30--
31
32local config = require("config")
33local hook = require("hook")
34
35local core = {}
36
37local default_safe_mode = false
38local default_single_user = false
39local default_verbose = false
40
41local function composeLoaderCmd(cmd_name, argstr)
42	if argstr ~= nil then
43		cmd_name = cmd_name .. " " .. argstr
44	end
45	return cmd_name
46end
47
48local function recordDefaults()
49	-- On i386, hint.acpi.0.rsdp will be set before we're loaded. On !i386,
50	-- it will generally be set upon execution of the kernel. Because of
51	-- this, we can't (or don't really want to) detect/disable ACPI on !i386
52	-- reliably. Just set it enabled if we detect it and leave well enough
53	-- alone if we don't.
54	local boot_acpi = core.isSystem386() and core.getACPIPresent(false)
55	local boot_single = loader.getenv("boot_single") or "no"
56	local boot_verbose = loader.getenv("boot_verbose") or "no"
57	default_single_user = boot_single:lower() ~= "no"
58	default_verbose = boot_verbose:lower() ~= "no"
59
60	if boot_acpi then
61		core.setACPI(true)
62	end
63	core.setSingleUser(default_single_user)
64	core.setVerbose(default_verbose)
65end
66
67
68-- Globals
69-- try_include will return the loaded module on success, or false and the error
70-- message on failure.
71function try_include(module)
72	local status, ret = pcall(require, module)
73	-- ret is the module if we succeeded.
74	if status then
75		return ret
76	end
77	return false, ret
78end
79
80-- Module exports
81-- Commonly appearing constants
82core.KEY_BACKSPACE	= 8
83core.KEY_ENTER		= 13
84core.KEY_DELETE		= 127
85
86-- Note that this is a decimal representation, despite the leading 0 that in
87-- other contexts (outside of Lua) may mean 'octal'
88core.KEYSTR_ESCAPE	= "\027"
89core.KEYSTR_CSI		= core.KEYSTR_ESCAPE .. "["
90
91core.MENU_RETURN	= "return"
92core.MENU_ENTRY		= "entry"
93core.MENU_SEPARATOR	= "separator"
94core.MENU_SUBMENU	= "submenu"
95core.MENU_CAROUSEL_ENTRY	= "carousel_entry"
96
97function core.setVerbose(verbose)
98	if verbose == nil then
99		verbose = not core.verbose
100	end
101
102	if verbose then
103		loader.setenv("boot_verbose", "YES")
104	else
105		loader.unsetenv("boot_verbose")
106	end
107	core.verbose = verbose
108end
109
110function core.setSingleUser(single_user)
111	if single_user == nil then
112		single_user = not core.su
113	end
114
115	if single_user then
116		loader.setenv("boot_single", "YES")
117	else
118		loader.unsetenv("boot_single")
119	end
120	core.su = single_user
121end
122
123function core.getACPIPresent(checking_system_defaults)
124	local c = loader.getenv("hint.acpi.0.rsdp")
125
126	if c ~= nil then
127		if checking_system_defaults then
128			return true
129		end
130		-- Otherwise, respect disabled if it's set
131		c = loader.getenv("hint.acpi.0.disabled")
132		return c == nil or tonumber(c) ~= 1
133	end
134	return false
135end
136
137function core.setACPI(acpi)
138	if acpi == nil then
139		acpi = not core.acpi
140	end
141
142	if acpi then
143		loader.setenv("acpi_load", "YES")
144		loader.setenv("hint.acpi.0.disabled", "0")
145		loader.unsetenv("loader.acpi_disabled_by_user")
146	else
147		loader.unsetenv("acpi_load")
148		loader.setenv("hint.acpi.0.disabled", "1")
149		loader.setenv("loader.acpi_disabled_by_user", "1")
150	end
151	core.acpi = acpi
152end
153
154function core.setSafeMode(safe_mode)
155	if safe_mode == nil then
156		safe_mode = not core.sm
157	end
158	if safe_mode then
159		loader.setenv("kern.smp.disabled", "1")
160		loader.setenv("hw.ata.ata_dma", "0")
161		loader.setenv("hw.ata.atapi_dma", "0")
162		loader.setenv("hw.ata.wc", "0")
163		loader.setenv("hw.eisa_slots", "0")
164		loader.setenv("kern.eventtimer.periodic", "1")
165		loader.setenv("kern.geom.part.check_integrity", "0")
166	else
167		loader.unsetenv("kern.smp.disabled")
168		loader.unsetenv("hw.ata.ata_dma")
169		loader.unsetenv("hw.ata.atapi_dma")
170		loader.unsetenv("hw.ata.wc")
171		loader.unsetenv("hw.eisa_slots")
172		loader.unsetenv("kern.eventtimer.periodic")
173		loader.unsetenv("kern.geom.part.check_integrity")
174	end
175	core.sm = safe_mode
176end
177
178function core.clearCachedKernels()
179	-- Clear the kernel cache on config changes, autodetect might have
180	-- changed or if we've switched boot environments then we could have
181	-- a new kernel set.
182	core.cached_kernels = nil
183end
184
185function core.kernelList()
186	if core.cached_kernels ~= nil then
187		return core.cached_kernels
188	end
189
190	local k = loader.getenv("kernel")
191	local v = loader.getenv("kernels")
192	local autodetect = loader.getenv("kernels_autodetect") or ""
193
194	local kernels = {}
195	local unique = {}
196	local i = 0
197	if k ~= nil then
198		i = i + 1
199		kernels[i] = k
200		unique[k] = true
201	end
202
203	if v ~= nil then
204		for n in v:gmatch("([^;, ]+)[;, ]?") do
205			if unique[n] == nil then
206				i = i + 1
207				kernels[i] = n
208				unique[n] = true
209			end
210		end
211	end
212
213	-- Base whether we autodetect kernels or not on a loader.conf(5)
214	-- setting, kernels_autodetect. If it's set to 'yes', we'll add
215	-- any kernels we detect based on the criteria described.
216	if autodetect:lower() ~= "yes" then
217		core.cached_kernels = kernels
218		return core.cached_kernels
219	end
220
221	-- Automatically detect other bootable kernel directories using a
222	-- heuristic.  Any directory in /boot that contains an ordinary file
223	-- named "kernel" is considered eligible.
224	for file in lfs.dir("/boot") do
225		local fname = "/boot/" .. file
226
227		if file == "." or file == ".." then
228			goto continue
229		end
230
231		if lfs.attributes(fname, "mode") ~= "directory" then
232			goto continue
233		end
234
235		if lfs.attributes(fname .. "/kernel", "mode") ~= "file" then
236			goto continue
237		end
238
239		if unique[file] == nil then
240			i = i + 1
241			kernels[i] = file
242			unique[file] = true
243		end
244
245		::continue::
246	end
247	core.cached_kernels = kernels
248	return core.cached_kernels
249end
250
251function core.bootenvDefault()
252	return loader.getenv("zfs_be_active")
253end
254
255function core.bootenvList()
256	local bootenv_count = tonumber(loader.getenv("bootenvs_count"))
257	local bootenvs = {}
258	local curenv
259	local envcount = 0
260	local unique = {}
261
262	if bootenv_count == nil or bootenv_count <= 0 then
263		return bootenvs
264	end
265
266	-- Currently selected bootenv is always first/default
267	curenv = core.bootenvDefault()
268	if curenv ~= nil then
269		envcount = envcount + 1
270		bootenvs[envcount] = curenv
271		unique[curenv] = true
272	end
273
274	for curenv_idx = 0, bootenv_count - 1 do
275		curenv = loader.getenv("bootenvs[" .. curenv_idx .. "]")
276		if curenv ~= nil and unique[curenv] == nil then
277			envcount = envcount + 1
278			bootenvs[envcount] = curenv
279			unique[curenv] = true
280		end
281	end
282	return bootenvs
283end
284
285function core.setDefaults()
286	core.setACPI(core.getACPIPresent(true))
287	core.setSafeMode(default_safe_mode)
288	core.setSingleUser(default_single_user)
289	core.setVerbose(default_verbose)
290end
291
292function core.autoboot(argstr)
293	-- loadelf() only if we've not already loaded a kernel
294	if loader.getenv("kernelname") == nil then
295		config.loadelf()
296	end
297	loader.perform(composeLoaderCmd("autoboot", argstr))
298end
299
300function core.boot(argstr)
301	-- loadelf() only if we've not already loaded a kernel
302	if loader.getenv("kernelname") == nil then
303		config.loadelf()
304	end
305	loader.perform(composeLoaderCmd("boot", argstr))
306end
307
308function core.isSingleUserBoot()
309	local single_user = loader.getenv("boot_single")
310	return single_user ~= nil and single_user:lower() == "yes"
311end
312
313function core.isZFSBoot()
314	local c = loader.getenv("currdev")
315
316	if c ~= nil then
317		return c:match("^zfs:") ~= nil
318	end
319	return false
320end
321
322function core.isSerialConsole()
323	local c = loader.getenv("console")
324	if c ~= nil then
325		if c:find("comconsole") ~= nil then
326			return true
327		end
328	end
329	return false
330end
331
332function core.isSerialBoot()
333	local s = loader.getenv("boot_serial")
334	if s ~= nil then
335		return true
336	end
337
338	local m = loader.getenv("boot_multicons")
339	if m ~= nil then
340		return true
341	end
342	return false
343end
344
345function core.isSystem386()
346	return loader.machine_arch == "i386"
347end
348
349-- Is the menu skipped in the environment in which we've booted?
350function core.isMenuSkipped()
351	return string.lower(loader.getenv("beastie_disable") or "") == "yes"
352end
353
354-- This may be a better candidate for a 'utility' module.
355function core.deepCopyTable(tbl)
356	local new_tbl = {}
357	for k, v in pairs(tbl) do
358		if type(v) == "table" then
359			new_tbl[k] = core.deepCopyTable(v)
360		else
361			new_tbl[k] = v
362		end
363	end
364	return new_tbl
365end
366
367-- XXX This should go away if we get the table lib into shape for importing.
368-- As of now, it requires some 'os' functions, so we'll implement this in lua
369-- for our uses
370function core.popFrontTable(tbl)
371	-- Shouldn't reasonably happen
372	if #tbl == 0 then
373		return nil, nil
374	elseif #tbl == 1 then
375		return tbl[1], {}
376	end
377
378	local first_value = tbl[1]
379	local new_tbl = {}
380	-- This is not a cheap operation
381	for k, v in ipairs(tbl) do
382		if k > 1 then
383			new_tbl[k - 1] = v
384		end
385	end
386
387	return first_value, new_tbl
388end
389
390recordDefaults()
391hook.register("config.reloaded", core.clearCachedKernels)
392return core
393