xref: /dragonfly/sys/kern/subr_firmware.c (revision 2b3f93ea6d1f70880f3e87f3c2cbe0dc0bfc9332)
1 /*-
2  * Copyright (c) 2005-2008, 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  * $FreeBSD: src/sys/kern/subr_firmware.c,v 1.13.2.2 2010/02/11 18:34:06 mjacob Exp $
27  */
28 
29 #include <sys/param.h>
30 #include <sys/kernel.h>
31 #include <sys/malloc.h>
32 #include <sys/queue.h>
33 #include <sys/taskqueue.h>
34 #include <sys/systm.h>
35 #include <sys/lock.h>
36 #include <sys/spinlock.h>
37 #include <sys/spinlock2.h>
38 #include <sys/errno.h>
39 #include <sys/linker.h>
40 #include <sys/firmware.h>
41 #include <sys/caps.h>
42 #include <sys/proc.h>
43 #include <sys/module.h>
44 #include <sys/eventhandler.h>
45 
46 #include <sys/filedesc.h>
47 #include <sys/vnode.h>
48 
49 /*
50  * Loadable firmware support. See sys/sys/firmware.h and firmware(9)
51  * form more details on the subsystem.
52  *
53  * 'struct firmware' is the user-visible part of the firmware table.
54  * Additional internal information is stored in a 'struct priv_fw'
55  * (currently a static array). A slot is in use if FW_INUSE is true:
56  */
57 
58 #define FW_INUSE(p) ((p)->file != NULL || (p)->fw.name != NULL)
59 
60 /*
61  * fw.name != NULL when an image is registered; file != NULL for
62  * autoloaded images whose handling has not been completed.
63  *
64  * The state of a slot evolves as follows:
65  *        firmware_register   -->  fw.name = image_name
66  *        (autoloaded image)  -->  file = module reference
67  *        firmware_unregister -->  fw.name = NULL
68  *        (unloadentry complete)        -->  file = NULL
69  *
70  * In order for the above to work, the 'file' field must remain
71  * unchanged in firmware_unregister().
72  *
73  * Images residing in the same module are linked to each other
74  * through the 'parent' argument of firmware_register().
75  * One image (typically, one with the same name as the module to let
76  * the autoloading mechanism work) is considered the parent image for
77  * all other images in the same module. Children affect the refcount
78  * on the parent image preventing improper unloading of the image itself.
79  */
80 
81 struct priv_fw {
82           int                 refcnt;             /* reference count */
83 
84           /*
85            * parent entry, see above. Set on firmware_register(),
86            * cleared on firmware_unregister().
87            */
88           struct priv_fw      *parent;
89 
90           int                 flags;    /* record FIRMWARE_UNLOAD requests */
91 #define FW_UNLOAD   0x100
92 
93           /*
94            * 'file' is private info managed by the autoload/unload code.
95            * Set at the end of firmware_get(), cleared only in the
96            * firmware_unload_task, so the latter can depend on its value even
97            * while the lock is not held.
98            */
99           linker_file_t   file;         /* module file, if autoloaded */
100 
101           /*
102            * 'fw' is the externally visible image information.
103            * We do not make it the first field in priv_fw, to avoid the
104            * temptation of casting pointers to each other.
105            * Use PRIV_FW(fw) to get a pointer to the cointainer of fw.
106            * Beware, PRIV_FW does not work for a NULL pointer.
107            */
108           struct firmware     fw;       /* externally visible information */
109 };
110 
111 /*
112  * PRIV_FW returns the pointer to the container of struct firmware *x.
113  * Cast to intptr_t to override the 'const' attribute of x
114  */
115 #define PRIV_FW(x)  ((struct priv_fw *)           \
116           ((intptr_t)(x) - offsetof(struct priv_fw, fw)) )
117 
118 /*
119  * At the moment we use a static array as backing store for the registry.
120  * Should we move to a dynamic structure, keep in mind that we cannot
121  * reallocate the array because pointers are held externally.
122  * A list may work, though.
123  */
124 #define   FIRMWARE_MAX        30
125 static struct priv_fw firmware_table[FIRMWARE_MAX];
126 
127 /*
128  * Firmware module operations are handled in a separate task as they
129  * might sleep and they require directory context to do i/o.
130  */
131 static struct taskqueue *firmware_tq;
132 static struct task firmware_unload_task;
133 
134 /*
135  * This lock protects accesses to the firmware table.
136  */
137 static struct lock firmware_lock;
138 
139 /*
140  * Helper function to lookup a name.
141  * As a side effect, it sets the pointer to a free slot, if any.
142  * This way we can concentrate most of the registry scanning in
143  * this function, which makes it easier to replace the registry
144  * with some other data structure.
145  */
146 static struct priv_fw *
lookup(const char * name,struct priv_fw ** empty_slot)147 lookup(const char *name, struct priv_fw **empty_slot)
148 {
149           struct priv_fw *fp = NULL;
150           struct priv_fw *dummy;
151           int i;
152 
153           if (empty_slot == NULL)
154                     empty_slot = &dummy;
155           *empty_slot = NULL;
156           for (i = 0; i < FIRMWARE_MAX; i++) {
157                     fp = &firmware_table[i];
158                     if (fp->fw.name != NULL && strcasecmp(name, fp->fw.name) == 0)
159                               break;
160                     else if (!FW_INUSE(fp))
161                               *empty_slot = fp;
162           }
163           return (i < FIRMWARE_MAX ) ? fp : NULL;
164 }
165 
166 /*
167  * Register a firmware image with the specified name.  The
168  * image name must not already be registered.  If this is a
169  * subimage then parent refers to a previously registered
170  * image that this should be associated with.
171  */
172 const struct firmware *
firmware_register(const char * imagename,const void * data,size_t datasize,unsigned int version,const struct firmware * parent)173 firmware_register(const char *imagename, const void *data, size_t datasize,
174     unsigned int version, const struct firmware *parent)
175 {
176           struct priv_fw *match, *frp;
177 
178           lockmgr(&firmware_lock, LK_EXCLUSIVE);
179           /*
180            * Do a lookup to make sure the name is unique or find a free slot.
181            */
182           match = lookup(imagename, &frp);
183           if (match != NULL) {
184                     lockmgr(&firmware_lock, LK_RELEASE);
185                     kprintf("%s: image %s already registered!\n",
186                               __func__, imagename);
187                     return NULL;
188           }
189           if (frp == NULL) {
190                     lockmgr(&firmware_lock, LK_RELEASE);
191                     kprintf("%s: cannot register image %s, firmware table full!\n",
192                         __func__, imagename);
193                     return NULL;
194           }
195           bzero(frp, sizeof(*frp));     /* start from a clean record */
196           frp->fw.name = imagename;
197           frp->fw.data = data;
198           frp->fw.datasize = datasize;
199           frp->fw.version = version;
200           if (parent != NULL) {
201                     frp->parent = PRIV_FW(parent);
202                     frp->parent->refcnt++;
203           }
204           lockmgr(&firmware_lock, LK_RELEASE);
205           if (bootverbose)
206                     kprintf("firmware: '%s' version %u: %zu bytes loaded at %p\n",
207                         imagename, version, datasize, data);
208           return &frp->fw;
209 }
210 
211 /*
212  * Unregister/remove a firmware image.  If there are outstanding
213  * references an error is returned and the image is not removed
214  * from the registry.
215  */
216 int
firmware_unregister(const char * imagename)217 firmware_unregister(const char *imagename)
218 {
219           struct priv_fw *fp;
220           int err;
221 
222           lockmgr(&firmware_lock, LK_EXCLUSIVE);
223           fp = lookup(imagename, NULL);
224           if (fp == NULL) {
225                     /*
226                      * It is ok for the lookup to fail; this can happen
227                      * when a module is unloaded on last reference and the
228                      * module unload handler unregister's each of it's
229                      * firmware images.
230                      */
231                     err = 0;
232           } else if (fp->refcnt != 0) { /* cannot unregister */
233                     err = EBUSY;
234           }  else {
235                     linker_file_t x = fp->file;   /* save value */
236 
237                     if (fp->parent != NULL)       /* release parent reference */
238                               fp->parent->refcnt--;
239                     /*
240                      * Clear the whole entry with bzero to make sure we
241                      * do not forget anything. Then restore 'file' which is
242                      * non-null for autoloaded images.
243                      */
244                     bzero(fp, sizeof(struct priv_fw));
245                     fp->file = x;
246                     err = 0;
247           }
248           lockmgr(&firmware_lock, LK_RELEASE);
249           return err;
250 }
251 
252 static void
loadimage(void * arg,int npending)253 loadimage(void *arg, int npending)
254 {
255 #ifdef notyet
256           struct thread *td = curthread;
257 #endif
258           char *imagename = arg;
259           struct priv_fw *fp;
260           linker_file_t result;
261           int error;
262 
263           /* synchronize with the thread that dispatched us */
264           lockmgr(&firmware_lock, LK_EXCLUSIVE);
265           lockmgr(&firmware_lock, LK_RELEASE);
266 
267 /* JAT
268           if (td->td_proc->p_fd->fd_rdir == NULL) {
269                     kprintf("%s: root not mounted yet, no way to load image\n",
270                         imagename);
271                     goto done;
272           }
273 */
274           error = linker_reference_module(imagename, NULL, &result);
275           if (error != 0) {
276                     kprintf("%s: could not load firmware image, error %d\n",
277                         imagename, error);
278                     goto done;
279           }
280 
281           lockmgr(&firmware_lock, LK_EXCLUSIVE);
282           fp = lookup(imagename, NULL);
283           if (fp == NULL || fp->file != NULL) {
284                     lockmgr(&firmware_lock, LK_RELEASE);
285                     if (fp == NULL)
286                               kprintf("%s: firmware image loaded, "
287                                   "but did not register\n", imagename);
288                     (void) linker_release_module(imagename, NULL, NULL);
289                     goto done;
290           }
291           fp->file = result;  /* record the module identity */
292           lockmgr(&firmware_lock, LK_RELEASE);
293 done:
294           wakeup_one(imagename);                  /* we're done */
295 }
296 
297 /*
298  * Lookup and potentially load the specified firmware image.
299  * If the firmware is not found in the registry, try to load a kernel
300  * module named as the image name.
301  * If the firmware is located, a reference is returned. The caller must
302  * release this reference for the image to be eligible for removal/unload.
303  */
304 const struct firmware *
firmware_get(const char * imagename)305 firmware_get(const char *imagename)
306 {
307           struct task fwload_task;
308           struct priv_fw *fp;
309 
310           lockmgr(&firmware_lock, LK_EXCLUSIVE);
311           fp = lookup(imagename, NULL);
312           if (fp != NULL)
313                     goto found;
314           /*
315            * Image not present, try to load the module holding it.
316            */
317           if (caps_priv_check_self(SYSCAP_NOKLD) != 0 || securelevel > 0) {
318                     lockmgr(&firmware_lock, LK_RELEASE);
319                     kprintf("%s: insufficient privileges to "
320                         "load firmware image %s\n", __func__, imagename);
321                     return NULL;
322           }
323           /*
324            * Defer load to a thread with known context.  linker_reference_module
325            * may do filesystem i/o which requires root & current dirs, etc.
326            * Also we must not hold any lock's over this call which is problematic.
327            */
328           if (!cold) {
329                     TASK_INIT(&fwload_task, 0, loadimage, __DECONST(void *,
330                         imagename));
331                     taskqueue_enqueue(firmware_tq, &fwload_task);
332                     lksleep(__DECONST(void *, imagename), &firmware_lock, 0,
333                         "fwload", 0);
334           }
335           /*
336            * After attempting to load the module, see if the image is registered.
337            */
338           fp = lookup(imagename, NULL);
339           if (fp == NULL) {
340                     lockmgr(&firmware_lock, LK_RELEASE);
341                     return NULL;
342           }
343 found:                                  /* common exit point on success */
344           fp->refcnt++;
345           lockmgr(&firmware_lock, LK_RELEASE);
346           return &fp->fw;
347 }
348 
349 /*
350  * Release a reference to a firmware image returned by firmware_get.
351  * The caller may specify, with the FIRMWARE_UNLOAD flag, its desire
352  * to release the resource, but the flag is only advisory.
353  *
354  * If this is the last reference to the firmware image, and this is an
355  * autoloaded module, wake up the firmware_unload_task to figure out
356  * what to do with the associated module.
357  */
358 void
firmware_put(const struct firmware * p,int flags)359 firmware_put(const struct firmware *p, int flags)
360 {
361           struct priv_fw *fp = PRIV_FW(p);
362 
363           lockmgr(&firmware_lock, LK_EXCLUSIVE);
364           fp->refcnt--;
365           if (fp->refcnt == 0) {
366                     if (flags & FIRMWARE_UNLOAD)
367                               fp->flags |= FW_UNLOAD;
368                     if (fp->file)
369                               taskqueue_enqueue(firmware_tq, &firmware_unload_task);
370           }
371           lockmgr(&firmware_lock, LK_RELEASE);
372 }
373 
374 #ifdef notyet
375 /*
376  * Setup directory state for the firmware_tq thread so we can do i/o.
377  */
378 static void
set_rootvnode(void * arg,int npending)379 set_rootvnode(void *arg, int npending)
380 {
381           struct thread *td = curthread;
382           struct proc *p = td->td_proc;
383 
384 
385 #if 0
386           spin_lock_wr(&p->p_fd->fd_spin);
387           if (p->p_fd->fd_cdir == NULL) {
388                     p->p_fd->fd_cdir = rootvnode;
389                     vref(rootvnode);
390           }
391           if (p->p_fd->fd_rdir == NULL) {
392                     p->p_fd->fd_rdir = rootvnode;
393                     vref(rootvnode);
394           }
395           spin_unlock_wr(&p->p_fd->fd_spin);
396 
397           kfree(arg, M_TEMP);
398 #endif
399 }
400 
401 /*
402  * Event handler called on mounting of /; bounce a task
403  * into the task queue thread to setup it's directories.
404  */
405 static void
firmware_mountroot(void * arg)406 firmware_mountroot(void *arg)
407 {
408           struct task *setroot_task;
409 
410           setroot_task = kmalloc(sizeof(struct task), M_TEMP, M_NOWAIT);
411           if (setroot_task != NULL) {
412                     TASK_INIT(setroot_task, 0, set_rootvnode, setroot_task);
413                     taskqueue_enqueue(firmware_tq, setroot_task);
414           } else
415                     kprintf("%s: no memory for task!\n", __func__);
416 }
417 EVENTHANDLER_DECLARE(mountroot, firmware_mountroot);
418 #endif
419 
420 /*
421  * The body of the task in charge of unloading autoloaded modules
422  * that are not needed anymore.
423  * Images can be cross-linked so we may need to make multiple passes,
424  * but the time we spend in the loop is bounded because we clear entries
425  * as we touch them.
426  */
427 static void
unloadentry(void * unused1,int unused2)428 unloadentry(void *unused1, int unused2)
429 {
430           int limit = FIRMWARE_MAX;
431           int i;    /* current cycle */
432 
433           lockmgr(&firmware_lock, LK_EXCLUSIVE);
434           /*
435            * Scan the table. limit is set to make sure we make another
436            * full sweep after matching an entry that requires unloading.
437            */
438           for (i = 0; i < limit; i++) {
439                     struct priv_fw *fp;
440                     int err;
441 
442                     fp = &firmware_table[i % FIRMWARE_MAX];
443                     if (fp->fw.name == NULL || fp->file == NULL ||
444                         fp->refcnt != 0 || (fp->flags & FW_UNLOAD) == 0)
445                               continue;
446 
447                     /*
448                      * Found an entry. Now:
449                      * 1. bump up limit to make sure we make another full round;
450                      * 2. clear FW_UNLOAD so we don't try this entry again.
451                      * 3. release the lock while trying to unload the module.
452                      * 'file' remains set so that the entry cannot be reused
453                      * in the meantime (it also means that fp->file will
454                      * not change while we release the lock).
455                      */
456                     limit = i + FIRMWARE_MAX;     /* make another full round */
457                     fp->flags &= ~FW_UNLOAD;      /* do not try again */
458 
459                     lockmgr(&firmware_lock, LK_RELEASE);
460                     err = linker_release_module(NULL, NULL, fp->file);
461                     lockmgr(&firmware_lock, LK_EXCLUSIVE);
462 
463                     /*
464                      * We rely on the module to call firmware_unregister()
465                      * on unload to actually release the entry.
466                      * If err = 0 we can drop our reference as the system
467                      * accepted it. Otherwise unloading failed (e.g. the
468                      * module itself gave an error) so our reference is
469                      * still valid.
470                      */
471                     if (err == 0)
472                               fp->file = NULL;
473           }
474           lockmgr(&firmware_lock, LK_RELEASE);
475 }
476 
477 /*
478  * Module glue.
479  */
480 static int
firmware_modevent(module_t mod,int type,void * unused)481 firmware_modevent(module_t mod, int type, void *unused)
482 {
483           struct priv_fw *fp;
484           int i, err;
485 
486           switch (type) {
487           case MOD_LOAD:
488                     TASK_INIT(&firmware_unload_task, 0, unloadentry, NULL);
489                     lockinit(&firmware_lock, "firmware table", 0, LK_CANRECURSE);
490                     firmware_tq = taskqueue_create("taskqueue_firmware", M_WAITOK,
491                         taskqueue_thread_enqueue, &firmware_tq);
492                     /* NB: use our own loop routine that sets up context */
493                     (void) taskqueue_start_threads(&firmware_tq, 1, TDPRI_KERN_DAEMON,
494                         -1, "firmware taskq");
495                     if (rootvnode != NULL) {
496                               /*
497                                * Root is already mounted so we won't get an event;
498                                * simulate one here.
499                                */
500 #ifdef notyet
501                               firmware_mountroot(NULL);
502 #endif
503                     }
504                     return 0;
505 
506           case MOD_UNLOAD:
507                     /* request all autoloaded modules to be released */
508                     lockmgr(&firmware_lock, LK_EXCLUSIVE);
509                     for (i = 0; i < FIRMWARE_MAX; i++) {
510                               fp = &firmware_table[i];
511                               fp->flags |= FW_UNLOAD;
512                     }
513                     lockmgr(&firmware_lock, LK_RELEASE);
514                     taskqueue_enqueue(firmware_tq, &firmware_unload_task);
515                     taskqueue_drain(firmware_tq, &firmware_unload_task);
516                     err = 0;
517                     for (i = 0; i < FIRMWARE_MAX; i++) {
518                               fp = &firmware_table[i];
519                               if (fp->fw.name != NULL) {
520                                         kprintf("%s: image %p ref %d still active slot %d\n",
521                                                   __func__, fp->fw.name,
522                                                   fp->refcnt,  i);
523                                         err = EINVAL;
524                               }
525                     }
526                     if (err == 0)
527                               taskqueue_free(firmware_tq);
528                     return err;
529           }
530           return EINVAL;
531 }
532 
533 static moduledata_t firmware_mod = {
534           "firmware",
535           firmware_modevent,
536           NULL
537 };
538 DECLARE_MODULE(firmware, firmware_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
539 MODULE_VERSION(firmware, 1);
540