xref: /freebsd/sys/kern/subr_firmware.c (revision 1e413cf93298b5b97441a21d9a50fdcd0ee9945e)
1 /*-
2  * Copyright (c) 2005, Sam Leffler <sam@errno.com>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice unmodified, this list of conditions, and the following
10  *    disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include <sys/param.h>
31 #include <sys/kernel.h>
32 #include <sys/malloc.h>
33 #include <sys/queue.h>
34 #include <sys/taskqueue.h>
35 #include <sys/systm.h>
36 #include <sys/lock.h>
37 #include <sys/mutex.h>
38 #include <sys/errno.h>
39 #include <sys/linker.h>
40 #include <sys/firmware.h>
41 #include <sys/priv.h>
42 #include <sys/proc.h>
43 #include <sys/module.h>
44 
45 /*
46  * Loadable firmware support. See sys/sys/firmware.h and firmware(9)
47  * form more details on the subsystem.
48  *
49  * 'struct firmware' is the user-visible part of the firmware table.
50  * Additional internal information is stored in a 'struct priv_fw'
51  * (currently a static array). A slot is in use if FW_INUSE is true:
52  */
53 
54 #define FW_INUSE(p)	((p)->file != NULL || (p)->fw.name != NULL)
55 
56 /*
57  * fw.name != NULL when an image is registered; file != NULL for
58  * autoloaded images whose handling has not been completed.
59  *
60  * The state of a slot evolves as follows:
61  *	firmware_register	-->  fw.name = image_name
62  *	(autoloaded image)	-->  file = module reference
63  *	firmware_unregister	-->  fw.name = NULL
64  *	(unloadentry complete)	-->  file = NULL
65  *
66  * In order for the above to work, the 'file' field must remain
67  * unchanged in firmware_unregister().
68  *
69  * Images residing in the same module are linked to each other
70  * through the 'parent' argument of firmware_register().
71  * One image (typically, one with the same name as the module to let
72  * the autoloading mechanism work) is considered the parent image for
73  * all other images in the same module. Children affect the refcount
74  * on the parent image preventing improper unloading of the image itself.
75  */
76 
77 struct priv_fw {
78 	int		refcnt;		/* reference count */
79 
80 	/*
81 	 * parent entry, see above. Set on firmware_register(),
82 	 * cleared on firmware_unregister().
83 	 */
84 	struct priv_fw	*parent;
85 
86 	int 		flags;	/* record FIRMWARE_UNLOAD requests */
87 #define FW_UNLOAD	0x100
88 
89 	/*
90 	 * 'file' is private info managed by the autoload/unload code.
91 	 * Set at the end of firmware_get(), cleared only in the
92 	 * firmware_task, so the latter can depend on its value even
93 	 * while the lock is not held.
94 	 */
95 	linker_file_t   file;	/* module file, if autoloaded */
96 
97 	/*
98 	 * 'fw' is the externally visible image information.
99 	 * We do not make it the first field in priv_fw, to avoid the
100 	 * temptation of casting pointers to each other.
101 	 * Use PRIV_FW(fw) to get a pointer to the cointainer of fw.
102 	 * Beware, PRIV_FW does not work for a NULL pointer.
103 	 */
104 	struct firmware	fw;	/* externally visible information */
105 };
106 
107 /*
108  * PRIV_FW returns the pointer to the container of struct firmware *x.
109  * Cast to intptr_t to override the 'const' attribute of x
110  */
111 #define PRIV_FW(x)	((struct priv_fw *)		\
112 	((intptr_t)(x) - offsetof(struct priv_fw, fw)) )
113 
114 /*
115  * At the moment we use a static array as backing store for the registry.
116  * Should we move to a dynamic structure, keep in mind that we cannot
117  * reallocate the array because pointers are held externally.
118  * A list may work, though.
119  */
120 #define	FIRMWARE_MAX	30
121 static struct priv_fw firmware_table[FIRMWARE_MAX];
122 
123 /*
124  * module release are handled in a separate task as they might sleep.
125  */
126 struct task firmware_task;
127 
128 /*
129  * This mutex protects accesses to the firmware table.
130  */
131 struct mtx firmware_mtx;
132 MTX_SYSINIT(firmware, &firmware_mtx, "firmware table", MTX_DEF);
133 
134 /*
135  * Helper function to lookup a name.
136  * As a side effect, it sets the pointer to a free slot, if any.
137  * This way we can concentrate most of the registry scanning in
138  * this function, which makes it easier to replace the registry
139  * with some other data structure.
140  */
141 static struct priv_fw *
142 lookup(const char *name, struct priv_fw **empty_slot)
143 {
144 	struct priv_fw *fp = NULL;
145 	struct priv_fw *dummy;
146 	int i;
147 
148 	if (empty_slot == NULL)
149 		empty_slot = &dummy;
150 	*empty_slot = NULL;
151 	for (i = 0; i < FIRMWARE_MAX; i++) {
152 		fp = &firmware_table[i];
153 		if (fp->fw.name != NULL && strcasecmp(name, fp->fw.name) == 0)
154 			break;
155 		else if (!FW_INUSE(fp))
156 			*empty_slot = fp;
157 	}
158 	return (i < FIRMWARE_MAX ) ? fp : NULL;
159 }
160 
161 /*
162  * Register a firmware image with the specified name.  The
163  * image name must not already be registered.  If this is a
164  * subimage then parent refers to a previously registered
165  * image that this should be associated with.
166  */
167 const struct firmware *
168 firmware_register(const char *imagename, const void *data, size_t datasize,
169     unsigned int version, const struct firmware *parent)
170 {
171 	struct priv_fw *match, *frp;
172 
173 	mtx_lock(&firmware_mtx);
174 	/*
175 	 * Do a lookup to make sure the name is unique or find a free slot.
176 	 */
177 	match = lookup(imagename, &frp);
178 	if (match != NULL) {
179 		mtx_unlock(&firmware_mtx);
180 		printf("%s: image %s already registered!\n",
181 			__func__, imagename);
182 		return NULL;
183 	}
184 	if (frp == NULL) {
185 		mtx_unlock(&firmware_mtx);
186 		printf("%s: cannot register image %s, firmware table full!\n",
187 		    __func__, imagename);
188 		return NULL;
189 	}
190 	bzero(frp, sizeof(frp));	/* start from a clean record */
191 	frp->fw.name = imagename;
192 	frp->fw.data = data;
193 	frp->fw.datasize = datasize;
194 	frp->fw.version = version;
195 	if (parent != NULL) {
196 		frp->parent = PRIV_FW(parent);
197 		frp->parent->refcnt++;
198 	}
199 	mtx_unlock(&firmware_mtx);
200 	if (bootverbose)
201 		printf("firmware: '%s' version %u: %zu bytes loaded at %p\n",
202 		    imagename, version, datasize, data);
203 	return &frp->fw;
204 }
205 
206 /*
207  * Unregister/remove a firmware image.  If there are outstanding
208  * references an error is returned and the image is not removed
209  * from the registry.
210  */
211 int
212 firmware_unregister(const char *imagename)
213 {
214 	struct priv_fw *fp;
215 	int err;
216 
217 	mtx_lock(&firmware_mtx);
218 	fp = lookup(imagename, NULL);
219 	if (fp == NULL) {
220 		/*
221 		 * It is ok for the lookup to fail; this can happen
222 		 * when a module is unloaded on last reference and the
223 		 * module unload handler unregister's each of it's
224 		 * firmware images.
225 		 */
226 		err = 0;
227 	} else if (fp->refcnt != 0) {	/* cannot unregister */
228 		err = EBUSY;
229 	}  else {
230 		linker_file_t   x = fp->file;	/* save value */
231 
232 		if (fp->parent != NULL)	/* release parent reference */
233 			fp->parent->refcnt--;
234 		/*
235 		 * Clear the whole entry with bzero to make sure we
236 		 * do not forget anything. Then restore 'file' which is
237 		 * non-null for autoloaded images.
238 		 */
239 		bzero(fp, sizeof(struct priv_fw));
240 		fp->file = x;
241 		err = 0;
242 	}
243 	mtx_unlock(&firmware_mtx);
244 	return err;
245 }
246 
247 /*
248  * Lookup and potentially load the specified firmware image.
249  * If the firmware is not found in the registry, try to load a kernel
250  * module named as the image name.
251  * If the firmware is located, a reference is returned. The caller must
252  * release this reference for the image to be eligible for removal/unload.
253  */
254 const struct firmware *
255 firmware_get(const char *imagename)
256 {
257 	struct thread *td;
258 	struct priv_fw *fp;
259 	linker_file_t result;
260 
261 	mtx_lock(&firmware_mtx);
262 	fp = lookup(imagename, NULL);
263 	if (fp != NULL)
264 		goto found;
265 	/*
266 	 * Image not present, try to load the module holding it.
267 	 */
268 	mtx_unlock(&firmware_mtx);
269 	td = curthread;
270 	if (priv_check(td, PRIV_FIRMWARE_LOAD) != 0 ||
271 	    securelevel_gt(td->td_ucred, 0) != 0) {
272 		printf("%s: insufficient privileges to "
273 		    "load firmware image %s\n", __func__, imagename);
274 		return NULL;
275 	}
276 	(void) linker_reference_module(imagename, NULL, &result);
277 	/*
278 	 * After loading the module, see if the image is registered now.
279 	 */
280 	mtx_lock(&firmware_mtx);
281 	fp = lookup(imagename, NULL);
282 	if (fp == NULL) {
283 		mtx_unlock(&firmware_mtx);
284 		printf("%s: failed to load firmware image %s\n",
285 			__func__, imagename);
286 		(void) linker_release_module(imagename, NULL, NULL);
287 		return NULL;
288 	}
289 	fp->file = result;	/* record the module identity */
290 
291 found:				/* common exit point on success */
292 	fp->refcnt++;
293 	mtx_unlock(&firmware_mtx);
294 	return &fp->fw;
295 }
296 
297 /*
298  * Release a reference to a firmware image returned by firmware_get.
299  * The caller may specify, with the FIRMWARE_UNLOAD flag, its desire
300  * to release the resource, but the flag is only advisory.
301  *
302  * If this is the last reference to the firmware image, and this is an
303  * autoloaded module, wake up the firmware_task to figure out what to do
304  * with the associated module.
305  */
306 void
307 firmware_put(const struct firmware *p, int flags)
308 {
309 	struct priv_fw *fp = PRIV_FW(p);
310 
311 	mtx_lock(&firmware_mtx);
312 	fp->refcnt--;
313 	if (fp->refcnt == 0) {
314 		if (flags & FIRMWARE_UNLOAD)
315 			fp->flags |= FW_UNLOAD;
316 		if (fp->file)
317 			taskqueue_enqueue(taskqueue_thread, &firmware_task);
318 	}
319 	mtx_unlock(&firmware_mtx);
320 }
321 
322 /*
323  * The body of the task in charge of unloading autoloaded modules
324  * that are not needed anymore.
325  * Images can be cross-linked so we may need to make multiple passes,
326  * but the time we spend in the loop is bounded because we clear entries
327  * as we touch them.
328  */
329 static void
330 unloadentry(void *unused1, int unused2)
331 {
332 	int limit = FIRMWARE_MAX;
333 	int i;	/* current cycle */
334 
335 	mtx_lock(&firmware_mtx);
336 	/*
337 	 * Scan the table. limit is set to make sure we make another
338 	 * full sweep after matching an entry that requires unloading.
339 	 */
340 	for (i = 0; i < limit; i++) {
341 		struct priv_fw *fp;
342 		int err;
343 
344 		fp = &firmware_table[i % FIRMWARE_MAX];
345 		if (fp->fw.name == NULL || fp->file == NULL ||
346 		    fp->refcnt != 0 || (fp->flags & FW_UNLOAD) == 0)
347 			continue;
348 
349 		/*
350 		 * Found an entry. Now:
351 		 * 1. bump up limit to make sure we make another full round;
352 		 * 2. clear FW_UNLOAD so we don't try this entry again.
353 		 * 3. release the lock while trying to unload the module.
354 		 * 'file' remains set so that the entry cannot be reused
355 		 * in the meantime (it also means that fp->file will
356 		 * not change while we release the lock).
357 		 */
358 		limit = i + FIRMWARE_MAX;	/* make another full round */
359 		fp->flags &= ~FW_UNLOAD;	/* do not try again */
360 
361 		mtx_unlock(&firmware_mtx);
362 		err = linker_release_module(NULL, NULL, fp->file);
363 		mtx_lock(&firmware_mtx);
364 
365 		/*
366 		 * We rely on the module to call firmware_unregister()
367 		 * on unload to actually release the entry.
368 		 * If err = 0 we can drop our reference as the system
369 		 * accepted it. Otherwise unloading failed (e.g. the
370 		 * module itself gave an error) so our reference is
371 		 * still valid.
372 		 */
373 		if (err == 0)
374 			fp->file = NULL;
375 	}
376 	mtx_unlock(&firmware_mtx);
377 }
378 
379 /*
380  * Module glue.
381  */
382 static int
383 firmware_modevent(module_t mod, int type, void *unused)
384 {
385 	struct priv_fw *fp;
386 	int i, err = EINVAL;
387 
388 	switch (type) {
389 	case MOD_LOAD:
390 		TASK_INIT(&firmware_task, 0, unloadentry, NULL);
391 		return 0;
392 
393 	case MOD_UNLOAD:
394 		/* request all autoloaded modules to be released */
395 		mtx_lock(&firmware_mtx);
396 		for (i = 0; i < FIRMWARE_MAX; i++) {
397 			fp = &firmware_table[i];
398 			fp->flags |= FW_UNLOAD;;
399 		}
400 		mtx_unlock(&firmware_mtx);
401 		taskqueue_enqueue(taskqueue_thread, &firmware_task);
402 		taskqueue_drain(taskqueue_thread, &firmware_task);
403 		for (i = 0; i < FIRMWARE_MAX; i++) {
404 			fp = &firmware_table[i];
405 			if (fp->fw.name != NULL) {
406 				printf("%s: image %p ref %d still active slot %d\n",
407 					__func__, fp->fw.name,
408 					fp->refcnt,  i);
409 				err = EINVAL;
410 			}
411 		}
412 		return err;
413 	}
414 	return EINVAL;
415 }
416 
417 static moduledata_t firmware_mod = {
418 	"firmware",
419 	firmware_modevent,
420 	0
421 };
422 DECLARE_MODULE(firmware, firmware_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
423 MODULE_VERSION(firmware, 1);
424