1 /* $OpenBSD: drm_linux.c,v 1.120 2025/02/07 03:03:08 jsg Exp $ */
2 /*
3 * Copyright (c) 2013 Jonathan Gray <jsg@openbsd.org>
4 * Copyright (c) 2015, 2016 Mark Kettenis <kettenis@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18
19 #include <sys/types.h>
20 #include <sys/systm.h>
21 #include <sys/param.h>
22 #include <sys/event.h>
23 #include <sys/filedesc.h>
24 #include <sys/kthread.h>
25 #include <sys/stat.h>
26 #include <sys/unistd.h>
27 #include <sys/proc.h>
28 #include <sys/pool.h>
29 #include <sys/fcntl.h>
30
31 #include <dev/pci/ppbreg.h>
32
33 #include <linux/dma-buf.h>
34 #include <linux/mod_devicetable.h>
35 #include <linux/acpi.h>
36 #include <linux/pagevec.h>
37 #include <linux/dma-fence-array.h>
38 #include <linux/dma-fence-chain.h>
39 #include <linux/interrupt.h>
40 #include <linux/err.h>
41 #include <linux/idr.h>
42 #include <linux/scatterlist.h>
43 #include <linux/i2c.h>
44 #include <linux/pci.h>
45 #include <linux/notifier.h>
46 #include <linux/backlight.h>
47 #include <linux/shrinker.h>
48 #include <linux/fb.h>
49 #include <linux/xarray.h>
50 #include <linux/interval_tree.h>
51 #include <linux/kthread.h>
52 #include <linux/processor.h>
53 #include <linux/sync_file.h>
54 #include <linux/suspend.h>
55 #include <linux/slab.h>
56
57 #include <drm/drm_device.h>
58 #include <drm/drm_connector.h>
59 #include <drm/drm_print.h>
60 #include <drm/drm_drv.h>
61
62 #if defined(__amd64__) || defined(__i386__)
63 #include "bios.h"
64 #endif
65
66 /* allowed to sleep */
67 void
tasklet_unlock_wait(struct tasklet_struct * ts)68 tasklet_unlock_wait(struct tasklet_struct *ts)
69 {
70 while (test_bit(TASKLET_STATE_RUN, &ts->state))
71 cpu_relax();
72 }
73
74 /* must not sleep */
75 void
tasklet_unlock_spin_wait(struct tasklet_struct * ts)76 tasklet_unlock_spin_wait(struct tasklet_struct *ts)
77 {
78 while (test_bit(TASKLET_STATE_RUN, &ts->state))
79 cpu_relax();
80 }
81
82 void
tasklet_run(void * arg)83 tasklet_run(void *arg)
84 {
85 struct tasklet_struct *ts = arg;
86
87 clear_bit(TASKLET_STATE_SCHED, &ts->state);
88 if (tasklet_trylock(ts)) {
89 if (!atomic_read(&ts->count)) {
90 if (ts->use_callback)
91 ts->callback(ts);
92 else
93 ts->func(ts->data);
94 }
95 tasklet_unlock(ts);
96 }
97 }
98
99 /* 32 bit powerpc lacks 64 bit atomics */
100 #if defined(__powerpc__) && !defined(__powerpc64__)
101 struct mutex atomic64_mtx = MUTEX_INITIALIZER(IPL_HIGH);
102 #endif
103
104 void
set_current_state(int state)105 set_current_state(int state)
106 {
107 int prio = state;
108
109 KASSERT(state != TASK_RUNNING);
110 /* check if already on the sleep list */
111 if (curproc->p_wchan != NULL)
112 return;
113 sleep_setup(curproc, prio, "schto");
114 }
115
116 void
__set_current_state(int state)117 __set_current_state(int state)
118 {
119 struct proc *p = curproc;
120
121 KASSERT(state == TASK_RUNNING);
122 SCHED_LOCK();
123 unsleep(p);
124 p->p_stat = SONPROC;
125 atomic_clearbits_int(&p->p_flag, P_WSLEEP);
126 SCHED_UNLOCK();
127 }
128
129 void
schedule(void)130 schedule(void)
131 {
132 schedule_timeout(MAX_SCHEDULE_TIMEOUT);
133 }
134
135 long
schedule_timeout(long timeout)136 schedule_timeout(long timeout)
137 {
138 unsigned long deadline;
139 int timo = 0;
140
141 KASSERT(!cold);
142
143 if (timeout != MAX_SCHEDULE_TIMEOUT)
144 timo = timeout;
145 if (timeout != MAX_SCHEDULE_TIMEOUT)
146 deadline = jiffies + timeout;
147 sleep_finish(timo, timeout > 0);
148 if (timeout != MAX_SCHEDULE_TIMEOUT)
149 timeout = deadline - jiffies;
150
151 return timeout > 0 ? timeout : 0;
152 }
153
154 long
schedule_timeout_uninterruptible(long timeout)155 schedule_timeout_uninterruptible(long timeout)
156 {
157 tsleep(curproc, PWAIT, "schtou", timeout);
158 return 0;
159 }
160
161 int
wake_up_process(struct proc * p)162 wake_up_process(struct proc *p)
163 {
164 int rv;
165
166 SCHED_LOCK();
167 rv = wakeup_proc(p, 0);
168 SCHED_UNLOCK();
169 return rv;
170 }
171
172 int
autoremove_wake_function(struct wait_queue_entry * wqe,unsigned int mode,int sync,void * key)173 autoremove_wake_function(struct wait_queue_entry *wqe, unsigned int mode,
174 int sync, void *key)
175 {
176 if (wqe->private)
177 wake_up_process(wqe->private);
178 list_del_init(&wqe->entry);
179 return 0;
180 }
181
182 void
prepare_to_wait(wait_queue_head_t * wqh,wait_queue_entry_t * wqe,int state)183 prepare_to_wait(wait_queue_head_t *wqh, wait_queue_entry_t *wqe, int state)
184 {
185 mtx_enter(&wqh->lock);
186 if (list_empty(&wqe->entry))
187 __add_wait_queue(wqh, wqe);
188 mtx_leave(&wqh->lock);
189
190 set_current_state(state);
191 }
192
193 void
finish_wait(wait_queue_head_t * wqh,wait_queue_entry_t * wqe)194 finish_wait(wait_queue_head_t *wqh, wait_queue_entry_t *wqe)
195 {
196 __set_current_state(TASK_RUNNING);
197
198 mtx_enter(&wqh->lock);
199 if (!list_empty(&wqe->entry))
200 list_del_init(&wqe->entry);
201 mtx_leave(&wqh->lock);
202 }
203
204 void
flush_workqueue(struct workqueue_struct * wq)205 flush_workqueue(struct workqueue_struct *wq)
206 {
207 if (cold)
208 return;
209
210 if (wq)
211 taskq_barrier((struct taskq *)wq);
212 }
213
214 bool
flush_work(struct work_struct * work)215 flush_work(struct work_struct *work)
216 {
217 if (cold)
218 return false;
219
220 if (work->tq)
221 taskq_barrier(work->tq);
222 return false;
223 }
224
225 bool
flush_delayed_work(struct delayed_work * dwork)226 flush_delayed_work(struct delayed_work *dwork)
227 {
228 bool ret = false;
229
230 if (cold)
231 return false;
232
233 while (timeout_pending(&dwork->to)) {
234 tsleep(dwork, PWAIT, "fldwto", 1);
235 ret = true;
236 }
237
238 if (dwork->tq)
239 taskq_barrier(dwork->tq);
240 return ret;
241 }
242
243 struct kthread {
244 int (*func)(void *);
245 void *data;
246 struct proc *proc;
247 volatile u_int flags;
248 #define KTHREAD_SHOULDSTOP 0x0000001
249 #define KTHREAD_STOPPED 0x0000002
250 #define KTHREAD_SHOULDPARK 0x0000004
251 #define KTHREAD_PARKED 0x0000008
252 LIST_ENTRY(kthread) next;
253 };
254
255 LIST_HEAD(, kthread) kthread_list = LIST_HEAD_INITIALIZER(kthread_list);
256
257 void
kthread_func(void * arg)258 kthread_func(void *arg)
259 {
260 struct kthread *thread = arg;
261 int ret;
262
263 ret = thread->func(thread->data);
264 thread->flags |= KTHREAD_STOPPED;
265 wakeup(thread);
266 kthread_exit(ret);
267 }
268
269 struct proc *
kthread_run(int (* func)(void *),void * data,const char * name)270 kthread_run(int (*func)(void *), void *data, const char *name)
271 {
272 struct kthread *thread;
273
274 thread = malloc(sizeof(*thread), M_DRM, M_WAITOK);
275 thread->func = func;
276 thread->data = data;
277 thread->flags = 0;
278
279 if (kthread_create(kthread_func, thread, &thread->proc, name)) {
280 free(thread, M_DRM, sizeof(*thread));
281 return ERR_PTR(-ENOMEM);
282 }
283
284 LIST_INSERT_HEAD(&kthread_list, thread, next);
285 return thread->proc;
286 }
287
288 struct kthread_worker *
kthread_create_worker(unsigned int flags,const char * fmt,...)289 kthread_create_worker(unsigned int flags, const char *fmt, ...)
290 {
291 char name[MAXCOMLEN+1];
292 va_list ap;
293
294 struct kthread_worker *w = malloc(sizeof(*w), M_DRM, M_WAITOK);
295 va_start(ap, fmt);
296 vsnprintf(name, sizeof(name), fmt, ap);
297 va_end(ap);
298 w->tq = taskq_create(name, 1, IPL_HIGH, 0);
299
300 return w;
301 }
302
303 void
kthread_destroy_worker(struct kthread_worker * worker)304 kthread_destroy_worker(struct kthread_worker *worker)
305 {
306 taskq_destroy(worker->tq);
307 free(worker, M_DRM, sizeof(*worker));
308
309 }
310
311 void
kthread_init_work(struct kthread_work * work,void (* func)(struct kthread_work *))312 kthread_init_work(struct kthread_work *work, void (*func)(struct kthread_work *))
313 {
314 work->tq = NULL;
315 task_set(&work->task, (void (*)(void *))func, work);
316 }
317
318 bool
kthread_queue_work(struct kthread_worker * worker,struct kthread_work * work)319 kthread_queue_work(struct kthread_worker *worker, struct kthread_work *work)
320 {
321 work->tq = worker->tq;
322 return task_add(work->tq, &work->task);
323 }
324
325 bool
kthread_cancel_work_sync(struct kthread_work * work)326 kthread_cancel_work_sync(struct kthread_work *work)
327 {
328 return task_del(work->tq, &work->task);
329 }
330
331 void
kthread_flush_work(struct kthread_work * work)332 kthread_flush_work(struct kthread_work *work)
333 {
334 if (cold)
335 return;
336
337 if (work->tq)
338 taskq_barrier(work->tq);
339 }
340
341 void
kthread_flush_worker(struct kthread_worker * worker)342 kthread_flush_worker(struct kthread_worker *worker)
343 {
344 if (cold)
345 return;
346
347 if (worker->tq)
348 taskq_barrier(worker->tq);
349 }
350
351 struct kthread *
kthread_lookup(struct proc * p)352 kthread_lookup(struct proc *p)
353 {
354 struct kthread *thread;
355
356 LIST_FOREACH(thread, &kthread_list, next) {
357 if (thread->proc == p)
358 break;
359 }
360 KASSERT(thread);
361
362 return thread;
363 }
364
365 int
kthread_should_park(void)366 kthread_should_park(void)
367 {
368 struct kthread *thread = kthread_lookup(curproc);
369 return (thread->flags & KTHREAD_SHOULDPARK);
370 }
371
372 void
kthread_parkme(void)373 kthread_parkme(void)
374 {
375 struct kthread *thread = kthread_lookup(curproc);
376
377 while (thread->flags & KTHREAD_SHOULDPARK) {
378 thread->flags |= KTHREAD_PARKED;
379 wakeup(thread);
380 tsleep_nsec(thread, PPAUSE, "parkme", INFSLP);
381 thread->flags &= ~KTHREAD_PARKED;
382 }
383 }
384
385 void
kthread_park(struct proc * p)386 kthread_park(struct proc *p)
387 {
388 struct kthread *thread = kthread_lookup(p);
389
390 while ((thread->flags & KTHREAD_PARKED) == 0) {
391 thread->flags |= KTHREAD_SHOULDPARK;
392 wake_up_process(thread->proc);
393 tsleep_nsec(thread, PPAUSE, "park", INFSLP);
394 }
395 }
396
397 void
kthread_unpark(struct proc * p)398 kthread_unpark(struct proc *p)
399 {
400 struct kthread *thread = kthread_lookup(p);
401
402 thread->flags &= ~KTHREAD_SHOULDPARK;
403 wakeup(thread);
404 }
405
406 int
kthread_should_stop(void)407 kthread_should_stop(void)
408 {
409 struct kthread *thread = kthread_lookup(curproc);
410 return (thread->flags & KTHREAD_SHOULDSTOP);
411 }
412
413 void
kthread_stop(struct proc * p)414 kthread_stop(struct proc *p)
415 {
416 struct kthread *thread = kthread_lookup(p);
417
418 while ((thread->flags & KTHREAD_STOPPED) == 0) {
419 thread->flags |= KTHREAD_SHOULDSTOP;
420 kthread_unpark(p);
421 wake_up_process(thread->proc);
422 tsleep_nsec(thread, PPAUSE, "stop", INFSLP);
423 }
424 LIST_REMOVE(thread, next);
425 free(thread, M_DRM, sizeof(*thread));
426 }
427
428 #if NBIOS > 0
429 extern char smbios_board_vendor[];
430 extern char smbios_board_prod[];
431 extern char smbios_board_serial[];
432 #endif
433
434 bool
dmi_match(int slot,const char * str)435 dmi_match(int slot, const char *str)
436 {
437 switch (slot) {
438 case DMI_SYS_VENDOR:
439 if (hw_vendor != NULL &&
440 !strcmp(hw_vendor, str))
441 return true;
442 break;
443 case DMI_PRODUCT_NAME:
444 if (hw_prod != NULL &&
445 !strcmp(hw_prod, str))
446 return true;
447 break;
448 case DMI_PRODUCT_VERSION:
449 if (hw_ver != NULL &&
450 !strcmp(hw_ver, str))
451 return true;
452 break;
453 #if NBIOS > 0
454 case DMI_BOARD_VENDOR:
455 if (strcmp(smbios_board_vendor, str) == 0)
456 return true;
457 break;
458 case DMI_BOARD_NAME:
459 if (strcmp(smbios_board_prod, str) == 0)
460 return true;
461 break;
462 case DMI_BOARD_SERIAL:
463 if (strcmp(smbios_board_serial, str) == 0)
464 return true;
465 break;
466 #else
467 case DMI_BOARD_VENDOR:
468 if (hw_vendor != NULL &&
469 !strcmp(hw_vendor, str))
470 return true;
471 break;
472 case DMI_BOARD_NAME:
473 if (hw_prod != NULL &&
474 !strcmp(hw_prod, str))
475 return true;
476 break;
477 #endif
478 case DMI_NONE:
479 default:
480 return false;
481 }
482
483 return false;
484 }
485
486 static bool
dmi_found(const struct dmi_system_id * dsi)487 dmi_found(const struct dmi_system_id *dsi)
488 {
489 int i, slot;
490
491 for (i = 0; i < nitems(dsi->matches); i++) {
492 slot = dsi->matches[i].slot;
493 if (slot == DMI_NONE)
494 break;
495 if (!dmi_match(slot, dsi->matches[i].substr))
496 return false;
497 }
498
499 return true;
500 }
501
502 const struct dmi_system_id *
dmi_first_match(const struct dmi_system_id * sysid)503 dmi_first_match(const struct dmi_system_id *sysid)
504 {
505 const struct dmi_system_id *dsi;
506
507 for (dsi = sysid; dsi->matches[0].slot != 0 ; dsi++) {
508 if (dmi_found(dsi))
509 return dsi;
510 }
511
512 return NULL;
513 }
514
515 #if NBIOS > 0
516 extern char smbios_bios_date[];
517 extern char smbios_bios_version[];
518 #endif
519
520 const char *
dmi_get_system_info(int slot)521 dmi_get_system_info(int slot)
522 {
523 #if NBIOS > 0
524 switch (slot) {
525 case DMI_BIOS_DATE:
526 return smbios_bios_date;
527 case DMI_BIOS_VERSION:
528 return smbios_bios_version;
529 default:
530 printf("%s slot %d not handled\n", __func__, slot);
531 }
532 #endif
533 return NULL;
534 }
535
536 int
dmi_check_system(const struct dmi_system_id * sysid)537 dmi_check_system(const struct dmi_system_id *sysid)
538 {
539 const struct dmi_system_id *dsi;
540 int num = 0;
541
542 for (dsi = sysid; dsi->matches[0].slot != 0 ; dsi++) {
543 if (dmi_found(dsi)) {
544 num++;
545 if (dsi->callback && dsi->callback(dsi))
546 break;
547 }
548 }
549 return (num);
550 }
551
552 struct vm_page *
alloc_pages(unsigned int gfp_mask,unsigned int order)553 alloc_pages(unsigned int gfp_mask, unsigned int order)
554 {
555 int flags = (gfp_mask & M_NOWAIT) ? UVM_PLA_NOWAIT : UVM_PLA_WAITOK;
556 struct uvm_constraint_range *constraint = &no_constraint;
557 struct pglist mlist;
558
559 if (gfp_mask & M_CANFAIL)
560 flags |= UVM_PLA_FAILOK;
561 if (gfp_mask & M_ZERO)
562 flags |= UVM_PLA_ZERO;
563 if (gfp_mask & __GFP_DMA32)
564 constraint = &dma_constraint;
565
566 TAILQ_INIT(&mlist);
567 if (uvm_pglistalloc(PAGE_SIZE << order, constraint->ucr_low,
568 constraint->ucr_high, PAGE_SIZE, 0, &mlist, 1, flags))
569 return NULL;
570 return TAILQ_FIRST(&mlist);
571 }
572
573 void
__free_pages(struct vm_page * page,unsigned int order)574 __free_pages(struct vm_page *page, unsigned int order)
575 {
576 struct pglist mlist;
577 int i;
578
579 TAILQ_INIT(&mlist);
580 for (i = 0; i < (1 << order); i++)
581 TAILQ_INSERT_TAIL(&mlist, &page[i], pageq);
582 uvm_pglistfree(&mlist);
583 }
584
585 void
__pagevec_release(struct pagevec * pvec)586 __pagevec_release(struct pagevec *pvec)
587 {
588 struct pglist mlist;
589 int i;
590
591 TAILQ_INIT(&mlist);
592 for (i = 0; i < pvec->nr; i++)
593 TAILQ_INSERT_TAIL(&mlist, pvec->pages[i], pageq);
594 uvm_pglistfree(&mlist);
595 pagevec_reinit(pvec);
596 }
597
598 static struct kmem_va_mode kv_physwait = {
599 .kv_map = &phys_map,
600 .kv_wait = 1,
601 };
602
603 void *
kmap(struct vm_page * pg)604 kmap(struct vm_page *pg)
605 {
606 vaddr_t va;
607
608 #if defined (__HAVE_PMAP_DIRECT)
609 va = pmap_map_direct(pg);
610 #else
611 va = (vaddr_t)km_alloc(PAGE_SIZE, &kv_physwait, &kp_none, &kd_waitok);
612 pmap_kenter_pa(va, VM_PAGE_TO_PHYS(pg), PROT_READ | PROT_WRITE);
613 pmap_update(pmap_kernel());
614 #endif
615 return (void *)va;
616 }
617
618 void
kunmap_va(void * addr)619 kunmap_va(void *addr)
620 {
621 vaddr_t va = (vaddr_t)addr;
622
623 #if defined (__HAVE_PMAP_DIRECT)
624 pmap_unmap_direct(va);
625 #else
626 pmap_kremove(va, PAGE_SIZE);
627 pmap_update(pmap_kernel());
628 km_free((void *)va, PAGE_SIZE, &kv_physwait, &kp_none);
629 #endif
630 }
631
632 vaddr_t kmap_atomic_va;
633 int kmap_atomic_inuse;
634
635 void *
kmap_atomic_prot(struct vm_page * pg,pgprot_t prot)636 kmap_atomic_prot(struct vm_page *pg, pgprot_t prot)
637 {
638 KASSERT(!kmap_atomic_inuse);
639
640 kmap_atomic_inuse = 1;
641 pmap_kenter_pa(kmap_atomic_va, VM_PAGE_TO_PHYS(pg) | prot,
642 PROT_READ | PROT_WRITE);
643 return (void *)kmap_atomic_va;
644 }
645
646 void
kunmap_atomic(void * addr)647 kunmap_atomic(void *addr)
648 {
649 KASSERT(kmap_atomic_inuse);
650
651 pmap_kremove(kmap_atomic_va, PAGE_SIZE);
652 kmap_atomic_inuse = 0;
653 }
654
655 void *
vmap(struct vm_page ** pages,unsigned int npages,unsigned long flags,pgprot_t prot)656 vmap(struct vm_page **pages, unsigned int npages, unsigned long flags,
657 pgprot_t prot)
658 {
659 vaddr_t va;
660 paddr_t pa;
661 int i;
662
663 va = (vaddr_t)km_alloc(PAGE_SIZE * npages, &kv_any, &kp_none,
664 &kd_nowait);
665 if (va == 0)
666 return NULL;
667 for (i = 0; i < npages; i++) {
668 pa = VM_PAGE_TO_PHYS(pages[i]) | prot;
669 pmap_enter(pmap_kernel(), va + (i * PAGE_SIZE), pa,
670 PROT_READ | PROT_WRITE,
671 PROT_READ | PROT_WRITE | PMAP_WIRED);
672 pmap_update(pmap_kernel());
673 }
674
675 return (void *)va;
676 }
677
678 void *
vmap_pfn(unsigned long * pfns,unsigned int npfn,pgprot_t prot)679 vmap_pfn(unsigned long *pfns, unsigned int npfn, pgprot_t prot)
680 {
681 vaddr_t va;
682 paddr_t pa;
683 int i;
684
685 va = (vaddr_t)km_alloc(PAGE_SIZE * npfn, &kv_any, &kp_none,
686 &kd_nowait);
687 if (va == 0)
688 return NULL;
689 for (i = 0; i < npfn; i++) {
690 pa = round_page(pfns[i]) | prot;
691 pmap_enter(pmap_kernel(), va + (i * PAGE_SIZE), pa,
692 PROT_READ | PROT_WRITE,
693 PROT_READ | PROT_WRITE | PMAP_WIRED);
694 pmap_update(pmap_kernel());
695 }
696
697 return (void *)va;
698 }
699
700 void
vunmap(void * addr,size_t size)701 vunmap(void *addr, size_t size)
702 {
703 vaddr_t va = (vaddr_t)addr;
704
705 pmap_remove(pmap_kernel(), va, va + size);
706 pmap_update(pmap_kernel());
707 km_free((void *)va, size, &kv_any, &kp_none);
708 }
709
710 bool
is_vmalloc_addr(const void * p)711 is_vmalloc_addr(const void *p)
712 {
713 vaddr_t min, max, addr;
714
715 min = vm_map_min(kernel_map);
716 max = vm_map_max(kernel_map);
717 addr = (vaddr_t)p;
718
719 if (addr >= min && addr <= max)
720 return true;
721 else
722 return false;
723 }
724
725 void
print_hex_dump(const char * level,const char * prefix_str,int prefix_type,int rowsize,int groupsize,const void * buf,size_t len,bool ascii)726 print_hex_dump(const char *level, const char *prefix_str, int prefix_type,
727 int rowsize, int groupsize, const void *buf, size_t len, bool ascii)
728 {
729 const uint8_t *cbuf = buf;
730 int i;
731
732 for (i = 0; i < len; i++) {
733 if ((i % rowsize) == 0)
734 printf("%s", prefix_str);
735 printf("%02x", cbuf[i]);
736 if ((i % rowsize) == (rowsize - 1))
737 printf("\n");
738 else
739 printf(" ");
740 }
741 }
742
743 void *
memchr_inv(const void * s,int c,size_t n)744 memchr_inv(const void *s, int c, size_t n)
745 {
746 if (n != 0) {
747 const unsigned char *p = s;
748
749 do {
750 if (*p++ != (unsigned char)c)
751 return ((void *)(p - 1));
752 } while (--n != 0);
753 }
754 return (NULL);
755 }
756
757 int
panic_cmp(struct rb_node * a,struct rb_node * b)758 panic_cmp(struct rb_node *a, struct rb_node *b)
759 {
760 panic(__func__);
761 }
762
763 #undef RB_ROOT
764 #define RB_ROOT(head) (head)->rbh_root
765
766 RB_GENERATE(linux_root, rb_node, __entry, panic_cmp);
767
768 /*
769 * This is a fairly minimal implementation of the Linux "idr" API. It
770 * probably isn't very efficient, and definitely isn't RCU safe. The
771 * pre-load buffer is global instead of per-cpu; we rely on the kernel
772 * lock to make this work. We do randomize our IDs in order to make
773 * them harder to guess.
774 */
775
776 int idr_cmp(struct idr_entry *, struct idr_entry *);
777 SPLAY_PROTOTYPE(idr_tree, idr_entry, entry, idr_cmp);
778
779 struct pool idr_pool;
780 struct idr_entry *idr_entry_cache;
781
782 void
idr_init(struct idr * idr)783 idr_init(struct idr *idr)
784 {
785 SPLAY_INIT(&idr->tree);
786 }
787
788 void
idr_destroy(struct idr * idr)789 idr_destroy(struct idr *idr)
790 {
791 struct idr_entry *id;
792
793 while ((id = SPLAY_MIN(idr_tree, &idr->tree))) {
794 SPLAY_REMOVE(idr_tree, &idr->tree, id);
795 pool_put(&idr_pool, id);
796 }
797 }
798
799 void
idr_preload(unsigned int gfp_mask)800 idr_preload(unsigned int gfp_mask)
801 {
802 int flags = (gfp_mask & GFP_NOWAIT) ? PR_NOWAIT : PR_WAITOK;
803
804 KERNEL_ASSERT_LOCKED();
805
806 if (idr_entry_cache == NULL)
807 idr_entry_cache = pool_get(&idr_pool, flags);
808 }
809
810 /* [start, end) */
811 int
idr_alloc(struct idr * idr,void * ptr,int start,int end,gfp_t gfp_mask)812 idr_alloc(struct idr *idr, void *ptr, int start, int end, gfp_t gfp_mask)
813 {
814 int flags = (gfp_mask & GFP_NOWAIT) ? PR_NOWAIT : PR_WAITOK;
815 struct idr_entry *id;
816 int begin;
817
818 KERNEL_ASSERT_LOCKED();
819
820 if (idr_entry_cache) {
821 id = idr_entry_cache;
822 idr_entry_cache = NULL;
823 } else {
824 id = pool_get(&idr_pool, flags);
825 if (id == NULL)
826 return -ENOMEM;
827 }
828
829 if (end <= 0)
830 end = INT_MAX;
831
832 #ifdef notyet
833 id->id = begin = start + arc4random_uniform(end - start);
834 #else
835 id->id = begin = start;
836 #endif
837 while (SPLAY_INSERT(idr_tree, &idr->tree, id)) {
838 if (id->id == end)
839 id->id = start;
840 else
841 id->id++;
842 if (id->id == begin) {
843 pool_put(&idr_pool, id);
844 return -ENOSPC;
845 }
846 }
847 id->ptr = ptr;
848 return id->id;
849 }
850
851 void *
idr_replace(struct idr * idr,void * ptr,unsigned long id)852 idr_replace(struct idr *idr, void *ptr, unsigned long id)
853 {
854 struct idr_entry find, *res;
855 void *old;
856
857 find.id = id;
858 res = SPLAY_FIND(idr_tree, &idr->tree, &find);
859 if (res == NULL)
860 return ERR_PTR(-ENOENT);
861 old = res->ptr;
862 res->ptr = ptr;
863 return old;
864 }
865
866 void *
idr_remove(struct idr * idr,unsigned long id)867 idr_remove(struct idr *idr, unsigned long id)
868 {
869 struct idr_entry find, *res;
870 void *ptr = NULL;
871
872 find.id = id;
873 res = SPLAY_FIND(idr_tree, &idr->tree, &find);
874 if (res) {
875 SPLAY_REMOVE(idr_tree, &idr->tree, res);
876 ptr = res->ptr;
877 pool_put(&idr_pool, res);
878 }
879 return ptr;
880 }
881
882 void *
idr_find(struct idr * idr,unsigned long id)883 idr_find(struct idr *idr, unsigned long id)
884 {
885 struct idr_entry find, *res;
886
887 find.id = id;
888 res = SPLAY_FIND(idr_tree, &idr->tree, &find);
889 if (res == NULL)
890 return NULL;
891 return res->ptr;
892 }
893
894 void *
idr_get_next(struct idr * idr,int * id)895 idr_get_next(struct idr *idr, int *id)
896 {
897 struct idr_entry *res;
898
899 SPLAY_FOREACH(res, idr_tree, &idr->tree) {
900 if (res->id >= *id) {
901 *id = res->id;
902 return res->ptr;
903 }
904 }
905
906 return NULL;
907 }
908
909 int
idr_for_each(struct idr * idr,int (* func)(int,void *,void *),void * data)910 idr_for_each(struct idr *idr, int (*func)(int, void *, void *), void *data)
911 {
912 struct idr_entry *id;
913 int ret;
914
915 SPLAY_FOREACH(id, idr_tree, &idr->tree) {
916 ret = func(id->id, id->ptr, data);
917 if (ret)
918 return ret;
919 }
920
921 return 0;
922 }
923
924 int
idr_cmp(struct idr_entry * a,struct idr_entry * b)925 idr_cmp(struct idr_entry *a, struct idr_entry *b)
926 {
927 return (a->id < b->id ? -1 : a->id > b->id);
928 }
929
930 SPLAY_GENERATE(idr_tree, idr_entry, entry, idr_cmp);
931
932 void
ida_init(struct ida * ida)933 ida_init(struct ida *ida)
934 {
935 idr_init(&ida->idr);
936 }
937
938 void
ida_destroy(struct ida * ida)939 ida_destroy(struct ida *ida)
940 {
941 idr_destroy(&ida->idr);
942 }
943
944 int
ida_simple_get(struct ida * ida,unsigned int start,unsigned int end,gfp_t gfp_mask)945 ida_simple_get(struct ida *ida, unsigned int start, unsigned int end,
946 gfp_t gfp_mask)
947 {
948 return idr_alloc(&ida->idr, NULL, start, end, gfp_mask);
949 }
950
951 void
ida_simple_remove(struct ida * ida,unsigned int id)952 ida_simple_remove(struct ida *ida, unsigned int id)
953 {
954 idr_remove(&ida->idr, id);
955 }
956
957 /* [start, end] */
958 int
ida_alloc_range(struct ida * ida,unsigned int start,unsigned int end,gfp_t gfp)959 ida_alloc_range(struct ida *ida, unsigned int start, unsigned int end, gfp_t gfp)
960 {
961 return idr_alloc(&ida->idr, NULL, start, end + 1, gfp);
962 }
963
964 int
ida_alloc_min(struct ida * ida,unsigned int min,gfp_t gfp)965 ida_alloc_min(struct ida *ida, unsigned int min, gfp_t gfp)
966 {
967 return idr_alloc(&ida->idr, NULL, min, INT_MAX, gfp);
968 }
969
970 int
ida_alloc_max(struct ida * ida,unsigned int max,gfp_t gfp)971 ida_alloc_max(struct ida *ida, unsigned int max, gfp_t gfp)
972 {
973 return idr_alloc(&ida->idr, NULL, 0, max - 1, gfp);
974 }
975
976 void
ida_free(struct ida * ida,unsigned int id)977 ida_free(struct ida *ida, unsigned int id)
978 {
979 idr_remove(&ida->idr, id);
980 }
981
982 int
xarray_cmp(struct xarray_entry * a,struct xarray_entry * b)983 xarray_cmp(struct xarray_entry *a, struct xarray_entry *b)
984 {
985 return (a->id < b->id ? -1 : a->id > b->id);
986 }
987
988 SPLAY_PROTOTYPE(xarray_tree, xarray_entry, entry, xarray_cmp);
989 struct pool xa_pool;
990 SPLAY_GENERATE(xarray_tree, xarray_entry, entry, xarray_cmp);
991
992 void
xa_init_flags(struct xarray * xa,gfp_t flags)993 xa_init_flags(struct xarray *xa, gfp_t flags)
994 {
995 SPLAY_INIT(&xa->xa_tree);
996 if (flags & XA_FLAGS_LOCK_IRQ)
997 mtx_init(&xa->xa_lock, IPL_TTY);
998 else
999 mtx_init(&xa->xa_lock, IPL_NONE);
1000 xa->xa_flags = flags;
1001 }
1002
1003 void
xa_destroy(struct xarray * xa)1004 xa_destroy(struct xarray *xa)
1005 {
1006 struct xarray_entry *id;
1007
1008 while ((id = SPLAY_MIN(xarray_tree, &xa->xa_tree))) {
1009 SPLAY_REMOVE(xarray_tree, &xa->xa_tree, id);
1010 pool_put(&xa_pool, id);
1011 }
1012 }
1013
1014 /* Don't wrap ids. */
1015 int
__xa_alloc(struct xarray * xa,u32 * id,void * entry,struct xarray_range xr,gfp_t gfp)1016 __xa_alloc(struct xarray *xa, u32 *id, void *entry, struct xarray_range xr,
1017 gfp_t gfp)
1018 {
1019 struct xarray_entry *xid;
1020 uint32_t start = xr.start;
1021 uint32_t end = xr.end;
1022
1023 if (start == 0 && (xa->xa_flags & XA_FLAGS_ALLOC1))
1024 start = 1;
1025
1026 if (gfp & GFP_NOWAIT) {
1027 xid = pool_get(&xa_pool, PR_NOWAIT);
1028 } else {
1029 mtx_leave(&xa->xa_lock);
1030 xid = pool_get(&xa_pool, PR_WAITOK);
1031 mtx_enter(&xa->xa_lock);
1032 }
1033
1034 if (xid == NULL)
1035 return -ENOMEM;
1036
1037 xid->id = start;
1038
1039 while (SPLAY_INSERT(xarray_tree, &xa->xa_tree, xid)) {
1040 if (xid->id == end)
1041 xid->id = start;
1042 else
1043 xid->id++;
1044 if (xid->id == start) {
1045 pool_put(&xa_pool, xid);
1046 return -EBUSY;
1047 }
1048 }
1049 xid->ptr = entry;
1050 *id = xid->id;
1051 return 0;
1052 }
1053
1054 /*
1055 * Wrap ids and store next id.
1056 * We walk the entire tree so don't special case wrapping.
1057 * The only caller of this (i915_drm_client.c) doesn't use next id.
1058 */
1059 int
__xa_alloc_cyclic(struct xarray * xa,u32 * id,void * entry,struct xarray_range xr,u32 * next,gfp_t gfp)1060 __xa_alloc_cyclic(struct xarray *xa, u32 *id, void *entry,
1061 struct xarray_range xr, u32 *next, gfp_t gfp)
1062 {
1063 int r = __xa_alloc(xa, id, entry, xr, gfp);
1064 *next = *id + 1;
1065 return r;
1066 }
1067
1068 void *
__xa_erase(struct xarray * xa,unsigned long index)1069 __xa_erase(struct xarray *xa, unsigned long index)
1070 {
1071 struct xarray_entry find, *res;
1072 void *ptr = NULL;
1073
1074 find.id = index;
1075 res = SPLAY_FIND(xarray_tree, &xa->xa_tree, &find);
1076 if (res) {
1077 SPLAY_REMOVE(xarray_tree, &xa->xa_tree, res);
1078 ptr = res->ptr;
1079 pool_put(&xa_pool, res);
1080 }
1081 return ptr;
1082 }
1083
1084 void *
__xa_load(struct xarray * xa,unsigned long index)1085 __xa_load(struct xarray *xa, unsigned long index)
1086 {
1087 struct xarray_entry find, *res;
1088
1089 find.id = index;
1090 res = SPLAY_FIND(xarray_tree, &xa->xa_tree, &find);
1091 if (res == NULL)
1092 return NULL;
1093 return res->ptr;
1094 }
1095
1096 void *
__xa_store(struct xarray * xa,unsigned long index,void * entry,gfp_t gfp)1097 __xa_store(struct xarray *xa, unsigned long index, void *entry, gfp_t gfp)
1098 {
1099 struct xarray_entry find, *res;
1100 void *prev;
1101
1102 if (entry == NULL)
1103 return __xa_erase(xa, index);
1104
1105 find.id = index;
1106 res = SPLAY_FIND(xarray_tree, &xa->xa_tree, &find);
1107 if (res != NULL) {
1108 /* index exists */
1109 /* XXX Multislot entries updates not implemented yet */
1110 prev = res->ptr;
1111 res->ptr = entry;
1112 return prev;
1113 }
1114
1115 /* index not found, add new */
1116 if (gfp & GFP_NOWAIT) {
1117 res = pool_get(&xa_pool, PR_NOWAIT);
1118 } else {
1119 mtx_leave(&xa->xa_lock);
1120 res = pool_get(&xa_pool, PR_WAITOK);
1121 mtx_enter(&xa->xa_lock);
1122 }
1123 if (res == NULL)
1124 return XA_ERROR(-ENOMEM);
1125 res->id = index;
1126 res->ptr = entry;
1127 if (SPLAY_INSERT(xarray_tree, &xa->xa_tree, res) != NULL)
1128 return XA_ERROR(-EINVAL);
1129 return NULL; /* no prev entry at index */
1130 }
1131
1132 void *
xa_get_next(struct xarray * xa,unsigned long * index)1133 xa_get_next(struct xarray *xa, unsigned long *index)
1134 {
1135 struct xarray_entry *res;
1136
1137 SPLAY_FOREACH(res, xarray_tree, &xa->xa_tree) {
1138 if (res->id >= *index) {
1139 *index = res->id;
1140 return res->ptr;
1141 }
1142 }
1143
1144 return NULL;
1145 }
1146
1147 int
sg_alloc_table(struct sg_table * table,unsigned int nents,gfp_t gfp_mask)1148 sg_alloc_table(struct sg_table *table, unsigned int nents, gfp_t gfp_mask)
1149 {
1150 table->sgl = mallocarray(nents, sizeof(struct scatterlist),
1151 M_DRM, gfp_mask | M_ZERO);
1152 if (table->sgl == NULL)
1153 return -ENOMEM;
1154 table->nents = table->orig_nents = nents;
1155 sg_mark_end(&table->sgl[nents - 1]);
1156 return 0;
1157 }
1158
1159 void
sg_free_table(struct sg_table * table)1160 sg_free_table(struct sg_table *table)
1161 {
1162 free(table->sgl, M_DRM,
1163 table->orig_nents * sizeof(struct scatterlist));
1164 table->orig_nents = 0;
1165 table->sgl = NULL;
1166 }
1167
1168 size_t
sg_copy_from_buffer(struct scatterlist * sgl,unsigned int nents,const void * buf,size_t buflen)1169 sg_copy_from_buffer(struct scatterlist *sgl, unsigned int nents,
1170 const void *buf, size_t buflen)
1171 {
1172 panic("%s", __func__);
1173 }
1174
1175 int
i2c_master_xfer(struct i2c_adapter * adap,struct i2c_msg * msgs,int num)1176 i2c_master_xfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
1177 {
1178 void *cmd = NULL;
1179 int cmdlen = 0;
1180 int err, ret = 0;
1181 int op;
1182
1183 iic_acquire_bus(&adap->ic, 0);
1184
1185 while (num > 2) {
1186 op = (msgs->flags & I2C_M_RD) ? I2C_OP_READ : I2C_OP_WRITE;
1187 err = iic_exec(&adap->ic, op, msgs->addr, NULL, 0,
1188 msgs->buf, msgs->len, 0);
1189 if (err) {
1190 ret = -err;
1191 goto fail;
1192 }
1193 msgs++;
1194 num--;
1195 ret++;
1196 }
1197
1198 if (num > 1) {
1199 cmd = msgs->buf;
1200 cmdlen = msgs->len;
1201 msgs++;
1202 num--;
1203 ret++;
1204 }
1205
1206 op = (msgs->flags & I2C_M_RD) ?
1207 I2C_OP_READ_WITH_STOP : I2C_OP_WRITE_WITH_STOP;
1208 err = iic_exec(&adap->ic, op, msgs->addr, cmd, cmdlen,
1209 msgs->buf, msgs->len, 0);
1210 if (err) {
1211 ret = -err;
1212 goto fail;
1213 }
1214 msgs++;
1215 ret++;
1216
1217 fail:
1218 iic_release_bus(&adap->ic, 0);
1219
1220 return ret;
1221 }
1222
1223 int
__i2c_transfer(struct i2c_adapter * adap,struct i2c_msg * msgs,int num)1224 __i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
1225 {
1226 int ret, retries;
1227
1228 retries = adap->retries;
1229 retry:
1230 if (adap->algo)
1231 ret = adap->algo->master_xfer(adap, msgs, num);
1232 else
1233 ret = i2c_master_xfer(adap, msgs, num);
1234 if (ret == -EAGAIN && retries > 0) {
1235 retries--;
1236 goto retry;
1237 }
1238
1239 return ret;
1240 }
1241
1242 int
i2c_transfer(struct i2c_adapter * adap,struct i2c_msg * msgs,int num)1243 i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
1244 {
1245 int ret;
1246
1247 if (adap->lock_ops)
1248 adap->lock_ops->lock_bus(adap, 0);
1249
1250 ret = __i2c_transfer(adap, msgs, num);
1251
1252 if (adap->lock_ops)
1253 adap->lock_ops->unlock_bus(adap, 0);
1254
1255 return ret;
1256 }
1257
1258 int
i2c_bb_master_xfer(struct i2c_adapter * adap,struct i2c_msg * msgs,int num)1259 i2c_bb_master_xfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
1260 {
1261 struct i2c_algo_bit_data *algo = adap->algo_data;
1262 struct i2c_adapter bb;
1263
1264 memset(&bb, 0, sizeof(bb));
1265 bb.ic = algo->ic;
1266 bb.retries = adap->retries;
1267 return i2c_master_xfer(&bb, msgs, num);
1268 }
1269
1270 uint32_t
i2c_bb_functionality(struct i2c_adapter * adap)1271 i2c_bb_functionality(struct i2c_adapter *adap)
1272 {
1273 return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
1274 }
1275
1276 struct i2c_algorithm i2c_bit_algo = {
1277 .master_xfer = i2c_bb_master_xfer,
1278 .functionality = i2c_bb_functionality
1279 };
1280
1281 int
i2c_bit_add_bus(struct i2c_adapter * adap)1282 i2c_bit_add_bus(struct i2c_adapter *adap)
1283 {
1284 adap->algo = &i2c_bit_algo;
1285 adap->retries = 3;
1286
1287 return 0;
1288 }
1289
1290 #if defined(__amd64__) || defined(__i386__)
1291
1292 /*
1293 * This is a minimal implementation of the Linux vga_get/vga_put
1294 * interface. In all likelihood, it will only work for inteldrm(4) as
1295 * it assumes that if there is another active VGA device in the
1296 * system, it is sitting behind a PCI bridge.
1297 */
1298
1299 extern int pci_enumerate_bus(struct pci_softc *,
1300 int (*)(struct pci_attach_args *), struct pci_attach_args *);
1301
1302 pcitag_t vga_bridge_tag;
1303 int vga_bridge_disabled;
1304
1305 int
vga_disable_bridge(struct pci_attach_args * pa)1306 vga_disable_bridge(struct pci_attach_args *pa)
1307 {
1308 pcireg_t bhlc, bc;
1309
1310 if (pa->pa_domain != 0)
1311 return 0;
1312
1313 bhlc = pci_conf_read(pa->pa_pc, pa->pa_tag, PCI_BHLC_REG);
1314 if (PCI_HDRTYPE_TYPE(bhlc) != 1)
1315 return 0;
1316
1317 bc = pci_conf_read(pa->pa_pc, pa->pa_tag, PPB_REG_BRIDGECONTROL);
1318 if ((bc & PPB_BC_VGA_ENABLE) == 0)
1319 return 0;
1320 bc &= ~PPB_BC_VGA_ENABLE;
1321 pci_conf_write(pa->pa_pc, pa->pa_tag, PPB_REG_BRIDGECONTROL, bc);
1322
1323 vga_bridge_tag = pa->pa_tag;
1324 vga_bridge_disabled = 1;
1325
1326 return 1;
1327 }
1328
1329 void
vga_get_uninterruptible(struct pci_dev * pdev,int rsrc)1330 vga_get_uninterruptible(struct pci_dev *pdev, int rsrc)
1331 {
1332 if (pdev->pci->sc_bridgetag != NULL)
1333 return;
1334 pci_enumerate_bus(pdev->pci, vga_disable_bridge, NULL);
1335 }
1336
1337 void
vga_put(struct pci_dev * pdev,int rsrc)1338 vga_put(struct pci_dev *pdev, int rsrc)
1339 {
1340 pcireg_t bc;
1341
1342 if (!vga_bridge_disabled)
1343 return;
1344
1345 bc = pci_conf_read(pdev->pc, vga_bridge_tag, PPB_REG_BRIDGECONTROL);
1346 bc |= PPB_BC_VGA_ENABLE;
1347 pci_conf_write(pdev->pc, vga_bridge_tag, PPB_REG_BRIDGECONTROL, bc);
1348
1349 vga_bridge_disabled = 0;
1350 }
1351
1352 #endif
1353
1354 suspend_state_t pm_suspend_target_state;
1355
1356 /*
1357 * ACPI types and interfaces.
1358 */
1359
1360 #ifdef __HAVE_ACPI
1361 #include "acpi.h"
1362 #endif
1363
1364 #if NACPI > 0
1365
1366 #include <dev/acpi/acpireg.h>
1367 #include <dev/acpi/acpivar.h>
1368 #include <dev/acpi/amltypes.h>
1369 #include <dev/acpi/dsdt.h>
1370
1371 struct acpi_fadt acpi_gbl_FADT;
1372
1373 acpi_status
acpi_get_table(const char * sig,int instance,struct acpi_table_header ** hdr)1374 acpi_get_table(const char *sig, int instance,
1375 struct acpi_table_header **hdr)
1376 {
1377 struct acpi_softc *sc = acpi_softc;
1378 struct acpi_q *entry;
1379
1380 KASSERT(instance == 1);
1381
1382 if (sc == NULL)
1383 return AE_NOT_FOUND;
1384
1385 SIMPLEQ_FOREACH(entry, &sc->sc_tables, q_next) {
1386 if (memcmp(entry->q_table, sig, strlen(sig)) == 0) {
1387 *hdr = entry->q_table;
1388 return 0;
1389 }
1390 }
1391
1392 return AE_NOT_FOUND;
1393 }
1394
1395 void
acpi_put_table(struct acpi_table_header * hdr)1396 acpi_put_table(struct acpi_table_header *hdr)
1397 {
1398 }
1399
1400 acpi_status
acpi_get_handle(acpi_handle node,const char * name,acpi_handle * rnode)1401 acpi_get_handle(acpi_handle node, const char *name, acpi_handle *rnode)
1402 {
1403 node = aml_searchname(node, name);
1404 if (node == NULL)
1405 return AE_NOT_FOUND;
1406
1407 *rnode = node;
1408 return 0;
1409 }
1410
1411 acpi_status
acpi_get_name(acpi_handle node,int type,struct acpi_buffer * buffer)1412 acpi_get_name(acpi_handle node, int type, struct acpi_buffer *buffer)
1413 {
1414 KASSERT(buffer->length != ACPI_ALLOCATE_BUFFER);
1415 KASSERT(type == ACPI_FULL_PATHNAME);
1416 strlcpy(buffer->pointer, aml_nodename(node), buffer->length);
1417 return 0;
1418 }
1419
1420 acpi_status
acpi_evaluate_object(acpi_handle node,const char * name,struct acpi_object_list * params,struct acpi_buffer * result)1421 acpi_evaluate_object(acpi_handle node, const char *name,
1422 struct acpi_object_list *params, struct acpi_buffer *result)
1423 {
1424 struct aml_value args[4], res;
1425 union acpi_object *obj;
1426 uint8_t *data;
1427 int i;
1428
1429 KASSERT(params->count <= nitems(args));
1430
1431 for (i = 0; i < params->count; i++) {
1432 args[i].type = params->pointer[i].type;
1433 switch (args[i].type) {
1434 case AML_OBJTYPE_INTEGER:
1435 args[i].v_integer = params->pointer[i].integer.value;
1436 break;
1437 case AML_OBJTYPE_BUFFER:
1438 args[i].length = params->pointer[i].buffer.length;
1439 args[i].v_buffer = params->pointer[i].buffer.pointer;
1440 break;
1441 default:
1442 printf("%s: arg type 0x%02x", __func__, args[i].type);
1443 return AE_BAD_PARAMETER;
1444 }
1445 }
1446
1447 if (name) {
1448 node = aml_searchname(node, name);
1449 if (node == NULL)
1450 return AE_NOT_FOUND;
1451 }
1452 if (aml_evalnode(acpi_softc, node, params->count, args, &res)) {
1453 aml_freevalue(&res);
1454 return AE_ERROR;
1455 }
1456
1457 KASSERT(result->length == ACPI_ALLOCATE_BUFFER);
1458
1459 result->length = sizeof(union acpi_object);
1460 switch (res.type) {
1461 case AML_OBJTYPE_BUFFER:
1462 result->length += res.length;
1463 result->pointer = malloc(result->length, M_DRM, M_WAITOK);
1464 obj = (union acpi_object *)result->pointer;
1465 data = (uint8_t *)(obj + 1);
1466 obj->type = res.type;
1467 obj->buffer.length = res.length;
1468 obj->buffer.pointer = data;
1469 memcpy(data, res.v_buffer, res.length);
1470 break;
1471 default:
1472 printf("%s: return type 0x%02x", __func__, res.type);
1473 aml_freevalue(&res);
1474 return AE_ERROR;
1475 }
1476
1477 aml_freevalue(&res);
1478 return 0;
1479 }
1480
1481 SLIST_HEAD(, notifier_block) drm_linux_acpi_notify_list =
1482 SLIST_HEAD_INITIALIZER(drm_linux_acpi_notify_list);
1483
1484 int
drm_linux_acpi_notify(struct aml_node * node,int notify,void * arg)1485 drm_linux_acpi_notify(struct aml_node *node, int notify, void *arg)
1486 {
1487 struct acpi_bus_event event;
1488 struct notifier_block *nb;
1489
1490 event.device_class = ACPI_VIDEO_CLASS;
1491 event.type = notify;
1492
1493 SLIST_FOREACH(nb, &drm_linux_acpi_notify_list, link)
1494 nb->notifier_call(nb, 0, &event);
1495 return 0;
1496 }
1497
1498 int
register_acpi_notifier(struct notifier_block * nb)1499 register_acpi_notifier(struct notifier_block *nb)
1500 {
1501 SLIST_INSERT_HEAD(&drm_linux_acpi_notify_list, nb, link);
1502 return 0;
1503 }
1504
1505 int
unregister_acpi_notifier(struct notifier_block * nb)1506 unregister_acpi_notifier(struct notifier_block *nb)
1507 {
1508 struct notifier_block *tmp;
1509
1510 SLIST_FOREACH(tmp, &drm_linux_acpi_notify_list, link) {
1511 if (tmp == nb) {
1512 SLIST_REMOVE(&drm_linux_acpi_notify_list, nb,
1513 notifier_block, link);
1514 return 0;
1515 }
1516 }
1517
1518 return -ENOENT;
1519 }
1520
1521 const char *
acpi_format_exception(acpi_status status)1522 acpi_format_exception(acpi_status status)
1523 {
1524 switch (status) {
1525 case AE_NOT_FOUND:
1526 return "not found";
1527 case AE_BAD_PARAMETER:
1528 return "bad parameter";
1529 default:
1530 return "unknown";
1531 }
1532 }
1533
1534 int
acpi_target_system_state(void)1535 acpi_target_system_state(void)
1536 {
1537 return acpi_softc->sc_state;
1538 }
1539
1540 #endif
1541
1542 SLIST_HEAD(,backlight_device) backlight_device_list =
1543 SLIST_HEAD_INITIALIZER(backlight_device_list);
1544
1545 void
backlight_do_update_status(void * arg)1546 backlight_do_update_status(void *arg)
1547 {
1548 backlight_update_status(arg);
1549 }
1550
1551 struct backlight_device *
backlight_device_register(const char * name,void * kdev,void * data,const struct backlight_ops * ops,const struct backlight_properties * props)1552 backlight_device_register(const char *name, void *kdev, void *data,
1553 const struct backlight_ops *ops, const struct backlight_properties *props)
1554 {
1555 struct backlight_device *bd;
1556
1557 bd = malloc(sizeof(*bd), M_DRM, M_WAITOK);
1558 bd->ops = ops;
1559 bd->props = *props;
1560 bd->data = data;
1561
1562 task_set(&bd->task, backlight_do_update_status, bd);
1563
1564 SLIST_INSERT_HEAD(&backlight_device_list, bd, next);
1565 bd->name = name;
1566
1567 return bd;
1568 }
1569
1570 void
backlight_device_unregister(struct backlight_device * bd)1571 backlight_device_unregister(struct backlight_device *bd)
1572 {
1573 SLIST_REMOVE(&backlight_device_list, bd, backlight_device, next);
1574 free(bd, M_DRM, sizeof(*bd));
1575 }
1576
1577 void
backlight_schedule_update_status(struct backlight_device * bd)1578 backlight_schedule_update_status(struct backlight_device *bd)
1579 {
1580 task_add(systq, &bd->task);
1581 }
1582
1583 int
backlight_enable(struct backlight_device * bd)1584 backlight_enable(struct backlight_device *bd)
1585 {
1586 if (bd == NULL)
1587 return 0;
1588
1589 bd->props.power = FB_BLANK_UNBLANK;
1590
1591 return bd->ops->update_status(bd);
1592 }
1593
1594 int
backlight_disable(struct backlight_device * bd)1595 backlight_disable(struct backlight_device *bd)
1596 {
1597 if (bd == NULL)
1598 return 0;
1599
1600 bd->props.power = FB_BLANK_POWERDOWN;
1601
1602 return bd->ops->update_status(bd);
1603 }
1604
1605 struct backlight_device *
backlight_device_get_by_name(const char * name)1606 backlight_device_get_by_name(const char *name)
1607 {
1608 struct backlight_device *bd;
1609
1610 SLIST_FOREACH(bd, &backlight_device_list, next) {
1611 if (strcmp(name, bd->name) == 0)
1612 return bd;
1613 }
1614
1615 return NULL;
1616 }
1617
1618 struct drvdata {
1619 struct device *dev;
1620 void *data;
1621 SLIST_ENTRY(drvdata) next;
1622 };
1623
1624 SLIST_HEAD(,drvdata) drvdata_list = SLIST_HEAD_INITIALIZER(drvdata_list);
1625
1626 void
dev_set_drvdata(struct device * dev,void * data)1627 dev_set_drvdata(struct device *dev, void *data)
1628 {
1629 struct drvdata *drvdata;
1630
1631 SLIST_FOREACH(drvdata, &drvdata_list, next) {
1632 if (drvdata->dev == dev) {
1633 drvdata->data = data;
1634 return;
1635 }
1636 }
1637
1638 if (data == NULL)
1639 return;
1640
1641 drvdata = malloc(sizeof(*drvdata), M_DRM, M_WAITOK);
1642 drvdata->dev = dev;
1643 drvdata->data = data;
1644
1645 SLIST_INSERT_HEAD(&drvdata_list, drvdata, next);
1646 }
1647
1648 void *
dev_get_drvdata(struct device * dev)1649 dev_get_drvdata(struct device *dev)
1650 {
1651 struct drvdata *drvdata;
1652
1653 SLIST_FOREACH(drvdata, &drvdata_list, next) {
1654 if (drvdata->dev == dev)
1655 return drvdata->data;
1656 }
1657
1658 return NULL;
1659 }
1660
1661 void
drm_sysfs_hotplug_event(struct drm_device * dev)1662 drm_sysfs_hotplug_event(struct drm_device *dev)
1663 {
1664 knote_locked(&dev->note, NOTE_CHANGE);
1665 }
1666
1667 void
drm_sysfs_connector_hotplug_event(struct drm_connector * connector)1668 drm_sysfs_connector_hotplug_event(struct drm_connector *connector)
1669 {
1670 knote_locked(&connector->dev->note, NOTE_CHANGE);
1671 }
1672
1673 void
drm_sysfs_connector_status_event(struct drm_connector * connector,struct drm_property * property)1674 drm_sysfs_connector_status_event(struct drm_connector *connector,
1675 struct drm_property *property)
1676 {
1677 STUB();
1678 }
1679
1680 void
drm_sysfs_connector_property_event(struct drm_connector * connector,struct drm_property * property)1681 drm_sysfs_connector_property_event(struct drm_connector *connector,
1682 struct drm_property *property)
1683 {
1684 STUB();
1685 }
1686
1687 struct dma_fence *
dma_fence_get(struct dma_fence * fence)1688 dma_fence_get(struct dma_fence *fence)
1689 {
1690 if (fence)
1691 kref_get(&fence->refcount);
1692 return fence;
1693 }
1694
1695 struct dma_fence *
dma_fence_get_rcu(struct dma_fence * fence)1696 dma_fence_get_rcu(struct dma_fence *fence)
1697 {
1698 if (fence)
1699 kref_get(&fence->refcount);
1700 return fence;
1701 }
1702
1703 struct dma_fence *
dma_fence_get_rcu_safe(struct dma_fence ** dfp)1704 dma_fence_get_rcu_safe(struct dma_fence **dfp)
1705 {
1706 struct dma_fence *fence;
1707 if (dfp == NULL)
1708 return NULL;
1709 fence = *dfp;
1710 if (fence)
1711 kref_get(&fence->refcount);
1712 return fence;
1713 }
1714
1715 void
dma_fence_release(struct kref * ref)1716 dma_fence_release(struct kref *ref)
1717 {
1718 struct dma_fence *fence = container_of(ref, struct dma_fence, refcount);
1719 if (fence->ops && fence->ops->release)
1720 fence->ops->release(fence);
1721 else
1722 free(fence, M_DRM, 0);
1723 }
1724
1725 void
dma_fence_put(struct dma_fence * fence)1726 dma_fence_put(struct dma_fence *fence)
1727 {
1728 if (fence)
1729 kref_put(&fence->refcount, dma_fence_release);
1730 }
1731
1732 int
dma_fence_signal_timestamp_locked(struct dma_fence * fence,ktime_t timestamp)1733 dma_fence_signal_timestamp_locked(struct dma_fence *fence, ktime_t timestamp)
1734 {
1735 struct dma_fence_cb *cur, *tmp;
1736 struct list_head cb_list;
1737
1738 if (fence == NULL)
1739 return -EINVAL;
1740
1741 if (test_and_set_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
1742 return -EINVAL;
1743
1744 list_replace(&fence->cb_list, &cb_list);
1745
1746 fence->timestamp = timestamp;
1747 set_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags);
1748
1749 list_for_each_entry_safe(cur, tmp, &cb_list, node) {
1750 INIT_LIST_HEAD(&cur->node);
1751 cur->func(fence, cur);
1752 }
1753
1754 return 0;
1755 }
1756
1757 int
dma_fence_signal(struct dma_fence * fence)1758 dma_fence_signal(struct dma_fence *fence)
1759 {
1760 int r;
1761
1762 if (fence == NULL)
1763 return -EINVAL;
1764
1765 mtx_enter(fence->lock);
1766 r = dma_fence_signal_timestamp_locked(fence, ktime_get());
1767 mtx_leave(fence->lock);
1768
1769 return r;
1770 }
1771
1772 int
dma_fence_signal_locked(struct dma_fence * fence)1773 dma_fence_signal_locked(struct dma_fence *fence)
1774 {
1775 if (fence == NULL)
1776 return -EINVAL;
1777
1778 return dma_fence_signal_timestamp_locked(fence, ktime_get());
1779 }
1780
1781 int
dma_fence_signal_timestamp(struct dma_fence * fence,ktime_t timestamp)1782 dma_fence_signal_timestamp(struct dma_fence *fence, ktime_t timestamp)
1783 {
1784 int r;
1785
1786 if (fence == NULL)
1787 return -EINVAL;
1788
1789 mtx_enter(fence->lock);
1790 r = dma_fence_signal_timestamp_locked(fence, timestamp);
1791 mtx_leave(fence->lock);
1792
1793 return r;
1794 }
1795
1796 bool
dma_fence_is_signaled(struct dma_fence * fence)1797 dma_fence_is_signaled(struct dma_fence *fence)
1798 {
1799 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
1800 return true;
1801
1802 if (fence->ops->signaled && fence->ops->signaled(fence)) {
1803 dma_fence_signal(fence);
1804 return true;
1805 }
1806
1807 return false;
1808 }
1809
1810 bool
dma_fence_is_signaled_locked(struct dma_fence * fence)1811 dma_fence_is_signaled_locked(struct dma_fence *fence)
1812 {
1813 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
1814 return true;
1815
1816 if (fence->ops->signaled && fence->ops->signaled(fence)) {
1817 dma_fence_signal_locked(fence);
1818 return true;
1819 }
1820
1821 return false;
1822 }
1823
1824 ktime_t
dma_fence_timestamp(struct dma_fence * fence)1825 dma_fence_timestamp(struct dma_fence *fence)
1826 {
1827 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
1828 while (!test_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags))
1829 CPU_BUSY_CYCLE();
1830 return fence->timestamp;
1831 } else {
1832 return ktime_get();
1833 }
1834 }
1835
1836 long
dma_fence_wait_timeout(struct dma_fence * fence,bool intr,long timeout)1837 dma_fence_wait_timeout(struct dma_fence *fence, bool intr, long timeout)
1838 {
1839 if (timeout < 0)
1840 return -EINVAL;
1841
1842 if (fence->ops->wait)
1843 return fence->ops->wait(fence, intr, timeout);
1844 else
1845 return dma_fence_default_wait(fence, intr, timeout);
1846 }
1847
1848 long
dma_fence_wait(struct dma_fence * fence,bool intr)1849 dma_fence_wait(struct dma_fence *fence, bool intr)
1850 {
1851 long ret;
1852
1853 ret = dma_fence_wait_timeout(fence, intr, MAX_SCHEDULE_TIMEOUT);
1854 if (ret < 0)
1855 return ret;
1856
1857 return 0;
1858 }
1859
1860 void
dma_fence_enable_sw_signaling(struct dma_fence * fence)1861 dma_fence_enable_sw_signaling(struct dma_fence *fence)
1862 {
1863 if (!test_and_set_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &fence->flags) &&
1864 !test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags) &&
1865 fence->ops->enable_signaling) {
1866 mtx_enter(fence->lock);
1867 if (!fence->ops->enable_signaling(fence))
1868 dma_fence_signal_locked(fence);
1869 mtx_leave(fence->lock);
1870 }
1871 }
1872
1873 void
dma_fence_init(struct dma_fence * fence,const struct dma_fence_ops * ops,struct mutex * lock,uint64_t context,uint64_t seqno)1874 dma_fence_init(struct dma_fence *fence, const struct dma_fence_ops *ops,
1875 struct mutex *lock, uint64_t context, uint64_t seqno)
1876 {
1877 fence->ops = ops;
1878 fence->lock = lock;
1879 fence->context = context;
1880 fence->seqno = seqno;
1881 fence->flags = 0;
1882 fence->error = 0;
1883 kref_init(&fence->refcount);
1884 INIT_LIST_HEAD(&fence->cb_list);
1885 }
1886
1887 int
dma_fence_add_callback(struct dma_fence * fence,struct dma_fence_cb * cb,dma_fence_func_t func)1888 dma_fence_add_callback(struct dma_fence *fence, struct dma_fence_cb *cb,
1889 dma_fence_func_t func)
1890 {
1891 int ret = 0;
1892 bool was_set;
1893
1894 if (WARN_ON(!fence || !func))
1895 return -EINVAL;
1896
1897 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
1898 INIT_LIST_HEAD(&cb->node);
1899 return -ENOENT;
1900 }
1901
1902 mtx_enter(fence->lock);
1903
1904 was_set = test_and_set_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &fence->flags);
1905
1906 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
1907 ret = -ENOENT;
1908 else if (!was_set && fence->ops->enable_signaling) {
1909 if (!fence->ops->enable_signaling(fence)) {
1910 dma_fence_signal_locked(fence);
1911 ret = -ENOENT;
1912 }
1913 }
1914
1915 if (!ret) {
1916 cb->func = func;
1917 list_add_tail(&cb->node, &fence->cb_list);
1918 } else
1919 INIT_LIST_HEAD(&cb->node);
1920 mtx_leave(fence->lock);
1921
1922 return ret;
1923 }
1924
1925 bool
dma_fence_remove_callback(struct dma_fence * fence,struct dma_fence_cb * cb)1926 dma_fence_remove_callback(struct dma_fence *fence, struct dma_fence_cb *cb)
1927 {
1928 bool ret;
1929
1930 mtx_enter(fence->lock);
1931
1932 ret = !list_empty(&cb->node);
1933 if (ret)
1934 list_del_init(&cb->node);
1935
1936 mtx_leave(fence->lock);
1937
1938 return ret;
1939 }
1940
1941 static atomic64_t drm_fence_context_count = ATOMIC64_INIT(1);
1942
1943 uint64_t
dma_fence_context_alloc(unsigned int num)1944 dma_fence_context_alloc(unsigned int num)
1945 {
1946 return atomic64_add_return(num, &drm_fence_context_count) - num;
1947 }
1948
1949 struct default_wait_cb {
1950 struct dma_fence_cb base;
1951 struct proc *proc;
1952 };
1953
1954 static void
dma_fence_default_wait_cb(struct dma_fence * fence,struct dma_fence_cb * cb)1955 dma_fence_default_wait_cb(struct dma_fence *fence, struct dma_fence_cb *cb)
1956 {
1957 struct default_wait_cb *wait =
1958 container_of(cb, struct default_wait_cb, base);
1959 wake_up_process(wait->proc);
1960 }
1961
1962 long
dma_fence_default_wait(struct dma_fence * fence,bool intr,signed long timeout)1963 dma_fence_default_wait(struct dma_fence *fence, bool intr, signed long timeout)
1964 {
1965 long ret = timeout ? timeout : 1;
1966 unsigned long end;
1967 int err;
1968 struct default_wait_cb cb;
1969 bool was_set;
1970
1971 KASSERT(timeout <= INT_MAX);
1972
1973 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
1974 return ret;
1975
1976 mtx_enter(fence->lock);
1977
1978 was_set = test_and_set_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT,
1979 &fence->flags);
1980
1981 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
1982 goto out;
1983
1984 if (!was_set && fence->ops->enable_signaling) {
1985 if (!fence->ops->enable_signaling(fence)) {
1986 dma_fence_signal_locked(fence);
1987 goto out;
1988 }
1989 }
1990
1991 if (timeout == 0) {
1992 ret = 0;
1993 goto out;
1994 }
1995
1996 cb.base.func = dma_fence_default_wait_cb;
1997 cb.proc = curproc;
1998 list_add(&cb.base.node, &fence->cb_list);
1999
2000 end = jiffies + timeout;
2001 for (ret = timeout; ret > 0; ret = MAX(0, end - jiffies)) {
2002 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
2003 break;
2004 err = msleep(curproc, fence->lock, intr ? PCATCH : 0,
2005 "dmafence", ret);
2006 if (err == EINTR || err == ERESTART) {
2007 ret = -ERESTARTSYS;
2008 break;
2009 }
2010 }
2011
2012 if (!list_empty(&cb.base.node))
2013 list_del(&cb.base.node);
2014 out:
2015 mtx_leave(fence->lock);
2016
2017 return ret;
2018 }
2019
2020 static bool
dma_fence_test_signaled_any(struct dma_fence ** fences,uint32_t count,uint32_t * idx)2021 dma_fence_test_signaled_any(struct dma_fence **fences, uint32_t count,
2022 uint32_t *idx)
2023 {
2024 int i;
2025
2026 for (i = 0; i < count; ++i) {
2027 struct dma_fence *fence = fences[i];
2028 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
2029 if (idx)
2030 *idx = i;
2031 return true;
2032 }
2033 }
2034 return false;
2035 }
2036
2037 long
dma_fence_wait_any_timeout(struct dma_fence ** fences,uint32_t count,bool intr,long timeout,uint32_t * idx)2038 dma_fence_wait_any_timeout(struct dma_fence **fences, uint32_t count,
2039 bool intr, long timeout, uint32_t *idx)
2040 {
2041 struct default_wait_cb *cb;
2042 long ret = timeout;
2043 unsigned long end;
2044 int i, err;
2045
2046 KASSERT(timeout <= INT_MAX);
2047
2048 if (timeout == 0) {
2049 for (i = 0; i < count; i++) {
2050 if (dma_fence_is_signaled(fences[i])) {
2051 if (idx)
2052 *idx = i;
2053 return 1;
2054 }
2055 }
2056 return 0;
2057 }
2058
2059 cb = mallocarray(count, sizeof(*cb), M_DRM, M_WAITOK|M_CANFAIL|M_ZERO);
2060 if (cb == NULL)
2061 return -ENOMEM;
2062
2063 for (i = 0; i < count; i++) {
2064 struct dma_fence *fence = fences[i];
2065 cb[i].proc = curproc;
2066 if (dma_fence_add_callback(fence, &cb[i].base,
2067 dma_fence_default_wait_cb)) {
2068 if (idx)
2069 *idx = i;
2070 goto cb_cleanup;
2071 }
2072 }
2073
2074 end = jiffies + timeout;
2075 for (ret = timeout; ret > 0; ret = MAX(0, end - jiffies)) {
2076 if (dma_fence_test_signaled_any(fences, count, idx))
2077 break;
2078 err = tsleep(curproc, intr ? PCATCH : 0, "dfwat", ret);
2079 if (err == EINTR || err == ERESTART) {
2080 ret = -ERESTARTSYS;
2081 break;
2082 }
2083 }
2084
2085 cb_cleanup:
2086 while (i-- > 0)
2087 dma_fence_remove_callback(fences[i], &cb[i].base);
2088 free(cb, M_DRM, count * sizeof(*cb));
2089 return ret;
2090 }
2091
2092 void
dma_fence_set_deadline(struct dma_fence * f,ktime_t t)2093 dma_fence_set_deadline(struct dma_fence *f, ktime_t t)
2094 {
2095 if (f->ops->set_deadline == NULL)
2096 return;
2097 if (dma_fence_is_signaled(f) == false)
2098 f->ops->set_deadline(f, t);
2099 }
2100
2101 static struct dma_fence dma_fence_stub;
2102 static struct mutex dma_fence_stub_mtx = MUTEX_INITIALIZER(IPL_TTY);
2103
2104 static const char *
dma_fence_stub_get_name(struct dma_fence * fence)2105 dma_fence_stub_get_name(struct dma_fence *fence)
2106 {
2107 return "stub";
2108 }
2109
2110 static const struct dma_fence_ops dma_fence_stub_ops = {
2111 .get_driver_name = dma_fence_stub_get_name,
2112 .get_timeline_name = dma_fence_stub_get_name,
2113 };
2114
2115 struct dma_fence *
dma_fence_get_stub(void)2116 dma_fence_get_stub(void)
2117 {
2118 mtx_enter(&dma_fence_stub_mtx);
2119 if (dma_fence_stub.ops == NULL) {
2120 dma_fence_init(&dma_fence_stub, &dma_fence_stub_ops,
2121 &dma_fence_stub_mtx, 0, 0);
2122 dma_fence_signal_locked(&dma_fence_stub);
2123 }
2124 mtx_leave(&dma_fence_stub_mtx);
2125
2126 return dma_fence_get(&dma_fence_stub);
2127 }
2128
2129 struct dma_fence *
dma_fence_allocate_private_stub(ktime_t ts)2130 dma_fence_allocate_private_stub(ktime_t ts)
2131 {
2132 struct dma_fence *f = malloc(sizeof(*f), M_DRM,
2133 M_ZERO | M_WAITOK | M_CANFAIL);
2134 if (f == NULL)
2135 return NULL;
2136 dma_fence_init(f, &dma_fence_stub_ops, &dma_fence_stub_mtx, 0, 0);
2137 dma_fence_signal_timestamp(f, ts);
2138 return f;
2139 }
2140
2141 static const char *
dma_fence_array_get_driver_name(struct dma_fence * fence)2142 dma_fence_array_get_driver_name(struct dma_fence *fence)
2143 {
2144 return "dma_fence_array";
2145 }
2146
2147 static const char *
dma_fence_array_get_timeline_name(struct dma_fence * fence)2148 dma_fence_array_get_timeline_name(struct dma_fence *fence)
2149 {
2150 return "unbound";
2151 }
2152
2153 static void
irq_dma_fence_array_work(void * arg)2154 irq_dma_fence_array_work(void *arg)
2155 {
2156 struct dma_fence_array *dfa = (struct dma_fence_array *)arg;
2157 dma_fence_signal(&dfa->base);
2158 dma_fence_put(&dfa->base);
2159 }
2160
2161 static void
dma_fence_array_cb_func(struct dma_fence * f,struct dma_fence_cb * cb)2162 dma_fence_array_cb_func(struct dma_fence *f, struct dma_fence_cb *cb)
2163 {
2164 struct dma_fence_array_cb *array_cb =
2165 container_of(cb, struct dma_fence_array_cb, cb);
2166 struct dma_fence_array *dfa = array_cb->array;
2167
2168 if (atomic_dec_and_test(&dfa->num_pending))
2169 timeout_add(&dfa->to, 1);
2170 else
2171 dma_fence_put(&dfa->base);
2172 }
2173
2174 static bool
dma_fence_array_enable_signaling(struct dma_fence * fence)2175 dma_fence_array_enable_signaling(struct dma_fence *fence)
2176 {
2177 struct dma_fence_array *dfa = to_dma_fence_array(fence);
2178 struct dma_fence_array_cb *cb = (void *)(&dfa[1]);
2179 int i;
2180
2181 for (i = 0; i < dfa->num_fences; ++i) {
2182 cb[i].array = dfa;
2183 dma_fence_get(&dfa->base);
2184 if (dma_fence_add_callback(dfa->fences[i], &cb[i].cb,
2185 dma_fence_array_cb_func)) {
2186 dma_fence_put(&dfa->base);
2187 if (atomic_dec_and_test(&dfa->num_pending))
2188 return false;
2189 }
2190 }
2191
2192 return true;
2193 }
2194
2195 static bool
dma_fence_array_signaled(struct dma_fence * fence)2196 dma_fence_array_signaled(struct dma_fence *fence)
2197 {
2198 struct dma_fence_array *dfa = to_dma_fence_array(fence);
2199
2200 return atomic_read(&dfa->num_pending) <= 0;
2201 }
2202
2203 static void
dma_fence_array_release(struct dma_fence * fence)2204 dma_fence_array_release(struct dma_fence *fence)
2205 {
2206 struct dma_fence_array *dfa = to_dma_fence_array(fence);
2207 int i;
2208
2209 for (i = 0; i < dfa->num_fences; ++i)
2210 dma_fence_put(dfa->fences[i]);
2211
2212 free(dfa->fences, M_DRM, 0);
2213 dma_fence_free(fence);
2214 }
2215
2216 struct dma_fence_array *
dma_fence_array_create(int num_fences,struct dma_fence ** fences,u64 context,unsigned seqno,bool signal_on_any)2217 dma_fence_array_create(int num_fences, struct dma_fence **fences, u64 context,
2218 unsigned seqno, bool signal_on_any)
2219 {
2220 struct dma_fence_array *dfa = malloc(sizeof(*dfa) +
2221 (num_fences * sizeof(struct dma_fence_array_cb)),
2222 M_DRM, M_WAITOK|M_CANFAIL|M_ZERO);
2223 if (dfa == NULL)
2224 return NULL;
2225
2226 mtx_init(&dfa->lock, IPL_TTY);
2227 dma_fence_init(&dfa->base, &dma_fence_array_ops, &dfa->lock,
2228 context, seqno);
2229 timeout_set(&dfa->to, irq_dma_fence_array_work, dfa);
2230
2231 dfa->num_fences = num_fences;
2232 atomic_set(&dfa->num_pending, signal_on_any ? 1 : num_fences);
2233 dfa->fences = fences;
2234
2235 return dfa;
2236 }
2237
2238 struct dma_fence *
dma_fence_array_first(struct dma_fence * f)2239 dma_fence_array_first(struct dma_fence *f)
2240 {
2241 struct dma_fence_array *dfa;
2242
2243 if (f == NULL)
2244 return NULL;
2245
2246 if ((dfa = to_dma_fence_array(f)) == NULL)
2247 return f;
2248
2249 if (dfa->num_fences > 0)
2250 return dfa->fences[0];
2251
2252 return NULL;
2253 }
2254
2255 struct dma_fence *
dma_fence_array_next(struct dma_fence * f,unsigned int i)2256 dma_fence_array_next(struct dma_fence *f, unsigned int i)
2257 {
2258 struct dma_fence_array *dfa;
2259
2260 if (f == NULL)
2261 return NULL;
2262
2263 if ((dfa = to_dma_fence_array(f)) == NULL)
2264 return NULL;
2265
2266 if (i < dfa->num_fences)
2267 return dfa->fences[i];
2268
2269 return NULL;
2270 }
2271
2272 const struct dma_fence_ops dma_fence_array_ops = {
2273 .get_driver_name = dma_fence_array_get_driver_name,
2274 .get_timeline_name = dma_fence_array_get_timeline_name,
2275 .enable_signaling = dma_fence_array_enable_signaling,
2276 .signaled = dma_fence_array_signaled,
2277 .release = dma_fence_array_release,
2278 };
2279
2280 int
dma_fence_chain_find_seqno(struct dma_fence ** df,uint64_t seqno)2281 dma_fence_chain_find_seqno(struct dma_fence **df, uint64_t seqno)
2282 {
2283 struct dma_fence_chain *chain;
2284 struct dma_fence *fence;
2285
2286 if (seqno == 0)
2287 return 0;
2288
2289 if ((chain = to_dma_fence_chain(*df)) == NULL)
2290 return -EINVAL;
2291
2292 fence = &chain->base;
2293 if (fence->seqno < seqno)
2294 return -EINVAL;
2295
2296 dma_fence_chain_for_each(*df, fence) {
2297 if ((*df)->context != fence->context)
2298 break;
2299
2300 chain = to_dma_fence_chain(*df);
2301 if (chain->prev_seqno < seqno)
2302 break;
2303 }
2304 dma_fence_put(fence);
2305
2306 return 0;
2307 }
2308
2309 void
dma_fence_chain_init(struct dma_fence_chain * chain,struct dma_fence * prev,struct dma_fence * fence,uint64_t seqno)2310 dma_fence_chain_init(struct dma_fence_chain *chain, struct dma_fence *prev,
2311 struct dma_fence *fence, uint64_t seqno)
2312 {
2313 uint64_t context;
2314
2315 chain->fence = fence;
2316 chain->prev = prev;
2317 mtx_init(&chain->lock, IPL_TTY);
2318
2319 /* if prev is a chain */
2320 if (to_dma_fence_chain(prev) != NULL) {
2321 if (__dma_fence_is_later(seqno, prev->seqno, prev->ops)) {
2322 chain->prev_seqno = prev->seqno;
2323 context = prev->context;
2324 } else {
2325 chain->prev_seqno = 0;
2326 context = dma_fence_context_alloc(1);
2327 seqno = prev->seqno;
2328 }
2329 } else {
2330 chain->prev_seqno = 0;
2331 context = dma_fence_context_alloc(1);
2332 }
2333
2334 dma_fence_init(&chain->base, &dma_fence_chain_ops, &chain->lock,
2335 context, seqno);
2336 }
2337
2338 static const char *
dma_fence_chain_get_driver_name(struct dma_fence * fence)2339 dma_fence_chain_get_driver_name(struct dma_fence *fence)
2340 {
2341 return "dma_fence_chain";
2342 }
2343
2344 static const char *
dma_fence_chain_get_timeline_name(struct dma_fence * fence)2345 dma_fence_chain_get_timeline_name(struct dma_fence *fence)
2346 {
2347 return "unbound";
2348 }
2349
2350 static bool dma_fence_chain_enable_signaling(struct dma_fence *);
2351
2352 static void
dma_fence_chain_timo(void * arg)2353 dma_fence_chain_timo(void *arg)
2354 {
2355 struct dma_fence_chain *chain = (struct dma_fence_chain *)arg;
2356
2357 if (dma_fence_chain_enable_signaling(&chain->base) == false)
2358 dma_fence_signal(&chain->base);
2359 dma_fence_put(&chain->base);
2360 }
2361
2362 static void
dma_fence_chain_cb(struct dma_fence * f,struct dma_fence_cb * cb)2363 dma_fence_chain_cb(struct dma_fence *f, struct dma_fence_cb *cb)
2364 {
2365 struct dma_fence_chain *chain =
2366 container_of(cb, struct dma_fence_chain, cb);
2367 timeout_set(&chain->to, dma_fence_chain_timo, chain);
2368 timeout_add(&chain->to, 1);
2369 dma_fence_put(f);
2370 }
2371
2372 static bool
dma_fence_chain_enable_signaling(struct dma_fence * fence)2373 dma_fence_chain_enable_signaling(struct dma_fence *fence)
2374 {
2375 struct dma_fence_chain *chain, *h;
2376 struct dma_fence *f;
2377
2378 h = to_dma_fence_chain(fence);
2379 dma_fence_get(&h->base);
2380 dma_fence_chain_for_each(fence, &h->base) {
2381 chain = to_dma_fence_chain(fence);
2382 if (chain == NULL)
2383 f = fence;
2384 else
2385 f = chain->fence;
2386
2387 dma_fence_get(f);
2388 if (!dma_fence_add_callback(f, &h->cb, dma_fence_chain_cb)) {
2389 dma_fence_put(fence);
2390 return true;
2391 }
2392 dma_fence_put(f);
2393 }
2394 dma_fence_put(&h->base);
2395 return false;
2396 }
2397
2398 static bool
dma_fence_chain_signaled(struct dma_fence * fence)2399 dma_fence_chain_signaled(struct dma_fence *fence)
2400 {
2401 struct dma_fence_chain *chain;
2402 struct dma_fence *f;
2403
2404 dma_fence_chain_for_each(fence, fence) {
2405 chain = to_dma_fence_chain(fence);
2406 if (chain == NULL)
2407 f = fence;
2408 else
2409 f = chain->fence;
2410
2411 if (dma_fence_is_signaled(f) == false) {
2412 dma_fence_put(fence);
2413 return false;
2414 }
2415 }
2416 return true;
2417 }
2418
2419 static void
dma_fence_chain_release(struct dma_fence * fence)2420 dma_fence_chain_release(struct dma_fence *fence)
2421 {
2422 struct dma_fence_chain *chain = to_dma_fence_chain(fence);
2423 struct dma_fence_chain *prev_chain;
2424 struct dma_fence *prev;
2425
2426 for (prev = chain->prev; prev != NULL; prev = chain->prev) {
2427 if (kref_read(&prev->refcount) > 1)
2428 break;
2429 if ((prev_chain = to_dma_fence_chain(prev)) == NULL)
2430 break;
2431 chain->prev = prev_chain->prev;
2432 prev_chain->prev = NULL;
2433 dma_fence_put(prev);
2434 }
2435 dma_fence_put(prev);
2436 dma_fence_put(chain->fence);
2437 dma_fence_free(fence);
2438 }
2439
2440 struct dma_fence *
dma_fence_chain_walk(struct dma_fence * fence)2441 dma_fence_chain_walk(struct dma_fence *fence)
2442 {
2443 struct dma_fence_chain *chain = to_dma_fence_chain(fence), *prev_chain;
2444 struct dma_fence *prev, *new_prev, *tmp;
2445
2446 if (chain == NULL) {
2447 dma_fence_put(fence);
2448 return NULL;
2449 }
2450
2451 while ((prev = dma_fence_get(chain->prev)) != NULL) {
2452 prev_chain = to_dma_fence_chain(prev);
2453 if (prev_chain != NULL) {
2454 if (!dma_fence_is_signaled(prev_chain->fence))
2455 break;
2456 new_prev = dma_fence_get(prev_chain->prev);
2457 } else {
2458 if (!dma_fence_is_signaled(prev))
2459 break;
2460 new_prev = NULL;
2461 }
2462 tmp = atomic_cas_ptr(&chain->prev, prev, new_prev);
2463 dma_fence_put(tmp == prev ? prev : new_prev);
2464 dma_fence_put(prev);
2465 }
2466
2467 dma_fence_put(fence);
2468 return prev;
2469 }
2470
2471 const struct dma_fence_ops dma_fence_chain_ops = {
2472 .get_driver_name = dma_fence_chain_get_driver_name,
2473 .get_timeline_name = dma_fence_chain_get_timeline_name,
2474 .enable_signaling = dma_fence_chain_enable_signaling,
2475 .signaled = dma_fence_chain_signaled,
2476 .release = dma_fence_chain_release,
2477 .use_64bit_seqno = true,
2478 };
2479
2480 bool
dma_fence_is_container(struct dma_fence * fence)2481 dma_fence_is_container(struct dma_fence *fence)
2482 {
2483 return (fence->ops == &dma_fence_chain_ops) ||
2484 (fence->ops == &dma_fence_array_ops);
2485 }
2486
2487 int
dmabuf_read(struct file * fp,struct uio * uio,int fflags)2488 dmabuf_read(struct file *fp, struct uio *uio, int fflags)
2489 {
2490 return (ENXIO);
2491 }
2492
2493 int
dmabuf_write(struct file * fp,struct uio * uio,int fflags)2494 dmabuf_write(struct file *fp, struct uio *uio, int fflags)
2495 {
2496 return (ENXIO);
2497 }
2498
2499 int
dmabuf_ioctl(struct file * fp,u_long com,caddr_t data,struct proc * p)2500 dmabuf_ioctl(struct file *fp, u_long com, caddr_t data, struct proc *p)
2501 {
2502 return (ENOTTY);
2503 }
2504
2505 int
dmabuf_kqfilter(struct file * fp,struct knote * kn)2506 dmabuf_kqfilter(struct file *fp, struct knote *kn)
2507 {
2508 return (EINVAL);
2509 }
2510
2511 int
dmabuf_stat(struct file * fp,struct stat * st,struct proc * p)2512 dmabuf_stat(struct file *fp, struct stat *st, struct proc *p)
2513 {
2514 struct dma_buf *dmabuf = fp->f_data;
2515
2516 memset(st, 0, sizeof(*st));
2517 st->st_size = dmabuf->size;
2518 st->st_mode = S_IFIFO; /* XXX */
2519 return (0);
2520 }
2521
2522 int
dmabuf_close(struct file * fp,struct proc * p)2523 dmabuf_close(struct file *fp, struct proc *p)
2524 {
2525 struct dma_buf *dmabuf = fp->f_data;
2526
2527 fp->f_data = NULL;
2528 KERNEL_LOCK();
2529 dmabuf->ops->release(dmabuf);
2530 KERNEL_UNLOCK();
2531 free(dmabuf, M_DRM, sizeof(struct dma_buf));
2532 return (0);
2533 }
2534
2535 int
dmabuf_seek(struct file * fp,off_t * offset,int whence,struct proc * p)2536 dmabuf_seek(struct file *fp, off_t *offset, int whence, struct proc *p)
2537 {
2538 struct dma_buf *dmabuf = fp->f_data;
2539 off_t newoff;
2540
2541 if (*offset != 0)
2542 return (EINVAL);
2543
2544 switch (whence) {
2545 case SEEK_SET:
2546 newoff = 0;
2547 break;
2548 case SEEK_END:
2549 newoff = dmabuf->size;
2550 break;
2551 default:
2552 return (EINVAL);
2553 }
2554 mtx_enter(&fp->f_mtx);
2555 fp->f_offset = newoff;
2556 mtx_leave(&fp->f_mtx);
2557 *offset = newoff;
2558 return (0);
2559 }
2560
2561 const struct fileops dmabufops = {
2562 .fo_read = dmabuf_read,
2563 .fo_write = dmabuf_write,
2564 .fo_ioctl = dmabuf_ioctl,
2565 .fo_kqfilter = dmabuf_kqfilter,
2566 .fo_stat = dmabuf_stat,
2567 .fo_close = dmabuf_close,
2568 .fo_seek = dmabuf_seek,
2569 };
2570
2571 struct dma_buf *
dma_buf_export(const struct dma_buf_export_info * info)2572 dma_buf_export(const struct dma_buf_export_info *info)
2573 {
2574 struct proc *p = curproc;
2575 struct dma_buf *dmabuf;
2576 struct file *fp;
2577
2578 fp = fnew(p);
2579 if (fp == NULL)
2580 return ERR_PTR(-ENFILE);
2581 fp->f_type = DTYPE_DMABUF;
2582 fp->f_ops = &dmabufops;
2583 dmabuf = malloc(sizeof(struct dma_buf), M_DRM, M_WAITOK | M_ZERO);
2584 dmabuf->priv = info->priv;
2585 dmabuf->ops = info->ops;
2586 dmabuf->size = info->size;
2587 dmabuf->file = fp;
2588 fp->f_data = dmabuf;
2589 INIT_LIST_HEAD(&dmabuf->attachments);
2590 return dmabuf;
2591 }
2592
2593 struct dma_buf *
dma_buf_get(int fd)2594 dma_buf_get(int fd)
2595 {
2596 struct proc *p = curproc;
2597 struct filedesc *fdp = p->p_fd;
2598 struct file *fp;
2599
2600 if ((fp = fd_getfile(fdp, fd)) == NULL)
2601 return ERR_PTR(-EBADF);
2602
2603 if (fp->f_type != DTYPE_DMABUF) {
2604 FRELE(fp, p);
2605 return ERR_PTR(-EINVAL);
2606 }
2607
2608 return fp->f_data;
2609 }
2610
2611 void
dma_buf_put(struct dma_buf * dmabuf)2612 dma_buf_put(struct dma_buf *dmabuf)
2613 {
2614 KASSERT(dmabuf);
2615 KASSERT(dmabuf->file);
2616
2617 FRELE(dmabuf->file, curproc);
2618 }
2619
2620 int
dma_buf_fd(struct dma_buf * dmabuf,int flags)2621 dma_buf_fd(struct dma_buf *dmabuf, int flags)
2622 {
2623 struct proc *p = curproc;
2624 struct filedesc *fdp = p->p_fd;
2625 struct file *fp = dmabuf->file;
2626 int fd, cloexec, error;
2627
2628 cloexec = (flags & O_CLOEXEC) ? UF_EXCLOSE : 0;
2629
2630 fdplock(fdp);
2631 restart:
2632 if ((error = fdalloc(p, 0, &fd)) != 0) {
2633 if (error == ENOSPC) {
2634 fdexpand(p);
2635 goto restart;
2636 }
2637 fdpunlock(fdp);
2638 return -error;
2639 }
2640
2641 fdinsert(fdp, fd, cloexec, fp);
2642 fdpunlock(fdp);
2643
2644 return fd;
2645 }
2646
2647 void
get_dma_buf(struct dma_buf * dmabuf)2648 get_dma_buf(struct dma_buf *dmabuf)
2649 {
2650 FREF(dmabuf->file);
2651 }
2652
2653 enum pci_bus_speed
pcie_get_speed_cap(struct pci_dev * pdev)2654 pcie_get_speed_cap(struct pci_dev *pdev)
2655 {
2656 pci_chipset_tag_t pc;
2657 pcitag_t tag;
2658 int pos ;
2659 pcireg_t xcap, lnkcap = 0, lnkcap2 = 0;
2660 pcireg_t id;
2661 enum pci_bus_speed cap = PCI_SPEED_UNKNOWN;
2662 int bus, device, function;
2663
2664 if (pdev == NULL)
2665 return PCI_SPEED_UNKNOWN;
2666
2667 pc = pdev->pc;
2668 tag = pdev->tag;
2669
2670 if (!pci_get_capability(pc, tag, PCI_CAP_PCIEXPRESS,
2671 &pos, NULL))
2672 return PCI_SPEED_UNKNOWN;
2673
2674 id = pci_conf_read(pc, tag, PCI_ID_REG);
2675 pci_decompose_tag(pc, tag, &bus, &device, &function);
2676
2677 /* we've been informed via and serverworks don't make the cut */
2678 if (PCI_VENDOR(id) == PCI_VENDOR_VIATECH ||
2679 PCI_VENDOR(id) == PCI_VENDOR_RCC)
2680 return PCI_SPEED_UNKNOWN;
2681
2682 lnkcap = pci_conf_read(pc, tag, pos + PCI_PCIE_LCAP);
2683 xcap = pci_conf_read(pc, tag, pos + PCI_PCIE_XCAP);
2684 if (PCI_PCIE_XCAP_VER(xcap) >= 2)
2685 lnkcap2 = pci_conf_read(pc, tag, pos + PCI_PCIE_LCAP2);
2686
2687 lnkcap &= 0x0f;
2688 lnkcap2 &= 0xfe;
2689
2690 if (lnkcap2) { /* PCIE GEN 3.0 */
2691 if (lnkcap2 & 0x02)
2692 cap = PCIE_SPEED_2_5GT;
2693 if (lnkcap2 & 0x04)
2694 cap = PCIE_SPEED_5_0GT;
2695 if (lnkcap2 & 0x08)
2696 cap = PCIE_SPEED_8_0GT;
2697 if (lnkcap2 & 0x10)
2698 cap = PCIE_SPEED_16_0GT;
2699 if (lnkcap2 & 0x20)
2700 cap = PCIE_SPEED_32_0GT;
2701 if (lnkcap2 & 0x40)
2702 cap = PCIE_SPEED_64_0GT;
2703 } else {
2704 if (lnkcap & 0x01)
2705 cap = PCIE_SPEED_2_5GT;
2706 if (lnkcap & 0x02)
2707 cap = PCIE_SPEED_5_0GT;
2708 }
2709
2710 DRM_INFO("probing pcie caps for device %d:%d:%d 0x%04x:0x%04x = %x/%x\n",
2711 bus, device, function, PCI_VENDOR(id), PCI_PRODUCT(id), lnkcap,
2712 lnkcap2);
2713 return cap;
2714 }
2715
2716 enum pcie_link_width
pcie_get_width_cap(struct pci_dev * pdev)2717 pcie_get_width_cap(struct pci_dev *pdev)
2718 {
2719 pci_chipset_tag_t pc = pdev->pc;
2720 pcitag_t tag = pdev->tag;
2721 int pos ;
2722 pcireg_t lnkcap = 0;
2723 pcireg_t id;
2724 int bus, device, function;
2725
2726 if (!pci_get_capability(pc, tag, PCI_CAP_PCIEXPRESS,
2727 &pos, NULL))
2728 return PCIE_LNK_WIDTH_UNKNOWN;
2729
2730 id = pci_conf_read(pc, tag, PCI_ID_REG);
2731 pci_decompose_tag(pc, tag, &bus, &device, &function);
2732
2733 lnkcap = pci_conf_read(pc, tag, pos + PCI_PCIE_LCAP);
2734
2735 DRM_INFO("probing pcie width for device %d:%d:%d 0x%04x:0x%04x = %x\n",
2736 bus, device, function, PCI_VENDOR(id), PCI_PRODUCT(id), lnkcap);
2737
2738 if (lnkcap)
2739 return (lnkcap & 0x3f0) >> 4;
2740 return PCIE_LNK_WIDTH_UNKNOWN;
2741 }
2742
2743 bool
pcie_aspm_enabled(struct pci_dev * pdev)2744 pcie_aspm_enabled(struct pci_dev *pdev)
2745 {
2746 pci_chipset_tag_t pc = pdev->pc;
2747 pcitag_t tag = pdev->tag;
2748 int pos ;
2749 pcireg_t lcsr;
2750
2751 if (!pci_get_capability(pc, tag, PCI_CAP_PCIEXPRESS,
2752 &pos, NULL))
2753 return false;
2754
2755 lcsr = pci_conf_read(pc, tag, pos + PCI_PCIE_LCSR);
2756 if ((lcsr & (PCI_PCIE_LCSR_ASPM_L0S | PCI_PCIE_LCSR_ASPM_L1)) != 0)
2757 return true;
2758
2759 return false;
2760 }
2761
2762 static wait_queue_head_t bit_waitq;
2763 wait_queue_head_t var_waitq;
2764 struct mutex wait_bit_mtx = MUTEX_INITIALIZER(IPL_TTY);
2765
2766 int
wait_on_bit(unsigned long * word,int bit,unsigned mode)2767 wait_on_bit(unsigned long *word, int bit, unsigned mode)
2768 {
2769 int err;
2770
2771 if (!test_bit(bit, word))
2772 return 0;
2773
2774 mtx_enter(&wait_bit_mtx);
2775 while (test_bit(bit, word)) {
2776 err = msleep_nsec(word, &wait_bit_mtx, PWAIT | mode, "wtb",
2777 INFSLP);
2778 if (err) {
2779 mtx_leave(&wait_bit_mtx);
2780 return 1;
2781 }
2782 }
2783 mtx_leave(&wait_bit_mtx);
2784 return 0;
2785 }
2786
2787 int
wait_on_bit_timeout(unsigned long * word,int bit,unsigned mode,int timo)2788 wait_on_bit_timeout(unsigned long *word, int bit, unsigned mode, int timo)
2789 {
2790 int err;
2791
2792 if (!test_bit(bit, word))
2793 return 0;
2794
2795 mtx_enter(&wait_bit_mtx);
2796 while (test_bit(bit, word)) {
2797 err = msleep(word, &wait_bit_mtx, PWAIT | mode, "wtb", timo);
2798 if (err) {
2799 mtx_leave(&wait_bit_mtx);
2800 return 1;
2801 }
2802 }
2803 mtx_leave(&wait_bit_mtx);
2804 return 0;
2805 }
2806
2807 void
wake_up_bit(void * word,int bit)2808 wake_up_bit(void *word, int bit)
2809 {
2810 mtx_enter(&wait_bit_mtx);
2811 wakeup(word);
2812 mtx_leave(&wait_bit_mtx);
2813 }
2814
2815 void
clear_and_wake_up_bit(int bit,void * word)2816 clear_and_wake_up_bit(int bit, void *word)
2817 {
2818 clear_bit(bit, word);
2819 wake_up_bit(word, bit);
2820 }
2821
2822 wait_queue_head_t *
bit_waitqueue(void * word,int bit)2823 bit_waitqueue(void *word, int bit)
2824 {
2825 /* XXX hash table of wait queues? */
2826 return &bit_waitq;
2827 }
2828
2829 wait_queue_head_t *
__var_waitqueue(void * p)2830 __var_waitqueue(void *p)
2831 {
2832 /* XXX hash table of wait queues? */
2833 return &bit_waitq;
2834 }
2835
2836 struct workqueue_struct *system_wq;
2837 struct workqueue_struct *system_highpri_wq;
2838 struct workqueue_struct *system_unbound_wq;
2839 struct workqueue_struct *system_long_wq;
2840 struct taskq *taskletq;
2841
2842 void
drm_linux_init(void)2843 drm_linux_init(void)
2844 {
2845 system_wq = (struct workqueue_struct *)
2846 taskq_create("drmwq", 4, IPL_HIGH, 0);
2847 system_highpri_wq = (struct workqueue_struct *)
2848 taskq_create("drmhpwq", 4, IPL_HIGH, 0);
2849 system_unbound_wq = (struct workqueue_struct *)
2850 taskq_create("drmubwq", 4, IPL_HIGH, 0);
2851 system_long_wq = (struct workqueue_struct *)
2852 taskq_create("drmlwq", 4, IPL_HIGH, 0);
2853
2854 taskletq = taskq_create("drmtskl", 1, IPL_HIGH, 0);
2855
2856 init_waitqueue_head(&bit_waitq);
2857 init_waitqueue_head(&var_waitq);
2858
2859 pool_init(&idr_pool, sizeof(struct idr_entry), 0, IPL_TTY, 0,
2860 "idrpl", NULL);
2861 pool_init(&xa_pool, sizeof(struct xarray_entry), 0, IPL_NONE, 0,
2862 "xapl", NULL);
2863
2864 kmap_atomic_va =
2865 (vaddr_t)km_alloc(PAGE_SIZE, &kv_any, &kp_none, &kd_waitok);
2866
2867 #if NACPI > 0
2868 if (acpi_softc) {
2869 memcpy(&acpi_gbl_FADT, acpi_softc->sc_fadt,
2870 sizeof(acpi_gbl_FADT));
2871 }
2872 #endif
2873 }
2874
2875 void
drm_linux_exit(void)2876 drm_linux_exit(void)
2877 {
2878 pool_destroy(&xa_pool);
2879 pool_destroy(&idr_pool);
2880
2881 taskq_destroy(taskletq);
2882
2883 taskq_destroy((struct taskq *)system_long_wq);
2884 taskq_destroy((struct taskq *)system_unbound_wq);
2885 taskq_destroy((struct taskq *)system_highpri_wq);
2886 taskq_destroy((struct taskq *)system_wq);
2887 }
2888
2889 #define PCIE_ECAP_RESIZE_BAR 0x15
2890 #define RBCAP0 0x04
2891 #define RBCTRL0 0x08
2892 #define RBCTRL_BARINDEX_MASK 0x07
2893 #define RBCTRL_BARSIZE_MASK 0x1f00
2894 #define RBCTRL_BARSIZE_SHIFT 8
2895
2896 /* size in MB is 1 << nsize */
2897 int
pci_resize_resource(struct pci_dev * pdev,int bar,int nsize)2898 pci_resize_resource(struct pci_dev *pdev, int bar, int nsize)
2899 {
2900 pcireg_t reg;
2901 uint32_t offset, capid;
2902
2903 KASSERT(bar == 0);
2904
2905 offset = PCI_PCIE_ECAP;
2906
2907 /* search PCI Express Extended Capabilities */
2908 do {
2909 reg = pci_conf_read(pdev->pc, pdev->tag, offset);
2910 capid = PCI_PCIE_ECAP_ID(reg);
2911 if (capid == PCIE_ECAP_RESIZE_BAR)
2912 break;
2913 offset = PCI_PCIE_ECAP_NEXT(reg);
2914 } while (capid != 0);
2915
2916 if (capid == 0) {
2917 printf("%s: could not find resize bar cap!\n", __func__);
2918 return -ENOTSUP;
2919 }
2920
2921 reg = pci_conf_read(pdev->pc, pdev->tag, offset + RBCAP0);
2922
2923 if ((reg & (1 << (nsize + 4))) == 0) {
2924 printf("%s size not supported\n", __func__);
2925 return -ENOTSUP;
2926 }
2927
2928 reg = pci_conf_read(pdev->pc, pdev->tag, offset + RBCTRL0);
2929 if ((reg & RBCTRL_BARINDEX_MASK) != 0) {
2930 printf("%s BAR index not 0\n", __func__);
2931 return -EINVAL;
2932 }
2933
2934 reg &= ~RBCTRL_BARSIZE_MASK;
2935 reg |= (nsize << RBCTRL_BARSIZE_SHIFT) & RBCTRL_BARSIZE_MASK;
2936
2937 pci_conf_write(pdev->pc, pdev->tag, offset + RBCTRL0, reg);
2938
2939 return 0;
2940 }
2941
2942 TAILQ_HEAD(, shrinker) shrinkers = TAILQ_HEAD_INITIALIZER(shrinkers);
2943
2944 struct shrinker *
shrinker_alloc(u_int flags,const char * format,...)2945 shrinker_alloc(u_int flags, const char *format, ...)
2946 {
2947 struct shrinker *s;
2948
2949 s = kzalloc(sizeof(*s), GFP_KERNEL);
2950 s->seeks = DEFAULT_SEEKS;
2951 return s;
2952 }
2953
2954 void
shrinker_register(struct shrinker * shrinker)2955 shrinker_register(struct shrinker *shrinker)
2956 {
2957 TAILQ_INSERT_TAIL(&shrinkers, shrinker, next);
2958 }
2959
2960 void
shrinker_free(struct shrinker * shrinker)2961 shrinker_free(struct shrinker *shrinker)
2962 {
2963 TAILQ_REMOVE(&shrinkers, shrinker, next);
2964 kfree(shrinker);
2965 }
2966
2967 unsigned long
drmbackoff(long npages)2968 drmbackoff(long npages)
2969 {
2970 struct shrink_control sc;
2971 struct shrinker *shrinker;
2972 u_long ret, freed = 0;
2973
2974 shrinker = TAILQ_FIRST(&shrinkers);
2975 while (shrinker && npages > 0) {
2976 sc.nr_to_scan = npages;
2977 ret = shrinker->scan_objects(shrinker, &sc);
2978 if (ret == SHRINK_STOP)
2979 break;
2980 npages -= ret;
2981 freed += ret;
2982 shrinker = TAILQ_NEXT(shrinker, next);
2983 }
2984
2985 return freed;
2986 }
2987
2988 void *
bitmap_zalloc(u_int n,gfp_t flags)2989 bitmap_zalloc(u_int n, gfp_t flags)
2990 {
2991 return kcalloc(BITS_TO_LONGS(n), sizeof(long), flags);
2992 }
2993
2994 void
bitmap_free(void * p)2995 bitmap_free(void *p)
2996 {
2997 kfree(p);
2998 }
2999
3000 int
atomic_dec_and_mutex_lock(volatile int * v,struct rwlock * lock)3001 atomic_dec_and_mutex_lock(volatile int *v, struct rwlock *lock)
3002 {
3003 if (atomic_add_unless(v, -1, 1))
3004 return 0;
3005
3006 rw_enter_write(lock);
3007 if (atomic_dec_return(v) == 0)
3008 return 1;
3009 rw_exit_write(lock);
3010 return 0;
3011 }
3012
3013 int
printk(const char * fmt,...)3014 printk(const char *fmt, ...)
3015 {
3016 int ret, level;
3017 va_list ap;
3018
3019 if (fmt != NULL && *fmt == '\001') {
3020 level = fmt[1];
3021 #ifndef DRMDEBUG
3022 if (level >= KERN_INFO[1] && level <= '9')
3023 return 0;
3024 #endif
3025 fmt += 2;
3026 }
3027
3028 va_start(ap, fmt);
3029 ret = vprintf(fmt, ap);
3030 va_end(ap);
3031
3032 return ret;
3033 }
3034
3035 #define START(node) ((node)->start)
3036 #define LAST(node) ((node)->last)
3037
3038 struct interval_tree_node *
interval_tree_iter_first(struct rb_root_cached * root,unsigned long start,unsigned long last)3039 interval_tree_iter_first(struct rb_root_cached *root, unsigned long start,
3040 unsigned long last)
3041 {
3042 struct interval_tree_node *node;
3043 struct rb_node *rb;
3044
3045 for (rb = rb_first_cached(root); rb; rb = rb_next(rb)) {
3046 node = rb_entry(rb, typeof(*node), rb);
3047 if (LAST(node) >= start && START(node) <= last)
3048 return node;
3049 }
3050 return NULL;
3051 }
3052
3053 void
interval_tree_remove(struct interval_tree_node * node,struct rb_root_cached * root)3054 interval_tree_remove(struct interval_tree_node *node,
3055 struct rb_root_cached *root)
3056 {
3057 rb_erase_cached(&node->rb, root);
3058 }
3059
3060 void
interval_tree_insert(struct interval_tree_node * node,struct rb_root_cached * root)3061 interval_tree_insert(struct interval_tree_node *node,
3062 struct rb_root_cached *root)
3063 {
3064 struct rb_node **iter = &root->rb_root.rb_node;
3065 struct rb_node *parent = NULL;
3066 struct interval_tree_node *iter_node;
3067
3068 while (*iter) {
3069 parent = *iter;
3070 iter_node = rb_entry(*iter, struct interval_tree_node, rb);
3071
3072 if (node->start < iter_node->start)
3073 iter = &(*iter)->rb_left;
3074 else
3075 iter = &(*iter)->rb_right;
3076 }
3077
3078 rb_link_node(&node->rb, parent, iter);
3079 rb_insert_color_cached(&node->rb, root, false);
3080 }
3081
3082 int
syncfile_read(struct file * fp,struct uio * uio,int fflags)3083 syncfile_read(struct file *fp, struct uio *uio, int fflags)
3084 {
3085 return ENXIO;
3086 }
3087
3088 int
syncfile_write(struct file * fp,struct uio * uio,int fflags)3089 syncfile_write(struct file *fp, struct uio *uio, int fflags)
3090 {
3091 return ENXIO;
3092 }
3093
3094 int
syncfile_ioctl(struct file * fp,u_long com,caddr_t data,struct proc * p)3095 syncfile_ioctl(struct file *fp, u_long com, caddr_t data, struct proc *p)
3096 {
3097 return ENOTTY;
3098 }
3099
3100 int
syncfile_kqfilter(struct file * fp,struct knote * kn)3101 syncfile_kqfilter(struct file *fp, struct knote *kn)
3102 {
3103 return EINVAL;
3104 }
3105
3106 int
syncfile_stat(struct file * fp,struct stat * st,struct proc * p)3107 syncfile_stat(struct file *fp, struct stat *st, struct proc *p)
3108 {
3109 memset(st, 0, sizeof(*st));
3110 st->st_mode = S_IFIFO; /* XXX */
3111 return 0;
3112 }
3113
3114 int
syncfile_close(struct file * fp,struct proc * p)3115 syncfile_close(struct file *fp, struct proc *p)
3116 {
3117 struct sync_file *sf = fp->f_data;
3118
3119 dma_fence_put(sf->fence);
3120 fp->f_data = NULL;
3121 free(sf, M_DRM, sizeof(struct sync_file));
3122 return 0;
3123 }
3124
3125 int
syncfile_seek(struct file * fp,off_t * offset,int whence,struct proc * p)3126 syncfile_seek(struct file *fp, off_t *offset, int whence, struct proc *p)
3127 {
3128 off_t newoff;
3129
3130 if (*offset != 0)
3131 return EINVAL;
3132
3133 switch (whence) {
3134 case SEEK_SET:
3135 newoff = 0;
3136 break;
3137 case SEEK_END:
3138 newoff = 0;
3139 break;
3140 default:
3141 return EINVAL;
3142 }
3143 mtx_enter(&fp->f_mtx);
3144 fp->f_offset = newoff;
3145 mtx_leave(&fp->f_mtx);
3146 *offset = newoff;
3147 return 0;
3148 }
3149
3150 const struct fileops syncfileops = {
3151 .fo_read = syncfile_read,
3152 .fo_write = syncfile_write,
3153 .fo_ioctl = syncfile_ioctl,
3154 .fo_kqfilter = syncfile_kqfilter,
3155 .fo_stat = syncfile_stat,
3156 .fo_close = syncfile_close,
3157 .fo_seek = syncfile_seek,
3158 };
3159
3160 void
fd_install(int fd,struct file * fp)3161 fd_install(int fd, struct file *fp)
3162 {
3163 struct proc *p = curproc;
3164 struct filedesc *fdp = p->p_fd;
3165
3166 fdplock(fdp);
3167 /* all callers use get_unused_fd_flags(O_CLOEXEC) */
3168 fdinsert(fdp, fd, UF_EXCLOSE, fp);
3169 fdpunlock(fdp);
3170 }
3171
3172 void
fput(struct file * fp)3173 fput(struct file *fp)
3174 {
3175 FRELE(fp, curproc);
3176 }
3177
3178 int
get_unused_fd_flags(unsigned int flags)3179 get_unused_fd_flags(unsigned int flags)
3180 {
3181 struct proc *p = curproc;
3182 struct filedesc *fdp = p->p_fd;
3183 int error, fd;
3184
3185 KASSERT((flags & O_CLOEXEC) != 0);
3186
3187 fdplock(fdp);
3188 retryalloc:
3189 if ((error = fdalloc(p, 0, &fd)) != 0) {
3190 if (error == ENOSPC) {
3191 fdexpand(p);
3192 goto retryalloc;
3193 }
3194 fdpunlock(fdp);
3195 return -1;
3196 }
3197 fdpunlock(fdp);
3198
3199 return fd;
3200 }
3201
3202 void
put_unused_fd(int fd)3203 put_unused_fd(int fd)
3204 {
3205 struct filedesc *fdp = curproc->p_fd;
3206
3207 fdplock(fdp);
3208 fdremove(fdp, fd);
3209 fdpunlock(fdp);
3210 }
3211
3212 struct dma_fence *
sync_file_get_fence(int fd)3213 sync_file_get_fence(int fd)
3214 {
3215 struct proc *p = curproc;
3216 struct filedesc *fdp = p->p_fd;
3217 struct file *fp;
3218 struct sync_file *sf;
3219 struct dma_fence *f;
3220
3221 if ((fp = fd_getfile(fdp, fd)) == NULL)
3222 return NULL;
3223
3224 if (fp->f_type != DTYPE_SYNC) {
3225 FRELE(fp, p);
3226 return NULL;
3227 }
3228 sf = fp->f_data;
3229 f = dma_fence_get(sf->fence);
3230 FRELE(sf->file, p);
3231 return f;
3232 }
3233
3234 struct sync_file *
sync_file_create(struct dma_fence * fence)3235 sync_file_create(struct dma_fence *fence)
3236 {
3237 struct proc *p = curproc;
3238 struct sync_file *sf;
3239 struct file *fp;
3240
3241 fp = fnew(p);
3242 if (fp == NULL)
3243 return NULL;
3244 fp->f_type = DTYPE_SYNC;
3245 fp->f_ops = &syncfileops;
3246 sf = malloc(sizeof(struct sync_file), M_DRM, M_WAITOK | M_ZERO);
3247 sf->file = fp;
3248 sf->fence = dma_fence_get(fence);
3249 fp->f_data = sf;
3250 return sf;
3251 }
3252
3253 void *
memremap(phys_addr_t phys_addr,size_t size,int flags)3254 memremap(phys_addr_t phys_addr, size_t size, int flags)
3255 {
3256 STUB();
3257 return NULL;
3258 }
3259
3260 void
memunmap(void * addr)3261 memunmap(void *addr)
3262 {
3263 STUB();
3264 }
3265
3266 void
kfree_const(const void * addr)3267 kfree_const(const void *addr)
3268 {
3269 kfree(addr);
3270 }
3271
3272 #include <linux/platform_device.h>
3273
3274 bus_dma_tag_t
dma_tag_lookup(struct device * dev)3275 dma_tag_lookup(struct device *dev)
3276 {
3277 extern struct cfdriver drm_cd;
3278 struct drm_device *drm;
3279 int i;
3280
3281 for (i = 0; i < drm_cd.cd_ndevs; i++) {
3282 drm = drm_cd.cd_devs[i];
3283 if (drm && drm->dev == dev)
3284 return drm->dmat;
3285 }
3286
3287 return ((struct platform_device *)dev)->dmat;
3288 }
3289
3290 LIST_HEAD(, drm_dmamem) dmamem_list = LIST_HEAD_INITIALIZER(dmamem_list);
3291
3292 void *
dma_alloc_coherent(struct device * dev,size_t size,dma_addr_t * dma_handle,int gfp)3293 dma_alloc_coherent(struct device *dev, size_t size, dma_addr_t *dma_handle,
3294 int gfp)
3295 {
3296 bus_dma_tag_t dmat = dma_tag_lookup(dev);
3297 struct drm_dmamem *mem;
3298
3299 mem = drm_dmamem_alloc(dmat, size, PAGE_SIZE, 1, size,
3300 BUS_DMA_COHERENT, 0);
3301 if (mem == NULL)
3302 return NULL;
3303 *dma_handle = mem->map->dm_segs[0].ds_addr;
3304 LIST_INSERT_HEAD(&dmamem_list, mem, next);
3305 return mem->kva;
3306 }
3307
3308 void
dma_free_coherent(struct device * dev,size_t size,void * cpu_addr,dma_addr_t dma_handle)3309 dma_free_coherent(struct device *dev, size_t size, void *cpu_addr,
3310 dma_addr_t dma_handle)
3311 {
3312 bus_dma_tag_t dmat = dma_tag_lookup(dev);
3313 struct drm_dmamem *mem;
3314
3315 LIST_FOREACH(mem, &dmamem_list, next) {
3316 if (mem->kva == cpu_addr)
3317 break;
3318 }
3319 KASSERT(mem);
3320 KASSERT(mem->size == size);
3321 KASSERT(mem->map->dm_segs[0].ds_addr == dma_handle);
3322
3323 LIST_REMOVE(mem, next);
3324 drm_dmamem_free(dmat, mem);
3325 }
3326
3327 int
dma_get_sgtable(struct device * dev,struct sg_table * sgt,void * cpu_addr,dma_addr_t dma_addr,size_t size)3328 dma_get_sgtable(struct device *dev, struct sg_table *sgt, void *cpu_addr,
3329 dma_addr_t dma_addr, size_t size)
3330 {
3331 paddr_t pa;
3332 int ret;
3333
3334 if (!pmap_extract(pmap_kernel(), (vaddr_t)cpu_addr, &pa))
3335 return -EINVAL;
3336
3337 ret = sg_alloc_table(sgt, 1, GFP_KERNEL);
3338 if (ret)
3339 return ret;
3340
3341 sg_set_page(sgt->sgl, PHYS_TO_VM_PAGE(pa), size, 0);
3342 return 0;
3343 }
3344
3345 dma_addr_t
dma_map_resource(struct device * dev,phys_addr_t phys_addr,size_t size,enum dma_data_direction dir,u_long attr)3346 dma_map_resource(struct device *dev, phys_addr_t phys_addr, size_t size,
3347 enum dma_data_direction dir, u_long attr)
3348 {
3349 bus_dma_tag_t dmat= dma_tag_lookup(dev);
3350 bus_dmamap_t map;
3351 bus_dma_segment_t seg;
3352
3353 if (bus_dmamap_create(dmat, size, 1, size, 0,
3354 BUS_DMA_WAITOK | BUS_DMA_ALLOCNOW, &map))
3355 return DMA_MAPPING_ERROR;
3356 seg.ds_addr = phys_addr;
3357 seg.ds_len = size;
3358 if (bus_dmamap_load_raw(dmat, map, &seg, 1, size, BUS_DMA_WAITOK)) {
3359 bus_dmamap_destroy(dmat, map);
3360 return DMA_MAPPING_ERROR;
3361 }
3362
3363 return map->dm_segs[0].ds_addr;
3364 }
3365
3366 #ifdef BUS_DMA_FIXED
3367
3368 #include <linux/iommu.h>
3369
3370 size_t
iommu_map_sgtable(struct iommu_domain * domain,u_long iova,struct sg_table * sgt,int prot)3371 iommu_map_sgtable(struct iommu_domain *domain, u_long iova,
3372 struct sg_table *sgt, int prot)
3373 {
3374 bus_dma_segment_t seg;
3375 int error;
3376
3377 error = bus_dmamap_create(domain->dmat, sgt->sgl->length, 1,
3378 sgt->sgl->length, 0, BUS_DMA_WAITOK, &sgt->dmamap);
3379 if (error)
3380 return -ENOMEM;
3381
3382 sgt->dmamap->dm_segs[0].ds_addr = iova;
3383 sgt->dmamap->dm_segs[0].ds_len = sgt->sgl->length;
3384 sgt->dmamap->dm_nsegs = 1;
3385 seg.ds_addr = VM_PAGE_TO_PHYS(sgt->sgl->__page);
3386 seg.ds_len = sgt->sgl->length;
3387 error = bus_dmamap_load_raw(domain->dmat, sgt->dmamap, &seg, 1,
3388 sgt->sgl->length, BUS_DMA_WAITOK | BUS_DMA_FIXED);
3389 if (error)
3390 return -ENOMEM;
3391
3392 return sg_dma_len(sgt->sgl);
3393 }
3394
3395 size_t
iommu_unmap(struct iommu_domain * domain,u_long iova,size_t size)3396 iommu_unmap(struct iommu_domain *domain, u_long iova, size_t size)
3397 {
3398 STUB();
3399 return 0;
3400 }
3401
3402 struct iommu_domain *
iommu_get_domain_for_dev(struct device * dev)3403 iommu_get_domain_for_dev(struct device *dev)
3404 {
3405 STUB();
3406 return NULL;
3407 }
3408
3409 phys_addr_t
iommu_iova_to_phys(struct iommu_domain * domain,dma_addr_t iova)3410 iommu_iova_to_phys(struct iommu_domain *domain, dma_addr_t iova)
3411 {
3412 STUB();
3413 return 0;
3414 }
3415
3416 struct iommu_domain *
iommu_domain_alloc(struct bus_type * type)3417 iommu_domain_alloc(struct bus_type *type)
3418 {
3419 return malloc(sizeof(struct iommu_domain), M_DEVBUF, M_WAITOK | M_ZERO);
3420 }
3421
3422 int
iommu_attach_device(struct iommu_domain * domain,struct device * dev)3423 iommu_attach_device(struct iommu_domain *domain, struct device *dev)
3424 {
3425 struct platform_device *pdev = (struct platform_device *)dev;
3426
3427 domain->dmat = pdev->dmat;
3428 return 0;
3429 }
3430
3431 #endif
3432
3433 #include <linux/component.h>
3434
3435 struct component {
3436 struct device *dev;
3437 struct device *adev;
3438 const struct component_ops *ops;
3439 SLIST_ENTRY(component) next;
3440 };
3441
3442 SLIST_HEAD(,component) component_list = SLIST_HEAD_INITIALIZER(component_list);
3443
3444 int
component_add(struct device * dev,const struct component_ops * ops)3445 component_add(struct device *dev, const struct component_ops *ops)
3446 {
3447 struct component *component;
3448
3449 component = malloc(sizeof(*component), M_DEVBUF, M_WAITOK | M_ZERO);
3450 component->dev = dev;
3451 component->ops = ops;
3452 SLIST_INSERT_HEAD(&component_list, component, next);
3453 return 0;
3454 }
3455
3456 int
component_add_typed(struct device * dev,const struct component_ops * ops,int type)3457 component_add_typed(struct device *dev, const struct component_ops *ops,
3458 int type)
3459 {
3460 return component_add(dev, ops);
3461 }
3462
3463 int
component_bind_all(struct device * dev,void * data)3464 component_bind_all(struct device *dev, void *data)
3465 {
3466 struct component *component;
3467 int ret = 0;
3468
3469 SLIST_FOREACH(component, &component_list, next) {
3470 if (component->adev == dev) {
3471 ret = component->ops->bind(component->dev, NULL, data);
3472 if (ret)
3473 break;
3474 }
3475 }
3476
3477 return ret;
3478 }
3479
3480 struct component_match_entry {
3481 int (*compare)(struct device *, void *);
3482 void *data;
3483 };
3484
3485 struct component_match {
3486 struct component_match_entry match[4];
3487 int nmatches;
3488 };
3489
3490 int
component_master_add_with_match(struct device * dev,const struct component_master_ops * ops,struct component_match * match)3491 component_master_add_with_match(struct device *dev,
3492 const struct component_master_ops *ops, struct component_match *match)
3493 {
3494 struct component *component;
3495 int found = 0;
3496 int i, ret;
3497
3498 SLIST_FOREACH(component, &component_list, next) {
3499 for (i = 0; i < match->nmatches; i++) {
3500 struct component_match_entry *m = &match->match[i];
3501 if (m->compare(component->dev, m->data)) {
3502 component->adev = dev;
3503 found = 1;
3504 break;
3505 }
3506 }
3507 }
3508
3509 if (found) {
3510 ret = ops->bind(dev);
3511 if (ret)
3512 return ret;
3513 }
3514
3515 return 0;
3516 }
3517
3518 #ifdef __HAVE_FDT
3519
3520 #include <linux/platform_device.h>
3521 #include <dev/ofw/openfirm.h>
3522 #include <dev/ofw/fdt.h>
3523 #include <machine/fdt.h>
3524
3525 LIST_HEAD(, platform_device) pdev_list = LIST_HEAD_INITIALIZER(pdev_list);
3526
3527 void
platform_device_register(struct platform_device * pdev)3528 platform_device_register(struct platform_device *pdev)
3529 {
3530 int i;
3531
3532 pdev->num_resources = pdev->faa->fa_nreg;
3533 if (pdev->faa->fa_nreg > 0) {
3534 pdev->resource = mallocarray(pdev->faa->fa_nreg,
3535 sizeof(*pdev->resource), M_DEVBUF, M_WAITOK | M_ZERO);
3536 for (i = 0; i < pdev->faa->fa_nreg; i++) {
3537 pdev->resource[i].start = pdev->faa->fa_reg[i].addr;
3538 pdev->resource[i].end = pdev->faa->fa_reg[i].addr +
3539 pdev->faa->fa_reg[i].size - 1;
3540 }
3541 }
3542
3543 pdev->parent = pdev->dev.dv_parent;
3544 pdev->node = pdev->faa->fa_node;
3545 pdev->iot = pdev->faa->fa_iot;
3546 pdev->dmat = pdev->faa->fa_dmat;
3547 LIST_INSERT_HEAD(&pdev_list, pdev, next);
3548 }
3549
3550
3551 struct resource *
platform_get_resource(struct platform_device * pdev,u_int type,u_int num)3552 platform_get_resource(struct platform_device *pdev, u_int type, u_int num)
3553 {
3554 KASSERT(num < pdev->num_resources);
3555 return &pdev->resource[num];
3556 }
3557
3558 void __iomem *
devm_platform_ioremap_resource_byname(struct platform_device * pdev,const char * name)3559 devm_platform_ioremap_resource_byname(struct platform_device *pdev,
3560 const char *name)
3561 {
3562 bus_space_handle_t ioh;
3563 int err, idx;
3564
3565 idx = OF_getindex(pdev->node, name, "reg-names");
3566 if (idx == -1 || idx >= pdev->num_resources)
3567 return ERR_PTR(-EINVAL);
3568
3569 err = bus_space_map(pdev->iot, pdev->resource[idx].start,
3570 pdev->resource[idx].end - pdev->resource[idx].start + 1,
3571 BUS_SPACE_MAP_LINEAR, &ioh);
3572 if (err)
3573 return ERR_PTR(-err);
3574
3575 return bus_space_vaddr(pdev->iot, ioh);
3576 }
3577
3578 #include <dev/ofw/ofw_clock.h>
3579 #include <linux/clk.h>
3580
3581 struct clk *
devm_clk_get(struct device * dev,const char * name)3582 devm_clk_get(struct device *dev, const char *name)
3583 {
3584 struct platform_device *pdev = (struct platform_device *)dev;
3585 struct clk *clk;
3586
3587 clk = malloc(sizeof(*clk), M_DEVBUF, M_WAITOK);
3588 clk->freq = clock_get_frequency(pdev->node, name);
3589 return clk;
3590 }
3591
3592 u_long
clk_get_rate(struct clk * clk)3593 clk_get_rate(struct clk *clk)
3594 {
3595 return clk->freq;
3596 }
3597
3598 #include <linux/gpio/consumer.h>
3599 #include <dev/ofw/ofw_gpio.h>
3600
3601 struct gpio_desc {
3602 uint32_t gpios[4];
3603 };
3604
3605 struct gpio_desc *
devm_gpiod_get_optional(struct device * dev,const char * name,int flags)3606 devm_gpiod_get_optional(struct device *dev, const char *name, int flags)
3607 {
3608 struct platform_device *pdev = (struct platform_device *)dev;
3609 struct gpio_desc *desc;
3610 char fullname[128];
3611 int len;
3612
3613 snprintf(fullname, sizeof(fullname), "%s-gpios", name);
3614
3615 desc = malloc(sizeof(*desc), M_DEVBUF, M_WAITOK | M_ZERO);
3616 len = OF_getpropintarray(pdev->node, fullname, desc->gpios,
3617 sizeof(desc->gpios));
3618 KASSERT(len <= sizeof(desc->gpios));
3619 if (len < 0) {
3620 free(desc, M_DEVBUF, sizeof(*desc));
3621 return NULL;
3622 }
3623
3624 switch (flags) {
3625 case GPIOD_IN:
3626 gpio_controller_config_pin(desc->gpios, GPIO_CONFIG_INPUT);
3627 break;
3628 case GPIOD_OUT_HIGH:
3629 gpio_controller_config_pin(desc->gpios, GPIO_CONFIG_OUTPUT);
3630 gpio_controller_set_pin(desc->gpios, 1);
3631 break;
3632 default:
3633 panic("%s: unimplemented flags 0x%x", __func__, flags);
3634 }
3635
3636 return desc;
3637 }
3638
3639 int
gpiod_get_value_cansleep(const struct gpio_desc * desc)3640 gpiod_get_value_cansleep(const struct gpio_desc *desc)
3641 {
3642 return gpio_controller_get_pin(((struct gpio_desc *)desc)->gpios);
3643 }
3644
3645 struct phy {
3646 int node;
3647 const char *name;
3648 };
3649
3650 struct phy *
devm_phy_optional_get(struct device * dev,const char * name)3651 devm_phy_optional_get(struct device *dev, const char *name)
3652 {
3653 struct platform_device *pdev = (struct platform_device *)dev;
3654 struct phy *phy;
3655 int idx;
3656
3657 idx = OF_getindex(pdev->node, name, "phy-names");
3658 if (idx == -1)
3659 return NULL;
3660
3661 phy = malloc(sizeof(*phy), M_DEVBUF, M_WAITOK);
3662 phy->node = pdev->node;
3663 phy->name = name;
3664
3665 return phy;
3666 }
3667
3668 struct bus_type platform_bus_type;
3669
3670 #include <dev/ofw/ofw_misc.h>
3671
3672 #include <linux/of.h>
3673 #include <linux/platform_device.h>
3674
3675 struct device_node *
__of_devnode(void * arg)3676 __of_devnode(void *arg)
3677 {
3678 struct device *dev = container_of(arg, struct device, of_node);
3679 struct platform_device *pdev = (struct platform_device *)dev;
3680
3681 return (struct device_node *)(uintptr_t)pdev->node;
3682 }
3683
3684 int
__of_device_is_compatible(struct device_node * np,const char * compatible)3685 __of_device_is_compatible(struct device_node *np, const char *compatible)
3686 {
3687 return OF_is_compatible((uintptr_t)np, compatible);
3688 }
3689
3690 int
__of_property_present(struct device_node * np,const char * propname)3691 __of_property_present(struct device_node *np, const char *propname)
3692 {
3693 return OF_getpropbool((uintptr_t)np, (char *)propname);
3694 }
3695
3696 int
__of_property_read_variable_u32_array(struct device_node * np,const char * propname,uint32_t * out_values,size_t sz_min,size_t sz_max)3697 __of_property_read_variable_u32_array(struct device_node *np,
3698 const char *propname, uint32_t *out_values, size_t sz_min, size_t sz_max)
3699 {
3700 int len;
3701
3702 len = OF_getpropintarray((uintptr_t)np, (char *)propname, out_values,
3703 sz_max * sizeof(*out_values));
3704 if (len < 0)
3705 return -EINVAL;
3706 if (len == 0)
3707 return -ENODATA;
3708 if (len < sz_min * sizeof(*out_values) ||
3709 len > sz_max * sizeof(*out_values))
3710 return -EOVERFLOW;
3711 if (sz_min == 1 && sz_max == 1)
3712 return 0;
3713 return len / sizeof(*out_values);
3714 }
3715
3716 int
__of_property_read_variable_u64_array(struct device_node * np,const char * propname,uint64_t * out_values,size_t sz_min,size_t sz_max)3717 __of_property_read_variable_u64_array(struct device_node *np,
3718 const char *propname, uint64_t *out_values, size_t sz_min, size_t sz_max)
3719 {
3720 int len;
3721
3722 len = OF_getpropint64array((uintptr_t)np, (char *)propname, out_values,
3723 sz_max * sizeof(*out_values));
3724 if (len < 0)
3725 return -EINVAL;
3726 if (len == 0)
3727 return -ENODATA;
3728 if (len < sz_min * sizeof(*out_values) ||
3729 len > sz_max * sizeof(*out_values))
3730 return -EOVERFLOW;
3731 if (sz_min == 1 && sz_max == 1)
3732 return 0;
3733 return len / sizeof(*out_values);
3734 }
3735
3736 int
__of_property_match_string(struct device_node * np,const char * propname,const char * str)3737 __of_property_match_string(struct device_node *np,
3738 const char *propname, const char *str)
3739 {
3740 int idx;
3741
3742 idx = OF_getindex((uintptr_t)np, str, propname);
3743 if (idx == -1)
3744 return -ENODATA;
3745 return idx;
3746 }
3747
3748 struct device_node *
__of_parse_phandle(struct device_node * np,const char * propname,int idx)3749 __of_parse_phandle(struct device_node *np, const char *propname, int idx)
3750 {
3751 uint32_t phandles[16] = {};
3752 int len, node;
3753
3754 len = OF_getpropintarray((uintptr_t)np, (char *)propname, phandles,
3755 sizeof(phandles));
3756 if (len < (idx + 1) * sizeof(uint32_t))
3757 return NULL;
3758
3759 node = OF_getnodebyphandle(phandles[idx]);
3760 if (node == 0)
3761 return NULL;
3762
3763 return (struct device_node *)(uintptr_t)node;
3764 }
3765
3766 int
__of_parse_phandle_with_args(struct device_node * np,const char * propname,const char * cellsname,int idx,struct of_phandle_args * args)3767 __of_parse_phandle_with_args(struct device_node *np, const char *propname,
3768 const char *cellsname, int idx, struct of_phandle_args *args)
3769 {
3770 uint32_t phandles[16] = {};
3771 int i, len, node;
3772
3773 len = OF_getpropintarray((uintptr_t)np, (char *)propname, phandles,
3774 sizeof(phandles));
3775 if (len < (idx + 1) * sizeof(uint32_t))
3776 return -ENOENT;
3777
3778 node = OF_getnodebyphandle(phandles[idx]);
3779 if (node == 0)
3780 return -ENOENT;
3781
3782 args->np = (struct device_node *)(uintptr_t)node;
3783 args->args_count = OF_getpropint(node, (char *)cellsname, 0);
3784 for (i = 0; i < args->args_count; i++)
3785 args->args[i] = phandles[i + 1];
3786
3787 return 0;
3788 }
3789
3790 int
of_address_to_resource(struct device_node * np,int idx,struct resource * res)3791 of_address_to_resource(struct device_node *np, int idx, struct resource *res)
3792 {
3793 uint64_t reg[16] = {};
3794 int len;
3795
3796 KASSERT(idx < 8);
3797
3798 len = OF_getpropint64array((uintptr_t)np, "reg", reg, sizeof(reg));
3799 if (len < 0 || idx >= (len / (2 * sizeof(uint64_t))))
3800 return -EINVAL;
3801
3802 res->start = reg[2 * idx];
3803 res->end = reg[2 * idx] + reg[2 * idx + 1] - 1;
3804
3805 return 0;
3806 }
3807
3808 static int
next_node(int node)3809 next_node(int node)
3810 {
3811 int peer = OF_peer(node);
3812
3813 while (node && !peer) {
3814 node = OF_parent(node);
3815 if (node)
3816 peer = OF_peer(node);
3817 }
3818
3819 return peer;
3820 }
3821
3822 static int
find_matching_node(int node,const struct of_device_id * id)3823 find_matching_node(int node, const struct of_device_id *id)
3824 {
3825 int child, match;
3826 int i;
3827
3828 for (child = OF_child(node); child; child = OF_peer(child)) {
3829 match = find_matching_node(child, id);
3830 if (match)
3831 return match;
3832 }
3833
3834 for (i = 0; id[i].compatible; i++) {
3835 if (OF_is_compatible(node, id[i].compatible))
3836 return node;
3837 }
3838
3839 return 0;
3840 }
3841
3842 struct device_node *
__matching_node(struct device_node * np,const struct of_device_id * id)3843 __matching_node(struct device_node *np, const struct of_device_id *id)
3844 {
3845 int node = OF_peer(0);
3846 int match;
3847
3848 if (np)
3849 node = next_node((uintptr_t)np);
3850 while (node) {
3851 match = find_matching_node(node, id);
3852 if (match)
3853 return (struct device_node *)(uintptr_t)match;
3854 node = next_node(node);
3855 }
3856
3857 return NULL;
3858 }
3859
3860 struct platform_device *
of_platform_device_create(struct device_node * np,const char * bus_id,struct device * parent)3861 of_platform_device_create(struct device_node *np, const char *bus_id,
3862 struct device *parent)
3863 {
3864 struct platform_device *pdev;
3865
3866 pdev = malloc(sizeof(*pdev), M_DEVBUF, M_WAITOK | M_ZERO);
3867 pdev->node = (intptr_t)np;
3868 pdev->parent = parent;
3869
3870 LIST_INSERT_HEAD(&pdev_list, pdev, next);
3871
3872 return pdev;
3873 }
3874
3875 struct platform_device *
of_find_device_by_node(struct device_node * np)3876 of_find_device_by_node(struct device_node *np)
3877 {
3878 struct platform_device *pdev;
3879
3880 LIST_FOREACH(pdev, &pdev_list, next) {
3881 if (pdev->node == (intptr_t)np)
3882 return pdev;
3883 }
3884
3885 return NULL;
3886 }
3887
3888 int
of_device_is_available(struct device_node * np)3889 of_device_is_available(struct device_node *np)
3890 {
3891 char status[32];
3892
3893 if (OF_getprop((uintptr_t)np, "status", status, sizeof(status)) > 0 &&
3894 strcmp(status, "disabled") == 0)
3895 return 0;
3896
3897 return 1;
3898 }
3899
3900 int
of_dma_configure(struct device * dev,struct device_node * np,int force_dma)3901 of_dma_configure(struct device *dev, struct device_node *np, int force_dma)
3902 {
3903 struct platform_device *pdev = (struct platform_device *)dev;
3904 bus_dma_tag_t dmat = dma_tag_lookup(pdev->parent);
3905
3906 pdev->dmat = iommu_device_map(pdev->node, dmat);
3907 return 0;
3908 }
3909
3910 struct device_node *
__of_get_compatible_child(void * p,const char * compat)3911 __of_get_compatible_child(void *p, const char *compat)
3912 {
3913 struct device *dev = container_of(p, struct device, of_node);
3914 struct platform_device *pdev = (struct platform_device *)dev;
3915 int child;
3916
3917 for (child = OF_child(pdev->node); child; child = OF_peer(child)) {
3918 if (OF_is_compatible(child, compat))
3919 return (struct device_node *)(uintptr_t)child;
3920 }
3921 return NULL;
3922 }
3923
3924 struct device_node *
__of_get_child_by_name(void * p,const char * name)3925 __of_get_child_by_name(void *p, const char *name)
3926 {
3927 struct device *dev = container_of(p, struct device, of_node);
3928 struct platform_device *pdev = (struct platform_device *)dev;
3929 int child;
3930
3931 child = OF_getnodebyname(pdev->node, name);
3932 if (child == 0)
3933 return NULL;
3934 return (struct device_node *)(uintptr_t)child;
3935 }
3936
3937 int
component_compare_of(struct device * dev,void * data)3938 component_compare_of(struct device *dev, void *data)
3939 {
3940 struct platform_device *pdev = (struct platform_device *)dev;
3941
3942 return (pdev->node == (intptr_t)data);
3943 }
3944
3945 void
drm_of_component_match_add(struct device * master,struct component_match ** matchptr,int (* compare)(struct device *,void *),struct device_node * np)3946 drm_of_component_match_add(struct device *master,
3947 struct component_match **matchptr,
3948 int (*compare)(struct device *, void *),
3949 struct device_node *np)
3950 {
3951 struct component_match *match = *matchptr;
3952
3953 if (match == NULL) {
3954 match = malloc(sizeof(struct component_match),
3955 M_DEVBUF, M_WAITOK | M_ZERO);
3956 *matchptr = match;
3957 }
3958
3959 KASSERT(match->nmatches < nitems(match->match));
3960 match->match[match->nmatches].compare = compare;
3961 match->match[match->nmatches].data = np;
3962 match->nmatches++;
3963 }
3964
3965 #endif
3966