text
stringlengths
2
100k
meta
dict
/* * SCLP VT220 terminal driver. * * Copyright IBM Corp. 2003, 2009 * * Author(s): Peter Oberparleiter <Peter.Oberparleiter@de.ibm.com> */ #include <linux/module.h> #include <linux/spinlock.h> #include <linux/list.h> #include <linux/wait.h> #include <linux/timer.h> #include <linux/kernel.h> #include <linux/sysrq.h> #include <linux/tty.h> #include <linux/tty_driver.h> #include <linux/tty_flip.h> #include <linux/errno.h> #include <linux/mm.h> #include <linux/major.h> #include <linux/console.h> #include <linux/kdev_t.h> #include <linux/interrupt.h> #include <linux/init.h> #include <linux/reboot.h> #include <linux/slab.h> #include <asm/uaccess.h> #include "sclp.h" #include "ctrlchar.h" #define SCLP_VT220_MAJOR TTY_MAJOR #define SCLP_VT220_MINOR 65 #define SCLP_VT220_DRIVER_NAME "sclp_vt220" #define SCLP_VT220_DEVICE_NAME "ttysclp" #define SCLP_VT220_CONSOLE_NAME "ttyS" #define SCLP_VT220_CONSOLE_INDEX 1 /* console=ttyS1 */ /* Representation of a single write request */ struct sclp_vt220_request { struct list_head list; struct sclp_req sclp_req; int retry_count; }; /* VT220 SCCB */ struct sclp_vt220_sccb { struct sccb_header header; struct evbuf_header evbuf; }; #define SCLP_VT220_MAX_CHARS_PER_BUFFER (PAGE_SIZE - \ sizeof(struct sclp_vt220_request) - \ sizeof(struct sclp_vt220_sccb)) /* Structures and data needed to register tty driver */ static struct tty_driver *sclp_vt220_driver; static struct tty_port sclp_vt220_port; /* Lock to protect internal data from concurrent access */ static spinlock_t sclp_vt220_lock; /* List of empty pages to be used as write request buffers */ static struct list_head sclp_vt220_empty; /* List of pending requests */ static struct list_head sclp_vt220_outqueue; /* Suspend mode flag */ static int sclp_vt220_suspended; /* Flag that output queue is currently running */ static int sclp_vt220_queue_running; /* Timer used for delaying write requests to merge subsequent messages into * a single buffer */ static struct timer_list sclp_vt220_timer; /* Pointer to current request buffer which has been partially filled but not * yet sent */ static struct sclp_vt220_request *sclp_vt220_current_request; /* Number of characters in current request buffer */ static int sclp_vt220_buffered_chars; /* Counter controlling core driver initialization. */ static int __initdata sclp_vt220_init_count; /* Flag indicating that sclp_vt220_current_request should really * have been already queued but wasn't because the SCLP was processing * another buffer */ static int sclp_vt220_flush_later; static void sclp_vt220_receiver_fn(struct evbuf_header *evbuf); static void sclp_vt220_pm_event_fn(struct sclp_register *reg, enum sclp_pm_event sclp_pm_event); static int __sclp_vt220_emit(struct sclp_vt220_request *request); static void sclp_vt220_emit_current(void); /* Registration structure for SCLP output event buffers */ static struct sclp_register sclp_vt220_register = { .send_mask = EVTYP_VT220MSG_MASK, .pm_event_fn = sclp_vt220_pm_event_fn, }; /* Registration structure for SCLP input event buffers */ static struct sclp_register sclp_vt220_register_input = { .receive_mask = EVTYP_VT220MSG_MASK, .receiver_fn = sclp_vt220_receiver_fn, }; /* * Put provided request buffer back into queue and check emit pending * buffers if necessary. */ static void sclp_vt220_process_queue(struct sclp_vt220_request *request) { unsigned long flags; void *page; do { /* Put buffer back to list of empty buffers */ page = request->sclp_req.sccb; spin_lock_irqsave(&sclp_vt220_lock, flags); /* Move request from outqueue to empty queue */ list_del(&request->list); list_add_tail((struct list_head *) page, &sclp_vt220_empty); /* Check if there is a pending buffer on the out queue. */ request = NULL; if (!list_empty(&sclp_vt220_outqueue)) request = list_entry(sclp_vt220_outqueue.next, struct sclp_vt220_request, list); if (!request || sclp_vt220_suspended) { sclp_vt220_queue_running = 0; spin_unlock_irqrestore(&sclp_vt220_lock, flags); break; } spin_unlock_irqrestore(&sclp_vt220_lock, flags); } while (__sclp_vt220_emit(request)); if (request == NULL && sclp_vt220_flush_later) sclp_vt220_emit_current(); tty_port_tty_wakeup(&sclp_vt220_port); } #define SCLP_BUFFER_MAX_RETRY 1 /* * Callback through which the result of a write request is reported by the * SCLP. */ static void sclp_vt220_callback(struct sclp_req *request, void *data) { struct sclp_vt220_request *vt220_request; struct sclp_vt220_sccb *sccb; vt220_request = (struct sclp_vt220_request *) data; if (request->status == SCLP_REQ_FAILED) { sclp_vt220_process_queue(vt220_request); return; } sccb = (struct sclp_vt220_sccb *) vt220_request->sclp_req.sccb; /* Check SCLP response code and choose suitable action */ switch (sccb->header.response_code) { case 0x0020 : break; case 0x05f0: /* Target resource in improper state */ break; case 0x0340: /* Contained SCLP equipment check */ if (++vt220_request->retry_count > SCLP_BUFFER_MAX_RETRY) break; /* Remove processed buffers and requeue rest */ if (sclp_remove_processed((struct sccb_header *) sccb) > 0) { /* Not all buffers were processed */ sccb->header.response_code = 0x0000; vt220_request->sclp_req.status = SCLP_REQ_FILLED; if (sclp_add_request(request) == 0) return; } break; case 0x0040: /* SCLP equipment check */ if (++vt220_request->retry_count > SCLP_BUFFER_MAX_RETRY) break; sccb->header.response_code = 0x0000; vt220_request->sclp_req.status = SCLP_REQ_FILLED; if (sclp_add_request(request) == 0) return; break; default: break; } sclp_vt220_process_queue(vt220_request); } /* * Emit vt220 request buffer to SCLP. Return zero on success, non-zero * otherwise. */ static int __sclp_vt220_emit(struct sclp_vt220_request *request) { request->sclp_req.command = SCLP_CMDW_WRITE_EVENT_DATA; request->sclp_req.status = SCLP_REQ_FILLED; request->sclp_req.callback = sclp_vt220_callback; request->sclp_req.callback_data = (void *) request; return sclp_add_request(&request->sclp_req); } /* * Queue and emit current request. */ static void sclp_vt220_emit_current(void) { unsigned long flags; struct sclp_vt220_request *request; struct sclp_vt220_sccb *sccb; spin_lock_irqsave(&sclp_vt220_lock, flags); if (sclp_vt220_current_request) { sccb = (struct sclp_vt220_sccb *) sclp_vt220_current_request->sclp_req.sccb; /* Only emit buffers with content */ if (sccb->header.length != sizeof(struct sclp_vt220_sccb)) { list_add_tail(&sclp_vt220_current_request->list, &sclp_vt220_outqueue); sclp_vt220_current_request = NULL; if (timer_pending(&sclp_vt220_timer)) del_timer(&sclp_vt220_timer); } sclp_vt220_flush_later = 0; } if (sclp_vt220_queue_running || sclp_vt220_suspended) goto out_unlock; if (list_empty(&sclp_vt220_outqueue)) goto out_unlock; request = list_first_entry(&sclp_vt220_outqueue, struct sclp_vt220_request, list); sclp_vt220_queue_running = 1; spin_unlock_irqrestore(&sclp_vt220_lock, flags); if (__sclp_vt220_emit(request)) sclp_vt220_process_queue(request); return; out_unlock: spin_unlock_irqrestore(&sclp_vt220_lock, flags); } #define SCLP_NORMAL_WRITE 0x00 /* * Helper function to initialize a page with the sclp request structure. */ static struct sclp_vt220_request * sclp_vt220_initialize_page(void *page) { struct sclp_vt220_request *request; struct sclp_vt220_sccb *sccb; /* Place request structure at end of page */ request = ((struct sclp_vt220_request *) ((addr_t) page + PAGE_SIZE)) - 1; request->retry_count = 0; request->sclp_req.sccb = page; /* SCCB goes at start of page */ sccb = (struct sclp_vt220_sccb *) page; memset((void *) sccb, 0, sizeof(struct sclp_vt220_sccb)); sccb->header.length = sizeof(struct sclp_vt220_sccb); sccb->header.function_code = SCLP_NORMAL_WRITE; sccb->header.response_code = 0x0000; sccb->evbuf.type = EVTYP_VT220MSG; sccb->evbuf.length = sizeof(struct evbuf_header); return request; } static inline unsigned int sclp_vt220_space_left(struct sclp_vt220_request *request) { struct sclp_vt220_sccb *sccb; sccb = (struct sclp_vt220_sccb *) request->sclp_req.sccb; return PAGE_SIZE - sizeof(struct sclp_vt220_request) - sccb->header.length; } static inline unsigned int sclp_vt220_chars_stored(struct sclp_vt220_request *request) { struct sclp_vt220_sccb *sccb; sccb = (struct sclp_vt220_sccb *) request->sclp_req.sccb; return sccb->evbuf.length - sizeof(struct evbuf_header); } /* * Add msg to buffer associated with request. Return the number of characters * added. */ static int sclp_vt220_add_msg(struct sclp_vt220_request *request, const unsigned char *msg, int count, int convertlf) { struct sclp_vt220_sccb *sccb; void *buffer; unsigned char c; int from; int to; if (count > sclp_vt220_space_left(request)) count = sclp_vt220_space_left(request); if (count <= 0) return 0; sccb = (struct sclp_vt220_sccb *) request->sclp_req.sccb; buffer = (void *) ((addr_t) sccb + sccb->header.length); if (convertlf) { /* Perform Linefeed conversion (0x0a -> 0x0a 0x0d)*/ for (from=0, to=0; (from < count) && (to < sclp_vt220_space_left(request)); from++) { /* Retrieve character */ c = msg[from]; /* Perform conversion */ if (c == 0x0a) { if (to + 1 < sclp_vt220_space_left(request)) { ((unsigned char *) buffer)[to++] = c; ((unsigned char *) buffer)[to++] = 0x0d; } else break; } else ((unsigned char *) buffer)[to++] = c; } sccb->header.length += to; sccb->evbuf.length += to; return from; } else { memcpy(buffer, (const void *) msg, count); sccb->header.length += count; sccb->evbuf.length += count; return count; } } /* * Emit buffer after having waited long enough for more data to arrive. */ static void sclp_vt220_timeout(unsigned long data) { sclp_vt220_emit_current(); } #define BUFFER_MAX_DELAY HZ/20 /* * Drop oldest console buffer if sclp_con_drop is set */ static int sclp_vt220_drop_buffer(void) { struct list_head *list; struct sclp_vt220_request *request; void *page; if (!sclp_console_drop) return 0; list = sclp_vt220_outqueue.next; if (sclp_vt220_queue_running) /* The first element is in I/O */ list = list->next; if (list == &sclp_vt220_outqueue) return 0; list_del(list); request = list_entry(list, struct sclp_vt220_request, list); page = request->sclp_req.sccb; list_add_tail((struct list_head *) page, &sclp_vt220_empty); return 1; } /* * Internal implementation of the write function. Write COUNT bytes of data * from memory at BUF * to the SCLP interface. In case that the data does not fit into the current * write buffer, emit the current one and allocate a new one. If there are no * more empty buffers available, wait until one gets emptied. If DO_SCHEDULE * is non-zero, the buffer will be scheduled for emitting after a timeout - * otherwise the user has to explicitly call the flush function. * A non-zero CONVERTLF parameter indicates that 0x0a characters in the message * buffer should be converted to 0x0a 0x0d. After completion, return the number * of bytes written. */ static int __sclp_vt220_write(const unsigned char *buf, int count, int do_schedule, int convertlf, int may_fail) { unsigned long flags; void *page; int written; int overall_written; if (count <= 0) return 0; overall_written = 0; spin_lock_irqsave(&sclp_vt220_lock, flags); do { /* Create an sclp output buffer if none exists yet */ if (sclp_vt220_current_request == NULL) { if (list_empty(&sclp_vt220_empty)) sclp_console_full++; while (list_empty(&sclp_vt220_empty)) { if (may_fail || sclp_vt220_suspended) goto out; if (sclp_vt220_drop_buffer()) break; spin_unlock_irqrestore(&sclp_vt220_lock, flags); sclp_sync_wait(); spin_lock_irqsave(&sclp_vt220_lock, flags); } page = (void *) sclp_vt220_empty.next; list_del((struct list_head *) page); sclp_vt220_current_request = sclp_vt220_initialize_page(page); } /* Try to write the string to the current request buffer */ written = sclp_vt220_add_msg(sclp_vt220_current_request, buf, count, convertlf); overall_written += written; if (written == count) break; /* * Not all characters could be written to the current * output buffer. Emit the buffer, create a new buffer * and then output the rest of the string. */ spin_unlock_irqrestore(&sclp_vt220_lock, flags); sclp_vt220_emit_current(); spin_lock_irqsave(&sclp_vt220_lock, flags); buf += written; count -= written; } while (count > 0); /* Setup timer to output current console buffer after some time */ if (sclp_vt220_current_request != NULL && !timer_pending(&sclp_vt220_timer) && do_schedule) { sclp_vt220_timer.function = sclp_vt220_timeout; sclp_vt220_timer.data = 0UL; sclp_vt220_timer.expires = jiffies + BUFFER_MAX_DELAY; add_timer(&sclp_vt220_timer); } out: spin_unlock_irqrestore(&sclp_vt220_lock, flags); return overall_written; } /* * This routine is called by the kernel to write a series of * characters to the tty device. The characters may come from * user space or kernel space. This routine will return the * number of characters actually accepted for writing. */ static int sclp_vt220_write(struct tty_struct *tty, const unsigned char *buf, int count) { return __sclp_vt220_write(buf, count, 1, 0, 1); } #define SCLP_VT220_SESSION_ENDED 0x01 #define SCLP_VT220_SESSION_STARTED 0x80 #define SCLP_VT220_SESSION_DATA 0x00 #ifdef CONFIG_MAGIC_SYSRQ static int sysrq_pressed; static struct sysrq_work sysrq; static void sclp_vt220_reset_session(void) { sysrq_pressed = 0; } static void sclp_vt220_handle_input(const char *buffer, unsigned int count) { int i; for (i = 0; i < count; i++) { /* Handle magic sys request */ if (buffer[i] == ('O' ^ 0100)) { /* CTRL-O */ /* * If pressed again, reset sysrq_pressed * and flip CTRL-O character */ sysrq_pressed = !sysrq_pressed; if (sysrq_pressed) continue; } else if (sysrq_pressed) { sysrq.key = buffer[i]; schedule_sysrq_work(&sysrq); sysrq_pressed = 0; continue; } tty_insert_flip_char(&sclp_vt220_port, buffer[i], 0); } } #else static void sclp_vt220_reset_session(void) { } static void sclp_vt220_handle_input(const char *buffer, unsigned int count) { tty_insert_flip_string(&sclp_vt220_port, buffer, count); } #endif /* * Called by the SCLP to report incoming event buffers. */ static void sclp_vt220_receiver_fn(struct evbuf_header *evbuf) { char *buffer; unsigned int count; buffer = (char *) ((addr_t) evbuf + sizeof(struct evbuf_header)); count = evbuf->length - sizeof(struct evbuf_header); switch (*buffer) { case SCLP_VT220_SESSION_ENDED: case SCLP_VT220_SESSION_STARTED: sclp_vt220_reset_session(); break; case SCLP_VT220_SESSION_DATA: /* Send input to line discipline */ buffer++; count--; sclp_vt220_handle_input(buffer, count); tty_flip_buffer_push(&sclp_vt220_port); break; } } /* * This routine is called when a particular tty device is opened. */ static int sclp_vt220_open(struct tty_struct *tty, struct file *filp) { if (tty->count == 1) { tty_port_tty_set(&sclp_vt220_port, tty); sclp_vt220_port.low_latency = 0; if (!tty->winsize.ws_row && !tty->winsize.ws_col) { tty->winsize.ws_row = 24; tty->winsize.ws_col = 80; } } return 0; } /* * This routine is called when a particular tty device is closed. */ static void sclp_vt220_close(struct tty_struct *tty, struct file *filp) { if (tty->count == 1) tty_port_tty_set(&sclp_vt220_port, NULL); } /* * This routine is called by the kernel to write a single * character to the tty device. If the kernel uses this routine, * it must call the flush_chars() routine (if defined) when it is * done stuffing characters into the driver. */ static int sclp_vt220_put_char(struct tty_struct *tty, unsigned char ch) { return __sclp_vt220_write(&ch, 1, 0, 0, 1); } /* * This routine is called by the kernel after it has written a * series of characters to the tty device using put_char(). */ static void sclp_vt220_flush_chars(struct tty_struct *tty) { if (!sclp_vt220_queue_running) sclp_vt220_emit_current(); else sclp_vt220_flush_later = 1; } /* * This routine returns the numbers of characters the tty driver * will accept for queuing to be written. This number is subject * to change as output buffers get emptied, or if the output flow * control is acted. */ static int sclp_vt220_write_room(struct tty_struct *tty) { unsigned long flags; struct list_head *l; int count; spin_lock_irqsave(&sclp_vt220_lock, flags); count = 0; if (sclp_vt220_current_request != NULL) count = sclp_vt220_space_left(sclp_vt220_current_request); list_for_each(l, &sclp_vt220_empty) count += SCLP_VT220_MAX_CHARS_PER_BUFFER; spin_unlock_irqrestore(&sclp_vt220_lock, flags); return count; } /* * Return number of buffered chars. */ static int sclp_vt220_chars_in_buffer(struct tty_struct *tty) { unsigned long flags; struct list_head *l; struct sclp_vt220_request *r; int count; spin_lock_irqsave(&sclp_vt220_lock, flags); count = 0; if (sclp_vt220_current_request != NULL) count = sclp_vt220_chars_stored(sclp_vt220_current_request); list_for_each(l, &sclp_vt220_outqueue) { r = list_entry(l, struct sclp_vt220_request, list); count += sclp_vt220_chars_stored(r); } spin_unlock_irqrestore(&sclp_vt220_lock, flags); return count; } /* * Pass on all buffers to the hardware. Return only when there are no more * buffers pending. */ static void sclp_vt220_flush_buffer(struct tty_struct *tty) { sclp_vt220_emit_current(); } /* Release allocated pages. */ static void __init __sclp_vt220_free_pages(void) { struct list_head *page, *p; list_for_each_safe(page, p, &sclp_vt220_empty) { list_del(page); free_page((unsigned long) page); } } /* Release memory and unregister from sclp core. Controlled by init counting - * only the last invoker will actually perform these actions. */ static void __init __sclp_vt220_cleanup(void) { sclp_vt220_init_count--; if (sclp_vt220_init_count != 0) return; sclp_unregister(&sclp_vt220_register); __sclp_vt220_free_pages(); tty_port_destroy(&sclp_vt220_port); } /* Allocate buffer pages and register with sclp core. Controlled by init * counting - only the first invoker will actually perform these actions. */ static int __init __sclp_vt220_init(int num_pages) { void *page; int i; int rc; sclp_vt220_init_count++; if (sclp_vt220_init_count != 1) return 0; spin_lock_init(&sclp_vt220_lock); INIT_LIST_HEAD(&sclp_vt220_empty); INIT_LIST_HEAD(&sclp_vt220_outqueue); init_timer(&sclp_vt220_timer); tty_port_init(&sclp_vt220_port); sclp_vt220_current_request = NULL; sclp_vt220_buffered_chars = 0; sclp_vt220_flush_later = 0; /* Allocate pages for output buffering */ rc = -ENOMEM; for (i = 0; i < num_pages; i++) { page = (void *) get_zeroed_page(GFP_KERNEL | GFP_DMA); if (!page) goto out; list_add_tail(page, &sclp_vt220_empty); } rc = sclp_register(&sclp_vt220_register); out: if (rc) { __sclp_vt220_free_pages(); sclp_vt220_init_count--; tty_port_destroy(&sclp_vt220_port); } return rc; } static const struct tty_operations sclp_vt220_ops = { .open = sclp_vt220_open, .close = sclp_vt220_close, .write = sclp_vt220_write, .put_char = sclp_vt220_put_char, .flush_chars = sclp_vt220_flush_chars, .write_room = sclp_vt220_write_room, .chars_in_buffer = sclp_vt220_chars_in_buffer, .flush_buffer = sclp_vt220_flush_buffer, }; /* * Register driver with SCLP and Linux and initialize internal tty structures. */ static int __init sclp_vt220_tty_init(void) { struct tty_driver *driver; int rc; /* Note: we're not testing for CONSOLE_IS_SCLP here to preserve * symmetry between VM and LPAR systems regarding ttyS1. */ driver = alloc_tty_driver(1); if (!driver) return -ENOMEM; rc = __sclp_vt220_init(MAX_KMEM_PAGES); if (rc) goto out_driver; driver->driver_name = SCLP_VT220_DRIVER_NAME; driver->name = SCLP_VT220_DEVICE_NAME; driver->major = SCLP_VT220_MAJOR; driver->minor_start = SCLP_VT220_MINOR; driver->type = TTY_DRIVER_TYPE_SYSTEM; driver->subtype = SYSTEM_TYPE_TTY; driver->init_termios = tty_std_termios; driver->flags = TTY_DRIVER_REAL_RAW; tty_set_operations(driver, &sclp_vt220_ops); tty_port_link_device(&sclp_vt220_port, driver, 0); rc = tty_register_driver(driver); if (rc) goto out_init; rc = sclp_register(&sclp_vt220_register_input); if (rc) goto out_reg; sclp_vt220_driver = driver; return 0; out_reg: tty_unregister_driver(driver); out_init: __sclp_vt220_cleanup(); out_driver: put_tty_driver(driver); return rc; } __initcall(sclp_vt220_tty_init); static void __sclp_vt220_flush_buffer(void) { unsigned long flags; sclp_vt220_emit_current(); spin_lock_irqsave(&sclp_vt220_lock, flags); if (timer_pending(&sclp_vt220_timer)) del_timer(&sclp_vt220_timer); while (sclp_vt220_queue_running) { spin_unlock_irqrestore(&sclp_vt220_lock, flags); sclp_sync_wait(); spin_lock_irqsave(&sclp_vt220_lock, flags); } spin_unlock_irqrestore(&sclp_vt220_lock, flags); } /* * Resume console: If there are cached messages, emit them. */ static void sclp_vt220_resume(void) { unsigned long flags; spin_lock_irqsave(&sclp_vt220_lock, flags); sclp_vt220_suspended = 0; spin_unlock_irqrestore(&sclp_vt220_lock, flags); sclp_vt220_emit_current(); } /* * Suspend console: Set suspend flag and flush console */ static void sclp_vt220_suspend(void) { unsigned long flags; spin_lock_irqsave(&sclp_vt220_lock, flags); sclp_vt220_suspended = 1; spin_unlock_irqrestore(&sclp_vt220_lock, flags); __sclp_vt220_flush_buffer(); } static void sclp_vt220_pm_event_fn(struct sclp_register *reg, enum sclp_pm_event sclp_pm_event) { switch (sclp_pm_event) { case SCLP_PM_EVENT_FREEZE: sclp_vt220_suspend(); break; case SCLP_PM_EVENT_RESTORE: case SCLP_PM_EVENT_THAW: sclp_vt220_resume(); break; } } #ifdef CONFIG_SCLP_VT220_CONSOLE static void sclp_vt220_con_write(struct console *con, const char *buf, unsigned int count) { __sclp_vt220_write((const unsigned char *) buf, count, 1, 1, 0); } static struct tty_driver * sclp_vt220_con_device(struct console *c, int *index) { *index = 0; return sclp_vt220_driver; } static int sclp_vt220_notify(struct notifier_block *self, unsigned long event, void *data) { __sclp_vt220_flush_buffer(); return NOTIFY_OK; } static struct notifier_block on_panic_nb = { .notifier_call = sclp_vt220_notify, .priority = 1, }; static struct notifier_block on_reboot_nb = { .notifier_call = sclp_vt220_notify, .priority = 1, }; /* Structure needed to register with printk */ static struct console sclp_vt220_console = { .name = SCLP_VT220_CONSOLE_NAME, .write = sclp_vt220_con_write, .device = sclp_vt220_con_device, .flags = CON_PRINTBUFFER, .index = SCLP_VT220_CONSOLE_INDEX }; static int __init sclp_vt220_con_init(void) { int rc; rc = __sclp_vt220_init(sclp_console_pages); if (rc) return rc; /* Attach linux console */ atomic_notifier_chain_register(&panic_notifier_list, &on_panic_nb); register_reboot_notifier(&on_reboot_nb); register_console(&sclp_vt220_console); return 0; } console_initcall(sclp_vt220_con_init); #endif /* CONFIG_SCLP_VT220_CONSOLE */
{ "language": "C" }
/**************************************************************************** * Copyright 2020 Thomas E. Dickey * * Copyright 2010,2015 Free Software Foundation, Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, distribute with modifications, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included * * in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * * * Except as contained in this notice, the name(s) of the above copyright * * holders shall not be used in advertising or otherwise to promote the * * sale, use or other dealings in this Software without prior written * * authorization. * ****************************************************************************/ /**************************************************************************** * Author: Thomas E. Dickey 2010-on * ****************************************************************************/ /* LINTLIBRARY */ /* ./m_attribs.c */ #include <menu.priv.h> #undef set_menu_fore int set_menu_fore( MENU *menu, chtype attr) { return(*(int *)0); } #undef menu_fore chtype menu_fore( const MENU *menu) { return(*(chtype *)0); } #undef set_menu_back int set_menu_back( MENU *menu, chtype attr) { return(*(int *)0); } #undef menu_back chtype menu_back( const MENU *menu) { return(*(chtype *)0); } #undef set_menu_grey int set_menu_grey( MENU *menu, chtype attr) { return(*(int *)0); } #undef menu_grey chtype menu_grey( const MENU *menu) { return(*(chtype *)0); } /* ./m_cursor.c */ #undef _nc_menu_cursor_pos int _nc_menu_cursor_pos( const MENU *menu, const ITEM *item, int *pY, int *pX) { return(*(int *)0); } #undef pos_menu_cursor int pos_menu_cursor( const MENU *menu) { return(*(int *)0); } /* ./m_driver.c */ #undef _nc_Match_Next_Character_In_Item_Name int _nc_Match_Next_Character_In_Item_Name( MENU *menu, int ch, ITEM **item) { return(*(int *)0); } #undef menu_driver int menu_driver( MENU *menu, int c) { return(*(int *)0); } /* ./m_format.c */ #undef set_menu_format int set_menu_format( MENU *menu, int rows, int cols) { return(*(int *)0); } #undef menu_format void menu_format( const MENU *menu, int *rows, int *cols) { /* void */ } /* ./m_global.c */ #undef _nc_Default_Menu MENU _nc_Default_Menu; #undef _nc_Default_Item ITEM _nc_Default_Item; #undef _nc_Connect_Items NCURSES_BOOL _nc_Connect_Items( MENU *menu, ITEM **items) { return(*(NCURSES_BOOL *)0); } #undef _nc_Disconnect_Items void _nc_Disconnect_Items( MENU *menu) { /* void */ } #undef _nc_Calculate_Text_Width int _nc_Calculate_Text_Width( const TEXT *item) { return(*(int *)0); } #undef _nc_Calculate_Item_Length_and_Width void _nc_Calculate_Item_Length_and_Width( MENU *menu) { /* void */ } #undef _nc_Link_Items void _nc_Link_Items( MENU *menu) { /* void */ } #undef _nc_Show_Menu void _nc_Show_Menu( const MENU *menu) { /* void */ } #undef _nc_New_TopRow_and_CurrentItem void _nc_New_TopRow_and_CurrentItem( MENU *menu, int new_toprow, ITEM *new_current_item) { /* void */ } /* ./m_hook.c */ #undef set_menu_init int set_menu_init( MENU *menu, Menu_Hook func) { return(*(int *)0); } #undef menu_init Menu_Hook menu_init( const MENU *menu) { return(*(Menu_Hook *)0); } #undef set_menu_term int set_menu_term( MENU *menu, Menu_Hook func) { return(*(int *)0); } #undef menu_term Menu_Hook menu_term( const MENU *menu) { return(*(Menu_Hook *)0); } #undef set_item_init int set_item_init( MENU *menu, Menu_Hook func) { return(*(int *)0); } #undef item_init Menu_Hook item_init( const MENU *menu) { return(*(Menu_Hook *)0); } #undef set_item_term int set_item_term( MENU *menu, Menu_Hook func) { return(*(int *)0); } #undef item_term Menu_Hook item_term( const MENU *menu) { return(*(Menu_Hook *)0); } /* ./m_item_cur.c */ #undef set_current_item int set_current_item( MENU *menu, ITEM *item) { return(*(int *)0); } #undef current_item ITEM *current_item( const MENU *menu) { return(*(ITEM **)0); } #undef item_index int item_index( const ITEM *item) { return(*(int *)0); } /* ./m_item_nam.c */ #undef item_name const char *item_name( const ITEM *item) { return(*(const char **)0); } #undef item_description const char *item_description( const ITEM *item) { return(*(const char **)0); } /* ./m_item_new.c */ #undef new_item ITEM *new_item( const char *name, const char *description) { return(*(ITEM **)0); } #undef free_item int free_item( ITEM *item) { return(*(int *)0); } #undef set_menu_mark int set_menu_mark( MENU *menu, const char *mark) { return(*(int *)0); } #undef menu_mark const char *menu_mark( const MENU *menu) { return(*(const char **)0); } /* ./m_item_opt.c */ #undef set_item_opts int set_item_opts( ITEM *item, Item_Options opts) { return(*(int *)0); } #undef item_opts_off int item_opts_off( ITEM *item, Item_Options opts) { return(*(int *)0); } #undef item_opts_on int item_opts_on( ITEM *item, Item_Options opts) { return(*(int *)0); } #undef item_opts Item_Options item_opts( const ITEM *item) { return(*(Item_Options *)0); } /* ./m_item_top.c */ #undef set_top_row int set_top_row( MENU *menu, int row) { return(*(int *)0); } #undef top_row int top_row( const MENU *menu) { return(*(int *)0); } /* ./m_item_use.c */ #undef set_item_userptr int set_item_userptr( ITEM *item, void *userptr) { return(*(int *)0); } #undef item_userptr void *item_userptr( const ITEM *item) { return(*(void **)0); } /* ./m_item_val.c */ #undef set_item_value int set_item_value( ITEM *item, NCURSES_BOOL value) { return(*(int *)0); } #undef item_value NCURSES_BOOL item_value( const ITEM *item) { return(*(NCURSES_BOOL *)0); } /* ./m_item_vis.c */ #undef item_visible NCURSES_BOOL item_visible( const ITEM *item) { return(*(NCURSES_BOOL *)0); } /* ./m_items.c */ #undef set_menu_items int set_menu_items( MENU *menu, ITEM **items) { return(*(int *)0); } #undef menu_items ITEM **menu_items( const MENU *menu) { return(*(ITEM ***)0); } #undef item_count int item_count( const MENU *menu) { return(*(int *)0); } /* ./m_new.c */ #undef new_menu_sp MENU *new_menu_sp( SCREEN *sp, ITEM **items) { return(*(MENU **)0); } #undef new_menu MENU *new_menu( ITEM **items) { return(*(MENU **)0); } #undef free_menu int free_menu( MENU *menu) { return(*(int *)0); } /* ./m_opts.c */ #undef set_menu_opts int set_menu_opts( MENU *menu, Menu_Options opts) { return(*(int *)0); } #undef menu_opts_off int menu_opts_off( MENU *menu, Menu_Options opts) { return(*(int *)0); } #undef menu_opts_on int menu_opts_on( MENU *menu, Menu_Options opts) { return(*(int *)0); } #undef menu_opts Menu_Options menu_opts( const MENU *menu) { return(*(Menu_Options *)0); } /* ./m_pad.c */ #undef set_menu_pad int set_menu_pad( MENU *menu, int pad) { return(*(int *)0); } #undef menu_pad int menu_pad( const MENU *menu) { return(*(int *)0); } /* ./m_pattern.c */ #undef menu_pattern char *menu_pattern( const MENU *menu) { return(*(char **)0); } #undef set_menu_pattern int set_menu_pattern( MENU *menu, const char *p) { return(*(int *)0); } /* ./m_post.c */ #undef _nc_Post_Item void _nc_Post_Item( const MENU *menu, const ITEM *item) { /* void */ } #undef _nc_Draw_Menu void _nc_Draw_Menu( const MENU *menu) { /* void */ } #undef post_menu int post_menu( MENU *menu) { return(*(int *)0); } #undef unpost_menu int unpost_menu( MENU *menu) { return(*(int *)0); } /* ./m_req_name.c */ #undef menu_request_name const char *menu_request_name( int request) { return(*(const char **)0); } #undef menu_request_by_name int menu_request_by_name( const char *str) { return(*(int *)0); } /* ./m_scale.c */ #undef scale_menu int scale_menu( const MENU *menu, int *rows, int *cols) { return(*(int *)0); } /* ./m_spacing.c */ #undef set_menu_spacing int set_menu_spacing( MENU *menu, int s_desc, int s_row, int s_col) { return(*(int *)0); } #undef menu_spacing int menu_spacing( const MENU *menu, int *s_desc, int *s_row, int *s_col) { return(*(int *)0); } /* ./m_sub.c */ #undef set_menu_sub int set_menu_sub( MENU *menu, WINDOW *win) { return(*(int *)0); } #undef menu_sub WINDOW *menu_sub( const MENU *menu) { return(*(WINDOW **)0); } /* ./m_trace.c */ #undef _nc_retrace_item ITEM *_nc_retrace_item( ITEM *code) { return(*(ITEM **)0); } #undef _nc_retrace_item_ptr ITEM **_nc_retrace_item_ptr( ITEM **code) { return(*(ITEM ***)0); } #undef _nc_retrace_item_opts Item_Options _nc_retrace_item_opts( Item_Options code) { return(*(Item_Options *)0); } #undef _nc_retrace_menu MENU *_nc_retrace_menu( MENU *code) { return(*(MENU **)0); } #undef _nc_retrace_menu_hook Menu_Hook _nc_retrace_menu_hook( Menu_Hook code) { return(*(Menu_Hook *)0); } #undef _nc_retrace_menu_opts Menu_Options _nc_retrace_menu_opts( Menu_Options code) { return(*(Menu_Options *)0); } /* ./m_userptr.c */ #undef set_menu_userptr int set_menu_userptr( MENU *menu, void *userptr) { return(*(int *)0); } #undef menu_userptr void *menu_userptr( const MENU *menu) { return(*(void **)0); } /* ./m_win.c */ #undef set_menu_win int set_menu_win( MENU *menu, WINDOW *win) { return(*(int *)0); } #undef menu_win WINDOW *menu_win( const MENU *menu) { return(*(WINDOW **)0); }
{ "language": "C" }
/* * Copyright (C) 2014 Jared Boone, ShareBrained Technology, Inc. * * This file is part of HackRF. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef __I2C_LPC_H__ #define __I2C_LPC_H__ #include <stdint.h> #include <stddef.h> #include "i2c_bus.h" typedef struct i2c_lpc_config_t { const uint16_t duty_cycle_count; } i2c_lpc_config_t; void i2c_lpc_start(i2c_bus_t* const bus, const void* const config); void i2c_lpc_stop(i2c_bus_t* const bus); void i2c_lpc_transfer(const uint32_t port, const uint_fast8_t slave_address, const uint8_t* const data_tx, const size_t count_tx, uint8_t* const data_rx, const size_t count_rx ); #endif/*__I2C_LPC_H__*/
{ "language": "C" }
/* SPDX-License-Identifier: GPL-2.0+ */ /* * da9210-regulator.h - Regulator definitions for DA9210 * Copyright (C) 2013 Dialog Semiconductor Ltd. */ #ifndef __DA9210_REGISTERS_H__ #define __DA9210_REGISTERS_H__ struct da9210_pdata { struct regulator_init_data da9210_constraints; }; /* Page selection */ #define DA9210_REG_PAGE_CON 0x00 /* System Control and Event Registers */ #define DA9210_REG_STATUS_A 0x50 #define DA9210_REG_STATUS_B 0x51 #define DA9210_REG_EVENT_A 0x52 #define DA9210_REG_EVENT_B 0x53 #define DA9210_REG_MASK_A 0x54 #define DA9210_REG_MASK_B 0x55 #define DA9210_REG_CONTROL_A 0x56 /* GPIO Control Registers */ #define DA9210_REG_GPIO_0_1 0x58 #define DA9210_REG_GPIO_2_3 0x59 #define DA9210_REG_GPIO_4_5 0x5A #define DA9210_REG_GPIO_6 0x5B /* Regulator Registers */ #define DA9210_REG_BUCK_CONT 0x5D #define DA9210_REG_BUCK_ILIM 0xD0 #define DA9210_REG_BUCK_CONF1 0xD1 #define DA9210_REG_BUCK_CONF2 0xD2 #define DA9210_REG_VBACK_AUTO 0xD4 #define DA9210_REG_VBACK_BASE 0xD5 #define DA9210_REG_VBACK_MAX_DVC_IF 0xD6 #define DA9210_REG_VBACK_DVC 0xD7 #define DA9210_REG_VBUCK_A 0xD8 #define DA9210_REG_VBUCK_B 0xD9 /* I2C Interface Settings */ #define DA9210_REG_INTERFACE 0x105 /* OTP */ #define DA9210_REG_OPT_COUNT 0x140 #define DA9210_REG_OPT_ADDR 0x141 #define DA9210_REG_OPT_DATA 0x142 /* Customer Trim and Configuration */ #define DA9210_REG_CONFIG_A 0x143 #define DA9210_REG_CONFIG_B 0x144 #define DA9210_REG_CONFIG_C 0x145 #define DA9210_REG_CONFIG_D 0x146 #define DA9210_REG_CONFIG_E 0x147 /* * Registers bits */ /* DA9210_REG_PAGE_CON (addr=0x00) */ #define DA9210_PEG_PAGE_SHIFT 0 #define DA9210_REG_PAGE_MASK 0x0F /* On I2C registers 0x00 - 0xFF */ #define DA9210_REG_PAGE0 0 /* On I2C registers 0x100 - 0x1FF */ #define DA9210_REG_PAGE2 2 #define DA9210_PAGE_WRITE_MODE 0x00 #define DA9210_REPEAT_WRITE_MODE 0x40 #define DA9210_PAGE_REVERT 0x80 /* DA9210_REG_STATUS_A (addr=0x50) */ #define DA9210_GPI0 0x01 #define DA9210_GPI1 0x02 #define DA9210_GPI2 0x04 #define DA9210_GPI3 0x08 #define DA9210_GPI4 0x10 #define DA9210_GPI5 0x20 #define DA9210_GPI6 0x40 /* DA9210_REG_EVENT_A (addr=0x52) */ #define DA9210_E_GPI0 0x01 #define DA9210_E_GPI1 0x02 #define DA9210_E_GPI2 0x04 #define DA9210_E_GPI3 0x08 #define DA9210_E_GPI4 0x10 #define DA9210_E_GPI5 0x20 #define DA9210_E_GPI6 0x40 /* DA9210_REG_EVENT_B (addr=0x53) */ #define DA9210_E_OVCURR 0x01 #define DA9210_E_NPWRGOOD 0x02 #define DA9210_E_TEMP_WARN 0x04 #define DA9210_E_TEMP_CRIT 0x08 #define DA9210_E_VMAX 0x10 /* DA9210_REG_MASK_A (addr=0x54) */ #define DA9210_M_GPI0 0x01 #define DA9210_M_GPI1 0x02 #define DA9210_M_GPI2 0x04 #define DA9210_M_GPI3 0x08 #define DA9210_M_GPI4 0x10 #define DA9210_M_GPI5 0x20 #define DA9210_M_GPI6 0x40 /* DA9210_REG_MASK_B (addr=0x55) */ #define DA9210_M_OVCURR 0x01 #define DA9210_M_NPWRGOOD 0x02 #define DA9210_M_TEMP_WARN 0x04 #define DA9210_M_TEMP_CRIT 0x08 #define DA9210_M_VMAX 0x10 /* DA9210_REG_CONTROL_A (addr=0x56) */ #define DA9210_DEBOUNCING_SHIFT 0 #define DA9210_DEBOUNCING_MASK 0x07 #define DA9210_SLEW_RATE_SHIFT 3 #define DA9210_SLEW_RATE_MASK 0x18 #define DA9210_V_LOCK 0x20 /* DA9210_REG_GPIO_0_1 (addr=0x58) */ #define DA9210_GPIO0_PIN_SHIFT 0 #define DA9210_GPIO0_PIN_MASK 0x03 #define DA9210_GPIO0_PIN_GPI 0x00 #define DA9210_GPIO0_PIN_GPO_OD 0x02 #define DA9210_GPIO0_PIN_GPO 0x03 #define DA9210_GPIO0_TYPE 0x04 #define DA9210_GPIO0_TYPE_GPI 0x00 #define DA9210_GPIO0_TYPE_GPO 0x04 #define DA9210_GPIO0_MODE 0x08 #define DA9210_GPIO1_PIN_SHIFT 4 #define DA9210_GPIO1_PIN_MASK 0x30 #define DA9210_GPIO1_PIN_GPI 0x00 #define DA9210_GPIO1_PIN_VERROR 0x10 #define DA9210_GPIO1_PIN_GPO_OD 0x20 #define DA9210_GPIO1_PIN_GPO 0x30 #define DA9210_GPIO1_TYPE_SHIFT 0x40 #define DA9210_GPIO1_TYPE_GPI 0x00 #define DA9210_GPIO1_TYPE_GPO 0x40 #define DA9210_GPIO1_MODE 0x80 /* DA9210_REG_GPIO_2_3 (addr=0x59) */ #define DA9210_GPIO2_PIN_SHIFT 0 #define DA9210_GPIO2_PIN_MASK 0x03 #define DA9210_GPIO2_PIN_GPI 0x00 #define DA9210_GPIO5_PIN_BUCK_CLK 0x10 #define DA9210_GPIO2_PIN_GPO_OD 0x02 #define DA9210_GPIO2_PIN_GPO 0x03 #define DA9210_GPIO2_TYPE 0x04 #define DA9210_GPIO2_TYPE_GPI 0x00 #define DA9210_GPIO2_TYPE_GPO 0x04 #define DA9210_GPIO2_MODE 0x08 #define DA9210_GPIO3_PIN_SHIFT 4 #define DA9210_GPIO3_PIN_MASK 0x30 #define DA9210_GPIO3_PIN_GPI 0x00 #define DA9210_GPIO3_PIN_IERROR 0x10 #define DA9210_GPIO3_PIN_GPO_OD 0x20 #define DA9210_GPIO3_PIN_GPO 0x30 #define DA9210_GPIO3_TYPE_SHIFT 0x40 #define DA9210_GPIO3_TYPE_GPI 0x00 #define DA9210_GPIO3_TYPE_GPO 0x40 #define DA9210_GPIO3_MODE 0x80 /* DA9210_REG_GPIO_4_5 (addr=0x5A) */ #define DA9210_GPIO4_PIN_SHIFT 0 #define DA9210_GPIO4_PIN_MASK 0x03 #define DA9210_GPIO4_PIN_GPI 0x00 #define DA9210_GPIO4_PIN_GPO_OD 0x02 #define DA9210_GPIO4_PIN_GPO 0x03 #define DA9210_GPIO4_TYPE 0x04 #define DA9210_GPIO4_TYPE_GPI 0x00 #define DA9210_GPIO4_TYPE_GPO 0x04 #define DA9210_GPIO4_MODE 0x08 #define DA9210_GPIO5_PIN_SHIFT 4 #define DA9210_GPIO5_PIN_MASK 0x30 #define DA9210_GPIO5_PIN_GPI 0x00 #define DA9210_GPIO5_PIN_INTERFACE 0x01 #define DA9210_GPIO5_PIN_GPO_OD 0x20 #define DA9210_GPIO5_PIN_GPO 0x30 #define DA9210_GPIO5_TYPE_SHIFT 0x40 #define DA9210_GPIO5_TYPE_GPI 0x00 #define DA9210_GPIO5_TYPE_GPO 0x40 #define DA9210_GPIO5_MODE 0x80 /* DA9210_REG_GPIO_6 (addr=0x5B) */ #define DA9210_GPIO6_PIN_SHIFT 0 #define DA9210_GPIO6_PIN_MASK 0x03 #define DA9210_GPIO6_PIN_GPI 0x00 #define DA9210_GPIO6_PIN_INTERFACE 0x01 #define DA9210_GPIO6_PIN_GPO_OD 0x02 #define DA9210_GPIO6_PIN_GPO 0x03 #define DA9210_GPIO6_TYPE 0x04 #define DA9210_GPIO6_TYPE_GPI 0x00 #define DA9210_GPIO6_TYPE_GPO 0x04 #define DA9210_GPIO6_MODE 0x08 /* DA9210_REG_BUCK_CONT (addr=0x5D) */ #define DA9210_BUCK_EN 0x01 #define DA9210_BUCK_GPI_SHIFT 1 #define DA9210_BUCK_GPI_MASK 0x06 #define DA9210_BUCK_GPI_OFF 0x00 #define DA9210_BUCK_GPI_GPIO0 0x02 #define DA9210_BUCK_GPI_GPIO3 0x04 #define DA9210_BUCK_GPI_GPIO4 0x06 #define DA9210_BUCK_PD_DIS 0x08 #define DA9210_VBUCK_SEL 0x10 #define DA9210_VBUCK_SEL_A 0x00 #define DA9210_VBUCK_SEL_B 0x10 #define DA9210_VBUCK_GPI_SHIFT 5 #define DA9210_VBUCK_GPI_MASK 0x60 #define DA9210_VBUCK_GPI_OFF 0x00 #define DA9210_VBUCK_GPI_GPIO0 0x20 #define DA9210_VBUCK_GPI_GPIO3 0x40 #define DA9210_VBUCK_GPI_GPIO4 0x60 #define DA9210_DVC_CTRL_EN 0x80 /* DA9210_REG_BUCK_ILIM (addr=0xD0) */ #define DA9210_BUCK_ILIM_SHIFT 0 #define DA9210_BUCK_ILIM_MASK 0x0F #define DA9210_BUCK_IALARM 0x10 /* DA9210_REG_BUCK_CONF1 (addr=0xD1) */ #define DA9210_BUCK_MODE_SHIFT 0 #define DA9210_BUCK_MODE_MASK 0x03 #define DA9210_BUCK_MODE_MANUAL 0x00 #define DA9210_BUCK_MODE_SLEEP 0x01 #define DA9210_BUCK_MODE_SYNC 0x02 #define DA9210_BUCK_MODE_AUTO 0x03 #define DA9210_STARTUP_CTRL_SHIFT 2 #define DA9210_STARTUP_CTRL_MASK 0x1C #define DA9210_PWR_DOWN_CTRL_SHIFT 5 #define DA9210_PWR_DOWN_CTRL_MASK 0xE0 /* DA9210_REG_BUCK_CONF2 (addr=0xD2) */ #define DA9210_PHASE_SEL_SHIFT 0 #define DA9210_PHASE_SEL_MASK 0x03 #define DA9210_FREQ_SEL 0x40 /* DA9210_REG_BUCK_AUTO (addr=0xD4) */ #define DA9210_VBUCK_AUTO_SHIFT 0 #define DA9210_VBUCK_AUTO_MASK 0x7F /* DA9210_REG_BUCK_BASE (addr=0xD5) */ #define DA9210_VBUCK_BASE_SHIFT 0 #define DA9210_VBUCK_BASE_MASK 0x7F /* DA9210_REG_VBUCK_MAX_DVC_IF (addr=0xD6) */ #define DA9210_VBUCK_MAX_SHIFT 0 #define DA9210_VBUCK_MAX_MASK 0x7F #define DA9210_DVC_STEP_SIZE 0x80 #define DA9210_DVC_STEP_SIZE_10MV 0x00 #define DA9210_DVC_STEP_SIZE_20MV 0x80 /* DA9210_REG_VBUCK_DVC (addr=0xD7) */ #define DA9210_VBUCK_DVC_SHIFT 0 #define DA9210_VBUCK_DVC_MASK 0x7F /* DA9210_REG_VBUCK_A/B (addr=0xD8/0xD9) */ #define DA9210_VBUCK_SHIFT 0 #define DA9210_VBUCK_MASK 0x7F #define DA9210_VBUCK_BIAS 0 #define DA9210_BUCK_SL 0x80 /* DA9210_REG_INTERFACE (addr=0x105) */ #define DA9210_IF_BASE_ADDR_SHIFT 4 #define DA9210_IF_BASE_ADDR_MASK 0xF0 /* DA9210_REG_CONFIG_E (addr=0x147) */ #define DA9210_STAND_ALONE 0x01 #endif /* __DA9210_REGISTERS_H__ */
{ "language": "C" }
/* * IBM Accurate Mathematical Library * written by International Business Machines Corp. * Copyright (C) 2001, 2009 Free Software Foundation * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /****************************************************************************/ /* */ /* MODULE_NAME:usncs.c */ /* */ /* FUNCTIONS: usin */ /* ucos */ /* slow */ /* slow1 */ /* slow2 */ /* sloww */ /* sloww1 */ /* sloww2 */ /* bsloww */ /* bsloww1 */ /* bsloww2 */ /* cslow2 */ /* csloww */ /* csloww1 */ /* csloww2 */ /* FILES NEEDED: dla.h endian.h mpa.h mydefs.h usncs.h */ /* branred.c sincos32.c dosincos.c mpa.c */ /* sincos.tbl */ /* */ /* An ultimate sin and routine. Given an IEEE double machine number x */ /* it computes the correctly rounded (to nearest) value of sin(x) or cos(x) */ /* Assumption: Machine arithmetic operations are performed in */ /* round to nearest mode of IEEE 754 standard. */ /* */ /****************************************************************************/ #include <errno.h> #include "endian.h" #include "mydefs.h" #include "usncs.h" #include "MathLib.h" #include "sincos.tbl" #include "math_private.h" static const double sn3 = -1.66666666666664880952546298448555E-01, sn5 = 8.33333214285722277379541354343671E-03, cs2 = 4.99999999999999999999950396842453E-01, cs4 = -4.16666666666664434524222570944589E-02, cs6 = 1.38888874007937613028114285595617E-03; void __dubsin(double x, double dx, double w[]); void __docos(double x, double dx, double w[]); double __mpsin(double x, double dx); double __mpcos(double x, double dx); double __mpsin1(double x); double __mpcos1(double x); static double slow(double x); static double slow1(double x); static double slow2(double x); static double sloww(double x, double dx, double orig); static double sloww1(double x, double dx, double orig); static double sloww2(double x, double dx, double orig, int n); static double bsloww(double x, double dx, double orig, int n); static double bsloww1(double x, double dx, double orig, int n); static double bsloww2(double x, double dx, double orig, int n); int __branred(double x, double *a, double *aa); static double cslow2(double x); static double csloww(double x, double dx, double orig); static double csloww1(double x, double dx, double orig); static double csloww2(double x, double dx, double orig, int n); /*******************************************************************/ /* An ultimate sin routine. Given an IEEE double machine number x */ /* it computes the correctly rounded (to nearest) value of sin(x) */ /*******************************************************************/ double __sin(double x){ double xx,res,t,cor,y,s,c,sn,ssn,cs,ccs,xn,a,da,db,eps,xn1,xn2; #if 0 double w[2]; #endif mynumber u,v; int4 k,m,n; #if 0 int4 nn; #endif u.x = x; m = u.i[HIGH_HALF]; k = 0x7fffffff&m; /* no sign */ if (k < 0x3e500000) /* if x->0 =>sin(x)=x */ return x; /*---------------------------- 2^-26 < |x|< 0.25 ----------------------*/ else if (k < 0x3fd00000){ xx = x*x; /*Taylor series */ t = ((((s5.x*xx + s4.x)*xx + s3.x)*xx + s2.x)*xx + s1.x)*(xx*x); res = x+t; cor = (x-res)+t; return (res == res + 1.07*cor)? res : slow(x); } /* else if (k < 0x3fd00000) */ /*---------------------------- 0.25<|x|< 0.855469---------------------- */ else if (k < 0x3feb6000) { u.x=(m>0)?big.x+x:big.x-x; y=(m>0)?x-(u.x-big.x):x+(u.x-big.x); xx=y*y; s = y + y*xx*(sn3 +xx*sn5); c = xx*(cs2 +xx*(cs4 + xx*cs6)); k=u.i[LOW_HALF]<<2; sn=(m>0)?sincos.x[k]:-sincos.x[k]; ssn=(m>0)?sincos.x[k+1]:-sincos.x[k+1]; cs=sincos.x[k+2]; ccs=sincos.x[k+3]; cor=(ssn+s*ccs-sn*c)+cs*s; res=sn+cor; cor=(sn-res)+cor; return (res==res+1.025*cor)? res : slow1(x); } /* else if (k < 0x3feb6000) */ /*----------------------- 0.855469 <|x|<2.426265 ----------------------*/ else if (k < 0x400368fd ) { y = (m>0)? hp0.x-x:hp0.x+x; if (y>=0) { u.x = big.x+y; y = (y-(u.x-big.x))+hp1.x; } else { u.x = big.x-y; y = (-hp1.x) - (y+(u.x-big.x)); } xx=y*y; s = y + y*xx*(sn3 +xx*sn5); c = xx*(cs2 +xx*(cs4 + xx*cs6)); k=u.i[LOW_HALF]<<2; sn=sincos.x[k]; ssn=sincos.x[k+1]; cs=sincos.x[k+2]; ccs=sincos.x[k+3]; cor=(ccs-s*ssn-cs*c)-sn*s; res=cs+cor; cor=(cs-res)+cor; return (res==res+1.020*cor)? ((m>0)?res:-res) : slow2(x); } /* else if (k < 0x400368fd) */ /*-------------------------- 2.426265<|x|< 105414350 ----------------------*/ else if (k < 0x419921FB ) { t = (x*hpinv.x + toint.x); xn = t - toint.x; v.x = t; y = (x - xn*mp1.x) - xn*mp2.x; n =v.i[LOW_HALF]&3; da = xn*mp3.x; a=y-da; da = (y-a)-da; eps = ABS(x)*1.2e-30; switch (n) { /* quarter of unit circle */ case 0: case 2: xx = a*a; if (n) {a=-a;da=-da;} if (xx < 0.01588) { /*Taylor series */ t = (((((s5.x*xx + s4.x)*xx + s3.x)*xx + s2.x)*xx + s1.x)*a - 0.5*da)*xx+da; res = a+t; cor = (a-res)+t; cor = (cor>0)? 1.02*cor+eps : 1.02*cor -eps; return (res == res + cor)? res : sloww(a,da,x); } else { if (a>0) {m=1;t=a;db=da;} else {m=0;t=-a;db=-da;} u.x=big.x+t; y=t-(u.x-big.x); xx=y*y; s = y + (db+y*xx*(sn3 +xx*sn5)); c = y*db+xx*(cs2 +xx*(cs4 + xx*cs6)); k=u.i[LOW_HALF]<<2; sn=sincos.x[k]; ssn=sincos.x[k+1]; cs=sincos.x[k+2]; ccs=sincos.x[k+3]; cor=(ssn+s*ccs-sn*c)+cs*s; res=sn+cor; cor=(sn-res)+cor; cor = (cor>0)? 1.035*cor+eps : 1.035*cor-eps; return (res==res+cor)? ((m)?res:-res) : sloww1(a,da,x); } break; case 1: case 3: if (a<0) {a=-a;da=-da;} u.x=big.x+a; y=a-(u.x-big.x)+da; xx=y*y; k=u.i[LOW_HALF]<<2; sn=sincos.x[k]; ssn=sincos.x[k+1]; cs=sincos.x[k+2]; ccs=sincos.x[k+3]; s = y + y*xx*(sn3 +xx*sn5); c = xx*(cs2 +xx*(cs4 + xx*cs6)); cor=(ccs-s*ssn-cs*c)-sn*s; res=cs+cor; cor=(cs-res)+cor; cor = (cor>0)? 1.025*cor+eps : 1.025*cor-eps; return (res==res+cor)? ((n&2)?-res:res) : sloww2(a,da,x,n); break; } } /* else if (k < 0x419921FB ) */ /*---------------------105414350 <|x|< 281474976710656 --------------------*/ else if (k < 0x42F00000 ) { t = (x*hpinv.x + toint.x); xn = t - toint.x; v.x = t; xn1 = (xn+8.0e22)-8.0e22; xn2 = xn - xn1; y = ((((x - xn1*mp1.x) - xn1*mp2.x)-xn2*mp1.x)-xn2*mp2.x); n =v.i[LOW_HALF]&3; da = xn1*pp3.x; t=y-da; da = (y-t)-da; da = (da - xn2*pp3.x) -xn*pp4.x; a = t+da; da = (t-a)+da; eps = 1.0e-24; switch (n) { case 0: case 2: xx = a*a; if (n) {a=-a;da=-da;} if (xx < 0.01588) { /* Taylor series */ t = (((((s5.x*xx + s4.x)*xx + s3.x)*xx + s2.x)*xx + s1.x)*a - 0.5*da)*xx+da; res = a+t; cor = (a-res)+t; cor = (cor>0)? 1.02*cor+eps : 1.02*cor -eps; return (res == res + cor)? res : bsloww(a,da,x,n); } else { if (a>0) {m=1;t=a;db=da;} else {m=0;t=-a;db=-da;} u.x=big.x+t; y=t-(u.x-big.x); xx=y*y; s = y + (db+y*xx*(sn3 +xx*sn5)); c = y*db+xx*(cs2 +xx*(cs4 + xx*cs6)); k=u.i[LOW_HALF]<<2; sn=sincos.x[k]; ssn=sincos.x[k+1]; cs=sincos.x[k+2]; ccs=sincos.x[k+3]; cor=(ssn+s*ccs-sn*c)+cs*s; res=sn+cor; cor=(sn-res)+cor; cor = (cor>0)? 1.035*cor+eps : 1.035*cor-eps; return (res==res+cor)? ((m)?res:-res) : bsloww1(a,da,x,n); } break; case 1: case 3: if (a<0) {a=-a;da=-da;} u.x=big.x+a; y=a-(u.x-big.x)+da; xx=y*y; k=u.i[LOW_HALF]<<2; sn=sincos.x[k]; ssn=sincos.x[k+1]; cs=sincos.x[k+2]; ccs=sincos.x[k+3]; s = y + y*xx*(sn3 +xx*sn5); c = xx*(cs2 +xx*(cs4 + xx*cs6)); cor=(ccs-s*ssn-cs*c)-sn*s; res=cs+cor; cor=(cs-res)+cor; cor = (cor>0)? 1.025*cor+eps : 1.025*cor-eps; return (res==res+cor)? ((n&2)?-res:res) : bsloww2(a,da,x,n); break; } } /* else if (k < 0x42F00000 ) */ /* -----------------281474976710656 <|x| <2^1024----------------------------*/ else if (k < 0x7ff00000) { n = __branred(x,&a,&da); switch (n) { case 0: if (a*a < 0.01588) return bsloww(a,da,x,n); else return bsloww1(a,da,x,n); break; case 2: if (a*a < 0.01588) return bsloww(-a,-da,x,n); else return bsloww1(-a,-da,x,n); break; case 1: case 3: return bsloww2(a,da,x,n); break; } } /* else if (k < 0x7ff00000 ) */ /*--------------------- |x| > 2^1024 ----------------------------------*/ else { if (k == 0x7ff00000 && u.i[LOW_HALF] == 0) __set_errno (EDOM); return x / x; } return 0; /* unreachable */ } /*******************************************************************/ /* An ultimate cos routine. Given an IEEE double machine number x */ /* it computes the correctly rounded (to nearest) value of cos(x) */ /*******************************************************************/ double __cos(double x) { double y,xx,res,t,cor,s,c,sn,ssn,cs,ccs,xn,a,da,db,eps,xn1,xn2; mynumber u,v; int4 k,m,n; u.x = x; m = u.i[HIGH_HALF]; k = 0x7fffffff&m; if (k < 0x3e400000 ) return 1.0; /* |x|<2^-27 => cos(x)=1 */ else if (k < 0x3feb6000 ) {/* 2^-27 < |x| < 0.855469 */ y=ABS(x); u.x = big.x+y; y = y-(u.x-big.x); xx=y*y; s = y + y*xx*(sn3 +xx*sn5); c = xx*(cs2 +xx*(cs4 + xx*cs6)); k=u.i[LOW_HALF]<<2; sn=sincos.x[k]; ssn=sincos.x[k+1]; cs=sincos.x[k+2]; ccs=sincos.x[k+3]; cor=(ccs-s*ssn-cs*c)-sn*s; res=cs+cor; cor=(cs-res)+cor; return (res==res+1.020*cor)? res : cslow2(x); } /* else if (k < 0x3feb6000) */ else if (k < 0x400368fd ) {/* 0.855469 <|x|<2.426265 */; y=hp0.x-ABS(x); a=y+hp1.x; da=(y-a)+hp1.x; xx=a*a; if (xx < 0.01588) { t = (((((s5.x*xx + s4.x)*xx + s3.x)*xx + s2.x)*xx + s1.x)*a - 0.5*da)*xx+da; res = a+t; cor = (a-res)+t; cor = (cor>0)? 1.02*cor+1.0e-31 : 1.02*cor -1.0e-31; return (res == res + cor)? res : csloww(a,da,x); } else { if (a>0) {m=1;t=a;db=da;} else {m=0;t=-a;db=-da;} u.x=big.x+t; y=t-(u.x-big.x); xx=y*y; s = y + (db+y*xx*(sn3 +xx*sn5)); c = y*db+xx*(cs2 +xx*(cs4 + xx*cs6)); k=u.i[LOW_HALF]<<2; sn=sincos.x[k]; ssn=sincos.x[k+1]; cs=sincos.x[k+2]; ccs=sincos.x[k+3]; cor=(ssn+s*ccs-sn*c)+cs*s; res=sn+cor; cor=(sn-res)+cor; cor = (cor>0)? 1.035*cor+1.0e-31 : 1.035*cor-1.0e-31; return (res==res+cor)? ((m)?res:-res) : csloww1(a,da,x); } } /* else if (k < 0x400368fd) */ else if (k < 0x419921FB ) {/* 2.426265<|x|< 105414350 */ t = (x*hpinv.x + toint.x); xn = t - toint.x; v.x = t; y = (x - xn*mp1.x) - xn*mp2.x; n =v.i[LOW_HALF]&3; da = xn*mp3.x; a=y-da; da = (y-a)-da; eps = ABS(x)*1.2e-30; switch (n) { case 1: case 3: xx = a*a; if (n == 1) {a=-a;da=-da;} if (xx < 0.01588) { t = (((((s5.x*xx + s4.x)*xx + s3.x)*xx + s2.x)*xx + s1.x)*a - 0.5*da)*xx+da; res = a+t; cor = (a-res)+t; cor = (cor>0)? 1.02*cor+eps : 1.02*cor -eps; return (res == res + cor)? res : csloww(a,da,x); } else { if (a>0) {m=1;t=a;db=da;} else {m=0;t=-a;db=-da;} u.x=big.x+t; y=t-(u.x-big.x); xx=y*y; s = y + (db+y*xx*(sn3 +xx*sn5)); c = y*db+xx*(cs2 +xx*(cs4 + xx*cs6)); k=u.i[LOW_HALF]<<2; sn=sincos.x[k]; ssn=sincos.x[k+1]; cs=sincos.x[k+2]; ccs=sincos.x[k+3]; cor=(ssn+s*ccs-sn*c)+cs*s; res=sn+cor; cor=(sn-res)+cor; cor = (cor>0)? 1.035*cor+eps : 1.035*cor-eps; return (res==res+cor)? ((m)?res:-res) : csloww1(a,da,x); } break; case 0: case 2: if (a<0) {a=-a;da=-da;} u.x=big.x+a; y=a-(u.x-big.x)+da; xx=y*y; k=u.i[LOW_HALF]<<2; sn=sincos.x[k]; ssn=sincos.x[k+1]; cs=sincos.x[k+2]; ccs=sincos.x[k+3]; s = y + y*xx*(sn3 +xx*sn5); c = xx*(cs2 +xx*(cs4 + xx*cs6)); cor=(ccs-s*ssn-cs*c)-sn*s; res=cs+cor; cor=(cs-res)+cor; cor = (cor>0)? 1.025*cor+eps : 1.025*cor-eps; return (res==res+cor)? ((n)?-res:res) : csloww2(a,da,x,n); break; } } /* else if (k < 0x419921FB ) */ else if (k < 0x42F00000 ) { t = (x*hpinv.x + toint.x); xn = t - toint.x; v.x = t; xn1 = (xn+8.0e22)-8.0e22; xn2 = xn - xn1; y = ((((x - xn1*mp1.x) - xn1*mp2.x)-xn2*mp1.x)-xn2*mp2.x); n =v.i[LOW_HALF]&3; da = xn1*pp3.x; t=y-da; da = (y-t)-da; da = (da - xn2*pp3.x) -xn*pp4.x; a = t+da; da = (t-a)+da; eps = 1.0e-24; switch (n) { case 1: case 3: xx = a*a; if (n==1) {a=-a;da=-da;} if (xx < 0.01588) { t = (((((s5.x*xx + s4.x)*xx + s3.x)*xx + s2.x)*xx + s1.x)*a - 0.5*da)*xx+da; res = a+t; cor = (a-res)+t; cor = (cor>0)? 1.02*cor+eps : 1.02*cor -eps; return (res == res + cor)? res : bsloww(a,da,x,n); } else { if (a>0) {m=1;t=a;db=da;} else {m=0;t=-a;db=-da;} u.x=big.x+t; y=t-(u.x-big.x); xx=y*y; s = y + (db+y*xx*(sn3 +xx*sn5)); c = y*db+xx*(cs2 +xx*(cs4 + xx*cs6)); k=u.i[LOW_HALF]<<2; sn=sincos.x[k]; ssn=sincos.x[k+1]; cs=sincos.x[k+2]; ccs=sincos.x[k+3]; cor=(ssn+s*ccs-sn*c)+cs*s; res=sn+cor; cor=(sn-res)+cor; cor = (cor>0)? 1.035*cor+eps : 1.035*cor-eps; return (res==res+cor)? ((m)?res:-res) : bsloww1(a,da,x,n); } break; case 0: case 2: if (a<0) {a=-a;da=-da;} u.x=big.x+a; y=a-(u.x-big.x)+da; xx=y*y; k=u.i[LOW_HALF]<<2; sn=sincos.x[k]; ssn=sincos.x[k+1]; cs=sincos.x[k+2]; ccs=sincos.x[k+3]; s = y + y*xx*(sn3 +xx*sn5); c = xx*(cs2 +xx*(cs4 + xx*cs6)); cor=(ccs-s*ssn-cs*c)-sn*s; res=cs+cor; cor=(cs-res)+cor; cor = (cor>0)? 1.025*cor+eps : 1.025*cor-eps; return (res==res+cor)? ((n)?-res:res) : bsloww2(a,da,x,n); break; } } /* else if (k < 0x42F00000 ) */ else if (k < 0x7ff00000) {/* 281474976710656 <|x| <2^1024 */ n = __branred(x,&a,&da); switch (n) { case 1: if (a*a < 0.01588) return bsloww(-a,-da,x,n); else return bsloww1(-a,-da,x,n); break; case 3: if (a*a < 0.01588) return bsloww(a,da,x,n); else return bsloww1(a,da,x,n); break; case 0: case 2: return bsloww2(a,da,x,n); break; } } /* else if (k < 0x7ff00000 ) */ else { if (k == 0x7ff00000 && u.i[LOW_HALF] == 0) __set_errno (EDOM); return x / x; /* |x| > 2^1024 */ } return 0; } /************************************************************************/ /* Routine compute sin(x) for 2^-26 < |x|< 0.25 by Taylor with more */ /* precision and if still doesn't accurate enough by mpsin or dubsin */ /************************************************************************/ static double slow(double x) { static const double th2_36 = 206158430208.0; /* 1.5*2**37 */ double y,x1,x2,xx,r,t,res,cor,w[2]; x1=(x+th2_36)-th2_36; y = aa.x*x1*x1*x1; r=x+y; x2=x-x1; xx=x*x; t = (((((s5.x*xx + s4.x)*xx + s3.x)*xx + s2.x)*xx + bb.x)*xx + 3.0*aa.x*x1*x2)*x +aa.x*x2*x2*x2; t=((x-r)+y)+t; res=r+t; cor = (r-res)+t; if (res == res + 1.0007*cor) return res; else { __dubsin(ABS(x),0,w); if (w[0] == w[0]+1.000000001*w[1]) return (x>0)?w[0]:-w[0]; else return (x>0)?__mpsin(x,0):-__mpsin(-x,0); } } /*******************************************************************************/ /* Routine compute sin(x) for 0.25<|x|< 0.855469 by sincos.tbl and Taylor */ /* and if result still doesn't accurate enough by mpsin or dubsin */ /*******************************************************************************/ static double slow1(double x) { mynumber u; double sn,ssn,cs,ccs,s,c,w[2],y,y1,y2,c1,c2,xx,cor,res; static const double t22 = 6291456.0; int4 k; y=ABS(x); u.x=big.x+y; y=y-(u.x-big.x); xx=y*y; s = y*xx*(sn3 +xx*sn5); c = xx*(cs2 +xx*(cs4 + xx*cs6)); k=u.i[LOW_HALF]<<2; sn=sincos.x[k]; /* Data */ ssn=sincos.x[k+1]; /* from */ cs=sincos.x[k+2]; /* tables */ ccs=sincos.x[k+3]; /* sincos.tbl */ y1 = (y+t22)-t22; y2 = y - y1; c1 = (cs+t22)-t22; c2=(cs-c1)+ccs; cor=(ssn+s*ccs+cs*s+c2*y+c1*y2)-sn*c; y=sn+c1*y1; cor = cor+((sn-y)+c1*y1); res=y+cor; cor=(y-res)+cor; if (res == res+1.0005*cor) return (x>0)?res:-res; else { __dubsin(ABS(x),0,w); if (w[0] == w[0]+1.000000005*w[1]) return (x>0)?w[0]:-w[0]; else return (x>0)?__mpsin(x,0):-__mpsin(-x,0); } } /**************************************************************************/ /* Routine compute sin(x) for 0.855469 <|x|<2.426265 by sincos.tbl */ /* and if result still doesn't accurate enough by mpsin or dubsin */ /**************************************************************************/ static double slow2(double x) { mynumber u; double sn,ssn,cs,ccs,s,c,w[2],y,y1,y2,e1,e2,xx,cor,res,del; static const double t22 = 6291456.0; int4 k; y=ABS(x); y = hp0.x-y; if (y>=0) { u.x = big.x+y; y = y-(u.x-big.x); del = hp1.x; } else { u.x = big.x-y; y = -(y+(u.x-big.x)); del = -hp1.x; } xx=y*y; s = y*xx*(sn3 +xx*sn5); c = y*del+xx*(cs2 +xx*(cs4 + xx*cs6)); k=u.i[LOW_HALF]<<2; sn=sincos.x[k]; ssn=sincos.x[k+1]; cs=sincos.x[k+2]; ccs=sincos.x[k+3]; y1 = (y+t22)-t22; y2 = (y - y1)+del; e1 = (sn+t22)-t22; e2=(sn-e1)+ssn; cor=(ccs-cs*c-e1*y2-e2*y)-sn*s; y=cs-e1*y1; cor = cor+((cs-y)-e1*y1); res=y+cor; cor=(y-res)+cor; if (res == res+1.0005*cor) return (x>0)?res:-res; else { y=ABS(x)-hp0.x; y1=y-hp1.x; y2=(y-y1)-hp1.x; __docos(y1,y2,w); if (w[0] == w[0]+1.000000005*w[1]) return (x>0)?w[0]:-w[0]; else return (x>0)?__mpsin(x,0):-__mpsin(-x,0); } } /***************************************************************************/ /* Routine compute sin(x+dx) (Double-Length number) where x is small enough*/ /* to use Taylor series around zero and (x+dx) */ /* in first or third quarter of unit circle.Routine receive also */ /* (right argument) the original value of x for computing error of */ /* result.And if result not accurate enough routine calls mpsin1 or dubsin */ /***************************************************************************/ static double sloww(double x,double dx, double orig) { static const double th2_36 = 206158430208.0; /* 1.5*2**37 */ double y,x1,x2,xx,r,t,res,cor,w[2],a,da,xn; union {int4 i[2]; double x;} v; int4 n; x1=(x+th2_36)-th2_36; y = aa.x*x1*x1*x1; r=x+y; x2=(x-x1)+dx; xx=x*x; t = (((((s5.x*xx + s4.x)*xx + s3.x)*xx + s2.x)*xx + bb.x)*xx + 3.0*aa.x*x1*x2)*x +aa.x*x2*x2*x2+dx; t=((x-r)+y)+t; res=r+t; cor = (r-res)+t; cor = (cor>0)? 1.0005*cor+ABS(orig)*3.1e-30 : 1.0005*cor-ABS(orig)*3.1e-30; if (res == res + cor) return res; else { (x>0)? __dubsin(x,dx,w) : __dubsin(-x,-dx,w); cor = (w[1]>0)? 1.000000001*w[1] + ABS(orig)*1.1e-30 : 1.000000001*w[1] - ABS(orig)*1.1e-30; if (w[0] == w[0]+cor) return (x>0)?w[0]:-w[0]; else { t = (orig*hpinv.x + toint.x); xn = t - toint.x; v.x = t; y = (orig - xn*mp1.x) - xn*mp2.x; n =v.i[LOW_HALF]&3; da = xn*pp3.x; t=y-da; da = (y-t)-da; y = xn*pp4.x; a = t - y; da = ((t-a)-y)+da; if (n&2) {a=-a; da=-da;} (a>0)? __dubsin(a,da,w) : __dubsin(-a,-da,w); cor = (w[1]>0)? 1.000000001*w[1] + ABS(orig)*1.1e-40 : 1.000000001*w[1] - ABS(orig)*1.1e-40; if (w[0] == w[0]+cor) return (a>0)?w[0]:-w[0]; else return __mpsin1(orig); } } } /***************************************************************************/ /* Routine compute sin(x+dx) (Double-Length number) where x in first or */ /* third quarter of unit circle.Routine receive also (right argument) the */ /* original value of x for computing error of result.And if result not */ /* accurate enough routine calls mpsin1 or dubsin */ /***************************************************************************/ static double sloww1(double x, double dx, double orig) { mynumber u; double sn,ssn,cs,ccs,s,c,w[2],y,y1,y2,c1,c2,xx,cor,res; static const double t22 = 6291456.0; int4 k; y=ABS(x); u.x=big.x+y; y=y-(u.x-big.x); dx=(x>0)?dx:-dx; xx=y*y; s = y*xx*(sn3 +xx*sn5); c = xx*(cs2 +xx*(cs4 + xx*cs6)); k=u.i[LOW_HALF]<<2; sn=sincos.x[k]; ssn=sincos.x[k+1]; cs=sincos.x[k+2]; ccs=sincos.x[k+3]; y1 = (y+t22)-t22; y2 = (y - y1)+dx; c1 = (cs+t22)-t22; c2=(cs-c1)+ccs; cor=(ssn+s*ccs+cs*s+c2*y+c1*y2-sn*y*dx)-sn*c; y=sn+c1*y1; cor = cor+((sn-y)+c1*y1); res=y+cor; cor=(y-res)+cor; cor = (cor>0)? 1.0005*cor+3.1e-30*ABS(orig) : 1.0005*cor-3.1e-30*ABS(orig); if (res == res + cor) return (x>0)?res:-res; else { __dubsin(ABS(x),dx,w); cor = (w[1]>0)? 1.000000005*w[1]+1.1e-30*ABS(orig) : 1.000000005*w[1]-1.1e-30*ABS(orig); if (w[0] == w[0]+cor) return (x>0)?w[0]:-w[0]; else return __mpsin1(orig); } } /***************************************************************************/ /* Routine compute sin(x+dx) (Double-Length number) where x in second or */ /* fourth quarter of unit circle.Routine receive also the original value */ /* and quarter(n= 1or 3)of x for computing error of result.And if result not*/ /* accurate enough routine calls mpsin1 or dubsin */ /***************************************************************************/ static double sloww2(double x, double dx, double orig, int n) { mynumber u; double sn,ssn,cs,ccs,s,c,w[2],y,y1,y2,e1,e2,xx,cor,res; static const double t22 = 6291456.0; int4 k; y=ABS(x); u.x=big.x+y; y=y-(u.x-big.x); dx=(x>0)?dx:-dx; xx=y*y; s = y*xx*(sn3 +xx*sn5); c = y*dx+xx*(cs2 +xx*(cs4 + xx*cs6)); k=u.i[LOW_HALF]<<2; sn=sincos.x[k]; ssn=sincos.x[k+1]; cs=sincos.x[k+2]; ccs=sincos.x[k+3]; y1 = (y+t22)-t22; y2 = (y - y1)+dx; e1 = (sn+t22)-t22; e2=(sn-e1)+ssn; cor=(ccs-cs*c-e1*y2-e2*y)-sn*s; y=cs-e1*y1; cor = cor+((cs-y)-e1*y1); res=y+cor; cor=(y-res)+cor; cor = (cor>0)? 1.0005*cor+3.1e-30*ABS(orig) : 1.0005*cor-3.1e-30*ABS(orig); if (res == res + cor) return (n&2)?-res:res; else { __docos(ABS(x),dx,w); cor = (w[1]>0)? 1.000000005*w[1]+1.1e-30*ABS(orig) : 1.000000005*w[1]-1.1e-30*ABS(orig); if (w[0] == w[0]+cor) return (n&2)?-w[0]:w[0]; else return __mpsin1(orig); } } /***************************************************************************/ /* Routine compute sin(x+dx) or cos(x+dx) (Double-Length number) where x */ /* is small enough to use Taylor series around zero and (x+dx) */ /* in first or third quarter of unit circle.Routine receive also */ /* (right argument) the original value of x for computing error of */ /* result.And if result not accurate enough routine calls other routines */ /***************************************************************************/ static double bsloww(double x,double dx, double orig,int n) { static const double th2_36 = 206158430208.0; /* 1.5*2**37 */ double y,x1,x2,xx,r,t,res,cor,w[2]; #if 0 double a,da,xn; union {int4 i[2]; double x;} v; #endif x1=(x+th2_36)-th2_36; y = aa.x*x1*x1*x1; r=x+y; x2=(x-x1)+dx; xx=x*x; t = (((((s5.x*xx + s4.x)*xx + s3.x)*xx + s2.x)*xx + bb.x)*xx + 3.0*aa.x*x1*x2)*x +aa.x*x2*x2*x2+dx; t=((x-r)+y)+t; res=r+t; cor = (r-res)+t; cor = (cor>0)? 1.0005*cor+1.1e-24 : 1.0005*cor-1.1e-24; if (res == res + cor) return res; else { (x>0)? __dubsin(x,dx,w) : __dubsin(-x,-dx,w); cor = (w[1]>0)? 1.000000001*w[1] + 1.1e-24 : 1.000000001*w[1] - 1.1e-24; if (w[0] == w[0]+cor) return (x>0)?w[0]:-w[0]; else return (n&1)?__mpcos1(orig):__mpsin1(orig); } } /***************************************************************************/ /* Routine compute sin(x+dx) or cos(x+dx) (Double-Length number) where x */ /* in first or third quarter of unit circle.Routine receive also */ /* (right argument) the original value of x for computing error of result.*/ /* And if result not accurate enough routine calls other routines */ /***************************************************************************/ static double bsloww1(double x, double dx, double orig,int n) { mynumber u; double sn,ssn,cs,ccs,s,c,w[2],y,y1,y2,c1,c2,xx,cor,res; static const double t22 = 6291456.0; int4 k; y=ABS(x); u.x=big.x+y; y=y-(u.x-big.x); dx=(x>0)?dx:-dx; xx=y*y; s = y*xx*(sn3 +xx*sn5); c = xx*(cs2 +xx*(cs4 + xx*cs6)); k=u.i[LOW_HALF]<<2; sn=sincos.x[k]; ssn=sincos.x[k+1]; cs=sincos.x[k+2]; ccs=sincos.x[k+3]; y1 = (y+t22)-t22; y2 = (y - y1)+dx; c1 = (cs+t22)-t22; c2=(cs-c1)+ccs; cor=(ssn+s*ccs+cs*s+c2*y+c1*y2-sn*y*dx)-sn*c; y=sn+c1*y1; cor = cor+((sn-y)+c1*y1); res=y+cor; cor=(y-res)+cor; cor = (cor>0)? 1.0005*cor+1.1e-24 : 1.0005*cor-1.1e-24; if (res == res + cor) return (x>0)?res:-res; else { __dubsin(ABS(x),dx,w); cor = (w[1]>0)? 1.000000005*w[1]+1.1e-24: 1.000000005*w[1]-1.1e-24; if (w[0] == w[0]+cor) return (x>0)?w[0]:-w[0]; else return (n&1)?__mpcos1(orig):__mpsin1(orig); } } /***************************************************************************/ /* Routine compute sin(x+dx) or cos(x+dx) (Double-Length number) where x */ /* in second or fourth quarter of unit circle.Routine receive also the */ /* original value and quarter(n= 1or 3)of x for computing error of result. */ /* And if result not accurate enough routine calls other routines */ /***************************************************************************/ static double bsloww2(double x, double dx, double orig, int n) { mynumber u; double sn,ssn,cs,ccs,s,c,w[2],y,y1,y2,e1,e2,xx,cor,res; static const double t22 = 6291456.0; int4 k; y=ABS(x); u.x=big.x+y; y=y-(u.x-big.x); dx=(x>0)?dx:-dx; xx=y*y; s = y*xx*(sn3 +xx*sn5); c = y*dx+xx*(cs2 +xx*(cs4 + xx*cs6)); k=u.i[LOW_HALF]<<2; sn=sincos.x[k]; ssn=sincos.x[k+1]; cs=sincos.x[k+2]; ccs=sincos.x[k+3]; y1 = (y+t22)-t22; y2 = (y - y1)+dx; e1 = (sn+t22)-t22; e2=(sn-e1)+ssn; cor=(ccs-cs*c-e1*y2-e2*y)-sn*s; y=cs-e1*y1; cor = cor+((cs-y)-e1*y1); res=y+cor; cor=(y-res)+cor; cor = (cor>0)? 1.0005*cor+1.1e-24 : 1.0005*cor-1.1e-24; if (res == res + cor) return (n&2)?-res:res; else { __docos(ABS(x),dx,w); cor = (w[1]>0)? 1.000000005*w[1]+1.1e-24 : 1.000000005*w[1]-1.1e-24; if (w[0] == w[0]+cor) return (n&2)?-w[0]:w[0]; else return (n&1)?__mpsin1(orig):__mpcos1(orig); } } /************************************************************************/ /* Routine compute cos(x) for 2^-27 < |x|< 0.25 by Taylor with more */ /* precision and if still doesn't accurate enough by mpcos or docos */ /************************************************************************/ static double cslow2(double x) { mynumber u; double sn,ssn,cs,ccs,s,c,w[2],y,y1,y2,e1,e2,xx,cor,res; static const double t22 = 6291456.0; int4 k; y=ABS(x); u.x = big.x+y; y = y-(u.x-big.x); xx=y*y; s = y*xx*(sn3 +xx*sn5); c = xx*(cs2 +xx*(cs4 + xx*cs6)); k=u.i[LOW_HALF]<<2; sn=sincos.x[k]; ssn=sincos.x[k+1]; cs=sincos.x[k+2]; ccs=sincos.x[k+3]; y1 = (y+t22)-t22; y2 = y - y1; e1 = (sn+t22)-t22; e2=(sn-e1)+ssn; cor=(ccs-cs*c-e1*y2-e2*y)-sn*s; y=cs-e1*y1; cor = cor+((cs-y)-e1*y1); res=y+cor; cor=(y-res)+cor; if (res == res+1.0005*cor) return res; else { y=ABS(x); __docos(y,0,w); if (w[0] == w[0]+1.000000005*w[1]) return w[0]; else return __mpcos(x,0); } } /***************************************************************************/ /* Routine compute cos(x+dx) (Double-Length number) where x is small enough*/ /* to use Taylor series around zero and (x+dx) .Routine receive also */ /* (right argument) the original value of x for computing error of */ /* result.And if result not accurate enough routine calls other routines */ /***************************************************************************/ static double csloww(double x,double dx, double orig) { static const double th2_36 = 206158430208.0; /* 1.5*2**37 */ double y,x1,x2,xx,r,t,res,cor,w[2],a,da,xn; union {int4 i[2]; double x;} v; int4 n; x1=(x+th2_36)-th2_36; y = aa.x*x1*x1*x1; r=x+y; x2=(x-x1)+dx; xx=x*x; /* Taylor series */ t = (((((s5.x*xx + s4.x)*xx + s3.x)*xx + s2.x)*xx + bb.x)*xx + 3.0*aa.x*x1*x2)*x +aa.x*x2*x2*x2+dx; t=((x-r)+y)+t; res=r+t; cor = (r-res)+t; cor = (cor>0)? 1.0005*cor+ABS(orig)*3.1e-30 : 1.0005*cor-ABS(orig)*3.1e-30; if (res == res + cor) return res; else { (x>0)? __dubsin(x,dx,w) : __dubsin(-x,-dx,w); cor = (w[1]>0)? 1.000000001*w[1] + ABS(orig)*1.1e-30 : 1.000000001*w[1] - ABS(orig)*1.1e-30; if (w[0] == w[0]+cor) return (x>0)?w[0]:-w[0]; else { t = (orig*hpinv.x + toint.x); xn = t - toint.x; v.x = t; y = (orig - xn*mp1.x) - xn*mp2.x; n =v.i[LOW_HALF]&3; da = xn*pp3.x; t=y-da; da = (y-t)-da; y = xn*pp4.x; a = t - y; da = ((t-a)-y)+da; if (n==1) {a=-a; da=-da;} (a>0)? __dubsin(a,da,w) : __dubsin(-a,-da,w); cor = (w[1]>0)? 1.000000001*w[1] + ABS(orig)*1.1e-40 : 1.000000001*w[1] - ABS(orig)*1.1e-40; if (w[0] == w[0]+cor) return (a>0)?w[0]:-w[0]; else return __mpcos1(orig); } } } /***************************************************************************/ /* Routine compute sin(x+dx) (Double-Length number) where x in first or */ /* third quarter of unit circle.Routine receive also (right argument) the */ /* original value of x for computing error of result.And if result not */ /* accurate enough routine calls other routines */ /***************************************************************************/ static double csloww1(double x, double dx, double orig) { mynumber u; double sn,ssn,cs,ccs,s,c,w[2],y,y1,y2,c1,c2,xx,cor,res; static const double t22 = 6291456.0; int4 k; y=ABS(x); u.x=big.x+y; y=y-(u.x-big.x); dx=(x>0)?dx:-dx; xx=y*y; s = y*xx*(sn3 +xx*sn5); c = xx*(cs2 +xx*(cs4 + xx*cs6)); k=u.i[LOW_HALF]<<2; sn=sincos.x[k]; ssn=sincos.x[k+1]; cs=sincos.x[k+2]; ccs=sincos.x[k+3]; y1 = (y+t22)-t22; y2 = (y - y1)+dx; c1 = (cs+t22)-t22; c2=(cs-c1)+ccs; cor=(ssn+s*ccs+cs*s+c2*y+c1*y2-sn*y*dx)-sn*c; y=sn+c1*y1; cor = cor+((sn-y)+c1*y1); res=y+cor; cor=(y-res)+cor; cor = (cor>0)? 1.0005*cor+3.1e-30*ABS(orig) : 1.0005*cor-3.1e-30*ABS(orig); if (res == res + cor) return (x>0)?res:-res; else { __dubsin(ABS(x),dx,w); cor = (w[1]>0)? 1.000000005*w[1]+1.1e-30*ABS(orig) : 1.000000005*w[1]-1.1e-30*ABS(orig); if (w[0] == w[0]+cor) return (x>0)?w[0]:-w[0]; else return __mpcos1(orig); } } /***************************************************************************/ /* Routine compute sin(x+dx) (Double-Length number) where x in second or */ /* fourth quarter of unit circle.Routine receive also the original value */ /* and quarter(n= 1or 3)of x for computing error of result.And if result not*/ /* accurate enough routine calls other routines */ /***************************************************************************/ static double csloww2(double x, double dx, double orig, int n) { mynumber u; double sn,ssn,cs,ccs,s,c,w[2],y,y1,y2,e1,e2,xx,cor,res; static const double t22 = 6291456.0; int4 k; y=ABS(x); u.x=big.x+y; y=y-(u.x-big.x); dx=(x>0)?dx:-dx; xx=y*y; s = y*xx*(sn3 +xx*sn5); c = y*dx+xx*(cs2 +xx*(cs4 + xx*cs6)); k=u.i[LOW_HALF]<<2; sn=sincos.x[k]; ssn=sincos.x[k+1]; cs=sincos.x[k+2]; ccs=sincos.x[k+3]; y1 = (y+t22)-t22; y2 = (y - y1)+dx; e1 = (sn+t22)-t22; e2=(sn-e1)+ssn; cor=(ccs-cs*c-e1*y2-e2*y)-sn*s; y=cs-e1*y1; cor = cor+((cs-y)-e1*y1); res=y+cor; cor=(y-res)+cor; cor = (cor>0)? 1.0005*cor+3.1e-30*ABS(orig) : 1.0005*cor-3.1e-30*ABS(orig); if (res == res + cor) return (n)?-res:res; else { __docos(ABS(x),dx,w); cor = (w[1]>0)? 1.000000005*w[1]+1.1e-30*ABS(orig) : 1.000000005*w[1]-1.1e-30*ABS(orig); if (w[0] == w[0]+cor) return (n)?-w[0]:w[0]; else return __mpcos1(orig); } } weak_alias (__cos, cos) weak_alias (__sin, sin) #ifdef NO_LONG_DOUBLE strong_alias (__sin, __sinl) weak_alias (__sin, sinl) strong_alias (__cos, __cosl) weak_alias (__cos, cosl) #endif
{ "language": "C" }
/* * Copyright (c) 2000-2016 Apple Computer, Inc. All rights reserved. * * @APPLE_OSREFERENCE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. The rights granted to you under the License * may not be used to create, or enable the creation or redistribution of, * unlawful or unlicensed copies of an Apple operating system, or to * circumvent, violate, or enable the circumvention or violation of, any * terms of an Apple operating system software license agreement. * * Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_OSREFERENCE_LICENSE_HEADER_END@ */ /* * Mach Operating System * Copyright (c) 1987 Carnegie-Mellon University * All rights reserved. The CMU software License Agreement specifies * the terms and conditions for use and redistribution. */ #include <sys/param.h> #include <sys/systm.h> #include <sys/proc_internal.h> #include <sys/user.h> #include <sys/file_internal.h> #include <sys/vnode.h> #include <sys/kernel.h> #include <kern/queue.h> #include <sys/lock.h> #include <kern/thread.h> #include <kern/sched_prim.h> #include <kern/ast.h> #include <kern/cpu_number.h> #include <vm/vm_kern.h> #include <kern/task.h> #include <mach/time_value.h> #include <kern/locks.h> #include <kern/policy_internal.h> #include <sys/systm.h> /* for unix_syscall_return() */ #include <libkern/OSAtomic.h> extern void compute_averunnable(void *); /* XXX */ __attribute__((noreturn)) static void _sleep_continue( __unused void *parameter, wait_result_t wresult) { struct proc *p = current_proc(); thread_t self = current_thread(); struct uthread * ut; int sig, catch; int error = 0; int dropmutex, spinmutex; ut = get_bsdthread_info(self); catch = ut->uu_pri & PCATCH; dropmutex = ut->uu_pri & PDROP; spinmutex = ut->uu_pri & PSPIN; switch (wresult) { case THREAD_TIMED_OUT: error = EWOULDBLOCK; break; case THREAD_AWAKENED: /* * Posix implies any signal should be delivered * first, regardless of whether awakened due * to receiving event. */ if (!catch) break; /* else fall through */ case THREAD_INTERRUPTED: if (catch) { if (thread_should_abort(self)) { error = EINTR; } else if (SHOULDissignal(p,ut)) { if ((sig = CURSIG(p)) != 0) { if (p->p_sigacts->ps_sigintr & sigmask(sig)) error = EINTR; else error = ERESTART; } if (thread_should_abort(self)) { error = EINTR; } } else if( (ut->uu_flag & ( UT_CANCELDISABLE | UT_CANCEL | UT_CANCELED)) == UT_CANCEL) { /* due to thread cancel */ error = EINTR; } } else error = EINTR; break; } if (error == EINTR || error == ERESTART) act_set_astbsd(self); if (ut->uu_mtx && !dropmutex) { if (spinmutex) lck_mtx_lock_spin(ut->uu_mtx); else lck_mtx_lock(ut->uu_mtx); } ut->uu_wchan = NULL; ut->uu_wmesg = NULL; unix_syscall_return((*ut->uu_continuation)(error)); } /* * Give up the processor till a wakeup occurs * on chan, at which time the process * enters the scheduling queue at priority pri. * The most important effect of pri is that when * pri<=PZERO a signal cannot disturb the sleep; * if pri>PZERO signals will be processed. * If pri&PCATCH is set, signals will cause sleep * to return 1, rather than longjmp. * Callers of this routine must be prepared for * premature return, and check that the reason for * sleeping has gone away. * * if msleep was the entry point, than we have a mutex to deal with * * The mutex is unlocked before the caller is blocked, and * relocked before msleep returns unless the priority includes the PDROP * flag... if PDROP is specified, _sleep returns with the mutex unlocked * regardless of whether it actually blocked or not. */ static int _sleep( caddr_t chan, int pri, const char *wmsg, u_int64_t abstime, int (*continuation)(int), lck_mtx_t *mtx) { struct proc *p; thread_t self = current_thread(); struct uthread * ut; int sig, catch; int dropmutex = pri & PDROP; int spinmutex = pri & PSPIN; int wait_result; int error = 0; ut = get_bsdthread_info(self); p = current_proc(); p->p_priority = pri & PRIMASK; /* It can still block in proc_exit() after the teardown. */ if (p->p_stats != NULL) OSIncrementAtomicLong(&p->p_stats->p_ru.ru_nvcsw); if (pri & PCATCH) catch = THREAD_ABORTSAFE; else catch = THREAD_UNINT; /* set wait message & channel */ ut->uu_wchan = chan; ut->uu_wmesg = wmsg ? wmsg : "unknown"; if (mtx != NULL && chan != NULL && (thread_continue_t)continuation == THREAD_CONTINUE_NULL) { int flags; if (dropmutex) flags = LCK_SLEEP_UNLOCK; else flags = LCK_SLEEP_DEFAULT; if (spinmutex) flags |= LCK_SLEEP_SPIN; if (abstime) wait_result = lck_mtx_sleep_deadline(mtx, flags, chan, catch, abstime); else wait_result = lck_mtx_sleep(mtx, flags, chan, catch); } else { if (chan != NULL) assert_wait_deadline(chan, catch, abstime); if (mtx) lck_mtx_unlock(mtx); if (catch == THREAD_ABORTSAFE) { if (SHOULDissignal(p,ut)) { if ((sig = CURSIG(p)) != 0) { if (clear_wait(self, THREAD_INTERRUPTED) == KERN_FAILURE) goto block; if (p->p_sigacts->ps_sigintr & sigmask(sig)) error = EINTR; else error = ERESTART; if (mtx && !dropmutex) { if (spinmutex) lck_mtx_lock_spin(mtx); else lck_mtx_lock(mtx); } goto out; } } if (thread_should_abort(self)) { if (clear_wait(self, THREAD_INTERRUPTED) == KERN_FAILURE) goto block; error = EINTR; if (mtx && !dropmutex) { if (spinmutex) lck_mtx_lock_spin(mtx); else lck_mtx_lock(mtx); } goto out; } } block: if ((thread_continue_t)continuation != THREAD_CONTINUE_NULL) { ut->uu_continuation = continuation; ut->uu_pri = pri; ut->uu_timo = abstime? 1: 0; ut->uu_mtx = mtx; (void) thread_block(_sleep_continue); /* NOTREACHED */ } wait_result = thread_block(THREAD_CONTINUE_NULL); if (mtx && !dropmutex) { if (spinmutex) lck_mtx_lock_spin(mtx); else lck_mtx_lock(mtx); } } switch (wait_result) { case THREAD_TIMED_OUT: error = EWOULDBLOCK; break; case THREAD_AWAKENED: case THREAD_RESTART: /* * Posix implies any signal should be delivered * first, regardless of whether awakened due * to receiving event. */ if (catch != THREAD_ABORTSAFE) break; /* else fall through */ case THREAD_INTERRUPTED: if (catch == THREAD_ABORTSAFE) { if (thread_should_abort(self)) { error = EINTR; } else if (SHOULDissignal(p, ut)) { if ((sig = CURSIG(p)) != 0) { if (p->p_sigacts->ps_sigintr & sigmask(sig)) error = EINTR; else error = ERESTART; } if (thread_should_abort(self)) { error = EINTR; } } else if( (ut->uu_flag & ( UT_CANCELDISABLE | UT_CANCEL | UT_CANCELED)) == UT_CANCEL) { /* due to thread cancel */ error = EINTR; } } else error = EINTR; break; } out: if (error == EINTR || error == ERESTART) act_set_astbsd(self); ut->uu_wchan = NULL; ut->uu_wmesg = NULL; return (error); } int sleep( void *chan, int pri) { return _sleep((caddr_t)chan, pri, (char *)NULL, 0, (int (*)(int))0, (lck_mtx_t *)0); } int msleep0( void *chan, lck_mtx_t *mtx, int pri, const char *wmsg, int timo, int (*continuation)(int)) { u_int64_t abstime = 0; if (timo) clock_interval_to_deadline(timo, NSEC_PER_SEC / hz, &abstime); return _sleep((caddr_t)chan, pri, wmsg, abstime, continuation, mtx); } int msleep( void *chan, lck_mtx_t *mtx, int pri, const char *wmsg, struct timespec *ts) { u_int64_t abstime = 0; if (ts && (ts->tv_sec || ts->tv_nsec)) { nanoseconds_to_absolutetime((uint64_t)ts->tv_sec * NSEC_PER_SEC + ts->tv_nsec, &abstime ); clock_absolutetime_interval_to_deadline( abstime, &abstime ); } return _sleep((caddr_t)chan, pri, wmsg, abstime, (int (*)(int))0, mtx); } int msleep1( void *chan, lck_mtx_t *mtx, int pri, const char *wmsg, u_int64_t abstime) { return _sleep((caddr_t)chan, pri, wmsg, abstime, (int (*)(int))0, mtx); } int tsleep( void *chan, int pri, const char *wmsg, int timo) { u_int64_t abstime = 0; if (timo) clock_interval_to_deadline(timo, NSEC_PER_SEC / hz, &abstime); return _sleep((caddr_t)chan, pri, wmsg, abstime, (int (*)(int))0, (lck_mtx_t *)0); } int tsleep0( void *chan, int pri, const char *wmsg, int timo, int (*continuation)(int)) { u_int64_t abstime = 0; if (timo) clock_interval_to_deadline(timo, NSEC_PER_SEC / hz, &abstime); return _sleep((caddr_t)chan, pri, wmsg, abstime, continuation, (lck_mtx_t *)0); } int tsleep1( void *chan, int pri, const char *wmsg, u_int64_t abstime, int (*continuation)(int)) { return _sleep((caddr_t)chan, pri, wmsg, abstime, continuation, (lck_mtx_t *)0); } /* * Wake up all processes sleeping on chan. */ void wakeup(void *chan) { thread_wakeup((caddr_t)chan); } /* * Wake up the first process sleeping on chan. * * Be very sure that the first process is really * the right one to wakeup. */ void wakeup_one(caddr_t chan) { thread_wakeup_one((caddr_t)chan); } /* * Compute the priority of a process when running in user mode. * Arrange to reschedule if the resulting priority is better * than that of the current process. */ void resetpriority(struct proc *p) { (void)task_importance(p->task, -p->p_nice); } struct loadavg averunnable = { {0, 0, 0}, FSCALE }; /* load average, of runnable procs */ /* * Constants for averages over 1, 5, and 15 minutes * when sampling at 5 second intervals. */ static fixpt_t cexp[3] = { (fixpt_t)(0.9200444146293232 * FSCALE), /* exp(-1/12) */ (fixpt_t)(0.9834714538216174 * FSCALE), /* exp(-1/60) */ (fixpt_t)(0.9944598480048967 * FSCALE), /* exp(-1/180) */ }; void compute_averunnable(void *arg) { unsigned int nrun = *(unsigned int *)arg; struct loadavg *avg = &averunnable; int i; for (i = 0; i < 3; i++) avg->ldavg[i] = (cexp[i] * avg->ldavg[i] + nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT; }
{ "language": "C" }
/* * Copyright 2014 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * */ #ifndef __AMDGPU_IH_H__ #define __AMDGPU_IH_H__ #include <linux/chash.h> #include "soc15_ih_clientid.h" struct amdgpu_device; #define AMDGPU_IH_CLIENTID_LEGACY 0 #define AMDGPU_IH_CLIENTID_MAX SOC15_IH_CLIENTID_MAX #define AMDGPU_PAGEFAULT_HASH_BITS 8 struct amdgpu_retryfault_hashtable { DECLARE_CHASH_TABLE(hash, AMDGPU_PAGEFAULT_HASH_BITS, 8, 0); spinlock_t lock; int count; }; /* * R6xx+ IH ring */ struct amdgpu_ih_ring { struct amdgpu_bo *ring_obj; volatile uint32_t *ring; unsigned rptr; unsigned ring_size; uint64_t gpu_addr; uint32_t ptr_mask; atomic_t lock; bool enabled; unsigned wptr_offs; unsigned rptr_offs; u32 doorbell_index; bool use_doorbell; bool use_bus_addr; dma_addr_t rb_dma_addr; /* only used when use_bus_addr = true */ struct amdgpu_retryfault_hashtable *faults; }; #define AMDGPU_IH_SRC_DATA_MAX_SIZE_DW 4 struct amdgpu_iv_entry { unsigned client_id; unsigned src_id; unsigned ring_id; unsigned vmid; unsigned vmid_src; uint64_t timestamp; unsigned timestamp_src; unsigned pasid; unsigned pasid_src; unsigned src_data[AMDGPU_IH_SRC_DATA_MAX_SIZE_DW]; const uint32_t *iv_entry; }; int amdgpu_ih_ring_init(struct amdgpu_device *adev, unsigned ring_size, bool use_bus_addr); void amdgpu_ih_ring_fini(struct amdgpu_device *adev); int amdgpu_ih_process(struct amdgpu_device *adev); int amdgpu_ih_add_fault(struct amdgpu_device *adev, u64 key); void amdgpu_ih_clear_fault(struct amdgpu_device *adev, u64 key); #endif
{ "language": "C" }
/* zip_error_get_sys_type.c -- return type of system error code Copyright (C) 1999-2014 Dieter Baron and Thomas Klausner This file is part of libzip, a library to manipulate ZIP archives. The authors can be contacted at <libzip@nih.at> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #define _ZIP_COMPILING_DEPRECATED #include "zipint.h" ZIP_EXTERN int zip_error_get_sys_type(int ze) { if (ze < 0 || ze >= _zip_nerr_str) return 0; return _zip_err_type[ze]; }
{ "language": "C" }
// -*- C++ -*- // // $Id: config-linux.h 95533 2012-02-14 22:59:17Z wotte $ // The following configuration file is designed to work for Linux // platforms using GNU C++. #ifndef ACE_CONFIG_LINUX_H #define ACE_CONFIG_LINUX_H #include /**/ "ace/pre.h" #if !defined (ACE_LINUX) #define ACE_LINUX #endif /* ACE_LINUX */ #if !defined (ACE_MT_SAFE) # define ACE_MT_SAFE 1 #endif #if !defined (__ACE_INLINE__) # define __ACE_INLINE__ #endif /* ! __ACE_INLINE__ */ #if !defined (ACE_PLATFORM_CONFIG) #define ACE_PLATFORM_CONFIG config-linux.h #endif #define ACE_HAS_BYTESEX_H // Needed to differentiate between libc 5 and libc 6 (aka glibc). #include <features.h> #if (defined _XOPEN_SOURCE && (_XOPEN_SOURCE - 0) >= 500) # define ACE_HAS_PTHREADS_UNIX98_EXT #endif /* _XOPEN_SOURCE - 0 >= 500 */ # include "ace/config-posix.h" #if !defined (ACE_LACKS_LINUX_NPTL) // Temporary fix because NPTL kernels do have shm_open but there is a problem // with shm_open/shm_unlink pairing in ACE which needs to be fixed when I have time. # if defined (ACE_HAS_SHM_OPEN) # undef ACE_HAS_SHM_OPEN # endif /* ACE_HAS_SHM_OPEN */ # if defined (ACE_USES_FIFO_SEM) // Don't use this for Linux NPTL since this has complete // POSIX semaphores which are more efficient # undef ACE_USES_FIFO_SEM # endif /* ACE_USES_FIFO_SEM */ # if defined (ACE_HAS_POSIX_SEM) // Linux NPTL may not define the right POSIX macro // but they have the actual runtime support for this stuff # if !defined (ACE_HAS_POSIX_SEM_TIMEOUT) && (((_POSIX_C_SOURCE - 0) >= 200112L) || (_XOPEN_SOURCE >= 600)) # define ACE_HAS_POSIX_SEM_TIMEOUT # endif /* !ACE_HAS_POSIX_SEM_TIMEOUT && (((_POSIX_C_SOURCE - 0) >= 200112L) || (_XOPEN_SOURCE >= 600)) */ # endif /* ACE_HAS_POSIX_SEM */ #endif /* !ACE_LACKS_LINUX_NPTL */ // AIO support pulls in the rt library, which pulls in the pthread // library. Disable AIO in single-threaded builds. #if defined (ACE_HAS_THREADS) # define ACE_HAS_CLOCK_GETTIME # define ACE_HAS_CLOCK_SETTIME #else # undef ACE_HAS_AIO_CALLS #endif // First the machine specific part #if defined (__powerpc__) || defined (__x86_64__) # if !defined (ACE_DEFAULT_BASE_ADDR) # define ACE_DEFAULT_BASE_ADDR ((char *) 0x40000000) # endif /* ! ACE_DEFAULT_BASE_ADDR */ #elif defined (__ia64) # if !defined (ACE_DEFAULT_BASE_ADDR) // Zero base address should work fine for Linux of IA-64: it just lets // the kernel to choose the right value. # define ACE_DEFAULT_BASE_ADDR ((char *) 0x0000000000000000) # endif /* ! ACE_DEFAULT_BASE_ADDR */ #endif /* ! __powerpc__ && ! __ia64 */ // Then glibc/libc5 specific parts #if defined(__GLIBC__) # if (__GLIBC__ < 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 3) # define ACE_HAS_RUSAGE_WHO_ENUM enum __rusage_who # define ACE_HAS_RLIMIT_RESOURCE_ENUM enum __rlimit_resource # define ACE_LACKS_ISCTYPE # endif # define ACE_HAS_SOCKLEN_T # define ACE_HAS_4_4BSD_SENDMSG_RECVMSG // glibc defines both of these, used in OS_String. # if defined (_GNU_SOURCE) # define ACE_HAS_STRNLEN # define ACE_HAS_WCSNLEN // This is probably not a 100%-sure-fire check... Red Hat Linux 9 // and Enterprise Linux 3 and up have a new kernel that can send signals // across threads. This was not possible prior because there was no real // difference between a process and a thread. With this, the // ACE_POSIX_SIG_Proactor is the only chance of getting asynch I/O working. // There are restrictions, such as all socket operations being silently // converted to synchronous by the kernel, that make aio a non-starter // for most Linux platforms at this time. But we'll start to crawl... # define ACE_POSIX_SIG_PROACTOR # endif // To avoid the strangeness with Linux's ::select (), which modifies // its timeout argument, use ::poll () instead. # define ACE_HAS_POLL # define ACE_HAS_SIGINFO_T # define ACE_LACKS_SIGINFO_H # define ACE_HAS_UCONTEXT_T # define ACE_HAS_SIGTIMEDWAIT #else /* ! __GLIBC__ */ // Fixes a problem with some non-glibc versions of Linux... # define ACE_LACKS_MADVISE # define ACE_LACKS_MSG_ACCRIGHTS #endif /* ! __GLIBC__ */ #define ACE_HAS_LSEEK64 //#define ACE_LACKS_LSEEK64_PROTOTYPE #define ACE_HAS_P_READ_WRITE // Use ACE's alternate cuserid() implementation since the use of the // system cuserid() is discouraged. #define ACE_HAS_ALT_CUSERID #if (__GLIBC__ > 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3) # define ACE_HAS_ISASTREAM_PROTOTYPE # define ACE_HAS_PTHREAD_SIGMASK_PROTOTYPE # define ACE_HAS_CPU_SET_T #endif /* __GLIBC__ > 2 || __GLIBC__ === 2 && __GLIBC_MINOR__ >= 3) */ // Then the compiler specific parts #if defined (__INTEL_COMPILER) # include "ace/config-icc-common.h" #elif defined (__GNUG__) // config-g++-common.h undef's ACE_HAS_STRING_CLASS with -frepo, so // this must appear before its #include. # define ACE_HAS_STRING_CLASS # include "ace/config-g++-common.h" # ifdef __clang__ # undef ACE_HAS_GCC_ATOMIC_BUILTINS # endif #elif defined (__SUNCC_PRO) || defined (__SUNPRO_CC) # include "ace/config-suncc-common.h" #elif defined (__PGI) // Portable group compiler # define ACE_HAS_CPLUSPLUS_HEADERS # define ACE_HAS_STDCPP_STL_INCLUDES # define ACE_HAS_STANDARD_CPP_LIBRARY 1 # define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 # define ACE_LACKS_SWAB #elif defined (__GNUC__) /** * GNU C compiler. * * We need to recognize the GNU C compiler since TAO has at least one * C source header and file * (TAO/orbsvcs/orbsvcs/SSLIOP/params_dup.{h,c}) that may indirectly * include this */ #else /* ! __GNUG__ && !__DECCXX && !__INTEL_COMPILER && && !__PGI */ # ifdef __cplusplus /* Let it slide for C compilers. */ # error unsupported compiler in ace/config-linux.h # endif /* __cplusplus */ #endif /* ! __GNUG__*/ // Completely common part :-) // Platform/compiler has the sigwait(2) prototype #define ACE_HAS_SIGWAIT #define ACE_HAS_SIGSUSPEND #define ACE_HAS_UALARM #define ACE_HAS_STRSIGNAL #ifndef ACE_HAS_POSIX_REALTIME_SIGNALS # define ACE_HAS_POSIX_REALTIME_SIGNALS #endif /* ACE_HAS_POSIX_REALTIME_SIGNALS */ #define ACE_HAS_XPG4_MULTIBYTE_CHAR #define ACE_HAS_VFWPRINTF #define ACE_LACKS_ITOW #define ACE_LACKS_WCSICMP #define ACE_LACKS_WCSNICMP #define ACE_LACKS_ISWASCII #define ACE_HAS_3_PARAM_WCSTOK #define ACE_HAS_3_PARAM_READDIR_R #if !defined (ACE_DEFAULT_BASE_ADDR) # define ACE_DEFAULT_BASE_ADDR ((char *) 0x80000000) #endif /* ! ACE_DEFAULT_BASE_ADDR */ #define ACE_HAS_ALLOCA // Compiler/platform has <alloca.h> #define ACE_HAS_ALLOCA_H #define ACE_HAS_SYS_SYSINFO_H #define ACE_HAS_LINUX_SYSINFO // Compiler/platform has the getrusage() system call. #define ACE_HAS_GETRUSAGE #define ACE_HAS_GETRUSAGE_PROTOTYPE #define ACE_HAS_BYTESWAP_H #define ACE_HAS_BSWAP_16 #define ACE_HAS_BSWAP_32 #if defined (__GNUC__) # define ACE_HAS_BSWAP_64 #endif #define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES // Optimize ACE_Handle_Set for select(). #define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT // ONLY define this if you have config'd multicast into a 2.0.34 or // prior kernel. It is enabled by default in 2.0.35 kernels. #if !defined (ACE_HAS_IP_MULTICAST) # define ACE_HAS_IP_MULTICAST #endif /* ! ACE_HAS_IP_MULTICAST */ // At least for IPv4, Linux lacks perfect filtering. #if !defined ACE_LACKS_PERFECT_MULTICAST_FILTERING # define ACE_LACKS_PERFECT_MULTICAST_FILTERING 1 #endif /* ACE_LACKS_PERFECT_MULTICAST_FILTERING */ #define ACE_HAS_BIG_FD_SET // Linux defines struct msghdr in /usr/include/socket.h #define ACE_HAS_MSG // Linux "improved" the interface to select() so that it modifies // the struct timeval to reflect the amount of time not slept // (see NOTES in Linux's select(2) man page). #define ACE_HAS_NONCONST_SELECT_TIMEVAL #define ACE_DEFAULT_MAX_SOCKET_BUFSIZ 65535 #define ACE_CDR_IMPLEMENT_WITH_NATIVE_DOUBLE 1 #define ACE_HAS_GETPAGESIZE 1 // Platform defines struct timespec but not timespec_t #define ACE_LACKS_TIMESPEC_T // Platform supplies scandir() #define ACE_HAS_SCANDIR #if (__GLIBC__ < 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 10) // Although the scandir man page says otherwise, this setting is correct. // The setting was fixed in 2.10, so do not use the hack after that. #define ACE_SCANDIR_CMP_USES_CONST_VOIDPTR #endif // A conflict appears when including both <ucontext.h> and // <sys/procfs.h> with recent glibc headers. //#define ACE_HAS_PROC_FS // Platform supports System V IPC (most versions of UNIX, but not Win32) #define ACE_HAS_SYSV_IPC // Compiler/platform contains the <sys/syscall.h> file. #define ACE_HAS_SYS_SYSCALL_H // Platform/compiler supports global timezone variable. #define ACE_HAS_TIMEZONE #define ACE_HAS_TIMEZONE_GETTIMEOFDAY // Compiler supports the ssize_t typedef. #define ACE_HAS_SSIZE_T // Compiler/platform defines the sig_atomic_t typedef. #define ACE_HAS_SIG_ATOMIC_T // Compiler/platform defines a union semun for SysV shared memory. #define ACE_HAS_SEMUN #define ACE_HAS_POSIX_TIME #define ACE_HAS_GPERF #define ACE_HAS_DIRENT // Starting with FC9 rawhide this file is not available anymore but // this define is set #if defined _XOPEN_STREAMS && _XOPEN_STREAMS == -1 # define ACE_LACKS_STROPTS_H # define ACE_LACKS_STRRECVFD #endif #if !defined (ACE_LACKS_STROPTS_H) # define ACE_HAS_STRBUF_T #endif #if defined (__ia64) || defined(__alpha) || defined (__x86_64__) || defined(__powerpc64__) // On 64 bit platforms, the "long" type is 64-bits. Override the // default 32-bit platform-specific format specifiers appropriately. # define ACE_UINT64_FORMAT_SPECIFIER_ASCII "%lu" # define ACE_SSIZE_T_FORMAT_SPECIFIER_ASCII "%ld" # define ACE_SIZE_T_FORMAT_SPECIFIER_ASCII "%lu" #endif /* __ia64 */ #define ACE_SIZEOF_WCHAR 4 #if defined (__powerpc__) && !defined (ACE_SIZEOF_LONG_DOUBLE) // 32bit PowerPC Linux uses 128bit long double # define ACE_SIZEOF_LONG_DOUBLE 16 #endif #define ACE_LACKS_GETIPNODEBYADDR #define ACE_LACKS_GETIPNODEBYNAME // Platform has POSIX terminal interface. #define ACE_HAS_TERMIOS // Linux implements sendfile(). #define ACE_HAS_SENDFILE 1 #define ACE_HAS_VOIDPTR_MMAP #define ACE_HAS_ICMP_SUPPORT 1 #define ACE_HAS_VASPRINTF // According to man pages Linux uses different (compared to UNIX systems) types // for setting IP_MULTICAST_TTL and IPV6_MULTICAST_LOOP / IP_MULTICAST_LOOP // in setsockopt/getsockopt. #define ACE_HAS_IP_MULTICAST_TTL_AS_INT 1 #define ACE_HAS_IPV6_MULTICAST_LOOP_AS_BOOL 1 #define ACE_HAS_IP_MULTICAST_LOOP_AS_INT 1 #if defined (ACE_LACKS_NETWORKING) # include "ace/config-posix-nonetworking.h" #else # define ACE_HAS_NETLINK # define ACE_HAS_GETIFADDRS #endif #if !defined (ACE_GETNAME_RETURNS_RANDOM_SIN_ZERO) // Detect if getsockname() and getpeername() returns random values in // the sockaddr_in::sin_zero field by evaluation of the kernel // version. Since version 2.5.47 this problem is fixed. # if !defined (ACE_LACKS_LINUX_VERSION_H) # include <linux/version.h> # endif /* !ACE_LACKS_LINUX_VERSION_H */ # if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,47)) # define ACE_GETNAME_RETURNS_RANDOM_SIN_ZERO 0 # else # define ACE_GETNAME_RETURNS_RANDOM_SIN_ZERO 1 # endif /* (LINUX_VERSION_CODE <= KERNEL_VERSION(2,5,47)) */ #endif /* ACE_GETNAME_RETURNS_RANDOM_SIN_ZERO */ #if !defined (ACE_HAS_EVENT_POLL) && !defined (ACE_HAS_DEV_POLL) # if !defined (ACE_LACKS_LINUX_VERSION_H) # include <linux/version.h> # endif /* !ACE_LACKS_LINUX_VERSION_H */ # if (LINUX_VERSION_CODE > KERNEL_VERSION (2,6,0)) # define ACE_HAS_EVENT_POLL # endif #endif #define ACE_HAS_SVR4_DYNAMIC_LINKING #define ACE_HAS_AUTOMATIC_INIT_FINI #define ACE_HAS_DLSYM_SEGFAULT_ON_INVALID_HANDLE #define ACE_HAS_RECURSIVE_MUTEXES #define ACE_HAS_THREAD_SPECIFIC_STORAGE #define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS #define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R #define ACE_HAS_REENTRANT_FUNCTIONS // To support UCLIBC #if defined (__UCLIBC__) # define ACE_LACKS_STROPTS_H # define ACE_LACKS_GETLOADAVG # define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS # define ACE_LACKS_PTHREAD_SETSTACK # define ACE_LACKS_STRRECVFD # define ACE_HAS_CPU_SET_T # if defined (ACE_HAS_STRBUF_T) # undef ACE_HAS_STRBUF_T # endif /* ACE_HAS_STRBUF_T */ # if defined (ACE_HAS_PTHREAD_SETSTACK) # undef ACE_HAS_PTHREAD_SETSTACK # endif /* ACE_HAS_PTHREAD_SETSTACK */ # if defined (ACE_HAS_AIO_CALLS) # undef ACE_HAS_AIO_CALLS # endif /* ACE_HAS_AIO_CALLS */ # if defined (ACE_HAS_GETIFADDRS) # undef ACE_HAS_GETIFADDRS # endif /* ACE_HAS_GETIFADDRS */ # if defined (ACE_SCANDIR_CMP_USES_VOIDPTR) # undef ACE_SCANDIR_CMP_USES_VOIDPTR # endif /* ACE_SCANDIR_CMP_USES_VOIDPTR */ # if defined (ACE_SCANDIR_CMP_USES_CONST_VOIDPTR) # undef ACE_SCANDIR_CMP_USES_CONST_VOIDPTR # endif /* ACE_SCANDIR_CMP_USES_CONST_VOIDPTR */ # if defined (ACE_HAS_EXECINFO_H) # undef ACE_HAS_EXECINFO_H # endif /* ACE_HAS_EXECINFO_H */ # if defined(__GLIBC__) # undef __GLIBC__ # endif /* __GLIBC__ */ # if defined(ACE_HAS_SEMUN) # undef ACE_HAS_SEMUN # endif /* ACE_HAS_SEMUN */ #endif /* __UCLIBC__ */ #include /**/ "ace/post.h" #endif /* ACE_CONFIG_LINUX_H */
{ "language": "C" }
/* * This file is part of GreatFET * Pins for the CCCamp 2015 rad1o badge. */ #ifndef __RAD1O_PINS_H #define __RAD1O_PINS_H #include <gpio_lpc.h> #include <libopencm3/lpc43xx/scu.h> /* * SCU PinMux */ /* GPIO Output PinMux */ #define NUM_LEDS 4 #define SCU_PINMUX_LED1 (P4_1) /* GPIO2[1] */ #define SCU_PINMUX_LED2 (P4_2) /* GPIO2[2] */ #define SCU_PINMUX_LED3 (P6_12) /* GPIO2[8] */ #define SCU_PINMUX_LED4 (PB_6) /* GPIO5[26] */ #define PIN_LED1 (1) #define PIN_LED2 (2) #define PIN_LED3 (8) #define PIN_LED4 (26) #define PORT_LED1 (2) #define PORT_LED2 (2) #define PORT_LED3 (2) #define PORT_LED4 (5) /* GPIO Output PinMux */ static const struct gpio_t gpio_led[NUM_LEDS] = { GPIO(PORT_LED1, PIN_LED1), GPIO(PORT_LED2, PIN_LED2), GPIO(PORT_LED3, PIN_LED3), GPIO(PORT_LED4, PIN_LED4) }; static const scu_grp_pin_t pinmux_led[NUM_LEDS] = { SCU_PINMUX_LED1, SCU_PINMUX_LED2, SCU_PINMUX_LED3, SCU_PINMUX_LED4 }; static const scu_grp_pin_t scu_type_led[NUM_LEDS] = { SCU_GPIO_NOPULL | SCU_CONF_FUNCTION0, SCU_GPIO_NOPULL | SCU_CONF_FUNCTION0, SCU_GPIO_NOPULL | SCU_CONF_FUNCTION0, SCU_GPIO_NOPULL | SCU_CONF_FUNCTION4, }; /* GPIO Input PinMux */ #define SCU_PINMUX_BOOT0 (P1_1) /* GPIO0[8] on P1_1 */ #define SCU_PINMUX_BOOT1 (P1_2) /* GPIO0[9] on P1_2 */ #define SCU_PINMUX_BOOT2 (P2_8) /* GPIO5[7] on P2_8 */ #define SCU_PINMUX_BOOT3 (P2_9) /* GPIO1[10] on P2_9 */ /* SSP1 Peripheral PinMux */ #define SCU_SSP1_MISO (P1_3) /* P1_3 */ #define SCU_SSP1_MOSI (P1_4) /* P1_4 */ #define SCU_SSP1_SCK (P1_19) /* P1_19 */ #define SCU_SSP1_SSEL (P1_20) /* P1_20 */ /* JTAG interface */ #define SCU_PINMUX_TDO (P9_5) /* GPIO5[18] */ #define SCU_PINMUX_TCK (P6_1) /* GPIO3[ 0] */ #define SCU_PINMUX_TMS (P6_5) /* GPIO3[ 4] */ #define SCU_PINMUX_TDI (P6_2) /* GPIO3[ 1] */ /* CPLD SGPIO interface */ #define SCU_PINMUX_SGPIO0 (P0_0) #define SCU_PINMUX_SGPIO1 (P0_1) #define SCU_PINMUX_SGPIO2 (P1_15) #define SCU_PINMUX_SGPIO3 (P1_16) #define SCU_PINMUX_SGPIO4 (P6_3) #define SCU_PINMUX_SGPIO5 (P6_6) #define SCU_PINMUX_SGPIO6 (P2_2) #define SCU_PINMUX_SGPIO7 (P1_0) #define SCU_PINMUX_SGPIO8 (P9_6) #define SCU_PINMUX_SGPIO9 (P4_3) #define SCU_PINMUX_SGPIO10 (P1_14) #define SCU_PINMUX_SGPIO11 (P1_17) #define SCU_PINMUX_SGPIO12 (P1_18) #define SCU_PINMUX_SGPIO13 (P4_8) #define SCU_PINMUX_SGPIO14 (P4_9) #define SCU_PINMUX_SGPIO15 (P4_10) /* SPI flash */ #define SCU_SSP0_MISO (P3_6) #define SCU_SSP0_MOSI (P3_7) #define SCU_SSP0_SCK (P3_3) #define SCU_SSP0_SSEL (P3_8) /* GPIO5[11] on P3_8 */ #define SCU_FLASH_HOLD (P3_4) /* GPIO1[14] on P3_4 */ #define SCU_FLASH_WP (P3_5) /* GPIO1[15] on P3_5 */ /* Pin locations for the onboard SPI flash. */ static const struct gpio_t gpio_onboard_flash_hold = GPIO(1, 14); static const struct gpio_t gpio_onboard_flash_wp = GPIO(1, 15); static const struct gpio_t gpio_onboard_flash_select = GPIO(5, 11); #define ONBOARD_FLASH_DEVICE_ID 0x14 /* Expected device_id for W25Q16DV */ #define ONBOARD_FLASH_PAGE_LEN 256U #define ONBOARD_FLASH_NUM_PAGES 8192U #define ONBOARD_FLASH_NUM_BYTES (ONBOARD_FLASH_PAGE_LEN * ONBOARD_FLASH_NUM_PAGES) /* TODO add other Pins */ #define SCU_PINMUX_GPIO0_10 (P1_3) /* GPIO0[10] */ #define SCU_PINMUX_GPIO0_11 (P1_4) /* GPIO0[11] */ #define SCU_PINMUX_GPIO0_15 (P1_20) /* GPIO0[15] */ #define SCU_PINMUX_GPIO1_14 (P3_4) /* GPIO1[14] */ #define SCU_PINMUX_GPIO2_2 (P4_2) /* GPIO2[2] */ #define SCU_PINMUX_GPIO2_3 (P4_3) /* GPIO2[3] */ #define SCU_PINMUX_GPIO3_8 (P7_0) /* GPIO3[8] */ #define SCU_PINMUX_GPIO3_9 (P7_1) /* GPIO3[9] */ #define SCU_PINMUX_GPIO3_10 (P7_2) /* GPIO3[10] */ #define SCU_PINMUX_GPIO3_11 (P7_3) /* GPIO3[11] */ #define SCU_PINMUX_GPIO3_12 (P7_4) /* GPIO3[12] */ #define SCU_PINMUX_GPIO3_13 (P7_5) /* GPIO3[13] */ #define SCU_PINMUX_GPIO3_14 (P7_6) /* GPIO3[14] */ #define SCU_PINMUX_GPIO3_15 (P7_7) /* GPIO3[15] */ #define SCU_PINMUX_GPIO5_3 (P2_3) /* GPIO5[3] */ #define SCU_PINMUX_GPIO5_5 (P2_5) /* GPIO5[5] */ #define SCU_PINMUX_GPIO5_8 (P3_1) /* GPIO5[8] */ #define SCU_PINMUX_SD_POW (P1_5) /* GPIO1[8] */ #define SCU_PINMUX_SD_CMD (P1_6) /* GPIO1[9] */ #define SCU_PINMUX_SD_VOLT0 (P1_8) /* GPIO1[1] */ #define SCU_PINMUX_SD_DAT0 (P1_9) /* GPIO1[2] */ #define SCU_PINMUX_SD_DAT1 (P1_10) /* GPIO1[3] */ #define SCU_PINMUX_SD_DAT2 (P1_11) /* GPIO1[4] */ #define SCU_PINMUX_SD_DAT3 (P1_12) /* GPIO1[5] */ #define SCU_PINMUX_SD_CD (P1_13) /* GPIO1[6] */ #define SCU_PINMUX_U0_TXD (P2_0) /* GPIO5[0] */ #define SCU_PINMUX_U0_RXD (P2_1) /* GPIO5[1] */ #define SCU_PINMUX_ISP (P2_7) /* GPIO0[7] */ #define SCU_PINMUX_GP_CLKIN (P4_7) /* Use the large, red LED as the heartbeat indicator. */ #define HEARTBEAT_LED LED4 #endif /* __RAD1O_PINS_H */
{ "language": "C" }
/* ********************************************************** * Copyright (c) 2010-2017 Google, Inc. All rights reserved. * Copyright (c) 2008-2010 VMware, Inc. All rights reserved. * **********************************************************/ /* Dr. Memory: the memory debugger * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License, and no later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /*************************************************************************** * spill.c: Dr. Memory scratch register spilling */ #include "dr_api.h" #include "drreg.h" #include "utils.h" #include "client_per_thread.h" #include "options.h" #include "spill.h" #include "instru.h" #include "slowpath.h" #include "replace.h" #include "shadow.h" #include "fastpath.h" #include <stddef.h> /* offsetof */ /*************************************************************************** * We allocate our own register spill slots for faster access than * the non-directly-addressable DR slots (only 3 are direct). */ /* Indirection to allow us to switch which TLS slots we use for spill slots */ #define MAX_FAST_DR_SPILL_SLOT SPILL_SLOT_3 /* We used to store segment bases in some TLS slots that were followed by the * reg spill slots, but now that DR has API support for bases we don't need them * anymore: */ #define NUM_INSTRU_TLS_SLOTS 0 /* drreg allocates our reg spill slots in pattern mode */ #define NUM_TLS_SLOTS \ (NUM_INSTRU_TLS_SLOTS + (options.pattern == 0 ? options.num_spill_slots : 0)) reg_id_t seg_tls; /* the offset of our tls_instr_t + reg spill tls slots */ static uint tls_instru_base; /* we store a pointer in regular tls for access to other threads' TLS */ static int tls_idx_instru = -1; byte * get_own_seg_base(void) { #ifdef WINDOWS return (byte *) get_TEB(); #else return dr_get_dr_segment_base(seg_tls); #endif } static bool handle_drreg_error(drreg_status_t status) { ASSERT(false, "drreg bb event failure"); /* XXX: can we share the tool crash message? */ NOTIFY_ERROR("FATAL ERROR: internal register failure %d: please report this", status); dr_abort(); return true; /* we handled it */ } void instru_tls_init(void) { if (options.pattern != 0) { drreg_options_t ops = { sizeof(ops), options.num_spill_slots, options.conservative, handle_drreg_error, }; IF_DEBUG(drreg_status_t res =) drreg_init(&ops); ASSERT(res == DRREG_SUCCESS, "fatal error: failed to initialize drreg"); } if (NUM_TLS_SLOTS > 0) { IF_DEBUG(bool ok =) dr_raw_tls_calloc(&seg_tls, &tls_instru_base, NUM_TLS_SLOTS, 0); ASSERT(ok, "fatal error: unable to reserve tls slots"); LOG(2, "TLS spill base: "PIFX"\n", tls_instru_base); tls_idx_instru = drmgr_register_tls_field(); ASSERT(tls_idx_instru > -1, "failed to reserve TLS slot"); ASSERT(seg_tls == EXPECTED_SEG_TLS, "unexpected tls segment"); } else { /* We still need the seg base. * XXX: DR should provide an API to retrieve it w/o allocating slots! */ if (dr_raw_tls_calloc(&seg_tls, &tls_instru_base, 1, 0)) { dr_raw_tls_cfree(tls_instru_base, 1); } else { /* Fall back to hardcoded defaults */ #ifdef X86 # ifdef X64 seg_tls = DR_SEG_GS; # else seg_tls = DR_SEG_FS; # endif #elif defined(ARM) # ifdef X64 seg_tls = DR_REG_TPIDRURO; # else seg_tls = DR_REG_TPIDRURW; # endif #endif } } } void instru_tls_exit(void) { if (NUM_TLS_SLOTS > 0) { IF_DEBUG(bool ok =) dr_raw_tls_cfree(tls_instru_base, NUM_TLS_SLOTS); ASSERT(ok, "WARNING: unable to free tls slots"); drmgr_unregister_tls_field(tls_idx_instru); } if (options.pattern != 0) { IF_DEBUG(drreg_status_t res =) drreg_exit(); ASSERT(res == DRREG_SUCCESS, "WARNING: drreg failed on exit"); } } void instru_tls_thread_init(void *drcontext) { #ifdef UNIX /* We used to acquire the app's fs and gs bases (via opnd_compute address on * a synthetic far-base-disp opnd) but with early injection they aren't set * up yet, and we'd need to do work to handle changes: instead, now that * DR supplies dr_insert_get_seg_base(), we just use that. */ LOG(1, "dr: TLS base="PFX"\n", dr_get_dr_segment_base(seg_tls)); #endif if (NUM_TLS_SLOTS > 0) { /* store in per-thread data struct so we can access from another thread */ drmgr_set_tls_field(drcontext, tls_idx_instru, (void *) (get_own_seg_base() + tls_instru_base)); } } void instru_tls_thread_exit(void *drcontext) { if (NUM_TLS_SLOTS > 0) drmgr_set_tls_field(drcontext, tls_idx_instru, NULL); } uint num_own_spill_slots(void) { return options.num_spill_slots; } static opnd_t opnd_create_own_spill_slot(uint index) { ASSERT(index < options.num_spill_slots, "spill slot index overflow"); ASSERT(INSTRUMENT_MEMREFS(), "incorrectly called"); return opnd_create_far_base_disp_ex /* must use 0 scale to match what DR decodes for opnd_same */ (seg_tls, REG_NULL, REG_NULL, 0, tls_instru_base + (NUM_INSTRU_TLS_SLOTS + index)*sizeof(ptr_uint_t), OPSZ_PTR, /* we do NOT want an addr16 prefix since most likely going to run on * Core or Core2, and P4 doesn't care that much */ false, true, false); } ptr_uint_t get_own_tls_value(uint index) { ASSERT(NUM_TLS_SLOTS > 0, "should not get here if we have no slots"); if (index < options.num_spill_slots) { byte *seg_base = get_own_seg_base(); return *(ptr_uint_t *) (seg_base + tls_instru_base + (NUM_INSTRU_TLS_SLOTS + index)*sizeof(ptr_uint_t)); } else { dr_spill_slot_t DR_slot = index - options.num_spill_slots; return dr_read_saved_reg(dr_get_current_drcontext(), DR_slot); } } void set_own_tls_value(uint index, ptr_uint_t val) { ASSERT(NUM_TLS_SLOTS > 0, "should not get here if we have no slots"); if (index < options.num_spill_slots) { byte *seg_base = get_own_seg_base(); *(ptr_uint_t *)(seg_base + tls_instru_base + (NUM_INSTRU_TLS_SLOTS + index)*sizeof(ptr_uint_t)) = val; } else { dr_spill_slot_t DR_slot = index - options.num_spill_slots; dr_write_saved_reg(dr_get_current_drcontext(), DR_slot, val); } } ptr_uint_t get_thread_tls_value(void *drcontext, uint index) { ASSERT(NUM_TLS_SLOTS > 0, "should not get here if we have no slots"); if (index < options.num_spill_slots) { byte *tls = (byte *) drmgr_get_tls_field(drcontext, tls_idx_instru); return *(ptr_uint_t *) (tls + (NUM_INSTRU_TLS_SLOTS + index)*sizeof(ptr_uint_t)); } else { dr_spill_slot_t DR_slot = index - options.num_spill_slots; return dr_read_saved_reg(drcontext, DR_slot); } } void set_thread_tls_value(void *drcontext, uint index, ptr_uint_t val) { ASSERT(NUM_TLS_SLOTS > 0, "should not get here if we have no slots"); if (index < options.num_spill_slots) { byte *tls = (byte *) drmgr_get_tls_field(drcontext, tls_idx_instru); *(ptr_uint_t *) (tls + (NUM_INSTRU_TLS_SLOTS + index)*sizeof(ptr_uint_t)) = val; } else { dr_spill_slot_t DR_slot = index - options.num_spill_slots; dr_write_saved_reg(drcontext, DR_slot, val); } } ptr_uint_t get_raw_tls_value(uint offset) { #ifdef X86 ptr_uint_t val; # ifdef WINDOWS val = *(ptr_uint_t *)(((byte *)get_TEB()) + offset); # else # ifdef X64 asm("movzbq %0, %%"ASM_XAX : : "m"(offset) : ASM_XAX); # else asm("movzbl %0, %%"ASM_XAX : : "m"(offset) : ASM_XAX); # endif asm("mov %%"ASM_SEG":(%%"ASM_XAX"), %%"ASM_XAX : : : ASM_XAX); asm("mov %%"ASM_XAX", %0" : "=m"(val) : : ASM_XAX); # endif return val; #else /* FIXME i#1726: port to ARM */ ASSERT_NOT_REACHED(); return 0; #endif } int spill_reg3_slot(bool eflags_dead, bool eax_dead, bool r1_dead, bool r2_dead) { if (whole_bb_spills_enabled()) return SPILL_SLOT_4; if (eflags_dead || eax_dead) return SPILL_SLOT_EFLAGS_EAX; /* we can only use slots 1 and 2 if no spill or xchg, since for xchg * we restore and then use the tls slot for slowpath param, so truly * if r1/r2 is dead. even then we must restore reg3 first in slowpath prefix * before we move param into tls slot. */ if (r1_dead) return SPILL_SLOT_1; if (r2_dead) return SPILL_SLOT_2; return SPILL_SLOT_4; } void spill_reg(void *drcontext, instrlist_t *ilist, instr_t *where, reg_id_t reg, dr_spill_slot_t slot) { ASSERT(options.pattern == 0, "not converted to drreg yet"); if (slot < options.num_spill_slots) { STATS_INC(reg_spill_own); PRE(ilist, where, XINST_CREATE_store(drcontext, opnd_create_own_spill_slot(slot), opnd_create_reg(reg))); } else { dr_spill_slot_t DR_slot = slot - options.num_spill_slots; #ifdef STATISTICS if (DR_slot > MAX_FAST_DR_SPILL_SLOT) STATS_INC(reg_spill_slow); #endif dr_save_reg(drcontext, ilist, where, reg, DR_slot); } } void restore_reg(void *drcontext, instrlist_t *ilist, instr_t *where, reg_id_t reg, dr_spill_slot_t slot) { ASSERT(options.pattern == 0, "not converted to drreg yet"); if (slot < options.num_spill_slots) { PRE(ilist, where, XINST_CREATE_load(drcontext, opnd_create_reg(reg), opnd_create_own_spill_slot(slot))); } else { dr_spill_slot_t DR_slot = slot - options.num_spill_slots; dr_restore_reg(drcontext, ilist, where, reg, DR_slot); } } opnd_t spill_slot_opnd(void *drcontext, dr_spill_slot_t slot) { ASSERT(options.pattern == 0, "not converted to drreg yet"); if (slot < options.num_spill_slots) { return opnd_create_own_spill_slot(slot); } else { dr_spill_slot_t DR_slot = slot - options.num_spill_slots; return dr_reg_spill_slot_opnd(drcontext, DR_slot); } } static bool is_spill_slot_opnd(void *drcontext, opnd_t op) { static uint offs_min_own, offs_max_own, offs_min_DR, offs_max_DR; if (offs_max_DR == 0) { offs_min_own = opnd_get_disp(opnd_create_own_spill_slot(0)); offs_max_own = opnd_get_disp(opnd_create_own_spill_slot (options.num_spill_slots - 1)); offs_min_DR = opnd_get_disp(dr_reg_spill_slot_opnd(drcontext, SPILL_SLOT_1)); offs_max_DR = opnd_get_disp(dr_reg_spill_slot_opnd (drcontext, dr_max_opnd_accessible_spill_slot())); } if (opnd_is_far_base_disp(op) && opnd_get_index(op) == REG_NULL && opnd_get_segment(op) == seg_tls) { uint offs = opnd_get_disp(op); if (offs >= offs_min_own && offs <= offs_max_own) return true; if (offs >= offs_min_DR && offs <= offs_max_DR) return true; } return false; } /*************************************************************************** * STATE RESTORATION */ /* Our state restoration model for non-pattern, until we transition * them to use drreg as well (i#1795): only whole-bb scratch regs and aflags * need to be restored (i.e., all local scratch regs are restored * before any app instr). For each such reg or aflags, we guarantee * that either the app value is in TLS at each app instr (where fault * might happen) or the app value is dead and it's ok to have garbage * in TLS b/c the app will write it before reading (this is all modulo * the app's own fault handler going off on a different path (xref * DRi#400): so we're slightly risky here). * * We also perform a few other shadow-related restorations at the end * of this routine. */ bool event_restore_state(void *drcontext, bool restore_memory, dr_restore_state_info_t *info) { bool shadow_write = false; instr_t inst; uint memopidx; bool write; byte *addr; /* If always app_code_consistent could just re-analyze aflags, but not * the case so we have to store whether we've done eflags-at-top */ #ifdef X86 /* XXX PR 485216: we should restore dead registers on a fault, but it * would be a perf hit to save them: for now we don't do anything. * It's doubtful an app will ever have a problem with that. */ bb_saved_info_t *save; #endif #ifdef TOOL_DR_MEMORY cls_drmem_t *cpt = (cls_drmem_t *) drmgr_get_cls_field(drcontext, cls_idx_drmem); ASSERT(cpt != NULL, "cpt shouldn't be null"); if (!INSTRUMENT_MEMREFS()) return true; if (options.pattern != 0) /* pattern is using drreg */ return true; /* Are we asking DR to translate just pc? Then return true and ignore regs */ if (cpt->self_translating) { ASSERT(options.verbose >= 3, "only used for -verbose 3+"); return true; } #endif #ifdef X86 /* ARM uses drreg's state restoration */ hashtable_lock(&bb_table); save = (bb_saved_info_t *) hashtable_lookup(&bb_table, info->fragment_info.tag); # ifdef TOOL_DR_MEMORY LOG(2, "%s: raw pc="PFX", xl8 pc="PFX", tag="PFX"\n", __FUNCTION__, info->raw_mcontext->pc, info->mcontext->pc, info->fragment_info.tag); DOLOG(2, { /* We leave the translation as being in our own library, since no * other good alternative. We document this to users. */ if (in_replace_routine(info->mcontext->pc)) LOG(2, "fault in replace_ routine "PFX"\n", info->mcontext->pc); }); # endif if (save != NULL) { /* We save first thing and restore prior to last instr. * Our restore clobbers the eflags value in our tls slot, so * on a fault in the last instr we should do nothing. * FIXME: NOT ENOUGH TESTED: * need carefully constructed tests like tests/state.c */ if (info->mcontext->pc != save->last_instr && /* i#1466: only restore after first_restore_pc */ info->mcontext->pc >= save->first_restore_pc) { /* Use drcontext's shadow, not executing thread's shadow! (PR 475211) */ ptr_uint_t regval; if (save->eflags_saved) { IF_DEBUG(ptr_uint_t orig_flags = info->mcontext->xflags;) uint sahf; regval = save->aflags_in_eax ? info->raw_mcontext->xax : get_thread_tls_value(drcontext, SPILL_SLOT_EFLAGS_EAX); sahf = (regval & 0xff00) >> 8; info->mcontext->xflags &= ~0xff; info->mcontext->xflags |= sahf; if (TEST(1, regval)) /* from "seto al" */ info->mcontext->xflags |= EFLAGS_OF; LOG(2, "translated eflags from "PFX" to "PFX"\n", orig_flags, info->mcontext->xflags); } /* Restore whole-bb spilled registers (PR 489221). Note that * now we're closer to being able to restore app state at any * point: but we still don't have any local 3rd scratch reg * recorded. */ if (save->scratch1 != REG_NULL) { regval = get_thread_tls_value(drcontext, SPILL_SLOT_1); LOG(2, "restoring per-bb %s to "PFX"\n", get_register_name(save->scratch1), regval); reg_set_value(save->scratch1, info->mcontext, regval); } if (save->scratch2 != REG_NULL) { regval = get_thread_tls_value(drcontext, SPILL_SLOT_2); LOG(2, "restoring per-bb %s to "PFX"\n", get_register_name(save->scratch2), regval); reg_set_value(save->scratch2, info->mcontext, regval); } if (save->aflags_in_eax) { regval = get_thread_tls_value(drcontext, SPILL_SLOT_5); LOG(2, "restoring %s to "PFX"\n", get_register_name(DR_REG_XAX), regval); reg_set_value(DR_REG_XAX, info->mcontext, regval); } } } hashtable_unlock(&bb_table); #endif /* X86 */ #ifndef TOOL_DR_MEMORY /* Dr. Heapstat has no fault paths */ return true; #endif /* Note that although we now have non-meta instrumentation that * comes through here for PR 448701 we do not restore registers * here since no such fault will make it to the app. * PR 480208: we do need to restore for a thread relocation. For now we * return false to force thread suspension elsewhere (b/c we can't relocate * for the 1st of our two-part sub-dword dst write), if the translation is * targeting our own meta-may-fault instr, which will always be a write to * shadow memory == DR memory. */ if (!info->raw_mcontext_valid) { ASSERT(false, "should always have raw_mcontext"); return true; } instr_init(drcontext, &inst); decode(drcontext, info->raw_mcontext->pc, &inst); ASSERT(instr_valid(&inst), "unknown translation instr"); DOLOG(3, { LOG(3, "considering to-be-translated instr: "); instr_disassemble(drcontext, &inst, LOGFILE_GET(drcontext)); LOG(3, "\n"); }); for (memopidx = 0; instr_compute_address_ex(&inst, info->raw_mcontext, memopidx, &addr, &write); memopidx++) { if (write && dr_memory_is_dr_internal(addr)) { shadow_write = true; break; } } instr_free(drcontext, &inst); if (shadow_write) { /* An app write to a random address could fool us, but shouldn't be * a problem: DR will just suspend somewhere else. */ if (!restore_memory) { /* We could move the state restoration code from * handle_special_shadow_fault() to here and return true, except * we'd also have to change our two-part sub-dword dst write to get * the final value in a reg before committing. So, we return false, * and only restore the state when we need to determine the app's * mem address for a real fault. */ LOG(1, "failing non-fault translation\n"); return false; } /* else, it must be our own special-shadow fault, handled by our * signal/exception events below */ } #ifdef TOOL_DR_MEMORY else if (restore_memory && cpt->mem2fpmm_source != NULL) { /* Our i#471 heuristic could end up with a thread relocation in between * the fld and the fstp. In such a case we restore the shadow. */ umbra_shadow_memory_info_t info; shadow_set_byte(&info, cpt->mem2fpmm_dest, cpt->mem2fpmm_prev_shadow); cpt->mem2fpmm_source = NULL; } #endif return true; } /*************************************************************************** * SCRATCH REGISTER SELECTION */ #ifdef X86 /* ARM uses drreg's state restoration */ # ifdef DEBUG static void print_scratch_reg(void *drcontext, scratch_reg_info_t *si, int num, file_t file) { dr_fprintf(file, "r%d=", num); opnd_disassemble(drcontext, opnd_create_reg(si->reg), file); if (si->xchg != REG_NULL) { dr_fprintf(file, " xchg "); opnd_disassemble(drcontext, opnd_create_reg(si->xchg), file); } else if (si->dead) { dr_fprintf(file, " dead"); } else { dr_fprintf(file, "spill#%d", si->slot); } } static void check_scratch_reg_no_overlap(scratch_reg_info_t *s1, scratch_reg_info_t *s2) { ASSERT(s1->reg != s2->reg, "scratch reg error"); ASSERT(s1->xchg != s2->reg, "scratch reg error"); ASSERT(s2->xchg != s1->reg, "scratch reg error"); /* if both are using slots (no xchg, not dead) then make sure they differ */ ASSERT(s1->xchg != REG_NULL || s2->xchg != REG_NULL || s1->dead || s2->dead || s1->slot != s2->slot, "scratch reg error"); } # endif /* DEBUG */ /* It's up to the caller to ensure that fixed was not already chosen * for an earlier scratch reg */ static void pick_scratch_reg_helper(fastpath_info_t *mi, scratch_reg_info_t *si, int live[NUM_LIVENESS_REGS], bool only_abcd, reg_id_t fixed, int slot, opnd_t no_overlap1, opnd_t no_overlap2) { int nxt_dead; for (nxt_dead = 0; nxt_dead < NUM_LIVENESS_REGS; nxt_dead++) { if (live[nxt_dead] == LIVE_DEAD) break; } si->global = false; /* FIXME PR 463053: we're technically being a little unsafe here: * even if a register is dead on the normal path, if a fault * can occur before the register is written to, we should * restore its value in the fault handler. Pretty pathological * so for now we ignore it, given that we have larger problems * and we need the speed. */ if (nxt_dead < NUM_LIVENESS_REGS && (!only_abcd || nxt_dead <= DR_REG_XBX - REG_START) && !opnd_uses_reg(no_overlap1, REG_START + nxt_dead) && !opnd_uses_reg(no_overlap2, REG_START + nxt_dead) && /* do not pick local reg that overlaps w/ whole-bb reg */ REG_START + nxt_dead != mi->bb->reg1.reg && REG_START + nxt_dead != mi->bb->reg2.reg) { /* we can use it directly */ si->reg = REG_START + nxt_dead; si->xchg = REG_NULL; si->dead = true; STATS_INC(reg_dead); live[nxt_dead] = LIVE_LIVE; } else if (nxt_dead < NUM_LIVENESS_REGS && /* FIXME OPT: if we split the spills up we could use xchg for * reg2 or reg3 even if not for reg1 */ !opnd_uses_reg(no_overlap1, REG_START + nxt_dead) && !opnd_uses_reg(no_overlap2, REG_START + nxt_dead) && !opnd_uses_reg(no_overlap1, fixed) && !opnd_uses_reg(no_overlap2, fixed) && /* do not pick local reg that overlaps w/ whole-bb reg */ REG_START + nxt_dead != mi->bb->reg1.reg && REG_START + nxt_dead != mi->bb->reg2.reg) { /* pick fixed reg and xchg for it */ si->reg = fixed; si->xchg = REG_START + nxt_dead; si->dead = false; STATS_INC(reg_xchg); live[nxt_dead] = LIVE_LIVE; } else { /* pick fixed reg and spill it */ si->reg = fixed; si->xchg = REG_NULL; si->dead = false; si->slot = slot; STATS_INC(reg_spill); } } /* Chooses scratch registers and sets liveness and eflags info * If mi->eax.used is set, does NOT determine how to spill eax based * on eflags and does NOT use the SPILL_SLOT_EFLAGS_EAX unless eflags * is dead. */ void pick_scratch_regs(instr_t *inst, fastpath_info_t *mi, bool only_abcd, bool need3, bool reg3_must_be_ecx, opnd_t no_overlap1, opnd_t no_overlap2) { int nxt_dead; int live[NUM_LIVENESS_REGS]; /* Slots for additional local regs, when using whole-bb slots 1 and 2 * for regs and slot 3 (SPILL_SLOT_EFLAGS_EAX) for eflags */ int local_slot[] = {SPILL_SLOT_4, SPILL_SLOT_5}; int local_idx = 0; IF_DEBUG(const int local_idx_max = sizeof(local_slot)/sizeof(local_slot[0]);) mi->aflags = get_aflags_and_reg_liveness(inst, live, false/* regs too */); ASSERT((whole_bb_spills_enabled() && mi->bb->reg1.reg != REG_NULL) || (!whole_bb_spills_enabled() && mi->bb->reg1.reg == REG_NULL), "whole_bb_spills_enabled() should correspond to reg1,reg2 being set"); /* don't pick esp since it can't be an index register */ live[DR_REG_XSP - REG_START] = LIVE_LIVE; if (mi->eax.used) { /* caller wants us to ignore eax and eflags */ } else if (!whole_bb_spills_enabled() && mi->aflags != EFLAGS_WRITE_ARITH) { mi->eax.reg = DR_REG_XAX; mi->eax.used = true; mi->eax.dead = (live[DR_REG_XAX - REG_START] == LIVE_DEAD); /* Ensure we don't use eax for another scratch reg */ if (mi->eax.dead) { live[DR_REG_XAX - REG_START] = LIVE_LIVE; STATS_INC(reg_dead); } else STATS_INC(reg_spill); /* we do not try to xchg instead of spilling as that would complicate * shared_slowpath, spill_reg3_slot, etc. */ mi->eax.xchg = REG_NULL; mi->eax.slot = SPILL_SLOT_EFLAGS_EAX; mi->eax.global = false; } else mi->eax.used = false; /* Up to 3 scratch regs (beyond eax for eflags) need to be from * ecx, edx, ebx so we can reference low and high 8-bit sub-regs */ mi->reg1.used = false; /* set later */ mi->reg2.used = false; /* set later */ mi->reg3.used = false; /* set later */ if (need3) { if (reg3_must_be_ecx && mi->bb->reg1.reg == DR_REG_XCX) { mi->reg3 = mi->bb->reg1; mi->reg3.dead = (live[mi->reg3.reg - REG_START] == LIVE_DEAD); } else if (reg3_must_be_ecx && mi->bb->reg2.reg == DR_REG_XCX) { mi->reg3 = mi->bb->reg2; mi->reg3.dead = (live[mi->reg3.reg - REG_START] == LIVE_DEAD); } else if (reg3_must_be_ecx && only_abcd) { /* instrument_fastpath requires reg3 to be ecx since we have * to use cl for OP_shl var op. */ mi->reg3.reg = DR_REG_XCX; mi->reg3.dead = (live[mi->reg3.reg - REG_START] == LIVE_DEAD); mi->reg3.global = false; /* Ensure we don't use for another scratch reg */ live[mi->reg3.reg - REG_START] = LIVE_LIVE; if (!mi->reg3.dead) { for (nxt_dead = 0; nxt_dead < NUM_LIVENESS_REGS; nxt_dead++) { if (live[nxt_dead] == LIVE_DEAD) break; } if (nxt_dead < NUM_LIVENESS_REGS && !opnd_uses_reg(no_overlap1, REG_START + nxt_dead) && !opnd_uses_reg(no_overlap2, REG_START + nxt_dead) && !opnd_uses_reg(no_overlap1, mi->reg3.reg) && !opnd_uses_reg(no_overlap2, mi->reg3.reg) && /* we can't xchg with what we'll use for reg1 or reg2 */ REG_START + nxt_dead != DR_REG_XDX && REG_START + nxt_dead != DR_REG_XBX && /* do not pick local reg that overlaps w/ whole-bb reg */ REG_START + nxt_dead != mi->bb->reg1.reg && REG_START + nxt_dead != mi->bb->reg2.reg) { mi->reg3.xchg = REG_START + nxt_dead; live[nxt_dead] = LIVE_LIVE; STATS_INC(reg_xchg); } else { mi->reg3.slot = spill_reg3_slot(mi->aflags == EFLAGS_WRITE_ARITH, !mi->eax.used || mi->eax.dead, /* later we'll update these */ false, false); STATS_INC(reg_spill); } } else STATS_INC(reg_dead); } else { pick_scratch_reg_helper(mi, &mi->reg3, live, only_abcd, (mi->bb->reg1.reg == DR_REG_XCX ? ((mi->bb->reg2.reg == DR_REG_XDX) ? DR_REG_XBX : DR_REG_XDX) : ((mi->bb->reg2.reg == DR_REG_XCX) ? ((mi->bb->reg1.reg == DR_REG_XDX) ? DR_REG_XBX : DR_REG_XDX) : DR_REG_XCX)), spill_reg3_slot(mi->aflags == EFLAGS_WRITE_6, !mi->eax.used || mi->eax.dead, /* later we'll update these */ false, false), no_overlap1, no_overlap2); } if (mi->bb->reg1.reg != REG_NULL && !mi->reg3.dead && mi->reg3.xchg == REG_NULL) { if (!mi->reg3.global) { /* spill_reg3_slot() should return SPILL_SLOT_4 for us */ ASSERT(mi->reg3.slot == local_slot[local_idx], "reg3: wrong slot!"); local_idx++; } else ASSERT(mi->reg3.slot < SPILL_SLOT_EFLAGS_EAX, "reg3 global: 0 or 1!"); } } else mi->reg3.reg = REG_NULL; if (mi->bb->reg1.reg != REG_NULL && (!need3 || !reg3_must_be_ecx || mi->bb->reg1.reg != DR_REG_XCX) && /* we only need to check for overlap for xchg (since messes up * app values) so we ignore no_overlap* */ (!mi->eax.used || mi->bb->reg1.reg != DR_REG_XAX)) { /* Use whole-bb spilled reg (PR 489221) */ mi->reg1 = mi->bb->reg1; mi->reg1.dead = (live[mi->reg1.reg - REG_START] == LIVE_DEAD); } else { /* Pick primary scratch reg */ ASSERT(local_idx < local_idx_max, "local slot overflow"); pick_scratch_reg_helper(mi, &mi->reg1, live, only_abcd, (need3 && mi->reg3.reg == DR_REG_XDX) ? DR_REG_XCX : ((mi->bb->reg2.reg == DR_REG_XDX) ? DR_REG_XBX : DR_REG_XDX), /* if whole-bb ecx is in slot 1 or 2, use 3rd slot */ (mi->bb->reg1.reg == REG_NULL) ? SPILL_SLOT_1 : local_slot[local_idx++], no_overlap1, no_overlap2); } if (mi->bb->reg2.reg != REG_NULL && (!need3 || !reg3_must_be_ecx || mi->bb->reg2.reg != DR_REG_XCX) && (!mi->eax.used || mi->bb->reg2.reg != DR_REG_XAX)) { /* Use whole-bb spilled reg (PR 489221) */ mi->reg2 = mi->bb->reg2; mi->reg2.dead = (live[mi->reg2.reg - REG_START] == LIVE_DEAD); } else { /* Pick secondary scratch reg */ ASSERT(local_idx < local_idx_max, "local slot overflow"); pick_scratch_reg_helper(mi, &mi->reg2, live, only_abcd, mi->reg1.reg == DR_REG_XBX ? ((need3 && mi->reg3.reg == DR_REG_XDX) ? DR_REG_XCX : DR_REG_XDX) : ((need3 && mi->reg3.reg == DR_REG_XBX) ? DR_REG_XCX : DR_REG_XBX), /* if whole-bb ecx is in slot 1 or 2, use 3rd slot */ (mi->bb->reg2.reg == REG_NULL) ? SPILL_SLOT_2 : local_slot[local_idx++], no_overlap1, no_overlap2); } if (mi->bb->reg1.reg == REG_NULL && need3 && !mi->reg3.dead && mi->reg3.xchg == REG_NULL) { /* See if we can use slots 1 or 2 instead: matters when using DR slots */ mi->reg3.slot = spill_reg3_slot(mi->aflags == EFLAGS_WRITE_ARITH, !mi->eax.used || mi->eax.dead, mi->reg1.dead, mi->reg2.dead); } DOLOG(4, { void *drcontext = dr_get_current_drcontext(); tls_util_t *pt = PT_GET(drcontext); ASSERT(pt != NULL, "should always have dcontext in cur DR"); LOG(3, "scratch: "); instr_disassemble(drcontext, inst, LOGFILE(pt)); LOG(3, "| "); print_scratch_reg(drcontext, &mi->reg1, 1, LOGFILE(pt)); LOG(3, ", "); print_scratch_reg(drcontext, &mi->reg2, 2, LOGFILE(pt)); if (need3) { LOG(3, ", "); print_scratch_reg(drcontext, &mi->reg3, 3, LOGFILE(pt)); } LOG(3, "\n"); }); # ifdef DEBUG check_scratch_reg_no_overlap(&mi->reg1, &mi->reg2); if (need3) { check_scratch_reg_no_overlap(&mi->reg1, &mi->reg3); check_scratch_reg_no_overlap(&mi->reg2, &mi->reg3); } # endif } #endif /* X86 */ static bool insert_spill_common(void *drcontext, instrlist_t *bb, instr_t *inst, scratch_reg_info_t *si, bool spill, bool just_xchg, bool do_global) { #ifdef X86 /* XXX i#1795: eliminate this and port to drreg */ /* No need to do a local spill/restore if globally spilled (PR 489221) */ if (si->used && !si->dead && (!si->global || do_global)) { if (si->xchg != REG_NULL) { /* spill/restore are identical */ PRE(bb, inst, INSTR_CREATE_xchg (drcontext, opnd_create_reg(si->reg), opnd_create_reg(si->xchg))); } else if (!just_xchg) { if (spill) spill_reg(drcontext, bb, inst, si->reg, si->slot); else restore_reg(drcontext, bb, inst, si->reg, si->slot); } if (!spill && do_global) { /* FIXME PR 553724: avoid later redundant restore at * bottom of bb by setting used to false here. * However that's not working for reasons I haven't yet determined. */ } return true; } return false; #else /* FIXME i#1795/i#1726: port shadow modes to use drreg */ ASSERT_NOT_REACHED(); return false; #endif } bool insert_spill_global(void *drcontext, instrlist_t *bb, instr_t *inst, scratch_reg_info_t *si, bool spill) { return insert_spill_common(drcontext, bb, inst, si, spill, false, true); } void insert_spill_or_restore(void *drcontext, instrlist_t *bb, instr_t *inst, scratch_reg_info_t *si, bool spill, bool just_xchg) { insert_spill_common(drcontext, bb, inst, si, spill, just_xchg, false); } /* insert aflags save code sequence w/o spill: lahf; seto %al; */ void insert_save_aflags_nospill(void *drcontext, instrlist_t *ilist, instr_t *inst, bool save_oflag) { #ifdef X86 /* XXX i#1795: eliminate this and port to drreg */ PRE(ilist, inst, INSTR_CREATE_lahf(drcontext)); if (save_oflag) { PRE(ilist, inst, INSTR_CREATE_setcc(drcontext, OP_seto, opnd_create_reg(DR_REG_AL))); } #else /* FIXME i#1795/i#1726: port shadow modes to use drreg */ ASSERT_NOT_REACHED(); #endif } /* insert aflags restore code sequence w/o spill: add %al, 0x7f; sahf; */ void insert_restore_aflags_nospill(void *drcontext, instrlist_t *ilist, instr_t *inst, bool restore_oflag) { #ifdef X86 /* XXX i#1795: eliminate this and port to drreg */ if (restore_oflag) { PRE(ilist, inst, INSTR_CREATE_add (drcontext, opnd_create_reg(REG_AL), OPND_CREATE_INT8(0x7f))); } PRE(ilist, inst, INSTR_CREATE_sahf(drcontext)); #else /* FIXME i#1795/i#1726: port shadow modes to use drreg */ ASSERT_NOT_REACHED(); #endif } void insert_save_aflags(void *drcontext, instrlist_t *bb, instr_t *inst, scratch_reg_info_t *si, int aflags) { #ifdef X86 /* XXX i#1795: eliminate this and port to drreg */ if (si->reg != REG_NULL) { ASSERT(si->reg == DR_REG_XAX, "must use eax for aflags"); insert_spill_or_restore(drcontext, bb, inst, si, true/*save*/, false); } insert_save_aflags_nospill(drcontext, bb, inst, aflags != EFLAGS_WRITE_OF); #else /* FIXME i#1795/i#1726: port shadow modes to use drreg */ ASSERT_NOT_REACHED(); #endif } void insert_restore_aflags(void *drcontext, instrlist_t *bb, instr_t *inst, scratch_reg_info_t *si, int aflags) { #ifdef X86 /* XXX i#1795: eliminate this and port to drreg */ insert_restore_aflags_nospill(drcontext, bb, inst, aflags != EFLAGS_WRITE_OF); if (si->reg != REG_NULL) { ASSERT(si->reg == DR_REG_XAX, "must use eax for aflags"); insert_spill_or_restore(drcontext, bb, inst, si, false/*restore*/, false); } #else /* FIXME i#1795/i#1726: port shadow modes to use drreg */ ASSERT_NOT_REACHED(); #endif } static inline bool scratch_reg1_is_avail(instr_t *inst, fastpath_info_t *mi, bb_info_t *bi) { int opc = instr_get_opcode(inst); return (bi->reg1.reg != DR_REG_NULL && bi->reg1.used && /* ensure neither sharing w/ next nor sharing w/ prev */ !SHARING_XL8_ADDR_BI(bi) && mi != NULL && !mi->use_shared && /* cmovcc does an aflags restore after the lea, so reg1 needs * to stay untouched */ !opc_is_cmovcc(opc) && !opc_is_fcmovcc(opc)); } static inline bool scratch_reg2_is_avail(instr_t *inst, fastpath_info_t *mi, bb_info_t *bi) { int opc = instr_get_opcode(inst); return (bi->reg2.reg != DR_REG_NULL && bi->reg2.used && /* we use reg2 for cmovcc */ !opc_is_cmovcc(opc) && !opc_is_fcmovcc(opc)); } /* single eflags save per bb */ void save_aflags_if_live(void *drcontext, instrlist_t *bb, instr_t *inst, fastpath_info_t *mi, bb_info_t *bi) { #ifdef X86 /* XXX i#1795: eliminate this and port to drreg */ scratch_reg_info_t si; /* We save aflags unless there's no read prior to the 1st write. * We clobber eax while doing so if eax is dead. * Technically both are unsafe: should restore on a fault (PR * 463053) but we consider that too pathological to bother. */ bool eax_dead = bi->eax_dead || (bi->reg1.reg == DR_REG_XAX && scratch_reg1_is_avail(inst, mi, bi)) || (bi->reg2.reg == DR_REG_XAX && scratch_reg2_is_avail(inst, mi, bi)); ASSERT(options.pattern == 0, "pattern is using drreg"); if (!bi->eflags_used) return; if (bi->aflags != EFLAGS_WRITE_ARITH) { /* slot 5 won't be used for 3rd reg (that's 4) and is ok for temp use */ si.slot = SPILL_SLOT_5; if (eax_dead || bi->aflags_where == AFLAGS_IN_EAX) { si.reg = REG_NULL; } else { si.reg = DR_REG_XAX; /* reg1 is used for xl8 sharing so check whether shared_memop is set * == share w/ next. it's cleared prior to post-app-write aflags save * so we use mi->use_shared to detect share w/ prev. * for aflags restore code added later it's ok to be too conservative: * these fields should all be cleared anyway, and won't matter for * top-of-bb save. * we can assume that reg2 is dead. */ if (scratch_reg1_is_avail(inst, mi, bi)) si.xchg = bi->reg1.reg; else if (scratch_reg2_is_avail(inst, mi, bi)) si.xchg = bi->reg2.reg; else si.xchg = REG_NULL; ASSERT(si.xchg != DR_REG_XAX, "xchg w/ self is not a save"); si.used = true; si.dead = false; si.global = false; /* to enable the save */ } insert_save_aflags(drcontext, bb, inst, &si, bi->aflags); /* optimization: * We keep the flags in eax if eax is not used in any app instrs later. * XXX: we can be more aggressive to keep the flags in eax if it is * not used in app instr between here and the next eflags restore. * Since a lahf followed by a read of eax causes a partial-reg * stall that could improve perf noticeably. * However, this would make the state restore more complex. */ if (bi->aflags_where == AFLAGS_UNKNOWN) { # ifdef TOOL_DR_MEMORY /* i#1466: remember where to start restore state for pattern mode. * In pattern mode, we only save eax if we save aflags. i#1466 is a bug * that tries to restore eax on a fault before we saving eax, so we use * first_restore_pc to remember where eax is saved and only restore eax * for fault happening after that pc. * For shadow mode, it should always start from the first pc, and we * set first_restore_pc to be NULL. */ if (options.pattern != 0) { ASSERT(bi->first_restore_pc == NULL, "first_restore_pc must be NULL if aflags_where is not set"); bi->first_restore_pc = (mi == NULL ? instr_get_app_pc(inst) : mi->xl8); ASSERT(bi->first_restore_pc != NULL, "instr app_pc must not be NULL"); } /* We can avoid saving eflags to TLS and restoring app %eax if we know that * %eax is not used later in the bb. This might be called in the middle of * a bb, so we need use first_restore_pc to remember where we start stealing * %eax (#i1466). */ if (!xax_is_used_subsequently(inst) && options.pattern != 0) { /* To keep aflags in %eax, we need a permanent TLS store for * storing app's %eax value. Current implementation uses SLOT 5, * which is used for third register spill and temporary eax * spill on aflags saving. So this optimization is only applied * in pattern mode. * XXX: to apply this optimization in shadow mode, we should use * a permanent TLS slot, and make sure neither spill reg1 nor * reg2 uses %eax. */ /* - eax is not used by app later in bb * - eax is holding aflags * - app's eax is in tls slot from now on */ bi->aflags_where = AFLAGS_IN_EAX; } else # endif bi->aflags_where = AFLAGS_IN_TLS; } if (bi->aflags_where == AFLAGS_IN_EAX) return; /* save aflags into tls */ PRE(bb, inst, INSTR_CREATE_mov_st (drcontext, spill_slot_opnd(drcontext, SPILL_SLOT_EFLAGS_EAX), opnd_create_reg(DR_REG_XAX))); if (!eax_dead) { /* restore eax */ /* I used to use xchg to avoid needing two instrs, but xchg w/ mem's * lock of the bus shows up as a measurable perf hit (PR 553724) */ insert_spill_or_restore(drcontext, bb, inst, &si, false/*restore*/, false); } } #else /* FIXME i#1795/i#1726: port shadow modes to use drreg */ ASSERT_NOT_REACHED(); #endif } /* Single eflags save per bb * N.B.: the sequence added here is matched in restore_mcontext_on_shadow_fault() */ void restore_aflags_if_live(void *drcontext, instrlist_t *bb, instr_t *inst, fastpath_info_t *mi, bb_info_t *bi) { #ifdef X86 /* XXX i#1795: eliminate this and port to drreg */ scratch_reg_info_t si; if (!bi->eflags_used) return; ASSERT(bi->aflags_where == AFLAGS_IN_TLS || bi->aflags_where == AFLAGS_IN_EAX, "bi->aflags_where is not set"); ASSERT(options.pattern == 0, "pattern is using drreg"); si.reg = DR_REG_XAX; si.xchg = REG_NULL; si.slot = SPILL_SLOT_EFLAGS_EAX; si.used = true; si.dead = false; si.global = false; /* to enable the restore */ if (bi->aflags_where == AFLAGS_IN_TLS) { if (bi->eax_dead || (bi->reg1.reg == DR_REG_XAX && scratch_reg1_is_avail(inst, mi, bi)) || (bi->reg2.reg == DR_REG_XAX && scratch_reg2_is_avail(inst, mi, bi))) { insert_spill_or_restore(drcontext, bb, inst, &si, false/*restore*/, false); /* we do NOT want the eax-restore at the end of insert_restore_aflags() */ si.reg = DR_REG_NULL; } else { si.slot = SPILL_SLOT_5; /* See notes in save_aflags_if_live on sharing impacting reg1 being scratch */ if (scratch_reg1_is_avail(inst, mi, bi)) si.xchg = bi->reg1.reg; else if (scratch_reg2_is_avail(inst, mi, bi)) si.xchg = bi->reg2.reg; ASSERT(si.xchg != DR_REG_XAX, "xchg w/ self is not a save"); /* I used to use xchg to avoid needing two instrs, but xchg w/ mem's * lock of the bus shows up as a measurable perf hit (PR 553724) */ insert_spill_or_restore(drcontext, bb, inst, &si, true/*save*/, false); PRE(bb, inst, INSTR_CREATE_mov_ld (drcontext, opnd_create_reg(DR_REG_XAX), spill_slot_opnd(drcontext, SPILL_SLOT_EFLAGS_EAX))); /* we DO want the eax-restore at the end of insert_restore_aflags() */ } } else { /* AFLAGS_IN_EAX */ si.slot = SPILL_SLOT_5; } insert_restore_aflags(drcontext, bb, inst, &si, bi->aflags); /* avoid re-restoring. FIXME: do this for insert_spill_global too? */ bi->eflags_used = false; #else /* FIXME i#1795/i#1726: port shadow modes to use drreg */ ASSERT_NOT_REACHED(); #endif } /*************************************************************************** * Whole-bb spilling (PR 489221) */ #ifdef X86 /* XXX i#1795: eliminate this and port to drreg */ static void pick_bb_scratch_regs_helper(opnd_t opnd, int uses[NUM_LIVENESS_REGS]) { int j; for (j = 0; j < opnd_num_regs_used(opnd); j++) { reg_id_t reg = opnd_get_reg_used(opnd, j); if (reg_is_gpr(reg)) { int idx = reg_to_pointer_sized(reg) - REG_START; ASSERT(idx >= 0 && idx < NUM_LIVENESS_REGS, "reg enum error"); uses[idx]++; if (opnd_is_memory_reference(opnd)) uses[idx]++; } } } static void pick_bb_scratch_regs(instr_t *inst, bb_info_t *bi) { /* Pick the best regs to use as scratch. We want the fewest uses, * since we have to restore on each use (twice for a memref: once * for lea, once for app instr). * Having varying scratch regs per bb forces us to store which * ones so we can restore on slowpath/shadow fault/app fault but * it is worth it to shrink fastpath instru. * * Plan: pick just 2 scratches, and then those that need 3 * (mem2mem or sub-dword) have to grab a local 3rd but adjust so * that ecx is considered #3. * Going to always put whole-bb eflags into tls slot, so not * considering leaving it in eax and getting 2 more scratch regs, for * simplicity: though that could be more efficient for some bbs. * * Future work PR 492073: if bb has high scores for all regs, try to * split into 2: maybe 1st half diff from 2nd half. Or, fall back to * per-instr, can be less expensive than restoring regs before each lea * and app instr. */ int uses[NUM_LIVENESS_REGS] = {0,}; int i, uses_least = INT_MAX, uses_second = INT_MAX; while (inst != NULL) { if (instr_is_app(inst)) { for (i = 0; i < instr_num_dsts(inst); i++) pick_bb_scratch_regs_helper(instr_get_dst(inst, i), uses); for (i = 0; i < instr_num_srcs(inst); i++) pick_bb_scratch_regs_helper(instr_get_src(inst, i), uses); if (instr_is_cti(inst)) break; } inst = instr_get_next(inst); } /* Too risky to use esp: if no alt sig stk (ESXi) or on Windows can't * handle fault */ uses[DR_REG_XSP - REG_START] = INT_MAX; #ifdef X86 /* Future work PR 492073: If esi/edi/ebp are among the least-used, xchg * w/ cx/dx/bx and swap in each app instr. Have to ensure results in * legal instrs (if app uses sub-dword, or certain addressing modes). */ uses[DR_REG_XBP - REG_START] = INT_MAX; uses[DR_REG_XSI - REG_START] = INT_MAX; uses[DR_REG_XDI - REG_START] = INT_MAX; #elif defined(ARM) /* stolen reg must not be used */ uses[dr_get_stolen_reg() - REG_START] = INT_MAX; uses[DR_REG_LR - REG_START] = INT_MAX; uses[DR_REG_PC - REG_START] = INT_MAX; #endif /* X86/ARM */ #ifdef X64 /* XXX i#1632: once we have byte-to-byte shadowing we shouldn't need * just a/b/c/d regs and should be able to use these. For now with * 1B-to-2b we need %ah, etc. */ for (i = DR_REG_R8; i <= DR_REG_R15; i++) { ASSERT(i - REG_START < NUM_LIVENESS_REGS, "overflow"); uses[i - REG_START] = INT_MAX; } #endif for (i = 0; i < NUM_LIVENESS_REGS; i++) { if (uses[i] < uses_least) { uses_second = uses_least; bi->reg2.reg = bi->reg1.reg; uses_least = uses[i]; bi->reg1.reg = REG_START + i; } else if (uses[i] < uses_second) { uses_second = uses[i]; bi->reg2.reg = REG_START + i; } } /* For PR 493257 (share shadow translations) we do NOT want reg1 to be * eax, so we can save eflags w/o clobbering shared shadow addr in reg1 */ if (bi->reg1.reg == DR_REG_XAX) { scratch_reg_info_t tmp = bi->reg1; ASSERT(bi->reg2.reg != DR_REG_XAX, "reg2 shouldn't be eax"); bi->reg1 = bi->reg2; bi->reg2 = tmp; } /* We don't want ecx in reg1, for sharing. Even though we swap * when we need ecx as a 3rd reg, sharing really wants reg1==whole-bb reg1. */ else if (bi->reg1.reg == DR_REG_XCX && bi->reg2.reg != DR_REG_XAX) { scratch_reg_info_t tmp = bi->reg1; ASSERT(bi->reg2.reg != DR_REG_XCX, "reg2 shouldn't equal reg1"); DOLOG(3, { void *drcontext = dr_get_current_drcontext(); LOG(3, "swapping reg1 "); opnd_disassemble(drcontext, opnd_create_reg(bi->reg1.reg), LOGFILE(PT_GET(drcontext))); LOG(3, " and reg2 "); opnd_disassemble(drcontext, opnd_create_reg(bi->reg2.reg), LOGFILE(PT_GET(drcontext))); LOG(3, "\n"); }); bi->reg1 = bi->reg2; bi->reg2 = tmp; } ASSERT(bi->reg1.reg <= DR_REG_XBX, "NYI non-a/b/c/d reg"); bi->reg1.slot = SPILL_SLOT_1; /* Dead-across-whole-bb is rare so we don't bother to support xchg */ bi->reg1.xchg = REG_NULL; /* The dead fields will be computed in fastpath_pre_app_instr */ bi->reg1.dead = false; bi->reg1.used = false; /* will be set once used */ bi->reg1.global = true; ASSERT(bi->reg2.reg <= DR_REG_XBX, "NYI non-a/b/c/d reg"); ASSERT(bi->reg1.reg != bi->reg2.reg, "reg conflict"); bi->reg2.slot = SPILL_SLOT_2; bi->reg2.xchg = REG_NULL; bi->reg2.dead = false; bi->reg2.used = false; /* will be set once used */ bi->reg2.global = true; #ifdef STATISTICS if (uses_least > 0) { STATS_INC(reg_spill_used_in_bb); } else { STATS_INC(reg_spill_unused_in_bb); } if (uses_second > 0) { STATS_INC(reg_spill_used_in_bb); } else { STATS_INC(reg_spill_unused_in_bb); } #endif DOLOG(3, { void *drcontext = dr_get_current_drcontext(); tls_util_t *pt = PT_GET(drcontext); ASSERT(pt != NULL, "should always have dcontext in cur DR"); LOG(3, "whole-bb scratch: "); print_scratch_reg(drcontext, &bi->reg1, 1, LOGFILE(pt)); LOG(3, " x%d, ", uses_least); print_scratch_reg(drcontext, &bi->reg2, 2, LOGFILE(pt)); LOG(3, " x%d\n", uses_second); }); } #endif /* X86 */ bool whole_bb_spills_enabled(void) { /* Whole-bb eflags and register saving requires spill slots that * can be live across instructions == our own spill slots. * We use SPILL_SLOT_1, SPILL_SLOT_2, and SPILL_SLOT_EFLAGS_EAX * for 2 registers and eflags. */ return (options.num_spill_slots >= SPILL_SLOT_EFLAGS_EAX && #ifdef TOOL_DR_HEAPSTAT options.staleness && #endif /* should we enable whole-bb for -leaks_only? * we'd need to enable bb table and state restore on fault. * since it's rare to have more than one stack adjust in a * single bb, I don't think we'd gain enough perf to be worth * the complexity. */ INSTRUMENT_MEMREFS()); } void fastpath_top_of_bb(void *drcontext, void *tag, instrlist_t *bb, bb_info_t *bi) { instr_t *inst = instrlist_first(bb); #ifdef DEBUG /* We look at instr pc, not the tag, to handle displaced code such * as for the vsyscall hook. */ app_pc prev_pc = instr_get_app_pc(instrlist_first_app(bb)); ASSERT(prev_pc != NULL, "bb first app pc must not be NULL"); /* i#260 and i#1466: bbs must be contiguous */ if (inst != NULL && whole_bb_spills_enabled() && /* bi->is_repstr_to_loop is set in app2app and may mess up the instr pc */ !bi->is_repstr_to_loop) { for (; inst != NULL; inst = instr_get_next_app(inst)) { app_pc cur_pc = instr_get_app_pc(inst); if (cur_pc == NULL) continue; /* relax the check here instead of "cur_pc == prev_pc + instr_length" * to allow client adding fake app instr */ ASSERT(cur_pc >= prev_pc, "bb is not contiguous"); prev_pc = cur_pc; } inst = instrlist_first(bb); } #endif if (inst == NULL || !whole_bb_spills_enabled() || /* pattern is using drreg */ options.pattern != 0) { bi->eflags_used = false; bi->reg1.reg = REG_NULL; bi->reg1.used = false; bi->reg2.reg = REG_NULL; bi->reg2.used = false; return; } #ifdef X86 /* XXX i#1795: eliminate this and port to drreg */ /* analyze bb and pick which scratch regs to use. don't actually do * the spills until we know there's actual instrumentation in this bb. * we don't also delay the analysis b/c it's simpler to analyze the * unmodified instrlist: we do add clean calls that don't count as * instru we need to spill for, etc. we could put in checks for meta * but will wait until analysis shows up as perf bottleneck. */ pick_bb_scratch_regs(inst, bi); #endif } /* Invoked before the regular pre-app instrumentation */ void fastpath_pre_instrument(void *drcontext, instrlist_t *bb, instr_t *inst, bb_info_t *bi) { #ifdef X86 int live[NUM_LIVENESS_REGS]; #endif app_pc pc = instr_get_app_pc(inst); if (pc != NULL) { if (bi->first_app_pc == NULL) bi->first_app_pc = pc; bi->last_app_pc = pc; } if (!whole_bb_spills_enabled()) return; if (options.pattern != 0) /* pattern is using drreg */ return; #ifdef X86 /* XXX i#1795: eliminate this and port to drreg */ /* Haven't instrumented below here yet, so forward analysis should * see only app instrs * XXX i#777: should do reverse walk during analysis phase and store results * in bit array in new note fields */ bi->aflags = get_aflags_and_reg_liveness(inst, live, options.pattern != 0); /* Update the dead fields */ if (bi->reg1.reg != DR_REG_NULL) bi->reg1.dead = (live[bi->reg1.reg - REG_START] == LIVE_DEAD); if (bi->reg2.reg != DR_REG_NULL) bi->reg2.dead = (live[bi->reg2.reg - REG_START] == LIVE_DEAD); bi->eax_dead = (live[DR_REG_XAX - REG_START] == LIVE_DEAD); #endif } bool instr_is_spill(instr_t *inst) { return (instr_get_opcode(inst) == IF_X86_ELSE(OP_mov_st, OP_str) && is_spill_slot_opnd(dr_get_current_drcontext(), instr_get_dst(inst, 0)) && opnd_is_reg(instr_get_src(inst, 0))); } bool instr_is_restore(instr_t *inst) { return (instr_get_opcode(inst) == IF_X86_ELSE(OP_mov_ld, OP_ldr) && is_spill_slot_opnd(dr_get_current_drcontext(), instr_get_src(inst, 0)) && opnd_is_reg(instr_get_dst(inst, 0))); } bool instr_at_pc_is_restore(void *drcontext, byte *pc) { instr_t inst; bool res; instr_init(drcontext, &inst); res = (decode(drcontext, pc, &inst) != NULL && instr_is_restore(&inst)); instr_free(drcontext, &inst); return res; } void mark_eflags_used(void *drcontext, instrlist_t *bb, bb_info_t *bi) { instr_t *where_spill = (bi == NULL || bi->spill_after == NULL) ? instrlist_first(bb) : instr_get_next(bi->spill_after); if (!whole_bb_spills_enabled() || bi == NULL/*gencode*/ || bi->eflags_used) return; /* optimization: if flags are dead then ignore our use. * technically unsafe (PR 463053). * FIXME: for use in fastpath_pre_instrument() for post-instr * save are we using the pre-instr analysis? */ if (bi->aflags == EFLAGS_WRITE_ARITH) { LOG(4, "eflags are dead so not saving\n"); return; } /* To use global-eax for eflags we must spill regs before flags */ while (instr_is_meta(where_spill) && instr_is_spill(where_spill) && instr_get_next(where_spill) != NULL) where_spill = instr_get_next(where_spill); LOG(4, "marking eflags used => spilling if live\n"); bi->eflags_used = true; save_aflags_if_live(drcontext, bb, where_spill, NULL, bi); #ifdef STATISTICS if (bi->aflags != EFLAGS_WRITE_ARITH) STATS_INC(aflags_saved_at_top); #endif } void mark_scratch_reg_used(void *drcontext, instrlist_t *bb, bb_info_t *bi, scratch_reg_info_t *si) { instr_t *where_spill = (bi == NULL || bi->spill_after == NULL) ? instrlist_first(bb) : instr_get_next(bi->spill_after); /* Update global used values, and if global save on first use in bb */ if (si->used) return; if (si->global) { ASSERT(bi != NULL, "should only use global in bb, not gencode"); /* To use global-eax for eflags we must spill regs before flags */ while (instr_get_prev(where_spill) != NULL && instr_is_meta(instr_get_prev(where_spill)) && /* We want to NOT walk back into clean call: clean call * ends in restore, not spill */ instr_is_spill(instr_get_prev(where_spill))) where_spill = instr_get_prev(where_spill); if (si->reg == bi->reg1.reg) { bi->reg1.used = true; insert_spill_global(drcontext, bb, where_spill, &bi->reg1, true/*save*/); } else { ASSERT(si->reg == bi->reg2.reg, "global vs local mismatch"); bi->reg2.used = true; insert_spill_global(drcontext, bb, where_spill, &bi->reg2, true/*save*/); } } /* Even if global we have to mark the si copy as used too */ si->used = true; } bool instr_needs_eflags_restore(instr_t *inst, uint aflags_liveness) { return (TESTANY(EFLAGS_READ_ARITH, instr_get_eflags(inst, DR_QUERY_DEFAULT)) || /* If the app instr writes some subset of eflags we need to restore * rest so they're combined properly */ (TESTANY(EFLAGS_WRITE_ARITH, instr_get_eflags(inst, DR_QUERY_INCLUDE_ALL)) && aflags_liveness != EFLAGS_WRITE_ARITH)); } /* Invoked after the regular pre-app instrumentation */ void fastpath_pre_app_instr(void *drcontext, instrlist_t *bb, instr_t *inst, bb_info_t *bi, fastpath_info_t *mi) { /* Preserve app semantics wrt global spilled registers */ /* XXX i#777: gets next instr, and below does liveness analysis w/ forward scan. * should use stored info from reverse scan done during analysis phase. */ #ifdef X86 instr_t *next = instr_get_next(inst); int live[NUM_LIVENESS_REGS]; bool restored_for_read = false; #endif if (!whole_bb_spills_enabled()) return; if (options.pattern != 0) /* pattern is using drreg */ return; #ifdef X86 /* XXX i#1795: eliminate this and port to drreg */ /* If this is the last instr, the end-of-bb restore will restore for any read, * and everything is dead so we can ignore writes */ if (next == NULL) return; /* Before each read, restore global spilled registers */ if (instr_needs_eflags_restore(inst, bi->aflags)) restore_aflags_if_live(drcontext, bb, inst, mi, bi); /* Optimization: don't bother to restore if this is not a meaningful read * (e.g., xor with self) */ if ((bi->reg1.reg != DR_REG_NULL || bi->reg2.reg != DR_REG_NULL) && (!result_is_always_defined(inst, true/*natively*/) || /* if sub-dword then we have to restore for rest of bits */ opnd_get_size(instr_get_src(inst, 0)) != OPSZ_4)) { /* we don't mark as used: if unused so far, no reason to restore */ if (instr_reads_from_reg(inst, bi->reg1.reg, DR_QUERY_INCLUDE_ALL) || /* if sub-reg is written we need to restore rest */ (instr_writes_to_reg(inst, bi->reg1.reg, DR_QUERY_INCLUDE_ALL) && !instr_writes_to_exact_reg(inst, bi->reg1.reg, DR_QUERY_INCLUDE_ALL)) || /* for conditional write, simplest to restore before and save after, b/c * if cond fails we have to avoid saving bogus value */ (instr_writes_to_reg(inst, bi->reg1.reg, DR_QUERY_INCLUDE_ALL) && !instr_writes_to_reg(inst, bi->reg1.reg, DR_QUERY_DEFAULT))) { restored_for_read = true; /* If reg1 holds a shared shadow addr, better to preserve it than * to have to re-translate */ if (!opnd_is_null(bi->shared_memop)) { if (instr_writes_to_reg(inst, bi->reg1.reg, DR_QUERY_INCLUDE_ALL) || instr_writes_to_reg(inst, bi->reg2.reg, DR_QUERY_INCLUDE_ALL) || /* must consider reading the other reg (PR 494169) */ instr_reads_from_reg(inst, bi->reg2.reg, DR_QUERY_INCLUDE_ALL)) { /* give up: not worth complexity (i#165 covers handling) */ STATS_INC(xl8_not_shared_reg_conflict); bi->shared_memop = opnd_create_null(); } else { PRE(bb, inst, XINST_CREATE_store(drcontext, opnd_create_reg(bi->reg2.reg), opnd_create_reg(bi->reg1.reg))); PRE(bb, next, XINST_CREATE_store(drcontext, opnd_create_reg(bi->reg1.reg), opnd_create_reg(bi->reg2.reg))); } } insert_spill_global(drcontext, bb, inst, &bi->reg1, false/*restore*/); } if (instr_reads_from_reg(inst, bi->reg2.reg, DR_QUERY_INCLUDE_ALL) || /* if sub-reg is written we need to restore rest */ (instr_writes_to_reg(inst, bi->reg2.reg, DR_QUERY_INCLUDE_ALL) && !instr_writes_to_exact_reg(inst, bi->reg2.reg, DR_QUERY_INCLUDE_ALL)) || /* for conditional write, simplest to restore before and save after, b/c * if cond fails we have to avoid saving bogus value */ (instr_writes_to_reg(inst, bi->reg2.reg, DR_QUERY_INCLUDE_ALL) && !instr_writes_to_reg(inst, bi->reg2.reg, DR_QUERY_DEFAULT))) { restored_for_read = true; insert_spill_global(drcontext, bb, inst, &bi->reg2, false/*restore*/); } } /* After each write, update global spilled values, unless that reg is * dead (xref PR 463053 for safety) */ /* Haven't instrumented below here yet, so forward analysis should * see only app instrs */ /* We updated reg*.dead in fastpath_pre_instrument() but here we want * liveness post-app-instr */ bi->aflags = get_aflags_and_reg_liveness(next, live, options.pattern != 0); /* Update the dead fields */ if (bi->reg1.reg != DR_REG_NULL) bi->reg1.dead = (live[bi->reg1.reg - REG_START] == LIVE_DEAD); if (bi->reg2.reg != DR_REG_NULL) bi->reg2.dead = (live[bi->reg2.reg - REG_START] == LIVE_DEAD); bi->eax_dead = (live[DR_REG_XAX - REG_START] == LIVE_DEAD); if (bi->reg1.reg != DR_REG_NULL && instr_writes_to_reg(inst, bi->reg1.reg, DR_QUERY_INCLUDE_ALL)) { if (!bi->reg1.dead) { bi->reg1.used = true; insert_spill_global(drcontext, bb, next, &bi->reg1, true/*save*/); } /* If reg1 holds a shared shadow addr, better to preserve it than * to have to re-translate. We must do this even if reg1 is dead. */ if (!opnd_is_null(bi->shared_memop)) { if (restored_for_read || (instr_writes_to_reg(inst, bi->reg2.reg, DR_QUERY_INCLUDE_ALL) && !bi->reg2.dead)) { /* give up: not worth complexity for now (i#165 covers handling) */ STATS_INC(xl8_not_shared_reg_conflict); bi->shared_memop = opnd_create_null(); } else { bi->reg1.used = true; PRE(bb, inst, XINST_CREATE_store(drcontext, opnd_create_reg(bi->reg2.reg), opnd_create_reg(bi->reg1.reg))); PRE(bb, next, XINST_CREATE_store(drcontext, opnd_create_reg(bi->reg1.reg), opnd_create_reg(bi->reg2.reg))); } } } if (bi->reg2.reg != DR_REG_NULL && instr_writes_to_reg(inst, bi->reg2.reg, DR_QUERY_INCLUDE_ALL) && !bi->reg2.dead) { bi->reg2.used = true; insert_spill_global(drcontext, bb, next, &bi->reg2, true/*save*/); } if (TESTANY(EFLAGS_WRITE_ARITH, instr_get_eflags(inst, DR_QUERY_INCLUDE_ALL)) && bi->aflags != EFLAGS_WRITE_ARITH) { /* Optimization: no need if next is jcc and we just checked definedness */ if (IF_DRMEM(bi->eflags_defined && ) instr_is_jcc(next)) { /* We just wrote to real eflags register, so don't restore at end */ LOG(4, "next instr is jcc so not saving eflags\n"); bi->eflags_used = false; } else { save_aflags_if_live(drcontext, bb, next, mi, bi); } } #endif /* X86 */ } void fastpath_bottom_of_bb(void *drcontext, void *tag, instrlist_t *bb, bb_info_t *bi, bool added_instru, bool translating, bool check_ignore_unaddr) { instr_t *last = instrlist_last(bb); bb_saved_info_t *save; if (!whole_bb_spills_enabled()) return; ASSERT(!added_instru || instrlist_first(bb) != NULL, "can't add instru w/o instrs"); /* the .used field controls whether we actually saved, and thus restore */ LOG(3, "whole-bb scratch: r1=%s, r2=%s, efl=%s\n", bi->reg1.used ? "used" : "unused", bi->reg2.used ? "used" : "unused", bi->eflags_used ? "used" : "unused"); if (!translating) { /* Add to table so we can restore on slowpath or a fault */ save = (bb_saved_info_t *) global_alloc(sizeof(*save), HEAPSTAT_PERBB); memset(save, 0, sizeof(*save)); /* If dead initially and only used later, fine to have fault path * restore from TLS early since dead. But if never used and thus never * spilled then we have to tell the fault path to not restore from TLS. */ if (bi->reg1.used) save->scratch1 = bi->reg1.reg; else save->scratch1 = REG_NULL; if (bi->reg2.used) save->scratch2 = bi->reg2.reg; else save->scratch2 = REG_NULL; save->eflags_saved = bi->eflags_used; save->aflags_in_eax = (bi->aflags_where == AFLAGS_IN_EAX); /* We store the pc of the last instr, since everything is restored * already (and NOT present in our tls slots) if have a fault in that * instr: unless it's a transformed repstr, in which case the final * OP_loop won't fault, so a fault will be before the restores (i#532). */ if (bi->is_repstr_to_loop) save->last_instr = NULL; else save->last_instr = bi->last_app_pc; /* i#1466: remember the first_restore_pc for restore state in pattern mode */ save->first_restore_pc = bi->first_restore_pc; save->check_ignore_unaddr = check_ignore_unaddr; /* i#826: share_xl8_max_diff can change, save it. */ save->share_xl8_max_diff = bi->share_xl8_max_diff; /* store style of instru rather than ask DR to store xl8. * XXX DRi#772: could add flush callback and avoid this save */ save->pattern_4byte_check_only = bi->pattern_4byte_check_only; /* we store the size and assume bbs are contiguous so we can free (i#260) */ ASSERT(bi->first_app_pc != NULL, "first instr should have app pc"); ASSERT(bi->last_app_pc != NULL, "last instr should have app pc"); if (bi->is_repstr_to_loop) /* first is +1 hack */ bi->first_app_pc = bi->last_app_pc; else { ASSERT(bi->last_app_pc >= bi->first_app_pc, "bb should be contiguous w/ increasing pcs"); } save->bb_size = decode_next_pc(drcontext, bi->last_app_pc) - bi->first_app_pc; /* PR 495787: Due to non-precise flushing we can have a flushed bb * removed from the htables and then a new bb created before we received * the deletion event. We can't tell this apart from duplication due to * thread-private copies: but this mechanism should handle that as well, * since our saved info should be deterministic and identical for each * copy. Note that we do not want a new "unreachable event" b/c we need * to keep our bb info around in case the semi-flushed bb hits a fault. */ hashtable_lock(&bb_table); bb_save_add_entry(tag, save); hashtable_unlock(&bb_table); } if (options.pattern != 0) /* pattern is using drreg */ return; /* We do this *after* recording what to restore, b/c this can change the used * fields (i#1458). */ if (added_instru) { restore_aflags_if_live(drcontext, bb, last, NULL, bi); if (bi->reg1.reg != DR_REG_NULL) insert_spill_global(drcontext, bb, last, &bi->reg1, false/*restore*/); if (bi->reg2.reg != DR_REG_NULL) insert_spill_global(drcontext, bb, last, &bi->reg2, false/*restore*/); } }
{ "language": "C" }
// SPDX-License-Identifier: GPL-2.0 /* * Driver for Marvell NETA network card for Armada XP and Armada 370 SoCs. * * U-Boot version: * Copyright (C) 2014-2015 Stefan Roese <sr@denx.de> * * Based on the Linux version which is: * Copyright (C) 2012 Marvell * * Rami Rosen <rosenr@marvell.com> * Thomas Petazzoni <thomas.petazzoni@free-electrons.com> */ #include <common.h> #include <dm.h> #include <net.h> #include <netdev.h> #include <config.h> #include <malloc.h> #include <asm/io.h> #include <linux/errno.h> #include <phy.h> #include <miiphy.h> #include <watchdog.h> #include <asm/arch/cpu.h> #include <asm/arch/soc.h> #include <linux/compat.h> #include <linux/mbus.h> DECLARE_GLOBAL_DATA_PTR; #if !defined(CONFIG_PHYLIB) # error Marvell mvneta requires PHYLIB #endif /* Some linux -> U-Boot compatibility stuff */ #define netdev_err(dev, fmt, args...) \ printf(fmt, ##args) #define netdev_warn(dev, fmt, args...) \ printf(fmt, ##args) #define netdev_info(dev, fmt, args...) \ printf(fmt, ##args) #define CONFIG_NR_CPUS 1 #define ETH_HLEN 14 /* Total octets in header */ /* 2(HW hdr) 14(MAC hdr) 4(CRC) 32(extra for cache prefetch) */ #define WRAP (2 + ETH_HLEN + 4 + 32) #define MTU 1500 #define RX_BUFFER_SIZE (ALIGN(MTU + WRAP, ARCH_DMA_MINALIGN)) #define MVNETA_SMI_TIMEOUT 10000 /* Registers */ #define MVNETA_RXQ_CONFIG_REG(q) (0x1400 + ((q) << 2)) #define MVNETA_RXQ_HW_BUF_ALLOC BIT(1) #define MVNETA_RXQ_PKT_OFFSET_ALL_MASK (0xf << 8) #define MVNETA_RXQ_PKT_OFFSET_MASK(offs) ((offs) << 8) #define MVNETA_RXQ_THRESHOLD_REG(q) (0x14c0 + ((q) << 2)) #define MVNETA_RXQ_NON_OCCUPIED(v) ((v) << 16) #define MVNETA_RXQ_BASE_ADDR_REG(q) (0x1480 + ((q) << 2)) #define MVNETA_RXQ_SIZE_REG(q) (0x14a0 + ((q) << 2)) #define MVNETA_RXQ_BUF_SIZE_SHIFT 19 #define MVNETA_RXQ_BUF_SIZE_MASK (0x1fff << 19) #define MVNETA_RXQ_STATUS_REG(q) (0x14e0 + ((q) << 2)) #define MVNETA_RXQ_OCCUPIED_ALL_MASK 0x3fff #define MVNETA_RXQ_STATUS_UPDATE_REG(q) (0x1500 + ((q) << 2)) #define MVNETA_RXQ_ADD_NON_OCCUPIED_SHIFT 16 #define MVNETA_RXQ_ADD_NON_OCCUPIED_MAX 255 #define MVNETA_PORT_RX_RESET 0x1cc0 #define MVNETA_PORT_RX_DMA_RESET BIT(0) #define MVNETA_PHY_ADDR 0x2000 #define MVNETA_PHY_ADDR_MASK 0x1f #define MVNETA_SMI 0x2004 #define MVNETA_PHY_REG_MASK 0x1f /* SMI register fields */ #define MVNETA_SMI_DATA_OFFS 0 /* Data */ #define MVNETA_SMI_DATA_MASK (0xffff << MVNETA_SMI_DATA_OFFS) #define MVNETA_SMI_DEV_ADDR_OFFS 16 /* PHY device address */ #define MVNETA_SMI_REG_ADDR_OFFS 21 /* PHY device reg addr*/ #define MVNETA_SMI_OPCODE_OFFS 26 /* Write/Read opcode */ #define MVNETA_SMI_OPCODE_READ (1 << MVNETA_SMI_OPCODE_OFFS) #define MVNETA_SMI_READ_VALID (1 << 27) /* Read Valid */ #define MVNETA_SMI_BUSY (1 << 28) /* Busy */ #define MVNETA_MBUS_RETRY 0x2010 #define MVNETA_UNIT_INTR_CAUSE 0x2080 #define MVNETA_UNIT_CONTROL 0x20B0 #define MVNETA_PHY_POLLING_ENABLE BIT(1) #define MVNETA_WIN_BASE(w) (0x2200 + ((w) << 3)) #define MVNETA_WIN_SIZE(w) (0x2204 + ((w) << 3)) #define MVNETA_WIN_REMAP(w) (0x2280 + ((w) << 2)) #define MVNETA_WIN_SIZE_MASK (0xffff0000) #define MVNETA_BASE_ADDR_ENABLE 0x2290 #define MVNETA_BASE_ADDR_ENABLE_BIT 0x1 #define MVNETA_PORT_ACCESS_PROTECT 0x2294 #define MVNETA_PORT_ACCESS_PROTECT_WIN0_RW 0x3 #define MVNETA_PORT_CONFIG 0x2400 #define MVNETA_UNI_PROMISC_MODE BIT(0) #define MVNETA_DEF_RXQ(q) ((q) << 1) #define MVNETA_DEF_RXQ_ARP(q) ((q) << 4) #define MVNETA_TX_UNSET_ERR_SUM BIT(12) #define MVNETA_DEF_RXQ_TCP(q) ((q) << 16) #define MVNETA_DEF_RXQ_UDP(q) ((q) << 19) #define MVNETA_DEF_RXQ_BPDU(q) ((q) << 22) #define MVNETA_RX_CSUM_WITH_PSEUDO_HDR BIT(25) #define MVNETA_PORT_CONFIG_DEFL_VALUE(q) (MVNETA_DEF_RXQ(q) | \ MVNETA_DEF_RXQ_ARP(q) | \ MVNETA_DEF_RXQ_TCP(q) | \ MVNETA_DEF_RXQ_UDP(q) | \ MVNETA_DEF_RXQ_BPDU(q) | \ MVNETA_TX_UNSET_ERR_SUM | \ MVNETA_RX_CSUM_WITH_PSEUDO_HDR) #define MVNETA_PORT_CONFIG_EXTEND 0x2404 #define MVNETA_MAC_ADDR_LOW 0x2414 #define MVNETA_MAC_ADDR_HIGH 0x2418 #define MVNETA_SDMA_CONFIG 0x241c #define MVNETA_SDMA_BRST_SIZE_16 4 #define MVNETA_RX_BRST_SZ_MASK(burst) ((burst) << 1) #define MVNETA_RX_NO_DATA_SWAP BIT(4) #define MVNETA_TX_NO_DATA_SWAP BIT(5) #define MVNETA_DESC_SWAP BIT(6) #define MVNETA_TX_BRST_SZ_MASK(burst) ((burst) << 22) #define MVNETA_PORT_STATUS 0x2444 #define MVNETA_TX_IN_PRGRS BIT(1) #define MVNETA_TX_FIFO_EMPTY BIT(8) #define MVNETA_RX_MIN_FRAME_SIZE 0x247c #define MVNETA_SERDES_CFG 0x24A0 #define MVNETA_SGMII_SERDES_PROTO 0x0cc7 #define MVNETA_QSGMII_SERDES_PROTO 0x0667 #define MVNETA_TYPE_PRIO 0x24bc #define MVNETA_FORCE_UNI BIT(21) #define MVNETA_TXQ_CMD_1 0x24e4 #define MVNETA_TXQ_CMD 0x2448 #define MVNETA_TXQ_DISABLE_SHIFT 8 #define MVNETA_TXQ_ENABLE_MASK 0x000000ff #define MVNETA_ACC_MODE 0x2500 #define MVNETA_CPU_MAP(cpu) (0x2540 + ((cpu) << 2)) #define MVNETA_CPU_RXQ_ACCESS_ALL_MASK 0x000000ff #define MVNETA_CPU_TXQ_ACCESS_ALL_MASK 0x0000ff00 #define MVNETA_RXQ_TIME_COAL_REG(q) (0x2580 + ((q) << 2)) /* Exception Interrupt Port/Queue Cause register */ #define MVNETA_INTR_NEW_CAUSE 0x25a0 #define MVNETA_INTR_NEW_MASK 0x25a4 /* bits 0..7 = TXQ SENT, one bit per queue. * bits 8..15 = RXQ OCCUP, one bit per queue. * bits 16..23 = RXQ FREE, one bit per queue. * bit 29 = OLD_REG_SUM, see old reg ? * bit 30 = TX_ERR_SUM, one bit for 4 ports * bit 31 = MISC_SUM, one bit for 4 ports */ #define MVNETA_TX_INTR_MASK(nr_txqs) (((1 << nr_txqs) - 1) << 0) #define MVNETA_TX_INTR_MASK_ALL (0xff << 0) #define MVNETA_RX_INTR_MASK(nr_rxqs) (((1 << nr_rxqs) - 1) << 8) #define MVNETA_RX_INTR_MASK_ALL (0xff << 8) #define MVNETA_INTR_OLD_CAUSE 0x25a8 #define MVNETA_INTR_OLD_MASK 0x25ac /* Data Path Port/Queue Cause Register */ #define MVNETA_INTR_MISC_CAUSE 0x25b0 #define MVNETA_INTR_MISC_MASK 0x25b4 #define MVNETA_INTR_ENABLE 0x25b8 #define MVNETA_RXQ_CMD 0x2680 #define MVNETA_RXQ_DISABLE_SHIFT 8 #define MVNETA_RXQ_ENABLE_MASK 0x000000ff #define MVETH_TXQ_TOKEN_COUNT_REG(q) (0x2700 + ((q) << 4)) #define MVETH_TXQ_TOKEN_CFG_REG(q) (0x2704 + ((q) << 4)) #define MVNETA_GMAC_CTRL_0 0x2c00 #define MVNETA_GMAC_MAX_RX_SIZE_SHIFT 2 #define MVNETA_GMAC_MAX_RX_SIZE_MASK 0x7ffc #define MVNETA_GMAC0_PORT_ENABLE BIT(0) #define MVNETA_GMAC_CTRL_2 0x2c08 #define MVNETA_GMAC2_PCS_ENABLE BIT(3) #define MVNETA_GMAC2_PORT_RGMII BIT(4) #define MVNETA_GMAC2_PORT_RESET BIT(6) #define MVNETA_GMAC_STATUS 0x2c10 #define MVNETA_GMAC_LINK_UP BIT(0) #define MVNETA_GMAC_SPEED_1000 BIT(1) #define MVNETA_GMAC_SPEED_100 BIT(2) #define MVNETA_GMAC_FULL_DUPLEX BIT(3) #define MVNETA_GMAC_RX_FLOW_CTRL_ENABLE BIT(4) #define MVNETA_GMAC_TX_FLOW_CTRL_ENABLE BIT(5) #define MVNETA_GMAC_RX_FLOW_CTRL_ACTIVE BIT(6) #define MVNETA_GMAC_TX_FLOW_CTRL_ACTIVE BIT(7) #define MVNETA_GMAC_AUTONEG_CONFIG 0x2c0c #define MVNETA_GMAC_FORCE_LINK_DOWN BIT(0) #define MVNETA_GMAC_FORCE_LINK_PASS BIT(1) #define MVNETA_GMAC_FORCE_LINK_UP (BIT(0) | BIT(1)) #define MVNETA_GMAC_IB_BYPASS_AN_EN BIT(3) #define MVNETA_GMAC_CONFIG_MII_SPEED BIT(5) #define MVNETA_GMAC_CONFIG_GMII_SPEED BIT(6) #define MVNETA_GMAC_AN_SPEED_EN BIT(7) #define MVNETA_GMAC_SET_FC_EN BIT(8) #define MVNETA_GMAC_ADVERT_FC_EN BIT(9) #define MVNETA_GMAC_CONFIG_FULL_DUPLEX BIT(12) #define MVNETA_GMAC_AN_DUPLEX_EN BIT(13) #define MVNETA_GMAC_SAMPLE_TX_CFG_EN BIT(15) #define MVNETA_MIB_COUNTERS_BASE 0x3080 #define MVNETA_MIB_LATE_COLLISION 0x7c #define MVNETA_DA_FILT_SPEC_MCAST 0x3400 #define MVNETA_DA_FILT_OTH_MCAST 0x3500 #define MVNETA_DA_FILT_UCAST_BASE 0x3600 #define MVNETA_TXQ_BASE_ADDR_REG(q) (0x3c00 + ((q) << 2)) #define MVNETA_TXQ_SIZE_REG(q) (0x3c20 + ((q) << 2)) #define MVNETA_TXQ_SENT_THRESH_ALL_MASK 0x3fff0000 #define MVNETA_TXQ_SENT_THRESH_MASK(coal) ((coal) << 16) #define MVNETA_TXQ_UPDATE_REG(q) (0x3c60 + ((q) << 2)) #define MVNETA_TXQ_DEC_SENT_SHIFT 16 #define MVNETA_TXQ_STATUS_REG(q) (0x3c40 + ((q) << 2)) #define MVNETA_TXQ_SENT_DESC_SHIFT 16 #define MVNETA_TXQ_SENT_DESC_MASK 0x3fff0000 #define MVNETA_PORT_TX_RESET 0x3cf0 #define MVNETA_PORT_TX_DMA_RESET BIT(0) #define MVNETA_TX_MTU 0x3e0c #define MVNETA_TX_TOKEN_SIZE 0x3e14 #define MVNETA_TX_TOKEN_SIZE_MAX 0xffffffff #define MVNETA_TXQ_TOKEN_SIZE_REG(q) (0x3e40 + ((q) << 2)) #define MVNETA_TXQ_TOKEN_SIZE_MAX 0x7fffffff /* Descriptor ring Macros */ #define MVNETA_QUEUE_NEXT_DESC(q, index) \ (((index) < (q)->last_desc) ? ((index) + 1) : 0) /* Various constants */ /* Coalescing */ #define MVNETA_TXDONE_COAL_PKTS 16 #define MVNETA_RX_COAL_PKTS 32 #define MVNETA_RX_COAL_USEC 100 /* The two bytes Marvell header. Either contains a special value used * by Marvell switches when a specific hardware mode is enabled (not * supported by this driver) or is filled automatically by zeroes on * the RX side. Those two bytes being at the front of the Ethernet * header, they allow to have the IP header aligned on a 4 bytes * boundary automatically: the hardware skips those two bytes on its * own. */ #define MVNETA_MH_SIZE 2 #define MVNETA_VLAN_TAG_LEN 4 #define MVNETA_CPU_D_CACHE_LINE_SIZE 32 #define MVNETA_TX_CSUM_MAX_SIZE 9800 #define MVNETA_ACC_MODE_EXT 1 /* Timeout constants */ #define MVNETA_TX_DISABLE_TIMEOUT_MSEC 1000 #define MVNETA_RX_DISABLE_TIMEOUT_MSEC 1000 #define MVNETA_TX_FIFO_EMPTY_TIMEOUT 10000 #define MVNETA_TX_MTU_MAX 0x3ffff /* Max number of Rx descriptors */ #define MVNETA_MAX_RXD 16 /* Max number of Tx descriptors */ #define MVNETA_MAX_TXD 16 /* descriptor aligned size */ #define MVNETA_DESC_ALIGNED_SIZE 32 struct mvneta_port { void __iomem *base; struct mvneta_rx_queue *rxqs; struct mvneta_tx_queue *txqs; u8 mcast_count[256]; u16 tx_ring_size; u16 rx_ring_size; phy_interface_t phy_interface; unsigned int link; unsigned int duplex; unsigned int speed; int init; int phyaddr; struct phy_device *phydev; struct mii_dev *bus; }; /* The mvneta_tx_desc and mvneta_rx_desc structures describe the * layout of the transmit and reception DMA descriptors, and their * layout is therefore defined by the hardware design */ #define MVNETA_TX_L3_OFF_SHIFT 0 #define MVNETA_TX_IP_HLEN_SHIFT 8 #define MVNETA_TX_L4_UDP BIT(16) #define MVNETA_TX_L3_IP6 BIT(17) #define MVNETA_TXD_IP_CSUM BIT(18) #define MVNETA_TXD_Z_PAD BIT(19) #define MVNETA_TXD_L_DESC BIT(20) #define MVNETA_TXD_F_DESC BIT(21) #define MVNETA_TXD_FLZ_DESC (MVNETA_TXD_Z_PAD | \ MVNETA_TXD_L_DESC | \ MVNETA_TXD_F_DESC) #define MVNETA_TX_L4_CSUM_FULL BIT(30) #define MVNETA_TX_L4_CSUM_NOT BIT(31) #define MVNETA_RXD_ERR_CRC 0x0 #define MVNETA_RXD_ERR_SUMMARY BIT(16) #define MVNETA_RXD_ERR_OVERRUN BIT(17) #define MVNETA_RXD_ERR_LEN BIT(18) #define MVNETA_RXD_ERR_RESOURCE (BIT(17) | BIT(18)) #define MVNETA_RXD_ERR_CODE_MASK (BIT(17) | BIT(18)) #define MVNETA_RXD_L3_IP4 BIT(25) #define MVNETA_RXD_FIRST_LAST_DESC (BIT(26) | BIT(27)) #define MVNETA_RXD_L4_CSUM_OK BIT(30) struct mvneta_tx_desc { u32 command; /* Options used by HW for packet transmitting.*/ u16 reserverd1; /* csum_l4 (for future use) */ u16 data_size; /* Data size of transmitted packet in bytes */ u32 buf_phys_addr; /* Physical addr of transmitted buffer */ u32 reserved2; /* hw_cmd - (for future use, PMT) */ u32 reserved3[4]; /* Reserved - (for future use) */ }; struct mvneta_rx_desc { u32 status; /* Info about received packet */ u16 reserved1; /* pnc_info - (for future use, PnC) */ u16 data_size; /* Size of received packet in bytes */ u32 buf_phys_addr; /* Physical address of the buffer */ u32 reserved2; /* pnc_flow_id (for future use, PnC) */ u32 buf_cookie; /* cookie for access to RX buffer in rx path */ u16 reserved3; /* prefetch_cmd, for future use */ u16 reserved4; /* csum_l4 - (for future use, PnC) */ u32 reserved5; /* pnc_extra PnC (for future use, PnC) */ u32 reserved6; /* hw_cmd (for future use, PnC and HWF) */ }; struct mvneta_tx_queue { /* Number of this TX queue, in the range 0-7 */ u8 id; /* Number of TX DMA descriptors in the descriptor ring */ int size; /* Index of last TX DMA descriptor that was inserted */ int txq_put_index; /* Index of the TX DMA descriptor to be cleaned up */ int txq_get_index; /* Virtual address of the TX DMA descriptors array */ struct mvneta_tx_desc *descs; /* DMA address of the TX DMA descriptors array */ dma_addr_t descs_phys; /* Index of the last TX DMA descriptor */ int last_desc; /* Index of the next TX DMA descriptor to process */ int next_desc_to_proc; }; struct mvneta_rx_queue { /* rx queue number, in the range 0-7 */ u8 id; /* num of rx descriptors in the rx descriptor ring */ int size; /* Virtual address of the RX DMA descriptors array */ struct mvneta_rx_desc *descs; /* DMA address of the RX DMA descriptors array */ dma_addr_t descs_phys; /* Index of the last RX DMA descriptor */ int last_desc; /* Index of the next RX DMA descriptor to process */ int next_desc_to_proc; }; /* U-Boot doesn't use the queues, so set the number to 1 */ static int rxq_number = 1; static int txq_number = 1; static int rxq_def; struct buffer_location { struct mvneta_tx_desc *tx_descs; struct mvneta_rx_desc *rx_descs; u32 rx_buffers; }; /* * All 4 interfaces use the same global buffer, since only one interface * can be enabled at once */ static struct buffer_location buffer_loc; /* * Page table entries are set to 1MB, or multiples of 1MB * (not < 1MB). driver uses less bd's so use 1MB bdspace. */ #define BD_SPACE (1 << 20) /* * Dummy implementation that can be overwritten by a board * specific function */ __weak int board_network_enable(struct mii_dev *bus) { return 0; } /* Utility/helper methods */ /* Write helper method */ static void mvreg_write(struct mvneta_port *pp, u32 offset, u32 data) { writel(data, pp->base + offset); } /* Read helper method */ static u32 mvreg_read(struct mvneta_port *pp, u32 offset) { return readl(pp->base + offset); } /* Clear all MIB counters */ static void mvneta_mib_counters_clear(struct mvneta_port *pp) { int i; /* Perform dummy reads from MIB counters */ for (i = 0; i < MVNETA_MIB_LATE_COLLISION; i += 4) mvreg_read(pp, (MVNETA_MIB_COUNTERS_BASE + i)); } /* Rx descriptors helper methods */ /* Checks whether the RX descriptor having this status is both the first * and the last descriptor for the RX packet. Each RX packet is currently * received through a single RX descriptor, so not having each RX * descriptor with its first and last bits set is an error */ static int mvneta_rxq_desc_is_first_last(u32 status) { return (status & MVNETA_RXD_FIRST_LAST_DESC) == MVNETA_RXD_FIRST_LAST_DESC; } /* Add number of descriptors ready to receive new packets */ static void mvneta_rxq_non_occup_desc_add(struct mvneta_port *pp, struct mvneta_rx_queue *rxq, int ndescs) { /* Only MVNETA_RXQ_ADD_NON_OCCUPIED_MAX (255) descriptors can * be added at once */ while (ndescs > MVNETA_RXQ_ADD_NON_OCCUPIED_MAX) { mvreg_write(pp, MVNETA_RXQ_STATUS_UPDATE_REG(rxq->id), (MVNETA_RXQ_ADD_NON_OCCUPIED_MAX << MVNETA_RXQ_ADD_NON_OCCUPIED_SHIFT)); ndescs -= MVNETA_RXQ_ADD_NON_OCCUPIED_MAX; } mvreg_write(pp, MVNETA_RXQ_STATUS_UPDATE_REG(rxq->id), (ndescs << MVNETA_RXQ_ADD_NON_OCCUPIED_SHIFT)); } /* Get number of RX descriptors occupied by received packets */ static int mvneta_rxq_busy_desc_num_get(struct mvneta_port *pp, struct mvneta_rx_queue *rxq) { u32 val; val = mvreg_read(pp, MVNETA_RXQ_STATUS_REG(rxq->id)); return val & MVNETA_RXQ_OCCUPIED_ALL_MASK; } /* Update num of rx desc called upon return from rx path or * from mvneta_rxq_drop_pkts(). */ static void mvneta_rxq_desc_num_update(struct mvneta_port *pp, struct mvneta_rx_queue *rxq, int rx_done, int rx_filled) { u32 val; if ((rx_done <= 0xff) && (rx_filled <= 0xff)) { val = rx_done | (rx_filled << MVNETA_RXQ_ADD_NON_OCCUPIED_SHIFT); mvreg_write(pp, MVNETA_RXQ_STATUS_UPDATE_REG(rxq->id), val); return; } /* Only 255 descriptors can be added at once */ while ((rx_done > 0) || (rx_filled > 0)) { if (rx_done <= 0xff) { val = rx_done; rx_done = 0; } else { val = 0xff; rx_done -= 0xff; } if (rx_filled <= 0xff) { val |= rx_filled << MVNETA_RXQ_ADD_NON_OCCUPIED_SHIFT; rx_filled = 0; } else { val |= 0xff << MVNETA_RXQ_ADD_NON_OCCUPIED_SHIFT; rx_filled -= 0xff; } mvreg_write(pp, MVNETA_RXQ_STATUS_UPDATE_REG(rxq->id), val); } } /* Get pointer to next RX descriptor to be processed by SW */ static struct mvneta_rx_desc * mvneta_rxq_next_desc_get(struct mvneta_rx_queue *rxq) { int rx_desc = rxq->next_desc_to_proc; rxq->next_desc_to_proc = MVNETA_QUEUE_NEXT_DESC(rxq, rx_desc); return rxq->descs + rx_desc; } /* Tx descriptors helper methods */ /* Update HW with number of TX descriptors to be sent */ static void mvneta_txq_pend_desc_add(struct mvneta_port *pp, struct mvneta_tx_queue *txq, int pend_desc) { u32 val; /* Only 255 descriptors can be added at once ; Assume caller * process TX descriptors in quanta less than 256 */ val = pend_desc; mvreg_write(pp, MVNETA_TXQ_UPDATE_REG(txq->id), val); } /* Get pointer to next TX descriptor to be processed (send) by HW */ static struct mvneta_tx_desc * mvneta_txq_next_desc_get(struct mvneta_tx_queue *txq) { int tx_desc = txq->next_desc_to_proc; txq->next_desc_to_proc = MVNETA_QUEUE_NEXT_DESC(txq, tx_desc); return txq->descs + tx_desc; } /* Set rxq buf size */ static void mvneta_rxq_buf_size_set(struct mvneta_port *pp, struct mvneta_rx_queue *rxq, int buf_size) { u32 val; val = mvreg_read(pp, MVNETA_RXQ_SIZE_REG(rxq->id)); val &= ~MVNETA_RXQ_BUF_SIZE_MASK; val |= ((buf_size >> 3) << MVNETA_RXQ_BUF_SIZE_SHIFT); mvreg_write(pp, MVNETA_RXQ_SIZE_REG(rxq->id), val); } static int mvneta_port_is_fixed_link(struct mvneta_port *pp) { /* phy_addr is set to invalid value for fixed link */ return pp->phyaddr > PHY_MAX_ADDR; } /* Start the Ethernet port RX and TX activity */ static void mvneta_port_up(struct mvneta_port *pp) { int queue; u32 q_map; /* Enable all initialized TXs. */ mvneta_mib_counters_clear(pp); q_map = 0; for (queue = 0; queue < txq_number; queue++) { struct mvneta_tx_queue *txq = &pp->txqs[queue]; if (txq->descs != NULL) q_map |= (1 << queue); } mvreg_write(pp, MVNETA_TXQ_CMD, q_map); /* Enable all initialized RXQs. */ q_map = 0; for (queue = 0; queue < rxq_number; queue++) { struct mvneta_rx_queue *rxq = &pp->rxqs[queue]; if (rxq->descs != NULL) q_map |= (1 << queue); } mvreg_write(pp, MVNETA_RXQ_CMD, q_map); } /* Stop the Ethernet port activity */ static void mvneta_port_down(struct mvneta_port *pp) { u32 val; int count; /* Stop Rx port activity. Check port Rx activity. */ val = mvreg_read(pp, MVNETA_RXQ_CMD) & MVNETA_RXQ_ENABLE_MASK; /* Issue stop command for active channels only */ if (val != 0) mvreg_write(pp, MVNETA_RXQ_CMD, val << MVNETA_RXQ_DISABLE_SHIFT); /* Wait for all Rx activity to terminate. */ count = 0; do { if (count++ >= MVNETA_RX_DISABLE_TIMEOUT_MSEC) { netdev_warn(pp->dev, "TIMEOUT for RX stopped ! rx_queue_cmd: 0x08%x\n", val); break; } mdelay(1); val = mvreg_read(pp, MVNETA_RXQ_CMD); } while (val & 0xff); /* Stop Tx port activity. Check port Tx activity. Issue stop * command for active channels only */ val = (mvreg_read(pp, MVNETA_TXQ_CMD)) & MVNETA_TXQ_ENABLE_MASK; if (val != 0) mvreg_write(pp, MVNETA_TXQ_CMD, (val << MVNETA_TXQ_DISABLE_SHIFT)); /* Wait for all Tx activity to terminate. */ count = 0; do { if (count++ >= MVNETA_TX_DISABLE_TIMEOUT_MSEC) { netdev_warn(pp->dev, "TIMEOUT for TX stopped status=0x%08x\n", val); break; } mdelay(1); /* Check TX Command reg that all Txqs are stopped */ val = mvreg_read(pp, MVNETA_TXQ_CMD); } while (val & 0xff); /* Double check to verify that TX FIFO is empty */ count = 0; do { if (count++ >= MVNETA_TX_FIFO_EMPTY_TIMEOUT) { netdev_warn(pp->dev, "TX FIFO empty timeout status=0x08%x\n", val); break; } mdelay(1); val = mvreg_read(pp, MVNETA_PORT_STATUS); } while (!(val & MVNETA_TX_FIFO_EMPTY) && (val & MVNETA_TX_IN_PRGRS)); udelay(200); } /* Enable the port by setting the port enable bit of the MAC control register */ static void mvneta_port_enable(struct mvneta_port *pp) { u32 val; /* Enable port */ val = mvreg_read(pp, MVNETA_GMAC_CTRL_0); val |= MVNETA_GMAC0_PORT_ENABLE; mvreg_write(pp, MVNETA_GMAC_CTRL_0, val); } /* Disable the port and wait for about 200 usec before retuning */ static void mvneta_port_disable(struct mvneta_port *pp) { u32 val; /* Reset the Enable bit in the Serial Control Register */ val = mvreg_read(pp, MVNETA_GMAC_CTRL_0); val &= ~MVNETA_GMAC0_PORT_ENABLE; mvreg_write(pp, MVNETA_GMAC_CTRL_0, val); udelay(200); } /* Multicast tables methods */ /* Set all entries in Unicast MAC Table; queue==-1 means reject all */ static void mvneta_set_ucast_table(struct mvneta_port *pp, int queue) { int offset; u32 val; if (queue == -1) { val = 0; } else { val = 0x1 | (queue << 1); val |= (val << 24) | (val << 16) | (val << 8); } for (offset = 0; offset <= 0xc; offset += 4) mvreg_write(pp, MVNETA_DA_FILT_UCAST_BASE + offset, val); } /* Set all entries in Special Multicast MAC Table; queue==-1 means reject all */ static void mvneta_set_special_mcast_table(struct mvneta_port *pp, int queue) { int offset; u32 val; if (queue == -1) { val = 0; } else { val = 0x1 | (queue << 1); val |= (val << 24) | (val << 16) | (val << 8); } for (offset = 0; offset <= 0xfc; offset += 4) mvreg_write(pp, MVNETA_DA_FILT_SPEC_MCAST + offset, val); } /* Set all entries in Other Multicast MAC Table. queue==-1 means reject all */ static void mvneta_set_other_mcast_table(struct mvneta_port *pp, int queue) { int offset; u32 val; if (queue == -1) { memset(pp->mcast_count, 0, sizeof(pp->mcast_count)); val = 0; } else { memset(pp->mcast_count, 1, sizeof(pp->mcast_count)); val = 0x1 | (queue << 1); val |= (val << 24) | (val << 16) | (val << 8); } for (offset = 0; offset <= 0xfc; offset += 4) mvreg_write(pp, MVNETA_DA_FILT_OTH_MCAST + offset, val); } /* This method sets defaults to the NETA port: * Clears interrupt Cause and Mask registers. * Clears all MAC tables. * Sets defaults to all registers. * Resets RX and TX descriptor rings. * Resets PHY. * This method can be called after mvneta_port_down() to return the port * settings to defaults. */ static void mvneta_defaults_set(struct mvneta_port *pp) { int cpu; int queue; u32 val; /* Clear all Cause registers */ mvreg_write(pp, MVNETA_INTR_NEW_CAUSE, 0); mvreg_write(pp, MVNETA_INTR_OLD_CAUSE, 0); mvreg_write(pp, MVNETA_INTR_MISC_CAUSE, 0); /* Mask all interrupts */ mvreg_write(pp, MVNETA_INTR_NEW_MASK, 0); mvreg_write(pp, MVNETA_INTR_OLD_MASK, 0); mvreg_write(pp, MVNETA_INTR_MISC_MASK, 0); mvreg_write(pp, MVNETA_INTR_ENABLE, 0); /* Enable MBUS Retry bit16 */ mvreg_write(pp, MVNETA_MBUS_RETRY, 0x20); /* Set CPU queue access map - all CPUs have access to all RX * queues and to all TX queues */ for (cpu = 0; cpu < CONFIG_NR_CPUS; cpu++) mvreg_write(pp, MVNETA_CPU_MAP(cpu), (MVNETA_CPU_RXQ_ACCESS_ALL_MASK | MVNETA_CPU_TXQ_ACCESS_ALL_MASK)); /* Reset RX and TX DMAs */ mvreg_write(pp, MVNETA_PORT_RX_RESET, MVNETA_PORT_RX_DMA_RESET); mvreg_write(pp, MVNETA_PORT_TX_RESET, MVNETA_PORT_TX_DMA_RESET); /* Disable Legacy WRR, Disable EJP, Release from reset */ mvreg_write(pp, MVNETA_TXQ_CMD_1, 0); for (queue = 0; queue < txq_number; queue++) { mvreg_write(pp, MVETH_TXQ_TOKEN_COUNT_REG(queue), 0); mvreg_write(pp, MVETH_TXQ_TOKEN_CFG_REG(queue), 0); } mvreg_write(pp, MVNETA_PORT_TX_RESET, 0); mvreg_write(pp, MVNETA_PORT_RX_RESET, 0); /* Set Port Acceleration Mode */ val = MVNETA_ACC_MODE_EXT; mvreg_write(pp, MVNETA_ACC_MODE, val); /* Update val of portCfg register accordingly with all RxQueue types */ val = MVNETA_PORT_CONFIG_DEFL_VALUE(rxq_def); mvreg_write(pp, MVNETA_PORT_CONFIG, val); val = 0; mvreg_write(pp, MVNETA_PORT_CONFIG_EXTEND, val); mvreg_write(pp, MVNETA_RX_MIN_FRAME_SIZE, 64); /* Build PORT_SDMA_CONFIG_REG */ val = 0; /* Default burst size */ val |= MVNETA_TX_BRST_SZ_MASK(MVNETA_SDMA_BRST_SIZE_16); val |= MVNETA_RX_BRST_SZ_MASK(MVNETA_SDMA_BRST_SIZE_16); val |= MVNETA_RX_NO_DATA_SWAP | MVNETA_TX_NO_DATA_SWAP; /* Assign port SDMA configuration */ mvreg_write(pp, MVNETA_SDMA_CONFIG, val); /* Enable PHY polling in hardware if not in fixed-link mode */ if (!mvneta_port_is_fixed_link(pp)) { val = mvreg_read(pp, MVNETA_UNIT_CONTROL); val |= MVNETA_PHY_POLLING_ENABLE; mvreg_write(pp, MVNETA_UNIT_CONTROL, val); } mvneta_set_ucast_table(pp, -1); mvneta_set_special_mcast_table(pp, -1); mvneta_set_other_mcast_table(pp, -1); } /* Set unicast address */ static void mvneta_set_ucast_addr(struct mvneta_port *pp, u8 last_nibble, int queue) { unsigned int unicast_reg; unsigned int tbl_offset; unsigned int reg_offset; /* Locate the Unicast table entry */ last_nibble = (0xf & last_nibble); /* offset from unicast tbl base */ tbl_offset = (last_nibble / 4) * 4; /* offset within the above reg */ reg_offset = last_nibble % 4; unicast_reg = mvreg_read(pp, (MVNETA_DA_FILT_UCAST_BASE + tbl_offset)); if (queue == -1) { /* Clear accepts frame bit at specified unicast DA tbl entry */ unicast_reg &= ~(0xff << (8 * reg_offset)); } else { unicast_reg &= ~(0xff << (8 * reg_offset)); unicast_reg |= ((0x01 | (queue << 1)) << (8 * reg_offset)); } mvreg_write(pp, (MVNETA_DA_FILT_UCAST_BASE + tbl_offset), unicast_reg); } /* Set mac address */ static void mvneta_mac_addr_set(struct mvneta_port *pp, unsigned char *addr, int queue) { unsigned int mac_h; unsigned int mac_l; if (queue != -1) { mac_l = (addr[4] << 8) | (addr[5]); mac_h = (addr[0] << 24) | (addr[1] << 16) | (addr[2] << 8) | (addr[3] << 0); mvreg_write(pp, MVNETA_MAC_ADDR_LOW, mac_l); mvreg_write(pp, MVNETA_MAC_ADDR_HIGH, mac_h); } /* Accept frames of this address */ mvneta_set_ucast_addr(pp, addr[5], queue); } static int mvneta_write_hwaddr(struct udevice *dev) { mvneta_mac_addr_set(dev_get_priv(dev), ((struct eth_pdata *)dev_get_platdata(dev))->enetaddr, rxq_def); return 0; } /* Handle rx descriptor fill by setting buf_cookie and buf_phys_addr */ static void mvneta_rx_desc_fill(struct mvneta_rx_desc *rx_desc, u32 phys_addr, u32 cookie) { rx_desc->buf_cookie = cookie; rx_desc->buf_phys_addr = phys_addr; } /* Decrement sent descriptors counter */ static void mvneta_txq_sent_desc_dec(struct mvneta_port *pp, struct mvneta_tx_queue *txq, int sent_desc) { u32 val; /* Only 255 TX descriptors can be updated at once */ while (sent_desc > 0xff) { val = 0xff << MVNETA_TXQ_DEC_SENT_SHIFT; mvreg_write(pp, MVNETA_TXQ_UPDATE_REG(txq->id), val); sent_desc = sent_desc - 0xff; } val = sent_desc << MVNETA_TXQ_DEC_SENT_SHIFT; mvreg_write(pp, MVNETA_TXQ_UPDATE_REG(txq->id), val); } /* Get number of TX descriptors already sent by HW */ static int mvneta_txq_sent_desc_num_get(struct mvneta_port *pp, struct mvneta_tx_queue *txq) { u32 val; int sent_desc; val = mvreg_read(pp, MVNETA_TXQ_STATUS_REG(txq->id)); sent_desc = (val & MVNETA_TXQ_SENT_DESC_MASK) >> MVNETA_TXQ_SENT_DESC_SHIFT; return sent_desc; } /* Display more error info */ static void mvneta_rx_error(struct mvneta_port *pp, struct mvneta_rx_desc *rx_desc) { u32 status = rx_desc->status; if (!mvneta_rxq_desc_is_first_last(status)) { netdev_err(pp->dev, "bad rx status %08x (buffer oversize), size=%d\n", status, rx_desc->data_size); return; } switch (status & MVNETA_RXD_ERR_CODE_MASK) { case MVNETA_RXD_ERR_CRC: netdev_err(pp->dev, "bad rx status %08x (crc error), size=%d\n", status, rx_desc->data_size); break; case MVNETA_RXD_ERR_OVERRUN: netdev_err(pp->dev, "bad rx status %08x (overrun error), size=%d\n", status, rx_desc->data_size); break; case MVNETA_RXD_ERR_LEN: netdev_err(pp->dev, "bad rx status %08x (max frame length error), size=%d\n", status, rx_desc->data_size); break; case MVNETA_RXD_ERR_RESOURCE: netdev_err(pp->dev, "bad rx status %08x (resource error), size=%d\n", status, rx_desc->data_size); break; } } static struct mvneta_rx_queue *mvneta_rxq_handle_get(struct mvneta_port *pp, int rxq) { return &pp->rxqs[rxq]; } /* Drop packets received by the RXQ and free buffers */ static void mvneta_rxq_drop_pkts(struct mvneta_port *pp, struct mvneta_rx_queue *rxq) { int rx_done; rx_done = mvneta_rxq_busy_desc_num_get(pp, rxq); if (rx_done) mvneta_rxq_desc_num_update(pp, rxq, rx_done, rx_done); } /* Handle rxq fill: allocates rxq skbs; called when initializing a port */ static int mvneta_rxq_fill(struct mvneta_port *pp, struct mvneta_rx_queue *rxq, int num) { int i; for (i = 0; i < num; i++) { u32 addr; /* U-Boot special: Fill in the rx buffer addresses */ addr = buffer_loc.rx_buffers + (i * RX_BUFFER_SIZE); mvneta_rx_desc_fill(rxq->descs + i, addr, addr); } /* Add this number of RX descriptors as non occupied (ready to * get packets) */ mvneta_rxq_non_occup_desc_add(pp, rxq, i); return 0; } /* Rx/Tx queue initialization/cleanup methods */ /* Create a specified RX queue */ static int mvneta_rxq_init(struct mvneta_port *pp, struct mvneta_rx_queue *rxq) { rxq->size = pp->rx_ring_size; /* Allocate memory for RX descriptors */ rxq->descs_phys = (dma_addr_t)rxq->descs; if (rxq->descs == NULL) return -ENOMEM; WARN_ON(rxq->descs != PTR_ALIGN(rxq->descs, ARCH_DMA_MINALIGN)); rxq->last_desc = rxq->size - 1; /* Set Rx descriptors queue starting address */ mvreg_write(pp, MVNETA_RXQ_BASE_ADDR_REG(rxq->id), rxq->descs_phys); mvreg_write(pp, MVNETA_RXQ_SIZE_REG(rxq->id), rxq->size); /* Fill RXQ with buffers from RX pool */ mvneta_rxq_buf_size_set(pp, rxq, RX_BUFFER_SIZE); mvneta_rxq_fill(pp, rxq, rxq->size); return 0; } /* Cleanup Rx queue */ static void mvneta_rxq_deinit(struct mvneta_port *pp, struct mvneta_rx_queue *rxq) { mvneta_rxq_drop_pkts(pp, rxq); rxq->descs = NULL; rxq->last_desc = 0; rxq->next_desc_to_proc = 0; rxq->descs_phys = 0; } /* Create and initialize a tx queue */ static int mvneta_txq_init(struct mvneta_port *pp, struct mvneta_tx_queue *txq) { txq->size = pp->tx_ring_size; /* Allocate memory for TX descriptors */ txq->descs_phys = (dma_addr_t)txq->descs; if (txq->descs == NULL) return -ENOMEM; WARN_ON(txq->descs != PTR_ALIGN(txq->descs, ARCH_DMA_MINALIGN)); txq->last_desc = txq->size - 1; /* Set maximum bandwidth for enabled TXQs */ mvreg_write(pp, MVETH_TXQ_TOKEN_CFG_REG(txq->id), 0x03ffffff); mvreg_write(pp, MVETH_TXQ_TOKEN_COUNT_REG(txq->id), 0x3fffffff); /* Set Tx descriptors queue starting address */ mvreg_write(pp, MVNETA_TXQ_BASE_ADDR_REG(txq->id), txq->descs_phys); mvreg_write(pp, MVNETA_TXQ_SIZE_REG(txq->id), txq->size); return 0; } /* Free allocated resources when mvneta_txq_init() fails to allocate memory*/ static void mvneta_txq_deinit(struct mvneta_port *pp, struct mvneta_tx_queue *txq) { txq->descs = NULL; txq->last_desc = 0; txq->next_desc_to_proc = 0; txq->descs_phys = 0; /* Set minimum bandwidth for disabled TXQs */ mvreg_write(pp, MVETH_TXQ_TOKEN_CFG_REG(txq->id), 0); mvreg_write(pp, MVETH_TXQ_TOKEN_COUNT_REG(txq->id), 0); /* Set Tx descriptors queue starting address and size */ mvreg_write(pp, MVNETA_TXQ_BASE_ADDR_REG(txq->id), 0); mvreg_write(pp, MVNETA_TXQ_SIZE_REG(txq->id), 0); } /* Cleanup all Tx queues */ static void mvneta_cleanup_txqs(struct mvneta_port *pp) { int queue; for (queue = 0; queue < txq_number; queue++) mvneta_txq_deinit(pp, &pp->txqs[queue]); } /* Cleanup all Rx queues */ static void mvneta_cleanup_rxqs(struct mvneta_port *pp) { int queue; for (queue = 0; queue < rxq_number; queue++) mvneta_rxq_deinit(pp, &pp->rxqs[queue]); } /* Init all Rx queues */ static int mvneta_setup_rxqs(struct mvneta_port *pp) { int queue; for (queue = 0; queue < rxq_number; queue++) { int err = mvneta_rxq_init(pp, &pp->rxqs[queue]); if (err) { netdev_err(pp->dev, "%s: can't create rxq=%d\n", __func__, queue); mvneta_cleanup_rxqs(pp); return err; } } return 0; } /* Init all tx queues */ static int mvneta_setup_txqs(struct mvneta_port *pp) { int queue; for (queue = 0; queue < txq_number; queue++) { int err = mvneta_txq_init(pp, &pp->txqs[queue]); if (err) { netdev_err(pp->dev, "%s: can't create txq=%d\n", __func__, queue); mvneta_cleanup_txqs(pp); return err; } } return 0; } static void mvneta_start_dev(struct mvneta_port *pp) { /* start the Rx/Tx activity */ mvneta_port_enable(pp); } static void mvneta_adjust_link(struct udevice *dev) { struct mvneta_port *pp = dev_get_priv(dev); struct phy_device *phydev = pp->phydev; int status_change = 0; if (mvneta_port_is_fixed_link(pp)) { debug("Using fixed link, skip link adjust\n"); return; } if (phydev->link) { if ((pp->speed != phydev->speed) || (pp->duplex != phydev->duplex)) { u32 val; val = mvreg_read(pp, MVNETA_GMAC_AUTONEG_CONFIG); val &= ~(MVNETA_GMAC_CONFIG_MII_SPEED | MVNETA_GMAC_CONFIG_GMII_SPEED | MVNETA_GMAC_CONFIG_FULL_DUPLEX | MVNETA_GMAC_AN_SPEED_EN | MVNETA_GMAC_AN_DUPLEX_EN); if (phydev->duplex) val |= MVNETA_GMAC_CONFIG_FULL_DUPLEX; if (phydev->speed == SPEED_1000) val |= MVNETA_GMAC_CONFIG_GMII_SPEED; else val |= MVNETA_GMAC_CONFIG_MII_SPEED; mvreg_write(pp, MVNETA_GMAC_AUTONEG_CONFIG, val); pp->duplex = phydev->duplex; pp->speed = phydev->speed; } } if (phydev->link != pp->link) { if (!phydev->link) { pp->duplex = -1; pp->speed = 0; } pp->link = phydev->link; status_change = 1; } if (status_change) { if (phydev->link) { u32 val = mvreg_read(pp, MVNETA_GMAC_AUTONEG_CONFIG); val |= (MVNETA_GMAC_FORCE_LINK_PASS | MVNETA_GMAC_FORCE_LINK_DOWN); mvreg_write(pp, MVNETA_GMAC_AUTONEG_CONFIG, val); mvneta_port_up(pp); } else { mvneta_port_down(pp); } } } static int mvneta_open(struct udevice *dev) { struct mvneta_port *pp = dev_get_priv(dev); int ret; ret = mvneta_setup_rxqs(pp); if (ret) return ret; ret = mvneta_setup_txqs(pp); if (ret) return ret; mvneta_adjust_link(dev); mvneta_start_dev(pp); return 0; } /* Initialize hw */ static int mvneta_init2(struct mvneta_port *pp) { int queue; /* Disable port */ mvneta_port_disable(pp); /* Set port default values */ mvneta_defaults_set(pp); pp->txqs = kzalloc(txq_number * sizeof(struct mvneta_tx_queue), GFP_KERNEL); if (!pp->txqs) return -ENOMEM; /* U-Boot special: use preallocated area */ pp->txqs[0].descs = buffer_loc.tx_descs; /* Initialize TX descriptor rings */ for (queue = 0; queue < txq_number; queue++) { struct mvneta_tx_queue *txq = &pp->txqs[queue]; txq->id = queue; txq->size = pp->tx_ring_size; } pp->rxqs = kzalloc(rxq_number * sizeof(struct mvneta_rx_queue), GFP_KERNEL); if (!pp->rxqs) { kfree(pp->txqs); return -ENOMEM; } /* U-Boot special: use preallocated area */ pp->rxqs[0].descs = buffer_loc.rx_descs; /* Create Rx descriptor rings */ for (queue = 0; queue < rxq_number; queue++) { struct mvneta_rx_queue *rxq = &pp->rxqs[queue]; rxq->id = queue; rxq->size = pp->rx_ring_size; } return 0; } /* platform glue : initialize decoding windows */ /* * Not like A380, in Armada3700, there are two layers of decode windows for GBE: * First layer is: GbE Address window that resides inside the GBE unit, * Second layer is: Fabric address window which is located in the NIC400 * (South Fabric). * To simplify the address decode configuration for Armada3700, we bypass the * first layer of GBE decode window by setting the first window to 4GB. */ static void mvneta_bypass_mbus_windows(struct mvneta_port *pp) { /* * Set window size to 4GB, to bypass GBE address decode, leave the * work to MBUS decode window */ mvreg_write(pp, MVNETA_WIN_SIZE(0), MVNETA_WIN_SIZE_MASK); /* Enable GBE address decode window 0 by set bit 0 to 0 */ clrbits_le32(pp->base + MVNETA_BASE_ADDR_ENABLE, MVNETA_BASE_ADDR_ENABLE_BIT); /* Set GBE address decode window 0 to full Access (read or write) */ setbits_le32(pp->base + MVNETA_PORT_ACCESS_PROTECT, MVNETA_PORT_ACCESS_PROTECT_WIN0_RW); } static void mvneta_conf_mbus_windows(struct mvneta_port *pp) { const struct mbus_dram_target_info *dram; u32 win_enable; u32 win_protect; int i; dram = mvebu_mbus_dram_info(); for (i = 0; i < 6; i++) { mvreg_write(pp, MVNETA_WIN_BASE(i), 0); mvreg_write(pp, MVNETA_WIN_SIZE(i), 0); if (i < 4) mvreg_write(pp, MVNETA_WIN_REMAP(i), 0); } win_enable = 0x3f; win_protect = 0; for (i = 0; i < dram->num_cs; i++) { const struct mbus_dram_window *cs = dram->cs + i; mvreg_write(pp, MVNETA_WIN_BASE(i), (cs->base & 0xffff0000) | (cs->mbus_attr << 8) | dram->mbus_dram_target_id); mvreg_write(pp, MVNETA_WIN_SIZE(i), (cs->size - 1) & 0xffff0000); win_enable &= ~(1 << i); win_protect |= 3 << (2 * i); } mvreg_write(pp, MVNETA_BASE_ADDR_ENABLE, win_enable); } /* Power up the port */ static int mvneta_port_power_up(struct mvneta_port *pp, int phy_mode) { u32 ctrl; /* MAC Cause register should be cleared */ mvreg_write(pp, MVNETA_UNIT_INTR_CAUSE, 0); ctrl = mvreg_read(pp, MVNETA_GMAC_CTRL_2); /* Even though it might look weird, when we're configured in * SGMII or QSGMII mode, the RGMII bit needs to be set. */ switch (phy_mode) { case PHY_INTERFACE_MODE_QSGMII: mvreg_write(pp, MVNETA_SERDES_CFG, MVNETA_QSGMII_SERDES_PROTO); ctrl |= MVNETA_GMAC2_PCS_ENABLE | MVNETA_GMAC2_PORT_RGMII; break; case PHY_INTERFACE_MODE_SGMII: mvreg_write(pp, MVNETA_SERDES_CFG, MVNETA_SGMII_SERDES_PROTO); ctrl |= MVNETA_GMAC2_PCS_ENABLE | MVNETA_GMAC2_PORT_RGMII; break; case PHY_INTERFACE_MODE_RGMII: case PHY_INTERFACE_MODE_RGMII_ID: ctrl |= MVNETA_GMAC2_PORT_RGMII; break; default: return -EINVAL; } /* Cancel Port Reset */ ctrl &= ~MVNETA_GMAC2_PORT_RESET; mvreg_write(pp, MVNETA_GMAC_CTRL_2, ctrl); while ((mvreg_read(pp, MVNETA_GMAC_CTRL_2) & MVNETA_GMAC2_PORT_RESET) != 0) continue; return 0; } /* Device initialization routine */ static int mvneta_init(struct udevice *dev) { struct eth_pdata *pdata = dev_get_platdata(dev); struct mvneta_port *pp = dev_get_priv(dev); int err; pp->tx_ring_size = MVNETA_MAX_TXD; pp->rx_ring_size = MVNETA_MAX_RXD; err = mvneta_init2(pp); if (err < 0) { dev_err(&pdev->dev, "can't init eth hal\n"); return err; } mvneta_mac_addr_set(pp, pdata->enetaddr, rxq_def); err = mvneta_port_power_up(pp, pp->phy_interface); if (err < 0) { dev_err(&pdev->dev, "can't power up port\n"); return err; } /* Call open() now as it needs to be done before runing send() */ mvneta_open(dev); return 0; } /* U-Boot only functions follow here */ /* SMI / MDIO functions */ static int smi_wait_ready(struct mvneta_port *pp) { u32 timeout = MVNETA_SMI_TIMEOUT; u32 smi_reg; /* wait till the SMI is not busy */ do { /* read smi register */ smi_reg = mvreg_read(pp, MVNETA_SMI); if (timeout-- == 0) { printf("Error: SMI busy timeout\n"); return -EFAULT; } } while (smi_reg & MVNETA_SMI_BUSY); return 0; } /* * mvneta_mdio_read - miiphy_read callback function. * * Returns 16bit phy register value, or 0xffff on error */ static int mvneta_mdio_read(struct mii_dev *bus, int addr, int devad, int reg) { struct mvneta_port *pp = bus->priv; u32 smi_reg; u32 timeout; /* check parameters */ if (addr > MVNETA_PHY_ADDR_MASK) { printf("Error: Invalid PHY address %d\n", addr); return -EFAULT; } if (reg > MVNETA_PHY_REG_MASK) { printf("Err: Invalid register offset %d\n", reg); return -EFAULT; } /* wait till the SMI is not busy */ if (smi_wait_ready(pp) < 0) return -EFAULT; /* fill the phy address and regiser offset and read opcode */ smi_reg = (addr << MVNETA_SMI_DEV_ADDR_OFFS) | (reg << MVNETA_SMI_REG_ADDR_OFFS) | MVNETA_SMI_OPCODE_READ; /* write the smi register */ mvreg_write(pp, MVNETA_SMI, smi_reg); /* wait till read value is ready */ timeout = MVNETA_SMI_TIMEOUT; do { /* read smi register */ smi_reg = mvreg_read(pp, MVNETA_SMI); if (timeout-- == 0) { printf("Err: SMI read ready timeout\n"); return -EFAULT; } } while (!(smi_reg & MVNETA_SMI_READ_VALID)); /* Wait for the data to update in the SMI register */ for (timeout = 0; timeout < MVNETA_SMI_TIMEOUT; timeout++) ; return mvreg_read(pp, MVNETA_SMI) & MVNETA_SMI_DATA_MASK; } /* * mvneta_mdio_write - miiphy_write callback function. * * Returns 0 if write succeed, -EINVAL on bad parameters * -ETIME on timeout */ static int mvneta_mdio_write(struct mii_dev *bus, int addr, int devad, int reg, u16 value) { struct mvneta_port *pp = bus->priv; u32 smi_reg; /* check parameters */ if (addr > MVNETA_PHY_ADDR_MASK) { printf("Error: Invalid PHY address %d\n", addr); return -EFAULT; } if (reg > MVNETA_PHY_REG_MASK) { printf("Err: Invalid register offset %d\n", reg); return -EFAULT; } /* wait till the SMI is not busy */ if (smi_wait_ready(pp) < 0) return -EFAULT; /* fill the phy addr and reg offset and write opcode and data */ smi_reg = value << MVNETA_SMI_DATA_OFFS; smi_reg |= (addr << MVNETA_SMI_DEV_ADDR_OFFS) | (reg << MVNETA_SMI_REG_ADDR_OFFS); smi_reg &= ~MVNETA_SMI_OPCODE_READ; /* write the smi register */ mvreg_write(pp, MVNETA_SMI, smi_reg); return 0; } static int mvneta_start(struct udevice *dev) { struct mvneta_port *pp = dev_get_priv(dev); struct phy_device *phydev; mvneta_port_power_up(pp, pp->phy_interface); if (!pp->init || pp->link == 0) { if (mvneta_port_is_fixed_link(pp)) { u32 val; pp->init = 1; pp->link = 1; mvneta_init(dev); val = MVNETA_GMAC_FORCE_LINK_UP | MVNETA_GMAC_IB_BYPASS_AN_EN | MVNETA_GMAC_SET_FC_EN | MVNETA_GMAC_ADVERT_FC_EN | MVNETA_GMAC_SAMPLE_TX_CFG_EN; if (pp->duplex) val |= MVNETA_GMAC_CONFIG_FULL_DUPLEX; if (pp->speed == SPEED_1000) val |= MVNETA_GMAC_CONFIG_GMII_SPEED; else if (pp->speed == SPEED_100) val |= MVNETA_GMAC_CONFIG_MII_SPEED; mvreg_write(pp, MVNETA_GMAC_AUTONEG_CONFIG, val); } else { /* Set phy address of the port */ mvreg_write(pp, MVNETA_PHY_ADDR, pp->phyaddr); phydev = phy_connect(pp->bus, pp->phyaddr, dev, pp->phy_interface); if (!phydev) { printf("phy_connect failed\n"); return -ENODEV; } pp->phydev = phydev; phy_config(phydev); phy_startup(phydev); if (!phydev->link) { printf("%s: No link.\n", phydev->dev->name); return -1; } /* Full init on first call */ mvneta_init(dev); pp->init = 1; return 0; } } /* Upon all following calls, this is enough */ mvneta_port_up(pp); mvneta_port_enable(pp); return 0; } static int mvneta_send(struct udevice *dev, void *packet, int length) { struct mvneta_port *pp = dev_get_priv(dev); struct mvneta_tx_queue *txq = &pp->txqs[0]; struct mvneta_tx_desc *tx_desc; int sent_desc; u32 timeout = 0; /* Get a descriptor for the first part of the packet */ tx_desc = mvneta_txq_next_desc_get(txq); tx_desc->buf_phys_addr = (u32)(uintptr_t)packet; tx_desc->data_size = length; flush_dcache_range((ulong)packet, (ulong)packet + ALIGN(length, PKTALIGN)); /* First and Last descriptor */ tx_desc->command = MVNETA_TX_L4_CSUM_NOT | MVNETA_TXD_FLZ_DESC; mvneta_txq_pend_desc_add(pp, txq, 1); /* Wait for packet to be sent (queue might help with speed here) */ sent_desc = mvneta_txq_sent_desc_num_get(pp, txq); while (!sent_desc) { if (timeout++ > 10000) { printf("timeout: packet not sent\n"); return -1; } sent_desc = mvneta_txq_sent_desc_num_get(pp, txq); } /* txDone has increased - hw sent packet */ mvneta_txq_sent_desc_dec(pp, txq, sent_desc); return 0; } static int mvneta_recv(struct udevice *dev, int flags, uchar **packetp) { struct mvneta_port *pp = dev_get_priv(dev); int rx_done; struct mvneta_rx_queue *rxq; int rx_bytes = 0; /* get rx queue */ rxq = mvneta_rxq_handle_get(pp, rxq_def); rx_done = mvneta_rxq_busy_desc_num_get(pp, rxq); if (rx_done) { struct mvneta_rx_desc *rx_desc; unsigned char *data; u32 rx_status; /* * No cache invalidation needed here, since the desc's are * located in a uncached memory region */ rx_desc = mvneta_rxq_next_desc_get(rxq); rx_status = rx_desc->status; if (!mvneta_rxq_desc_is_first_last(rx_status) || (rx_status & MVNETA_RXD_ERR_SUMMARY)) { mvneta_rx_error(pp, rx_desc); /* leave the descriptor untouched */ return -EIO; } /* 2 bytes for marvell header. 4 bytes for crc */ rx_bytes = rx_desc->data_size - 6; /* give packet to stack - skip on first 2 bytes */ data = (u8 *)(uintptr_t)rx_desc->buf_cookie + 2; /* * No cache invalidation needed here, since the rx_buffer's are * located in a uncached memory region */ *packetp = data; /* * Only mark one descriptor as free * since only one was processed */ mvneta_rxq_desc_num_update(pp, rxq, 1, 1); } return rx_bytes; } static int mvneta_probe(struct udevice *dev) { struct eth_pdata *pdata = dev_get_platdata(dev); struct mvneta_port *pp = dev_get_priv(dev); void *blob = (void *)gd->fdt_blob; int node = dev_of_offset(dev); struct mii_dev *bus; unsigned long addr; void *bd_space; int ret; int fl_node; /* * Allocate buffer area for descs and rx_buffers. This is only * done once for all interfaces. As only one interface can * be active. Make this area DMA safe by disabling the D-cache */ if (!buffer_loc.tx_descs) { u32 size; /* Align buffer area for descs and rx_buffers to 1MiB */ bd_space = memalign(1 << MMU_SECTION_SHIFT, BD_SPACE); flush_dcache_range((ulong)bd_space, (ulong)bd_space + BD_SPACE); mmu_set_region_dcache_behaviour((phys_addr_t)bd_space, BD_SPACE, DCACHE_OFF); buffer_loc.tx_descs = (struct mvneta_tx_desc *)bd_space; size = roundup(MVNETA_MAX_TXD * sizeof(struct mvneta_tx_desc), ARCH_DMA_MINALIGN); memset(buffer_loc.tx_descs, 0, size); buffer_loc.rx_descs = (struct mvneta_rx_desc *) ((phys_addr_t)bd_space + size); size += roundup(MVNETA_MAX_RXD * sizeof(struct mvneta_rx_desc), ARCH_DMA_MINALIGN); buffer_loc.rx_buffers = (phys_addr_t)(bd_space + size); } pp->base = (void __iomem *)pdata->iobase; /* Configure MBUS address windows */ if (device_is_compatible(dev, "marvell,armada-3700-neta")) mvneta_bypass_mbus_windows(pp); else mvneta_conf_mbus_windows(pp); /* PHY interface is already decoded in mvneta_ofdata_to_platdata() */ pp->phy_interface = pdata->phy_interface; /* fetch 'fixed-link' property from 'neta' node */ fl_node = fdt_subnode_offset(blob, node, "fixed-link"); if (fl_node != -FDT_ERR_NOTFOUND) { /* set phy_addr to invalid value for fixed link */ pp->phyaddr = PHY_MAX_ADDR + 1; pp->duplex = fdtdec_get_bool(blob, fl_node, "full-duplex"); pp->speed = fdtdec_get_int(blob, fl_node, "speed", 0); } else { /* Now read phyaddr from DT */ addr = fdtdec_get_int(blob, node, "phy", 0); addr = fdt_node_offset_by_phandle(blob, addr); pp->phyaddr = fdtdec_get_int(blob, addr, "reg", 0); } bus = mdio_alloc(); if (!bus) { printf("Failed to allocate MDIO bus\n"); return -ENOMEM; } bus->read = mvneta_mdio_read; bus->write = mvneta_mdio_write; snprintf(bus->name, sizeof(bus->name), dev->name); bus->priv = (void *)pp; pp->bus = bus; ret = mdio_register(bus); if (ret) return ret; return board_network_enable(bus); } static void mvneta_stop(struct udevice *dev) { struct mvneta_port *pp = dev_get_priv(dev); mvneta_port_down(pp); mvneta_port_disable(pp); } static const struct eth_ops mvneta_ops = { .start = mvneta_start, .send = mvneta_send, .recv = mvneta_recv, .stop = mvneta_stop, .write_hwaddr = mvneta_write_hwaddr, }; static int mvneta_ofdata_to_platdata(struct udevice *dev) { struct eth_pdata *pdata = dev_get_platdata(dev); const char *phy_mode; pdata->iobase = devfdt_get_addr(dev); /* Get phy-mode / phy_interface from DT */ pdata->phy_interface = -1; phy_mode = fdt_getprop(gd->fdt_blob, dev_of_offset(dev), "phy-mode", NULL); if (phy_mode) pdata->phy_interface = phy_get_interface_by_name(phy_mode); if (pdata->phy_interface == -1) { debug("%s: Invalid PHY interface '%s'\n", __func__, phy_mode); return -EINVAL; } return 0; } static const struct udevice_id mvneta_ids[] = { { .compatible = "marvell,armada-370-neta" }, { .compatible = "marvell,armada-xp-neta" }, { .compatible = "marvell,armada-3700-neta" }, { } }; U_BOOT_DRIVER(mvneta) = { .name = "mvneta", .id = UCLASS_ETH, .of_match = mvneta_ids, .ofdata_to_platdata = mvneta_ofdata_to_platdata, .probe = mvneta_probe, .ops = &mvneta_ops, .priv_auto_alloc_size = sizeof(struct mvneta_port), .platdata_auto_alloc_size = sizeof(struct eth_pdata), };
{ "language": "C" }
#include "test/jemalloc_test.h" TEST_BEGIN(test_overflow) { unsigned nlextents; size_t mib[4]; size_t sz, miblen, max_size_class; void *p; sz = sizeof(unsigned); assert_d_eq(mallctl("arenas.nlextents", (void *)&nlextents, &sz, NULL, 0), 0, "Unexpected mallctl() error"); miblen = sizeof(mib) / sizeof(size_t); assert_d_eq(mallctlnametomib("arenas.lextent.0.size", mib, &miblen), 0, "Unexpected mallctlnametomib() error"); mib[2] = nlextents - 1; sz = sizeof(size_t); assert_d_eq(mallctlbymib(mib, miblen, (void *)&max_size_class, &sz, NULL, 0), 0, "Unexpected mallctlbymib() error"); assert_ptr_null(malloc(max_size_class + 1), "Expected OOM due to over-sized allocation request"); assert_ptr_null(malloc(SIZE_T_MAX), "Expected OOM due to over-sized allocation request"); assert_ptr_null(calloc(1, max_size_class + 1), "Expected OOM due to over-sized allocation request"); assert_ptr_null(calloc(1, SIZE_T_MAX), "Expected OOM due to over-sized allocation request"); p = malloc(1); assert_ptr_not_null(p, "Unexpected malloc() OOM"); assert_ptr_null(realloc(p, max_size_class + 1), "Expected OOM due to over-sized allocation request"); assert_ptr_null(realloc(p, SIZE_T_MAX), "Expected OOM due to over-sized allocation request"); free(p); } TEST_END int main(void) { return test( test_overflow); }
{ "language": "C" }
// Created via CMake from template jsincludes.h.in // WARNING! Any changes to this file will be overwritten by the next CMake run! #ifndef SYNCTHINGCTL_JAVA_SCRIPT_INCLUDES #define SYNCTHINGCTL_JAVA_SCRIPT_INCLUDES #include <QtGlobal> #if defined(SYNCTHINGCTL_USE_JSENGINE) # include <QJSEngine> # include <QJSValue> #elif defined(SYNCTHINGCTL_USE_SCRIPT) # include <QScriptEngine> # include <QScriptValue> #elif !defined(SYNCTHINGCTL_NO_JSENGINE) # error "No definition for JavaScript provider present." #endif #endif // SYNCTHINGCTL_JAVA_SCRIPT_INCLUDES
{ "language": "C" }
/* * ALSA SoC TLV320AIC23 codec driver * * Author: Arun KS, <arunks@mistralsolutions.com> * Copyright: (C) 2008 Mistral Solutions Pvt Ltd * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #ifndef _TLV320AIC23_H #define _TLV320AIC23_H struct device; struct regmap_config; extern const struct regmap_config tlv320aic23_regmap; int tlv320aic23_probe(struct device *dev, struct regmap *regmap); /* Codec TLV320AIC23 */ #define TLV320AIC23_LINVOL 0x00 #define TLV320AIC23_RINVOL 0x01 #define TLV320AIC23_LCHNVOL 0x02 #define TLV320AIC23_RCHNVOL 0x03 #define TLV320AIC23_ANLG 0x04 #define TLV320AIC23_DIGT 0x05 #define TLV320AIC23_PWR 0x06 #define TLV320AIC23_DIGT_FMT 0x07 #define TLV320AIC23_SRATE 0x08 #define TLV320AIC23_ACTIVE 0x09 #define TLV320AIC23_RESET 0x0F /* Left (right) line input volume control register */ #define TLV320AIC23_LRS_ENABLED 0x0100 #define TLV320AIC23_LIM_MUTED 0x0080 #define TLV320AIC23_LIV_DEFAULT 0x0017 #define TLV320AIC23_LIV_MAX 0x001f #define TLV320AIC23_LIV_MIN 0x0000 /* Left (right) channel headphone volume control register */ #define TLV320AIC23_LZC_ON 0x0080 #define TLV320AIC23_LHV_DEFAULT 0x0079 #define TLV320AIC23_LHV_MAX 0x007f #define TLV320AIC23_LHV_MIN 0x0000 /* Analog audio path control register */ #define TLV320AIC23_STA_REG(x) ((x)<<6) #define TLV320AIC23_STE_ENABLED 0x0020 #define TLV320AIC23_DAC_SELECTED 0x0010 #define TLV320AIC23_BYPASS_ON 0x0008 #define TLV320AIC23_INSEL_MIC 0x0004 #define TLV320AIC23_MICM_MUTED 0x0002 #define TLV320AIC23_MICB_20DB 0x0001 /* Digital audio path control register */ #define TLV320AIC23_DACM_MUTE 0x0008 #define TLV320AIC23_DEEMP_32K 0x0002 #define TLV320AIC23_DEEMP_44K 0x0004 #define TLV320AIC23_DEEMP_48K 0x0006 #define TLV320AIC23_ADCHP_ON 0x0001 /* Power control down register */ #define TLV320AIC23_DEVICE_PWR_OFF 0x0080 #define TLV320AIC23_CLK_OFF 0x0040 #define TLV320AIC23_OSC_OFF 0x0020 #define TLV320AIC23_OUT_OFF 0x0010 #define TLV320AIC23_DAC_OFF 0x0008 #define TLV320AIC23_ADC_OFF 0x0004 #define TLV320AIC23_MIC_OFF 0x0002 #define TLV320AIC23_LINE_OFF 0x0001 /* Digital audio interface register */ #define TLV320AIC23_MS_MASTER 0x0040 #define TLV320AIC23_LRSWAP_ON 0x0020 #define TLV320AIC23_LRP_ON 0x0010 #define TLV320AIC23_IWL_16 0x0000 #define TLV320AIC23_IWL_20 0x0004 #define TLV320AIC23_IWL_24 0x0008 #define TLV320AIC23_IWL_32 0x000C #define TLV320AIC23_FOR_I2S 0x0002 #define TLV320AIC23_FOR_DSP 0x0003 #define TLV320AIC23_FOR_LJUST 0x0001 /* Sample rate control register */ #define TLV320AIC23_CLKOUT_HALF 0x0080 #define TLV320AIC23_CLKIN_HALF 0x0040 #define TLV320AIC23_BOSR_384fs 0x0002 /* BOSR_272fs in USB mode */ #define TLV320AIC23_USB_CLK_ON 0x0001 #define TLV320AIC23_SR_MASK 0xf #define TLV320AIC23_CLKOUT_SHIFT 7 #define TLV320AIC23_CLKIN_SHIFT 6 #define TLV320AIC23_SR_SHIFT 2 #define TLV320AIC23_BOSR_SHIFT 1 /* Digital interface register */ #define TLV320AIC23_ACT_ON 0x0001 /* * AUDIO related MACROS */ #define TLV320AIC23_DEFAULT_OUT_VOL 0x70 #define TLV320AIC23_DEFAULT_IN_VOLUME 0x10 #define TLV320AIC23_OUT_VOL_MIN TLV320AIC23_LHV_MIN #define TLV320AIC23_OUT_VOL_MAX TLV320AIC23_LHV_MAX #define TLV320AIC23_OUT_VO_RANGE (TLV320AIC23_OUT_VOL_MAX - \ TLV320AIC23_OUT_VOL_MIN) #define TLV320AIC23_OUT_VOL_MASK TLV320AIC23_OUT_VOL_MAX #define TLV320AIC23_IN_VOL_MIN TLV320AIC23_LIV_MIN #define TLV320AIC23_IN_VOL_MAX TLV320AIC23_LIV_MAX #define TLV320AIC23_IN_VOL_RANGE (TLV320AIC23_IN_VOL_MAX - \ TLV320AIC23_IN_VOL_MIN) #define TLV320AIC23_IN_VOL_MASK TLV320AIC23_IN_VOL_MAX #define TLV320AIC23_SIDETONE_MASK 0x1c0 #define TLV320AIC23_SIDETONE_0 0x100 #define TLV320AIC23_SIDETONE_6 0x000 #define TLV320AIC23_SIDETONE_9 0x040 #define TLV320AIC23_SIDETONE_12 0x080 #define TLV320AIC23_SIDETONE_18 0x0c0 #endif /* _TLV320AIC23_H */
{ "language": "C" }
/* * Copyright 2007 Dave Airlied * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * VA LINUX SYSTEMS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /* * Authors: Dave Airlied <airlied@linux.ie> * Ben Skeggs <darktama@iinet.net.au> * Jeremy Kolb <jkolb@brandeis.edu> */ #include "nouveau_bo.h" #include "nouveau_dma.h" #include "nouveau_mem.h" #include <nvif/push206e.h> /*XXX: Fixup class to be compatible with NVIDIA's, which will allow sharing * code with KeplerDmaCopyA. */ int nva3_bo_move_copy(struct nouveau_channel *chan, struct ttm_buffer_object *bo, struct ttm_mem_reg *old_reg, struct ttm_mem_reg *new_reg) { struct nouveau_mem *mem = nouveau_mem(old_reg); struct nvif_push *push = chan->chan.push; u64 src_offset = mem->vma[0].addr; u64 dst_offset = mem->vma[1].addr; u32 page_count = new_reg->num_pages; int ret; page_count = new_reg->num_pages; while (page_count) { int line_count = (page_count > 8191) ? 8191 : page_count; ret = PUSH_WAIT(push, 11); if (ret) return ret; PUSH_NVSQ(push, NV85B5, 0x030c, upper_32_bits(src_offset), 0x0310, lower_32_bits(src_offset), 0x0314, upper_32_bits(dst_offset), 0x0318, lower_32_bits(dst_offset), 0x031c, PAGE_SIZE, 0x0320, PAGE_SIZE, 0x0324, PAGE_SIZE, 0x0328, line_count); PUSH_NVSQ(push, NV85B5, 0x0300, 0x00000110); page_count -= line_count; src_offset += (PAGE_SIZE * line_count); dst_offset += (PAGE_SIZE * line_count); } return 0; }
{ "language": "C" }
/* LzmaRamDecode.c */ #include "LzmaRamDecode.h" #ifdef _SZ_ONE_DIRECTORY #include "LzmaDecode.h" #include "BranchX86.h" #else #include "../../../../C/Compress/Lzma/LzmaDecode.h" #include "../../../../C/Compress/Branch/BranchX86.h" #endif #define LZMA_PROPS_SIZE 14 #define LZMA_SIZE_OFFSET 6 int LzmaRamGetUncompressedSize( const unsigned char *inBuffer, size_t inSize, size_t *outSize) { unsigned int i; if (inSize < LZMA_PROPS_SIZE) return 1; *outSize = 0; for(i = 0; i < sizeof(size_t); i++) *outSize += ((size_t)inBuffer[LZMA_SIZE_OFFSET + i]) << (8 * i); for(; i < 8; i++) if (inBuffer[LZMA_SIZE_OFFSET + i] != 0) return 1; return 0; } #define SZE_DATA_ERROR (1) #define SZE_OUTOFMEMORY (2) int LzmaRamDecompress( const unsigned char *inBuffer, size_t inSize, unsigned char *outBuffer, size_t outSize, size_t *outSizeProcessed, void * (*allocFunc)(size_t size), void (*freeFunc)(void *)) { CLzmaDecoderState state; /* it's about 24 bytes structure, if int is 32-bit */ int result; SizeT outSizeProcessedLoc; SizeT inProcessed; int useFilter; if (inSize < LZMA_PROPS_SIZE) return 1; useFilter = inBuffer[0]; *outSizeProcessed = 0; if (useFilter > 1) return 1; if (LzmaDecodeProperties(&state.Properties, inBuffer + 1, LZMA_PROPERTIES_SIZE) != LZMA_RESULT_OK) return 1; state.Probs = (CProb *)allocFunc(LzmaGetNumProbs(&state.Properties) * sizeof(CProb)); if (state.Probs == 0) return SZE_OUTOFMEMORY; result = LzmaDecode(&state, inBuffer + LZMA_PROPS_SIZE, (SizeT)inSize - LZMA_PROPS_SIZE, &inProcessed, outBuffer, (SizeT)outSize, &outSizeProcessedLoc); freeFunc(state.Probs); if (result != LZMA_RESULT_OK) return 1; *outSizeProcessed = (size_t)outSizeProcessedLoc; if (useFilter == 1) { UInt32 x86State; x86_Convert_Init(x86State); x86_Convert(outBuffer, (SizeT)outSizeProcessedLoc, 0, &x86State, 0); } return 0; }
{ "language": "C" }
/* * security/tomoyo/common.c * * Securityfs interface for TOMOYO. * * Copyright (C) 2005-2010 NTT DATA CORPORATION */ #include <linux/security.h> #include "common.h" /** * tomoyo_open - open() for /sys/kernel/security/tomoyo/ interface. * * @inode: Pointer to "struct inode". * @file: Pointer to "struct file". * * Returns 0 on success, negative value otherwise. */ static int tomoyo_open(struct inode *inode, struct file *file) { const int key = ((u8 *) file->f_path.dentry->d_inode->i_private) - ((u8 *) NULL); return tomoyo_open_control(key, file); } /** * tomoyo_release - close() for /sys/kernel/security/tomoyo/ interface. * * @inode: Pointer to "struct inode". * @file: Pointer to "struct file". * * Returns 0 on success, negative value otherwise. */ static int tomoyo_release(struct inode *inode, struct file *file) { return tomoyo_close_control(file); } /** * tomoyo_poll - poll() for /proc/ccs/ interface. * * @file: Pointer to "struct file". * @wait: Pointer to "poll_table". * * Returns 0 on success, negative value otherwise. */ static unsigned int tomoyo_poll(struct file *file, poll_table *wait) { return tomoyo_poll_control(file, wait); } /** * tomoyo_read - read() for /sys/kernel/security/tomoyo/ interface. * * @file: Pointer to "struct file". * @buf: Pointer to buffer. * @count: Size of @buf. * @ppos: Unused. * * Returns bytes read on success, negative value otherwise. */ static ssize_t tomoyo_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { return tomoyo_read_control(file, buf, count); } /** * tomoyo_write - write() for /sys/kernel/security/tomoyo/ interface. * * @file: Pointer to "struct file". * @buf: Pointer to buffer. * @count: Size of @buf. * @ppos: Unused. * * Returns @count on success, negative value otherwise. */ static ssize_t tomoyo_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { return tomoyo_write_control(file, buf, count); } /* * tomoyo_operations is a "struct file_operations" which is used for handling * /sys/kernel/security/tomoyo/ interface. * * Some files under /sys/kernel/security/tomoyo/ directory accept open(O_RDWR). * See tomoyo_io_buffer for internals. */ static const struct file_operations tomoyo_operations = { .open = tomoyo_open, .release = tomoyo_release, .poll = tomoyo_poll, .read = tomoyo_read, .write = tomoyo_write, .llseek = noop_llseek, }; /** * tomoyo_create_entry - Create interface files under /sys/kernel/security/tomoyo/ directory. * * @name: The name of the interface file. * @mode: The permission of the interface file. * @parent: The parent directory. * @key: Type of interface. * * Returns nothing. */ static void __init tomoyo_create_entry(const char *name, const mode_t mode, struct dentry *parent, const u8 key) { securityfs_create_file(name, mode, parent, ((u8 *) NULL) + key, &tomoyo_operations); } /** * tomoyo_initerface_init - Initialize /sys/kernel/security/tomoyo/ interface. * * Returns 0. */ static int __init tomoyo_initerface_init(void) { struct dentry *tomoyo_dir; /* Don't create securityfs entries unless registered. */ if (current_cred()->security != &tomoyo_kernel_domain) return 0; tomoyo_dir = securityfs_create_dir("tomoyo", NULL); tomoyo_create_entry("query", 0600, tomoyo_dir, TOMOYO_QUERY); tomoyo_create_entry("domain_policy", 0600, tomoyo_dir, TOMOYO_DOMAINPOLICY); tomoyo_create_entry("exception_policy", 0600, tomoyo_dir, TOMOYO_EXCEPTIONPOLICY); tomoyo_create_entry("self_domain", 0400, tomoyo_dir, TOMOYO_SELFDOMAIN); tomoyo_create_entry(".domain_status", 0600, tomoyo_dir, TOMOYO_DOMAIN_STATUS); tomoyo_create_entry(".process_status", 0600, tomoyo_dir, TOMOYO_PROCESS_STATUS); tomoyo_create_entry("meminfo", 0600, tomoyo_dir, TOMOYO_MEMINFO); tomoyo_create_entry("profile", 0600, tomoyo_dir, TOMOYO_PROFILE); tomoyo_create_entry("manager", 0600, tomoyo_dir, TOMOYO_MANAGER); tomoyo_create_entry("version", 0400, tomoyo_dir, TOMOYO_VERSION); return 0; } fs_initcall(tomoyo_initerface_init);
{ "language": "C" }
/* * Copyright (c) 2016, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "rt_TypeDef.h" #include "rt_Memory.h" #include "secure_allocator.h" #include "uvisor-lib/uvisor-lib.h" #include <stdio.h> #include <stdlib.h> #include <string.h> /* Use printf with caution inside malloc: printf may allocate memory itself, so using printf in malloc may lead to recursive calls! */ #define DPRINTF(...) {} /* offsetof is a gcc built-in function, this is the manual implementation */ #define OFFSETOF(type, member) ((uint32_t) (&(((type *)(0))->member))) /* Internal structure currently only contains the page table. */ typedef struct { UvisorPageTable table; } SecureAllocatorInternal; static inline UvisorPageTable * table(SecureAllocator allocator) { return &(((SecureAllocatorInternal *) allocator)->table); } SecureAllocator secure_allocator_create_with_pool( void * mem, size_t bytes) { SecureAllocatorInternal * allocator = mem; /* Signal that this is non-page allocated memory. */ allocator->table.page_size = bytes; allocator->table.page_count = 0; /* The internal rt_Memory MEMP structure must be placed AFTER table.page_origins[0] !!! */ size_t offset = OFFSETOF(SecureAllocatorInternal, table.page_origins) + sizeof(((UvisorPageTable) {0}).page_origins); /* Create MEMP structure inside the memory. */ if (rt_init_mem(mem + offset, bytes - offset)) { /* Abort if failed. */ DPRINTF("secure_allocator_create_with_pool: MEMP allocator creation failed\n\n"); return NULL; } /* Remember the MEMP pointer though. */ allocator->table.page_origins[0] = mem + offset; DPRINTF("secure_allocator_create_with_pool: Created MEMP allocator %p with offset %d\n\n", mem + offset, offset); return allocator; } SecureAllocator secure_allocator_create_with_pages( size_t size, size_t maximum_malloc_size) { const uint32_t page_size = uvisor_get_page_size(); /* The rt_Memory allocator puts one MEMP structure at both the * beginning and end of the memory pool. */ const size_t block_overhead = 2 * sizeof(MEMP); const size_t page_size_with_overhead = page_size + block_overhead; /* Calculate the integer part of required the page count. */ size_t page_count = size / page_size_with_overhead; /* Add another page if the remainder is not zero. */ if (size - page_count * page_size_with_overhead) { page_count++; } DPRINTF("secure_allocator_create_with_pages: Requesting %u pages for at least %uB\n", page_count, size); /* Compute the maximum allocation within our blocks. */ size_t maximum_allocation_size = page_size - block_overhead; /* If the required maximum allocation is larger than we can provide, abort. */ if (maximum_malloc_size > maximum_allocation_size) { DPRINTF("secure_allocator_create_with_pages: Maximum allocation request %uB is larger then available %uB\n\n", maximum_malloc_size, maximum_allocation_size); return NULL; } /* Compute the required memory size for the page table. */ size_t allocator_type_size = sizeof(SecureAllocatorInternal); /* Add size for each additional page. */ allocator_type_size += (page_count - 1) * sizeof(((UvisorPageTable) {0}).page_origins); /* Allocate this much memory. */ SecureAllocatorInternal * const allocator = malloc(allocator_type_size); /* If malloc failed, abort. */ if (allocator == NULL) { DPRINTF("secure_allocator_create_with_pages: SecureAllocatorInternal failed to be allocated!\n\n"); return NULL; } /* Prepare the page table. */ allocator->table.page_size = page_size; allocator->table.page_count = page_count; /* Get me some pages. */ if (uvisor_page_malloc((UvisorPageTable *) &(allocator->table))) { free(allocator); DPRINTF("secure_allocator_create_with_pages: Not enough free pages available!\n\n"); return NULL; } /* Initialize a MEMP structure in all pages. */ for(size_t ii = 0; ii < page_count; ii++) { /* Add each page as a pool. */ rt_init_mem(allocator->table.page_origins[ii], page_size); DPRINTF("secure_allocator_create_with_pages: Created MEMP allocator %p with offset %d\n", allocator->table.page_origins[ii], 0); } DPRINTF("\n"); /* Aaaand across the line. */ return (SecureAllocator) allocator; } int secure_allocator_destroy( SecureAllocator allocator) { DPRINTF("secure_allocator_destroy: Destroying MEMP allocator at %p\n", table(allocator)->page_origins[0]); /* Check if we are working on statically allocated memory. */ SecureAllocatorInternal * alloc = (SecureAllocatorInternal * const) allocator; if (alloc->table.page_count == 0) { DPRINTF("secure_allocator_destroy: %p is not page-backed memory, not freeing!\n", allocator); return -1; } /* Free all pages. */ if (uvisor_page_free(&(alloc->table))) { DPRINTF("secure_allocator_destroy: Unable to free pages!\n\n"); return -1; } /* Free the allocator structure. */ free(allocator); DPRINTF("\n"); return 0; } void * secure_malloc( SecureAllocator allocator, size_t size) { size_t index = 0; do { /* Search in this page. */ void * mem = rt_alloc_mem(table(allocator)->page_origins[index], size); /* Return if we found something. */ if (mem) { DPRINTF("secure_malloc: Found %4uB in page %u at %p\n", size, index, mem); return mem; } /* Otherwise, go to the next page. */ index++; } /* Continue search if more pages are available. */ while (index < table(allocator)->page_count); DPRINTF("secure_malloc: Out of memory in allocator %p \n", allocator); /* We found nothing. */ return NULL; } void * secure_realloc( SecureAllocator allocator, void * ptr, size_t new_size) { /* TODO: THIS IS A NAIVE IMPLEMENTATION, which always allocates new memory, and copies the memory, then frees the old memory. */ /* Allocate new memory. */ void * new_ptr = secure_malloc(allocator, new_size); /* If memory allocation failed, abort. */ if (new_ptr == NULL) { return NULL; } /* Passing NULL as ptr is legal, realloc acts as malloc then. */ if (ptr) { /* Get the size of the ptr memory. */ size_t size = ((MEMP *) ((uint32_t) ptr - sizeof(MEMP)))->len; /* Copy the memory to the new location, min(new_size, size). */ memcpy(new_ptr, ptr, new_size < size ? new_size : size); /* Free the previous memory. */ secure_free(allocator, ptr); } return new_ptr; } void secure_free( SecureAllocator allocator, void * ptr) { size_t index = 0; do { /* Search in this page. */ int ret = rt_free_mem(table(allocator)->page_origins[index], ptr); /* Return if free was successful. */ if (ret == 0) { DPRINTF("secure_free: Freed %p in page %u.\n", ptr, index); return; } /* Otherwise, go to the next page. */ index++; } /* Continue search if more pages are available. */ while (index < table(allocator)->page_count); DPRINTF("secure_free: %p not found in allocator %p!\n", ptr, allocator); /* We found nothing. */ return; }
{ "language": "C" }
/* * Copyright (C) 2013 Politecnico di Torino, Italy * TORSEC group -- http://security.polito.it * * Author: Roberto Sassu <roberto.sassu@polito.it> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, version 2 of the * License. * * File: ima_template.c * Helpers to manage template descriptors. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <crypto/hash_info.h> #include "ima.h" #include "ima_template_lib.h" static struct ima_template_desc defined_templates[] = { {.name = IMA_TEMPLATE_IMA_NAME, .fmt = IMA_TEMPLATE_IMA_FMT}, {.name = "ima-ng", .fmt = "d-ng|n-ng"}, {.name = "ima-sig", .fmt = "d-ng|n-ng|sig"}, {.name = "", .fmt = ""}, /* placeholder for a custom format */ }; static struct ima_template_field supported_fields[] = { {.field_id = "d", .field_init = ima_eventdigest_init, .field_show = ima_show_template_digest}, {.field_id = "n", .field_init = ima_eventname_init, .field_show = ima_show_template_string}, {.field_id = "d-ng", .field_init = ima_eventdigest_ng_init, .field_show = ima_show_template_digest_ng}, {.field_id = "n-ng", .field_init = ima_eventname_ng_init, .field_show = ima_show_template_string}, {.field_id = "sig", .field_init = ima_eventsig_init, .field_show = ima_show_template_sig}, }; static struct ima_template_desc *ima_template; static struct ima_template_desc *lookup_template_desc(const char *name); static int template_desc_init_fields(const char *template_fmt, struct ima_template_field ***fields, int *num_fields); static int __init ima_template_setup(char *str) { struct ima_template_desc *template_desc; int template_len = strlen(str); if (ima_template) return 1; /* * Verify that a template with the supplied name exists. * If not, use CONFIG_IMA_DEFAULT_TEMPLATE. */ template_desc = lookup_template_desc(str); if (!template_desc) { pr_err("template %s not found, using %s\n", str, CONFIG_IMA_DEFAULT_TEMPLATE); return 1; } /* * Verify whether the current hash algorithm is supported * by the 'ima' template. */ if (template_len == 3 && strcmp(str, IMA_TEMPLATE_IMA_NAME) == 0 && ima_hash_algo != HASH_ALGO_SHA1 && ima_hash_algo != HASH_ALGO_MD5) { pr_err("template does not support hash alg\n"); return 1; } ima_template = template_desc; return 1; } __setup("ima_template=", ima_template_setup); static int __init ima_template_fmt_setup(char *str) { int num_templates = ARRAY_SIZE(defined_templates); if (ima_template) return 1; if (template_desc_init_fields(str, NULL, NULL) < 0) { pr_err("format string '%s' not valid, using template %s\n", str, CONFIG_IMA_DEFAULT_TEMPLATE); return 1; } defined_templates[num_templates - 1].fmt = str; ima_template = defined_templates + num_templates - 1; return 1; } __setup("ima_template_fmt=", ima_template_fmt_setup); static struct ima_template_desc *lookup_template_desc(const char *name) { int i; for (i = 0; i < ARRAY_SIZE(defined_templates); i++) { if (strcmp(defined_templates[i].name, name) == 0) return defined_templates + i; } return NULL; } static struct ima_template_field *lookup_template_field(const char *field_id) { int i; for (i = 0; i < ARRAY_SIZE(supported_fields); i++) if (strncmp(supported_fields[i].field_id, field_id, IMA_TEMPLATE_FIELD_ID_MAX_LEN) == 0) return &supported_fields[i]; return NULL; } static int template_fmt_size(const char *template_fmt) { char c; int template_fmt_len = strlen(template_fmt); int i = 0, j = 0; while (i < template_fmt_len) { c = template_fmt[i]; if (c == '|') j++; i++; } return j + 1; } static int template_desc_init_fields(const char *template_fmt, struct ima_template_field ***fields, int *num_fields) { const char *template_fmt_ptr; struct ima_template_field *found_fields[IMA_TEMPLATE_NUM_FIELDS_MAX]; int template_num_fields = template_fmt_size(template_fmt); int i, len; if (template_num_fields > IMA_TEMPLATE_NUM_FIELDS_MAX) { pr_err("format string '%s' contains too many fields\n", template_fmt); return -EINVAL; } for (i = 0, template_fmt_ptr = template_fmt; i < template_num_fields; i++, template_fmt_ptr += len + 1) { char tmp_field_id[IMA_TEMPLATE_FIELD_ID_MAX_LEN + 1]; len = strchrnul(template_fmt_ptr, '|') - template_fmt_ptr; if (len == 0 || len > IMA_TEMPLATE_FIELD_ID_MAX_LEN) { pr_err("Invalid field with length %d\n", len); return -EINVAL; } memcpy(tmp_field_id, template_fmt_ptr, len); tmp_field_id[len] = '\0'; found_fields[i] = lookup_template_field(tmp_field_id); if (!found_fields[i]) { pr_err("field '%s' not found\n", tmp_field_id); return -ENOENT; } } if (fields && num_fields) { *fields = kmalloc_array(i, sizeof(*fields), GFP_KERNEL); if (*fields == NULL) return -ENOMEM; memcpy(*fields, found_fields, i * sizeof(*fields)); *num_fields = i; } return 0; } struct ima_template_desc *ima_template_desc_current(void) { if (!ima_template) ima_template = lookup_template_desc(CONFIG_IMA_DEFAULT_TEMPLATE); return ima_template; } int __init ima_init_template(void) { struct ima_template_desc *template = ima_template_desc_current(); int result; result = template_desc_init_fields(template->fmt, &(template->fields), &(template->num_fields)); if (result < 0) pr_err("template %s init failed, result: %d\n", (strlen(template->name) ? template->name : template->fmt), result); return result; }
{ "language": "C" }
/* * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef TRINITY_GAMEOBJECTAI_H #define TRINITY_GAMEOBJECTAI_H #include "Define.h" #include <list> class GameObject; class Player; class Quest; class SpellInfo; class Unit; class TC_GAME_API GameObjectAI { protected: GameObject* const me; public: explicit GameObjectAI(GameObject* g) : me(g) { } virtual ~GameObjectAI() { } virtual void UpdateAI(uint32 /*diff*/) { } virtual void InitializeAI() { Reset(); } virtual void Reset() { } // Pass parameters between AI virtual void DoAction(int32 /*param = 0 */) { } virtual void SetGUID(uint64 /*guid*/, int32 /*id = 0 */) { } virtual uint64 GetGUID(int32 /*id = 0 */) const { return 0; } static int32 Permissible(GameObject const* go); // Called when a player opens a gossip dialog with the gameobject. virtual bool GossipHello(Player* /*player*/) { return false; } // Called when a player selects a gossip item in the gameobject's gossip menu. virtual bool GossipSelect(Player* /*player*/, uint32 /*menuId*/, uint32 /*gossipListId*/) { return false; } // Called when a player selects a gossip with a code in the gameobject's gossip menu. virtual bool GossipSelectCode(Player* /*player*/, uint32 /*menuId*/, uint32 /*gossipListId*/, char const* /*code*/) { return false; } // Called when a player accepts a quest from the gameobject. virtual void QuestAccept(Player* /*player*/, Quest const* /*quest*/) { } // Called when a player completes a quest and is rewarded, opt is the selected item's index or 0 virtual void QuestReward(Player* /*player*/, Quest const* /*quest*/, uint32 /*opt*/) { } // Called when the dialog status between a player and the gameobject is requested. virtual uint32 GetDialogStatus(Player* player); // Called when a Player clicks a GameObject, before GossipHello // prevents achievement tracking if returning true virtual bool OnReportUse(Player* /*player*/) { return false; } virtual void Destroyed(Player* /*player*/, uint32 /*eventId*/) { } virtual void Damaged(Player* /*player*/, uint32 /*eventId*/) { } virtual uint32 GetData(uint32 /*id*/) const { return 0; } virtual void SetData64(uint32 /*id*/, uint64 /*value*/) { } virtual uint64 GetData64(uint32 /*id*/) const { return 0; } virtual void SetData(uint32 /*id*/, uint32 /*value*/) { } virtual void OnGameEvent(bool /*start*/, uint16 /*eventId*/) { } virtual void OnLootStateChanged(uint32 /*state*/, Unit* /*unit*/) { } virtual void OnStateChanged(uint32 /*state*/) { } virtual void EventInform(uint32 /*eventId*/) { } virtual void SpellHit(Unit* /*unit*/, SpellInfo const* /*spellInfo*/) { } }; class TC_GAME_API NullGameObjectAI : public GameObjectAI { public: explicit NullGameObjectAI(GameObject* g); void UpdateAI(uint32 /*diff*/) override { } static int32 Permissible(GameObject const* go); }; #endif
{ "language": "C" }
/****************************************************************************** * Copyright (c) 2004, 2008 IBM Corporation * All rights reserved. * This program and the accompanying materials * are made available under the terms of the BSD License * which accompanies this distribution, and is available at * http://www.opensource.org/licenses/bsd-license.php * * Contributors: * IBM Corporation - initial implementation *****************************************************************************/ #ifndef CALCULATECRC_H #define CALCULATECRC_H #define FLASHFS_DATADDR 0x18 // uint64_t position of pointer to data #define FLASHFS_FILE_SIZE_ADDR 0x08 // uint64_t pos of total flashimage size value relative to data #define FLASHFS_HEADER_SIZE_ADDR 0x08 // uint64_t position of total flash header size value #ifdef __ASSEMBLER__ // "CRC_GENERATOR" must contain equal inforamtion as "CRC_METHODE" #define CRC_GENERATOR 0x0000000004C11DB7 #define CRC_REGISTERMASK 0x00000000FFFFFFFF #define CRC_REGISTERLENGTH 32 #endif /* __ASSEMBLER__ */ #ifndef __ASSEMBLER__ #define FLASHFS_ROMADDR 0x00 // uint64_t position of pointer to next file #define FLASHFS_HEADER_DATA_SIZE 0x68 // 104 bytes of total header data size #define CRC_METHODE Ethernet_32 // define the CRc genarator (CRC 16 bit to 64 is supported) //--- header format --------------------------------- struct stH { char magic[8]; // (generic!) headerfile uint64_t flashlen; // dyn char version[16]; // $DRIVER_INFO alignment! char platform_name[32]; // (hardware) headerfile char date[6]; // dyn (format -> JB) char padding1[2]; // padding byte char mdate[6]; // modify date char padding2[2]; // padding byte char platform_revision[4];// (hardware) headerfile uint32_t padding; uint64_t ui64CRC; // insert calculated CRC here uint64_t ui64FileEnd; // = 0xFFFF FFFF FFFF FFFF }; #endif /* __ASSEMBLER__ */ #endif /* CALCULATECRC_H */ /*--- supported CRC Generators ------------------------- + Name length usage Generator + Tap_16 16 bit Tape 0x00008005 + Floppy_16 16 bit Floppy 0x00001021 + Ethernet_32 32 bit Ethernet 0x04C11DB7 + SPTrEMBL_64 64 bit white noise like date 0x0000001B + SPTrEMBL_improved_64 64 bit DNA code like date 0xAD93D23594C9362D + DLT1_64 64 bit Tape 0x42F0E1EBA9EA3693 + + CRC_REGISTERLENGTH = bit length + CRC_REGISTERMASK = -1 for a n-bit numer where n = bit length + example TAP_16: CRC_REGSISTERLENGTH = 16 + CRC_REGISTERMASK = 0xFFFFFFFF = (-1 if 16 bit number is used) + + TrEMBL see also http://www.cs.ud.ac.uk/staff/D.Jones/crcbote.pdf + DLT1 se also http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-182.pdf +--------------------------------------------------------*/
{ "language": "C" }
// SPDX-License-Identifier: GPL-2.0-or-later /* drm_edid_load.c: use a built-in EDID data set or load it via the firmware interface Copyright (C) 2012 Carsten Emde <C.Emde@osadl.org> */ #include <linux/firmware.h> #include <linux/module.h> #include <linux/platform_device.h> #include <drm/drm_crtc.h> #include <drm/drm_crtc_helper.h> #include <drm/drm_drv.h> #include <drm/drm_edid.h> #include <drm/drm_print.h> static char edid_firmware[PATH_MAX]; module_param_string(edid_firmware, edid_firmware, sizeof(edid_firmware), 0644); MODULE_PARM_DESC(edid_firmware, "Do not probe monitor, use specified EDID blob " "from built-in data or /lib/firmware instead. "); /* Use only for backward compatibility with drm_kms_helper.edid_firmware */ int __drm_set_edid_firmware_path(const char *path) { scnprintf(edid_firmware, sizeof(edid_firmware), "%s", path); return 0; } EXPORT_SYMBOL(__drm_set_edid_firmware_path); /* Use only for backward compatibility with drm_kms_helper.edid_firmware */ int __drm_get_edid_firmware_path(char *buf, size_t bufsize) { return scnprintf(buf, bufsize, "%s", edid_firmware); } EXPORT_SYMBOL(__drm_get_edid_firmware_path); #define GENERIC_EDIDS 6 static const char * const generic_edid_name[GENERIC_EDIDS] = { "edid/800x600.bin", "edid/1024x768.bin", "edid/1280x1024.bin", "edid/1600x1200.bin", "edid/1680x1050.bin", "edid/1920x1080.bin", }; static const u8 generic_edid[GENERIC_EDIDS][128] = { { 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x31, 0xd8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x16, 0x01, 0x03, 0x6d, 0x1b, 0x14, 0x78, 0xea, 0x5e, 0xc0, 0xa4, 0x59, 0x4a, 0x98, 0x25, 0x20, 0x50, 0x54, 0x01, 0x00, 0x00, 0x45, 0x40, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0xa0, 0x0f, 0x20, 0x00, 0x31, 0x58, 0x1c, 0x20, 0x28, 0x80, 0x14, 0x00, 0x15, 0xd0, 0x10, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0xff, 0x00, 0x4c, 0x69, 0x6e, 0x75, 0x78, 0x20, 0x23, 0x30, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x3b, 0x3d, 0x24, 0x26, 0x05, 0x00, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x4c, 0x69, 0x6e, 0x75, 0x78, 0x20, 0x53, 0x56, 0x47, 0x41, 0x0a, 0x20, 0x20, 0x00, 0xc2, }, { 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x31, 0xd8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x16, 0x01, 0x03, 0x6d, 0x23, 0x1a, 0x78, 0xea, 0x5e, 0xc0, 0xa4, 0x59, 0x4a, 0x98, 0x25, 0x20, 0x50, 0x54, 0x00, 0x08, 0x00, 0x61, 0x40, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x64, 0x19, 0x00, 0x40, 0x41, 0x00, 0x26, 0x30, 0x08, 0x90, 0x36, 0x00, 0x63, 0x0a, 0x11, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0xff, 0x00, 0x4c, 0x69, 0x6e, 0x75, 0x78, 0x20, 0x23, 0x30, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x3b, 0x3d, 0x2f, 0x31, 0x07, 0x00, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x4c, 0x69, 0x6e, 0x75, 0x78, 0x20, 0x58, 0x47, 0x41, 0x0a, 0x20, 0x20, 0x20, 0x00, 0x55, }, { 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x31, 0xd8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x16, 0x01, 0x03, 0x6d, 0x2c, 0x23, 0x78, 0xea, 0x5e, 0xc0, 0xa4, 0x59, 0x4a, 0x98, 0x25, 0x20, 0x50, 0x54, 0x00, 0x00, 0x00, 0x81, 0x80, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x30, 0x2a, 0x00, 0x98, 0x51, 0x00, 0x2a, 0x40, 0x30, 0x70, 0x13, 0x00, 0xbc, 0x63, 0x11, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0xff, 0x00, 0x4c, 0x69, 0x6e, 0x75, 0x78, 0x20, 0x23, 0x30, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x3b, 0x3d, 0x3e, 0x40, 0x0b, 0x00, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x4c, 0x69, 0x6e, 0x75, 0x78, 0x20, 0x53, 0x58, 0x47, 0x41, 0x0a, 0x20, 0x20, 0x00, 0xa0, }, { 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x31, 0xd8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x16, 0x01, 0x03, 0x6d, 0x37, 0x29, 0x78, 0xea, 0x5e, 0xc0, 0xa4, 0x59, 0x4a, 0x98, 0x25, 0x20, 0x50, 0x54, 0x00, 0x00, 0x00, 0xa9, 0x40, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x48, 0x3f, 0x40, 0x30, 0x62, 0xb0, 0x32, 0x40, 0x40, 0xc0, 0x13, 0x00, 0x2b, 0xa0, 0x21, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0xff, 0x00, 0x4c, 0x69, 0x6e, 0x75, 0x78, 0x20, 0x23, 0x30, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x3b, 0x3d, 0x4a, 0x4c, 0x11, 0x00, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x4c, 0x69, 0x6e, 0x75, 0x78, 0x20, 0x55, 0x58, 0x47, 0x41, 0x0a, 0x20, 0x20, 0x00, 0x9d, }, { 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x31, 0xd8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x16, 0x01, 0x03, 0x6d, 0x2b, 0x1b, 0x78, 0xea, 0x5e, 0xc0, 0xa4, 0x59, 0x4a, 0x98, 0x25, 0x20, 0x50, 0x54, 0x00, 0x00, 0x00, 0xb3, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x21, 0x39, 0x90, 0x30, 0x62, 0x1a, 0x27, 0x40, 0x68, 0xb0, 0x36, 0x00, 0xb5, 0x11, 0x11, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0xff, 0x00, 0x4c, 0x69, 0x6e, 0x75, 0x78, 0x20, 0x23, 0x30, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x3b, 0x3d, 0x40, 0x42, 0x0f, 0x00, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x4c, 0x69, 0x6e, 0x75, 0x78, 0x20, 0x57, 0x53, 0x58, 0x47, 0x41, 0x0a, 0x20, 0x00, 0x26, }, { 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x31, 0xd8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x16, 0x01, 0x03, 0x6d, 0x32, 0x1c, 0x78, 0xea, 0x5e, 0xc0, 0xa4, 0x59, 0x4a, 0x98, 0x25, 0x20, 0x50, 0x54, 0x00, 0x00, 0x00, 0xd1, 0xc0, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x3a, 0x80, 0x18, 0x71, 0x38, 0x2d, 0x40, 0x58, 0x2c, 0x45, 0x00, 0xf4, 0x19, 0x11, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0xff, 0x00, 0x4c, 0x69, 0x6e, 0x75, 0x78, 0x20, 0x23, 0x30, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x3b, 0x3d, 0x42, 0x44, 0x0f, 0x00, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x4c, 0x69, 0x6e, 0x75, 0x78, 0x20, 0x46, 0x48, 0x44, 0x0a, 0x20, 0x20, 0x20, 0x00, 0x05, }, }; static int edid_size(const u8 *edid, int data_size) { if (data_size < EDID_LENGTH) return 0; return (edid[0x7e] + 1) * EDID_LENGTH; } static void *edid_load(struct drm_connector *connector, const char *name, const char *connector_name) { const struct firmware *fw = NULL; const u8 *fwdata; u8 *edid; int fwsize, builtin; int i, valid_extensions = 0; bool print_bad_edid = !connector->bad_edid_counter || drm_debug_enabled(DRM_UT_KMS); builtin = match_string(generic_edid_name, GENERIC_EDIDS, name); if (builtin >= 0) { fwdata = generic_edid[builtin]; fwsize = sizeof(generic_edid[builtin]); } else { struct platform_device *pdev; int err; pdev = platform_device_register_simple(connector_name, -1, NULL, 0); if (IS_ERR(pdev)) { DRM_ERROR("Failed to register EDID firmware platform device " "for connector \"%s\"\n", connector_name); return ERR_CAST(pdev); } err = request_firmware(&fw, name, &pdev->dev); platform_device_unregister(pdev); if (err) { DRM_ERROR("Requesting EDID firmware \"%s\" failed (err=%d)\n", name, err); return ERR_PTR(err); } fwdata = fw->data; fwsize = fw->size; } if (edid_size(fwdata, fwsize) != fwsize) { DRM_ERROR("Size of EDID firmware \"%s\" is invalid " "(expected %d, got %d\n", name, edid_size(fwdata, fwsize), (int)fwsize); edid = ERR_PTR(-EINVAL); goto out; } edid = kmemdup(fwdata, fwsize, GFP_KERNEL); if (edid == NULL) { edid = ERR_PTR(-ENOMEM); goto out; } if (!drm_edid_block_valid(edid, 0, print_bad_edid, &connector->edid_corrupt)) { connector->bad_edid_counter++; DRM_ERROR("Base block of EDID firmware \"%s\" is invalid ", name); kfree(edid); edid = ERR_PTR(-EINVAL); goto out; } for (i = 1; i <= edid[0x7e]; i++) { if (i != valid_extensions + 1) memcpy(edid + (valid_extensions + 1) * EDID_LENGTH, edid + i * EDID_LENGTH, EDID_LENGTH); if (drm_edid_block_valid(edid + i * EDID_LENGTH, i, print_bad_edid, NULL)) valid_extensions++; } if (valid_extensions != edid[0x7e]) { u8 *new_edid; edid[EDID_LENGTH-1] += edid[0x7e] - valid_extensions; DRM_INFO("Found %d valid extensions instead of %d in EDID data " "\"%s\" for connector \"%s\"\n", valid_extensions, edid[0x7e], name, connector_name); edid[0x7e] = valid_extensions; new_edid = krealloc(edid, (valid_extensions + 1) * EDID_LENGTH, GFP_KERNEL); if (new_edid) edid = new_edid; } DRM_INFO("Got %s EDID base block and %d extension%s from " "\"%s\" for connector \"%s\"\n", (builtin >= 0) ? "built-in" : "external", valid_extensions, valid_extensions == 1 ? "" : "s", name, connector_name); out: release_firmware(fw); return edid; } struct edid *drm_load_edid_firmware(struct drm_connector *connector) { const char *connector_name = connector->name; char *edidname, *last, *colon, *fwstr, *edidstr, *fallback = NULL; struct edid *edid; if (edid_firmware[0] == '\0') return ERR_PTR(-ENOENT); /* * If there are multiple edid files specified and separated * by commas, search through the list looking for one that * matches the connector. * * If there's one or more that doesn't specify a connector, keep * the last one found one as a fallback. */ fwstr = kstrdup(edid_firmware, GFP_KERNEL); if (!fwstr) return ERR_PTR(-ENOMEM); edidstr = fwstr; while ((edidname = strsep(&edidstr, ","))) { colon = strchr(edidname, ':'); if (colon != NULL) { if (strncmp(connector_name, edidname, colon - edidname)) continue; edidname = colon + 1; break; } if (*edidname != '\0') /* corner case: multiple ',' */ fallback = edidname; } if (!edidname) { if (!fallback) { kfree(fwstr); return ERR_PTR(-ENOENT); } edidname = fallback; } last = edidname + strlen(edidname) - 1; if (*last == '\n') *last = '\0'; edid = edid_load(connector, edidname, connector_name); kfree(fwstr); return edid; }
{ "language": "C" }
#ifndef _LIBFAT_PC_H #define _LIBFAT_PC_H #ifdef LIBFAT_PC #include "../../types.h" #ifdef _MSC_VER #include <stdint.h> #include <time.h> #include <stdio.h> #include <sys/stat.h> #define S_IRUSR S_IREAD #define S_IRGRP S_IREAD #define S_IROTH S_IREAD #define S_IWUSR S_IWRITE #define S_IWGRP S_IWRITE #define S_IWOTH S_IWRITE //struct stat { // u32 st_dev; // u32 st_ino; // u32 st_mode; // u32 st_nlink; // u32 st_uid; // u32 st_gid; // u32 st_rdev; // s64 st_size; // time_t st_atime; // time_t st_mtime; // time_t st_ctime; // s32 st_blksize; // s32 st_blocks; // u32 st_attr; //}; #else // (!_MSC_VER) #include <unistd.h> #endif //_MSC_VER struct _reent { intptr_t _errno; }; #ifdef __APPLE__ typedef __darwin_mode_t mode_t; #elif defined(_MSC_VER) typedef uint32_t mode_t; #else #include <sys/types.h> #endif struct DIR_ITER { void* dirStruct; }; struct devoptab_t { const char *name; int structSize; intptr_t (*open_r)(struct _reent *r, void *fileStruct, const char *path, int flags, int mode); intptr_t (*close_r)(struct _reent *r, intptr_t fd); ssize_t (*write_r)(struct _reent *r, intptr_t fd, const char *ptr, size_t len); ssize_t (*read_r)(struct _reent *r, intptr_t fd, char *ptr, size_t len); off_t (*seek_r)(struct _reent *r, intptr_t fd, off_t pos, int dir); int (*fstat_r)(struct _reent *r, intptr_t fd, struct stat *st); int (*stat_r)(struct _reent *r, const char *file, struct stat *st); int (*link_r)(struct _reent *r, const char *existing, const char *newLink); int (*unlink_r)(struct _reent *r, const char *name); int (*chdir_r)(struct _reent *r, const char *name); int (*rename_r) (struct _reent *r, const char *oldName, const char *newName); int (*mkdir_r) (struct _reent *r, const char *path, int mode); int dirStateSize; DIR_ITER* (*diropen_r)(struct _reent *r, DIR_ITER *dirState, const char *path); int (*dirreset_r)(struct _reent *r, DIR_ITER *dirState); int (*dirnext_r)(struct _reent *r, DIR_ITER *dirState, char *filename, struct stat *filestat); int (*dirclose_r)(struct _reent *r, DIR_ITER *dirState); #ifndef LIBFAT_PC int (*statvfs_r)(struct _reent *r, const char *path, struct statvfs *buf); #endif int (*ftruncate_r)(struct _reent *r, intptr_t fd, off_t len); int (*fsync_r)(struct _reent *r, intptr_t fd); void *deviceData; int (*chmod_r)(struct _reent *r, const char *path, mode_t mode); int (*fchmod_r)(struct _reent *r, int fd, mode_t mode); }; devoptab_t* GetDeviceOpTab(const char* name); #define _ATTR_WEAK_ #endif //LIBFAT_PC #endif //_LIBFAT_PC_H
{ "language": "C" }
/* * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ #include <sys/types.h> #include <sys/uio.h> #include <unistd.h> #include "jni.h" #include "jni_util.h" #include "jlong.h" #include "nio.h" #include "nio_util.h" #include "sun_nio_ch_SocketDispatcher.h" JNIEXPORT jint JNICALL Java_sun_nio_ch_SocketDispatcher_read0(JNIEnv *env, jclass clazz, jobject fdo, jlong address, jint len) { jint fd = fdval(env, fdo); void *buf = (void *)jlong_to_ptr(address); jint n = read(fd, buf, len); if ((n == -1) && (errno == ECONNRESET || errno == EPIPE)) { JNU_ThrowByName(env, "sun/net/ConnectionResetException", "Connection reset"); return IOS_THROWN; } else { return convertReturnVal(env, n, JNI_TRUE); } } JNIEXPORT jlong JNICALL Java_sun_nio_ch_SocketDispatcher_readv0(JNIEnv *env, jclass clazz, jobject fdo, jlong address, jint len) { jint fd = fdval(env, fdo); struct iovec *iov = (struct iovec *)jlong_to_ptr(address); jlong n = readv(fd, iov, len); if ((n == -1) && (errno == ECONNRESET || errno == EPIPE)) { JNU_ThrowByName(env, "sun/net/ConnectionResetException", "Connection reset"); return IOS_THROWN; } else { return convertLongReturnVal(env, n, JNI_TRUE); } }
{ "language": "C" }
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "test.h" #include "memdebug.h" static char data[]= #ifdef CURL_DOES_CONVERSIONS /* ASCII representation with escape sequences for non-ASCII platforms */ "\x74\x68\x69\x73\x20\x69\x73\x20\x77\x68\x61\x74\x20\x77\x65\x20\x70" "\x6f\x73\x74\x20\x74\x6f\x20\x74\x68\x65\x20\x73\x69\x6c\x6c\x79\x20" "\x77\x65\x62\x20\x73\x65\x72\x76\x65\x72\x0a"; #else "this is what we post to the silly web server\n"; #endif struct WriteThis { char *readptr; size_t sizeleft; }; static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *userp) { #ifdef LIB587 (void)ptr; (void)size; (void)nmemb; (void)userp; return CURL_READFUNC_ABORT; #else struct WriteThis *pooh = (struct WriteThis *)userp; if(size*nmemb < 1) return 0; if(pooh->sizeleft) { *(char *)ptr = pooh->readptr[0]; /* copy one single byte */ pooh->readptr++; /* advance pointer */ pooh->sizeleft--; /* less data left */ return 1; /* we return 1 byte at a time! */ } return 0; /* no more data left to deliver */ #endif } static int once(char *URL, bool oldstyle) { CURL *curl; CURLcode res = CURLE_OK; CURLFORMcode formrc; struct curl_httppost *formpost = NULL; struct curl_httppost *lastptr = NULL; struct WriteThis pooh; struct WriteThis pooh2; pooh.readptr = data; pooh.sizeleft = strlen(data); /* Fill in the file upload field */ if(oldstyle) { formrc = curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "sendfile", CURLFORM_STREAM, &pooh, CURLFORM_CONTENTSLENGTH, (long)pooh.sizeleft, CURLFORM_FILENAME, "postit2.c", CURLFORM_END); } else { /* new style */ formrc = curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "sendfile alternative", CURLFORM_STREAM, &pooh, CURLFORM_CONTENTLEN, (curl_off_t)pooh.sizeleft, CURLFORM_FILENAME, "file name 2", CURLFORM_END); } if(formrc) printf("curl_formadd(1) = %d\n", (int)formrc); /* Now add the same data with another name and make it not look like a file upload but still using the callback */ pooh2.readptr = data; pooh2.sizeleft = strlen(data); /* Fill in the file upload field */ formrc = curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "callbackdata", CURLFORM_STREAM, &pooh2, CURLFORM_CONTENTSLENGTH, (long)pooh2.sizeleft, CURLFORM_END); if(formrc) printf("curl_formadd(2) = %d\n", (int)formrc); /* Fill in the filename field */ formrc = curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "filename", #ifdef CURL_DOES_CONVERSIONS /* ASCII representation with escape sequences for non-ASCII platforms */ CURLFORM_COPYCONTENTS, "\x70\x6f\x73\x74\x69\x74\x32\x2e\x63", #else CURLFORM_COPYCONTENTS, "postit2.c", #endif CURLFORM_END); if(formrc) printf("curl_formadd(3) = %d\n", (int)formrc); /* Fill in a submit field too */ formrc = curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "submit", #ifdef CURL_DOES_CONVERSIONS /* ASCII representation with escape sequences for non-ASCII platforms */ CURLFORM_COPYCONTENTS, "\x73\x65\x6e\x64", #else CURLFORM_COPYCONTENTS, "send", #endif CURLFORM_CONTENTTYPE, "text/plain", CURLFORM_END); if(formrc) printf("curl_formadd(4) = %d\n", (int)formrc); formrc = curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "somename", CURLFORM_BUFFER, "somefile.txt", CURLFORM_BUFFERPTR, "blah blah", CURLFORM_BUFFERLENGTH, (long)9, CURLFORM_END); if(formrc) printf("curl_formadd(5) = %d\n", (int)formrc); curl = curl_easy_init(); if(!curl) { fprintf(stderr, "curl_easy_init() failed\n"); curl_formfree(formpost); curl_global_cleanup(); return TEST_ERR_MAJOR_BAD; } /* First set the URL that is about to receive our POST. */ test_setopt(curl, CURLOPT_URL, URL); /* Now specify we want to POST data */ test_setopt(curl, CURLOPT_POST, 1L); /* Set the expected POST size */ test_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)pooh.sizeleft); /* we want to use our own read function */ test_setopt(curl, CURLOPT_READFUNCTION, read_callback); /* send a multi-part formpost */ test_setopt(curl, CURLOPT_HTTPPOST, formpost); /* get verbose debug output please */ test_setopt(curl, CURLOPT_VERBOSE, 1L); /* include headers in the output */ test_setopt(curl, CURLOPT_HEADER, 1L); /* Perform the request, res will get the return code */ res = curl_easy_perform(curl); test_cleanup: /* always cleanup */ curl_easy_cleanup(curl); /* now cleanup the formpost chain */ curl_formfree(formpost); return res; } int test(char *URL) { int res; if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { fprintf(stderr, "curl_global_init() failed\n"); return TEST_ERR_MAJOR_BAD; } res = once(URL, TRUE); /* old */ if(!res) res = once(URL, FALSE); /* new */ curl_global_cleanup(); return res; }
{ "language": "C" }
/* * 16-bit local heap functions * * Copyright 1995 Alexandre Julliard * Copyright 1996 Huw Davies * Copyright 1998 Ulrich Weigand * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA */ /* * Note: * All local heap functions need the current DS as first parameter * when called from the emulation library, so they take one more * parameter than usual. */ #include "config.h" #define NONAMELESSUNION #include <stdlib.h> #include <string.h> #include "wine/winbase16.h" #include "wownt32.h" #include "winternl.h" #include "kernel16_private.h" #include "wine/debug.h" WINE_DEFAULT_DEBUG_CHANNEL(local); typedef struct { /* Arena header */ WORD prev; /* Previous arena | arena type */ WORD next; /* Next arena */ /* Start of the memory block or free-list info */ WORD size; /* Size of the free block */ WORD free_prev; /* Previous free block */ WORD free_next; /* Next free block */ } LOCALARENA; #define ARENA_HEADER_SIZE 4 #define ARENA_HEADER( handle) ((handle) - ARENA_HEADER_SIZE) /* Arena types (stored in 'prev' field of the arena) */ #define LOCAL_ARENA_FREE 0 #define LOCAL_ARENA_FIXED 1 /* LocalNotify() msgs */ #define LN_OUTOFMEM 0 #define LN_MOVE 1 #define LN_DISCARD 2 /* Layout of a handle entry table * * WORD count of entries * LOCALHANDLEENTRY[count] entries * WORD near ptr to next table */ typedef struct { WORD addr; /* Address of the MOVEABLE block */ BYTE flags; /* Flags for this block */ BYTE lock; /* Lock count */ } LOCALHANDLEENTRY; /* * We make addr = 4n + 2 and set *((WORD *)addr - 1) = &addr like Windows does * in case something actually relies on this. * Note that if the architecture does not allow unaligned accesses, we make * addr = 4n + 4 to avoid returning unaligned pointers from LocalAlloc etc. * * An unused handle has lock = flags = 0xff. In windows addr is that of next * free handle, at the moment in wine we set it to 0. * * A discarded block's handle has lock = addr = 0 and flags = 0x40 * (LMEM_DISCARDED >> 8) */ #ifdef ALLOW_UNALIGNED_ACCESS # define MOVEABLE_PREFIX sizeof(HLOCAL16) #else # define MOVEABLE_PREFIX sizeof(int) #endif #include "pshpack1.h" typedef struct { WORD check; /* 00 Heap checking flag */ WORD freeze; /* 02 Heap frozen flag */ WORD items; /* 04 Count of items on the heap */ WORD first; /* 06 First item of the heap */ WORD pad1; /* 08 Always 0 */ WORD last; /* 0a Last item of the heap */ WORD pad2; /* 0c Always 0 */ BYTE ncompact; /* 0e Compactions counter */ BYTE dislevel; /* 0f Discard level */ DWORD distotal; /* 10 Total bytes discarded */ WORD htable; /* 14 Pointer to handle table */ WORD hfree; /* 16 Pointer to free handle table */ WORD hdelta; /* 18 Delta to expand the handle table */ WORD expand; /* 1a Pointer to expand function (unused) */ WORD pstat; /* 1c Pointer to status structure (unused) */ FARPROC16 notify; /* 1e Pointer to LocalNotify() function */ WORD lock; /* 22 Lock count for the heap */ WORD extra; /* 24 Extra bytes to allocate when expanding */ WORD minsize; /* 26 Minimum size of the heap */ WORD magic; /* 28 Magic number */ } LOCALHEAPINFO; typedef struct { DWORD dwSize; /* 00 */ DWORD dwMemReserved; /* 04 */ DWORD dwMemCommitted; /* 08 */ DWORD dwTotalFree; /* 0C */ DWORD dwLargestFreeBlock; /* 10 */ DWORD dwcFreeHandles; /* 14 */ } LOCAL32INFO; typedef struct { DWORD dwSize; /* 00 */ WORD hHandle; /* 04 */ DWORD dwAddress; /* 06 */ DWORD dwSizeBlock; /* 0A */ WORD wFlags; /* 0E */ WORD wType; /* 10 */ WORD hHeap; /* 12 */ WORD wHeapType; /* 14 */ DWORD dwNext; /* 16 */ DWORD dwNextAlt; /* 1A */ } LOCAL32ENTRY; #include "poppack.h" #define LOCAL_HEAP_MAGIC 0x484c /* 'LH' */ /* All local heap allocations are aligned on 4-byte boundaries */ #define LALIGN(word) (((word) + 3) & ~3) #define ARENA_PTR(ptr,arena) ((LOCALARENA *)((char *)(ptr)+(arena))) #define ARENA_PREV(ptr,arena) (ARENA_PTR((ptr),(arena))->prev & ~3) #define ARENA_NEXT(ptr,arena) (ARENA_PTR((ptr),(arena))->next) #define ARENA_FLAGS(ptr,arena) (ARENA_PTR((ptr),(arena))->prev & 3) /* determine whether the handle belongs to a fixed or a moveable block */ #define HANDLE_FIXED(handle) (((handle) & 3) == 0) #define HANDLE_MOVEABLE(handle) (((handle) & 3) == 2) /* 32-bit heap definitions */ #define HTABLE_SIZE 0x10000 #define HTABLE_PAGESIZE 0x1000 #define HTABLE_NPAGES (HTABLE_SIZE / HTABLE_PAGESIZE) #include "pshpack1.h" typedef struct _LOCAL32HEADER { WORD freeListFirst[HTABLE_NPAGES]; WORD freeListSize[HTABLE_NPAGES]; WORD freeListLast[HTABLE_NPAGES]; DWORD selectorTableOffset; WORD selectorTableSize; WORD selectorDelta; DWORD segment; LPBYTE base; DWORD limit; DWORD flags; DWORD magic; HANDLE heap; } LOCAL32HEADER; #include "poppack.h" #define LOCAL32_MAGIC ((DWORD)('L' | ('H'<<8) | ('3'<<16) | ('2'<<24))) static inline BOOL16 call_notify_func( FARPROC16 proc, WORD msg, HLOCAL16 handle, WORD arg ) { DWORD ret; WORD args[3]; if (!proc) return FALSE; args[2] = msg; args[1] = handle; args[0] = arg; WOWCallback16Ex( (DWORD)proc, WCB16_PASCAL, sizeof(args), args, &ret ); return LOWORD(ret); } /*********************************************************************** * LOCAL_GetHeap * * Return a pointer to the local heap, making sure it exists. */ static LOCALHEAPINFO *LOCAL_GetHeap( HANDLE16 ds ) { LOCALHEAPINFO *pInfo; INSTANCEDATA *ptr = MapSL( MAKESEGPTR( ds, 0 )); TRACE("Heap at %p, %04x\n", ptr, (ptr != NULL ? ptr->heap : 0xFFFF)); if (!ptr || !ptr->heap) return NULL; if (IsBadReadPtr16( (SEGPTR)MAKELONG(ptr->heap,ds), sizeof(LOCALHEAPINFO))) { WARN("Bad pointer\n"); return NULL; } pInfo = (LOCALHEAPINFO*)((char*)ptr + ptr->heap); if (pInfo->magic != LOCAL_HEAP_MAGIC) { WARN("Bad magic\n"); return NULL; } return pInfo; } /*********************************************************************** * LOCAL_MakeBlockFree * * Make a block free, inserting it in the free-list. * 'block' is the handle of the block arena; 'baseptr' points to * the beginning of the data segment containing the heap. */ static void LOCAL_MakeBlockFree( char *baseptr, WORD block ) { LOCALARENA *pArena, *pNext; WORD next; /* Mark the block as free */ pArena = ARENA_PTR( baseptr, block ); pArena->prev = (pArena->prev & ~3) | LOCAL_ARENA_FREE; pArena->size = pArena->next - block; /* Find the next free block (last block is always free) */ next = pArena->next; for (;;) { pNext = ARENA_PTR( baseptr, next ); if ((pNext->prev & 3) == LOCAL_ARENA_FREE) break; next = pNext->next; } TRACE("%04x, next %04x\n", block, next ); /* Insert the free block in the free-list */ pArena->free_prev = pNext->free_prev; pArena->free_next = next; ARENA_PTR(baseptr,pNext->free_prev)->free_next = block; pNext->free_prev = block; } /*********************************************************************** * LOCAL_RemoveFreeBlock * * Remove a block from the free-list. * 'block' is the handle of the block arena; 'baseptr' points to * the beginning of the data segment containing the heap. */ static void LOCAL_RemoveFreeBlock( char *baseptr, WORD block ) { /* Mark the block as fixed */ LOCALARENA *pArena = ARENA_PTR( baseptr, block ); pArena->prev = (pArena->prev & ~3) | LOCAL_ARENA_FIXED; /* Remove it from the list */ ARENA_PTR(baseptr,pArena->free_prev)->free_next = pArena->free_next; ARENA_PTR(baseptr,pArena->free_next)->free_prev = pArena->free_prev; } /*********************************************************************** * LOCAL_AddBlock * * Insert a new block in the heap. * 'new' is the handle of the new block arena; 'baseptr' points to * the beginning of the data segment containing the heap; 'prev' is * the block before the new one. */ static void LOCAL_AddBlock( char *baseptr, WORD prev, WORD new ) { LOCALARENA *pPrev = ARENA_PTR( baseptr, prev ); LOCALARENA *pNew = ARENA_PTR( baseptr, new ); pNew->prev = (prev & ~3) | LOCAL_ARENA_FIXED; pNew->next = pPrev->next; ARENA_PTR(baseptr,pPrev->next)->prev &= 3; ARENA_PTR(baseptr,pPrev->next)->prev |= new; pPrev->next = new; } /*********************************************************************** * LOCAL_RemoveBlock * * Remove a block from the heap. * 'block' is the handle of the block arena; 'baseptr' points to * the beginning of the data segment containing the heap. */ static void LOCAL_RemoveBlock( char *baseptr, WORD block ) { LOCALARENA *pArena, *pTmp; /* Remove the block from the free-list */ TRACE("\n"); pArena = ARENA_PTR( baseptr, block ); if ((pArena->prev & 3) == LOCAL_ARENA_FREE) LOCAL_RemoveFreeBlock( baseptr, block ); /* If the previous block is free, expand its size */ pTmp = ARENA_PTR( baseptr, pArena->prev & ~3 ); if ((pTmp->prev & 3) == LOCAL_ARENA_FREE) pTmp->size += pArena->next - block; /* Remove the block from the linked list */ pTmp->next = pArena->next; pTmp = ARENA_PTR( baseptr, pArena->next ); pTmp->prev = (pTmp->prev & 3) | (pArena->prev & ~3); } /*********************************************************************** * LOCAL_PrintHeap */ static void LOCAL_PrintHeap( HANDLE16 ds ) { char *ptr; LOCALHEAPINFO *pInfo; WORD arena; /* FIXME - the test should be done when calling the function! plus is not clear that we should print this info only when TRACE_ON is on! */ if(!TRACE_ON(local)) return; ptr = MapSL( MAKESEGPTR( ds, 0 )); pInfo = LOCAL_GetHeap( ds ); if (!pInfo) { ERR( "Local Heap corrupted! ds=%04x\n", ds ); return; } TRACE( "Local Heap ds=%04x first=%04x last=%04x items=%d\n", ds, pInfo->first, pInfo->last, pInfo->items ); arena = pInfo->first; for (;;) { LOCALARENA *pArena = ARENA_PTR(ptr,arena); TRACE( " %04x: prev=%04x next=%04x type=%d\n", arena, pArena->prev & ~3, pArena->next, pArena->prev & 3 ); if (arena == pInfo->first) { TRACE( " size=%d free_prev=%04x free_next=%04x\n", pArena->size, pArena->free_prev, pArena->free_next ); } if ((pArena->prev & 3) == LOCAL_ARENA_FREE) { TRACE( " size=%d free_prev=%04x free_next=%04x\n", pArena->size, pArena->free_prev, pArena->free_next ); if (pArena->next == arena) break; /* last one */ if (ARENA_PTR(ptr,pArena->free_next)->free_prev != arena) { TRACE( "*** arena->free_next->free_prev != arena\n" ); break; } } if (pArena->next == arena) { TRACE( "*** last block is not marked free\n" ); break; } if ((ARENA_PTR(ptr,pArena->next)->prev & ~3) != arena) { TRACE( "*** arena->next->prev != arena (%04x, %04x)\n", pArena->next, ARENA_PTR(ptr,pArena->next)->prev); break; } arena = pArena->next; } } /*********************************************************************** * LocalInit (KERNEL.4) */ BOOL16 WINAPI LocalInit16( HANDLE16 selector, WORD start, WORD end ) { char *ptr; WORD heapInfoArena, freeArena, lastArena; LOCALHEAPINFO *pHeapInfo; LOCALARENA *pArena, *pFirstArena, *pLastArena; BOOL16 ret = FALSE; /* The initial layout of the heap is: */ /* - first arena (FIXED) */ /* - heap info structure (FIXED) */ /* - large free block (FREE) */ /* - last arena (FREE) */ TRACE("%04x %04x-%04x\n", selector, start, end); if (!selector) selector = CURRENT_DS; if (TRACE_ON(local)) { /* If TRACE_ON(local) is set, the global heap blocks are */ /* cleared before use, so we can test for double initialization. */ if (LOCAL_GetHeap(selector)) { ERR("Heap %04x initialized twice.\n", selector); LOCAL_PrintHeap(selector); } } if (start == 0) { /* start == 0 means: put the local heap at the end of the segment */ DWORD size = GlobalSize16( GlobalHandle16( selector ) ); start = (WORD)(size > 0xffff ? 0xffff : size) - 1; if ( end > 0xfffe ) end = 0xfffe; start -= end; end += start; } ptr = MapSL( MAKESEGPTR( selector, 0 ) ); start = LALIGN( max( start, sizeof(INSTANCEDATA) ) ); heapInfoArena = LALIGN(start + sizeof(LOCALARENA) ); freeArena = LALIGN( heapInfoArena + ARENA_HEADER_SIZE + sizeof(LOCALHEAPINFO) ); lastArena = (end - sizeof(LOCALARENA)) & ~3; /* Make sure there's enough space. */ if (freeArena + sizeof(LOCALARENA) >= lastArena) goto done; /* Initialise the first arena */ pFirstArena = ARENA_PTR( ptr, start ); pFirstArena->prev = start | LOCAL_ARENA_FIXED; pFirstArena->next = heapInfoArena; pFirstArena->size = LALIGN(sizeof(LOCALARENA)); pFirstArena->free_prev = start; /* this one */ pFirstArena->free_next = freeArena; /* Initialise the arena of the heap info structure */ pArena = ARENA_PTR( ptr, heapInfoArena ); pArena->prev = start | LOCAL_ARENA_FIXED; pArena->next = freeArena; /* Initialise the heap info structure */ pHeapInfo = (LOCALHEAPINFO *) (ptr + heapInfoArena + ARENA_HEADER_SIZE ); memset( pHeapInfo, 0, sizeof(LOCALHEAPINFO) ); pHeapInfo->items = 4; pHeapInfo->first = start; pHeapInfo->last = lastArena; pHeapInfo->htable = 0; pHeapInfo->hdelta = 0x20; pHeapInfo->extra = 0x200; pHeapInfo->minsize = lastArena - freeArena; pHeapInfo->magic = LOCAL_HEAP_MAGIC; /* Initialise the large free block */ pArena = ARENA_PTR( ptr, freeArena ); pArena->prev = heapInfoArena | LOCAL_ARENA_FREE; pArena->next = lastArena; pArena->size = lastArena - freeArena; pArena->free_prev = start; pArena->free_next = lastArena; /* Initialise the last block */ pLastArena = ARENA_PTR( ptr, lastArena ); pLastArena->prev = freeArena | LOCAL_ARENA_FREE; pLastArena->next = lastArena; /* this one */ pLastArena->size = LALIGN(sizeof(LOCALARENA)); pLastArena->free_prev = freeArena; pLastArena->free_next = lastArena; /* this one */ /* Store the local heap address in the instance data */ ((INSTANCEDATA *)ptr)->heap = heapInfoArena + ARENA_HEADER_SIZE; LOCAL_PrintHeap( selector ); ret = TRUE; done: CURRENT_STACK16->ecx = ret; /* must be returned in cx too */ return ret; } /*********************************************************************** * LOCAL_GrowHeap */ static BOOL16 LOCAL_GrowHeap( HANDLE16 ds ) { HANDLE16 hseg; LONG oldsize; LONG end; LOCALHEAPINFO *pHeapInfo; WORD freeArena, lastArena; LOCALARENA *pArena, *pLastArena; char *ptr; hseg = GlobalHandle16( ds ); /* maybe mem allocated by Virtual*() ? */ if (!hseg) return FALSE; oldsize = GlobalSize16( hseg ); /* if nothing can be gained, return */ if (oldsize > 0xfff0) return FALSE; hseg = GlobalReAlloc16( hseg, 0x10000, GMEM_FIXED ); ptr = MapSL( MAKESEGPTR( ds, 0 ) ); pHeapInfo = LOCAL_GetHeap( ds ); if (pHeapInfo == NULL) { ERR("Heap not found\n" ); return FALSE; } end = GlobalSize16( hseg ); lastArena = (end - sizeof(LOCALARENA)) & ~3; /* Update the HeapInfo */ pHeapInfo->items++; freeArena = pHeapInfo->last; pHeapInfo->last = lastArena; pHeapInfo->minsize += end - oldsize; /* grow the old last block */ pArena = ARENA_PTR( ptr, freeArena ); pArena->size = lastArena - freeArena; pArena->next = lastArena; pArena->free_next = lastArena; /* Initialise the new last block */ pLastArena = ARENA_PTR( ptr, lastArena ); pLastArena->prev = freeArena | LOCAL_ARENA_FREE; pLastArena->next = lastArena; /* this one */ pLastArena->size = LALIGN(sizeof(LOCALARENA)); pLastArena->free_prev = freeArena; pLastArena->free_next = lastArena; /* this one */ /* If block before freeArena is also free then merge them */ if((ARENA_PTR(ptr, (pArena->prev & ~3))->prev & 3) == LOCAL_ARENA_FREE) { LOCAL_RemoveBlock(ptr, freeArena); pHeapInfo->items--; } TRACE("Heap expanded\n" ); LOCAL_PrintHeap( ds ); return TRUE; } /*********************************************************************** * LOCAL_FreeArena */ static HLOCAL16 LOCAL_FreeArena( WORD ds, WORD arena ) { char *ptr = MapSL( MAKESEGPTR( ds, 0 ) ); LOCALHEAPINFO *pInfo; LOCALARENA *pArena, *pPrev; TRACE("%04x ds=%04x\n", arena, ds ); if (!(pInfo = LOCAL_GetHeap( ds ))) return arena; pArena = ARENA_PTR( ptr, arena ); if ((pArena->prev & 3) == LOCAL_ARENA_FREE) { /* shouldn't happen */ ERR("Trying to free block %04x twice!\n", arena ); LOCAL_PrintHeap( ds ); return arena; } /* Check if we can merge with the previous block */ pPrev = ARENA_PTR( ptr, pArena->prev & ~3 ); if ((pPrev->prev & 3) == LOCAL_ARENA_FREE) { arena = pArena->prev & ~3; pArena = pPrev; LOCAL_RemoveBlock( ptr, pPrev->next ); pInfo->items--; } else /* Make a new free block */ { LOCAL_MakeBlockFree( ptr, arena ); } /* Check if we can merge with the next block */ if ((pArena->next == pArena->free_next) && (pArena->next != pInfo->last)) { LOCAL_RemoveBlock( ptr, pArena->next ); pInfo->items--; } return 0; } /*********************************************************************** * LOCAL_ShrinkArena * * Shrink an arena by creating a free block at its end if possible. * 'size' includes the arena header, and must be aligned. */ static void LOCAL_ShrinkArena( WORD ds, WORD arena, WORD size ) { char *ptr = MapSL( MAKESEGPTR( ds, 0 ) ); LOCALARENA *pArena = ARENA_PTR( ptr, arena ); if (arena + size + LALIGN(sizeof(LOCALARENA)) < pArena->next) { LOCALHEAPINFO *pInfo = LOCAL_GetHeap( ds ); if (!pInfo) return; LOCAL_AddBlock( ptr, arena, arena + size ); pInfo->items++; LOCAL_FreeArena( ds, arena + size ); } } /*********************************************************************** * LOCAL_GrowArenaDownward * * Grow an arena downward by using the previous arena (must be free). */ static void LOCAL_GrowArenaDownward( WORD ds, WORD arena, WORD newsize ) { char *ptr = MapSL( MAKESEGPTR( ds, 0 ) ); LOCALHEAPINFO *pInfo; LOCALARENA *pArena = ARENA_PTR( ptr, arena ); WORD prevArena = pArena->prev & ~3; LOCALARENA *pPrevArena = ARENA_PTR( ptr, prevArena ); WORD offset, size; char *p; if (!(pInfo = LOCAL_GetHeap( ds ))) return; offset = pPrevArena->size; size = pArena->next - arena - ARENA_HEADER_SIZE; LOCAL_RemoveFreeBlock( ptr, prevArena ); LOCAL_RemoveBlock( ptr, arena ); pInfo->items--; p = (char *)pPrevArena + ARENA_HEADER_SIZE; while (offset < size) { memcpy( p, p + offset, offset ); p += offset; size -= offset; } if (size) memcpy( p, p + offset, size ); LOCAL_ShrinkArena( ds, prevArena, newsize ); } /*********************************************************************** * LOCAL_GrowArenaUpward * * Grow an arena upward by using the next arena (must be free and big * enough). Newsize includes the arena header and must be aligned. */ static void LOCAL_GrowArenaUpward( WORD ds, WORD arena, WORD newsize ) { char *ptr = MapSL( MAKESEGPTR( ds, 0 ) ); LOCALHEAPINFO *pInfo; LOCALARENA *pArena = ARENA_PTR( ptr, arena ); WORD nextArena = pArena->next; if (!(pInfo = LOCAL_GetHeap( ds ))) return; LOCAL_RemoveBlock( ptr, nextArena ); pInfo->items--; LOCAL_ShrinkArena( ds, arena, newsize ); } /*********************************************************************** * LOCAL_GetFreeSpace */ static WORD LOCAL_GetFreeSpace(WORD ds, WORD countdiscard) { char *ptr = MapSL( MAKESEGPTR( ds, 0 ) ); LOCALHEAPINFO *pInfo; LOCALARENA *pArena; WORD arena; WORD freespace = 0; if (!(pInfo = LOCAL_GetHeap( ds ))) { ERR("Local heap not found\n" ); LOCAL_PrintHeap(ds); return 0; } arena = pInfo->first; pArena = ARENA_PTR( ptr, arena ); while (arena != pArena->free_next) { arena = pArena->free_next; pArena = ARENA_PTR( ptr, arena ); if (pArena->size >= freespace) freespace = pArena->size; } /* FIXME doesn't yet calculate space that would become free if everything were discarded when countdiscard == 1 */ if (freespace < ARENA_HEADER_SIZE) freespace = 0; else freespace -= ARENA_HEADER_SIZE; return freespace; } /*********************************************************************** * LOCAL_Compact */ static UINT16 LOCAL_Compact( HANDLE16 ds, UINT16 minfree, UINT16 flags ) { char *ptr = MapSL( MAKESEGPTR( ds, 0 ) ); LOCALHEAPINFO *pInfo; LOCALARENA *pArena, *pMoveArena, *pFinalArena; WORD arena, movearena, finalarena, table; WORD count, movesize, size; WORD freespace; LOCALHANDLEENTRY *pEntry; if (!(pInfo = LOCAL_GetHeap( ds ))) { ERR("Local heap not found\n" ); LOCAL_PrintHeap(ds); return 0; } TRACE("ds = %04x, minfree = %04x, flags = %04x\n", ds, minfree, flags); freespace = LOCAL_GetFreeSpace(ds, minfree ? 0 : 1); if(freespace >= minfree || (flags & LMEM_NOCOMPACT)) { TRACE("Returning %04x.\n", freespace); return freespace; } TRACE("Compacting heap %04x.\n", ds); table = pInfo->htable; while(table) { pEntry = (LOCALHANDLEENTRY *)(ptr + table + sizeof(WORD)); for(count = *(WORD *)(ptr + table); count > 0; count--, pEntry++) { if((pEntry->lock == 0) && (pEntry->flags != (LMEM_DISCARDED >> 8))) { /* OK we can move this one if we want */ TRACE("handle %04x (block %04x) can be moved.\n", (WORD)((char *)pEntry - ptr), pEntry->addr); movearena = ARENA_HEADER(pEntry->addr - MOVEABLE_PREFIX); pMoveArena = ARENA_PTR(ptr, movearena); movesize = pMoveArena->next - movearena; arena = pInfo->first; pArena = ARENA_PTR(ptr, arena); size = 0xffff; finalarena = 0; /* Try to find the smallest arena that will do, */ /* which is below us in memory */ for(;;) { arena = pArena->free_next; pArena = ARENA_PTR(ptr, arena); if(arena >= movearena) break; if(arena == pArena->free_next) break; if((pArena->size >= movesize) && (pArena->size < size)) { size = pArena->size; finalarena = arena; } } if (finalarena) /* Actually got somewhere to move */ { TRACE("Moving it to %04x.\n", finalarena); pFinalArena = ARENA_PTR(ptr, finalarena); size = pFinalArena->size; LOCAL_RemoveFreeBlock(ptr, finalarena); LOCAL_ShrinkArena( ds, finalarena, movesize ); /* Copy the arena to its new location */ memcpy((char *)pFinalArena + ARENA_HEADER_SIZE, (char *)pMoveArena + ARENA_HEADER_SIZE, movesize - ARENA_HEADER_SIZE ); /* Free the old location */ LOCAL_FreeArena(ds, movearena); call_notify_func(pInfo->notify, LN_MOVE, (WORD)((char *)pEntry - ptr), pEntry->addr); /* Update handle table entry */ pEntry->addr = finalarena + ARENA_HEADER_SIZE + MOVEABLE_PREFIX; } else if((ARENA_PTR(ptr, pMoveArena->prev & ~3)->prev & 3) == LOCAL_ARENA_FREE) { /* Previous arena is free (but < movesize) */ /* so we can 'slide' movearena down into it */ finalarena = pMoveArena->prev & ~3; LOCAL_GrowArenaDownward( ds, movearena, movesize ); /* Update handle table entry */ pEntry->addr = finalarena + ARENA_HEADER_SIZE + MOVEABLE_PREFIX; } } } table = *(WORD *)pEntry; } freespace = LOCAL_GetFreeSpace(ds, minfree ? 0 : 1); if(freespace >= minfree || (flags & LMEM_NODISCARD)) { TRACE("Returning %04x.\n", freespace); return freespace; } table = pInfo->htable; while(table) { pEntry = (LOCALHANDLEENTRY *)(ptr + table + sizeof(WORD)); for(count = *(WORD *)(ptr + table); count > 0; count--, pEntry++) { if(pEntry->addr && pEntry->lock == 0 && (pEntry->flags & (LMEM_DISCARDABLE >> 8))) { TRACE("Discarding handle %04x (block %04x).\n", (char *)pEntry - ptr, pEntry->addr); LOCAL_FreeArena(ds, ARENA_HEADER(pEntry->addr - MOVEABLE_PREFIX)); call_notify_func(pInfo->notify, LN_DISCARD, (char *)pEntry - ptr, pEntry->flags); pEntry->addr = 0; pEntry->flags = (LMEM_DISCARDED >> 8); } } table = *(WORD *)pEntry; } return LOCAL_Compact(ds, 0xffff, LMEM_NODISCARD); } /*********************************************************************** * LOCAL_FindFreeBlock */ static HLOCAL16 LOCAL_FindFreeBlock( HANDLE16 ds, WORD size ) { char *ptr = MapSL( MAKESEGPTR( ds, 0 ) ); LOCALHEAPINFO *pInfo; LOCALARENA *pArena; WORD arena; if (!(pInfo = LOCAL_GetHeap( ds ))) { ERR("Local heap not found\n" ); LOCAL_PrintHeap(ds); return 0; } arena = pInfo->first; pArena = ARENA_PTR( ptr, arena ); for (;;) { arena = pArena->free_next; pArena = ARENA_PTR( ptr, arena ); if (arena == pArena->free_next) break; if (pArena->size >= size) return arena; } TRACE("not enough space\n" ); LOCAL_PrintHeap(ds); return 0; } /*********************************************************************** * get_heap_name */ static const char *get_heap_name( WORD ds ) { HINSTANCE16 inst = LoadLibrary16( "GDI" ); if (ds == GlobalHandleToSel16( inst )) { FreeLibrary16( inst ); return "GDI"; } FreeLibrary16( inst ); inst = LoadLibrary16( "USER" ); if (ds == GlobalHandleToSel16( inst )) { FreeLibrary16( inst ); return "USER"; } FreeLibrary16( inst ); return "local"; } /*********************************************************************** * LOCAL_GetBlock * The segment may get moved around in this function, so all callers * should reset their pointer variables. */ static HLOCAL16 LOCAL_GetBlock( HANDLE16 ds, WORD size, WORD flags ) { char *ptr = MapSL( MAKESEGPTR( ds, 0 ) ); LOCALHEAPINFO *pInfo; LOCALARENA *pArena; WORD arena; if (!(pInfo = LOCAL_GetHeap( ds ))) { ERR("Local heap not found\n"); LOCAL_PrintHeap(ds); return 0; } size += ARENA_HEADER_SIZE; size = LALIGN( max( size, sizeof(LOCALARENA) ) ); #if 0 notify_done: #endif /* Find a suitable free block */ arena = LOCAL_FindFreeBlock( ds, size ); if (arena == 0) { /* no space: try to make some */ LOCAL_Compact( ds, size, flags ); arena = LOCAL_FindFreeBlock( ds, size ); } if (arena == 0) { /* still no space: try to grow the segment */ if (!(LOCAL_GrowHeap( ds ))) { #if 0 /* FIXME: doesn't work correctly yet */ if (call_notify_func(pInfo->notify, LN_OUTOFMEM, ds - 20, size)) /* FIXME: "size" correct ? (should indicate bytes needed) */ goto notify_done; #endif ERR( "not enough space in %s heap %04x for %d bytes\n", get_heap_name(ds), ds, size ); return 0; } ptr = MapSL( MAKESEGPTR( ds, 0 ) ); pInfo = LOCAL_GetHeap( ds ); arena = LOCAL_FindFreeBlock( ds, size ); } if (arena == 0) { ERR( "not enough space in %s heap %04x for %d bytes\n", get_heap_name(ds), ds, size ); #if 0 /* FIXME: "size" correct ? (should indicate bytes needed) */ if (call_notify_func(pInfo->notify, LN_OUTOFMEM, ds, size)) goto notify_done; #endif return 0; } /* Make a block out of the free arena */ pArena = ARENA_PTR( ptr, arena ); TRACE("size = %04x, arena %04x size %04x\n", size, arena, pArena->size ); LOCAL_RemoveFreeBlock( ptr, arena ); LOCAL_ShrinkArena( ds, arena, size ); if (flags & LMEM_ZEROINIT) memset((char *)pArena + ARENA_HEADER_SIZE, 0, size-ARENA_HEADER_SIZE); return arena + ARENA_HEADER_SIZE; } /*********************************************************************** * LOCAL_NewHTable */ static BOOL16 LOCAL_NewHTable( HANDLE16 ds ) { char *ptr; LOCALHEAPINFO *pInfo; LOCALHANDLEENTRY *pEntry; HLOCAL16 handle; int i; TRACE("\n" ); if (!(pInfo = LOCAL_GetHeap( ds ))) { ERR("Local heap not found\n"); LOCAL_PrintHeap(ds); return FALSE; } if (!(handle = LOCAL_GetBlock( ds, pInfo->hdelta * sizeof(LOCALHANDLEENTRY) + 2 * sizeof(WORD), LMEM_FIXED ))) return FALSE; if (!(ptr = MapSL( MAKESEGPTR( ds, 0 ) ))) ERR("ptr == NULL after GetBlock.\n"); if (!(pInfo = LOCAL_GetHeap( ds ))) ERR("pInfo == NULL after GetBlock.\n"); /* Fill the entry table */ *(WORD *)(ptr + handle) = pInfo->hdelta; pEntry = (LOCALHANDLEENTRY *)(ptr + handle + sizeof(WORD)); for (i = pInfo->hdelta; i > 0; i--, pEntry++) { pEntry->lock = pEntry->flags = 0xff; pEntry->addr = 0; } *(WORD *)pEntry = pInfo->htable; pInfo->htable = handle; return TRUE; } /*********************************************************************** * LOCAL_GetNewHandleEntry */ static HLOCAL16 LOCAL_GetNewHandleEntry( HANDLE16 ds ) { char *ptr = MapSL( MAKESEGPTR( ds, 0 ) ); LOCALHEAPINFO *pInfo; LOCALHANDLEENTRY *pEntry = NULL; WORD table; if (!(pInfo = LOCAL_GetHeap( ds ))) { ERR("Local heap not found\n"); LOCAL_PrintHeap(ds); return 0; } /* Find a free slot in existing tables */ table = pInfo->htable; while (table) { WORD count = *(WORD *)(ptr + table); pEntry = (LOCALHANDLEENTRY *)(ptr + table + sizeof(WORD)); for (; count > 0; count--, pEntry++) if (pEntry->lock == 0xff) break; if (count) break; table = *(WORD *)pEntry; } if (!table) /* We need to create a new table */ { if (!LOCAL_NewHTable( ds )) return 0; ptr = MapSL( MAKESEGPTR( ds, 0 ) ); pInfo = LOCAL_GetHeap( ds ); pEntry = (LOCALHANDLEENTRY *)(ptr + pInfo->htable + sizeof(WORD)); } /* Now allocate this entry */ pEntry->lock = 0; pEntry->flags = 0; TRACE("(%04x): %04x\n", ds, ((char *)pEntry - ptr) ); return (HLOCAL16)((char *)pEntry - ptr); } /*********************************************************************** * LOCAL_FreeHandleEntry * * Free a handle table entry. */ static void LOCAL_FreeHandleEntry( HANDLE16 ds, HLOCAL16 handle ) { char *ptr = MapSL( MAKESEGPTR( ds, 0 ) ); LOCALHANDLEENTRY *pEntry = (LOCALHANDLEENTRY *)(ptr + handle); LOCALHEAPINFO *pInfo; WORD *pTable; WORD table, count, i; if (!(pInfo = LOCAL_GetHeap( ds ))) return; /* Find the table where this handle comes from */ pTable = &pInfo->htable; while (*pTable) { WORD size = (*(WORD *)(ptr + *pTable)) * sizeof(LOCALHANDLEENTRY); if ((handle >= *pTable + sizeof(WORD)) && (handle < *pTable + sizeof(WORD) + size)) break; /* Found it */ pTable = (WORD *)(ptr + *pTable + sizeof(WORD) + size); } if (!*pTable) { ERR("Invalid entry %04x\n", handle); LOCAL_PrintHeap( ds ); return; } /* Make the entry free */ pEntry->addr = 0; /* just in case */ pEntry->lock = 0xff; pEntry->flags = 0xff; /* Now check if all entries in this table are free */ table = *pTable; pEntry = (LOCALHANDLEENTRY *)(ptr + table + sizeof(WORD)); count = *(WORD *)(ptr + table); for (i = count; i > 0; i--, pEntry++) if (pEntry->lock != 0xff) return; /* Remove the table from the linked list and free it */ TRACE("(%04x): freeing table %04x\n", ds, table); *pTable = *(WORD *)pEntry; LOCAL_FreeArena( ds, ARENA_HEADER( table ) ); } /*********************************************************************** * LocalFree (KERNEL.7) */ HLOCAL16 WINAPI LocalFree16( HLOCAL16 handle ) { HANDLE16 ds = CURRENT_DS; char *ptr = MapSL( MAKESEGPTR( ds, 0 ) ); TRACE("%04x ds=%04x\n", handle, ds ); if (!handle) { WARN("Handle is 0.\n" ); return 0; } if (HANDLE_FIXED( handle )) { if (!LOCAL_FreeArena( ds, ARENA_HEADER( handle ) )) return 0; /* OK */ else return handle; /* couldn't free it */ } else { LOCALHANDLEENTRY *pEntry = (LOCALHANDLEENTRY *)(ptr + handle); if (pEntry->flags != (LMEM_DISCARDED >> 8)) { TRACE("real block at %04x\n", pEntry->addr ); if (LOCAL_FreeArena( ds, ARENA_HEADER(pEntry->addr - MOVEABLE_PREFIX) )) return handle; /* couldn't free it */ } LOCAL_FreeHandleEntry( ds, handle ); return 0; /* OK */ } } /*********************************************************************** * LocalAlloc (KERNEL.5) */ HLOCAL16 WINAPI LocalAlloc16( UINT16 flags, WORD size ) { HANDLE16 ds = CURRENT_DS; HLOCAL16 handle = 0; char *ptr; TRACE("%04x %d ds=%04x\n", flags, size, ds ); if(size > 0 && size <= 4) size = 5; if (flags & LMEM_MOVEABLE) { LOCALHANDLEENTRY *plhe; HLOCAL16 hmem; if(size) { if (!(hmem = LOCAL_GetBlock( ds, size + MOVEABLE_PREFIX, flags ))) goto exit; } else /* We just need to allocate a discarded handle */ hmem = 0; if (!(handle = LOCAL_GetNewHandleEntry( ds ))) { WARN("Couldn't get handle.\n"); if(hmem) LOCAL_FreeArena( ds, ARENA_HEADER(hmem) ); goto exit; } ptr = MapSL( MAKESEGPTR( ds, 0 ) ); plhe = (LOCALHANDLEENTRY *)(ptr + handle); plhe->lock = 0; if(hmem) { plhe->addr = hmem + MOVEABLE_PREFIX; plhe->flags = (BYTE)((flags & 0x0f00) >> 8); *(HLOCAL16 *)(ptr + hmem) = handle; } else { plhe->addr = 0; plhe->flags = LMEM_DISCARDED >> 8; } } else /* FIXED */ { if(size) handle = LOCAL_GetBlock( ds, size, flags ); } exit: CURRENT_STACK16->ecx = handle; /* must be returned in cx too */ return handle; } /*********************************************************************** * LocalReAlloc (KERNEL.6) */ HLOCAL16 WINAPI LocalReAlloc16( HLOCAL16 handle, WORD size, UINT16 flags ) { HANDLE16 ds = CURRENT_DS; char *ptr = MapSL( MAKESEGPTR( ds, 0 ) ); LOCALHEAPINFO *pInfo; LOCALARENA *pArena, *pNext; LOCALHANDLEENTRY *pEntry = NULL; WORD arena, oldsize; HLOCAL16 hmem, blockhandle; LONG nextarena; if (!handle) return 0; if(HANDLE_MOVEABLE(handle) && ((LOCALHANDLEENTRY *)(ptr + handle))->lock == 0xff) /* An unused handle */ return 0; TRACE("%04x %d %04x ds=%04x\n", handle, size, flags, ds ); if (!(pInfo = LOCAL_GetHeap( ds ))) return 0; if (HANDLE_FIXED( handle )) blockhandle = handle; else { pEntry = (LOCALHANDLEENTRY *) (ptr + handle); if(pEntry->flags == (LMEM_DISCARDED >> 8)) { HLOCAL16 hl; if(pEntry->addr) WARN("Dicarded block has non-zero addr.\n"); TRACE("ReAllocating discarded block\n"); if(size <= 4) size = 5; if (!(hl = LOCAL_GetBlock( ds, size + MOVEABLE_PREFIX, flags))) return 0; ptr = MapSL( MAKESEGPTR( ds, 0 ) ); /* Reload ptr */ pEntry = (LOCALHANDLEENTRY *) (ptr + handle); pEntry->addr = hl + MOVEABLE_PREFIX; pEntry->flags = 0; pEntry->lock = 0; *(HLOCAL16 *)(ptr + hl) = handle; return handle; } if (((blockhandle = pEntry->addr - MOVEABLE_PREFIX) & 3) != 0) { ERR("(%04x,%04x): invalid handle\n", ds, handle ); return 0; } if (*(HLOCAL16 *)(ptr + blockhandle) != handle) { ERR("Back ptr to handle is invalid\n"); return 0; } } if (flags & LMEM_MODIFY) { if (HANDLE_MOVEABLE(handle)) { pEntry = (LOCALHANDLEENTRY *)(ptr + handle); pEntry->flags = (flags & 0x0f00) >> 8; TRACE("Changing flags to %x.\n", pEntry->flags); } return handle; } if (!size) { if (flags & LMEM_MOVEABLE) { if (HANDLE_FIXED(handle)) { TRACE("Freeing fixed block.\n"); return LocalFree16( handle ); } else /* Moveable block */ { pEntry = (LOCALHANDLEENTRY *)(ptr + handle); if (pEntry->lock == 0) { /* discards moveable blocks */ TRACE("Discarding block\n"); LOCAL_FreeArena(ds, ARENA_HEADER(pEntry->addr - MOVEABLE_PREFIX)); pEntry->addr = 0; pEntry->flags = (LMEM_DISCARDED >> 8); return handle; } } return 0; } else if(flags == 0) { pEntry = (LOCALHANDLEENTRY *)(ptr + handle); if (pEntry->lock == 0) { /* Frees block */ return LocalFree16( handle ); } } return 0; } arena = ARENA_HEADER( blockhandle ); TRACE("arena is %04x\n", arena ); pArena = ARENA_PTR( ptr, arena ); if(size <= 4) size = 5; if(HANDLE_MOVEABLE(handle)) size += MOVEABLE_PREFIX; oldsize = pArena->next - arena - ARENA_HEADER_SIZE; nextarena = LALIGN(blockhandle + size); /* Check for size reduction */ if (nextarena <= pArena->next) { TRACE("size reduction, making new free block\n"); LOCAL_ShrinkArena(ds, arena, nextarena - arena); TRACE("returning %04x\n", handle ); return handle; } /* Check if the next block is free and large enough */ pNext = ARENA_PTR( ptr, pArena->next ); if (((pNext->prev & 3) == LOCAL_ARENA_FREE) && (nextarena <= pNext->next)) { TRACE("size increase, making new free block\n"); LOCAL_GrowArenaUpward(ds, arena, nextarena - arena); if (flags & LMEM_ZEROINIT) { char *oldend = (char *)pArena + ARENA_HEADER_SIZE + oldsize; char *newend = ptr + pArena->next; TRACE("Clearing memory from %p to %p (DS -> %p)\n", oldend, newend, ptr); memset(oldend, 0, newend - oldend); } TRACE("returning %04x\n", handle ); return handle; } /* Now we have to allocate a new block, but not if (fixed block or locked block) and no LMEM_MOVEABLE */ if (!(flags & LMEM_MOVEABLE)) { if (HANDLE_FIXED(handle)) { ERR("Needed to move fixed block, but LMEM_MOVEABLE not specified.\n"); return 0; } else { if(((LOCALHANDLEENTRY *)(ptr + handle))->lock != 0) { ERR("Needed to move locked block, but LMEM_MOVEABLE not specified.\n"); return 0; } } } hmem = LOCAL_GetBlock( ds, size, flags ); ptr = MapSL( MAKESEGPTR( ds, 0 )); /* Reload ptr */ if(HANDLE_MOVEABLE(handle)) /* LOCAL_GetBlock might have triggered */ { /* a compaction, which might in turn have */ blockhandle = pEntry->addr - MOVEABLE_PREFIX; /* moved the very block we are resizing */ arena = ARENA_HEADER( blockhandle ); /* thus, we reload arena, too */ } if (!hmem) { /* Remove the block from the heap and try again */ LPSTR buffer = HeapAlloc( GetProcessHeap(), 0, oldsize ); if (!buffer) return 0; memcpy( buffer, ptr + arena + ARENA_HEADER_SIZE, oldsize ); LOCAL_FreeArena( ds, arena ); if (!(hmem = LOCAL_GetBlock( ds, size, flags ))) { if (!(hmem = LOCAL_GetBlock( ds, oldsize, flags ))) { ERR("Can't restore saved block\n" ); HeapFree( GetProcessHeap(), 0, buffer ); return 0; } size = oldsize; } ptr = MapSL( MAKESEGPTR( ds, 0 ) ); /* Reload ptr */ memcpy( ptr + hmem, buffer, oldsize ); HeapFree( GetProcessHeap(), 0, buffer ); } else { memcpy( ptr + hmem, ptr + (arena + ARENA_HEADER_SIZE), oldsize ); LOCAL_FreeArena( ds, arena ); } if (HANDLE_MOVEABLE( handle )) { TRACE("fixing handle\n"); pEntry = (LOCALHANDLEENTRY *)(ptr + handle); pEntry->addr = hmem + MOVEABLE_PREFIX; /* Back ptr should still be correct */ if(*(HLOCAL16 *)(ptr + hmem) != handle) ERR("back ptr is invalid.\n"); hmem = handle; } if (size == oldsize) hmem = 0; /* Realloc failed */ TRACE("returning %04x\n", hmem ); return hmem; } /*********************************************************************** * LOCAL_InternalLock */ static HLOCAL16 LOCAL_InternalLock( LPSTR heap, HLOCAL16 handle ) { HLOCAL16 old_handle = handle; if (HANDLE_MOVEABLE(handle)) { LOCALHANDLEENTRY *pEntry = (LOCALHANDLEENTRY *)(heap + handle); if (pEntry->flags == (LMEM_DISCARDED >> 8)) return 0; if (pEntry->lock < 0xfe) pEntry->lock++; handle = pEntry->addr; } TRACE("%04x returning %04x\n", old_handle, handle ); return handle; } /*********************************************************************** * LocalUnlock (KERNEL.9) */ BOOL16 WINAPI LocalUnlock16( HLOCAL16 handle ) { HANDLE16 ds = CURRENT_DS; char *ptr = MapSL( MAKESEGPTR( ds, 0 ) ); TRACE("%04x\n", handle ); if (HANDLE_MOVEABLE(handle)) { LOCALHANDLEENTRY *pEntry = (LOCALHANDLEENTRY *)(ptr + handle); if (!pEntry->lock || (pEntry->lock == 0xff)) return FALSE; /* For moveable block, return the new lock count */ /* (see _Windows_Internals_ p. 197) */ return --pEntry->lock; } else return FALSE; } /*********************************************************************** * LocalSize (KERNEL.10) */ UINT16 WINAPI LocalSize16( HLOCAL16 handle ) { HANDLE16 ds = CURRENT_DS; char *ptr = MapSL( MAKESEGPTR( ds, 0 ) ); LOCALARENA *pArena; TRACE("%04x ds=%04x\n", handle, ds ); if (!handle) return 0; if (HANDLE_MOVEABLE( handle )) { handle = *(WORD *)(ptr + handle); if (!handle) return 0; pArena = ARENA_PTR( ptr, ARENA_HEADER(handle - MOVEABLE_PREFIX) ); } else pArena = ARENA_PTR( ptr, ARENA_HEADER(handle) ); return pArena->next - handle; } /*********************************************************************** * LocalFlags (KERNEL.12) */ UINT16 WINAPI LocalFlags16( HLOCAL16 handle ) { HANDLE16 ds = CURRENT_DS; char *ptr = MapSL( MAKESEGPTR( ds, 0 ) ); if (HANDLE_MOVEABLE(handle)) { LOCALHANDLEENTRY *pEntry = (LOCALHANDLEENTRY *)(ptr + handle); TRACE("(%04x,%04x): returning %04x\n", ds, handle, pEntry->lock | (pEntry->flags << 8) ); return pEntry->lock | (pEntry->flags << 8); } else { TRACE("(%04x,%04x): returning 0\n", ds, handle ); return 0; } } /*********************************************************************** * LocalHeapSize (KERNEL.162) */ WORD WINAPI LocalHeapSize16(void) { HANDLE16 ds = CURRENT_DS; LOCALHEAPINFO *pInfo = LOCAL_GetHeap( ds ); return pInfo ? pInfo->last - pInfo->first : 0; } /*********************************************************************** * LocalCountFree (KERNEL.161) */ WORD WINAPI LocalCountFree16(void) { HANDLE16 ds = CURRENT_DS; WORD arena, total; LOCALARENA *pArena; LOCALHEAPINFO *pInfo; char *ptr = MapSL( MAKESEGPTR( ds, 0 ) ); if (!(pInfo = LOCAL_GetHeap( ds ))) { ERR("(%04x): Local heap not found\n", ds ); LOCAL_PrintHeap( ds ); return 0; } total = 0; arena = pInfo->first; pArena = ARENA_PTR( ptr, arena ); for (;;) { arena = pArena->free_next; pArena = ARENA_PTR( ptr, arena ); if (arena == pArena->free_next) break; total += pArena->size; } TRACE("(%04x): returning %d\n", ds, total); return total; } /*********************************************************************** * LocalHandle (KERNEL.11) */ HLOCAL16 WINAPI LocalHandle16( WORD addr ) { HANDLE16 ds = CURRENT_DS; char *ptr = MapSL( MAKESEGPTR( ds, 0 ) ); LOCALHEAPINFO *pInfo; WORD table; if (!(pInfo = LOCAL_GetHeap( ds ))) { ERR("(%04x): Local heap not found\n", ds ); LOCAL_PrintHeap( ds ); return 0; } /* Find the address in the entry tables */ table = pInfo->htable; while (table) { WORD count = *(WORD *)(ptr + table); LOCALHANDLEENTRY *pEntry = (LOCALHANDLEENTRY*)(ptr+table+sizeof(WORD)); for (; count > 0; count--, pEntry++) if (pEntry->addr == addr) return (HLOCAL16)((char *)pEntry - ptr); table = *(WORD *)pEntry; } return (HLOCAL16)addr; /* Fixed block handle is addr */ } /*********************************************************************** * LocalLock (KERNEL.8) * * Note: only the offset part of the pointer is returned by the relay code. */ SEGPTR WINAPI LocalLock16( HLOCAL16 handle ) { WORD ds = CURRENT_DS; char *ptr = MapSL( MAKESEGPTR( ds, 0 ) ); return MAKESEGPTR( ds, LOCAL_InternalLock( ptr, handle ) ); } /*********************************************************************** * LocalCompact (KERNEL.13) */ UINT16 WINAPI LocalCompact16( UINT16 minfree ) { TRACE("%04x\n", minfree ); return LOCAL_Compact( CURRENT_DS, minfree, 0 ); } /*********************************************************************** * LocalNotify (KERNEL.14) * * Installs a callback function that is called for local memory events * Callback function prototype is * BOOL16 NotifyFunc(WORD wMsg, HLOCAL16 hMem, WORD wArg) * wMsg: * - LN_OUTOFMEM * NotifyFunc seems to be responsible for allocating some memory, * returns TRUE for success. * wArg = number of bytes needed additionally * - LN_MOVE * hMem = handle; wArg = old mem location * - LN_DISCARD * NotifyFunc seems to be strongly encouraged to return TRUE, * otherwise LogError() gets called. * hMem = handle; wArg = flags */ FARPROC16 WINAPI LocalNotify16( FARPROC16 func ) { LOCALHEAPINFO *pInfo; FARPROC16 oldNotify; HANDLE16 ds = CURRENT_DS; if (!(pInfo = LOCAL_GetHeap( ds ))) { ERR("(%04x): Local heap not found\n", ds ); LOCAL_PrintHeap( ds ); return 0; } TRACE("(%04x): %p\n", ds, func ); FIXME("Half implemented\n"); oldNotify = pInfo->notify; pInfo->notify = func; return oldNotify; } /*********************************************************************** * LocalShrink (KERNEL.121) */ UINT16 WINAPI LocalShrink16( HGLOBAL16 handle, UINT16 newsize ) { TRACE("%04x %04x\n", handle, newsize ); return 0; } /*********************************************************************** * GetHeapSpaces (KERNEL.138) */ DWORD WINAPI GetHeapSpaces16( HMODULE16 module ) { NE_MODULE *pModule; WORD oldDS = CURRENT_DS; DWORD spaces; if (!(pModule = NE_GetPtr( module ))) return 0; CURRENT_DS = GlobalHandleToSel16((NE_SEG_TABLE( pModule ) + pModule->ne_autodata - 1)->hSeg); spaces = MAKELONG( LocalCountFree16(), LocalHeapSize16() ); CURRENT_DS = oldDS; return spaces; } /*********************************************************************** * LocalHandleDelta (KERNEL.310) */ WORD WINAPI LocalHandleDelta16( WORD delta ) { LOCALHEAPINFO *pInfo; if (!(pInfo = LOCAL_GetHeap( CURRENT_DS ))) { ERR("Local heap not found\n"); LOCAL_PrintHeap( CURRENT_DS ); return 0; } if (delta) pInfo->hdelta = delta; TRACE("returning %04x\n", pInfo->hdelta); return pInfo->hdelta; } /*********************************************************************** * 32-bit local heap functions (Win95; undocumented) */ /*********************************************************************** * K208 (KERNEL.208) */ HANDLE WINAPI Local32Init16( WORD segment, DWORD tableSize, DWORD heapSize, DWORD flags ) { DWORD totSize, segSize = 0; LPBYTE base; LOCAL32HEADER *header; HANDLE heap; WORD *selectorTable; WORD selectorEven, selectorOdd; int i, nrBlocks; /* Determine new heap size */ if ( segment ) { if ( (segSize = GetSelectorLimit16( segment )) == 0 ) return 0; else segSize++; } if ( heapSize == (DWORD)-1 ) heapSize = 1024*1024; /* FIXME */ heapSize = (heapSize + 0xffff) & 0xffff0000; segSize = (segSize + 0x0fff) & 0xfffff000; totSize = segSize + HTABLE_SIZE + heapSize; /* Allocate memory and initialize heap */ if ( !(base = VirtualAlloc( NULL, totSize, MEM_RESERVE, PAGE_READWRITE )) ) return 0; if ( !VirtualAlloc( base, segSize + HTABLE_PAGESIZE, MEM_COMMIT, PAGE_READWRITE ) ) { VirtualFree( base, 0, MEM_RELEASE ); return 0; } if (!(heap = RtlCreateHeap( 0, base + segSize + HTABLE_SIZE, heapSize, 0x10000, NULL, NULL ))) { VirtualFree( base, 0, MEM_RELEASE ); return 0; } /* Set up header and handle table */ header = (LOCAL32HEADER *)(base + segSize); header->base = base; header->limit = HTABLE_PAGESIZE-1; header->flags = 0; header->magic = LOCAL32_MAGIC; header->heap = heap; header->freeListFirst[0] = sizeof(LOCAL32HEADER); header->freeListLast[0] = HTABLE_PAGESIZE - 4; header->freeListSize[0] = (HTABLE_PAGESIZE - sizeof(LOCAL32HEADER)) / 4; for (i = header->freeListFirst[0]; i < header->freeListLast[0]; i += 4) *(DWORD *)((LPBYTE)header + i) = i+4; header->freeListFirst[1] = 0xffff; /* Set up selector table */ nrBlocks = (totSize + 0x7fff) >> 15; selectorTable = HeapAlloc( header->heap, 0, nrBlocks * 2 ); selectorEven = SELECTOR_AllocBlock( base, totSize, WINE_LDT_FLAGS_DATA ); selectorOdd = SELECTOR_AllocBlock( base + 0x8000, totSize - 0x8000, WINE_LDT_FLAGS_DATA ); if ( !selectorTable || !selectorEven || !selectorOdd ) { HeapFree( header->heap, 0, selectorTable ); if ( selectorEven ) SELECTOR_FreeBlock( selectorEven ); if ( selectorOdd ) SELECTOR_FreeBlock( selectorOdd ); HeapDestroy( header->heap ); VirtualFree( base, 0, MEM_RELEASE ); return 0; } header->selectorTableOffset = (LPBYTE)selectorTable - header->base; header->selectorTableSize = nrBlocks * 4; /* ??? Win95 does it this way! */ header->selectorDelta = selectorEven - selectorOdd; header->segment = segment? segment : selectorEven; for (i = 0; i < nrBlocks; i++) selectorTable[i] = (i & 1)? selectorOdd + ((i >> 1) << __AHSHIFT) : selectorEven + ((i >> 1) << __AHSHIFT); /* Move old segment */ if ( segment ) { /* FIXME: This is somewhat ugly and relies on implementation details about 16-bit global memory handles ... */ LPBYTE oldBase = (LPBYTE)GetSelectorBase( segment ); memcpy( base, oldBase, segSize ); GLOBAL_MoveBlock( segment, base, totSize ); HeapFree( GetProcessHeap(), 0, oldBase ); } return header; } /*********************************************************************** * Local32_SearchHandle */ static LPDWORD Local32_SearchHandle( LOCAL32HEADER *header, DWORD addr ) { LPDWORD handle; for ( handle = (LPDWORD)((LPBYTE)header + sizeof(LOCAL32HEADER)); handle < (LPDWORD)((LPBYTE)header + header->limit); handle++) { if (*handle == addr) return handle; } return NULL; } /*********************************************************************** * Local32_ToHandle */ static VOID Local32_ToHandle( LOCAL32HEADER *header, INT16 type, DWORD addr, LPDWORD *handle, LPBYTE *ptr ) { *handle = NULL; *ptr = NULL; switch (type) { case -2: /* 16:16 pointer, no handles */ *ptr = MapSL( addr ); *handle = (LPDWORD)*ptr; break; case -1: /* 32-bit offset, no handles */ *ptr = header->base + addr; *handle = (LPDWORD)*ptr; break; case 0: /* handle */ if ( addr >= sizeof(LOCAL32HEADER) && addr < header->limit && !(addr & 3) && *(LPDWORD)((LPBYTE)header + addr) >= HTABLE_SIZE ) { *handle = (LPDWORD)((LPBYTE)header + addr); *ptr = header->base + **handle; } break; case 1: /* 16:16 pointer */ *ptr = MapSL( addr ); *handle = Local32_SearchHandle( header, *ptr - header->base ); break; case 2: /* 32-bit offset */ *ptr = header->base + addr; *handle = Local32_SearchHandle( header, *ptr - header->base ); break; } } /*********************************************************************** * Local32_FromHandle */ static VOID Local32_FromHandle( LOCAL32HEADER *header, INT16 type, DWORD *addr, LPDWORD handle, LPBYTE ptr ) { *addr = 0; switch (type) { case -2: /* 16:16 pointer */ case 1: { WORD *selTable = (LPWORD)(header->base + header->selectorTableOffset); DWORD offset = ptr - header->base; *addr = MAKELONG( offset & 0x7fff, selTable[offset >> 15] ); } break; case -1: /* 32-bit offset */ case 2: *addr = ptr - header->base; break; case 0: /* handle */ *addr = (LPBYTE)handle - (LPBYTE)header; break; } } /*********************************************************************** * K209 (KERNEL.209) */ DWORD WINAPI Local32Alloc16( HANDLE heap, DWORD size, INT16 type, DWORD flags ) { LOCAL32HEADER *header = heap; LPDWORD handle; LPBYTE ptr; DWORD addr; /* Allocate memory */ ptr = HeapAlloc( header->heap, (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0, size ); if (!ptr) return 0; /* Allocate handle if requested */ if (type >= 0) { int page, i; /* Find first page of handle table with free slots */ for (page = 0; page < HTABLE_NPAGES; page++) if (header->freeListFirst[page] != 0) break; if (page == HTABLE_NPAGES) { WARN("Out of handles!\n" ); HeapFree( header->heap, 0, ptr ); return 0; } /* If virgin page, initialize it */ if (header->freeListFirst[page] == 0xffff) { if ( !VirtualAlloc( (LPBYTE)header + (page << 12), 0x1000, MEM_COMMIT, PAGE_READWRITE ) ) { WARN("Cannot grow handle table!\n" ); HeapFree( header->heap, 0, ptr ); return 0; } header->limit += HTABLE_PAGESIZE; header->freeListFirst[page] = 0; header->freeListLast[page] = HTABLE_PAGESIZE - 4; header->freeListSize[page] = HTABLE_PAGESIZE / 4; for (i = 0; i < HTABLE_PAGESIZE; i += 4) *(DWORD *)((LPBYTE)header + i) = i+4; if (page < HTABLE_NPAGES-1) header->freeListFirst[page+1] = 0xffff; } /* Allocate handle slot from page */ handle = (LPDWORD)((LPBYTE)header + header->freeListFirst[page]); if (--header->freeListSize[page] == 0) header->freeListFirst[page] = header->freeListLast[page] = 0; else header->freeListFirst[page] = *handle; /* Store 32-bit offset in handle slot */ *handle = ptr - header->base; } else { handle = (LPDWORD)ptr; header->flags |= 1; } /* Convert handle to requested output type */ Local32_FromHandle( header, type, &addr, handle, ptr ); return addr; } /*********************************************************************** * K210 (KERNEL.210) */ DWORD WINAPI Local32ReAlloc16( HANDLE heap, DWORD addr, INT16 type, DWORD size, DWORD flags ) { LOCAL32HEADER *header = heap; LPDWORD handle; LPBYTE ptr; if (!addr) return Local32Alloc16( heap, size, type, flags ); /* Retrieve handle and pointer */ Local32_ToHandle( header, type, addr, &handle, &ptr ); if (!handle) return FALSE; /* Reallocate memory block */ ptr = HeapReAlloc( header->heap, (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0, ptr, size ); if (!ptr) return 0; /* Modify handle */ if (type >= 0) *handle = ptr - header->base; else handle = (LPDWORD)ptr; /* Convert handle to requested output type */ Local32_FromHandle( header, type, &addr, handle, ptr ); return addr; } /*********************************************************************** * K211 (KERNEL.211) */ BOOL WINAPI Local32Free16( HANDLE heap, DWORD addr, INT16 type ) { LOCAL32HEADER *header = heap; LPDWORD handle; LPBYTE ptr; /* Retrieve handle and pointer */ Local32_ToHandle( header, type, addr, &handle, &ptr ); if (!handle) return FALSE; /* Free handle if necessary */ if (type >= 0) { int offset = (LPBYTE)handle - (LPBYTE)header; int page = offset >> 12; /* Return handle slot to page free list */ if (header->freeListSize[page]++ == 0) header->freeListFirst[page] = header->freeListLast[page] = offset; else *(LPDWORD)((LPBYTE)header + header->freeListLast[page]) = offset, header->freeListLast[page] = offset; *handle = 0; /* Shrink handle table when possible */ while (page > 0 && header->freeListSize[page] == HTABLE_PAGESIZE / 4) { if ( VirtualFree( (LPBYTE)header + (header->limit & ~(HTABLE_PAGESIZE-1)), HTABLE_PAGESIZE, MEM_DECOMMIT ) ) break; header->limit -= HTABLE_PAGESIZE; header->freeListFirst[page] = 0xffff; page--; } } /* Free memory */ return HeapFree( header->heap, 0, ptr ); } /*********************************************************************** * K213 (KERNEL.213) */ DWORD WINAPI Local32Translate16( HANDLE heap, DWORD addr, INT16 type1, INT16 type2 ) { LOCAL32HEADER *header = heap; LPDWORD handle; LPBYTE ptr; Local32_ToHandle( header, type1, addr, &handle, &ptr ); if (!handle) return 0; Local32_FromHandle( header, type2, &addr, handle, ptr ); return addr; } /*********************************************************************** * K214 (KERNEL.214) */ DWORD WINAPI Local32Size16( HANDLE heap, DWORD addr, INT16 type ) { LOCAL32HEADER *header = heap; LPDWORD handle; LPBYTE ptr; Local32_ToHandle( header, type, addr, &handle, &ptr ); if (!handle) return 0; return HeapSize( header->heap, 0, ptr ); } /*********************************************************************** * K215 (KERNEL.215) */ BOOL WINAPI Local32ValidHandle16( HANDLE heap, WORD addr ) { LOCAL32HEADER *header = heap; LPDWORD handle; LPBYTE ptr; Local32_ToHandle( header, 0, addr, &handle, &ptr ); return handle != NULL; } /*********************************************************************** * K229 (KERNEL.229) */ WORD WINAPI Local32GetSegment16( HANDLE heap ) { LOCAL32HEADER *header = heap; return header->segment; } /*********************************************************************** * Local32_GetHeap */ static LOCAL32HEADER *Local32_GetHeap( HGLOBAL16 handle ) { WORD selector = GlobalHandleToSel16( handle ); DWORD base = GetSelectorBase( selector ); DWORD limit = GetSelectorLimit16( selector ); /* Hmmm. This is a somewhat stupid heuristic, but Windows 95 does it this way ... */ if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC ) return (LOCAL32HEADER *)base; base += 0x10000; limit -= 0x10000; if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC ) return (LOCAL32HEADER *)base; return NULL; } /*********************************************************************** * Local32Info (KERNEL.444) */ BOOL16 WINAPI Local32Info16( LOCAL32INFO *pLocal32Info, HGLOBAL16 handle ) { PROCESS_HEAP_ENTRY entry; int i; LOCAL32HEADER *header = Local32_GetHeap( handle ); if ( !header ) return FALSE; if ( !pLocal32Info || pLocal32Info->dwSize < sizeof(LOCAL32INFO) ) return FALSE; pLocal32Info->dwMemReserved = 0; pLocal32Info->dwMemCommitted = 0; pLocal32Info->dwTotalFree = 0; pLocal32Info->dwLargestFreeBlock = 0; while (HeapWalk( header->heap, &entry )) { if (entry.wFlags & PROCESS_HEAP_REGION) { pLocal32Info->dwMemReserved += entry.u.Region.dwCommittedSize + entry.u.Region.dwUnCommittedSize; pLocal32Info->dwMemCommitted = entry.u.Region.dwCommittedSize; } else if (!(entry.wFlags & PROCESS_HEAP_ENTRY_BUSY)) { DWORD size = entry.cbData + entry.cbOverhead; pLocal32Info->dwTotalFree += size; if (size > pLocal32Info->dwLargestFreeBlock) pLocal32Info->dwLargestFreeBlock = size; } } pLocal32Info->dwcFreeHandles = 0; for ( i = 0; i < HTABLE_NPAGES; i++ ) { if ( header->freeListFirst[i] == 0xffff ) break; pLocal32Info->dwcFreeHandles += header->freeListSize[i]; } pLocal32Info->dwcFreeHandles += (HTABLE_NPAGES - i) * HTABLE_PAGESIZE/4; return TRUE; } /*********************************************************************** * Local32First (KERNEL.445) */ BOOL16 WINAPI Local32First16( LOCAL32ENTRY *pLocal32Entry, HGLOBAL16 handle ) { FIXME("(%p, %04X): stub!\n", pLocal32Entry, handle ); return FALSE; } /*********************************************************************** * Local32Next (KERNEL.446) */ BOOL16 WINAPI Local32Next16( LOCAL32ENTRY *pLocal32Entry ) { FIXME("(%p): stub!\n", pLocal32Entry ); return FALSE; }
{ "language": "C" }
#define _GNU_SOURCE #include "util.h" #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <stdio.h> #include <inttypes.h> #include <string.h> #include <err.h> #include <sysexits.h> #include <glob.h> #include <string.h> #include <htslib/kstring.h> #include "unity.h" #include "bpt.h" #include "giggle_index.h" #include "lists.h" #include "file_read.h" #include "wah.h" #include "ll.h" #include "jsw_avltree.h" #include "pq.h" #define MIN(X, Y) (((X) < (Y)) ? (X) : (Y)) #define MAX(X, Y) (((X) > (Y)) ? (X) : (Y)) void setUp(void) { } void tearDown(void) { } //{{{ void test_offset_index_add_no_data(void) void test_offset_index_add_no_data(void) { //{{{ uint32_t A_offsets[1000] = uint32_t A_offsets[1000] = {0, 61, 118, 173, 230, 292, 350, 412, 476, 534, 599, 661, 726, 784, 841, 899, 964, 1026, 1085, 1145, 1204, 1267, 1330, 1388, 1447, 1508, 1566, 1627, 1686, 1747, 1810, 1873, 1935, 1992, 2050, 2108, 2167, 2226, 2285, 2344, 2401, 2460, 2519, 2578, 2636, 2702, 2766, 2826, 2886, 2947, 3009, 3069, 3128, 3188, 3248, 3312, 3375, 3441, 3499, 3559, 3622, 3683, 3746, 3804, 3863, 3922, 3983, 4043, 4104, 4164, 4225, 4285, 4352, 4413, 4480, 4544, 4607, 4668, 4729, 4792, 4853, 4917, 4978, 5037, 5101, 5161, 5218, 5285, 5346, 5409, 5465, 5526, 5583, 5645, 5706, 5767, 5827, 5887, 5950, 6010, 6069, 6133, 6193, 6254, 6316, 6375, 6435, 6494, 6557, 6616, 6676, 6736, 6796, 6855, 6915, 6975, 7033, 7092, 7158, 7218, 7277, 7337, 7397, 7455, 7518, 7577, 7637, 7701, 7761, 7822, 7885, 7951, 8016, 8078, 8140, 8202, 8264, 8326, 8388, 8453, 8513, 8575, 8636, 8698, 8752, 8810, 8868, 8926, 8985, 9043, 9103, 9162, 9222, 9282, 9341, 9401, 9461, 9524, 9583, 9641, 9700, 9762, 9822, 9882, 9945, 10008, 10065, 10128, 10188, 10248, 10308, 10370, 10427, 10487, 10547, 10606, 10665, 10726, 10788, 10853, 10914, 10976, 11039, 11104, 11168, 11229, 11291, 11355, 11413, 11470, 11525, 11584, 11641, 11698, 11755, 11815, 11877, 11936, 11999, 12058, 12120, 12184, 12244, 12304, 12364, 12427, 12491, 12549, 12610, 12674, 12738, 12803, 12869, 12929, 12990, 13049, 13111, 13171, 13233, 13296, 13356, 13416, 13480, 13539, 13599, 13663, 13725, 13787, 13851, 13913, 13978, 14044, 14105, 14166, 14226, 14288, 14351, 14411, 14471, 14530, 14589, 14651, 14715, 14773, 14832, 14893, 14957, 15016, 15075, 15135, 15194, 15253, 15313, 15373, 15432, 15491, 15550, 15610, 15670, 15731, 15790, 15848, 15910, 15970, 16033, 16092, 16156, 16216, 16276, 16335, 16392, 16452, 16511, 16569, 16628, 16686, 16746, 16804, 16870, 16932, 16993, 17055, 17116, 17176, 17235, 17297, 17357, 17415, 17474, 17537, 17596, 17656, 17717, 17779, 17839, 17899, 17958, 18018, 18079, 18138, 18200, 18259, 18317, 18376, 18439, 18503, 18566, 18625, 18687, 18748, 18808, 18870, 18931, 18991, 19054, 19115, 19175, 19234, 19296, 19358, 19417, 19475, 19536, 19596, 19658, 19716, 19776, 19837, 19899, 19958, 20016, 20073, 20137, 20203, 20262, 20321, 20382, 20441, 20504, 20564, 20629, 20688, 20747, 20806, 20865, 20923, 20982, 21041, 21103, 21164, 21222, 21285, 21341, 21398, 21457, 21516, 21575, 21634, 21694, 21757, 21822, 21881, 21941, 22000, 22059, 22123, 22181, 22239, 22297, 22355, 22411, 22470, 22531, 22595, 22654, 22715, 22778, 22839, 22898, 22956, 23016, 23080, 23140, 23199, 23259, 23319, 23382, 23445, 23504, 23564, 23626, 23693, 23757, 23816, 23876, 23936, 23996, 24055, 24113, 24172, 24232, 24293, 24353, 24415, 24474, 24536, 24594, 24653, 24712, 24776, 24840, 24896, 24956, 25012, 25069, 25128, 25184, 25244, 25303, 25364, 25424, 25487, 25546, 25606, 25664, 25722, 25784, 25843, 25902, 25962, 26021, 26079, 26138, 26200, 26259, 26321, 26382, 26443, 26505, 26563, 26620, 26682, 26738, 26798, 26856, 26915, 26975, 27036, 27098, 27158, 27221, 27283, 27343, 27406, 27466, 27525, 27587, 27646, 27705, 27767, 27828, 27887, 27947, 28006, 28065, 28131, 28191, 28254, 28314, 28372, 28431, 28491, 28551, 28615, 28681, 28741, 28800, 28859, 28919, 28978, 29038, 29104, 29165, 29225, 29287, 29344, 29401, 29458, 29519, 29578, 29636, 29695, 29754, 29812, 29871, 29934, 29996, 30057, 30116, 30174, 30233, 30291, 30352, 30411, 30473, 30531, 30592, 30652, 30716, 30775, 30834, 30896, 30959, 31016, 31074, 31133, 31194, 31254, 31317, 31376, 31436, 31497, 31558, 31618, 31678, 31739, 31802, 31865, 31928, 31988, 32048, 32106, 32167, 32231, 32290, 32355, 32414, 32474, 32534, 32599, 32660, 32721, 32781, 32842, 32905, 32966, 33027, 33090, 33151, 33213, 33278, 33338, 33399, 33460, 33520, 33578, 33639, 33699, 33759, 33819, 33878, 33941, 34001, 34065, 34125, 34185, 34245, 34304, 34362, 34421, 34487, 34546, 34605, 34664, 34724, 34787, 34846, 34905, 34967, 35027, 35089, 35148, 35207, 35267, 35329, 35389, 35451, 35511, 35570, 35630, 35691, 35755, 35814, 35873, 35935, 35998, 36064, 36124, 36183, 36247, 36310, 36369, 36430, 36489, 36551, 36611, 36670, 36730, 36790, 36850, 36914, 36974, 37033, 37093, 37152, 37210, 37269, 37327, 37390, 37455, 37512, 37571, 37631, 37687, 37743, 37806, 37864, 37922, 37985, 38043, 38102, 38164, 38223, 38280, 38341, 38399, 38461, 38522, 38583, 38642, 38700, 38760, 38822, 38882, 38940, 38999, 39064, 39124, 39185, 39248, 39309, 39369, 39434, 39495, 39556, 39616, 39680, 39741, 39802, 39862, 39925, 39990, 40052, 40116, 40177, 40237, 40298, 40359, 40418, 40479, 40540, 40599, 40665, 40726, 40787, 40850, 40914, 40970, 41027, 41085, 41141, 41202, 41260, 41322, 41379, 41438, 41498, 41552, 41614, 41677, 41738, 41797, 41860, 41918, 41975, 42032, 42091, 42150, 42209, 42267, 42329, 42387, 42448, 42509, 42569, 42630, 42690, 42751, 42814, 42874, 42934, 42995, 43059, 43119, 43182, 43245, 43304, 43366, 43430, 43486, 43544, 43602, 43661, 43718, 43777, 43836, 43895, 43953, 44014, 44073, 44132, 44190, 44249, 44312, 44369, 44431, 44489, 44548, 44609, 44674, 44735, 44797, 44858, 44919, 44984, 45045, 45103, 45168, 45228, 45290, 45349, 45412, 45475, 45538, 45598, 45659, 45719, 45784, 45847, 45910, 45971, 46032, 46093, 46157, 46218, 46280, 46344, 46405, 46465, 46526, 46590, 46650, 46714, 46774, 46833, 46893, 46953, 47017, 47077, 47131, 47186, 47245, 47305, 47361, 47420, 47476, 47533, 47588, 47647, 47706, 47765, 47824, 47883, 47942, 48003, 48061, 48121, 48180, 48239, 48298, 48360, 48422, 48478, 48536, 48598, 48663, 48724, 48785, 48844, 48908, 48967, 49026, 49086, 49145, 49204, 49263, 49325, 49383, 49443, 49506, 49570, 49630, 49691, 49751, 49812, 49873, 49933, 49996, 50063, 50127, 50188, 50249, 50309, 50370, 50430, 50490, 50551, 50605, 50658, 50712, 50769, 50827, 50887, 50943, 51003, 51066, 51125, 51183, 51242, 51303, 51361, 51419, 51481, 51539, 51598, 51657, 51715, 51778, 51836, 51894, 51955, 52013, 52074, 52137, 52201, 52265, 52325, 52387, 52451, 52515, 52574, 52641, 52701, 52764, 52824, 52884, 52947, 53006, 53070, 53131, 53192, 53254, 53314, 53376, 53439, 53498, 53556, 53617, 53682, 53745, 53806, 53866, 53925, 53987, 54048, 54108, 54169, 54232, 54297, 54356, 54413, 54468, 54525, 54588, 54646, 54704, 54766, 54829, 54890, 54949, 55012, 55072, 55129, 55187, 55250, 55307, 55365, 55423, 55482, 55540, 55598, 55659, 55716, 55775, 55833, 55890, 55948, 56006, 56071, 56133, 56194, 56254, 56314, 56374, 56435, 56496, 56560, 56621, 56681, 56742, 56800, 56863, 56926, 56985, 57043, 57101, 57163, 57223, 57285, 57342, 57403, 57466, 57523, 57581, 57641, 57698, 57759, 57820, 57879, 57937, 57998, 58063, 58126, 58183, 58244, 58305, 58365, 58428, 58489, 58549, 58610, 58672, 58733, 58793, 58853, 58918, 58982, 59044, 59104, 59164, 59225, 59286, 59347, 59404, 59460, 59522, 59581, 59637, 59698, 59760, 59823, 59883, 59944, 60007, 60068, 60127, 60187, 60249, 60310, 60372}; //}}} char *file_name = "../data/many/2.1.bed.gz"; struct input_file *i = input_file_init(file_name); int chrm_len = 10; char *chrm = (char *)malloc(chrm_len*sizeof(char)); uint32_t start, end; long offset; kstring_t line = {0, 0, NULL}; struct offset_index *offset_idx = offset_index_init(100, "tmp.test_offset_index_add"); uint32_t intrv_id; TEST_ASSERT_EQUAL(on_disk, offset_idx->type); while (i->input_file_get_next_interval(i, &chrm, &chrm_len, &start, &end, &offset, &line) >= 0) { intrv_id = offset_index_add(offset_idx, offset, &line, 1); } fprintf(stderr, "\n"); TEST_ASSERT_EQUAL(1000, offset_idx->index->num); uint32_t j; for (j = 0; j < 1000; ++j) TEST_ASSERT_EQUAL(A_offsets[j], OFFSET_INDEX_PAIR(offset_idx, j)->offset); offset_index_store(offset_idx); offset_index_destroy(&offset_idx); if (line.s != NULL) free(line.s); input_file_destroy(&i); free(chrm); offset_idx = offset_index_load("tmp.test_offset_index_add"); TEST_ASSERT_EQUAL(on_disk, offset_idx->type); for (j = 0; j < 1000; ++j) TEST_ASSERT_EQUAL(A_offsets[j], OFFSET_INDEX_PAIR(offset_idx, j)->offset); offset_index_destroy(&offset_idx); } //}}} //{{{ void test_offset_index_add_data(void) struct offset_data_append_data_test_struct { uint32_t data; }; void offset_data_append_data_test_func(uint8_t *dest, kstring_t *line) { int n; int *fields = ksplit(line, '\t', &n); struct offset_data_append_data_test_struct a; a.data = atoi(line->s + fields[4]); memcpy(dest, &a, sizeof(struct offset_data_append_data_test_struct)); free(fields); } void test_offset_index_add_data(void) { //{{{ uint32_t A_offsets[1000] = uint32_t A_offsets[1000] = {0, 61, 118, 173, 230, 292, 350, 412, 476, 534, 599, 661, 726, 784, 841, 899, 964, 1026, 1085, 1145, 1204, 1267, 1330, 1388, 1447, 1508, 1566, 1627, 1686, 1747, 1810, 1873, 1935, 1992, 2050, 2108, 2167, 2226, 2285, 2344, 2401, 2460, 2519, 2578, 2636, 2702, 2766, 2826, 2886, 2947, 3009, 3069, 3128, 3188, 3248, 3312, 3375, 3441, 3499, 3559, 3622, 3683, 3746, 3804, 3863, 3922, 3983, 4043, 4104, 4164, 4225, 4285, 4352, 4413, 4480, 4544, 4607, 4668, 4729, 4792, 4853, 4917, 4978, 5037, 5101, 5161, 5218, 5285, 5346, 5409, 5465, 5526, 5583, 5645, 5706, 5767, 5827, 5887, 5950, 6010, 6069, 6133, 6193, 6254, 6316, 6375, 6435, 6494, 6557, 6616, 6676, 6736, 6796, 6855, 6915, 6975, 7033, 7092, 7158, 7218, 7277, 7337, 7397, 7455, 7518, 7577, 7637, 7701, 7761, 7822, 7885, 7951, 8016, 8078, 8140, 8202, 8264, 8326, 8388, 8453, 8513, 8575, 8636, 8698, 8752, 8810, 8868, 8926, 8985, 9043, 9103, 9162, 9222, 9282, 9341, 9401, 9461, 9524, 9583, 9641, 9700, 9762, 9822, 9882, 9945, 10008, 10065, 10128, 10188, 10248, 10308, 10370, 10427, 10487, 10547, 10606, 10665, 10726, 10788, 10853, 10914, 10976, 11039, 11104, 11168, 11229, 11291, 11355, 11413, 11470, 11525, 11584, 11641, 11698, 11755, 11815, 11877, 11936, 11999, 12058, 12120, 12184, 12244, 12304, 12364, 12427, 12491, 12549, 12610, 12674, 12738, 12803, 12869, 12929, 12990, 13049, 13111, 13171, 13233, 13296, 13356, 13416, 13480, 13539, 13599, 13663, 13725, 13787, 13851, 13913, 13978, 14044, 14105, 14166, 14226, 14288, 14351, 14411, 14471, 14530, 14589, 14651, 14715, 14773, 14832, 14893, 14957, 15016, 15075, 15135, 15194, 15253, 15313, 15373, 15432, 15491, 15550, 15610, 15670, 15731, 15790, 15848, 15910, 15970, 16033, 16092, 16156, 16216, 16276, 16335, 16392, 16452, 16511, 16569, 16628, 16686, 16746, 16804, 16870, 16932, 16993, 17055, 17116, 17176, 17235, 17297, 17357, 17415, 17474, 17537, 17596, 17656, 17717, 17779, 17839, 17899, 17958, 18018, 18079, 18138, 18200, 18259, 18317, 18376, 18439, 18503, 18566, 18625, 18687, 18748, 18808, 18870, 18931, 18991, 19054, 19115, 19175, 19234, 19296, 19358, 19417, 19475, 19536, 19596, 19658, 19716, 19776, 19837, 19899, 19958, 20016, 20073, 20137, 20203, 20262, 20321, 20382, 20441, 20504, 20564, 20629, 20688, 20747, 20806, 20865, 20923, 20982, 21041, 21103, 21164, 21222, 21285, 21341, 21398, 21457, 21516, 21575, 21634, 21694, 21757, 21822, 21881, 21941, 22000, 22059, 22123, 22181, 22239, 22297, 22355, 22411, 22470, 22531, 22595, 22654, 22715, 22778, 22839, 22898, 22956, 23016, 23080, 23140, 23199, 23259, 23319, 23382, 23445, 23504, 23564, 23626, 23693, 23757, 23816, 23876, 23936, 23996, 24055, 24113, 24172, 24232, 24293, 24353, 24415, 24474, 24536, 24594, 24653, 24712, 24776, 24840, 24896, 24956, 25012, 25069, 25128, 25184, 25244, 25303, 25364, 25424, 25487, 25546, 25606, 25664, 25722, 25784, 25843, 25902, 25962, 26021, 26079, 26138, 26200, 26259, 26321, 26382, 26443, 26505, 26563, 26620, 26682, 26738, 26798, 26856, 26915, 26975, 27036, 27098, 27158, 27221, 27283, 27343, 27406, 27466, 27525, 27587, 27646, 27705, 27767, 27828, 27887, 27947, 28006, 28065, 28131, 28191, 28254, 28314, 28372, 28431, 28491, 28551, 28615, 28681, 28741, 28800, 28859, 28919, 28978, 29038, 29104, 29165, 29225, 29287, 29344, 29401, 29458, 29519, 29578, 29636, 29695, 29754, 29812, 29871, 29934, 29996, 30057, 30116, 30174, 30233, 30291, 30352, 30411, 30473, 30531, 30592, 30652, 30716, 30775, 30834, 30896, 30959, 31016, 31074, 31133, 31194, 31254, 31317, 31376, 31436, 31497, 31558, 31618, 31678, 31739, 31802, 31865, 31928, 31988, 32048, 32106, 32167, 32231, 32290, 32355, 32414, 32474, 32534, 32599, 32660, 32721, 32781, 32842, 32905, 32966, 33027, 33090, 33151, 33213, 33278, 33338, 33399, 33460, 33520, 33578, 33639, 33699, 33759, 33819, 33878, 33941, 34001, 34065, 34125, 34185, 34245, 34304, 34362, 34421, 34487, 34546, 34605, 34664, 34724, 34787, 34846, 34905, 34967, 35027, 35089, 35148, 35207, 35267, 35329, 35389, 35451, 35511, 35570, 35630, 35691, 35755, 35814, 35873, 35935, 35998, 36064, 36124, 36183, 36247, 36310, 36369, 36430, 36489, 36551, 36611, 36670, 36730, 36790, 36850, 36914, 36974, 37033, 37093, 37152, 37210, 37269, 37327, 37390, 37455, 37512, 37571, 37631, 37687, 37743, 37806, 37864, 37922, 37985, 38043, 38102, 38164, 38223, 38280, 38341, 38399, 38461, 38522, 38583, 38642, 38700, 38760, 38822, 38882, 38940, 38999, 39064, 39124, 39185, 39248, 39309, 39369, 39434, 39495, 39556, 39616, 39680, 39741, 39802, 39862, 39925, 39990, 40052, 40116, 40177, 40237, 40298, 40359, 40418, 40479, 40540, 40599, 40665, 40726, 40787, 40850, 40914, 40970, 41027, 41085, 41141, 41202, 41260, 41322, 41379, 41438, 41498, 41552, 41614, 41677, 41738, 41797, 41860, 41918, 41975, 42032, 42091, 42150, 42209, 42267, 42329, 42387, 42448, 42509, 42569, 42630, 42690, 42751, 42814, 42874, 42934, 42995, 43059, 43119, 43182, 43245, 43304, 43366, 43430, 43486, 43544, 43602, 43661, 43718, 43777, 43836, 43895, 43953, 44014, 44073, 44132, 44190, 44249, 44312, 44369, 44431, 44489, 44548, 44609, 44674, 44735, 44797, 44858, 44919, 44984, 45045, 45103, 45168, 45228, 45290, 45349, 45412, 45475, 45538, 45598, 45659, 45719, 45784, 45847, 45910, 45971, 46032, 46093, 46157, 46218, 46280, 46344, 46405, 46465, 46526, 46590, 46650, 46714, 46774, 46833, 46893, 46953, 47017, 47077, 47131, 47186, 47245, 47305, 47361, 47420, 47476, 47533, 47588, 47647, 47706, 47765, 47824, 47883, 47942, 48003, 48061, 48121, 48180, 48239, 48298, 48360, 48422, 48478, 48536, 48598, 48663, 48724, 48785, 48844, 48908, 48967, 49026, 49086, 49145, 49204, 49263, 49325, 49383, 49443, 49506, 49570, 49630, 49691, 49751, 49812, 49873, 49933, 49996, 50063, 50127, 50188, 50249, 50309, 50370, 50430, 50490, 50551, 50605, 50658, 50712, 50769, 50827, 50887, 50943, 51003, 51066, 51125, 51183, 51242, 51303, 51361, 51419, 51481, 51539, 51598, 51657, 51715, 51778, 51836, 51894, 51955, 52013, 52074, 52137, 52201, 52265, 52325, 52387, 52451, 52515, 52574, 52641, 52701, 52764, 52824, 52884, 52947, 53006, 53070, 53131, 53192, 53254, 53314, 53376, 53439, 53498, 53556, 53617, 53682, 53745, 53806, 53866, 53925, 53987, 54048, 54108, 54169, 54232, 54297, 54356, 54413, 54468, 54525, 54588, 54646, 54704, 54766, 54829, 54890, 54949, 55012, 55072, 55129, 55187, 55250, 55307, 55365, 55423, 55482, 55540, 55598, 55659, 55716, 55775, 55833, 55890, 55948, 56006, 56071, 56133, 56194, 56254, 56314, 56374, 56435, 56496, 56560, 56621, 56681, 56742, 56800, 56863, 56926, 56985, 57043, 57101, 57163, 57223, 57285, 57342, 57403, 57466, 57523, 57581, 57641, 57698, 57759, 57820, 57879, 57937, 57998, 58063, 58126, 58183, 58244, 58305, 58365, 58428, 58489, 58549, 58610, 58672, 58733, 58793, 58853, 58918, 58982, 59044, 59104, 59164, 59225, 59286, 59347, 59404, 59460, 59522, 59581, 59637, 59698, 59760, 59823, 59883, 59944, 60007, 60068, 60127, 60187, 60249, 60310, 60372}; //}}} //{{{uint32_t A_data[1000] = uint32_t A_data[1000] = {1000, 453, 421, 506, 1000, 426, 1000, 1000, 531, 1000, 1000, 1000, 490, 397, 497, 1000, 1000, 606, 680, 604, 1000, 1000, 534, 482, 692, 448, 893, 494, 670, 1000, 1000, 1000, 487, 565, 472, 427, 613, 552, 577, 371, 638, 422, 478, 397, 1000, 1000, 459, 429, 603, 630, 429, 426, 443, 380, 752, 768, 1000, 440, 422, 933, 537, 876, 386, 415, 379, 481, 415, 556, 409, 579, 473, 1000, 442, 1000, 1000, 905, 496, 392, 856, 489, 1000, 427, 415, 1000, 382, 408, 1000, 523, 973, 408, 1000, 453, 1000, 1000, 1000, 545, 517, 1000, 402, 370, 1000, 495, 945, 1000, 482, 430, 414, 1000, 465, 581, 499, 375, 468, 501, 538, 378, 443, 1000, 490, 524, 477, 517, 437, 1000, 397, 370, 1000, 416, 473, 993, 1000, 801, 592, 535, 433, 531, 386, 393, 1000, 385, 385, 378, 403, 388, 918, 1000, 956, 795, 408, 488, 378, 464, 418, 595, 502, 459, 919, 596, 385, 448, 931, 617, 497, 772, 754, 385, 1000, 646, 441, 515, 712, 379, 410, 597, 371, 420, 872, 719, 1000, 410, 410, 973, 1000, 732, 403, 470, 719, 1000, 400, 436, 552, 386, 389, 393, 373, 788, 371, 1000, 397, 896, 1000, 380, 526, 372, 937, 1000, 373, 964, 1000, 1000, 1000, 1000, 419, 689, 373, 888, 406, 1000, 1000, 423, 592, 1000, 423, 523, 995, 383, 473, 795, 472, 654, 1000, 391, 402, 407, 461, 1000, 395, 424, 407, 378, 872, 1000, 378, 479, 503, 1000, 400, 380, 380, 389, 370, 509, 371, 393, 378, 444, 436, 478, 424, 383, 393, 986, 472, 1000, 483, 1000, 380, 373, 516, 371, 481, 380, 407, 430, 378, 580, 373, 1000, 502, 415, 419, 380, 483, 382, 656, 517, 423, 391, 692, 395, 538, 699, 706, 422, 405, 372, 569, 841, 508, 1000, 436, 424, 439, 1000, 1000, 1000, 424, 785, 646, 580, 724, 640, 427, 1000, 1000, 448, 466, 554, 422, 1000, 772, 717, 744, 1000, 578, 499, 914, 694, 380, 402, 393, 1000, 1000, 461, 380, 646, 490, 1000, 495, 1000, 525, 436, 414, 393, 371, 509, 530, 668, 643, 375, 756, 393, 491, 490, 493, 408, 524, 567, 1000, 1000, 556, 511, 452, 465, 1000, 396, 375, 511, 371, 489, 432, 1000, 1000, 400, 708, 1000, 672, 380, 440, 391, 1000, 433, 375, 950, 483, 1000, 1000, 461, 625, 974, 1000, 1000, 430, 575, 433, 545, 415, 380, 470, 580, 642, 460, 896, 403, 754, 564, 392, 430, 1000, 1000, 370, 741, 603, 410, 643, 515, 371, 622, 644, 505, 1000, 375, 437, 380, 400, 706, 487, 525, 389, 393, 378, 389, 978, 386, 1000, 1000, 882, 1000, 547, 400, 1000, 370, 829, 494, 749, 610, 906, 1000, 403, 1000, 744, 423, 1000, 432, 617, 833, 502, 380, 996, 589, 429, 525, 416, 430, 1000, 403, 1000, 397, 381, 749, 432, 539, 1000, 1000, 484, 558, 422, 399, 516, 480, 1000, 684, 594, 677, 424, 432, 443, 864, 509, 371, 547, 501, 428, 580, 1000, 1000, 689, 391, 618, 524, 482, 682, 624, 1000, 436, 742, 499, 1000, 458, 397, 1000, 1000, 406, 375, 407, 661, 592, 662, 436, 378, 465, 508, 429, 473, 380, 882, 623, 1000, 409, 508, 584, 511, 1000, 375, 1000, 373, 501, 381, 1000, 493, 440, 494, 413, 757, 624, 491, 734, 413, 863, 1000, 397, 389, 386, 371, 876, 1000, 819, 460, 422, 407, 1000, 497, 1000, 432, 400, 422, 399, 510, 466, 1000, 436, 573, 381, 376, 1000, 578, 419, 719, 482, 656, 390, 388, 511, 843, 426, 723, 538, 372, 400, 884, 1000, 415, 450, 681, 656, 1000, 497, 425, 1000, 1000, 444, 820, 450, 816, 431, 399, 370, 394, 387, 1000, 625, 385, 524, 422, 385, 387, 403, 1000, 1000, 593, 1000, 1000, 530, 458, 1000, 472, 436, 1000, 441, 456, 1000, 449, 394, 786, 391, 1000, 1000, 706, 383, 375, 517, 1000, 592, 422, 501, 1000, 429, 449, 1000, 386, 591, 1000, 590, 591, 371, 876, 415, 389, 375, 1000, 1000, 795, 1000, 472, 401, 451, 392, 469, 493, 437, 415, 1000, 430, 554, 952, 1000, 442, 620, 634, 440, 1000, 800, 1000, 378, 441, 617, 373, 1000, 1000, 1000, 442, 1000, 530, 436, 499, 503, 597, 523, 444, 1000, 544, 691, 737, 390, 452, 385, 397, 809, 400, 380, 499, 846, 501, 1000, 809, 371, 640, 1000, 377, 415, 383, 524, 371, 400, 479, 389, 508, 985, 410, 486, 380, 423, 1000, 499, 1000, 409, 382, 436, 1000, 382, 660, 592, 420, 1000, 380, 389, 1000, 400, 759, 436, 808, 1000, 1000, 410, 415, 400, 1000, 1000, 703, 482, 646, 400, 938, 475, 651, 1000, 482, 596, 624, 1000, 416, 1000, 424, 373, 371, 483, 809, 444, 415, 390, 1000, 1000, 495, 857, 436, 445, 383, 432, 553, 621, 375, 460, 473, 748, 566, 632, 484, 504, 520, 1000, 1000, 380, 371, 1000, 1000, 1000, 914, 813, 1000, 467, 409, 797, 400, 515, 581, 1000, 524, 400, 821, 1000, 489, 490, 432, 524, 444, 559, 1000, 1000, 1000, 376, 593, 470, 468, 375, 395, 451, 422, 375, 389, 521, 751, 745, 443, 849, 1000, 489, 394, 445, 713, 530, 407, 1000, 503, 519, 402, 382, 1000, 385, 389, 901, 444, 731, 877, 1000, 1000, 525, 636, 1000, 1000, 439, 1000, 591, 754, 422, 489, 846, 378, 1000, 533, 533, 1000, 370, 631, 1000, 382, 378, 422, 1000, 669, 1000, 407, 403, 1000, 524, 372, 504, 994, 1000, 1000, 425, 373, 371, 1000, 432, 393, 1000, 1000, 660, 592, 1000, 769, 493, 400, 1000, 406, 393, 372, 385, 593, 393, 762, 482, 425, 416, 378, 371, 440, 1000, 684, 438, 380, 380, 385, 471, 581, 1000, 552, 424, 386, 459, 1000, 1000, 438, 566, 597, 1000, 482, 1000, 372, 897, 1000, 400, 407, 482, 534, 940, 686, 411, 424, 921, 1000, 1000, 465, 464, 400, 383, 714, 434, 391, 513, 884, 457, 432, 517, 1000, 773, 791, 525, 393, 396, 461, 1000, 429, 371, 1000, 458, 371, 713, 1000, 1000, 763, 436, 668, 609, 437, 443, 543, 616, 670, 694}; //}}} char *file_name = "../data/many/2.1.bed.gz"; struct input_file *i = input_file_init(file_name); int chrm_len = 10; char *chrm = (char *)malloc(chrm_len*sizeof(char)); uint32_t start, end; long offset; kstring_t line = {0, 0, NULL}; offset_data_size = sizeof(struct offset_data_append_data_test_struct); offset_data_append_data = offset_data_append_data_test_func; struct offset_index *offset_idx = offset_index_init(100, "tmp.test_offset_index_add"); TEST_ASSERT_EQUAL(on_disk, offset_idx->type); uint32_t intrv_id; while (i->input_file_get_next_interval(i, &chrm, &chrm_len, &start, &end, &offset, &line) >= 0) { intrv_id = offset_index_add(offset_idx, offset, &line, 1); } TEST_ASSERT_EQUAL(1000, offset_idx->index->num); uint32_t j; for (j = 0; j < 1000; ++j) { TEST_ASSERT_EQUAL(A_offsets[j], OFFSET_INDEX_PAIR(offset_idx, j)->offset); struct offset_data_append_data_test_struct *tmp; tmp = (struct offset_data_append_data_test_struct *) OFFSET_INDEX_DATA(offset_idx, j); TEST_ASSERT_EQUAL(A_data[j], tmp->data); } if (line.s != NULL) free(line.s); input_file_destroy(&i); offset_index_destroy(&offset_idx); free(chrm); } //}}} //{{{ void test_offset_index_add_larger_data(void) struct offset_data_append_data_test_struct_larger { uint32_t uint; float flt; char concat[20]; }; void offset_data_append_data_test_func_larger(uint8_t *dest, kstring_t *line) { int n; int *fields = ksplit(line, '\t', &n); struct offset_data_append_data_test_struct_larger a; a.uint = atoi(line->s + fields[4]); a.flt = atof(line->s + fields[6]); memset(&a.concat, 0, 20); int ret = sprintf(a.concat, "%u %.6f", a.uint, a.flt); /* fprintf(stderr, "offset_data_append_data_test_func_larger: dest:%p line:%s uint:%u flt:%f\n", dest, line->s, a.uint, a.flt); */ memcpy(dest, &a, sizeof(struct offset_data_append_data_test_struct_larger)); free(fields); } void test_offset_index_add_data_larger(void) { //{{{ uint32_t A_offsets[1000] = uint32_t A_offsets[1000] = {0, 61, 118, 173, 230, 292, 350, 412, 476, 534, 599, 661, 726, 784, 841, 899, 964, 1026, 1085, 1145, 1204, 1267, 1330, 1388, 1447, 1508, 1566, 1627, 1686, 1747, 1810, 1873, 1935, 1992, 2050, 2108, 2167, 2226, 2285, 2344, 2401, 2460, 2519, 2578, 2636, 2702, 2766, 2826, 2886, 2947, 3009, 3069, 3128, 3188, 3248, 3312, 3375, 3441, 3499, 3559, 3622, 3683, 3746, 3804, 3863, 3922, 3983, 4043, 4104, 4164, 4225, 4285, 4352, 4413, 4480, 4544, 4607, 4668, 4729, 4792, 4853, 4917, 4978, 5037, 5101, 5161, 5218, 5285, 5346, 5409, 5465, 5526, 5583, 5645, 5706, 5767, 5827, 5887, 5950, 6010, 6069, 6133, 6193, 6254, 6316, 6375, 6435, 6494, 6557, 6616, 6676, 6736, 6796, 6855, 6915, 6975, 7033, 7092, 7158, 7218, 7277, 7337, 7397, 7455, 7518, 7577, 7637, 7701, 7761, 7822, 7885, 7951, 8016, 8078, 8140, 8202, 8264, 8326, 8388, 8453, 8513, 8575, 8636, 8698, 8752, 8810, 8868, 8926, 8985, 9043, 9103, 9162, 9222, 9282, 9341, 9401, 9461, 9524, 9583, 9641, 9700, 9762, 9822, 9882, 9945, 10008, 10065, 10128, 10188, 10248, 10308, 10370, 10427, 10487, 10547, 10606, 10665, 10726, 10788, 10853, 10914, 10976, 11039, 11104, 11168, 11229, 11291, 11355, 11413, 11470, 11525, 11584, 11641, 11698, 11755, 11815, 11877, 11936, 11999, 12058, 12120, 12184, 12244, 12304, 12364, 12427, 12491, 12549, 12610, 12674, 12738, 12803, 12869, 12929, 12990, 13049, 13111, 13171, 13233, 13296, 13356, 13416, 13480, 13539, 13599, 13663, 13725, 13787, 13851, 13913, 13978, 14044, 14105, 14166, 14226, 14288, 14351, 14411, 14471, 14530, 14589, 14651, 14715, 14773, 14832, 14893, 14957, 15016, 15075, 15135, 15194, 15253, 15313, 15373, 15432, 15491, 15550, 15610, 15670, 15731, 15790, 15848, 15910, 15970, 16033, 16092, 16156, 16216, 16276, 16335, 16392, 16452, 16511, 16569, 16628, 16686, 16746, 16804, 16870, 16932, 16993, 17055, 17116, 17176, 17235, 17297, 17357, 17415, 17474, 17537, 17596, 17656, 17717, 17779, 17839, 17899, 17958, 18018, 18079, 18138, 18200, 18259, 18317, 18376, 18439, 18503, 18566, 18625, 18687, 18748, 18808, 18870, 18931, 18991, 19054, 19115, 19175, 19234, 19296, 19358, 19417, 19475, 19536, 19596, 19658, 19716, 19776, 19837, 19899, 19958, 20016, 20073, 20137, 20203, 20262, 20321, 20382, 20441, 20504, 20564, 20629, 20688, 20747, 20806, 20865, 20923, 20982, 21041, 21103, 21164, 21222, 21285, 21341, 21398, 21457, 21516, 21575, 21634, 21694, 21757, 21822, 21881, 21941, 22000, 22059, 22123, 22181, 22239, 22297, 22355, 22411, 22470, 22531, 22595, 22654, 22715, 22778, 22839, 22898, 22956, 23016, 23080, 23140, 23199, 23259, 23319, 23382, 23445, 23504, 23564, 23626, 23693, 23757, 23816, 23876, 23936, 23996, 24055, 24113, 24172, 24232, 24293, 24353, 24415, 24474, 24536, 24594, 24653, 24712, 24776, 24840, 24896, 24956, 25012, 25069, 25128, 25184, 25244, 25303, 25364, 25424, 25487, 25546, 25606, 25664, 25722, 25784, 25843, 25902, 25962, 26021, 26079, 26138, 26200, 26259, 26321, 26382, 26443, 26505, 26563, 26620, 26682, 26738, 26798, 26856, 26915, 26975, 27036, 27098, 27158, 27221, 27283, 27343, 27406, 27466, 27525, 27587, 27646, 27705, 27767, 27828, 27887, 27947, 28006, 28065, 28131, 28191, 28254, 28314, 28372, 28431, 28491, 28551, 28615, 28681, 28741, 28800, 28859, 28919, 28978, 29038, 29104, 29165, 29225, 29287, 29344, 29401, 29458, 29519, 29578, 29636, 29695, 29754, 29812, 29871, 29934, 29996, 30057, 30116, 30174, 30233, 30291, 30352, 30411, 30473, 30531, 30592, 30652, 30716, 30775, 30834, 30896, 30959, 31016, 31074, 31133, 31194, 31254, 31317, 31376, 31436, 31497, 31558, 31618, 31678, 31739, 31802, 31865, 31928, 31988, 32048, 32106, 32167, 32231, 32290, 32355, 32414, 32474, 32534, 32599, 32660, 32721, 32781, 32842, 32905, 32966, 33027, 33090, 33151, 33213, 33278, 33338, 33399, 33460, 33520, 33578, 33639, 33699, 33759, 33819, 33878, 33941, 34001, 34065, 34125, 34185, 34245, 34304, 34362, 34421, 34487, 34546, 34605, 34664, 34724, 34787, 34846, 34905, 34967, 35027, 35089, 35148, 35207, 35267, 35329, 35389, 35451, 35511, 35570, 35630, 35691, 35755, 35814, 35873, 35935, 35998, 36064, 36124, 36183, 36247, 36310, 36369, 36430, 36489, 36551, 36611, 36670, 36730, 36790, 36850, 36914, 36974, 37033, 37093, 37152, 37210, 37269, 37327, 37390, 37455, 37512, 37571, 37631, 37687, 37743, 37806, 37864, 37922, 37985, 38043, 38102, 38164, 38223, 38280, 38341, 38399, 38461, 38522, 38583, 38642, 38700, 38760, 38822, 38882, 38940, 38999, 39064, 39124, 39185, 39248, 39309, 39369, 39434, 39495, 39556, 39616, 39680, 39741, 39802, 39862, 39925, 39990, 40052, 40116, 40177, 40237, 40298, 40359, 40418, 40479, 40540, 40599, 40665, 40726, 40787, 40850, 40914, 40970, 41027, 41085, 41141, 41202, 41260, 41322, 41379, 41438, 41498, 41552, 41614, 41677, 41738, 41797, 41860, 41918, 41975, 42032, 42091, 42150, 42209, 42267, 42329, 42387, 42448, 42509, 42569, 42630, 42690, 42751, 42814, 42874, 42934, 42995, 43059, 43119, 43182, 43245, 43304, 43366, 43430, 43486, 43544, 43602, 43661, 43718, 43777, 43836, 43895, 43953, 44014, 44073, 44132, 44190, 44249, 44312, 44369, 44431, 44489, 44548, 44609, 44674, 44735, 44797, 44858, 44919, 44984, 45045, 45103, 45168, 45228, 45290, 45349, 45412, 45475, 45538, 45598, 45659, 45719, 45784, 45847, 45910, 45971, 46032, 46093, 46157, 46218, 46280, 46344, 46405, 46465, 46526, 46590, 46650, 46714, 46774, 46833, 46893, 46953, 47017, 47077, 47131, 47186, 47245, 47305, 47361, 47420, 47476, 47533, 47588, 47647, 47706, 47765, 47824, 47883, 47942, 48003, 48061, 48121, 48180, 48239, 48298, 48360, 48422, 48478, 48536, 48598, 48663, 48724, 48785, 48844, 48908, 48967, 49026, 49086, 49145, 49204, 49263, 49325, 49383, 49443, 49506, 49570, 49630, 49691, 49751, 49812, 49873, 49933, 49996, 50063, 50127, 50188, 50249, 50309, 50370, 50430, 50490, 50551, 50605, 50658, 50712, 50769, 50827, 50887, 50943, 51003, 51066, 51125, 51183, 51242, 51303, 51361, 51419, 51481, 51539, 51598, 51657, 51715, 51778, 51836, 51894, 51955, 52013, 52074, 52137, 52201, 52265, 52325, 52387, 52451, 52515, 52574, 52641, 52701, 52764, 52824, 52884, 52947, 53006, 53070, 53131, 53192, 53254, 53314, 53376, 53439, 53498, 53556, 53617, 53682, 53745, 53806, 53866, 53925, 53987, 54048, 54108, 54169, 54232, 54297, 54356, 54413, 54468, 54525, 54588, 54646, 54704, 54766, 54829, 54890, 54949, 55012, 55072, 55129, 55187, 55250, 55307, 55365, 55423, 55482, 55540, 55598, 55659, 55716, 55775, 55833, 55890, 55948, 56006, 56071, 56133, 56194, 56254, 56314, 56374, 56435, 56496, 56560, 56621, 56681, 56742, 56800, 56863, 56926, 56985, 57043, 57101, 57163, 57223, 57285, 57342, 57403, 57466, 57523, 57581, 57641, 57698, 57759, 57820, 57879, 57937, 57998, 58063, 58126, 58183, 58244, 58305, 58365, 58428, 58489, 58549, 58610, 58672, 58733, 58793, 58853, 58918, 58982, 59044, 59104, 59164, 59225, 59286, 59347, 59404, 59460, 59522, 59581, 59637, 59698, 59760, 59823, 59883, 59944, 60007, 60068, 60127, 60187, 60249, 60310, 60372}; //}}} //{{{uint32_t A_data[1000] = uint32_t A_data[1000] = {1000, 453, 421, 506, 1000, 426, 1000, 1000, 531, 1000, 1000, 1000, 490, 397, 497, 1000, 1000, 606, 680, 604, 1000, 1000, 534, 482, 692, 448, 893, 494, 670, 1000, 1000, 1000, 487, 565, 472, 427, 613, 552, 577, 371, 638, 422, 478, 397, 1000, 1000, 459, 429, 603, 630, 429, 426, 443, 380, 752, 768, 1000, 440, 422, 933, 537, 876, 386, 415, 379, 481, 415, 556, 409, 579, 473, 1000, 442, 1000, 1000, 905, 496, 392, 856, 489, 1000, 427, 415, 1000, 382, 408, 1000, 523, 973, 408, 1000, 453, 1000, 1000, 1000, 545, 517, 1000, 402, 370, 1000, 495, 945, 1000, 482, 430, 414, 1000, 465, 581, 499, 375, 468, 501, 538, 378, 443, 1000, 490, 524, 477, 517, 437, 1000, 397, 370, 1000, 416, 473, 993, 1000, 801, 592, 535, 433, 531, 386, 393, 1000, 385, 385, 378, 403, 388, 918, 1000, 956, 795, 408, 488, 378, 464, 418, 595, 502, 459, 919, 596, 385, 448, 931, 617, 497, 772, 754, 385, 1000, 646, 441, 515, 712, 379, 410, 597, 371, 420, 872, 719, 1000, 410, 410, 973, 1000, 732, 403, 470, 719, 1000, 400, 436, 552, 386, 389, 393, 373, 788, 371, 1000, 397, 896, 1000, 380, 526, 372, 937, 1000, 373, 964, 1000, 1000, 1000, 1000, 419, 689, 373, 888, 406, 1000, 1000, 423, 592, 1000, 423, 523, 995, 383, 473, 795, 472, 654, 1000, 391, 402, 407, 461, 1000, 395, 424, 407, 378, 872, 1000, 378, 479, 503, 1000, 400, 380, 380, 389, 370, 509, 371, 393, 378, 444, 436, 478, 424, 383, 393, 986, 472, 1000, 483, 1000, 380, 373, 516, 371, 481, 380, 407, 430, 378, 580, 373, 1000, 502, 415, 419, 380, 483, 382, 656, 517, 423, 391, 692, 395, 538, 699, 706, 422, 405, 372, 569, 841, 508, 1000, 436, 424, 439, 1000, 1000, 1000, 424, 785, 646, 580, 724, 640, 427, 1000, 1000, 448, 466, 554, 422, 1000, 772, 717, 744, 1000, 578, 499, 914, 694, 380, 402, 393, 1000, 1000, 461, 380, 646, 490, 1000, 495, 1000, 525, 436, 414, 393, 371, 509, 530, 668, 643, 375, 756, 393, 491, 490, 493, 408, 524, 567, 1000, 1000, 556, 511, 452, 465, 1000, 396, 375, 511, 371, 489, 432, 1000, 1000, 400, 708, 1000, 672, 380, 440, 391, 1000, 433, 375, 950, 483, 1000, 1000, 461, 625, 974, 1000, 1000, 430, 575, 433, 545, 415, 380, 470, 580, 642, 460, 896, 403, 754, 564, 392, 430, 1000, 1000, 370, 741, 603, 410, 643, 515, 371, 622, 644, 505, 1000, 375, 437, 380, 400, 706, 487, 525, 389, 393, 378, 389, 978, 386, 1000, 1000, 882, 1000, 547, 400, 1000, 370, 829, 494, 749, 610, 906, 1000, 403, 1000, 744, 423, 1000, 432, 617, 833, 502, 380, 996, 589, 429, 525, 416, 430, 1000, 403, 1000, 397, 381, 749, 432, 539, 1000, 1000, 484, 558, 422, 399, 516, 480, 1000, 684, 594, 677, 424, 432, 443, 864, 509, 371, 547, 501, 428, 580, 1000, 1000, 689, 391, 618, 524, 482, 682, 624, 1000, 436, 742, 499, 1000, 458, 397, 1000, 1000, 406, 375, 407, 661, 592, 662, 436, 378, 465, 508, 429, 473, 380, 882, 623, 1000, 409, 508, 584, 511, 1000, 375, 1000, 373, 501, 381, 1000, 493, 440, 494, 413, 757, 624, 491, 734, 413, 863, 1000, 397, 389, 386, 371, 876, 1000, 819, 460, 422, 407, 1000, 497, 1000, 432, 400, 422, 399, 510, 466, 1000, 436, 573, 381, 376, 1000, 578, 419, 719, 482, 656, 390, 388, 511, 843, 426, 723, 538, 372, 400, 884, 1000, 415, 450, 681, 656, 1000, 497, 425, 1000, 1000, 444, 820, 450, 816, 431, 399, 370, 394, 387, 1000, 625, 385, 524, 422, 385, 387, 403, 1000, 1000, 593, 1000, 1000, 530, 458, 1000, 472, 436, 1000, 441, 456, 1000, 449, 394, 786, 391, 1000, 1000, 706, 383, 375, 517, 1000, 592, 422, 501, 1000, 429, 449, 1000, 386, 591, 1000, 590, 591, 371, 876, 415, 389, 375, 1000, 1000, 795, 1000, 472, 401, 451, 392, 469, 493, 437, 415, 1000, 430, 554, 952, 1000, 442, 620, 634, 440, 1000, 800, 1000, 378, 441, 617, 373, 1000, 1000, 1000, 442, 1000, 530, 436, 499, 503, 597, 523, 444, 1000, 544, 691, 737, 390, 452, 385, 397, 809, 400, 380, 499, 846, 501, 1000, 809, 371, 640, 1000, 377, 415, 383, 524, 371, 400, 479, 389, 508, 985, 410, 486, 380, 423, 1000, 499, 1000, 409, 382, 436, 1000, 382, 660, 592, 420, 1000, 380, 389, 1000, 400, 759, 436, 808, 1000, 1000, 410, 415, 400, 1000, 1000, 703, 482, 646, 400, 938, 475, 651, 1000, 482, 596, 624, 1000, 416, 1000, 424, 373, 371, 483, 809, 444, 415, 390, 1000, 1000, 495, 857, 436, 445, 383, 432, 553, 621, 375, 460, 473, 748, 566, 632, 484, 504, 520, 1000, 1000, 380, 371, 1000, 1000, 1000, 914, 813, 1000, 467, 409, 797, 400, 515, 581, 1000, 524, 400, 821, 1000, 489, 490, 432, 524, 444, 559, 1000, 1000, 1000, 376, 593, 470, 468, 375, 395, 451, 422, 375, 389, 521, 751, 745, 443, 849, 1000, 489, 394, 445, 713, 530, 407, 1000, 503, 519, 402, 382, 1000, 385, 389, 901, 444, 731, 877, 1000, 1000, 525, 636, 1000, 1000, 439, 1000, 591, 754, 422, 489, 846, 378, 1000, 533, 533, 1000, 370, 631, 1000, 382, 378, 422, 1000, 669, 1000, 407, 403, 1000, 524, 372, 504, 994, 1000, 1000, 425, 373, 371, 1000, 432, 393, 1000, 1000, 660, 592, 1000, 769, 493, 400, 1000, 406, 393, 372, 385, 593, 393, 762, 482, 425, 416, 378, 371, 440, 1000, 684, 438, 380, 380, 385, 471, 581, 1000, 552, 424, 386, 459, 1000, 1000, 438, 566, 597, 1000, 482, 1000, 372, 897, 1000, 400, 407, 482, 534, 940, 686, 411, 424, 921, 1000, 1000, 465, 464, 400, 383, 714, 434, 391, 513, 884, 457, 432, 517, 1000, 773, 791, 525, 393, 396, 461, 1000, 429, 371, 1000, 458, 371, 713, 1000, 1000, 763, 436, 668, 609, 437, 443, 543, 616, 670, 694}; //}}} //{{{float A_flt[1000] = { float A_flt[1000] = { 12.12021, 3.88225, 3.4088, 14.7654, 3.48997, 1.87484, 6.77027, 11.9687, 3.91381, 14.51326, 15.4361, 70.82748, 10.98394, 3.4088, 7.00699, 14.99353, 6.74875, 3.70339, 5.9086, 9.46891, 11.11019, 12.83984, 2.98867, 10.60518, 3.52535, 9.09015, 6.88074, 5.51758, 6.57388, 9.72435, 19.31658, 8.55989, 4.3557, 3.29518, 3.34568, 14.73803, 3.03005, 3.24808, 3.78756, 5.30259, 7.87982, 5.11321, 2.65129, 703.58101, 16.76629, 9.75298, 6.42889, 5.30259, 4.22043, 10.03705, 4.74661, 3.18155, 4.29257, 2.21843, 18.93783, 2.25607, 221.42388, 8.7114, 5.11321, 5.26471, 7.95388, 8.08975, 7.6656, 3.31412, 3.03005, 2.86171, 7.21588, 6.18635, 3.21943, 3.32893, 9.87197, 15.46589, 3.03005, 12.27171, 17.15226, 7.70302, 2.27253, 2.46191, 4.22459, 3.93906, 5.11321, 3.50349, 5.51496, 18.43282, 2.33566, 7.19637, 19.94784, 4.31782, 3.47468, 8.91237, 55.35055, 8.03434, 24.23541, 7.40464, 5.32535, 4.15464, 35.09704, 7.00258, 4.06529, 2.34536, 23.12527, 3.14278, 9.09766, 7.56379, 3.40077, 7.28391, 5.62886, 9.42185, 5.47251, 4.92526, 3.02764, 2.27835, 3.6744, 3.57667, 3.47113, 7.03608, 5.59169, 17.01169, 3.61855, 8.00551, 3.48453, 5.54992, 4.10438, 6.30188, 45.08121, 2.34536, 34.71985, 9.38144, 12.66495, 11.96134, 31.76898, 11.72681, 7.97423, 6.87972, 3.56495, 5.62886, 4.69072, 4.92526, 6.09794, 7.27949, 2.81443, 7.03608, 3.09587, 4.29351, 7.28596, 9.12913, 14.21216, 7.02574, 4.87899, 30.27434, 5.85479, 2.81897, 2.62071, 3.51287, 5.46447, 2.43949, 11.94931, 5.07415, 6.2451, 2.68886, 5.07415, 4.34927, 15.91178, 13.46601, 13.07569, 6.2451, 12.33409, 4.57231, 2.73223, 4.87899, 3.51287, 3.12255, 3.77308, 3.95198, 5.46447, 2.17928, 9.1725, 8.49777, 9.98567, 3.77308, 3.77308, 4.7739, 5.04813, 9.10745, 3.22013, 7.32016, 8.56192, 278.95909, 4.47425, 4.47425, 14.64303, 4.0675, 74.15807, 4.27088, 3.66075, 9.23069, 5.69451, 6.72335, 3.66075, 3.84153, 26.57438, 25.86841, 2.63032, 2.64388, 12.60927, 25.57446, 2.03375, 7.79605, 16.21919, 15.89002, 19.9522, 28.35634, 3.45738, 4.37627, 3.66075, 7.18593, 711.99196, 8.13501, 7.10458, 4.20309, 5.89788, 11.72182, 2.59303, 5.28467, 4.76479, 2.32429, 2.93764, 5.38944, 4.27088, 10.77889, 10.98227, 3.52517, 2.55671, 3.254, 20.84931, 20.3708, 3.18293, 3.18293, 4.8805, 8.27563, 7.35612, 24.57228, 8.27563, 17.58992, 10.50369, 10.82198, 4.6683, 4.03172, 2.63729, 3.81952, 7.63905, 5.38724, 1.66492, 4.45611, 8.27563, 5.94148, 12.73175, 9.54881, 120.4028, 2.84145, 6.90067, 4.38903, 5.14167, 8.64033, 6.69771, 6.37121, 2.36787, 1.76866, 7.50955, 5.6829, 6.73498, 3.85625, 2.60949, 6.33298, 6.08882, 7.03598, 3.65329, 16.10157, 4.22158, 20.45145, 3.45033, 3.85625, 6.81006, 2.65302, 7.06046, 6.27596, 4.4217, 3.70852, 11.79783, 2.50631, 2.46046, 12.4093, 8.80896, 5.72578, 2.46046, 2.78139, 5.88372, 6.4186, 7.70232, 6.2211, 4.70697, 8.98604, 2.11436, 6.97488, 13.93754, 9.41395, 28.7183, 5.99069, 4.27906, 7.41705, 6.76093, 3.97953, 2.37293, 6.10739, 6.4186, 8.49451, 1.9652, 3.79767, 2.43906, 8.59356, 13.44763, 14.87347, 9.17197, 14.74953, 6.69306, 2.89842, 8.59356, 7.23842, 4.70993, 4.29678, 8.4283, 12.27062, 14.30332, 7.50125, 2.25856, 4.36288, 3.8246, 6.66552, 4.21415, 132.01495, 16.36082, 5.12308, 5.94939, 5.20571, 6.94095, 6.02564, 4.6273, 9.91565, 7.68463, 3.09864, 11.56826, 8.4283, 8.4283, 14.37769, 3.59442, 7.65796, 4.17873, 5.65192, 7.84238, 10.78327, 3.71836, 6.77569, 7.18884, 5.78413, 10.23115, 2.77158, 2.45482, 3.89341, 1.40558, 6.64682, 10.11018, 8.14505, 24.74626, 8.89158, 3.40508, 7.80002, 8.41589, 2.87056, 9.10662, 3.06853, 14.19728, 23.05476, 2.77158, 5.50356, 1.93874, 8.97464, 4.89715, 2.34735, 4.20686, 8.78987, 32.86303, 15.93659, 3.2467, 3.01523, 3.76143, 2.69239, 5.14722, 2.53401, 14.9326, 4.55331, 5.62235, 3.36549, 5.22641, 3.2665, 6.73098, 6.599, 2.57361, 3.03554, 12.67008, 13.46196, 2.33794, 6.00072, 4.25505, 2.56394, 3.19129, 4.546, 2.12752, 5.81888, 12.42236, 2.58404, 7.85549, 3.6368, 4.50054, 2.63668, 5.4552, 7.85549, 5.4552, 12.73173, 17.79964, 5.18244, 7.09176, 3.16401, 17.89681, 7.63728, 23.66953, 7.53271, 13.70596, 15.50422, 6.09442, 6.58198, 13.31022, 2.92532, 4.91617, 8.07562, 6.985, 7.06953, 6.26855, 10.6043, 3.01674, 5.53584, 9.01975, 2.66413, 7.77039, 3.14472, 7.7539, 8.19699, 3.94918, 4.17865, 4.87554, 20.61221, 5.11931, 3.83948, 7.31331, 7.93728, 17.58677, 2.77905, 12.70687, 2.40294, 3.83948, 5.22379, 3.14472, 3.96137, 12.43263, 47.90219, 2.74249, 8.9588, 4.93648, 1.98068, 5.60687, 4.11373, 27.75734, 5.18026, 3.57539, 9.53361, 3.88196, 2.63503, 2.72913, 12.16264, 5.29359, 3.29378, 5.62242, 4.51719, 2.95768, 3.59322, 27.57372, 6.74442, 6.03861, 2.91735, 7.1355, 8.94028, 3.41142, 4.75769, 2.91735, 9.81469, 4.86226, 5.17595, 14.11624, 34.34951, 2.62718, 941.31799, 4.42308, 10.56239, 6.58757, 2.43113, 1.42451, 4.10654, 10.82245, 3.92117, 6.3523, 7.05812, 5.48964, 4.73982, 6.11703, 6.65148, 18.89433, 356.30091, 293.75971, 10.60102, 4.23487, 4.6113, 7.8496, 6.43073, 10.19506, 2.94088, 23.91918, 3.24673, 3.58787, 4.00325, 10.19506, 2.99435, 3.67022, 5.05831, 2.70561, 5.28051, 4.33943, 2.86245, 5.12367, 2.70561, 31.8797, 14.78844, 92.30747, 610.58464, 4.70541, 3.29378, 8.28664, 6.62077, 4.44232, 3.75888, 6.87706, 5.86581, 6.50748, 3.75888, 16.42786, 2.32367, 2.08447, 2.93876, 2.90459, 3.89557, 5.63833, 14.66536, 4.9549, 4.51066, 3.58803, 2.00758, 6.05807, 2.26387, 2.4399, 3.31953, 2.78779, 5.70311, 2.5287, 2.73373, 2.38517, 9.71738, 3.09189, 5.55278, 3.97529, 2.35572, 2.25266, 8.6573, 17.99924, 6.52081, 4.85869, 7.15639, 10.11753, 46.59926, 22.22549, 3.86486, 62.05873, 6.65638, 2.88552, 8.07947, 2.93799, 3.23178, 1.65818, 3.55007, 2.09856, 4.22336, 3.30523, 17.87277, 5.21493, 5.87598, 8.53824, 4.95785, 5.87598, 2.57074, 3.0298, 10.7948, 12.87665, 3.38472, 6.62337, 6.41995, 3.47825, 2.89037, 10.73001, 5.19463, 2.69441, 16.18051, 2.7434, 2.38164, 3.65484, 3.44885, 4.50702, 3.03308, 3.03048, 6.58418, 8.08771, 3.28229, 2.23951, 3.91915, 11.88933, 5.29086, 10.25454, 3.40792, 4.70298, 14.73023, 5.40111, 3.44885, 5.91792, 13.13354, 2.76646, 14.78081, 12.97096, 2.64027, 5.48681, 10.09529, 17.67994, 13.15142, 3.91915, 4.74909, 12.23336, 7.05448, 5.74809, 4.96426, 2.82179, 2.65631, 2.35149, 2.98835, 3.18431, 2.46906, 5.0949, 44.87433, 4.18043, 8.62214, 6.27064, 5.13025, 2.80661, 3.43829, 5.56028, 10.8051, 22.24113, 12.43104, 6.72841, 7.14893, 3.60658, 11.96839, 4.28936, 7.14893, 11.98298, 7.6851, 2.26383, 9.27773, 4.95659, 2.62127, 7.90684, 6.35461, 5.41946, 4.21893, 6.67234, 9.87853, 4.60709, 5.16776, 5.48085, 2.10496, 6.91063, 2.3234, 3.05021, 6.01702, 5.07265, 4.52766, 8.34042, 12.54419, 4.57531, 6.08227, 6.01702, 4.7149, 5.10638, 3.61955, 3.25597, 2.95997, 3.10797, 3.10797, 6.21595, 2.08336, 4.77296, 1.62798, 4.52876, 7.61137, 3.19677, 4.88396, 93.19067, 4.23694, 4.27716, 7.57789, 5.18921, 3.99597, 2.34683, 4.58796, 12.93933, 2.51598, 9.19883, 7.54794, 3.03397, 11.91391, 15.83552, 66.766, 4.46463, 4.88396, 6.51195, 4.58796, 8.73091, 6.13001, 8.6826, 2.35318, 166.66526, 7.99194, 10.65592, 7.2654, 6.87075, 10.34996, 4.3413, 2.49748, 14.62498, 3.05864, 8.58393, 7.07782, 3.77397, 4.27346, 6.88194, 6.90661, 8.87993, 9.19961, 9.32393, 3.99597, 3.10797, 3.32997, 15.53988, 6.21595, 22.91597, 1.75206, 6.51226, 4.33224, 2.9566, 4.07902, 4.87641, 2.58703, 3.77788, 2.62809, 2.37258, 2.60984, 2.54596, 3.96007, 2.66459, 2.87447, 5.0098, 4.12986, 2.73759, 2.54596, 11.49791, 6.67973, 3.92785, 2.20943, 3.44937, 6.33906, 10.21515, 7.68677, 5.46142, 5.831, 6.92731, 2.00565, 1.74629, 2.80603, 2.21745, 5.25618, 4.37766, 5.34069, 7.9774, 5.95029, 4.92767, 4.91707, 2.0921, 1.92053, 3.94214, 3.16192, 1.82823, 4.92767, 7.30306, 12.37394, 5.09193, 1.66445, 2.57012, 9.52684, 3.86001, 2.54596, 3.28511, 4.95543, 5.96741, 3.45937, 3.00965, 6.91874, 6.44925, 15.56717, 4.4107, 20.14233, 50.63039, 3.85473, 3.97827, 3.94368, 5.24671, 4.2995, 5.44851, 10.41518, 2.76749, 6.61812, 2.35866, 2.5204, 10.63757, 4.67015, 625.8006, 7.78358, 3.33582, 3.66116, 23.55738, 7.00523, 20.11554, 5.83769, 3.63234, 9.50246, 7.13495, 2.80209, 5.30362, 3.8682, 4.26244, 2.54735, 3.85473, 8.98668, 4.4107, 5.88093, 3.80531, 3.80531, 4.874, 1.72968, 4.61249, 6.14903, 2.5204, 4.4107, 6.72949, 15.48069, 5.25392, 9.643, 2.33507, 3.63234, 5.86931, 3.95665, 4.15124, 3.37288, 4.24559, 13.07643, 8.1283, 3.68784, 3.7932, 5.90054, 32.52693, 3.7932, 7.16494, 7.52157, 10.26848, 4.53077, 6.11127, 16.12113, 5.86378, 3.49215, 4.63614, 11.41474, 2.80978, 2.03709, 2.44451, 1.79123, 3.33661, 7.16494, 9.31376, 3.8803, 3.68784, 3.11885, 2.8449, 5.90054, 9.69375, 15.1404, 5.11781, 3.89857, 92.81556, 4.00394, 3.51222, 2.46859, 4.27488, 5.77878, 5.00768, 8.19586, 4.21467, 6.32201, 11.73622, 13.06006, 3.74345, 4.9373, 7.28455, 8.90334, 11.33152, 9.86449, 4.04697, 5.26106, 11.07399, 7.28455, 5.13173, 11.33152, 2.93405, 8.66052, 6.72705, 2.76543, 218.03325, 30.3523, 23.03095, 11.55227, 8.88089, 3.37247, 2.18536, 2.17524, 7.38572, 2.89069, 3.50737, 3.64227, 3.22139, 3.12195, 8.90334, 3.91207, 43.99865, 17.65578, 5.8392, 11.26905, 4.24932, 2.14489, 14.27604, 12.67801, 6.27863, 3.3808, 9.28379, 5.47368, 6.7616, 6.43962, 8.63983, 19.81925, 11.755, 2.65634, 5.01083, 8.09792, 4.226, 5.1517, 16.39522, 14.79535, 6.7616, 5.65767}; //}}} char *file_name = "../data/many/2.1.bed.gz"; struct input_file *i = input_file_init(file_name); int chrm_len = 10; char *chrm = (char *)malloc(chrm_len*sizeof(char)); uint32_t start, end; long offset; kstring_t line = {0, 0, NULL}; offset_data_size = sizeof(struct offset_data_append_data_test_struct_larger); offset_data_append_data = offset_data_append_data_test_func_larger; struct offset_index *offset_idx = offset_index_init(100, "tmp.test_offset_index_add"); TEST_ASSERT_EQUAL(on_disk, offset_idx->type); uint32_t intrv_id; while (i->input_file_get_next_interval(i, &chrm, &chrm_len, &start, &end, &offset, &line) >= 0) { intrv_id = offset_index_add(offset_idx, offset, &line, 1); } TEST_ASSERT_EQUAL(1000, offset_idx->index->num); uint32_t j; char A_concat[20]; for (j = 0; j < 1000; ++j) { TEST_ASSERT_EQUAL(A_offsets[j], OFFSET_INDEX_PAIR(offset_idx, j)->offset); struct offset_data_append_data_test_struct_larger *tmp; tmp = (struct offset_data_append_data_test_struct_larger *) OFFSET_INDEX_DATA(offset_idx, j); TEST_ASSERT_EQUAL(A_data[j], tmp->uint); TEST_ASSERT_EQUAL(A_flt[j], tmp->flt); int ret = sprintf(A_concat, "%u %.6f", tmp->uint, tmp->flt); TEST_ASSERT_EQUAL(0, strcmp(A_concat, tmp->concat)); } if (line.s != NULL) free(line.s); input_file_destroy(&i); offset_index_destroy(&offset_idx); free(chrm); } //}}} //{{{ void test_offset_index_store_load_data(void) void test_offset_index_store_load_data(void) { //{{{ uint32_t A_offsets[1000] = uint32_t A_offsets[1000] = {0, 61, 118, 173, 230, 292, 350, 412, 476, 534, 599, 661, 726, 784, 841, 899, 964, 1026, 1085, 1145, 1204, 1267, 1330, 1388, 1447, 1508, 1566, 1627, 1686, 1747, 1810, 1873, 1935, 1992, 2050, 2108, 2167, 2226, 2285, 2344, 2401, 2460, 2519, 2578, 2636, 2702, 2766, 2826, 2886, 2947, 3009, 3069, 3128, 3188, 3248, 3312, 3375, 3441, 3499, 3559, 3622, 3683, 3746, 3804, 3863, 3922, 3983, 4043, 4104, 4164, 4225, 4285, 4352, 4413, 4480, 4544, 4607, 4668, 4729, 4792, 4853, 4917, 4978, 5037, 5101, 5161, 5218, 5285, 5346, 5409, 5465, 5526, 5583, 5645, 5706, 5767, 5827, 5887, 5950, 6010, 6069, 6133, 6193, 6254, 6316, 6375, 6435, 6494, 6557, 6616, 6676, 6736, 6796, 6855, 6915, 6975, 7033, 7092, 7158, 7218, 7277, 7337, 7397, 7455, 7518, 7577, 7637, 7701, 7761, 7822, 7885, 7951, 8016, 8078, 8140, 8202, 8264, 8326, 8388, 8453, 8513, 8575, 8636, 8698, 8752, 8810, 8868, 8926, 8985, 9043, 9103, 9162, 9222, 9282, 9341, 9401, 9461, 9524, 9583, 9641, 9700, 9762, 9822, 9882, 9945, 10008, 10065, 10128, 10188, 10248, 10308, 10370, 10427, 10487, 10547, 10606, 10665, 10726, 10788, 10853, 10914, 10976, 11039, 11104, 11168, 11229, 11291, 11355, 11413, 11470, 11525, 11584, 11641, 11698, 11755, 11815, 11877, 11936, 11999, 12058, 12120, 12184, 12244, 12304, 12364, 12427, 12491, 12549, 12610, 12674, 12738, 12803, 12869, 12929, 12990, 13049, 13111, 13171, 13233, 13296, 13356, 13416, 13480, 13539, 13599, 13663, 13725, 13787, 13851, 13913, 13978, 14044, 14105, 14166, 14226, 14288, 14351, 14411, 14471, 14530, 14589, 14651, 14715, 14773, 14832, 14893, 14957, 15016, 15075, 15135, 15194, 15253, 15313, 15373, 15432, 15491, 15550, 15610, 15670, 15731, 15790, 15848, 15910, 15970, 16033, 16092, 16156, 16216, 16276, 16335, 16392, 16452, 16511, 16569, 16628, 16686, 16746, 16804, 16870, 16932, 16993, 17055, 17116, 17176, 17235, 17297, 17357, 17415, 17474, 17537, 17596, 17656, 17717, 17779, 17839, 17899, 17958, 18018, 18079, 18138, 18200, 18259, 18317, 18376, 18439, 18503, 18566, 18625, 18687, 18748, 18808, 18870, 18931, 18991, 19054, 19115, 19175, 19234, 19296, 19358, 19417, 19475, 19536, 19596, 19658, 19716, 19776, 19837, 19899, 19958, 20016, 20073, 20137, 20203, 20262, 20321, 20382, 20441, 20504, 20564, 20629, 20688, 20747, 20806, 20865, 20923, 20982, 21041, 21103, 21164, 21222, 21285, 21341, 21398, 21457, 21516, 21575, 21634, 21694, 21757, 21822, 21881, 21941, 22000, 22059, 22123, 22181, 22239, 22297, 22355, 22411, 22470, 22531, 22595, 22654, 22715, 22778, 22839, 22898, 22956, 23016, 23080, 23140, 23199, 23259, 23319, 23382, 23445, 23504, 23564, 23626, 23693, 23757, 23816, 23876, 23936, 23996, 24055, 24113, 24172, 24232, 24293, 24353, 24415, 24474, 24536, 24594, 24653, 24712, 24776, 24840, 24896, 24956, 25012, 25069, 25128, 25184, 25244, 25303, 25364, 25424, 25487, 25546, 25606, 25664, 25722, 25784, 25843, 25902, 25962, 26021, 26079, 26138, 26200, 26259, 26321, 26382, 26443, 26505, 26563, 26620, 26682, 26738, 26798, 26856, 26915, 26975, 27036, 27098, 27158, 27221, 27283, 27343, 27406, 27466, 27525, 27587, 27646, 27705, 27767, 27828, 27887, 27947, 28006, 28065, 28131, 28191, 28254, 28314, 28372, 28431, 28491, 28551, 28615, 28681, 28741, 28800, 28859, 28919, 28978, 29038, 29104, 29165, 29225, 29287, 29344, 29401, 29458, 29519, 29578, 29636, 29695, 29754, 29812, 29871, 29934, 29996, 30057, 30116, 30174, 30233, 30291, 30352, 30411, 30473, 30531, 30592, 30652, 30716, 30775, 30834, 30896, 30959, 31016, 31074, 31133, 31194, 31254, 31317, 31376, 31436, 31497, 31558, 31618, 31678, 31739, 31802, 31865, 31928, 31988, 32048, 32106, 32167, 32231, 32290, 32355, 32414, 32474, 32534, 32599, 32660, 32721, 32781, 32842, 32905, 32966, 33027, 33090, 33151, 33213, 33278, 33338, 33399, 33460, 33520, 33578, 33639, 33699, 33759, 33819, 33878, 33941, 34001, 34065, 34125, 34185, 34245, 34304, 34362, 34421, 34487, 34546, 34605, 34664, 34724, 34787, 34846, 34905, 34967, 35027, 35089, 35148, 35207, 35267, 35329, 35389, 35451, 35511, 35570, 35630, 35691, 35755, 35814, 35873, 35935, 35998, 36064, 36124, 36183, 36247, 36310, 36369, 36430, 36489, 36551, 36611, 36670, 36730, 36790, 36850, 36914, 36974, 37033, 37093, 37152, 37210, 37269, 37327, 37390, 37455, 37512, 37571, 37631, 37687, 37743, 37806, 37864, 37922, 37985, 38043, 38102, 38164, 38223, 38280, 38341, 38399, 38461, 38522, 38583, 38642, 38700, 38760, 38822, 38882, 38940, 38999, 39064, 39124, 39185, 39248, 39309, 39369, 39434, 39495, 39556, 39616, 39680, 39741, 39802, 39862, 39925, 39990, 40052, 40116, 40177, 40237, 40298, 40359, 40418, 40479, 40540, 40599, 40665, 40726, 40787, 40850, 40914, 40970, 41027, 41085, 41141, 41202, 41260, 41322, 41379, 41438, 41498, 41552, 41614, 41677, 41738, 41797, 41860, 41918, 41975, 42032, 42091, 42150, 42209, 42267, 42329, 42387, 42448, 42509, 42569, 42630, 42690, 42751, 42814, 42874, 42934, 42995, 43059, 43119, 43182, 43245, 43304, 43366, 43430, 43486, 43544, 43602, 43661, 43718, 43777, 43836, 43895, 43953, 44014, 44073, 44132, 44190, 44249, 44312, 44369, 44431, 44489, 44548, 44609, 44674, 44735, 44797, 44858, 44919, 44984, 45045, 45103, 45168, 45228, 45290, 45349, 45412, 45475, 45538, 45598, 45659, 45719, 45784, 45847, 45910, 45971, 46032, 46093, 46157, 46218, 46280, 46344, 46405, 46465, 46526, 46590, 46650, 46714, 46774, 46833, 46893, 46953, 47017, 47077, 47131, 47186, 47245, 47305, 47361, 47420, 47476, 47533, 47588, 47647, 47706, 47765, 47824, 47883, 47942, 48003, 48061, 48121, 48180, 48239, 48298, 48360, 48422, 48478, 48536, 48598, 48663, 48724, 48785, 48844, 48908, 48967, 49026, 49086, 49145, 49204, 49263, 49325, 49383, 49443, 49506, 49570, 49630, 49691, 49751, 49812, 49873, 49933, 49996, 50063, 50127, 50188, 50249, 50309, 50370, 50430, 50490, 50551, 50605, 50658, 50712, 50769, 50827, 50887, 50943, 51003, 51066, 51125, 51183, 51242, 51303, 51361, 51419, 51481, 51539, 51598, 51657, 51715, 51778, 51836, 51894, 51955, 52013, 52074, 52137, 52201, 52265, 52325, 52387, 52451, 52515, 52574, 52641, 52701, 52764, 52824, 52884, 52947, 53006, 53070, 53131, 53192, 53254, 53314, 53376, 53439, 53498, 53556, 53617, 53682, 53745, 53806, 53866, 53925, 53987, 54048, 54108, 54169, 54232, 54297, 54356, 54413, 54468, 54525, 54588, 54646, 54704, 54766, 54829, 54890, 54949, 55012, 55072, 55129, 55187, 55250, 55307, 55365, 55423, 55482, 55540, 55598, 55659, 55716, 55775, 55833, 55890, 55948, 56006, 56071, 56133, 56194, 56254, 56314, 56374, 56435, 56496, 56560, 56621, 56681, 56742, 56800, 56863, 56926, 56985, 57043, 57101, 57163, 57223, 57285, 57342, 57403, 57466, 57523, 57581, 57641, 57698, 57759, 57820, 57879, 57937, 57998, 58063, 58126, 58183, 58244, 58305, 58365, 58428, 58489, 58549, 58610, 58672, 58733, 58793, 58853, 58918, 58982, 59044, 59104, 59164, 59225, 59286, 59347, 59404, 59460, 59522, 59581, 59637, 59698, 59760, 59823, 59883, 59944, 60007, 60068, 60127, 60187, 60249, 60310, 60372}; //}}} //{{{uint32_t A_data[1000] = uint32_t A_data[1000] = {1000, 453, 421, 506, 1000, 426, 1000, 1000, 531, 1000, 1000, 1000, 490, 397, 497, 1000, 1000, 606, 680, 604, 1000, 1000, 534, 482, 692, 448, 893, 494, 670, 1000, 1000, 1000, 487, 565, 472, 427, 613, 552, 577, 371, 638, 422, 478, 397, 1000, 1000, 459, 429, 603, 630, 429, 426, 443, 380, 752, 768, 1000, 440, 422, 933, 537, 876, 386, 415, 379, 481, 415, 556, 409, 579, 473, 1000, 442, 1000, 1000, 905, 496, 392, 856, 489, 1000, 427, 415, 1000, 382, 408, 1000, 523, 973, 408, 1000, 453, 1000, 1000, 1000, 545, 517, 1000, 402, 370, 1000, 495, 945, 1000, 482, 430, 414, 1000, 465, 581, 499, 375, 468, 501, 538, 378, 443, 1000, 490, 524, 477, 517, 437, 1000, 397, 370, 1000, 416, 473, 993, 1000, 801, 592, 535, 433, 531, 386, 393, 1000, 385, 385, 378, 403, 388, 918, 1000, 956, 795, 408, 488, 378, 464, 418, 595, 502, 459, 919, 596, 385, 448, 931, 617, 497, 772, 754, 385, 1000, 646, 441, 515, 712, 379, 410, 597, 371, 420, 872, 719, 1000, 410, 410, 973, 1000, 732, 403, 470, 719, 1000, 400, 436, 552, 386, 389, 393, 373, 788, 371, 1000, 397, 896, 1000, 380, 526, 372, 937, 1000, 373, 964, 1000, 1000, 1000, 1000, 419, 689, 373, 888, 406, 1000, 1000, 423, 592, 1000, 423, 523, 995, 383, 473, 795, 472, 654, 1000, 391, 402, 407, 461, 1000, 395, 424, 407, 378, 872, 1000, 378, 479, 503, 1000, 400, 380, 380, 389, 370, 509, 371, 393, 378, 444, 436, 478, 424, 383, 393, 986, 472, 1000, 483, 1000, 380, 373, 516, 371, 481, 380, 407, 430, 378, 580, 373, 1000, 502, 415, 419, 380, 483, 382, 656, 517, 423, 391, 692, 395, 538, 699, 706, 422, 405, 372, 569, 841, 508, 1000, 436, 424, 439, 1000, 1000, 1000, 424, 785, 646, 580, 724, 640, 427, 1000, 1000, 448, 466, 554, 422, 1000, 772, 717, 744, 1000, 578, 499, 914, 694, 380, 402, 393, 1000, 1000, 461, 380, 646, 490, 1000, 495, 1000, 525, 436, 414, 393, 371, 509, 530, 668, 643, 375, 756, 393, 491, 490, 493, 408, 524, 567, 1000, 1000, 556, 511, 452, 465, 1000, 396, 375, 511, 371, 489, 432, 1000, 1000, 400, 708, 1000, 672, 380, 440, 391, 1000, 433, 375, 950, 483, 1000, 1000, 461, 625, 974, 1000, 1000, 430, 575, 433, 545, 415, 380, 470, 580, 642, 460, 896, 403, 754, 564, 392, 430, 1000, 1000, 370, 741, 603, 410, 643, 515, 371, 622, 644, 505, 1000, 375, 437, 380, 400, 706, 487, 525, 389, 393, 378, 389, 978, 386, 1000, 1000, 882, 1000, 547, 400, 1000, 370, 829, 494, 749, 610, 906, 1000, 403, 1000, 744, 423, 1000, 432, 617, 833, 502, 380, 996, 589, 429, 525, 416, 430, 1000, 403, 1000, 397, 381, 749, 432, 539, 1000, 1000, 484, 558, 422, 399, 516, 480, 1000, 684, 594, 677, 424, 432, 443, 864, 509, 371, 547, 501, 428, 580, 1000, 1000, 689, 391, 618, 524, 482, 682, 624, 1000, 436, 742, 499, 1000, 458, 397, 1000, 1000, 406, 375, 407, 661, 592, 662, 436, 378, 465, 508, 429, 473, 380, 882, 623, 1000, 409, 508, 584, 511, 1000, 375, 1000, 373, 501, 381, 1000, 493, 440, 494, 413, 757, 624, 491, 734, 413, 863, 1000, 397, 389, 386, 371, 876, 1000, 819, 460, 422, 407, 1000, 497, 1000, 432, 400, 422, 399, 510, 466, 1000, 436, 573, 381, 376, 1000, 578, 419, 719, 482, 656, 390, 388, 511, 843, 426, 723, 538, 372, 400, 884, 1000, 415, 450, 681, 656, 1000, 497, 425, 1000, 1000, 444, 820, 450, 816, 431, 399, 370, 394, 387, 1000, 625, 385, 524, 422, 385, 387, 403, 1000, 1000, 593, 1000, 1000, 530, 458, 1000, 472, 436, 1000, 441, 456, 1000, 449, 394, 786, 391, 1000, 1000, 706, 383, 375, 517, 1000, 592, 422, 501, 1000, 429, 449, 1000, 386, 591, 1000, 590, 591, 371, 876, 415, 389, 375, 1000, 1000, 795, 1000, 472, 401, 451, 392, 469, 493, 437, 415, 1000, 430, 554, 952, 1000, 442, 620, 634, 440, 1000, 800, 1000, 378, 441, 617, 373, 1000, 1000, 1000, 442, 1000, 530, 436, 499, 503, 597, 523, 444, 1000, 544, 691, 737, 390, 452, 385, 397, 809, 400, 380, 499, 846, 501, 1000, 809, 371, 640, 1000, 377, 415, 383, 524, 371, 400, 479, 389, 508, 985, 410, 486, 380, 423, 1000, 499, 1000, 409, 382, 436, 1000, 382, 660, 592, 420, 1000, 380, 389, 1000, 400, 759, 436, 808, 1000, 1000, 410, 415, 400, 1000, 1000, 703, 482, 646, 400, 938, 475, 651, 1000, 482, 596, 624, 1000, 416, 1000, 424, 373, 371, 483, 809, 444, 415, 390, 1000, 1000, 495, 857, 436, 445, 383, 432, 553, 621, 375, 460, 473, 748, 566, 632, 484, 504, 520, 1000, 1000, 380, 371, 1000, 1000, 1000, 914, 813, 1000, 467, 409, 797, 400, 515, 581, 1000, 524, 400, 821, 1000, 489, 490, 432, 524, 444, 559, 1000, 1000, 1000, 376, 593, 470, 468, 375, 395, 451, 422, 375, 389, 521, 751, 745, 443, 849, 1000, 489, 394, 445, 713, 530, 407, 1000, 503, 519, 402, 382, 1000, 385, 389, 901, 444, 731, 877, 1000, 1000, 525, 636, 1000, 1000, 439, 1000, 591, 754, 422, 489, 846, 378, 1000, 533, 533, 1000, 370, 631, 1000, 382, 378, 422, 1000, 669, 1000, 407, 403, 1000, 524, 372, 504, 994, 1000, 1000, 425, 373, 371, 1000, 432, 393, 1000, 1000, 660, 592, 1000, 769, 493, 400, 1000, 406, 393, 372, 385, 593, 393, 762, 482, 425, 416, 378, 371, 440, 1000, 684, 438, 380, 380, 385, 471, 581, 1000, 552, 424, 386, 459, 1000, 1000, 438, 566, 597, 1000, 482, 1000, 372, 897, 1000, 400, 407, 482, 534, 940, 686, 411, 424, 921, 1000, 1000, 465, 464, 400, 383, 714, 434, 391, 513, 884, 457, 432, 517, 1000, 773, 791, 525, 393, 396, 461, 1000, 429, 371, 1000, 458, 371, 713, 1000, 1000, 763, 436, 668, 609, 437, 443, 543, 616, 670, 694}; //}}} //{{{float A_flt[1000] = { float A_flt[1000] = { 12.12021, 3.88225, 3.4088, 14.7654, 3.48997, 1.87484, 6.77027, 11.9687, 3.91381, 14.51326, 15.4361, 70.82748, 10.98394, 3.4088, 7.00699, 14.99353, 6.74875, 3.70339, 5.9086, 9.46891, 11.11019, 12.83984, 2.98867, 10.60518, 3.52535, 9.09015, 6.88074, 5.51758, 6.57388, 9.72435, 19.31658, 8.55989, 4.3557, 3.29518, 3.34568, 14.73803, 3.03005, 3.24808, 3.78756, 5.30259, 7.87982, 5.11321, 2.65129, 703.58101, 16.76629, 9.75298, 6.42889, 5.30259, 4.22043, 10.03705, 4.74661, 3.18155, 4.29257, 2.21843, 18.93783, 2.25607, 221.42388, 8.7114, 5.11321, 5.26471, 7.95388, 8.08975, 7.6656, 3.31412, 3.03005, 2.86171, 7.21588, 6.18635, 3.21943, 3.32893, 9.87197, 15.46589, 3.03005, 12.27171, 17.15226, 7.70302, 2.27253, 2.46191, 4.22459, 3.93906, 5.11321, 3.50349, 5.51496, 18.43282, 2.33566, 7.19637, 19.94784, 4.31782, 3.47468, 8.91237, 55.35055, 8.03434, 24.23541, 7.40464, 5.32535, 4.15464, 35.09704, 7.00258, 4.06529, 2.34536, 23.12527, 3.14278, 9.09766, 7.56379, 3.40077, 7.28391, 5.62886, 9.42185, 5.47251, 4.92526, 3.02764, 2.27835, 3.6744, 3.57667, 3.47113, 7.03608, 5.59169, 17.01169, 3.61855, 8.00551, 3.48453, 5.54992, 4.10438, 6.30188, 45.08121, 2.34536, 34.71985, 9.38144, 12.66495, 11.96134, 31.76898, 11.72681, 7.97423, 6.87972, 3.56495, 5.62886, 4.69072, 4.92526, 6.09794, 7.27949, 2.81443, 7.03608, 3.09587, 4.29351, 7.28596, 9.12913, 14.21216, 7.02574, 4.87899, 30.27434, 5.85479, 2.81897, 2.62071, 3.51287, 5.46447, 2.43949, 11.94931, 5.07415, 6.2451, 2.68886, 5.07415, 4.34927, 15.91178, 13.46601, 13.07569, 6.2451, 12.33409, 4.57231, 2.73223, 4.87899, 3.51287, 3.12255, 3.77308, 3.95198, 5.46447, 2.17928, 9.1725, 8.49777, 9.98567, 3.77308, 3.77308, 4.7739, 5.04813, 9.10745, 3.22013, 7.32016, 8.56192, 278.95909, 4.47425, 4.47425, 14.64303, 4.0675, 74.15807, 4.27088, 3.66075, 9.23069, 5.69451, 6.72335, 3.66075, 3.84153, 26.57438, 25.86841, 2.63032, 2.64388, 12.60927, 25.57446, 2.03375, 7.79605, 16.21919, 15.89002, 19.9522, 28.35634, 3.45738, 4.37627, 3.66075, 7.18593, 711.99196, 8.13501, 7.10458, 4.20309, 5.89788, 11.72182, 2.59303, 5.28467, 4.76479, 2.32429, 2.93764, 5.38944, 4.27088, 10.77889, 10.98227, 3.52517, 2.55671, 3.254, 20.84931, 20.3708, 3.18293, 3.18293, 4.8805, 8.27563, 7.35612, 24.57228, 8.27563, 17.58992, 10.50369, 10.82198, 4.6683, 4.03172, 2.63729, 3.81952, 7.63905, 5.38724, 1.66492, 4.45611, 8.27563, 5.94148, 12.73175, 9.54881, 120.4028, 2.84145, 6.90067, 4.38903, 5.14167, 8.64033, 6.69771, 6.37121, 2.36787, 1.76866, 7.50955, 5.6829, 6.73498, 3.85625, 2.60949, 6.33298, 6.08882, 7.03598, 3.65329, 16.10157, 4.22158, 20.45145, 3.45033, 3.85625, 6.81006, 2.65302, 7.06046, 6.27596, 4.4217, 3.70852, 11.79783, 2.50631, 2.46046, 12.4093, 8.80896, 5.72578, 2.46046, 2.78139, 5.88372, 6.4186, 7.70232, 6.2211, 4.70697, 8.98604, 2.11436, 6.97488, 13.93754, 9.41395, 28.7183, 5.99069, 4.27906, 7.41705, 6.76093, 3.97953, 2.37293, 6.10739, 6.4186, 8.49451, 1.9652, 3.79767, 2.43906, 8.59356, 13.44763, 14.87347, 9.17197, 14.74953, 6.69306, 2.89842, 8.59356, 7.23842, 4.70993, 4.29678, 8.4283, 12.27062, 14.30332, 7.50125, 2.25856, 4.36288, 3.8246, 6.66552, 4.21415, 132.01495, 16.36082, 5.12308, 5.94939, 5.20571, 6.94095, 6.02564, 4.6273, 9.91565, 7.68463, 3.09864, 11.56826, 8.4283, 8.4283, 14.37769, 3.59442, 7.65796, 4.17873, 5.65192, 7.84238, 10.78327, 3.71836, 6.77569, 7.18884, 5.78413, 10.23115, 2.77158, 2.45482, 3.89341, 1.40558, 6.64682, 10.11018, 8.14505, 24.74626, 8.89158, 3.40508, 7.80002, 8.41589, 2.87056, 9.10662, 3.06853, 14.19728, 23.05476, 2.77158, 5.50356, 1.93874, 8.97464, 4.89715, 2.34735, 4.20686, 8.78987, 32.86303, 15.93659, 3.2467, 3.01523, 3.76143, 2.69239, 5.14722, 2.53401, 14.9326, 4.55331, 5.62235, 3.36549, 5.22641, 3.2665, 6.73098, 6.599, 2.57361, 3.03554, 12.67008, 13.46196, 2.33794, 6.00072, 4.25505, 2.56394, 3.19129, 4.546, 2.12752, 5.81888, 12.42236, 2.58404, 7.85549, 3.6368, 4.50054, 2.63668, 5.4552, 7.85549, 5.4552, 12.73173, 17.79964, 5.18244, 7.09176, 3.16401, 17.89681, 7.63728, 23.66953, 7.53271, 13.70596, 15.50422, 6.09442, 6.58198, 13.31022, 2.92532, 4.91617, 8.07562, 6.985, 7.06953, 6.26855, 10.6043, 3.01674, 5.53584, 9.01975, 2.66413, 7.77039, 3.14472, 7.7539, 8.19699, 3.94918, 4.17865, 4.87554, 20.61221, 5.11931, 3.83948, 7.31331, 7.93728, 17.58677, 2.77905, 12.70687, 2.40294, 3.83948, 5.22379, 3.14472, 3.96137, 12.43263, 47.90219, 2.74249, 8.9588, 4.93648, 1.98068, 5.60687, 4.11373, 27.75734, 5.18026, 3.57539, 9.53361, 3.88196, 2.63503, 2.72913, 12.16264, 5.29359, 3.29378, 5.62242, 4.51719, 2.95768, 3.59322, 27.57372, 6.74442, 6.03861, 2.91735, 7.1355, 8.94028, 3.41142, 4.75769, 2.91735, 9.81469, 4.86226, 5.17595, 14.11624, 34.34951, 2.62718, 941.31799, 4.42308, 10.56239, 6.58757, 2.43113, 1.42451, 4.10654, 10.82245, 3.92117, 6.3523, 7.05812, 5.48964, 4.73982, 6.11703, 6.65148, 18.89433, 356.30091, 293.75971, 10.60102, 4.23487, 4.6113, 7.8496, 6.43073, 10.19506, 2.94088, 23.91918, 3.24673, 3.58787, 4.00325, 10.19506, 2.99435, 3.67022, 5.05831, 2.70561, 5.28051, 4.33943, 2.86245, 5.12367, 2.70561, 31.8797, 14.78844, 92.30747, 610.58464, 4.70541, 3.29378, 8.28664, 6.62077, 4.44232, 3.75888, 6.87706, 5.86581, 6.50748, 3.75888, 16.42786, 2.32367, 2.08447, 2.93876, 2.90459, 3.89557, 5.63833, 14.66536, 4.9549, 4.51066, 3.58803, 2.00758, 6.05807, 2.26387, 2.4399, 3.31953, 2.78779, 5.70311, 2.5287, 2.73373, 2.38517, 9.71738, 3.09189, 5.55278, 3.97529, 2.35572, 2.25266, 8.6573, 17.99924, 6.52081, 4.85869, 7.15639, 10.11753, 46.59926, 22.22549, 3.86486, 62.05873, 6.65638, 2.88552, 8.07947, 2.93799, 3.23178, 1.65818, 3.55007, 2.09856, 4.22336, 3.30523, 17.87277, 5.21493, 5.87598, 8.53824, 4.95785, 5.87598, 2.57074, 3.0298, 10.7948, 12.87665, 3.38472, 6.62337, 6.41995, 3.47825, 2.89037, 10.73001, 5.19463, 2.69441, 16.18051, 2.7434, 2.38164, 3.65484, 3.44885, 4.50702, 3.03308, 3.03048, 6.58418, 8.08771, 3.28229, 2.23951, 3.91915, 11.88933, 5.29086, 10.25454, 3.40792, 4.70298, 14.73023, 5.40111, 3.44885, 5.91792, 13.13354, 2.76646, 14.78081, 12.97096, 2.64027, 5.48681, 10.09529, 17.67994, 13.15142, 3.91915, 4.74909, 12.23336, 7.05448, 5.74809, 4.96426, 2.82179, 2.65631, 2.35149, 2.98835, 3.18431, 2.46906, 5.0949, 44.87433, 4.18043, 8.62214, 6.27064, 5.13025, 2.80661, 3.43829, 5.56028, 10.8051, 22.24113, 12.43104, 6.72841, 7.14893, 3.60658, 11.96839, 4.28936, 7.14893, 11.98298, 7.6851, 2.26383, 9.27773, 4.95659, 2.62127, 7.90684, 6.35461, 5.41946, 4.21893, 6.67234, 9.87853, 4.60709, 5.16776, 5.48085, 2.10496, 6.91063, 2.3234, 3.05021, 6.01702, 5.07265, 4.52766, 8.34042, 12.54419, 4.57531, 6.08227, 6.01702, 4.7149, 5.10638, 3.61955, 3.25597, 2.95997, 3.10797, 3.10797, 6.21595, 2.08336, 4.77296, 1.62798, 4.52876, 7.61137, 3.19677, 4.88396, 93.19067, 4.23694, 4.27716, 7.57789, 5.18921, 3.99597, 2.34683, 4.58796, 12.93933, 2.51598, 9.19883, 7.54794, 3.03397, 11.91391, 15.83552, 66.766, 4.46463, 4.88396, 6.51195, 4.58796, 8.73091, 6.13001, 8.6826, 2.35318, 166.66526, 7.99194, 10.65592, 7.2654, 6.87075, 10.34996, 4.3413, 2.49748, 14.62498, 3.05864, 8.58393, 7.07782, 3.77397, 4.27346, 6.88194, 6.90661, 8.87993, 9.19961, 9.32393, 3.99597, 3.10797, 3.32997, 15.53988, 6.21595, 22.91597, 1.75206, 6.51226, 4.33224, 2.9566, 4.07902, 4.87641, 2.58703, 3.77788, 2.62809, 2.37258, 2.60984, 2.54596, 3.96007, 2.66459, 2.87447, 5.0098, 4.12986, 2.73759, 2.54596, 11.49791, 6.67973, 3.92785, 2.20943, 3.44937, 6.33906, 10.21515, 7.68677, 5.46142, 5.831, 6.92731, 2.00565, 1.74629, 2.80603, 2.21745, 5.25618, 4.37766, 5.34069, 7.9774, 5.95029, 4.92767, 4.91707, 2.0921, 1.92053, 3.94214, 3.16192, 1.82823, 4.92767, 7.30306, 12.37394, 5.09193, 1.66445, 2.57012, 9.52684, 3.86001, 2.54596, 3.28511, 4.95543, 5.96741, 3.45937, 3.00965, 6.91874, 6.44925, 15.56717, 4.4107, 20.14233, 50.63039, 3.85473, 3.97827, 3.94368, 5.24671, 4.2995, 5.44851, 10.41518, 2.76749, 6.61812, 2.35866, 2.5204, 10.63757, 4.67015, 625.8006, 7.78358, 3.33582, 3.66116, 23.55738, 7.00523, 20.11554, 5.83769, 3.63234, 9.50246, 7.13495, 2.80209, 5.30362, 3.8682, 4.26244, 2.54735, 3.85473, 8.98668, 4.4107, 5.88093, 3.80531, 3.80531, 4.874, 1.72968, 4.61249, 6.14903, 2.5204, 4.4107, 6.72949, 15.48069, 5.25392, 9.643, 2.33507, 3.63234, 5.86931, 3.95665, 4.15124, 3.37288, 4.24559, 13.07643, 8.1283, 3.68784, 3.7932, 5.90054, 32.52693, 3.7932, 7.16494, 7.52157, 10.26848, 4.53077, 6.11127, 16.12113, 5.86378, 3.49215, 4.63614, 11.41474, 2.80978, 2.03709, 2.44451, 1.79123, 3.33661, 7.16494, 9.31376, 3.8803, 3.68784, 3.11885, 2.8449, 5.90054, 9.69375, 15.1404, 5.11781, 3.89857, 92.81556, 4.00394, 3.51222, 2.46859, 4.27488, 5.77878, 5.00768, 8.19586, 4.21467, 6.32201, 11.73622, 13.06006, 3.74345, 4.9373, 7.28455, 8.90334, 11.33152, 9.86449, 4.04697, 5.26106, 11.07399, 7.28455, 5.13173, 11.33152, 2.93405, 8.66052, 6.72705, 2.76543, 218.03325, 30.3523, 23.03095, 11.55227, 8.88089, 3.37247, 2.18536, 2.17524, 7.38572, 2.89069, 3.50737, 3.64227, 3.22139, 3.12195, 8.90334, 3.91207, 43.99865, 17.65578, 5.8392, 11.26905, 4.24932, 2.14489, 14.27604, 12.67801, 6.27863, 3.3808, 9.28379, 5.47368, 6.7616, 6.43962, 8.63983, 19.81925, 11.755, 2.65634, 5.01083, 8.09792, 4.226, 5.1517, 16.39522, 14.79535, 6.7616, 5.65767}; //}}} char *file_name = "../data/many/2.1.bed.gz"; struct input_file *i = input_file_init(file_name); int chrm_len = 10; char *chrm = (char *)malloc(chrm_len*sizeof(char)); uint32_t start, end; long offset; kstring_t line = {0, 0, NULL}; offset_data_size = sizeof(struct offset_data_append_data_test_struct_larger); offset_data_append_data = offset_data_append_data_test_func_larger; struct offset_index *offset_idx = offset_index_init(10, "tmp.test_offset_index_add"); TEST_ASSERT_EQUAL(on_disk, offset_idx->type); uint32_t intrv_id; while (i->input_file_get_next_interval(i, &chrm, &chrm_len, &start, &end, &offset, &line) >= 0) { intrv_id = offset_index_add(offset_idx, offset, &line, 1); } TEST_ASSERT_EQUAL(1000, offset_idx->index->num); uint32_t j; char A_concat[20]; for (j = 0; j < 1000; ++j) { TEST_ASSERT_EQUAL(A_offsets[j], OFFSET_INDEX_PAIR(offset_idx, j)->offset); struct offset_data_append_data_test_struct_larger *tmp; tmp = (struct offset_data_append_data_test_struct_larger *) OFFSET_INDEX_DATA(offset_idx, j); TEST_ASSERT_EQUAL(A_data[j], tmp->uint); TEST_ASSERT_EQUAL(A_flt[j], tmp->flt); int ret = sprintf(A_concat, "%u %.6f", tmp->uint, tmp->flt); TEST_ASSERT_EQUAL(0, strcmp(A_concat, tmp->concat)); } if (line.s != NULL) free(line.s); input_file_destroy(&i); offset_index_store(offset_idx); offset_index_destroy(&offset_idx); free(chrm); offset_idx = offset_index_load("tmp.test_offset_index_add"); TEST_ASSERT_EQUAL(on_disk, offset_idx->type); for (j = 0; j < 1000; ++j) { TEST_ASSERT_EQUAL(A_offsets[j], OFFSET_INDEX_PAIR(offset_idx, j)->offset); struct offset_data_append_data_test_struct_larger *tmp; tmp = (struct offset_data_append_data_test_struct_larger *) OFFSET_INDEX_DATA(offset_idx, j); TEST_ASSERT_EQUAL(A_data[j], tmp->uint); TEST_ASSERT_EQUAL(A_flt[j], tmp->flt); int ret = sprintf(A_concat, "%u %.6f", tmp->uint, tmp->flt); TEST_ASSERT_EQUAL(0, strcmp(A_concat, tmp->concat)); } offset_index_destroy(&offset_idx); remove("tmp.test_offset_index_add"); } //}}}
{ "language": "C" }
/* * device-process.c: detailed processing of device information sent * from kernel. * * Copyright (c) 2006 The Regents of the University of Michigan. * All rights reserved. * * Andy Adamson <andros@citi.umich.edu> * Fred Isaman <iisaman@umich.edu> * * Copyright (c) 2010 EMC Corporation, Haiying Tang <Tang_Haiying@emc.com> * * Used codes in linux/fs/nfs/blocklayout/blocklayoutdev.c. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sys/types.h> #include <sys/stat.h> #include <sys/user.h> #include <arpa/inet.h> #include <linux/kdev_t.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <syslog.h> #include <fcntl.h> #include <errno.h> #include "device-discovery.h" uint32_t *blk_overflow(uint32_t * p, uint32_t * end, size_t nbytes) { uint32_t *q = p + ((nbytes + 3) >> 2); if (q > end || q < p) return NULL; return p; } static int decode_blk_signature(uint32_t **pp, uint32_t * end, struct bl_sig *sig) { int i; uint32_t siglen, *p = *pp; BLK_READBUF(p, end, 4); READ32(sig->si_num_comps); if (sig->si_num_comps == 0) { BL_LOG_ERR("0 components in sig\n"); goto out_err; } if (sig->si_num_comps >= BLOCK_MAX_SIG_COMP) { BL_LOG_ERR("number of sig comps %i >= BLOCK_MAX_SIG_COMP\n", sig->si_num_comps); goto out_err; } for (i = 0; i < sig->si_num_comps; i++) { struct bl_sig_comp *comp = &sig->si_comps[i]; BLK_READBUF(p, end, 12); READ64(comp->bs_offset); READ32(siglen); comp->bs_length = siglen; BLK_READBUF(p, end, siglen); /* Note we rely here on fact that sig is used immediately * for mapping, then thrown away. */ comp->bs_string = (char *)p; p += ((siglen + 3) >> 2); } *pp = p; return 0; out_err: return -EIO; } /* * Read signature from device and compare to sig_comp * return: 0=match, 1=no match, -1=error */ static int read_cmp_blk_sig(struct bl_disk *disk, int fd, struct bl_sig_comp *comp) { const char *dev_name = disk->valid_path->full_path; int ret = -1; ssize_t siglen = comp->bs_length; int64_t bs_offset = comp->bs_offset; char *sig = NULL; sig = (char *)malloc(siglen); if (!sig) { BL_LOG_ERR("%s: Out of memory\n", __func__); goto out; } if (bs_offset < 0) bs_offset += (((int64_t) disk->size) << 9); if (lseek64(fd, bs_offset, SEEK_SET) == -1) { BL_LOG_ERR("File %s lseek error\n", dev_name); goto out; } if (read(fd, sig, siglen) != siglen) { BL_LOG_ERR("File %s read error\n", dev_name); goto out; } ret = memcmp(sig, comp->bs_string, siglen); out: if (sig) free(sig); return ret; } /* * All signatures in sig must be found on disk for verification. * Returns True if sig matches, False otherwise. */ static int verify_sig(struct bl_disk *disk, struct bl_sig *sig) { const char *dev_name = disk->valid_path->full_path; int fd, i, rv; fd = open(dev_name, O_RDONLY | O_LARGEFILE); if (fd < 0) { BL_LOG_ERR("%s: %s could not be opened for read\n", __func__, dev_name); return 0; } rv = 1; for (i = 0; i < sig->si_num_comps; i++) { if (read_cmp_blk_sig(disk, fd, &sig->si_comps[i])) { rv = 0; break; } } if (fd >= 0) close(fd); return rv; } /* * map_sig_to_device() * Given a signature, walk the list of visible disks searching for * a match. Returns True if mapping was done, False otherwise. * * While we're at it, fill in the vol->bv_size. */ static int map_sig_to_device(struct bl_sig *sig, struct bl_volume *vol) { int mapped = 0; struct bl_disk *disk; /* scan disk list to find out match device */ for (disk = visible_disk_list; disk; disk = disk->next) { /* FIXME: should we use better algorithm for disk scan? */ mapped = verify_sig(disk, sig); if (mapped) { vol->param.bv_dev = disk->dev; vol->bv_size = disk->size; break; } } return mapped; } /* We are given an array of XDR encoded array indices, each of which should * refer to a previously decoded device. Translate into a list of pointers * to the appropriate pnfs_blk_volume's. */ static int set_vol_array(uint32_t **pp, uint32_t *end, struct bl_volume *vols, int working) { int i, index; uint32_t *p = *pp; struct bl_volume **array = vols[working].bv_vols; for (i = 0; i < vols[working].bv_vol_n; i++) { BLK_READBUF(p, end, 4); READ32(index); if ((index < 0) || (index >= working)) { BL_LOG_ERR("set_vol_array: Id %i out of range\n", index); goto out_err; } array[i] = &vols[index]; } *pp = p; return 0; out_err: return -EIO; } static uint64_t sum_subvolume_sizes(struct bl_volume *vol) { int i; uint64_t sum = 0; for (i = 0; i < vol->bv_vol_n; i++) sum += vol->bv_vols[i]->bv_size; return sum; } static int decode_blk_volume(uint32_t **pp, uint32_t *end, struct bl_volume *vols, int voln, int *array_cnt) { int status = 0, j; struct bl_sig sig; uint32_t *p = *pp; struct bl_volume *vol = &vols[voln]; uint64_t tmp; BLK_READBUF(p, end, 4); READ32(vol->bv_type); switch (vol->bv_type) { case BLOCK_VOLUME_SIMPLE: *array_cnt = 0; status = decode_blk_signature(&p, end, &sig); if (status) return status; status = map_sig_to_device(&sig, vol); if (!status) { BL_LOG_ERR("Could not find disk for device\n"); return -ENXIO; } BL_LOG_INFO("%s: simple %d\n", __func__, voln); status = 0; break; case BLOCK_VOLUME_SLICE: BLK_READBUF(p, end, 16); READ_SECTOR(vol->param.bv_offset); READ_SECTOR(vol->bv_size); *array_cnt = vol->bv_vol_n = 1; BL_LOG_INFO("%s: slice %d\n", __func__, voln); status = set_vol_array(&p, end, vols, voln); break; case BLOCK_VOLUME_STRIPE: BLK_READBUF(p, end, 8); READ_SECTOR(vol->param.bv_stripe_unit); off_t stripe_unit = vol->param.bv_stripe_unit; /* Check limitations imposed by device-mapper */ if ((stripe_unit & (stripe_unit - 1)) != 0 || stripe_unit < (off_t) (sysconf(_SC_PAGE_SIZE) >> 9)) return -EIO; BLK_READBUF(p, end, 4); READ32(vol->bv_vol_n); if (!vol->bv_vol_n) return -EIO; *array_cnt = vol->bv_vol_n; BL_LOG_INFO("%s: stripe %d nvols=%d unit=%ld\n", __func__, voln, vol->bv_vol_n, (long)stripe_unit); status = set_vol_array(&p, end, vols, voln); if (status) return status; for (j = 1; j < vol->bv_vol_n; j++) { if (vol->bv_vols[j]->bv_size != vol->bv_vols[0]->bv_size) { BL_LOG_ERR("varying subvol size\n"); return -EIO; } } vol->bv_size = vol->bv_vols[0]->bv_size * vol->bv_vol_n; break; case BLOCK_VOLUME_CONCAT: BLK_READBUF(p, end, 4); READ32(vol->bv_vol_n); if (!vol->bv_vol_n) return -EIO; *array_cnt = vol->bv_vol_n; BL_LOG_INFO("%s: concat %d %d\n", __func__, voln, vol->bv_vol_n); status = set_vol_array(&p, end, vols, voln); if (status) return status; vol->bv_size = sum_subvolume_sizes(vol); break; default: BL_LOG_ERR("Unknown volume type %i\n", vol->bv_type); out_err: return -EIO; } *pp = p; return status; } uint64_t process_deviceinfo(const char *dev_addr_buf, unsigned int dev_addr_len, uint32_t *major, uint32_t *minor) { int num_vols, i, status, count; uint32_t *p, *end; struct bl_volume *vols = NULL, **arrays = NULL, **arrays_ptr = NULL; uint64_t dev = 0; p = (uint32_t *) dev_addr_buf; end = (uint32_t *) ((char *)p + dev_addr_len); /* Decode block volume */ BLK_READBUF(p, end, 4); READ32(num_vols); BL_LOG_INFO("%s: %d vols\n", __func__, num_vols); if (num_vols <= 0) goto out_err; vols = (struct bl_volume *)malloc(num_vols * sizeof(struct bl_volume)); if (!vols) { BL_LOG_ERR("%s: Out of memory\n", __func__); goto out_err; } /* Each volume in vols array needs its own array. Save time by * allocating them all in one large hunk. Because each volume * array can only reference previous volumes, and because once * a concat or stripe references a volume, it may never be * referenced again, the volume arrays are guaranteed to fit * in the suprisingly small space allocated. */ arrays_ptr = arrays = (struct bl_volume **)malloc(num_vols * 2 * sizeof(struct bl_volume *)); if (!arrays) { BL_LOG_ERR("%s: Out of memory\n", __func__); goto out_err; } for (i = 0; i < num_vols; i++) { vols[i].bv_vols = arrays_ptr; status = decode_blk_volume(&p, end, vols, i, &count); if (status) goto out_err; arrays_ptr += count; } if (p != end) { BL_LOG_ERR("p is not equal to end!\n"); goto out_err; } dev = dm_device_create(vols, num_vols); if (dev) { *major = MAJOR(dev); *minor = MINOR(dev); } out_err: if (vols) free(vols); if (arrays) free(arrays); return dev; }
{ "language": "C" }
/* bnx2fc_debug.h: QLogic Linux FCoE offload driver. * Handles operations such as session offload/upload etc, and manages * session resources such as connection id and qp resources. * * Copyright (c) 2008-2013 Broadcom Corporation * Copyright (c) 2014-2015 QLogic Corporation * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation. * */ #ifndef __BNX2FC_DEBUG__ #define __BNX2FC_DEBUG__ /* Log level bit mask */ #define LOG_IO 0x01 /* scsi cmd error, cleanup */ #define LOG_TGT 0x02 /* Session setup, cleanup, etc' */ #define LOG_HBA 0x04 /* lport events, link, mtu, etc' */ #define LOG_ELS 0x08 /* ELS logs */ #define LOG_MISC 0x10 /* fcoe L2 frame related logs*/ #define LOG_ALL 0xff /* LOG all messages */ extern unsigned int bnx2fc_debug_level; #define BNX2FC_ELS_DBG(fmt, ...) \ do { \ if (unlikely(bnx2fc_debug_level & LOG_ELS)) \ pr_info(fmt, ##__VA_ARGS__); \ } while (0) #define BNX2FC_MISC_DBG(fmt, ...) \ do { \ if (unlikely(bnx2fc_debug_level & LOG_MISC)) \ pr_info(fmt, ##__VA_ARGS__); \ } while (0) __printf(2, 3) void BNX2FC_IO_DBG(const struct bnx2fc_cmd *io_req, const char *fmt, ...); __printf(2, 3) void BNX2FC_TGT_DBG(const struct bnx2fc_rport *tgt, const char *fmt, ...); __printf(2, 3) void BNX2FC_HBA_DBG(const struct fc_lport *lport, const char *fmt, ...); #endif
{ "language": "C" }
/****************************************************************************** * Copyright(c) 2008 - 2010 Realtek Corporation. All rights reserved. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * The full GNU General Public License is included in this distribution in the * file called LICENSE. * * Contact Information: * wlanfae <wlanfae@realtek.com> ******************************************************************************/ #ifndef R819x_WX_H #define R819x_WX_H struct iw_handler_def; extern const struct iw_handler_def r8192_wx_handlers_def; #endif
{ "language": "C" }
/* Register fork handlers. Generic version. Copyright (C) 2002-2020 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <https://www.gnu.org/licenses/>. */ #include <pthread.h> #include <pt-internal.h> #include <fork.h> #include <dso_handle.h> /* Hide the symbol so that no definition but the one locally in the executable or DSO is used. */ int #ifndef __pthread_atfork /* Don't mark the compatibility function as hidden. */ attribute_hidden #endif __pthread_atfork (void (*prepare) (void), void (*parent) (void), void (*child) (void)) { return __register_atfork (prepare, parent, child, __dso_handle); } #ifndef __pthread_atfork extern int pthread_atfork (void (*prepare) (void), void (*parent) (void), void (*child) (void)) attribute_hidden; weak_alias (__pthread_atfork, pthread_atfork) #endif
{ "language": "C" }
/**************************************************************************/ /* */ /* This file is part of tis-interpreter. */ /* Copyright (C) 2016 TrustInSoft */ /* */ /* you can redistribute it and/or modify it under the terms of the GNU */ /* General Public License as published by the Free Software */ /* Foundation, version 2. */ /* */ /* It is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /* GNU General Public License version 2 for more details. */ /* (enclosed in the file licences/GPLv2). */ /* */ /**************************************************************************/ /* POSIX header */ #ifndef __FC_SYS_TIMEB_H__ #define __FC_SYS_TIMEB_H__ #include "../features.h" #include "../__fc_define_time_t.h" __BEGIN_DECLS struct timeb { time_t time; unsigned short millitm; short timezone; short dstflag; }; int ftime(struct timeb *timebuf); __END_DECLS #endif
{ "language": "C" }
#ifndef _UNISTD_ #define _UNISTD_ /* Win32 define for porting git*/ #ifndef _MODE_T_ #define _MODE_T_ typedef unsigned short _mode_t; #ifndef _NO_OLDNAMES typedef _mode_t mode_t; #endif #endif /* Not _MODE_T_ */ #ifndef _SSIZE_T_ #define _SSIZE_T_ typedef long _ssize_t; #ifndef _OFF_T_ #define _OFF_T_ typedef long _off_t; #ifndef _NO_OLDNAMES typedef _off_t off_t; #endif #endif /* Not _OFF_T_ */ #ifndef _NO_OLDNAMES typedef _ssize_t ssize_t; #endif #endif /* Not _SSIZE_T_ */ typedef signed char int8_t; typedef unsigned char uint8_t; typedef short int16_t; typedef unsigned short uint16_t; typedef int int32_t; typedef unsigned uint32_t; typedef long long int64_t; typedef unsigned long long uint64_t; typedef long long intmax_t; typedef unsigned long long uintmax_t; typedef int64_t off64_t; #if !defined(_MSC_VER) || _MSC_VER < 1600 #define INTMAX_MIN _I64_MIN #define INTMAX_MAX _I64_MAX #define UINTMAX_MAX _UI64_MAX #define UINT32_MAX 0xffffffff /* 4294967295U */ #else #include <stdint.h> #endif #define STDIN_FILENO 0 #define STDOUT_FILENO 1 #define STDERR_FILENO 2 /* Some defines for _access nAccessMode (MS doesn't define them, but * it doesn't seem to hurt to add them). */ #define F_OK 0 /* Check for file existence */ /* Well maybe it does hurt. On newer versions of MSVCRT, an access mode of 1 causes invalid parameter error. */ #define X_OK 0 /* MS access() doesn't check for execute permission. */ #define W_OK 2 /* Check for write permission */ #define R_OK 4 /* Check for read permission */ #define _S_IFIFO 0x1000 /* FIFO */ #define _S_IFCHR 0x2000 /* Character */ #define _S_IFBLK 0x3000 /* Block: Is this ever set under w32? */ #define _S_IFDIR 0x4000 /* Directory */ #define _S_IFREG 0x8000 /* Regular */ #define _S_IFMT 0xF000 /* File type mask */ #define _S_IXUSR _S_IEXEC #define _S_IWUSR _S_IWRITE #define _S_IRUSR _S_IREAD #define _S_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR) #define S_IFIFO _S_IFIFO #define S_IFCHR _S_IFCHR #define S_IFBLK _S_IFBLK #define S_IFDIR _S_IFDIR #define S_IFREG _S_IFREG #define S_IFMT _S_IFMT #define S_IEXEC _S_IEXEC #define S_IWRITE _S_IWRITE #define S_IREAD _S_IREAD #define S_IRWXU _S_IRWXU #define S_IXUSR _S_IXUSR #define S_IWUSR _S_IWUSR #define S_IRUSR _S_IRUSR #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG) #define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO) #endif
{ "language": "C" }
/* This file is to be kept in sync with newlib/libc/include/sys/errno.h on which it is based, except values used or returned by syscalls must be those of the Linux/CRIS kernel. */ /* errno is not a global variable, because that would make using it non-reentrant. Instead, its address is returned by the function __errno. */ #ifndef _SYS_ERRNO_H_ #ifdef __cplusplus extern "C" { #endif #define _SYS_ERRNO_H_ #include <sys/reent.h> #ifndef _REENT_ONLY #define errno (*__errno()) extern int *__errno _PARAMS ((void)); #endif /* Please don't use these variables directly. Use strerror instead. */ extern _CONST char * _CONST _sys_errlist[]; extern int _sys_nerr; #define __errno_r(ptr) ((ptr)->_errno) /* Adjusted to the linux asm/errno.h */ #define EPERM 1 /* Operation not permitted */ #define ENOENT 2 /* No such file or directory */ #define ESRCH 3 /* No such process */ #define EINTR 4 /* Interrupted system call */ #define EIO 5 /* I/O error */ #define ENXIO 6 /* No such device or address */ #define E2BIG 7 /* Arg list too long */ #define ENOEXEC 8 /* Exec format error */ #define EBADF 9 /* Bad file number */ #define ECHILD 10 /* No child processes */ #define EAGAIN 11 /* Try again */ #define ENOMEM 12 /* Out of memory */ #define EACCES 13 /* Permission denied */ #define EFAULT 14 /* Bad address */ #define ENOTBLK 15 /* Block device required */ #define EBUSY 16 /* Device or resource busy */ #define EEXIST 17 /* File exists */ #define EXDEV 18 /* Cross-device link */ #define ENODEV 19 /* No such device */ #define ENOTDIR 20 /* Not a directory */ #define EISDIR 21 /* Is a directory */ #define EINVAL 22 /* Invalid argument */ #define ENFILE 23 /* File table overflow */ #define EMFILE 24 /* Too many open files */ #define ENOTTY 25 /* Not a typewriter */ #define ETXTBSY 26 /* Text file busy */ #define EFBIG 27 /* File too large */ #define ENOSPC 28 /* No space left on device */ #define ESPIPE 29 /* Illegal seek */ #define EROFS 30 /* Read-only file system */ #define EMLINK 31 /* Too many links */ #define EPIPE 32 /* Broken pipe */ #define EDOM 33 /* Math argument out of domain of func */ #define ERANGE 34 /* Math result not representable */ #define EDEADLK 35 /* Resource deadlock would occur */ #define ENAMETOOLONG 36 /* File name too long */ #define ENOLCK 37 /* No record locks available */ #define ENOSYS 38 /* Function not implemented */ #define ENOTEMPTY 39 /* Directory not empty */ #define ELOOP 40 /* Too many symbolic links encountered */ #define EWOULDBLOCK EAGAIN /* Operation would block */ #define ENOMSG 42 /* No message of desired type */ #define EIDRM 43 /* Identifier removed */ #define ECHRNG 44 /* Channel number out of range */ #define EL2NSYNC 45 /* Level 2 not synchronized */ #define EL3HLT 46 /* Level 3 halted */ #define EL3RST 47 /* Level 3 reset */ #define ELNRNG 48 /* Link number out of range */ #define EUNATCH 49 /* Protocol driver not attached */ #define ENOCSI 50 /* No CSI structure available */ #define EL2HLT 51 /* Level 2 halted */ #define EBADE 52 /* Invalid exchange */ #define EBADR 53 /* Invalid request descriptor */ #define EXFULL 54 /* Exchange full */ #define ENOANO 55 /* No anode */ #define EBADRQC 56 /* Invalid request code */ #define EBADSLT 57 /* Invalid slot */ #define EDEADLOCK EDEADLK #define EBFONT 59 /* Bad font file format */ /* This is only used internally in newlib; not returned by the kernel. EBFONT seems the closest match for a "bad file format" error. */ #define EFTYPE EBFONT /* Inappropriate file type or format */ #define ENOSTR 60 /* Device not a stream */ #define ENODATA 61 /* No data available */ #define ETIME 62 /* Timer expired */ #define ENOSR 63 /* Out of streams resources */ #define ENONET 64 /* Machine is not on the network */ #define ENOPKG 65 /* Package not installed */ #define EREMOTE 66 /* Object is remote */ #define ENOLINK 67 /* Link has been severed */ #define EADV 68 /* Advertise error */ #define ESRMNT 69 /* Srmount error */ #define ECOMM 70 /* Communication error on send */ #define EPROTO 71 /* Protocol error */ #define EMULTIHOP 72 /* Multihop attempted */ #define EDOTDOT 73 /* RFS specific error */ #define EBADMSG 74 /* Not a data message */ #define EOVERFLOW 75 /* Value too large for defined data type */ #define ENOTUNIQ 76 /* Name not unique on network */ #define EBADFD 77 /* File descriptor in bad state */ #define EREMCHG 78 /* Remote address changed */ #define ELIBACC 79 /* Can not access a needed shared library */ #define ELIBBAD 80 /* Accessing a corrupted shared library */ #define ELIBSCN 81 /* .lib section in a.out corrupted */ #define ELIBMAX 82 /* Attempting to link in too many shared libraries */ #define ELIBEXEC 83 /* Cannot exec a shared library directly */ #define EILSEQ 84 /* Illegal byte sequence */ #define ERESTART 85 /* Interrupted system call should be restarted */ #define ESTRPIPE 86 /* Streams pipe error */ #define EUSERS 87 /* Too many users */ #define ENOTSOCK 88 /* Socket operation on non-socket */ #define EDESTADDRREQ 89 /* Destination address required */ #define EMSGSIZE 90 /* Message too long */ #define EPROTOTYPE 91 /* Protocol wrong type for socket */ #define ENOPROTOOPT 92 /* Protocol not available */ #define EPROTONOSUPPORT 93 /* Protocol not supported */ #define ESOCKTNOSUPPORT 94 /* Socket type not supported */ #define EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ #define EPFNOSUPPORT 96 /* Protocol family not supported */ #define EAFNOSUPPORT 97 /* Address family not supported by protocol */ #define EADDRINUSE 98 /* Address already in use */ #define EADDRNOTAVAIL 99 /* Cannot assign requested address */ #define ENETDOWN 100 /* Network is down */ #define ENETUNREACH 101 /* Network is unreachable */ #define ENETRESET 102 /* Network dropped connection because of reset */ #define ECONNABORTED 103 /* Software caused connection abort */ #define ECONNRESET 104 /* Connection reset by peer */ #define ENOBUFS 105 /* No buffer space available */ #define EISCONN 106 /* Transport endpoint is already connected */ #define ENOTCONN 107 /* Transport endpoint is not connected */ #define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */ #define ETOOMANYREFS 109 /* Too many references: cannot splice */ #define ETIMEDOUT 110 /* Connection timed out */ #define ECONNREFUSED 111 /* Connection refused */ #define EHOSTDOWN 112 /* Host is down */ #define EHOSTUNREACH 113 /* No route to host */ #define EALREADY 114 /* Operation already in progress */ #define EINPROGRESS 115 /* Operation now in progress */ #define ESTALE 116 /* Stale NFS file handle */ #define EUCLEAN 117 /* Structure needs cleaning */ #define ENOTNAM 118 /* Not a XENIX named type file */ #define ENAVAIL 119 /* No XENIX semaphores available */ #define EISNAM 120 /* Is a named type file */ #define EREMOTEIO 121 /* Remote I/O error */ #define EDQUOT 122 /* Quota exceeded */ #define ENOMEDIUM 123 /* No medium found */ #define EMEDIUMTYPE 124 /* Wrong medium type */ #define ECANCELED 125 /* Operation Canceled */ #define ENOKEY 126 /* Required key not available */ #define EKEYEXPIRED 127 /* Key has expired */ #define EKEYREVOKED 128 /* Key has been revoked */ #define EKEYREJECTED 129 /* Key was rejected by service */ #define EOWNERDEAD 130 /* Owner died */ #define ENOTRECOVERABLE 131 /* State not recoverable */ /* Widely known to be a synonym in Linux. */ #define ENOTSUP EOPNOTSUPP #define __ELASTERROR 2000 /* Users can add values starting here */ #ifdef __cplusplus } #endif #endif /* _SYS_ERRNO_H */
{ "language": "C" }
/* * File: cancel7.c * * * -------------------------------------------------------------------------- * * Pthreads-win32 - POSIX Threads Library for Win32 * Copyright(C) 1998 John E. Bossom * Copyright(C) 1999,2005 Pthreads-win32 contributors * * Contact Email: rpj@callisto.canberra.edu.au * * The current list of contributors is contained * in the file CONTRIBUTORS included with the source * code distribution. The list can also be seen at the * following World Wide Web location: * http://sources.redhat.com/pthreads-win32/contributors.html * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library in the file COPYING.LIB; * if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA * * -------------------------------------------------------------------------- * * Test Synopsis: Test canceling a Win32 thread having created an * implicit POSIX handle for it. * * Test Method (Validation or Falsification): * - Validate return value and that POSIX handle is created and destroyed. * * Requirements Tested: * - * * Features Tested: * - * * Cases Tested: * - * * Description: * - * * Environment: * - * * Input: * - None. * * Output: * - File name, Line number, and failed expression on failure. * - No output on success. * * Assumptions: * - have working pthread_create, pthread_self, pthread_mutex_lock/unlock * pthread_testcancel, pthread_cancel * * Pass Criteria: * - Process returns zero exit status. * * Fail Criteria: * - Process returns non-zero exit status. */ #include "test.h" #ifndef _UWIN #include <process.h> #endif /* * Create NUMTHREADS threads in addition to the Main thread. */ enum { NUMTHREADS = 4 }; typedef struct bag_t_ bag_t; struct bag_t_ { int threadnum; int started; /* Add more per-thread state variables here */ int count; pthread_t self; }; static bag_t threadbag[NUMTHREADS + 1]; #if ! defined (__MINGW32__) || defined (__MSVCRT__) unsigned __stdcall #else void #endif Win32thread(void * arg) { int i; bag_t * bag = (bag_t *) arg; assert(bag == &threadbag[bag->threadnum]); assert(bag->started == 0); bag->started = 1; assert((bag->self = pthread_self()).p != NULL); assert(pthread_kill(bag->self, 0) == 0); for (i = 0; i < 100; i++) { Sleep(100); pthread_testcancel(); } #if ! defined (__MINGW32__) || defined (__MSVCRT__) return 0; #endif } int main() { int failed = 0; int i; HANDLE h[NUMTHREADS + 1]; unsigned thrAddr; /* Dummy variable to pass a valid location to _beginthreadex (Win98). */ for (i = 1; i <= NUMTHREADS; i++) { threadbag[i].started = 0; threadbag[i].threadnum = i; #if ! defined (__MINGW32__) || defined (__MSVCRT__) h[i] = (HANDLE) _beginthreadex(NULL, 0, Win32thread, (void *) &threadbag[i], 0, &thrAddr); #else h[i] = (HANDLE) _beginthread(Win32thread, 0, (void *) &threadbag[i]); #endif } /* * Code to control or munipulate child threads should probably go here. */ Sleep(500); /* * Cancel all threads. */ for (i = 1; i <= NUMTHREADS; i++) { assert(pthread_kill(threadbag[i].self, 0) == 0); assert(pthread_cancel(threadbag[i].self) == 0); } /* * Give threads time to run. */ Sleep(NUMTHREADS * 100); /* * Standard check that all threads started. */ for (i = 1; i <= NUMTHREADS; i++) { if (!threadbag[i].started) { failed |= !threadbag[i].started; fprintf(stderr, "Thread %d: started %d\n", i, threadbag[i].started); } } assert(!failed); /* * Check any results here. Set "failed" and only print output on failure. */ failed = 0; for (i = 1; i <= NUMTHREADS; i++) { int fail = 0; int result = 0; #if ! defined (__MINGW32__) || defined (__MSVCRT__) assert(GetExitCodeThread(h[i], (LPDWORD) &result) == TRUE); #else /* * Can't get a result code. */ result = (int)(size_t)PTHREAD_CANCELED; #endif assert(threadbag[i].self.p != NULL); assert(pthread_kill(threadbag[i].self, 0) == ESRCH); fail = (result != (int)(size_t)PTHREAD_CANCELED); if (fail) { fprintf(stderr, "Thread %d: started %d: count %d\n", i, threadbag[i].started, threadbag[i].count); } failed = (failed || fail); } assert(!failed); /* * Success. */ return 0; }
{ "language": "C" }
/* Run-time dynamic linker data structures for loaded ELF shared objects. Copyright (C) 1995-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #ifndef _POWERPC_LDSODEFS_H #define _POWERPC_LDSODEFS_H 1 #include <elf.h> #include <cpu-features.h> struct La_ppc32_regs; struct La_ppc32_retval; struct La_ppc64_regs; struct La_ppc64_retval; struct La_ppc64v2_regs; struct La_ppc64v2_retval; #define ARCH_PLTENTER_MEMBERS \ Elf32_Addr (*ppc32_gnu_pltenter) (Elf32_Sym *, unsigned int, uintptr_t *, \ uintptr_t *, struct La_ppc32_regs *, \ unsigned int *, const char *name, \ long int *framesizep); \ Elf64_Addr (*ppc64_gnu_pltenter) (Elf64_Sym *, unsigned int, uintptr_t *, \ uintptr_t *, struct La_ppc64_regs *, \ unsigned int *, const char *name, \ long int *framesizep); \ Elf64_Addr (*ppc64v2_gnu_pltenter) (Elf64_Sym *, unsigned int, \ uintptr_t *, uintptr_t *, \ struct La_ppc64v2_regs *, \ unsigned int *, const char *name, \ long int *framesizep) #define ARCH_PLTEXIT_MEMBERS \ unsigned int (*ppc32_gnu_pltexit) (Elf32_Sym *, unsigned int, \ uintptr_t *, \ uintptr_t *, \ const struct La_ppc32_regs *, \ struct La_ppc32_retval *, \ const char *); \ unsigned int (*ppc64_gnu_pltexit) (Elf64_Sym *, unsigned int, \ uintptr_t *, \ uintptr_t *, \ const struct La_ppc64_regs *, \ struct La_ppc64_retval *, \ const char *); \ unsigned int (*ppc64v2_gnu_pltexit) (Elf64_Sym *, unsigned int, \ uintptr_t *, \ uintptr_t *, \ const struct La_ppc64v2_regs *,\ struct La_ppc64v2_retval *, \ const char *) #include_next <ldsodefs.h> #endif
{ "language": "C" }
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "common.h" #include "commit.h" #include "tag.h" #include "merge.h" #include "diff.h" #include "annotated_commit.h" #include "git2/reset.h" #include "git2/checkout.h" #include "git2/merge.h" #include "git2/refs.h" #define ERROR_MSG "Cannot perform reset" int git_reset_default( git_repository *repo, const git_object *target, const git_strarray* pathspecs) { git_object *commit = NULL; git_tree *tree = NULL; git_diff *diff = NULL; git_diff_options opts = GIT_DIFF_OPTIONS_INIT; size_t i, max_i; git_index_entry entry; int error; git_index *index = NULL; assert(pathspecs != NULL && pathspecs->count > 0); memset(&entry, 0, sizeof(git_index_entry)); if ((error = git_repository_index(&index, repo)) < 0) goto cleanup; if (target) { if (git_object_owner(target) != repo) { git_error_set(GIT_ERROR_OBJECT, "%s_default - The given target does not belong to this repository.", ERROR_MSG); return -1; } if ((error = git_object_peel(&commit, target, GIT_OBJECT_COMMIT)) < 0 || (error = git_commit_tree(&tree, (git_commit *)commit)) < 0) goto cleanup; } opts.pathspec = *pathspecs; opts.flags = GIT_DIFF_REVERSE; if ((error = git_diff_tree_to_index( &diff, repo, tree, index, &opts)) < 0) goto cleanup; for (i = 0, max_i = git_diff_num_deltas(diff); i < max_i; ++i) { const git_diff_delta *delta = git_diff_get_delta(diff, i); assert(delta->status == GIT_DELTA_ADDED || delta->status == GIT_DELTA_MODIFIED || delta->status == GIT_DELTA_CONFLICTED || delta->status == GIT_DELTA_DELETED); error = git_index_conflict_remove(index, delta->old_file.path); if (error < 0) { if (delta->status == GIT_DELTA_ADDED && error == GIT_ENOTFOUND) git_error_clear(); else goto cleanup; } if (delta->status == GIT_DELTA_DELETED) { if ((error = git_index_remove(index, delta->old_file.path, 0)) < 0) goto cleanup; } else { entry.mode = delta->new_file.mode; git_oid_cpy(&entry.id, &delta->new_file.id); entry.path = (char *)delta->new_file.path; if ((error = git_index_add(index, &entry)) < 0) goto cleanup; } } error = git_index_write(index); cleanup: git_object_free(commit); git_tree_free(tree); git_index_free(index); git_diff_free(diff); return error; } static int reset( git_repository *repo, const git_object *target, const char *to, git_reset_t reset_type, const git_checkout_options *checkout_opts) { git_object *commit = NULL; git_index *index = NULL; git_tree *tree = NULL; int error = 0; git_checkout_options opts = GIT_CHECKOUT_OPTIONS_INIT; git_buf log_message = GIT_BUF_INIT; assert(repo && target); if (checkout_opts) opts = *checkout_opts; if (git_object_owner(target) != repo) { git_error_set(GIT_ERROR_OBJECT, "%s - The given target does not belong to this repository.", ERROR_MSG); return -1; } if (reset_type != GIT_RESET_SOFT && (error = git_repository__ensure_not_bare(repo, reset_type == GIT_RESET_MIXED ? "reset mixed" : "reset hard")) < 0) return error; if ((error = git_object_peel(&commit, target, GIT_OBJECT_COMMIT)) < 0 || (error = git_repository_index(&index, repo)) < 0 || (error = git_commit_tree(&tree, (git_commit *)commit)) < 0) goto cleanup; if (reset_type == GIT_RESET_SOFT && (git_repository_state(repo) == GIT_REPOSITORY_STATE_MERGE || git_index_has_conflicts(index))) { git_error_set(GIT_ERROR_OBJECT, "%s (soft) in the middle of a merge", ERROR_MSG); error = GIT_EUNMERGED; goto cleanup; } if ((error = git_buf_printf(&log_message, "reset: moving to %s", to)) < 0) return error; if (reset_type == GIT_RESET_HARD) { /* overwrite working directory with the new tree */ opts.checkout_strategy = GIT_CHECKOUT_FORCE; if ((error = git_checkout_tree(repo, (git_object *)tree, &opts)) < 0) goto cleanup; } /* move HEAD to the new target */ if ((error = git_reference__update_terminal(repo, GIT_HEAD_FILE, git_object_id(commit), NULL, git_buf_cstr(&log_message))) < 0) goto cleanup; if (reset_type > GIT_RESET_SOFT) { /* reset index to the target content */ if ((error = git_index_read_tree(index, tree)) < 0 || (error = git_index_write(index)) < 0) goto cleanup; if ((error = git_repository_state_cleanup(repo)) < 0) { git_error_set(GIT_ERROR_INDEX, "%s - failed to clean up merge data", ERROR_MSG); goto cleanup; } } cleanup: git_object_free(commit); git_index_free(index); git_tree_free(tree); git_buf_dispose(&log_message); return error; } int git_reset( git_repository *repo, const git_object *target, git_reset_t reset_type, const git_checkout_options *checkout_opts) { return reset(repo, target, git_oid_tostr_s(git_object_id(target)), reset_type, checkout_opts); } int git_reset_from_annotated( git_repository *repo, const git_annotated_commit *commit, git_reset_t reset_type, const git_checkout_options *checkout_opts) { return reset(repo, (git_object *) commit->commit, commit->description, reset_type, checkout_opts); }
{ "language": "C" }
/* * Copyright (c) 2008-2015 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #include "si_module.h" #include <paths.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <time.h> #include <dirent.h> #include <errno.h> #include <notify.h> #include <pthread.h> #include <arpa/inet.h> #include <sys/param.h> #include <sys/mount.h> #include <sys/stat.h> #include "ils.h" #include <dispatch/dispatch.h> #include <TargetConditionals.h> /* notify SPI */ uint32_t notify_peek(int token, uint32_t *val); extern uint32_t gL1CacheEnabled; /* These really should be in netdb.h & etc. */ #define _PATH_RPCS "/etc/rpc" #define _PATH_ALIASES "/etc/aliases" #define _PATH_ETHERS "/etc/ethers" #define _PATH_NETGROUP "/etc/netgroup" static dispatch_once_t rootfs_once; static si_item_t *rootfs = NULL; #define CHUNK 256 #define FNG_MEM 0x00000010 #define FNG_GRP 0x00000020 #define forever for(;;) #define VALIDATION_PASSWD 0 #define VALIDATION_MASTER_PASSWD 1 #define VALIDATION_GROUP 2 #define VALIDATION_NETGROUP 3 #define VALIDATION_ALIASES 4 #define VALIDATION_HOSTS 5 #define VALIDATION_NETWORKS 6 #define VALIDATION_SERVICES 7 #define VALIDATION_PROTOCOLS 8 #define VALIDATION_RPC 9 #define VALIDATION_FSTAB 10 #define VALIDATION_ETHERS 11 #define VALIDATION_COUNT 12 #define VALIDATION_MASK_PASSWD 0x00000001 #define VALIDATION_MASK_MASTER_PASSWD 0x00000002 #define VALIDATION_MASK_MASK_GROUP 0x00000004 #define VALIDATION_MASK_NETGROUP 0x00000008 #define VALIDATION_MASK_ALIASES 0x00000010 #define VALIDATION_MASK_HOSTS 0x00000020 #define VALIDATION_MASK_NETWORKS 0x00000040 #define VALIDATION_MASK_SERVICES 0x00000080 #define VALIDATION_MASK_PROTOCOLS 0x00000100 #define VALIDATION_MASK_RPC 0x00000200 #define VALIDATION_MASK_FSTAB 0x00000400 #define VALIDATION_MASK_ETHERS 0x00000800 typedef struct file_netgroup_member_s { uint32_t flags; char *host; char *user; char *domain; struct file_netgroup_member_s *next; } file_netgroup_member_t; typedef struct file_netgroup_s { char *name; uint32_t flags; file_netgroup_member_t *members; struct file_netgroup_s *next; } file_netgroup_t; typedef struct { uint32_t validation_notify_mask; int notify_token[VALIDATION_COUNT]; file_netgroup_t *file_netgroup_cache; uint64_t netgroup_validation_a; uint64_t netgroup_validation_b; } file_si_private_t; static pthread_mutex_t file_mutex = PTHREAD_MUTEX_INITIALIZER; static char * _fsi_copy_string(char *s) { int len; char *t; if (s == NULL) return NULL; len = strlen(s) + 1; t = malloc(len); if (t == NULL) return NULL; bcopy(s, t, len); return t; } static char ** _fsi_append_string(char *s, char **l) { int i, len; if (s == NULL) return l; if (l != NULL) { for (i = 0; l[i] != NULL; i++); len = i; } else { len = 0; } l = (char **) reallocf(l, (len + 2) * sizeof(char *)); if (l == NULL) return NULL; l[len] = s; l[len + 1] = NULL; return l; } char ** _fsi_tokenize(char *data, const char *sep, int trailing_empty, int *ntokens) { char **tokens; int p, i, start, end, more, len, end_on_sep; int scanning; tokens = NULL; end_on_sep = 0; if (data == NULL) return NULL; if (ntokens != NULL) *ntokens = 0; if (sep == NULL) { tokens = _fsi_append_string(data, tokens); if (ntokens != NULL) *ntokens = *ntokens + 1; return tokens; } len = strlen(sep); p = 0; while (data[p] != '\0') { end_on_sep = 1; /* skip leading white space */ while ((data[p] == ' ') || (data[p] == '\t') || (data[p] == '\n')) p++; /* check for end of line */ if (data[p] == '\0') break; /* scan for separator */ start = p; end = p; scanning = 1; end_on_sep = 0; while (scanning == 1) { if (data[p] == '\0') break; for (i = 0; i < len; i++) { if (data[p] == sep[i]) { scanning = 0; end_on_sep = 1; break; } } /* end is last non-whitespace character */ if ((scanning == 1) && (data[p] != ' ') && (data[p] != '\t') && (data[p] != '\n')) end = p; p += scanning; } /* see if there's data left after p */ more = 0; if (data[p] != '\0') more = 1; /* set the character following the token to nul */ if (start == p) data[p] = '\0'; else data[end + 1] = '\0'; tokens = _fsi_append_string(data + start, tokens); if (ntokens != NULL) *ntokens = *ntokens + 1; p += more; } if ((end_on_sep == 1) && (trailing_empty != 0)) { /* if the scan ended on an empty token, add a null string */ tokens = _fsi_append_string(data + p, tokens); if (ntokens != NULL) *ntokens = *ntokens + 1; } return tokens; } char * _fsi_get_line(FILE *fp) { char s[4096]; char *x, *out; s[0] = '\0'; x = fgets(s, sizeof(s), fp); if ((x == NULL) || (s[0] == '\0')) return NULL; if (s[0] != '#') s[strlen(s) - 1] = '\0'; out = _fsi_copy_string(s); return out; } static const char * _fsi_validation_path(int vtype) { if (vtype == VALIDATION_PASSWD) return _PATH_PASSWD; else if (vtype == VALIDATION_MASTER_PASSWD) return _PATH_MASTERPASSWD; else if (vtype == VALIDATION_GROUP) return _PATH_GROUP; else if (vtype == VALIDATION_NETGROUP) return _PATH_NETGROUP; else if (vtype == VALIDATION_ALIASES) return _PATH_ALIASES; else if (vtype == VALIDATION_HOSTS) return _PATH_HOSTS; else if (vtype == VALIDATION_NETWORKS) return _PATH_NETWORKS; else if (vtype == VALIDATION_SERVICES) return _PATH_SERVICES; else if (vtype == VALIDATION_PROTOCOLS) return _PATH_PROTOCOLS; else if (vtype == VALIDATION_RPC) return _PATH_RPCS; else if (vtype == VALIDATION_FSTAB) return _PATH_FSTAB; else if (vtype == VALIDATION_ETHERS) return _PATH_ETHERS; return NULL; } static void _fsi_get_validation(si_mod_t *si, int vtype, const char *path, FILE *f, uint64_t *a, uint64_t *b) { struct stat sb; file_si_private_t *pp; uint32_t peek, bit; int status; if (a != NULL) *a = 0; if (b != NULL) *b = 0; if (si == NULL) return; if (path == NULL) return; if (gL1CacheEnabled == 0) return; pp = (file_si_private_t *)si->private; if (pp == NULL) return; if (vtype >= VALIDATION_COUNT) return; bit = 1 << vtype; if (bit & pp->validation_notify_mask) { /* use notify validation for this type */ if (pp->notify_token[vtype] < 0) { char *str = NULL; asprintf(&str, "com.apple.system.info:%s", path); if (str == NULL) return; status = notify_register_check(str, &(pp->notify_token[vtype])); free(str); } if (a != NULL) { status = notify_peek(pp->notify_token[vtype], &peek); if (status == NOTIFY_STATUS_OK) *a = ntohl(peek); } if (b != NULL) *b = vtype; } else { /* use stat() and last mod time for this type */ memset(&sb, 0, sizeof(struct stat)); if (f != NULL) { if (fstat(fileno(f), &sb) == 0) { if (a != NULL) *a = sb.st_mtimespec.tv_sec; if (b != NULL) *b = sb.st_mtimespec.tv_nsec; } } else { path = _fsi_validation_path(vtype); if (path != NULL) { memset(&sb, 0, sizeof(struct stat)); if (stat(path, &sb) == 0) { if (a != NULL) *a = sb.st_mtimespec.tv_sec; if (b != NULL) *b = sb.st_mtimespec.tv_nsec; } } } } } static int _fsi_validate(si_mod_t *si, int cat, uint64_t va, uint64_t vb) { #if !TARGET_OS_EMBEDDED struct stat sb; const char *path; uint32_t item_val, curr_val, vtype; file_si_private_t *pp; int status; #endif if (si == NULL) return 0; #if !TARGET_OS_EMBEDDED /* /etc is on a read-only filesystem, so no validation is required */ pp = (file_si_private_t *)si->private; if (pp == NULL) return 0; vtype = UINT32_MAX; switch (cat) { case CATEGORY_USER: { if (geteuid() == 0) vtype = VALIDATION_MASTER_PASSWD; else vtype = VALIDATION_PASSWD; break; } case CATEGORY_GROUP: { vtype = VALIDATION_GROUP; break; } case CATEGORY_GROUPLIST: { vtype = VALIDATION_GROUP; break; } case CATEGORY_NETGROUP: { vtype = VALIDATION_NETGROUP; break; } case CATEGORY_ALIAS: { vtype = VALIDATION_ALIASES; break; } case CATEGORY_HOST_IPV4: { vtype = VALIDATION_HOSTS; break; } case CATEGORY_HOST_IPV6: { vtype = VALIDATION_HOSTS; break; } case CATEGORY_NETWORK: { vtype = VALIDATION_NETWORKS; break; } case CATEGORY_SERVICE: { vtype = VALIDATION_SERVICES; break; } case CATEGORY_PROTOCOL: { vtype = VALIDATION_PROTOCOLS; break; } case CATEGORY_RPC: { vtype = VALIDATION_RPC; break; } case CATEGORY_FS: { vtype = VALIDATION_FSTAB; break; } case CATEGORY_MAC: { vtype = VALIDATION_ETHERS; break; } default: return 0; } if (pp->notify_token[vtype] < 0) { path = _fsi_validation_path(vtype); if (path == NULL) return 0; memset(&sb, 0, sizeof(struct stat)); if (stat(path, &sb) != 0) return 0; if (va != sb.st_mtimespec.tv_sec) return 0; if (vb != sb.st_mtimespec.tv_nsec) return 0; } else { item_val = va; curr_val = -1; status = notify_peek(pp->notify_token[vtype], &curr_val); if (status != NOTIFY_STATUS_OK) return 0; curr_val = ntohl(curr_val); if (item_val != curr_val) return 0; } #endif return 1; } /* netgroup support */ static char * _fsi_append_char_to_line(char c, char *buf, size_t *x) { if (x == NULL) return NULL; if (buf == NULL) *x = 0; if ((*x % CHUNK) == 0) { buf = reallocf(buf, *x + CHUNK); if (buf == NULL) return NULL; memset(buf + *x, 0, CHUNK); } buf[*x] = c; *x = *x + 1; return buf; } static char * _fsi_read_netgroup_line(FILE *f) { char *out = NULL; size_t x = 0; int white = 0; int paren = 0; if (f == NULL) return NULL; forever { int c = getc(f); if (c == EOF) { if (out == NULL) return NULL; return _fsi_append_char_to_line('\0', out, &x); } if (c == '\n') return _fsi_append_char_to_line('\0', out, &x); if (c == '(') paren = 1; else if (c == ')') paren = 0; if ((c == ' ') || (c == '\t')) { if ((white == 0) && (paren == 0)) out = _fsi_append_char_to_line(' ', out, &x); white = 1; } else if (c == '\\') { forever { c = getc(f); if (c == EOF) return _fsi_append_char_to_line('\0', out, &x); if (c == '\n') break; } } else { out = _fsi_append_char_to_line(c, out, &x); white = 0; } } } static file_netgroup_t * _fsi_find_netgroup(file_netgroup_t **list, const char *name, int create) { file_netgroup_t *n; if (list == NULL) return NULL; for (n = *list; n != NULL; n = n->next) { if (!strcmp(name, n->name)) return n; } if (create == 0) return NULL; n = (file_netgroup_t *)calloc(1, sizeof(file_netgroup_t)); if (n == NULL) return NULL; n->name = strdup(name); n->next = *list; *list = n; return n; } void _fsi_free_file_netgroup(file_netgroup_t *n) { file_netgroup_member_t *m; if (n == NULL) return; free(n->name); m = n->members; while (m != NULL) { file_netgroup_member_t *x = m; m = m->next; free(x->host); free(x->user); free(x->domain); free(x); } free(n); } static void _fsi_add_netgroup_group(file_netgroup_t *n, char *grp) { file_netgroup_member_t *g; if (n == NULL) return; g = (file_netgroup_member_t *)calloc(1, sizeof(file_netgroup_member_t)); if (g == NULL) return; g->flags = FNG_GRP; g->host = strdup(grp); g->next = n->members; n->members = g; return; } static void _fsi_add_netgroup_member(file_netgroup_t *n, char *mem) { char **tokens; file_netgroup_member_t *m; int ntokens; if (n == NULL) return; m = (file_netgroup_member_t *)calloc(1, sizeof(file_netgroup_member_t)); if (m == NULL) return; tokens = _fsi_tokenize(mem + 1, ",)", 0, &ntokens); if (tokens == NULL) { free(m); return; } if ((ntokens > 0) && (tokens[0][0] != '\0')) m->host = strdup(tokens[0]); if ((ntokens > 1) && (tokens[1][0] != '\0')) m->user = strdup(tokens[1]); if ((ntokens > 2) && (tokens[2][0] != '\0')) m->domain = strdup(tokens[2]); free(tokens); m->flags = FNG_MEM; m->next = n->members; n->members = m; } static file_netgroup_t * _fsi_process_netgroup_line(file_netgroup_t **pass1, char *line) { file_netgroup_t *n; char **tokens; int i, ntokens = 0; tokens = _fsi_tokenize(line, " ", 0, &ntokens); if (tokens == NULL) return NULL; if (tokens[0] == NULL) { free(tokens); return NULL; } n = _fsi_find_netgroup(pass1, tokens[0], 1); for (i = 1; tokens[i] != NULL; i++) { if (tokens[i][0] == '(') _fsi_add_netgroup_member(n, tokens[i]); else if (tokens[i][0] != '\0') _fsi_add_netgroup_group(n, tokens[i]); } free(tokens); return n; } static void _fsi_flatten_netgroup(file_netgroup_t *pass1, file_netgroup_t **top, file_netgroup_t *n, file_netgroup_member_t *m) { if (n == NULL) return; if (n->flags == 1) return; n->flags = 1; if (*top == NULL) { *top = (file_netgroup_t *)calloc(1, sizeof(file_netgroup_t)); if (*top == NULL) return; (*top)->name = strdup(n->name); if ((*top)->name == NULL) { free(*top); *top = NULL; return; } } while (m!= NULL) { if (m->flags & FNG_MEM) { file_netgroup_member_t *x = (file_netgroup_member_t *)calloc(1, sizeof(file_netgroup_member_t)); if (x == NULL) return; x->flags = FNG_MEM; if (m->host != NULL) x->host = strdup(m->host); if (m->user != NULL) x->user = strdup(m->user); if (m->domain != NULL) x->domain = strdup(m->domain); x->next = (*top)->members; (*top)->members = x; } else { file_netgroup_t *g = _fsi_find_netgroup(&pass1, m->host, 0); if (g == NULL) continue; _fsi_flatten_netgroup(pass1, top, g, g->members); } m = m->next; } } static void _fsi_check_netgroup_cache(si_mod_t *si) { file_netgroup_t *p1, *n, *x, *a; char *line; FILE *f; file_si_private_t *pp; if (si == NULL) return; pp = (file_si_private_t *)si->private; if (pp == NULL) return; pthread_mutex_lock(&file_mutex); if (_fsi_validate(si, CATEGORY_NETGROUP, pp->netgroup_validation_a, pp->netgroup_validation_b)) { pthread_mutex_unlock(&file_mutex); return; } n = pp->file_netgroup_cache; while (n != NULL) { x = n; n = n->next; _fsi_free_file_netgroup(x); } pp->file_netgroup_cache = NULL; f = fopen(_PATH_NETGROUP, "r"); if (f == NULL) { pthread_mutex_unlock(&file_mutex); return; } _fsi_get_validation(si, VALIDATION_NETGROUP, _PATH_NETGROUP, f, &(pp->netgroup_validation_a), &(pp->netgroup_validation_b)); p1 = NULL; line = _fsi_read_netgroup_line(f); while (line != NULL) { n = _fsi_process_netgroup_line(&p1, line); free(line); line = _fsi_read_netgroup_line(f); } fclose(f); for (n = p1; n != NULL; n = n->next) { a = NULL; _fsi_flatten_netgroup(p1, &a, n, n->members); for (x = p1; x != NULL; x = x->next) x->flags = 0; if (a != NULL) { a->next = pp->file_netgroup_cache; pp->file_netgroup_cache = a; } } n = p1; while (n != NULL) { x = n; n = n->next; _fsi_free_file_netgroup(x); } pthread_mutex_unlock(&file_mutex); } /* USERS */ static si_item_t * _fsi_parse_user(si_mod_t *si, const char *name, uid_t uid, int which, char *data, int format, uint64_t va, uint64_t vb) { char **tokens; int ntokens, match; time_t change, expire; si_item_t *item; uid_t xuid; if (data == NULL) return NULL; ntokens = 0; tokens = _fsi_tokenize(data, ":", 1, &ntokens); if (((format == 0) && (ntokens != 10)) || ((format == 1) && (ntokens != 7))) { free(tokens); return NULL; } xuid = atoi(tokens[2]); match = 0; /* XXX MATCH GECOS? XXX*/ if (which == SEL_ALL) match = 1; else if ((which == SEL_NAME) && (string_equal(name, tokens[0]))) match = 1; else if ((which == SEL_NUMBER) && (uid == xuid)) match = 1; if (match == 0) { free(tokens); return NULL; } if (format == 0) { /* master.passwd: name[0] passwd[1] uid[2] gid[3] class[4] change[5] expire[6] gecos[7] dir[8] shell[9] */ /* struct pwd: name[0] passwd[1] uid[2] gid[3] change[5] class[4] gecos[7] dir[8] shell[9] expire[6] */ change = atoi(tokens[5]); expire = atoi(tokens[6]); item = (si_item_t *)LI_ils_create("L4488ss44LssssL", (unsigned long)si, CATEGORY_USER, 1, va, vb, tokens[0], tokens[1], xuid, atoi(tokens[3]), change, tokens[4], tokens[7], tokens[8], tokens[9], expire); } else { /* passwd: name[0] passwd[1] uid[2] gid[3] gecos[4] dir[5] shell[6] */ /* struct pwd: name[0] passwd[1] uid[2] gid[3] change[-] class[-] gecos[4] dir[5] shell[6] expire[-] */ item = (si_item_t *)LI_ils_create("L4488ss44LssssL", (unsigned long)si, CATEGORY_USER, 1, va, vb, tokens[0], tokens[1], xuid, atoi(tokens[3]), 0, "", tokens[4], tokens[5], tokens[6], 0); } free(tokens); return item; } static void * _fsi_get_user(si_mod_t *si, const char *name, uid_t uid, int which) { char *line; si_item_t *item; int fmt; FILE *f; si_list_t *all; uint64_t va, vb; if ((which == SEL_NAME) && (name == NULL)) return NULL; all = NULL; f = NULL; fmt = 0; va = 0; vb = 0; if (geteuid() == 0) { f = fopen(_PATH_MASTERPASSWD, "r"); _fsi_get_validation(si, VALIDATION_MASTER_PASSWD, _PATH_MASTERPASSWD, f, &va, &vb); } else { f = fopen(_PATH_PASSWD, "r"); _fsi_get_validation(si, VALIDATION_PASSWD, _PATH_PASSWD, f, &va, &vb); fmt = 1; } if (f == NULL) return NULL; forever { line = _fsi_get_line(f); if (line == NULL) break; if (line[0] == '#') { free(line); line = NULL; continue; } item = _fsi_parse_user(si, name, uid, which, line, fmt, va, vb); free(line); line = NULL; if (item == NULL) continue; if (which == SEL_ALL) { all = si_list_add(all, item); si_item_release(item); continue; } fclose(f); return item; } fclose(f); return all; } /* GROUPS */ static si_item_t * _fsi_parse_group(si_mod_t *si, const char *name, gid_t gid, int which, char *data, uint64_t va, uint64_t vb) { char **tokens, **members; int ntokens, match; si_item_t *item; gid_t xgid; if (data == NULL) return NULL; ntokens = 0; tokens = _fsi_tokenize(data, ":", 1, &ntokens); if (ntokens != 4) { free(tokens); return NULL; } xgid = atoi(tokens[2]); match = 0; if (which == SEL_ALL) match = 1; else if ((which == SEL_NAME) && (string_equal(name, tokens[0]))) match = 1; else if ((which == SEL_NUMBER) && (gid == xgid)) match = 1; if (match == 0) { free(tokens); return NULL; } ntokens = 0; members = _fsi_tokenize(tokens[3], ",", 1, &ntokens); item = (si_item_t *)LI_ils_create("L4488ss4*", (unsigned long)si, CATEGORY_GROUP, 1, va, vb, tokens[0], tokens[1], xgid, members); free(tokens); free(members); return item; } static void * _fsi_get_group(si_mod_t *si, const char *name, gid_t gid, int which) { char *line; si_item_t *item; FILE *f; si_list_t *all; uint64_t va, vb; if ((which == SEL_NAME) && (name == NULL)) return NULL; all = NULL; f = NULL; f = fopen(_PATH_GROUP, "r"); if (f == NULL) return NULL; _fsi_get_validation(si, VALIDATION_GROUP, _PATH_GROUP, f, &va, &vb); forever { line = _fsi_get_line(f); if (line == NULL) break; if (line[0] == '#') { free(line); line = NULL; continue; } item = _fsi_parse_group(si, name, gid, which, line, va, vb); free(line); line = NULL; if (item == NULL) continue; if (which == SEL_ALL) { all = si_list_add(all, item); si_item_release(item); continue; } fclose(f); return item; } fclose(f); return all; } static void * _fsi_get_grouplist(si_mod_t *si, const char *user) { char **tokens, **members; int ntokens, i, match, gidcount; char *line; si_item_t *item; FILE *f; uint64_t va, vb; gid_t gid, basegid; gid_t *gidlist; struct passwd *pw; if (user == NULL) return NULL; gidlist = NULL; gidcount = 0; f = NULL; basegid = -1; item = si->vtable->sim_user_byname(si, user); if (item != NULL) { pw = (struct passwd *)((uintptr_t)item + sizeof(si_item_t)); basegid = pw->pw_gid; si_item_release(item); item = NULL; } f = fopen(_PATH_GROUP, "r"); if (f == NULL) return NULL; _fsi_get_validation(si, VALIDATION_GROUP, _PATH_GROUP, f, &va, &vb); forever { line = _fsi_get_line(f); if (line == NULL) break; if (line[0] == '#') { free(line); line = NULL; continue; } ntokens = 0; tokens = _fsi_tokenize(line, ":", 1, &ntokens); if (ntokens != 4) { free(tokens); continue; } ntokens = 0; members = _fsi_tokenize(tokens[3], ",", 1, &ntokens); match = 0; gid = -2; for (i = 0; i < ntokens; i++) { if (string_equal(user, members[i])) { gid = atoi(tokens[2]); match = 1; break; } } free(tokens); free(members); free(line); line = NULL; if (match == 1) { gidlist = (gid_t *) reallocf(gidlist, (gidcount + 1) * sizeof(gid_t)); if (gidlist == NULL) { gidcount = 0; break; } gidlist[gidcount++] = gid; } } fclose(f); if (gidcount != 0) { item = (si_item_t *)LI_ils_create("L4488s4@", (unsigned long)si, CATEGORY_GROUPLIST, 1, va, vb, user, gidcount, gidcount * sizeof(gid_t), gidlist); } free(gidlist); return item; } /* ALIASES */ static si_item_t * _fsi_parse_alias(si_mod_t *si, const char *name, int which, char *data, uint64_t va, uint64_t vb) { char **tokens, **members; int ntokens, match; si_item_t *item; if (data == NULL) return NULL; ntokens = 0; tokens = _fsi_tokenize(data, ":", 1, &ntokens); if (ntokens < 2) { free(tokens); return NULL; } match = 0; if (which == SEL_ALL) match = 1; else if (string_equal(name, tokens[0])) match = 1; if (match == 0) { free(tokens); return NULL; } ntokens = 0; members = _fsi_tokenize(tokens[1], ",", 1, &ntokens); item = (si_item_t *)LI_ils_create("L4488s4*4", (unsigned long)si, CATEGORY_ALIAS, 1, va, vb, tokens[0], ntokens, members, 1); free(tokens); free(members); return item; } static void * _fsi_get_alias(si_mod_t *si, const char *name, int which) { char *line; si_item_t *item; FILE *f; si_list_t *all; uint64_t va, vb; if ((which == SEL_NAME) && (name == NULL)) return NULL; all = NULL; f = NULL; f = fopen(_PATH_ALIASES, "r"); if (f == NULL) return NULL; _fsi_get_validation(si, VALIDATION_ALIASES, _PATH_ALIASES, f, &va, &vb); forever { line = _fsi_get_line(f); if (line == NULL) break; if (line[0] == '#') { free(line); line = NULL; continue; } item = _fsi_parse_alias(si, name, which, line, va, vb); free(line); line = NULL; if (item == NULL) continue; if (which == SEL_ALL) { all = si_list_add(all, item); si_item_release(item); continue; } fclose(f); return item; } fclose(f); return all; } /* ETHERS */ static si_item_t * _fsi_parse_ether(si_mod_t *si, const char *name, int which, char *data, uint64_t va, uint64_t vb) { char **tokens; char *cmac; int ntokens, match; si_item_t *item; if (data == NULL) return NULL; ntokens = 0; tokens = _fsi_tokenize(data, " \t", 1, &ntokens); if (ntokens != 2) { free(tokens); return NULL; } cmac = si_standardize_mac_address(tokens[0]); if (cmac == NULL) { free(tokens); return NULL; } match = 0; if (which == SEL_ALL) match = 1; else if ((which == SEL_NAME) && (string_equal(name, tokens[1]))) match = 1; else if ((which == SEL_NUMBER) && (string_equal(name, cmac))) match = 1; if (match == 0) { free(tokens); free(cmac); return NULL; } item = (si_item_t *)LI_ils_create("L4488ss", (unsigned long)si, CATEGORY_MAC, 1, va, vb, tokens[1], cmac); free(tokens); free(cmac); return item; } static void * _fsi_get_ether(si_mod_t *si, const char *name, int which) { char *line, *cmac; si_item_t *item; FILE *f; si_list_t *all; uint64_t va, vb; if ((which != SEL_ALL) && (name == NULL)) return NULL; cmac = NULL; if (which == SEL_NUMBER) { cmac = si_standardize_mac_address(name); if (cmac == NULL) return NULL; } all = NULL; f = NULL; f = fopen(_PATH_ETHERS, "r"); if (f == NULL) return NULL; _fsi_get_validation(si, VALIDATION_ETHERS, _PATH_ETHERS, f, &va, &vb); forever { line = _fsi_get_line(f); if (line == NULL) break; if (line[0] == '#') { free(line); line = NULL; continue; } item = NULL; if (which == SEL_NUMBER) item = _fsi_parse_ether(si, cmac, which, line, va, vb); else item = _fsi_parse_ether(si, name, which, line, va, vb); free(line); line = NULL; if (item == NULL) continue; if (which == SEL_ALL) { all = si_list_add(all, item); si_item_release(item); continue; } fclose(f); return item; } fclose(f); return all; } /* HOSTS */ static si_item_t * _fsi_parse_host(si_mod_t *si, const char *name, const void *addr, int af, int which, char *data, uint64_t va, uint64_t vb) { char **tokens, **h_aliases, *null_alias; int i, ntokens, match, h_addrtype, h_length; struct in_addr a4; struct in6_addr a6; si_item_t *item; char *h_addr_list[2]; char h_addr_4[4], h_addr_6[16]; if (data == NULL) return NULL; null_alias = NULL; ntokens = 0; tokens = _fsi_tokenize(data, " ", 0, &ntokens); if (ntokens < 2) { free(tokens); return NULL; } h_addr_list[1] = NULL; h_addrtype = AF_UNSPEC; if (inet_pton(AF_INET, tokens[0], &a4) == 1) { h_addrtype = AF_INET; h_length = sizeof(struct in_addr); memcpy(h_addr_4, &a4, 4); h_addr_list[0] = h_addr_4; } else if (inet_pton(AF_INET6, tokens[0], &a6) == 1) { h_addrtype = AF_INET6; h_length = sizeof(struct in6_addr); memcpy(h_addr_6, &a6, 16); h_addr_list[0] = h_addr_6; } if (h_addrtype == AF_UNSPEC) { free(tokens); return NULL; } h_aliases = NULL; if (ntokens > 2) h_aliases = &(tokens[2]); match = 0; if (which == SEL_ALL) match = 1; else { if (h_addrtype == af) { if (which == SEL_NAME) { if (string_equal(name, tokens[1])) match = 1; else if (h_aliases != NULL) { for (i = 0; (h_aliases[i] != NULL) && (match == 0); i++) if (string_equal(name, h_aliases[i])) match = 1; } } else if (which == SEL_NUMBER) { if (memcmp(addr, h_addr_list[0], h_length) == 0) match = 1; } } } if (match == 0) { free(tokens); return NULL; } item = NULL; if (h_aliases == NULL) h_aliases = &null_alias; if (h_addrtype == AF_INET) { item = (si_item_t *)LI_ils_create("L4488s*44a", (unsigned long)si, CATEGORY_HOST_IPV4, 1, va, vb, tokens[1], h_aliases, h_addrtype, h_length, h_addr_list); } else { item = (si_item_t *)LI_ils_create("L4488s*44c", (unsigned long)si, CATEGORY_HOST_IPV6, 1, va, vb, tokens[1], h_aliases, h_addrtype, h_length, h_addr_list); } free(tokens); return item; } static void * _fsi_get_host(si_mod_t *si, const char *name, const void *addr, int af, int which, uint32_t *err) { char *line; si_item_t *item; FILE *f; si_list_t *all; uint64_t va, vb; if ((which == SEL_NAME) && (name == NULL)) { if (err != NULL) *err = NO_RECOVERY; return NULL; } if ((which == SEL_NUMBER) && (addr == NULL)) { if (err != NULL) *err = NO_RECOVERY; return NULL; } f = fopen(_PATH_HOSTS, "r"); if (f == NULL) { if (err != NULL) *err = NO_RECOVERY; return NULL; } _fsi_get_validation(si, VALIDATION_HOSTS, _PATH_HOSTS, f, &va, &vb); all = NULL; forever { line = _fsi_get_line(f); if (line == NULL) break; if (line[0] == '#') { free(line); line = NULL; continue; } item = _fsi_parse_host(si, name, addr, af, which, line, va, vb); free(line); line = NULL; if (item == NULL) continue; if (which == SEL_ALL) { all = si_list_add(all, item); si_item_release(item); continue; } fclose(f); return item; } fclose(f); return all; } /* SERVICE */ static si_item_t * _fsi_parse_service(si_mod_t *si, const char *name, const char *proto, int port, int which, char *data, uint64_t va, uint64_t vb) { char **tokens, **s_aliases, *xproto; int i, ntokens, match; si_item_t *item; int xport; if (data == NULL) return NULL; port = ntohs(port); ntokens = 0; tokens = _fsi_tokenize(data, " ", 0, &ntokens); if (ntokens < 2) { free(tokens); return NULL; } s_aliases = NULL; if (ntokens > 2) s_aliases = &(tokens[2]); xport = atoi(tokens[1]); xproto = strchr(tokens[1], '/'); if (xproto == NULL) { free(tokens); return NULL; } *xproto++ = '\0'; if ((proto != NULL) && (string_not_equal(proto, xproto))) { free(tokens); return NULL; } match = 0; if (which == SEL_ALL) match = 1; else if (which == SEL_NAME) { if (string_equal(name, tokens[0])) match = 1; else if (s_aliases != NULL) { for (i = 0; (s_aliases[i] != NULL) && (match == 0); i++) if (string_equal(name, s_aliases[i])) match = 1; } } else if ((which == SEL_NUMBER) && (port == xport)) match = 1; if (match == 0) { free(tokens); return NULL; } /* strange but correct */ xport = htons(xport); item = (si_item_t *)LI_ils_create("L4488s*4s", (unsigned long)si, CATEGORY_SERVICE, 1, va, vb, tokens[0], s_aliases, xport, xproto); free(tokens); return item; } static void * _fsi_get_service(si_mod_t *si, const char *name, const char *proto, int port, int which) { char *p, *line; si_item_t *item; FILE *f; si_list_t *all; uint64_t va, vb; if ((which == SEL_NAME) && (name == NULL)) return NULL; if ((which == SEL_NUMBER) && (port == 0)) return NULL; f = fopen(_PATH_SERVICES, "r"); if (f == NULL) return NULL; _fsi_get_validation(si, VALIDATION_SERVICES, _PATH_SERVICES, f, &va, &vb); all = NULL; forever { line = _fsi_get_line(f); if (line == NULL) break; if (line[0] == '#') { free(line); line = NULL; continue; } p = strchr(line, '#'); if (p != NULL) *p = '\0'; item = _fsi_parse_service(si, name, proto, port, which, line, va, vb); free(line); line = NULL; if (item == NULL) continue; if (which == SEL_ALL) { all = si_list_add(all, item); si_item_release(item); continue; } fclose(f); return item; } fclose(f); return all; } /* * Generic name/number/aliases lookup * Works for protocols, networks, and rpcs */ static si_item_t * _fsi_parse_name_num_aliases(si_mod_t *si, const char *name, int num, int which, char *data, uint64_t va, uint64_t vb, int cat) { char **tokens, **aliases; int i, ntokens, match, xnum; si_item_t *item; if (data == NULL) return NULL; ntokens = 0; tokens = _fsi_tokenize(data, " ", 0, &ntokens); if (ntokens < 2) { free(tokens); return NULL; } xnum = atoi(tokens[1]); aliases = NULL; if (ntokens > 2) aliases = &(tokens[2]); match = 0; if (which == SEL_ALL) match = 1; else if (which == SEL_NAME) { if (string_equal(name, tokens[0])) match = 1; else if (aliases != NULL) { for (i = 0; (aliases[i] != NULL) && (match == 0); i++) if (string_equal(name, aliases[i])) match = 1; } } else if ((which == SEL_NUMBER) && (num == xnum)) match = 1; if (match == 0) { free(tokens); return NULL; } switch (cat) { case CATEGORY_NETWORK: // struct netent item = (si_item_t *)LI_ils_create("L4488s*44", (unsigned long)si, cat, 1, va, vb, tokens[0], aliases, AF_INET, xnum); break; case CATEGORY_PROTOCOL: case CATEGORY_RPC: // struct protoent // struct rpcent item = (si_item_t *)LI_ils_create("L4488s*4", (unsigned long)si, cat, 1, va, vb, tokens[0], aliases, xnum); break; default: abort(); } free(tokens); return item; } static void * _fsi_get_name_number_aliases(si_mod_t *si, const char *name, int num, int which, int cat) { char *p, *line; si_item_t *item; FILE *f; si_list_t *all; uint64_t va, vb; const char *path; int vtype; switch (cat) { case CATEGORY_NETWORK: vtype = VALIDATION_NETWORKS; path = _PATH_NETWORKS; break; case CATEGORY_PROTOCOL: vtype = VALIDATION_PROTOCOLS; path = _PATH_PROTOCOLS; break; case CATEGORY_RPC: vtype = VALIDATION_RPC; path = _PATH_RPCS; break; default: abort(); } f = fopen(path, "r"); if (f == NULL) return NULL; _fsi_get_validation(si, vtype, path, f, &va, &vb); all = NULL; forever { line = _fsi_get_line(f); if (line == NULL) break; if (line[0] == '#') { free(line); line = NULL; continue; } p = strchr(line, '#'); if (p != NULL) *p = '\0'; item = _fsi_parse_name_num_aliases(si, name, num, which, line, va, vb, cat); free(line); line = NULL; if (item == NULL) continue; if (which == SEL_ALL) { all = si_list_add(all, item); si_item_release(item); continue; } fclose(f); return item; } fclose(f); return all; } /* MOUNT */ static si_item_t * _fsi_parse_fs(si_mod_t *si, const char *name, int which, char *data, uint64_t va, uint64_t vb) { char **tokens, *tmp, **opts, *fstype; int ntokens, match, i, freq, passno; si_item_t *item; if (data == NULL) return NULL; freq = 0; passno = 0; fstype = NULL; ntokens = 0; tokens = _fsi_tokenize(data, " ", 0, &ntokens); if ((ntokens < 4) || (ntokens > 6)) { free(tokens); return NULL; } if (ntokens >= 5) freq = atoi(tokens[4]); if (ntokens == 6) passno = atoi(tokens[5]); tmp = strdup(tokens[3]); if (tmp == NULL) { free(tokens); return NULL; } ntokens = 0; opts = _fsi_tokenize(tmp, ",", 0, &ntokens); if (opts == NULL) { free(tokens); free(tmp); return NULL; } for (i = 0; i < ntokens; i++) { if ((string_equal(opts[i], "rw")) || (string_equal(opts[i], "ro")) || (string_equal(opts[i], "sw")) || (string_equal(opts[i], "xx"))) { fstype = opts[i]; break; } } match = 0; if (which == SEL_ALL) match = 1; else if ((which == SEL_NAME) && (string_equal(name, tokens[0]))) match = 1; else if ((which == SEL_NUMBER) && (string_equal(name, tokens[1]))) match = 1; if (match == 0) { free(tokens); return NULL; } item = (si_item_t *)LI_ils_create("L4488sssss44", (unsigned long)si, CATEGORY_FS, 1, va, vb, tokens[0], tokens[1], tokens[2], tokens[3], (fstype == NULL) ? "rw" : fstype, freq, passno); free(tokens); free(opts); free(tmp); return item; } static char * _fsi_get_device_path(dev_t target_dev) { char *result; char dev[PATH_MAX]; char *name; char namebuf[PATH_MAX]; result = NULL; strlcpy(dev, _PATH_DEV, sizeof(dev)); /* The root device in fstab should always be a block special device */ name = devname_r(target_dev, S_IFBLK, namebuf, sizeof(namebuf)); if (name == NULL) { DIR *dirp; struct stat devst; struct dirent *ent, entbuf; /* No _PATH_DEVDB. We have to search for it the slow way */ dirp = opendir(_PATH_DEV); if (dirp == NULL) return NULL; while (readdir_r(dirp, &entbuf, &ent) == 0 && ent != NULL) { /* Look for a block special device */ if (ent->d_type == DT_BLK) { strlcat(dev, ent->d_name, sizeof(dev)); if (stat(dev, &devst) == 0) { if (devst.st_rdev == target_dev) { result = strdup(dev); break; } } } /* reset dev to _PATH_DEV and try again */ dev[sizeof(_PATH_DEV) - 1] = '\0'; } if (dirp) closedir(dirp); } else { /* We found the _PATH_DEVDB entry */ strlcat(dev, name, sizeof(dev)); result = strdup(dev); } return result; } static si_item_t * _fsi_fs_root(si_mod_t *si) { dispatch_once(&rootfs_once, ^{ struct stat rootstat; struct statfs rootfsinfo; char *root_spec; const char *root_path = "/"; if (stat(root_path, &rootstat) < 0) return; if (statfs(root_path, &rootfsinfo) < 0) return; // Check to make sure we're not looking at a synthetic root: if (string_equal(rootfsinfo.f_fstypename, "synthfs")) { root_path = "/root"; if (stat(root_path, &rootstat) < 0) return; if (statfs(root_path, &rootfsinfo) < 0) return; } root_spec = _fsi_get_device_path(rootstat.st_dev); rootfs = (si_item_t *)LI_ils_create("L4488sssss44", (unsigned long)si, CATEGORY_FS, 1, 0LL, 0LL, root_spec, root_path, rootfsinfo.f_fstypename, FSTAB_RW, FSTAB_RW, 0, 1); free(root_spec); }); return si_item_retain(rootfs); } static void * _fsi_get_fs(si_mod_t *si, const char *name, int which) { char *line; si_item_t *item; FILE *f; si_list_t *all; uint64_t va, vb; int synthesize_root; struct fstab *rfs; if ((which != SEL_ALL) && (name == NULL)) return NULL; all = NULL; f = NULL; #ifdef SYNTH_ROOTFS synthesize_root = 1; #else synthesize_root = 0; #endif f = fopen(_PATH_FSTAB, "r"); if ((f == NULL) || (synthesize_root == 1)) { item = _fsi_fs_root(si); rfs = NULL; if (item != NULL) rfs = (struct fstab *)((uintptr_t)item + sizeof(si_item_t)); switch (which) { case SEL_NAME: { if ((rfs != NULL) && (string_equal(name, rfs->fs_spec))) { if (f != NULL) fclose(f); return item; } break; } case SEL_NUMBER: { if ((rfs != NULL) && (string_equal(name, rfs->fs_file))) { if (f != NULL) fclose(f); return item; } break; } case SEL_ALL: { all = si_list_add(all, item); si_item_release(item); break; } } } if (f == NULL) return all; _fsi_get_validation(si, VALIDATION_FSTAB, _PATH_FSTAB, f, &va, &vb); forever { line = _fsi_get_line(f); if (line == NULL) break; if (line[0] == '#') { free(line); line = NULL; continue; } item = _fsi_parse_fs(si, name, which, line, va, vb); free(line); line = NULL; if (item == NULL) continue; if (which == SEL_ALL) { all = si_list_add(all, item); si_item_release(item); continue; } fclose(f); return item; } fclose(f); return all; } static int file_is_valid(si_mod_t *si, si_item_t *item) { si_mod_t *src; if (si == NULL) return 0; if (item == NULL) return 0; if (si->name == NULL) return 0; if (item->src == NULL) return 0; src = (si_mod_t *)item->src; if (src->name == NULL) return 0; if (string_not_equal(si->name, src->name)) return 0; if (item == rootfs) return 1; return _fsi_validate(si, item->type, item->validation_a, item->validation_b); } static si_item_t * file_user_byname(si_mod_t *si, const char *name) { return _fsi_get_user(si, name, 0, SEL_NAME); } static si_item_t * file_user_byuid(si_mod_t *si, uid_t uid) { return _fsi_get_user(si, NULL, uid, SEL_NUMBER); } static si_list_t * file_user_all(si_mod_t *si) { return _fsi_get_user(si, NULL, 0, SEL_ALL); } static si_item_t * file_group_byname(si_mod_t *si, const char *name) { return _fsi_get_group(si, name, 0, SEL_NAME); } static si_item_t * file_group_bygid(si_mod_t *si, gid_t gid) { return _fsi_get_group(si, NULL, gid, SEL_NUMBER); } static si_list_t * file_group_all(si_mod_t *si) { return _fsi_get_group(si, NULL, 0, SEL_ALL); } static si_item_t * file_grouplist(si_mod_t *si, const char *name, __unused uint32_t ignored) { return _fsi_get_grouplist(si, name); } static si_list_t * file_netgroup_byname(si_mod_t *si, const char *name) { si_list_t *list = NULL; si_item_t *item; uint64_t va=0, vb=0; file_netgroup_t *n; file_si_private_t *pp; if (name == NULL) return NULL; pp = (file_si_private_t *)si->private; if (pp == NULL) return NULL; _fsi_check_netgroup_cache(si); pthread_mutex_lock(&file_mutex); n = _fsi_find_netgroup(&(pp->file_netgroup_cache), name, 0); if (n != NULL) { file_netgroup_member_t *m = n->members; while (m != NULL) { item = (si_item_t *)LI_ils_create("L4488sss", (unsigned long)si, CATEGORY_NETGROUP, 1, va, vb, m->host, m->user, m->domain); list = si_list_add(list, item); m = m->next; } } pthread_mutex_unlock(&file_mutex); return list; } static int file_in_netgroup(si_mod_t *si, const char *group, const char *host, const char *user, const char *domain) { file_netgroup_t *n; file_netgroup_member_t *m; file_si_private_t *pp; if (group == NULL) return 0; pp = (file_si_private_t *)si->private; if (pp == NULL) return 0; _fsi_check_netgroup_cache(si); pthread_mutex_lock(&file_mutex); n = _fsi_find_netgroup(&(pp->file_netgroup_cache), group, 0); if (n == NULL) { pthread_mutex_unlock(&file_mutex); return 0; } m = n->members; while (m != NULL) { file_netgroup_member_t *x = m; m = m->next; if (host != NULL) { if (x->host == NULL) continue; if (strcmp(host, x->host)) continue; } if (user != NULL) { if (x->user == NULL) continue; if (strcmp(user, x->user)) continue; } if (domain != NULL) { if (x->domain == NULL) continue; if (strcmp(domain, x->domain)) continue; } pthread_mutex_unlock(&file_mutex); return 1; } pthread_mutex_unlock(&file_mutex); return 0; } static si_item_t * file_host_byname(si_mod_t *si, const char *name, int af, const char *ignored, uint32_t *err) { si_item_t *item; if (err != NULL) *err = SI_STATUS_NO_ERROR; item = _fsi_get_host(si, name, NULL, af, SEL_NAME, err); if ((item == NULL) && (err != NULL) && (*err == 0)) *err = SI_STATUS_H_ERRNO_HOST_NOT_FOUND; return item; } static si_item_t * file_host_byaddr(si_mod_t *si, const void *addr, int af, const char *ignored, uint32_t *err) { si_item_t *item; if (err != NULL) *err = SI_STATUS_NO_ERROR; item = _fsi_get_host(si, NULL, addr, af, SEL_NUMBER, err); if ((item == NULL) && (err != NULL) && (*err == 0)) *err = SI_STATUS_H_ERRNO_HOST_NOT_FOUND; return item; } static si_list_t * file_host_all(si_mod_t *si) { return _fsi_get_host(si, NULL, NULL, 0, SEL_ALL, NULL); } static si_item_t * file_network_byname(si_mod_t *si, const char *name) { if (name == NULL) return NULL; return _fsi_get_name_number_aliases(si, name, 0, SEL_NAME, CATEGORY_NETWORK); } static si_item_t * file_network_byaddr(si_mod_t *si, uint32_t addr) { return _fsi_get_name_number_aliases(si, NULL, (int)addr, SEL_NUMBER, CATEGORY_NETWORK); } static si_list_t * file_network_all(si_mod_t *si) { return _fsi_get_name_number_aliases(si, NULL, 0, SEL_ALL, CATEGORY_NETWORK); } static si_item_t * file_service_byname(si_mod_t *si, const char *name, const char *proto) { return _fsi_get_service(si, name, proto, 0, SEL_NAME); } static si_item_t * file_service_byport(si_mod_t *si, int port, const char *proto) { return _fsi_get_service(si, NULL, proto, port, SEL_NUMBER); } static si_list_t * file_service_all(si_mod_t *si) { return _fsi_get_service(si, NULL, NULL, 0, SEL_ALL); } static si_item_t * file_protocol_byname(si_mod_t *si, const char *name) { if (name == NULL) return NULL; return _fsi_get_name_number_aliases(si, name, 0, SEL_NAME, CATEGORY_PROTOCOL); } static si_item_t * file_protocol_bynumber(si_mod_t *si, int number) { return _fsi_get_name_number_aliases(si, NULL, number, SEL_NUMBER, CATEGORY_PROTOCOL); } static si_list_t * file_protocol_all(si_mod_t *si) { return _fsi_get_name_number_aliases(si, NULL, 0, SEL_ALL, CATEGORY_PROTOCOL); } static si_item_t * file_rpc_byname(si_mod_t *si, const char *name) { if (name == NULL) return NULL; return _fsi_get_name_number_aliases(si, name, 0, SEL_NAME, CATEGORY_RPC); } static si_item_t * file_rpc_bynumber(si_mod_t *si, int number) { return _fsi_get_name_number_aliases(si, NULL, number, SEL_NUMBER, CATEGORY_RPC); } static si_list_t * file_rpc_all(si_mod_t *si) { return _fsi_get_name_number_aliases(si, NULL, 0, SEL_ALL, CATEGORY_RPC); } static si_item_t * file_fs_byspec(si_mod_t *si, const char *spec) { return _fsi_get_fs(si, spec, SEL_NAME); } static si_item_t * file_fs_byfile(si_mod_t *si, const char *file) { return _fsi_get_fs(si, file, SEL_NUMBER); } static si_list_t * file_fs_all(si_mod_t *si) { return _fsi_get_fs(si, NULL, SEL_ALL); } static si_item_t * file_alias_byname(si_mod_t *si, const char *name) { return _fsi_get_alias(si, name, SEL_NAME); } static si_list_t * file_alias_all(si_mod_t *si) { return _fsi_get_alias(si, NULL, SEL_ALL); } static si_item_t * file_mac_byname(si_mod_t *si, const char *name) { return _fsi_get_ether(si, name, SEL_NAME); } static si_item_t * file_mac_bymac(si_mod_t *si, const char *mac) { return _fsi_get_ether(si, mac, SEL_NUMBER); } static si_list_t * file_mac_all(si_mod_t *si) { return _fsi_get_ether(si, NULL, SEL_ALL); } static si_list_t * file_addrinfo(si_mod_t *si, const void *node, const void *serv, uint32_t family, uint32_t socktype, uint32_t proto, uint32_t flags, const char *interface, uint32_t *err) { if (err != NULL) *err = SI_STATUS_NO_ERROR; return _gai_simple(si, node, serv, family, socktype, proto, flags, interface, err); } si_mod_t * si_module_static_file(void) { static const struct si_mod_vtable_s file_vtable = { .sim_is_valid = &file_is_valid, .sim_user_byname = &file_user_byname, .sim_user_byuid = &file_user_byuid, .sim_user_byuuid = NULL, .sim_user_all = &file_user_all, .sim_group_byname = &file_group_byname, .sim_group_bygid = &file_group_bygid, .sim_group_byuuid = NULL, .sim_group_all = &file_group_all, .sim_grouplist = &file_grouplist, .sim_netgroup_byname = &file_netgroup_byname, .sim_in_netgroup = &file_in_netgroup, .sim_alias_byname = &file_alias_byname, .sim_alias_all = &file_alias_all, .sim_host_byname = &file_host_byname, .sim_host_byaddr = &file_host_byaddr, .sim_host_all = &file_host_all, .sim_network_byname = &file_network_byname, .sim_network_byaddr = &file_network_byaddr, .sim_network_all = &file_network_all, .sim_service_byname = &file_service_byname, .sim_service_byport = &file_service_byport, .sim_service_all = &file_service_all, .sim_protocol_byname = &file_protocol_byname, .sim_protocol_bynumber = &file_protocol_bynumber, .sim_protocol_all = &file_protocol_all, .sim_rpc_byname = &file_rpc_byname, .sim_rpc_bynumber = &file_rpc_bynumber, .sim_rpc_all = &file_rpc_all, .sim_fs_byspec = &file_fs_byspec, .sim_fs_byfile = &file_fs_byfile, .sim_fs_all = &file_fs_all, .sim_mac_byname = &file_mac_byname, .sim_mac_bymac = &file_mac_bymac, .sim_mac_all = &file_mac_all, .sim_wants_addrinfo = NULL, .sim_addrinfo = &file_addrinfo, /* no nameinfo support */ .sim_nameinfo = NULL, }; static si_mod_t si = { .vers = 1, .refcount = 1, .flags = SI_MOD_FLAG_STATIC, .private = NULL, .vtable = &file_vtable, }; static dispatch_once_t once; dispatch_once(&once, ^{ si.name = strdup("file"); file_si_private_t *pp = calloc(1, sizeof(file_si_private_t)); if (pp != NULL) { int i; for (i = 0; i < VALIDATION_COUNT; i++) pp->notify_token[i] = -1; /* hardwired for now, but we may want to make this configurable someday */ pp->validation_notify_mask = VALIDATION_MASK_HOSTS | VALIDATION_MASK_SERVICES | VALIDATION_MASK_PROTOCOLS; } si.private = pp; }); return (si_mod_t *)&si; }
{ "language": "C" }
/** ****************************************************************************** * @file stm32f4xx_hal_cortex.c * @author MCD Application Team * @brief CORTEX HAL module driver. * This file provides firmware functions to manage the following * functionalities of the CORTEX: * + Initialization and de-initialization functions * + Peripheral Control functions * @verbatim ============================================================================== ##### How to use this driver ##### ============================================================================== [..] *** How to configure Interrupts using CORTEX HAL driver *** =========================================================== [..] This section provides functions allowing to configure the NVIC interrupts (IRQ). The Cortex-M4 exceptions are managed by CMSIS functions. (#) Configure the NVIC Priority Grouping using HAL_NVIC_SetPriorityGrouping() function according to the following table. (#) Configure the priority of the selected IRQ Channels using HAL_NVIC_SetPriority(). (#) Enable the selected IRQ Channels using HAL_NVIC_EnableIRQ(). (#) please refer to programming manual for details in how to configure priority. -@- When the NVIC_PRIORITYGROUP_0 is selected, IRQ preemption is no more possible. The pending IRQ priority will be managed only by the sub priority. -@- IRQ priority order (sorted by highest to lowest priority): (+@) Lowest preemption priority (+@) Lowest sub priority (+@) Lowest hardware priority (IRQ number) [..] *** How to configure Systick using CORTEX HAL driver *** ======================================================== [..] Setup SysTick Timer for time base. (+) The HAL_SYSTICK_Config() function calls the SysTick_Config() function which is a CMSIS function that: (++) Configures the SysTick Reload register with value passed as function parameter. (++) Configures the SysTick IRQ priority to the lowest value 0x0F. (++) Resets the SysTick Counter register. (++) Configures the SysTick Counter clock source to be Core Clock Source (HCLK). (++) Enables the SysTick Interrupt. (++) Starts the SysTick Counter. (+) You can change the SysTick Clock source to be HCLK_Div8 by calling the macro __HAL_CORTEX_SYSTICKCLK_CONFIG(SYSTICK_CLKSOURCE_HCLK_DIV8) just after the HAL_SYSTICK_Config() function call. The __HAL_CORTEX_SYSTICKCLK_CONFIG() macro is defined inside the stm32f4xx_hal_cortex.h file. (+) You can change the SysTick IRQ priority by calling the HAL_NVIC_SetPriority(SysTick_IRQn,...) function just after the HAL_SYSTICK_Config() function call. The HAL_NVIC_SetPriority() call the NVIC_SetPriority() function which is a CMSIS function. (+) To adjust the SysTick time base, use the following formula: Reload Value = SysTick Counter Clock (Hz) x Desired Time base (s) (++) Reload Value is the parameter to be passed for HAL_SYSTICK_Config() function (++) Reload Value should not exceed 0xFFFFFF @endverbatim ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2017 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @defgroup CORTEX CORTEX * @brief CORTEX HAL module driver * @{ */ #ifdef HAL_CORTEX_MODULE_ENABLED /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @defgroup CORTEX_Exported_Functions CORTEX Exported Functions * @{ */ /** @defgroup CORTEX_Exported_Functions_Group1 Initialization and de-initialization functions * @brief Initialization and Configuration functions * @verbatim ============================================================================== ##### Initialization and de-initialization functions ##### ============================================================================== [..] This section provides the CORTEX HAL driver functions allowing to configure Interrupts Systick functionalities @endverbatim * @{ */ /** * @brief Sets the priority grouping field (preemption priority and subpriority) * using the required unlock sequence. * @param PriorityGroup The priority grouping bits length. * This parameter can be one of the following values: * @arg NVIC_PRIORITYGROUP_0: 0 bits for preemption priority * 4 bits for subpriority * @arg NVIC_PRIORITYGROUP_1: 1 bits for preemption priority * 3 bits for subpriority * @arg NVIC_PRIORITYGROUP_2: 2 bits for preemption priority * 2 bits for subpriority * @arg NVIC_PRIORITYGROUP_3: 3 bits for preemption priority * 1 bits for subpriority * @arg NVIC_PRIORITYGROUP_4: 4 bits for preemption priority * 0 bits for subpriority * @note When the NVIC_PriorityGroup_0 is selected, IRQ preemption is no more possible. * The pending IRQ priority will be managed only by the subpriority. * @retval None */ void HAL_NVIC_SetPriorityGrouping(uint32_t PriorityGroup) { /* Check the parameters */ assert_param(IS_NVIC_PRIORITY_GROUP(PriorityGroup)); /* Set the PRIGROUP[10:8] bits according to the PriorityGroup parameter value */ NVIC_SetPriorityGrouping(PriorityGroup); } /** * @brief Sets the priority of an interrupt. * @param IRQn External interrupt number. * This parameter can be an enumerator of IRQn_Type enumeration * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f4xxxx.h)) * @param PreemptPriority The preemption priority for the IRQn channel. * This parameter can be a value between 0 and 15 * A lower priority value indicates a higher priority * @param SubPriority the subpriority level for the IRQ channel. * This parameter can be a value between 0 and 15 * A lower priority value indicates a higher priority. * @retval None */ void HAL_NVIC_SetPriority(IRQn_Type IRQn, uint32_t PreemptPriority, uint32_t SubPriority) { uint32_t prioritygroup = 0x00U; /* Check the parameters */ assert_param(IS_NVIC_SUB_PRIORITY(SubPriority)); assert_param(IS_NVIC_PREEMPTION_PRIORITY(PreemptPriority)); prioritygroup = NVIC_GetPriorityGrouping(); NVIC_SetPriority(IRQn, NVIC_EncodePriority(prioritygroup, PreemptPriority, SubPriority)); } /** * @brief Enables a device specific interrupt in the NVIC interrupt controller. * @note To configure interrupts priority correctly, the NVIC_PriorityGroupConfig() * function should be called before. * @param IRQn External interrupt number. * This parameter can be an enumerator of IRQn_Type enumeration * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f4xxxx.h)) * @retval None */ void HAL_NVIC_EnableIRQ(IRQn_Type IRQn) { /* Check the parameters */ assert_param(IS_NVIC_DEVICE_IRQ(IRQn)); /* Enable interrupt */ NVIC_EnableIRQ(IRQn); } /** * @brief Disables a device specific interrupt in the NVIC interrupt controller. * @param IRQn External interrupt number. * This parameter can be an enumerator of IRQn_Type enumeration * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f4xxxx.h)) * @retval None */ void HAL_NVIC_DisableIRQ(IRQn_Type IRQn) { /* Check the parameters */ assert_param(IS_NVIC_DEVICE_IRQ(IRQn)); /* Disable interrupt */ NVIC_DisableIRQ(IRQn); } /** * @brief Initiates a system reset request to reset the MCU. * @retval None */ void HAL_NVIC_SystemReset(void) { /* System Reset */ NVIC_SystemReset(); } /** * @brief Initializes the System Timer and its interrupt, and starts the System Tick Timer. * Counter is in free running mode to generate periodic interrupts. * @param TicksNumb Specifies the ticks Number of ticks between two interrupts. * @retval status: - 0 Function succeeded. * - 1 Function failed. */ uint32_t HAL_SYSTICK_Config(uint32_t TicksNumb) { return SysTick_Config(TicksNumb); } /** * @} */ /** @defgroup CORTEX_Exported_Functions_Group2 Peripheral Control functions * @brief Cortex control functions * @verbatim ============================================================================== ##### Peripheral Control functions ##### ============================================================================== [..] This subsection provides a set of functions allowing to control the CORTEX (NVIC, SYSTICK, MPU) functionalities. @endverbatim * @{ */ #if (__MPU_PRESENT == 1U) /** * @brief Disables the MPU * @retval None */ void HAL_MPU_Disable(void) { /* Make sure outstanding transfers are done */ __DMB(); /* Disable fault exceptions */ SCB->SHCSR &= ~SCB_SHCSR_MEMFAULTENA_Msk; /* Disable the MPU and clear the control register*/ MPU->CTRL = 0U; } /** * @brief Enable the MPU. * @param MPU_Control Specifies the control mode of the MPU during hard fault, * NMI, FAULTMASK and privileged access to the default memory * This parameter can be one of the following values: * @arg MPU_HFNMI_PRIVDEF_NONE * @arg MPU_HARDFAULT_NMI * @arg MPU_PRIVILEGED_DEFAULT * @arg MPU_HFNMI_PRIVDEF * @retval None */ void HAL_MPU_Enable(uint32_t MPU_Control) { /* Enable the MPU */ MPU->CTRL = MPU_Control | MPU_CTRL_ENABLE_Msk; /* Enable fault exceptions */ SCB->SHCSR |= SCB_SHCSR_MEMFAULTENA_Msk; /* Ensure MPU setting take effects */ __DSB(); __ISB(); } /** * @brief Initializes and configures the Region and the memory to be protected. * @param MPU_Init Pointer to a MPU_Region_InitTypeDef structure that contains * the initialization and configuration information. * @retval None */ void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init) { /* Check the parameters */ assert_param(IS_MPU_REGION_NUMBER(MPU_Init->Number)); assert_param(IS_MPU_REGION_ENABLE(MPU_Init->Enable)); /* Set the Region number */ MPU->RNR = MPU_Init->Number; if ((MPU_Init->Enable) != RESET) { /* Check the parameters */ assert_param(IS_MPU_INSTRUCTION_ACCESS(MPU_Init->DisableExec)); assert_param(IS_MPU_REGION_PERMISSION_ATTRIBUTE(MPU_Init->AccessPermission)); assert_param(IS_MPU_TEX_LEVEL(MPU_Init->TypeExtField)); assert_param(IS_MPU_ACCESS_SHAREABLE(MPU_Init->IsShareable)); assert_param(IS_MPU_ACCESS_CACHEABLE(MPU_Init->IsCacheable)); assert_param(IS_MPU_ACCESS_BUFFERABLE(MPU_Init->IsBufferable)); assert_param(IS_MPU_SUB_REGION_DISABLE(MPU_Init->SubRegionDisable)); assert_param(IS_MPU_REGION_SIZE(MPU_Init->Size)); MPU->RBAR = MPU_Init->BaseAddress; MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) | ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) | ((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos) | ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) | ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) | ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) | ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) | ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) | ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos); } else { MPU->RBAR = 0x00U; MPU->RASR = 0x00U; } } #endif /* __MPU_PRESENT */ /** * @brief Gets the priority grouping field from the NVIC Interrupt Controller. * @retval Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field) */ uint32_t HAL_NVIC_GetPriorityGrouping(void) { /* Get the PRIGROUP[10:8] field value */ return NVIC_GetPriorityGrouping(); } /** * @brief Gets the priority of an interrupt. * @param IRQn External interrupt number. * This parameter can be an enumerator of IRQn_Type enumeration * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f4xxxx.h)) * @param PriorityGroup the priority grouping bits length. * This parameter can be one of the following values: * @arg NVIC_PRIORITYGROUP_0: 0 bits for preemption priority * 4 bits for subpriority * @arg NVIC_PRIORITYGROUP_1: 1 bits for preemption priority * 3 bits for subpriority * @arg NVIC_PRIORITYGROUP_2: 2 bits for preemption priority * 2 bits for subpriority * @arg NVIC_PRIORITYGROUP_3: 3 bits for preemption priority * 1 bits for subpriority * @arg NVIC_PRIORITYGROUP_4: 4 bits for preemption priority * 0 bits for subpriority * @param pPreemptPriority Pointer on the Preemptive priority value (starting from 0). * @param pSubPriority Pointer on the Subpriority value (starting from 0). * @retval None */ void HAL_NVIC_GetPriority(IRQn_Type IRQn, uint32_t PriorityGroup, uint32_t *pPreemptPriority, uint32_t *pSubPriority) { /* Check the parameters */ assert_param(IS_NVIC_PRIORITY_GROUP(PriorityGroup)); /* Get priority for Cortex-M system or device specific interrupts */ NVIC_DecodePriority(NVIC_GetPriority(IRQn), PriorityGroup, pPreemptPriority, pSubPriority); } /** * @brief Sets Pending bit of an external interrupt. * @param IRQn External interrupt number * This parameter can be an enumerator of IRQn_Type enumeration * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f4xxxx.h)) * @retval None */ void HAL_NVIC_SetPendingIRQ(IRQn_Type IRQn) { /* Check the parameters */ assert_param(IS_NVIC_DEVICE_IRQ(IRQn)); /* Set interrupt pending */ NVIC_SetPendingIRQ(IRQn); } /** * @brief Gets Pending Interrupt (reads the pending register in the NVIC * and returns the pending bit for the specified interrupt). * @param IRQn External interrupt number. * This parameter can be an enumerator of IRQn_Type enumeration * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f4xxxx.h)) * @retval status: - 0 Interrupt status is not pending. * - 1 Interrupt status is pending. */ uint32_t HAL_NVIC_GetPendingIRQ(IRQn_Type IRQn) { /* Check the parameters */ assert_param(IS_NVIC_DEVICE_IRQ(IRQn)); /* Return 1 if pending else 0 */ return NVIC_GetPendingIRQ(IRQn); } /** * @brief Clears the pending bit of an external interrupt. * @param IRQn External interrupt number. * This parameter can be an enumerator of IRQn_Type enumeration * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f4xxxx.h)) * @retval None */ void HAL_NVIC_ClearPendingIRQ(IRQn_Type IRQn) { /* Check the parameters */ assert_param(IS_NVIC_DEVICE_IRQ(IRQn)); /* Clear pending interrupt */ NVIC_ClearPendingIRQ(IRQn); } /** * @brief Gets active interrupt ( reads the active register in NVIC and returns the active bit). * @param IRQn External interrupt number * This parameter can be an enumerator of IRQn_Type enumeration * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f4xxxx.h)) * @retval status: - 0 Interrupt status is not pending. * - 1 Interrupt status is pending. */ uint32_t HAL_NVIC_GetActive(IRQn_Type IRQn) { /* Check the parameters */ assert_param(IS_NVIC_DEVICE_IRQ(IRQn)); /* Return 1 if active else 0 */ return NVIC_GetActive(IRQn); } /** * @brief Configures the SysTick clock source. * @param CLKSource specifies the SysTick clock source. * This parameter can be one of the following values: * @arg SYSTICK_CLKSOURCE_HCLK_DIV8: AHB clock divided by 8 selected as SysTick clock source. * @arg SYSTICK_CLKSOURCE_HCLK: AHB clock selected as SysTick clock source. * @retval None */ void HAL_SYSTICK_CLKSourceConfig(uint32_t CLKSource) { /* Check the parameters */ assert_param(IS_SYSTICK_CLK_SOURCE(CLKSource)); if (CLKSource == SYSTICK_CLKSOURCE_HCLK) { SysTick->CTRL |= SYSTICK_CLKSOURCE_HCLK; } else { SysTick->CTRL &= ~SYSTICK_CLKSOURCE_HCLK; } } /** * @brief This function handles SYSTICK interrupt request. * @retval None */ void HAL_SYSTICK_IRQHandler(void) { HAL_SYSTICK_Callback(); } /** * @brief SYSTICK callback. * @retval None */ __weak void HAL_SYSTICK_Callback(void) { /* NOTE : This function Should not be modified, when the callback is needed, the HAL_SYSTICK_Callback could be implemented in the user file */ } /** * @} */ /** * @} */ #endif /* HAL_CORTEX_MODULE_ENABLED */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
{ "language": "C" }
/* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_DV_PROFILE_INTERNAL_H #define AVCODEC_DV_PROFILE_INTERNAL_H #include "dv_profile.h" /** * Print all allowed DV profiles into logctx at specified logging level. */ void ff_dv_print_profiles(void *logctx, int loglevel); /** * Get a DV profile for the provided compressed frame. */ const AVDVProfile* ff_dv_frame_profile(AVCodecContext* codec, const AVDVProfile *sys, const uint8_t *frame, unsigned buf_size); #endif /* AVCODEC_DV_PROFILE_INTERNAL_H */
{ "language": "C" }
/***************************************************************************** Copyright (c) 2014, Intel Corp. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***************************************************************************** * Contents: Native high-level C interface to LAPACK function dsysvx * Author: Intel Corporation * Generated November 2015 *****************************************************************************/ #include "lapacke_utils.h" lapack_int LAPACKE_dsysvx( int matrix_layout, char fact, char uplo, lapack_int n, lapack_int nrhs, const double* a, lapack_int lda, double* af, lapack_int ldaf, lapack_int* ipiv, const double* b, lapack_int ldb, double* x, lapack_int ldx, double* rcond, double* ferr, double* berr ) { lapack_int info = 0; lapack_int lwork = -1; lapack_int* iwork = NULL; double* work = NULL; double work_query; if( matrix_layout != LAPACK_COL_MAJOR && matrix_layout != LAPACK_ROW_MAJOR ) { LAPACKE_xerbla( "LAPACKE_dsysvx", -1 ); return -1; } #ifndef LAPACK_DISABLE_NAN_CHECK if( LAPACKE_get_nancheck() ) { /* Optionally check input matrices for NaNs */ if( LAPACKE_dsy_nancheck( matrix_layout, uplo, n, a, lda ) ) { return -6; } if( LAPACKE_lsame( fact, 'f' ) ) { if( LAPACKE_dsy_nancheck( matrix_layout, uplo, n, af, ldaf ) ) { return -8; } } if( LAPACKE_dge_nancheck( matrix_layout, n, nrhs, b, ldb ) ) { return -11; } } #endif /* Allocate memory for working array(s) */ iwork = (lapack_int*)LAPACKE_malloc( sizeof(lapack_int) * MAX(1,n) ); if( iwork == NULL ) { info = LAPACK_WORK_MEMORY_ERROR; goto exit_level_0; } /* Query optimal working array(s) size */ info = LAPACKE_dsysvx_work( matrix_layout, fact, uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, rcond, ferr, berr, &work_query, lwork, iwork ); if( info != 0 ) { goto exit_level_1; } lwork = (lapack_int)work_query; /* Allocate memory for work arrays */ work = (double*)LAPACKE_malloc( sizeof(double) * lwork ); if( work == NULL ) { info = LAPACK_WORK_MEMORY_ERROR; goto exit_level_1; } /* Call middle-level interface */ info = LAPACKE_dsysvx_work( matrix_layout, fact, uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, lwork, iwork ); /* Release memory and exit */ LAPACKE_free( work ); exit_level_1: LAPACKE_free( iwork ); exit_level_0: if( info == LAPACK_WORK_MEMORY_ERROR ) { LAPACKE_xerbla( "LAPACKE_dsysvx", info ); } return info; }
{ "language": "C" }
/* crypto/ts/ts_lib.c */ /* * Written by Zoltan Glozik (zglozik@stones.com) for the OpenSSL project * 2002. */ /* ==================================================================== * Copyright (c) 2006 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * licensing@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ #include <stdio.h> #include "cryptlib.h" #include <openssl/objects.h> #include <openssl/bn.h> #include <openssl/x509v3.h> #include "ts.h" /* Local function declarations. */ /* Function definitions. */ int TS_ASN1_INTEGER_print_bio(BIO *bio, const ASN1_INTEGER *num) { BIGNUM num_bn; int result = 0; char *hex; BN_init(&num_bn); ASN1_INTEGER_to_BN(num, &num_bn); if ((hex = BN_bn2hex(&num_bn))) { result = BIO_write(bio, "0x", 2) > 0; result = result && BIO_write(bio, hex, strlen(hex)) > 0; OPENSSL_free(hex); } BN_free(&num_bn); return result; } int TS_OBJ_print_bio(BIO *bio, const ASN1_OBJECT *obj) { char obj_txt[128]; int len = OBJ_obj2txt(obj_txt, sizeof(obj_txt), obj, 0); BIO_write(bio, obj_txt, len); BIO_write(bio, "\n", 1); return 1; } int TS_ext_print_bio(BIO *bio, const STACK_OF(X509_EXTENSION) *extensions) { int i, critical, n; X509_EXTENSION *ex; ASN1_OBJECT *obj; BIO_printf(bio, "Extensions:\n"); n = X509v3_get_ext_count(extensions); for (i = 0; i < n; i++) { ex = X509v3_get_ext(extensions, i); obj = X509_EXTENSION_get_object(ex); i2a_ASN1_OBJECT(bio, obj); critical = X509_EXTENSION_get_critical(ex); BIO_printf(bio, ": %s\n", critical ? "critical" : ""); if (!X509V3_EXT_print(bio, ex, 0, 4)) { BIO_printf(bio, "%4s", ""); M_ASN1_OCTET_STRING_print(bio, ex->value); } BIO_write(bio, "\n", 1); } return 1; } int TS_X509_ALGOR_print_bio(BIO *bio, const X509_ALGOR *alg) { int i = OBJ_obj2nid(alg->algorithm); return BIO_printf(bio, "Hash Algorithm: %s\n", (i == NID_undef) ? "UNKNOWN" : OBJ_nid2ln(i)); } int TS_MSG_IMPRINT_print_bio(BIO *bio, TS_MSG_IMPRINT *a) { const ASN1_OCTET_STRING *msg; TS_X509_ALGOR_print_bio(bio, TS_MSG_IMPRINT_get_algo(a)); BIO_printf(bio, "Message data:\n"); msg = TS_MSG_IMPRINT_get_msg(a); BIO_dump_indent(bio, (const char *)M_ASN1_STRING_data(msg), M_ASN1_STRING_length(msg), 4); return 1; }
{ "language": "C" }
--- a/driver/wl_linux.c +++ b/driver/wl_linux.c @@ -1583,7 +1583,7 @@ wl_add_if(wl_info_t *wl, struct wlc_if* wl_if_setup(wlif->dev); - sprintf(wlif->dev->name, "%s%d.%d", devname, wl->pub->unit, wlif->subunit); + sprintf(wlif->dev->name, "%s%d-%d", devname, wl->pub->unit, wlif->subunit); if (remote) bcopy(remote, &wlif->remote, ETHER_ADDR_LEN);
{ "language": "C" }
/* SPDX-License-Identifier: BSD-2-Clause */ /* X-SPDX-Copyright-Text: (c) Solarflare Communications Inc */ /* Declarations common to apps in the efsend suite. * * CUSTOMER NOTE: This code is not intended to be used outside of the efsend * suite! */ #ifndef __SENDCOMMON_H__ #define __SENDCOMMON_H__ #include "utils.h" #include <etherfabric/vi.h> #include <ci/tools.h> #include <ci/tools/ippacket.h> #include <ci/net/ipv4.h> extern void usage(void); #define CL_CHK(x) \ do{ \ if( ! (x) ) \ usage(); \ }while(0) extern int init_udp_pkt(void* pkt_buf, int paylen, ef_vi *vi, ef_driver_handle dh, int vlan); extern void common_usage(void); extern void parse_args(char *argv[], int *ifindex, int local_port, int vlan); #endif
{ "language": "C" }
/* * * Copyright © 2000 Keith Packard, member of The XFree86 Project, Inc. * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of Keith Packard not be used in * advertising or publicity pertaining to distribution of the software without * specific, written prior permission. Keith Packard makes no * representations about the suitability of this software for any purpose. It * is provided "as is" without express or implied warranty. * * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL KEITH PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> #endif #ifndef _FBPICT_H_ #define _FBPICT_H_ /* fbpict.c */ extern _X_EXPORT void fbComposite(CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height); /* fbtrap.c */ extern _X_EXPORT void fbAddTraps(PicturePtr pPicture, INT16 xOff, INT16 yOff, int ntrap, xTrap * traps); extern _X_EXPORT void fbRasterizeTrapezoid(PicturePtr alpha, xTrapezoid * trap, int x_off, int y_off); extern _X_EXPORT void fbAddTriangles(PicturePtr pPicture, INT16 xOff, INT16 yOff, int ntri, xTriangle * tris); extern _X_EXPORT void fbTrapezoids(CARD8 op, PicturePtr pSrc, PicturePtr pDst, PictFormatPtr maskFormat, INT16 xSrc, INT16 ySrc, int ntrap, xTrapezoid * traps); extern _X_EXPORT void fbTriangles(CARD8 op, PicturePtr pSrc, PicturePtr pDst, PictFormatPtr maskFormat, INT16 xSrc, INT16 ySrc, int ntris, xTriangle * tris); extern _X_EXPORT void fbGlyphs(CARD8 op, PicturePtr pSrc, PicturePtr pDst, PictFormatPtr maskFormat, INT16 xSrc, INT16 ySrc, int nlist, GlyphListPtr list, GlyphPtr *glyphs); #endif /* _FBPICT_H_ */
{ "language": "C" }
/* * \brief Simple execve test * \author Norman Feske * \date 2019-08-20 */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(int argc, char **argv) { if (argc <= 1) return -1; int const count = atoi(argv[1]); printf("count %d\n", count); if (count <= 0) return 0; { char argv0[20]; char argv1[20]; snprintf(argv0, sizeof(argv0), "test-execve"); snprintf(argv1, sizeof(argv1), "%d", count - 1); char *argv[] { argv0, argv1, NULL }; execve("test-execve", argv, NULL); } printf("This code should never be reached.\n"); return -1; }
{ "language": "C" }
/* * feat.c -- Feature vector description and cepstra->feature computation. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 12-Jun-98 M K Ravishankar (rkm@cs.cmu.edu) at Carnegie Mellon University * Major changes to accommodate arbitrary feature input types. Added * feat_read(), moved various cep2feat functions from other files into * this one. Also, made this module object-oriented with the feat_t type. * Changed definition of s2mfc_read to let the caller manage MFC buffers. * * 03-Oct-96 M K Ravishankar (rkm@cs.cmu.edu) at Carnegie Mellon University * Added unistd.h include. * * 02-Oct-96 M K Ravishankar (rkm@cs.cmu.edu) at Carnegie Mellon University * Added check for sf argument to s2mfc_read being within file size. * * 18-Sep-96 M K Ravishankar (rkm@cs.cmu.edu) at Carnegie Mellon University * Added sf, ef parameters to s2mfc_read(). * * 10-Jan-96 M K Ravishankar (rkm@cs.cmu.edu) at Carnegie Mellon University * Added feat_cepsize(). * Added different feature-handling (s2_4x, s3_1x39 at this point). * Moved feature-dependent functions to feature-dependent files. * * 09-Jan-96 M K Ravishankar (rkm@cs.cmu.edu) at Carnegie Mellon University * Moved constant declarations from feat.h into here. * * 04-Nov-95 M K Ravishankar (rkm@cs.cmu.edu) at Carnegie Mellon University * Created. */ /* * This module encapsulates different feature streams used by the Sphinx group. New * stream types can be added by augmenting feat_init() and providing an accompanying * compute_feat function. It also provides a "generic" feature vector definition for * handling "arbitrary" speech input feature types (see the last section in feat_init()). * In this case the speech input data should already be feature vectors; no computation, * such as MFC->feature conversion, is available or needed. */ #include "feat.h" #include "bio.h" #include "cmn.h" #include "agc.h" #include "s3types.h" #if (! WIN32) #include <sys/file.h> #include <sys/errno.h> #include <sys/param.h> #else #include <fcntl.h> #endif #define FEAT_VERSION "1.0" int32 feat_readfile (feat_t *fcb, char *file, int32 sf, int32 ef, float32 ***feat, int32 maxfr) { FILE *fp; int32 i, l, k, nfr; int32 byteswap, chksum_present; uint32 chksum; char **argname, **argval; E_INFO("Reading feature file: '%s'[%d..%d]\n", file, sf, ef); assert (fcb); if (ef <= sf) { E_ERROR("%s: End frame (%d) <= Start frame (%d)\n", file, ef, sf); return -1; } if ((fp = fopen(file, "rb")) == NULL) { E_ERROR("fopen(%s,rb) failed\n", file); return -1; } /* Read header */ if (bio_readhdr (fp, &argname, &argval, &byteswap) < 0) { E_ERROR("bio_readhdr(%s) failed\n", file); fclose (fp); return -1; } /* Parse header info (although nothing much is done with it) */ chksum_present = 0; for (i = 0; argname[i]; i++) { if (strcmp (argname[i], "version") == 0) { if (strcmp(argval[i], FEAT_VERSION) != 0) E_WARN("%s: Version mismatch: %s, expecting %s\n", file, argval[i], FEAT_VERSION); } else if (strcmp (argname[i], "chksum0") == 0) { chksum_present = 1; /* Ignore the associated value */ } } bio_hdrarg_free (argname, argval); argname = argval = NULL; chksum = 0; /* #Frames */ if (bio_fread (&nfr, sizeof(int32), 1, fp, byteswap, &chksum) != 1) { E_ERROR("%s: fread(#frames) failed\n", file); fclose (fp); return -1; } /* #Feature streams */ if ((bio_fread (&l, sizeof(int32), 1, fp, byteswap, &chksum) != 1) || (l != feat_n_stream(fcb))) { E_ERROR("%s: Missing or bad #feature streams\n", file); fclose (fp); return -1; } /* Feature stream lengths */ k = 0; for (i = 0; i < feat_n_stream(fcb); i++) { if ((bio_fread (&l, sizeof(int32), 1, fp, byteswap, &chksum) != 1) || (l != feat_stream_len (fcb, i))) { E_ERROR("%s: Missing or bad feature stream size\n", file); fclose (fp); return -1; } k += l; } /* Check sf/ef specified */ if (sf > 0) { if (sf >= nfr) { E_ERROR("%s: Start frame (%d) beyond file size (%d)\n", file, sf, nfr); fclose (fp); return -1; } nfr -= sf; } /* Limit nfr as indicated by [sf..ef] */ if ((ef-sf+1) < nfr) nfr = (ef-sf+1); if (nfr > maxfr) { E_ERROR("%s: Feature buffer size(%d frames) < actual #frames(%d)\n", file, maxfr, nfr); fclose (fp); return -1; } /* Position at desired start frame and read feature data */ if (sf > 0) fseek (fp, sf * k * sizeof(float32), SEEK_CUR); if (bio_fread (feat[0][0], sizeof(float32), nfr*k, fp, byteswap, &chksum) != nfr*k) { E_ERROR("%s: fread(%dx%d) (feature data) failed\n", file, nfr, k); fclose (fp); return -1; } fclose (fp); /* NOTE: checksum NOT verified; we might read only part of file */ return nfr; } int32 feat_writefile (feat_t *fcb, char *file, float32 ***feat, int32 nfr) { FILE *fp; int32 i, k; E_INFO ("Writing feature file: '%s'\n", file); assert (fcb); if ((fp = fopen (file, "wb")) == NULL) { E_ERROR("fopen(%s,wb) failed\n", file); return -1; } /* Write header */ bio_writehdr_version (fp, FEAT_VERSION); fwrite (&nfr, sizeof(int32), 1, fp); fwrite (&(fcb->n_stream), sizeof(int32), 1, fp); k = 0; for (i = 0; i < feat_n_stream(fcb); i++) { fwrite (&(fcb->stream_len[i]), sizeof(int32), 1, fp); k += feat_stream_len(fcb, i); } /* Feature data is assumed to be in a single block, starting at feat[0][0][0] */ if (fwrite (feat[0][0], sizeof(float32), nfr*k, fp) != nfr*k) { E_ERROR("%s: fwrite(%dx%d feature data) failed\n", file, nfr, k); fclose (fp); return -1; } fclose (fp); return 0; } /* * Read specified segment [sf..ef] of Sphinx-II format mfc file read and return * #frames read. Return -1 if error. */ int32 feat_s2mfc_read (char *file, int32 sf, int32 ef, float32 **mfc, int32 maxfr) { FILE *fp; int32 n_float32; struct stat statbuf; int32 i, n, byterev, cepsize; if (ef < 0) ef = (int32)0x7fff0000; /* Hack!! hardwired constant */ E_INFO("Reading mfc file: '%s'[%d..%d]\n", file, sf, ef); if (ef <= sf) { E_ERROR("%s: End frame (%d) <= Start frame (%d)\n", file, ef, sf); return -1; } cepsize = 13; /* Hack!! hardwired constant */ /* Find filesize; HACK!! To get around intermittent NFS failures, use stat_retry */ if ((stat_retry (file, &statbuf) < 0) || ((fp = fopen(file, "rb")) == NULL)) { E_ERROR("stat_retry/fopen(%s) failed\n", file); return -1; } /* Read #floats in header */ if (fread_retry (&n_float32, sizeof(int32), 1, fp) != 1) { E_ERROR("%s: fread(#floats) failed\n", file); fclose (fp); return -1; } /* Check if n_float32 matches file size */ byterev = FALSE; if ((n_float32*sizeof(float32) + 4) != statbuf.st_size) { n = n_float32; SWAP_INT32(&n); if ((n*sizeof(float32) + 4) != statbuf.st_size) { E_ERROR("%s: Header size field: %d(%08x); filesize: %d(%08x)\n", file, n_float32, n_float32, statbuf.st_size, statbuf.st_size); fclose (fp); return -1; } n_float32 = n; byterev = TRUE; } if (n_float32 <= 0) { E_ERROR("%s: Header size field (#floats) = %d\n", file, n_float32); fclose (fp); return -1; } /* Convert n to #frames of input */ n = n_float32/cepsize; if (n * cepsize != n_float32) { E_ERROR("Header size field: %d; not multiple of %d\n", n_float32, cepsize); fclose (fp); return -1; } /* Check sf/ef specified */ if (sf > 0) { if (sf >= n) { E_ERROR("%s: Start frame (%d) beyond file size (%d)\n", file, sf, n); fclose (fp); return -1; } n -= sf; } /* Limit n if indicated by [sf..ef] */ if ((ef-sf+1) < n) n = (ef-sf+1); if (n > maxfr) { E_ERROR("%s: MFC buffer size(%d frames) < actual #frames(%d)\n", file, maxfr, n); fclose (fp); return -1; } /* Position at desired start frame and read MFC data */ if (sf > 0) fseek (fp, sf * cepsize * sizeof(float32), SEEK_CUR); n_float32 = n * cepsize; if (fread_retry (mfc[0], sizeof(float32), n_float32, fp) != n_float32) { E_ERROR("%s: fread(%dx%d) (MFC data) failed\n", file, n, cepsize); fclose (fp); return -1; } if (byterev) { for (i = 0; i < n_float32; i++) SWAP_FLOAT32(&(mfc[0][i])); } fclose (fp); return n; } static int32 feat_stream_len_sum (feat_t *fcb) { int32 i, k; k = 0; for (i = 0; i < feat_n_stream(fcb); i++) k += feat_stream_len (fcb, i); return k; } float32 **feat_vector_alloc (feat_t *fcb) { int32 i, k; float32 *data, **feat; assert (fcb); if ((k = feat_stream_len_sum(fcb)) <= 0) { E_ERROR("Sum(feature stream lengths) = %d\n", k); return NULL; } /* Allocate feature data array so that data is in one block from feat[0][0] */ feat = (float32 **) ckd_calloc (feat_n_stream(fcb), sizeof(float32 *)); data = (float32 *) ckd_calloc (k, sizeof(float32)); for (i = 0; i < feat_n_stream(fcb); i++) { feat[i] = data; data += feat_stream_len (fcb, i); } return feat; } float32 ***feat_array_alloc (feat_t *fcb, int32 nfr) { int32 i, j, k; float32 *data, ***feat; assert (fcb); assert (nfr > 0); if ((k = feat_stream_len_sum(fcb)) <= 0) { E_ERROR("Sum(feature stream lengths) = %d\n", k); return NULL; } /* Allocate feature data array so that data is in one block from feat[0][0][0] */ feat = (float32 ***) ckd_calloc_2d (nfr, feat_n_stream(fcb), sizeof(float32 *)); data = (float32 *) ckd_calloc (nfr*k, sizeof(float32)); for (i = 0; i < nfr; i++) { for (j = 0; j < feat_n_stream(fcb); j++) { feat[i][j] = data; data += feat_stream_len (fcb, j); } } return feat; } static void feat_s2_4x_cep2feat (feat_t *fcb, float32 **mfc, float32 **feat) { float32 *f; float32 *w, *_w; float32 *w1, *w_1, *_w1, *_w_1; float32 d1, d2; int32 i, j; assert (fcb); assert (feat_cepsize (fcb) == 13); assert (feat_cepsize_used (fcb) == 13); assert (feat_n_stream (fcb) == 4); assert (feat_stream_len (fcb, 0) == 12); assert (feat_stream_len (fcb, 1) == 24); assert (feat_stream_len (fcb, 2) == 3); assert (feat_stream_len (fcb, 3) == 12); assert (feat_window_size (fcb) == 4); /* CEP; skip C0 */ memcpy (feat[0], mfc[0]+1, (feat_cepsize(fcb)-1) * sizeof(float32)); /* * DCEP(SHORT): mfc[2] - mfc[-2] * DCEP(LONG): mfc[4] - mfc[-4] */ w = mfc[2] + 1; /* +1 to skip C0 */ _w = mfc[-2] + 1; f = feat[1]; for (i = 0; i < feat_cepsize(fcb)-1; i++) /* Short-term */ f[i] = w[i] - _w[i]; w = mfc[4] + 1; /* +1 to skip C0 */ _w = mfc[-4] + 1; for (j = 0; j < feat_cepsize(fcb)-1; i++, j++) /* Long-term */ f[i] = w[j] - _w[j]; /* D2CEP: (mfc[3] - mfc[-1]) - (mfc[1] - mfc[-3]) */ w1 = mfc[3] + 1; /* Final +1 to skip C0 */ _w1 = mfc[-1] + 1; w_1 = mfc[1] + 1; _w_1 = mfc[-3] + 1; f = feat[3]; for (i = 0; i < feat_cepsize(fcb)-1; i++) { d1 = w1[i] - _w1[i]; d2 = w_1[i] - _w_1[i]; f[i] = d1 - d2; } /* POW: C0, DC0, D2C0; differences computed as above for rest of cep */ f = feat[2]; f[0] = mfc[0][0]; f[1] = mfc[2][0] - mfc[-2][0]; d1 = mfc[3][0] - mfc[-1][0]; d2 = mfc[1][0] - mfc[-3][0]; f[2] = d1 - d2; } static void feat_s3_1x39_cep2feat (feat_t *fcb, float32 **mfc, float32 **feat) { float32 *f; float32 *w, *_w; float32 *w1, *w_1, *_w1, *_w_1; float32 d1, d2; int32 i; assert (fcb); assert (feat_cepsize (fcb) == 13); assert (feat_cepsize_used (fcb) == 13); assert (feat_n_stream (fcb) == 1); assert (feat_stream_len (fcb, 0) == 39); assert (feat_window_size (fcb) == 3); /* CEP; skip C0 */ memcpy (feat[0], mfc[0]+1, (feat_cepsize(fcb)-1) * sizeof(float32)); /* * DCEP: mfc[2] - mfc[-2]; */ f = feat[0] + feat_cepsize(fcb)-1; w = mfc[2] + 1; /* +1 to skip C0 */ _w = mfc[-2] + 1; for (i = 0; i < feat_cepsize(fcb)-1; i++) f[i] = w[i] - _w[i]; /* POW: C0, DC0, D2C0 */ f += feat_cepsize(fcb)-1; f[0] = mfc[0][0]; f[1] = mfc[2][0] - mfc[-2][0]; d1 = mfc[3][0] - mfc[-1][0]; d2 = mfc[1][0] - mfc[-3][0]; f[2] = d1 - d2; /* D2CEP: (mfc[3] - mfc[-1]) - (mfc[1] - mfc[-3]) */ f += 3; w1 = mfc[3] + 1; /* Final +1 to skip C0 */ _w1 = mfc[-1] + 1; w_1 = mfc[1] + 1; _w_1 = mfc[-3] + 1; for (i = 0; i < feat_cepsize(fcb)-1; i++) { d1 = w1[i] - _w1[i]; d2 = w_1[i] - _w_1[i]; f[i] = d1 - d2; } } static void feat_s3_cep (feat_t *fcb, float32 **mfc, float32 **feat) { assert (fcb); assert (feat_cepsize (fcb) == 13); assert ((feat_cepsize_used (fcb) <= 13) && (feat_cepsize_used(fcb) > 0)); assert (feat_n_stream (fcb) == 1); assert (feat_stream_len (fcb, 0) == feat_cepsize_used(fcb)); assert (feat_window_size (fcb) == 0); /* CEP */ memcpy (feat[0], mfc[0], feat_cepsize_used(fcb) * sizeof(float32)); } static void feat_s3_cep_dcep (feat_t *fcb, float32 **mfc, float32 **feat) { float32 *f; float32 *w, *_w; int32 i; assert (fcb); assert (feat_cepsize (fcb) == 13); assert ((feat_cepsize_used (fcb) <= 13) && (feat_cepsize_used(fcb) > 0)); assert (feat_n_stream (fcb) == 1); assert (feat_stream_len (fcb, 0) == (feat_cepsize_used(fcb) * 2)); assert (feat_window_size (fcb) == 2); /* CEP */ memcpy (feat[0], mfc[0], feat_cepsize_used(fcb) * sizeof(float32)); /* * DCEP: mfc[2] - mfc[-2]; */ f = feat[0] + feat_cepsize_used(fcb); w = mfc[2]; _w = mfc[-2]; for (i = 0; i < feat_cepsize_used(fcb); i++) f[i] = w[i] - _w[i]; } feat_t *feat_init (char *type, char *cmn, char *varnorm, char *agc) { feat_t *fcb; int32 i, l, k; char wd[16384], *strp; E_INFO("Initializing feature stream to type: '%s', CMN='%s', VARNORM='%s', AGC='%s'\n", type, cmn, varnorm, agc); fcb = (feat_t *) ckd_calloc (1, sizeof(feat_t)); fcb->name = (char *) ckd_salloc (type); if (strcmp (type, "s2_4x") == 0) { /* Sphinx-II format 4-stream feature (Hack!! hardwired constants below) */ fcb->cepsize = 13; fcb->cepsize_used = 13; fcb->n_stream = 4; fcb->stream_len = (int32 *) ckd_calloc (4, sizeof(int32)); fcb->stream_len[0] = 12; fcb->stream_len[1] = 24; fcb->stream_len[2] = 3; fcb->stream_len[3] = 12; fcb->window_size = 4; fcb->compute_feat = feat_s2_4x_cep2feat; } else if (strcmp (type, "s3_1x39") == 0) { /* 1-stream cep/dcep/pow/ddcep (Hack!! hardwired constants below) */ fcb->cepsize = 13; fcb->cepsize_used = 13; fcb->n_stream = 1; fcb->stream_len = (int32 *) ckd_calloc (1, sizeof(int32)); fcb->stream_len[0] = 39; fcb->window_size = 3; fcb->compute_feat = feat_s3_1x39_cep2feat; } else if (strncmp (type, "cep_dcep", 8) == 0) { /* 1-stream cep/dcep (Hack!! hardwired constants below) */ fcb->cepsize = 13; /* Check if using only a portion of cep dimensions */ if (type[8] == ',') { if ((sscanf (type+9, "%d%n", &(fcb->cepsize_used), &l) != 1) || (type[l+9] != '\0') || (feat_cepsize_used(fcb) <= 0) || (feat_cepsize_used(fcb) > feat_cepsize(fcb))) E_FATAL("Bad feature type argument: '%s'\n", type); } else fcb->cepsize_used = 13; fcb->n_stream = 1; fcb->stream_len = (int32 *) ckd_calloc (1, sizeof(int32)); fcb->stream_len[0] = feat_cepsize_used(fcb) * 2; fcb->window_size = 2; fcb->compute_feat = feat_s3_cep_dcep; } else if (strncmp (type, "cep", 3) == 0) { /* 1-stream cep (Hack!! hardwired constants below) */ fcb->cepsize = 13; /* Check if using only a portion of cep dimensions */ if (type[3] == ',') { if ((sscanf (type+4, "%d%n", &(fcb->cepsize_used), &l) != 1) || (type[l+4] != '\0') || (feat_cepsize_used(fcb) <= 0) || (feat_cepsize_used(fcb) > feat_cepsize(fcb))) E_FATAL("Bad feature type argument: '%s'\n", type); } else fcb->cepsize_used = 13; fcb->n_stream = 1; fcb->stream_len = (int32 *) ckd_calloc (1, sizeof(int32)); fcb->stream_len[0] = feat_cepsize_used(fcb); fcb->window_size = 0; fcb->compute_feat = feat_s3_cep; } else { /* * Generic definition: Format should be %d,%d,%d,...,%d (i.e., comma separated * list of feature stream widths; #items = #streams). */ l = strlen(type); k = 0; for (i = 1; i < l-1; i++) if (type[i] == ',') { type[i] = ' '; k++; } k++; /* Presumably there are (#commas+1) streams */ fcb->n_stream = k; fcb->stream_len = (int32 *) ckd_calloc (k, sizeof(int32)); /* Scan individual feature stream lengths */ strp = type; i = 0; while (sscanf (strp, "%s%n", wd, &l) == 1) { strp += l; if ((i >= fcb->n_stream) || (sscanf (wd, "%d", &(fcb->stream_len[i])) != 1) || (fcb->stream_len[i] <= 0)) E_FATAL("Bad feature type argument\n"); i++; } if (i != fcb->n_stream) E_FATAL("Bad feature type argument\n"); /* Input is already the feature stream */ fcb->cepsize = -1; fcb->cepsize_used = -1; fcb->window_size = 0; fcb->compute_feat = NULL; } if (strcmp (cmn, "current") == 0) fcb->cmn = 1; else E_FATAL("Unsupported CMN type '%s'\n", cmn); if (strcmp (varnorm, "yes") == 0) fcb->varnorm = 1; else if (strcmp (varnorm, "no") == 0) fcb->varnorm = 0; else E_FATAL("Unsupported VARNORM type '%s'\n", varnorm); if (strcmp (agc, "max") == 0) fcb->agc = 1; else if (strcmp (agc, "none") == 0) fcb->agc = 0; else E_FATAL("Unsupported AGC type '%s'\n", agc); return fcb; } void feat_print (feat_t *fcb, float32 ***feat, int32 nfr, FILE *fp) { int32 i, j, k; for (i = 0; i < nfr; i++) { fprintf (fp, "%8d:", i); for (j = 0; j < feat_n_stream(fcb); j++) { fprintf (fp, "\t%2d:", j); for (k = 0; k < feat_stream_len(fcb, j); k++) fprintf (fp, " %8.4f", feat[i][j][k]); fprintf (fp, "\n"); } } fflush (fp); } int32 feat_s2mfc2feat (feat_t *fcb, char *file, char *dir, int32 sf, int32 ef, float32 ***feat, int32 maxfr) { char path[16384]; int32 win, nfr; int32 i, k; float32 **mfc; if (fcb->cepsize <= 0) { E_ERROR("Bad cepsize: %d\n", fcb->cepsize); return -1; } /* Create mfc filename, combining file, dir and extension (.mfc) if necessary */ k = strlen(file); if ((k > 4) && (strcmp (file+k-4, ".mfc") == 0)) { /* Hack!! Hardwired .mfc extension */ if (dir && (file[0] != '/')) sprintf (path, "%s/%s", dir, file); else strcpy (path, file); } else { if (dir && (file[0] != '/')) sprintf (path, "%s/%s.mfc", dir, file); else sprintf (path, "%s.mfc", file); } win = feat_window_size(fcb); /* Adjust boundaries to include padding for feature computation */ if (ef < 0) ef = (int32)0x7fff0000 - win; /* Hack!! Hardwired constant */ sf -= win; ef += win; /* Read mfc file */ mfc = (float32 **) ckd_calloc_2d (S3_MAX_FRAMES, fcb->cepsize, sizeof(float32)); if (sf < 0) nfr = feat_s2mfc_read (path, 0, ef, mfc-sf, S3_MAX_FRAMES+sf-win); else nfr = feat_s2mfc_read (path, sf, ef, mfc, S3_MAX_FRAMES-win); if (nfr < 0) { ckd_free_2d((void **) mfc); return -1; } if (nfr < 2*win+1) { E_ERROR("%s: MFC file/segment too short to compute features: %d frames\n", file, nfr); ckd_free_2d((void **) mfc); return -1; } /* Add padding at the beginning by replicating input data, if necessary */ if (sf < 0) { for (i = 0; i < -sf; i++) memcpy (mfc[i], mfc[i-sf+1], fcb->cepsize * sizeof(float32)); nfr -= sf; } /* Add padding at the end by replicating input data, if necessary */ k = ef - sf + 1; if (nfr < k) { k -= nfr; /* Extra frames padding needed at the end */ if (k > win) k = win; /* Limit feature frames to extent of file, not to unbounded ef */ for (i = 0; i < k; i++) memcpy (mfc[nfr+i], mfc[nfr+i-1-k], fcb->cepsize * sizeof(float32)); nfr += k; } /* At this point, nfr includes complete padded cepstrum frames */ if (nfr - win*2 > maxfr) { E_ERROR("%s: Feature buffer size(%d frames) < required(%d)\n", maxfr, nfr - win*2); ckd_free_2d((void **) mfc); return -1; } if (fcb->cmn) cmn (mfc, fcb->varnorm, nfr, fcb->cepsize); if (fcb->agc) agc_max (mfc, nfr); /* Create feature vectors */ for (i = win; i < nfr-win; i++) fcb->compute_feat (fcb, mfc+i, feat[i-win]); ckd_free_2d((void **) mfc); return (nfr - win*2); }
{ "language": "C" }
/*================================================================================================== File: AudioToolbox/AudioSession.h Contains: API for audio session services. Copyright: (c) 2006 - 2013 by Apple, Inc., all rights reserved. Bugs?: For bug reports, consult the following page on the World Wide Web: http://developer.apple.com/bugreporter/ ==================================================================================================*/ #if !defined(__AudioSession_h__) #define __AudioSession_h__ //================================================================================================== /*! @header AudioSession This header describes the API for audio session services. Note: As of iOS 7, this entire API has been deprecated in favor of AVAudioSession, part of the AVFoundation framework. */ //================================================================================================== #pragma mark Includes #include <TargetConditionals.h> #include <Availability.h> #if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) #if !TARGET_OS_IPHONE #include <CoreAudio/AudioHardware.h> #endif #include <CoreFoundation/CoreFoundation.h> #else #include <AudioHardware.h> #include <CFRunLoop.h> #include <CFString.h> #include <CFURL.h> #endif //================================================================================================== #if defined(__cplusplus) extern "C" { #endif //================================================================================================== #pragma mark - #pragma mark AudioSession Error Constants /*! @enum AudioSession error codes @abstract Error codes returned from the AudioSession portion of the API. @constant kAudioSessionNoError No error has occurred @constant kAudioSessionNotInitialized This error is returned when the AudioSessionInitialize function was not called prior to calling any other AudioSession function. @constant kAudioSessionAlreadyInitialized This error is returned when you call AudioSessionInitialize more than once. @constant kAudioSessionInitializationError This error indicates an AudioSession initialization error. @constant kAudioSessionUnsupportedPropertyError The property is not supported. This error code can also be used to indicate that a bad property value was passed in a SetProperty call, an attempt was made to set a read-only property, an attempt was made to read a write-only property, an attempt was made to read a property that is only available by way of a property listener, or an attempt was made to set a listener on a property for which listeners are not supported. @constant kAudioSessionBadPropertySizeError The size of the property data was not correct. @constant kAudioSessionNotActiveError The operation failed because the AudioSession is not active. Calling AudioSessionSetActive(true) first will fix this error in most cases. @constant kAudioSessionNoCategorySet The requested operation failed because it requires that the session have had an audio category explicitly set, and none was set. @constant kAudioSessionIncompatibleCategory The requested operation failed because the AudioSession has an incompatible category (e.g. attempting to play or record when the category is AudioProcessing) or the session is not active. @constant kAudioSessionUnspecifiedError An audio session unspecified error has occurred. */ enum { kAudioSessionNoError = 0, kAudioSessionNotInitialized = '!ini', kAudioSessionAlreadyInitialized = 'init', kAudioSessionInitializationError = 'ini?', kAudioSessionUnsupportedPropertyError = 'pty?', kAudioSessionBadPropertySizeError = '!siz', kAudioSessionNotActiveError = '!act', kAudioServicesNoHardwareError = 'nohw', kAudioSessionNoCategorySet = '?cat', kAudioSessionIncompatibleCategory = '!cat', kAudioSessionUnspecifiedError = 'what' }; //================================================================================================== #pragma mark - #pragma mark AudioSession Types /*! @typedef AudioSessionPropertyID @abstract Type used for specifying an AudioSession property. */ typedef UInt32 AudioSessionPropertyID; //================================================================================================== #pragma mark - #pragma mark AudioSession Interruption States /*! @enum AudioSession interruptions states @abstract These are used with the AudioSessionInterruptionListener to indicate if an interruption begins or ends. @constant kAudioSessionBeginInterruption Indicates that this AudioSession has just been interrupted. @constant kAudioSessionEndInterruption Indicates the end of an interruption. */ enum { kAudioSessionBeginInterruption = 1, kAudioSessionEndInterruption = 0 }; //================================================================================================== #pragma mark - #pragma mark AudioSession Audio Categories /*! @enum AudioSession audio categories states @abstract These are used with as values for the kAudioSessionProperty_AudioCategory property to indicate the audio category of the AudioSession. @constant kAudioSessionCategory_AmbientSound Use this category for background sounds such as rain, car engine noise, etc. Mixes with other music. @constant kAudioSessionCategory_SoloAmbientSound Use this category for background sounds. Other music will stop playing. @constant kAudioSessionCategory_MediaPlayback Use this category for music tracks. @constant kAudioSessionCategory_RecordAudio Use this category when recording audio. @constant kAudioSessionCategory_PlayAndRecord Use this category when recording and playing back audio. @constant kAudioSessionCategory_AudioProcessing Use this category when using a hardware codec or signal processor while not playing or recording audio. */ enum { kAudioSessionCategory_AmbientSound = 'ambi', kAudioSessionCategory_SoloAmbientSound = 'solo', kAudioSessionCategory_MediaPlayback = 'medi', kAudioSessionCategory_RecordAudio = 'reca', kAudioSessionCategory_PlayAndRecord = 'plar', kAudioSessionCategory_AudioProcessing = 'proc' }; #pragma mark AudioSession Audio Category Routing Overrides /*! @enum AudioSession audio category routing overrides @abstract These are used with as values for the kAudioSessionProperty_OverrideAudioRoute property. @constant kAudioSessionOverrideAudioRoute_None No override. Return audio routing to the default state for the current audio category. @constant kAudioSessionOverrideAudioRoute_Speaker Route audio output to speaker. Use this override with the kAudioSessionCategory_PlayAndRecord category, which by default routes the output to the receiver. */ enum { kAudioSessionOverrideAudioRoute_None = 0, kAudioSessionOverrideAudioRoute_Speaker = 'spkr' }; //================================================================================================== #pragma mark AudioSession reason codes for route change /*! @enum AudioSession reason codes for route change @abstract These are codes used when the kAudioSessionProperty_AudioRoute property changes @constant kAudioSessionRouteChangeReason_Unknown The reason is unknown. @constant kAudioSessionRouteChangeReason_NewDeviceAvailable A new device became available (e.g. headphones have been plugged in). @constant kAudioSessionRouteChangeReason_OldDeviceUnavailable The old device became unavailable (e.g. headphones have been unplugged). @constant kAudioSessionRouteChangeReason_CategoryChange The audio category has changed (e.g. kAudioSessionCategory_MediaPlayback has been changed to kAudioSessionCategory_PlayAndRecord). @constant kAudioSessionRouteChangeReason_Override The route has been overridden (e.g. category is kAudioSessionCategory_PlayAndRecord and the output has been changed from the receiver, which is the default, to the speaker). @constant kAudioSessionRouteChangeReason_WakeFromSleep The device woke from sleep. @constant kAudioSessionRouteChangeReason_NoSuitableRouteForCategory Returned when there is no route for the current category (for instance RecordCategory but no input device) @constant kAudioSessionRouteChangeReason_RouteConfigurationChange Indicates that the set of input and/our output ports has not changed, but some aspect of their configuration has changed. For example, a port's selected data source has changed. */ enum { kAudioSessionRouteChangeReason_Unknown = 0, kAudioSessionRouteChangeReason_NewDeviceAvailable = 1, kAudioSessionRouteChangeReason_OldDeviceUnavailable = 2, kAudioSessionRouteChangeReason_CategoryChange = 3, kAudioSessionRouteChangeReason_Override = 4, kAudioSessionRouteChangeReason_WakeFromSleep = 6, kAudioSessionRouteChangeReason_NoSuitableRouteForCategory = 7, kAudioSessionRouteChangeReason_RouteConfigurationChange = 8 }; // see documentation for kAudioSessionProperty_AudioRouteChange // Note: the string refers to "OutputDevice" for historical reasons. Audio routes may contain zero or more inputs and // zero or more outputs. #define kAudioSession_AudioRouteChangeKey_Reason "OutputDeviceDidChange_Reason" // CFString version of kAudioSession_AudioRouteChangeKey_Reason. This is more convenient to use than the raw string version. // Available in iOS 5.0 or greater extern const CFStringRef kAudioSession_RouteChangeKey_Reason __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_5_0,__IPHONE_7_0); // CFDictionary keys for kAudioSessionProperty_AudioRouteChange // Available in iOS 5.0 or greater extern const CFStringRef kAudioSession_AudioRouteChangeKey_PreviousRouteDescription __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_5_0,__IPHONE_7_0); extern const CFStringRef kAudioSession_AudioRouteChangeKey_CurrentRouteDescription __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_5_0,__IPHONE_7_0); // CFDictionary keys for kAudioSessionProperty_AudioRouteDescription // Available in iOS 5.0 or greater extern const CFStringRef kAudioSession_AudioRouteKey_Inputs __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_5_0,__IPHONE_7_0); extern const CFStringRef kAudioSession_AudioRouteKey_Outputs __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_5_0,__IPHONE_7_0); // key(s) for the CFDictionary associated with each entry of the CFArrays returned by kAudioSession_AudioRouteKey_Inputs // and kAudioSession_AudioRouteKey_Outputs. // Available in iOS 5.0 or greater extern const CFStringRef kAudioSession_AudioRouteKey_Type __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_5_0,__IPHONE_7_0); /*! @enum AudioSession route input types @abstract These are the strings used with the kAudioSession_AudioRouteKey_Type key for the CFDictionary associated with kAudioSession_AudioRouteKey_Inputs. Available in iOS 5.0 or greater @constant kAudioSessionInputRoute_LineIn A line in input @constant kAudioSessionInputRoute_BuiltInMic A built-in microphone input. (Note that some devices like early iPods do not have this input) @constant kAudioSessionInputRoute_HeadsetMic A microphone that is part of a headset (combined microphone and headphones) @constant kAudioSessionInputRoute_BluetoothHFP A microphone that is part of a Bluetooth Hands-Free Profile device @constant kAudioSessionInputRoute_USBAudio A Universal Serial Bus input */ extern const CFStringRef kAudioSessionInputRoute_LineIn __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_5_0,__IPHONE_7_0); extern const CFStringRef kAudioSessionInputRoute_BuiltInMic __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_5_0,__IPHONE_7_0); extern const CFStringRef kAudioSessionInputRoute_HeadsetMic __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_5_0,__IPHONE_7_0); extern const CFStringRef kAudioSessionInputRoute_BluetoothHFP __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_5_0,__IPHONE_7_0); extern const CFStringRef kAudioSessionInputRoute_USBAudio __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_5_0,__IPHONE_7_0); /*! @enum AudioSession route output types @abstract These are strings used with the kAudioSession_AudioRouteKey_Type key for the CFDictionary associated with kAudioSession_AudioRouteKey_Outputs. Available in iOS 5.0 or greater @constant kAudioSessionOutputRoute_LineOut A line out output @constant kAudioSessionOutputRoute_Headphones Speakers in a headset (mic and headphones) or simple headphones @constant kAudioSessionOutputRoute_BluetoothHFP Speakers that are part of a Bluetooth Hands-Free Profile device @constant kAudioSessionOutputRoute_BluetoothA2DP Speakers in a Bluetooth A2DP device @constant kAudioSessionOutputRoute_BuiltInReceiver The speaker you hold to your ear when on a phone call @constant kAudioSessionOutputRoute_BuiltInSpeaker The built-in speaker @constant kAudioSessionOutputRoute_USBAudio Speaker(s) in a Universal Serial Bus device @constant kAudioSessionOutputRoute_HDMI Output via High-Definition Multimedia Interface @constant kAudioSessionOutputRoute_AirPlay Output on a remote Air Play device */ extern const CFStringRef kAudioSessionOutputRoute_LineOut __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_5_0,__IPHONE_7_0); extern const CFStringRef kAudioSessionOutputRoute_Headphones __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_5_0,__IPHONE_7_0); extern const CFStringRef kAudioSessionOutputRoute_BluetoothHFP __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_5_0,__IPHONE_7_0); extern const CFStringRef kAudioSessionOutputRoute_BluetoothA2DP __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_5_0,__IPHONE_7_0); extern const CFStringRef kAudioSessionOutputRoute_BuiltInReceiver __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_5_0,__IPHONE_7_0); extern const CFStringRef kAudioSessionOutputRoute_BuiltInSpeaker __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_5_0,__IPHONE_7_0); extern const CFStringRef kAudioSessionOutputRoute_USBAudio __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_5_0,__IPHONE_7_0); extern const CFStringRef kAudioSessionOutputRoute_HDMI __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_5_0,__IPHONE_7_0); extern const CFStringRef kAudioSessionOutputRoute_AirPlay __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_5_0,__IPHONE_7_0); // CFDictionary keys for kAudioSessionProperty_InputSources extern const CFStringRef kAudioSession_InputSourceKey_ID __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_5_0,__IPHONE_7_0); extern const CFStringRef kAudioSession_InputSourceKey_Description __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_5_0,__IPHONE_7_0); // CFDictionary keys for kAudioSessionProperty_OutputDestinations extern const CFStringRef kAudioSession_OutputDestinationKey_ID __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_5_0,__IPHONE_7_0); extern const CFStringRef kAudioSession_OutputDestinationKey_Description __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_5_0,__IPHONE_7_0); //================================================================================================== #pragma mark AudioSession interruption types for end interruption events /*! @enum AudioSession Interruption types @abstract When an app's AudioSessionInterruptionListener is called at the end of an interruption event, the app may query to see if it should resume audio or not. The interruption type can be obtained through the kAudioSessionProperty_InterruptionType, available in iOS 4.0 and greater. @constant kAudioSessionInterruptionType_ShouldResume Indicates that the interruption was one where it is appropriate to resume playback at the conclusion of the interruption. (e.g.: a phone call was rejected) @constant kAudioSessionInterruptionType_ShouldNotResume Indicates that the interruption was one where it is not appropriate to resume playback at the conclusion of the interruption. (e.g.: interruption due to iPod playback) */ enum { // typedef UInt32 AudioSessionInterruptionType kAudioSessionInterruptionType_ShouldResume = 'irsm', kAudioSessionInterruptionType_ShouldNotResume = '!rsm' }; typedef UInt32 AudioSessionInterruptionType; //================================================================================================== #pragma mark AudioSession mode values /*! @enum AudioSession Modes @abstract Modes modify the audio category in order to introduce behavior that is tailored to the specific use of audio within an application. Available in iOS 5.0 and greater. @constant kAudioSessionMode_Default The default mode. @constant kAudioSessionMode_VoiceChat Only valid with kAudioSessionCategory_PlayAndRecord. Appropriate for Voice Over IP (VOIP) applications. Reduces the number of allowable audio routes to be only those that are appropriate for VOIP applications and may engage appropriate system-supplied signal processing. Has the side effect of setting kAudioSessionProperty_OverrideCategoryEnableBluetoothInput to true. @constant kAudioSessionMode_VideoRecording Only valid with kAudioSessionCategory_PlayAndRecord or kAudioSessionCategory_RecordAudio. Modifies the audio routing options and may engage appropriate system-supplied signal processing. @constant kAudioSessionMode_Measurement Appropriate for applications that wish to minimize the effect of system-supplied signal processing for input and/or output audio signals. @constant kAudioSessionMode_GameChat Set by Game Kit on behalf of an application that uses a GKVoiceChat object; valid only with the kAudioSessionCategory_PlayAndRecord category. Do not set this mode directly. If you need similar behavior and are not using a GKVoiceChat object, use the kAudioSessionMode_VoiceChat mode. */ enum { kAudioSessionMode_Default = 'dflt', kAudioSessionMode_VoiceChat = 'vcct', kAudioSessionMode_VideoRecording = 'vrcd', kAudioSessionMode_Measurement = 'msmt', kAudioSessionMode_GameChat = 'gmct' }; //================================================================================================== #pragma mark AudioSession Properties /*! @enum AudioSession property codes @abstract These are the property codes used with the AudioSession API. @constant kAudioSessionProperty_PreferredHardwareSampleRate A Float64 indicating the preferred hardware sample rate for the AudioSession. The actual sample rate may be different @constant kAudioSessionProperty_PreferredHardwareIOBufferDuration A Float32 indicating the preferred hardware IO buffer duration in seconds. The actual IO buffer duration may be different @constant kAudioSessionProperty_AudioCategory A UInt32 value indicating the audio category for the AudioSession (see constants above). @constant kAudioSessionProperty_AudioRouteChange The value for this property is ONLY provided with the property changed callback. You cannot get the value of this property (or set it). The property changed callback provides a CFDictionaryRef with keyed values: Key = kAudioSession_AudioRouteChangeKey_Reason; value is a CFNumberRef with one of the reasons listed above. Key = kAudioSession_AudioRouteChangeKey_PreviousRouteDescription; value is a CFDictionaryRef containing information about the previous route. This dictionary is of exactly the same format as the dictionary associated with kAudioSessionProperty_AudioRouteDescription. Available in iOS 5.0 or greater. Key = kAudioSession_AudioRouteChangeKey_CurrentRouteDescription; value is a CFDictionaryRef containing information about the new route. This dictionary is of exactly the same format as the dictionary associated with kAudioSessionProperty_AudioRouteDescription. Available in iOS 5.0 or greater. @constant kAudioSessionProperty_CurrentHardwareSampleRate A Float64 indicating the current hardware sample rate @constant kAudioSessionProperty_CurrentHardwareInputNumberChannels A UInt32 indicating the current number of hardware input channels @constant kAudioSessionProperty_CurrentHardwareOutputNumberChannels A UInt32 indicating the current number of hardware output channels @constant kAudioSessionProperty_CurrentHardwareOutputVolume A Float32 indicating the current output volume @constant kAudioSessionProperty_CurrentHardwareInputLatency A Float32 indicating the current hardware input latency in seconds. @constant kAudioSessionProperty_CurrentHardwareOutputLatency A Float32 indicating the current hardware output latency in seconds. @constant kAudioSessionProperty_CurrentHardwareIOBufferDuration A Float32 indicating the current hardware IO buffer duration in seconds. @constant kAudioSessionProperty_OtherAudioIsPlaying A UInt32 with a value other than zero when someone else, typically the iPod application, is playing audio @constant kAudioSessionProperty_OverrideAudioRoute A UInt32 with one of two values: kAudioSessionOverrideAudioRoute_None or kAudioSessionOverrideAudioRoute_Speaker @constant kAudioSessionProperty_AudioInputAvailable A UInt32 with a value other than zero when audio input is available. Use this property, rather than the device model, to determine if audio input is available. A listener will notify you when audio input becomes available. For instance, when a headset is attached to the second generation iPod Touch, audio input becomes available via the wired microphone. @constant kAudioSessionProperty_ServerDied Available with iOS 3.0 or greater The value for this property is ONLY provided with the property changed callback. You cannot get the value of this property (or set it). The property changed callback notifies you that the audio server has died. @constant kAudioSessionProperty_OtherMixableAudioShouldDuck Available with iOS 3.0 or greater If the current session category of an application allows mixing (iPod playback in the background for example), then that other audio will be ducked when the current application makes any sound. An example of this is the Nike app that does this as it provides periodic updates to its user (it ducks any iPod music currently being played while it provides its status). This defaults to off (0). Note that the other audio will be ducked for as long as the current session is active. You will need to deactivate your audio session when you want full volume playback of the other audio. If your category is the Playback category and you have this set to its default (non-mixable), setting this value to on, will also make your category mixable with others (kAudioSessionProperty_OverrideCategoryMixWithOthers will be set to true) @constant kAudioSessionProperty_OverrideCategoryMixWithOthers Available with iOS 3.0 or greater This allows an application to change the default behavior of some audio session categories with regards to whether other applications can play while your session is active. The two typical cases are: (1) PlayAndRecord category this will default to false, but can be set to true. This would allow iPod to play in the background while an app had both audio input and output enabled (2) MediaPlayback category this will default to false, but can be set to true. This would allow iPod to play in the background, but an app will still be able to play regardless of the setting of the ringer switch (3) Other categories this defaults to false and cannot be changed (that is, the mix with others setting of these categories cannot be overridden An application must be prepared for setting this property to fail as behaviour may change in future releases. If an application changes their category, they should reassert the override (it is not sticky across category changes) @constant kAudioSessionProperty_OverrideCategoryDefaultToSpeaker Available with iOS 3.1 or greater This allows an application to change the default behaviour of some audio session categories with regards to the audio route. The current category behavior is: (1) PlayAndRecord category this will default to false, but can be set to true. this will route to Speaker (instead of Receiver) when no other audio route is connected. (2) Other categories this defaults to false and cannot be changed (that is, the default to speaker setting of these categories cannot be overridden An application must be prepared for setting this property to fail as behaviour may change in future releases. If an application changes their category, they should reassert the override (it is not sticky across category changes) @constant kAudioSessionProperty_OverrideCategoryEnableBluetoothInput Available with iOS 3.1 or greater This allows an application to change the default behaviour of some audio session categories with regards to showing bluetooth devices as available routes. The current category behavior is: (1) PlayAndRecord category this will default to false, but can be set to true. This will allow a paired bluetooth device to show up as an available route for input, while playing through the category-appropriate output (2) Record category this will default to false, but can be set to true. This will allow a paired bluetooth device to show up as an available route for input (3) Other categories this defaults to false and cannot be changed (that is, enabling bluetooth for input in these categories is not allowed) An application must be prepared for setting this property to fail as behaviour may change in future releases. If an application changes their category, they should reassert the override (it is not sticky across category changes) @constant kAudioSessionProperty_InterruptionType Available with iOS 4.0 or greater This is a read-only property that gives the type of the end interruption event. Media playback apps (i.e., those apps that have a "play" button), may use this property as a guideline for when to resume playing after an interruption ends. Apps without a "play" button, (e.g., games) should always resume audio playback when the interruption ends. This property is only valid within the scope of the client app's AudioSessionInterruptionListener callback and only valid for the AudioSessionEndInterruption event. Attempting to read the property at any other time is invalid. @constant kAudioSessionProperty_Mode Available with iOS 5.0 or greater A UInt32 value that specifies the mode to be combined with the Audio Category. See AudioSession mode values defined above. @constant kAudioSessionProperty_InputSources Available with iOS 5.0 or greater For use with certain accessories, such as some USB audio devices, that support input source selection. If the attached accessory supports source selection, provides a description of the available sources. Not to be confused with kAudioSessionProperty_AudioRouteDescription, which provides a description of the current audio route. A CFArray of CFDictionaries with the keys listed below. If no input sources are available, a valid CFArray with 0 entries will be returned by a get operation. Key = kAudioSession_InputSourceKey_ID; value is a CFNumberRef representing a system-defined identifier for the input source. This is the identifier to be used when setting the input source. Key = kAudioSession_InputSourceKey_Description; value is a CFStringRef description of the input source suitable for displaying in a user interface. Examples: "Internal Mic", "External Mic", "Ext 48V Mic", "Instrument", "External Line Connector" @constant kAudioSessionProperty_OutputDestinations Available with iOS 5.0 or greater For use with certain accessories, such as some USB audio devices, that support output destination selection. If the attached accessory supports destination selection, provides a description of the available destinations. Not to be confused with kAudioSessionProperty_AudioRouteDescription, which provides a description of the current audio route. A CFArray of CFDictionaries with the keys listed below. If no output destinations are available, a valid CFArray with 0 entries will be returned by a get operation. Key = kAudioSession_OutputDestinationKey_ID; value is a CFNumberRef representing a system-defined identifier for the output destination. This is the identifier to be used when setting the destination. Key = kAudioSession_OutputDestinationKey_Description; value is a CFStringRef description of the output destination suitable for displaying in a user interface. @constant kAudioSessionProperty_InputSource Available with iOS 5.0 or greater For use with certain accessories, such as some USB audio devices, that support input source selection. A CFNumberRef value that specifies the input source to be selected. The value must be one of the IDs provided by the kAudioSession_InputSourceKey_ID as part of the data associated with kAudioSessionProperty_InputSources. @constant kAudioSessionProperty_OutputDestination Available with iOS 5.0 or greater For use with certain accessories, such as some USB audio devices, that support output destination selection. A CFNumberRef value that specifies the output destination to be selected. The value must be one of the IDs provided by the kAudioSession_OutputDestinationKey_ID as part of the data associated with kAudioSessionProperty_OutputDestinations. @constant kAudioSessionProperty_InputGainAvailable Available with iOS 5.0 or greater A UInt32 with a value other than zero when audio input gain is available. Some inputs may not provide the ability to set the input gain, so check this value before attempting to set input gain. @constant kAudioSessionProperty_InputGainScalar Available with iOS 5.0 or greater A Float32 value defined over the range [0.0, 1.0], with 0.0 corresponding to the lowest analog gain setting and 1.0 corresponding to the highest analog gain setting. Attempting to set values outside of the defined range will result in the value being "clamped" to a valid input. This is a global input gain setting that applies to the current input source for the entire system. When no applications are using the input gain control, the system will restore the default input gain setting for the input source. Note that some audio accessories, such as USB devices, may not have a default value. This property is only valid if kAudioSessionProperty_InputGainAvailable is true. Note that route change events represent substantive changes to the audio system. Input gain settings are not guaranteed to persist across route changes. Application code should be aware that route change events can (and likely will) cause a change to input gain settings, and so should be prepared to reassess the state of input gain after the new route is established. @constant kAudioSessionProperty_AudioRouteDescription Available with iOS 5.0 or greater A CFDictionaryRef with information about the current audio route; keyed values: Key = kAudioSession_AudioRouteKey_Inputs; value is a CFArray of CFDictionaries with information about the inputs utilitized in the current audio route. Key = kAudioSession_AudioRouteKey_Outputs; value is a CFArray of CFDictionaries with information about the outputs utilitized in the current audio route. Both kAudioSession_AudioRouteKey_Inputs and kAudioSession_AudioRouteKey_Outputs return a CFArray of CFDictionaries with Key = kAudioSession_AudioRouteKey_Type; value is a CFString corresponding to the input or output types documented above. */ enum { // typedef UInt32 AudioSessionPropertyID kAudioSessionProperty_PreferredHardwareSampleRate = 'hwsr', // Float64 (get/set) kAudioSessionProperty_PreferredHardwareIOBufferDuration = 'iobd', // Float32 (get/set) kAudioSessionProperty_AudioCategory = 'acat', // UInt32 (get/set) kAudioSessionProperty_AudioRouteChange = 'roch', // CFDictionaryRef (property listener) kAudioSessionProperty_CurrentHardwareSampleRate = 'chsr', // Float64 (get only) kAudioSessionProperty_CurrentHardwareInputNumberChannels = 'chic', // UInt32 (get only/property listener) kAudioSessionProperty_CurrentHardwareOutputNumberChannels = 'choc', // UInt32 (get only/property listener) kAudioSessionProperty_CurrentHardwareOutputVolume = 'chov', // Float32 (get only/property listener) kAudioSessionProperty_CurrentHardwareInputLatency = 'cilt', // Float32 (get only) kAudioSessionProperty_CurrentHardwareOutputLatency = 'colt', // Float32 (get only) kAudioSessionProperty_CurrentHardwareIOBufferDuration = 'chbd', // Float32 (get only) kAudioSessionProperty_OtherAudioIsPlaying = 'othr', // UInt32 (get only) kAudioSessionProperty_OverrideAudioRoute = 'ovrd', // UInt32 (set only) kAudioSessionProperty_AudioInputAvailable = 'aiav', // UInt32 (get only/property listener) kAudioSessionProperty_ServerDied = 'died', // UInt32 (property listener) kAudioSessionProperty_OtherMixableAudioShouldDuck = 'duck', // UInt32 (get/set) kAudioSessionProperty_OverrideCategoryMixWithOthers = 'cmix', // UInt32 (get, some set) kAudioSessionProperty_OverrideCategoryDefaultToSpeaker = 'cspk', // UInt32 (get, some set) kAudioSessionProperty_OverrideCategoryEnableBluetoothInput = 'cblu', // UInt32 (get, some set) kAudioSessionProperty_InterruptionType = 'type', // UInt32 (get only) kAudioSessionProperty_Mode = 'mode', // UInt32 (get/set) kAudioSessionProperty_InputSources = 'srcs', // CFArrayRef (get only/property listener) kAudioSessionProperty_OutputDestinations = 'dsts', // CFArrayRef (get only/property listener) kAudioSessionProperty_InputSource = 'isrc', // CFNumberRef (get/set) kAudioSessionProperty_OutputDestination = 'odst', // CFNumberRef (get/set) kAudioSessionProperty_InputGainAvailable = 'igav', // UInt32 (get only/property listener) kAudioSessionProperty_InputGainScalar = 'igsc', // Float32 (get/set/property listener) kAudioSessionProperty_AudioRouteDescription = 'crar' // CFDictionaryRef (get only) }; //================================================================================================== #pragma mark - #pragma mark Callbacks /*! @typedef AudioSessionInterruptionListener @abstract A function to be called when an interruption begins or ends. @discussion AudioSessionInterruptionListener has to be provided by client applications in the AudioSessionInitialize function. It will be called when an interruption begins or ends. @param inClientData The client user data to use when calling the listener. @param inInterruptionState Indicates if the interruption begins (kAudioSessionBeginInterruption) or ends (kAudioSessionEndInterruption) */ typedef void (*AudioSessionInterruptionListener)( void * inClientData, UInt32 inInterruptionState); /*! @typedef AudioSessionPropertyListener @abstract A function to be executed when a property changes. @discussion AudioSessionPropertyListener may be provided by client application to be called when a property changes. @param inClientData The client user data to use when calling the listener. @param inID The AudioSession property that changed @param inDataSize The size of the payload @param inData The payload of the property that changed (see data type for each property) */ typedef void (*AudioSessionPropertyListener)( void * inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void * inData); //================================================================================================== #pragma mark - #pragma mark AudioSession Functions /*! @functiongroup AudioSession */ /*! @function AudioSessionInitialize @abstract Initialize the AudioSession. @discussion This function has to be called once before calling any other AudioSession functions. @param inRunLoop A CFRunLoopRef indicating the desired run loop the interruption routine should be run on. Pass NULL to use the main run loop. @param inRunLoopMode A CFStringRef indicating the run loop mode for the runloop where the completion routine will be executed. Pass NULL to use kCFRunLoopDefaultMode. @param inInterruptionListener An AudioSessionInterruptionListener to be called when the AudioSession is interrupted. @param inClientData The client user data to use when calling the interruption listener. */ extern OSStatus AudioSessionInitialize( CFRunLoopRef inRunLoop, CFStringRef inRunLoopMode, AudioSessionInterruptionListener inInterruptionListener, void *inClientData) __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_2_0,__IPHONE_7_0); /*! @function AudioSessionSetActive @abstract Activate or deactivate the AudioSession. @discussion Call this function with active set to true to activate this AudioSession (interrupt the currently active AudioSession). Call this function with active set to false to deactivate this AudioSession (allow another interrupted AudioSession to resume). When active is true this call may fail if the currently active AudioSession has a higher priority. @param active A Boolean indicating if you want to make this AudioSession active or inactive. */ extern OSStatus AudioSessionSetActive( Boolean active) __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_2_0,__IPHONE_7_0); //================================================================================================== #pragma mark AudioSessionActivationFlags for AudioSessionSetActiveWithFlags /*! @enum Flags for AudioSessionSetActiveWithFlags @abstract These are valid bitmap flags that may be combined and passed to AudioSessionSetActiveWithFlags to refine this routine's behavior. @constant kAudioSessionSetActiveFlag_NotifyOthersOnDeactivation Notify an interrupted app that the interruption has ended and it may resume playback. Only valid on session deactivation. */ enum { kAudioSessionSetActiveFlag_NotifyOthersOnDeactivation = (1 << 0) // 0x01 }; /*! @function AudioSessionSetActiveWithFlags @abstract Same functionality as AudioSessionSetActive, with an additional flags parameter for refining behavior. @discussion Call this function with active set to true to activate this AudioSession (interrupt the currently active AudioSession). Call this function with active set to false to deactivate this AudioSession (allow another interrupted AudioSession to resume). Pass in one or more flags to refine the behavior during activation or deactivation. When active is true this call may fail if the currently active AudioSession has a higher priority. @param active A Boolean indicating if you want to make this AudioSession active or inactive. @param inFlags A bitmap containing one or more flags from the AudioSessionActivationFlags enum. */ extern OSStatus AudioSessionSetActiveWithFlags( Boolean active, UInt32 inFlags) __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_4_0,__IPHONE_7_0); /*! @function AudioSessionGetProperty @abstract Get the value of a property. @discussion This function can be called to get the value for a property of the AudioSession. Valid properties are listed in an enum above. @param inID The AudioSessionPropertyID for which we want to get the value. @param ioDataSize The size of the data payload. On entry it should contain the size of the memory pointed to by outData. On exit it will contain the actual size of the data. @param outData The data for the property will be copied here. @return kAudioSessionNoError if the operation was successful. If the property is a write-only property or only available by way of property listeners, kAudioSessionUnsupportedPropertyError will be returned. Other error codes listed under AudioSession Error Constants also apply to this function. */ extern OSStatus AudioSessionGetProperty( AudioSessionPropertyID inID, UInt32 *ioDataSize, void *outData) __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_2_0,__IPHONE_7_0); /*! @function AudioSessionSetProperty @abstract Set the value of a property. @discussion This function can be called to set the value for a property of the AudioSession. Valid properties are listed in an enum above. @param inID The AudioSessionPropertyID for which we want to set the value. @param inDataSize The size of the data payload. @param inData The data for the property we want to set. @return kAudioSessionNoError if the operation was successful. If the property is a read-only property or an invalid property value is passed in, kAudioSessionUnsupportedPropertyError will be returned. Other error codes listed under AudioSession Error Constants also apply to this function. */ extern OSStatus AudioSessionSetProperty( AudioSessionPropertyID inID, UInt32 inDataSize, const void *inData) __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_2_0,__IPHONE_7_0); /*! @function AudioSessionGetPropertySize @abstract Get the size of the payload for a property. @discussion This function can be called to get the size for the payload of a property. Valid properties are listed in an enum above. @param inID The AudioSessionPropertyID for which we want to get the size of the payload. @param outDataSize The size of the data payload will be copied here. */ extern OSStatus AudioSessionGetPropertySize( AudioSessionPropertyID inID, UInt32 *outDataSize) __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_2_0,__IPHONE_7_0); /*! @function AudioSessionAddPropertyListener @abstract Add a property listener. @discussion This function can be used to add a listener to be called when a property changes. If a listener and user data already exist for this property, they will be replaced. Valid properties are listed above. @param inID The AudioSessionPropertyID for which we want to set a listener. @param inProc The listener to be called when the property changes. @param inClientData The client user data to use when calling the listener. @return kAudioSessionNoError if the operation was successful. If the property does not support listeners, kAudioSessionUnsupportedPropertyError will be returned. Other error codes listed under AudioSession Error Constants also apply to this function. */ extern OSStatus AudioSessionAddPropertyListener( AudioSessionPropertyID inID, AudioSessionPropertyListener inProc, void *inClientData) __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_2_0,__IPHONE_7_0); /*! @function AudioSessionRemovePropertyListener @abstract see AudioSessionRemovePropertyListenerWithUserData @discussion see AudioSessionRemovePropertyListenerWithUserData */ extern OSStatus AudioSessionRemovePropertyListener( AudioSessionPropertyID inID) __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_2_0,__IPHONE_2_0); /*! @function AudioSessionRemovePropertyListener @abstract Remove a property listener. @discussion This function can be called to remove the listener for a property. The caller provides the same proc and user data that was used to add the listener. This ensures that there can be more than one listener established for a given property ID, and each listener can be removed as requested. Valid properties are listed above. @param inID The AudioSessionPropertyID for which we want to remove the listener. @param inProc The proc that was used to add the listener that needs to be removed. @param inClientData The client data that was used to add the listener that needs to be removed. @return kAudioSessionNoError if the operation was successful. If the property does not support listeners, kAudioSessionUnsupportedPropertyError will be returned. Other error codes listed under AudioSession Error Constants also apply to this function. */ extern OSStatus AudioSessionRemovePropertyListenerWithUserData( AudioSessionPropertyID inID, AudioSessionPropertyListener inProc, void *inClientData) __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_2_1,__IPHONE_7_0); #pragma mark - #pragma mark Deprecated /*! @enum AudioSession audio categories states @abstract These two session categories are deprecated in iOS 3.0 or later @constant kAudioSessionCategory_UserInterfaceSoundEffects use kAudioSessionCategory_AmbientSound @constant kAudioSessionCategory_LiveAudio use kAudioSessionCategory_MediaPlayback */ enum { kAudioSessionCategory_UserInterfaceSoundEffects = 'uifx', kAudioSessionCategory_LiveAudio = 'live' }; /*! @enum AudioSession audio categories states @abstract Deprecated AudioSession properties @constant kAudioSessionProperty_AudioRoute Deprecated in iOS 5.0; Use kAudioSessionProperty_AudioRouteDescription */ enum { kAudioSessionProperty_AudioRoute = 'rout', // CFStringRef (get only) }; // deprecated dictionary keys // Deprecated in iOS 5.0; Use kAudioSession_AudioRouteChangeKey_PreviousRouteDescription instead #define kAudioSession_AudioRouteChangeKey_OldRoute "OutputDeviceDidChange_OldRoute" //================================================================================================== #ifdef __cplusplus } #endif #endif /* __AudioSession_h__ */
{ "language": "C" }
/* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels <adam@sics.se> * */ #ifndef __LWIP_INET_H__ #define __LWIP_INET_H__ #include "lwip/opt.h" #include "lwip/def.h" #include "lwip/ip_addr.h" #ifdef __cplusplus extern "C" { #endif /** For compatibility with BSD code */ struct in_addr { u32_t s_addr; }; /** 255.255.255.255 */ #define INADDR_NONE IPADDR_NONE /** 127.0.0.1 */ #define INADDR_LOOPBACK IPADDR_LOOPBACK /** 0.0.0.0 */ #define INADDR_ANY IPADDR_ANY /** 255.255.255.255 */ #define INADDR_BROADCAST IPADDR_BROADCAST /* Definitions of the bits in an Internet address integer. On subnets, host and network parts are found according to the subnet mask, not these masks. */ #define IN_CLASSA(a) IP_CLASSA(a) #define IN_CLASSA_NET IP_CLASSA_NET #define IN_CLASSA_NSHIFT IP_CLASSA_NSHIFT #define IN_CLASSA_HOST IP_CLASSA_HOST #define IN_CLASSA_MAX IP_CLASSA_MAX #define IN_CLASSB(b) IP_CLASSB(b) #define IN_CLASSB_NET IP_CLASSB_NET #define IN_CLASSB_NSHIFT IP_CLASSB_NSHIFT #define IN_CLASSB_HOST IP_CLASSB_HOST #define IN_CLASSB_MAX IP_CLASSB_MAX #define IN_CLASSC(c) IP_CLASSC(c) #define IN_CLASSC_NET IP_CLASSC_NET #define IN_CLASSC_NSHIFT IP_CLASSC_NSHIFT #define IN_CLASSC_HOST IP_CLASSC_HOST #define IN_CLASSC_MAX IP_CLASSC_MAX #define IN_CLASSD(d) IP_CLASSD(d) #define IN_CLASSD_NET IP_CLASSD_NET /* These ones aren't really */ #define IN_CLASSD_NSHIFT IP_CLASSD_NSHIFT /* net and host fields, but */ #define IN_CLASSD_HOST IP_CLASSD_HOST /* routing needn't know. */ #define IN_CLASSD_MAX IP_CLASSD_MAX #define IN_MULTICAST(a) IP_MULTICAST(a) #define IN_EXPERIMENTAL(a) IP_EXPERIMENTAL(a) #define IN_BADCLASS(a) IP_BADCLASS(a) #define IN_LOOPBACKNET IP_LOOPBACKNET #define inet_addr_from_ipaddr(target_inaddr, source_ipaddr) ((target_inaddr)->s_addr = ip4_addr_get_u32(source_ipaddr)) #define inet_addr_to_ipaddr(target_ipaddr, source_inaddr) (ip4_addr_set_u32(target_ipaddr, (source_inaddr)->s_addr)) /* ATTENTION: the next define only works because both s_addr and ip_addr_t are an u32_t effectively! */ #define inet_addr_to_ipaddr_p(target_ipaddr_p, source_inaddr) ((target_ipaddr_p) = (ip_addr_t*)&((source_inaddr)->s_addr)) /* directly map this to the lwip internal functions */ #define inet_addr(cp) ipaddr_addr(cp) #define inet_aton(cp, addr) ipaddr_aton(cp, (ip_addr_t*)addr) #define inet_ntoa(addr) ipaddr_ntoa((ip_addr_t*)&(addr)) #define inet_ntoa_r(addr, buf, buflen) ipaddr_ntoa_r((ip_addr_t*)&(addr), buf, buflen) #ifdef __cplusplus } #endif #endif /* __LWIP_INET_H__ */
{ "language": "C" }
/***************************************************************************** * * MODULE: Demo board button controls * * DESCRIPTION: * Macros to make it easier to read buttons on demo boards */ /**************************************************************************** * * This software is owned by NXP B.V. and/or its supplier and is protected * under applicable copyright laws. All rights are reserved. We grant You, * and any third parties, a license to use this software solely and * exclusively on NXP products [NXP Microcontrollers such as JN5148, JN5142, JN5139]. * You, and any third parties must reproduce the copyright and warranty notice * and any other legend of ownership on each copy or partial copy of the * software. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * Copyright NXP B.V. 2012. All rights reserved * ***************************************************************************/ #ifndef BUTTON_INCLUDED #define BUTTON_INCLUDED #if defined __cplusplus extern "C" { #endif /****************************************************************************/ /*** Include Files ***/ /****************************************************************************/ #include "jendefs.h" #include "AppHardwareApi.h" /****************************************************************************/ /*** Macro Definitions ***/ /****************************************************************************/ #define BUTTON_0_MASK 1 #define BUTTON_1_MASK 4 #define BUTTON_2_MASK 8 #define BUTTON_3_MASK 16 #define BUTTON_ALL_MASK_RFD (BUTTON_0_MASK | BUTTON_1_MASK) #define BUTTON_ALL_MASK_FFD (BUTTON_0_MASK | BUTTON_1_MASK | \ BUTTON_2_MASK | BUTTON_3_MASK) #define BUTTON_BASE_BIT 0 #define BUTTON_0_PIN 1 << 9 #define BUTTON_1_PIN 1 << 10 #define BUTTON_2_PIN 1 << 11 #define BUTTON_3_PIN 1 << 20 #define BUTTON_ALL_MASK_RFD_PIN ( BUTTON_0_PIN | BUTTON_1_PIN ) #define BUTTON_ALL_MASK_FFD_PIN ( BUTTON_0_PIN | BUTTON_1_PIN | \ BUTTON_2_PIN | BUTTON_3_PIN ) #define vButtonInitRfd() \ vAHI_DioSetDirection(BUTTON_ALL_MASK_RFD_PIN, 0) #define vButtonInitFfd() \ vAHI_DioSetDirection(BUTTON_ALL_MASK_FFD_PIN, 0) /****************************************************************************/ /*** Type Definitions ***/ /****************************************************************************/ /****************************************************************************/ /*** Exported Functions ***/ /****************************************************************************/ PUBLIC uint8 u8ButtonReadRfd(void); PUBLIC uint8 u8ButtonReadFfd(void); /****************************************************************************/ /*** Exported Variables ***/ /****************************************************************************/ #if defined __cplusplus } #endif #endif /* BUTTON_INCLUDED */ /****************************************************************************/ /*** END OF FILE ***/ /****************************************************************************/
{ "language": "C" }
// Copyright 2009 the Sputnik authors. All rights reserved. /** * The scope chain is initialised to contain the same objects, * in the same order, as the calling context's scope chain * * @path ch10/10.4/10.4.2/S10.4.2_A1.1_T1.js * @description eval within global execution context */ var i; var j; str1 = ''; str2 = ''; x = 1; y = 2; for(i in this){ str1+=i; } eval('for(j in this){\nstr2+=j;\n}'); if(!(str1 === str2)){ $ERROR("#1: scope chain must contain same objects in the same order as the calling context"); }
{ "language": "C" }
/* Simple DirectMedia Layer Copyright (C) 1997-2016 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ // Modified by Yao Wei Tjong for Urho3D #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_X11 #include <unistd.h> /* For getpid() and readlink() */ #include "SDL_video.h" #include "SDL_mouse.h" #include "../SDL_sysvideo.h" #include "../SDL_pixels_c.h" #include "SDL_x11video.h" #include "SDL_x11framebuffer.h" #include "SDL_x11shape.h" #include "SDL_x11touch.h" #include "SDL_x11xinput2.h" #if SDL_VIDEO_OPENGL_EGL #include "SDL_x11opengles.h" #endif #ifdef X_HAVE_UTF8_STRING #include <locale.h> #endif /* Initialization/Query functions */ static int X11_VideoInit(_THIS); static void X11_VideoQuit(_THIS); /* Find out what class name we should use */ static char * get_classname() { char *spot; #if defined(__LINUX__) || defined(__FREEBSD__) char procfile[1024]; char linkfile[1024]; int linksize; #endif /* First allow environment variable override */ spot = SDL_getenv("SDL_VIDEO_X11_WMCLASS"); if (spot) { return SDL_strdup(spot); } /* Next look at the application's executable name */ #if defined(__LINUX__) || defined(__FREEBSD__) #if defined(__LINUX__) SDL_snprintf(procfile, SDL_arraysize(procfile), "/proc/%d/exe", getpid()); #elif defined(__FREEBSD__) SDL_snprintf(procfile, SDL_arraysize(procfile), "/proc/%d/file", getpid()); #else #error Where can we find the executable name? #endif linksize = readlink(procfile, linkfile, sizeof(linkfile) - 1); if (linksize > 0) { linkfile[linksize] = '\0'; spot = SDL_strrchr(linkfile, '/'); if (spot) { return SDL_strdup(spot + 1); } else { return SDL_strdup(linkfile); } } #endif /* __LINUX__ || __FREEBSD__ */ /* Finally use the default we've used forever */ return SDL_strdup("SDL_App"); } /* X11 driver bootstrap functions */ static int X11_Available(void) { Display *display = NULL; if (SDL_X11_LoadSymbols()) { display = X11_XOpenDisplay(NULL); if (display != NULL) { X11_XCloseDisplay(display); } SDL_X11_UnloadSymbols(); } return (display != NULL); } static void X11_DeleteDevice(SDL_VideoDevice * device) { SDL_VideoData *data = (SDL_VideoData *) device->driverdata; if (data->display) { X11_XCloseDisplay(data->display); } SDL_free(data->windowlist); SDL_free(device->driverdata); SDL_free(device); SDL_X11_UnloadSymbols(); } /* An error handler to reset the vidmode and then call the default handler. */ static SDL_bool safety_net_triggered = SDL_FALSE; static int (*orig_x11_errhandler) (Display *, XErrorEvent *) = NULL; static int X11_SafetyNetErrHandler(Display * d, XErrorEvent * e) { SDL_VideoDevice *device = NULL; /* if we trigger an error in our error handler, don't try again. */ if (!safety_net_triggered) { safety_net_triggered = SDL_TRUE; device = SDL_GetVideoDevice(); if (device != NULL) { int i; for (i = 0; i < device->num_displays; i++) { SDL_VideoDisplay *display = &device->displays[i]; if (SDL_memcmp(&display->current_mode, &display->desktop_mode, sizeof (SDL_DisplayMode)) != 0) { X11_SetDisplayMode(device, display, &display->desktop_mode); } } } } if (orig_x11_errhandler != NULL) { return orig_x11_errhandler(d, e); /* probably terminate. */ } return 0; } static SDL_VideoDevice * X11_CreateDevice(int devindex) { SDL_VideoDevice *device; SDL_VideoData *data; const char *display = NULL; /* Use the DISPLAY environment variable */ if (!SDL_X11_LoadSymbols()) { return NULL; } /* Need for threading gl calls. This is also required for the proprietary nVidia driver to be threaded. */ X11_XInitThreads(); /* Initialize all variables that we clean on shutdown */ device = (SDL_VideoDevice *) SDL_calloc(1, sizeof(SDL_VideoDevice)); if (!device) { SDL_OutOfMemory(); return NULL; } data = (struct SDL_VideoData *) SDL_calloc(1, sizeof(SDL_VideoData)); if (!data) { SDL_free(device); SDL_OutOfMemory(); return NULL; } device->driverdata = data; data->global_mouse_changed = SDL_TRUE; /* FIXME: Do we need this? if ( (SDL_strncmp(X11_XDisplayName(display), ":", 1) == 0) || (SDL_strncmp(X11_XDisplayName(display), "unix:", 5) == 0) ) { local_X11 = 1; } else { local_X11 = 0; } */ data->display = X11_XOpenDisplay(display); #if defined(__osf__) && defined(SDL_VIDEO_DRIVER_X11_DYNAMIC) /* On Tru64 if linking without -lX11, it fails and you get following message. * Xlib: connection to ":0.0" refused by server * Xlib: XDM authorization key matches an existing client! * * It succeeds if retrying 1 second later * or if running xhost +localhost on shell. */ if (data->display == NULL) { SDL_Delay(1000); data->display = X11_XOpenDisplay(display); } #endif if (data->display == NULL) { SDL_free(device->driverdata); SDL_free(device); SDL_SetError("Couldn't open X11 display"); return NULL; } #ifdef X11_DEBUG X11_XSynchronize(data->display, True); #endif /* Hook up an X11 error handler to recover the desktop resolution. */ safety_net_triggered = SDL_FALSE; orig_x11_errhandler = X11_XSetErrorHandler(X11_SafetyNetErrHandler); /* Set the function pointers */ device->VideoInit = X11_VideoInit; device->VideoQuit = X11_VideoQuit; device->GetDisplayModes = X11_GetDisplayModes; device->GetDisplayBounds = X11_GetDisplayBounds; device->GetDisplayUsableBounds = X11_GetDisplayUsableBounds; device->GetDisplayDPI = X11_GetDisplayDPI; device->SetDisplayMode = X11_SetDisplayMode; device->SuspendScreenSaver = X11_SuspendScreenSaver; device->PumpEvents = X11_PumpEvents; device->CreateWindow = X11_CreateWindow; device->CreateWindowFrom = X11_CreateWindowFrom; device->SetWindowTitle = X11_SetWindowTitle; device->SetWindowIcon = X11_SetWindowIcon; device->SetWindowPosition = X11_SetWindowPosition; device->SetWindowSize = X11_SetWindowSize; device->SetWindowMinimumSize = X11_SetWindowMinimumSize; device->SetWindowMaximumSize = X11_SetWindowMaximumSize; device->GetWindowBordersSize = X11_GetWindowBordersSize; device->SetWindowOpacity = X11_SetWindowOpacity; device->SetWindowModalFor = X11_SetWindowModalFor; device->SetWindowInputFocus = X11_SetWindowInputFocus; device->ShowWindow = X11_ShowWindow; device->HideWindow = X11_HideWindow; device->RaiseWindow = X11_RaiseWindow; device->MaximizeWindow = X11_MaximizeWindow; device->MinimizeWindow = X11_MinimizeWindow; device->RestoreWindow = X11_RestoreWindow; device->SetWindowBordered = X11_SetWindowBordered; device->SetWindowResizable = X11_SetWindowResizable; device->SetWindowFullscreen = X11_SetWindowFullscreen; device->SetWindowGammaRamp = X11_SetWindowGammaRamp; device->SetWindowGrab = X11_SetWindowGrab; device->DestroyWindow = X11_DestroyWindow; device->CreateWindowFramebuffer = X11_CreateWindowFramebuffer; device->UpdateWindowFramebuffer = X11_UpdateWindowFramebuffer; device->DestroyWindowFramebuffer = X11_DestroyWindowFramebuffer; device->GetWindowWMInfo = X11_GetWindowWMInfo; device->SetWindowHitTest = X11_SetWindowHitTest; device->shape_driver.CreateShaper = X11_CreateShaper; device->shape_driver.SetWindowShape = X11_SetWindowShape; device->shape_driver.ResizeWindowShape = X11_ResizeWindowShape; #if SDL_VIDEO_OPENGL_GLX device->GL_LoadLibrary = X11_GL_LoadLibrary; device->GL_GetProcAddress = X11_GL_GetProcAddress; device->GL_UnloadLibrary = X11_GL_UnloadLibrary; device->GL_CreateContext = X11_GL_CreateContext; device->GL_MakeCurrent = X11_GL_MakeCurrent; device->GL_SetSwapInterval = X11_GL_SetSwapInterval; device->GL_GetSwapInterval = X11_GL_GetSwapInterval; device->GL_SwapWindow = X11_GL_SwapWindow; device->GL_DeleteContext = X11_GL_DeleteContext; #elif SDL_VIDEO_OPENGL_EGL device->GL_LoadLibrary = X11_GLES_LoadLibrary; device->GL_GetProcAddress = X11_GLES_GetProcAddress; device->GL_UnloadLibrary = X11_GLES_UnloadLibrary; device->GL_CreateContext = X11_GLES_CreateContext; device->GL_MakeCurrent = X11_GLES_MakeCurrent; device->GL_SetSwapInterval = X11_GLES_SetSwapInterval; device->GL_GetSwapInterval = X11_GLES_GetSwapInterval; device->GL_SwapWindow = X11_GLES_SwapWindow; device->GL_DeleteContext = X11_GLES_DeleteContext; #endif device->SetClipboardText = X11_SetClipboardText; device->GetClipboardText = X11_GetClipboardText; device->HasClipboardText = X11_HasClipboardText; device->StartTextInput = X11_StartTextInput; device->StopTextInput = X11_StopTextInput; device->SetTextInputRect = X11_SetTextInputRect; device->free = X11_DeleteDevice; return device; } VideoBootStrap X11_bootstrap = { "x11", "SDL X11 video driver", X11_Available, X11_CreateDevice }; static int (*handler) (Display *, XErrorEvent *) = NULL; static int X11_CheckWindowManagerErrorHandler(Display * d, XErrorEvent * e) { if (e->error_code == BadWindow) { return (0); } else { return (handler(d, e)); } } static void X11_CheckWindowManager(_THIS) { SDL_VideoData *data = (SDL_VideoData *) _this->driverdata; Display *display = data->display; Atom _NET_SUPPORTING_WM_CHECK; int status, real_format; Atom real_type; unsigned long items_read = 0, items_left = 0; unsigned char *propdata = NULL; Window wm_window = 0; #ifdef DEBUG_WINDOW_MANAGER char *wm_name; #endif /* Set up a handler to gracefully catch errors */ X11_XSync(display, False); handler = X11_XSetErrorHandler(X11_CheckWindowManagerErrorHandler); _NET_SUPPORTING_WM_CHECK = X11_XInternAtom(display, "_NET_SUPPORTING_WM_CHECK", False); status = X11_XGetWindowProperty(display, DefaultRootWindow(display), _NET_SUPPORTING_WM_CHECK, 0L, 1L, False, XA_WINDOW, &real_type, &real_format, &items_read, &items_left, &propdata); if (status == Success) { if (items_read) { wm_window = ((Window*)propdata)[0]; } if (propdata) { X11_XFree(propdata); propdata = NULL; } } if (wm_window) { status = X11_XGetWindowProperty(display, wm_window, _NET_SUPPORTING_WM_CHECK, 0L, 1L, False, XA_WINDOW, &real_type, &real_format, &items_read, &items_left, &propdata); if (status != Success || !items_read || wm_window != ((Window*)propdata)[0]) { wm_window = None; } if (status == Success && propdata) { X11_XFree(propdata); propdata = NULL; } } /* Reset the error handler, we're done checking */ X11_XSync(display, False); X11_XSetErrorHandler(handler); if (!wm_window) { #ifdef DEBUG_WINDOW_MANAGER printf("Couldn't get _NET_SUPPORTING_WM_CHECK property\n"); #endif return; } data->net_wm = SDL_TRUE; #ifdef DEBUG_WINDOW_MANAGER wm_name = X11_GetWindowTitle(_this, wm_window); printf("Window manager: %s\n", wm_name); SDL_free(wm_name); #endif } int X11_VideoInit(_THIS) { SDL_VideoData *data = (SDL_VideoData *) _this->driverdata; /* Get the window class name, usually the name of the application */ data->classname = get_classname(); /* Get the process PID to be associated to the window */ data->pid = getpid(); /* I have no idea how random this actually is, or has to be. */ data->window_group = (XID) (((size_t) data->pid) ^ ((size_t) _this)); /* Open a connection to the X input manager */ #ifdef X_HAVE_UTF8_STRING if (SDL_X11_HAVE_UTF8) { /* Set the locale, and call XSetLocaleModifiers before XOpenIM so that Compose keys will work correctly. */ char *prev_locale = setlocale(LC_ALL, NULL); char *prev_xmods = X11_XSetLocaleModifiers(NULL); // Urho3D - bug fix - the default XMODIFIERS should be null instead of empty string const char *new_xmods = 0; #if defined(HAVE_IBUS_IBUS_H) || defined(HAVE_FCITX_FRONTEND_H) const char *env_xmods = SDL_getenv("XMODIFIERS"); #endif SDL_bool has_dbus_ime_support = SDL_FALSE; if (prev_locale) { prev_locale = SDL_strdup(prev_locale); } if (prev_xmods) { prev_xmods = SDL_strdup(prev_xmods); } /* IBus resends some key events that were filtered by XFilterEvents when it is used via XIM which causes issues. Prevent this by forcing @im=none if XMODIFIERS contains @im=ibus. IBus can still be used via the DBus implementation, which also has support for pre-editing. */ #ifdef HAVE_IBUS_IBUS_H if (env_xmods && SDL_strstr(env_xmods, "@im=ibus") != NULL) { has_dbus_ime_support = SDL_TRUE; } #endif #ifdef HAVE_FCITX_FRONTEND_H if (env_xmods && SDL_strstr(env_xmods, "@im=fcitx") != NULL) { has_dbus_ime_support = SDL_TRUE; } #endif if (has_dbus_ime_support) { new_xmods = "@im=none"; } setlocale(LC_ALL, ""); X11_XSetLocaleModifiers(new_xmods); data->im = X11_XOpenIM(data->display, NULL, data->classname, data->classname); /* Reset the locale + X locale modifiers back to how they were, locale first because the X locale modifiers depend on it. */ setlocale(LC_ALL, prev_locale); X11_XSetLocaleModifiers(prev_xmods); if (prev_locale) { SDL_free(prev_locale); } if (prev_xmods) { SDL_free(prev_xmods); } } #endif /* Look up some useful Atoms */ #define GET_ATOM(X) data->X = X11_XInternAtom(data->display, #X, False) GET_ATOM(WM_PROTOCOLS); GET_ATOM(WM_DELETE_WINDOW); GET_ATOM(WM_TAKE_FOCUS); GET_ATOM(_NET_WM_STATE); GET_ATOM(_NET_WM_STATE_HIDDEN); GET_ATOM(_NET_WM_STATE_FOCUSED); GET_ATOM(_NET_WM_STATE_MAXIMIZED_VERT); GET_ATOM(_NET_WM_STATE_MAXIMIZED_HORZ); GET_ATOM(_NET_WM_STATE_FULLSCREEN); GET_ATOM(_NET_WM_STATE_ABOVE); GET_ATOM(_NET_WM_STATE_SKIP_TASKBAR); GET_ATOM(_NET_WM_STATE_SKIP_PAGER); GET_ATOM(_NET_WM_ALLOWED_ACTIONS); GET_ATOM(_NET_WM_ACTION_FULLSCREEN); GET_ATOM(_NET_WM_NAME); GET_ATOM(_NET_WM_ICON_NAME); GET_ATOM(_NET_WM_ICON); GET_ATOM(_NET_WM_PING); GET_ATOM(_NET_WM_WINDOW_OPACITY); GET_ATOM(_NET_WM_USER_TIME); GET_ATOM(_NET_ACTIVE_WINDOW); GET_ATOM(_NET_FRAME_EXTENTS); GET_ATOM(UTF8_STRING); GET_ATOM(PRIMARY); GET_ATOM(XdndEnter); GET_ATOM(XdndPosition); GET_ATOM(XdndStatus); GET_ATOM(XdndTypeList); GET_ATOM(XdndActionCopy); GET_ATOM(XdndDrop); GET_ATOM(XdndFinished); GET_ATOM(XdndSelection); GET_ATOM(XKLAVIER_STATE); /* Detect the window manager */ X11_CheckWindowManager(_this); if (X11_InitModes(_this) < 0) { return -1; } X11_InitXinput2(_this); if (X11_InitKeyboard(_this) != 0) { return -1; } X11_InitMouse(_this); X11_InitTouch(_this); #if SDL_USE_LIBDBUS SDL_DBus_Init(); #endif return 0; } void X11_VideoQuit(_THIS) { SDL_VideoData *data = (SDL_VideoData *) _this->driverdata; SDL_free(data->classname); #ifdef X_HAVE_UTF8_STRING if (data->im) { X11_XCloseIM(data->im); } #endif X11_QuitModes(_this); X11_QuitKeyboard(_this); X11_QuitMouse(_this); X11_QuitTouch(_this); #if SDL_USE_LIBDBUS SDL_DBus_Quit(); #endif } SDL_bool X11_UseDirectColorVisuals(void) { return SDL_getenv("SDL_VIDEO_X11_NODIRECTCOLOR") ? SDL_FALSE : SDL_TRUE; } #endif /* SDL_VIDEO_DRIVER_X11 */ /* vim: set ts=4 sw=4 expandtab: */
{ "language": "C" }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*** *tcstok_s.inl - general implementation of _tcstok_s * * *Purpose: * This file contains the general algorithm for strtok_s and its variants. * ****/ _FUNC_PROLOGUE _CHAR * __cdecl _FUNC_NAME(_CHAR *_String, const _CHAR *_Control, _CHAR **_Context) { _CHAR *token; const _CHAR *ctl; /* validation section */ _VALIDATE_POINTER_ERROR_RETURN(_Context, EINVAL, NULL); _VALIDATE_POINTER_ERROR_RETURN(_Control, EINVAL, NULL); _VALIDATE_CONDITION_ERROR_RETURN(_String != NULL || *_Context != NULL, EINVAL, NULL); /* If string==NULL, continue with previous string */ if (!_String) { _String = *_Context; } /* Find beginning of token (skip over leading delimiters). Note that * there is no token iff this loop sets string to point to the terminal null. */ for ( ; *_String != 0 ; _String++) { for (ctl = _Control; *ctl != 0 && *ctl != *_String; ctl++) ; if (*ctl == 0) { break; } } token = _String; /* Find the end of the token. If it is not the end of the string, * put a null there. */ for ( ; *_String != 0 ; _String++) { for (ctl = _Control; *ctl != 0 && *ctl != *_String; ctl++) ; if (*ctl != 0) { *_String++ = 0; break; } } /* Update the context */ *_Context = _String; /* Determine if a token has been found. */ if (token == _String) { return NULL; } else { return token; } }
{ "language": "C" }
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (c) 2016 Google, Inc */ #include <common.h> DECLARE_GLOBAL_DATA_PTR; int dram_init(void) { gd->ram_size = 1ULL << 31; gd->bd->bi_dram[0].start = 0; gd->bd->bi_dram[0].size = gd->ram_size; return 0; }
{ "language": "C" }
/*- * Copyright (c) 1983, 1992, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* This file implements a subset of the profiling support functions. It has been copied and adapted from mcount.c, gmon.c and gmon.h in the glibc sources. Since we do not have access to a timer interrupt in the simulator the histogram and basic block information is not generated. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> /* Fraction of text space to allocate for histogram counters here, 1/2. */ #define HISTFRACTION 2 /* Fraction of text space to allocate for from hash buckets. The value of HASHFRACTION is based on the minimum number of bytes of separation between two subroutine call points in the object code. Given MIN_SUBR_SEPARATION bytes of separation the value of HASHFRACTION is calculated as: HASHFRACTION = MIN_SUBR_SEPARATION / (2 * sizeof (short) - 1); For example, on the VAX, the shortest two call sequence is: calls $0,(r0) calls $0,(r0) which is separated by only three bytes, thus HASHFRACTION is calculated as: HASHFRACTION = 3 / (2 * 2 - 1) = 1 Note that the division above rounds down, thus if MIN_SUBR_FRACTION is less than three, this algorithm will not work! In practice, however, call instructions are rarely at a minimal distance. Hence, we will define HASHFRACTION to be 2 across all architectures. This saves a reasonable amount of space for profiling data structures without (in practice) sacrificing any granularity. */ #define HASHFRACTION 2 /* Percent of text space to allocate for tostructs. This is a heuristic; we will fail with a warning when profiling programs with a very large number of very small functions, but that's normally OK. 2 is probably still a good value for normal programs. Profiling a test case with 64000 small functions will work if you raise this value to 3 and link statically (which bloats the text size, thus raising the number of arcs expected by the heuristic). */ #define ARCDENSITY 3 /* Always allocate at least this many tostructs. This hides the inadequacy of the ARCDENSITY heuristic, at least for small programs. */ #define MINARCS 50 /* Maximum number of arcs we want to allow. Used to be max representable value of ARCINDEX minus 2, but now that ARCINDEX is a long, that's too large; we don't really want to allow a 48 gigabyte table. The old value of 1<<16 wasn't high enough in practice for large C++ programs; will 1<<20 be adequate for long? FIXME */ #define MAXARCS (1 << 20) #define SCALE_1_TO_1 0x10000L #define GMON_MAGIC "gmon" /* Magic cookie. */ #define GMON_VERSION 1 /* Version number. */ /* General rounding functions. */ #define ROUNDDOWN(x ,y) (((x) / (y)) * (y)) #define ROUNDUP(x, y) ((((x) + (y) - 1) / (y)) * (y)) struct tostruct { unsigned long selfpc; unsigned long count; unsigned long link; }; /* Possible states of profiling. */ enum profiling_state { GMON_PROF_OFF, GMON_PROF_ON, GMON_PROF_BUSY, GMON_PROF_ERROR }; /* The profiling data structures are housed in this structure. */ struct gmonparam { enum profiling_state state; unsigned short * kcount; unsigned long kcountsize; unsigned long * froms; unsigned long fromssize; struct tostruct * tos; unsigned long tossize; long tolimit; unsigned long lowpc; unsigned long highpc; unsigned long textsize; unsigned long hashfraction; long log_hashfraction; }; /* Raw header as it appears in the gmon.out file (without padding). This header always comes first and is then followed by a series records defined below. */ struct gmon_hdr { char cookie[4]; char version[4]; char spare[3 * 4]; }; /* Types of records in this file. */ typedef enum { GMON_TAG_TIME_HIST = 0, GMON_TAG_CG_ARC = 1, } GMON_Record_Tag; struct gmon_cg_arc_record { char tag; /* Set to GMON_TAG_CG_ARC. */ char from_pc[sizeof (char *)]; /* Address within caller's body. */ char self_pc[sizeof (char *)]; /* Address within callee's body. */ char count[4]; /* Number of arc traversals. */ }; /* Forward declarations. */ void _mcount_internal (unsigned long); void _monstartup (unsigned long, unsigned long); void _mcleanup (void); static struct gmonparam _gmonparam; void _mcount_internal (unsigned long frompc) { unsigned long selfpc = frompc; unsigned long * frompcindex; struct tostruct * top; struct tostruct * prevtop; struct gmonparam * p; unsigned long toindex; int i; p = & _gmonparam; /* Check that we are profiling and that we aren't recursively invoked. NB/ This version is not thread-safe. */ if (p->state != GMON_PROF_ON) return; p->state = GMON_PROF_BUSY; /* Check that frompcindex is a reasonable pc value. For example: signal catchers get called from the stack, not from text space. Too bad. */ frompc -= p->lowpc; if (frompc > p->textsize) goto done; i = frompc >> p->log_hashfraction; frompcindex = p->froms + i; toindex = * frompcindex; if (toindex == 0) { /* First time traversing this arc. */ toindex = ++ p->tos[0].link; if (toindex >= p->tolimit) /* Halt further profiling. */ goto overflow; * frompcindex = toindex; top = p->tos + toindex; top->selfpc = selfpc; top->count = 1; top->link = 0; goto done; } top = p->tos + toindex; if (top->selfpc == selfpc) { /* Arc at front of chain: usual case. */ top->count ++; goto done; } /* Have to go looking down chain for it. Top points to what we are looking at, prevtop points to previous top. We know it is not at the head of the chain. */ for (;;) { if (top->link == 0) { /* Top is end of the chain and none of the chain had top->selfpc == selfpc. So we allocate a new tostruct and link it to the head of the chain. */ toindex = ++ p->tos[0].link; if (toindex >= p->tolimit) goto overflow; top = p->tos + toindex; top->selfpc = selfpc; top->count = 1; top->link = * frompcindex; * frompcindex = toindex; goto done; } /* Otherwise, check the next arc on the chain. */ prevtop = top; top = p->tos + top->link; if (top->selfpc == selfpc) { /* There it is. Increment its count move it to the head of the chain. */ top->count ++; toindex = prevtop->link; prevtop->link = top->link; top->link = * frompcindex; * frompcindex = toindex; goto done; } } done: p->state = GMON_PROF_ON; return; overflow: p->state = GMON_PROF_ERROR; return; } void _monstartup (unsigned long lowpc, unsigned long highpc) { char * cp; struct gmonparam * p = & _gmonparam; /* If the calloc() function has been instrumented we must make sure that it is not profiled until we are ready. */ p->state = GMON_PROF_BUSY; /* Round lowpc and highpc to multiples of the density we're using so the rest of the scaling (here and in gprof) stays in ints. */ p->lowpc = ROUNDDOWN (lowpc, HISTFRACTION * sizeof (* p->kcount)); p->highpc = ROUNDUP (highpc, HISTFRACTION * sizeof (* p->kcount)); p->textsize = p->highpc - p->lowpc; p->kcountsize = ROUNDUP (p->textsize / HISTFRACTION, sizeof (*p->froms)); p->hashfraction = HASHFRACTION; p->log_hashfraction = -1; p->log_hashfraction = ffs (p->hashfraction * sizeof (*p->froms)) - 1; p->fromssize = p->textsize / HASHFRACTION; p->tolimit = p->textsize * ARCDENSITY / 100; if (p->tolimit < MINARCS) p->tolimit = MINARCS; else if (p->tolimit > MAXARCS) p->tolimit = MAXARCS; p->tossize = p->tolimit * sizeof (struct tostruct); cp = calloc (p->kcountsize + p->fromssize + p->tossize, 1); if (cp == NULL) { write (2, "monstartup: out of memory\n", 26); p->tos = NULL; p->state = GMON_PROF_ERROR; return; } p->tos = (struct tostruct *) cp; cp += p->tossize; p->kcount = (unsigned short *) cp; cp += p->kcountsize; p->froms = (unsigned long *) cp; p->tos[0].link = 0; p->state = GMON_PROF_ON; } static void write_call_graph (int fd) { #define NARCS_PER_WRITE 32 struct gmon_cg_arc_record raw_arc[NARCS_PER_WRITE] __attribute__ ((aligned (__alignof__ (char *)))); unsigned long from_index; unsigned long to_index; unsigned long from_len; unsigned long frompc; int nfilled; for (nfilled = 0; nfilled < NARCS_PER_WRITE; ++ nfilled) raw_arc[nfilled].tag = GMON_TAG_CG_ARC; nfilled = 0; from_len = _gmonparam.fromssize / sizeof (*_gmonparam.froms); for (from_index = 0; from_index < from_len; ++from_index) { if (_gmonparam.froms[from_index] == 0) continue; frompc = _gmonparam.lowpc; frompc += (from_index * _gmonparam.hashfraction * sizeof (*_gmonparam.froms)); for (to_index = _gmonparam.froms[from_index]; to_index != 0; to_index = _gmonparam.tos[to_index].link) { struct gmon_cg_arc_record * arc = raw_arc + nfilled; memcpy (arc->from_pc, & frompc, sizeof (arc->from_pc)); memcpy (arc->self_pc, & _gmonparam.tos[to_index].selfpc, sizeof (arc->self_pc)); memcpy (arc->count, & _gmonparam.tos[to_index].count, sizeof (arc->count)); if (++ nfilled == NARCS_PER_WRITE) { write (fd, raw_arc, sizeof raw_arc); nfilled = 0; } } } if (nfilled > 0) write (fd, raw_arc, nfilled * sizeof (raw_arc[0])); } #include <errno.h> static void write_gmon (void) { struct gmon_hdr ghdr __attribute__ ((aligned (__alignof__ (int)))); int fd; fd = open ("gmon.out", O_CREAT|O_TRUNC|O_WRONLY, 0666); if (fd < 0) { write (2, "_mcleanup: could not create gmon.out\n", 37); return; } /* Write gmon.out header: */ memset (& ghdr, '\0', sizeof (ghdr)); memcpy (ghdr.cookie, GMON_MAGIC, sizeof (ghdr.cookie)); * (unsigned long *) ghdr.version = GMON_VERSION; write (fd, & ghdr, sizeof (ghdr)); /* We do not have histogram or basic block information, so we do not generate these parts of the gmon.out file. */ /* Write call-graph. */ write_call_graph (fd); close (fd); } void _mcleanup (void) { if (_gmonparam.state != GMON_PROF_ERROR) { _gmonparam.state = GMON_PROF_OFF; write_gmon (); } /* Free the memory. */ if (_gmonparam.tos != NULL) { free (_gmonparam.tos); _gmonparam.tos = NULL; } }
{ "language": "C" }
/* * Xilinx gpio driver * * Copyright 2008 Xilinx, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/init.h> #include <linux/errno.h> #include <linux/module.h> #include <linux/of_device.h> #include <linux/of_platform.h> #include <linux/of_gpio.h> #include <linux/io.h> #include <linux/gpio.h> #include <linux/slab.h> /* Register Offset Definitions */ #define XGPIO_DATA_OFFSET (0x0) /* Data register */ #define XGPIO_TRI_OFFSET (0x4) /* I/O direction register */ struct xgpio_instance { struct of_mm_gpio_chip mmchip; u32 gpio_state; /* GPIO state shadow register */ u32 gpio_dir; /* GPIO direction shadow register */ spinlock_t gpio_lock; /* Lock used for synchronization */ }; /** * xgpio_get - Read the specified signal of the GPIO device. * @gc: Pointer to gpio_chip device structure. * @gpio: GPIO signal number. * * This function reads the specified signal of the GPIO device. It returns 0 if * the signal clear, 1 if signal is set or negative value on error. */ static int xgpio_get(struct gpio_chip *gc, unsigned int gpio) { struct of_mm_gpio_chip *mm_gc = to_of_mm_gpio_chip(gc); return (in_be32(mm_gc->regs + XGPIO_DATA_OFFSET) >> gpio) & 1; } /** * xgpio_set - Write the specified signal of the GPIO device. * @gc: Pointer to gpio_chip device structure. * @gpio: GPIO signal number. * @val: Value to be written to specified signal. * * This function writes the specified value in to the specified signal of the * GPIO device. */ static void xgpio_set(struct gpio_chip *gc, unsigned int gpio, int val) { unsigned long flags; struct of_mm_gpio_chip *mm_gc = to_of_mm_gpio_chip(gc); struct xgpio_instance *chip = container_of(mm_gc, struct xgpio_instance, mmchip); spin_lock_irqsave(&chip->gpio_lock, flags); /* Write to GPIO signal and set its direction to output */ if (val) chip->gpio_state |= 1 << gpio; else chip->gpio_state &= ~(1 << gpio); out_be32(mm_gc->regs + XGPIO_DATA_OFFSET, chip->gpio_state); spin_unlock_irqrestore(&chip->gpio_lock, flags); } /** * xgpio_dir_in - Set the direction of the specified GPIO signal as input. * @gc: Pointer to gpio_chip device structure. * @gpio: GPIO signal number. * * This function sets the direction of specified GPIO signal as input. * It returns 0 if direction of GPIO signals is set as input otherwise it * returns negative error value. */ static int xgpio_dir_in(struct gpio_chip *gc, unsigned int gpio) { unsigned long flags; struct of_mm_gpio_chip *mm_gc = to_of_mm_gpio_chip(gc); struct xgpio_instance *chip = container_of(mm_gc, struct xgpio_instance, mmchip); spin_lock_irqsave(&chip->gpio_lock, flags); /* Set the GPIO bit in shadow register and set direction as input */ chip->gpio_dir |= (1 << gpio); out_be32(mm_gc->regs + XGPIO_TRI_OFFSET, chip->gpio_dir); spin_unlock_irqrestore(&chip->gpio_lock, flags); return 0; } /** * xgpio_dir_out - Set the direction of the specified GPIO signal as output. * @gc: Pointer to gpio_chip device structure. * @gpio: GPIO signal number. * @val: Value to be written to specified signal. * * This function sets the direction of specified GPIO signal as output. If all * GPIO signals of GPIO chip is configured as input then it returns * error otherwise it returns 0. */ static int xgpio_dir_out(struct gpio_chip *gc, unsigned int gpio, int val) { unsigned long flags; struct of_mm_gpio_chip *mm_gc = to_of_mm_gpio_chip(gc); struct xgpio_instance *chip = container_of(mm_gc, struct xgpio_instance, mmchip); spin_lock_irqsave(&chip->gpio_lock, flags); /* Write state of GPIO signal */ if (val) chip->gpio_state |= 1 << gpio; else chip->gpio_state &= ~(1 << gpio); out_be32(mm_gc->regs + XGPIO_DATA_OFFSET, chip->gpio_state); /* Clear the GPIO bit in shadow register and set direction as output */ chip->gpio_dir &= (~(1 << gpio)); out_be32(mm_gc->regs + XGPIO_TRI_OFFSET, chip->gpio_dir); spin_unlock_irqrestore(&chip->gpio_lock, flags); return 0; } /** * xgpio_save_regs - Set initial values of GPIO pins * @mm_gc: pointer to memory mapped GPIO chip structure */ static void xgpio_save_regs(struct of_mm_gpio_chip *mm_gc) { struct xgpio_instance *chip = container_of(mm_gc, struct xgpio_instance, mmchip); out_be32(mm_gc->regs + XGPIO_DATA_OFFSET, chip->gpio_state); out_be32(mm_gc->regs + XGPIO_TRI_OFFSET, chip->gpio_dir); } /** * xgpio_of_probe - Probe method for the GPIO device. * @np: pointer to device tree node * * This function probes the GPIO device in the device tree. It initializes the * driver data structure. It returns 0, if the driver is bound to the GPIO * device, or a negative value if there is an error. */ static int __devinit xgpio_of_probe(struct device_node *np) { struct xgpio_instance *chip; int status = 0; const u32 *tree_info; chip = kzalloc(sizeof(*chip), GFP_KERNEL); if (!chip) return -ENOMEM; /* Update GPIO state shadow register with default value */ tree_info = of_get_property(np, "xlnx,dout-default", NULL); if (tree_info) chip->gpio_state = be32_to_cpup(tree_info); /* Update GPIO direction shadow register with default value */ chip->gpio_dir = 0xFFFFFFFF; /* By default, all pins are inputs */ tree_info = of_get_property(np, "xlnx,tri-default", NULL); if (tree_info) chip->gpio_dir = be32_to_cpup(tree_info); /* Check device node and parent device node for device width */ chip->mmchip.gc.ngpio = 32; /* By default assume full GPIO controller */ tree_info = of_get_property(np, "xlnx,gpio-width", NULL); if (!tree_info) tree_info = of_get_property(np->parent, "xlnx,gpio-width", NULL); if (tree_info) chip->mmchip.gc.ngpio = be32_to_cpup(tree_info); spin_lock_init(&chip->gpio_lock); chip->mmchip.gc.direction_input = xgpio_dir_in; chip->mmchip.gc.direction_output = xgpio_dir_out; chip->mmchip.gc.get = xgpio_get; chip->mmchip.gc.set = xgpio_set; chip->mmchip.save_regs = xgpio_save_regs; /* Call the OF gpio helper to setup and register the GPIO device */ status = of_mm_gpiochip_add(np, &chip->mmchip); if (status) { kfree(chip); pr_err("%s: error in probe function with status %d\n", np->full_name, status); return status; } return 0; } static struct of_device_id xgpio_of_match[] __devinitdata = { { .compatible = "xlnx,xps-gpio-1.00.a", }, { /* end of list */ }, }; static int __init xgpio_init(void) { struct device_node *np; for_each_matching_node(np, xgpio_of_match) xgpio_of_probe(np); return 0; } /* Make sure we get initialized before anyone else tries to use us */ subsys_initcall(xgpio_init); /* No exit call at the moment as we cannot unregister of GPIO chips */ MODULE_AUTHOR("Xilinx, Inc."); MODULE_DESCRIPTION("Xilinx GPIO driver"); MODULE_LICENSE("GPL");
{ "language": "C" }
/* Copyright (c) 2012-2013, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/module.h> #include <linux/types.h> #include <linux/net.h> #include <linux/socket.h> #include <linux/errno.h> #include <linux/mm.h> #include <linux/poll.h> #include <linux/fcntl.h> #include <linux/gfp.h> #include <linux/uaccess.h> #include <linux/kernel.h> #include <linux/msm_ipc.h> #include <linux/rwsem.h> #include <asm/uaccess.h> #include <net/sock.h> #include "ipc_router.h" #include "msm_ipc_router_security.h" #define IRSC_COMPLETION_TIMEOUT_MS 30000 #define SEC_RULES_HASH_SZ 32 #ifndef SIZE_MAX #define SIZE_MAX ((size_t)-1) #endif struct security_rule { struct list_head list; uint32_t service_id; uint32_t instance_id; unsigned reserved; int num_group_info; gid_t *group_id; }; static DECLARE_RWSEM(security_rules_lock_lha4); static struct list_head security_rules[SEC_RULES_HASH_SZ]; static DECLARE_COMPLETION(irsc_completion); /** * wait_for_irsc_completion() - Wait for IPC Router Security Configuration * (IRSC) to complete */ void wait_for_irsc_completion(void) { unsigned long rem_jiffies; do { rem_jiffies = wait_for_completion_timeout(&irsc_completion, msecs_to_jiffies(IRSC_COMPLETION_TIMEOUT_MS)); if (rem_jiffies) return; pr_err("%s: waiting for IPC Security Conf.\n", __func__); } while (1); } /** * signal_irsc_completion() - Signal the completion of IRSC */ void signal_irsc_completion(void) { complete_all(&irsc_completion); } /** * check_permisions() - Check whether the process has permissions to * create an interface handle with IPC Router * * @return: true if the process has permissions, else false. */ int check_permissions(void) { int rc = 0; if (!current_euid() || in_egroup_p(AID_NET_RAW)) rc = 1; return rc; } EXPORT_SYMBOL(check_permissions); /** * msm_ipc_config_sec_rules() - Add a security rule to the database * @arg: Pointer to the buffer containing the rule. * * @return: 0 if successfully added, < 0 for error. * * A security rule is defined using <Service_ID: Group_ID> tuple. The rule * implies that a user-space process in order to send a QMI message to * service Service_ID should belong to the Linux group Group_ID. */ int msm_ipc_config_sec_rules(void *arg) { struct config_sec_rules_args sec_rules_arg; struct security_rule *rule, *temp_rule; int key; size_t group_info_sz; int ret; if (current_euid()) return -EPERM; ret = copy_from_user(&sec_rules_arg, (void *)arg, sizeof(sec_rules_arg)); if (ret) return -EFAULT; if (sec_rules_arg.num_group_info <= 0) return -EINVAL; if (sec_rules_arg.num_group_info > (SIZE_MAX / sizeof(gid_t))) { pr_err("%s: Integer Overflow %d * %d\n", __func__, sizeof(gid_t), sec_rules_arg.num_group_info); return -EINVAL; } group_info_sz = sec_rules_arg.num_group_info * sizeof(gid_t); rule = kzalloc(sizeof(struct security_rule), GFP_KERNEL); if (!rule) { pr_err("%s: security_rule alloc failed\n", __func__); return -ENOMEM; } rule->group_id = kzalloc(group_info_sz, GFP_KERNEL); if (!rule->group_id) { pr_err("%s: group_id alloc failed\n", __func__); kfree(rule); return -ENOMEM; } rule->service_id = sec_rules_arg.service_id; rule->instance_id = sec_rules_arg.instance_id; rule->reserved = sec_rules_arg.reserved; rule->num_group_info = sec_rules_arg.num_group_info; ret = copy_from_user(rule->group_id, ((void *)(arg + sizeof(sec_rules_arg))), group_info_sz); if (ret) { kfree(rule->group_id); kfree(rule); return -EFAULT; } key = rule->service_id & (SEC_RULES_HASH_SZ - 1); down_write(&security_rules_lock_lha4); if (rule->service_id == ALL_SERVICE) { temp_rule = list_first_entry(&security_rules[key], struct security_rule, list); list_del(&temp_rule->list); kfree(temp_rule->group_id); kfree(temp_rule); } list_add_tail(&rule->list, &security_rules[key]); up_write(&security_rules_lock_lha4); if (rule->service_id == ALL_SERVICE) msm_ipc_sync_default_sec_rule((void *)rule); else msm_ipc_sync_sec_rule(rule->service_id, rule->instance_id, (void *)rule); return 0; } EXPORT_SYMBOL(msm_ipc_config_sec_rules); /** * msm_ipc_add_default_rule() - Add default security rule * * @return: 0 on success, < 0 on error/ * * This function is used to ensure the basic security, if there is no * security rule defined for a service. It can be overwritten by the * default security rule from user-space script. */ static int msm_ipc_add_default_rule(void) { struct security_rule *rule; int key; rule = kzalloc(sizeof(struct security_rule), GFP_KERNEL); if (!rule) { pr_err("%s: security_rule alloc failed\n", __func__); return -ENOMEM; } rule->group_id = kzalloc(sizeof(int), GFP_KERNEL); if (!rule->group_id) { pr_err("%s: group_id alloc failed\n", __func__); kfree(rule); return -ENOMEM; } rule->service_id = ALL_SERVICE; rule->instance_id = ALL_INSTANCE; rule->num_group_info = 1; *(rule->group_id) = AID_NET_RAW; down_write(&security_rules_lock_lha4); key = (ALL_SERVICE & (SEC_RULES_HASH_SZ - 1)); list_add_tail(&rule->list, &security_rules[key]); up_write(&security_rules_lock_lha4); return 0; } /** * msm_ipc_get_security_rule() - Get the security rule corresponding to a * service * @service_id: Service ID for which the rule has to be got. * @instance_id: Instance ID for which the rule has to be got. * * @return: Returns the rule info on success, NULL on error. * * This function is used when the service comes up and gets registered with * the IPC Router. */ void *msm_ipc_get_security_rule(uint32_t service_id, uint32_t instance_id) { int key; struct security_rule *rule; key = (service_id & (SEC_RULES_HASH_SZ - 1)); down_read(&security_rules_lock_lha4); /* Return the rule for a specific <service:instance>, if found. */ list_for_each_entry(rule, &security_rules[key], list) { if ((rule->service_id == service_id) && (rule->instance_id == instance_id)) { up_read(&security_rules_lock_lha4); return (void *)rule; } } /* Return the rule for a specific service, if found. */ list_for_each_entry(rule, &security_rules[key], list) { if ((rule->service_id == service_id) && (rule->instance_id == ALL_INSTANCE)) { up_read(&security_rules_lock_lha4); return (void *)rule; } } /* Return the default rule, if no rule defined for a service. */ key = (ALL_SERVICE & (SEC_RULES_HASH_SZ - 1)); list_for_each_entry(rule, &security_rules[key], list) { if ((rule->service_id == ALL_SERVICE) && (rule->instance_id == ALL_INSTANCE)) { up_read(&security_rules_lock_lha4); return (void *)rule; } } up_read(&security_rules_lock_lha4); return NULL; } EXPORT_SYMBOL(msm_ipc_get_security_rule); /** * msm_ipc_check_send_permissions() - Check if the sendng process has * permissions specified as per the rule * @data: Security rule to be checked. * * @return: true if the process has permissions, else false. * * This function is used to check if the current executing process has * permissions to send message to the remote entity. The security rule * corresponding to the remote entity is specified by "data" parameter */ int msm_ipc_check_send_permissions(void *data) { int i; struct security_rule *rule = (struct security_rule *)data; /* Source/Sender is Root user */ if (!current_euid()) return 1; /* Destination has no rules defined, possibly a client. */ if (!rule) return 1; for (i = 0; i < rule->num_group_info; i++) { if (in_egroup_p(rule->group_id[i])) return 1; } return 0; } EXPORT_SYMBOL(msm_ipc_check_send_permissions); /** * msm_ipc_router_security_init() - Initialize the security rule database * * @return: 0 if successful, < 0 for error. */ int msm_ipc_router_security_init(void) { int i; for (i = 0; i < SEC_RULES_HASH_SZ; i++) INIT_LIST_HEAD(&security_rules[i]); msm_ipc_add_default_rule(); return 0; } EXPORT_SYMBOL(msm_ipc_router_security_init);
{ "language": "C" }
/* * Copyright 2015 Red Hat Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * Authors: Ben Skeggs */ #include "gk104.h" #include "changk104.h" #include <nvif/class.h> int gm200_fifo_pbdma_nr(struct gk104_fifo *fifo) { struct nvkm_device *device = fifo->base.engine.subdev.device; return nvkm_rd32(device, 0x002004) & 0x000000ff; } const struct gk104_fifo_pbdma_func gm200_fifo_pbdma = { .nr = gm200_fifo_pbdma_nr, .init = gk104_fifo_pbdma_init, .init_timeout = gk208_fifo_pbdma_init_timeout, }; static const struct gk104_fifo_func gm200_fifo = { .intr.fault = gm107_fifo_intr_fault, .pbdma = &gm200_fifo_pbdma, .fault.access = gk104_fifo_fault_access, .fault.engine = gm107_fifo_fault_engine, .fault.reason = gk104_fifo_fault_reason, .fault.hubclient = gk104_fifo_fault_hubclient, .fault.gpcclient = gk104_fifo_fault_gpcclient, .runlist = &gm107_fifo_runlist, .chan = {{0,0,MAXWELL_CHANNEL_GPFIFO_A}, gk104_fifo_gpfifo_new }, }; int gm200_fifo_new(struct nvkm_device *device, int index, struct nvkm_fifo **pfifo) { return gk104_fifo_new_(&gm200_fifo, device, index, 4096, pfifo); }
{ "language": "C" }
/* * Copyright 2002-2007 Haiku Inc. All rights reserved. * Distributed under the terms of the MIT license. */ #ifndef DRIVE_SETUP_H #define DRIVE_SETUP_H #include <Application.h> #include <Catalog.h> #include <Message.h> class BFile; class MainWindow; class DriveSetup : public BApplication { public: DriveSetup(); virtual ~DriveSetup(); virtual void ReadyToRun(); virtual bool QuitRequested(); private: status_t _StoreSettings(); status_t _RestoreSettings(); status_t _GetSettingsFile(BFile& file, bool forWriting) const; MainWindow* fWindow; BMessage fSettings; }; #endif // DRIVE_SETUP_H
{ "language": "C" }
/* * Copyright (C) 2016 Texas Instruments * Author: Tomi Valkeinen <tomi.valkeinen@ti.com> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __OMAP_DRM_DSS_H #define __OMAP_DRM_DSS_H #include <linux/list.h> #include <linux/kobject.h> #include <linux/device.h> #include <linux/interrupt.h> #include <video/videomode.h> #include <linux/platform_data/omapdss.h> #include <uapi/drm/drm_mode.h> #define DISPC_IRQ_FRAMEDONE (1 << 0) #define DISPC_IRQ_VSYNC (1 << 1) #define DISPC_IRQ_EVSYNC_EVEN (1 << 2) #define DISPC_IRQ_EVSYNC_ODD (1 << 3) #define DISPC_IRQ_ACBIAS_COUNT_STAT (1 << 4) #define DISPC_IRQ_PROG_LINE_NUM (1 << 5) #define DISPC_IRQ_GFX_FIFO_UNDERFLOW (1 << 6) #define DISPC_IRQ_GFX_END_WIN (1 << 7) #define DISPC_IRQ_PAL_GAMMA_MASK (1 << 8) #define DISPC_IRQ_OCP_ERR (1 << 9) #define DISPC_IRQ_VID1_FIFO_UNDERFLOW (1 << 10) #define DISPC_IRQ_VID1_END_WIN (1 << 11) #define DISPC_IRQ_VID2_FIFO_UNDERFLOW (1 << 12) #define DISPC_IRQ_VID2_END_WIN (1 << 13) #define DISPC_IRQ_SYNC_LOST (1 << 14) #define DISPC_IRQ_SYNC_LOST_DIGIT (1 << 15) #define DISPC_IRQ_WAKEUP (1 << 16) #define DISPC_IRQ_SYNC_LOST2 (1 << 17) #define DISPC_IRQ_VSYNC2 (1 << 18) #define DISPC_IRQ_VID3_END_WIN (1 << 19) #define DISPC_IRQ_VID3_FIFO_UNDERFLOW (1 << 20) #define DISPC_IRQ_ACBIAS_COUNT_STAT2 (1 << 21) #define DISPC_IRQ_FRAMEDONE2 (1 << 22) #define DISPC_IRQ_FRAMEDONEWB (1 << 23) #define DISPC_IRQ_FRAMEDONETV (1 << 24) #define DISPC_IRQ_WBBUFFEROVERFLOW (1 << 25) #define DISPC_IRQ_WBUNCOMPLETEERROR (1 << 26) #define DISPC_IRQ_SYNC_LOST3 (1 << 27) #define DISPC_IRQ_VSYNC3 (1 << 28) #define DISPC_IRQ_ACBIAS_COUNT_STAT3 (1 << 29) #define DISPC_IRQ_FRAMEDONE3 (1 << 30) struct omap_dss_device; struct omap_overlay_manager; struct dss_lcd_mgr_config; struct snd_aes_iec958; struct snd_cea_861_aud_if; struct hdmi_avi_infoframe; enum omap_display_type { OMAP_DISPLAY_TYPE_NONE = 0, OMAP_DISPLAY_TYPE_DPI = 1 << 0, OMAP_DISPLAY_TYPE_DBI = 1 << 1, OMAP_DISPLAY_TYPE_SDI = 1 << 2, OMAP_DISPLAY_TYPE_DSI = 1 << 3, OMAP_DISPLAY_TYPE_VENC = 1 << 4, OMAP_DISPLAY_TYPE_HDMI = 1 << 5, OMAP_DISPLAY_TYPE_DVI = 1 << 6, }; enum omap_plane { OMAP_DSS_GFX = 0, OMAP_DSS_VIDEO1 = 1, OMAP_DSS_VIDEO2 = 2, OMAP_DSS_VIDEO3 = 3, OMAP_DSS_WB = 4, }; enum omap_channel { OMAP_DSS_CHANNEL_LCD = 0, OMAP_DSS_CHANNEL_DIGIT = 1, OMAP_DSS_CHANNEL_LCD2 = 2, OMAP_DSS_CHANNEL_LCD3 = 3, OMAP_DSS_CHANNEL_WB = 4, }; enum omap_color_mode { OMAP_DSS_COLOR_CLUT1 = 1 << 0, /* BITMAP 1 */ OMAP_DSS_COLOR_CLUT2 = 1 << 1, /* BITMAP 2 */ OMAP_DSS_COLOR_CLUT4 = 1 << 2, /* BITMAP 4 */ OMAP_DSS_COLOR_CLUT8 = 1 << 3, /* BITMAP 8 */ OMAP_DSS_COLOR_RGB12U = 1 << 4, /* RGB12, 16-bit container */ OMAP_DSS_COLOR_ARGB16 = 1 << 5, /* ARGB16 */ OMAP_DSS_COLOR_RGB16 = 1 << 6, /* RGB16 */ OMAP_DSS_COLOR_RGB24U = 1 << 7, /* RGB24, 32-bit container */ OMAP_DSS_COLOR_RGB24P = 1 << 8, /* RGB24, 24-bit container */ OMAP_DSS_COLOR_YUV2 = 1 << 9, /* YUV2 4:2:2 co-sited */ OMAP_DSS_COLOR_UYVY = 1 << 10, /* UYVY 4:2:2 co-sited */ OMAP_DSS_COLOR_ARGB32 = 1 << 11, /* ARGB32 */ OMAP_DSS_COLOR_RGBA32 = 1 << 12, /* RGBA32 */ OMAP_DSS_COLOR_RGBX32 = 1 << 13, /* RGBx32 */ OMAP_DSS_COLOR_NV12 = 1 << 14, /* NV12 format: YUV 4:2:0 */ OMAP_DSS_COLOR_RGBA16 = 1 << 15, /* RGBA16 - 4444 */ OMAP_DSS_COLOR_RGBX16 = 1 << 16, /* RGBx16 - 4444 */ OMAP_DSS_COLOR_ARGB16_1555 = 1 << 17, /* ARGB16 - 1555 */ OMAP_DSS_COLOR_XRGB16_1555 = 1 << 18, /* xRGB16 - 1555 */ }; enum omap_dss_load_mode { OMAP_DSS_LOAD_CLUT_AND_FRAME = 0, OMAP_DSS_LOAD_CLUT_ONLY = 1, OMAP_DSS_LOAD_FRAME_ONLY = 2, OMAP_DSS_LOAD_CLUT_ONCE_FRAME = 3, }; enum omap_dss_trans_key_type { OMAP_DSS_COLOR_KEY_GFX_DST = 0, OMAP_DSS_COLOR_KEY_VID_SRC = 1, }; enum omap_rfbi_te_mode { OMAP_DSS_RFBI_TE_MODE_1 = 1, OMAP_DSS_RFBI_TE_MODE_2 = 2, }; enum omap_dss_signal_level { OMAPDSS_SIG_ACTIVE_LOW, OMAPDSS_SIG_ACTIVE_HIGH, }; enum omap_dss_signal_edge { OMAPDSS_DRIVE_SIG_FALLING_EDGE, OMAPDSS_DRIVE_SIG_RISING_EDGE, }; enum omap_dss_venc_type { OMAP_DSS_VENC_TYPE_COMPOSITE, OMAP_DSS_VENC_TYPE_SVIDEO, }; enum omap_dss_dsi_pixel_format { OMAP_DSS_DSI_FMT_RGB888, OMAP_DSS_DSI_FMT_RGB666, OMAP_DSS_DSI_FMT_RGB666_PACKED, OMAP_DSS_DSI_FMT_RGB565, }; enum omap_dss_dsi_mode { OMAP_DSS_DSI_CMD_MODE = 0, OMAP_DSS_DSI_VIDEO_MODE, }; enum omap_display_caps { OMAP_DSS_DISPLAY_CAP_MANUAL_UPDATE = 1 << 0, OMAP_DSS_DISPLAY_CAP_TEAR_ELIM = 1 << 1, }; enum omap_dss_display_state { OMAP_DSS_DISPLAY_DISABLED = 0, OMAP_DSS_DISPLAY_ACTIVE, }; enum omap_dss_rotation_type { OMAP_DSS_ROT_DMA = 1 << 0, OMAP_DSS_ROT_VRFB = 1 << 1, OMAP_DSS_ROT_TILER = 1 << 2, }; /* clockwise rotation angle */ enum omap_dss_rotation_angle { OMAP_DSS_ROT_0 = 0, OMAP_DSS_ROT_90 = 1, OMAP_DSS_ROT_180 = 2, OMAP_DSS_ROT_270 = 3, }; enum omap_overlay_caps { OMAP_DSS_OVL_CAP_SCALE = 1 << 0, OMAP_DSS_OVL_CAP_GLOBAL_ALPHA = 1 << 1, OMAP_DSS_OVL_CAP_PRE_MULT_ALPHA = 1 << 2, OMAP_DSS_OVL_CAP_ZORDER = 1 << 3, OMAP_DSS_OVL_CAP_POS = 1 << 4, OMAP_DSS_OVL_CAP_REPLICATION = 1 << 5, }; enum omap_overlay_manager_caps { OMAP_DSS_DUMMY_VALUE, /* add a dummy value to prevent compiler error */ }; enum omap_dss_clk_source { OMAP_DSS_CLK_SRC_FCK = 0, /* OMAP2/3: DSS1_ALWON_FCLK * OMAP4: DSS_FCLK */ OMAP_DSS_CLK_SRC_DSI_PLL_HSDIV_DISPC, /* OMAP3: DSI1_PLL_FCLK * OMAP4: PLL1_CLK1 */ OMAP_DSS_CLK_SRC_DSI_PLL_HSDIV_DSI, /* OMAP3: DSI2_PLL_FCLK * OMAP4: PLL1_CLK2 */ OMAP_DSS_CLK_SRC_DSI2_PLL_HSDIV_DISPC, /* OMAP4: PLL2_CLK1 */ OMAP_DSS_CLK_SRC_DSI2_PLL_HSDIV_DSI, /* OMAP4: PLL2_CLK2 */ }; enum omap_hdmi_flags { OMAP_HDMI_SDA_SCL_EXTERNAL_PULLUP = 1 << 0, }; enum omap_dss_output_id { OMAP_DSS_OUTPUT_DPI = 1 << 0, OMAP_DSS_OUTPUT_DBI = 1 << 1, OMAP_DSS_OUTPUT_SDI = 1 << 2, OMAP_DSS_OUTPUT_DSI1 = 1 << 3, OMAP_DSS_OUTPUT_DSI2 = 1 << 4, OMAP_DSS_OUTPUT_VENC = 1 << 5, OMAP_DSS_OUTPUT_HDMI = 1 << 6, }; /* RFBI */ struct rfbi_timings { int cs_on_time; int cs_off_time; int we_on_time; int we_off_time; int re_on_time; int re_off_time; int we_cycle_time; int re_cycle_time; int cs_pulse_width; int access_time; int clk_div; u32 tim[5]; /* set by rfbi_convert_timings() */ int converted; }; /* DSI */ enum omap_dss_dsi_trans_mode { /* Sync Pulses: both sync start and end packets sent */ OMAP_DSS_DSI_PULSE_MODE, /* Sync Events: only sync start packets sent */ OMAP_DSS_DSI_EVENT_MODE, /* Burst: only sync start packets sent, pixels are time compressed */ OMAP_DSS_DSI_BURST_MODE, }; struct omap_dss_dsi_videomode_timings { unsigned long hsclk; unsigned ndl; unsigned bitspp; /* pixels */ u16 hact; /* lines */ u16 vact; /* DSI video mode blanking data */ /* Unit: byte clock cycles */ u16 hss; u16 hsa; u16 hse; u16 hfp; u16 hbp; /* Unit: line clocks */ u16 vsa; u16 vfp; u16 vbp; /* DSI blanking modes */ int blanking_mode; int hsa_blanking_mode; int hbp_blanking_mode; int hfp_blanking_mode; enum omap_dss_dsi_trans_mode trans_mode; bool ddr_clk_always_on; int window_sync; }; struct omap_dss_dsi_config { enum omap_dss_dsi_mode mode; enum omap_dss_dsi_pixel_format pixel_format; const struct videomode *vm; unsigned long hs_clk_min, hs_clk_max; unsigned long lp_clk_min, lp_clk_max; bool ddr_clk_always_on; enum omap_dss_dsi_trans_mode trans_mode; }; /* Hardcoded videomodes for tv. Venc only uses these to * identify the mode, and does not actually use the configs * itself. However, the configs should be something that * a normal monitor can also show */ extern const struct videomode omap_dss_pal_vm; extern const struct videomode omap_dss_ntsc_vm; struct omap_dss_cpr_coefs { s16 rr, rg, rb; s16 gr, gg, gb; s16 br, bg, bb; }; struct omap_overlay_info { dma_addr_t paddr; dma_addr_t p_uv_addr; /* for NV12 format */ u16 screen_width; u16 width; u16 height; enum omap_color_mode color_mode; u8 rotation; enum omap_dss_rotation_type rotation_type; bool mirror; u16 pos_x; u16 pos_y; u16 out_width; /* if 0, out_width == width */ u16 out_height; /* if 0, out_height == height */ u8 global_alpha; u8 pre_mult_alpha; u8 zorder; }; struct omap_overlay { struct kobject kobj; struct list_head list; /* static fields */ const char *name; enum omap_plane id; enum omap_color_mode supported_modes; enum omap_overlay_caps caps; /* dynamic fields */ struct omap_overlay_manager *manager; /* * The following functions do not block: * * is_enabled * set_overlay_info * get_overlay_info * * The rest of the functions may block and cannot be called from * interrupt context */ int (*enable)(struct omap_overlay *ovl); int (*disable)(struct omap_overlay *ovl); bool (*is_enabled)(struct omap_overlay *ovl); int (*set_manager)(struct omap_overlay *ovl, struct omap_overlay_manager *mgr); int (*unset_manager)(struct omap_overlay *ovl); int (*set_overlay_info)(struct omap_overlay *ovl, struct omap_overlay_info *info); void (*get_overlay_info)(struct omap_overlay *ovl, struct omap_overlay_info *info); int (*wait_for_go)(struct omap_overlay *ovl); struct omap_dss_device *(*get_device)(struct omap_overlay *ovl); }; struct omap_overlay_manager_info { u32 default_color; enum omap_dss_trans_key_type trans_key_type; u32 trans_key; bool trans_enabled; bool partial_alpha_enabled; bool cpr_enable; struct omap_dss_cpr_coefs cpr_coefs; }; struct omap_overlay_manager { struct kobject kobj; /* static fields */ const char *name; enum omap_channel id; enum omap_overlay_manager_caps caps; struct list_head overlays; enum omap_display_type supported_displays; enum omap_dss_output_id supported_outputs; /* dynamic fields */ struct omap_dss_device *output; /* * The following functions do not block: * * set_manager_info * get_manager_info * apply * * The rest of the functions may block and cannot be called from * interrupt context */ int (*set_output)(struct omap_overlay_manager *mgr, struct omap_dss_device *output); int (*unset_output)(struct omap_overlay_manager *mgr); int (*set_manager_info)(struct omap_overlay_manager *mgr, struct omap_overlay_manager_info *info); void (*get_manager_info)(struct omap_overlay_manager *mgr, struct omap_overlay_manager_info *info); int (*apply)(struct omap_overlay_manager *mgr); int (*wait_for_go)(struct omap_overlay_manager *mgr); int (*wait_for_vsync)(struct omap_overlay_manager *mgr); struct omap_dss_device *(*get_device)(struct omap_overlay_manager *mgr); }; /* 22 pins means 1 clk lane and 10 data lanes */ #define OMAP_DSS_MAX_DSI_PINS 22 struct omap_dsi_pin_config { int num_pins; /* * pin numbers in the following order: * clk+, clk- * data1+, data1- * data2+, data2- * ... */ int pins[OMAP_DSS_MAX_DSI_PINS]; }; struct omap_dss_writeback_info { u32 paddr; u32 p_uv_addr; u16 buf_width; u16 width; u16 height; enum omap_color_mode color_mode; u8 rotation; enum omap_dss_rotation_type rotation_type; bool mirror; u8 pre_mult_alpha; }; struct omapdss_dpi_ops { int (*connect)(struct omap_dss_device *dssdev, struct omap_dss_device *dst); void (*disconnect)(struct omap_dss_device *dssdev, struct omap_dss_device *dst); int (*enable)(struct omap_dss_device *dssdev); void (*disable)(struct omap_dss_device *dssdev); int (*check_timings)(struct omap_dss_device *dssdev, struct videomode *vm); void (*set_timings)(struct omap_dss_device *dssdev, struct videomode *vm); void (*get_timings)(struct omap_dss_device *dssdev, struct videomode *vm); void (*set_data_lines)(struct omap_dss_device *dssdev, int data_lines); }; struct omapdss_sdi_ops { int (*connect)(struct omap_dss_device *dssdev, struct omap_dss_device *dst); void (*disconnect)(struct omap_dss_device *dssdev, struct omap_dss_device *dst); int (*enable)(struct omap_dss_device *dssdev); void (*disable)(struct omap_dss_device *dssdev); int (*check_timings)(struct omap_dss_device *dssdev, struct videomode *vm); void (*set_timings)(struct omap_dss_device *dssdev, struct videomode *vm); void (*get_timings)(struct omap_dss_device *dssdev, struct videomode *vm); void (*set_datapairs)(struct omap_dss_device *dssdev, int datapairs); }; struct omapdss_dvi_ops { int (*connect)(struct omap_dss_device *dssdev, struct omap_dss_device *dst); void (*disconnect)(struct omap_dss_device *dssdev, struct omap_dss_device *dst); int (*enable)(struct omap_dss_device *dssdev); void (*disable)(struct omap_dss_device *dssdev); int (*check_timings)(struct omap_dss_device *dssdev, struct videomode *vm); void (*set_timings)(struct omap_dss_device *dssdev, struct videomode *vm); void (*get_timings)(struct omap_dss_device *dssdev, struct videomode *vm); }; struct omapdss_atv_ops { int (*connect)(struct omap_dss_device *dssdev, struct omap_dss_device *dst); void (*disconnect)(struct omap_dss_device *dssdev, struct omap_dss_device *dst); int (*enable)(struct omap_dss_device *dssdev); void (*disable)(struct omap_dss_device *dssdev); int (*check_timings)(struct omap_dss_device *dssdev, struct videomode *vm); void (*set_timings)(struct omap_dss_device *dssdev, struct videomode *vm); void (*get_timings)(struct omap_dss_device *dssdev, struct videomode *vm); void (*set_type)(struct omap_dss_device *dssdev, enum omap_dss_venc_type type); void (*invert_vid_out_polarity)(struct omap_dss_device *dssdev, bool invert_polarity); int (*set_wss)(struct omap_dss_device *dssdev, u32 wss); u32 (*get_wss)(struct omap_dss_device *dssdev); }; struct omapdss_hdmi_ops { int (*connect)(struct omap_dss_device *dssdev, struct omap_dss_device *dst); void (*disconnect)(struct omap_dss_device *dssdev, struct omap_dss_device *dst); int (*enable)(struct omap_dss_device *dssdev); void (*disable)(struct omap_dss_device *dssdev); int (*check_timings)(struct omap_dss_device *dssdev, struct videomode *vm); void (*set_timings)(struct omap_dss_device *dssdev, struct videomode *vm); void (*get_timings)(struct omap_dss_device *dssdev, struct videomode *vm); int (*read_edid)(struct omap_dss_device *dssdev, u8 *buf, int len); bool (*detect)(struct omap_dss_device *dssdev); int (*set_hdmi_mode)(struct omap_dss_device *dssdev, bool hdmi_mode); int (*set_infoframe)(struct omap_dss_device *dssdev, const struct hdmi_avi_infoframe *avi); }; struct omapdss_dsi_ops { int (*connect)(struct omap_dss_device *dssdev, struct omap_dss_device *dst); void (*disconnect)(struct omap_dss_device *dssdev, struct omap_dss_device *dst); int (*enable)(struct omap_dss_device *dssdev); void (*disable)(struct omap_dss_device *dssdev, bool disconnect_lanes, bool enter_ulps); /* bus configuration */ int (*set_config)(struct omap_dss_device *dssdev, const struct omap_dss_dsi_config *cfg); int (*configure_pins)(struct omap_dss_device *dssdev, const struct omap_dsi_pin_config *pin_cfg); void (*enable_hs)(struct omap_dss_device *dssdev, int channel, bool enable); int (*enable_te)(struct omap_dss_device *dssdev, bool enable); int (*update)(struct omap_dss_device *dssdev, int channel, void (*callback)(int, void *), void *data); void (*bus_lock)(struct omap_dss_device *dssdev); void (*bus_unlock)(struct omap_dss_device *dssdev); int (*enable_video_output)(struct omap_dss_device *dssdev, int channel); void (*disable_video_output)(struct omap_dss_device *dssdev, int channel); int (*request_vc)(struct omap_dss_device *dssdev, int *channel); int (*set_vc_id)(struct omap_dss_device *dssdev, int channel, int vc_id); void (*release_vc)(struct omap_dss_device *dssdev, int channel); /* data transfer */ int (*dcs_write)(struct omap_dss_device *dssdev, int channel, u8 *data, int len); int (*dcs_write_nosync)(struct omap_dss_device *dssdev, int channel, u8 *data, int len); int (*dcs_read)(struct omap_dss_device *dssdev, int channel, u8 dcs_cmd, u8 *data, int len); int (*gen_write)(struct omap_dss_device *dssdev, int channel, u8 *data, int len); int (*gen_write_nosync)(struct omap_dss_device *dssdev, int channel, u8 *data, int len); int (*gen_read)(struct omap_dss_device *dssdev, int channel, u8 *reqdata, int reqlen, u8 *data, int len); int (*bta_sync)(struct omap_dss_device *dssdev, int channel); int (*set_max_rx_packet_size)(struct omap_dss_device *dssdev, int channel, u16 plen); }; struct omap_dss_device { struct kobject kobj; struct device *dev; struct module *owner; struct list_head panel_list; /* alias in the form of "display%d" */ char alias[16]; enum omap_display_type type; enum omap_display_type output_type; union { struct { u8 data_lines; } dpi; struct { u8 channel; u8 data_lines; } rfbi; struct { u8 datapairs; } sdi; struct { int module; } dsi; struct { enum omap_dss_venc_type type; bool invert_polarity; } venc; } phy; struct { struct videomode vm; enum omap_dss_dsi_pixel_format dsi_pix_fmt; enum omap_dss_dsi_mode dsi_mode; } panel; struct { u8 pixel_size; struct rfbi_timings rfbi_timings; } ctrl; const char *name; /* used to match device to driver */ const char *driver_name; void *data; struct omap_dss_driver *driver; union { const struct omapdss_dpi_ops *dpi; const struct omapdss_sdi_ops *sdi; const struct omapdss_dvi_ops *dvi; const struct omapdss_hdmi_ops *hdmi; const struct omapdss_atv_ops *atv; const struct omapdss_dsi_ops *dsi; } ops; /* helper variable for driver suspend/resume */ bool activate_after_resume; enum omap_display_caps caps; struct omap_dss_device *src; enum omap_dss_display_state state; /* OMAP DSS output specific fields */ struct list_head list; /* DISPC channel for this output */ enum omap_channel dispc_channel; bool dispc_channel_connected; /* output instance */ enum omap_dss_output_id id; /* the port number in the DT node */ int port_num; /* dynamic fields */ struct omap_overlay_manager *manager; struct omap_dss_device *dst; }; struct omap_dss_driver { int (*probe)(struct omap_dss_device *); void (*remove)(struct omap_dss_device *); int (*connect)(struct omap_dss_device *dssdev); void (*disconnect)(struct omap_dss_device *dssdev); int (*enable)(struct omap_dss_device *display); void (*disable)(struct omap_dss_device *display); int (*run_test)(struct omap_dss_device *display, int test); int (*update)(struct omap_dss_device *dssdev, u16 x, u16 y, u16 w, u16 h); int (*sync)(struct omap_dss_device *dssdev); int (*enable_te)(struct omap_dss_device *dssdev, bool enable); int (*get_te)(struct omap_dss_device *dssdev); u8 (*get_rotate)(struct omap_dss_device *dssdev); int (*set_rotate)(struct omap_dss_device *dssdev, u8 rotate); bool (*get_mirror)(struct omap_dss_device *dssdev); int (*set_mirror)(struct omap_dss_device *dssdev, bool enable); int (*memory_read)(struct omap_dss_device *dssdev, void *buf, size_t size, u16 x, u16 y, u16 w, u16 h); void (*get_resolution)(struct omap_dss_device *dssdev, u16 *xres, u16 *yres); void (*get_dimensions)(struct omap_dss_device *dssdev, u32 *width, u32 *height); int (*get_recommended_bpp)(struct omap_dss_device *dssdev); int (*check_timings)(struct omap_dss_device *dssdev, struct videomode *vm); void (*set_timings)(struct omap_dss_device *dssdev, struct videomode *vm); void (*get_timings)(struct omap_dss_device *dssdev, struct videomode *vm); int (*set_wss)(struct omap_dss_device *dssdev, u32 wss); u32 (*get_wss)(struct omap_dss_device *dssdev); int (*read_edid)(struct omap_dss_device *dssdev, u8 *buf, int len); bool (*detect)(struct omap_dss_device *dssdev); int (*set_hdmi_mode)(struct omap_dss_device *dssdev, bool hdmi_mode); int (*set_hdmi_infoframe)(struct omap_dss_device *dssdev, const struct hdmi_avi_infoframe *avi); }; enum omapdss_version omapdss_get_version(void); bool omapdss_is_initialized(void); int omap_dss_register_driver(struct omap_dss_driver *); void omap_dss_unregister_driver(struct omap_dss_driver *); int omapdss_register_display(struct omap_dss_device *dssdev); void omapdss_unregister_display(struct omap_dss_device *dssdev); struct omap_dss_device *omap_dss_get_device(struct omap_dss_device *dssdev); void omap_dss_put_device(struct omap_dss_device *dssdev); #define for_each_dss_dev(d) while ((d = omap_dss_get_next_device(d)) != NULL) struct omap_dss_device *omap_dss_get_next_device(struct omap_dss_device *from); struct omap_dss_device *omap_dss_find_device(void *data, int (*match)(struct omap_dss_device *dssdev, void *data)); const char *omapdss_get_default_display_name(void); int dss_feat_get_num_mgrs(void); int dss_feat_get_num_ovls(void); enum omap_color_mode dss_feat_get_supported_color_modes(enum omap_plane plane); int omap_dss_get_num_overlay_managers(void); struct omap_overlay_manager *omap_dss_get_overlay_manager(int num); int omap_dss_get_num_overlays(void); struct omap_overlay *omap_dss_get_overlay(int num); int omapdss_register_output(struct omap_dss_device *output); void omapdss_unregister_output(struct omap_dss_device *output); struct omap_dss_device *omap_dss_get_output(enum omap_dss_output_id id); struct omap_dss_device *omap_dss_find_output(const char *name); struct omap_dss_device *omap_dss_find_output_by_port_node(struct device_node *port); int omapdss_output_set_device(struct omap_dss_device *out, struct omap_dss_device *dssdev); int omapdss_output_unset_device(struct omap_dss_device *out); struct omap_dss_device *omapdss_find_output_from_display(struct omap_dss_device *dssdev); struct omap_overlay_manager *omapdss_find_mgr_from_display(struct omap_dss_device *dssdev); void omapdss_default_get_resolution(struct omap_dss_device *dssdev, u16 *xres, u16 *yres); int omapdss_default_get_recommended_bpp(struct omap_dss_device *dssdev); void omapdss_default_get_timings(struct omap_dss_device *dssdev, struct videomode *vm); typedef void (*omap_dispc_isr_t) (void *arg, u32 mask); int omap_dispc_register_isr(omap_dispc_isr_t isr, void *arg, u32 mask); int omap_dispc_unregister_isr(omap_dispc_isr_t isr, void *arg, u32 mask); int omapdss_compat_init(void); void omapdss_compat_uninit(void); static inline bool omapdss_device_is_connected(struct omap_dss_device *dssdev) { return dssdev->src; } static inline bool omapdss_device_is_enabled(struct omap_dss_device *dssdev) { return dssdev->state == OMAP_DSS_DISPLAY_ACTIVE; } struct device_node * omapdss_of_get_next_port(const struct device_node *parent, struct device_node *prev); struct device_node * omapdss_of_get_next_endpoint(const struct device_node *parent, struct device_node *prev); struct device_node * omapdss_of_get_first_endpoint(const struct device_node *parent); struct omap_dss_device * omapdss_of_find_source_for_first_ep(struct device_node *node); u32 dispc_read_irqstatus(void); void dispc_clear_irqstatus(u32 mask); u32 dispc_read_irqenable(void); void dispc_write_irqenable(u32 mask); int dispc_request_irq(irq_handler_t handler, void *dev_id); void dispc_free_irq(void *dev_id); int dispc_runtime_get(void); void dispc_runtime_put(void); void dispc_mgr_enable(enum omap_channel channel, bool enable); u32 dispc_mgr_get_vsync_irq(enum omap_channel channel); u32 dispc_mgr_get_framedone_irq(enum omap_channel channel); u32 dispc_mgr_get_sync_lost_irq(enum omap_channel channel); bool dispc_mgr_go_busy(enum omap_channel channel); void dispc_mgr_go(enum omap_channel channel); void dispc_mgr_set_lcd_config(enum omap_channel channel, const struct dss_lcd_mgr_config *config); void dispc_mgr_set_timings(enum omap_channel channel, const struct videomode *vm); void dispc_mgr_setup(enum omap_channel channel, const struct omap_overlay_manager_info *info); u32 dispc_mgr_gamma_size(enum omap_channel channel); void dispc_mgr_set_gamma(enum omap_channel channel, const struct drm_color_lut *lut, unsigned int length); int dispc_ovl_enable(enum omap_plane plane, bool enable); bool dispc_ovl_enabled(enum omap_plane plane); void dispc_ovl_set_channel_out(enum omap_plane plane, enum omap_channel channel); int dispc_ovl_setup(enum omap_plane plane, const struct omap_overlay_info *oi, bool replication, const struct videomode *vm, bool mem_to_mem); enum omap_dss_output_id dispc_mgr_get_supported_outputs(enum omap_channel channel); struct dss_mgr_ops { int (*connect)(enum omap_channel channel, struct omap_dss_device *dst); void (*disconnect)(enum omap_channel channel, struct omap_dss_device *dst); void (*start_update)(enum omap_channel channel); int (*enable)(enum omap_channel channel); void (*disable)(enum omap_channel channel); void (*set_timings)(enum omap_channel channel, const struct videomode *vm); void (*set_lcd_config)(enum omap_channel channel, const struct dss_lcd_mgr_config *config); int (*register_framedone_handler)(enum omap_channel channel, void (*handler)(void *), void *data); void (*unregister_framedone_handler)(enum omap_channel channel, void (*handler)(void *), void *data); }; int dss_install_mgr_ops(const struct dss_mgr_ops *mgr_ops); void dss_uninstall_mgr_ops(void); int dss_mgr_connect(enum omap_channel channel, struct omap_dss_device *dst); void dss_mgr_disconnect(enum omap_channel channel, struct omap_dss_device *dst); void dss_mgr_set_timings(enum omap_channel channel, const struct videomode *vm); void dss_mgr_set_lcd_config(enum omap_channel channel, const struct dss_lcd_mgr_config *config); int dss_mgr_enable(enum omap_channel channel); void dss_mgr_disable(enum omap_channel channel); void dss_mgr_start_update(enum omap_channel channel); int dss_mgr_register_framedone_handler(enum omap_channel channel, void (*handler)(void *), void *data); void dss_mgr_unregister_framedone_handler(enum omap_channel channel, void (*handler)(void *), void *data); #endif /* __OMAP_DRM_DSS_H */
{ "language": "C" }
/* * linux/fs/nls/nls_cp775.c * * Charset cp775 translation tables. * Generated automatically from the Unicode and charset * tables from the Unicode Organization (www.unicode.org). * The Unicode to charset table has only exact mappings. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/nls.h> #include <linux/errno.h> static const wchar_t charset2uni[256] = { /* 0x00*/ 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f, /* 0x10*/ 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, 0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f, /* 0x20*/ 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f, /* 0x30*/ 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f, /* 0x40*/ 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f, /* 0x50*/ 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f, /* 0x60*/ 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f, /* 0x70*/ 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x007f, /* 0x80*/ 0x0106, 0x00fc, 0x00e9, 0x0101, 0x00e4, 0x0123, 0x00e5, 0x0107, 0x0142, 0x0113, 0x0156, 0x0157, 0x012b, 0x0179, 0x00c4, 0x00c5, /* 0x90*/ 0x00c9, 0x00e6, 0x00c6, 0x014d, 0x00f6, 0x0122, 0x00a2, 0x015a, 0x015b, 0x00d6, 0x00dc, 0x00f8, 0x00a3, 0x00d8, 0x00d7, 0x00a4, /* 0xa0*/ 0x0100, 0x012a, 0x00f3, 0x017b, 0x017c, 0x017a, 0x201d, 0x00a6, 0x00a9, 0x00ae, 0x00ac, 0x00bd, 0x00bc, 0x0141, 0x00ab, 0x00bb, /* 0xb0*/ 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x0104, 0x010c, 0x0118, 0x0116, 0x2563, 0x2551, 0x2557, 0x255d, 0x012e, 0x0160, 0x2510, /* 0xc0*/ 0x2514, 0x2534, 0x252c, 0x251c, 0x2500, 0x253c, 0x0172, 0x016a, 0x255a, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256c, 0x017d, /* 0xd0*/ 0x0105, 0x010d, 0x0119, 0x0117, 0x012f, 0x0161, 0x0173, 0x016b, 0x017e, 0x2518, 0x250c, 0x2588, 0x2584, 0x258c, 0x2590, 0x2580, /* 0xe0*/ 0x00d3, 0x00df, 0x014c, 0x0143, 0x00f5, 0x00d5, 0x00b5, 0x0144, 0x0136, 0x0137, 0x013b, 0x013c, 0x0146, 0x0112, 0x0145, 0x2019, /* 0xf0*/ 0x00ad, 0x00b1, 0x201c, 0x00be, 0x00b6, 0x00a7, 0x00f7, 0x201e, 0x00b0, 0x2219, 0x00b7, 0x00b9, 0x00b3, 0x00b2, 0x25a0, 0x00a0, }; static const unsigned char page00[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */ 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */ 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */ 0xff, 0x00, 0x96, 0x9c, 0x9f, 0x00, 0xa7, 0xf5, /* 0xa0-0xa7 */ 0x00, 0xa8, 0x00, 0xae, 0xaa, 0xf0, 0xa9, 0x00, /* 0xa8-0xaf */ 0xf8, 0xf1, 0xfd, 0xfc, 0x00, 0xe6, 0xf4, 0xfa, /* 0xb0-0xb7 */ 0x00, 0xfb, 0x00, 0xaf, 0xac, 0xab, 0xf3, 0x00, /* 0xb8-0xbf */ 0x00, 0x00, 0x00, 0x00, 0x8e, 0x8f, 0x92, 0x00, /* 0xc0-0xc7 */ 0x00, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc8-0xcf */ 0x00, 0x00, 0x00, 0xe0, 0x00, 0xe5, 0x99, 0x9e, /* 0xd0-0xd7 */ 0x9d, 0x00, 0x00, 0x00, 0x9a, 0x00, 0x00, 0xe1, /* 0xd8-0xdf */ 0x00, 0x00, 0x00, 0x00, 0x84, 0x86, 0x91, 0x00, /* 0xe0-0xe7 */ 0x00, 0x82, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xe8-0xef */ 0x00, 0x00, 0x00, 0xa2, 0x00, 0xe4, 0x94, 0xf6, /* 0xf0-0xf7 */ 0x9b, 0x00, 0x00, 0x00, 0x81, 0x00, 0x00, 0x00, /* 0xf8-0xff */ }; static const unsigned char page01[256] = { 0xa0, 0x83, 0x00, 0x00, 0xb5, 0xd0, 0x80, 0x87, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0xb6, 0xd1, 0x00, 0x00, /* 0x08-0x0f */ 0x00, 0x00, 0xed, 0x89, 0x00, 0x00, 0xb8, 0xd3, /* 0x10-0x17 */ 0xb7, 0xd2, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */ 0x00, 0x00, 0x95, 0x85, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */ 0x00, 0x00, 0xa1, 0x8c, 0x00, 0x00, 0xbd, 0xd4, /* 0x28-0x2f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe8, 0xe9, /* 0x30-0x37 */ 0x00, 0x00, 0x00, 0xea, 0xeb, 0x00, 0x00, 0x00, /* 0x38-0x3f */ 0x00, 0xad, 0x88, 0xe3, 0xe7, 0xee, 0xec, 0x00, /* 0x40-0x47 */ 0x00, 0x00, 0x00, 0x00, 0xe2, 0x93, 0x00, 0x00, /* 0x48-0x4f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8a, 0x8b, /* 0x50-0x57 */ 0x00, 0x00, 0x97, 0x98, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */ 0xbe, 0xd5, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */ 0x00, 0x00, 0xc7, 0xd7, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */ 0x00, 0x00, 0xc6, 0xd6, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */ 0x00, 0x8d, 0xa5, 0xa3, 0xa4, 0xcf, 0xd8, 0x00, /* 0x78-0x7f */ }; static const unsigned char page20[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */ 0x00, 0xef, 0x00, 0x00, 0xf2, 0xa6, 0xf7, 0x00, /* 0x18-0x1f */ }; static const unsigned char page22[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */ 0x00, 0xf9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */ }; static const unsigned char page25[256] = { 0xc4, 0x00, 0xb3, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0xda, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0xbf, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, /* 0x10-0x17 */ 0xd9, 0x00, 0x00, 0x00, 0xc3, 0x00, 0x00, 0x00, /* 0x18-0x1f */ 0x00, 0x00, 0x00, 0x00, 0xb4, 0x00, 0x00, 0x00, /* 0x20-0x27 */ 0x00, 0x00, 0x00, 0x00, 0xc2, 0x00, 0x00, 0x00, /* 0x28-0x2f */ 0x00, 0x00, 0x00, 0x00, 0xc1, 0x00, 0x00, 0x00, /* 0x30-0x37 */ 0x00, 0x00, 0x00, 0x00, 0xc5, 0x00, 0x00, 0x00, /* 0x38-0x3f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */ 0xcd, 0xba, 0x00, 0x00, 0xc9, 0x00, 0x00, 0xbb, /* 0x50-0x57 */ 0x00, 0x00, 0xc8, 0x00, 0x00, 0xbc, 0x00, 0x00, /* 0x58-0x5f */ 0xcc, 0x00, 0x00, 0xb9, 0x00, 0x00, 0xcb, 0x00, /* 0x60-0x67 */ 0x00, 0xca, 0x00, 0x00, 0xce, 0x00, 0x00, 0x00, /* 0x68-0x6f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */ 0xdf, 0x00, 0x00, 0x00, 0xdc, 0x00, 0x00, 0x00, /* 0x80-0x87 */ 0xdb, 0x00, 0x00, 0x00, 0xdd, 0x00, 0x00, 0x00, /* 0x88-0x8f */ 0xde, 0xb0, 0xb1, 0xb2, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */ 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */ }; static const unsigned char *const page_uni2charset[256] = { page00, page01, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, page20, NULL, page22, NULL, NULL, page25, NULL, NULL, }; static const unsigned char charset2lower[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */ 0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x40-0x47 */ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x48-0x4f */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x50-0x57 */ 0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */ 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */ 0x87, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x80-0x87 */ 0x88, 0x89, 0x8b, 0x8b, 0x8c, 0xa5, 0x84, 0x86, /* 0x88-0x8f */ 0x82, 0x91, 0x91, 0x93, 0x94, 0x85, 0x96, 0x98, /* 0x90-0x97 */ 0x98, 0x94, 0x81, 0x9b, 0x9c, 0x9b, 0x9e, 0x9f, /* 0x98-0x9f */ 0x83, 0x8c, 0xa2, 0xa4, 0xa4, 0xa5, 0xa6, 0xa7, /* 0xa0-0xa7 */ 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0x88, 0xae, 0xaf, /* 0xa8-0xaf */ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xd0, 0xd1, 0xd2, /* 0xb0-0xb7 */ 0xd3, 0xb9, 0xba, 0xbb, 0xbc, 0xd4, 0xd5, 0xbf, /* 0xb8-0xbf */ 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xd6, 0xd7, /* 0xc0-0xc7 */ 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xd8, /* 0xc8-0xcf */ 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xd0-0xd7 */ 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */ 0xa2, 0xe1, 0x93, 0xe7, 0xe4, 0xe4, 0xe6, 0xe7, /* 0xe0-0xe7 */ 0xe9, 0xe9, 0xeb, 0xeb, 0xec, 0x89, 0xec, 0xef, /* 0xe8-0xef */ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */ 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */ }; static const unsigned char charset2upper[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */ 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */ 0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x60-0x67 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x68-0x6f */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x70-0x77 */ 0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */ 0x80, 0x9a, 0x90, 0xa0, 0x8e, 0x95, 0x8f, 0x80, /* 0x80-0x87 */ 0xad, 0xed, 0x8a, 0x8a, 0xa1, 0x8d, 0x8e, 0x8f, /* 0x88-0x8f */ 0x90, 0x92, 0x92, 0xe2, 0x99, 0x95, 0x96, 0x97, /* 0x90-0x97 */ 0x97, 0x99, 0x9a, 0x9d, 0x9c, 0x9d, 0x9e, 0x9f, /* 0x98-0x9f */ 0xa0, 0xa1, 0xe0, 0xa3, 0xa3, 0x8d, 0xa6, 0xa7, /* 0xa0-0xa7 */ 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0xa8-0xaf */ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */ 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */ 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xc0-0xc7 */ 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */ 0xb5, 0xb6, 0xb7, 0xb8, 0xbd, 0xbe, 0xc6, 0xc7, /* 0xd0-0xd7 */ 0xcf, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */ 0xe0, 0xe1, 0xe2, 0xe3, 0xe5, 0xe5, 0x00, 0xe3, /* 0xe0-0xe7 */ 0xe8, 0xe8, 0xea, 0xea, 0xee, 0xed, 0xee, 0xef, /* 0xe8-0xef */ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */ 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */ }; static int uni2char(wchar_t uni, unsigned char *out, int boundlen) { const unsigned char *uni2charset; unsigned char cl = uni & 0x00ff; unsigned char ch = (uni & 0xff00) >> 8; if (boundlen <= 0) return -ENAMETOOLONG; uni2charset = page_uni2charset[ch]; if (uni2charset && uni2charset[cl]) out[0] = uni2charset[cl]; else return -EINVAL; return 1; } static int char2uni(const unsigned char *rawstring, int boundlen, wchar_t *uni) { *uni = charset2uni[*rawstring]; if (*uni == 0x0000) return -EINVAL; return 1; } static struct nls_table table = { .charset = "cp775", .uni2char = uni2char, .char2uni = char2uni, .charset2lower = charset2lower, .charset2upper = charset2upper, }; static int __init init_nls_cp775(void) { return register_nls(&table); } static void __exit exit_nls_cp775(void) { unregister_nls(&table); } module_init(init_nls_cp775) module_exit(exit_nls_cp775) MODULE_LICENSE("Dual BSD/GPL");
{ "language": "C" }
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (C) 2012 Texas Instruments * Author: Rob Clark <robdclark@gmail.com> */ #include <linux/gpio/consumer.h> #include <linux/pinctrl/consumer.h> #include <linux/platform_device.h> #include <video/display_timing.h> #include <video/of_display_timing.h> #include <video/videomode.h> #include <drm/drm_atomic_state_helper.h> #include <drm/drm_connector.h> #include <drm/drm_modeset_helper_vtables.h> #include <drm/drm_probe_helper.h> #include "tilcdc_drv.h" #include "tilcdc_panel.h" struct panel_module { struct tilcdc_module base; struct tilcdc_panel_info *info; struct display_timings *timings; struct backlight_device *backlight; struct gpio_desc *enable_gpio; }; #define to_panel_module(x) container_of(x, struct panel_module, base) /* * Encoder: */ struct panel_encoder { struct drm_encoder base; struct panel_module *mod; }; #define to_panel_encoder(x) container_of(x, struct panel_encoder, base) static void panel_encoder_dpms(struct drm_encoder *encoder, int mode) { struct panel_encoder *panel_encoder = to_panel_encoder(encoder); struct backlight_device *backlight = panel_encoder->mod->backlight; struct gpio_desc *gpio = panel_encoder->mod->enable_gpio; if (backlight) { backlight->props.power = mode == DRM_MODE_DPMS_ON ? FB_BLANK_UNBLANK : FB_BLANK_POWERDOWN; backlight_update_status(backlight); } if (gpio) gpiod_set_value_cansleep(gpio, mode == DRM_MODE_DPMS_ON ? 1 : 0); } static void panel_encoder_prepare(struct drm_encoder *encoder) { panel_encoder_dpms(encoder, DRM_MODE_DPMS_OFF); } static void panel_encoder_commit(struct drm_encoder *encoder) { panel_encoder_dpms(encoder, DRM_MODE_DPMS_ON); } static void panel_encoder_mode_set(struct drm_encoder *encoder, struct drm_display_mode *mode, struct drm_display_mode *adjusted_mode) { /* nothing needed */ } static const struct drm_encoder_funcs panel_encoder_funcs = { .destroy = drm_encoder_cleanup, }; static const struct drm_encoder_helper_funcs panel_encoder_helper_funcs = { .dpms = panel_encoder_dpms, .prepare = panel_encoder_prepare, .commit = panel_encoder_commit, .mode_set = panel_encoder_mode_set, }; static struct drm_encoder *panel_encoder_create(struct drm_device *dev, struct panel_module *mod) { struct panel_encoder *panel_encoder; struct drm_encoder *encoder; int ret; panel_encoder = devm_kzalloc(dev->dev, sizeof(*panel_encoder), GFP_KERNEL); if (!panel_encoder) return NULL; panel_encoder->mod = mod; encoder = &panel_encoder->base; encoder->possible_crtcs = 1; ret = drm_encoder_init(dev, encoder, &panel_encoder_funcs, DRM_MODE_ENCODER_LVDS, NULL); if (ret < 0) goto fail; drm_encoder_helper_add(encoder, &panel_encoder_helper_funcs); return encoder; fail: drm_encoder_cleanup(encoder); return NULL; } /* * Connector: */ struct panel_connector { struct drm_connector base; struct drm_encoder *encoder; /* our connected encoder */ struct panel_module *mod; }; #define to_panel_connector(x) container_of(x, struct panel_connector, base) static void panel_connector_destroy(struct drm_connector *connector) { drm_connector_unregister(connector); drm_connector_cleanup(connector); } static int panel_connector_get_modes(struct drm_connector *connector) { struct drm_device *dev = connector->dev; struct panel_connector *panel_connector = to_panel_connector(connector); struct display_timings *timings = panel_connector->mod->timings; int i; for (i = 0; i < timings->num_timings; i++) { struct drm_display_mode *mode = drm_mode_create(dev); struct videomode vm; if (videomode_from_timings(timings, &vm, i)) break; drm_display_mode_from_videomode(&vm, mode); mode->type = DRM_MODE_TYPE_DRIVER; if (timings->native_mode == i) mode->type |= DRM_MODE_TYPE_PREFERRED; drm_mode_set_name(mode); drm_mode_probed_add(connector, mode); } return i; } static struct drm_encoder *panel_connector_best_encoder( struct drm_connector *connector) { struct panel_connector *panel_connector = to_panel_connector(connector); return panel_connector->encoder; } static const struct drm_connector_funcs panel_connector_funcs = { .destroy = panel_connector_destroy, .fill_modes = drm_helper_probe_single_connector_modes, .reset = drm_atomic_helper_connector_reset, .atomic_duplicate_state = drm_atomic_helper_connector_duplicate_state, .atomic_destroy_state = drm_atomic_helper_connector_destroy_state, }; static const struct drm_connector_helper_funcs panel_connector_helper_funcs = { .get_modes = panel_connector_get_modes, .best_encoder = panel_connector_best_encoder, }; static struct drm_connector *panel_connector_create(struct drm_device *dev, struct panel_module *mod, struct drm_encoder *encoder) { struct panel_connector *panel_connector; struct drm_connector *connector; int ret; panel_connector = devm_kzalloc(dev->dev, sizeof(*panel_connector), GFP_KERNEL); if (!panel_connector) return NULL; panel_connector->encoder = encoder; panel_connector->mod = mod; connector = &panel_connector->base; drm_connector_init(dev, connector, &panel_connector_funcs, DRM_MODE_CONNECTOR_LVDS); drm_connector_helper_add(connector, &panel_connector_helper_funcs); connector->interlace_allowed = 0; connector->doublescan_allowed = 0; ret = drm_connector_attach_encoder(connector, encoder); if (ret) goto fail; return connector; fail: panel_connector_destroy(connector); return NULL; } /* * Module: */ static int panel_modeset_init(struct tilcdc_module *mod, struct drm_device *dev) { struct panel_module *panel_mod = to_panel_module(mod); struct tilcdc_drm_private *priv = dev->dev_private; struct drm_encoder *encoder; struct drm_connector *connector; encoder = panel_encoder_create(dev, panel_mod); if (!encoder) return -ENOMEM; connector = panel_connector_create(dev, panel_mod, encoder); if (!connector) return -ENOMEM; priv->encoders[priv->num_encoders++] = encoder; priv->connectors[priv->num_connectors++] = connector; tilcdc_crtc_set_panel_info(priv->crtc, to_panel_encoder(encoder)->mod->info); return 0; } static const struct tilcdc_module_ops panel_module_ops = { .modeset_init = panel_modeset_init, }; /* * Device: */ /* maybe move this somewhere common if it is needed by other outputs? */ static struct tilcdc_panel_info *of_get_panel_info(struct device_node *np) { struct device_node *info_np; struct tilcdc_panel_info *info; int ret = 0; if (!np) { pr_err("%s: no devicenode given\n", __func__); return NULL; } info_np = of_get_child_by_name(np, "panel-info"); if (!info_np) { pr_err("%s: could not find panel-info node\n", __func__); return NULL; } info = kzalloc(sizeof(*info), GFP_KERNEL); if (!info) goto put_node; ret |= of_property_read_u32(info_np, "ac-bias", &info->ac_bias); ret |= of_property_read_u32(info_np, "ac-bias-intrpt", &info->ac_bias_intrpt); ret |= of_property_read_u32(info_np, "dma-burst-sz", &info->dma_burst_sz); ret |= of_property_read_u32(info_np, "bpp", &info->bpp); ret |= of_property_read_u32(info_np, "fdd", &info->fdd); ret |= of_property_read_u32(info_np, "sync-edge", &info->sync_edge); ret |= of_property_read_u32(info_np, "sync-ctrl", &info->sync_ctrl); ret |= of_property_read_u32(info_np, "raster-order", &info->raster_order); ret |= of_property_read_u32(info_np, "fifo-th", &info->fifo_th); /* optional: */ info->tft_alt_mode = of_property_read_bool(info_np, "tft-alt-mode"); info->invert_pxl_clk = of_property_read_bool(info_np, "invert-pxl-clk"); if (ret) { pr_err("%s: error reading panel-info properties\n", __func__); kfree(info); info = NULL; } put_node: of_node_put(info_np); return info; } static int panel_probe(struct platform_device *pdev) { struct device_node *bl_node, *node = pdev->dev.of_node; struct panel_module *panel_mod; struct tilcdc_module *mod; struct pinctrl *pinctrl; int ret; /* bail out early if no DT data: */ if (!node) { dev_err(&pdev->dev, "device-tree data is missing\n"); return -ENXIO; } panel_mod = devm_kzalloc(&pdev->dev, sizeof(*panel_mod), GFP_KERNEL); if (!panel_mod) return -ENOMEM; bl_node = of_parse_phandle(node, "backlight", 0); if (bl_node) { panel_mod->backlight = of_find_backlight_by_node(bl_node); of_node_put(bl_node); if (!panel_mod->backlight) return -EPROBE_DEFER; dev_info(&pdev->dev, "found backlight\n"); } panel_mod->enable_gpio = devm_gpiod_get_optional(&pdev->dev, "enable", GPIOD_OUT_LOW); if (IS_ERR(panel_mod->enable_gpio)) { ret = PTR_ERR(panel_mod->enable_gpio); dev_err(&pdev->dev, "failed to request enable GPIO\n"); goto fail_backlight; } if (panel_mod->enable_gpio) dev_info(&pdev->dev, "found enable GPIO\n"); mod = &panel_mod->base; pdev->dev.platform_data = mod; tilcdc_module_init(mod, "panel", &panel_module_ops); pinctrl = devm_pinctrl_get_select_default(&pdev->dev); if (IS_ERR(pinctrl)) dev_warn(&pdev->dev, "pins are not configured\n"); panel_mod->timings = of_get_display_timings(node); if (!panel_mod->timings) { dev_err(&pdev->dev, "could not get panel timings\n"); ret = -EINVAL; goto fail_free; } panel_mod->info = of_get_panel_info(node); if (!panel_mod->info) { dev_err(&pdev->dev, "could not get panel info\n"); ret = -EINVAL; goto fail_timings; } return 0; fail_timings: display_timings_release(panel_mod->timings); fail_free: tilcdc_module_cleanup(mod); fail_backlight: if (panel_mod->backlight) put_device(&panel_mod->backlight->dev); return ret; } static int panel_remove(struct platform_device *pdev) { struct tilcdc_module *mod = dev_get_platdata(&pdev->dev); struct panel_module *panel_mod = to_panel_module(mod); struct backlight_device *backlight = panel_mod->backlight; if (backlight) put_device(&backlight->dev); display_timings_release(panel_mod->timings); tilcdc_module_cleanup(mod); kfree(panel_mod->info); return 0; } static const struct of_device_id panel_of_match[] = { { .compatible = "ti,tilcdc,panel", }, { }, }; struct platform_driver panel_driver = { .probe = panel_probe, .remove = panel_remove, .driver = { .owner = THIS_MODULE, .name = "tilcdc-panel", .of_match_table = panel_of_match, }, }; int __init tilcdc_panel_init(void) { return platform_driver_register(&panel_driver); } void __exit tilcdc_panel_fini(void) { platform_driver_unregister(&panel_driver); }
{ "language": "C" }
/** * * \file * * \brief Common Standard I/O Serial Management. * * This file defines a useful set of functions for the Stdio Serial interface on AVR * and SAM devices. * * Copyright (c) 2009-2013 Atmel Corporation. All rights reserved. * * \asf_license_start * * \page License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name of Atmel may not be used to endorse or promote products derived * from this software without specific prior written permission. * * 4. This software may only be redistributed and used in connection with an * Atmel microcontroller product. * * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \asf_license_stop * ******************************************************************************/ #ifndef _STDIO_SERIAL_H_ #define _STDIO_SERIAL_H_ /** * \defgroup group_common_utils_stdio_stdio_serial Standard serial I/O (stdio) * \ingroup group_common_utils_stdio * * Common standard serial I/O management driver that * implements a stdio serial interface on AVR and SAM devices. * * \{ */ #include <stdio.h> #include "compiler.h" #include "sysclk.h" #include "serial.h" #if (XMEGA || MEGA_RF) && defined(__GNUC__) extern int _write (char c, int *f); extern int _read (int *f); #endif //! Pointer to the base of the USART module instance to use for stdio. extern volatile void *volatile stdio_base; //! Pointer to the external low level write function. extern int (*ptr_put)(void volatile*, char); //! Pointer to the external low level read function. extern void (*ptr_get)(void volatile*, char*); /*! \brief Initializes the stdio in Serial Mode. * * \param usart Base address of the USART instance. * \param opt Options needed to set up RS232 communication (see \ref usart_options_t). * */ static inline void stdio_serial_init(volatile void *usart, const usart_serial_options_t *opt) { stdio_base = (void *)usart; ptr_put = (int (*)(void volatile*,char))&usart_serial_putchar; ptr_get = (void (*)(void volatile*,char*))&usart_serial_getchar; #if (XMEGA || MEGA_RF) usart_serial_init((USART_t *)usart,opt); #elif UC3 usart_serial_init(usart,(usart_serial_options_t *)opt); #elif SAM usart_serial_init((Usart *)usart,(usart_serial_options_t *)opt); #else # error Unsupported chip type #endif #if defined(__GNUC__) # if (XMEGA || MEGA_RF) // For AVR GCC libc print redirection uses fdevopen. fdevopen((int (*)(char, FILE*))(_write),(int (*)(FILE*))(_read)); # endif # if UC3 || SAM // For AVR32 and SAM GCC // Specify that stdout and stdin should not be buffered. setbuf(stdout, NULL); setbuf(stdin, NULL); // Note: Already the case in IAR's Normal DLIB default configuration // and AVR GCC library: // - printf() emits one character at a time. // - getchar() requests only 1 byte to exit. # endif #endif } /** * \} */ #endif // _STDIO_SERIAL_H_
{ "language": "C" }
/* SPDX-License-Identifier: GPL-2.0+ */ /* * Digital Beep Input Interface for HD-audio codec * * Author: Matt Ranostay <matt.ranostay@konsulko.com> * Copyright (c) 2008 Embedded Alley Solutions Inc */ #ifndef __SOUND_HDA_BEEP_H #define __SOUND_HDA_BEEP_H #include <sound/hda_codec.h> #define HDA_BEEP_MODE_OFF 0 #define HDA_BEEP_MODE_ON 1 /* beep information */ struct hda_beep { struct input_dev *dev; struct hda_codec *codec; char phys[32]; int tone; hda_nid_t nid; unsigned int registered:1; unsigned int enabled:1; unsigned int linear_tone:1; /* linear tone for IDT/STAC codec */ unsigned int playing:1; struct work_struct beep_work; /* scheduled task for beep event */ struct mutex mutex; void (*power_hook)(struct hda_beep *beep, bool on); }; #ifdef CONFIG_SND_HDA_INPUT_BEEP int snd_hda_enable_beep_device(struct hda_codec *codec, int enable); int snd_hda_attach_beep_device(struct hda_codec *codec, int nid); void snd_hda_detach_beep_device(struct hda_codec *codec); #else static inline int snd_hda_attach_beep_device(struct hda_codec *codec, int nid) { return 0; } static inline void snd_hda_detach_beep_device(struct hda_codec *codec) { } #endif #endif
{ "language": "C" }
/* * Copyright (C) 2002-2020 by the Widelands Development Team * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef WL_EDITOR_TOOLS_SET_TERRAIN_TOOL_H #define WL_EDITOR_TOOLS_SET_TERRAIN_TOOL_H #include "editor/tools/multi_select.h" #include "editor/tools/tool.h" struct EditorSetTerrainTool : public EditorTool, public MultiSelect { EditorSetTerrainTool() : EditorTool(*this, *this) { } int32_t handle_click_impl(const Widelands::NodeAndTriangle<>& center, EditorInteractive& parent, EditorActionArgs* args, Widelands::Map* map) override; int32_t handle_undo_impl(const Widelands::NodeAndTriangle<>& center, EditorInteractive& parent, EditorActionArgs* args, Widelands::Map* map) override; EditorActionArgs format_args_impl(EditorInteractive& parent) override; const Image* get_sel_impl() const override { return g_image_cache->get("images/ui_basic/fsel.png"); } bool operates_on_triangles() const override { return true; } }; #endif // end of include guard: WL_EDITOR_TOOLS_SET_TERRAIN_TOOL_H
{ "language": "C" }
/** @file * * VBox HDD container test utility, memory disk/file. */ /* * Copyright (C) 2011-2017 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ #ifndef __VDMemDisk_h__ #define __VDMemDisk_h__ #include <iprt/sg.h> /** Handle to the a memory disk. */ typedef struct VDMEMDISK *PVDMEMDISK; /** Pointer to a memory disk handle. */ typedef PVDMEMDISK *PPVDMEMDISK; /** * Creates a new memory disk with the given size. * * @returns VBOX status code. * * @param ppMemDisk Where to store the memory disk handle. * @param cbSize Size of the disk if it is fixed. * If 0 the disk grows when it is written to * and the size can be changed with * VDMemDiskSetSize(). */ int VDMemDiskCreate(PPVDMEMDISK ppMemDisk, uint64_t cbSize); /** * Destroys a memory disk. * * @returns nothing. * * @param pMemDisk The memory disk to destroy. */ void VDMemDiskDestroy(PVDMEMDISK pMemDisk); /** * Writes the specified amount of data from the S/G buffer at * the given offset. * * @returns VBox status code. * * @param pMemDisk The memory disk handle. * @param off Where to start writing to. * @param cbWrite How many bytes to write. * @param pSgBuf The S/G buffer to write from. */ int VDMemDiskWrite(PVDMEMDISK pMemDisk, uint64_t off, size_t cbWrite, PRTSGBUF pSgBuf); /** * Reads the specified amount of data into the S/G buffer * starting from the given offset. * * @returns VBox status code. * * @param pMemDisk The memory disk handle. * @param off Where to start reading from. * @param cbRead The amount of bytes to read. * @param pSgBuf The S/G buffer to read into. */ int VDMemDiskRead(PVDMEMDISK pMemDisk, uint64_t off, size_t cbRead, PRTSGBUF pSgBuf); /** * Sets the size of the memory disk. * * @returns VBox status code. * * @param pMemDisk The memory disk handle. * @param cbSize The new size to set. */ int VDMemDiskSetSize(PVDMEMDISK pMemDisk, uint64_t cbSize); /** * Gets the current size of the memory disk. * * @returns VBox status code. * * @param pMemDisk The memory disk handle. * @param pcbSize Where to store the size of the memory * disk. */ int VDMemDiskGetSize(PVDMEMDISK pMemDisk, uint64_t *pcbSize); /** * Dumps the memory disk to a file. * * @returns VBox status code. * * @param pMemDisk The memory disk handle. * @param pcszFilename Where to dump the content. */ int VDMemDiskWriteToFile(PVDMEMDISK pMemDisk, const char *pcszFilename); /** * Reads the content of a file into the given memory disk. * All data stored in the memory disk will be overwritten. * * @returns VBox status code. * * @param pMemDisk The memory disk handle. * @param pcszFilename The file to load from. */ int VDMemDiskReadFromFile(PVDMEMDISK pMemDisk, const char *pcszFilename); /** * Compares the given range of the memory disk with a provided S/G buffer. * * @returns whatever memcmp returns. * * @param pMemDisk The memory disk handle. * @param off Where to start comparing. * @param cbCmp How many bytes to compare. * @param pSgBuf The S/G buffer to compare with. */ int VDMemDiskCmp(PVDMEMDISK pMemDisk, uint64_t off, size_t cbCmp, PRTSGBUF pSgBuf); #endif /* __VDMemDisk_h__ */
{ "language": "C" }
/*************************************************************************** * Plug-in for HV7131D image sensor connected to the SN9C1xx PC Camera * * Controllers * * * * Copyright (C) 2004-2007 by Luca Risolia <luca.risolia@studio.unibo.it> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * ***************************************************************************/ #include "sn9c102_sensor.h" #include "sn9c102_devtable.h" static int hv7131d_init(struct sn9c102_device* cam) { int err; err = sn9c102_write_const_regs(cam, {0x00, 0x10}, {0x00, 0x11}, {0x00, 0x14}, {0x60, 0x17}, {0x0e, 0x18}, {0xf2, 0x19}); err += sn9c102_i2c_write(cam, 0x01, 0x04); err += sn9c102_i2c_write(cam, 0x02, 0x00); err += sn9c102_i2c_write(cam, 0x28, 0x00); return err; } static int hv7131d_get_ctrl(struct sn9c102_device* cam, struct v4l2_control* ctrl) { switch (ctrl->id) { case V4L2_CID_EXPOSURE: { int r1 = sn9c102_i2c_read(cam, 0x26), r2 = sn9c102_i2c_read(cam, 0x27); if (r1 < 0 || r2 < 0) return -EIO; ctrl->value = (r1 << 8) | (r2 & 0xff); } return 0; case V4L2_CID_RED_BALANCE: if ((ctrl->value = sn9c102_i2c_read(cam, 0x31)) < 0) return -EIO; ctrl->value = 0x3f - (ctrl->value & 0x3f); return 0; case V4L2_CID_BLUE_BALANCE: if ((ctrl->value = sn9c102_i2c_read(cam, 0x33)) < 0) return -EIO; ctrl->value = 0x3f - (ctrl->value & 0x3f); return 0; case SN9C102_V4L2_CID_GREEN_BALANCE: if ((ctrl->value = sn9c102_i2c_read(cam, 0x32)) < 0) return -EIO; ctrl->value = 0x3f - (ctrl->value & 0x3f); return 0; case SN9C102_V4L2_CID_RESET_LEVEL: if ((ctrl->value = sn9c102_i2c_read(cam, 0x30)) < 0) return -EIO; ctrl->value &= 0x3f; return 0; case SN9C102_V4L2_CID_PIXEL_BIAS_VOLTAGE: if ((ctrl->value = sn9c102_i2c_read(cam, 0x34)) < 0) return -EIO; ctrl->value &= 0x07; return 0; default: return -EINVAL; } } static int hv7131d_set_ctrl(struct sn9c102_device* cam, const struct v4l2_control* ctrl) { int err = 0; switch (ctrl->id) { case V4L2_CID_EXPOSURE: err += sn9c102_i2c_write(cam, 0x26, ctrl->value >> 8); err += sn9c102_i2c_write(cam, 0x27, ctrl->value & 0xff); break; case V4L2_CID_RED_BALANCE: err += sn9c102_i2c_write(cam, 0x31, 0x3f - ctrl->value); break; case V4L2_CID_BLUE_BALANCE: err += sn9c102_i2c_write(cam, 0x33, 0x3f - ctrl->value); break; case SN9C102_V4L2_CID_GREEN_BALANCE: err += sn9c102_i2c_write(cam, 0x32, 0x3f - ctrl->value); break; case SN9C102_V4L2_CID_RESET_LEVEL: err += sn9c102_i2c_write(cam, 0x30, ctrl->value); break; case SN9C102_V4L2_CID_PIXEL_BIAS_VOLTAGE: err += sn9c102_i2c_write(cam, 0x34, ctrl->value); break; default: return -EINVAL; } return err ? -EIO : 0; } static int hv7131d_set_crop(struct sn9c102_device* cam, const struct v4l2_rect* rect) { struct sn9c102_sensor* s = sn9c102_get_sensor(cam); int err = 0; u8 h_start = (u8)(rect->left - s->cropcap.bounds.left) + 2, v_start = (u8)(rect->top - s->cropcap.bounds.top) + 2; err += sn9c102_write_reg(cam, h_start, 0x12); err += sn9c102_write_reg(cam, v_start, 0x13); return err; } static int hv7131d_set_pix_format(struct sn9c102_device* cam, const struct v4l2_pix_format* pix) { int err = 0; if (pix->pixelformat == V4L2_PIX_FMT_SN9C10X) err += sn9c102_write_reg(cam, 0x42, 0x19); else err += sn9c102_write_reg(cam, 0xf2, 0x19); return err; } static const struct sn9c102_sensor hv7131d = { .name = "HV7131D", .maintainer = "Luca Risolia <luca.risolia@studio.unibo.it>", .supported_bridge = BRIDGE_SN9C101 | BRIDGE_SN9C102, .sysfs_ops = SN9C102_I2C_READ | SN9C102_I2C_WRITE, .frequency = SN9C102_I2C_100KHZ, .interface = SN9C102_I2C_2WIRES, .i2c_slave_id = 0x11, .init = &hv7131d_init, .qctrl = { { .id = V4L2_CID_EXPOSURE, .type = V4L2_CTRL_TYPE_INTEGER, .name = "exposure", .minimum = 0x0250, .maximum = 0xffff, .step = 0x0001, .default_value = 0x0250, .flags = 0, }, { .id = V4L2_CID_RED_BALANCE, .type = V4L2_CTRL_TYPE_INTEGER, .name = "red balance", .minimum = 0x00, .maximum = 0x3f, .step = 0x01, .default_value = 0x00, .flags = 0, }, { .id = V4L2_CID_BLUE_BALANCE, .type = V4L2_CTRL_TYPE_INTEGER, .name = "blue balance", .minimum = 0x00, .maximum = 0x3f, .step = 0x01, .default_value = 0x20, .flags = 0, }, { .id = SN9C102_V4L2_CID_GREEN_BALANCE, .type = V4L2_CTRL_TYPE_INTEGER, .name = "green balance", .minimum = 0x00, .maximum = 0x3f, .step = 0x01, .default_value = 0x1e, .flags = 0, }, { .id = SN9C102_V4L2_CID_RESET_LEVEL, .type = V4L2_CTRL_TYPE_INTEGER, .name = "reset level", .minimum = 0x19, .maximum = 0x3f, .step = 0x01, .default_value = 0x30, .flags = 0, }, { .id = SN9C102_V4L2_CID_PIXEL_BIAS_VOLTAGE, .type = V4L2_CTRL_TYPE_INTEGER, .name = "pixel bias voltage", .minimum = 0x00, .maximum = 0x07, .step = 0x01, .default_value = 0x02, .flags = 0, }, }, .get_ctrl = &hv7131d_get_ctrl, .set_ctrl = &hv7131d_set_ctrl, .cropcap = { .bounds = { .left = 0, .top = 0, .width = 640, .height = 480, }, .defrect = { .left = 0, .top = 0, .width = 640, .height = 480, }, }, .set_crop = &hv7131d_set_crop, .pix_format = { .width = 640, .height = 480, .pixelformat = V4L2_PIX_FMT_SBGGR8, .priv = 8, }, .set_pix_format = &hv7131d_set_pix_format }; int sn9c102_probe_hv7131d(struct sn9c102_device* cam) { int r0 = 0, r1 = 0, err; err = sn9c102_write_const_regs(cam, {0x01, 0x01}, {0x00, 0x01}, {0x28, 0x17}); r0 = sn9c102_i2c_try_read(cam, &hv7131d, 0x00); r1 = sn9c102_i2c_try_read(cam, &hv7131d, 0x01); if (err || r0 < 0 || r1 < 0) return -EIO; if ((r0 != 0x00 && r0 != 0x01) || r1 != 0x04) return -ENODEV; sn9c102_attach_sensor(cam, &hv7131d); return 0; }
{ "language": "C" }
// // fpieee.h // // Copyright (c) Microsoft Corporation. All rights reserved. // // This file contains constant and type definitions for handling floating point // exceptions (IEEE 754). // #pragma once #define _INC_FPIEEE #ifndef __midl #ifdef _M_CEE_PURE #error ERROR: This file is not supported in the pure mode! #endif #include <corecrt.h> _CRT_BEGIN_C_HEADER #ifndef __assembler // Disable C4324: structure was padded due to __declspec(align()) #pragma warning(push) #pragma warning(disable: 4324) // Define floating point IEEE compare result values. typedef enum { _FpCompareEqual, _FpCompareGreater, _FpCompareLess, _FpCompareUnordered } _FPIEEE_COMPARE_RESULT; // Define floating point format and result precision values. typedef enum { _FpFormatFp32, _FpFormatFp64, _FpFormatFp80, _FpFormatFp128, _FpFormatI16, _FpFormatI32, _FpFormatI64, _FpFormatU16, _FpFormatU32, _FpFormatU64, _FpFormatBcd80, _FpFormatCompare, _FpFormatString, } _FPIEEE_FORMAT; // Define operation code values. typedef enum { _FpCodeUnspecified, _FpCodeAdd, _FpCodeSubtract, _FpCodeMultiply, _FpCodeDivide, _FpCodeSquareRoot, _FpCodeRemainder, _FpCodeCompare, _FpCodeConvert, _FpCodeRound, _FpCodeTruncate, _FpCodeFloor, _FpCodeCeil, _FpCodeAcos, _FpCodeAsin, _FpCodeAtan, _FpCodeAtan2, _FpCodeCabs, _FpCodeCos, _FpCodeCosh, _FpCodeExp, _FpCodeFabs, _FpCodeFmod, _FpCodeFrexp, _FpCodeHypot, _FpCodeLdexp, _FpCodeLog, _FpCodeLog10, _FpCodeModf, _FpCodePow, _FpCodeSin, _FpCodeSinh, _FpCodeTan, _FpCodeTanh, _FpCodeY0, _FpCodeY1, _FpCodeYn, _FpCodeLogb, _FpCodeNextafter, _FpCodeNegate, _FpCodeFmin, // XMMI _FpCodeFmax, // XMMI _FpCodeConvertTrunc, // XMMI _XMMIAddps, // XMMI _XMMIAddss, _XMMISubps, _XMMISubss, _XMMIMulps, _XMMIMulss, _XMMIDivps, _XMMIDivss, _XMMISqrtps, _XMMISqrtss, _XMMIMaxps, _XMMIMaxss, _XMMIMinps, _XMMIMinss, _XMMICmpps, _XMMICmpss, _XMMIComiss, _XMMIUComiss, _XMMICvtpi2ps, _XMMICvtsi2ss, _XMMICvtps2pi, _XMMICvtss2si, _XMMICvttps2pi, _XMMICvttss2si, _XMMIAddsubps, // XMMI for PNI _XMMIHaddps, // XMMI for PNI _XMMIHsubps, // XMMI for PNI _XMMIRoundps, // 66 0F 3A 08 _XMMIRoundss, // 66 0F 3A 0A _XMMIDpps, // 66 0F 3A 40 _XMMI2Addpd, // XMMI2 _XMMI2Addsd, _XMMI2Subpd, _XMMI2Subsd, _XMMI2Mulpd, _XMMI2Mulsd, _XMMI2Divpd, _XMMI2Divsd, _XMMI2Sqrtpd, _XMMI2Sqrtsd, _XMMI2Maxpd, _XMMI2Maxsd, _XMMI2Minpd, _XMMI2Minsd, _XMMI2Cmppd, _XMMI2Cmpsd, _XMMI2Comisd, _XMMI2UComisd, _XMMI2Cvtpd2pi, // 66 2D _XMMI2Cvtsd2si, // F2 _XMMI2Cvttpd2pi, // 66 2C _XMMI2Cvttsd2si, // F2 _XMMI2Cvtps2pd, // 0F 5A _XMMI2Cvtss2sd, // F3 _XMMI2Cvtpd2ps, // 66 _XMMI2Cvtsd2ss, // F2 _XMMI2Cvtdq2ps, // 0F 5B _XMMI2Cvttps2dq, // F3 _XMMI2Cvtps2dq, // 66 _XMMI2Cvttpd2dq, // 66 0F E6 _XMMI2Cvtpd2dq, // F2 _XMMI2Addsubpd, // 66 0F D0 _XMMI2Haddpd, // 66 0F 7C _XMMI2Hsubpd, // 66 0F 7D _XMMI2Roundpd, // 66 0F 3A 09 _XMMI2Roundsd, // 66 0F 3A 0B _XMMI2Dppd, // 66 0F 3A 41 } _FP_OPERATION_CODE; #endif // __assembler #ifdef _CORECRT_BUILD #ifndef __assembler #define OP_UNSPEC _FpCodeUnspecified #define OP_ADD _FpCodeAdd #define OP_SUB _FpCodeSubtract #define OP_MUL _FpCodeMultiply #define OP_DIV _FpCodeDivide #define OP_REM _FpCodeRemainder #define OP_COMP _FpCodeCompare #define OP_CVT _FpCodeConvert #define OP_RND _FpCodeRound #define OP_TRUNC _FpCodeTruncate #define OP_EXP _FpCodeExp #define OP_POW _FpCodePow #define OP_LOG _FpCodeLog #define OP_LOG10 _FpCodeLog10 #define OP_SINH _FpCodeSinh #define OP_COSH _FpCodeCosh #define OP_TANH _FpCodeTanh #define OP_ASIN _FpCodeAsin #define OP_ACOS _FpCodeAcos #define OP_ATAN _FpCodeAtan #define OP_ATAN2 _FpCodeAtan2 #define OP_SQRT _FpCodeSquareRoot #define OP_SIN _FpCodeSin #define OP_COS _FpCodeCos #define OP_TAN _FpCodeTan #define OP_CEIL _FpCodeCeil #define OP_FLOOR _FpCodeFloor #define OP_ABS _FpCodeFabs #define OP_MODF _FpCodeModf #define OP_LDEXP _FpCodeLdexp #define OP_CABS _FpCodeCabs #define OP_HYPOT _FpCodeHypot #define OP_FMOD _FpCodeFmod #define OP_FREXP _FpCodeFrexp #define OP_Y0 _FpCodeY0 #define OP_Y1 _FpCodeY1 #define OP_YN _FpCodeYn #define OP_LOGB _FpCodeLogb #define OP_NEXTAFTER _FpCodeNextafter // XMMI #define OP_ADDPS _XMMIAddps #define OP_ADDSS _XMMIAddss #define OP_SUBPS _XMMISubps #define OP_SUBSS _XMMISubss #define OP_MULPS _XMMIMulps #define OP_MULSS _XMMIMulss #define OP_DIVPS _XMMIDivps #define OP_DIVSS _XMMIDivss #define OP_SQRTPS _XMMISqrtps #define OP_SQRTSS _XMMISqrtss #define OP_MAXPS _XMMIMaxps #define OP_MAXSS _XMMIMaxss #define OP_MINPS _XMMIMinps #define OP_MINSS _XMMIMinss #define OP_CMPPS _XMMICmpps #define OP_CMPSS _XMMICmpss #define OP_COMISS _XMMIComiss #define OP_UCOMISS _XMMIUComiss #define OP_CVTPI2PS _XMMICvtpi2ps #define OP_CVTSI2SS _XMMICvtsi2ss #define OP_CVTPS2PI _XMMICvtps2pi #define OP_CVTSS2SI _XMMICvtss2si #define OP_CVTTPS2PI _XMMICvttps2pi #define OP_CVTTSS2SI _XMMICvttss2si #define OP_ADDSUBPS _XMMIAddsubps #define OP_HADDPS _XMMIHaddps #define OP_HSUBPS _XMMIHsubps #define OP_ROUNDPS _XMMIRoundps #define OP_ROUNDSS _XMMIRoundss #define OP_DPPS _XMMIDpps // XMMI // XMMI2 #define OP_ADDPD _XMMI2Addpd // XMMI2 #define OP_ADDSD _XMMI2Addsd #define OP_SUBPD _XMMI2Subpd #define OP_SUBSD _XMMI2Subsd #define OP_MULPD _XMMI2Mulpd #define OP_MULSD _XMMI2Mulsd #define OP_DIVPD _XMMI2Divpd #define OP_DIVSD _XMMI2Divsd #define OP_SQRTPD _XMMI2Sqrtpd #define OP_SQRTSD _XMMI2Sqrtsd #define OP_MAXPD _XMMI2Maxpd #define OP_MAXSD _XMMI2Maxsd #define OP_MINPD _XMMI2Minpd #define OP_MINSD _XMMI2Minsd #define OP_CMPPD _XMMI2Cmppd #define OP_CMPSD _XMMI2Cmpsd #define OP_COMISD _XMMI2Comisd #define OP_UCOMISD _XMMI2UComisd #define OP_CVTPD2PI _XMMI2Cvtpd2pi // 66 2D #define OP_CVTSD2SI _XMMI2Cvtsd2si // F2 #define OP_CVTTPD2PI _XMMI2Cvttpd2pi // 66 2C #define OP_CVTTSD2SI _XMMI2Cvttsd2si // F2 #define OP_CVTPS2PD _XMMI2Cvtps2pd // 0F 5A #define OP_CVTSS2SD _XMMI2Cvtss2sd // F3 #define OP_CVTPD2PS _XMMI2Cvtpd2ps // 66 #define OP_CVTSD2SS _XMMI2Cvtsd2ss // F2 #define OP_CVTDQ2PS _XMMI2Cvtdq2ps // 0F 5B #define OP_CVTTPS2DQ _XMMI2Cvttps2dq // F3 #define OP_CVTPS2DQ _XMMI2Cvtps2dq // 66 #define OP_CVTTPD2DQ _XMMI2Cvttpd2dq // 66 0F E6 #define OP_CVTPD2DQ _XMMI2Cvtpd2dq // F2 #define OP_ADDSUBPD _XMMI2Addsubpd // 66 0F D0 #define OP_HADDPD _XMMI2Haddpd // 66 0F 7C #define OP_HSUBPD _XMMI2Hsubpd // 66 0F 7D #define OP_ROUNDPD _XMMI2Roundpd // 66 0F 3A 09 #define OP_ROUNDSD _XMMI2Roundsd // 66 0F 3A 0B #define OP_DPPD _XMMI2Dppd // 66 0F 3A 41 // XMMI2 #else // __assembler // This must be the same as the enumerator _FP_OPERATION_CODE #define OP_UNSPEC 0 #define OP_ADD 1 #define OP_SUB 2 #define OP_MUL 3 #define OP_DIV 4 #define OP_SQRT 5 #define OP_REM 6 #define OP_COMP 7 #define OP_CVT 8 #define OP_RND 9 #define OP_TRUNC 10 #define OP_FLOOR 11 #define OP_CEIL 12 #define OP_ACOS 13 #define OP_ASIN 14 #define OP_ATAN 15 #define OP_ATAN2 16 #define OP_CABS 17 #define OP_COS 18 #define OP_COSH 19 #define OP_EXP 20 #define OP_ABS 21 // same as OP_FABS #define OP_FABS 21 // same as OP_ABS #define OP_FMOD 22 #define OP_FREXP 23 #define OP_HYPOT 24 #define OP_LDEXP 25 #define OP_LOG 26 #define OP_LOG10 27 #define OP_MODF 28 #define OP_POW 29 #define OP_SIN 30 #define OP_SINH 31 #define OP_TAN 32 #define OP_TANH 33 #define OP_Y0 34 #define OP_Y1 35 #define OP_YN 36 #define OP_LOGB 37 #define OP_NEXTAFTER 38 #define OP_NEG 39 #endif // __assembler #endif // _CORECRT_BUILD // Define rounding modes. #ifndef __assembler typedef enum { _FpRoundNearest, _FpRoundMinusInfinity, _FpRoundPlusInfinity, _FpRoundChopped } _FPIEEE_ROUNDING_MODE; typedef enum { _FpPrecisionFull, _FpPrecision53, _FpPrecision24, } _FPIEEE_PRECISION; // Define floating point context record typedef float _FP32; typedef double _FP64; typedef short _I16; typedef int _I32; typedef unsigned short _U16; typedef unsigned int _U32; typedef __int64 _Q64; #ifdef _CORECRT_BUILD typedef struct { unsigned long W[4]; } _U32ARRAY; #endif typedef struct { unsigned short W[5]; } _FP80; typedef struct _CRT_ALIGN(16) { unsigned long W[4]; } _FP128; typedef struct _CRT_ALIGN(8) { unsigned long W[2]; } _I64; typedef struct _CRT_ALIGN(8) { unsigned long W[2]; } _U64; typedef struct { unsigned short W[5]; } _BCD80; typedef struct _CRT_ALIGN(16) { _Q64 W[2]; } _FPQ64; typedef struct { union { _FP32 Fp32Value; _FP64 Fp64Value; _FP80 Fp80Value; _FP128 Fp128Value; _I16 I16Value; _I32 I32Value; _I64 I64Value; _U16 U16Value; _U32 U32Value; _U64 U64Value; _BCD80 Bcd80Value; char *StringValue; int CompareValue; #ifdef _CORECRT_BUILD _U32ARRAY U32ArrayValue; #endif _Q64 Q64Value; _FPQ64 Fpq64Value; } Value; unsigned int OperandValid : 1; unsigned int Format : 4; } _FPIEEE_VALUE; typedef struct { unsigned int Inexact : 1; unsigned int Underflow : 1; unsigned int Overflow : 1; unsigned int ZeroDivide : 1; unsigned int InvalidOperation : 1; } _FPIEEE_EXCEPTION_FLAGS; typedef struct { unsigned int RoundingMode : 2; unsigned int Precision : 3; unsigned int Operation : 12; _FPIEEE_EXCEPTION_FLAGS Cause; _FPIEEE_EXCEPTION_FLAGS Enable; _FPIEEE_EXCEPTION_FLAGS Status; _FPIEEE_VALUE Operand1; _FPIEEE_VALUE Operand2; _FPIEEE_VALUE Result; } _FPIEEE_RECORD, *_PFPIEEE_RECORD; struct _EXCEPTION_POINTERS; typedef int (__cdecl* _FpieeFltHandlerType)(_FPIEEE_RECORD*); // Floating point IEEE exception filter routine _ACRTIMP int __cdecl _fpieee_flt( _In_ unsigned long _ExceptionCode, _In_ struct _EXCEPTION_POINTERS* _PtExceptionPtr, _In_ _FpieeFltHandlerType _Handler ); #pragma warning(pop) #endif // __assembler _CRT_END_C_HEADER #endif // __midl
{ "language": "C" }
/***************************************************************************/ /* */ /* ftstdlib.h */ /* */ /* ANSI-specific library and header configuration file (specification */ /* only). */ /* */ /* Copyright 2002, 2003, 2004, 2005, 2006, 2007, 2009 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /*************************************************************************/ /* */ /* This file is used to group all #includes to the ANSI C library that */ /* FreeType normally requires. It also defines macros to rename the */ /* standard functions within the FreeType source code. */ /* */ /* Load a file which defines __FTSTDLIB_H__ before this one to override */ /* it. */ /* */ /*************************************************************************/ #ifndef __FTSTDLIB_H__ #define __FTSTDLIB_H__ #include <stddef.h> #define ft_ptrdiff_t ptrdiff_t /**********************************************************************/ /* */ /* integer limits */ /* */ /* UINT_MAX and ULONG_MAX are used to automatically compute the size */ /* of `int' and `long' in bytes at compile-time. So far, this works */ /* for all platforms the library has been tested on. */ /* */ /* Note that on the extremely rare platforms that do not provide */ /* integer types that are _exactly_ 16 and 32 bits wide (e.g. some */ /* old Crays where `int' is 36 bits), we do not make any guarantee */ /* about the correct behaviour of FT2 with all fonts. */ /* */ /* In these case, `ftconfig.h' will refuse to compile anyway with a */ /* message like `couldn't find 32-bit type' or something similar. */ /* */ /**********************************************************************/ #include <limits.h> #define FT_CHAR_BIT CHAR_BIT #define FT_INT_MAX INT_MAX #define FT_INT_MIN INT_MIN #define FT_UINT_MAX UINT_MAX #define FT_ULONG_MAX ULONG_MAX /**********************************************************************/ /* */ /* character and string processing */ /* */ /**********************************************************************/ #include <string.h> #define ft_memchr memchr #define ft_memcmp memcmp #define ft_memcpy memcpy #define ft_memmove memmove #define ft_memset memset #define ft_strcat strcat #define ft_strcmp strcmp #define ft_strcpy strcpy #define ft_strlen strlen #define ft_strncmp strncmp #define ft_strncpy strncpy #define ft_strrchr strrchr #define ft_strstr strstr /**********************************************************************/ /* */ /* file handling */ /* */ /**********************************************************************/ #include <stdio.h> #define FT_FILE FILE #define ft_fclose fclose #define ft_fopen fopen #define ft_fread fread #define ft_fseek fseek #define ft_ftell ftell #define ft_sprintf sprintf /**********************************************************************/ /* */ /* sorting */ /* */ /**********************************************************************/ #include <stdlib.h> #define ft_qsort qsort /**********************************************************************/ /* */ /* memory allocation */ /* */ /**********************************************************************/ #define ft_scalloc calloc #define ft_sfree free #define ft_smalloc malloc #define ft_srealloc realloc /**********************************************************************/ /* */ /* miscellaneous */ /* */ /**********************************************************************/ #define ft_atol atol #define ft_labs labs /**********************************************************************/ /* */ /* execution control */ /* */ /**********************************************************************/ #include <setjmp.h> #define ft_jmp_buf jmp_buf /* note: this cannot be a typedef since */ /* jmp_buf is defined as a macro */ /* on certain platforms */ #define ft_longjmp longjmp #define ft_setjmp( b ) setjmp( *(jmp_buf*) &(b) ) /* same thing here */ /* the following is only used for debugging purposes, i.e., if */ /* FT_DEBUG_LEVEL_ERROR or FT_DEBUG_LEVEL_TRACE are defined */ #include <stdarg.h> #endif /* __FTSTDLIB_H__ */ /* END */
{ "language": "C" }
/************************************************************ * thermali.c * * Copyright 2018 Inventec Technology Corporation. * ************************************************************ * * Thermal Sensor Platform Implementation. * ***********************************************************/ #include <unistd.h> #include <onlplib/file.h> #include <onlp/platformi/thermali.h> #include <fcntl.h> #include <onlp/platformi/psui.h> #include "platform_lib.h" #define VALIDATE(_id) \ do { \ if(!ONLP_OID_IS_THERMAL(_id)) { \ return ONLP_STATUS_E_INVALID; \ } \ } while(0) typedef struct thermali_path_s { char file[ONLP_CONFIG_INFO_STR_MAX]; } thermali_path_t; #define MAKE_THERMAL_PATH_ON_CPU(id) { "/var/coretemp/temp"#id"_input"} #define MAKE_THERMAL_PATH_ON_MAIN_BROAD(id) { "/var/thermal_"#id"/temp1_input"} #define MAKE_THERMAL_PATH_ON_PSU(psu_id,thermal_id) { "/var/psu"#psu_id"/temp"#thermal_id"_input"} static thermali_path_t __path_list[ ] = { {}, MAKE_THERMAL_PATH_ON_CPU(1), MAKE_THERMAL_PATH_ON_CPU(2), MAKE_THERMAL_PATH_ON_CPU(3), MAKE_THERMAL_PATH_ON_CPU(4), MAKE_THERMAL_PATH_ON_CPU(5), MAKE_THERMAL_PATH_ON_MAIN_BROAD(6), MAKE_THERMAL_PATH_ON_MAIN_BROAD(7), MAKE_THERMAL_PATH_ON_MAIN_BROAD(8), MAKE_THERMAL_PATH_ON_MAIN_BROAD(9), MAKE_THERMAL_PATH_ON_PSU(1,1), MAKE_THERMAL_PATH_ON_PSU(1,2), MAKE_THERMAL_PATH_ON_PSU(1,3), MAKE_THERMAL_PATH_ON_PSU(2,1), MAKE_THERMAL_PATH_ON_PSU(2,2), MAKE_THERMAL_PATH_ON_PSU(2,3) }; #define MAKE_THERMAL_INFO_NODE_ON_CPU_PHY \ { { ONLP_THERMAL_ID_CREATE(ONLP_THERMAL_CPU_PHY), "CPU Physical", 0}, \ ONLP_THERMAL_STATUS_PRESENT, \ ONLP_THERMAL_CAPS_GET_TEMPERATURE, 0, ONLP_THERMAL_THRESHOLD_INIT_DEFAULTS \ } #define MAKE_THERMAL_INFO_NODE_ON_CPU_CORE(id) \ { { ONLP_THERMAL_ID_CREATE(ONLP_THERMAL_CPU_CORE##id), "CPU Core "#id, 0},\ ONLP_THERMAL_STATUS_PRESENT, \ ONLP_THERMAL_CAPS_GET_TEMPERATURE, 0, ONLP_THERMAL_THRESHOLD_INIT_DEFAULTS \ } #define MAKE_THERMAL_INFO_NODE_ON_BROADS(id) \ { { ONLP_THERMAL_ID_CREATE(ONLP_THERMAL_##id##_ON_MAIN_BROAD), "Thermal Sensor "#id, 0}, \ ONLP_THERMAL_STATUS_PRESENT, \ ONLP_THERMAL_CAPS_GET_TEMPERATURE, 0, ONLP_THERMAL_THRESHOLD_INIT_DEFAULTS \ } #define MAKE_THERMAL_INFO_NODE_ON_PSU(thermal_id, psu_id) \ { { \ ONLP_THERMAL_ID_CREATE(ONLP_THERMAL_##thermal_id##_ON_PSU##psu_id), \ "PSU-"#psu_id" Thermal Sensor "#thermal_id, \ ONLP_PSU_ID_CREATE(ONLP_PSU_##psu_id) \ }, \ ONLP_THERMAL_STATUS_PRESENT, \ ONLP_THERMAL_CAPS_GET_TEMPERATURE, 0, ONLP_THERMAL_THRESHOLD_INIT_DEFAULTS \ } /* Static values */ static onlp_thermal_info_t __onlp_thermal_info[ ] = { {}, MAKE_THERMAL_INFO_NODE_ON_CPU_PHY, MAKE_THERMAL_INFO_NODE_ON_CPU_CORE(0), MAKE_THERMAL_INFO_NODE_ON_CPU_CORE(1), MAKE_THERMAL_INFO_NODE_ON_CPU_CORE(2), MAKE_THERMAL_INFO_NODE_ON_CPU_CORE(3), MAKE_THERMAL_INFO_NODE_ON_BROADS(1), MAKE_THERMAL_INFO_NODE_ON_BROADS(2), MAKE_THERMAL_INFO_NODE_ON_BROADS(3), MAKE_THERMAL_INFO_NODE_ON_BROADS(4), MAKE_THERMAL_INFO_NODE_ON_PSU(1,1), MAKE_THERMAL_INFO_NODE_ON_PSU(2,1), MAKE_THERMAL_INFO_NODE_ON_PSU(3,1), MAKE_THERMAL_INFO_NODE_ON_PSU(1,2), MAKE_THERMAL_INFO_NODE_ON_PSU(2,2), MAKE_THERMAL_INFO_NODE_ON_PSU(3,2), }; /* * This will be called to intiialize the thermali subsystem. */ int onlp_thermali_init(void) { return ONLP_STATUS_OK; } /* * Retrieve the information structure for the given thermal OID. * * If the OID is invalid, return ONLP_E_STATUS_INVALID. * If an unexpected error occurs, return ONLP_E_STATUS_INTERNAL. * Otherwise, return ONLP_STATUS_OK with the OID's information. * * Note -- it is expected that you fill out the information * structure even if the sensor described by the OID is not present. */ int onlp_thermali_info_get(onlp_oid_t id, onlp_thermal_info_t* info) { VALIDATE(id); int ret; int thermal_id = ONLP_OID_ID_GET(id); if(thermal_id >= ONLP_THERMAL_MAX) { return ONLP_STATUS_E_INVALID; } /* Set the onlp_oid_hdr_t and capabilities */ *info = __onlp_thermal_info[ thermal_id]; ret = onlp_thermali_status_get(id, &info->status); if( ret != ONLP_STATUS_OK ) { return ret; } if(info->status & ONLP_THERMAL_STATUS_PRESENT) { ret = onlp_file_read_int(&info->mcelsius, __path_list[thermal_id].file ); } return ret; } /** * @brief Retrieve the thermal's operational status. * @param id The thermal oid. * @param rv [out] Receives the operational status. */ int onlp_thermali_status_get(onlp_oid_t id, uint32_t* rv) { int ret = ONLP_STATUS_OK; onlp_thermal_info_t* info; VALIDATE(id); uint32_t psu_status; int thermal_id = ONLP_OID_ID_GET(id); if(thermal_id >= ONLP_THERMAL_MAX) { return ONLP_STATUS_E_INVALID; } info = &__onlp_thermal_info[ thermal_id]; switch(thermal_id) { case ONLP_THERMAL_1_ON_PSU1: case ONLP_THERMAL_2_ON_PSU1: case ONLP_THERMAL_3_ON_PSU1: case ONLP_THERMAL_1_ON_PSU2: case ONLP_THERMAL_2_ON_PSU2: case ONLP_THERMAL_3_ON_PSU2: ret = onlp_psui_status_get((&info->hdr)->poid, &psu_status); if(ret != ONLP_STATUS_OK) { return ret; } if(psu_status & ONLP_PSU_STATUS_PRESENT) { info->status = ADD_STATE(info->status,ONLP_PSU_STATUS_PRESENT); } else { info->status = 0; } break; default: break; } *rv = info->status; return ret; } /** * @brief Retrieve the thermal's oid header. * @param id The thermal oid. * @param rv [out] Receives the header. */ int onlp_thermali_hdr_get(onlp_oid_t id, onlp_oid_hdr_t* rv) { onlp_thermal_info_t* info; VALIDATE(id); int thermal_id = ONLP_OID_ID_GET(id); if(thermal_id >= ONLP_THERMAL_MAX) { return ONLP_STATUS_E_INVALID; } info = &__onlp_thermal_info[ thermal_id]; *rv = info->hdr; return ONLP_STATUS_OK; }
{ "language": "C" }
/* ** Package library. ** Copyright (C) 2005-2013 Mike Pall. See Copyright Notice in luajit.h ** ** Major portions taken verbatim or adapted from the Lua interpreter. ** Copyright (C) 1994-2012 Lua.org, PUC-Rio. See Copyright Notice in lua.h */ #define lib_package_c #define LUA_LIB #include "lua.h" #include "lauxlib.h" #include "lualib.h" #include "lj_obj.h" #include "lj_err.h" #include "lj_lib.h" /* ------------------------------------------------------------------------ */ /* Error codes for ll_loadfunc. */ #define PACKAGE_ERR_LIB 1 #define PACKAGE_ERR_FUNC 2 #define PACKAGE_ERR_LOAD 3 /* Redefined in platform specific part. */ #define PACKAGE_LIB_FAIL "open" #define setprogdir(L) ((void)0) /* Symbol name prefixes. */ #define SYMPREFIX_CF "luaopen_%s" #define SYMPREFIX_BC "luaJIT_BC_%s" #if LJ_TARGET_DLOPEN #include <dlfcn.h> static void ll_unloadlib(void *lib) { dlclose(lib); } static void *ll_load(lua_State *L, const char *path, int gl) { void *lib = dlopen(path, RTLD_NOW | (gl ? RTLD_GLOBAL : RTLD_LOCAL)); if (lib == NULL) lua_pushstring(L, dlerror()); return lib; } static lua_CFunction ll_sym(lua_State *L, void *lib, const char *sym) { lua_CFunction f = (lua_CFunction)dlsym(lib, sym); if (f == NULL) lua_pushstring(L, dlerror()); return f; } static const char *ll_bcsym(void *lib, const char *sym) { #if defined(RTLD_DEFAULT) if (lib == NULL) lib = RTLD_DEFAULT; #elif LJ_TARGET_OSX || LJ_TARGET_BSD if (lib == NULL) lib = (void *)(intptr_t)-2; #endif return (const char *)dlsym(lib, sym); } #elif LJ_TARGET_WINDOWS #define WIN32_LEAN_AND_MEAN #ifndef WINVER #define WINVER 0x0500 #endif #include <windows.h> #ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS #define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4 #define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2 BOOL WINAPI GetModuleHandleExA(DWORD, LPCSTR, HMODULE*); #endif #undef setprogdir static void setprogdir(lua_State *L) { char buff[MAX_PATH + 1]; char *lb; DWORD nsize = sizeof(buff); DWORD n = GetModuleFileNameA(NULL, buff, nsize); if (n == 0 || n == nsize || (lb = strrchr(buff, '\\')) == NULL) { luaL_error(L, "unable to get ModuleFileName"); } else { *lb = '\0'; luaL_gsub(L, lua_tostring(L, -1), LUA_EXECDIR, buff); lua_remove(L, -2); /* remove original string */ } } static void pusherror(lua_State *L) { DWORD error = GetLastError(); char buffer[128]; if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, buffer, sizeof(buffer), NULL)) lua_pushstring(L, buffer); else lua_pushfstring(L, "system error %d\n", error); } static void ll_unloadlib(void *lib) { FreeLibrary((HINSTANCE)lib); } static void *ll_load(lua_State *L, const char *path, int gl) { HINSTANCE lib = LoadLibraryA(path); if (lib == NULL) pusherror(L); UNUSED(gl); return lib; } static lua_CFunction ll_sym(lua_State *L, void *lib, const char *sym) { lua_CFunction f = (lua_CFunction)GetProcAddress((HINSTANCE)lib, sym); if (f == NULL) pusherror(L); return f; } static const char *ll_bcsym(void *lib, const char *sym) { if (lib) { return (const char *)GetProcAddress((HINSTANCE)lib, sym); } else { HINSTANCE h = GetModuleHandleA(NULL); const char *p = (const char *)GetProcAddress(h, sym); if (p == NULL && GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS|GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (const char *)ll_bcsym, &h)) p = (const char *)GetProcAddress(h, sym); return p; } } #else #undef PACKAGE_LIB_FAIL #define PACKAGE_LIB_FAIL "absent" #define DLMSG "dynamic libraries not enabled; no support for target OS" static void ll_unloadlib(void *lib) { UNUSED(lib); } static void *ll_load(lua_State *L, const char *path, int gl) { UNUSED(path); UNUSED(gl); lua_pushliteral(L, DLMSG); return NULL; } static lua_CFunction ll_sym(lua_State *L, void *lib, const char *sym) { UNUSED(lib); UNUSED(sym); lua_pushliteral(L, DLMSG); return NULL; } static const char *ll_bcsym(void *lib, const char *sym) { UNUSED(lib); UNUSED(sym); return NULL; } #endif /* ------------------------------------------------------------------------ */ static void **ll_register(lua_State *L, const char *path) { void **plib; lua_pushfstring(L, "LOADLIB: %s", path); lua_gettable(L, LUA_REGISTRYINDEX); /* check library in registry? */ if (!lua_isnil(L, -1)) { /* is there an entry? */ plib = (void **)lua_touserdata(L, -1); } else { /* no entry yet; create one */ lua_pop(L, 1); plib = (void **)lua_newuserdata(L, sizeof(void *)); *plib = NULL; luaL_getmetatable(L, "_LOADLIB"); lua_setmetatable(L, -2); lua_pushfstring(L, "LOADLIB: %s", path); lua_pushvalue(L, -2); lua_settable(L, LUA_REGISTRYINDEX); } return plib; } static const char *mksymname(lua_State *L, const char *modname, const char *prefix) { const char *funcname; const char *mark = strchr(modname, *LUA_IGMARK); if (mark) modname = mark + 1; funcname = luaL_gsub(L, modname, ".", "_"); funcname = lua_pushfstring(L, prefix, funcname); lua_remove(L, -2); /* remove 'gsub' result */ return funcname; } static int ll_loadfunc(lua_State *L, const char *path, const char *name, int r) { void **reg = ll_register(L, path); if (*reg == NULL) *reg = ll_load(L, path, (*name == '*')); if (*reg == NULL) { return PACKAGE_ERR_LIB; /* Unable to load library. */ } else if (*name == '*') { /* Only load library into global namespace. */ lua_pushboolean(L, 1); return 0; } else { const char *sym = r ? name : mksymname(L, name, SYMPREFIX_CF); lua_CFunction f = ll_sym(L, *reg, sym); if (f) { lua_pushcfunction(L, f); return 0; } if (!r) { const char *bcdata = ll_bcsym(*reg, mksymname(L, name, SYMPREFIX_BC)); lua_pop(L, 1); if (bcdata) { if (luaL_loadbuffer(L, bcdata, ~(size_t)0, name) != 0) return PACKAGE_ERR_LOAD; return 0; } } return PACKAGE_ERR_FUNC; /* Unable to find function. */ } } static int lj_cf_package_loadlib(lua_State *L) { const char *path = luaL_checkstring(L, 1); const char *init = luaL_checkstring(L, 2); int st = ll_loadfunc(L, path, init, 1); if (st == 0) { /* no errors? */ return 1; /* return the loaded function */ } else { /* error; error message is on stack top */ lua_pushnil(L); lua_insert(L, -2); lua_pushstring(L, (st == PACKAGE_ERR_LIB) ? PACKAGE_LIB_FAIL : "init"); return 3; /* return nil, error message, and where */ } } static int lj_cf_package_unloadlib(lua_State *L) { void **lib = (void **)luaL_checkudata(L, 1, "_LOADLIB"); if (*lib) ll_unloadlib(*lib); *lib = NULL; /* mark library as closed */ return 0; } /* ------------------------------------------------------------------------ */ static int readable(const char *filename) { FILE *f = fopen(filename, "r"); /* try to open file */ if (f == NULL) return 0; /* open failed */ fclose(f); return 1; } static const char *pushnexttemplate(lua_State *L, const char *path) { const char *l; while (*path == *LUA_PATHSEP) path++; /* skip separators */ if (*path == '\0') return NULL; /* no more templates */ l = strchr(path, *LUA_PATHSEP); /* find next separator */ if (l == NULL) l = path + strlen(path); lua_pushlstring(L, path, (size_t)(l - path)); /* template */ return l; } static const char *searchpath (lua_State *L, const char *name, const char *path, const char *sep, const char *dirsep) { luaL_Buffer msg; /* to build error message */ luaL_buffinit(L, &msg); if (*sep != '\0') /* non-empty separator? */ name = luaL_gsub(L, name, sep, dirsep); /* replace it by 'dirsep' */ while ((path = pushnexttemplate(L, path)) != NULL) { const char *filename = luaL_gsub(L, lua_tostring(L, -1), LUA_PATH_MARK, name); lua_remove(L, -2); /* remove path template */ if (readable(filename)) /* does file exist and is readable? */ return filename; /* return that file name */ lua_pushfstring(L, "\n\tno file " LUA_QS, filename); lua_remove(L, -2); /* remove file name */ luaL_addvalue(&msg); /* concatenate error msg. entry */ } luaL_pushresult(&msg); /* create error message */ return NULL; /* not found */ } static int lj_cf_package_searchpath(lua_State *L) { const char *f = searchpath(L, luaL_checkstring(L, 1), luaL_checkstring(L, 2), luaL_optstring(L, 3, "."), luaL_optstring(L, 4, LUA_DIRSEP)); if (f != NULL) { return 1; } else { /* error message is on top of the stack */ lua_pushnil(L); lua_insert(L, -2); return 2; /* return nil + error message */ } } static const char *findfile(lua_State *L, const char *name, const char *pname) { const char *path; lua_getfield(L, LUA_ENVIRONINDEX, pname); path = lua_tostring(L, -1); if (path == NULL) luaL_error(L, LUA_QL("package.%s") " must be a string", pname); return searchpath(L, name, path, ".", LUA_DIRSEP); } static void loaderror(lua_State *L, const char *filename) { luaL_error(L, "error loading module " LUA_QS " from file " LUA_QS ":\n\t%s", lua_tostring(L, 1), filename, lua_tostring(L, -1)); } static int lj_cf_package_loader_lua(lua_State *L) { const char *filename; const char *name = luaL_checkstring(L, 1); filename = findfile(L, name, "path"); if (filename == NULL) return 1; /* library not found in this path */ if (luaL_loadfile(L, filename) != 0) loaderror(L, filename); return 1; /* library loaded successfully */ } static int lj_cf_package_loader_c(lua_State *L) { const char *name = luaL_checkstring(L, 1); const char *filename = findfile(L, name, "cpath"); if (filename == NULL) return 1; /* library not found in this path */ if (ll_loadfunc(L, filename, name, 0) != 0) loaderror(L, filename); return 1; /* library loaded successfully */ } static int lj_cf_package_loader_croot(lua_State *L) { const char *filename; const char *name = luaL_checkstring(L, 1); const char *p = strchr(name, '.'); int st; if (p == NULL) return 0; /* is root */ lua_pushlstring(L, name, (size_t)(p - name)); filename = findfile(L, lua_tostring(L, -1), "cpath"); if (filename == NULL) return 1; /* root not found */ if ((st = ll_loadfunc(L, filename, name, 0)) != 0) { if (st != PACKAGE_ERR_FUNC) loaderror(L, filename); /* real error */ lua_pushfstring(L, "\n\tno module " LUA_QS " in file " LUA_QS, name, filename); return 1; /* function not found */ } return 1; } static int lj_cf_package_loader_preload(lua_State *L) { const char *name = luaL_checkstring(L, 1); lua_getfield(L, LUA_ENVIRONINDEX, "preload"); if (!lua_istable(L, -1)) luaL_error(L, LUA_QL("package.preload") " must be a table"); lua_getfield(L, -1, name); if (lua_isnil(L, -1)) { /* Not found? */ const char *bcname = mksymname(L, name, SYMPREFIX_BC); const char *bcdata = ll_bcsym(NULL, bcname); if (bcdata == NULL || luaL_loadbuffer(L, bcdata, ~(size_t)0, name) != 0) lua_pushfstring(L, "\n\tno field package.preload['%s']", name); } return 1; } /* ------------------------------------------------------------------------ */ static const int sentinel_ = 0; #define sentinel ((void *)&sentinel_) static int lj_cf_package_require(lua_State *L) { const char *name = luaL_checkstring(L, 1); int i; lua_settop(L, 1); /* _LOADED table will be at index 2 */ lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED"); lua_getfield(L, 2, name); if (lua_toboolean(L, -1)) { /* is it there? */ if (lua_touserdata(L, -1) == sentinel) /* check loops */ luaL_error(L, "loop or previous error loading module " LUA_QS, name); return 1; /* package is already loaded */ } /* else must load it; iterate over available loaders */ lua_getfield(L, LUA_ENVIRONINDEX, "loaders"); if (!lua_istable(L, -1)) luaL_error(L, LUA_QL("package.loaders") " must be a table"); lua_pushliteral(L, ""); /* error message accumulator */ for (i = 1; ; i++) { lua_rawgeti(L, -2, i); /* get a loader */ if (lua_isnil(L, -1)) luaL_error(L, "module " LUA_QS " not found:%s", name, lua_tostring(L, -2)); lua_pushstring(L, name); lua_call(L, 1, 1); /* call it */ if (lua_isfunction(L, -1)) /* did it find module? */ break; /* module loaded successfully */ else if (lua_isstring(L, -1)) /* loader returned error message? */ lua_concat(L, 2); /* accumulate it */ else lua_pop(L, 1); } lua_pushlightuserdata(L, sentinel); lua_setfield(L, 2, name); /* _LOADED[name] = sentinel */ lua_pushstring(L, name); /* pass name as argument to module */ lua_call(L, 1, 1); /* run loaded module */ if (!lua_isnil(L, -1)) /* non-nil return? */ lua_setfield(L, 2, name); /* _LOADED[name] = returned value */ lua_getfield(L, 2, name); if (lua_touserdata(L, -1) == sentinel) { /* module did not set a value? */ lua_pushboolean(L, 1); /* use true as result */ lua_pushvalue(L, -1); /* extra copy to be returned */ lua_setfield(L, 2, name); /* _LOADED[name] = true */ } lj_lib_checkfpu(L); return 1; } /* ------------------------------------------------------------------------ */ static void setfenv(lua_State *L) { lua_Debug ar; if (lua_getstack(L, 1, &ar) == 0 || lua_getinfo(L, "f", &ar) == 0 || /* get calling function */ lua_iscfunction(L, -1)) luaL_error(L, LUA_QL("module") " not called from a Lua function"); lua_pushvalue(L, -2); lua_setfenv(L, -2); lua_pop(L, 1); } static void dooptions(lua_State *L, int n) { int i; for (i = 2; i <= n; i++) { lua_pushvalue(L, i); /* get option (a function) */ lua_pushvalue(L, -2); /* module */ lua_call(L, 1, 0); } } static void modinit(lua_State *L, const char *modname) { const char *dot; lua_pushvalue(L, -1); lua_setfield(L, -2, "_M"); /* module._M = module */ lua_pushstring(L, modname); lua_setfield(L, -2, "_NAME"); dot = strrchr(modname, '.'); /* look for last dot in module name */ if (dot == NULL) dot = modname; else dot++; /* set _PACKAGE as package name (full module name minus last part) */ lua_pushlstring(L, modname, (size_t)(dot - modname)); lua_setfield(L, -2, "_PACKAGE"); } static int lj_cf_package_module(lua_State *L) { const char *modname = luaL_checkstring(L, 1); int loaded = lua_gettop(L) + 1; /* index of _LOADED table */ lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED"); lua_getfield(L, loaded, modname); /* get _LOADED[modname] */ if (!lua_istable(L, -1)) { /* not found? */ lua_pop(L, 1); /* remove previous result */ /* try global variable (and create one if it does not exist) */ if (luaL_findtable(L, LUA_GLOBALSINDEX, modname, 1) != NULL) lj_err_callerv(L, LJ_ERR_BADMODN, modname); lua_pushvalue(L, -1); lua_setfield(L, loaded, modname); /* _LOADED[modname] = new table */ } /* check whether table already has a _NAME field */ lua_getfield(L, -1, "_NAME"); if (!lua_isnil(L, -1)) { /* is table an initialized module? */ lua_pop(L, 1); } else { /* no; initialize it */ lua_pop(L, 1); modinit(L, modname); } lua_pushvalue(L, -1); setfenv(L); dooptions(L, loaded - 1); return 0; } static int lj_cf_package_seeall(lua_State *L) { luaL_checktype(L, 1, LUA_TTABLE); if (!lua_getmetatable(L, 1)) { lua_createtable(L, 0, 1); /* create new metatable */ lua_pushvalue(L, -1); lua_setmetatable(L, 1); } lua_pushvalue(L, LUA_GLOBALSINDEX); lua_setfield(L, -2, "__index"); /* mt.__index = _G */ return 0; } /* ------------------------------------------------------------------------ */ #define AUXMARK "\1" static void setpath(lua_State *L, const char *fieldname, const char *envname, const char *def, int noenv) { #if LJ_TARGET_CONSOLE const char *path = NULL; UNUSED(envname); #else const char *path = getenv(envname); #endif if (path == NULL || noenv) { lua_pushstring(L, def); } else { path = luaL_gsub(L, path, LUA_PATHSEP LUA_PATHSEP, LUA_PATHSEP AUXMARK LUA_PATHSEP); luaL_gsub(L, path, AUXMARK, def); lua_remove(L, -2); } setprogdir(L); lua_setfield(L, -2, fieldname); } static const luaL_Reg package_lib[] = { { "loadlib", lj_cf_package_loadlib }, { "searchpath", lj_cf_package_searchpath }, { "seeall", lj_cf_package_seeall }, { NULL, NULL } }; static const luaL_Reg package_global[] = { { "module", lj_cf_package_module }, { "require", lj_cf_package_require }, { NULL, NULL } }; static const lua_CFunction package_loaders[] = { lj_cf_package_loader_preload, lj_cf_package_loader_lua, lj_cf_package_loader_c, lj_cf_package_loader_croot, NULL }; LUALIB_API int luaopen_package(lua_State *L) { int i; int noenv; luaL_newmetatable(L, "_LOADLIB"); lj_lib_pushcf(L, lj_cf_package_unloadlib, 1); lua_setfield(L, -2, "__gc"); luaL_register(L, LUA_LOADLIBNAME, package_lib); lua_pushvalue(L, -1); lua_replace(L, LUA_ENVIRONINDEX); lua_createtable(L, sizeof(package_loaders)/sizeof(package_loaders[0])-1, 0); for (i = 0; package_loaders[i] != NULL; i++) { lj_lib_pushcf(L, package_loaders[i], 1); lua_rawseti(L, -2, i+1); } lua_setfield(L, -2, "loaders"); lua_getfield(L, LUA_REGISTRYINDEX, "LUA_NOENV"); noenv = lua_toboolean(L, -1); lua_pop(L, 1); setpath(L, "path", LUA_PATH, LUA_PATH_DEFAULT, noenv); setpath(L, "cpath", LUA_CPATH, LUA_CPATH_DEFAULT, noenv); lua_pushliteral(L, LUA_PATH_CONFIG); lua_setfield(L, -2, "config"); luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 16); lua_setfield(L, -2, "loaded"); luaL_findtable(L, LUA_REGISTRYINDEX, "_PRELOAD", 4); lua_setfield(L, -2, "preload"); lua_pushvalue(L, LUA_GLOBALSINDEX); luaL_register(L, NULL, package_global); lua_pop(L, 1); return 1; }
{ "language": "C" }
/* * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ #include <stdio.h> #include <string.h> #include <jni.h> #include "jli_util.h" /* * Returns a pointer to a block of at least 'size' bytes of memory. * Prints error message and exits if the memory could not be allocated. */ void * JLI_MemAlloc(size_t size) { void *p = malloc(size); if (p == 0) { perror("malloc"); exit(1); } return p; } /* * Equivalent to realloc(size). * Prints error message and exits if the memory could not be reallocated. */ void * JLI_MemRealloc(void *ptr, size_t size) { void *p = realloc(ptr, size); if (p == 0) { perror("realloc"); exit(1); } return p; } /* * Wrapper over strdup(3C) which prints an error message and exits if memory * could not be allocated. */ char * JLI_StringDup(const char *s1) { char *s = strdup(s1); if (s == NULL) { perror("strdup"); exit(1); } return s; } /* * Very equivalent to free(ptr). * Here to maintain pairing with the above routines. */ void JLI_MemFree(void *ptr) { free(ptr); } /* * debug helpers we use */ static jboolean _launcher_debug = JNI_FALSE; void JLI_TraceLauncher(const char* fmt, ...) { va_list vl; if (_launcher_debug != JNI_TRUE) return; va_start(vl, fmt); vprintf(fmt,vl); va_end(vl); } void JLI_SetTraceLauncher() { if (getenv(JLDEBUG_ENV_ENTRY) != 0) { _launcher_debug = JNI_TRUE; JLI_TraceLauncher("----%s----\n", JLDEBUG_ENV_ENTRY); } } jboolean JLI_IsTraceLauncher() { return _launcher_debug; } int JLI_StrCCmp(const char *s1, const char* s2) { return JLI_StrNCmp(s1, s2, JLI_StrLen(s2)); }
{ "language": "C" }
/** @file This is an origin server / intercept plugin, which implements flexible health checks. @section license Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <limits.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <unistd.h> #include <inttypes.h> /* ToDo: Linux specific */ #include <sys/inotify.h> #include <libgen.h> #include "ts/ts.h" #include "tscore/ink_platform.h" #include "tscore/ink_defs.h" static const char PLUGIN_NAME[] = "healthchecks"; static const char SEPARATORS[] = " \t\n"; #define MAX_PATH_LEN 4096 #define MAX_BODY_LEN 16384 #define FREELIST_TIMEOUT 300 static inline void * ink_atomic_swap_ptr(void *mem, void *value) { return __sync_lock_test_and_set((void **)mem, value); } /* Directories that we are watching for inotify IN_CREATE events. */ typedef struct HCDirEntry_t { char dname[MAX_PATH_LEN]; /* Directory name */ int wd; /* Watch descriptor */ struct HCDirEntry_t *_next; /* Linked list */ } HCDirEntry; /* Information about a status file. This is never modified (only replaced, see HCFileInfo_t) */ typedef struct HCFileData_t { int exists; /* Does this file exist */ char body[MAX_BODY_LEN]; /* Body from fname. NULL means file is missing */ int b_len; /* Length of data */ time_t remove; /* Used for deciding when the old object can be permanently removed */ struct HCFileData_t *_next; /* Only used when these guys end up on the freelist */ } HCFileData; /* The only thing that should change in this struct is data, atomically swapping ptrs */ typedef struct HCFileInfo_t { char fname[MAX_PATH_LEN]; /* Filename */ char *basename; /* The "basename" of the file */ char path[PATH_NAME_MAX]; /* URL path for this HC */ int p_len; /* Length of path */ const char *ok; /* Header for an OK result */ int o_len; /* Length of OK header */ const char *miss; /* Header for miss results */ int m_len; /* Length of miss header */ HCFileData *data; /* Holds the current data for this health check file */ int wd; /* Watch descriptor */ HCDirEntry *dir; /* Reference to the directory this file resides in */ struct HCFileInfo_t *_next; /* Linked list */ } HCFileInfo; /* Global configuration */ HCFileInfo *g_config; /* State used for the intercept plugin. ToDo: Can this be improved ? */ typedef struct HCState_t { TSVConn net_vc; TSVIO read_vio; TSVIO write_vio; TSIOBuffer req_buffer; TSIOBuffer resp_buffer; TSIOBufferReader resp_reader; int output_bytes; /* We actually need both here, so that our lock free switches works safely */ HCFileInfo *info; HCFileData *data; } HCState; /* Read / check the status files */ static void reload_status_file(HCFileInfo *info, HCFileData *data) { FILE *fd; memset(data, 0, sizeof(HCFileData)); if (NULL != (fd = fopen(info->fname, "r"))) { data->exists = 1; do { data->b_len = fread(data->body, 1, MAX_BODY_LEN, fd); } while (!feof(fd)); /* Only save the last 16KB of the file ... */ fclose(fd); } } /* Find a HCDirEntry from the linked list */ static HCDirEntry * find_direntry(const char *dname, HCDirEntry *dir) { while (dir) { if (!strncmp(dname, dir->dname, MAX_PATH_LEN)) { return dir; } dir = dir->_next; } return NULL; } /* Setup up watchers, directory as well as initial files */ static HCDirEntry * setup_watchers(int fd) { HCFileInfo *conf = g_config; HCDirEntry *head_dir = NULL, *last_dir = NULL, *dir; char fname[MAX_PATH_LEN]; while (conf) { conf->wd = inotify_add_watch(fd, conf->fname, IN_DELETE_SELF | IN_CLOSE_WRITE | IN_ATTRIB); TSDebug(PLUGIN_NAME, "Setting up a watcher for %s", conf->fname); strncpy(fname, conf->fname, MAX_PATH_LEN); char *dname = dirname(fname); /* Make sure to only watch each directory once */ if (!(dir = find_direntry(dname, head_dir))) { TSDebug(PLUGIN_NAME, "Setting up a watcher for directory %s", dname); dir = TSmalloc(sizeof(HCDirEntry)); memset(dir, 0, sizeof(HCDirEntry)); strncpy(dir->dname, dname, MAX_PATH_LEN - 1); dir->wd = inotify_add_watch(fd, dname, IN_CREATE | IN_MOVED_FROM | IN_MOVED_TO | IN_ATTRIB); if (!head_dir) { head_dir = dir; } else { last_dir->_next = dir; } last_dir = dir; } conf->dir = dir; conf = conf->_next; } return head_dir; } /* Separate thread to monitor status files for reload */ #define INOTIFY_BUFLEN (1024 * sizeof(struct inotify_event)) static void * hc_thread(void *data ATS_UNUSED) { int fd = inotify_init(); HCFileData *fl_head = NULL; char buffer[INOTIFY_BUFLEN]; struct timeval last_free, now; gettimeofday(&last_free, NULL); /* Setup watchers for the directories, these are a one time setup */ setup_watchers(fd); // This is a leak, but since we enter an infinite loop this is ok? while (1) { HCFileData *fdata = fl_head, *fdata_prev = NULL; gettimeofday(&now, NULL); /* Read the inotify events, blocking until we get something */ int len = read(fd, buffer, INOTIFY_BUFLEN); /* The fl_head is a linked list of previously released data entries. They are ordered "by time", so once we find one that is scheduled for deletion, we can also delete all entries after it in the linked list. */ while (fdata) { if (now.tv_sec > fdata->remove) { /* Now drop off the "tail" from the freelist */ if (fdata_prev) { fdata_prev->_next = NULL; } else { fl_head = NULL; } /* free() everything in the "tail" */ do { HCFileData *next = fdata->_next; TSDebug(PLUGIN_NAME, "Cleaning up entry from freelist"); TSfree(fdata); fdata = next; } while (fdata); break; /* Stop the loop, there's nothing else left to examine */ } fdata_prev = fdata; fdata = fdata->_next; } if (len >= 0) { int i = 0; while (i < len) { struct inotify_event *event = (struct inotify_event *)&buffer[i]; HCFileInfo *finfo = g_config; while (finfo && !((event->wd == finfo->wd) || ((event->wd == finfo->dir->wd) && !strncmp(event->name, finfo->basename, event->len)))) { finfo = finfo->_next; } if (finfo) { HCFileData *new_data = TSmalloc(sizeof(HCFileData)); HCFileData *old_data; if (event->mask & (IN_CLOSE_WRITE | IN_ATTRIB)) { TSDebug(PLUGIN_NAME, "Modify file event (%d) on %s", event->mask, finfo->fname); } else if (event->mask & (IN_CREATE | IN_MOVED_TO)) { TSDebug(PLUGIN_NAME, "Create file event (%d) on %s", event->mask, finfo->fname); finfo->wd = inotify_add_watch(fd, finfo->fname, IN_DELETE_SELF | IN_CLOSE_WRITE | IN_ATTRIB); } else if (event->mask & (IN_DELETE_SELF | IN_MOVED_FROM)) { TSDebug(PLUGIN_NAME, "Delete file event (%d) on %s", event->mask, finfo->fname); finfo->wd = inotify_rm_watch(fd, finfo->wd); } /* Load the new data and then swap this atomically */ memset(new_data, 0, sizeof(HCFileData)); reload_status_file(finfo, new_data); TSDebug(PLUGIN_NAME, "Reloaded %s, len == %d, exists == %d", finfo->fname, new_data->b_len, new_data->exists); old_data = ink_atomic_swap_ptr(&(finfo->data), new_data); /* Add the old data to the head of the freelist */ old_data->remove = now.tv_sec + FREELIST_TIMEOUT; old_data->_next = fl_head; fl_head = old_data; } /* coverity[ -tainted_data_return] */ i += sizeof(struct inotify_event) + event->len; } } } return NULL; /* Yeah, that never happens */ } /* Config file parsing */ static const char HEADER_TEMPLATE[] = "HTTP/1.1 %d %s\r\nContent-Type: %s\r\nCache-Control: no-cache\r\n"; static char * gen_header(char *status_str, char *mime, int *header_len) { TSHttpStatus status; char *buf = NULL; status = atoi(status_str); if (status > TS_HTTP_STATUS_NONE && status < (TSHttpStatus)999) { const char *status_reason; int len = sizeof(HEADER_TEMPLATE) + 3 + 1; status_reason = TSHttpHdrReasonLookup(status); len += strlen(status_reason); len += strlen(mime); buf = TSmalloc(len); *header_len = snprintf(buf, len, HEADER_TEMPLATE, status, status_reason, mime); } else { *header_len = 0; } return buf; } static HCFileInfo * parse_configs(const char *fname) { FILE *fd; char buf[2 * 1024]; HCFileInfo *head_finfo = NULL, *finfo = NULL, *prev_finfo = NULL; if (!fname) { return NULL; } if ('/' == *fname) { fd = fopen(fname, "r"); } else { char filename[PATH_MAX + 1]; snprintf(filename, sizeof(filename), "%s/%s", TSConfigDirGet(), fname); fd = fopen(filename, "r"); } if (NULL == fd) { TSError("%s: Could not open config file", PLUGIN_NAME); return NULL; } while (!feof(fd)) { char *str, *save; char *ok = NULL, *miss = NULL, *mime = NULL; finfo = TSmalloc(sizeof(HCFileInfo)); memset(finfo, 0, sizeof(HCFileInfo)); if (fgets(buf, sizeof(buf) - 1, fd)) { str = strtok_r(buf, SEPARATORS, &save); int state = 0; while (NULL != str) { if (strlen(str) > 0) { switch (state) { case 0: if ('/' == *str) { ++str; } strncpy(finfo->path, str, PATH_NAME_MAX - 1); finfo->p_len = strlen(finfo->path); break; case 1: strncpy(finfo->fname, str, MAX_PATH_LEN - 1); finfo->basename = strrchr(finfo->fname, '/'); if (finfo->basename) { ++(finfo->basename); } break; case 2: mime = str; break; case 3: ok = str; break; case 4: miss = str; break; } ++state; } str = strtok_r(NULL, SEPARATORS, &save); } /* Fill in the info if everything was ok */ if (state > 4) { TSDebug(PLUGIN_NAME, "Parsed: %s %s %s %s %s", finfo->path, finfo->fname, mime, ok, miss); finfo->ok = gen_header(ok, mime, &finfo->o_len); finfo->miss = gen_header(miss, mime, &finfo->m_len); finfo->data = TSmalloc(sizeof(HCFileData)); memset(finfo->data, 0, sizeof(HCFileData)); reload_status_file(finfo, finfo->data); /* Add it the linked list */ TSDebug(PLUGIN_NAME, "Adding path=%s to linked list", finfo->path); if (NULL == head_finfo) { head_finfo = finfo; } else { prev_finfo->_next = finfo; } prev_finfo = finfo; } else { TSfree(finfo); } } } fclose(fd); return head_finfo; } /* Cleanup after intercept has completed */ static void cleanup(TSCont contp, HCState *my_state) { if (my_state->req_buffer) { TSIOBufferDestroy(my_state->req_buffer); my_state->req_buffer = NULL; } if (my_state->resp_buffer) { TSIOBufferDestroy(my_state->resp_buffer); my_state->resp_buffer = NULL; } TSVConnClose(my_state->net_vc); TSfree(my_state); TSContDestroy(contp); } /* Add data to the output */ inline static int add_data_to_resp(const char *buf, int len, HCState *my_state) { TSIOBufferWrite(my_state->resp_buffer, buf, len); return len; } /* Process a read event from the SM */ static void hc_process_read(TSCont contp, TSEvent event, HCState *my_state) { if (event == TS_EVENT_VCONN_READ_READY) { if (my_state->data->exists) { TSDebug(PLUGIN_NAME, "Setting OK response header"); my_state->output_bytes = add_data_to_resp(my_state->info->ok, my_state->info->o_len, my_state); } else { TSDebug(PLUGIN_NAME, "Setting MISS response header"); my_state->output_bytes = add_data_to_resp(my_state->info->miss, my_state->info->m_len, my_state); } TSVConnShutdown(my_state->net_vc, 1, 0); my_state->write_vio = TSVConnWrite(my_state->net_vc, contp, my_state->resp_reader, INT64_MAX); } else if (event == TS_EVENT_ERROR) { TSError("[healthchecks] hc_process_read: Received TS_EVENT_ERROR"); } else if (event == TS_EVENT_VCONN_EOS) { /* client may end the connection, simply return */ return; } else if (event == TS_EVENT_NET_ACCEPT_FAILED) { TSError("[healthchecks] hc_process_read: Received TS_EVENT_NET_ACCEPT_FAILED"); } else { TSReleaseAssert(!"Unexpected Event"); } } /* Process a write event from the SM */ static void hc_process_write(TSCont contp, TSEvent event, HCState *my_state) { if (event == TS_EVENT_VCONN_WRITE_READY) { char buf[48]; int len; len = snprintf(buf, sizeof(buf), "Content-Length: %d\r\n\r\n", my_state->data->b_len); my_state->output_bytes += add_data_to_resp(buf, len, my_state); if (my_state->data->b_len > 0) { my_state->output_bytes += add_data_to_resp(my_state->data->body, my_state->data->b_len, my_state); } else { my_state->output_bytes += add_data_to_resp("\r\n", 2, my_state); } TSVIONBytesSet(my_state->write_vio, my_state->output_bytes); TSVIOReenable(my_state->write_vio); } else if (event == TS_EVENT_VCONN_WRITE_COMPLETE) { cleanup(contp, my_state); } else if (event == TS_EVENT_ERROR) { TSError("[healthchecks] hc_process_write: Received TS_EVENT_ERROR"); } else { TSReleaseAssert(!"Unexpected Event"); } } /* Process the accept event from the SM */ static void hc_process_accept(TSCont contp, HCState *my_state) { my_state->req_buffer = TSIOBufferCreate(); my_state->resp_buffer = TSIOBufferCreate(); my_state->resp_reader = TSIOBufferReaderAlloc(my_state->resp_buffer); my_state->read_vio = TSVConnRead(my_state->net_vc, contp, my_state->req_buffer, INT64_MAX); } /* Implement the server intercept */ static int hc_intercept(TSCont contp, TSEvent event, void *edata) { HCState *my_state = TSContDataGet(contp); if (event == TS_EVENT_NET_ACCEPT) { my_state->net_vc = (TSVConn)edata; hc_process_accept(contp, my_state); } else if (edata == my_state->read_vio) { /* All read events */ hc_process_read(contp, event, my_state); } else if (edata == my_state->write_vio) { /* All write events */ hc_process_write(contp, event, my_state); } else { TSReleaseAssert(!"Unexpected Event"); } return 0; } /* Read-request header continuation, used to kick off the server intercept if necessary */ static int health_check_origin(TSCont contp ATS_UNUSED, TSEvent event ATS_UNUSED, void *edata) { TSMBuffer reqp; TSMLoc hdr_loc = NULL, url_loc = NULL; TSCont icontp; HCState *my_state; TSHttpTxn txnp = (TSHttpTxn)edata; HCFileInfo *info = g_config; if ((TS_SUCCESS == TSHttpTxnClientReqGet(txnp, &reqp, &hdr_loc)) && (TS_SUCCESS == TSHttpHdrUrlGet(reqp, hdr_loc, &url_loc))) { int path_len = 0; const char *path = TSUrlPathGet(reqp, url_loc, &path_len); /* Short circuit the / path, common case, and we won't allow healthchecks on / */ if (!path || !path_len) { goto cleanup; } while (info) { if (info->p_len == path_len && !memcmp(info->path, path, path_len)) { TSDebug(PLUGIN_NAME, "Found match for /%.*s", path_len, path); break; } info = info->_next; } if (!info) { goto cleanup; } TSSkipRemappingSet(txnp, 1); /* not strictly necessary, but speed is everything these days */ /* This is us -- register our intercept */ icontp = TSContCreate(hc_intercept, TSMutexCreate()); my_state = (HCState *)TSmalloc(sizeof(*my_state)); memset(my_state, 0, sizeof(*my_state)); my_state->info = info; my_state->data = info->data; TSContDataSet(icontp, my_state); TSHttpTxnIntercept(icontp, txnp); } cleanup: if (url_loc) { TSHandleMLocRelease(reqp, hdr_loc, url_loc); } if (hdr_loc) { TSHandleMLocRelease(reqp, TS_NULL_MLOC, hdr_loc); } TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE); return 0; } /* Initialize the plugin / global continuation hook */ void TSPluginInit(int argc, const char *argv[]) { TSPluginRegistrationInfo info; if (2 != argc) { TSError("[healthchecks] Must specify a configuration file"); return; } info.plugin_name = "health_checks"; info.vendor_name = "Apache Software Foundation"; info.support_email = "dev@trafficserver.apache.org"; if (TS_SUCCESS != TSPluginRegister(&info)) { TSError("[healthchecks] Plugin registration failed"); return; } /* This will update the global configuration file, and is not reloaded at run time */ /* ToDo: Support reloading with traffic_ctl config reload ? */ if (NULL == (g_config = parse_configs(argv[1]))) { TSError("[healthchecks] Unable to read / parse %s config file", argv[1]); return; } /* Setup the background thread */ if (!TSThreadCreate(hc_thread, NULL)) { TSError("[healthchecks] Failure in thread creation"); return; } /* Create a continuation with a mutex as there is a shared global structure containing the headers to add */ TSDebug(PLUGIN_NAME, "Started %s plugin", PLUGIN_NAME); TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, TSContCreate(health_check_origin, NULL)); }
{ "language": "C" }
/* * Copyright (C) 2014 Traphandler * Copyright (C) 2014 Free Electrons * Copyright (C) 2014 Atmel * * Author: Jean-Jacques Hiblot <jjhiblot@traphandler.com> * Author: Boris BREZILLON <boris.brezillon@free-electrons.com> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ #include <linux/clk.h> #include <linux/irq.h> #include <linux/irqchip.h> #include <linux/module.h> #include <linux/pm_runtime.h> #include "atmel_hlcdc_dc.h" #define ATMEL_HLCDC_LAYER_IRQS_OFFSET 8 static const struct atmel_hlcdc_layer_desc atmel_hlcdc_at91sam9n12_layers[] = { { .name = "base", .formats = &atmel_hlcdc_plane_rgb_formats, .regs_offset = 0x40, .id = 0, .type = ATMEL_HLCDC_BASE_LAYER, .nconfigs = 5, .layout = { .xstride = { 2 }, .default_color = 3, .general_config = 4, }, }, }; static const struct atmel_hlcdc_dc_desc atmel_hlcdc_dc_at91sam9n12 = { .min_width = 0, .min_height = 0, .max_width = 1280, .max_height = 860, .max_spw = 0x3f, .max_vpw = 0x3f, .max_hpw = 0xff, .conflicting_output_formats = true, .nlayers = ARRAY_SIZE(atmel_hlcdc_at91sam9n12_layers), .layers = atmel_hlcdc_at91sam9n12_layers, }; static const struct atmel_hlcdc_layer_desc atmel_hlcdc_at91sam9x5_layers[] = { { .name = "base", .formats = &atmel_hlcdc_plane_rgb_formats, .regs_offset = 0x40, .id = 0, .type = ATMEL_HLCDC_BASE_LAYER, .nconfigs = 5, .layout = { .xstride = { 2 }, .default_color = 3, .general_config = 4, .disc_pos = 5, .disc_size = 6, }, }, { .name = "overlay1", .formats = &atmel_hlcdc_plane_rgb_formats, .regs_offset = 0x100, .id = 1, .type = ATMEL_HLCDC_OVERLAY_LAYER, .nconfigs = 10, .layout = { .pos = 2, .size = 3, .xstride = { 4 }, .pstride = { 5 }, .default_color = 6, .chroma_key = 7, .chroma_key_mask = 8, .general_config = 9, }, }, { .name = "high-end-overlay", .formats = &atmel_hlcdc_plane_rgb_and_yuv_formats, .regs_offset = 0x280, .id = 2, .type = ATMEL_HLCDC_OVERLAY_LAYER, .nconfigs = 17, .layout = { .pos = 2, .size = 3, .memsize = 4, .xstride = { 5, 7 }, .pstride = { 6, 8 }, .default_color = 9, .chroma_key = 10, .chroma_key_mask = 11, .general_config = 12, .csc = 14, }, }, { .name = "cursor", .formats = &atmel_hlcdc_plane_rgb_formats, .regs_offset = 0x340, .id = 3, .type = ATMEL_HLCDC_CURSOR_LAYER, .nconfigs = 10, .max_width = 128, .max_height = 128, .layout = { .pos = 2, .size = 3, .xstride = { 4 }, .default_color = 6, .chroma_key = 7, .chroma_key_mask = 8, .general_config = 9, }, }, }; static const struct atmel_hlcdc_dc_desc atmel_hlcdc_dc_at91sam9x5 = { .min_width = 0, .min_height = 0, .max_width = 800, .max_height = 600, .max_spw = 0x3f, .max_vpw = 0x3f, .max_hpw = 0xff, .conflicting_output_formats = true, .nlayers = ARRAY_SIZE(atmel_hlcdc_at91sam9x5_layers), .layers = atmel_hlcdc_at91sam9x5_layers, }; static const struct atmel_hlcdc_layer_desc atmel_hlcdc_sama5d3_layers[] = { { .name = "base", .formats = &atmel_hlcdc_plane_rgb_formats, .regs_offset = 0x40, .id = 0, .type = ATMEL_HLCDC_BASE_LAYER, .nconfigs = 7, .layout = { .xstride = { 2 }, .default_color = 3, .general_config = 4, .disc_pos = 5, .disc_size = 6, }, }, { .name = "overlay1", .formats = &atmel_hlcdc_plane_rgb_formats, .regs_offset = 0x140, .id = 1, .type = ATMEL_HLCDC_OVERLAY_LAYER, .nconfigs = 10, .layout = { .pos = 2, .size = 3, .xstride = { 4 }, .pstride = { 5 }, .default_color = 6, .chroma_key = 7, .chroma_key_mask = 8, .general_config = 9, }, }, { .name = "overlay2", .formats = &atmel_hlcdc_plane_rgb_formats, .regs_offset = 0x240, .id = 2, .type = ATMEL_HLCDC_OVERLAY_LAYER, .nconfigs = 10, .layout = { .pos = 2, .size = 3, .xstride = { 4 }, .pstride = { 5 }, .default_color = 6, .chroma_key = 7, .chroma_key_mask = 8, .general_config = 9, }, }, { .name = "high-end-overlay", .formats = &atmel_hlcdc_plane_rgb_and_yuv_formats, .regs_offset = 0x340, .id = 3, .type = ATMEL_HLCDC_OVERLAY_LAYER, .nconfigs = 42, .layout = { .pos = 2, .size = 3, .memsize = 4, .xstride = { 5, 7 }, .pstride = { 6, 8 }, .default_color = 9, .chroma_key = 10, .chroma_key_mask = 11, .general_config = 12, .csc = 14, }, }, { .name = "cursor", .formats = &atmel_hlcdc_plane_rgb_formats, .regs_offset = 0x440, .id = 4, .type = ATMEL_HLCDC_CURSOR_LAYER, .nconfigs = 10, .max_width = 128, .max_height = 128, .layout = { .pos = 2, .size = 3, .xstride = { 4 }, .pstride = { 5 }, .default_color = 6, .chroma_key = 7, .chroma_key_mask = 8, .general_config = 9, }, }, }; static const struct atmel_hlcdc_dc_desc atmel_hlcdc_dc_sama5d3 = { .min_width = 0, .min_height = 0, .max_width = 2048, .max_height = 2048, .max_spw = 0x3f, .max_vpw = 0x3f, .max_hpw = 0x1ff, .conflicting_output_formats = true, .nlayers = ARRAY_SIZE(atmel_hlcdc_sama5d3_layers), .layers = atmel_hlcdc_sama5d3_layers, }; static const struct atmel_hlcdc_layer_desc atmel_hlcdc_sama5d4_layers[] = { { .name = "base", .formats = &atmel_hlcdc_plane_rgb_formats, .regs_offset = 0x40, .id = 0, .type = ATMEL_HLCDC_BASE_LAYER, .nconfigs = 7, .layout = { .xstride = { 2 }, .default_color = 3, .general_config = 4, .disc_pos = 5, .disc_size = 6, }, }, { .name = "overlay1", .formats = &atmel_hlcdc_plane_rgb_formats, .regs_offset = 0x140, .id = 1, .type = ATMEL_HLCDC_OVERLAY_LAYER, .nconfigs = 10, .layout = { .pos = 2, .size = 3, .xstride = { 4 }, .pstride = { 5 }, .default_color = 6, .chroma_key = 7, .chroma_key_mask = 8, .general_config = 9, }, }, { .name = "overlay2", .formats = &atmel_hlcdc_plane_rgb_formats, .regs_offset = 0x240, .id = 2, .type = ATMEL_HLCDC_OVERLAY_LAYER, .nconfigs = 10, .layout = { .pos = 2, .size = 3, .xstride = { 4 }, .pstride = { 5 }, .default_color = 6, .chroma_key = 7, .chroma_key_mask = 8, .general_config = 9, }, }, { .name = "high-end-overlay", .formats = &atmel_hlcdc_plane_rgb_and_yuv_formats, .regs_offset = 0x340, .id = 3, .type = ATMEL_HLCDC_OVERLAY_LAYER, .nconfigs = 42, .layout = { .pos = 2, .size = 3, .memsize = 4, .xstride = { 5, 7 }, .pstride = { 6, 8 }, .default_color = 9, .chroma_key = 10, .chroma_key_mask = 11, .general_config = 12, .csc = 14, }, }, }; static const struct atmel_hlcdc_dc_desc atmel_hlcdc_dc_sama5d4 = { .min_width = 0, .min_height = 0, .max_width = 2048, .max_height = 2048, .max_spw = 0xff, .max_vpw = 0xff, .max_hpw = 0x3ff, .nlayers = ARRAY_SIZE(atmel_hlcdc_sama5d4_layers), .layers = atmel_hlcdc_sama5d4_layers, }; static const struct of_device_id atmel_hlcdc_of_match[] = { { .compatible = "atmel,at91sam9n12-hlcdc", .data = &atmel_hlcdc_dc_at91sam9n12, }, { .compatible = "atmel,at91sam9x5-hlcdc", .data = &atmel_hlcdc_dc_at91sam9x5, }, { .compatible = "atmel,sama5d2-hlcdc", .data = &atmel_hlcdc_dc_sama5d4, }, { .compatible = "atmel,sama5d3-hlcdc", .data = &atmel_hlcdc_dc_sama5d3, }, { .compatible = "atmel,sama5d4-hlcdc", .data = &atmel_hlcdc_dc_sama5d4, }, { /* sentinel */ }, }; MODULE_DEVICE_TABLE(of, atmel_hlcdc_of_match); int atmel_hlcdc_dc_mode_valid(struct atmel_hlcdc_dc *dc, struct drm_display_mode *mode) { int vfront_porch = mode->vsync_start - mode->vdisplay; int vback_porch = mode->vtotal - mode->vsync_end; int vsync_len = mode->vsync_end - mode->vsync_start; int hfront_porch = mode->hsync_start - mode->hdisplay; int hback_porch = mode->htotal - mode->hsync_end; int hsync_len = mode->hsync_end - mode->hsync_start; if (hsync_len > dc->desc->max_spw + 1 || hsync_len < 1) return MODE_HSYNC; if (vsync_len > dc->desc->max_spw + 1 || vsync_len < 1) return MODE_VSYNC; if (hfront_porch > dc->desc->max_hpw + 1 || hfront_porch < 1 || hback_porch > dc->desc->max_hpw + 1 || hback_porch < 1 || mode->hdisplay < 1) return MODE_H_ILLEGAL; if (vfront_porch > dc->desc->max_vpw + 1 || vfront_porch < 1 || vback_porch > dc->desc->max_vpw || vback_porch < 0 || mode->vdisplay < 1) return MODE_V_ILLEGAL; return MODE_OK; } static irqreturn_t atmel_hlcdc_dc_irq_handler(int irq, void *data) { struct drm_device *dev = data; struct atmel_hlcdc_dc *dc = dev->dev_private; unsigned long status; unsigned int imr, isr; int i; regmap_read(dc->hlcdc->regmap, ATMEL_HLCDC_IMR, &imr); regmap_read(dc->hlcdc->regmap, ATMEL_HLCDC_ISR, &isr); status = imr & isr; if (!status) return IRQ_NONE; if (status & ATMEL_HLCDC_SOF) atmel_hlcdc_crtc_irq(dc->crtc); for (i = 0; i < ATMEL_HLCDC_MAX_LAYERS; i++) { struct atmel_hlcdc_layer *layer = dc->layers[i]; if (!(ATMEL_HLCDC_LAYER_STATUS(i) & status) || !layer) continue; atmel_hlcdc_layer_irq(layer); } return IRQ_HANDLED; } static struct drm_framebuffer *atmel_hlcdc_fb_create(struct drm_device *dev, struct drm_file *file_priv, const struct drm_mode_fb_cmd2 *mode_cmd) { return drm_fb_cma_create(dev, file_priv, mode_cmd); } static void atmel_hlcdc_fb_output_poll_changed(struct drm_device *dev) { struct atmel_hlcdc_dc *dc = dev->dev_private; if (dc->fbdev) { drm_fbdev_cma_hotplug_event(dc->fbdev); } else { dc->fbdev = drm_fbdev_cma_init(dev, 24, dev->mode_config.num_crtc, dev->mode_config.num_connector); if (IS_ERR(dc->fbdev)) dc->fbdev = NULL; } } struct atmel_hlcdc_dc_commit { struct work_struct work; struct drm_device *dev; struct drm_atomic_state *state; }; static void atmel_hlcdc_dc_atomic_complete(struct atmel_hlcdc_dc_commit *commit) { struct drm_device *dev = commit->dev; struct atmel_hlcdc_dc *dc = dev->dev_private; struct drm_atomic_state *old_state = commit->state; /* Apply the atomic update. */ drm_atomic_helper_commit_modeset_disables(dev, old_state); drm_atomic_helper_commit_planes(dev, old_state, false); drm_atomic_helper_commit_modeset_enables(dev, old_state); drm_atomic_helper_wait_for_vblanks(dev, old_state); drm_atomic_helper_cleanup_planes(dev, old_state); drm_atomic_state_free(old_state); /* Complete the commit, wake up any waiter. */ spin_lock(&dc->commit.wait.lock); dc->commit.pending = false; wake_up_all_locked(&dc->commit.wait); spin_unlock(&dc->commit.wait.lock); kfree(commit); } static void atmel_hlcdc_dc_atomic_work(struct work_struct *work) { struct atmel_hlcdc_dc_commit *commit = container_of(work, struct atmel_hlcdc_dc_commit, work); atmel_hlcdc_dc_atomic_complete(commit); } static int atmel_hlcdc_dc_atomic_commit(struct drm_device *dev, struct drm_atomic_state *state, bool async) { struct atmel_hlcdc_dc *dc = dev->dev_private; struct atmel_hlcdc_dc_commit *commit; int ret; ret = drm_atomic_helper_prepare_planes(dev, state); if (ret) return ret; /* Allocate the commit object. */ commit = kzalloc(sizeof(*commit), GFP_KERNEL); if (!commit) { ret = -ENOMEM; goto error; } INIT_WORK(&commit->work, atmel_hlcdc_dc_atomic_work); commit->dev = dev; commit->state = state; spin_lock(&dc->commit.wait.lock); ret = wait_event_interruptible_locked(dc->commit.wait, !dc->commit.pending); if (ret == 0) dc->commit.pending = true; spin_unlock(&dc->commit.wait.lock); if (ret) { kfree(commit); goto error; } /* Swap the state, this is the point of no return. */ drm_atomic_helper_swap_state(dev, state); if (async) queue_work(dc->wq, &commit->work); else atmel_hlcdc_dc_atomic_complete(commit); return 0; error: drm_atomic_helper_cleanup_planes(dev, state); return ret; } static const struct drm_mode_config_funcs mode_config_funcs = { .fb_create = atmel_hlcdc_fb_create, .output_poll_changed = atmel_hlcdc_fb_output_poll_changed, .atomic_check = drm_atomic_helper_check, .atomic_commit = atmel_hlcdc_dc_atomic_commit, }; static int atmel_hlcdc_dc_modeset_init(struct drm_device *dev) { struct atmel_hlcdc_dc *dc = dev->dev_private; struct atmel_hlcdc_planes *planes; int ret; int i; drm_mode_config_init(dev); ret = atmel_hlcdc_create_outputs(dev); if (ret) { dev_err(dev->dev, "failed to create HLCDC outputs: %d\n", ret); return ret; } planes = atmel_hlcdc_create_planes(dev); if (IS_ERR(planes)) { dev_err(dev->dev, "failed to create planes\n"); return PTR_ERR(planes); } dc->planes = planes; dc->layers[planes->primary->layer.desc->id] = &planes->primary->layer; if (planes->cursor) dc->layers[planes->cursor->layer.desc->id] = &planes->cursor->layer; for (i = 0; i < planes->noverlays; i++) dc->layers[planes->overlays[i]->layer.desc->id] = &planes->overlays[i]->layer; ret = atmel_hlcdc_crtc_create(dev); if (ret) { dev_err(dev->dev, "failed to create crtc\n"); return ret; } dev->mode_config.min_width = dc->desc->min_width; dev->mode_config.min_height = dc->desc->min_height; dev->mode_config.max_width = dc->desc->max_width; dev->mode_config.max_height = dc->desc->max_height; dev->mode_config.funcs = &mode_config_funcs; return 0; } static int atmel_hlcdc_dc_load(struct drm_device *dev) { struct platform_device *pdev = to_platform_device(dev->dev); const struct of_device_id *match; struct atmel_hlcdc_dc *dc; int ret; match = of_match_node(atmel_hlcdc_of_match, dev->dev->parent->of_node); if (!match) { dev_err(&pdev->dev, "invalid compatible string\n"); return -ENODEV; } if (!match->data) { dev_err(&pdev->dev, "invalid hlcdc description\n"); return -EINVAL; } dc = devm_kzalloc(dev->dev, sizeof(*dc), GFP_KERNEL); if (!dc) return -ENOMEM; dc->wq = alloc_ordered_workqueue("atmel-hlcdc-dc", 0); if (!dc->wq) return -ENOMEM; init_waitqueue_head(&dc->commit.wait); dc->desc = match->data; dc->hlcdc = dev_get_drvdata(dev->dev->parent); dev->dev_private = dc; ret = clk_prepare_enable(dc->hlcdc->periph_clk); if (ret) { dev_err(dev->dev, "failed to enable periph_clk\n"); goto err_destroy_wq; } pm_runtime_enable(dev->dev); ret = drm_vblank_init(dev, 1); if (ret < 0) { dev_err(dev->dev, "failed to initialize vblank\n"); goto err_periph_clk_disable; } ret = atmel_hlcdc_dc_modeset_init(dev); if (ret < 0) { dev_err(dev->dev, "failed to initialize mode setting\n"); goto err_periph_clk_disable; } drm_mode_config_reset(dev); pm_runtime_get_sync(dev->dev); ret = drm_irq_install(dev, dc->hlcdc->irq); pm_runtime_put_sync(dev->dev); if (ret < 0) { dev_err(dev->dev, "failed to install IRQ handler\n"); goto err_periph_clk_disable; } platform_set_drvdata(pdev, dev); drm_kms_helper_poll_init(dev); /* force connectors detection */ drm_helper_hpd_irq_event(dev); return 0; err_periph_clk_disable: pm_runtime_disable(dev->dev); clk_disable_unprepare(dc->hlcdc->periph_clk); err_destroy_wq: destroy_workqueue(dc->wq); return ret; } static void atmel_hlcdc_dc_unload(struct drm_device *dev) { struct atmel_hlcdc_dc *dc = dev->dev_private; if (dc->fbdev) drm_fbdev_cma_fini(dc->fbdev); flush_workqueue(dc->wq); drm_kms_helper_poll_fini(dev); drm_mode_config_cleanup(dev); drm_vblank_cleanup(dev); pm_runtime_get_sync(dev->dev); drm_irq_uninstall(dev); pm_runtime_put_sync(dev->dev); dev->dev_private = NULL; pm_runtime_disable(dev->dev); clk_disable_unprepare(dc->hlcdc->periph_clk); destroy_workqueue(dc->wq); } static void atmel_hlcdc_dc_connector_unplug_all(struct drm_device *dev) { mutex_lock(&dev->mode_config.mutex); drm_connector_unregister_all(dev); mutex_unlock(&dev->mode_config.mutex); } static void atmel_hlcdc_dc_lastclose(struct drm_device *dev) { struct atmel_hlcdc_dc *dc = dev->dev_private; drm_fbdev_cma_restore_mode(dc->fbdev); } static int atmel_hlcdc_dc_irq_postinstall(struct drm_device *dev) { struct atmel_hlcdc_dc *dc = dev->dev_private; unsigned int cfg = 0; int i; /* Enable interrupts on activated layers */ for (i = 0; i < ATMEL_HLCDC_MAX_LAYERS; i++) { if (dc->layers[i]) cfg |= ATMEL_HLCDC_LAYER_STATUS(i); } regmap_write(dc->hlcdc->regmap, ATMEL_HLCDC_IER, cfg); return 0; } static void atmel_hlcdc_dc_irq_uninstall(struct drm_device *dev) { struct atmel_hlcdc_dc *dc = dev->dev_private; unsigned int isr; regmap_write(dc->hlcdc->regmap, ATMEL_HLCDC_IDR, 0xffffffff); regmap_read(dc->hlcdc->regmap, ATMEL_HLCDC_ISR, &isr); } static int atmel_hlcdc_dc_enable_vblank(struct drm_device *dev, unsigned int pipe) { struct atmel_hlcdc_dc *dc = dev->dev_private; /* Enable SOF (Start Of Frame) interrupt for vblank counting */ regmap_write(dc->hlcdc->regmap, ATMEL_HLCDC_IER, ATMEL_HLCDC_SOF); return 0; } static void atmel_hlcdc_dc_disable_vblank(struct drm_device *dev, unsigned int pipe) { struct atmel_hlcdc_dc *dc = dev->dev_private; regmap_write(dc->hlcdc->regmap, ATMEL_HLCDC_IDR, ATMEL_HLCDC_SOF); } static const struct file_operations fops = { .owner = THIS_MODULE, .open = drm_open, .release = drm_release, .unlocked_ioctl = drm_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = drm_compat_ioctl, #endif .poll = drm_poll, .read = drm_read, .llseek = no_llseek, .mmap = drm_gem_cma_mmap, }; static struct drm_driver atmel_hlcdc_dc_driver = { .driver_features = DRIVER_HAVE_IRQ | DRIVER_GEM | DRIVER_MODESET | DRIVER_PRIME | DRIVER_ATOMIC, .lastclose = atmel_hlcdc_dc_lastclose, .irq_handler = atmel_hlcdc_dc_irq_handler, .irq_preinstall = atmel_hlcdc_dc_irq_uninstall, .irq_postinstall = atmel_hlcdc_dc_irq_postinstall, .irq_uninstall = atmel_hlcdc_dc_irq_uninstall, .get_vblank_counter = drm_vblank_no_hw_counter, .enable_vblank = atmel_hlcdc_dc_enable_vblank, .disable_vblank = atmel_hlcdc_dc_disable_vblank, .gem_free_object = drm_gem_cma_free_object, .gem_vm_ops = &drm_gem_cma_vm_ops, .prime_handle_to_fd = drm_gem_prime_handle_to_fd, .prime_fd_to_handle = drm_gem_prime_fd_to_handle, .gem_prime_import = drm_gem_prime_import, .gem_prime_export = drm_gem_prime_export, .gem_prime_get_sg_table = drm_gem_cma_prime_get_sg_table, .gem_prime_import_sg_table = drm_gem_cma_prime_import_sg_table, .gem_prime_vmap = drm_gem_cma_prime_vmap, .gem_prime_vunmap = drm_gem_cma_prime_vunmap, .gem_prime_mmap = drm_gem_cma_prime_mmap, .dumb_create = drm_gem_cma_dumb_create, .dumb_map_offset = drm_gem_cma_dumb_map_offset, .dumb_destroy = drm_gem_dumb_destroy, .fops = &fops, .name = "atmel-hlcdc", .desc = "Atmel HLCD Controller DRM", .date = "20141504", .major = 1, .minor = 0, }; static int atmel_hlcdc_dc_drm_probe(struct platform_device *pdev) { struct drm_device *ddev; int ret; ddev = drm_dev_alloc(&atmel_hlcdc_dc_driver, &pdev->dev); if (!ddev) return -ENOMEM; ret = atmel_hlcdc_dc_load(ddev); if (ret) goto err_unref; ret = drm_dev_register(ddev, 0); if (ret) goto err_unload; ret = drm_connector_register_all(ddev); if (ret) goto err_unregister; return 0; err_unregister: drm_dev_unregister(ddev); err_unload: atmel_hlcdc_dc_unload(ddev); err_unref: drm_dev_unref(ddev); return ret; } static int atmel_hlcdc_dc_drm_remove(struct platform_device *pdev) { struct drm_device *ddev = platform_get_drvdata(pdev); atmel_hlcdc_dc_connector_unplug_all(ddev); drm_dev_unregister(ddev); atmel_hlcdc_dc_unload(ddev); drm_dev_unref(ddev); return 0; } #ifdef CONFIG_PM_SLEEP static int atmel_hlcdc_dc_drm_suspend(struct device *dev) { struct drm_device *drm_dev = dev_get_drvdata(dev); struct drm_crtc *crtc; if (pm_runtime_suspended(dev)) return 0; drm_modeset_lock_all(drm_dev); list_for_each_entry(crtc, &drm_dev->mode_config.crtc_list, head) atmel_hlcdc_crtc_suspend(crtc); drm_modeset_unlock_all(drm_dev); return 0; } static int atmel_hlcdc_dc_drm_resume(struct device *dev) { struct drm_device *drm_dev = dev_get_drvdata(dev); struct drm_crtc *crtc; if (pm_runtime_suspended(dev)) return 0; drm_modeset_lock_all(drm_dev); list_for_each_entry(crtc, &drm_dev->mode_config.crtc_list, head) atmel_hlcdc_crtc_resume(crtc); drm_modeset_unlock_all(drm_dev); return 0; } #endif static SIMPLE_DEV_PM_OPS(atmel_hlcdc_dc_drm_pm_ops, atmel_hlcdc_dc_drm_suspend, atmel_hlcdc_dc_drm_resume); static const struct of_device_id atmel_hlcdc_dc_of_match[] = { { .compatible = "atmel,hlcdc-display-controller" }, { }, }; static struct platform_driver atmel_hlcdc_dc_platform_driver = { .probe = atmel_hlcdc_dc_drm_probe, .remove = atmel_hlcdc_dc_drm_remove, .driver = { .name = "atmel-hlcdc-display-controller", .pm = &atmel_hlcdc_dc_drm_pm_ops, .of_match_table = atmel_hlcdc_dc_of_match, }, }; module_platform_driver(atmel_hlcdc_dc_platform_driver); MODULE_AUTHOR("Jean-Jacques Hiblot <jjhiblot@traphandler.com>"); MODULE_AUTHOR("Boris Brezillon <boris.brezillon@free-electrons.com>"); MODULE_DESCRIPTION("Atmel HLCDC Display Controller DRM Driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:atmel-hlcdc-dc");
{ "language": "C" }
#ifndef DDEBUG #define DDEBUG 0 #endif #include "ddebug.h" #include "ngx_http_lua_output.h" #include "ngx_http_lua_util.h" #include "ngx_http_lua_contentby.h" #include <math.h> static int ngx_http_lua_ngx_say(lua_State *L); static int ngx_http_lua_ngx_print(lua_State *L); static int ngx_http_lua_ngx_flush(lua_State *L); static int ngx_http_lua_ngx_eof(lua_State *L); static int ngx_http_lua_ngx_send_headers(lua_State *L); static int ngx_http_lua_ngx_echo(lua_State *L, unsigned newline); static void ngx_http_lua_flush_cleanup(void *data); static int ngx_http_lua_ngx_print(lua_State *L) { dd("calling lua print"); return ngx_http_lua_ngx_echo(L, 0); } static int ngx_http_lua_ngx_say(lua_State *L) { dd("calling"); return ngx_http_lua_ngx_echo(L, 1); } static int ngx_http_lua_ngx_echo(lua_State *L, unsigned newline) { ngx_http_request_t *r; ngx_http_lua_ctx_t *ctx; const char *p; size_t len; size_t size; ngx_buf_t *b; ngx_chain_t *cl; ngx_int_t rc; int i; int nargs; int type; const char *msg; r = ngx_http_lua_get_req(L); if (r == NULL) { return luaL_error(L, "no request object found"); } ctx = ngx_http_get_module_ctx(r, ngx_http_lua_module); if (ctx == NULL) { return luaL_error(L, "no request ctx found"); } ngx_http_lua_check_context(L, ctx, NGX_HTTP_LUA_CONTEXT_REWRITE | NGX_HTTP_LUA_CONTEXT_ACCESS | NGX_HTTP_LUA_CONTEXT_CONTENT); if (ctx->acquired_raw_req_socket) { lua_pushnil(L); lua_pushliteral(L, "raw request socket acquired"); return 2; } if (r->header_only) { lua_pushnil(L); lua_pushliteral(L, "header only"); return 2; } if (ctx->eof) { lua_pushnil(L); lua_pushliteral(L, "seen eof"); return 2; } nargs = lua_gettop(L); size = 0; for (i = 1; i <= nargs; i++) { type = lua_type(L, i); switch (type) { case LUA_TNUMBER: case LUA_TSTRING: lua_tolstring(L, i, &len); size += len; break; case LUA_TNIL: size += sizeof("nil") - 1; break; case LUA_TBOOLEAN: if (lua_toboolean(L, i)) { size += sizeof("true") - 1; } else { size += sizeof("false") - 1; } break; case LUA_TTABLE: size += ngx_http_lua_calc_strlen_in_table(L, i, i, 0 /* strict */); break; case LUA_TLIGHTUSERDATA: dd("userdata: %p", lua_touserdata(L, i)); if (lua_touserdata(L, i) == NULL) { size += sizeof("null") - 1; break; } continue; default: msg = lua_pushfstring(L, "string, number, boolean, nil, " "ngx.null, or array table expected, " "but got %s", lua_typename(L, type)); return luaL_argerror(L, i, msg); } } if (newline) { size += sizeof("\n") - 1; } if (size == 0) { /* do nothing for empty strings */ lua_pushinteger(L, 1); return 1; } cl = ngx_http_lua_chain_get_free_buf(r->connection->log, r->pool, &ctx->free_bufs, size); if (cl == NULL) { return luaL_error(L, "no memory"); } b = cl->buf; for (i = 1; i <= nargs; i++) { type = lua_type(L, i); switch (type) { case LUA_TNUMBER: case LUA_TSTRING: p = lua_tolstring(L, i, &len); b->last = ngx_copy(b->last, (u_char *) p, len); break; case LUA_TNIL: *b->last++ = 'n'; *b->last++ = 'i'; *b->last++ = 'l'; break; case LUA_TBOOLEAN: if (lua_toboolean(L, i)) { *b->last++ = 't'; *b->last++ = 'r'; *b->last++ = 'u'; *b->last++ = 'e'; } else { *b->last++ = 'f'; *b->last++ = 'a'; *b->last++ = 'l'; *b->last++ = 's'; *b->last++ = 'e'; } break; case LUA_TTABLE: b->last = ngx_http_lua_copy_str_in_table(L, i, b->last); break; case LUA_TLIGHTUSERDATA: *b->last++ = 'n'; *b->last++ = 'u'; *b->last++ = 'l'; *b->last++ = 'l'; break; default: return luaL_error(L, "impossible to reach here"); } } if (newline) { *b->last++ = '\n'; } #if 0 if (b->last != b->end) { return luaL_error(L, "buffer error: %p != %p", b->last, b->end); } #endif ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, newline ? "lua say response" : "lua print response"); rc = ngx_http_lua_send_chain_link(r, ctx, cl); if (rc == NGX_ERROR || rc >= NGX_HTTP_SPECIAL_RESPONSE) { lua_pushnil(L); lua_pushliteral(L, "nginx output filter error"); return 2; } dd("downstream write: %d, buf len: %d", (int) rc, (int) (b->last - b->pos)); lua_pushinteger(L, 1); return 1; } size_t ngx_http_lua_calc_strlen_in_table(lua_State *L, int index, int arg_i, unsigned strict) { double key; int max; int i; int type; size_t size; size_t len; const char *msg; if (index < 0) { index = lua_gettop(L) + index + 1; } dd("table index: %d", index); max = 0; lua_pushnil(L); /* stack: table key */ while (lua_next(L, index) != 0) { /* stack: table key value */ dd("key type: %s", luaL_typename(L, -2)); if (lua_type(L, -2) == LUA_TNUMBER) { key = lua_tonumber(L, -2); dd("key value: %d", (int) key); if (floor(key) == key && key >= 1) { if (key > max) { max = (int) key; } lua_pop(L, 1); /* stack: table key */ continue; } } /* not an array (non positive integer key) */ lua_pop(L, 2); /* stack: table */ luaL_argerror(L, arg_i, "non-array table found"); return 0; } size = 0; for (i = 1; i <= max; i++) { lua_rawgeti(L, index, i); /* stack: table value */ type = lua_type(L, -1); switch (type) { case LUA_TNUMBER: case LUA_TSTRING: lua_tolstring(L, -1, &len); size += len; break; case LUA_TNIL: if (strict) { goto bad_type; } size += sizeof("nil") - 1; break; case LUA_TBOOLEAN: if (strict) { goto bad_type; } if (lua_toboolean(L, -1)) { size += sizeof("true") - 1; } else { size += sizeof("false") - 1; } break; case LUA_TTABLE: size += ngx_http_lua_calc_strlen_in_table(L, -1, arg_i, strict); break; case LUA_TLIGHTUSERDATA: if (strict) { goto bad_type; } if (lua_touserdata(L, -1) == NULL) { size += sizeof("null") - 1; break; } continue; default: bad_type: msg = lua_pushfstring(L, "bad data type %s found", lua_typename(L, type)); return luaL_argerror(L, arg_i, msg); } lua_pop(L, 1); /* stack: table */ } return size; } u_char * ngx_http_lua_copy_str_in_table(lua_State *L, int index, u_char *dst) { double key; int max; int i; int type; size_t len; u_char *p; if (index < 0) { index = lua_gettop(L) + index + 1; } max = 0; lua_pushnil(L); /* stack: table key */ while (lua_next(L, index) != 0) { /* stack: table key value */ key = lua_tonumber(L, -2); if (key > max) { max = (int) key; } lua_pop(L, 1); /* stack: table key */ } for (i = 1; i <= max; i++) { lua_rawgeti(L, index, i); /* stack: table value */ type = lua_type(L, -1); switch (type) { case LUA_TNUMBER: case LUA_TSTRING: p = (u_char *) lua_tolstring(L, -1, &len); dst = ngx_copy(dst, p, len); break; case LUA_TNIL: *dst++ = 'n'; *dst++ = 'i'; *dst++ = 'l'; break; case LUA_TBOOLEAN: if (lua_toboolean(L, -1)) { *dst++ = 't'; *dst++ = 'r'; *dst++ = 'u'; *dst++ = 'e'; } else { *dst++ = 'f'; *dst++ = 'a'; *dst++ = 'l'; *dst++ = 's'; *dst++ = 'e'; } break; case LUA_TTABLE: dst = ngx_http_lua_copy_str_in_table(L, -1, dst); break; case LUA_TLIGHTUSERDATA: *dst++ = 'n'; *dst++ = 'u'; *dst++ = 'l'; *dst++ = 'l'; break; default: luaL_error(L, "impossible to reach here"); return NULL; } lua_pop(L, 1); /* stack: table */ } return dst; } /** * Force flush out response content * */ static int ngx_http_lua_ngx_flush(lua_State *L) { ngx_http_request_t *r; ngx_http_lua_ctx_t *ctx; ngx_chain_t *cl; ngx_int_t rc; int n; unsigned wait = 0; ngx_event_t *wev; ngx_http_core_loc_conf_t *clcf; ngx_http_lua_co_ctx_t *coctx; n = lua_gettop(L); if (n > 1) { return luaL_error(L, "attempt to pass %d arguments, but accepted 0 " "or 1", n); } r = ngx_http_lua_get_req(L); if (n == 1 && r == r->main) { luaL_checktype(L, 1, LUA_TBOOLEAN); wait = lua_toboolean(L, 1); } ctx = ngx_http_get_module_ctx(r, ngx_http_lua_module); if (ctx == NULL) { return luaL_error(L, "no request ctx found"); } ngx_http_lua_check_context(L, ctx, NGX_HTTP_LUA_CONTEXT_REWRITE | NGX_HTTP_LUA_CONTEXT_ACCESS | NGX_HTTP_LUA_CONTEXT_CONTENT); if (ctx->acquired_raw_req_socket) { lua_pushnil(L); lua_pushliteral(L, "raw request socket acquired"); return 2; } coctx = ctx->cur_co_ctx; if (coctx == NULL) { return luaL_error(L, "no co ctx found"); } if (r->header_only) { lua_pushnil(L); lua_pushliteral(L, "header only"); return 2; } if (ctx->eof) { lua_pushnil(L); lua_pushliteral(L, "seen eof"); return 2; } if (ctx->buffering) { ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "lua http 1.0 buffering makes ngx.flush() a no-op"); lua_pushnil(L); lua_pushliteral(L, "buffering"); return 2; } #if 1 if (!r->header_sent) { lua_pushnil(L); lua_pushliteral(L, "nothing to flush"); return 2; } #endif cl = ngx_http_lua_get_flush_chain(r, ctx); if (cl == NULL) { return luaL_error(L, "no memory"); } rc = ngx_http_lua_send_chain_link(r, ctx, cl); dd("send chain: %d", (int) rc); if (rc == NGX_ERROR || rc >= NGX_HTTP_SPECIAL_RESPONSE) { lua_pushnil(L); lua_pushliteral(L, "nginx output filter error"); return 2; } dd("wait:%d, rc:%d, buffered:0x%x", wait, (int) rc, r->connection->buffered); wev = r->connection->write; if (wait && (r->connection->buffered & NGX_HTTP_LOWLEVEL_BUFFERED || wev->delayed)) { ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "lua flush requires waiting: buffered 0x%uxd, " "delayed:%d", (unsigned) r->connection->buffered, wev->delayed); coctx->flushing = 1; ctx->flushing_coros++; if (ctx->entered_content_phase) { /* mimic ngx_http_set_write_handler */ r->write_event_handler = ngx_http_lua_content_wev_handler; } else { r->write_event_handler = ngx_http_core_run_phases; } clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module); if (!wev->delayed) { ngx_add_timer(wev, clcf->send_timeout); } if (ngx_handle_write_event(wev, clcf->send_lowat) != NGX_OK) { if (wev->timer_set) { wev->delayed = 0; ngx_del_timer(wev); } lua_pushnil(L); lua_pushliteral(L, "connection broken"); return 2; } ngx_http_lua_cleanup_pending_operation(ctx->cur_co_ctx); coctx->cleanup = ngx_http_lua_flush_cleanup; coctx->data = r; return lua_yield(L, 0); } ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "lua flush asynchronously"); lua_pushinteger(L, 1); return 1; } /** * Send last_buf, terminate output stream * */ static int ngx_http_lua_ngx_eof(lua_State *L) { ngx_http_request_t *r; ngx_http_lua_ctx_t *ctx; ngx_int_t rc; r = ngx_http_lua_get_req(L); if (r == NULL) { return luaL_error(L, "no request object found"); } if (lua_gettop(L) != 0) { return luaL_error(L, "no argument is expected"); } ctx = ngx_http_get_module_ctx(r, ngx_http_lua_module); if (ctx == NULL) { return luaL_error(L, "no ctx found"); } if (ctx->acquired_raw_req_socket) { lua_pushnil(L); lua_pushliteral(L, "raw request socket acquired"); return 2; } if (ctx->eof) { lua_pushnil(L); lua_pushliteral(L, "seen eof"); return 2; } ngx_http_lua_check_context(L, ctx, NGX_HTTP_LUA_CONTEXT_REWRITE | NGX_HTTP_LUA_CONTEXT_ACCESS | NGX_HTTP_LUA_CONTEXT_CONTENT); ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "lua send eof"); rc = ngx_http_lua_send_chain_link(r, ctx, NULL /* indicate last_buf */); dd("send chain: %d", (int) rc); if (rc == NGX_ERROR || rc >= NGX_HTTP_SPECIAL_RESPONSE) { lua_pushnil(L); lua_pushliteral(L, "nginx output filter error"); return 2; } lua_pushinteger(L, 1); return 1; } void ngx_http_lua_inject_output_api(lua_State *L) { lua_pushcfunction(L, ngx_http_lua_ngx_send_headers); lua_setfield(L, -2, "send_headers"); lua_pushcfunction(L, ngx_http_lua_ngx_print); lua_setfield(L, -2, "print"); lua_pushcfunction(L, ngx_http_lua_ngx_say); lua_setfield(L, -2, "say"); lua_pushcfunction(L, ngx_http_lua_ngx_flush); lua_setfield(L, -2, "flush"); lua_pushcfunction(L, ngx_http_lua_ngx_eof); lua_setfield(L, -2, "eof"); } /** * Send out headers * */ static int ngx_http_lua_ngx_send_headers(lua_State *L) { ngx_int_t rc; ngx_http_request_t *r; ngx_http_lua_ctx_t *ctx; r = ngx_http_lua_get_req(L); if (r == NULL) { return luaL_error(L, "no request found"); } ctx = ngx_http_get_module_ctx(r, ngx_http_lua_module); if (ctx == NULL) { return luaL_error(L, "no ctx found"); } ngx_http_lua_check_context(L, ctx, NGX_HTTP_LUA_CONTEXT_REWRITE | NGX_HTTP_LUA_CONTEXT_ACCESS | NGX_HTTP_LUA_CONTEXT_CONTENT); if (!r->header_sent) { ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "lua send headers"); rc = ngx_http_lua_send_header_if_needed(r, ctx); if (rc == NGX_ERROR || rc > NGX_OK) { lua_pushnil(L); lua_pushliteral(L, "nginx output filter error"); return 2; } } lua_pushinteger(L, 1); return 1; } ngx_int_t ngx_http_lua_flush_resume_helper(ngx_http_request_t *r, ngx_http_lua_ctx_t *ctx) { int n; lua_State *vm; ngx_int_t rc; ngx_connection_t *c; c = r->connection; ctx->cur_co_ctx->cleanup = NULL; /* push the return values */ if (c->timedout) { lua_pushnil(ctx->cur_co_ctx->co); lua_pushliteral(ctx->cur_co_ctx->co, "timeout"); n = 2; } else if (c->error) { lua_pushnil(ctx->cur_co_ctx->co); lua_pushliteral(ctx->cur_co_ctx->co, "client aborted"); n = 2; } else { lua_pushinteger(ctx->cur_co_ctx->co, 1); n = 1; } vm = ngx_http_lua_get_lua_vm(r, ctx); rc = ngx_http_lua_run_thread(vm, r, ctx, n); ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "lua run thread returned %d", rc); if (rc == NGX_AGAIN) { return ngx_http_lua_run_posted_threads(c, vm, r, ctx); } if (rc == NGX_DONE) { ngx_http_lua_finalize_request(r, NGX_DONE); return ngx_http_lua_run_posted_threads(c, vm, r, ctx); } /* rc == NGX_ERROR || rc >= NGX_OK */ if (ctx->entered_content_phase) { ngx_http_lua_finalize_request(r, rc); return NGX_DONE; } return rc; } static void ngx_http_lua_flush_cleanup(void *data) { ngx_http_request_t *r; ngx_event_t *wev; ngx_http_lua_ctx_t *ctx; ngx_http_lua_co_ctx_t *coctx = data; coctx->flushing = 0; r = coctx->data; if (r == NULL) { return; } wev = r->connection->write; if (wev && wev->timer_set) { ngx_del_timer(wev); } ctx = ngx_http_get_module_ctx(r, ngx_http_lua_module); if (ctx == NULL) { return; } ctx->flushing_coros--; } /* vi:set ft=c ts=4 sw=4 et fdm=marker: */
{ "language": "C" }
/// @author Alexander Rykovanov 2013 /// @email rykovanov.as@gmail.com /// @brief Monitored items services. /// @license GNU LGPL /// /// Distributed under the GNU LGPL License /// (See accompanying file LICENSE or copy at /// http://www.gnu.org/licenses/lgpl.html) /// #ifndef OPC_UA_MAPPINGS_MONITORED_ITEMS_H_ #define OPC_UA_MAPPINGS_MONITORED_ITEMS_H_ #include <opc/ua/protocol/protocol.h> namespace OpcUa { } #endif // OPC_UA_MAPPINGS_MONITORED_ITEMS_H_
{ "language": "C" }
/* htmlFromBeds - htmlFromBeds - This program creates a web page with a series of hyperlinks to the beds in the bed track. This is useful when a bed track is sparse and you want to just zoom to items instead of scrolling around.\n. */ /* Copyright (C) 2011 The Regents of the University of California * See README in this or parent directory for licensing information. */ #include "common.h" #include "linefile.h" #include "hash.h" #include "options.h" #include "bed.h" void usage() /* Explain usage and exit. */ { errAbort( "htmlFromBeds - htmlFromBeds - This program creates a web page with a\n" "series of hyperlinks to the beds in the bed track. This is useful\n" "when a bed track is sparse and you want to just zoom to items instead\n" "of scrolling around.\n" "usage:\n" " htmlFromBeds bedFile htmlFile db url\n" "options:\n" " -xxx=XXX\n" ); } struct bed *bedLoadAll(char *fileName) /* Load all bed's in file. */ { struct lineFile *lf = lineFileOpen(fileName, TRUE); struct bed *bedList = NULL, *bed; char *row[12]; while(lineFileRow(lf,row)) { bed = bedLoad12(row); slAddHead(&bedList, bed); } slReverse(&bedList); lineFileClose(&lf); return bedList; } void htmlFromBeds(char *bedFile, char *htmlFile, char *db, char *url) /* htmlFromBeds - htmlFromBeds - This program creates a web page with a series of hyperlinks to the beds in the bed track. This is useful when a bed track is sparse and you want to just zoom to items instead of scrolling around.\n. */ { struct bed *bed = NULL; struct bed *bedList = bedLoadAll(bedFile); FILE *htmlOut = mustOpen(htmlFile, "w"); slSort(&bedList, bedCmp); fprintf(htmlOut, "<html><body>\n<ul>\n"); for(bed = bedList; bed != NULL; bed = bed->next) { fprintf(htmlOut, "<li><a href=\"http://genome.ucsc.edu/cgi-bin/hgTracks?db=%s&position=%s:%d-%d&hgt.customText=%s/%s\">%s:%d-%d</a></li>\n", db, bed->chrom, bed->chromStart, bed->chromEnd, url, bedFile, bed->chrom, bed->chromStart, bed->chromEnd); } fprintf(htmlOut, "</ul></body></html>\n"); carefulClose(&htmlOut); } int main(int argc, char *argv[]) /* Process command line. */ { optionHash(&argc, argv); if (argc != 5) usage(); htmlFromBeds(argv[1], argv[2], argv[3], argv[4]); return 0; }
{ "language": "C" }
/** @file GUID for system configuration table entry that points to the table in case an entity in DXE wishes to update/change the vector table contents. Copyright (c) 2013 - 2018, Intel Corporation. All rights reserved.<BR> This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. @par Revision Reference: GUID defined in PI 1.2.1 spec. **/ #ifndef __EFI_VECTOR_HANDOFF_TABLE_H__ #define __EFI_VECTOR_HANDOFF_TABLE_H__ #include <Ppi/VectorHandoffInfo.h> // // System configuration table entry that points to the table // in case an entity in DXE wishes to update/change the vector // table contents. // #define EFI_VECTOR_HANDOF_TABLE_GUID \ { 0x996ec11c, 0x5397, 0x4e73, { 0xb5, 0x8f, 0x82, 0x7e, 0x52, 0x90, 0x6d, 0xef }} extern EFI_GUID gEfiVectorHandoffTableGuid; #endif
{ "language": "C" }
/* * This file is part of the Sofia-SIP package * * Copyright (C) 2005 Nokia Corporation. * * Contact: Pekka Pessi <pekka.pessi@nokia.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * */ /**@ingroup su_wait * @CFILE su_base_port.c * * OS-Independent Socket Syncronization Interface. * * This looks like nth reincarnation of "reactor". It implements the * poll/select/WaitForMultipleObjects and message passing functionality. * * @author Pekka Pessi <Pekka.Pessi@nokia.com> * @author Kai Vehmanen <kai.vehmanen@nokia.com> * * @date Created: Tue Sep 14 15:51:04 1999 ppessi */ #include "config.h" #define su_base_port_s su_port_s #define SU_CLONE_T su_msg_t #include "sofia-sip/su.h" #include "su_port.h" #include "sofia-sip/su_alloc.h" #include <stdlib.h> #include <assert.h> #include <stdarg.h> #include <stdio.h> #include <string.h> #include <limits.h> #include <errno.h> #if 1 #define PORT_REFCOUNT_DEBUG(x) ((void)0) #else #define PORT_REFCOUNT_DEBUG(x) printf x #endif static int su_base_port_execute_msgs(su_msg_t *queue); /**@internal * * Initialize a message port. * * @retval 0 when successful * @retval -1 upon an error */ int su_base_port_init(su_port_t *self, su_port_vtable_t const *vtable) { if (self) { self->sup_vtable = vtable; self->sup_tail = &self->sup_head; self->sup_max_defer = 15 * 1000; return su_port_obtain(self); } return -1; } /** @internal Deinit a base implementation of port. */ void su_base_port_deinit(su_port_t *self) { if (su_port_own_thread(self)) su_port_release(self); } void su_base_port_lock(su_port_t *self, char const *who) { } void su_base_port_unlock(su_port_t *self, char const *who) { } /** @internal Dummy implementation of su_port_thread() method. * * Currently this is only used if SU_HAVE_PTHREADS is 0. */ int su_base_port_thread(su_port_t const *self, enum su_port_thread_op op) { switch (op) { case su_port_thread_op_is_obtained: return 2; /* Current thread has obtained the port */ case su_port_thread_op_release: return errno = ENOSYS, -1; case su_port_thread_op_obtain: return 0; /* Allow initial obtain */ default: return errno = ENOSYS, -1; } } void su_base_port_incref(su_port_t *self, char const *who) { su_home_ref(self->sup_home); PORT_REFCOUNT_DEBUG(("incref(%p) to %u by %s\n", self, su_home_refcount(self->sup_home), who)); } int su_base_port_decref(su_port_t *self, int blocking, char const *who) { int zapped = su_home_unref(self->sup_home); PORT_REFCOUNT_DEBUG(("%s(%p) to %u%s by %s\n", blocking ? "zapref" : "decref", self, zapped ? 0 : su_home_refcount(self->sup_home), blocking && !zapped ? " FAILED" :"", who)); /* We should block until all references are destroyed */ if (blocking) /* ...but we just abort() */ assert(zapped); return zapped; } struct _GSource *su_base_port_gsource(su_port_t *self) { return NULL; } /** @internal Send a message to the port. * * @retval 0 if there are other messages in queue, too * @retval -1 upon an error */ int su_base_port_send(su_port_t *self, su_msg_r rmsg) { if (self) { int wakeup; su_port_lock(self, "su_port_send"); wakeup = self->sup_head == NULL; *self->sup_tail = rmsg[0]; rmsg[0] = NULL; self->sup_tail = &(*self->sup_tail)->sum_next; su_port_unlock(self, "su_port_send"); if (wakeup > 0) su_port_wakeup(self); return 0; } else { su_msg_destroy(rmsg); return -1; } } /** @internal * Execute the messages in the incoming queue. * * @param self - pointer to a port object * * @retval Number of messages executed */ int su_base_port_getmsgs(su_port_t *self) { if (self->sup_head) { su_msg_t *queue; su_port_lock(self, "su_base_port_getmsgs"); queue = self->sup_head; self->sup_tail = &self->sup_head; self->sup_head = NULL; su_port_unlock(self, "su_base_port_getmsgs"); return su_base_port_execute_msgs(queue); } return 0; } int su_base_port_getmsgs_from(su_port_t *self, su_port_t *from) { su_msg_t *msg, *selected; su_msg_t **next = &self->sup_head, **tail= &selected; if (!*next) return 0; su_port_lock(self, "su_base_port_getmsgs_from_port"); while (*next) { msg = *next; if (msg->sum_from->sut_port == from) { *tail = msg, *next = msg->sum_next, tail = &msg->sum_next; } else next = &msg->sum_next; } *tail = NULL, self->sup_tail = next; su_port_unlock(self, "su_base_port_getmsgs_from_port"); return su_base_port_execute_msgs(selected); } static int su_base_port_getmsgs_of_root(su_port_t *self, su_root_t *root) { su_msg_t *msg, *selected; su_msg_t **next = &self->sup_head, **tail= &selected; if (!*next) return 0; su_port_lock(self, "su_base_port_getmsgs_of_root"); while (*next) { msg = *next; if (msg->sum_from->sut_root == root || msg->sum_to->sut_root == root) { *tail = msg, *next = msg->sum_next, tail = &msg->sum_next; } else next = &msg->sum_next; } *tail = NULL, self->sup_tail = next; su_port_unlock(self, "su_base_port_getmsgs_of_root"); return su_base_port_execute_msgs(selected); } static int su_base_port_execute_msgs(su_msg_t *queue) { su_msg_t *msg; int n = 0; for (msg = queue; msg; msg = queue) { su_msg_f f = msg->sum_func; queue = msg->sum_next, msg->sum_next = NULL; if (f) { su_root_t *root = msg->sum_to->sut_root; if (msg->sum_to->sut_port == NULL) msg->sum_to->sut_root = NULL; f(SU_ROOT_MAGIC(root), &msg, msg->sum_data); } su_msg_delivery_report(&msg); n++; } return n; } /** @internal Enable multishot mode. * * The function su_port_multishot() enables, disables or queries the * multishot mode for the port. The multishot mode determines how the events * are scheduled by port. If multishot mode is enabled, port serves all the * sockets that have received network events. If it is disabled, the * socket events are server one at a time. * * @param self pointer to port object * @param multishot multishot mode (0 => disables, 1 => enables, -1 => query) * * @retval 0 multishot mode is disabled * @retval 1 multishot mode is enabled * @retval -1 an error occurred */ int su_base_port_multishot(su_port_t *self, int multishot) { return 0; } /** @internal Main loop. * * The function @c su_port_run() waits for wait objects and the timers * associated with the port object. When any wait object is signaled or * timer is expired, it invokes the callbacks, and returns waiting. * * The function @c su_port_run() runs until @c su_port_break() is called * from a callback. * * @param self pointer to port object * */ void su_base_port_run(su_port_t *self) { su_duration_t tout = 0, tout2 = 0; assert(su_port_own_thread(self)); for (self->sup_running = 1; self->sup_running;) { tout = self->sup_max_defer; if (self->sup_prepoll) self->sup_prepoll(self->sup_pp_magic, self->sup_pp_root); if (self->sup_head) self->sup_vtable->su_port_getmsgs(self); if (self->sup_timers || self->sup_deferrable) { su_time_t now = su_now(); su_timer_expire(&self->sup_timers, &tout, now); su_timer_expire(&self->sup_deferrable, &tout2, now); } if (!self->sup_running) break; if (self->sup_head) /* if there are messages do a quick wait */ tout = 0; self->sup_vtable->su_port_wait_events(self, tout); } } #if tuning /* This version can help tuning... */ void su_base_port_run_tune(su_port_t *self) { int i; int timers = 0, messages = 0, events = 0; su_duration_t tout = 0, tout2 = 0; su_time_t started = su_now(), woken = started, bedtime = woken; assert(su_port_own_thread(self)); for (self->sup_running = 1; self->sup_running;) { tout = self->sup_max_defer; timers = 0, messages = 0; if (self->sup_prepoll) self->sup_prepoll(self->sup_pp_magic, self->sup_pp_root); if (self->sup_head) messages = self->sup_vtable->su_port_getmsgs(self); if (self->sup_timers || self->sup_deferrable) { su_time_t now = su_now(); timers = su_timer_expire(&self->sup_timers, &tout, now) + su_timer_expire(&self->sup_deferrable, &tout2, now); } if (!self->sup_running) break; if (self->sup_head) /* if there are messages do a quick wait */ tout = 0; bedtime = su_now(); events = self->sup_vtable->su_port_wait_events(self, tout); woken = su_now(); if (messages || timers || events) SU_DEBUG_1(("su_port_run(%p): %.6f: %u messages %u timers %u " "events slept %.6f/%.3f\n", self, su_time_diff(woken, started), messages, timers, events, su_time_diff(woken, bedtime), tout * 1e-3)); if (!self->sup_running) break; } } #endif /** @internal * The function @c su_port_break() is used to terminate execution of @c * su_port_run(). It can be called from a callback function. * * @param self pointer to port * */ void su_base_port_break(su_port_t *self) { self->sup_running = 0; } /** @internal * Check if port is running. * * @param self pointer to port */ int su_base_port_is_running(su_port_t const *self) { return self->sup_running != 0; } /** @internal Block until wait object is signaled or timeout. * * This function waits for wait objects and the timers associated with * the root object. When any wait object is signaled or timer is * expired, it invokes the callbacks. * * This function returns when a callback has been invoked or @c tout * milliseconds is elapsed. * * @param self pointer to port * @param tout timeout in milliseconds * * @return * Milliseconds to the next invocation of timer, or @c SU_WAIT_FOREVER if * there are no active timers. */ su_duration_t su_base_port_step(su_port_t *self, su_duration_t tout) { su_time_t now = su_now(); assert(su_port_own_thread(self)); if (self->sup_prepoll) self->sup_prepoll(self->sup_pp_magic, self->sup_pp_root); if (self->sup_head) self->sup_vtable->su_port_getmsgs(self); if (self->sup_timers) su_timer_expire(&self->sup_timers, &tout, now); /* XXX: why isn't the timeout ignored here? */ if (self->sup_deferrable) su_timer_expire(&self->sup_deferrable, &tout, now); /* if there are messages do a quick wait */ if (self->sup_head) tout = 0; if (self->sup_vtable->su_port_wait_events(self, tout)) tout = 0; else tout = SU_WAIT_FOREVER; if (self->sup_head) { if (self->sup_vtable->su_port_getmsgs(self)) { /* Check for wait events that may have been generated by messages */ if (self->sup_vtable->su_port_wait_events(self, 0)) tout = 0; } } if (self->sup_timers || self->sup_deferrable) { su_duration_t tout2 = SU_WAIT_FOREVER; now = su_now(); su_timer_expire(&self->sup_timers, &tout, now); su_timer_expire(&self->sup_deferrable, &tout2, now); if (tout == SU_WAIT_FOREVER && tout2 != SU_WAIT_FOREVER) { if (tout2 < self->sup_max_defer) tout2 = self->sup_max_defer; tout = tout2; } } if (self->sup_head) tout = 0; return tout; } /* ========================================================================= * Pre-poll() callback */ int su_base_port_add_prepoll(su_port_t *self, su_root_t *root, su_prepoll_f *callback, su_prepoll_magic_t *magic) { if (self->sup_prepoll) return -1; self->sup_prepoll = callback; self->sup_pp_magic = magic; self->sup_pp_root = root; return 0; } int su_base_port_remove_prepoll(su_port_t *self, su_root_t *root) { if (self->sup_pp_root != root) return -1; self->sup_prepoll = NULL; self->sup_pp_magic = NULL; self->sup_pp_root = NULL; return 0; } /* ========================================================================= * Timers */ su_timer_queue_t *su_base_port_timers(su_port_t *self) { return &self->sup_timers; } su_timer_queue_t *su_base_port_deferrable(su_port_t *self) { return &self->sup_deferrable; } int su_base_port_max_defer(su_port_t *self, su_duration_t *return_duration, su_duration_t *set_duration) { if (set_duration && *set_duration > 0) self->sup_max_defer = *set_duration; if (return_duration) *return_duration = self->sup_max_defer; return 0; } /* ====================================================================== * Clones */ #define SU_TASK_COPY(d, s, by) (void)((d)[0]=(s)[0], \ (s)->sut_port?(void)su_port_incref(s->sut_port, #by):(void)0) static void su_base_port_clone_break(su_root_magic_t *m, su_msg_r msg, su_msg_arg_t *arg); int su_base_port_start_shared(su_root_t *parent, su_clone_r return_clone, su_root_magic_t *magic, su_root_init_f init, su_root_deinit_f deinit) { su_port_t *self = parent->sur_task->sut_port; su_root_t *child; child = su_salloc(su_port_home(self), sizeof *child); if (!child) return -1; child->sur_magic = magic; child->sur_deinit = deinit; child->sur_threading = parent->sur_threading; SU_TASK_COPY(child->sur_parent, su_root_task(parent), su_base_port_clone_start); SU_TASK_COPY(child->sur_task, child->sur_parent, su_base_port_clone_start); child->sur_task->sut_root = child; if (su_msg_create(return_clone, child->sur_task, su_root_task(parent), su_base_port_clone_break, 0) == 0 && init(child, magic) == 0) return 0; su_msg_destroy(return_clone); su_root_destroy(child); return -1; } static void su_base_port_clone_break(su_root_magic_t *m, su_msg_r msg, su_msg_arg_t *arg) { _su_task_t const *task = su_msg_to(msg); while (su_base_port_getmsgs_of_root(task->sut_port, task->sut_root)) ; su_root_destroy(task->sut_root); } /**Wait for the clone to exit. * @internal * * Called by su_port_wait() and su_clone_wait() */ void su_base_port_wait(su_clone_r rclone) { su_port_t *self; su_root_t *root_to_wait; assert(*rclone); self = su_msg_from(rclone)->sut_port; assert(self == su_msg_to(rclone)->sut_port); root_to_wait = su_msg_to(rclone)->sut_root; assert(rclone[0]->sum_func == su_base_port_clone_break); while (su_base_port_getmsgs_of_root(self, root_to_wait)) ; su_root_destroy(root_to_wait); su_msg_destroy(rclone); }
{ "language": "C" }
/* * Copyright 2012 Red Hat Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * Authors: Ben Skeggs */ #include <subdev/clock.h> #include <subdev/bios.h> #include <subdev/bios/pll.h> #include "pll.h" struct nv04_clock_priv { struct nouveau_clock base; }; static int powerctrl_1_shift(int chip_version, int reg) { int shift = -4; if (chip_version < 0x17 || chip_version == 0x1a || chip_version == 0x20) return shift; switch (reg) { case 0x680520: shift += 4; case 0x680508: shift += 4; case 0x680504: shift += 4; case 0x680500: shift += 4; } /* * the shift for vpll regs is only used for nv3x chips with a single * stage pll */ if (shift > 4 && (chip_version < 0x32 || chip_version == 0x35 || chip_version == 0x36 || chip_version >= 0x40)) shift = -4; return shift; } static void setPLL_single(struct nv04_clock_priv *priv, u32 reg, struct nouveau_pll_vals *pv) { int chip_version = nouveau_bios(priv)->version.chip; uint32_t oldpll = nv_rd32(priv, reg); int oldN = (oldpll >> 8) & 0xff, oldM = oldpll & 0xff; uint32_t pll = (oldpll & 0xfff80000) | pv->log2P << 16 | pv->NM1; uint32_t saved_powerctrl_1 = 0; int shift_powerctrl_1 = powerctrl_1_shift(chip_version, reg); if (oldpll == pll) return; /* already set */ if (shift_powerctrl_1 >= 0) { saved_powerctrl_1 = nv_rd32(priv, 0x001584); nv_wr32(priv, 0x001584, (saved_powerctrl_1 & ~(0xf << shift_powerctrl_1)) | 1 << shift_powerctrl_1); } if (oldM && pv->M1 && (oldN / oldM < pv->N1 / pv->M1)) /* upclock -- write new post divider first */ nv_wr32(priv, reg, pv->log2P << 16 | (oldpll & 0xffff)); else /* downclock -- write new NM first */ nv_wr32(priv, reg, (oldpll & 0xffff0000) | pv->NM1); if (chip_version < 0x17 && chip_version != 0x11) /* wait a bit on older chips */ msleep(64); nv_rd32(priv, reg); /* then write the other half as well */ nv_wr32(priv, reg, pll); if (shift_powerctrl_1 >= 0) nv_wr32(priv, 0x001584, saved_powerctrl_1); } static uint32_t new_ramdac580(uint32_t reg1, bool ss, uint32_t ramdac580) { bool head_a = (reg1 == 0x680508); if (ss) /* single stage pll mode */ ramdac580 |= head_a ? 0x00000100 : 0x10000000; else ramdac580 &= head_a ? 0xfffffeff : 0xefffffff; return ramdac580; } static void setPLL_double_highregs(struct nv04_clock_priv *priv, u32 reg1, struct nouveau_pll_vals *pv) { int chip_version = nouveau_bios(priv)->version.chip; bool nv3035 = chip_version == 0x30 || chip_version == 0x35; uint32_t reg2 = reg1 + ((reg1 == 0x680520) ? 0x5c : 0x70); uint32_t oldpll1 = nv_rd32(priv, reg1); uint32_t oldpll2 = !nv3035 ? nv_rd32(priv, reg2) : 0; uint32_t pll1 = (oldpll1 & 0xfff80000) | pv->log2P << 16 | pv->NM1; uint32_t pll2 = (oldpll2 & 0x7fff0000) | 1 << 31 | pv->NM2; uint32_t oldramdac580 = 0, ramdac580 = 0; bool single_stage = !pv->NM2 || pv->N2 == pv->M2; /* nv41+ only */ uint32_t saved_powerctrl_1 = 0, savedc040 = 0; int shift_powerctrl_1 = powerctrl_1_shift(chip_version, reg1); /* model specific additions to generic pll1 and pll2 set up above */ if (nv3035) { pll1 = (pll1 & 0xfcc7ffff) | (pv->N2 & 0x18) << 21 | (pv->N2 & 0x7) << 19 | 8 << 4 | (pv->M2 & 7) << 4; pll2 = 0; } if (chip_version > 0x40 && reg1 >= 0x680508) { /* !nv40 */ oldramdac580 = nv_rd32(priv, 0x680580); ramdac580 = new_ramdac580(reg1, single_stage, oldramdac580); if (oldramdac580 != ramdac580) oldpll1 = ~0; /* force mismatch */ if (single_stage) /* magic value used by nvidia in single stage mode */ pll2 |= 0x011f; } if (chip_version > 0x70) /* magic bits set by the blob (but not the bios) on g71-73 */ pll1 = (pll1 & 0x7fffffff) | (single_stage ? 0x4 : 0xc) << 28; if (oldpll1 == pll1 && oldpll2 == pll2) return; /* already set */ if (shift_powerctrl_1 >= 0) { saved_powerctrl_1 = nv_rd32(priv, 0x001584); nv_wr32(priv, 0x001584, (saved_powerctrl_1 & ~(0xf << shift_powerctrl_1)) | 1 << shift_powerctrl_1); } if (chip_version >= 0x40) { int shift_c040 = 14; switch (reg1) { case 0x680504: shift_c040 += 2; case 0x680500: shift_c040 += 2; case 0x680520: shift_c040 += 2; case 0x680508: shift_c040 += 2; } savedc040 = nv_rd32(priv, 0xc040); if (shift_c040 != 14) nv_wr32(priv, 0xc040, savedc040 & ~(3 << shift_c040)); } if (oldramdac580 != ramdac580) nv_wr32(priv, 0x680580, ramdac580); if (!nv3035) nv_wr32(priv, reg2, pll2); nv_wr32(priv, reg1, pll1); if (shift_powerctrl_1 >= 0) nv_wr32(priv, 0x001584, saved_powerctrl_1); if (chip_version >= 0x40) nv_wr32(priv, 0xc040, savedc040); } static void setPLL_double_lowregs(struct nv04_clock_priv *priv, u32 NMNMreg, struct nouveau_pll_vals *pv) { /* When setting PLLs, there is a merry game of disabling and enabling * various bits of hardware during the process. This function is a * synthesis of six nv4x traces, nearly each card doing a subtly * different thing. With luck all the necessary bits for each card are * combined herein. Without luck it deviates from each card's formula * so as to not work on any :) */ uint32_t Preg = NMNMreg - 4; bool mpll = Preg == 0x4020; uint32_t oldPval = nv_rd32(priv, Preg); uint32_t NMNM = pv->NM2 << 16 | pv->NM1; uint32_t Pval = (oldPval & (mpll ? ~(0x77 << 16) : ~(7 << 16))) | 0xc << 28 | pv->log2P << 16; uint32_t saved4600 = 0; /* some cards have different maskc040s */ uint32_t maskc040 = ~(3 << 14), savedc040; bool single_stage = !pv->NM2 || pv->N2 == pv->M2; if (nv_rd32(priv, NMNMreg) == NMNM && (oldPval & 0xc0070000) == Pval) return; if (Preg == 0x4000) maskc040 = ~0x333; if (Preg == 0x4058) maskc040 = ~(0xc << 24); if (mpll) { struct nvbios_pll info; uint8_t Pval2; if (nvbios_pll_parse(nouveau_bios(priv), Preg, &info)) return; Pval2 = pv->log2P + info.bias_p; if (Pval2 > info.max_p) Pval2 = info.max_p; Pval |= 1 << 28 | Pval2 << 20; saved4600 = nv_rd32(priv, 0x4600); nv_wr32(priv, 0x4600, saved4600 | 8 << 28); } if (single_stage) Pval |= mpll ? 1 << 12 : 1 << 8; nv_wr32(priv, Preg, oldPval | 1 << 28); nv_wr32(priv, Preg, Pval & ~(4 << 28)); if (mpll) { Pval |= 8 << 20; nv_wr32(priv, 0x4020, Pval & ~(0xc << 28)); nv_wr32(priv, 0x4038, Pval & ~(0xc << 28)); } savedc040 = nv_rd32(priv, 0xc040); nv_wr32(priv, 0xc040, savedc040 & maskc040); nv_wr32(priv, NMNMreg, NMNM); if (NMNMreg == 0x4024) nv_wr32(priv, 0x403c, NMNM); nv_wr32(priv, Preg, Pval); if (mpll) { Pval &= ~(8 << 20); nv_wr32(priv, 0x4020, Pval); nv_wr32(priv, 0x4038, Pval); nv_wr32(priv, 0x4600, saved4600); } nv_wr32(priv, 0xc040, savedc040); if (mpll) { nv_wr32(priv, 0x4020, Pval & ~(1 << 28)); nv_wr32(priv, 0x4038, Pval & ~(1 << 28)); } } int nv04_clock_pll_set(struct nouveau_clock *clk, u32 type, u32 freq) { struct nv04_clock_priv *priv = (void *)clk; struct nouveau_pll_vals pv; struct nvbios_pll info; int ret; ret = nvbios_pll_parse(nouveau_bios(priv), type > 0x405c ? type : type - 4, &info); if (ret) return ret; ret = clk->pll_calc(clk, &info, freq, &pv); if (!ret) return ret; return clk->pll_prog(clk, type, &pv); } int nv04_clock_pll_calc(struct nouveau_clock *clock, struct nvbios_pll *info, int clk, struct nouveau_pll_vals *pv) { int N1, M1, N2, M2, P; int ret = nv04_pll_calc(clock, info, clk, &N1, &M1, &N2, &M2, &P); if (ret) { pv->refclk = info->refclk; pv->N1 = N1; pv->M1 = M1; pv->N2 = N2; pv->M2 = M2; pv->log2P = P; } return ret; } int nv04_clock_pll_prog(struct nouveau_clock *clk, u32 reg1, struct nouveau_pll_vals *pv) { struct nv04_clock_priv *priv = (void *)clk; int cv = nouveau_bios(clk)->version.chip; if (cv == 0x30 || cv == 0x31 || cv == 0x35 || cv == 0x36 || cv >= 0x40) { if (reg1 > 0x405c) setPLL_double_highregs(priv, reg1, pv); else setPLL_double_lowregs(priv, reg1, pv); } else setPLL_single(priv, reg1, pv); return 0; } static int nv04_clock_ctor(struct nouveau_object *parent, struct nouveau_object *engine, struct nouveau_oclass *oclass, void *data, u32 size, struct nouveau_object **pobject) { struct nv04_clock_priv *priv; int ret; ret = nouveau_clock_create(parent, engine, oclass, &priv); *pobject = nv_object(priv); if (ret) return ret; priv->base.pll_set = nv04_clock_pll_set; priv->base.pll_calc = nv04_clock_pll_calc; priv->base.pll_prog = nv04_clock_pll_prog; return 0; } struct nouveau_oclass nv04_clock_oclass = { .handle = NV_SUBDEV(CLOCK, 0x04), .ofuncs = &(struct nouveau_ofuncs) { .ctor = nv04_clock_ctor, .dtor = _nouveau_clock_dtor, .init = _nouveau_clock_init, .fini = _nouveau_clock_fini, }, };
{ "language": "C" }
/* * Aic94xx SAS/SATA driver SAS definitions and hardware interface header file. * * Copyright (C) 2005 Adaptec, Inc. All rights reserved. * Copyright (C) 2005 Luben Tuikov <luben_tuikov@adaptec.com> * * This file is licensed under GPLv2. * * This file is part of the aic94xx driver. * * The aic94xx driver is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; version 2 of the * License. * * The aic94xx driver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with the aic94xx driver; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifndef _AIC94XX_SAS_H_ #define _AIC94XX_SAS_H_ #include <scsi/libsas.h> /* ---------- DDBs ---------- */ /* DDBs are device descriptor blocks which describe a device in the * domain that this sequencer can maintain low-level connections for * us. They are be 64 bytes. */ #define ASD_MAX_DDBS 128 struct asd_ddb_ssp_smp_target_port { u8 conn_type; /* byte 0 */ #define DDB_TP_CONN_TYPE 0x81 /* Initiator port and addr frame type 0x01 */ u8 conn_rate; __be16 init_conn_tag; u8 dest_sas_addr[8]; /* bytes 4-11 */ __le16 send_queue_head; u8 sq_suspended; u8 ddb_type; /* DDB_TYPE_TARGET */ #define DDB_TYPE_UNUSED 0xFF #define DDB_TYPE_TARGET 0xFE #define DDB_TYPE_INITIATOR 0xFD #define DDB_TYPE_PM_PORT 0xFC __le16 _r_a; __be16 awt_def; u8 compat_features; /* byte 20 */ u8 pathway_blocked_count; __be16 arb_wait_time; __be32 more_compat_features; /* byte 24 */ u8 conn_mask; u8 flags; /* concurrent conn:2,2 and open:0(1) */ #define CONCURRENT_CONN_SUPP 0x04 #define OPEN_REQUIRED 0x01 u16 _r_b; __le16 exec_queue_tail; __le16 send_queue_tail; __le16 sister_ddb; __le16 _r_c; u8 max_concurrent_conn; u8 num_concurrent_conn; u8 num_contexts; u8 _r_d; __le16 active_task_count; u8 _r_e[9]; u8 itnl_reason; /* I_T nexus loss reason */ __le16 _r_f; __le16 itnl_timeout; #define ITNL_TIMEOUT_CONST 0x7D0 /* 2 seconds */ __le32 itnl_timestamp; } __attribute__ ((packed)); struct asd_ddb_stp_sata_target_port { u8 conn_type; /* byte 0 */ u8 conn_rate; __be16 init_conn_tag; u8 dest_sas_addr[8]; /* bytes 4-11 */ __le16 send_queue_head; u8 sq_suspended; u8 ddb_type; /* DDB_TYPE_TARGET */ __le16 _r_a; __be16 awt_def; u8 compat_features; /* byte 20 */ u8 pathway_blocked_count; __be16 arb_wait_time; __be32 more_compat_features; /* byte 24 */ u8 conn_mask; u8 flags; /* concurrent conn:2,2 and open:0(1) */ #define SATA_MULTIPORT 0x80 #define SUPPORTS_AFFIL 0x40 #define STP_AFFIL_POL 0x20 u8 _r_b; u8 flags2; /* STP close policy:0 */ #define STP_CL_POL_NO_TX 0x00 #define STP_CL_POL_BTW_CMDS 0x01 __le16 exec_queue_tail; __le16 send_queue_tail; __le16 sister_ddb; __le16 ata_cmd_scbptr; __le32 sata_tag_alloc_mask; __le16 active_task_count; __le16 _r_c; __le32 sata_sactive; u8 num_sata_tags; u8 sata_status; u8 sata_ending_status; u8 itnl_reason; /* I_T nexus loss reason */ __le16 ncq_data_scb_ptr; __le16 itnl_timeout; __le32 itnl_timestamp; } __attribute__ ((packed)); /* This struct asd_ddb_init_port, describes the device descriptor block * of an initiator port (when the sequencer is operating in target mode). * Bytes [0,11] and [20,27] are from the OPEN address frame. * The sequencer allocates an initiator port DDB entry. */ struct asd_ddb_init_port { u8 conn_type; /* byte 0 */ u8 conn_rate; __be16 init_conn_tag; /* BE */ u8 dest_sas_addr[8]; __le16 send_queue_head; /* LE, byte 12 */ u8 sq_suspended; u8 ddb_type; /* DDB_TYPE_INITIATOR */ __le16 _r_a; __be16 awt_def; /* BE */ u8 compat_features; u8 pathway_blocked_count; __be16 arb_wait_time; /* BE */ __be32 more_compat_features; /* BE */ u8 conn_mask; u8 flags; /* == 5 */ u16 _r_b; __le16 exec_queue_tail; /* execution queue tail */ __le16 send_queue_tail; __le16 sister_ddb; __le16 init_resp_timeout; /* initiator response timeout */ __le32 _r_c; __le16 active_tasks; /* active task count */ __le16 init_list; /* initiator list link pointer */ __le32 _r_d; u8 max_conn_to[3]; /* from Conn-Disc mode page, in us, LE */ u8 itnl_reason; /* I_T nexus loss reason */ __le16 bus_inact_to; /* from Conn-Disc mode page, in 100 us, LE */ __le16 itnl_to; /* from the Protocol Specific Port Ctrl MP */ __le32 itnl_timestamp; } __attribute__ ((packed)); /* This struct asd_ddb_sata_tag, describes a look-up table to be used * by the sequencers. SATA II, IDENTIFY DEVICE data, word 76, bit 8: * NCQ support. This table is used by the sequencers to find the * corresponding SCB, given a SATA II tag value. */ struct asd_ddb_sata_tag { __le16 scb_pointer[32]; } __attribute__ ((packed)); /* This struct asd_ddb_sata_pm_table, describes a port number to * connection handle look-up table. SATA targets attached to a port * multiplier require a 4-bit port number value. There is one DDB * entry of this type for each SATA port multiplier (sister DDB). * Given a SATA PM port number, this table gives us the SATA PM Port * DDB of the SATA port multiplier port (i.e. the SATA target * discovered on the port). */ struct asd_ddb_sata_pm_table { __le16 ddb_pointer[16]; __le16 _r_a[16]; } __attribute__ ((packed)); /* This struct asd_ddb_sata_pm_port, describes the SATA port multiplier * port format DDB. */ struct asd_ddb_sata_pm_port { u8 _r_a[15]; u8 ddb_type; u8 _r_b[13]; u8 pm_port_flags; #define PM_PORT_MASK 0xF0 #define PM_PORT_SET 0x02 u8 _r_c[6]; __le16 sister_ddb; __le16 ata_cmd_scbptr; __le32 sata_tag_alloc_mask; __le16 active_task_count; __le16 parent_ddb; __le32 sata_sactive; u8 num_sata_tags; u8 sata_status; u8 sata_ending_status; u8 _r_d[9]; } __attribute__ ((packed)); /* This struct asd_ddb_seq_shared, describes a DDB shared by the * central and link sequencers. port_map_by_links is indexed phy * number [0,7]; each byte is a bit mask of all the phys that are in * the same port as the indexed phy. */ struct asd_ddb_seq_shared { __le16 q_free_ddb_head; __le16 q_free_ddb_tail; __le16 q_free_ddb_cnt; __le16 q_used_ddb_head; __le16 q_used_ddb_tail; __le16 shared_mem_lock; __le16 smp_conn_tag; __le16 est_nexus_buf_cnt; __le16 est_nexus_buf_thresh; u32 _r_a; u8 settable_max_contexts; u8 _r_b[23]; u8 conn_not_active; u8 phy_is_up; u8 _r_c[8]; u8 port_map_by_links[8]; } __attribute__ ((packed)); /* ---------- SG Element ---------- */ /* This struct sg_el, describes the hardware scatter gather buffer * element. All entries are little endian. In an SCB, there are 2 of * this, plus one more, called a link element of this indicating a * sublist if needed. * * A link element has only the bus address set and the flags (DS) bit * valid. The bus address points to the start of the sublist. * * If a sublist is needed, then that sublist should also include the 2 * sg_el embedded in the SCB, in which case next_sg_offset is 32, * since sizeof(sg_el) = 16; EOS should be 1 and EOL 0 in this case. */ struct sg_el { __le64 bus_addr; __le32 size; __le16 _r; u8 next_sg_offs; u8 flags; #define ASD_SG_EL_DS_MASK 0x30 #define ASD_SG_EL_DS_OCM 0x10 #define ASD_SG_EL_DS_HM 0x00 #define ASD_SG_EL_LIST_MASK 0xC0 #define ASD_SG_EL_LIST_EOL 0x40 #define ASD_SG_EL_LIST_EOS 0x80 } __attribute__ ((packed)); /* ---------- SCBs ---------- */ /* An SCB (sequencer control block) is comprised of a common header * and a task part, for a total of 128 bytes. All fields are in LE * order, unless otherwise noted. */ /* This struct scb_header, defines the SCB header format. */ struct scb_header { __le64 next_scb; __le16 index; /* transaction context */ u8 opcode; } __attribute__ ((packed)); /* SCB opcodes: Execution queue */ #define INITIATE_SSP_TASK 0x00 #define INITIATE_LONG_SSP_TASK 0x01 #define INITIATE_BIDIR_SSP_TASK 0x02 #define ABORT_TASK 0x03 #define INITIATE_SSP_TMF 0x04 #define SSP_TARG_GET_DATA 0x05 #define SSP_TARG_GET_DATA_GOOD 0x06 #define SSP_TARG_SEND_RESP 0x07 #define QUERY_SSP_TASK 0x08 #define INITIATE_ATA_TASK 0x09 #define INITIATE_ATAPI_TASK 0x0a #define CONTROL_ATA_DEV 0x0b #define INITIATE_SMP_TASK 0x0c #define SMP_TARG_SEND_RESP 0x0f /* SCB opcodes: Send Queue */ #define SSP_TARG_SEND_DATA 0x40 #define SSP_TARG_SEND_DATA_GOOD 0x41 /* SCB opcodes: Link Queue */ #define CONTROL_PHY 0x80 #define SEND_PRIMITIVE 0x81 #define INITIATE_LINK_ADM_TASK 0x82 /* SCB opcodes: other */ #define EMPTY_SCB 0xc0 #define INITIATE_SEQ_ADM_TASK 0xc1 #define EST_ICL_TARG_WINDOW 0xc2 #define COPY_MEM 0xc3 #define CLEAR_NEXUS 0xc4 #define INITIATE_DDB_ADM_TASK 0xc6 #define ESTABLISH_NEXUS_ESCB 0xd0 #define LUN_SIZE 8 /* See SAS spec, task IU */ struct ssp_task_iu { u8 lun[LUN_SIZE]; /* BE */ u16 _r_a; u8 tmf; u8 _r_b; __be16 tag; /* BE */ u8 _r_c[14]; } __attribute__ ((packed)); /* See SAS spec, command IU */ struct ssp_command_iu { u8 lun[LUN_SIZE]; u8 _r_a; u8 efb_prio_attr; /* enable first burst, task prio & attr */ #define EFB_MASK 0x80 #define TASK_PRIO_MASK 0x78 #define TASK_ATTR_MASK 0x07 u8 _r_b; u8 add_cdb_len; /* in dwords, since bit 0,1 are reserved */ union { u8 cdb[16]; struct { __le64 long_cdb_addr; /* bus address, LE */ __le32 long_cdb_size; /* LE */ u8 _r_c[3]; u8 eol_ds; /* eol:6,6, ds:5,4 */ } long_cdb; /* sequencer extension */ }; } __attribute__ ((packed)); struct xfer_rdy_iu { __be32 requested_offset; /* BE */ __be32 write_data_len; /* BE */ __be32 _r_a; } __attribute__ ((packed)); /* ---------- SCB tasks ---------- */ /* This is both ssp_task and long_ssp_task */ struct initiate_ssp_task { u8 proto_conn_rate; /* proto:6,4, conn_rate:3,0 */ __le32 total_xfer_len; struct ssp_frame_hdr ssp_frame; struct ssp_command_iu ssp_cmd; __le16 sister_scb; /* 0xFFFF */ __le16 conn_handle; /* index to DDB for the intended target */ u8 data_dir; /* :1,0 */ #define DATA_DIR_NONE 0x00 #define DATA_DIR_IN 0x01 #define DATA_DIR_OUT 0x02 #define DATA_DIR_BYRECIPIENT 0x03 u8 _r_a; u8 retry_count; u8 _r_b[5]; struct sg_el sg_element[3]; /* 2 real and 1 link */ } __attribute__ ((packed)); /* This defines both ata_task and atapi_task. * ata: C bit of FIS should be 1, * atapi: C bit of FIS should be 1, and command register should be 0xA0, * to indicate a packet command. */ struct initiate_ata_task { u8 proto_conn_rate; __le32 total_xfer_len; struct host_to_dev_fis fis; __le32 data_offs; u8 atapi_packet[16]; u8 _r_a[12]; __le16 sister_scb; __le16 conn_handle; u8 ata_flags; /* CSMI:6,6, DTM:4,4, QT:3,3, data dir:1,0 */ #define CSMI_TASK 0x40 #define DATA_XFER_MODE_DMA 0x10 #define ATA_Q_TYPE_MASK 0x08 #define ATA_Q_TYPE_UNTAGGED 0x00 #define ATA_Q_TYPE_NCQ 0x08 u8 _r_b; u8 retry_count; u8 _r_c; u8 flags; #define STP_AFFIL_POLICY 0x20 #define SET_AFFIL_POLICY 0x10 #define RET_PARTIAL_SGLIST 0x02 u8 _r_d[3]; struct sg_el sg_element[3]; } __attribute__ ((packed)); struct initiate_smp_task { u8 proto_conn_rate; u8 _r_a[40]; struct sg_el smp_req; __le16 sister_scb; __le16 conn_handle; u8 _r_c[8]; struct sg_el smp_resp; u8 _r_d[32]; } __attribute__ ((packed)); struct control_phy { u8 phy_id; u8 sub_func; #define DISABLE_PHY 0x00 #define ENABLE_PHY 0x01 #define RELEASE_SPINUP_HOLD 0x02 #define ENABLE_PHY_NO_SAS_OOB 0x03 #define ENABLE_PHY_NO_SATA_OOB 0x04 #define PHY_NO_OP 0x05 #define EXECUTE_HARD_RESET 0x81 u8 func_mask; u8 speed_mask; u8 hot_plug_delay; u8 port_type; u8 flags; #define DEV_PRES_TIMER_OVERRIDE_ENABLE 0x01 #define DISABLE_PHY_IF_OOB_FAILS 0x02 __le32 timeout_override; u8 link_reset_retries; u8 _r_a[47]; __le16 conn_handle; u8 _r_b[56]; } __attribute__ ((packed)); struct control_ata_dev { u8 proto_conn_rate; __le32 _r_a; struct host_to_dev_fis fis; u8 _r_b[32]; __le16 sister_scb; __le16 conn_handle; u8 ata_flags; /* 0 */ u8 _r_c[55]; } __attribute__ ((packed)); struct empty_scb { u8 num_valid; __le32 _r_a; #define ASD_EDBS_PER_SCB 7 /* header+data+CRC+DMA suffix data */ #define ASD_EDB_SIZE (24+1024+4+16) struct sg_el eb[ASD_EDBS_PER_SCB]; #define ELEMENT_NOT_VALID 0xC0 } __attribute__ ((packed)); struct initiate_link_adm { u8 phy_id; u8 sub_func; #define GET_LINK_ERROR_COUNT 0x00 #define RESET_LINK_ERROR_COUNT 0x01 #define ENABLE_NOTIFY_SPINUP_INTS 0x02 u8 _r_a[57]; __le16 conn_handle; u8 _r_b[56]; } __attribute__ ((packed)); struct copy_memory { u8 _r_a; __le16 xfer_len; __le16 _r_b; __le64 src_busaddr; u8 src_ds; /* See definition of sg_el */ u8 _r_c[45]; __le16 conn_handle; __le64 _r_d; __le64 dest_busaddr; u8 dest_ds; /* See definition of sg_el */ u8 _r_e[39]; } __attribute__ ((packed)); struct abort_task { u8 proto_conn_rate; __le32 _r_a; struct ssp_frame_hdr ssp_frame; struct ssp_task_iu ssp_task; __le16 sister_scb; __le16 conn_handle; u8 flags; /* ovrd_itnl_timer:3,3, suspend_data_trans:2,2 */ #define SUSPEND_DATA_TRANS 0x04 u8 _r_b; u8 retry_count; u8 _r_c[5]; __le16 index; /* Transaction context of task to be queried */ __le16 itnl_to; u8 _r_d[44]; } __attribute__ ((packed)); struct clear_nexus { u8 nexus; #define NEXUS_ADAPTER 0x00 #define NEXUS_PORT 0x01 #define NEXUS_I_T 0x02 #define NEXUS_I_T_L 0x03 #define NEXUS_TAG 0x04 #define NEXUS_TRANS_CX 0x05 #define NEXUS_SATA_TAG 0x06 #define NEXUS_T_L 0x07 #define NEXUS_L 0x08 #define NEXUS_T_TAG 0x09 __le32 _r_a; u8 flags; #define SUSPEND_TX 0x80 #define RESUME_TX 0x40 #define SEND_Q 0x04 #define EXEC_Q 0x02 #define NOTINQ 0x01 u8 _r_b[3]; u8 conn_mask; u8 _r_c[19]; struct ssp_task_iu ssp_task; /* LUN and TAG */ __le16 _r_d; __le16 conn_handle; __le64 _r_e; __le16 index; /* Transaction context of task to be cleared */ __le16 context; /* Clear nexus context */ u8 _r_f[44]; } __attribute__ ((packed)); struct initiate_ssp_tmf { u8 proto_conn_rate; __le32 _r_a; struct ssp_frame_hdr ssp_frame; struct ssp_task_iu ssp_task; __le16 sister_scb; __le16 conn_handle; u8 flags; /* itnl override and suspend data tx */ #define OVERRIDE_ITNL_TIMER 8 u8 _r_b; u8 retry_count; u8 _r_c[5]; __le16 index; /* Transaction context of task to be queried */ __le16 itnl_to; u8 _r_d[44]; } __attribute__ ((packed)); /* Transmits an arbitrary primitive on the link. * Used for NOTIFY and BROADCAST. */ struct send_prim { u8 phy_id; u8 wait_transmit; /* :0,0 */ u8 xmit_flags; #define XMTPSIZE_MASK 0xF0 #define XMTPSIZE_SINGLE 0x10 #define XMTPSIZE_REPEATED 0x20 #define XMTPSIZE_CONT 0x20 #define XMTPSIZE_TRIPLE 0x30 #define XMTPSIZE_REDUNDANT 0x60 #define XMTPSIZE_INF 0 #define XMTCONTEN 0x04 #define XMTPFRM 0x02 /* Transmit at the next frame boundary */ #define XMTPIMM 0x01 /* Transmit immediately */ __le16 _r_a; u8 prim[4]; /* K, D0, D1, D2 */ u8 _r_b[50]; __le16 conn_handle; u8 _r_c[56]; } __attribute__ ((packed)); /* This describes both SSP Target Get Data and SSP Target Get Data And * Send Good Response SCBs. Used when the sequencer is operating in * target mode... */ struct ssp_targ_get_data { u8 proto_conn_rate; __le32 total_xfer_len; struct ssp_frame_hdr ssp_frame; struct xfer_rdy_iu xfer_rdy; u8 lun[LUN_SIZE]; __le64 _r_a; __le16 sister_scb; __le16 conn_handle; u8 data_dir; /* 01b */ u8 _r_b; u8 retry_count; u8 _r_c[5]; struct sg_el sg_element[3]; } __attribute__ ((packed)); /* ---------- The actual SCB struct ---------- */ struct scb { struct scb_header header; union { struct initiate_ssp_task ssp_task; struct initiate_ata_task ata_task; struct initiate_smp_task smp_task; struct control_phy control_phy; struct control_ata_dev control_ata_dev; struct empty_scb escb; struct initiate_link_adm link_adm; struct copy_memory cp_mem; struct abort_task abort_task; struct clear_nexus clear_nexus; struct initiate_ssp_tmf ssp_tmf; }; } __attribute__ ((packed)); /* ---------- Done List ---------- */ /* The done list entry opcode field is defined below. * The mnemonic encoding and meaning is as follows: * TC - Task Complete, status was received and acknowledged * TF - Task Failed, indicates an error prior to receiving acknowledgment * for the command: * - no conn, * - NACK or R_ERR received in response to this command, * - credit blocked or not available, or in the case of SMP request, * - no SMP response was received. * In these four cases it is known that the target didn't receive the * command. * TI - Task Interrupted, error after the command was acknowledged. It is * known that the command was received by the target. * TU - Task Unacked, command was transmitted but neither ACK (R_OK) nor NAK * (R_ERR) was received due to loss of signal, broken connection, loss of * dword sync or other reason. The application client should send the * appropriate task query. * TA - Task Aborted, see TF. * _RESP - The completion includes an empty buffer containing status. * TO - Timeout. */ #define TC_NO_ERROR 0x00 #define TC_UNDERRUN 0x01 #define TC_OVERRUN 0x02 #define TF_OPEN_TO 0x03 #define TF_OPEN_REJECT 0x04 #define TI_BREAK 0x05 #define TI_PROTO_ERR 0x06 #define TC_SSP_RESP 0x07 #define TI_PHY_DOWN 0x08 #define TF_PHY_DOWN 0x09 #define TC_LINK_ADM_RESP 0x0a #define TC_CSMI 0x0b #define TC_ATA_RESP 0x0c #define TU_PHY_DOWN 0x0d #define TU_BREAK 0x0e #define TI_SATA_TO 0x0f #define TI_NAK 0x10 #define TC_CONTROL_PHY 0x11 #define TF_BREAK 0x12 #define TC_RESUME 0x13 #define TI_ACK_NAK_TO 0x14 #define TF_SMPRSP_TO 0x15 #define TF_SMP_XMIT_RCV_ERR 0x16 #define TC_PARTIAL_SG_LIST 0x17 #define TU_ACK_NAK_TO 0x18 #define TU_SATA_TO 0x19 #define TF_NAK_RECV 0x1a #define TA_I_T_NEXUS_LOSS 0x1b #define TC_ATA_R_ERR_RECV 0x1c #define TF_TMF_NO_CTX 0x1d #define TA_ON_REQ 0x1e #define TF_TMF_NO_TAG 0x1f #define TF_TMF_TAG_FREE 0x20 #define TF_TMF_TASK_DONE 0x21 #define TF_TMF_NO_CONN_HANDLE 0x22 #define TC_TASK_CLEARED 0x23 #define TI_SYNCS_RECV 0x24 #define TU_SYNCS_RECV 0x25 #define TF_IRTT_TO 0x26 #define TF_NO_SMP_CONN 0x27 #define TF_IU_SHORT 0x28 #define TF_DATA_OFFS_ERR 0x29 #define TF_INV_CONN_HANDLE 0x2a #define TF_REQUESTED_N_PENDING 0x2b /* 0xc1 - 0xc7: empty buffer received, 0xd1 - 0xd7: establish nexus empty buffer received */ /* This is the ESCB mask */ #define ESCB_RECVD 0xC0 /* This struct done_list_struct defines the done list entry. * All fields are LE. */ struct done_list_struct { __le16 index; /* aka transaction context */ u8 opcode; u8 status_block[4]; u8 toggle; /* bit 0 */ #define DL_TOGGLE_MASK 0x01 } __attribute__ ((packed)); /* ---------- PHYS ---------- */ struct asd_phy { struct asd_sas_phy sas_phy; struct asd_phy_desc *phy_desc; /* hw profile */ struct sas_identify_frame *identify_frame; struct asd_dma_tok *id_frm_tok; struct asd_port *asd_port; u8 frame_rcvd[ASD_EDB_SIZE]; }; #define ASD_SCB_SIZE sizeof(struct scb) #define ASD_DDB_SIZE sizeof(struct asd_ddb_ssp_smp_target_port) /* Define this to 0 if you do not want NOTIFY (ENABLE SPINIP) sent. * Default: 0x10 (it's a mask) */ #define ASD_NOTIFY_ENABLE_SPINUP 0x10 /* If enabled, set this to the interval between transmission * of NOTIFY (ENABLE SPINUP). In units of 200 us. */ #define ASD_NOTIFY_TIMEOUT 2500 /* Initial delay after OOB, before we transmit NOTIFY (ENABLE SPINUP). * If 0, transmit immediately. In milliseconds. */ #define ASD_NOTIFY_DOWN_COUNT 0 /* Device present timer timeout constant, 10 ms. */ #define ASD_DEV_PRESENT_TIMEOUT 0x2710 #define ASD_SATA_INTERLOCK_TIMEOUT 0 /* How long to wait before shutting down an STP connection, unless * an STP target sent frame(s). 50 usec. * IGNORED by the sequencer (i.e. value 0 always). */ #define ASD_STP_SHUTDOWN_TIMEOUT 0x0 /* ATA soft reset timer timeout. 5 usec. */ #define ASD_SRST_ASSERT_TIMEOUT 0x05 /* 31 sec */ #define ASD_RCV_FIS_TIMEOUT 0x01D905C0 #define ASD_ONE_MILLISEC_TIMEOUT 0x03e8 /* COMINIT timer */ #define ASD_TEN_MILLISEC_TIMEOUT 0x2710 #define ASD_COMINIT_TIMEOUT ASD_TEN_MILLISEC_TIMEOUT /* 1 sec */ #define ASD_SMP_RCV_TIMEOUT 0x000F4240 #endif
{ "language": "C" }
/* * Copyright 2008 Extreme Engineering Solutions, Inc. * Copyright 2008 Freescale Semiconductor, Inc. * * (C) Copyright 2000 * Wolfgang Denk, DENX Software Engineering, wd@denx.de. * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <common.h> #include <asm/fsl_law.h> #include <asm/mmu.h> /* * Notes: * CCSRBAR and L2-as-SRAM don't need a configured Local Access Window. * If flash is 8M at default position (last 8M), no LAW needed. */ struct law_entry law_table[] = { /* LBC window - maps 256M 0xf0000000 -> 0xffffffff */ SET_LAW(CONFIG_SYS_FLASH_BASE2, LAW_SIZE_256M, LAW_TRGT_IF_LBC), SET_LAW(CONFIG_SYS_NAND_BASE, LAW_SIZE_1M, LAW_TRGT_IF_LBC), #if CONFIG_SYS_PCI1_MEM_PHYS SET_LAW(CONFIG_SYS_PCI1_MEM_PHYS, LAW_SIZE_1G, LAW_TRGT_IF_PCI_1), SET_LAW(CONFIG_SYS_PCI1_IO_PHYS, LAW_SIZE_8M, LAW_TRGT_IF_PCI_1), #endif #if CONFIG_SYS_PCI2_MEM_PHYS SET_LAW(CONFIG_SYS_PCI2_MEM_PHYS, LAW_SIZE_256M, LAW_TRGT_IF_PCI_2), SET_LAW(CONFIG_SYS_PCI2_IO_PHYS, LAW_SIZE_8M, LAW_TRGT_IF_PCI_2), #endif }; int num_law_entries = ARRAY_SIZE(law_table);
{ "language": "C" }
/*++ Copyright (c) 1989 Microsoft Corporation Module Name: debug.c Abstract: This module implements the debugging function for the MUP. Author: Manny Weiser (mannyw) 27-Dec-1991 Revision History: --*/ #include "mup.h" #include "stdio.h" #ifdef MUPDBG #ifdef ALLOC_PRAGMA #pragma alloc_text( PAGE, _DebugTrace ) #endif VOID _DebugTrace( LONG Indent, ULONG Level, PSZ X, ULONG Y ) /*++ Routine Description: This routine display debugging information. Arguments: Level - The debug level required to display this message. If level is 0 the message is displayed regardless of the setting or the debug level Indent - Incremement or the current debug message indent X - 1st print parameter Y - 2nd print parameter Return Value: None. --*/ { LONG i; char printMask[100]; PAGED_CODE(); if ((Level == 0) || (MupDebugTraceLevel & Level)) { if (Indent < 0) { MupDebugTraceIndent += Indent; } if (MupDebugTraceIndent < 0) { MupDebugTraceIndent = 0; } sprintf( printMask, "%%08lx:%%.*s%s", X ); i = (LONG)PsGetCurrentThread(); DbgPrint( printMask, i, MupDebugTraceIndent, "", Y ); if (Indent > 0) { MupDebugTraceIndent += Indent; } } } #endif // MUPDBG
{ "language": "C" }
#ifndef BB_MONKEY_C_H #define BB_MONKEY_C_H #ifdef __cplusplus extern "C"{ #endif extern void bb_printf( const char *fmt,...); #ifdef __cplusplus } #endif #endif
{ "language": "C" }
#ifndef T_SHA_H #define T_SHA_H #if !defined(P) #ifdef __STDC__ #define P(x) x #else #define P(x) () #endif #endif #define SHA_DIGESTSIZE 20 typedef unsigned int uint32; typedef struct { uint32 state[5]; uint32 count[2]; unsigned char buffer[64]; } SHA1_CTX; void SHA1Init P((SHA1_CTX* context)); void SHA1Update P((SHA1_CTX* context, const unsigned char* data, unsigned int len)); void SHA1Final P((unsigned char digest[20], SHA1_CTX* context)); #endif /* T_SHA_H */
{ "language": "C" }
// SPDX-License-Identifier: GPL-2.0-only /* * AMD Cryptographic Coprocessor (CCP) driver * * Copyright (C) 2017 Advanced Micro Devices, Inc. * * Author: Gary R Hook <gary.hook@amd.com> */ #include <linux/debugfs.h> #include <linux/ccp.h> #include "ccp-dev.h" /* DebugFS helpers */ #define OBUFP (obuf + oboff) #define OBUFLEN 512 #define OBUFSPC (OBUFLEN - oboff) #define OSCNPRINTF(fmt, ...) \ scnprintf(OBUFP, OBUFSPC, fmt, ## __VA_ARGS__) #define BUFLEN 63 #define RI_VERSION_NUM 0x0000003F #define RI_AES_PRESENT 0x00000040 #define RI_3DES_PRESENT 0x00000080 #define RI_SHA_PRESENT 0x00000100 #define RI_RSA_PRESENT 0x00000200 #define RI_ECC_PRESENT 0x00000400 #define RI_ZDE_PRESENT 0x00000800 #define RI_ZCE_PRESENT 0x00001000 #define RI_TRNG_PRESENT 0x00002000 #define RI_ELFC_PRESENT 0x00004000 #define RI_ELFC_SHIFT 14 #define RI_NUM_VQM 0x00078000 #define RI_NVQM_SHIFT 15 #define RI_NVQM(r) (((r) * RI_NUM_VQM) >> RI_NVQM_SHIFT) #define RI_LSB_ENTRIES 0x0FF80000 #define RI_NLSB_SHIFT 19 #define RI_NLSB(r) (((r) * RI_LSB_ENTRIES) >> RI_NLSB_SHIFT) static ssize_t ccp5_debugfs_info_read(struct file *filp, char __user *ubuf, size_t count, loff_t *offp) { struct ccp_device *ccp = filp->private_data; unsigned int oboff = 0; unsigned int regval; ssize_t ret; char *obuf; if (!ccp) return 0; obuf = kmalloc(OBUFLEN, GFP_KERNEL); if (!obuf) return -ENOMEM; oboff += OSCNPRINTF("Device name: %s\n", ccp->name); oboff += OSCNPRINTF(" RNG name: %s\n", ccp->rngname); oboff += OSCNPRINTF(" # Queues: %d\n", ccp->cmd_q_count); oboff += OSCNPRINTF(" # Cmds: %d\n", ccp->cmd_count); regval = ioread32(ccp->io_regs + CMD5_PSP_CCP_VERSION); oboff += OSCNPRINTF(" Version: %d\n", regval & RI_VERSION_NUM); oboff += OSCNPRINTF(" Engines:"); if (regval & RI_AES_PRESENT) oboff += OSCNPRINTF(" AES"); if (regval & RI_3DES_PRESENT) oboff += OSCNPRINTF(" 3DES"); if (regval & RI_SHA_PRESENT) oboff += OSCNPRINTF(" SHA"); if (regval & RI_RSA_PRESENT) oboff += OSCNPRINTF(" RSA"); if (regval & RI_ECC_PRESENT) oboff += OSCNPRINTF(" ECC"); if (regval & RI_ZDE_PRESENT) oboff += OSCNPRINTF(" ZDE"); if (regval & RI_ZCE_PRESENT) oboff += OSCNPRINTF(" ZCE"); if (regval & RI_TRNG_PRESENT) oboff += OSCNPRINTF(" TRNG"); oboff += OSCNPRINTF("\n"); oboff += OSCNPRINTF(" Queues: %d\n", (regval & RI_NUM_VQM) >> RI_NVQM_SHIFT); oboff += OSCNPRINTF("LSB Entries: %d\n", (regval & RI_LSB_ENTRIES) >> RI_NLSB_SHIFT); ret = simple_read_from_buffer(ubuf, count, offp, obuf, oboff); kfree(obuf); return ret; } /* Return a formatted buffer containing the current * statistics across all queues for a CCP. */ static ssize_t ccp5_debugfs_stats_read(struct file *filp, char __user *ubuf, size_t count, loff_t *offp) { struct ccp_device *ccp = filp->private_data; unsigned long total_xts_aes_ops = 0; unsigned long total_3des_ops = 0; unsigned long total_aes_ops = 0; unsigned long total_sha_ops = 0; unsigned long total_rsa_ops = 0; unsigned long total_ecc_ops = 0; unsigned long total_pt_ops = 0; unsigned long total_ops = 0; unsigned int oboff = 0; ssize_t ret = 0; unsigned int i; char *obuf; for (i = 0; i < ccp->cmd_q_count; i++) { struct ccp_cmd_queue *cmd_q = &ccp->cmd_q[i]; total_ops += cmd_q->total_ops; total_aes_ops += cmd_q->total_aes_ops; total_xts_aes_ops += cmd_q->total_xts_aes_ops; total_3des_ops += cmd_q->total_3des_ops; total_sha_ops += cmd_q->total_sha_ops; total_rsa_ops += cmd_q->total_rsa_ops; total_pt_ops += cmd_q->total_pt_ops; total_ecc_ops += cmd_q->total_ecc_ops; } obuf = kmalloc(OBUFLEN, GFP_KERNEL); if (!obuf) return -ENOMEM; oboff += OSCNPRINTF("Total Interrupts Handled: %ld\n", ccp->total_interrupts); oboff += OSCNPRINTF(" Total Operations: %ld\n", total_ops); oboff += OSCNPRINTF(" AES: %ld\n", total_aes_ops); oboff += OSCNPRINTF(" XTS AES: %ld\n", total_xts_aes_ops); oboff += OSCNPRINTF(" SHA: %ld\n", total_3des_ops); oboff += OSCNPRINTF(" SHA: %ld\n", total_sha_ops); oboff += OSCNPRINTF(" RSA: %ld\n", total_rsa_ops); oboff += OSCNPRINTF(" Pass-Thru: %ld\n", total_pt_ops); oboff += OSCNPRINTF(" ECC: %ld\n", total_ecc_ops); ret = simple_read_from_buffer(ubuf, count, offp, obuf, oboff); kfree(obuf); return ret; } /* Reset the counters in a queue */ static void ccp5_debugfs_reset_queue_stats(struct ccp_cmd_queue *cmd_q) { cmd_q->total_ops = 0L; cmd_q->total_aes_ops = 0L; cmd_q->total_xts_aes_ops = 0L; cmd_q->total_3des_ops = 0L; cmd_q->total_sha_ops = 0L; cmd_q->total_rsa_ops = 0L; cmd_q->total_pt_ops = 0L; cmd_q->total_ecc_ops = 0L; } /* A value was written to the stats variable, which * should be used to reset the queue counters across * that device. */ static ssize_t ccp5_debugfs_stats_write(struct file *filp, const char __user *ubuf, size_t count, loff_t *offp) { struct ccp_device *ccp = filp->private_data; int i; for (i = 0; i < ccp->cmd_q_count; i++) ccp5_debugfs_reset_queue_stats(&ccp->cmd_q[i]); ccp->total_interrupts = 0L; return count; } /* Return a formatted buffer containing the current information * for that queue */ static ssize_t ccp5_debugfs_queue_read(struct file *filp, char __user *ubuf, size_t count, loff_t *offp) { struct ccp_cmd_queue *cmd_q = filp->private_data; unsigned int oboff = 0; unsigned int regval; ssize_t ret; char *obuf; if (!cmd_q) return 0; obuf = kmalloc(OBUFLEN, GFP_KERNEL); if (!obuf) return -ENOMEM; oboff += OSCNPRINTF(" Total Queue Operations: %ld\n", cmd_q->total_ops); oboff += OSCNPRINTF(" AES: %ld\n", cmd_q->total_aes_ops); oboff += OSCNPRINTF(" XTS AES: %ld\n", cmd_q->total_xts_aes_ops); oboff += OSCNPRINTF(" SHA: %ld\n", cmd_q->total_3des_ops); oboff += OSCNPRINTF(" SHA: %ld\n", cmd_q->total_sha_ops); oboff += OSCNPRINTF(" RSA: %ld\n", cmd_q->total_rsa_ops); oboff += OSCNPRINTF(" Pass-Thru: %ld\n", cmd_q->total_pt_ops); oboff += OSCNPRINTF(" ECC: %ld\n", cmd_q->total_ecc_ops); regval = ioread32(cmd_q->reg_int_enable); oboff += OSCNPRINTF(" Enabled Interrupts:"); if (regval & INT_EMPTY_QUEUE) oboff += OSCNPRINTF(" EMPTY"); if (regval & INT_QUEUE_STOPPED) oboff += OSCNPRINTF(" STOPPED"); if (regval & INT_ERROR) oboff += OSCNPRINTF(" ERROR"); if (regval & INT_COMPLETION) oboff += OSCNPRINTF(" COMPLETION"); oboff += OSCNPRINTF("\n"); ret = simple_read_from_buffer(ubuf, count, offp, obuf, oboff); kfree(obuf); return ret; } /* A value was written to the stats variable for a * queue. Reset the queue counters to this value. */ static ssize_t ccp5_debugfs_queue_write(struct file *filp, const char __user *ubuf, size_t count, loff_t *offp) { struct ccp_cmd_queue *cmd_q = filp->private_data; ccp5_debugfs_reset_queue_stats(cmd_q); return count; } static const struct file_operations ccp_debugfs_info_ops = { .owner = THIS_MODULE, .open = simple_open, .read = ccp5_debugfs_info_read, .write = NULL, }; static const struct file_operations ccp_debugfs_queue_ops = { .owner = THIS_MODULE, .open = simple_open, .read = ccp5_debugfs_queue_read, .write = ccp5_debugfs_queue_write, }; static const struct file_operations ccp_debugfs_stats_ops = { .owner = THIS_MODULE, .open = simple_open, .read = ccp5_debugfs_stats_read, .write = ccp5_debugfs_stats_write, }; static struct dentry *ccp_debugfs_dir; static DEFINE_MUTEX(ccp_debugfs_lock); #define MAX_NAME_LEN 20 void ccp5_debugfs_setup(struct ccp_device *ccp) { struct ccp_cmd_queue *cmd_q; char name[MAX_NAME_LEN + 1]; struct dentry *debugfs_q_instance; int i; if (!debugfs_initialized()) return; mutex_lock(&ccp_debugfs_lock); if (!ccp_debugfs_dir) ccp_debugfs_dir = debugfs_create_dir(KBUILD_MODNAME, NULL); mutex_unlock(&ccp_debugfs_lock); ccp->debugfs_instance = debugfs_create_dir(ccp->name, ccp_debugfs_dir); debugfs_create_file("info", 0400, ccp->debugfs_instance, ccp, &ccp_debugfs_info_ops); debugfs_create_file("stats", 0600, ccp->debugfs_instance, ccp, &ccp_debugfs_stats_ops); for (i = 0; i < ccp->cmd_q_count; i++) { cmd_q = &ccp->cmd_q[i]; snprintf(name, MAX_NAME_LEN - 1, "q%d", cmd_q->id); debugfs_q_instance = debugfs_create_dir(name, ccp->debugfs_instance); debugfs_create_file("stats", 0600, debugfs_q_instance, cmd_q, &ccp_debugfs_queue_ops); } return; } void ccp5_debugfs_destroy(void) { debugfs_remove_recursive(ccp_debugfs_dir); }
{ "language": "C" }
/* * ELF object format helpers * * Copyright (C) 2003-2007 Michael Urman * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND OTHER CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR OTHER CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <util.h> #include <libyasm.h> #define YASM_OBJFMT_ELF_INTERNAL #include "elf.h" #include "elf-machine.h" static void elf_section_data_destroy(void *data); static void elf_secthead_print(void *data, FILE *f, int indent_level); const yasm_assoc_data_callback elf_section_data = { elf_section_data_destroy, elf_secthead_print }; static void elf_symrec_data_destroy(/*@only@*/ void *d); static void elf_symtab_entry_print(void *data, FILE *f, int indent_level); static void elf_ssym_symtab_entry_print(void *data, FILE *f, int indent_level); const yasm_assoc_data_callback elf_symrec_data = { elf_symrec_data_destroy, elf_symtab_entry_print }; const yasm_assoc_data_callback elf_ssym_symrec_data = { elf_symrec_data_destroy, elf_ssym_symtab_entry_print }; extern elf_machine_handler elf_machine_handler_x86_x86, elf_machine_handler_x86_amd64, elf_machine_handler_x86_x32; static const elf_machine_handler *elf_machine_handlers[] = { &elf_machine_handler_x86_x86, &elf_machine_handler_x86_amd64, &elf_machine_handler_x86_x32, NULL }; static const elf_machine_handler elf_null_machine = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; static elf_machine_handler const *elf_march = &elf_null_machine; static yasm_symrec **elf_ssyms; const elf_machine_handler * elf_set_arch(yasm_arch *arch, yasm_symtab *symtab, int bits_pref) { const char *machine = yasm_arch_get_machine(arch); int i; for (i=0, elf_march = elf_machine_handlers[0]; elf_march != NULL; elf_march = elf_machine_handlers[++i]) { if (yasm__strcasecmp(yasm_arch_keyword(arch), elf_march->arch)==0) { if (yasm__strcasecmp(machine, elf_march->machine)==0) { if (bits_pref == 0 || bits_pref == elf_march->bits) break; } else if (bits_pref == elf_march->bits && yasm__strcasecmp(machine, "amd64") == 0 && yasm__strcasecmp(elf_march->machine, "x32") == 0) break; } } if (elf_march && elf_march->num_ssyms > 0) { /* Allocate "special" syms */ elf_ssyms = yasm_xmalloc(elf_march->num_ssyms * sizeof(yasm_symrec *)); for (i=0; (unsigned int)i<elf_march->num_ssyms; i++) { /* FIXME: misuse of NULL bytecode */ elf_ssyms[i] = yasm_symtab_define_label(symtab, elf_march->ssyms[i].name, NULL, 0, 0); yasm_symrec_add_data(elf_ssyms[i], &elf_ssym_symrec_data, (void*)&elf_march->ssyms[i]); } } return elf_march; } yasm_symrec * elf_get_special_sym(const char *name, const char *parser) { int i; for (i=0; (unsigned int)i<elf_march->num_ssyms; i++) { if (yasm__strcasecmp(name, elf_march->ssyms[i].name) == 0) return elf_ssyms[i]; } return NULL; } /* reloc functions */ int elf_ssym_has_flag(yasm_symrec *wrt, int flag); int elf_is_wrt_sym_relative(yasm_symrec *wrt) { return elf_ssym_has_flag(wrt, ELF_SSYM_SYM_RELATIVE); } int elf_is_wrt_pos_adjusted(yasm_symrec *wrt) { return elf_ssym_has_flag(wrt, ELF_SSYM_CURPOS_ADJUST); } int elf_ssym_has_flag(yasm_symrec *wrt, int flag) { int i; for (i=0; (unsigned int)i<elf_march->num_ssyms; i++) { if (elf_ssyms[i] == wrt) return (elf_march->ssyms[i].sym_rel & flag) != 0; } return 0; } /* takes ownership of addr */ elf_reloc_entry * elf_reloc_entry_create(yasm_symrec *sym, yasm_symrec *wrt, yasm_intnum *addr, int rel, size_t valsize, int is_GOT_sym) { elf_reloc_entry *entry; if (!elf_march->accepts_reloc) yasm_internal_error(N_("Unsupported machine for ELF output")); if (!elf_march->accepts_reloc(valsize, wrt)) { if (addr) yasm_intnum_destroy(addr); return NULL; } if (sym == NULL) yasm_internal_error("sym is null"); entry = yasm_xmalloc(sizeof(elf_reloc_entry)); entry->reloc.sym = sym; entry->reloc.addr = addr; entry->rtype_rel = rel; entry->valsize = valsize; entry->addend = NULL; entry->wrt = wrt; entry->is_GOT_sym = is_GOT_sym; return entry; } void elf_reloc_entry_destroy(void *entry) { if (((elf_reloc_entry*)entry)->addend) yasm_intnum_destroy(((elf_reloc_entry*)entry)->addend); yasm_xfree(entry); } /* strtab functions */ elf_strtab_entry * elf_strtab_entry_create(const char *str) { elf_strtab_entry *entry = yasm_xmalloc(sizeof(elf_strtab_entry)); entry->str = yasm__xstrdup(str); entry->index = 0; return entry; } void elf_strtab_entry_set_str(elf_strtab_entry *entry, const char *str) { elf_strtab_entry *last; if (entry->str) yasm_xfree(entry->str); entry->str = yasm__xstrdup(str); /* Update all following indices since string length probably changes */ last = entry; entry = STAILQ_NEXT(last, qlink); while (entry) { entry->index = last->index + (unsigned long)strlen(last->str) + 1; last = entry; entry = STAILQ_NEXT(last, qlink); } } elf_strtab_head * elf_strtab_create() { elf_strtab_head *strtab = yasm_xmalloc(sizeof(elf_strtab_head)); elf_strtab_entry *entry = yasm_xmalloc(sizeof(elf_strtab_entry)); STAILQ_INIT(strtab); entry->index = 0; entry->str = yasm__xstrdup(""); STAILQ_INSERT_TAIL(strtab, entry, qlink); return strtab; } elf_strtab_entry * elf_strtab_append_str(elf_strtab_head *strtab, const char *str) { elf_strtab_entry *last, *entry; if (strtab == NULL) yasm_internal_error("strtab is null"); if (STAILQ_EMPTY(strtab)) yasm_internal_error("strtab is missing initial dummy entry"); last = STAILQ_LAST(strtab, elf_strtab_entry, qlink); entry = elf_strtab_entry_create(str); entry->index = last->index + (unsigned long)strlen(last->str) + 1; STAILQ_INSERT_TAIL(strtab, entry, qlink); return entry; } void elf_strtab_destroy(elf_strtab_head *strtab) { elf_strtab_entry *s1, *s2; if (strtab == NULL) yasm_internal_error("strtab is null"); if (STAILQ_EMPTY(strtab)) yasm_internal_error("strtab is missing initial dummy entry"); s1 = STAILQ_FIRST(strtab); while (s1 != NULL) { s2 = STAILQ_NEXT(s1, qlink); yasm_xfree(s1->str); yasm_xfree(s1); s1 = s2; } yasm_xfree(strtab); } unsigned long elf_strtab_output_to_file(FILE *f, elf_strtab_head *strtab) { unsigned long size = 0; elf_strtab_entry *entry; if (strtab == NULL) yasm_internal_error("strtab is null"); /* consider optimizing tables here */ STAILQ_FOREACH(entry, strtab, qlink) { size_t len = 1 + strlen(entry->str); fwrite(entry->str, len, 1, f); size += (unsigned long)len; } return size; } /* symtab functions */ elf_symtab_entry * elf_symtab_entry_create(elf_strtab_entry *name, yasm_symrec *sym) { elf_symtab_entry *entry = yasm_xmalloc(sizeof(elf_symtab_entry)); entry->in_table = 0; entry->sym = sym; entry->sect = NULL; entry->name = name; entry->value = 0; entry->xsize = NULL; entry->size = 0; entry->index = 0; entry->bind = 0; entry->type = STT_NOTYPE; entry->vis = STV_DEFAULT; return entry; } static void elf_symtab_entry_destroy(elf_symtab_entry *entry) { if (entry == NULL) yasm_internal_error("symtab entry is null"); yasm_xfree(entry); } static void elf_symrec_data_destroy(void *data) { /* do nothing, as this stuff is in the symtab anyway... this speaks of bad * design/use or this stuff, i fear */ /* watch for double-free here ... */ /*elf_symtab_entry_destroy((elf_symtab_entry *)data);*/ } static void elf_symtab_entry_print(void *data, FILE *f, int indent_level) { elf_symtab_entry *entry = data; if (entry == NULL) yasm_internal_error("symtab entry is null"); fprintf(f, "%*sbind=", indent_level, ""); switch (entry->bind) { case STB_LOCAL: fprintf(f, "local\n"); break; case STB_GLOBAL: fprintf(f, "global\n"); break; case STB_WEAK: fprintf(f, "weak\n"); break; default: fprintf(f, "undef\n"); break; } fprintf(f, "%*stype=", indent_level, ""); switch (entry->type) { case STT_NOTYPE: fprintf(f, "notype\n"); break; case STT_OBJECT: fprintf(f, "object\n"); break; case STT_FUNC: fprintf(f, "func\n"); break; case STT_SECTION: fprintf(f, "section\n");break; case STT_FILE: fprintf(f, "file\n"); break; default: fprintf(f, "undef\n"); break; } fprintf(f, "%*ssize=", indent_level, ""); if (entry->xsize) yasm_expr_print(entry->xsize, f); else fprintf(f, "%ld", entry->size); fprintf(f, "\n"); } static void elf_ssym_symtab_entry_print(void *data, FILE *f, int indent_level) { /* TODO */ } elf_symtab_head * elf_symtab_create() { elf_symtab_head *symtab = yasm_xmalloc(sizeof(elf_symtab_head)); elf_symtab_entry *entry = yasm_xmalloc(sizeof(elf_symtab_entry)); STAILQ_INIT(symtab); entry->in_table = 1; entry->sym = NULL; entry->sect = NULL; entry->name = NULL; entry->value = 0; entry->xsize = NULL; entry->size = 0; entry->index = SHN_UNDEF; entry->bind = STB_LOCAL; entry->type = STT_NOTYPE; entry->vis = STV_DEFAULT; entry->symindex = 0; STAILQ_INSERT_TAIL(symtab, entry, qlink); return symtab; } void elf_symtab_append_entry(elf_symtab_head *symtab, elf_symtab_entry *entry) { if (symtab == NULL) yasm_internal_error("symtab is null"); if (entry == NULL) yasm_internal_error("symtab entry is null"); if (STAILQ_EMPTY(symtab)) yasm_internal_error(N_("symtab is missing initial dummy entry")); STAILQ_INSERT_TAIL(symtab, entry, qlink); entry->in_table = 1; } void elf_symtab_insert_local_sym(elf_symtab_head *symtab, elf_symtab_entry *entry) { elf_symtab_entry *after = STAILQ_FIRST(symtab); elf_symtab_entry *before = NULL; while (after && (after->bind == STB_LOCAL)) { before = after; if (before->type == STT_FILE) break; after = STAILQ_NEXT(after, qlink); } STAILQ_INSERT_AFTER(symtab, before, entry, qlink); entry->in_table = 1; } void elf_symtab_destroy(elf_symtab_head *symtab) { elf_symtab_entry *s1, *s2; if (symtab == NULL) yasm_internal_error("symtab is null"); if (STAILQ_EMPTY(symtab)) yasm_internal_error(N_("symtab is missing initial dummy entry")); s1 = STAILQ_FIRST(symtab); while (s1 != NULL) { s2 = STAILQ_NEXT(s1, qlink); elf_symtab_entry_destroy(s1); s1 = s2; } yasm_xfree(symtab); } unsigned long elf_symtab_assign_indices(elf_symtab_head *symtab) { elf_symtab_entry *entry, *prev=NULL; unsigned long last_local=0; if (symtab == NULL) yasm_internal_error("symtab is null"); if (STAILQ_EMPTY(symtab)) yasm_internal_error(N_("symtab is missing initial dummy entry")); STAILQ_FOREACH(entry, symtab, qlink) { if (prev) entry->symindex = prev->symindex + 1; if (entry->bind == STB_LOCAL) last_local = entry->symindex; prev = entry; } return last_local + 1; } unsigned long elf_symtab_write_to_file(FILE *f, elf_symtab_head *symtab, yasm_errwarns *errwarns) { unsigned char buf[SYMTAB_MAXSIZE], *bufp; elf_symtab_entry *entry; unsigned long size = 0; if (!symtab) yasm_internal_error(N_("symtab is null")); STAILQ_FOREACH(entry, symtab, qlink) { yasm_intnum *size_intn=NULL, *value_intn=NULL; bufp = buf; /* get size (if specified); expr overrides stored integer */ if (entry->xsize) { size_intn = yasm_intnum_copy( yasm_expr_get_intnum(&entry->xsize, 1)); if (!size_intn) { yasm_error_set(YASM_ERROR_VALUE, N_("size specifier not an integer expression")); yasm_errwarn_propagate(errwarns, entry->xsize->line); } } else size_intn = yasm_intnum_create_uint(entry->size); /* get EQU value for constants */ if (entry->sym) { const yasm_expr *equ_expr_c; equ_expr_c = yasm_symrec_get_equ(entry->sym); if (equ_expr_c != NULL) { const yasm_intnum *equ_intn; yasm_expr *equ_expr = yasm_expr_copy(equ_expr_c); equ_intn = yasm_expr_get_intnum(&equ_expr, 1); if (equ_intn == NULL) { yasm_error_set(YASM_ERROR_VALUE, N_("EQU value not an integer expression")); yasm_errwarn_propagate(errwarns, equ_expr->line); } else value_intn = yasm_intnum_copy(equ_intn); entry->index = SHN_ABS; yasm_expr_destroy(equ_expr); } } if (value_intn == NULL) value_intn = yasm_intnum_create_uint(entry->value); /* If symbol is in a TLS section, force its type to TLS. */ if (entry->sym) { yasm_bytecode *precbc; yasm_section *sect; elf_secthead *shead; if (yasm_symrec_get_label(entry->sym, &precbc) && (sect = yasm_bc_get_section(precbc)) && (shead = yasm_section_get_data(sect, &elf_section_data)) && shead->flags & SHF_TLS) { entry->type = STT_TLS; } } if (!elf_march->write_symtab_entry || !elf_march->symtab_entry_size) yasm_internal_error(N_("Unsupported machine for ELF output")); elf_march->write_symtab_entry(bufp, entry, value_intn, size_intn); fwrite(buf, elf_march->symtab_entry_size, 1, f); size += elf_march->symtab_entry_size; yasm_intnum_destroy(size_intn); yasm_intnum_destroy(value_intn); } return size; } void elf_symtab_set_nonzero(elf_symtab_entry *entry, yasm_section *sect, elf_section_index sectidx, elf_symbol_binding bind, elf_symbol_type type, yasm_expr *xsize, elf_address *value) { if (!entry) yasm_internal_error("NULL entry"); if (sect) entry->sect = sect; if (sectidx) entry->index = sectidx; if (bind) entry->bind = bind; if (type) entry->type = type; if (xsize) entry->xsize = xsize; if (value) entry->value = *value; } void elf_sym_set_visibility(elf_symtab_entry *entry, elf_symbol_vis vis) { entry->vis = ELF_ST_VISIBILITY(vis); } void elf_sym_set_type(elf_symtab_entry *entry, elf_symbol_type type) { entry->type = type; } void elf_sym_set_size(elf_symtab_entry *entry, struct yasm_expr *size) { if (entry->xsize) yasm_expr_destroy(entry->xsize); entry->xsize = size; } int elf_sym_in_table(elf_symtab_entry *entry) { return entry->in_table; } elf_secthead * elf_secthead_create(elf_strtab_entry *name, elf_section_type type, elf_section_flags flags, elf_address offset, elf_size size) { elf_secthead *esd = yasm_xmalloc(sizeof(elf_secthead)); esd->type = type; esd->flags = flags; esd->offset = offset; esd->size = yasm_intnum_create_uint(size); esd->link = 0; esd->info = 0; esd->align = 0; esd->entsize = 0; esd->index = 0; esd->sym = NULL; esd->name = name; esd->index = 0; esd->rel_name = NULL; esd->rel_index = 0; esd->rel_offset = 0; esd->nreloc = 0; if (name && (strcmp(name->str, ".symtab") == 0)) { if (!elf_march->symtab_entry_size || !elf_march->symtab_entry_align) yasm_internal_error(N_("unsupported ELF format")); esd->entsize = elf_march->symtab_entry_size; esd->align = elf_march->symtab_entry_align; } return esd; } void elf_secthead_destroy(elf_secthead *shead) { if (shead == NULL) yasm_internal_error(N_("shead is null")); yasm_intnum_destroy(shead->size); yasm_xfree(shead); } static void elf_section_data_destroy(void *data) { elf_secthead_destroy((elf_secthead *)data); } static void elf_secthead_print(void *data, FILE *f, int indent_level) { elf_secthead *sect = data; fprintf(f, "%*sname=%s\n", indent_level, "", sect->name ? sect->name->str : "<undef>"); fprintf(f, "%*ssym=\n", indent_level, ""); yasm_symrec_print(sect->sym, f, indent_level+1); fprintf(f, "%*sindex=0x%x\n", indent_level, "", sect->index); fprintf(f, "%*sflags=", indent_level, ""); if (sect->flags & SHF_WRITE) fprintf(f, "WRITE "); if (sect->flags & SHF_ALLOC) fprintf(f, "ALLOC "); if (sect->flags & SHF_EXECINSTR) fprintf(f, "EXEC "); /*if (sect->flags & SHF_MASKPROC) fprintf(f, "PROC-SPECIFIC"); */ fprintf(f, "%*soffset=0x%lx\n", indent_level, "", sect->offset); fprintf(f, "%*ssize=0x%lx\n", indent_level, "", yasm_intnum_get_uint(sect->size)); fprintf(f, "%*slink=0x%x\n", indent_level, "", sect->link); fprintf(f, "%*salign=%lu\n", indent_level, "", sect->align); fprintf(f, "%*snreloc=%ld\n", indent_level, "", sect->nreloc); } unsigned long elf_secthead_write_to_file(FILE *f, elf_secthead *shead, elf_section_index sindex) { unsigned char buf[SHDR_MAXSIZE], *bufp = buf; shead->index = sindex; if (shead == NULL) yasm_internal_error("shead is null"); if (!elf_march->write_secthead || !elf_march->secthead_size) yasm_internal_error(N_("Unsupported machine for ELF output")); elf_march->write_secthead(bufp, shead); if (fwrite(buf, elf_march->secthead_size, 1, f)) return elf_march->secthead_size; yasm_internal_error(N_("Failed to write an elf section header")); return 0; } void elf_secthead_append_reloc(yasm_section *sect, elf_secthead *shead, elf_reloc_entry *reloc) { if (sect == NULL) yasm_internal_error("sect is null"); if (shead == NULL) yasm_internal_error("shead is null"); if (reloc == NULL) yasm_internal_error("reloc is null"); shead->nreloc++; yasm_section_add_reloc(sect, (yasm_reloc *)reloc, elf_reloc_entry_destroy); } char * elf_secthead_name_reloc_section(const char *basesect) { if (!elf_march->reloc_section_prefix) { yasm_internal_error(N_("Unsupported machine for ELF output")); return NULL; } else { size_t prepend_length = strlen(elf_march->reloc_section_prefix); char *sectname = yasm_xmalloc(prepend_length + strlen(basesect) + 1); strcpy(sectname, elf_march->reloc_section_prefix); strcat(sectname, basesect); return sectname; } } void elf_handle_reloc_addend(yasm_intnum *intn, elf_reloc_entry *reloc, unsigned long offset) { if (!elf_march->handle_reloc_addend) yasm_internal_error(N_("Unsupported machine for ELF output")); elf_march->handle_reloc_addend(intn, reloc, offset); } unsigned long elf_secthead_write_rel_to_file(FILE *f, elf_section_index symtab_idx, yasm_section *sect, elf_secthead *shead, elf_section_index sindex) { unsigned char buf[SHDR_MAXSIZE], *bufp = buf; if (shead == NULL) yasm_internal_error("shead is null"); if (!yasm_section_relocs_first(sect)) return 0; /* no relocations, no .rel.* section header */ shead->rel_index = sindex; if (!elf_march->write_secthead_rel || !elf_march->secthead_size) yasm_internal_error(N_("Unsupported machine for ELF output")); elf_march->write_secthead_rel(bufp, shead, symtab_idx, sindex); if (fwrite(buf, elf_march->secthead_size, 1, f)) return elf_march->secthead_size; yasm_internal_error(N_("Failed to write an elf section header")); return 0; } unsigned long elf_secthead_write_relocs_to_file(FILE *f, yasm_section *sect, elf_secthead *shead, yasm_errwarns *errwarns) { elf_reloc_entry *reloc; unsigned char buf[RELOC_MAXSIZE], *bufp; unsigned long size = 0; long pos; if (shead == NULL) yasm_internal_error("shead is null"); reloc = (elf_reloc_entry *)yasm_section_relocs_first(sect); if (!reloc) return 0; /* first align section to multiple of 4 */ pos = ftell(f); if (pos == -1) { yasm_error_set(YASM_ERROR_IO, N_("couldn't read position on output stream")); yasm_errwarn_propagate(errwarns, 0); } pos = (pos + 3) & ~3; if (fseek(f, pos, SEEK_SET) < 0) { yasm_error_set(YASM_ERROR_IO, N_("couldn't seek on output stream")); yasm_errwarn_propagate(errwarns, 0); } shead->rel_offset = (unsigned long)pos; while (reloc) { unsigned int r_type=0, r_sym; elf_symtab_entry *esym; esym = yasm_symrec_get_data(reloc->reloc.sym, &elf_symrec_data); if (esym) r_sym = esym->symindex; else r_sym = STN_UNDEF; if (!elf_march->map_reloc_info_to_type) yasm_internal_error(N_("Unsupported arch/machine for elf output")); r_type = elf_march->map_reloc_info_to_type(reloc); bufp = buf; if (!elf_march->write_reloc || !elf_march->reloc_entry_size) yasm_internal_error(N_("Unsupported arch/machine for elf output")); elf_march->write_reloc(bufp, reloc, r_type, r_sym); fwrite(buf, elf_march->reloc_entry_size, 1, f); size += elf_march->reloc_entry_size; reloc = (elf_reloc_entry *) yasm_section_reloc_next((yasm_reloc *)reloc); } return size; } elf_section_type elf_secthead_get_type(elf_secthead *shead) { return shead->type; } void elf_secthead_set_typeflags(elf_secthead *shead, elf_section_type type, elf_section_flags flags) { shead->type = type; shead->flags = flags; } int elf_secthead_is_empty(elf_secthead *shead) { return yasm_intnum_is_zero(shead->size); } yasm_symrec * elf_secthead_get_sym(elf_secthead *shead) { return shead->sym; } elf_section_index elf_secthead_get_index(elf_secthead *shead) { return shead->index; } unsigned long elf_secthead_get_align(const elf_secthead *shead) { return shead->align; } unsigned long elf_secthead_set_align(elf_secthead *shead, unsigned long align) { return shead->align = align; } elf_section_info elf_secthead_set_info(elf_secthead *shead, elf_section_info info) { return shead->info = info; } elf_section_index elf_secthead_set_index(elf_secthead *shead, elf_section_index sectidx) { return shead->index = sectidx; } elf_section_index elf_secthead_set_link(elf_secthead *shead, elf_section_index link) { return shead->link = link; } elf_section_index elf_secthead_set_rel_index(elf_secthead *shead, elf_section_index sectidx) { return shead->rel_index = sectidx; } elf_strtab_entry * elf_secthead_set_rel_name(elf_secthead *shead, elf_strtab_entry *entry) { return shead->rel_name = entry; } elf_size elf_secthead_set_entsize(elf_secthead *shead, elf_size size) { return shead->entsize = size; } yasm_symrec * elf_secthead_set_sym(elf_secthead *shead, yasm_symrec *sym) { return shead->sym = sym; } void elf_secthead_add_size(elf_secthead *shead, yasm_intnum *size) { if (size) { yasm_intnum_calc(shead->size, YASM_EXPR_ADD, size); } } long elf_secthead_set_file_offset(elf_secthead *shead, long pos) { unsigned long align = shead->align; if (align == 0 || align == 1) { shead->offset = (unsigned long)pos; return pos; } else if (align & (align - 1)) yasm_internal_error( N_("alignment %d for section `%s' is not a power of 2")); /*, align, sect->name->str);*/ shead->offset = (unsigned long)((pos + align - 1) & ~(align - 1)); return (long)shead->offset; } unsigned long elf_proghead_get_size(void) { if (!elf_march->proghead_size) yasm_internal_error(N_("Unsupported ELF format for output")); return elf_march->proghead_size; } unsigned long elf_proghead_write_to_file(FILE *f, elf_offset secthead_addr, unsigned long secthead_count, elf_section_index shstrtab_index) { unsigned char buf[EHDR_MAXSIZE], *bufp = buf; YASM_WRITE_8(bufp, ELFMAG0); /* ELF magic number */ YASM_WRITE_8(bufp, ELFMAG1); YASM_WRITE_8(bufp, ELFMAG2); YASM_WRITE_8(bufp, ELFMAG3); if (!elf_march->write_proghead || !elf_march->proghead_size) yasm_internal_error(N_("Unsupported ELF format for output")); elf_march->write_proghead(&bufp, secthead_addr, secthead_count, shstrtab_index); if (((unsigned)(bufp - buf)) != elf_march->proghead_size) yasm_internal_error(N_("ELF program header is not proper length")); if (fwrite(buf, elf_march->proghead_size, 1, f)) return elf_march->proghead_size; yasm_internal_error(N_("Failed to write ELF program header")); return 0; }
{ "language": "C" }
/*- * Copyright (c) 1991, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Ronnie Kon at Mindcraft Inc., Kevin Lew and Elmer Yglesias. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * Heapsort -- Knuth, Vol. 3, page 145. Runs in O (N lg N), both average * and worst. While heapsort is faster than the worst case of quicksort, * the BSD quicksort does median selection so that the chance of finding * a data set that will trigger the worst case is nonexistent. Heapsort's * only advantage over quicksort is that it requires little additional memory. */ #include <agar/core/core.h> #include <agar/math/m.h> /* * Swap two areas of size number of bytes. Although qsort(3) permits random * blocks of memory to be sorted, sorting pointers is almost certainly the * common case (and, were it not, could easily be made so). Regardless, it * isn't worth optimizing; the SWAP's get sped up by the cache, and pointer * arithmetic gets lost in the time required for comparison function calls. */ #define SWAP(a, b, count, size, tmp) { \ count = size; \ do { \ tmp = *a; \ *a++ = *b; \ *b++ = tmp; \ } while (--count); \ } /* Copy one block of size size to another. */ #define COPY(a, b, count, size, tmp1, tmp2) { \ count = size; \ tmp1 = a; \ tmp2 = b; \ do { \ *tmp1++ = *tmp2++; \ } while (--count); \ } /* * Build the list into a heap, where a heap is defined such that for * the records K1 ... KN, Kj/2 >= Kj for 1 <= j/2 <= j <= N. * * There are two cases. If j == nmemb, select largest of Ki and Kj. If * j < nmemb, select largest of Ki, Kj and Kj+1. */ #define CREATE(initval, nmemb, par_i, child_i, par, child, size, count, tmp) { \ for (par_i = initval; (child_i = par_i * 2) <= nmemb; \ par_i = child_i) { \ child = base + child_i * size; \ if (child_i < nmemb && compar(child, child + size) < 0) { \ child += size; \ ++child_i; \ } \ par = base + par_i * size; \ if (compar(child, par) <= 0) \ break; \ SWAP(par, child, count, size, tmp); \ } \ } /* * Select the top of the heap and 'heapify'. Since by far the most expensive * action is the call to the compar function, a considerable optimization * in the average case can be achieved due to the fact that k, the displaced * element, is usually quite small, so it would be preferable to first * heapify, always maintaining the invariant that the larger child is copied * over its parent's record. * * Then, starting from the *bottom* of the heap, finding k's correct place, * again maintaining the invariant. As a result of the invariant no element * is 'lost' when k is assigned its correct place in the heap. * * The time savings from this optimization are on the order of 15-20% for the * average case. See Knuth, Vol. 3, page 158, problem 18. * * XXX Don't break the #define SELECT line, below. Reiser cpp gets upset. */ #define SELECT(par_i, child_i, nmemb, par, child, size, k, count, tmp1, tmp2) { \ for (par_i = 1; (child_i = par_i * 2) <= nmemb; par_i = child_i) { \ child = base + child_i * size; \ if (child_i < nmemb && compar(child, child + size) < 0) { \ child += size; \ ++child_i; \ } \ par = base + par_i * size; \ COPY(par, child, count, size, tmp1, tmp2); \ } \ for (;;) { \ child_i = par_i; \ par_i = child_i / 2; \ child = base + child_i * size; \ par = base + par_i * size; \ if (child_i == 1 || compar(k, par) < 0) { \ COPY(child, k, count, size, tmp1, tmp2); \ break; \ } \ COPY(child, par, count, size, tmp1, tmp2); \ } \ } int M_HeapSort(void *vbase, AG_Size nmemb, AG_Size size, int (*compar)(const void *, const void *)) { int cnt, i, j, l; char tmp, *tmp1, *tmp2; char *base, *k, *p, *t; if (nmemb <= 1) return (0); if (!size) { AG_SetError("Size==0"); return (-1); } if ((k = TryMalloc(size)) == NULL) return (-1); /* * Items are numbered from 1 to nmemb, so offset from size bytes * below the starting address. */ base = (char *)vbase - size; for (l = nmemb / 2 + 1; --l;) CREATE(l, nmemb, i, j, t, p, size, cnt, tmp); /* * For each element of the heap, save the largest element into its * final slot, save the displaced element (k), then recreate the * heap. */ while (nmemb > 1) { COPY(k, base + nmemb * size, cnt, size, tmp1, tmp2); COPY(base + nmemb * size, base + size, cnt, size, tmp1, tmp2); --nmemb; SELECT(i, j, nmemb, t, p, size, k, cnt, tmp1, tmp2); } Free(k); return (0); }
{ "language": "C" }
.\" ************************************************************************** .\" * _ _ ____ _ .\" * Project ___| | | | _ \| | .\" * / __| | | | |_) | | .\" * | (__| |_| | _ <| |___ .\" * \___|\___/|_| \_\_____| .\" * .\" * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. .\" * .\" * This software is licensed as described in the file COPYING, which .\" * you should have received as part of this distribution. The terms .\" * are also available at https://curl.haxx.se/docs/copyright.html. .\" * .\" * You may opt to use, copy, modify, merge, publish, distribute and/or sell .\" * copies of the Software, and permit persons to whom the Software is .\" * furnished to do so, under the terms of the COPYING file. .\" * .\" * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY .\" * KIND, either express or implied. .\" * .\" ************************************************************************** .\" .TH CURLOPT_DIRLISTONLY 3 "17 Jun 2014" "libcurl 7.37.0" "curl_easy_setopt options" .SH NAME CURLOPT_DIRLISTONLY \- ask for names only in a directory listing .SH SYNOPSIS #include <curl/curl.h> CURLcode curl_easy_setopt(CURL *handle, CURLOPT_DIRLISTONLY, long listonly); .SH DESCRIPTION For FTP and SFTP based URLs a parameter set to 1 tells the library to list the names of files in a directory, rather than performing a full directory listing that would normally include file sizes, dates etc. For POP3 a parameter of 1 tells the library to list the email message or messages on the POP3 server. This can be used to change the default behaviour of libcurl, when combined with a URL that contains a message ID, to perform a "scan listing" which can then be used to determine the size of an email. Note: For FTP this causes a NLST command to be sent to the FTP server. Beware that some FTP servers list only files in their response to NLST; they might not include subdirectories and symbolic links. Setting this option to 1 also implies a directory listing even if the URL doesn't end with a slash, which otherwise is necessary. Do NOT use this option if you also use \fICURLOPT_WILDCARDMATCH(3)\fP as it will effectively break that feature then. .SH DEFAULT 0, disabled .SH PROTOCOLS FTP, SFTP and POP3 .SH EXAMPLE .nf CURL *curl = curl_easy_init(); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, "ftp://example.com/dir/"); /* list only */ curl_easy_setopt(curl, CURLOPT_DIRLISTONLY, 1L); ret = curl_easy_perform(curl); curl_easy_cleanup(curl); } .fi .SH AVAILABILITY This option was known as CURLOPT_FTPLISTONLY up to 7.16.4. POP3 is supported since 7.21.5. .SH RETURN VALUE Returns CURLE_OK if the option is supported, and CURLE_UNKNOWN_OPTION if not. .SH "SEE ALSO" .BR CURLOPT_CUSTOMREQUEST "(3), "
{ "language": "C" }
/* LUFA Library Copyright (C) Dean Camera, 2013. dean [at] fourwalledcubicle [dot] com www.lufa-lib.org */ /* Copyright 2013 Dean Camera (dean [at] fourwalledcubicle [dot] com) Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that the copyright notice and this permission notice and warranty disclaimer appear in supporting documentation, and that the name of the author not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. The author disclaims all warranties with regard to this software, including all implied warranties of merchantability and fitness. In no event shall the author be liable for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of this software. */ /** \file * \brief Serial USART Peripheral Driver (AVR8) * * On-chip serial USART driver for the 8-bit AVR microcontrollers. * * \note This file should not be included directly. It is automatically included as needed by the USART driver * dispatch header located in LUFA/Drivers/Peripheral/Serial.h. */ /** \ingroup Group_Serial * \defgroup Group_Serial_AVR8 Serial USART Peripheral Driver (AVR8) * * \section Sec_ModDescription Module Description * On-chip serial USART driver for the 8-bit AVR microcontrollers. * * \note This file should not be included directly. It is automatically included as needed by the USART driver * dispatch header located in LUFA/Drivers/Peripheral/Serial.h. * * \section Sec_ExampleUsage Example Usage * The following snippet is an example of how this module may be used within a typical * application. * * \code * // Initialize the serial USART driver before first use, with 9600 baud (and no double-speed mode) * Serial_Init(9600, false); * * // Send a string through the USART * Serial_SendString("Test String\r\n"); * * // Send a raw byte through the USART * Serial_SendByte(0xDC); * * // Receive a byte through the USART (or -1 if no data received) * int16_t DataByte = Serial_ReceiveByte(); * \endcode * * @{ */ #ifndef __SERIAL_AVR8_H__ #define __SERIAL_AVR8_H__ /* Includes: */ #include "../../../Common/Common.h" #include "../../Misc/TerminalCodes.h" #include <stdio.h> /* Enable C linkage for C++ Compilers: */ #if defined(__cplusplus) extern "C" { #endif /* Preprocessor Checks: */ #if !defined(__INCLUDE_FROM_SERIAL_H) && !defined(__INCLUDE_FROM_SERIAL_C) #error Do not include this file directly. Include LUFA/Drivers/Peripheral/Serial.h instead. #endif /* Private Interface - For use in library only: */ #if !defined(__DOXYGEN__) /* External Variables: */ extern FILE USARTSerialStream; /* Function Prototypes: */ int Serial_putchar(char DataByte, FILE *Stream); int Serial_getchar(FILE *Stream); int Serial_getchar_Blocking(FILE *Stream); #endif /* Public Interface - May be used in end-application: */ /* Macros: */ /** Macro for calculating the baud value from a given baud rate when the \c U2X (double speed) bit is * not set. * * \param[in] Baud Target serial UART baud rate. * * \return Closest UBRR register value for the given UART frequency. */ #define SERIAL_UBBRVAL(Baud) ((((F_CPU / 16) + (Baud / 2)) / (Baud)) - 1) /** Macro for calculating the baud value from a given baud rate when the \c U2X (double speed) bit is * set. * * \param[in] Baud Target serial UART baud rate. * * \return Closest UBRR register value for the given UART frequency. */ #define SERIAL_2X_UBBRVAL(Baud) ((((F_CPU / 8) + (Baud / 2)) / (Baud)) - 1) /* Function Prototypes: */ /** Transmits a given NUL terminated string located in program space (FLASH) through the USART. * * \param[in] FlashStringPtr Pointer to a string located in program space. */ void Serial_SendString_P(const char* FlashStringPtr) ATTR_NON_NULL_PTR_ARG(1); /** Transmits a given NUL terminated string located in SRAM memory through the USART. * * \param[in] StringPtr Pointer to a string located in SRAM space. */ void Serial_SendString(const char* StringPtr) ATTR_NON_NULL_PTR_ARG(1); /** Transmits a given buffer located in SRAM memory through the USART. * * \param[in] Buffer Pointer to a buffer containing the data to send. * \param[in] Length Length of the data to send, in bytes. */ void Serial_SendData(const void* Buffer, uint16_t Length) ATTR_NON_NULL_PTR_ARG(1); /** Creates a standard character stream from the USART so that it can be used with all the regular functions * in the avr-libc \c <stdio.h> library that accept a \c FILE stream as a destination (e.g. \c fprintf). The created * stream is bidirectional and can be used for both input and output functions. * * Reading data from this stream is non-blocking, i.e. in most instances, complete strings cannot be read in by a single * fetch, as the endpoint will not be ready at some point in the transmission, aborting the transfer. However, this may * be used when the read data is processed byte-per-bye (via \c getc()) or when the user application will implement its own * line buffering. * * \param[in,out] Stream Pointer to a FILE structure where the created stream should be placed, if \c NULL, \c stdout * and \c stdin will be configured to use the USART. * * \pre The USART must first be configured via a call to \ref Serial_Init() before the stream is used. */ void Serial_CreateStream(FILE* Stream); /** Identical to \ref Serial_CreateStream(), except that reads are blocking until the calling stream function terminates * the transfer. * * \param[in,out] Stream Pointer to a FILE structure where the created stream should be placed, if \c NULL, \c stdout * and \c stdin will be configured to use the USART. * * \pre The USART must first be configured via a call to \ref Serial_Init() before the stream is used. */ void Serial_CreateBlockingStream(FILE* Stream); /* Inline Functions: */ /** Initializes the USART, ready for serial data transmission and reception. This initializes the interface to * standard 8-bit, no parity, 1 stop bit settings suitable for most applications. * * \param[in] BaudRate Serial baud rate, in bits per second. * \param[in] DoubleSpeed Enables double speed mode when set, halving the sample time to double the baud rate. */ static inline void Serial_Init(const uint32_t BaudRate, const bool DoubleSpeed) { UBRR1 = (DoubleSpeed ? SERIAL_2X_UBBRVAL(BaudRate) : SERIAL_UBBRVAL(BaudRate)); UCSR1C = ((1 << UCSZ11) | (1 << UCSZ10)); UCSR1A = (DoubleSpeed ? (1 << U2X1) : 0); UCSR1B = ((1 << TXEN1) | (1 << RXEN1)); DDRD |= (1 << 3); PORTD |= (1 << 2); } /** Turns off the USART driver, disabling and returning used hardware to their default configuration. */ static inline void Serial_Disable(void) { UCSR1B = 0; UCSR1A = 0; UCSR1C = 0; UBRR1 = 0; DDRD &= ~(1 << 3); PORTD &= ~(1 << 2); } /** Indicates whether a character has been received through the USART. * * \return Boolean \c true if a character has been received, \c false otherwise. */ static inline bool Serial_IsCharReceived(void) ATTR_WARN_UNUSED_RESULT ATTR_ALWAYS_INLINE; static inline bool Serial_IsCharReceived(void) { return ((UCSR1A & (1 << RXC1)) ? true : false); } /** Transmits a given byte through the USART. * * \param[in] DataByte Byte to transmit through the USART. */ static inline void Serial_SendByte(const char DataByte) ATTR_ALWAYS_INLINE; static inline void Serial_SendByte(const char DataByte) { while (!(UCSR1A & (1 << UDRE1))); UDR1 = DataByte; } /** Receives the next byte from the USART. * * \return Next byte received from the USART, or a negative value if no byte has been received. */ static inline int16_t Serial_ReceiveByte(void) ATTR_ALWAYS_INLINE; static inline int16_t Serial_ReceiveByte(void) { if (!(Serial_IsCharReceived())) return -1; return UDR1; } /* Disable C linkage for C++ Compilers: */ #if defined(__cplusplus) } #endif #endif /** @} */
{ "language": "C" }
/* * Memory based image store Operation * * Copyright(c) 2018 Xilinx Ltd. * All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include <metal/io.h> #include <metal/sys.h> #include <openamp/remoteproc_loader.h> #include <stdarg.h> #include <stdio.h> /* Xilinx headers */ #include <pm_api_sys.h> #include <pm_defs.h> #include <xil_printf.h> #define LPRINTF(format, ...) xil_printf(format, ##__VA_ARGS__) //#define LPRINTF(format, ...) #define LPERROR(format, ...) LPRINTF("ERROR: " format, ##__VA_ARGS__) struct mem_file { const void *base; }; int mem_image_open(void *store, const char *path, const void **image_data) { struct mem_file *image = store; const void *fw_base = image->base; (void)(path); if (image_data == NULL) { LPERROR("%s: input image_data is NULL\r\n", __func__); return -EINVAL; } *image_data = fw_base; /* return an abitrary length, as the whole firmware is in memory */ return 0x100; } void mem_image_close(void *store) { /* The image is in memory, does nothing */ (void)store; } int mem_image_load(void *store, size_t offset, size_t size, const void **data, metal_phys_addr_t pa, struct metal_io_region *io, char is_blocking) { struct mem_file *image = store; const void *fw_base = image->base; (void)is_blocking; LPRINTF("%s: offset=0x%x, size=0x%x\n\r", __func__, offset, size); if (pa == METAL_BAD_PHYS) { if (data == NULL) { LPERROR("%s: data is NULL while pa is ANY\r\n", __func__); return -EINVAL; } *data = (const void *)((const char *)fw_base + offset); } else { void *va; if (io == NULL) { LPERROR("%s, io is NULL while pa is not ANY\r\n", __func__); return -EINVAL; } va = metal_io_phys_to_virt(io, pa); if (va == NULL) { LPERROR("%s: no va is found\r\n", __func__); return -EINVAL; } memcpy(va, (const void *)((const char *)fw_base + offset), size); } return (int)size; } struct image_store_ops mem_image_store_ops = { .open = mem_image_open, .close = mem_image_close, .load = mem_image_load, .features = SUPPORT_SEEK, };
{ "language": "C" }
/* Compatibility shim for <getopt.h> * * Copyright (C) 2006 to 2013 by Jonathan Duddington * email: jonsd@users.sourceforge.net * Copyright (C) 2016 Reece H. Dunn * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see: <http://www.gnu.org/licenses/>. */ #ifndef GETOPT_H_COMPAT_SHIM #define GETOPT_H_COMPAT_SHIM #if defined(HAVE_GETOPT_H) #pragma GCC system_header // Silence "warning: #include_next is a GCC extension" #include_next <getopt.h> #else struct option { char *name; int has_arg; int *flag; int val; }; extern int optind; extern char *optarg; #define no_argument 0 #define required_argument 1 #define optional_argument 2 int getopt_long(int nargc, char * const *nargv, const char *options, const struct option *long_options, int *idx); #endif #endif
{ "language": "C" }
/* ** Copyright 2003-2010, VisualOn, Inc. ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ /******************************************************************************* File: ms_stereo.h Content: Declaration MS stereo processing structure and functions *******************************************************************************/ #ifndef __MS_STEREO_H__ #define __MS_STEREO_H__ #include "typedef.h" void MsStereoProcessing(Word32 *sfbEnergyLeft, Word32 *sfbEnergyRight, const Word32 *sfbEnergyMid, const Word32 *sfbEnergySide, Word32 *mdctSpectrumLeft, Word32 *mdctSpectrumRight, Word32 *sfbThresholdLeft, Word32 *sfbThresholdRight, Word32 *sfbSpreadedEnLeft, Word32 *sfbSpreadedEnRight, Word16 *msDigest, Word16 *msMask, const Word16 sfbCnt, const Word16 sfbPerGroup, const Word16 maxSfbPerGroup, const Word16 *sfbOffset); #endif
{ "language": "C" }
#ifdef HAVE_CONFIG_H #include "config.h" #endif #define FASTER #ifndef PSZ #define PSZ 8 #endif #if PSZ == 24 # define APM_SUFF_24 "24" # define A(s) Apm##s##24 #else # define APM_SUFF_24 "" # define A(s) Apm##s #endif #define DPRINTNAME(s) do { xf86DrvMsgVerb(pScrn->pScreen->myNum, X_NOTICE, 6, "Apm" #s APM_SUFF_24 "\n"); } while (0) #if PSZ == 24 #undef SETSOURCEXY #undef SETDESTXY #undef SETWIDTH #undef SETWIDTHHEIGHT #undef UPDATEDEST #define SETSOURCEXY(x,y) do { int off = ((((y) & 0xFFFF) * pApm->CurrentLayout.displayWidth + ((x) & 0x3FFF)) * 3); SETSOURCEOFF(((off & 0xFFF000) << 4) | (off & 0xFFF)); break;} while(1) #define SETDESTXY(x,y) do { int off = ((((y) & 0xFFFF) * pApm->CurrentLayout.displayWidth + ((x) & 0x3FFF)) * 3); SETDESTOFF(((off & 0xFFF000) << 4) | (off & 0xFFF)); break;} while(1) #define SETWIDTH(w) WRXW(0x58, ((w) & 0x3FFF) * 3) #define SETWIDTHHEIGHT(w,h) WRXL(0x58, ((h) << 16) | (((w) & 0x3FFF) * 3)) #define UPDATEDEST(x,y) (void)(curr32[0x54 / 4] = ((((y) & 0xFFFF) * pApm->CurrentLayout.displayWidth + ((x) & 0xFFFF)) * 3)) #endif /* Defines */ #define MAXLOOP 1000000 /* Local functions */ static void A(Sync)(ScrnInfoPtr pScrn); static void A(SetupForSolidFill)(ScrnInfoPtr pScrn, int color, int rop, unsigned int planemask); static void A(SubsequentSolidFillRect)(ScrnInfoPtr pScrn, int x, int y, int w, int h); static void A(SetupForScreenToScreenCopy)(ScrnInfoPtr pScrn, int xdir, int ydir, int rop, unsigned int planemask, int transparency_color); static void A(SubsequentScreenToScreenCopy)(ScrnInfoPtr pScrn, int x1, int y1, int x2, int y2, int w, int h); #if PSZ != 24 static void A(Sync6422)(ScrnInfoPtr pScrn); static void A(WriteBitmap)(ScrnInfoPtr pScrn, int x, int y, int w, int h, unsigned char *src, int srcwidth, int skipleft, int fg, int bg, int rop, unsigned int planemask); static void A(TEGlyphRenderer)(ScrnInfoPtr pScrn, int x, int y, int w, int h, int skipleft, int startline, unsigned int **glyphs, int glyphWidth, int fg, int bg, int rop, unsigned planemask); static void A(SetupForMono8x8PatternFill)(ScrnInfoPtr pScrn, int patx, int paty, int fg, int bg, int rop, unsigned int planemask); static void A(SubsequentMono8x8PatternFillRect)(ScrnInfoPtr pScrn, int patx, int paty, int x, int y, int w, int h); #if 0 static void A(SetupForCPUToScreenColorExpandFill)(ScrnInfoPtr pScrn, int bg, int fg, int rop, unsigned int planemask); static void A(SubsequentCPUToScreenColorExpandFill)(ScrnInfoPtr pScrn, int x, int y, int w, int h, int skipleft); #endif static void A(SetupForScreenToScreenColorExpandFill)(ScrnInfoPtr pScrn, int fg, int bg, int rop, unsigned int planemask); static void A(SetupForImageWrite)(ScrnInfoPtr pScrn, int rop, unsigned int planemask, int trans_color, int bpp, int depth); static void A(SubsequentImageWriteRect)(ScrnInfoPtr pScrn, int x, int y, int w, int h, int skipleft); static void A(SubsequentScreenToScreenColorExpandFill)(ScrnInfoPtr pScrn, int x, int y, int w, int h, int srcx, int srcy, int offset); static void A(SubsequentSolidBresenhamLine)(ScrnInfoPtr pScrn, int x1, int y1, int octant, int err, int e1, int e2, int length); static void A(SubsequentSolidBresenhamLine6422)(ScrnInfoPtr pScrn, int x1, int y1, int octant, int err, int e1, int e2, int length); static void A(SetClippingRectangle)(ScrnInfoPtr pScrn, int x1, int y1, int x2, int y2); static void A(WritePixmap)(ScrnInfoPtr pScrn, int x, int y, int w, int h, unsigned char *src, int srcwidth, int rop, unsigned int planemask, int trans, int bpp, int depth); static void A(FillImageWriteRects)(ScrnInfoPtr pScrn, int rop, unsigned int planemask, int nBox, BoxPtr pBox, int xorg, int yorg, PixmapPtr pPix); static void A(SetupForColor8x8PatternFill)(ScrnInfoPtr pScrn,int patx,int paty, int rop, unsigned int planemask, int transparency_color); static void A(SubsequentColor8x8PatternFillRect)(ScrnInfoPtr pScrn, int patx, int paty, int x, int y, int w, int h); #endif /* Inline functions */ static __inline__ void A(WaitForFifo)(ApmPtr pApm, int slots) { if (!pApm->UsePCIRetry) { volatile int i; for(i = 0; i < MAXLOOP; i++) { if ((STATUS() & STATUS_FIFO) >= slots) break; } if (i == MAXLOOP) { unsigned int status = STATUS(); WRXB(0x1FF, 0); if (!xf86ServerIsExiting()) FatalError("Hung in WaitForFifo() (Status = 0x%08X)\n", status); } } } static void A(SetupForSolidFill)(ScrnInfoPtr pScrn, int color, int rop, unsigned int planemask) { APMDECL(pScrn); DPRINTNAME(SetupForSolidFill); #ifdef FASTER A(WaitForFifo)(pApm, 3 + pApm->apmClip); SETDEC(DEC_QUICKSTART_ONDIMX | DEC_OP_RECT | DEC_DEST_UPD_TRCORNER | pApm->CurrentLayout.Setup_DEC); #else A(WaitForFifo)(pApm, 2 + pApm->apmClip); #endif #if PSZ == 2 pApm->color = ((color & 0xFF0000) << 8) | ((color & 0xFF0000) >> 16) | ((color & 0xFF00) << 8) | ((color & 0xFF) << 16); #else SETFOREGROUNDCOLOR(color); #endif if (pApm->apmClip) { SETCLIP_CTRL(0); pApm->apmClip = FALSE; } SETROP(apmROP[rop]); } static void A(SubsequentSolidFillRect)(ScrnInfoPtr pScrn, int x, int y, int w, int h) { APMDECL(pScrn); DPRINTNAME(SubsequentSolidFillRect); #if PSZ == 24 # ifndef FASTER A(WaitForFifo)(pApm, 5); # else A(WaitForFifo)(pApm, 4); # endif SETOFFSET(3*(pApm->CurrentLayout.displayWidth - w)); #if 0 switch ((((y * pApm->CurrentLayout.displayWidth + x)* 3) / 8) % 3) { case 0: SETFOREGROUNDCOLOR(pApm->color); break; case 1: SETFOREGROUNDCOLOR((pApm->color << 8) | (pApm->color >> 16)); break; case 2: SETFOREGROUNDCOLOR(pApm->color >> 8); break; } #endif #else # ifndef FASTER A(WaitForFifo)(pApm, 3); # else A(WaitForFifo)(pApm, 2); # endif #endif SETDESTXY(x, y); SETWIDTHHEIGHT(w, h); UPDATEDEST(x + w + 1, y); #ifndef FASTER SETDEC(DEC_START | DEC_OP_RECT | DEC_DEST_UPD_TRCORNER | pApm->CurrentLayout.Setup_DEC); #endif } static void A(SetupForScreenToScreenCopy)(ScrnInfoPtr pScrn, int xdir, int ydir, int rop, unsigned int planemask, int transparency_color) { unsigned char tmp; APMDECL(pScrn); DPRINTNAME(SetupForScreenToScreenCopy); if (pApm->apmLock) { /* * This is just an attempt, because Daryll is tampering with MY registers. */ tmp = (RDXB(0xDB) & 0xF4) | 0x0A; WRXB(0xDB, tmp); ApmWriteSeq(0x1B, 0x20); ApmWriteSeq(0x1C, 0x2F); pApm->apmLock = FALSE; } pApm->blitxdir = xdir; pApm->blitydir = ydir; pApm->apmTransparency = (transparency_color != -1); #ifdef FASTER A(WaitForFifo)(pApm, 2 + (transparency_color != -1)); SETDEC(DEC_QUICKSTART_ONDIMX | DEC_OP_BLT | DEC_DEST_UPD_TRCORNER | (pApm->apmTransparency ? DEC_SOURCE_TRANSPARENCY : 0) | pApm->CurrentLayout.Setup_DEC | ((xdir < 0) ? DEC_DIR_X_NEG : DEC_DIR_X_POS) | ((ydir < 0) ? DEC_DIR_Y_NEG : DEC_DIR_Y_POS)); #else A(WaitForFifo)(pApm, 1 + (transparency_color != -1)); #endif if (transparency_color != -1) SETBACKGROUNDCOLOR(transparency_color); SETROP(apmROP[rop]); } static void A(SubsequentScreenToScreenCopy)(ScrnInfoPtr pScrn, int x1, int y1, int x2, int y2, int w, int h) { APMDECL(pScrn); #ifndef FASTER u32 c = pApm->apmTransparency ? DEC_SOURCE_TRANSPARENCY : 0; #endif u32 sx, dx, sy, dy; int i = y1 / pApm->CurrentLayout.Scanlines; DPRINTNAME(SubsequentScreenToScreenCopy); if (i && pApm->pixelStride) { #ifdef FASTER A(WaitForFifo)(pApm, 1); SETDEC(curr32[0x40 / 4] | (DEC_SOURCE_CONTIG | DEC_SOURCE_LINEAR)); #else c |= DEC_SOURCE_LINEAR | DEC_SOURCE_CONTIG; #endif pApm->apmClip = TRUE; A(WaitForFifo)(pApm, 3); SETCLIP_LEFTTOP(x2, y2); SETCLIP_RIGHTBOT(x2 + w - 1, y2 + h - 1); SETCLIP_CTRL(1); w = (pApm->pixelStride * 8) / pApm->CurrentLayout.bitsPerPixel; } else { #ifdef FASTER A(WaitForFifo)(pApm, 1 + pApm->apmClip); SETDEC(curr32[0x40 / 4] & ~(DEC_SOURCE_CONTIG | DEC_SOURCE_LINEAR)); if (pApm->apmClip) SETCLIP_CTRL(0); pApm->apmClip = FALSE; #else if (pApm->apmClip) { A(WaitForFifo)(pApm, 1); SETCLIP_CTRL(0); pApm->apmClip = FALSE; } #endif } if (i) { if (pApm->pixelStride) { x1 += (((y1 % pApm->CurrentLayout.Scanlines) - pApm->RushY[i - 1]) * pApm->pixelStride * 8) / pApm->CurrentLayout.bitsPerPixel; y1 = pApm->RushY[i - 1]; } else y1 -= i * pApm->CurrentLayout.Scanlines; } if (pApm->blitxdir < 0) { #ifndef FASTER c |= DEC_DIR_X_NEG; #endif sx = x1+w-1; dx = x2+w-1; } else { #ifndef FASTER c |= DEC_DIR_X_POS; #endif sx = x1; dx = x2; } if (pApm->blitydir < 0) { #ifndef FASTER c |= DEC_DIR_Y_NEG | DEC_START | DEC_OP_BLT | DEC_DEST_UPD_TRCORNER | pApm->CurrentLayout.Setup_DEC; #endif sy = y1+h-1; dy = y2+h-1; } else { #ifndef FASTER c |= DEC_DIR_Y_POS | DEC_START | DEC_OP_BLT | DEC_DEST_UPD_TRCORNER | pApm->CurrentLayout.Setup_DEC; #endif sy = y1; dy = y2; } #if PSZ == 24 # ifndef FASTER A(WaitForFifo)(pApm, 5); # else A(WaitForFifo)(pApm, 4); # endif if (pApm->blitxdir == pApm->blitydir) SETOFFSET(3 * (pApm->CurrentLayout.displayWidth - w)); else SETOFFSET(3 * (pApm->CurrentLayout.displayWidth + w)); #else # ifndef FASTER A(WaitForFifo)(pApm, 4); # else A(WaitForFifo)(pApm, 3); # endif #endif if (i && pApm->pixelStride) { register unsigned int off = sx + sy * pApm->CurrentLayout.displayWidth; SETSOURCEOFF(((off & 0xFFF000) << 4) | (off & 0xFFF)); } else SETSOURCEXY(sx,sy); SETDESTXY(dx,dy); SETWIDTHHEIGHT(w,h); UPDATEDEST(dx + (w + 1)*pApm->blitxdir, dy); #ifndef FASTER SETDEC(c); #endif if (i) A(Sync)(pScrn); /* Only for AT3D */ } #if PSZ != 24 static void A(SetupForScreenToScreenColorExpandFill)(ScrnInfoPtr pScrn, int fg, int bg, int rop, unsigned int planemask) { APMDECL(pScrn); DPRINTNAME(SetupForScreenToScreenColorExpandFill); A(WaitForFifo)(pApm, 3 + pApm->apmClip); if (bg == -1) { SETFOREGROUNDCOLOR(fg); SETBACKGROUNDCOLOR(fg+1); pApm->apmTransparency = TRUE; } else { SETFOREGROUNDCOLOR(fg); SETBACKGROUNDCOLOR(bg); pApm->apmTransparency = FALSE; } SETROP(apmROP[rop]); } static void A(WriteBitmap)(ScrnInfoPtr pScrn, int x, int y, int w, int h, unsigned char *src, int srcwidth, int skipleft, int fg, int bg, int rop, unsigned int planemask) { APMDECL(pScrn); Bool beCareful, apmClip = FALSE; int wc, n, nc, wr, wrd; CARD32 *dstPtr; #ifndef FASTER int c; #endif DPRINTNAME(WriteBitmap); if (w <= 0 && h <= 0) return; /* * The function is a bit long, but the spirit is simple : put the monochrome * data in scratch memory and color-expand it using the * ScreenToScreenColorExpand techniques. */ w += skipleft; x -= skipleft; wc = pApm->ScratchMemSize * 8; wrd = (w + 31) >> 5; wr = wrd << 5; nc = wc / wr; if (nc > h) nc = h; if (wr / 8 > srcwidth) beCareful = TRUE; else beCareful = FALSE; srcwidth -= wr / 8; if (skipleft || w != wr) { apmClip = TRUE; A(WaitForFifo)(pApm, 3); SETCLIP_LEFTTOP(x + skipleft, y); SETCLIP_RIGHTBOT(x + w - 1, y + h - 1); SETCLIP_CTRL(1); } else if (pApm->apmClip) { A(WaitForFifo)(pApm, 1); SETCLIP_CTRL(0); } pApm->apmClip = FALSE; A(SetupForScreenToScreenColorExpandFill)(pScrn, fg, bg, rop, planemask); #ifdef FASTER A(WaitForFifo)(pApm, 2); if (pApm->apmTransparency) SETDEC(DEC_OP_BLT | DEC_DIR_X_POS | DEC_DIR_Y_POS | DEC_SOURCE_MONOCHROME | DEC_QUICKSTART_ONDIMX | DEC_DEST_UPD_BLCORNER | DEC_SOURCE_LINEAR | DEC_SOURCE_CONTIG | DEC_SOURCE_TRANSPARENCY | pApm->CurrentLayout.Setup_DEC); else SETDEC(DEC_OP_BLT | DEC_DIR_X_POS | DEC_DIR_Y_POS | DEC_SOURCE_MONOCHROME | DEC_QUICKSTART_ONDIMX | DEC_DEST_UPD_BLCORNER | DEC_SOURCE_LINEAR | DEC_SOURCE_CONTIG | pApm->CurrentLayout.Setup_DEC); #else A(WaitForFifo)(pApm, 1); c = DEC_OP_BLT | DEC_DIR_X_POS | DEC_DIR_Y_POS | DEC_SOURCE_MONOCHROME | DEC_START | DEC_DEST_UPD_BLCORNER | DEC_SOURCE_LINEAR | DEC_SOURCE_CONTIG | pApm->CurrentLayout.Setup_DEC; if (pApm->apmTransparency) c |= DEC_SOURCE_TRANSPARENCY; #endif SETDESTXY(x, y); if (!beCareful || h % nc > 3 || (w > 16 && h % nc)) { #ifndef FASTER if (h / nc) SETWIDTHHEIGHT(wr, nc); #endif for (n = h / nc; n-- > 0; ) { int i, j; if (pApm->ScratchMemPtr + nc * wrd * 4 < pApm->ScratchMemEnd) { #define d ((memType)dstPtr - (memType)pApm->FbBase) A(WaitForFifo)(pApm, 1); dstPtr = (CARD32 *)pApm->ScratchMemPtr; switch(pApm->CurrentLayout.bitsPerPixel) { case 8: case 24: SETSOURCEOFF((d & 0xFFF000) << 4 | (d & 0xFFF)); break; case 16: SETSOURCEOFF((d & 0xFFE000) << 3 | ((d & 0x1FFE) >> 1)); break; case 32: SETSOURCEOFF((d & 0xFFC000) << 2 | ((d & 0x3FFC) >> 2)); break; } #undef d } else { (*pApm->AccelInfoRec->Sync)(pScrn); dstPtr = (CARD32 *)pApm->ScratchMemOffset; SETSOURCEOFF(pApm->ScratchMem); } pApm->ScratchMemPtr = ((memType)(dstPtr + wrd * nc) + 4) & ~(memType)7; for (i = nc; i-- > 0; ) { for (j = wrd; j-- > 0; ) { *dstPtr++ = XAAReverseBitOrder(*(CARD32 *)src); src += 4; } src += srcwidth; } A(WaitForFifo)(pApm, 1); #ifdef FASTER SETWIDTHHEIGHT(wr, nc); #else SETDEC(c); #endif } } else { #ifndef FASTER if (h / nc) SETWIDTHHEIGHT(wr, nc); #endif for (n = h / nc; n-- > 0; ) { int i, j; if (pApm->ScratchMemPtr + nc * wrd * 4 < pApm->ScratchMemEnd) { #define d ((memType)dstPtr - (memType)pApm->FbBase) A(WaitForFifo)(pApm, 1); dstPtr = (CARD32 *)pApm->ScratchMemPtr; switch(pApm->CurrentLayout.bitsPerPixel) { case 8: case 24: SETSOURCEOFF((d & 0xFFF000) << 4 | (d & 0xFFF)); break; case 16: SETSOURCEOFF((d & 0xFFE000) << 3 | ((d & 0x1FFE) >> 1)); break; case 32: SETSOURCEOFF((d & 0xFFC000) << 2 | ((d & 0x3FFC) >> 2)); break; } #undef d } else { (*pApm->AccelInfoRec->Sync)(pScrn); dstPtr = (CARD32 *)pApm->ScratchMemOffset; SETSOURCEOFF(pApm->ScratchMem); } pApm->ScratchMemPtr = ((memType)(dstPtr + wrd * nc * 4) + 4) & ~7; for (i = nc; i-- > 0; ) { for (j = wrd; j-- > 0; ) { if (i || j || n) *dstPtr++ = XAAReverseBitOrder(*(CARD32 *)src); else if (srcwidth > -8) { ((CARD8 *)dstPtr)[0] = byte_reversed[((CARD8 *)src)[2]]; ((CARD8 *)dstPtr)[1] = byte_reversed[((CARD8 *)src)[1]]; ((CARD8 *)dstPtr)[2] = byte_reversed[((CARD8 *)src)[0]]; dstPtr = (CARD32 *)(3 + (CARD8 *)dstPtr); } else if (srcwidth > -16) { ((CARD8 *)dstPtr)[0] = byte_reversed[((CARD8 *)src)[1]]; ((CARD8 *)dstPtr)[1] = byte_reversed[((CARD8 *)src)[0]]; dstPtr = (CARD32 *)(2 + (CARD8 *)dstPtr); } else { *(CARD8 *)dstPtr = byte_reversed[*(CARD8 *)src]; dstPtr = (CARD32 *)(1 + (CARD8 *)dstPtr); } src += 4; } src += srcwidth; } A(WaitForFifo)(pApm, 1); #ifdef FASTER SETWIDTHHEIGHT(wr, nc); #else SETDEC(c); #endif } } /* * Same thing for the remnant */ UPDATEDEST(x, y + h + 1); h %= nc; if (h) { if (!beCareful) { int i, j; #ifndef FASTER SETWIDTHHEIGHT(wr, h); #endif if (pApm->ScratchMemPtr + h * wrd * 4 < pApm->ScratchMemEnd) { #define d ((memType)dstPtr - (memType)pApm->FbBase) A(WaitForFifo)(pApm, 1); dstPtr = (CARD32 *)pApm->ScratchMemPtr; switch(pApm->CurrentLayout.bitsPerPixel) { case 8: case 24: SETSOURCEOFF((d & 0xFFF000) << 4 | (d & 0xFFF)); break; case 16: SETSOURCEOFF((d & 0xFFE000) << 3 | ((d & 0x1FFE) >> 1)); break; case 32: SETSOURCEOFF((d & 0xFFC000) << 2 | ((d & 0x3FFC) >> 2)); break; } #undef d } else { (*pApm->AccelInfoRec->Sync)(pScrn); dstPtr = (CARD32 *)pApm->ScratchMemOffset; SETSOURCEOFF(pApm->ScratchMem); } pApm->ScratchMemPtr = ((memType)(dstPtr + wrd * h) + 4) & ~7; for (i = h; i-- > 0; ) { for (j = wrd; j-- > 0; ) { *dstPtr++ = XAAReverseBitOrder(*(CARD32 *)src); src += 4; } src += srcwidth; } A(WaitForFifo)(pApm, 1); #ifdef FASTER SETWIDTHHEIGHT(wr, h); #else SETDEC(c); #endif } else { int i, j; #ifndef FASTER SETWIDTHHEIGHT(w, h); #endif if (pApm->ScratchMemPtr + h * wrd * 4 < pApm->ScratchMemEnd) { #define d ((memType)dstPtr - (memType)pApm->FbBase) A(WaitForFifo)(pApm, 1); dstPtr = (CARD32 *)pApm->ScratchMemPtr; switch(pApm->CurrentLayout.bitsPerPixel) { case 8: case 24: SETSOURCEOFF((d & 0xFFF000) << 4 | (d & 0xFFF)); break; case 16: SETSOURCEOFF((d & 0xFFE000) << 3 | ((d & 0x1FFE) >> 1)); break; case 32: SETSOURCEOFF((d & 0xFFC000) << 2 | ((d & 0x3FFC) >> 2)); break; } #undef d } else { (*pApm->AccelInfoRec->Sync)(pScrn); dstPtr = (CARD32 *)pApm->ScratchMemOffset; SETSOURCEOFF(pApm->ScratchMem); } pApm->ScratchMemPtr = ((memType)(dstPtr + wrd * h) + 4) & ~7; for (i = h; i-- > 0; ) { for (j = wrd; j-- > 0; ) { if (i || j) *dstPtr++ = XAAReverseBitOrder(*(CARD32 *)src); else if (srcwidth > -8) { ((CARD8 *)dstPtr)[0] = byte_reversed[((CARD8 *)src)[2]]; ((CARD8 *)dstPtr)[1] = byte_reversed[((CARD8 *)src)[1]]; ((CARD8 *)dstPtr)[2] = byte_reversed[((CARD8 *)src)[0]]; dstPtr = (CARD32 *)(3 + (CARD8 *)dstPtr); } else if (srcwidth > -16) { ((CARD8 *)dstPtr)[0] = byte_reversed[((CARD8 *)src)[1]]; ((CARD8 *)dstPtr)[1] = byte_reversed[((CARD8 *)src)[0]]; dstPtr = (CARD32 *)(2 + (CARD8 *)dstPtr); } else { *(CARD8 *)dstPtr = byte_reversed[*(CARD8 *)src]; dstPtr = (CARD32 *)(1 + (CARD8 *)dstPtr); } src += 4; } src += srcwidth; } A(WaitForFifo)(pApm, 1); #ifdef FASTER SETWIDTHHEIGHT(w, h); #else SETDEC(c); #endif } } pApm->apmClip = apmClip; } static void A(TEGlyphRenderer)(ScrnInfoPtr pScrn, int x, int y, int w, int h, int skipleft, int startline, unsigned int **glyphs, int glyphWidth, int fg, int bg, int rop, unsigned planemask) { CARD32 *base, *base0; GlyphScanlineFuncPtr GlyphFunc; static GlyphScanlineFuncPtr *GlyphTab = NULL; int w2, h2, dwords; if (!GlyphTab) GlyphTab = XAAGetGlyphScanlineFuncLSBFirst(); GlyphFunc = GlyphTab[glyphWidth - 1]; w2 = w + skipleft; h2 = h; dwords = (w2 + 31) >> 5; dwords <<= 2; base0 = base = malloc(dwords * h); if (!base) return; /* Should not happen : it's rather small... */ while(h--) { base = (*GlyphFunc)(base, glyphs, startline++, w2, glyphWidth); } A(WriteBitmap)(pScrn, x, y, w, h2, (unsigned char *)base0, dwords, skipleft, fg, bg, rop, planemask); free(base0); } static void A(SetupForMono8x8PatternFill)(ScrnInfoPtr pScrn, int patx, int paty, int fg, int bg, int rop, unsigned int planemask) { APMDECL(pScrn); DPRINTNAME(SetupForMono8x8PatternFill); pApm->apmTransparency = (pApm->Chipset >= AT3D) && (bg == -1); pApm->Bg8x8 = bg; pApm->Fg8x8 = fg; pApm->rop = apmROP[rop]; A(WaitForFifo)(pApm, 3 + pApm->apmClip); if (bg == -1) SETBACKGROUNDCOLOR(fg + 1); else SETBACKGROUNDCOLOR(bg); SETFOREGROUNDCOLOR(fg); if (pApm->Chipset >= AT3D) SETROP(apmROP[rop] & 0xF0); else SETROP((apmROP[rop] & 0xF0) | 0x0A); if (pApm->apmClip) { SETCLIP_CTRL(0); pApm->apmClip = FALSE; } } static void A(SubsequentMono8x8PatternFillRect)(ScrnInfoPtr pScrn, int patx, int paty, int x, int y, int w, int h) { APMDECL(pScrn); DPRINTNAME(SubsequentMono8x8PatternFillRect); SETDESTXY(x, y); UPDATEDEST(x, y + h + 1); A(WaitForFifo)(pApm, 6); if (pApm->Chipset == AT24 && pApm->Bg8x8 != -1) { SETROP(pApm->rop); SETFOREGROUNDCOLOR(pApm->Bg8x8); #ifdef FASTER SETDEC(pApm->CurrentLayout.Setup_DEC | ((h == 1) ? DEC_OP_STRIP : DEC_OP_RECT) | DEC_DEST_XY | DEC_QUICKSTART_ONDIMX); SETWIDTHHEIGHT(w, h); #else SETWIDTHHEIGHT(w, h); SETDEC(pApm->CurrentLayout.Setup_DEC | ((h == 1) ? DEC_OP_STRIP : DEC_OP_RECT) | DEC_DEST_XY | DEC_START); #endif A(WaitForFifo)(pApm, 6); SETROP((pApm->rop & 0xF0) | 0x0A); SETFOREGROUNDCOLOR(pApm->Fg8x8); } SETPATTERN(patx, paty); #ifdef FASTER SETDEC(pApm->CurrentLayout.Setup_DEC | ((h == 1) ? DEC_OP_STRIP : DEC_OP_RECT) | DEC_DEST_XY | DEC_PATTERN_88_1bMONO | DEC_DEST_UPD_TRCORNER | (pApm->apmTransparency ? DEC_SOURCE_TRANSPARENCY : 0) | DEC_QUICKSTART_ONDIMX); SETWIDTHHEIGHT(w, h); #else SETWIDTHHEIGHT(w, h); SETDEC(pApm->CurrentLayout.Setup_DEC | ((h == 1) ? DEC_OP_STRIP : DEC_OP_RECT) | DEC_DEST_XY | DEC_PATTERN_88_1bMONO | DEC_DEST_UPD_TRCORNER | (pApm->apmTransparency ? DEC_SOURCE_TRANSPARENCY : 0) | DEC_START); #endif } #if 0 static void A(SetupForCPUToScreenColorExpandFill)(ScrnInfoPtr pScrn, int fg, int bg, int rop, unsigned int planemask) { APMDECL(pScrn); DPRINTNAME(SetupForCPUToScreenColorExpandFill); if (bg == -1) { #ifndef FASTER pApm->apmTransparency = TRUE; A(WaitForFifo)(pApm, 3); #else A(WaitForFifo)(pApm, 4); SETDEC(DEC_OP_HOSTBLT_HOST2SCREEN | DEC_SOURCE_LINEAR | DEC_SOURCE_CONTIG | DEC_SOURCE_TRANSPARENCY | DEC_SOURCE_MONOCHROME | DEC_QUICKSTART_ONDIMX | DEC_DEST_UPD_TRCORNER | pApm->CurrentLayout.Setup_DEC); #endif SETFOREGROUNDCOLOR(fg); SETBACKGROUNDCOLOR(fg+1); } else { #ifndef FASTER pApm->apmTransparency = FALSE; A(WaitForFifo)(pApm, 3); #else A(WaitForFifo)(pApm, 4); SETDEC(DEC_OP_HOSTBLT_HOST2SCREEN | DEC_SOURCE_LINEAR | DEC_SOURCE_CONTIG | DEC_DEST_UPD_TRCORNER | DEC_SOURCE_MONOCHROME | DEC_QUICKSTART_ONDIMX | pApm->CurrentLayout.Setup_DEC); #endif SETFOREGROUNDCOLOR(fg); SETBACKGROUNDCOLOR(bg); } SETROP(apmROP[rop]); } static void A(SubsequentCPUToScreenColorExpandFill)(ScrnInfoPtr pScrn, int x, int y, int w, int h, int skipleft) { APMDECL(pScrn); #ifndef FASTER u32 c; #endif DPRINTNAME(SubsequentCPUToScreenColorExpandFill); #ifndef FASTER c = DEC_OP_HOSTBLT_HOST2SCREEN | DEC_SOURCE_LINEAR | DEC_SOURCE_CONTIG | DEC_SOURCE_MONOCHROME | DEC_START | DEC_DEST_UPD_TRCORNER | pApm->CurrentLayout.Setup_DEC; if (pApm->apmTransparency) c |= DEC_SOURCE_TRANSPARENCY; A(WaitForFifo)(pApm, 7); #else A(WaitForFifo)(pApm, 6); #endif SETCLIP_LEFTTOP(x+skipleft, y); SETCLIP_RIGHTBOT(x+w-1, y+h-1); SETCLIP_CTRL(0x01); pApm->apmClip = TRUE; SETSOURCEX(0); /* According to manual, it just has to be zero */ SETDESTXY(x, y); SETWIDTHHEIGHT((w + 31) & ~31, h); UPDATEDEST(x + ((w + 31) & ~31), y); #ifndef FASTER SETDEC(c); #endif } #endif static void A(SetupForImageWrite)(ScrnInfoPtr pScrn, int rop, unsigned int planemask, int trans_color, int bpp, int depth) { APMDECL(pScrn); DPRINTNAME(SetupForImageWrite); if (trans_color != -1) { #ifndef FASTER pApm->apmTransparency = TRUE; A(WaitForFifo)(pApm, 3); #else A(WaitForFifo)(pApm, 4); SETDEC(DEC_OP_HOSTBLT_HOST2SCREEN | DEC_SOURCE_LINEAR | DEC_SOURCE_CONTIG | DEC_SOURCE_TRANSPARENCY | DEC_QUICKSTART_ONDIMX | pApm->CurrentLayout.Setup_DEC); #endif SETBACKGROUNDCOLOR(trans_color); } else { #ifndef FASTER pApm->apmTransparency = FALSE; A(WaitForFifo)(pApm, 2); #else A(WaitForFifo)(pApm, 3); SETDEC(DEC_OP_HOSTBLT_HOST2SCREEN | DEC_SOURCE_LINEAR | DEC_SOURCE_CONTIG | DEC_QUICKSTART_ONDIMX | pApm->CurrentLayout.Setup_DEC); #endif } SETROP(apmROP[rop]); } static void A(SubsequentImageWriteRect)(ScrnInfoPtr pScrn, int x, int y, int w, int h, int skipleft) { APMDECL(pScrn); #ifndef FASTER u32 c; #endif DPRINTNAME(SubsequentImageWriteRect); #ifndef FASTER c = DEC_OP_HOSTBLT_HOST2SCREEN | DEC_SOURCE_LINEAR | DEC_SOURCE_CONTIG | DEC_START | pApm->CurrentLayout.Setup_DEC; if (pApm->apmTransparency) c |= DEC_SOURCE_TRANSPARENCY; if (pApm->Chipset >= AT24) A(WaitForFifo)(pApm, 7); else A(WaitForFifo)(pApm, 3); #else if (pApm->Chipset >= AT24) A(WaitForFifo)(pApm, 6); else A(WaitForFifo)(pApm, 3); #endif SETCLIP_LEFTTOP(x+skipleft, y); SETCLIP_RIGHTBOT(x+w-1, y+h-1); SETCLIP_CTRL(0x01); pApm->apmClip = TRUE; if (pApm->Chipset < AT24) A(WaitForFifo)(pApm, 4); SETSOURCEX(0); /* According to manual, it just has to be zero */ SETDESTXY(x, y); SETWIDTHHEIGHT((w + 3) & ~3, h); #ifndef FASTER SETDEC(c); #endif } static void A(SubsequentScreenToScreenColorExpandFill)(ScrnInfoPtr pScrn, int x, int y, int w, int h, int srcx, int srcy, int offset) { APMDECL(pScrn); u32 c; DPRINTNAME(SubsequentScreenToScreenColorExpandFill); #ifdef FASTER c = DEC_OP_BLT | DEC_DIR_X_POS | DEC_DIR_Y_POS | DEC_SOURCE_MONOCHROME | DEC_QUICKSTART_ONDIMX | DEC_DEST_UPD_TRCORNER | pApm->CurrentLayout.Setup_DEC; #else c = DEC_OP_BLT | DEC_DIR_X_POS | DEC_DIR_Y_POS | DEC_SOURCE_MONOCHROME | DEC_START | DEC_DEST_UPD_TRCORNER | pApm->CurrentLayout.Setup_DEC; #endif if (pApm->apmTransparency) c |= DEC_SOURCE_TRANSPARENCY; if (srcy >= pApm->CurrentLayout.Scanlines) { struct ApmStippleCacheRec *pCache; CARD32 dist; /* * Offscreen linear stipple */ pCache = &pApm->apmCache[srcy / pApm->CurrentLayout.Scanlines - 1]; if (w != pCache->apmStippleCache.w * pApm->CurrentLayout.bitsPerPixel) { A(WaitForFifo)(pApm, 3); SETCLIP_LEFTTOP(x, y); SETCLIP_RIGHTBOT(x + w - 1, y + h - 1); SETCLIP_CTRL(0x01); pApm->apmClip = TRUE; w = pCache->apmStippleCache.w * pApm->CurrentLayout.bitsPerPixel; x -= srcx - pCache->apmStippleCache.x + offset; srcx = (srcy - pCache->apmStippleCache.y) & 7; srcy -= srcx; y -= srcx; h += srcx; srcx = pCache->apmStippleCache.x; } else if (pApm->apmClip) { A(WaitForFifo)(pApm, 1); SETCLIP_CTRL(0x00); pApm->apmClip = FALSE; } srcx += (srcy - pCache->apmStippleCache.y) * pCache->apmStippleCache.w; srcy = pCache->apmStippleCache.y % pApm->CurrentLayout.Scanlines; dist = srcx + srcy * pApm->CurrentLayout.displayWidth; srcx = dist & 0xFFF; srcy = dist >> 12; c |= DEC_SOURCE_CONTIG | DEC_SOURCE_LINEAR; } else if (offset) { A(WaitForFifo)(pApm, 3); SETCLIP_LEFTTOP(x, y); SETCLIP_RIGHTBOT(x + w, y + h); SETCLIP_CTRL(0x01); pApm->apmClip = TRUE; w += offset; x -= offset; } else if (pApm->apmClip) { A(WaitForFifo)(pApm, 1); SETCLIP_CTRL(0x00); pApm->apmClip = FALSE; } A(WaitForFifo)(pApm, 4); SETSOURCEXY(srcx, srcy); SETDESTXY(x, y); #ifdef FASTER SETDEC(c); SETWIDTHHEIGHT(w, h); #else SETWIDTHHEIGHT(w, h); SETDEC(c); #endif UPDATEDEST(x + w + 1, h); } static void A(SubsequentSolidBresenhamLine)(ScrnInfoPtr pScrn, int x1, int y1, int e1, int e2, int err, int length, int octant) { APMDECL(pScrn); #ifdef FASTER u32 c = DEC_QUICKSTART_ONDIMX | DEC_OP_VECT_ENDP | DEC_DEST_UPD_LASTPIX | pApm->CurrentLayout.Setup_DEC; #else u32 c = DEC_START | DEC_OP_VECT_ENDP | DEC_DEST_UPD_LASTPIX | pApm->CurrentLayout.Setup_DEC; #endif int tmp; DPRINTNAME(SubsequentSolidBresenhamLine); A(WaitForFifo)(pApm, 5); SETDESTXY(x1,y1); SETDDA_ERRORTERM(err); SETDDA_ADSTEP(e1, e2); if (octant & YMAJOR) { c |= DEC_MAJORAXIS_Y; tmp = e1; e1 = e2; e2 = tmp; } else c |= DEC_MAJORAXIS_X; if (octant & XDECREASING) { c |= DEC_DIR_X_NEG; e1 = -e1; } else c |= DEC_DIR_X_POS; if (octant & YDECREASING) { c |= DEC_DIR_Y_NEG; e2 = -e2; } else c |= DEC_DIR_Y_POS; #ifdef FASTER SETDEC(c); SETWIDTH(length); #else SETWIDTH(length); SETDEC(c); #endif if (octant & YMAJOR) UPDATEDEST(x1 + e1 / 2, y1 + e2 / 2); else UPDATEDEST(x1 + e2 / 2, y1 + e1 / 2); if (pApm->apmClip) { pApm->apmClip = FALSE; A(WaitForFifo)(pApm, 1); SETCLIP_CTRL(0); } } static void A(SubsequentSolidBresenhamLine6422)(ScrnInfoPtr pScrn, int x1, int y1, int e1, int e2, int err, int length, int octant) { APMDECL(pScrn); #ifdef FASTER u32 c = DEC_QUICKSTART_ONDIMX | DEC_OP_VECT_ENDP | DEC_DEST_UPD_LASTPIX | pApm->CurrentLayout.Setup_DEC; #else u32 c = DEC_START | DEC_OP_VECT_ENDP | DEC_DEST_UPD_LASTPIX | pApm->CurrentLayout.Setup_DEC; #endif int tmp; DPRINTNAME(SubsequentSolidBresenhamLine6422); A(WaitForFifo)(pApm, 1); SETDESTXY(x1,y1); A(WaitForFifo)(pApm, 4); SETDDA_ERRORTERM(err); SETDDA_ADSTEP(e1, e2); if (octant & YMAJOR) { c |= DEC_MAJORAXIS_Y; tmp = e1; e1 = e2; e2 = tmp; } else c |= DEC_MAJORAXIS_X; if (octant & XDECREASING) { c |= DEC_DIR_X_NEG; e1 = -e1; } else c |= DEC_DIR_X_POS; if (octant & YDECREASING) { c |= DEC_DIR_Y_NEG; e2 = -e2; } else c |= DEC_DIR_Y_POS; #ifdef FASTER SETDEC(c); SETWIDTH(length); #else SETWIDTH(length); SETDEC(c); #endif if (octant & YMAJOR) UPDATEDEST(x1 + e1 / 2, y1 + e2 / 2); else UPDATEDEST(x1 + e2 / 2, y1 + e1 / 2); if (pApm->apmClip) { pApm->apmClip = FALSE; A(WaitForFifo)(pApm, 1); SETCLIP_CTRL(0); } } static void A(SetClippingRectangle)(ScrnInfoPtr pScrn, int x1, int y1, int x2, int y2) { APMDECL(pScrn); DPRINTNAME(SetClippingRectangle); A(WaitForFifo)(pApm, 3); SETCLIP_LEFTTOP(x1,y1); SETCLIP_RIGHTBOT(x2,y2); SETCLIP_CTRL(0x01); pApm->apmClip = TRUE; } static void A(SyncBlt)(ApmPtr pApm) { int again = (pApm->Chipset == AP6422); do { while (!(STATUS() & STATUS_HOSTBLTBUSY)) ; } while (again--); /* See remark in Sync6422 */ } static void A(WritePixmap)(ScrnInfoPtr pScrn, int x, int y, int w, int h, unsigned char *src, int srcwidth, int rop, unsigned int planemask, int trans, int bpp, int depth) { APMDECL(pScrn); int dwords, skipleft, Bpp = bpp >> 3; Bool beCareful = FALSE; unsigned char *dst = ((unsigned char *)pApm->FbBase) + x * Bpp + y * pApm->CurrentLayout.bytesPerScanline; int PlusOne = 0, mask, count; DPRINTNAME(WritePixmap); if (rop == GXnoop) return; /* * The function seems to crash more than it feels good. I hope that a * good sync will help. This sync is anyway needed for direct write. */ (*pApm->AccelInfoRec->Sync)(pScrn); /* * First the fast case : source and dest have same alignment. Doc says * it's faster to do it here, which may be true since one has to read * the chip when CPU to screen-ing. */ if ((skipleft = (long)src & 3L) == ((long)dst & 3L) && rop == GXcopy) { int skipright; if (skipleft) skipleft = 4 - skipleft; dwords = (skipright = w * Bpp - skipleft) >> 2; skipright %= 4; if (!skipleft && !skipright) while (h-- > 0) { CARD32 *src2 = (CARD32 *)src; CARD32 *dst2 = (CARD32 *)dst; for (count = dwords; count-- > 0; ) *dst2++ = *src2++; src += srcwidth; dst += pApm->CurrentLayout.bytesPerScanline; } else if (!skipleft) while (h-- > 0) { CARD32 *src2 = (CARD32 *)src; CARD32 *dst2 = (CARD32 *)dst; for (count = dwords; count-- > 0; ) *dst2++ = *src2++; for (count = skipright; count-- > 0; ) ((char *)dst2)[count] = ((char *)src2)[count]; src += srcwidth; dst += pApm->CurrentLayout.bytesPerScanline; } else if (!skipright) while (h-- > 0) { CARD32 *src2 = (CARD32 *)(src + skipleft); CARD32 *dst2 = (CARD32 *)(dst + skipleft); for (count = skipleft; count-- > 0; ) dst[count] = src[count]; for (count = dwords; count-- > 0; ) *dst2++ = *src2++; src += srcwidth; dst += pApm->CurrentLayout.bytesPerScanline; } else while (h-- > 0) { CARD32 *src2 = (CARD32 *)(src + skipleft); CARD32 *dst2 = (CARD32 *)(dst + skipleft); for (count = skipleft; count-- > 0; ) dst[count] = src[count]; for (count = dwords; count-- > 0; ) *dst2++ = *src2++; for (count = skipright; count-- > 0; ) ((char *)dst2)[count] = ((char *)src2)[count]; src += srcwidth; dst += pApm->CurrentLayout.bytesPerScanline; } return; } if (skipleft) { if (Bpp == 3) skipleft = 4 - skipleft; else skipleft /= Bpp; if (x < skipleft) { skipleft = 0; beCareful = TRUE; goto BAD_ALIGNMENT; } x -= skipleft; w += skipleft; if (Bpp == 3) src -= 3 * skipleft; else /* is this Alpha friendly ? */ src = (unsigned char*)((long)src & ~0x03L); } BAD_ALIGNMENT: dwords = ((w * Bpp) + 3) >> 2; mask = (pApm->CurrentLayout.bitsPerPixel / 8) - 1; if (dwords & mask) { /* * Experimental... * It seems the AT3D needs a padding of scanline to a multiple of * 4 pixels, not only bytes. */ PlusOne = mask - (dwords & mask) + 1; } A(SetupForImageWrite)(pScrn, rop, planemask, trans, bpp, depth); A(SubsequentImageWriteRect)(pScrn, x, y, w, h, skipleft); if (beCareful) { /* in cases with bad alignment we have to be careful not to read beyond the end of the source */ if (((x * Bpp) + (dwords << 2)) > srcwidth) h--; else beCareful = FALSE; } srcwidth -= (dwords << 2); while (h--) { for (count = dwords; count-- > 0; ) { A(SyncBlt)(pApm); *(CARD32*)pApm->BltMap = *(CARD32*)src; src += 4; } src += srcwidth; for (count = PlusOne; count-- > 0; ) { int status; while (!((status = STATUS()) & STATUS_HOSTBLTBUSY)) if (!(status & STATUS_ENGINEBUSY)) break; if (pApm->Chipset == AP6422) /* See remark in Sync6422 */ while (!((status = STATUS()) & STATUS_HOSTBLTBUSY)) if (!(status & STATUS_ENGINEBUSY)) break; if (status & STATUS_ENGINEBUSY) *(CARD32*)pApm->BltMap = 0x00000000; } } if (beCareful) { int shift = ((long)src & 0x03L) << 3; if (--dwords) { for (count = dwords >> 2; count-- > 0; ) { A(SyncBlt)(pApm); *(CARD32*)pApm->BltMap = *(CARD32*)src; src += 4; } } A(SyncBlt)(pApm); *((CARD32*)pApm->BltMap) = *((CARD32*)src) >> shift; } pApm->apmClip = FALSE; A(WaitForFifo)(pApm, 1); SETCLIP_CTRL(0); } static void A(FillImageWriteRects)(ScrnInfoPtr pScrn, int rop, unsigned int planemask, int nBox, BoxPtr pBox, int xorg, int yorg, PixmapPtr pPix) { XAAInfoRecPtr infoRec = GET_XAAINFORECPTR_FROM_SCRNINFOPTR(pScrn); int x, y, phaseY, phaseX, height, width, blit_w; int pHeight = pPix->drawable.height; int pWidth = pPix->drawable.width; int depth = pPix->drawable.depth; int bpp = pPix->drawable.bitsPerPixel; unsigned char *pSrc; int srcwidth = pPix->devKind; while(nBox--) { x = pBox->x1; y = pBox->y1; phaseY = (pBox->y1 - yorg) % pHeight; if(phaseY < 0) phaseY += pHeight; phaseX = (x - xorg) % pWidth; pSrc = (unsigned char *)pPix->devPrivate.ptr + phaseX * pPix->drawable.bitsPerPixel / 8; if(phaseX < 0) phaseX += pWidth; height = pBox->y2 - pBox->y1; width = pBox->x2 - x; while(1) { int ch = height, cp = phaseY, cy = y; blit_w = pWidth - phaseX; if(blit_w > width) blit_w = width; while (ch > 0) { int h = MIN(pHeight - cp, ch); A(WritePixmap)(pScrn, x, cy, blit_w, h, pSrc + cp * srcwidth, srcwidth, rop, planemask, FALSE, bpp, depth); cy += h; ch -= h; cp = 0; } width -= blit_w; if(!width) break; x += blit_w; phaseX = (phaseX + blit_w) % pWidth; } pBox++; } SET_SYNC_FLAG(infoRec); } static void A(SetupForColor8x8PatternFill)(ScrnInfoPtr pScrn,int patx,int paty, int rop, unsigned int planemask, int transparency_color) { APMDECL(pScrn); DPRINTNAME(SetupForColor8x8PatternFillRect); if (transparency_color != -1) { #ifndef FASTER pApm->apmTransparency = TRUE; A(WaitForFifo)(pApm, 2 + pApm->apmClip); #else A(WaitForFifo)(pApm, 3 + pApm->apmClip); SETDEC(pApm->CurrentLayout.Setup_DEC | DEC_OP_BLT | DEC_DEST_XY | DEC_PATTERN_88_8bCOLOR | DEC_SOURCE_TRANSPARENCY | DEC_QUICKSTART_ONDIMX); #endif SETBACKGROUNDCOLOR(transparency_color); } else { #ifndef FASTER pApm->apmTransparency = FALSE; A(WaitForFifo)(pApm, 1 + pApm->apmClip); #else A(WaitForFifo)(pApm, 2 + pApm->apmClip); SETDEC(pApm->CurrentLayout.Setup_DEC | DEC_OP_BLT | DEC_DEST_XY | DEC_PATTERN_88_8bCOLOR | DEC_QUICKSTART_ONDIMX); #endif } if (pApm->apmClip) { SETCLIP_CTRL(0); pApm->apmClip = FALSE; } SETROP(apmROP[rop]); } static void A(SubsequentColor8x8PatternFillRect)(ScrnInfoPtr pScrn, int patx, int paty, int x, int y, int w, int h) { APMDECL(pScrn); DPRINTNAME(SubsequentColor8x8PatternFillRect); #ifndef FASTER A(WaitForFifo)(pApm, 5); #else A(WaitForFifo)(pApm, 4); #endif SETSOURCEXY(patx, paty); SETDESTXY(x, y); SETWIDTHHEIGHT(w, h); UPDATEDEST(x + w + 1, y); #ifndef FASTER SETDEC(pApm->CurrentLayout.Setup_DEC | DEC_OP_BLT | DEC_DEST_XY | (pApm->apmTransparency * DEC_SOURCE_TRANSPARENCY) | DEC_PATTERN_88_8bCOLOR | DEC_START); #endif } #endif static void A(Sync)(ScrnInfoPtr pScrn) { APMDECL(pScrn); volatile u32 i, stat; for(i = 0; i < MAXLOOP; i++) { stat = STATUS(); if ((!(stat & (STATUS_HOSTBLTBUSY | STATUS_ENGINEBUSY))) && ((stat & STATUS_FIFO) >= 8)) break; } if (i == MAXLOOP) { unsigned int status = STATUS(); WRXB(0x1FF, 0); if (!xf86ServerIsExiting()) FatalError("Hung in ApmSync" APM_SUFF_24 "(%d) (Status = 0x%08X)\n", pScrn->pScreen->myNum, status); } if (pApm->apmClip) { SETCLIP_CTRL(0); pApm->apmClip = FALSE; } } #if PSZ != 24 static void A(Sync6422)(ScrnInfoPtr pScrn) { APMDECL(pScrn); volatile u32 i, j, stat; for (j = 0; j < 2; j++) { /* * From Henrik Harmsen : * * This is a kludge. We can't trust the status register. Don't * know why... We shouldn't be forced to read the status reg and get * a correct value more than once... */ for(i = 0; i < MAXLOOP; i++) { stat = STATUS(); if ((!(stat & (STATUS_HOSTBLTBUSY | STATUS_ENGINEBUSY))) && ((stat & STATUS_FIFO) >= 4)) break; } } if (i == MAXLOOP) { unsigned int status = STATUS(); WRXB(0x1FF, 0); if (!xf86ServerIsExiting()) FatalError("Hung in ApmSync6422() (Status = 0x%08X)\n", status); } if (pApm->apmClip) { SETCLIP_CTRL(0); pApm->apmClip = FALSE; } } #endif #include "apm_video.c" #undef RDXB #undef RDXW #undef RDXL #undef WRXB #undef WRXW #undef WRXL #undef ApmWriteSeq #define RDXB RDXB_M #define RDXW RDXW_M #define RDXL RDXL_M #define WRXB WRXB_M #define WRXW WRXW_M #define WRXL WRXL_M #define ApmWriteSeq(idx, val) do { APMVGAB(0x3C4) = (idx); APMVGAB(0x3C5) = (val); break; } while(1) #undef DPRINTNAME #undef A #undef DEPTH #undef PSZ #undef APM_SUFF_24
{ "language": "C" }
/* charsets.h -- character set information and mappings (c) 1998-2006 (W3C) MIT, ERCIM, Keio University See tidy.h for the copyright notice. */ uint TY_(GetEncodingIdFromName)(ctmbstr name); uint TY_(GetEncodingIdFromCodePage)(uint cp); uint TY_(GetEncodingCodePageFromName)(ctmbstr name); uint TY_(GetEncodingCodePageFromId)(uint id); ctmbstr TY_(GetEncodingNameFromId)(uint id); ctmbstr TY_(GetEncodingNameFromCodePage)(uint cp);
{ "language": "C" }
/* =========================================================================== Copyright (C) 1999-2005 Id Software, Inc. This file is part of Quake III Arena source code. Quake III Arena source code is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Quake III Arena source code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Quake III Arena source code; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ /***************************************************************************** * name: l_struct.h * * desc: structure reading/writing * * $Archive: /source/code/botlib/l_struct.h $ * *****************************************************************************/ #define MAX_STRINGFIELD 80 //field types #define FT_CHAR 1 // char #define FT_INT 2 // int #define FT_FLOAT 3 // float #define FT_STRING 4 // char [MAX_STRINGFIELD] #define FT_STRUCT 6 // struct (sub structure) //type only mask #define FT_TYPE 0x00FF // only type, clear subtype //sub types #define FT_ARRAY 0x0100 // array of type #define FT_BOUNDED 0x0200 // bounded value #define FT_UNSIGNED 0x0400 //structure field definition typedef struct fielddef_s { char *name; //name of the field int offset; //offset in the structure int type; //type of the field //type specific fields int maxarray; //maximum array size float floatmin, floatmax; //float min and max struct structdef_s *substruct; //sub structure } fielddef_t; //structure definition typedef struct structdef_s { int size; fielddef_t *fields; } structdef_t; //read a structure from a script int ReadStructure(source_t *source, structdef_t *def, char *structure); //write a structure to a file int WriteStructure(FILE *fp, structdef_t *def, char *structure); //writes indents int WriteIndent(FILE *fp, int indent); //writes a float without traling zeros int WriteFloat(FILE *fp, float value);
{ "language": "C" }
/* * Copyright (C) 2000 Takashi Iwai <tiwai@suse.de> * * Routines for control of EMU WaveTable chip * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/wait.h> #include <linux/slab.h> #include <linux/string.h> #include <sound/core.h> #include <sound/emux_synth.h> #include <linux/init.h> #include <linux/module.h> #include "emux_voice.h" MODULE_AUTHOR("Takashi Iwai"); MODULE_DESCRIPTION("Routines for control of EMU WaveTable chip"); MODULE_LICENSE("GPL"); /* * create a new hardware dependent device for Emu8000/Emu10k1 */ int snd_emux_new(struct snd_emux **remu) { struct snd_emux *emu; *remu = NULL; emu = kzalloc(sizeof(*emu), GFP_KERNEL); if (emu == NULL) return -ENOMEM; spin_lock_init(&emu->voice_lock); mutex_init(&emu->register_mutex); emu->client = -1; #ifdef CONFIG_SND_SEQUENCER_OSS emu->oss_synth = NULL; #endif emu->max_voices = 0; emu->use_time = 0; init_timer(&emu->tlist); emu->tlist.function = snd_emux_timer_callback; emu->tlist.data = (unsigned long)emu; emu->timer_active = 0; *remu = emu; return 0; } EXPORT_SYMBOL(snd_emux_new); /* */ static int sf_sample_new(void *private_data, struct snd_sf_sample *sp, struct snd_util_memhdr *hdr, const void __user *buf, long count) { struct snd_emux *emu = private_data; return emu->ops.sample_new(emu, sp, hdr, buf, count); } static int sf_sample_free(void *private_data, struct snd_sf_sample *sp, struct snd_util_memhdr *hdr) { struct snd_emux *emu = private_data; return emu->ops.sample_free(emu, sp, hdr); } static void sf_sample_reset(void *private_data) { struct snd_emux *emu = private_data; emu->ops.sample_reset(emu); } int snd_emux_register(struct snd_emux *emu, struct snd_card *card, int index, char *name) { int err; struct snd_sf_callback sf_cb; if (snd_BUG_ON(!emu->hw || emu->max_voices <= 0)) return -EINVAL; if (snd_BUG_ON(!card || !name)) return -EINVAL; emu->card = card; emu->name = kstrdup(name, GFP_KERNEL); emu->voices = kcalloc(emu->max_voices, sizeof(struct snd_emux_voice), GFP_KERNEL); if (emu->voices == NULL) return -ENOMEM; /* create soundfont list */ memset(&sf_cb, 0, sizeof(sf_cb)); sf_cb.private_data = emu; if (emu->ops.sample_new) sf_cb.sample_new = sf_sample_new; if (emu->ops.sample_free) sf_cb.sample_free = sf_sample_free; if (emu->ops.sample_reset) sf_cb.sample_reset = sf_sample_reset; emu->sflist = snd_sf_new(&sf_cb, emu->memhdr); if (emu->sflist == NULL) return -ENOMEM; if ((err = snd_emux_init_hwdep(emu)) < 0) return err; snd_emux_init_voices(emu); snd_emux_init_seq(emu, card, index); #ifdef CONFIG_SND_SEQUENCER_OSS snd_emux_init_seq_oss(emu); #endif snd_emux_init_virmidi(emu, card); #ifdef CONFIG_PROC_FS snd_emux_proc_init(emu, card, index); #endif return 0; } EXPORT_SYMBOL(snd_emux_register); /* */ int snd_emux_free(struct snd_emux *emu) { unsigned long flags; if (! emu) return -EINVAL; spin_lock_irqsave(&emu->voice_lock, flags); if (emu->timer_active) del_timer(&emu->tlist); spin_unlock_irqrestore(&emu->voice_lock, flags); #ifdef CONFIG_PROC_FS snd_emux_proc_free(emu); #endif snd_emux_delete_virmidi(emu); #ifdef CONFIG_SND_SEQUENCER_OSS snd_emux_detach_seq_oss(emu); #endif snd_emux_detach_seq(emu); snd_emux_delete_hwdep(emu); if (emu->sflist) snd_sf_free(emu->sflist); kfree(emu->voices); kfree(emu->name); kfree(emu); return 0; } EXPORT_SYMBOL(snd_emux_free); /* * INIT part */ static int __init alsa_emux_init(void) { return 0; } static void __exit alsa_emux_exit(void) { } module_init(alsa_emux_init) module_exit(alsa_emux_exit)
{ "language": "C" }
/* * QEMU HAXM support * * Copyright IBM, Corp. 2008 * * Authors: * Anthony Liguori <aliguori@us.ibm.com> * * Copyright (c) 2011 Intel Corporation * Written by: * Jiang Yunhong<yunhong.jiang@intel.com> * Xin Xiaohui<xiaohui.xin@intel.com> * Zhang Xiantao<xiantao.zhang@intel.com> * * This work is licensed under the terms of the GNU GPL, version 2 or later. * See the COPYING file in the top-level directory. * */ #ifndef TARGET_I386_HAX_WINDOWS_H #define TARGET_I386_HAX_WINDOWS_H #include <windows.h> #include <memory.h> #include <malloc.h> #include <winioctl.h> #include <string.h> #include <stdio.h> #include <windef.h> #define HAX_INVALID_FD INVALID_HANDLE_VALUE static inline void hax_mod_close(struct hax_state *hax) { CloseHandle(hax->fd); } static inline void hax_close_fd(hax_fd fd) { CloseHandle(fd); } static inline int hax_invalid_fd(hax_fd fd) { return (fd == INVALID_HANDLE_VALUE); } #define HAX_DEVICE_TYPE 0x4000 #define HAX_IOCTL_VERSION CTL_CODE(HAX_DEVICE_TYPE, 0x900, \ METHOD_BUFFERED, FILE_ANY_ACCESS) #define HAX_IOCTL_CREATE_VM CTL_CODE(HAX_DEVICE_TYPE, 0x901, \ METHOD_BUFFERED, FILE_ANY_ACCESS) #define HAX_IOCTL_CAPABILITY CTL_CODE(HAX_DEVICE_TYPE, 0x910, \ METHOD_BUFFERED, FILE_ANY_ACCESS) #define HAX_VM_IOCTL_VCPU_CREATE CTL_CODE(HAX_DEVICE_TYPE, 0x902, \ METHOD_BUFFERED, FILE_ANY_ACCESS) #define HAX_VM_IOCTL_ALLOC_RAM CTL_CODE(HAX_DEVICE_TYPE, 0x903, \ METHOD_BUFFERED, FILE_ANY_ACCESS) #define HAX_VM_IOCTL_SET_RAM CTL_CODE(HAX_DEVICE_TYPE, 0x904, \ METHOD_BUFFERED, FILE_ANY_ACCESS) #define HAX_VM_IOCTL_VCPU_DESTROY CTL_CODE(HAX_DEVICE_TYPE, 0x905, \ METHOD_BUFFERED, FILE_ANY_ACCESS) #define HAX_VCPU_IOCTL_RUN CTL_CODE(HAX_DEVICE_TYPE, 0x906, \ METHOD_BUFFERED, FILE_ANY_ACCESS) #define HAX_VCPU_IOCTL_SET_MSRS CTL_CODE(HAX_DEVICE_TYPE, 0x907, \ METHOD_BUFFERED, FILE_ANY_ACCESS) #define HAX_VCPU_IOCTL_GET_MSRS CTL_CODE(HAX_DEVICE_TYPE, 0x908, \ METHOD_BUFFERED, FILE_ANY_ACCESS) #define HAX_VCPU_IOCTL_SET_FPU CTL_CODE(HAX_DEVICE_TYPE, 0x909, \ METHOD_BUFFERED, FILE_ANY_ACCESS) #define HAX_VCPU_IOCTL_GET_FPU CTL_CODE(HAX_DEVICE_TYPE, 0x90a, \ METHOD_BUFFERED, FILE_ANY_ACCESS) #define HAX_VCPU_IOCTL_SETUP_TUNNEL CTL_CODE(HAX_DEVICE_TYPE, 0x90b, \ METHOD_BUFFERED, FILE_ANY_ACCESS) #define HAX_VCPU_IOCTL_INTERRUPT CTL_CODE(HAX_DEVICE_TYPE, 0x90c, \ METHOD_BUFFERED, FILE_ANY_ACCESS) #define HAX_VCPU_SET_REGS CTL_CODE(HAX_DEVICE_TYPE, 0x90d, \ METHOD_BUFFERED, FILE_ANY_ACCESS) #define HAX_VCPU_GET_REGS CTL_CODE(HAX_DEVICE_TYPE, 0x90e, \ METHOD_BUFFERED, FILE_ANY_ACCESS) #define HAX_VM_IOCTL_NOTIFY_QEMU_VERSION CTL_CODE(HAX_DEVICE_TYPE, 0x910, \ METHOD_BUFFERED, \ FILE_ANY_ACCESS) #endif /* TARGET_I386_HAX_WINDOWS_H */
{ "language": "C" }
/// Make sure calls to d_find_alias() have a corresponding call to dput(). // // Keywords: d_find_alias, dput // // Confidence: Moderate // URL: http://coccinelle.lip6.fr/ // Options: -include_headers virtual context virtual org virtual patch virtual report @r exists@ local idexpression struct dentry *dent; expression E, E1; statement S1, S2; position p1, p2; @@ ( if (!(dent@p1 = d_find_alias(...))) S1 | dent@p1 = d_find_alias(...) ) <...when != dput(dent) when != if (...) { <+... dput(dent) ...+> } when != true !dent || ... when != dent = E when != E = dent if (!dent || ...) S2 ...> ( return <+...dent...+>; | return @p2 ...; | dent@p2 = E1; | E1 = dent; ) @depends on context@ local idexpression struct dentry *r.dent; position r.p1,r.p2; @@ * dent@p1 = ... ... ( * return@p2 ...; | * dent@p2 ) @script:python depends on org@ p1 << r.p1; p2 << r.p2; @@ cocci.print_main("Missing call to dput()",p1) cocci.print_secs("",p2) @depends on patch@ local idexpression struct dentry *r.dent; position r.p2; @@ ( + dput(dent); return @p2 ...; | + dput(dent); dent@p2 = ...; ) @script:python depends on report@ p1 << r.p1; p2 << r.p2; @@ msg = "Missing call to dput() at line %s." coccilib.report.print_report(p1[0], msg % (p2[0].line))
{ "language": "C" }